From e07efad9d3d56d0a6bb5f1074dff26221ee885f2 Mon Sep 17 00:00:00 2001 From: Duane Nykamp Date: Tue, 7 Mar 2023 12:23:43 -0600 Subject: [PATCH] tweaks to pegboard (#1979) --- src/Viewer/core.js | 4 ++-- src/Viewer/renderers/graph.jsx | 10 +++++----- src/Viewer/renderers/pegboard.jsx | 32 +++++++++++++++++-------------- 3 files changed, 25 insertions(+), 21 deletions(-) diff --git a/src/Viewer/core.js b/src/Viewer/core.js index 400493fe9f..cc28ee9467 100644 --- a/src/Viewer/core.js +++ b/src/Viewer/core.js @@ -15,7 +15,7 @@ var Core=function(){"use strict";class ParameterStack{constructor(e){this.stack= //!!This function should only be called if bottom has coefficient 1 and divides the top (e.g., bottom was computed using mono_gcd)!! if(!Array.isArray(t)||"monomial"!==t[0])return 1===t?e:Array.isArray(e)&&"monomial"===e[0]?[e[0],evaluate_numbers(["/",e[1],t]),e[2]]:evaluate_numbers(["/",e,t]);if(!Array.isArray(e)||"monomial"!==e[0])return;let n=e[2],r=t[2],a=[],i=n.length,s=r.length,o=0,l=0;for(;o=0;){var r=[];r.push([e[2][t][1],n]),n=["polynomial",e[2][t][0],r],t-=1}return n}function max_div_init(e,t){if(0===e)return 0;let n=e,r=[];for(;Array.isArray(n)&&"polynomial"===n[0];){let e=n[1],t=n[2],a=t[t.length-1][0];n=t[t.length-1][1],r.push([e,a])}let a=["monomial",n,r],i=t.length;for(var s=0;s0?choice_lowest_degree(i):0}function update_hij_table(e,t,n){let r=t.length;t.push(n);let a=0,i=1,s=[];for(;i0?choice_lowest_degree(s):0}function choice_lowest_degree(e){let t=[],n=e.length;for(a=0;a15?n:(t=Math.round(t),round_numbers_to_precision_sub(n,t))}const round_numbers_to_precision_sub=function(e,t=14){if("number"==typeof e&&Number.isFinite(e)&&0!==e){const n=math$1.floor(math$1.log10(math$1.abs(e))),r=t-n-1;return r<0?parseFloat(toFixed(e,r)+"0".repeat(math$1.abs(r))):parseFloat(toFixed(e,r))}return Array.isArray(e)?[e[0],...e.slice(1).map((e=>round_numbers_to_precision_sub(e,t)))]:e};function round_numbers_to_decimals(e,t=14){var n=get_tree(e);if(!Number.isFinite(t))throw Error("For round_numbers_to_decimals, ndecimals must be a number");return t=Math.round(t),t=Math.max(-330,Math.min(330,t)),round_numbers_to_decimals_sub(n,t)}const round_numbers_to_decimals_sub=function(e,t=0){return"number"==typeof e?t<0?parseFloat(toFixed(e,t)+"0".repeat(math$1.abs(t))):parseFloat(toFixed(e,t)):Array.isArray(e)?[e[0],...e.slice(1).map((e=>round_numbers_to_decimals_sub(e,t)))]:e};var round=Object.freeze({__proto__:null,round_numbers_to_precision:round_numbers_to_precision,round_numbers_to_decimals:round_numbers_to_decimals});const match=function(e,t,n){let r=get_tree(e),a=get_tree(t);return match$2(r,a,n)};var match$1=Object.freeze({__proto__:null,match:match});const expression_to_tree$1=[simplify$1,differentiation,normalization,arithmetic,transformation,solve,sets,matrix$1,rational,round],expression_to_other=[variables$1,printing,equality,integration,evaluation,analytic,sign_error,match$1];function abs(e){return["apply","abs",get_tree(e)]}function exp(e){return["apply","exp",get_tree(e)]}function log(e){return["apply","log",get_tree(e)]}function log10(e){return["apply","log10",get_tree(e)]}function sign(e){return["apply","sign",get_tree(e)]}function sqrt(e){return["apply","sqrt",get_tree(e)]}function conj(e){return["apply","conj",get_tree(e)]}function im(e){return["apply","im",get_tree(e)]}function re(e){return["apply","re",get_tree(e)]}function factorial(e){return["apply","factorial",get_tree(e)]}function gamma(e){return["apply","gamma",get_tree(e)]}function erf(e){return["apply","erf",get_tree(e)]}function acos(e){return["apply","acos",get_tree(e)]}function acosh(e){return["apply","acosh",get_tree(e)]}function acot(e){return["apply","acot",get_tree(e)]}function acoth(e){return["apply","acoth",get_tree(e)]}function acsc(e){return["apply","acsc",get_tree(e)]}function acsch(e){return["apply","acsch",get_tree(e)]}function asec(e){return["apply","asec",get_tree(e)]}function asech(e){return["apply","asech",get_tree(e)]}function asin(e){return["apply","asin",get_tree(e)]}function asinh(e){return["apply","asinh",get_tree(e)]}function atan(e){return["apply","atan",get_tree(e)]}function atanh(e){return["apply","atanh",get_tree(e)]}function cos(e){return["apply","cos",get_tree(e)]}function cosh(e){return["apply","cosh",get_tree(e)]}function cot(e){return["apply","cot",get_tree(e)]}function coth(e){return["apply","coth",get_tree(e)]}function csc(e){return["apply","csc",get_tree(e)]}function csch(e){return["apply","csch",get_tree(e)]}function sec(e){return["apply","sec",get_tree(e)]}function sech(e){return["apply","sech",get_tree(e)]}function sin(e){return["apply","sin",get_tree(e)]}function sinh(e){return["apply","sinh",get_tree(e)]}function tan(e){return["apply","tan",get_tree(e)]}function tanh(e){return["apply","tanh",get_tree(e)]}function atan2(e,t){return["apply","atan2",["tuple",get_tree(e),get_tree(t)]]}var standard=Object.freeze({__proto__:null,abs:abs,exp:exp,log:log,log10:log10,sign:sign,sqrt:sqrt,conj:conj,im:im,re:re,factorial:factorial,gamma:gamma,erf:erf,acos:acos,acosh:acosh,acot:acot,acoth:acoth,acsc:acsc,acsch:acsch,asec:asec,asech:asech,asin:asin,asinh:asinh,atan:atan,atanh:atanh,cos:cos,cosh:cosh,cot:cot,coth:coth,csc:csc,csch:csch,sec:sec,sech:sech,sin:sin,sinh:sinh,tan:tan,tanh:tanh,atan2:atan2});const expression_to_tree=[standard],whitespace_rule="\\s|\\\\,|\\\\!|\\\\ |\\\\>|\\\\;|\\\\:|\\\\quad\\b|\\\\qquad\\b",sci_notat_exp_regex="(E[+\\-]?[0-9]+\\s*($|(?=\\,|&|\\||\\\\\\||\\)|\\}|\\\\}|\\]|\\\\\\\\|\\\\end)))?",number_rules_sci=[["[0-9]+(\\.[0-9]*)?"+sci_notat_exp_regex,"NUMBER"],["\\.[0-9]+"+sci_notat_exp_regex,"NUMBER"]],number_rules_non_sci=[["[0-9]+(\\.[0-9]*)?","NUMBER"],["\\.[0-9]+","NUMBER"]],base_latex_rules=[["\\*","*"],["\\/","/"],["-","-"],["\\+","+"],["\\^","^"],["\\(","("],["\\\\left\\s*\\(","("],["\\\\bigl\\s*\\(","("],["\\\\Bigl\\s*\\(","("],["\\\\biggl\\s*\\(","("],["\\\\Biggl\\s*\\(","("],["\\)",")"],["\\\\right\\s*\\)",")"],["\\\\bigr\\s*\\)",")"],["\\\\Bigr\\s*\\)",")"],["\\\\biggr\\s*\\)",")"],["\\\\Biggr\\s*\\)",")"],["\\[","["],["\\\\left\\s*\\[","["],["\\\\bigl\\s*\\[","["],["\\\\Bigl\\s*\\[","["],["\\\\biggl\\s*\\[","["],["\\\\Biggl\\s*\\[","["],["\\]","]"],["\\\\right\\s*\\]","]"],["\\\\bigr\\s*\\]","]"],["\\\\Bigr\\s*\\]","]"],["\\\\biggr\\s*\\]","]"],["\\\\Biggr\\s*\\]","]"],["\\|","|"],["\\\\left\\s*\\|","|L"],["\\\\bigl\\s*\\|","|L"],["\\\\Bigl\\s*\\|","|L"],["\\\\biggl\\s*\\|","|L"],["\\\\Biggl\\s*\\|","|L"],["\\\\right\\s*\\|","|"],["\\\\bigr\\s*\\|","|"],["\\\\Bigr\\s*\\|","|"],["\\\\biggr\\s*\\|","|"],["\\\\Biggr\\s*\\|","|"],["\\\\big\\s*\\|","|"],["\\\\Big\\s*\\|","|"],["\\\\bigg\\s*\\|","|"],["\\\\Bigg\\s*\\|","|"],["{","{"],["}","}"],["\\\\{","LBRACE"],["\\\\left\\s*\\\\{","LBRACE"],["\\\\bigl\\s*\\\\{","LBRACE"],["\\\\Bigl\\s*\\\\{","LBRACE"],["\\\\biggl\\s*\\\\{","LBRACE"],["\\\\Biggl\\s*\\\\{","LBRACE"],["\\\\}","RBRACE"],["\\\\right\\s*\\\\}","RBRACE"],["\\\\bigr\\s*\\\\}","RBRACE"],["\\\\Bigr\\s*\\\\}","RBRACE"],["\\\\biggr\\s*\\\\}","RBRACE"],["\\\\Biggr\\s*\\\\}","RBRACE"],["\\\\lfloor(?![a-zA-Z])","LFLOOR"],["\\\\left\\s*\\\\lfloor(?![a-zA-Z])","LFLOOR"],["\\\\bigl\\s*\\\\lfloor(?![a-zA-Z])","LFLOOR"],["\\\\Bigl\\s*\\\\lfloor(?![a-zA-Z])","LFLOOR"],["\\\\biggl\\s*\\\\lfloor(?![a-zA-Z])","LFLOOR"],["\\\\Biggl\\s*\\\\lfloor(?![a-zA-Z])","LFLOOR"],["\\\\rfloor(?![a-zA-Z])","RFLOOR"],["\\\\right\\s*\\\\rfloor(?![a-zA-Z])","RFLOOR"],["\\\\bigr\\s*\\\\rfloor(?![a-zA-Z])","RFLOOR"],["\\\\Bigr\\s*\\\\rfloor(?![a-zA-Z])","RFLOOR"],["\\\\biggr\\s*\\\\rfloor(?![a-zA-Z])","RFLOOR"],["\\\\Biggr\\s*\\\\rfloor(?![a-zA-Z])","RFLOOR"],["\\\\lceil(?![a-zA-Z])","LCEIL"],["\\\\left\\s*\\\\lceil(?![a-zA-Z])","LCEIL"],["\\\\bigl\\s*\\\\lceil(?![a-zA-Z])","LCEIL"],["\\\\Bigl\\s*\\\\lceil(?![a-zA-Z])","LCEIL"],["\\\\biggl\\s*\\\\lceil(?![a-zA-Z])","LCEIL"],["\\\\Biggl\\s*\\\\lceil(?![a-zA-Z])","LCEIL"],["\\\\rceil(?![a-zA-Z])","RCEIL"],["\\\\right\\s*\\\\rceil(?![a-zA-Z])","RCEIL"],["\\\\bigr\\s*\\\\rceil(?![a-zA-Z])","RCEIL"],["\\\\Bigr\\s*\\\\rceil(?![a-zA-Z])","RCEIL"],["\\\\biggr\\s*\\\\rceil(?![a-zA-Z])","RCEIL"],["\\\\Biggr\\s*\\\\rceil(?![a-zA-Z])","RCEIL"],["\\\\langle(?![a-zA-Z])","LANGLE"],["\\\\left\\s*\\\\langle(?![a-zA-Z])","LANGLE"],["\\\\bigl\\s*\\\\langle(?![a-zA-Z])","LANGLE"],["\\\\Bigl\\s*\\\\langle(?![a-zA-Z])","LANGLE"],["\\\\biggl\\s*\\\\langle(?![a-zA-Z])","LANGLE"],["\\\\Biggl\\s*\\\\langle(?![a-zA-Z])","LANGLE"],["\\\\rangle(?![a-zA-Z])","RANGLE"],["\\\\right\\s*\\\\rangle(?![a-zA-Z])","RANGLE"],["\\\\bigr\\s*\\\\rangle(?![a-zA-Z])","RANGLE"],["\\\\Bigr\\s*\\\\rangle(?![a-zA-Z])","RANGLE"],["\\\\biggr\\s*\\\\rangle(?![a-zA-Z])","RANGLE"],["\\\\Biggr\\s*\\\\rangle(?![a-zA-Z])","RANGLE"],["\\\\cdot(?![a-zA-Z])","*"],["\\\\div(?![a-zA-Z])","/"],["\\\\times(?![a-zA-Z])","*"],[",",","],[":",":"],["\\\\mid(?![a-zA-Z])","MID"],["\\\\vartheta(?![a-zA-Z])","LATEXCOMMAND","\\theta"],["\\\\varepsilon(?![a-zA-Z])","LATEXCOMMAND","\\epsilon"],["\\\\varrho(?![a-zA-Z])","LATEXCOMMAND","\\rho"],["\\\\varphi(?![a-zA-Z])","LATEXCOMMAND","\\phi"],["\\\\infty(?![a-zA-Z])","INFINITY"],["\\\\asin(?![a-zA-Z])","LATEXCOMMAND","\\arcsin"],["\\\\acos(?![a-zA-Z])","LATEXCOMMAND","\\arccos"],["\\\\atan(?![a-zA-Z])","LATEXCOMMAND","\\arctan"],["\\\\sqrt(?![a-zA-Z])","SQRT"],["\\\\land(?![a-zA-Z])","AND"],["\\\\wedge(?![a-zA-Z])","AND"],["\\\\lor(?![a-zA-Z])","OR"],["\\\\vee(?![a-zA-Z])","OR"],["\\\\lnot(?![a-zA-Z])","NOT"],["=","="],["\\\\neq(?![a-zA-Z])","NE"],["\\\\ne(?![a-zA-Z])","NE"],["\\\\not\\s*=","NE"],["\\\\leq(?![a-zA-Z])","LE"],["\\\\le(?![a-zA-Z])","LE"],["\\\\geq(?![a-zA-Z])","GE"],["\\\\ge(?![a-zA-Z])","GE"],["<","<"],["\\\\lt(?![a-zA-Z])","<"],[">",">"],["\\\\gt(?![a-zA-Z])",">"],["\\\\in(?![a-zA-Z])","IN"],["\\\\notin(?![a-zA-Z])","NOTIN"],["\\\\not\\s*\\\\in(?![a-zA-Z])","NOTIN"],["\\\\ni(?![a-zA-Z])","NI"],["\\\\not\\s*\\\\ni(?![a-zA-Z])","NOTNI"],["\\\\subset(?![a-zA-Z])","SUBSET"],["\\\\subseteq(?![a-zA-Z])","SUBSETEQ"],["\\\\not\\s*\\\\subset(?![a-zA-Z])","NOTSUBSET"],["\\\\not\\s*\\\\subseteq(?![a-zA-Z])","NOTSUBSETEQ"],["\\\\supset(?![a-zA-Z])","SUPERSET"],["\\\\supseteq(?![a-zA-Z])","SUPERSETEQ"],["\\\\not\\s*\\\\supset(?![a-zA-Z])","NOTSUPERSET"],["\\\\not\\s*\\\\supseteq(?![a-zA-Z])","NOTSUPERSETEQ"],["\\\\cup(?![a-zA-Z])","UNION"],["\\\\cap(?![a-zA-Z])","INTERSECT"],["\\\\perp(?![a-zA-Z])","PERP"],["\\\\bot(?![a-zA-Z])","PERP"],["\\\\parallel(?![a-zA-Z])","PARALLEL"],["\\\\\\|","PARALLEL"],["\\\\angle(?![a-zA-Z])","ANGLE"],["\\\\int(?![a-zA-Z])","INT"],["!","!"],["'","'"],["_","_"],["&","&"],["\\\\ldots(?![a-zA-Z])","LDOTS"],["\\\\\\\\","LINEBREAK"],["\\\\begin\\s*{\\s*[a-zA-Z0-9]+\\s*}","BEGINENVIRONMENT"],["\\\\end\\s*{\\s*[a-zA-Z0-9]+\\s*}","ENDENVIRONMENT"],["\\\\operatorname\\s*{\\s*[a-zA-Z0-9\\+\\-]+\\s*}","VARMULTICHAR"],["\\\\[a-zA-Z]+(?![a-zA-Z])","LATEXCOMMAND"],["\\\\[$%]","LATEXCOMMAND"],["[a-zA-Z_$%]","VAR"]],allowSimplifiedFunctionApplicationDefault=!0,allowedLatexSymbolsDefault=["alpha","beta","gamma","Gamma","delta","Delta","epsilon","zeta","eta","theta","Theta","iota","kappa","lambda","Lambda","mu","nu","xi","Xi","pi","Pi","rho","sigma","Sigma","tau","Tau","upsilon","Upsilon","phi","Phi","chi","psi","Psi","omega","Omega","partial","angle","circ","%","$"],appliedFunctionSymbolsDefault=["abs","exp","log","ln","log10","sign","sqrt","erf","cos","cosh","acos","acosh","arccos","arccosh","cot","coth","acot","acoth","arccot","arccoth","csc","csch","acsc","acsch","arccsc","arccsch","sec","sech","asec","asech","arcsec","arcsech","sin","sinh","asin","asinh","arcsin","arcsinh","tan","tanh","atan","atan2","atanh","arctan","arctanh","arg","conj","Re","Im","det","trace","nPr","nCr","floor","ceil","round"],functionSymbolsDefault=["f","g"],operatorSymbolsDefault={frac:{nargs:2,substitute:"/"},binom:{nargs:2},vec:{nargs:1},overline:{nargs:1,substitute:"linesegment",remove_products:!0}},unitsDefault=get_all_units();unitsDefault.circ=unitsDefault.deg,unitsDefault.circ.substitute="deg",unitsDefault.circ.isExponent=!0,delete unitsDefault.deg;const parseLeibnizNotationDefault=!0;class latexToAst$1{constructor({allowSimplifiedFunctionApplication:e=allowSimplifiedFunctionApplicationDefault,allowedLatexSymbols:t=allowedLatexSymbolsDefault,appliedFunctionSymbols:n=appliedFunctionSymbolsDefault,functionSymbols:r=functionSymbolsDefault,operatorSymbols:a=operatorSymbolsDefault,units:i=unitsDefault,parseLeibnizNotation:s=parseLeibnizNotationDefault,parseScientificNotation:o=!0}={}){this.allowSimplifiedFunctionApplication=e,this.allowedLatexSymbols=t,this.appliedFunctionSymbols=n,this.functionSymbols=r,this.operatorSymbols=a,this.units=i,this.parseLeibnizNotation=s;let l=base_latex_rules;l=o?[...number_rules_sci,...l]:[...number_rules_non_sci,...l],this.lexer=new lexer(l,whitespace_rule)}advance(e){if(this.token=this.lexer.advance(e),"INVALID"===this.token.token_type)throw new ParseError("Invalid symbol '"+this.token.original_text+"'",this.lexer.location)}return_state(){return{lexer_state:this.lexer.return_state(),token:Object.assign({},this.token)}}set_state(e){this.lexer.set_state(e.lexer_state),this.token=Object.assign({},e.token)}convert(e){this.lexer.set_input(e),this.advance();var t=this.statement_list();if("EOF"!==this.token.token_type)throw new ParseError("Invalid location of '"+this.token.original_text+"'",this.lexer.location);return flatten(t)}statement_list(){for(var e=[this.statement()];","===this.token.token_type;)this.advance(),e.push(this.statement());return e.length>1?["list"].concat(e):e[0]}statement({inside_absolute_value:e=0}={}){if("LDOTS"===this.token.token_type)return this.advance(),["ldots"];var t;try{t=this.return_state();let n=this.statement_a({inside_absolute_value:e});if(":"!==this.token.token_type&&"MID"!==this.token.token_type)return n;let r=":"===this.token.token_type?":":"|";return this.advance(),[r,n,this.statement_a()]}catch(e){try{this.set_state(t);let n=this.statement_a({parse_absolute_value:!1});if("|"!==this.token.token_type[0])throw e;return this.advance(),["|",n,this.statement_a({parse_absolute_value:!1})]}catch(t){throw e}}}statement_a({inside_absolute_value:e=0,parse_absolute_value:t=!0}={}){for(var n=this.statement_b({inside_absolute_value:e,parse_absolute_value:t});"OR"===this.token.token_type;){let r=this.token.token_type.toLowerCase();this.advance(),n=[r,n,this.statement_b({inside_absolute_value:e,parse_absolute_value:t})]}return n}statement_b(e){for(var t=this.relation(e);"AND"===this.token.token_type;){let n=this.token.token_type.toLowerCase();this.advance(),t=[n,t,this.relation(e)]}return t}relation(e){if("NOT"===this.token.token_type||"!"===this.token.token_type)return this.advance(),["not",this.relation(e)];for(var t=this.expression(e);"="===this.token.token_type||"NE"===this.token.token_type||"<"===this.token.token_type||">"===this.token.token_type||"LE"===this.token.token_type||"GE"===this.token.token_type||"IN"===this.token.token_type||"NOTIN"===this.token.token_type||"NI"===this.token.token_type||"NOTNI"===this.token.token_type||"SUBSET"===this.token.token_type||"NOTSUBSET"===this.token.token_type||"SUBSETEQ"===this.token.token_type||"NOTSUBSETEQ"===this.token.token_type||"SUPERSET"===this.token.token_type||"NOTSUPERSET"===this.token.token_type||"SUPERSETEQ"===this.token.token_type||"NOTSUPERSETEQ"===this.token.token_type;){let n=this.token.token_type.toLowerCase(),r=0;"<"===this.token.token_type||"LE"===this.token.token_type?r=-1:">"!==this.token.token_type&&"GE"!==this.token.token_type||(r=1),this.advance();let a=this.expression(e);if(-1===r)if("<"===this.token.token_type||"LE"===this.token.token_type){let r=["tuple"];"<"===n?r.push(!0):r.push(!1);let i=["tuple",t,a];for(;"<"===this.token.token_type||"LE"===this.token.token_type;)"<"===this.token.token_type?r.push(!0):r.push(!1),this.advance(),i.push(this.expression(e));t=["lts",i,r]}else t=[n,t,a];else if(1===r)if(">"===this.token.token_type||"GE"===this.token.token_type){let r=["tuple"];">"===n?r.push(!0):r.push(!1);let i=["tuple",t,a];for(;">"===this.token.token_type||"GE"===this.token.token_type;)">"===this.token.token_type?r.push(!0):r.push(!1),this.advance(),i.push(this.expression(e));t=["gts",i,r]}else t=[n,t,a];else if("="===n)for(t=["=",t,a];"="===this.token.token_type;)this.advance(),t.push(this.expression(e));else t=[n,t,a]}return t}expression(e){let t=!1;"+"===this.token.token_type&&(t=!0,this.advance());let n=!1;"-"===this.token.token_type&&(n=!0,this.advance());var r=this.term(e);if(n||t){if(!1===r)return(t?"+":"")+(n?"-":"");if("string"==typeof r&&[...r].every((e=>["+","-"].includes(e))))return(t?"+":"")+(n?"-":"")+r}for(!1===r&&(r="_"),n&&(r=r>0?-r:["-",r]),t&&(r=["+",r]);["+","-","UNION","INTERSECT","PERP","PARALLEL"].includes(this.token.token_type);){let t=this.token.token_type.toLowerCase(),n=!1,a=!1;"-"===this.token.token_type?(t="+",n=!0,this.advance()):(this.advance(),"+"===t&&"-"===this.token.token_type&&(n=!0,a=!0,this.advance()));let i=this.term(e);if("+"===t){if(!1===i&&("number"==typeof r||"string"==typeof r))return a?r+"+-":n?r+"-":r+"+";if("string"==typeof i&&[...i].every((e=>["+","-"].includes(e)))&&("number"==typeof r||"string"==typeof r))return a?r+"+-"+i:n?r+"-"+i:r+"+"+i}!1===i&&(i="_"),n&&(i=i>0?-i:["-",i]),r=[t,r,i]}return r}term(e){var t=this.factor(e),n=!1;do{if(n=!1,"*"===this.token.token_type){this.advance(),!1===t&&(t="_");let r=this.factor(e);!1===r&&(r="_"),t=["*",t,r],n=!0}else if("/"===this.token.token_type){this.advance(),!1===t&&(t="_");let r=this.factor(e);!1===r&&(r="_"),t=["/",t,r],n=!0}else{let r=Object.assign({},e);r.allow_absolute_value_closing=!0;let a=this.nonMinusFactor(r);!1!==a&&(!1===t&&(t="_"),t=["*",t,a],n=!0)}}while(n);return this.convert_units_in_term(flatten(t))}convert_units_in_term(e){if(!Array.isArray(e))return e;let t=e[0],n=e.slice(1);if("*"===t){let e=n.length;for(let[t,r]of n.entries()){let a=this.units[r];if(a){if(a.prefix&&t0){let i,s=r;return a.substitute&&(s=a.substitute),i=1===t?["unit",n[0],s]:["unit",["*",...n.slice(0,t).map(this.convert_units_in_term.bind(this))],s],t===e-1?i:this.convert_units_in_term(["*",i,...n.slice(t+1)])}}}return[t,...n.map(this.convert_units_in_term.bind(this))]}if("/"===t)return["/",this.convert_units_in_term(n[0]),this.convert_units_in_term(n[1])];if("^"===t){let e=this.units[n[1]];if(e&&e.isExponent){let t=n[1];return e.substitute&&(t=e.substitute),["unit",n[0],t]}return[t,...n.map(this.convert_units_in_term.bind(this))]}return[t,...n.map(this.convert_units_in_term.bind(this))]}factor(e){if("+"===this.token.token_text){this.advance();let t=this.factor(e);return!1===t?"+":"string"==typeof t&&[...t].every((e=>["+","-"].includes(e)))?"+"+t:["+",t]}if("-"===this.token.token_type){this.advance();let t=this.factor(e);return t>0?-t:!1===t?"-":"string"==typeof t&&[...t].every((e=>["+","-"].includes(e)))?"-"+t:["-",t]}let t=this.nonMinusFactor(e);return!1===t&&"PERP"===this.token.token_type&&(t="perp",this.advance()),t}nonMinusFactor(e){for(var t=this.baseFactor(e);"^"===this.token.token_type||"!"===this.token.token_type||"'"===this.token.token_type;)!1===t&&(t="_"),"^"===this.token.token_type?(this.advance(),t=["^",t,this.get_subsuperscript(e)]):"!"===this.token.token_type?(t=["apply","factorial",t],this.advance()):(t=["prime",t],this.advance());return t}get_single_digit_as_number(){if("NUMBER"===this.token.token_type&&"."!==this.token.token_text[0]){let e=Number(this.token.token_text[0]);return this.token.token_text.length>1&&this.lexer.unput(this.token.token_text.slice(1)),this.advance(),e}return null}get_subsuperscript({parse_absolute_value:e}){let t=this.get_single_digit_as_number();if(null!==t)return t;if(["+","-","PERP"].includes(this.token.token_type)){let e=this.token.token_type.toLowerCase();return this.advance(),e}{let t=this.baseFactor({parse_absolute_value:e,in_subsuperscript_with_no_delimiters:!0});return!1===t&&(t="_"),t}}baseFactor({inside_absolute_value:e=0,parse_absolute_value:t=!0,allow_absolute_value_closing:n=!1,in_subsuperscript_with_no_delimiters:r=!1}={}){var a=!1;if("BEGINENVIRONMENT"===this.token.token_type){let e=/\\begin\s*{\s*([a-zA-Z0-9]+)\s*}/.exec(this.token.token_text)[1];if(["matrix","pmatrix","bmatrix"].includes(e)){let n=0,r=0,i=[],s=[],o=0,l=this.token.token_type;for(this.advance();"ENDENVIRONMENT"!==this.token.token_type;)"&"===this.token.token_type?("&"!==l&&"LINEBREAK"!==l||(s.push(0),o+=1),l=this.token.token_type,this.advance()):"LINEBREAK"===this.token.token_type?("&"!==l&&"LINEBREAK"!==l||(s.push(0),o+=1),i.push(s),o>r&&(r=o),n+=1,o=0,s=[],l=this.token.token_type,this.advance()):(s.push(this.statement({parse_absolute_value:t})),o+=1,l=" ");if(/\\end\s*{\s*([a-zA-Z0-9]+)\s*}/.exec(this.token.token_text)[1]!==e)throw new ParseError("Expecting \\end{"+e+"}",this.lexer.location);"&"===l&&(s.push(0),o+=1),i.push(s),o>r&&(r=o),n+=1,this.advance(),a=["matrix",["tuple",n,r]];let u=["tuple"];for(let e of i){let t=["tuple"].concat(e);for(let n=e.length;n=2?a[0]="("===n||"{"===n?"tuple":"["===n?"array":"LBRACE"===n?"set":"altvector":"LBRACE"===n&&("|"===a[0]||a[0],a=["set",a]);this.advance()}else if("|"!==this.token.token_type[0]||!t||0!==e&&n&&"L"!==this.token.token_type[1]){if("LFLOOR"===this.token.token_type||"LCEIL"===this.token.token_type){let e,t;if("LFLOOR"===this.token.token_type?(e="RFLOOR",t="floor"):"LCEIL"===this.token.token_type&&(e="RCEIL",t="ceil"),this.advance(),a=["apply",t,a=this.statement()],this.token.token_type!==e)throw new ParseError("Expecting "+e,this.lexer.location);this.advance()}else if("ANGLE"===this.token.token_type)if(this.advance(),"{"===this.token.token_type||"("===this.token.token_type){let e;e="{"===this.token.token_type?"}":")",this.advance();let t=this.statement_list();if(this.token.token_type!==e)throw new ParseError("Expecting "+e,this.lexer.location);this.advance(),"list"===t[0]?a=["angle",...t.slice(1)]:"*"===t[0]&&(a=["angle",t])}else{let e=[],n=this.nonMinusFactor({parse_absolute_value:t});for(;!1!==n;)e.push(n),n=this.nonMinusFactor({parse_absolute_value:t});a=0===e.length?"angle":["angle",...e]}else if("INT"===this.token.token_type){this.advance();let e="int";"_"===this.token.token_type&&(this.advance(),e=["_",e,this.get_subsuperscript({parse_absolute_value:t})]),"^"===this.token.token_type&&(this.advance(),e=["^",e,this.get_subsuperscript({parse_absolute_value:t})]);let n=flatten(this.term({parse_absolute_value:t}));if(Array.isArray(n)&&"*"===n[0]){let e=[];for(let t=0;tn)return!1;if(s===n){if("}"!==this.token.token_type)return!1;this.advance();let s="derivative_leibniz";"∂"===t&&(s="partial_"+s),e=[s],1===n?e.push(r):e.push(["tuple",r,n]);let o=[];for(let e=0;e,larger":function(e){return[">",e[0],e[1]]},"<=,smallerEq":function(e){return["le",e[0],e[1]]},">=,largerEq":function(e){return["ge",e[0],e[1]]},"!=,unequal":function(e){return["ne",e[0],e[1]]},"!,factorial":function(e){return["apply","factorial",e[0]]}};class mathjsToAst{convert(e){if(e.isConstantNode)return e.value;if(e.isSymbolNode)return e.name;if(e.isOperatorNode){var t=[e.op,e.fn].join(",");if(t in operators)return operators[t](e.args.map(function(e,t){return this.convert(e)}.bind(this)));throw Error("Unsupported operator: "+e.op+", "+e.fn)}if(e.isFunctionNode){var n=e.args.map(function(e,t){return this.convert(e)}.bind(this));n=n.length>1?["tuple"].concat(n):n[0];var r=["apply",e.name];return r.push(n),r}if(e.isArrayNode)return["vector"].concat(e.args.map(function(e,t){return this.convert(e)}.bind(this)));if(e.isParenthesisNode)return this.convert(e.content);throw Error("Unsupported node type: "+e.type)}}class mathjsToGuppy{constructor(){this.mathjsToAst=new mathjsToAst,this.astToGuppy=new astToGuppy$1}convert(e){return this.astToGuppy.convert(this.mathjsToAst.convert(e))}}class mathjsToLatex{constructor(){this.mathjsToAst=new mathjsToAst,this.astToLatex=new astToLatex$1}convert(e){return this.astToLatex.convert(this.mathjsToAst.convert(e))}}class mathjsToText{constructor(){this.mathjsToAst=new mathjsToAst,this.astToText=new astToText$2}convert(e){return this.astToText.convert(this.mathjsToAst.convert(e))}}function defaultSetTimout(){throw new Error("setTimeout has not been defined")}function defaultClearTimeout(){throw new Error("clearTimeout has not been defined")}var cachedSetTimeout=defaultSetTimout,cachedClearTimeout=defaultClearTimeout;function runTimeout(e){if(cachedSetTimeout===setTimeout)return setTimeout(e,0);if((cachedSetTimeout===defaultSetTimout||!cachedSetTimeout)&&setTimeout)return cachedSetTimeout=setTimeout,setTimeout(e,0);try{return cachedSetTimeout(e,0)}catch(t){try{return cachedSetTimeout.call(null,e,0)}catch(t){return cachedSetTimeout.call(this,e,0)}}}function runClearTimeout(e){if(cachedClearTimeout===clearTimeout)return clearTimeout(e);if((cachedClearTimeout===defaultClearTimeout||!cachedClearTimeout)&&clearTimeout)return cachedClearTimeout=clearTimeout,clearTimeout(e);try{return cachedClearTimeout(e)}catch(t){try{return cachedClearTimeout.call(null,e)}catch(t){return cachedClearTimeout.call(this,e)}}}"function"==typeof global$1.setTimeout&&(cachedSetTimeout=setTimeout),"function"==typeof global$1.clearTimeout&&(cachedClearTimeout=clearTimeout);var queue=[],draining=!1,currentQueue,queueIndex=-1;function cleanUpNextTick(){draining&¤tQueue&&(draining=!1,currentQueue.length?queue=currentQueue.concat(queue):queueIndex=-1,queue.length&&drainQueue())}function drainQueue(){if(!draining){var e=runTimeout(cleanUpNextTick);draining=!0;for(var t=queue.length;t;){for(currentQueue=queue,queue=[];++queueIndex1)for(var n=1;n0)return parse$1(e);if("number"===n&&!1===isNaN(e))return t.long?fmtLong(e):fmtShort(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))};function parse$1(e){if(!((e=String(e)).length>100)){var t=/^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(e);if(t){var n=parseFloat(t[1]);switch((t[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return n*y;case"days":case"day":case"d":return n*d;case"hours":case"hour":case"hrs":case"hr":case"h":return n*h;case"minutes":case"minute":case"mins":case"min":case"m":return n*m;case"seconds":case"second":case"secs":case"sec":case"s":return n*s;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return n;default:return}}}}function fmtShort(e){return e>=d?Math.round(e/d)+"d":e>=h?Math.round(e/h)+"h":e>=m?Math.round(e/m)+"m":e>=s?Math.round(e/s)+"s":e+"ms"}function fmtLong(e){return plural(e,d,"day")||plural(e,h,"hour")||plural(e,m,"minute")||plural(e,s,"second")||e+" ms"}function plural(e,t,n){if(!(e=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/))},t.storage="undefined"!=typeof chrome&&void 0!==chrome.storage?chrome.storage.local:function(){try{return window.localStorage}catch(e){}}(),t.colors=["lightseagreen","forestgreen","goldenrod","dodgerblue","darkorchid","crimson"],t.formatters.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}},t.enable(n())}(browser,browser.exports);var debug=browser.exports("xml-parser"),xmlParser=parse;function parse(e){return e=(e=e.trim()).replace(//g,""),{declaration:function(){if(n(/^<\?xml\s*/)){for(var e={attributes:{}};!r()&&!a("?>");){var i=t();if(!i)return e;e.attributes[i.name]=i.value}return n(/\?>\s*/),e}}(),root:function i(){debug("tag %j",e);var s=n(/^<([\w-:.]+)\s*/);if(s){for(var o,l={name:s[1],attributes:{},children:[]};!(r()||a(">")||a("?>")||a("/>"));){var u=t();if(!u)return l;l.attributes[u.name]=u.value}if(n(/^\s*\/>\s*/))return l;for(n(/\??>\s*/),l.content=function(){debug("content %j",e);var t=n(/^([^<]*)/);return t?t[1]:""}();o=i();)l.children.push(o);return n(/^<\/[\w-:.]+>\s*/),l}}()};function t(){debug("attribute %j",e);var t,r=n(/([\w:-]+)\s*=\s*("[^"]*"|'[^']*'|\w+)\s*/);if(r)return{name:r[1],value:(t=r[2],t.replace(/^['"]|['"]$/g,""))}}function n(t){var n=e.match(t);if(n)return e=e.slice(n[0].length),n}function r(){return 0==e.length}function a(t){return 0==e.indexOf(t)}}const entities={"Α":"\\Alpha","Α":"\\Alpha","Α":"\\Alpha","\\u0391;":"\\Alpha","Β":"\\Beta","Β":"\\Beta","Β":"\\Beta","\\u0392;":"\\Beta","Γ":"\\Gamma","Γ":"\\Gamma","Γ":"\\Gamma","\\u0393;":"\\Gamma","Δ":"\\Delta","Δ":"\\Delta","Δ":"\\Delta","\\u0394;":"\\Delta","Ε":"\\Epsilon","Ε":"\\Epsilon","Ε":"\\Epsilon","\\u0395;":"\\Epsilon","Ζ":"\\Zeta","Ζ":"\\Zeta","Ζ":"\\Zeta","\\u0396;":"\\Zeta","Η":"\\Eta","Η":"\\Eta","Η":"\\Eta","\\u0397;":"\\Eta","Θ":"\\Theta","Θ":"\\Theta","Θ":"\\Theta","\\u0398;":"\\Theta","Ι":"\\Iota","Ι":"\\Iota","Ι":"\\Iota","\\u0399;":"\\Iota","Κ":"\\Kappa","Κ":"\\Kappa","Κ":"\\Kappa","\\u039A;":"\\Kappa","Λ":"\\Lambda","Λ":"\\Lambda","Λ":"\\Lambda","\\u039B;":"\\Lambda","Μ":"\\Mu","Μ":"\\Mu","Μ":"\\Mu","\\u039C;":"\\Mu","Ν":"\\Nu","Ν":"\\Nu","Ν":"\\Nu","\\u039D;":"\\Nu","Ξ":"\\Xi","Ξ":"\\Xi","Ξ":"\\Xi","\\u039E;":"\\Xi","Ο":"\\Omicron","Ο":"\\Omicron","Ο":"\\Omicron","\\u039F;":"\\Omicron","Π":"\\Pi","Π":"\\Pi","Π":"\\Pi","\\u03A0;":"\\Pi","Ρ":"\\Rho","Ρ":"\\Rho","Ρ":"\\Rho","\\u03A1;":"\\Rho","Σ":"\\Sigma","Σ":"\\Sigma","Σ":"\\Sigma","\\u03A3;":"\\Sigma","Τ":"\\Tau","Τ":"\\Tau","Τ":"\\Tau","\\u03A4;":"\\Tau","Υ":"\\Upsilon","Υ":"\\Upsilon","Υ":"\\Upsilon","\\u03A5;":"\\Upsilon","Φ":"\\Phi","Φ":"\\Phi","Φ":"\\Phi","\\u03A6;":"\\Phi","Χ":"\\Chi","Χ":"\\Chi","Χ":"\\Chi","\\u03A7;":"\\Chi","Ψ":"\\Psi","Ψ":"\\Psi","Ψ":"\\Psi","\\u03A8;":"\\Psi","Ω":"\\Omega","Ω":"\\Omega","Ω":"\\Omega","\\u03A9;":"\\Omega","α":"\\alpha","α":"\\alpha","α":"\\alpha","\\u03B1;":"\\alpha","β":"\\beta","β":"\\beta","β":"\\beta","\\u03B2;":"\\beta","γ":"\\gamma","γ":"\\gamma","γ":"\\gamma","\\u03B3;":"\\gamma","δ":"\\delta","δ":"\\delta","δ":"\\delta","\\u03B4;":"\\delta","ε":"\\epsilon","ε":"\\epsilon","ε":"\\epsilon","\\u03B5;":"\\epsilon","ζ":"\\zeta","ζ":"\\zeta","ζ":"\\zeta","\\u03B6;":"\\zeta","η":"\\eta","η":"\\eta","η":"\\eta","\\u03B7;":"\\eta","θ":"\\theta","θ":"\\theta","θ":"\\theta","\\u03B8;":"\\theta","ι":"\\iota","ι":"\\iota","ι":"\\iota","\\u03B9;":"\\iota","κ":"\\kappa","κ":"\\kappa","κ":"\\kappa","\\u03BA;":"\\kappa","λ":"\\lambda","λ":"\\lambda","λ":"\\lambda","\\u03BB;":"\\lambda","μ":"\\mu","μ":"\\mu","μ":"\\mu","\\u03BC;":"\\mu","ν":"\\nu","ν":"\\nu","ν":"\\nu","\\u03BD;":"\\nu","ξ":"\\xi","ξ":"\\xi","ξ":"\\xi","\\u03BE;":"\\xi","ο":"\\omicron","ο":"\\omicron","ο":"\\omicron","\\u03BF;":"\\omicron","π":"\\pi","π":"\\pi","π":"\\pi","\\u03C0;":"\\pi","ρ":"\\rho","ρ":"\\rho","ρ":"\\rho","\\u03C1;":"\\rho","ς":"\\sigma",";":"\\sigma","ς":"\\sigma","\\u03C2;":"\\sigma","σ":"\\sigma","σ":"\\sigma","σ":"\\sigma","\\u03C3;":"\\sigma","τ":"\\tau","τ":"\\tau","τ":"\\tau","\\u03C4;":"\\tau","υ":"\\upsilon","υ":"\\upsilon","υ":"\\upsilon","\\u03C5;":"\\upsilon","φ":"\\phi","φ":"\\phi","φ":"\\phi","\\u03C6;":"\\phi","χ":"\\chi","χ":"\\chi","χ":"\\chi","\\u03C7;":"\\chi","ψ":"\\psi","ψ":"\\psi","ψ":"\\psi","\\u03C8;":"\\psi","ω":"\\omega","ω":"\\omega","ω":"\\omega","\\u03C9;":"\\omega","−":"-","−":"-","∞":"\\infty","∞":"\\infty","∞":"\\infty","⋅":"\\cdot","⋅":"\\cdot","⋅":"\\cdot","×":"\\times","×":"\\times","×":"\\times"};class mmlToLatex{parse(e){return"mi"===e.name?entities[e.content]?entities[e.content]:e.content.length>1?"\\"+e.content:e.content:"mn"===e.name?e.content:"msup"===e.name?this.parse(e.children[0])+"^{"+this.parse(e.children[1])+"}":"mroot"===e.name?"\\sqrt["+this.parse(e.children[1])+"]{"+this.parse(e.children[1])+"}":"mfrac"===e.name?"\\frac{"+this.parse(e.children[0])+"}{"+this.parse(e.children[1])+"}":"msqrt"===e.name?"\\sqrt{"+e.children.map(function(e,t){return this.parse(e)}.bind(this)).join(" ")+"}":"mo"===e.name?entities[e.content]?entities[e.content]:"⁡"===e.content?" ":e.content:"mrow"===e.name&&"MJX-TeXAtom-ORD"===e.attributes.class?e.children.map(function(e,t){return this.parse(e)}.bind(this)).join(" "):"math"===e.name||"mrow"===e.name?"("+e.children.map(function(e,t){return this.parse(e)}.bind(this)).join(" ")+")":void 0}convert(e){return this.parse(xmlParser(e).root)}}class mmlToAst$1{constructor(){this.mmlToLatex=new mmlToLatex,this.latexToAst=new latexToAst$1}convert(e){return this.latexToAst.convert(this.mmlToLatex.convert(e))}}class mmlToGuppy{constructor(){this.mmlToLatex=new mmlToLatex,this.latexToAst=new latexToAst$1,this.astToGuppy=new astToGuppy$1}convert(e){return this.astToGuppy.convert(this.latexToAst.convert(this.mmlToLatex.convert(e)))}}class mmlToMathjs{constructor(){this.mmlToLatex=new mmlToLatex,this.latexToAst=new latexToAst$1,this.astToMathjs=new astToMathjs$1}convert(e){return this.astToMathjs.convert(this.latexToAst.convert(this.mmlToLatex.convert(e)))}}class mmlToText{constructor(){this.mmlToLatex=new mmlToLatex,this.latexToAst=new latexToAst$1,this.astToText=new astToText$2}convert(e){return this.astToText.convert(this.latexToAst.convert(this.mmlToLatex.convert(e)))}}class textToGuppy{constructor(){this.textToAst=new textToAst$4,this.astToGuppy=new astToGuppy$1}convert(e){return this.astToGuppy.convert(this.textToAst.convert(e))}}class textToLatex{constructor(){this.textToAst=new textToAst$4,this.astToLatex=new astToLatex$1}convert(e){return this.astToLatex.convert(this.textToAst.convert(e))}}class textToMathjs{constructor(){this.textToAst=new textToAst$4,this.astToMathjs=new astToMathjs$1}convert(e){return this.astToMathjs.convert(this.textToAst.convert(e))}}var converters=Object.freeze({__proto__:null,astToLatexObj:astToLatex$1,astToTextObj:astToText$2,astToGuppyObj:astToGuppy$1,astToMathjsObj:astToMathjs$1,latexToAstObj:latexToAst$1,latexToGuppyObj:latexToGuppy,latexToMathjsObj:latexToMathjs,latexToTextObj:latexToText,mathjsToAstObj:mathjsToAst,mathjsToGuppyObj:mathjsToGuppy,mathjsToLatexObj:mathjsToLatex,mathjsToTextObj:mathjsToText,mmlToAstObj:mmlToAst$1,mmlToGuppyObj:mmlToGuppy,mmlToLatexObj:mmlToLatex,mmlToMathjsObj:mmlToMathjs,mmlToTextObj:mmlToText,textToAstObj:textToAst$4,textToGuppyObj:textToGuppy,textToLatexObj:textToLatex,textToMathjsObj:textToMathjs,astToGLSL:astToGLSL$1}),textToAst=new textToAst$4,latexToAst=new latexToAst$1,mmlToAst=new mmlToAst$1,utils={match:match$2,flatten:flatten$5,unflattenLeft:unflattenLeft,unflattenRight:unflattenRight};function Expression(e,t){this.tree=flatten$5(e),this.context=t,this.toJSON=function(){let e={objectType:"math-expression",tree:this.tree},t={};for(let e in this.context.assumptions)Object.keys(this.context.assumptions[e]).length>0&&(t[e]=this.context.assumptions[e]);return Object.keys(t).length>0&&(e.assumptions=t),e}}function extend(e,t){return flatten_array(Array.prototype.slice.call(arguments,2)).forEach((function(n){if(n)for(var r in n)t?function(){var t=r;e[t]=function(){return this.fromAst(n[t].apply(null,arguments))}}():e[r]=n[r]})),e}function extend_prototype(e,t){return flatten_array(Array.prototype.slice.call(arguments,2)).forEach((function(n){if(n)for(var r in n)!function(){var a=r;e[a]=function(){var e=[this].concat(Array.prototype.slice.call(arguments));return t?this.context.fromAst(n[a].apply(null,e)):n[a].apply(null,e)}}()})),e}function create_from_multiple(e,t){if(Array.isArray(e)||"number"==typeof e)return new Expression(e,Context);if("string"==typeof e)try{return new Expression(textToAst.convert(e),Context)}catch(t){try{return new Expression(latexToAst.convert(e),Context)}catch(n){try{return new Expression(mmlToAst.convert(e),Context)}catch(r){if(-1!==e.indexOf("\\"))throw n;if(-1!==e.indexOf(">>2]>>>24-i%4*8&255;t[r+i>>>2]|=s<<24-(r+i)%4*8}else for(i=0;i>>2]=n[i>>>2];return this.sigBytes+=a,this},clamp:function(){var t=this.words,n=this.sigBytes;t[n>>>2]&=4294967295<<32-n%4*8,t.length=e.ceil(n/4)},clone:function(){var e=i.clone.call(this);return e.words=this.words.slice(0),e},random:function(t){for(var n,r=[],a=function(t){var n=987654321,r=4294967295;return function(){var a=((n=36969*(65535&n)+(n>>16)&r)<<16)+(t=18e3*(65535&t)+(t>>16)&r)&r;return a/=4294967296,(a+=.5)*(e.random()>.5?1:-1)}},i=0;i>>2]>>>24-a%4*8&255;r.push((i>>>4).toString(16)),r.push((15&i).toString(16))}return r.join("")},parse:function(e){for(var t=e.length,n=[],r=0;r>>3]|=parseInt(e.substr(r,2),16)<<24-r%8*4;return new s.init(n,t/2)}},u=o.Latin1={stringify:function(e){for(var t=e.words,n=e.sigBytes,r=[],a=0;a>>2]>>>24-a%4*8&255;r.push(String.fromCharCode(i))}return r.join("")},parse:function(e){for(var t=e.length,n=[],r=0;r>>2]|=(255&e.charCodeAt(r))<<24-r%4*8;return new s.init(n,t)}},c=o.Utf8={stringify:function(e){try{return decodeURIComponent(escape(u.stringify(e)))}catch(e){throw new Error("Malformed UTF-8 data")}},parse:function(e){return u.parse(unescape(encodeURIComponent(e)))}},p=a.BufferedBlockAlgorithm=i.extend({reset:function(){this._data=new s.init,this._nDataBytes=0},_append:function(e){"string"==typeof e&&(e=c.parse(e)),this._data.concat(e),this._nDataBytes+=e.sigBytes},_process:function(t){var n=this._data,r=n.words,a=n.sigBytes,i=this.blockSize,o=a/(4*i),l=(o=t?e.ceil(o):e.max((0|o)-this._minBufferSize,0))*i,u=e.min(4*l,a);if(l){for(var c=0;c>>31}var p=(r<<5|r>>>27)+l+i[u];p+=u<20?1518500249+(a&s|~a&o):u<40?1859775393+(a^s^o):u<60?(a&s|a&o|s&o)-1894007588:(a^s^o)-899497514,l=o,o=s,s=a<<30|a>>>2,a=r,r=p}n[0]=n[0]+r|0,n[1]=n[1]+a|0,n[2]=n[2]+s|0,n[3]=n[3]+o|0,n[4]=n[4]+l|0},_doFinalize:function(){var e=this._data,t=e.words,n=8*this._nDataBytes,r=8*e.sigBytes;return t[r>>>5]|=128<<24-r%32,t[14+(r+64>>>9<<4)]=Math.floor(n/4294967296),t[15+(r+64>>>9<<4)]=n,e.sigBytes=4*t.length,this._process(),this._hash},clone:function(){var e=r.clone.call(this);return e._hash=this._hash.clone(),e}});e.SHA1=r._createHelper(s),e.HmacSHA1=r._createHmacHelper(s)}(),CryptoJS.SHA1);var sha1=sha1$1.exports,encBase64={exports:{}};!function(e,t){e.exports=function(e){return function(){var t=e,n=t.lib.WordArray;function r(e,t,r){for(var a=[],i=0,s=0;s>>6-s%4*2;a[i>>>2]|=(o|l)<<24-i%4*8,i++}return n.create(a,i)}t.enc.Base64={stringify:function(e){var t=e.words,n=e.sigBytes,r=this._map;e.clamp();for(var a=[],i=0;i>>2]>>>24-i%4*8&255)<<16|(t[i+1>>>2]>>>24-(i+1)%4*8&255)<<8|t[i+2>>>2]>>>24-(i+2)%4*8&255,o=0;o<4&&i+.75*o>>6*(3-o)&63));var l=r.charAt(64);if(l)for(;a.length%4;)a.push(l);return a.join("")},parse:function(e){var t=e.length,n=this._map,a=this._reverseMap;if(!a){a=this._reverseMap=[];for(var i=0;iArray.isArray(t)?e.concat(flattenDeep(t)):e.concat(t)),[])}function flattenLevels(e,t){return console.log(`levels: ${t}`),e.reduce(((e,n)=>Array.isArray(n)&&t>1?e.concat(flattenLevels(n,t-1)):e.concat(n)),[])}class Subset{union(e){return this.complement().intersect(e.complement()).complement()}intersectWithOpenInterval(e){return this.intersect(e)}setMinus(e){return this.intersect(e.complement())}symmetricDifference(e){return this.setMinus(e).union(e.setMinus(this))}equals(e){return this.symmetricDifference(e).isEmpty()}toJSON(){return{objectType:"subset",data:Object.assign({},this),subsetType:this.constructor.subsetType}}static reviver(e,t){if(t&&"subset"===t.objectType&&void 0!==t.subsetType){if("emptySet"===t.subsetType)return new EmptySet;if("realLine"===t.subsetType)return new RealLine;if("singleton"===t.subsetType)return new Singleton(t.data.element);if("union"===t.subsetType)return new Union(t.data.subsets);if("openInterval"===t.subsetType)return new OpenInterval(t.data.left,t.data.right)}return t}copy(){return this.constructor.reviver(null,this.toJSON())}}class EmptySet extends Subset{static subsetType="emptySet";union(e){return e}intersect(){return new EmptySet}contains(){return!1}isEmpty(){return!0}complement(){return new RealLine}toString(){return"∅"}toMathExpression(){return me$3.fromAst("∅")}}class RealLine extends Subset{static subsetType="realLine";union(){return new RealLine}intersect(e){return e}contains(){return!0}complement(){return new EmptySet}isEmpty(){return!1}toString(){return"ℝ"}toMathExpression(){return me$3.fromAst("R")}}class Singleton extends Subset{static subsetType="singleton";constructor(e){if(super(),!Number.isFinite(e))return new EmptySet;this.element=e}union(e){return e.contains(this.element)?e:new Union([e,this])}intersect(e){return e.contains(this.element)?new Singleton(this.element):new EmptySet}isEmpty(){return!1}contains(e){return e===this.element}complement(){return new Union([new OpenInterval(-1/0,this.element),new OpenInterval(this.element,1/0)])}toString(){return`{${this.element}}`}toMathExpression(){return me$3.fromAst(["set",this.element])}}class Union extends Subset{static subsetType="union";intersect(e){return new Union(this.subsets.map((t=>e.intersect(t))))}toString(){return this.subsets.map((e=>e.toString())).join(" U ")}toMathExpression(){return me$3.fromAst(["union",...this.subsets.map((e=>e.toMathExpression().tree))])}constructor(e){super();let t=e.filter((e=>!e.isEmpty()));if(0===t.length)return new EmptySet;t=t.reduce(((e,t)=>t instanceof Union?e.concat(t.subsets):e.concat(t)),[]),this.subsets=[];for(let e=0;ea&&s.elementi.left&&at.contains(e)))}isEmpty(){return this.subsets.every((e=>e.isEmpty()))}complement(){return this.subsets.map((e=>e.complement())).reduce(((e,t)=>e.intersect(t)))}}class Interval$1 extends Subset{constructor(e,t){return super(),this.left=e,this.right=t,this.left<=this.right?this.left===-1/0&&this.right===1/0?new RealLine:this:new EmptySet}}class OpenInterval extends Interval$1{static subsetType="openInterval";constructor(e,t){return super(e,t),e===t?new EmptySet:this}intersect(e){return e.intersectWithOpenInterval(this)}intersectWithOpenInterval(e){return new OpenInterval(Math.max(this.left,e.left),Math.min(this.right,e.right))}complement(){return new Union([new OpenClosedInterval(-1/0,this.left),new ClosedOpenInterval(this.right,1/0)])}isEmpty(){return this.left>=this.right}contains(e){return e>this.left&&ebuildSubsetFromIntervals(e,t))).filter((e=>e));return 0===n.length?new EmptySet:1===n.length?n[0]:new Union(n)}if("intersect"===n||"and"===n){let n=e.slice(1).map((e=>buildSubsetFromIntervals(e,t))).filter((e=>e));return 0===n.length?new RealLine:n.reduce(((e,t)=>e.intersect(t)))}if("set"===n){let n=e.slice(1).map((e=>buildSubsetFromIntervals(e,t))).filter((e=>e));return 0===n.length?new EmptySet:1===n.length?n[0]:new Union(n)}if(["<","le",">","ge","=","ne"].includes(n)){let r=e[1],a=!1;if(!Number.isFinite(r))if(deepCompare(r,t))a=!0;else if(r=me$3.fromAst(r).evaluate_to_constant(),!Number.isFinite(r)&&r!==1/0&&r!==-1/0)return new EmptySet;let i=e[2],s=!1;if(!Number.isFinite(i))if(deepCompare(i,t))s=!0;else if(i=me$3.fromAst(i).evaluate_to_constant(),!Number.isFinite(i)&&i!==1/0&&i!==-1/0)return new EmptySet;return a?s?new EmptySet:"<"===n?new OpenInterval(-1/0,i):"le"===n?new OpenClosedInterval(-1/0,i):">"===n?new OpenInterval(i,1/0):"ge"===n?new ClosedOpenInterval(i,1/0):"="===n?Number.isFinite(i)?new Singleton(i):new EmptySet:Number.isFinite(i)?new Union([new OpenInterval(-1/0,i),new OpenInterval(i,1/0)]):new RealLine:s?"<"===n?new OpenInterval(r,1/0):"le"===n?new ClosedOpenInterval(r,1/0):">"===n?new OpenInterval(-1/0,r):"ge"===n?new OpenClosedInterval(-1/0,r):"="===n?Number.isFinite(r)?new Singleton(r):new EmptySet:Number.isFinite(r)?new Union([new OpenInterval(-1/0,r),new OpenInterval(r,1/0)]):new RealLine:new EmptySet}if(["lts","gts"].includes(n)){let r=e[1].slice(1),a=e[2].slice(1);if(3!==r.length||!deepCompare(r[1],t))return new EmptySet;"gts"===n&&(r.reverse(),a.reverse());let i=r[0];if(!Number.isFinite(i)&&(i=me$3.fromAst(i).evaluate_to_constant(),!Number.isFinite(i)&&i!==1/0&&i!==-1/0))return new EmptySet;let s=r[2];return Number.isFinite(s)||(s=me$3.fromAst(s).evaluate_to_constant(),Number.isFinite(s)||s===1/0||s===-1/0)?a[0]?a[1]?new OpenInterval(i,s):new OpenClosedInterval(i,s):a[1]?new ClosedOpenInterval(i,s):new ClosedInterval(i,s):new EmptySet}if("|"===n){let t=e[1];return buildSubsetFromIntervals(e[2],t)}if("^"!==n||"C"!==e[2]&&"c"!==e[2]){if("in"===n)return deepCompare(e[1],t)?buildSubsetFromIntervals(e[2],t):new EmptySet;if("ni"===n)return deepCompare(e[2],t)?buildSubsetFromIntervals(e[1],t):new EmptySet;if("notin"===n){if(deepCompare(e[1],t)){let n=buildSubsetFromIntervals(e[2],t);if(n)return n.complement()}return new EmptySet}if("notni"===n){if(deepCompare(e[2],t)){let n=buildSubsetFromIntervals(e[1],t);if(n)return n.complement()}return new EmptySet}{let t=me$3.fromAst(e).evaluate_to_constant();return Number.isFinite(t)?new Singleton(t):new EmptySet}}{let n=buildSubsetFromIntervals(e[1],t);return n?n.complement():new EmptySet}}function buildSubsetFromMathExpression(e,t){return buildSubsetFromIntervals(e.to_intervals().tree,t.tree)}function deepClone(e,t,n){if(Object(e)!==e||e instanceof Function)return e;if(void 0!==t&&e instanceof t)return e;if(e instanceof me$3.class||e instanceof theModule.Subset)return e.copy();if(void 0===n&&(n=new WeakMap),Array.isArray(e))return[...e.map((e=>deepClone(e,t,n)))];if(e.constructor===Object&&0===Object.entries(e).length)return{};if(n.has(e))return n.get(e);try{var r=new e.constructor}catch(t){r=Object.create(Object.getPrototypeOf(e))}return e instanceof Map?Array.from(e,(([e,a])=>r.set(deepClone(e,t,n),deepClone(a,t,n)))):e instanceof Set&&Array.from(e,(e=>r.add(deepClone(e,t,n)))),n.set(e,r),Object.assign(r,...Object.keys(e).map((r=>({[r]:deepClone(e[r],t,n)}))))}function deepCompare(e,t,n){var r,a;return r=[],a=[],function e(t,i){var s;if(Number.isNaN(t)&&Number.isNaN(i))return!0;if(t===i)return!0;if(void 0!==n&&t instanceof n&&i instanceof n)return t.componentName===i.componentName;if(t instanceof me$3.class&&i instanceof me$3.class)return e(t.tree,i.tree);if("function"==typeof t&&"function"==typeof i||t instanceof Date&&i instanceof Date||t instanceof RegExp&&i instanceof RegExp||t instanceof String&&i instanceof String||t instanceof Number&&i instanceof Number)return t.toString()===i.toString();if(!(t instanceof Object&&i instanceof Object))return!1;if(t.isPrototypeOf(i)||i.isPrototypeOf(t))return!1;if(t.constructor!==i.constructor)return!1;if(t.prototype!==i.prototype)return!1;if(r.indexOf(t)>-1||a.indexOf(i)>-1)return!1;for(s in i){if(i.hasOwnProperty(s)!==t.hasOwnProperty(s))return!1;if(typeof i[s]!=typeof t[s])return!1}for(s in t){if(i.hasOwnProperty(s)!==t.hasOwnProperty(s))return!1;if(typeof i[s]!=typeof t[s])return!1;switch(typeof t[s]){case"object":case"function":if(r.push(t),a.push(i),!e(t[s],i[s]))return!1;r.pop(),a.pop();break;default:if(!(t[s]===i[s]||Number.isNaN(t[s])&&Number.isNaN(i[s])))return!1}}return!0}(e,t)}function breakStringsAndOthersIntoComponentsByStringCommas(e){return null}function returnBreakStringsSugarFunction({childrenToComponentFunction:e,mustStripOffOuterParentheses:t=!1}){return function({matchedChildren:n}){let r=0,a=[],i=[],s=!1,o=n.length;if(t){let e=n[0];if("string"!=typeof e||"("!==e.trimLeft()[0])return{success:!1}}for(let[e,l]of n.entries()){if("string"!=typeof l){i.push(l);continue}let u=l.trim();if(0===e&&t&&"("===u[0]){let e=n[o-1];if("string"==typeof e){let t=e.trimRight();")"===t[t.length-1]&&(s=!0,u=u.substring(1))}}let c=0;for(let t=0;tc&&i.push(u.substring(c,t)),a.push(i),i=[],c=t+1)}u.length>c&&i.push(u.substring(c,u.length))}return 0!==r?{success:!1}:(a.push(i),{success:!0,newChildren:a.map(e)})}}function breakEmbeddedStringByCommas({childrenList:e}){let t=0,n=[],r=[];for(let a of e){if("string"!=typeof a){r.push(a);continue}let e=a.trim(),i=0;for(let a=0;ai){let t=e.substring(i,a).trim();r.push(t)}n.push(r),r=[],i=a+1}}if(e.length>i){let t=e.substring(i,e.length).trim();r.push(t)}}return 0!==t?{success:!1}:(n.push(r),{success:!0,pieces:n})}function breakEmbeddedStringsIntoParensPieces({componentList:e,removeParens:t=!1}){let n=0,r=[],a=[];for(let i of e){if("string"!=typeof i){0===n?r.push([i]):a.push(i);continue}let e=i.trim(),s=0;for(let i=0;is){let n=t?i:i+1,r=e.substring(s,n).trim();r.length>0&&a.push(r)}r.push(a),a=[],s=i+1}n--}else if(0===n&&!o.match(/\s/))return{success:!1}}if(e.length>s){let t=e.substring(s,e.length).trim();a.push(t)}}return 0!==n?{success:!1}:(a.length>0&&r.push(a),{success:!0,pieces:r})}var global$1="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{};function defaultSetTimout(){throw new Error("setTimeout has not been defined")}function defaultClearTimeout(){throw new Error("clearTimeout has not been defined")}var cachedSetTimeout=defaultSetTimout,cachedClearTimeout=defaultClearTimeout;function runTimeout(e){if(cachedSetTimeout===setTimeout)return setTimeout(e,0);if((cachedSetTimeout===defaultSetTimout||!cachedSetTimeout)&&setTimeout)return cachedSetTimeout=setTimeout,setTimeout(e,0);try{return cachedSetTimeout(e,0)}catch(t){try{return cachedSetTimeout.call(null,e,0)}catch(t){return cachedSetTimeout.call(this,e,0)}}}function runClearTimeout(e){if(cachedClearTimeout===clearTimeout)return clearTimeout(e);if((cachedClearTimeout===defaultClearTimeout||!cachedClearTimeout)&&clearTimeout)return cachedClearTimeout=clearTimeout,clearTimeout(e);try{return cachedClearTimeout(e)}catch(t){try{return cachedClearTimeout.call(null,e)}catch(t){return cachedClearTimeout.call(this,e)}}}"function"==typeof global$1.setTimeout&&(cachedSetTimeout=setTimeout),"function"==typeof global$1.clearTimeout&&(cachedClearTimeout=clearTimeout);var queue=[],draining=!1,currentQueue,queueIndex=-1;function cleanUpNextTick(){draining&¤tQueue&&(draining=!1,currentQueue.length?queue=currentQueue.concat(queue):queueIndex=-1,queue.length&&drainQueue())}function drainQueue(){if(!draining){var e=runTimeout(cleanUpNextTick);draining=!0;for(var t=queue.length;t;){for(currentQueue=queue,queue=[];++queueIndex1)for(var n=1;n{throw new Error("This node type doesn't define a deserialize function")})}add(e){if(this.perNode)throw new RangeError("Can't add per-node props to node types");return"function"!=typeof e&&(e=NodeType.match(e)),t=>{let n=e(t);return void 0===n?null:[this,n]}}}NodeProp.closedBy=new NodeProp({deserialize:e=>e.split(" ")}),NodeProp.openedBy=new NodeProp({deserialize:e=>e.split(" ")}),NodeProp.group=new NodeProp({deserialize:e=>e.split(" ")}),NodeProp.contextHash=new NodeProp({perNode:!0}),NodeProp.lookAhead=new NodeProp({perNode:!0}),NodeProp.mounted=new NodeProp({perNode:!0});const noProps=Object.create(null);class NodeType{constructor(e,t,n,r=0){this.name=e,this.props=t,this.id=n,this.flags=r}static define(e){let t=e.props&&e.props.length?Object.create(null):noProps,n=(e.top?1:0)|(e.skipped?2:0)|(e.error?4:0)|(null==e.name?8:0),r=new NodeType(e.name||"",t,e.id,n);if(e.props)for(let n of e.props)if(Array.isArray(n)||(n=n(r)),n){if(n[0].perNode)throw new RangeError("Can't store a per-node prop on a node type");t[n[0].id]=n[1]}return r}prop(e){return this.props[e.id]}get isTop(){return(1&this.flags)>0}get isSkipped(){return(2&this.flags)>0}get isError(){return(4&this.flags)>0}get isAnonymous(){return(8&this.flags)>0}is(e){if("string"==typeof e){if(this.name==e)return!0;let t=this.prop(NodeProp.group);return!!t&&t.indexOf(e)>-1}return this.id==e}static match(e){let t=Object.create(null);for(let n in e)for(let r of n.split(" "))t[r]=e[n];return e=>{for(let n=e.prop(NodeProp.group),r=-1;r<(n?n.length:0);r++){let a=t[r<0?e.name:n[r]];if(a)return a}}}}NodeType.none=new NodeType("",Object.create(null),0,8);class NodeSet{constructor(e){this.types=e;for(let t=0;te.node;;){let s=!1;if(e.from<=a&&e.to>=r&&(e.type.isAnonymous||!1!==t(e.type,e.from,e.to,i))){if(e.firstChild())continue;e.type.isAnonymous||(s=!0)}for(;s&&n&&n(e.type,e.from,e.to,i),s=e.type.isAnonymous,!e.nextSibling();){if(!e.parent())return;s=!0}}}prop(e){return e.perNode?this.props?this.props[e.id]:void 0:this.type.prop(e)}get propValues(){let e=[];if(this.props)for(let t in this.props)e.push([+t,this.props[t]]);return e}balance(e={}){return this.children.length<=8?this:balanceRange(NodeType.none,this.children,this.positions,0,this.children.length,0,this.length,((e,t,n)=>new Tree(this.type,e,t,n,this.propValues)),e.makeTree||((e,t,n)=>new Tree(NodeType.none,e,t,n)))}static build(e){return buildTree(e)}}Tree.empty=new Tree(NodeType.none,[],[],0);class FlatBufferCursor{constructor(e,t){this.buffer=e,this.index=t}get id(){return this.buffer[this.index-4]}get start(){return this.buffer[this.index-3]}get end(){return this.buffer[this.index-2]}get size(){return this.buffer[this.index-1]}get pos(){return this.index}next(){this.index-=4}fork(){return new FlatBufferCursor(this.buffer,this.index)}}class TreeBuffer{constructor(e,t,n){this.buffer=e,this.length=t,this.set=n}get type(){return NodeType.none}toString(){let e=[];for(let t=0;t0));o=i[o+3]);return s}slice(e,t,n,r){let a=this.buffer,i=new Uint16Array(t-e);for(let r=e,s=0;r=t&&nt;case 1:return n<=t&&r>t;case 2:return r>t;case 4:return!0}}function enterUnfinishedNodesBefore(e,t){let n=e.childBefore(t);for(;n;){let t=n.lastChild;if(!t||t.to!=n.to)break;t.type.isError&&t.from==t.to?(e=n,n=t.prevSibling):n=t}return e}function resolveNode(e,t,n,r){for(var a;e.from==e.to||(n<1?e.from>=t:e.from>t)||(n>-1?e.to<=t:e.to0?s.length:-1;e!=l;e+=t){let l=s[e],u=o[e]+i._from;if(checkSide(r,n,u,u+l.length))if(l instanceof TreeBuffer){if(2&a)continue;let s=l.findChild(0,l.buffer.length,t,n-u,r);if(s>-1)return new BufferNode(new BufferContext(i,l,e,u),null,s)}else if(1&a||!l.type.isAnonymous||hasChild(l)){let s;if(!(1&a)&&l.props&&(s=l.prop(NodeProp.mounted))&&!s.overlay)return new TreeNode(s.tree,u,e,i);let o=new TreeNode(l,u,e,i);return 1&a||!o.type.isAnonymous?o:o.nextChild(t<0?l.children.length-1:0,t,n,r)}}if(1&a||!i.type.isAnonymous)return null;if(e=i.index>=0?i.index+t:t<0?-1:i._parent.node.children.length,i=i._parent,!i)return null}}get firstChild(){return this.nextChild(0,1,0,4)}get lastChild(){return this.nextChild(this.node.children.length-1,-1,0,4)}childAfter(e){return this.nextChild(0,1,e,2)}childBefore(e){return this.nextChild(this.node.children.length-1,-1,e,-2)}enter(e,t,n=!0,r=!0){let a;if(n&&(a=this.node.prop(NodeProp.mounted))&&a.overlay){let n=e-this.from;for(let{from:e,to:r}of a.overlay)if((t>0?e<=n:e=n:r>n))return new TreeNode(a.tree,a.overlay[0].from+this.from,-1,this)}return this.nextChild(0,1,e,t,r?0:2)}nextSignificantParent(){let e=this;for(;e.type.isAnonymous&&e._parent;)e=e._parent;return e}get parent(){return this._parent?this._parent.nextSignificantParent():null}get nextSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index+1,1,0,4):null}get prevSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index-1,-1,0,4):null}get cursor(){return new TreeCursor(this)}get tree(){return this.node}toTree(){return this.node}resolve(e,t=0){return resolveNode(this,e,t,!1)}resolveInner(e,t=0){return resolveNode(this,e,t,!0)}enterUnfinishedNodesBefore(e){return enterUnfinishedNodesBefore(this,e)}getChild(e,t=null,n=null){let r=getChildren(this,e,t,n);return r.length?r[0]:null}getChildren(e,t=null,n=null){return getChildren(this,e,t,n)}toString(){return this.node.toString()}}function getChildren(e,t,n,r){let a=e.cursor,i=[];if(!a.firstChild())return i;if(null!=n)for(;!a.type.is(n);)if(!a.nextSibling())return i;for(;;){if(null!=r&&a.type.is(r))return i;if(a.type.is(t)&&i.push(a.node),!a.nextSibling())return null==r?i:[]}}class BufferContext{constructor(e,t,n,r){this.parent=e,this.buffer=t,this.index=n,this.start=r}}class BufferNode{constructor(e,t,n){this.context=e,this._parent=t,this.index=n,this.type=e.buffer.set.types[e.buffer.buffer[n]]}get name(){return this.type.name}get from(){return this.context.start+this.context.buffer.buffer[this.index+1]}get to(){return this.context.start+this.context.buffer.buffer[this.index+2]}child(e,t,n){let{buffer:r}=this.context,a=r.findChild(this.index+4,r.buffer[this.index+3],e,t-this.context.start,n);return a<0?null:new BufferNode(this.context,this,a)}get firstChild(){return this.child(1,0,4)}get lastChild(){return this.child(-1,0,4)}childAfter(e){return this.child(1,e,2)}childBefore(e){return this.child(-1,e,-2)}enter(e,t,n,r=!0){if(!r)return null;let{buffer:a}=this.context,i=a.findChild(this.index+4,a.buffer[this.index+3],t>0?1:-1,e-this.context.start,t);return i<0?null:new BufferNode(this.context,this,i)}get parent(){return this._parent||this.context.parent.nextSignificantParent()}externalSibling(e){return this._parent?null:this.context.parent.nextChild(this.context.index+e,e,0,4)}get nextSibling(){let{buffer:e}=this.context,t=e.buffer[this.index+3];return t<(this._parent?e.buffer[this._parent.index+3]:e.buffer.length)?new BufferNode(this.context,this._parent,t):this.externalSibling(1)}get prevSibling(){let{buffer:e}=this.context,t=this._parent?this._parent.index+4:0;return this.index==t?this.externalSibling(-1):new BufferNode(this.context,this._parent,e.findChild(t,this.index,-1,0,4))}get cursor(){return new TreeCursor(this)}get tree(){return null}toTree(){let e=[],t=[],{buffer:n}=this.context,r=this.index+4,a=n.buffer[this.index+3];if(a>r){let i=n.buffer[this.index+1],s=n.buffer[this.index+2];e.push(n.slice(r,a,i,s)),t.push(0)}return new Tree(this.type,e,t,this.to-this.from)}resolve(e,t=0){return resolveNode(this,e,t,!1)}resolveInner(e,t=0){return resolveNode(this,e,t,!0)}enterUnfinishedNodesBefore(e){return enterUnfinishedNodesBefore(this,e)}toString(){return this.context.buffer.childString(this.index)}getChild(e,t=null,n=null){let r=getChildren(this,e,t,n);return r.length?r[0]:null}getChildren(e,t=null,n=null){return getChildren(this,e,t,n)}}class TreeCursor{constructor(e,t=0){if(this.mode=t,this.buffer=null,this.stack=[],this.index=0,this.bufferNode=null,e instanceof TreeNode)this.yieldNode(e);else{this._tree=e.context.parent,this.buffer=e.context;for(let t=e._parent;t;t=t._parent)this.stack.unshift(t.index);this.bufferNode=e,this.yieldBuf(e.index)}}get name(){return this.type.name}yieldNode(e){return!!e&&(this._tree=e,this.type=e.type,this.from=e.from,this.to=e.to,!0)}yieldBuf(e,t){this.index=e;let{start:n,buffer:r}=this.buffer;return this.type=t||r.set.types[r.buffer[e]],this.from=n+r.buffer[e+1],this.to=n+r.buffer[e+2],!0}yield(e){return!!e&&(e instanceof TreeNode?(this.buffer=null,this.yieldNode(e)):(this.buffer=e.context,this.yieldBuf(e.index,e.type)))}toString(){return this.buffer?this.buffer.buffer.childString(this.index):this._tree.toString()}enterChild(e,t,n){if(!this.buffer)return this.yield(this._tree.nextChild(e<0?this._tree.node.children.length-1:0,e,t,n,this.mode));let{buffer:r}=this.buffer,a=r.findChild(this.index+4,r.buffer[this.index+3],e,t-this.buffer.start,n);return!(a<0)&&(this.stack.push(this.index),this.yieldBuf(a))}firstChild(){return this.enterChild(1,0,4)}lastChild(){return this.enterChild(-1,0,4)}childAfter(e){return this.enterChild(1,e,2)}childBefore(e){return this.enterChild(-1,e,-2)}enter(e,t,n=!0,r=!0){return this.buffer?!!r&&this.enterChild(1,e,t):this.yield(this._tree.enter(e,t,n&&!(1&this.mode),r))}parent(){if(!this.buffer)return this.yieldNode(1&this.mode?this._tree._parent:this._tree.parent);if(this.stack.length)return this.yieldBuf(this.stack.pop());let e=1&this.mode?this.buffer.parent:this.buffer.parent.nextSignificantParent();return this.buffer=null,this.yieldNode(e)}sibling(e){if(!this.buffer)return!!this._tree._parent&&this.yield(this._tree.index<0?null:this._tree._parent.nextChild(this._tree.index+e,e,0,4,this.mode));let{buffer:t}=this.buffer,n=this.stack.length-1;if(e<0){let e=n<0?0:this.stack[n]+4;if(this.index!=e)return this.yieldBuf(t.findChild(e,this.index,-1,0,4))}else{let e=t.buffer[this.index+3];if(e<(n<0?t.buffer.length:t.buffer[this.stack[n]+3]))return this.yieldBuf(e)}return n<0&&this.yield(this.buffer.parent.nextChild(this.buffer.index+e,e,0,4,this.mode))}nextSibling(){return this.sibling(1)}prevSibling(){return this.sibling(-1)}atLastNode(e){let t,n,{buffer:r}=this;if(r){if(e>0){if(this.index-1)for(let r=t+e,a=e<0?-1:n.node.children.length;r!=a;r+=e){let e=n.node.children[r];if(1&this.mode||e instanceof TreeBuffer||!e.type.isAnonymous||hasChild(e))return!1}return!0}move(e,t){if(t&&this.enterChild(e,0,4))return!0;for(;;){if(this.sibling(e))return!0;if(this.atLastNode(e)||!this.parent())return!1}}next(e=!0){return this.move(1,e)}prev(e=!0){return this.move(-1,e)}moveTo(e,t=0){for(;(this.from==this.to||(t<1?this.from>=e:this.from>e)||(t>-1?this.to<=e:this.to=0;){for(let i=e;i;i=i._parent)if(i.index==r){if(r==this.index)return i;t=i,n=a+1;break e}r=this.stack[--a]}for(let e=n;ee instanceof TreeBuffer||!e.type.isAnonymous||hasChild(e)))}function buildTree(e){var t;let{buffer:n,nodeSet:r,maxBufferLength:a=DefaultBufferLength,reused:i=[],minRepeatType:s=r.types.length}=e,o=Array.isArray(n)?new FlatBufferCursor(n,n.length):n,l=r.types,u=0,c=0;function p(e,t,n,f,y){let{id:g,start:b,end:v,size:N}=o,T=c;for(;N<0;){if(o.next(),-1==N){let t=i[g];return n.push(t),void f.push(b-e)}if(-3==N)return void(u=g);if(-4==N)return void(c=g);throw new RangeError(`Unrecognized record size: ${N}`)}let C,A,V=l[g],x=b-e;if(v-b<=a&&(A=function(e,t){let n=o.fork(),r=0,i=0,l=0,u=n.end-a,c={size:0,start:0,skip:0};e:for(let a=n.pos-e;n.pos>a;){let e=n.size;if(n.id==t&&e>=0){c.size=r,c.start=i,c.skip=l,l+=4,r+=4,n.next();continue}let o=n.pos-e;if(e<0||o=s?4:0,d=n.start;for(n.next();n.pos>o;){if(n.size<0){if(-3!=n.size)break e;p+=4}else n.id>=s&&(p+=4);n.next()}i=d,r+=e,l+=p}(t<0||r==e)&&(c.size=r,c.start=i,c.skip=l);return c.size>4?c:void 0}(o.pos-t,y))){let t=new Uint16Array(A.size-A.skip),n=o.pos-A.size,a=t.length;for(;o.pos>n;)a=h(A.start,t,a);C=new TreeBuffer(t,v-A.start,r),x=A.start-e}else{let e=o.pos-N;o.next();let t=[],n=[],r=g>=s?g:-1,i=0,l=v;for(;o.pos>e;)r>=0&&o.id==r&&o.size>=0?(o.end<=l-a&&(d(t,n,b,i,o.end,l,r,T),i=t.length,l=o.end),o.next()):p(b,e,t,n,r);if(r>=0&&i>0&&i-1&&i>0){let e=function(e){return(t,n,r)=>{let a,i,s=0,o=t.length-1;if(o>=0&&(a=t[o])instanceof Tree){if(!o&&a.type==e&&a.length==r)return a;(i=a.prop(NodeProp.lookAhead))&&(s=n[o]+a.length+i)}return m(e,t,n,r,s)}}(V);C=balanceRange(V,t,n,0,t.length,0,v-b,e,e)}else C=m(V,t,n,v-b,T-v)}n.push(C),f.push(x)}function d(e,t,n,a,i,s,o,l){let u=[],c=[];for(;e.length>a;)u.push(e.pop()),c.push(t.pop()+n-i);e.push(m(r.types[o],u,c,s-i,l-s)),t.push(i-n)}function m(e,t,n,r,a=0,i){if(u){let e=[NodeProp.contextHash,u];i=i?[e].concat(i):[e]}if(a>25){let e=[NodeProp.lookAhead,a];i=i?[e].concat(i):[e]}return new Tree(e,t,n,r,i)}function h(e,t,n){let{id:r,start:a,end:i,size:l}=o;if(o.next(),l>=0&&r4){let r=o.pos-(l-4);for(;o.pos>r;)n=h(e,t,n)}t[--n]=s,t[--n]=i-e,t[--n]=a-e,t[--n]=r}else-3==l?u=r:-4==l&&(c=r);return n}let f=[],y=[];for(;o.pos>0;)p(e.start||0,e.bufferStart||0,f,y,-1);let g=null!==(t=e.length)&&void 0!==t?t:f.length?y[0]+f[0].length:0;return new Tree(l[e.topID],f.reverse(),y.reverse(),g)}const nodeSizeCache=new WeakMap;function nodeSize(e,t){if(!e.isAnonymous||t instanceof TreeBuffer||t.type!=e)return 1;let n=nodeSizeCache.get(t);if(null==n){n=1;for(let r of t.children){if(r.type!=e||!(r instanceof Tree)){n=1;break}n+=nodeSize(e,r)}nodeSizeCache.set(t,n)}return n}function balanceRange(e,t,n,r,a,i,s,o,l){let u=0;for(let n=r;n=c)break;h+=t}if(u==a+1){if(h>c){let e=n[a];t(e.children,e.positions,0,e.children.length,r[a]+o);continue}p.push(n[a])}else{let t=r[u-1]+n[u-1].length-m;p.push(balanceRange(e,n,r,a,u,m,t,null,l))}d.push(m+o-i)}}(t,n,r,a,0),(o||l)(p,d,s)}class Parser$1{startParse(e,t,n){return"string"==typeof e&&(e=new StringInput(e)),n=n?n.length?n.map((e=>new Range(e.from,e.to))):[new Range(0,0)]:[new Range(0,e.length)],this.createParse(e,t||[],n)}parse(e,t,n){let r=this.startParse(e,t,n);for(;;){let e=r.advance();if(e)return e}}}class StringInput{constructor(e){this.string=e}get length(){return this.string.length}chunk(e){return this.string.slice(e)}get lineChunks(){return!1}read(e,t){return this.string.slice(e,t)}}new NodeProp({perNode:!0});class Stack$1{constructor(e,t,n,r,a,i,s,o,l,u=0,c){this.p=e,this.stack=t,this.state=n,this.reducePos=r,this.pos=a,this.score=i,this.buffer=s,this.bufferBase=o,this.curContext=l,this.lookAhead=u,this.parent=c}toString(){return`[${this.stack.filter(((e,t)=>t%3==0)).concat(this.state)}]@${this.pos}${this.score?"!"+this.score:""}`}static start(e,t,n=0){let r=e.parser.context;return new Stack$1(e,[],t,n,n,0,[],0,r?new StackContext(r,r.start):null,0,null)}get context(){return this.curContext?this.curContext.context:null}pushState(e,t){this.stack.push(this.state,t,this.bufferBase+this.buffer.length),this.state=e}reduce(e){let t=e>>19,n=65535&e,{parser:r}=this.p,a=r.dynamicPrecedence(n);if(a&&(this.score+=a),0==t)return this.pushState(r.getGoto(this.state,n,!0),this.reducePos),ni;)this.stack.pop();this.reduceContext(n,s)}storeNode(e,t,n,r=4,a=!1){if(0==e){let e=this,r=this.buffer.length;if(0==r&&e.parent&&(r=e.bufferBase-e.parent.bufferBase,e=e.parent),r>0&&0==e.buffer[r-4]&&e.buffer[r-1]>-1){if(t==n)return;if(e.buffer[r-2]>=t)return void(e.buffer[r-2]=n)}}if(a&&this.pos!=n){let a=this.buffer.length;if(a>0&&0!=this.buffer[a-4])for(;a>0&&this.buffer[a-2]>n;)this.buffer[a]=this.buffer[a-4],this.buffer[a+1]=this.buffer[a-3],this.buffer[a+2]=this.buffer[a-2],this.buffer[a+3]=this.buffer[a-1],a-=4,r>4&&(r-=4);this.buffer[a]=e,this.buffer[a+1]=t,this.buffer[a+2]=n,this.buffer[a+3]=r}else this.buffer.push(e,t,n,r)}shift(e,t,n){let r=this.pos;if(131072&e)this.pushState(65535&e,this.pos);else if(0==(262144&e)){let a=e,{parser:i}=this.p;(n>this.pos||t<=i.maxNode)&&(this.pos=n,i.stateFlag(a,1)||(this.reducePos=n)),this.pushState(a,r),this.shiftContext(t,r),t<=i.maxNode&&this.buffer.push(t,r,n,4)}else this.pos=n,this.shiftContext(t,r),t<=this.p.parser.maxNode&&this.buffer.push(t,r,n,4)}apply(e,t,n){65536&e?this.reduce(e):this.shift(e,t,n)}useNode(e,t){let n=this.p.reused.length-1;(n<0||this.p.reused[n]!=e)&&(this.p.reused.push(e),n++);let r=this.pos;this.reducePos=this.pos=r+e.length,this.pushState(t,r),this.buffer.push(n,r,this.reducePos,-1),this.curContext&&this.updateContext(this.curContext.tracker.reuse(this.curContext.context,e,this,this.p.stream.reset(this.pos-e.length)))}split(){let e=this,t=e.buffer.length;for(;t>0&&e.buffer[t-2]>e.reducePos;)t-=4;let n=e.buffer.slice(t),r=e.bufferBase+t;for(;e&&r==e.bufferBase;)e=e.parent;return new Stack$1(this.p,this.stack.slice(),this.state,this.reducePos,this.pos,this.score,n,r,this.curContext,this.lookAhead,e)}recoverByDelete(e,t){let n=e<=this.p.parser.maxNode;n&&this.storeNode(e,this.pos,t,4),this.storeNode(0,this.pos,t,n?8:4),this.pos=this.reducePos=t,this.score-=190}canShift(e){for(let t=new SimulatedStack(this);;){let n=this.p.parser.stateSlot(t.state,4)||this.p.parser.hasAction(t.state,e);if(0==(65536&n))return!0;if(0==n)return!1;t.reduce(n)}}recoverByInsert(e){if(this.stack.length>=300)return[];let t=this.p.parser.nextStates(this.state);if(t.length>8||this.stack.length>=120){let n=[];for(let r,a=0;a1&t&&e==r))||n.push(t[e],r)}t=n}let n=[];for(let e=0;e>19,r=65535&e,a=this.stack.length-3*n;if(a<0||t.getGoto(this.stack[a],r,!1)<0)return!1;this.storeNode(0,this.reducePos,this.reducePos,4,!0),this.score-=100}return this.reduce(e),!0}forceAll(){for(;!this.p.parser.stateFlag(this.state,2);)if(!this.forceReduce()){this.storeNode(0,this.pos,this.pos,4,!0);break}return this}get deadEnd(){if(3!=this.stack.length)return!1;let{parser:e}=this.p;return 65535==e.data[e.stateSlot(this.state,1)]&&!e.stateSlot(this.state,4)}restart(){this.state=this.stack[0],this.stack.length=0}sameState(e){if(this.state!=e.state||this.stack.length!=e.stack.length)return!1;for(let t=0;tthis.lookAhead&&(this.emitLookAhead(),this.lookAhead=e)}close(){this.curContext&&this.curContext.tracker.strict&&this.emitContext(),this.lookAhead>0&&this.emitLookAhead()}}class StackContext{constructor(e,t){this.tracker=e,this.context=t,this.hash=e.strict?e.hash(t):0}}var Recover;!function(e){e[e.Insert=200]="Insert",e[e.Delete=190]="Delete",e[e.Reduce=100]="Reduce",e[e.MaxNext=4]="MaxNext",e[e.MaxInsertStackDepth=300]="MaxInsertStackDepth",e[e.DampenInsertStackDepth=120]="DampenInsertStackDepth"}(Recover||(Recover={}));class SimulatedStack{constructor(e){this.start=e,this.state=e.state,this.stack=e.stack,this.base=this.stack.length}reduce(e){let t=65535&e,n=e>>19;0==n?(this.stack==this.start.stack&&(this.stack=this.stack.slice()),this.stack.push(this.state,0,0),this.base+=3):this.base-=3*(n-1);let r=this.start.p.parser.getGoto(this.stack[this.base-3],t,!0);this.state=r}}class StackBufferCursor{constructor(e,t,n){this.stack=e,this.pos=t,this.index=n,this.buffer=e.buffer,0==this.index&&this.maybeNext()}static create(e,t=e.bufferBase+e.buffer.length){return new StackBufferCursor(e,t,t-e.bufferBase)}maybeNext(){let e=this.stack.parent;null!=e&&(this.index=this.stack.bufferBase-e.bufferBase,this.stack=e,this.buffer=e.buffer)}get id(){return this.buffer[this.index-4]}get start(){return this.buffer[this.index-3]}get end(){return this.buffer[this.index-2]}get size(){return this.buffer[this.index-1]}next(){this.index-=4,this.pos-=4,0==this.index&&this.maybeNext()}fork(){return new StackBufferCursor(this.stack,this.pos,this.index)}}class CachedToken{constructor(){this.start=-1,this.value=-1,this.end=-1,this.extended=-1,this.lookAhead=0,this.mask=0,this.context=0}}const nullToken=new CachedToken;class InputStream{constructor(e,t){this.input=e,this.ranges=t,this.chunk="",this.chunkOff=0,this.chunk2="",this.chunk2Pos=0,this.next=-1,this.token=nullToken,this.rangeIndex=0,this.pos=this.chunkPos=t[0].from,this.range=t[0],this.end=t[t.length-1].to,this.readNext()}resolveOffset(e,t){let n=this.range,r=this.rangeIndex,a=this.pos+e;for(;an.to:a>=n.to;){if(r==this.ranges.length-1)return null;let e=this.ranges[++r];a+=e.from-n.to,n=e}return a}peek(e){let t,n,r=this.chunkOff+e;if(r>=0&&r=this.chunk2Pos&&tr.to&&(this.chunk2=this.chunk2.slice(0,r.to-t)),n=this.chunk2.charCodeAt(0)}}return t>=this.token.lookAhead&&(this.token.lookAhead=t+1),n}acceptToken(e,t=0){let n=t?this.resolveOffset(t,-1):this.pos;if(null==n||n=this.chunk2Pos&&this.posthis.range.to?e.slice(0,this.range.to-this.pos):e,this.chunkPos=this.pos,this.chunkOff=0}}readNext(){return this.chunkOff>=this.chunk.length&&(this.getChunk(),this.chunkOff==this.chunk.length)?this.next=-1:this.next=this.chunk.charCodeAt(this.chunkOff)}advance(e=1){for(this.chunkOff+=e;this.pos+e>=this.range.to;){if(this.rangeIndex==this.ranges.length-1)return this.setDone();e-=this.range.to-this.pos,this.range=this.ranges[++this.rangeIndex],this.pos=this.range.from}return this.pos+=e,this.pos>=this.token.lookAhead&&(this.token.lookAhead=this.pos+1),this.readNext()}setDone(){return this.pos=this.chunkPos=this.end,this.range=this.ranges[this.rangeIndex=this.ranges.length-1],this.chunk="",this.next=-1}reset(e,t){if(t?(this.token=t,t.start=e,t.lookAhead=e+1,t.value=t.extended=-1):this.token=nullToken,this.pos!=e){if(this.pos=e,e==this.end)return this.setDone(),this;for(;e=this.range.to;)this.range=this.ranges[++this.rangeIndex];e>=this.chunkPos&&e=this.chunkPos&&t<=this.chunkPos+this.chunk.length)return this.chunk.slice(e-this.chunkPos,t-this.chunkPos);if(e>=this.chunk2Pos&&t<=this.chunk2Pos+this.chunk2.length)return this.chunk2.slice(e-this.chunk2Pos,t-this.chunk2Pos);if(e>=this.range.from&&t<=this.range.to)return this.input.read(e,t);let n="";for(let r of this.ranges){if(r.from>=t)break;r.to>e&&(n+=this.input.read(Math.max(r.from,e),Math.min(r.to,t)))}return n}}class TokenGroup{constructor(e,t){this.data=e,this.id=t}token(e,t){readToken(this.data,e,t,this.id)}}TokenGroup.prototype.contextual=TokenGroup.prototype.fallback=TokenGroup.prototype.extend=!1;class ExternalTokenizer{constructor(e,t={}){this.token=e,this.contextual=!!t.contextual,this.fallback=!!t.fallback,this.extend=!!t.extend}}function readToken(e,t,n,r){let a=0,i=1<0){let n=e[r];if(o.allows(n)&&(-1==t.token.value||t.token.value==n||s.overrides(n,t.token.value))){t.acceptToken(n);break}}for(let r=t.next,i=0,s=e[a+2];i>1,l=n+o+(o<<1),u=e[l],c=e[l+1];if(r=c)){a=e[l+2],t.advance();continue e}i=o+1}}break}}function decodeArray(e,t=Uint16Array){if("string"!=typeof e)return e;let n=null;for(let r=0,a=0;r=92&&t--,t>=34&&t--;let a=t-32;if(a>=46&&(a-=46,n=!0),i+=a,n)break;i*=46}n?n[a++]=i:n=new t(i)}return n}const verbose=void 0!==browser$1&&/\bparse\b/.test(browser$1.env.LOG);let stackIDs=null;var Safety,Rec;function cutAt(e,t,n){let r=e.fullCursor();for(r.moveTo(t);;)if(!(n<0?r.childBefore(t):r.childAfter(t)))for(;;){if((n<0?r.tot)&&!r.type.isError)return n<0?Math.max(0,Math.min(r.to-1,t-25)):Math.min(e.length,Math.max(r.from+1,t+25));if(n<0?r.prevSibling():r.nextSibling())break;if(!r.parent())return n<0?0:e.length}}!function(e){e[e.Margin=25]="Margin"}(Safety||(Safety={}));class FragmentCursor{constructor(e,t){this.fragments=e,this.nodeSet=t,this.i=0,this.fragment=null,this.safeFrom=-1,this.safeTo=-1,this.trees=[],this.start=[],this.index=[],this.nextFragment()}nextFragment(){let e=this.fragment=this.i==this.fragments.length?null:this.fragments[this.i++];if(e){for(this.safeFrom=e.openStart?cutAt(e.tree,e.from+e.offset,1)-e.offset:e.from,this.safeTo=e.openEnd?cutAt(e.tree,e.to+e.offset,-1)-e.offset:e.to;this.trees.length;)this.trees.pop(),this.start.pop(),this.index.pop();this.trees.push(e.tree),this.start.push(-e.offset),this.index.push(0),this.nextStart=this.safeFrom}else this.nextStart=1e9}nodeAt(e){if(ee)return this.nextStart=i,null;if(a instanceof Tree){if(i==e){if(i=Math.max(this.safeFrom,e)&&(this.trees.push(a),this.start.push(i),this.index.push(0))}else this.index[t]++,this.nextStart=i+a.length}}}class TokenCache{constructor(e,t){this.stream=t,this.tokens=[],this.mainToken=null,this.actions=[],this.tokens=e.tokenizers.map((e=>new CachedToken))}getActions(e){let t=0,n=null,{parser:r}=e.p,{tokenizers:a}=r,i=r.stateSlot(e.state,3),s=e.curContext?e.curContext.hash:0,o=0;for(let r=0;ru.end+25&&(o=Math.max(u.lookAhead,o)),0!=u.value)){let r=t;if(u.extended>-1&&(t=this.addActions(e,u.extended,u.end,t)),t=this.addActions(e,u.value,u.end,t),!l.extend&&(n=u,t>r))break}}for(;this.actions.length>t;)this.actions.pop();return o&&e.setLookAhead(o),n||e.pos!=this.stream.end||(n=new CachedToken,n.value=e.p.parser.eofTerm,n.start=n.end=e.pos,t=this.addActions(e,n.value,n.end,t)),this.mainToken=n,this.actions}getMainToken(e){if(this.mainToken)return this.mainToken;let t=new CachedToken,{pos:n,p:r}=e;return t.start=n,t.end=Math.min(n+1,r.stream.end),t.value=n==r.stream.end?r.parser.eofTerm:0,t}updateCachedToken(e,t,n){if(t.token(this.stream.reset(n.pos,e),n),e.value>-1){let{parser:t}=n.p;for(let r=0;r=0&&n.p.parser.dialect.allows(a>>1)){0==(1&a)?e.value=a>>1:e.extended=a>>1;break}}}else e.value=0,e.end=Math.min(n.p.stream.end,n.pos+1)}putAction(e,t,n,r){for(let t=0;t4*e.bufferLength?new FragmentCursor(n,e.nodeSet):null}get parsedPos(){return this.minStackPos}advance(){let e,t,n=this.stacks,r=this.minStackPos,a=this.stacks=[];for(let i=0;ir)a.push(s);else{if(this.advanceStack(s,a,n))continue;{e||(e=[],t=[]),e.push(s);let n=this.tokens.getMainToken(s);t.push(n.value,n.end)}}break}}if(!a.length){let t=e&&findFinished(e);if(t)return this.stackToTree(t);if(this.parser.strict)throw verbose&&e&&console.log("Stuck with token "+(this.tokens.mainToken?this.parser.getName(this.tokens.mainToken.value):"none")),new SyntaxError("No parse at "+r);this.recovering||(this.recovering=5)}if(this.recovering&&e){let n=null!=this.stoppedAt&&e[0].pos>this.stoppedAt?e[0]:this.runRecovery(e,t,a);if(n)return this.stackToTree(n.forceAll())}if(this.recovering){let e=1==this.recovering?1:3*this.recovering;if(a.length>e)for(a.sort(((e,t)=>t.score-e.score));a.length>e;)a.pop();a.some((e=>e.reducePos>r))&&this.recovering--}else if(a.length>1)e:for(let e=0;e500&&r.buffer.length>500){if(!((t.score-r.score||t.buffer.length-r.buffer.length)>0)){a.splice(e--,1);continue e}a.splice(n--,1)}}}this.minStackPos=a[0].pos;for(let e=1;e ":"";if(null!=this.stoppedAt&&r>this.stoppedAt)return e.forceReduce()?e:null;if(this.fragments){let t=e.curContext&&e.curContext.tracker.strict,n=t?e.curContext.hash:0;for(let s=this.fragments.nodeAt(r);s;){let r=this.parser.nodeSet.types[s.type.id]==s.type?a.getGoto(e.state,s.type.id):-1;if(r>-1&&s.length&&(!t||(s.prop(NodeProp.contextHash)||0)==n))return e.useNode(s,r),verbose&&console.log(i+this.stackID(e)+` (via reuse of ${a.getName(s.type.id)})`),!0;if(!(s instanceof Tree)||0==s.children.length||s.positions[0]>0)break;let o=s.children[0];if(!(o instanceof Tree&&0==s.positions[0]))break;s=o}}let s=a.stateSlot(e.state,4);if(s>0)return e.reduce(s),verbose&&console.log(i+this.stackID(e)+` (via always-reduce ${a.getName(65535&s)})`),!0;if(e.stack.length>=15e3)for(;e.stack.length>9e3&&e.forceReduce(););let o=this.tokens.getActions(e);for(let s=0;sr?t.push(d):n.push(d)}return!1}advanceFully(e,t){let n=e.pos;for(;;){if(!this.advanceStack(e,null,null))return!1;if(e.pos>n)return pushStackDedup(e,t),!0}}runRecovery(e,t,n){let r=null,a=!1;for(let i=0;i ":"";if(s.deadEnd){if(a)continue;if(a=!0,s.restart(),verbose&&console.log(u+this.stackID(s)+" (restarted)"),this.advanceFully(s,n))continue}let c=s.split(),p=u;for(let e=0;c.forceReduce()&&e<10;e++){if(verbose&&console.log(p+this.stackID(c)+" (via force-reduce)"),this.advanceFully(c,n))break;verbose&&(p=this.stackID(c)+" -> ")}for(let e of s.recoverByInsert(o))verbose&&console.log(u+this.stackID(e)+" (via recover-insert)"),this.advanceFully(e,n);this.stream.end>s.pos?(l==s.pos&&(l++,o=0),s.recoverByDelete(o,l),verbose&&console.log(u+this.stackID(s)+` (via recover-delete ${this.parser.getName(o)})`),pushStackDedup(s,n)):(!r||r.scoree;class ContextTracker{constructor(e){this.start=e.start,this.shift=e.shift||id,this.reduce=e.reduce||id,this.reuse=e.reuse||id,this.hash=e.hash||(()=>0),this.strict=!1!==e.strict}}class LRParser extends Parser$1{constructor(e){if(super(),this.wrappers=[],13!=e.version)throw new RangeError(`Parser version (${e.version}) doesn't match runtime version (13)`);let t=e.nodeNames.split(" ");this.minRepeatTerm=t.length;for(let n=0;ne.topRules[t][1])),r=[];for(let e=0;e=0)a(r,e,t[n++]);else{let i=t[n+-r];for(let s=-r;s>0;s--)a(t[n++],e,i);n++}}}this.nodeSet=new NodeSet(t.map(((t,a)=>NodeType.define({name:a>=this.minRepeatTerm?void 0:t,id:a,props:r[a],top:n.indexOf(a)>-1,error:0==a,skipped:e.skippedNodes&&e.skippedNodes.indexOf(a)>-1})))),this.strict=!1,this.bufferLength=DefaultBufferLength;let i=decodeArray(e.tokenData);if(this.context=e.context,this.specialized=new Uint16Array(e.specialized?e.specialized.length:0),this.specializers=[],e.specialized)for(let t=0;t"number"==typeof e?new TokenGroup(i,e):e)),this.topRules=e.topRules,this.dialects=e.dialects||{},this.dynamicPrecedences=e.dynamicPrecedences||null,this.tokenPrecTable=e.tokenPrec,this.termNames=e.termNames||null,this.maxNode=this.nodeSet.types.length-1,this.dialect=this.parseDialect(),this.top=this.topRules[Object.keys(this.topRules)[0]]}createParse(e,t,n){let r=new Parse(this,e,t,n);for(let a of this.wrappers)r=a(r,e,t,n);return r}getGoto(e,t,n=!1){let r=this.goto;if(t>=r[0])return-1;for(let a=r[t+1];;){let t=r[a++],i=1&t,s=r[a++];if(i&&n)return s;for(let n=a+(t>>1);a0}validAction(e,t){if(t==this.stateSlot(e,4))return!0;for(let n=this.stateSlot(e,1);;n+=3){if(65535==this.data[n]){if(1!=this.data[n+1])return!1;n=pair(this.data,n+2)}if(t==pair(this.data,n+1))return!0}}nextStates(e){let t=[];for(let n=this.stateSlot(e,1);;n+=3){if(65535==this.data[n]){if(1!=this.data[n+1])break;n=pair(this.data,n+2)}if(0==(1&this.data[n+2])){let e=this.data[n+1];t.some(((t,n)=>1&n&&t==e))||t.push(this.data[n],e)}}return t}overrides(e,t){let n=findOffset(this.data,this.tokenPrecTable,t);return n<0||findOffset(this.data,this.tokenPrecTable,e){let n=e.tokenizers.find((e=>e.from==t));return n?n.to:t}))),e.contextTracker&&(t.context=e.contextTracker),e.dialect&&(t.dialect=this.parseDialect(e.dialect)),null!=e.strict&&(t.strict=e.strict),e.wrap&&(t.wrappers=t.wrappers.concat(e.wrap)),null!=e.bufferLength&&(t.bufferLength=e.bufferLength),t}getName(e){return this.termNames?this.termNames[e]:String(e<=this.maxNode&&this.nodeSet.types[e].name||e)}get eofTerm(){return this.maxNode+1}get topNode(){return this.nodeSet.types[this.top[1]]}dynamicPrecedence(e){let t=this.dynamicPrecedences;return null==t?0:t[e]||0}parseDialect(e){let t=Object.keys(this.dialects),n=t.map((()=>!1));if(e)for(let r of e.split(" ")){let e=t.indexOf(r);e>=0&&(n[e]=!0)}let r=null;for(let e=0;ee)&&n.p.parser.stateFlag(n.state,2)&&(!t||t.score=65&&e<=90||95==e||e>=97&&e<=122||e>=161}function isSpace(e){return 9==e||10==e||13==e||32==e}let cachedName=null,cachedInput=null,cachedPos=0;function tagNameAfter(e,t){let n=e.pos+t;if(cachedInput==e&&cachedPos==n)return cachedName;for(;isSpace(e.peek(t));)t++;let r="";for(;;){let n=e.peek(t);if(!nameChar(n))break;r+=String.fromCharCode(n),t++}return cachedInput=e,cachedPos=n,cachedName=r||null}function ElementContext(e,t){this.name=e,this.parent=t,this.hash=t?t.hash:0;for(let t=0;tt==StartTag?new ElementContext(tagNameAfter(r,1)||"",e):e,reduce:(e,t)=>t==Element&&e?e.parent:e,reuse(e,t,n,r){let a=t.type.id;return a==StartTag||a==OpenTag?new ElementContext(tagNameAfter(r,1)||"",e):e},hash:e=>e?e.hash:0,strict:!1}),startTag=new ExternalTokenizer(((e,t)=>{if(60==e.next)if(e.advance(),47==e.next){e.advance();let n=tagNameAfter(e,0);if(!n)return e.acceptToken(incompleteStartCloseTag);if(t.context&&n.toLowerCase()==t.context.name.toLowerCase())return e.acceptToken(StartCloseTag);for(let r=t.context;r;r=r.parent)if(r.name==n)return e.acceptToken(MissingCloseTag,-2);e.acceptToken(mismatchedStartCloseTag)}else if(33!=e.next&&63!=e.next&&!isSpace(e.next))return e.acceptToken(StartTag)}),{contextual:!0});function scanTo(e,t){return new ExternalTokenizer((n=>{for(let r=0,a=0;;a++){if(n.next<0){a&&n.acceptToken(e);break}if(n.next==t.charCodeAt(r)){if(r++,r==t.length){a>t.length&&n.acceptToken(e,1-t.length);break}}else r=0;n.advance()}}))}const commentContent=scanTo(commentContent$1,"--\x3e"),parser=LRParser.deserialize({version:13,states:"*[OQOTOOO]OYO'#CdOeO`O'#CfO!OOTO'#CeOOOP'#Ce'#CeOOOP'#Cx'#CxOOOP'#Co'#CoQQOTOOOOOQ'#Cp'#CpO!VOYO,59OOOOP,59O,59OO!_OpO,59QO!mO`O'#ClOOOP'#DT'#DTOOOP'#Cu'#CuO!rOTO,59PO!yO`O'#CmOOOP,59P,59POOOP-E6m-E6mOOOQ-E6n-E6nOOOP1G.j1G.jOOOO'#Cq'#CqO#ROpO1G.lO#aOpO'#ChOOOO'#Cr'#CrO#rOpO1G.lOOOP1G.l1G.lOOOP1G.t1G.tO#}OWO,59WOOOP-E6s-E6sOOOP1G.k1G.kO$SO`O,59XO$[OWO,59XOOOO-E6o-E6oO$dOpO7+$WOOOP7+$W7+$WOOOP7+$`7+$`O$oOpO,59SO%QOWO,59SOOOO-E6p-E6pOOOP1G.r1G.rO%]OWO1G.sO%]OWO1G.sOOOP1G.s1G.sOOOP< tag. Found ${e.slice(a-1,i)}`)}n.firstChild();let t=e.substring(n.from,n.to);if(!1===n.nextSibling()){if(t in i)throw Error(`Duplicate attribute ${t}. Found in component of type ${r} at indices ${n.from}-${n.to}`);i[t]=!0}else{n.nextSibling();let a=e.substring(n.from+1,n.to-1);if(t in i)throw Error(`Duplicate attribute ${t}. Found in component of type ${r} at indices ${n.from}-${n.to}`);i[t]=a}n.parent()}n.parent();let s=n.to,o={componentType:r,props:{...i},children:[]};for(;n.nextSibling();)if("Text"===n.name){let t=e.substring(n.from,n.to);""!==t&&o.children.push(t)}else{if("Element"!==n.name){if("CloseTag"===n.name)break;if("Comment"===n.name)continue;throw"MismatchedCloseTag"===n.name?Error(`Invalid DoenetML at position ${n.from}. Mismatched closing tag. Expected . Found ${e.slice(n.from,n.to)}.`):Error(`Invalid DoenetML at position ${n.from}. Expected a closing tag. Instead found ${e.slice(n.from,n.to)}.`)}o.children.push(t(n.node.cursor))}return o.range={openBegin:a,openEnd:s,closeBegin:n.from,closeEnd:n.to},o}if("SelfClosingTag"===n.name){n.firstChild(),n.nextSibling();let t=e.substring(n.from,n.to),r=n.from,a={};for(;n.nextSibling();){if("Attribute"!==n.name)throw Error(`Invalid DoenetML at positions ${n.from} to ${n.to}. Error in self-closing <${t}/> tag.`);n.firstChild();let r=e.substring(n.from,n.to);if(!1===n.nextSibling()){if(r in a)throw Error(`Duplicate attribute ${r}. Found in component of type ${t} at indices ${n.from}-${n.to}`);a[r]=!0}else{if(n.nextSibling(),r in a)throw Error(`Duplicate attribute ${r}. Found in component of type ${t} at indices ${n.from}-${n.to}`);let i=e.substring(n.from+1,n.to-1);a[r]=i}n.parent()}let i={selfCloseBegin:r,selfCloseEnd:n.to+2};return{componentType:t,props:{...a},children:[],range:i}}throw Error("Non SelfClosingTag/OpenTag in Element. How did you do that?")}function n(n){if("Element"===n.node.name)return t(n.node.cursor);if("Comment"===n.node.name)return null;if("Text"!==n.node.name)throw Error(`Invalid DoenetML at positions ${n.node.from} to ${n.node.to}. Found ${e.substring(n.node.from,n.node.to)}`);{let t=e.substring(n.node.from,n.node.to);if(""!==t)return t}}if(!e)return[];let r=parse(e),a=[];if(!r.firstChild())return a;let i=n(r);for(null!=i&&a.push(i);r.nextSibling();){let e=n(r);null!=e&&a.push(e)}return a}var base32$1={exports:{}};!function(e){!function(){var t="object"==typeof window?window:{};!t.HI_BASE32_NO_NODE_JS&&"object"==typeof browser$1&&browser$1.versions&&browser$1.versions.node&&(t=commonjsGlobal);var n=!t.HI_BASE32_NO_COMMON_JS&&e.exports,r="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567".split(""),a={A:0,B:1,C:2,D:3,E:4,F:5,G:6,H:7,I:8,J:9,K:10,L:11,M:12,N:13,O:14,P:15,Q:16,R:17,S:18,T:19,U:20,V:21,W:22,X:23,Y:24,Z:25,2:26,3:27,4:28,5:29,6:30,7:31},i=[0,0,0,0,0,0,0,0],s=function(e,t){t.length>10&&(t="..."+t.substr(-10));var n=new Error("Decoded data is not valid UTF-8. Maybe try base32.decode.asBytes()? Partial data after reading "+e+" bytes: "+t+" <-");throw n.position=e,n},o=function(e){if(""===e)return[];if(!/^[A-Z2-7=]+$/.test(e))throw new Error("Invalid base32 characters");for(var t,n,r,i,s,o,l,u,c=[],p=0,d=(e=e.replace(/=/g,"")).length,m=0,h=d>>3<<3;m>>2),c[p++]=255&(n<<6|r<<1|i>>>4),c[p++]=255&(i<<4|s>>>1),c[p++]=255&(s<<7|o<<2|l>>>3),c[p++]=255&(l<<5|u);var f=d-h;return 2===f?(t=a[e.charAt(m++)],n=a[e.charAt(m++)],c[p++]=255&(t<<3|n>>>2)):4===f?(t=a[e.charAt(m++)],n=a[e.charAt(m++)],r=a[e.charAt(m++)],i=a[e.charAt(m++)],c[p++]=255&(t<<3|n>>>2),c[p++]=255&(n<<6|r<<1|i>>>4)):5===f?(t=a[e.charAt(m++)],n=a[e.charAt(m++)],r=a[e.charAt(m++)],i=a[e.charAt(m++)],s=a[e.charAt(m++)],c[p++]=255&(t<<3|n>>>2),c[p++]=255&(n<<6|r<<1|i>>>4),c[p++]=255&(i<<4|s>>>1)):7===f&&(t=a[e.charAt(m++)],n=a[e.charAt(m++)],r=a[e.charAt(m++)],i=a[e.charAt(m++)],s=a[e.charAt(m++)],o=a[e.charAt(m++)],l=a[e.charAt(m++)],c[p++]=255&(t<<3|n>>>2),c[p++]=255&(n<<6|r<<1|i>>>4),c[p++]=255&(i<<4|s>>>1),c[p++]=255&(s<<7|o<<2|l>>>3)),c},l=function(e,t){if(!t)return function(e){for(var t,n,r="",a=e.length,i=0,o=0;i191&&t<=223?(n=31&t,o=1):t<=239?(n=15&t,o=2):t<=247?(n=7&t,o=3):s(i,r);for(var l=0;l191)&&s(i,r),n<<=6,n+=63&t;n>=55296&&n<=57343&&s(i,r),n>1114111&&s(i,r),n<=65535?r+=String.fromCharCode(n):(n-=65536,r+=String.fromCharCode(55296+(n>>10)),r+=String.fromCharCode(56320+(1023&n)))}return r}(o(e));if(""===e)return"";if(!/^[A-Z2-7=]+$/.test(e))throw new Error("Invalid base32 characters");var n,r,i,l,u,c,p,d,m="",h=e.indexOf("=");-1===h&&(h=e.length);for(var f=0,y=h>>3<<3;f>>2))+String.fromCharCode(255&(r<<6|i<<1|l>>>4))+String.fromCharCode(255&(l<<4|u>>>1))+String.fromCharCode(255&(u<<7|c<<2|p>>>3))+String.fromCharCode(255&(p<<5|d));var g=h-y;return 2===g?(n=a[e.charAt(f++)],r=a[e.charAt(f++)],m+=String.fromCharCode(255&(n<<3|r>>>2))):4===g?(n=a[e.charAt(f++)],r=a[e.charAt(f++)],i=a[e.charAt(f++)],l=a[e.charAt(f++)],m+=String.fromCharCode(255&(n<<3|r>>>2))+String.fromCharCode(255&(r<<6|i<<1|l>>>4))):5===g?(n=a[e.charAt(f++)],r=a[e.charAt(f++)],i=a[e.charAt(f++)],l=a[e.charAt(f++)],u=a[e.charAt(f++)],m+=String.fromCharCode(255&(n<<3|r>>>2))+String.fromCharCode(255&(r<<6|i<<1|l>>>4))+String.fromCharCode(255&(l<<4|u>>>1))):7===g&&(n=a[e.charAt(f++)],r=a[e.charAt(f++)],i=a[e.charAt(f++)],l=a[e.charAt(f++)],u=a[e.charAt(f++)],c=a[e.charAt(f++)],p=a[e.charAt(f++)],m+=String.fromCharCode(255&(n<<3|r>>>2))+String.fromCharCode(255&(r<<6|i<<1|l>>>4))+String.fromCharCode(255&(l<<4|u>>>1))+String.fromCharCode(255&(u<<7|c<<2|p>>>3))),m},u={encode:function(e,t){var n="string"!=typeof e;return n&&e.constructor===ArrayBuffer&&(e=new Uint8Array(e)),n?function(e){for(var t,n,a,i,s,o="",l=e.length,u=0,c=5*parseInt(l/5);u>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[31&(n<<4|a>>>4)]+r[31&(a<<1|i>>>7)]+r[i>>>2&31]+r[31&(i<<3|s>>>5)]+r[31&s];var p=l-c;return 1===p?(t=e[u],o+=r[t>>>3]+r[t<<2&31]+"======"):2===p?(t=e[u++],n=e[u],o+=r[t>>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[n<<4&31]+"===="):3===p?(t=e[u++],n=e[u++],a=e[u],o+=r[t>>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[31&(n<<4|a>>>4)]+r[a<<1&31]+"==="):4===p&&(t=e[u++],n=e[u++],a=e[u++],i=e[u],o+=r[t>>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[31&(n<<4|a>>>4)]+r[31&(a<<1|i>>>7)]+r[i>>>2&31]+r[i<<3&31]+"="),o}(e):t?function(e){for(var t,n,a,i,s,o="",l=e.length,u=0,c=5*parseInt(l/5);u>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[31&(n<<4|a>>>4)]+r[31&(a<<1|i>>>7)]+r[i>>>2&31]+r[31&(i<<3|s>>>5)]+r[31&s];var p=l-c;return 1===p?(t=e.charCodeAt(u),o+=r[t>>>3]+r[t<<2&31]+"======"):2===p?(t=e.charCodeAt(u++),n=e.charCodeAt(u),o+=r[t>>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[n<<4&31]+"===="):3===p?(t=e.charCodeAt(u++),n=e.charCodeAt(u++),a=e.charCodeAt(u),o+=r[t>>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[31&(n<<4|a>>>4)]+r[a<<1&31]+"==="):4===p&&(t=e.charCodeAt(u++),n=e.charCodeAt(u++),a=e.charCodeAt(u++),i=e.charCodeAt(u),o+=r[t>>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[31&(n<<4|a>>>4)]+r[31&(a<<1|i>>>7)]+r[i>>>2&31]+r[i<<3&31]+"="),o}(e):function(e){var t,n,a,s,o,l,u,c=!1,p="",d=0,m=0,h=e.length;if(""===e)return p;do{for(i[0]=i[5],i[1]=i[6],i[2]=i[7],u=m;d>6,i[u++]=128|63&l):l<55296||l>=57344?(i[u++]=224|l>>12,i[u++]=128|l>>6&63,i[u++]=128|63&l):(l=65536+((1023&l)<<10|1023&e.charCodeAt(++d)),i[u++]=240|l>>18,i[u++]=128|l>>12&63,i[u++]=128|l>>6&63,i[u++]=128|63&l);m=u-5,d===h&&++d,d>h&&u<6&&(c=!0),t=i[0],u>4?(n=i[1],a=i[2],s=i[3],o=i[4],p+=r[t>>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[31&(n<<4|a>>>4)]+r[31&(a<<1|s>>>7)]+r[s>>>2&31]+r[31&(s<<3|o>>>5)]+r[31&o]):1===u?p+=r[t>>>3]+r[t<<2&31]+"======":2===u?(n=i[1],p+=r[t>>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[n<<4&31]+"===="):3===u?(n=i[1],a=i[2],p+=r[t>>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[31&(n<<4|a>>>4)]+r[a<<1&31]+"==="):(n=i[1],a=i[2],s=i[3],p+=r[t>>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[31&(n<<4|a>>>4)]+r[31&(a<<1|s>>>7)]+r[s>>>2&31]+r[s<<3&31]+"=")}while(!c);return p}(e)},decode:l};l.asBytes=o,n?e.exports=u:t.base32=u}()}(base32$1);var base32=base32$1.exports;async function cidFromText(e){let t=(new TextEncoder).encode(e);return await cidFromArrayBuffer(t)}async function cidFromArrayBuffer(e){let t=await crypto.subtle.digest("SHA-256",e),n=new Uint8Array(36);return n.set([1,85,18,32]),n.set(new Uint8Array(t),4),"b"+base32.encode(n).toLowerCase().replace(/=+/,"")}const textByCid={};function retrieveTextFileForCid(e,t="doenet"){return void 0!==textByCid[e]?Promise.resolve(textByCid[e]):new Promise(((n,r)=>{let a,i,s=retrieveTextFileFromIPFS(e),o=s.promise,l=s.controller,u=!1,c=!1;o.then((t=>{clearTimeout(i),a&&!c&&a.abort(),textByCid[e]=t,n(t)})).catch((e=>{u=!0,c&&(clearTimeout(i),r(e))})),i=setTimeout((()=>{let s=retrieveTextFileFromServer(e,t),o=s.promise;a=s.controller,o.then((t=>{u||l.abort(),textByCid[e]=t,n(t)})).catch((e=>{c=!0,u?r(e):i=setTimeout((()=>{l.abort(),r(e)}),5e3)}))}),100)}))}function retrieveTextFileFromIPFS(e){let t=new AbortController,n=t.signal;return{promise:async function(){try{let t=await fetch(`https://${e}.ipfs.dweb.link/`,{signal:n});if(t.ok){let n=await t.text();return await cidFromText(n)===e?n:Promise.reject(new Error("cid mismatch"))}return Promise.reject(new Error(`cid not found: ${e}`))}catch(t){return Promise.reject(new Error(`cid not found: ${e}`))}}(),controller:t}}function retrieveTextFileFromServer(e,t){let n=new AbortController,r=n.signal;return{promise:async function(){try{let n=await fetch(`/media/${e}.${t}`,{signal:r});if(n.ok){let t=await n.text(),r=await cidFromText(t);return r===e?t:(console.warn(`cid mismatch, ${e}, ${r}`),Promise.reject(new Error("cid mismatch")))}return Promise.reject(new Error(`cid not found: ${e}`))}catch(t){return Promise.reject(new Error(`cid not found: ${e}`))}}(),controller:n}}async function expandDoenetMLsToFullSerializedComponents({cids:e,doenetMLs:t,componentInfoObjects:n}){let r=[],a={};for(let e of t){let t=parseAndCompile(e);t=cleanIfHaveJustDocument(t),substituteDeprecations(t),temporarilyRenameSourceBackToTarget(t),correctComponentTypeCapitalization(t,n.componentTypeLowerCaseMapping),copyTargetOrFromURIAttributeCreatesCopyComponent(t,n.isCompositeComponent),createAttributesFromProps(t,n),breakUpTargetIntoPropsAndIndices(t,n),applyMacros(t,n),removeBlankStringChildren(t,n),decodeXMLEntities(t),applySugar({serializedComponents:t,componentInfoObjects:n}),r.push(t);let i=findContentCopies({serializedComponents:t});for(let e in i.cidComponents)void 0===a[e]&&(a[e]=[]),a[e].push(...i.cidComponents[e])}let i=Object.keys(a);if(i.length>0){let{newDoenetMLs:e,newCids:t}=await cidsToDoenetMLs(i);for(let[e,n]of i.entries())if(t[e]&&t[e].substring(0,n.length)!==n)return Promise.reject(new Error(`Requested cid ${n} but got back ${t[e]}!`));let r=i.length;for(let n=0;n"string"!=typeof e||e.trim())),r=1===t.length&&"object"==typeof t[0],a=e.doenetAttributes?.fromCopyFromURI;if(a||r)if(a&&!r)console.warn("ignoring copyFromURI as it was not a single component");else{let n=t[0];n.attributes||(n.attributes={}),e.doenetAttributes||(e.doenetAttributes={}),e.doenetAttributes.keptNewNamespaceOfLastChild=Boolean(n.attributes.newNamespace?.primitive),n.attributes.newNamespace={primitive:!0},e.children=[n,...e.children],e.doenetAttributes.nameFirstChildIndependently=!0}else{let t={componentType:"externalContent",children:JSON.parse(JSON.stringify(n)),attributes:{newNamespace:{primitive:!0}},doenetAttributes:{createUniqueName:!0}};e.children=[t,...e.children]}}}}return{cids:e,fullSerializedComponents:r}}function cidsToDoenetMLs(e){let t=[],n=e;for(let n of e)t.push(retrieveTextFileForCid(n,"doenet"));return Promise.all(t).then((e=>Promise.resolve({newDoenetMLs:e,newCids:n}))).catch((e=>{let t;return t=1===n.length?`Could not retrieve cid ${n[0]}`:`Could not retrieve cids ${n.join(",")}`,t+=": "+e.message,console.error(t),Promise.reject(new Error(t))}))}function removeBlankStringChildren(e,t){for(let n of e){if(n.children){let e=t.allComponentClasses[n.componentType];e&&!e.includeBlankStringChildren&&(n.children=n.children.filter((e=>"string"!=typeof e||""!==e.trim()))),removeBlankStringChildren(n.children,t)}for(let e in n.attributes){let r=n.attributes[e].component;r&&r.children&&removeBlankStringChildren([r],t)}}}function findContentCopies({serializedComponents:e}){let t={};for(let n of e)if("copy"===n.componentType){if(n.attributes&&n.attributes.uri){let e=n.attributes.uri.primitive;if(e&&"doenet:"===e.substring(0,7).toLowerCase()){let r=e.match(/[:&]cid=([^&]+)/i);if(r){let e=r[1];void 0===t[e]&&(t[e]=[]),t[e].push(n)}}}}else if(void 0!==n.children){let e=findContentCopies({serializedComponents:n.children});for(let n in e.cidComponents)void 0===t[n]&&(t[n]=[]),t[n].push(...e.cidComponents[n])}return{cidComponents:t}}function addDocumentIfItsMissing(e){if(1!==e.length||"document"!==e[0].componentType){let t=e.splice(0);e.push({componentType:"document",children:t})}}function substituteDeprecations(e){let t={tname:"target",triggerwithtnames:"triggerWith",updatewithtname:"updateWith",paginatortname:"paginator",randomizeorder:"shuffleOrder",copytarget:"copySource",triggerwithtargets:"triggerWith",triggerwhentargetsclicked:"triggerWhenObjectsClicked",fortarget:"forObject",targetattributestoignore:"sourceAttributesToIgnore",targetattributestoignorerecursively:"sourceAttributesToIgnoreRecursively",targetsareresponses:"sourcesAreResponses",updatewithtarget:"updateWith",targetsarefunctionsymbols:"sourcesAreFunctionSymbols",selectforvariantnames:"selectForVariants"},n={copy:{target:"source",tname:"source"},collect:{target:"source",tname:"source"},summarystatistics:{target:"source"}};for(let r of e)if("object"==typeof r){if(r.props){let e=r.componentType,a=n[e.toLowerCase()];a||(a={});let i=!0;for(;i;){i=!1;for(let n in r.props){let s=n.toLowerCase();if(s in a){let t=a[s];console.warn(`Attribute ${n} of component type ${e} is deprecated. Use ${t} instead.`),r.props[t]=r.props[n],delete r.props[n],i=!0;break}if(s in t){let e=t[s];console.warn(`Attribute ${n} is deprecated. Use ${e} instead.`),r.props[e]=r.props[n],delete r.props[n],i=!0;break}}}}r.children&&substituteDeprecations(r.children)}}function temporarilyRenameSourceBackToTarget(e){let t={copysource:"copyTarget"},n={copy:{source:"target"},collect:{source:"target"}};for(let r of e)if("object"==typeof r){if(r.props){let e=n[r.componentType.toLowerCase()];e||(e={});let a=!0;for(;a;){a=!1;for(let n in r.props){let i=n.toLowerCase();if(i in e){let t=e[i];r.props[t]=r.props[n],delete r.props[n],a=!0;break}if(i in t){let e=t[i];r.props[e]=r.props[n],delete r.props[n],a=!0;break}}}}r.children&&temporarilyRenameSourceBackToTarget(r.children)}}function cleanIfHaveJustDocument(e){let t=e.filter((e=>"string"!=typeof e||""!==e.trim()));return 1===t.length&&"document"===t[0].componentType?t:e}function correctComponentTypeCapitalization(e,t){for(let n of e){if("object"!=typeof n)continue;let e=t[n.componentType.toLowerCase()];if(!e)throw Error(`Invalid component type${indexRangeString(n)}: ${n.componentType}`);n.componentType=e,n.children&&correctComponentTypeCapitalization(n.children,t)}}function copyTargetOrFromURIAttributeCreatesCopyComponent(e,t){for(let n of e){if(n.props){let e=!1,r=!1,a=!1,i=n.componentType,s=t({componentType:i,includeNonStandard:!1}),o=t({componentType:i,includeNonStandard:!0});for(let t of Object.keys(n.props)){let l=t.toLowerCase();if("copytarget"===l){if(e)throw Error(`Cannot repeat attribute ${t}. Found in component type ${i}${indexRangeString(n)}`);if(r)throw Error(`Cannot combine copyTarget and copyFromURI attribiutes. For in component of type ${i}${indexRangeString(n)}`);if(a)throw o?Error(`A component of type ${i} cannot have both assignNames and copyTarget. Found${indexRangeString(n)}.`):Error(`Invalid attribute assignNames for component of type ${i}${indexRangeString(n)}`);if(e=!0,n.doenetAttributes||(n.doenetAttributes={}),s||(n.props.createComponentOfType=i,n.doenetAttributes.nameBecomesAssignNames=!0),n.componentType="copy",n.props.target=n.props[t],"string"!=typeof n.props.target)throw Error(`Must specify value for copyTarget. Found in component of type ${i}${indexRangeString(n)}`);delete n.props[t],n.doenetAttributes.fromCopyTarget=!0,n.doenetAttributes.createNameFromComponentType=i,n.props.assignNamesSkip="1"}else if("copyfromuri"===l){if(r)throw Error(`Cannot repeat attribute ${t}. Found in component type ${i}${indexRangeString(n)}`);if(e)throw Error(`Cannot combine copyTarget and copyFromURI attribiutes. For in component of type ${i}${indexRangeString(n)}`);if(a)throw o?Error(`A component of type ${i} cannot have both assignNames and copyFromURI. Found${indexRangeString(n)}.`):Error(`Invalid attribute assignNames for component of type ${i}${indexRangeString(n)}`);if(r=!0,n.doenetAttributes||(n.doenetAttributes={}),s||(n.props.createComponentOfType=i,n.doenetAttributes.nameBecomesAssignNames=!0),n.componentType="copy",n.props.uri=n.props[t],"string"!=typeof n.props.uri)throw Error(`Must specify value for copyFromURI. Found in component of type ${i}${indexRangeString(n)}`);delete n.props[t],n.doenetAttributes.fromCopyFromURI=!0,n.doenetAttributes.createNameFromComponentType=i,n.props.assignNamesSkip="1"}else if("assignnames"===l&&!s){if(e||r)throw o?Error(`A component of type ${i} cannot have both assignNames and copyTarget. Found${indexRangeString(n)}.`):Error(`Invalid attribute assignNames for component of type ${i}${indexRangeString(n)}`);a=!0}}if(e){for(let e of Object.keys(n.props)){if("prop"===e.toLowerCase())throw Error(`Invalid attribute prop for component of type ${i}${indexRangeString(n)}`)}let e=!1;for(let t of Object.keys(n.props)){if("copyprop"===t.toLowerCase()){if(e)throw Error(`Cannot repeat attribute ${t}. Found in component type ${i}${indexRangeString(n)}`);n.props.prop=n.props[t],delete n.props[t],e=!0}}}}n.children&©TargetOrFromURIAttributeCreatesCopyComponent(n.children,t)}}function breakUpTargetIntoPropsAndIndices(e,t,n=""){for(let[r,a]of e.entries()){if(a.props&&["copy","updateValue","animateFromSequence"].includes(a.componentType)){let i,s,o,l,u,c,p;for(let e of Object.keys(a.props)){if("target"===e.toLowerCase()){if(i)throw Error(`Cannot repeat attribute ${e}. Found in component type ${a.componentType}${indexRangeString(a)}`);i=e,p=a.props[e];let t=buildSourcePieces(p,!0);t.success&&t.matchLength===p.length&&(s=t.sourceName,o=t.componentIndex,l=t.componentAttributes,u=t.propArray,c=t.subNames)}}if(i&&s)if(o||l||u.length>0){if(a.attributes.prop)throw Error(`Cannot combine the prop attribute with an extended source attribute. Found in component type ${a.componentType}${indexRangeString(a)}`);if(a.attributes.propIndex)throw Error(`Cannot combine the propIndex attribute with an extended source attribute. Found in component type ${a.componentType}${indexRangeString(a)}`);if(a.attributes.componentIndex)throw Error(`Cannot combine the componentIndex attribute with an extended source attribute. Found in component type ${a.componentType}${indexRangeString(a)}`);let d=createComponentFromExtendedSource({sourceName:s,componentIndex:o,subNames:c,componentAttributes:l,propArray:u,componentInfoObjects:t});if(d.success){let t=d.newComponent;if("copy"===a.componentType)delete a.props[i],Object.assign(a.attributes,t.attributes),a.doenetAttributes||(a.doenetAttributes={}),Object.assign(a.doenetAttributes,t.doenetAttributes),a.doenetAttributes.createNameFromComponentType||(a.doenetAttributes.createNameFromComponentType=a.componentType),a.componentType=t.componentType,0!==u.length||a.attributes.prop||a.attributes.propIndex||(a.doenetAttributes.isPlainCopy=!0),t.children&&(a.children=t.children);else if("copy"===t.componentType)delete a.props[i],Object.assign(a.attributes,t.attributes),a.doenetAttributes||(a.doenetAttributes={}),Object.assign(a.doenetAttributes,t.doenetAttributes);else{let s=createUniqueName("extract","fromExtendedSource"+n+"|"+r);t.doenetAttributes.prescribedName=s,t.doenetAttributes.createdFromMacro=!0;let o={componentType:"setup",children:[t],doenetAttributes:{createdFromMacro:!0}};e.push(o),delete a.props[i],a.doenetAttributes||(a.doenetAttributes={}),a.doenetAttributes.target=s,a.doenetAttributes.allowDoubleUnderscoreTarget=!0}}else"copy"===a.componentType?console.warn(`invalid copy source: ${p}`):console.warn(`invalid target: ${p}`)}else"copy"!==a.componentType||a.attributes.prop||a.attributes.propIndex||(a.doenetAttributes||(a.doenetAttributes={}),a.doenetAttributes.isPlainCopy=!0)}a.children&&breakUpTargetIntoPropsAndIndices(a.children,t,n+"|"+r)}}function createAttributesFromProps(e,t){for(let n of e){if("object"!=typeof n)continue;let e=t.allComponentClasses[n.componentType],r=e.createAttributesObject(),a={};for(let e in r)a[e.toLowerCase()]=e;let i={},s=Object.assign({},n.props);if(n.props)for(let o in n.props){let l=a[o.toLowerCase()],u=r[l];if(u){if(l in i)throw Error(`Cannot repeat attribute ${l}. Found in component type ${n.componentType}${indexRangeString(n)}`);i[l]=componentFromAttribute({attrObj:u,value:n.props[o],originalComponentProps:s,componentInfoObjects:t}),delete n.props[o]}else if(!["name","assignnames","target"].includes(o.toLowerCase())){if(!e.acceptAnyAttribute)throw Error(`Invalid attribute ${o} for component of type ${n.componentType}${indexRangeString(n)}`);i[o]=componentFromAttribute({value:n.props[o],originalComponentProps:s,componentInfoObjects:t}),delete n.props[o]}}for(let e in r){let n=r[e];n.createPrimitiveOfType&&"defaultPrimitiveValue"in n&&!(e in i)&&(i[e]=componentFromAttribute({attrObj:n,originalComponentProps:s,value:n.defaultPrimitiveValue.toString(),componentInfoObjects:t}))}n.attributes=i,void 0!==n.children&&createAttributesFromProps(n.children,t)}}function componentFromAttribute({attrObj:e,value:t,originalComponentProps:n,componentInfoObjects:r}){if("object"!=typeof t?t={rawString:t.toString()}:null===t&&(t={rawString:""}),e&&e.createComponentOfType){let a,i=t.rawString.trim().toLowerCase();if("true"===i&&void 0!==e.valueForTrue)a={componentType:e.createComponentOfType,state:{value:e.valueForTrue}};else if("false"===i&&void 0!==e.valueForFalse)a={componentType:e.createComponentOfType,state:{value:e.valueForFalse}};else if(r.isInheritedComponentType({inheritedComponentType:e.createComponentOfType,baseComponentType:"boolean"})&&["true","false"].includes(i))a={componentType:e.createComponentOfType,state:{value:"true"===i}};else{let n=t.childrenForComponent;n=n?JSON.parse(JSON.stringify(n)):[t.rawString],a={componentType:e.createComponentOfType,children:n},removeBlankStringChildren([a],r)}if(e.attributesForCreatedComponent||e.copyComponentAttributesForCreatedComponent){if(e.attributesForCreatedComponent?a.props=e.attributesForCreatedComponent:a.props={},e.copyComponentAttributesForCreatedComponent)for(let t of e.copyComponentAttributesForCreatedComponent)n[t]&&(a.props[t]=JSON.parse(JSON.stringify(n[t])));createAttributesFromProps([a],r)}let s={component:a};return e.ignoreFixed&&(s.ignoreFixed=!0),s}if(e&&e.createPrimitiveOfType){let n;if("boolean"===e.createPrimitiveOfType){n="true"===t.rawString.trim().toLowerCase()}else n="number"===e.createPrimitiveOfType?Number(t.rawString):"integer"===e.createPrimitiveOfType?Math.round(Number(t.rawString)):"stringArray"===e.createPrimitiveOfType?t.rawString.trim().split(/\s+/):"numberArray"===e.createPrimitiveOfType?t.rawString.trim().split(/\s+/).map(Number):t.rawString;return e.validationFunction&&(n=e.validationFunction(n)),{primitive:n}}if(e&&e.createTargetComponentNames){return{targetComponentNames:t.rawString.trim().split(/\s+/).map((e=>("$"===e[0]&&"$"!==e[1]&&"("===(e=e.slice(1))[0]&&")"===e[e.length-1]&&(e=e.slice(1,e.length-1)),{relativeName:e})))}}return t.childrenForComponent||(t.childrenForComponent=[t.rawString]),t}function findPreSugarIndsAndMarkFromSugar(e){let t=[];for(let n of e)if("object"==typeof n)if(void 0!==n.preSugarInd)t.push(n.preSugarInd);else if(n.doenetAttributes||(n.doenetAttributes={}),n.doenetAttributes.createdFromSugar=!0,n.children){let e=findPreSugarIndsAndMarkFromSugar(n.children);t.push(...e)}return t}function applyMacros(e,t){for(let n of e)if(n.children&&applyMacros(n.children,t),n.attributes)for(let e in n.attributes){let r=n.attributes[e];r.component?applyMacros([r.component],t):r.childrenForComponent&&applyMacros(r.childrenForComponent,t)}substituteMacros(e,t)}function substituteMacros(e,t){for(let n=0;n0&&e[n-1].range){let t=e[n-1].range;t.closeEnd?r+=t.closeEnd:t.selfCloseEnd&&(r+=t.selfCloseBegin)}throw Error(`${d.message}. At indices ${r}-${r+c}. Found: ${t}`)}l=d.newComponent,markCreatedFromMacro([l]),0===s.propArray.length&&(l.doenetAttributes.isPlainMacro=!0),o=[l];let m=1,h=i.substring(u+c);if(2===p){let r=i.slice(u+c).match(/^\s*\(/);if(!r){a=u+2;continue}let s=c+r[0].length,l=[],p=!1;i.length>u+s&&(p=!0,l.push(i.substring(u+s))),l.push(...e.slice(n+1));let d=createEvaluateIfFindMatchedClosingParens({componentsFromMacro:o,remainingComponents:l,includeFirstInRemaining:p,componentInfoObjects:t});if(!d.success){a=u+2;continue}o=d.componentsFromMacro,m=d.lastComponentIndMatched+1,p||m++,h=""}let f=[];u>0&&f.push(i.substring(0,u)),f.push(...o),h.length>0&&f.push(h),e.splice(n,m,...f),u>0&&n++;break}}}}function createComponentFromExtendedSource({sourceName:e,componentIndex:t,componentAttributes:n,propArray:r,subNames:a,componentInfoObjects:i}){let s={componentType:"copy",doenetAttributes:{target:e},attributes:{}};if(t){let e=[t];applyMacros(e,i),s.attributes.componentIndex={component:{componentType:"integer",children:e}}}if(a?.length>0){let e=[],t=[];for(let n of a)e.push(n.subName),void 0!==n.subNameComponentIndex&&(t.length0){let e=[t.join(" ")];applyMacros(e,i),s.attributes.sourceSubnamesComponentIndex={component:{componentType:"numberList",children:e}}}}let o=!1;if(n){o=!0;let e=createAttributesFromString(n,i);if(!e.success)return e;Object.assign(s.attributes,e.newAttributes),e.assignNames&&(s.props={assignNames:e.assignNames})}for(let e of r){if(o&&(s.doenetAttributes.createdFromMacro=!0,s={componentType:"extract",attributes:{},doenetAttributes:{},children:[s]}),s.attributes.prop={primitive:e.prop},e.propIndex){let t=[e.propIndex.join(" ")];applyMacros(t,i),s.attributes.propIndex={component:{componentType:"numberList",children:t}}}if(e.attributes){let t=createAttributesFromString(e.attributes,i);if(!t.success)return t;Object.assign(s.attributes,t.newAttributes),t.assignNames&&(s.props={assignNames:t.assignNames})}o=!0}return{success:!0,newComponent:s}}function createAttributesFromString(e,t){let n,r=``;try{n=parseAndCompile(r)}catch(e){return{success:!1,message:"Error in macro"}}createAttributesFromProps(n,t),markCreatedFromMacro(n),applyMacros(n,t);let a,i=n[0].attributes;if(i.prop||i.propIndex||i.componentIndex)return{success:!1,message:"Error in macro: macro cannot directly add attributes prop, propIndex, or componentIndex"};if(n[0].props)for(let e in n[0].props)if("assignnames"===e.toLowerCase()){if(a)return{success:!1,message:"Error in macro: cannot repeat assignNames"};a=n[0].props[e]}return{success:!0,newAttributes:i,assignNames:a}}function findFirstFullMacroInString(e){let t,n=0;for(;;){let r=e.substring(n).match(/(\$+)(.?)/);if(!r)return{success:!1};if(t=r[1].length,n+=r.index+t,t<=2){let r=!1,a=e.substring(n),i=0,s=findWordOrDelimitedGroup(a,r);"("===s.startDelim&&(r=!0,a=s.group,i=s.group.length);let o=buildSourcePieces(a,r);if(o.success){if(r){if(o.matchLength!==i)return{success:!1};o.matchLength+=2}return o.nDollarSigns=t,o.firstIndMatched=n-t,o.matchLength+=t,o}}}}function buildSourcePieces(e,t){let n=findWordOrDelimitedGroup(e,t),r=0;if(n.withPeriod||!n.word)return{success:!1};let a={sourceName:(n.withSlash?"/":"")+n.word};r+=n.matchLength,n=findWordOrDelimitedGroup(e=e.substring(n.matchLength),t),"["===n.startDelim&&(a.componentIndex=n.group,r+=n.matchLength,n=findWordOrDelimitedGroup(e=e.substring(n.matchLength),t));let i=[];for(;n.withSlash;){let a={subName:n.word};r+=n.matchLength,n=findWordOrDelimitedGroup(e=e.substring(n.matchLength),t),"["===n.startDelim&&(a.subNameComponentIndex=n.group,r+=n.matchLength,n=findWordOrDelimitedGroup(e=e.substring(n.matchLength),t)),i.push(a)}a.subNames=i,"{"===n.startDelim&&(a.componentAttributes=n.group,r+=n.matchLength,n=findWordOrDelimitedGroup(e=e.substring(n.matchLength),t));let s=[];for(;n.withPeriod;){let a={prop:n.word};r+=n.matchLength,n=findWordOrDelimitedGroup(e=e.substring(n.matchLength),t);let i=[];for(;"["===n.startDelim;)i.push(n.group),r+=n.matchLength,n=findWordOrDelimitedGroup(e=e.substring(n.matchLength),t);i.length>0&&(a.propIndex=i),"{"===n.startDelim&&(a.attributes=n.group,r+=n.matchLength,n=findWordOrDelimitedGroup(e=e.substring(n.matchLength),t)),s.push(a)}return a.propArray=s,a.matchLength=r,a.success=!0,a}function findWordOrDelimitedGroup(e,t=!1){let n,r=!1,a=!1;"."===e[0]&&"."!==e[1]&&(r=!0,e=e.substring(1)),t?r?n=/^[\w-]+/:("/"===e[0]&&e[1].match(/\w/)&&(a=!0,e=e.substring(1)),n=/^([\w\/-]|\.\.\/)+/):n=/^[a-zA-Z_]\w*/;let i=e.match(n);if(i)return{success:!0,withPeriod:r,withSlash:a,word:i[0],matchLength:i[0].length+(r?1:0)+(a?1:0)};if(r||a)return{success:!1};let s=[],o={"(":")","{":"}","[":"]"},l=Object.values(o),u=e[0],c=o[u];if(!c)return{success:!1};s.push(c);for(let t=1;t0?t[i]=s.substring(0,a.charInd):t=t.slice(0,i);let l=breakEmbeddedStringByCommas({childrenList:t});l.pieces.forEach((e=>applyMacros(e,r)));let u=l.pieces.map((e=>1===e.length&&"string"!=typeof e[0]?e[0]:{componentType:"math",doenetAttributes:{createdFromMacro:!0},children:e})),c=[{componentType:"evaluate",doenetAttributes:{createdFromMacro:!0},attributes:{function:{component:{componentType:"function",doenetAttributes:{createdFromMacro:!0},children:e}},input:{component:{componentType:"mathList",doenetAttributes:{createdFromMacro:!0},children:u}}}}];return o.length>0&&c.push(o),{success:!0,componentsFromMacro:c,lastComponentIndMatched:i}}function findFirstUnmatchedClosingParens(e){let t=0;for(let[n,r]of e.entries())if("string"==typeof r){let e=r;for(let r=0;r").replace(/</g,"<").replace(/$/g,"$").replace(/&/g,"&")}for(let[n,r]of e.entries())if("string"==typeof r)e[n]=t(r);else if(r.children&&decodeXMLEntities(r.children),r.attributes)for(let e in r.attributes){let n=r.attributes[e];n.component?decodeXMLEntities([n.component]):n.primitive?"string"==typeof n.primitive&&(n.primitive=t(n.primitive)):(n.childrenForComponent&&decodeXMLEntities(n.childrenForComponent),n.rawString&&(n.rawString=t(n.rawString)))}}function applySugar({serializedComponents:e,parentParametersFromSugar:t={},parentAttributes:n={},componentInfoObjects:r,parentUniqueId:a="",isAttributeComponent:i=!1}){for(let[s,o]of e.entries()){if("object"!=typeof o)continue;let e=o.componentType,l=r.allComponentClasses[e];if(!l)throw Error(`Unrecognized component type ${e}`);let u=a+"|"+e+s,c={};for(let e in o.attributes){let t=o.attributes[e];void 0!==t.primitive&&(c[e]=t.primitive)}if(o.children){let a={};if(!o.skipSugar)for(let[s,p]of l.returnSugarInstructions().entries()){let l=o.children.map((e=>"string"==typeof e?"s":"n")).join("");if(p.childrenRegex){let e=l.match(p.childrenRegex);if(!e||e[0].length!==o.children.length)continue}let d=deepClone(o.children),m=0;for(let e of d)"string"!=typeof e&&(e.preSugarInd=m,m++);let h=!1;o.doenetAttributes&&o.doenetAttributes.createdFromMacro&&(h=!0);let f=p.replacementFunction({matchedChildren:d,parentParametersFromSugar:t,parentAttributes:n,componentAttributes:c,uniqueId:u+"|sugar"+s,componentInfoObjects:r,isAttributeComponent:i,createdFromMacro:h});if(f.success){let t=f.newChildren,n=f.newAttributes,r=[],i=[];if(t&&(r=findPreSugarIndsAndMarkFromSugar(t)),n)for(let e in n){let t=n[e].component;t&&i.push(...findPreSugarIndsAndMarkFromSugar(t.children))}let s=[...r,...i];if(s.length!==m||!s.sort(((e,t)=>e-t)).every(((e,t)=>e===t)))throw Error(`Invalid sugar for ${e} as didn't return set of original components`);if(r.length>0){let t=[...r].sort(((e,t)=>e-t));if(!t.every(((e,t)=>e===r[t])))throw Error(`Invalid sugar for ${e} as didn't return original components in order`)}f.parametersForChildrenSugar&&Object.assign(a,f.parametersForChildrenSugar),o.children=t||[],n&&(o.attributes||(o.attributes={}),Object.assign(o.attributes,n))}}l.removeBlankStringChildrenPostSugar&&(o.children=o.children.filter((e=>"string"!=typeof e||/\S/.test(e)))),applySugar({serializedComponents:o.children,parentParametersFromSugar:a,parentAttributes:c,componentInfoObjects:r,parentUniqueId:u})}if(o.attributes)for(let e in o.attributes){let t=o.attributes[e];t.component&&applySugar({serializedComponents:[t.component],parentAttributes:c,componentInfoObjects:r,parentUniqueId:u,isAttributeComponent:!0})}}}function breakStringInPiecesBySpacesOrParens(e){if("string"!=typeof e)return{success:!1};let t=0,n=[];e=e.trim();let r=0;for(let a=0;a0&&n.push(t),r=a}t++}else if(")"===i){if(0===t)return{success:!1};if(1===t){let t=e.substring(r+1,a).trim();if(t.length>0){let e=breakStringInPiecesBySpacesOrParens(t);!0===e.success?n.push(e.pieces):n.push(t)}r=a+1}t--}else if(0===t&&i.match(/\s/)){let t=e.substring(r,a).trim();t.length>0&&n.push(t),r=a}}if(0!==t)return{success:!1};let a=e.substring(r,e.length).trim();return a.length>0&&n.push(a),{success:!0,pieces:n}}function countRegularComponentTypesInNamespace(e,t={}){for(let n of e)if("object"==typeof n){let e=n.componentType,r=t[e];void 0===r&&(r=0);let a=n.doenetAttributes;a?.isAttributeChild||a?.createdFromSugar||a?.createdFromMacro||(t[e]=++r),n.children&&!n.attributes?.newNamespace?.primitive&&(t=countRegularComponentTypesInNamespace(n.children,t))}return t}function renameAutonameBasedOnNewCounts(e,t={}){let n={...t};for(let t of e)if("object"==typeof t){let e=t.componentType,r=n[e];void 0===r&&(r=0);let a=t.doenetAttributes;if(!(a?.isAttributeChild||a?.createdFromSugar||a?.createdFromMacro)&&(n[e]=++r,t.componentName)){let n=t.componentName.lastIndexOf("/"),a=t.componentName.substring(n+1),i="_"+e.toLowerCase();a.substring(0,i.length)===i&&(t.componentName=t.componentName.substring(0,n+1)+i+r)}t.children&&!t.attributes?.newNamespace?.primitive&&(n=renameAutonameBasedOnNewCounts(t.children,n))}return n}function createComponentNames({serializedComponents:e,namespaceStack:t=[],componentInfoObjects:n,parentDoenetAttributes:r={},parentName:a,useOriginalNames:i=!1,attributesByTargetComponentName:s,indOffset:o=0,createNameContext:l="",initWithoutShadowingComposite:u=!1}){0===t.length&&t.push({namespace:"",componentCounts:{},namesUsed:{}});let c=t.length-1,p=t[c];for(let[r,d]of e.entries()){if("object"!=typeof d)continue;let e=d.componentType,m=n.allComponentClasses[e],h=d.doenetAttributes;void 0===h&&(h=d.doenetAttributes={});let f=d.attributes;f||(f=d.attributes={}),h.createNameFromComponentType&&(e=h.createNameFromComponentType);let y,g=h.prescribedName,b=h.assignNames,v=h.target,N=h.isAttributeChild||h.createdFromSugar||h.createdFromMacro||h.createUniqueName;(f.newNamespace?.primitive||i&&d.originalAttributes&&d.originalAttributes.newNamespace)&&(y=!0);let T=void 0!==g,C=d.props;if(void 0===C)C=d.props={};else for(let t in C){let n=t.toLowerCase();if("name"===n){if(void 0!==g)throw Error(`Cannot define name twice. Found in component of type ${e}${indexRangeString(d)}`);g=C[t],delete C[t]}else if("assignnames"===n){if(void 0!==b)throw Error(`Cannot define assignNames twice for a component. Found in component of type ${e}${indexRangeString(d)}`);{let n=breakStringInPiecesBySpacesOrParens(C[t]);if(!n.success)throw Error(`Invalid format for assignnames. Found in component of type ${e}${indexRangeString(d)}`);b=n.pieces,delete C[t]}}else if("target"===n){if(void 0!==v)throw Error(`Cannot define target twice for a component. Found in component of type ${e}${indexRangeString(d)}`);if("string"!=typeof C[t])throw Error(`Must specify value for target. Found in component of type ${e}${indexRangeString(d)}`);v=C[t].trim(),delete C[t]}}if(g){if(!T&&!h.createdFromSugar){if(!/[a-zA-Z]/.test(g.substring(0,1)))throw Error(`Invalid component name: ${g}. Component name must begin with a letter. Found in component of type ${e}${indexRangeString(d)}`);if(!/^[a-zA-Z0-9_\-]+$/.test(g))throw Error(`Invalid component name: ${g}. Component name can contain only letters, numbers, hyphens, and underscores. Found in component of type ${e}${indexRangeString(d)}`)}h.prescribedName=g}else if(N){let t=a+"|createUniqueName|";d.downstreamDependencies?t+=JSON.stringify(d.downstreamDependencies):t+=r+"|"+o+"|"+l,g=createUniqueName(e.toLowerCase(),t)}if(!b&&i&&d.originalDoenetAttributes&&d.originalDoenetAttributes.assignNames&&(b=d.originalDoenetAttributes.assignNames),b){if(!m.assignNamesToReplacements)throw Error(`Cannot assign names for component type ${e}${indexRangeString(d)}`);if(h.assignNames=b,!h.createUniqueAssignNames){let t=flattenDeep(b);if(!h.fromCopyTarget&&!h.fromCopyFromURI)for(let n of t){if(!/[a-zA-Z]/.test(n.substring(0,1)))throw Error(`All assigned names must begin with a letter. Found in component of type ${e}${indexRangeString(d)}`);if(!/^[a-zA-Z0-9_\-]+$/.test(n))throw Error(`Assigned names can contain only letters, numbers, hyphens, and underscores. Found in component of type ${e}${indexRangeString(d)}`)}if(t.length!==new Set(t).size)throw Error(`Duplicate assigned names. Found in component of type ${e}${indexRangeString(d)}`)}}y&&(f.newNamespace={primitive:y});let A=p.componentCounts[e];void 0===A&&(A=0),h.isAttributeChild||h.createdFromSugar||h.createdFromMacro||(p.componentCounts[e]=++A);let V="";for(let e=0;e<=c;e++)V+=t[e].namespace+"/";if(!g){if(i&&d.originalName){let e=d.originalName.lastIndexOf("/");g=d.originalName.substring(e+1)}g||(g="_"+e.toLowerCase()+A)}if(h.nameBecomesAssignNames){y&&(f.assignNewNamespaces={primitive:!0},delete f.newNamespace,y=!1),b=h.assignNames=[g],delete h.nameBecomesAssignNames;let e=a+"|createUniqueName|";h.createUniqueName=!0,delete h.prescribedName,d.downstreamDependencies?e+=JSON.stringify(d.downstreamDependencies):e+=r+"|"+o+"|"+l,g=createUniqueName("copy",e)}if(V+=g,d.componentName=V,g){if(g in p.namesUsed)throw Error(`Duplicate component name ${V}. Found in component of type ${e}${indexRangeString(d)}`);p.namesUsed[g]=!0}if(!y&&b)for(let t of flattenDeep(b)){if(t in p.namesUsed)throw Error(`Duplicate component name ${t} (from assignNames of ${V}). Found in component of type ${e}${indexRangeString(d)}`);p.namesUsed[t]=!0}if(d.doenetAttributes.createUniqueAssignNames&&d.originalName){let e=d.doenetAttributes.assignNames;e||(e=d.doenetAttributes.originalAssignNames);let n,r=V+"|createUniqueName|assignNames|",a="";if(y)a=V+"/",n=d.originalName+"/";else{for(let e=0;e<=c;e++)a+=t[e].namespace+"/";let e=d.originalName.lastIndexOf("/");n=d.originalName.slice(0,e+1)}let i=createNewAssignNamesAndrenameMatchingTargetNames({originalAssignNames:e,longNameIdBase:r,namespace:a,oldNamespace:n,attributesByTargetComponentName:s});b=d.doenetAttributes.assignNames=i}if(renameMatchingTargetNames(d,s),v){if(!m.acceptTarget)throw Error(`Component type ${e} does not accept a target attribute. Found in component ${V}${indexRangeString(d)}`);if(v.includes("|"))throw Error(`target cannot include |. Found in component of type ${e}${indexRangeString(d)}`);h.target=v,h.targetComponentName=convertComponentTarget({relativeName:v,oldAbsoluteName:h.targetComponentName,namespaceStack:t,acceptDoubleUnderscore:h.createdFromSugar||h.allowDoubleUnderscoreTarget})}for(let e in f){let n=f[e];if(n.targetComponentNames)for(let e of n.targetComponentNames)e.absoluteName=convertComponentTarget({relativeName:e.relativeName,oldAbsoluteName:e.absoluteName,namespaceStack:t,acceptDoubleUnderscore:h.createdFromSugar||h.allowDoubleUnderscoreTarget})}if(d.children)if(y||f.assignNewNamespaces?.primitive){let e={};b&&flattenDeep(b).forEach((t=>e[t]=!0));let r=d.children;if(h.nameFirstChildIndependently&&d.children.length>0){r=r.slice(1);let e={namespace:g,componentCounts:{},namesUsed:{}};t.push(e),createComponentNames({serializedComponents:[d.children[0]],namespaceStack:t,componentInfoObjects:n,parentDoenetAttributes:h,parentName:V,useOriginalNames:i,attributesByTargetComponentName:s}),t.pop()}let a={namespace:g,componentCounts:{},namesUsed:e};if(h.haveNewNamespaceOnlyFromShadow){let e=!0,o=[...r];for(;o.length>0;){let r=[];for(let t of o){if(Boolean(t.doenetAttributes?.ignoreParentNewNamespace)===e)break;r.push(t)}o.splice(0,r.length),e?t.push(a):u&&r.forEach((e=>e.doenetAttributes.createUniqueName=!0)),createComponentNames({serializedComponents:r,namespaceStack:t,componentInfoObjects:n,parentDoenetAttributes:h,parentName:V,useOriginalNames:i,attributesByTargetComponentName:s}),e&&t.pop(),e=!e}}else t.push(a),createComponentNames({serializedComponents:r,namespaceStack:t,componentInfoObjects:n,parentDoenetAttributes:h,parentName:V,useOriginalNames:i,attributesByTargetComponentName:s}),t.pop()}else{let e=d.children;if(h.nameFirstChildIndependently&&e.length>0){e=e.slice(1);let r=p.namesUsed,a=p.componentCounts;p.namesUsed={},p.componentCounts={},createComponentNames({serializedComponents:[d.children[0]],namespaceStack:t,componentInfoObjects:n,parentDoenetAttributes:h,parentName:V,useOriginalNames:i,attributesByTargetComponentName:s}),p.namesUsed=r,p.componentCounts=a}createComponentNames({serializedComponents:e,namespaceStack:t,componentInfoObjects:n,parentDoenetAttributes:h,parentName:V,useOriginalNames:i,attributesByTargetComponentName:s})}if(d.attributes)for(let e in d.attributes){let r=d.attributes[e];if(r.component){let a=r.component;a.doenetAttributes||(a.doenetAttributes={}),a.doenetAttributes.isAttributeChild=!0,r.ignoreFixed&&(a.doenetAttributes.ignoreParentFixed=!0),createComponentNames({serializedComponents:[a],namespaceStack:t,componentInfoObjects:n,parentDoenetAttributes:h,parentName:V,useOriginalNames:i,attributesByTargetComponentName:s,createNameContext:e})}else r.childrenForComponent&&createComponentNames({serializedComponents:r.childrenForComponent,namespaceStack:t,componentInfoObjects:n,parentDoenetAttributes:h,parentName:V,useOriginalNames:i,attributesByTargetComponentName:s,createNameContext:e})}}return e}function createNewAssignNamesAndrenameMatchingTargetNames({originalAssignNames:e,longNameIdBase:t,namespace:n,oldNamespace:r,attributesByTargetComponentName:a}){let i=[];for(let[s,o]of e.entries())if(Array.isArray(o)){let e=createNewAssignNamesAndrenameMatchingTargetNames({originalAssignNames:o,longNameIdBase:t+s+"_",namespace:n,oldNamespace:r,attributesByTargetComponentName:a});i.push(e)}else{let e=createUniqueName("fromAssignNames",t+s);i.push(e),renameMatchingTargetNames({componentName:n+e,originalName:r+o},a,!0)}return i}function convertComponentTarget({relativeName:e,oldAbsoluteName:t,namespaceStack:n,acceptDoubleUnderscore:r}){if(!t&&/__/.test(e)&&!r)throw Error("Invalid reference target: "+e);let a;if("/"===e.substring(0,1))a=e;else{let t=n.length-1;for(;"../"===e.substring(0,3);)e=e.substring(3),t--;t<0&&(t=0),a="";for(let e=0;e<=t;e++)a+=n[e].namespace+"/";a+=e}return a}function serializedComponentsReplacer(e,t){return t!=t?{objectType:"special-numeric",stringValue:"NaN"}:t===1/0?{objectType:"special-numeric",stringValue:"Infinity"}:t===-1/0?{objectType:"special-numeric",stringValue:"-Infinity"}:t}let nanInfinityReviver=function(e,t){if(t&&"special-numeric"===t.objectType){if("NaN"===t.stringValue)return NaN;if("Infinity"===t.stringValue)return 1/0;if("-Infinity"===t.stringValue)return-1/0}return t};function serializedComponentsReviver(e,t){return me$3.reviver(e,theModule.Subset.reviver(e,nanInfinityReviver(e,t)))}function processAssignNames({assignNames:e=[],assignNewNamespaces:t=!1,serializedComponents:n,parentName:r,parentCreatesNewNamespace:a,componentInfoObjects:i,indOffset:s=0,originalNamesAreConsistent:o=!1,shadowingComposite:l=!1}){let u=n.length;moveComponentNamesToOriginalNames(n);let c={},p=null;if(o){if(u>0){let e=n.filter((e=>"object"==typeof e))[0];if(e&&e.originalName){let t=e.originalName.lastIndexOf("/");p=e.originalName.substring(0,t)}}if(null!==p)for(let e of n)setTargetsOutsideNamespaceToAbsoluteAndRecordAllTargetComponentNames({namespace:p,components:[e],attributesByTargetComponentName:c})}else for(let e=0;e0&&t.originalName){let e=t.originalName.lastIndexOf("/");p=t.originalName.substring(0,e)}null!==p&&setTargetsOutsideNamespaceToAbsoluteAndRecordAllTargetComponentNames({namespace:p,components:[t],attributesByTargetComponentName:c})}}let d=[],m=0;for(let h=0;h0&&y.originalName)){let e=y.originalName.lastIndexOf("/");p=y.originalName.substring(0,e)}if(g)if(i.allComponentClasses[y.componentType].assignNamesSkipOver)g=[g];else if(y.attributes?.assignNamesSkip){let e=y.attributes.assignNamesSkip.primitive;if(e>0)for(let t=0;t({namespace:e,componentCounts:{},namesUsed:{}})));"/"!==e[0]&&c.splice(0,0,{componentCounts:{},namesUsed:{},namespace:""}),t.doenetAttributes||(t.doenetAttributes={}),t.attributes||(t.attributes={}),t.attributes.newNamespace?.primitive||s?u=!0:(u=!1,t.children&&markToCreateAllUniqueNames(t.children));for(let e in t.attributes){let n=t.attributes[e];n.component?markToCreateAllUniqueNames([n.component]):n.childrenForComponent&&markToCreateAllUniqueNames(n.childrenForComponent)}createComponentNames({serializedComponents:[t],namespaceStack:c,componentInfoObjects:a,parentName:e,useOriginalNames:u,attributesByTargetComponentName:i,indOffset:n,initWithoutShadowingComposite:!o})}function setTargetsOutsideNamespaceToAbsoluteAndRecordAllTargetComponentNames({namespace:e,components:t,attributesByTargetComponentName:n}){let r=e.length;for(let a of t)if("object"==typeof a){if(a.doenetAttributes&&a.doenetAttributes.target){let t=a.doenetAttributes.targetComponentName;void 0!==t&&(t.substring(0,r)!==e&&(a.doenetAttributes.target=t),n[t]||(n[t]=[]),n[t].push(a.doenetAttributes))}for(let t in a.attributes){let i=a.attributes[t];if(i.targetComponentNames)for(let t of i.targetComponentNames){let a=t.absoluteName;void 0!==a&&(a.substring(0,r)!==e&&(t.relativeName=a),n[a]||(n[a]=[]),n[a].push(t))}}if(a.children&&setTargetsOutsideNamespaceToAbsoluteAndRecordAllTargetComponentNames({namespace:e,components:a.children,attributesByTargetComponentName:n}),a.attributes)for(let t in a.attributes){let r=a.attributes[t];r.component?setTargetsOutsideNamespaceToAbsoluteAndRecordAllTargetComponentNames({namespace:e,components:[r.component],attributesByTargetComponentName:n}):r.childrenForComponent&&setTargetsOutsideNamespaceToAbsoluteAndRecordAllTargetComponentNames({namespace:e,components:r.childrenForComponent,attributesByTargetComponentName:n})}}}function renameMatchingTargetNames(e,t,n=!1){if(e.originalName&&t&&e.componentName!==e.originalName){if(t[e.originalName])for(let n of t[e.originalName])n.relativeName?(n.relativeName=e.componentName,n.absoluteName=e.componentName):(n.target=e.componentName,n.targetComponentName=e.componentName);if(n){let n=e.originalName+"/",r=n.length;for(let a in t)if(a.substring(0,r)===n){let n=a.substring(r);for(let r of t[a])r.relativeName?(r.relativeName=e.componentName+"/"+n,r.absoluteName=e.componentName+"/"+n):(r.target=e.componentName+"/"+n,r.targetComponentName=e.componentName+"/"+n)}}}}function moveComponentNamesToOriginalNames(e){for(let t of e)if(t.componentName&&(t.originalName=t.componentName,delete t.componentName),t.children&&moveComponentNamesToOriginalNames(t.children),t.attributes)for(let e in t.attributes){let n=t.attributes[e];n.component?moveComponentNamesToOriginalNames([n.component]):n.childrenForComponent&&moveComponentNamesToOriginalNames(n.childrenForComponent)}}function markToCreateAllUniqueNames(e){for(let t of e)if("object"==typeof t&&(t.doenetAttributes||(t.doenetAttributes={}),t.doenetAttributes.createUniqueName=!0,delete t.doenetAttributes.prescribedName,t.attributes?.newNamespace?.primitive||(t.doenetAttributes.assignNames?(t.doenetAttributes.createUniqueAssignNames=!0,t.doenetAttributes.originalAssignNames=t.doenetAttributes.assignNames,delete t.doenetAttributes.assignNames):t.originalDoenetAttributes&&t.originalDoenetAttributes.assignNames&&(t.doenetAttributes.createUniqueAssignNames=!0,t.doenetAttributes.originalAssignNames=t.originalDoenetAttributes.assignNames),t.children&&markToCreateAllUniqueNames(t.children)),t.attributes))for(let e in t.attributes){let n=t.attributes[e];n.component?markToCreateAllUniqueNames([n.component]):n.childrenForComponent&&markToCreateAllUniqueNames(n.childrenForComponent)}}function setTNamesToAbsolute(e){for(let t of e){if(t.doenetAttributes&&t.doenetAttributes.target){let e=t.doenetAttributes.targetComponentName;void 0!==e&&(t.doenetAttributes.target=e)}if(t.children&&setTNamesToAbsolute(t.children),t.attributes)for(let e in t.attributes){let n=t.attributes[e];n.component?setTNamesToAbsolute([n.component]):n.childrenForComponent&&setTNamesToAbsolute(n.childrenForComponent)}}}function restrictTNamesToNamespace({components:e,namespace:t,parentNamespace:n,parentIsCopy:r=!1,invalidateReferencesToBaseNamespace:a=!1}){void 0===n&&(n=t);let i=t.length;for(let s of e){if(s.doenetAttributes&&s.doenetAttributes.target){let e=s.doenetAttributes.target;if("/"===e[0]){if(e.substring(0,i)!==t){let n=t.split("/").slice(1),r=e.split("/").slice(1),a=!1,i=t+e.slice(1);for(;n.length>0&&n[0]===r[0];)n=n.slice(1),r=r.slice(1),a=!0;if(a)i=t+r.join("/");else{let n=t.split("/").slice(1);for(let t=1;tn){r&&t<=n&&a.push({begin:t,end:n,componentName:r}),s=!0;break}r&&o.indBegin>t&&a.push({begin:t,end:o.indBegin-1,componentName:r});let l=extractRangeIndexPieces({componentArray:e.slice(i+1),lastInd:o.indBegin,stopInd:o.indEnd,enclosingComponentName:o.componentName});i+=l.componentsConsumed+1,a.push(...l.rangePieces),t=o.indEnd+1}return!s&&Number.isFinite(n)&&n>=t&&a.push({begin:t,end:n,componentName:r}),{componentsConsumed:i,rangePieces:a}}function createStateProxyHandler(){return{get:function(e,t){let n=e[t];return void 0!==n&&(n=n.isArray&&(n.public||n.trackChanges)?new Proxy(n.value,createArrayProxyHandler({variable:t,nDimensions:n.nDimensions})):n.value),n},set:function(e,t,n){throw Error("Property "+t+" is read-only")},deleteProperty:function(e,t){throw Error("Property "+t+" is read-only")}}}function createArrayProxyHandler({variable:e,nDimensions:t,indicesSoFar:n=[]}){return{variable:e,nDimensions:t,indicesSoFar:n,get:function(e,n){if("then"===n&&e instanceof Promise)return t=>e.then.bind(e)((e=>t(null!==e&&"object"==typeof e?new Proxy(e,createArrayProxyHandler({variable:this.variable,nDimensions:this.nDimensions,indicesSoFar:this.indicesSoFar})):e)));let r=e[n];return null!==r&&"object"==typeof r&&t>1&&(r=new Proxy(r,createArrayProxyHandler({variable:this.variable,nDimensions:this.nDimensions-1,indicesSoFar:[...this.indicesSoFar,n]}))),r},set:function(e,t,n){throw Error("Property "+t+" is read-only")},deleteProperty:function(e,t){throw Error("Property "+t+" is read-only")}}}function postProcessCopy({serializedComponents:e,componentName:t,addShadowDependencies:n=!0,markAsPrimaryShadow:r=!1,uniqueIdentifiersUsed:a=[],identifierPrefix:i="",unlinkExternalCopies:s=!1,copiesByTargetComponentName:o={},componentNamesFound:l=[],assignNamesFound:u=[],activeAliases:c=[],init:p=!0}){for(let d in e){let m,h=e[d];if("object"==typeof h){if(h.originalName){if(s){if(l.push(h.originalName),h.originalDoenetAttributes&&h.originalDoenetAttributes.assignNames){let e;if(h.attributes.newNamespace?.primitive)e=h.originalName;else{let t=h.originalName.lastIndexOf("/");e=h.originalName.substring(0,t)}for(let t of h.originalDoenetAttributes.assignNames)l.push(e+"/"+t),u.push(e+"/"+t)}h.attributes&&(h.attributes.alias&&c.push(h.attributes.alias.primitive),h.attributes.indexAlias&&c.push(h.attributes.indexAlias.primitive))}if(m=i+h.originalName+"|shadow",!h.originalNameFromSerializedComponent)if(n){let e={[h.originalName]:[{dependencyType:"referenceShadow",compositeName:t}]};if(p&&(e[h.originalName][0].firstLevelReplacement=!0),r&&(e[h.originalName][0].isPrimaryShadow=!0),h.state){let t=Object.keys(h.state);e[h.originalName].downstreamStateVariables=t,e[h.originalName].upstreamStateVariables=t}h.downstreamDependencies=e}else h.unlinkedCopySource=h.originalName}else m=i+h.componentType+"|shadowUnnamed";if("copy"===h.componentType&&s){let e=h.doenetAttributes.targetComponentName;if(e)c.includes(h.doenetAttributes.target)?h.doenetAttributes.targetComponentName=h.doenetAttributes.target:(void 0===o[e]&&(o[e]=[]),o[e].push(h));else if(!h.attributes.uri)throw Error("we need to create a targetComponentName here, then.")}h.uniqueIdentifier=getUniqueIdentifierFromBase(m,a)}}for(let p in e){let d=e[p];if("object"==typeof d){postProcessCopy({serializedComponents:d.children,componentName:t,addShadowDependencies:n,markAsPrimaryShadow:r,uniqueIdentifiersUsed:a,identifierPrefix:i,unlinkExternalCopies:s,copiesByTargetComponentName:o,componentNamesFound:l,assignNamesFound:u,activeAliases:[...c],init:!1});for(let e in d.attributes){let p=d.attributes[e];p.component&&(p.component=postProcessCopy({serializedComponents:[p.component],componentName:t,addShadowDependencies:n,markAsPrimaryShadow:r,uniqueIdentifiersUsed:a,identifierPrefix:i,unlinkExternalCopies:s,copiesByTargetComponentName:o,componentNamesFound:l,assignNamesFound:u,activeAliases:[...c],init:!1})[0])}d.replacements&&postProcessCopy({serializedComponents:d.replacements,componentName:t,addShadowDependencies:n,markAsPrimaryShadow:r,uniqueIdentifiersUsed:a,identifierPrefix:i,unlinkExternalCopies:s,copiesByTargetComponentName:o,componentNamesFound:l,assignNamesFound:u,activeAliases:[...c],init:!1})}}if(p&&s)for(let e in o)if(!l.includes(e)){let t=!1;for(let n of u){let r=n+"/",a=r.length;if(e.substring(0,a)===r){t=!0;break}}if(!t)for(let t of o[e])t.attributes||(t.attributes={}),t.attributes.link={primitive:!1},t.doenetAttributes.target=t.doenetAttributes.targetComponentName}return e}function convertAttributesForComponentType({attributes:e,componentType:t,componentInfoObjects:n,compositeAttributesObj:r={},compositeCreatesNewNamespace:a,flags:i}){let s=n.allComponentClasses[t],o=s.createAttributesObject(),l={};for(let e in o)l[e.toLowerCase()]=e;let u={};for(let t in e){if(t in r&&!r[t].leaveRaw)continue;let i=l[t.toLowerCase()],c=o[i];if(c){if(i in u)throw Error(`Cannot repeat prop ${i}`);if(u[i]=componentFromAttribute({attrObj:c,value:JSON.parse(JSON.stringify(e[t])),componentInfoObjects:n}),u[i].component?.children){let e=[u[i].component];if(applyMacros(e,n),removeBlankStringChildren(e,n),applySugar({serializedComponents:e,componentInfoObjects:n,isAttributeComponent:!0}),a)for(let e of u[i].component.children)if("copy"===e.componentType){let t=e.doenetAttributes.target;/[a-zA-Z_]/.test(t[0])&&(e.doenetAttributes.target="../"+t)}}}else s.acceptAnyAttribute&&(u[t]=JSON.parse(JSON.stringify(e[t])))}return u}async function verifyReplacementsMatchSpecifiedType({component:e,replacements:t,replacementChanges:n,assignNames:r,workspace:a={},componentInfoObjects:i,compositeAttributesObj:s,flags:o}){if(!e.attributes.createComponentOfType?.primitive&&!e.sharedParameters.compositesMustHaveAReplacement)return{replacements:t,replacementChanges:n};let l,u=e.replacementsToWithhold;if(n){l=e.replacements.map((e=>e.componentType));for(let e of n)if("add"===e.changeType){if(void 0!==e.replacementsToWithhold&&(u=e.replacementsToWithhold),!e.changeTopLevelReplacements)continue;if(e.serializedReplacements){let t=e.numberReplacementsToReplace;t>0||(t=0);let n=e.firstReplacementInd,r=e.serializedReplacements.map((e=>e.componentType));l.splice(n,t,...r)}}else if("delete"===e.changeType){if(void 0!==e.replacementsToWithhold&&(u=e.replacementsToWithhold),e.changeTopLevelReplacements){let t=e.firstReplacementInd,n=e.numberReplacementsToDelete;l.splice(t,n)}}else"changeReplacementsToWithhold"===e.changeType&&void 0!==e.replacementsToWithhold&&(u=e.replacementsToWithhold)}else i.isInheritedComponentType({inheritedComponentType:e.componentType,baseComponentType:"template"})&&(t=t.filter((e=>e.componentType||e.trim().length>0))),l=t.map((e=>e.componentType)),1===l.length&&"externalContent"===l[0]&&(l=t[0].children.filter((e=>e.componentType||e.trim().length>0)).map((e=>e.componentType)));if(u>0&&(l=l.slice(0,l.length-u)),!e.attributes.createComponentOfType?.primitive&&e.sharedParameters.compositesMustHaveAReplacement&&l.length>0)return{replacements:t,replacementChanges:n};let c=e.attributes.createComponentOfType?.primitive,p=await e.stateValues.nComponentsSpecified;if(!c){if(c=e.sharedParameters.compositesDefaultReplacementType,!c)throw Error("A component class specified descendantCompositesMustHaveAReplacement but didn't specify descendantCompositesDefaultReplacementType");p=1}if(c=i.componentTypeLowerCaseMapping[c.toLowerCase()],l.length!==p||!l.every((e=>e===c))){if(1===t?.length&&i.isInheritedComponentType({inheritedComponentType:t[0].componentType,baseComponentType:"template"}))return t[0].attributes||(t[0].attributes={}),t[0].attributes.createComponentOfType={primitive:c},t[0].attributes.nComponents={primitive:p},{replacements:t,replacementChanges:n};let d,m=l.length===p&&!(u>0)&&a.sourceNames?.length===p;m&&n&&(1===n.length&&n[0].numberReplacementsToReplace===p?d=n[0].serializedReplacements:m=!1),m?d||(d=t):(a.numReplacementsBySource=[],a.numNonStringReplacementsBySource=[],a.propVariablesCopiedBySource=[],a.sourceNames=[],a.uniqueIdentifiersUsedBySource={},a.uniqueIdentifiersUsedBySource[0]=[]);let h=e.attributes.newNamespace?.primitive;t=[];for(let n=0;n"string"!=typeof e)).length),n){n=[],e.replacementsToWithhold>0&&n.push({changeType:"changeReplacementsToWithhold",replacementsToWithhold:0});let r=0;e.replacements&&(r=e.replacements.length),n.push({changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:0,numberReplacementsToReplace:r,serializedReplacements:t})}}return{replacements:t,replacementChanges:n}}function gatherDescendants({ancestor:e,descendantTypes:t,recurseToMatchedChildren:n=!0,useReplacementsForComposites:r=!1,includeNonActiveChildren:a=!1,skipOverAdapters:i=!1,ignoreReplacementsOfMatchedComposites:s=!1,ignoreReplacementsOfEncounteredComposites:o=!1,init:l=!0,componentInfoObjects:u}){let c=e=>t.some((t=>u.isInheritedComponentType({inheritedComponentType:e.componentType,baseComponentType:t}))),p=[];if(r&&u.isInheritedComponentType({inheritedComponentType:e.componentType,baseComponentType:"_composite"}))l&&p.push(...replacementsForComposites({composite:e,componentInfoObjects:u,includeComposites:a}).filter((e=>"object"==typeof e)));else for(let t of e.allChildrenOrdered){let n,r=e.allChildren[t],s=!1,o=!1;if(r)n=r.component,n.adaptedFrom&&(o=!0),e.activeChildren.includes(n)&&(s=!0);else for(let r of e.activeChildren){if(r.placeholderInd===t){n=r,s=!0,"string"==typeof t&&"adapt"===t.substring(t.length-5,t.length)&&(o=!0);break}if(r.adaptedFrom&&achild.adaptedFrom.placeholderInd===t){n=r.adaptedFrom;break}}n&&(o&&i?p.includes(n.adaptedFrom)||p.push(n.adaptedFrom):(s||a)&&p.push(n))}if(s||o){let e=[];for(let t of p){let n=c(t);o&&!n&&(n=!("copy"===t.componentType&&t.doenetAttributes.copiedURI)),n&&u.isInheritedComponentType({inheritedComponentType:t.componentType,baseComponentType:"_composite"})&&(e=[...e,...replacementsForComposites({composite:t,componentInfoObjects:u,includeComposites:!0}).filter((e=>"object"==typeof e)).map((e=>e.componentName?e.componentName:e.placeholderInd))])}e.length>0&&(p=p.filter((t=>!(e.includes(t.componentName)||e.includes(t.placeholderInd)))))}let d=[];for(let e of p){let l=c(e);if(l&&d.push({componentName:e.componentName?e.componentName:e.placeholderInd,componentType:e.componentType}),(!l||n)&&void 0===e.placeholderInd){let l=gatherDescendants({ancestor:e,descendantTypes:t,recurseToMatchedChildren:n,useReplacementsForComposites:r,includeNonActiveChildren:a,skipOverAdapters:i,ignoreReplacementsOfMatchedComposites:s,ignoreReplacementsOfEncounteredComposites:o,init:!1,componentInfoObjects:u});d.push(...l)}}return d}function replacementsForComposites({composite:e,includeComposites:t=!1,componentInfoObjects:n}){let r=[];if(e.replacements){let a;if(e.replacementsToWithhold){let t=e.replacements.length-e.replacementsToWithhold;a=e.replacements.slice(0,t)}else a=e.replacements;for(let e of a)n.isInheritedComponentType({inheritedComponentType:e.componentType,baseComponentType:"_composite"})?(t&&r.push(e),r.push(...replacementsForComposites({composite:e,componentInfoObjects:n,includeComposites:t}))):r.push(e)}return r}function ancestorsIncludingComposites(e,t){if(void 0===e.ancestors||0===e.ancestors.length)return[];let n=[e.ancestors[0].componentName],r=t[e.ancestors[0].componentName];if(r&&n.push(...ancestorsIncludingComposites(r,t)),e.replacementOf){n.push(e.replacementOf.componentName);let r=ancestorsIncludingComposites(e.replacementOf,t);for(let e of r)n.includes(e)||n.push(e)}return n}const dependencyTypeArray=[];class DependencyHandler{constructor({_components:e,componentInfoObjects:t,core:n}){this.upstreamDependencies={},this.downstreamDependencies={},this.switchDependencies={},this.circularCheckPassed={},this.circularResolveBlockedCheckPassed={},this.dependencyTypes={},dependencyTypeArray.forEach((e=>this.dependencyTypes[e.dependencyType]=e)),this.core=n,this._components=e,this.componentInfoObjects=t,this.updateTriggers={descendantDependenciesByAncestor:{},ancestorDependenciesByPotentialAncestor:{},replacementDependenciesByComposite:{},childDependenciesByParent:{},parentDependenciesByParent:{},dependenciesMissingComponentBySpecifiedName:{},dependenciesBasedOnDependenciesOfStateVariables:{},primaryShadowDependencies:{}},this.resolveBlockers={neededToResolve:{},resolveBlockedBy:{}}}async setUpComponentDependencies(e){this.downstreamDependencies[e.componentName]&&this.deleteAllDownstreamDependencies({component:e}),this.downstreamDependencies[e.componentName]={},this.upstreamDependencies[e.componentName]||(this.upstreamDependencies[e.componentName]={});let t=[],n=[];for(let r in e.state)e.state[r].isArrayEntry||e.state[r].isAlias||n.includes(r)||(t.push(r),e.state[r].additionalStateVariablesDefined&&n.push(...e.state[r].additionalStateVariablesDefined));for(let n of t){let t=[n];e.state[n].additionalStateVariablesDefined&&t.push(...e.state[n].additionalStateVariablesDefined),await this.setUpStateVariableDependencies({component:e,stateVariable:n,allStateVariablesAffected:t})}}async setUpStateVariableDependencies({component:e,stateVariable:t,allStateVariablesAffected:n}){let r,a=e.state[t];a.stateVariablesDeterminingDependencies?(r={},a.stateVariablesDeterminingDependencies&&(r.__determine_dependencies={dependencyType:"determineDependencies",variableNames:a.stateVariablesDeterminingDependencies})):r=await a.returnDependencies({componentInfoObjects:this.componentInfoObjects,sharedParameters:e.sharedParameters});for(let a in r){let i=r[a];if(!(i.dependencyType in this.dependencyTypes))throw Error(`Unrecognized dependency type ${i.dependencyType} for ${a} of ${t} of ${e.componentName}`);let s=new this.dependencyTypes[i.dependencyType]({component:e,stateVariable:t,allStateVariablesAffected:n,dependencyName:a,dependencyDefinition:i,dependencyHandler:this,expandComposites:!1,forceExpandComposites:!1});await s.initialize(),s.checkForCircular()}}deleteAllDownstreamDependencies({component:e,stateVariables:t="__all__"}){let n,r=e.componentName;n="__all__"===t?Object.keys(this.downstreamDependencies[r]):t;for(let e of n){let t=this.downstreamDependencies[r][e];for(let e in t)t[e].deleteDependency();delete this.downstreamDependencies[r][e]}0!==Object.keys(this.downstreamDependencies[r]).length||this.components[r]||delete this.downstreamDependencies[r]}async deleteAllUpstreamDependencies({component:e,stateVariables:t="__all__",completelyDelete:n=!1}){let r,a=e.componentName;r="__all__"===t?Object.keys(this.upstreamDependencies[a]):t;for(let e of r){if(this.upstreamDependencies[a][e])for(let t of[...this.upstreamDependencies[a][e]])if(n){for(let e of t.upstreamVariableNames)this._components[t.upstreamComponentName].state[e].initiallyResolved&&await this.core.markStateVariableAndUpstreamDependentsStale({component:this.components[t.upstreamComponentName],varName:e});t.deleteDependency()}else await t.removeDownstreamComponent({indexToRemove:t.downstreamComponentNames.indexOf(a)});delete this.upstreamDependencies[a][e]}0!==Object.keys(this.upstreamDependencies[a]).length||this._components[a]||delete this.upstreamDependencies[a]}async addBlockersFromChangedStateVariableDependencies({componentName:e,stateVariables:t}){let n=this.updateTriggers.dependenciesBasedOnDependenciesOfStateVariables[e];if(n)for(let r of t){let t=n[r];if(t)for(let n of t)if(n.gettingValue){let t=n.varsWithUpdatedDeps[e];t||(t=n.varsWithUpdatedDeps[e]=[]),t.includes(r)||t.push(r)}else for(let e of n.upstreamVariableNames)await this.addBlocker({blockerComponentName:n.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:n.dependencyName,componentNameBlocked:n.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e})}}async addBlockersFromChangedActiveChildren({parent:e}){if(await this.collateCountersAndPropagateToAncestors(e),this.updateTriggers.childDependenciesByParent[e.componentName])for(let t of this.updateTriggers.childDependenciesByParent[e.componentName]){for(let e of t.upstreamVariableNames)await this.addBlocker({blockerComponentName:t.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:t.dependencyName,componentNameBlocked:t.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});await this.addBlockersFromChangedStateVariableDependencies({componentName:t.upstreamComponentName,stateVariables:t.upstreamVariableNames})}if(e.ancestors){if(this.updateTriggers.parentDependenciesByParent[e.componentName])for(let t of this.updateTriggers.parentDependenciesByParent[e.componentName]){for(let e of t.upstreamVariableNames)await this.addBlocker({blockerComponentName:t.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:t.dependencyName,componentNameBlocked:t.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});await this.addBlockersFromChangedStateVariableDependencies({componentName:t.upstreamComponentName,stateVariables:t.upstreamVariableNames})}for(let t of[e.componentName,...ancestorsIncludingComposites(e,this.components)])await this.addDescendantBlockersToAncestor(t);if(this.updateTriggers.ancestorDependenciesByPotentialAncestor[e.componentName])for(let t of this.updateTriggers.ancestorDependenciesByPotentialAncestor[e.componentName]){for(let e of t.upstreamVariableNames)await this.addBlocker({blockerComponentName:t.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:t.dependencyName,componentNameBlocked:t.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});await this.addBlockersFromChangedStateVariableDependencies({componentName:t.upstreamComponentName,stateVariables:t.upstreamVariableNames})}}}async resolveBlockersFromChangedActiveChildren(e,t=!1){if(await this.collateCountersAndPropagateToAncestors(e),this.updateTriggers.childDependenciesByParent[e.componentName])for(let n of this.updateTriggers.childDependenciesByParent[e.componentName])await this.resolveIfReady({componentName:n.upstreamComponentName,type:"recalculateDownstreamComponents",stateVariable:n.representativeStateVariable,dependency:n.dependencyName,force:t});if(e.ancestors){if(this.updateTriggers.parentDependenciesByParent[e.componentName])for(let n of this.updateTriggers.parentDependenciesByParent[e.componentName])await this.resolveIfReady({componentName:n.upstreamComponentName,type:"recalculateDownstreamComponents",stateVariable:n.representativeStateVariable,dependency:n.dependencyName,force:t});for(let n of[e.componentName,...ancestorsIncludingComposites(e,this.components)])await this.resolveDescendantBlockersToAncestor(n,t);if(this.updateTriggers.ancestorDependenciesByPotentialAncestor[e.componentName])for(let n of this.updateTriggers.ancestorDependenciesByPotentialAncestor[e.componentName])await this.resolveIfReady({componentName:n.upstreamComponentName,type:"recalculateDownstreamComponents",stateVariable:n.representativeStateVariable,dependency:n.dependencyName,force:t})}}async addDescendantBlockersToAncestor(e){if(this.updateTriggers.descendantDependenciesByAncestor[e])for(let t of this.updateTriggers.descendantDependenciesByAncestor[e]){for(let e of t.upstreamVariableNames)await this.addBlocker({blockerComponentName:t.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:t.dependencyName,componentNameBlocked:t.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});await this.addBlockersFromChangedStateVariableDependencies({componentName:t.upstreamComponentName,stateVariables:t.upstreamVariableNames})}}async resolveDescendantBlockersToAncestor(e,t=!1){if(this.updateTriggers.descendantDependenciesByAncestor[e])for(let n of this.updateTriggers.descendantDependenciesByAncestor[e])await this.resolveIfReady({componentName:n.upstreamComponentName,type:"recalculateDownstreamComponents",stateVariable:n.representativeStateVariable,dependency:n.dependencyName,force:t})}async addBlockersFromChangedReplacements(e){if(this.updateTriggers.replacementDependenciesByComposite[e.componentName])for(let t of this.updateTriggers.replacementDependenciesByComposite[e.componentName])for(let e of t.upstreamVariableNames)await this.addBlocker({blockerComponentName:t.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:t.dependencyName,componentNameBlocked:t.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});for(let t of[e.componentName,...ancestorsIncludingComposites(e,this.components)])await this.addDescendantBlockersToAncestor(t)}checkForCircularDependency({componentName:e,varName:t,previouslyVisited:n=[]}){let r=e+":"+t;if(n.includes(r)){console.log("found circular",r,n);let e,t=/^(.*):/,a=n.map((e=>e.match(t)[1])),i=a.filter((e=>"__"!==e.slice(0,2))).reduce(((e,t)=>e.includes(t)?e:[...e,t]),[]);throw 0===i.length&&(i=[a[0]]),1===i.length?e=i[0]:2===i.length?e=i.join(" and "):(i[i.length-2]=i.slice(i.length-2).join(", and "),i.pop(),e=i.join(", ")),Error(`Circular dependency involving ${e}`)}if(n=[...n,r],!this.circularCheckPassed[r]&&(this.circularCheckPassed[r]=!0,e in this.downstreamDependencies)){let r=this.downstreamDependencies[e][t];for(let e in r){let t=r[e],a=t.downstreamComponentNames;if(!a)continue;let i=t.mappedDownstreamVariableNamesByComponent;if(i)for(let[e,t]of a.entries()){let r=i[e];for(let e of r)this.checkForCircularDependency({componentName:t,varName:e,previouslyVisited:n})}}}}resetCircularCheckPassed(e,t){let n=e+":"+t;if(this.circularCheckPassed[n]){delete this.circularCheckPassed[n];let r=this.upstreamDependencies[e][t];if(r)for(let e of r)for(let t of e.upstreamVariableNames)"__identity"!==t&&this.resetCircularCheckPassed(e.upstreamComponentName,t)}}async updateDependencies({componentName:e,stateVariable:t,dependency:n}){let r=this._components[e],a=r.state[t],i=[t];a.additionalStateVariablesDefined&&i.push(...a.additionalStateVariablesDefined);let s,o=this.downstreamDependencies[e][t].__determine_dependencies;if(o){let t=!0;if(o.originalDownstreamVariableNames.length>0)for(let[r,a]of o.downstreamComponentNames.entries()){let s=this._components[a];for(let l of o.mappedDownstreamVariableNamesByComponent[r]){let r=s.state[l].isResolved;if(!r){r=(await this.resolveItem({componentName:a,type:"stateVariable",stateVariable:l})).success}if(!r){t=!1;for(let t of i)await this.addBlocker({blockerComponentName:a,blockerType:"stateVariable",blockerStateVariable:l,componentNameBlocked:e,typeBlocked:"determineDependencies",stateVariableBlocked:t,dependencyBlocked:n})}}}if(!t)return{success:!1};s=await o.getValue()}else s={changes:{},value:{stateValues:{}}};if(0===Object.keys(s.changes).length&&void 0!==a._previousValue)return{success:!0};let l={stateValues:Object.assign({},s.value.stateValues),componentInfoObjects:this.componentInfoObjects,sharedParameters:r.sharedParameters},u=await a.returnDependencies(l);a.stateVariablesDeterminingDependencies&&(u.__determine_dependencies={dependencyType:"determineDependencies",variableNames:a.stateVariablesDeterminingDependencies});let c=await this.replaceDependenciesIfChanged({component:r,stateVariable:t,newDependencies:u,allStateVariablesAffected:i});if(!c.changedDependency&&!l.changedDependency)return{success:!0};for(let e of c.newlyCreatedDependencies)e.checkForCircular();for(let e of i)this.checkForCircularDependency({componentName:r.componentName,varName:e}),r.state[e].forceRecalculation=!0;a.initiallyResolved&&await this.core.markStateVariableAndUpstreamDependentsStale({component:r,varName:t});for(let e of i)r.state[e].initiallyResolved&&this.recordActualChangeInUpstreamDependencies({component:r,varName:e});return await this.addBlockersFromChangedStateVariableDependencies({componentName:e,stateVariables:i}),{success:!0}}async replaceDependenciesIfChanged({component:e,stateVariable:t,newDependencies:n,allStateVariablesAffected:r}){let a=this.downstreamDependencies[e.componentName][t],i=!1,s=[];for(let e in a)e in n||(i=!0,a[e].deleteDependency());for(let o in n)if(o in a){if(!deepCompare(n[o],a[o].definition)){i=!0,a[o].deleteDependency();let l=n[o],u=new this.dependencyTypes[l.dependencyType]({component:e,stateVariable:t,allStateVariablesAffected:r,dependencyName:o,dependencyDefinition:l,dependencyHandler:this});await u.initialize(),s.push(u)}}else{i=!0;let a=n[o],l=new this.dependencyTypes[a.dependencyType]({component:e,stateVariable:t,allStateVariablesAffected:r,dependencyName:o,dependencyDefinition:a,dependencyHandler:this});await l.initialize(),s.push(l)}return{changedDependency:i,newlyCreatedDependencies:s}}async checkForDependenciesOnNewComponent(e){let t=[],n={};if(this.updateTriggers.dependenciesMissingComponentBySpecifiedName[e]){for(let r of this.updateTriggers.dependenciesMissingComponentBySpecifiedName[e]){let a=this._components[r.upstreamComponentName];if(!a)continue;let i=!0;for(let e of r.upstreamVariableNames)if(!(e in a.state)){i=!1;break}if(i){for(let e of r.upstreamVariableNames){a.state[e].initiallyResolved&&(n[r.upstreamComponentName]&&n[r.upstreamComponentName][e]||t.push({componentName:r.upstreamComponentName,varName:e}))}for(let t of r.upstreamVariableNames)this.deleteFromNeededToResolve({componentNameBlocked:r.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:t,dependencyBlocked:r.dependencyName,blockerComponentName:e,blockerType:"componentIdentity"});if((await this.resolveIfReady({componentName:r.upstreamComponentName,type:"recalculateDownstreamComponents",stateVariable:r.representativeStateVariable,dependency:r.dependencyName,expandComposites:!1,recurseUpstream:!0})).success)for(let e of r.upstreamVariableNames)a.state[e].initiallyResolved||(n[r.upstreamComponentName]||(n[r.upstreamComponentName]={}),n[r.upstreamComponentName][e]=!0);else for(let e of r.upstreamVariableNames)await this.addBlocker({blockerComponentName:r.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:r.dependencyName,componentNameBlocked:r.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e})}}delete this.updateTriggers.dependenciesMissingComponentBySpecifiedName[e]}return t}async getStateVariableDependencyValues({component:e,stateVariable:t}){let n={},r={},a={},i=this.downstreamDependencies[e.componentName][t];for(let e in i){let{value:t,changes:s,usedDefault:o}=await i[e].getValue();n[e]=t,Object.keys(s).length>0&&(r[e]=s),o&&(a[e]=o)}return{dependencyValues:n,changes:r,usedDefault:a}}recordActualChangeInUpstreamDependencies({component:e,varName:t,changes:n}){let r=e.componentName,a=this.upstreamDependencies[r][t];if(a)for(let i of a)if(i.valuesChanged){let a=i.downstreamComponentNames.indexOf(r),s=i.valuesChanged[a][t];if(!s&&e.stateVarAliases)for(let n in e.stateVarAliases)e.stateVarAliases[n]===t&&n in upValuesChangedSub&&(s=upValuesChangedSub[n]);if(!s){if(!e.state[t].isArrayEntry)throw Error(`Something is wrong, as a variable ${t} of ${e.componentName} actually changed, but wasn't marked with a potential change`);s=upValuesChangedSub[t]={changed:{}}}e.state[t]&&e.state[t].isArray?(void 0===s.changed?s.changed={arrayKeysChanged:{}}:!0===s.changed&&(s.changed={allArrayKeysChanged:!0,arraySizeChanged:!0,arrayKeysChanged:{}}),n&&(n.allArrayKeysChanged&&(s.changed.allArrayKeysChanged=!0),n.arraySizeChanged&&(s.changed.arraySizeChanged=!0),Object.assign(s.changed.arrayKeysChanged,n.arrayKeysChanged))):s.changed=!0}}async collateCountersAndPropagateToAncestors(e){let t=Object.keys(e.counters);for(let n of e.allChildrenOrdered){let e=this._components[n];if(e)for(let n in e.counters)t.includes(n)||t.push(n)}let n=!1;for(let r of t){let t=e.counters[r];t||(t=e.counters[r]={dependencies:[],componentList:[]});let a=[];t.dependencies.length>0&&a.push(e.componentName);for(let t of e.allChildrenOrdered){let e=this._components[t];if(e){let t=e.counters[r];t&&a.push(...t.componentList)}}(a.length!==t.componentList.length||t.componentList.some(((e,t)=>e!=a[t])))&&(n=!0,t.componentList=a)}if(!n)return{foundChange:!1};if(!e.ancestors[0]){for(let n of t){let t=e.counters[n];for(let[e,r]of t.componentList.entries()){let t=this._components[r],a=t.counters[n];a.value=e+1;for(let e of a.dependencies)if(t.state[e.representativeStateVariable].initiallyResolved){await this.core.markStateVariableAndUpstreamDependentsStale({component:t,varName:e.representativeStateVariable});for(let n of e.upstreamVariableNames)t.state[n].forceRecalculation=!0,this.recordActualChangeInUpstreamDependencies({component:t,varName:n})}}}return{foundChange:!0,finishedPropagation:!0}}let r=this._components[e.ancestors[0].componentName];if(!r||!r.allChildrenOrdered.includes(e.componentName))return{foundChange:!0,finishedPropagation:!1};let a=await this.collateCountersAndPropagateToAncestors(r);return a.foundChange||console.error(`we found a change in propagating counters for ${e.componentName}, but no change for ancestors!`),{foundChange:!0,finishedPropagation:a.finishedPropagation}}getNeededToResolve({componentName:e,type:t,stateVariable:n,dependency:r}){let a=this.resolveBlockers.neededToResolve[e];a||(a=this.resolveBlockers.neededToResolve[e]={});let i=a[t];if(i||(i=a[t]={}),n){let e=i;if(i=e[n],i||(i=e[n]={}),r){let e=i;i=e[r],i||(i=e[r]={})}}return i}deleteFromNeededToResolve({componentNameBlocked:e,typeBlocked:t,stateVariableBlocked:n,dependencyBlocked:r,blockerType:a,blockerCode:i,deleteFromReciprocal:s=!0}){let o=e;n&&(o+="|"+n,r&&(o+="|"+r));let l=function(e){if(a){if(e[a])if(i){let n=e[a].indexOf(i);if(-1!==n&&e[a].splice(n,1),0===e[a].length&&delete e[a],s){let[e,n,r]=i.split("|");this.deleteFromResolveBlockedBy({blockerComponentName:e,blockerType:a,blockerStateVariable:n,blockerDependency:r,typeBlocked:t,codeBlocked:o,deleteFromReciprocal:!1})}}else{if(s)for(let n of e[a]){let[e,r,i]=n.split("|");this.deleteFromResolveBlockedBy({blockerComponentName:e,blockerType:a,blockerStateVariable:r,blockerDependency:i,typeBlocked:t,codeBlocked:o,deleteFromReciprocal:!1})}delete e[a]}}else if(s)for(let n in e)for(let r of e[n]){let[e,a,i]=r.split("|");this.deleteFromResolveBlockedBy({blockerComponentName:e,blockerType:n,blockerStateVariable:a,blockerDependency:i,typeBlocked:t,codeBlocked:o,deleteFromReciprocal:!1})}}.bind(this),u=this.resolveBlockers.neededToResolve[e];if(u){let i=u[t];if(i)if(n){let e=i[n];if(e)if(r){let t=e[r];t&&(l(t),a&&0!==Object.keys(t).length||delete e[r]),0===Object.keys(e).length&&delete i[n]}else l(e),a&&0!==Object.keys(e).length||delete i[n];0===Object.keys(i).length&&delete u[t]}else l(i),a&&0!==Object.keys(i).length||delete u[t];0===Object.keys(u).length&&delete this.resolveBlockers.neededToResolve[e]}}checkIfHaveNeededToResolve({componentName:e,type:t,stateVariable:n,dependency:r}){let a=this.resolveBlockers.neededToResolve[e];if(!a)return!1;let i=a[t];if(!i)return!1;if(n){if(i=i[n],!i)return!1;if(r){if(i=i[r],!i)return!1}}return Object.keys(i).length>0}getResolveBlockedBy({componentName:e,type:t,stateVariable:n,dependency:r}){let a=this.resolveBlockers.resolveBlockedBy[e];a||(a=this.resolveBlockers.resolveBlockedBy[e]={});let i=a[t];if(i||(i=a[t]={}),n){let e=i;if(i=e[n],i||(i=e[n]={}),r){let e=i;i=e[r],i||(i=e[r]={})}}return i}deleteFromResolveBlockedBy({blockerComponentName:e,blockerType:t,blockerStateVariable:n,blockerDependency:r,typeBlocked:a,codeBlocked:i,deleteFromReciprocal:s=!0}){let o=e;n&&(o+="|"+n,r&&(o+="|"+r));let l=function(e){if(a){if(e[a])if(i){let n=e[a].indexOf(i);if(-1!==n&&e[a].splice(n,1),0===e[a].length&&delete e[a],s){let[e,n,r]=i.split("|");this.deleteFromNeededToResolve({componentNameBlocked:e,typeBlocked:a,stateVariableBlocked:n,dependencyBlocked:r,blockerType:t,blockerCode:o,deleteFromReciprocal:!1})}}else{if(s)for(let n of e[a]){let[e,r,i]=n.split("|");this.deleteFromNeededToResolve({componentNameBlocked:e,typeBlocked:a,stateVariableBlocked:r,dependencyBlocked:i,blockerType:t,blockerCode:o,deleteFromReciprocal:!1})}delete e[a]}}else if(s)for(let n in e)for(let r of e[n]){let[e,a,i]=r.split("|");this.deleteFromNeededToResolve({componentNameBlocked:e,typeBlocked:n,stateVariableBlocked:a,dependencyBlocked:i,blockerType:t,blockerCode:o,deleteFromReciprocal:!1})}}.bind(this),u=this.resolveBlockers.resolveBlockedBy[e];if(u){let i=u[t];if(i)if(n){let e=i[n];if(e)if(r){let t=e[r];t&&(l(t),a&&0!==Object.keys(t).length||delete e[r]),0===Object.keys(e).length&&delete i[n]}else l(e),a&&0!==Object.keys(e).length||delete i[n];0===Object.keys(i).length&&delete u[t]}else l(i),a&&0!==Object.keys(i).length||delete u[t];0===Object.keys(u).length&&delete this.resolveBlockers.resolveBlockedBy[e]}}async addBlocker({blockerComponentName:e,blockerType:t,blockerStateVariable:n,blockerDependency:r,componentNameBlocked:a,typeBlocked:i,stateVariableBlocked:s,dependencyBlocked:o}){let l=e;n&&(l+="|"+n,r&&(l+="|"+r));let u=a;s&&(u+="|"+s,o&&(u+="|"+o));let c=this.getNeededToResolve({componentName:a,type:i,stateVariable:s,dependency:o}),p=c[t];if(p||(p=c[t]=[]),p.includes(l))return;if(p.push(l),"stateVariable"===i){let e=this._components[a];if(e){let t=e.state[s];if(t.isResolved=!1,t.initiallyResolved){await this.core.markStateVariableAndUpstreamDependentsStale({component:e,varName:s});let t=this.upstreamDependencies[a][s];if(t)for(let e of t)if(this._components[e.upstreamComponentName])for(let t of e.upstreamVariableNames)await this.addBlocker({blockerComponentName:a,blockerType:"stateVariable",blockerStateVariable:s,componentNameBlocked:e.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:t})}}}let d=this.getResolveBlockedBy({componentName:e,type:t,stateVariable:n,dependency:r}),m=d[i];m||(m=d[i]=[]),m.includes(u)||m.push(u),this.resetCircularResolveBlockerCheckPassed({componentName:a,type:i,stateVariable:s,dependency:o}),this.checkForCircularResolveBlocker({componentName:a,type:i,stateVariable:s,dependency:o})}async processNewlyResolved({componentNameNewlyResolved:e,typeNewlyResolved:t,stateVariableNewlyResolved:n,dependencyNewlyResolved:r,expandComposites:a=!0,force:i=!1,recurseUpstream:s=!1}){if("stateVariable"===t){let t=this._components[e];if(t){t.state[n]&&(t.state[n].isResolved=!0,t.state[n].initiallyResolved=!0)}}else if("componentIdentity"===t){if(!(e in this._components)&&!i)return{success:!1}}else if("recalculateDownstreamComponents"===t){let t;try{t=this.downstreamDependencies[e][n][r]}catch(e){}if(t){let e=await t.recalculateDownstreamComponents({force:i});if(!e.success&&!i)return e;for(let e of t.upstreamVariableNames)this.deleteFromNeededToResolve({componentNameBlocked:t.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e,blockerType:"recalculateDownstreamComponents",blockerCode:t.upstreamComponentName+"|"+e+"|"+r});for(let e of t.upstreamVariableNames)await this.resolveIfReady({componentName:t.upstreamComponentName,type:"stateVariable",stateVariable:e,expandComposites:a,force:i,recurseUpstream:s});return{success:!0}}}else if("determineDependencies"===t){let t;try{t=this.downstreamDependencies[e][n][r]}catch(e){}if(t){let o=this.getNeededToResolve({componentName:e,type:"stateVariable",stateVariable:n}),l=!1,u=[];if(o.determineDependencies)for(let t of o.determineDependencies){let[r,a,i]=t.split("|");if(this.checkIfHaveNeededToResolve({componentName:e,type:"determineDependency",stateVariable:n,dependency:i})){l=!0;break}u.push(i)}if(l)return{success:!0};if(!(await this.updateDependencies({componentName:e,stateVariable:n,dependency:r})).success)return{success:!1};for(let n of t.upstreamVariableNames){for(let e of u)this.deleteFromResolveBlockedBy({blockerComponentName:t.upstreamComponentName,blockerType:"determineDependencies",blockerStateVariable:n,blockerDependency:e});await this.resolveIfReady({componentName:e,type:"stateVariable",stateVariable:n,expandComposites:a,force:i,recurseUpstream:s})}return{success:!0}}}else if("childMatches"===t){let t=this._components[e];if(t&&!t.childrenMatched){if(!(await this.core.deriveChildResultsFromDefiningChildren({parent:t,expandComposites:a,forceExpandComposites:i})).skipping&&!t.childrenMatchedWithPlaceholders&&!i)return{success:!1}}}else{if("expandComposite"!==t)throw Error(`Unrecognized type newly resolved: ${t}`);if(!this._components[e].isExpanded){if(this.core.updateInfo.compositesBeingExpanded.includes(e))return{success:!1};await this.core.expandCompositeComponent(this._components[e])}}let o=this.getResolveBlockedBy({componentName:e,type:t,stateVariable:n,dependency:r});o=Object.assign({},o);for(let l in o)for(let u of[...o[l]])if(this.deleteFromResolveBlockedBy({blockerComponentName:e,blockerType:t,blockerStateVariable:n,blockerDependency:r,typeBlocked:l,codeBlocked:u}),s){let[e,t,n]=u.split("|");await this.resolveIfReady({componentName:e,type:l,stateVariable:t,dependency:n,expandComposites:a,force:i,recurseUpstream:s})}return{success:!0}}async resolveStateVariablesIfReady({component:e,stateVariables:t}){let n=e.componentName;t||(await this.resolveIfReady({componentName:n,type:"componentIdentity",expandComposites:!1}),t=Object.keys(e.state));for(let r of t){let t=e.state[r];if(t&&t.determineDependenciesImmediately){let e=this.getNeededToResolve({componentName:n,type:"stateVariable",stateVariable:r}).determineDependencies;if(e)for(let t of e){let[e,n,r]=t.split("|");await this.resolveIfReady({componentName:e,type:"determineDependencies",stateVariable:n,dependency:r,expandComposites:!0})}}await this.resolveIfReady({componentName:n,type:"stateVariable",stateVariable:r,expandComposites:!1})}}async resolveIfReady({componentName:e,type:t,stateVariable:n,dependency:r,expandComposites:a=!0,force:i=!1,recurseUpstream:s=!1}){return this.checkIfHaveNeededToResolve({componentName:e,type:t,stateVariable:n,dependency:r})?{success:!1}:(this.deleteFromNeededToResolve({componentNameBlocked:e,typeBlocked:t,stateVariableBlocked:n,dependencyBlocked:r}),await this.processNewlyResolved({componentNameNewlyResolved:e,typeNewlyResolved:t,stateVariableNewlyResolved:n,dependencyNewlyResolved:r,expandComposites:a,force:i,recurseUpstream:s}))}async resolveItem({componentName:e,type:t,stateVariable:n,dependency:r,force:a=!1,recurseUpstream:i=!1,expandComposites:s=!0,numPreviouslyNeeded:o}){let l,u=this.getNeededToResolve({componentName:e,type:t,stateVariable:n,dependency:r}),c=u.determineDependencies;if(c&&c.length>0)for(let e of[...c]){let[t,n,r]=e.split("|"),i=await this.resolveItem({componentName:t,type:"determineDependencies",stateVariable:n,dependency:r,force:a,expandComposites:s});if(!i.success)return i}"stateVariable"===t&&this._components[e]&&(l=this._components[e].state[n],l&&(l.currentlyResolving=!0));let p=1/0,d=1/0;for(;(Object.keys(u).length>0||d>0)&&!(Number.isFinite(d)&&d>=p);){d>0&&(u=this.getNeededToResolve({componentName:e,type:t,stateVariable:n,dependency:r})),p=d,d=0;for(let i in u){if("determineDependencies"===i)throw Error(`Shouldn't have determine dependencies blocker after determining dependencies: ${e}, ${t}, ${n}, ${r}`);for(let e of[...u[i]]){let[t,n,r]=e.split("|"),o=await this.resolveItem({componentName:t,type:i,stateVariable:n,dependency:r,expandComposites:s});if(!o.success){if(!a)return o;d++}}}}if(d>0)for(u=this.getNeededToResolve({componentName:e,type:t,stateVariable:n,dependency:r});Object.keys(u).length>0;)for(let i in u){if("determineDependencies"===i)throw Error(`Shouldn't have determine dependencies blocker after determining dependencies: ${e}, ${t}, ${n}, ${r}`);for(let e of[...u[i]]){let[t,n,r]=e.split("|"),o=await this.resolveItem({componentName:t,type:i,stateVariable:n,dependency:r,force:a,expandComposites:s});if(!o.success)return o}}l&&(l.currentlyResolving=!1);let m=await this.resolveIfReady({componentName:e,type:t,stateVariable:n,dependency:r,force:a,recurseUpstream:i,expandComposites:s});if(!m.success){let l=this.getNeededToResolve({componentName:e,type:t,stateVariable:n,dependency:r}),u=Object.keys(l).length;u>0&&(void 0===o||ue.match(t)[1])),r=n.filter((e=>"__"!==e.slice(0,2))).reduce(((e,t)=>e.includes(t)?e:[...e,t]),[]);0===r.length&&(r=[n[0]]),1===r.length?e=r[0]:2===r.length?e=r.join(" and "):(r[r.length-2]=r.slice(r.length-2).join(", and "),r.pop(),e=r.join(", "));let i=[],o=[];for(let e of a){let[t,n]=e.split("|"),r=this._components[t];if(r){this.componentInfoObjects.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"_composite"})&&!r.attributes.createComponentOfType?.primitive&&("readyToExpandWhenResolved"===n?i.push(t):n===r.constructor.stateVariableToEvaluateAfterReplacements&&o.push(t))}}let l=!1;for(let e of i)if(o.includes(e)){l=!0;break}let u=`Circular dependency involving ${e}.`;throw l&&(u+=" Specifying the type of a composite component may address this circular dependency."),Error(u)}if(a=[...a,s],!this.circularResolveBlockedCheckPassed[s]){this.circularResolveBlockedCheckPassed[s]=!0;let i=this.getNeededToResolve({componentName:e,type:t,stateVariable:n,dependency:r});for(let e in i)for(let t of i[e]){let[n,r,i]=t.split("|");this.checkForCircularResolveBlocker({componentName:n,type:e,stateVariable:r,dependency:i,previouslyVisited:a})}}}resetCircularResolveBlockerCheckPassed({componentName:e,type:t,stateVariable:n,dependency:r}){let a=e;n&&(a+="|"+n,r&&(a+="|"+r));let i=a+"|"+t;if(this.circularResolveBlockedCheckPassed[i]){delete this.circularResolveBlockedCheckPassed[i];let a=this.getResolveBlockedBy({componentName:e,type:t,stateVariable:n,dependency:r});for(let e in a)for(let t of a[e]){let[n,r,a]=t.split("|");this.resetCircularResolveBlockerCheckPassed({componentName:n,type:e,stateVariable:r,dependency:a})}}}get components(){return this._components}set components(e){return null}}class Dependency{constructor({component:e,stateVariable:t,allStateVariablesAffected:n,dependencyName:r,dependencyDefinition:a,dependencyHandler:i}){this.dependencyName=r,this.dependencyHandler=i,this.upstreamComponentName=e.componentName,this.upstreamVariableNames=n,this.definition=Object.assign({},a),this.representativeStateVariable=t,a.doNotProxy&&(this.doNotProxy=!0),a.variablesOptional&&(this.variablesOptional=!0),a.publicStateVariablesOnly&&(this.publicStateVariablesOnly=!0),a.caseInsensitiveVariableMatch&&(this.caseInsensitiveVariableMatch=!0),a.useMappedVariableNames&&(this.useMappedVariableNames=!0),a.propIndex&&(a.propIndex.every(Number.isFinite)?this.propIndex=a.propIndex.map(Math.round):this.propIndex=[]),this.returnSingleVariableValue=!1,this.returnSingleComponent=!1,this.originalDownstreamVariableNames=[]}static dependencyType="_base";downstreamVariableNameIfNoVariables="__identity";static get rendererType(){return this.componentType}get dependencyType(){return this.constructor.dependencyType}setUpParameters(){}async determineDownstreamComponents(){return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]}}async initialize(){this.setUpParameters();let e=await this.determineDownstreamComponents(),t=e.downstreamComponentNames,n=e.downstreamComponentTypes;this.componentIdentitiesChanged=!0;let r=this.dependencyHandler.downstreamDependencies[this.upstreamComponentName];r||(r=this.dependencyHandler.downstreamDependencies[this.upstreamComponentName]={});for(let e of this.upstreamVariableNames)r[e]||(r[e]={}),r[e][this.dependencyName]=this;0!==this.originalDownstreamVariableNames.length||this.originalVariablesByComponent?(this.mappedDownstreamVariableNamesByComponent=[],this.valuesChanged=[]):(delete this.mappedDownstreamVariableNamesByComponent,delete this.upValuesChanged),this.downstreamComponentNames=[],this.downstreamComponentTypes=[];for(let[e,r]of t.entries())await this.addDownstreamComponent({downstreamComponentName:r,downstreamComponentType:n[e],index:e})}async addDownstreamComponent({downstreamComponentName:e,downstreamComponentType:t,index:n}){this.componentIdentitiesChanged=!0,this.downstreamComponentNames.splice(n,0,e),this.downstreamComponentTypes.splice(n,0,t);let r=this.dependencyHandler._components[e];if(r){let t;t=this.originalVariablesByComponent?this.originalDownstreamVariableNamesByComponent[n]:this.originalDownstreamVariableNames,this.caseInsensitiveVariableMatch&&(t=this.dependencyHandler.core.findCaseInsensitiveMatches({stateVariables:t,componentClass:r.constructor})),this.publicStateVariablesOnly&&(t=this.dependencyHandler.core.matchPublicStateVariables({stateVariables:t,componentClass:r.constructor}));let a=this.dependencyHandler.core.substituteAliases({stateVariables:t,componentClass:r.constructor});this.constructor.convertToArraySize&&(a=a.map((function(e){let t=r.state[e];if(t)return t.arraySizeStateVariable?t.arraySizeStateVariable:`__${e}_is_not_an_array`;if(r.arrayEntryPrefixes){let t=Object.keys(r.arrayEntryPrefixes).sort(((e,t)=>t.length-e.length));for(let n of t)if(e.substring(0,n.length)===n){let t=r.arrayEntryPrefixes[n],a=r.state[t];if(a.getArrayKeysFromVarName({arrayEntryPrefix:n,varEnding:e.substring(n.length),nDimensions:a.nDimensions}).length>0)return r.state[t].arraySizeStateVariable}}return`__${e}_is_not_an_array`}))),void 0!==this.propIndex&&(a=await this.dependencyHandler.core.arrayEntryNamesFromPropIndex({stateVariables:a,component:r,propIndex:this.propIndex}));let i=a;if(t.length>0||this.originalVariablesByComponent){this.mappedDownstreamVariableNamesByComponent.splice(n,0,a);let t={};for(let e of a)t[e]={changed:!0};this.valuesChanged.splice(n,0,t),this.variablesOptional&&(i=i.filter((e=>e in r.state||this.dependencyHandler.core.checkIfArrayEntry({stateVariable:e,component:r}))));for(let t of i)if(r.state[t]||await this.dependencyHandler.core.createFromArrayEntry({component:r,stateVariable:t}),!r.state[t].isResolved)for(let n of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:e,blockerType:"stateVariable",blockerStateVariable:t,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:n}),"determineDependencies"===this.dependencyType&&await this.dependencyHandler.addBlocker({blockerComponentName:e,blockerType:"stateVariable",blockerStateVariable:t,componentNameBlocked:this.upstreamComponentName,typeBlocked:"determineDependencies",stateVariableBlocked:n,dependencyBlocked:this.dependencyName})}0===i.length&&(i=[this.downstreamVariableNameIfNoVariables]);let s=this.dependencyHandler.upstreamDependencies[e];s||(s=this.dependencyHandler.upstreamDependencies[e]={});for(let e of i)if(void 0===s[e]&&(s[e]=[]),s[e].push(this),e!==this.downstreamVariableNameIfNoVariables)for(let e of this.upstreamVariableNames)this.dependencyHandler.resetCircularCheckPassed(this.upstreamComponentName,e)}for(let e of this.upstreamVariableNames)this.dependencyHandler._components[this.upstreamComponentName].state[e].initiallyResolved&&await this.dependencyHandler.core.markStateVariableAndUpstreamDependentsStale({component:this.dependencyHandler.components[this.upstreamComponentName],varName:e})}async removeDownstreamComponent({indexToRemove:e,recordChange:t=!0}){t&&(this.componentIdentitiesChanged=!0);let n=this.downstreamComponentNames[e];if(this.downstreamComponentNames.splice(e,1),this.downstreamComponentTypes.splice(e,1),n in this.dependencyHandler._components){let t;this.mappedDownstreamVariableNamesByComponent?(t=this.mappedDownstreamVariableNamesByComponent[e],this.mappedDownstreamVariableNamesByComponent.splice(e,1),this.valuesChanged.splice(e,1),this.variablesOptional&&t.push(this.downstreamVariableNameIfNoVariables)):t=[this.downstreamVariableNameIfNoVariables];for(let e of t){let t=this.dependencyHandler.upstreamDependencies[n][e];if(t){let r=t.indexOf(this);-1!==r&&(1===t.length?delete this.dependencyHandler.upstreamDependencies[n][e]:t.splice(r,1))}if(e!==this.downstreamVariableNameIfNoVariables)for(let e of this.upstreamVariableNames)this.dependencyHandler.resetCircularCheckPassed(this.upstreamComponentName,e)}}if(t)for(let e of this.upstreamVariableNames)this.dependencyHandler._components[this.upstreamComponentName].state[e].initiallyResolved&&await this.dependencyHandler.core.markStateVariableAndUpstreamDependentsStale({component:this.dependencyHandler.components[this.upstreamComponentName],varName:e})}async swapDownstreamComponents(e,t){this.componentIdentitiesChanged=!0,[this.downstreamComponentNames[e],this.downstreamComponentNames[t]]=[this.downstreamComponentNames[t],this.downstreamComponentNames[e]],[this.downstreamComponentTypes[e],this.downstreamComponentTypes[t]]=[this.downstreamComponentTypes[t],this.downstreamComponentTypes[e]],(this.originalDownstreamVariableNames.length>0||this.originalVariablesByComponent)&&([this.mappedDownstreamVariableNamesByComponent[e],this.mappedDownstreamVariableNamesByComponent[t]]=[this.mappedDownstreamVariableNamesByComponent[t],this.mappedDownstreamVariableNamesByComponent[e]],[this.valuesChanged[e],this.valuesChanged[t]]=[this.valuesChanged[t],this.valuesChanged[e]]);for(let e of this.upstreamVariableNames)this.dependencyHandler._components[this.upstreamComponentName].state[e].initiallyResolved&&await this.dependencyHandler.core.markStateVariableAndUpstreamDependentsStale({component:this.dependencyHandler.components[this.upstreamComponentName],varName:e})}deleteDependency(){let e=[];if(this.mappedDownstreamVariableNamesByComponent){if(e=this.mappedDownstreamVariableNamesByComponent,this.variablesOptional){let t=[];for(let[n,r]of this.downstreamComponentNames.entries()){let a=[];for(let t of e[n])this.dependencyHandler.components[r].state[t]&&a.push(t);a.length>0?t.push(a):t.push([this.downstreamVariableNameIfNoVariables])}e=t}}else e=Array(this.downstreamComponentNames.length).fill([this.downstreamVariableNameIfNoVariables]);for(let[t,n]of this.downstreamComponentNames.entries())for(let r of e[t]){let e=this.dependencyHandler.upstreamDependencies[n][r];if(e){let t=e.indexOf(this);-1!==t&&(1===e.length?delete this.dependencyHandler.upstreamDependencies[n][r]:e.splice(t,1))}for(let e of this.upstreamVariableNames)this.dependencyHandler.deleteFromNeededToResolve({componentNameBlocked:this.componentName,typeBlocked:"stateVariable",stateVariableBlocked:e,blockerType:"stateVariable",blockerCode:n+"|"+r});if(r!==this.downstreamVariableNameIfNoVariables)for(let e of this.upstreamVariableNames)this.dependencyHandler.resetCircularCheckPassed(this.upstreamComponentName,e)}this.deleteFromUpdateTriggers();let t=this.dependencyHandler.downstreamDependencies[this.upstreamComponentName];for(let e of this.upstreamVariableNames)delete t[e][this.dependencyName]}deleteFromUpdateTriggers(){}async getValue({verbose:e=!1,skipProxy:t=!1}={}){let n=[],r={},a=[];this.componentIdentitiesChanged&&(r.componentIdentitiesChanged=!0,this.componentIdentitiesChanged=!1);for(let[e,t]of this.downstreamComponentNames.entries()){let i=this.dependencyHandler._components[t];if(a[e]=!1,i){let s,o={componentType:i.componentType};if(this.skipComponentNames||(o.componentName=t),s=this.originalVariablesByComponent?this.originalDownstreamVariableNamesByComponent[e]:this.originalDownstreamVariableNames,s.length>0){o.stateValues={};let t={},n=!1;for(let[a,l]of s.entries()){let s=this.mappedDownstreamVariableNamesByComponent[e][a],u=this.useMappedVariableNames?s:l;if(!this.variablesOptional||s in i.state){let a=i.state[s];if(!a.deferred)if(o.stateValues[u]=await a.value,this.valuesChanged[e][s].changed&&(r.valuesChanged||(r.valuesChanged={}),r.valuesChanged[e]||(r.valuesChanged[e]={}),r.valuesChanged[e][u]=this.valuesChanged[e][s]),this.valuesChanged[e][s]={},a.usedDefault)t[u]=!0,n=!0;else if(a.isArrayEntry&&1===a.arrayKeys.length){i.state[a.arrayStateVariable].usedDefaultByArrayKey[a.arrayKeys[0]]&&(t[u]=!0,n=!0)}}}n&&(a[e]=t)}n.push(o)}else n.push({componentType:this.downstreamComponentTypes[e]})}if(!e)if(this.returnSingleVariableValue)if(1===n.length){n=n[0],r.valuesChanged&&r.valuesChanged[0]?r.valuesChanged=r.valuesChanged[0]:delete r.valuesChanged,a=a[0];let e=Object.keys(n.stateValues);if(1===e.length){let t=e[0];n=n.stateValues[t],r.valuesChanged&&r.valuesChanged[t]&&(r.valuesChanged=r.valuesChanged[t]),a&&(a=a[t])}else n=null,r={},a=!1}else n=null,r={},a=!1;else this.returnSingleComponent&&(1===n.length?(n=n[0],r.valuesChanged&&r.valuesChanged[0]?r.valuesChanged=r.valuesChanged[0]:delete r.valuesChanged,a=a[0]):(n=null,a=!1));return{value:n,changes:r,usedDefault:a}}checkForCircular(){for(let e of this.upstreamVariableNames)this.dependencyHandler.resetCircularCheckPassed(this.upstreamComponentName,e);for(let e of this.upstreamVariableNames)this.dependencyHandler.checkForCircularDependency({componentName:this.upstreamComponentName,varName:e})}async recalculateDownstreamComponents({force:e=!1}={}){let t=await this.determineDownstreamComponents({force:e}),n=t.downstreamComponentNames,r=n.length!==this.downstreamComponentNames.length||this.downstreamComponentNames.some(((e,t)=>e!=n[t]));if(r){this.componentIdentitiesChanged=!0;let e=0;for(let[t,r]of[...this.downstreamComponentNames].entries())n.includes(r)||(await this.removeDownstreamComponent({indexToRemove:t-e}),e++);for(let[e,r]of n.entries()){let n=this.downstreamComponentNames.indexOf(r);-1!==n?n!==e&&await this.swapDownstreamComponents(n,e):await this.addDownstreamComponent({downstreamComponentName:r,downstreamComponentType:t.downstreamComponentTypes[e],index:e})}}if(this.originalVariablesByComponent)for(let[e,n]of[...this.downstreamComponentNames].entries())(this.mappedDownstreamVariableNamesByComponent[e].length!==this.originalDownstreamVariableNamesByComponent[e].length||this.mappedDownstreamVariableNamesByComponent[e].some(((t,n)=>this.originalDownstreamVariableNamesByComponent[e][n]!==t)))&&(await this.removeDownstreamComponent({indexToRemove:e}),await this.addDownstreamComponent({downstreamComponentName:n,downstreamComponentType:t.downstreamComponentTypes[e],index:e}));return{success:t.success}}}class StateVariableDependency extends Dependency{static dependencyType="stateVariable";setUpParameters(){if(this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName,void 0===this.definition.variableName)throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableName is not defined`);this.originalDownstreamVariableNames=[this.definition.variableName],this.definition.returnAsComponentObject?this.returnSingleComponent=!0:this.returnSingleVariableValue=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}return{success:!0,downstreamComponentNames:[this.componentName],downstreamComponentTypes:[e.componentType]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(StateVariableDependency);class MultipleStateVariablesDependency extends Dependency{static dependencyType="multipleStateVariables";setUpParameters(){if(this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName,!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames,this.returnSingleComponent=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}return{success:!0,downstreamComponentNames:[this.componentName],downstreamComponentTypes:[e.componentType]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(MultipleStateVariablesDependency);class StateVariableComponentTypeDependency extends StateVariableDependency{static dependencyType="stateVariableComponentType";async getValue({verbose:e=!1}={}){let t=[],n={};if(this.staticValue)t=[this.staticValue];else if(this.componentIdentitiesChanged&&(n.componentIdentitiesChanged=!0,this.componentIdentitiesChanged=!1),1===this.downstreamComponentNames.length){let e=this.downstreamComponentNames[0],r=this.dependencyHandler.components[e],a={componentName:r.componentName,componentType:r.componentType,stateValues:{}},i=this.originalDownstreamVariableNames[0],s=this.mappedDownstreamVariableNamesByComponent[0][0],o=this.useMappedVariableNames?s:i;if((!this.variablesOptional||s in r.state)&&!r.state[s].deferred){let e=r.state[s];if(await e.value,a.stateValues[o]=e.componentType,e.isArray&&e.wrappingComponents?.length>0){let t=e.wrappingComponents[e.wrappingComponents.length-1][0];"object"==typeof t&&(t=t.componentType),a.stateValues[o]=t}this.valuesChanged[0][s].changed&&(n.valuesChanged||(n.valuesChanged={}),n.valuesChanged[0]||(n.valuesChanged[0]={}),n.valuesChanged[0][o]=this.valuesChanged[0][s]),this.valuesChanged[0][s]={};let t=e.shadowingInstructions?.hasVariableComponentType;if(!t&&e.isArrayEntry){t=r.state[e.arrayStateVariable].shadowingInstructions?.hasVariableComponentType}t||(this.staticValue=a,await this.removeDownstreamComponent({indexToRemove:0,recordChange:!1}))}t=[a]}if(!e)if(this.returnSingleVariableValue)if(1===t.length){t=t[0];let e=Object.keys(t.stateValues);n.valuesChanged&&n.valuesChanged[0]&&n.valuesChanged[0][0]&&(n.valuesChanged=n.valuesChanged[0][0]),t=1===e.length?t.stateValues[e[0]]:null}else t=null;else this.returnSingleComponent&&(1===t.length?(t=t[0],n.valuesChanged&&n.valuesChanged[0]&&(n.valuesChanged=n.valuesChanged[0])):t=null);return{value:t,changes:n,usedDefault:!1}}}dependencyTypeArray.push(StateVariableComponentTypeDependency);class StateVariableArraySizeDependency extends StateVariableDependency{static dependencyType="stateVariableArraySize";static convertToArraySize=!0}dependencyTypeArray.push(StateVariableArraySizeDependency);class RecursiveDependencyValuesDependency extends Dependency{static dependencyType="recursiveDependencyValues";setUpParameters(){if(this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName,void 0===this.definition.variableNames)throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames is not defined`);this.startingVariableNames=this.definition.variableNames,this.originalVariablesByComponent=!0,this.includeImmediateValueWithValue=this.definition.includeImmediateValueWithValue,this.includeRawValueWithImmediateValue=this.definition.includeRawValueWithImmediateValue,this.includeOnlyEssentialValues=this.definition.includeOnlyEssentialValues,this.variablesOptional=!0}async determineDownstreamComponents({force:e=!1}={}){this.missingComponents=[],this.originalDownstreamVariableNamesByComponent=[];let t=await this.getRecursiveDependencyVariables({componentName:this.componentName,variableNames:this.startingVariableNames,force:e});if(!t.success)return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]};let n=[],r=[];for(let e in t.components)if(this.includeOnlyEssentialValues){let a=[],i=this.dependencyHandler._components[e];for(let n of t.components[e].variableNames)(i.state[n]?.hasEssential||i.state[n]?.isArrayEntry&&i.state[i.state[n].arrayStateVariable].hasEssential)&&a.push(n);a.length>0&&(n.push(e),r.push(t.components[e].componentType),this.originalDownstreamVariableNamesByComponent.push(a))}else n.push(e),r.push(t.components[e].componentType),this.originalDownstreamVariableNamesByComponent.push(t.components[e].variableNames);return{success:!0,downstreamComponentNames:n,downstreamComponentTypes:r}}async getRecursiveDependencyVariables({componentName:e,variableNames:t,force:n,components:r={}}){let a=this.dependencyHandler._components[e];if(!a){if(!this.missingComponents.includes(e)){let t=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[e];t||(t=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[e]=[]),t.includes(this)||t.push(this)}for(let t of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:e,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:t,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:t,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:t});return{success:!1}}this.includeImmediateValueWithValue&&t.includes("value")&&!t.includes("immediateValue")&&"immediateValue"in a.state&&(t=[...t,"immediateValue"]),this.includeRawValueWithImmediateValue&&t.includes("immediateValue")&&!t.includes("rawRendererValue")&&"rawRendererValue"in a.state&&(t=[...t,"rawRendererValue"]);let i=r[e];i||(i=r[e]={componentName:e,componentType:a.componentType,variableNames:[]});let s=this.dependencyHandler.updateTriggers.dependenciesBasedOnDependenciesOfStateVariables[e];s||(s=this.dependencyHandler.updateTriggers.dependenciesBasedOnDependenciesOfStateVariables[e]={});for(let o of t)if(!i.variableNames.includes(o)){i.variableNames.push(o);let t=s[o];t||(t=s[o]=[]),t.includes(this)||t.push(this);let l=a.state[o];if(l){if(!l.isResolved){if(!n){for(let t of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:e,blockerType:"stateVariable",blockerStateVariable:o,componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:t,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:t,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:t});return{success:!1}}await l.value}let t=this.dependencyHandler.downstreamDependencies[a.componentName][o];for(let e in t){let a=t[e];for(let[e,t]of a.downstreamComponentNames.entries()){let i=[];if((a.originalDownstreamVariableNames.length>0||a.originalVariablesByComponent)&&(i=a.mappedDownstreamVariableNamesByComponent[e]),!(await this.getRecursiveDependencyVariables({componentName:t,variableNames:i,force:n,components:r})).success)return{success:!1}}}}}return{success:!0,components:r}}async getValue(){let e;this.gettingValue=!0,this.varsWithUpdatedDeps={};let t={},n=!0,r={};for(;n;){if(n=!1,e=await super.getValue(),e.changes.valuesChanged)if(r.valuesChanged)for(let t in e.changes.valuesChanged){let n=e.changes.valuesChanged[t];if(r.valuesChanged[t])for(let e in n)r.valuesChanged[t][e]=n[e];else r.valuesChanged[t]=n}else r.valuesChanged=e.changes.valuesChanged;for(let e in this.varsWithUpdatedDeps){let r=t[e];r||(r=t[e]=[]);for(let t of this.varsWithUpdatedDeps[e])r.includes(t)||(r.push(t),n=!0)}n&&await this.recalculateDownstreamComponents()}return this.gettingValue=!1,e.changes=r,e}deleteFromUpdateTriggers(){for(let e of this.missingComponents){let t=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[e];if(t){let e=t.indexOf(this);-1!==e&&t.splice(e,1)}}}}dependencyTypeArray.push(RecursiveDependencyValuesDependency);class ComponentIdentityDependency extends Dependency{static dependencyType="componentIdentity";setUpParameters(){this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName,this.returnSingleComponent=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}return{success:!0,downstreamComponentNames:[this.componentName],downstreamComponentTypes:[e.componentType]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(ComponentIdentityDependency);class AttributeComponentDependency extends Dependency{static dependencyType="attributeComponent";setUpParameters(){if(this.definition.parentName?(this.parentName=this.definition.parentName,this.specifiedComponentName=this.parentName):this.parentName=this.upstreamComponentName,this.definition.variableNames){if(!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames}else this.originalDownstreamVariableNames=[];this.attributeName=this.definition.attributeName,this.returnSingleComponent=!0,this.shadowDepth=0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.parentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.parentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}let t=e.attributes[this.attributeName];if(this.shadowDepth=0,t?.component)return{success:!0,downstreamComponentNames:[t.component.componentName],downstreamComponentTypes:[t.component.componentType]};let n=e;for(;n.shadows;){let e=n.shadows,r=n.shadows.propVariable;if(n=this.dependencyHandler._components[e.componentName],!n)break;if(r){if(!n.state[r]?.shadowingInstructions?.attributesToShadow?.includes(this.attributeName)&&!n.constructor.createAttributesObject()[this.attributeName]?.propagateToProps)break}else{let t=this.dependencyHandler._components[e.compositeName];if("sourceAttributesToIgnoreRecursively"in t.state){if((await t.stateValues.sourceAttributesToIgnoreRecursively).includes(this.attributeName))break}if(e.firstLevelReplacement&&"sourceAttributesToIgnore"in t.state){if((await t.stateValues.sourceAttributesToIgnore).includes(this.attributeName))break}}if(this.shadowDepth++,t=n.attributes[this.attributeName],t?.component)return{success:!0,downstreamComponentNames:[t.component.componentName],downstreamComponentTypes:[t.component.componentType]}}return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]}}async getValue({verbose:e}={}){let t=await super.getValue({verbose:e,skipProxy:!0});return t.value&&(t.value.shadowDepth=this.shadowDepth),t}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(AttributeComponentDependency);class ChildDependency extends Dependency{static dependencyType="child";setUpParameters(){if(this.definition.parentName?(this.parentName=this.definition.parentName,this.specifiedComponentName=this.parentName):this.parentName=this.upstreamComponentName,this.definition.variableNames){if(!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames}else this.originalDownstreamVariableNames=[];if(this.childGroups=this.definition.childGroups,!Array.isArray(this.childGroups))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: childGroups must be an array`);void 0!==this.definition.childIndices&&(this.childIndices=this.definition.childIndices.map((e=>Number(e)))),this.skipComponentNames=this.definition.skipComponentNames,this.skipPlaceholders=this.definition.skipPlaceholders,this.proceedIfAllChildrenNotMatched=this.definition.proceedIfAllChildrenNotMatched}async determineDownstreamComponents(){this.downstreamPrimitives?this.previousDownstreamPrimitives=[...this.downstreamPrimitives]:this.previousDownstreamPrimitives=[],this.downstreamPrimitives=[];let e=this.dependencyHandler._components[this.parentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.parentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}let t=this.dependencyHandler.updateTriggers.childDependenciesByParent[this.parentName];t||(t=this.dependencyHandler.updateTriggers.childDependenciesByParent[this.parentName]=[]),t.includes(this)||t.push(this);let n=e.returnMatchedChildIndices(this.childGroups);if(void 0===n)throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: childGroups ${this.childGroups} does not exist.`);if(this.childIndices&&(n=n.filter(((e,t)=>this.childIndices.includes(t)))),!e.childrenMatched&&!this.proceedIfAllChildrenNotMatched){let t=!1;if(e.childrenMatchedWithPlaceholders&&(this.skipPlaceholders&&(n=n.filter((t=>!e.placeholderActiveChildrenIndices.includes(t)))),t=!(!this.skipComponentNames||0!==this.originalDownstreamVariableNames.length)||n.every((t=>!e.placeholderActiveChildrenIndices.includes(t)))),!t){let t=e.unexpandedCompositesNotReady.length>0;if(!t&&e.unexpandedCompositesReady.length>0){for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.parentName,blockerType:"childMatches",blockerStateVariable:e,componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(t){for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.parentName,blockerType:"childMatches",blockerStateVariable:e,componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});let t=[],r=[];for(let a of e.unexpandedCompositesNotReady){if(e.childrenMatchedWithPlaceholders){if(e.placeholderActiveChildrenIndicesByComposite[a].every((e=>!n.includes(e))))continue}this.dependencyHandler._components[a].attributes.createComponentOfType?.primitive?t.push(a):r.push(a)}let a=r;0===a.length&&(a=t);for(let e of a)for(let t of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:e,blockerType:"stateVariable",blockerStateVariable:"readyToExpandWhenResolved",componentNameBlocked:this.upstreamComponentName,typeBlocked:"childMatches",stateVariableBlocked:t});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}}}let r=n.map((t=>e.activeChildren[t]));if(this.compositeReplacementRange=[],e.compositeReplacementActiveRange&&r.length>0){let t=0;for(;t=r){let e=t,i=t;for(;a.lastInd>r&&t=r);)i=t;if(this.compositeReplacementRange.push({compositeName:a.compositeName,target:a.target,firstInd:e,lastInd:i}),t++,t===n.length)break;r=n[t]}t++}}this.shadowDepthByChild=[];for(let t of r){let n=0,r=t,a=e;for(;r?.shadows&&r.shadows.compositeName===a?.shadows?.compositeName;)n++,a=this.dependencyHandler._components[a.shadows.componentName],r=this.dependencyHandler._components[r.shadows.componentName];this.shadowDepthByChild.push(n)}this.activeChildrenIndices=n;let a=[],i=[];for(let[e,t]of r.entries())"object"==typeof t?(this.downstreamPrimitives.push(null),a.push(t.componentName?t.componentName:`__placeholder_${e}`),i.push(t.componentType)):this.downstreamPrimitives.push(t);return{success:!0,downstreamComponentNames:a,downstreamComponentTypes:i}}async getValue({verbose:e}={}){let t=await super.getValue({verbose:e,skipProxy:!0}),n=[],r=0;for(let[e,a]of this.downstreamPrimitives.entries())if(null===a){t.value[r].shadowDepth=this.shadowDepthByChild[e],n.push(t.value[r]),r++}else n.push(a);return n.compositeReplacementRange=this.compositeReplacementRange,t.value=n,(this.downstreamPrimitives.length!==this.previousDownstreamPrimitives.length||this.downstreamPrimitives.some(((e,t)=>e!==this.previousDownstreamPrimitives[t])))&&(t.changes.componentIdentitiesChanged=!0,this.previousDownstreamPrimitives=[...this.downstreamPrimitives]),t}deleteFromUpdateTriggers(){let e=this.dependencyHandler.updateTriggers.childDependenciesByParent[this.parentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(ChildDependency);class DescendantDependency extends Dependency{static dependencyType="descendant";setUpParameters(){if(this.definition.ancestorName?(this.ancestorName=this.definition.ancestorName,this.specifiedComponentName=this.ancestorName):this.ancestorName=this.upstreamComponentName,this.definition.variableNames){if(!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames}else this.originalDownstreamVariableNames=[];this.componentTypes=this.definition.componentTypes,this.recurseToMatchedChildren=this.definition.recurseToMatchedChildren,this.useReplacementsForComposites=this.definition.useReplacementsForComposites,this.includeNonActiveChildren=this.definition.includeNonActiveChildren,this.includeAttributeChildren=this.definition.includeAttributeChildren,this.skipOverAdapters=this.definition.skipOverAdapters,this.ignoreReplacementsOfMatchedComposites=this.definition.ignoreReplacementsOfMatchedComposites,this.ignoreReplacementsOfEncounteredComposites=this.definition.ignoreReplacementsOfEncounteredComposites,null!==this.definition.componentIndex&&void 0!==this.definition.componentIndex&&(Number.isInteger(this.definition.componentIndex)?this.componentIndex=this.definition.componentIndex:this.componentIndex=NaN)}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.ancestorName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.ancestorName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.ancestorName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.ancestorName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}let t=this.dependencyHandler.updateTriggers.descendantDependenciesByAncestor[this.ancestorName];t||(t=this.dependencyHandler.updateTriggers.descendantDependenciesByAncestor[this.ancestorName]=[]),t.includes(this)||t.push(this);let n=this.gatherUnexpandedComposites(e);if(n.haveCompositesNotReady||n.haveUnexpandedCompositeReady){for(let e of this.upstreamVariableNames){await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});for(let t in n.unexpandedCompositesReadyByParentName)await this.dependencyHandler.addBlocker({blockerComponentName:t,blockerType:"childMatches",blockerStateVariable:e,componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName});for(let t in n.unexpandedCompositesNotReadyByParentName)await this.dependencyHandler.addBlocker({blockerComponentName:t,blockerType:"childMatches",blockerStateVariable:e,componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName})}return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}let r=gatherDescendants({ancestor:e,descendantTypes:this.componentTypes,recurseToMatchedChildren:this.recurseToMatchedChildren,useReplacementsForComposites:this.useReplacementsForComposites,includeNonActiveChildren:this.includeNonActiveChildren,skipOverAdapters:this.skipOverAdapters,ignoreReplacementsOfMatchedComposites:this.ignoreReplacementsOfMatchedComposites,ignoreReplacementsOfEncounteredComposites:this.ignoreReplacementsOfEncounteredComposites,componentInfoObjects:this.dependencyHandler.componentInfoObjects});if(void 0!==this.componentIndex){let e=r[this.componentIndex-1];r=e?[e]:[]}return{success:!0,downstreamComponentNames:r.map((e=>e.componentName)),downstreamComponentTypes:r.map((e=>e.componentType))}}gatherUnexpandedComposites(e){let t={},n={},r=!1,a=!1,i=this.skipComponentNames&&0===this.originalDownstreamVariableNames.length;if(!e.childrenMatched)if(e.childrenMatchedWithPlaceholders){if(e.unexpandedCompositesReady.length>0){let n=this.unexpandedCompositesAdjustedForPlacedholders(e.unexpandedCompositesReady,i);n.length>0&&(t[e.componentName]=n,r=!0)}if(e.unexpandedCompositesNotReady.length>0){let t=this.unexpandedCompositesAdjustedForPlacedholders(e.unexpandedCompositesNotReady,i);t.length>0&&(n[e.componentName]=t,a=!0)}}else e.unexpandedCompositesReady.length>0&&(t[e.componentName]=e.unexpandedCompositesReady,r=!0),e.unexpandedCompositesNotReady.length>0&&(n[e.componentName]=e.unexpandedCompositesNotReady,a=!0);for(let i in e.allChildren){let s=e.allChildren[i].component;if("object"==typeof s){let e=this.gatherUnexpandedComposites(s);e.haveUnexpandedCompositeReady&&(Object.assign(t,e.unexpandedCompositesReadyByParentName),r=!0),e.haveCompositesNotReady&&(Object.assign(n,e.unexpandedCompositesNotReadyByParentName),a=!0)}}return{unexpandedCompositesReadyByParentName:t,haveUnexpandedCompositeReady:r,unexpandedCompositesNotReadyByParentName:n,haveCompositesNotReady:a}}unexpandedCompositesAdjustedForPlacedholders(e,t){let n=[];for(let r of e){let e=this.dependencyHandler._components[r];if(e.attributes.createComponentOfType){let a=this.dependencyHandler.componentInfoObjects.componentTypeLowerCaseMapping[e.attributes.createComponentOfType.primitive.toLowerCase()],i=this.componentTypes.some((e=>this.dependencyHandler.componentInfoObjects.isInheritedComponentType({inheritedComponentType:a,baseComponentType:e})));i&&t||n.push(r)}else n.push(r)}return n}deleteFromUpdateTriggers(){let e=this.dependencyHandler.updateTriggers.descendantDependenciesByAncestor[this.ancestorName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(DescendantDependency);class ParentDependency extends Dependency{static dependencyType="parentStateVariable";setUpParameters(){if(this.definition.childName?(this.childName=this.definition.childName,this.specifiedComponentName=this.childName):this.childName=this.upstreamComponentName,!this.definition.variableName)throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: must have a variableName`);this.originalDownstreamVariableNames=[this.definition.variableName],this.definition.parentComponentType&&(this.parentComponentType=this.definition.parentComponentType),this.returnSingleVariableValue=!0,this.variablesOptional=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.childName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.childName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.childName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.childName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!e.parentName)return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};this.parentName=e.parentName;let t=this.dependencyHandler._components[this.parentName];if(!t){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.parentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(this.parentComponentType&&!this.dependencyHandler.componentInfoObjects.isInheritedComponentType({inheritedComponentType:t.componentType,baseComponentType:this.parentComponentType}))return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};let n=this.dependencyHandler.updateTriggers.parentDependenciesByParent[this.parentName];return n||(n=this.dependencyHandler.updateTriggers.parentDependenciesByParent[this.parentName]=[]),n.includes(this)||n.push(this),{success:!0,downstreamComponentNames:[this.parentName],downstreamComponentTypes:[t.componentType]}}deleteFromUpdateTriggers(){let e=this.dependencyHandler.updateTriggers.parentDependenciesByParent[this.parentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}let t=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName];if(t){let e=t.indexOf(this);-1!==e&&t.splice(e,1)}}}dependencyTypeArray.push(ParentDependency);class ParentIdentityDependency extends Dependency{static dependencyType="parentIdentity";setUpParameters(){this.definition.childName?(this.childName=this.definition.childName,this.specifiedComponentName=this.childName):this.childName=this.upstreamComponentName,this.definition.parentComponentType&&(this.parentComponentType=this.definition.parentComponentType),this.returnSingleComponent=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.childName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.childName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.childName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.childName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!e.parentName)return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};this.parentName=e.parentName;let t=this.dependencyHandler._components[this.parentName];if(!t){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.parentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(this.parentComponentType&&!this.dependencyHandler.componentInfoObjects.isInheritedComponentType({inheritedComponentType:t.componentType,baseComponentType:this.parentComponentType}))return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};let n=this.dependencyHandler.updateTriggers.parentDependenciesByParent[this.parentName];return n||(n=this.dependencyHandler.updateTriggers.parentDependenciesByParent[this.parentName]=[]),n.includes(this)||n.push(this),{success:!0,downstreamComponentNames:[this.parentName],downstreamComponentTypes:[t.componentType]}}deleteFromUpdateTriggers(){let e=this.dependencyHandler.updateTriggers.parentDependenciesByParent[this.parentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}let t=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName];if(t){let e=t.indexOf(this);-1!==e&&t.splice(e,1)}}}dependencyTypeArray.push(ParentIdentityDependency);class AncestorDependency extends Dependency{static dependencyType="ancestor";setUpParameters(){if(this.definition.descendantName?(this.descendantName=this.definition.descendantName,this.specifiedComponentName=this.descendantName):this.descendantName=this.upstreamComponentName,this.definition.variableNames){if(!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames}else this.originalDownstreamVariableNames=[];this.returnSingleComponent=!0,this.definition.componentType&&(this.componentType=this.definition.componentType)}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.descendantName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.descendantName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.descendantName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.descendantName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!(this.dependencyHandler.core.documentName in this.dependencyHandler._components)){for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e}),await this.dependencyHandler.addBlocker({blockerComponentName:this.dependencyHandler.core.documentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}let t=this.findMatchingAncestor(e);if(t.missingComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[t.missingComponentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[t.missingComponentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:t.missingComponentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}for(let e of t.ancestorsExamined){let t=this.dependencyHandler.updateTriggers.ancestorDependenciesByPotentialAncestor[e];t||(t=this.dependencyHandler.updateTriggers.ancestorDependenciesByPotentialAncestor[e]=[]),t.includes(this)||t.push(this)}return this.ancestorResults=t,t.ancestorFound?{success:!0,downstreamComponentNames:[t.ancestorFound.componentName],downstreamComponentTypes:[t.ancestorFound.componentClass.componentType]}:{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]}}findMatchingAncestor(e){let t=[];if(this.componentType){for(let n of e.ancestors){let e=this.dependencyHandler._components[n.componentName];if(!e)return{missingComponentName:n.componentName};if(t.push(n.componentName),this.dependencyHandler.componentInfoObjects.isInheritedComponentType({inheritedComponentType:e.componentType,baseComponentType:this.componentType}))return{ancestorsExamined:t,ancestorFound:n}}return{ancestorsExamined:t}}if(0===this.originalDownstreamVariableNames.length)return console.warn(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: must specify componentType or variableNames to find ancestor`),{ancestorsExamined:t};let n=this.originalDownstreamVariableNames;for(let r of e.ancestors){let e=this.dependencyHandler._components[r.componentName];if(!e)return{missingComponentName:r.componentName};t.push(r.componentName);let a=!0;for(let t of n)if(!(t in e.state)&&!this.dependencyHandler.core.checkIfArrayEntry({stateVariable:t,component:e})){a=!1;break}if(a)return{ancestorsExamined:t,ancestorFound:r}}return{ancestorsExamined:t}}deleteFromUpdateTriggers(){for(let e of this.ancestorResults.ancestorsExamined){let t=this.dependencyHandler.updateTriggers.ancestorDependenciesByPotentialAncestor[e];if(t){let e=t.indexOf(this);-1!==e&&t.splice(e,1)}}if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}if(this.ancestorResults&&this.ancestorResults.missingComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.ancestorResults.missingComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(AncestorDependency);class ReplacementDependency extends Dependency{static dependencyType="replacement";setUpParameters(){if(this.definition.compositeName?(this.compositeName=this.definition.compositeName,this.specifiedComponentName=this.compositeName):this.compositeName=this.upstreamComponentName,this.definition.variableNames){if(!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames}else this.originalDownstreamVariableNames=[];this.recursive=this.definition.recursive,this.recurseNonStandardComposites=this.definition.recurseNonStandardComposites,null!==this.definition.componentIndex&&void 0!==this.definition.componentIndex&&(Number.isInteger(this.definition.componentIndex)?this.componentIndex=this.definition.componentIndex:this.componentIndex=NaN),this.definition.targetSubnames&&(this.targetSubnames=this.definition.targetSubnames),this.definition.targetSubnamesComponentIndex&&(this.definition.targetSubnamesComponentIndex.every(Number.isInteger)?this.targetSubnamesComponentIndex=this.definition.targetSubnamesComponentIndex:this.targetSubnamesComponentIndex=[NaN]),this.includeWithheldReplacements=this.definition.includeWithheldReplacements,this.expandReplacements=!0}async determineDownstreamComponents(){this.replacementPrimitives?this.previousReplacementPrimitives=[...this.replacementPrimitives]:this.previousReplacementPrimitives=[],this.replacementPrimitives=[];let e=this.dependencyHandler._components[this.compositeName];if(!e){let a=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.compositeName];a||(a=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.compositeName]=[]),a.includes(this)||a.push(this);for(let i of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.compositeName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:i,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:i,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:i});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!e.isExpanded){for(let s of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:s,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:s}),await this.dependencyHandler.addBlocker({blockerComponentName:this.compositeName,blockerType:"expandComposite",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:s,dependencyBlocked:this.dependencyName});return e.state.readyToExpandWhenResolved.isResolved||await this.dependencyHandler.addBlocker({blockerComponentName:this.compositeName,blockerType:"stateVariable",blockerStateVariable:"readyToExpandWhenResolved",componentNameBlocked:this.compositeName,typeBlocked:"expandComposite"}),{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}this.compositesFound=[this.compositeName];let t=e.replacements;if(!this.includeWithheldReplacements&&e.replacementsToWithhold>0&&(t=t.slice(0,-e.replacementsToWithhold)),this.recursive){let o=this.dependencyHandler.core.recursivelyReplaceCompositesWithReplacements({replacements:t,recurseNonStandardComposites:this.recurseNonStandardComposites,includeWithheldReplacements:this.includeWithheldReplacements});if(o.unexpandedCompositesNotReady.length>0||o.unexpandedCompositesReady.length>0){for(let l of this.upstreamVariableNames){await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:l,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:l});for(let u of[...o.unexpandedCompositesReady,...o.unexpandedCompositesNotReady])await this.dependencyHandler.addBlocker({blockerComponentName:u,blockerType:"expandComposite",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:l,dependencyBlocked:this.dependencyName})}for(let c of o.unexpandedCompositesNotReady)await this.dependencyHandler.addBlocker({blockerComponentName:c,blockerType:"stateVariable",blockerStateVariable:"readyToExpandWhenResolved",componentNameBlocked:c,typeBlocked:"expandComposite"});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}t=o.newReplacements,this.compositesFound.push(...o.compositesFound)}for(let p of this.compositesFound){let d=this.dependencyHandler.updateTriggers.replacementDependenciesByComposite[p];d||(d=this.dependencyHandler.updateTriggers.replacementDependenciesByComposite[p]=[]),d.includes(this)||d.push(this)}if(void 0!==this.componentIndex){let m=t[this.componentIndex-1];t=m?[m]:[]}if(this.targetSubnames){function h({components:e,subNames:t,subNamesComponentIndex:n,dep:r}){if(0===t.length)return e;let a=t.slice(1),i=[];for(let s of e){let e=s.componentName+"/"+t[0],o=r.dependencyHandler._components[e];if(o)r.dependencyHandler.componentInfoObjects.isInheritedComponentType({inheritedComponentType:o.componentType,baseComponentType:"_composite"})?console.warn("Have not yet implemented recursing subnames to multiple levels of composites"):0===a.length&&(n?.length,1)&&i.push(o);else{let t=r.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[e];t||(t=r.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[e]=[]),t.includes(r)||t.push(r)}}return i}t=h({components:t,subNames:this.targetSubnames,subNamesComponentIndex:this.targetSubnamesComponentIndex,dep:this})}let n=[],r=[];for(let f of t)"object"==typeof f?(this.replacementPrimitives.push(null),n.push(f.componentName),r.push(f.componentType)):this.replacementPrimitives.push(f);return{success:!0,downstreamComponentNames:n,downstreamComponentTypes:r}}async getValue({verbose:e}={}){let t=await super.getValue({verbose:e,skipProxy:!0}),n=[],r=0;for(let e of this.replacementPrimitives)null===e?(n.push(t.value[r]),r++):n.push(e);return t.value=n,(this.replacementPrimitives.length!==this.previousReplacementPrimitives.length||this.replacementPrimitives.some(((e,t)=>e!==this.previousReplacementPrimitives[t])))&&(t.changes.componentIdentitiesChanged=!0,this.previousReplacementPrimitives=[...this.replacementPrimitives]),t}deleteFromUpdateTriggers(){if(this.compositesFound)for(let e of this.compositesFound){let t=this.dependencyHandler.updateTriggers.replacementDependenciesByComposite[e];if(t){let e=t.indexOf(this);-1!==e&&t.splice(e,1)}}if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(ReplacementDependency);class SourceCompositeStateVariableDependency extends Dependency{static dependencyType="sourceCompositeStateVariable";setUpParameters(){if(this.definition.replacementName?(this.replacementName=this.definition.replacementName,this.specifiedComponentName=this.replacementName):this.replacementName=this.upstreamComponentName,!this.definition.variableName)throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: must have a variableName`);this.originalDownstreamVariableNames=[this.definition.variableName],this.definition.compositeComponentType&&(this.compositeComponentType=this.definition.compositeComponentType),this.returnSingleVariableValue=!0,this.variablesOptional=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.replacementName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.replacementName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.replacementName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.replacementName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!e.replacementOf)return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};let t=e.replacementOf;if(this.compositeComponentType)for(;!this.dependencyHandler.componentInfoObjects.isInheritedComponentType({inheritedComponentType:t.componentType,baseComponentType:this.compositeComponentType});){if(!t.replacementOf)return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};t=t.replacementOf}return{success:!0,downstreamComponentNames:[t.componentName],downstreamComponentTypes:[t.componentType]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(SourceCompositeStateVariableDependency);class SourceCompositeIdentityDependency extends Dependency{static dependencyType="sourceCompositeIdentity";setUpParameters(){this.definition.replacementName?(this.replacementName=this.definition.replacementName,this.specifiedComponentName=this.replacementName):this.replacementName=this.upstreamComponentName,this.returnSingleComponent=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.replacementName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.replacementName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.replacementName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.replacementName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!e.replacementOf)return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};let t=e.replacementOf;return{success:!0,downstreamComponentNames:[t.componentName],downstreamComponentTypes:[t.componentType]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(SourceCompositeIdentityDependency);class ShadowSourceDependency extends Dependency{static dependencyType="shadowSource";setUpParameters(){if(this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName,this.definition.variableNames){if(!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames}else this.originalDownstreamVariableNames=[];this.returnSingleComponent=!0,this.variablesOptional=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!e.shadows)return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};let t=e.shadows.componentName,n=this.dependencyHandler._components[t];return n?{success:!0,downstreamComponentNames:[n.componentName],downstreamComponentTypes:[n.componentType]}:{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(ShadowSourceDependency);class UnlinkedCopySourceDependency extends Dependency{static dependencyType="unlinkedCopySource";setUpParameters(){if(this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName,this.definition.variableNames){if(!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames}else this.originalDownstreamVariableNames=[];this.returnSingleComponent=!0,this.variablesOptional=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!e.unlinkedCopySource)return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};let t=e.unlinkedCopySource,n=this.dependencyHandler._components[t];return n?{success:!0,downstreamComponentNames:[n.componentName],downstreamComponentTypes:[n.componentType]}:{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(UnlinkedCopySourceDependency);class PrimaryShadowDependency extends Dependency{static dependencyType="primaryShadow";setUpParameters(){if(this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName,this.definition.variableNames){if(!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames}else this.originalDownstreamVariableNames=[];this.returnSingleComponent=!0,this.variablesOptional=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}let t=this.dependencyHandler.updateTriggers.primaryShadowDependencies[this.componentName];if(t||(t=this.dependencyHandler.updateTriggers.primaryShadowDependencies[this.componentName]=[]),t.includes(this)||t.push(this),!e.primaryShadow)return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};let n=e.primaryShadow,r=this.dependencyHandler._components[n];return r?{success:!0,downstreamComponentNames:[r.componentName],downstreamComponentTypes:[r.componentType]}:{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(PrimaryShadowDependency);class AdapterSourceStateVariableDependency extends Dependency{static dependencyType="adapterSourceStateVariable";setUpParameters(){if(this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName,!this.definition.variableName)throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: must have a variableName`);this.originalDownstreamVariableNames=[this.definition.variableName],this.returnSingleVariableValue=!0,this.variablesOptional=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!e.adaptedFrom)return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};let t=e.adaptedFrom;return{success:!0,downstreamComponentNames:[t.componentName],downstreamComponentTypes:[t.componentType]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(AdapterSourceStateVariableDependency);class AdapterSourceDependency extends Dependency{static dependencyType="adapterSource";setUpParameters(){if(this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName,this.definition.variableNames){if(!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames}else this.originalDownstreamVariableNames=[];this.returnSingleComponent=!0,this.variablesOptional=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!e.adaptedFrom)return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};let t=e.adaptedFrom;return{success:!0,downstreamComponentNames:[t.componentName],downstreamComponentTypes:[t.componentType]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(AdapterSourceDependency);class CountAmongSiblingsDependency extends Dependency{static dependencyType="countAmongSiblingsOfSameType";setUpParameters(){this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!e.parentName)return console.warn(`component ${this.componentName} does not have a parent for state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}.`),{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};this.parentName=e.parentName;let t=this.dependencyHandler._components[this.parentName];if(!t){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.parentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}let n=this.dependencyHandler.updateTriggers.childDependenciesByParent[this.parentName];if(n||(n=this.dependencyHandler.updateTriggers.childDependenciesByParent[this.parentName]=[]),n.includes(this)||n.push(this),!t.childrenMatched){if(!t.childrenMatchedWithPlaceholders){let e=t.unexpandedCompositesNotReady.length>0;if(!e&&t.unexpandedCompositesReady.length>0){for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.parentName,blockerType:"childMatches",blockerStateVariable:e,componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(e){for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.parentName,blockerType:"childMatches",blockerStateVariable:e,componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});for(let e of t.unexpandedCompositesNotReady)for(let t of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:e,blockerType:"stateVariable",blockerStateVariable:"readyToExpandWhenResolved",componentNameBlocked:this.upstreamComponentName,typeBlocked:"childMatches",stateVariableBlocked:t});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}}}return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]}}deleteFromUpdateTriggers(){let e=this.dependencyHandler.updateTriggers.childDependenciesByParent[this.parentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}let t=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName];if(t){let e=t.indexOf(this);-1!==e&&t.splice(e,1)}}async getValue(){let e=this.dependencyHandler.components[this.upstreamComponentName].componentType,t=this.dependencyHandler.components[this.parentName].activeChildren.filter((t=>t.componentType===e)),n=t.map((e=>e.componentName)).indexOf(this.upstreamComponentName)+1;if(this.parentName===this.dependencyHandler.core.documentName){let t=this.dependencyHandler.core.previousComponentTypeCounts[e];t&&(n+=t)}return{value:n,changes:{}}}}dependencyTypeArray.push(CountAmongSiblingsDependency);class AttributeTargetComponentNamesDependency extends StateVariableDependency{static dependencyType="attributeTargetComponentNames";setUpParameters(){this.attributeName=this.definition.attributeName,this.definition.parentName?(this.componentName=this.definition.parentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName}async getValue(){let e=null,t={};if(this.componentIdentitiesChanged&&(t.componentIdentitiesChanged=!0,this.componentIdentitiesChanged=!1),1===this.downstreamComponentNames.length){let t=this.dependencyHandler.components[this.componentName];t&&(e=t.attributes[this.attributeName],e=e?e.targetComponentNames:null)}return{value:e,changes:t}}}dependencyTypeArray.push(AttributeTargetComponentNamesDependency);class TargetComponentDependency extends Dependency{static dependencyType="targetComponent";setUpParameters(){let e=this.dependencyHandler._components[this.upstreamComponentName];if(this.target=e.doenetAttributes.target,this.target&&(this.targetComponentName=this.specifiedComponentName=e.doenetAttributes.targetComponentName),this.definition.variableNames){if(!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames}else this.originalDownstreamVariableNames=[];this.returnSingleComponent=!0}async determineDownstreamComponents(){if(!this.target)return{downstreamComponentNames:[],downstreamComponentTypes:[]};let e=this.dependencyHandler._components[this.targetComponentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.targetComponentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.targetComponentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.targetComponentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}return{success:!0,downstreamComponentNames:[this.targetComponentName],downstreamComponentTypes:[e.componentType]}}deleteFromUpdateTriggers(){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}dependencyTypeArray.push(TargetComponentDependency);class ValueDependency extends Dependency{static dependencyType="value";setUpParameters(){this.value=this.definition.value}async getValue(){return{value:this.value,changes:{}}}}dependencyTypeArray.push(ValueDependency);class FlagDependency extends ValueDependency{static dependencyType="flag";setUpParameters(){this.flagName=this.definition.flagName,this.value=this.dependencyHandler.core.flags[this.flagName]}}dependencyTypeArray.push(FlagDependency);class DoenetAttributeDependency extends StateVariableDependency{static dependencyType="doenetAttribute";setUpParameters(){this.attributeName=this.definition.attributeName,this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName}async getValue(){let e=null,t={};if(this.componentIdentitiesChanged&&(t.componentIdentitiesChanged=!0,this.componentIdentitiesChanged=!1),1===this.downstreamComponentNames.length){e=this.dependencyHandler.components[this.downstreamComponentNames[0]].doenetAttributes[this.attributeName]}return{value:e,changes:t}}}dependencyTypeArray.push(DoenetAttributeDependency);class AttributePrimitiveDependency extends StateVariableDependency{static dependencyType="attributePrimitive";setUpParameters(){this.attributeName=this.definition.attributeName,this.definition.parentName?(this.componentName=this.definition.parentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName}async getValue(){let e=null,t={};if(this.componentIdentitiesChanged&&(t.componentIdentitiesChanged=!0,this.componentIdentitiesChanged=!1),1===this.downstreamComponentNames.length){let t=this.dependencyHandler.components[this.componentName];t&&(e=t.attributes[this.attributeName],e=e?e.primitive:null)}return{value:e,changes:t}}}dependencyTypeArray.push(AttributePrimitiveDependency);class SerializedChildrenDependency extends Dependency{static dependencyType="serializedChildren";setUpParameters(){this.definition.parentName?(this.parentName=this.definition.parentName,this.specifiedComponentName=this.parentName):this.parentName=this.upstreamComponentName}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.parentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.parentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}return{success:!0,downstreamComponentNames:[this.parentName],downstreamComponentTypes:[e.componentType]}}async getValue(){return{value:this.dependencyHandler._components[this.parentName].serializedChildren,changes:{}}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(SerializedChildrenDependency);class DoenetMLDependency extends Dependency{static dependencyType="doenetML";setUpParameters(){this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName,this.displayOnlyChildren=this.definition.displayOnlyChildren}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}return{success:!0,downstreamComponentNames:[this.componentName],downstreamComponentTypes:[e.componentType]}}async getValue(){return{value:this.dependencyHandler.core.requestComponentDoenetML(this.componentName,this.displayOnlyChildren),changes:{}}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(DoenetMLDependency);class VariantsDependency extends Dependency{static dependencyType="variants";setUpParameters(){this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}return{success:!0,downstreamComponentNames:[this.componentName],downstreamComponentTypes:[e.componentType]}}async getValue(){return{value:this.dependencyHandler._components[this.componentName].variants,changes:{}}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(VariantsDependency);class CounterDependency extends Dependency{static dependencyType="counter";setUpParameters(){this.counterName=this.definition.counterName,this.componentName=this.upstreamComponentName}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName],t=e.counters[this.counterName];return t||(t=e.counters[this.counterName]={dependencies:[],componentList:[],value:null}),t.dependencies.includes(this)||t.dependencies.push(this),await this.dependencyHandler.collateCountersAndPropagateToAncestors(e),{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]}}async getValue(){return{value:this.dependencyHandler._components[this.componentName].counters[this.counterName].value,changes:{}}}}dependencyTypeArray.push(CounterDependency);class DetermineDependenciesDependency extends Dependency{static dependencyType="determineDependencies";setUpParameters(){if(this.recalculateDependencies=!0,this.definition.componentName?this.componentName=this.definition.componentName:this.componentName=this.upstreamComponentName,void 0===this.definition.variableNames)throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames is not defined`);this.originalDownstreamVariableNames=this.definition.variableNames,this.returnSingleComponent=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"determineDependencies",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!0,downstreamComponentNames:[this.componentName],downstreamComponentTypes:[e.componentType]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}async markStale(){let e=this.dependencyHandler._components[this.upstreamComponentName];for(let t of this.upstreamVariableNames)if(!(e&&e.state[t]&&e.state[t].currentlyResolving)){await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"determineDependencies",blockerStateVariable:t,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:t});for(let e in this.dependencyHandler.downstreamDependencies[this.upstreamComponentName][t]){"determineDependencies"!==this.dependencyHandler.downstreamDependencies[this.upstreamComponentName][t][e].dependencyType&&await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"determineDependencies",blockerStateVariable:t,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:t,dependencyBlocked:e})}}}}dependencyTypeArray.push(DetermineDependenciesDependency);class FileDependency extends Dependency{static dependencyType="file";setUpParameters(){this.cid=this.definition.cid,this.uri=this.definition.uri,this.fileType=this.definition.fileType}async getValue(){let e;if(this.cid){if("csv"!==this.fileType.toLowerCase())return{value:null,changes:{}};return e="csv",{value:await retrieveTextFileForCid(this.cid,e),changes:{}}}{let e=await fetch(this.uri);if(e.ok){return{value:await e.text(),changes:{}}}return{value:null,changes:{}}}}}dependencyTypeArray.push(FileDependency);var appliedFunctionSymbolsDefault=["abs","exp","log","ln","log10","sign","sqrt","erf","cos","cosh","acos","acosh","arccos","arccosh","cot","coth","acot","acoth","arccot","arccoth","csc","csch","acsc","acsch","arccsc","arccsch","sec","sech","asec","asech","arcsec","arcsech","sin","sinh","asin","asinh","arcsin","arcsinh","tan","tanh","atan","atan2","atanh","arctan","arctanh","arg","min","max","mean","median","floor","ceil","round","sum","prod","variance","std","count","mod","re","im","det","trace","nPr","nCr"],appliedFunctionSymbolsDefaultLatex=["abs","exp","log","ln","log10","sign","sqrt","erf","cos","cosh","acos","acosh","arccos","arccosh","cot","coth","acot","acoth","arccot","arccoth","csc","csch","acsc","acsch","arccsc","arccsch","sec","sech","asec","asech","arcsec","arcsech","sin","sinh","asin","asinh","arcsin","arcsinh","tan","tanh","atan","atan2","atanh","arctan","arctanh","arg","min","max","mean","median","floor","ceil","round","sum","prod","variance","std","count","mod","Re","Im","det","trace","nPr","nCr"];let allowedLatexSymbols=["alpha","beta","gamma","Gamma","delta","Delta","epsilon","zeta","eta","theta","Theta","iota","kappa","lambda","Lambda","mu","nu","xi","Xi","pi","Pi","rho","sigma","Sigma","tau","Tau","upsilon","Upsilon","phi","Phi","chi","psi","Psi","omega","Omega","partial","varnothing","emptyset","angle","circ","$","%"];var textToAst$1=new me$3.converters.textToAstObj({appliedFunctionSymbols:appliedFunctionSymbolsDefault});function getFromText({functionSymbols:e,appliedFunctionSymbols:t=appliedFunctionSymbolsDefault,splitSymbols:n=!0,parseScientificNotation:r=!1}){return a=>me$3.fromAst(new me$3.converters.textToAstObj({appliedFunctionSymbols:t,functionSymbols:e,splitSymbols:n,parseScientificNotation:r}).convert(a))}var latexToAst=new me$3.converters.latexToAstObj({appliedFunctionSymbols:appliedFunctionSymbolsDefaultLatex,allowedLatexSymbols:allowedLatexSymbols});function getFromLatex({functionSymbols:e,appliedFunctionSymbols:t=appliedFunctionSymbolsDefaultLatex,splitSymbols:n=!0,parseScientificNotation:r=!1}){return n?n=>me$3.fromAst(new me$3.converters.latexToAstObj({appliedFunctionSymbols:t,functionSymbols:e,allowedLatexSymbols:allowedLatexSymbols,parseScientificNotation:r}).convert(wrapWordIncludingNumberWithVar(n,r))):n=>me$3.fromAst(new me$3.converters.latexToAstObj({appliedFunctionSymbols:t,functionSymbols:e,allowedLatexSymbols:allowedLatexSymbols,parseScientificNotation:r}).convert(wrapWordWithVar(n,r)))}function normalizeMathExpression({value:e,simplify:t,expand:n=!1,createVectors:r=!1,createIntervals:a=!1}){return r&&(e=e.tuples_to_vectors()),a&&(e=e.to_intervals()),n&&(e=e.expand()),"full"===t?e.simplify():"numbers"===t?e.evaluate_numbers():"numberspreserveorder"===t?e.evaluate_numbers({skip_ordering:!0}):e}function findFiniteNumericalValue(e){if(void 0!==e)return Number.isFinite(e)||void 0!==e.evaluate_to_constant&&(e=e.evaluate_to_constant(),Number.isFinite(e))?e:null}function convertValueToMathExpression(e){return e instanceof me$3.class?e:"number"==typeof e||"string"==typeof e||Array.isArray(e)?me$3.fromAst(e):me$3.fromAst("_")}function returnNVariables(e,t){if(!Number.isInteger(e)||e<1)return[];let n=t.length;if(0===n){if(1===e)return[me$3.fromAst("x")];if(2===e)return[me$3.fromAst("x"),me$3.fromAst("y")];if(3===e)return[me$3.fromAst("x"),me$3.fromAst("y"),me$3.fromAst("z")];{let t=[];for(let n=1;n<=e;n++)t.push(me$3.fromAst(textToAst$1.convert(`x_${n}`)));return t}}if(new Set(t.map((e=>e.toString()))).sizee.toString()))],a=[...t];for(let t=n+1;t<=e;t++){let n;n=1==t?e>3?["x_1"]:["x"]:2==t?e>3?["x_2","y_2"]:["y","x_2"]:3==t?e>3?["x_3","y_3","z_3"]:["z","x_3","z_3"]:["x","y","z","u","v","w","X","Y","Z"].map((e=>`${e}_${t}`));let i=!1;for(let e of n)if(!r.includes(e)){a.push(me$3.fromAst(textToAst$1.convert(e))),r.push(e),i=!0;break}if(!i){let e=n[0];a.push(me$3.fromAst(textToAst$1.convert(e))),r.push(e),console.warn("Variables added were not unique")}}return a}async function preprocessMathInverseDefinition({desiredValue:e,stateValues:t,variableName:n="value",arrayKey:r,workspace:a}){if(!vectorOperators.includes(e.tree[0])||!e.tree.includes())return{desiredValue:e};let i,s=n+"Ast";if(void 0!==r&&(s+=`_${r}`),a[s])i=a[s].slice(0,e.tree.length);else{let a=await t[n];a&&void 0!==r&&(a=a[r]),a&&vectorOperators.includes(a.tree[0])&&(i=a.tree.slice(0,e.tree.length))}if(i){let t=[],n=!1;for(let[r,a]of e.tree.entries())void 0===a?(n=!0,t.push(r)):i[r]=a;return e=me$3.fromAst(i),a[s]=i,n?{desiredValue:e,vectorComponentsNotAffected:t}:{desiredValue:e}}{let t=[];for(let n of e.tree.slice(1))void 0===n?t.push("_"):t.push(n);return{desiredValue:e=me$3.fromAst([e.tree[0],...t])}}}function normalizeLatexString(e,{unionFromU:t=!1}={}){let n=[["α","\\alpha "],["β","\\beta "],["ϐ","\\beta "],["Γ","\\Gamma "],["γ","\\gamma "],["Δ","\\Delta "],["δ","\\delta "],["ε","\\epsilon "],["ϵ","\\epsilon "],["ζ","\\zeta "],["η","\\eta "],["Θ","\\Theta "],["ϴ","\\Theta "],["θ","\\theta "],["ᶿ","\\theta "],["ϑ","\\theta "],["ι","\\iota "],["κ","\\kappa "],["Λ","\\Lambda "],["λ","\\lambda "],["μ","\\mu "],["µ","\\mu "],["ν","\\nu "],["Ξ","\\Xi "],["ξ","\\xi "],["Π","\\Pi "],["π","\\pi "],["ϖ","\\pi "],["ρ","\\rho "],["ϱ","\\rho "],["Σ","\\Sigma "],["σ","\\sigma "],["ς","\\sigma "],["τ","\\tau "],["Υ","\\Upsilon "],["υ","\\upsilon "],["Φ","\\Phi "],["φ","\\phi "],["ϕ","\\phi "],["Ψ","\\Psi "],["ψ","\\psi "],["Ω","\\Omega "],["ω","\\omega "],["−","-"],["⋅"," \\cdot "],["·"," \\cdot "],["∪"," \\cup "],["∩"," \\cap "],["∞"," \\infty "],["∅"," \\emptyset "]];for(let t of n)e=e.replaceAll(t[0],t[1]);let r=e.match(/^(\\ )*(\\ldots|\.(\\ )*\.(\\ )*\.)(\\ )*(.*)$/);if(r){let t=r[6];e=","!==t[0]?"\\ldots,"+t:"\\ldots"+t}let a=e.match(/^(.*?)(\\ )*(\\ldots|\.(\\ )*\.(\\ )*\.)(\\ )*$/);if(a){let t=a[1];e=","!==t[t.length-1]?t+",\\ldots":t+"\\ldots"}return e=(e=e.replaceAll(/(\b|\\ )or(\b|\\ )/g,"$1\\lor$2")).replaceAll(/(\b|\\ )and(\b|\\ )/g,"$1\\land$2"),t&&(e=e.replaceAll(/(\b|\\ )U(\b|\\ )/g,"$1\\cup$2")),e}function isValidVariable(e){let t=e.tree,n=!0;return"string"==typeof t?"_"===t&&(n=!1):(!Array.isArray(t)||"_"!==t[0]||"string"!=typeof t[1]||"string"!=typeof t[2]&&"number"!=typeof t[2])&&(n=!1),n}function mathStateVariableFromNumberStateVariable({numberVariableName:e="number",mathVariableName:t="math",isPublic:n=!1}={}){let r={returnDependencies:()=>({number:{dependencyType:"stateVariable",variableName:e}}),definition:function({dependencyValues:e}){return{setValue:{[t]:numberToMathExpression(e.number)}}},inverseDefinition:function({desiredStateVariableValues:e}){let n=e[t].evaluate_to_constant();return null===n&&(n=NaN),{success:!0,instructions:[{setDependency:"number",desiredValue:n}]}}};return n&&(r.public=!0,r.shadowingInstructions={createComponentOfType:"math"}),r}function numberToMathExpression(e){let t;if("number"==typeof e?.re&&"number"==typeof e?.im)if(0===e.im)t=e.re;else{let n;n=1===e.im?"i":-1===e.im?["-","i"]:["*",e.im,"i"],t=0===e.re?n:["+",e.re,n]}else t=e;return me$3.fromAst(t)}function roundForDisplay({value:e,dependencyValues:t,usedDefault:n}){let r;return!n.displayDigits&&t.displayDigits>=1||n.displayDecimals||!Number.isFinite(t.displayDecimals)?(r=t.displayDigits>=1?me$3.round_numbers_to_precision(e,t.displayDigits):me$3.round_numbers_to_precision(e,10),t.displaySmallAsZero>0&&(r=me$3.evaluate_numbers(r,{skip_ordering:!0,set_small_zero:t.displaySmallAsZero}))):r=me$3.round_numbers_to_decimals(e,t.displayDecimals),r}function mergeListsWithOtherContainers(e){if(!Array.isArray(e))return e;let t=e[0],n=e.slice(1);return[...vectorOperators,"list","set"].includes(t)&&(n=n.reduce(((e,t)=>Array.isArray(t)&&"list"===t[0]?[...e,...t.slice(1)]:[...e,t]),[])),n=n.map((e=>mergeListsWithOtherContainers(e))),[t,...n]}function wrapWordWithVar(e,t){let n="",r=/\\operatorname\s*{[^{}]*}/,a=e.match(r);for(;a;){let i=a.index,s=i+a[0].length;n+=wrapWordWithVarSub(e.substring(0,i),t),n+=e.substring(i,s),a=(e=e.substring(s)).match(r)}return n+=wrapWordWithVarSub(e,t),n}function wrapWordWithVarSub(e,t){let n="";const r=/([^a-zA-Z0-9]?)([a-zA-Z][a-zA-Z0-9]+)([^a-zA-Z0-9]?)/;let a;if(t){const e="(E[+\\-]?[0-9]+\\s*($|(?=\\,|&|\\||\\\\\\||\\)|\\}|\\\\}|\\]|\\\\\\\\|\\\\end)))";a=new RegExp("([0-9]+(\\.[0-9]*)?"+e+")|(\\.[0-9]+"+e+")")}let i=e.match(r);for(;i;){let s=i.index,o=s+i[0].length-i[3].length;if(t){let t=e.match(a);if(t&&t.indexs){n+=e.substring(0,o),i=(e=e.substring(o)).match(r);continue}}if("\\"===i[1])n+=e.substring(0,o),e=e.substring(o);else{let t=s+i[1].length;n+=e.substring(0,t),n+=`\\operatorname{${i[2]}}`,e=e.substring(o)}i=e.match(r)}return n+=e,n}function wrapWordIncludingNumberWithVar(e,t){let n="",r=/\\operatorname\s*{[^{}]*}/,a=e.match(r);for(;a;){let i=a.index,s=i+a[0].length;n+=wrapWordIncludingNumberWithVarSub(e.substring(0,i),t),n+=e.substring(i,s),a=(e=e.substring(s)).match(r)}return n+=wrapWordIncludingNumberWithVarSub(e,t),n}function wrapWordIncludingNumberWithVarSub(e,t){let n="";const r=/([^a-zA-Z0-9\s]?\s*)([a-zA-Z][a-zA-Z0-9]*[0-9][a-zA-Z0-9]*)([^a-zA-Z0-9]?)/;let a;if(t){const e="(E[+\\-]?[0-9]+\\s*($|(?=\\,|&|\\||\\\\\\||\\)|\\}|\\\\}|\\]|\\\\\\\\|\\\\end)))";a=new RegExp("([0-9]+(\\.[0-9]*)?"+e+")|(\\.[0-9]+"+e+")")}let i=e.match(r);for(;i;){let s=i.index,o=s+i[0].length-i[3].length;if(t){let t=e.match(a);if(t&&t.indexs){n+=e.substring(0,o),i=(e=e.substring(o)).match(r);continue}}if("\\"===i[1]||"^"===i[1][0]||"_"===i[1][0])n+=e.substring(0,o),e=e.substring(o);else{let t=s+i[1].length;n+=e.substring(0,t),n+=`\\operatorname{${i[2]}}`,e=e.substring(o)}i=e.match(r)}return n+=e,n}function stripLatex(e){return e.replaceAll("\\,","").replaceAll(/\\operatorname{([^{}]*)}/g,"$1")}function superSubscriptsToUnicode(e){let t={0:"₀",1:"₁",2:"₂",3:"₃",4:"₄",5:"₅",6:"₆",7:"₇",8:"₈",9:"₉","+":"₊","-":"₋"," ":""},n={0:"⁰",1:"¹",2:"²",3:"³",4:"⁴",5:"⁵",6:"⁶",7:"⁷",8:"⁸",9:"⁹","+":"⁺","-":"⁻"," ":""};function r(e,n){let r="";for(let e of n)r+=t[e];return r}function a(e,t){let r="";for(let e of t)r+=n[e];return r}return e=(e=(e=(e=e.replaceAll(/_(\d+)/g,r)).replaceAll(/_\(([\d +-]+)\)/g,r)).replaceAll(/\^(\d+)/g,a)).replaceAll(/\^\(([\d +-]+)\)/g,a)}function unicodeToSuperSubscripts(e){let t={"₀":"0","₁":"1","₂":"2","₃":"3","₄":"4","₅":"5","₆":"6","₇":"7","₈":"8","₉":"9","₊":"+","₋":"-"},n={"⁰":"0","¹":"1","²":"2","³":"3","⁴":"4","⁵":"5","⁶":"6","⁷":"7","⁸":"8","⁹":"9","⁺":"+","⁻":"-"};return e=(e=e.replaceAll(/([\u2080\u2081\u2082\u2083\u2084\u2085\u2086\u2087\u2088\u2089\u208A\u208B]+)/g,(function(e,n){let r="";for(let e of n)r+=t[e];return"_("+r+")"}))).replaceAll(/([\u2070\u00B9\u00B2\u00B3\u2074\u2075\u2076\u2077\u2078\u2079\u207A\u207B]+)/g,(function(e,t){let r="";for(let e of t)r+=n[e];return"^("+r+")"}))}const vectorOperators=["vector","altvector","tuple"];function renameStateVariable({stateVariableDefinitions:e,oldName:t,newName:n}){let r=e[n]=e[t];if(delete e[t],r.additionalStateVariablesDefined){let e=r.additionalStateVariablesDefined.indexOf(t);-1!==e&&(r.additionalStateVariablesDefined[e]=n)}let a=r.definition,i=["setValue","useEssentialOrDefaultValue","setEssentialValue"],s=["noChanges"];r.definition=function(e){let r=a(e);for(let e of i)r[e]&&t in r[e]&&(r[e][n]=r[e][t],delete r[e][t]);for(let e of s)if(r[e]){let a=r[e].indexOf(t);-1!==a&&(r[e][a]=n)}return r};let o=r.inverseDefinition;o&&(r.inverseDefinition=async function(e){let r=e.desiredStateVariableValues;r[t]=r[n],delete r[n];let a=await o(e);if(a.success)for(let e of a.instructions)e.setEssentialValue===t&&(e.setEssentialValue=n);return a})}function returnDefaultGetArrayKeysFromVarName(e){return e>1?function({arrayEntryPrefix:e,varEnding:t,arraySize:n,nDimensions:r}){let a=t.split("_").map((e=>Number(e)-1));return a.length===r&&a.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?a.every(((e,t)=>e=0?n?rcrypto.getRandomValues(new Uint8Array(e)).reduce(((e,t)=>e+=(t&=63)<36?t.toString(36):t<62?(t-26).toString(36).toUpperCase():t>62?"-":"_"),""),core,queuedRequestActions=[];async function createCore(e){core=new Core(e),core.getInitializedPromise().then((()=>{for(let e of queuedRequestActions)core.requestAction(e);queuedRequestActions=[]}))}async function returnAllStateVariables(e){if(!e.components)return{};let t={};for(let n in e.components){let r=e.components[n],a=t[n]={componentName:n,componentType:r.componentType,stateValues:{}};for(let e in r.state)a.stateValues[e]=removeFunctionsMathExpressionClass(await r.state[e].value);a.activeChildren=r.activeChildren.map((e=>e.componentName?{componentName:e.componentName,componentType:e.componentType}:e)),r.replacements&&(a.replacements=r.replacements.map((e=>e.componentName?{componentName:e.componentName,componentType:e.componentType}:e)),void 0!==r.replacementsToWithhold&&(a.replacementsToWithhold=r.replacementsToWithhold)),a.sharedParameters=removeFunctionsMathExpressionClass(r.sharedParameters)}return t}function removeFunctionsMathExpressionClass(e){if(e instanceof me$3.class)e=e.tree;else if("function"==typeof e)e=void 0;else if(Array.isArray(e))e=e.map((e=>removeFunctionsMathExpressionClass(e)));else if("object"==typeof e&&null!==e){let t={};for(let n in e)t[n]=removeFunctionsMathExpressionClass(e[n]);e=t}return e}onmessage=function(e){"createCore"===e.data.messageType?createCore(e.data.args):"requestAction"===e.data.messageType?core?.initialized?core.requestAction(e.data.args):queuedRequestActions.push(e.data.args):"returnAllStateVariables"===e.data.messageType?(console.log("all components"),console.log(core._components),returnAllStateVariables(core).then((e=>{postMessage({messageType:"returnAllStateVariables",args:e})}))):"visibilityChange"===e.data.messageType?core.handleVisibilityChange(e.data.args):"terminate"===e.data.messageType?core.terminate().then((()=>{postMessage({messageType:"terminated"})})):"navigatingToComponent"===e.data.messageType?core.handleNavigatingToComponent(e.data.args.componentName):"submitAllAnswers"===e.data.messageType&&core.requestAction({componentName:core.documentName,actionName:"submitAllAnswers",args:e.data.args})};let styleAttributes={lineColor:{componentType:"text"},lineColorWord:{componentType:"text"},lineOpacity:{componentType:"number"},lineWidth:{componentType:"number"},lineWidthWord:{componentType:"text"},lineStyle:{componentType:"text"},lineStyleWord:{componentType:"text"},markerColor:{componentType:"text"},markerColorWord:{componentType:"text"},markerStyle:{componentType:"text"},markerStyleWord:{componentType:"text"},markerSize:{componentType:"number"},fillColor:{componentType:"text"},fillColorWord:{componentType:"text"},fillOpacity:{componentType:"number"}},defaultStyle={lineColor:"#648FFF",lineColorWord:"blue",lineOpacity:.7,lineWidth:4,lineWidthWord:"thick",lineStyle:"solid",lineStyleWord:"",markerColor:"#648FFF",markerColorWord:"blue",markerStyle:"circle",markerStyleWord:"point",markerSize:5,fillColor:"#648FFF",fillColorWord:"blue",fillOpacity:.3};function returnDefaultStyleDefinitions(){return{1:{lineColor:"#648FFF",lineColorWord:"blue",lineOpacity:.7,lineWidth:4,lineWidthWord:"thick",lineStyle:"solid",lineStyleWord:"",markerColor:"#648FFF",markerColorWord:"blue",markerStyle:"circle",markerStyleWord:"point",markerSize:5,fillColor:"#648FFF",fillColorWord:"blue",fillOpacity:.3},2:{lineColor:"#D4042D",lineColorWord:"red",lineOpacity:.7,lineWidth:2,lineWidthWord:"",lineStyle:"solid",lineStyleWord:"",markerColor:"#D4042D",markerColorWord:"red",markerStyle:"square",markerStyleWord:"square",markerSize:5,fillColor:"#D4042D",fillColorWord:"red",fillOpacity:.3},3:{lineColor:"#F19143",lineColorWord:"orange",lineOpacity:.7,lineWidth:3,lineWidthWord:"",lineStyle:"solid",lineStyleWord:"",markerColor:"#F19143",markerColorWord:"orange",markerStyle:"triangle",markerStyleWord:"triangle",markerSize:5,fillColor:"#F19143",fillColorWord:"orange",fillOpacity:.3},4:{lineColor:"#644CD6",lineColorWord:"purple",lineOpacity:.7,lineWidth:2,lineWidthWord:"",lineStyle:"solid",lineStyleWord:"",markerColor:"#644CD6",markerColorWord:"purple",markerStyle:"diamond",markerStyleWord:"diamond",markerSize:5,fillColor:"#644CD6",fillColorWord:"purple",fillOpacity:.3},5:{lineColor:"black",lineColorWord:"black",lineOpacity:.7,lineWidth:1,lineWidthWord:"thin",lineStyle:"solid",lineStyleWord:"",markerColor:"black",markerColorWord:"black",markerStyle:"circle",markerStyleWord:"point",markerSize:5,fillColor:"black",fillColorWord:"black",fillOpacity:.3},6:{lineColor:"gray",lineColorWord:"gray",lineOpacity:.7,lineWidth:1,lineWidthWord:"thin",lineStyle:"dotted",lineStyleWord:"dotted",markerColor:"gray",markerColorWord:"gray",markerStyle:"circle",markerStyleWord:"point",markerSize:5,fillColor:"gray",fillColorWord:"gray",fillOpacity:.3}}}function returnStyleDefinitionStateVariables(){let e={setupChildren:{returnDependencies:()=>({setupChildren:{dependencyType:"child",childGroups:["setups"],proceedIfAllChildrenNotMatched:!0}}),definition:({dependencyValues:e})=>({setValue:{setupChildren:e.setupChildren}})}};return e.styleDefinitions={stateVariablesDeterminingDependencies:["setupChildren"],returnDependencies({stateValues:e}){let t={ancestorWithStyle:{dependencyType:"ancestor",variableNames:["styleDefinitions"]},setupChildren:{dependencyType:"child",childGroups:["setups"],proceedIfAllChildrenNotMatched:!0}};for(let n of e.setupChildren)t[`styleDefinitionsOf${n.componentName}`]={dependencyType:"child",parentName:n.componentName,childGroups:["styleDefinitions"],variableNames:["value"]};return t},definition({dependencyValues:e}){let t,n={};e.ancestorWithStyle&&(t=e.ancestorWithStyle.stateValues.styleDefinitions),t||(t=returnDefaultStyleDefinitions());for(let e in t)n[e]=Object.assign({},t[e]);let r=[];for(let t of e.setupChildren)r.push(...e[`styleDefinitionsOf${t.componentName}`]);for(let e of r){let t=e.stateValues.value;for(let e in t){let r=n[e];r||(r=n[e]=Object.assign({},defaultStyle));let a=Object.assign({},t[e]);"markerColor"in a&&!("markerColorWord"in a)&&(a.markerColorWord=a.markerColor),"markerStyle"in a&&!("markerStyleWord"in a)&&(a.markerStyleWord=a.markerStyle,"circle"===a.markerStyleWord?a.markerStyleWord="point":"triangle"===a.markerStyleWord.slice(0,8)&&(a.markerStyleWord="triangle")),"lineColor"in a&&!("lineColorWord"in a)&&(a.lineColorWord=a.lineColor),"fillColor"in a&&!("fillColorWord"in a)&&(a.fillColorWord=a.fillColor),"lineWidth"in a&&!("lineWidthWord"in a)&&(a.lineWidth>=4?a.lineWidthWord="thick":a.lineWidth<=1?a.lineWidthWord="thin":a.lineWidthWord=""),"lineStyle"in a&&!("lineStyleWord"in a)&&("dashed"===a.lineStyle?a.lineStyleWord="dashed":"dotted"===a.lineStyle?a.lineStyleWord="dotted":a.lineStyleWord=""),Object.assign(r,a)}}return{setValue:{styleDefinitions:n}}}},e}function returnSelectedStyleStateVariableDefinition(){return{selectedStyle:{forRenderer:!0,willNeverBeEssential:!0,returnDependencies:()=>({styleNumber:{dependencyType:"stateVariable",variableName:"styleNumber"},ancestorWithStyle:{dependencyType:"ancestor",variableNames:["styleDefinitions"]}}),definition:function({dependencyValues:e}){let t=e.ancestorWithStyle.stateValues.styleDefinitions;t||(t=returnDefaultStyleDefinitions());let n=t[e.styleNumber];return void 0===n&&(n=defaultStyle),{setValue:{selectedStyle:n}}}}}}function enumerateSelectionCombinations({numberOfIndices:e,numberOfOptions:t,maxNumber:n=1/0,withReplacement:r=!1,skipZero:a=!1}){if(1===e){let e=[...Array(t).keys()];return e=e.slice(1),a||(e=[...e,0]),e=e.slice(0,n),e=e.map((e=>[e])),e}let i=enumerateSelectionCombinations({numberOfIndices:e-1,numberOfOptions:t,maxNumber:n,withReplacement:r,skipZero:!r}),s=[],o=0;for(let e of i)for(let r=1;r<=t;r++){let i=[r%t,...e.map((e=>(r+e)%t))];if((!a||!i.includes(0))&&(s.push(i),o++,o>=n))return s}return s}function enumerateCombinations({numberOfOptionsByIndex:e,maxNumber:t=1/0}){let n=e.length;if(0===n)return[];let r=[];for(let t=0;t[...t,...e]),[]).reduce(((e,t)=>Math.max(e,t)),1);if(1===a){let n=e.reduce(((e,t)=>e*t));n=Math.min(n,t);let r=[];for(let t=0;tt%e));r.push(n)}return r}if(2===n){let n=a,r=me$3.math.lcm(...e),i=[],s=0;for(let a=0;a=t)return i}return i}let i=[];for(let t=0;t1?n.push(me$3.math.lcm(e[t],e[a])):n.push(null);i.push(n)}let s,o=i.reduce(((e,t)=>[...t,...e]),[]).filter((e=>null!==e)).reduce(((e,t)=>Math.min(e,t)),1/0);for(let e=0;e{if(0===e.length)n.push(a);else for(let i=0;i=t)return}};return r(e),n}function returnStandardSequenceAttributes(){return{type:{createPrimitiveOfType:"string",createStateVariable:"type",defaultPrimitiveValue:"number",toLowerCase:!0,validValues:["number","math","letters"]},from:{createComponentOfType:"_componentWithSelectableType"},to:{createComponentOfType:"_componentWithSelectableType"},step:{createComponentOfType:"math"},length:{createComponentOfType:"number"},exclude:{createComponentOfType:"_componentListWithSelectableType"}}}function returnStandardSequenceStateVariableDefinitions(){let e={specifiedFrom:{returnDependencies:()=>({fromAttr:{dependencyType:"attributeComponent",attributeName:"from",variableNames:["value"]}}),defaultValue:null,hasEssential:!0,essentialVarName:"from",definition:function({dependencyValues:e}){return null===e.fromAttr?{useEssentialOrDefaultValue:{specifiedFrom:!0}}:null===e.fromAttr.stateValues.value?{setValue:{specifiedFrom:NaN}}:{setValue:{specifiedFrom:e.fromAttr.stateValues.value}}}},specifiedTo:{returnDependencies:()=>({toAttr:{dependencyType:"attributeComponent",attributeName:"to",variableNames:["value"]}}),defaultValue:null,hasEssential:!0,essentialVarName:"to",definition:function({dependencyValues:e}){return null===e.toAttr?{useEssentialOrDefaultValue:{specifiedTo:!0}}:null===e.toAttr.stateValues.value?{setValue:{specifiedTo:NaN}}:{setValue:{specifiedTo:e.toAttr.stateValues.value}}}},specifiedLength:{returnDependencies:()=>({lengthAttr:{dependencyType:"attributeComponent",attributeName:"length",variableNames:["value"]}}),defaultValue:null,hasEssential:!0,essentialVarName:"length",definition:function({dependencyValues:e}){return null===e.lengthAttr?{useEssentialOrDefaultValue:{specifiedLength:!0}}:null===e.lengthAttr.stateValues.value?{setValue:{specifiedLength:NaN}}:{setValue:{specifiedLength:e.lengthAttr.stateValues.value}}}},specifiedStep:{returnDependencies:()=>({stepAttr:{dependencyType:"attributeComponent",attributeName:"step",variableNames:["value"]},type:{dependencyType:"stateVariable",variableName:"type"}}),defaultValue:null,hasEssential:!0,essentialVarName:"step",definition:function({dependencyValues:e}){if(null===e.stepAttr)return{useEssentialOrDefaultValue:{specifiedStep:!0}};let t=e.stepAttr.stateValues.value;return null===t?{setValue:{specifiedStep:NaN}}:{setValue:{specifiedStep:t}}}},specifiedExclude:{returnDependencies:()=>({excludeAttr:{dependencyType:"attributeComponent",attributeName:"exclude",variableNames:["values"]}}),defaultValue:[],hasEssential:!0,essentialVarName:"exclude",definition:function({dependencyValues:e}){return null===e.excludeAttr?{useEssentialOrDefaultValue:{specifiedExclude:!0}}:{setValue:{specifiedExclude:e.excludeAttr.stateValues.values}}}},lowercase:{returnDependencies:()=>({specifiedTo:{dependencyType:"stateVariable",variableName:"specifiedTo"},specifiedFrom:{dependencyType:"stateVariable",variableName:"specifiedFrom"}}),definition:function({dependencyValues:e}){let t=/^[A-Z]*$/,n=!0;return null!==e.specifiedFrom?t.test(e.specifiedFrom)&&(n=!1):null!==e.specifiedTo&&t.test(e.specifiedTo)&&(n=!1),{setValue:{lowercase:n}}}}};return e.validSequence={returnDependencies:()=>({specifiedLength:{dependencyType:"stateVariable",variableName:"specifiedLength"},specifiedStep:{dependencyType:"stateVariable",variableName:"specifiedStep"},specifiedFrom:{dependencyType:"stateVariable",variableName:"specifiedFrom"},specifiedTo:{dependencyType:"stateVariable",variableName:"specifiedTo"},type:{dependencyType:"stateVariable",variableName:"type"},lowercase:{dependencyType:"stateVariable",variableName:"lowercase"}}),definition:function({dependencyValues:e}){let t=!0;if(null!==e.specifiedLength&&(!Number.isInteger(e.specifiedLength)||e.specifiedLength<0)&&(console.warn("Invalid length of sequence. Must be a non-negative integer."),t=!1),null!==e.specifiedStep&&"math"!==e.type){let n=findFiniteNumericalValue(e.specifiedStep);Number.isFinite(n)||(console.warn("Invalid step of sequence. Must be a number for sequence of type "+e.type+"."),t=!1)}if(null!==e.specifiedFrom)if("number"===e.type){let n=findFiniteNumericalValue(e.specifiedFrom);Number.isFinite(n)||(console.warn("Invalid from of number sequence. Must be a number"),t=!1)}else Number.isNaN(e.specifiedFrom)&&(console.warn("Invalid from of sequence"),t=!1);if(null!==e.specifiedTo)if("number"===e.type){let n=findFiniteNumericalValue(e.specifiedTo);Number.isFinite(n)||(console.warn("Invalid to of number sequence. Must be a number"),t=!1)}else Number.isNaN(e.specifiedTo)&&(console.warn("Invalid to of sequence"),t=!1);return{setValue:{validSequence:t}}}},e.from={additionalStateVariablesDefined:["step","length","exclude"],returnDependencies:()=>({specifiedFrom:{dependencyType:"stateVariable",variableName:"specifiedFrom"},specifiedTo:{dependencyType:"stateVariable",variableName:"specifiedTo"},specifiedLength:{dependencyType:"stateVariable",variableName:"specifiedLength"},specifiedStep:{dependencyType:"stateVariable",variableName:"specifiedStep"},type:{dependencyType:"stateVariable",variableName:"type"},specifiedExclude:{dependencyType:"stateVariable",variableName:"specifiedExclude"},validSequence:{dependencyType:"stateVariable",variableName:"validSequence"}}),definition:function({dependencyValues:e}){let t=e.specifiedFrom,n=e.specifiedTo,r=e.specifiedStep,a=e.specifiedLength,i=[...e.specifiedExclude],s=e.type;if("math"===e.type)null!==n&&(n instanceof me$3.class||(n=me$3.fromAst(n))),null!==t&&(t instanceof me$3.class||(t=me$3.fromAst(t))),null!==r&&(r instanceof me$3.class||(r=me$3.fromAst(r)));else if(null!==r&&r instanceof me$3.class&&(r=r.evaluate_to_constant()),"letters"===e.type)null!==t&&(t=lettersToNumber$1(t)),null!==n&&(n=lettersToNumber$1(n)),i=i.map(lettersToNumber$1);else if("number"===e.type){null!==n&&(n=n instanceof me$3.class?n.evaluate_to_constant():Number(n)),null!==t&&(t=t instanceof me$3.class?t.evaluate_to_constant():Number(t));for(let[e,t]of i.entries())t instanceof me$3.class?i[e]=t.evaluate_to_constant():i[e]=Number(t)}if(e.validSequence){let e=calculateSequenceParameters({from:t,to:n,step:r,length:a,type:s});return e.exclude=i,{setValue:e}}return(!Number.isInteger(a)||a<0)&&(a=0),{setValue:{from:t,step:r,length:a,exclude:i}}}},e}function calculateSequenceParameters({from:e,to:t,step:n,length:r,type:a}){if(null===e)null===t?(e="math"===a?me$3.fromAst(1):1,null===n?(n="math"===a?me$3.fromAst(1):1,null===r&&(r=10)):null===r&&(r=10)):(null===n&&(n="math"===a?me$3.fromAst(1):1),null===r&&(r="math"===a?Math.floor((t.subtract(1).divide(n).evaluate_to_constant()+1)*(1+1e-14)):Math.floor(((t-1)/n+1)*(1+1e-14))),"math"===a?e=t.subtract(n.multiply(r-1)).simplify():(e=t-n*(r-1),"letters"===a&&e<1&&(e=t-n*((r=Math.floor(((t-1)/n+1)*(1+1e-14)))-1))));else if(null===t)null===n&&(n="math"===a?me$3.fromAst(1):1),null===r&&(r=10);else if(null===n)null===r?"math"===a?(n=me$3.fromAst(1),r=Math.floor(t.subtract(e).add(1).evaluate_to_constant()*(1+1e-14))):(n=1,r=Math.floor((t-e+1)*(1+1e-14))):"math"===a?n=t.subtract(e).divide(r-1):(n=(t-e)/(r-1),"letters"===a&&(n=Math.floor(n)));else{if(null!==r)throw Error("Can't define from, to, step, and length for sequence");r="math"===a?Math.floor(t.subtract(e).divide(n).add(1).evaluate_to_constant()*(1+1e-14)):Math.floor(((t-e)/n+1)*(1+1e-14))}return(!Number.isInteger(r)||r<0)&&(console.warn("Invalid length of sequence. Must be a non-negative integer."),r=0),{from:e,step:n,length:r}}function returnSequenceValues({from:e,step:t,length:n,exclude:r,type:a,lowercase:i,maxNum:s},o=!1){let l=[],u=0;for(let c=0;c0&&("math"===a?n=n.add(t.multiply(me$3.fromAst(c))).expand().simplify():n+=t*c),"math"===a){if(r.some((e=>e&&e.equals(n))))continue}else if("number"===a){if(r.some((e=>Math.abs(e-n)<=1e-14*Math.max(Math.abs(e),Math.abs(n)))))continue}else if(r.includes(n))continue;if("letters"===a&&(n=numberToLetters(n,i)),o?l.push({value:n,originalIndex:c}):l.push(n),u++,u===s)break}return l}function returnSequenceValueForIndex({index:e,from:t,step:n,length:r,exclude:a,type:i,lowercase:s}){if(!(e>=0&&(void 0===r||e0&&("math"===i?o=o.add(n.multiply(me$3.fromAst(e))).expand().simplify():o+=n*e),"math"===i){if(a.some((e=>e&&e.equals(o))))return null}else if("number"===i){if(a.some((e=>Math.abs(e-o)<=1e-14*Math.max(Math.abs(e),Math.abs(o)))))return null}else if(a.includes(o))return null;return"letters"===i&&(o=numberToLetters(o,s)),o}function lettersToNumber$1(e){try{e=e.toUpperCase()}catch(t){return void console.warn("Cannot convert "+e+" to a number")}let t=0,n=e.length,r=n;for(;(r-=1)>-1;){let a=e.charCodeAt(r)-64;if(a<1||a>26)return void console.warn("Cannot convert "+e+" to a number");t+=a*Math.pow(26,n-1-r)}return t}function numberToLetters(e,t){e--;let n=65;t&&(n=97);let r="";for(;;){let t=e%26;if(r=String.fromCharCode(n+t)+r,e<26)break;e=Math.floor(e/26)-1}return r}function getVariantsForDescendantsForUniqueVariants({variantIndex:e,serializedComponent:t,componentInfoObjects:n}){let r=t.variants?.descendantVariantComponents;if(void 0===r)return{success:!1};let a=r.map((e=>e.variants.numberOfVariants)),i=enumerateCombinations({numberOfOptionsByIndex:a,maxNumber:e})[e-1],s=[];for(let[e,t]of r.entries()){let r=n.allComponentClasses[t.componentType].getUniqueVariant({serializedComponent:t,variantIndex:i[e]+1,componentInfoObjects:n});if(!r.success)return{succss:!1};s.push(r.desiredVariant)}return{success:!0,desiredVariants:s}}function setUpVariantSeedAndRng({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n,useSubpartVariantRng:r=!1}){let a,i;if(e.variants&&(i=e.variants.desiredVariant),a=void 0!==i?.seed?i.seed.toString():r?t.subpartVariantRng().toString().slice(2):t.variantRng().toString().slice(2),t.variantSeed=a,t.variantRng=new t.rngClass(t.variantSeed),t.subpartVariantRng=new t.rngClass(t.variantSeed+"s"),i?.subvariants&&n)for(let e in i.subvariants){let t=i.subvariants[e],r=n[e];if(void 0===r)break;r.variants.desiredVariant=t}}function gatherVariantComponents({serializedComponents:e,componentInfoObjects:t}){let n=[];for(let r of e){if("object"!=typeof r)continue;if(r.variants||(r.variants={}),r.variants.isVariantComponent){n.push(r);continue}if(r.componentType in t.componentTypesCreatingVariants){r.variants.isVariantComponent=!0,n.push(r);continue}if(!r.children)continue;if(r.children.some((e=>"variantControl"===e.componentType))){r.variants.isVariantComponent=!0,n.push(r);continue}let e=gatherVariantComponents({serializedComponents:r.children,componentInfoObjects:t});e.length>0&&(r.variants.descendantVariantComponents=e,n.push(...e))}return n}function getNumberOfVariants({serializedComponent:e,componentInfoObjects:t}){let n;e.variants||(e.variants={});for(let t of e.children)if("variantControl"===t.componentType){n=t;break}let r="document"===e.componentType;if(!n){if(!r)return{success:!1};let n=e.children.filter((e=>e.componentType||""!==e.trim()));if(1===n.length&&t.isInheritedComponentType({inheritedComponentType:n[0].componentType,baseComponentType:"_sectioningComponent"})){let r=n[0],a=getNumberOfVariants({serializedComponent:r,componentInfoObjects:t});if(a.success)return e.variants.descendantVariantComponents=gatherVariantComponents({serializedComponents:e.children,componentInfoObjects:t}),e.variants.uniqueVariants=!0,e.variants.numberOfVariants=r.variants.numberOfVariants,e.variants.allPossibleVariants=r.variants.allPossibleVariants,e.variants.allVariantNames=r.variants.allVariantNames,e.variants.allPossibleVariantUniqueIndices=[...r.variants.allPossibleVariants.keys()].map((e=>e+1)),e.variants.allPossibleVariantSeeds=[...r.variants.allPossibleVariants.keys()].map((e=>(e+1).toString())),a}}return determineVariantsForSection({serializedComponent:e,componentInfoObjects:t,isDocument:r})}function determineVariantsForSection({serializedComponent:e,componentInfoObjects:t,isDocument:n=!1}){let r;void 0===e.variants&&(e.variants={});for(let t of e.children)if("variantControl"===t.componentType){r=t;break}if(!r&&!n){return t.allComponentClasses._base.determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t})}let a=[];if(r?.attributes.variantNames&&(a=r.attributes.variantNames.component.children.map((e=>e.toLowerCase()))),a.length!==[...new Set(a)].length)throw Error("Duplicate variant names specified");let i=r?.attributes.nVariants?.primitive;Number.isFinite(i)||(i=100),i=Math.min(Math.max(i,1),1e3);let s=[...a];if(s.lengthe.toLowerCase())),o=[...new Set(o)];for(let e of o)if(!s.includes(e))throw Error(`Cannot include variant ${e} as ${e} is a not variant name`)}let l=r?.attributes.variantsToExclude?.component.children;if(l){l=l.map((e=>e.toLowerCase()));for(let e of l)if(!s.includes(e))throw Error(`Cannot exclude variant ${e} as ${e} is not a variant name`)}else l=[];o=o?o.filter((e=>!l.includes(e))):[...s].filter((e=>!l.includes(e)));let u=o.map((e=>s.indexOf(e)+1)),c=[];r?.attributes.seeds&&(c=r.attributes.seeds.component.children);let p=[...c];if(p.lengthp[e-1])),h=void 0!==r?.attributes.uniqueVariants,f=r?.attributes.uniqueVariants?.primitive;if(f||!h){d=t.allComponentClasses._base.determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t}),f=!!d.success&&(f||d.numberOfVariants<=i)}let y=[],g=[],b=[];if(f)for(let[e,t]of u.entries())t<=d.numberOfVariants&&(g.push(t),y.push(o[e]),b.push(m[e]));else y=o,g=u,b=m;let v=y.length;if(0===v)throw Error("No variants selected based on variantsToInclude, variantsToExclude, and the number of variants available");return e.variants.uniqueVariants=f,e.variants.numberOfVariants=v,e.variants.allPossibleVariants=y,e.variants.allVariantNames=s,e.variants.allPossibleVariantUniqueIndices=g,e.variants.allPossibleVariantSeeds=b,{success:!0,numberOfVariants:v}}function indexToLowercaseLetters(e){return numberToLetters(e,!0)}class BaseComponent{constructor({componentName:e,ancestors:t,serializedComponent:n,definingChildren:r,serializedChildren:a,attributes:i,stateVariableDefinitions:s,componentInfoObjects:o,coreFunctions:l,flags:u,shadow:c,numerics:p,parentSharedParameters:d,sharedParameters:m}){this.numerics=p,this.parentSharedParameters=d,this.sharedParameters=m,this.componentName=e,this.ancestors=t,this.counters={},this.componentInfoObjects=o,this.coreFunctions=l,this.flags=u,!0===c&&(this.isShadow=!0),this.definingChildren=r,void 0===this.definingChildren&&(this.definingChildren=[]),this.serializedChildren=a,this.attributes=i,this.state={};for(let e in s)this.state[e]=Object.assign({},s[e]);this.stateValues=new Proxy(this.state,createStateProxyHandler()),this.essentialState={},n.state&&(this.essentialState=deepClone(n.state)),this.doenetAttributes={},void 0!==n.doenetAttributes&&Object.assign(this.doenetAttributes,n.doenetAttributes),void 0!==n.variants&&(this.variants=n.variants),n.range&&(this.doenetMLrange=n.range),this.actions={copyDoenetMLToClipboard:this.copyDoenetMLToClipboard.bind(this)}}static componentType="_base";static get rendererType(){return this.componentType}get componentType(){return this.constructor.componentType}get componentOrAdaptedName(){return this.adaptedFrom?this.adaptedFrom.componentOrAdaptedName:this.componentName}get rendererType(){return this.constructor.rendererType}get allPotentialRendererTypes(){let e=[];this.rendererType&&e.push(this.rendererType);for(let t in this.state){let n=this.state[t];if(n.public){let t=n.componentType;Array.isArray(t)||(t=[t]),n.wrappingComponents&&t.push(...flattenDeep(n.wrappingComponents).map((e=>"object"==typeof e?e.componentType:e)));for(let n of t){let t=this.componentInfoObjects.allComponentClasses[n];if(t){let n=t.rendererType;n&&!e.includes(n)&&e.push(n)}}}}if(this.constructor.adapters)for(let t of this.constructor.adapters){let n;n="string"==typeof t?t:t.componentType;let r=this.componentInfoObjects.allComponentClasses[n];if(r){let t=r.rendererType;t&&!e.includes(t)&&e.push(t)}}if(!this.rendererType)return e;for(let t in this.allChildren){let n=this.allChildren[t].component;if("object"==typeof n)for(let t of n.allPotentialRendererTypes)e.includes(t)||e.push(t)}return e}potentialRendererTypesFromSerializedComponents(e){let t=[];for(let n of e){let e=this.componentInfoObjects.allComponentClasses[n.componentType];if(e){let n=e.rendererType;n&&!t.includes(n)&&t.push(n);let r=e.returnStateVariableInfo({onlyPublic:!0}).stateVariableDescriptions;for(let e in r){let n=r[e],a=n.shadowingInstructions?.createComponentOfType;Array.isArray(a)||(a=[a]),n.wrappingComponents&&a.push(...flattenDeep(n.wrappingComponents).map((e=>"object"==typeof e?e.componentType:e)));for(let e of a){let n=this.componentInfoObjects.allComponentClasses[e];if(n){let e=n.rendererType;e&&!t.includes(e)&&t.push(e)}}}if(e.adapters)for(let n of e.adapters){let e;e="string"==typeof n?n:n.componentType;let r=this.componentInfoObjects.allComponentClasses[e];if(r){let e=r.rendererType;e&&!t.includes(e)&&t.push(e)}}}if(n.children){let e=this.potentialRendererTypesFromSerializedComponents(n.children);for(let n of e)t.includes(n)||t.push(n)}}return t}get childrenMatched(){return this.childrenMatchedWithPlaceholders&&!this.placeholderActiveChildrenIndices}static createAttributesObject(){return{hide:{createComponentOfType:"boolean",createStateVariable:"hide",defaultValue:!1,public:!0},disabled:{createComponentOfType:"boolean"},fixed:{createComponentOfType:"boolean",ignoreFixed:!0},modifyIndirectly:{createComponentOfType:"boolean",createStateVariable:"modifyIndirectly",defaultValue:!0,public:!0,propagateToProps:!0},styleNumber:{createComponentOfType:"number",createStateVariable:"styleNumber",defaultValue:1,public:!0,fallBackToParentStateVariable:"styleNumber"},isResponse:{createPrimitiveOfType:"boolean",createStateVariable:"isResponse",defaultValue:!1,public:!0},newNamespace:{createPrimitiveOfType:"boolean",createStateVariable:"newNamespace",defaultValue:!1,public:!0}}}static returnSugarInstructions(){return[]}static returnChildGroups(){return[]}static get childGroups(){return this.hasOwnProperty("childGroupsData")||(this.childGroupsData=this.returnChildGroups()),this.childGroupsData}static childGroupOfComponentTypeData;static get childGroupOfComponentType(){return this.hasOwnProperty("childGroupOfComponentTypeData")||(this.childGroupOfComponentTypeData={}),this.childGroupOfComponentTypeData}static childGroupIndsByNameData;static get childGroupIndsByName(){if(this.hasOwnProperty("childGroupIndsByNameData"))return Object.assign({},this.childGroupIndsByNameData);this.childGroupIndsByNameData={};for(let[e,t]of this.childGroups.entries()){if(t.group in this.childGroupIndsByNameData)throw Error(`Invalid childGroups for componentClass ${this.componentType}: ${t} is repeated`);this.childGroupIndsByNameData[t.group]=e}return Object.assign({},this.childGroupIndsByNameData)}returnMatchedChildIndices(e){let t=[];for(let n of e){let e=this.childMatchesByGroup[n];if(!e)return;t.push(...e)}return t.sort(((e,t)=>e-t))}static returnStateVariableDefinitions(){let e={};return e.hidden={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,returnDependencies:()=>({hide:{dependencyType:"stateVariable",variableName:"hide",variablesOptional:!0},parentHidden:{dependencyType:"parentStateVariable",variableName:"hidden"},sourceCompositeHidden:{dependencyType:"sourceCompositeStateVariable",variableName:"hidden"},adapterSourceHidden:{dependencyType:"adapterSourceStateVariable",variableName:"hidden"}}),definition:({dependencyValues:e})=>({setValue:{hidden:Boolean(e.parentHidden||e.sourceCompositeHidden||e.adapterSourceHidden||e.hide)}}),markStale:()=>({updateParentRenderedChildren:!0}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setDependency:"hide",desiredValue:e.hidden}]})},e.disabled={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,hasEssential:!0,doNotShadowEssential:!0,defaultValue:!1,provideEssentialValuesInDefinition:!0,returnDependencies:()=>({disabledAttr:{dependencyType:"attributeComponent",attributeName:"disabled",variableNames:["value"]},readOnly:{dependencyType:"flag",flagName:"readOnly"},parentDisabled:{dependencyType:"parentStateVariable",variableName:"disabled"},sourceCompositeDisabled:{dependencyType:"sourceCompositeStateVariable",variableName:"disabled"},adapterSourceDisabled:{dependencyType:"adapterSourceStateVariable",variableName:"disabled"}}),definition({dependencyValues:e,usedDefault:t,essentialValues:n}){if(e.readOnly)return{setValue:{disabled:!0}};if(null!==e.disabledAttr)return{setValue:{disabled:e.disabledAttr.stateValues.value}};if(void 0!==n.disabled)return{useEssentialOrDefaultValue:{disabled:!0}};let r=!1,a=!0;return null===e.parentDisabled||t.parentDisabled||(r=r||e.parentDisabled,a=!1),null===e.sourceCompositeDisabled||t.sourceCompositeDisabled||(r=r||e.sourceCompositeDisabled,a=!1),null===e.adapterSourceDisabled||t.adapterSourceDisabled||(r=r||e.adapterSourceDisabled,a=!1),a?{useEssentialOrDefaultValue:{disabled:!0}}:{setValue:{disabled:r}}},inverseDefinition:({dependencyValues:e,desiredStateVariableValues:t})=>null!==e.disabledAttr?{success:!0,instructions:[{setDependency:"disabledAttr",desiredValue:t.disabled,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"disabled",value:t.disabled}]}},e.fixed={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,defaultValue:!1,hasEssential:!0,doNotShadowEssential:!0,ignoreFixed:!0,provideEssentialValuesInDefinition:!0,returnDependencies:()=>({fixedAttr:{dependencyType:"attributeComponent",attributeName:"fixed",variableNames:["value"]},parentFixed:{dependencyType:"parentStateVariable",variableName:"fixed"},sourceCompositeFixed:{dependencyType:"sourceCompositeStateVariable",variableName:"fixed"},adapterSourceFixed:{dependencyType:"adapterSourceStateVariable",variableName:"fixed"},ignoreParentFixed:{dependencyType:"doenetAttribute",attributeName:"ignoreParentFixed"}}),definition({dependencyValues:e,usedDefault:t,essentialValues:n}){if(null!==e.fixedAttr)return{setValue:{fixed:e.fixedAttr.stateValues.value}};if(void 0!==n.fixed)return{useEssentialOrDefaultValue:{fixed:!0}};let r=!1,a=!0;return null===e.parentFixed||t.parentFixed||e.ignoreParentFixed||(r=r||e.parentFixed,a=!1),null===e.sourceCompositeFixed||t.sourceCompositeFixed||(r=r||e.sourceCompositeFixed,a=!1),null===e.adapterSourceFixed||t.adapterSourceFixed||(r=r||e.adapterSourceFixed,a=!1),a?{useEssentialOrDefaultValue:{fixed:!0}}:{setValue:{fixed:r}}},inverseDefinition:({dependencyValues:e,desiredStateVariableValues:t})=>null!==e.fixedAttr?{success:!0,instructions:[{setDependency:"fixedAttr",desiredValue:t.fixed,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"fixed",value:t.fixed}]}},e.isInactiveCompositeReplacement={defaultValue:!1,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{isInactiveCompositeReplacement:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:{variableName:"isInactiveCompositeReplacement",value:e.isInactiveCompositeReplacement}}]})},e.doenetML={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({doenetML:{dependencyType:"doenetML"}}),definition({dependencyValues:e}){let t=e.doenetML;return t||(t=""),{setValue:{doenetML:t}}}},e}static returnNormalizedStateVariableDefinitions({attributeNames:e,numerics:t}){let n=this.returnStateVariableDefinitions({attributeNames:e,numerics:t});if(!n)throw Error(`Error in state variable definitions of ${this.componentType}: returnStateVariableDefinitions did not return anything`);let r=function(e){for(let[t,n]of e.entries())"object"==typeof n&&(e[t]=n.variableName)},a=["returnDependencies","definition","inverseDefinition","stateVariablesDeterminingDependencies","stateVariablesDeterminingArraySizeDependencies","isArray","nDimensions","returnArraySizeDependencies","returnArraySize","returnArrayDependenciesByKey","arrayDefinitionByKey","inverseArrayDefinitionByKey","basedOnArrayKeyStateVariables","markStale","getPreviousDependencyValuesForMarkStale","determineDependenciesImmediately","createWorkspace","workspace","provideEssentialValuesInDefinition","providePreviousValuesInDefinition"],i={};for(let e in n){let t=n[e];if(i[e]=t,t.createWorkspace&&(t.workspace={}),t.additionalStateVariablesDefined){for(let[n,s]of t.additionalStateVariablesDefined.entries()){let o={};for(let e of a)e in t&&(o[e]=t[e]);o.additionalStateVariablesDefined=[...t.additionalStateVariablesDefined],o.additionalStateVariablesDefined[n]=e,r(o.additionalStateVariablesDefined);let l=s;"object"==typeof s&&(l=s.variableName,s=Object.assign({},s),delete s.variableName,Object.assign(o,s)),i[l]=o}r(t.additionalStateVariablesDefined)}}return i}static returnStateVariableInfo({onlyPublic:e=!1,onlyForRenderer:t=!1}={}){let n=this.createAttributesObject(),r={},a={},i={};for(let a in n){let i=n[a],s=i.createStateVariable;if(s&&(!e||i.public)&&(!t||i.forRenderer))if(i.public){let e;!i.createComponentOfType?(e=i.createPrimitiveOfType,"string"===e&&(e="text")):e=i.createComponentOfType,r[s]={createComponentOfType:e,public:!0}}else r[s]={}}let s=this.returnNormalizedStateVariableDefinitions({attributeNames:Object.keys(r)});for(let n in s){let o=s[n];if(o.isAlias)i[n]=o.targetVariableName;else if((!e||o.public)&&(!t||o.forRenderer)&&(o.public?r[n]={createComponentOfType:o.shadowingInstructions.createComponentOfType,public:!0}:r[n]={},o.isArray)){let e;r[n].isArray=!0,r[n].nDimensions=void 0===o.nDimensions?1:o.nDimensions,r[n].wrappingComponents=o.shadowingInstructions?.returnWrappingComponents?o.shadowingInstructions.returnWrappingComponents():[],e=o.entryPrefixes?o.entryPrefixes:[n];for(let t of e)a[t]={arrayVariableName:n,nDimensions:o.returnEntryDimensions?o.returnEntryDimensions(t):1,wrappingComponents:o.shadowingInstructions?.returnWrappingComponents?o.shadowingInstructions.returnWrappingComponents(t):[]};o.getArrayKeysFromVarName?r[n].getArrayKeysFromVarName=o.getArrayKeysFromVarName:r[n].getArrayKeysFromVarName=returnDefaultGetArrayKeysFromVarName(r[n].nDimensions)}}return{stateVariableDescriptions:r,arrayEntryPrefixes:a,aliases:i}}get parentName(){if(void 0!==this.ancestors&&0!==this.ancestors.length)return this.ancestors[0].componentName}getAllChildrenDownstreamComponentNames(e=!1){const t=Object.keys(this.allChildren);let n=Object.keys(this.downstreamDependencies);return!0!==e&&(n=n.filter((e=>!0!==this.downstreamDependencies[e].inactive))),[...t,...n]}get allDescendants(){let e=[];for(let t in this.allChildren){let n=this.allChildren[t].component;e=[...e,t,...n.allDescendants]}return e}async serialize(e={}){let t,n={componentType:this.componentType},r=[],a={...e};t=e.sourceAttributesToIgnoreRecursively?[...e.sourceAttributesToIgnoreRecursively]:[],e.sourceAttributesToIgnore&&(t.push(...e.sourceAttributesToIgnore),delete a.sourceAttributesToIgnore);for(let e of this.definingChildren)"object"!=typeof e?r.push(e):r.push(await e.serialize(a));if(void 0!==this.serializedChildren)for(let e of this.serializedChildren)r.push(this.copySerializedComponent(e));r.length>0&&(n.children=r),n.attributes={};for(let r in this.attributes){let i=this.attributes[r];i.component?e.copyAll&&(n.attributes[r]={component:await i.component.serialize(a)}):t.includes(r)&&!e.copyAll||(n.attributes[r]=JSON.parse(JSON.stringify(i)))}return this.essentialState&&Object.keys(this.essentialState).length>0&&(n.state=deepClone(this.essentialState)),e.copyVariants&&this.state.generatedVariantInfo&&(n.variants={desiredVariant:await this.stateValues.generatedVariantInfo}),n.originalName=this.componentName,n.originalDoenetAttributes=deepClone(this.doenetAttributes),n.doenetAttributes=deepClone(this.doenetAttributes),n.originalAttributes=deepClone(n.attributes),delete n.doenetAttributes.prescribedName,delete n.doenetAttributes.assignNames,n}copySerializedComponent(e){if("object"!=typeof e)return e;let t=[];if(void 0!==e.children)for(let n of e.children)t.push(this.copySerializedComponent(n));let n={componentType:e.componentType,originalName:e.componentName,originalNameFromSerializedComponent:!0,children:t,state:{},doenetAttributes:{}};return void 0!==e.doenetAttributes&&(n.originalDoenetAttributes=deepClone(e.doenetAttributes),n.doenetAttributes=deepClone(e.doenetAttributes),n.originalAttributes=deepClone(e.attributes),n.attributes=deepClone(e.attributes),delete n.doenetAttributes.prescribedName,delete n.doenetAttributes.assignNames),void 0!==e.state&&Object.assign(n.state,e.state),n}static adapters=[];static get nAdapters(){return this.adapters.length}getAdapter(e){if(e>=this.constructor.adapters.length)return;let t,n,r,a,i=this.constructor.adapters[e];"string"==typeof i?t=i:(t=i.stateVariable,n=i.componentType,r=i.substituteForPrimaryStateVariable,a=i.stateVariablesToShadow);let s=this.state[t];if(void 0===s||!s.public&&!n)throw Error("Invalid adapter "+t+" in "+this.componentType);return void 0===n&&(n=s.shadowingInstructions.createComponentOfType),{componentType:n,downstreamDependencies:{[this.componentName]:[{dependencyType:"adapter",adapterVariable:t,adapterTargetIdentity:{componentName:this.componentName,componentType:this.componentType},substituteForPrimaryStateVariable:r,stateVariablesToShadow:a}]}}}static getAdapterComponentType(e,t){if(e>=this.adapters.length)return;let n,r,a=this.adapters[e];if("string"==typeof a?n=a:(n=a.stateVariable,r=a.componentType),void 0===r){let e=t[this.componentType].stateVariableDescriptions[n];if(!e)throw Error("Invalid adapter "+n+" in "+this.componentType);if(r=e.createComponentOfType,!r)throw Error(`Couldn't get adapter component type for ${n} of componentType ${this.componentType}`)}return r}static determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t}){let n=e.variants?.numberOfVariants;if(void 0!==n)return{success:!0,numberOfVariants:n};let r=[];e.children&&(r=gatherVariantComponents({serializedComponents:e.children,componentInfoObjects:t})),void 0===e.variants&&(e.variants={}),e.variants.descendantVariantComponents=r,n=1;let a=[];for(let e of r){let r=t.allComponentClasses[e.componentType].determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t});if(!r.success)return{success:!1};a.push(r.numberOfVariants),n*=r.numberOfVariants}return e.variants.numberOfVariants=n,e.variants.uniqueVariantData={numberOfVariantsByDescendant:a},{success:!0,numberOfVariants:n}}static getUniqueVariant({serializedComponent:e,variantIndex:t,componentInfoObjects:n}){let r=e.variants?.numberOfVariants;if(void 0===r)return{success:!1};if(!Number.isInteger(t)||t<1||t>r)return{success:!1};let a=!1,i=e.variants.uniqueVariantData.numberOfVariantsByDescendant,s=e.variants.descendantVariantComponents,o=[];if(s.length>0){let e=enumerateCombinations({numberOfOptionsByIndex:i,maxNumber:t})[t-1].map((e=>e+1));for(let t=0;t1){let r=s[t],i=n.allComponentClasses[r.componentType].getUniqueVariant({serializedComponent:r,variantIndex:e[t],componentInfoObjects:n});if(!i.success)return{success:!1};o.push(i.desiredVariant),a=!0}else o.push({})}let l={index:t};return a&&(l.subvariants=o),{success:!0,desiredVariant:l}}async copyDoenetMLToClipboard({actionId:e}){let t=await this.stateValues.doenetML;t?this.coreFunctions.copyToClipboard(t,e):this.coreFunctions.resolveAction({actionId:e})}}class InlineComponent extends BaseComponent{static componentType="_inline"}class Text extends InlineComponent{constructor(e){super(e),Object.assign(this.actions,{moveText:this.moveText.bind(this)})}static componentType="text";static includeBlankStringChildren=!0;static variableForPlainMacro="value";static descendantCompositesMustHaveAReplacement=!1;static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.layer={createComponentOfType:"number",createStateVariable:"layer",defaultValue:0,public:!0,forRenderer:!0},e.anchor={createComponentOfType:"point"},e.positionFromAnchor={createComponentOfType:"text",createStateVariable:"positionFromAnchor",defaultValue:"center",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft","top","bottom","left","right","center"]},e.styleNumber.defaultValue=0,e}static returnChildGroups(){return[{group:"textLike",componentTypes:["string","text","_singleCharacterInline","_inlineRenderInlineChildren"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnSelectedStyleStateVariableDefinition();return Object.assign(e,t),e.value={public:!0,shadowingInstructions:{createComponentOfType:this.componentType,addAttributeComponentsShadowingStateVariables:{fixed:{stateVariableToShadow:"fixed"}}},hasEssential:!0,returnDependencies:()=>({textLikeChildren:{dependencyType:"child",childGroups:["textLike"],variableNames:["text"]}}),defaultValue:"",set:e=>null===e?"":String(e),definition:function({dependencyValues:e}){if(0===e.textLikeChildren.length)return{useEssentialOrDefaultValue:{value:!0}};let t="";for(let n of e.textLikeChildren)t+="string"==typeof n?n:n.stateValues.text;return{setValue:{value:t}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){let n=t.textLikeChildren.length;return n>1?{success:!1}:1===n?{success:!0,instructions:[{setDependency:"textLikeChildren",desiredValue:e.value,childIndex:0,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"value",value:null===e.value?"":String(e.value)}]}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:({dependencyValues:e})=>({setValue:{text:e.value}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setDependency:"value",desiredValue:e.text}]})},e.anchor={defaultValue:me$3.fromText("(0,0)"),public:!0,forRenderer:!0,hasEssential:!0,shadowingInstructions:{createComponentOfType:"point"},returnDependencies:()=>({anchorAttr:{dependencyType:"attributeComponent",attributeName:"anchor",variableNames:["coords"]}}),definition:({dependencyValues:e})=>e.anchorAttr?{setValue:{anchor:e.anchorAttr.stateValues.coords}}:{useEssentialOrDefaultValue:{anchor:!0}},inverseDefinition:async({desiredStateVariableValues:e,dependencyValues:t,stateValues:n,initialChange:r})=>r&&!await n.draggable?{success:!1}:t.anchorAttr?{success:!0,instructions:[{setDependency:"anchorAttr",desiredValue:e.anchor,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"anchor",value:e.anchor}]}},e}async moveText({x:e,y:t,z:n,transient:r,actionId:a}){let i=["vector"];return void 0!==e&&(i[1]=e),void 0!==t&&(i[2]=t),void 0!==n&&(i[3]=n),r?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],transient:r,actionId:a}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],actionId:a,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{x:e,y:t,z:n}}})}}class TextOrInline extends InlineComponent{static componentType="_textOrInline";static renderChildren=!0;static rendererType="containerInline";static includeBlankStringChildren=!0;static returnChildGroups(){return[{group:"inlines",componentTypes:["_inline"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.value={public:!0,shadowingInstructions:{createComponentOfType:this.componentType},returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["inlines"],variableNames:["text"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let t="";for(let n of e.inlineChildren)"object"!=typeof n?t+=n.toString():"string"==typeof n.stateValues.text&&(t+=n.stateValues.text);return{setValue:{value:t}}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:({dependencyValues:e})=>({setValue:{text:e.value}})},e}}class CompositeComponent extends BaseComponent{constructor(e){super(e),this.replacementsWorkspace={}}static componentType="_composite";static rendererType=void 0;static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.replacements={returnDependencies:()=>({replacements:{dependencyType:"replacement"}}),definition:({dependencyValues:e})=>({setValue:{replacements:e.replacements}})},e.recursiveReplacements={returnDependencies:()=>({recursiveReplacements:{dependencyType:"replacement",recursive:!0}}),definition:({dependencyValues:e})=>({setValue:{recursiveReplacements:e.recursiveReplacements}})},e.fullRecursiveReplacements={returnDependencies:()=>({recursiveReplacements:{dependencyType:"replacement",recursive:!0,recurseNonStandardComposites:!0}}),definition:({dependencyValues:e})=>({setValue:{fullRecursiveReplacements:e.recursiveReplacements}})},e}static createSerializedReplacements(){return{replacements:[]}}static calculateReplacementChanges(){return[]}replacements=[];replacementsToWithhold=0;get allPotentialRendererTypes(){let e=super.allPotentialRendererTypes;for(let t in this.allChildren){let n=this.allChildren[t].component;for(let t of n.allPotentialRendererTypes)e.includes(t)||e.push(t)}if(this.replacements)for(let t of this.replacements)if("object"==typeof t)for(let n of t.allPotentialRendererTypes)e.includes(n)||e.push(n);return e}}class Template extends CompositeComponent{static componentType="template";static treatAsComponentForRecursiveReplacements=!0;static includeBlankStringChildren=!0;static renderedDefault=!1;static assignNamesToReplacements=!0;static createsVariants=!0;static keepChildrenSerialized({serializedComponent:e}){return void 0===e.children?[]:Object.keys(e.children)}static createAttributesObject(){let e=super.createAttributesObject();return e.rendered={createComponentOfType:"boolean",createStateVariable:"rendered",defaultValue:this.renderedDefault,public:!0},e.isResponse={leaveRaw:!0},e.createComponentOfType={createPrimitiveOfType:"string"},e.nComponents={createPrimitiveOfType:"number"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=this;return e.serializedChildren={returnDependencies:()=>({serializedChildren:{dependencyType:"serializedChildren",doNotProxy:!0}}),definition:function({dependencyValues:e}){return{setValue:{serializedChildren:e.serializedChildren}}}},e.newNamespace={returnDependencies:()=>({newNamespace:{dependencyType:"attributePrimitive",attributeName:"newNamespace"}}),definition:({dependencyValues:e})=>({setValue:{newNamespace:e.newNamespace}})},e.readyToExpandWhenResolved={returnDependencies:()=>({}),definition:function(){return{setValue:{readyToExpandWhenResolved:!0}}}},e.isVariantComponent={returnDependencies:()=>({}),definition:()=>({setValue:{isVariantComponent:!0}})},e.generatedVariantInfo={returnDependencies:({sharedParameters:e,componentInfoObjects:t})=>({variantSeed:{dependencyType:"value",value:e.variantSeed},variantDescendants:{dependencyType:"descendant",componentTypes:Object.keys(t.componentTypesCreatingVariants),variableNames:["isVariantComponent","generatedVariantInfo"],useReplacementsForComposites:!0,recurseToMatchedChildren:!1,variablesOptional:!0,includeNonActiveChildren:!0,ignoreReplacementsOfEncounteredComposites:!0}}),definition({dependencyValues:e,componentName:t}){let n={seed:e.variantSeed,meta:{createdBy:t}},r=n.subvariants=[];for(let t of e.variantDescendants)t.stateValues.isVariantComponent?r.push(t.stateValues.generatedVariantInfo):t.stateValues.generatedVariantInfo&&r.push(...t.stateValues.generatedVariantInfo.subvariants);return{setValue:{generatedVariantInfo:n}}}},e.nComponentsSpecified={returnDependencies:()=>({nComponentsAttr:{dependencyType:"attributePrimitive",attributeName:"nComponents"},typeAttr:{dependencyType:"attributePrimitive",attributeName:"createComponentOfType"}}),definition({dependencyValues:e,componentInfoObjects:n}){let r;if(e.typeAttr){if(!(n.componentTypeLowerCaseMapping[e.typeAttr.toLowerCase()]in n.allComponentClasses))throw Error(`Invalid componentType ${e.typeAttr} of copy.`);r=null!==e.nComponentsAttr?e.nComponentsAttr:1}else{if(null!==e.nComponentsAttr)throw Error(`You must specify createComponentOfType when specifying nComponents for a ${t.componentType}.`);r=null}return{setValue:{nComponentsSpecified:r}}}},e}static async createSerializedReplacements({component:e,componentInfoObjects:t,alwaysCreateReplacements:n,flags:r}){if(await e.stateValues.nComponentsSpecified,await e.stateValues.rendered||n){let n=deepClone(await e.state.serializedChildren.value),a=e.attributes.newNamespace?.primitive;if("isResponse"in e.attributes)for(let i of n){if("object"!=typeof i)continue;let n=convertAttributesForComponentType({attributes:{isResponse:e.attributes.isResponse},componentType:i.componentType,componentInfoObjects:t,compositeCreatesNewNamespace:a,flags:r});i.attributes||(i.attributes={}),Object.assign(i.attributes,n)}let i=processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:n,parentName:e.componentName,parentCreatesNewNamespace:a,componentInfoObjects:t,originalNamesAreConsistent:!0});return{replacements:(await verifyReplacementsMatchSpecifiedType({component:e,replacements:i.serializedComponents,assignNames:e.doenetAttributes.assignNames,componentInfoObjects:t,compositeAttributesObj:this.createAttributesObject(),flags:r})).replacements}}return{replacements:[]}}static setUpVariant({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n}){setUpVariantSeedAndRng({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n,useSubpartVariantRng:!0})}get allPotentialRendererTypes(){let e=super.allPotentialRendererTypes,t=this.potentialRendererTypesFromSerializedComponents(this.serializedChildren);for(let n of t)e.includes(n)||e.push(n);return e}}const vectorAndListOperators=["list",...vectorOperators];class MathComponent extends InlineComponent{constructor(e){super(e),Object.assign(this.actions,{moveMath:this.moveMath.bind(this)})}static componentType="math";static primaryStateVariableForDefinition="unnormalizedValue";static primaryEssentialStateVariable="value";static variableForPlainMacro="value";static descendantCompositesMustHaveAReplacement=!0;static descendantCompositesDefaultReplacementType="math";static createAttributesObject(){let e=super.createAttributesObject();return e.format={createComponentOfType:"text",createStateVariable:"format",defaultValue:"text",public:!0,toLowerCase:!0,validValues:["text","latex"]},e.simplify={createComponentOfType:"text",createStateVariable:"simplify",defaultValue:"none",public:!0,toLowerCase:!0,valueTransformations:{true:"full",false:"none"},validValues:["none","full","numbers","numberspreserveorder"]},e.expand={createComponentOfType:"boolean",createStateVariable:"expand",defaultValue:!1,public:!0},e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer"},e.displaySmallAsZero={createComponentOfType:"number",valueForTrue:1e-14,valueForFalse:0},e.padZeros={createComponentOfType:"boolean"},e.renderMode={createComponentOfType:"text",createStateVariable:"renderMode",defaultValue:"inline",public:!0,forRenderer:!0},e.unordered={createComponentOfType:"boolean"},e.createVectors={createComponentOfType:"boolean",createStateVariable:"createVectors",defaultValue:!1,public:!0},e.createIntervals={createComponentOfType:"boolean",createStateVariable:"createIntervals",defaultValue:!1,public:!0},e.functionSymbols={createComponentOfType:"textList",createStateVariable:"functionSymbols",defaultValue:["f","g"],public:!0},e.sourcesAreFunctionSymbols={createComponentOfType:"textList",createStateVariable:"sourcesAreFunctionSymbols",defaultValue:[]},e.splitSymbols={createComponentOfType:"boolean",createStateVariable:"splitSymbols",defaultValue:!0,public:!0,fallBackToParentStateVariable:"splitSymbols"},e.parseScientificNotation={createComponentOfType:"boolean",createStateVariable:"parseScientificNotation",defaultValue:!1,public:!0,fallBackToParentStateVariable:"parseScientificNotation"},e.groupCompositeReplacements={createPrimitiveOfType:"boolean",createStateVariable:"groupCompositeReplacements",defaultValue:!0},e.displayBlanks={createComponentOfType:"boolean",createStateVariable:"displayBlanks",defaultValue:!0,public:!0},e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.layer={createComponentOfType:"number",createStateVariable:"layer",defaultValue:0,public:!0,forRenderer:!0},e.anchor={createComponentOfType:"point"},e.positionFromAnchor={createComponentOfType:"text",createStateVariable:"positionFromAnchor",defaultValue:"center",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft","top","bottom","left","right","center"]},e.styleNumber.defaultValue=0,e}static returnChildGroups(){return[{group:"maths",componentTypes:["math"]},{group:"strings",componentTypes:["string"]},{group:"displayedMaths",componentTypes:["m","me","men"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnSelectedStyleStateVariableDefinition();return Object.assign(e,t),e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({mathListParentDisplayDigits:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"displayDigits"},numberListParentDisplayDigits:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"displayDigits"},mathListParentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"displayDecimals"},numberListParentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"displayDecimals"},displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["displayDigits"]},stringChildren:{dependencyType:"child",childGroups:["strings"]}}),definition({dependencyValues:e,usedDefault:t}){let n,r=!1;if(null!==e.mathListParentDisplayDigits){if(!t.mathListParentDisplayDigits)return{setValue:{displayDigits:e.mathListParentDisplayDigits}};r=!0,n=e.mathListParentDisplayDigits}if(null!==e.numberListParentDisplayDigits){if(!t.numberListParentDisplayDigits)return{setValue:{displayDigits:e.numberListParentDisplayDigits}};r=!0,n=e.numberListParentDisplayDigits}let a=null!==e.numberListParentDisplayDecimals&&!t.numberListParentDisplayDecimals||null!==e.mathListParentDisplayDecimals&&!t.mathListParentDisplayDecimals,i=null===e.displayDigitsAttr||t.displayDigitsAttr,s=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!i&&!s){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({mathListParentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"displayDecimals"},numberListParentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"displayDecimals"},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["displayDecimals"]},stringChildren:{dependencyType:"child",childGroups:["strings"]}}),definition({dependencyValues:e,usedDefault:t}){let n,r=!1;if(null!==e.mathListParentDisplayDecimals){if(!t.mathListParentDisplayDecimals)return{setValue:{displayDecimals:e.mathListParentDisplayDecimals}};r=!0,n=e.mathListParentDisplayDecimals}if(null!==e.numberListParentDisplayDecimals){if(!t.numberListParentDisplayDecimals)return{setValue:{displayDecimals:e.numberListParentDisplayDecimals}};r=!0,n=e.numberListParentDisplayDecimals}if(null!==e.displayDecimalsAttr){if(!t.displayDecimalsAttr)return{setValue:{displayDecimals:e.displayDecimalsAttr.stateValues.value}};r=!0,n=e.displayDecimalsAttr.stateValues.value}if(1===e.mathChildren.length&&0===e.stringChildren.length){if(!t.mathChildren[0]||!t.mathChildren[0].displayDecimals)return{setValue:{displayDecimals:e.mathChildren[0].stateValues.displayDecimals}};r=!0,n=e.mathChildren[0].stateValues.displayDecimals}return r?{useEssentialOrDefaultValue:{displayDecimals:{defaultValue:n}}}:{useEssentialOrDefaultValue:{displayDecimals:!0}}}},e.displaySmallAsZero={public:!0,shadowingInstructions:{createComponentOfType:"number"},hasEssential:!0,defaultValue:0,returnDependencies:()=>({mathListParentDisplaySmallAsZero:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"displaySmallAsZero"},numberListParentDisplaySmallAsZero:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"displaySmallAsZero"},displaySmallAsZeroAttr:{dependencyType:"attributeComponent",attributeName:"displaySmallAsZero",variableNames:["value"]},mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["displaySmallAsZero"]},stringChildren:{dependencyType:"child",childGroups:["strings"]}}),definition({dependencyValues:e,usedDefault:t}){let n,r=!1;if(null!==e.mathListParentDisplaySmallAsZero){if(!t.mathListParentDisplaySmallAsZero)return{setValue:{displaySmallAsZero:e.mathListParentDisplaySmallAsZero}};r=!0,n=e.mathListParentDisplaySmallAsZero}if(null!==e.numberListParentDisplaySmallAsZero){if(!t.numberListParentDisplaySmallAsZero)return{setValue:{displaySmallAsZero:e.numberListParentDisplaySmallAsZero}};r=!0,n=e.numberListParentDisplaySmallAsZero}if(null!==e.displaySmallAsZeroAttr){if(!t.displaySmallAsZeroAttr)return{setValue:{displaySmallAsZero:e.displaySmallAsZeroAttr.stateValues.value}};r=!0,n=e.displaySmallAsZeroAttr.stateValues.value}if(1===e.mathChildren.length&&0===e.stringChildren.length){if(!t.mathChildren[0]||!t.mathChildren[0].displaySmallAsZero)return{setValue:{displaySmallAsZero:e.mathChildren[0].stateValues.displaySmallAsZero}};r=!0,n=e.mathChildren[0].stateValues.displaySmallAsZero}return r?{useEssentialOrDefaultValue:{displaySmallAsZero:{defaultValue:n}}}:{useEssentialOrDefaultValue:{displaySmallAsZero:!0}}}},e.padZeros={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},hasEssential:!0,defaultValue:!1,returnDependencies:()=>({mathListParentPadZeros:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"padZeros"},numberListParentPadZeros:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"padZeros"},padZerosAttr:{dependencyType:"attributeComponent",attributeName:"padZeros",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["padZeros"]},stringChildren:{dependencyType:"child",childGroups:["strings"]}}),definition({dependencyValues:e,usedDefault:t}){let n,r=!1;if(null!==e.mathListParentPadZeros){if(!t.mathListParentPadZeros)return{setValue:{padZeros:e.mathListParentPadZeros}};r=!0,n=e.mathListParentPadZeros}if(null!==e.numberListParentPadZeros){if(!t.numberListParentPadZeros)return{setValue:{padZeros:e.numberListParentPadZeros}};r=!0,n=e.numberListParentPadZeros}if(null!==e.padZerosAttr){if(!t.padZerosAttr)return{setValue:{padZeros:e.padZerosAttr.stateValues.value}};r=!0,n=e.padZerosAttr.stateValues.value}if(1===e.mathChildren.length&&0==e.stringChildren.length){if(!t.mathChildren[0]||!t.mathChildren[0].padZeros)return{setValue:{padZeros:e.mathChildren[0].stateValues.padZeros}};r=!0,n=e.mathChildren[0].stateValues.padZeros}return r?{useEssentialOrDefaultValue:{padZeros:{defaultValue:n}}}:{useEssentialOrDefaultValue:{padZeros:!0}}}},e.valueShadow={defaultValue:me$3.fromAst("_"),hasEssential:!0,essentialVarName:"value",returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{valueShadow:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"valueShadow",value:e.valueShadow}]}}},e.unordered={defaultValue:!1,public:!0,shadowingInstructions:{createComponentOfType:"boolean"},hasEssential:!0,returnDependencies:()=>({unorderedAttr:{dependencyType:"attributeComponent",attributeName:"unordered",variableNames:["value"]},mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["unordered"]}}),definition({dependencyValues:e}){if(null===e.unorderedAttr){if(e.mathChildren.length>0){let t=e.mathChildren.every((e=>e.stateValues.unordered));return{setValue:{unordered:t}}}return{useEssentialOrDefaultValue:{unordered:!0}}}return{setValue:{unordered:e.unorderedAttr.stateValues.value}}}},e.codePre={returnDependencies:()=>({stringChildren:{dependencyType:"child",childGroups:["strings"]}}),definition({dependencyValues:e}){let t="math",n=!1;do{n=!1;for(let r of e.stringChildren)if(!0===r.includes(t)){n=!0,t+="m";break}}while(n);return{setValue:{codePre:t}}}},e.mathChildrenFunctionSymbols={returnDependencies:()=>({sourcesAreFunctionSymbols:{dependencyType:"stateVariable",variableName:"sourcesAreFunctionSymbols"},mathChildren:{dependencyType:"child",childGroups:["maths"]}}),definition({dependencyValues:e}){let t=[];if(e.mathChildren.compositeReplacementRange)for(let n of e.mathChildren.compositeReplacementRange)if(e.sourcesAreFunctionSymbols.includes(n.target))for(let e=n.firstInd;e<=n.lastInd;e++)t.push(e);return{setValue:{mathChildrenFunctionSymbols:t}}}},e.expressionWithCodes={hasEssential:!0,doNotShadowEssential:!0,returnDependencies:()=>({stringMathChildren:{dependencyType:"child",childGroups:["strings","maths"]},stringChildren:{dependencyType:"child",childGroups:["strings"]},mathChildren:{dependencyType:"child",childGroups:["maths"]},displayedMathChildren:{dependencyType:"child",childGroups:["displayedMaths"],variableNames:["latex"]},format:{dependencyType:"stateVariable",variableName:"format"},codePre:{dependencyType:"stateVariable",variableName:"codePre"},functionSymbols:{dependencyType:"stateVariable",variableName:"functionSymbols"},mathChildrenFunctionSymbols:{dependencyType:"stateVariable",variableName:"mathChildrenFunctionSymbols"},splitSymbols:{dependencyType:"stateVariable",variableName:"splitSymbols"},parseScientificNotation:{dependencyType:"stateVariable",variableName:"parseScientificNotation"},groupCompositeReplacements:{dependencyType:"stateVariable",variableName:"groupCompositeReplacements"}}),set:e=>null===e?null:convertValueToMathExpression(e),definition:calculateExpressionWithCodes,async inverseDefinition({desiredStateVariableValues:e,dependencyValues:t,stateValues:n,componentName:r}){let a=e.expressionWithCodes,i=[{setEssentialValue:"expressionWithCodes",value:a}],s=t.stringChildren.length;if(0===s)return{success:!1};if(0===t.mathChildren.length){let e;e="latex"===await n.format?a.toLatex():a.toString(),i.push({setDependency:"stringChildren",desiredValue:e,childIndex:0,variableIndex:0,ignoreChildChangeForComponent:!0});for(let e=1;e({mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["value","canBeModified"]}}),definition:({dependencyValues:e})=>({setValue:{mathChildrenWithCanBeModified:e.mathChildren}})},e.unnormalizedValue={returnDependencies:()=>({mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]},stringChildren:{dependencyType:"child",childGroups:["strings"],variableNames:["value"]},expressionWithCodes:{dependencyType:"stateVariable",variableName:"expressionWithCodes"},codePre:{dependencyType:"stateVariable",variableName:"codePre"},valueShadow:{dependencyType:"stateVariable",variableName:"valueShadow"}}),set:convertValueToMathExpression,defaultValue:me$3.fromAst("_"),definition:calculateMathValue,inverseDefinition:invertMath},e.value={public:!0,shadowingInstructions:{createComponentOfType:this.componentType,attributesToShadow:["unordered","displayDigits","displayDecimals","displaySmallAsZero","padZeros","simplify","expand"],addAttributeComponentsShadowingStateVariables:{fixed:{stateVariableToShadow:"fixed"}}},returnDependencies:()=>({unnormalizedValue:{dependencyType:"stateVariable",variableName:"unnormalizedValue"},simplify:{dependencyType:"stateVariable",variableName:"simplify"},expand:{dependencyType:"stateVariable",variableName:"expand"},createVectors:{dependencyType:"stateVariable",variableName:"createVectors"},createIntervals:{dependencyType:"stateVariable",variableName:"createIntervals"}}),definition:function({dependencyValues:e}){let t=e.unnormalizedValue,{simplify:n,expand:r,createVectors:a,createIntervals:i}=e;return t=normalizeMathExpression({value:t,simplify:n,expand:r,createVectors:a,createIntervals:i}),{setValue:{value:t}}},inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setDependency:"unnormalizedValue",desiredValue:e.value}]}}},e.number={public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:function({dependencyValues:e}){let t=e.value.evaluate_to_constant();return null===t&&(t=NaN),{setValue:{number:t}}},inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setDependency:"value",desiredValue:me$3.fromAst(e.number)}]}}},e.isNumber={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:function({dependencyValues:e}){return{setValue:{isNumber:Number.isFinite(e.value.tree)}}}},e.isNumeric={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({number:{dependencyType:"stateVariable",variableName:"number"}}),definition:function({dependencyValues:e}){return{setValue:{isNumeric:Number.isFinite(e.number)}}}},e.valueForDisplay={returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"},simplify:{dependencyType:"stateVariable",variableName:"simplify"},expand:{dependencyType:"stateVariable",variableName:"expand"}}),definition:function({dependencyValues:e,usedDefault:t}){return{setValue:{valueForDisplay:normalizeMathExpression({value:roundForDisplay({value:e.value,dependencyValues:e,usedDefault:t}),simplify:e.simplify,expand:e.expand})}}},inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setDependency:"value",desiredValue:e.valueForDisplay}]})},e.latex={public:!0,forRenderer:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({valueForDisplay:{dependencyType:"stateVariable",variableName:"valueForDisplay"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displayBlanks:{dependencyType:"stateVariable",variableName:"displayBlanks"}}),definition:function({dependencyValues:e,usedDefault:t}){let n,r={};e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(r.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(r.padToDigits=e.displayDigits)),e.displayBlanks||(r.showBlanks=!1);try{n=e.valueForDisplay.toLatex(r)}catch(t){n=e.displayBlanks?"_":""}return{setValue:{latex:n}}},inverseDefinition({desiredStateVariableValues:e}){let t;try{t=me$3.fromLatex(e.latex)}catch(e){return{success:!1}}return{success:!0,instructions:[{setDependency:"valueForDisplay",desiredValue:t}]}}},e.latexWithInputChildren={forRenderer:!0,returnDependencies:()=>({latex:{dependencyType:"stateVariable",variableName:"latex"}}),definition:function({dependencyValues:e}){return{setValue:{latexWithInputChildren:[e.latex]}}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({valueForDisplay:{dependencyType:"stateVariable",variableName:"valueForDisplay"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},value:{dependencyType:"stateVariable",variableName:"value"},displayBlanks:{dependencyType:"stateVariable",variableName:"displayBlanks"}}),definition:function({dependencyValues:e,usedDefault:t}){let n,r={};e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(r.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(r.padToDigits=e.displayDigits)),e.displayBlanks||(r.showBlanks=!1);try{n=e.valueForDisplay.toString(r)}catch(t){n=e.displayBlanks?"_":""}return{setValue:{text:superSubscriptsToUnicode(n.toString())}}},async inverseDefinition({desiredStateVariableValues:e,stateValues:t}){let n,r=getFromText({functionSymbols:await t.functionSymbols,splitSymbols:await t.splitSymbols,parseScientificNotation:await t.parseScientificNotation});try{n=r(unicodeToSuperSubscripts(e.text))}catch(e){return{success:!1}}return{success:!0,instructions:[{setDependency:"value",desiredValue:n}]}}},e.codesAdjacentToStrings={returnDependencies:()=>({stringMathChildren:{dependencyType:"child",childGroups:["strings","maths"]},codePre:{dependencyType:"stateVariable",variableName:"codePre"},format:{dependencyType:"stateVariable",variableName:"format"}}),definition:calculateCodesAdjacentToStrings},e.canBeModified={additionalStateVariablesDefined:["constantChildIndices","codeForExpression","inverseMaps","template","mathChildrenMapped"],returnDependencies:()=>({mathChildrenModifiable:{dependencyType:"child",childGroups:["maths"],variableNames:["canBeModified"]},displayedMathChildren:{dependencyType:"child",childGroups:["displayedMaths"]},expressionWithCodes:{dependencyType:"stateVariable",variableName:"expressionWithCodes"},modifyIndirectly:{dependencyType:"stateVariable",variableName:"modifyIndirectly"},fixed:{dependencyType:"stateVariable",variableName:"fixed"},codePre:{dependencyType:"stateVariable",variableName:"codePre"}}),definition:determineCanBeModified},e.mathChildrenByVectorComponent={returnDependencies:()=>({codePre:{dependencyType:"stateVariable",variableName:"codePre"},mathChildren:{dependencyType:"child",childGroups:["maths"]},expressionWithCodes:{dependencyType:"stateVariable",variableName:"expressionWithCodes"}}),definition:function({dependencyValues:e}){if(null===e.expressionWithCodes)return{setValue:{mathChildrenByVectorComponent:null}};let t=e.expressionWithCodes.tree,n=e.mathChildren.length;if(0===n||!Array.isArray(t)||!vectorOperators.includes(t[0]))return{setValue:{mathChildrenByVectorComponent:null}};let r={},a=0,i=e.codePre+a;for(let s=1;s=n)break}return{setValue:{mathChildrenByVectorComponent:r}}}},e.nDimensions={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition({dependencyValues:e}){let t=1,n=e.value.tree;if(Array.isArray(n))if(vectorAndListOperators.includes(n[0]))t=n.length-1;else if("matrix"===n[0]){let e=n[1].slice(1);1===e[0]?t=e[1]:1===e[1]&&(t=e[0])}else vectorOperators.includes(n[1][0])&&("^"===n[0]&&"T"===n[2]||"prime"===n[0])&&(t=n[1].length-1);return{setValue:{nDimensions:t}}}},e.vector={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"],returnWrappingComponents:e=>"x"===e?[]:[["vector",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,entryPrefixes:["x"],returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey:()=>({globalDependencies:{value:{dependencyType:"stateVariable",variableName:"value"}}}),arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t,arraySize:n}){let r=e.value.tree,a=!1,i={};if(Array.isArray(r))if(vectorAndListOperators.includes(r[0])){for(let e=0;ee.tree))]);else if("matrix"===s[0]){let e=s[1].slice(1);if(1===e[0]){let e=["tuple"];for(let t=0;te.tree))]],s[2]&&i.push(s[2]),i=me$3.fromAst(i));return i||(i=r.desiredVector[0]),{success:!0,instructions:[{setDependency:"value",desiredValue:i}]}}},e.x={isAlias:!0,targetVariableName:"x1"},e.y={isAlias:!0,targetVariableName:"x2"},e.z={isAlias:!0,targetVariableName:"x3"},e.matrixSize={public:!0,shadowingInstructions:{createComponentOfType:"numberList"},returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition({dependencyValues:e}){let t=[1,1],n=e.value.tree;return Array.isArray(n)&&(vectorAndListOperators.includes(n[0])?t=[n.length-1,1]:"matrix"===n[0]?t=n[1].slice(1):vectorOperators.includes(n[1][0])&&("^"===n[0]&&"T"===n[2]||"prime"===n[0])&&(t=[1,n[1].length-1])),{setValue:{matrixSize:t}}}},e.nRows={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({matrixSize:{dependencyType:"stateVariable",variableName:"matrixSize"}}),definition:({dependencyValues:e})=>({setValue:{nRows:e.matrixSize[0]}})},e.nColumns={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({matrixSize:{dependencyType:"stateVariable",variableName:"matrixSize"}}),definition:({dependencyValues:e})=>({setValue:{nColumns:e.matrixSize[1]}})},e.matrix={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"],returnWrappingComponents:e=>"matrixEntry"===e?[]:"row"===e?[["matrix","matrixRow"]]:"column"===e?[["matrix","matrixColumn"]]:[["matrixRow"],["matrix"]]},isArray:!0,nDimensions:2,entryPrefixes:["matrixEntry","row","column","rows","columns"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("matrixEntry"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}if("column"===e){let e=Number(t)-1;return Number.isInteger(e)&&e>=0?n?en+","+e)):[]:["0,"+e]:[]}if("rows"===e||"columns"===e){if(!n)return["0,0"];let e=[];for(let t=0;tt+","+n)));return e}},arrayVarNameFromPropIndex(e,t){if("matrix"===t||"rows"===t)return 1===e.length?"row"+e[0]:`matrixEntry${e[0]}_${e[1]}`;if("columns"===t)return 1===e.length?"column"+e[0]:`matrixEntry${e[1]}_${e[0]}`;if("row"===t.slice(0,3)){let n=Number(t.slice(3));if(Number.isInteger(n)&&n>0)return`matrixEntry${n}_${e[0]}`}if("column"===t.slice(0,6)){let n=Number(t.slice(6));if(Number.isInteger(n)&&n>0)return`matrixEntry${e[0]}_${n}`}return null},returnArraySizeDependencies:()=>({matrixSize:{dependencyType:"stateVariable",variableName:"matrixSize"}}),returnArraySize:({dependencyValues:e})=>e.matrixSize,returnArrayDependenciesByKey:()=>({globalDependencies:{value:{dependencyType:"stateVariable",variableName:"value"}}}),arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t,arraySize:n}){let r=e.value.tree,a=!1,i={};if(Array.isArray(r))if(vectorAndListOperators.includes(r[0])){for(let e=0;e({anchorAttr:{dependencyType:"attributeComponent",attributeName:"anchor",variableNames:["coords"]}}),definition:({dependencyValues:e})=>e.anchorAttr?{setValue:{anchor:e.anchorAttr.stateValues.coords}}:{useEssentialOrDefaultValue:{anchor:!0}},inverseDefinition:async({desiredStateVariableValues:e,dependencyValues:t,stateValues:n,initialChange:r})=>r&&!await n.draggable?{success:!1}:t.anchorAttr?{success:!0,instructions:[{setDependency:"anchorAttr",desiredValue:e.anchor,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"anchor",value:e.anchor}]}},e}static adapters=[{stateVariable:"number",stateVariablesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},"text",{componentType:"subsetOfReals",stateVariable:"value",substituteForPrimaryStateVariable:"subsetValue"}];async moveMath({x:e,y:t,z:n,transient:r,actionId:a}){let i=["vector"];return void 0!==e&&(i[1]=e),void 0!==t&&(i[2]=t),void 0!==n&&(i[3]=n),r?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],transient:r,actionId:a}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],actionId:a,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{x:e,y:t,z:n}}})}}function calculateExpressionWithCodes({dependencyValues:e,changes:t}){if(!("stringMathChildren"in t&&t.stringMathChildren.componentIdentitiesChanged||"displayedMathChildren"in t||"format"in t||"splitSymbols"in t||"parseScientificNotation"in t||"functionSymbols"in t||"mathChildrenFunctionSymbols"in t))return{useEssentialOrDefaultValue:{expressionWithCodes:!0}};if(0===e.stringMathChildren.length){if(e.displayedMathChildren.length>0){let t;try{t=me$3.fromLatex(e.displayedMathChildren[0].stateValues.latex)}catch(e){t=me$3.fromAst("_")}return{setValue:{expressionWithCodes:t},setEssentialValue:{expressionWithCodes:t}}}return{setValue:{expressionWithCodes:null},setEssentialValue:{expressionWithCodes:null}}}let n,r,a,i,s="",o=0,l="",u=e.stringMathChildren.compositeReplacementRange;e.groupCompositeReplacements&&u.length>0&&(a=0,i=u[a].firstInd);for(let[t,c]of e.stringMathChildren.entries()){if(void 0===n&&t===i){n=a,r=u[a].lastInd,l="";let s=r===t;if(!s)for(let n=t;n<=r;n++)if("string"==typeof e.stringMathChildren[n]){s=!0;break}s&&(u.length>n+1?(a=n+1,i=u[a].firstInd):(a=void 0,i=void 0),n=void 0,r=void 0)}if("string"==typeof c)s+=" "+c+" ";else{let t,r=e.codePre+o;o++,t="latex"===e.format?"\\operatorname{"+r+"}":" "+r+" ",void 0!==n?(l&&(l+=","),l+=t):s+=t}if(t===r){let o=s.trimEnd(),c=!1;if(0===o.length)c=!0;else{let n=o[o.length-1];if(["{","[","(","|",","].includes(n)){let n=e.stringMathChildren[t+1];if("string"!=typeof n)c=!0;else{let t=n.trimStart();if(0===t.length)c=!0;else{let n=t[0];"latex"===e.format&&"\\"===n&&t.length>1&&(n=t[1]),["}","]",")","|",","].includes(n)||(c=!0)}}}else c=!0}c&&(l="("+l+")"),s+=l,l="",u.length>n+1?(a=n+1,i=u[a].firstInd):(a=void 0,i=void 0),n=void 0,r=void 0}}let c=null,p=[...e.functionSymbols];if(p.push(...e.mathChildrenFunctionSymbols.map((t=>e.codePre+t))),""===s)c=me$3.fromAst("_");else if("text"===e.format){let t=getFromText({functionSymbols:p,splitSymbols:e.splitSymbols,parseScientificNotation:e.parseScientificNotation});try{c=t(s)}catch(e){c=me$3.fromAst("_"),console.log("Invalid value for a math of text format: "+s)}}else if("latex"===e.format){let t=getFromLatex({functionSymbols:p,splitSymbols:e.splitSymbols,parseScientificNotation:e.parseScientificNotation});try{c=t(s)}catch(e){c=me$3.fromAst("_"),console.log("Invalid value for a math of latex format: "+s)}}return{setValue:{expressionWithCodes:c},setEssentialValue:{expressionWithCodes:c}}}function calculateMathValue({dependencyValues:e}={}){if(null===e.expressionWithCodes)return{setValue:{unnormalizedValue:e.valueShadow}};let t={};for(let[n,r]of e.mathChildren.entries())t[e.codePre+n]=r.stateValues.value;let n=e.expressionWithCodes;return e.mathChildren.length>0&&(n=n.substitute(t)),n=me$3.fromAst(mergeListsWithOtherContainers(n.tree)),{setValue:{unnormalizedValue:n}}}function calculateCodesAdjacentToStrings({dependencyValues:e}){let t,n=[];for(let[r,a]of e.stringMathChildren.entries())if("string"==typeof a){let a=e.stringMathChildren[r+1];if(void 0!==a&&"string"==typeof a)continue;let i={};if(void 0!==t&&("latex"===e.format?i.prevCode="\\operatorname{"+e.codePre+t+"}":i.prevCode=e.codePre+t),void 0!==a){let n=0;void 0!==t&&(n=t+1),"latex"===e.format?i.nextCode="\\operatorname{"+e.codePre+n+"}":i.nextCode=e.codePre+n}n.push(i)}else void 0===t?t=0:t++;return{setValue:{codesAdjacentToStrings:n}}}function determineCanBeModified({dependencyValues:e}){if(!e.modifyIndirectly||e.fixed)return{setValue:{canBeModified:!1,constantChildIndices:null,codeForExpression:null,inverseMaps:null,template:null,mathChildrenMapped:null}};if(0===e.mathChildrenModifiable.length)return e.displayedMathChildren.length>0?{setValue:{canBeModified:!1,constantChildIndices:null,codeForExpression:null,inverseMaps:null,template:null,mathChildrenMapped:null}}:{setValue:{canBeModified:!0,constantChildIndices:null,codeForExpression:null,inverseMaps:null,template:null,mathChildrenMapped:null}};let t=[],n=[],r=[],a={};for(let[i,s]of e.mathChildrenModifiable.entries()){let o=e.codePre+i;!0===s.stateValues.canBeModified?(t.push(i),n.push(o)):(r.push(o),a[o]=i)}let i=e.codePre+"expr",s=checkForLinearExpression(me$3.utils.unflattenLeft(e.expressionWithCodes.tree),n,i,r);if(s.foundLinear){let e={},r=s.template,o=new Set;for(let r in s.mappings){e[r]=s.mappings[r];let a=e[r].mathChildSub;if(a){let i=t[n.indexOf(a)];e[r].mathChildInd=i,o.add(Number(i))}}return o.has=o.has.bind(o),{setValue:{canBeModified:!0,constantChildIndices:a,codeForExpression:i,inverseMaps:e,template:r,mathChildrenMapped:o}}}return{setValue:{canBeModified:!1,constantChildIndices:null,codeForExpression:null,inverseMaps:null,template:null,mathChildrenMapped:null}}}function checkForLinearExpression(e,t,n,r=[],a=[]){let i=me$3.variables(e);if(i.every((e=>!t.includes(e)))&&i.every((e=>!r.includes(e)))){let e={},t="x"+a.join("_");return e[t]={result:me$3.fromAst(n).simplify(),components:a},{foundLinear:!0,mappings:e,template:t}}if(!Array.isArray(e))return checkForScalarLinearExpression(e,t,n,a);let s=e[0],o=e.slice(1);if(vectorAndListOperators.includes(s)){let e={mappings:{},template:[s]},i=0;for(let s=0;s!t.includes(e)))?(n=["+",n,["-",i[0]]],checkForScalarLinearExpression(i[1],t,n,r)):me$3.variables(i[1]).every((e=>!t.includes(e)))?(n=["+",n,["-",i[1]]],checkForScalarLinearExpression(i[0],t,n,r)):{foundLinear:!1}:"*"===a?me$3.variables(i[0]).every((e=>!t.includes(e)))?(n=["/",n,i[0]],checkForScalarLinearExpression(i[1],t,n,r)):me$3.variables(i[1]).every((e=>!t.includes(e)))?(n=["/",n,i[1]],checkForScalarLinearExpression(i[0],t,n,r)):{foundLinear:!1}:"/"===a&&me$3.variables(i[1]).every((e=>!t.includes(e)))?(n=["*",n,i[1]],checkForScalarLinearExpression(i[0],t,n,r)):{foundLinear:!1}}async function invertMath({desiredStateVariableValues:e,dependencyValues:t,stateValues:n,workspace:r,overrideFixed:a,componentName:i}){if(!await n.canBeModified&&!a)return{success:!1};let s=t.mathChildren,o=t.stringChildren.length;if(1===s.length&&0===o)return{success:!0,instructions:[{setDependency:"mathChildren",desiredValue:e.unnormalizedValue,childIndex:0,variableIndex:0}]};let l=convertValueToMathExpression(e.unnormalizedValue),u=await preprocessMathInverseDefinition({desiredValue:l,stateValues:n,variableName:"value",workspace:r}),c=u.vectorComponentsNotAffected;if(l=u.desiredValue,0===s.length){let f=[];return o>0?f.push({setDependency:"expressionWithCodes",desiredValue:l}):f.push({setDependency:"valueShadow",desiredValue:l}),{success:!0,instructions:f}}let p=await getExpressionPieces({expression:l,stateValues:n});if(!p)return{success:!1};let d=[],m=[];if(c&&await n.mathChildrenByVectorComponent){let y=await n.mathChildrenByVectorComponent;for(let g of c)y[g]&&m.push(...y[g])}let h=await n.mathChildrenWithCanBeModified;for(let[b,v]of s.entries())if(n.mathChildrenMapped.has(b)&&h[b].stateValues.canBeModified){if(!m.includes(b)){let N=p[b],T={},C=!1,A=await n.constantChildIndices;for(let V in A){let x=A[V];T[V]=s[x].stateValues.value,C=!0}C&&(N=N.substitute(T)),N=N.simplify(),d.push({setDependency:"mathChildren",desiredValue:N,childIndex:b,variableIndex:0})}delete p[b]}if(o>0){let S=t.expressionWithCodes,w=t.codePre,E=w.length;function D(e){return"string"==typeof e&&e.substring(0,E)===w}function O(e){return Array.isArray(e)?flattenDeep(e.slice(1)).some(D):D(e)}if(vectorAndListOperators.includes(S.tree[0])&&!S.tree.slice(1).every(O)){let I=await n.inverseMaps;for(let R in p){let _=I[R];if(void 0!==_.mathChildInd)continue;let M=_.components;S=S.substitute_component(M,p[R])}d.push({setDependency:"expressionWithCodes",desiredValue:S})}}return{success:!0,instructions:d}}async function getExpressionPieces({expression:e,stateValues:t}){let n=await t.template,r=me$3.utils.match(e.tree,n);if(!(r||(r=me$3.utils.match(e.tuples_to_vectors().tree,me$3.fromAst(n).tuples_to_vectors().tree),r||(r=me$3.utils.match(e.to_intervals().tree,me$3.fromAst(n).to_intervals().tree),r||(r=me$3.utils.match(e.tuples_to_vectors().to_intervals().tree,me$3.fromAst(n).tuples_to_vectors().to_intervals().tree),r)))))return!1;let a={};for(let e in r){let n={};n[await t.codeForExpression]=r[e];let i=(await t.inverseMaps)[e];if(void 0!==i){let r=e;void 0!==i.mathChildInd&&(r=i.mathChildInd),a[r]=i.result.substitute(n),a[r]=normalizeMathExpression({value:a[r],simplify:await t.simplify,expand:await t.expand,createVectors:await t.createVectors,createIntervals:await t.createIntervals})}}return a}class Label extends InlineComponent{constructor(e){super(e),Object.assign(this.actions,{moveLabel:this.moveLabel.bind(this)})}static componentType="label";static renderChildren=!0;static rendererType="label";static includeBlankStringChildren=!0;static primaryStateVariableForDefinition="valueShadow";static createAttributesObject(){let e=super.createAttributesObject();return e.forObject={createTargetComponentNames:!0},e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.layer={createComponentOfType:"number",createStateVariable:"layer",defaultValue:0,public:!0,forRenderer:!0},e.anchor={createComponentOfType:"point"},e.positionFromAnchor={createComponentOfType:"text",createStateVariable:"positionFromAnchor",defaultValue:"center",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft","top","bottom","left","right","center"]},e.styleNumber.defaultValue=0,e}static returnChildGroups(){return[{group:"inlines",componentTypes:["_inline"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnSelectedStyleStateVariableDefinition();return Object.assign(e,t),e.valueShadow={hasEssential:!0,defaultValue:null,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{valueShadow:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"valueShadow",value:e.valueShadow}]})},e.hasLatex={public:!0,forRenderer:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["inlines"],variableNames:["text","latex","value","hasLatex","renderAsMath"],variablesOptional:!0},valueShadow:{dependencyType:"stateVariable",variableName:"valueShadow"}}),definition:function({dependencyValues:e}){if(0===e.inlineChildren.length&&null!==e.valueShadow){let t=e.valueShadow;return{setValue:{hasLatex:Boolean(/\\\(.*\\\)/.exec(t))}}}for(let t of e.inlineChildren)if("object"!=typeof t);else if("boolean"==typeof t.stateValues.hasLatex&&"string"==typeof t.stateValues.value&&"string"==typeof t.stateValues.text){if(t.stateValues.hasLatex)return{setValue:{hasLatex:!0}}}else if("boolean"==typeof t.stateValues.renderAsMath&&"string"==typeof t.stateValues.latex&&"string"==typeof t.stateValues.text){if(t.stateValues.renderAsMath)return{setValue:{hasLatex:!0}}}else if("string"==typeof t.stateValues.latex)return{setValue:{hasLatex:!0}};return{setValue:{hasLatex:!1}}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},additionalStateVariablesDefined:[{variableName:"latex",public:!0,shadowingInstructions:{createComponentOfType:"text"}},{variableName:"value",public:!0,forRenderer:!0,shadowingInstructions:{createComponentOfType:"label",addStateVariablesShadowingStateVariables:{hasLatex:{stateVariableToShadow:"hasLatex"}}}}],returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["inlines"],variableNames:["text","latex","value","hasLatex","renderAsMath"],variablesOptional:!0},valueShadow:{dependencyType:"stateVariable",variableName:"valueShadow"},hasLatex:{dependencyType:"stateVariable",variableName:"hasLatex"}}),definition:function({dependencyValues:e}){if(0===e.inlineChildren.length&&null!==e.valueShadow){let t=e.valueShadow,n=t;return e.hasLatex&&(n=n.replace(/\\\(/g,""),n=n.replace(/\\\)/g,"")),{setValue:{text:n,latex:n,value:t}}}let t="",n="";for(let r of e.inlineChildren)if("object"!=typeof r){let e=r.toString();t+=e,n+=e}else"boolean"==typeof r.stateValues.hasLatex&&"string"==typeof r.stateValues.value&&"string"==typeof r.stateValues.text?(t+=r.stateValues.text,n+=r.stateValues.value):"boolean"==typeof r.stateValues.renderAsMath&&"string"==typeof r.stateValues.latex&&"string"==typeof r.stateValues.text?r.stateValues.renderAsMath?(t+=r.stateValues.latex,n+="\\("+r.stateValues.latex+"\\)"):(t+=r.stateValues.text,n+=r.stateValues.text):"string"==typeof r.stateValues.latex?(t+=r.stateValues.latex,n+="\\("+r.stateValues.latex+"\\)"):"string"==typeof r.stateValues.text&&(t+=r.stateValues.text,n+=r.stateValues.text);return{setValue:{text:t,latex:t,value:n}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){let n;if("string"==typeof e.value)n=e.value;else if("string"==typeof e.text)n=e.text;else{if("string"!=typeof e.latex)return{success:!1};n=e.latex}if(0===t.inlineChildren.length&&null!==t.valueShadow)return{success:!0,instructions:[{setDependency:"valueShadow",desiredValue:n}]};if(1===t.inlineChildren.length){let n=t.inlineChildren[0],r=e.value;if("object"!=typeof n)return{success:!0,instructions:[{setDependency:"inlineChildren",desiredValue:r,childIndex:0}]};if("boolean"==typeof n.stateValues.hasLatex&&"string"==typeof n.stateValues.value&&"string"==typeof n.stateValues.text)return{success:!0,instructions:[{setDependency:"inlineChildren",desiredValue:r,childIndex:0,variableIndex:2}]};if("boolean"==typeof n.stateValues.renderAsMath&&"string"==typeof n.stateValues.latex&&"string"==typeof n.stateValues.text){if(n.stateValues.renderAsMath){let e=r.match(/^\\\((.*)\\\)/);return e&&(r=e[1]),{success:!0,instructions:[{setDependency:"inlineChildren",desiredValue:r,childIndex:0,variableIndex:1}]}}return{success:!0,instructions:[{setDependency:"inlineChildren",desiredValue:r,childIndex:0,variableIndex:0}]}}if("string"==typeof n.stateValues.latex){let e=r.match(/^\\\((.*)\\\)/);return e&&(r=e[1]),{success:!0,instructions:[{setDependency:"inlineChildren",desiredValue:r,childIndex:0,variableIndex:1}]}}return"string"==typeof n.stateValues.text?{success:!0,instructions:[{setDependency:"inlineChildren",desiredValue:r,childIndex:0,variableIndex:0}]}:{success:!1}}return{success:!1}}},e.forObjectComponentName={returnDependencies:()=>({forObject:{dependencyType:"attributeTargetComponentNames",attributeName:"forObject"}}),definition({dependencyValues:e}){let t;return t=1===e.forObject?.length?e.forObject[0].absoluteName:null,{setValue:{forObjectComponentName:t}}}},e.anchor={defaultValue:me$3.fromText("(0,0)"),public:!0,forRenderer:!0,hasEssential:!0,shadowingInstructions:{createComponentOfType:"point"},returnDependencies:()=>({anchorAttr:{dependencyType:"attributeComponent",attributeName:"anchor",variableNames:["coords"]}}),definition:({dependencyValues:e})=>e.anchorAttr?{setValue:{anchor:e.anchorAttr.stateValues.coords}}:{useEssentialOrDefaultValue:{anchor:!0}},inverseDefinition:async({desiredStateVariableValues:e,dependencyValues:t,stateValues:n,initialChange:r})=>r&&!await n.draggable?{success:!1}:t.anchorAttr?{success:!0,instructions:[{setDependency:"anchorAttr",desiredValue:e.anchor,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"anchor",value:e.anchor}]}},e}static adapters=["text"];async moveLabel({x:e,y:t,z:n,transient:r,actionId:a}){let i=["vector"];return void 0!==e&&(i[1]=e),void 0!==t&&(i[2]=t),void 0!==n&&(i[3]=n),r?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],transient:r,actionId:a}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],actionId:a,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{x:e,y:t,z:n}}})}}function returnGroupIntoComponentTypeSeparatedBySpaces({componentType:e,forceComponentType:t=!1}){return function({matchedChildren:n,componentInfoObjects:r}){let a=[],i=[];function s(){let n=!1;if(t){if(1===i.length){let t=i[0],s=t.componentType;"copy"===s&&t.attributes?.createComponentOfType&&(t.attributes.nComponents&&1!==t.attributes.nComponents.primitive||(s=t.attributes.createComponentOfType.primitive)),r.isInheritedComponentType({inheritedComponentType:s,baseComponentType:e})&&(a.push(t),n=!0)}}else 1===i.length&&"string"!=typeof i[0]&&(a.push(i[0]),n=!0);!n&&i.length>0&&a.push({componentType:e,children:i}),i=[]}for(let e of n)if("string"!=typeof e)i.push(e);else{let t=e.split(/\s+/),n=t[0];""===n?s():i.push(n);for(let e of t.slice(1))s(),""!==e&&i.push(e)}return s(),{success:!0,newChildren:a}}}function returnBreakStringsIntoComponentTypeBySpaces({componentType:e}){return function({matchedChildren:t}){let n=t.reduce((function(t,n){return"string"==typeof n?[...t,...n.split(/\s+/).filter((e=>e)).map((t=>({componentType:e,children:[t]})))]:[...t,n]}),[]);return{success:!0,newChildren:n}}}class MathList extends InlineComponent{static componentType="mathList";static renderChildren=!0;static includeBlankStringChildren=!0;static removeBlankStringChildrenPostSugar=!0;static stateVariableForAttributeValue="maths";static primaryStateVariableForDefinition="mathsShadow";static descendantCompositesMustHaveAReplacement=!1;static createAttributesObject(){let e=super.createAttributesObject();return e.unordered={createComponentOfType:"boolean",createStateVariable:"unordered",defaultValue:!1,public:!0},e.maximumNumber={createComponentOfType:"number",createStateVariable:"maximumNumber",defaultValue:null,public:!0},e.mergeMathLists={createComponentOfType:"boolean"},e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.padZeros={createComponentOfType:"boolean",createStateVariable:"padZeros",defaultValue:!1,public:!0},e}static returnSugarInstructions(){let e=super.returnSugarInstructions(),t=returnGroupIntoComponentTypeSeparatedBySpaces({componentType:"math"}),n=returnBreakStringsIntoComponentTypeBySpaces({componentType:"math"});return e.push({replacementFunction:function({matchedChildren:e,isAttributeComponent:r=!1,createdFromMacro:a=!1}){return r&&!a?t({matchedChildren:e}):n({matchedChildren:e})}}),e}static returnChildGroups(){return[{group:"maths",componentTypes:["math"]},{group:"mathLists",componentTypes:["mathList"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.overrideChildHide={returnDependencies:()=>({}),definition:()=>({setValue:{overrideChildHide:!0}})},e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.displayDigitsAttr){let n=t.displayDigitsAttr,r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!n&&!r){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({}),definition:()=>({useEssentialOrDefaultValue:{mathsShadow:!0}})},e.mergeMathLists={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({mergeMathListsAttr:{dependencyType:"attributeComponent",attributeName:"mergeMathLists",variableNames:["value"]},mathListChildren:{dependencyType:"child",childGroups:["mathLists"],skipComponentNames:!0},mathChildren:{dependencyType:"child",childGroups:["maths"],skipComponentNames:!0}}),definition:({dependencyValues:e})=>({setValue:{mergeMathLists:e.mergeMathListsAttr?.stateValues.value||0===e.mathListChildren.length&&1===e.mathChildren.length}})},e.nComponents={public:!0,shadowingInstructions:{createComponentOfType:"number"},stateVariablesDeterminingDependencies:["mergeMathLists"],additionalStateVariablesDefined:["childIndexByArrayKey"],returnDependencies({stateValues:e}){let t={maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"},mergeMathLists:{dependencyType:"stateVariable",variableName:"mergeMathLists"},mathsShadow:{dependencyType:"stateVariable",variableName:"mathsShadow"}};return e.mergeMathLists?t.mathAndMathListChildren={dependencyType:"child",childGroups:["maths","mathLists"],variableNames:["value","nComponents"],variablesOptional:!0}:(t.mathListChildren={dependencyType:"child",childGroups:["mathLists"],variableNames:["nComponents"]},t.mathAndMathListChildren={dependencyType:"child",childGroups:["maths","mathLists"],skipComponentNames:!0}),t},definition:function({dependencyValues:e,componentInfoObjects:t}){let n=0,r=[];if(e.mathAndMathListChildren.length>0)if(e.mergeMathLists)for(let[a,i]of e.mathAndMathListChildren.entries())if(t.isInheritedComponentType({inheritedComponentType:i.componentType,baseComponentType:"mathList"})){for(let e=0;ea&&(n=a,r=r.slice(0,a)),{setValue:{nComponents:n,childIndexByArrayKey:r},checkForActualChange:{nComponents:!0}}}},e.maths={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},isArray:!0,entryPrefixes:["math"],stateVariablesDeterminingDependencies:["mergeMathLists","childIndexByArrayKey"],returnArraySizeDependencies:()=>({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"}}),returnArraySize:({dependencyValues:e})=>[e.nComponents],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=[],a="1";t.childIndexByArrayKey[r]&&(e=[t.childIndexByArrayKey[r][0]],a=t.childIndexByArrayKey[r][1]+1),n[r]={mathAndMathListChildren:{dependencyType:"child",childGroups:["maths","mathLists"],variableNames:["value","math"+a],variablesOptional:!0,childIndices:e}}}return{globalDependencies:{mergeMathLists:{dependencyType:"stateVariable",variableName:"mergeMathLists"},childIndexByArrayKey:{dependencyType:"stateVariable",variableName:"childIndexByArrayKey"},mathsShadow:{dependencyType:"stateVariable",variableName:"mathsShadow"}},dependenciesByKey:n}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};for(let a of n){let n=t[a].mathAndMathListChildren[0];if(n)if(void 0!==n.stateValues.value){let t=n.stateValues.value;if(e.mergeMathLists&&Array.isArray(t.tree)&&"list"===t.tree[0]){let n=e.childIndexByArrayKey[a][1];r[a]=t.get_component(n)}else r[a]=t}else{let t=e.childIndexByArrayKey[a][1]+1;r[a]=n.stateValues["math"+t]}else null!==e.mathsShadow&&(r[a]=e.mathsShadow[a])}return{setValue:{maths:r}}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,stateValues:a,workspace:i}){if(t.mergeMathLists){let t=[],s=await a.childIndexByArrayKey,o=[];for(let l in e.maths){if(!n[l])continue;if(o.includes(l))continue;let u;if(void 0!==s[l][2]){let t=Number(l)-s[l][1],n=t+s[l][2]-1;i.desiredMaths||(i.desiredMaths=[]);let r=["list"];for(let s=t;s<=n;s++)void 0!==e.maths[s]?i.desiredMaths[s]=convertValueToMathExpression(e.maths[s]):void 0===i.desiredMaths[s]&&(i.desiredMaths[s]=(await a.maths)[s]),r.push(i.desiredMaths[s].tree),o.push(s.toString());u=me$3.fromAst(r)}else u=e.maths[l];let c=n[l].mathAndMathListChildren[0];c&&(void 0!==c.stateValues.value?t.push({setDependency:r[l].mathAndMathListChildren,desiredValue:u,childIndex:0,variableIndex:0}):t.push({setDependency:r[l].mathAndMathListChildren,desiredValue:u,childIndex:0,variableIndex:1}))}return{success:!0,instructions:t}}let s=[];for(let t in e.maths){if(!n[t])continue;let a=n[t].mathAndMathListChildren[0];a&&(void 0!==a.stateValues.value?s.push({setDependency:r[t].mathAndMathListChildren,desiredValue:e.maths[t],childIndex:0,variableIndex:0}):s.push({setDependency:r[t].mathAndMathListChildren,desiredValue:e.maths[t],childIndex:0,variableIndex:1}))}return{success:!0,instructions:s}}},e.math={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},returnDependencies:()=>({maths:{dependencyType:"stateVariable",variableName:"maths"}}),definition({dependencyValues:e}){let t;return t=0===e.maths.length?me$3.fromAst("_"):1===e.maths.length?e.maths[0]:me$3.fromAst(["list",...e.maths.map((e=>e.tree))]),{setValue:{math:t}}}},e.nValues={isAlias:!0,targetVariableName:"nComponents"},e.values={isAlias:!0,targetVariableName:"maths"},e.latex={additionalStateVariablesDefined:["latexs"],public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({mathAndMathListChildren:{dependencyType:"child",childGroups:["maths","mathLists"],variableNames:["valueForDisplay","latex","latexs"],variablesOptional:!0},maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"},mergeMathLists:{dependencyType:"stateVariable",variableName:"mergeMathLists"},mathsShadow:{dependencyType:"stateVariable",variableName:"mathsShadow"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"}}),definition:function({dependencyValues:e,usedDefault:t}){let n=[],r={};if(e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(r.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(r.padToDigits=e.displayDigits)),e.mathAndMathListChildren.length>0)for(let t of e.mathAndMathListChildren)if(t.stateValues.valueForDisplay){let a=t.stateValues.valueForDisplay;if(e.mergeMathLists&&Array.isArray(a.tree)&&"list"===a.tree[0])for(let e=0;eroundForDisplay({value:n,dependencyValues:e,usedDefault:t}).toLatex(r))));let a=e.maximumNumber;return null!==a&&n.length>a&&(a=Math.max(0,Math.floor(a)),n=n.slice(0,a)),{setValue:{latex:n.join(", "),latexs:n}}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},additionalStateVariablesDefined:["texts"],returnDependencies:()=>({mathAndMathListChildren:{dependencyType:"child",childGroups:["maths","mathLists"],variableNames:["valueForDisplay","text","texts"],variablesOptional:!0},maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"},mergeMathLists:{dependencyType:"stateVariable",variableName:"mergeMathLists"},mathsShadow:{dependencyType:"stateVariable",variableName:"mathsShadow"}}),definition:function({dependencyValues:e}){let t=[];if(e.mathAndMathListChildren.length>0)for(let n of e.mathAndMathListChildren)if(n.stateValues.valueForDisplay){let r=n.stateValues.valueForDisplay;if(e.mergeMathLists&&Array.isArray(r.tree)&&"list"===r.tree[0])for(let e=0;ee.toString())));let n=e.maximumNumber;return null!==n&&t.length>n&&(n=Math.max(0,Math.floor(n)),t=t.slice(0,n)),{setValue:{text:t.join(", "),texts:t}}}},e.componentNamesInList={returnDependencies:()=>({mathAndMathListChildren:{dependencyType:"child",childGroups:["maths","mathLists"],variableNames:["componentNamesInList"],variablesOptional:!0},maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=[];for(let r of e.mathAndMathListChildren)t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"mathList"})?n.push(...r.stateValues.componentNamesInList):n.push(r.componentName);let r=e.maximumNumber;return null!==r&&n.length>r&&(r=Math.max(0,Math.floor(r)),n=n.slice(0,r)),{setValue:{componentNamesInList:n}}}},e.nComponentsToDisplayByChild={additionalStateVariablesDefined:["nChildrenToRender"],returnDependencies:()=>({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"},mathListChildren:{dependencyType:"child",childGroups:["mathLists"],variableNames:["nComponents"]},mathAndMathListChildren:{dependencyType:"child",childGroups:["maths","mathLists"],skipComponentNames:!0},parentNComponentsToDisplayByChild:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"nComponentsToDisplayByChild"}}),definition:function({dependencyValues:e,componentInfoObjects:t,componentName:n}){let r=e.nComponents;null!==e.parentNComponentsToDisplayByChild&&(r=e.parentNComponentsToDisplayByChild[n]);let a={},i=0,s=0,o=0;for(let n of e.mathAndMathListChildren){let l=Math.max(0,r-i);if(l>0&&s++,t.isInheritedComponentType({inheritedComponentType:n.componentType,baseComponentType:"mathList"})){let t=e.mathListChildren[o];o++;let n=Math.min(l,t.stateValues.nComponents);a[t.componentName]=n,i+=n}else i+=1}return{setValue:{nComponentsToDisplayByChild:a,nChildrenToRender:s}}},markStale:()=>({updateRenderedChildren:!0})},e}static adapters=[{stateVariable:"math",stateVariablesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},"text"]}class Columns extends Text{static componentType="columns";static rendererType="text"}class Title extends TextOrInline{static componentType="title"}class RightHandSide extends MathComponent{static componentType="rightHandSide";static rendererType="math"}class Description extends TextOrInline{static componentType="description";static rendererType=void 0}class Else extends Template{static componentType="else"}class Xlabel extends Label{static componentType="xlabel";static rendererType="label"}class Ylabel extends Label{static componentType="ylabel";static rendererType="label"}class MatrixRow extends MathList{static componentType="matrixRow";static rendererType="mathList"}class MatrixColumn extends MathList{static componentType="matrixColumn";static rendererType="mathList"}var Aliases=Object.freeze({__proto__:null,Columns:Columns,Title:Title,RightHandSide:RightHandSide,Description:Description,Else:Else,Xlabel:Xlabel,Ylabel:Ylabel,MatrixRow:MatrixRow,MatrixColumn:MatrixColumn});class M$3 extends InlineComponent{constructor(e){super(e),Object.assign(this.actions,{moveMath:this.moveMath.bind(this)})}static componentType="m";static rendererType="math";static includeBlankStringChildren=!0;static primaryStateVariableForDefinition="latex";static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.layer={createComponentOfType:"number",createStateVariable:"layer",defaultValue:0,public:!0,forRenderer:!0},e.anchor={createComponentOfType:"point"},e.positionFromAnchor={createComponentOfType:"text",createStateVariable:"positionFromAnchor",defaultValue:"center",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft","top","bottom","left","right","center"]},e.styleNumber.defaultValue=0,e}static returnChildGroups(){return[{group:"inline",componentTypes:["_inline"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnSelectedStyleStateVariableDefinition();return Object.assign(e,t),e.latex={public:!0,shadowingInstructions:{createComponentOfType:"text"},defaultValue:"",hasEssential:!0,forRenderer:!0,returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["inline"],variableNames:["latex","text"],variablesOptional:!0}}),definition:function({dependencyValues:e}){if(0===e.inlineChildren.length)return{useEssentialOrDefaultValue:{latex:!0}};let t="";for(let n of e.inlineChildren)"object"!=typeof n?t+=n:"string"==typeof n.stateValues.latex?t+=n.stateValues.latex:"string"==typeof n.stateValues.text&&(t+=n.stateValues.text);return{setValue:{latex:t}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){if("string"!=typeof e.latex)return{success:!1};if(0===t.inlineChildren.length)return{success:!0,instructions:[{setEssentialValue:"latex",value:e.latex}]};if(1===t.inlineChildren.length){let n=t.inlineChildren[0];return"object"!=typeof n?{success:!0,instructions:[{setDependency:"inlineChildren",desiredValue:e.latex,childIndex:0}]}:"string"==typeof n.stateValues.latex?{success:!0,instructions:[{setDependency:"inlineChildren",desiredValue:e.latex,childIndex:0,variableIndex:0}]}:"string"==typeof n.stateValues.text?{success:!0,instructions:[{setDependency:"inlineChildren",desiredValue:e.latex,childIndex:0,variableIndex:1}]}:{success:!1}}return{success:!1}}},e.latexWithInputChildren={forRenderer:!0,returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["inline"],variableNames:["latex","text"],variablesOptional:!0},latex:{dependencyType:"stateVariable",variableName:"latex"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){if(0===e.inlineChildren.length)return{setValue:{latexWithInputChildren:[e.latex]}};let n=[],r="",a=0;for(let i of e.inlineChildren)"object"!=typeof i?r+=i:t.isInheritedComponentType({inheritedComponentType:i.componentType,baseComponentType:"input"})?(r.length>0&&(n.push(r),r=""),n.push(a),a++):"string"==typeof i.stateValues.latex?r+=i.stateValues.latex:"string"==typeof i.stateValues.text&&(r+=i.stateValues.text);return r.length>0&&n.push(r),{setValue:{latexWithInputChildren:n}}}},e.renderMode={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{renderMode:"inline"}})},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({latex:{dependencyType:"stateVariable",variableName:"latex"}}),definition:function({dependencyValues:e}){let t;try{t=me$3.fromAst(latexToAst.convert(e.latex))}catch(t){return{setValue:{text:e.latex}}}return{setValue:{text:superSubscriptsToUnicode(t.toString())}}}},e.anchor={defaultValue:me$3.fromText("(0,0)"),public:!0,forRenderer:!0,hasEssential:!0,shadowingInstructions:{createComponentOfType:"point"},returnDependencies:()=>({anchorAttr:{dependencyType:"attributeComponent",attributeName:"anchor",variableNames:["coords"]}}),definition:({dependencyValues:e})=>e.anchorAttr?{setValue:{anchor:e.anchorAttr.stateValues.coords}}:{useEssentialOrDefaultValue:{anchor:!0}},inverseDefinition:async({desiredStateVariableValues:e,dependencyValues:t,stateValues:n,initialChange:r})=>r&&!await n.draggable?{success:!1}:t.anchorAttr?{success:!0,instructions:[{setDependency:"anchorAttr",desiredValue:e.anchor,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"anchor",value:e.anchor}]}},e}async moveMath({x:e,y:t,z:n,transient:r,actionId:a}){let i=["vector"];return void 0!==e&&(i[1]=e),void 0!==t&&(i[2]=t),void 0!==n&&(i[3]=n),r?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],transient:r,actionId:a}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],actionId:a,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{x:e,y:t,z:n}}})}}class Me$2 extends M$3{static componentType="me";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.renderMode.definition=()=>({setValue:{renderMode:"display"}}),e}}class Men extends M$3{static componentType="men";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.renderMode.definition=()=>({setValue:{renderMode:"numbered"}}),e.equationTag={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({equationCounter:{dependencyType:"counter",counterName:"equation"}}),definition:({dependencyValues:e})=>({setValue:{equationTag:String(e.equationCounter)}})},e}}var MMeMen=Object.freeze({__proto__:null,M:M$3,Me:Me$2,Men:Men});class Md extends InlineComponent{constructor(e){super(e),Object.assign(this.actions,{moveMath:this.moveMath.bind(this)})}static componentType="md";static rendererType="math";static primaryStateVariableForDefinition="latex";static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.layer={createComponentOfType:"number",createStateVariable:"layer",defaultValue:0,public:!0,forRenderer:!0},e.anchor={createComponentOfType:"point"},e.positionFromAnchor={createComponentOfType:"text",createStateVariable:"positionFromAnchor",defaultValue:"center",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft","top","bottom","left","right","center"]},e.styleNumber.defaultValue=0,e}static returnChildGroups(){return[{group:"mrows",componentTypes:["mrow"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnSelectedStyleStateVariableDefinition();return Object.assign(e,t),e.mrowChildNames={forRenderer:!0,returnDependencies:()=>({mrowChildren:{dependencyType:"child",childGroups:["mrows"]}}),definition:({dependencyValues:e})=>({setValue:{mrowChildNames:e.mrowChildren.map((e=>e.componentName))}})},e.latex={public:!0,shadowingInstructions:{createComponentOfType:"text"},defaultValue:"",hasEssential:!0,shadowVariable:!0,forRenderer:!0,returnDependencies:()=>({mrowChildren:{dependencyType:"child",childGroups:["mrows"],variableNames:["latex","hide","equationTag","numbered"]}}),definition:function({dependencyValues:e}){if(e.mrowChildren.length>0){let t="";for(let n of e.mrowChildren)n.stateValues.hide||(t.length>0&&(t+="\\\\"),n.stateValues.numbered?t+=`\\tag{${n.stateValues.equationTag}}`:t+="\\notag ",t+=n.stateValues.latex);return{setValue:{latex:t}}}return{useEssentialOrDefaultValue:{latex:!0}}}},e.latexWithInputChildren={forRenderer:!0,returnDependencies:()=>({mrowChildren:{dependencyType:"child",childGroups:["mrows"],variableNames:["latexWithInputChildren","hide","equationTag","numbered"]},latex:{dependencyType:"stateVariable",variableName:"latex"}}),definition:function({dependencyValues:e}){if(e.mrowChildren.length>0){let t=[],n=0,r="";for(let a of e.mrowChildren)if(!a.stateValues.hide){r.length>0&&(r+="\\\\"),a.stateValues.numbered?r+=`\\tag{${a.stateValues.equationTag}}`:r+="\\notag ";for(let e of a.stateValues.latexWithInputChildren)"number"==typeof e?(r.length>0&&(t.push(r),r=""),t.push(n),n++):r+=e}return r.length>0&&t.push(r),{setValue:{latexWithInputChildren:t}}}return{setValue:{latexWithInputChildren:[e.latex]}}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({latex:{dependencyType:"stateVariable",variableName:"latex"}}),definition:function({dependencyValues:e}){let t;try{t=e.latex.replaceAll("\\notag","").replaceAll("\\amp","").split("\\\\").map((e=>me$3.fromAst(latexToAst.convert(e)).toString())).join("\\\\\n")}catch(t){return{setValue:{text:e.latex}}}return{setValue:{text:superSubscriptsToUnicode(t.toString())}}}},e.renderMode={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{renderMode:"align"}})},e.numbered={returnDependencies:()=>({}),definition:()=>({setValue:{numbered:!1}})},e.anchor={defaultValue:me$3.fromText("(0,0)"),public:!0,forRenderer:!0,hasEssential:!0,shadowingInstructions:{createComponentOfType:"point"},returnDependencies:()=>({anchorAttr:{dependencyType:"attributeComponent",attributeName:"anchor",variableNames:["coords"]}}),definition:({dependencyValues:e})=>e.anchorAttr?{setValue:{anchor:e.anchorAttr.stateValues.coords}}:{useEssentialOrDefaultValue:{anchor:!0}},inverseDefinition:async({desiredStateVariableValues:e,dependencyValues:t,stateValues:n,initialChange:r})=>r&&!await n.draggable?{success:!1}:t.anchorAttr?{success:!0,instructions:[{setDependency:"anchorAttr",desiredValue:e.anchor,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"anchor",value:e.anchor}]}},e}async moveMath({x:e,y:t,z:n,transient:r,actionId:a}){let i=["vector"];return void 0!==e&&(i[1]=e),void 0!==t&&(i[2]=t),void 0!==n&&(i[3]=n),r?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],transient:r,actionId:a}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],actionId:a,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{x:e,y:t,z:n}}})}}class Mdn extends Md{static componentType="mdn";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numbered={returnDependencies:()=>({}),definition:()=>({setValue:{numbered:!0}})},e}}class Mrow extends M$3{static componentType="mrow";static createAttributesObject(){let e=super.createAttributesObject();return e.number={createComponentOfType:"boolean"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.renderMode.definition=()=>({setValue:{renderMode:"display"}}),e.numbered={forRenderer:!0,returnDependencies:()=>({parentNumbered:{dependencyType:"parentStateVariable",variableName:"numbered"},numberAttr:{dependencyType:"attributeComponent",attributeName:"number",variableNames:["value"]}}),definition({dependencyValues:e}){let t;return t=null!==e.numberAttr?e.numberAttr.stateValues.value:e.parentNumbered,{setValue:{numbered:t}}}},e.equationTag={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,stateVariablesDeterminingDependencies:["numbered"],returnDependencies:({stateValues:e})=>e.numbered?{equationCounter:{dependencyType:"counter",counterName:"equation"}}:{},definition:({dependencyValues:e})=>void 0!==e.equationCounter?{setValue:{equationTag:String(e.equationCounter)}}:{setValue:{equationTag:null}}},e}}var MdMdnMrow=Object.freeze({__proto__:null,Md:Md,Mdn:Mdn,Mrow:Mrow});function periodicSetEquality(e,t,{min_elements_match:n=3,match_partial:r=!1}={}){if(!is_periodic_set(e))return!1;if(is_periodic_set(t)){if(r){let n=contained_in(e.tree,t.tree,r);if(!1===n)return 0;let a=contained_in(t.tree,e.tree,r);return!1===a?0:!0===n?!0===a?1:a:!0===a?n:Math.min(n,a)}return contained_in(e.tree,t.tree,r)&&contained_in(t.tree,e.tree,r)}{let a=e.tree.slice(1);if(a.length>1)return!1;let i=me$3.fromAst(a[0][1]).evaluate_to_constant(),s=me$3.fromAst(["apply","abs",a[0][2]]).evaluate_to_constant();if(!Number.isFinite(i)||!Number.isFinite(s))return!1;let o=a[0][3],l=a[0][4];if(o!==-1/0||l!==1/0)return!1;if("list"!==t.tree[0])return!1;let u=t.tree.slice(1),c=0;if("ldots"===u[0][0])c++,u=u.slice(1);else if(!r)return!1;if("ldots"===u[u.length-1][0])c++,u=u.slice(0,u.length-1);else if(!r)return!1;let p=u.length;if(0===p)return!1;if(!r&&pme$3.fromAst(e).evaluate_to_constant())).map((e=>Number.isFinite(e)?e:NaN));let d=me$3.math.mod(u[0]-i,s);if(!(me$3.math.min(d,s-d)<1e-10*s))return!1;let m=1;for(let e=1;e=n)return!0;let h=m/Math.max(p,n);return h*=(9+c/2)/10,h}}function is_periodic_set(e){var t=e.tree;if(!Array.isArray(t))return!1;if("periodic_set"!==t[0])return!1;var n=t.slice(1);for(var r of n){if(!Array.isArray(r))return!1;if("tuple"!==r[0])return!1;if(5!==r.length)return!1}return!0}function contained_in(e,t,n){if("periodic_set"===e[0]){if(n){let r=0;for(let a of e.slice(1)){let e=contained_in(a,t,n);!0===e?r++:!1!==e&&(r+=e)}let a=e.length-1;return r===a||0!==r&&r/a}return e.slice(1).every((e=>contained_in(e,t)))}var r=e[1],a=e[2],i=e[3],s=e[4];if(i!==-1/0||s!==1/0)return!1;r=me$3.fromAst(["/",r,a]).evaluate_to_constant();var o=t.slice(1),l=[];for(let e=0;e1e3)return!1;let c=s.d;l.push([u,c,r,i])}for(l.sort();;){if(1!==l[0][0])break;let e=l[0][2],t=l[0][3],n=me$3.fromAst(["+",e,["-",r]]).evaluate_to_constant();if(Number.isFinite(n)&&Number.isFinite(t)&&(n=me$3.math.mod(n,t),me$3.math.min(n,t-n)<1e-10*t))return!0;if(l.splice(0,1),0===l.length)return!1}var u=[...new Set(l.map((e=>e[0])))];let c=0;for(let e of u){let t=l.map((function(t,n){let r=e/t[0];return Number.isInteger(r)?[t[0],r,n]:void 0})).filter((e=>e)),a=[];for(let n of t){let t=n[0],i=n[1],s=n[2],o=l[s][2],u=l[s][3];for(let n=0;nc&&(c=t)}}return!!(n&&c>0)&&c}const nonTupleVectorOperators=["vector","altvector"];function checkEquality({object1:e,object2:t,isUnordered:n=!1,partialMatches:r=!1,matchByExactPositions:a=!1,symbolicEquality:i=!1,simplify:s="none",expand:o=!1,allowedErrorInNumbers:l=0,includeErrorInNumberExponents:u=!1,allowedErrorIsAbsolute:c=!1,nSignErrorsMatched:p=0,nPeriodicSetMatchesRequired:d=3,caseInsensitiveMatch:m=!1,matchBlanks:h=!1}){let f=!1;if(e instanceof me$3.class){if(f=!0,!(t instanceof me$3.class)){if("number"!=typeof t&&"string"!=typeof t)return{fraction_equal:0};t=me$3.fromAst(t)}}else if(t instanceof me$3.class){if(f=!0,"number"!=typeof e&&"string"!=typeof e)return{fraction_equal:0};e=me$3.fromAst(e)}let y,g=function(e,t=!1){e instanceof me$3.class||(e=me$3.fromAst(e)),e=e.normalize_function_names().normalize_applied_functions(),m&&(e=me$3.fromAst(setStringsInTreeToLowerCase(e.tree)));let n=s,r=o;return t&&(n="full",r=!0),"none"===n?l>0&&(e=e.constants_to_floats()):e="numberspreserveorder"===n?e.evaluate_numbers({max_digits:1/0,skip_ordering:!0}):"number"===n?e.evaluate_numbers({max_digits:1/0}):e.evaluate_numbers({max_digits:1/0,evaluate_functions:!0}),normalizeMathExpression({value:e,simplify:n,expand:r})};y=f?i?function(e,t){let n=e,r=t;if(e instanceof me$3.class||(n=me$3.fromAst(e)),t instanceof me$3.class||(r=me$3.fromAst(t)),p>0){r=JSON.parse(JSON.stringify(r),me$3.reviver);let e=function(e,t){return!e.variables().includes("_")&&!t.variables().includes("_")&&(e=g(e)).equalsViaSyntax(t,{allowed_error_in_numbers:l,include_error_in_number_exponents:u,allowed_error_is_absolute:c,allow_blanks:h})};return n.tree.im||r.tree.im?{fraction_equal:0}:{fraction_equal:me$3.equalSpecifiedSignErrors(r,n,{equalityFunction:e,n_sign_errors:p})?1:0}}if(n.variables().includes("_")||r.variables().includes("_"))return{fraction_equal:0};if(n.tree.im||r.tree.im)return{fraction_equal:0};return{fraction_equal:n.equalsViaSyntax(r,{allowed_error_in_numbers:l,include_error_in_number_exponents:u,allowed_error_is_absolute:c,allow_blanks:h})?1:0}}:function(e,t){let n=e,r=t;if(e instanceof me$3.class||(n=me$3.fromAst(e)),t instanceof me$3.class||(r=me$3.fromAst(t)),m&&(n=me$3.fromAst(setStringsInTreeToLowerCase(n.tree)),r=me$3.fromAst(setStringsInTreeToLowerCase(r.tree))),p>0){r=JSON.parse(JSON.stringify(r),me$3.reviver);let e=function(e,t){return e.equals(t,{allowed_error_in_numbers:l,include_error_in_number_exponents:u,allowed_error_is_absolute:c,allow_blanks:h})};return n.tree.im||r.tree.im?{fraction_equal:0}:{fraction_equal:me$3.equalSpecifiedSignErrors(r,n,{equalityFunction:e,n_sign_errors:p})?1:0}}if(n.tree.im||r.tree.im)return{fraction_equal:0};return{fraction_equal:n.equals(r,{allowed_error_in_numbers:l,include_error_in_number_exponents:u,allowed_error_is_absolute:c,allow_blanks:h})?1:0}}:(e,t)=>(m&&(e=convertStringsToLowerCase(e),t=convertStringsToLowerCase(t)),{fraction_equal:deepCompare(e,t)?1:0});let b=!1,v=!1;if(f){e=g(e,!i),t=g(t,!i);let s=e.tree[0],o=t.tree[0];if("periodic_set"===s||"periodic_set"===o){let n=e,a=t;"periodic_set"!==s&&(n=t,a=e);let i=periodicSetEquality(n,a,{match_partial:r,min_elements_match:d});return!0===i?{fraction_equal:1}:!1===i?{fraction_equal:0}:{fraction_equal:i}}if("list"===s)e=e.tree.slice(1),t="list"===o?t.tree.slice(1):[t.tree];else if("list"===o)t=t.tree.slice(1),e=[e.tree];else if(nonTupleVectorOperators.includes(s)){if(e=e.tree.slice(1),"interval"===o||"matrix"===o||"array"===o||"set"===o)return{fraction_equal:0};t=vectorOperators.includes(o)?t.tree.slice(1):[t.tree]}else if(nonTupleVectorOperators.includes(o)){if(t=t.tree.slice(1),"interval"===s||"matrix"===s||"array"===s||"set"===s)return{fraction_equal:0};e="tuple"===s?e.tree.slice(1):[e.tree]}else if("interval"===s){a=!0;let n=e.tree[2],r=n[1],i=n[2];if(e=e.tree[1].slice(1),"matrix"===o||"set"===o)return{fraction_equal:0};if("tuple"===o){let e=t.tree.slice(1);if(2!==e.length||!1!==r||!1!==i)return{fraction_equal:0};t=e}else if("array"===o){let e=t.tree.slice(1);if(2!==e.length||!0!==r||!0!==i)return{fraction_equal:0};t=e}else{if("interval"!==o)return{fraction_equal:0};{let e=t.tree[2];if(e[1]!==r||e[2]!==i)return{fraction_equal:0};t=t.tree[1].slice(1)}}}else if("interval"===o){a=!0;let n=t.tree[2],r=n[1],i=n[2];if(t=t.tree[1].slice(1),"matrix"===s||"set"===s)return{fraction_equal:0};if("tuple"===s){let t=e.tree.slice(1);if(2!==t.length||!1!==r||!1!==i)return{fraction_equal:0};e=t}else{if("array"!==s)return{fraction_equal:0};{let t=e.tree.slice(1);if(2!==t.length||!0!==r||!0!==i)return{fraction_equal:0};e=t}}}else if("matrix"===s){if("matrix"!==o)return{fraction_equal:0};e=convertMatrixToArrayOfTuples(e.tree.slice(1)),t=convertMatrixToArrayOfTuples(t.tree.slice(1)),a=!0,v=!0,b=!0}else{if("matrix"===o)return{fraction_equal:0};if("set"===s){let r=[];for(let t of e.tree.slice(1))r.some((e=>1===y(e,t).fraction_equal))||r.push(t);if(e=r,n=!0,"tuple"===o||"array"===o)return{fraction_equal:0};if("set"===o){r=[];for(let e of t.tree.slice(1))r.some((t=>1===y(t,e).fraction_equal))||r.push(e);t=r}else t=[t.tree]}else if("set"===o){let r=[];for(let e of t.tree.slice(1))r.some((t=>1===y(t,e).fraction_equal))||r.push(e);if(t=r,n=!0,"tuple"===s||"array"===s)return{fraction_equal:0};e=[e.tree]}else if("tuple"===s){if(e=e.tree.slice(1),"array"===o)return{fraction_equal:0};t="tuple"===o?t.tree.slice(1):[t.tree]}else if("tuple"===o){if(t=t.tree.slice(1),"array"===s)return{fraction_equal:0};e=[e.tree]}else if("array"===s)e=e.tree.slice(1),t="array"===o?t.tree.slice(1):[t.tree];else{if("array"!==o)return y(e.tree,t.tree);t=t.tree.slice(1),e=[e.tree]}}}else if(Array.isArray(e))Array.isArray(t)||(t="string"==typeof t&&e.every((e=>"string"==typeof e&&!e.includes(",")))?t.split(",").map((e=>e.trim())):[t]);else{if(!Array.isArray(t))return y(e,t);e="string"==typeof e&&t.every((e=>"string"==typeof e&&!e.includes(",")))?e.split(",").map((e=>e.trim())):[e]}let N=e.length,T=t.length,C={fraction_equal:0};if(a&&(n=!1),!n){let n=0,u=Math.min(N,T);for(let r=0;rArray(T+1).fill(0)));for(let n=0;nr&&(r=t.fraction_equal,e=a)}-1!==e&&(V+=r,A.add(e))}return N===T&&N===V?(C.fraction_equal=1,C):r?(C.fraction_equal=V/Math.max(N,T),C):C}function setStringsInTreeToLowerCase(e){return"string"==typeof e?e.toLowerCase():Array.isArray(e)?[e[0],...e.slice(1).map(setStringsInTreeToLowerCase)]:e}function convertStringsToLowerCase(e){return"string"==typeof e?e.toLowerCase():Array.isArray(e)?e.map(convertStringsToLowerCase):e}function convertMatrixToArrayOfTuples(e){let t=e[0][1],n=e[0][2];if(!Number.isInteger(t)||!Number.isInteger(n))return e;let r=[];for(let a=0;aevaluateLogic({logicTree:e,canOverrideUnorderedCompare:t,dependencyValues:n,valueOnInvalid:r});if(!Array.isArray(e)){if("string"==typeof e){let t=n.booleanChildrenByCode[e];if(t)return n.matchPartial&&void 0!==t.stateValues.fractionSatisfied?t.stateValues.fractionSatisfied:t.stateValues.value?1:0;{let t=n.mathChildrenByCode[e];if(t){let e=t.stateValues.value.simplify().evaluate_to_constant();return Number.isFinite(e)&&0!==e?1:0}{let t=n.numberChildrenByCode[e];if(t){let e=t.stateValues.value;return Number.isFinite(e)&&0!==e?1:0}if("true"===e.toLowerCase())return 1;if("false"===e.toLowerCase())return 0}}}else if("number"==typeof e)return 0===e?0:1;return console.warn("Invalid format for boolean condition"),r}let i=e[0],s=e.slice(1);if("not"===i)return 1!==s.length?(console.warn("Invalid format for boolean condition"),r):0===a(s[0])?1:0;if("and"===i)return n.matchPartial?s.reduce(((e,t)=>e+a(t)),0)/s.length:s.every((e=>1===a(e)))?1:0;if("or"===i)return n.matchPartial?s.reduce(((e,t)=>Math.max(a(t),e)),0):s.some((e=>1===a(e)))?1:0;let o=!1,l=!1,u=!1,c=!1;s.forEach((function(e){"string"==typeof e&&(e in n.mathChildrenByCode||e in n.mathListChildrenByCode||e in n.numberChildrenByCode||e in n.numberListChildrenByCode?o=!0:e in n.textChildrenByCode||e in n.textListChildrenByCode?l=!0:e in n.booleanChildrenByCode||e in n.booleanListChildrenByCode?u=!0:e in n.otherChildrenByCode&&(c=!0))}));let p,d=function(e){if("string"==typeof e){let t=n.mathChildrenByCode[e];return void 0!==t?t.stateValues.value.tree:(t=n.mathListChildrenByCode[e],void 0!==t?["list",...t.stateValues.maths.map((e=>e.tree))]:(t=n.numberChildrenByCode[e],void 0!==t?numberToMathExpression(t.stateValues.value).tree:(t=n.numberListChildrenByCode[e],void 0!==t?["list",...t.stateValues.numbers]:e)))}return Array.isArray(e)?[e[0],...e.slice(1).map(d)]:e};if("apply"===i&&["isnumber","isinteger"].includes(s[0])){if(l||u||c)return 0;let e=me$3.fromAst(d(s[1])).simplify().evaluate_to_constant();if(!Number.isFinite(e))return 0;if("isnumber"===s[0])return 1;{let t=Math.round(e);return Math.abs(t-e)<=1e-15*Math.abs(e)?1:0}}if(!["=","ne","<",">","le","ge","lts","gts","in","notin"].includes(i)){if(l||u||c)return console.warn("Invalid format for boolean condition"),r;let t=me$3.fromAst(d(e)).simplify().evaluate_to_constant();return Number.isFinite(t)&&0!==t?1:0}if(u){if(o||l||c)return console.warn("Invalid format for boolean condition"),r;let e=!1,a=!1;if(s=s.map((function(t){if("string"==typeof t){let i=n.booleanChildrenByCode[t];return void 0!==i?i.stateValues.value:(i=n.booleanListChildrenByCode[t],void 0!==i?(i.stateValues.unordered&&(a=!0),i.stateValues.booleans):"true"===(t=t.toLowerCase().trim())||"t"===t||"false"!==t&&"f"!==t&&(console.warn("Invalid format for boolean condition"),e=!0,r))}return console.warn("Invalid format for boolean condition"),e=!0,r})),e)return r;let u=n.unorderedCompare;if(t&&a&&(u=!0),"="===i){let e=s[0];if(n.matchPartial){let t=s.slice(1).map((t=>checkEquality({object1:e,object2:t,isUnordered:u,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions}))),r=t.reduce(((e,t)=>e+t.fraction_equal),0);return r/t.length}return s.slice(1).every((t=>1===checkEquality({object1:e,object2:t,isUnordered:u,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions}).fraction_equal))?1:0}if("ne"===i){if(2!==s.length)return console.warn("Invalid format for boolean condition"),r;return 0===checkEquality({object1:s[0],object2:s[1],isUnordered:u,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions}).fraction_equal?1:0}return console.warn("Invalid format for boolean condition"),r}if(l){if(o||c)return console.warn("Invalid format for boolean condition"),r;let e=!1,a=!1,l=function(t,r=!1){if("string"==typeof t){let e=n.textChildrenByCode[t];return void 0!==e?e.stateValues.value.trim().replace(/\s+/," "):(e=n.textListChildrenByCode[t],void 0!==e?(e.stateValues.unordered&&(a=!0),e.stateValues.texts.map((e=>e.trim().replace(/\s+/," ")))):t.trim())}return"number"==typeof t?t.toString():r&&Array.isArray(t)&&"*"===t[0]?t.slice(1).map(l).join(" "):(console.warn("Invalid format for boolean condition"),e=!0,"")};if(s=s.map((e=>l(e,!0))),e)return r;let u=n.unorderedCompare;if(t&&a&&(u=!0),"="===i){let e=s[0];if(n.matchPartial){let t=s.slice(1).map((t=>checkEquality({object1:e,object2:t,isUnordered:u,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions,caseInsensitiveMatch:n.caseInsensitiveMatch}))),r=t.reduce(((e,t)=>e+t.fraction_equal),0);return r/t.length}return s.slice(1).every((t=>1===checkEquality({object1:e,object2:t,isUnordered:u,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions,caseInsensitiveMatch:n.caseInsensitiveMatch}).fraction_equal))?1:0}if("ne"===i){if(2!==s.length)return console.warn("Invalid format for boolean condition"),0;return 0===checkEquality({object1:s[0],object2:s[1],isUnordered:u,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions,caseInsensitiveMatch:n.caseInsensitiveMatch}).fraction_equal?1:0}return console.warn("Invalid format for boolean condition"),r}if(c){if(o)return console.warn("Invalid format for boolean condition"),r;let e=!1;return s=s.map((function(t){if("string"==typeof t){let e=n.otherChildrenByCode[t];if(void 0!==e)return e.stateValues.value}return console.warn("Invalid format for boolean condition"),e=!0,null})),e?r:"="===i?s.slice(1).every((e=>deepCompare(e,s[0])))?1:0:"ne"===i?2!==s.length?(console.warn("Invalid format for boolean condition"),0):deepCompare(s[0],s[1])?0:1:(console.warn("Invalid format for boolean condition"),0)}"lts"!==i&&"gts"!==i||(p=s[1].slice(1),s=s[0].slice(1));let m=!1,h=function(e){if("string"==typeof e){let t=n.mathChildrenByCode[e];return void 0!==t?(t.stateValues.unordered&&(m=!0),t.stateValues.value.tree):(t=n.mathListChildrenByCode[e],void 0!==t?(t.stateValues.unordered&&(m=!0),["list",...t.stateValues.maths.map((e=>e.tree))]):(t=n.numberChildrenByCode[e],void 0!==t?numberToMathExpression(t.stateValues.value).tree:(t=n.numberListChildrenByCode[e],void 0!==t?(t.stateValues.unordered&&(m=!0),["list",...t.stateValues.numbers]):e)))}return Array.isArray(e)?[e[0],...e.slice(1).map(h)]:e},f=s.map((function(e){return me$3.fromAst(h(e))})),y=n.unorderedCompare;if(t&&m&&(y=!0),"="===i){let e=f[0];if(Number.isNaN(e.tree))return f.slice(1).every((e=>Number.isNaN(e.tree)))?1:0;if(n.matchPartial){let t=f.slice(1).map((t=>checkEquality({object1:e,object2:t,isUnordered:y,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions,symbolicEquality:n.symbolicEquality,simplify:n.simplifyOnCompare,expand:n.expandOnCompare,allowedErrorInNumbers:n.allowedErrorInNumbers,includeErrorInNumberExponents:n.includeErrorInNumberExponents,allowedErrorIsAbsolute:n.allowedErrorIsAbsolute,nSignErrorsMatched:n.nSignErrorsMatched,nPeriodicSetMatchesRequired:n.nPeriodicSetMatchesRequired,caseInsensitiveMatch:n.caseInsensitiveMatch,matchBlanks:n.matchBlanks}))),r=t.reduce(((e,t)=>e+t.fraction_equal),0);return r/t.length}return f.slice(1).every((t=>1===checkEquality({object1:e,object2:t,isUnordered:y,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions,symbolicEquality:n.symbolicEquality,simplify:n.simplifyOnCompare,expand:n.expandOnCompare,allowedErrorInNumbers:n.allowedErrorInNumbers,includeErrorInNumberExponents:n.includeErrorInNumberExponents,allowedErrorIsAbsolute:n.allowedErrorIsAbsolute,nSignErrorsMatched:n.nSignErrorsMatched,nPeriodicSetMatchesRequired:n.nPeriodicSetMatchesRequired,caseInsensitiveMatch:n.caseInsensitiveMatch,matchBlanks:n.matchBlanks}).fraction_equal))?1:0}if("ne"===i){return 0===checkEquality({object1:f[0],object2:f[1],isUnordered:y,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions,symbolicEquality:n.symbolicEquality,simplify:n.simplifyOnCompare,expand:n.expandOnCompare,allowedErrorInNumbers:n.allowedErrorInNumbers,includeErrorInNumberExponents:n.includeErrorInNumberExponents,allowedErrorIsAbsolute:n.allowedErrorIsAbsolute,nSignErrorsMatched:n.nSignErrorsMatched,nPeriodicSetMatchesRequired:n.nPeriodicSetMatchesRequired,caseInsensitiveMatch:n.caseInsensitiveMatch,matchBlanks:n.matchBlanks}).fraction_equal?1:0}if("in"===i||"notin"===i){let e=f[0],t=f[1].tree;if(!Array.isArray(t)||"set"!==t[0])return console.warn("Invalid format for boolean condition"),r;if(n.matchPartial){let r=t.slice(1).map((t=>checkEquality({object1:e,object2:me$3.fromAst(t),isUnordered:y,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions,symbolicEquality:n.symbolicEquality,simplify:n.simplifyOnCompare,expand:n.expandOnCompare,allowedErrorInNumbers:n.allowedErrorInNumbers,includeErrorInNumberExponents:n.includeErrorInNumberExponents,allowedErrorIsAbsolute:n.allowedErrorIsAbsolute,nSignErrorsMatched:n.nSignErrorsMatched,nPeriodicSetMatchesRequired:n.nPeriodicSetMatchesRequired,caseInsensitiveMatch:n.caseInsensitiveMatch,matchBlanks:n.matchBlanks}))),a=r.reduce(((e,t)=>Math.max(e,t.fraction_equal)),0);return"in"===i?a:1-a}{let r=t.slice(1).some((t=>1===checkEquality({object1:e,object2:me$3.fromAst(t),isUnordered:y,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions,symbolicEquality:n.symbolicEquality,simplify:n.simplifyOnCompare,expand:n.expandOnCompare,allowedErrorInNumbers:n.allowedErrorInNumbers,includeErrorInNumberExponents:n.includeErrorInNumberExponents,allowedErrorIsAbsolute:n.allowedErrorIsAbsolute,nSignErrorsMatched:n.nSignErrorsMatched,nPeriodicSetMatchesRequired:n.nPeriodicSetMatchesRequired,caseInsensitiveMatch:n.caseInsensitiveMatch,matchBlanks:n.matchBlanks}).fraction_equal));return"in"===i?r?1:0:r?0:1}}let g=f.map((e=>e.simplify().evaluate_to_constant()));if(g.some((e=>null===e||Number.isNaN(e))))return 0;if("<"===i)return g[0]"===i)return g[0]>g[1]?1:0;if("le"===i)return g[0]<=g[1]?1:0;if("ge"===i)return g[0]>=g[1]?1:0;for(let e=0;eg[e+1]))return 0}else if(!(g[e]>=g[e+1]))return 0;return 1}function splitSymbolsIfMath({logicTree:e,nonMathCodes:t,foundNonMath:n=!1,init:r=!0}){if(!Array.isArray(e))return"string"!=typeof e||n||r?e:fromTextSplit(e).tree;let a=e[0],i=e.slice(1);if(["and","not","or"].includes(a))return[a,...i.map((e=>splitSymbolsIfMath({logicTree:e,nonMathCodes:t,foundNonMath:n,init:r})))];if(i.some((e=>t.includes(e)))&&(n=!0),"apply"===a){i=[i[0],...i.slice(1).map((e=>splitSymbolsIfMath({logicTree:e,nonMathCodes:t,foundNonMath:n,init:!1})))];let e=!1;if("int"===i[0]?e=!0:Array.isArray(i[0])&&("^"===i[0][0]?("int"===i[0][1]||Array.isArray(i[0][1])&&"_"===i[0][1][0]&&"int"===i[0][1][1])&&(e=!0):"_"===i[0][0]&&"int"===i[0][1]&&(e=!0)),e){i=me$3.fromAst([a,...i]).tree.slice(1);let e=i[1];if(Array.isArray(e)&&"*"===e[0]){let t=[];for(let n=0;nsplitSymbolsIfMath({logicTree:e,nonMathCodes:t,foundNonMath:n,init:!1})))]}class BooleanComponent extends InlineComponent{static componentType="boolean";static variableForPlainMacro="value";static descendantCompositesMustHaveAReplacement=!0;static descendantCompositesDefaultReplacementType="math";static createAttributesObject(){let e=super.createAttributesObject();return e.symbolicEquality={createComponentOfType:"boolean",createStateVariable:"symbolicEquality",defaultValue:!1,public:!0},e.expandOnCompare={createComponentOfType:"boolean",createStateVariable:"expandOnCompare",defaultValue:!1,public:!0},e.simplifyOnCompare={createComponentOfType:"text",createStateVariable:"simplifyOnCompare",defaultValue:"none",toLowerCase:!0,valueTransformations:{"":"full",true:"full"},validValues:["none","full","numbers","numbersepreserveorder"],public:!0},e.unorderedCompare={createComponentOfType:"boolean",createStateVariable:"unorderedCompare",defaultValue:!1,public:!0},e.matchByExactPositions={createComponentOfType:"boolean",createStateVariable:"matchByExactPositions",defaultValue:!1,public:!0},e.allowedErrorInNumbers={createComponentOfType:"number",createStateVariable:"allowedErrorInNumbers",defaultValue:0,public:!0},e.includeErrorInNumberExponents={createComponentOfType:"boolean",createStateVariable:"includeErrorInNumberExponents",defaultValue:!1,public:!0},e.allowedErrorIsAbsolute={createComponentOfType:"boolean",createStateVariable:"allowedErrorIsAbsolute",defaultValue:!1,public:!0},e.nSignErrorsMatched={createComponentOfType:"number",createStateVariable:"nSignErrorsMatched",defaultValue:0,public:!0},e.nPeriodicSetMatchesRequired={createComponentOfType:"integer",createStateVariable:"nPeriodicSetMatchesRequired",defaultValue:3,public:!0},e.caseInsensitiveMatch={createComponentOfType:"boolean",createStateVariable:"caseInsensitiveMatch",defaultValue:!1,public:!0},e.matchBlanks={createComponentOfType:"boolean",createStateVariable:"matchBlanks",defaultValue:!1,public:!0},e}static returnChildGroups(){return[{group:"strings",componentTypes:["string"]},{group:"comparableTypes",componentTypes:["math","mathList","number","numberList","text","textList","boolean","booleanList","orbitalDiagram"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.parsedExpression={additionalStateVariablesDefined:["codePre"],returnDependencies:()=>({allChildren:{dependencyType:"child",childGroups:["strings","comparableTypes"]},stringChildren:{dependencyType:"child",childGroups:["strings"],variableNames:["value"]}}),definition:buildParsedExpression},e.mathChildrenByCode={additionalStateVariablesDefined:["mathListChildrenByCode","numberChildrenByCode","numberListChildrenByCode","textChildrenByCode","textListChildrenByCode","booleanChildrenByCode","booleanListChildrenByCode","otherChildrenByCode"],returnDependencies:()=>({allChildren:{dependencyType:"child",childGroups:["strings","comparableTypes"],variableNames:["value","texts","maths","numbers","booleans","fractionSatisfied","unordered"],variablesOptional:!0},codePre:{dependencyType:"stateVariable",variableName:"codePre"}}),definition({dependencyValues:e,componentInfoObjects:t}){let n={},r={},a={},i={},s={},o={},l={},u={},c={},p=0,d=e.codePre;for(let m of e.allChildren)if("string"!=typeof m){let e=d+p;t.isInheritedComponentType({inheritedComponentType:m.componentType,baseComponentType:"math"})?n[e]=m:t.isInheritedComponentType({inheritedComponentType:m.componentType,baseComponentType:"mathList"})?r[e]=m:t.isInheritedComponentType({inheritedComponentType:m.componentType,baseComponentType:"number"})?a[e]=m:t.isInheritedComponentType({inheritedComponentType:m.componentType,baseComponentType:"numberList"})?i[e]=m:t.isInheritedComponentType({inheritedComponentType:m.componentType,baseComponentType:"text"})?s[e]=m:t.isInheritedComponentType({inheritedComponentType:m.componentType,baseComponentType:"textList"})?o[e]=m:t.isInheritedComponentType({inheritedComponentType:m.componentType,baseComponentType:"boolean"})?l[e]=m:t.isInheritedComponentType({inheritedComponentType:m.componentType,baseComponentType:"booleanList"})?u[e]=m:c[e]=m,p+=1}return{setValue:{mathChildrenByCode:n,mathListChildrenByCode:r,numberChildrenByCode:a,numberListChildrenByCode:i,textChildrenByCode:s,textListChildrenByCode:o,booleanChildrenByCode:l,booleanListChildrenByCode:u,otherChildrenByCode:c}}}},e.value={public:!0,shadowingInstructions:{createComponentOfType:"boolean",attributesToShadow:["fixed"]},forRenderer:!0,hasEssential:!0,defaultValue:!1,set:Boolean,returnDependencies:()=>({symbolicEquality:{dependencyType:"stateVariable",variableName:"symbolicEquality"},expandOnCompare:{dependencyType:"stateVariable",variableName:"expandOnCompare"},simplifyOnCompare:{dependencyType:"stateVariable",variableName:"simplifyOnCompare"},unorderedCompare:{dependencyType:"stateVariable",variableName:"unorderedCompare"},matchByExactPositions:{dependencyType:"stateVariable",variableName:"matchByExactPositions"},allowedErrorInNumbers:{dependencyType:"stateVariable",variableName:"allowedErrorInNumbers"},includeErrorInNumberExponents:{dependencyType:"stateVariable",variableName:"includeErrorInNumberExponents"},allowedErrorIsAbsolute:{dependencyType:"stateVariable",variableName:"allowedErrorIsAbsolute"},nSignErrorsMatched:{dependencyType:"stateVariable",variableName:"nSignErrorsMatched"},nPeriodicSetMatchesRequired:{dependencyType:"stateVariable",variableName:"nPeriodicSetMatchesRequired"},caseInsensitiveMatch:{dependencyType:"stateVariable",variableName:"caseInsensitiveMatch"},matchBlanks:{dependencyType:"stateVariable",variableName:"matchBlanks"},parsedExpression:{dependencyType:"stateVariable",variableName:"parsedExpression"},allChildren:{dependencyType:"child",childGroups:["strings","comparableTypes"],variableNames:["value"],variablesOptional:!0},booleanChildrenByCode:{dependencyType:"stateVariable",variableName:"booleanChildrenByCode"},booleanListChildrenByCode:{dependencyType:"stateVariable",variableName:"booleanListChildrenByCode"},textChildrenByCode:{dependencyType:"stateVariable",variableName:"textChildrenByCode"},textListChildrenByCode:{dependencyType:"stateVariable",variableName:"textListChildrenByCode"},mathChildrenByCode:{dependencyType:"stateVariable",variableName:"mathChildrenByCode"},mathListChildrenByCode:{dependencyType:"stateVariable",variableName:"mathListChildrenByCode"},numberChildrenByCode:{dependencyType:"stateVariable",variableName:"numberChildrenByCode"},numberListChildrenByCode:{dependencyType:"stateVariable",variableName:"numberListChildrenByCode"},otherChildrenByCode:{dependencyType:"stateVariable",variableName:"otherChildrenByCode"}}),definition({dependencyValues:e,usedDefault:t}){if(0===e.allChildren.length)return{useEssentialOrDefaultValue:{value:!0}};if(null===e.parsedExpression)return{setValue:{value:!1}};let n=t.unorderedCompare;return{setValue:{value:1===evaluateLogic({logicTree:e.parsedExpression.tree,canOverrideUnorderedCompare:n,dependencyValues:e})}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t,componentInfoObjects:n}){if(0===t.allChildren.length)return{success:!0,instructions:[{setEssentialValue:"value",value:Boolean(e.value)}]};if(1===t.allChildren.length){let r=t.allChildren[0];if("string"==typeof r)return{success:!0,instructions:[{setDependency:"allChildren",desiredValue:e.value.toString(),childIndex:0,variableIndex:0}]};if(n.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"boolean"}))return{success:!0,instructions:[{setDependency:"allChildren",desiredValue:e.value,childIndex:0,variableIndex:0}]}}return{success:!1}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:function({dependencyValues:e}){return{setValue:{text:e.value?"true":"false"}}},inverseDefinition({desiredStateVariableValues:e}){let t,n=String(e.text).toLowerCase();return"true"===n?t=!0:"false"===n&&(t=!1),void 0!==t?{success:!0,instructions:[{setDependency:"value",desiredValue:t}]}:{success:!1}}},e}static adapters=["text"]}class BooleanOperator extends BooleanComponent{static componentType="_booleanOperator";static rendererType="boolean";static descendantCompositesMustHaveAReplacement=!1;static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e}){let t=e.reduce((function(e,t){return"string"==typeof t?[...e,...t.split(/\s+/).filter((e=>e)).map((e=>({componentType:"boolean",children:[e]})))]:[...e,t]}),[]);return{success:!0,newChildren:t}}}),e}static returnChildGroups(){return[{group:"booleans",componentTypes:["boolean"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();delete e.parsedExpression,delete e.mathChildrenByCode;let t=this;return e.value={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,returnDependencies:()=>({booleanChildren:{dependencyType:"child",childGroups:["booleans"],variableNames:["value"]}}),definition:function({dependencyValues:e}){return{setValue:{value:t.applyBooleanOperator(e.booleanChildren.map((e=>e.stateValues.value)))}}}},e}}class BooleanOperatorOneInput extends BooleanComponent{static componentType="_booleanOperatorOneInput";static rendererType="boolean";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=this;return renameStateVariable({stateVariableDefinitions:e,oldName:"value",newName:"valuePreOperator"}),e.value={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"valuePreOperator"}}),definition:function({dependencyValues:e}){return{setValue:{value:t.applyBooleanOperator(e.value)}}}},e}}class Not extends BooleanOperatorOneInput{static componentType="not";static applyBooleanOperator(e){return!e}}class And extends BooleanOperator{static componentType="and";static applyBooleanOperator(e){return e.every((e=>e))}}class Or$1 extends BooleanOperator{static componentType="or";static applyBooleanOperator(e){return e.some((e=>e))}}class Xor extends BooleanOperator{static componentType="xor";static applyBooleanOperator(e){return 1===e.reduce(((e,t)=>e+t),0)}}var BooleanOperators=Object.freeze({__proto__:null,Not:Not,And:And,Or:Or$1,Xor:Xor});class BooleanBaseOperatorOfMath extends BooleanComponent{static componentType="_booleanOperatorOfMath";static rendererType="boolean";static returnSugarInstructions(){let e=[];return e.push({replacementFunction:function({matchedChildren:e}){return e.every((e=>"string"==typeof e||e.doenetAttributes&&e.doenetAttributes.createdFromMacro))?1===e.length&&"string"!=typeof e[0]?{success:!1}:{success:!0,newChildren:[{componentType:"math",children:e}]}:{success:!1}}}),e}static returnChildGroups(){return[{group:"maths",componentTypes:["math"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return delete e.parsedExpression,delete e.mathChildrenByCode,e.booleanOperator={returnDependencies:()=>({}),definition:()=>({setValue:{booleanOperator:e=>!1}})},e.value={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,returnDependencies:()=>({mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]},booleanOperator:{dependencyType:"stateVariable",variableName:"booleanOperator"}}),definition:function({dependencyValues:e}){return{setValue:{value:e.booleanOperator(e.mathChildren.map((e=>e.stateValues.value)))}}}},e}}class IsInteger extends BooleanBaseOperatorOfMath{static componentType="isInteger";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.booleanOperator.definition=()=>({setValue:{booleanOperator:function(e){if(0===e.length)return!1;if(1!==e.length)return console.warn("IsInteger requires exactly one math child"),null;let t=e[0].evaluate_to_constant();if(!Number.isFinite(t))return!1;let n=Math.round(t);return Math.abs(n-t)<=1e-15*Math.abs(t)}}}),e}}class IsNumber extends BooleanBaseOperatorOfMath{static componentType="isNumber";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.booleanOperator.definition=()=>({setValue:{booleanOperator:function(e){if(0===e.length)return!1;if(1!==e.length)return console.warn("IsNumber requires exactly one math child"),null;let t=e[0].evaluate_to_constant();return Number.isFinite(t)}}}),e}}class IsBetween extends BooleanBaseOperatorOfMath{static componentType="isBetween";static createAttributesObject(){let e=super.createAttributesObject();return e.limits={createComponentOfType:"numberList",createStateVariable:"limits",defaultValue:[],public:!0},e.strict={createComponentOfType:"boolean",createStateVariable:"strict",defaultValue:!1,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.booleanOperator={returnDependencies:()=>({limits:{dependencyType:"stateVariable",variableName:"limits"},strict:{dependencyType:"stateVariable",variableName:"strict"}}),definition({dependencyValues:e}){let t,n,r=e.limits[0],a=e.limits[1];if(r!1}};n=a,t=r}let i=e.strict;return{setValue:{booleanOperator:function(e){if(0===e.length)return!1;if(1!==e.length)return console.warn("IsBetween requires exactly one math child"),null;let r=e[0].evaluate_to_constant();return i?r>n&&r=n&&r<=t}}}}},e}}var BooleanOperatorsOfMath=Object.freeze({__proto__:null,IsInteger:IsInteger,IsNumber:IsNumber,IsBetween:IsBetween});class MathOperator extends MathComponent{static componentType="_mathOperator";static rendererType="math";static descendantCompositesMustHaveAReplacement=!1;static createAttributesObject(){let e=super.createAttributesObject();return e.forceSymbolic={createComponentOfType:"boolean",createStateVariable:"forceSymbolic",defaultValue:!1,public:!0},e.forceNumeric={createComponentOfType:"boolean",createStateVariable:"forceNumeric",defaultValue:!1,public:!0},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e}){let t=e.reduce((function(e,t){return"string"==typeof t?[...e,...t.split(/\s+/).filter((e=>e)).map((e=>({componentType:Number.isFinite(Number(e))?"number":"math",children:[e]})))]:[...e,t]}),[]);return{success:!0,newChildren:t}}}),e}static returnChildGroups(){return[{group:"maths",componentTypes:["math"]},{group:"numbers",componentTypes:["number"]},{group:"mathLists",componentTypes:["mathList"]},{group:"numberLists",componentTypes:["numberList"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},mathLikeChildren:{dependencyType:"child",childGroups:["maths","numbers","mathLists","numberLists"],variableNames:["displayDigits"]}}),definition:({dependencyValues:e,usedDefault:t})=>null!==e.displayDigitsAttr?{setValue:{displayDigits:e.displayDigitsAttr.stateValues.value}}:null!==e.displayDecimalsAttr||1!==e.mathLikeChildren.length||t.mathLikeChildren[0]&&t.mathLikeChildren[0].displayDigits?{useEssentialOrDefaultValue:{displayDigits:!0}}:{setValue:{displayDigits:e.mathLikeChildren[0].stateValues.displayDigits}}},e.displayDecimals={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:null,returnDependencies:()=>({displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},mathLikeChildren:{dependencyType:"child",childGroups:["maths","numbers","mathLists","numberLists"],variableNames:["displayDecimals"]}}),definition:({dependencyValues:e,usedDefault:t})=>null!==e.displayDecimalsAttr?{setValue:{displayDecimals:e.displayDecimalsAttr.stateValues.value}}:1!==e.mathLikeChildren.length||t.mathLikeChildren[0]&&t.mathLikeChildren[0].displayDecimals?{useEssentialOrDefaultValue:{displayDecimals:!0}}:{setValue:{displayDecimals:e.mathLikeChildren[0].stateValues.displayDecimals}}},e.displaySmallAsZero={public:!0,shadowingInstructions:{createComponentOfType:"number"},hasEssential:!0,defaultValue:0,returnDependencies:()=>({displaySmallAsZeroAttr:{dependencyType:"attributeComponent",attributeName:"displaySmallAsZero",variableNames:["value"]},mathLikeChildren:{dependencyType:"child",childGroups:["maths","numbers","mathLists","numberLists"],variableNames:["displaySmallAsZero"]}}),definition:({dependencyValues:e,usedDefault:t})=>null!==e.displaySmallAsZeroAttr?{setValue:{displaySmallAsZero:e.displaySmallAsZeroAttr.stateValues.value}}:1!==e.mathLikeChildren.length||t.mathLikeChildren[0]&&t.mathLikeChildren[0].displaySmallAsZero?{useEssentialOrDefaultValue:{displaySmallAsZero:!0}}:{setValue:{displaySmallAsZero:e.mathLikeChildren[0].stateValues.displaySmallAsZero}}},e.padZeros={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},hasEssential:!0,defaultValue:!1,returnDependencies:()=>({padZerosAttr:{dependencyType:"attributeComponent",attributeName:"padZeros",variableNames:["value"]},mathLikeChildren:{dependencyType:"child",childGroups:["maths","numbers","mathLists","numberLists"],variableNames:["padZeros"]}}),definition:({dependencyValues:e,usedDefault:t})=>null!==e.padZerosAttr?{setValue:{padZeros:e.padZerosAttr.stateValues.value}}:1!==e.mathLikeChildren.length||t.mathLikeChildren[0]&&t.mathLikeChildren[0].padZeros?{useEssentialOrDefaultValue:{padZeros:!0}}:{setValue:{padZeros:e.mathLikeChildren[0].stateValues.padZeros}}},e.isNumericOperator={returnDependencies:()=>({forceNumeric:{dependencyType:"stateVariable",variableName:"forceNumeric"},forceSymbolic:{dependencyType:"stateVariable",variableName:"forceSymbolic"},mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["isNumber"],variablesOptional:!0},mathListChildren:{dependencyType:"child",childGroups:["mathLists"],variableNames:["maths"]}}),definition({dependencyValues:e}){let t;return t=!!e.forceNumeric||!e.forceSymbolic&&(0===e.mathChildren.length&&0===e.mathListChildren.length||e.mathChildren.every((e=>e.stateValues.isNumber))&&e.mathListChildren.every((e=>e.stateValues.maths.every((e=>Number.isFinite(e.tree)))))),{setValue:{isNumericOperator:t}}}},delete e.codePre,delete e.expressionWithCodes,delete e.mathChildrenFunctionSymbols,delete e.codesAdjacentToStrings,delete e.mathChildrenByVectorComponent,e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:e=>me$3.fromAst("_")}})},e.numericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{numericOperator:e=>me$3.fromAst("_")}})},e.inverseMathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseMathOperator:null}})},e.inverseNumericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseNumericOperator:null}})},e.unnormalizedValue={returnDependencies:()=>({mathNumberChildren:{dependencyType:"child",childGroups:["maths","numbers","mathLists","numberLists"],variableNames:["value","maths","numbers","canBeModified"],variablesOptional:!0},isNumericOperator:{dependencyType:"stateVariable",variableName:"isNumericOperator"},mathOperator:{dependencyType:"stateVariable",variableName:"mathOperator"},numericOperator:{dependencyType:"stateVariable",variableName:"numericOperator"},inverseMathOperator:{dependencyType:"stateVariable",variableName:"inverseMathOperator"},inverseNumericOperator:{dependencyType:"stateVariable",variableName:"inverseNumericOperator"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){if(0===e.mathNumberChildren.length)return{setValue:{unnormalizedValue:me$3.fromAst("_")}};if(e.isNumericOperator){let n=[];for(let r of e.mathNumberChildren)if(t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"number"}))n.push(r.stateValues.value);else if(t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"math"})){let e=r.stateValues.value.evaluate_to_constant();Number.isFinite(e)||(e=NaN),n.push(e)}else if(t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"numberList"}))n.push(...r.stateValues.numbers);else{let e=r.stateValues.maths.map((e=>{let t=e.evaluate_to_constant();return Number.isFinite(t)||(t=NaN),t}));n.push(...e)}return{setValue:{unnormalizedValue:me$3.fromAst(e.numericOperator(n))}}}{let n=[];for(let r of e.mathNumberChildren)t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"number"})?n.push(me$3.fromAst(r.stateValues.value)):t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"math"})?n.push(r.stateValues.value):t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"numberList"})?n.push(...r.stateValues.numbers.map((e=>me$3.fromAst(e)))):n.push(...r.stateValues.maths);return{setValue:{unnormalizedValue:e.mathOperator(n)}}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t,componentInfoObjects:n}){if(0===t.mathNumberChildren.length)return{success:!1};if(t.isNumericOperator){if(t.inverseNumericOperator){let r=[],a=[],i=[];for(let[e,s]of t.mathNumberChildren.entries())if(n.isInheritedComponentType({inheritedComponentType:s.componentType,baseComponentType:"number"}))r.push(s.stateValues.value),a.push(s.stateValues.canBeModified),i.push(e);else if(n.isInheritedComponentType({inheritedComponentType:s.componentType,baseComponentType:"math"})){let t=s.stateValues.value.evaluate_to_constant();Number.isFinite(t)||(t=NaN),r.push(t),a.push(s.stateValues.canBeModified),i.push(e)}else if(n.isInheritedComponentType({inheritedComponentType:s.componentType,baseComponentType:"numberList"}))r.push(...s.stateValues.numbers),a.push(...Array(s.stateValues.numbers.length).fill(s.stateValues.canBeModified)),1===s.stateValues.numbers.length?i.push(e):i.push(...Array(s.stateValues.numbers.length).fill(NaN));else{let t=s.stateValues.maths.map((e=>{let t=e.evaluate_to_constant();return Number.isFinite(t)||(t=NaN),t}));r.push(...t),a.push(...Array(s.stateValues.maths.length).fill(s.stateValues.canBeModified)),1===s.stateValues.maths.length?i.push(e):i.push(...Array(s.stateValues.maths.length).fill(NaN))}let s=t.inverseNumericOperator({desiredValue:e.unnormalizedValue.evaluate_to_constant(),inputs:r,canBeModified:a,desiredMathValue:e.unnormalizedValue});if(s.success){let e=i[s.inputNumber];if(Number.isFinite(e)){let r=s.inputValue,a=0,i=t.mathNumberChildren[e];return n.isInheritedComponentType({inheritedComponentType:i.componentType,baseComponentType:"numberList"})?(a=2,r={0:r}):n.isInheritedComponentType({inheritedComponentType:i.componentType,baseComponentType:"mathList"})&&(a=1,r={0:r}),{success:!0,instructions:[{setDependency:"mathNumberChildren",desiredValue:r,childIndex:e,variableIndex:a}]}}return{success:!1}}return{success:!1}}return{success:!1}}if(t.inverseMathOperator){let r=[],a=[],i=[];for(let[e,s]of t.mathNumberChildren.entries())n.isInheritedComponentType({inheritedComponentType:s.componentType,baseComponentType:"number"})?(r.push(me$3.fromAst(s.stateValues.value)),a.push(s.stateValues.canBeModified),i.push(e)):n.isInheritedComponentType({inheritedComponentType:s.componentType,baseComponentType:"math"})?(r.push(s.stateValues.value),a.push(s.stateValues.canBeModified),i.push(e)):n.isInheritedComponentType({inheritedComponentType:s.componentType,baseComponentType:"numberList"})?(r.push(...s.stateValues.numbers.map((e=>me$3.fromAst(e)))),a.push(...Array(s.stateValues.numbers.length).fill(s.stateValues.canBeModified)),1===s.stateValues.numbers.length?i.push(e):i.push(...Array(s.stateValues.numbers.length).fill(NaN))):(r.push(...s.stateValues.maths),a.push(...Array(s.stateValues.maths.length).fill(s.stateValues.canBeModified)),1===s.stateValues.maths.length?i.push(e):i.push(...Array(s.stateValues.maths.length).fill(NaN)));let s=t.inverseMathOperator({desiredValue:e.unnormalizedValue,inputs:r,canBeModified:a});if(s.success){let e=i[s.inputNumber];if(Number.isFinite(e)){let r=s.inputValue,a=0,i=t.mathNumberChildren[e];return n.isInheritedComponentType({inheritedComponentType:i.componentType,baseComponentType:"numberList"})?(a=2,r={0:r}):n.isInheritedComponentType({inheritedComponentType:i.componentType,baseComponentType:"mathList"})&&(a=1,r={0:r}),{success:!0,instructions:[{setDependency:"mathNumberChildren",desiredValue:r,childIndex:e,variableIndex:a}]}}return{success:!1}}return{success:!1}}return{success:!1}}},e.canBeModified={returnDependencies:()=>({modifyIndirectly:{dependencyType:"stateVariable",variableName:"modifyIndirectly"},fixed:{dependencyType:"stateVariable",variableName:"fixed"},mathNumberChildren:{dependencyType:"child",childGroups:["maths","numbers"],variableNames:["canBeModified"]},mathNumberListChildren:{dependencyType:"child",childGroups:["mathLists","numberLists"],variableNames:["nComponents"]},isNumericOperator:{dependencyType:"stateVariable",variableName:"isNumericOperator"},inverseMathOperator:{dependencyType:"stateVariable",variableName:"mathOperator"},inverseNumericOperator:{dependencyType:"stateVariable",variableName:"inverseNumericOperator"}}),definition:function({dependencyValues:e}){let t=e.modifyIndirectly&&!e.fixed&&Boolean(e.isNumericOperator?e.inverseNumericOperator:e.inverseMathOperator);if(t&&e.mathNumberChildren.length+e.mathNumberListChildren.length>0){let n=e.mathNumberChildren.filter((e=>e.stateValues.canBeModified)).length+e.mathNumberListChildren.reduce(((e,t)=>e+t.stateValues.nComponents),0);1!==n&&(t=!1)}return{setValue:{canBeModified:t}}}},e}}class MathOperatorOneInput extends MathComponent{static componentType="_mathOperatorOneInput";static rendererType="math";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:e=>me.fromAst("_")}})},e.inverseMathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseMathOperator:null}})},renameStateVariable({stateVariableDefinitions:e,oldName:"unnormalizedValue",newName:"unnormalizedValuePreOperator"}),e.unnormalizedValue={returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"unnormalizedValuePreOperator"},mathOperator:{dependencyType:"stateVariable",variableName:"mathOperator"},inverseMathOperator:{dependencyType:"stateVariable",variableName:"inverseMathOperator"}}),definition:function({dependencyValues:e}){return{setValue:{unnormalizedValue:e.mathOperator(e.value)}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t,componentName:n}){if(t.inverseMathOperator){return{success:!0,instructions:[{setDependency:"value",desiredValue:t.inverseMathOperator(e.unnormalizedValue)}]}}return{success:!1}}},renameStateVariable({stateVariableDefinitions:e,oldName:"canBeModified",newName:"canBeModifiedPreOperator"}),e.canBeModified={returnDependencies:()=>({canBeModifiedPreOperator:{dependencyType:"stateVariable",variableName:"canBeModifiedPreOperator"},inverseMathOperator:{dependencyType:"stateVariable",variableName:"mathOperator"}}),definition:function({dependencyValues:e}){let t=e.canBeModifiedPreOperator;return e.inverseMathOperator||(t=!1),{setValue:{canBeModified:t}}}},e}}class Sum extends MathOperator{static componentType="sum";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{numericOperator:function(e){return e.reduce(((e,t)=>e+t))}}})},e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){return e.reduce(((e,t)=>e.add(t)))}}})},e}}class Product extends MathOperator{static componentType="product";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{numericOperator:function(e){return e.reduce(((e,t)=>e*t))}}})},e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){return e.reduce(((e,t)=>e.multiply(t)))}}})},e}}class ClampNumber extends MathOperatorOneInput{static componentType="clampNumber";static createAttributesObject(){let e=super.createAttributesObject();return e.lowerValue={createComponentOfType:"number",createStateVariable:"lowerValue",defaultValue:0,public:!0},e.upperValue={createComponentOfType:"number",createStateVariable:"upperValue",defaultValue:1,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.isNumericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{isNumericOperator:!0}})},e.mathOperator={returnDependencies:()=>({lowerValue:{dependencyType:"stateVariable",variableName:"lowerValue"},upperValue:{dependencyType:"stateVariable",variableName:"upperValue"}}),definition:({dependencyValues:e})=>({setValue:{mathOperator:function(t){return clamp({value:t,lowerValue:e.lowerValue,upperValue:e.upperValue})}}})},e.inverseMathOperator={returnDependencies:()=>({lowerValue:{dependencyType:"stateVariable",variableName:"lowerValue"},upperValue:{dependencyType:"stateVariable",variableName:"upperValue"}}),definition:({dependencyValues:e})=>({setValue:{inverseMathOperator:function(t){return clamp({value:t,lowerValue:e.lowerValue,upperValue:e.upperValue})}}})},e}}function clamp({value:e,lowerValue:t,upperValue:n}){let r=e;return r instanceof me$3.class&&(r=r.evaluate_to_constant()),Number.isFinite(r)?me$3.fromAst(Math.max(t,Math.min(n,r))):me$3.fromAst(NaN)}class WrapNumberPeriodic extends MathOperatorOneInput{static componentType="wrapNumberPeriodic";static createAttributesObject(){let e=super.createAttributesObject();return e.lowerValue={createComponentOfType:"number",createStateVariable:"lowerValue",defaultValue:0,public:!0},e.upperValue={createComponentOfType:"number",createStateVariable:"upperValue",defaultValue:1,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.isNumericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{isNumericOperator:!0}})},e.mathOperator={returnDependencies:()=>({lowerValue:{dependencyType:"stateVariable",variableName:"lowerValue"},upperValue:{dependencyType:"stateVariable",variableName:"upperValue"}}),definition:({dependencyValues:e})=>({setValue:{mathOperator:function(t){return makePeriodic({value:t,lowerValue:e.lowerValue,upperValue:e.upperValue})}}})},e.inverseMathOperator={returnDependencies:()=>({lowerValue:{dependencyType:"stateVariable",variableName:"lowerValue"},upperValue:{dependencyType:"stateVariable",variableName:"upperValue"}}),definition:({dependencyValues:e})=>({setValue:{inverseMathOperator:function(t){return makePeriodic({value:t,lowerValue:e.lowerValue,upperValue:e.upperValue})}}})},e}}function makePeriodic({value:e,lowerValue:t,upperValue:n}){let r=e;return r instanceof me$3.class&&(r=r.evaluate_to_constant()),Number.isFinite(r)?t===n?me$3.fromAst(t):(t>n&&([n,t]=[t,n]),me$3.fromAst(t+me$3.math.mod(r-t,n-t))):me$3.fromAst(NaN)}class Round extends MathOperatorOneInput{static componentType="round";static createAttributesObject(){let e=super.createAttributesObject();return e.numberDecimals={createComponentOfType:"number",createStateVariable:"numberDecimals",defaultValue:0,public:!0},e.numberDigits={createComponentOfType:"number",createStateVariable:"numberDigits",defaultValue:null,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.mathOperator={returnDependencies:()=>({numberDecimals:{dependencyType:"stateVariable",variableName:"numberDecimals"},numberDigits:{dependencyType:"stateVariable",variableName:"numberDigits"}}),definition:({dependencyValues:e})=>({setValue:{mathOperator:function(t){let n=t.evaluate_numbers({max_digits:1/0,evaluate_functions:!0});return null!==e.numberDigits?n.round_numbers_to_precision(e.numberDigits):n.round_numbers_to_decimals(e.numberDecimals)}}})},e.inverseMathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseMathOperator:e=>e}})},e}}class setSmallToZero extends MathOperatorOneInput{static componentType="setSmallToZero";static createAttributesObject(){let e=super.createAttributesObject();return e.threshold={createComponentOfType:"number",createStateVariable:"threshold",defaultValue:1e-14,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.mathOperator={returnDependencies:()=>({threshold:{dependencyType:"stateVariable",variableName:"threshold"}}),definition:({dependencyValues:e})=>({setValue:{mathOperator:function(t){return t.evaluate_numbers({skip_ordering:!0,set_small_zero:e.threshold})}}})},e.inverseMathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseMathOperator:e=>e}})},e}}class ConvertSetToList extends MathOperatorOneInput{static componentType="convertSetToList";static createAttributesObject(){let e=super.createAttributesObject();return delete e.unordered,e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.unordered={returnDependencies:()=>({}),definition:()=>({setValue:{unordered:!0}})},e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){if(void 0!==e&&Array.isArray(e.tree)&&"set"===e.tree[0]){let t=[];for(let n of e.tree.slice(1))t.some((t=>e.context.equalsViaSyntax(e.context.fromAst(t),e.context.fromAst(n))))||t.push(n);return e.context.fromAst(["list",...t])}return e}}})},e}}class Ceil extends MathOperatorOneInput{static componentType="ceil";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){let t=e.evaluate_to_constant();if(!Number.isFinite(t))return me$3.fromAst(["apply","ceil",e.tree]);let n=Math.round(t);return Math.abs((n-t)/t)<1e-15?me$3.fromAst(n):me$3.fromAst(Math.ceil(t))}}})},e.inverseMathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseMathOperator:e=>e}})},e}}class Floor extends MathOperatorOneInput{static componentType="floor";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){let t=e.evaluate_to_constant();if(!Number.isFinite(t))return me$3.fromAst(["apply","floor",e.tree]);let n=Math.round(t);return Math.abs((n-t)/t)<1e-15?me$3.fromAst(n):me$3.fromAst(Math.floor(t))}}})},e.inverseMathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseMathOperator:e=>e}})},e}}class Abs extends MathOperatorOneInput{static componentType="abs";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){let t=e.evaluate_to_constant();return Number.isFinite(t)?me$3.fromAst(Math.abs(t)):me$3.fromAst(["apply","abs",e.tree])}}})},e.inverseMathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseMathOperator:function(e){let t=e,n=e.evaluate_to_constant();return Number.isFinite(n)?n<0&&(t=me$3.fromAst(0)):Array.isArray(e.tree)&&"apply"===e.tree[0]&&"abs"===e.tree[1]&&(t=me$3.fromAst(e.tree[2])),t}}})},e}}class Sign extends MathOperatorOneInput{static componentType="sign";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){let t=e.evaluate_to_constant();return Number.isFinite(t)?me$3.fromAst(Math.sign(t)):me$3.fromAst(["apply","sign",e.tree])}}})},e}}class Mean extends MathOperator{static componentType="mean";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{numericOperator:function(e){let t=e.reduce(((e,t)=>e+t));return t/=e.length,t}}})},e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){return e.reduce(((e,t)=>e.add(t))).divide(e.length)}}})},e}}class Variance extends MathOperator{static componentType="variance";static createAttributesObject(){let e=super.createAttributesObject();return e.population={createComponentOfType:"boolean",createStateVariable:"population",defaultValue:!1,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numericOperator={returnDependencies:()=>({population:{dependencyType:"stateVariable",variableName:"population"}}),definition:({dependencyValues:e})=>({setValue:{numericOperator:function(t){return calculateNumericVariance(t,e.population)}}})},e.mathOperator={returnDependencies:()=>({population:{dependencyType:"stateVariable",variableName:"population"}}),definition:({dependencyValues:e})=>({setValue:{mathOperator:function(t){return calculateSymbolicVariance(t,e.population)}}})},e}}function calculateNumericVariance(e,t){let n=0,r=0;for(let t of e)n+=t,r+=t*t;let a=e.length;return r-=n**2/a,r/=t?a:a-1,r}function calculateSymbolicVariance(e,t){let n=e.length,r=e.reduce(((e,t)=>e.add(t))),a=e.slice(1).reduce(((e,t)=>e.add(t.pow(2))),e[0].pow(2)).subtract(r.pow(2).divide(n));return a=t?a.divide(n):a.divide(n-1),a}class StandardDeviation extends Variance{static componentType="standardDeviation";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numericOperator.definition=({dependencyValues:e})=>({setValue:{numericOperator:function(t){return Math.sqrt(calculateNumericVariance(t,e.population))}}}),e.mathOperator.definition=({dependencyValues:e})=>({setValue:{mathOperator:function(t){return me$3.fromAst(["apply","sqrt",calculateSymbolicVariance(t,e.population).tree])}}}),e}}class Count extends MathOperator{static componentType="count";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.isNumericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{isNumericOperator:!0}})},e.numericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{numericOperator:function(e){return e.length}}})},e}}class Min extends MathOperator{static componentType="min";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{numericOperator:function(e){return e.reduce(((e,t)=>Math.min(e,t)),1/0)}}})},e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){return me$3.fromAst(["apply","min",["tuple",...e.map((e=>e.tree))]])}}})},e.inverseMathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseMathOperator:function({desiredValue:e,canBeModified:t}){if(1===t.filter((e=>e)).length){let n=t.indexOf(!0);if(n>=0)return{success:!0,inputValue:e,inputNumber:n}}return{success:!1}}}})},e.inverseNumericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseNumericOperator:function({desiredValue:e,canBeModified:t,desiredMathValue:n}){if(1===t.filter((e=>e)).length){let r=t.indexOf(!0);if(r>=0)return Number.isFinite(e)||(e=n),{success:!0,inputValue:e,inputNumber:r}}return{success:!1}}}})},e}}class Max extends MathOperator{static componentType="max";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{numericOperator:function(e){return e.reduce(((e,t)=>Math.max(e,t)),-1/0)}}})},e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){return me$3.fromAst(["apply","max",["tuple",...e.map((e=>e.tree))]])}}})},e.inverseMathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseMathOperator:function({desiredValue:e,canBeModified:t}){if(1===t.filter((e=>e)).length){let n=t.indexOf(!0);if(n>=0)return{success:!0,inputValue:e,inputNumber:n}}return{success:!1}}}})},e.inverseNumericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseNumericOperator:function({desiredValue:e,canBeModified:t,desiredMathValue:n}){if(1===t.filter((e=>e)).length){let r=t.indexOf(!0);if(r>=0)return Number.isFinite(e)||(e=n),{success:!0,inputValue:e,inputNumber:r}}return{success:!1}}}})},e}}class Mod extends MathOperator{static componentType="mod";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{numericOperator:function(e){return 2!==e.length?NaN:me$3.math.mod(e[0],e[1])}}})},e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){return 2!==e.length?me$3.fromAst("_"):me$3.fromAst(["apply","mod",["tuple",...e.map((e=>e.tree))]])}}})},e}}class Gcd extends MathOperator{static componentType="gcd";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{numericOperator:function(e){return e.every(Number.isInteger)?gcd(...e):NaN}}})},e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){return me$3.fromAst(["apply","gcd",["tuple",...e.map((e=>e.tree))]])}}})},e}}class ExtractMath extends MathOperatorOneInput{static componentType="extractMath";static createAttributesObject(){let e=super.createAttributesObject();return e.type={createComponentOfType:"text",createStateVariable:"type",defaultValue:null,toLowerCase:!0,validValues:["operand","function","functionargument","numberofoperands"]},e.operandNumber={createComponentOfType:"number",createStateVariable:"operandNumber",defaultValue:null,public:!0},e.argumentNumber={createComponentOfType:"number",createStateVariable:"argumentNumber",defaultValue:null,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.mathOperator={returnDependencies:()=>({type:{dependencyType:"stateVariable",variableName:"type"},operandNumber:{dependencyType:"stateVariable",variableName:"operandNumber"},argumentNumber:{dependencyType:"stateVariable",variableName:"argumentNumber"}}),definition:({dependencyValues:e})=>"operand"===e.type?null===e.operandNumber?(console.warn("Must specify a operandNumber when extracting a math operand"),{setValue:{mathOperator:e=>me$3.fromAst("_")}}):{setValue:{mathOperator:function(t){let n=t.tree;if(!Array.isArray(n))return 1===e.operandNumber?t:me$3.fromAst("_");if("apply"===n[0])return 1===e.operandNumber?t:me$3.fromAst("_");let r=n[e.operandNumber];return void 0===r?me$3.fromAst("_"):me$3.fromAst(r)}}}:"function"===e.type?{setValue:{mathOperator:function(e){let t=e.tree;return Array.isArray(t)?"apply"!==t[0]?me$3.fromAst("_"):me$3.fromAst(t[1]):me$3.fromAst("_")}}}:"functionargument"===e.type?{setValue:{mathOperator:function(t){let n=t.tree;if(!Array.isArray(n))return me$3.fromAst("_");if("apply"!==n[0])return me$3.fromAst("_");let r=n[2];if(null===e.argumentNumber)return me$3.fromAst(r);if(1===e.argumentNumber)return Array.isArray(r)&&"tuple"===r[0]?me$3.fromAst(r[1]):me$3.fromAst(r);if(Array.isArray(r)&&"tuple"===r[0]){let t=r[e.argumentNumber];return void 0===t?me$3.fromAst("_"):me$3.fromAst(t)}return me$3.fromAst("_")}}}:"numberofoperands"===e.type?{setValue:{mathOperator:function(e){let t=e.tree;return Array.isArray(t)?"apply"===t[0]?me$3.fromAst(1):me$3.fromAst(t.length-1):me$3.fromAst(1)}}}:{setValue:{mathOperator:e=>me$3.fromAst("_")}}},e}}function gcd(e,t,...n){return!t&&n.length>0?gcd(e,...n):t?gcd(t,e%t,...n):e}var MathOperators=Object.freeze({__proto__:null,Sum:Sum,Product:Product,ClampNumber:ClampNumber,WrapNumberPeriodic:WrapNumberPeriodic,Round:Round,setSmallToZero:setSmallToZero,ConvertSetToList:ConvertSetToList,Ceil:Ceil,Floor:Floor,Abs:Abs,Sign:Sign,Mean:Mean,Variance:Variance,StandardDeviation:StandardDeviation,Count:Count,Min:Min,Max:Max,Mod:Mod,Gcd:Gcd,ExtractMath:ExtractMath});function returnLabelStateVariableDefinitions(){let e={};return e.componentNameAndShadowSourceNames={returnDependencies:()=>({shadowSource:{dependencyType:"shadowSource",variableNames:["componentNameAndShadowSourceNames"]},unlinkedCopySource:{dependencyType:"unlinkedCopySource",variableNames:["componentNameAndShadowSourceNames"]}}),definition({dependencyValues:e,componentName:t}){let n=[t];return e.shadowSource?.stateValues.componentNameAndShadowSourceNames?n.push(...e.shadowSource.stateValues.componentNameAndShadowSourceNames):e.unlinkedCopySource?.stateValues.componentNameAndShadowSourceNames&&n.push(...e.unlinkedCopySource.stateValues.componentNameAndShadowSourceNames),{setValue:{componentNameAndShadowSourceNames:n}}}},e.label={forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"label",addStateVariablesShadowingStateVariables:{hasLatex:{stateVariableToShadow:"labelHasLatex"}}},hasEssential:!0,doNotShadowEssential:!0,defaultValue:"",provideEssentialValuesInDefinition:!0,additionalStateVariablesDefined:[{variableName:"labelHasLatex",forRenderer:!0}],returnDependencies:()=>({labelChild:{dependencyType:"child",childGroups:["labels"],variableNames:["value","hasLatex"]},labelIsName:{dependencyType:"stateVariable",variableName:"labelIsName"},labelIsNameAttr:{dependencyType:"attributeComponent",attributeName:"labelIsName"},componentNameAndShadowSourceNames:{dependencyType:"stateVariable",variableName:"componentNameAndShadowSourceNames"},shadowSource:{dependencyType:"shadowSource",variableNames:["label","labelHasLatex"]}}),definition({dependencyValues:e,essentialValues:t}){let n=e.labelChild[e.labelChild.length-1];if(n&&!n.shadowDepth)return{setValue:{label:n.stateValues.value,labelHasLatex:n.stateValues.hasLatex}};if(void 0!==t.label)return{useEssentialOrDefaultValue:{label:!0},setValue:{labelHasLatex:!1}};if(e.labelIsName&&!e.labelIsNameAttr.shadowDepth){let t="__",n=e.componentNameAndShadowSourceNames;for(let e of n){let n=e.lastIndexOf("/");if(t=e.substring(n+1),"__"!==t.slice(0,2))break}return"__"===t.slice(0,2)?{setValue:{label:"",labelHasLatex:!1}}:("_"!==t[0]&&(t.includes("_")||t.includes("-")?t=t.replace(/[_\-]/g," "):t.match(/^[a-z]/)?t.match(/[A-Z]/)&&(t=t.replace(/([A-Z])/g," $1").toLowerCase()):t.match(/^[A-Z]/)&&t.match(/[a-z]/)&&(t=t.replace(/([A-Z])/g," $1"),t=t.slice(1))),{setValue:{label:t,labelHasLatex:!1}})}return"string"==typeof e.shadowSource?.stateValues.label?{setValue:{label:e.shadowSource.stateValues.label,labelHasLatex:Boolean(e.shadowSource.stateValues.labelHasLatex)}}:{useEssentialOrDefaultValue:{label:!0},setValue:{labelHasLatex:!1}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){if("string"!=typeof e.label)return{success:!1};let n=t.labelChild.length-1,r=t.labelChild[n];return r&&!r.shadowDepth?{success:!0,instructions:[{setDependency:"labelChild",desiredValue:e.label,childIndex:n,variableIndex:0}]}:t.labelIsName&&!t.labelIsNameAttr.shadowDepth?{success:!0,instructions:[{setEssentialValue:"label",value:e.label}]}:"string"==typeof t.shadowSource?.stateValues.label?{success:!0,instructions:[{setDependency:"shadowSource",desiredValue:e.label,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"label",value:e.label}]}}},e.labelForGraph={forRenderer:!0,returnDependencies:()=>({label:{dependencyType:"stateVariable",variableName:"label"},labelHasLatex:{dependencyType:"stateVariable",variableName:"labelHasLatex"}}),definition({dependencyValues:e}){let t;if(e.labelHasLatex){let n=0;t="";for(let r of e.label)"("===r?n++:")"===r?n--:0===n&&("_"===r?r="_":"^"===r&&(r="^")),t+=r}else t=e.label.replaceAll("_","_").replaceAll("^","^");return{setValue:{labelForGraph:t}}}},e}class GraphicalComponent extends BaseComponent{static componentType="_graphical";static createAttributesObject(){let e=super.createAttributesObject();return e.labelIsName={createComponentOfType:"boolean",createStateVariable:"labelIsName",defaultValue:!1,public:!0},e.showLabel={createComponentOfType:"boolean",createStateVariable:"showLabel",defaultValue:!0,public:!0,forRenderer:!0},e.applyStyleToLabel={createComponentOfType:"boolean",createStateVariable:"applyStyleToLabel",defaultValue:!1,public:!0,forRenderer:!0},e.layer={createComponentOfType:"integer",createStateVariable:"layer",defaultValue:0,public:!0,forRenderer:!0},e}static returnChildGroups(){return[{group:"labels",componentTypes:["label"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnSelectedStyleStateVariableDefinition();Object.assign(e,t);let n=returnLabelStateVariableDefinitions();return Object.assign(e,n),e}}function returnNumericalFunctionFromFormula({formula:e,nInputs:t,variables:n,domain:r,component:a=0}){let i;if(a=Number(a),Array.isArray(e.tree)&&vectorOperators.includes(e.tree[0]))try{e=e.get_component(Number(a))}catch(e){return()=>NaN}else if(0!==a)return()=>NaN;try{i=e.subscripts_to_strings().f()}catch(e){return()=>NaN}if(1===t){let e=n[0].subscripts_to_strings().tree,t=-1/0,a=1/0,s=!1,o=!1;if(null!==r){let e=r[0];if(void 0!==e)try{t=me$3.fromAst(e.tree[1][1]).evaluate_to_constant(),Number.isFinite(t)?s=!e.tree[2][1]:t=-1/0,a=me$3.fromAst(e.tree[1][2]).evaluate_to_constant(),Number.isFinite(a)?o=!e.tree[2][2]:a=1/0}catch(e){}}return function(n,r=!1){if(r){if(isNaN(n))return NaN}else if(!(n>=t)||!(n<=a)||s&&n===t||o&&n===a)return NaN;try{return i({[e]:n})}catch(e){return NaN}}}let s=[];for(let e=0;eme$3.fromAst("_")}else if("0"!==t)return e=>me$3.fromAst("_");let r=e.simplify,a=e.expand,i=n.subscripts_to_strings();if(1===e.nInputs){let t=e.variables[0].subscripts_to_strings().tree;return e=>normalizeMathExpression({value:i.substitute({[t]:e}).strings_to_subscripts(),simplify:r,expand:a})}let s=[];for(let t=0;tNaN;return e}let o=e-1,l={};for(let e=0;e<2;e++){let u,c,p=t[0][e],d=t[o][e],m=n.map((t=>t[e]));i&&(u=s[e]),r&&(c=a[e]),l[e]=function(e){if(isNaN(e))return NaN;if(e<0)return i?(u[2]*e+u[1])*e+u[0]:p;if(e>=o)return r?(e-=o,(c[2]*e+c[1])*e+c[0]):d;let t=Math.floor(e);e-=t;let n=m[t];return((n[3]*e+n[2])*e+n[1])*e+n[0]}}return l}function returnInterpolatedFunction({xs:e,coeffs:t,interpolationPoints:n,domain:r}){let a=[];if(n&&(a=n.map((e=>e.y))),null===e)return e=>NaN;let i=-1/0,s=1/0,o=!1,l=!1;if(null!==r){let e=r[0];if(void 0!==e)try{i=me$3.fromAst(e.tree[1][1]).evaluate_to_constant(),Number.isFinite(i)?o=!e.tree[2][1]:i=-1/0,s=me$3.fromAst(e.tree[1][2]).evaluate_to_constant(),Number.isFinite(s)?l=!e.tree[2][2]:s=1/0}catch(e){}}let u=e[0],c=e[e.length-1];return function(n,r=!1){if(r){if(isNaN(n))return NaN}else if(!(n>=i)||!(n<=s)||o&&n===i||l&&n===s)return NaN;if(n<=u){n-=u;let e=t[0];return((e[3]*n+e[2])*n+e[1])*n+e[0]}if(n>=c){let r=e.length-2;n-=e[r];let a=t[r];return((a[3]*n+a[2])*n+a[1])*n+a[0]}for(var p,d=0,m=e.length-1;d<=m;){p=Math.floor(.5*(d+m));let t=e[p];if(tn))return a[p];m=p-1}}let h=Math.max(0,m);n-=e[h];let f=t[h];return((f[3]*n+f[2])*n+f[1])*n+f[0]}}function returnReturnDerivativesOfInterpolatedFunction({xs:e,coeffs:t,variables:n}){if(!e)return e=>NaN;let r=n[0].subscripts_to_strings().tree,a=e[0],i=e[e.length-1];return function(n){let s=n.map((e=>e.subscripts_to_strings().tree)),o=s.length;return o>3||!s.every((e=>e===r))||s.includes("_")?e=>0:0===o||null===e?e=>NaN:function(n){if(isNaN(n))return NaN;if(n<=a){n-=a;let e=t[0];return 1===o?(3*e[3]*n+2*e[2])*n+e[1]:2===o?6*e[3]*n+2*e[2]:6*e[3]}if(n>=i){let r=e.length-2;n-=e[r];let a=t[r];return 1===o?(3*a[3]*n+2*a[2])*n+a[1]:2===o?6*a[3]*n+2*a[2]:6*a[3]}for(var r,s=0,l=e.length-1;s<=l;){r=Math.floor(.5*(s+l));let a=e[r];if(an))return 1===o?t[r][1]:2===o?2*t[r][2]:6*t[r][3];l=r-1}}let u=Math.max(0,l);n-=e[u];let c=t[u];return 1===o?(3*c[3]*n+2*c[2])*n+c[1]:2===o?6*c[3]*n+2*c[2]:6*c[3]}}}var functionOperatorDefinitions={clampFunction:function(e,t){return function(n){return Number.isFinite(n)?Math.max(e,Math.min(t,n)):NaN}},wrapFunctionPeriodic:function(e,t){return function(n){if(!Number.isFinite(n))return NaN;let r=e,a=t;return r===a?r:(r>a&&([a,r]=[r,a]),r+me$3.math.mod(n-r,a-r))}},derivative:function(e,t){if("interpolatedFunction"===e.derivativeType){let n=returnReturnDerivativesOfInterpolatedFunction({xs:e.xs,coeffs:e.coeffs,variables:e.variables.map(convertValueToMathExpression)}),r=t.map(convertValueToMathExpression);if(e.additionalDerivVariables){r=[...e.additionalDerivVariables.map(convertValueToMathExpression),...r]}if(e.variableMappings)for(let t of e.variableMappings){let e=[];for(let n of r){let r=t[n.subscripts_to_strings().tree];r?e.push(convertValueToMathExpression(r)):e.push(me$3.fromAst("_"))}r=e}return n(r)}return e=>NaN}};class Function$1 extends InlineComponent{static componentType="function";static rendererType="math";static primaryStateVariableForDefinition="numericalfShadow";static createAttributesObject(){let e=super.createAttributesObject();return e.simplify={createComponentOfType:"text",createStateVariable:"simplifySpecified",defaultValue:"none",toLowerCase:!0,valueTransformations:{true:"full"},validValues:["none","full","numbers","numberspreserveorder"]},e.expand={createComponentOfType:"boolean",createStateVariable:"expandSpecified",defaultValue:!1,public:!0},e.xscale={createComponentOfType:"number",createStateVariable:"xscale",defaultValue:1,public:!0},e.yscale={createComponentOfType:"number",createStateVariable:"yscale",defaultValue:1,public:!0},e.nInputs={createComponentOfType:"integer"},e.nOutputs={createComponentOfType:"integer"},e.domain={createComponentOfType:"_intervalListComponent"},e.labelIsName={createComponentOfType:"boolean",createStateVariable:"labelIsName",defaultValue:!1,public:!0},e.showLabel={createComponentOfType:"boolean",createStateVariable:"showLabel",defaultValue:!0,public:!0,forRenderer:!0},e.applyStyleToLabel={createComponentOfType:"boolean",createStateVariable:"applyStyleToLabel",defaultValue:!1,public:!0,forRenderer:!0},e.labelPosition={createComponentOfType:"text",createStateVariable:"labelPosition",defaultValue:"upperright",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft","top","bottom","left","right"]},e.layer={createComponentOfType:"number",createStateVariable:"layer",defaultValue:0,public:!0,forRenderer:!0},e.minima={createComponentOfType:"extrema"},e.maxima={createComponentOfType:"extrema"},e.extrema={createComponentOfType:"extrema"},e.through={createComponentOfType:"_pointListComponent"},e.throughSlopes={createComponentOfType:"mathList"},e.variables={createComponentOfType:"variables"},e.symbolic={createComponentOfType:"boolean"},e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer"},e.displaySmallAsZero={createComponentOfType:"number",valueForTrue:1e-14,valueForFalse:0},e.padZeros={createComponentOfType:"boolean"},e.nearestPointAsCurve={createComponentOfType:"boolean",createStateVariable:"nearestPointAsCurve",defaultValue:!1},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e,componentInfoObjects:t}){let n=e.map((e=>t.componentIsSpecifiedType(e,"label"))),r=[],a=[],i=[];if(0===n.filter((e=>e)).length)r=e;else{if(n[0]){let t=n.indexOf(!1);-1!==t&&(a=e.slice(0,t),e=e.slice(t),n=n.slice(t))}let t=n.indexOf(!0);-1===t?r=e:(r=e.slice(0,t),i=e.slice(t))}return 1===r.length&&"string"!=typeof r[0]||0===r.length?{success:!1}:{success:!0,newChildren:[...a,{componentType:"math",children:r},...i]}}}),e}static returnChildGroups(){return[{group:"maths",componentTypes:["math"]},{group:"functions",componentTypes:["function"]},{group:"labels",componentTypes:["label"]}]}static returnStateVariableDefinitions({numerics:e}){let t=GraphicalComponent.returnStateVariableDefinitions();return t.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){let t=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(t&&(t+=" "),t+=e.selectedStyle.lineStyleWord),t&&(t+=" "),t+=e.selectedStyle.lineColorWord,{setValue:{styleDescription:t}}}},t.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({styleDescription:{dependencyType:"stateVariable",variableName:"styleDescription"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescriptionWithNoun:e.styleDescription+" function"}}}},t.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},defaultValue:10,hasEssential:!0,returnDependencies:()=>({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["displayDigits"]}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.displayDigitsAttr){let n=t.displayDigitsAttr,r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!n&&!r){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth0){let n=t.functionChild[0],r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;return n||r||(n=!0),n?{useEssentialOrDefaultValue:{displayDigits:{defaultValue:e.functionChild[0].stateValues.displayDigits}}}:{setValue:{displayDigits:e.functionChild[0].stateValues.displayDigits}}}return{useEssentialOrDefaultValue:{displayDigits:!0}}}},t.displayDecimals={public:!0,shadowingInstructions:{createComponentOfType:"integer"},defaultValue:null,hasEssential:!0,returnDependencies:()=>({displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["displayDecimals"]}}),definition:({dependencyValues:e,usedDefault:t})=>null!==e.displayDecimalsAttr?{setValue:{displayDecimals:e.displayDecimalsAttr.stateValues.value}}:e.functionChild.length>0&&!t.functionChild[0]?{setValue:{displayDecimals:e.functionChild[0].stateValues.displayDecimals}}:{useEssentialOrDefaultValue:{displayDecimals:!0}}},t.displaySmallAsZero={public:!0,shadowingInstructions:{createComponentOfType:"number"},defaultValue:0,hasEssential:!0,returnDependencies:()=>({displaySmallAsZeroAttr:{dependencyType:"attributeComponent",attributeName:"displaySmallAsZero",variableNames:["value"]},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["displaySmallAsZero"]}}),definition:({dependencyValues:e,usedDefault:t})=>null!==e.displaySmallAsZeroAttr?{setValue:{displaySmallAsZero:e.displaySmallAsZeroAttr.stateValues.value}}:e.functionChild.length>0&&!t.functionChild[0]?{setValue:{displaySmallAsZero:e.functionChild[0].stateValues.displaySmallAsZero}}:{useEssentialOrDefaultValue:{displaySmallAsZero:!0}}},t.padZeros={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},defaultValue:!1,hasEssential:!0,returnDependencies:()=>({padZerosAttr:{dependencyType:"attributeComponent",attributeName:"padZeros",variableNames:["value"]},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["padZeros"]}}),definition:({dependencyValues:e,usedDefault:t})=>null!==e.padZerosAttr?{setValue:{padZeros:e.padZerosAttr.stateValues.value}}:e.functionChild.length>0&&!t.functionChild[0]?{setValue:{padZeros:e.functionChild[0].stateValues.padZeros}}:{useEssentialOrDefaultValue:{padZeros:!0}}},t.isInterpolatedFunction={returnDependencies:()=>({through:{dependencyType:"attributeComponent",attributeName:"through"},minima:{dependencyType:"attributeComponent",attributeName:"minima"},maxima:{dependencyType:"attributeComponent",attributeName:"maxima"},extrema:{dependencyType:"attributeComponent",attributeName:"extrema"}}),definition:({dependencyValues:e})=>({setValue:{isInterpolatedFunction:e.through||e.minima||e.maxima||e.extrema}})},t.nInputs={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({nInputsAttr:{dependencyType:"attributeComponent",attributeName:"nInputs",variableNames:["value"]},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["nInputs"]},variablesAttr:{dependencyType:"attributeComponent",attributeName:"variables",variableNames:["nComponents"]},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"}}),definition({dependencyValues:e}){if(e.isInterpolatedFunction)return{setValue:{nInputs:1}};if(null!==e.nInputsAttr){let t=e.nInputsAttr.stateValues.value;return t>=0||(t=1),{setValue:{nInputs:t}}}return null!==e.variablesAttr?{setValue:{nInputs:Math.max(1,e.variablesAttr.stateValues.nComponents)}}:e.functionChild.length>0?{setValue:{nInputs:e.functionChild[0].stateValues.nInputs}}:{setValue:{nInputs:1}}}},t.nOutputs={defaultValue:1,hasEssential:!0,public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({nOutputsAttr:{dependencyType:"attributeComponent",attributeName:"nOutputs",variableNames:["value"]},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["nOutputs"]},mathChild:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]}}),definition({dependencyValues:e}){if(e.functionChild.length>0)return{setValue:{nOutputs:e.functionChild[0].stateValues.nOutputs}};if(null!==e.nOutputsAttr){let t=e.nOutputsAttr.stateValues.value;return t>=0||(t=1),{setValue:{nOutputs:t}}}if(e.mathChild.length>0){let t=e.mathChild[0].stateValues.value,n=1;return Array.isArray(t.tree)&&vectorOperators.includes(t.tree[0])&&(n=t.tree.length-1),{setValue:{nOutputs:n}}}return{useEssentialOrDefaultValue:{nOutputs:!0}}}},t.domain={returnDependencies:()=>({domainAttr:{dependencyType:"attributeComponent",attributeName:"domain",variableNames:["intervals"]},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["domain"]},nInputs:{dependencyType:"stateVariable",variableName:"nInputs"}}),definition({dependencyValues:e}){if(null!==e.domainAttr){let t=e.nInputs,n=e.domainAttr.stateValues.intervals.slice(0,t);return n.length!==t?{setValue:{domain:null}}:n.every((e=>Array.isArray(e.tree)&&"interval"===e.tree[0]))?{setValue:{domain:n}}:{setValue:{domain:null}}}return e.functionChild.length>0?{setValue:{domain:e.functionChild[0].stateValues.domain}}:{setValue:{domain:null}}}},t.simplify={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({simplifySpecified:{dependencyType:"stateVariable",variableName:"simplifySpecified"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["simplify"]}}),definition:({dependencyValues:e,usedDefault:t})=>t.simplifySpecified&&e.functionChild.length>0?{setValue:{simplify:e.functionChild[0].stateValues.simplify}}:{setValue:{simplify:e.simplifySpecified}},inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t,usedDefault:n})=>n.simplifySpecified&&t.functionChild.length>0?{success:!0,instructions:[{setDependency:"functionChild",desiredValue:e.simplify,childIndex:0,variableIndex:0}]}:{success:!0,instructions:[{setDependency:"simplifySpecified",desiredValue:e.simplify}]}},t.expand={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({expandSpecified:{dependencyType:"stateVariable",variableName:"expandSpecified"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["expand"]}}),definition:({dependencyValues:e,usedDefault:t})=>t.expandSpecified&&e.functionChild.length>0?{setValue:{expand:e.functionChild[0].stateValues.expand}}:{setValue:{expand:e.expandSpecified}},inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t,usedDefault:n})=>n.expandSpecified&&t.functionChild.length>0?{success:!0,instructions:[{setDependency:"functionChild",desiredValue:e.expand,childIndex:0,variableIndex:0}]}:{success:!0,instructions:[{setDependency:"expandSpecified",desiredValue:e.expand}]}},t.numericalfShadow={defaultValue:null,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{numericalfShadow:!0}})},t.symbolicfShadow={defaultValue:null,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{symbolicfShadow:!0}})},t.symbolic={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},defaultValue:!1,hasEssential:!0,returnDependencies:()=>({symbolicAttr:{dependencyType:"attributeComponent",attributeName:"symbolic",variableNames:["value"]},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["symbolic"]},numericalfShadow:{dependencyType:"stateVariable",variableName:"numericalfShadow"},symbolicfShadow:{dependencyType:"stateVariable",variableName:"symbolicfShadow"}}),definition:({dependencyValues:e})=>null!==e.symbolicAttr?{setValue:{symbolic:e.symbolicAttr.stateValues.value}}:e.functionChild.length>0?{setValue:{symbolic:e.functionChild[0].stateValues.symbolic}}:e.numericalfShadow?{setValue:{symbolic:!1}}:e.symbolicfShadow?{setValue:{symbolic:!0}}:{useEssentialOrDefaultValue:{symbolic:!0}}},t.variables={isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"variable"},entryPrefixes:["variable"],returnArraySizeDependencies:()=>({nInputs:{dependencyType:"stateVariable",variableName:"nInputs"}}),returnArraySize:({dependencyValues:e})=>[e.nInputs],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["variable"+(Number(n)+1)]}};return{globalDependencies:{variablesAttr:{dependencyType:"attributeComponent",attributeName:"variables",variableNames:["variables"]},parentVariableForChild:{dependencyType:"parentStateVariable",variableName:"variableForChild"},functionChild:{dependencyType:"child",childGroups:["functions"]}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arraySize:n,arrayKeys:r,usedDefault:a}){if(null!==e.variablesAttr){let t=e.variablesAttr.stateValues.variables;return{setValue:{variables:returnNVariables(n[0],t)}}}if(e.functionChild.length>0){let e={};for(let n of r)e[n]=t[n].functionChild[0].stateValues["variable"+(Number(n)+1)];return{setValue:{variables:e}}}return e.parentVariableForChild&&!a.parentVariableForChild?{setValue:{variables:Array(n[0]).fill(e.parentVariableForChild)}}:{setValue:{variables:returnNVariables(n[0],[])}}}},t.variable={isAlias:!0,targetVariableName:"variable1"},t.unnormalizedFormula={defaultValue:me$3.fromAst(0),hasEssential:!0,returnDependencies:()=>({mathChild:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["formula"]},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"}}),definition:function({dependencyValues:e,usedDefault:t}){return e.isInterpolatedFunction?{setValue:{unnormalizedFormula:me$3.fromAst("_")}}:e.mathChild.length>0?{setValue:{unnormalizedFormula:e.mathChild[0].stateValues.value}}:e.functionChild.length>0&&!t.functionChild[0].formula?{setValue:{unnormalizedFormula:e.functionChild[0].stateValues.formula}}:{useEssentialOrDefaultValue:{unnormalizedFormula:!0}}}},t.formula={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},defaultValue:me$3.fromAst(0),hasEssential:!0,returnDependencies:()=>({unnormalizedFormula:{dependencyType:"stateVariable",variableName:"unnormalizedFormula"},simplify:{dependencyType:"stateVariable",variableName:"simplify"},expand:{dependencyType:"stateVariable",variableName:"expand"}}),definition:function({dependencyValues:e,usedDefault:t}){if(t.unnormalizedFormula)return{useEssentialOrDefaultValue:{formula:!0}};return{setValue:{formula:normalizeMathExpression({value:e.unnormalizedFormula,simplify:e.simplify,expand:e.expand})}}}},t.nPrescribedPoints={returnDependencies:()=>({through:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["nPoints"]}}),definition({dependencyValues:e}){let t=0;return null!==e.through&&(t=e.through.stateValues.nPoints),{setValue:{nPrescribedPoints:t}}}},t.prescribedPoints={isArray:!0,entryPrefixes:["prescribedPoint"],returnArraySizeDependencies:()=>({nPrescribedPoints:{dependencyType:"stateVariable",variableName:"nPrescribedPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nPrescribedPoints],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={through:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["point"+e]},throughSlopes:{dependencyType:"attributeComponent",attributeName:"throughSlopes",variableNames:["math"+e]}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].through;if(null!==t){let a=Number(r)+1,i=t.stateValues["point"+a],s=null,o=e[r].throughSlopes;null!==o&&(s=o.stateValues["math"+a],void 0===s&&(s=null)),n[r]={x:i[0],y:i[1],slope:s}}}return{setValue:{prescribedPoints:n}}}},t.prescribedMinima={returnDependencies:()=>({minima:{dependencyType:"attributeComponent",attributeName:"minima",variableNames:["extrema"]}}),definition({dependencyValues:e}){let t=[];return null!==e.minima&&(t=e.minima.stateValues.extrema.map((e=>({x:e[0],y:e[1]})))),{setValue:{prescribedMinima:t}}}},t.prescribedMaxima={returnDependencies:()=>({maxima:{dependencyType:"attributeComponent",attributeName:"maxima",variableNames:["extrema"]}}),definition({dependencyValues:e}){let t=[];return null!==e.maxima&&(t=e.maxima.stateValues.extrema.map((e=>({x:e[0],y:e[1]})))),{setValue:{prescribedMaxima:t}}}},t.prescribedExtrema={returnDependencies:()=>({extrema:{dependencyType:"attributeComponent",attributeName:"extrema",variableNames:["extrema"]}}),definition({dependencyValues:e}){let t=[];return null!==e.extrema&&(t=e.extrema.stateValues.extrema.map((e=>({x:e[0],y:e[1]})))),{setValue:{prescribedExtrema:t}}}},t.interpolationPoints={returnDependencies:()=>({xscale:{dependencyType:"stateVariable",variableName:"xscale"},yscale:{dependencyType:"stateVariable",variableName:"yscale"},prescribedPoints:{dependencyType:"stateVariable",variableName:"prescribedPoints"},prescribedMinima:{dependencyType:"stateVariable",variableName:"prescribedMinima"},prescribedMaxima:{dependencyType:"stateVariable",variableName:"prescribedMaxima"},prescribedExtrema:{dependencyType:"stateVariable",variableName:"prescribedExtrema"}}),definition:({dependencyValues:t})=>calculateInterpolationPoints({dependencyValues:t,numerics:e})},t.xs={additionalStateVariablesDefined:["coeffs"],returnDependencies:()=>({interpolationPoints:{dependencyType:"stateVariable",variableName:"interpolationPoints"}}),definition:computeSplineParamCoeffs},t.symbolicfs={isArray:!0,entryPrefixes:["symbolicf"],stateVariablesDeterminingDependencies:["isInterpolatedFunction"],returnArraySizeDependencies:()=>({nOutputs:{dependencyType:"stateVariable",variableName:"nOutputs"}}),returnArraySize:({dependencyValues:e})=>[e.nOutputs],returnArrayDependenciesByKey:({stateValues:e})=>e.isInterpolatedFunction?{globalDependencies:{xs:{dependencyType:"stateVariable",variableName:"xs"},coeffs:{dependencyType:"stateVariable",variableName:"coeffs"},interpolationPoints:{dependencyType:"stateVariable",variableName:"interpolationPoints"},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},domain:{dependencyType:"stateVariable",variableName:"domain"}}}:{globalDependencies:{formula:{dependencyType:"stateVariable",variableName:"formula"},variables:{dependencyType:"stateVariable",variableName:"variables"},nInputs:{dependencyType:"stateVariable",variableName:"nInputs"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["symbolicfs"]},simplify:{dependencyType:"stateVariable",variableName:"simplify"},expand:{dependencyType:"stateVariable",variableName:"expand"},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},symbolicfShadow:{dependencyType:"stateVariable",variableName:"symbolicfShadow"},numericalfShadow:{dependencyType:"stateVariable",variableName:"numericalfShadow"},domain:{dependencyType:"stateVariable",variableName:"domain"}}},arrayDefinitionByKey:function({globalDependencyValues:e,usedDefault:t,arrayKeys:n}){if(e.isInterpolatedFunction){let t={};for(let r of n)if("0"===r){let n=returnInterpolatedFunction({xs:e.xs,coeffs:e.coeffs,interpolationPoints:e.interpolationPoints,domain:e.domain});t[r]=function(e){me$3.fromAst(n(e.evaluate_to_constant()))}}else t[r]=e=>me$3.fromAst("_");return{setValue:{symbolicfs:t}}}if(t.formula||"_"===e.formula.tree&&0!==e.functionChild.length){if(e.functionChild.length>0){let t={};for(let r of n)t[r]=e.functionChild[0].stateValues.symbolicfs[r];return{setValue:{symbolicfs:t}}}if(e.symbolicfShadow){let t={};for(let r of n)t[r]="0"===r?e.symbolicfShadow:e=>me$3.fromAst("_");return{setValue:{symbolicfs:t}}}if(e.numericalfShadow){let t={};for(let r of n)t[r]="0"===r?function(t){let n=t.evaluate_to_constant();return null===n?NaN:me$3.fromAst(e.numericalfShadow(n))}:e=>me$3.fromAst("_");return{setValue:{symbolicfs:t}}}{let t={};for(let r of n)t[r]=returnSymbolicFunctionFromFormula(e,r);return{setValue:{symbolicfs:t}}}}{let t={};for(let r of n)t[r]=returnSymbolicFunctionFromFormula(e,r);return{setValue:{symbolicfs:t}}}}},t.symbolicf={isAlias:!0,targetVariableName:"symbolicf1"},t.numericalfs={isArray:!0,entryPrefixes:["numericalf"],stateVariablesDeterminingDependencies:["isInterpolatedFunction"],returnArraySizeDependencies:()=>({nOutputs:{dependencyType:"stateVariable",variableName:"nOutputs"}}),returnArraySize:({dependencyValues:e})=>[e.nOutputs],returnArrayDependenciesByKey:({stateValues:e})=>e.isInterpolatedFunction?{globalDependencies:{xs:{dependencyType:"stateVariable",variableName:"xs"},coeffs:{dependencyType:"stateVariable",variableName:"coeffs"},interpolationPoints:{dependencyType:"stateVariable",variableName:"interpolationPoints"},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},domain:{dependencyType:"stateVariable",variableName:"domain"}}}:{globalDependencies:{formula:{dependencyType:"stateVariable",variableName:"formula"},variables:{dependencyType:"stateVariable",variableName:"variables"},nInputs:{dependencyType:"stateVariable",variableName:"nInputs"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["numericalfs"]},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},symbolicfShadow:{dependencyType:"stateVariable",variableName:"symbolicfShadow"},numericalfShadow:{dependencyType:"stateVariable",variableName:"numericalfShadow"},domain:{dependencyType:"stateVariable",variableName:"domain"}}},arrayDefinitionByKey:function({globalDependencyValues:e,usedDefault:t,arrayKeys:n}){if(e.isInterpolatedFunction){let t={};for(let r of n)t[r]="0"===r?returnInterpolatedFunction({xs:e.xs,coeffs:e.coeffs,interpolationPoints:e.interpolationPoints,domain:e.domain}):e=>me$3.fromAst("_");return{setValue:{numericalfs:t}}}if(t.formula||"_"===e.formula.tree&&0!==e.functionChild.length){if(e.functionChild.length>0){let t={};for(let r of n)t[r]=e.functionChild[0].stateValues.numericalfs[r];return{setValue:{numericalfs:t}}}if(e.numericalfShadow){let t={};for(let r of n)t[r]="0"===r?e.numericalfShadow:()=>NaN;return{setValue:{numericalfs:t}}}if(e.symbolicfShadow){let e={};for(let t of n)e[t]="0"===t?function(e){let t=dependencyValues.symbolicfShadow(me$3.fromAst(e)).evaluate_to_constant();return null===t&&(t=NaN),t}:()=>NaN;return{setValue:{numericalfs:e}}}{let t={};for(let r of n)t[r]=returnNumericalFunctionFromFormula({formula:e.formula,nInputs:e.nInputs,variables:e.variables,domain:e.domain,component:r});return{setValue:{numericalfs:t}}}}{let t={};for(let r of n)t[r]=returnNumericalFunctionFromFormula({formula:e.formula,nInputs:e.nInputs,variables:e.variables,domain:e.domain,component:r});return{setValue:{numericalfs:t}}}}},t.numericalf={returnDependencies:()=>({numericalf1:{dependencyType:"stateVariable",variableName:"numericalf1"}}),definition:({dependencyValues:e})=>({setValue:{numericalf:e.numericalf1}})},t.fDefinition={stateVariablesDeterminingDependencies:["isInterpolatedFunction"],returnDependencies:({stateValues:e})=>e.isInterpolatedFunction?{xs:{dependencyType:"stateVariable",variableName:"xs"},coeffs:{dependencyType:"stateVariable",variableName:"coeffs"},interpolationPoints:{dependencyType:"stateVariable",variableName:"interpolationPoints"},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},domain:{dependencyType:"stateVariable",variableName:"domain"}}:{formula:{dependencyType:"stateVariable",variableName:"formula"},variables:{dependencyType:"stateVariable",variableName:"variables"},nInputs:{dependencyType:"stateVariable",variableName:"nInputs"},nOutputs:{dependencyType:"stateVariable",variableName:"nOutputs"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["fDefinition"]},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},symbolicfShadow:{dependencyType:"stateVariable",variableName:"symbolicfShadow"},numericalfShadow:{dependencyType:"stateVariable",variableName:"numericalfShadow"},domain:{dependencyType:"stateVariable",variableName:"domain"}},definition:({dependencyValues:e,usedDefault:t})=>e.isInterpolatedFunction?{setValue:{fDefinition:{functionType:"interpolated",xs:e.xs,coeffs:e.coeffs,interpolationPoints:e.interpolationPoints,domain:e.domain}}}:t.formula||"_"===e.formula.tree&&0!==e.functionChild.length?e.functionChild.length>0?{setValue:{fDefinition:e.functionChild[0].stateValues.fDefinition}}:e.numericalfShadow||e.symbolicfShadow?{setValue:{fDefinition:{}}}:{setValue:{fDefinition:{functionType:"formula",formula:e.formula.tree,variables:e.variables.map((e=>e.tree)),nInputs:e.nInputs,nOutputs:e.nOutputs,domain:e.domain}}}:{setValue:{fDefinition:{functionType:"formula",formula:e.formula.tree,variables:e.variables.map((e=>e.tree)),nInputs:e.nInputs,nOutputs:e.nOutputs,domain:e.domain}}}},t.fs={isArray:!0,entryPrefixes:["f"],returnArraySizeDependencies:()=>({nOutputs:{dependencyType:"stateVariable",variableName:"nOutputs"}}),returnArraySize:({dependencyValues:e})=>[e.nOutputs],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={symbolicf:{dependencyType:"stateVariable",variableName:"symbolicf"+e},numericalf:{dependencyType:"stateVariable",variableName:"numericalf"+e}}}return{globalDependencies:{symbolic:{dependencyType:"stateVariable",variableName:"symbolic"}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};if(e.symbolic)for(let e of n)r[e]=t[e].symbolicf;else for(let e of n)r[e]=t[e].numericalf;return{setValue:{fs:r}}}},t.f={isAlias:!0,targetVariableName:"f1"},t.latex={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({formula:{dependencyType:"stateVariable",variableName:"formula"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"}}),definition:function({dependencyValues:e,usedDefault:t}){let n={};return e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(n.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(n.padToDigits=e.displayDigits)),{setValue:{latex:roundForDisplay({value:e.formula,dependencyValues:e,usedDefault:t}).toLatex(n)}}}},t.latexWithInputChildren={forRenderer:!0,returnDependencies:()=>({latex:{dependencyType:"stateVariable",variableName:"latex"}}),definition:function({dependencyValues:e}){return{setValue:{latexWithInputChildren:[e.latex]}}}},t.allMinima={stateVariablesDeterminingDependencies:["isInterpolatedFunction"],returnDependencies:({stateValues:e})=>e.isInterpolatedFunction?{xs:{dependencyType:"stateVariable",variableName:"xs"},coeffs:{dependencyType:"stateVariable",variableName:"coeffs"},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},domain:{dependencyType:"stateVariable",variableName:"domain"}}:{numericalf:{dependencyType:"stateVariable",variableName:"numericalf"},formula:{dependencyType:"stateVariable",variableName:"formula"},variables:{dependencyType:"stateVariable",variableName:"variables"},xscale:{dependencyType:"stateVariable",variableName:"xscale"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["allMinima"]},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},nInputs:{dependencyType:"stateVariable",variableName:"nInputs"},nOutputs:{dependencyType:"stateVariable",variableName:"nOutputs"},domain:{dependencyType:"stateVariable",variableName:"domain"}},definition:function({dependencyValues:t}){if(t.isInterpolatedFunction){let n=t.xs,r=t.coeffs,a=e.eps,i=[];if(null===n)return{setValue:{allMinima:i}};let s=!1,o=-1/0,l=1/0,u=!1,c=!1;if(null!==t.domain){let e=t.domain[0];if(void 0!==e)try{o=me$3.fromAst(e.tree[1][1]).evaluate_to_constant(),Number.isFinite(o)?u=!e.tree[2][1]:o=-1/0,l=me$3.fromAst(e.tree[1][2]).evaluate_to_constant(),Number.isFinite(l)?c=!e.tree[2][2]:l=1/0}catch(e){}}let p=1e-14*Math.max(Math.abs(o),Math.abs(l)),d=r[0],m=n[1]-n[0];if(0===d[3]){if(d[2]>0){let e=-d[1]/(2*d[2]);e+n[0]>=o-p&&e+n[0]<=l+p&&(e<=m-a?u&&Math.abs(e+n[0]-o)0){let t=Math.sqrt(e),r=(-2*d[2]+t)/(6*d[3]);r+n[0]>=o-p&&r+n[0]<=l+p&&(r<=m-a?u&&Math.abs(r+n[0]-o)0){let t=-d[1]/(2*d[2]);if(t+n[e]>=o-p){if(!(t+n[e]<=l+p)){s=!1;continue}Math.abs(t)=a&&t<=m-a&&(u&&Math.abs(t+n[e]-o)0){let r=Math.sqrt(t),h=(-2*d[2]+r)/(6*d[3]);if(h+n[e]>=o-p){if(!(h+n[e]<=l+p)){s=!1;continue}Math.abs(h)=a&&h<=m-a&&(u&&Math.abs(h+n[e]-o)0){let e=-d[1]/(2*d[2]);e+n[n.length-2]>=o-p&&e+n[n.length-2]<=l+p&&(Math.abs(e)=a&&(u&&Math.abs(e+n[n.length-2]-o)0){let t=Math.sqrt(e),r=(-2*d[2]+t)/(6*d[3]);r+n[n.length-2]>=o-p&&r+n[n.length-2]<=l+p&&(r>=a||Math.abs(r)0)return{setValue:{allMinima:t.functionChild[0].stateValues.allMinima}};if(1!==t.nInputs||1!==t.nOutputs)return{setValue:{allMinima:[]}};let n,r,a=t.variables[0].subscripts_to_strings().tree,i=t.formula.subscripts_to_strings().derivative(a),s=!0;try{n=i.subscripts_to_strings().f()}catch(e){s=!1,r=()=>NaN}s&&(r=function(e){try{return n({[a]:e})}catch(e){return NaN}});let o=e=>t.numericalf(e,!0),l=-100*t.xscale,u=100*t.xscale,c=!1,p=!1;if(null!==t.domain){let e=t.domain[0];if(void 0!==e)try{l=me$3.fromAst(e.tree[1][1]).evaluate_to_constant(),Number.isFinite(l)?c=!e.tree[2][1]:l=-100*t.xscale,u=me$3.fromAst(e.tree[1][2]).evaluate_to_constant(),Number.isFinite(u)?p=!e.tree[2][2]:u=100*t.xscale}catch(e){}}let d=1e3,m=(u-l)/d,h=1e-10*Math.max(Math.abs(l),Math.abs(u)),f=[],y=!1,g=!1,b=o(l-m),v=r(l-m);for(let t=-1;t0&&(N=!0,y=!1,!(t>=l-h&&t<=u+h)||c&&Math.abs(t-l)({allMinima:{dependencyType:"stateVariable",variableName:"allMinima"}}),definition:({dependencyValues:e})=>({setValue:{numberMinima:e.allMinima.length},checkForActualChange:{numberMinima:!0}})},t.minima={stateVariablesDeterminingDependencies:["isInterpolatedFunction"],public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"],returnWrappingComponents:e=>"minimum"===e||void 0===e?[["point",{componentType:"mathList",isAttribute:"xs"}]]:[]},isArray:!0,nDimensions:2,entryPrefixes:["minimum","minimumLocations","minimumLocation","minimumValues","minimumValue"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if(["minimum","minimumLocation","minimumValue"].includes(e)){let r=Number(t)-1;return Number.isInteger(r)&&r>=0&&(!n||rt+",0")):["0,0"]:"minimumValues"===e?""!==t?[]:n?Array.from(Array(n[0]),((e,t)=>t+",1")):["0,1"]:[]},arrayVarNameFromArrayKey(e){let[t,n]=e.split(",");return"0"===n?"minimumLocation"+(Number(t)+1):"minimumValue"+(Number(t)+1)},arrayVarNameFromPropIndex(e,t){if("minima"===t){if(1===e.length)return"minimum"+e[0];{let t=Number(e[0]);if(Number.isInteger(t)&&t>0){if(1===e[1])return"minimumLocation"+t;if(2===e[1])return"minimumValue"+t}return null}}if("minimumLocations"===t)return"minimumLocation"+e[0];if("minimumValues"===t)return"minimumValue"+e[0];if("minimum"===t.slice(0,7)){let n=Number(t.slice(7));if(Number.isInteger(n)&&n>0){if(1===e[0])return"minimumLocation"+n;if(2===e[0])return"minimumValue"+n}}return null},returnArraySizeDependencies:()=>({numberMinima:{dependencyType:"stateVariable",variableName:"numberMinima"}}),returnArraySize:({dependencyValues:e})=>[e.numberMinima,2],returnArrayDependenciesByKey:()=>({globalDependencies:{allMinima:{dependencyType:"stateVariable",variableName:"allMinima"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n=0;ne.isInterpolatedFunction?{xs:{dependencyType:"stateVariable",variableName:"xs"},coeffs:{dependencyType:"stateVariable",variableName:"coeffs"},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},domain:{dependencyType:"stateVariable",variableName:"domain"}}:{numericalf:{dependencyType:"stateVariable",variableName:"numericalf"},formula:{dependencyType:"stateVariable",variableName:"formula"},variables:{dependencyType:"stateVariable",variableName:"variables"},xscale:{dependencyType:"stateVariable",variableName:"xscale"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["allMaxima"]},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},nInputs:{dependencyType:"stateVariable",variableName:"nInputs"},nOutputs:{dependencyType:"stateVariable",variableName:"nOutputs"},domain:{dependencyType:"stateVariable",variableName:"domain"}},definition:function({dependencyValues:t}){if(t.isInterpolatedFunction){let n=t.xs,r=t.coeffs,a=e.eps,i=[];if(null===n)return{setValue:{allMaxima:i}};let s=!1,o=-1/0,l=1/0,u=!1,c=!1;if(null!==t.domain){let e=t.domain[0];if(void 0!==e)try{o=me$3.fromAst(e.tree[1][1]).evaluate_to_constant(),Number.isFinite(o)?u=!e.tree[2][1]:o=-1/0,l=me$3.fromAst(e.tree[1][2]).evaluate_to_constant(),Number.isFinite(l)?c=!e.tree[2][2]:l=1/0}catch(e){}}let p=1e-14*Math.max(Math.abs(o),Math.abs(l)),d=r[0],m=n[1]-n[0];if(0===d[3]){if(d[2]<0){let e=-d[1]/(2*d[2]);e+n[0]>=o-p&&e+n[0]<=l+p&&(e<=m-a?u&&Math.abs(e+n[0]-o)0){let t=Math.sqrt(e),r=(-2*d[2]-t)/(6*d[3]);r+n[0]>=o-p&&r+n[0]<=l+p&&(r<=m-a?u&&Math.abs(r+n[0]-o)=o-p){if(!(t+n[e]<=l+p)){s=!1;continue}Math.abs(t)=a&&t<=m-a&&(u&&Math.abs(t+n[e]-o)0){let r=Math.sqrt(t),h=(-2*d[2]-r)/(6*d[3]);if(h+n[e]>=o-p){if(!(h+n[e]<=l+p)){s=!1;continue}Math.abs(h)=a&&h<=m-a&&(u&&Math.abs(h+n[e]-o)=o-p&&e+n[n.length-2]<=l+p&&(Math.abs(e)=a&&(u&&Math.abs(e+n[n.length-2]-o)0){let t=Math.sqrt(e),r=(-2*d[2]-t)/(6*d[3]);r+n[n.length-2]>=o-p&&r+n[n.length-2]<=l+p&&(r>=a||Math.abs(r)0)return{setValue:{allMaxima:t.functionChild[0].stateValues.allMaxima}};if(1!==t.nInputs||1!==t.nOutputs)return{setValue:{allMaxima:[]}};let n,r,a=t.variables[0].subscripts_to_strings().tree,i=t.formula.subscripts_to_strings().derivative(a),s=!0;try{n=i.subscripts_to_strings().f()}catch(e){s=!1,r=()=>NaN}s&&(r=function(e){try{return n({[a]:e})}catch(e){return NaN}});let o=e=>-t.numericalf(e,!0),l=-100*t.xscale,u=100*t.xscale,c=!1,p=!1;if(null!==t.domain){let e=t.domain[0];if(void 0!==e)try{l=me$3.fromAst(e.tree[1][1]).evaluate_to_constant(),Number.isFinite(l)?c=!e.tree[2][1]:l=-100*t.xscale,u=me$3.fromAst(e.tree[1][2]).evaluate_to_constant(),Number.isFinite(u)?p=!e.tree[2][2]:u=100*t.xscale}catch(e){}}let d=1e3,m=(u-l)/d,h=1e-10*Math.max(Math.abs(l),Math.abs(u)),f=[],y=!1,g=!1,b=o(l-m),v=r(l-m);for(let t=-1;t0&&r(t+i)<0&&(N=!0,y=!1,!(t>=l-h&&t<=u+h)||c&&Math.abs(t-l)({allMaxima:{dependencyType:"stateVariable",variableName:"allMaxima"}}),definition:({dependencyValues:e})=>({setValue:{numberMaxima:e.allMaxima.length},checkForActualChange:{numberMaxima:!0}})},t.maxima={stateVariablesDeterminingDependencies:["isInterpolatedFunction"],public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"],returnWrappingComponents:e=>"maximum"===e||void 0===e?[["point",{componentType:"mathList",isAttribute:"xs"}]]:[]},isArray:!0,nDimensions:2,entryPrefixes:["maximum","maximumLocations","maximumLocation","maximumValues","maximumValue"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if(["maximum","maximumLocation","maximumValue"].includes(e)){let r=Number(t)-1;return Number.isInteger(r)&&r>=0&&(!n||rt+",0")):["0,0"]:"maximumValues"===e?""!==t?[]:n?Array.from(Array(n[0]),((e,t)=>t+",1")):["0,1"]:[]},arrayVarNameFromArrayKey(e){let[t,n]=e.split(",");return"0"===n?"maximumLocation"+(Number(t)+1):"maximumValue"+(Number(t)+1)},arrayVarNameFromPropIndex(e,t){if("maxima"===t){if(1===e.length)return"maximum"+e[0];{let t=Number(e[0]);if(Number.isInteger(t)&&t>0){if(1===e[1])return"maximumLocation"+t;if(2===e[1])return"maximumValue"+t}return null}}if("maximumLocations"===t)return"maximumLocation"+e[0];if("maximumValues"===t)return"maximumValue"+e[0];if("maximum"===t.slice(0,7)){let n=Number(t.slice(7));if(Number.isInteger(n)&&n>0){if(1===e[0])return"maximumLocation"+n;if(2===e[0])return"maximumValue"+n}}return null},returnArraySizeDependencies:()=>({numberMaxima:{dependencyType:"stateVariable",variableName:"numberMaxima"}}),returnArraySize:({dependencyValues:e})=>[e.numberMaxima,2],returnArrayDependenciesByKey:()=>({globalDependencies:{allMaxima:{dependencyType:"stateVariable",variableName:"allMaxima"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n=0;n({numberMinima:{dependencyType:"stateVariable",variableName:"numberMinima"},numberMaxima:{dependencyType:"stateVariable",variableName:"numberMaxima"}}),definition:function({dependencyValues:e}){return{setValue:{numberExtrema:e.numberMinima+e.numberMaxima},checkForActualChange:{numberExtrema:!0}}}},t.allExtrema={returnDependencies:()=>({allMinima:{dependencyType:"stateVariable",variableName:"allMinima"},allMaxima:{dependencyType:"stateVariable",variableName:"allMaxima"}}),definition({dependencyValues:e}){let t=[...e.allMinima,...e.allMaxima].sort(((e,t)=>e[0]-t[0]));return{setValue:{allExtrema:t}}}},t.extrema={public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"],returnWrappingComponents:e=>"extremum"===e||void 0===e?[["point",{componentType:"mathList",isAttribute:"xs"}]]:[]},isArray:!0,nDimensions:2,entryPrefixes:["extremum","extremumLocations","extremumLocation","extremumValues","extremumValue"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if(["extremum","extremumLocation","extremumValue"].includes(e)){let r=Number(t)-1;return Number.isInteger(r)&&r>=0&&(!n||rt+",0")):["0,0"]:"extremumValues"===e?""!==t?[]:n?Array.from(Array(n[0]),((e,t)=>t+",1")):["0,1"]:[]},arrayVarNameFromArrayKey(e){let[t,n]=e.split(",");return"0"===n?"extremumLocation"+(Number(t)+1):"extremumValue"+(Number(t)+1)},arrayVarNameFromPropIndex(e,t){if("extrema"===t){if(1===e.length)return"extremum"+e[0];{let t=Number(e[0]);if(Number.isInteger(t)&&t>0){if(1===e[1])return"extremumLocation"+t;if(2===e[1])return"extremumValue"+t}return null}}if("extremumLocations"===t)return"extremumLocation"+e[0];if("extremumValues"===t)return"extremumValue"+e[0];if("extremum"===t.slice(0,8)){let n=Number(t.slice(8));if(Number.isInteger(n)&&n>0){if(1===e[0])return"extremumLocation"+n;if(2===e[0])return"extremumValue"+n}}return null},returnArraySizeDependencies:()=>({numberExtrema:{dependencyType:"stateVariable",variableName:"numberExtrema"}}),returnArraySize:({dependencyValues:e})=>[e.numberExtrema,2],returnArrayDependenciesByKey:()=>({globalDependencies:{allExtrema:{dependencyType:"stateVariable",variableName:"allExtrema"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n=0;ne.isInterpolatedFunction?{xs:{dependencyType:"stateVariable",variableName:"xs"},coeffs:{dependencyType:"stateVariable",variableName:"coeffs"},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},variables:{dependencyType:"stateVariable",variableName:"variables"}}:{functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["returnNumericalDerivatives","variables"]},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},variables:{dependencyType:"stateVariable",variableName:"variables"}},definition:function({dependencyValues:e}){if(e.isInterpolatedFunction)return{setValue:{returnNumericalDerivatives:returnReturnDerivativesOfInterpolatedFunction(e)}};if(e.functionChild.length>0&&e.functionChild[0].stateValues.returnNumericalDerivatives){let t=e.variables.map((e=>e.subscripts_to_strings().tree)),n=e.functionChild[0].stateValues.variables,r=n.map((e=>e.subscripts_to_strings().tree)),a={};for(let[e,i]of t.entries())r[e]&&r[e]!==i&&(a[i]=n[e]);if(0===Object.keys(a).length)return{setValue:{returnNumericalDerivatives:e.functionChild[0].stateValues.returnNumericalDerivatives}};return{setValue:{returnNumericalDerivatives:function(t){let n=[];for(let e of t){let t=a[e.subscripts_to_strings().tree];t?n.push(t):n.push(me$3.fromAst("_"))}return e.functionChild[0].stateValues.returnNumericalDerivatives(n)}}}}return{setValue:{returnNumericalDerivatives:null}}}},t.numericalDerivativesDefinition={stateVariablesDeterminingDependencies:["isInterpolatedFunction"],returnDependencies:({stateValues:e})=>e.isInterpolatedFunction?{xs:{dependencyType:"stateVariable",variableName:"xs"},coeffs:{dependencyType:"stateVariable",variableName:"coeffs"},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},variables:{dependencyType:"stateVariable",variableName:"variables"}}:{functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["numericalDerivativesDefinition","variables"]},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},variables:{dependencyType:"stateVariable",variableName:"variables"}},definition:function({dependencyValues:e}){if(e.isInterpolatedFunction)return{setValue:{numericalDerivativesDefinition:{derivativeType:"interpolatedFunction",xs:e.xs,coeffs:e.coeffs,variables:e.variables}}};if(e.functionChild.length>0&&e.functionChild[0].stateValues.numericalDerivativesDefinition){let t=e.variables.map((e=>e.subscripts_to_strings().tree)),n=e.functionChild[0].stateValues.variables,r=n.map((e=>e.subscripts_to_strings().tree)),a={};for(let[e,i]of t.entries())r[e]&&r[e]!==i&&(a[i]=n[e]);if(0===Object.keys(a).length)return{setValue:{numericalDerivativesDefinition:e.functionChild[0].stateValues.numericalDerivativesDefinition}};{let t={...e.functionChild[0].stateValues.numericalDerivativesDefinition};return t.variableMappings?t.variableMappings=[a,...t.variableMappings]:t.variableMappings=[a],{setValue:{numericalDerivativesDefinition:t}}}}return{setValue:{numericalDerivativesDefinition:{}}}}},t}static adapters=[{stateVariable:"numericalf",componentType:"curve",stateVariablesToShadow:["label","labelHasLatex"]},{stateVariable:"formula",componentType:"math",stateVariablesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]}]}function calculateInterpolationPoints({dependencyValues:e,numerics:t}){let n=[],r=[],a={maximum:e.prescribedMaxima,minimum:e.prescribedMinima,extremum:e.prescribedExtrema,point:e.prescribedPoints};for(let e in a)for(let t of a[e]){let a=null,i=null,s=null;if(null===t.x||(a=t.x.evaluate_to_constant(),Number.isFinite(a)))if(null===t.y||(i=t.y.evaluate_to_constant(),Number.isFinite(i)))if(null!==t.slope&&void 0!==t.slope&&(s=t.slope.evaluate_to_constant(),Number.isFinite(s)||(console.warn("Ignoring non-numerical slope"),s=null)),null===a){if(null===i){console.warn(`Ignoring empty ${e}`);continue}r.push({type:e,y:i,slope:s})}else n.push({type:e,x:a,y:i,slope:s});else console.warn(`Ignoring non-numerical ${e}`);else console.warn(`Ignoring non-numerical ${e}`)}n.sort(((e,t)=>e.x-t.x)),r.sort(((e,t)=>e.y-t.y));let i=-1/0,s=t.eps;for(let e=0;e0;){let e,t;void 0===l?e=v({allowedTypes:["maximum","minimum","extremum"],comparison:"atLeast",value:-1/0}):"maximum"===l?e=v({allowedTypes:["minimum","extremum"],comparison:"atMost",value:o-c}):"minimum"===l?e=v({allowedTypes:["maximum","extremum"],comparison:"atLeast",value:o+c}):"point"===l&&(e=v({allowedTypes:["maximum","extremum"],comparison:"atLeast",value:o+c}),!0!==e.success&&(e=v({allowedTypes:["minimum","extremum"],comparison:"atMost",value:o-c}))),!0===e.success?(t=e.point,r.splice(e.ind,1),m?(t.x=0,m=!1):t.x=i+u):(t=r.pop(),m?(t.x=0,m=!1):t.x=i+2*u);let n=y({p:t,typePrev:l,xPrev:i,yPrev:o});l=n.type,i=n.x,o=n.y}if(0===p.length&&p.push({type:"point",x:0,y:0,slope:0}),m=p[0],"maximum"===m.type){let e={type:"point",x:m.x-u,y:m.y-c,slope:2*c/u};p.splice(0,0,e)}else if("minimum"===m.type){let e={type:"point",x:m.x-u,y:m.y+c,slope:-2*c/u};p.splice(0,0,e)}else if("point"===m.type)if(1===p.length)null===m.slope&&(m.slope=0);else{let e=p[1],t=(e.y-m.y)/(e.x-m.x);if("maximum"===e.type||"minimum"===e.type)null===m.slope&&(m.slope=2*t);else{2===p.length?null===m.slope&&(m.slope=t):(null===e.slope&&(e.slope=f({point:e,prevPoint:m,nextPoint:p[2]})),null===m.slope&&(m.slope=2*(m.y-e.y)/(m.x-e.x)-e.slope));let n={x:m.x-u,y:m.y-u*m.slope,slope:m.slope};p.splice(0,0,n)}}let h=p[p.length-1];if("maximum"===h.type){let e={type:"point",x:h.x+u,y:h.y-c,slope:-2*c/u};p.push(e)}else if("minimum"===h.type){let e={type:"point",x:h.x+u,y:h.y+c,slope:2*c/u};p.push(e)}else if("point"===h.type)if(1===p.length){let e={type:"point",x:h.x+u,y:h.y+m.slope*u,slope:m.slope};p.push(e)}else{let e=p[p.length-2],t=(e.y-h.y)/(e.x-h.x);if("maximum"===e.type||"minimum"===e.type)null===h.slope&&(h.slope=2*t);else{2===p.length?null===h.slope&&(h.slope=t):(null===e.slope&&(e.slope=f({point:e,prevPoint:p[p.length-3],nextPoint:h})),null===h.slope&&(h.slope=2*(e.y-h.y)/(e.x-h.x)-e.slope));let n={x:h.x+u,y:h.y+u*h.slope,slope:h.slope};p.push(n)}}for(let e=1;ei-c||void 0!==r&&null!==e.y&&e.y>t.y-c?g({x:e.x,y:e.y,typePrev:n,xPrev:a,yPrev:i,yNext:s,pNext:t}):b({x:e.x,y:e.y,typePrev:n,xPrev:a,yPrev:i,yNext:s,pNext:t});if("minimum"===n||"minimum"===r)return null!==e.y&&e.yt.y+c?b({x:e.x,y:e.y,typePrev:n,xPrev:a,yPrev:i,yNext:s,pNext:t}):g({x:e.x,y:e.y,typePrev:n,xPrev:a,yPrev:i,yNext:s,pNext:t});if("point"===n||"point"===r){let o="maximum";return(null===e.y&&void 0!==t&&t.type===maximum||null!==e.y&&e.y<=i-c||void 0!==r&&null!==e.y&&e.y>=t.y-c)&&(o="minimum"),"minimum"===o?b({x:e.x,y:e.y,typePrev:n,xPrev:a,yPrev:i,yNext:s,pNext:t}):g({x:e.x,y:e.y,typePrev:n,xPrev:a,yPrev:i,yNext:s,pNext:t})}return null!==e.y&&e.ys-c){let n,a,o=(e+i)/2,l=null,u=v({allowedTypes:["minimum","extremum"],comparison:"atMost",value:Math.min(s,t)-c});!0===u.success?(a="minimum",n=u.point.y,r.splice(u.ind,1),l=0):(a="point",n=s-c),p.push({type:a,x:o,y:n,slope:l})}}else if("minimum"===a&&ti-c){let n=[(2*a+e)/3,(a+2*e)/3],s=[i-c,t+c],o=["atMost","atLeast"],l=[["minimum","extremum"],["maximum","extremum"]];for(let e=0;e<2;e++){let t,a,i=n[e],u=null,c=v({allowedTypes:l[e],comparison:o[e],value:s[e]});!0===c.success?(a=l[e][0],t=c.point.y,r.splice(c.ind,1),u=0):(a="point",t=s[e],u=null),p.push({type:a,x:i,y:t,slope:u})}}}else if("minimum"===n){null===t&&(t=void 0===s?i:"minimum"===o.type?Math.min(i,s):Math.min(i,s-c));let n,l,u=Math.max(i,t)+c,d=(e+a)/2,m=null,h=v({allowedTypes:["maximum","extremum"],comparison:"atLeast",value:u});!0===h.success?(l="maximum",n=h.point.y,r.splice(h.ind,1),m=0):(l="point",n=u),p.push({type:l,x:d,y:n,slope:m})}else if("point"===n)if(null===t)t=void 0===s?i-c:"minimum"===o.type?Math.min(i-c,s):Math.min(i,s)-c;else if(t>i-c){let n,i,s=(e+a)/2,o=null,l=v({allowedTypes:["maximum","extremum"],comparison:"atLeast",value:t+c});!0===l.success?(i="maximum",n=l.point.y,r.splice(l.ind,1),o=0):(i="point",n=t+c),p.push({type:i,x:s,y:n,slope:o})}let l={type:"minimum",x:e,y:t,slope:0};return p.push(l),l}function v({allowedTypes:e,comparison:t,value:n}){let a=[];if("atMost"===t)a=Object.keys(r).reverse();else{if("atLeast"!==t)return{success:!1};a=Object.keys(r)}for(let i of e)for(let e of a){let a=r[e];if(a.type===i)if("atMost"===t){if(a.y<=n)return{success:!0,ind:e,point:a}}else if(a.y>=n)return{success:!0,ind:e,point:a}}return{success:!1}}}function computeSplineParamCoeffs({dependencyValues:e}){let t=e.interpolationPoints;if(null===t)return{setValue:{xs:null,coeffs:null}};let n,r=[],a=[],i=t[0];a.push(i.x);for(let e=1;et.componentIsSpecifiedType(e,"label");if(0===e.length||!e.every((e=>"string"==typeof e||e.doenetAttributes?.createdFromMacro||n(e))))return{success:!1};let r=e.map(n),a=[],i=[],s=[];if(0===r.filter((e=>e)).length)a=e;else{if(r[0]){let t=r.indexOf(!1);-1!==t&&(i=e.slice(0,t),e=e.slice(t),r=r.slice(t))}let t=r.indexOf(!0);-1===t?a=e:(a=e.slice(0,t),s=e.slice(t))}return 0===a.length||1===a.length&&"string"!=typeof a[0]?{success:!1}:{success:!0,newChildren:[...i,{componentType:"math",children:a},...s]}}}),e}static returnStateVariableDefinitions({numerics:e}){let t=super.returnStateVariableDefinitions({numerics:e}),n=this.componentType;t.isInterpolatedFunction={returnDependencies:()=>({}),definition:()=>({setValue:{isInterpolatedFunction:!1}})},delete t.nPrescribedPoints,delete t.prescribedPoints,delete t.prescribedMinima,delete t.prescribedMaxima,delete t.prescribedExtrema,delete t.interpolationPoints,delete t.xs,t.operatorBasedOnFormulaIfAvailable={returnDependencies:()=>({}),definition:()=>({setValue:{operatorBasedOnFormulaIfAvailable:!1}})},t.formula.returnDependencies=()=>({}),t.formula.definition=()=>({setValue:{formula:me$3.fromAst("_")}}),t.operatorComposesWithOriginal={returnDependencies:()=>({}),definition:()=>({setValue:{operatorComposesWithOriginal:!0}})},t.symbolicFunctionOperator={returnDependencies:()=>({}),definition:()=>({setValue:{symbolicFunctionOperator:e=>me$3.fromAst("_")}})},t.numericalFunctionOperator={additionalStateVariablesDefined:["numericalFunctionOperatorArguments"],returnDependencies:()=>({}),definition:()=>({setValue:{numericalFunctionOperator:e=>NaN,numericalFunctionOperatorArguments:[]}})},t.numericalFunctionOperatorArguments={returnDependencies:()=>({}),definition:()=>({setValue:{numericalFunctionOperatorArguments:{}}})},t.formulaOperator={returnDependencies:()=>({}),definition:()=>({setValue:{formulaOperator:e=>me$3.fromAst("_")}})},t.returnNumericalDerivatives={returnDependencies:()=>({}),definition:()=>({setValue:{returnNumericalDerivatives:null}})},t.formula={public:!0,shadowingInstructions:{createComponentOfType:"math"},additionalStateVariablesDefined:["operatorBasedOnFormula"],returnDependencies:()=>({operatorBasedOnFormulaIfAvailable:{dependencyType:"stateVariable",variableName:"operatorBasedOnFormulaIfAvailable"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["formula"]},mathChild:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]},formulaOperator:{dependencyType:"stateVariable",variableName:"formulaOperator"}}),definition:function({dependencyValues:e}){if(!e.operatorBasedOnFormulaIfAvailable||(0===e.functionChild.length||"_"===e.functionChild[0].stateValues.formula.tree)&&(0===e.mathChild.length||"_"===e.mathChild[0].stateValues.value.tree))return{setValue:{formula:me$3.fromAst("_"),operatorBasedOnFormula:!1}};let t;return t=0===e.functionChild.length?e.mathChild[0].stateValues.value:e.functionChild[0].stateValues.formula,{setValue:{formula:e.formulaOperator(t),operatorBasedOnFormula:!0}}}},t.symbolicfs={isArray:!0,entryPrefixes:["symbolicf"],returnArraySizeDependencies:()=>({nOutputs:{dependencyType:"stateVariable",variableName:"nOutputs"}}),returnArraySize:({dependencyValues:e})=>[e.nOutputs],returnArrayDependenciesByKey:()=>({globalDependencies:{operatorBasedOnFormula:{dependencyType:"stateVariable",variableName:"operatorBasedOnFormula"},formula:{dependencyType:"stateVariable",variableName:"formula"},variables:{dependencyType:"stateVariable",variableName:"variables"},nInputs:{dependencyType:"stateVariable",variableName:"nInputs"},simplify:{dependencyType:"stateVariable",variableName:"simplify"},expand:{dependencyType:"stateVariable",variableName:"expand"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["symbolicfs"]},mathChild:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]},symbolicFunctionOperator:{dependencyType:"stateVariable",variableName:"symbolicFunctionOperator"},operatorComposesWithOriginal:{dependencyType:"stateVariable",variableName:"operatorComposesWithOriginal"},domain:{dependencyType:"stateVariable",variableName:"domain"}}}),arrayDefinitionByKey:function({globalDependencyValues:e,usedDefault:t,arrayKeys:n,arraySize:r}){if(!e.operatorBasedOnFormula){if(e.operatorComposesWithOriginal){if(0===e.functionChild.length){if(0===e.mathChild.length){let e={};for(let t of n)e[t]=e=>me$3.fromAst("_");return{setValue:{symbolicfs:e}}}{let t=Object.assign({},e);t.formula=e.mathChild[0].stateValues.value;let a=[];for(let e=0;ee.symbolicFunctionOperator(...a.map((e=>e(...t))));return{setValue:{symbolicfs:i}}}}{let t=[];for(let n=0;ne.symbolicFunctionOperator(...t.map((e=>e(...n))));return{setValue:{symbolicfs:a}}}}{let t={};for(let r of n)t[r]=(...t)=>e.symbolicFunctionOperator(...t);return{setValue:{symbolicfs:t}}}}{let t={};for(let r of n)return t[r]=returnSymbolicFunctionFromFormula(e,r),{setValue:{symbolicfs:t}}}}},t.numericalfs={isArray:!0,entryPrefixes:["numericalf"],returnArraySizeDependencies:()=>({nOutputs:{dependencyType:"stateVariable",variableName:"nOutputs"}}),returnArraySize:({dependencyValues:e})=>[e.nOutputs],returnArrayDependenciesByKey:()=>({globalDependencies:{operatorBasedOnFormula:{dependencyType:"stateVariable",variableName:"operatorBasedOnFormula"},formula:{dependencyType:"stateVariable",variableName:"formula"},variables:{dependencyType:"stateVariable",variableName:"variables"},nInputs:{dependencyType:"stateVariable",variableName:"nInputs"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["numericalfs"]},mathChild:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]},numericalFunctionOperator:{dependencyType:"stateVariable",variableName:"numericalFunctionOperator"},operatorComposesWithOriginal:{dependencyType:"stateVariable",variableName:"operatorComposesWithOriginal"},domain:{dependencyType:"stateVariable",variableName:"domain"}}}),arrayDefinitionByKey:function({globalDependencyValues:e,usedDefault:t,arrayKeys:n,arraySize:r}){if(!e.operatorBasedOnFormula){if(e.operatorComposesWithOriginal){if(0===e.functionChild.length){if(0===e.mathChild.length){let e={};for(let t of n)e[t]=e=>NaN;return{setValue:{numericalfs:e}}}{Object.assign({},e).formula=e.mathChild[0].stateValues.value;let t=[];for(let n=0;ne.numericalFunctionOperator(...t.map((e=>e(...n))));return{setValue:{numericalfs:a}}}}{let t=[];for(let n=0;ne.numericalFunctionOperator(...t.map((e=>e(...n))));return{setValue:{numericalfs:a}}}}{let t={};for(let r of n)t[r]=(...t)=>e.numericalFunctionOperator(...t);return{setValue:{numericalfs:t}}}}{let t={};for(let r of n)return t[r]=returnNumericalFunctionFromFormula({formula:e.formula,nInputs:e.nInputs,variables:e.variables,domain:e.domain,component:r}),{setValue:{numericalfs:t}}}}},t.fDefinition={returnDependencies:()=>({operatorBasedOnFormula:{dependencyType:"stateVariable",variableName:"operatorBasedOnFormula"},formula:{dependencyType:"stateVariable",variableName:"formula"},variables:{dependencyType:"stateVariable",variableName:"variables"},nInputs:{dependencyType:"stateVariable",variableName:"nInputs"},nOutputs:{dependencyType:"stateVariable",variableName:"nOutputs"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["fDefinition"]},mathChild:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]},numericalFunctionOperator:{dependencyType:"stateVariable",variableName:"numericalFunctionOperator"},numericalFunctionOperatorArguments:{dependencyType:"stateVariable",variableName:"numericalFunctionOperatorArguments"},operatorComposesWithOriginal:{dependencyType:"stateVariable",variableName:"operatorComposesWithOriginal"},domain:{dependencyType:"stateVariable",variableName:"domain"}}),definition({dependencyValues:e}){if(e.operatorBasedOnFormula)return{setValue:{fDefinition:{functionType:"formula",formula:e.formula.tree,variables:e.variables.map((e=>e.tree)),nInputs:e.nInputs,nOutputs:e.nOutputs,domain:e.domain}}};if(e.operatorComposesWithOriginal){if(0===e.functionChild.length){if(0===e.mathChild.length)return{setValue:{fDefinition:{functionType:"formula",formula:"_",variables:e.variables.map((e=>e.tree)),nInputs:e.nInputs,nOutputs:e.nOutputs,domain:e.domain}}};throw Error("function operator with math child not implemented yet")}return{setValue:{fDefinition:{functionType:"functionOperator",componentType:n,nOutputs:e.nOutputs,functionOperatorArguments:e.numericalFunctionOperatorArguments,operatorComposesWithOriginal:!0,originalFDefinition:e.functionChild[0].stateValues.fDefinition}}}}if(0===e.functionChild.length){if(0===e.mathChild.length)return{setValue:{fDefinition:{functionType:"formula",formula:"_",variables:e.variables.map((e=>e.tree)),nInputs:e.nInputs,nOutputs:e.nOutputs,domain:e.domain}}};throw Error("function operator with math child not implemented yet")}return{setValue:{fDefinition:{functionType:"functionOperator",componentType:n,nOutputs:e.nOutputs,functionOperatorArguments:e.numericalFunctionOperatorArguments,operatorComposesWithOriginal:!1,originalFDefinition:e.functionChild[0].stateValues.fDefinition}}}}};let r=t.allMinima.returnDependencies;t.allMinima.returnDependencies=function(e){let t=r(e);return delete t.functionChild,t};let a=t.allMaxima.returnDependencies;return t.allMaxima.returnDependencies=function(e){let t=a(e);return delete t.functionChild,t},t}}class ClampFunction extends FunctionOperator{static componentType="clampFunction";static createAttributesObject(){let e=super.createAttributesObject();return e.lowerValue={createComponentOfType:"number",createStateVariable:"lowerValue",defaultValue:0,public:!0},e.upperValue={createComponentOfType:"number",createStateVariable:"upperValue",defaultValue:1,public:!0},e}static returnStateVariableDefinitions({numerics:e}){let t=super.returnStateVariableDefinitions({numerics:e});return t.numericalFunctionOperator={additionalStateVariablesDefined:["numericalFunctionOperatorArguments"],returnDependencies:()=>({lowerValue:{dependencyType:"stateVariable",variableName:"lowerValue"},upperValue:{dependencyType:"stateVariable",variableName:"upperValue"}}),definition:function({dependencyValues:e}){return{setValue:{numericalFunctionOperator:functionOperatorDefinitions.clampFunction(e.lowerValue,e.upperValue),numericalFunctionOperatorArguments:[e.lowerValue,e.upperValue]}}}},t.symbolicFunctionOperator={returnDependencies:()=>({numericalFunctionOperator:{dependencyType:"stateVariable",variableName:"numericalFunctionOperator"}}),definition:({dependencyValues:e})=>({setValue:{symbolicFunctionOperator:t=>me$3.fromAst(e.numericalFunctionOperator(t.evaluate_to_constant()))}})},t}}class WrapFunctionPeriodic extends FunctionOperator{static componentType="wrapFunctionPeriodic";static createAttributesObject(){let e=super.createAttributesObject();return e.lowerValue={createComponentOfType:"number",createStateVariable:"lowerValue",defaultValue:0,public:!0},e.upperValue={createComponentOfType:"number",createStateVariable:"upperValue",defaultValue:1,public:!0},e}static returnStateVariableDefinitions({numerics:e}){let t=super.returnStateVariableDefinitions({numerics:e});return t.numericalFunctionOperator={additionalStateVariablesDefined:["numericalFunctionOperatorArguments"],returnDependencies:()=>({lowerValue:{dependencyType:"stateVariable",variableName:"lowerValue"},upperValue:{dependencyType:"stateVariable",variableName:"upperValue"}}),definition:function({dependencyValues:e}){return{setValue:{numericalFunctionOperator:functionOperatorDefinitions.wrapFunctionPeriodic(e.lowerValue,e.upperValue),numericalFunctionOperatorArguments:[e.lowerValue,e.upperValue]}}}},t.symbolicFunctionOperator={returnDependencies:()=>({numericalFunctionOperator:{dependencyType:"stateVariable",variableName:"numericalFunctionOperator"}}),definition:({dependencyValues:e})=>({setValue:{symbolicFunctionOperator:t=>me$3.fromAst(e.numericalFunctionOperator(t.evaluate_to_constant()))}})},t}}class Derivative extends FunctionOperator{static componentType="derivative";static createAttributesObject(){let e=super.createAttributesObject();return e.derivVariables={createComponentOfType:"variables"},e}static returnStateVariableDefinitions({numerics:e}){let t=super.returnStateVariableDefinitions({numerics:e});return t.operatorBasedOnFormulaIfAvailable={returnDependencies:()=>({}),definition:()=>({setValue:{operatorBasedOnFormulaIfAvailable:!0}})},t.operatorComposesWithOriginal={returnDependencies:()=>({}),definition:()=>({setValue:{operatorComposesWithOriginal:!1}})},t.haveFunctionChild={returnDependencies:()=>({functionChild:{dependencyType:"child",childGroups:["functions"]}}),definition:({dependencyValues:e})=>({setValue:{haveFunctionChild:e.functionChild.length>0}})},t.nInputs={defaultValue:1,hasEssential:!0,public:!0,shadowingInstructions:{createComponentOfType:"integer"},stateVariablesDeterminingDependencies:["haveFunctionChild"],returnDependencies({stateValues:e}){let t={nInputsAttr:{dependencyType:"attributeComponent",attributeName:"nInputs",variableNames:["value"]},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["nInputs"]},variablesAttr:{dependencyType:"attributeComponent",attributeName:"variables",variableNames:["nComponents"]}};return e.haveFunctionChild||(t.derivVariablesAttr={dependencyType:"attributeComponent",attributeName:"derivVariables",variableNames:["variables"]}),t},definition({dependencyValues:e}){if(null!==e.nInputsAttr){let t=e.nInputsAttr.stateValues.value;return t>=0||(t=1),{setValue:{nInputs:t}}}if(null!==e.variablesAttr)return{setValue:{nInputs:Math.max(1,e.variablesAttr.stateValues.nComponents)}};if(e.functionChild.length>0)return{setValue:{nInputs:e.functionChild[0].stateValues.nInputs}};if(null!==e.derivVariablesAttr){let t=[...new Set(e.derivVariablesAttr.stateValues.variables.map((e=>e.subscripts_to_strings().tree)))].length;return{setValue:{nInputs:t}}}return{useEssentialOrDefaultValue:{nInputs:!0}}}},t.variables={isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"variable"},entryPrefixes:["variable"],returnArraySizeDependencies:()=>({nInputs:{dependencyType:"stateVariable",variableName:"nInputs"}}),returnArraySize:({dependencyValues:e})=>[e.nInputs],stateVariablesDeterminingDependencies:["haveFunctionChild"],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={variablesAttr:{dependencyType:"attributeComponent",attributeName:"variables",variableNames:["variables"]},parentVariableForChild:{dependencyType:"parentStateVariable",variableName:"variableForChild"},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},haveFunctionChild:{dependencyType:"stateVariable",variableName:"haveFunctionChild"}},r={};if(t.haveFunctionChild)for(let t of e)r[t]={functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["variable"+(Number(t)+1)]}};else n.derivVariablesAttr={dependencyType:"attributeComponent",attributeName:"derivVariables",variableNames:["variables"]};return{globalDependencies:n,dependenciesByKey:r}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arraySize:n,arrayKeys:r,usedDefault:a}){if(null!==e.variablesAttr){let t=e.variablesAttr.stateValues.variables;return{setValue:{variables:returnNVariables(n[0],t)}}}if(e.haveFunctionChild){let e={};for(let n of r)e[n]=t[n].functionChild[0].stateValues["variable"+(Number(n)+1)];return{setValue:{variables:e}}}if(null!==e.derivVariablesAttr){let t=[],r=[];for(let n of e.derivVariablesAttr.stateValues.variables){let e=n.subscripts_to_strings().tree;r.includes(e)||(t.push(n),r.push(e))}return{setValue:{variables:returnNVariables(n[0],t)}}}return e.parentVariableForChild&&!a.parentVariableForChild?{setValue:{variables:Array(n[0]).fill(e.parentVariableForChild)}}:{setValue:{variables:returnNVariables(n[0],[])}}}},t.nDerivatives={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({derivVariablesAttr:{dependencyType:"attributeComponent",attributeName:"derivVariables",variableNames:["nComponents"]}}),definition:({dependencyValues:e})=>null!==e.derivVariablesAttr?{setValue:{nDerivatives:e.derivVariablesAttr.stateValues.nComponents}}:{setValue:{nDerivatives:1}}},t.derivVariables={isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"variable"},entryPrefixes:["derivVariable"],returnArraySizeDependencies:()=>({nDerivatives:{dependencyType:"stateVariable",variableName:"nDerivatives"}}),returnArraySize:({dependencyValues:e})=>[e.nDerivatives],returnArrayDependenciesByKey:()=>({globalDependencies:{derivVariablesAttr:{dependencyType:"attributeComponent",attributeName:"derivVariables",variableNames:["variables"]},variable1:{dependencyType:"stateVariable",variableName:"variable1"}}}),arrayDefinitionByKey:({globalDependencyValues:e})=>null!==e.derivVariablesAttr?{setValue:{derivVariables:e.derivVariablesAttr.stateValues.variables}}:{setValue:{derivVariables:{0:e.variable1}}}},t.formulaOperator={returnDependencies:()=>({derivVariables:{dependencyType:"stateVariable",variableName:"derivVariables"}}),definition:({dependencyValues:e})=>({setValue:{formulaOperator:function(t){let n=t.subscripts_to_strings();for(let t of e.derivVariables)n=n.derivative(t.subscripts_to_strings().tree);return n.strings_to_subscripts()}}})},t.numericalFunctionOperator={returnDependencies:()=>({functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["returnNumericalDerivatives"],variablesOptional:!0},derivVariables:{dependencyType:"stateVariable",variableName:"derivVariables"}}),additionalStateVariablesDefined:["returnNumericalDerivatives"],definition:function({dependencyValues:e}){if(0===e.functionChild.length||!e.functionChild[0].stateValues.returnNumericalDerivatives)return{setValue:{numericalFunctionOperator:e=>NaN,returnNumericalDerivatives:null}};return{setValue:{numericalFunctionOperator:e.functionChild[0].stateValues.returnNumericalDerivatives(e.derivVariables),returnNumericalDerivatives:function(t){let n=[...e.derivVariables,...t];return e.functionChild[0].stateValues.returnNumericalDerivatives(n)}}}}},t.numericalFunctionOperatorArguments={returnDependencies:()=>({functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["numericalDerivativesDefinition"],variablesOptional:!0},derivVariables:{dependencyType:"stateVariable",variableName:"derivVariables"}}),additionalStateVariablesDefined:["numericalDerivativesDefinition"],definition:function({dependencyValues:e}){if(0===e.functionChild.length||!e.functionChild[0].stateValues.numericalDerivativesDefinition)return{setValue:{numericalFunctionOperatorArguments:[],numericalDerivativesDefinition:{}}};let t=e.functionChild[0].stateValues.numericalDerivativesDefinition,n={...t};return n.additionalDerivVariables?n.additionalDerivVariables=[...e.derivVariables,...n.additionalDerivVariables]:n.additionalDerivVariables=[...e.derivVariables],{setValue:{numericalFunctionOperatorArguments:[t,e.derivVariables],numericalDerivativesDefinition:n}}}},t.symbolicFunctionOperator={returnDependencies:()=>({numericalFunctionOperator:{dependencyType:"stateVariable",variableName:"numericalFunctionOperator"}}),definition:({dependencyValues:e})=>({setValue:{symbolicFunctionOperator:t=>me$3.fromAst(e.numericalFunctionOperator(t.evaluate_to_constant()))}})},t}}var FunctionOperators=Object.freeze({__proto__:null,ClampFunction:ClampFunction,WrapFunctionPeriodic:WrapFunctionPeriodic,Derivative:Derivative});class TextBaseOperatorOfMath extends Text{static componentType="_textOperatorOfMath";static rendererType="text";static returnChildGroups(){return[{group:"maths",componentTypes:["math"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=this;return e.value={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]}}),definition:function({dependencyValues:e}){return{setValue:{value:t.applyTextOperator(e.mathChildren.map((e=>e.stateValues.value)))}}}},e}}class ExtractMathOperator extends TextBaseOperatorOfMath{static componentType="extractMathOperator";static applyTextOperator(e){return 0===e.length?"":1!==e.length?(console.warn("MathOperator requires exactly one math child"),""):Array.isArray(e[0].tree)?e[0].tree[0]:""}}var TextOperatorsOfMath=Object.freeze({__proto__:null,ExtractMathOperator:ExtractMathOperator});class Extremum extends BaseComponent{static componentType="extremum";static rendererType=void 0;static createAttributesObject(){let e=super.createAttributesObject();return e.location={createComponentOfType:"math"},e.value={createComponentOfType:"math"},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({childrenRegex:/s+(.*s)?/,replacementFunction:function({matchedChildren:e}){let t=returnBreakStringsSugarFunction({childrenToComponentFunction:e=>({componentType:"math",children:e}),mustStripOffOuterParentheses:!0}),n=t({matchedChildren:e});if(!n.success&&1===e.length)return{success:!0,newAttributes:{value:{component:{componentType:"math",children:e}}}};if(n.success){if(1===n.newChildren.length)return{success:!0,newAttributes:{value:{component:n.newChildren[0]}}};if(2===n.newChildren.length){let e=n.newChildren[0],t=n.newChildren[1],r={location:{component:e},value:{component:t}};return(0===e.children.length||1===e.children.length&&"string"==typeof e.children[0]&&""===e.children[0].trim())&&delete r.location,(0===t.children.length||1===t.children.length&&"string"==typeof t.children[0]&&""===t.children[0].trim())&&delete r.value,{success:!0,newAttributes:r}}return{success:!1}}return n}}),e}static returnChildGroups(){return[{group:"points",componentTypes:["point"]}]}static returnStateVariableDefinitions({numerics:e}){let t=super.returnStateVariableDefinitions({numerics:e}),n=this;return t.value={public:!0,shadowingInstructions:{createComponentOfType:"math"},defaultValue:null,hasEssential:!0,additionalStateVariablesDefined:[{variableName:"location",public:!0,shadowingInstructions:{createComponentOfType:"math"},defaultValue:null,hasEssential:!0}],returnDependencies:()=>({extremumChild:{dependencyType:"child",childGroups:["points"],variableNames:["nDimensions","xs"]},location:{dependencyType:"attributeComponent",attributeName:"location",variableNames:["value"]},value:{dependencyType:"attributeComponent",attributeName:"value",variableNames:["value"]}}),definition:function({dependencyValues:e}){let t,r;if(e.extremumChild.length>0){let a=e.extremumChild[0];2!==a.stateValues.nDimensions?(console.log("Cannot determine "+n.componentType+" from a point that isn't 2D"),t=null,r=null):(t=a.stateValues.xs[0],r=a.stateValues.xs[1])}else null!==e.location&&(t=e.location.stateValues.value),null!==e.value&&(r=e.value.stateValues.value);let a={},i={},s=!1,o=!1;void 0===t?(i.location=!0,o=!0):(a.location=t,s=!0),void 0===r?(i.value=!0,o=!0):(a.value=r,s=!0);let l={};return s&&(l.setValue=a),o&&(l.useEssentialOrDefaultValue=i),l}},t}}class Extrema extends BaseComponent{static componentType="extrema";static rendererType=void 0;static componentTypeSingular="extremum";static get componentTypeCapitalized(){return this.componentType.charAt(0).toUpperCase()+this.componentType.slice(1)}static returnSugarInstructions(){let e=super.returnSugarInstructions(),t=this;return e.push({replacementFunction:function({matchedChildren:e}){let n=breakEmbeddedStringsIntoParensPieces({componentList:e});return!0!==n.success?{success:!1}:{success:!0,newChildren:n.pieces.map((function(e){return e.length>1||"string"==typeof e[0]?{componentType:t.componentTypeSingular,children:e}:e[0]}))}}}),e}static returnChildGroups(){return[{group:"extrema",componentTypes:[this.componentTypeSingular]},{group:"points",componentTypes:["point"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=this;return e["n"+t.componentTypeCapitalized]={additionalStateVariablesDefined:["childIdentities"],returnDependencies:()=>({children:{dependencyType:"child",childGroups:["extrema","points"]}}),definition:function({dependencyValues:e}){return{setValue:{["n"+t.componentTypeCapitalized]:e.children.length,childIdentities:e.children}}}},e[t.componentType]={isArray:!0,nDimensions:2,entryPrefixes:[t.componentTypeSingular,t.componentTypeSingular+"Locations",t.componentTypeSingular+"Location",t.componentTypeSingular+"Values",t.componentTypeSingular+"Value"],stateVariablesDeterminingDependencies:["childIdentities"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:n,arraySize:r}){if([t.componentTypeSingular,t.componentTypeSingular+"Location",t.componentTypeSingular+"Value"].includes(e)){let a=Number(n)-1;return Number.isInteger(a)&&a>=0&&(!r||at+",0")):["0,0"]:e===t.componentTypeSingular+"Values"?""!==n?[]:r?Array.from(Array(r[0]),((e,t)=>t+",1")):["0,1"]:[]},arrayVarNameFromArrayKey(e){let[n,r]=e.split(",");return"0"===r?t.componentTypeSingular+"Location"+(Number(n)+1):t.componentTypeSingular+"Value"+(Number(n)+1)},arrayVarNameFromPropIndex(e,n){if(n===t.componentType){if(1===e.length)return t.componentTypeSingular+e[0];{let n=Number(e[0]);if(Number.isInteger(n)&&n>0){if(1===e[1])return t.componentTypeSingular+"Location"+n;if(2===e[1])return t.componentTypeSingular+"Value"+n}return null}}if(n===t.componentTypeSingular+"Locations")return t.componentTypeSingular+"Location"+e[0];if(n===t.componentTypeSingular+"Values")return t.componentTypeSingular+"Value"+e[0];let r=t.componentTypeSingular.length;if(n.slice(0,r)===t.componentTypeSingular){let a=Number(n.slice(r));if(Number.isInteger(a)&&a>0){if(1===e[0])return t.componentTypeSingular+"Location"+a;if(2===e[0])return t.componentTypeSingular+"Value"+a}}return null},returnArraySizeDependencies:()=>({nChildren:{dependencyType:"stateVariable",variableName:"n"+t.componentTypeCapitalized}}),returnArraySize:({dependencyValues:e})=>[e.nChildren,2],returnArrayDependenciesByKey({arrayKeys:e,stateValues:n}){let r={};for(let a of e){let e,[i,s]=a.split(",");e=n.childIdentities[i].componentType===t.componentTypeSingular?0===Number(s)?"location":"value":"x"+(Number(s)+1),r[a]={child:{dependencyType:"child",childGroups:["extrema","points"],variableNames:[e],childIndices:[i]}}}return{dependenciesByKey:r}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:n}){let r={};for(let t of n){let n=e[t].child[0];if(n){let e=t.split(",")[1],a=0===Number(e)?"location":"value";a in n.stateValues?r[t]=n.stateValues[a]:r[t]=n.stateValues["x"+(Number(e)+1)]}}return{setValue:{[t.componentType]:r}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:n}){let r=[];for(let a in e[t.componentType])r.push({setDependency:n[a].extremumChild,desiredValue:e[t.componentType][a],childIndex:0,variableIndex:0});return{success:!0,instructions:r}}},e}}var Extrema$1=Object.freeze({__proto__:null,Extremum:Extremum,Extrema:Extrema});class InlineRenderInlineChildren extends InlineComponent{static componentType="_inlineRenderInlineChildren";static renderChildren=!0;static includeBlankStringChildren=!0;static beginTextDelimiter="";static endTextDelimiter="";static returnChildGroups(){return[{group:"inlines",componentTypes:["_inline"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=this;return e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["inlines"],variableNames:["text"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let n="";for(let t of e.inlineChildren)"object"!=typeof t?n+=t.toString():"string"==typeof t.stateValues.text?n+=t.stateValues.text:n+=" ";return n=t.beginTextDelimiter+n+t.endTextDelimiter,{setValue:{text:n}}}},e}}class Em extends InlineRenderInlineChildren{static componentType="em"}class Alert extends InlineRenderInlineChildren{static componentType="alert"}class Q$2 extends InlineRenderInlineChildren{static componentType="q";static beginTextDelimiter='"';static endTextDelimiter='"'}class SQ extends InlineRenderInlineChildren{static componentType="sq";static beginTextDelimiter="'";static endTextDelimiter="'"}class Term extends InlineRenderInlineChildren{static componentType="term";static rendererType="alert"}class C$2 extends InlineRenderInlineChildren{static componentType="c"}class Tag extends InlineRenderInlineChildren{static componentType="tag";static rendererType="tag";static beginTextDelimiter="<";static endTextDelimiter=">"}class Tage extends InlineRenderInlineChildren{static componentType="tage";static rendererType="tag";static beginTextDelimiter="<";static endTextDelimiter="/>";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.selfClosed={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{selfClosed:!0}})},e}}class Attr extends InlineRenderInlineChildren{static componentType="attr";static rendererType="c"}var ParagraphMarkup=Object.freeze({__proto__:null,Em:Em,Alert:Alert,Q:Q$2,SQ:SQ,Term:Term,C:C$2,Tag:Tag,Tage:Tage,Attr:Attr});class SingleCharacter extends InlineComponent{static componentType="_singleCharacterInline";static unicodeCharacter="";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({}),definition:()=>({setValue:{text:this.unicodeCharacter}})},e}}class Ndash extends SingleCharacter{static componentType="ndash";static unicodeCharacter="–"}class Mdash extends SingleCharacter{static componentType="mdash";static unicodeCharacter="—"}class NBSP extends SingleCharacter{static componentType="nbsp";static unicodeCharacter=" "}class Ellipsis extends SingleCharacter{static componentType="ellipsis";static unicodeCharacter="…"}var SingleCharacterComponents=Object.freeze({__proto__:null,Ndash:Ndash,Mdash:Mdash,NBSP:NBSP,Ellipsis:Ellipsis});class BlockComponent extends BaseComponent{static componentType="_block"}function returnDefaultFeedbackDefinitions(){return{numericalerror:"Credit reduced because numbers in your answer weren't quite right. Did you round too much?",goodjob:"Good job!",onesignerror:"Credit reduced because it appears that you made a sign error.",twosignerrors:"Credit reduced because it appears that you made two sign errors."}}function returnFeedbackDefinitionStateVariables(){let e={setupChildren:{returnDependencies:()=>({setupChildren:{dependencyType:"child",childGroups:["setups"],proceedIfAllChildrenNotMatched:!0}}),definition:({dependencyValues:e})=>({setValue:{setupChildren:e.setupChildren}})}};return e.feedbackDefinitions={stateVariablesDeterminingDependencies:["setupChildren"],returnDependencies({stateValues:e}){let t={ancestorWithFeedback:{dependencyType:"ancestor",variableNames:["feedbackDefinitions"]},setupChildren:{dependencyType:"child",childGroups:["setups"],proceedIfAllChildrenNotMatched:!0}};for(let n of e.setupChildren)t[`feedbackDefinitionsOf${n.componentName}`]={dependencyType:"child",parentName:n.componentName,childGroups:["feedbackDefinitions"],variableNames:["value"]};return t},definition({dependencyValues:e}){let t,n={};e.ancestorWithFeedback&&(t=e.ancestorWithFeedback.stateValues.feedbackDefinitions),t||(t=returnDefaultFeedbackDefinitions()),Object.assign(n,t);let r=[];for(let t of e.setupChildren)r.push(...e[`feedbackDefinitionsOf${t.componentName}`]);for(let e of r)Object.assign(n,e.stateValues.value);return{setValue:{feedbackDefinitions:n}}}},e}class SectioningComponent extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{submitAllAnswers:this.submitAllAnswers.bind(this),revealSection:this.revealSection.bind(this),closeSection:this.closeSection.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="_sectioningComponent";static renderChildren=!0;static includeBlankStringChildren=!0;static createsVariants=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.aggregateScores={createComponentOfType:"boolean",createStateVariable:"aggregateScores",defaultValue:!1,public:!0},e.weight={createComponentOfType:"number",createStateVariable:"weight",defaultValue:1,public:!0},e.sectionWideCheckWork={createComponentOfType:"boolean",createStateVariable:"sectionWideCheckWork",defaultValue:!1,public:!0},e.submitLabel={createComponentOfType:"text",createStateVariable:"submitLabel",defaultValue:"Check Work",public:!0,forRenderer:!0},e.submitLabelNoCorrectness={createComponentOfType:"text",createStateVariable:"submitLabelNoCorrectness",defaultValue:"Submit Response",public:!0,forRenderer:!0},e.boxed={createComponentOfType:"boolean",createStateVariable:"boxed",defaultValue:!1,public:!0,forRenderer:!0},e.suppressAutoName={createComponentOfType:"boolean",createStateVariable:"suppressAutoName",defaultValue:!1,public:!0},e.suppressAutoNumber={createComponentOfType:"boolean",createStateVariable:"suppressAutoNumber",defaultValue:!1,public:!0},e.includeAutoName={createComponentOfType:"boolean",createStateVariable:"includeAutoName",defaultValue:!1,public:!0},e.includeAutoNumber={createComponentOfType:"boolean",createStateVariable:"includeAutoNumber",defaultValue:!1,public:!0},e.includeAutoNameNumberIfNoTitle={createComponentOfType:"boolean",createStateVariable:"includeAutoNameNumberIfNoTitle",defaultValue:!0,public:!0},e.includeParentNumber={createComponentOfType:"boolean",createStateVariable:"includeParentNumber",defaultValue:!1,public:!0},e.level={createComponentOfType:"integer"},e}static returnChildGroups(){return[{group:"variantControls",componentTypes:["variantControl"]},{group:"titles",componentTypes:["title"]},{group:"setups",componentTypes:["setup"]},{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnStyleDefinitionStateVariables();Object.assign(e,t);let n=returnFeedbackDefinitionStateVariables();return Object.assign(e,n),e.enumeration={additionalStateVariablesDefined:[{variableName:"sectionNumber",public:!0,shadowingInstructions:{createComponentOfType:"text"}}],returnDependencies:()=>({countAmongSiblings:{dependencyType:"countAmongSiblingsOfSameType"},sectionAncestor:{dependencyType:"ancestor",componentType:"_sectioningComponent",variableNames:["enumeration"]},includeParentNumber:{dependencyType:"stateVariable",variableName:"includeParentNumber"}}),definition({dependencyValues:e}){let t=[];return e.includeParentNumber&&e.sectionAncestor&&t.push(...e.sectionAncestor.stateValues.enumeration),t.push(e.countAmongSiblings),{setValue:{enumeration:t,sectionNumber:t.join(".")}}}},e.sectionName={returnDependencies:()=>({}),definition:()=>({setValue:{sectionName:"Section"}})},e.titleChildName={forRenderer:!0,returnDependencies:()=>({titleChild:{dependencyType:"child",childGroups:["titles"]}}),definition({dependencyValues:e}){let t=null;return e.titleChild.length>0&&(t=e.titleChild[e.titleChild.length-1].componentName),{setValue:{titleChildName:t}}}},e.childIndicesToRender={returnDependencies:()=>({titleChildren:{dependencyType:"child",childGroups:["titles"]},allChildren:{dependencyType:"child",childGroups:["anything","variantControls","titles","setups"]},titleChildName:{dependencyType:"stateVariable",variableName:"titleChildName"}}),definition({dependencyValues:e}){let t=[],n=e.titleChildren.map((e=>e.componentName));for(let[r,a]of e.allChildren.entries())"object"==typeof a&&n.includes(a.componentName)&&a.componentName!==e.titleChildName||t.push(r);return{setValue:{childIndicesToRender:t}}}},e.title={additionalStateVariablesDefined:[{variableName:"titlePrefix",forRenderer:!0,alwaysUpdateRenderer:!0}],public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,alwaysUpdateRenderer:!0,returnDependencies:({sharedParameters:e})=>({titleChild:{dependencyType:"child",childGroups:["titles"],variableNames:["text"]},sectionName:{dependencyType:"stateVariable",variableName:"sectionName"},sectionNumber:{dependencyType:"stateVariable",variableName:"sectionNumber"},includeAutoName:{dependencyType:"stateVariable",variableName:"includeAutoName"},includeAutoNumber:{dependencyType:"stateVariable",variableName:"includeAutoNumber"},prerender:{dependencyType:"value",value:e.prerender},includeAutoNameNumberIfNoTitle:{dependencyType:"stateVariable",variableName:"includeAutoNameNumberIfNoTitle"}}),definition({dependencyValues:e}){let t="",n="";const r=e.titleChild.length>0;let a=(e.includeAutoNumber||!r&&e.includeAutoNameNumberIfNoTitle)&&!e.prerender,i=e.includeAutoName||!r&&e.includeAutoNameNumberIfNoTitle;return a?(i&&(t=e.sectionName+" "),t+=e.sectionNumber):i&&(t=e.sectionName),r?(t&&(e.includeAutoName?t+=": ":t+=". "),n=e.titleChild[e.titleChild.length-1].stateValues.text):n=t,{setValue:{title:n,titlePrefix:t}}}},e.containerTag={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{containerTag:"section"}})},e.level={forRenderer:!0,returnDependencies:()=>({ancestorLevel:{dependencyType:"ancestor",componentType:"_sectioningComponent",variableNames:["level"]},levelAttr:{dependencyType:"attributeComponent",attributeName:"level",variableNames:["value"]}}),definition({dependencyValues:e}){let t=e.levelAttr?.stateValues.value;return t>0||(t=(e.ancestorLevel?.stateValues.level||0)+1),{setValue:{level:t}}}},e.viewedSolution={defaultValue:!1,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{viewedSolution:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"viewedSolution",value:e.viewedSolution}]})},e.scoredDescendants={returnDependencies:()=>({scoredDescendants:{dependencyType:"descendant",componentTypes:["_sectioningComponent","answer","setup"],variableNames:["scoredDescendants","aggregateScores","weight"],recurseToMatchedChildren:!1,variablesOptional:!0}}),definition({dependencyValues:e}){let t=[];for(let n of e.scoredDescendants)"setup"!==n.componentType&&(n.stateValues.aggregateScores||void 0===n.stateValues.scoredDescendants?t.push(n):t.push(...n.stateValues.scoredDescendants));return{setValue:{scoredDescendants:t}}}},e.answerDescendants={returnDependencies:()=>({answerDescendants:{dependencyType:"descendant",componentTypes:["answer"],variableNames:["justSubmitted"],recurseToMatchedChildren:!1}}),definition:({dependencyValues:e})=>({setValue:{answerDescendants:e.answerDescendants}})},e.justSubmitted={forRenderer:!0,returnDependencies:()=>({answerDescendants:{dependencyType:"stateVariable",variableName:"answerDescendants"}}),definition:({dependencyValues:e})=>({setValue:{justSubmitted:e.answerDescendants.every((e=>e.stateValues.justSubmitted))}})},e.showCorrectness={forRenderer:!0,returnDependencies:()=>({showCorrectnessFlag:{dependencyType:"flag",flagName:"showCorrectness"}}),definition:({dependencyValues:e})=>({setValue:{showCorrectness:!1!==e.showCorrectnessFlag}})},e.displayDigitsForCreditAchieved={returnDependencies:()=>({}),definition:()=>({setValue:{displayDigitsForCreditAchieved:3}})},e.creditAchieved={public:!0,shadowingInstructions:{createComponentOfType:"number",addAttributeComponentsShadowingStateVariables:{displayDigits:{stateVariableToShadow:"displayDigitsForCreditAchieved"}}},forRenderer:!0,defaultValue:0,hasEssential:!0,additionalStateVariablesDefined:[{variableName:"percentCreditAchieved",public:!0,shadowingInstructions:{createComponentOfType:"number",addAttributeComponentsShadowingStateVariables:{displayDigits:{stateVariableToShadow:"displayDigitsForCreditAchieved"}}},defaultValue:0,hasEssential:!0}],stateVariablesDeterminingDependencies:["aggregateScores","scoredDescendants"],returnDependencies({stateValues:e}){let t={aggregateScores:{dependencyType:"stateVariable",variableName:"aggregateScores"}};if(e.aggregateScores){t.scoredDescendants={dependencyType:"stateVariable",variableName:"scoredDescendants"};for(let[n,r]of e.scoredDescendants.entries())t["creditAchieved"+n]={dependencyType:"stateVariable",componentName:r.componentName,variableName:"creditAchieved"}}return t},definition({dependencyValues:e}){if(!e.aggregateScores)return{setValue:{creditAchieved:0,percentCreditAchieved:0}};let t,n=0,r=0;for(let[t,a]of e.scoredDescendants.entries()){let i=a.stateValues.weight;n+=e["creditAchieved"+t]*i,r+=i}return t=r>0?n/r:1,{setValue:{creditAchieved:t,percentCreditAchieved:100*t}}}},e.creditAchievedIfSubmit={defaultValue:0,stateVariablesDeterminingDependencies:["aggregateScores","scoredDescendants"],returnDependencies({stateValues:e}){let t={aggregateScores:{dependencyType:"stateVariable",variableName:"aggregateScores"}};if(e.aggregateScores){t.scoredDescendants={dependencyType:"stateVariable",variableName:"scoredDescendants"};for(let[n,r]of e.scoredDescendants.entries())t["creditAchievedIfSubmit"+n]={dependencyType:"stateVariable",componentName:r.componentName,variableName:"creditAchievedIfSubmit"}}return t},definition({dependencyValues:e}){if(!e.aggregateScores)return{setValue:{creditAchievedIfSubmit:0}};let t=0,n=0;for(let[r,a]of e.scoredDescendants.entries()){let i=a.stateValues.weight;t+=e["creditAchievedIfSubmit"+r]*i,n+=i}return{setValue:{creditAchievedIfSubmit:t/n}}}},e.generatedVariantInfo={additionalStateVariablesDefined:["isVariantComponent"],returnDependencies:({sharedParameters:e,componentInfoObjects:t})=>({variantSeed:{dependencyType:"value",value:e.variantSeed},variantIndex:{dependencyType:"value",value:e.variantIndex},variantName:{dependencyType:"value",value:e.variantName},variantDescendants:{dependencyType:"descendant",componentTypes:Object.keys(t.componentTypesCreatingVariants),variableNames:["isVariantComponent","generatedVariantInfo"],recurseToMatchedChildren:!1,variablesOptional:!0,includeNonActiveChildren:!0,ignoreReplacementsOfEncounteredComposites:!0}}),definition({dependencyValues:e,componentName:t}){let n={};e.variantName?(n.index=e.variantIndex,n.name=e.variantName):n.seed=e.variantSeed,n.meta={createdBy:t};let r=n.subvariants=[];for(let t of e.variantDescendants)t.stateValues.isVariantComponent?r.push(t.stateValues.generatedVariantInfo):t.stateValues.generatedVariantInfo&&r.push(...t.stateValues.generatedVariantInfo.subvariants);return{setValue:{generatedVariantInfo:n,isVariantComponent:!0}}}},e.collapsible={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{collapsible:!1}})},e.open={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,defaultValue:!0,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{open:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"open",value:e.open}]})},e.createSubmitAllButton={forRenderer:!0,additionalStateVariablesDefined:[{variableName:"suppressAnswerSubmitButtons",forRenderer:!0}],returnDependencies:()=>({sectionWideCheckWork:{dependencyType:"stateVariable",variableName:"sectionWideCheckWork"},aggregateScores:{dependencyType:"stateVariable",variableName:"aggregateScores"},sectionAncestor:{dependencyType:"ancestor",componentType:"_sectioningComponent",variableNames:["suppressAnswerSubmitButtons"]},documentAncestor:{dependencyType:"ancestor",componentType:"document",variableNames:["suppressAnswerSubmitButtons"]}}),definition({dependencyValues:e,componentName:t}){let n=!1,r=!1;return e.documentAncestor.stateValues.suppressAnswerSubmitButtons||e.sectionAncestor&&e.sectionAncestor.stateValues.suppressAnswerSubmitButtons?r=!0:e.sectionWideCheckWork&&(e.aggregateScores?(n=!0,r=!0):console.warn(`Cannot create submit all button for ${t} because it doesn't aggegrate scores`)),{setValue:{createSubmitAllButton:n,suppressAnswerSubmitButtons:r}}}},e.suppressCheckwork={forRenderer:!0,returnDependencies:()=>({autoSubmit:{dependencyType:"flag",flagName:"autoSubmit"}}),definition:({dependencyValues:e})=>({setValue:{suppressCheckwork:e.autoSubmit}})},e}async submitAllAnswers({actionId:e}){this.coreFunctions.requestRecordEvent({verb:"submitted",object:{componentName:this.componentName,componentType:this.componentType},result:{creditAchieved:await this.stateValues.creditAchievedIfSubmit}});for(let e of await this.stateValues.answerDescendants)await e.stateValues.justSubmitted||await this.coreFunctions.performAction({componentName:e.componentName,actionName:"submitAnswer"});this.coreFunctions.resolveAction({actionId:e})}async revealSection({actionId:e}){return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"open",value:!0}],overrideReadOnly:!0,actionId:e,event:{verb:"viewed",object:{componentName:this.componentName,componentType:this.componentType}}})}async closeSection({actionId:e}){return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"open",value:!1}],overrideReadOnly:!0,actionId:e,event:{verb:"closed",object:{componentName:this.componentName,componentType:this.componentType}}})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}static setUpVariant({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n}){if(!e.variants?.allPossibleVariants)return void setUpVariantSeedAndRng({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n,useSubpartVariantRng:!0});let r,a=e.variants.numberOfVariants,i=e.variants.desiredVariant;if(void 0!==i&&void 0!==i.index){let e=Number(i.index);if(Number.isFinite(e)){Number.isInteger(e)||(console.warn("Variant index "+i.index+" must be an integer"),e=Math.round(e));let t=(e-1)%a;t<0&&(t+=a),r=t+1}else console.warn("Variant index "+i.index+" must be a number"),r=1}if(void 0===r){let e=t.variantRng();r=Math.floor(e*a)+1}if(t.allPossibleVariants=e.variants.allPossibleVariants,t.allVariantNames=e.variants.allVariantNames,t.variantSeed=e.variants.allPossibleVariantSeeds[r-1],t.variantIndex=r,t.variantName=e.variants.allPossibleVariants[r-1],t.uniqueIndex=e.variants.allPossibleVariantUniqueIndices[r-1],t.variantRng=new t.rngClass(t.variantSeed),t.subpartVariantRng=new t.rngClass(t.variantSeed+"s"),i?.subvariants&&n)for(let e in i.subvariants){let t=i.subvariants[e],r=n[e];if(void 0===r)break;r.variants.desiredVariant=t}}static determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t}){return determineVariantsForSection({serializedComponent:e,componentInfoObjects:t})}static getUniqueVariant({serializedComponent:e,variantIndex:t,componentInfoObjects:n}){if(!e.variants.allPossibleVariants)return super.getUniqueVariant({serializedComponent:e,variantIndex:t,componentInfoObjects:n});let r=e.variants.allPossibleVariantUniqueIndices[t-1];if(void 0===r)return{success:!1};if(!e.variants.uniqueVariants)return{success:!0,desiredVariant:{index:t}};let a=getVariantsForDescendantsForUniqueVariants({variantIndex:r,serializedComponent:e,componentInfoObjects:n});return a.success?(e.variants.selectedUniqueVariant=!0,{success:!0,desiredVariant:{index:t,subvariants:a.desiredVariants}}):(console.log("Failed to get unique variant for section."),{success:!1})}}class Section extends SectioningComponent{static componentType="section";static rendererType="section";static createAttributesObject(){let e=super.createAttributesObject();return e.includeParentNumber.defaultValue=!0,e}}class Subsection extends Section{static componentType="subsection"}class Subsubsection extends Section{static componentType="subsubsection"}class Paragraphs extends SectioningComponent{static componentType="paragraphs";static rendererType="section";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.level.definition=()=>({setValue:{level:4}}),e.sectionName.definition=()=>({setValue:{sectionName:"Paragraphs"}}),e}}class Aside extends SectioningComponent{static componentType="aside";static rendererType="section";static createAttributesObject(){let e=super.createAttributesObject();return e.collapsible={createComponentOfType:"boolean",createStateVariable:"collapsible",defaultValue:!0,public:!0,forRenderer:!0},e.startOpen={createComponentOfType:"boolean",createStateVariable:"startOpen",defaultValue:!1},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return delete e.collapsible,e.open.returnDependencies=()=>({startOpen:{dependencyType:"stateVariable",variableName:"startOpen"}}),e.open.definition=({dependencyValues:e})=>({useEssentialOrDefaultValue:{open:{defaultValue:e.startOpen}}}),e.level.definition=()=>({setValue:{level:3}}),e.containerTag.definition=()=>({setValue:{containerTag:"aside"}}),e.sectionName.definition=()=>({setValue:{sectionName:"Aside"}}),e}}class Problem extends SectioningComponent{static componentType="problem";static rendererType="section";static createAttributesObject(){let e=super.createAttributesObject();return e.aggregateScores.defaultValue=!0,e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.sectionName.definition=()=>({setValue:{sectionName:"Problem"}}),e}}class Exercise extends Problem{static componentType="exercise";static rendererType="section";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.sectionName.definition=()=>({setValue:{sectionName:"Exercise"}}),e}}class Example extends SectioningComponent{static componentType="example";static rendererType="section";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.sectionName.definition=()=>({setValue:{sectionName:"Example"}}),e}}class StandinForFutureLayoutTag extends SectioningComponent{static componentType="standinForFutureLayoutTag";static rendererType="section";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.level.definition=()=>({setValue:{level:3}}),e.containerTag.definition=()=>({setValue:{containerTag:"aside"}}),e}}class externalContent extends SectioningComponent{static componentType="externalContent";static rendererType="section";static createAttributesObject(){let e=super.createAttributesObject();return e.includeAutoNameNumberIfNoTitle.defaultValue=!1,e}}var Sectioning=Object.freeze({__proto__:null,Section:Section,Subsection:Subsection,Subsubsection:Subsubsection,Paragraphs:Paragraphs,Aside:Aside,Problem:Problem,Exercise:Exercise,Example:Example,StandinForFutureLayoutTag:StandinForFutureLayoutTag,externalContent:externalContent});class Ol extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="ol";static rendererType="list";static renderChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.label={createComponentOfType:"text",createStateVariable:"label",defaultValue:null,public:!0,forRenderer:!0},e}static returnChildGroups(){return[{group:"lis",componentTypes:["li"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numbered={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{numbered:!0}})},e}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class Ul extends Ol{static componentType="ul";static rendererType="list";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numbered={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{numbered:!1}})},e}}class Li$1 extends BaseComponent{constructor(e){super(e),Object.assign(this.actions,{recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="li";static rendererType="list";static renderChildren=!0;static includeBlankStringChildren=!0;static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.item={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{item:!0}})},e}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}var Lists=Object.freeze({__proto__:null,Ol:Ol,Ul:Ul,Li:Li$1});class ODESystem extends InlineComponent{static componentType="odesystem";static rendererType="math";static createAttributesObject(){let e=super.createAttributesObject();return e.independentVariable={createComponentOfType:"variable",createStateVariable:"independentVariable",defaultValue:me$3.fromAst("t"),public:!0},e.initialIndependentVariableValue={createComponentOfType:"math",createStateVariable:"initialIndependentVariableValue",defaultValue:me$3.fromAst(0),public:!0},e.displayDigits={createComponentOfType:"integer",createStateVariable:"displayDigits",defaultValue:14,public:!0},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.padZeros={createComponentOfType:"boolean",createStateVariable:"padZeros",defaultValue:!1,public:!0},e.renderMode={createComponentOfType:"text",createStateVariable:"renderMode",defaultValue:"align",public:!0,forRenderer:!0},e.chunkSize={createComponentOfType:"number",createStateVariable:"chunkSize",defaultValue:10,public:!0},e.tolerance={createComponentOfType:"number",createStateVariable:"tolerance",defaultValue:1e-6,public:!0},e.maxIterations={createComponentOfType:"number",createStateVariable:"maxIterations",defaultValue:1e3,public:!0},e.hideInitialCondition={createComponentOfType:"boolean",createStateVariable:"hideInitialCondition",defaultValue:!1,public:!0},e.initialConditions={createComponentOfType:"mathList"},e.variables={createComponentOfType:"variables"},e.number={createComponentOfType:"boolean",createStateVariable:"number",defaultValue:!1,public:!0},e}static returnChildGroups(){return[{group:"rightHandSides",componentTypes:["rightHandSide"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.validIndependentVariable={returnDependencies:()=>({independentVarAttr:{dependencyType:"attributeComponent",attributeName:"independentVariable",variableNames:["validVariable"]}}),definition({dependencyValues:e}){let t=!0;return e.independentVarAttr&&(t=e.independentVarAttr.stateValues.validVariable),{setValue:{validIndependentVariable:t}}}},e.nDimensions={returnDependencies:()=>({rhsChildren:{dependencyType:"child",childGroups:["rightHandSides"],skipComponentNames:!0}}),definition:function({dependencyValues:e}){return{setValue:{nDimensions:e.rhsChildren.length},checkForActualChange:{nDimensions:!0}}}},e.variables={additionalStateVariablesDefined:[{variableName:"validVariables",isArray:!0,entryPrefixes:["validVar"]}],isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"variable"},entryPrefixes:["var"],returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey:()=>({globalDependencies:{nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},variables:{dependencyType:"attributeComponent",attributeName:"variables",variableNames:["variables","validVariables"]},independentVariable:{dependencyType:"stateVariable",variableName:"independentVariable"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t=[],n=[],r=e.nDimensions;null!==e.variables&&(t=e.variables.stateValues.variables,n=[...e.variables.stateValues.validVariables].slice(0,r));let a=returnNVariables(r,t);return a.some((t=>t.equals(e.independentVariable)))&&console.warn("Variables of odesystem must be different than independent variable."),n.length({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={rhsChild:{dependencyType:"child",childGroups:["rightHandSides"],variableNames:["value"],childIndices:[n]}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t)n[r]=e[r].rhsChild[0].stateValues.value;return{setValue:{rhss:n}}}},e.rhs={isAlias:!0,targetVariableName:"rhs1"},e.righthandside={isAlias:!0,targetVariableName:"rhs1"},e.righthandsides={isAlias:!0,targetVariableName:"rhss"},e.initialConditions={isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"math"},entryPrefixes:["initialCondition"],defaultValueByArrayKey:()=>me$3.fromAst(0),returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={initialConditionAttr:{dependencyType:"attributeComponent",attributeName:"initialConditions",variableNames:[`math${Number(n)+1}`]}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={},r={};for(let a of t){let t=!1;if(e[a].initialConditionAttr){let r=e[a].initialConditionAttr.stateValues[`math${Number(a)+1}`];void 0!==r&&(t=!0,n[a]=r)}t||(r[a]=!0)}let a={};return Object.keys(n).length>0&&(a.setValue={initialConditions:n}),Object.keys(r).length>0&&(a.useEssentialOrDefaultValue={initialConditions:r}),a}},e.initialCondition={isAlias:!0,targetVariableName:"initialCondition1"},e.equationTag={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,stateVariablesDeterminingDependencies:["number"],returnDependencies:({stateValues:e})=>e.number?{equationCounter:{dependencyType:"counter",counterName:"equation"}}:{},definition:({dependencyValues:e})=>void 0!==e.equationCounter?{setValue:{equationTag:String(e.equationCounter)}}:{setValue:{equationTag:null}}},e.latex={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},variables:{dependencyType:"stateVariable",variableName:"variables"},initialConditions:{dependencyType:"stateVariable",variableName:"initialConditions"},hideInitialCondition:{dependencyType:"stateVariable",variableName:"hideInitialCondition"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"},independentVariable:{dependencyType:"stateVariable",variableName:"independentVariable"},initialIndependentVariableValue:{dependencyType:"stateVariable",variableName:"initialIndependentVariableValue"},rhss:{dependencyType:"stateVariable",variableName:"rhss"},number:{dependencyType:"stateVariable",variableName:"number"},equationTag:{dependencyType:"stateVariable",variableName:"equationTag"}}),definition({dependencyValues:e,usedDefault:t}){let n={};e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(n.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(n.padToDigits=e.displayDigits));let r=[],a=e.independentVariable.toLatex();for(let i=0;i({latex:{dependencyType:"stateVariable",variableName:"latex"}}),definition:function({dependencyValues:e}){return{setValue:{latexWithInputChildren:[e.latex]}}}},e.numericalRHSf={additionalStateVariablesDefined:["numericalRHSfDefinitions"],returnDependencies:()=>({validIndependentVariable:{dependencyType:"stateVariable",variableName:"validIndependentVariable"},independentVariable:{dependencyType:"stateVariable",variableName:"independentVariable"},validVariables:{dependencyType:"stateVariable",variableName:"validVariables"},variables:{dependencyType:"stateVariable",variableName:"variables"},rhss:{dependencyType:"stateVariable",variableName:"rhss"}}),definition({dependencyValues:e}){let t=!0;e.validIndependentVariable||(console.warn("Can't define ODE RHS functions with invalid independent variable."),t=!1),e.validVariables.every((e=>e))||(console.warn("Can't define ODE RHS functions with an invalid variable."),t=!1);let n,r=e.independentVariable.subscripts_to_strings().tree,a=e.variables.map((e=>e.subscripts_to_strings().tree));a.includes(r)&&(console.warn("Can't define ODE RHS functions when independent variable is a dependent variable"),t=!1),[...new Set(a)].length!==a.length&&(console.warn("Can't define ODE RHS functions with duplicate dependent variable names"),t=!1);try{n=e.rhss.map((e=>e.subscripts_to_strings().f()))}catch(e){console.warn("Cannot define ODE RHS function. Error creating mathjs function"),t=!1}if(!t){let t=e.rhss.length;return{setValue:{numericalRHSf:()=>NaN,numericalRHSfDefinitions:Array(t).fill({})}}}return{setValue:{numericalRHSf:function(e,t){let i={[r]:e};Array.isArray(t)?t.forEach(((e,t)=>i[a[t]]=e)):i[a[0]]=t;try{return n.map((e=>e(i)))}catch(e){return NaN}},numericalRHSfDefinitions:e.rhss.map((e=>({functionType:"formula",formula:e,nInputs:a.length+1,variables:[r,...a]})))}}}},e.haveNumericalInitialConditions={additionalStateVariablesDefined:["t0","x0s"],returnDependencies:()=>({initialIndependentVariableValue:{dependencyType:"stateVariable",variableName:"initialIndependentVariableValue"},initialConditions:{dependencyType:"stateVariable",variableName:"initialConditions"}}),definition({dependencyValues:e}){let t=e.initialIndependentVariableValue.evaluate_to_constant(),n=e.initialConditions.map((e=>e.evaluate_to_constant())),r=Number.isFinite(t)&&n.every((e=>Number.isFinite(e)));return{setValue:{t0:t,x0s:n,haveNumericalInitialConditions:r}}}},e.numericalSolutions={isArray:!0,entryPrefixes:["numericalSolution"],public:!0,shadowingInstructions:{createComponentOfType:"function",addStateVariablesShadowingStateVariables:{fDefinition:{stateVariableToShadow:"numericalSolutionFDefinitions"}}},createWorkspace:!0,returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey:()=>({globalDependencies:{nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},validIndependentVariable:{dependencyType:"stateVariable",variableName:"validIndependentVariable"},independentVariable:{dependencyType:"stateVariable",variableName:"independentVariable"},validVariables:{dependencyType:"stateVariable",variableName:"validVariables"},variables:{dependencyType:"stateVariable",variableName:"variables"},chunkSize:{dependencyType:"stateVariable",variableName:"chunkSize"},tolerance:{dependencyType:"stateVariable",variableName:"tolerance"},maxIterations:{dependencyType:"stateVariable",variableName:"maxIterations"},haveNumericalInitialConditions:{dependencyType:"stateVariable",variableName:"haveNumericalInitialConditions"},t0:{dependencyType:"stateVariable",variableName:"t0"},x0s:{dependencyType:"stateVariable",variableName:"x0s"},numericalRHSf:{dependencyType:"stateVariable",variableName:"numericalRHSf"}}}),arrayDefinitionByKey({globalDependencyValues:e,workspace:t,componentName:n}){let r={};if(t.calculatedNumericSolutions=[],t.endingNumericalValues=[],t.maxPossibleTime=void 0,!e.haveNumericalInitialConditions){for(let t=0;tNaN;return{setValue:{numericalSolutions:r}}}let a=e.t0,i=e.x0s,s=e.chunkSize,o=e.tolerance,l=e.numericalRHSf,u=e.maxIterations;for(let c=0;c=r)for(let e=r;e<=p;e++){let r=t.endingNumericalValues[e-1];void 0===r&&(r=i);let c=a+e*s,p=me$3.math.dopri(c,c+s,r,l,o,u);t.endingNumericalValues.push(p.y[p.y.length-1]),t.calculatedNumericSolutions.push(p.at.bind(p));let d=p.x[p.x.length-1];if(d<.999999*(c+s)){t.maxPossibleTime=d;let e="For chunksize "+s+" and tolerance "+o+", odesystem";void 0!==n&&(e+=" ("+n+")"),e+=" hit maxiterations ("+u+") at t = "+t.maxPossibleTime+". Will not calculate solution beyond that time. Decrease chunksize, increase maxiterations, or increase tolerance to calculate further.";break}}return e>t.maxPossibleTime?NaN:t.calculatedNumericSolutions[p](e)[c]};return{setValue:{numericalSolutions:r}}}},e.numericalSolution={isAlias:!0,targetVariableName:"numericalSolution1"},e.numericalSolutionFDefinitions={forRenderer:!0,isArray:!0,entryPrefixes:["numericalSolutionFDefinition"],returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey:()=>({globalDependencies:{nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},validIndependentVariable:{dependencyType:"stateVariable",variableName:"validIndependentVariable"},independentVariable:{dependencyType:"stateVariable",variableName:"independentVariable"},validVariables:{dependencyType:"stateVariable",variableName:"validVariables"},variables:{dependencyType:"stateVariable",variableName:"variables"},chunkSize:{dependencyType:"stateVariable",variableName:"chunkSize"},tolerance:{dependencyType:"stateVariable",variableName:"tolerance"},maxIterations:{dependencyType:"stateVariable",variableName:"maxIterations"},haveNumericalInitialConditions:{dependencyType:"stateVariable",variableName:"haveNumericalInitialConditions"},t0:{dependencyType:"stateVariable",variableName:"t0"},x0s:{dependencyType:"stateVariable",variableName:"x0s"},numericalRHSfDefinitions:{dependencyType:"stateVariable",variableName:"numericalRHSfDefinitions"}}}),arrayDefinitionByKey:({globalDependencyValues:e})=>e.haveNumericalInitialConditions?{setValue:{numericalSolutionFDefinitions:[...Array(e.nDimensions).keys()].map((t=>({functionType:"ODESolution",nDimensions:e.nDimensions,t0:e.t0,x0s:e.x0s,chunkSize:e.chunkSize,tolerance:e.tolerance,numericalRHSfDefinitions:e.numericalRHSfDefinitions,maxIterations:e.maxIterations,component:t})))}}:{setValue:{numericalSolutionFDefinitions:Array(e.nDimensions).fill({})}}},e}}class Polyline extends GraphicalComponent{constructor(e){super(e),Object.assign(this.actions,{movePolyline:this.movePolyline.bind(this),finalizePolylinePosition:this.finalizePolylinePosition.bind(this),polylineClicked:this.polylineClicked.bind(this),mouseDownOnPolyline:this.mouseDownOnPolyline.bind(this)})}static componentType="polyline";static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.verticesDraggable={createComponentOfType:"boolean"},e.vertices={createComponentOfType:"_pointListComponent"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){let t=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(t&&(t+=" "),t+=e.selectedStyle.lineStyleWord),t&&(t+=" "),t+=e.selectedStyle.lineColorWord,{setValue:{styleDescription:t}}}},e.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({styleDescription:{dependencyType:"stateVariable",variableName:"styleDescription"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescriptionWithNoun:e.styleDescription+" polyline"}}}},e.verticesDraggable={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},hasEssential:!0,forRenderer:!0,returnDependencies:()=>({verticesDraggableAttr:{dependencyType:"attributeComponent",attributeName:"verticesDraggable",variableNames:["value"]},draggable:{dependencyType:"stateVariable",variableName:"draggable"}}),definition:({dependencyValues:e})=>e.verticesDraggableAttr?{setValue:{verticesDraggable:e.verticesDraggableAttr.stateValues.value}}:{useEssentialOrDefaultValue:{verticesDraggable:{defaultValue:e.draggable}}}},e.nVertices={public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies:()=>({vertices:{dependencyType:"attributeComponent",attributeName:"vertices",variableNames:["nPoints"]}}),definition:function({dependencyValues:e}){return null!==e.vertices?{setValue:{nVertices:e.vertices.stateValues.nPoints}}:{setValue:{nVertices:0}}}},e.nDimensions={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({vertices:{dependencyType:"attributeComponent",attributeName:"vertices",variableNames:["nDimensions"]}}),definition:function({dependencyValues:e}){if(null!==e.vertices){return{setValue:{nDimensions:e.vertices.stateValues.nDimensions},checkForActualChange:{nDimensions:!0}}}return{setValue:{nDimensions:2}}}},e.vertices={public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"vertexX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,nDimensions:2,entryPrefixes:["vertexX","vertex"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("vertexX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},getAllArrayKeys(e,t=!0,n){function r(e){if(1===e.length)return Array.from(Array(e[0]),((e,t)=>String(t)));{let n=e[0],a=r(e.slice(1)),i=[];for(let e=0;ee+","+t))):i.push(a.map((t=>e+","+t)));return i}}if(n){if(0!==n.length&&e){let t=[...e];return t[0]=n[0],r(t)}return[]}return e&&0!==e.length?r(e):[]},arrayVarNameFromPropIndex(e,t){if("vertices"===t)return 1===e.length?"vertex"+e[0]:`vertexX${e[0]}_${e[1]}`;if("vertex"===t.slice(0,6)){let n=Number(t.slice(6));if(Number.isInteger(n)&&n>0)return`vertexX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nVertices:{dependencyType:"stateVariable",variableName:"nVertices"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nVertices,e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let[e,r]=n.split(","),a=Number(e)+1+"_"+(Number(r)+1);t[n]={vertices:{dependencyType:"attributeComponent",attributeName:"vertices",variableNames:["pointX"+a]}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let[t,a]=r.split(","),i=Number(t)+1+"_"+(Number(a)+1),s=e[r].vertices;null!==s&&s.stateValues["pointX"+i]?n[r]=s.stateValues["pointX"+i]:n[r]=me$3.fromAst("_")}return{setValue:{vertices:n}}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n,initialChange:r,stateValues:a}){let i=[];for(let r in e.vertices){let[a,s]=r.split(","),o=Number(a)+1+"_"+(Number(s)+1);if(null===t[r].vertices||!t[r].vertices.stateValues["pointX"+o])return{success:!1};i.push({setDependency:n[r].vertices,desiredValue:e.vertices[r],variableIndex:0})}return{success:!0,instructions:i}}},e.numericalVertices={isArray:!0,entryPrefixes:["numericalVertex"],forRenderer:!0,returnArraySizeDependencies:()=>({nVertices:{dependencyType:"stateVariable",variableName:"nVertices"}}),returnArraySize:({dependencyValues:e})=>[e.nVertices],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={vertex:{dependencyType:"stateVariable",variableName:"vertex"+(Number(n)+1)}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].vertex.map((e=>e.evaluate_to_constant()));t.every((e=>Number.isFinite(e)))||(t=Array(t.length).fill(NaN)),n[r]=t}return{setValue:{numericalVertices:n}}}},e.nearestPoint={returnDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},numericalVertices:{dependencyType:"stateVariable",variableName:"numericalVertices"},nVertices:{dependencyType:"stateVariable",variableName:"nVertices"}}),definition({dependencyValues:e}){let t,n,r=e.nDimensions,a=e.nVertices,i=e.numericalVertices,s=[],o=i[0]?.[0],l=i[0]?.[1];for(let e=1;e=1?{x1:h,x2:f}:{x1:l+g*a*n,x2:u+g*y*o};let b=Math.pow((d-r.x1)/n,2)+Math.pow((m-r.x2)/o,2);b0&&(p.x3=0),p}}}}},e}async movePolyline({pointCoords:e,transient:t,sourceInformation:n,actionId:r}){if(1===Object.keys(e).length){if(!await this.stateValues.verticesDraggable)return await this.coreFunctions.resolveAction({actionId:r})}else if(!await this.stateValues.draggable)return await this.coreFunctions.resolveAction({actionId:r});let a={};for(let t in e)a[t+",0"]=me$3.fromAst(e[t][0]),a[t+",1"]=me$3.fromAst(e[t][1]);return t?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"vertices",value:a,sourceInformation:n}],transient:t,actionId:r}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"vertices",value:a,sourceInformation:n}],actionId:r,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{pointCoordinates:e}}})}async finalizePolylinePosition(){return await this.actions.movePolyline({pointCoords:await this.stateValues.numericalVertices,transient:!1})}async polylineClicked({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"click",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}async mouseDownOnPolyline({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"down",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}}class CobwebPolyline extends Polyline{static componentType="cobwebPolyline";static rendererType="cobwebPolyline";static createAttributesObject(){let e=super.createAttributesObject();return e.attractThreshold={createComponentOfType:"number",createStateVariable:"attractThreshold",defaultValue:.5,public:!0},e.nPoints={createComponentOfType:"number",createStateVariable:"nPoints",defaultValue:1,public:!0,clamp:[0,1/0],forRenderer:!0},e.variable={createComponentOfType:"variable",createStateVariable:"variable",defaultValue:me$3.fromAst("x"),public:!0,forRenderer:!0},e.nIterationsRequired={createComponentOfType:"number",createStateVariable:"nIterationsRequired",defaultValue:0,public:!0},e.initialPoint={createComponentOfType:"point"},e.function={createComponentOfType:"function"},e.lockToSolution={createComponentOfType:"boolean",createStateVariable:"lockToSolution",defaultValue:!1},e.defaultPoint={createComponentOfType:"point"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nDimensions.returnDependencies=()=>({}),e.nDimensions.definition=()=>({setValue:{nDimensions:2}}),e.initialPoint={isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"initialPointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},entryPrefixes:["initialPointX"],defaultValueByArrayKey:()=>me$3.fromAst(0),hasEssential:!0,returnArraySizeDependencies:()=>({}),returnArraySize:()=>[2],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={initialPointAttr:{dependencyType:"attributeComponent",attributeName:"initialPoint",variableNames:["x"+e]}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={},r={};for(let a of t){let t=Number(a)+1;e[a].initialPointAttr?n[a]=e[a].initialPointAttr.stateValues["x"+t]:r[a]=!0}let a={};return Object.keys(n).length>0&&(a.setValue={initialPoint:n}),Object.keys(r).length>0&&(a.useEssentialOrDefaultValue={initialPoint:r}),a},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n}){let r=[];for(let a in e.initialPoint)t[a].initialPointAttr&&t[a].initialPointAttr.stateValues["x"+(Number(a)+1)]?r.push({setDependency:n[a].initialPointAttr,desiredValue:e.initialPoint[a],variableIndex:0}):r.push({setEssentialValue:"initialPoint",value:{[a]:e.initialPoint[a]}});return{success:!0,instructions:r}}},e.f={additionalStateVariablesDefined:[{variableName:"fDefinition",forRenderer:!0}],returnDependencies:()=>({functionAttr:{dependencyType:"attributeComponent",attributeName:"function",variableNames:["numericalf","fDefinition"]}}),definition:({dependencyValues:e})=>e.functionAttr?{setValue:{f:e.functionAttr.stateValues.numericalf,fDefinition:e.functionAttr.stateValues.fDefinition}}:{setValue:{f:null,fDefinition:null}}},e.nVertices={isAlias:!0,targetVariableName:"nPoints"},e.nOriginalVertices={providePreviousValuesInDefinition:!0,returnDependencies:()=>({nVertices:{dependencyType:"stateVariable",variableName:"nVertices"}}),definition({dependencyValues:e,previousValues:t}){let n=e.nVertices;return t.nOriginalVertices>n&&(n=t.nOriginalVertices),{setValue:{nOriginalVertices:n}}}},e.originalVertices={isArray:!0,nDimensions:2,hasEssential:!0,entryPrefixes:["originalVertexX","originalVertex"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("originalVertexX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("originalVertices"===t)return 1===e.length?"originalVertex"+e[0]:`originalVertexX${e[0]}_${e[1]}`;if("originalVertex"===t.slice(0,14)){let n=Number(t.slice(14));if(Number.isInteger(n)&&n>0)return`originalVertexX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nOriginalVertices:{dependencyType:"stateVariable",variableName:"nOriginalVertices"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nOriginalVertices-1,e.nDimensions],returnArrayDependenciesByKey:()=>({globalDependencies:{graphAncestor:{dependencyType:"ancestor",componentType:"graph",variableNames:["xmin","xmax","ymin","ymax"]},defaultPoint:{dependencyType:"attributeComponent",attributeName:"defaultPoint",variableNames:["xs"]}}}),arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t}){let n={};for(let r of t){let t=r.split(",").map(Number);n[r]={get defaultValue(){if(e.defaultPoint){let n=e.defaultPoint.stateValues.xs;if(2===n.length&&t[1]<2)return n[t[1]]}if(e.graphAncestor){if(0===t[1]){let t=e.graphAncestor.stateValues.xmin,n=e.graphAncestor.stateValues.xmax;return me$3.fromAst((t+n)/2)}if(1===t[1]){let t=e.graphAncestor.stateValues.ymin,n=e.graphAncestor.stateValues.ymax;return me$3.fromAst((t+n)/2)}}return me$3.fromAst(0)}}}return{useEssentialOrDefaultValue:{originalVertices:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e}){let t=[];for(let n in e.originalVertices)t.push({setEssentialValue:"originalVertices",value:{[n]:e.originalVertices[n]}});return{success:!0,instructions:t}}},e.vertices.additionalStateVariablesDefined=[{variableName:"prelimCorrectVertices",entryPrefixes:["prelimCorrectVertexX","prelimCorrectVertex"],getArrayKeysFromVarName:function({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("prelimCorrectVertexX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}}}],e.vertices.basedOnArrayKeyStateVariables=!0,e.vertices.returnArrayDependenciesByKey=function({arrayKeys:e}){let t={};for(let n of e){let[e,r]=n.split(",");t[n]="0"===e?{initialPoint:{dependencyType:"stateVariable",variableName:"initialPointX"+(Number(r)+1)}}:{originalVertexX1:{dependencyType:"stateVariable",variableName:"originalVertexX"+e+"_1"},originalVertexX2:{dependencyType:"stateVariable",variableName:"originalVertexX"+e+"_2"},previousVertexX1:{dependencyType:"stateVariable",variableName:"vertexX"+e+"_1"},previousVertexX2:{dependencyType:"stateVariable",variableName:"vertexX"+e+"_2"}}}return{globalDependencies:{f:{dependencyType:"stateVariable",variableName:"f"},attractThreshold:{dependencyType:"stateVariable",variableName:"attractThreshold"},lockToSolution:{dependencyType:"stateVariable",variableName:"lockToSolution"}},dependenciesByKey:t}},e.vertices.arrayDefinitionByKey=function({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={},a={};for(let i of n){let[n,s]=i.split(",");if("0"===n)r[i]=t[i].initialPoint,a[i]=null;else{let s,o,l;try{s=[t[i].originalVertexX1.evaluate_to_constant(),t[i].originalVertexX2.evaluate_to_constant()],o=[t[i].previousVertexX1.evaluate_to_constant(),t[i].previousVertexX2.evaluate_to_constant()]}catch(e){r[n+",0"]=me$3.fromAst(0),r[n+",1"]=me$3.fromAst(0),a[n+",0"]=!1;continue}if(Number(n)%2==1){let t=e.f(o[0]);l=[o[0],t]}else l=[o[1],o[1]];Math.pow(s[0]-l[0],2)+Math.pow(s[1]-l[1],2)({nVertices:{dependencyType:"stateVariable",variableName:"nVertices"}}),returnArraySize:({dependencyValues:e})=>[e.nVertices-1],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={prelimCorrectVertex:{dependencyType:"stateVariable",variableName:"prelimCorrectVertexX"+(Number(n)+2)+"_1"}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t)n[r]=e[r].prelimCorrectVertex;return{setValue:{correctVertices:n}}}},e.fractionCorrectVertices={public:!0,shadowingInstructions:{createComponentOfType:"number"},additionalStateVariablesDefined:[{variableName:"nGradedVertices",public:!0,shadowingInstructions:{createComponentOfType:"number"}},{variableName:"nCorrectVertices",public:!0,shadowingInstructions:{createComponentOfType:"number"}}],returnDependencies:()=>({correctVertices:{dependencyType:"stateVariable",variableName:"correctVertices"}}),definition({dependencyValues:e}){let t,n,r=e.correctVertices.length;return 0===r?(t=0,n=0):(n=e.correctVertices.reduce(((e,t)=>e+t),0),t=n/r),{setValue:{fractionCorrectVertices:t,nGradedVertices:r,nCorrectVertices:n}}}},e.fractionCorrectVerticesAdjusted={public:!0,shadowingInstructions:{createComponentOfType:"number"},additionalStateVariablesDefined:[{variableName:"nGradedVerticesAdjusted",public:!0,shadowingInstructions:{createComponentOfType:"number"}}],returnDependencies:()=>({nCorrectVertices:{dependencyType:"stateVariable",variableName:"nCorrectVertices"},nGradedVertices:{dependencyType:"stateVariable",variableName:"nGradedVertices"},nIterationsRequired:{dependencyType:"stateVariable",variableName:"nIterationsRequired"}}),definition({dependencyValues:e}){let t=0;e.nIterationsRequired>0&&(t=2*e.nIterationsRequired-1);let n,r=Math.max(e.nGradedVertices,t);return n=0===r?0:e.nCorrectVertices/r,{setValue:{fractionCorrectVerticesAdjusted:n,nGradedVerticesAdjusted:r}}}},e.nIterateValues={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({nVertices:{dependencyType:"stateVariable",variableName:"nVertices"}}),definition:({dependencyValues:e})=>({setValue:{nIterateValues:Math.ceil((e.nVertices+1)/2)}})},e.iterateValues={isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"math"},entryPrefixes:["iterateValue"],returnArraySizeDependencies:()=>({nIterateValues:{dependencyType:"stateVariable",variableName:"nIterateValues"}}),returnArraySize:({dependencyValues:e})=>[e.nIterateValues],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]="0"===n?{iterateValue:{dependencyType:"stateVariable",variableName:"vertexX1_1"}}:{iterateValue:{dependencyType:"stateVariable",variableName:"vertexX"+2*Number(n)+"_2"}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t)n[r]=e[r].iterateValue;return{setValue:{iterateValues:n}}}},e}}class Point extends GraphicalComponent{constructor(e){super(e),Object.assign(this.actions,{movePoint:this.movePoint.bind(this),switchPoint:this.switchPoint.bind(this),pointClicked:this.pointClicked.bind(this),mouseDownOnPoint:this.mouseDownOnPoint.bind(this)})}static componentType="point";static primaryStateVariableForDefinition="coordsShadow";static stateVariableForAttributeValue="coords";static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.x={createComponentOfType:"math"},e.y={createComponentOfType:"math"},e.z={createComponentOfType:"math"},e.xs={createComponentOfType:"mathList"},e.coords={createComponentOfType:"coords"},e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.padZeros={createComponentOfType:"boolean",createStateVariable:"padZeros",defaultValue:!1,public:!0},e.labelPosition={createComponentOfType:"text",createStateVariable:"labelPosition",defaultValue:"upperright",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft","top","bottom","left","right"]},e.showCoordsWhenDragging={createComponentOfType:"boolean",createStateVariable:"showCoordsWhenDragging",defaultValue:!0,public:!0,forRenderer:!0},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e,componentInfoObjects:t}){let n=returnBreakStringsSugarFunction({childrenToComponentFunction:e=>({componentType:"math",children:e}),mustStripOffOuterParentheses:!0}),r=e.map((e=>typeof e)),a=r.indexOf("string"),i=r.lastIndexOf("string");if(-1===a){let n=t.componentIsSpecifiedType,r=e.filter((e=>!(n(e,"point")||n(e,"vector")||n(e,"constraints")||n(e,"label"))));if(1===r.length){let t=r[0],n=e.indexOf(t);return{success:!0,newAttributes:{coords:{component:{componentType:"math",children:r}}},newChildren:[...e.slice(0,n),...e.slice(n+1)]}}return{success:!1}}let s=[...e.slice(0,a),...e.slice(i+1)],o=n({matchedChildren:e=e.slice(a,i+1)});return o.success||1!==e.length?o.success?{success:!0,newAttributes:{xs:{component:{componentType:"mathList",children:o.newChildren,skipSugar:!0}}},newChildren:s}:{success:!1}:{success:!0,newAttributes:{xs:{component:{componentType:"mathList",children:[{componentType:"math",children:e}]}}},newChildren:s}}}),e}static returnChildGroups(){let e=super.returnChildGroups();return e.push({group:"points",componentTypes:["point"]},{group:"vectors",componentTypes:["vector"]},{group:"constraints",componentTypes:["constraints"]}),e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescription:e.selectedStyle.markerColorWord}}}},e.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescriptionWithNoun:e.selectedStyle.markerColorWord+" "+e.selectedStyle.markerStyleWord}}}},e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.displayDigitsAttr){let n=null===e.displayDigitsAttr||t.displayDigitsAttr,r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!n&&!r){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({}),definition:()=>({useEssentialOrDefaultValue:{coordsShadow:!0}}),inverseDefinition:async function({desiredStateVariableValues:e,stateValues:t,workspace:n}){return{success:!0,instructions:[{setEssentialValue:"coordsShadow",value:e.coordsShadow}]}}},e.nDimensions={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({coordsShadow:{dependencyType:"stateVariable",variableName:"coordsShadow"},coords:{dependencyType:"attributeComponent",attributeName:"coords",variableNames:["value"]},x:{dependencyType:"attributeComponent",attributeName:"x"},y:{dependencyType:"attributeComponent",attributeName:"y"},z:{dependencyType:"attributeComponent",attributeName:"z"},xs:{dependencyType:"attributeComponent",attributeName:"xs",variableNames:["nComponents"]},pointChild:{dependencyType:"child",childGroups:["points"],variableNames:["nDimensions"]},vectorChild:{dependencyType:"child",childGroups:["vectors"],variableNames:["nDimensions"]}}),definition:function({dependencyValues:e}){let t,n,r=!1;if(n=null!==e.z?3:null!==e.y?2:0,null!==e.coords?(r=!0,t=e.coords.stateValues.value):e.coordsShadow&&(r=!0,t=e.coordsShadow),r){let e=t.tree;return n=Array.isArray(e)&&vectorOperators.includes(e[0])?Math.max(e.length-1,n):Math.max(1,n),{setValue:{nDimensions:n},checkForActualChange:{nDimensions:!0}}}return null!==e.xs?{setValue:{nDimensions:Math.max(e.xs.stateValues.nComponents,n)}}:e.pointChild.length>0?{setValue:{nDimensions:Math.max(e.pointChild[0].stateValues.nDimensions,n)}}:e.vectorChild.length>0?{setValue:{nDimensions:Math.max(e.vectorChild[0].stateValues.nDimensions,n)}}:(0===n&&(n=2),{setValue:{nDimensions:n},checkForActualChange:{nDimensions:!0}})}},e.arrayVariableForConstraints={returnDependencies:()=>({}),definition:()=>({setValue:{arrayVariableForConstraints:"unconstrainedXs"}})},e.arrayEntryPrefixForConstraints={returnDependencies:()=>({}),definition:()=>({setValue:{arrayEntryPrefixForConstraints:"unconstrainedX"}})},e.nDimensionsForConstraints={isAlias:!0,targetVariableName:"nDimensions"},e.unconstrainedXs={isArray:!0,entryPrefixes:["unconstrainedX"],defaultValueByArrayKey:()=>me$3.fromAst(0),hasEssential:!0,returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={xs:{dependencyType:"attributeComponent",attributeName:"xs",variableNames:["math"+e]},pointChild:{dependencyType:"child",childGroups:["points"],variableNames:["x"+e]},vectorChild:{dependencyType:"child",childGroups:["vectors"],variableNames:["x"+e]}},"0"===n?t[n].component={dependencyType:"attributeComponent",attributeName:"x",variableNames:["value"]}:"1"===n?t[n].component={dependencyType:"attributeComponent",attributeName:"y",variableNames:["value"]}:"2"===n&&(t[n].component={dependencyType:"attributeComponent",attributeName:"z",variableNames:["value"]})}return{globalDependencies:{coordsShadow:{dependencyType:"stateVariable",variableName:"coordsShadow"},coords:{dependencyType:"attributeComponent",attributeName:"coords",variableNames:["value"]}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r,a={},i={},s=!1;if(null!==e.coords?(s=!0,r=e.coords.stateValues.value):e.coordsShadow&&(s=!0,r=e.coordsShadow),s){let e=r.tree;if(Array.isArray(e)&&vectorOperators.includes(e[0]))for(let t of n){let n=Number(t);(n>=0||n0)a[e]=r[0].stateValues["x"+n];else{let r=t[e].vectorChild;r.length>0&&(a[e]=r[0].stateValues["x"+n])}}}for(let e of n){let n=t[e].component;n?a[e]=n.stateValues.value.simplify():void 0===a[e]&&(i[e]=!0)}let o={};return Object.keys(a).length>0&&(o.setValue={unconstrainedXs:a}),Object.keys(i).length>0&&(o.useEssentialOrDefaultValue={unconstrainedXs:i}),o},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i,s,o=[],l=!1,u=!1;null!==t.coords?(l=!0,i="coords",s=Array(a[0]+1)):null!==t.coordsShadow&&(l=!0,i="coordsShadow",s=Array(a[0]+1));for(let t of Object.keys(e.unconstrainedXs).reverse()){let a=convertValueToMathExpression(e.unconstrainedXs[t]);if(null!==n[t].component)o.push({setDependency:r[t].component,desiredValue:a,childIndex:0,variableIndex:0});else if(l)s[Number(t)+1]=a.tree,u=!0;else{if(null!==n[t].xs)o.push({setDependency:r[t].xs,desiredValue:a,childIndex:0,variableIndex:0});else{if(n[t].pointChild.length>0)o.push({setDependency:r[t].pointChild,desiredValue:a,childIndex:0,variableIndex:0});else{n[t].vectorChild.length>0?o.push({setDependency:r[t].vectorChild,desiredValue:a,childIndex:0,variableIndex:0}):o.push({setEssentialValue:"unconstrainedXs",value:{[t]:a}})}}}}if(u){let e;1===a[0]?e=me$3.fromAst(s[1]):(s[0]="vector",e=me$3.fromAst(s));let t={setDependency:i,desiredValue:e};"coords"===i&&(t.childIndex=0,t.variableIndex=0),o.push(t)}return{success:!0,instructions:o}}},e.xs={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},isArray:!0,entryPrefixes:["x"],returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1,r={};r.unconstrainedX={dependencyType:"stateVariable",variableName:`unconstrainedX${e}`},r.constraintsChild={dependencyType:"child",childGroups:["constraints"],variableNames:[`constraintResult${e}`]},t[n]=r}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t)if(e[r].constraintsChild.length>0){let t=Number(r)+1;n[r]=convertValueToMathExpression(e[r].constraintsChild[0].stateValues["constraintResult"+t])}else n[r]=convertValueToMathExpression(e[r].unconstrainedX);return t.length>0?{setValue:{xs:n}}:{}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n,initialChange:r,stateValues:a}){if(r&&!await a.draggable)return{success:!1};let i=[];for(let r of Object.keys(e.xs).reverse())t[r]&&(t[r].constraintsChild.length>0?i.push({setDependency:n[r].constraintsChild,desiredValue:e.xs[r],childIndex:0,variableIndex:0}):i.push({setDependency:n[r].unconstrainedX,desiredValue:e.xs[r]}));return{success:!0,instructions:i}}},e.x={isAlias:!0,targetVariableName:"x1"},e.y={isAlias:!0,targetVariableName:"x2"},e.z={isAlias:!0,targetVariableName:"x3"},e.coords={public:!0,shadowingInstructions:{createComponentOfType:"coords",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},returnDependencies:()=>({xs:{dependencyType:"stateVariable",variableName:"xs"}}),definition:function({dependencyValues:e}){let t=[];for(let n of e.xs)n?t.push(n.tree):t.push("_");return t=t.length>1?["vector",...t]:1===t.length?t[0]:"_",{setValue:{coords:me$3.fromAst(t)}}},inverseDefinition:async function({desiredStateVariableValues:e,stateValues:t,initialChange:n}){if(n&&!await t.draggable)return{success:!1};let r=[],a={},i=e.coords.tree;if(Array.isArray(i)&&vectorOperators.includes(i[0]))for(let t=0;t({coords:{dependencyType:"stateVariable",variableName:"coords"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"}}),definition:function({dependencyValues:e,usedDefault:t}){let n={};return e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(n.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(n.padToDigits=e.displayDigits)),{setValue:{latex:roundForDisplay({value:e.coords,dependencyValues:e,usedDefault:t}).toLatex(n)}}}},e.value={isAlias:!0,targetVariableName:"coords"},e.constraintUsed={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({constraintsChild:{dependencyType:"child",childGroups:["constraints"],variableNames:["constraintUsed"]}}),definition:function({dependencyValues:e}){return 0===e.constraintsChild.length?{setValue:{constraintUsed:!1}}:{setValue:{constraintUsed:e.constraintsChild[0].stateValues.constraintUsed}}}},e.numericalXs={isArray:!0,entryPrefixes:["numericalX"],forRenderer:!0,returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={x:{dependencyType:"stateVariable",variableName:`x${e}`}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].x;t?(t=e[r].x.evaluate_to_constant(),Number.isFinite(t)?n[r]=t:n[r]=NaN):n[r]=NaN}return{setValue:{numericalXs:n}}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,initialChange:n,stateValues:r}){if(n&&!await r.draggable)return{success:!1};let a=[];for(let n in e.numericalXs)dependencyValuesByKey[n]&&a.push({setDependency:t[n].xs,desiredValue:e.numericalXs[n]});return{success:!0,instructions:a}}},e.nearestPoint={returnDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},numericalXs:{dependencyType:"stateVariable",variableName:"numericalXs"}}),definition:({dependencyValues:e})=>({setValue:{nearestPoint:function(){let t={};for(let n=1;n<=e.nDimensions;n++){let r=e.numericalXs[n-1];if(!Number.isFinite(r))return{};t["x"+n]=r}return t}}})},e}static adapters=[{stateVariable:"coords",stateVariablesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]}];async movePoint({x:e,y:t,z:n,transient:r,actionId:a}){let i={};return void 0!==e&&(i[0]=me$3.fromAst(e)),void 0!==t&&(i[1]=me$3.fromAst(t)),void 0!==n&&(i[2]=me$3.fromAst(n)),r?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"xs",value:i}],transient:r,actionId:a}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"xs",value:i}],actionId:a,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{x:e,y:t,z:n}}})}switchPoint(){}async pointClicked({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"click",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}async mouseDownOnPoint({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"down",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}}class EquilibriumPoint extends Point{static componentType="equilibriumPoint";static rendererType="point";static createAttributesObject(){let e=super.createAttributesObject();return e.stable={createComponentOfType:"boolean",createStateVariable:"stable",defaultValue:!0,public:!0},e.switchable={createComponentOfType:"boolean",createStateVariable:"switchable",defaultValue:!1,public:!0,forRenderer:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.open={forRenderer:!0,returnDependencies:()=>({stable:{dependencyType:"stateVariable",variableName:"stable"}}),definition:({dependencyValues:e})=>({setValue:{open:!e.stable}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setDependency:"stable",desiredValue:!e.open}]})},e}async switchPoint({actionId:e}){if(await this.stateValues.switchable)return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"stable",value:!this.stateValues.stable}],actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{stable:!this.stateValues.stable}}});this.coreFunctions.resolveAction({actionId:e})}}class Line extends GraphicalComponent{constructor(e){super(e),Object.assign(this.actions,{moveLine:this.moveLine.bind(this),switchLine:this.switchLine.bind(this),lineClicked:this.lineClicked.bind(this),mouseDownOnLine:this.mouseDownOnLine.bind(this)})}static componentType="line";static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.equation={createComponentOfType:"math"},e.through={createComponentOfType:"_pointListComponent"},e.slope={createComponentOfType:"number"},e.variables={createComponentOfType:"variables"},e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.padZeros={createComponentOfType:"boolean",createStateVariable:"padZeros",defaultValue:!1,public:!0},e.labelPosition={createComponentOfType:"text",createStateVariable:"labelPosition",defaultValue:"upperright",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft"]},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e,componentInfoObjects:t}){if(0===e.length)return{success:!1};let n=e.map((e=>t.componentIsSpecifiedType(e,"label"))),r=[],a=[];if(0===n.filter((e=>e)).length)r=e;else{if(n[0]){let t=n.indexOf(!1);-1!==t&&(a.push(...e.slice(0,t)),e=e.slice(t),n=n.slice(t))}let t=n.indexOf(!0);-1===t?r=e:(r=e.slice(0,t),a.push(...e.slice(t)))}return 0===r.length?{success:!1}:{success:!0,newAttributes:{equation:{component:{componentType:"math",children:r}}},newChildren:a}}}),e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){let t=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(t&&(t+=" "),t+=e.selectedStyle.lineStyleWord),t&&(t+=" "),t+=e.selectedStyle.lineColorWord,{setValue:{styleDescription:t}}}},e.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({styleDescription:{dependencyType:"stateVariable",variableName:"styleDescription"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescriptionWithNoun:e.styleDescription+" line"}}}},e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){let n=null===e.displayDigitsAttr||t.displayDigitsAttr,r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!n&&!r){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({throughAttr:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["nPoints"]}}),definition:function({dependencyValues:e}){return null===e.throughAttr?{setValue:{nPointsPrescribed:0}}:{setValue:{nPointsPrescribed:e.throughAttr.stateValues.nPoints}}}},e.basedOnSlope={returnDependencies:()=>({slopeAttr:{dependencyType:"attributeComponent",attributeName:"slope"},nPointsPrescribed:{dependencyType:"stateVariable",variableName:"nPointsPrescribed"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),definition:({dependencyValues:e})=>({setValue:{basedOnSlope:e.nPointsPrescribed<2&&null!==e.slopeAttr&&2===e.nDimensions}})},e.dForSlope={defaultValue:1,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{dForSlope:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"dForSlope",value:e.dForSlope}]})},e.variables={isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"variable"},entryPrefixes:["var"],returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey:()=>({globalDependencies:{variables:{dependencyType:"attributeComponent",attributeName:"variables",variableNames:["variables"]}}}),arrayDefinitionByKey({globalDependencyValues:e,arraySize:t}){let n=[];return null!==e.variables&&(n=e.variables.stateValues.variables),{setValue:{variables:returnNVariables(t[0],n)}}}},e.equationIdentity={returnDependencies:()=>({equation:{dependencyType:"attributeComponent",attributeName:"equation"}}),definition:function({dependencyValues:e}){return null!==e.equation?{setValue:{equationIdentity:e.equation}}:{setValue:{equationIdentity:null}}}},e.essentialPoints={isArray:!0,nDimensions:"2",hasEssential:!0,entryPrefixes:["essentialPointX","essentialPoint"],set:convertValueToMathExpression,defaultValueByArrayKey:e=>me$3.fromAst("0,0"===e?1:0),getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("essentialPointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[2,e.nDimensions],returnArrayDependenciesByKey:()=>({}),arrayDefinitionByKey({arrayKeys:e}){let t={};for(let n of e)t[n]=!0;return{useEssentialOrDefaultValue:{essentialPoints:t}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e}){let t=[];for(let n in e.essentialPoints)t.push({setEssentialValue:"essentialPoints",value:{[n]:convertValueToMathExpression(e.essentialPoints[n])}});return{success:!0,instructions:t}}},e.points={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"],returnWrappingComponents:e=>"pointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,nDimensions:2,entryPrefixes:["pointX","point"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("pointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("points"===t)return 1===e.length?"point"+e[0]:`pointX${e[0]}_${e[1]}`;if("point"===t.slice(0,5)){let n=Number(t.slice(5));if(Number.isInteger(n)&&n>0)return`pointX${n}_${e[0]}`}return null},stateVariablesDeterminingDependencies:["equationIdentity","nPointsPrescribed","basedOnSlope"],returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[2,e.nDimensions],returnArrayDependenciesByKey({stateValues:e,arrayKeys:t}){if(null===e.equationIdentity){let n={};for(let r of t){let[t,a]=r.split(","),i=Number(t)+1+"_"+(Number(a)+1);n[r]={through:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["pointX"+i]}},e.basedOnSlope?("1"===t&&(1===e.nPointsPrescribed&&n[r].through.variableNames.push("pointX1_"+(Number(a)+1)),n[r].dForSlope={dependencyType:"stateVariable",variableName:"dForSlope"},n[r].slopeAttr={dependencyType:"attributeComponent",attributeName:"slope",variableNames:["value"]}),0===e.nPointsPrescribed&&(n[r].essentialPoint={dependencyType:"stateVariable",variableName:"essentialPointX2_"+(Number(a)+1)})):n[r].essentialPoint={dependencyType:"stateVariable",variableName:"essentialPointX"+i}}return{dependenciesByKey:n,globalDependencies:{nPointsPrescribed:{dependencyType:"stateVariable",variableName:"nPointsPrescribed"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},basedOnSlope:{dependencyType:"stateVariable",variableName:"basedOnSlope"}}}}return{globalDependencies:{coeff0:{dependencyType:"stateVariable",variableName:"coeff0"},coeffvar1:{dependencyType:"stateVariable",variableName:"coeffvar1"},coeffvar2:{dependencyType:"stateVariable",variableName:"coeffvar2"},variables:{dependencyType:"stateVariable",variableName:"variables"},lastPointsFromInverting:{dependencyType:"stateVariable",variableName:"lastPointsFromInverting"}}}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n,arraySize:r,componentName:a}){if("coeff0"in e){let t=calculatePointsFromCoeffs(e);if(t.success)return{setValue:{points:t.points}};{let e={};for(let t=0;te.toString()))];for(let e=0;e({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>Number.isNaN(e.nDimensions)?[0]:[2],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={point:{dependencyType:"stateVariable",variableName:"point"+(Number(n)+1)}};return{globalDependencies:{nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n,componentName:r}){if(Number.isNaN(e.nDimensions))return{};let a={};for(let r of n){let n=t[r].point;Array.isArray(n)||(n=[n]);let i=[];for(let t=0;t({coeff0:{dependencyType:"stateVariable",variableName:"coeff0"},coeffvar1:{dependencyType:"stateVariable",variableName:"coeffvar1"},coeffvar2:{dependencyType:"stateVariable",variableName:"coeffvar2"}}),definition:function({dependencyValues:e}){let t=e.coeff0.evaluate_to_constant();Number.isFinite(t)||(t=NaN);let n=e.coeffvar1.evaluate_to_constant();Number.isFinite(n)||(n=NaN);let r=e.coeffvar2.evaluate_to_constant();return Number.isFinite(r)||(r=NaN),{setValue:{numericalCoeff0:t,numericalCoeffvar1:n,numericalCoeffvar2:r}}}},e.slope={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},returnDependencies:()=>({coeffvar1:{dependencyType:"stateVariable",variableName:"coeffvar1"},coeffvar2:{dependencyType:"stateVariable",variableName:"coeffvar2"}}),definition:function({dependencyValues:e}){return{setValue:{slope:me$3.fromAst(["-",["/","a","b"]]).substitute({a:e.coeffvar1,b:e.coeffvar2}).simplify()}}}},e.xintercept={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},returnDependencies:()=>({coeff0:{dependencyType:"stateVariable",variableName:"coeff0"},coeffvar1:{dependencyType:"stateVariable",variableName:"coeffvar1"}}),definition:({dependencyValues:e})=>({setValue:{xintercept:me$3.fromAst(["-",["/","a","b"]]).substitute({a:e.coeff0,b:e.coeffvar1}).simplify()}})},e.yintercept={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},returnDependencies:()=>({coeff0:{dependencyType:"stateVariable",variableName:"coeff0"},coeffvar2:{dependencyType:"stateVariable",variableName:"coeffvar2"}}),definition:({dependencyValues:e})=>({setValue:{yintercept:me$3.fromAst(["-",["/","a","b"]]).substitute({a:e.coeff0,b:e.coeffvar2}).simplify()}})},e.lastPointsFromInverting={defaultValue:null,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{lastPointsFromInverting:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"lastPointsFromInverting",value:e.lastPointsFromInverting}]})},e.latex={forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({equation:{dependencyType:"stateVariable",variableName:"equation"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"}}),definition:function({dependencyValues:e,usedDefault:t}){let n={};return e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(n.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(n.padToDigits=e.displayDigits)),{setValue:{latex:roundForDisplay({value:e.equation,dependencyValues:e,usedDefault:t}).toLatex(n)}}}},e.nearestPoint={returnDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},numericalCoeff0:{dependencyType:"stateVariable",variableName:"numericalCoeff0"},numericalCoeffvar1:{dependencyType:"stateVariable",variableName:"numericalCoeffvar1"},numericalCoeffvar2:{dependencyType:"stateVariable",variableName:"numericalCoeffvar2"}}),definition({dependencyValues:e}){let t=e.numericalCoeffvar1,n=e.numericalCoeffvar2,r=e.numericalCoeff0,a=Number.isFinite(t)&&Number.isFinite(n)&&Number.isFinite(r),i=2!==e.nDimensions||!a||0===t&&0===n;return{setValue:{nearestPoint:function({variables:e,scales:a=[1,1]}){if(i)return{};let s=a[0],o=a[1],l=t*s,u=n*o,c=l*l+u*u,p=e.x1?.evaluate_to_constant(),d=e.x2?.evaluate_to_constant();if(!Number.isFinite(p)||!Number.isFinite(d))return{};let m=p/s,h=d/o,f={};return f.x1=(u*(u*m-l*h)-l*r)*s/c,f.x2=(l*(-u*m+l*h)-u*r)*o/c,void 0!==e.x3&&(f.x3=0),f}}}}},e}static adapters=[{stateVariable:"equation",stateVariablesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]}];async moveLine({point1coords:e,point2coords:t,transient:n,actionId:r}){let a={"0,0":me$3.fromAst(e[0]),"0,1":me$3.fromAst(e[1])};return await this.stateValues.basedOnSlope||(a["1,0"]=me$3.fromAst(t[0]),a["1,1"]=me$3.fromAst(t[1])),n?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"points",value:a}],transient:!0,actionId:r}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"points",value:a}],actionId:r,event:{verb:"interacted",object:{componentId:this.componentName},result:{point1:e,point2:t}}})}switchLine(){}async lineClicked({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"click",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}async mouseDownOnLine({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"down",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}}function calculateCoeffsFromEquation({equation:e,variables:t}){let n=t[0],r=t[1],a=n.toString(),i=r.toString();if(e=e.expand().simplify(),!Array.isArray(e.tree)||"="!==e.tree[0]||3!==e.tree.length)return{success:!1};let s=me$3.fromAst(["+",e.tree[2],["-",e.tree[1]]]).expand().simplify(),o=[];o=Array.isArray(s.tree)&&"+"===s.tree[0]?s.tree.slice(1):[s.tree];let l=me$3.fromAst(0),u=me$3.fromAst(0),c=me$3.fromAst(0);for(let e of o){let t=p(e);if(!t.success)return{success:!1};l=l.add(t.coeffvar1),u=u.add(t.coeffvar2),c=c.add(t.coeff0)}return l=l.simplify(),u=u.simplify(),c=c.simplify(),{success:!0,coeff0:c,coeffvar1:l,coeffvar2:u};function p(e){let t=0,s=0,o=0;if("string"==typeof e)e===a?t=1:e===i?s=1:o=e;else if("number"==typeof e)o=e;else{if(!Array.isArray(e))return console.warn("Invalid format for equation of line in variables "+n+" and "+r),{success:!1};{let a=e[0],i=e.slice(1);if("-"===a){let e=p(i[0]);if(!e.success)return{success:!1};t=["-",e.coeffvar1.tree],s=["-",e.coeffvar2.tree],o=["-",e.coeff0.tree]}else{if("+"===a)return console.warn("Invalid format for equation of line in variables "+n+" and "+r),{success:!1};if("*"===a){let a=-1,l=-1;for(let e=0;e({stable:{dependencyType:"stateVariable",variableName:"stable"}}),definition:({dependencyValues:e})=>({setValue:{dashed:!e.stable}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setDependency:"stable",desiredValue:!e.dashed}]})},e}async switchLine({actionId:e}){if(await this.stateValues.switchable)return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"stable",value:!this.stateValues.stable}],actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{stable:!this.stateValues.stable}}});this.coreFunctions.resolveAction({actionId:e})}}class Curve extends GraphicalComponent{constructor(e){super(e),Object.assign(this.actions,{moveControlVector:this.moveControlVector.bind(this),moveThroughPoint:this.moveThroughPoint.bind(this),changeVectorControlDirection:this.changeVectorControlDirection.bind(this),switchCurve:this.switchCurve.bind(this),curveClicked:this.curveClicked.bind(this),mouseDownOnCurve:this.mouseDownOnCurve.bind(this)})}static componentType="curve";static rendererType="curve";static primaryStateVariableForDefinition="fShadow";static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.labelPosition={createComponentOfType:"text",createStateVariable:"labelPosition",defaultValue:"upperright",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft","top","bottom","left","right"]},e.flipFunction={createComponentOfType:"boolean",createStateVariable:"flipFunction",defaultValue:!1,public:!0,forRenderer:!0},e.nDiscretizationPoints={createComponentOfType:"number",createStateVariable:"nDiscretizationPoints",defaultValue:1e3,public:!0},e.periodic={createComponentOfType:"boolean",createStateVariable:"periodic",defaultValue:!1,public:!0},e.splineTension={createComponentOfType:"number",createStateVariable:"splineTension",defaultValue:.8,clamp:[0,1],public:!0},e.extrapolateBackward={createComponentOfType:"boolean",createStateVariable:"extrapolateBackward",defaultValue:!1,public:!0,forRenderer:!0},e.extrapolateForward={createComponentOfType:"boolean",createStateVariable:"extrapolateForward",defaultValue:!1,public:!0,forRenderer:!0},e.splineForm={createComponentOfType:"text",createStateVariable:"splineForm",defaultValue:"centripetal",public:!0,toLowerCase:!0,validValues:["centripetal","uniform"]},e.variable={createComponentOfType:"variable",createStateVariable:"variableForChild",defaultValue:me$3.fromAst("x")},e.through={createComponentOfType:"_pointListComponent"},e.parMin={createComponentOfType:"math"},e.parMax={createComponentOfType:"math"},e.nearestPointAsCurve={createComponentOfType:"boolean",createStateVariable:"nearestPointAsCurvePrelim",defaultValue:!1},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e,componentInfoObjects:t}){let n=e=>t.componentIsSpecifiedType(e,"label");if(0===e.length||!e.every((e=>"string"==typeof e||e.doenetAttributes?.createdFromMacro||n(e))))return{success:!1};let r=e.map(n),a=[],i=[],s=[];if(0===r.filter((e=>e)).length)a=e;else{if(r[0]){let t=r.indexOf(!1);-1!==t&&(i=e.slice(0,t),e=e.slice(t),r=r.slice(t))}let t=r.indexOf(!0);-1===t?a=e:(a=e.slice(0,t),s=e.slice(t))}if(0===a.length)return{success:!1};let o=returnBreakStringsSugarFunction({childrenToComponentFunction:e=>({componentType:"function",children:e}),mustStripOffOuterParentheses:!0}),l=o({matchedChildren:a}),u=[];return u=l.success?l.newChildren:[{componentType:"function",children:a}],{success:!0,newChildren:[...i,...u,...s]}}}),e}static returnChildGroups(){let e=super.returnChildGroups();return e.push({group:"functions",componentTypes:["function"]},{group:"bezierControls",componentTypes:["bezierControls"]}),e}static returnStateVariableDefinitions({numerics:e}){let t=super.returnStateVariableDefinitions({numerics:e});return t.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){let t=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(t&&(t+=" "),t+=e.selectedStyle.lineStyleWord),t&&(t+=" "),t+=e.selectedStyle.lineColorWord,{setValue:{styleDescription:t}}}},t.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({styleDescription:{dependencyType:"stateVariable",variableName:"styleDescription"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescriptionWithNoun:e.styleDescription+" curve"}}}},t.curveType={forRenderer:!0,returnDependencies:()=>({functionChildren:{dependencyType:"child",childGroups:["functions"]},through:{dependencyType:"attributeComponent",attributeName:"through"}}),definition({dependencyValues:e}){let t="function";return null!==e.through?t="bezier":e.functionChildren.length>1&&(t="parameterization"),{setValue:{curveType:t}}}},t.fShadow={defaultValue:null,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{fShadow:!0}})},t.graphXmin={forRenderer:!0,additionalStateVariablesDefined:[{variableName:"graphXmax",forRenderer:!0},{variableName:"graphYmin",forRenderer:!0},{variableName:"graphYmax",forRenderer:!0}],returnDependencies:()=>({graphAncestor:{dependencyType:"ancestor",componentType:"graph",variableNames:["xmin","xmax","ymin","ymax"]}}),definition:({dependencyValues:e})=>e.graphAncestor?{setValue:{graphXmin:e.graphAncestor.stateValues.xmin,graphXmax:e.graphAncestor.stateValues.xmax,graphYmin:e.graphAncestor.stateValues.ymin,graphYmax:e.graphAncestor.stateValues.ymax}}:{setValue:{graphXmin:null,graphXmax:null,graphYmin:null,graphYmax:null}}},t.parMax={public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies:()=>({curveType:{dependencyType:"stateVariable",variableName:"curveType"},parMaxAttr:{dependencyType:"attributeComponent",attributeName:"parMax",variableNames:["value"]},nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"},extrapolateForward:{dependencyType:"stateVariable",variableName:"extrapolateForward"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["domain"]},adapterSourceDomain:{dependencyType:"adapterSourceStateVariable",variableName:"domain"},graphXmin:{dependencyType:"stateVariable",variableName:"graphXmin"},graphXmax:{dependencyType:"stateVariable",variableName:"graphXmax"},graphYmin:{dependencyType:"stateVariable",variableName:"graphYmin"},graphYmax:{dependencyType:"stateVariable",variableName:"graphYmax"},flipFunction:{dependencyType:"stateVariable",variableName:"flipFunction"}}),definition:function({dependencyValues:e}){let t;if("bezier"===e.curveType)t=e.nThroughPoints-1,e.extrapolateForward&&(t*=2);else if(null!==e.parMaxAttr)t=e.parMaxAttr.stateValues.value.evaluate_to_constant(),Number.isFinite(t)||(t=NaN);else if("function"===e.curveType){let n,r,a=null;if(a=1===e.functionChild.length?e.functionChild[0].stateValues.domain:e.adapterSourceDomain,null!==a){a=a[0];try{t=me$3.fromAst(a.tree[1][2]).evaluate_to_constant(),Number.isFinite(t)||t===1/0||(t=NaN)}catch(e){}}e.flipFunction?(r=e.graphYmax,n=e.graphYmin):(r=e.graphXmax,n=e.graphXmin),null!==r&&null!==n&&(t=void 0===t?r+.1*(r-n):Math.min(t,r+.1*(r-n))),void 0===t&&(t=1/0)}else t=10;return{setValue:{parMax:t}}}},t.parMin={forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({curveType:{dependencyType:"stateVariable",variableName:"curveType"},parMinAttr:{dependencyType:"attributeComponent",attributeName:"parMin",variableNames:["value"]},nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"},extrapolateBackward:{dependencyType:"stateVariable",variableName:"extrapolateBackward"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["domain"]},adapterSourceDomain:{dependencyType:"adapterSourceStateVariable",variableName:"domain"},graphXmin:{dependencyType:"stateVariable",variableName:"graphXmin"},graphXmax:{dependencyType:"stateVariable",variableName:"graphXmax"},graphYmin:{dependencyType:"stateVariable",variableName:"graphYmin"},graphYmax:{dependencyType:"stateVariable",variableName:"graphYmax"},flipFunction:{dependencyType:"stateVariable",variableName:"flipFunction"}}),definition:function({dependencyValues:e}){let t;if("bezier"===e.curveType)t=0,e.extrapolateBackward&&(t=-(e.nThroughPoints-1));else if(null!==e.parMinAttr)t=e.parMinAttr.stateValues.value.evaluate_to_constant(),Number.isFinite(t)||(t=NaN);else if("function"===e.curveType){let n,r,a=null;if(a=1===e.functionChild.length?e.functionChild[0].stateValues.domain:e.adapterSourceDomain,null!==a){a=a[0];try{t=me$3.fromAst(a.tree[1][1]).evaluate_to_constant(),Number.isFinite(t)||t===-1/0||(t=NaN)}catch(e){}}e.flipFunction?(r=e.graphYmax,n=e.graphYmin):(r=e.graphXmax,n=e.graphXmin),null!==r&&null!==n&&(t=void 0===t?n+.1*(n-r):Math.max(t,n+.1*(n-r))),void 0===t&&(t=-1/0)}else t=-10;return{setValue:{parMin:t}}}},t.nThroughPoints={returnDependencies:()=>({through:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["nPoints"]}}),definition({dependencyValues:e}){let t=0;return null!==e.through&&(t=e.through.stateValues.nPoints),{setValue:{nThroughPoints:t}}}},t.nDimensions={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({through:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["nDimensions"]}}),definition:function({dependencyValues:e}){if(null!==e.through){return{setValue:{nDimensions:e.through.stateValues.nDimensions},checkForActualChange:{nDimensions:!0}}}return{setValue:{nDimensions:2}}}},t.throughPoints={public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"throughPointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,nDimensions:2,entryPrefixes:["throughPointX","throughPoint"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("throughPointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("throughPoints"===t)return 1===e.length?"throughPoint"+e[0]:`throughPointX${e[0]}_${e[1]}`;if("throughPoint"===t.slice(0,12)){let n=Number(t.slice(12));if(Number.isInteger(n)&&n>0)return`throughPointX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints,e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let[e,r]=n.split(","),a=Number(e)+1+"_"+(Number(r)+1);t[n]={through:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["pointX"+a]}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let[t,a]=r.split(","),i=Number(t)+1+"_"+(Number(a)+1),s=e[r].through;null!==s&&s.stateValues["pointX"+i]?n[r]=s.stateValues["pointX"+i]:n[r]=me$3.fromAst(0)}return{setValue:{throughPoints:n}}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n,initialChange:r,stateValues:a}){if(r&&!await a.draggable)return{success:!1};let i=[];for(let r in e.throughPoints){let[a,s]=r.split(","),o=Number(a)+1+"_"+(Number(s)+1);if(null===t[r].through||!t[r].through.stateValues["pointX"+o])return{success:!1};i.push({setDependency:n[r].through,desiredValue:e.throughPoints[r],childIndex:0,variableIndex:0})}return{success:!0,instructions:i}}},t.numericalThroughPoints={isArray:!0,entryPrefixes:["numericalThroughPoint"],forRenderer:!0,returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={throughPoint:{dependencyType:"stateVariable",variableName:"throughPoint"+(Number(n)+1)}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].throughPoint.map((e=>e.evaluate_to_constant()));t.every((e=>Number.isFinite(e)))||(t=Array(t.length).fill(NaN)),n[r]=t}return{setValue:{numericalThroughPoints:n}}}},t.haveBezierControls={forRenderer:!0,returnDependencies:()=>({controlChild:{dependencyType:"child",childGroups:["bezierControls"]}}),definition:({dependencyValues:e})=>({setValue:{haveBezierControls:e.controlChild.length>0}})},t.bezierControlsAlwaysVisible={forRenderer:!0,returnDependencies:()=>({controlChild:{dependencyType:"child",childGroups:["bezierControls"],variableNames:["alwaysVisible"]}}),definition:({dependencyValues:e})=>({setValue:{bezierControlsAlwaysVisible:e.controlChild.length>0&&e.controlChild[0].stateValues.alwaysVisible}})},t.vectorControlDirections={public:!0,shadowingInstructions:{createComponentOfType:"text"},isArray:!0,entryPrefixes:["vectorControlDirection"],forRenderer:!0,returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={controlChild:{dependencyType:"child",childGroups:["bezierControls"],variableNames:["direction"+(Number(n)+1)]}};return{dependenciesByKey:t,globalDependencies:{haveBezierControls:{dependencyType:"stateVariable",variableName:"haveBezierControls"}}}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].controlChild;t&&t.length>0?n[r]=t[0].stateValues["direction"+(Number(r)+1)]:n[r]="none"}return{setValue:{vectorControlDirections:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,dependencyValuesByKey:n,globalDependencyValues:r}){if(!r.haveBezierControls)return{success:!1};let a=[];for(let r in e.vectorControlDirections){let i=n[r].controlChild;i&&i.length>0&&a.push({setDependency:t[r].controlChild,desiredValue:e.vectorControlDirections[r],childIndex:0,variableIndex:0})}return{success:!0,instructions:a}}},t.hiddenControls={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},isArray:!0,entryPrefixes:["hiddenControl"],forRenderer:!0,returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={controlChild:{dependencyType:"child",childGroups:["bezierControls"],variableNames:["hiddenControl"+(Number(n)+1)]}};return{dependenciesByKey:t,globalDependencies:{haveBezierControls:{dependencyType:"stateVariable",variableName:"haveBezierControls"}}}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].controlChild;t&&t.length>0?n[r]=t[0].stateValues["hiddenControl"+(Number(r)+1)]:n[r]=!1}return{setValue:{hiddenControls:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,dependencyValuesByKey:n,globalDependencyValues:r}){if(!r.haveBezierControls)return{success:!1};let a=[];for(let r in e.hiddenControls){let i=n[r].controlChild;i&&i.length>0&&a.push({setDependency:t[r].controlChild,desiredValue:e.hiddenControls[r],childIndex:0,variableIndex:0})}return{success:!0,instructions:a}}},t.controlVectors={isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"controlVectorX"===e?[]:[["vector",{componentType:"mathList",isAttribute:"xs"}]]},entryPrefixes:["controlVectorX","controlVector"],nDimensions:3,stateVariablesDeterminingDependencies:["vectorControlDirections","nThroughPoints"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("controlVectorX"===e){let e=t.split("_").map((e=>Number(e)-1));return 3===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>eNumber(e)-1));return 2===e.length&&e.every((e=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>eString(e)+","+n)):[]:[String(e)+",0"]:[]}},returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints,2,e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=r.split(",").map((e=>Number(e))),a=e.map((e=>e+1)),i=a.join("_");n[r]={direction:{dependencyType:"stateVariable",variableName:"vectorControlDirection"+a[0]},controlChild:{dependencyType:"child",childGroups:["bezierControls"],variableNames:["control"+i]}};let s=e[0],o=t.vectorControlDirections[s],l=[];"none"===o?l=[s-1,s,s+1]:"previous"===o?l=[s,s+1]:"next"===o&&(l=[s-1,s]);for(let e of l)e>=0&&eNumber(e))),s=r.map((e=>e+1)),o=s.join("_"),l=r[0],u=r[1],c=n[i].direction;if("none"===c){let r,s,o=n[i]["throughPoint"+(l+1)];l>0&&(r=n[i]["throughPoint"+l]),lNumber(e))),s=i.map((e=>e+1)),o=s.join("_"),l=n[r].controlChild;if(l.length>0){l[0].stateValues["control"+o]&&a.push({setDependency:t[r].controlChild,desiredValue:e.controlVectors[r],childIndex:0,variableIndex:0})}}return{success:!0,instructions:a}}},t.numericalControlVectors={isArray:!0,entryPrefixes:["numericalControlVector"],forRenderer:!0,nDimensions:2,returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints,2],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=n.split(",").map((e=>Number(e))),r=e.map((e=>e+1)),a=r.join("_");t[n]={controlVector:{dependencyType:"stateVariable",variableName:"controlVector"+a}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].controlVector.map((e=>e.tree));n[r]=t}return{setValue:{numericalControlVectors:n}}}},t.controlPoints={isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"controlPointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},entryPrefixes:["controlPointX","controlPoint"],nDimensions:3,getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("controlPointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 3===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>eNumber(e)-1));return 2===e.length&&e.every((e=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>eString(e)+","+n)):[]:[String(e)+",0"]:[]}},returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints,2,e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=n.split(",").map((e=>Number(e))),r=e.map((e=>e+1)),a=r.join("_");t[n]={throughPointX:{dependencyType:"stateVariable",variableName:"throughPointX"+r[0]+"_"+r[2]},controlVectorX:{dependencyType:"stateVariable",variableName:"controlVectorX"+a}}}return{globalDependencies:{haveBezierControls:{dependencyType:"stateVariable",variableName:"haveBezierControls"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};for(let a of n)if(2!==e.nDimensions)r[a]=me$3.fromAst(NaN);else{let e=t[a].controlVectorX;if(e){let n=t[a].throughPointX.evaluate_to_constant();Number.isFinite(n)||(n=NaN),r[a]=me$3.fromAst(n+e.tree)}else r[a]=null}return{setValue:{controlPoints:r}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,dependencyValuesByKey:n,globalDependencyValues:r}){if(!r.haveBezierControls||2!==r.nDimensions)return{success:!1};let a=[];for(let r in e.controlPoints){if(n[r].controlVectorX){let i=n[r].throughPointX,s=e.controlPoints[r];s.tree&&(s=s.tree);let o=me$3.fromAst(["+",s,["-",i.tree]]);a.push({setDependency:t[r].controlVectorX,desiredValue:o})}}return{success:!0,instructions:a}}},t.numericalControlPoints={isArray:!0,entryPrefixes:["numericalControlPoint"],forRenderer:!0,nDimensions:2,returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints,2],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=n.split(",").map((e=>Number(e))),r=e.map((e=>e+1)),a=r.join("_");t[n]={controlPoint:{dependencyType:"stateVariable",variableName:"controlPoint"+a}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].controlPoint.map((e=>e.tree));n[r]=t}return{setValue:{numericalControlPoints:n}}}},t.splineCoeffs={isArray:!0,returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints-1],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1,r=e+1;t[n]={previousPoint:{dependencyType:"stateVariable",variableName:"numericalThroughPoint"+e},nextPoint:{dependencyType:"stateVariable",variableName:"numericalThroughPoint"+r},previousVector:{dependencyType:"stateVariable",variableName:"numericalControlVector"+e+"_2"},nextVector:{dependencyType:"stateVariable",variableName:"numericalControlVector"+r+"_1"}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].previousPoint,a=e[r].nextPoint,i=e[r].previousVector,s=e[r].nextVector,o=[];for(let e=0;e<2;e++)o.push(initCubicPoly(t[e],a[e],3*i[e],-3*s[e]));n[r]=o}return{setValue:{splineCoeffs:n}}}},t.extrapolateBackwardCoeffs={stateVariablesDeterminingDependencies:["extrapolateBackward"],additionalStateVariablesDefined:[{variableName:"extrapolateBackwardMode",public:!0,shadowingInstructions:{createComponentOfType:"text"}}],returnDependencies({stateValues:e}){let t={extrapolateBackward:{dependencyType:"stateVariable",variableName:"extrapolateBackward"},nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}};return e.extrapolateBackward&&(t.firstSplineCoeffs={dependencyType:"stateVariable",variableName:"splineCoeffs1"},t.graphXmin={dependencyType:"stateVariable",variableName:"graphXmin"},t.graphXmax={dependencyType:"stateVariable",variableName:"graphXmax"},t.graphYmin={dependencyType:"stateVariable",variableName:"graphYmin"},t.graphYmax={dependencyType:"stateVariable",variableName:"graphYmax"}),t},definition({dependencyValues:e}){if(!e.extrapolateBackward||!e.firstSplineCoeffs)return{setValue:{extrapolateBackwardCoeffs:null,extrapolateBackwardMode:""}};let t=e.firstSplineCoeffs[0],n=e.firstSplineCoeffs[1],r=t[0],a=t[1],i=2*t[2],s=n[0],o=n[1],l=a*a+o*o,u=(o*i-a*(2*n[2]))/(l*l);if(Math.abs(u)<1e-12||Math.abs(a)<1e-12||Math.abs(o)<1e-12){let t=a,n=o;if(null!==e.graphXmin&&null!==e.graphXmax&&null!==e.graphYmin&&null!==e.graphYmax){let r=e.graphXmax-e.graphXmin,a=e.graphYmax-e.graphYmin,i=e.nThroughPoints-1,s=r/i/Math.abs(t),o=a/i/Math.abs(n),l=Math.min(s,o);l>1&&(t*=l,n*=l)}return{setValue:{extrapolateBackwardCoeffs:[[r,t,0],[s,n,0]],extrapolateBackwardMode:"line"}}}let c=o*u,p=-a*u;if(c*a>0){let t=c/p,n=(1+t*t)**2,i=a;if(null!==e.graphXmin&&null!==e.graphXmax&&null!==e.graphYmin&&null!==e.graphYmax){let r=e.graphXmax-e.graphXmin,a=e.graphYmax-e.graphYmin,s=e.nThroughPoints-1,o=r/s,l=1/0;if(0!==p){let e=p*n/2*s*s,r=-t*s,i=Math.sqrt(r*r+4*Math.abs(e)*a);l=(Math.abs(r)+i)/(2*Math.abs(e))}let u=Math.min(o,l);u>Math.abs(i)&&(i*=u/Math.abs(i))}return{setValue:{extrapolateBackwardCoeffs:[[r,i,0],[s,-i*t,p*i*i*n/2]],extrapolateBackwardMode:"parabolaVertical"}}}{let t=p/c,n=(1+t*t)**2,a=o;if(null!==e.graphXmin&&null!==e.graphXmax&&null!==e.graphYmin&&null!==e.graphYmax){let r=e.graphXmax-e.graphXmin,i=e.graphYmax-e.graphYmin,s=e.nThroughPoints-1,o=i/s,l=1/0;if(0!==c){let e=c*n/2*s*s,a=-t*s,i=Math.sqrt(a*a+4*Math.abs(e)*r);l=(Math.abs(a)+i)/(2*Math.abs(e))}let u=Math.min(l,o);u>Math.abs(a)&&(a*=u/Math.abs(a))}return{setValue:{extrapolateBackwardCoeffs:[[r,-a*t,c*a*a*n/2],[s,a,0]],extrapolateBackwardMode:"parabolaHorizontal"}}}}},t.extrapolateForwardCoeffs={stateVariablesDeterminingDependencies:["nThroughPoints","extrapolateForward"],additionalStateVariablesDefined:[{variableName:"extrapolateForwardMode",public:!0,shadowingInstructions:{createComponentOfType:"text"}}],returnDependencies({stateValues:e}){let t={extrapolateForward:{dependencyType:"stateVariable",variableName:"extrapolateForward"},nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}};return e.extrapolateForward&&e.nThroughPoints>=2&&(t.lastSplineCoeffs={dependencyType:"stateVariable",variableName:"splineCoeffs"+(e.nThroughPoints-1)},t.graphXmin={dependencyType:"stateVariable",variableName:"graphXmin"},t.graphXmax={dependencyType:"stateVariable",variableName:"graphXmax"},t.graphYmin={dependencyType:"stateVariable",variableName:"graphYmin"},t.graphYmax={dependencyType:"stateVariable",variableName:"graphYmax"}),t},definition({dependencyValues:e}){if(!e.extrapolateForward||!e.lastSplineCoeffs)return{setValue:{extrapolateForwardCoeffs:null,extrapolateForwardMode:""}};let t=e.lastSplineCoeffs[0],n=e.lastSplineCoeffs[1],r=t[0]+t[1]+t[2]+t[3],a=t[1]+2*t[2]+3*t[3],i=2*t[2]+6*t[3],s=n[0]+n[1]+n[2]+n[3],o=n[1]+2*n[2]+3*n[3],l=a*a+o*o,u=(o*i-a*(2*n[2]+6*n[3]))/(l*l);if(Math.abs(u)<1e-12||Math.abs(a)<1e-12||Math.abs(o)<1e-12){let t=a,n=o;if(null!==e.graphXmin&&null!==e.graphXmax&&null!==e.graphYmin&&null!==e.graphYmax){let r=e.graphXmax-e.graphXmin,a=e.graphYmax-e.graphYmin,i=e.nThroughPoints-1,s=r/i/Math.abs(t),o=a/i/Math.abs(n),l=Math.min(s,o);l>1&&(t*=l,n*=l)}return{setValue:{extrapolateForwardCoeffs:[[r,t,0],[s,n,0]],extrapolateForwardMode:"line"}}}let c=o*u,p=-a*u;if(c*a<0){let t=c/p,n=(1+t*t)**2,i=a;if(null!==e.graphXmin&&null!==e.graphXmax&&null!==e.graphYmin&&null!==e.graphYmax){let r=e.graphXmax-e.graphXmin,a=e.graphYmax-e.graphYmin,s=e.nThroughPoints-1,o=r/s,l=1/0;if(0!==p){let e=p*n/2*s*s,r=-t*s,i=Math.sqrt(r*r+4*Math.abs(e)*a);l=(Math.abs(r)+i)/(2*Math.abs(e))}let u=Math.min(o,l);u>Math.abs(i)&&(i*=u/Math.abs(i))}return{setValue:{extrapolateForwardCoeffs:[[r,i,0],[s,-i*t,p*i*i*n/2]],extrapolateForwardMode:"parabolaVertical"}}}{let t=p/c,n=(1+t*t)**2,a=o;if(null!==e.graphXmin&&null!==e.graphXmax&&null!==e.graphYmin&&null!==e.graphYmax){let r=e.graphXmax-e.graphXmin,i=e.graphYmax-e.graphYmin,s=e.nThroughPoints-1,o=i/s,l=1/0;if(0!==c){let e=c*n/2*s*s,a=-t*s,i=Math.sqrt(a*a+4*Math.abs(e)*r);l=(Math.abs(a)+i)/(2*Math.abs(e))}let u=Math.min(l,o);u>Math.abs(a)&&(a*=u/Math.abs(a))}return{setValue:{extrapolateForwardCoeffs:[[r,-a*t,c*a*a*n/2],[s,a,0]],extrapolateForwardMode:"parabolaHorizontal"}}}}},t.fs={isArray:!0,entryPrefixes:["f"],additionalStateVariablesDefined:[{variableName:"fDefinitions",isArray:!0,forRenderer:!0}],returnArraySizeDependencies:()=>({functionChildren:{dependencyType:"child",childGroups:["functions"]},curveType:{dependencyType:"stateVariable",variableName:"curveType"}}),returnArraySize:({dependencyValues:e})=>"bezier"===e.curveType?[2]:[Math.max(1,e.functionChildren.length)],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["numericalf","fDefinition"],childIndices:[n]}},0===Number(n)&&(t[n].fShadow={dependencyType:"stateVariable",variableName:"fShadow"},t[n].fDefinitionAdapted={dependencyType:"adapterSourceStateVariable",variableName:"fDefinition"});return{globalDependencies:{curveType:{dependencyType:"stateVariable",variableName:"curveType"},numericalThroughPoints:{dependencyType:"stateVariable",variableName:"numericalThroughPoints"},splineCoeffs:{dependencyType:"stateVariable",variableName:"splineCoeffs"},nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"},extrapolateBackward:{dependencyType:"stateVariable",variableName:"extrapolateBackward"},extrapolateBackwardCoeffs:{dependencyType:"stateVariable",variableName:"extrapolateBackwardCoeffs"},extrapolateForward:{dependencyType:"stateVariable",variableName:"extrapolateForward"},extrapolateForwardCoeffs:{dependencyType:"stateVariable",variableName:"extrapolateForwardCoeffs"}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){if("bezier"===e.curveType)return{setValue:{fs:returnBezierFunctions(e),fDefinitions:{0:{functionType:"bezier",nThroughPoints:e.nThroughPoints,numericalThroughPoints:e.numericalThroughPoints,splineCoeffs:e.splineCoeffs,extrapolateForward:e.extrapolateForward,extrapolateForwardCoeffs:e.extrapolateForwardCoeffs,extrapolateBackward:e.extrapolateBackward,extrapolateBackwardCoeffs:e.extrapolateBackwardCoeffs},1:null}}};let r={},a={};for(let e of n){let n=t[e].functionChild;1===n.length?(r[e]=n[0].stateValues.numericalf,a[e]=n[0].stateValues.fDefinition):0===Number(e)&&t[e].fShadow?(r[e]=t[e].fShadow,a[e]=t[e].fDefinitionAdapted):(r[e]=()=>0,a[e]={functionType:"zero"})}return{setValue:{fs:r,fDefinitions:a}}}},t.f={isAlias:!0,targetVariableName:"f1"},t.allXCriticalPoints={returnDependencies:()=>({splineCoeffs:{dependencyType:"stateVariable",variableName:"splineCoeffs"},fs:{dependencyType:"stateVariable",variableName:"fs"},curveType:{dependencyType:"stateVariable",variableName:"curveType"}}),definition({dependencyValues:e}){let t=[];if("bezier"!==e.curveType)return{setValue:{allXCriticalPoints:t}};let n=e.fs[0],r=e.fs[1],a=[],i=!1;for(let[t,n]of e.splineCoeffs.entries()){let e=n[0],r=3*e[3],s=2*e[2],o=e[1];if(Math.abs(r)<1e-14){i=addTimePointBezier({t:-o/s,ind:t,ts:a,ignoreLeft:i})}else{let e=s*s-4*r*o;if(0==e){i=addTimePointBezier({t:-s/(2*r),ind:t,ts:a,ignoreLeft:i})}else if(e>0){let n=Math.sqrt(e),o=[(-s-n)/(2*r),(-s+n)/(2*r)];r<0&&(o=[o[1],o[0]]);let l=!1;for(let e of o){addTimePointBezier({t:e,ind:t,ts:a,ignoreLeft:i})&&(l=!0)}i=l}else i=!1}}for(let e of a)t.push([n(e),r(e)]);return{setValue:{allXCriticalPoints:t}}}},t.nXCriticalPoints={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({allXCriticalPoints:{dependencyType:"stateVariable",variableName:"allXCriticalPoints"}}),definition:({dependencyValues:e})=>({setValue:{nXCriticalPoints:e.allXCriticalPoints.length}})},t.xCriticalPoints={public:!0,shadowingInstructions:{createComponentOfType:"number",returnWrappingComponents:e=>"xCriticalPointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,nDimensions:2,entryPrefixes:["xCriticalPointX","xCriticalPoint"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("xCriticalPointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("xCriticalPoints"===t)return 1===e.length?"xCriticalPoint"+e[0]:`xCriticalPointX${e[0]}_${e[1]}`;if("xCriticalPoint"===t.slice(0,14)){let n=Number(t.slice(14));if(Number.isInteger(n)&&n>0)return`xCriticalPointX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nXCriticalPoints:{dependencyType:"stateVariable",variableName:"nXCriticalPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nXCriticalPoints,2],returnArrayDependenciesByKey:()=>({globalDependencies:{allXCriticalPoints:{dependencyType:"stateVariable",variableName:"allXCriticalPoints"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n=0;n({splineCoeffs:{dependencyType:"stateVariable",variableName:"splineCoeffs"},fs:{dependencyType:"stateVariable",variableName:"fs"},curveType:{dependencyType:"stateVariable",variableName:"curveType"}}),definition({dependencyValues:e}){let t=[];if("bezier"!==e.curveType)return{setValue:{allYCriticalPoints:t}};let n=e.fs[0],r=e.fs[1],a=[],i=!1;for(let[t,n]of e.splineCoeffs.entries()){let e=n[1],r=3*e[3],s=2*e[2],o=e[1];if(Math.abs(r)<1e-14){i=addTimePointBezier({t:-o/s,ind:t,ts:a,ignoreLeft:i})}else{let e=s*s-4*r*o;if(0==e){i=addTimePointBezier({t:-s/(2*r),ind:t,ts:a,ignoreLeft:i})}else if(e>0){let n=Math.sqrt(e),o=[(-s-n)/(2*r),(-s+n)/(2*r)];r<0&&(o=[o[1],o[0]]);let l=!1;for(let e of o){addTimePointBezier({t:e,ind:t,ts:a,ignoreLeft:i})&&(l=!0)}i=l}else i=!1}}for(let e of a)t.push([n(e),r(e)]);return{setValue:{allYCriticalPoints:t}}}},t.nYCriticalPoints={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({allYCriticalPoints:{dependencyType:"stateVariable",variableName:"allYCriticalPoints"}}),definition:({dependencyValues:e})=>({setValue:{nYCriticalPoints:e.allYCriticalPoints.length}})},t.yCriticalPoints={public:!0,shadowingInstructions:{createComponentOfType:"number",returnWrappingComponents:e=>"yCriticalPointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,nDimensions:2,entryPrefixes:["yCriticalPointX","yCriticalPoint"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("yCriticalPointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("yCriticalPoints"===t)return 1===e.length?"yCriticalPoint"+e[0]:`yCriticalPointX${e[0]}_${e[1]}`;if("yCriticalPoint"===t.slice(0,14)){let n=Number(t.slice(14));if(Number.isInteger(n)&&n>0)return`yCriticalPointX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nYCriticalPoints:{dependencyType:"stateVariable",variableName:"nYCriticalPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nYCriticalPoints,2],returnArrayDependenciesByKey:()=>({globalDependencies:{allYCriticalPoints:{dependencyType:"stateVariable",variableName:"allYCriticalPoints"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n=0;n({splineCoeffs:{dependencyType:"stateVariable",variableName:"splineCoeffs"},fs:{dependencyType:"stateVariable",variableName:"fs"},curveType:{dependencyType:"stateVariable",variableName:"curveType"}}),definition({dependencyValues:e}){let t=[];if("bezier"!==e.curveType)return{setValue:{allCurvatureChangePoints:t}};let n=e.fs[0],r=e.fs[1],a=[],i=!1;for(let[t,n]of e.splineCoeffs.entries()){let[e,r,s,o]=n[0],[l,u,c,p]=n[1],d=3*(s*p-c*o),m=3*(r*p-u*o),h=r*c-u*s;if(Math.abs(d)<1e-14){i=addTimePointBezier({t:-h/m,ind:t,ts:a,ignoreLeft:i})}else{let e=m*m-4*d*h;if(0==e){i=addTimePointBezier({t:-m/(2*d),ind:t,ts:a,ignoreLeft:i})}else if(e>0){let n=Math.sqrt(e),r=[(-m-n)/(2*d),(-m+n)/(2*d)];d<0&&(r=[r[1],r[0]]);let s=!1;for(let e of r){addTimePointBezier({t:e,ind:t,ts:a,ignoreLeft:i})&&(s=!0)}i=s}else i=!1}}for(let e of a)t.push([n(e),r(e)]);return{setValue:{allCurvatureChangePoints:t}}}},t.nCurvatureChangePoints={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({allCurvatureChangePoints:{dependencyType:"stateVariable",variableName:"allCurvatureChangePoints"}}),definition:({dependencyValues:e})=>({setValue:{nCurvatureChangePoints:e.allCurvatureChangePoints.length}})},t.curvatureChangePoints={public:!0,shadowingInstructions:{createComponentOfType:"number",returnWrappingComponents:e=>"curvatureChangePointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,nDimensions:2,entryPrefixes:["curvatureChangePointX","curvatureChangePoint"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("curvatureChangePointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("curvatureChangePoints"===t)return 1===e.length?"curvatureChangePoint"+e[0]:`curvatureChangePointX${e[0]}_${e[1]}`;if("curvatureChangePoint"===t.slice(0,20)){let n=Number(t.slice(20));if(Number.isInteger(n)&&n>0)return`curvatureChangePointX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nCurvatureChangePoints:{dependencyType:"stateVariable",variableName:"nCurvatureChangePoints"}}),returnArraySize:({dependencyValues:e})=>[e.nCurvatureChangePoints,2],returnArrayDependenciesByKey:()=>({globalDependencies:{allCurvatureChangePoints:{dependencyType:"stateVariable",variableName:"allCurvatureChangePoints"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n=0;n({nearestPointAsCurvePrelim:{dependencyType:"stateVariable",variableName:"nearestPointAsCurvePrelim"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["nearestPointAsCurve"]},adapterSourceValue:{dependencyType:"adapterSourceStateVariable",variableName:"nearestPointAsCurve"}}),definition({dependencyValues:e,usedDefault:t}){let n=e.nearestPointAsCurvePrelim;return t.nearestPointAsCurvePrelim&&(e.functionChild.length>0?n=e.functionChild[0].stateValues.nearestPointAsCurve:null!==e.adapterSourceValue&&(n=e.adapterSourceValue)),{setValue:{nearestPointAsCurve:n}}}},t.nearestPoint={returnDependencies:()=>({curveType:{dependencyType:"stateVariable",variableName:"curveType"},fs:{dependencyType:"stateVariable",variableName:"fs"},flipFunction:{dependencyType:"stateVariable",variableName:"flipFunction"},nDiscretizationPoints:{dependencyType:"stateVariable",variableName:"nDiscretizationPoints"},parMin:{dependencyType:"stateVariable",variableName:"parMin"},parMax:{dependencyType:"stateVariable",variableName:"parMax"},periodic:{dependencyType:"stateVariable",variableName:"periodic"},graphXmin:{dependencyType:"stateVariable",variableName:"graphXmin"},graphXmax:{dependencyType:"stateVariable",variableName:"graphXmax"},graphYmin:{dependencyType:"stateVariable",variableName:"graphYmin"},graphYmax:{dependencyType:"stateVariable",variableName:"graphYmax"},nearestPointAsCurve:{dependencyType:"stateVariable",variableName:"nearestPointAsCurve"}}),definition({dependencyValues:t}){let n=null;return"function"===t.curveType?n=getNearestPointFunctionCurve({dependencyValues:t,numerics:e}):["parameterization","bezier"].includes(t.curveType)&&(n=getNearestPointParametrizedCurve({dependencyValues:t,numerics:e})),{setValue:{nearestPoint:n}}}},t}async moveControlVector({controlVector:e,controlVectorInds:t,transient:n,actionId:r}){let a={[t+",0"]:me$3.fromAst(e[0]),[t+",1"]:me$3.fromAst(e[1])};return n?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"controlVectors",value:a,sourceInformation:{controlVectorMoved:t}}],transient:n,actionId:r}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"controlVectors",value:a,sourceInformation:{controlVectorMoved:t}}],actionId:r,event:{verb:"interacted",object:{componentId:this.componentName},result:{["controlVector"+t.join("_")]:e}}})}async moveThroughPoint({throughPoint:e,throughPointInd:t,transient:n,actionId:r}){let a={[t+",0"]:me$3.fromAst(e[0]),[t+",1"]:me$3.fromAst(e[1])};return n?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"throughPoints",value:a,sourceInformation:{throughPointMoved:t}}],transient:n,actionId:r}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"throughPoints",value:a,sourceInformation:{throughPointMoved:t}}],actionId:r,event:{verb:"interacted",object:{componentId:this.componentName},result:{["throughPoint"+t]:e}}})}async changeVectorControlDirection({direction:e,throughPointInd:t,actionId:n}){return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"vectorControlDirection",value:{[t]:e}}],actionId:n})}switchCurve(){}async curveClicked({actionId:e,name:t}){await this.coreFunctions.triggerChainedActions({triggeringAction:"click",componentName:t}),this.coreFunctions.resolveAction({actionId:e})}async mouseDownOnCurve({actionId:e,name:t}){await this.coreFunctions.triggerChainedActions({triggeringAction:"down",componentName:t}),this.coreFunctions.resolveAction({actionId:e})}}function getNearestPointFunctionCurve({dependencyValues:e,numerics:t}){let n=e.flipFunction,r=e.fs[0],a=e.nDiscretizationPoints,i=e.parMax,s=e.parMin;return function({variables:o,scales:l}){let u,c,p,d,m=o.x1?.evaluate_to_constant(),h=o.x2?.evaluate_to_constant(),f=l[0],y=l[1];if(s!==-1/0){if(u=s,c=r(s),!Number.isFinite(c)){let e=.99999*s+1e-5*i,t=r(e);Number.isFinite(t)&&(u=e,c=t)}if(n){let e=u;u=c,c=e}}if(i!==1/0){if(p=i,d=r(i),!Number.isFinite(d)){let e=1e-5*s+.99999*i,t=r(e);Number.isFinite(t)&&(p=e,d=t)}if(n){let e=p;p=d,d=e}}if(!e.nearestPointAsCurve||!Number.isFinite(m)||!Number.isFinite(h)){let e,t;if(n?(t=h,e=r(t)):(e=m,t=r(e)),!Number.isFinite(e)||!Number.isFinite(t)){let r,a;n?(r=Math.abs(s-h),a=Math.abs(i-h)):(r=Math.abs(s-m),a=Math.abs(i-m)),re.evaluate_to_constant())),a)l=a.map((e=>e.evaluate_to_constant())),s=n?n.map((e=>e.evaluate_to_constant())):[2*o[0]-l[0],2*o[1]-l[1]];else{if(!n)return{coordsNumeric:[me$3.fromAst(NaN),me$3.fromAst(NaN)],numericEntries:!1};s=n.map((e=>e.evaluate_to_constant())),l=[2*o[0]-s[0],2*o[1]-s[1]]}let c=[];if("centripetal"===i){let n=u(s,o),r=u(o,l);n=Math.sqrt(n),r=Math.sqrt(r),rme$3.fromAst(e)));return{coordsNumeric:p,numericEntries:Number.isFinite(c[0])&&Number.isFinite(c[1])}}function initCubicPoly(e,t,n,r){return[e,n,-3*e+3*t-2*n-r,2*e-2*t+n+r]}function addTimePointBezier({t:e,ind:t,ts:n,ignoreLeft:r=!1}){const a=1e-14;let i=!1;return e>=a?e<=.99999999999999?n.push(t+e):e<1.00000000000001&&(n.push(t+1),i=!0):e>-a&&!r&&n.push(t),i}class EquilibriumCurve extends Curve{static componentType="equilibriumCurve";static rendererType="curve";static createAttributesObject(){let e=super.createAttributesObject();return e.stable={createComponentOfType:"boolean",createStateVariable:"stable",defaultValue:!0,public:!0},e.switchable={createComponentOfType:"boolean",createStateVariable:"switchable",defaultValue:!1,public:!0,forRenderer:!0},e}static returnStateVariableDefinitions({numerics:e}){let t=super.returnStateVariableDefinitions({numerics:e});return t.dashed={forRenderer:!0,returnDependencies:()=>({stable:{dependencyType:"stateVariable",variableName:"stable"}}),definition:({dependencyValues:e})=>({setValue:{dashed:!e.stable}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setDependency:"stable",desiredValue:!e.dashed}]})},t}async switchCurve({actionId:e}){if(await this.stateValues.switchable)return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"stable",value:!this.stateValues.stable}],actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{stable:!this.stateValues.stable}}});this.coreFunctions.resolveAction({actionId:e})}}var DynamicalSystems=Object.freeze({__proto__:null,ODESystem:ODESystem,CobwebPolyline:CobwebPolyline,EquilibriumPoint:EquilibriumPoint,EquilibriumLine:EquilibriumLine,EquilibriumCurve:EquilibriumCurve});class Atom extends InlineComponent{static componentType="atom";static rendererType="math";static primaryStateVariableForDefinition="atomicNumberShadow";static createAttributesObject(){let e=super.createAttributesObject();return e.symbol={createComponentOfType:"text"},e.atomicNumber={createComponentOfType:"integer"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.atomicNumberShadow={defaultValue:null,hasEssential:!0,essentialVarName:"atomicNumber",returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{atomicNumberShadow:!0}}),inverseDefinition:async function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"atomicNumberShadow",value:e.atomicNumberShadow}]}}},e.dataForAtom={returnDependencies:()=>({fileContents:{dependencyType:"file",cid:"bafkreibilal4glrbpo7p7oodtwtnzkfhiylfoqa2td4ij6h6iqva57kzcy",fileType:"csv"},symbolAttr:{dependencyType:"attributeComponent",attributeName:"symbol",variableNames:["value"]},atomicNumberAttr:{dependencyType:"attributeComponent",attributeName:"atomicNumber",variableNames:["value"]},atomicNumberShadow:{dependencyType:"stateVariable",variableName:"atomicNumberShadow"}}),definition:function({dependencyValues:e}){let t=null,n=null;if(e.symbolAttr)t=e.symbolAttr.stateValues.value.toLowerCase();else if(e.atomicNumberAttr)n=e.atomicNumberAttr.stateValues.value;else{if(!e.atomicNumberShadow)return{setValue:{dataForAtom:null}};n=e.atomicNumberShadow}let r,a=e.fileContents.trim().split("\n");r=null!==n?n-1:["h","he","li","be","b","c","n","o","f","ne","na","mg","al","si","p","s","cl","ar","k","ca","sc","ti","v","cr","mn","fe","co","ni","cu","zn","ga","ge","as","se","br","kr","rb","sr","y","zr","nb","mo","tc","ru","rh","pd","ag","cd","in","sn","sb","te","i","xe","cs","ba","la","ce","pr","nd","pm","sm","eu","gd","tb","dy","ho","er","tm","yb","lu","hf","ta","w","re","os","ir","pt","au","hg","tl","pb","bi","po","at","rn","fr","ra","ac","th","pa","u","np","pu","am","cm","bk","cf","es","fm","md","no","lr","rf","db","sg","bh","hs","mt","ds","rg","cn","nh","fl","mc","lv","ts","og"].indexOf(t?.toLowerCase());let i=a.slice(1)[r];if(!i)return{setValue:{dataForAtom:null}};i=i.trim().split(",").map((e=>e.trim()));let s=a[0].trim().split(",").map((e=>e.trim())).map((e=>(['"',"'"].includes(e[0])&&e[e.length-1]===e[0]&&(e=e.substring(1,e.length-1).trim()),e))),o=s.length,l=["number","string","string","number","number","string","number","string","string","number","number","number","number","number","number","number","string"],u={};for(let e=0;e({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Atomic Number"]:null,{setValue:{atomicNumber:t}}}},e.symbol={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom.Symbol:null,{setValue:{symbol:t}}}},e.name={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom.Name:null,{setValue:{name:t}}}},e.group={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom.Group:null,{setValue:{group:t}}}},e.atomicMass={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Atomic Mass"]:null,{setValue:{atomicMass:t}}}},e.phaseAtSTP={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Phase at STP"]:null,{setValue:{phaseAtSTP:t}}}},e.chargeOfCommonIon={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Charge of Common Ion"]:null,{setValue:{chargeOfCommonIon:t}}}},e.metalCategory={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Metal/Nonmetal/Metalloid"]:null,{setValue:{metalCategory:t}}}},e.groupName={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Group Name"]:null,{setValue:{groupName:t}}}},e.period={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom.Period:null,{setValue:{period:t}}}},e.ionizationEnergy={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Ionization Energy"]:null,{setValue:{ionizationEnergy:t}}}},e.meltingPoint={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Melting Point"]:null,{setValue:{meltingPoint:t}}}},e.boilingPoint={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Boiling Point"]:null,{setValue:{boilingPoint:t}}}},e.atomicRadius={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Atomic Radius"]:null,{setValue:{atomicRadius:t}}}},e.density={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom.Density:null,{setValue:{density:t}}}},e.electronegativity={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom.Electronegativity:null,{setValue:{electronegativity:t}}}},e.electronConfiguration={public:!0,shadowingInstructions:{createComponentOfType:"electronConfiguration"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Electron Configuration"]:null,{setValue:{electronConfiguration:t}}}},e.orbitalDiagram={public:!0,shadowingInstructions:{createComponentOfType:"orbitalDiagram"},returnDependencies:()=>({electronConfiguration:{dependencyType:"stateVariable",variableName:"electronConfiguration"}}),definition({dependencyValues:e}){let t;return t=e.electronConfiguration?electronConfigurationToOrbitalDiagram(e.electronConfiguration):null,{setValue:{orbitalDiagram:t}}}},e.math={public:!0,shadowingInstructions:{createComponentOfType:"math"},returnDependencies:()=>({symbol:{dependencyType:"stateVariable",variableName:"symbol"}}),definition({dependencyValues:e}){let t;return t=e.symbol?["^",e.symbol]:"_",{setValue:{math:me$3.fromAst(t)}}}},e.latex={additionalStateVariablesDefined:[{variableName:"latexWithInputChildren",forRenderer:!0}],returnDependencies:()=>({symbol:{dependencyType:"stateVariable",variableName:"symbol"}}),definition({dependencyValues:e}){let t;return t=e.symbol?`\\text{${e.symbol}}`:"[\\text{Invalid Chemical Symbol}]",{setValue:{latex:t,latexWithInputChildren:[t]}}}},e}static adapters=["math","name",{stateVariable:"atomicNumber",componentType:"ion"}]}function electronConfigurationToOrbitalDiagram(e){let t=e.tree;if(!Array.isArray(t)||"*"!==t[0])return null;t=t.slice(1);let n=t.length/2;if(!Number.isInteger(n))return null;let r=[];for(let e=0;e0))return null;let a=t[2*e+1];if(!Array.isArray(a)||"^"!==a[0])return null;let i=a[1],s=a[2];if(!(["s","p","d","f"].includes(i)&&Number.isInteger(s)&&s>0))return null;let o,l=`${n}${i}`;o="s"===i?1:"p"===i?3:"d"===i?5:7;let u=Array(o).fill("");for(let e=0;e({}),definition:()=>({useEssentialOrDefaultValue:{atomicNumberShadow:!0}}),inverseDefinition:async function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"atomicNumberShadow",value:e.atomicNumberShadow}]}}},e.dataForAtom={returnDependencies:()=>({fileContents:{dependencyType:"file",cid:"bafkreibilal4glrbpo7p7oodtwtnzkfhiylfoqa2td4ij6h6iqva57kzcy",fileType:"csv"},symbolAttr:{dependencyType:"attributeComponent",attributeName:"symbol",variableNames:["value"]},atomicNumberAttr:{dependencyType:"attributeComponent",attributeName:"atomicNumber",variableNames:["value"]},atomChild:{dependencyType:"child",childGroups:["atoms"],variableNames:["atomicNumber"]},atomicNumberShadow:{dependencyType:"stateVariable",variableName:"atomicNumberShadow"}}),definition:function({dependencyValues:e}){let t=null,n=null;if(e.atomChild.length>0)n=e.atomChild[0].stateValues.atomicNumber;else if(e.symbolAttr)t=e.symbolAttr.stateValues.value.toLowerCase();else if(e.atomicNumberAttr)n=e.atomicNumberAttr.stateValues.value;else{if(!e.atomicNumberShadow)return{setValue:{dataForAtom:null}};n=e.atomicNumberShadow}let r,a=e.fileContents.trim().split("\n");r=null!==n?n-1:["h","he","li","be","b","c","n","o","f","ne","na","mg","al","si","p","s","cl","ar","k","ca","sc","ti","v","cr","mn","fe","co","ni","cu","zn","ga","ge","as","se","br","kr","rb","sr","y","zr","nb","mo","tc","ru","rh","pd","ag","cd","in","sn","sb","te","i","xe","cs","ba","la","ce","pr","nd","pm","sm","eu","gd","tb","dy","ho","er","tm","yb","lu","hf","ta","w","re","os","ir","pt","au","hg","tl","pb","bi","po","at","rn","fr","ra","ac","th","pa","u","np","pu","am","cm","bk","cf","es","fm","md","no","lr","rf","db","sg","bh","hs","mt","ds","rg","cn","nh","fl","mc","lv","ts","og"].indexOf(t?.toLowerCase());let i=a.slice(1)[r];if(!i)return{setValue:{dataForAtom:null}};i=i.trim().split(",").map((e=>e.trim()));let s=a[0].trim().split(",").map((e=>e.trim())).map((e=>(['"',"'"].includes(e[0])&&e[e.length-1]===e[0]&&(e=e.substring(1,e.length-1).trim()),e))),o=s.length,l=["number","string","string","number","number","string","number","string","string","number","number","number","number","number","number","number","string"],u={};for(let e=0;e({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Atomic Number"]:null,{setValue:{atomicNumber:t}}}},e.symbol={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom.Symbol:null,{setValue:{symbol:t}}}},e.charge={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"},chargeAttr:{dependencyType:"attributeComponent",attributeName:"charge",variableNames:["value"]}}),definition({dependencyValues:e}){let t;return e.chargeAttr?(t=e.chargeAttr.stateValues.value,Number.isFinite(t)||(t=0)):t=e.dataForAtom&&e.dataForAtom["Charge of Common Ion"]||0,{setValue:{charge:t}}}},e.name={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"},charge:{dependencyType:"stateVariable",variableName:"charge"},group:{dependencyType:"stateVariable",variableName:"group"},atomicNumber:{dependencyType:"stateVariable",variableName:"atomicNumber"}}),definition({dependencyValues:e}){let t;if(e.dataForAtom){if(t=e.dataForAtom.Name,e.charge<0){let e={Hydrogen:"Hydride",Oxygen:"Oxide",Sulfur:"Sulfide",Nitrogen:"Nitride",Phosphorus:"Phosphide",Carbon:"Carbide"},n=t.length;"ine"===t.substring(n-3,n)?t=t.substring(0,n-3)+"ide":t in e&&(t=e[t])}else if(e.charge>0&&(e.group>=3&&e.group<=12||101===e.group||102===e.group||[13,31,49,50,81,82,83,84].includes(e.atomicNumber))){let n="";switch(e.charge){case 1:n=" (I)";break;case 2:n=" (II)";break;case 3:n=" (III)";break;case 4:n=" (IV)";break;case 5:n=" (V)";break;case 6:n=" (VI)";break;case 7:n=" (VII)";break;case 8:n=" (VIII)"}t+=n}}else t=null;return{setValue:{name:t}}}},e.group={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom.Group:null,{setValue:{group:t}}}},e.metalCategory={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Metal/Nonmetal/Metalloid"]:null,{setValue:{metalCategory:t}}}},e.groupName={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Group Name"]:null,{setValue:{groupName:t}}}},e.period={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom.Period:null,{setValue:{period:t}}}},e.math={public:!0,shadowingInstructions:{createComponentOfType:"math"},returnDependencies:()=>({symbol:{dependencyType:"stateVariable",variableName:"symbol"},charge:{dependencyType:"stateVariable",variableName:"charge"}}),definition({dependencyValues:e}){let t;return e.symbol?(t=["^",e.symbol],-1===e.charge?t.push("-"):1===e.charge?t.push("+"):e.charge<0?t.push(Math.abs(e.charge)+"-"):e.charge>0&&t.push(Math.abs(e.charge)+"+")):t="_",{setValue:{math:me$3.fromAst(t)}}}},e.latex={additionalStateVariablesDefined:[{variableName:"latexWithInputChildren",forRenderer:!0}],returnDependencies:()=>({symbol:{dependencyType:"stateVariable",variableName:"symbol"},charge:{dependencyType:"stateVariable",variableName:"charge"}}),definition({dependencyValues:e}){let t;return e.symbol?(t=`\\text{${e.symbol}}`,-1===e.charge?t+="^-":1===e.charge?t+="^+":e.charge<0?t+=`^{${Math.abs(e.charge)}-}`:e.charge>0&&(t+=`^{${Math.abs(e.charge)}+}`)):t="[\\text{Invalid Chemical Symbol}]",{setValue:{latex:t,latexWithInputChildren:[t]}}}},e}static adapters=["math","name"]}class IonicCompound extends InlineComponent{static componentType="ionicCompound";static rendererType="math";static createAttributesObject(){let e=super.createAttributesObject();return e.symbol={createComponentOfType:"text"},e.atomicNumber={createComponentOfType:"integer"},e.charge={createComponentOfType:"integer"},e}static returnChildGroups(){return[{group:"ions",componentTypes:["ion"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.ionicCompound={returnDependencies:()=>({ionChildren:{dependencyType:"child",childGroups:["ions"],variableNames:["symbol","charge","atomicNumber","name"]}}),definition({dependencyValues:e}){let t=e.ionChildren.map((e=>e.stateValues.charge));if(2!==t.length)return console.warn("have not implemented ionic compound for anything other than two ions"),{setValue:{ionicCompound:null}};if(!(t[0]*t[1]<0))return console.warn("ionic compound implemented only for one cation and one anion"),{setValue:{ionicCompound:null}};let n=Math.abs(t[1]),r=Math.abs(t[0]),a=me$3.math.gcd(n,r);return n/=a,r/=a,{setValue:{ionicCompound:[{symbol:e.ionChildren[0].stateValues.symbol,atomicNumber:e.ionChildren[0].stateValues.atomicNumber,name:e.ionChildren[0].stateValues.name,charge:t[0],count:n},{symbol:e.ionChildren[1].stateValues.symbol,atomicNumber:e.ionChildren[1].stateValues.atomicNumber,name:e.ionChildren[1].stateValues.name,charge:t[1],count:r}]}}}},e.math={public:!0,shadowingInstructions:{createComponentOfType:"math"},returnDependencies:()=>({ionicCompound:{dependencyType:"stateVariable",variableName:"ionicCompound"}}),definition({dependencyValues:e}){let t;if(e.ionicCompound){t=[];for(let n of e.ionicCompound){let e=n.symbol;n.count>1&&(e=["_",e,n.count]),t.push(e)}t=t.length>1?["*",...t]:1===t.length?t[0]:"_"}else t="_";return{setValue:{math:me$3.fromAst(t)}}}},e.latex={additionalStateVariablesDefined:[{variableName:"latexWithInputChildren",forRenderer:!0}],returnDependencies:()=>({ionicCompound:{dependencyType:"stateVariable",variableName:"ionicCompound"}}),definition({dependencyValues:e}){let t;if(e.ionicCompound){t="";for(let n of e.ionicCompound)t+=`\\text{${n.symbol}}`,n.count>1&&(t+=`_{${n.count}}`)}else t="[\\text{Invalid Ionic Compound}]";return{setValue:{latex:t,latexWithInputChildren:[t]}}}},e}static adapters=["math"]}class ElectronConfiguration extends MathComponent{static componentType="electronConfiguration";static rendererType="math";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.latex={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({valueForDisplay:{dependencyType:"stateVariable",variableName:"valueForDisplay"}}),definition:function({dependencyValues:e,usedDefault:t}){let n;try{n=e.valueForDisplay.toLatex()}catch(e){n="_"}return n=n.replaceAll("\\,",""),n=n.replaceAll("\\cdot","~"),{setValue:{latex:n}}}},e}}class OrbitalDiagram extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="orbitalDiagram";static variableForPlainMacro="value";static createAttributesObject(){let e=super.createAttributesObject();return e.labels={createComponentOfType:"textList",createStateVariable:"labels",defaultValue:[]},e}static returnSugarInstructions(){return[{replacementFunction:function({matchedChildren:e}){return 1===e.length&&"string"!=typeof e[0]?{success:!1}:{success:!0,newChildren:[{componentType:"tupleList",children:e}]}}}]}static returnChildGroups(){return[{group:"tupleLists",componentTypes:["tupleList"]},{group:"orbitalDiagrams",componentTypes:["orbitalDiagram"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.value={defaultValue:[{orbitalText:"",boxes:[]}],public:!0,shadowingInstructions:{createComponentOfType:"orbitalDiagram"},forRenderer:!0,returnDependencies:()=>({orbitalDiagramChildren:{dependencyType:"child",childGroups:["orbitalDiagrams"],variableNames:["value"]},tupleListChildren:{dependencyType:"child",childGroups:["tupleLists"],variableNames:["maths"]},labels:{dependencyType:"stateVariable",variableName:"labels"}}),definition:function({dependencyValues:e}){return{setValue:{value:function(){function t(e){if("u"===e||"U"===e)return"U";if("d"===e||"D"===e)return"D";if("e"===e||"E"===e)return"";if(Array.isArray(e)&&"*"===e[0]){let t="";for(let n of e.slice(1))if("u"===n||"U"===n)t+="U";else{if("d"!==n&&"D"!==n)return"";t+="D"}return t}return""}if(1===e.orbitalDiagramChildren.length)return e.orbitalDiagramChildren[0].stateValues.value;let n=[];if(e.tupleListChildren[0]?.stateValues.maths.length>0){let r=e.tupleListChildren[0].stateValues.maths;for(let[a,i]of r.entries()){let r="";e.labels[a]&&(r=e.labels[a]);let s=[];if(Array.isArray(i.tree)&&"tuple"===i.tree[0])for(let e of i.tree.slice(1))s.push(t(e));else s.push(t(i.tree));n.push({orbitalText:r,boxes:s})}return n}return[{orbitalText:"",boxes:[]}]}()}}}},e}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class OrbitalDiagramInput extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{addRow:this.addRow.bind(this),removeRow:this.removeRow.bind(this),addBox:this.addBox.bind(this),removeBox:this.removeBox.bind(this),addUpArrow:this.addUpArrow.bind(this),addDownArrow:this.addDownArrow.bind(this),removeArrow:this.removeArrow.bind(this),updateRowText:this.updateRowText.bind(this),selectRow:this.selectRow.bind(this),selectBox:this.selectBox.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="orbitalDiagramInput";static variableForPlainMacro="value";static variableForPlainCopy="value";static createAttributesObject(){let e=super.createAttributesObject();return e.prefill={createComponentOfType:"orbitalDiagram",createStateVariable:"prefill",defaultValue:[]},e.prefillLabel={createComponentOfType:"textList",createStateVariable:"prefillLabel",defaultValue:[]},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.value={defaultValue:[{orbitalText:"",boxes:[]}],hasEssential:!0,forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"orbitalDiagram"},returnDependencies:()=>({prefill:{dependencyType:"stateVariable",variableName:"prefill"},prefillLabel:{dependencyType:"stateVariable",variableName:"prefillLabel"}}),definition:function({dependencyValues:e}){return{useEssentialOrDefaultValue:{value:{get defaultValue(){return function(){if(e.prefill?.length>0){let t=JSON.parse(JSON.stringify(e.prefill));for(let[n,r]of t.entries())e.prefillLabel[n]&&(r.orbitalText=e.prefillLabel[n]);return t}return[{orbitalText:"",boxes:[]}]}()}}}}},inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"value",value:e.value}]})},e.rows={public:!0,shadowingInstructions:{createComponentOfType:"orbitalDiagram"},forRenderer:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:({dependencyValues:e})=>({setValue:{rows:[...e.value].reverse()}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setDependency:"value",desiredValue:[...e.rows].reverse()}]})},e.numRows={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({rows:{dependencyType:"stateVariable",variableName:"rows"}}),definition:function({dependencyValues:e}){return{setValue:{numRows:e.rows.length}}}},e.selectedRowIndex={defaultValue:0,hasEssential:!0,forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({}),definition:function(){return{useEssentialOrDefaultValue:{selectedRowIndex:!0}}},async inverseDefinition({desiredStateVariableValues:e,stateValues:t}){let n=await t.numRows,r=e.selectedRowIndex;return r=Number.isFinite(r)?Math.min(n,Math.max(0,Math.round(r))):0,{success:!0,instructions:[{setEssentialValue:"selectedRowIndex",value:r}]}}},e.selectedBoxIndex={defaultValue:0,hasEssential:!0,forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({}),definition:function(){return{useEssentialOrDefaultValue:{selectedBoxIndex:!0}}},async inverseDefinition({desiredStateVariableValues:e}){let t=e.selectedBoxIndex;return t=Number.isFinite(t)?Math.max(0,Math.round(t)):0,{success:!0,instructions:[{setEssentialValue:"selectedBoxIndex",value:t}]}}},e}async addRow({actionId:e}){let t=await this.stateValues.rows,n=JSON.parse(JSON.stringify(t));t.length<20&&(n=[{orbitalText:"",boxes:[]},...t]);let r=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rows",value:n}];return-1!==await this.stateValues.selectedRowIndex-1&&r.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"selectedRowIndex",value:0}),-1!==await this.stateValues.selectedBoxIndex-1&&r.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"selectedBoxIndex",value:0}),await this.coreFunctions.performUpdate({updateInstructions:r,actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{rows:n}}})}async removeRow({actionId:e}){let t=await this.stateValues.rows,n=await this.stateValues.selectedRowIndex-1,r=JSON.parse(JSON.stringify(t));if(t.length>1){let e=t.length-1-n;-1===n&&(e=0),r.splice(e,1)}return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rows",value:r},{updateType:"updateValue",componentName:this.componentName,stateVariable:"selectedRowIndex",value:0},{updateType:"updateValue",componentName:this.componentName,stateVariable:"selectedBoxIndex",value:0}],actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{rows:r}}})}async addBox({actionId:e}){let t=await this.stateValues.rows,n=JSON.parse(JSON.stringify(t)),r=await this.stateValues.selectedRowIndex-1,a=t.length-r-1;-1===r&&(a=0),n[a].boxes.length<17&&n[a].boxes.push("");let i=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rows",value:n}];if(-1!==r){let e=0;i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"selectedBoxIndex",value:e})}return await this.coreFunctions.performUpdate({updateInstructions:i,actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{rows:n}}})}async removeBox({actionId:e}){let t=await this.stateValues.rows,n=JSON.parse(JSON.stringify(t)),r=await this.stateValues.selectedRowIndex-1,a=t.length-r-1;-1===r&&(a=0);let i=await this.stateValues.selectedBoxIndex-1,s=i;-1===i&&(s=n[a].boxes.length-1),n[a].boxes.splice(s,1);let o=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rows",value:n}];return-1!==i&&o.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"selectedBoxIndex",value:0}),await this.coreFunctions.performUpdate({updateInstructions:o,actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{rows:n}}})}async addUpArrow({actionId:e}){let t=await this.stateValues.rows,n=JSON.parse(JSON.stringify(t)),r=await this.stateValues.selectedRowIndex-1,a=t.length-r-1;-1===r&&(a=0);let i=await this.stateValues.selectedBoxIndex-1,s=i;-1===i&&(s=n[a].boxes.length-1),n[a].boxes.length>0&&n[a].boxes[s].length<3&&(n[a].boxes[s]=n[a].boxes[s]+"U");let o=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rows",value:n}];return await this.coreFunctions.performUpdate({updateInstructions:o,actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{rows:n}}})}async addDownArrow({actionId:e}){let t=await this.stateValues.rows,n=JSON.parse(JSON.stringify(t)),r=await this.stateValues.selectedRowIndex-1,a=t.length-r-1;-1===r&&(a=0);let i=await this.stateValues.selectedBoxIndex-1,s=i;-1===i&&(s=n[a].boxes.length-1),n[a].boxes.length>0&&n[a].boxes[s].length<3&&(n[a].boxes[s]=n[a].boxes[s]+"D");let o=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rows",value:n}];return await this.coreFunctions.performUpdate({updateInstructions:o,actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{rows:n}}})}async removeArrow({actionId:e}){let t=await this.stateValues.rows,n=JSON.parse(JSON.stringify(t)),r=await this.stateValues.selectedRowIndex-1,a=t.length-r-1;-1===r&&(a=0);let i=await this.stateValues.selectedBoxIndex-1,s=i;-1===i&&(s=n[a].boxes.length-1),n[a].boxes.length>0&&n[a].boxes[s].length>0&&(n[a].boxes[s]=n[a].boxes[s].slice(0,-1));let o=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rows",value:n}];return await this.coreFunctions.performUpdate({updateInstructions:o,actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{rows:n}}})}async updateRowText({newValue:e,actionId:t}){let n=await this.stateValues.rows,r=JSON.parse(JSON.stringify(n)),a=await this.stateValues.selectedRowIndex-1,i=n.length-a-1;-1===a&&(i=0),r[i].orbitalText=e;let s=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rows",value:r}];return await this.coreFunctions.performUpdate({updateInstructions:s,actionId:t,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{rows:r}}})}async selectRow({index:e,actionId:t}){return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"selectedRowIndex",value:e}],actionId:t,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{selectedRowIndex:e}}})}async selectBox({index:e,actionId:t}){return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"selectedBoxIndex",value:e}],actionId:t,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{selectedBoxIndex:e}}})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}var Chemistry=Object.freeze({__proto__:null,Atom:Atom,Ion:Ion,IonicCompound:IonicCompound,ElectronConfiguration:ElectronConfiguration,OrbitalDiagram:OrbitalDiagram,OrbitalDiagramInput:OrbitalDiagramInput});class FeedbackDefinition extends BaseComponent{static componentType="feedbackDefinition";static createAttributesObject(){let e=super.createAttributesObject();return e.code={createComponentOfType:"text"},e.text={createComponentOfType:"text"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.feedbackDefinition={returnDependencies:()=>({codeAttr:{dependencyType:"attributeComponent",attributeName:"code",variableNames:["value"]},textAttr:{dependencyType:"attributeComponent",attributeName:"text",variableNames:["value"]}}),definition({dependencyValues:e}){if(null!==e.codeAttr&&null!==e.textAttr){return{setValue:{feedbackDefinition:{[e.codeAttr.stateValues.value.toLowerCase()]:e.textAttr.stateValues.value}}}}return{setValue:{feedbackDefinition:null}}}},e}}class FeedbackDefinitions extends BaseComponent{static componentType="feedbackDefinitions";static rendererType=void 0;static returnChildGroups(){return[{group:"feedbackDefinition",componentTypes:["feedbackDefinition"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.value={returnDependencies:()=>({feedbackDefinitionChildren:{dependencyType:"child",childGroups:["feedbackDefinition"],variableNames:["feedbackDefinition"]}}),definition({dependencyValues:e}){let t={};for(let n of e.feedbackDefinitionChildren)n.stateValues.feedbackDefinition&&Object.assign(t,n.stateValues.feedbackDefinition);return{setValue:{value:t}}}},e}}var FeedbackDefinitions$1=Object.freeze({__proto__:null,FeedbackDefinition:FeedbackDefinition,FeedbackDefinitions:FeedbackDefinitions});class StyleDefinition extends BaseComponent{static componentType="styleDefinition";static rendererType=void 0;static createAttributesObject(){let e=super.createAttributesObject();e.styleNumber={createPrimitiveOfType:"number",createStateVariable:"styleNumber",defaultValue:1};for(let t in styleAttributes)e[t]={createComponentOfType:styleAttributes[t].componentType};return e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.styleDefinition={returnDependencies:function(){let e={};for(let t in styleAttributes)e[t]={dependencyType:"attributeComponent",attributeName:t,variableNames:["value"]};return e},definition:function({dependencyValues:e}){let t={};for(let n in styleAttributes)null!==e[n]&&(t[n]=e[n].stateValues.value,"string"==typeof t[n]&&(t[n]=t[n].toLowerCase()));return{setValue:{styleDefinition:t}}}},e}}class StyleDefinitions extends BaseComponent{static componentType="styleDefinitions";static rendererType=void 0;static returnChildGroups(){return[{group:"styleDefinition",componentTypes:["styleDefinition"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.value={returnDependencies:()=>({styleDefinitionChildren:{dependencyType:"child",childGroups:["styleDefinition"],variableNames:["styleNumber","styleDefinition"]}}),definition({dependencyValues:e}){let t={};for(let n of e.styleDefinitionChildren){let e=n.stateValues.styleNumber,r=t[e];r||(r=t[e]={}),Object.assign(r,n.stateValues.styleDefinition)}return{setValue:{value:t}}}},e}}var StyleDefinitions$1=Object.freeze({__proto__:null,StyleDefinition:StyleDefinition,StyleDefinitions:StyleDefinitions});class ComponentWithSelectableType extends BaseComponent{static componentType="_componentWithSelectableType";static rendererType=void 0;static includeBlankStringChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.type={createPrimitiveOfType:"string"},e}static returnSugarInstructions(){let e=[];return e.push({replacementFunction:function({matchedChildren:e,componentAttributes:t,parentAttributes:n}){let r=t.type;r||(r=n.type),r?["number","letters","math","text","boolean"].includes(r)||(console.warn(`Invalid type ${r}, setting type to number`),r="number"):r="number";let a="letters"===r?"text":r;return"text"!==a&&(e=e.filter((e=>"string"!=typeof e||""!==e.trim()))),{success:!0,newChildren:[{componentType:a,children:e}]}}}),e}static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.type={shadowVariable:!0,returnDependencies:()=>({type:{dependencyType:"doenetAttribute",attributeName:"type"},parentType:{dependencyType:"parentStateVariable",variableName:"type"}}),definition:function({dependencyValues:e,componentName:t}){let n=e.type;return n||(n=e.parentType),n?["number","letters","math","text","boolean"].includes(n)||(console.warn(`Invalid type ${n}, setting type to number`),n="number"):n="number",{setValue:{type:n}}}},e.value={public:!0,shadowingInstructions:{hasVariableComponentType:!0},shadowVariable:!0,returnDependencies:()=>({type:{dependencyType:"stateVariable",variableName:"type"},atMostOneChild:{dependencyType:"child",childGroups:["anything"],variableNames:["value"]}}),definition({dependencyValues:e}){let t;return t=e.atMostOneChild.length>0?e.atMostOneChild[0].stateValues.value:"text"===e.type||"letters"===e.type?"":"boolean"!==e.type&&("number"===e.type?NaN:me$3.fromAst("_")),{setValue:{value:t},setCreateComponentOfType:{value:e.type}}},inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t})=>t.atMostOneChild.length>0?{success:!0,instructions:[{setDependency:"atMostOneChild",desiredValue:e.value,childIndex:0,variableIndex:0}]}:{success:!1}},e}}class ComponentListWithSelectableType extends ComponentWithSelectableType{static componentType="_componentListWithSelectableType";static includeBlankStringChildren=!0;static removeBlankStringChildrenPostSugar=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.type={createPrimitiveOfType:"string"},e}static returnSugarInstructions(){let e=[];return e.push({replacementFunction:function({matchedChildren:e,componentAttributes:t,parentAttributes:n,isAttributeComponent:r=!1,createdFromMacro:a=!1,componentInfoObjects:i}){let s=t.type;s||(s=n.type),s?["number","letters","math","text","boolean"].includes(s)||(console.warn(`Invalid type ${s}, setting type to number`),s="number"):s="number";let o="letters"===s?"text":s;if(r&&!a){return returnGroupIntoComponentTypeSeparatedBySpaces({componentType:o})({matchedChildren:e})}return returnBreakStringsIntoComponentTypeBySpaces({componentType:o})({matchedChildren:e})}}),e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return delete e.value,e.nValues={additionalStateVariablesDefined:["childForValue"],returnDependencies:()=>({anythingForSelectedType:{dependencyType:"child",childGroups:["anything"],variableNames:["nValues"],variablesOptional:!0}}),definition({dependencyValues:e}){let t=0,n=[];for(let[r,a]of e.anythingForSelectedType.entries()){let e=Number.isInteger(a.stateValues.nValues)?a.stateValues.nValues:1;t+=e;for(let t=0;t({nValues:{dependencyType:"stateVariable",variableName:"nValues"}}),returnArraySize:({dependencyValues:e})=>[e.nValues],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=t.childForValue[r];n[r]={anythingForSelectedType:{dependencyType:"child",childGroups:["anything"],variableNames:["value","values"],childIndices:[e.child],variablesOptional:!0},valueIndex:{dependencyType:"value",value:e.valueIndex}}}return{globalDependencies:{type:{dependencyType:"stateVariable",variableName:"type"}},dependenciesByKey:n}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n,componentName:r}){let a={};for(let r of n)if(t[r].anythingForSelectedType&&1===t[r].anythingForSelectedType.length){let n,i=t[r].anythingForSelectedType[0];n=i.stateValues.values?i.stateValues.values[t[r].valueIndex]:i.stateValues.value,a[r]=convertValueToType(n,e.type)}return{setValue:{values:a},setCreateComponentOfType:{values:e.type}}}},e}}class ComponentListOfListsWithSelectableType extends ComponentWithSelectableType{static componentType="_componentListOfListsWithSelectableType";static createAttributesObject(){let e=super.createAttributesObject();return e.type={createPrimitiveOfType:"string"},e}static returnSugarInstructions(){let e=[];return e.push({replacementFunction:function({matchedChildren:e,componentAttributes:t,parentAttributes:n}){let r=breakEmbeddedStringsIntoParensPieces({componentList:e,removeParens:!0});if(!0!==r.success)return{success:!1};let a=t.type;return a||(a=n.type),a?["number","letters","math","text","boolean"].includes(a)||(console.warn(`Invalid type ${a}, setting type to number`),a="number"):a="number",{success:!0,newChildren:r.pieces.map((e=>({componentType:"_componentListWithSelectableType",attributes:{type:{primitive:a}},children:e})))}}}),e}static returnChildGroups(){return[{group:"lists",componentTypes:["_componentListWithSelectableType"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return delete e.value,e.nLists={returnDependencies:()=>({listChildren:{dependencyType:"child",childGroups:["lists"]}}),definition:({dependencyValues:e})=>({setValue:{nLists:e.listChildren.length}})},e.lists={isArray:!0,entryPrefixes:["list"],returnArraySizeDependencies:()=>({nLists:{dependencyType:"stateVariable",variableName:"nLists"}}),returnArraySize:({dependencyValues:e})=>[e.nLists],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={listChildren:{dependencyType:"child",childGroups:["lists"],variableNames:["values","type"],childIndices:[n]}};return{globalDependencies:{type:{dependencyType:"stateVariable",variableName:"type"}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};for(let a of n)if(t[a].listChildren&&1===t[a].listChildren.length){let n=t[a].listChildren[0];n.stateValues.type===e.type?r[a]=n.stateValues.values:r[a]=n.stateValues.values.map((t=>convertValueToType(t,e.type)))}return{setValue:{lists:r}}}},e}}function convertValueToType(e,t){if(Array.isArray(e)&&(e=e[0]),"number"===t){if(e instanceof me$3.class){let t=e.evaluate_to_constant();return Number.isFinite(t)||(t=NaN),t}return Number(e)}if("math"===t){if("string"==typeof e)try{return me$3.fromAst(textToAst$1.convert(e))}catch(e){}return convertValueToMathExpression(e)}return"boolean"===t?Boolean(e):String(e)}var ComponentWithSelectableType$1=Object.freeze({__proto__:null,ComponentWithSelectableType:ComponentWithSelectableType,ComponentListWithSelectableType:ComponentListWithSelectableType,ComponentListOfListsWithSelectableType:ComponentListOfListsWithSelectableType});class SideBySide extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="sideBySide";static renderChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.width={createComponentOfType:"_componentSize"},e.widths={createComponentOfType:"_componentSizeList"},e.margins={createComponentOfType:"_componentSizeList"},e.valign={createComponentOfType:"text"},e.valigns={createComponentOfType:"textList"},e}static returnChildGroups(){return[{group:"blocks",componentTypes:["_block"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nPanels={forRenderer:!0,returnDependencies:()=>({blockChildren:{dependencyType:"child",childGroups:["blocks"],skipComponentNames:!0}}),definition:({dependencyValues:e})=>({setValue:{nPanels:e.blockChildren.length},checkForActualChange:{nPanels:!0}})},e.essentialWidths={isArray:!0,entryPrefixes:["essentialWidth"],defaultValueByArrayKey:()=>null,hasEssential:!0,returnArraySizeDependencies:()=>({nPanels:{dependencyType:"stateVariable",variableName:"nPanels"}}),returnArraySize:({dependencyValues:e})=>[e.nPanels],returnArrayDependenciesByKey:()=>({}),arrayDefinitionByKey({arrayKeys:e}){let t={};for(let n of e)t[n]=!0;return{useEssentialOrDefaultValue:{essentialWidths:t}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e}){let t={};for(let n in e.essentialWidths)t[n]=e.essentialWidths[n];return{success:!0,instructions:[{setEssentialValue:"essentialWidths",value:t}]}}},e.allWidthsSpecified={additionalStateVariablesDefined:["widthsAbsolute"],returnDependencies:()=>({nPanels:{dependencyType:"stateVariable",variableName:"nPanels"},widthAttr:{dependencyType:"attributeComponent",attributeName:"width",variableNames:["componentSize"]},widthsAttr:{dependencyType:"attributeComponent",attributeName:"widths",variableNames:["nComponents","componentSizes"]},parentWidths:{dependencyType:"parentStateVariable",parentComponentType:"sbsGroup",variableName:"specifiedWidths"},parentWidthsAbsolute:{dependencyType:"parentStateVariable",parentComponentType:"sbsGroup",variableName:"widthsAbsolute"},essentialWidth:{dependencyType:"stateVariable",variableName:"essentialWidths"}}),definition({dependencyValues:e}){let t,n=[],r=null,a=!1;null!==e.widthsAttr?t=e.widthsAttr.stateValues.nComponents:null!==e.widthAttr?(t=e.nPanels,a=!0):t=0;for(let i=0;iNumber.isFinite(e)?e:null)),{setValue:{allWidthsSpecified:n,widthsAbsolute:r}}}},e.essentialMargins={isArray:!0,entryPrefixes:["essentialMargin"],hasEssential:!0,defaultValueByArrayKey:()=>null,returnArraySizeDependencies:()=>({}),returnArraySize:()=>[2],returnArrayDependenciesByKey:()=>({}),arrayDefinitionByKey({arrayKeys:e}){let t={};for(let n of e)t[n]=!0;return{useEssentialOrDefaultValue:{essentialMargins:t}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e}){let t={};for(let n in e.essentialMargins)t[n]=e.essentialMargins[n];return{success:!0,instructions:[{setEssentialValue:"essentialMargins",value:t}]}}},e.allMarginsSpecified={additionalStateVariablesDefined:["marginsAbsolute"],returnDependencies:()=>({nPanels:{dependencyType:"stateVariable",variableName:"nPanels"},marginsAttr:{dependencyType:"attributeComponent",attributeName:"margins",variableNames:["nComponents","componentSizes"]},parentMargins:{dependencyType:"parentStateVariable",parentComponentType:"sbsGroup",variableName:"specifiedMargins"},parentMarginsAbsolute:{dependencyType:"parentStateVariable",parentComponentType:"sbsGroup",variableName:"marginsAbsolute"},essentialMargins:{dependencyType:"stateVariable",variableName:"essentialMargins"}}),definition({dependencyValues:e}){let t=[],n=null;if(null===e.marginsAttr)if(e.parentMargins){n=e.parentMarginsAbsolute;for(let n=0;n<2;n++)null===e.essentialMargins[n]?t[n]=e.parentMargins[n]:t[n]=e.essentialMargins[n]}else for(let n=0;n<2;n++)t[n]=e.essentialMargins[n];else if(0===e.marginsAttr.stateValues.nComponents)for(let n=0;n<2;n++)t[n]=e.essentialMargins[n];else if(1===e.marginsAttr.stateValues.nComponents){let r=null;e.marginsAttr.stateValues.componentSizes[0]&&(r=e.marginsAttr.stateValues.componentSizes[0].size,Number.isFinite(r)||(r=null),n=Boolean(e.marginsAttr.stateValues.componentSizes[0].isAbsolute)),t=[r,r]}else{let r;if(n=!!e.marginsAttr.stateValues.componentSizes[0]&&Boolean(e.marginsAttr.stateValues.componentSizes[0].isAbsolute),r=!!e.marginsAttr.stateValues.componentSizes[1]&&Boolean(e.marginsAttr.stateValues.componentSizes[1].isAbsolute),r!==n)throw Error("SideBySide is not implemented for absolute measurements");t=e.marginsAttr.stateValues.componentSizes.slice(0,2).map((e=>e&&Number.isFinite(e.size)?e.size:null))}return{setValue:{allMarginsSpecified:t,marginsAbsolute:n}}}},e.absoluteMeasurements={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,returnDependencies:()=>({widthsAbsolute:{dependencyType:"stateVariable",variableName:"widthsAbsolute"},marginsAbsolute:{dependencyType:"stateVariable",variableName:"marginsAbsolute"}}),definition({dependencyValues:e}){let t;if(null===e.widthsAbsolute)t=null!==e.marginsAbsolute&&e.marginsAbsolute;else if(null===e.marginsAbsolute)t=e.widthsAbsolute;else{if(e.widthsAbsolute!==e.marginsAbsolute)throw Error("SideBySide is not implemented for absolute measurements");t=e.widthsAbsolute}if(!0===t)throw Error("SideBySide is not implemented for absolute measurements");return{setValue:{absoluteMeasurements:t}}}},e.allWidths={additionalStateVariablesDefined:["allMargins",{variableName:"gapWidth",public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0}],returnDependencies:()=>({nPanels:{dependencyType:"stateVariable",variableName:"nPanels"},allWidthsSpecified:{dependencyType:"stateVariable",variableName:"allWidthsSpecified"},allMarginsSpecified:{dependencyType:"stateVariable",variableName:"allMarginsSpecified"},absoluteMeasurements:{dependencyType:"stateVariable",variableName:"absoluteMeasurements"}}),definition({dependencyValues:e}){let t=0,n=[...e.allWidthsSpecified],r=[...e.allMarginsSpecified],a=0,i=0;for(let t=0;t=100){let t=100/(a+s);for(let r=0;r0){let t=(100-(a+s))/i;for(let r=0;r0){let t=(100-(a+s))/(o*e.nPanels);for(let e=0;e<2;e++)null===r[e]&&(r[e]=t)}else e.nPanels>1?t=(100-(a+s))/(e.nPanels-1):1===e.nPanels?r[1]=100-(r[0]+n[0]):console.warn("Invalid sideBySide, as it must have at least one block child");return{setValue:{allWidths:n,allMargins:r,gapWidth:t}}}},e.widths={public:!0,isArray:!0,shadowingInstructions:{createComponentOfType:"number"},entryPrefixes:["width"],forRenderer:!0,returnArraySizeDependencies:()=>({nPanels:{dependencyType:"stateVariable",variableName:"nPanels"}}),returnArraySize:({dependencyValues:e})=>[e.nPanels],returnArrayDependenciesByKey({arrayKeys:e}){let t={allWidths:{dependencyType:"stateVariable",variableName:"allWidths"},widthsAttr:{dependencyType:"attributeComponent",attributeName:"widths",variableNames:["nComponents"]},widthAttr:{dependencyType:"attributeComponent",attributeName:"width",variableNames:["componentSize"]},absoluteMeasurements:{dependencyType:"stateVariable",variableName:"absoluteMeasurements"}},n={};for(let t of e){let e=Number(t)+1;n[t]={widthsAttr:{dependencyType:"attributeComponent",attributeName:"widths",variableNames:[`componentSize${e}`]},essentialWidth:{dependencyType:"stateVariable",variableName:`essentialWidth${e}`}}}return{globalDependencies:t,dependenciesByKey:n}},arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t}){let n={};for(let r of t)n[r]=e.allWidths[r];return{setValue:{widths:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,dependencyValuesByKey:n,globalDependencyValues:r,arraySize:a}){let i,s=!1;null!==r.widthsAttr?i=r.widthsAttr.stateValues.nComponents:null!==r.widthAttr?(i=a[0],s=!0):i=0;let o=[];for(let n in e.widths){Number(n)({}),returnArraySize:()=>[2],returnArrayDependenciesByKey({arrayKeys:e}){let t={allMargins:{dependencyType:"stateVariable",variableName:"allMargins"},marginsAttr:{dependencyType:"attributeComponent",attributeName:"margins",variableNames:["componentSize1","componentSize2","nComponents"]},absoluteMeasurements:{dependencyType:"stateVariable",variableName:"absoluteMeasurements"}},n={};for(let t of e){let e=Number(t)+1;n[t]={essentialMargin:{dependencyType:"stateVariable",variableName:`essentialMargin${e}`}}}return{globalDependencies:t,dependenciesByKey:n}},arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t}){let n={};for(let r of t)n[r]=e.allMargins[r];return{setValue:{margins:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyNamesByKey:n}){let r=[];if(null===t.marginsAttr)for(let t in e.margins)r.push({setDependency:n[t].essentialMargin,desiredValue:e.margins[t]});else if(t.marginsAttr.stateValues.componentSize1&&Number.isFinite(t.marginsAttr.stateValues.componentSize1.size)){let n=1===t.marginsAttr.stateValues.nComponents;for(let a in e.margins)n?r.push({setDependency:"marginsAttr",desiredValue:{size:e.margins[a],isAbsolute:t.absoluteMeasurements},variableIndex:0}):r.push({setDependency:"marginsAttr",desiredValue:{size:e.margins[a],isAbsolute:t.absoluteMeasurements},variableIndex:a})}else"0"in e.margins?r.push({setDependency:"marginsAttr",desiredValue:{size:e.margins[0],isAbsolute:t.absoluteMeasurements},variableIndex:0}):r.push({setDependency:"marginsAttr",desiredValue:{size:e.margins[1],isAbsolute:t.absoluteMeasurements},variableIndex:0}),"1"in e.margins&&t.marginsAttr.stateValues.nComponents>1&&r.push({setDependency:"marginsAttr",desiredValue:{size:e.margins[1],isAbsolute:t.absoluteMeasurements},variableIndex:1});return{success:!0,instructions:r}}},e.essentialValigns={isArray:!0,entryPrefixes:["essentialValign"],defaultValueByArrayKey:()=>null,hasEssential:!0,returnArraySizeDependencies:()=>({nPanels:{dependencyType:"stateVariable",variableName:"nPanels"}}),returnArraySize:({dependencyValues:e})=>[e.nPanels],returnArrayDependenciesByKey:()=>({}),arrayDefinitionByKey({arrayKeys:e}){let t={};for(let n of e)t[n]=!0;return{useEssentialOrDefaultValue:{essentialValigns:t}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e}){let t={};for(let n in e.essentialValigns)t[n]=e.essentialValigns[n];return{success:!0,instructions:[{setEssentialValue:"essentialValigns",value:t}]}}},e.valigns={public:!0,isArray:!0,shadowingInstructions:{createComponentOfType:"text"},entryPrefixes:["valign"],forRenderer:!0,returnArraySizeDependencies:()=>({nPanels:{dependencyType:"stateVariable",variableName:"nPanels"}}),returnArraySize:({dependencyValues:e})=>[e.nPanels],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={valignsAttr:{dependencyType:"attributeComponent",attributeName:"valigns",variableNames:[`text${e}`]},parentValign:{dependencyType:"parentStateVariable",parentComponentType:"sbsGroup",variableName:`valign${e}`},parentValignAbsolute:{dependencyType:"parentStateVariable",parentComponentType:"sbsGroup",variableName:`valignAbsolute${e}`},essentialValign:{dependencyType:"stateVariable",variableName:`essentialValign${e}`}}}return{globalDependencies:{valignAttr:{dependencyType:"attributeComponent",attributeName:"valign",variableNames:["value"]},valignsAttr:{dependencyType:"attributeComponent",attributeName:"valigns",variableNames:["nComponents"]}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n,arraySize:r}){let a,i={},s=!1;null!==e.valignsAttr?a=e.valignsAttr.stateValues.nComponents:null!==e.valignAttr?(a=r[0],s=!0):a=0;for(let r of n){let n=Number(r);if(n({sideBySideChildren:{dependencyType:"child",childGroups:["sideBySides"],variableNames:["nPanels"]}}),definition:({dependencyValues:e})=>({setValue:{maxNPanelsPerRow:me$3.math.max(e.sideBySideChildren.map((e=>e.stateValues.nPanels)))},checkForActualChange:{maxNPanelsPerRow:!0}})},e.specifiedWidths={additionalStateVariablesDefined:[{variableName:"widthsAbsoluteArray",isArray:!0}],isArray:!0,entryPrefixes:["specifiedWidth"],hasEssential:!0,defaultValueByArrayKey:()=>null,returnArraySizeDependencies:()=>({maxNPanelsPerRow:{dependencyType:"stateVariable",variableName:"maxNPanelsPerRow"}}),returnArraySize:({dependencyValues:e})=>[e.maxNPanelsPerRow],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={widthsAttr:{dependencyType:"attributeComponent",attributeName:"widths",variableNames:[`componentSize${e}`]}}}return{globalDependencies:{widthAttr:{dependencyType:"attributeComponent",attributeName:"width",variableNames:["componentSize"]},widthsAttr:{dependencyType:"attributeComponent",attributeName:"widths",variableNames:["nComponents"]}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n,arraySize:r}){let a,i={},s={},o={},l=!1;null!==e.widthsAttr?a=e.widthsAttr.stateValues.nComponents:null!==e.widthAttr?(a=r[0],l=!0):a=0;for(let r of n){let n=Number(r);if(n0&&(u.useEssentialOrDefaultValue={specifiedWidths:s}),u},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,globalDependencyValues:n,stateValues:r,arraySize:a}){let i,s=!1;null!==n.widthsAttr?i=n.widthsAttr.stateValues.nComponents:null!==n.widthAttr?(i=a[0],s=!0):i=0;let o=[];for(let n in e.specifiedWidths){Number(n)({widthsAbsoluteArray:{dependencyType:"stateVariable",variableName:"widthsAbsoluteArray"}}),definition({dependencyValues:e}){let t=null;for(let n in e.widthsAbsoluteArray){let r=e.widthsAbsoluteArray[n];if(null!==r)if(r=Boolean(r),null===t)t=r;else if(t!==r)throw Error("SbsGroup is not implemented for absolute measurements")}return{setValue:{widthsAbsolute:t}}}},e.specifiedMargins={additionalStateVariablesDefined:[{variableName:"marginsAbsoluteArray",isArray:!0,entryPrefixes:["marginAbsolute"]}],isArray:!0,entryPrefixes:["specifiedMargin"],hasEssential:!0,defaultValueByArrayKey:()=>null,returnArraySizeDependencies:()=>({}),returnArraySize:()=>[2],returnArrayDependenciesByKey:({arrayKeys:e})=>({globalDependencies:{marginsAttr:{dependencyType:"attributeComponent",attributeName:"margins",variableNames:["componentSize1","componentSize2","nComponents"]}}}),arrayDefinitionByKey({dependencyValuesByKey:e,globalDependencyValues:t,arrayKeys:n}){let r={},a={},i={};if(null===t.marginsAttr||0===t.marginsAttr.stateValues.nComponents)for(let e of n)a[e]=!0,i[e]=null;else if(1===t.marginsAttr.stateValues.nComponents){let e=null,a=null;t.marginsAttr.stateValues.componentSize1&&(e=t.marginsAttr.stateValues.componentSize1.size,Number.isFinite(e)||(e=null),a=Boolean(t.marginsAttr.stateValues.componentSize1.isAbsolute));for(let t of n)r[t]=e,i[t]=a}else for(let e of n)if(t.marginsAttr.stateValues[`componentSize${Number(e)+1}`]){let n=t.marginsAttr.stateValues[`componentSize${Number(e)+1}`].size;Number.isFinite(n)||(n=null);let a=Boolean(t.marginsAttr.stateValues[`componentSize${Number(e)+1}`].isAbsolute);r[e]=n,i[e]=a}let s={setValue:{marginsAbsoluteArray:i,specifiedMargins:r}};return Object.keys(a).length>0&&(s.useEssentialOrDefaultValue={specifiedMargins:a}),s},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,globalDependencyValues:n,stateValues:r}){let a=[];if(null===n.marginsAttr)a.push({setEssentialValue:"specifiedMargins",value:e.specifiedMargins});else if(n.marginsAttr.stateValues.componentSize1&&Number.isFinite(n.marginsAttr.stateValues.componentSize1.size)){let t=1===n.marginsAttr.stateValues.nComponents;for(let n in e.specifiedMargins)t?a.push({setDependency:"marginsAttr",desiredValue:{size:e.specifiedMargins[n],isAbsolute:await r.marginsAbsolute},variableIndex:0}):a.push({setDependency:"marginsAttr",desiredValue:{size:e.specifiedMargins[n],isAbsolute:await r.marginsAbsolute},variableIndex:n})}else"0"in e.specifiedMargins?a.push({setDependency:"marginsAttr",desiredValue:{size:e.specifiedMargins[0],isAbsolute:await r.marginsAbsolute},variableIndex:0}):a.push({setDependency:"marginsAttr",desiredValue:{size:e.specifiedMargins[1],isAbsolute:await r.marginsAbsolute},variableIndex:0}),"1"in e.specifiedMargins&&n.marginsAttr.stateValues.nComponents>1&&a.push({setDependency:"marginsAttr",desiredValue:{size:e.specifiedMargins[1],isAbsolute:await r.marginsAbsolute},variableIndex:1});return{success:!0,instructions:a}}},e.marginsAbsolute={returnDependencies:()=>({marginsAbsoluteArray:{dependencyType:"stateVariable",variableName:"marginsAbsoluteArray"}}),definition({dependencyValues:e}){let t=null;for(let n in e.marginsAbsoluteArray){let r=e.marginsAbsoluteArray[n];if(null!==r)if(r=Boolean(r),null===t)t=r;else if(t!==r)throw Error("SbsGroup is not implemented for absolute measurements")}return{setValue:{marginsAbsolute:t}}}},e.absoluteMeasurements={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({widthsAbsolute:{dependencyType:"stateVariable",variableName:"widthsAbsolute"},marginsAbsolute:{dependencyType:"stateVariable",variableName:"marginsAbsolute"}}),definition({dependencyValues:e}){let t;if(null===e.widthsAbsolute)t=null!==e.marginsAbsolute&&e.marginsAbsolute;else if(null===e.marginsAbsolute)t=e.widthsAbsolute;else{if(e.widthsAbsolute!==e.marginsAbsolute)throw Error("SbsGroup is not implemented for absolute measurements");t=e.widthsAbsolute}if(!0===t)throw Error("SbsGroup is not implemented for absolute measurements");return{setValue:{absoluteMeasurements:t}}}},e.allWidths={additionalStateVariablesDefined:["allMargins",{variableName:"gapWidth",public:!0,shadowingInstructions:{createComponentOfType:"number"}}],returnDependencies:()=>({maxNPanelsPerRow:{dependencyType:"stateVariable",variableName:"maxNPanelsPerRow"},specifiedWidths:{dependencyType:"stateVariable",variableName:"specifiedWidths"},specifiedMargins:{dependencyType:"stateVariable",variableName:"specifiedMargins"},absoluteMeasurements:{dependencyType:"stateVariable",variableName:"absoluteMeasurements"}}),definition({dependencyValues:e}){let t=0,n=[...e.specifiedWidths],r=[...e.specifiedMargins],a=0,i=0;for(let t=0;t=100){let t=100/(a+s);for(let r=0;r0){let t=(100-(a+s))/i;for(let r=0;r0){let t=(100-(a+s))/(o*e.maxNPanelsPerRow);for(let e=0;e<2;e++)null===r[e]&&(r[e]=t)}else e.maxNPanelsPerRow>1?t=(100-(a+s))/(e.maxNPanelsPerRow-1):1===e.maxNPanelsPerRow?r[1]=100-(r[0]+n[0]):console.warn("Invalid sideBySide, as it must have at least one block child");return{setValue:{allWidths:n,allMargins:r,gapWidth:t}}}},e.widths={public:!0,isArray:!0,shadowingInstructions:{createComponentOfType:"number"},entryPrefixes:["width"],returnArraySizeDependencies:()=>({maxNPanelsPerRow:{dependencyType:"stateVariable",variableName:"maxNPanelsPerRow"}}),returnArraySize:({dependencyValues:e})=>[e.maxNPanelsPerRow],returnArrayDependenciesByKey({arrayKeys:e}){let t={allWidths:{dependencyType:"stateVariable",variableName:"allWidths"}},n={};for(let t of e){let e=Number(t)+1;n[t]={specifiedWidth:{dependencyType:"stateVariable",variableName:`specifiedWidth${e}`}}}return{globalDependencies:t,dependenciesByKey:n}},arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t}){let n={};for(let r of t)n[r]=e.allWidths[r];return{setValue:{widths:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t}){let n=[];for(let r in e.widths)n.push({setDependency:t[r].specifiedWidth,desiredValue:e.widths[r],variableIndex:0});return{success:!0,instructions:n}}},e.margins={public:!0,isArray:!0,shadowingInstructions:{createComponentOfType:"number"},entryPrefixes:["margin"],returnArraySizeDependencies:()=>({}),returnArraySize:()=>[2],returnArrayDependenciesByKey({arrayKeys:e}){let t={allMargins:{dependencyType:"stateVariable",variableName:"allMargins"}},n={};for(let t of e){let e=Number(t)+1;n[t]={specifiedMargin:{dependencyType:"stateVariable",variableName:`specifiedMargin${e}`}}}return{globalDependencies:t,dependenciesByKey:n}},arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t}){let n={};for(let r of t)n[r]=e.allMargins[r];return{setValue:{margins:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t}){let n=[];for(let r in e.margins)n.push({setDependency:t[r].specifiedMargin,desiredValue:e.margins[r],variableIndex:0});return{success:!0,instructions:n}}},e.valigns={public:!0,isArray:!0,shadowingInstructions:{createComponentOfType:"text"},entryPrefixes:["valign"],hasEssential:!0,defaultValueByArrayKey:()=>"top",returnArraySizeDependencies:()=>({maxNPanelsPerRow:{dependencyType:"stateVariable",variableName:"maxNPanelsPerRow"}}),returnArraySize:({dependencyValues:e})=>[e.maxNPanelsPerRow],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={valignsAttr:{dependencyType:"attributeComponent",attributeName:"valigns",variableNames:[`text${e}`]}}}return{globalDependencies:{valignAttr:{dependencyType:"attributeComponent",attributeName:"valign",variableNames:["value"]},valignsAttr:{dependencyType:"attributeComponent",attributeName:"valigns",variableNames:["nComponents"]}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n,arraySize:r}){let a,i={},s={},o=!1;null!==e.valignsAttr?a=e.valignsAttr.stateValues.nComponents:null!==e.valignAttr?(a=r[0],o=!0):a=0;for(let r of n){let n=Number(r);if(n0&&(l.setValue={valigns:i}),Object.keys(s).length>0&&(l.useEssentialOrDefaultValue={valigns:s}),l},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,globalDependencyValues:n,arraySize:r}){let a,i=!1;null!==n.valignsAttr?a=n.valignsAttr.stateValues.nComponents:null!==n.valignAttr?(a=r[0],i=!0):a=0;let s=[];for(let n in e.valigns){let r=e.valigns[n].toLowerCase();["top","middle","bottom"].includes(r)&&(Number(n)({stringTextChildren:{dependencyType:"child",childGroups:["stringsTexts"],variableNames:["value"]},hChildren:{dependencyType:"child",childGroups:["hs"],variableNames:["value"]}}),definition({dependencyValues:e}){let t;if(e.hChildren.length>0)t=e.hChildren.map((e=>e.stateValues.value));else{let n="";for(let t of e.stringTextChildren)n+="string"==typeof t?t:t.stateValues.value;t=[n]}return{setValue:{terms:t}}}},e}}var Indexing=Object.freeze({__proto__:null,H:H$2,Idx:Idx});class Div extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="div";static rendererType="containerBlock";static renderChildren=!0;static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class Span extends InlineComponent{static componentType="span";static rendererType="containerInline";static renderChildren=!0;static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}}var Divisions=Object.freeze({__proto__:null,Div:Div,Span:Span});class Pre extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="pre";static renderChildren=!0;static includeBlankStringChildren=!0;static returnChildGroups(){return[{group:"allChildren",componentTypes:["_base"]}]}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class DisplayDoenetML extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="displayDoenetML";static rendererType="text";static includeBlankStringChildren=!0;static returnChildGroups(){return[{group:"allChildren",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.value={returnDependencies:()=>({childrenDoenetML:{dependencyType:"doenetML",displayOnlyChildren:!0}}),definition:({dependencyValues:e})=>({setValue:{value:e.childrenDoenetML}})},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:({dependencyValues:e})=>({setValue:{text:e.value}})},e}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}var Verbatim=Object.freeze({__proto__:null,Pre:Pre,DisplayDoenetML:DisplayDoenetML});class Paginator extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{setPage:this.setPage.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="paginator";static rendererType="containerBlock";static renderChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.initialPage={createComponentOfType:"integer",createStateVariable:"initialPage",defaultValue:1},e}static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nPages={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({children:{dependencyType:"child",childGroups:["anything"]}}),definition:({dependencyValues:e})=>({setValue:{nPages:e.children.length}})},e.currentPage={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,returnDependencies:()=>({initialPage:{dependencyType:"stateVariable",variableName:"initialPage"},nPages:{dependencyType:"stateVariable",variableName:"nPages"}}),definition:({dependencyValues:e})=>({useEssentialOrDefaultValue:{currentPage:{get defaultValue(){let t=e.initialPage;return Number.isInteger(t)?Math.max(1,Math.min(e.nPages,t)):1}}}}),async inverseDefinition({desiredStateVariableValues:e,stateValues:t,sourceInformation:n={}}){if(!n.fromSetPage)return{success:!1};let r=Number(e.currentPage);return Number.isInteger(r)?(r=Math.max(1,Math.min(await t.nPages,r)),{success:!0,instructions:[{setEssentialValue:"currentPage",value:r}]}):{success:!1}}},e.childIndicesToRender={returnDependencies:()=>({currentPage:{dependencyType:"stateVariable",variableName:"currentPage"}}),definition:({dependencyValues:e})=>({setValue:{childIndicesToRender:[e.currentPage-1]}}),markStale:()=>({updateRenderedChildren:!0})},e}async setPage({number:e,actionId:t}){if(!Number.isInteger(e))return void this.coreFunctions.resolveAction({actionId:t});let n=Math.max(1,Math.min(await this.stateValues.nPages,e)),r=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"currentPage",value:n,sourceInformation:{fromSetPage:!0}}];await this.coreFunctions.performUpdate({updateInstructions:r,actionId:t,event:{verb:"selected",object:{componentName:this.componentName,componentType:this.componentType},result:{response:n,responseText:n.toString()}}})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class PaginatorControls extends BlockComponent{constructor(e){super(e),this.externalActions={},Object.defineProperty(this.externalActions,"setPage",{enumerable:!0,get:async function(){let e=await this.stateValues.paginatorComponentName;return e?{componentName:e,actionName:"setPage"}:void 0}.bind(this)})}static componentType="paginatorControls";static renderChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.previousLabel={createComponentOfType:"text",createStateVariable:"previousLabel",defaultValue:"Previous",forRenderer:!0,public:!0},e.nextLabel={createComponentOfType:"text",createStateVariable:"nextLabel",defaultValue:"Next",forRenderer:!0,public:!0},e.pageLabel={createComponentOfType:"text",createStateVariable:"pageLabel",defaultValue:"Page",forRenderer:!0,public:!0},e.paginator={createTargetComponentNames:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.paginatorComponentName={returnDependencies:()=>({paginator:{dependencyType:"attributeTargetComponentNames",attributeName:"paginator"}}),definition({dependencyValues:e}){let t;return t=1===e.paginator?.length?e.paginator[0].absoluteName:null,{setValue:{paginatorComponentName:t}}}},e.currentPage={forRenderer:!0,stateVariablesDeterminingDependencies:["paginatorComponentName"],returnDependencies:({stateValues:e})=>e.paginatorComponentName?{paginatorPage:{dependencyType:"stateVariable",componentName:e.paginatorComponentName,variableName:"currentPage"}}:{},definition:({dependencyValues:e})=>"paginatorPage"in e?{setValue:{currentPage:e.paginatorPage}}:{setValue:{currentPage:1}}},e.nPages={forRenderer:!0,stateVariablesDeterminingDependencies:["paginatorComponentName"],returnDependencies:({stateValues:e})=>e.paginatorComponentName?{paginatorNPages:{dependencyType:"stateVariable",componentName:e.paginatorComponentName,variableName:"nPages"}}:{},definition:({dependencyValues:e})=>"paginatorNPages"in e?{setValue:{nPages:e.paginatorNPages}}:{setValue:{nPages:1}}},e}}var Paginator$1=Object.freeze({__proto__:null,Paginator:Paginator,PaginatorControls:PaginatorControls});class Input extends InlineComponent{static componentType="_input";static createAttributesObject(){let e=super.createAttributesObject();return e.collaborateGroups={createComponentOfType:"collaborateGroups",createStateVariable:"collaborateGroups",defaultValue:null,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nValues={returnDependencies:()=>({}),definition:()=>({setValue:{nValues:1}})},e.answerAncestor={returnDependencies:()=>({answerAncestor:{dependencyType:"ancestor",componentType:"answer",variableNames:["delegateCheckWorkToInput","justSubmitted","creditAchieved","showCorrectness","numberOfAttemptsLeft"]}}),definition:function({dependencyValues:e}){return{setValue:{answerAncestor:e.answerAncestor}}}},e.includeCheckWork={forRenderer:!0,returnDependencies:()=>({answerAncestor:{dependencyType:"stateVariable",variableName:"answerAncestor"}}),definition:function({dependencyValues:e}){let t=!1;return e.answerAncestor&&(t=e.answerAncestor.stateValues.delegateCheckWorkToInput),{setValue:{includeCheckWork:t}}}},e.suppressCheckwork={forRenderer:!0,returnDependencies:()=>({autoSubmit:{dependencyType:"flag",flagName:"autoSubmit"}}),definition:({dependencyValues:e})=>({setValue:{suppressCheckwork:e.autoSubmit}})},e.creditAchieved={defaultValue:0,public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies:()=>({answerAncestor:{dependencyType:"stateVariable",variableName:"answerAncestor"}}),definition:function({dependencyValues:e}){let t=0;return e.answerAncestor&&(t=e.answerAncestor.stateValues.creditAchieved),{setValue:{creditAchieved:t}}}},e.valueHasBeenValidated={forRenderer:!0,returnDependencies:()=>({answerAncestor:{dependencyType:"stateVariable",variableName:"answerAncestor"}}),definition:function({dependencyValues:e}){let t=!1;return e.answerAncestor&&e.answerAncestor.stateValues.justSubmitted&&(t=!0),{setValue:{valueHasBeenValidated:t}}}},e.showCorrectness={forRenderer:!0,returnDependencies:()=>({showCorrectnessFlag:{dependencyType:"flag",flagName:"showCorrectness"},answerAncestor:{dependencyType:"stateVariable",variableName:"answerAncestor"}}),definition({dependencyValues:e}){let t;return t=e.answerAncestor?e.answerAncestor.stateValues.showCorrectness:!1!==e.showCorrectnessFlag,{setValue:{showCorrectness:t}}}},e.numberOfAttemptsLeft={forRenderer:!0,returnDependencies:()=>({answerAncestor:{dependencyType:"stateVariable",variableName:"answerAncestor"}}),definition({dependencyValues:e}){let t;return t=e.answerAncestor?e.answerAncestor.stateValues.numberOfAttemptsLeft:1/0,{setValue:{numberOfAttemptsLeft:t}}}},e}}class MatrixInput extends Input{constructor(e){super(e),Object.assign(this.actions,{updateNumRows:this.updateNumRows.bind(this),updateNumColumns:this.updateNumColumns.bind(this)}),this.externalActions={},Object.defineProperty(this.externalActions,"submitAnswer",{enumerable:!0,get:async function(){let e=await this.stateValues.answerAncestor;return null!==e?{componentName:e.componentName,actionName:"submitAnswer"}:void 0}.bind(this)})}static componentType="matrixInput";static variableForPlainMacro="value";static variableForPlainCopy="value";static processWhenJustUpdatedForNewComponent=!0;static renderChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.numRows={createComponentOfType:"integer",createStateVariable:"numRowsPreliminary",defaultValue:1,transformNonFiniteTo:0},e.numColumns={createComponentOfType:"integer",createStateVariable:"numColumnsPreliminary",defaultValue:1,transformNonFiniteTo:0},e.showSizeControls={createComponentOfType:"boolean",createStateVariable:"showSizeControls",defaultValue:!0,public:!0,forRenderer:!0},e.defaultEntry={createComponentOfType:"math",createStateVariable:"defaultEntry",defaultValue:me$3.fromAst("_")},e.prefill={createComponentOfType:"math",createStateVariable:"prefill",defaultValue:me$3.fromAst("_"),public:!0,copyComponentAttributesForCreatedComponent:["format","functionSymbols","splitSymbols","parseScientificNotation"]},e.format={createComponentOfType:"text",createStateVariable:"format",defaultValue:"text",public:!0},e.functionSymbols={createComponentOfType:"textList",createStateVariable:"functionSymbols",defaultValue:["f","g"],public:!0},e.splitSymbols={createComponentOfType:"boolean",createStateVariable:"splitSymbols",defaultValue:!0,public:!0},e.parseScientificNotation={createComponentOfType:"boolean",createStateVariable:"parseScientificNotation",defaultValue:!1,public:!0},e.displayDigits={createComponentOfType:"integer",createStateVariable:"displayDigits",defaultValue:10,public:!0},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.bindValueTo={createComponentOfType:"math"},e.unionFromU={createComponentOfType:"boolean",createStateVariable:"unionFromU",defaultValue:!1,public:!0},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e,componentAttributes:t}){if(e.length>0)return{success:!1};return{success:!0,newChildren:[{componentType:"matrixInputGrid"}]}}}),e}static returnChildGroups(){return[{group:"matrixComponentInputs",componentTypes:["matrixComponentInput"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.valueOriginal={hasEssential:!0,shadowVariable:!0,returnDependencies:()=>({bindValueTo:{dependencyType:"attributeComponent",attributeName:"bindValueTo",variableNames:["value"]},prefill:{dependencyType:"stateVariable",variableName:"prefill"}}),set:convertValueToMathExpression,definition:function({dependencyValues:e}){return e.bindValueTo?{setValue:{valueOriginal:e.bindValueTo.stateValues.value}}:{useEssentialOrDefaultValue:{valueOriginal:{defaultValue:e.prefill}}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){return t.bindValueTo?{success:!0,instructions:[{setDependency:"bindValueTo",desiredValue:e.valueOriginal,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"valueOriginal",value:e.valueOriginal}]}}},e.immediateValueOriginal={hasEssential:!0,shadowVariable:!0,returnDependencies:()=>({valueOriginal:{dependencyType:"stateVariable",variableName:"valueOriginal"}}),set:convertValueToMathExpression,definition:function({dependencyValues:e,changes:t,justUpdatedForNewComponent:n}){return t.valueOriginal&&!n?{setValue:{immediateValueOriginal:e.valueOriginal},setEssentialValue:{immediateValueOriginal:e.valueOriginal}}:{useEssentialOrDefaultValue:{immediateValueOriginal:{defaultValue:e.valueOriginal}}}},inverseDefinition:function({desiredStateVariableValues:e,initialChange:t,shadowedVariable:n}){let r=[{setEssentialValue:"immediateValueOriginal",value:e.immediateValueOriginal}];return t||n||r.push({setDependency:"valueOriginal",desiredValue:e.immediateValueOriginal}),{success:!0,instructions:r}}},e.haveBoundValue={returnDependencies:()=>({bindValueTo:{dependencyType:"attributeComponent",attributeName:"bindValueTo"}}),definition:({dependencyValues:e})=>({setValue:{haveBoundValue:null!==e.bindValueTo}})},e.numRows={public:!0,shadowingInstructions:{createComponentOfType:"integer"},forRenderer:!0,returnDependencies:()=>({numRowsPreliminary:{dependencyType:"stateVariable",variableName:"numRowsPreliminary"},valueOriginal:{dependencyType:"stateVariable",variableName:"valueOriginal"},haveBoundValue:{dependencyType:"stateVariable",variableName:"haveBoundValue"}}),definition({dependencyValues:e,usedDefault:t}){let n=e.numRowsPreliminary;if(t.numRowsPreliminary||e.haveBoundValue){let t=e.valueOriginal.tree;if(n=1,Array.isArray(t)){let e=t[0];"matrix"===e?n=t[1][1]:vectorOperators.includes(e)&&(n=t.length-1)}}return{setValue:{numRows:n}}},async inverseDefinition({desiredStateVariableValues:e,dependencyValues:t,stateValues:n}){let r=e.numRows;if(!Number.isInteger(r))return{success:!1};r=Math.max(0,r);let a=[{setDependency:"numRowsPreliminary",desiredValue:r}];if(t.haveBoundValue){let e=t.valueOriginal.tree,i=(await n.defaultEntry).tree;if(1===await n.numColumns&&Array.isArray(e)&&vectorOperators.includes(e[0])){let t=e.length-1;if(rt){let s=deepClone(e),o=await n.accumulatedComponents;for(let e=t;e({numColumnsPreliminary:{dependencyType:"stateVariable",variableName:"numColumnsPreliminary"},valueOriginal:{dependencyType:"stateVariable",variableName:"valueOriginal"},haveBoundValue:{dependencyType:"stateVariable",variableName:"haveBoundValue"}}),definition({dependencyValues:e,usedDefault:t}){let n=e.numColumnsPreliminary;if(t.numColumnsPreliminary||e.haveBoundValue){let t=e.valueOriginal.tree;if(n=1,Array.isArray(t)){let e=t[0];"matrix"===e?n=t[1][2]:Array.isArray(t[1])&&vectorOperators.includes(t[1][0])&&("^"===e&&"T"===t[2]||"prime"===e)&&(n=t[1].length-1)}}return{setValue:{numColumns:n}}},async inverseDefinition({desiredStateVariableValues:e,dependencyValues:t,stateValues:n}){let r=e.numColumns;if(!Number.isInteger(r))return{success:!1};r=Math.max(0,r);let a=[{setDependency:"numColumnsPreliminary",desiredValue:r}];if(t.haveBoundValue){let e=(await n.defaultEntry).tree,i=t.valueOriginal.tree,s=i[0];if(Array.isArray(i[1])&&vectorOperators.includes(i[1][0])&&("^"===s&&"T"===i[2]||"prime"===s)){let t=i[1].length-1;if(rt){let s=deepClone(i),o=(await n.accumulatedComponents)[0];o||(o=[]);for(let n=t;n({valueOriginal:{dependencyType:"stateVariable",variableName:"valueOriginal"}}),definition({dependencyValues:e,previousValues:t}){let n=[];t.accumulatedComponents&&(n=deepClone(t.accumulatedComponents));let r=e.valueOriginal.tree;if(Array.isArray(r)){let e=r[0];if("matrix"===e){let e=r[2];for(let[t,r]of e.slice(1).entries()){let e=n[t];e||(e=n[t]=[]);for(let[t,n]of r.slice(1).entries())e[t]=n}return{setValue:{accumulatedComponents:n}}}if(vectorOperators.includes(e)){for(let[e,t]of r.slice(1).entries()){let r=n[e];r||(r=n[e]=[]),r[0]=t}return{setValue:{accumulatedComponents:n}}}if(Array.isArray(r[1])&&vectorOperators.includes(r[1][0])&&("^"===e&&"T"===r[2]||"prime"===e)){let e=n[0];e||(e=n[0]=[]);for(let[t,n]of r[1].slice(1).entries())e[t]=n;return{setValue:{accumulatedComponents:n}}}}let a=n[0];return a||(a=n[0]=[]),a[0]=r,{setValue:{accumulatedComponents:n}}}},e.componentValues={isArray:!0,entryPrefixes:["componentValue"],nDimensions:2,returnArraySizeDependencies:()=>({numRows:{dependencyType:"stateVariable",variableName:"numRows"},numColumns:{dependencyType:"stateVariable",variableName:"numColumns"}}),returnArraySize:({dependencyValues:e})=>[e.numRows,e.numColumns],returnArrayDependenciesByKey:()=>({globalDependencies:{valueOriginal:{dependencyType:"stateVariable",variableName:"valueOriginal"},numRows:{dependencyType:"stateVariable",variableName:"numRows"},numColumns:{dependencyType:"stateVariable",variableName:"numColumns"},accumulatedComponents:{dependencyType:"stateVariable",variableName:"accumulatedComponents"},defaultEntry:{dependencyType:"stateVariable",variableName:"defaultEntry"}}}),arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t}){let n=e.valueOriginal.tree,r=e.accumulatedComponents,a=e.numRows,i=e.numColumns;if(Array.isArray(n)){let t=n[0];if("matrix"===t){if(n[1][1]===a&&n[1][2]===i){let e={},t=n[2];for(let n=0;ns)for(let t=0;tt)for(let n=t;n[...e]));else{let e=t.valueOriginal.tree;if(o){if(a=e.slice(1,1+i).map((e=>[e])),a.length1)for(let e=0;e1)for(let e=1;ee.slice(1,s+1))),a[0].length1&&a[0].push(...Array(s-1).fill("_")),i>1)for(let e=1;ee[0]))]);return{success:!0,instructions:[{setDependency:"valueOriginal",desiredValue:r,treatAsInitialChange:n}]}}if(1===i&&l){let e=t.valueOriginal.tree,r=e[0],i=[e[1][0],...a[0]];return i="^"===r?me$3.fromAst(["^",i,"T"]):me$3.fromAst(["prime",i]),{success:!0,instructions:[{setDependency:"valueOriginal",desiredValue:i,treatAsInitialChange:n}]}}{let e=["matrix",["tuple",t.numRows,t.numColumns],["tuple",...a.map((e=>["tuple",...e]))]];return{success:!0,instructions:[{setDependency:"valueOriginal",desiredValue:me$3.fromAst(e),treatAsInitialChange:n}]}}}},e.componentImmediateValues={isArray:!0,entryPrefixes:["componentImmediateValue"],nDimensions:2,returnArraySizeDependencies:()=>({numRows:{dependencyType:"stateVariable",variableName:"numRows"},numColumns:{dependencyType:"stateVariable",variableName:"numColumns"}}),returnArraySize:({dependencyValues:e})=>[e.numRows,e.numColumns],returnArrayDependenciesByKey:()=>({globalDependencies:{immediateValueOriginal:{dependencyType:"stateVariable",variableName:"immediateValueOriginal"},numRows:{dependencyType:"stateVariable",variableName:"numRows"},numColumns:{dependencyType:"stateVariable",variableName:"numColumns"},accumulatedComponents:{dependencyType:"stateVariable",variableName:"accumulatedComponents"},defaultEntry:{dependencyType:"stateVariable",variableName:"defaultEntry"}}}),arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t}){let n=e.immediateValueOriginal.tree,r=e.accumulatedComponents,a=e.numRows,i=e.numColumns;if(Array.isArray(n)){let t=n[0];if("matrix"===t){if(n[1][1]===a&&n[1][2]===i){let e={},t=n[2];for(let n=0;ns)for(let t=0;tt)for(let n=t;n[...e]));else{let e=t.immediateValueOriginal.tree;if(o){if(a=e.slice(1,1+i).map((e=>[e])),a.length1)for(let e=0;e1)for(let e=1;ee.slice(1,s+1))),a[0].length1&&a[0].push(...Array(s-1).fill("_")),i>1)for(let e=1;ee[0]))]);return{success:!0,instructions:[{setDependency:"immediateValueOriginal",desiredValue:r,treatAsInitialChange:n}]}}if(1===i&&l){let e=t.immediateValueOriginal.tree,r=e[0],i=[e[1][0],...a[0]];return i="^"===r?me$3.fromAst(["^",i,"T"]):me$3.fromAst(["prime",i]),{success:!0,instructions:[{setDependency:"immediateValueOriginal",desiredValue:i,treatAsInitialChange:n}]}}{let e=["matrix",["tuple",t.numRows,t.numColumns],["tuple",...a.map((e=>["tuple",...e]))]];return{success:!0,instructions:[{setDependency:"immediateValueOriginal",desiredValue:me$3.fromAst(e),treatAsInitialChange:n}]}}}},e.componentValuesForDisplay={isArray:!0,entryPrefixes:["componentValueForDisplay"],nDimensions:2,forRenderer:!0,returnArraySizeDependencies:()=>({numRows:{dependencyType:"stateVariable",variableName:"numRows"},numColumns:{dependencyType:"stateVariable",variableName:"numColumns"}}),returnArraySize:({dependencyValues:e})=>[e.numRows,e.numColumns],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let[e,r]=n.split(","),a=Number(e)+1+"_"+(Number(r)+1);t[n]={componentValue:{dependencyType:"stateVariable",variableName:`componentValue${a}`}}}return{globalDependencies:{displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n,usedDefault:r}){let a={};for(let i of n){let n=roundForDisplay({value:t[i].componentValue,dependencyValues:e,usedDefault:r});a[i]=n}return{setValue:{componentValuesForDisplay:a}}}},e.value={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]},returnDependencies:()=>({componentValues:{dependencyType:"stateVariable",variableName:"componentValues"},numRows:{dependencyType:"stateVariable",variableName:"numRows"},numColumns:{dependencyType:"stateVariable",variableName:"numColumns"},valueOriginal:{dependencyType:"stateVariable",variableName:"valueOriginal"}}),definition({dependencyValues:e}){let t=e.numRows,n=e.numColumns,r=["matrix",["tuple",t,n]],a=r[2]=["tuple"];for(let r=0;re[1]))]);return{success:!0,instructions:[{setDependency:"valueOriginal",desiredValue:e}]}}}}else if(1===t.numRows){let e=t.valueOriginal.tree;if(Array.isArray(e)){let t=e[0];if(Array.isArray(e[1])&&vectorOperators.includes(e[1][0])&&("^"===t&&"T"===e[2]||"prime"===t)){let r=[e[1][0],...n[2][1].slice(1)];return r="^"===t?me$3.fromAst(["^",r,"T"]):me$3.fromAst(["prime",r]),{success:!0,instructions:[{setDependency:"valueOriginal",desiredValue:r}]}}}}return{success:!0,instructions:[{setDependency:"valueOriginal",desiredValue:e.value}]}}return{success:!1}}},e.immediateValue={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]},returnDependencies:()=>({componentImmediateValues:{dependencyType:"stateVariable",variableName:"componentImmediateValues"},numRows:{dependencyType:"stateVariable",variableName:"numRows"},numColumns:{dependencyType:"stateVariable",variableName:"numColumns"},immediateValueOriginal:{dependencyType:"stateVariable",variableName:"immediateValueOriginal"}}),definition({dependencyValues:e}){let t=e.numRows,n=e.numColumns,r=["matrix",["tuple",t,n]],a=r[2]=["tuple"];for(let r=0;re[1]))]);return{success:!0,instructions:[{setDependency:"immediateValueOriginal",desiredValue:e}]}}}}else if(1===t.numRows){let e=t.immediateValueOriginal.tree;if(Array.isArray(e)){let t=e[0];if(Array.isArray(e[1])&&vectorOperators.includes(e[1][0])&&("^"===t&&"T"===e[2]||"prime"===t)){let r=[e[1][0],...n[2][1].slice(1)];return r="^"===t?me$3.fromAst(["^",r,"T"]):me$3.fromAst(["prime",r]),{success:!0,instructions:[{setDependency:"immediateValueOriginal",desiredValue:r}]}}}}return{success:!0,instructions:[{setDependency:"immediateValueOriginal",desiredValue:e.immediateValue}]}}return{success:!1}}},e.valueForDisplay={forRenderer:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"}}),definition:function({dependencyValues:e,usedDefault:t}){return{setValue:{valueForDisplay:roundForDisplay({value:e.value,dependencyValues:e,usedDefault:t})}}}},e.componentType={returnDependencies:()=>({}),definition:()=>({setValue:{componentType:"matrix"}})},e}async updateRawValues({rawRendererValues:e,transient:t=!1,actionId:n}){if(!await this.stateValues.disabled)return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rawRendererValues",value:e}],transient:t,actionId:n});this.coreFunctions.resolveAction({actionId:n})}async updateNumRows({numRows:e,actionId:t}){if(!await this.stateValues.disabled)return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"numRows",value:e}],actionId:t});this.coreFunctions.resolveAction({actionId:t})}async updateNumColumns({numColumns:e,actionId:t}){if(!await this.stateValues.disabled)return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"numColumns",value:e}],actionId:t});this.coreFunctions.resolveAction({actionId:t})}static adapters=[{stateVariable:"value",stateVariablesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]}]}class MatrixInputGrid extends CompositeComponent{static componentType="matrixInputGrid";static stateVariableToEvaluateAfterReplacements="readyToExpandWhenResolved";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numRows={returnDependencies:()=>({parentNumRows:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"numRows"}}),definition:({dependencyValues:e})=>({setValue:{numRows:e.parentNumRows}})},e.numColumns={returnDependencies:()=>({parentNumColumns:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"numColumns"}}),definition:({dependencyValues:e})=>({setValue:{numColumns:e.parentNumColumns}})},e.readyToExpandWhenResolved={returnDependencies:()=>({numRows:{dependencyType:"stateVariable",variableName:"numRows"},numColumns:{dependencyType:"stateVariable",variableName:"numColumns"}}),markStale:()=>({updateReplacements:!0}),definition:()=>({setValue:{readyToExpandWhenResolved:!0}})},e}static async createSerializedReplacements({component:e,componentInfoObjects:t,flags:n,workspace:r}){let a=[],i=await e.stateValues.numRows;r.previousNumRows=i;for(let e=0;eo&&(u=l-o,e.replacementsToWithhold>0))if(e.replacementsToWithhold>=u){i=e.replacementsToWithhold-u,o+=u,u=0;let t={changeType:"changeReplacementsToWithhold",replacementsToWithhold:i};s.push(t)}else u-=e.replacementsToWithhold,o+=e.replacementsToWithhold,i=0;if(u>0){let e=[];for(let t=o;t({}),definition:()=>({useEssentialOrDefaultValue:{rowInd:!0}})},e.numColumns={returnDependencies:()=>({parentNumColumns:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"numColumns"}}),definition:({dependencyValues:e})=>({setValue:{numColumns:e.parentNumColumns}})},e.readyToExpandWhenResolved={returnDependencies:()=>({numColumns:{dependencyType:"stateVariable",variableName:"numColumns"}}),markStale:()=>({updateReplacements:!0}),definition:()=>({setValue:{readyToExpandWhenResolved:!0}})},e}j;static async createSerializedReplacements({component:e,componentInfoObjects:t,flags:n,workspace:r}){let a=[],i=await e.stateValues.numColumns,s=await e.stateValues.rowInd;r.previousNumColumns=i;for(let e=0;eo&&(c=l-o,e.replacementsToWithhold>0))if(e.replacementsToWithhold>=c){i=e.replacementsToWithhold-c,o+=c,c=0;let t={changeType:"changeReplacementsToWithhold",replacementsToWithhold:i};s.push(t)}else c-=e.replacementsToWithhold,o+=e.replacementsToWithhold,i=0;if(c>0){let e=[];for(let t=o;t({}),definition:()=>({useEssentialOrDefaultValue:{rowInd:!0}})},e.colInd={hasEssential:!0,defaultValue:null,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{colInd:!0}})},e.format={returnDependencies:()=>({parentFormat:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"format"}}),definition:({dependencyValues:e})=>({setValue:{format:e.parentFormat}})},e.functionSymbols={returnDependencies:()=>({parentFunctionSymbols:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"functionSymbols"}}),definition:({dependencyValues:e})=>({setValue:{functionSymbols:e.parentFunctionSymbols}})},e.splitSymbols={returnDependencies:()=>({parentSplitSymbols:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"splitSymbols"}}),definition:({dependencyValues:e})=>({setValue:{splitSymbols:e.parentSplitSymbols}})},e.parseScientificNotation={returnDependencies:()=>({parentParseScientificNotation:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"parseScientificNotation"}}),definition:({dependencyValues:e})=>({setValue:{parseScientificNotation:e.parentParseScientificNotation}})},e.displayDigits={returnDependencies:()=>({parentDisplayDigits:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"displayDigits"}}),definition({dependencyValues:e,usedDefault:t}){let n={setValue:{displayDigits:e.parentDisplayDigits}};return t.parentDisplayDigits&&(n.markAsUsedDefault={displayDigits:!0}),n}},e.displayDecimals={returnDependencies:()=>({parentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"displayDecimals"}}),definition({dependencyValues:e,usedDefault:t}){let n={setValue:{displayDecimals:e.parentDisplayDecimals}};return t.parentDisplayDecimals&&(n.markAsUsedDefault={displayDecimals:!0}),n}},e.displaySmallAsZero={returnDependencies:()=>({parentDisplaySmallAsZero:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"displaySmallAsZero"}}),definition:({dependencyValues:e})=>({setValue:{displaySmallAsZero:e.parentDisplaySmallAsZero}})},e.unionFromU={returnDependencies:()=>({parentUnionFromU:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"unionFromU"}}),definition:({dependencyValues:e})=>({setValue:{unionFromU:e.parentUnionFromU}})},e.value={stateVariablesDeterminingDependencies:["rowInd","colInd"],returnDependencies:({stateValues:e})=>{let t="";return null!==e.rowInd&&null!==e.colInd&&(t=`${e.rowInd+1}_${e.colInd+1}`),{parentComponentValue:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:`componentValue${t}`}}},definition:function({dependencyValues:e}){return e.parentComponentValue?{setValue:{value:e.parentComponentValue}}:{setValue:{value:me$3.fromAst("_")}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){return{success:!0,instructions:[{setDependency:"parentComponentValue",desiredValue:e.value}]}}},e.immediateValue={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]},stateVariablesDeterminingDependencies:["rowInd","colInd"],returnDependencies:({stateValues:e})=>{let t="";return null!==e.rowInd&&null!==e.colInd&&(t=`${e.rowInd+1}_${e.colInd+1}`),{parentComponentImmediateValue:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:`componentImmediateValue${t}`}}},definition:function({dependencyValues:e}){return{setValue:{immediateValue:e.parentComponentImmediateValue}}},inverseDefinition:function({desiredStateVariableValues:e,initialChange:t}){return{success:!0,instructions:[{setDependency:"parentComponentImmediateValue",desiredValue:e.immediateValue,treatAsInitialChange:t}]}}},e.valueForDisplay={forRenderer:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"}}),definition:function({dependencyValues:e,usedDefault:t}){return{setValue:{valueForDisplay:roundForDisplay({value:e.value,dependencyValues:e,usedDefault:t})}}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({valueForDisplay:{dependencyType:"stateVariable",variableName:"valueForDisplay"}}),definition:function({dependencyValues:e}){return{setValue:{text:e.valueForDisplay.toString()}}}},e.rawRendererValue={forRenderer:!0,hasEssential:!0,shadowVariable:!0,defaultValue:"",provideEssentialValuesInDefinition:!0,public:!0,shadowingInstructions:{createComponentOfType:"text"},additionalStateVariablesDefined:[{variableName:"lastValueForDisplay",hasEssential:!0,shadowVariable:!0,defaultValue:null,set:convertValueToMathExpression}],returnDependencies:()=>({immediateValue:{dependencyType:"stateVariable",variableName:"immediateValue"},valueForDisplay:{dependencyType:"stateVariable",variableName:"valueForDisplay"}}),definition({dependencyValues:e,essentialValues:t}){if(void 0!==t.rawRendererValue&&deepCompare(t.lastValueForDisplay.tree,e.valueForDisplay.tree))return{useEssentialOrDefaultValue:{rawRendererValue:!0,lastValueForDisplay:!0}};{let t=stripLatex(e.valueForDisplay.toLatex());return"_"===t&&(t=""),{setValue:{rawRendererValue:t,lastValueForDisplay:e.valueForDisplay},setEssentialValue:{rawRendererValue:t,lastValueForDisplay:e.valueForDisplay}}}},async inverseDefinition({desiredStateVariableValues:e,stateValues:t,essentialValues:n}){const r=async e=>{let n;e=(e=normalizeLatexString(e,{unionFromU:await t.unionFromU})).replace(/\^(\w)/g,"^{$1}");let r=getFromLatex({functionSymbols:await t.functionSymbols,splitSymbols:await t.splitSymbols,parseScientificNotation:await t.parseScientificNotation});try{n=r(e)}catch(e){n=me$3.fromAst("_")}return n};let a=[];if("string"==typeof e.rawRendererValue){let t=n.rawRendererValue,i=e.rawRendererValue;t!==i&&a.push({setEssentialValue:"rawRendererValue",value:i});let s=await r(t),o=await r(i);deepCompare(o.tree,s.tree)||a.push({setDependency:"immediateValue",desiredValue:o,treatAsInitialChange:!0})}else{a.push({setEssentialValue:"lastValueForDisplay",value:e.rawRendererValue});let t=await r(n.rawRendererValue);if(!deepCompare(e.rawRendererValue.tree,t.tree)){let t=stripLatex(e.rawRendererValue.toLatex());"_"===t&&(t=""),a.push({setEssentialValue:"rawRendererValue",value:t})}}return{success:!0,instructions:a}}},e.componentType={returnDependencies:()=>({}),definition:()=>({setValue:{componentType:"math"}})},e}async updateRawValue({rawRendererValue:e,actionId:t}){if(!await this.stateValues.disabled)return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rawRendererValue",value:e},{updateType:"setComponentNeedingUpdateValue",componentName:this.componentName}],actionId:t});this.coreFunctions.resolveAction({actionId:t})}async updateValue({actionId:e}){if(await this.stateValues.disabled)this.coreFunctions.resolveAction({actionId:e});else{let t=await this.stateValues.immediateValue;if(!deepCompare((await this.stateValues.value).tree,t.tree)){let n=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"value",value:t},{updateType:"executeUpdate"},{updateType:"updateValue",componentName:this.componentName,stateVariable:"immediateValue",valueOfStateVariable:"value"},{updateType:"unsetComponentNeedingUpdateValue"}];"_"!==t.tree&&n.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"rawRendererValue",valueOfStateVariable:"valueForDisplay"});let r={verb:"answered",object:{componentName:this.componentName,componentType:this.componentType},result:{response:t,responseText:t.toString()}},a=await this.stateValues.answerAncestor;return a&&(r.context={answerAncestor:a.componentName}),await this.coreFunctions.performUpdate({updateInstructions:n,actionId:e,event:r}),await this.coreFunctions.triggerChainedActions({componentName:this.componentName})}await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rawRendererValue",valueOfStateVariable:"rawRendererValue"}],actionId:e})}}}var MatrixInput$1=Object.freeze({__proto__:null,MatrixInput:MatrixInput,MatrixInputGrid:MatrixInputGrid,MatrixInputRow:MatrixInputRow,default:MatrixComponentInput});class Document extends BaseComponent{constructor(e){super(e),Object.assign(this.actions,{submitAllAnswers:this.submitAllAnswers.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="document";static rendererType="section";static renderChildren=!0;static createsVariants=!0;static createAttributesObject(){let e=super.createAttributesObject();return delete e.hide,delete e.disabled,delete e.modifyIndirectly,delete e.fixed,delete e.styleNumber,delete e.isResponse,e.documentWideCheckWork={createComponentOfType:"boolean",createStateVariable:"documentWideCheckWork",defaultValue:!1,public:!0},e.submitLabel={createComponentOfType:"text",createStateVariable:"submitLabel",defaultValue:"Check Work",public:!0,forRenderer:!0},e.submitLabelNoCorrectness={createComponentOfType:"text",createStateVariable:"submitLabelNoCorrectness",defaultValue:"Submit Response",public:!0,forRenderer:!0},e.displayDigitsForCreditAchieved={createComponentOfType:"integer",createStateVariable:"displayDigitsForCreditAchieved",defaultValue:3,public:!0},e.xmlns={createPrimitiveOfType:"string"},e.type={createPrimitiveOfType:"string"},e}static returnChildGroups(){return[{group:"variantControl",componentTypes:["variantControl"]},{group:"title",componentTypes:["title"]},{group:"description",componentTypes:["description"]},{group:"setups",componentTypes:["setup"]},{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnStyleDefinitionStateVariables();Object.assign(e,t);let n=returnFeedbackDefinitionStateVariables();return Object.assign(e,n),e.titleChildName={forRenderer:!0,returnDependencies:()=>({titleChild:{dependencyType:"child",childGroups:["title"]}}),definition({dependencyValues:e}){let t=null;return e.titleChild.length>0&&(t=e.titleChild[0].componentName),{setValue:{titleChildName:t}}}},e.title={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({titleChild:{dependencyType:"child",childGroups:["title"],variableNames:["text"]}}),definition:({dependencyValues:e})=>0===e.titleChild.length?{setValue:{title:""}}:{setValue:{title:e.titleChild[0].stateValues.text}}},e.description={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({descriptionChild:{dependencyType:"child",childGroups:["description"],variableNames:["text"]}}),definition:({dependencyValues:e})=>0===e.descriptionChild.length?{setValue:{description:""}}:{setValue:{description:e.descriptionChild[0].stateValues.text}}},e.level={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{level:0}})},e.viewedSolution={defaultValue:!1,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{viewedSolution:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"viewedSolution",value:e.viewedSolution}]})},e.scoredDescendants={returnDependencies:()=>({scoredDescendants:{dependencyType:"descendant",componentTypes:["_sectioningComponent","answer","setup"],variableNames:["scoredDescendants","aggregateScores","weight"],recurseToMatchedChildren:!1,variablesOptional:!0}}),definition({dependencyValues:e}){let t=[];for(let n of e.scoredDescendants)"setup"!==n.componentType&&(n.stateValues.aggregateScores||void 0===n.stateValues.scoredDescendants?t.push(n):t.push(...n.stateValues.scoredDescendants));return{setValue:{scoredDescendants:t}}}},e.nScoredDescendants={returnDependencies:()=>({scoredDescendants:{dependencyType:"stateVariable",variableName:"scoredDescendants"}}),definition:({dependencyValues:e})=>({setValue:{nScoredDescendants:e.scoredDescendants.length}})},e.itemCreditAchieved={isArray:!0,returnArraySizeDependencies:()=>({nScoredDescendants:{dependencyType:"stateVariable",variableName:"nScoredDescendants"}}),returnArraySize:({dependencyValues:e})=>[e.nScoredDescendants],stateVariablesDeterminingDependencies:["scoredDescendants"],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=t.scoredDescendants[r];e&&(n[r]={creditAchieved:{dependencyType:"stateVariable",componentName:e.componentName,variableName:"creditAchieved"}})}return{dependenciesByKey:n}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t)n[r]=e[r].creditAchieved;return{setValue:{itemCreditAchieved:n}}}},e.itemNumberByAnswerName={stateVariablesDeterminingDependencies:["scoredDescendants"],returnDependencies({stateValues:e}){let t={scoredDescendants:{dependencyType:"stateVariable",variableName:"scoredDescendants"}};for(let n in e.scoredDescendants){let r=e.scoredDescendants[n];t[`descendantsOf${n}`]={dependencyType:"descendant",ancestorName:r.componentName,componentTypes:["answer"],recurseToMatchedChildren:!1}}return t},definition({dependencyValues:e,componentInfoObjects:t}){let n={};for(let[r,a]of e.scoredDescendants.entries()){let i=r+1;for(let t of e[`descendantsOf${r}`])n[t.componentName]=i;t.isInheritedComponentType({inheritedComponentType:a.componentType,baseComponentType:"answer"})&&(n[a.componentName]=i)}return{setValue:{itemNumberByAnswerName:n}}}},e.itemVariantInfo={isArray:!0,returnArraySizeDependencies:()=>({nScoredDescendants:{dependencyType:"stateVariable",variableName:"nScoredDescendants"}}),returnArraySize:({dependencyValues:e})=>[e.nScoredDescendants],stateVariablesDeterminingDependencies:["scoredDescendants"],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=t.scoredDescendants[r];e&&(n[r]={generatedVariantInfo:{dependencyType:"stateVariable",componentName:e.componentName,variableName:"generatedVariantInfo",variablesOptional:!0}})}return{dependenciesByKey:n}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t)n[r]=e[r].generatedVariantInfo;return{setValue:{itemVariantInfo:n}}}},e.answerDescendants={returnDependencies:()=>({answerDescendants:{dependencyType:"descendant",componentTypes:["answer"],variableNames:["justSubmitted"],recurseToMatchedChildren:!1}}),definition:({dependencyValues:e})=>({setValue:{answerDescendants:e.answerDescendants}})},e.justSubmitted={forRenderer:!0,returnDependencies:()=>({answerDescendants:{dependencyType:"stateVariable",variableName:"answerDescendants"}}),definition:({dependencyValues:e})=>({setValue:{justSubmitted:e.answerDescendants.every((e=>e.stateValues.justSubmitted))}})},e.showCorrectness={forRenderer:!0,returnDependencies:()=>({showCorrectnessFlag:{dependencyType:"flag",flagName:"showCorrectness"}}),definition:({dependencyValues:e})=>({setValue:{showCorrectness:!1!==e.showCorrectnessFlag}})},e.creditAchieved={public:!0,forRenderer:!0,defaultValue:0,shadowingInstructions:{createComponentOfType:"number",addAttributeComponentsShadowingStateVariables:{displayDigits:{stateVariableToShadow:"displayDigitsForCreditAchieved"}}},additionalStateVariablesDefined:[{variableName:"percentCreditAchieved",public:!0,shadowingInstructions:{createComponentOfType:"number",addAttributeComponentsShadowingStateVariables:{displayDigits:{stateVariableToShadow:"displayDigitsForCreditAchieved"}}}}],returnDependencies:()=>({scoredDescendants:{dependencyType:"stateVariable",variableName:"scoredDescendants"},itemCreditAchieved:{dependencyType:"stateVariable",variableName:"itemCreditAchieved"}}),definition({dependencyValues:e}){let t,n=0,r=0;for(let[t,a]of e.scoredDescendants.entries()){let i=a.stateValues.weight;n+=e.itemCreditAchieved[t]*i,r+=i}return t=r>0?n/r:1,{setValue:{creditAchieved:t,percentCreditAchieved:100*t}}}},e.creditAchievedIfSubmit={defaultValue:0,stateVariablesDeterminingDependencies:["scoredDescendants"],returnDependencies({stateValues:e}){let t={scoredDescendants:{dependencyType:"stateVariable",variableName:"scoredDescendants"}};for(let[n,r]of e.scoredDescendants.entries())t["creditAchievedIfSubmit"+n]={dependencyType:"stateVariable",componentName:r.componentName,variableName:"creditAchievedIfSubmit"};return t},definition({dependencyValues:e}){let t=0,n=0;for(let[r,a]of e.scoredDescendants.entries()){let i=a.stateValues.weight;t+=e["creditAchievedIfSubmit"+r]*i,n+=i}return{setValue:{creditAchievedIfSubmit:t/n}}}},e.generatedVariantInfo={providePreviousValuesInDefinition:!0,returnDependencies:({sharedParameters:e,componentInfoObjects:t})=>({variantIndex:{dependencyType:"value",value:e.variantIndex},variantName:{dependencyType:"value",value:e.variantName},variantDescendants:{dependencyType:"descendant",componentTypes:Object.keys(t.componentTypesCreatingVariants),variableNames:["isVariantComponent","generatedVariantInfo"],recurseToMatchedChildren:!1,variablesOptional:!0,includeNonActiveChildren:!0,ignoreReplacementsOfEncounteredComposites:!0}}),definition({dependencyValues:e,componentName:t,previousValues:n}){let r={index:e.variantIndex,name:e.variantName,meta:{createdBy:t}},a=r.subvariants=[];for(let t of e.variantDescendants)t.stateValues.isVariantComponent?a.push(t.stateValues.generatedVariantInfo):t.stateValues.generatedVariantInfo&&a.push(...t.stateValues.generatedVariantInfo.subvariants);for(let[e,t]of a.entries())if(!t.subvariants&&n.generatedVariantInfo){let t=n.generatedVariantInfo.subvariants;t[e]?.subvariants&&(a[e]=Object.assign({},a[e]),a[e].subvariants=t[e].subvariants)}return{setValue:{generatedVariantInfo:r}}}},e.createSubmitAllButton={forRenderer:!0,additionalStateVariablesDefined:[{variableName:"suppressAnswerSubmitButtons",forRenderer:!0}],returnDependencies:()=>({documentWideCheckWork:{dependencyType:"stateVariable",variableName:"documentWideCheckWork"}}),definition({dependencyValues:e,componentName:t}){let n=!1,r=!1;return e.documentWideCheckWork&&(n=!0,r=!0),{setValue:{createSubmitAllButton:n,suppressAnswerSubmitButtons:r}}}},e.suppressCheckwork={forRenderer:!0,returnDependencies:()=>({autoSubmit:{dependencyType:"flag",flagName:"autoSubmit"}}),definition:({dependencyValues:e})=>({setValue:{suppressCheckwork:e.autoSubmit}})},e}async submitAllAnswers({actionId:e}){this.coreFunctions.requestRecordEvent({verb:"submitted",object:{componentName:this.componentName,componentType:this.componentType}});for(let e of await this.stateValues.answerDescendants)await e.stateValues.justSubmitted||await this.coreFunctions.performAction({componentName:e.componentName,actionName:"submitAnswer"});this.coreFunctions.resolveAction({actionId:e})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}static setUpVariant({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n}){let r,a=e.variants.numberOfVariants,i=e.variants.desiredVariant;if(void 0!==i&&void 0!==i.index){let e=Number(i.index);if(Number.isFinite(e)){Number.isInteger(e)||(console.warn("Variant index "+i.index+" must be an integer"),e=Math.round(e));let t=(e-1)%a;t<0&&(t+=a),r=t+1}else console.warn("Variant index "+i.index+" must be a number"),r=1}if(void 0===r&&(r=1),t.allPossibleVariants=e.variants.allPossibleVariants,t.allVariantNames=e.variants.allVariantNames,t.variantSeed=e.variants.allPossibleVariantSeeds[r-1],t.variantIndex=r,t.variantName=e.variants.allPossibleVariants[r-1],t.uniqueIndex=e.variants.allPossibleVariantUniqueIndices[r-1],t.variantRng=new t.rngClass(t.variantSeed),t.subpartVariantRng=new t.rngClass(t.variantSeed+"s"),i?.subvariants&&n)for(let e in i.subvariants){let t=i.subvariants[e],r=n[e];if(void 0===r)break;r.variants.desiredVariant=t}}static determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t}){return determineVariantsForSection({serializedComponent:e,componentInfoObjects:t,isDocument:!0})}static getUniqueVariant({serializedComponent:e,variantIndex:t,componentInfoObjects:n}){let r=e.variants.allPossibleVariantUniqueIndices[t-1];if(void 0===r)return{success:!1};let a=getVariantsForDescendantsForUniqueVariants({variantIndex:r,serializedComponent:e,componentInfoObjects:n});return a.success?{success:!0,desiredVariant:{index:t,subvariants:a.desiredVariants}}:(console.log("Failed to get unique variant for document."),{success:!1})}static includeBlankStringChildren=!0}class TextList$1 extends InlineComponent{static componentType="textList";static renderChildren=!0;static includeBlankStringChildren=!0;static removeBlankStringChildrenPostSugar=!0;static stateVariableForAttributeValue="texts";static primaryStateVariableForDefinition="textsShadow";static descendantCompositesMustHaveAReplacement=!1;static createAttributesObject(){let e=super.createAttributesObject();return e.unordered={createComponentOfType:"boolean",createStateVariable:"unordered",defaultValue:!1,public:!0},e.maximumNumber={createComponentOfType:"number",createStateVariable:"maximumNumber",defaultValue:null,public:!0},e}static returnSugarInstructions(){let e=super.returnSugarInstructions(),t=returnGroupIntoComponentTypeSeparatedBySpaces({componentType:"text"}),n=returnBreakStringsIntoComponentTypeBySpaces({componentType:"text"});return e.push({replacementFunction:function({matchedChildren:e,isAttributeComponent:r=!1,createdFromMacro:a=!1}){return r&&!a?t({matchedChildren:e}):n({matchedChildren:e})}}),e}static returnChildGroups(){return[{group:"texts",componentTypes:["text"]},{group:"textLists",componentTypes:["textList"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.overrideChildHide={returnDependencies:()=>({}),definition:()=>({setValue:{overrideChildHide:!0}})},e.textsShadow={defaultValue:null,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{textsShadow:!0}})},e.nComponents={public:!0,shadowingInstructions:{createComponentOfType:"number"},additionalStateVariablesDefined:["childIndexByArrayKey"],returnDependencies:()=>({maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"},textListChildren:{dependencyType:"child",childGroups:["textLists"],variableNames:["nComponents"]},textAndTextListChildren:{dependencyType:"child",childGroups:["texts","textLists"],skipComponentNames:!0},textsShadow:{dependencyType:"stateVariable",variableName:"textsShadow"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=0,r=[];if(e.textAndTextListChildren.length>0){let a=0;for(let[i,s]of e.textAndTextListChildren.entries())if(t.isInheritedComponentType({inheritedComponentType:s.componentType,baseComponentType:"textList"})){let t=e.textListChildren[a];a++;for(let e=0;ea&&(n=a,r=r.slice(0,a)),{setValue:{nComponents:n,childIndexByArrayKey:r},checkForActualChange:{nComponents:!0}}}},e.texts={public:!0,shadowingInstructions:{createComponentOfType:"text"},isArray:!0,entryPrefixes:["text"],stateVariablesDeterminingDependencies:["childIndexByArrayKey"],returnArraySizeDependencies:()=>({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"}}),returnArraySize:({dependencyValues:e})=>[e.nComponents],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=[],a="1";t.childIndexByArrayKey[r]&&(e=[t.childIndexByArrayKey[r][0]],a=t.childIndexByArrayKey[r][1]+1),n[r]={textAndTextListChildren:{dependencyType:"child",childGroups:["texts","textLists"],variableNames:["value","text"+a],variablesOptional:!0,childIndices:e}}}return{globalDependencies:{childIndexByArrayKey:{dependencyType:"stateVariable",variableName:"childIndexByArrayKey"},textsShadow:{dependencyType:"stateVariable",variableName:"textsShadow"}},dependenciesByKey:n}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};for(let a of n){let n=t[a].textAndTextListChildren[0];if(n)if(void 0!==n.stateValues.value)r[a]=n.stateValues.value;else{let t=e.childIndexByArrayKey[a][1]+1;r[a]=n.stateValues["text"+t]}else null!==e.textsShadow&&(r[a]=e.textsShadow[a])}return{setValue:{texts:r}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i=[];for(let t in e.texts){if(!n[t])continue;let a=n[t].textAndTextListChildren[0];a&&(void 0!==a.stateValues.value?i.push({setDependency:r[t].textAndTextListChildren,desiredValue:e.texts[t],childIndex:0,variableIndex:0}):i.push({setDependency:r[t].textAndTextListChildren,desiredValue:e.texts[t],childIndex:0,variableIndex:1}))}return{success:!0,instructions:i}}},e.nValues={isAlias:!0,targetVariableName:"nComponents"},e.values={isAlias:!0,targetVariableName:"texts"},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({texts:{dependencyType:"stateVariable",variableName:"texts"}}),definition:({dependencyValues:e})=>({setValue:{text:e.texts.join(", ")}})},e.componentNamesInList={returnDependencies:()=>({textAndTextListChildren:{dependencyType:"child",childGroups:["texts","textLists"],variableNames:["componentNamesInList"],variablesOptional:!0},maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=[];for(let r of e.textAndTextListChildren)t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"textList"})?n.push(...r.stateValues.componentNamesInList):n.push(r.componentName);let r=e.maximumNumber;return null!==r&&n.length>r&&(r=Math.max(0,Math.floor(r)),n=n.slice(0,r)),{setValue:{componentNamesInList:n}}}},e.nComponentsToDisplayByChild={additionalStateVariablesDefined:["nChildrenToRender"],returnDependencies:()=>({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"},textListChildren:{dependencyType:"child",childGroups:["textLists"],variableNames:["nComponents"]},textAndTextListChildren:{dependencyType:"child",childGroups:["texts","textLists"],skipComponentNames:!0},parentNComponentsToDisplayByChild:{dependencyType:"parentStateVariable",parentComponentType:"textList",variableName:"nComponentsToDisplayByChild"}}),definition:function({dependencyValues:e,componentInfoObjects:t,componentName:n}){let r=e.nComponents;null!==e.parentNComponentsToDisplayByChild&&(r=e.parentNComponentsToDisplayByChild[n]);let a={},i=0,s=0,o=0;for(let n of e.textAndTextListChildren){let l=Math.max(0,r-i);if(l>0&&s++,t.isInheritedComponentType({inheritedComponentType:n.componentType,baseComponentType:"textList"})){let t=e.textListChildren[o];o++;let n=Math.min(l,t.stateValues.nComponents);a[t.componentName]=n,i+=n}else i+=1}return{setValue:{nComponentsToDisplayByChild:a,nChildrenToRender:s}}},markStale:()=>({updateRenderedChildren:!0})},e}static adapters=["text"]}class TextList extends InlineComponent{static componentType="randomizedTextList";static stateVariableForAttributeValue="texts";static createAttributesObject(){let e=super.createAttributesObject();return e.unordered={default:!1},e.maximumNumber={default:null},e}static returnChildLogic(e){let t=super.returnChildLogic(e),n=t.newLeaf({name:"atLeastZeroTexts",componentType:"text",comparison:"atLeast",number:0}),r=t.newLeaf({name:"atLeastZeroTextLists",componentType:"textList",comparison:"atLeast",number:0}),a=t.newLeaf({name:"exactlyOneString",componentType:"string",number:1,isSugar:!0,returnSugarDependencies:()=>({stringChildren:{dependencyType:"child",childLogicName:"exactlyOneString",variableNames:["value"]}}),logicToWaitOnSugar:["atLeastZeroTexts"],replacementFunction:function({dependencyValues:e}){let t=e.stringChildren[0],n=t.stateValues.value.split(",").map((e=>({componentType:"text",state:{value:e.trim()}})));return{success:!0,newChildren:n,toDelete:[t.componentName]}}}),i=t.newOperator({name:"textAndTextLists",operator:"and",propositions:[n,r]});return t.newOperator({name:"TextsXorSugar",operator:"xor",propositions:[a,i],setAsBase:!0}),t}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.texts={public:!0,shadowingInstructions:{createComponentOfType:"text"},isArray:!0,entryPrefixes:["text"],returnDependencies:()=>({textAndTextListChildren:{dependencyType:"child",childLogicName:"textAndTextLists",variableNames:["value","texts"],variablesOptional:!0},maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"},childrenToRender:{dependencyType:"stateVariable",variableName:"childrenToRender"}}),definition:function({dependencyValues:e}){let t=[],n=e.textAndTextListChildren.map((e=>e.componentName));for(let r of e.childrenToRender){let a=n.indexOf(r),i=e.textAndTextListChildren[a];i.stateValues.texts?t.push(...i.stateValues.texts):t.push(i.stateValues.value)}return{setValue:{texts:t}}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({texts:{dependencyType:"stateVariable",variableName:"texts"}}),definition:({dependencyValues:e})=>({setValue:{text:e.texts.join(", ")}})},e.nComponents={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({texts:{dependencyType:"stateVariable",variableName:"texts"}}),definition:function({dependencyValues:e}){return{setValue:{nComponents:e.texts.length}}}},e.childrenToRender={returnDependencies:({sharedParameters:e})=>({textAndTextListChildren:{dependencyType:"child",childLogicName:"textAndTextLists",variableNames:["childrenToRender"],variablesOptional:!0},maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"},selectRng:{dependencyType:"value",value:e.selectRng,doNotProxy:!0}}),definition:function({dependencyValues:e}){let t=[];for(let n of e.textAndTextListChildren)n.stateValues.childrenToRender?t.push(...n.stateValues.childrenToRender):t.push(n.componentName);let n=e.maximumNumber;null!==n&&t.length>n&&(n=Math.max(0,Math.floor(n)),t=t.slice(0,n)),console.log("randomizing children");for(let n=t.length-1;n>0;n--){const r=e.selectRng(),a=Math.floor(r*(n+1));[t[n],t[a]]=[t[a],t[n]]}let r=Math.ceil(e.selectRng()*t.length);return console.log(`numChildren: ${r}`),t=t.slice(0,r),{setValue:{childrenToRender:t}}}},e}initializeRenderer(){void 0===this.renderer&&(this.renderer=new this.availableRenderers.aslist({key:this.componentName}))}}class TupleList extends MathList{static componentType="tupleList";static rendererType="mathList";static includeBlankStringChildren=!1;static returnSugarInstructions(){let e=[];return e.push({replacementFunction:function({matchedChildren:e}){let t=breakEmbeddedStringsIntoParensPieces({componentList:e});return!0!==t.success?{success:!1}:{success:!0,newChildren:t.pieces.map((function(e){return e.length>1||"string"==typeof e[0]?{componentType:"math",children:e}:e[0]}))}}}),e}}class NumberList extends InlineComponent{static componentType="numberList";static renderChildren=!0;static includeBlankStringChildren=!0;static removeBlankStringChildrenPostSugar=!0;static stateVariableForAttributeValue="numbers";static primaryStateVariableForDefinition="numbersShadow";static createAttributesObject(){let e=super.createAttributesObject();return e.unordered={createComponentOfType:"boolean",createStateVariable:"unordered",defaultValue:!1,public:!0},e.maximumNumber={createComponentOfType:"number",createStateVariable:"maximumNumber",defaultValue:null,public:!0},e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.padZeros={createComponentOfType:"boolean",createStateVariable:"padZeros",defaultValue:!1,public:!0},e}static returnSugarInstructions(){let e=super.returnSugarInstructions(),t=returnGroupIntoComponentTypeSeparatedBySpaces({componentType:"number"}),n=returnBreakStringsIntoComponentTypeBySpaces({componentType:"number"});return e.push({replacementFunction:function({matchedChildren:e,isAttributeComponent:r=!1,createdFromMacro:a=!1}){return r&&!a?t({matchedChildren:e}):n({matchedChildren:e})}}),e}static returnChildGroups(){return[{group:"numbers",componentTypes:["number"]},{group:"numberLists",componentTypes:["numberList"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.overrideChildHide={returnDependencies:()=>({}),definition:()=>({setValue:{overrideChildHide:!0}})},e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.displayDigitsAttr){let n=t.displayDigitsAttr,r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!n&&!r){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({}),definition:()=>({useEssentialOrDefaultValue:{numbersShadow:!0}})},e.nComponents={public:!0,shadowingInstructions:{createComponentOfType:"number"},additionalStateVariablesDefined:["childIndexByArrayKey"],returnDependencies:()=>({maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"},numberListChildren:{dependencyType:"child",childGroups:["numberLists"],variableNames:["nComponents"]},numberAndNumberListChildren:{dependencyType:"child",childGroups:["numbers","numberLists"],skipComponentNames:!0},numbersShadow:{dependencyType:"stateVariable",variableName:"numbersShadow"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=0,r=[],a=0;if(e.numberAndNumberListChildren.length>0)for(let[i,s]of e.numberAndNumberListChildren.entries())if(t.isInheritedComponentType({inheritedComponentType:s.componentType,baseComponentType:"numberList"})){let t=e.numberListChildren[a];a++;for(let e=0;ei&&(n=i,r=r.slice(0,i)),{setValue:{nComponents:n,childIndexByArrayKey:r},checkForActualChange:{nComponents:!0}}}},e.numbers={public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},isArray:!0,entryPrefixes:["number"],stateVariablesDeterminingDependencies:["childIndexByArrayKey"],returnArraySizeDependencies:()=>({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"}}),returnArraySize:({dependencyValues:e})=>[e.nComponents],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=[],a="1";t.childIndexByArrayKey[r]&&(e=[t.childIndexByArrayKey[r][0]],a=t.childIndexByArrayKey[r][1]+1),n[r]={numberAndNumberListChildren:{dependencyType:"child",childGroups:["numbers","numberLists"],variableNames:["value","number"+a],variablesOptional:!0,childIndices:e}}}return{globalDependencies:{childIndexByArrayKey:{dependencyType:"stateVariable",variableName:"childIndexByArrayKey"},numbersShadow:{dependencyType:"stateVariable",variableName:"numbersShadow"}},dependenciesByKey:n}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};for(let a of n){let n=t[a].numberAndNumberListChildren[0];if(n)if(void 0!==n.stateValues.value)r[a]=n.stateValues.value;else{let t=e.childIndexByArrayKey[a][1]+1;r[a]=n.stateValues["number"+t]}else null!==e.numbersShadow&&(r[a]=e.numbersShadow[a])}return{setValue:{numbers:r}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i=[];for(let t in e.numbers){if(!n[t])continue;let a=n[t].numberAndNumberListChildren[0];a&&(void 0!==a.stateValues.value?i.push({setDependency:r[t].numberAndNumberListChildren,desiredValue:e.numbers[t],childIndex:0,variableIndex:0}):i.push({setDependency:r[t].numberAndNumberListChildren,desiredValue:e.numbers[t],childIndex:0,variableIndex:1}))}return{success:!0,instructions:i}}},e.nValues={isAlias:!0,targetVariableName:"nComponents"},e.values={isAlias:!0,targetVariableName:"numbers"},e.math={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},returnDependencies:()=>({numbers:{dependencyType:"stateVariable",variableName:"numbers"}}),definition({dependencyValues:e}){let t;return t=0===e.numbers.length?me$3.fromAst("_"):1===e.numbers.length?me$3.fromAst(e.numbers[0]):me$3.fromAst(["list",...e.numbers]),{setValue:{math:t}}}},e.text={public:!0,forRenderer:!0,shadowingInstructions:{createComponentOfType:"text"},additionalStateVariablesDefined:["texts"],returnDependencies:()=>({numberAndNumberListChildren:{dependencyType:"child",childGroups:["numbers","numberLists"],variableNames:["valueForDisplay","text","texts"],variablesOptional:!0},maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"},numbersShadow:{dependencyType:"stateVariable",variableName:"numbersShadow"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"}}),definition:function({dependencyValues:e,usedDefault:t}){let n=[],r={};if(e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(r.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(r.padToDigits=e.displayDigits)),e.numberAndNumberListChildren.length>0)for(let t of e.numberAndNumberListChildren)void 0!==t.stateValues.valueForDisplay?n.push(t.stateValues.text):n.push(...t.stateValues.texts);else null!==e.numbersShadow&&(n=e.numbersShadow.map((n=>roundForDisplay({value:me$3.fromAst(n),dependencyValues:e,usedDefault:t}).toString(r))));let a=e.maximumNumber;return null!==a&&n.length>a&&(a=Math.max(0,Math.floor(a)),n=n.slice(0,a)),{setValue:{text:n.join(", "),texts:n}}}},e.componentNamesInList={returnDependencies:()=>({numberAndNumberListChildren:{dependencyType:"child",childGroups:["numbers","numberLists"],variableNames:["componentNamesInList"],variablesOptional:!0},maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=[];for(let r of e.numberAndNumberListChildren)t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"numberList"})?n.push(...r.stateValues.componentNamesInList):n.push(r.componentName);let r=e.maximumNumber;return null!==r&&n.length>r&&(r=Math.max(0,Math.floor(r)),n=n.slice(0,r)),{setValue:{componentNamesInList:n}}}},e.nComponentsToDisplayByChild={additionalStateVariablesDefined:["nChildrenToRender"],returnDependencies:()=>({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"},numberListChildren:{dependencyType:"child",childGroups:["numberLists"],variableNames:["nComponents"]},numberAndNumberListChildren:{dependencyType:"child",childGroups:["numbers","numberLists"],skipComponentNames:!0},parentNComponentsToDisplayByChild:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"nComponentsToDisplayByChild"}}),definition:function({dependencyValues:e,componentInfoObjects:t,componentName:n}){let r=e.nComponents;null!==e.parentNComponentsToDisplayByChild&&(r=e.parentNComponentsToDisplayByChild[n]);let a={},i=0,s=0,o=0;for(let n of e.numberAndNumberListChildren){let l=Math.max(0,r-i);if(l>0&&s++,t.isInheritedComponentType({inheritedComponentType:n.componentType,baseComponentType:"numberList"})){let t=e.numberListChildren[o];o++;let n=Math.min(l,t.stateValues.nComponents);a[t.componentName]=n,i+=n}else i+=1}return{setValue:{nComponentsToDisplayByChild:a,nChildrenToRender:s}}},markStale:()=>({updateRenderedChildren:!0})},e}static adapters=[{stateVariable:"math",stateVariablesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},"text"]}class NumberListFromString extends InlineComponent{static componentType="numberListFromString";static rendererType="asList";static renderChildren=!0;static stateVariableForAttributeValue="numbers";static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e}){let t=e.reduce((function(e,t){return"string"==typeof t?[...e,...t.split(/\s+/).filter((e=>e))]:[...e,t]}),[]);return{success:!0,newChildren:t}}}),e}static returnChildGroups(){return[{group:"strings",componentTypes:["string"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nComponents={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({stringChildren:{dependencyType:"child",childGroups:["strings"]}}),definition:function({dependencyValues:e}){return{setValue:{nComponents:e.stringChildren.length}}}},e.numbers={public:!0,shadowingInstructions:{createComponentOfType:"number"},isArray:!0,entryPrefixes:["number"],returnArraySizeDependencies:()=>({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"}}),returnArraySize:({dependencyValues:e})=>[e.nComponents],returnArrayDependenciesByKey:()=>({globalDependencies:{stringChildren:{dependencyType:"child",childGroups:["strings"]}}}),arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t}){let n={};for(let[t,r]of e.stringChildren.entries())n[t]=Number(r);return{setValue:{numbers:n}}}},e.nValues={isAlias:!0,targetVariableName:"nComponents"},e.values={isAlias:!0,targetVariableName:"numbers"},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},additionalStateVariablesDefined:["texts"],returnDependencies:()=>({numbers:{dependencyType:"stateVariable",variableName:"numbers"}}),definition:function({dependencyValues:e}){let t=e.numbers.map((e=>e.toString()));return{setValue:{text:t.join(", "),texts:t}}}},e}}class P$2 extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="p";static renderChildren=!0;static includeBlankStringChildren=!0;static returnChildGroups(){return[{group:"inlines",componentTypes:["_inline"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["inlines"],variableNames:["text"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let t="";for(let n of e.inlineChildren)"object"!=typeof n?t+=n.toString():"string"==typeof n.stateValues.text?t+=n.stateValues.text:t+=" ";return{setValue:{text:t}}}},e}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class BooleanList extends InlineComponent{static componentType="booleanList";static rendererType="asList";static renderChildren=!0;static includeBlankStringChildren=!0;static removeBlankStringChildrenPostSugar=!0;static stateVariableForAttributeValue="booleans";static descendantCompositesMustHaveAReplacement=!1;static createAttributesObject(){let e=super.createAttributesObject();return e.unordered={createComponentOfType:"boolean",createStateVariable:"unordered",defaultValue:!1,public:!0},e.maximumNumber={createComponentOfType:"number",createStateVariable:"maximumNumber",defaultValue:null,public:!0},e}static returnSugarInstructions(){let e=super.returnSugarInstructions(),t=returnGroupIntoComponentTypeSeparatedBySpaces({componentType:"boolean"}),n=returnBreakStringsIntoComponentTypeBySpaces({componentType:"boolean"});return e.push({replacementFunction:function({matchedChildren:e,isAttributeComponent:r=!1,createdFromMacro:a=!1}){return r&&!a?t({matchedChildren:e}):n({matchedChildren:e})}}),e}static returnChildGroups(){return[{group:"booleans",componentTypes:["boolean"]},{group:"booleanLists",componentTypes:["booleanList"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.overrideChildHide={returnDependencies:()=>({}),definition:()=>({setValue:{overrideChildHide:!0}})},e.nComponents={public:!0,shadowingInstructions:{createComponentOfType:"number"},additionalStateVariablesDefined:["childIndexByArrayKey"],returnDependencies:()=>({maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"},booleanListChildren:{dependencyType:"child",childGroups:["booleanLists"],variableNames:["nComponents"]},booleanAndBooleanListChildren:{dependencyType:"child",childGroups:["booleans","booleanLists"],skipComponentNames:!0}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=0,r=[],a=0;for(let[i,s]of e.booleanAndBooleanListChildren.entries())if(t.isInheritedComponentType({inheritedComponentType:s.componentType,baseComponentType:"booleanList"})){let t=e.booleanListChildren[a];a++;for(let e=0;ei&&(n=i,r=r.slice(0,i)),{setValue:{nComponents:n,childIndexByArrayKey:r},checkForActualChange:{nComponents:!0}}}},e.booleans={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},isArray:!0,entryPrefixes:["boolean"],stateVariablesDeterminingDependencies:["childIndexByArrayKey"],returnArraySizeDependencies:()=>({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"}}),returnArraySize:({dependencyValues:e})=>[e.nComponents],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=[],a="1";t.childIndexByArrayKey[r]&&(e=[t.childIndexByArrayKey[r][0]],a=t.childIndexByArrayKey[r][1]+1),n[r]={booleanAndBooleanListChildren:{dependencyType:"child",childGroups:["booleans","booleanLists"],variableNames:["value","boolean"+a],variablesOptional:!0,childIndices:e}}}return{globalDependencies:{childIndexByArrayKey:{dependencyType:"stateVariable",variableName:"childIndexByArrayKey"}},dependenciesByKey:n}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};for(let a of n){let n=t[a].booleanAndBooleanListChildren[0];if(n)if(void 0!==n.stateValues.value)r[a]=n.stateValues.value;else{let t=e.childIndexByArrayKey[a][1]+1;r[a]=n.stateValues["boolean"+t]}}return{setValue:{booleans:r}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i=[];for(let t in e.booleans){if(!n[t])continue;let a=n[t].booleanAndBooleanListChildren[0];a&&(void 0!==a.stateValues.value?i.push({setDependency:r[t].booleanAndBooleanListChildren,desiredValue:e.booleans[t],childIndex:0,variableIndex:0}):i.push({setDependency:r[t].booleanAndBooleanListChildren,desiredValue:e.booleans[t],childIndex:0,variableIndex:1}))}return{success:!0,instructions:i}}},e.nValues={isAlias:!0,targetVariableName:"nComponents"},e.values={isAlias:!0,targetVariableName:"booleans"},e.componentNamesInList={returnDependencies:()=>({booleanAndBooleanListChildren:{dependencyType:"child",childGroups:["booleans","booleanLists"],variableNames:["componentNamesInList"],variablesOptional:!0},maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=[];for(let r of e.booleanAndBooleanListChildren)t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"booleanList"})?n.push(...r.stateValues.componentNamesInList):n.push(r.componentName);let r=e.maximumNumber;return null!==r&&n.length>r&&(r=Math.max(0,Math.floor(r)),n=n.slice(0,r)),{setValue:{componentNamesInList:n}}}},e.nComponentsToDisplayByChild={additionalStateVariablesDefined:["nChildrenToRender"],returnDependencies:()=>({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"},booleanListChildren:{dependencyType:"child",childGroups:["booleanLists"],variableNames:["nComponents"]},booleanAndBooleanListChildren:{dependencyType:"child",childGroups:["booleans","booleanLists"],skipComponentNames:!0},parentNComponentsToDisplayByChild:{dependencyType:"parentStateVariable",parentComponentType:"booleanList",variableName:"nComponentsToDisplayByChild"}}),definition:function({dependencyValues:e,componentInfoObjects:t,componentName:n}){let r=e.nComponents;null!==e.parentNComponentsToDisplayByChild&&(r=e.parentNComponentsToDisplayByChild[n]);let a={},i=0,s=0,o=0;for(let n of e.booleanAndBooleanListChildren){let l=Math.max(0,r-i);if(l>0&&s++,t.isInheritedComponentType({inheritedComponentType:n.componentType,baseComponentType:"booleanList"})){let t=e.booleanListChildren[o];o++;let n=Math.min(l,t.stateValues.nComponents);a[t.componentName]=n,i+=n}else i+=1}return{setValue:{nComponentsToDisplayByChild:a,nChildrenToRender:s}}},markStale:()=>({updateRenderedChildren:!0})},e}}class Copy extends CompositeComponent{static componentType="copy";static assignNamesToReplacements=!0;static acceptTarget=!0;static acceptAnyAttribute=!0;static includeBlankStringChildren=!0;static stateVariableToEvaluateAfterReplacements="needsReplacementsUpdatedWhenStale";static createAttributesObject(){let e=super.createAttributesObject();return delete e.disabled,delete e.modifyIndirectly,delete e.fixed,delete e.styleNumber,delete e.isResponse,e.assignNewNamespaces={createPrimitiveOfType:"boolean"},e.assignNamesSkip={createPrimitiveOfType:"number"},e.prop={createPrimitiveOfType:"string"},e.obtainPropFromComposite={createPrimitiveOfType:"boolean",createStateVariable:"obtainPropFromComposite",defaultValue:!1,public:!0},e.createComponentOfType={createPrimitiveOfType:"string"},e.nComponents={createPrimitiveOfType:"number"},e.componentIndex={createComponentOfType:"integer",createStateVariable:"componentIndex",defaultValue:null,public:!0},e.sourceSubnames={createPrimitiveOfType:"stringArray",createStateVariable:"targetSubnames",defaultValue:null,public:!0},e.sourceSubnamesComponentIndex={createComponentOfType:"numberList",createStateVariable:"targetSubnamesComponentIndex",defaultValue:null,public:!0},e.propIndex={createComponentOfType:"numberList",createStateVariable:"propIndex",defaultValue:null,public:!0},e.uri={createPrimitiveOfType:"string",createStateVariable:"uri",defaultValue:null,public:!0},e.sourceAttributesToIgnore={createPrimitiveOfType:"stringArray",createStateVariable:"sourceAttributesToIgnore",defaultValue:["hide"],public:!0},e.sourceAttributesToIgnoreRecursively={createPrimitiveOfType:"stringArray",createStateVariable:"sourceAttributesToIgnoreRecursively",defaultValue:["isResponse"],public:!0},e.link={createPrimitiveOfType:"boolean"},e.removeEmptyArrayEntries={createPrimitiveOfType:"boolean",createStateVariable:"removeEmptyArrayEntries",defaultValue:!1},e}static keepChildrenSerialized({serializedComponent:e}){return void 0===e.children?[]:Object.keys(e.children)}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.target={returnDependencies:()=>({target:{dependencyType:"doenetAttribute",attributeName:"target"}}),definition:({dependencyValues:e})=>({setValue:{target:e.target}})},e.targetSourcesName={additionalStateVariablesDefined:[{variableName:"sourcesChildNumber",hasEssential:!0,shadowVariable:!0}],stateVariablesDeterminingDependencies:["target"],determineDependenciesImmediately:!0,hasEssential:!0,shadowVariable:!0,returnDependencies:function({stateValues:e,sharedParameters:t}){let n=t.sourceNameMappings;if(!n)return{};let r=n[e.target];return r?{targetSourcesName:{dependencyType:"value",value:r.name},sourcesChildNumber:{dependencyType:"value",value:r.childNumber}}:{}},definition:function({dependencyValues:e}){let t=e.targetSourcesName,n=e.sourcesChildNumber;return t||(t=null,n=null),{setValue:{targetSourcesName:t,sourcesChildNumber:n},setEssentialValue:{targetSourcesName:t,sourcesChildNumber:n}}}},e.targetSources={stateVariablesDeterminingDependencies:["targetSourcesName"],determineDependenciesImmediately:!0,returnDependencies:({stateValues:e})=>e.targetSourcesName?{targetSourcesComponent:{dependencyType:"componentIdentity",componentName:e.targetSourcesName}}:{},definition:function({dependencyValues:e}){let t=e.targetSourcesComponent;return t||(t=null),{setValue:{targetSources:t}}}},e.sourceIndex={stateVariablesDeterminingDependencies:["target"],determineDependenciesImmediately:!0,hasEssential:!0,shadowVariable:!0,returnDependencies:function({stateValues:e,sharedParameters:t}){let n=t.sourceIndexMappings;if(!n)return{};let r=n[e.target];return void 0===r?{}:{sourceIndex:{dependencyType:"value",value:r}}},definition:function({dependencyValues:e}){let t=e.sourceIndex;return void 0===t&&(t=null),{setValue:{sourceIndex:t},setEssentialValue:{sourceIndex:t}}}},e.targetComponent={shadowVariable:!0,stateVariablesDeterminingDependencies:["targetSources","sourceIndex"],determineDependenciesImmediately:!0,returnDependencies:({stateValues:e})=>null!==e.sourceIndex?{}:null!==e.targetSources?{targetSourcesChildren:{dependencyType:"stateVariable",componentName:e.targetSources.componentName,variableName:"childIdentities"},sourcesChildNumber:{dependencyType:"stateVariable",variableName:"sourcesChildNumber"}}:{targetComponent:{dependencyType:"targetComponent"}},definition:function({dependencyValues:e}){let t=null;return e.targetSourcesChildren?(t=e.targetSourcesChildren[e.sourcesChildNumber],t||(t=null)):e.targetComponent&&(t=e.targetComponent),{setValue:{targetComponent:t}}}},e.targetInactive={stateVariablesDeterminingDependencies:["targetComponent"],returnDependencies:({stateValues:e})=>e.targetComponent?{targetIsInactiveCompositeReplacement:{dependencyType:"stateVariable",componentName:e.targetComponent.componentName,variableName:"isInactiveCompositeReplacement"}}:{},definition:function({dependencyValues:e}){return{setValue:{targetInactive:Boolean(e.targetIsInactiveCompositeReplacement)}}}},e.cid={additionalStateVariablesDefined:["doenetId"],returnDependencies:()=>({uri:{dependencyType:"stateVariable",variableName:"uri"}}),definition:function({dependencyValues:e}){if(!e.uri||"doenet:"!==e.uri.substring(0,7).toLowerCase())return{setValue:{cid:null,doenetId:null}};let t=null,n=null,r=e.uri.match(/[:&]cid=([^&]+)/i);return r&&(t=r[1]),r=e.uri.match(/[:&]doenetid=([^&]+)/i),r&&(n=r[1]),{setValue:{cid:t,doenetId:n}}}},e.serializedComponentsForCid={returnDependencies:()=>({cid:{dependencyType:"stateVariable",variableName:"cid"},serializedChildren:{dependencyType:"serializedChildren",doNotProxy:!0}}),definition:function({dependencyValues:e}){return e.cid&&e.serializedChildren?.length>0?{setValue:{serializedComponentsForCid:e.serializedChildren}}:{setValue:{serializedComponentsForCid:null}}}},e.propName={shadowVariable:!0,returnDependencies:()=>({propName:{dependencyType:"attributePrimitive",attributeName:"prop"}}),definition:function({dependencyValues:e}){return{setValue:{propName:e.propName}}}},e.isPlainMacro={returnDependencies:()=>({isPlainMacro:{dependencyType:"doenetAttribute",attributeName:"isPlainMacro"},targetComponent:{dependencyType:"stateVariable",variableName:"targetComponent"},typeAttr:{dependencyType:"attributePrimitive",attributeName:"createComponentOfType"},targetSubnames:{dependencyType:"stateVariable",variableName:"targetSubnames"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=e.isPlainMacro&&(!t.isCompositeComponent({componentType:e.targetComponent?.componentType})||e.targetSubnames);if(n&&e.typeAttr){n=!1;let r=t.componentTypeLowerCaseMapping[e.typeAttr.toLowerCase()],a=t.allComponentClasses[e.targetComponent?.componentType];if(a){let e=t.publicStateVariableInfo[a.componentType].stateVariableDescriptions[a.variableForPlainMacro];r===a.componentType||!e||void 0!==e.createComponentOfType&&e.createComponentOfType!==r||(n=!0)}}return{setValue:{isPlainMacro:n}}}},e.isPlainCopy={returnDependencies:()=>({isPlainCopy:{dependencyType:"doenetAttribute",attributeName:"isPlainCopy"},targetComponent:{dependencyType:"stateVariable",variableName:"targetComponent"},typeAttr:{dependencyType:"attributePrimitive",attributeName:"createComponentOfType"},targetSubnames:{dependencyType:"stateVariable",variableName:"targetSubnames"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=e.isPlainCopy&&(!t.isCompositeComponent({componentType:e.targetComponent?.componentType})||e.targetSubnames);if(n&&e.typeAttr){n=!1;let r=t.componentTypeLowerCaseMapping[e.typeAttr.toLowerCase()],a=t.allComponentClasses[e.targetComponent?.componentType];if(a){let e=t.publicStateVariableInfo[a.componentType].stateVariableDescriptions[a.variableForPlainCopy];r===a.componentType||!e||void 0!==e.createComponentOfType&&e.createComponentOfType!==r||(n=!0)}}return{setValue:{isPlainCopy:n}}}},e.linkAttrForDetermineDeps={returnDependencies:()=>({linkAttr:{dependencyType:"attributePrimitive",attributeName:"link"}}),definition({dependencyValues:e}){let t;return t=null===e.linkAttr||e.linkAttr,{setValue:{linkAttrForDetermineDeps:t}}}},e.replacementSourceIdentities={stateVariablesDeterminingDependencies:["targetComponent","componentIndex","propName","targetSubnames","targetSubnamesComponentIndex","obtainPropFromComposite","linkAttrForDetermineDeps"],additionalStateVariablesDefined:["addLevelToAssignNames"],returnDependencies:function({stateValues:e,componentInfoObjects:t}){let n={},r=!1,a=!1;if(null!==e.targetComponent){if(t.isCompositeComponent({componentType:e.targetComponent.componentType,includeNonStandard:!1})&&(!e.propName||!e.obtainPropFromComposite))if(e.linkAttrForDetermineDeps){a=!0;let t=e.targetSubnamesComponentIndex;t&&(t=[...t]),n.targets={dependencyType:"replacement",compositeName:e.targetComponent.componentName,recursive:!0,componentIndex:e.componentIndex,targetSubnames:e.targetSubnames,targetSubnamesComponentIndex:t}}else r=!0;a||null!==e.componentIndex&&1!==e.componentIndex||(n.targets={dependencyType:"stateVariable",variableName:"targetComponent"})}return n.addLevelToAssignNames={dependencyType:"value",value:r},n},definition({dependencyValues:e}){let t=null;return e.targets&&(t=e.targets,Array.isArray(t)||(t=[t])),{setValue:{replacementSourceIdentities:t,addLevelToAssignNames:e.addLevelToAssignNames}}}},e.replacementSources={stateVariablesDeterminingDependencies:["replacementSourceIdentities","propName","propIndex","isPlainMacro","isPlainCopy"],additionalStateVariablesDefined:["effectivePropNameBySource"],returnDependencies:function({stateValues:e,componentInfoObjects:t}){let n={replacementSourceIdentities:{dependencyType:"stateVariable",variableName:"replacementSourceIdentities"},propIndex:{dependencyType:"stateVariable",variableName:"propIndex"}};if(!e.propName&&null!==e.propIndex)throw Error("You cannot specify a propIndex without specifying a prop.");if(null!==e.replacementSourceIdentities)for(let[r,a]of e.replacementSourceIdentities.entries()){let i,s=e.propName;if(e.isPlainMacro?s=t.allComponentClasses[a.componentType].variableForPlainMacro:e.isPlainCopy&&(s=t.allComponentClasses[a.componentType].variableForPlainCopy),s){n["propName"+r]={dependencyType:"value",value:s};let t=e.propIndex;t&&(t=[...t]),i={dependencyType:"stateVariable",componentName:a.componentName,variableName:s,returnAsComponentObject:!0,variablesOptional:!0,propIndex:t,caseInsensitiveVariableMatch:!0,publicStateVariablesOnly:!0,useMappedVariableNames:!0}}else i={dependencyType:"componentIdentity",componentName:a.componentName};n["target"+r]=i}return n},definition({dependencyValues:e}){let t=null,n=null;if(null!==e.replacementSourceIdentities){t=[],n=[];for(let r in e.replacementSourceIdentities){let a=e["target"+r];if(a){let i;t.push(a),a.stateValues&&(i=Object.keys(a.stateValues)[0]),!i&&e["propName"+r]&&(i="__prop_name_not_found"),n.push(i)}}}return{setValue:{replacementSources:t,effectivePropNameBySource:n}}}},e.nComponentsSpecified={returnDependencies:()=>({nComponentsAttr:{dependencyType:"attributePrimitive",attributeName:"nComponents"},typeAttr:{dependencyType:"attributePrimitive",attributeName:"createComponentOfType"}}),definition({dependencyValues:e,componentInfoObjects:t}){let n;if(e.typeAttr){if(!(t.componentTypeLowerCaseMapping[e.typeAttr.toLowerCase()]in t.allComponentClasses))throw Error(`Invalid componentType ${e.typeAttr} of copy.`);n=null!==e.nComponentsAttr?e.nComponentsAttr:1}else{if(null!==e.nComponentsAttr)throw Error("You must specify createComponentOfType when specifying nComponents for a copy.");n=null}return{setValue:{nComponentsSpecified:n}}}},e.link={returnDependencies:()=>({linkAttr:{dependencyType:"attributePrimitive",attributeName:"link"},serializedComponentsForCid:{dependencyType:"stateVariable",variableName:"serializedComponentsForCid"},replacementSourceIdentities:{dependencyType:"stateVariable",variableName:"replacementSourceIdentities"}}),definition({dependencyValues:e,componentInfoObjects:t}){let n;return n=null===e.linkAttr?!(e.serializedComponentsForCid||e.replacementSourceIdentities&&e.replacementSourceIdentities.some((e=>t.isInheritedComponentType({inheritedComponentType:e.componentType,baseComponentType:"module"})))):!1!==e.linkAttr,{setValue:{link:n}}}},e.readyToExpandWhenResolved={stateVariablesDeterminingDependencies:["targetComponent","propName","obtainPropFromComposite","link"],returnDependencies({stateValues:e,componentInfoObjects:t}){let n={targetComponent:{dependencyType:"stateVariable",variableName:"targetComponent"},needsReplacementsUpdatedWhenStale:{dependencyType:"stateVariable",variableName:"needsReplacementsUpdatedWhenStale"},serializedComponentsForCid:{dependencyType:"stateVariable",variableName:"serializedComponentsForCid"},link:{dependencyType:"stateVariable",variableName:"link"}};return!e.targetComponent||!t.isCompositeComponent({componentType:e.targetComponent.componentType,includeNonStandard:!1})||e.propName&&e.obtainPropFromComposite||(n.targetReadyToExpandWhenResolved={dependencyType:"stateVariable",componentName:e.targetComponent.componentName,variableName:"readyToExpandWhenResolved"}),e.link||(n.replacementSources={dependencyType:"stateVariable",variableName:"replacementSources"}),n},definition:()=>({setValue:{readyToExpandWhenResolved:!0}})},e.needsReplacementsUpdatedWhenStale={stateVariablesDeterminingDependencies:["targetComponent","replacementSourceIdentities","effectivePropNameBySource","propName","obtainPropFromComposite","link","removeEmptyArrayEntries"],returnDependencies:function({stateValues:e,componentInfoObjects:t}){if(!e.link)return{};let n={targetComponent:{dependencyType:"stateVariable",variableName:"targetComponent"},targetInactive:{dependencyType:"stateVariable",variableName:"targetInactive"},replacementSourceIdentities:{dependencyType:"stateVariable",variableName:"replacementSourceIdentities"},propIndex:{dependencyType:"stateVariable",variableName:"propIndex"}};if(null!==e.effectivePropNameBySource)for(let[t,r]of e.effectivePropNameBySource.entries())if(r){let a=e.replacementSourceIdentities[t];n["sourceArraySize"+t]={dependencyType:"stateVariableArraySize",componentName:a.componentName,variableName:r,variablesOptional:!0,caseInsensitiveVariableMatch:!0},n["sourceComponentType"+t]={dependencyType:"stateVariableComponentType",componentName:a.componentName,variableName:r,variablesOptional:!0,caseInsensitiveVariableMatch:!0}}return null===e.targetComponent||!t.isCompositeComponent({componentType:e.targetComponent.componentType,includeNonStandard:!1})||e.propName&&e.obtainPropFromComposite||(n.allReplacementIdentities={dependencyType:"replacement",compositeName:e.targetComponent.componentName,recursive:!0,variableNames:["isInactiveCompositeReplacement"]}),e.removeEmptyArrayEntries&&(n.replacementSources={dependencyType:"stateVariable",variableName:"replacementSources"}),n},markStale:()=>({updateReplacements:!0}),definition:()=>({setValue:{needsReplacementsUpdatedWhenStale:!0}})},e.effectiveAssignNames={returnDependencies:()=>({assignNames:{dependencyType:"doenetAttribute",attributeName:"assignNames"},addLevelToAssignNames:{dependencyType:"stateVariable",variableName:"addLevelToAssignNames"}}),definition({dependencyValues:e}){let t=e.assignNames;return t&&e.addLevelToAssignNames&&(t=[t]),{setValue:{effectiveAssignNames:t}}}},e}static async createSerializedReplacements({component:e,components:t,workspace:n,componentInfoObjects:r,flags:a,resolveItem:i,publicCaseInsensitiveAliasSubstitutions:s}){await e.stateValues.nComponentsSpecified,n.numReplacementsBySource=[],n.numNonStringReplacementsBySource=[],n.propVariablesCopiedBySource=[],n.sourceNames=[],n.uniqueIdentifiersUsedBySource={};let o=e.attributes.newNamespace?.primitive,l=this.createAttributesObject(),u=await e.stateValues.effectiveAssignNames,c=await e.stateValues.serializedComponentsForCid;if(c){let t=deepClone([c[0]]),i=deepClone(c.slice(1));if(t[0].children){let n;if(n=t[0].componentName?t[0].componentName+"/":t[0].originalName+"/",e.doenetAttributes.keptNewNamespaceOfLastChild){n=n.slice(0,n.length-1);let e=n.lastIndexOf("/");n=n.slice(0,e+1)}restrictTNamesToNamespace({components:t[0].children,namespace:n,invalidateReferencesToBaseNamespace:e.doenetAttributes.keptNewNamespaceOfLastChild})}if("externalContent"===t[0].componentType)for(let n of t[0].children){if("object"!=typeof n)continue;n.attributes||(n.attributes={});let t=convertAttributesForComponentType({attributes:e.attributes,componentType:n.componentType,componentInfoObjects:r,compositeAttributesObj:l,compositeCreatesNewNamespace:o,flags:a});for(let e in t){let n=t[e];n.component?setTNamesToAbsolute([n.component]):n.childrenForComponent&&setTNamesToAbsolute(n.childrenForComponent)}Object.assign(n.attributes,t)}else{t[0].attributes||(t[0].attributes={});let n=convertAttributesForComponentType({attributes:e.attributes,componentType:t[0].componentType,componentInfoObjects:r,compositeAttributesObj:l,compositeCreatesNewNamespace:o,flags:a});for(let e in n){let t=n[e];t.component?setTNamesToAbsolute([t.component]):t.childrenForComponent&&setTNamesToAbsolute(t.childrenForComponent)}Object.assign(t[0].attributes,n)}return t=processAssignNames({assignNames:u,assignNewNamespaces:e.attributes.assignNewNamespaces?.primitive,serializedComponents:t,parentName:e.componentName,parentCreatesNewNamespace:o,componentInfoObjects:r}).serializedComponents,e.doenetAttributes.fromCopyFromURI&&i.length>0&&this.addChildrenFromComposite({replacements:t,children:i,assignNewNamespaces:e.attributes.assignNewNamespaces?.primitive,componentInfoObjects:r}),{replacements:(await verifyReplacementsMatchSpecifiedType({component:e,replacements:t,assignNames:u,workspace:n,componentInfoObjects:r,compositeAttributesObj:l,flags:a})).replacements}}let p=await e.stateValues.sourceIndex;if(null!==p){let t=processAssignNames({assignNames:u,serializedComponents:[{componentType:"number",attributes:convertAttributesForComponentType({attributes:e.attributes,componentType:"number",componentInfoObjects:r,compositeAttributesObj:l,compositeCreatesNewNamespace:o,flags:a}),state:{value:p,fixed:!0}}],parentName:e.componentName,parentCreatesNewNamespace:o,componentInfoObjects:r});return{replacements:(await verifyReplacementsMatchSpecifiedType({component:e,replacements:t.serializedComponents,assignNames:u,workspace:n,componentInfoObjects:r,compositeAttributesObj:l,flags:a})).replacements}}let d=await e.stateValues.replacementSourceIdentities;if(!await e.stateValues.targetComponent||!d){let t=[];if(e.doenetAttributes.fromCopyTarget){let i=r.componentTypeLowerCaseMapping[e.attributes.createComponentOfType.primitive.toLowerCase()],s=r.allComponentClasses[i],c=convertAttributesForComponentType({attributes:e.attributes,componentType:i,componentInfoObjects:r,compositeAttributesObj:l,compositeCreatesNewNamespace:o,flags:a});n.uniqueIdentifiersUsedBySource[0]=[];let p=getUniqueIdentifierFromBase(i+"|empty",n.uniqueIdentifiersUsedBySource[0]),d=deepClone(e.serializedChildren);s.includeBlankStringChildren||(d=d.filter((e=>"string"!=typeof e||""!==e.trim())));let m=c;e.attributes.assignNewNamespaces?.primitive&&(m.newNamespace={primitive:!0}),t=[{componentType:i,attributes:m,children:d,uniqueIdentifier:p}],t=processAssignNames({assignNames:u,serializedComponents:t,parentName:e.componentName,componentInfoObjects:r,originalNamesAreConsistent:!0}).serializedComponents,n.numReplacementsBySource.push(t.length),n.numNonStringReplacementsBySource.push(t.filter((e=>"string"!=typeof e)).length)}return{replacements:(await verifyReplacementsMatchSpecifiedType({component:e,replacements:t,assignNames:u,workspace:n,componentInfoObjects:r,compositeAttributesObj:l})).replacements}}let m=await i({componentName:e.componentName,type:"determineDependencies",stateVariable:"replacementSources",dependency:"__determine_dependencies",expandComposites:!1});if(!m.success)throw Error(`Couldn't resolve determineDependencies of replacementSources of ${e.componentName}`);let h=await e.stateValues.effectivePropNameBySource;for(let t in d){if(h[t]&&(m=await i({componentName:e.componentName,type:"recalculateDownstreamComponents",stateVariable:"replacementSources",dependency:"target"+t,expandComposites:!1}),!m.success))throw Error(`Couldn't resolve recalculateDownstreamComponents for target${t} of replacementSources of ${e.componentName}`)}let f=[],y=[],g=[],b=0,v=0;for(let i in d){let o,u=n.uniqueIdentifiersUsedBySource[i]=[];if(e.attributes.createComponentOfType?.primitive){let t=await e.stateValues.nComponentsSpecified,n=d.length;o=Math.floor(t/n),i"string"!=typeof e)).length,b+=y[i],v+=g[i],f.push(...p)}return n.numReplacementsBySource=y,n.numNonStringReplacementsBySource=g,n.sourceNames=d.map((e=>e.componentName)),{replacements:(await verifyReplacementsMatchSpecifiedType({component:e,replacements:f,assignNames:u,workspace:n,componentInfoObjects:r,compositeAttributesObj:l,flags:a})).replacements}}static async createReplacementForSource({component:e,sourceNum:t,components:n,numReplacementsSoFar:r,numNonStringReplacementsSoFar:a,uniqueIdentifiersUsed:i,compositeAttributesObj:s,componentInfoObjects:o,nComponentsForSource:l,publicCaseInsensitiveAliasSubstitutions:u,flags:c,fromCopyTarget:p}){let d=(await e.stateValues.replacementSourceIdentities)[t];if("object"!=typeof d)return{serializedReplacements:[d]};let m=n[d.componentName],h=await e.stateValues.link;h&&!await e.stateValues.removeEmptyArrayEntries||(d=(await e.stateValues.replacementSources)[t]);let f=e.attributes.newNamespace?.primitive,y=await e.stateValues.effectiveAssignNames,g=(await e.stateValues.effectivePropNameBySource)[t];if(g){let t=await replacementFromProp({component:e,components:n,replacementSource:d,propName:g,numReplacementsSoFar:r,numNonStringReplacementsSoFar:a,uniqueIdentifiersUsed:i,compositeAttributesObj:s,componentInfoObjects:o,nComponentsForSource:l,publicCaseInsensitiveAliasSubstitutions:u,flags:c});return{serializedReplacements:processAssignNames({assignNames:y,serializedComponents:t.serializedReplacements,parentName:e.componentName,parentCreatesNewNamespace:f,indOffset:a,componentInfoObjects:o}).serializedComponents,propVariablesCopiedByReplacement:t.propVariablesCopiedByReplacement}}let b=await e.stateValues.sourceAttributesToIgnore,v=await e.stateValues.sourceAttributesToIgnoreRecursively,N=[await m.serialize({copyAll:!h,copyVariants:!h,sourceAttributesToIgnore:b,sourceAttributesToIgnoreRecursively:v})];h||void 0===N[0].state?.fixed||delete N[0].state.fixed,N=postProcessCopy({serializedComponents:N,componentName:e.componentName,uniqueIdentifiersUsed:i,addShadowDependencies:h,unlinkExternalCopies:!h}),N.length>0&&delete N[0].doenetAttributes.haveNewNamespaceOnlyFromShadow;for(let t of N){if("object"!=typeof t)continue;t.attributes||(t.attributes={});let n=convertAttributesForComponentType({attributes:e.attributes,componentType:t.componentType,componentInfoObjects:o,compositeAttributesObj:s,compositeCreatesNewNamespace:f,flags:c});Object.assign(t.attributes,n)}return N[0].attributes.newNamespace?.primitive&&!e.attributes.assignNewNamespaces?.primitive&&(N[0].doenetAttributes.haveNewNamespaceOnlyFromShadow=!0),N=processAssignNames({assignNames:y,assignNewNamespaces:e.attributes.assignNewNamespaces?.primitive,serializedComponents:N,parentName:e.componentName,parentCreatesNewNamespace:f,indOffset:a,componentInfoObjects:o,originalNamesAreConsistent:f&&!y}).serializedComponents,p&&1===N.length&&e.serializedChildren.length>0&&this.addChildrenFromComposite({replacements:N,children:e.serializedChildren,assignNewNamespaces:e.attributes.assignNewNamespaces?.primitive,componentInfoObjects:o}),{serializedReplacements:N}}static addChildrenFromComposite({replacements:e,children:t,assignNewNamespaces:n,componentInfoObjects:r}){let a=e[0];a.children||(a.children=[]);let i=deepClone(t);if(r.allComponentClasses[a.componentType].includeBlankStringChildren||(i=i.filter((e=>"string"!=typeof e||""!==e.trim()))),e[0].attributes.newNamespace?.primitive&&n){renameAutonameBasedOnNewCounts(i,countRegularComponentTypesInNamespace(a.children))}let s=processAssignNames({serializedComponents:i,parentName:e[0].componentName,parentCreatesNewNamespace:n,componentInfoObjects:r,originalNamesAreConsistent:!0});if(e[0].attributes.newNamespace?.primitive&&!n)for(let e of s.serializedComponents)"object"==typeof e&&(e.doenetAttributes.ignoreParentNewNamespace=!0);a.children.push(...s.serializedComponents)}static async calculateReplacementChanges({component:e,componentChanges:t,components:n,workspace:r,componentInfoObjects:a,flags:i,resolveItem:s,publicCaseInsensitiveAliasSubstitutions:o}){if(await e.stateValues.serializedComponentsForCid)return[];if(null!==await e.stateValues.sourceIndex)return[];let l=this.createAttributesObject(),u=await e.stateValues.effectiveAssignNames,c=await e.stateValues.replacementSourceIdentities;if(!await e.stateValues.targetComponent||!c){if(await e.stateValues.targetSources)return[];{let t=[];if(e.replacements.length>0){let n={changeType:"delete",changeTopLevelReplacements:!0,firstReplacementInd:0,numberReplacementsToDelete:e.replacements.length};t.push(n)}let n=0===r.sourceNames.length;r.sourceNames=[],r.numReplacementsBySource=[],r.numNonStringReplacementsBySource=[],r.propVariablesCopiedBySource=[];let s=await verifyReplacementsMatchSpecifiedType({component:e,replacementChanges:t,assignNames:u,workspace:r,componentInfoObjects:a,compositeAttributesObj:l,flags:i});return n?[]:s.replacementChanges}}if(await e.stateValues.targetInactive){let t=[],n=e.replacements.length;if(n>0){if(e.replacementsToWithhold!==n){let e={changeType:"changeReplacementsToWithhold",replacementsToWithhold:n};t.push(e)}t=(await verifyReplacementsMatchSpecifiedType({component:e,replacementChanges:t,assignNames:u,workspace:r,componentInfoObjects:a,compositeAttributesObj:l,flags:i})).replacementChanges}return t}let p=await s({componentName:e.componentName,type:"determineDependencies",stateVariable:"replacementSources",dependency:"__determine_dependencies",expandComposites:!1});if(!p.success)throw Error(`Couldn't resolve determineDependencies of replacementSources of ${e.componentName}`);let d=await e.stateValues.effectivePropNameBySource;for(let t in c){if(d[t]&&(p=await s({componentName:e.componentName,type:"recalculateDownstreamComponents",stateVariable:"replacementSources",dependency:"target"+t,expandComposites:!1}),!p.success))throw Error(`Couldn't resolve recalculateDownstreamComponents for target${t} of replacementSources of ${e.componentName}`)}let m=[];if(e.replacementsToWithhold>0){let e={changeType:"changeReplacementsToWithhold",replacementsToWithhold:0};m.push(e)}let h=0,f=0,y=[],g=[],b=[],v=Math.max(c.length,r.numReplacementsBySource.length),N=!1;for(let t=0;t0){if(!N){let e=r.numReplacementsBySource.slice(t).reduce(((e,t)=>e+t),0);if(e>0){let t={changeType:"delete",changeTopLevelReplacements:!0,firstReplacementInd:h,numberReplacementsToDelete:e};m.push(t)}N=!0,r.numReplacementsBySource.slice(t).forEach(((e,t)=>r.numReplacementsBySource[t]=0)),r.numNonStringReplacementsBySource.slice(t).forEach(((e,t)=>r.numNonStringReplacementsBySource[t]=0))}r.uniqueIdentifiersUsedBySource[t]=[]}y[t]=0,g[t]=0,b.push([]);continue}let p=r.sourceNames[t],v=void 0===p||u.componentName!==p||N;if(!v)for(let n=0;ne+t),0);v.numberReplacementsToReplace=e,N=!0,r.numReplacementsBySource.slice(t).forEach(((e,t)=>r.numReplacementsBySource[t]=0)),r.numNonStringReplacementsBySource.slice(t).forEach(((e,t)=>r.numNonStringReplacementsBySource[t]=0))}m.push(v);continue}if(!d[t]&&r.numReplacementsBySource[t]>0){h+=r.numReplacementsBySource[t],f+=r.numNonStringReplacementsBySource[t],y[t]=r.numReplacementsBySource[t],g[t]=r.numNonStringReplacementsBySource[t];continue}let T=r.uniqueIdentifiersUsedBySource[t]=[],C=await this.createReplacementForSource({component:e,sourceNum:t,components:n,numReplacementsSoFar:h,numNonStringReplacementsSoFar:f,uniqueIdentifiersUsed:T,compositeAttributesObj:l,componentInfoObjects:a,nComponentsForSource:s,publicCaseInsensitiveAliasSubstitutions:o,flags:i}),A=C.propVariablesCopiedByReplacement,V=C.serializedReplacements,x=V.length;if(x!==r.numReplacementsBySource[t]){let e=r.numReplacementsBySource.slice(t).reduce(((e,t)=>e+t),0),n={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:h,numberReplacementsToReplace:e,serializedReplacements:V,assignNamesOffset:f};m.push(n),N=!0,r.numReplacementsBySource.slice(t).forEach(((e,t)=>r.numReplacementsBySource[t]=0)),r.numNonStringReplacementsBySource.slice(t).forEach(((e,t)=>r.numNonStringReplacementsBySource[t]=0))}else{let n=0;for(let a=0;ae!==A[a][t]))?(s=!1,i=!0):e.replacements[h+a].componentType!==V[a].componentType&&(i=!0)),0==a&&i&&s){1===await e.stateValues.nComponentsSpecified&&1===x&&!(e.replacementsToWithhold>0)&&1===r.sourceNames.length&&(i=!1)}if(i){let e={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:h+a,numberReplacementsToReplace:1,serializedReplacements:[V[a]],assignNamesOffset:f+n};m.push(e)}"string"!=typeof V[a]&&n++}}let S=V.filter((e=>"string"!=typeof e)).length;h+=x,f+=S,y[t]=x,g[t]=S,b[t]=A}let T=0===r.sourceNames.length;r.numReplacementsBySource=y,r.numNonStringReplacementsBySource=g,r.sourceNames=c.map((e=>e.componentName)),r.propVariablesCopiedBySource=b;let C=await verifyReplacementsMatchSpecifiedType({component:e,replacementChanges:m,assignNames:u,workspace:r,componentInfoObjects:a,compositeAttributesObj:l,flags:i});return T&&0===r.sourceNames.length?[]:C.replacementChanges}static async recreateReplacements({component:e,sourceNum:t,numReplacementsSoFar:n,numNonStringReplacementsSoFar:r,numReplacementsToDelete:a,uniqueIdentifiersUsed:i,components:s,compositeAttributesObj:o,componentInfoObjects:l,nComponentsForSource:u,publicCaseInsensitiveAliasSubstitutions:c,flags:p}){let d=await this.createReplacementForSource({component:e,sourceNum:t,numReplacementsSoFar:n,numNonStringReplacementsSoFar:r,components:s,uniqueIdentifiersUsed:i,compositeAttributesObj:o,componentInfoObjects:l,nComponentsForSource:u,publicCaseInsensitiveAliasSubstitutions:c,flags:p}),m=d.propVariablesCopiedByReplacement,h=d.serializedReplacements,f={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:n,numberReplacementsToReplace:a,serializedReplacements:h,assignNamesOffset:r};return{numReplacements:h.length,numNonStringReplacements:h.filter((e=>"string"!=typeof e)).length,propVariablesCopiedByReplacement:m,replacementInstruction:f}}}async function replacementFromProp({component:e,components:t,replacementSource:n,propName:r,uniqueIdentifiersUsed:a,compositeAttributesObj:i,componentInfoObjects:s,nComponentsForSource:o,publicCaseInsensitiveAliasSubstitutions:l,flags:u}){let c=[],p=[],d=e.attributes.newNamespace?.primitive,m=-1,h=t[n.componentName],f=l({stateVariables:[r],componentClass:h.constructor})[0];if(void 0===f||"__not_public"===f.slice(0,12))return"__prop_name_not_found"!==r&&console.warn(`Could not find prop ${r} on a component of type ${n.componentType}`),{serializedReplacements:[],propVariablesCopiedByReplacement:[]};let y=h.state[f],g=await y.value,b=await e.stateValues.link;if(y.isArray||y.isArrayEntry){let t,r,l,g;if(y.isArray?(t=y,l=await y.arraySize,r=y.getAllArrayKeys(l,!1)):(t=h.state[y.arrayStateVariable],r=await y.unflattenedArrayKeys,g=await y.arrayKeys),t.shadowingInstructions?.hasVariableComponentType&&(await e.stateValues.replacementSources,!t.shadowingInstructions.createComponentOfType))return{serializedReplacements:[],propVariablesCopiedByReplacement:[]};let v=y.wrappingComponents,N=v.length,T=o;if(y.isArray)T=l.slice(0,l.length-N).reduce(((e,t)=>e*t),1);else if(0===g.length)T=0;else if(0===N)T=g.length;else if(N>=y.nDimensions)T=1;else if(N===y.nDimensions-1)T=r.length;else{T=flattenLevels(r,y.nDimensions-N-1).length}if(0===N){let o=flattenDeep(r);for(let r=0;r1)for(let e of r){let t=await o(e,i-1);l.push(...t.pieces),c.push(...t.propVariablesCopiedByPiece)}else for(let i of r){let r,o,p=t.arrayVarNameFromArrayKey(i),d=[p],m=getUniqueIdentifierFromBase(n.componentName+"|shadow|"+p,a),f=t.shadowingInstructions.createComponentOfType;if(Array.isArray(f)&&(f=f[t.keyToIndex(i)]),t.shadowingInstructions.addAttributeComponentsShadowingStateVariables){r={};for(let e in t.shadowingInstructions.addAttributeComponentsShadowingStateVariables){let n=t.shadowingInstructions.addAttributeComponentsShadowingStateVariables[e].stateVariableToShadow,a=h.state[n];a.isArray&&(n=a.arrayVarNameFromArrayKey(i)),r[e]={stateVariableToShadow:n}}}if(t.shadowingInstructions.addStateVariablesShadowingStateVariables){o={};for(let e in t.shadowingInstructions.addStateVariablesShadowingStateVariables){let n=t.shadowingInstructions.addStateVariablesShadowingStateVariables[e].stateVariableToShadow,r=h.state[n];r.isArray&&(n=r.arrayVarNameFromArrayKey(i)),o[e]={stateVariableToShadow:n}}}if(b){let t={};if(r){let n=s.allComponentClasses[f].createAttributesObject();for(let a in r){let i=r[a].stateVariableToShadow,s={componentType:n[a].createComponentOfType,downstreamDependencies:{[h.componentName]:[{compositeName:e.componentName,dependencyType:"referenceShadow",propVariable:i}]}};t[a]={component:s}}}l.push({componentType:f,attributes:t,downstreamDependencies:{[n.componentName]:[{dependencyType:"referenceShadow",compositeName:e.componentName,propVariable:p,additionalStateVariableShadowing:o}]},uniqueIdentifier:m})}else{let e={};if(r){let t={};for(let e in r){let n=r[e].stateVariableToShadow,a=h.state[n],s=await a.value;a.isArray&&(s=s[a.keyToIndex[i]]),h.state[n].usedDefault||(t[e]=s)}let n=convertAttributesForComponentType({attributes:t,componentType:f,componentInfoObjects:s,flags:u});if(y.shadowingInstructions.attributesToShadow)for(let e of y.shadowingInstructions.attributesToShadow)h.attributes[e]?.component?n[e]={component:await(h.attributes[e]?.component.serialize({copyAll:!0,copyVariants:!0}))}:void 0!==h.attributes[e]?.primitive&&(n[e]={primitive:JSON.parse(JSON.stringify(h.attributes[e].primitive))});Object.assign(e,n)}let n="value",a=s.allComponentClasses[f];a.primaryEssentialStateVariable?n=a.primaryEssentialStateVariable:a.primaryStateVariableForDefinition&&(n=a.primaryStateVariableForDefinition);let o=t.keyToIndex(i);Array.isArray(o)||(o=[o]);let c=await t.value;for(let e of o)c=c[e];let p={componentType:f,attributes:e,state:{[n]:c},uniqueIdentifier:m};l.push(p)}c.push(d)}let p=v[i-1];if(l.length>0&&p&&p.length>0){for(let e=p.length-1;e>=0;e--){let t="object"==typeof p[e]?p[e].componentType:p[e],n=getUniqueIdentifierFromBase(t+"|wrapper",a),r=[],i={};for(let e of l)if(e.isAttribute){let t=e.isAttribute;delete e.isAttribute,i[t]={component:e}}else r.push(e);l=[{componentType:t,children:r,attributes:i,uniqueIdentifier:n,skipSugar:!0}],"object"==typeof p[e]&&(p[e].doenetAttributes&&(l[0].doenetAttributes=Object.assign({},p[e].doenetAttributes)),p[e].isAttribute&&(l[0].isAttribute=p[e].isAttribute))}c=[flattenDeep(c)]}return{pieces:l,propVariablesCopiedByPiece:c}},l=await o(r,y.nDimensions),N=l.pieces;p=l.propVariablesCopiedByPiece;for(let t of N){if("object"!=typeof t)continue;t.attributes||(t.attributes={});let r=convertAttributesForComponentType({attributes:e.attributes,componentType:t.componentType,componentInfoObjects:s,compositeAttributesObj:i,compositeCreatesNewNamespace:d,flags:u});Object.assign(t.attributes,r),b&&(t.downstreamDependencies={[n.componentName]:[{dependencyType:"referenceShadow",compositeName:e.componentName,propVariable:f,ignorePrimaryStateVariable:!0}]})}if(m+=N.length,c.push(...N),N.length0?"object"==typeof i[0]?(n=i[0].componentType,r=Object.assign({},i[0].doenetAttributes)):n=i[0]:(n=t.shadowingInstructions.createComponentOfType,Array.isArray(n)&&(n=y.isArrayEntry?n[t.keyToIndex(g[e])]:n[e]));let s={componentType:n,uniqueIdentifier:getUniqueIdentifierFromBase(n+"|empty",a)};r&&(s.doenetAttributes=r),c.push(s)}else if(N>T)throw Error(`Something went wrong when creating replacements for ${e.componentName} as we ended up with too many replacements`)}}else{if(y.shadowingInstructions?.hasVariableComponentType&&await y.value,!y.shadowingInstructions?.createComponentOfType)return{serializedReplacements:[],propVariablesCopiedByReplacement:[]};m++,(p[m]=[]).push(f);let t=getUniqueIdentifierFromBase(h.componentName+"|shadow|"+f,a);if("string"===y.shadowingInstructions.createComponentOfType)c.push(await y.value);else{let n=convertAttributesForComponentType({attributes:e.attributes,componentType:y.shadowingInstructions.createComponentOfType,componentInfoObjects:s,compositeAttributesObj:i,compositeCreatesNewNamespace:d,flags:u});if(b){let r={};if(y.shadowingInstructions.addAttributeComponentsShadowingStateVariables){let t=s.allComponentClasses[y.shadowingInstructions.createComponentOfType].createAttributesObject();for(let n in y.shadowingInstructions.addAttributeComponentsShadowingStateVariables){let a=y.shadowingInstructions.addAttributeComponentsShadowingStateVariables[n].stateVariableToShadow,i={componentType:t[n].createComponentOfType,downstreamDependencies:{[h.componentName]:[{compositeName:e.componentName,dependencyType:"referenceShadow",propVariable:a}]}};r[n]={component:i}}}Object.assign(r,n),c.push({componentType:y.shadowingInstructions.createComponentOfType,attributes:r,downstreamDependencies:{[h.componentName]:[{dependencyType:"referenceShadow",compositeName:e.componentName,propVariable:f,additionalStateVariableShadowing:y.shadowingInstructions.addStateVariablesShadowingStateVariables}]},uniqueIdentifier:t})}else{let e={};if(y.shadowingInstructions.addAttributeComponentsShadowingStateVariables){let t={};for(let e in y.shadowingInstructions.addAttributeComponentsShadowingStateVariables)if("fixed"!==e){let n=y.shadowingInstructions.addAttributeComponentsShadowingStateVariables[e].stateVariableToShadow,r=await h.state[n].value;h.state[n].usedDefault||(t[e]=r)}let n=convertAttributesForComponentType({attributes:t,componentType:y.shadowingInstructions.createComponentOfType,componentInfoObjects:s,flags:u});if(y.shadowingInstructions.attributesToShadow)for(let e of y.shadowingInstructions.attributesToShadow)h.attributes[e]?.component?n[e]={component:await(h.attributes[e]?.component.serialize({copyAll:!0,copyVariants:!0}))}:void 0!==h.attributes[e]?.primitive&&(n[e]={primitive:JSON.parse(JSON.stringify(h.attributes[e].primitive))});Object.assign(e,n)}Object.assign(e,n);let r="value",a=s.allComponentClasses[y.shadowingInstructions.createComponentOfType];a.primaryEssentialStateVariable?r=a.primaryEssentialStateVariable:a.primaryStateVariableForDefinition&&(r=a.primaryStateVariableForDefinition);let i={componentType:y.shadowingInstructions.createComponentOfType,attributes:e,state:{[r]:g},uniqueIdentifier:t};c.push(i)}}}return{serializedReplacements:c,propVariablesCopiedByReplacement:p}}class Extract extends CompositeComponent{static componentType="extract";static assignNamesToReplacements=!0;static acceptAnyAttribute=!0;static stateVariableToEvaluateAfterReplacements="needsReplacementsUpdatedWhenStale";static createAttributesObject(){let e=super.createAttributesObject();return delete e.disabled,delete e.modifyIndirectly,delete e.fixed,delete e.styleNumber,delete e.isResponse,e.assignNamesSkip={createPrimitiveOfType:"number"},e.prop={createPrimitiveOfType:"string"},e.createComponentOfType={createPrimitiveOfType:"string"},e.nComponents={createPrimitiveOfType:"number"},e.componentIndex={createComponentOfType:"integer",createStateVariable:"componentIndex",defaultValue:null,public:!0},e.propIndex={createComponentOfType:"numberList",createStateVariable:"propIndex",defaultValue:null,public:!0},e}static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nComponentsSpecified={returnDependencies:()=>({nComponentsAttr:{dependencyType:"attributePrimitive",attributeName:"nComponents"},typeAttr:{dependencyType:"attributePrimitive",attributeName:"createComponentOfType"}}),definition({dependencyValues:e,componentInfoObjects:t}){let n;if(e.typeAttr){if(!(t.componentTypeLowerCaseMapping[e.typeAttr.toLowerCase()]in t.allComponentClasses))throw Error(`Invalid componentType ${e.typeAttr} of copy.`);n=null!==e.nComponentsAttr?e.nComponentsAttr:1}else{if(null!==e.nComponentsAttr)throw Error("You must specify createComponentOfType when specifying nComponents for a copy.");n=null}return{setValue:{nComponentsSpecified:n}}}},e.link={returnDependencies:()=>({}),definition:()=>({setValue:{link:!0}})},e.propName={shadowVariable:!0,returnDependencies:()=>({propName:{dependencyType:"attributePrimitive",attributeName:"prop"}}),definition:function({dependencyValues:e}){return{setValue:{propName:e.propName}}}},e.sourceComponents={stateVariablesDeterminingDependencies:["propName","componentIndex","propIndex"],additionalStateVariablesDefined:["effectivePropNameBySource"],returnDependencies:function({stateValues:e}){let t,n;null!==e.componentIndex&&(n=Number(e.componentIndex),t=Number.isInteger(n)?[n-1]:[]);let r=e.propIndex;return r&&(r=[...r]),{children:{dependencyType:"child",childGroups:["anything"],variableNames:[e.propName],variablesOptional:!0,childIndices:t,propIndex:r,caseInsensitiveVariableMatch:!0,publicStateVariablesOnly:!0,useMappedVariableNames:!0},propName:{dependencyType:"stateVariable",variableName:"propName"}}},definition:function({dependencyValues:e}){let t=e.children,n=[];for(let e of t){let t;e.stateValues&&(t=Object.keys(e.stateValues)[0]),t||(t="__prop_name_not_found"),n.push(t)}return{setValue:{sourceComponents:t,effectivePropNameBySource:n}}}},e.readyToExpandWhenResolved={returnDependencies:()=>({replacementClasses:{dependencyType:"stateVariable",variableName:"sourceComponents"},needsReplacementsUpdatedWhenStale:{dependencyType:"stateVariable",variableName:"needsReplacementsUpdatedWhenStale"}}),definition:()=>({setValue:{readyToExpandWhenResolved:!0}})},e.needsReplacementsUpdatedWhenStale={returnDependencies:()=>({sourceComponents:{dependencyType:"stateVariable",variableName:"sourceComponents"}}),markStale:()=>({updateReplacements:!0}),definition:()=>({setValue:{needsReplacementsUpdatedWhenStale:!0}})},e}static async createSerializedReplacements({component:e,components:t,workspace:n,componentInfoObjects:r,flags:a,publicCaseInsensitiveAliasSubstitutions:i}){let s=[],o=[],l=0;n.propVariablesCopiedBySource=[],n.uniqueIdentifiersUsedBySource={};let u=this.createAttributesObject(),c=await e.stateValues.sourceComponents;for(let a=0;ae.componentName)),{replacements:(await verifyReplacementsMatchSpecifiedType({component:e,replacements:s,assignNames:e.doenetAttributes.assignNames,workspace:n,componentInfoObjects:r,compositeAttributesObj:u,flags:a})).replacements}}static async createReplacementForSource({component:e,components:t,sourceNum:n,numReplacementsSoFar:r,uniqueIdentifiersUsed:a,componentInfoObjects:i,compositeAttributesObj:s,publicCaseInsensitiveAliasSubstitutions:o}){let l=(await e.stateValues.effectivePropNameBySource)[n],u=await replacementFromProp({component:e,components:t,replacementSource:(await e.stateValues.sourceComponents)[n],propName:l,uniqueIdentifiersUsed:a,compositeAttributesObj:s,componentInfoObjects:i,publicCaseInsensitiveAliasSubstitutions:o}),c=u.serializedReplacements,p=u.propVariablesCopiedByReplacement,d=e.attributes.newNamespace?.primitive;return c=processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:c,parentName:e.componentName,indOffset:r,parentCreatesNewNamespace:d,componentInfoObjects:i}).serializedComponents,{serializedReplacements:c,propVariablesCopiedByReplacement:p}}static async calculateReplacementChanges({component:e,components:t,workspace:n,componentInfoObjects:r,flags:a,publicCaseInsensitiveAliasSubstitutions:i}){let s=[],o=0,l=[],u=[],c=this.createAttributesObject(),p=await e.stateValues.sourceComponents,d=Math.max(p.length,n.numReplacementsBySource.length),m=!1;for(let a=0;a0){if(!m){let e=n.numReplacementsBySource.slice(a).reduce(((e,t)=>e+t),0);if(e>0){let t={changeType:"delete",changeTopLevelReplacements:!0,firstReplacementInd:o,numberReplacementsToDelete:e};s.push(t)}m=!0,n.numReplacementsBySource.slice(a).forEach(((e,t)=>n.numReplacementsBySource[t]=0))}n.uniqueIdentifiersUsedBySource[a]=[]}l[a]=0,u.push([]);continue}let h=n.sourceNames[a],f=void 0===h||d.componentName!==h||m;if(!f)for(let t=0;te+t),0);g.numberReplacementsToReplace=e,m=!0,n.numReplacementsBySource.slice(a).forEach(((e,t)=>n.numReplacementsBySource[t]=0))}s.push(g);continue}let y=n.uniqueIdentifiersUsedBySource[a]=[],g=await this.createReplacementForSource({component:e,sourceNum:a,components:t,numReplacementsSoFar:o,uniqueIdentifiersUsed:y,componentInfoObjects:r,compositeAttributesObj:c,publicCaseInsensitiveAliasSubstitutions:i}),b=g.propVariablesCopiedByReplacement,v=g.serializedReplacements,N=v.length;if(N!==n.numReplacementsBySource[a]){let e=n.numReplacementsBySource.slice(a).reduce(((e,t)=>e+t),0),t={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:o,numberReplacementsToReplace:e,serializedReplacements:v,assignNamesOffset:o};s.push(t),m=!0,n.numReplacementsBySource.slice(a).forEach(((e,t)=>n.numReplacementsBySource[t]=0))}else for(let e=0;et!==b[e][n]))){let t={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:o+e,numberReplacementsToReplace:1,serializedReplacements:[v[e]],assignNamesOffset:o+e};s.push(t)}o+=N,l[a]=N,u[a]=b}return n.numReplacementsBySource=l,n.numNonStringReplacementsBySource=[...l],n.sourceNames=p.map((e=>e.componentName)),n.propVariablesCopiedBySource=u,(await verifyReplacementsMatchSpecifiedType({component:e,replacementChanges:s,assignNames:e.doenetAttributes.assignNames,workspace:n,componentInfoObjects:r,compositeAttributesObj:c,flags:a})).replacementChanges}static async recreateReplacements({component:e,sourceNum:t,numReplacementsSoFar:n,numReplacementsToDelete:r,uniqueIdentifiersUsed:a,components:i,componentInfoObjects:s,compositeAttributesObj:o,publicCaseInsensitiveAliasSubstitutions:l}){let u=await this.createReplacementForSource({component:e,sourceNum:t,numReplacementsSoFar:n,components:i,uniqueIdentifiersUsed:a,componentInfoObjects:s,compositeAttributesObj:o,publicCaseInsensitiveAliasSubstitutions:l}),c=u.propVariablesCopiedByReplacement,p=u.serializedReplacements,d={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:n,numberReplacementsToReplace:r,serializedReplacements:p,assignNamesOffset:n};return{numReplacements:p.length,propVariablesCopiedByReplacement:c,replacementInstruction:d}}}class Collect extends CompositeComponent{static componentType="collect";static assignNamesToReplacements=!0;static acceptTarget=!0;static acceptAnyAttribute=!0;static stateVariableToEvaluateAfterReplacements="needsReplacementsUpdatedWhenStale";static createAttributesObject(){let e=super.createAttributesObject();return delete e.disabled,delete e.modifyIndirectly,delete e.fixed,delete e.styleNumber,delete e.isResponse,e.assignNamesSkip={createPrimitiveOfType:"number"},e.prop={createPrimitiveOfType:"string"},e.maximumNumber={createComponentOfType:"number",createStateVariable:"maximumNumber",defaultValue:null,public:!0},e.componentIndex={createComponentOfType:"integer",createStateVariable:"componentIndex",defaultValue:null,public:!0},e.propIndex={createComponentOfType:"numberList",createStateVariable:"propIndex",defaultValue:null,public:!0},e.sourceAttributesToIgnore={createPrimitiveOfType:"stringArray",createStateVariable:"sourceAttributesToIgnore",defaultValue:[],public:!0},e.sourceAttributesToIgnoreRecursively={createPrimitiveOfType:"stringArray",createStateVariable:"sourceAttributesToIgnoreRecursively",defaultValue:["isResponse"],public:!0},e.componentTypes={createComponentOfType:"textList"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.link={returnDependencies:()=>({}),definition:()=>({setValue:{link:!0}})},e.targetComponent={shadowVariable:!0,returnDependencies:()=>({targetComponent:{dependencyType:"targetComponent"}}),definition:function({dependencyValues:e}){return{setValue:{targetComponent:e.targetComponent}}}},e.targetInactive={stateVariablesDeterminingDependencies:["targetComponent"],returnDependencies:({stateValues:e})=>e.targetComponent?{targetIsInactiveCompositeReplacement:{dependencyType:"stateVariable",componentName:e.targetComponent.componentName,variableName:"isInactiveCompositeReplacement"}}:{},definition:function({dependencyValues:e}){return{setValue:{targetInactive:Boolean(e.targetIsInactiveCompositeReplacement)}}}},e.targetName={returnDependencies:()=>({targetComponent:{dependencyType:"stateVariable",variableName:"targetComponent"}}),definition:function({dependencyValues:e}){return null===e.targetComponent?(console.warn("No copy target"),{setValue:{targetName:""}}):{setValue:{targetName:e.targetComponent.componentName}}}},e.propName={shadowVariable:!0,returnDependencies:()=>({propName:{dependencyType:"attributePrimitive",attributeName:"prop"}}),definition:function({dependencyValues:e}){return{setValue:{propName:e.propName}}}},e.componentTypesToCollect={shadowVariable:!0,additionalStateVariablesDefined:[{variableName:"componentClassesToCollect",shadowVariable:!0}],returnDependencies:()=>({componentTypesAttr:{dependencyType:"attributeComponent",attributeName:"componentTypes",variableNames:["texts"]}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=[],r=[];if(null!==e.componentTypesAttr)for(let a of e.componentTypesAttr.stateValues.texts){let e=t.componentTypeLowerCaseMapping[a.toLowerCase()],i=t.allComponentClasses[e];if(i)n.push(e),r.push(i);else{let e="Cannot collect component type "+a+". Component type not found.";console.warn(e)}}return{setValue:{componentTypesToCollect:n,componentClassesToCollect:r}}}},e.collectedComponents={stateVariablesDeterminingDependencies:["componentTypesToCollect","targetName","propName","componentIndex","propIndex"],additionalStateVariablesDefined:["effectivePropNameByComponent"],returnDependencies:function({stateValues:e}){if(!e.targetName)return{};let t={dependencyType:"descendant",ancestorName:e.targetName,componentTypes:e.componentTypesToCollect,useReplacementsForComposites:!0,includeNonActiveChildren:!0,recurseToMatchedChildren:!1,componentIndex:e.componentIndex};if(e.propName){let n=e.propIndex;n&&(n=[...n]),t.variableNames=[e.propName],t.variablesOptional=!0,t.propIndex=n,t.caseInsensitiveVariableMatch=!0,t.publicStateVariablesOnly=!0,t.useMappedVariableNames=!0}return{descendants:t,maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"},propName:{dependencyType:"stateVariable",variableName:"propName"}}},definition:function({dependencyValues:e}){let t=e.descendants;if(t||(t=[]),null!==e.maximumNumber&&t.length>e.maximumNumber){let n=Math.max(0,Math.floor(e.maximumNumber));t=t.slice(0,n)}let n=[];for(let r of t){let t;r.stateValues&&(t=Object.keys(r.stateValues)[0]),!t&&e.propName&&(t="__prop_name_not_found"),n.push(t)}return{setValue:{collectedComponents:t,effectivePropNameByComponent:n}}}},e.readyToExpandWhenResolved={returnDependencies:()=>({collectedComponents:{dependencyType:"stateVariable",variableName:"collectedComponents"},needsReplacementsUpdatedWhenStale:{dependencyType:"stateVariable",variableName:"needsReplacementsUpdatedWhenStale"}}),definition:()=>({setValue:{readyToExpandWhenResolved:!0}})},e.needsReplacementsUpdatedWhenStale={returnDependencies:()=>({collectedComponents:{dependencyType:"stateVariable",variableName:"collectedComponents"}}),markStale:()=>({updateReplacements:!0}),definition:()=>({setValue:{needsReplacementsUpdatedWhenStale:!0}})},e}static async createSerializedReplacements({component:e,components:t,workspace:n,componentInfoObjects:r,nComponentsForSource:a,publicCaseInsensitiveAliasSubstitutions:i,flags:s}){if(!await e.stateValues.targetComponent)return{replacements:[]};let o=[],l=[],u=0,c=[];n.propVariablesCopiedByCollected=[],n.uniqueIdentifiersUsedByCollected={};let p=this.createAttributesObject(),d=await e.stateValues.collectedComponents;for(let m=0;me.componentName))}else l[m]=0,c[m]=[],n.propVariablesCopiedByCollected[m]=[];return n.numReplacementsByCollected=l,n.collectedNames=d.map((e=>e.componentName)),n.replacementNamesByCollected=c,{replacements:o}}static async createReplacementForCollected({component:e,components:t,collectedNum:n,numReplacementsSoFar:r,uniqueIdentifiersUsed:a,componentInfoObjects:i,compositeAttributesObj:s,nComponentsForSource:o,publicCaseInsensitiveAliasSubstitutions:l,flags:u}){let c=(await e.stateValues.collectedComponents)[n],p=t[c.componentName],d=[],m=[];if(!p)return{serializedReplacements:d,propVariablesCopiedByReplacement:m};let h=e.attributes.newNamespace?.primitive,f=(await e.stateValues.effectivePropNameByComponent)[n];if(f){let n=await replacementFromProp({component:e,components:t,replacementSource:c,propName:f,uniqueIdentifiersUsed:a,compositeAttributesObj:s,componentInfoObjects:i,nComponentsForSource:o,publicCaseInsensitiveAliasSubstitutions:l});d=n.serializedReplacements,m=n.propVariablesCopiedByReplacement}else{let t=await e.stateValues.sourceAttributesToIgnore,r=await e.stateValues.sourceAttributesToIgnoreRecursively;d=postProcessCopy({serializedComponents:[await p.serialize({sourceAttributesToIgnore:t,sourceAttributesToIgnoreRecursively:r})],componentName:e.componentName,uniqueIdentifiersUsed:a,identifierPrefix:n+"|"});for(let t of d){t.attributes||(t.attributes={});let n=convertAttributesForComponentType({attributes:e.attributes,componentType:t.componentType,componentInfoObjects:i,compositeAttributesObj:s,compositeCreatesNewNamespace:h,flags:u});Object.assign(t.attributes,n)}}return d=processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:d,parentName:e.componentName,indOffset:r,parentCreatesNewNamespace:h,componentInfoObjects:i}).serializedComponents,{serializedReplacements:d,propVariablesCopiedByReplacement:m}}static async calculateReplacementChanges({component:e,componentChanges:t,components:n,workspace:r,componentInfoObjects:a,nComponentsForSource:i,publicCaseInsensitiveAliasSubstitutions:s,flags:o}){let l=0;for(let t=0;t0){if(!y){let e=r.numReplacementsByCollected.slice(t).reduce(((e,t)=>e+t),0);if(e>0){let t={changeType:"delete",changeTopLevelReplacements:!0,firstReplacementInd:c,numberReplacementsToDelete:e};u.push(t)}y=!0,r.numReplacementsByCollected.slice(t).forEach(((e,t)=>r.numReplacementsByCollected[t]=0))}r.uniqueIdentifiersUsedByCollected[t]=[]}p[t]=0,d.push([]),m.push([]);continue}let f=r.collectedNames[t];if(void 0===f||l.componentName!==f||y){let l=0;void 0!==f&&(l=r.numReplacementsByCollected[t]);let h=l;y&&(h=0);let b=r.uniqueIdentifiersUsedByCollected[t]=[],v=await this.recreateReplacements({component:e,collectedNum:t,numReplacementsSoFar:c,numReplacementsToDelete:h,components:n,uniqueIdentifiersUsed:b,componentInfoObjects:a,compositeAttributesObj:g,nComponentsForSource:i,publicCaseInsensitiveAliasSubstitutions:s,flags:o});c+=v.numReplacements,p[t]=v.numReplacements,d[t]=v.propVariablesCopiedByReplacement;let N=v.replacementInstruction;if(m[t]=N.serializedReplacements.map((e=>e.componentName)),!y&&v.numReplacements!==l){let e=r.numReplacementsByCollected.slice(t).reduce(((e,t)=>e+t),0);N.numberReplacementsToReplace=e,y=!0,r.numReplacementsByCollected.slice(t).forEach(((e,t)=>r.numReplacementsByCollected[t]=0))}u.push(N);continue}if(!await e.stateValues.propName){c+=r.numReplacementsByCollected[t],p[t]=r.numReplacementsByCollected[t],m[t]=r.replacementNamesByCollected[t],d[t]=[];continue}let b=r.uniqueIdentifiersUsedByCollected[t]=[],v=await this.createReplacementForCollected({component:e,collectedNum:t,components:n,numReplacementsSoFar:c,uniqueIdentifiersUsed:b,componentInfoObjects:a,compositeAttributesObj:g,nComponentsForSource:i,publicCaseInsensitiveAliasSubstitutions:s,flags:o}),N=v.propVariablesCopiedByReplacement,T=v.serializedReplacements,C=T.length;if(C!==r.numReplacementsByCollected[t]){let e=r.numReplacementsByCollected.slice(t).reduce(((e,t)=>e+t),0),n={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:c,numberReplacementsToReplace:e,serializedReplacements:T,assignNamesOffset:c};u.push(n),y=!0,r.numReplacementsByCollected.slice(t).forEach(((e,t)=>r.numReplacementsByCollected[t]=0))}else for(let e=0;et!==N[e][n]))){let t={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:c+e,numberReplacementsToReplace:1,serializedReplacements:[T[e]],assignNamesOffset:c+e};u.push(t)}c+=C,p[t]=C,d[t]=N,m[t]=T.map((e=>e.componentName))}return r.numReplacementsByCollected=p,r.collectedNames=h.map((e=>e.componentName)),r.propVariablesCopiedByCollected=d,r.replacementNamesByCollected=m,u}static async recreateReplacements({component:e,collectedNum:t,numReplacementsSoFar:n,numReplacementsToDelete:r,uniqueIdentifiersUsed:a,components:i,componentInfoObjects:s,compositeAttributesObj:o,nComponentsForSource:l,publicCaseInsensitiveAliasSubstitutions:u,flags:c}){let p=await this.createReplacementForCollected({component:e,collectedNum:t,components:i,numReplacementsSoFar:n,uniqueIdentifiersUsed:a,componentInfoObjects:s,compositeAttributesObj:o,nComponentsForSource:l,publicCaseInsensitiveAliasSubstitutions:u,flags:c}),d=p.propVariablesCopiedByReplacement,m=p.serializedReplacements,h={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:n,numberReplacementsToReplace:r,serializedReplacements:m,assignNamesOffset:n};return{numReplacements:m.length,propVariablesCopiedByReplacement:d,replacementInstruction:h}}}class Ref extends InlineComponent{constructor(e){super(e),Object.assign(this.actions,{navigateToTarget:this.navigateToTarget.bind(this)})}static componentType="ref";static renderChildren=!0;static acceptTarget=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.textType={createComponentOfType:"text",createStateVariable:"textType",defaultValue:"type-global",public:!0},e.uri={createPrimitiveOfType:"string",createStateVariable:"uri",defaultValue:null,public:!0,forRenderer:!0},e.page={createPrimitiveOfType:"integer",createStateVariable:"page",defaultValue:null,public:!0,forRenderer:!0},e.createButton={createComponentOfType:"boolean",createStateVariable:"createButton",defaultValue:!1,forRenderer:!0},e}static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.targetComponent={returnDependencies:()=>({targetComponent:{dependencyType:"targetComponent"}}),definition:function({dependencyValues:e}){return{setValue:{targetComponent:e.targetComponent}}}},e.targetInactive={stateVariablesDeterminingDependencies:["targetComponent"],returnDependencies:({stateValues:e})=>e.targetComponent?{targetIsInactiveCompositeReplacement:{dependencyType:"stateVariable",componentName:e.targetComponent.componentName,variableName:"isInactiveCompositeReplacement"}}:{},definition:function({dependencyValues:e}){return{setValue:{targetInactive:Boolean(e.targetIsInactiveCompositeReplacement)}}}},e.targetName={forRenderer:!0,returnDependencies:()=>({targetComponent:{dependencyType:"stateVariable",variableName:"targetComponent"},uri:{dependencyType:"stateVariable",variableName:"uri"},page:{dependencyType:"stateVariable",variableName:"page"},targetInactive:{dependencyType:"stateVariable",variableName:"targetInactive"},targetAttribute:{dependencyType:"doenetAttribute",attributeName:"target"}}),definition:function({dependencyValues:e}){if(e.uri||e.page){if(e.targetAttribute){let t=e.targetAttribute;return"/"!==t[0]&&(t="/"+t),{setValue:{targetName:t}}}return{setValue:{targetName:""}}}return null===e.targetComponent||e.targetInactive?{setValue:{targetName:""}}:{setValue:{targetName:e.targetComponent.componentName}}}},e.cid={forRenderer:!0,additionalStateVariablesDefined:[{variableName:"doenetId",forRenderer:!0},{variableName:"variantIndex",forRenderer:!0},{variableName:"edit",forRenderer:!0},{variableName:"draft",forRenderer:!0},{variableName:"hash",forRenderer:!0}],returnDependencies:()=>({uri:{dependencyType:"stateVariable",variableName:"uri"}}),definition:function({dependencyValues:e}){if(!e.uri||"doenet:"!==e.uri.substring(0,7).toLowerCase())return{setValue:{cid:null,doenetId:null,variantIndex:null,edit:null,draft:null,hash:null}};let t=null,n=null,r=null,a=null,i=null,s=null,o=e.uri.match(/[:&]cid=([^&^#]+)/i);return o&&(t=o[1]),o=e.uri.match(/[:&]doenetid=([^&^#]+)/i),o&&(n=o[1]),o=e.uri.match(/[:&]variant=([^&^#]+)/i),o&&(r=Number(o[1]),!Number.isInteger(r)&&r>=1&&(r=1)),o=e.uri.match(/[:&]edit=([^&^#]+)/i),o&&(i="true"===o[1].toLowerCase()),o=e.uri.match(/[:&]draft=([^&^#]+)/i),o&&(a="true"===o[1].toLowerCase()),o=e.uri.match(/(#.+)/i),o&&(s=o[1]),{setValue:{cid:t,doenetId:n,variantIndex:r,edit:i,draft:a,hash:s}}}},e.linkText={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,stateVariablesDeterminingDependencies:["targetName"],returnDependencies({stateValues:e}){let t={allChildren:{dependencyType:"child",childGroups:["anything"],variableNames:["text"],variablesOptional:!0},uri:{dependencyType:"stateVariable",variableName:"uri"},targetInactive:{dependencyType:"stateVariable",variableName:"targetInactive"}};return e.targetName&&(t.equationTag={dependencyType:"stateVariable",componentName:e.targetName,variableName:"equationTag",variablesOptional:!0},t.title={dependencyType:"stateVariable",componentName:e.targetName,variableName:"title",variablesOptional:!0}),t},definition:function({dependencyValues:e}){let t="";if(0===e.allChildren.length)null!==e.uri?t=e.uri:e.targetInactive||(null!==e.title?t=e.title:null!==e.equationTag&&(t="("+e.equationTag+")"));else for(let n of e.allChildren)"object"!=typeof n?t+=n.toString():"string"==typeof n.stateValues.text&&(t+=n.stateValues.text);return t||(t="???"),{setValue:{linkText:t}}}},e}async navigateToTarget({actionId:e}){if(await this.stateValues.disabled)this.coreFunctions.resolveAction({actionId:e});else{let t=await this.stateValues.cid,n=await this.stateValues.doenetId,r=await this.stateValues.variantIndex,a=await this.stateValues.edit,i=await this.stateValues.hash,s=await this.stateValues.page,o=await this.stateValues.uri,l=await this.stateValues.targetName,u=this.componentOrAdaptedName;this.coreFunctions.navigateToTarget({cid:t,doenetId:n,variantIndex:r,edit:a,hash:i,page:s,uri:o,targetName:l,actionId:e,componentName:this.componentName,effectiveName:u})}}}class Coords extends MathComponent{static componentType="coords";static rendererType="math";static createAttributesObject(){let e=super.createAttributesObject();return delete e.createVectors,e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.createVectors={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({}),definition:()=>({setValue:{createVectors:!0}})},e}}class LineSegment extends GraphicalComponent{constructor(e){super(e),Object.assign(this.actions,{moveLineSegment:this.moveLineSegment.bind(this),lineSegmentClicked:this.lineSegmentClicked.bind(this),mouseDownOnLineSegment:this.mouseDownOnLineSegment.bind(this)})}static componentType="lineSegment";static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.endpointsDraggable={createComponentOfType:"boolean"},e.endpoints={createComponentOfType:"_pointListComponent"},e.showCoordsWhenDragging={createComponentOfType:"boolean",createStateVariable:"showCoordsWhenDragging",defaultValue:!0,public:!0,forRenderer:!0},e.labelPosition={createComponentOfType:"text",createStateVariable:"labelPosition",defaultValue:"upperright",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft"]},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){let t=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(t&&(t+=" "),t+=e.selectedStyle.lineStyleWord),t&&(t+=" "),t+=e.selectedStyle.lineColorWord,{setValue:{styleDescription:t}}}},e.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({styleDescription:{dependencyType:"stateVariable",variableName:"styleDescription"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescriptionWithNoun:e.styleDescription+" line segment"}}}},e.endpointsDraggable={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},hasEssential:!0,forRenderer:!0,returnDependencies:()=>({endpointsDraggableAttr:{dependencyType:"attributeComponent",attributeName:"endpointsDraggable",variableNames:["value"]},draggable:{dependencyType:"stateVariable",variableName:"draggable"}}),definition:({dependencyValues:e})=>e.endpointsDraggableAttr?{setValue:{endpointsDraggable:e.endpointsDraggableAttr.stateValues.value}}:{useEssentialOrDefaultValue:{endpointsDraggable:{defaultValue:e.draggable}}}},e.nDimensions={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({endpointsAttr:{dependencyType:"attributeComponent",attributeName:"endpoints",variableNames:["nDimensions"]}}),definition:function({dependencyValues:e}){if(null!==e.endpointsAttr){return{setValue:{nDimensions:e.endpointsAttr.stateValues.nDimensions},checkForActualChange:{nDimensions:!0}}}return{setValue:{nDimensions:2}}}},e.endpoints={public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"endpointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,nDimensions:2,entryPrefixes:["endpointX","endpoint"],hasEssential:!0,set:convertValueToMathExpression,defaultValueByArrayKey:e=>me$3.fromAst("0,0"===e?1:0),getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("endpointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("endpoints"===t)return 1===e.length?"endpoint"+e[0]:`endpointX${e[0]}_${e[1]}`;if("endpoint"===t.slice(0,8)){let n=Number(t.slice(8));if(Number.isInteger(n)&&n>0)return`endpointX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[2,e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let[e,r]=n.split(","),a=Number(e)+1+"_"+(Number(r)+1);t[n]={endpointsAttr:{dependencyType:"attributeComponent",attributeName:"endpoints",variableNames:["pointX"+a]}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t,arraySize:n}){let r={},a={};for(let n of t){let[t,i]=n.split(","),s=Number(t)+1+"_"+(Number(i)+1);null!==e[n].endpointsAttr&&e[n].endpointsAttr.stateValues["pointX"+s]?r[n]=e[n].endpointsAttr.stateValues["pointX"+s]:a[n]=!0}let i={};return Object.keys(r).length>0&&(i.setValue={endpoints:r}),Object.keys(a).length>0&&(i.useEssentialOrDefaultValue={endpoints:a}),i},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n,initialChange:r,stateValues:a}){let i=[];for(let r in e.endpoints){let[a,s]=r.split(","),o=Number(a)+1+"_"+(Number(s)+1);null!==t[r].endpointsAttr&&t[r].endpointsAttr.stateValues["pointX"+o]?i.push({setDependency:n[r].endpointsAttr,desiredValue:e.endpoints[r],childIndex:0,variableIndex:0}):i.push({setEssentialValue:"endpoints",value:{[r]:e.endpoints[r]}})}return{success:!0,instructions:i}}},e.length={public:!0,shadowingInstructions:{createComponentOfType:"math"},returnDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},endpoints:{dependencyType:"stateVariable",variableName:"endpoints"}}),definition({dependencyValues:e}){let t=0,n=e.endpoints[0],r=e.endpoints[1],a=!0;for(let i=0;ie+t*t),0));r=r.map((e=>e/o));let l=e.length.evaluate_to_constant();if(!Number.isFinite(l)||l<0)return{success:!1};let u=[],c=[],p=l/2;for(let e=0;e({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>Number.isNaN(e.nDimensions)?[0]:[2],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={endpoint:{dependencyType:"stateVariable",variableName:"endpoint"+(Number(n)+1)}};return{globalDependencies:{nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){if(Number.isNaN(e.nDimensions))return{};let r={};for(let a of n){let n=t[a].endpoint,i=[];for(let t=0;t({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},numericalEndpoints:{dependencyType:"stateVariable",variableName:"numericalEndpoints"}}),definition({dependencyValues:e}){let t=e.numericalEndpoints[0][0],n=e.numericalEndpoints[0][1],r=e.numericalEndpoints[1][0],a=e.numericalEndpoints[1][1],i=Number.isFinite(t)&&Number.isFinite(n)&&Number.isFinite(r)&&Number.isFinite(a),s=2!==e.nDimensions||!i||r===t&&a===n;return{setValue:{nearestPoint:function({variables:e,scales:i}){if(s)return{};let o=i[0],l=i[1],u=(r-t)/o,c=(a-n)/l,p=u*u+c*c,d=((e.x1-t)/o*u+(e.x2-n)/l*c)/p,m={};return m=d<=0?{x1:t,x2:n}:d>=1?{x1:r,x2:a}:{x1:t+d*u*o,x2:n+d*c*l},void 0!==e.x3&&(m.x3=0),m}}}}},e.slope={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({numericalEndpoints:{dependencyType:"stateVariable",variableName:"numericalEndpoints"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),definition({dependencyValues:e}){if(2!==e.nDimensions)return{setValue:{slope:NaN}};let t=e.numericalEndpoints;return{setValue:{slope:(t[1][1]-t[0][1])/(t[1][0]-t[0][0])}}}},e}async moveLineSegment({point1coords:e,point2coords:t,transient:n,actionId:r}){if(void 0===e||void 0===t){if(!await this.stateValues.endpointsDraggable)return await this.coreFunctions.resolveAction({actionId:r})}else if(!await this.stateValues.draggable)return await this.coreFunctions.resolveAction({actionId:r});let a={};return void 0!==e&&(a["0,0"]=me$3.fromAst(e[0]),a["0,1"]=me$3.fromAst(e[1])),void 0!==t&&(a["1,0"]=me$3.fromAst(t[0]),a["1,1"]=me$3.fromAst(t[1])),n?await this.coreFunctions.performUpdate({updateInstructions:[{componentName:this.componentName,updateType:"updateValue",stateVariable:"endpoints",value:a}],transient:!0,actionId:r}):await this.coreFunctions.performUpdate({updateInstructions:[{componentName:this.componentName,updateType:"updateValue",stateVariable:"endpoints",value:a}],actionId:r,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{point1:e,point2:t}}})}async lineSegmentClicked({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"click",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}async mouseDownOnLineSegment({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"down",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}}class Ray extends GraphicalComponent{constructor(e){super(e),Object.assign(this.actions,{moveRay:this.moveRay.bind(this),rayClicked:this.rayClicked.bind(this),mouseDownOnRay:this.mouseDownOnRay.bind(this)})}static componentType="ray";static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.endpoint={createComponentOfType:"point"},e.through={createComponentOfType:"point"},e.direction={createComponentOfType:"vector"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){let t=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(t&&(t+=" "),t+=e.selectedStyle.lineStyleWord),t&&(t+=" "),t+=e.selectedStyle.lineColorWord,{setValue:{styleDescription:t}}}},e.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({styleDescription:{dependencyType:"stateVariable",variableName:"styleDescription"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescriptionWithNoun:e.styleDescription+" ray"}}}},e.directionShadow={defaultValue:null,hasEssential:!0,essentialVarName:"direction",set:convertValueToMathExpression,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{directionShadow:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"directionShadow",value:convertValueToMathExpression(e.directionShadow)}]}}},e.throughShadow={defaultValue:null,hasEssential:!0,essentialVarName:"through",set:convertValueToMathExpression,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{throughShadow:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"throughShadow",value:convertValueToMathExpression(e.throughShadow)}]}}},e.endpointShadow={defaultValue:null,hasEssential:!0,essentialVarName:"endpoint",set:convertValueToMathExpression,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{endpointShadow:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"endpointShadow",value:convertValueToMathExpression(e.endpointShadow)}]}}},e.basedOnThrough={returnDependencies:()=>({throughAttr:{dependencyType:"attributeComponent",attributeName:"through"},throughShadow:{dependencyType:"stateVariable",variableName:"throughShadow"},endpointAttr:{dependencyType:"attributeComponent",attributeName:"endpoint"},directionAttr:{dependencyType:"attributeComponent",attributeName:"direction"}}),definition:function({dependencyValues:e}){return null!==e.endpointAttr&&null!==e.directionAttr?(null!==e.throughAttr&&console.warn("Ray is prescribed by through, endpoint, and direction. Ignoring specified through."),{setValue:{basedOnThrough:!1},checkForActualChange:{basedOnThrough:!0}}):null!==e.throughAttr?{setValue:{basedOnThrough:!0},checkForActualChange:{basedOnThrough:!0}}:{setValue:{basedOnThrough:null!==e.throughShadow},checkForActualChange:{basedOnThrough:!0}}}},e.basedOnEndpoint={returnDependencies:()=>({endpointAttr:{dependencyType:"attributeComponent",attributeName:"endpoint"},endpointShadow:{dependencyType:"stateVariable",variableName:"endpointShadow"}}),definition:function({dependencyValues:e}){return null!==e.endpointAttr?{setValue:{basedOnEndpoint:!0},checkForActualChange:{basedOnEndpoint:!0}}:{setValue:{basedOnEndpoint:null!==e.endpointShadow},checkForActualChange:{basedOnEndpoint:!0}}}},e.basedOnDirection={returnDependencies:()=>({directionAttr:{dependencyType:"attributeComponent",attributeName:"direction"},directionShadow:{dependencyType:"stateVariable",variableName:"directionShadow"}}),definition:function({dependencyValues:e}){return null!==e.directionAttr?{setValue:{basedOnDirection:!0},checkForActualChange:{basedOnDirection:!0}}:{setValue:{basedOnDirection:null!==e.directionShadow},checkForActualChange:{basedOnDirection:!0}}}},e.nDimDirection={stateVariablesDeterminingDependencies:["basedOnDirection","basedOnThrough","basedOnEndpoint"],returnDependencies({stateValues:e}){let t={basedOnThrough:{dependencyType:"stateVariable",variableName:"basedOnThrough"},basedOnEndpoint:{dependencyType:"stateVariable",variableName:"basedOnEndpoint"},basedOnDirection:{dependencyType:"stateVariable",variableName:"basedOnDirection"},directionShadow:{dependencyType:"stateVariable",variableName:"directionShadow"},directionAttr:{dependencyType:"attributeComponent",attributeName:"direction",variableNames:["nDimensions"]}};return e.basedOnDirection||(e.basedOnThrough&&(t.nDimThrough={dependencyType:"stateVariable",variableName:"nDimThrough"}),e.basedOnEndpoint&&(t.nDimEndpoint={dependencyType:"stateVariable",variableName:"nDimEndpoint"})),t},definition:function({dependencyValues:e}){let t;if(e.basedOnDirection){if(null!==e.directionAttr)t=e.directionAttr.stateValues.nDimensions;else if(e.directionShadow){let n=e.directionShadow.tree;t=Array.isArray(n)&&vectorOperators.includes(n[0])?n.length-1:2}}else t=e.basedOnThrough?e.basedOnEndpoint?e.nDimThrough===e.nDimEndpoint?e.nDimThrough:NaN:e.nDimThrough:e.basedOnEndpoint?e.nDimEndpoint:2;return{setValue:{nDimDirection:t},checkForActualChange:{nDimDirection:!0}}}},e.nDimThrough={stateVariablesDeterminingDependencies:["basedOnDirection","basedOnThrough","basedOnEndpoint"],returnDependencies({stateValues:e}){let t={basedOnThrough:{dependencyType:"stateVariable",variableName:"basedOnThrough"},basedOnEndpoint:{dependencyType:"stateVariable",variableName:"basedOnEndpoint"},basedOnDirection:{dependencyType:"stateVariable",variableName:"basedOnDirection"},throughShadow:{dependencyType:"stateVariable",variableName:"throughShadow"},throughAttr:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["nDimensions"]}};return e.basedOnThrough||(e.basedOnEndpoint&&(t.nDimEndpoint={dependencyType:"stateVariable",variableName:"nDimEndpoint"}),e.basedOnDirection&&(t.nDimDirection={dependencyType:"stateVariable",variableName:"nDimDirection"})),t},definition:function({dependencyValues:e}){let t;if(e.basedOnThrough){if(null!==e.throughAttr)t=e.throughAttr.stateValues.nDimensions;else if(e.throughShadow){let n=e.throughShadow.tree;t=Array.isArray(n)&&vectorOperators.includes(n[0])?n.length-1:2}}else t=e.basedOnDirection?e.basedOnEndpoint?e.nDimDirection===e.nDimEndpoint?e.nDimDirection:NaN:e.nDimDirection:e.basedOnEndpoint?e.nDimEndpoint:2;return{setValue:{nDimThrough:t},checkForActualChange:{nDimThrough:!0}}}},e.nDimEndpoint={stateVariablesDeterminingDependencies:["basedOnDirection","basedOnThrough","basedOnEndpoint"],returnDependencies({stateValues:e}){let t={basedOnThrough:{dependencyType:"stateVariable",variableName:"basedOnThrough"},basedOnEndpoint:{dependencyType:"stateVariable",variableName:"basedOnEndpoint"},basedOnDirection:{dependencyType:"stateVariable",variableName:"basedOnDirection"},endpointShadow:{dependencyType:"stateVariable",variableName:"endpointShadow"},endpointAttr:{dependencyType:"attributeComponent",attributeName:"endpoint",variableNames:["nDimensions"]}};return e.basedOnEndpoint||(e.basedOnThrough&&(t.nDimThrough={dependencyType:"stateVariable",variableName:"nDimThrough"}),e.basedOnDirection&&(t.nDimDirection={dependencyType:"stateVariable",variableName:"nDimDirection"})),t},definition:function({dependencyValues:e}){let t;if(e.basedOnEndpoint){if(null!==e.endpointAttr)t=e.endpointAttr.stateValues.nDimensions;else if(e.endpointShadow){let n=e.endpointShadow.tree;t=Array.isArray(n)&&vectorOperators.includes(n[0])?n.length-1:2}}else t=e.basedOnDirection?e.basedOnThrough?e.nDimDirection===e.nDimThrough?e.nDimDirection:NaN:e.nDimDirection:e.basedOnThrough?e.nDimThrough:2;return{setValue:{nDimEndpoint:t},checkForActualChange:{nDimEndpoint:!0}}}},e.nDimensions={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({basedOnThrough:{dependencyType:"stateVariable",variableName:"basedOnThrough"},basedOnEndpoint:{dependencyType:"stateVariable",variableName:"basedOnEndpoint"},basedOnDirection:{dependencyType:"stateVariable",variableName:"basedOnDirection"},nDimDirection:{dependencyType:"stateVariable",variableName:"nDimDirection"},nDimThrough:{dependencyType:"stateVariable",variableName:"nDimThrough"},nDimEndpoint:{dependencyType:"stateVariable",variableName:"nDimEndpoint"}}),definition:function({dependencyValues:e}){let t;if(e.basedOnDirection){if(e.basedOnEndpoint){if(e.nDimDirection!==e.nDimEndpoint)return console.warn("nDimensions mismatch in vector"),{setValue:{nDimensions:NaN}}}else if(e.basedOnThrough&&e.nDimDirection!==e.nDimThrough)return console.warn("nDimensions mismatch in vector"),{setValue:{nDimensions:NaN}};t=e.nDimDirection}else if(e.basedOnEndpoint){if(e.basedOnThrough&&e.nDimEndpoint!==e.nDimThrough)return console.warn("nDimensions mismatch in vector"),{setValue:{nDimensions:NaN}};t=e.nDimEndpoint}else t=e.basedOnThrough?e.nDimThrough:2;return{setValue:{nDimensions:t},checkForActualChange:{nDimensions:!0}}}},e.direction={public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"directionX"===e?[]:[["vector",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,entryPrefixes:["directionX"],hasEssential:!0,essentialVarName:"direction2",set:convertValueToMathExpression,stateVariablesDeterminingDependencies:["basedOnDirection","basedOnThrough"],returnArraySizeDependencies:()=>({nDimDirection:{dependencyType:"stateVariable",variableName:"nDimDirection"}}),returnArraySize:({dependencyValues:e})=>[e.nDimDirection],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=Number(r)+1;n[r]={directionAttr:{dependencyType:"attributeComponent",attributeName:"direction",variableNames:["x"+e]}},!t.basedOnDirection&&t.basedOnThrough&&(n[r].endpointX={dependencyType:"stateVariable",variableName:"endpointX"+e},n[r].throughX={dependencyType:"stateVariable",variableName:"throughX"+e})}return{globalDependencies:{basedOnThrough:{dependencyType:"stateVariable",variableName:"basedOnThrough"},basedOnEndpoint:{dependencyType:"stateVariable",variableName:"basedOnEndpoint"},basedOnDirection:{dependencyType:"stateVariable",variableName:"basedOnDirection"},directionShadow:{dependencyType:"stateVariable",variableName:"directionShadow"}},dependenciesByKey:n}},arrayDefinitionByKey:function({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={},a={};for(let i of n){let n=Number(i)+1;e.basedOnDirection?null!==t[i].directionAttr?r[i]=t[i].directionAttr.stateValues["x"+n]:null!==e.directionShadow&&(r[i]=e.directionShadow.get_component(Number(i))):e.basedOnThrough?r[i]=t[i].throughX.subtract(t[i].endpointX).simplify():a[i]={defaultValue:me$3.fromAst("0"===i?1:0)}}let i={};return Object.keys(r).length>0&&(i.setValue={direction:r}),Object.keys(a).length>0&&(i.useEssentialOrDefaultValue={direction:a}),i},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i=[],s=!1;for(let a in e.direction)t.basedOnDirection?null!==n[a].directionAttr?i.push({setDependency:r[a].directionAttr,desiredValue:e.direction[a],variableIndex:0}):s=!0:t.basedOnThrough?i.push({setDependency:r[a].throughX,desiredValue:n[a].endpointX.add(e.direction[a]).simplify()}):i.push({setEssentialValue:"direction",value:{[a]:convertValueToMathExpression(e.direction[a])}});if(s)if(a[0]>1){let t=["vector"];for(let n in e.direction)t[Number(n)+1]=e.direction[n].tree;t.length=a[0]+1,i.push({setDependency:"directionShadow",desiredValue:me$3.fromAst(t)})}else 1===a[0]&&"0"in e.direction&&i.push({setDependency:"directionShadow",desiredValue:e.direction[0]});return{success:!0,instructions:i}}},e.through={public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"throughX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,entryPrefixes:["throughX"],set:convertValueToMathExpression,stateVariablesDeterminingDependencies:["basedOnThrough"],returnArraySizeDependencies:()=>({nDimThrough:{dependencyType:"stateVariable",variableName:"nDimThrough"}}),returnArraySize:({dependencyValues:e})=>[e.nDimThrough],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=Number(r)+1;n[r]={throughAttr:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["x"+e]}},t.basedOnThrough||(n[r].endpointX={dependencyType:"stateVariable",variableName:"endpointX"+e},n[r].directionX={dependencyType:"stateVariable",variableName:"directionX"+e})}return{globalDependencies:{basedOnDirection:{dependencyType:"stateVariable",variableName:"basedOnDirection"},basedOnEndpoint:{dependencyType:"stateVariable",variableName:"basedOnEndpoint"},basedOnThrough:{dependencyType:"stateVariable",variableName:"basedOnThrough"},throughShadow:{dependencyType:"stateVariable",variableName:"throughShadow"}},dependenciesByKey:n}},arrayDefinitionByKey:function({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};for(let a of n){let n=Number(a)+1;e.basedOnThrough?null!==t[a].throughAttr?r[a]=t[a].throughAttr.stateValues["x"+n]:null!==e.throughShadow&&(r[a]=e.throughShadow.get_component(Number(a))):r[a]=t[a].endpointX.add(t[a].directionX).simplify()}return{setValue:{through:r}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i=[],s=!1;for(let a in e.through)t.basedOnThrough?n[a].throughAttr&&null!==n[a].throughAttr?i.push({setDependency:r[a].throughAttr,desiredValue:e.through[a],variableIndex:0}):null!==t.throughShadow&&(s=!0):i.push({setDependency:r[a].directionX,desiredValue:e.through[a].subtract(n[a].endpointX).simplify()});if(s)if(a[0]>1){let t=["vector"];for(let n in e.through)t[Number(n)+1]=e.through[n].tree;t.length=a[0]+1,i.push({setDependency:"throughShadow",desiredValue:me$3.fromAst(t)})}else 1===a[0]&&"0"in e.through&&i.push({setDependency:"throughShadow",desiredValue:e.through[0]});return{success:!0,instructions:i}}},e.endpoint={public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"endpointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,entryPrefixes:["endpointX"],hasEssential:!0,defaultValueByArrayKey:()=>me$3.fromAst(0),essentialVarName:"endpoint2",set:convertValueToMathExpression,stateVariablesDeterminingDependencies:["basedOnEndpoint","basedOnThrough","basedOnDirection"],returnArraySizeDependencies:()=>({nDimEndpoint:{dependencyType:"stateVariable",variableName:"nDimEndpoint"}}),returnArraySize:({dependencyValues:e})=>[e.nDimEndpoint],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=Number(r)+1;n[r]={endpointAttr:{dependencyType:"attributeComponent",attributeName:"endpoint",variableNames:["x"+e]}},t.basedOnEndpoint||t.basedOnThrough&&t.basedOnDirection&&(n[r].throughX={dependencyType:"stateVariable",variableName:"throughX"+e},n[r].directionX={dependencyType:"stateVariable",variableName:"directionX"+e})}return{globalDependencies:{basedOnDirection:{dependencyType:"stateVariable",variableName:"basedOnDirection"},basedOnThrough:{dependencyType:"stateVariable",variableName:"basedOnThrough"},endpointShadow:{dependencyType:"stateVariable",variableName:"endpointShadow"}},dependenciesByKey:n}},arrayDefinitionByKey:function({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={},a={};for(let i of n){let n=Number(i)+1;null!==t[i].endpointAttr?r[i]=t[i].endpointAttr.stateValues["x"+n]:null!==e.endpointShadow?r[i]=e.endpointShadow.get_component(Number(i)):e.basedOnThrough&&e.basedOnDirection?r[i]=t[i].throughX.subtract(t[i].directionX).simplify():a[i]=!0}let i={};return Object.keys(r).length>0&&(i.setValue={endpoint:r}),Object.keys(a).length>0&&(i.useEssentialOrDefaultValue={endpoint:a}),i},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i=[],s=!1;for(let a in e.endpoint)n[a].endpointAttr&&null!==n[a].endpointAttr?i.push({setDependency:r[a].endpointAttr,desiredValue:e.endpoint[a],variableIndex:0}):null!==t.endpointShadow?s=!0:t.basedOnThrough&&t.basedOnDirection?i.push({setDependency:r[a].directionX,desiredValue:n[a].throughX.subtract(e.endpoint[a]).simplify()}):i.push({setEssentialValue:"endpoint",value:{[a]:convertValueToMathExpression(e.endpoint[a])}});if(s)if(a[0]>1){let t=["vector"];for(let n in e.endpoint)t[Number(n)+1]=e.endpoint[n].tree;t.length=a[0]+1,i.push({setDependency:"endpointShadow",desiredValue:me$3.fromAst(t)})}else 1===a[0]&&"0"in e.endpoint&&i.push({setDependency:"endpointShadow",desiredValue:e.endpoint[0]});return{success:!0,instructions:i}}},e.numericalEndpoint={forRenderer:!0,returnDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},endpoint:{dependencyType:"stateVariable",variableName:"endpoint"}}),definition({dependencyValues:e}){if(Number.isNaN(e.nDimensions))return null;let t=e.endpoint,n=[];for(let r=0;r({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},through:{dependencyType:"stateVariable",variableName:"through"}}),definition({dependencyValues:e}){if(Number.isNaN(e.nDimensions))return null;let t=e.through,n=[];for(let r=0;r({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},numericalEndpoint:{dependencyType:"stateVariable",variableName:"numericalEndpoint"},numericalThroughpoint:{dependencyType:"stateVariable",variableName:"numericalThroughpoint"}}),definition({dependencyValues:e}){let t=e.numericalEndpoint[0],n=e.numericalEndpoint[1],r=e.numericalThroughpoint[0],a=e.numericalThroughpoint[1],i=Number.isFinite(t)&&Number.isFinite(n)&&Number.isFinite(r)&&Number.isFinite(a),s=2!==e.nDimensions||!i||r===t&&a===n;return{setValue:{nearestPoint:function({variables:e,scales:i}){if(s)return{};let o=i[0],l=i[1],u=(r-t)/o,c=(a-n)/l,p=u*u+c*c,d=((e.x1-t)/o*u+(e.x2-n)/l*c)/p,m={};return m=d<=0?{x1:t,x2:n}:{x1:t+d*u*o,x2:n+d*c*l},void 0!==e.x3&&(m.x3=0),m}}}}},e}async moveRay({endpointcoords:e,throughcoords:t,transient:n,skippable:r,sourceInformation:a,actionId:i}){let s=[];if(void 0!==e){if(await this.stateValues.basedOnThrough&&await this.stateValues.basedOnDirection){let n;if(void 0===t){let t=await this.stateValues.numericalThroughpoint;n=e.map(((e,n)=>t[n]-e))}else n=e.map(((e,n)=>t[n]-e));s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"direction",value:n.map((e=>me$3.fromAst(e))),sourceInformation:a})}else s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"endpoint",value:e.map((e=>me$3.fromAst(e))),sourceInformation:a});if(void 0===t&&!await this.stateValues.basedOnThrough){let t=await this.stateValues.numericalThroughpoint,n=e.map(((e,n)=>t[n]-e));s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"direction",value:n.map((e=>me$3.fromAst(e))),sourceInformation:a})}}if(void 0!==t){if(await this.stateValues.basedOnThrough)s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"through",value:t.map((e=>me$3.fromAst(e))),sourceInformation:a});else{null==e&&(e=await this.stateValues.numericalEndpoint);let n=e.map(((e,n)=>t[n]-e));s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"direction",value:n.map((e=>me$3.fromAst(e))),sourceInformation:a})}if(void 0===e&&await this.stateValues.basedOnThrough&&await this.stateValues.basedOnDirection){let e=await this.stateValues.numericalEndpoint,n=t.map(((t,n)=>t-e[n]));s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"direction",value:n.map((e=>me$3.fromAst(e))),sourceInformation:a})}}return n?await this.coreFunctions.performUpdate({updateInstructions:s,transient:n,skippable:r,actionId:i}):await this.coreFunctions.performUpdate({updateInstructions:s,actionId:i,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{through:t,endpoint:e}}})}async rayClicked({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"click",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}async mouseDownOnRay({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"down",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}}class Polygon extends Polyline{constructor(e){super(e),Object.assign(this.actions,{movePolygon:this.movePolygon.bind(this),polygonClicked:this.polygonClicked.bind(this),mouseDownOnPolygon:this.mouseDownOnPolygon.bind(this)})}static componentType="polygon";static representsClosedPath=!0;get movePolygon(){return this.movePolyline}get polygonClicked(){return this.polylineClicked}get mouseDownOnPolygon(){return this.mouseDownOnPolyline}static createAttributesObject(){let e=super.createAttributesObject();return e.filled={createComponentOfType:"boolean",createStateVariable:"filled",defaultValue:!1,public:!0,forRenderer:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"},filled:{dependencyType:"stateVariable",variableName:"filled"}}),definition:function({dependencyValues:e}){let t,n=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(n&&(n+=" "),n+=e.selectedStyle.lineStyleWord),n&&(n+=" "),e.filled?e.selectedStyle.fillColorWord===e.selectedStyle.lineColorWord?(t="filled "+e.selectedStyle.fillColorWord,n&&(t+=" with "+n+"border")):t="filled "+e.selectedStyle.fillColorWord+" with "+n+e.selectedStyle.lineColorWord+" border":t=n+e.selectedStyle.lineColorWord,{setValue:{styleDescription:t}}}},e.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"},filled:{dependencyType:"stateVariable",variableName:"filled"}}),definition:function({dependencyValues:e}){let t,n=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(n&&(n+=" "),n+=e.selectedStyle.lineStyleWord),n&&(n+=" "),e.filled?e.selectedStyle.fillColorWord===e.selectedStyle.lineColorWord?(t="filled "+e.selectedStyle.fillColorWord+" polygon",n&&(t+=" with a "+n+"border")):t="filled "+e.selectedStyle.fillColorWord+" polygon with a "+n+e.selectedStyle.lineColorWord+" border":t=n+e.selectedStyle.lineColorWord+" polygon",{setValue:{styleDescriptionWithNoun:t}}}},e.borderStyleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){let t=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(t&&(t+=" "),t+=e.selectedStyle.lineStyleWord),t&&(t+=" "),t+=e.selectedStyle.lineColorWord,{setValue:{borderStyleDescription:t}}}},e.fillStyleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"},filled:{dependencyType:"stateVariable",variableName:"filled"}}),definition:function({dependencyValues:e}){let t;return t=e.filled?e.selectedStyle.fillColorWord:"unfilled",{setValue:{fillStyleDescription:t}}}},e.nearestPoint={returnDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},numericalVertices:{dependencyType:"stateVariable",variableName:"numericalVertices"},nVertices:{dependencyType:"stateVariable",variableName:"nVertices"}}),definition({dependencyValues:e}){let t,n,r=e.nDimensions,a=e.nVertices,i=e.numericalVertices,s=[],o=i[a-1]?.[0],l=i[a-1]?.[1];for(let e=0;e=1?{x1:h,x2:f}:{x1:l+g*a*n,x2:u+g*y*o};let b=Math.pow((d-r.x1)/n,2)+Math.pow((m-r.x2)/o,2);b0&&(p.x3=0),p}}}}},e}}class Triangle extends Polygon{static componentType="triangle";static rendererType="polygon";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=e.styleDescriptionWithNoun.definition;return e.styleDescriptionWithNoun.definition=function({dependencyValues:e}){let n=t({dependencyValues:e}).setValue.styleDescriptionWithNoun;return n=n.replaceAll("polygon","triangle"),{setValue:{styleDescriptionWithNoun:n}}},e.vertices.hasEssential=!0,e.vertices.defaultValueByArrayKey=function(e){return["0,1","1,0"].includes(e)?me$3.fromAst(1):me$3.fromAst(0)},e.vertices.returnArraySizeDependencies=()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),e.vertices.returnArraySize=function({dependencyValues:e}){return[3,e.nDimensions]},e.vertices.arrayDefinitionByKey=function({dependencyValuesByKey:e,arrayKeys:t}){let n={},r={};for(let a of t){let[t,i]=a.split(","),s=Number(t)+1+"_"+(Number(i)+1),o=e[a].vertices;null!==o&&o.stateValues["pointX"+s]?n[a]=o.stateValues["pointX"+s]:r[a]=!0}return{setValue:{vertices:n},useEssentialOrDefaultValue:{vertices:r}}},e.vertices.inverseArrayDefinitionByKey=async function({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n,initialChange:r,stateValues:a}){if(r&&!await a.draggable)return{success:!1};let i=[];for(let r in e.vertices){let[a,s]=r.split(","),o=Number(a)+1+"_"+(Number(s)+1);null!==t[r].vertices&&t[r].vertices.stateValues["pointX"+o]?i.push({setDependency:n[r].vertices,desiredValue:e.vertices[r],variableIndex:0}):i.push({setEssentialValue:"vertices",value:{[r]:e.vertices[r].simplify()}})}return{success:!0,instructions:i}},e.nVertices={public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{nVertices:3}})},e}}class Rectangle extends Polygon{static componentType="rectangle";static rendererType="polygon";static createAttributesObject(){let e=super.createAttributesObject();return e.center={createComponentOfType:"point"},e.width={createComponentOfType:"number"},e.height={createComponentOfType:"number"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=e.styleDescriptionWithNoun.definition;return e.styleDescriptionWithNoun.definition=function({dependencyValues:e}){let n=t({dependencyValues:e}).setValue.styleDescriptionWithNoun;return n=n.replaceAll("polygon","rectangle"),{setValue:{styleDescriptionWithNoun:n}}},e.nVerticesSpecified={returnDependencies:()=>({verticesAttr:{dependencyType:"attributeComponent",attributeName:"vertices",variableNames:["nPoints"]}}),definition:function({dependencyValues:e}){return null!==e.verticesAttr?{setValue:{nVerticesSpecified:e.verticesAttr.stateValues.nPoints}}:{setValue:{nVerticesSpecified:0}}}},e.essentialVertex={isArray:!0,entryPrefixes:["essentialVertexX"],defaultValueByArrayKey:()=>me$3.fromAst(0),hasEssential:!0,returnArraySizeDependencies:()=>({nVerticesSpecified:{dependencyType:"stateVariable",variableName:"nVerticesSpecified"}}),returnArraySize:({dependencyValues:e})=>[0===e.nVerticesSpecified?2:0],returnArrayDependenciesByKey:()=>({}),arrayDefinitionByKey:function({arrayKeys:e}){let t={};for(let n of e)t[n]=!0;return{useEssentialOrDefaultValue:{essentialVertex:t}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e}){let t=[];for(let n in e.essentialVertex)t.push({setEssentialValue:"essentialVertex",value:{[n]:e.essentialVertex[n]}});return{success:!0,instructions:t}}},e.haveSpecifiedCenter={returnDependencies:()=>({centerAttr:{dependencyType:"attributeComponent",attributeName:"center"}}),definition:({dependencyValues:e})=>({setValue:{haveSpecifiedCenter:null!==e.centerAttr}})},e.specifiedCenter={isArray:!0,entryPrefixes:["specifiedCenterX"],returnArraySizeDependencies:()=>({haveSpecifiedCenter:{dependencyType:"stateVariable",variableName:"haveSpecifiedCenter"}}),returnArraySize:({dependencyValues:e})=>[e.haveSpecifiedCenter?2:0],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={centerAttr:{dependencyType:"attributeComponent",attributeName:"center",variableNames:["x"+e]}}}return{dependenciesByKey:t}},arrayDefinitionByKey:function({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=Number(r)+1;null!==e[r].centerAttr&&(n[r]=e[r].centerAttr.stateValues["x"+t])}return{setValue:{specifiedCenter:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n}){let r=[];for(let a in e.specifiedCenter)t[a].centerAttr&&null!==t[a].centerAttr&&r.push({setDependency:n[a].centerAttr,desiredValue:e.specifiedCenter[a],variableIndex:0});return{success:!0,instructions:r}}},e.specifiedWidth={defaultValue:1,hasEssential:!0,essentialVarName:"width",returnDependencies:()=>({widthAttr:{dependencyType:"attributeComponent",attributeName:"width",variableNames:["value"]},nVerticesSpecified:{dependencyType:"stateVariable",variableName:"nVerticesSpecified"},haveSpecifiedCenter:{dependencyType:"stateVariable",variableName:"haveSpecifiedCenter"}}),definition:({dependencyValues:e})=>null!==e.widthAttr?{setValue:{specifiedWidth:e.widthAttr.stateValues.value}}:(e.haveSpecifiedCenter?1:0)+e.nVerticesSpecified<=1?{useEssentialOrDefaultValue:{specifiedWidth:!0}}:{setValue:{specifiedWidth:null}},inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t})=>null!==t.widthAttr?{success:!0,instructions:[{setDependency:"widthAttr",desiredValue:e.specifiedWidth,childIndex:0,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"specifiedWidth",value:e.specifiedWidth}]}},e.specifiedHeight={defaultValue:1,hasEssential:!0,essentialVarName:"height",returnDependencies:()=>({heightAttr:{dependencyType:"attributeComponent",attributeName:"height",variableNames:["value"]},nVerticesSpecified:{dependencyType:"stateVariable",variableName:"nVerticesSpecified"},haveSpecifiedCenter:{dependencyType:"stateVariable",variableName:"haveSpecifiedCenter"}}),definition:({dependencyValues:e})=>null!==e.heightAttr?{setValue:{specifiedHeight:e.heightAttr.stateValues.value}}:(e.haveSpecifiedCenter?1:0)+e.nVerticesSpecified<=1?{useEssentialOrDefaultValue:{specifiedHeight:!0}}:{setValue:{specifiedHeight:null}},inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t})=>null!==t.heightAttr?{success:!0,instructions:[{setDependency:"heightAttr",desiredValue:e.specifiedHeight,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"specifiedHeight",value:e.specifiedHeight}]}},e.center={public:!0,isArray:!0,entryPrefixes:["centerX"],shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"centerX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},returnArraySizeDependencies:()=>({}),returnArraySize:()=>[2],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={vertex0:{dependencyType:"stateVariable",variableName:"vertexX1_"+e},vertex2:{dependencyType:"stateVariable",variableName:"vertexX3_"+e}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].vertex0,a=e[r].vertex2;n[r]=t.add(a).divide(2).simplify()}return{setValue:{center:n}}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n,stateValues:r}){let a=[],i=await r.center;for(let r in e.center){let s=Number(r),o=t[r].vertex0,l=t[r].vertex2,u=e.center[s].subtract(i[s]),c=o.add(u).simplify(),p=l.add(u).simplify();a.push({setDependency:n[r].vertex0,desiredValue:c},{setDependency:n[r].vertex2,desiredValue:p})}return{success:!0,instructions:a}}},e.width={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:({})=>({vertex0:{dependencyType:"stateVariable",variableName:"vertexX1_1"},vertex2:{dependencyType:"stateVariable",variableName:"vertexX3_1"}}),definition({dependencyValues:e}){let t=e.vertex0.evaluate_to_constant(),n=e.vertex2.evaluate_to_constant();return{setValue:{width:Math.abs(t-n)}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){let n=t.vertex0.evaluate_to_constant(),r=t.vertex2.evaluate_to_constant(),a=(r+n)/2,i=(r-n<0?-1:1)*Math.max(0,e.width)/2;return{success:!0,instructions:[{setDependency:"vertex0",desiredValue:me$3.fromAst(a-i)},{setDependency:"vertex2",desiredValue:me$3.fromAst(a+i)}]}}},e.height={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:({})=>({vertex0:{dependencyType:"stateVariable",variableName:"vertexX1_2"},vertex2:{dependencyType:"stateVariable",variableName:"vertexX3_2"}}),definition({dependencyValues:e}){let t=e.vertex0.evaluate_to_constant(),n=e.vertex2.evaluate_to_constant();return{setValue:{height:Math.abs(t-n)}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){let n=t.vertex0.evaluate_to_constant(),r=t.vertex2.evaluate_to_constant(),a=(r+n)/2,i=(r-n<0?-1:1)*Math.max(0,e.height)/2;return{success:!0,instructions:[{setDependency:"vertex0",desiredValue:me$3.fromAst(a-i)},{setDependency:"vertex2",desiredValue:me$3.fromAst(a+i)}]}}},e.vertices={public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"vertexX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,nDimensions:2,entryPrefixes:["vertexX","vertex"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("vertexX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("vertices"===t)return 1===e.length?"vertex"+e[0]:`vertexX${e[0]}_${e[1]}`;if("vertex"===t.slice(0,6)){let n=Number(t.slice(6));if(Number.isInteger(n)&&n>0)return`vertexX${n}_${e[0]}`}return null},stateVariablesDeterminingDependencies:["nVerticesSpecified","haveSpecifiedCenter"],returnArraySizeDependencies:()=>({}),returnArraySize:()=>[4,2],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={},r={nVerticesSpecified:{dependencyType:"stateVariable",variableName:"nVerticesSpecified"}};if(0===t.nVerticesSpecified)if(r.haveSpecifiedCenter={dependencyType:"stateVariable",variableName:"haveSpecifiedCenter"},t.haveSpecifiedCenter)for(let t of e){let[e,r]=t.split(",");n[t]={specifiedCenter:{dependencyType:"stateVariable",variableName:"specifiedCenterX"+(Number(r)+1)}},"0"===r?n[t].specifiedWidth={dependencyType:"stateVariable",variableName:"specifiedWidth"}:n[t].specifiedHeight={dependencyType:"stateVariable",variableName:"specifiedHeight"}}else for(let t of e){let[e,r]=t.split(",");n[t]={essentialVertex:{dependencyType:"stateVariable",variableName:"essentialVertexX"+(Number(r)+1)}},"0"===r?"1"!==e&&"2"!==e||(n[t].specifiedWidth={dependencyType:"stateVariable",variableName:"specifiedWidth"}):"2"!==e&&"3"!==e||(n[t].specifiedHeight={dependencyType:"stateVariable",variableName:"specifiedHeight"})}else if(1===t.nVerticesSpecified)if(r.haveSpecifiedCenter={dependencyType:"stateVariable",variableName:"haveSpecifiedCenter"},t.haveSpecifiedCenter)for(let t of e){let[e,r]=t.split(","),a="1_"+(Number(r)+1);n[t]={verticesAttr:{dependencyType:"attributeComponent",attributeName:"vertices",variableNames:["pointX"+a]}},("0"===r&&"1"===e||"2"===e||"1"===r&&"2"===e||"3"===e)&&(n[t].specifiedCenter={dependencyType:"stateVariable",variableName:"specifiedCenterX"+(Number(r)+1)})}else for(let t of e){let[e,r]=t.split(","),a="1_"+(Number(r)+1);n[t]={verticesAttr:{dependencyType:"attributeComponent",attributeName:"vertices",variableNames:["pointX"+a]}},"0"===r?"1"!==e&&"2"!==e||(n[t].specifiedWidth={dependencyType:"stateVariable",variableName:"specifiedWidth"}):"2"!==e&&"3"!==e||(n[t].specifiedHeight={dependencyType:"stateVariable",variableName:"specifiedHeight"})}else for(let t of e){let e,[r,a]=t.split(","),i="1_"+(Number(a)+1),s="2_"+(Number(a)+1);e="0"===r?i:"2"===r?s:"1"===r?"0"===a?s:i:"0"===a?i:s,n[t]={verticesAttr:{dependencyType:"attributeComponent",attributeName:"vertices",variableNames:["pointX"+e]}}}return{dependenciesByKey:n,globalDependencies:r}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t,globalDependencyValues:n}){let r={};if(0===n.nVerticesSpecified)if(n.haveSpecifiedCenter)for(let n of t){let[t,a]=n.split(","),i=e[n].specifiedCenter;if("0"===a){let a=e[n].specifiedWidth;r[n]="0"===t||"3"===t?i.subtract(a/2):i.add(a/2)}else{let a=e[n].specifiedHeight;r[n]="0"===t||"1"===t?i.subtract(a/2):i.add(a/2)}}else for(let n of t){let[t,a]=n.split(","),i=e[n].essentialVertex;if("0"===a)if("0"===t||"3"===t)r[n]=i;else{let t=e[n].specifiedWidth;r[n]=i.add(t)}else if("0"===t||"1"===t)r[n]=i;else{let t=e[n].specifiedHeight;r[n]=i.add(t)}}else if(1===n.nVerticesSpecified)if(n.haveSpecifiedCenter)for(let n of t){let t,[a,i]=n.split(","),s=e[n].verticesAttr;if(t=null!==s&&1===Object.keys(s.stateValues).length?Object.values(s.stateValues)[0]:me$3.fromAst("_"),"0"===i&&("0"===a||"3"===a)||"1"===i&&("0"===a||"1"===a))r[n]=t;else{let a=e[n].specifiedCenter;r[n]=t.add(a.subtract(t).multiply(2))}}else for(let n of t){let t,[a,i]=n.split(","),s=e[n].verticesAttr;if(t=null!==s&&1===Object.keys(s.stateValues).length?Object.values(s.stateValues)[0]:me$3.fromAst("_"),"0"===i)if("0"===a||"3"===a)r[n]=t;else{let a=e[n].specifiedWidth;r[n]=t.add(a)}else if("0"===a||"1"===a)r[n]=t;else{let a=e[n].specifiedHeight;r[n]=t.add(a)}}else for(let n of t){let t=e[n].verticesAttr;null!==t&&1===Object.keys(t.stateValues).length?r[n]=Object.values(t.stateValues)[0]:r[n]=me$3.fromAst("_")}return{setValue:{vertices:r}}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,globalDependencyValues:n,stateValues:r,workspace:a,initialChange:i,dependencyNamesByKey:s}){if(i&&!await r.draggable)return{success:!1};if(!a.v0){let e=await r.vertices;a.v0=[...e[0]],a.v2=[...e[2]]}let o,l,u,c,p,d;for(let t in e.vertices){let[n,r]=t.split(","),i=e.vertices[t];"0"===n?a.v0[Number(r)]=i:"2"===n?a.v2[Number(r)]=i:"1"===n?"0"===r?a.v2[Number(r)]=i:a.v0[Number(r)]=i:"0"===r?a.v0[Number(r)]=i:a.v2[Number(r)]=i,"0"===r?(o=t,"0"===n||"3"===n?u=t:p=t):(l=t,"0"===n||"1"===n?c=t:d=t)}let m=[];if(0===n.nVerticesSpecified)if(n.haveSpecifiedCenter){if(void 0!==o){let e=a.v2[0].subtract(a.v0[0]).evaluate_to_constant(),t=a.v2[0].add(a.v0[0]).divide(2).simplify();m.push({setDependency:s[o].specifiedWidth,desiredValue:e},{setDependency:s[o].specifiedCenter,desiredValue:t})}if(void 0!==l){let e=a.v2[1].subtract(a.v0[1]).evaluate_to_constant(),t=a.v2[1].add(a.v0[1]).divide(2).simplify();m.push({setDependency:s[l].specifiedHeight,desiredValue:e},{setDependency:s[l].specifiedCenter,desiredValue:t})}}else{if(void 0!==u){let e=a.v0[0].simplify();m.push({setDependency:s[u].essentialVertex,desiredValue:e})}if(void 0!==p){let e=a.v2[0].subtract(a.v0[0]).evaluate_to_constant();m.push({setDependency:s[p].specifiedWidth,desiredValue:e})}if(void 0!==c){let e=a.v0[1].simplify();m.push({setDependency:s[c].essentialVertex,desiredValue:e})}if(void 0!==d){let e=a.v2[1].subtract(a.v0[1]).evaluate_to_constant();m.push({setDependency:s[d].specifiedHeight,desiredValue:e})}}else if(1===n.nVerticesSpecified)if(n.haveSpecifiedCenter){if(void 0!==u){let e=a.v0[0].simplify();m.push({setDependency:s[u].verticesAttr,desiredValue:e,variableIndex:0})}if(void 0!==p){let e=a.v2[0].add(a.v0[0]).divide(2).simplify();m.push({setDependency:s[p].specifiedCenter,desiredValue:e})}if(void 0!==c){let e=a.v0[1].simplify();m.push({setDependency:s[c].verticesAttr,desiredValue:e,variableIndex:0})}if(void 0!==d){let e=a.v2[1].add(a.v0[1]).divide(2).simplify();m.push({setDependency:s[d].specifiedCenter,desiredValue:e})}}else{if(void 0!==u){let e=a.v0[0].simplify();m.push({setDependency:s[u].verticesAttr,desiredValue:e,variableIndex:0})}if(void 0!==p){let e=a.v2[0].subtract(a.v0[0]).evaluate_to_constant();m.push({setDependency:s[p].specifiedWidth,desiredValue:e})}if(void 0!==c){let e=a.v0[1].simplify();m.push({setDependency:s[c].verticesAttr,desiredValue:e,variableIndex:0})}if(void 0!==d){let e=a.v2[1].subtract(a.v0[1]).evaluate_to_constant();m.push({setDependency:s[d].specifiedHeight,desiredValue:e})}}else void 0!==u&&m.push({setDependency:s[u].verticesAttr,desiredValue:a.v0[0],variableIndex:0}),void 0!==p&&m.push({setDependency:s[p].verticesAttr,desiredValue:a.v2[0],variableIndex:0}),void 0!==c&&m.push({setDependency:s[c].verticesAttr,desiredValue:a.v0[1],variableIndex:0}),void 0!==d&&m.push({setDependency:s[d].verticesAttr,desiredValue:a.v2[1],variableIndex:0});return{success:!0,instructions:m}}},e.nVertices={public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{nVertices:4}})},e}async movePolygon({pointCoords:e,transient:t,sourceInformation:n,actionId:r}){let a=[],i={};for(let t in e)i[t+",0"]=me$3.fromAst(e[t][0]),i[t+",1"]=me$3.fromAst(e[t][1]);if(a.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"vertices",value:i,sourceInformation:n}),1===Object.keys(e).length){let t=Number(Object.keys(e)[0]),n=me$3.fromAst(e[t][0]),r=me$3.fromAst(e[t][1]),i=(t+2)%4,s=await this.stateValues.vertices,o=s[i][0],l=s[i][1];if(await this.stateValues.nVerticesSpecified<2)if(await this.stateValues.haveSpecifiedCenter){let e,i;0===t?(e=n.add(o).divide(2),i=r.add(l).divide(2)):1===t?i=r.add(l).divide(2):3===t&&(e=n.add(o).divide(2)),void 0!==e&&a.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"specifiedCenter",value:{0:e.simplify()}}),void 0!==i&&a.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"specifiedCenter",value:{1:i.simplify()}})}else{let e,i;0===t?(e=o.subtract(n),i=l.subtract(r)):1===t?i=l.subtract(r):3===t&&(e=o.subtract(n)),void 0!==e&&a.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"specifiedWidth",value:e.simplify()}),void 0!==i&&a.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"specifiedHeight",value:i.simplify()})}}return t?await this.coreFunctions.performUpdate({updateInstructions:a,transient:t,actionId:r}):await this.coreFunctions.performUpdate({updateInstructions:a,actionId:r,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{pointCoordinates:e}}})}}class Circle extends Curve{constructor(e){super(e),Object.assign(this.actions,{moveCircle:this.moveCircle.bind(this),circleClicked:this.circleClicked.bind(this),mouseDownOnCircle:this.mouseDownOnCircle.bind(this)})}static componentType="circle";static rendererType="circle";static representsClosedPath=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.through={createComponentOfType:"_pointListComponent"},e.center={createComponentOfType:"point"},e.radius={createComponentOfType:"math"},e.filled={createComponentOfType:"boolean",createStateVariable:"filled",defaultValue:!1,public:!0,forRenderer:!0},delete e.parMin,delete e.parMax,delete e.variable,e}static returnChildGroups(){return GraphicalComponent.returnChildGroups()}static returnStateVariableDefinitions(e){let t=GraphicalComponent.returnStateVariableDefinitions(e);return t.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"},filled:{dependencyType:"stateVariable",variableName:"filled"}}),definition:function({dependencyValues:e}){let t,n=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(n&&(n+=" "),n+=e.selectedStyle.lineStyleWord),n&&(n+=" "),e.filled?e.selectedStyle.fillColorWord===e.selectedStyle.lineColorWord?(t="filled "+e.selectedStyle.fillColorWord,n&&(t+=" with "+n+"border")):t="filled "+e.selectedStyle.fillColorWord+" with "+n+e.selectedStyle.lineColorWord+" border":t=n+e.selectedStyle.lineColorWord,{setValue:{styleDescription:t}}}},t.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"},filled:{dependencyType:"stateVariable",variableName:"filled"}}),definition:function({dependencyValues:e}){let t,n=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(n&&(n+=" "),n+=e.selectedStyle.lineStyleWord),n&&(n+=" "),e.filled?e.selectedStyle.fillColorWord===e.selectedStyle.lineColorWord?(t="filled "+e.selectedStyle.fillColorWord+" circle",n&&(t+=" with a "+n+"border")):t="filled "+e.selectedStyle.fillColorWord+" circle with a "+n+e.selectedStyle.lineColorWord+" border":t=n+e.selectedStyle.lineColorWord+" circle",{setValue:{styleDescriptionWithNoun:t}}}},t.borderStyleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){let t=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(t&&(t+=" "),t+=e.selectedStyle.lineStyleWord),t&&(t+=" "),t+=e.selectedStyle.lineColorWord,{setValue:{borderStyleDescription:t}}}},t.fillStyleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"},filled:{dependencyType:"stateVariable",variableName:"filled"}}),definition:function({dependencyValues:e}){let t;return t=e.filled?e.selectedStyle.fillColorWord:"unfilled",{setValue:{fillStyleDescription:t}}}},t.curveType={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{curveType:"circle"}})},t.parMax={public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{parMax:NaN}})},t.parMin={public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{parMin:NaN}})},t.fs={forRenderer:!0,isArray:!0,entryPrefixes:["f"],returnArraySizeDependencies:()=>({}),returnArraySize:()=>[0],returnArrayDependenciesByKey:()=>({}),arrayDefinitionByKey:()=>({setValue:{fs:{}}})},t.nThroughPoints={returnDependencies:()=>({throughAttr:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["nPoints"]}}),definition:function({dependencyValues:e}){return null!==e.throughAttr?{setValue:{nThroughPoints:e.throughAttr.stateValues.nPoints}}:{setValue:{nThroughPoints:0}}}},t.throughPoints={public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"throughPointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,nDimensions:2,entryPrefixes:["throughPointX","throughPoint"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("throughPointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("throughPoints"===t)return 1===e.length?"throughPoint"+e[0]:`throughPointX${e[0]}_${e[1]}`;if("throughPoint"===t.slice(0,12)){let n=Number(t.slice(12));if(Number.isInteger(n)&&n>0)return`throughPointX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints,2],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let[e,r]=n.split(","),a=Number(e)+1+"_"+(Number(r)+1);t[n]={throughAttr:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["pointX"+a]}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let[t,a]=r.split(","),i=Number(t)+1+"_"+(Number(a)+1),s=e[r].throughAttr;null!==s&&s.stateValues["pointX"+i]?n[r]=s.stateValues["pointX"+i]:n[r]=me$3.fromAst("_")}return{setValue:{throughPoints:n}}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n,initialChange:r,stateValues:a}){if(r&&!await a.draggable)return{success:!1};let i=[];for(let r in e.throughPoints){let[a,s]=r.split(","),o=Number(a)+1+"_"+(Number(s)+1);if(null===t[r].throughAttr||!t[r].throughAttr.stateValues["pointX"+o])return{success:!1};i.push({setDependency:n[r].throughAttr,desiredValue:e.throughPoints[r],variableIndex:0})}return{success:!0,instructions:i}}},t.havePrescribedCenter={returnDependencies:()=>({centerAttr:{dependencyType:"attributeComponent",attributeName:"center"}}),definition:({dependencyValues:e})=>({setValue:{havePrescribedCenter:null!==e.centerAttr},checkForActualChange:{havePrescribedCenter:!0}})},t.prescribedCenter={isArray:!0,entryPrefixes:["prescribedCenterX"],returnArraySizeDependencies:()=>({havePrescribedCenter:{dependencyType:"stateVariable",variableName:"havePrescribedCenter"}}),returnArraySize:({dependencyValues:e})=>[e.havePrescribedCenter?2:0],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={centerAttr:{dependencyType:"attributeComponent",attributeName:"center",variableNames:["x"+e]}}}return{dependenciesByKey:t}},arrayDefinitionByKey:function({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};for(let e of n){let n=Number(e)+1;null!==t[e].centerAttr&&(r[e]=t[e].centerAttr.stateValues["x"+n],r[e]||(r[e]=me$3.fromAst("_")))}return{setValue:{prescribedCenter:r}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i=[];for(let t of Object.keys(e.prescribedCenter).reverse())null!==n[t].centerAttr&&i.push({setDependency:r[t].centerAttr,desiredValue:e.prescribedCenter[t],variableIndex:0});return{success:!0,instructions:i}}},t.prescribedRadius={defaultValue:null,returnDependencies:()=>({radiusAttr:{dependencyType:"attributeComponent",attributeName:"radius",variableNames:["value"]}}),definition:function({dependencyValues:e}){return null!==e.radiusAttr?{setValue:{prescribedRadius:e.radiusAttr.stateValues.value}}:{setValue:{prescribedRadius:null}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){return null!==t.radiusAttr?{success:!0,instructions:[{setDependency:"radiusAttr",desiredValue:e.prescribedRadius,childIndex:0,variableIndex:0}]}:{success:!1}}},t.havePrescribedRadius={returnDependencies:()=>({radiusAttr:{dependencyType:"attributeComponent",attributeName:"radius"}}),definition:({dependencyValues:e})=>({setValue:{havePrescribedRadius:null!==e.radiusAttr},checkForActualChange:{havePrescribedRadius:!0}})},t.numericalPrescribedRadius={returnDependencies:()=>({prescribedRadius:{dependencyType:"stateVariable",variableName:"prescribedRadius"}}),additionalStateVariablesDefined:["haveNonNumericalPrescribedRadius"],definition:function({dependencyValues:e}){let t,n=!1;return null===e.prescribedRadius?t=null:(t=e.prescribedRadius.evaluate_to_constant(),Number.isFinite(t)||(t=NaN,n=!0)),{setValue:{haveNonNumericalPrescribedRadius:n,numericalPrescribedRadius:t},checkForActualChange:{haveNonNumericalEntriesNumericalRadius:!0}}},inverseDefinition:async function({desiredStateVariableValues:e,dependencyValues:t,stateValues:n}){return await n.haveNonNumericalPrescribedRadius?{success:!1}:void 0!==e.numericalPrescribedRadius?null===t.prescribedRadius?{success:!1}:{success:!0,instructions:[{setDependency:"prescribedRadius",desiredValue:me$3.fromAst(e.numericalPrescribedRadius)}]}:{success:!1}}},t.numericalPrescribedCenter={isArray:!0,entryPrefixes:["numericalPrescribedCenterX"],returnArraySizeDependencies:()=>({havePrescribedCenter:{dependencyType:"stateVariable",variableName:"havePrescribedCenter"}}),returnArraySize:({dependencyValues:e})=>[e.havePrescribedCenter?2:0],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={prescribedCenterX:{dependencyType:"stateVariable",variableName:"prescribedCenterX"+e}}}return{dependenciesByKey:t}},arrayDefinitionByKey:function({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].prescribedCenterX;t?(n[r]=t.evaluate_to_constant(),Number.isFinite(n[r])||(n[r]=NaN)):n[r]=NaN}return{setValue:{numericalPrescribedCenter:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t}){let n=[];for(let r in e.numericalPrescribedCenter)n.push({setDependency:t[r].prescribedCenterX,desiredValue:me$3.fromAst(e.numericalPrescribedCenter[r])});return{success:!0,instructions:n}}},t.haveNonNumericalPrescribedCenter={returnDependencies:()=>({numericalPrescribedCenter:{dependencyType:"stateVariable",variableName:"numericalPrescribedCenter"}}),definition({dependencyValues:e}){let t=e.numericalPrescribedCenter.some((e=>!Number.isFinite(e)));return{setValue:{haveNonNumericalPrescribedCenter:t},checkForActualChange:{haveNonNumericalPrescribedCenter:!0}}}},t.numericalThroughPoints={returnDependencies:()=>({throughPoints:{dependencyType:"stateVariable",variableName:"throughPoints"}}),additionalStateVariablesDefined:["haveNonNumericalThroughPoints"],definition:function({dependencyValues:e}){let t=!1,n=[];for(let r of e.throughPoints){let e=[];for(let n=0;n<2;n++){let a;try{a=r[n].evaluate_to_constant()}catch(n){console.warn("Invalid point of circle"),t=!0,e=[];break}if(!Number.isFinite(a)){t=!0,e=[];break}e.push(a)}if(!(e.length>0)){n=[];break}n.push(e)}return{setValue:{haveNonNumericalThroughPoints:t,numericalThroughPoints:n},checkForActualChange:{haveNonNumericalThroughPoints:!0}}},inverseDefinition:async function({desiredStateVariableValues:e,dependencyValues:t,stateValues:n}){if(await n.haveNonNumericalThroughPoints)return{success:!1};if(void 0!==e.numericalThroughPoints){let t={};for(let[n,r]of e.numericalThroughPoints.entries())t[n+",0"]=me$3.fromAst(r[0]),t[n+",1"]=me$3.fromAst(r[1]);return{success:!0,instructions:[{setDependency:"throughPoints",desiredValue:t}]}}return{success:!1}}},t.haveNumericalEntries={returnDependencies:()=>({haveNonNumericalPrescribedCenter:{dependencyType:"stateVariable",variableName:"haveNonNumericalPrescribedCenter"},haveNonNumericalPrescribedRadius:{dependencyType:"stateVariable",variableName:"haveNonNumericalPrescribedRadius"},haveNonNumericalThroughPoints:{dependencyType:"stateVariable",variableName:"haveNonNumericalThroughPoints"}}),definition:({dependencyValues:e})=>({setValue:{haveNumericalEntries:!(e.haveNonNumericalPrescribedCenter||e.haveNonNumericalPrescribedRadius||e.haveNonNumericalThroughPoints)}})},t.numericalRadiusCalculatedWithCenter={additionalStateVariablesDefined:["numericalCenterCalculatedWithRadius"],returnDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"},numericalThroughPoints:{dependencyType:"stateVariable",variableName:"numericalThroughPoints"},haveNumericalEntries:{dependencyType:"stateVariable",variableName:"haveNonNumericalThroughPoints"}}),definition:function({dependencyValues:e}){if(e.haveNonNumericalThroughPoints){let t="Haven't implemented circle through "+e.nThroughPoints+" points";return t+=" in case where don't have numerical values.",console.warn(t),{setValue:{numericalRadiusCalculatedWithCenter:null,numericalCenterCalculatedWithRadius:null}}}if(2===e.nThroughPoints){let{numericalCenter:t,numericalRadius:n}=circleFromTwoNumericalPoints({point1:e.numericalThroughPoints[0],point2:e.numericalThroughPoints[1]});return{setValue:{numericalCenterCalculatedWithRadius:t,numericalRadiusCalculatedWithCenter:n}}}if(3===e.nThroughPoints){let t,n,r=e.numericalThroughPoints[0][0],a=e.numericalThroughPoints[1][0],i=e.numericalThroughPoints[2][0],s=e.numericalThroughPoints[0][1],o=e.numericalThroughPoints[1][1],l=e.numericalThroughPoints[2][1];if(r===a&&s===o)if(r===i&&s===l)t=[r,s],n=0;else{let e=circleFromTwoNumericalPoints({point1:[r,s],point2:[i,l]});t=e.numericalCenter,n=e.numericalRadius}else if(r===i&&s===l||a===i&&o===l){let e=circleFromTwoNumericalPoints({point1:[r,s],point2:[a,o]});t=e.numericalCenter,n=e.numericalRadius}else{let e=r*r+s*s,u=a*a+o*o,c=i*i+l*l,p=r*(o-l)-s*(a-i)+a*l-i*o,d=e*(l-o)+u*(s-l)+c*(o-s),m=e*(a-i)+u*(i-r)+c*(r-a),h=e*(i*o-a*l)+u*(r*l-i*s)+c*(a*s-r*o);0!==p?(t=[-d/(2*p),-m/(2*p)],n=Math.sqrt((d*d+m*m-4*p*h)/(4*p*p))):(t=[NaN,NaN],n=NaN)}return{setValue:{numericalCenterCalculatedWithRadius:t,numericalRadiusCalculatedWithCenter:n}}}return e.nThroughPoints>3?(console.warn("Can't calculate circle through more than 3 points"),{setValue:{numericalRadiusCalculatedWithCenter:null,numericalCenterCalculatedWithRadius:null}}):{setValue:{numericalRadiusCalculatedWithCenter:null,numericalCenterCalculatedWithRadius:null}}}},t.essentialRadius={defaultValue:1,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{essentialRadius:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"essentialRadius",value:e.essentialRadius}]}}},t.numericalRadius={forRenderer:!0,stateVariablesDeterminingDependencies:["nThroughPoints","havePrescribedCenter","havePrescribedRadius"],returnDependencies:function({stateValues:e}){let t={haveNonNumericalPrescribedRadius:{dependencyType:"stateVariable",variableName:"haveNonNumericalPrescribedRadius"},nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"},essentialRadius:{dependencyType:"stateVariable",variableName:"essentialRadius"}};return e.havePrescribedRadius?(t.numericalPrescribedRadius={dependencyType:"stateVariable",variableName:"numericalPrescribedRadius"},e.havePrescribedCenter&&e.nThroughPoints>0&&(t.haveCenterRadiusPoints={dependencyType:"value",value:!0})):e.havePrescribedCenter?1===e.nThroughPoints&&(t.haveNonNumericalPrescribedCenter={dependencyType:"stateVariable",variableName:"haveNonNumericalPrescribedCenter"},t.numericalPrescribedCenter={dependencyType:"stateVariable",variableName:"numericalPrescribedCenter"},t.haveNonNumericalThroughPoints={dependencyType:"stateVariable",variableName:"haveNonNumericalThroughPoints"},t.numericalThroughPoints={dependencyType:"stateVariable",variableName:"numericalThroughPoints"}):e.nThroughPoints>1&&(t.numericalRadiusCalculatedWithCenter={dependencyType:"stateVariable",variableName:"numericalRadiusCalculatedWithCenter"},t.numericalThroughPoints={dependencyType:"stateVariable",variableName:"numericalThroughPoints"}),t},definition:function({dependencyValues:e}){if(e.haveNonNumericalPrescribedRadius||e.haveNonNumericalPrescribedCenter||e.haveNonNumericalThroughPoints)return{setValue:{numericalRadius:NaN}};if(void 0!==e.numericalPrescribedRadius)return e.haveCenterRadiusPoints?(console.warn("Can't calculate circle with specified radius and center and through points"),{setValue:{numericalRadius:NaN}}):{setValue:{numericalRadius:Math.max(0,e.numericalPrescribedRadius)}};if(void 0!==e.numericalPrescribedCenter){if(0===e.nThroughPoints){let t=e.essentialRadius;if(t instanceof me$3.class){try{t=t.evaluate_to_constant()}catch(e){}Number.isFinite(t)||(t=NaN)}return{setValue:{numericalRadius:t}}}if(1===e.nThroughPoints){let t=e.numericalThroughPoints[0];return void 0===t?{setValue:{numericalRadius:NaN}}:{setValue:{numericalRadius:Math.sqrt(Math.pow(t[0]-e.numericalPrescribedCenter[0],2)+Math.pow(t[1]-e.numericalPrescribedCenter[1],2))}}}return console.warn("Can't calculate circle with specified center through more than 1 point"),{setValue:{numericalRadius:NaN}}}if(e.nThroughPoints<2){let t=e.essentialRadius;if(t instanceof me$3.class){try{t=t.evaluate_to_constant()}catch(e){}Number.isFinite(t)||(t=NaN)}return{setValue:{numericalRadius:t}}}return{setValue:{numericalRadius:e.numericalRadiusCalculatedWithCenter}}},inverseDefinition:async function({desiredStateVariableValues:e,dependencyValues:t,stateValues:n}){if(void 0!==t.numericalPrescribedRadius)return{success:!0,instructions:[{setDependency:"numericalPrescribedRadius",desiredValue:Math.max(0,e.numericalRadius)}]};if(void 0!==t.numericalPrescribedCenter){if(0===t.nThroughPoints)return{success:!0,instructions:[{setDependency:"essentialRadius",desiredValue:Math.max(0,e.numericalRadius)}]};if(1===t.nThroughPoints){let t=Math.max(0,e.numericalRadius),r=(await n.throughAngles)[0];if(!Number.isFinite(r))return{success:!1};let a=await n.numericalCenter;return{success:!0,instructions:[{setDependency:"numericalThroughPoints",desiredValue:[[a[0]+t*Math.cos(r),a[1]+t*Math.sin(r)]]}]}}return{success:!1}}if(t.nThroughPoints<2)return{success:!0,instructions:[{setDependency:"essentialRadius",desiredValue:Math.max(0,e.numericalRadius)}]};{let r=[],a=Math.max(0,e.numericalRadius);for(let e=0;e0,returnArraySizeDependencies:()=>({}),returnArraySize:()=>[2],returnArrayDependenciesByKey:()=>({}),arrayDefinitionByKey:function({arrayKeys:e}){let t={};for(let n of e)t[n]=!0;return{useEssentialOrDefaultValue:{essentialCenter:t}}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,stateValues:t,workspace:n}){let r=[];for(let t in e.essentialCenter)r.push({setEssentialValue:"essentialCenter",value:{[t]:e.essentialCenter[t]}});return{success:!0,instructions:r}}},t.numericalCenter={forRenderer:!0,isArray:!0,entryPrefixes:["numericalCenterX"],stateVariablesDeterminingDependencies:["nThroughPoints","havePrescribedCenter","havePrescribedRadius"],returnArraySizeDependencies:()=>({}),returnArraySize:()=>[2],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={},r={};if(t.havePrescribedCenter){for(let t of e){let e=Number(t)+1;r[t]={numericalPrescribedCenterX:{dependencyType:"stateVariable",variableName:"numericalPrescribedCenterX"+e}}}t.havePrescribedRadius&&t.nThroughPoints>0&&(n.haveCenterRadiusPoints={dependencyType:"value",value:!0})}else{for(let t of e){let e=Number(t)+1;r[t]={essentialCenterX:{dependencyType:"stateVariable",variableName:"essentialCenterX"+e}}}n.nThroughPoints={dependencyType:"stateVariable",variableName:"nThroughPoints"},n.numericalThroughPoints={dependencyType:"stateVariable",variableName:"numericalThroughPoints"},n.haveNonNumericalThroughPoints={dependencyType:"stateVariable",variableName:"haveNonNumericalThroughPoints"},t.havePrescribedRadius||1==t.nThroughPoints?n.numericalRadius={dependencyType:"stateVariable",variableName:"numericalRadius"}:t.nThroughPoints>1&&(n.numericalCenterCalculatedWithRadius={dependencyType:"stateVariable",variableName:"numericalCenterCalculatedWithRadius"})}return{globalDependencies:n,dependenciesByKey:r}},arrayDefinitionByKey:function({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};for(let a of n)if(void 0!==t[a].numericalPrescribedCenterX){if(e.haveCenterRadiusPoints)return console.warn("Can't calculate circle with specified radius and center and through points"),{setValue:{numericalCenter:[NaN,NaN]}};r[a]=t[a].numericalPrescribedCenterX}if(Object.keys(r).length>0)return{setValue:{numericalCenter:r}};if(e.haveNonNumericalPrescribedRadius||e.haveNonNumericalThroughPoints)return{setValue:{numericalCenter:[NaN,NaN]}};if(void 0!==e.numericalRadius){if(0===e.nThroughPoints){for(let e of n){let n=t[e].essentialCenterX;if(n instanceof me$3.class){try{n=n.evaluate_to_constant()}catch(e){}Number.isFinite(n)||(n=NaN)}r[e]=n}return{setValue:{numericalCenter:r}}}if(1===e.nThroughPoints){if(e.numericalThroughPoints.length<1)return{setValue:{numericalCenter:[NaN,NaN]}};return{setValue:{numericalCenter:[e.numericalThroughPoints[0][0],e.numericalThroughPoints[0][1]-e.numericalRadius]}}}if(2===e.nThroughPoints){if(e.numericalThroughPoints.length<2)return{setValue:{numericalCenter:[NaN,NaN]}};let t=e.numericalRadius,n=e.numericalThroughPoints[0][0],r=e.numericalThroughPoints[1][0],a=e.numericalThroughPoints[0][1],i=e.numericalThroughPoints[1][1],s=Math.pow(n-r,2)+Math.pow(a-i,2),o=t*t;return t<0||4*o0)return{success:!0,instructions:s};if(0===t.nThroughPoints){for(let t in e.numericalCenter)s.push({setDependency:r[t].essentialCenterX,desiredValue:e.numericalCenter[t]});return{success:!0,instructions:s}}{i.desiredCenter||(i.desiredCenter={});for(let t=0;t<2;t++)void 0!==e.numericalCenter[t]?i.desiredCenter[t]=e.numericalCenter[t]:void 0===i.desiredCenter[t]&&(i.desiredCenter[t]=a.numericalCenter[t]);let n=[],r=await a.throughAngles,s=await a.numericalRadius;for(let e=0;e({haveNumericalEntries:{dependencyType:"stateVariable",variableName:"haveNumericalEntries"},nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"},numericalThroughPoints:{dependencyType:"stateVariable",variableName:"numericalThroughPoints"},numericalRadius:{dependencyType:"stateVariable",variableName:"numericalRadius"},numericalCenter:{dependencyType:"stateVariable",variableName:"numericalCenter"}}),definition:function({dependencyValues:e}){if(!(e.haveNumericalEntries&&e.nThroughPoints>0&&e.numericalRadius>0&&e.numericalCenter.every((e=>Number.isFinite(e)))))return{useEssentialOrDefaultValue:{throughAngles:!0}};let t=[];for(let n of e.numericalThroughPoints)t.push(Math.atan2(n[1]-e.numericalCenter[1],n[0]-e.numericalCenter[0]));return{setValue:{throughAngles:t},setEssentialValue:{throughAngles:t}}}},t.radius={public:!0,shadowingInstructions:{createComponentOfType:"math"},stateVariablesDeterminingDependencies:["nThroughPoints","havePrescribedCenter","havePrescribedRadius"],returnDependencies:function({stateValues:e}){let t={numericalRadius:{dependencyType:"stateVariable",variableName:"numericalRadius"},nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"},essentialRadius:{dependencyType:"stateVariable",variableName:"essentialRadius"}};return e.havePrescribedRadius?(t.prescribedRadius={dependencyType:"stateVariable",variableName:"prescribedRadius"},e.havePrescribedCenter&&e.nThroughPoints>0&&(t.haveCenterRadiusPoints={dependencyType:"value",value:!0})):e.havePrescribedCenter&&1===e.nThroughPoints&&(t.prescribedCenter={dependencyType:"stateVariable",variableName:"prescribedCenter"},t.throughPoints={dependencyType:"stateVariable",variableName:"throughPoints"}),t},definition:function({dependencyValues:e}){if(Number.isFinite(e.numericalRadius))return{setValue:{radius:me$3.fromAst(e.numericalRadius)}};if(void 0!==e.prescribedRadius)return e.haveCenterRadiusPoints?(console.warn("Can't calculate circle with specified radius and center and through points"),{setValue:{radius:me$3.fromAst("_")}}):{setValue:{radius:e.prescribedRadius}};if(void 0!==e.prescribedCenter){if(0===e.nThroughPoints){let t=e.essentialRadius;return t instanceof me$3.class||(t=Number.isFinite(t)?me$3.fromAst(t):me$3.fromAst("_")),{setValue:{radius:t}}}if(1!==e.nThroughPoints)return console.warn("Can't calculate circle with specified center through more than 1 point"),{setValue:{radius:me$3.fromAst("_")}};try{let t=e.throughPoints[0],n=t[0],r=t[1],a=e.prescribedCenter[0],i=e.prescribedCenter[1];return{setValue:{radius:n.subtract(a).pow(2).add(r.subtract(i).pow(2)).pow(.5).simplify()}}}catch(e){return console.warn("Invalid center or through points of circle"),{setValue:{radius:me$3.fromAst("_")}}}}if(e.nThroughPoints<2){let t=e.essentialRadius;return t instanceof me$3.class||(t=Number.isFinite(t)?me$3.fromAst(t):me$3.fromAst("_")),{setValue:{radius:t}}}return console.warn(`Have not implemented circle through ${e.nThroughPoints} points when non-numerical values`),{setValue:{radius:me$3.fromAst("_")}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){let n=e.radius.evaluate_to_constant();if(Number.isFinite(n)&&Number.isFinite(t.numericalRadius))return{success:!0,instructions:[{setDependency:"numericalRadius",desiredValue:n}]};if(void 0!==t.prescribedRadius)return{success:!0,instructions:[{setDependency:"prescribedRadius",desiredValue:e.radius}]};if(0===t.nThroughPoints){return{success:!0,instructions:[{setDependency:"essentialRadius",desiredValue:e.radius}]}}return console.warn("Can't change radius of circle with non-numerical values through points"),{success:!1}}},t.diameter={public:!0,shadowingInstructions:{createComponentOfType:"math"},returnDependencies:()=>({radius:{dependencyType:"stateVariable",variableName:"radius"}}),definition:({dependencyValues:e})=>({setValue:{diameter:e.radius.multiply(2).simplify()}}),inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){return{success:!0,instructions:[{setDependency:"radius",desiredValue:e.diameter.divide(2).simplify()}]}}},t.center={forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"centerX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,entryPrefixes:["centerX"],stateVariablesDeterminingDependencies:["nThroughPoints","havePrescribedCenter","havePrescribedRadius"],returnArraySizeDependencies:()=>({}),returnArraySize:()=>[2],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={},r={};if(t.havePrescribedCenter){n.havePrescribedCenter={dependencyType:"value",value:!0};for(let t of e){let e=Number(t)+1;r[t]={numericalCenterX:{dependencyType:"stateVariable",variableName:"numericalCenterX"+e},prescribedCenterX:{dependencyType:"stateVariable",variableName:"prescribedCenterX"+e}}}t.havePrescribedRadius&&t.nThroughPoints>0&&(n.haveCenterRadiusPoints={dependencyType:"value",value:!0})}else{for(let t of e){let e=Number(t)+1;r[t]={essentialCenterX:{dependencyType:"stateVariable",variableName:"essentialCenterX"+e}}}n.numericalCenter={dependencyType:"stateVariable",variableName:"numericalCenter"},n.nThroughPoints={dependencyType:"stateVariable",variableName:"nThroughPoints"},n.throughPoints={dependencyType:"stateVariable",variableName:"throughPoints"},t.havePrescribedRadius?n.radius={dependencyType:"stateVariable",variableName:"prescribedRadius"}:1==t.nThroughPoints&&(n.radius={dependencyType:"stateVariable",variableName:"radius"})}return{dependenciesByKey:r,globalDependencies:n}},arrayDefinitionByKey:function({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){if(e.havePrescribedCenter){if(e.haveCenterRadiusPoints)return console.warn("Can't calculate circle with specified radius and center and through points"),{setValue:{center:[me$3.fromAst("_"),me$3.fromAst("_")]}};let r={};for(let e of n)Number.isFinite(t[e].numericalCenterX)?r[e]=me$3.fromAst(t[e].numericalCenterX):r[e]=t[e].prescribedCenterX;return{setValue:{center:r}}}if(e.numericalCenter.every((e=>Number.isFinite(e))))return{setValue:{center:e.numericalCenter.map((e=>me$3.fromAst(e)))}};if(void 0!==e.radius){if(0===e.nThroughPoints){let e={};for(let r of n){let n=t[r].essentialCenterX;n instanceof me$3.class||(n=Number.isFinite(n)?me$3.fromAst(n):me$3.fromAst("_")),e[r]=n}return{setValue:{center:e}}}if(1===e.nThroughPoints){let t;try{t=[e.throughPoints[0][0],e.throughPoints[0][1].subtract(e.radius).simplify()]}catch(e){t=[me$3.fromAst("_"),me$3.fromAst("_")]}return{setValue:{center:t}}}return console.warn("Can't create circle through more than one point with given radius when don't have numerical values"),{setValue:{center:[me$3.fromAst("_"),me$3.fromAst("_")]}}}if(0===e.nThroughPoints){let e={};for(let r of n){let n=t[r].essentialCenterX;n instanceof me$3.class||(n=Number.isFinite(n)?me$3.fromAst(n):me$3.fromAst("_")),e[r]=n}return{setValue:{center:e}}}return console.warn("Can't create circle through more than one point when don't have numerical values"),{setValue:{center:[me$3.fromAst("_"),me$3.fromAst("_")]}}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,stateValues:n,dependencyNamesByKey:r,workspace:a}){if(t.havePrescribedCenter){let t=[];for(let n in e.center)t.push({setDependency:r[n].prescribedCenterX,desiredValue:e.center[n],arrayKey:n});return{success:!0,instructions:t}}a.desiredCenter||(a.desiredCenter={});for(let t=0;t<2;t++)void 0!==e.center[t]?a.desiredCenter[t]=e.center[t]:void 0===a.desiredCenter[t]&&(a.desiredCenter[t]=(await n.center)[t]);let i=[],s=!0;for(let e=0;e<2;e++){let t=a.desiredCenter[e].evaluate_to_constant();if(!Number.isFinite(t)){s=!1;break}i.push(t)}if(s&&t.numericalCenter.every((e=>Number.isFinite(e))))return{success:!0,instructions:[{setDependency:"numericalCenter",desiredValue:i}]};if(0===t.nThroughPoints){let t=[];for(let n in e.center)t.push({setDependency:r[n].essentialCenterX,desiredValue:e.center[n],arrayKey:n});return{success:!0,instructions:t}}return console.warn("Haven't implemented changing center of circle through points with non numerical values"),{success:!1}}},t.nearestPoint={returnDependencies:()=>({numericalCenter:{dependencyType:"stateVariable",variableName:"numericalCenter"},numericalRadius:{dependencyType:"stateVariable",variableName:"numericalRadius"}}),definition({dependencyValues:e}){let t=e.numericalRadius,n=e.numericalCenter[0],r=e.numericalCenter[1];return{setValue:{nearestPoint:function({variables:e,scales:a}){let i=e.x1?.evaluate_to_constant(),s=e.x2?.evaluate_to_constant();if(!Number.isFinite(i)||!Number.isFinite(s))return{};if(!(Number.isFinite(n)&&Number.isFinite(r)&&Number.isFinite(t)))return{};let o=Math.atan2(s-r,i-n),l={x1:n+t*Math.cos(o),x2:r+t*Math.sin(o)};return void 0!==e.x3&&(l.x3=0),l}}}}},t}async moveCircle({center:e,radius:t,throughAngles:n,transient:r,actionId:a}){let i=[],s=await this.stateValues.nThroughPoints,o=await this.stateValues.numericalPrescribedCenter;if((s<=1||null!==o)&&i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"numericalCenter",value:e}),s>=1){let r=[];void 0===n&&(n=await this.stateValues.throughAngles),void 0===t&&(t=await this.stateValues.numericalRadius);for(let a=0;a({styleDescription:{dependencyType:"stateVariable",variableName:"styleDescription"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescriptionWithNoun:e.styleDescription+" parabola"}}}},t.curveType={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{curveType:"function"}})},t.parMax={public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{parMax:1/0}})},t.parMin={public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{parMin:-1/0}})},t.aShadow={defaultValue:1,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{aShadow:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"aShadow",value:e.aShadow}]}}},t.nThroughPoints={returnDependencies:()=>({throughAttr:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["nPoints"]}}),definition:function({dependencyValues:e}){return null===e.throughAttr?{setValue:{nThroughPoints:0}}:{setValue:{nThroughPoints:e.throughAttr.stateValues.nPoints}}}},t.throughPoints={public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"throughPointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,nDimensions:2,entryPrefixes:["throughPointX","throughPoint"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("throughPointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("throughPoints"===t)return 1===e.length?"throughPoint"+e[0]:`throughPointX${e[0]}_${e[1]}`;if("throughPoint"===t.slice(0,12)){let n=Number(t.slice(12));if(Number.isInteger(n)&&n>0)return`throughPointX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints,2],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let[e,r]=n.split(","),a=Number(e)+1+"_"+(Number(r)+1);t[n]={throughAttr:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["pointX"+a]}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let[t,a]=r.split(","),i=Number(t)+1+"_"+(Number(a)+1),s=e[r].throughAttr;if(null!==s&&s.stateValues["pointX"+i]){let e=s.stateValues["pointX"+i].evaluate_to_constant();Number.isFinite(e)?n[r]=me$3.fromAst(e):n[r]=me$3.fromAst("_")}else n[r]=me$3.fromAst("_")}return{setValue:{throughPoints:n}}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n,initialChange:r,stateValues:a}){if(r&&!await a.draggable)return{success:!1};let i=[];for(let r in e.throughPoints){let[a,s]=r.split(","),o=Number(a)+1+"_"+(Number(s)+1);if(null===t[r].throughAttr||!t[r].throughAttr.stateValues["pointX"+o])return{success:!1};i.push({setDependency:n[r].throughAttr,desiredValue:e.throughPoints[r],childIndex:0,variableIndex:0})}return{success:!0,instructions:i}}},t.numericalThroughPoints={isArray:!0,forRenderer:!0,returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={throughPoint:{dependencyType:"stateVariable",variableName:"throughPoint"+(Number(n)+1)}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].throughPoint.map((e=>e.tree));t.every((e=>Number.isFinite(e)))||(t=Array(t.length).fill(NaN)),n[r]=t}return{setValue:{numericalThroughPoints:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n}){let r=[];for(let a in e.numericalThroughPoints){if(!t[a].throughPoint)return{success:!1};r.push({setDependency:n[a].throughPoint,desiredValue:e.numericalThroughPoints[a].map((e=>me$3.fromAst(e)))})}return{success:!0,instructions:r}}},t.numericalPrescribedVertex={returnDependencies:()=>({prescribedVertex:{dependencyType:"stateVariable",variableName:"prescribedVertex"}}),definition({dependencyValues:e}){if(null===e.prescribedVertex)return{setValue:{numericalPrescribedVertex:null}};let t,n;try{t=e.prescribedVertex.get_component(0).evaluate_to_constant(),n=e.prescribedVertex.get_component(1).evaluate_to_constant(),Number.isFinite(t)&&Number.isFinite(n)||(t=NaN,n=NaN)}catch(e){t=NaN,n=NaN}return{setValue:{numericalPrescribedVertex:[t,n]}}}},t.pointsAreNumerical={returnDependencies:()=>({numericalThroughPoints:{dependencyType:"stateVariable",variableName:"numericalThroughPoints"},numericalPrescribedVertex:{dependencyType:"stateVariable",variableName:"numericalPrescribedVertex"}}),definition:({dependencyValues:e})=>({setValue:{pointsAreNumerical:e.numericalThroughPoints.every((e=>Number.isFinite(e[0])))&&(!e.numericalPrescribedVertex||Number.isFinite(e.numericalPrescribedVertex[0]))},checkForActualChange:{pointsAreNumerical:!0}})},t.a={public:!0,shadowingInstructions:{createComponentOfType:"number"},additionalStateVariablesDefined:[{variableName:"b",public:!0,shadowingInstructions:{createComponentOfType:"number"},hasEssential:!0,defaultValue:0},{variableName:"c",public:!0,shadowingInstructions:{createComponentOfType:"number"},hasEssential:!0,defaultValue:0},"realValued"],returnDependencies:()=>({numericalThroughPoints:{dependencyType:"stateVariable",variableName:"numericalThroughPoints"},numericalPrescribedVertex:{dependencyType:"stateVariable",variableName:"numericalPrescribedVertex"},pointsAreNumerical:{dependencyType:"stateVariable",variableName:"pointsAreNumerical"},aShadow:{dependencyType:"stateVariable",variableName:"aShadow"}}),definition:function({dependencyValues:e,componentName:t}){if(!e.pointsAreNumerical)return{setValue:{a:NaN,b:NaN,c:NaN,realValued:!1}};let n,r,a,i=!0;if(e.numericalPrescribedVertex){if(0===e.numericalThroughPoints.length){let t=e.numericalPrescribedVertex,i=t[0],s=t[1];return n=e.aShadow,r=-2*n*i,a=n*i*i+s,{setValue:{a:n,b:r,c:a,realValued:!0}}}{let t=e.numericalPrescribedVertex,i=t[0],s=t[1],o=e.numericalThroughPoints[0],l=o[0];return n=(o[1]-s)/(l-i)**2,r=-2*n*i,a=n*i*i+s,{setValue:{a:n,b:r,c:a,realValued:!0}}}}if(0===e.numericalThroughPoints.length)return{setValue:{a:e.aShadow,realValued:!0},useEssentialOrDefaultValue:{b:!0,c:!0}};if(1===e.numericalThroughPoints.length){let t=e.numericalThroughPoints[0],i=t[0],s=t[1];return n=e.aShadow,r=-2*n*i,a=n*i*i+s,{setValue:{a:n,b:r,c:a,realValued:!0}}}if(2===e.numericalThroughPoints.length){n=e.aShadow;let t=e.numericalThroughPoints[0],s=t[0],o=t[1],l=s*s,u=e.numericalThroughPoints[1],c=u[0],p=u[1],d=c*c;return s===c?o==p?(r=-2*n*s,a=n*l+o):(i=!1,n=NaN,r=NaN,a=NaN):(r=(o-p-n*(l-d))/(s-c),a=o-n*l-r*s),{setValue:{a:n,b:r,c:a,realValued:i}}}if(3===e.numericalThroughPoints.length){let t=e.numericalThroughPoints[0],s=t[0],o=t[1],l=s*s,u=e.numericalThroughPoints[1],c=u[0],p=u[1],d=c*c,m=e.numericalThroughPoints[2],h=m[0],f=m[1],y=h*h,g=l-y,b=d-y,v=s-h,N=c-h,T=o-f,C=p-f,A=g*N-b*v;if(0===A){let t,u,d,m=!1;s===c?o===p?s===h?o==f?t=1:m=!0:(t=2,u=h,d=f):m=!0:s===h?o===f?(t=2,u=c,d=p):m=!0:c===h&&p===f?(t=2,u=c,d=p):m=!0,m?(i=!1,n=NaN,r=NaN,a=NaN):1===t?(n=e.aShadow,r=-2*n*s,a=n*s*s+o):(n=e.aShadow,r=(o-d-n*(l-u*u))/(s-u),a=o-n*l-r*s)}else n=(T*N-C*v)/A,r=(C*g-T*b)/A,a=o-r*s-n*l;return{setValue:{a:n,b:r,c:a,realValued:i}}}return console.warn("Haven't implemented parabola through more than 3 points"),{setValue:{a:NaN,b:NaN,c:NaN,realValued:!1}}},inverseDefinition:async function({desiredStateVariableValues:e,dependencyValues:t,stateValues:n,workspace:r}){if(!t.pointsAreNumerical)return{success:!1};let a={},i=function(e){if(Number.isFinite(e))return{success:!0,value:e};if(e instanceof me$3.class){let t=e.evaluate_to_constant();if(Number.isFinite(t))return{success:!0,value:t}}return{success:!1}};if(void 0!==e.a){let t=i(e.a);if(!t.success)return{success:!1};a.a=t.value}if(void 0!==e.b){let t=i(e.b);if(!t.success)return{success:!1};a.b=t.value}if(void 0!==e.c){let t=i(e.c);if(!t.success)return{success:!1};a.c=t.value}Object.assign(r,a);let s=async function(e){return void 0!==r[e]?r[e]:await n[e]};if(0===t.numericalThroughPoints.length){let e=[];return void 0!==a.a&&e.push({setDependency:"aShadow",desiredValue:a.a}),void 0!==a.b&&e.push({setEssentialValue:"b",value:a.b}),void 0!==a.c&&e.push({setEssentialValue:"c",value:a.c}),{success:!0,instructions:e}}if(1===t.numericalThroughPoints.length){let e=await s("a"),t=await s("b"),n=await s("c"),r=[{setDependency:"numericalThroughPoints",desiredValue:[[-t/(2*e),n-t*t/(4*e)]]}];return void 0!==a.a&&r.push({setDependency:"aShadow",desiredValue:a.a}),{success:!0,instructions:r}}if(2===t.numericalThroughPoints.length){let e=await s("a"),n=await s("b"),r=await s("c"),i=t.numericalThroughPoints[0][0],o=t.numericalThroughPoints[1][0];if(i===o){i=-n/(2*e);let t=r-n*n/(4*e),s=[{setDependency:"numericalThroughPoints",desiredValue:[[i,t],[i,t]]}];return void 0!==a.a&&s.push({setDependency:"aShadow",desiredValue:a.a}),{success:!0,instructions:s}}{let t=[{setDependency:"numericalThroughPoints",desiredValue:[[i,e*i*i+n*i+r],[o,e*o*o+n*o+r]]}];return void 0!==a.a&&t.push({setDependency:"aShadow",desiredValue:a.a}),{success:!0,instructions:t}}}if(3===t.numericalThroughPoints.length){let e,n=await s("a"),r=await s("b"),i=await s("c"),o=t.numericalThroughPoints[0][0],l=t.numericalThroughPoints[1][0],u=t.numericalThroughPoints[2][0],c=3;if(o===l?o===u?c=1:(c=2,e=3):o===u?(c=2,e=2):l===u&&(c=2,e=1),3===c){let e=[{setDependency:"numericalThroughPoints",desiredValue:[[o,n*o*o+r*o+i],[l,n*l*l+r*l+i],[u,n*u*u+r*u+i]]}];return void 0!==a.a&&e.push({setDependency:"aShadow",desiredValue:a.a}),{success:!0,instructions:e}}if(2===c){if(1===e){let e=n*l*l+r*l+i,t=[{setDependency:"numericalThroughPoints",desiredValue:[[o,n*o*o+r*o+i],[l,e],[l,e]]}];return void 0!==a.a&&t.push({setDependency:"aShadow",desiredValue:a.a}),{success:!0,instructions:t}}if(2===e){let e=n*o*o+r*o+i,t=[{setDependency:"numericalThroughPoints",desiredValue:[[o,e],[l,n*l*l+r*l+i],[o,e]]}];return void 0!==a.a&&t.push({setDependency:"aShadow",desiredValue:a.a}),{success:!0,instructions:t}}{let e=n*o*o+r*o+i,t=[{setDependency:"numericalThroughPoints",desiredValue:[[o,e],[o,e],[u,n*u*u+r*u+i]]}];return void 0!==a.a&&t.push({setDependency:"aShadow",desiredValue:a.a}),{success:!0,instructions:t}}}{o=-r/(2*n);let e=i-r*r/(4*n),t=[{setDependency:"numericalThroughPoints",desiredValue:[[o,e],[o,e],[o,e]]}];return void 0!==a.a&&t.push({setDependency:"aShadow",desiredValue:a.a}),{success:!0,instructions:t}}}return{success:!1}}},t.vertex={public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"vertexX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,entryPrefixes:["vertexX"],returnArraySizeDependencies:()=>({}),returnArraySize:()=>[2],returnArrayDependenciesByKey:()=>({globalDependencies:{a:{dependencyType:"stateVariable",variableName:"a"},b:{dependencyType:"stateVariable",variableName:"b"},c:{dependencyType:"stateVariable",variableName:"c"},realValued:{dependencyType:"stateVariable",variableName:"realValued"}}}),arrayDefinitionByKey:function({globalDependencyValues:e}){let t={};return e.realValued&&0!==e.a?(t[0]=me$3.fromAst(-e.b/(2*e.a)),t[1]=me$3.fromAst(e.c-e.b**2/(4*e.a))):(t[0]=me$3.fromAst("_"),t[1]=me$3.fromAst("_")),{setValue:{vertex:t}}},inverseArrayDefinitionByKey:async function({desiredStateVariableValues:e,globalDependencyValues:t,workspace:n,stateValues:r}){let a,i;if(a="0"in e.vertex?e.vertex[0].evaluate_to_constant():void 0!==n.x?n.x:(await r.vertex)[0].tree,!Number.isFinite(a))return{success:!1};if(n.x=a,i="1"in e.vertex?e.vertex[1].evaluate_to_constant():void 0!==n.y?n.y:(await r.vertex)[1].tree,!Number.isFinite(i))return{success:!1};n.y=i;let s=t.a;return{success:!0,instructions:[{setDependency:"b",desiredValue:-2*s*a,additionalDependencyValues:{c:i+s*a*a}}]}}},t.equation={public:!0,shadowingInstructions:{createComponentOfType:"math"},additionalProperties:{simplify:"numberspreserveorder",displaysmallaszero:!0},returnDependencies:()=>({a:{dependencyType:"stateVariable",variableName:"a"},b:{dependencyType:"stateVariable",variableName:"b"},c:{dependencyType:"stateVariable",variableName:"c"}}),definition:function({dependencyValues:e}){let t=["=","y",["+",["*",e.a,["^","x",2]],["*",e.b,"x"],e.c]];return{setValue:{equation:me$3.fromAst(t).evaluate_numbers({skip_ordering:!0})}}}},t.fs={forRenderer:!0,isArray:!0,entryPrefixes:["f"],additionalStateVariablesDefined:[{variableName:"fDefinitions",isArray:!0,forRenderer:!0}],returnArraySizeDependencies:()=>({}),returnArraySize:()=>[1],returnArrayDependenciesByKey:()=>({globalDependencies:{a:{dependencyType:"stateVariable",variableName:"a"},b:{dependencyType:"stateVariable",variableName:"b"},c:{dependencyType:"stateVariable",variableName:"c"}}}),arrayDefinitionByKey:({globalDependencyValues:e})=>({setValue:{fs:[function(t){return e.a*t*t+e.b*t+e.c}],fDefinitions:[{functionType:"formula",formula:["+",["*",e.a,"x","x"],["*",e.b,"x"],e.c],variables:["x"],nInputs:1,nOutputs:1,domain:null}]}})},t.f={isAlias:!0,targetVariableName:"f1"},t.nearestPoint={returnDependencies:()=>({f:{dependencyType:"stateVariable",variableName:"f"},a:{dependencyType:"stateVariable",variableName:"a"},b:{dependencyType:"stateVariable",variableName:"b"},c:{dependencyType:"stateVariable",variableName:"c"}}),definition({dependencyValues:e,componentName:t}){let n=!(Number.isFinite(e.a)&&Number.isFinite(e.b)&&Number.isFinite(e.c));return{setValue:{nearestPoint:function({variables:t,scales:r}){if(n)return{};let a=r[0],i=r[1],s=t.x1?.evaluate_to_constant(),o=t.x2?.evaluate_to_constant();if(!Number.isFinite(s)||!Number.isFinite(o))return{};s/=a,o/=i;let l=e.a*a*a/i,u=e.b*a/i,c=e.c/i;if(0===l){let e=u*u+1,n={};return n.x1=(s+u*o-u*c)/e*a,n.x2=(u*(s+u*o)+c)/e*i,void 0!==t.x3&&(n.x3=0),n}let p=c-o,d=2*l**2,m=cardano(3*l*u/d,(2*l*p+u**2+1)/d,(u*p-s)/d,1e-14),h=m[0],f=e.f(h*a)/i,y=(s-h)**2+(o-f)**2;for(let t of m.slice(1)){let n=t,r=e.f(n*a)/i,l=(s-n)**2+(o-r)**2;l0){const t=Math.sqrt(s/108),n=2*Math.sqrt(Math.cbrt(i*i/4+s/108)),r=Math.atan2(t,-i/2);return[Math.cos(r/3),Math.cos(r/3+2*Math.PI/3),Math.cos(r/3-2*Math.PI/3)].sort(((e,t)=>e-t)).map((t=>n*t-e/3))}const o=Math.sqrt(-s/108);return[Math.cbrt(-i/2+o)+Math.cbrt(-i/2-o)-e/3]}class BezierControls extends InlineComponent{static componentType="bezierControls";static rendererType="containerInline";static createAttributesObject(){let e=super.createAttributesObject();return e.alwaysVisible={createComponentOfType:"boolean",createStateVariable:"alwaysVisible",defaultValue:!1,public:!0},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e}){let t=breakEmbeddedStringsIntoParensPieces({componentList:e});return!0!==t.success?{success:!1}:{success:!0,newChildren:t.pieces.map((function(e){return e.length>1||"string"==typeof e[0]?{componentType:"controlVectors",children:[{componentType:"vector",children:e}]}:e[0]}))}}}),e}static returnChildGroups(){return[{group:"controlVectors",componentTypes:["controlVectors"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nControls={returnDependencies:()=>({nParentPoints:{dependencyType:"parentStateVariable",variableName:"nThroughPoints",skipComponentNames:!0}}),definition({dependencyValues:e}){let t=e.nParentPoints;return Number.isInteger(t)&&t>=0||(t=0),{setValue:{nControls:t}}}},e.pointIndMap={returnDependencies:()=>({controlChildren:{dependencyType:"child",childGroups:["controlVectors"],variableNames:["pointNumber"]}}),definition:function({dependencyValues:e}){let t=[],n=-1;for(let[r,a]of e.controlChildren.entries()){let e=a.stateValues.pointNumber;Number.isFinite(e)?n=Math.round(e)-1:n+=1,t[n]=r}return{setValue:{pointIndMap:t}}}},e.directions={isArray:!0,entryPrefixes:["direction"],hasEssential:!0,defaultValueByArrayKey:()=>"none",stateVariablesDeterminingDependencies:["pointIndMap"],returnArraySizeDependencies:()=>({nControls:{dependencyType:"stateVariable",variableName:"nControls"}}),returnArraySize:({dependencyValues:e})=>[e.nControls],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=t.pointIndMap[r];void 0!==e&&(n[r]={controlChild:{dependencyType:"child",childGroups:["controlVectors"],variableNames:["direction"],childIndices:[e]}})}return{dependenciesByKey:n}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={},r={};for(let a of t){let t=e[a].controlChild;t&&1===t.length?n[a]=t[0].stateValues.direction:r[a]=!0}return{setValue:{directions:n},useEssentialOrDefaultValue:{directions:r}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,dependencyValuesByKey:n}){let r=[],a={};for(let i in e.directions){let s=n[i].controlChild;s&&1===s.length?r.push({setDependency:t[i].controlChild,desiredValue:e.directions[i],childIndex:0,variableIndex:0}):a[i]=e.directions[i]}return Object.keys(a).length>0&&r.push({setEssentialValue:"directions",value:a}),{success:!0,instructions:r}}},e.hiddenControls={isArray:!0,entryPrefixes:["hiddenControl"],hasEssential:!0,defaultValueByArrayKey:()=>!1,stateVariablesDeterminingDependencies:["pointIndMap"],returnArraySizeDependencies:()=>({nControls:{dependencyType:"stateVariable",variableName:"nControls"}}),returnArraySize:({dependencyValues:e})=>[e.nControls],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=t.pointIndMap[r];void 0!==e&&(n[r]={controlChild:{dependencyType:"child",childGroups:["controlVectors"],variableNames:["hide"],childIndices:[e]}})}return{dependenciesByKey:n}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={},r={};for(let a of t){let t=e[a].controlChild;t&&1===t.length?n[a]=t[0].stateValues.hide:r[a]=!0}return{setValue:{hiddenControls:n},useEssentialOrDefaultValue:{hiddenControls:r}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,dependencyValuesByKey:n}){let r=[],a={};for(let i in e.hiddenControls){let s=n[i].controlChild;s&&1===s.length?r.push({setDependency:t[i].controlChild,desiredValue:e.hiddenControls[i],childIndex:0,variableIndex:0}):a[i]=e.hiddenControls[i]}return Object.keys(a).length>0&&r.push({setEssentialValue:"hiddenControls",value:a}),{success:!0,instructions:r}}},e.nDimensions={returnDependencies:()=>({nParentDimensions:{dependencyType:"parentStateVariable",variableName:"nDimensions"}}),definition:function({dependencyValues:e}){let t=e.nParentDimensions;return Number.isInteger(t)&&t>=0||(t=0),{setValue:{nDimensions:t},checkForActualChange:{nDimensions:!0}}}},e.essentialSymmetricControls={isArray:!0,entryPrefixes:["essentialSymmetricControl"],nDimensions:2,hasEssential:!0,defaultValueByArrayKey:()=>me$3.fromAst(1),returnArraySizeDependencies:()=>({nControls:{dependencyType:"stateVariable",variableName:"nControls"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nControls,e.nDimensions],returnArrayDependenciesByKey:()=>({}),arrayDefinitionByKey({arrayKeys:e}){let t={};for(let n of e)n.split(",").map((e=>Number(e))),t[n]=!0;return{useEssentialOrDefaultValue:{essentialSymmetricControls:t}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e}){let t=[],n={};for(let t in e.essentialSymmetricControls)n[t]=e.essentialSymmetricControls[t];return Object.keys(n).length>0&&t.push({setEssentialValue:"essentialSymmetricControls",value:n}),{success:!0,instructions:t}}},e.controls={isArray:!0,entryPrefixes:["control"],nDimensions:3,hasEssential:!0,shadowVariable:!0,defaultValueByArrayKey:()=>me$3.fromAst(1),stateVariablesDeterminingDependencies:["pointIndMap","directions"],returnArraySizeDependencies:()=>({nControls:{dependencyType:"stateVariable",variableName:"nControls"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nControls,2,e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=r.split(",").map((e=>Number(e))),a=e.map((e=>e+1));n[r]={direction:{dependencyType:"stateVariable",variableName:"direction"+a[0]}};let i=t.directions[e[0]];if("none"!==i&&(0===e[1]||1===e[1])){let s=t.pointIndMap[e[0]];void 0!==s&&("symmetric"===i||"previous"===i&&0===e[1]||"next"===i&&1===e[1]?n[r].controlChild={dependencyType:"child",childGroups:["controlVectors"],variableNames:["vectorX1_"+a[2]],childIndices:[s]}:"both"===i&&(n[r].controlChild={dependencyType:"child",childGroups:["controlVectors"],variableNames:["vectorX"+a[1]+"_"+a[2]],childIndices:[s]})),"symmetric"===i&&(n[r].essentialSymmetricControl={dependencyType:"stateVariable",variableName:"essentialSymmetricControl"+a[0]+"_"+a[2]})}}return{dependenciesByKey:n}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t,componentName:n}){let r={},a={};for(let n of t){let t=n.split(",").map((e=>Number(e))),i=t.map((e=>e+1)),s=e[n].direction;if(0===t[1])if("none"===s||"next"===s)r[n]=null;else{let t=e[n].controlChild,o=!0;if(t&&1===t.length){let e=t[0].stateValues["vectorX1_"+i[2]];e&&(o=!1,e=e.evaluate_to_constant(),Number.isFinite(e)||(e=NaN),r[n]=me$3.fromAst(e))}o&&("symmetric"===s?r[n]=e[n].essentialSymmetricControl:a[n]=!0)}else if(1===t[1])if("none"===s||"previous"===s)r[n]=null;else{let t=e[n].controlChild,o=!0;if(t&&1===t.length)if("both"===s){let e=t[0].stateValues["vectorX2_"+i[2]];e&&(o=!1,e=e.evaluate_to_constant(),Number.isFinite(e)||(e=NaN),r[n]=me$3.fromAst(e))}else{let e=t[0].stateValues["vectorX1_"+i[2]];e&&(o=!1,e=e.evaluate_to_constant(),Number.isFinite(e)||(e=NaN),r[n]="symmetric"===s?me$3.fromAst(-e):me$3.fromAst(e))}o&&("symmetric"===s?e[n].essentialSymmetricControl&&(r[n]=me$3.fromAst(-e[n].essentialSymmetricControl.tree)):a[n]=!0)}}return{setValue:{controls:r},useEssentialOrDefaultValue:{controls:a}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,dependencyValuesByKey:n}){let r=[],a={};for(let i in e.controls){let s=i.split(",").map((e=>Number(e))),o=s.map((e=>e+1)),l=n[i].direction;if(l)if(0===s[1]){if("none"!==l&&"next"!==l){let s=n[i].controlChild,u=!0;if(s&&1===s.length){s[0].stateValues["vectorX1_"+o[2]]&&(u=!1,r.push({setDependency:t[i].controlChild,desiredValue:e.controls[i],childIndex:0,variableIndex:0}))}if(u){let n=e.controls[i].evaluate_to_constant();Number.isFinite(n)||(n=NaN),n=me$3.fromAst(n),"symmetric"===l?r.push({setDependency:t[i].essentialSymmetricControl,desiredValue:n}):a[i]=n}}}else if(1===s[1]&&"none"!==l&&"previous"!==l){let s,u=n[i].controlChild,c=!0;if(u&&1===u.length)if("both"===l){u[0].stateValues["vectorX2_"+o[2]]&&(c=!1)}else{u[0].stateValues["vectorX1_"+o[2]]&&(c=!1)}s="symmetric"===l?me$3.fromAst(["-",e.controls[i].tree]):e.controls[i],c?(s=s.evaluate_to_constant(),Number.isFinite(s)||(s=NaN),s=me$3.fromAst(s),"symmetric"===l?r.push({setDependency:t[i].essentialSymmetricControl,desiredValue:s}):a[i]=s):r.push({setDependency:t[i].controlChild,desiredValue:s,childIndex:0,variableIndex:0})}}return Object.keys(a).length>0&&r.push({setEssentialValue:"controls",value:a}),{success:!0,instructions:r}}},e}}class VectorListComponent extends BaseComponent{static componentType="_vectorListComponent";static rendererType="containerInline";static renderChildren=!0;static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e}){let t=breakEmbeddedStringsIntoParensPieces({componentList:e});return!0!==t.success?{success:!1}:{success:!0,newChildren:t.pieces.map((function(e){return e.length>1||"string"==typeof e[0]?{componentType:"vector",children:e}:e[0]}))}}}),e}static returnChildGroups(){return[{group:"vectors",componentTypes:["vector"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nVectors={returnDependencies:()=>({vectorChildren:{dependencyType:"child",childGroups:["vectors"],skipComponentNames:!0}}),definition:({dependencyValues:e})=>({setValue:{nVectors:e.vectorChildren.length},checkForActualChange:{nVectors:!0}})},e.nDimensions={returnDependencies:()=>({vectorChildren:{dependencyType:"child",childGroups:["vectors"],variableNames:["nDimensions"],skipPlaceholders:!0}}),definition:function({dependencyValues:e}){let t;if(0===e.vectorChildren.length)t=2;else{t=1;for(let n of e.vectorChildren)Number.isFinite(n.stateValues.nDimensions)&&(t=Math.max(t,n.stateValues.nDimensions))}return{setValue:{nDimensions:t},checkForActualChange:{nDimensions:!0}}}},e.vectors={isArray:!0,nDimensions:2,entryPrefixes:["vectorX","vector"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("vectorX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("vectors"===t)return 1===e.length?"vector"+e[0]:`vectorX${e[0]}_${e[1]}`;if("vector"===t.slice(0,6)){let n=Number(t.slice(6));if(Number.isInteger(n)&&n>0)return`vectorX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nVectors:{dependencyType:"stateVariable",variableName:"nVectors"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nVectors,e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let[e,r]=n.split(",");t[n]={vectorChild:{dependencyType:"child",childGroups:["vectors"],variableNames:["x"+(Number(r)+1)],childIndices:[e]}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=r.split(",")[1],a=e[r].vectorChild[0];a&&(n[r]=a.stateValues["x"+(Number(t)+1)])}return{setValue:{vectors:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t}){let n=[];for(let r in e.vectors)n.push({setDependency:t[r].vectorChild,desiredValue:e.vectors[r],childIndex:0,variableIndex:0});return{success:!0,instructions:n}}},e}}class ControlVectors extends VectorListComponent{static componentType="controlVectors";static createAttributesObject(){let e=super.createAttributesObject();return e.direction={createComponentOfType:"text",createStateVariable:"direction",defaultValue:"symmetric",public:!0,toLowerCase:!0,validValues:["symmetric","previous","next","both","none"]},e.pointNumber={createComponentOfType:"number",createStateVariable:"pointNumber",defaultValue:null,public:!0},e}}class PointListComponent extends BaseComponent{static componentType="_pointListComponent";static rendererType="containerInline";static renderChildren=!0;static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e}){let t=breakEmbeddedStringsIntoParensPieces({componentList:e});return!0!==t.success?{success:!1}:{success:!0,newChildren:t.pieces.map((function(e){return e.length>1||"string"==typeof e[0]?{componentType:"point",children:e}:e[0]}))}}}),e}static returnChildGroups(){return[{group:"points",componentTypes:["point"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nPoints={returnDependencies:()=>({pointChildren:{dependencyType:"child",childGroups:["points"],skipComponentNames:!0}}),definition:function({dependencyValues:e}){return{setValue:{nPoints:e.pointChildren.length},checkForActualChange:{nPoints:!0}}}},e.nDimensions={returnDependencies:()=>({pointChildren:{dependencyType:"child",childGroups:["points"],variableNames:["nDimensions"],skipPlaceholders:!0}}),definition:function({dependencyValues:e}){let t;if(0===e.pointChildren.length)t=2;else{t=1;for(let n of e.pointChildren)Number.isFinite(n.stateValues.nDimensions)&&(t=Math.max(t,n.stateValues.nDimensions))}return{setValue:{nDimensions:t},checkForActualChange:{nDimensions:!0}}}},e.points={isArray:!0,nDimensions:2,entryPrefixes:["pointX","point"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("pointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("points"===t)return 1===e.length?"point"+e[0]:`pointX${e[0]}_${e[1]}`;if("point"===t.slice(0,5)){let n=Number(t.slice(5));if(Number.isInteger(n)&&n>0)return`pointX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nPoints:{dependencyType:"stateVariable",variableName:"nPoints"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nPoints,e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let[e,r]=n.split(",");t[n]={pointChild:{dependencyType:"child",childGroups:["points"],variableNames:["x"+(Number(r)+1)],childIndices:[e]}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=r.split(",")[1],a=e[r].pointChild[0];a&&(n[r]=a.stateValues["x"+(Number(t)+1)])}return{setValue:{points:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t}){let n=[];for(let r in e.points)n.push({setDependency:t[r].pointChild,desiredValue:e.points[r],childIndex:0,variableIndex:0});return{success:!0,instructions:n}}},e}}class IntervalListComponent extends BaseComponent{static componentType="_intervalListComponent";static rendererType="containerInline";static renderChildren=!0;static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e}){let t=breakEmbeddedStringsIntoIntervalPieces({componentList:e});return!0!==t.success?{success:!1}:{success:!0,newChildren:t.pieces.map((function(e){return e.length>1||"string"==typeof e[0]?{componentType:"interval",children:e}:e[0]}))}}}),e}static returnChildGroups(){return[{group:"intervals",componentTypes:["interval"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nIntervals={returnDependencies:()=>({intervalChildren:{dependencyType:"child",childGroups:["intervals"],skipComponentNames:!0}}),definition:function({dependencyValues:e}){return{setValue:{nIntervals:e.intervalChildren.length},checkForActualChange:{nIntervals:!0}}}},e.intervals={isArray:!0,nDimensions:1,entryPrefixes:["interval"],returnArraySizeDependencies:()=>({nIntervals:{dependencyType:"stateVariable",variableName:"nIntervals"}}),returnArraySize:({dependencyValues:e})=>[e.nIntervals],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={intervalChild:{dependencyType:"child",childGroups:["intervals"],variableNames:["value"],childIndices:[n]}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].intervalChild[0];t&&(n[r]=t.stateValues.value)}return{setValue:{intervals:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t}){let n=[];for(let r in e.intervals)n.push({setDependency:t[r].intervalChild,desiredValue:e.intervals[r],childIndex:0,variableIndex:0});return{success:!0,instructions:n}}},e}}function breakEmbeddedStringsIntoIntervalPieces({componentList:e}){let t=0,n=[],r=[];for(let a of e){if("string"!=typeof a){if(0===t)return{success:!1};r.push(a);continue}let e=a.trim(),i=0;for(let a=0;ai){let t=a+1,n=e.substring(i,t).trim();n.length>0&&r.push(n)}n.push(r),r=[],i=a+1}t--}else if(0===t&&!s.match(/\s/))return{success:!1}}if(e.length>i){let t=e.substring(i,e.length).trim();r.push(t)}}return 0!==t||r.length>0?{success:!1}:{success:!0,pieces:n}}class LineListComponent extends BaseComponent{static componentType="_lineListComponent";static rendererType="containerInline";static renderChildren=!0;static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e}){let t=e.reduce((function(e,t){return"string"==typeof t?[...e,...t.split(/\s+/).filter((e=>e)).map((e=>({componentType:"line",children:[e]})))]:[...e,t]}),[]);return{success:!0,newChildren:t}}}),e}static returnChildGroups(){return[{group:"lines",componentTypes:["line"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nLines={returnDependencies:()=>({lineChildren:{dependencyType:"child",childGroups:["lines"],skipComponentNames:!0}}),definition:function({dependencyValues:e}){return{setValue:{nLines:e.lineChildren.length},checkForActualChange:{nLines:!0}}}},e.lineNames={isArray:!0,entryPrefixes:["lineName"],returnArraySizeDependencies:()=>({nLines:{dependencyType:"stateVariable",variableName:"nLines"}}),returnArraySize:({dependencyValues:e})=>[e.nLines],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={lineChild:{dependencyType:"child",childGroups:["lines"],childIndices:[n]}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].lineChild[0];t&&(n[r]=t.componentName)}return{setValue:{lineNames:n}}}},e}}class AngleListComponent extends BaseComponent{static componentType="_angleListComponent";static createAttributesObject(){let e=super.createAttributesObject();return e.hide={default:!0},e}static returnChildLogic(e){let t=super.returnChildLogic(e),n=t.newLeaf({name:"AtLeastZeroAngles",componentType:"angle",comparison:"atLeast",number:0}),r=breakStringsAndOthersIntoComponentsByStringCommas(),a=t.newLeaf({name:"AtLeastOneString",componentType:"string",comparison:"atLeast",number:1}),i=t.newLeaf({name:"AtLeastOneMath",componentType:"math",comparison:"atLeast",number:1}),s=t.newOperator({name:"StringsAndMaths",operator:"or",propositions:[a,i],requireConsecutive:!0,isSugar:!0,replacementFunction:r});return t.newOperator({name:"AnglesXorSugar",operator:"xor",propositions:[n,s],setAsBase:!0}),t}updateState(e={}){if(e.init&&(this._state.angles={trackChanges:!0}),super.updateState(e),!this.childLogicSatisfied)return this.unresolvedState.angles=!0,void(this.unresolvedState.nAngles=!0);if(this.currentTracker.trackChanges.childrenChanged(this.componentName)){delete this.unresolvedState.angles,delete this.unresolvedState.nAngles;let e=this.childLogic.returnMatches("AtLeastZeroAngles");this.state.nAngles=e.length,this.state.angles=e.map((e=>this.activeChildren[e]))}}initializeRenderer(){void 0===this.renderer&&(this.renderer=new this.availableRenderers.container({key:this.componentName}))}updateChildrenWhoRender(){this.childrenWhoRender=this.state.angles.map((e=>e.componentName))}}class Vector extends GraphicalComponent{constructor(e){super(e),Object.assign(this.actions,{moveVector:this.moveVector.bind(this),vectorClicked:this.vectorClicked.bind(this),mouseDownOnVector:this.mouseDownOnVector.bind(this)})}static componentType="vector";static primaryStateVariableForDefinition="displacementShadow";static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.headDraggable={createComponentOfType:"boolean"},e.tailDraggable={createComponentOfType:"boolean"},e.x={createComponentOfType:"math"},e.y={createComponentOfType:"math"},e.z={createComponentOfType:"math"},e.xs={createComponentOfType:"mathList"},e.displacement={createComponentOfType:"vector"},e.head={createComponentOfType:"point"},e.tail={createComponentOfType:"point"},e.displayDigits={createComponentOfType:"integer",createStateVariable:"displayDigits",defaultValue:10,public:!0},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.padZeros={createComponentOfType:"boolean",createStateVariable:"padZeros",defaultValue:!1,public:!0},e.displayWithAngleBrackets={createComponentOfType:"boolean",createStateVariable:"displayWithAngleBrackets",defaultValue:!1,public:!0},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e,componentInfoObjects:t}){let n=returnBreakStringsSugarFunction({childrenToComponentFunction:e=>({componentType:"math",children:e}),mustStripOffOuterParentheses:!0}),r=e.map((e=>typeof e)),a=r.indexOf("string"),i=r.lastIndexOf("string");if(-1===a){let n=t.componentIsSpecifiedType,r=e.filter((e=>!(n(e,"point")||n(e,"vector")||n(e,"label"))));if(1===r.length){let t=r[0],n=e.indexOf(t);return{success:!0,newAttributes:{displacement:{component:{componentType:"math",children:r}}},newChildren:[...e.slice(0,n),...e.slice(n+1)]}}return{success:!1}}let s=[...e.slice(0,a),...e.slice(i+1)],o=n({matchedChildren:e=e.slice(a,i+1)});return o.success||1!==e.length?o.success?{success:!0,newAttributes:{xs:{component:{componentType:"mathList",children:o.newChildren,skipSugar:!0}}},newChildren:s}:{success:!1}:{success:!0,newAttributes:{x:{component:{componentType:"math",children:e}}},newChildren:s}}}),e}static returnChildGroups(){let e=super.returnChildGroups();return e.push({group:"points",componentTypes:["point"]},{group:"vectors",componentTypes:["vector"]}),e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){let t=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(t&&(t+=" "),t+=e.selectedStyle.lineStyleWord),t&&(t+=" "),t+=e.selectedStyle.lineColorWord,{setValue:{styleDescription:t}}}},e.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({styleDescription:{dependencyType:"stateVariable",variableName:"styleDescription"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescriptionWithNoun:e.styleDescription+" vector"}}}},e.tailDraggable={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},hasEssential:!0,forRenderer:!0,returnDependencies:()=>({tailDraggableAttr:{dependencyType:"attributeComponent",attributeName:"tailDraggable",variableNames:["value"]},draggable:{dependencyType:"stateVariable",variableName:"draggable"}}),definition:({dependencyValues:e})=>e.tailDraggableAttr?{setValue:{tailDraggable:e.tailDraggableAttr.stateValues.value}}:{useEssentialOrDefaultValue:{tailDraggable:{defaultValue:e.draggable}}}},e.headDraggable={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},hasEssential:!0,forRenderer:!0,returnDependencies:()=>({headDraggableAttr:{dependencyType:"attributeComponent",attributeName:"headDraggable",variableNames:["value"]},draggable:{dependencyType:"stateVariable",variableName:"draggable"}}),definition:({dependencyValues:e})=>e.headDraggableAttr?{setValue:{headDraggable:e.headDraggableAttr.stateValues.value}}:{useEssentialOrDefaultValue:{headDraggable:{defaultValue:e.draggable}}}},e.displacementShadow={defaultValue:null,hasEssential:!0,essentialVarName:"displacement",set:convertValueToMathExpression,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{displacementShadow:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"displacementShadow",value:convertValueToMathExpression(e.displacementShadow)}]}}},e.headShadow={defaultValue:null,hasEssential:!0,essentialVarName:"head",set:convertValueToMathExpression,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{headShadow:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"headShadow",value:convertValueToMathExpression(e.headShadow)}]}}},e.tailShadow={defaultValue:null,hasEssential:!0,essentialVarName:"tail",set:convertValueToMathExpression,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{tailShadow:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"tailShadow",value:convertValueToMathExpression(e.tailShadow)}]}}},e.sourceOfDisplacement={returnDependencies:()=>({xAttr:{dependencyType:"attributeComponent",attributeName:"x"},yAttr:{dependencyType:"attributeComponent",attributeName:"y"},zAttr:{dependencyType:"attributeComponent",attributeName:"z"},xsAttr:{dependencyType:"attributeComponent",attributeName:"xs"},displacementAttr:{dependencyType:"attributeComponent",attributeName:"displacement"},pointChild:{dependencyType:"child",childGroups:["points"]},vectorChild:{dependencyType:"child",childGroups:["vectors"]}}),definition({dependencyValues:e}){let t=null;return e.vectorChild.length>0?t="vectorChild":e.pointChild.length>0?t="pointChild":null!==e.displacementAttr?t="displacementAttr":null!==e.xsAttr?t="xsAttr":null===e.xAttr&&null===e.yAttr&&null===e.zAttr||(t="componentAttrs"),{setValue:{sourceOfDisplacement:t}}}},e.basedOnHead={returnDependencies:()=>({headAttr:{dependencyType:"attributeComponent",attributeName:"head"},headShadow:{dependencyType:"stateVariable",variableName:"headShadow"},tailAttr:{dependencyType:"attributeComponent",attributeName:"tail"},sourceOfDisplacement:{dependencyType:"stateVariable",variableName:"sourceOfDisplacement"}}),definition:function({dependencyValues:e}){return null!==e.tailAttr&&null!==e.sourceOfDisplacement?(null!==e.headAttr&&console.warn("Vector is prescribed by head, tail, and displacement. Ignoring specified head."),{setValue:{basedOnHead:!1},checkForActualChange:{basedOnHead:!0}}):null!==e.headAttr?{setValue:{basedOnHead:!0},checkForActualChange:{basedOnHead:!0}}:{setValue:{basedOnHead:null!==e.headShadow},checkForActualChange:{basedOnHead:!0}}}},e.basedOnTail={returnDependencies:()=>({tailAttr:{dependencyType:"attributeComponent",attributeName:"tail"},tailShadow:{dependencyType:"stateVariable",variableName:"tailShadow"}}),definition:function({dependencyValues:e}){return null!==e.tailAttr?{setValue:{basedOnTail:!0},checkForActualChange:{basedOnTail:!0}}:{setValue:{basedOnTail:null!==e.tailShadow},checkForActualChange:{basedOnTail:!0}}}},e.basedOnDisplacement={returnDependencies:()=>({sourceOfDisplacement:{dependencyType:"stateVariable",variableName:"sourceOfDisplacement"},displacementShadow:{dependencyType:"stateVariable",variableName:"displacementShadow"}}),definition:function({dependencyValues:e}){return null!==e.sourceOfDisplacement?{setValue:{basedOnDisplacement:!0},checkForActualChange:{basedOnDisplacement:!0}}:{setValue:{basedOnDisplacement:null!==e.displacementShadow},checkForActualChange:{basedOnDisplacement:!0}}}},e.nDimDisplacement={stateVariablesDeterminingDependencies:["basedOnDisplacement","basedOnHead","basedOnTail"],returnDependencies({stateValues:e}){let t={basedOnHead:{dependencyType:"stateVariable",variableName:"basedOnHead"},basedOnTail:{dependencyType:"stateVariable",variableName:"basedOnTail"},basedOnDisplacement:{dependencyType:"stateVariable",variableName:"basedOnDisplacement"},sourceOfDisplacement:{dependencyType:"stateVariable",variableName:"sourceOfDisplacement"},displacementShadow:{dependencyType:"stateVariable",variableName:"displacementShadow"},displacementAttr:{dependencyType:"attributeComponent",attributeName:"displacement",variableNames:["nDimensions"]},vectorChild:{dependencyType:"child",childGroups:["vectors"],variableNames:["nDimensions"]},pointChild:{dependencyType:"child",childGroups:["points"],variableNames:["nDimensions"]},xAttr:{dependencyType:"attributeComponent",attributeName:"x"},yAttr:{dependencyType:"attributeComponent",attributeName:"y"},zAttr:{dependencyType:"attributeComponent",attributeName:"z"},xsAttr:{dependencyType:"attributeComponent",attributeName:"xs",variableNames:["nComponents"]}};return e.basedOnDisplacement||(e.basedOnHead&&(t.nDimHead={dependencyType:"stateVariable",variableName:"nDimHead"}),e.basedOnTail&&(t.nDimTail={dependencyType:"stateVariable",variableName:"nDimTail"})),t},definition:function({dependencyValues:e}){let t;if(e.basedOnDisplacement)switch(e.sourceOfDisplacement){case"vectorChild":t=e.vectorChild[0].stateValues.nDimensions;break;case"pointChild":t=e.pointChild[0].stateValues.nDimensions;break;case"displacementAttr":t=e.displacementAttr.stateValues.nDimensions;break;case"xsAttr":t=e.xsAttr.stateValues.nComponents;break;case"componentAttrs":t=null!==e.zAttr?3:null!==e.yAttr?2:1;break;default:let n=e.displacementShadow.tree;t=Array.isArray(n)&&vectorOperators.includes(n[0])?n.length-1:1}else t=e.basedOnHead?e.basedOnTail?e.nDimHead===e.nDimTail?e.nDimHead:NaN:e.nDimHead:e.basedOnTail?e.nDimTail:2;return{setValue:{nDimDisplacement:t},checkForActualChange:{nDimDisplacement:!0}}}},e.nDimHead={stateVariablesDeterminingDependencies:["basedOnDisplacement","basedOnHead","basedOnTail"],returnDependencies({stateValues:e}){let t={basedOnHead:{dependencyType:"stateVariable",variableName:"basedOnHead"},basedOnTail:{dependencyType:"stateVariable",variableName:"basedOnTail"},basedOnDisplacement:{dependencyType:"stateVariable",variableName:"basedOnDisplacement"},headShadow:{dependencyType:"stateVariable",variableName:"headShadow"},headAttr:{dependencyType:"attributeComponent",attributeName:"head",variableNames:["nDimensions"]}};return e.basedOnHead||(e.basedOnTail&&(t.nDimTail={dependencyType:"stateVariable",variableName:"nDimTail"}),e.basedOnDisplacement&&(t.nDimDisplacement={dependencyType:"stateVariable",variableName:"nDimDisplacement"})),t},definition:function({dependencyValues:e}){let t;if(e.basedOnHead){if(null!==e.headAttr)t=e.headAttr.stateValues.nDimensions;else if(e.headShadow){let n=e.headShadow.tree;t=Array.isArray(n)&&vectorOperators.includes(n[0])?n.length-1:2}}else t=e.basedOnDisplacement?e.basedOnTail?e.nDimDisplacement===e.nDimTail?e.nDimDisplacement:NaN:e.nDimDisplacement:e.basedOnTail?e.nDimTail:2;return{setValue:{nDimHead:t},checkForActualChange:{nDimHead:!0}}}},e.nDimTail={stateVariablesDeterminingDependencies:["basedOnDisplacement","basedOnHead","basedOnTail"],returnDependencies({stateValues:e}){let t={basedOnHead:{dependencyType:"stateVariable",variableName:"basedOnHead"},basedOnTail:{dependencyType:"stateVariable",variableName:"basedOnTail"},basedOnDisplacement:{dependencyType:"stateVariable",variableName:"basedOnDisplacement"},tailShadow:{dependencyType:"stateVariable",variableName:"tailShadow"},tailAttr:{dependencyType:"attributeComponent",attributeName:"tail",variableNames:["nDimensions"]}};return e.basedOnTail||(e.basedOnHead&&(t.nDimHead={dependencyType:"stateVariable",variableName:"nDimHead"}),e.basedOnDisplacement&&(t.nDimDisplacement={dependencyType:"stateVariable",variableName:"nDimDisplacement"})),t},definition:function({dependencyValues:e}){let t;if(e.basedOnTail){if(null!==e.tailAttr)t=e.tailAttr.stateValues.nDimensions;else if(e.tailShadow){let n=e.tailShadow.tree;t=Array.isArray(n)&&vectorOperators.includes(n[0])?n.length-1:2}}else t=e.basedOnDisplacement?e.basedOnHead?e.nDimDisplacement===e.nDimHead?e.nDimDisplacement:NaN:e.nDimDisplacement:e.basedOnHead?e.nDimHead:2;return{setValue:{nDimTail:t},checkForActualChange:{nDimTail:!0}}}},e.nDimensions={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({basedOnHead:{dependencyType:"stateVariable",variableName:"basedOnHead"},basedOnTail:{dependencyType:"stateVariable",variableName:"basedOnTail"},basedOnDisplacement:{dependencyType:"stateVariable",variableName:"basedOnDisplacement"},nDimDisplacement:{dependencyType:"stateVariable",variableName:"nDimDisplacement"},nDimHead:{dependencyType:"stateVariable",variableName:"nDimHead"},nDimTail:{dependencyType:"stateVariable",variableName:"nDimTail"}}),definition:function({dependencyValues:e}){let t;if(e.basedOnDisplacement){if(e.basedOnTail){if(e.nDimDisplacement!==e.nDimTail)return console.warn("nDimensions mismatch in vector"),{setValue:{nDimensions:NaN}}}else if(e.basedOnHead&&e.nDimDisplacement!==e.nDimHead)return console.warn("nDimensions mismatch in vector"),{setValue:{nDimensions:NaN}};t=e.nDimDisplacement}else if(e.basedOnTail){if(e.basedOnHead&&e.nDimTail!==e.nDimHead)return console.warn("nDimensions mismatch in vector"),{setValue:{nDimensions:NaN}};t=e.nDimTail}else t=e.basedOnHead?e.nDimHead:2;return{setValue:{nDimensions:t},checkForActualChange:{nDimensions:!0}}}},e.displacement={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros","displayWithAngleBrackets"],returnWrappingComponents:e=>"x"===e?[]:[["vector",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,entryPrefixes:["x"],hasEssential:!0,essentialVarName:"displacement2",set:convertValueToMathExpression,stateVariablesDeterminingDependencies:["basedOnDisplacement","basedOnHead","sourceOfDisplacement"],returnArraySizeDependencies:()=>({nDimDisplacement:{dependencyType:"stateVariable",variableName:"nDimDisplacement"}}),returnArraySize:({dependencyValues:e})=>[e.nDimDisplacement],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=Number(r)+1;n[r]={xsAttr:{dependencyType:"attributeComponent",attributeName:"xs",variableNames:["math"+e]},displacementAttr:{dependencyType:"attributeComponent",attributeName:"displacement",variableNames:["x"+e]},pointChild:{dependencyType:"child",childGroups:["points"],variableNames:["x"+e]},vectorChild:{dependencyType:"child",childGroups:["vectors"],variableNames:["x"+e]}},"0"===r?n[r].componentAttr={dependencyType:"attributeComponent",attributeName:"x",variableNames:["value"]}:"1"===r?n[r].componentAttr={dependencyType:"attributeComponent",attributeName:"y",variableNames:["value"]}:"2"===r&&(n[r].componentAttr={dependencyType:"attributeComponent",attributeName:"z",variableNames:["value"]}),!t.basedOnDisplacement&&t.basedOnHead&&(n[r].tailX={dependencyType:"stateVariable",variableName:"tailX"+e},n[r].headX={dependencyType:"stateVariable",variableName:"headX"+e})}return{globalDependencies:{basedOnHead:{dependencyType:"stateVariable",variableName:"basedOnHead"},basedOnTail:{dependencyType:"stateVariable",variableName:"basedOnTail"},basedOnDisplacement:{dependencyType:"stateVariable",variableName:"basedOnDisplacement"},displacementShadow:{dependencyType:"stateVariable",variableName:"displacementShadow"},sourceOfDisplacement:{dependencyType:"stateVariable",variableName:"sourceOfDisplacement"}},dependenciesByKey:n}},arrayDefinitionByKey:function({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={},a={};for(let i of n){let n=Number(i)+1;if(e.basedOnDisplacement)switch(e.sourceOfDisplacement){case"vectorChild":r[i]=t[i].vectorChild[0].stateValues["x"+n];break;case"pointChild":r[i]=t[i].pointChild[0].stateValues["x"+n];break;case"displacementAttr":r[i]=t[i].displacementAttr.stateValues["x"+n];break;case"xsAttr":r[i]=t[i].xsAttr.stateValues["math"+n].simplify();break;case"componentAttrs":let s=t[i].componentAttr;null===s?a[i]={defaultValue:me$3.fromAst(0)}:r[i]=s.stateValues.value.simplify();break;default:let o=e.displacementShadow.tree;Array.isArray(o)&&vectorOperators.includes(o[0])?r[i]=e.displacementShadow.get_component(Number(i)):r[i]=e.displacementShadow}else e.basedOnHead?r[i]=t[i].headX.subtract(t[i].tailX).simplify():a[i]={defaultValue:me$3.fromAst("0"===i?1:0)}}let i={};return Object.keys(r).length>0&&(i.setValue={displacement:r}),Object.keys(a).length>0&&(i.useEssentialOrDefaultValue={displacement:a}),i},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i=[],s=!1;for(let a in e.displacement)if(t.basedOnDisplacement)switch(t.sourceOfDisplacement){case"vectorChild":i.push({setDependency:r[a].vectorChild,desiredValue:e.displacement[a],childIndex:0,variableIndex:0});break;case"pointChild":i.push({setDependency:r[a].pointChild,desiredValue:e.displacement[a],childIndex:0,variableIndex:0});break;case"displacementAttr":i.push({setDependency:r[a].displacementAttr,desiredValue:e.displacement[a],variableIndex:0});break;case"xsAttr":i.push({setDependency:r[a].xsAttr,desiredValue:e.displacement[a],variableIndex:0});break;case"componentAttrs":null===n[a].componentAttr?i.push({setEssentialValue:"displacement",value:{[a]:convertValueToMathExpression(e.displacement[a])}}):i.push({setDependency:r[a].componentAttr,desiredValue:e.displacement[a],variableIndex:0});break;default:s=!0}else t.basedOnHead?i.push({setDependency:r[a].headX,desiredValue:n[a].tailX.add(e.displacement[a]).simplify()}):i.push({setEssentialValue:"displacement",value:{[a]:convertValueToMathExpression(e.displacement[a])}});if(s)if(a[0]>1){let t=["vector"];for(let n in e.displacement)t[Number(n)+1]=e.displacement[n].tree;t.length=a[0]+1,i.push({setDependency:"displacementShadow",desiredValue:me$3.fromAst(t)})}else 1===a[0]&&"0"in e.displacement&&i.push({setDependency:"displacementShadow",desiredValue:e.displacement[0]});return{success:!0,instructions:i}}},e.x={isAlias:!0,targetVariableName:"x1"},e.y={isAlias:!0,targetVariableName:"x2"},e.z={isAlias:!0,targetVariableName:"x3"},e.head={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"],returnWrappingComponents:e=>"headX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,entryPrefixes:["headX"],set:convertValueToMathExpression,stateVariablesDeterminingDependencies:["basedOnHead"],returnArraySizeDependencies:()=>({nDimHead:{dependencyType:"stateVariable",variableName:"nDimHead"}}),returnArraySize:({dependencyValues:e})=>[e.nDimHead],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=Number(r)+1;n[r]={headAttr:{dependencyType:"attributeComponent",attributeName:"head",variableNames:["x"+e]}},t.basedOnHead||(n[r].tailX={dependencyType:"stateVariable",variableName:"tailX"+e},n[r].x={dependencyType:"stateVariable",variableName:"x"+e})}return{globalDependencies:{basedOnDisplacement:{dependencyType:"stateVariable",variableName:"basedOnDisplacement"},basedOnTail:{dependencyType:"stateVariable",variableName:"basedOnTail"},basedOnHead:{dependencyType:"stateVariable",variableName:"basedOnHead"},headShadow:{dependencyType:"stateVariable",variableName:"headShadow"}},dependenciesByKey:n}},arrayDefinitionByKey:function({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};for(let a of n){let n=Number(a)+1;e.basedOnHead?null!==t[a].headAttr?r[a]=t[a].headAttr.stateValues["x"+n]:null!==e.headShadow&&(r[a]=e.headShadow.get_component(Number(a))):r[a]=t[a].tailX.add(t[a].x).simplify()}return{setValue:{head:r}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i=[],s=!1;for(let a in e.head)t.basedOnHead?n[a].headAttr&&null!==n[a].headAttr?i.push({setDependency:r[a].headAttr,desiredValue:e.head[a],variableIndex:0}):null!==t.headShadow&&(s=!0):i.push({setDependency:r[a].x,desiredValue:e.head[a].subtract(n[a].tailX).simplify()});if(s)if(a[0]>1){let t=["vector"];for(let n in e.head)t[Number(n)+1]=e.head[n].tree;t.length=a[0]+1,i.push({setDependency:"headShadow",desiredValue:me$3.fromAst(t)})}else 1===a[0]&&"0"in e.head&&i.push({setDependency:"headShadow",desiredValue:e.head[0]});return{success:!0,instructions:i}}},e.tail={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"],returnWrappingComponents:e=>"tailX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,entryPrefixes:["tailX"],hasEssential:!0,defaultValueByArrayKey:()=>me$3.fromAst(0),essentialVarName:"tail2",set:convertValueToMathExpression,stateVariablesDeterminingDependencies:["basedOnTail","basedOnHead","basedOnDisplacement"],returnArraySizeDependencies:()=>({nDimTail:{dependencyType:"stateVariable",variableName:"nDimTail"}}),returnArraySize:({dependencyValues:e})=>[e.nDimTail],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=Number(r)+1;n[r]={tailAttr:{dependencyType:"attributeComponent",attributeName:"tail",variableNames:["x"+e]}},t.basedOnTail||t.basedOnHead&&t.basedOnDisplacement&&(n[r].headX={dependencyType:"stateVariable",variableName:"headX"+e},n[r].x={dependencyType:"stateVariable",variableName:"x"+e})}return{globalDependencies:{basedOnDisplacement:{dependencyType:"stateVariable",variableName:"basedOnDisplacement"},basedOnHead:{dependencyType:"stateVariable",variableName:"basedOnHead"},tailShadow:{dependencyType:"stateVariable",variableName:"tailShadow"}},dependenciesByKey:n}},arrayDefinitionByKey:function({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={},a={};for(let i of n){let n=Number(i)+1;null!==t[i].tailAttr?r[i]=t[i].tailAttr.stateValues["x"+n]:null!==e.tailShadow?r[i]=e.tailShadow.get_component(Number(i)):e.basedOnHead&&e.basedOnDisplacement?r[i]=t[i].headX.subtract(t[i].x).simplify():a[i]=!0}let i={};return Object.keys(r).length>0&&(i.setValue={tail:r}),Object.keys(a).length>0&&(i.useEssentialOrDefaultValue={tail:a}),i},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i=[],s=!1;for(let a in e.tail)n[a].tailAttr&&null!==n[a].tailAttr?i.push({setDependency:r[a].tailAttr,desiredValue:e.tail[a],variableIndex:0}):null!==t.tailShadow?s=!0:t.basedOnHead&&t.basedOnDisplacement?i.push({setDependency:r[a].x,desiredValue:n[a].headX.subtract(e.tail[a]).simplify()}):i.push({setEssentialValue:"tail",value:{[a]:convertValueToMathExpression(e.tail[a])}});if(s)if(a[0]>1){let t=["vector"];for(let n in e.tail)t[Number(n)+1]=e.tail[n].tree;t.length=a[0]+1,i.push({setDependency:"tailShadow",desiredValue:me$3.fromAst(t)})}else 1===a[0]&&"0"in e.tail&&i.push({setDependency:"tailShadow",desiredValue:e.tail[0]});return{success:!0,instructions:i}}},e.magnitude={public:!0,shadowingInstructions:{createComponentOfType:"math"},returnDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},displacement:{dependencyType:"stateVariable",variableName:"displacement"}}),definition({dependencyValues:e}){let t=0,n=!0;for(let r=0;re/i));let s=e.magnitude.evaluate_to_constant();if(!Number.isFinite(s)||s<0)return{success:!1};let o=[];for(let e=0;e({head:{dependencyType:"stateVariable",variableName:"head"},tail:{dependencyType:"stateVariable",variableName:"tail"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),definition:function({dependencyValues:e}){let t,n;if(1===e.nDimensions)e.head[0].evaluate_to_constant(),n=e.tail[0].evaluate_to_constant(),Number.isFinite(n)||(n=NaN);else{t=[],n=[];for(let r=0;r({displacement:{dependencyType:"stateVariable",variableName:"displacement"},displayWithAngleBrackets:{dependencyType:"stateVariable",variableName:"displayWithAngleBrackets"}}),definition({dependencyValues:e}){let t=[];for(let n of e.displacement)n?t.push(n.tree):t.push("_");if(t.length>1){t=[e.displayWithAngleBrackets?"altvector":"vector",...t]}else t=1===t.length?t[0]:"_";return{setValue:{displacementCoords:me$3.fromAst(t)}}},inverseDefinition({desiredStateVariableValues:e}){let t,n=e.displacementCoords.tree;return t=Array.isArray(n)&&vectorOperators.includes(n[0])?n.slice(1).map((e=>me$3.fromAst(e))):[e.displacementCoords],{success:!0,instructions:[{setDependency:"displacement",desiredValue:t}]}}},e.latex={forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({displacementCoords:{dependencyType:"stateVariable",variableName:"displacementCoords"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"}}),definition:function({dependencyValues:e,usedDefault:t}){let n={};return e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(n.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(n.padToDigits=e.displayDigits)),{setValue:{latex:roundForDisplay({value:e.displacementCoords,dependencyValues:e,usedDefault:t}).toLatex(n)}}}},e.nearestPoint={returnDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},numericalEndpoints:{dependencyType:"stateVariable",variableName:"numericalEndpoints"}}),definition({dependencyValues:e}){let t=e.numericalEndpoints[0]?.[0],n=e.numericalEndpoints[0]?.[1],r=e.numericalEndpoints[1]?.[0],a=e.numericalEndpoints[1]?.[1],i=Number.isFinite(t)&&Number.isFinite(n)&&Number.isFinite(r)&&Number.isFinite(a),s=2!==e.nDimensions||!i||r===t&&a===n;return{setValue:{nearestPoint:function({variables:e,scales:i}){if(s)return{};let o=i[0],l=i[1],u=(r-t)/o,c=(a-n)/l,p=u*u+c*c,d=((e.x1-t)/o*u+(e.x2-n)/l*c)/p,m={};return m=d<=0?{x1:t,x2:n}:d>=1?{x1:r,x2:a}:{x1:t+d*u*o,x2:n+d*c*l},void 0!==e.x3&&(m.x3=0),m}}}}},e}static adapters=[{stateVariable:"displacementCoords",componentType:"coords",stateVariablesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]}];async moveVector({tailcoords:e,headcoords:t,transient:n,skippable:r,sourceInformation:a,actionId:i}){if(void 0!==e){if(void 0!==t){if(!await this.stateValues.draggable)return await this.coreFunctions.resolveAction({actionId:i})}else if(!await this.stateValues.tailDraggable)return await this.coreFunctions.resolveAction({actionId:i})}else if(!await this.stateValues.headDraggable)return await this.coreFunctions.resolveAction({actionId:i});let s=[];if(void 0!==e){if(await this.stateValues.basedOnHead&&await this.stateValues.basedOnDisplacement){let n;if(void 0===t){let t=await this.stateValues.numericalEndpoints;n=e.map(((e,n)=>t[1][n]-e))}else n=e.map(((e,n)=>t[n]-e));s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"displacement",value:n.map((e=>me$3.fromAst(e))),sourceInformation:a})}else s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"tail",value:e.map((e=>me$3.fromAst(e))),sourceInformation:a});if(void 0===t&&!await this.stateValues.basedOnHead){let t=await this.stateValues.numericalEndpoints,n=e.map(((e,n)=>t[1][n]-e));s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"displacement",value:n.map((e=>me$3.fromAst(e))),sourceInformation:a})}}if(void 0!==t){if(await this.stateValues.basedOnHead)s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"head",value:t.map((e=>me$3.fromAst(e))),sourceInformation:a});else{null==e&&(e=(await this.stateValues.numericalEndpoints)[0]);let n=e.map(((e,n)=>t[n]-e));s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"displacement",value:n.map((e=>me$3.fromAst(e))),sourceInformation:a})}if(void 0===e&&await this.stateValues.basedOnHead&&await this.stateValues.basedOnDisplacement){let e=await this.stateValues.numericalEndpoints,n=t.map(((t,n)=>t-e[0][n]));s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"displacement",value:n.map((e=>me$3.fromAst(e))),sourceInformation:a})}}return n?await this.coreFunctions.performUpdate({updateInstructions:s,transient:n,skippable:r,actionId:i}):await this.coreFunctions.performUpdate({updateInstructions:s,actionId:i,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{head:t,tail:e}}})}async vectorClicked({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"click",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}async mouseDownOnVector({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"down",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}}class Angle extends GraphicalComponent{static componentType="angle";static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.radius={createComponentOfType:"math",createStateVariable:"radius",defaultValue:me$3.fromAst(1),public:!0},e.chooseReflexAngle={createComponentOfType:"text",createStateVariable:"chooseReflexAngle",defaultValue:"never",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["never","allowed","always"]},e.inDegrees={createComponentOfType:"boolean",createStateVariable:"inDegrees",defaultValue:!1,public:!0,forRenderer:!0},e.radians={createComponentOfType:"math"},e.degrees={createComponentOfType:"math"},e.through={createComponentOfType:"_pointListComponent"},e.betweenLines={createComponentOfType:"_lineListComponent"},e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.padZeros={createComponentOfType:"boolean",createStateVariable:"padZeros",defaultValue:!1,public:!0},e.emphasizeRightAngle={createComponentOfType:"boolean",createStateVariable:"emphasizeRightAngle",defaultValue:!0,public:!0,forRenderer:!0},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e,componentInfoObjects:t}){let n=e.map((e=>t.componentIsSpecifiedType(e,"label"))),r=[],a=[];if(0===n.filter((e=>e)).length)r=e;else{if(n[0]){let t=n.indexOf(!1);-1!==t&&(a.push(...e.slice(0,t)),e=e.slice(t),n=n.slice(t))}let t=n.indexOf(!0);-1===t?r=e:(r=e.slice(0,t),a.push(...e.slice(t)))}return 0===r.length?{success:!1}:{success:!0,newAttributes:{radians:{component:{componentType:"math",children:r}}},newChildren:a}}}),e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.displayDigitsAttr){let n=t.displayDigitsAttr,r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!n&&!r){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({betweenLines:{dependencyType:"attributeComponent",attributeName:"betweenLines"}}),definition({dependencyValues:e}){let t=null;return null!==e.betweenLines&&(t=e.betweenLines.componentName),{setValue:{betweenLinesName:t}}}},e.nPointsSpecified={returnDependencies:()=>({through:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["nPoints"]}}),definition:({dependencyValues:e})=>null!==e.through?{setValue:{nPointsSpecified:e.through.stateValues.nPoints}}:{setValue:{nPointsSpecified:0}}},e.points={isArray:!0,nDimensions:2,entryPrefixes:["pointX","point"],stateVariablesDeterminingDependencies:["betweenLinesName"],returnArraySizeDependencies:()=>({}),returnArraySize:()=>[3,2],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("pointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},returnArrayDependenciesByKey({stateValues:e}){let t={nPointsSpecified:{dependencyType:"stateVariable",variableName:"nPointsSpecified"},throughAttr:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["points"]},radiansAttr:{dependencyType:"attributeComponent",attributeName:"radians",variableNames:["value"]},degreesAttr:{dependencyType:"attributeComponent",attributeName:"degrees",variableNames:["value"]}};return null!==e.betweenLinesName&&(t.lineChildren={dependencyType:"child",parentName:e.betweenLinesName,childGroups:["lines"],variableNames:["points","nDimensions","coeff0","coeffvar1","coeffvar2","nearestPoint"]}),{globalDependencies:t}},arrayDefinitionByKey({globalDependencyValues:e}){if(e.lineChildren){if(e.lineChildren.length>2){console.warn(`Cannot define an angle between ${e.lineChildren.length} line(s)`);let t={};for(let e=0;e<3;e++)for(let n=0;n<2;n++)t[e+","+n]=me$3.fromAst("_");return{setValue:{points:t}}}if(1===e.lineChildren.length){let t=e.lineChildren[0];if(2!==t.stateValues.nDimensions){let e={};for(let t=0;t<3;t++)for(let n=0;n<2;n++)e[t+","+n]=me$3.fromAst("_");return{setValue:{points:e}}}let n=t.stateValues.nearestPoint({variables:{x1:me$3.fromAst(0),x2:me$3.fromAst(0)}}),r=t.stateValues.points[0][0].evaluate_to_constant(),a=t.stateValues.points[0][1].evaluate_to_constant(),i=t.stateValues.points[1][0].evaluate_to_constant(),s=t.stateValues.points[1][1].evaluate_to_constant(),o=Math.atan2(s-a,i-r),l={"0,0":me$3.fromAst(n.x1+Math.cos(o)),"0,1":me$3.fromAst(n.x2+Math.sin(o)),"1,0":me$3.fromAst(n.x1),"1,1":me$3.fromAst(n.x2)},u=null;if(e.radiansAttr){if(u=e.radiansAttr.stateValues.value.evaluate_to_constant(),!Number.isFinite(u)){let e={};return e["2,0"]=me$3.fromAst("_"),e["2,1"]=me$3.fromAst("_"),{setValue:{points:e}}}}else if(e.degreesAttr){let t=e.degreesAttr.stateValues.value.evaluate_to_constant();if(!Number.isFinite(t))return l["2,0"]=me$3.fromAst("_"),l["2,1"]=me$3.fromAst("_"),{setValue:{points:l}};u=t/180*Math.PI}else u=Math.PI/2;let c=o+u;return l["2,0"]=me$3.fromAst(n.x1+Math.cos(c)),l["2,1"]=me$3.fromAst(n.x2+Math.sin(c)),{setValue:{points:l}}}{let t=e.lineChildren[0],n=e.lineChildren[1],r=calculateLineIntersection(t,n);if(void 0===r){let e={};for(let t=0;t<3;t++)for(let n=0;n<2;n++)e[t+","+n]=me$3.fromAst("_");return{setValue:{points:e}}}let a=r,i=t.stateValues.points[0][0].evaluate_to_constant(),s=t.stateValues.points[0][1].evaluate_to_constant(),o=t.stateValues.points[1][0].evaluate_to_constant(),l=t.stateValues.points[1][1].evaluate_to_constant(),u=[me$3.fromAst(a[0].tree+o-i),me$3.fromAst(a[1].tree+l-s)];i=n.stateValues.points[0][0].evaluate_to_constant(),s=n.stateValues.points[0][1].evaluate_to_constant(),o=n.stateValues.points[1][0].evaluate_to_constant(),l=n.stateValues.points[1][1].evaluate_to_constant();let c=[me$3.fromAst(a[0].tree+o-i),me$3.fromAst(a[1].tree+l-s)];return{setValue:{points:{"0,0":u[0],"0,1":u[1],"1,0":a[0],"1,1":a[1],"2,0":c[0],"2,1":c[1]}}}}}let t,n=e.nPointsSpecified;t=e.throughAttr?e.throughAttr.stateValues.points:[];let r={};for(let[e,n]of t.entries())r[e+",0"]=n[0],r[e+",1"]=n[1];if(0===n&&(r["0,0"]=me$3.fromAst(1),r["0,1"]=me$3.fromAst(0)),n<2&&(r["1,0"]=me$3.fromAst(0),r["1,1"]=me$3.fromAst(0)),n<3){let t=null;if(e.radiansAttr){if(t=e.radiansAttr.stateValues.value.evaluate_to_constant(),!Number.isFinite(t))return r["2,0"]=me$3.fromAst("_"),r["2,1"]=me$3.fromAst("_"),{setValue:{points:r}}}else if(e.degreesAttr){let n=e.degreesAttr.stateValues.value.evaluate_to_constant();if(!Number.isFinite(n))return r["2,0"]=me$3.fromAst("_"),r["2,1"]=me$3.fromAst("_"),{setValue:{points:r}};t=n/180*Math.PI}else t=Math.PI/2;let n=r["0,0"].evaluate_to_constant(),a=r["0,1"].evaluate_to_constant(),i=r["1,0"].evaluate_to_constant(),s=r["1,1"].evaluate_to_constant(),o=Math.atan2(a-s,n-i)+t;r["2,0"]=me$3.fromAst(i+Math.cos(o)),r["2,1"]=me$3.fromAst(s+Math.sin(o))}return{setValue:{points:r}}}},e.radians={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},additionalStateVariablesDefined:[{variableName:"swapPointOrder",forRenderer:!0}],returnDependencies:()=>({radians:{dependencyType:"attributeComponent",attributeName:"radians",variableNames:["value"]},degrees:{dependencyType:"attributeComponent",attributeName:"degrees",variableNames:["value"]},points:{dependencyType:"stateVariable",variableName:"points"},chooseReflexAngle:{dependencyType:"stateVariable",variableName:"chooseReflexAngle"}}),definition({dependencyValues:e}){let t=!1;if(null!==e.radians)return{setValue:{radians:e.radians.stateValues.value.simplify(),swapPointOrder:t}};if(null!==e.degrees)return{setValue:{radians:e.degrees.stateValues.value.divide(me$3.fromAst(180)).simplify().multiply(me$3.fromAst("pi")).simplify(),swapPointOrder:t}};let n,r=[],a=!1;for(let t=0;t<3;t++)r.push([e.points[t][0].evaluate_to_constant(),e.points[t][1].evaluate_to_constant()]),null!==r[t][0]&&null!==r[t][1]||(a=!0);return a?{setValue:{radians:me$3.fromAst("_"),swapPointOrder:t}}:(n=Math.atan2(r[2][1]-r[1][1],r[2][0]-r[1][0])-Math.atan2(r[0][1]-r[1][1],r[0][0]-r[1][0]),n<0&&(n+=2*Math.PI),n>Math.PI?"never"===e.chooseReflexAngle&&(n=2*Math.PI-n,t=!0):"always"===e.chooseReflexAngle&&(n=2*Math.PI-n,t=!0),{setValue:{radians:me$3.fromAst(n),swapPointOrder:t}})}},e.value={isAlias:!0,targetVariableName:"radians"},e.angle={isAlias:!0,targetVariableName:"radians"},e.degrees={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},returnDependencies:()=>({radians:{dependencyType:"stateVariable",variableName:"radians"}}),definition({dependencyValues:e}){let t;if("_"===e.radians.tree||Number.isNaN(e.radians.tree))t=e.radians;else{let n=e.radians.evaluate_to_constant();t=Number.isFinite(n)?me$3.fromAst(180*n/Math.PI):e.radians.multiply(me$3.fromAst(["/",180,"pi"])).simplify()}return{setValue:{degrees:t}}}},e.latexForRenderer={forRenderer:!0,returnDependencies:()=>({inDegrees:{dependencyType:"stateVariable",variableName:"inDegrees"},radians:{dependencyType:"stateVariable",variableName:"radians"},degrees:{dependencyType:"stateVariable",variableName:"degrees"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"}}),definition:function({dependencyValues:e,usedDefault:t}){let n={};e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(n.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(n.padToDigits=e.displayDigits));let r=roundForDisplay({value:e.inDegrees?e.degrees:e.radians,dependencyValues:e,usedDefault:t}).toLatex(n);return e.inDegrees&&(r+="^\\circ"),{setValue:{latexForRenderer:r}}}},e.numericalPoints={isArray:!0,entryPrefixes:["numericalPoint"],forRenderer:!0,returnArraySizeDependencies:()=>({}),returnArraySize:()=>[3],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={point:{dependencyType:"stateVariable",variableName:"point"+(Number(n)+1)}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].point,a=[];for(let e=0;e<2;e++){let n=t[e].evaluate_to_constant();Number.isFinite(n)||(n=NaN),a.push(n)}n[r]=a}return{setValue:{numericalPoints:n}}}},e.numericalRadius={forRenderer:!0,returnDependencies:()=>({radius:{dependencyType:"stateVariable",variableName:"radius"}}),definition({dependencyValues:e}){let t=e.radius.evaluate_to_constant();return Number.isFinite(t)||(t=NaN),{setValue:{numericalRadius:t}}}},e}static adapters=["radians"]}function calculateLineIntersection(e,t){if(2!==e.stateValues.nDimensions||2!==t.stateValues.nDimensions)return void console.log("Calculating angle between two lines implemented only in 2D");let n=e.stateValues.coeffvar1.evaluate_to_constant(),r=e.stateValues.coeffvar2.evaluate_to_constant(),a=e.stateValues.coeff0.evaluate_to_constant(),i=t.stateValues.coeffvar1.evaluate_to_constant(),s=t.stateValues.coeffvar2.evaluate_to_constant(),o=t.stateValues.coeff0.evaluate_to_constant();if(!(Number.isFinite(n)&&Number.isFinite(r)&&Number.isFinite(a)&&Number.isFinite(i)&&Number.isFinite(s)&&Number.isFinite(o)))return void console.log("Calculating angle between two lines implemented only for constant coefficients");let l=n*s-i*r;if(Math.abs(l)<1e-14)return Math.abs(o*n-a*i)>1e-14?void console.log("Cannot calculate angle between two parallel lines"):0===n&&0===r&&0===a||0===i&&0===s&&0===o?void 0:0!==r?[me$3.fromAst(0),me$3.fromAst(-a/r)]:[me$3.fromAst(-a/n),me$3.fromAst(0)];let u=(o*r-a*s)/l,c=(a*i-o*n)/l;return[me$3.fromAst(u),me$3.fromAst(c)]}var defaults$5={space:"",cycles:!1,replacer:(e,t)=>t,stringify:JSON.stringify},util$1={isArray:Array.isArray,assign:Object.assign,isObject:e=>"object"==typeof e,isFunction:e=>"function"==typeof e,isBoolean:e=>"boolean"==typeof e,isRegex:e=>e instanceof RegExp,keys:Object.keys};const DEFAULTS=defaults$5,isFunction$2=util$1.isFunction,isBoolean$1=util$1.isBoolean,isObject$2=util$1.isObject,isArray$3=util$1.isArray,isRegex=util$1.isRegex,assign$1=util$1.assign,keys$1=util$1.keys;function serialize(e){return null==e?e:isRegex(e)?e.toString():e.toJSON?e.toJSON():e}function stringifyDeterministic(e,t){t=t||assign$1({},DEFAULTS),isFunction$2(t)&&(t={compare:t});const n=t.space||DEFAULTS.space,r=isBoolean$1(t.cycles)?t.cycles:DEFAULTS.cycles,a=t.replacer||DEFAULTS.replacer,i=t.stringify||DEFAULTS.stringify,s=t.compare&&function(e){return function(t){return function(n,r){const a={key:n,value:t[n]},i={key:r,value:t[r]};return e(a,i)}}}(t.compare);r||i(e);const o=[];return function e(t,l,u,c){const p=n?"\n"+new Array(c+1).join(n):"",d=n?": ":":";if(u=serialize(u),void 0!==(u=a.call(t,l,u))){if(!isObject$2(u)||null===u)return i(u);if(isArray$3(u)){const t=[];for(let r=0;r0)for(let e of t.children)"object"!=typeof e?e.trim()&&(p=!0):i(e,"when")||(i(e,"math")||i(e,"number")||i(e,"mathList")||i(e,"numberList")?(s=!0,p=!0):i(e,"text")||i(e,"textList")?(o=!0,p=!0):i(e,"boolean")?(l=!0,p=!0):i(e,"booleanList")?l=!0:n.isInheritedComponentType({inheritedComponentType:e.componentType,baseComponentType:"_composite"})&&!e.attributes?.createComponentOfType?.primitive?p=!0:i(e,"orbitalDiagram")||(p=!0));else p=!0;else i(t,"mathInput")?(m.push(!1),s=!0,c=!0):i(t,"textInput")?(m.push(!1),o=!0,c=!0):i(t,"_input")||i(t,"considerAsResponses")?(m.push(!1),c=!0):(n.isInheritedComponentType({inheritedComponentType:t.componentType,baseComponentType:"_composite"})&&t.attributes?.createComponentOfType?.primitive,m.push(!0),p=!0);if(c&&(d=!0),u>0){if(e=e.filter((e=>"string"!=typeof e||""!==e.trim())),e.length!==u)return{success:!1};{let n={componentType:"choiceInput",children:e};return t.shuffleOrder&&(n.attributes={shuffleOrder:{primitive:!0}}),{success:!0,newChildren:[n]}}}if(!p&&!d){for(let t of e)if(i(t,"award")&&t.children?.length>0&&r(t.children)){d=!0;break}if(!d)for(let t of e)i(t,"award")&&t.children?.length>0&&a(t.children)}let h=[],f=[],y=[];if(0===m.filter((e=>!e)).length)h=e;else{if(!m[0]){let t=m.indexOf(!0);-1!==t&&(f=e.slice(0,t),e=e.slice(t),m=m.slice(t))}let t=m.indexOf(!1);-1===t?h=e:(h=e.slice(0,t),y=e.slice(t))}for(;"string"==typeof h[0]&&""===h[0].trim();)h=h.slice(1);let g,b,v=h.length;for(;"string"==typeof h[v-1]&&""===h[v-1].trim();)h=h.slice(0,v-1),v=h.length;if(t.type?(b=t.type,["math","text","boolean"].includes(b)||(console.warn(`Invalid type ${b}`),b="math")):b=s?"math":o?"text":l?"boolean":"math",0===h.length)g=[...f,...y];else{let e;e=h.length>1||n.isInheritedComponentType({inheritedComponentType:h[0].componentType,baseComponentType:"_composite"})&&!h[0].props?.componentType?[{componentType:b,children:h}]:h,g=[...f,{componentType:"award",children:e},...y]}if(p&&!c){g=[{componentType:b+"Input"},...g]}return{success:!0,newChildren:g}}}),e}static returnChildGroups(){return[{group:"awards",componentTypes:["award"]},{group:"inputs",componentTypes:["_input"]},{group:"responses",componentTypes:["considerAsResponses"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return renameStateVariable({stateVariableDefinitions:e,oldName:"disabled",newName:"disabledOriginal"}),e.showCorrectness={forRenderer:!0,returnDependencies:()=>({showCorrectnessPreliminary:{dependencyType:"stateVariable",variableName:"showCorrectnessPreliminary"},showCorrectnessFlag:{dependencyType:"flag",flagName:"showCorrectness"}}),definition({dependencyValues:e,usedDefault:t}){let n;return n=t.showCorrectnessPreliminary?!1!==e.showCorrectnessFlag:e.showCorrectnessPreliminary,{setValue:{showCorrectness:n}}}},e.haveAwardThatRequiresInput={returnDependencies:()=>({awardChildren:{dependencyType:"child",childGroups:["awards"],variableNames:["requireInputInAnswer"]}}),definition:({dependencyValues:e})=>({setValue:{haveAwardThatRequiresInput:e.awardChildren.some((e=>e.stateValues.requireInputInAnswer))}})},e.allInputChildrenIncludingSugared={returnDependencies:()=>({allInputChildrenIncludingSugared:{dependencyType:"child",childGroups:["inputs"]}}),definition:({dependencyValues:e})=>({setValue:{allInputChildrenIncludingSugared:e.allInputChildrenIncludingSugared}})},e.inputChildren={stateVariablesDeterminingDependencies:["allInputChildrenIncludingSugared"],additionalStateVariablesDefined:["inputChildIndices","skippedFirstInput"],forRenderer:!0,returnDependencies({stateValues:e}){let t={allInputChildrenIncludingSugared:{dependencyType:"stateVariable",variableName:"allInputChildrenIncludingSugared"},haveAwardThatRequiresInput:{dependencyType:"stateVariable",variableName:"haveAwardThatRequiresInput"}};return e.allInputChildrenIncludingSugared.length>0&&(t.firstInputFromSugar={dependencyType:"doenetAttribute",componentName:e.allInputChildrenIncludingSugared[0].componentName,attributeName:"createdFromSugar"}),t},definition({dependencyValues:e}){let t=[...e.allInputChildrenIncludingSugared],n=[...e.allInputChildrenIncludingSugared.keys()],r=!1;return"choiceInput"!==t[0]?.componentType&&(!e.haveAwardThatRequiresInput||e.allInputChildrenIncludingSugared.length>1)&&e.firstInputFromSugar&&(r=!0,t=t.slice(1),n=n.slice(1)),{setValue:{inputChildren:t,inputChildIndices:n,skippedFirstInput:r}}}},e.inputChildrenWithValues={stateVariablesDeterminingDependencies:["inputChildIndices"],forRenderer:!0,returnDependencies:({stateValues:e})=>({inputChildren:{dependencyType:"child",childGroups:["inputs"],variableNames:["valueToRecordOnSubmit","valueRecordedAtSubmit","value"],childIndices:e.inputChildIndices,variablesOptional:!0}}),definition:function({dependencyValues:e}){return{setValue:{inputChildrenWithValues:e.inputChildren}}}},e.inputChildWithValues={returnDependencies:()=>({inputChildrenWithValues:{dependencyType:"stateVariable",variableName:"inputChildrenWithValues"}}),definition({dependencyValues:e}){let t=null;return 1===e.inputChildrenWithValues.length&&(t=e.inputChildrenWithValues[0]),{setValue:{inputChildWithValues:t}}}},e.awardInputResponseChildren={returnDependencies:()=>({awardInputResponseChildren:{dependencyType:"child",childGroups:["awards","inputs","responses"]},skippedFirstInput:{dependencyType:"stateVariable",variableName:"skippedFirstInput"}}),definition({dependencyValues:e}){let t=[...e.awardInputResponseChildren];return e.skippedFirstInput&&(t=t.slice(1)),{setValue:{awardInputResponseChildren:t}}}},e.nResponses={public:!0,shadowingInstructions:{createComponentOfType:"number"},stateVariablesDeterminingDependencies:["awardInputResponseChildren"],returnDependencies({stateValues:e,componentInfoObjects:t}){let n={childTypes:{dependencyType:"value",value:e.awardInputResponseChildren.map((e=>e.componentType))}};for(let[r,a]of e.awardInputResponseChildren.entries())t.isInheritedComponentType({inheritedComponentType:a.componentType,baseComponentType:"award"})?n["child"+r]={dependencyType:"descendant",ancestorName:a.componentName,componentTypes:["_base"],variableNames:["isResponse","nValues"],variablesOptional:!0,recurseToMatchedChildren:!0,includeNonActiveChildren:!0,skipOverAdapters:!0}:t.isInheritedComponentType({inheritedComponentType:a.componentType,baseComponentType:"_input"})?n["childNValues"+r]={dependencyType:"stateVariable",componentName:a.componentName,variableName:"nValues",variablesOptional:!0}:n["child"+r]={dependencyType:"stateVariable",componentName:a.componentName,variableName:"childrenWithNValues"};return n},definition({dependencyValues:e,componentInfoObjects:t}){let n=0;for(let[r,a]of e.childTypes.entries())if(t.isInheritedComponentType({inheritedComponentType:a,baseComponentType:"award"}))for(let a of e["child"+r])a.stateValues.isResponse&&!t.isInheritedComponentType({inheritedComponentType:a.componentType,baseComponentType:"_composite"})&&(void 0===a.stateValues.nValues?n+=1:n+=a.stateValues.nValues);else if(t.isInheritedComponentType({inheritedComponentType:a,baseComponentType:"_input"})){let t=e["childNValues"+r];n+=void 0===t?1:t}else for(let t of e["child"+r])void 0===t.stateValues.nValues?n+=1:n+=t.stateValues.nValues;return{setValue:{nResponses:n}}}},e.currentResponses={public:!0,shadowingInstructions:{hasVariableComponentType:!0},isArray:!0,entryPrefixes:["currentResponse"],stateVariablesDeterminingDependencies:["awardInputResponseChildren"],returnArraySizeDependencies:()=>({nResponses:{dependencyType:"stateVariable",variableName:"nResponses"}}),returnArraySize:({dependencyValues:e})=>[e.nResponses],returnArrayDependenciesByKey({stateValues:e,componentInfoObjects:t}){let n={childTypes:{dependencyType:"value",value:e.awardInputResponseChildren.map((e=>e.componentType))}};for(let[r,a]of e.awardInputResponseChildren.entries())t.isInheritedComponentType({inheritedComponentType:a.componentType,baseComponentType:"award"})?n["child"+r]={dependencyType:"descendant",ancestorName:a.componentName,componentTypes:["_base"],variableNames:["isResponse","value","values","formula","componentType"],variablesOptional:!0,recurseToMatchedChildren:!0,includeAttributeChildren:!0,includeNonActiveChildren:!0,skipOverAdapters:!0}:t.isInheritedComponentType({inheritedComponentType:a.componentType,baseComponentType:"_input"})?(n["childValue"+r]={dependencyType:"stateVariable",componentName:a.componentName,variableName:"value",variablesOptional:!0},n["childValues"+r]={dependencyType:"stateVariable",componentName:a.componentName,variableName:"values",variablesOptional:!0},n["childComponentType"+r]={dependencyType:"stateVariable",componentName:a.componentName,variableName:"componentType",variablesOptional:!0}):n["child"+r]={dependencyType:"stateVariable",componentName:a.componentName,variableName:"childrenAsResponses"};return{globalDependencies:n}},arrayDefinitionByKey({globalDependencyValues:e,componentInfoObjects:t}){let n=[],r=[],a=[];for(let[n,r]of e.childTypes.entries())if(t.isInheritedComponentType({inheritedComponentType:r,baseComponentType:"award"}))for(let r of e["child"+n])r.stateValues.isResponse&&!t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"_composite"})&&a.push(r);else if(t.isInheritedComponentType({inheritedComponentType:r,baseComponentType:"_input"})){let t={componentType:r,stateValues:{value:e["childValue"+n],values:e["childValues"+n],componentType:e["childComponentType"+n]}};a.push(t)}else a.push(...e["child"+n]);for(let e of a){let t=e.stateValues.componentType;t||(t=e.componentType),"mathList"===t?t="math":"numberList"===t?t="number":"textList"===t?t="text":"booleanList"===t&&(t="boolean"),Array.isArray(e.stateValues.values)?(n.push(...e.stateValues.values),r.push(...Array(e.stateValues.values.length).fill(t))):void 0!==e.stateValues.value?(n.push(e.stateValues.value),r.push(t)):e.stateValues.formula instanceof me$3.class?(n.push(e.stateValues.formula),r.push("math")):(n.push(""),r.push("text"))}return{setValue:{currentResponses:n},setCreateComponentOfType:{currentResponses:r}}}},e.currentResponse={isAlias:!0,targetVariableName:"currentResponse1"},e.nSubmittedResponses={public:!0,shadowingInstructions:{createComponentOfType:"number"},hasEssential:!0,defaultValue:0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{nSubmittedResponses:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"nSubmittedResponses",value:e.nSubmittedResponses}]})},e.submittedResponsesComponentType={hasEssential:!0,defaultValue:null,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{submittedResponsesComponentType:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return e.submittedResponsesComponentType?{success:!0,instructions:[{setEssentialValue:"submittedResponsesComponentType",value:[...e.submittedResponsesComponentType]}]}:{success:!0,instructions:[{setEssentialValue:"submittedResponsesComponentType",value:[]}]}}},e.submittedResponses={public:!0,shadowingInstructions:{hasVariableComponentType:!0},isArray:!0,entryPrefixes:["submittedResponse"],defaultValueByArrayKey:()=>"_",hasEssential:!0,inverseShadowToSetEntireArray:!0,doNotCombineInverseArrayInstructions:!0,returnArraySizeDependencies:()=>({nSubmittedResponses:{dependencyType:"stateVariable",variableName:"nSubmittedResponses"}}),returnArraySize:({dependencyValues:e})=>[e.nSubmittedResponses],returnArrayDependenciesByKey:()=>({globalDependencies:{submittedResponsesComponentType:{dependencyType:"stateVariable",variableName:"submittedResponsesComponentType"},nSubmittedResponses:{dependencyType:"stateVariable",variableName:"nSubmittedResponses"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t=[];e.submittedResponsesComponentType&&t.push(...e.submittedResponsesComponentType.slice(0,e.nSubmittedResponses));let n={};for(let r=0;r({autoSubmit:{dependencyType:"flag",flagName:"autoSubmit"}}),definition:({dependencyValues:e})=>({setValue:{suppressCheckwork:e.autoSubmit}})},e.delegateCheckWork={additionalStateVariablesDefined:["delegateCheckWorkToInput","delegateCheckWorkToAncestor"],forRenderer:!0,returnDependencies:()=>({inputChildren:{dependencyType:"stateVariable",variableName:"inputChildren"},forceFullCheckworkButton:{dependencyType:"stateVariable",variableName:"forceFullCheckworkButton"},sectionAncestor:{dependencyType:"ancestor",componentType:"_sectioningComponent",variableNames:["suppressAnswerSubmitButtons"]},documentAncestor:{dependencyType:"ancestor",componentType:"document",variableNames:["suppressAnswerSubmitButtons"]}}),definition:function({dependencyValues:e}){let t=!1,n=!1,r=!1;return e.documentAncestor.stateValues.suppressAnswerSubmitButtons||e.sectionAncestor?.stateValues.suppressAnswerSubmitButtons?t=r=!0:1!==e.inputChildren.length||e.forceFullCheckworkButton||(n=r=!0),{setValue:{delegateCheckWork:r,delegateCheckWorkToAncestor:t,delegateCheckWorkToInput:n}}}},e.creditAchievedIfSubmit={additionalStateVariablesDefined:["awardsUsedIfSubmit","awardChildren","inputUsedIfSubmit"],stateVariablesDeterminingDependencies:["inputChildIndices"],returnDependencies:({stateValues:e})=>({awardChildren:{dependencyType:"child",childGroups:["awards"],variableNames:["credit","creditAchievedIfSubmit","fractionSatisfiedIfSubmit"]},inputChildren:{dependencyType:"child",childGroups:["inputs"],variableNames:["creditAchievedIfSubmit"],childIndices:e.inputChildIndices,variablesOptional:!0},nAwardsCredited:{dependencyType:"stateVariable",variableName:"nAwardsCredited"}}),definition:function({dependencyValues:e}){let t=0,n=e.nAwardsCredited,r=Array(n).fill(null),a=null;if(0===e.awardChildren.length){if(1===e.inputChildren.length){let n=e.inputChildren[0].stateValues.creditAchievedIfSubmit;n>=0&&(t=n,a=e.inputChildren[0].componentName)}}else{let a=Array(n).fill(null),i=0;for(let t of e.awardChildren){let e=t.stateValues.creditAchievedIfSubmit;if((e>i||null===r[n-1])&&t.stateValues.fractionSatisfiedIfSubmit>0)if(null===r[0])r[0]=t.componentName,a[0]=e,i=Math.min(...a);else for(let[s,o]of a.entries())if(e>o||null===o){r.splice(s,0,t.componentName),r=r.slice(0,n),a.splice(s,0,e),a=a.slice(0,n),i=Math.min(...a);break}}t=Math.min(1,a.reduce(((e,t)=>e+t),0))}return{setValue:{creditAchievedIfSubmit:t,awardsUsedIfSubmit:r,awardChildren:e.awardChildren,inputUsedIfSubmit:a}}}},e.creditAchieved={defaultValue:0,public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{creditAchieved:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"creditAchieved",value:e.creditAchieved}]}}},e.responseHasBeenSubmitted={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},defaultValue:!1,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{responseHasBeenSubmitted:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"responseHasBeenSubmitted",value:e.responseHasBeenSubmitted}]}}},e.autoSubmit={returnDependencies:()=>({autoSubmit:{dependencyType:"flag",flagName:"autoSubmit"}}),definition:({dependencyValues:e})=>({setValue:{autoSubmit:Boolean(e.autoSubmit)}})},e.creditAchievedDependencies={shadowVariable:!0,stateVariablesDeterminingDependencies:["autoSubmit"],returnDependencies:({stateValues:e})=>({currentCreditAchievedDependencies:{dependencyType:"recursiveDependencyValues",variableNames:["creditAchievedIfSubmit"],includeImmediateValueWithValue:!e.autoSubmit,includeRawValueWithImmediateValue:!e.autoSubmit,includeOnlyEssentialValues:!0}}),definition({dependencyValues:e}){let t=lib(e.currentCreditAchievedDependencies,{replacer:serializedComponentsReplacer});return{setValue:{creditAchievedDependencies:Base64.stringify(sha1(t))}}},markStale:()=>({answerCreditPotentiallyChanged:!0})},e.creditAchievedDependenciesAtSubmit={defaultValue:null,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{creditAchievedDependenciesAtSubmit:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"creditAchievedDependenciesAtSubmit",value:e.creditAchievedDependenciesAtSubmit}]}}},e.justSubmitted={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,defaultValue:!1,hasEssential:!0,shadowVariable:!0,returnDependencies:()=>({currentCreditAchievedDependencies:{dependencyType:"stateVariable",variableName:"creditAchievedDependencies"},creditAchievedDependenciesAtSubmit:{dependencyType:"stateVariable",variableName:"creditAchievedDependenciesAtSubmit"},disableAfterCorrect:{dependencyType:"stateVariable",variableName:"disableAfterCorrect"},hasBeenCorrect:{dependencyType:"stateVariable",variableName:"hasBeenCorrect"}}),definition:function({dependencyValues:e,justUpdatedForNewComponent:t,componentName:n}){if(e.disableAfterCorrect&&e.hasBeenCorrect)return{setValue:{justSubmitted:!0}};return e.creditAchievedDependenciesAtSubmit!==e.currentCreditAchievedDependencies&&!t?{setValue:{justSubmitted:!1},setEssentialValue:{justSubmitted:!1}}:{useEssentialOrDefaultValue:{justSubmitted:!0}}},inverseDefinition:({desiredStateVariableValues:e,componentName:t})=>({success:!0,instructions:[{setEssentialValue:"justSubmitted",value:e.justSubmitted}]})},e.allFeedbacks={returnDependencies:()=>({awardChildren:{dependencyType:"child",childGroups:["awards"],variableNames:["feedbacks"]},feedbackComponents:{dependencyType:"descendant",componentTypes:["_input"],variableNames:["feedbacks"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let t=[];for(let n of e.awardChildren)t.push(...n.stateValues.feedbacks);for(let n of e.feedbackComponents)Array.isArray(n.stateValues.feedbacks)&&t.push(...n.stateValues.feedbacks);return{setValue:{allFeedbacks:t}}}},e.numberFeedbacks={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({allFeedbacks:{dependencyType:"stateVariable",variableName:"allFeedbacks"}}),definition:({dependencyValues:e})=>({setValue:{numberFeedbacks:e.allFeedbacks.length},checkForActualChange:{numberFeedbacks:!0}})},e.feedbacks={public:!0,shadowingInstructions:{createComponentOfType:"feedback"},isArray:!0,entryPrefixes:["feedback"],returnArraySizeDependencies:()=>({numberFeedbacks:{dependencyType:"stateVariable",variableName:"numberFeedbacks"}}),returnArraySize:({dependencyValues:e})=>[e.numberFeedbacks],returnArrayDependenciesByKey:()=>({globalDependencies:{allFeedbacks:{dependencyType:"stateVariable",variableName:"allFeedbacks"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n=0;n({}),definition:()=>({useEssentialOrDefaultValue:{nSubmissions:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"nSubmissions",value:e.nSubmissions}]})},e.numberOfAttemptsLeft={public:!0,shadowingInstructions:{createComponentOfType:"integer"},forRenderer:!0,returnDependencies:()=>({nSubmissions:{dependencyType:"stateVariable",variableName:"nSubmissions"},maximumNumberOfAttempts:{dependencyType:"stateVariable",variableName:"maximumNumberOfAttempts"}}),definition:({dependencyValues:e})=>({setValue:{numberOfAttemptsLeft:e.maximumNumberOfAttempts-e.nSubmissions}})},e.hasBeenCorrect={defaultValue:!1,hasEssential:!0,shadowVariable:!0,returnDependencies:()=>({creditAchieved:{dependencyType:"stateVariable",variableName:"creditAchieved"}}),definition:({dependencyValues:e})=>1===e.creditAchieved?{setValue:{hasBeenCorrect:!0},setEssentialValue:{hasBeenCorrect:!0}}:{useEssentialOrDefaultValue:{hasBeenCorrect:!0}}},e.disabled={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,stateVariablesDeterminingDependencies:["disableAfterCorrect"],returnDependencies({stateValues:e}){let t={disabledOriginal:{dependencyType:"stateVariable",variableName:"disabledOriginal"},numberOfAttemptsLeft:{dependencyType:"stateVariable",variableName:"numberOfAttemptsLeft"},disableAfterCorrect:{dependencyType:"stateVariable",variableName:"disableAfterCorrect"}};return e.disableAfterCorrect&&(t.hasBeenCorrect={dependencyType:"stateVariable",variableName:"hasBeenCorrect"}),t},definition:({dependencyValues:e})=>({setValue:{disabled:e.disabledOriginal||e.numberOfAttemptsLeft<1||e.disableAfterCorrect&&e.hasBeenCorrect}})},e.inItemNumber={returnDependencies:()=>({documentAncestor:{dependencyType:"ancestor",componentType:"document",variableNames:["itemNumberByAnswerName"]}}),definition:({dependencyValues:e,componentName:t})=>({setValue:{inItemNumber:e.documentAncestor.stateValues.itemNumberByAnswerName[t]}})},e}async submitAnswer({actionId:e}){let t=await this.stateValues.numberOfAttemptsLeft;if(t<1)return void console.warn(`Cannot submit answer for ${this.componentName} as number of attempts left is ${t}`);let n=await this.stateValues.creditAchievedIfSubmit,r=await this.stateValues.awardsUsedIfSubmit,a=await this.stateValues.inputUsedIfSubmit,i=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"creditAchieved",value:n},{updateType:"updateValue",componentName:this.componentName,stateVariable:"responseHasBeenSubmitted",value:!0}],s=await this.stateValues.inputChildrenWithValues;if(1===s.length){let e=s[0];a===e.componentName&&"valueToRecordOnSubmit"in e.stateValues&&"valueRecordedAtSubmit"in e.stateValues&&i.push({updateType:"updateValue",componentName:e.componentName,stateVariable:"valueRecordedAtSubmit",value:e.stateValues.valueToRecordOnSubmit})}let o=await this.stateValues.currentResponses;i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"submittedResponses",value:o}),i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"submittedResponsesComponentType",value:this.state.currentResponses.shadowingInstructions.createComponentOfType}),i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"justSubmitted",value:!0}),i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"creditAchievedDependenciesAtSubmit",value:await this.stateValues.creditAchievedDependencies}),i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"nSubmissions",value:await this.stateValues.nSubmissions+1});for(let e of await this.stateValues.awardChildren){let t=r.includes(e.componentName);i.push({updateType:"updateValue",componentName:e.componentName,stateVariable:"awarded",value:t}),i.push({updateType:"updateValue",componentName:e.componentName,stateVariable:"creditAchieved",value:e.stateValues.creditAchievedIfSubmit}),i.push({updateType:"updateValue",componentName:e.componentName,stateVariable:"fractionSatisfied",value:e.stateValues.fractionSatisfiedIfSubmit})}let l=[];for(let e of o)if(e.toString)try{l.push(e.toString())}catch(e){l.push("_")}else l.push(e);return i.push({updateType:"recordItemSubmission",itemNumber:await this.stateValues.inItemNumber,submittedComponent:this.componentName,response:o,responseText:l,creditAchieved:n}),await this.coreFunctions.performUpdate({updateInstructions:i,actionId:e,event:{verb:"submitted",object:{componentName:this.componentName,componentType:this.componentType},result:{response:o,responseText:l,creditAchieved:n}},suppressToast:await this.stateValues.suppressToast}),await this.coreFunctions.triggerChainedActions({componentName:this.componentName})}}class Award extends BaseComponent{static componentType="award";static rendererType=void 0;static includeBlankStringChildren=!0;static removeBlankStringChildrenPostSugar=!0;static variableForPlainMacro="awarded";static variableForPlainCopy="awarded";static createAttributesObject(){let e=super.createAttributesObject();return e.credit={createComponentOfType:"number",createStateVariable:"credit",defaultValue:1,public:!0,attributesForCreatedComponent:{convertBoolean:!0}},e.matchPartial={createComponentOfType:"boolean",createStateVariable:"matchPartial",defaultValue:!1,public:!0,fallBackToParentStateVariable:"matchPartial"},e.symbolicEquality={createComponentOfType:"boolean",createStateVariable:"symbolicEquality",defaultValue:!1,public:!0,fallBackToParentStateVariable:"symbolicEquality"},e.expandOnCompare={createComponentOfType:"boolean",createStateVariable:"expandOnCompare",defaultValue:!1,public:!0,fallBackToParentStateVariable:"expandOnCompare"},e.simplifyOnCompare={createComponentOfType:"text",createStateVariable:"simplifyOnCompare",defaultValue:"none",toLowerCase:!0,valueTransformations:{"":"full",true:"full"},validValues:["none","full","numbers","numberspreserveorder"],public:!0,fallBackToParentStateVariable:"simplifyOnCompare"},e.unorderedCompare={createComponentOfType:"boolean",createStateVariable:"unorderedCompare",defaultValue:!1,public:!0,fallBackToParentStateVariable:"unorderedCompare"},e.matchByExactPositions={createComponentOfType:"boolean",createStateVariable:"matchByExactPositions",defaultValue:!1,public:!0,fallBackToParentStateVariable:"matchByExactPositions"},e.allowedErrorInNumbers={createComponentOfType:"number",createStateVariable:"allowedErrorInNumbers",defaultValue:0,public:!0,fallBackToParentStateVariable:"allowedErrorInNumbers"},e.includeErrorInNumberExponents={createComponentOfType:"boolean",createStateVariable:"includeErrorInNumberExponents",defaultValue:!1,public:!0,fallBackToParentStateVariable:"includeErrorInNumberExponents"},e.allowedErrorIsAbsolute={createComponentOfType:"boolean",createStateVariable:"allowedErrorIsAbsolute",defaultValue:!1,public:!0,fallBackToParentStateVariable:"allowedErrorIsAbsolute"},e.nSignErrorsMatched={createComponentOfType:"number",createStateVariable:"nSignErrorsMatched",defaultValue:0,public:!0,fallBackToParentStateVariable:"nSignErrorsMatched"},e.nPeriodicSetMatchesRequired={createComponentOfType:"integer",createStateVariable:"nPeriodicSetMatchesRequired",defaultValue:3,public:!0,fallBackToParentStateVariable:"nPeriodicSetMatchesRequired"},e.caseInsensitiveMatch={createComponentOfType:"boolean",createStateVariable:"caseInsensitiveMatch",defaultValue:!1,public:!0,fallBackToParentStateVariable:"caseInsensitiveMatch"},e.matchBlanks={createComponentOfType:"boolean",createStateVariable:"matchBlanks",defaultValue:!1,public:!0,fallBackToParentStateVariable:"matchBlanks"},e.feedbackCodes={createComponentOfType:"textList",createStateVariable:"feedbackCodes",defaultValue:[],public:!0},e.feedbackText={createComponentOfType:"text",createStateVariable:"feedbackText",defaultValue:null,public:!0},e.sourcesAreResponses={createPrimitiveOfType:"string"},e.splitSymbols={createComponentOfType:"boolean",createStateVariable:"splitSymbols",defaultValue:!0,public:!0,fallBackToParentStateVariable:"splitSymbols"},e.parseScientificNotation={createComponentOfType:"boolean",createStateVariable:"parseScientificNotation",defaultValue:!1,public:!0,fallBackToParentStateVariable:"parseScientificNotation"},e}static preprocessSerializedChildren({serializedChildren:e,attributes:t,componentName:n}){if(t.sourcesAreResponses){let r,a=t.sourcesAreResponses.primitive.split(/\s+/).filter((e=>e));r=t.newNamespace?.primitive?n+"/":getNamespaceFromName(n);for(let t of a){let n;if("/"===t[0])n=t;else if("../"===t.slice(0,3)){let e=getNamespaceFromName(r.slice(0,r.length-1)),a=t.slice(3);for(;"../"===a.slice(0,3);){if("/"===e){n=null;break}e=getNamespaceFromName(e.slice(0,e.length-1)),a=a.slice(3)}null!==n&&(n=e+a)}else n=r+t;addResponsesToDescendantsWithTarget(e,t,n)}}}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e,parentAttributes:t,componentInfoObjects:n}){for(;"string"==typeof e[0]&&""===e[0].trim();)e=e.slice(1);let r=e.length;for(;"string"==typeof e[r-1]&&""===e[r-1].trim();)r=(e=e.slice(0,r-1)).length;if(1===e.length&&"object"==typeof e[0])return{success:!1};let a,i=n.componentIsSpecifiedType,s=!1,o=!1,l=!1;for(let t of e)"object"==typeof t&&(i(t,"math")||i(t,"number")||i(t,"mathList")||i(t,"numberList")?s=!0:i(t,"text")||i(t,"textList")?o=!0:(i(t,"boolean")||i(t,"booleanList"))&&(l=!0));return t.type?(a=t.type,["math","text","boolean"].includes(a)||(console.warn(`Invalid type ${a}`),a="math")):a=s?"math":o?"text":l?"boolean":"math",{success:!0,newChildren:[{componentType:a,children:e}]}}}),e}static returnChildGroups(){return[{group:"whens",componentTypes:["when"]},{group:"maths",componentTypes:["math"]},{group:"numbers",componentTypes:["number"]},{group:"texts",componentTypes:["text"]},{group:"booleans",componentTypes:["boolean"]},{group:"mathLists",componentTypes:["mathList"]},{group:"numberLists",componentTypes:["numberList"]},{group:"textLists",componentTypes:["textList"]},{group:"booleanLists",componentTypes:["booleanList"]},{group:"otherComparableTypes",componentTypes:["orbitalDiagram"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.parsedExpression={additionalStateVariablesDefined:["requireInputInAnswer"],returnDependencies:()=>({whenChild:{dependencyType:"child",childGroups:["whens"]},typeChildren:{dependencyType:"child",childGroups:["maths","numbers","texts","booleans","mathLists","numberLists","textLists","booleanLists","otherComparableTypes"]}}),definition:function({dependencyValues:e}){let t=null,n=!1;return 0==e.whenChild.length&&e.typeChildren.length>0&&(n=!0,t=me$3.fromAst(["=","comp1","comp2"])),{setValue:{parsedExpression:t,requireInputInAnswer:n}}}},e.creditAchievedIfSubmit={public:!0,shadowingInstructions:{createComponentOfType:"number"},additionalStateVariablesDefined:[{variableName:"fractionSatisfiedIfSubmit",public:!0,shadowingInstructions:{createComponentOfType:"number"}}],returnDependencies:()=>({credit:{dependencyType:"stateVariable",variableName:"credit"},whenChild:{dependencyType:"child",childGroups:["whens"],variableNames:["fractionSatisfied"]},mathChild:{dependencyType:"child",childGroups:["maths"],variableNames:["value","unordered"]},numberChild:{dependencyType:"child",childGroups:["numbers"],variableNames:["value"]},textChild:{dependencyType:"child",childGroups:["texts"],variableNames:["value"]},booleanChild:{dependencyType:"child",childGroups:["booleans"],variableNames:["value"]},mathListChild:{dependencyType:"child",childGroups:["mathLists"],variableNames:["maths","unordered"]},numberListChild:{dependencyType:"child",childGroups:["numberLists"],variableNames:["numbers","unordered"]},textListChild:{dependencyType:"child",childGroups:["textLists"],variableNames:["texts","unordered"]},booleanListChild:{dependencyType:"child",childGroups:["booleanLists"],variableNames:["booleans","unordered"]},otherComparableChild:{dependencyType:"child",childGroups:["otherComparableTypes"],variableNames:["value"]},answerInput:{dependencyType:"parentStateVariable",variableName:"inputChildWithValues"},parsedExpression:{dependencyType:"stateVariable",variableName:"parsedExpression"},matchPartial:{dependencyType:"stateVariable",variableName:"matchPartial"},symbolicEquality:{dependencyType:"stateVariable",variableName:"symbolicEquality"},expandOnCompare:{dependencyType:"stateVariable",variableName:"expandOnCompare"},simplifyOnCompare:{dependencyType:"stateVariable",variableName:"simplifyOnCompare"},unorderedCompare:{dependencyType:"stateVariable",variableName:"unorderedCompare"},matchByExactPositions:{dependencyType:"stateVariable",variableName:"matchByExactPositions"},allowedErrorInNumbers:{dependencyType:"stateVariable",variableName:"allowedErrorInNumbers"},includeErrorInNumberExponents:{dependencyType:"stateVariable",variableName:"includeErrorInNumberExponents"},allowedErrorIsAbsolute:{dependencyType:"stateVariable",variableName:"allowedErrorIsAbsolute"},nSignErrorsMatched:{dependencyType:"stateVariable",variableName:"nSignErrorsMatched"},nPeriodicSetMatchesRequired:{dependencyType:"stateVariable",variableName:"nPeriodicSetMatchesRequired"},caseInsensitiveMatch:{dependencyType:"stateVariable",variableName:"caseInsensitiveMatch"},matchBlanks:{dependencyType:"stateVariable",variableName:"matchBlanks"}}),definition:function({dependencyValues:e,usedDefault:t}){let n;if(e.whenChild.length>0)n=e.whenChild[0].stateValues.fractionSatisfied;else{if(!e.answerInput||!e.parsedExpression)return{setValue:{creditAchievedIfSubmit:0,fractionSatisfiedIfSubmit:0}};n=evaluateLogicDirectlyFromChildren({dependencyValues:e,usedDefault:t})}n=Math.max(0,Math.min(1,n));let r=0;return Number.isFinite(e.credit)&&(r=Math.max(0,Math.min(1,e.credit))*n),{setValue:{fractionSatisfiedIfSubmit:n,creditAchievedIfSubmit:r}}}},e.fractionSatisfied={public:!0,shadowingInstructions:{createComponentOfType:"number"},defaultValue:0,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{fractionSatisfied:!0}}),inverseDefinition:function({desiredStateVariableValues:e,initialChange:t}){return t?{success:!0,instructions:[{setEssentialValue:"fractionSatisfied",value:e.fractionSatisfied}]}:{success:!1}}},e.creditAchieved={public:!0,shadowingInstructions:{createComponentOfType:"number"},defaultValue:0,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{creditAchieved:!0}}),inverseDefinition:function({desiredStateVariableValues:e,initialChange:t}){return t?{success:!0,instructions:[{setEssentialValue:"creditAchieved",value:e.creditAchieved}]}:{success:!1}}},e.awarded={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},defaultValue:!1,hasEssential:!0,doNotShadowEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{awarded:!0}}),inverseDefinition:function({desiredStateVariableValues:e,initialChange:t}){return t?{success:!0,instructions:[{setEssentialValue:"awarded",value:e.awarded}]}:{success:!1}}},e.allFeedbacks={returnDependencies:()=>({feedbackText:{dependencyType:"stateVariable",variableName:"feedbackText"},feedbackCodes:{dependencyType:"stateVariable",variableName:"feedbackCodes"},feedbackDefinitionAncestor:{dependencyType:"ancestor",variableNames:["feedbackDefinitions"]},awarded:{dependencyType:"stateVariable",variableName:"awarded"}}),definition:function({dependencyValues:e}){if(!e.awarded)return{setValue:{allFeedbacks:[]}};let t=[],n=e.feedbackDefinitionAncestor.stateValues.feedbackDefinitions;for(let r of e.feedbackCodes){let e=n[r.toLowerCase()];e&&t.push(e)}return null!==e.feedbackText&&t.push(e.feedbackText),{setValue:{allFeedbacks:t}}}},e.numberFeedbacks={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({allFeedbacks:{dependencyType:"stateVariable",variableName:"allFeedbacks"}}),definition:({dependencyValues:e})=>({setValue:{numberFeedbacks:e.allFeedbacks.length},checkForActualChange:{numberFeedbacks:!0}})},e.feedbacks={public:!0,shadowingInstructions:{createComponentOfType:"feedback"},isArray:!0,entryPrefixes:["feedback"],returnArraySizeDependencies:()=>({numberFeedbacks:{dependencyType:"stateVariable",variableName:"numberFeedbacks"}}),returnArraySize:({dependencyValues:e})=>[e.numberFeedbacks],returnArrayDependenciesByKey:()=>({globalDependencies:{allFeedbacks:{dependencyType:"stateVariable",variableName:"allFeedbacks"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n=0;n0?n.textChildrenByCode.comp2=e.textChild[0]:e.mathChild.length>0?n.mathChildrenByCode.comp2=e.mathChild[0]:e.numberChild.length>0?n.numberChildrenByCode.comp2=e.numberChild[0]:e.booleanChild.length>0?n.booleanChildrenByCode.comp2=e.booleanChild[0]:e.textListChild.length>0?n.textListChildrenByCode.comp2=e.textListChild[0]:e.mathListChild.length>0?n.mathListChildrenByCode.comp2=e.mathListChild[0]:e.numberListChild.length>0?n.numberListChildrenByCode.comp2=e.numberListChild[0]:e.booleanListChild.length>0?n.booleanListChildrenByCode.comp2=e.booleanListChild[0]:e.otherComparableChild.length>0&&(n.otherChildrenByCode.comp2=e.otherComparableChild[0]);let a=e.answerInput.stateValues.immediateValue;void 0===a&&(a=e.answerInput.stateValues.value);let i={stateValues:{value:a}};return"textInput"===e.answerInput.componentType?n.textChildrenByCode.comp1=i:"booleanInput"===e.answerInput.componentType?n.booleanChildrenByCode.comp1=i:n.mathChildrenByCode.comp1=i,evaluateLogic({logicTree:e.parsedExpression.tree,canOverrideUnorderedCompare:r,dependencyValues:n})}function addResponsesToDescendantsWithTarget(e,t,n){for(let r of e){let e=r.props;if(e&&0!==Object.keys(e).length||(e=r.doenetAttributes),e)for(let a in e)if("target"===a.toLowerCase()&&e[a]===t||"targetcomponentname"===a.toLowerCase()&&e[a]===n){r.attributes||(r.attributes={});let e=Object.keys(r.attributes).map((e=>e.toLowerCase())).includes("isresponse");e||(r.attributes.isResponse=!0)}r.children&&addResponsesToDescendantsWithTarget(r.children,t,n)}}class When extends BooleanComponent{static componentType="when";static rendererType=void 0;static stateVariableForAttributeValue="conditionSatisfied";static createAttributesObject(){let e=super.createAttributesObject();e.matchPartial={createComponentOfType:"boolean",createStateVariable:"matchPartial",defaultValue:!1,public:!0,fallBackToParentStateVariable:"matchPartial"};for(let t of["symbolicEquality","expandOnCompare","simplifyOnCompare","unorderedCompare","matchByExactPositions","allowedErrorInNumbers","includeErrorInNumberExponents","allowedErrorIsAbsolute","nSignErrorsMatched","nPeriodicSetMatchesRequired","caseInsensitiveMatch","matchBlanks"])e[t].fallBackToParentStateVariable=t;return e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.value={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},additionalStateVariablesDefined:[{variableName:"fractionSatisfied",public:!0,shadowingInstructions:{createComponentOfType:"number"}},{variableName:"conditionSatisfied",public:!0,shadowingInstructions:{createComponentOfType:"boolean"}}],returnDependencies:()=>({matchPartial:{dependencyType:"stateVariable",variableName:"matchPartial"},symbolicEquality:{dependencyType:"stateVariable",variableName:"symbolicEquality"},expandOnCompare:{dependencyType:"stateVariable",variableName:"expandOnCompare"},simplifyOnCompare:{dependencyType:"stateVariable",variableName:"simplifyOnCompare"},unorderedCompare:{dependencyType:"stateVariable",variableName:"unorderedCompare"},matchByExactPositions:{dependencyType:"stateVariable",variableName:"matchByExactPositions"},allowedErrorInNumbers:{dependencyType:"stateVariable",variableName:"allowedErrorInNumbers"},includeErrorInNumberExponents:{dependencyType:"stateVariable",variableName:"includeErrorInNumberExponents"},allowedErrorIsAbsolute:{dependencyType:"stateVariable",variableName:"allowedErrorIsAbsolute"},nSignErrorsMatched:{dependencyType:"stateVariable",variableName:"nSignErrorsMatched"},nPeriodicSetMatchesRequired:{dependencyType:"stateVariable",variableName:"nPeriodicSetMatchesRequired"},caseInsensitiveMatch:{dependencyType:"stateVariable",variableName:"caseInsensitiveMatch"},matchBlanks:{dependencyType:"stateVariable",variableName:"matchBlanks"},parsedExpression:{dependencyType:"stateVariable",variableName:"parsedExpression"},booleanChildrenByCode:{dependencyType:"stateVariable",variableName:"booleanChildrenByCode"},booleanListChildrenByCode:{dependencyType:"stateVariable",variableName:"booleanListChildrenByCode"},textChildrenByCode:{dependencyType:"stateVariable",variableName:"textChildrenByCode"},textListChildrenByCode:{dependencyType:"stateVariable",variableName:"textListChildrenByCode"},mathChildrenByCode:{dependencyType:"stateVariable",variableName:"mathChildrenByCode"},mathListChildrenByCode:{dependencyType:"stateVariable",variableName:"mathListChildrenByCode"},numberChildrenByCode:{dependencyType:"stateVariable",variableName:"numberChildrenByCode"},numberListChildrenByCode:{dependencyType:"stateVariable",variableName:"numberListChildrenByCode"},otherChildrenByCode:{dependencyType:"stateVariable",variableName:"otherChildrenByCode"}}),definition({dependencyValues:e,usedDefault:t}){if(null===e.parsedExpression)return{setValue:{conditionSatisfied:!1,value:!1,fractionSatisfied:0}};let n=t.unorderedCompare,r=evaluateLogic({logicTree:e.parsedExpression.tree,canOverrideUnorderedCompare:n,dependencyValues:e}),a=1===r;return{setValue:{fractionSatisfied:r,conditionSatisfied:a,value:a}}}},e}}class MathInput extends Input{constructor(e){super(e),Object.assign(this.actions,{updateRawValue:this.updateRawValue.bind(this),updateValue:this.updateValue.bind(this)}),this.externalActions={},Object.defineProperty(this.externalActions,"submitAnswer",{enumerable:!0,get:async function(){let e=await this.stateValues.answerAncestor;return null!==e?{componentName:e.componentName,actionName:"submitAnswer"}:void 0}.bind(this)})}static componentType="mathInput";static variableForPlainMacro="value";static variableForPlainCopy="value";static processWhenJustUpdatedForNewComponent=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.prefill={createComponentOfType:"math",createStateVariable:"prefill",defaultValue:me$3.fromAst("_"),public:!0,copyComponentAttributesForCreatedComponent:["format","functionSymbols","splitSymbols","parseScientificNotation"]},e.prefillLatex={createComponentOfType:"latex",createStateVariable:"prefillLatex",defaultValue:"",public:!0},e.format={createComponentOfType:"text",createStateVariable:"format",defaultValue:"text",public:!0},e.functionSymbols={createComponentOfType:"textList",createStateVariable:"functionSymbols",defaultValue:["f","g"],public:!0},e.splitSymbols={createComponentOfType:"boolean",createStateVariable:"splitSymbols",defaultValue:!0,public:!0,fallBackToParentStateVariable:"splitSymbols"},e.parseScientificNotation={createComponentOfType:"boolean",createStateVariable:"parseScientificNotation",defaultValue:!1,public:!0,fallBackToParentStateVariable:"parseScientificNotation"},e.displayDigits={createComponentOfType:"integer",createStateVariable:"displayDigits",defaultValue:10,public:!0},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.bindValueTo={createComponentOfType:"math"},e.unionFromU={createComponentOfType:"boolean",createStateVariable:"unionFromU",defaultValue:!1,public:!0},e.hideNaN={createComponentOfType:"boolean",createStateVariable:"hideNaN",defaultValue:!0,public:!0},e.removeStrings={createComponentOfType:"textList",createStateVariable:"removeStrings",defaultValue:null},e}static returnSugarInstructions(){let e=[];return e.push({replacementFunction:function({matchedChildren:e}){return 0===e.length?{success:!1}:{success:!0,newChildren:[{componentType:"math",children:e}]}}}),e}static returnChildGroups(){return[{group:"maths",componentTypes:["math"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.value={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]},hasEssential:!0,shadowVariable:!0,returnDependencies:()=>({mathChild:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]},bindValueTo:{dependencyType:"attributeComponent",attributeName:"bindValueTo",variableNames:["value"]},prefill:{dependencyType:"stateVariable",variableName:"prefill"},prefillLatex:{dependencyType:"stateVariable",variableName:"prefillLatex"},unionFromU:{dependencyType:"stateVariable",variableName:"unionFromU"},functionSymbols:{dependencyType:"stateVariable",variableName:"functionSymbols"},splitSymbols:{dependencyType:"stateVariable",variableName:"splitSymbols"},parseScientificNotation:{dependencyType:"stateVariable",variableName:"parseScientificNotation"}}),set:convertValueToMathExpression,definition:function({dependencyValues:e,usedDefault:t}){return e.mathChild.length>0?{setValue:{value:e.mathChild[0].stateValues.value}}:e.bindValueTo?{setValue:{value:e.bindValueTo.stateValues.value}}:{useEssentialOrDefaultValue:{value:{get defaultValue(){return!t.prefill||t.prefillLatex?e.prefill:calculateMathExpressionFromLatex({latex:e.prefillLatex,unionFromU:e.unionFromU,functionSymbols:e.functionSymbols,splitSymbols:e.splitSymbols,parseScientificNotation:e.parseScientificNotation})}}}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){return t.mathChild.length>0?{success:!0,instructions:[{setDependency:"mathChild",desiredValue:e.value,variableIndex:0,childIndex:0}]}:t.bindValueTo?{success:!0,instructions:[{setDependency:"bindValueTo",desiredValue:e.value,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"value",value:e.value}]}}},e.immediateValue={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]},hasEssential:!0,shadowVariable:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),set:convertValueToMathExpression,definition:function({dependencyValues:e,changes:t,justUpdatedForNewComponent:n,usedDefault:r}){return!t.value||n||r.value?{useEssentialOrDefaultValue:{immediateValue:{defaultValue:e.value}}}:{setValue:{immediateValue:e.value},setEssentialValue:{immediateValue:e.value}}},inverseDefinition:function({desiredStateVariableValues:e,initialChange:t,shadowedVariable:n}){let r=[{setEssentialValue:"immediateValue",value:e.immediateValue}];return t||n||r.push({setDependency:"value",desiredValue:e.immediateValue}),{success:!0,instructions:r}}},e.valueForDisplay={forRenderer:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"}}),set:convertValueToMathExpression,definition:function({dependencyValues:e,usedDefault:t}){return{setValue:{valueForDisplay:roundForDisplay({value:e.value,dependencyValues:e,usedDefault:t})}}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({valueForDisplay:{dependencyType:"stateVariable",variableName:"valueForDisplay"}}),definition:function({dependencyValues:e}){return{setValue:{text:e.valueForDisplay.toString()}}}},e.dontUpdateRawValueInDefinition={defaultValue:!1,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{dontUpdateRawValueInDefinition:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"dontUpdateRawValueInDefinition",value:e.dontUpdateRawValueInDefinition}]})},e.rawRendererValue={forRenderer:!0,hasEssential:!0,shadowVariable:!0,defaultValue:"",provideEssentialValuesInDefinition:!0,public:!0,shadowingInstructions:{createComponentOfType:"text"},additionalStateVariablesDefined:[{variableName:"lastValueForDisplay",hasEssential:!0,shadowVariable:!0,defaultValue:null,set:convertValueToMathExpression}],returnDependencies:()=>({immediateValue:{dependencyType:"stateVariable",variableName:"immediateValue"},valueForDisplay:{dependencyType:"stateVariable",variableName:"valueForDisplay"},hideNaN:{dependencyType:"stateVariable",variableName:"hideNaN"},dontUpdateRawValueInDefinition:{dependencyType:"stateVariable",variableName:"dontUpdateRawValueInDefinition"},prefill:{dependencyType:"stateVariable",variableName:"prefill"},prefillLatex:{dependencyType:"stateVariable",variableName:"prefillLatex"}}),definition({dependencyValues:e,essentialValues:t,justUpdatedForNewComponent:n,usedDefault:r}){if(void 0!==t.rawRendererValue&&(n||deepCompare(t.lastValueForDisplay.tree,e.valueForDisplay.tree)||e.dontUpdateRawValueInDefinition))return{useEssentialOrDefaultValue:{rawRendererValue:!0,lastValueForDisplay:!0}};{let t;return t=r.immediateValue&&r.prefill&&!r.prefillLatex?stripLatex(e.prefillLatex):stripLatex(e.valueForDisplay.toLatex({showBlanks:!1})),e.hideNaN&&"NaN"===t&&(t=""),{setValue:{rawRendererValue:t,lastValueForDisplay:e.valueForDisplay},setEssentialValue:{rawRendererValue:t,lastValueForDisplay:e.valueForDisplay}}}},async inverseDefinition({desiredStateVariableValues:e,stateValues:t,essentialValues:n,dependencyValues:r,componentName:a}){let i=[];if("string"==typeof e.rawRendererValue){let r=n.rawRendererValue,a=e.rawRendererValue;r!==a&&i.push({setEssentialValue:"rawRendererValue",value:a});let s=await t.unionFromU,o=await t.functionSymbols,l=await t.splitSymbols,u=await t.parseScientificNotation,c=await t.removeStrings,p=calculateMathExpressionFromLatex({latex:r,unionFromU:s,functionSymbols:o,splitSymbols:l,parseScientificNotation:u,removeStrings:c}),d=calculateMathExpressionFromLatex({latex:a,unionFromU:s,functionSymbols:o,splitSymbols:l,parseScientificNotation:u,removeStrings:c});deepCompare(d.tree,p.tree)||i.push({setDependency:"immediateValue",desiredValue:d,treatAsInitialChange:!0})}else if(e.rawRendererValue instanceof me$3.class){i.push({setEssentialValue:"lastValueForDisplay",value:e.rawRendererValue});let a=await t.unionFromU,s=await t.functionSymbols,o=await t.splitSymbols,l=await t.parseScientificNotation,u=await t.removeStrings,c=calculateMathExpressionFromLatex({latex:n.rawRendererValue,unionFromU:a,functionSymbols:s,splitSymbols:o,parseScientificNotation:l,removeStrings:u});if(!deepCompare(e.rawRendererValue.tree,c.tree)){let t=stripLatex(e.rawRendererValue.toLatex({showBlanks:!1}));r.hideNaN&&"NaN"===t&&(t=""),i.push({setEssentialValue:"rawRendererValue",value:t})}}else e.lastValueForDisplay instanceof me$3.class&&i.push({setEssentialValue:"lastValueForDisplay",value:e.lastValueForDisplay});return{success:!0,instructions:i}}},e.componentType={returnDependencies:()=>({}),definition:()=>({setValue:{componentType:"math"}})},e}async updateRawValue({rawRendererValue:e,actionId:t}){if(!await this.stateValues.disabled)return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rawRendererValue",value:e},{updateType:"setComponentNeedingUpdateValue",componentName:this.componentName}],transient:!0,actionId:t});this.coreFunctions.resolveAction({actionId:t})}async updateValue({actionId:e}){if(await this.stateValues.disabled)this.coreFunctions.resolveAction({actionId:e});else{let t=await this.stateValues.immediateValue;if(!deepCompare((await this.stateValues.value).tree,t.tree)){let n=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"dontUpdateRawValueInDefinition",value:!0},{updateType:"updateValue",componentName:this.componentName,stateVariable:"value",value:t},{updateType:"executeUpdate"},{updateType:"updateValue",componentName:this.componentName,stateVariable:"dontUpdateRawValueInDefinition",value:!1},{updateType:"updateValue",componentName:this.componentName,stateVariable:"immediateValue",valueOfStateVariable:"value"},{updateType:"unsetComponentNeedingUpdateValue"}];"_"!==t.tree?n.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"rawRendererValue",valueOfStateVariable:"valueForDisplay"}):n.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"lastValueForDisplay",valueOfStateVariable:"valueForDisplay"});let r={verb:"answered",object:{componentName:this.componentName,componentType:this.componentType},result:{response:t,responseText:t.toString()}},a=await this.stateValues.answerAncestor;return a&&(r.context={answerAncestor:a.componentName}),await this.coreFunctions.performUpdate({updateInstructions:n,actionId:e,event:r}),await this.coreFunctions.triggerChainedActions({componentName:this.componentName})}this.coreFunctions.resolveAction({actionId:e})}}static adapters=[{stateVariable:"value",stateVariablesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]}]}function calculateMathExpressionFromLatex({latex:e,unionFromU:t,functionSymbols:n,splitSymbols:r,parseScientificNotation:a,removeStrings:i}){let s;if(i)for(let t of i)["$","%"].includes(t)&&(t="\\"+t),e=e.replaceAll(t,"");e=normalizeLatexString(e,{unionFromU:t});let o=getFromLatex({functionSymbols:n,splitSymbols:r,parseScientificNotation:a});try{s=o(e)}catch(e){s=me$3.fromAst("_")}return s}class Textinput extends Input{constructor(e){super(e),Object.assign(this.actions,{updateImmediateValue:this.updateImmediateValue.bind(this),updateValue:this.updateValue.bind(this)}),this.externalActions={},Object.defineProperty(this.externalActions,"submitAnswer",{enumerable:!0,get:async function(){let e=await this.stateValues.answerAncestor;return null!==e?{componentName:e.componentName,actionName:"submitAnswer"}:void 0}.bind(this)})}static componentType="textInput";static variableForPlainMacro="value";static variableForPlainCopy="value";static processWhenJustUpdatedForNewComponent=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.prefill={createComponentOfType:"text",createStateVariable:"prefill",defaultValue:"",public:!0},e.size={createComponentOfType:"number",createStateVariable:"size",defaultValue:10,forRenderer:!0,public:!0},e.bindValueTo={createComponentOfType:"text"},e.expanded={createComponentOfType:"boolean",createStateVariable:"expanded",defaultValue:!1,forRenderer:!0,public:!0},e.width={createComponentOfType:"_componentSize",createStateVariable:"width",defaultValue:{size:600,isAbsolute:!0},forRenderer:!0,public:!0},e.height={createComponentOfType:"_componentSize",createStateVariable:"height",defaultValue:{size:120,isAbsolute:!0},forRenderer:!0,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.value={public:!0,shadowingInstructions:{createComponentOfType:"text"},hasEssential:!0,shadowVariable:!0,returnDependencies:()=>({bindValueTo:{dependencyType:"attributeComponent",attributeName:"bindValueTo",variableNames:["value"]},prefill:{dependencyType:"stateVariable",variableName:"prefill"}}),definition:function({dependencyValues:e}){return e.bindValueTo?{setValue:{value:e.bindValueTo.stateValues.value}}:{useEssentialOrDefaultValue:{value:{defaultValue:e.prefill}}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){return t.bindValueTo?{success:!0,instructions:[{setDependency:"bindValueTo",desiredValue:e.value,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"value",value:e.value}]}}},e.immediateValue={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,hasEssential:!0,shadowVariable:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:function({dependencyValues:e,changes:t,justUpdatedForNewComponent:n}){return t.value&&!n?{setValue:{immediateValue:e.value},setEssentialValue:{immediateValue:e.value}}:{useEssentialOrDefaultValue:{immediateValue:{defaultValue:e.value}}}},inverseDefinition:function({desiredStateVariableValues:e,initialChange:t,shadowedVariable:n}){let r=[{setEssentialValue:"immediateValue",value:e.immediateValue}];return t||n||r.push({setDependency:"value",desiredValue:e.immediateValue}),{success:!0,instructions:r}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:function({dependencyValues:e}){return{setValue:{text:e.value}}}},e.componentType={returnDependencies:()=>({}),definition:()=>({setValue:{componentType:"text"}})},e}async updateImmediateValue({text:e,actionId:t}){if(!await this.stateValues.disabled)return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"immediateValue",value:e},{updateType:"setComponentNeedingUpdateValue",componentName:this.componentName}],transient:!0,actionId:t});this.coreFunctions.resolveAction({actionId:t})}async updateValue({actionId:e}){if(!await this.stateValues.disabled){let t=await this.stateValues.immediateValue;if(await this.stateValues.value!==t){let n=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"value",value:t},{updateType:"executeUpdate"},{updateType:"updateValue",componentName:this.componentName,stateVariable:"immediateValue",valueOfStateVariable:"value"},{updateType:"unsetComponentNeedingUpdateValue"}],r={verb:"answered",object:{componentName:this.componentName,componentType:this.componentType},result:{response:t,responseText:t}},a=await this.stateValues.answerAncestor;return a&&(r.context={answerAncestor:a.componentName}),await this.coreFunctions.performUpdate({updateInstructions:n,actionId:e,event:r}),await this.coreFunctions.triggerChainedActions({componentName:this.componentName})}}this.coreFunctions.resolveAction({actionId:e})}}class BooleanInput extends Input{constructor(e){super(e),Object.assign(this.actions,{updateBoolean:this.updateBoolean.bind(this)}),this.externalActions={},Object.defineProperty(this.externalActions,"submitAnswer",{enumerable:!0,get:async function(){let e=await this.stateValues.answerAncestor;return null!==e?{componentName:e.componentName,actionName:"submitAnswer"}:void 0}.bind(this)})}static componentType="booleanInput";static variableForPlainMacro="value";static variableForPlainCopy="value";static createAttributesObject(){let e=super.createAttributesObject();return e.prefill={createComponentOfType:"boolean",createStateVariable:"prefill",defaultValue:!1,public:!0},e.labelIsName={createComponentOfType:"boolean",createStateVariable:"labelIsName",defaultValue:!1,public:!0},e.asToggleButton={createComponentOfType:"boolean",createStateVariable:"asToggleButton",defaultValue:!1,forRenderer:!0,public:!0},e.bindValueTo={createComponentOfType:"boolean"},e}static returnChildGroups(){return[{group:"labels",componentTypes:["label"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnLabelStateVariableDefinitions();return Object.assign(e,t),e.value={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,hasEssential:!0,shadowVariable:!0,returnDependencies:()=>({bindValueTo:{dependencyType:"attributeComponent",attributeName:"bindValueTo",variableNames:["value"]},prefill:{dependencyType:"stateVariable",variableName:"prefill"}}),definition:function({dependencyValues:e}){return e.bindValueTo?{setValue:{value:e.bindValueTo.stateValues.value}}:{useEssentialOrDefaultValue:{value:{defaultValue:e.prefill}}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){return t.bindValueTo?{success:!0,instructions:[{setDependency:"bindValueTo",desiredValue:e.value,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"value",value:e.value}]}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:function({dependencyValues:e}){return{setValue:{text:e.value?"true":"false"}}}},e.componentType={returnDependencies:()=>({}),definition:()=>({setValue:{componentType:"boolean"}})},e}static adapters=["value"];async updateBoolean({boolean:e,actionId:t}){if(!await this.stateValues.disabled){let n=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"value",value:e}],r={verb:"selected",object:{componentName:this.componentName,componentType:this.componentType},result:{response:e,responseText:e.toString()}},a=await this.stateValues.answerAncestor;return a&&(r.context={answerAncestor:a.componentName}),await this.coreFunctions.performUpdate({updateInstructions:n,event:r,actionId:t}),await this.coreFunctions.triggerChainedActions({componentName:this.componentName})}this.coreFunctions.resolveAction({actionId:t})}}class Choiceinput extends Input{constructor(e){super(e),Object.assign(this.actions,{updateSelectedIndices:this.updateSelectedIndices.bind(this)}),this.externalActions={},Object.defineProperty(this.externalActions,"submitAnswer",{enumerable:!0,get:async function(){let e=await this.stateValues.answerAncestor;return null!==e?{componentName:e.componentName,actionName:"submitAnswer"}:void 0}.bind(this)})}static componentType="choiceInput";static renderChildren=!0;static variableForPlainMacro="values";static variableForPlainCopy="values";static createsVariants=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.selectMultiple={createComponentOfType:"boolean",createStateVariable:"selectMultiple",defaultValue:!1,public:!0,forRenderer:!0,fallBackToParentStateVariable:"selectMultiple"},e.matchPartial={createComponentOfType:"boolean",createStateVariable:"matchPartial",defaultValue:!1,public:!0,fallBackToParentStateVariable:"matchPartial"},e.inline={createComponentOfType:"boolean"},e.shuffleOrder={createPrimitiveOfType:"boolean",createStateVariable:"shuffleOrder",defaultValue:!1,public:!0},e.preselectChoice={createComponentOfType:"number",createStateVariable:"preselectChoice",defaultValue:null},e.bindValueTo={createComponentOfType:"text"},e.placeHolder={createComponentOfType:"text",createStateVariable:"placeHolder",defaultValue:"",forRenderer:!0},e.submitLabel={createComponentOfType:"text",createStateVariable:"submitLabel",defaultValue:"Check Work",public:!0,forRenderer:!0,fallBackToParentStateVariable:"submitLabel"},e.submitLabelNoCorrectness={createComponentOfType:"text",createStateVariable:"submitLabelNoCorrectness",defaultValue:"Submit Response",public:!0,forRenderer:!0,fallBackToParentStateVariable:"submitLabelNoCorrectness"},e}static returnChildGroups(){return[{group:"choices",componentTypes:["choice"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.inline={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,defaultValue:!1,hasEssential:!0,returnDependencies:()=>({inlineAttr:{dependencyType:"attributeComponent",attributeName:"inline",variableNames:["value"]},parentInline:{dependencyType:"parentStateVariable",variableName:"inline"}}),definition:({dependencyValues:e})=>e.inlineAttr?{setValue:{inline:e.inlineAttr.stateValues.value}}:null!==e.parentInline?{setValue:{inline:e.parentInline}}:{useEssentialOrDefaultValue:{inline:{}}}},e.numberChoices={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({choiceChildren:{dependencyType:"child",childGroups:["choices"]}}),definition:({dependencyValues:e})=>({setValue:{numberChoices:e.choiceChildren.length}})},e.choiceOrder={forRenderer:!0,shadowVariable:!0,returnDependencies:({sharedParameters:e})=>({choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["text"]},shuffleOrder:{dependencyType:"stateVariable",variableName:"shuffleOrder"},variantSeed:{dependencyType:"value",value:e.variantSeed},rngClass:{dependencyType:"value",value:e.rngClass,doNotProxy:!0},variants:{dependencyType:"variants"}}),definition:function({dependencyValues:e}){let t,n=e.choiceChildren.length;if(e.shuffleOrder){let r=e.variants?.desiredVariant?.indices;if(void 0!==r)if(r.length!==n)console.warn("Ignoring indices specified for choiceInput as number of indices doesn't match number of choice children.");else{if(r=r.map(Number),!r.every(Number.isInteger))throw Error("All indices specified for choiceInput must be integers");if(r.every((e=>e>=1&&e<=n)))return{setValue:{choiceOrder:r}};console.warn("Ignoring indices specified for choiceInput as some indices out of range.")}let a=e.rngClass(e.variantSeed+"co");t=[...Array(n).keys()].map((e=>e+1));for(let e=n-1;e>0;e--){const n=a(),r=Math.floor(n*(e+1));[t[e],t[r]]=[t[r],t[e]]}}else t=[...Array(n).keys()].map((e=>e+1));return{setValue:{choiceOrder:t}}}},e.generatedVariantInfo={additionalStateVariablesDefined:["isVariantComponent"],returnDependencies:({componentInfoObjects:e,sharedParameters:t})=>({variantSeed:{dependencyType:"value",value:t.variantSeed},choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},shuffleOrder:{dependencyType:"stateVariable",variableName:"shuffleOrder"},variantDescendants:{dependencyType:"descendant",componentTypes:Object.keys(e.componentTypesCreatingVariants),variableNames:["isVariantComponent","generatedVariantInfo"],useReplacementsForComposites:!0,recurseToMatchedChildren:!1,variablesOptional:!0,includeNonActiveChildren:!0,ignoreReplacementsOfEncounteredComposites:!0}}),definition({dependencyValues:e,componentName:t}){let n={seed:e.variantSeed,meta:{createdBy:t}};e.shuffleOrder&&(n.indices=e.choiceOrder);let r=n.subvariants=[];for(let t of e.variantDescendants)t.stateValues.isVariantComponent?r.push(t.stateValues.generatedVariantInfo):t.stateValues.generatedVariantInfo&&r.push(...t.stateValues.generatedVariantInfo.subvariants);return{setValue:{generatedVariantInfo:n,isVariantComponent:!0}}}},e.choiceChildrenOrdered={additionalStateVariablesDefined:[{variableName:"numberChoices",public:!0,shadowingInstructions:{createComponentOfType:"number"}}],returnDependencies:()=>({choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},choiceChildren:{dependencyType:"child",childGroups:["choices"]}}),definition:function({dependencyValues:e}){let t=e.choiceChildren.length,n=e.choiceOrder.map((t=>e.choiceChildren[t-1]));return{setValue:{choiceChildrenOrdered:n,numberChoices:t}}}},e.choiceTexts={public:!0,shadowingInstructions:{createComponentOfType:"text"},isArray:!0,entryPrefixes:["choiceText"],forRenderer:!0,returnArraySizeDependencies:()=>({numberChoices:{dependencyType:"stateVariable",variableName:"numberChoices"}}),returnArraySize:({dependencyValues:e})=>[e.numberChoices],returnArrayDependenciesByKey:()=>({globalDependencies:{choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["text"]}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t=e.choiceOrder.map((t=>e.choiceChildren[t-1]));return{setValue:{choiceTexts:t.map((e=>e.stateValues.text))}}}},e.choiceMaths={public:!0,shadowingInstructions:{createComponentOfType:"math"},isArray:!0,entryPrefixes:["choiceMath"],forRenderer:!0,returnArraySizeDependencies:()=>({numberChoices:{dependencyType:"stateVariable",variableName:"numberChoices"}}),returnArraySize:({dependencyValues:e})=>[e.numberChoices],returnArrayDependenciesByKey:()=>({globalDependencies:{choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["math"]}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t=e.choiceOrder.map((t=>e.choiceChildren[t-1]));return{setValue:{choiceMaths:t.map((e=>e.stateValues.math))}}}},e.choicePreselects={isArray:!0,returnArraySizeDependencies:()=>({numberChoices:{dependencyType:"stateVariable",variableName:"numberChoices"}}),returnArraySize:({dependencyValues:e})=>[e.numberChoices],returnArrayDependenciesByKey:()=>({globalDependencies:{choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["preSelect"]}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t=e.choiceOrder.map((t=>e.choiceChildren[t-1]));return{setValue:{choicePreselects:t.map((e=>e.stateValues.preSelect))}}}},e.choicesDisabled={isArray:!0,forRenderer:!0,returnArraySizeDependencies:()=>({numberChoices:{dependencyType:"stateVariable",variableName:"numberChoices"}}),returnArraySize:({dependencyValues:e})=>[e.numberChoices],returnArrayDependenciesByKey:()=>({globalDependencies:{choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["disabled"]}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t=e.choiceOrder.map((t=>e.choiceChildren[t-1]));return{setValue:{choicesDisabled:t.map((e=>e.stateValues.disabled))}}}},e.choicesHidden={isArray:!0,forRenderer:!0,returnArraySizeDependencies:()=>({numberChoices:{dependencyType:"stateVariable",variableName:"numberChoices"}}),returnArraySize:({dependencyValues:e})=>[e.numberChoices],returnArrayDependenciesByKey:()=>({globalDependencies:{choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["hidden"]}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t=e.choiceOrder.map((t=>e.choiceChildren[t-1]));return{setValue:{choicesHidden:t.map((e=>e.stateValues.hidden))}}}},e.componentType={returnDependencies:()=>({choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["math"]}}),definition({dependencyValues:e}){let t="text";return e.choiceChildren.length>0&&e.choiceChildren.every((e=>e.stateValues.math))&&(t="math"),{setValue:{componentType:t}}}},e.indicesMatchedByBoundValue={returnDependencies:()=>({choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["text"]},bindValueTo:{dependencyType:"attributeComponent",attributeName:"bindValueTo",variableNames:["value"]},selectMultiple:{dependencyType:"stateVariable",variableName:"selectMultiple"}}),definition({dependencyValues:e}){let t=e.choiceOrder.map((t=>e.choiceChildren[t-1]));if(null!==e.bindValueTo){let n=t.map((e=>e.stateValues.text.toLowerCase().trim()));if(e.bindValueTo.stateValues.value){if(e.selectMultiple){let t=e.bindValueTo.stateValues.value.toLowerCase().split(",").map((e=>e.trim())),r=[];for(let e of t){let t=n.indexOf(e);-1===t||r.includes(t+1)||r.push(t+1)}return r.sort(((e,t)=>e-t)),{setValue:{indicesMatchedByBoundValue:r}}}{let t=n.indexOf(e.bindValueTo.stateValues.value.toLowerCase().trim());if(-1!==t)return{setValue:{indicesMatchedByBoundValue:[t+1]}}}}}return{setValue:{indicesMatchedByBoundValue:[]}}}},e.allSelectedIndices={hasEssential:!0,returnDependencies:()=>({choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["text"]},indicesMatchedByBoundValue:{dependencyType:"stateVariable",variableName:"indicesMatchedByBoundValue"},preselectChoice:{dependencyType:"stateVariable",variableName:"preselectChoice"},choicePreselects:{dependencyType:"stateVariable",variableName:"choicePreselects"},bindValueTo:{dependencyType:"attributeComponent",attributeName:"bindValueTo",variableNames:["value"]}}),definition:({dependencyValues:e})=>null!==e.bindValueTo?{setValue:{allSelectedIndices:e.indicesMatchedByBoundValue}}:{useEssentialOrDefaultValue:{allSelectedIndices:{get defaultValue(){let t=e.choicePreselects.indexOf(!0);return-1!==t?[t+1]:null!==e.preselectChoice?[e.preselectChoice]:[]}}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){if(null===t.bindValueTo)return{success:!0,instructions:[{setEssentialValue:"allSelectedIndices",value:e.allSelectedIndices}]};{let n="";if(e.allSelectedIndices.length>0){let r=t.choiceOrder.map((e=>t.choiceChildren[e-1])),a=[];for(let t of e.allSelectedIndices){let e=r[t-1];e&&a.push(e.stateValues.text)}n=a.join(", ")}return{success:!0,instructions:[{setDependency:"bindValueTo",desiredValue:n,variableIndex:0}]}}}},e.nSelectedIndices={returnDependencies:()=>({allSelectedIndices:{dependencyType:"stateVariable",variableName:"allSelectedIndices"}}),definition:({dependencyValues:e})=>({setValue:{nSelectedIndices:e.allSelectedIndices.length}})},e.selectedIndices={public:!0,shadowingInstructions:{createComponentOfType:"number"},isArray:!0,entryPrefixes:["selectedIndex"],forRenderer:!0,returnArraySizeDependencies:()=>({nSelectedIndices:{dependencyType:"stateVariable",variableName:"nSelectedIndices"}}),returnArraySize:({dependencyValues:e})=>[e.nSelectedIndices],returnArrayDependenciesByKey:()=>({globalDependencies:{allSelectedIndices:{dependencyType:"stateVariable",variableName:"allSelectedIndices"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n in e.allSelectedIndices)t[n]=e.allSelectedIndices[n];return{setValue:{selectedIndices:t}}}},e.selectedIndex={isAlias:!0,targetVariableName:"selectedIndex1"},e.selectedValues={public:!0,shadowingInstructions:{hasVariableComponentType:!0},isArray:!0,entryPrefixes:["selectedValue"],returnArraySizeDependencies:()=>({nSelectedIndices:{dependencyType:"stateVariable",variableName:"nSelectedIndices"}}),returnArraySize:({dependencyValues:e})=>[e.nSelectedIndices],returnArrayDependenciesByKey:()=>({globalDependencies:{selectedIndices:{dependencyType:"stateVariable",variableName:"selectedIndices"},choiceTexts:{dependencyType:"stateVariable",variableName:"choiceTexts"},choiceMaths:{dependencyType:"stateVariable",variableName:"choiceMaths"},componentType:{dependencyType:"stateVariable",variableName:"componentType"}}}),arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t}){let n={},r=e.componentType;for(let a of t)n[a]="math"===r?e.choiceMaths[e.selectedIndices[a]-1]:e.choiceTexts[e.selectedIndices[a]-1];return{setValue:{selectedValues:n},setCreateComponentOfType:{selectedValues:r}}}},e.selectedValue={isAlias:!0,targetVariableName:"selectedValue1"},e.values={isAlias:!0,targetVariableName:"selectedValues"},e.nValues={isAlias:!0,targetVariableName:"nSelectedIndices"},e.childIndicesSelected={returnDependencies:()=>({selectedIndices:{dependencyType:"stateVariable",variableName:"selectedIndices"},choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"}}),definition({dependencyValues:e}){let t=e.selectedIndices.map((t=>e.choiceOrder[t-1]));return{setValue:{childIndicesSelected:t}}}},e.creditAchievedIfSubmit={returnDependencies:()=>({choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["selected","credit"]},selectMultiple:{dependencyType:"stateVariable",variableName:"selectMultiple"},matchPartial:{dependencyType:"stateVariable",variableName:"matchPartial"}}),definition:function({dependencyValues:e}){let t=0;if(e.selectMultiple){let n=0,r=0,a=0;for(let t of e.choiceChildren)t.stateValues.selected?1===t.stateValues.credit?n++:r++:1===t.stateValues.credit&&a++;if(e.matchPartial){let e=n+r+a;t=0===e?1:n/e}else r+a===0&&(t=1)}else for(let n of e.choiceChildren)if(n.stateValues.selected){t=n.stateValues.credit;break}return{setValue:{creditAchievedIfSubmit:t}}}},e.valueToRecordOnSubmit={isAlias:!0,targetVariableName:"selectedIndices"},e.submittedIndices={returnDependencies:()=>({choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["submitted"]}}),definition({dependencyValues:e}){let t=[],n=e.choiceOrder.map((t=>e.choiceChildren[t-1]));for(let[e,r]of n.entries())r.stateValues.submitted&&t.push(e+1);return{setValue:{submittedIndices:t}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){let n=[];for(let[r,a]of t.choiceOrder.entries())n.push({setDependency:"choiceChildren",desiredValue:e.submittedIndices.includes(r+1),variableIndex:0,childIndex:a-1});return{success:!0,instructions:n}}},e.valueRecordedAtSubmit={isAlias:!0,targetVariableName:"submittedIndices"},e.allFeedbacks={returnDependencies:()=>({choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["feedbacks"]}}),definition({dependencyValues:e}){let t=e.choiceOrder.map((t=>e.choiceChildren[t-1])),n=[];for(let e of t)n.push(...e.stateValues.feedbacks);return{setValue:{allFeedbacks:n}}}},e.numberFeedbacks={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({allFeedbacks:{dependencyType:"stateVariable",variableName:"allFeedbacks"}}),definition:({dependencyValues:e})=>({setValue:{numberFeedbacks:e.allFeedbacks.length},checkForActualChange:{numberFeedbacks:!0}})},e.feedbacks={public:!0,shadowingInstructions:{createComponentOfType:"feedback"},isArray:!0,entryPrefixes:["feedback"],returnArraySizeDependencies:()=>({numberFeedbacks:{dependencyType:"stateVariable",variableName:"numberFeedbacks"}}),returnArraySize:({dependencyValues:e})=>[e.numberFeedbacks],returnArrayDependenciesByKey:()=>({globalDependencies:{allFeedbacks:{dependencyType:"stateVariable",variableName:"allFeedbacks"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n=0;nr[e-1]))}},i=await this.stateValues.answerAncestor;return i&&(a.context={answerAncestor:i.componentName}),await this.coreFunctions.performUpdate({updateInstructions:n,actionId:t,event:a}),await this.coreFunctions.triggerChainedActions({componentName:this.componentName})}this.coreFunctions.resolveAction({actionId:t})}static setUpVariant({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n}){setUpVariantSeedAndRng({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n})}static determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t}){if(!e.attributes?.shuffleOrder?.primitive)return super.determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t});let n=0;for(let r of e.children)if("choice"===r.componentType)n++;else{if(!t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"_composite"})||"choice"!==r.attributes.createComponentOfType?.primitive)return{success:!1};if(void 0!==r.attributes.nComponents?.primitive){let e=Number(r.attributes.nComponents?.primitive);if(!(Number.isInteger(e)&&e>=0))return{success:!1};n+=e}else n++}let r=1;for(let e=2;e<=n;e++)r*=e;let a=super.determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t});if(!a.success)return{success:!1};let i=a.numberOfVariants*r;return e.variants.numberOfVariants=i,e.variants.uniqueVariantData={numberOfVariantsByDescendant:e.variants.uniqueVariantData.numberOfVariantsByDescendant,numberOfPermutations:r,numberOfChoices:n},{success:!0,numberOfVariants:i}}static getUniqueVariant({serializedComponent:e,variantIndex:t,componentInfoObjects:n}){let r=e.variants?.numberOfVariants;if(void 0===r)return{success:!1};if(!Number.isInteger(t)||t<1||t>r)return{success:!1};if(!e.attributes.shuffleOrder?.primitive)return super.getUniqueVariant({serializedComponent:e,variantIndex:t,componentInfoObjects:n});let a=e.variants.uniqueVariantData.numberOfVariantsByDescendant,i=e.variants.descendantVariantComponents,s=e.variants.uniqueVariantData.numberOfPermutations,o=e.variants.uniqueVariantData.numberOfChoices,l=[...a];l.push(s);let u=enumerateCombinations({numberOfOptionsByIndex:l,maxNumber:t})[t-1].map((e=>e+1)),c=u.pop(),p=u,d=[...Array(o).keys()].map((e=>e+1)),m=enumeratePermutations({values:d,maxNumber:c})[c-1],h=!1,f=[];for(let e=0;e1){let t=i[e],r=n.allComponentClasses[t.componentType].getUniqueVariant({serializedComponent:t,variantIndex:p[e],componentInfoObjects:n});if(!r.success)return{success:!1};f.push(r.desiredVariant),h=!0}else f.push({});let y={indices:m};return h&&(y.subvariants=f),{success:!0,desiredVariant:y}}}class Choice extends InlineComponent{static componentType="choice";static rendererType="containerInline";static renderChildren=!0;static variableForPlainMacro="submitted";static variableForPlainCopy="submitted";static createAttributesObject(){let e=super.createAttributesObject();return e.credit={createComponentOfType:"number",createStateVariable:"credit",defaultValue:0,public:!0,attributesForCreatedComponent:{convertBoolean:!0}},e.feedbackCodes={createComponentOfType:"textList",createStateVariable:"feedbackCodes",defaultValue:[],public:!0},e.feedbackText={createComponentOfType:"text",createStateVariable:"feedbackText",defaultValue:null,public:!0},e.preSelect={createComponentOfType:"boolean",createStateVariable:"preSelect",defaultValue:!1},e}static returnChildGroups(){return[{group:"children",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["children"],variableNames:["text"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let t="";for(let n of e.inlineChildren)"object"!=typeof n?t+=n.toString():"string"==typeof n.stateValues.text&&(t+=n.stateValues.text);return{setValue:{text:t}}}},e.math={public:!0,shadowingInstructions:{createComponentOfType:"math"},returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["children"],variableNames:["value","latex"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let t=null;if(1===e.inlineChildren.length){let n=e.inlineChildren[0];if("object"==typeof n){let e=n.stateValues.value;if(e instanceof me$3.class)t=e;else if("number"==typeof e)t=me$3.fromAst(e);else if("string"==typeof n.stateValues.latex)try{t=me$3.fromLatex(n.stateValues.latex)}catch(e){}}}return{setValue:{math:t}}}},e.selected={defaultValue:!1,public:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({countAmongSiblings:{dependencyType:"countAmongSiblingsOfSameType"},childIndicesSelected:{dependencyType:"parentStateVariable",parentComponentType:"choiceInput",variableName:"childIndicesSelected"},primaryShadow:{dependencyType:"primaryShadow",variableNames:["selected"]}}),definition({dependencyValues:e,componentName:t}){let n;return n=e.childIndicesSelected?e.childIndicesSelected.includes(e.countAmongSiblings):!!e.primaryShadow&&e.primaryShadow.stateValues.selected,{setValue:{selected:n}}}},e.submitted={defaultValue:!1,hasEssential:!0,public:!0,shadowingInstructions:{createComponentOfType:"boolean"},doNotShadowEssential:!0,returnDependencies:()=>({primaryShadow:{dependencyType:"primaryShadow",variableNames:["submitted"]}}),definition:({dependencyValues:e})=>e.primaryShadow?{setValue:{submitted:e.primaryShadow.stateValues.submitted}}:{useEssentialOrDefaultValue:{submitted:!0}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){return t.primaryShadow?{success:!1}:{success:!0,instructions:[{setEssentialValue:"submitted",value:e.submitted}]}}},e.feedbacks={public:!0,shadowingInstructions:{createComponentOfType:"feedbacktext"},returnDependencies:()=>({feedbackText:{dependencyType:"stateVariable",variableName:"feedbackText"},feedbackCodes:{dependencyType:"stateVariable",variableName:"feedbackCodes"},feedbackDefinitionAncestor:{dependencyType:"ancestor",variableNames:["feedbackDefinitions"]},submitted:{dependencyType:"stateVariable",variableName:"submitted"}}),definition({dependencyValues:e}){if(!e.submitted)return{setValue:{feedbacks:[]}};let t=[],n=e.feedbackDefinitionAncestor.stateValues.feedbackDefinitions;for(let r of e.feedbackCodes){let e=n[r.toLowerCase()];e&&t.push(e)}return null!==e.feedbackText&&t.push(e.feedbackText),{setValue:{feedbacks:t}}}},e}static includeBlankStringChildren=!0;static adapters=["text","math"]}class NumberComponent extends InlineComponent{static componentType="number";static variableForPlainMacro="value";static createAttributesObject(){let e=super.createAttributesObject();return e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer"},e.displaySmallAsZero={createComponentOfType:"number",valueForTrue:1e-14,valueForFalse:0},e.padZeros={createComponentOfType:"boolean"},e.renderAsMath={createComponentOfType:"boolean",createStateVariable:"renderAsMath",defaultValue:!1,public:!0,forRenderer:!0},e.convertBoolean={createPrimitiveOfType:"boolean",createStateVariable:"convertBoolean",defaultValue:!1},e.valueOnNaN={createPrimitiveOfType:"number",createStateVariable:"valueOnNaN",defaultValue:NaN},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({childrenRegex:/..+/,replacementFunction:({matchedChildren:e,componentAttributes:t})=>({success:!t.convertBoolean,newChildren:[{componentType:"math",children:e}]})}),e}static returnChildGroups(){return[{group:"strings",componentTypes:["string"]},{group:"numbers",componentTypes:["number"]},{group:"maths",componentTypes:["math"]},{group:"texts",componentTypes:["text"]},{group:"booleans",componentTypes:["boolean"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({numberListParentDisplayDigits:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"displayDigits"},mathListParentDisplayDigits:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"displayDigits"},numberListParentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"displayDecimals"},mathListParentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"displayDecimals"},displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},numberMathChildren:{dependencyType:"child",childGroups:["numbers","maths"],variableNames:["displayDigits"]},otherChildren:{dependencyType:"child",childGroups:["strings","texts","booleans"]}}),definition({dependencyValues:e,usedDefault:t}){let n,r=!1;if(null!==e.numberListParentDisplayDigits){if(!t.numberListParentDisplayDigits)return{setValue:{displayDigits:e.numberListParentDisplayDigits}};r=!0,n=e.numberListParentDisplayDigits}if(null!==e.mathListParentDisplayDigits){if(!t.mathListParentDisplayDigits)return{setValue:{displayDigits:e.mathListParentDisplayDigits}};r=!0,n=e.mathListParentDisplayDigits}let a=null!==e.numberListParentDisplayDecimals&&!t.numberListParentDisplayDecimals||null!==e.mathListParentDisplayDecimals&&!t.mathListParentDisplayDecimals,i=null===e.displayDigitsAttr||t.displayDigitsAttr,s=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!i&&!s){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({numberListParentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"displayDecimals"},mathListParentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"displayDecimals"},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},numberMathChildren:{dependencyType:"child",childGroups:["numbers","maths"],variableNames:["displayDecimals"]},otherChildren:{dependencyType:"child",childGroups:["strings","texts","booleans"]}}),definition({dependencyValues:e,usedDefault:t}){let n,r=!1;if(null!==e.numberListParentDisplayDecimals){if(!t.numberListParentDisplayDecimals)return{setValue:{displayDecimals:e.numberListParentDisplayDecimals}};r=!0,n=e.numberListParentDisplayDecimals}if(null!==e.mathListParentDisplayDecimals){if(!t.mathListParentDisplayDecimals)return{setValue:{displayDecimals:e.mathListParentDisplayDecimals}};r=!0,n=e.mathListParentDisplayDecimals}if(null!==e.displayDecimalsAttr){if(!t.displayDecimalsAttr)return{setValue:{displayDecimals:e.displayDecimalsAttr.stateValues.value}};r=!0,n=e.displayDecimalsAttr.stateValues.value}if(1===e.numberMathChildren.length&&0===e.otherChildren.length){if(!t.numberMathChildren[0]||!t.numberMathChildren[0].displayDecimals)return{setValue:{displayDecimals:e.numberMathChildren[0].stateValues.displayDecimals}};r=!0,n=e.numberMathChildren[0].stateValues.displayDecimals}return r?{useEssentialOrDefaultValue:{displayDecimals:{defaultValue:n}}}:{useEssentialOrDefaultValue:{displayDecimals:!0}}}},e.displaySmallAsZero={public:!0,shadowingInstructions:{createComponentOfType:"number"},hasEssential:!0,defaultValue:0,returnDependencies:()=>({numberListParentDisplaySmallAsZero:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"displaySmallAsZero"},mathListParentDisplaySmallAsZero:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"displaySmallAsZero"},displaySmallAsZeroAttr:{dependencyType:"attributeComponent",attributeName:"displaySmallAsZero",variableNames:["value"]},numberMathChildren:{dependencyType:"child",childGroups:["numbers","maths"],variableNames:["displaySmallAsZero"]},otherChildren:{dependencyType:"child",childGroups:["strings","texts","booleans"]}}),definition({dependencyValues:e,usedDefault:t}){let n,r=!1;if(null!==e.numberListParentDisplaySmallAsZero){if(!t.numberListParentDisplaySmallAsZero)return{setValue:{displaySmallAsZero:e.numberListParentDisplaySmallAsZero}};r=!0,n=e.numberListParentDisplaySmallAsZero}if(null!==e.mathListParentDisplaySmallAsZero){if(!t.mathListParentDisplaySmallAsZero)return{setValue:{displaySmallAsZero:e.mathListParentDisplaySmallAsZero}};r=!0,n=e.mathListParentDisplaySmallAsZero}if(null!==e.displaySmallAsZeroAttr){if(!t.displaySmallAsZeroAttr)return{setValue:{displaySmallAsZero:e.displaySmallAsZeroAttr.stateValues.value}};r=!0,n=e.displaySmallAsZeroAttr.stateValues.value}if(1===e.numberMathChildren.length&&0===e.otherChildren.length){if(!t.numberMathChildren[0]||!t.numberMathChildren[0].displaySmallAsZero)return{setValue:{displaySmallAsZero:e.numberMathChildren[0].stateValues.displaySmallAsZero}};r=!0,n=e.numberMathChildren[0].stateValues.displaySmallAsZero}return r?{useEssentialOrDefaultValue:{displaySmallAsZero:{defaultValue:n}}}:{useEssentialOrDefaultValue:{displaySmallAsZero:!0}}}},e.padZeros={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},hasEssential:!0,defaultValue:!1,returnDependencies:()=>({numberListParentPadZeros:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"padZeros"},mathListParentPadZeros:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"padZeros"},padZerosAttr:{dependencyType:"attributeComponent",attributeName:"padZeros",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},numberMathChildren:{dependencyType:"child",childGroups:["numbers","maths"],variableNames:["padZeros"]},otherChildren:{dependencyType:"child",childGroups:["strings","texts","booleans"]}}),definition({dependencyValues:e,usedDefault:t}){let n,r=!1;if(null!==e.numberListParentPadZeros){if(!t.numberListParentPadZeros)return{setValue:{padZeros:e.numberListParentPadZeros}};r=!0,n=e.numberListParentPadZeros}if(null!==e.mathListParentPadZeros){if(!t.mathListParentPadZeros)return{setValue:{padZeros:e.mathListParentPadZeros}};r=!0,n=e.mathListParentPadZeros}if(null!==e.padZerosAttr){if(!t.padZerosAttr)return{setValue:{padZeros:e.padZerosAttr.stateValues.value}};r=!0,n=e.padZerosAttr.stateValues.value}if(1===e.numberMathChildren.length&&0==e.otherChildren.length){if(!t.numberMathChildren[0]||!t.numberMathChildren[0].padZeros)return{setValue:{padZeros:e.numberMathChildren[0].stateValues.padZeros}};r=!0,n=e.numberMathChildren[0].stateValues.padZeros}return r?{useEssentialOrDefaultValue:{padZeros:{defaultValue:n}}}:{useEssentialOrDefaultValue:{padZeros:!0}}}},e.singleNumberOrStringChild={additionalStateVariablesDefined:["singleMathChild"],returnDependencies:()=>({numberChildren:{dependencyType:"child",childGroups:["numbers"]},stringChildren:{dependencyType:"child",childGroups:["strings"]},mathChildren:{dependencyType:"child",childGroups:["maths"]},booleanChildren:{dependencyType:"child",childGroups:["booleans"]},textChildren:{dependencyType:"child",childGroups:["texts"]}}),definition({dependencyValues:e}){let t=e.numberChildren.length+e.stringChildren.length,n=e.mathChildren.length,r=e.booleanChildren.length+e.textChildren.length;return{setValue:{singleNumberOrStringChild:t<=1&&n+r===0,singleMathChild:1===n&&t+r===0}}}},e.parsedExpression={additionalStateVariablesDefined:["codePre"],returnDependencies:()=>({allChildren:{dependencyType:"child",childGroups:["strings","numbers","maths","texts","booleans"]},stringChildren:{dependencyType:"child",childGroups:["strings"],variableNames:["value"]}}),definition:buildParsedExpression},e.mathChildrenByCode={additionalStateVariablesDefined:["textChildrenByCode","numberChildrenByCode","booleanChildrenByCode"],returnDependencies:()=>({allChildren:{dependencyType:"child",childGroups:["strings","numbers","maths","texts","booleans"],variableNames:["value","texts","maths","booleans"],variablesOptional:!0},codePre:{dependencyType:"stateVariable",variableName:"codePre"}}),definition({dependencyValues:e,componentInfoObjects:t}){let n={},r={},a={},i={},s=0,o=e.codePre;for(let l of e.allChildren)if("string"!=typeof l){let e=o+s;t.isInheritedComponentType({inheritedComponentType:l.componentType,baseComponentType:"math"})?n[e]=l:t.isInheritedComponentType({inheritedComponentType:l.componentType,baseComponentType:"number"})?r[e]=l:t.isInheritedComponentType({inheritedComponentType:l.componentType,baseComponentType:"text"})?a[e]=l:i[e]=l,s+=1}return{setValue:{mathChildrenByCode:n,numberChildrenByCode:r,textChildrenByCode:a,booleanChildrenByCode:i}}}},e.value={public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"],addAttributeComponentsShadowingStateVariables:{fixed:{stateVariableToShadow:"fixed"}}},hasEssential:!0,stateVariablesDeterminingDependencies:["singleNumberOrStringChild"],returnDependencies:({stateValues:e})=>e.singleNumberOrStringChild?{singleNumberOrStringChild:{dependencyType:"stateVariable",variableName:"singleNumberOrStringChild"},convertBoolean:{dependencyType:"stateVariable",variableName:"convertBoolean"},numberChild:{dependencyType:"child",childGroups:["numbers"],variableNames:["value"]},stringChild:{dependencyType:"child",childGroups:["strings"],variableNames:["value"]},valueOnNaN:{dependencyType:"stateVariable",variableName:"valueOnNaN"}}:{singleNumberOrStringChild:{dependencyType:"stateVariable",variableName:"singleNumberOrStringChild"},singleMathChild:{dependencyType:"stateVariable",variableName:"singleMathChild"},convertBoolean:{dependencyType:"stateVariable",variableName:"convertBoolean"},parsedExpression:{dependencyType:"stateVariable",variableName:"parsedExpression"},allChildren:{dependencyType:"child",childGroups:["strings","numbers","maths","texts","booleans"],variableNames:["value","texts","maths","unordered"],variablesOptional:!0},booleanChildrenByCode:{dependencyType:"stateVariable",variableName:"booleanChildrenByCode"},textChildrenByCode:{dependencyType:"stateVariable",variableName:"textChildrenByCode"},mathChildrenByCode:{dependencyType:"stateVariable",variableName:"mathChildrenByCode"},numberChildrenByCode:{dependencyType:"stateVariable",variableName:"numberChildrenByCode"},valueOnNaN:{dependencyType:"stateVariable",variableName:"valueOnNaN"}},definition({dependencyValues:e,componentInfoObjects:t}){if(e.singleNumberOrStringChild){if(0===e.numberChild.length){if(0===e.stringChild.length)return{useEssentialOrDefaultValue:{value:{defaultValue:e.valueOnNaN}}};let n=Number(e.stringChild[0]);if(Number.isNaN(n))try{if(n=me$3.fromAst(textToAst$1.convert(e.stringChild[0])).evaluate_to_constant(),"boolean"==typeof n)n=e.convertBoolean?n?1:0:e.valueOnNaN;else if(null===n||Number.isNaN(n))if(e.convertBoolean){n=evaluateLogic({logicTree:buildParsedExpression({dependencyValues:{stringChildren:e.stringChild,allChildren:e.stringChild},componentInfoObjects:t}).setValue.parsedExpression.tree,dependencyValues:{booleanChildrenByCode:{},booleanListChildrenByCode:{},textChildrenByCode:{},textListChildrenByCode:{},mathChildrenByCode:{},mathListChildrenByCode:{},numberChildrenByCode:{},numberListChildrenByCode:{},otherChildrenByCode:{}},valueOnInvalid:e.valueOnNaN})}else n=e.valueOnNaN;else n?.re===1/0||n?.re===-1/0||n?.im===1/0||n?.im===-1/0?n=numberToMathExpression(n).evaluate_to_constant():0===n?.im&&(n=n.re)}catch(t){n=e.valueOnNaN}return{setValue:{value:n}}}{let t=e.numberChild[0].stateValues.value;return Number.isNaN(t)&&(t=e.valueOnNaN),{setValue:{value:t}}}}if(null===e.parsedExpression)return{setValue:{value:e.valueOnNaN}};if(0===Object.keys(e.textChildrenByCode).length&&0===Object.keys(e.booleanChildrenByCode).length){let t,n=function(t){if("string"==typeof t){let n=e.mathChildrenByCode[t];return void 0!==n?n.stateValues.value.tree:(n=e.numberChildrenByCode[t],void 0!==n?numberToMathExpression(n.stateValues.value).tree:t)}return Array.isArray(t)?[t[0],...t.slice(1).map(n)]:t};try{t=me$3.fromAst(n(e.parsedExpression.tree)).evaluate_to_constant()}catch(n){t=e.valueOnNaN}if(!Number.isNaN(t)&&("number"==typeof t||"number"==typeof t?.re&&"number"==typeof t?.im))return t.re===1/0||t.re===-1/0||t.im===1/0||t.im===-1/0?t=numberToMathExpression(t).evaluate_to_constant():0===t.im&&(t=t.re),{setValue:{value:t}}}if(!e.convertBoolean)return{setValue:{value:e.valueOnNaN}};return(e=Object.assign({},e)).mathListChildrenByCode={},e.numberListChildrenByCode={},e.textListChildrenByCode={},e.booleanListChildrenByCode={},e.otherChildrenByCode={},{setValue:{value:evaluateLogic({logicTree:e.parsedExpression.tree,dependencyValues:e,valueOnInvalid:e.valueOnNaN})}}},set:function(e){if(null===e)return NaN;if("number"==typeof e||"number"==typeof e?.re&&"number"==typeof e?.im)return e;let t=Number(e);if(Number.isNaN(t))try{t=me$3.fromAst(textToAst$1.convert(e)).evaluate_to_constant(),null===t&&(t=NaN)}catch(e){t=NaN}return t},inverseDefinition:async function({desiredStateVariableValues:e,dependencyValues:t,stateValues:n,overrideFixed:r}){if(!await n.canBeModified&&!r)return{success:!1};let a,i=e.value;return i instanceof me$3.class?(i=i.evaluate_to_constant(),(Number.isNaN(i)||"number"!=typeof i&&("number"!=typeof i?.re||"number"!=typeof i?.im))&&(i=t.valueOnNaN)):(Number.isNaN(i)||"number"!=typeof i&&("number"!=typeof i?.re||"number"!=typeof i?.im))&&(i=Number(i),Number.isNaN(i)&&(i=t.valueOnNaN)),t.singleNumberOrStringChild?(a=0===t.numberChild.length?0===t.stringChild.length?[{setEssentialValue:"value",value:numberToMathExpression(i).evaluate_to_constant()}]:[{setDependency:"stringChild",desiredValue:numberToMathExpression(i).toString(),childIndex:0,variableIndex:0}]:[{setDependency:"numberChild",desiredValue:i,childIndex:0,variableIndex:0}],{success:!0,instructions:a}):t.singleMathChild?{success:!0,instructions:[{setDependency:"allChildren",desiredValue:numberToMathExpression(i),childIndex:0,variableIndex:0}]}:{success:!1}}},e.valueForDisplay={returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"}}),definition:function({dependencyValues:e,usedDefault:t}){return{setValue:{valueForDisplay:roundForDisplay({value:numberToMathExpression(e.value),dependencyValues:e,usedDefault:t}).evaluate_to_constant()}}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({valueForDisplay:{dependencyType:"stateVariable",variableName:"valueForDisplay"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},value:{dependencyType:"stateVariable",variableName:"value"}}),definition:function({dependencyValues:e,usedDefault:t}){let n={};return e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(n.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(n.padToDigits=e.displayDigits)),{setValue:{text:numberToMathExpression(e.valueForDisplay).toString(n)}}},async inverseDefinition({desiredStateVariableValues:e,stateValues:t}){let n=Number(e.text);if(Number.isFinite(n))return{success:!0,instructions:[{setDependency:"value",desiredValue:n}]};{let t,r=getFromText({parseScientificNotation:!1});try{t=r(e.text)}catch(e){return{success:!1}}return n=t.evaluate_to_constant(),Number.isFinite(n)?{success:!0,instructions:[{setDependency:"value",desiredValue:n}]}:{success:!1}}}},e.math=mathStateVariableFromNumberStateVariable({numberVariableName:"value",mathVariableName:"math",isPublic:!0}),e.math.shadowingInstructions.attributesToShadow=["displayDigits","displayDecimals","displaySmallAsZero","padZeros"],e.latex={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({valueForDisplay:{dependencyType:"stateVariable",variableName:"valueForDisplay"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"}}),definition({dependencyValues:e,usedDefault:t}){let n={};return e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(n.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(n.padToDigits=e.displayDigits)),{setValue:{latex:numberToMathExpression(e.valueForDisplay).toLatex(n)}}}},e.canBeModified={returnDependencies:()=>({numberChildModifiable:{dependencyType:"child",childGroups:["numbers"],variableNames:["canBeModified"]},modifyIndirectly:{dependencyType:"stateVariable",variableName:"modifyIndirectly"},fixed:{dependencyType:"stateVariable",variableName:"fixed"},singleNumberOrStringChild:{dependencyType:"stateVariable",variableName:"singleNumberOrStringChild"},singleMathChild:{dependencyType:"stateVariable",variableName:"singleMathChild"}}),definition:function({dependencyValues:e}){return!e.modifyIndirectly||e.fixed||!e.singleNumberOrStringChild&&!e.singleMathChild?{setValue:{canBeModified:!1}}:1!==e.numberChildModifiable.length||e.numberChildModifiable[0].stateValues.canBeModified?{setValue:{canBeModified:!0}}:{setValue:{canBeModified:!1}}}},e}static adapters=[{stateVariable:"math",stateVariablesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},"text"]}class Integer extends NumberComponent{static componentType="integer";static rendererType="number";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return renameStateVariable({stateVariableDefinitions:e,oldName:"value",newName:"valuePreRound"}),e.value={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({valuePreRound:{dependencyType:"stateVariable",variableName:"valuePreRound"}}),set:function(e){if(null===e)return NaN;let t=Number(e);if(Number.isNaN(t))try{t=me$3.fromAst(textToAst.convert(e)).evaluate_to_constant(),null===t&&(t=NaN)}catch(e){t=NaN}return Math.round(t)},definition:({dependencyValues:e})=>({setValue:{value:Math.round(e.valuePreRound)}}),inverseDefinition({desiredStateVariableValues:e}){let t=e.value;return t instanceof me$3.class?(t=t.evaluate_to_constant(),Number.isFinite(t)||(t=NaN)):t=Number(t),t=Math.round(t),{success:!0,instructions:[{setDependency:"valuePreRound",desiredValue:t}]}}},e}}const maxWidth=850,sizePossibilities=["tiny","small","medium","large","full"],widthFractions=[1/12,.3,.5,.7,1],fractionMidpoints=widthFractions.map(((e,t)=>(e+(widthFractions[t+1]||1/0))/2)),orderedWidthMidpoints=fractionMidpoints.map((e=>maxWidth*e)),orderedPercentWidthMidpoints=fractionMidpoints.map((e=>100*e)),widthsBySize={};sizePossibilities.forEach(((e,t)=>widthsBySize[e]=Math.floor(widthFractions[t]*maxWidth)));const percentWidthsBySize={};sizePossibilities.forEach(((e,t)=>percentWidthsBySize[e]=Math.round(100*widthFractions[t])));class Graph$1 extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{changeAxisLimits:this.changeAxisLimits.bind(this),addChildren:this.addChildren.bind(this),deleteChildren:this.deleteChildren.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="graph";static renderChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.xmin={createComponentOfType:"number",createStateVariable:"xminPrelim",defaultValue:-10},e.xmax={createComponentOfType:"number",createStateVariable:"xmaxPrelim",defaultValue:10},e.ymin={createComponentOfType:"number",createStateVariable:"yminPrelim",defaultValue:-10},e.ymax={createComponentOfType:"number",createStateVariable:"ymaxPrelim",defaultValue:10},e.width={createComponentOfType:"_componentSize"},e.size={createComponentOfType:"text"},e.aspectRatio={createComponentOfType:"number"},e.height={createComponentOfType:"_componentSize"},e.displayMode={createComponentOfType:"text",createStateVariable:"displayMode",validValues:["block","inline"],defaultValue:"block",forRenderer:!0,public:!0},e.horizontalAlign={createComponentOfType:"text",createStateVariable:"horizontalAlign",validValues:["center","left","right"],defaultValue:"center",forRenderer:!0,public:!0},e.identicalAxisScales={createPrimitiveOfType:"boolean",createStateVariable:"identicalAxisScales",defaultValue:!1,public:!0},e.displayXAxis={createComponentOfType:"boolean",createStateVariable:"displayXAxis",defaultValue:!0,public:!0,forRenderer:!0},e.displayYAxis={createComponentOfType:"boolean",createStateVariable:"displayYAxis",defaultValue:!0,public:!0,forRenderer:!0},e.displayXAxisTickLabels={createComponentOfType:"boolean",createStateVariable:"displayXAxisTickLabels",defaultValue:!0,public:!0,forRenderer:!0},e.displayYAxisTickLabels={createComponentOfType:"boolean",createStateVariable:"displayYAxisTickLabels",defaultValue:!0,public:!0,forRenderer:!0},e.xlabel={createComponentOfType:"label"},e.xlabelPosition={createComponentOfType:"text",createStateVariable:"xlabelPosition",defaultValue:"right",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["right","left"]},e.xTickScaleFactor={createComponentOfType:"math",createStateVariable:"xTickScaleFactor",defaultValue:null,public:!0,forRenderer:!0},e.ylabel={createComponentOfType:"label"},e.ylabelPosition={createComponentOfType:"text",createStateVariable:"ylabelPosition",defaultValue:"top",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["top","bottom"]},e.ylabelAlignment={createComponentOfType:"text",createStateVariable:"ylabelAlignment",defaultValue:"left",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["left","right"]},e.yTickScaleFactor={createComponentOfType:"math",createStateVariable:"yTickScaleFactor",defaultValue:null,public:!0,forRenderer:!0},e.showNavigation={createComponentOfType:"boolean",createStateVariable:"showNavigation",defaultValue:!0,public:!0,forRenderer:!0},e.fixAxes={createComponentOfType:"boolean",createStateVariable:"fixAxes",defaultValue:!1,public:!0,forRenderer:!0},e.grid={createComponentOfType:"text"},e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.padZeros={createComponentOfType:"boolean",createStateVariable:"padZeros",defaultValue:!1,public:!0},e}static returnChildGroups(){return[{group:"xlabels",componentTypes:["xlabel"]},{group:"ylabels",componentTypes:["ylabel"]},{group:"graphical",componentTypes:["_graphical","text","image","math","m","md","label"]},{group:"childrenThatShouldNotBeHere",componentTypes:["_base"],matchAfterAdapters:!0}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.displayDigitsAttr){let n=t.displayDigitsAttr,r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!n&&!r){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({xlabelAttr:{dependencyType:"attributeComponent",attributeName:"xlabel",variableNames:["value","hasLatex"]},xlabelChild:{dependencyType:"child",childGroups:["xlabels"],variableNames:["value","hasLatex"]}}),definition({dependencyValues:e}){if(e.xlabelChild.length>0){let t=e.xlabelChild[e.xlabelChild.length-1];return{setValue:{xlabel:t.stateValues.value,xlabelHasLatex:t.stateValues.hasLatex}}}return e.xlabelAttr?{setValue:{xlabel:e.xlabelAttr.stateValues.value,xlabelHasLatex:e.xlabelAttr.stateValues.hasLatex}}:{useEssentialOrDefaultValue:{xlabel:!0},setValue:{xlabelHasLatex:!1}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){if("string"!=typeof e.xlabel)return{success:!1};if(t.xlabelChild.length>0){let n=t.xlabelChild.length-1;return{success:!0,instructions:[{setDependency:"xlabelChild",desiredValue:e.xlabel,childIndex:n,variableIndex:0}]}}return{success:!0,instructions:[{setEssentialValue:"xlabel",value:e.xlabel}]}}},e.ylabel={forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"label",addStateVariablesShadowingStateVariables:{hasLatex:{stateVariableToShadow:"ylabelHasLatex"}}},hasEssential:!0,defaultValue:"",additionalStateVariablesDefined:[{variableName:"ylabelHasLatex",forRenderer:!0}],returnDependencies:()=>({ylabelAttr:{dependencyType:"attributeComponent",attributeName:"ylabel",variableNames:["value","hasLatex"]},ylabelChild:{dependencyType:"child",childGroups:["ylabels"],variableNames:["value","hasLatex"]}}),definition({dependencyValues:e}){if(e.ylabelChild.length>0){let t=e.ylabelChild[e.ylabelChild.length-1];return{setValue:{ylabel:t.stateValues.value,ylabelHasLatex:t.stateValues.hasLatex}}}return e.ylabelAttr?{setValue:{ylabel:e.ylabelAttr.stateValues.value,ylabelHasLatex:e.ylabelAttr.stateValues.hasLatex}}:{useEssentialOrDefaultValue:{ylabel:!0},setValue:{ylabelHasLatex:!1}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){if("string"!=typeof e.ylabel)return{success:!1};if(t.ylabelChild.length>0){let n=t.ylabelChild.length-1;return{success:!0,instructions:[{setDependency:"ylabelChild",desiredValue:e.ylabel,childIndex:n,variableIndex:0}]}}return{success:!0,instructions:[{setEssentialValue:"ylabel",value:e.ylabel}]}}},e.graphicalDescendants={forRenderer:!0,returnDependencies:()=>({graphicalDescendants:{dependencyType:"descendant",componentTypes:["_graphical"]}}),definition:function({dependencyValues:e}){return{setValue:{graphicalDescendants:e.graphicalDescendants}}}},e.childIndicesToRender={returnDependencies:()=>({graphicalChildren:{dependencyType:"child",childGroups:["graphical"]},allChildren:{dependencyType:"child",childGroups:["graphical","xlabels","ylabels","childrenThatShouldNotBeHere"]}}),definition({dependencyValues:e}){let t=[],n=e.graphicalChildren.map((e=>e.componentName));for(let[r,a]of e.allChildren.entries())n.includes(a.componentName)&&t.push(r);return{setValue:{childIndicesToRender:t}}}},e.nChildrenAdded={defaultValue:0,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{nChildrenAdded:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"nChildrenAdded",value:e.nChildrenAdded}]})},e.size={public:!0,defaultValue:"medium",hasEssential:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({sizeAttr:{dependencyType:"attributeComponent",attributeName:"size",variableNames:["value"]},widthAttr:{dependencyType:"attributeComponent",attributeName:"width",variableNames:["componentSize"]}}),definition({dependencyValues:e}){const t="medium";if(e.sizeAttr){let n=e.sizeAttr.stateValues.value.toLowerCase();return sizePossibilities.includes(n)||(n=t),{setValue:{size:n}}}if(e.widthAttr){let n=e.widthAttr.stateValues.componentSize;if(null===n)return{setValue:{size:t}};let r,{isAbsolute:a,size:i}=n;if(a){for(let[e,t]of orderedWidthMidpoints.entries())if(i<=t){r=sizePossibilities[e];break}r||(r=t)}else{for(let[e,t]of orderedPercentWidthMidpoints.entries())if(i<=t){r=sizePossibilities[e];break}r||(r=t)}return{setValue:{size:r}}}return{useEssentialOrDefaultValue:{size:!0}}}},e.width={public:!0,forRenderer:!0,shadowingInstructions:{createComponentOfType:"_componentSize"},returnDependencies:()=>({size:{dependencyType:"stateVariable",variableName:"size"}}),definition:({dependencyValues:e})=>({setValue:{width:{isAbsolute:!0,size:widthsBySize[e.size]}}})},e.aspectRatioFromAxisScales={returnDependencies:()=>({aspectRatioAttr:{dependencyType:"attributeComponent",attributeName:"aspectRatio",variableNames:["value"]},identicalAxisScales:{dependencyType:"stateVariable",variableName:"identicalAxisScales"},heightAttr:{dependencyType:"attributeComponent",attributeName:"height",variableNames:["componentSize"]}}),definition:({dependencyValues:e})=>(null!==e.heightAttr&&console.warn("Height attribute of graph is deprecated and is being ignored. Use aspectRatio attribute instead."),{setValue:{aspectRatioFromAxisScales:e.identicalAxisScales&&null===e.aspectRatioAttr},checkForActualChange:{aspectRatioFromAxisScales:!0}})},e.aspectRatio={public:!0,forRenderer:!0,defaultValue:1,hasEssential:!0,shadowingInstructions:{createComponentOfType:"number"},stateVariablesDeterminingDependencies:["aspectRatioFromAxisScales"],returnDependencies:({stateValues:e})=>e.aspectRatioFromAxisScales?{aspectRatioFromAxisScales:{dependencyType:"stateVariable",variableName:"aspectRatioFromAxisScales"},xscale:{dependencyType:"stateVariable",variableName:"xscale"},yscale:{dependencyType:"stateVariable",variableName:"yscale"}}:{aspectRatioFromAxisScales:{dependencyType:"stateVariable",variableName:"aspectRatioFromAxisScales"},aspectRatioAttr:{dependencyType:"attributeComponent",attributeName:"aspectRatio",variableNames:["value"]},width:{dependencyType:"stateVariable",variableName:"width"}},definition({dependencyValues:e}){if(e.aspectRatioFromAxisScales){return{setValue:{aspectRatio:e.xscale/e.yscale}}}if(null!==e.aspectRatioAttr){let t=e.aspectRatioAttr.stateValues.value;return Number.isFinite(t)||(t=1),{setValue:{aspectRatio:t}}}return{useEssentialOrDefaultValue:{aspectRatio:!0}}}},e.xmin={stateVariablesDeterminingDependencies:["identicalAxisScales","aspectRatioFromAxisScales"],public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},forRenderer:!0,returnDependencies({stateValues:e}){let t={identicalAxisScales:{dependencyType:"stateVariable",variableName:"identicalAxisScales"},aspectRatioFromAxisScales:{dependencyType:"stateVariable",variableName:"aspectRatioFromAxisScales"},xminPrelim:{dependencyType:"stateVariable",variableName:"xminPrelim"}};return e.identicalAxisScales&&!e.aspectRatioFromAxisScales&&(t.xmaxPrelim={dependencyType:"stateVariable",variableName:"xmaxPrelim"},t.yminPrelim={dependencyType:"stateVariable",variableName:"yminPrelim"},t.ymaxPrelim={dependencyType:"stateVariable",variableName:"ymaxPrelim"},t.aspectRatio={dependencyType:"stateVariable",variableName:"aspectRatio"}),t},definition({dependencyValues:e,usedDefault:t}){if(!e.identicalAxisScales||e.aspectRatioFromAxisScales)return{setValue:{xmin:e.xminPrelim}};if(!t.xminPrelim)return{setValue:{xmin:e.xminPrelim}};let n=!t.xmaxPrelim,r=!t.yminPrelim,a=!t.ymaxPrelim;if(r&&a){let t=e.aspectRatio,r=(e.ymaxPrelim-e.yminPrelim)*t;return n?{setValue:{xmin:e.xmaxPrelim-r}}:{setValue:{xmin:-r/2}}}return n?{setValue:{xmin:e.xmaxPrelim-20}}:{setValue:{xmin:-10}}},inverseDefinition:async({desiredStateVariableValues:e,stateValues:t})=>await t.fixAxes?{success:!1}:{success:!0,instructions:[{setDependency:"xminPrelim",desiredValue:e.xmin}]}},e.xmax={stateVariablesDeterminingDependencies:["identicalAxisScales","aspectRatioFromAxisScales"],public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},forRenderer:!0,returnDependencies({stateValues:e}){let t={identicalAxisScales:{dependencyType:"stateVariable",variableName:"identicalAxisScales"},aspectRatioFromAxisScales:{dependencyType:"stateVariable",variableName:"aspectRatioFromAxisScales"},xmaxPrelim:{dependencyType:"stateVariable",variableName:"xmaxPrelim"}};return e.identicalAxisScales&&!e.aspectRatioFromAxisScales&&(t.xminPrelim={dependencyType:"stateVariable",variableName:"xminPrelim"},t.yminPrelim={dependencyType:"stateVariable",variableName:"yminPrelim"},t.ymaxPrelim={dependencyType:"stateVariable",variableName:"ymaxPrelim"},t.aspectRatio={dependencyType:"stateVariable",variableName:"aspectRatio"}),t},definition({dependencyValues:e,usedDefault:t}){if(!e.identicalAxisScales||e.aspectRatioFromAxisScales)return{setValue:{xmax:e.xmaxPrelim}};let n=!t.xminPrelim,r=!t.xmaxPrelim,a=!t.yminPrelim,i=!t.ymaxPrelim,s=a&&i,o=n&&r,l=e.xminPrelim;if(s){let t=e.aspectRatio,a=(e.ymaxPrelim-e.yminPrelim)*t;if(o){let t=e.xmaxPrelim-l;return{setValue:{xmax:l+Math.max(t,a)}}}return n?{setValue:{xmax:l+a}}:r?{setValue:{xmax:e.xmaxPrelim}}:{setValue:{xmax:a/2}}}return r?{setValue:{xmax:e.xmaxPrelim}}:n?{setValue:{xmax:l+20}}:{setValue:{xmax:10}}},inverseDefinition:async({desiredStateVariableValues:e,stateValues:t})=>await t.fixAxes?{success:!1}:{success:!0,instructions:[{setDependency:"xmaxPrelim",desiredValue:e.xmax}]}},e.ymin={stateVariablesDeterminingDependencies:["identicalAxisScales","aspectRatioFromAxisScales"],public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},forRenderer:!0,returnDependencies({stateValues:e}){let t={identicalAxisScales:{dependencyType:"stateVariable",variableName:"identicalAxisScales"},aspectRatioFromAxisScales:{dependencyType:"stateVariable",variableName:"aspectRatioFromAxisScales"},yminPrelim:{dependencyType:"stateVariable",variableName:"yminPrelim"}};return e.identicalAxisScales&&!e.aspectRatioFromAxisScales&&(t.xmaxPrelim={dependencyType:"stateVariable",variableName:"xmaxPrelim"},t.xminPrelim={dependencyType:"stateVariable",variableName:"xminPrelim"},t.ymaxPrelim={dependencyType:"stateVariable",variableName:"ymaxPrelim"},t.aspectRatio={dependencyType:"stateVariable",variableName:"aspectRatio"}),t},definition({dependencyValues:e,usedDefault:t}){if(!e.identicalAxisScales||e.aspectRatioFromAxisScales)return{setValue:{ymin:e.yminPrelim}};if(!t.yminPrelim)return{setValue:{ymin:e.yminPrelim}};let n=!t.ymaxPrelim,r=!t.xminPrelim,a=!t.xmaxPrelim,i=r&&a,s=e.aspectRatio;if(i){let t=(e.xmaxPrelim-e.xminPrelim)/s;return n?{setValue:{ymin:e.ymaxPrelim-t}}:{setValue:{ymin:-t/2}}}return n?{setValue:{ymin:e.ymaxPrelim-20/s}}:{setValue:{ymin:-10/s}}},inverseDefinition:async({desiredStateVariableValues:e,stateValues:t})=>await t.fixAxes?{success:!1}:{success:!0,instructions:[{setDependency:"yminPrelim",desiredValue:e.ymin}]}},e.ymax={stateVariablesDeterminingDependencies:["identicalAxisScales","aspectRatioFromAxisScales"],public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},forRenderer:!0,returnDependencies({stateValues:e}){let t={identicalAxisScales:{dependencyType:"stateVariable",variableName:"identicalAxisScales"},aspectRatioFromAxisScales:{dependencyType:"stateVariable",variableName:"aspectRatioFromAxisScales"},ymaxPrelim:{dependencyType:"stateVariable",variableName:"ymaxPrelim"}};return e.identicalAxisScales&&!e.aspectRatioFromAxisScales&&(t.xminPrelim={dependencyType:"stateVariable",variableName:"xminPrelim"},t.yminPrelim={dependencyType:"stateVariable",variableName:"yminPrelim"},t.xmaxPrelim={dependencyType:"stateVariable",variableName:"xmaxPrelim"},t.aspectRatio={dependencyType:"stateVariable",variableName:"aspectRatio"}),t},definition({dependencyValues:e,usedDefault:t}){if(!e.identicalAxisScales||e.aspectRatioFromAxisScales)return{setValue:{ymax:e.ymaxPrelim}};let n=!t.xminPrelim,r=!t.xmaxPrelim,a=!t.yminPrelim,i=!t.ymaxPrelim,s=a&&i,o=n&&r,l=e.yminPrelim,u=e.aspectRatio;if(o){let t=(e.xmaxPrelim-e.xminPrelim)/u;if(s){let n=e.ymaxPrelim-l;return{setValue:{ymax:l+Math.max(n,t)}}}return a?{setValue:{ymax:l+t}}:i?{setValue:{ymax:e.ymaxPrelim}}:{setValue:{ymax:t/2}}}return i?{setValue:{ymax:e.ymaxPrelim}}:a?{setValue:{ymax:l+20/u}}:{setValue:{ymax:10/u}}},inverseDefinition:async({desiredStateVariableValues:e,stateValues:t})=>await t.fixAxes?{success:!1}:{success:!0,instructions:[{setDependency:"ymaxPrelim",desiredValue:e.ymax}]}},e.xscale={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({xmin:{dependencyType:"stateVariable",variableName:"xmin"},xmax:{dependencyType:"stateVariable",variableName:"xmax"}}),definition:({dependencyValues:e})=>({setValue:{xscale:e.xmax-e.xmin}})},e.yscale={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({ymin:{dependencyType:"stateVariable",variableName:"ymin"},ymax:{dependencyType:"stateVariable",variableName:"ymax"}}),definition:({dependencyValues:e})=>({setValue:{yscale:e.ymax-e.ymin}})},e.gridAttrCompName={returnDependencies:()=>({gridAttr:{dependencyType:"attributeComponent",attributeName:"grid"}}),definition:({dependencyValues:e})=>e.gridAttr?{setValue:{gridAttrCompName:e.gridAttr.componentName}}:{setValue:{gridAttrCompName:null}}},e.gridAttrCompChildren={stateVariablesDeterminingDependencies:["gridAttrCompName"],returnDependencies:({stateValues:e})=>e.gridAttrCompName?{gridAttrCompChildren:{dependencyType:"child",parentName:e.gridAttrCompName,childGroups:["textLike"],variableNames:["value"]}}:{},definition:({dependencyValues:e})=>e.gridAttrCompChildren?{setValue:{gridAttrCompChildren:e.gridAttrCompChildren}}:{setValue:{gridAttrCompChildren:null}}},e.grid={public:!0,shadowingInstructions:{hasVariableComponentType:!0,attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},forRenderer:!0,stateVariablesDeterminingDependencies:["gridAttrCompChildren"],returnDependencies({stateValues:e}){if(e.gridAttrCompChildren){let t={gridAttrCompChildren:{dependencyType:"stateVariable",variableName:"gridAttrCompChildren"},gridAttr:{dependencyType:"attributeComponent",attributeName:"grid",variableNames:["value"]}};for(let[n,r]of e.gridAttrCompChildren.entries())t["childAdapter"+n]={dependencyType:"adapterSourceStateVariable",componentName:r.componentName,variableName:"value"};return t}return{}},definition({dependencyValues:e}){if(!e.gridAttrCompChildren)return{setValue:{grid:"none"},setCreateComponentOfType:{grid:"text"}};let t=e.gridAttr.stateValues.value.toLowerCase().trim();if("true"===t?t="medium":"false"===t&&(t="none"),["medium","dense","none"].includes(t))return{setValue:{grid:t},setCreateComponentOfType:{grid:"text"}};let n=[],r=[];for(let t of e.gridAttrCompChildren)if("string"!=typeof t)r.push(t);else{let e=t.split(/\s+/),a=e[0];""===a?r.length>0&&(n.push(r),r=[]):r.push(a);for(let t of e.slice(1))r.length>0&&(n.push(r),r=[]),""!==t&&r.push(t)}if(r.length>0&&n.push(r),n.length<2)return{setValue:{grid:"none"},setCreateComponentOfType:{grid:"text"}};t=[];for(let r of n)if(1===r.length){let n=r[0];if("string"==typeof n){let e=me$3.fromText(n).evaluate_to_constant();if(!(e>0))return{setValue:{grid:"none"},setCreateComponentOfType:{grid:"text"}};t.push(e)}else{let r=e.gridAttrCompChildren.indexOf(n),a=e["childAdapter"+r];if(a instanceof me$3.class&&(a=a.evaluate_to_constant()),!(a>0))return{setValue:{grid:"none"},setCreateComponentOfType:{grid:"text"}};t.push(a)}}else{let n=1;for(let t of r)if("string"==typeof t)n*=me$3.fromText(t).evaluate_to_constant();else{let r=e.gridAttrCompChildren.indexOf(t),a=e["childAdapter"+r];a instanceof me$3.class&&(a=a.evaluate_to_constant()),n*=a}if(!(n>0))return{setValue:{grid:"none"},setCreateComponentOfType:{grid:"text"}};t.push(n)}return{setValue:{grid:t},setCreateComponentOfType:{grid:"numberList"}}}},e}async changeAxisLimits({xmin:e,xmax:t,ymin:n,ymax:r,actionId:a}){let i=[];return void 0!==e&&i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"xmin",value:e}),void 0!==t&&i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"xmax",value:t}),void 0!==n&&i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"ymin",value:n}),void 0!==r&&i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"ymax",value:r}),await this.coreFunctions.performUpdate({updateInstructions:i,actionId:a,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{xmin:e,xmax:t,ymin:n,ymax:r}}})}async addChildren({serializedComponents:e,actionId:t}){if(e&&e.length>0){let n=processAssignNames({serializedComponents:e,parentName:this.componentName,parentCreatesNewNamespace:this.attributes.newNamespace?.primitive,componentInfoObjects:this.componentInfoObjects,indOffset:await this.stateValues.nChildrenAdded});return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"addComponents",serializedComponents:n.serializedComponents,parentName:this.componentName,assignNamesOffset:await this.stateValues.nChildrenAdded},{updateType:"updateValue",componentName:this.componentName,stateVariable:"nChildrenAdded",value:await this.stateValues.nChildrenAdded+n.serializedComponents.length}],actionId:t})}this.coreFunctions.resolveAction({actionId:t})}async deleteChildren({number:e,actionId:t}){let n=Math.min(e,await this.stateValues.nChildrenAdded);if(n>0){let e=this.definingChildren.length,r=this.definingChildren.slice(e-n,e).map((e=>e.componentName));return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"deleteComponents",componentNames:r},{updateType:"updateValue",componentName:this.componentName,stateVariable:"nChildrenAdded",value:await this.stateValues.nChildrenAdded-n}],actionId:t})}this.coreFunctions.resolveAction({actionId:t})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class Variables extends MathList{static componentType="variables";static stateVariableForAttributeValue="variables";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();e.variables={public:!0,shadowingInstructions:{createComponentOfType:"variable"},isArray:!0,entryPrefixes:["var"],returnArraySizeDependencies:()=>({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"}}),returnArraySize:({dependencyValues:e})=>[e.nComponents],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={math:{dependencyType:"stateVariable",variableName:"math"+(Number(n)+1)}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t)n[r]=e[r].math;return{setValue:{variables:n}}}};let t=this.componentType;return e.validVariables={returnDependencies:()=>({variables:{dependencyType:"stateVariable",variableName:"variables"}}),definition:function({dependencyValues:e}){let n=[];for(let r of e.variables){let e=isValidVariable(r);e||(console.warn("Invalid value for "+t),e=!1),n.push(e)}return{setValue:{validVariables:n}}}},e}}class Variable extends MathComponent{static componentType="variable";static rendererType="math";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.validVariable={returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:function({dependencyValues:e}){let t=isValidVariable(e.value);return t||console.warn("Invalid value of a "+this.componentType),{setValue:{validVariable:t}}}},e}}class Interval extends MathComponent{static componentType="interval";static rendererType="math";static createAttributesObject(){let e=super.createAttributesObject();return delete e.createIntervals,e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.createIntervals={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({}),definition:()=>({setValue:{createIntervals:!0}})},e}}class Group extends Template{static componentType="group";static renderedDefault=!0}class Option$1 extends Group{static componentType="option";static renderedDefault=!1;static createAttributesObject(){let e=super.createAttributesObject();return e.selectForVariants={createComponentOfType:"textListFromString",createStateVariable:"selectForVariants",defaultValue:[],public:!0},e.selectWeight={createComponentOfType:"number",createStateVariable:"selectWeight",defaultValue:1,public:!0},e}}class Sequence extends CompositeComponent{static componentType="sequence";static assignNamesToReplacements=!0;static stateVariableToEvaluateAfterReplacements="readyToExpandWhenResolved";static createAttributesObject(){let e=super.createAttributesObject();e.fixed={leaveRaw:!0},e.displayDigits={leaveRaw:!0},e.displayDecimals={leaveRaw:!0},e.displaySmallAsZero={leaveRaw:!0},e.padZeros={leaveRaw:!0};let t=returnStandardSequenceAttributes();return Object.assign(e,t),e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnStandardSequenceStateVariableDefinitions();return Object.assign(e,t),e.readyToExpandWhenResolved={returnDependencies:()=>({from:{dependencyType:"stateVariable",variableName:"from"},length:{dependencyType:"stateVariable",variableName:"length"},step:{dependencyType:"stateVariable",variableName:"step"},type:{dependencyType:"stateVariable",variableName:"type"},exclude:{dependencyType:"stateVariable",variableName:"exclude"}}),markStale:()=>({updateReplacements:!0}),definition:function(){return{setValue:{readyToExpandWhenResolved:!0}}}},e}static async createSerializedReplacements({component:e,workspace:t,componentInfoObjects:n,flags:r}){if(!await e.stateValues.validSequence)return t.lastReplacementParameters={from:null,length:null,step:null,type:null,exclude:null},{replacements:[]};let a=await e.stateValues.from,i=await e.stateValues.length,s=await e.stateValues.step,o=await e.stateValues.type,l=await e.stateValues.exclude;t.lastReplacementParameters={from:a,length:i,step:s,type:o,exclude:l};let u=e.attributes.newNamespace?.primitive,c=returnSequenceValues({from:a,step:s,length:i,exclude:l,type:o,lowercase:await e.stateValues.lowercase}),p=o;"letters"===o&&(p="text");let d=[],m={};for(let t of["fixed","displayDigits","displaySmallAsZero","displayDecimals","padZeros"])t in e.attributes&&(m[t]=e.attributes[t]);for(let e of c){let t={};Object.keys(m).length>0&&(t=convertAttributesForComponentType({attributes:m,componentType:p,componentInfoObjects:n,compositeCreatesNewNamespace:u,flags:r}));let a={componentType:p,attributes:t,state:{value:e,fixed:!0}};d.push(a)}return{replacements:processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:d,parentName:e.componentName,parentCreatesNewNamespace:u,componentInfoObjects:n}).serializedComponents}}static async calculateReplacementChanges({component:e,workspace:t,componentInfoObjects:n,flags:r}){let a=t.lastReplacementParameters,i=[];if(!await e.stateValues.validSequence){let t=e.replacementsToWithhold;if(t||(t=0),e.replacements.length-t>0){let t={changeType:"changeReplacementsToWithhold",replacementsToWithhold:e.replacements.length};i.push(t)}return a.length=0,i}let s=await e.stateValues.from,o=await e.stateValues.length,l=await e.stateValues.step,u=await e.stateValues.type,c=await e.stateValues.exclude,p=await e.stateValues.lowercase;if(a.type!==u||a.exclude.length>0||c.length>0){let a=(await this.createSerializedReplacements({component:e,workspace:t,componentInfoObjects:n,flags:r})).replacements,s={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:0,numberReplacementsToReplace:e.replacements.length,serializedReplacements:a,replacementsToWithhold:0};i.push(s)}else{let t=!1;"math"===u?s.equals(a.from)&&l.equals(a.step)||(t=!0):s===a.from&&l===a.step||(t=!0);let c,d=a.length,m=0,h=0,f=d;if(od&&(m=o-d,e.replacementsToWithhold>0))if(e.replacementsToWithhold>=m){c=e.replacementsToWithhold-m,h+=m,d+=m,m=0;let t={changeType:"changeReplacementsToWithhold",replacementsToWithhold:c};i.push(t)}else m-=e.replacementsToWithhold,h+=e.replacementsToWithhold,d+=e.replacementsToWithhold,c=0;if(!0===t&&(h=d,f=0),h>0)for(let t=f;t0){let t=[],a=e.attributes.newNamespace?.primitive,o={};for(let t of["fixed","displayDigits","displaySmallAsZero","displayDecimals","padZeros"])t in e.attributes&&(o[t]=e.attributes[t]);for(let i=d;i0&&(m=convertAttributesForComponentType({attributes:o,componentType:d,componentInfoObjects:n,compositeCreatesNewNamespace:a,flags:r}));let h={componentType:d,attributes:m,state:{value:c,fixed:!0}};t.push(h)}let c={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:d,serializedReplacements:processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:t,parentName:e.componentName,parentCreatesNewNamespace:a,componentInfoObjects:n,indOffset:d}).serializedComponents,replacementsToWithhold:0,assignNamesOffset:d};i.push(c)}}return a.type=u,a.from=s,a.length=o,a.step=l,a.exclude=c,i}get allPotentialRendererTypes(){let e=super.allPotentialRendererTypes,t="number";this.attributes.type&&this.attributes.type.primitive&&(t=this.attributes.type.primitive);let n=this.componentInfoObjects.allComponentClasses["letters"===t?"text":t].rendererType;return e.includes(n)||e.push(n),e}}class Map$1 extends CompositeComponent{static componentType="map";static assignNamesToReplacements=!0;static createsVariants=!0;static stateVariableToEvaluateAfterReplacements="readyToExpandWhenResolved";static createAttributesObject(){let e=super.createAttributesObject();return e.assignNamesSkip={createPrimitiveOfType:"number"},e.behavior={createComponentOfType:"text",createStateVariable:"behavior",defaultValue:"combination",public:!0,trim:!0},e.isResponse={leaveRaw:!0},e}static returnChildGroups(){return[{group:"templates",componentTypes:["template"]},{group:"sources",componentTypes:["sources"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nSources={additionalStateVariablesDefined:["sourcesNames","sourceAliases","sourceIndexAliases"],returnDependencies:()=>({sourcesChildren:{dependencyType:"child",childGroups:["sources"],variableNames:["alias","indexAlias"]}}),definition:function({dependencyValues:e}){return{setValue:{nSources:e.sourcesChildren.length,sourcesNames:e.sourcesChildren.map((e=>e.componentName)),sourceAliases:e.sourcesChildren.map((e=>e.stateValues.alias)),sourceIndexAliases:e.sourcesChildren.map((e=>e.stateValues.indexAlias))}}}},e.nIterates={additionalStateVariablesDefined:["minNIterates","sourcesChildNames"],returnDependencies:()=>({sourcesChildren:{dependencyType:"child",childGroups:["sources"],variableNames:["numberOfChildren","childComponentNames"]}}),definition:function({dependencyValues:e}){let t=e.sourcesChildren.map((e=>e.stateValues.numberOfChildren)),n=Math.min(...t),r=e.sourcesChildren.map((e=>[...e.stateValues.childComponentNames]));return{setValue:{nIterates:t,minNIterates:n,sourcesChildNames:r}}}},e.template={returnDependencies:()=>({templateChild:{dependencyType:"child",childGroups:["templates"],variableNames:["serializedChildren","newNamespace"]}}),definition:function({dependencyValues:e}){let t=e.templateChild[0];if(!t)return{setValue:{template:null}};let n={componentType:"template",state:{rendered:!0},children:t.stateValues.serializedChildren,originalName:t.componentName};return t.stateValues.newNamespace&&(n.attributes={newNamespace:{primitive:!0}}),{setValue:{template:n}}}},e.validBehavior={returnDependencies:()=>({behavior:{dependencyType:"stateVariable",variableName:"behavior"},nIterates:{dependencyType:"stateVariable",variableName:"nIterates"}}),definition:function({dependencyValues:e}){let t=!0;return"parallel"===e.behavior?e.nIterates.slice(1).some((t=>t!=e.nIterates[0]))&&console.warn("Warning: map with parallel behavior and different numbers of iterates in sources activeChildren. Extra iterates will be ignored."):"combination"!==e.behavior&&(console.warn("Invalid map behavior: "+e.behavior),t=!1),{setValue:{validBehavior:t}}}},e.readyToExpandWhenResolved={returnDependencies:()=>({validBehavior:{dependencyType:"stateVariable",variableName:"validBehavior"}}),markStale:()=>({updateReplacements:!0}),definition:function(){return{setValue:{readyToExpandWhenResolved:!0}}}},e.isVariantComponent={returnDependencies:()=>({}),definition:()=>({setValue:{isVariantComponent:!0}})},e.generatedVariantInfo={returnDependencies:({sharedParameters:e,componentInfoObjects:t})=>({variantSeed:{dependencyType:"value",value:e.variantSeed},variantDescendants:{dependencyType:"descendant",componentTypes:Object.keys(t.componentTypesCreatingVariants),variableNames:["isVariantComponent","generatedVariantInfo"],useReplacementsForComposites:!0,recurseToMatchedChildren:!1,variablesOptional:!0,includeNonActiveChildren:!0,ignoreReplacementsOfEncounteredComposites:!0}}),definition({dependencyValues:e,componentName:t}){let n={seed:e.variantSeed,meta:{createdBy:t}},r=n.subvariants=[];for(let t of e.variantDescendants)t.stateValues.isVariantComponent?r.push(t.stateValues.generatedVariantInfo):t.stateValues.generatedVariantInfo&&r.push(...t.stateValues.generatedVariantInfo.subvariants);return{setValue:{generatedVariantInfo:n}}}},e}static async createSerializedReplacements({component:e,workspace:t,componentInfoObjects:n,flags:r}){if(!await e.stateValues.validBehavior)return t.lastReplacementParameters={sourcesNames:[],sourcesChildNames:[],behavior:void 0,nIterates:void 0,minNIterates:void 0},{replacements:[]};t.lastReplacementParameters={sourcesNames:await e.stateValues.sourcesNames,sourcesChildNames:await e.stateValues.sourcesChildNames,behavior:await e.stateValues.behavior,nIterates:await e.stateValues.nIterates,minNIterates:await e.stateValues.minNIterates,replacementsToWithhold:0,withheldSubstitutionChildNames:[]};let a=[];if("parallel"===await e.stateValues.behavior)for(let t=0;t=c-1){r++;let t=[deepClone(p)],n={};n=convertAttributesForComponentType({attributes:e.attributes,componentType:t[0].componentType,componentInfoObjects:a,compositeAttributesObj:d,compositeCreatesNewNamespace:l,flags:i}),t[0].attributes||(t[0].attributes={}),Object.assign(t[0].attributes,n),!t[0].attributes.newNamespace?.primitive&&t[0].children&&markToCreateAllUniqueNames(t[0].children);let u=processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:t,parentName:e.componentName,parentCreatesNewNamespace:l,componentInfoObjects:a,indOffset:r}).serializedComponents[0];await addSharedParameters(u,e,o),s.push(u)}else{let n=await this.recurseThroughCombinations({component:e,sourcesNumber:t+1,childnumberArray:o,iterateNumber:r,componentInfoObjects:a,flags:i});s.push(...n.replacements),r=n.iterateNumber}return{replacements:s,iterateNumber:r}}static async calculateReplacementChanges({component:e,components:t,workspace:n,componentInfoObjects:r,flags:a}){let i=[];if(!await e.stateValues.validBehavior){if(n.lastReplacementParameters={sourcesNames:[],sourcesChildNames:[],behavior:void 0,nIterates:void 0,minNIterates:void 0,replacementsToWithhold:0,withheldSubstitutionChildNames:[]},e.replacements.length>0){let t={changeType:"delete",changeTopLevelReplacements:!0,firstReplacementInd:0,numberReplacementsToDelete:e.replacements.length,replacementsToWithhold:0};i.push(t)}return i}let s=n.lastReplacementParameters,o=!1,l=!0,u=await e.stateValues.nSources,c=await e.stateValues.sourcesNames;if(u!==s.sourcesNames.length)l=!1;else for(let e=0;e1&&(o=!0)}else o=!0;if(o){let t=await this.createSerializedReplacements({component:e,workspace:n,componentInfoObjects:r,flags:a}).replacements,s={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:0,numberReplacementsToReplace:e.replacements.length,serializedReplacements:t,replacementsToWithhold:0};return i.push(s),n.lastReplacementParameters={sourcesNames:c,sourcesChildNames:d,behavior:m,nIterates:p,minNIterates:await e.stateValues.minNIterates,replacementsToWithhold:0,withheldSubstitutionChildNames:[]},i}let h=await e.stateValues.minNIterates,f=s.minNIterates,y=0,g=e.replacementsToWithhold;g||(g=0);let b=s.withheldSubstitutionChildNames,v=!1;if(hf){let t=h-f;if(g>0)if(g>=t){y=g-t,t=0;let e={changeType:"changeReplacementsToWithhold",replacementsToWithhold:y};i.push(e)}else t-=g,f+=g,y=0;if(t>0){let t=[];for(let n=f;nr?{success:!1}:{success:!0,desiredVariant:{index:t}}}}async function addSharedParameters(e,t,n){let r=e.doenetAttributes.addToSharedParameters=[],a=await t.stateValues.sourcesNames;for(let[e,i]of(await t.stateValues.sourceAliases).entries())if(i){let t=a[e];r.push({parameterName:"sourceNameMappings",key:i,value:{name:t,childNumber:n[e]}})}for(let[e,a]of(await t.stateValues.sourceIndexAliases).entries())a&&r.push({parameterName:"sourceIndexMappings",key:a,value:n[e]+1})}class Sources extends BaseComponent{static componentType="sources";static rendererType="containerInline";static renderChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.alias={createPrimitiveOfType:"string",validationFunction:function(e){if(!/[a-zA-Z_]/.test(e.substring(0,1)))throw Error("All aliases must begin with a letter or an underscore");if(!/^[a-zA-Z0-9_\-]+$/.test(e))throw Error("Aliases can contain only letters, numbers, hyphens, and underscores");return e}},e.indexAlias={createPrimitiveOfType:"string",validationFunction:function(e){if(!/[a-zA-Z_]/.test(e.substring(0,1)))throw Error("All index aliases must begin with a letter or an underscore");if(!/^[a-zA-Z0-9_\-]+$/.test(e))throw Error("Index aliases can contain only letters, numbers, hyphens, and underscores");return e}},e}static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.alias={returnDependencies:()=>({alias:{dependencyType:"attributePrimitive",attributeName:"alias"}}),definition:({dependencyValues:e})=>({setValue:{alias:e.alias}})},e.indexAlias={returnDependencies:()=>({indexAlias:{dependencyType:"attributePrimitive",attributeName:"indexAlias"}}),definition:({dependencyValues:e})=>({setValue:{indexAlias:e.indexAlias}})},e.numberOfChildren={additionalStateVariablesDefined:["childComponentNames","childIdentities"],returnDependencies:()=>({children:{dependencyType:"child",childGroups:["anything"]}}),definition:function({dependencyValues:e}){let t=e.children.length,n=e.children.map((e=>e.componentName));return{setValue:{numberOfChildren:t,childComponentNames:n,childIdentities:e.children}}}},e}}class Slider extends BaseComponent{constructor(e){super(e),this.changeValue=this.changeValue.bind(this),Object.assign(this.actions,{changeValue:this.changeValue})}static componentType="slider";static variableForPlainMacro="value";static variableForPlainCopy="value";static createAttributesObject(){let e=super.createAttributesObject();return e.type={createPrimitiveOfType:"string",createStateVariable:"type",defaultValue:"number",toLowerCase:!0,validValues:["number","text"],forRenderer:!0},e.width={createComponentOfType:"_componentSize",createStateVariable:"width",defaultValue:{size:300,isAbsolute:!0},public:!0,forRenderer:!0},e.height={createComponentOfType:"_componentSize",createStateVariable:"height",defaultValue:{size:100,isAbsolute:!0},public:!0,forRenderer:!0},e.initialValue={createComponentOfType:"_componentWithSelectableType",createStateVariable:"initialValue",defaultValue:null},e.labelIsName={createComponentOfType:"boolean",createStateVariable:"labelIsName",defaultValue:!1,public:!0},e.showControls={createComponentOfType:"boolean",createStateVariable:"showControls",defaultValue:!1,public:!0,forRenderer:!0},e.showTicks={createComponentOfType:"boolean",createStateVariable:"showTicks",defaultValue:!0,public:!0,forRenderer:!0},e.showValue={createComponentOfType:"boolean",createStateVariable:"showValue",defaultValue:!0,public:!0,forRenderer:!0},e.from={createComponentOfType:"number",createStateVariable:"from",defaultValue:0,public:!0,forRenderer:!0},e.to={createComponentOfType:"number",createStateVariable:"to",defaultValue:10,public:!0,forRenderer:!0},e.step={createComponentOfType:"number",createStateVariable:"step",defaultValue:1,public:!0,forRenderer:!0},e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.bindValueTo={createComponentOfType:"_componentWithSelectableType"},e}static returnChildGroups(){return[{group:"numbersTexts",componentTypes:["number","text"]},{group:"markers",componentTypes:["markers"]},{group:"labels",componentTypes:["label"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnLabelStateVariableDefinitions();return Object.assign(e,t),e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.displayDigitsAttr){let n=t.displayDigitsAttr,r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!n&&!r){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({numberAndTextChildren:{dependencyType:"child",childGroups:["numbersTexts"],variableNames:["value"]},type:{dependencyType:"stateVariable",variableName:"type"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=[];if("text"===e.type)for(let r of e.numberAndTextChildren)t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"text"})?n.push(r.stateValues.value):n.push(r.stateValues.value.toString());else if(e.numberAndTextChildren.length>0){for(let r of e.numberAndTextChildren)if(t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"number"}))n.push(r.stateValues.value);else{let e=Number(r.stateValues.value);Number.isFinite(e)&&n.push(e)}n.sort(((e,t)=>e-t))}return{setValue:{items:n},setCreateComponentOfType:{items:e.type}}}},e.nItems={forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({items:{dependencyType:"stateVariable",variableName:"items"},from:{dependencyType:"stateVariable",variableName:"from"},to:{dependencyType:"stateVariable",variableName:"to"},step:{dependencyType:"stateVariable",variableName:"step"},type:{dependencyType:"stateVariable",variableName:"type"}}),definition({dependencyValues:e}){let t=e.items.length;return 0===t&&"number"===e.type&&(t=Math.floor((e.to-e.from)/e.step+1e-10)+1,t>=0&&Number.isFinite(t)||(t=0)),{setValue:{nItems:t}}}},e.firstItem={forRenderer:!0,returnDependencies:()=>({items:{dependencyType:"stateVariable",variableName:"items"},from:{dependencyType:"stateVariable",variableName:"from"},type:{dependencyType:"stateVariable",variableName:"type"}}),definition({dependencyValues:e}){let t;return t=e.items.length>0?e.items[0]:"number"===e.type?e.from:null,{setValue:{firstItem:t}}}},e.lastItem={forRenderer:!0,returnDependencies:()=>({items:{dependencyType:"stateVariable",variableName:"items"},from:{dependencyType:"stateVariable",variableName:"from"},nItems:{dependencyType:"stateVariable",variableName:"nItems"},step:{dependencyType:"stateVariable",variableName:"step"},type:{dependencyType:"stateVariable",variableName:"type"}}),definition({dependencyValues:e}){let t;return t=e.items.length>0?e.items[e.items.length-1]:"number"===e.type?e.from+(e.nItems-1)*e.step:null,{setValue:{lastItem:t}}}},e.valueToIndex={forRenderer:!0,returnDependencies:()=>({items:{dependencyType:"stateVariable",variableName:"items"}}),definition:function({dependencyValues:e}){let t={};for(let[n,r]of e.items.entries())t[r]=n;return{setValue:{valueToIndex:t}}}},e.preliminaryValue={hasEssential:!0,returnDependencies:()=>({type:{dependencyType:"stateVariable",variableName:"type"},initialValue:{dependencyType:"stateVariable",variableName:"initialValue"},bindValueTo:{dependencyType:"attributeComponent",attributeName:"bindValueTo",variableNames:["value"]}}),definition:({dependencyValues:e})=>e.bindValueTo?{setValue:{preliminaryValue:e.bindValueTo.stateValues.value}}:{useEssentialOrDefaultValue:{preliminaryValue:{get defaultValue(){return e.initialValue}}}},inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t})=>t.bindValueTo?{success:!0,instructions:[{setDependency:"bindValueTo",desiredValue:e.preliminaryValue,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"preliminaryValue",value:e.preliminaryValue}]}},e.index={forRenderer:!0,returnDependencies:()=>({type:{dependencyType:"stateVariable",variableName:"type"},valueToIndex:{dependencyType:"stateVariable",variableName:"valueToIndex"},items:{dependencyType:"stateVariable",variableName:"items"},preliminaryValue:{dependencyType:"stateVariable",variableName:"preliminaryValue"},from:{dependencyType:"stateVariable",variableName:"from"},step:{dependencyType:"stateVariable",variableName:"step"},nItems:{dependencyType:"stateVariable",variableName:"nItems"}}),definition:function({dependencyValues:e}){let t=findIndexOfClosestValidValue(e);return void 0===t&&(t=0),{setValue:{index:t}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){if(0===t.items.length){let n=t.from,r=t.step,a=e.index;return Number.isInteger(a)&&(a>=0&&a({type:{dependencyType:"stateVariable",variableName:"type"},items:{dependencyType:"stateVariable",variableName:"items"},index:{dependencyType:"stateVariable",variableName:"index"},from:{dependencyType:"stateVariable",variableName:"from"},step:{dependencyType:"stateVariable",variableName:"step"}}),definition:function({dependencyValues:e}){let t;return t=e.items.length>0?e.items[e.index]:e.from+e.step*e.index,{setValue:{value:t},setCreateComponentOfType:{value:e.type}}},inverseDefinition:invertSliderValue},e.valueForDisplay={forRenderer:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"}}),definition:function({dependencyValues:e,usedDefault:t}){return{setValue:{valueForDisplay:roundForDisplay({value:e.value,dependencyValues:e,usedDefault:t}).tree}}}},e.markers={forRenderer:!0,returnDependencies:()=>({markersChild:{dependencyType:"child",childGroups:["markers"],variableNames:["markerType","markers"]},type:{dependencyType:"stateVariable",variableName:"type"},items:{dependencyType:"stateVariable",variableName:"items"}}),definition:function({dependencyValues:e}){let t=[];if(e.markersChild.length>0){let n=e.markersChild[0].stateValues.markerType;"empty"===n?t=[...e.items]:n!==e.type?(console.warn("Markers type doesn't match slider type."),t=[]):t=e.markersChild[0].stateValues.markers}return{setValue:{markers:t}}}},e}async changeValue({value:e,transient:t,actionId:n}){if(!await this.stateValues.disabled)return t?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"value",value:e}],transient:t,actionId:n}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"value",value:e}],actionId:n,event:{verb:"selected",object:{componentName:this.componentName,componentType:this.componentType},result:{response:e,responseText:e.toString()}}});this.coreFunctions.resolveAction({actionId:n})}}function findIndexOfClosestValidValue({preliminaryValue:e,valueToIndex:t,type:n,items:r,from:a,step:i,nItems:s}){let o=e;if(0===r.length){if(!Number.isFinite(o))return;let e=Math.round((o-a)/i);return e>=0?er[e]?t:e;let n=Math.round((t+e)/2);return o>r[n]?u(n,t):u(e,n)},c=u();if(0!==c){let e=r[c-1],t=r[c];Math.abs(o-e)({textChildren:{dependencyType:"child",childGroups:["texts"]},numberChildren:{dependencyType:"child",childGroups:["numbers"]}}),definition:function({dependencyValues:e}){let t;return t=e.textChildren.length>0?"text":e.numberChildren.length>0?"number":"empty",{setValue:{markerType:t}}}},e.markers={public:!0,isArray:!0,shadowingInstructions:{hasVariableComponentType:!0},entryPrefixes:["item"],returnDependencies:()=>({markerType:{dependencyType:"stateVariable",variableName:"markerType"},textChildren:{dependencyType:"child",childGroups:["texts"],variableNames:["value"]},numberChildren:{dependencyType:"child",childGroups:["numbers"],variableNames:["value"]}}),definition:function({dependencyValues:e}){let t=[],n=e.markerType;return"text"===e.markerType?t=e.textChildren.map((e=>e.stateValues.value)):"number"===e.markerType?(t=e.numberChildren.map((e=>e.stateValues.value)),t.sort(((e,t)=>e-t))):n="text",{setValue:{markers:t},setCreateComponentOfType:{markers:n}}}},e}}function applyConstraintFromComponentConstraints({variables:e,applyComponentConstraint:t,scales:n}){let r={},a=!1;for(let i in e){let s=t({variables:{[i]:e[i]},scales:n});s.constrained&&(a=!0,r[i]=s.variables[i])}return a?{constrained:a,variables:r}:{}}class Constraints extends BaseComponent{static componentType="constraints";static rendererType=void 0;static createAttributesObject(){let e=super.createAttributesObject();return e.baseOnGraph={createTargetComponentNames:!0},e}static returnChildGroups(){return[{group:"constraints",componentTypes:["_constraint"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.independentComponentConstraints={returnDependencies:()=>({constraintChildren:{dependencyType:"child",childGroups:["constraints"],variableNames:["independentComponentConstraints"]}}),definition:({dependencyValues:e})=>({setValue:{independentComponentConstraints:e.constraintChildren.every((e=>e.stateValues.independentComponentConstraints))}})},e.arrayEntryPrefixForConstraints={returnDependencies:()=>({arrayEntryPrefixForConstraints:{dependencyType:"parentStateVariable",variableName:"arrayEntryPrefixForConstraints"}}),definition:({dependencyValues:e})=>({setValue:{arrayEntryPrefixForConstraints:e.arrayEntryPrefixForConstraints}})},e.arrayVariableForConstraints={returnDependencies:()=>({arrayVariableForConstraints:{dependencyType:"parentStateVariable",variableName:"arrayVariableForConstraints"}}),definition:({dependencyValues:e})=>({setValue:{arrayVariableForConstraints:e.arrayVariableForConstraints}})},e.nDimensions={returnDependencies:()=>({nDimensions:{dependencyType:"parentStateVariable",variableName:"nDimensionsForConstraints"}}),definition:({dependencyValues:e})=>({setValue:{nDimensions:e.nDimensions}})},e.graphComponentName={returnDependencies:()=>({graphComponentName:{dependencyType:"attributeTargetComponentNames",attributeName:"baseOnGraph"}}),definition:({dependencyValues:e})=>1===e.graphComponentName?.length?{setValue:{graphComponentName:e.graphComponentName[0].absoluteName}}:{setValue:{graphComponentName:null}}},e.scales={public:!0,shadowingInstructions:{createComponentOfType:"number"},stateVariablesDeterminingDependencies:["graphComponentName"],returnDependencies:({stateValues:e})=>e.graphComponentName?{graph:{dependencyType:"multipleStateVariables",componentName:e.graphComponentName,variableNames:["xscale","yscale"],variablesOptional:!0}}:{},definition({dependencyValues:e}){if(e.graph){let t=e.graph.stateValues,n=[t.xscale,t.yscale,1];if(n.every((e=>Number.isFinite(e)&&e>0)))return{setValue:{scales:n}}}return{setValue:{scales:[1,1,1]}}}},e.graphXmin={additionalStateVariablesDefined:["graphXmax","graphYmin","graphYmax"],stateVariablesDeterminingDependencies:["graphComponentName"],returnDependencies:({stateValues:e})=>e.graphComponentName?{graph:{dependencyType:"multipleStateVariables",componentName:e.graphComponentName,variableNames:["xmin","xmax","ymin","ymax"],variablesOptional:!0}}:{},definition({dependencyValues:e}){if(!e.graph)return{setValue:{graphXmin:null,graphXmax:null,graphYmin:null,graphYmax:null}};let t=e.graph.stateValues.xmin,n=e.graph.stateValues.xmax,r=e.graph.stateValues.ymin,a=e.graph.stateValues.ymax;return[t,n,r,a].every(Number.isFinite)?{setValue:{graphXmin:t,graphXmax:n,graphYmin:r,graphYmax:a}}:{setValue:{graphXmin:null,graphXmax:null,graphYmin:null,graphYmax:null}}}},e.constraintResults={additionalStateVariablesDefined:[{variableName:"constraintUsedByComponent",isArray:!0,entryPrefixes:["constraintUsedByComponent"]}],isArray:!0,entryPrefixes:["constraintResult"],stateVariablesDeterminingDependencies:["independentComponentConstraints","arrayEntryPrefixForConstraints","arrayVariableForConstraints"],returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={constraintChildren:{dependencyType:"child",childGroups:["constraints"],variableNames:["applyConstraint","applyComponentConstraint"],variablesOptional:!0},independentComponentConstraints:{dependencyType:"stateVariable",variableName:"independentComponentConstraints"},scales:{dependencyType:"stateVariable",variableName:"scales"}},r=t.arrayEntryPrefixForConstraints,a={};if(t.independentComponentConstraints)for(let t of e)a[t]={x:{dependencyType:"parentStateVariable",variableName:r+(Number(t)+1)}};else{let e=t.arrayVariableForConstraints?t.arrayVariableForConstraints:"__null";n.xs={dependencyType:"parentStateVariable",variableName:e}}return{globalDependencies:n,dependenciesByKey:a}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){if(e.independentComponentConstraints){let r={},a={};for(let i of n){let n=Number(i)+1,s={["x"+n]:t[i].x},o=!1;for(let t of e.constraintChildren){let r=t.stateValues.applyComponentConstraint({variables:s,scales:e.scales});r.constrained&&(s["x"+n]=convertValueToMathExpression(r.variables["x"+n]),o=!0)}r[i]=s["x"+n],a[i]=o}return{setValue:{constraintResults:r,constraintUsedByComponent:a}}}{let t={},n=!1;for(let n in e.xs)t[`x${Number(n)+1}`]=e.xs[n];for(let r of e.constraintChildren){let a;if(a=r.stateValues.applyConstraint?r.stateValues.applyConstraint({variables:t,scales:e.scales}):applyConstraintFromComponentConstraints({variables:t,applyComponentConstraint:r.stateValues.applyComponentConstraint,scales:e.scales}),a.constrained){for(let e in a.variables)t[e]=convertValueToMathExpression(a.variables[e]);n=!0}}let r={},a={};for(let i in e.xs)r[i]=t[`x${Number(i)+1}`],a[i]=n;return{setValue:{constraintResults:r,constraintUsedByComponent:a}}}},inverseArrayDefinitionByKey:async function({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,stateValues:a,workspace:i}){if(t.independentComponentConstraints){let n=[];for(let a in e.constraintResults){let i=Number(a)+1,s={["x"+i]:convertValueToMathExpression(e.constraintResults[a])};for(let e of t.constraintChildren){let n=e.stateValues.applyComponentConstraint({variables:s,scales:t.scales});n.constrained&&(s["x"+i]=convertValueToMathExpression(n.variables["x"+i]))}n.push({setDependency:r[a].x,desiredValue:s["x"+i]})}return{success:!0,instructions:n}}{let n={};i.desiredConstraintResults||(i.desiredConstraintResults={}),Object.assign(i.desiredConstraintResults,e.constraintResults);let r=await a.constraintResults;for(let e in r){let t=Number(e)+1;e in i.desiredConstraintResults?n["x"+t]=convertValueToMathExpression(i.desiredConstraintResults[e]):n["x"+t]=convertValueToMathExpression(r[e])}for(let e of t.constraintChildren){let r;if(r=e.stateValues.applyConstraint?e.stateValues.applyConstraint({variables:n,scales:t.scales}):applyConstraintFromComponentConstraints({variables:n,applyComponentConstraint:e.stateValues.applyComponentConstraint,scales:t.scales}),r.constrained)for(let e in r.variables)n[e]=convertValueToMathExpression(r.variables[e])}let s={};for(let e in i.desiredConstraintResults)s[e]=n[`x${Number(e)+1}`];return{success:!0,instructions:[{setDependency:"xs",desiredValue:s}]}}}},e.constraintUsed={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({constraintUsedByComponent:{dependencyType:"stateVariable",variableName:"constraintUsedByComponent"}}),definition:function({dependencyValues:e}){let t=Object.values(e.constraintUsedByComponent).some((e=>e));return{setValue:{constraintUsed:t}}}},e}}class ConstraintComponent extends BaseComponent{static componentType="_constraint";static rendererType=void 0;static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.independentComponentConstraints={returnDependencies:()=>({}),definition:()=>({setValue:{independentComponentConstraints:!1}})},e}}class ConstrainToGrid extends ConstraintComponent{static componentType="constrainToGrid";static createAttributesObject(){let e=super.createAttributesObject();return e.dx={createComponentOfType:"number",createStateVariable:"dx",defaultValue:1,public:!0},e.dy={createComponentOfType:"number",createStateVariable:"dy",defaultValue:1,public:!0},e.dz={createComponentOfType:"number",createStateVariable:"dz",defaultValue:1,public:!0},e.xoffset={createComponentOfType:"number",createStateVariable:"xoffset",defaultValue:0,public:!0},e.yoffset={createComponentOfType:"number",createStateVariable:"yoffset",defaultValue:0,public:!0},e.zoffset={createComponentOfType:"number",createStateVariable:"zoffset",defaultValue:0,public:!0},e.ignoreGraphBounds={createComponentOfType:"boolean",createStateVariable:"ignoreGraphBounds",defaultValue:!1,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.independentComponentConstraints={returnDependencies:()=>({}),definition:()=>({setValue:{independentComponentConstraints:!0}})},e.applyComponentConstraint={returnDependencies:()=>({dx:{dependencyType:"stateVariable",variableName:"dx"},dy:{dependencyType:"stateVariable",variableName:"dy"},dz:{dependencyType:"stateVariable",variableName:"dz"},xoffset:{dependencyType:"stateVariable",variableName:"xoffset"},yoffset:{dependencyType:"stateVariable",variableName:"yoffset"},zoffset:{dependencyType:"stateVariable",variableName:"zoffset"},constraintAncestor:{dependencyType:"ancestor",componentType:"constraints",variableNames:["graphXmin","graphXmax","graphYmin","graphYmax"]},graphAncestor:{dependencyType:"ancestor",componentType:"graph",variableNames:["xmin","xmax","ymin","ymax"]},ignoreGraphBounds:{dependencyType:"stateVariable",variableName:"ignoreGraphBounds"}}),definition:({dependencyValues:e})=>({setValue:{applyComponentConstraint:function({variables:t,scales:n}){let r;if(null!==e.constraintAncestor&&null!==e.constraintAncestor.stateValues.graphXmin?r="constraints":null!==e.graphAncestor&&null!==e.graphAncestor.stateValues.xmin&&(r="graph"),"x1"in t){let n=findFiniteNumericalValue(t.x1);if(!Number.isFinite(n))return{};let a=e.dx,i=e.xoffset,s=Math.round((n-i)/a)*a+i;if(Number.isFinite(s)){if(!e.ignoreGraphBounds){let t,n;"constraints"===r?(t=e.constraintAncestor.stateValues.graphXmin,n=e.constraintAncestor.stateValues.graphXmax):"graph"===r&&(t=e.graphAncestor.stateValues.xmin,n=e.graphAncestor.stateValues.xmax),void 0!==t&&(sn&&(s=Math.floor((n-i)/a)*a+i))}return{constrained:!0,variables:{x1:s}}}return{}}if("x2"in t){let n=findFiniteNumericalValue(t.x2);if(!Number.isFinite(n))return{};let a=e.dy,i=e.yoffset,s=Math.round((n-i)/a)*a+i;if(Number.isFinite(s)){if(!e.ignoreGraphBounds){let t,n;"constraints"===r?(t=e.constraintAncestor.stateValues.graphYmin,n=e.constraintAncestor.stateValues.graphYmax):"graph"===r&&(t=e.graphAncestor.stateValues.ymin,n=e.graphAncestor.stateValues.ymax),void 0!==t&&(sn&&(s=Math.floor((n-i)/a)*a+i))}return{constrained:!0,variables:{x2:s}}}return{}}if("x3"in t){let n=findFiniteNumericalValue(t.x3);if(!Number.isFinite(n))return{};let r=e.dz,a=e.zoffset,i=Math.round((n-a)/r)*r+a;return Number.isFinite(i)?{constrained:!0,variables:{x3:i}}:{}}return{}}}})},e}}class ConstrainToGraph extends ConstraintComponent{static componentType="constrainToGraph";static createAttributesObject(){let e=super.createAttributesObject();return e.buffer={createComponentOfType:"number",createStateVariable:"buffer",defaultValue:.01,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.independentComponentConstraints={returnDependencies:()=>({}),definition:()=>({setValue:{independentComponentConstraints:!0}})},e.applyComponentConstraint={returnDependencies:()=>({constraintAncestor:{dependencyType:"ancestor",componentType:"constraints",variableNames:["graphXmin","graphXmax","graphYmin","graphYmax"]},buffer:{dependencyType:"stateVariable",variableName:"buffer"},graphAncestor:{dependencyType:"ancestor",componentType:"graph",variableNames:["xmin","xmax","ymin","ymax"]}}),definition:({dependencyValues:e})=>({setValue:{applyComponentConstraint:function({variables:t,scales:n}){let r;if(null!==e.constraintAncestor&&null!==e.constraintAncestor.stateValues.graphXmin?r="constraints":null!==e.graphAncestor&&null!==e.graphAncestor.stateValues.xmin&&(r="graph"),!r)return{};if("x1"in t){let n,a,i=findFiniteNumericalValue(t.x1);if(!Number.isFinite(i))return{};if("constraints"===r?(n=e.constraintAncestor.stateValues.graphXmin,a=e.constraintAncestor.stateValues.graphXmax):(n=e.graphAncestor.stateValues.xmin,a=e.graphAncestor.stateValues.xmax),!Number.isFinite(n)||!Number.isFinite(a))return{};let s=n,o=a,l=e.buffer;if(l>0){let e=l*(a-n);s+=e,o-=e}return{constrained:!0,variables:{x1:Math.max(s,Math.min(o,i))}}}if("x2"in t){let n,a,i=findFiniteNumericalValue(t.x2);if(!Number.isFinite(i))return{};if("constraints"===r?(n=e.constraintAncestor.stateValues.graphYmin,a=e.constraintAncestor.stateValues.graphYmax):(n=e.graphAncestor.stateValues.ymin,a=e.graphAncestor.stateValues.ymax),!Number.isFinite(n)||!Number.isFinite(a))return{};let s=n,o=a,l=e.buffer;if(l>0){let e=l*(a-n);s+=e,o-=e}return{constrained:!0,variables:{x2:Math.max(s,Math.min(o,i))}}}return{}}}})},e}}class AttractToGrid extends ConstraintComponent{static componentType="attractToGrid";static createAttributesObject(){let e=super.createAttributesObject();return e.dx={createComponentOfType:"number",createStateVariable:"dx",defaultValue:1,public:!0},e.dy={createComponentOfType:"number",createStateVariable:"dy",defaultValue:1,public:!0},e.dz={createComponentOfType:"number",createStateVariable:"dz",defaultValue:1,public:!0},e.xoffset={createComponentOfType:"number",createStateVariable:"xoffset",defaultValue:0,public:!0},e.yoffset={createComponentOfType:"number",createStateVariable:"yoffset",defaultValue:0,public:!0},e.zoffset={createComponentOfType:"number",createStateVariable:"zoffset",defaultValue:0,public:!0},e.xthreshold={createComponentOfType:"number",createStateVariable:"xthreshold",defaultValue:.2,public:!0},e.ythreshold={createComponentOfType:"number",createStateVariable:"ythreshold",defaultValue:.2,public:!0},e.zthreshold={createComponentOfType:"number",createStateVariable:"zthreshold",defaultValue:.2,public:!0},e.includeGridlines={createComponentOfType:"boolean",createStateVariable:"includeGridlines",defaultValue:!1,public:!0},e.ignoreGraphBounds={createComponentOfType:"boolean",createStateVariable:"ignoreGraphBounds",defaultValue:!1,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.independentComponentConstraints={returnDependencies:()=>({includeGridlines:{dependencyType:"stateVariable",variableName:"includeGridlines"}}),definition:({dependencyValues:e})=>({setValue:{independentComponentConstraints:e.includeGridlines}})},e.applyComponentConstraint={returnDependencies:()=>({dx:{dependencyType:"stateVariable",variableName:"dx"},dy:{dependencyType:"stateVariable",variableName:"dy"},dz:{dependencyType:"stateVariable",variableName:"dz"},xoffset:{dependencyType:"stateVariable",variableName:"xoffset"},yoffset:{dependencyType:"stateVariable",variableName:"yoffset"},zoffset:{dependencyType:"stateVariable",variableName:"zoffset"},xthreshold:{dependencyType:"stateVariable",variableName:"xthreshold"},ythreshold:{dependencyType:"stateVariable",variableName:"ythreshold"},zthreshold:{dependencyType:"stateVariable",variableName:"zthreshold"},constraintAncestor:{dependencyType:"ancestor",componentType:"constraints",variableNames:["graphXmin","graphXmax","graphYmin","graphYmax"]},graphAncestor:{dependencyType:"ancestor",componentType:"graph",variableNames:["xmin","xmax","ymin","ymax"]},ignoreGraphBounds:{dependencyType:"stateVariable",variableName:"ignoreGraphBounds"}}),definition:({dependencyValues:e})=>({setValue:{applyComponentConstraint:function({variables:t,scales:n}){let r;if(null!==e.constraintAncestor&&null!==e.constraintAncestor.stateValues.graphXmin?r="constraints":null!==e.graphAncestor&&null!==e.graphAncestor.stateValues.xmin&&(r="graph"),"x1"in t){let n=findFiniteNumericalValue(t.x1);if(!Number.isFinite(n))return{};let a=e.dx,i=e.xoffset,s=Math.round((n-i)/a)*a+i;if(!Number.isFinite(s))return{};if(!e.ignoreGraphBounds){let t,n;"constraints"===r?(t=e.constraintAncestor.stateValues.graphXmin,n=e.constraintAncestor.stateValues.graphXmax):"graph"===r&&(t=e.graphAncestor.stateValues.xmin,n=e.graphAncestor.stateValues.xmax),void 0!==t&&(sn&&(s=Math.floor((n-i)/a)*a+i))}return Math.abs(n-s)n&&(s=Math.floor((n-i)/a)*a+i))}return Math.abs(n-s)({dx:{dependencyType:"stateVariable",variableName:"dx"},dy:{dependencyType:"stateVariable",variableName:"dy"},dz:{dependencyType:"stateVariable",variableName:"dz"},xoffset:{dependencyType:"stateVariable",variableName:"xoffset"},yoffset:{dependencyType:"stateVariable",variableName:"yoffset"},zoffset:{dependencyType:"stateVariable",variableName:"zoffset"},xthreshold:{dependencyType:"stateVariable",variableName:"xthreshold"},ythreshold:{dependencyType:"stateVariable",variableName:"ythreshold"},zthreshold:{dependencyType:"stateVariable",variableName:"zthreshold"},includeGridlines:{dependencyType:"stateVariable",variableName:"includeGridlines"},applyComponentConstraint:{dependencyType:"stateVariable",variableName:"applyComponentConstraint"}}),definition:({dependencyValues:e})=>({setValue:{applyConstraint:function({variables:t,scales:n}){let r={},a=!1;for(let i in t){let s=e.applyComponentConstraint({variables:{[i]:t[i]},scales:n});s.constrained&&(a=!0,r[i]=s.variables[i])}if(!a)return{};if(!e.includeGridlines){if(void 0!==t.x1&&void 0===r.x1)return{};if(void 0!==t.x2&&void 0===r.x2)return{};if(void 0!==t.x3&&void 0===r.x3)return{}}return{constrained:a,variables:r}}}})},e}}class ConstrainTo extends ConstraintComponent{static componentType="constrainTo";static returnChildGroups(){return[{group:"graphical",componentTypes:["_graphical"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nearestPointFunctions={returnDependencies:()=>({graphicalChildren:{dependencyType:"child",childGroups:["graphical"],variableNames:["nearestPoint"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let t=[];for(let n of e.graphicalChildren)n.stateValues.nearestPoint?t.push(n.stateValues.nearestPoint):console.warn(`cannot attract to ${n.componentName} as it doesn't have a nearestPoint state variable`);return{setValue:{nearestPointFunctions:t}}}},e.applyConstraint={returnDependencies:()=>({nearestPointFunctions:{dependencyType:"stateVariable",variableName:"nearestPointFunctions"}}),definition:({dependencyValues:e})=>({setValue:{applyConstraint:function({variables:t,scales:n}){let r=1/0,a={},i=!1,s={};for(let e in t)s[e]=findFiniteNumericalValue(t[e]);for(let o of e.nearestPointFunctions){let e=o({variables:t,scales:n});if(void 0===e)continue;let l={},u=0;if(void 0!==s.x1){if(void 0===e.x1)continue;l.x1=e.x1,u+=Math.pow(s.x1-e.x1,2)}if(void 0!==s.x2){if(void 0===e.x2)continue;l.x2=e.x2,u+=Math.pow(s.x2-e.x2,2)}if(void 0!==s.x3){if(void 0===e.x3)continue;l.x3=e.x3,u+=Math.pow(s.x3-e.x3,2)}u({thresholdAttr:{dependencyType:"attributeComponent",attributeName:"threshold",variableNames:["value"]},constraintsAncestor:{dependencyType:"ancestor",componentType:"constraints",variableNames:["graphXmin"]}}),definition({dependencyValues:e}){if(e.thresholdAttr)return{setValue:{threshold:e.thresholdAttr.stateValues.value}};{let t=.02;return null!==e.constraintsAncestor&&null!==e.constraintsAncestor.stateValues.graphXmin||(t=.5),{useEssentialOrDefaultValue:{threshold:{defaultValue:t}}}}},inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t})=>t.thresholdAttr?{success:!0,instructions:[{setDependency:"thresholdAttr",desiredValue:e.threshold}]}:{success:!0,instructions:[{setEssentialValue:"threshold",value:e.threshold}]}},e.nearestPointFunctions={returnDependencies:()=>({graphicalChildren:{dependencyType:"child",childGroups:["graphical"],variableNames:["nearestPoint"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let t=[];for(let n of e.graphicalChildren)n.stateValues.nearestPoint?t.push(n.stateValues.nearestPoint):console.warn(`cannot attract to ${n.componentName} as it doesn't have a nearestPoint state variable`);return{setValue:{nearestPointFunctions:t}}}},e.graphXscale={additionalStateVariablesDefined:["graphYscale"],returnDependencies:()=>({graphAncestor:{dependencyType:"ancestor",componentType:"constraints",variableNames:["scales"]}}),definition({dependencyValues:e}){if(!e.graphAncestor)return{setValue:{graphXscale:null,graphYscale:null}};return{setValue:{graphXscale:e.graphAncestor.stateValues.xscale,graphYscale:e.graphAncestor.stateValues.yscale}}}},e.applyConstraint={returnDependencies:()=>({nearestPointFunctions:{dependencyType:"stateVariable",variableName:"nearestPointFunctions"},threshold:{dependencyType:"stateVariable",variableName:"threshold"},constraintsAncestor:{dependencyType:"ancestor",componentType:"constraints",variableNames:["scales"]}}),definition({dependencyValues:e}){let t=1,n=1;return e.constraintsAncestor&&([t,n]=e.constraintsAncestor.stateValues.scales),{setValue:{applyConstraint:function({variables:r,scales:a}){let i=1/0,s={},o={};for(let e in r)o[e]=findFiniteNumericalValue(r[e]);for(let l of e.nearestPointFunctions){let e=l({variables:r,scales:a});if(void 0===e)continue;let u={},c=0;if(void 0!==o.x1){if(void 0===e.x1)continue;u.x1=e.x1,c+=Math.pow((o.x1-e.x1)/t,2)}if(void 0!==o.x2){if(void 0===e.x2)continue;u.x2=e.x2,c+=Math.pow((o.x2-e.x2)/n,2)}if(void 0!==o.x3){if(void 0===e.x3)continue;u.x3=e.x3,c+=Math.pow(o.x3-e.x3,2)}ce.threshold*e.threshold?{}:{constrained:!0,variables:s}}}}}},e}}class ConstraintUnion extends ConstraintComponent{static componentType="constraintUnion";static returnChildGroups(){return[{group:"constraints",componentTypes:["_constraint"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.applyConstraint={returnDependencies:()=>({constraintChildren:{dependencyType:"child",childGroups:["constraints"],variableNames:["applyConstraint","applyComponentConstraint"],variablesOptional:!0}}),definition:({dependencyValues:e})=>({setValue:{applyConstraint:function({variables:t,scales:n}){let r;if(1===e.constraintChildren.length){let a=e.constraintChildren[0];return r=a.stateValues.applyConstraint?a.stateValues.applyConstraint({variables:t,scales:n}):applyConstraintFromComponentConstraints({variables:t,applyComponentConstraint:a.stateValues.applyComponentConstraint,scales:n}),r}let a,i=1/0,s={};for(let[o,l]of e.constraintChildren.entries()){if(r=l.stateValues.applyConstraint?l.stateValues.applyConstraint({variables:t,scales:n}):applyConstraintFromComponentConstraints({variables:t,applyComponentConstraint:l.stateValues.applyComponentConstraint,scales:n}),!r.constrained)continue;let e=0;for(let n in r.variables){let a=findFiniteNumericalValue(t[n]),i=findFiniteNumericalValue(r.variables[n]);if(!Number.isFinite(a)||!Number.isFinite(i)){e=1/0;break}e+=Math.pow(a-i,2)}e({constraintChild:{dependencyType:"child",childGroups:["constraints"],variableNames:["applyConstraint","applyComponentConstraint"],variablesOptional:!0},independentComponentConstraints:{dependencyType:"stateVariable",variableName:"independentComponentConstraints"},threshold:{dependencyType:"stateVariable",variableName:"threshold"}}),definition:({dependencyValues:e})=>({setValue:{applyConstraint:function({variables:t,scales:n}){let r,a=e.constraintChild[0];if(!a)return{};r=a.stateValues.applyConstraint?a.stateValues.applyConstraint({variables:t,scales:n}):applyConstraintFromComponentConstraints({variables:t,applyComponentConstraint:a.stateValues.applyComponentConstraint,scales:n});let i=0;for(let e in r.variables){let n=findFiniteNumericalValue(t[e]),a=findFiniteNumericalValue(r.variables[e]);if(!Number.isFinite(n)||!Number.isFinite(a))return{};i+=Math.pow(n-a,2)}return i>e.threshold*e.threshold?{}:r}}})},e}}class Intersection extends CompositeComponent{static componentType="intersection";static assignNamesToReplacements=!0;static stateVariableToEvaluateAfterReplacements="readyToExpandWhenResolved";static createAttributesObject(){let e=super.createAttributesObject();return e.assignNamesSkip={createPrimitiveOfType:"number"},e}static returnChildGroups(){return[{group:"lines",componentTypes:["line"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.lineChildren={returnDependencies:()=>({lineChildren:{dependencyType:"child",childGroups:["lines"],variableNames:["numericalCoeff0","numericalCoeffvar1","numericalCoeffvar2","nDimensions"]}}),definition:({dependencyValues:e})=>({setValue:{lineChildren:e.lineChildren}})},e.readyToExpandWhenResolved={returnDependencies:()=>({lineChildren:{dependencyType:"stateVariable",variableName:"lineChildren"}}),markStale:()=>({updateReplacements:!0}),definition:function(){return{setValue:{readyToExpandWhenResolved:!0}}}},e}static async createSerializedReplacements({component:e,components:t,componentInfoObjects:n}){let r=await e.stateValues.lineChildren,a=r.length;if(0===a)return{replacements:[]};if(1===a){let a=r[0].componentName,i=await t[a].serialize({sourceAttributesToIgnoreRecursively:["isResponse"]});i.state||(i.state={}),i.state.draggable=!1,i.state.fixed=!0;let s=postProcessCopy({serializedComponents:[i],componentName:e.componentName}),o=e.attributes.newNamespace?.primitive;return s=processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:s,parentName:e.componentName,parentCreatesNewNamespace:o,componentInfoObjects:n}).serializedComponents,{replacements:s}}if(a>2)return console.warn("Haven't implemented intersection for more than two objects"),{replacements:[]};let i=r[0],s=r[1];if(2!==i.stateValues.nDimensions||2!==s.stateValues.nDimensions)return console.log("Intersection of lines implemented only in 2D"),{replacements:[]};let o=i.stateValues.numericalCoeffvar1,l=i.stateValues.numericalCoeffvar2,u=i.stateValues.numericalCoeff0,c=s.stateValues.numericalCoeffvar1,p=s.stateValues.numericalCoeffvar2,d=s.stateValues.numericalCoeff0;if(!(Number.isFinite(o)&&Number.isFinite(l)&&Number.isFinite(u)&&Number.isFinite(c)&&Number.isFinite(p)&&Number.isFinite(d)))return console.log("Intersection of lines implemented only for constant coefficients"),{replacements:[]};let m=o*p-c*l;if(Math.abs(m)<1e-14){if(Math.abs(d*o-u*c)>1e-14)return{replacements:[]};if(0===o&&0===l&&0===u||0===c&&0===p&&0===d)return{replacements:[]};{let a=r[0].componentName,i=await t[a].serialize({sourceAttributesToIgnoreRecursively:["isResponse"]});i.state||(i.state={}),i.state.draggable=!1,i.state.fixed=!0;let s=postProcessCopy({serializedComponents:[i],componentName:e.componentName}),o=e.attributes.newNamespace?.primitive;return s=processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:s,parentName:e.componentName,parentCreatesNewNamespace:o,componentInfoObjects:n}).serializedComponents,{replacements:s}}}let h=(d*l-u*p)/m,f=(u*c-d*o)/m,y=[{componentType:"point",state:{coords:me$3.fromAst(["vector",h,f]),draggable:!1,fixed:!0}}],g=e.attributes.newNamespace?.primitive;return y=processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:y,parentName:e.componentName,parentCreatesNewNamespace:g,componentInfoObjects:n}).serializedComponents,{replacements:y}}static async calculateReplacementChanges({component:e,components:t,componentInfoObjects:n}){let r=[],a=(await this.createSerializedReplacements({component:e,components:t,componentInfoObjects:n})).replacements,i=a.length,s=!0;if(i===e.replacements.length){s=!1;for(let t=0;t({children:{dependencyType:"child",childGroups:["anything"],variableNames:["width"]},columns:{dependencyType:"stateVariable",variableName:"columns"}}),definition:function({dependencyValues:e}){let t=[],n=e.children.map((e=>e.stateValues.width));if(null!==e.columns){let r;if(-1!==e.columns.indexOf(","))r=e.columns.split(",").map(Number);else if(-1!==e.columns.indexOf("-")){let[t,n]=e.columns.split("-");r=[];for(let e=Number(t);e<=n;e++)r.push(e)}else r=[Number(e.columns)];let a={},i={};for(let e of r){let t=[],r=0;for(let a=0;ai&&(i=n[t]);t.push(i),r+=Number(i)}a[e]=t,i[e]=r}let s=-1;for(let e of r){let e=Number.POSITIVE_INFINITY,n=-1;for(let t of r)i[t]<=e&&t>s&&(e=i[t],n=t);e=this.state.threshold?{}:{variables:{x1:p,x2:d},constraintIndices:[i+1],constrained:!0}}}class ConditionalContent extends CompositeComponent{static componentType="conditionalContent";static includeBlankStringChildren=!0;static assignNamesToReplacements=!0;static createsVariants=!0;static stateVariableToEvaluateAfterReplacements="readyToExpandWhenResolved";static keepChildrenSerialized({serializedComponent:e,componentInfoObjects:t}){if(void 0===e.children)return[];let n=t.componentIsSpecifiedType,r=[];for(let[t,a]of e.children.entries())n(a,"case")||n(a,"else")||r.push(t);return r}static createAttributesObject(){let e=super.createAttributesObject();return e.assignNamesSkip={createPrimitiveOfType:"number"},e.maximumNumberToShow={createComponentOfType:"number",createStateVariable:"maximumNumberToShow",defaultValue:null,public:!0},e.condition={createComponentOfType:"boolean"},e}static returnChildGroups(){return[{group:"cases",componentTypes:["case"]},{group:"elses",componentTypes:["else"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.baseConditionSatisfied={returnDependencies:()=>({conditionAttr:{dependencyType:"attributeComponent",attributeName:"condition",variableNames:["value"]}}),definition:function({dependencyValues:e}){let t=!0;return e.conditionAttr&&(t=e.conditionAttr.stateValues.value),{setValue:{baseConditionSatisfied:t}}}},e.nCases={additionalStateVariablesDefined:["caseChildren"],returnDependencies:()=>({caseChildren:{dependencyType:"child",childGroups:["cases"]}}),definition:({dependencyValues:e})=>({setValue:{caseChildren:e.caseChildren,nCases:e.caseChildren.length}})},e.elseChild={returnDependencies:()=>({elseChild:{dependencyType:"child",childGroups:["elses"]}}),definition({dependencyValues:e}){let t=null;return e.elseChild.length>0&&(t=e.elseChild[0]),{setValue:{elseChild:t}}}},e.haveCasesOrElse={returnDependencies:()=>({nCases:{dependencyType:"stateVariable",variableName:"nCases"},elseChild:{dependencyType:"stateVariable",variableName:"elseChild"}}),definition:({dependencyValues:e})=>({setValue:{haveCasesOrElse:e.nCases>0||null!==e.elseChild}})},e.selectedIndices={returnDependencies:()=>({caseChildren:{dependencyType:"child",childGroups:["cases"],variableNames:["conditionSatisfied"]},elseChild:{dependencyType:"stateVariable",variableName:"elseChild"},maximumNumberToShow:{dependencyType:"stateVariable",variableName:"maximumNumberToShow"}}),definition({dependencyValues:e}){let t=[];for(let[n,r]of e.caseChildren.entries())r.stateValues.conditionSatisfied&&t.push(n);if(0===t.length&&e.elseChild&&t.push(e.caseChildren.length),null!==e.maximumNumberToShow&&t.length>e.maximumNumberToShow){let n=Math.max(0,Math.floor(e.maximumNumberToShow));t=t.slice(0,n)}return{setValue:{selectedIndices:t}}}},e.readyToExpandWhenResolved={returnDependencies:()=>({baseConditionSatisfied:{dependencyType:"stateVariable",variableName:"baseConditionSatisfied"},haveCasesOrElse:{dependencyType:"stateVariable",variableName:"haveCasesOrElse"},selectedIndices:{dependencyType:"stateVariable",variableName:"selectedIndices"}}),markStale:()=>({updateReplacements:!0}),definition:()=>({setValue:{readyToExpandWhenResolved:!0}})},e.isVariantComponent={returnDependencies:()=>({}),definition:()=>({setValue:{isVariantComponent:!0}})},e.generatedVariantInfo={returnDependencies:({sharedParameters:e,componentInfoObjects:t})=>({variantSeed:{dependencyType:"value",value:e.variantSeed},variantDescendants:{dependencyType:"descendant",componentTypes:Object.keys(t.componentTypesCreatingVariants),variableNames:["isVariantComponent","generatedVariantInfo"],useReplacementsForComposites:!0,recurseToMatchedChildren:!1,variablesOptional:!0,includeNonActiveChildren:!0,ignoreReplacementsOfEncounteredComposites:!0}}),definition({dependencyValues:e,componentName:t}){let n={seed:e.variantSeed,meta:{createdBy:t}},r=n.subvariants=[];for(let t of e.variantDescendants)t.stateValues.isVariantComponent?r.push(t.stateValues.generatedVariantInfo):t.stateValues.generatedVariantInfo&&r.push(...t.stateValues.generatedVariantInfo.subvariants);return{setValue:{generatedVariantInfo:n}}}},e}static async createSerializedReplacements({component:e,components:t,workspace:n,componentInfoObjects:r}){let a=await this.getReplacements(e,t,r);return n.previousSelectedIndices=[...await e.stateValues.selectedIndices],n.previousBaseConditionSatisfied=await e.stateValues.baseConditionSatisfied,{replacements:a}}static async getReplacements(e,t,n){if(!await e.stateValues.baseConditionSatisfied)return[];let r=[];if(await e.stateValues.haveCasesOrElse){let n=await e.stateValues.caseChildren;for(let[a,i]of(await e.stateValues.selectedIndices).entries()){let s,o,l;ie===i[t]))){if(r.previousBaseConditionSatisfied===s)return[];if(!s){let t={changeType:"changeReplacementsToWithhold",replacementsToWithhold:e.replacements.length};return r.previousBaseConditionSatisfied=s,[t]}if(e.replacements.length===e.serializedChildren.length){let e={changeType:"changeReplacementsToWithhold",replacementsToWithhold:0};return r.previousBaseConditionSatisfied=s,[e]}}let o=[],l=await this.getReplacements(e,n,a),u={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:0,numberReplacementsToReplace:e.replacements.length,serializedReplacements:l,replacementsToWithhold:0};return o.push(u),r.previousSelectedIndices=[...i],r.previousBaseConditionSatisfied=s,o}static setUpVariant({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n}){setUpVariantSeedAndRng({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n,useSubpartVariantRng:!0})}get allPotentialRendererTypes(){let e=super.allPotentialRendererTypes;if(this.serializedChildren){let t=this.potentialRendererTypesFromSerializedComponents(this.serializedChildren);for(let n of t)e.includes(n)||e.push(n)}return e}}class AsList extends InlineComponent{static componentType="asList";static renderChildren=!0;static returnChildGroups(){return[{group:"inline",componentTypes:["_inline"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["inline"],variableNames:["text"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let t=[];for(let n of e.inlineChildren)"object"!=typeof n?t.push(n.toString()):"string"==typeof n.stateValues.text?t.push(n.stateValues.text):t.push("");return{setValue:{text:t.join(", ")}}}},e.latex={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["inline"],variableNames:["text","latex"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let t=[];for(let n of e.inlineChildren)"object"!=typeof n?t.push(n.toString()):"string"==typeof n.stateValues.latex?t.push(n.stateValues.latex):"string"==typeof n.stateValues.text?t.push(n.stateValues.text):t.push("");return{setValue:{latex:t.join(", ")}}}},e}}function normalizeIndex(e){if(null!==e&&""!==e){if(Number.isFinite(Number(e)))return Number(e)-1;if("string"==typeof e)return lettersToNumber(e)}}function lettersToNumber(e){let t=0,n=(e=e.toUpperCase()).length,r=n;for(;(r-=1)>-1;){let a=e.charCodeAt(r)-64;if(a<1||a>26)return void console.warn("Cannot convert "+e+" to a number");t+=a*Math.pow(26,n-1-r)}return t--,t} +let n=poly_div(e,[t]),r=0,a=n[0].length;for(var i=0;i15?n:(t=Math.round(t),round_numbers_to_precision_sub(n,t))}const round_numbers_to_precision_sub=function(e,t=14){if("number"==typeof e&&Number.isFinite(e)&&0!==e){const n=math$1.floor(math$1.log10(math$1.abs(e))),r=t-n-1;return r<0?parseFloat(toFixed(e,r)+"0".repeat(math$1.abs(r))):parseFloat(toFixed(e,r))}return Array.isArray(e)?[e[0],...e.slice(1).map((e=>round_numbers_to_precision_sub(e,t)))]:e};function round_numbers_to_decimals(e,t=14){var n=get_tree(e);if(!Number.isFinite(t))throw Error("For round_numbers_to_decimals, ndecimals must be a number");return t=Math.round(t),t=Math.max(-330,Math.min(330,t)),round_numbers_to_decimals_sub(n,t)}const round_numbers_to_decimals_sub=function(e,t=0){return"number"==typeof e?t<0?parseFloat(toFixed(e,t)+"0".repeat(math$1.abs(t))):parseFloat(toFixed(e,t)):Array.isArray(e)?[e[0],...e.slice(1).map((e=>round_numbers_to_decimals_sub(e,t)))]:e};var round=Object.freeze({__proto__:null,round_numbers_to_precision:round_numbers_to_precision,round_numbers_to_decimals:round_numbers_to_decimals});const match=function(e,t,n){let r=get_tree(e),a=get_tree(t);return match$2(r,a,n)};var match$1=Object.freeze({__proto__:null,match:match});const expression_to_tree$1=[simplify$1,differentiation,normalization,arithmetic,transformation,solve,sets,matrix$1,rational,round],expression_to_other=[variables$1,printing,equality,integration,evaluation,analytic,sign_error,match$1];function abs(e){return["apply","abs",get_tree(e)]}function exp(e){return["apply","exp",get_tree(e)]}function log(e){return["apply","log",get_tree(e)]}function log10(e){return["apply","log10",get_tree(e)]}function sign(e){return["apply","sign",get_tree(e)]}function sqrt(e){return["apply","sqrt",get_tree(e)]}function conj(e){return["apply","conj",get_tree(e)]}function im(e){return["apply","im",get_tree(e)]}function re(e){return["apply","re",get_tree(e)]}function factorial(e){return["apply","factorial",get_tree(e)]}function gamma(e){return["apply","gamma",get_tree(e)]}function erf(e){return["apply","erf",get_tree(e)]}function acos(e){return["apply","acos",get_tree(e)]}function acosh(e){return["apply","acosh",get_tree(e)]}function acot(e){return["apply","acot",get_tree(e)]}function acoth(e){return["apply","acoth",get_tree(e)]}function acsc(e){return["apply","acsc",get_tree(e)]}function acsch(e){return["apply","acsch",get_tree(e)]}function asec(e){return["apply","asec",get_tree(e)]}function asech(e){return["apply","asech",get_tree(e)]}function asin(e){return["apply","asin",get_tree(e)]}function asinh(e){return["apply","asinh",get_tree(e)]}function atan(e){return["apply","atan",get_tree(e)]}function atanh(e){return["apply","atanh",get_tree(e)]}function cos(e){return["apply","cos",get_tree(e)]}function cosh(e){return["apply","cosh",get_tree(e)]}function cot(e){return["apply","cot",get_tree(e)]}function coth(e){return["apply","coth",get_tree(e)]}function csc(e){return["apply","csc",get_tree(e)]}function csch(e){return["apply","csch",get_tree(e)]}function sec(e){return["apply","sec",get_tree(e)]}function sech(e){return["apply","sech",get_tree(e)]}function sin(e){return["apply","sin",get_tree(e)]}function sinh(e){return["apply","sinh",get_tree(e)]}function tan(e){return["apply","tan",get_tree(e)]}function tanh(e){return["apply","tanh",get_tree(e)]}function atan2(e,t){return["apply","atan2",["tuple",get_tree(e),get_tree(t)]]}var standard=Object.freeze({__proto__:null,abs:abs,exp:exp,log:log,log10:log10,sign:sign,sqrt:sqrt,conj:conj,im:im,re:re,factorial:factorial,gamma:gamma,erf:erf,acos:acos,acosh:acosh,acot:acot,acoth:acoth,acsc:acsc,acsch:acsch,asec:asec,asech:asech,asin:asin,asinh:asinh,atan:atan,atanh:atanh,cos:cos,cosh:cosh,cot:cot,coth:coth,csc:csc,csch:csch,sec:sec,sech:sech,sin:sin,sinh:sinh,tan:tan,tanh:tanh,atan2:atan2});const expression_to_tree=[standard],whitespace_rule="\\s|\\\\,|\\\\!|\\\\ |\\\\>|\\\\;|\\\\:|\\\\quad\\b|\\\\qquad\\b",sci_notat_exp_regex="(E[+\\-]?[0-9]+\\s*($|(?=\\,|&|\\||\\\\\\||\\)|\\}|\\\\}|\\]|\\\\\\\\|\\\\end)))?",number_rules_sci=[["[0-9]+(\\.[0-9]*)?"+sci_notat_exp_regex,"NUMBER"],["\\.[0-9]+"+sci_notat_exp_regex,"NUMBER"]],number_rules_non_sci=[["[0-9]+(\\.[0-9]*)?","NUMBER"],["\\.[0-9]+","NUMBER"]],base_latex_rules=[["\\*","*"],["\\/","/"],["-","-"],["\\+","+"],["\\^","^"],["\\(","("],["\\\\left\\s*\\(","("],["\\\\bigl\\s*\\(","("],["\\\\Bigl\\s*\\(","("],["\\\\biggl\\s*\\(","("],["\\\\Biggl\\s*\\(","("],["\\)",")"],["\\\\right\\s*\\)",")"],["\\\\bigr\\s*\\)",")"],["\\\\Bigr\\s*\\)",")"],["\\\\biggr\\s*\\)",")"],["\\\\Biggr\\s*\\)",")"],["\\[","["],["\\\\left\\s*\\[","["],["\\\\bigl\\s*\\[","["],["\\\\Bigl\\s*\\[","["],["\\\\biggl\\s*\\[","["],["\\\\Biggl\\s*\\[","["],["\\]","]"],["\\\\right\\s*\\]","]"],["\\\\bigr\\s*\\]","]"],["\\\\Bigr\\s*\\]","]"],["\\\\biggr\\s*\\]","]"],["\\\\Biggr\\s*\\]","]"],["\\|","|"],["\\\\left\\s*\\|","|L"],["\\\\bigl\\s*\\|","|L"],["\\\\Bigl\\s*\\|","|L"],["\\\\biggl\\s*\\|","|L"],["\\\\Biggl\\s*\\|","|L"],["\\\\right\\s*\\|","|"],["\\\\bigr\\s*\\|","|"],["\\\\Bigr\\s*\\|","|"],["\\\\biggr\\s*\\|","|"],["\\\\Biggr\\s*\\|","|"],["\\\\big\\s*\\|","|"],["\\\\Big\\s*\\|","|"],["\\\\bigg\\s*\\|","|"],["\\\\Bigg\\s*\\|","|"],["{","{"],["}","}"],["\\\\{","LBRACE"],["\\\\left\\s*\\\\{","LBRACE"],["\\\\bigl\\s*\\\\{","LBRACE"],["\\\\Bigl\\s*\\\\{","LBRACE"],["\\\\biggl\\s*\\\\{","LBRACE"],["\\\\Biggl\\s*\\\\{","LBRACE"],["\\\\}","RBRACE"],["\\\\right\\s*\\\\}","RBRACE"],["\\\\bigr\\s*\\\\}","RBRACE"],["\\\\Bigr\\s*\\\\}","RBRACE"],["\\\\biggr\\s*\\\\}","RBRACE"],["\\\\Biggr\\s*\\\\}","RBRACE"],["\\\\lfloor(?![a-zA-Z])","LFLOOR"],["\\\\left\\s*\\\\lfloor(?![a-zA-Z])","LFLOOR"],["\\\\bigl\\s*\\\\lfloor(?![a-zA-Z])","LFLOOR"],["\\\\Bigl\\s*\\\\lfloor(?![a-zA-Z])","LFLOOR"],["\\\\biggl\\s*\\\\lfloor(?![a-zA-Z])","LFLOOR"],["\\\\Biggl\\s*\\\\lfloor(?![a-zA-Z])","LFLOOR"],["\\\\rfloor(?![a-zA-Z])","RFLOOR"],["\\\\right\\s*\\\\rfloor(?![a-zA-Z])","RFLOOR"],["\\\\bigr\\s*\\\\rfloor(?![a-zA-Z])","RFLOOR"],["\\\\Bigr\\s*\\\\rfloor(?![a-zA-Z])","RFLOOR"],["\\\\biggr\\s*\\\\rfloor(?![a-zA-Z])","RFLOOR"],["\\\\Biggr\\s*\\\\rfloor(?![a-zA-Z])","RFLOOR"],["\\\\lceil(?![a-zA-Z])","LCEIL"],["\\\\left\\s*\\\\lceil(?![a-zA-Z])","LCEIL"],["\\\\bigl\\s*\\\\lceil(?![a-zA-Z])","LCEIL"],["\\\\Bigl\\s*\\\\lceil(?![a-zA-Z])","LCEIL"],["\\\\biggl\\s*\\\\lceil(?![a-zA-Z])","LCEIL"],["\\\\Biggl\\s*\\\\lceil(?![a-zA-Z])","LCEIL"],["\\\\rceil(?![a-zA-Z])","RCEIL"],["\\\\right\\s*\\\\rceil(?![a-zA-Z])","RCEIL"],["\\\\bigr\\s*\\\\rceil(?![a-zA-Z])","RCEIL"],["\\\\Bigr\\s*\\\\rceil(?![a-zA-Z])","RCEIL"],["\\\\biggr\\s*\\\\rceil(?![a-zA-Z])","RCEIL"],["\\\\Biggr\\s*\\\\rceil(?![a-zA-Z])","RCEIL"],["\\\\langle(?![a-zA-Z])","LANGLE"],["\\\\left\\s*\\\\langle(?![a-zA-Z])","LANGLE"],["\\\\bigl\\s*\\\\langle(?![a-zA-Z])","LANGLE"],["\\\\Bigl\\s*\\\\langle(?![a-zA-Z])","LANGLE"],["\\\\biggl\\s*\\\\langle(?![a-zA-Z])","LANGLE"],["\\\\Biggl\\s*\\\\langle(?![a-zA-Z])","LANGLE"],["\\\\rangle(?![a-zA-Z])","RANGLE"],["\\\\right\\s*\\\\rangle(?![a-zA-Z])","RANGLE"],["\\\\bigr\\s*\\\\rangle(?![a-zA-Z])","RANGLE"],["\\\\Bigr\\s*\\\\rangle(?![a-zA-Z])","RANGLE"],["\\\\biggr\\s*\\\\rangle(?![a-zA-Z])","RANGLE"],["\\\\Biggr\\s*\\\\rangle(?![a-zA-Z])","RANGLE"],["\\\\cdot(?![a-zA-Z])","*"],["\\\\div(?![a-zA-Z])","/"],["\\\\times(?![a-zA-Z])","*"],[",",","],[":",":"],["\\\\mid(?![a-zA-Z])","MID"],["\\\\vartheta(?![a-zA-Z])","LATEXCOMMAND","\\theta"],["\\\\varepsilon(?![a-zA-Z])","LATEXCOMMAND","\\epsilon"],["\\\\varrho(?![a-zA-Z])","LATEXCOMMAND","\\rho"],["\\\\varphi(?![a-zA-Z])","LATEXCOMMAND","\\phi"],["\\\\infty(?![a-zA-Z])","INFINITY"],["\\\\asin(?![a-zA-Z])","LATEXCOMMAND","\\arcsin"],["\\\\acos(?![a-zA-Z])","LATEXCOMMAND","\\arccos"],["\\\\atan(?![a-zA-Z])","LATEXCOMMAND","\\arctan"],["\\\\sqrt(?![a-zA-Z])","SQRT"],["\\\\land(?![a-zA-Z])","AND"],["\\\\wedge(?![a-zA-Z])","AND"],["\\\\lor(?![a-zA-Z])","OR"],["\\\\vee(?![a-zA-Z])","OR"],["\\\\lnot(?![a-zA-Z])","NOT"],["=","="],["\\\\neq(?![a-zA-Z])","NE"],["\\\\ne(?![a-zA-Z])","NE"],["\\\\not\\s*=","NE"],["\\\\leq(?![a-zA-Z])","LE"],["\\\\le(?![a-zA-Z])","LE"],["\\\\geq(?![a-zA-Z])","GE"],["\\\\ge(?![a-zA-Z])","GE"],["<","<"],["\\\\lt(?![a-zA-Z])","<"],[">",">"],["\\\\gt(?![a-zA-Z])",">"],["\\\\in(?![a-zA-Z])","IN"],["\\\\notin(?![a-zA-Z])","NOTIN"],["\\\\not\\s*\\\\in(?![a-zA-Z])","NOTIN"],["\\\\ni(?![a-zA-Z])","NI"],["\\\\not\\s*\\\\ni(?![a-zA-Z])","NOTNI"],["\\\\subset(?![a-zA-Z])","SUBSET"],["\\\\subseteq(?![a-zA-Z])","SUBSETEQ"],["\\\\not\\s*\\\\subset(?![a-zA-Z])","NOTSUBSET"],["\\\\not\\s*\\\\subseteq(?![a-zA-Z])","NOTSUBSETEQ"],["\\\\supset(?![a-zA-Z])","SUPERSET"],["\\\\supseteq(?![a-zA-Z])","SUPERSETEQ"],["\\\\not\\s*\\\\supset(?![a-zA-Z])","NOTSUPERSET"],["\\\\not\\s*\\\\supseteq(?![a-zA-Z])","NOTSUPERSETEQ"],["\\\\cup(?![a-zA-Z])","UNION"],["\\\\cap(?![a-zA-Z])","INTERSECT"],["\\\\perp(?![a-zA-Z])","PERP"],["\\\\bot(?![a-zA-Z])","PERP"],["\\\\parallel(?![a-zA-Z])","PARALLEL"],["\\\\\\|","PARALLEL"],["\\\\angle(?![a-zA-Z])","ANGLE"],["\\\\int(?![a-zA-Z])","INT"],["!","!"],["'","'"],["_","_"],["&","&"],["\\\\ldots(?![a-zA-Z])","LDOTS"],["\\\\\\\\","LINEBREAK"],["\\\\begin\\s*{\\s*[a-zA-Z0-9]+\\s*}","BEGINENVIRONMENT"],["\\\\end\\s*{\\s*[a-zA-Z0-9]+\\s*}","ENDENVIRONMENT"],["\\\\operatorname\\s*{\\s*[a-zA-Z0-9\\+\\-]+\\s*}","VARMULTICHAR"],["\\\\[a-zA-Z]+(?![a-zA-Z])","LATEXCOMMAND"],["\\\\[$%]","LATEXCOMMAND"],["[a-zA-Z_$%]","VAR"]],allowSimplifiedFunctionApplicationDefault=!0,allowedLatexSymbolsDefault=["alpha","beta","gamma","Gamma","delta","Delta","epsilon","zeta","eta","theta","Theta","iota","kappa","lambda","Lambda","mu","nu","xi","Xi","pi","Pi","rho","sigma","Sigma","tau","Tau","upsilon","Upsilon","phi","Phi","chi","psi","Psi","omega","Omega","partial","angle","circ","%","$"],appliedFunctionSymbolsDefault=["abs","exp","log","ln","log10","sign","sqrt","erf","cos","cosh","acos","acosh","arccos","arccosh","cot","coth","acot","acoth","arccot","arccoth","csc","csch","acsc","acsch","arccsc","arccsch","sec","sech","asec","asech","arcsec","arcsech","sin","sinh","asin","asinh","arcsin","arcsinh","tan","tanh","atan","atan2","atanh","arctan","arctanh","arg","conj","Re","Im","det","trace","nPr","nCr","floor","ceil","round"],functionSymbolsDefault=["f","g"],operatorSymbolsDefault={frac:{nargs:2,substitute:"/"},binom:{nargs:2},vec:{nargs:1},overline:{nargs:1,substitute:"linesegment",remove_products:!0}},unitsDefault=get_all_units();unitsDefault.circ=unitsDefault.deg,unitsDefault.circ.substitute="deg",unitsDefault.circ.isExponent=!0,delete unitsDefault.deg;const parseLeibnizNotationDefault=!0;class latexToAst$1{constructor({allowSimplifiedFunctionApplication:e=allowSimplifiedFunctionApplicationDefault,allowedLatexSymbols:t=allowedLatexSymbolsDefault,appliedFunctionSymbols:n=appliedFunctionSymbolsDefault,functionSymbols:r=functionSymbolsDefault,operatorSymbols:a=operatorSymbolsDefault,units:i=unitsDefault,parseLeibnizNotation:s=parseLeibnizNotationDefault,parseScientificNotation:o=!0}={}){this.allowSimplifiedFunctionApplication=e,this.allowedLatexSymbols=t,this.appliedFunctionSymbols=n,this.functionSymbols=r,this.operatorSymbols=a,this.units=i,this.parseLeibnizNotation=s;let l=base_latex_rules;l=o?[...number_rules_sci,...l]:[...number_rules_non_sci,...l],this.lexer=new lexer(l,whitespace_rule)}advance(e){if(this.token=this.lexer.advance(e),"INVALID"===this.token.token_type)throw new ParseError("Invalid symbol '"+this.token.original_text+"'",this.lexer.location)}return_state(){return{lexer_state:this.lexer.return_state(),token:Object.assign({},this.token)}}set_state(e){this.lexer.set_state(e.lexer_state),this.token=Object.assign({},e.token)}convert(e){this.lexer.set_input(e),this.advance();var t=this.statement_list();if("EOF"!==this.token.token_type)throw new ParseError("Invalid location of '"+this.token.original_text+"'",this.lexer.location);return flatten(t)}statement_list(){for(var e=[this.statement()];","===this.token.token_type;)this.advance(),e.push(this.statement());return e.length>1?["list"].concat(e):e[0]}statement({inside_absolute_value:e=0}={}){if("LDOTS"===this.token.token_type)return this.advance(),["ldots"];var t;try{t=this.return_state();let n=this.statement_a({inside_absolute_value:e});if(":"!==this.token.token_type&&"MID"!==this.token.token_type)return n;let r=":"===this.token.token_type?":":"|";return this.advance(),[r,n,this.statement_a()]}catch(e){try{this.set_state(t);let n=this.statement_a({parse_absolute_value:!1});if("|"!==this.token.token_type[0])throw e;return this.advance(),["|",n,this.statement_a({parse_absolute_value:!1})]}catch(t){throw e}}}statement_a({inside_absolute_value:e=0,parse_absolute_value:t=!0}={}){for(var n=this.statement_b({inside_absolute_value:e,parse_absolute_value:t});"OR"===this.token.token_type;){let r=this.token.token_type.toLowerCase();this.advance(),n=[r,n,this.statement_b({inside_absolute_value:e,parse_absolute_value:t})]}return n}statement_b(e){for(var t=this.relation(e);"AND"===this.token.token_type;){let n=this.token.token_type.toLowerCase();this.advance(),t=[n,t,this.relation(e)]}return t}relation(e){if("NOT"===this.token.token_type||"!"===this.token.token_type)return this.advance(),["not",this.relation(e)];for(var t=this.expression(e);"="===this.token.token_type||"NE"===this.token.token_type||"<"===this.token.token_type||">"===this.token.token_type||"LE"===this.token.token_type||"GE"===this.token.token_type||"IN"===this.token.token_type||"NOTIN"===this.token.token_type||"NI"===this.token.token_type||"NOTNI"===this.token.token_type||"SUBSET"===this.token.token_type||"NOTSUBSET"===this.token.token_type||"SUBSETEQ"===this.token.token_type||"NOTSUBSETEQ"===this.token.token_type||"SUPERSET"===this.token.token_type||"NOTSUPERSET"===this.token.token_type||"SUPERSETEQ"===this.token.token_type||"NOTSUPERSETEQ"===this.token.token_type;){let n=this.token.token_type.toLowerCase(),r=0;"<"===this.token.token_type||"LE"===this.token.token_type?r=-1:">"!==this.token.token_type&&"GE"!==this.token.token_type||(r=1),this.advance();let a=this.expression(e);if(-1===r)if("<"===this.token.token_type||"LE"===this.token.token_type){let r=["tuple"];"<"===n?r.push(!0):r.push(!1);let i=["tuple",t,a];for(;"<"===this.token.token_type||"LE"===this.token.token_type;)"<"===this.token.token_type?r.push(!0):r.push(!1),this.advance(),i.push(this.expression(e));t=["lts",i,r]}else t=[n,t,a];else if(1===r)if(">"===this.token.token_type||"GE"===this.token.token_type){let r=["tuple"];">"===n?r.push(!0):r.push(!1);let i=["tuple",t,a];for(;">"===this.token.token_type||"GE"===this.token.token_type;)">"===this.token.token_type?r.push(!0):r.push(!1),this.advance(),i.push(this.expression(e));t=["gts",i,r]}else t=[n,t,a];else if("="===n)for(t=["=",t,a];"="===this.token.token_type;)this.advance(),t.push(this.expression(e));else t=[n,t,a]}return t}expression(e){let t=!1;"+"===this.token.token_type&&(t=!0,this.advance());let n=!1;"-"===this.token.token_type&&(n=!0,this.advance());var r=this.term(e);if(n||t){if(!1===r)return(t?"+":"")+(n?"-":"");if("string"==typeof r&&[...r].every((e=>["+","-"].includes(e))))return(t?"+":"")+(n?"-":"")+r}for(!1===r&&(r="_"),n&&(r=r>0?-r:["-",r]),t&&(r=["+",r]);["+","-","UNION","INTERSECT","PERP","PARALLEL"].includes(this.token.token_type);){let t=this.token.token_type.toLowerCase(),n=!1,a=!1;"-"===this.token.token_type?(t="+",n=!0,this.advance()):(this.advance(),"+"===t&&"-"===this.token.token_type&&(n=!0,a=!0,this.advance()));let i=this.term(e);if("+"===t){if(!1===i&&("number"==typeof r||"string"==typeof r))return a?r+"+-":n?r+"-":r+"+";if("string"==typeof i&&[...i].every((e=>["+","-"].includes(e)))&&("number"==typeof r||"string"==typeof r))return a?r+"+-"+i:n?r+"-"+i:r+"+"+i}!1===i&&(i="_"),n&&(i=i>0?-i:["-",i]),r=[t,r,i]}return r}term(e){var t=this.factor(e),n=!1;do{if(n=!1,"*"===this.token.token_type){this.advance(),!1===t&&(t="_");let r=this.factor(e);!1===r&&(r="_"),t=["*",t,r],n=!0}else if("/"===this.token.token_type){this.advance(),!1===t&&(t="_");let r=this.factor(e);!1===r&&(r="_"),t=["/",t,r],n=!0}else{let r=Object.assign({},e);r.allow_absolute_value_closing=!0;let a=this.nonMinusFactor(r);!1!==a&&(!1===t&&(t="_"),t=["*",t,a],n=!0)}}while(n);return this.convert_units_in_term(flatten(t))}convert_units_in_term(e){if(!Array.isArray(e))return e;let t=e[0],n=e.slice(1);if("*"===t){let e=n.length;for(let[t,r]of n.entries()){let a=this.units[r];if(a){if(a.prefix&&t0){let i,s=r;return a.substitute&&(s=a.substitute),i=1===t?["unit",n[0],s]:["unit",["*",...n.slice(0,t).map(this.convert_units_in_term.bind(this))],s],t===e-1?i:this.convert_units_in_term(["*",i,...n.slice(t+1)])}}}return[t,...n.map(this.convert_units_in_term.bind(this))]}if("/"===t)return["/",this.convert_units_in_term(n[0]),this.convert_units_in_term(n[1])];if("^"===t){let e=this.units[n[1]];if(e&&e.isExponent){let t=n[1];return e.substitute&&(t=e.substitute),["unit",n[0],t]}return[t,...n.map(this.convert_units_in_term.bind(this))]}return[t,...n.map(this.convert_units_in_term.bind(this))]}factor(e){if("+"===this.token.token_text){this.advance();let t=this.factor(e);return!1===t?"+":"string"==typeof t&&[...t].every((e=>["+","-"].includes(e)))?"+"+t:["+",t]}if("-"===this.token.token_type){this.advance();let t=this.factor(e);return t>0?-t:!1===t?"-":"string"==typeof t&&[...t].every((e=>["+","-"].includes(e)))?"-"+t:["-",t]}let t=this.nonMinusFactor(e);return!1===t&&"PERP"===this.token.token_type&&(t="perp",this.advance()),t}nonMinusFactor(e){for(var t=this.baseFactor(e);"^"===this.token.token_type||"!"===this.token.token_type||"'"===this.token.token_type;)!1===t&&(t="_"),"^"===this.token.token_type?(this.advance(),t=["^",t,this.get_subsuperscript(e)]):"!"===this.token.token_type?(t=["apply","factorial",t],this.advance()):(t=["prime",t],this.advance());return t}get_single_digit_as_number(){if("NUMBER"===this.token.token_type&&"."!==this.token.token_text[0]){let e=Number(this.token.token_text[0]);return this.token.token_text.length>1&&this.lexer.unput(this.token.token_text.slice(1)),this.advance(),e}return null}get_subsuperscript({parse_absolute_value:e}){let t=this.get_single_digit_as_number();if(null!==t)return t;if(["+","-","PERP"].includes(this.token.token_type)){let e=this.token.token_type.toLowerCase();return this.advance(),e}{let t=this.baseFactor({parse_absolute_value:e,in_subsuperscript_with_no_delimiters:!0});return!1===t&&(t="_"),t}}baseFactor({inside_absolute_value:e=0,parse_absolute_value:t=!0,allow_absolute_value_closing:n=!1,in_subsuperscript_with_no_delimiters:r=!1}={}){var a=!1;if("BEGINENVIRONMENT"===this.token.token_type){let e=/\\begin\s*{\s*([a-zA-Z0-9]+)\s*}/.exec(this.token.token_text)[1];if(["matrix","pmatrix","bmatrix"].includes(e)){let n=0,r=0,i=[],s=[],o=0,l=this.token.token_type;for(this.advance();"ENDENVIRONMENT"!==this.token.token_type;)"&"===this.token.token_type?("&"!==l&&"LINEBREAK"!==l||(s.push(0),o+=1),l=this.token.token_type,this.advance()):"LINEBREAK"===this.token.token_type?("&"!==l&&"LINEBREAK"!==l||(s.push(0),o+=1),i.push(s),o>r&&(r=o),n+=1,o=0,s=[],l=this.token.token_type,this.advance()):(s.push(this.statement({parse_absolute_value:t})),o+=1,l=" ");if(/\\end\s*{\s*([a-zA-Z0-9]+)\s*}/.exec(this.token.token_text)[1]!==e)throw new ParseError("Expecting \\end{"+e+"}",this.lexer.location);"&"===l&&(s.push(0),o+=1),i.push(s),o>r&&(r=o),n+=1,this.advance(),a=["matrix",["tuple",n,r]];let u=["tuple"];for(let e of i){let t=["tuple"].concat(e);for(let n=e.length;n=2?a[0]="("===n||"{"===n?"tuple":"["===n?"array":"LBRACE"===n?"set":"altvector":"LBRACE"===n&&("|"===a[0]||a[0],a=["set",a]);this.advance()}else if("|"!==this.token.token_type[0]||!t||0!==e&&n&&"L"!==this.token.token_type[1]){if("LFLOOR"===this.token.token_type||"LCEIL"===this.token.token_type){let e,t;if("LFLOOR"===this.token.token_type?(e="RFLOOR",t="floor"):"LCEIL"===this.token.token_type&&(e="RCEIL",t="ceil"),this.advance(),a=["apply",t,a=this.statement()],this.token.token_type!==e)throw new ParseError("Expecting "+e,this.lexer.location);this.advance()}else if("ANGLE"===this.token.token_type)if(this.advance(),"{"===this.token.token_type||"("===this.token.token_type){let e;e="{"===this.token.token_type?"}":")",this.advance();let t=this.statement_list();if(this.token.token_type!==e)throw new ParseError("Expecting "+e,this.lexer.location);this.advance(),"list"===t[0]?a=["angle",...t.slice(1)]:"*"===t[0]&&(a=["angle",t])}else{let e=[],n=this.nonMinusFactor({parse_absolute_value:t});for(;!1!==n;)e.push(n),n=this.nonMinusFactor({parse_absolute_value:t});a=0===e.length?"angle":["angle",...e]}else if("INT"===this.token.token_type){this.advance();let e="int";"_"===this.token.token_type&&(this.advance(),e=["_",e,this.get_subsuperscript({parse_absolute_value:t})]),"^"===this.token.token_type&&(this.advance(),e=["^",e,this.get_subsuperscript({parse_absolute_value:t})]);let n=flatten(this.term({parse_absolute_value:t}));if(Array.isArray(n)&&"*"===n[0]){let e=[];for(let t=0;tn)return!1;if(s===n){if("}"!==this.token.token_type)return!1;this.advance();let s="derivative_leibniz";"∂"===t&&(s="partial_"+s),e=[s],1===n?e.push(r):e.push(["tuple",r,n]);let o=[];for(let e=0;e,larger":function(e){return[">",e[0],e[1]]},"<=,smallerEq":function(e){return["le",e[0],e[1]]},">=,largerEq":function(e){return["ge",e[0],e[1]]},"!=,unequal":function(e){return["ne",e[0],e[1]]},"!,factorial":function(e){return["apply","factorial",e[0]]}};class mathjsToAst{convert(e){if(e.isConstantNode)return e.value;if(e.isSymbolNode)return e.name;if(e.isOperatorNode){var t=[e.op,e.fn].join(",");if(t in operators)return operators[t](e.args.map(function(e,t){return this.convert(e)}.bind(this)));throw Error("Unsupported operator: "+e.op+", "+e.fn)}if(e.isFunctionNode){var n=e.args.map(function(e,t){return this.convert(e)}.bind(this));n=n.length>1?["tuple"].concat(n):n[0];var r=["apply",e.name];return r.push(n),r}if(e.isArrayNode)return["vector"].concat(e.args.map(function(e,t){return this.convert(e)}.bind(this)));if(e.isParenthesisNode)return this.convert(e.content);throw Error("Unsupported node type: "+e.type)}}class mathjsToGuppy{constructor(){this.mathjsToAst=new mathjsToAst,this.astToGuppy=new astToGuppy$1}convert(e){return this.astToGuppy.convert(this.mathjsToAst.convert(e))}}class mathjsToLatex{constructor(){this.mathjsToAst=new mathjsToAst,this.astToLatex=new astToLatex$1}convert(e){return this.astToLatex.convert(this.mathjsToAst.convert(e))}}class mathjsToText{constructor(){this.mathjsToAst=new mathjsToAst,this.astToText=new astToText$2}convert(e){return this.astToText.convert(this.mathjsToAst.convert(e))}}function defaultSetTimout(){throw new Error("setTimeout has not been defined")}function defaultClearTimeout(){throw new Error("clearTimeout has not been defined")}var cachedSetTimeout=defaultSetTimout,cachedClearTimeout=defaultClearTimeout;function runTimeout(e){if(cachedSetTimeout===setTimeout)return setTimeout(e,0);if((cachedSetTimeout===defaultSetTimout||!cachedSetTimeout)&&setTimeout)return cachedSetTimeout=setTimeout,setTimeout(e,0);try{return cachedSetTimeout(e,0)}catch(t){try{return cachedSetTimeout.call(null,e,0)}catch(t){return cachedSetTimeout.call(this,e,0)}}}function runClearTimeout(e){if(cachedClearTimeout===clearTimeout)return clearTimeout(e);if((cachedClearTimeout===defaultClearTimeout||!cachedClearTimeout)&&clearTimeout)return cachedClearTimeout=clearTimeout,clearTimeout(e);try{return cachedClearTimeout(e)}catch(t){try{return cachedClearTimeout.call(null,e)}catch(t){return cachedClearTimeout.call(this,e)}}}"function"==typeof global$1.setTimeout&&(cachedSetTimeout=setTimeout),"function"==typeof global$1.clearTimeout&&(cachedClearTimeout=clearTimeout);var queue=[],draining=!1,currentQueue,queueIndex=-1;function cleanUpNextTick(){draining&¤tQueue&&(draining=!1,currentQueue.length?queue=currentQueue.concat(queue):queueIndex=-1,queue.length&&drainQueue())}function drainQueue(){if(!draining){var e=runTimeout(cleanUpNextTick);draining=!0;for(var t=queue.length;t;){for(currentQueue=queue,queue=[];++queueIndex1)for(var n=1;n0)return parse$1(e);if("number"===n&&!1===isNaN(e))return t.long?fmtLong(e):fmtShort(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))};function parse$1(e){if(!((e=String(e)).length>100)){var t=/^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(e);if(t){var n=parseFloat(t[1]);switch((t[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return n*y;case"days":case"day":case"d":return n*d;case"hours":case"hour":case"hrs":case"hr":case"h":return n*h;case"minutes":case"minute":case"mins":case"min":case"m":return n*m;case"seconds":case"second":case"secs":case"sec":case"s":return n*s;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return n;default:return}}}}function fmtShort(e){return e>=d?Math.round(e/d)+"d":e>=h?Math.round(e/h)+"h":e>=m?Math.round(e/m)+"m":e>=s?Math.round(e/s)+"s":e+"ms"}function fmtLong(e){return plural(e,d,"day")||plural(e,h,"hour")||plural(e,m,"minute")||plural(e,s,"second")||e+" ms"}function plural(e,t,n){if(!(e=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/))},t.storage="undefined"!=typeof chrome&&void 0!==chrome.storage?chrome.storage.local:function(){try{return window.localStorage}catch(e){}}(),t.colors=["lightseagreen","forestgreen","goldenrod","dodgerblue","darkorchid","crimson"],t.formatters.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}},t.enable(n())}(browser,browser.exports);var debug=browser.exports("xml-parser"),xmlParser=parse;function parse(e){return e=(e=e.trim()).replace(//g,""),{declaration:function(){if(n(/^<\?xml\s*/)){for(var e={attributes:{}};!r()&&!a("?>");){var i=t();if(!i)return e;e.attributes[i.name]=i.value}return n(/\?>\s*/),e}}(),root:function i(){debug("tag %j",e);var s=n(/^<([\w-:.]+)\s*/);if(s){for(var o,l={name:s[1],attributes:{},children:[]};!(r()||a(">")||a("?>")||a("/>"));){var u=t();if(!u)return l;l.attributes[u.name]=u.value}if(n(/^\s*\/>\s*/))return l;for(n(/\??>\s*/),l.content=function(){debug("content %j",e);var t=n(/^([^<]*)/);return t?t[1]:""}();o=i();)l.children.push(o);return n(/^<\/[\w-:.]+>\s*/),l}}()};function t(){debug("attribute %j",e);var t,r=n(/([\w:-]+)\s*=\s*("[^"]*"|'[^']*'|\w+)\s*/);if(r)return{name:r[1],value:(t=r[2],t.replace(/^['"]|['"]$/g,""))}}function n(t){var n=e.match(t);if(n)return e=e.slice(n[0].length),n}function r(){return 0==e.length}function a(t){return 0==e.indexOf(t)}}const entities={"Α":"\\Alpha","Α":"\\Alpha","Α":"\\Alpha","\\u0391;":"\\Alpha","Β":"\\Beta","Β":"\\Beta","Β":"\\Beta","\\u0392;":"\\Beta","Γ":"\\Gamma","Γ":"\\Gamma","Γ":"\\Gamma","\\u0393;":"\\Gamma","Δ":"\\Delta","Δ":"\\Delta","Δ":"\\Delta","\\u0394;":"\\Delta","Ε":"\\Epsilon","Ε":"\\Epsilon","Ε":"\\Epsilon","\\u0395;":"\\Epsilon","Ζ":"\\Zeta","Ζ":"\\Zeta","Ζ":"\\Zeta","\\u0396;":"\\Zeta","Η":"\\Eta","Η":"\\Eta","Η":"\\Eta","\\u0397;":"\\Eta","Θ":"\\Theta","Θ":"\\Theta","Θ":"\\Theta","\\u0398;":"\\Theta","Ι":"\\Iota","Ι":"\\Iota","Ι":"\\Iota","\\u0399;":"\\Iota","Κ":"\\Kappa","Κ":"\\Kappa","Κ":"\\Kappa","\\u039A;":"\\Kappa","Λ":"\\Lambda","Λ":"\\Lambda","Λ":"\\Lambda","\\u039B;":"\\Lambda","Μ":"\\Mu","Μ":"\\Mu","Μ":"\\Mu","\\u039C;":"\\Mu","Ν":"\\Nu","Ν":"\\Nu","Ν":"\\Nu","\\u039D;":"\\Nu","Ξ":"\\Xi","Ξ":"\\Xi","Ξ":"\\Xi","\\u039E;":"\\Xi","Ο":"\\Omicron","Ο":"\\Omicron","Ο":"\\Omicron","\\u039F;":"\\Omicron","Π":"\\Pi","Π":"\\Pi","Π":"\\Pi","\\u03A0;":"\\Pi","Ρ":"\\Rho","Ρ":"\\Rho","Ρ":"\\Rho","\\u03A1;":"\\Rho","Σ":"\\Sigma","Σ":"\\Sigma","Σ":"\\Sigma","\\u03A3;":"\\Sigma","Τ":"\\Tau","Τ":"\\Tau","Τ":"\\Tau","\\u03A4;":"\\Tau","Υ":"\\Upsilon","Υ":"\\Upsilon","Υ":"\\Upsilon","\\u03A5;":"\\Upsilon","Φ":"\\Phi","Φ":"\\Phi","Φ":"\\Phi","\\u03A6;":"\\Phi","Χ":"\\Chi","Χ":"\\Chi","Χ":"\\Chi","\\u03A7;":"\\Chi","Ψ":"\\Psi","Ψ":"\\Psi","Ψ":"\\Psi","\\u03A8;":"\\Psi","Ω":"\\Omega","Ω":"\\Omega","Ω":"\\Omega","\\u03A9;":"\\Omega","α":"\\alpha","α":"\\alpha","α":"\\alpha","\\u03B1;":"\\alpha","β":"\\beta","β":"\\beta","β":"\\beta","\\u03B2;":"\\beta","γ":"\\gamma","γ":"\\gamma","γ":"\\gamma","\\u03B3;":"\\gamma","δ":"\\delta","δ":"\\delta","δ":"\\delta","\\u03B4;":"\\delta","ε":"\\epsilon","ε":"\\epsilon","ε":"\\epsilon","\\u03B5;":"\\epsilon","ζ":"\\zeta","ζ":"\\zeta","ζ":"\\zeta","\\u03B6;":"\\zeta","η":"\\eta","η":"\\eta","η":"\\eta","\\u03B7;":"\\eta","θ":"\\theta","θ":"\\theta","θ":"\\theta","\\u03B8;":"\\theta","ι":"\\iota","ι":"\\iota","ι":"\\iota","\\u03B9;":"\\iota","κ":"\\kappa","κ":"\\kappa","κ":"\\kappa","\\u03BA;":"\\kappa","λ":"\\lambda","λ":"\\lambda","λ":"\\lambda","\\u03BB;":"\\lambda","μ":"\\mu","μ":"\\mu","μ":"\\mu","\\u03BC;":"\\mu","ν":"\\nu","ν":"\\nu","ν":"\\nu","\\u03BD;":"\\nu","ξ":"\\xi","ξ":"\\xi","ξ":"\\xi","\\u03BE;":"\\xi","ο":"\\omicron","ο":"\\omicron","ο":"\\omicron","\\u03BF;":"\\omicron","π":"\\pi","π":"\\pi","π":"\\pi","\\u03C0;":"\\pi","ρ":"\\rho","ρ":"\\rho","ρ":"\\rho","\\u03C1;":"\\rho","ς":"\\sigma",";":"\\sigma","ς":"\\sigma","\\u03C2;":"\\sigma","σ":"\\sigma","σ":"\\sigma","σ":"\\sigma","\\u03C3;":"\\sigma","τ":"\\tau","τ":"\\tau","τ":"\\tau","\\u03C4;":"\\tau","υ":"\\upsilon","υ":"\\upsilon","υ":"\\upsilon","\\u03C5;":"\\upsilon","φ":"\\phi","φ":"\\phi","φ":"\\phi","\\u03C6;":"\\phi","χ":"\\chi","χ":"\\chi","χ":"\\chi","\\u03C7;":"\\chi","ψ":"\\psi","ψ":"\\psi","ψ":"\\psi","\\u03C8;":"\\psi","ω":"\\omega","ω":"\\omega","ω":"\\omega","\\u03C9;":"\\omega","−":"-","−":"-","∞":"\\infty","∞":"\\infty","∞":"\\infty","⋅":"\\cdot","⋅":"\\cdot","⋅":"\\cdot","×":"\\times","×":"\\times","×":"\\times"};class mmlToLatex{parse(e){return"mi"===e.name?entities[e.content]?entities[e.content]:e.content.length>1?"\\"+e.content:e.content:"mn"===e.name?e.content:"msup"===e.name?this.parse(e.children[0])+"^{"+this.parse(e.children[1])+"}":"mroot"===e.name?"\\sqrt["+this.parse(e.children[1])+"]{"+this.parse(e.children[1])+"}":"mfrac"===e.name?"\\frac{"+this.parse(e.children[0])+"}{"+this.parse(e.children[1])+"}":"msqrt"===e.name?"\\sqrt{"+e.children.map(function(e,t){return this.parse(e)}.bind(this)).join(" ")+"}":"mo"===e.name?entities[e.content]?entities[e.content]:"⁡"===e.content?" ":e.content:"mrow"===e.name&&"MJX-TeXAtom-ORD"===e.attributes.class?e.children.map(function(e,t){return this.parse(e)}.bind(this)).join(" "):"math"===e.name||"mrow"===e.name?"("+e.children.map(function(e,t){return this.parse(e)}.bind(this)).join(" ")+")":void 0}convert(e){return this.parse(xmlParser(e).root)}}class mmlToAst$1{constructor(){this.mmlToLatex=new mmlToLatex,this.latexToAst=new latexToAst$1}convert(e){return this.latexToAst.convert(this.mmlToLatex.convert(e))}}class mmlToGuppy{constructor(){this.mmlToLatex=new mmlToLatex,this.latexToAst=new latexToAst$1,this.astToGuppy=new astToGuppy$1}convert(e){return this.astToGuppy.convert(this.latexToAst.convert(this.mmlToLatex.convert(e)))}}class mmlToMathjs{constructor(){this.mmlToLatex=new mmlToLatex,this.latexToAst=new latexToAst$1,this.astToMathjs=new astToMathjs$1}convert(e){return this.astToMathjs.convert(this.latexToAst.convert(this.mmlToLatex.convert(e)))}}class mmlToText{constructor(){this.mmlToLatex=new mmlToLatex,this.latexToAst=new latexToAst$1,this.astToText=new astToText$2}convert(e){return this.astToText.convert(this.latexToAst.convert(this.mmlToLatex.convert(e)))}}class textToGuppy{constructor(){this.textToAst=new textToAst$4,this.astToGuppy=new astToGuppy$1}convert(e){return this.astToGuppy.convert(this.textToAst.convert(e))}}class textToLatex{constructor(){this.textToAst=new textToAst$4,this.astToLatex=new astToLatex$1}convert(e){return this.astToLatex.convert(this.textToAst.convert(e))}}class textToMathjs{constructor(){this.textToAst=new textToAst$4,this.astToMathjs=new astToMathjs$1}convert(e){return this.astToMathjs.convert(this.textToAst.convert(e))}}var converters=Object.freeze({__proto__:null,astToLatexObj:astToLatex$1,astToTextObj:astToText$2,astToGuppyObj:astToGuppy$1,astToMathjsObj:astToMathjs$1,latexToAstObj:latexToAst$1,latexToGuppyObj:latexToGuppy,latexToMathjsObj:latexToMathjs,latexToTextObj:latexToText,mathjsToAstObj:mathjsToAst,mathjsToGuppyObj:mathjsToGuppy,mathjsToLatexObj:mathjsToLatex,mathjsToTextObj:mathjsToText,mmlToAstObj:mmlToAst$1,mmlToGuppyObj:mmlToGuppy,mmlToLatexObj:mmlToLatex,mmlToMathjsObj:mmlToMathjs,mmlToTextObj:mmlToText,textToAstObj:textToAst$4,textToGuppyObj:textToGuppy,textToLatexObj:textToLatex,textToMathjsObj:textToMathjs,astToGLSL:astToGLSL$1}),textToAst=new textToAst$4,latexToAst=new latexToAst$1,mmlToAst=new mmlToAst$1,utils={match:match$2,flatten:flatten$5,unflattenLeft:unflattenLeft,unflattenRight:unflattenRight};function Expression(e,t){this.tree=flatten$5(e),this.context=t,this.toJSON=function(){let e={objectType:"math-expression",tree:this.tree},t={};for(let e in this.context.assumptions)Object.keys(this.context.assumptions[e]).length>0&&(t[e]=this.context.assumptions[e]);return Object.keys(t).length>0&&(e.assumptions=t),e}}function extend(e,t){return flatten_array(Array.prototype.slice.call(arguments,2)).forEach((function(n){if(n)for(var r in n)t?function(){var t=r;e[t]=function(){return this.fromAst(n[t].apply(null,arguments))}}():e[r]=n[r]})),e}function extend_prototype(e,t){return flatten_array(Array.prototype.slice.call(arguments,2)).forEach((function(n){if(n)for(var r in n)!function(){var a=r;e[a]=function(){var e=[this].concat(Array.prototype.slice.call(arguments));return t?this.context.fromAst(n[a].apply(null,e)):n[a].apply(null,e)}}()})),e}function create_from_multiple(e,t){if(Array.isArray(e)||"number"==typeof e)return new Expression(e,Context);if("string"==typeof e)try{return new Expression(textToAst.convert(e),Context)}catch(t){try{return new Expression(latexToAst.convert(e),Context)}catch(n){try{return new Expression(mmlToAst.convert(e),Context)}catch(r){if(-1!==e.indexOf("\\"))throw n;if(-1!==e.indexOf(">>2]>>>24-i%4*8&255;t[r+i>>>2]|=s<<24-(r+i)%4*8}else for(i=0;i>>2]=n[i>>>2];return this.sigBytes+=a,this},clamp:function(){var t=this.words,n=this.sigBytes;t[n>>>2]&=4294967295<<32-n%4*8,t.length=e.ceil(n/4)},clone:function(){var e=i.clone.call(this);return e.words=this.words.slice(0),e},random:function(t){for(var n,r=[],a=function(t){var n=987654321,r=4294967295;return function(){var a=((n=36969*(65535&n)+(n>>16)&r)<<16)+(t=18e3*(65535&t)+(t>>16)&r)&r;return a/=4294967296,(a+=.5)*(e.random()>.5?1:-1)}},i=0;i>>2]>>>24-a%4*8&255;r.push((i>>>4).toString(16)),r.push((15&i).toString(16))}return r.join("")},parse:function(e){for(var t=e.length,n=[],r=0;r>>3]|=parseInt(e.substr(r,2),16)<<24-r%8*4;return new s.init(n,t/2)}},u=o.Latin1={stringify:function(e){for(var t=e.words,n=e.sigBytes,r=[],a=0;a>>2]>>>24-a%4*8&255;r.push(String.fromCharCode(i))}return r.join("")},parse:function(e){for(var t=e.length,n=[],r=0;r>>2]|=(255&e.charCodeAt(r))<<24-r%4*8;return new s.init(n,t)}},c=o.Utf8={stringify:function(e){try{return decodeURIComponent(escape(u.stringify(e)))}catch(e){throw new Error("Malformed UTF-8 data")}},parse:function(e){return u.parse(unescape(encodeURIComponent(e)))}},p=a.BufferedBlockAlgorithm=i.extend({reset:function(){this._data=new s.init,this._nDataBytes=0},_append:function(e){"string"==typeof e&&(e=c.parse(e)),this._data.concat(e),this._nDataBytes+=e.sigBytes},_process:function(t){var n=this._data,r=n.words,a=n.sigBytes,i=this.blockSize,o=a/(4*i),l=(o=t?e.ceil(o):e.max((0|o)-this._minBufferSize,0))*i,u=e.min(4*l,a);if(l){for(var c=0;c>>31}var p=(r<<5|r>>>27)+l+i[u];p+=u<20?1518500249+(a&s|~a&o):u<40?1859775393+(a^s^o):u<60?(a&s|a&o|s&o)-1894007588:(a^s^o)-899497514,l=o,o=s,s=a<<30|a>>>2,a=r,r=p}n[0]=n[0]+r|0,n[1]=n[1]+a|0,n[2]=n[2]+s|0,n[3]=n[3]+o|0,n[4]=n[4]+l|0},_doFinalize:function(){var e=this._data,t=e.words,n=8*this._nDataBytes,r=8*e.sigBytes;return t[r>>>5]|=128<<24-r%32,t[14+(r+64>>>9<<4)]=Math.floor(n/4294967296),t[15+(r+64>>>9<<4)]=n,e.sigBytes=4*t.length,this._process(),this._hash},clone:function(){var e=r.clone.call(this);return e._hash=this._hash.clone(),e}});e.SHA1=r._createHelper(s),e.HmacSHA1=r._createHmacHelper(s)}(),CryptoJS.SHA1);var sha1=sha1$1.exports,encBase64={exports:{}};!function(e,t){e.exports=function(e){return function(){var t=e,n=t.lib.WordArray;function r(e,t,r){for(var a=[],i=0,s=0;s>>6-s%4*2;a[i>>>2]|=(o|l)<<24-i%4*8,i++}return n.create(a,i)}t.enc.Base64={stringify:function(e){var t=e.words,n=e.sigBytes,r=this._map;e.clamp();for(var a=[],i=0;i>>2]>>>24-i%4*8&255)<<16|(t[i+1>>>2]>>>24-(i+1)%4*8&255)<<8|t[i+2>>>2]>>>24-(i+2)%4*8&255,o=0;o<4&&i+.75*o>>6*(3-o)&63));var l=r.charAt(64);if(l)for(;a.length%4;)a.push(l);return a.join("")},parse:function(e){var t=e.length,n=this._map,a=this._reverseMap;if(!a){a=this._reverseMap=[];for(var i=0;iArray.isArray(t)?e.concat(flattenDeep(t)):e.concat(t)),[])}function flattenLevels(e,t){return console.log(`levels: ${t}`),e.reduce(((e,n)=>Array.isArray(n)&&t>1?e.concat(flattenLevels(n,t-1)):e.concat(n)),[])}class Subset{union(e){return this.complement().intersect(e.complement()).complement()}intersectWithOpenInterval(e){return this.intersect(e)}setMinus(e){return this.intersect(e.complement())}symmetricDifference(e){return this.setMinus(e).union(e.setMinus(this))}equals(e){return this.symmetricDifference(e).isEmpty()}toJSON(){return{objectType:"subset",data:Object.assign({},this),subsetType:this.constructor.subsetType}}static reviver(e,t){if(t&&"subset"===t.objectType&&void 0!==t.subsetType){if("emptySet"===t.subsetType)return new EmptySet;if("realLine"===t.subsetType)return new RealLine;if("singleton"===t.subsetType)return new Singleton(t.data.element);if("union"===t.subsetType)return new Union(t.data.subsets);if("openInterval"===t.subsetType)return new OpenInterval(t.data.left,t.data.right)}return t}copy(){return this.constructor.reviver(null,this.toJSON())}}class EmptySet extends Subset{static subsetType="emptySet";union(e){return e}intersect(){return new EmptySet}contains(){return!1}isEmpty(){return!0}complement(){return new RealLine}toString(){return"∅"}toMathExpression(){return me$3.fromAst("∅")}}class RealLine extends Subset{static subsetType="realLine";union(){return new RealLine}intersect(e){return e}contains(){return!0}complement(){return new EmptySet}isEmpty(){return!1}toString(){return"ℝ"}toMathExpression(){return me$3.fromAst("R")}}class Singleton extends Subset{static subsetType="singleton";constructor(e){if(super(),!Number.isFinite(e))return new EmptySet;this.element=e}union(e){return e.contains(this.element)?e:new Union([e,this])}intersect(e){return e.contains(this.element)?new Singleton(this.element):new EmptySet}isEmpty(){return!1}contains(e){return e===this.element}complement(){return new Union([new OpenInterval(-1/0,this.element),new OpenInterval(this.element,1/0)])}toString(){return`{${this.element}}`}toMathExpression(){return me$3.fromAst(["set",this.element])}}class Union extends Subset{static subsetType="union";intersect(e){return new Union(this.subsets.map((t=>e.intersect(t))))}toString(){return this.subsets.map((e=>e.toString())).join(" U ")}toMathExpression(){return me$3.fromAst(["union",...this.subsets.map((e=>e.toMathExpression().tree))])}constructor(e){super();let t=e.filter((e=>!e.isEmpty()));if(0===t.length)return new EmptySet;t=t.reduce(((e,t)=>t instanceof Union?e.concat(t.subsets):e.concat(t)),[]),this.subsets=[];for(let e=0;ea&&s.elementi.left&&at.contains(e)))}isEmpty(){return this.subsets.every((e=>e.isEmpty()))}complement(){return this.subsets.map((e=>e.complement())).reduce(((e,t)=>e.intersect(t)))}}class Interval$1 extends Subset{constructor(e,t){return super(),this.left=e,this.right=t,this.left<=this.right?this.left===-1/0&&this.right===1/0?new RealLine:this:new EmptySet}}class OpenInterval extends Interval$1{static subsetType="openInterval";constructor(e,t){return super(e,t),e===t?new EmptySet:this}intersect(e){return e.intersectWithOpenInterval(this)}intersectWithOpenInterval(e){return new OpenInterval(Math.max(this.left,e.left),Math.min(this.right,e.right))}complement(){return new Union([new OpenClosedInterval(-1/0,this.left),new ClosedOpenInterval(this.right,1/0)])}isEmpty(){return this.left>=this.right}contains(e){return e>this.left&&ebuildSubsetFromIntervals(e,t))).filter((e=>e));return 0===n.length?new EmptySet:1===n.length?n[0]:new Union(n)}if("intersect"===n||"and"===n){let n=e.slice(1).map((e=>buildSubsetFromIntervals(e,t))).filter((e=>e));return 0===n.length?new RealLine:n.reduce(((e,t)=>e.intersect(t)))}if("set"===n){let n=e.slice(1).map((e=>buildSubsetFromIntervals(e,t))).filter((e=>e));return 0===n.length?new EmptySet:1===n.length?n[0]:new Union(n)}if(["<","le",">","ge","=","ne"].includes(n)){let r=e[1],a=!1;if(!Number.isFinite(r))if(deepCompare(r,t))a=!0;else if(r=me$3.fromAst(r).evaluate_to_constant(),!Number.isFinite(r)&&r!==1/0&&r!==-1/0)return new EmptySet;let i=e[2],s=!1;if(!Number.isFinite(i))if(deepCompare(i,t))s=!0;else if(i=me$3.fromAst(i).evaluate_to_constant(),!Number.isFinite(i)&&i!==1/0&&i!==-1/0)return new EmptySet;return a?s?new EmptySet:"<"===n?new OpenInterval(-1/0,i):"le"===n?new OpenClosedInterval(-1/0,i):">"===n?new OpenInterval(i,1/0):"ge"===n?new ClosedOpenInterval(i,1/0):"="===n?Number.isFinite(i)?new Singleton(i):new EmptySet:Number.isFinite(i)?new Union([new OpenInterval(-1/0,i),new OpenInterval(i,1/0)]):new RealLine:s?"<"===n?new OpenInterval(r,1/0):"le"===n?new ClosedOpenInterval(r,1/0):">"===n?new OpenInterval(-1/0,r):"ge"===n?new OpenClosedInterval(-1/0,r):"="===n?Number.isFinite(r)?new Singleton(r):new EmptySet:Number.isFinite(r)?new Union([new OpenInterval(-1/0,r),new OpenInterval(r,1/0)]):new RealLine:new EmptySet}if(["lts","gts"].includes(n)){let r=e[1].slice(1),a=e[2].slice(1);if(3!==r.length||!deepCompare(r[1],t))return new EmptySet;"gts"===n&&(r.reverse(),a.reverse());let i=r[0];if(!Number.isFinite(i)&&(i=me$3.fromAst(i).evaluate_to_constant(),!Number.isFinite(i)&&i!==1/0&&i!==-1/0))return new EmptySet;let s=r[2];return Number.isFinite(s)||(s=me$3.fromAst(s).evaluate_to_constant(),Number.isFinite(s)||s===1/0||s===-1/0)?a[0]?a[1]?new OpenInterval(i,s):new OpenClosedInterval(i,s):a[1]?new ClosedOpenInterval(i,s):new ClosedInterval(i,s):new EmptySet}if("|"===n){let t=e[1];return buildSubsetFromIntervals(e[2],t)}if("^"!==n||"C"!==e[2]&&"c"!==e[2]){if("in"===n)return deepCompare(e[1],t)?buildSubsetFromIntervals(e[2],t):new EmptySet;if("ni"===n)return deepCompare(e[2],t)?buildSubsetFromIntervals(e[1],t):new EmptySet;if("notin"===n){if(deepCompare(e[1],t)){let n=buildSubsetFromIntervals(e[2],t);if(n)return n.complement()}return new EmptySet}if("notni"===n){if(deepCompare(e[2],t)){let n=buildSubsetFromIntervals(e[1],t);if(n)return n.complement()}return new EmptySet}{let t=me$3.fromAst(e).evaluate_to_constant();return Number.isFinite(t)?new Singleton(t):new EmptySet}}{let n=buildSubsetFromIntervals(e[1],t);return n?n.complement():new EmptySet}}function buildSubsetFromMathExpression(e,t){return buildSubsetFromIntervals(e.to_intervals().tree,t.tree)}function deepClone(e,t,n){if(Object(e)!==e||e instanceof Function)return e;if(void 0!==t&&e instanceof t)return e;if(e instanceof me$3.class||e instanceof theModule.Subset)return e.copy();if(void 0===n&&(n=new WeakMap),Array.isArray(e))return[...e.map((e=>deepClone(e,t,n)))];if(e.constructor===Object&&0===Object.entries(e).length)return{};if(n.has(e))return n.get(e);try{var r=new e.constructor}catch(t){r=Object.create(Object.getPrototypeOf(e))}return e instanceof Map?Array.from(e,(([e,a])=>r.set(deepClone(e,t,n),deepClone(a,t,n)))):e instanceof Set&&Array.from(e,(e=>r.add(deepClone(e,t,n)))),n.set(e,r),Object.assign(r,...Object.keys(e).map((r=>({[r]:deepClone(e[r],t,n)}))))}function deepCompare(e,t,n){var r,a;return r=[],a=[],function e(t,i){var s;if(Number.isNaN(t)&&Number.isNaN(i))return!0;if(t===i)return!0;if(void 0!==n&&t instanceof n&&i instanceof n)return t.componentName===i.componentName;if(t instanceof me$3.class&&i instanceof me$3.class)return e(t.tree,i.tree);if("function"==typeof t&&"function"==typeof i||t instanceof Date&&i instanceof Date||t instanceof RegExp&&i instanceof RegExp||t instanceof String&&i instanceof String||t instanceof Number&&i instanceof Number)return t.toString()===i.toString();if(!(t instanceof Object&&i instanceof Object))return!1;if(t.isPrototypeOf(i)||i.isPrototypeOf(t))return!1;if(t.constructor!==i.constructor)return!1;if(t.prototype!==i.prototype)return!1;if(r.indexOf(t)>-1||a.indexOf(i)>-1)return!1;for(s in i){if(i.hasOwnProperty(s)!==t.hasOwnProperty(s))return!1;if(typeof i[s]!=typeof t[s])return!1}for(s in t){if(i.hasOwnProperty(s)!==t.hasOwnProperty(s))return!1;if(typeof i[s]!=typeof t[s])return!1;switch(typeof t[s]){case"object":case"function":if(r.push(t),a.push(i),!e(t[s],i[s]))return!1;r.pop(),a.pop();break;default:if(!(t[s]===i[s]||Number.isNaN(t[s])&&Number.isNaN(i[s])))return!1}}return!0}(e,t)}function breakStringsAndOthersIntoComponentsByStringCommas(e){return null}function returnBreakStringsSugarFunction({childrenToComponentFunction:e,mustStripOffOuterParentheses:t=!1}){return function({matchedChildren:n}){let r=0,a=[],i=[],s=!1,o=n.length;if(t){let e=n[0];if("string"!=typeof e||"("!==e.trimLeft()[0])return{success:!1}}for(let[e,l]of n.entries()){if("string"!=typeof l){i.push(l);continue}let u=l.trim();if(0===e&&t&&"("===u[0]){let e=n[o-1];if("string"==typeof e){let t=e.trimRight();")"===t[t.length-1]&&(s=!0,u=u.substring(1))}}let c=0;for(let t=0;tc&&i.push(u.substring(c,t)),a.push(i),i=[],c=t+1)}u.length>c&&i.push(u.substring(c,u.length))}return 0!==r?{success:!1}:(a.push(i),{success:!0,newChildren:a.map(e)})}}function breakEmbeddedStringByCommas({childrenList:e}){let t=0,n=[],r=[];for(let a of e){if("string"!=typeof a){r.push(a);continue}let e=a.trim(),i=0;for(let a=0;ai){let t=e.substring(i,a).trim();r.push(t)}n.push(r),r=[],i=a+1}}if(e.length>i){let t=e.substring(i,e.length).trim();r.push(t)}}return 0!==t?{success:!1}:(n.push(r),{success:!0,pieces:n})}function breakEmbeddedStringsIntoParensPieces({componentList:e,removeParens:t=!1}){let n=0,r=[],a=[];for(let i of e){if("string"!=typeof i){0===n?r.push([i]):a.push(i);continue}let e=i.trim(),s=0;for(let i=0;is){let n=t?i:i+1,r=e.substring(s,n).trim();r.length>0&&a.push(r)}r.push(a),a=[],s=i+1}n--}else if(0===n&&!o.match(/\s/))return{success:!1}}if(e.length>s){let t=e.substring(s,e.length).trim();a.push(t)}}return 0!==n?{success:!1}:(a.length>0&&r.push(a),{success:!0,pieces:r})}var global$1="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{};function defaultSetTimout(){throw new Error("setTimeout has not been defined")}function defaultClearTimeout(){throw new Error("clearTimeout has not been defined")}var cachedSetTimeout=defaultSetTimout,cachedClearTimeout=defaultClearTimeout;function runTimeout(e){if(cachedSetTimeout===setTimeout)return setTimeout(e,0);if((cachedSetTimeout===defaultSetTimout||!cachedSetTimeout)&&setTimeout)return cachedSetTimeout=setTimeout,setTimeout(e,0);try{return cachedSetTimeout(e,0)}catch(t){try{return cachedSetTimeout.call(null,e,0)}catch(t){return cachedSetTimeout.call(this,e,0)}}}function runClearTimeout(e){if(cachedClearTimeout===clearTimeout)return clearTimeout(e);if((cachedClearTimeout===defaultClearTimeout||!cachedClearTimeout)&&clearTimeout)return cachedClearTimeout=clearTimeout,clearTimeout(e);try{return cachedClearTimeout(e)}catch(t){try{return cachedClearTimeout.call(null,e)}catch(t){return cachedClearTimeout.call(this,e)}}}"function"==typeof global$1.setTimeout&&(cachedSetTimeout=setTimeout),"function"==typeof global$1.clearTimeout&&(cachedClearTimeout=clearTimeout);var queue=[],draining=!1,currentQueue,queueIndex=-1;function cleanUpNextTick(){draining&¤tQueue&&(draining=!1,currentQueue.length?queue=currentQueue.concat(queue):queueIndex=-1,queue.length&&drainQueue())}function drainQueue(){if(!draining){var e=runTimeout(cleanUpNextTick);draining=!0;for(var t=queue.length;t;){for(currentQueue=queue,queue=[];++queueIndex1)for(var n=1;n{throw new Error("This node type doesn't define a deserialize function")})}add(e){if(this.perNode)throw new RangeError("Can't add per-node props to node types");return"function"!=typeof e&&(e=NodeType.match(e)),t=>{let n=e(t);return void 0===n?null:[this,n]}}}NodeProp.closedBy=new NodeProp({deserialize:e=>e.split(" ")}),NodeProp.openedBy=new NodeProp({deserialize:e=>e.split(" ")}),NodeProp.group=new NodeProp({deserialize:e=>e.split(" ")}),NodeProp.contextHash=new NodeProp({perNode:!0}),NodeProp.lookAhead=new NodeProp({perNode:!0}),NodeProp.mounted=new NodeProp({perNode:!0});const noProps=Object.create(null);class NodeType{constructor(e,t,n,r=0){this.name=e,this.props=t,this.id=n,this.flags=r}static define(e){let t=e.props&&e.props.length?Object.create(null):noProps,n=(e.top?1:0)|(e.skipped?2:0)|(e.error?4:0)|(null==e.name?8:0),r=new NodeType(e.name||"",t,e.id,n);if(e.props)for(let n of e.props)if(Array.isArray(n)||(n=n(r)),n){if(n[0].perNode)throw new RangeError("Can't store a per-node prop on a node type");t[n[0].id]=n[1]}return r}prop(e){return this.props[e.id]}get isTop(){return(1&this.flags)>0}get isSkipped(){return(2&this.flags)>0}get isError(){return(4&this.flags)>0}get isAnonymous(){return(8&this.flags)>0}is(e){if("string"==typeof e){if(this.name==e)return!0;let t=this.prop(NodeProp.group);return!!t&&t.indexOf(e)>-1}return this.id==e}static match(e){let t=Object.create(null);for(let n in e)for(let r of n.split(" "))t[r]=e[n];return e=>{for(let n=e.prop(NodeProp.group),r=-1;r<(n?n.length:0);r++){let a=t[r<0?e.name:n[r]];if(a)return a}}}}NodeType.none=new NodeType("",Object.create(null),0,8);class NodeSet{constructor(e){this.types=e;for(let t=0;te.node;;){let s=!1;if(e.from<=a&&e.to>=r&&(e.type.isAnonymous||!1!==t(e.type,e.from,e.to,i))){if(e.firstChild())continue;e.type.isAnonymous||(s=!0)}for(;s&&n&&n(e.type,e.from,e.to,i),s=e.type.isAnonymous,!e.nextSibling();){if(!e.parent())return;s=!0}}}prop(e){return e.perNode?this.props?this.props[e.id]:void 0:this.type.prop(e)}get propValues(){let e=[];if(this.props)for(let t in this.props)e.push([+t,this.props[t]]);return e}balance(e={}){return this.children.length<=8?this:balanceRange(NodeType.none,this.children,this.positions,0,this.children.length,0,this.length,((e,t,n)=>new Tree(this.type,e,t,n,this.propValues)),e.makeTree||((e,t,n)=>new Tree(NodeType.none,e,t,n)))}static build(e){return buildTree(e)}}Tree.empty=new Tree(NodeType.none,[],[],0);class FlatBufferCursor{constructor(e,t){this.buffer=e,this.index=t}get id(){return this.buffer[this.index-4]}get start(){return this.buffer[this.index-3]}get end(){return this.buffer[this.index-2]}get size(){return this.buffer[this.index-1]}get pos(){return this.index}next(){this.index-=4}fork(){return new FlatBufferCursor(this.buffer,this.index)}}class TreeBuffer{constructor(e,t,n){this.buffer=e,this.length=t,this.set=n}get type(){return NodeType.none}toString(){let e=[];for(let t=0;t0));o=i[o+3]);return s}slice(e,t,n,r){let a=this.buffer,i=new Uint16Array(t-e);for(let r=e,s=0;r=t&&nt;case 1:return n<=t&&r>t;case 2:return r>t;case 4:return!0}}function enterUnfinishedNodesBefore(e,t){let n=e.childBefore(t);for(;n;){let t=n.lastChild;if(!t||t.to!=n.to)break;t.type.isError&&t.from==t.to?(e=n,n=t.prevSibling):n=t}return e}function resolveNode(e,t,n,r){for(var a;e.from==e.to||(n<1?e.from>=t:e.from>t)||(n>-1?e.to<=t:e.to0?s.length:-1;e!=l;e+=t){let l=s[e],u=o[e]+i._from;if(checkSide(r,n,u,u+l.length))if(l instanceof TreeBuffer){if(2&a)continue;let s=l.findChild(0,l.buffer.length,t,n-u,r);if(s>-1)return new BufferNode(new BufferContext(i,l,e,u),null,s)}else if(1&a||!l.type.isAnonymous||hasChild(l)){let s;if(!(1&a)&&l.props&&(s=l.prop(NodeProp.mounted))&&!s.overlay)return new TreeNode(s.tree,u,e,i);let o=new TreeNode(l,u,e,i);return 1&a||!o.type.isAnonymous?o:o.nextChild(t<0?l.children.length-1:0,t,n,r)}}if(1&a||!i.type.isAnonymous)return null;if(e=i.index>=0?i.index+t:t<0?-1:i._parent.node.children.length,i=i._parent,!i)return null}}get firstChild(){return this.nextChild(0,1,0,4)}get lastChild(){return this.nextChild(this.node.children.length-1,-1,0,4)}childAfter(e){return this.nextChild(0,1,e,2)}childBefore(e){return this.nextChild(this.node.children.length-1,-1,e,-2)}enter(e,t,n=!0,r=!0){let a;if(n&&(a=this.node.prop(NodeProp.mounted))&&a.overlay){let n=e-this.from;for(let{from:e,to:r}of a.overlay)if((t>0?e<=n:e=n:r>n))return new TreeNode(a.tree,a.overlay[0].from+this.from,-1,this)}return this.nextChild(0,1,e,t,r?0:2)}nextSignificantParent(){let e=this;for(;e.type.isAnonymous&&e._parent;)e=e._parent;return e}get parent(){return this._parent?this._parent.nextSignificantParent():null}get nextSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index+1,1,0,4):null}get prevSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index-1,-1,0,4):null}get cursor(){return new TreeCursor(this)}get tree(){return this.node}toTree(){return this.node}resolve(e,t=0){return resolveNode(this,e,t,!1)}resolveInner(e,t=0){return resolveNode(this,e,t,!0)}enterUnfinishedNodesBefore(e){return enterUnfinishedNodesBefore(this,e)}getChild(e,t=null,n=null){let r=getChildren(this,e,t,n);return r.length?r[0]:null}getChildren(e,t=null,n=null){return getChildren(this,e,t,n)}toString(){return this.node.toString()}}function getChildren(e,t,n,r){let a=e.cursor,i=[];if(!a.firstChild())return i;if(null!=n)for(;!a.type.is(n);)if(!a.nextSibling())return i;for(;;){if(null!=r&&a.type.is(r))return i;if(a.type.is(t)&&i.push(a.node),!a.nextSibling())return null==r?i:[]}}class BufferContext{constructor(e,t,n,r){this.parent=e,this.buffer=t,this.index=n,this.start=r}}class BufferNode{constructor(e,t,n){this.context=e,this._parent=t,this.index=n,this.type=e.buffer.set.types[e.buffer.buffer[n]]}get name(){return this.type.name}get from(){return this.context.start+this.context.buffer.buffer[this.index+1]}get to(){return this.context.start+this.context.buffer.buffer[this.index+2]}child(e,t,n){let{buffer:r}=this.context,a=r.findChild(this.index+4,r.buffer[this.index+3],e,t-this.context.start,n);return a<0?null:new BufferNode(this.context,this,a)}get firstChild(){return this.child(1,0,4)}get lastChild(){return this.child(-1,0,4)}childAfter(e){return this.child(1,e,2)}childBefore(e){return this.child(-1,e,-2)}enter(e,t,n,r=!0){if(!r)return null;let{buffer:a}=this.context,i=a.findChild(this.index+4,a.buffer[this.index+3],t>0?1:-1,e-this.context.start,t);return i<0?null:new BufferNode(this.context,this,i)}get parent(){return this._parent||this.context.parent.nextSignificantParent()}externalSibling(e){return this._parent?null:this.context.parent.nextChild(this.context.index+e,e,0,4)}get nextSibling(){let{buffer:e}=this.context,t=e.buffer[this.index+3];return t<(this._parent?e.buffer[this._parent.index+3]:e.buffer.length)?new BufferNode(this.context,this._parent,t):this.externalSibling(1)}get prevSibling(){let{buffer:e}=this.context,t=this._parent?this._parent.index+4:0;return this.index==t?this.externalSibling(-1):new BufferNode(this.context,this._parent,e.findChild(t,this.index,-1,0,4))}get cursor(){return new TreeCursor(this)}get tree(){return null}toTree(){let e=[],t=[],{buffer:n}=this.context,r=this.index+4,a=n.buffer[this.index+3];if(a>r){let i=n.buffer[this.index+1],s=n.buffer[this.index+2];e.push(n.slice(r,a,i,s)),t.push(0)}return new Tree(this.type,e,t,this.to-this.from)}resolve(e,t=0){return resolveNode(this,e,t,!1)}resolveInner(e,t=0){return resolveNode(this,e,t,!0)}enterUnfinishedNodesBefore(e){return enterUnfinishedNodesBefore(this,e)}toString(){return this.context.buffer.childString(this.index)}getChild(e,t=null,n=null){let r=getChildren(this,e,t,n);return r.length?r[0]:null}getChildren(e,t=null,n=null){return getChildren(this,e,t,n)}}class TreeCursor{constructor(e,t=0){if(this.mode=t,this.buffer=null,this.stack=[],this.index=0,this.bufferNode=null,e instanceof TreeNode)this.yieldNode(e);else{this._tree=e.context.parent,this.buffer=e.context;for(let t=e._parent;t;t=t._parent)this.stack.unshift(t.index);this.bufferNode=e,this.yieldBuf(e.index)}}get name(){return this.type.name}yieldNode(e){return!!e&&(this._tree=e,this.type=e.type,this.from=e.from,this.to=e.to,!0)}yieldBuf(e,t){this.index=e;let{start:n,buffer:r}=this.buffer;return this.type=t||r.set.types[r.buffer[e]],this.from=n+r.buffer[e+1],this.to=n+r.buffer[e+2],!0}yield(e){return!!e&&(e instanceof TreeNode?(this.buffer=null,this.yieldNode(e)):(this.buffer=e.context,this.yieldBuf(e.index,e.type)))}toString(){return this.buffer?this.buffer.buffer.childString(this.index):this._tree.toString()}enterChild(e,t,n){if(!this.buffer)return this.yield(this._tree.nextChild(e<0?this._tree.node.children.length-1:0,e,t,n,this.mode));let{buffer:r}=this.buffer,a=r.findChild(this.index+4,r.buffer[this.index+3],e,t-this.buffer.start,n);return!(a<0)&&(this.stack.push(this.index),this.yieldBuf(a))}firstChild(){return this.enterChild(1,0,4)}lastChild(){return this.enterChild(-1,0,4)}childAfter(e){return this.enterChild(1,e,2)}childBefore(e){return this.enterChild(-1,e,-2)}enter(e,t,n=!0,r=!0){return this.buffer?!!r&&this.enterChild(1,e,t):this.yield(this._tree.enter(e,t,n&&!(1&this.mode),r))}parent(){if(!this.buffer)return this.yieldNode(1&this.mode?this._tree._parent:this._tree.parent);if(this.stack.length)return this.yieldBuf(this.stack.pop());let e=1&this.mode?this.buffer.parent:this.buffer.parent.nextSignificantParent();return this.buffer=null,this.yieldNode(e)}sibling(e){if(!this.buffer)return!!this._tree._parent&&this.yield(this._tree.index<0?null:this._tree._parent.nextChild(this._tree.index+e,e,0,4,this.mode));let{buffer:t}=this.buffer,n=this.stack.length-1;if(e<0){let e=n<0?0:this.stack[n]+4;if(this.index!=e)return this.yieldBuf(t.findChild(e,this.index,-1,0,4))}else{let e=t.buffer[this.index+3];if(e<(n<0?t.buffer.length:t.buffer[this.stack[n]+3]))return this.yieldBuf(e)}return n<0&&this.yield(this.buffer.parent.nextChild(this.buffer.index+e,e,0,4,this.mode))}nextSibling(){return this.sibling(1)}prevSibling(){return this.sibling(-1)}atLastNode(e){let t,n,{buffer:r}=this;if(r){if(e>0){if(this.index-1)for(let r=t+e,a=e<0?-1:n.node.children.length;r!=a;r+=e){let e=n.node.children[r];if(1&this.mode||e instanceof TreeBuffer||!e.type.isAnonymous||hasChild(e))return!1}return!0}move(e,t){if(t&&this.enterChild(e,0,4))return!0;for(;;){if(this.sibling(e))return!0;if(this.atLastNode(e)||!this.parent())return!1}}next(e=!0){return this.move(1,e)}prev(e=!0){return this.move(-1,e)}moveTo(e,t=0){for(;(this.from==this.to||(t<1?this.from>=e:this.from>e)||(t>-1?this.to<=e:this.to=0;){for(let i=e;i;i=i._parent)if(i.index==r){if(r==this.index)return i;t=i,n=a+1;break e}r=this.stack[--a]}for(let e=n;ee instanceof TreeBuffer||!e.type.isAnonymous||hasChild(e)))}function buildTree(e){var t;let{buffer:n,nodeSet:r,maxBufferLength:a=DefaultBufferLength,reused:i=[],minRepeatType:s=r.types.length}=e,o=Array.isArray(n)?new FlatBufferCursor(n,n.length):n,l=r.types,u=0,c=0;function p(e,t,n,f,y){let{id:g,start:b,end:v,size:N}=o,T=c;for(;N<0;){if(o.next(),-1==N){let t=i[g];return n.push(t),void f.push(b-e)}if(-3==N)return void(u=g);if(-4==N)return void(c=g);throw new RangeError(`Unrecognized record size: ${N}`)}let C,A,V=l[g],x=b-e;if(v-b<=a&&(A=function(e,t){let n=o.fork(),r=0,i=0,l=0,u=n.end-a,c={size:0,start:0,skip:0};e:for(let a=n.pos-e;n.pos>a;){let e=n.size;if(n.id==t&&e>=0){c.size=r,c.start=i,c.skip=l,l+=4,r+=4,n.next();continue}let o=n.pos-e;if(e<0||o=s?4:0,d=n.start;for(n.next();n.pos>o;){if(n.size<0){if(-3!=n.size)break e;p+=4}else n.id>=s&&(p+=4);n.next()}i=d,r+=e,l+=p}(t<0||r==e)&&(c.size=r,c.start=i,c.skip=l);return c.size>4?c:void 0}(o.pos-t,y))){let t=new Uint16Array(A.size-A.skip),n=o.pos-A.size,a=t.length;for(;o.pos>n;)a=h(A.start,t,a);C=new TreeBuffer(t,v-A.start,r),x=A.start-e}else{let e=o.pos-N;o.next();let t=[],n=[],r=g>=s?g:-1,i=0,l=v;for(;o.pos>e;)r>=0&&o.id==r&&o.size>=0?(o.end<=l-a&&(d(t,n,b,i,o.end,l,r,T),i=t.length,l=o.end),o.next()):p(b,e,t,n,r);if(r>=0&&i>0&&i-1&&i>0){let e=function(e){return(t,n,r)=>{let a,i,s=0,o=t.length-1;if(o>=0&&(a=t[o])instanceof Tree){if(!o&&a.type==e&&a.length==r)return a;(i=a.prop(NodeProp.lookAhead))&&(s=n[o]+a.length+i)}return m(e,t,n,r,s)}}(V);C=balanceRange(V,t,n,0,t.length,0,v-b,e,e)}else C=m(V,t,n,v-b,T-v)}n.push(C),f.push(x)}function d(e,t,n,a,i,s,o,l){let u=[],c=[];for(;e.length>a;)u.push(e.pop()),c.push(t.pop()+n-i);e.push(m(r.types[o],u,c,s-i,l-s)),t.push(i-n)}function m(e,t,n,r,a=0,i){if(u){let e=[NodeProp.contextHash,u];i=i?[e].concat(i):[e]}if(a>25){let e=[NodeProp.lookAhead,a];i=i?[e].concat(i):[e]}return new Tree(e,t,n,r,i)}function h(e,t,n){let{id:r,start:a,end:i,size:l}=o;if(o.next(),l>=0&&r4){let r=o.pos-(l-4);for(;o.pos>r;)n=h(e,t,n)}t[--n]=s,t[--n]=i-e,t[--n]=a-e,t[--n]=r}else-3==l?u=r:-4==l&&(c=r);return n}let f=[],y=[];for(;o.pos>0;)p(e.start||0,e.bufferStart||0,f,y,-1);let g=null!==(t=e.length)&&void 0!==t?t:f.length?y[0]+f[0].length:0;return new Tree(l[e.topID],f.reverse(),y.reverse(),g)}const nodeSizeCache=new WeakMap;function nodeSize(e,t){if(!e.isAnonymous||t instanceof TreeBuffer||t.type!=e)return 1;let n=nodeSizeCache.get(t);if(null==n){n=1;for(let r of t.children){if(r.type!=e||!(r instanceof Tree)){n=1;break}n+=nodeSize(e,r)}nodeSizeCache.set(t,n)}return n}function balanceRange(e,t,n,r,a,i,s,o,l){let u=0;for(let n=r;n=c)break;h+=t}if(u==a+1){if(h>c){let e=n[a];t(e.children,e.positions,0,e.children.length,r[a]+o);continue}p.push(n[a])}else{let t=r[u-1]+n[u-1].length-m;p.push(balanceRange(e,n,r,a,u,m,t,null,l))}d.push(m+o-i)}}(t,n,r,a,0),(o||l)(p,d,s)}class Parser$1{startParse(e,t,n){return"string"==typeof e&&(e=new StringInput(e)),n=n?n.length?n.map((e=>new Range(e.from,e.to))):[new Range(0,0)]:[new Range(0,e.length)],this.createParse(e,t||[],n)}parse(e,t,n){let r=this.startParse(e,t,n);for(;;){let e=r.advance();if(e)return e}}}class StringInput{constructor(e){this.string=e}get length(){return this.string.length}chunk(e){return this.string.slice(e)}get lineChunks(){return!1}read(e,t){return this.string.slice(e,t)}}new NodeProp({perNode:!0});class Stack$1{constructor(e,t,n,r,a,i,s,o,l,u=0,c){this.p=e,this.stack=t,this.state=n,this.reducePos=r,this.pos=a,this.score=i,this.buffer=s,this.bufferBase=o,this.curContext=l,this.lookAhead=u,this.parent=c}toString(){return`[${this.stack.filter(((e,t)=>t%3==0)).concat(this.state)}]@${this.pos}${this.score?"!"+this.score:""}`}static start(e,t,n=0){let r=e.parser.context;return new Stack$1(e,[],t,n,n,0,[],0,r?new StackContext(r,r.start):null,0,null)}get context(){return this.curContext?this.curContext.context:null}pushState(e,t){this.stack.push(this.state,t,this.bufferBase+this.buffer.length),this.state=e}reduce(e){let t=e>>19,n=65535&e,{parser:r}=this.p,a=r.dynamicPrecedence(n);if(a&&(this.score+=a),0==t)return this.pushState(r.getGoto(this.state,n,!0),this.reducePos),ni;)this.stack.pop();this.reduceContext(n,s)}storeNode(e,t,n,r=4,a=!1){if(0==e){let e=this,r=this.buffer.length;if(0==r&&e.parent&&(r=e.bufferBase-e.parent.bufferBase,e=e.parent),r>0&&0==e.buffer[r-4]&&e.buffer[r-1]>-1){if(t==n)return;if(e.buffer[r-2]>=t)return void(e.buffer[r-2]=n)}}if(a&&this.pos!=n){let a=this.buffer.length;if(a>0&&0!=this.buffer[a-4])for(;a>0&&this.buffer[a-2]>n;)this.buffer[a]=this.buffer[a-4],this.buffer[a+1]=this.buffer[a-3],this.buffer[a+2]=this.buffer[a-2],this.buffer[a+3]=this.buffer[a-1],a-=4,r>4&&(r-=4);this.buffer[a]=e,this.buffer[a+1]=t,this.buffer[a+2]=n,this.buffer[a+3]=r}else this.buffer.push(e,t,n,r)}shift(e,t,n){let r=this.pos;if(131072&e)this.pushState(65535&e,this.pos);else if(0==(262144&e)){let a=e,{parser:i}=this.p;(n>this.pos||t<=i.maxNode)&&(this.pos=n,i.stateFlag(a,1)||(this.reducePos=n)),this.pushState(a,r),this.shiftContext(t,r),t<=i.maxNode&&this.buffer.push(t,r,n,4)}else this.pos=n,this.shiftContext(t,r),t<=this.p.parser.maxNode&&this.buffer.push(t,r,n,4)}apply(e,t,n){65536&e?this.reduce(e):this.shift(e,t,n)}useNode(e,t){let n=this.p.reused.length-1;(n<0||this.p.reused[n]!=e)&&(this.p.reused.push(e),n++);let r=this.pos;this.reducePos=this.pos=r+e.length,this.pushState(t,r),this.buffer.push(n,r,this.reducePos,-1),this.curContext&&this.updateContext(this.curContext.tracker.reuse(this.curContext.context,e,this,this.p.stream.reset(this.pos-e.length)))}split(){let e=this,t=e.buffer.length;for(;t>0&&e.buffer[t-2]>e.reducePos;)t-=4;let n=e.buffer.slice(t),r=e.bufferBase+t;for(;e&&r==e.bufferBase;)e=e.parent;return new Stack$1(this.p,this.stack.slice(),this.state,this.reducePos,this.pos,this.score,n,r,this.curContext,this.lookAhead,e)}recoverByDelete(e,t){let n=e<=this.p.parser.maxNode;n&&this.storeNode(e,this.pos,t,4),this.storeNode(0,this.pos,t,n?8:4),this.pos=this.reducePos=t,this.score-=190}canShift(e){for(let t=new SimulatedStack(this);;){let n=this.p.parser.stateSlot(t.state,4)||this.p.parser.hasAction(t.state,e);if(0==(65536&n))return!0;if(0==n)return!1;t.reduce(n)}}recoverByInsert(e){if(this.stack.length>=300)return[];let t=this.p.parser.nextStates(this.state);if(t.length>8||this.stack.length>=120){let n=[];for(let r,a=0;a1&t&&e==r))||n.push(t[e],r)}t=n}let n=[];for(let e=0;e>19,r=65535&e,a=this.stack.length-3*n;if(a<0||t.getGoto(this.stack[a],r,!1)<0)return!1;this.storeNode(0,this.reducePos,this.reducePos,4,!0),this.score-=100}return this.reduce(e),!0}forceAll(){for(;!this.p.parser.stateFlag(this.state,2);)if(!this.forceReduce()){this.storeNode(0,this.pos,this.pos,4,!0);break}return this}get deadEnd(){if(3!=this.stack.length)return!1;let{parser:e}=this.p;return 65535==e.data[e.stateSlot(this.state,1)]&&!e.stateSlot(this.state,4)}restart(){this.state=this.stack[0],this.stack.length=0}sameState(e){if(this.state!=e.state||this.stack.length!=e.stack.length)return!1;for(let t=0;tthis.lookAhead&&(this.emitLookAhead(),this.lookAhead=e)}close(){this.curContext&&this.curContext.tracker.strict&&this.emitContext(),this.lookAhead>0&&this.emitLookAhead()}}class StackContext{constructor(e,t){this.tracker=e,this.context=t,this.hash=e.strict?e.hash(t):0}}var Recover;!function(e){e[e.Insert=200]="Insert",e[e.Delete=190]="Delete",e[e.Reduce=100]="Reduce",e[e.MaxNext=4]="MaxNext",e[e.MaxInsertStackDepth=300]="MaxInsertStackDepth",e[e.DampenInsertStackDepth=120]="DampenInsertStackDepth"}(Recover||(Recover={}));class SimulatedStack{constructor(e){this.start=e,this.state=e.state,this.stack=e.stack,this.base=this.stack.length}reduce(e){let t=65535&e,n=e>>19;0==n?(this.stack==this.start.stack&&(this.stack=this.stack.slice()),this.stack.push(this.state,0,0),this.base+=3):this.base-=3*(n-1);let r=this.start.p.parser.getGoto(this.stack[this.base-3],t,!0);this.state=r}}class StackBufferCursor{constructor(e,t,n){this.stack=e,this.pos=t,this.index=n,this.buffer=e.buffer,0==this.index&&this.maybeNext()}static create(e,t=e.bufferBase+e.buffer.length){return new StackBufferCursor(e,t,t-e.bufferBase)}maybeNext(){let e=this.stack.parent;null!=e&&(this.index=this.stack.bufferBase-e.bufferBase,this.stack=e,this.buffer=e.buffer)}get id(){return this.buffer[this.index-4]}get start(){return this.buffer[this.index-3]}get end(){return this.buffer[this.index-2]}get size(){return this.buffer[this.index-1]}next(){this.index-=4,this.pos-=4,0==this.index&&this.maybeNext()}fork(){return new StackBufferCursor(this.stack,this.pos,this.index)}}class CachedToken{constructor(){this.start=-1,this.value=-1,this.end=-1,this.extended=-1,this.lookAhead=0,this.mask=0,this.context=0}}const nullToken=new CachedToken;class InputStream{constructor(e,t){this.input=e,this.ranges=t,this.chunk="",this.chunkOff=0,this.chunk2="",this.chunk2Pos=0,this.next=-1,this.token=nullToken,this.rangeIndex=0,this.pos=this.chunkPos=t[0].from,this.range=t[0],this.end=t[t.length-1].to,this.readNext()}resolveOffset(e,t){let n=this.range,r=this.rangeIndex,a=this.pos+e;for(;an.to:a>=n.to;){if(r==this.ranges.length-1)return null;let e=this.ranges[++r];a+=e.from-n.to,n=e}return a}peek(e){let t,n,r=this.chunkOff+e;if(r>=0&&r=this.chunk2Pos&&tr.to&&(this.chunk2=this.chunk2.slice(0,r.to-t)),n=this.chunk2.charCodeAt(0)}}return t>=this.token.lookAhead&&(this.token.lookAhead=t+1),n}acceptToken(e,t=0){let n=t?this.resolveOffset(t,-1):this.pos;if(null==n||n=this.chunk2Pos&&this.posthis.range.to?e.slice(0,this.range.to-this.pos):e,this.chunkPos=this.pos,this.chunkOff=0}}readNext(){return this.chunkOff>=this.chunk.length&&(this.getChunk(),this.chunkOff==this.chunk.length)?this.next=-1:this.next=this.chunk.charCodeAt(this.chunkOff)}advance(e=1){for(this.chunkOff+=e;this.pos+e>=this.range.to;){if(this.rangeIndex==this.ranges.length-1)return this.setDone();e-=this.range.to-this.pos,this.range=this.ranges[++this.rangeIndex],this.pos=this.range.from}return this.pos+=e,this.pos>=this.token.lookAhead&&(this.token.lookAhead=this.pos+1),this.readNext()}setDone(){return this.pos=this.chunkPos=this.end,this.range=this.ranges[this.rangeIndex=this.ranges.length-1],this.chunk="",this.next=-1}reset(e,t){if(t?(this.token=t,t.start=e,t.lookAhead=e+1,t.value=t.extended=-1):this.token=nullToken,this.pos!=e){if(this.pos=e,e==this.end)return this.setDone(),this;for(;e=this.range.to;)this.range=this.ranges[++this.rangeIndex];e>=this.chunkPos&&e=this.chunkPos&&t<=this.chunkPos+this.chunk.length)return this.chunk.slice(e-this.chunkPos,t-this.chunkPos);if(e>=this.chunk2Pos&&t<=this.chunk2Pos+this.chunk2.length)return this.chunk2.slice(e-this.chunk2Pos,t-this.chunk2Pos);if(e>=this.range.from&&t<=this.range.to)return this.input.read(e,t);let n="";for(let r of this.ranges){if(r.from>=t)break;r.to>e&&(n+=this.input.read(Math.max(r.from,e),Math.min(r.to,t)))}return n}}class TokenGroup{constructor(e,t){this.data=e,this.id=t}token(e,t){readToken(this.data,e,t,this.id)}}TokenGroup.prototype.contextual=TokenGroup.prototype.fallback=TokenGroup.prototype.extend=!1;class ExternalTokenizer{constructor(e,t={}){this.token=e,this.contextual=!!t.contextual,this.fallback=!!t.fallback,this.extend=!!t.extend}}function readToken(e,t,n,r){let a=0,i=1<0){let n=e[r];if(o.allows(n)&&(-1==t.token.value||t.token.value==n||s.overrides(n,t.token.value))){t.acceptToken(n);break}}for(let r=t.next,i=0,s=e[a+2];i>1,l=n+o+(o<<1),u=e[l],c=e[l+1];if(r=c)){a=e[l+2],t.advance();continue e}i=o+1}}break}}function decodeArray(e,t=Uint16Array){if("string"!=typeof e)return e;let n=null;for(let r=0,a=0;r=92&&t--,t>=34&&t--;let a=t-32;if(a>=46&&(a-=46,n=!0),i+=a,n)break;i*=46}n?n[a++]=i:n=new t(i)}return n}const verbose=void 0!==browser$1&&/\bparse\b/.test(browser$1.env.LOG);let stackIDs=null;var Safety,Rec;function cutAt(e,t,n){let r=e.fullCursor();for(r.moveTo(t);;)if(!(n<0?r.childBefore(t):r.childAfter(t)))for(;;){if((n<0?r.tot)&&!r.type.isError)return n<0?Math.max(0,Math.min(r.to-1,t-25)):Math.min(e.length,Math.max(r.from+1,t+25));if(n<0?r.prevSibling():r.nextSibling())break;if(!r.parent())return n<0?0:e.length}}!function(e){e[e.Margin=25]="Margin"}(Safety||(Safety={}));class FragmentCursor{constructor(e,t){this.fragments=e,this.nodeSet=t,this.i=0,this.fragment=null,this.safeFrom=-1,this.safeTo=-1,this.trees=[],this.start=[],this.index=[],this.nextFragment()}nextFragment(){let e=this.fragment=this.i==this.fragments.length?null:this.fragments[this.i++];if(e){for(this.safeFrom=e.openStart?cutAt(e.tree,e.from+e.offset,1)-e.offset:e.from,this.safeTo=e.openEnd?cutAt(e.tree,e.to+e.offset,-1)-e.offset:e.to;this.trees.length;)this.trees.pop(),this.start.pop(),this.index.pop();this.trees.push(e.tree),this.start.push(-e.offset),this.index.push(0),this.nextStart=this.safeFrom}else this.nextStart=1e9}nodeAt(e){if(ee)return this.nextStart=i,null;if(a instanceof Tree){if(i==e){if(i=Math.max(this.safeFrom,e)&&(this.trees.push(a),this.start.push(i),this.index.push(0))}else this.index[t]++,this.nextStart=i+a.length}}}class TokenCache{constructor(e,t){this.stream=t,this.tokens=[],this.mainToken=null,this.actions=[],this.tokens=e.tokenizers.map((e=>new CachedToken))}getActions(e){let t=0,n=null,{parser:r}=e.p,{tokenizers:a}=r,i=r.stateSlot(e.state,3),s=e.curContext?e.curContext.hash:0,o=0;for(let r=0;ru.end+25&&(o=Math.max(u.lookAhead,o)),0!=u.value)){let r=t;if(u.extended>-1&&(t=this.addActions(e,u.extended,u.end,t)),t=this.addActions(e,u.value,u.end,t),!l.extend&&(n=u,t>r))break}}for(;this.actions.length>t;)this.actions.pop();return o&&e.setLookAhead(o),n||e.pos!=this.stream.end||(n=new CachedToken,n.value=e.p.parser.eofTerm,n.start=n.end=e.pos,t=this.addActions(e,n.value,n.end,t)),this.mainToken=n,this.actions}getMainToken(e){if(this.mainToken)return this.mainToken;let t=new CachedToken,{pos:n,p:r}=e;return t.start=n,t.end=Math.min(n+1,r.stream.end),t.value=n==r.stream.end?r.parser.eofTerm:0,t}updateCachedToken(e,t,n){if(t.token(this.stream.reset(n.pos,e),n),e.value>-1){let{parser:t}=n.p;for(let r=0;r=0&&n.p.parser.dialect.allows(a>>1)){0==(1&a)?e.value=a>>1:e.extended=a>>1;break}}}else e.value=0,e.end=Math.min(n.p.stream.end,n.pos+1)}putAction(e,t,n,r){for(let t=0;t4*e.bufferLength?new FragmentCursor(n,e.nodeSet):null}get parsedPos(){return this.minStackPos}advance(){let e,t,n=this.stacks,r=this.minStackPos,a=this.stacks=[];for(let i=0;ir)a.push(s);else{if(this.advanceStack(s,a,n))continue;{e||(e=[],t=[]),e.push(s);let n=this.tokens.getMainToken(s);t.push(n.value,n.end)}}break}}if(!a.length){let t=e&&findFinished(e);if(t)return this.stackToTree(t);if(this.parser.strict)throw verbose&&e&&console.log("Stuck with token "+(this.tokens.mainToken?this.parser.getName(this.tokens.mainToken.value):"none")),new SyntaxError("No parse at "+r);this.recovering||(this.recovering=5)}if(this.recovering&&e){let n=null!=this.stoppedAt&&e[0].pos>this.stoppedAt?e[0]:this.runRecovery(e,t,a);if(n)return this.stackToTree(n.forceAll())}if(this.recovering){let e=1==this.recovering?1:3*this.recovering;if(a.length>e)for(a.sort(((e,t)=>t.score-e.score));a.length>e;)a.pop();a.some((e=>e.reducePos>r))&&this.recovering--}else if(a.length>1)e:for(let e=0;e500&&r.buffer.length>500){if(!((t.score-r.score||t.buffer.length-r.buffer.length)>0)){a.splice(e--,1);continue e}a.splice(n--,1)}}}this.minStackPos=a[0].pos;for(let e=1;e ":"";if(null!=this.stoppedAt&&r>this.stoppedAt)return e.forceReduce()?e:null;if(this.fragments){let t=e.curContext&&e.curContext.tracker.strict,n=t?e.curContext.hash:0;for(let s=this.fragments.nodeAt(r);s;){let r=this.parser.nodeSet.types[s.type.id]==s.type?a.getGoto(e.state,s.type.id):-1;if(r>-1&&s.length&&(!t||(s.prop(NodeProp.contextHash)||0)==n))return e.useNode(s,r),verbose&&console.log(i+this.stackID(e)+` (via reuse of ${a.getName(s.type.id)})`),!0;if(!(s instanceof Tree)||0==s.children.length||s.positions[0]>0)break;let o=s.children[0];if(!(o instanceof Tree&&0==s.positions[0]))break;s=o}}let s=a.stateSlot(e.state,4);if(s>0)return e.reduce(s),verbose&&console.log(i+this.stackID(e)+` (via always-reduce ${a.getName(65535&s)})`),!0;if(e.stack.length>=15e3)for(;e.stack.length>9e3&&e.forceReduce(););let o=this.tokens.getActions(e);for(let s=0;sr?t.push(d):n.push(d)}return!1}advanceFully(e,t){let n=e.pos;for(;;){if(!this.advanceStack(e,null,null))return!1;if(e.pos>n)return pushStackDedup(e,t),!0}}runRecovery(e,t,n){let r=null,a=!1;for(let i=0;i ":"";if(s.deadEnd){if(a)continue;if(a=!0,s.restart(),verbose&&console.log(u+this.stackID(s)+" (restarted)"),this.advanceFully(s,n))continue}let c=s.split(),p=u;for(let e=0;c.forceReduce()&&e<10;e++){if(verbose&&console.log(p+this.stackID(c)+" (via force-reduce)"),this.advanceFully(c,n))break;verbose&&(p=this.stackID(c)+" -> ")}for(let e of s.recoverByInsert(o))verbose&&console.log(u+this.stackID(e)+" (via recover-insert)"),this.advanceFully(e,n);this.stream.end>s.pos?(l==s.pos&&(l++,o=0),s.recoverByDelete(o,l),verbose&&console.log(u+this.stackID(s)+` (via recover-delete ${this.parser.getName(o)})`),pushStackDedup(s,n)):(!r||r.scoree;class ContextTracker{constructor(e){this.start=e.start,this.shift=e.shift||id,this.reduce=e.reduce||id,this.reuse=e.reuse||id,this.hash=e.hash||(()=>0),this.strict=!1!==e.strict}}class LRParser extends Parser$1{constructor(e){if(super(),this.wrappers=[],13!=e.version)throw new RangeError(`Parser version (${e.version}) doesn't match runtime version (13)`);let t=e.nodeNames.split(" ");this.minRepeatTerm=t.length;for(let n=0;ne.topRules[t][1])),r=[];for(let e=0;e=0)a(r,e,t[n++]);else{let i=t[n+-r];for(let s=-r;s>0;s--)a(t[n++],e,i);n++}}}this.nodeSet=new NodeSet(t.map(((t,a)=>NodeType.define({name:a>=this.minRepeatTerm?void 0:t,id:a,props:r[a],top:n.indexOf(a)>-1,error:0==a,skipped:e.skippedNodes&&e.skippedNodes.indexOf(a)>-1})))),this.strict=!1,this.bufferLength=DefaultBufferLength;let i=decodeArray(e.tokenData);if(this.context=e.context,this.specialized=new Uint16Array(e.specialized?e.specialized.length:0),this.specializers=[],e.specialized)for(let t=0;t"number"==typeof e?new TokenGroup(i,e):e)),this.topRules=e.topRules,this.dialects=e.dialects||{},this.dynamicPrecedences=e.dynamicPrecedences||null,this.tokenPrecTable=e.tokenPrec,this.termNames=e.termNames||null,this.maxNode=this.nodeSet.types.length-1,this.dialect=this.parseDialect(),this.top=this.topRules[Object.keys(this.topRules)[0]]}createParse(e,t,n){let r=new Parse(this,e,t,n);for(let a of this.wrappers)r=a(r,e,t,n);return r}getGoto(e,t,n=!1){let r=this.goto;if(t>=r[0])return-1;for(let a=r[t+1];;){let t=r[a++],i=1&t,s=r[a++];if(i&&n)return s;for(let n=a+(t>>1);a0}validAction(e,t){if(t==this.stateSlot(e,4))return!0;for(let n=this.stateSlot(e,1);;n+=3){if(65535==this.data[n]){if(1!=this.data[n+1])return!1;n=pair(this.data,n+2)}if(t==pair(this.data,n+1))return!0}}nextStates(e){let t=[];for(let n=this.stateSlot(e,1);;n+=3){if(65535==this.data[n]){if(1!=this.data[n+1])break;n=pair(this.data,n+2)}if(0==(1&this.data[n+2])){let e=this.data[n+1];t.some(((t,n)=>1&n&&t==e))||t.push(this.data[n],e)}}return t}overrides(e,t){let n=findOffset(this.data,this.tokenPrecTable,t);return n<0||findOffset(this.data,this.tokenPrecTable,e){let n=e.tokenizers.find((e=>e.from==t));return n?n.to:t}))),e.contextTracker&&(t.context=e.contextTracker),e.dialect&&(t.dialect=this.parseDialect(e.dialect)),null!=e.strict&&(t.strict=e.strict),e.wrap&&(t.wrappers=t.wrappers.concat(e.wrap)),null!=e.bufferLength&&(t.bufferLength=e.bufferLength),t}getName(e){return this.termNames?this.termNames[e]:String(e<=this.maxNode&&this.nodeSet.types[e].name||e)}get eofTerm(){return this.maxNode+1}get topNode(){return this.nodeSet.types[this.top[1]]}dynamicPrecedence(e){let t=this.dynamicPrecedences;return null==t?0:t[e]||0}parseDialect(e){let t=Object.keys(this.dialects),n=t.map((()=>!1));if(e)for(let r of e.split(" ")){let e=t.indexOf(r);e>=0&&(n[e]=!0)}let r=null;for(let e=0;ee)&&n.p.parser.stateFlag(n.state,2)&&(!t||t.score=65&&e<=90||95==e||e>=97&&e<=122||e>=161}function isSpace(e){return 9==e||10==e||13==e||32==e}let cachedName=null,cachedInput=null,cachedPos=0;function tagNameAfter(e,t){let n=e.pos+t;if(cachedInput==e&&cachedPos==n)return cachedName;for(;isSpace(e.peek(t));)t++;let r="";for(;;){let n=e.peek(t);if(!nameChar(n))break;r+=String.fromCharCode(n),t++}return cachedInput=e,cachedPos=n,cachedName=r||null}function ElementContext(e,t){this.name=e,this.parent=t,this.hash=t?t.hash:0;for(let t=0;tt==StartTag?new ElementContext(tagNameAfter(r,1)||"",e):e,reduce:(e,t)=>t==Element&&e?e.parent:e,reuse(e,t,n,r){let a=t.type.id;return a==StartTag||a==OpenTag?new ElementContext(tagNameAfter(r,1)||"",e):e},hash:e=>e?e.hash:0,strict:!1}),startTag=new ExternalTokenizer(((e,t)=>{if(60==e.next)if(e.advance(),47==e.next){e.advance();let n=tagNameAfter(e,0);if(!n)return e.acceptToken(incompleteStartCloseTag);if(t.context&&n.toLowerCase()==t.context.name.toLowerCase())return e.acceptToken(StartCloseTag);for(let r=t.context;r;r=r.parent)if(r.name==n)return e.acceptToken(MissingCloseTag,-2);e.acceptToken(mismatchedStartCloseTag)}else if(33!=e.next&&63!=e.next&&!isSpace(e.next))return e.acceptToken(StartTag)}),{contextual:!0});function scanTo(e,t){return new ExternalTokenizer((n=>{for(let r=0,a=0;;a++){if(n.next<0){a&&n.acceptToken(e);break}if(n.next==t.charCodeAt(r)){if(r++,r==t.length){a>t.length&&n.acceptToken(e,1-t.length);break}}else r=0;n.advance()}}))}const commentContent=scanTo(commentContent$1,"--\x3e"),parser=LRParser.deserialize({version:13,states:"*[OQOTOOO]OYO'#CdOeO`O'#CfO!OOTO'#CeOOOP'#Ce'#CeOOOP'#Cx'#CxOOOP'#Co'#CoQQOTOOOOOQ'#Cp'#CpO!VOYO,59OOOOP,59O,59OO!_OpO,59QO!mO`O'#ClOOOP'#DT'#DTOOOP'#Cu'#CuO!rOTO,59PO!yO`O'#CmOOOP,59P,59POOOP-E6m-E6mOOOQ-E6n-E6nOOOP1G.j1G.jOOOO'#Cq'#CqO#ROpO1G.lO#aOpO'#ChOOOO'#Cr'#CrO#rOpO1G.lOOOP1G.l1G.lOOOP1G.t1G.tO#}OWO,59WOOOP-E6s-E6sOOOP1G.k1G.kO$SO`O,59XO$[OWO,59XOOOO-E6o-E6oO$dOpO7+$WOOOP7+$W7+$WOOOP7+$`7+$`O$oOpO,59SO%QOWO,59SOOOO-E6p-E6pOOOP1G.r1G.rO%]OWO1G.sO%]OWO1G.sOOOP1G.s1G.sOOOP< tag. Found ${e.slice(a-1,i)}`)}n.firstChild();let t=e.substring(n.from,n.to);if(!1===n.nextSibling()){if(t in i)throw Error(`Duplicate attribute ${t}. Found in component of type ${r} at indices ${n.from}-${n.to}`);i[t]=!0}else{n.nextSibling();let a=e.substring(n.from+1,n.to-1);if(t in i)throw Error(`Duplicate attribute ${t}. Found in component of type ${r} at indices ${n.from}-${n.to}`);i[t]=a}n.parent()}n.parent();let s=n.to,o={componentType:r,props:{...i},children:[]};for(;n.nextSibling();)if("Text"===n.name){let t=e.substring(n.from,n.to);""!==t&&o.children.push(t)}else{if("Element"!==n.name){if("CloseTag"===n.name)break;if("Comment"===n.name)continue;throw"MismatchedCloseTag"===n.name?Error(`Invalid DoenetML at position ${n.from}. Mismatched closing tag. Expected . Found ${e.slice(n.from,n.to)}.`):Error(`Invalid DoenetML at position ${n.from}. Expected a closing tag. Instead found ${e.slice(n.from,n.to)}.`)}o.children.push(t(n.node.cursor))}return o.range={openBegin:a,openEnd:s,closeBegin:n.from,closeEnd:n.to},o}if("SelfClosingTag"===n.name){n.firstChild(),n.nextSibling();let t=e.substring(n.from,n.to),r=n.from,a={};for(;n.nextSibling();){if("Attribute"!==n.name)throw Error(`Invalid DoenetML at positions ${n.from} to ${n.to}. Error in self-closing <${t}/> tag.`);n.firstChild();let r=e.substring(n.from,n.to);if(!1===n.nextSibling()){if(r in a)throw Error(`Duplicate attribute ${r}. Found in component of type ${t} at indices ${n.from}-${n.to}`);a[r]=!0}else{if(n.nextSibling(),r in a)throw Error(`Duplicate attribute ${r}. Found in component of type ${t} at indices ${n.from}-${n.to}`);let i=e.substring(n.from+1,n.to-1);a[r]=i}n.parent()}let i={selfCloseBegin:r,selfCloseEnd:n.to+2};return{componentType:t,props:{...a},children:[],range:i}}throw Error("Non SelfClosingTag/OpenTag in Element. How did you do that?")}function n(n){if("Element"===n.node.name)return t(n.node.cursor);if("Comment"===n.node.name)return null;if("Text"!==n.node.name)throw Error(`Invalid DoenetML at positions ${n.node.from} to ${n.node.to}. Found ${e.substring(n.node.from,n.node.to)}`);{let t=e.substring(n.node.from,n.node.to);if(""!==t)return t}}if(!e)return[];let r=parse(e),a=[];if(!r.firstChild())return a;let i=n(r);for(null!=i&&a.push(i);r.nextSibling();){let e=n(r);null!=e&&a.push(e)}return a}var base32$1={exports:{}};!function(e){!function(){var t="object"==typeof window?window:{};!t.HI_BASE32_NO_NODE_JS&&"object"==typeof browser$1&&browser$1.versions&&browser$1.versions.node&&(t=commonjsGlobal);var n=!t.HI_BASE32_NO_COMMON_JS&&e.exports,r="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567".split(""),a={A:0,B:1,C:2,D:3,E:4,F:5,G:6,H:7,I:8,J:9,K:10,L:11,M:12,N:13,O:14,P:15,Q:16,R:17,S:18,T:19,U:20,V:21,W:22,X:23,Y:24,Z:25,2:26,3:27,4:28,5:29,6:30,7:31},i=[0,0,0,0,0,0,0,0],s=function(e,t){t.length>10&&(t="..."+t.substr(-10));var n=new Error("Decoded data is not valid UTF-8. Maybe try base32.decode.asBytes()? Partial data after reading "+e+" bytes: "+t+" <-");throw n.position=e,n},o=function(e){if(""===e)return[];if(!/^[A-Z2-7=]+$/.test(e))throw new Error("Invalid base32 characters");for(var t,n,r,i,s,o,l,u,c=[],p=0,d=(e=e.replace(/=/g,"")).length,m=0,h=d>>3<<3;m>>2),c[p++]=255&(n<<6|r<<1|i>>>4),c[p++]=255&(i<<4|s>>>1),c[p++]=255&(s<<7|o<<2|l>>>3),c[p++]=255&(l<<5|u);var f=d-h;return 2===f?(t=a[e.charAt(m++)],n=a[e.charAt(m++)],c[p++]=255&(t<<3|n>>>2)):4===f?(t=a[e.charAt(m++)],n=a[e.charAt(m++)],r=a[e.charAt(m++)],i=a[e.charAt(m++)],c[p++]=255&(t<<3|n>>>2),c[p++]=255&(n<<6|r<<1|i>>>4)):5===f?(t=a[e.charAt(m++)],n=a[e.charAt(m++)],r=a[e.charAt(m++)],i=a[e.charAt(m++)],s=a[e.charAt(m++)],c[p++]=255&(t<<3|n>>>2),c[p++]=255&(n<<6|r<<1|i>>>4),c[p++]=255&(i<<4|s>>>1)):7===f&&(t=a[e.charAt(m++)],n=a[e.charAt(m++)],r=a[e.charAt(m++)],i=a[e.charAt(m++)],s=a[e.charAt(m++)],o=a[e.charAt(m++)],l=a[e.charAt(m++)],c[p++]=255&(t<<3|n>>>2),c[p++]=255&(n<<6|r<<1|i>>>4),c[p++]=255&(i<<4|s>>>1),c[p++]=255&(s<<7|o<<2|l>>>3)),c},l=function(e,t){if(!t)return function(e){for(var t,n,r="",a=e.length,i=0,o=0;i191&&t<=223?(n=31&t,o=1):t<=239?(n=15&t,o=2):t<=247?(n=7&t,o=3):s(i,r);for(var l=0;l191)&&s(i,r),n<<=6,n+=63&t;n>=55296&&n<=57343&&s(i,r),n>1114111&&s(i,r),n<=65535?r+=String.fromCharCode(n):(n-=65536,r+=String.fromCharCode(55296+(n>>10)),r+=String.fromCharCode(56320+(1023&n)))}return r}(o(e));if(""===e)return"";if(!/^[A-Z2-7=]+$/.test(e))throw new Error("Invalid base32 characters");var n,r,i,l,u,c,p,d,m="",h=e.indexOf("=");-1===h&&(h=e.length);for(var f=0,y=h>>3<<3;f>>2))+String.fromCharCode(255&(r<<6|i<<1|l>>>4))+String.fromCharCode(255&(l<<4|u>>>1))+String.fromCharCode(255&(u<<7|c<<2|p>>>3))+String.fromCharCode(255&(p<<5|d));var g=h-y;return 2===g?(n=a[e.charAt(f++)],r=a[e.charAt(f++)],m+=String.fromCharCode(255&(n<<3|r>>>2))):4===g?(n=a[e.charAt(f++)],r=a[e.charAt(f++)],i=a[e.charAt(f++)],l=a[e.charAt(f++)],m+=String.fromCharCode(255&(n<<3|r>>>2))+String.fromCharCode(255&(r<<6|i<<1|l>>>4))):5===g?(n=a[e.charAt(f++)],r=a[e.charAt(f++)],i=a[e.charAt(f++)],l=a[e.charAt(f++)],u=a[e.charAt(f++)],m+=String.fromCharCode(255&(n<<3|r>>>2))+String.fromCharCode(255&(r<<6|i<<1|l>>>4))+String.fromCharCode(255&(l<<4|u>>>1))):7===g&&(n=a[e.charAt(f++)],r=a[e.charAt(f++)],i=a[e.charAt(f++)],l=a[e.charAt(f++)],u=a[e.charAt(f++)],c=a[e.charAt(f++)],p=a[e.charAt(f++)],m+=String.fromCharCode(255&(n<<3|r>>>2))+String.fromCharCode(255&(r<<6|i<<1|l>>>4))+String.fromCharCode(255&(l<<4|u>>>1))+String.fromCharCode(255&(u<<7|c<<2|p>>>3))),m},u={encode:function(e,t){var n="string"!=typeof e;return n&&e.constructor===ArrayBuffer&&(e=new Uint8Array(e)),n?function(e){for(var t,n,a,i,s,o="",l=e.length,u=0,c=5*parseInt(l/5);u>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[31&(n<<4|a>>>4)]+r[31&(a<<1|i>>>7)]+r[i>>>2&31]+r[31&(i<<3|s>>>5)]+r[31&s];var p=l-c;return 1===p?(t=e[u],o+=r[t>>>3]+r[t<<2&31]+"======"):2===p?(t=e[u++],n=e[u],o+=r[t>>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[n<<4&31]+"===="):3===p?(t=e[u++],n=e[u++],a=e[u],o+=r[t>>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[31&(n<<4|a>>>4)]+r[a<<1&31]+"==="):4===p&&(t=e[u++],n=e[u++],a=e[u++],i=e[u],o+=r[t>>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[31&(n<<4|a>>>4)]+r[31&(a<<1|i>>>7)]+r[i>>>2&31]+r[i<<3&31]+"="),o}(e):t?function(e){for(var t,n,a,i,s,o="",l=e.length,u=0,c=5*parseInt(l/5);u>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[31&(n<<4|a>>>4)]+r[31&(a<<1|i>>>7)]+r[i>>>2&31]+r[31&(i<<3|s>>>5)]+r[31&s];var p=l-c;return 1===p?(t=e.charCodeAt(u),o+=r[t>>>3]+r[t<<2&31]+"======"):2===p?(t=e.charCodeAt(u++),n=e.charCodeAt(u),o+=r[t>>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[n<<4&31]+"===="):3===p?(t=e.charCodeAt(u++),n=e.charCodeAt(u++),a=e.charCodeAt(u),o+=r[t>>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[31&(n<<4|a>>>4)]+r[a<<1&31]+"==="):4===p&&(t=e.charCodeAt(u++),n=e.charCodeAt(u++),a=e.charCodeAt(u++),i=e.charCodeAt(u),o+=r[t>>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[31&(n<<4|a>>>4)]+r[31&(a<<1|i>>>7)]+r[i>>>2&31]+r[i<<3&31]+"="),o}(e):function(e){var t,n,a,s,o,l,u,c=!1,p="",d=0,m=0,h=e.length;if(""===e)return p;do{for(i[0]=i[5],i[1]=i[6],i[2]=i[7],u=m;d>6,i[u++]=128|63&l):l<55296||l>=57344?(i[u++]=224|l>>12,i[u++]=128|l>>6&63,i[u++]=128|63&l):(l=65536+((1023&l)<<10|1023&e.charCodeAt(++d)),i[u++]=240|l>>18,i[u++]=128|l>>12&63,i[u++]=128|l>>6&63,i[u++]=128|63&l);m=u-5,d===h&&++d,d>h&&u<6&&(c=!0),t=i[0],u>4?(n=i[1],a=i[2],s=i[3],o=i[4],p+=r[t>>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[31&(n<<4|a>>>4)]+r[31&(a<<1|s>>>7)]+r[s>>>2&31]+r[31&(s<<3|o>>>5)]+r[31&o]):1===u?p+=r[t>>>3]+r[t<<2&31]+"======":2===u?(n=i[1],p+=r[t>>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[n<<4&31]+"===="):3===u?(n=i[1],a=i[2],p+=r[t>>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[31&(n<<4|a>>>4)]+r[a<<1&31]+"==="):(n=i[1],a=i[2],s=i[3],p+=r[t>>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[31&(n<<4|a>>>4)]+r[31&(a<<1|s>>>7)]+r[s>>>2&31]+r[s<<3&31]+"=")}while(!c);return p}(e)},decode:l};l.asBytes=o,n?e.exports=u:t.base32=u}()}(base32$1);var base32=base32$1.exports;async function cidFromText(e){let t=(new TextEncoder).encode(e);return await cidFromArrayBuffer(t)}async function cidFromArrayBuffer(e){let t=await crypto.subtle.digest("SHA-256",e),n=new Uint8Array(36);return n.set([1,85,18,32]),n.set(new Uint8Array(t),4),"b"+base32.encode(n).toLowerCase().replace(/=+/,"")}const textByCid={};function retrieveTextFileForCid(e,t="doenet"){return void 0!==textByCid[e]?Promise.resolve(textByCid[e]):new Promise(((n,r)=>{let a,i,s=retrieveTextFileFromIPFS(e),o=s.promise,l=s.controller,u=!1,c=!1;o.then((t=>{clearTimeout(i),a&&!c&&a.abort(),textByCid[e]=t,n(t)})).catch((e=>{u=!0,c&&(clearTimeout(i),r(e))})),i=setTimeout((()=>{let s=retrieveTextFileFromServer(e,t),o=s.promise;a=s.controller,o.then((t=>{u||l.abort(),textByCid[e]=t,n(t)})).catch((e=>{c=!0,u?r(e):i=setTimeout((()=>{l.abort(),r(e)}),5e3)}))}),100)}))}function retrieveTextFileFromIPFS(e){let t=new AbortController,n=t.signal;return{promise:async function(){try{let t=await fetch(`https://${e}.ipfs.dweb.link/`,{signal:n});if(t.ok){let n=await t.text();return await cidFromText(n)===e?n:Promise.reject(new Error("cid mismatch"))}return Promise.reject(new Error(`cid not found: ${e}`))}catch(t){return Promise.reject(new Error(`cid not found: ${e}`))}}(),controller:t}}function retrieveTextFileFromServer(e,t){let n=new AbortController,r=n.signal;return{promise:async function(){try{let n=await fetch(`/media/${e}.${t}`,{signal:r});if(n.ok){let t=await n.text(),r=await cidFromText(t);return r===e?t:(console.warn(`cid mismatch, ${e}, ${r}`),Promise.reject(new Error("cid mismatch")))}return Promise.reject(new Error(`cid not found: ${e}`))}catch(t){return Promise.reject(new Error(`cid not found: ${e}`))}}(),controller:n}}async function expandDoenetMLsToFullSerializedComponents({cids:e,doenetMLs:t,componentInfoObjects:n}){let r=[],a={};for(let e of t){let t=parseAndCompile(e);t=cleanIfHaveJustDocument(t),substituteDeprecations(t),temporarilyRenameSourceBackToTarget(t),correctComponentTypeCapitalization(t,n.componentTypeLowerCaseMapping),copyTargetOrFromURIAttributeCreatesCopyComponent(t,n.isCompositeComponent),createAttributesFromProps(t,n),breakUpTargetIntoPropsAndIndices(t,n),applyMacros(t,n),removeBlankStringChildren(t,n),decodeXMLEntities(t),applySugar({serializedComponents:t,componentInfoObjects:n}),r.push(t);let i=findContentCopies({serializedComponents:t});for(let e in i.cidComponents)void 0===a[e]&&(a[e]=[]),a[e].push(...i.cidComponents[e])}let i=Object.keys(a);if(i.length>0){let{newDoenetMLs:e,newCids:t}=await cidsToDoenetMLs(i);for(let[e,n]of i.entries())if(t[e]&&t[e].substring(0,n.length)!==n)return Promise.reject(new Error(`Requested cid ${n} but got back ${t[e]}!`));let r=i.length;for(let n=0;n"string"!=typeof e||e.trim())),r=1===t.length&&"object"==typeof t[0],a=e.doenetAttributes?.fromCopyFromURI;if(a||r)if(a&&!r)console.warn("ignoring copyFromURI as it was not a single component");else{let n=t[0];n.attributes||(n.attributes={}),e.doenetAttributes||(e.doenetAttributes={}),e.doenetAttributes.keptNewNamespaceOfLastChild=Boolean(n.attributes.newNamespace?.primitive),n.attributes.newNamespace={primitive:!0},e.children=[n,...e.children],e.doenetAttributes.nameFirstChildIndependently=!0}else{let t={componentType:"externalContent",children:JSON.parse(JSON.stringify(n)),attributes:{newNamespace:{primitive:!0}},doenetAttributes:{createUniqueName:!0}};e.children=[t,...e.children]}}}}return{cids:e,fullSerializedComponents:r}}function cidsToDoenetMLs(e){let t=[],n=e;for(let n of e)t.push(retrieveTextFileForCid(n,"doenet"));return Promise.all(t).then((e=>Promise.resolve({newDoenetMLs:e,newCids:n}))).catch((e=>{let t;return t=1===n.length?`Could not retrieve cid ${n[0]}`:`Could not retrieve cids ${n.join(",")}`,t+=": "+e.message,console.error(t),Promise.reject(new Error(t))}))}function removeBlankStringChildren(e,t){for(let n of e){if(n.children){let e=t.allComponentClasses[n.componentType];e&&!e.includeBlankStringChildren&&(n.children=n.children.filter((e=>"string"!=typeof e||""!==e.trim()))),removeBlankStringChildren(n.children,t)}for(let e in n.attributes){let r=n.attributes[e].component;r&&r.children&&removeBlankStringChildren([r],t)}}}function findContentCopies({serializedComponents:e}){let t={};for(let n of e)if("copy"===n.componentType){if(n.attributes&&n.attributes.uri){let e=n.attributes.uri.primitive;if(e&&"doenet:"===e.substring(0,7).toLowerCase()){let r=e.match(/[:&]cid=([^&]+)/i);if(r){let e=r[1];void 0===t[e]&&(t[e]=[]),t[e].push(n)}}}}else if(void 0!==n.children){let e=findContentCopies({serializedComponents:n.children});for(let n in e.cidComponents)void 0===t[n]&&(t[n]=[]),t[n].push(...e.cidComponents[n])}return{cidComponents:t}}function addDocumentIfItsMissing(e){if(1!==e.length||"document"!==e[0].componentType){let t=e.splice(0);e.push({componentType:"document",children:t})}}function substituteDeprecations(e){let t={tname:"target",triggerwithtnames:"triggerWith",updatewithtname:"updateWith",paginatortname:"paginator",randomizeorder:"shuffleOrder",copytarget:"copySource",triggerwithtargets:"triggerWith",triggerwhentargetsclicked:"triggerWhenObjectsClicked",fortarget:"forObject",targetattributestoignore:"sourceAttributesToIgnore",targetattributestoignorerecursively:"sourceAttributesToIgnoreRecursively",targetsareresponses:"sourcesAreResponses",updatewithtarget:"updateWith",targetsarefunctionsymbols:"sourcesAreFunctionSymbols",selectforvariantnames:"selectForVariants"},n={copy:{target:"source",tname:"source"},collect:{target:"source",tname:"source"},summarystatistics:{target:"source"}};for(let r of e)if("object"==typeof r){if(r.props){let e=r.componentType,a=n[e.toLowerCase()];a||(a={});let i=!0;for(;i;){i=!1;for(let n in r.props){let s=n.toLowerCase();if(s in a){let t=a[s];console.warn(`Attribute ${n} of component type ${e} is deprecated. Use ${t} instead.`),r.props[t]=r.props[n],delete r.props[n],i=!0;break}if(s in t){let e=t[s];console.warn(`Attribute ${n} is deprecated. Use ${e} instead.`),r.props[e]=r.props[n],delete r.props[n],i=!0;break}}}}r.children&&substituteDeprecations(r.children)}}function temporarilyRenameSourceBackToTarget(e){let t={copysource:"copyTarget"},n={copy:{source:"target"},collect:{source:"target"}};for(let r of e)if("object"==typeof r){if(r.props){let e=n[r.componentType.toLowerCase()];e||(e={});let a=!0;for(;a;){a=!1;for(let n in r.props){let i=n.toLowerCase();if(i in e){let t=e[i];r.props[t]=r.props[n],delete r.props[n],a=!0;break}if(i in t){let e=t[i];r.props[e]=r.props[n],delete r.props[n],a=!0;break}}}}r.children&&temporarilyRenameSourceBackToTarget(r.children)}}function cleanIfHaveJustDocument(e){let t=e.filter((e=>"string"!=typeof e||""!==e.trim()));return 1===t.length&&"document"===t[0].componentType?t:e}function correctComponentTypeCapitalization(e,t){for(let n of e){if("object"!=typeof n)continue;let e=t[n.componentType.toLowerCase()];if(!e)throw Error(`Invalid component type${indexRangeString(n)}: ${n.componentType}`);n.componentType=e,n.children&&correctComponentTypeCapitalization(n.children,t)}}function copyTargetOrFromURIAttributeCreatesCopyComponent(e,t){for(let n of e){if(n.props){let e=!1,r=!1,a=!1,i=n.componentType,s=t({componentType:i,includeNonStandard:!1}),o=t({componentType:i,includeNonStandard:!0});for(let t of Object.keys(n.props)){let l=t.toLowerCase();if("copytarget"===l){if(e)throw Error(`Cannot repeat attribute ${t}. Found in component type ${i}${indexRangeString(n)}`);if(r)throw Error(`Cannot combine copyTarget and copyFromURI attribiutes. For in component of type ${i}${indexRangeString(n)}`);if(a)throw o?Error(`A component of type ${i} cannot have both assignNames and copyTarget. Found${indexRangeString(n)}.`):Error(`Invalid attribute assignNames for component of type ${i}${indexRangeString(n)}`);if(e=!0,n.doenetAttributes||(n.doenetAttributes={}),s||(n.props.createComponentOfType=i,n.doenetAttributes.nameBecomesAssignNames=!0),n.componentType="copy",n.props.target=n.props[t],"string"!=typeof n.props.target)throw Error(`Must specify value for copyTarget. Found in component of type ${i}${indexRangeString(n)}`);delete n.props[t],n.doenetAttributes.fromCopyTarget=!0,n.doenetAttributes.createNameFromComponentType=i,n.props.assignNamesSkip="1"}else if("copyfromuri"===l){if(r)throw Error(`Cannot repeat attribute ${t}. Found in component type ${i}${indexRangeString(n)}`);if(e)throw Error(`Cannot combine copyTarget and copyFromURI attribiutes. For in component of type ${i}${indexRangeString(n)}`);if(a)throw o?Error(`A component of type ${i} cannot have both assignNames and copyFromURI. Found${indexRangeString(n)}.`):Error(`Invalid attribute assignNames for component of type ${i}${indexRangeString(n)}`);if(r=!0,n.doenetAttributes||(n.doenetAttributes={}),s||(n.props.createComponentOfType=i,n.doenetAttributes.nameBecomesAssignNames=!0),n.componentType="copy",n.props.uri=n.props[t],"string"!=typeof n.props.uri)throw Error(`Must specify value for copyFromURI. Found in component of type ${i}${indexRangeString(n)}`);delete n.props[t],n.doenetAttributes.fromCopyFromURI=!0,n.doenetAttributes.createNameFromComponentType=i,n.props.assignNamesSkip="1"}else if("assignnames"===l&&!s){if(e||r)throw o?Error(`A component of type ${i} cannot have both assignNames and copyTarget. Found${indexRangeString(n)}.`):Error(`Invalid attribute assignNames for component of type ${i}${indexRangeString(n)}`);a=!0}}if(e){for(let e of Object.keys(n.props)){if("prop"===e.toLowerCase())throw Error(`Invalid attribute prop for component of type ${i}${indexRangeString(n)}`)}let e=!1;for(let t of Object.keys(n.props)){if("copyprop"===t.toLowerCase()){if(e)throw Error(`Cannot repeat attribute ${t}. Found in component type ${i}${indexRangeString(n)}`);n.props.prop=n.props[t],delete n.props[t],e=!0}}}}n.children&©TargetOrFromURIAttributeCreatesCopyComponent(n.children,t)}}function breakUpTargetIntoPropsAndIndices(e,t,n=""){for(let[r,a]of e.entries()){if(a.props&&["copy","updateValue","animateFromSequence"].includes(a.componentType)){let i,s,o,l,u,c,p;for(let e of Object.keys(a.props)){if("target"===e.toLowerCase()){if(i)throw Error(`Cannot repeat attribute ${e}. Found in component type ${a.componentType}${indexRangeString(a)}`);i=e,p=a.props[e];let t=buildSourcePieces(p,!0);t.success&&t.matchLength===p.length&&(s=t.sourceName,o=t.componentIndex,l=t.componentAttributes,u=t.propArray,c=t.subNames)}}if(i&&s)if(o||l||u.length>0){if(a.attributes.prop)throw Error(`Cannot combine the prop attribute with an extended source attribute. Found in component type ${a.componentType}${indexRangeString(a)}`);if(a.attributes.propIndex)throw Error(`Cannot combine the propIndex attribute with an extended source attribute. Found in component type ${a.componentType}${indexRangeString(a)}`);if(a.attributes.componentIndex)throw Error(`Cannot combine the componentIndex attribute with an extended source attribute. Found in component type ${a.componentType}${indexRangeString(a)}`);let d=createComponentFromExtendedSource({sourceName:s,componentIndex:o,subNames:c,componentAttributes:l,propArray:u,componentInfoObjects:t});if(d.success){let t=d.newComponent;if("copy"===a.componentType)delete a.props[i],Object.assign(a.attributes,t.attributes),a.doenetAttributes||(a.doenetAttributes={}),Object.assign(a.doenetAttributes,t.doenetAttributes),a.doenetAttributes.createNameFromComponentType||(a.doenetAttributes.createNameFromComponentType=a.componentType),a.componentType=t.componentType,0!==u.length||a.attributes.prop||a.attributes.propIndex||(a.doenetAttributes.isPlainCopy=!0),t.children&&(a.children=t.children);else if("copy"===t.componentType)delete a.props[i],Object.assign(a.attributes,t.attributes),a.doenetAttributes||(a.doenetAttributes={}),Object.assign(a.doenetAttributes,t.doenetAttributes);else{let s=createUniqueName("extract","fromExtendedSource"+n+"|"+r);t.doenetAttributes.prescribedName=s,t.doenetAttributes.createdFromMacro=!0;let o={componentType:"setup",children:[t],doenetAttributes:{createdFromMacro:!0}};e.push(o),delete a.props[i],a.doenetAttributes||(a.doenetAttributes={}),a.doenetAttributes.target=s,a.doenetAttributes.allowDoubleUnderscoreTarget=!0}}else"copy"===a.componentType?console.warn(`invalid copy source: ${p}`):console.warn(`invalid target: ${p}`)}else"copy"!==a.componentType||a.attributes.prop||a.attributes.propIndex||(a.doenetAttributes||(a.doenetAttributes={}),a.doenetAttributes.isPlainCopy=!0)}a.children&&breakUpTargetIntoPropsAndIndices(a.children,t,n+"|"+r)}}function createAttributesFromProps(e,t){for(let n of e){if("object"!=typeof n)continue;let e=t.allComponentClasses[n.componentType],r=e.createAttributesObject(),a={};for(let e in r)a[e.toLowerCase()]=e;let i={},s=Object.assign({},n.props);if(n.props)for(let o in n.props){let l=a[o.toLowerCase()],u=r[l];if(u){if(l in i)throw Error(`Cannot repeat attribute ${l}. Found in component type ${n.componentType}${indexRangeString(n)}`);i[l]=componentFromAttribute({attrObj:u,value:n.props[o],originalComponentProps:s,componentInfoObjects:t}),delete n.props[o]}else if(!["name","assignnames","target"].includes(o.toLowerCase())){if(!e.acceptAnyAttribute)throw Error(`Invalid attribute ${o} for component of type ${n.componentType}${indexRangeString(n)}`);i[o]=componentFromAttribute({value:n.props[o],originalComponentProps:s,componentInfoObjects:t}),delete n.props[o]}}for(let e in r){let n=r[e];n.createPrimitiveOfType&&"defaultPrimitiveValue"in n&&!(e in i)&&(i[e]=componentFromAttribute({attrObj:n,originalComponentProps:s,value:n.defaultPrimitiveValue.toString(),componentInfoObjects:t}))}n.attributes=i,void 0!==n.children&&createAttributesFromProps(n.children,t)}}function componentFromAttribute({attrObj:e,value:t,originalComponentProps:n,componentInfoObjects:r}){if("object"!=typeof t?t={rawString:t.toString()}:null===t&&(t={rawString:""}),e&&e.createComponentOfType){let a,i=t.rawString.trim().toLowerCase();if("true"===i&&void 0!==e.valueForTrue)a={componentType:e.createComponentOfType,state:{value:e.valueForTrue}};else if("false"===i&&void 0!==e.valueForFalse)a={componentType:e.createComponentOfType,state:{value:e.valueForFalse}};else if(r.isInheritedComponentType({inheritedComponentType:e.createComponentOfType,baseComponentType:"boolean"})&&["true","false"].includes(i))a={componentType:e.createComponentOfType,state:{value:"true"===i}};else{let n=t.childrenForComponent;n=n?JSON.parse(JSON.stringify(n)):[t.rawString],a={componentType:e.createComponentOfType,children:n},removeBlankStringChildren([a],r)}if(e.attributesForCreatedComponent||e.copyComponentAttributesForCreatedComponent){if(e.attributesForCreatedComponent?a.props=e.attributesForCreatedComponent:a.props={},e.copyComponentAttributesForCreatedComponent)for(let t of e.copyComponentAttributesForCreatedComponent)n[t]&&(a.props[t]=JSON.parse(JSON.stringify(n[t])));createAttributesFromProps([a],r)}let s={component:a};return e.ignoreFixed&&(s.ignoreFixed=!0),s}if(e&&e.createPrimitiveOfType){let n;if("boolean"===e.createPrimitiveOfType){n="true"===t.rawString.trim().toLowerCase()}else n="number"===e.createPrimitiveOfType?Number(t.rawString):"integer"===e.createPrimitiveOfType?Math.round(Number(t.rawString)):"stringArray"===e.createPrimitiveOfType?t.rawString.trim().split(/\s+/):"numberArray"===e.createPrimitiveOfType?t.rawString.trim().split(/\s+/).map(Number):t.rawString;return e.validationFunction&&(n=e.validationFunction(n)),{primitive:n}}if(e&&e.createTargetComponentNames){return{targetComponentNames:t.rawString.trim().split(/\s+/).map((e=>("$"===e[0]&&"$"!==e[1]&&"("===(e=e.slice(1))[0]&&")"===e[e.length-1]&&(e=e.slice(1,e.length-1)),{relativeName:e})))}}return t.childrenForComponent||(t.childrenForComponent=[t.rawString]),t}function findPreSugarIndsAndMarkFromSugar(e){let t=[];for(let n of e)if("object"==typeof n)if(void 0!==n.preSugarInd)t.push(n.preSugarInd);else if(n.doenetAttributes||(n.doenetAttributes={}),n.doenetAttributes.createdFromSugar=!0,n.children){let e=findPreSugarIndsAndMarkFromSugar(n.children);t.push(...e)}return t}function applyMacros(e,t){for(let n of e)if(n.children&&applyMacros(n.children,t),n.attributes)for(let e in n.attributes){let r=n.attributes[e];r.component?applyMacros([r.component],t):r.childrenForComponent&&applyMacros(r.childrenForComponent,t)}substituteMacros(e,t)}function substituteMacros(e,t){for(let n=0;n0&&e[n-1].range){let t=e[n-1].range;t.closeEnd?r+=t.closeEnd:t.selfCloseEnd&&(r+=t.selfCloseBegin)}throw Error(`${d.message}. At indices ${r}-${r+c}. Found: ${t}`)}l=d.newComponent,markCreatedFromMacro([l]),0===s.propArray.length&&(l.doenetAttributes.isPlainMacro=!0),o=[l];let m=1,h=i.substring(u+c);if(2===p){let r=i.slice(u+c).match(/^\s*\(/);if(!r){a=u+2;continue}let s=c+r[0].length,l=[],p=!1;i.length>u+s&&(p=!0,l.push(i.substring(u+s))),l.push(...e.slice(n+1));let d=createEvaluateIfFindMatchedClosingParens({componentsFromMacro:o,remainingComponents:l,includeFirstInRemaining:p,componentInfoObjects:t});if(!d.success){a=u+2;continue}o=d.componentsFromMacro,m=d.lastComponentIndMatched+1,p||m++,h=""}let f=[];u>0&&f.push(i.substring(0,u)),f.push(...o),h.length>0&&f.push(h),e.splice(n,m,...f),u>0&&n++;break}}}}function createComponentFromExtendedSource({sourceName:e,componentIndex:t,componentAttributes:n,propArray:r,subNames:a,componentInfoObjects:i}){let s={componentType:"copy",doenetAttributes:{target:e},attributes:{}};if(t){let e=[t];applyMacros(e,i),s.attributes.componentIndex={component:{componentType:"integer",children:e}}}if(a?.length>0){let e=[],t=[];for(let n of a)e.push(n.subName),void 0!==n.subNameComponentIndex&&(t.length0){let e=[t.join(" ")];applyMacros(e,i),s.attributes.sourceSubnamesComponentIndex={component:{componentType:"numberList",children:e}}}}let o=!1;if(n){o=!0;let e=createAttributesFromString(n,i);if(!e.success)return e;Object.assign(s.attributes,e.newAttributes),e.assignNames&&(s.props={assignNames:e.assignNames})}for(let e of r){if(o&&(s.doenetAttributes.createdFromMacro=!0,s={componentType:"extract",attributes:{},doenetAttributes:{},children:[s]}),s.attributes.prop={primitive:e.prop},e.propIndex){let t=[e.propIndex.join(" ")];applyMacros(t,i),s.attributes.propIndex={component:{componentType:"numberList",children:t}}}if(e.attributes){let t=createAttributesFromString(e.attributes,i);if(!t.success)return t;Object.assign(s.attributes,t.newAttributes),t.assignNames&&(s.props={assignNames:t.assignNames})}o=!0}return{success:!0,newComponent:s}}function createAttributesFromString(e,t){let n,r=``;try{n=parseAndCompile(r)}catch(e){return{success:!1,message:"Error in macro"}}createAttributesFromProps(n,t),markCreatedFromMacro(n),applyMacros(n,t);let a,i=n[0].attributes;if(i.prop||i.propIndex||i.componentIndex)return{success:!1,message:"Error in macro: macro cannot directly add attributes prop, propIndex, or componentIndex"};if(n[0].props)for(let e in n[0].props)if("assignnames"===e.toLowerCase()){if(a)return{success:!1,message:"Error in macro: cannot repeat assignNames"};a=n[0].props[e]}return{success:!0,newAttributes:i,assignNames:a}}function findFirstFullMacroInString(e){let t,n=0;for(;;){let r=e.substring(n).match(/(\$+)(.?)/);if(!r)return{success:!1};if(t=r[1].length,n+=r.index+t,t<=2){let r=!1,a=e.substring(n),i=0,s=findWordOrDelimitedGroup(a,r);"("===s.startDelim&&(r=!0,a=s.group,i=s.group.length);let o=buildSourcePieces(a,r);if(o.success){if(r){if(o.matchLength!==i)return{success:!1};o.matchLength+=2}return o.nDollarSigns=t,o.firstIndMatched=n-t,o.matchLength+=t,o}}}}function buildSourcePieces(e,t){let n=findWordOrDelimitedGroup(e,t),r=0;if(n.withPeriod||!n.word)return{success:!1};let a={sourceName:(n.withSlash?"/":"")+n.word};r+=n.matchLength,n=findWordOrDelimitedGroup(e=e.substring(n.matchLength),t),"["===n.startDelim&&(a.componentIndex=n.group,r+=n.matchLength,n=findWordOrDelimitedGroup(e=e.substring(n.matchLength),t));let i=[];for(;n.withSlash;){let a={subName:n.word};r+=n.matchLength,n=findWordOrDelimitedGroup(e=e.substring(n.matchLength),t),"["===n.startDelim&&(a.subNameComponentIndex=n.group,r+=n.matchLength,n=findWordOrDelimitedGroup(e=e.substring(n.matchLength),t)),i.push(a)}a.subNames=i,"{"===n.startDelim&&(a.componentAttributes=n.group,r+=n.matchLength,n=findWordOrDelimitedGroup(e=e.substring(n.matchLength),t));let s=[];for(;n.withPeriod;){let a={prop:n.word};r+=n.matchLength,n=findWordOrDelimitedGroup(e=e.substring(n.matchLength),t);let i=[];for(;"["===n.startDelim;)i.push(n.group),r+=n.matchLength,n=findWordOrDelimitedGroup(e=e.substring(n.matchLength),t);i.length>0&&(a.propIndex=i),"{"===n.startDelim&&(a.attributes=n.group,r+=n.matchLength,n=findWordOrDelimitedGroup(e=e.substring(n.matchLength),t)),s.push(a)}return a.propArray=s,a.matchLength=r,a.success=!0,a}function findWordOrDelimitedGroup(e,t=!1){let n,r=!1,a=!1;"."===e[0]&&"."!==e[1]&&(r=!0,e=e.substring(1)),t?r?n=/^[\w-]+/:("/"===e[0]&&e[1].match(/\w/)&&(a=!0,e=e.substring(1)),n=/^([\w\/-]|\.\.\/)+/):n=/^[a-zA-Z_]\w*/;let i=e.match(n);if(i)return{success:!0,withPeriod:r,withSlash:a,word:i[0],matchLength:i[0].length+(r?1:0)+(a?1:0)};if(r||a)return{success:!1};let s=[],o={"(":")","{":"}","[":"]"},l=Object.values(o),u=e[0],c=o[u];if(!c)return{success:!1};s.push(c);for(let t=1;t0?t[i]=s.substring(0,a.charInd):t=t.slice(0,i);let l=breakEmbeddedStringByCommas({childrenList:t});l.pieces.forEach((e=>applyMacros(e,r)));let u=l.pieces.map((e=>1===e.length&&"string"!=typeof e[0]?e[0]:{componentType:"math",doenetAttributes:{createdFromMacro:!0},children:e})),c=[{componentType:"evaluate",doenetAttributes:{createdFromMacro:!0},attributes:{function:{component:{componentType:"function",doenetAttributes:{createdFromMacro:!0},children:e}},input:{component:{componentType:"mathList",doenetAttributes:{createdFromMacro:!0},children:u}}}}];return o.length>0&&c.push(o),{success:!0,componentsFromMacro:c,lastComponentIndMatched:i}}function findFirstUnmatchedClosingParens(e){let t=0;for(let[n,r]of e.entries())if("string"==typeof r){let e=r;for(let r=0;r").replace(/</g,"<").replace(/$/g,"$").replace(/&/g,"&")}for(let[n,r]of e.entries())if("string"==typeof r)e[n]=t(r);else if(r.children&&decodeXMLEntities(r.children),r.attributes)for(let e in r.attributes){let n=r.attributes[e];n.component?decodeXMLEntities([n.component]):n.primitive?"string"==typeof n.primitive&&(n.primitive=t(n.primitive)):(n.childrenForComponent&&decodeXMLEntities(n.childrenForComponent),n.rawString&&(n.rawString=t(n.rawString)))}}function applySugar({serializedComponents:e,parentParametersFromSugar:t={},parentAttributes:n={},componentInfoObjects:r,parentUniqueId:a="",isAttributeComponent:i=!1}){for(let[s,o]of e.entries()){if("object"!=typeof o)continue;let e=o.componentType,l=r.allComponentClasses[e];if(!l)throw Error(`Unrecognized component type ${e}`);let u=a+"|"+e+s,c={};for(let e in o.attributes){let t=o.attributes[e];void 0!==t.primitive&&(c[e]=t.primitive)}if(o.children){let a={};if(!o.skipSugar)for(let[s,p]of l.returnSugarInstructions().entries()){let l=o.children.map((e=>"string"==typeof e?"s":"n")).join("");if(p.childrenRegex){let e=l.match(p.childrenRegex);if(!e||e[0].length!==o.children.length)continue}let d=deepClone(o.children),m=0;for(let e of d)"string"!=typeof e&&(e.preSugarInd=m,m++);let h=!1;o.doenetAttributes&&o.doenetAttributes.createdFromMacro&&(h=!0);let f=p.replacementFunction({matchedChildren:d,parentParametersFromSugar:t,parentAttributes:n,componentAttributes:c,uniqueId:u+"|sugar"+s,componentInfoObjects:r,isAttributeComponent:i,createdFromMacro:h});if(f.success){let t=f.newChildren,n=f.newAttributes,r=[],i=[];if(t&&(r=findPreSugarIndsAndMarkFromSugar(t)),n)for(let e in n){let t=n[e].component;t&&i.push(...findPreSugarIndsAndMarkFromSugar(t.children))}let s=[...r,...i];if(s.length!==m||!s.sort(((e,t)=>e-t)).every(((e,t)=>e===t)))throw Error(`Invalid sugar for ${e} as didn't return set of original components`);if(r.length>0){let t=[...r].sort(((e,t)=>e-t));if(!t.every(((e,t)=>e===r[t])))throw Error(`Invalid sugar for ${e} as didn't return original components in order`)}f.parametersForChildrenSugar&&Object.assign(a,f.parametersForChildrenSugar),o.children=t||[],n&&(o.attributes||(o.attributes={}),Object.assign(o.attributes,n))}}l.removeBlankStringChildrenPostSugar&&(o.children=o.children.filter((e=>"string"!=typeof e||/\S/.test(e)))),applySugar({serializedComponents:o.children,parentParametersFromSugar:a,parentAttributes:c,componentInfoObjects:r,parentUniqueId:u})}if(o.attributes)for(let e in o.attributes){let t=o.attributes[e];t.component&&applySugar({serializedComponents:[t.component],parentAttributes:c,componentInfoObjects:r,parentUniqueId:u,isAttributeComponent:!0})}}}function breakStringInPiecesBySpacesOrParens(e){if("string"!=typeof e)return{success:!1};let t=0,n=[];e=e.trim();let r=0;for(let a=0;a0&&n.push(t),r=a}t++}else if(")"===i){if(0===t)return{success:!1};if(1===t){let t=e.substring(r+1,a).trim();if(t.length>0){let e=breakStringInPiecesBySpacesOrParens(t);!0===e.success?n.push(e.pieces):n.push(t)}r=a+1}t--}else if(0===t&&i.match(/\s/)){let t=e.substring(r,a).trim();t.length>0&&n.push(t),r=a}}if(0!==t)return{success:!1};let a=e.substring(r,e.length).trim();return a.length>0&&n.push(a),{success:!0,pieces:n}}function countRegularComponentTypesInNamespace(e,t={}){for(let n of e)if("object"==typeof n){let e=n.componentType,r=t[e];void 0===r&&(r=0);let a=n.doenetAttributes;a?.isAttributeChild||a?.createdFromSugar||a?.createdFromMacro||(t[e]=++r),n.children&&!n.attributes?.newNamespace?.primitive&&(t=countRegularComponentTypesInNamespace(n.children,t))}return t}function renameAutonameBasedOnNewCounts(e,t={}){let n={...t};for(let t of e)if("object"==typeof t){let e=t.componentType,r=n[e];void 0===r&&(r=0);let a=t.doenetAttributes;if(!(a?.isAttributeChild||a?.createdFromSugar||a?.createdFromMacro)&&(n[e]=++r,t.componentName)){let n=t.componentName.lastIndexOf("/"),a=t.componentName.substring(n+1),i="_"+e.toLowerCase();a.substring(0,i.length)===i&&(t.componentName=t.componentName.substring(0,n+1)+i+r)}t.children&&!t.attributes?.newNamespace?.primitive&&(n=renameAutonameBasedOnNewCounts(t.children,n))}return n}function createComponentNames({serializedComponents:e,namespaceStack:t=[],componentInfoObjects:n,parentDoenetAttributes:r={},parentName:a,useOriginalNames:i=!1,attributesByTargetComponentName:s,indOffset:o=0,createNameContext:l="",initWithoutShadowingComposite:u=!1}){0===t.length&&t.push({namespace:"",componentCounts:{},namesUsed:{}});let c=t.length-1,p=t[c];for(let[r,d]of e.entries()){if("object"!=typeof d)continue;let e=d.componentType,m=n.allComponentClasses[e],h=d.doenetAttributes;void 0===h&&(h=d.doenetAttributes={});let f=d.attributes;f||(f=d.attributes={}),h.createNameFromComponentType&&(e=h.createNameFromComponentType);let y,g=h.prescribedName,b=h.assignNames,v=h.target,N=h.isAttributeChild||h.createdFromSugar||h.createdFromMacro||h.createUniqueName;(f.newNamespace?.primitive||i&&d.originalAttributes&&d.originalAttributes.newNamespace)&&(y=!0);let T=void 0!==g,C=d.props;if(void 0===C)C=d.props={};else for(let t in C){let n=t.toLowerCase();if("name"===n){if(void 0!==g)throw Error(`Cannot define name twice. Found in component of type ${e}${indexRangeString(d)}`);g=C[t],delete C[t]}else if("assignnames"===n){if(void 0!==b)throw Error(`Cannot define assignNames twice for a component. Found in component of type ${e}${indexRangeString(d)}`);{let n=breakStringInPiecesBySpacesOrParens(C[t]);if(!n.success)throw Error(`Invalid format for assignnames. Found in component of type ${e}${indexRangeString(d)}`);b=n.pieces,delete C[t]}}else if("target"===n){if(void 0!==v)throw Error(`Cannot define target twice for a component. Found in component of type ${e}${indexRangeString(d)}`);if("string"!=typeof C[t])throw Error(`Must specify value for target. Found in component of type ${e}${indexRangeString(d)}`);v=C[t].trim(),delete C[t]}}if(g){if(!T&&!h.createdFromSugar){if(!/[a-zA-Z]/.test(g.substring(0,1)))throw Error(`Invalid component name: ${g}. Component name must begin with a letter. Found in component of type ${e}${indexRangeString(d)}`);if(!/^[a-zA-Z0-9_\-]+$/.test(g))throw Error(`Invalid component name: ${g}. Component name can contain only letters, numbers, hyphens, and underscores. Found in component of type ${e}${indexRangeString(d)}`)}h.prescribedName=g}else if(N){let t=a+"|createUniqueName|";d.downstreamDependencies?t+=JSON.stringify(d.downstreamDependencies):t+=r+"|"+o+"|"+l,g=createUniqueName(e.toLowerCase(),t)}if(!b&&i&&d.originalDoenetAttributes&&d.originalDoenetAttributes.assignNames&&(b=d.originalDoenetAttributes.assignNames),b){if(!m.assignNamesToReplacements)throw Error(`Cannot assign names for component type ${e}${indexRangeString(d)}`);if(h.assignNames=b,!h.createUniqueAssignNames){let t=flattenDeep(b);if(!h.fromCopyTarget&&!h.fromCopyFromURI)for(let n of t){if(!/[a-zA-Z]/.test(n.substring(0,1)))throw Error(`All assigned names must begin with a letter. Found in component of type ${e}${indexRangeString(d)}`);if(!/^[a-zA-Z0-9_\-]+$/.test(n))throw Error(`Assigned names can contain only letters, numbers, hyphens, and underscores. Found in component of type ${e}${indexRangeString(d)}`)}if(t.length!==new Set(t).size)throw Error(`Duplicate assigned names. Found in component of type ${e}${indexRangeString(d)}`)}}y&&(f.newNamespace={primitive:y});let A=p.componentCounts[e];void 0===A&&(A=0),h.isAttributeChild||h.createdFromSugar||h.createdFromMacro||(p.componentCounts[e]=++A);let V="";for(let e=0;e<=c;e++)V+=t[e].namespace+"/";if(!g){if(i&&d.originalName){let e=d.originalName.lastIndexOf("/");g=d.originalName.substring(e+1)}g||(g="_"+e.toLowerCase()+A)}if(h.nameBecomesAssignNames){y&&(f.assignNewNamespaces={primitive:!0},delete f.newNamespace,y=!1),b=h.assignNames=[g],delete h.nameBecomesAssignNames;let e=a+"|createUniqueName|";h.createUniqueName=!0,delete h.prescribedName,d.downstreamDependencies?e+=JSON.stringify(d.downstreamDependencies):e+=r+"|"+o+"|"+l,g=createUniqueName("copy",e)}if(V+=g,d.componentName=V,g){if(g in p.namesUsed)throw Error(`Duplicate component name ${V}. Found in component of type ${e}${indexRangeString(d)}`);p.namesUsed[g]=!0}if(!y&&b)for(let t of flattenDeep(b)){if(t in p.namesUsed)throw Error(`Duplicate component name ${t} (from assignNames of ${V}). Found in component of type ${e}${indexRangeString(d)}`);p.namesUsed[t]=!0}if(d.doenetAttributes.createUniqueAssignNames&&d.originalName){let e=d.doenetAttributes.assignNames;e||(e=d.doenetAttributes.originalAssignNames);let n,r=V+"|createUniqueName|assignNames|",a="";if(y)a=V+"/",n=d.originalName+"/";else{for(let e=0;e<=c;e++)a+=t[e].namespace+"/";let e=d.originalName.lastIndexOf("/");n=d.originalName.slice(0,e+1)}let i=createNewAssignNamesAndrenameMatchingTargetNames({originalAssignNames:e,longNameIdBase:r,namespace:a,oldNamespace:n,attributesByTargetComponentName:s});b=d.doenetAttributes.assignNames=i}if(renameMatchingTargetNames(d,s),v){if(!m.acceptTarget)throw Error(`Component type ${e} does not accept a target attribute. Found in component ${V}${indexRangeString(d)}`);if(v.includes("|"))throw Error(`target cannot include |. Found in component of type ${e}${indexRangeString(d)}`);h.target=v,h.targetComponentName=convertComponentTarget({relativeName:v,oldAbsoluteName:h.targetComponentName,namespaceStack:t,acceptDoubleUnderscore:h.createdFromSugar||h.allowDoubleUnderscoreTarget})}for(let e in f){let n=f[e];if(n.targetComponentNames)for(let e of n.targetComponentNames)e.absoluteName=convertComponentTarget({relativeName:e.relativeName,oldAbsoluteName:e.absoluteName,namespaceStack:t,acceptDoubleUnderscore:h.createdFromSugar||h.allowDoubleUnderscoreTarget})}if(d.children)if(y||f.assignNewNamespaces?.primitive){let e={};b&&flattenDeep(b).forEach((t=>e[t]=!0));let r=d.children;if(h.nameFirstChildIndependently&&d.children.length>0){r=r.slice(1);let e={namespace:g,componentCounts:{},namesUsed:{}};t.push(e),createComponentNames({serializedComponents:[d.children[0]],namespaceStack:t,componentInfoObjects:n,parentDoenetAttributes:h,parentName:V,useOriginalNames:i,attributesByTargetComponentName:s}),t.pop()}let a={namespace:g,componentCounts:{},namesUsed:e};if(h.haveNewNamespaceOnlyFromShadow){let e=!0,o=[...r];for(;o.length>0;){let r=[];for(let t of o){if(Boolean(t.doenetAttributes?.ignoreParentNewNamespace)===e)break;r.push(t)}o.splice(0,r.length),e?t.push(a):u&&r.forEach((e=>e.doenetAttributes.createUniqueName=!0)),createComponentNames({serializedComponents:r,namespaceStack:t,componentInfoObjects:n,parentDoenetAttributes:h,parentName:V,useOriginalNames:i,attributesByTargetComponentName:s}),e&&t.pop(),e=!e}}else t.push(a),createComponentNames({serializedComponents:r,namespaceStack:t,componentInfoObjects:n,parentDoenetAttributes:h,parentName:V,useOriginalNames:i,attributesByTargetComponentName:s}),t.pop()}else{let e=d.children;if(h.nameFirstChildIndependently&&e.length>0){e=e.slice(1);let r=p.namesUsed,a=p.componentCounts;p.namesUsed={},p.componentCounts={},createComponentNames({serializedComponents:[d.children[0]],namespaceStack:t,componentInfoObjects:n,parentDoenetAttributes:h,parentName:V,useOriginalNames:i,attributesByTargetComponentName:s}),p.namesUsed=r,p.componentCounts=a}createComponentNames({serializedComponents:e,namespaceStack:t,componentInfoObjects:n,parentDoenetAttributes:h,parentName:V,useOriginalNames:i,attributesByTargetComponentName:s})}if(d.attributes)for(let e in d.attributes){let r=d.attributes[e];if(r.component){let a=r.component;a.doenetAttributes||(a.doenetAttributes={}),a.doenetAttributes.isAttributeChild=!0,r.ignoreFixed&&(a.doenetAttributes.ignoreParentFixed=!0),createComponentNames({serializedComponents:[a],namespaceStack:t,componentInfoObjects:n,parentDoenetAttributes:h,parentName:V,useOriginalNames:i,attributesByTargetComponentName:s,createNameContext:e})}else r.childrenForComponent&&createComponentNames({serializedComponents:r.childrenForComponent,namespaceStack:t,componentInfoObjects:n,parentDoenetAttributes:h,parentName:V,useOriginalNames:i,attributesByTargetComponentName:s,createNameContext:e})}}return e}function createNewAssignNamesAndrenameMatchingTargetNames({originalAssignNames:e,longNameIdBase:t,namespace:n,oldNamespace:r,attributesByTargetComponentName:a}){let i=[];for(let[s,o]of e.entries())if(Array.isArray(o)){let e=createNewAssignNamesAndrenameMatchingTargetNames({originalAssignNames:o,longNameIdBase:t+s+"_",namespace:n,oldNamespace:r,attributesByTargetComponentName:a});i.push(e)}else{let e=createUniqueName("fromAssignNames",t+s);i.push(e),renameMatchingTargetNames({componentName:n+e,originalName:r+o},a,!0)}return i}function convertComponentTarget({relativeName:e,oldAbsoluteName:t,namespaceStack:n,acceptDoubleUnderscore:r}){if(!t&&/__/.test(e)&&!r)throw Error("Invalid reference target: "+e);let a;if("/"===e.substring(0,1))a=e;else{let t=n.length-1;for(;"../"===e.substring(0,3);)e=e.substring(3),t--;t<0&&(t=0),a="";for(let e=0;e<=t;e++)a+=n[e].namespace+"/";a+=e}return a}function serializedComponentsReplacer(e,t){return t!=t?{objectType:"special-numeric",stringValue:"NaN"}:t===1/0?{objectType:"special-numeric",stringValue:"Infinity"}:t===-1/0?{objectType:"special-numeric",stringValue:"-Infinity"}:t}let nanInfinityReviver=function(e,t){if(t&&"special-numeric"===t.objectType){if("NaN"===t.stringValue)return NaN;if("Infinity"===t.stringValue)return 1/0;if("-Infinity"===t.stringValue)return-1/0}return t};function serializedComponentsReviver(e,t){return me$3.reviver(e,theModule.Subset.reviver(e,nanInfinityReviver(e,t)))}function processAssignNames({assignNames:e=[],assignNewNamespaces:t=!1,serializedComponents:n,parentName:r,parentCreatesNewNamespace:a,componentInfoObjects:i,indOffset:s=0,originalNamesAreConsistent:o=!1,shadowingComposite:l=!1}){let u=n.length;moveComponentNamesToOriginalNames(n);let c={},p=null;if(o){if(u>0){let e=n.filter((e=>"object"==typeof e))[0];if(e&&e.originalName){let t=e.originalName.lastIndexOf("/");p=e.originalName.substring(0,t)}}if(null!==p)for(let e of n)setTargetsOutsideNamespaceToAbsoluteAndRecordAllTargetComponentNames({namespace:p,components:[e],attributesByTargetComponentName:c})}else for(let e=0;e0&&t.originalName){let e=t.originalName.lastIndexOf("/");p=t.originalName.substring(0,e)}null!==p&&setTargetsOutsideNamespaceToAbsoluteAndRecordAllTargetComponentNames({namespace:p,components:[t],attributesByTargetComponentName:c})}}let d=[],m=0;for(let h=0;h0&&y.originalName)){let e=y.originalName.lastIndexOf("/");p=y.originalName.substring(0,e)}if(g)if(i.allComponentClasses[y.componentType].assignNamesSkipOver)g=[g];else if(y.attributes?.assignNamesSkip){let e=y.attributes.assignNamesSkip.primitive;if(e>0)for(let t=0;t({namespace:e,componentCounts:{},namesUsed:{}})));"/"!==e[0]&&c.splice(0,0,{componentCounts:{},namesUsed:{},namespace:""}),t.doenetAttributes||(t.doenetAttributes={}),t.attributes||(t.attributes={}),t.attributes.newNamespace?.primitive||s?u=!0:(u=!1,t.children&&markToCreateAllUniqueNames(t.children));for(let e in t.attributes){let n=t.attributes[e];n.component?markToCreateAllUniqueNames([n.component]):n.childrenForComponent&&markToCreateAllUniqueNames(n.childrenForComponent)}createComponentNames({serializedComponents:[t],namespaceStack:c,componentInfoObjects:a,parentName:e,useOriginalNames:u,attributesByTargetComponentName:i,indOffset:n,initWithoutShadowingComposite:!o})}function setTargetsOutsideNamespaceToAbsoluteAndRecordAllTargetComponentNames({namespace:e,components:t,attributesByTargetComponentName:n}){let r=e.length;for(let a of t)if("object"==typeof a){if(a.doenetAttributes&&a.doenetAttributes.target){let t=a.doenetAttributes.targetComponentName;void 0!==t&&(t.substring(0,r)!==e&&(a.doenetAttributes.target=t),n[t]||(n[t]=[]),n[t].push(a.doenetAttributes))}for(let t in a.attributes){let i=a.attributes[t];if(i.targetComponentNames)for(let t of i.targetComponentNames){let a=t.absoluteName;void 0!==a&&(a.substring(0,r)!==e&&(t.relativeName=a),n[a]||(n[a]=[]),n[a].push(t))}}if(a.children&&setTargetsOutsideNamespaceToAbsoluteAndRecordAllTargetComponentNames({namespace:e,components:a.children,attributesByTargetComponentName:n}),a.attributes)for(let t in a.attributes){let r=a.attributes[t];r.component?setTargetsOutsideNamespaceToAbsoluteAndRecordAllTargetComponentNames({namespace:e,components:[r.component],attributesByTargetComponentName:n}):r.childrenForComponent&&setTargetsOutsideNamespaceToAbsoluteAndRecordAllTargetComponentNames({namespace:e,components:r.childrenForComponent,attributesByTargetComponentName:n})}}}function renameMatchingTargetNames(e,t,n=!1){if(e.originalName&&t&&e.componentName!==e.originalName){if(t[e.originalName])for(let n of t[e.originalName])n.relativeName?(n.relativeName=e.componentName,n.absoluteName=e.componentName):(n.target=e.componentName,n.targetComponentName=e.componentName);if(n){let n=e.originalName+"/",r=n.length;for(let a in t)if(a.substring(0,r)===n){let n=a.substring(r);for(let r of t[a])r.relativeName?(r.relativeName=e.componentName+"/"+n,r.absoluteName=e.componentName+"/"+n):(r.target=e.componentName+"/"+n,r.targetComponentName=e.componentName+"/"+n)}}}}function moveComponentNamesToOriginalNames(e){for(let t of e)if(t.componentName&&(t.originalName=t.componentName,delete t.componentName),t.children&&moveComponentNamesToOriginalNames(t.children),t.attributes)for(let e in t.attributes){let n=t.attributes[e];n.component?moveComponentNamesToOriginalNames([n.component]):n.childrenForComponent&&moveComponentNamesToOriginalNames(n.childrenForComponent)}}function markToCreateAllUniqueNames(e){for(let t of e)if("object"==typeof t&&(t.doenetAttributes||(t.doenetAttributes={}),t.doenetAttributes.createUniqueName=!0,delete t.doenetAttributes.prescribedName,t.attributes?.newNamespace?.primitive||(t.doenetAttributes.assignNames?(t.doenetAttributes.createUniqueAssignNames=!0,t.doenetAttributes.originalAssignNames=t.doenetAttributes.assignNames,delete t.doenetAttributes.assignNames):t.originalDoenetAttributes&&t.originalDoenetAttributes.assignNames&&(t.doenetAttributes.createUniqueAssignNames=!0,t.doenetAttributes.originalAssignNames=t.originalDoenetAttributes.assignNames),t.children&&markToCreateAllUniqueNames(t.children)),t.attributes))for(let e in t.attributes){let n=t.attributes[e];n.component?markToCreateAllUniqueNames([n.component]):n.childrenForComponent&&markToCreateAllUniqueNames(n.childrenForComponent)}}function setTNamesToAbsolute(e){for(let t of e){if(t.doenetAttributes&&t.doenetAttributes.target){let e=t.doenetAttributes.targetComponentName;void 0!==e&&(t.doenetAttributes.target=e)}if(t.children&&setTNamesToAbsolute(t.children),t.attributes)for(let e in t.attributes){let n=t.attributes[e];n.component?setTNamesToAbsolute([n.component]):n.childrenForComponent&&setTNamesToAbsolute(n.childrenForComponent)}}}function restrictTNamesToNamespace({components:e,namespace:t,parentNamespace:n,parentIsCopy:r=!1,invalidateReferencesToBaseNamespace:a=!1}){void 0===n&&(n=t);let i=t.length;for(let s of e){if(s.doenetAttributes&&s.doenetAttributes.target){let e=s.doenetAttributes.target;if("/"===e[0]){if(e.substring(0,i)!==t){let n=t.split("/").slice(1),r=e.split("/").slice(1),a=!1,i=t+e.slice(1);for(;n.length>0&&n[0]===r[0];)n=n.slice(1),r=r.slice(1),a=!0;if(a)i=t+r.join("/");else{let n=t.split("/").slice(1);for(let t=1;tn){r&&t<=n&&a.push({begin:t,end:n,componentName:r}),s=!0;break}r&&o.indBegin>t&&a.push({begin:t,end:o.indBegin-1,componentName:r});let l=extractRangeIndexPieces({componentArray:e.slice(i+1),lastInd:o.indBegin,stopInd:o.indEnd,enclosingComponentName:o.componentName});i+=l.componentsConsumed+1,a.push(...l.rangePieces),t=o.indEnd+1}return!s&&Number.isFinite(n)&&n>=t&&a.push({begin:t,end:n,componentName:r}),{componentsConsumed:i,rangePieces:a}}function createStateProxyHandler(){return{get:function(e,t){let n=e[t];return void 0!==n&&(n=n.isArray&&(n.public||n.trackChanges)?new Proxy(n.value,createArrayProxyHandler({variable:t,nDimensions:n.nDimensions})):n.value),n},set:function(e,t,n){throw Error("Property "+t+" is read-only")},deleteProperty:function(e,t){throw Error("Property "+t+" is read-only")}}}function createArrayProxyHandler({variable:e,nDimensions:t,indicesSoFar:n=[]}){return{variable:e,nDimensions:t,indicesSoFar:n,get:function(e,n){if("then"===n&&e instanceof Promise)return t=>e.then.bind(e)((e=>t(null!==e&&"object"==typeof e?new Proxy(e,createArrayProxyHandler({variable:this.variable,nDimensions:this.nDimensions,indicesSoFar:this.indicesSoFar})):e)));let r=e[n];return null!==r&&"object"==typeof r&&t>1&&(r=new Proxy(r,createArrayProxyHandler({variable:this.variable,nDimensions:this.nDimensions-1,indicesSoFar:[...this.indicesSoFar,n]}))),r},set:function(e,t,n){throw Error("Property "+t+" is read-only")},deleteProperty:function(e,t){throw Error("Property "+t+" is read-only")}}}function postProcessCopy({serializedComponents:e,componentName:t,addShadowDependencies:n=!0,markAsPrimaryShadow:r=!1,uniqueIdentifiersUsed:a=[],identifierPrefix:i="",unlinkExternalCopies:s=!1,copiesByTargetComponentName:o={},componentNamesFound:l=[],assignNamesFound:u=[],activeAliases:c=[],init:p=!0}){for(let d in e){let m,h=e[d];if("object"==typeof h){if(h.originalName){if(s){if(l.push(h.originalName),h.originalDoenetAttributes&&h.originalDoenetAttributes.assignNames){let e;if(h.attributes.newNamespace?.primitive)e=h.originalName;else{let t=h.originalName.lastIndexOf("/");e=h.originalName.substring(0,t)}for(let t of h.originalDoenetAttributes.assignNames)l.push(e+"/"+t),u.push(e+"/"+t)}h.attributes&&(h.attributes.alias&&c.push(h.attributes.alias.primitive),h.attributes.indexAlias&&c.push(h.attributes.indexAlias.primitive))}if(m=i+h.originalName+"|shadow",!h.originalNameFromSerializedComponent)if(n){let e={[h.originalName]:[{dependencyType:"referenceShadow",compositeName:t}]};if(p&&(e[h.originalName][0].firstLevelReplacement=!0),r&&(e[h.originalName][0].isPrimaryShadow=!0),h.state){let t=Object.keys(h.state);e[h.originalName].downstreamStateVariables=t,e[h.originalName].upstreamStateVariables=t}h.downstreamDependencies=e}else h.unlinkedCopySource=h.originalName}else m=i+h.componentType+"|shadowUnnamed";if("copy"===h.componentType&&s){let e=h.doenetAttributes.targetComponentName;if(e)c.includes(h.doenetAttributes.target)?h.doenetAttributes.targetComponentName=h.doenetAttributes.target:(void 0===o[e]&&(o[e]=[]),o[e].push(h));else if(!h.attributes.uri)throw Error("we need to create a targetComponentName here, then.")}h.uniqueIdentifier=getUniqueIdentifierFromBase(m,a)}}for(let p in e){let d=e[p];if("object"==typeof d){postProcessCopy({serializedComponents:d.children,componentName:t,addShadowDependencies:n,markAsPrimaryShadow:r,uniqueIdentifiersUsed:a,identifierPrefix:i,unlinkExternalCopies:s,copiesByTargetComponentName:o,componentNamesFound:l,assignNamesFound:u,activeAliases:[...c],init:!1});for(let e in d.attributes){let p=d.attributes[e];p.component&&(p.component=postProcessCopy({serializedComponents:[p.component],componentName:t,addShadowDependencies:n,markAsPrimaryShadow:r,uniqueIdentifiersUsed:a,identifierPrefix:i,unlinkExternalCopies:s,copiesByTargetComponentName:o,componentNamesFound:l,assignNamesFound:u,activeAliases:[...c],init:!1})[0])}d.replacements&&postProcessCopy({serializedComponents:d.replacements,componentName:t,addShadowDependencies:n,markAsPrimaryShadow:r,uniqueIdentifiersUsed:a,identifierPrefix:i,unlinkExternalCopies:s,copiesByTargetComponentName:o,componentNamesFound:l,assignNamesFound:u,activeAliases:[...c],init:!1})}}if(p&&s)for(let e in o)if(!l.includes(e)){let t=!1;for(let n of u){let r=n+"/",a=r.length;if(e.substring(0,a)===r){t=!0;break}}if(!t)for(let t of o[e])t.attributes||(t.attributes={}),t.attributes.link={primitive:!1},t.doenetAttributes.target=t.doenetAttributes.targetComponentName}return e}function convertAttributesForComponentType({attributes:e,componentType:t,componentInfoObjects:n,compositeAttributesObj:r={},compositeCreatesNewNamespace:a,flags:i}){let s=n.allComponentClasses[t],o=s.createAttributesObject(),l={};for(let e in o)l[e.toLowerCase()]=e;let u={};for(let t in e){if(t in r&&!r[t].leaveRaw)continue;let i=l[t.toLowerCase()],c=o[i];if(c){if(i in u)throw Error(`Cannot repeat prop ${i}`);if(u[i]=componentFromAttribute({attrObj:c,value:JSON.parse(JSON.stringify(e[t])),componentInfoObjects:n}),u[i].component?.children){let e=[u[i].component];if(applyMacros(e,n),removeBlankStringChildren(e,n),applySugar({serializedComponents:e,componentInfoObjects:n,isAttributeComponent:!0}),a)for(let e of u[i].component.children)if("copy"===e.componentType){let t=e.doenetAttributes.target;/[a-zA-Z_]/.test(t[0])&&(e.doenetAttributes.target="../"+t)}}}else s.acceptAnyAttribute&&(u[t]=JSON.parse(JSON.stringify(e[t])))}return u}async function verifyReplacementsMatchSpecifiedType({component:e,replacements:t,replacementChanges:n,assignNames:r,workspace:a={},componentInfoObjects:i,compositeAttributesObj:s,flags:o}){if(!e.attributes.createComponentOfType?.primitive&&!e.sharedParameters.compositesMustHaveAReplacement)return{replacements:t,replacementChanges:n};let l,u=e.replacementsToWithhold;if(n){l=e.replacements.map((e=>e.componentType));for(let e of n)if("add"===e.changeType){if(void 0!==e.replacementsToWithhold&&(u=e.replacementsToWithhold),!e.changeTopLevelReplacements)continue;if(e.serializedReplacements){let t=e.numberReplacementsToReplace;t>0||(t=0);let n=e.firstReplacementInd,r=e.serializedReplacements.map((e=>e.componentType));l.splice(n,t,...r)}}else if("delete"===e.changeType){if(void 0!==e.replacementsToWithhold&&(u=e.replacementsToWithhold),e.changeTopLevelReplacements){let t=e.firstReplacementInd,n=e.numberReplacementsToDelete;l.splice(t,n)}}else"changeReplacementsToWithhold"===e.changeType&&void 0!==e.replacementsToWithhold&&(u=e.replacementsToWithhold)}else i.isInheritedComponentType({inheritedComponentType:e.componentType,baseComponentType:"template"})&&(t=t.filter((e=>e.componentType||e.trim().length>0))),l=t.map((e=>e.componentType)),1===l.length&&"externalContent"===l[0]&&(l=t[0].children.filter((e=>e.componentType||e.trim().length>0)).map((e=>e.componentType)));if(u>0&&(l=l.slice(0,l.length-u)),!e.attributes.createComponentOfType?.primitive&&e.sharedParameters.compositesMustHaveAReplacement&&l.length>0)return{replacements:t,replacementChanges:n};let c=e.attributes.createComponentOfType?.primitive,p=await e.stateValues.nComponentsSpecified;if(!c){if(c=e.sharedParameters.compositesDefaultReplacementType,!c)throw Error("A component class specified descendantCompositesMustHaveAReplacement but didn't specify descendantCompositesDefaultReplacementType");p=1}if(c=i.componentTypeLowerCaseMapping[c.toLowerCase()],l.length!==p||!l.every((e=>e===c))){if(1===t?.length&&i.isInheritedComponentType({inheritedComponentType:t[0].componentType,baseComponentType:"template"}))return t[0].attributes||(t[0].attributes={}),t[0].attributes.createComponentOfType={primitive:c},t[0].attributes.nComponents={primitive:p},{replacements:t,replacementChanges:n};let d,m=l.length===p&&!(u>0)&&a.sourceNames?.length===p;m&&n&&(1===n.length&&n[0].numberReplacementsToReplace===p?d=n[0].serializedReplacements:m=!1),m?d||(d=t):(a.numReplacementsBySource=[],a.numNonStringReplacementsBySource=[],a.propVariablesCopiedBySource=[],a.sourceNames=[],a.uniqueIdentifiersUsedBySource={},a.uniqueIdentifiersUsedBySource[0]=[]);let h=e.attributes.newNamespace?.primitive;t=[];for(let n=0;n"string"!=typeof e)).length),n){n=[],e.replacementsToWithhold>0&&n.push({changeType:"changeReplacementsToWithhold",replacementsToWithhold:0});let r=0;e.replacements&&(r=e.replacements.length),n.push({changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:0,numberReplacementsToReplace:r,serializedReplacements:t})}}return{replacements:t,replacementChanges:n}}function gatherDescendants({ancestor:e,descendantTypes:t,recurseToMatchedChildren:n=!0,useReplacementsForComposites:r=!1,includeNonActiveChildren:a=!1,skipOverAdapters:i=!1,ignoreReplacementsOfMatchedComposites:s=!1,ignoreReplacementsOfEncounteredComposites:o=!1,init:l=!0,componentInfoObjects:u}){let c=e=>t.some((t=>u.isInheritedComponentType({inheritedComponentType:e.componentType,baseComponentType:t}))),p=[];if(r&&u.isInheritedComponentType({inheritedComponentType:e.componentType,baseComponentType:"_composite"}))l&&p.push(...replacementsForComposites({composite:e,componentInfoObjects:u,includeComposites:a}).filter((e=>"object"==typeof e)));else for(let t of e.allChildrenOrdered){let n,r=e.allChildren[t],s=!1,o=!1;if(r)n=r.component,n.adaptedFrom&&(o=!0),e.activeChildren.includes(n)&&(s=!0);else for(let r of e.activeChildren){if(r.placeholderInd===t){n=r,s=!0,"string"==typeof t&&"adapt"===t.substring(t.length-5,t.length)&&(o=!0);break}if(r.adaptedFrom&&achild.adaptedFrom.placeholderInd===t){n=r.adaptedFrom;break}}n&&(o&&i?p.includes(n.adaptedFrom)||p.push(n.adaptedFrom):(s||a)&&p.push(n))}if(s||o){let e=[];for(let t of p){let n=c(t);o&&!n&&(n=!("copy"===t.componentType&&t.doenetAttributes.copiedURI)),n&&u.isInheritedComponentType({inheritedComponentType:t.componentType,baseComponentType:"_composite"})&&(e=[...e,...replacementsForComposites({composite:t,componentInfoObjects:u,includeComposites:!0}).filter((e=>"object"==typeof e)).map((e=>e.componentName?e.componentName:e.placeholderInd))])}e.length>0&&(p=p.filter((t=>!(e.includes(t.componentName)||e.includes(t.placeholderInd)))))}let d=[];for(let e of p){let l=c(e);if(l&&d.push({componentName:e.componentName?e.componentName:e.placeholderInd,componentType:e.componentType}),(!l||n)&&void 0===e.placeholderInd){let l=gatherDescendants({ancestor:e,descendantTypes:t,recurseToMatchedChildren:n,useReplacementsForComposites:r,includeNonActiveChildren:a,skipOverAdapters:i,ignoreReplacementsOfMatchedComposites:s,ignoreReplacementsOfEncounteredComposites:o,init:!1,componentInfoObjects:u});d.push(...l)}}return d}function replacementsForComposites({composite:e,includeComposites:t=!1,componentInfoObjects:n}){let r=[];if(e.replacements){let a;if(e.replacementsToWithhold){let t=e.replacements.length-e.replacementsToWithhold;a=e.replacements.slice(0,t)}else a=e.replacements;for(let e of a)n.isInheritedComponentType({inheritedComponentType:e.componentType,baseComponentType:"_composite"})?(t&&r.push(e),r.push(...replacementsForComposites({composite:e,componentInfoObjects:n,includeComposites:t}))):r.push(e)}return r}function ancestorsIncludingComposites(e,t){if(void 0===e.ancestors||0===e.ancestors.length)return[];let n=[e.ancestors[0].componentName],r=t[e.ancestors[0].componentName];if(r&&n.push(...ancestorsIncludingComposites(r,t)),e.replacementOf){n.push(e.replacementOf.componentName);let r=ancestorsIncludingComposites(e.replacementOf,t);for(let e of r)n.includes(e)||n.push(e)}return n}const dependencyTypeArray=[];class DependencyHandler{constructor({_components:e,componentInfoObjects:t,core:n}){this.upstreamDependencies={},this.downstreamDependencies={},this.switchDependencies={},this.circularCheckPassed={},this.circularResolveBlockedCheckPassed={},this.dependencyTypes={},dependencyTypeArray.forEach((e=>this.dependencyTypes[e.dependencyType]=e)),this.core=n,this._components=e,this.componentInfoObjects=t,this.updateTriggers={descendantDependenciesByAncestor:{},ancestorDependenciesByPotentialAncestor:{},replacementDependenciesByComposite:{},childDependenciesByParent:{},parentDependenciesByParent:{},dependenciesMissingComponentBySpecifiedName:{},dependenciesBasedOnDependenciesOfStateVariables:{},primaryShadowDependencies:{}},this.resolveBlockers={neededToResolve:{},resolveBlockedBy:{}}}async setUpComponentDependencies(e){this.downstreamDependencies[e.componentName]&&this.deleteAllDownstreamDependencies({component:e}),this.downstreamDependencies[e.componentName]={},this.upstreamDependencies[e.componentName]||(this.upstreamDependencies[e.componentName]={});let t=[],n=[];for(let r in e.state)e.state[r].isArrayEntry||e.state[r].isAlias||n.includes(r)||(t.push(r),e.state[r].additionalStateVariablesDefined&&n.push(...e.state[r].additionalStateVariablesDefined));for(let n of t){let t=[n];e.state[n].additionalStateVariablesDefined&&t.push(...e.state[n].additionalStateVariablesDefined),await this.setUpStateVariableDependencies({component:e,stateVariable:n,allStateVariablesAffected:t})}}async setUpStateVariableDependencies({component:e,stateVariable:t,allStateVariablesAffected:n}){let r,a=e.state[t];a.stateVariablesDeterminingDependencies?(r={},a.stateVariablesDeterminingDependencies&&(r.__determine_dependencies={dependencyType:"determineDependencies",variableNames:a.stateVariablesDeterminingDependencies})):r=await a.returnDependencies({componentInfoObjects:this.componentInfoObjects,sharedParameters:e.sharedParameters});for(let a in r){let i=r[a];if(!(i.dependencyType in this.dependencyTypes))throw Error(`Unrecognized dependency type ${i.dependencyType} for ${a} of ${t} of ${e.componentName}`);let s=new this.dependencyTypes[i.dependencyType]({component:e,stateVariable:t,allStateVariablesAffected:n,dependencyName:a,dependencyDefinition:i,dependencyHandler:this,expandComposites:!1,forceExpandComposites:!1});await s.initialize(),s.checkForCircular()}}deleteAllDownstreamDependencies({component:e,stateVariables:t="__all__"}){let n,r=e.componentName;n="__all__"===t?Object.keys(this.downstreamDependencies[r]):t;for(let e of n){let t=this.downstreamDependencies[r][e];for(let e in t)t[e].deleteDependency();delete this.downstreamDependencies[r][e]}0!==Object.keys(this.downstreamDependencies[r]).length||this.components[r]||delete this.downstreamDependencies[r]}async deleteAllUpstreamDependencies({component:e,stateVariables:t="__all__",completelyDelete:n=!1}){let r,a=e.componentName;r="__all__"===t?Object.keys(this.upstreamDependencies[a]):t;for(let e of r){if(this.upstreamDependencies[a][e])for(let t of[...this.upstreamDependencies[a][e]])if(n){for(let e of t.upstreamVariableNames)this._components[t.upstreamComponentName].state[e].initiallyResolved&&await this.core.markStateVariableAndUpstreamDependentsStale({component:this.components[t.upstreamComponentName],varName:e});t.deleteDependency()}else await t.removeDownstreamComponent({indexToRemove:t.downstreamComponentNames.indexOf(a)});delete this.upstreamDependencies[a][e]}0!==Object.keys(this.upstreamDependencies[a]).length||this._components[a]||delete this.upstreamDependencies[a]}async addBlockersFromChangedStateVariableDependencies({componentName:e,stateVariables:t}){let n=this.updateTriggers.dependenciesBasedOnDependenciesOfStateVariables[e];if(n)for(let r of t){let t=n[r];if(t)for(let n of t)if(n.gettingValue){let t=n.varsWithUpdatedDeps[e];t||(t=n.varsWithUpdatedDeps[e]=[]),t.includes(r)||t.push(r)}else for(let e of n.upstreamVariableNames)await this.addBlocker({blockerComponentName:n.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:n.dependencyName,componentNameBlocked:n.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e})}}async addBlockersFromChangedActiveChildren({parent:e}){if(await this.collateCountersAndPropagateToAncestors(e),this.updateTriggers.childDependenciesByParent[e.componentName])for(let t of this.updateTriggers.childDependenciesByParent[e.componentName]){for(let e of t.upstreamVariableNames)await this.addBlocker({blockerComponentName:t.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:t.dependencyName,componentNameBlocked:t.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});await this.addBlockersFromChangedStateVariableDependencies({componentName:t.upstreamComponentName,stateVariables:t.upstreamVariableNames})}if(e.ancestors){if(this.updateTriggers.parentDependenciesByParent[e.componentName])for(let t of this.updateTriggers.parentDependenciesByParent[e.componentName]){for(let e of t.upstreamVariableNames)await this.addBlocker({blockerComponentName:t.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:t.dependencyName,componentNameBlocked:t.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});await this.addBlockersFromChangedStateVariableDependencies({componentName:t.upstreamComponentName,stateVariables:t.upstreamVariableNames})}for(let t of[e.componentName,...ancestorsIncludingComposites(e,this.components)])await this.addDescendantBlockersToAncestor(t);if(this.updateTriggers.ancestorDependenciesByPotentialAncestor[e.componentName])for(let t of this.updateTriggers.ancestorDependenciesByPotentialAncestor[e.componentName]){for(let e of t.upstreamVariableNames)await this.addBlocker({blockerComponentName:t.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:t.dependencyName,componentNameBlocked:t.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});await this.addBlockersFromChangedStateVariableDependencies({componentName:t.upstreamComponentName,stateVariables:t.upstreamVariableNames})}}}async resolveBlockersFromChangedActiveChildren(e,t=!1){if(await this.collateCountersAndPropagateToAncestors(e),this.updateTriggers.childDependenciesByParent[e.componentName])for(let n of this.updateTriggers.childDependenciesByParent[e.componentName])await this.resolveIfReady({componentName:n.upstreamComponentName,type:"recalculateDownstreamComponents",stateVariable:n.representativeStateVariable,dependency:n.dependencyName,force:t});if(e.ancestors){if(this.updateTriggers.parentDependenciesByParent[e.componentName])for(let n of this.updateTriggers.parentDependenciesByParent[e.componentName])await this.resolveIfReady({componentName:n.upstreamComponentName,type:"recalculateDownstreamComponents",stateVariable:n.representativeStateVariable,dependency:n.dependencyName,force:t});for(let n of[e.componentName,...ancestorsIncludingComposites(e,this.components)])await this.resolveDescendantBlockersToAncestor(n,t);if(this.updateTriggers.ancestorDependenciesByPotentialAncestor[e.componentName])for(let n of this.updateTriggers.ancestorDependenciesByPotentialAncestor[e.componentName])await this.resolveIfReady({componentName:n.upstreamComponentName,type:"recalculateDownstreamComponents",stateVariable:n.representativeStateVariable,dependency:n.dependencyName,force:t})}}async addDescendantBlockersToAncestor(e){if(this.updateTriggers.descendantDependenciesByAncestor[e])for(let t of this.updateTriggers.descendantDependenciesByAncestor[e]){for(let e of t.upstreamVariableNames)await this.addBlocker({blockerComponentName:t.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:t.dependencyName,componentNameBlocked:t.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});await this.addBlockersFromChangedStateVariableDependencies({componentName:t.upstreamComponentName,stateVariables:t.upstreamVariableNames})}}async resolveDescendantBlockersToAncestor(e,t=!1){if(this.updateTriggers.descendantDependenciesByAncestor[e])for(let n of this.updateTriggers.descendantDependenciesByAncestor[e])await this.resolveIfReady({componentName:n.upstreamComponentName,type:"recalculateDownstreamComponents",stateVariable:n.representativeStateVariable,dependency:n.dependencyName,force:t})}async addBlockersFromChangedReplacements(e){if(this.updateTriggers.replacementDependenciesByComposite[e.componentName])for(let t of this.updateTriggers.replacementDependenciesByComposite[e.componentName])for(let e of t.upstreamVariableNames)await this.addBlocker({blockerComponentName:t.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:t.dependencyName,componentNameBlocked:t.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});for(let t of[e.componentName,...ancestorsIncludingComposites(e,this.components)])await this.addDescendantBlockersToAncestor(t)}checkForCircularDependency({componentName:e,varName:t,previouslyVisited:n=[]}){let r=e+":"+t;if(n.includes(r)){console.log("found circular",r,n);let e,t=/^(.*):/,a=n.map((e=>e.match(t)[1])),i=a.filter((e=>"__"!==e.slice(0,2))).reduce(((e,t)=>e.includes(t)?e:[...e,t]),[]);throw 0===i.length&&(i=[a[0]]),1===i.length?e=i[0]:2===i.length?e=i.join(" and "):(i[i.length-2]=i.slice(i.length-2).join(", and "),i.pop(),e=i.join(", ")),Error(`Circular dependency involving ${e}`)}if(n=[...n,r],!this.circularCheckPassed[r]&&(this.circularCheckPassed[r]=!0,e in this.downstreamDependencies)){let r=this.downstreamDependencies[e][t];for(let e in r){let t=r[e],a=t.downstreamComponentNames;if(!a)continue;let i=t.mappedDownstreamVariableNamesByComponent;if(i)for(let[e,t]of a.entries()){let r=i[e];for(let e of r)this.checkForCircularDependency({componentName:t,varName:e,previouslyVisited:n})}}}}resetCircularCheckPassed(e,t){let n=e+":"+t;if(this.circularCheckPassed[n]){delete this.circularCheckPassed[n];let r=this.upstreamDependencies[e][t];if(r)for(let e of r)for(let t of e.upstreamVariableNames)"__identity"!==t&&this.resetCircularCheckPassed(e.upstreamComponentName,t)}}async updateDependencies({componentName:e,stateVariable:t,dependency:n}){let r=this._components[e],a=r.state[t],i=[t];a.additionalStateVariablesDefined&&i.push(...a.additionalStateVariablesDefined);let s,o=this.downstreamDependencies[e][t].__determine_dependencies;if(o){let t=!0;if(o.originalDownstreamVariableNames.length>0)for(let[r,a]of o.downstreamComponentNames.entries()){let s=this._components[a];for(let l of o.mappedDownstreamVariableNamesByComponent[r]){let r=s.state[l].isResolved;if(!r){r=(await this.resolveItem({componentName:a,type:"stateVariable",stateVariable:l})).success}if(!r){t=!1;for(let t of i)await this.addBlocker({blockerComponentName:a,blockerType:"stateVariable",blockerStateVariable:l,componentNameBlocked:e,typeBlocked:"determineDependencies",stateVariableBlocked:t,dependencyBlocked:n})}}}if(!t)return{success:!1};s=await o.getValue()}else s={changes:{},value:{stateValues:{}}};if(0===Object.keys(s.changes).length&&void 0!==a._previousValue)return{success:!0};let l={stateValues:Object.assign({},s.value.stateValues),componentInfoObjects:this.componentInfoObjects,sharedParameters:r.sharedParameters},u=await a.returnDependencies(l);a.stateVariablesDeterminingDependencies&&(u.__determine_dependencies={dependencyType:"determineDependencies",variableNames:a.stateVariablesDeterminingDependencies});let c=await this.replaceDependenciesIfChanged({component:r,stateVariable:t,newDependencies:u,allStateVariablesAffected:i});if(!c.changedDependency&&!l.changedDependency)return{success:!0};for(let e of c.newlyCreatedDependencies)e.checkForCircular();for(let e of i)this.checkForCircularDependency({componentName:r.componentName,varName:e}),r.state[e].forceRecalculation=!0;a.initiallyResolved&&await this.core.markStateVariableAndUpstreamDependentsStale({component:r,varName:t});for(let e of i)r.state[e].initiallyResolved&&this.recordActualChangeInUpstreamDependencies({component:r,varName:e});return await this.addBlockersFromChangedStateVariableDependencies({componentName:e,stateVariables:i}),{success:!0}}async replaceDependenciesIfChanged({component:e,stateVariable:t,newDependencies:n,allStateVariablesAffected:r}){let a=this.downstreamDependencies[e.componentName][t],i=!1,s=[];for(let e in a)e in n||(i=!0,a[e].deleteDependency());for(let o in n)if(o in a){if(!deepCompare(n[o],a[o].definition)){i=!0,a[o].deleteDependency();let l=n[o],u=new this.dependencyTypes[l.dependencyType]({component:e,stateVariable:t,allStateVariablesAffected:r,dependencyName:o,dependencyDefinition:l,dependencyHandler:this});await u.initialize(),s.push(u)}}else{i=!0;let a=n[o],l=new this.dependencyTypes[a.dependencyType]({component:e,stateVariable:t,allStateVariablesAffected:r,dependencyName:o,dependencyDefinition:a,dependencyHandler:this});await l.initialize(),s.push(l)}return{changedDependency:i,newlyCreatedDependencies:s}}async checkForDependenciesOnNewComponent(e){let t=[],n={};if(this.updateTriggers.dependenciesMissingComponentBySpecifiedName[e]){for(let r of this.updateTriggers.dependenciesMissingComponentBySpecifiedName[e]){let a=this._components[r.upstreamComponentName];if(!a)continue;let i=!0;for(let e of r.upstreamVariableNames)if(!(e in a.state)){i=!1;break}if(i){for(let e of r.upstreamVariableNames){a.state[e].initiallyResolved&&(n[r.upstreamComponentName]&&n[r.upstreamComponentName][e]||t.push({componentName:r.upstreamComponentName,varName:e}))}for(let t of r.upstreamVariableNames)this.deleteFromNeededToResolve({componentNameBlocked:r.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:t,dependencyBlocked:r.dependencyName,blockerComponentName:e,blockerType:"componentIdentity"});if((await this.resolveIfReady({componentName:r.upstreamComponentName,type:"recalculateDownstreamComponents",stateVariable:r.representativeStateVariable,dependency:r.dependencyName,expandComposites:!1,recurseUpstream:!0})).success)for(let e of r.upstreamVariableNames)a.state[e].initiallyResolved||(n[r.upstreamComponentName]||(n[r.upstreamComponentName]={}),n[r.upstreamComponentName][e]=!0);else for(let e of r.upstreamVariableNames)await this.addBlocker({blockerComponentName:r.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:r.dependencyName,componentNameBlocked:r.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e})}}delete this.updateTriggers.dependenciesMissingComponentBySpecifiedName[e]}return t}async getStateVariableDependencyValues({component:e,stateVariable:t}){let n={},r={},a={},i=this.downstreamDependencies[e.componentName][t];for(let e in i){let{value:t,changes:s,usedDefault:o}=await i[e].getValue();n[e]=t,Object.keys(s).length>0&&(r[e]=s),o&&(a[e]=o)}return{dependencyValues:n,changes:r,usedDefault:a}}recordActualChangeInUpstreamDependencies({component:e,varName:t,changes:n}){let r=e.componentName,a=this.upstreamDependencies[r][t];if(a)for(let i of a)if(i.valuesChanged){let a=i.downstreamComponentNames.indexOf(r),s=i.valuesChanged[a][t];if(!s&&e.stateVarAliases)for(let n in e.stateVarAliases)e.stateVarAliases[n]===t&&n in upValuesChangedSub&&(s=upValuesChangedSub[n]);if(!s){if(!e.state[t].isArrayEntry)throw Error(`Something is wrong, as a variable ${t} of ${e.componentName} actually changed, but wasn't marked with a potential change`);s=upValuesChangedSub[t]={changed:{}}}e.state[t]&&e.state[t].isArray?(void 0===s.changed?s.changed={arrayKeysChanged:{}}:!0===s.changed&&(s.changed={allArrayKeysChanged:!0,arraySizeChanged:!0,arrayKeysChanged:{}}),n&&(n.allArrayKeysChanged&&(s.changed.allArrayKeysChanged=!0),n.arraySizeChanged&&(s.changed.arraySizeChanged=!0),Object.assign(s.changed.arrayKeysChanged,n.arrayKeysChanged))):s.changed=!0}}async collateCountersAndPropagateToAncestors(e){let t=Object.keys(e.counters);for(let n of e.allChildrenOrdered){let e=this._components[n];if(e)for(let n in e.counters)t.includes(n)||t.push(n)}let n=!1;for(let r of t){let t=e.counters[r];t||(t=e.counters[r]={dependencies:[],componentList:[]});let a=[];t.dependencies.length>0&&a.push(e.componentName);for(let t of e.allChildrenOrdered){let e=this._components[t];if(e){let t=e.counters[r];t&&a.push(...t.componentList)}}(a.length!==t.componentList.length||t.componentList.some(((e,t)=>e!=a[t])))&&(n=!0,t.componentList=a)}if(!n)return{foundChange:!1};if(!e.ancestors[0]){for(let n of t){let t=e.counters[n];for(let[e,r]of t.componentList.entries()){let t=this._components[r],a=t.counters[n];a.value=e+1;for(let e of a.dependencies)if(t.state[e.representativeStateVariable].initiallyResolved){await this.core.markStateVariableAndUpstreamDependentsStale({component:t,varName:e.representativeStateVariable});for(let n of e.upstreamVariableNames)t.state[n].forceRecalculation=!0,this.recordActualChangeInUpstreamDependencies({component:t,varName:n})}}}return{foundChange:!0,finishedPropagation:!0}}let r=this._components[e.ancestors[0].componentName];if(!r||!r.allChildrenOrdered.includes(e.componentName))return{foundChange:!0,finishedPropagation:!1};let a=await this.collateCountersAndPropagateToAncestors(r);return a.foundChange||console.error(`we found a change in propagating counters for ${e.componentName}, but no change for ancestors!`),{foundChange:!0,finishedPropagation:a.finishedPropagation}}getNeededToResolve({componentName:e,type:t,stateVariable:n,dependency:r}){let a=this.resolveBlockers.neededToResolve[e];a||(a=this.resolveBlockers.neededToResolve[e]={});let i=a[t];if(i||(i=a[t]={}),n){let e=i;if(i=e[n],i||(i=e[n]={}),r){let e=i;i=e[r],i||(i=e[r]={})}}return i}deleteFromNeededToResolve({componentNameBlocked:e,typeBlocked:t,stateVariableBlocked:n,dependencyBlocked:r,blockerType:a,blockerCode:i,deleteFromReciprocal:s=!0}){let o=e;n&&(o+="|"+n,r&&(o+="|"+r));let l=function(e){if(a){if(e[a])if(i){let n=e[a].indexOf(i);if(-1!==n&&e[a].splice(n,1),0===e[a].length&&delete e[a],s){let[e,n,r]=i.split("|");this.deleteFromResolveBlockedBy({blockerComponentName:e,blockerType:a,blockerStateVariable:n,blockerDependency:r,typeBlocked:t,codeBlocked:o,deleteFromReciprocal:!1})}}else{if(s)for(let n of e[a]){let[e,r,i]=n.split("|");this.deleteFromResolveBlockedBy({blockerComponentName:e,blockerType:a,blockerStateVariable:r,blockerDependency:i,typeBlocked:t,codeBlocked:o,deleteFromReciprocal:!1})}delete e[a]}}else if(s)for(let n in e)for(let r of e[n]){let[e,a,i]=r.split("|");this.deleteFromResolveBlockedBy({blockerComponentName:e,blockerType:n,blockerStateVariable:a,blockerDependency:i,typeBlocked:t,codeBlocked:o,deleteFromReciprocal:!1})}}.bind(this),u=this.resolveBlockers.neededToResolve[e];if(u){let i=u[t];if(i)if(n){let e=i[n];if(e)if(r){let t=e[r];t&&(l(t),a&&0!==Object.keys(t).length||delete e[r]),0===Object.keys(e).length&&delete i[n]}else l(e),a&&0!==Object.keys(e).length||delete i[n];0===Object.keys(i).length&&delete u[t]}else l(i),a&&0!==Object.keys(i).length||delete u[t];0===Object.keys(u).length&&delete this.resolveBlockers.neededToResolve[e]}}checkIfHaveNeededToResolve({componentName:e,type:t,stateVariable:n,dependency:r}){let a=this.resolveBlockers.neededToResolve[e];if(!a)return!1;let i=a[t];if(!i)return!1;if(n){if(i=i[n],!i)return!1;if(r){if(i=i[r],!i)return!1}}return Object.keys(i).length>0}getResolveBlockedBy({componentName:e,type:t,stateVariable:n,dependency:r}){let a=this.resolveBlockers.resolveBlockedBy[e];a||(a=this.resolveBlockers.resolveBlockedBy[e]={});let i=a[t];if(i||(i=a[t]={}),n){let e=i;if(i=e[n],i||(i=e[n]={}),r){let e=i;i=e[r],i||(i=e[r]={})}}return i}deleteFromResolveBlockedBy({blockerComponentName:e,blockerType:t,blockerStateVariable:n,blockerDependency:r,typeBlocked:a,codeBlocked:i,deleteFromReciprocal:s=!0}){let o=e;n&&(o+="|"+n,r&&(o+="|"+r));let l=function(e){if(a){if(e[a])if(i){let n=e[a].indexOf(i);if(-1!==n&&e[a].splice(n,1),0===e[a].length&&delete e[a],s){let[e,n,r]=i.split("|");this.deleteFromNeededToResolve({componentNameBlocked:e,typeBlocked:a,stateVariableBlocked:n,dependencyBlocked:r,blockerType:t,blockerCode:o,deleteFromReciprocal:!1})}}else{if(s)for(let n of e[a]){let[e,r,i]=n.split("|");this.deleteFromNeededToResolve({componentNameBlocked:e,typeBlocked:a,stateVariableBlocked:r,dependencyBlocked:i,blockerType:t,blockerCode:o,deleteFromReciprocal:!1})}delete e[a]}}else if(s)for(let n in e)for(let r of e[n]){let[e,a,i]=r.split("|");this.deleteFromNeededToResolve({componentNameBlocked:e,typeBlocked:n,stateVariableBlocked:a,dependencyBlocked:i,blockerType:t,blockerCode:o,deleteFromReciprocal:!1})}}.bind(this),u=this.resolveBlockers.resolveBlockedBy[e];if(u){let i=u[t];if(i)if(n){let e=i[n];if(e)if(r){let t=e[r];t&&(l(t),a&&0!==Object.keys(t).length||delete e[r]),0===Object.keys(e).length&&delete i[n]}else l(e),a&&0!==Object.keys(e).length||delete i[n];0===Object.keys(i).length&&delete u[t]}else l(i),a&&0!==Object.keys(i).length||delete u[t];0===Object.keys(u).length&&delete this.resolveBlockers.resolveBlockedBy[e]}}async addBlocker({blockerComponentName:e,blockerType:t,blockerStateVariable:n,blockerDependency:r,componentNameBlocked:a,typeBlocked:i,stateVariableBlocked:s,dependencyBlocked:o}){let l=e;n&&(l+="|"+n,r&&(l+="|"+r));let u=a;s&&(u+="|"+s,o&&(u+="|"+o));let c=this.getNeededToResolve({componentName:a,type:i,stateVariable:s,dependency:o}),p=c[t];if(p||(p=c[t]=[]),p.includes(l))return;if(p.push(l),"stateVariable"===i){let e=this._components[a];if(e){let t=e.state[s];if(t.isResolved=!1,t.initiallyResolved){await this.core.markStateVariableAndUpstreamDependentsStale({component:e,varName:s});let t=this.upstreamDependencies[a][s];if(t)for(let e of t)if(this._components[e.upstreamComponentName])for(let t of e.upstreamVariableNames)await this.addBlocker({blockerComponentName:a,blockerType:"stateVariable",blockerStateVariable:s,componentNameBlocked:e.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:t})}}}let d=this.getResolveBlockedBy({componentName:e,type:t,stateVariable:n,dependency:r}),m=d[i];m||(m=d[i]=[]),m.includes(u)||m.push(u),this.resetCircularResolveBlockerCheckPassed({componentName:a,type:i,stateVariable:s,dependency:o}),this.checkForCircularResolveBlocker({componentName:a,type:i,stateVariable:s,dependency:o})}async processNewlyResolved({componentNameNewlyResolved:e,typeNewlyResolved:t,stateVariableNewlyResolved:n,dependencyNewlyResolved:r,expandComposites:a=!0,force:i=!1,recurseUpstream:s=!1}){if("stateVariable"===t){let t=this._components[e];if(t){t.state[n]&&(t.state[n].isResolved=!0,t.state[n].initiallyResolved=!0)}}else if("componentIdentity"===t){if(!(e in this._components)&&!i)return{success:!1}}else if("recalculateDownstreamComponents"===t){let t;try{t=this.downstreamDependencies[e][n][r]}catch(e){}if(t){let e=await t.recalculateDownstreamComponents({force:i});if(!e.success&&!i)return e;for(let e of t.upstreamVariableNames)this.deleteFromNeededToResolve({componentNameBlocked:t.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e,blockerType:"recalculateDownstreamComponents",blockerCode:t.upstreamComponentName+"|"+e+"|"+r});for(let e of t.upstreamVariableNames)await this.resolveIfReady({componentName:t.upstreamComponentName,type:"stateVariable",stateVariable:e,expandComposites:a,force:i,recurseUpstream:s});return{success:!0}}}else if("determineDependencies"===t){let t;try{t=this.downstreamDependencies[e][n][r]}catch(e){}if(t){let o=this.getNeededToResolve({componentName:e,type:"stateVariable",stateVariable:n}),l=!1,u=[];if(o.determineDependencies)for(let t of o.determineDependencies){let[r,a,i]=t.split("|");if(this.checkIfHaveNeededToResolve({componentName:e,type:"determineDependency",stateVariable:n,dependency:i})){l=!0;break}u.push(i)}if(l)return{success:!0};if(!(await this.updateDependencies({componentName:e,stateVariable:n,dependency:r})).success)return{success:!1};for(let n of t.upstreamVariableNames){for(let e of u)this.deleteFromResolveBlockedBy({blockerComponentName:t.upstreamComponentName,blockerType:"determineDependencies",blockerStateVariable:n,blockerDependency:e});await this.resolveIfReady({componentName:e,type:"stateVariable",stateVariable:n,expandComposites:a,force:i,recurseUpstream:s})}return{success:!0}}}else if("childMatches"===t){let t=this._components[e];if(t&&!t.childrenMatched){if(!(await this.core.deriveChildResultsFromDefiningChildren({parent:t,expandComposites:a,forceExpandComposites:i})).skipping&&!t.childrenMatchedWithPlaceholders&&!i)return{success:!1}}}else{if("expandComposite"!==t)throw Error(`Unrecognized type newly resolved: ${t}`);if(!this._components[e].isExpanded){if(this.core.updateInfo.compositesBeingExpanded.includes(e))return{success:!1};await this.core.expandCompositeComponent(this._components[e])}}let o=this.getResolveBlockedBy({componentName:e,type:t,stateVariable:n,dependency:r});o=Object.assign({},o);for(let l in o)for(let u of[...o[l]])if(this.deleteFromResolveBlockedBy({blockerComponentName:e,blockerType:t,blockerStateVariable:n,blockerDependency:r,typeBlocked:l,codeBlocked:u}),s){let[e,t,n]=u.split("|");await this.resolveIfReady({componentName:e,type:l,stateVariable:t,dependency:n,expandComposites:a,force:i,recurseUpstream:s})}return{success:!0}}async resolveStateVariablesIfReady({component:e,stateVariables:t}){let n=e.componentName;t||(await this.resolveIfReady({componentName:n,type:"componentIdentity",expandComposites:!1}),t=Object.keys(e.state));for(let r of t){let t=e.state[r];if(t&&t.determineDependenciesImmediately){let e=this.getNeededToResolve({componentName:n,type:"stateVariable",stateVariable:r}).determineDependencies;if(e)for(let t of e){let[e,n,r]=t.split("|");await this.resolveIfReady({componentName:e,type:"determineDependencies",stateVariable:n,dependency:r,expandComposites:!0})}}await this.resolveIfReady({componentName:n,type:"stateVariable",stateVariable:r,expandComposites:!1})}}async resolveIfReady({componentName:e,type:t,stateVariable:n,dependency:r,expandComposites:a=!0,force:i=!1,recurseUpstream:s=!1}){return this.checkIfHaveNeededToResolve({componentName:e,type:t,stateVariable:n,dependency:r})?{success:!1}:(this.deleteFromNeededToResolve({componentNameBlocked:e,typeBlocked:t,stateVariableBlocked:n,dependencyBlocked:r}),await this.processNewlyResolved({componentNameNewlyResolved:e,typeNewlyResolved:t,stateVariableNewlyResolved:n,dependencyNewlyResolved:r,expandComposites:a,force:i,recurseUpstream:s}))}async resolveItem({componentName:e,type:t,stateVariable:n,dependency:r,force:a=!1,recurseUpstream:i=!1,expandComposites:s=!0,numPreviouslyNeeded:o}){let l,u=this.getNeededToResolve({componentName:e,type:t,stateVariable:n,dependency:r}),c=u.determineDependencies;if(c&&c.length>0)for(let e of[...c]){let[t,n,r]=e.split("|"),i=await this.resolveItem({componentName:t,type:"determineDependencies",stateVariable:n,dependency:r,force:a,expandComposites:s});if(!i.success)return i}"stateVariable"===t&&this._components[e]&&(l=this._components[e].state[n],l&&(l.currentlyResolving=!0));let p=1/0,d=1/0;for(;(Object.keys(u).length>0||d>0)&&!(Number.isFinite(d)&&d>=p);){d>0&&(u=this.getNeededToResolve({componentName:e,type:t,stateVariable:n,dependency:r})),p=d,d=0;for(let i in u){if("determineDependencies"===i)throw Error(`Shouldn't have determine dependencies blocker after determining dependencies: ${e}, ${t}, ${n}, ${r}`);for(let e of[...u[i]]){let[t,n,r]=e.split("|"),o=await this.resolveItem({componentName:t,type:i,stateVariable:n,dependency:r,expandComposites:s});if(!o.success){if(!a)return o;d++}}}}if(d>0)for(u=this.getNeededToResolve({componentName:e,type:t,stateVariable:n,dependency:r});Object.keys(u).length>0;)for(let i in u){if("determineDependencies"===i)throw Error(`Shouldn't have determine dependencies blocker after determining dependencies: ${e}, ${t}, ${n}, ${r}`);for(let e of[...u[i]]){let[t,n,r]=e.split("|"),o=await this.resolveItem({componentName:t,type:i,stateVariable:n,dependency:r,force:a,expandComposites:s});if(!o.success)return o}}l&&(l.currentlyResolving=!1);let m=await this.resolveIfReady({componentName:e,type:t,stateVariable:n,dependency:r,force:a,recurseUpstream:i,expandComposites:s});if(!m.success){let l=this.getNeededToResolve({componentName:e,type:t,stateVariable:n,dependency:r}),u=Object.keys(l).length;u>0&&(void 0===o||ue.match(t)[1])),r=n.filter((e=>"__"!==e.slice(0,2))).reduce(((e,t)=>e.includes(t)?e:[...e,t]),[]);0===r.length&&(r=[n[0]]),1===r.length?e=r[0]:2===r.length?e=r.join(" and "):(r[r.length-2]=r.slice(r.length-2).join(", and "),r.pop(),e=r.join(", "));let i=[],o=[];for(let e of a){let[t,n]=e.split("|"),r=this._components[t];if(r){this.componentInfoObjects.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"_composite"})&&!r.attributes.createComponentOfType?.primitive&&("readyToExpandWhenResolved"===n?i.push(t):n===r.constructor.stateVariableToEvaluateAfterReplacements&&o.push(t))}}let l=!1;for(let e of i)if(o.includes(e)){l=!0;break}let u=`Circular dependency involving ${e}.`;throw l&&(u+=" Specifying the type of a composite component may address this circular dependency."),Error(u)}if(a=[...a,s],!this.circularResolveBlockedCheckPassed[s]){this.circularResolveBlockedCheckPassed[s]=!0;let i=this.getNeededToResolve({componentName:e,type:t,stateVariable:n,dependency:r});for(let e in i)for(let t of i[e]){let[n,r,i]=t.split("|");this.checkForCircularResolveBlocker({componentName:n,type:e,stateVariable:r,dependency:i,previouslyVisited:a})}}}resetCircularResolveBlockerCheckPassed({componentName:e,type:t,stateVariable:n,dependency:r}){let a=e;n&&(a+="|"+n,r&&(a+="|"+r));let i=a+"|"+t;if(this.circularResolveBlockedCheckPassed[i]){delete this.circularResolveBlockedCheckPassed[i];let a=this.getResolveBlockedBy({componentName:e,type:t,stateVariable:n,dependency:r});for(let e in a)for(let t of a[e]){let[n,r,a]=t.split("|");this.resetCircularResolveBlockerCheckPassed({componentName:n,type:e,stateVariable:r,dependency:a})}}}get components(){return this._components}set components(e){return null}}class Dependency{constructor({component:e,stateVariable:t,allStateVariablesAffected:n,dependencyName:r,dependencyDefinition:a,dependencyHandler:i}){this.dependencyName=r,this.dependencyHandler=i,this.upstreamComponentName=e.componentName,this.upstreamVariableNames=n,this.definition=Object.assign({},a),this.representativeStateVariable=t,a.doNotProxy&&(this.doNotProxy=!0),a.variablesOptional&&(this.variablesOptional=!0),a.publicStateVariablesOnly&&(this.publicStateVariablesOnly=!0),a.caseInsensitiveVariableMatch&&(this.caseInsensitiveVariableMatch=!0),a.useMappedVariableNames&&(this.useMappedVariableNames=!0),a.propIndex&&(a.propIndex.every(Number.isFinite)?this.propIndex=a.propIndex.map(Math.round):this.propIndex=[]),this.returnSingleVariableValue=!1,this.returnSingleComponent=!1,this.originalDownstreamVariableNames=[]}static dependencyType="_base";downstreamVariableNameIfNoVariables="__identity";static get rendererType(){return this.componentType}get dependencyType(){return this.constructor.dependencyType}setUpParameters(){}async determineDownstreamComponents(){return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]}}async initialize(){this.setUpParameters();let e=await this.determineDownstreamComponents(),t=e.downstreamComponentNames,n=e.downstreamComponentTypes;this.componentIdentitiesChanged=!0;let r=this.dependencyHandler.downstreamDependencies[this.upstreamComponentName];r||(r=this.dependencyHandler.downstreamDependencies[this.upstreamComponentName]={});for(let e of this.upstreamVariableNames)r[e]||(r[e]={}),r[e][this.dependencyName]=this;0!==this.originalDownstreamVariableNames.length||this.originalVariablesByComponent?(this.mappedDownstreamVariableNamesByComponent=[],this.valuesChanged=[]):(delete this.mappedDownstreamVariableNamesByComponent,delete this.upValuesChanged),this.downstreamComponentNames=[],this.downstreamComponentTypes=[];for(let[e,r]of t.entries())await this.addDownstreamComponent({downstreamComponentName:r,downstreamComponentType:n[e],index:e})}async addDownstreamComponent({downstreamComponentName:e,downstreamComponentType:t,index:n}){this.componentIdentitiesChanged=!0,this.downstreamComponentNames.splice(n,0,e),this.downstreamComponentTypes.splice(n,0,t);let r=this.dependencyHandler._components[e];if(r){let t;t=this.originalVariablesByComponent?this.originalDownstreamVariableNamesByComponent[n]:this.originalDownstreamVariableNames,this.caseInsensitiveVariableMatch&&(t=this.dependencyHandler.core.findCaseInsensitiveMatches({stateVariables:t,componentClass:r.constructor})),this.publicStateVariablesOnly&&(t=this.dependencyHandler.core.matchPublicStateVariables({stateVariables:t,componentClass:r.constructor}));let a=this.dependencyHandler.core.substituteAliases({stateVariables:t,componentClass:r.constructor});this.constructor.convertToArraySize&&(a=a.map((function(e){let t=r.state[e];if(t)return t.arraySizeStateVariable?t.arraySizeStateVariable:`__${e}_is_not_an_array`;if(r.arrayEntryPrefixes){let t=Object.keys(r.arrayEntryPrefixes).sort(((e,t)=>t.length-e.length));for(let n of t)if(e.substring(0,n.length)===n){let t=r.arrayEntryPrefixes[n],a=r.state[t];if(a.getArrayKeysFromVarName({arrayEntryPrefix:n,varEnding:e.substring(n.length),nDimensions:a.nDimensions}).length>0)return r.state[t].arraySizeStateVariable}}return`__${e}_is_not_an_array`}))),void 0!==this.propIndex&&(a=await this.dependencyHandler.core.arrayEntryNamesFromPropIndex({stateVariables:a,component:r,propIndex:this.propIndex}));let i=a;if(t.length>0||this.originalVariablesByComponent){this.mappedDownstreamVariableNamesByComponent.splice(n,0,a);let t={};for(let e of a)t[e]={changed:!0};this.valuesChanged.splice(n,0,t),this.variablesOptional&&(i=i.filter((e=>e in r.state||this.dependencyHandler.core.checkIfArrayEntry({stateVariable:e,component:r}))));for(let t of i)if(r.state[t]||await this.dependencyHandler.core.createFromArrayEntry({component:r,stateVariable:t}),!r.state[t].isResolved)for(let n of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:e,blockerType:"stateVariable",blockerStateVariable:t,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:n}),"determineDependencies"===this.dependencyType&&await this.dependencyHandler.addBlocker({blockerComponentName:e,blockerType:"stateVariable",blockerStateVariable:t,componentNameBlocked:this.upstreamComponentName,typeBlocked:"determineDependencies",stateVariableBlocked:n,dependencyBlocked:this.dependencyName})}0===i.length&&(i=[this.downstreamVariableNameIfNoVariables]);let s=this.dependencyHandler.upstreamDependencies[e];s||(s=this.dependencyHandler.upstreamDependencies[e]={});for(let e of i)if(void 0===s[e]&&(s[e]=[]),s[e].push(this),e!==this.downstreamVariableNameIfNoVariables)for(let e of this.upstreamVariableNames)this.dependencyHandler.resetCircularCheckPassed(this.upstreamComponentName,e)}for(let e of this.upstreamVariableNames)this.dependencyHandler._components[this.upstreamComponentName].state[e].initiallyResolved&&await this.dependencyHandler.core.markStateVariableAndUpstreamDependentsStale({component:this.dependencyHandler.components[this.upstreamComponentName],varName:e})}async removeDownstreamComponent({indexToRemove:e,recordChange:t=!0}){t&&(this.componentIdentitiesChanged=!0);let n=this.downstreamComponentNames[e];if(this.downstreamComponentNames.splice(e,1),this.downstreamComponentTypes.splice(e,1),n in this.dependencyHandler._components){let t;this.mappedDownstreamVariableNamesByComponent?(t=this.mappedDownstreamVariableNamesByComponent[e],this.mappedDownstreamVariableNamesByComponent.splice(e,1),this.valuesChanged.splice(e,1),this.variablesOptional&&t.push(this.downstreamVariableNameIfNoVariables)):t=[this.downstreamVariableNameIfNoVariables];for(let e of t){let t=this.dependencyHandler.upstreamDependencies[n][e];if(t){let r=t.indexOf(this);-1!==r&&(1===t.length?delete this.dependencyHandler.upstreamDependencies[n][e]:t.splice(r,1))}if(e!==this.downstreamVariableNameIfNoVariables)for(let e of this.upstreamVariableNames)this.dependencyHandler.resetCircularCheckPassed(this.upstreamComponentName,e)}}if(t)for(let e of this.upstreamVariableNames)this.dependencyHandler._components[this.upstreamComponentName].state[e].initiallyResolved&&await this.dependencyHandler.core.markStateVariableAndUpstreamDependentsStale({component:this.dependencyHandler.components[this.upstreamComponentName],varName:e})}async swapDownstreamComponents(e,t){this.componentIdentitiesChanged=!0,[this.downstreamComponentNames[e],this.downstreamComponentNames[t]]=[this.downstreamComponentNames[t],this.downstreamComponentNames[e]],[this.downstreamComponentTypes[e],this.downstreamComponentTypes[t]]=[this.downstreamComponentTypes[t],this.downstreamComponentTypes[e]],(this.originalDownstreamVariableNames.length>0||this.originalVariablesByComponent)&&([this.mappedDownstreamVariableNamesByComponent[e],this.mappedDownstreamVariableNamesByComponent[t]]=[this.mappedDownstreamVariableNamesByComponent[t],this.mappedDownstreamVariableNamesByComponent[e]],[this.valuesChanged[e],this.valuesChanged[t]]=[this.valuesChanged[t],this.valuesChanged[e]]);for(let e of this.upstreamVariableNames)this.dependencyHandler._components[this.upstreamComponentName].state[e].initiallyResolved&&await this.dependencyHandler.core.markStateVariableAndUpstreamDependentsStale({component:this.dependencyHandler.components[this.upstreamComponentName],varName:e})}deleteDependency(){let e=[];if(this.mappedDownstreamVariableNamesByComponent){if(e=this.mappedDownstreamVariableNamesByComponent,this.variablesOptional){let t=[];for(let[n,r]of this.downstreamComponentNames.entries()){let a=[];for(let t of e[n])this.dependencyHandler.components[r].state[t]&&a.push(t);a.length>0?t.push(a):t.push([this.downstreamVariableNameIfNoVariables])}e=t}}else e=Array(this.downstreamComponentNames.length).fill([this.downstreamVariableNameIfNoVariables]);for(let[t,n]of this.downstreamComponentNames.entries())for(let r of e[t]){let e=this.dependencyHandler.upstreamDependencies[n][r];if(e){let t=e.indexOf(this);-1!==t&&(1===e.length?delete this.dependencyHandler.upstreamDependencies[n][r]:e.splice(t,1))}for(let e of this.upstreamVariableNames)this.dependencyHandler.deleteFromNeededToResolve({componentNameBlocked:this.componentName,typeBlocked:"stateVariable",stateVariableBlocked:e,blockerType:"stateVariable",blockerCode:n+"|"+r});if(r!==this.downstreamVariableNameIfNoVariables)for(let e of this.upstreamVariableNames)this.dependencyHandler.resetCircularCheckPassed(this.upstreamComponentName,e)}this.deleteFromUpdateTriggers();let t=this.dependencyHandler.downstreamDependencies[this.upstreamComponentName];for(let e of this.upstreamVariableNames)delete t[e][this.dependencyName]}deleteFromUpdateTriggers(){}async getValue({verbose:e=!1,skipProxy:t=!1}={}){let n=[],r={},a=[];this.componentIdentitiesChanged&&(r.componentIdentitiesChanged=!0,this.componentIdentitiesChanged=!1);for(let[e,t]of this.downstreamComponentNames.entries()){let i=this.dependencyHandler._components[t];if(a[e]=!1,i){let s,o={componentType:i.componentType};if(this.skipComponentNames||(o.componentName=t),s=this.originalVariablesByComponent?this.originalDownstreamVariableNamesByComponent[e]:this.originalDownstreamVariableNames,s.length>0){o.stateValues={};let t={},n=!1;for(let[a,l]of s.entries()){let s=this.mappedDownstreamVariableNamesByComponent[e][a],u=this.useMappedVariableNames?s:l;if(!this.variablesOptional||s in i.state){let a=i.state[s];if(!a.deferred)if(o.stateValues[u]=await a.value,this.valuesChanged[e][s].changed&&(r.valuesChanged||(r.valuesChanged={}),r.valuesChanged[e]||(r.valuesChanged[e]={}),r.valuesChanged[e][u]=this.valuesChanged[e][s]),this.valuesChanged[e][s]={},a.usedDefault)t[u]=!0,n=!0;else if(a.isArrayEntry&&1===a.arrayKeys.length){i.state[a.arrayStateVariable].usedDefaultByArrayKey[a.arrayKeys[0]]&&(t[u]=!0,n=!0)}}}n&&(a[e]=t)}n.push(o)}else n.push({componentType:this.downstreamComponentTypes[e]})}if(!e)if(this.returnSingleVariableValue)if(1===n.length){n=n[0],r.valuesChanged&&r.valuesChanged[0]?r.valuesChanged=r.valuesChanged[0]:delete r.valuesChanged,a=a[0];let e=Object.keys(n.stateValues);if(1===e.length){let t=e[0];n=n.stateValues[t],r.valuesChanged&&r.valuesChanged[t]&&(r.valuesChanged=r.valuesChanged[t]),a&&(a=a[t])}else n=null,r={},a=!1}else n=null,r={},a=!1;else this.returnSingleComponent&&(1===n.length?(n=n[0],r.valuesChanged&&r.valuesChanged[0]?r.valuesChanged=r.valuesChanged[0]:delete r.valuesChanged,a=a[0]):(n=null,a=!1));return{value:n,changes:r,usedDefault:a}}checkForCircular(){for(let e of this.upstreamVariableNames)this.dependencyHandler.resetCircularCheckPassed(this.upstreamComponentName,e);for(let e of this.upstreamVariableNames)this.dependencyHandler.checkForCircularDependency({componentName:this.upstreamComponentName,varName:e})}async recalculateDownstreamComponents({force:e=!1}={}){let t=await this.determineDownstreamComponents({force:e}),n=t.downstreamComponentNames,r=n.length!==this.downstreamComponentNames.length||this.downstreamComponentNames.some(((e,t)=>e!=n[t]));if(r){this.componentIdentitiesChanged=!0;let e=0;for(let[t,r]of[...this.downstreamComponentNames].entries())n.includes(r)||(await this.removeDownstreamComponent({indexToRemove:t-e}),e++);for(let[e,r]of n.entries()){let n=this.downstreamComponentNames.indexOf(r);-1!==n?n!==e&&await this.swapDownstreamComponents(n,e):await this.addDownstreamComponent({downstreamComponentName:r,downstreamComponentType:t.downstreamComponentTypes[e],index:e})}}if(this.originalVariablesByComponent)for(let[e,n]of[...this.downstreamComponentNames].entries())(this.mappedDownstreamVariableNamesByComponent[e].length!==this.originalDownstreamVariableNamesByComponent[e].length||this.mappedDownstreamVariableNamesByComponent[e].some(((t,n)=>this.originalDownstreamVariableNamesByComponent[e][n]!==t)))&&(await this.removeDownstreamComponent({indexToRemove:e}),await this.addDownstreamComponent({downstreamComponentName:n,downstreamComponentType:t.downstreamComponentTypes[e],index:e}));return{success:t.success}}}class StateVariableDependency extends Dependency{static dependencyType="stateVariable";setUpParameters(){if(this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName,void 0===this.definition.variableName)throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableName is not defined`);this.originalDownstreamVariableNames=[this.definition.variableName],this.definition.returnAsComponentObject?this.returnSingleComponent=!0:this.returnSingleVariableValue=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}return{success:!0,downstreamComponentNames:[this.componentName],downstreamComponentTypes:[e.componentType]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(StateVariableDependency);class MultipleStateVariablesDependency extends Dependency{static dependencyType="multipleStateVariables";setUpParameters(){if(this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName,!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames,this.returnSingleComponent=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}return{success:!0,downstreamComponentNames:[this.componentName],downstreamComponentTypes:[e.componentType]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(MultipleStateVariablesDependency);class StateVariableComponentTypeDependency extends StateVariableDependency{static dependencyType="stateVariableComponentType";async getValue({verbose:e=!1}={}){let t=[],n={};if(this.staticValue)t=[this.staticValue];else if(this.componentIdentitiesChanged&&(n.componentIdentitiesChanged=!0,this.componentIdentitiesChanged=!1),1===this.downstreamComponentNames.length){let e=this.downstreamComponentNames[0],r=this.dependencyHandler.components[e],a={componentName:r.componentName,componentType:r.componentType,stateValues:{}},i=this.originalDownstreamVariableNames[0],s=this.mappedDownstreamVariableNamesByComponent[0][0],o=this.useMappedVariableNames?s:i;if((!this.variablesOptional||s in r.state)&&!r.state[s].deferred){let e=r.state[s];if(await e.value,a.stateValues[o]=e.componentType,e.isArray&&e.wrappingComponents?.length>0){let t=e.wrappingComponents[e.wrappingComponents.length-1][0];"object"==typeof t&&(t=t.componentType),a.stateValues[o]=t}this.valuesChanged[0][s].changed&&(n.valuesChanged||(n.valuesChanged={}),n.valuesChanged[0]||(n.valuesChanged[0]={}),n.valuesChanged[0][o]=this.valuesChanged[0][s]),this.valuesChanged[0][s]={};let t=e.shadowingInstructions?.hasVariableComponentType;if(!t&&e.isArrayEntry){t=r.state[e.arrayStateVariable].shadowingInstructions?.hasVariableComponentType}t||(this.staticValue=a,await this.removeDownstreamComponent({indexToRemove:0,recordChange:!1}))}t=[a]}if(!e)if(this.returnSingleVariableValue)if(1===t.length){t=t[0];let e=Object.keys(t.stateValues);n.valuesChanged&&n.valuesChanged[0]&&n.valuesChanged[0][0]&&(n.valuesChanged=n.valuesChanged[0][0]),t=1===e.length?t.stateValues[e[0]]:null}else t=null;else this.returnSingleComponent&&(1===t.length?(t=t[0],n.valuesChanged&&n.valuesChanged[0]&&(n.valuesChanged=n.valuesChanged[0])):t=null);return{value:t,changes:n,usedDefault:!1}}}dependencyTypeArray.push(StateVariableComponentTypeDependency);class StateVariableArraySizeDependency extends StateVariableDependency{static dependencyType="stateVariableArraySize";static convertToArraySize=!0}dependencyTypeArray.push(StateVariableArraySizeDependency);class RecursiveDependencyValuesDependency extends Dependency{static dependencyType="recursiveDependencyValues";setUpParameters(){if(this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName,void 0===this.definition.variableNames)throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames is not defined`);this.startingVariableNames=this.definition.variableNames,this.originalVariablesByComponent=!0,this.includeImmediateValueWithValue=this.definition.includeImmediateValueWithValue,this.includeRawValueWithImmediateValue=this.definition.includeRawValueWithImmediateValue,this.includeOnlyEssentialValues=this.definition.includeOnlyEssentialValues,this.variablesOptional=!0}async determineDownstreamComponents({force:e=!1}={}){this.missingComponents=[],this.originalDownstreamVariableNamesByComponent=[];let t=await this.getRecursiveDependencyVariables({componentName:this.componentName,variableNames:this.startingVariableNames,force:e});if(!t.success)return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]};let n=[],r=[];for(let e in t.components)if(this.includeOnlyEssentialValues){let a=[],i=this.dependencyHandler._components[e];for(let n of t.components[e].variableNames)(i.state[n]?.hasEssential||i.state[n]?.isArrayEntry&&i.state[i.state[n].arrayStateVariable].hasEssential)&&a.push(n);a.length>0&&(n.push(e),r.push(t.components[e].componentType),this.originalDownstreamVariableNamesByComponent.push(a))}else n.push(e),r.push(t.components[e].componentType),this.originalDownstreamVariableNamesByComponent.push(t.components[e].variableNames);return{success:!0,downstreamComponentNames:n,downstreamComponentTypes:r}}async getRecursiveDependencyVariables({componentName:e,variableNames:t,force:n,components:r={}}){let a=this.dependencyHandler._components[e];if(!a){if(!this.missingComponents.includes(e)){let t=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[e];t||(t=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[e]=[]),t.includes(this)||t.push(this)}for(let t of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:e,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:t,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:t,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:t});return{success:!1}}this.includeImmediateValueWithValue&&t.includes("value")&&!t.includes("immediateValue")&&"immediateValue"in a.state&&(t=[...t,"immediateValue"]),this.includeRawValueWithImmediateValue&&t.includes("immediateValue")&&!t.includes("rawRendererValue")&&"rawRendererValue"in a.state&&(t=[...t,"rawRendererValue"]);let i=r[e];i||(i=r[e]={componentName:e,componentType:a.componentType,variableNames:[]});let s=this.dependencyHandler.updateTriggers.dependenciesBasedOnDependenciesOfStateVariables[e];s||(s=this.dependencyHandler.updateTriggers.dependenciesBasedOnDependenciesOfStateVariables[e]={});for(let o of t)if(!i.variableNames.includes(o)){i.variableNames.push(o);let t=s[o];t||(t=s[o]=[]),t.includes(this)||t.push(this);let l=a.state[o];if(l){if(!l.isResolved){if(!n){for(let t of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:e,blockerType:"stateVariable",blockerStateVariable:o,componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:t,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:t,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:t});return{success:!1}}await l.value}let t=this.dependencyHandler.downstreamDependencies[a.componentName][o];for(let e in t){let a=t[e];for(let[e,t]of a.downstreamComponentNames.entries()){let i=[];if((a.originalDownstreamVariableNames.length>0||a.originalVariablesByComponent)&&(i=a.mappedDownstreamVariableNamesByComponent[e]),!(await this.getRecursiveDependencyVariables({componentName:t,variableNames:i,force:n,components:r})).success)return{success:!1}}}}}return{success:!0,components:r}}async getValue(){let e;this.gettingValue=!0,this.varsWithUpdatedDeps={};let t={},n=!0,r={};for(;n;){if(n=!1,e=await super.getValue(),e.changes.valuesChanged)if(r.valuesChanged)for(let t in e.changes.valuesChanged){let n=e.changes.valuesChanged[t];if(r.valuesChanged[t])for(let e in n)r.valuesChanged[t][e]=n[e];else r.valuesChanged[t]=n}else r.valuesChanged=e.changes.valuesChanged;for(let e in this.varsWithUpdatedDeps){let r=t[e];r||(r=t[e]=[]);for(let t of this.varsWithUpdatedDeps[e])r.includes(t)||(r.push(t),n=!0)}n&&await this.recalculateDownstreamComponents()}return this.gettingValue=!1,e.changes=r,e}deleteFromUpdateTriggers(){for(let e of this.missingComponents){let t=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[e];if(t){let e=t.indexOf(this);-1!==e&&t.splice(e,1)}}}}dependencyTypeArray.push(RecursiveDependencyValuesDependency);class ComponentIdentityDependency extends Dependency{static dependencyType="componentIdentity";setUpParameters(){this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName,this.returnSingleComponent=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}return{success:!0,downstreamComponentNames:[this.componentName],downstreamComponentTypes:[e.componentType]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(ComponentIdentityDependency);class AttributeComponentDependency extends Dependency{static dependencyType="attributeComponent";setUpParameters(){if(this.definition.parentName?(this.parentName=this.definition.parentName,this.specifiedComponentName=this.parentName):this.parentName=this.upstreamComponentName,this.definition.variableNames){if(!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames}else this.originalDownstreamVariableNames=[];this.attributeName=this.definition.attributeName,this.returnSingleComponent=!0,this.shadowDepth=0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.parentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.parentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}let t=e.attributes[this.attributeName];if(this.shadowDepth=0,t?.component)return{success:!0,downstreamComponentNames:[t.component.componentName],downstreamComponentTypes:[t.component.componentType]};let n=e;for(;n.shadows;){let e=n.shadows,r=n.shadows.propVariable;if(n=this.dependencyHandler._components[e.componentName],!n)break;if(r){if(!n.state[r]?.shadowingInstructions?.attributesToShadow?.includes(this.attributeName)&&!n.constructor.createAttributesObject()[this.attributeName]?.propagateToProps)break}else{let t=this.dependencyHandler._components[e.compositeName];if("sourceAttributesToIgnoreRecursively"in t.state){if((await t.stateValues.sourceAttributesToIgnoreRecursively).includes(this.attributeName))break}if(e.firstLevelReplacement&&"sourceAttributesToIgnore"in t.state){if((await t.stateValues.sourceAttributesToIgnore).includes(this.attributeName))break}}if(this.shadowDepth++,t=n.attributes[this.attributeName],t?.component)return{success:!0,downstreamComponentNames:[t.component.componentName],downstreamComponentTypes:[t.component.componentType]}}return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]}}async getValue({verbose:e}={}){let t=await super.getValue({verbose:e,skipProxy:!0});return t.value&&(t.value.shadowDepth=this.shadowDepth),t}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(AttributeComponentDependency);class ChildDependency extends Dependency{static dependencyType="child";setUpParameters(){if(this.definition.parentName?(this.parentName=this.definition.parentName,this.specifiedComponentName=this.parentName):this.parentName=this.upstreamComponentName,this.definition.variableNames){if(!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames}else this.originalDownstreamVariableNames=[];if(this.childGroups=this.definition.childGroups,!Array.isArray(this.childGroups))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: childGroups must be an array`);void 0!==this.definition.childIndices&&(this.childIndices=this.definition.childIndices.map((e=>Number(e)))),this.skipComponentNames=this.definition.skipComponentNames,this.skipPlaceholders=this.definition.skipPlaceholders,this.proceedIfAllChildrenNotMatched=this.definition.proceedIfAllChildrenNotMatched}async determineDownstreamComponents(){this.downstreamPrimitives?this.previousDownstreamPrimitives=[...this.downstreamPrimitives]:this.previousDownstreamPrimitives=[],this.downstreamPrimitives=[];let e=this.dependencyHandler._components[this.parentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.parentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}let t=this.dependencyHandler.updateTriggers.childDependenciesByParent[this.parentName];t||(t=this.dependencyHandler.updateTriggers.childDependenciesByParent[this.parentName]=[]),t.includes(this)||t.push(this);let n=e.returnMatchedChildIndices(this.childGroups);if(void 0===n)throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: childGroups ${this.childGroups} does not exist.`);if(this.childIndices&&(n=n.filter(((e,t)=>this.childIndices.includes(t)))),!e.childrenMatched&&!this.proceedIfAllChildrenNotMatched){let t=!1;if(e.childrenMatchedWithPlaceholders&&(this.skipPlaceholders&&(n=n.filter((t=>!e.placeholderActiveChildrenIndices.includes(t)))),t=!(!this.skipComponentNames||0!==this.originalDownstreamVariableNames.length)||n.every((t=>!e.placeholderActiveChildrenIndices.includes(t)))),!t){let t=e.unexpandedCompositesNotReady.length>0;if(!t&&e.unexpandedCompositesReady.length>0){for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.parentName,blockerType:"childMatches",blockerStateVariable:e,componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(t){for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.parentName,blockerType:"childMatches",blockerStateVariable:e,componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});let t=[],r=[];for(let a of e.unexpandedCompositesNotReady){if(e.childrenMatchedWithPlaceholders){if(e.placeholderActiveChildrenIndicesByComposite[a].every((e=>!n.includes(e))))continue}this.dependencyHandler._components[a].attributes.createComponentOfType?.primitive?t.push(a):r.push(a)}let a=r;0===a.length&&(a=t);for(let e of a)for(let t of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:e,blockerType:"stateVariable",blockerStateVariable:"readyToExpandWhenResolved",componentNameBlocked:this.upstreamComponentName,typeBlocked:"childMatches",stateVariableBlocked:t});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}}}let r=n.map((t=>e.activeChildren[t]));if(this.compositeReplacementRange=[],e.compositeReplacementActiveRange&&r.length>0){let t=0;for(;t=r){let e=t,i=t;for(;a.lastInd>r&&t=r);)i=t;if(this.compositeReplacementRange.push({compositeName:a.compositeName,target:a.target,firstInd:e,lastInd:i}),t++,t===n.length)break;r=n[t]}t++}}this.shadowDepthByChild=[];for(let t of r){let n=0,r=t,a=e;for(;r?.shadows&&r.shadows.compositeName===a?.shadows?.compositeName;)n++,a=this.dependencyHandler._components[a.shadows.componentName],r=this.dependencyHandler._components[r.shadows.componentName];this.shadowDepthByChild.push(n)}this.activeChildrenIndices=n;let a=[],i=[];for(let[e,t]of r.entries())"object"==typeof t?(this.downstreamPrimitives.push(null),a.push(t.componentName?t.componentName:`__placeholder_${e}`),i.push(t.componentType)):this.downstreamPrimitives.push(t);return{success:!0,downstreamComponentNames:a,downstreamComponentTypes:i}}async getValue({verbose:e}={}){let t=await super.getValue({verbose:e,skipProxy:!0}),n=[],r=0;for(let[e,a]of this.downstreamPrimitives.entries())if(null===a){t.value[r].shadowDepth=this.shadowDepthByChild[e],n.push(t.value[r]),r++}else n.push(a);return n.compositeReplacementRange=this.compositeReplacementRange,t.value=n,(this.downstreamPrimitives.length!==this.previousDownstreamPrimitives.length||this.downstreamPrimitives.some(((e,t)=>e!==this.previousDownstreamPrimitives[t])))&&(t.changes.componentIdentitiesChanged=!0,this.previousDownstreamPrimitives=[...this.downstreamPrimitives]),t}deleteFromUpdateTriggers(){let e=this.dependencyHandler.updateTriggers.childDependenciesByParent[this.parentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(ChildDependency);class DescendantDependency extends Dependency{static dependencyType="descendant";setUpParameters(){if(this.definition.ancestorName?(this.ancestorName=this.definition.ancestorName,this.specifiedComponentName=this.ancestorName):this.ancestorName=this.upstreamComponentName,this.definition.variableNames){if(!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames}else this.originalDownstreamVariableNames=[];this.componentTypes=this.definition.componentTypes,this.recurseToMatchedChildren=this.definition.recurseToMatchedChildren,this.useReplacementsForComposites=this.definition.useReplacementsForComposites,this.includeNonActiveChildren=this.definition.includeNonActiveChildren,this.includeAttributeChildren=this.definition.includeAttributeChildren,this.skipOverAdapters=this.definition.skipOverAdapters,this.ignoreReplacementsOfMatchedComposites=this.definition.ignoreReplacementsOfMatchedComposites,this.ignoreReplacementsOfEncounteredComposites=this.definition.ignoreReplacementsOfEncounteredComposites,null!==this.definition.componentIndex&&void 0!==this.definition.componentIndex&&(Number.isInteger(this.definition.componentIndex)?this.componentIndex=this.definition.componentIndex:this.componentIndex=NaN)}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.ancestorName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.ancestorName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.ancestorName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.ancestorName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}let t=this.dependencyHandler.updateTriggers.descendantDependenciesByAncestor[this.ancestorName];t||(t=this.dependencyHandler.updateTriggers.descendantDependenciesByAncestor[this.ancestorName]=[]),t.includes(this)||t.push(this);let n=this.gatherUnexpandedComposites(e);if(n.haveCompositesNotReady||n.haveUnexpandedCompositeReady){for(let e of this.upstreamVariableNames){await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});for(let t in n.unexpandedCompositesReadyByParentName)await this.dependencyHandler.addBlocker({blockerComponentName:t,blockerType:"childMatches",blockerStateVariable:e,componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName});for(let t in n.unexpandedCompositesNotReadyByParentName)await this.dependencyHandler.addBlocker({blockerComponentName:t,blockerType:"childMatches",blockerStateVariable:e,componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName})}return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}let r=gatherDescendants({ancestor:e,descendantTypes:this.componentTypes,recurseToMatchedChildren:this.recurseToMatchedChildren,useReplacementsForComposites:this.useReplacementsForComposites,includeNonActiveChildren:this.includeNonActiveChildren,skipOverAdapters:this.skipOverAdapters,ignoreReplacementsOfMatchedComposites:this.ignoreReplacementsOfMatchedComposites,ignoreReplacementsOfEncounteredComposites:this.ignoreReplacementsOfEncounteredComposites,componentInfoObjects:this.dependencyHandler.componentInfoObjects});if(void 0!==this.componentIndex){let e=r[this.componentIndex-1];r=e?[e]:[]}return{success:!0,downstreamComponentNames:r.map((e=>e.componentName)),downstreamComponentTypes:r.map((e=>e.componentType))}}gatherUnexpandedComposites(e){let t={},n={},r=!1,a=!1,i=this.skipComponentNames&&0===this.originalDownstreamVariableNames.length;if(!e.childrenMatched)if(e.childrenMatchedWithPlaceholders){if(e.unexpandedCompositesReady.length>0){let n=this.unexpandedCompositesAdjustedForPlacedholders(e.unexpandedCompositesReady,i);n.length>0&&(t[e.componentName]=n,r=!0)}if(e.unexpandedCompositesNotReady.length>0){let t=this.unexpandedCompositesAdjustedForPlacedholders(e.unexpandedCompositesNotReady,i);t.length>0&&(n[e.componentName]=t,a=!0)}}else e.unexpandedCompositesReady.length>0&&(t[e.componentName]=e.unexpandedCompositesReady,r=!0),e.unexpandedCompositesNotReady.length>0&&(n[e.componentName]=e.unexpandedCompositesNotReady,a=!0);for(let i in e.allChildren){let s=e.allChildren[i].component;if("object"==typeof s){let e=this.gatherUnexpandedComposites(s);e.haveUnexpandedCompositeReady&&(Object.assign(t,e.unexpandedCompositesReadyByParentName),r=!0),e.haveCompositesNotReady&&(Object.assign(n,e.unexpandedCompositesNotReadyByParentName),a=!0)}}return{unexpandedCompositesReadyByParentName:t,haveUnexpandedCompositeReady:r,unexpandedCompositesNotReadyByParentName:n,haveCompositesNotReady:a}}unexpandedCompositesAdjustedForPlacedholders(e,t){let n=[];for(let r of e){let e=this.dependencyHandler._components[r];if(e.attributes.createComponentOfType){let a=this.dependencyHandler.componentInfoObjects.componentTypeLowerCaseMapping[e.attributes.createComponentOfType.primitive.toLowerCase()],i=this.componentTypes.some((e=>this.dependencyHandler.componentInfoObjects.isInheritedComponentType({inheritedComponentType:a,baseComponentType:e})));i&&t||n.push(r)}else n.push(r)}return n}deleteFromUpdateTriggers(){let e=this.dependencyHandler.updateTriggers.descendantDependenciesByAncestor[this.ancestorName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(DescendantDependency);class ParentDependency extends Dependency{static dependencyType="parentStateVariable";setUpParameters(){if(this.definition.childName?(this.childName=this.definition.childName,this.specifiedComponentName=this.childName):this.childName=this.upstreamComponentName,!this.definition.variableName)throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: must have a variableName`);this.originalDownstreamVariableNames=[this.definition.variableName],this.definition.parentComponentType&&(this.parentComponentType=this.definition.parentComponentType),this.returnSingleVariableValue=!0,this.variablesOptional=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.childName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.childName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.childName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.childName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!e.parentName)return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};this.parentName=e.parentName;let t=this.dependencyHandler._components[this.parentName];if(!t){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.parentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(this.parentComponentType&&!this.dependencyHandler.componentInfoObjects.isInheritedComponentType({inheritedComponentType:t.componentType,baseComponentType:this.parentComponentType}))return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};let n=this.dependencyHandler.updateTriggers.parentDependenciesByParent[this.parentName];return n||(n=this.dependencyHandler.updateTriggers.parentDependenciesByParent[this.parentName]=[]),n.includes(this)||n.push(this),{success:!0,downstreamComponentNames:[this.parentName],downstreamComponentTypes:[t.componentType]}}deleteFromUpdateTriggers(){let e=this.dependencyHandler.updateTriggers.parentDependenciesByParent[this.parentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}let t=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName];if(t){let e=t.indexOf(this);-1!==e&&t.splice(e,1)}}}dependencyTypeArray.push(ParentDependency);class ParentIdentityDependency extends Dependency{static dependencyType="parentIdentity";setUpParameters(){this.definition.childName?(this.childName=this.definition.childName,this.specifiedComponentName=this.childName):this.childName=this.upstreamComponentName,this.definition.parentComponentType&&(this.parentComponentType=this.definition.parentComponentType),this.returnSingleComponent=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.childName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.childName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.childName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.childName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!e.parentName)return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};this.parentName=e.parentName;let t=this.dependencyHandler._components[this.parentName];if(!t){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.parentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(this.parentComponentType&&!this.dependencyHandler.componentInfoObjects.isInheritedComponentType({inheritedComponentType:t.componentType,baseComponentType:this.parentComponentType}))return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};let n=this.dependencyHandler.updateTriggers.parentDependenciesByParent[this.parentName];return n||(n=this.dependencyHandler.updateTriggers.parentDependenciesByParent[this.parentName]=[]),n.includes(this)||n.push(this),{success:!0,downstreamComponentNames:[this.parentName],downstreamComponentTypes:[t.componentType]}}deleteFromUpdateTriggers(){let e=this.dependencyHandler.updateTriggers.parentDependenciesByParent[this.parentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}let t=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName];if(t){let e=t.indexOf(this);-1!==e&&t.splice(e,1)}}}dependencyTypeArray.push(ParentIdentityDependency);class AncestorDependency extends Dependency{static dependencyType="ancestor";setUpParameters(){if(this.definition.descendantName?(this.descendantName=this.definition.descendantName,this.specifiedComponentName=this.descendantName):this.descendantName=this.upstreamComponentName,this.definition.variableNames){if(!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames}else this.originalDownstreamVariableNames=[];this.returnSingleComponent=!0,this.definition.componentType&&(this.componentType=this.definition.componentType)}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.descendantName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.descendantName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.descendantName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.descendantName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!(this.dependencyHandler.core.documentName in this.dependencyHandler._components)){for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e}),await this.dependencyHandler.addBlocker({blockerComponentName:this.dependencyHandler.core.documentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}let t=this.findMatchingAncestor(e);if(t.missingComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[t.missingComponentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[t.missingComponentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:t.missingComponentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}for(let e of t.ancestorsExamined){let t=this.dependencyHandler.updateTriggers.ancestorDependenciesByPotentialAncestor[e];t||(t=this.dependencyHandler.updateTriggers.ancestorDependenciesByPotentialAncestor[e]=[]),t.includes(this)||t.push(this)}return this.ancestorResults=t,t.ancestorFound?{success:!0,downstreamComponentNames:[t.ancestorFound.componentName],downstreamComponentTypes:[t.ancestorFound.componentClass.componentType]}:{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]}}findMatchingAncestor(e){let t=[];if(this.componentType){for(let n of e.ancestors){let e=this.dependencyHandler._components[n.componentName];if(!e)return{missingComponentName:n.componentName};if(t.push(n.componentName),this.dependencyHandler.componentInfoObjects.isInheritedComponentType({inheritedComponentType:e.componentType,baseComponentType:this.componentType}))return{ancestorsExamined:t,ancestorFound:n}}return{ancestorsExamined:t}}if(0===this.originalDownstreamVariableNames.length)return console.warn(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: must specify componentType or variableNames to find ancestor`),{ancestorsExamined:t};let n=this.originalDownstreamVariableNames;for(let r of e.ancestors){let e=this.dependencyHandler._components[r.componentName];if(!e)return{missingComponentName:r.componentName};t.push(r.componentName);let a=!0;for(let t of n)if(!(t in e.state)&&!this.dependencyHandler.core.checkIfArrayEntry({stateVariable:t,component:e})){a=!1;break}if(a)return{ancestorsExamined:t,ancestorFound:r}}return{ancestorsExamined:t}}deleteFromUpdateTriggers(){for(let e of this.ancestorResults.ancestorsExamined){let t=this.dependencyHandler.updateTriggers.ancestorDependenciesByPotentialAncestor[e];if(t){let e=t.indexOf(this);-1!==e&&t.splice(e,1)}}if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}if(this.ancestorResults&&this.ancestorResults.missingComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.ancestorResults.missingComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(AncestorDependency);class ReplacementDependency extends Dependency{static dependencyType="replacement";setUpParameters(){if(this.definition.compositeName?(this.compositeName=this.definition.compositeName,this.specifiedComponentName=this.compositeName):this.compositeName=this.upstreamComponentName,this.definition.variableNames){if(!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames}else this.originalDownstreamVariableNames=[];this.recursive=this.definition.recursive,this.recurseNonStandardComposites=this.definition.recurseNonStandardComposites,null!==this.definition.componentIndex&&void 0!==this.definition.componentIndex&&(Number.isInteger(this.definition.componentIndex)?this.componentIndex=this.definition.componentIndex:this.componentIndex=NaN),this.definition.targetSubnames&&(this.targetSubnames=this.definition.targetSubnames),this.definition.targetSubnamesComponentIndex&&(this.definition.targetSubnamesComponentIndex.every(Number.isInteger)?this.targetSubnamesComponentIndex=this.definition.targetSubnamesComponentIndex:this.targetSubnamesComponentIndex=[NaN]),this.includeWithheldReplacements=this.definition.includeWithheldReplacements,this.expandReplacements=!0}async determineDownstreamComponents(){this.replacementPrimitives?this.previousReplacementPrimitives=[...this.replacementPrimitives]:this.previousReplacementPrimitives=[],this.replacementPrimitives=[];let e=this.dependencyHandler._components[this.compositeName];if(!e){let a=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.compositeName];a||(a=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.compositeName]=[]),a.includes(this)||a.push(this);for(let i of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.compositeName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:i,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:i,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:i});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!e.isExpanded){for(let s of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:s,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:s}),await this.dependencyHandler.addBlocker({blockerComponentName:this.compositeName,blockerType:"expandComposite",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:s,dependencyBlocked:this.dependencyName});return e.state.readyToExpandWhenResolved.isResolved||await this.dependencyHandler.addBlocker({blockerComponentName:this.compositeName,blockerType:"stateVariable",blockerStateVariable:"readyToExpandWhenResolved",componentNameBlocked:this.compositeName,typeBlocked:"expandComposite"}),{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}this.compositesFound=[this.compositeName];let t=e.replacements;if(!this.includeWithheldReplacements&&e.replacementsToWithhold>0&&(t=t.slice(0,-e.replacementsToWithhold)),this.recursive){let o=this.dependencyHandler.core.recursivelyReplaceCompositesWithReplacements({replacements:t,recurseNonStandardComposites:this.recurseNonStandardComposites,includeWithheldReplacements:this.includeWithheldReplacements});if(o.unexpandedCompositesNotReady.length>0||o.unexpandedCompositesReady.length>0){for(let l of this.upstreamVariableNames){await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:l,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:l});for(let u of[...o.unexpandedCompositesReady,...o.unexpandedCompositesNotReady])await this.dependencyHandler.addBlocker({blockerComponentName:u,blockerType:"expandComposite",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:l,dependencyBlocked:this.dependencyName})}for(let c of o.unexpandedCompositesNotReady)await this.dependencyHandler.addBlocker({blockerComponentName:c,blockerType:"stateVariable",blockerStateVariable:"readyToExpandWhenResolved",componentNameBlocked:c,typeBlocked:"expandComposite"});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}t=o.newReplacements,this.compositesFound.push(...o.compositesFound)}for(let p of this.compositesFound){let d=this.dependencyHandler.updateTriggers.replacementDependenciesByComposite[p];d||(d=this.dependencyHandler.updateTriggers.replacementDependenciesByComposite[p]=[]),d.includes(this)||d.push(this)}if(void 0!==this.componentIndex){let m=t[this.componentIndex-1];t=m?[m]:[]}if(this.targetSubnames){function h({components:e,subNames:t,subNamesComponentIndex:n,dep:r}){if(0===t.length)return e;let a=t.slice(1),i=[];for(let s of e){let e=s.componentName+"/"+t[0],o=r.dependencyHandler._components[e];if(o)r.dependencyHandler.componentInfoObjects.isInheritedComponentType({inheritedComponentType:o.componentType,baseComponentType:"_composite"})?console.warn("Have not yet implemented recursing subnames to multiple levels of composites"):0===a.length&&(n?.length,1)&&i.push(o);else{let t=r.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[e];t||(t=r.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[e]=[]),t.includes(r)||t.push(r)}}return i}t=h({components:t,subNames:this.targetSubnames,subNamesComponentIndex:this.targetSubnamesComponentIndex,dep:this})}let n=[],r=[];for(let f of t)"object"==typeof f?(this.replacementPrimitives.push(null),n.push(f.componentName),r.push(f.componentType)):this.replacementPrimitives.push(f);return{success:!0,downstreamComponentNames:n,downstreamComponentTypes:r}}async getValue({verbose:e}={}){let t=await super.getValue({verbose:e,skipProxy:!0}),n=[],r=0;for(let e of this.replacementPrimitives)null===e?(n.push(t.value[r]),r++):n.push(e);return t.value=n,(this.replacementPrimitives.length!==this.previousReplacementPrimitives.length||this.replacementPrimitives.some(((e,t)=>e!==this.previousReplacementPrimitives[t])))&&(t.changes.componentIdentitiesChanged=!0,this.previousReplacementPrimitives=[...this.replacementPrimitives]),t}deleteFromUpdateTriggers(){if(this.compositesFound)for(let e of this.compositesFound){let t=this.dependencyHandler.updateTriggers.replacementDependenciesByComposite[e];if(t){let e=t.indexOf(this);-1!==e&&t.splice(e,1)}}if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(ReplacementDependency);class SourceCompositeStateVariableDependency extends Dependency{static dependencyType="sourceCompositeStateVariable";setUpParameters(){if(this.definition.replacementName?(this.replacementName=this.definition.replacementName,this.specifiedComponentName=this.replacementName):this.replacementName=this.upstreamComponentName,!this.definition.variableName)throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: must have a variableName`);this.originalDownstreamVariableNames=[this.definition.variableName],this.definition.compositeComponentType&&(this.compositeComponentType=this.definition.compositeComponentType),this.returnSingleVariableValue=!0,this.variablesOptional=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.replacementName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.replacementName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.replacementName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.replacementName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!e.replacementOf)return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};let t=e.replacementOf;if(this.compositeComponentType)for(;!this.dependencyHandler.componentInfoObjects.isInheritedComponentType({inheritedComponentType:t.componentType,baseComponentType:this.compositeComponentType});){if(!t.replacementOf)return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};t=t.replacementOf}return{success:!0,downstreamComponentNames:[t.componentName],downstreamComponentTypes:[t.componentType]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(SourceCompositeStateVariableDependency);class SourceCompositeIdentityDependency extends Dependency{static dependencyType="sourceCompositeIdentity";setUpParameters(){this.definition.replacementName?(this.replacementName=this.definition.replacementName,this.specifiedComponentName=this.replacementName):this.replacementName=this.upstreamComponentName,this.returnSingleComponent=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.replacementName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.replacementName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.replacementName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.replacementName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!e.replacementOf)return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};let t=e.replacementOf;return{success:!0,downstreamComponentNames:[t.componentName],downstreamComponentTypes:[t.componentType]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(SourceCompositeIdentityDependency);class ShadowSourceDependency extends Dependency{static dependencyType="shadowSource";setUpParameters(){if(this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName,this.definition.variableNames){if(!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames}else this.originalDownstreamVariableNames=[];this.returnSingleComponent=!0,this.variablesOptional=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!e.shadows)return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};let t=e.shadows.componentName,n=this.dependencyHandler._components[t];return n?{success:!0,downstreamComponentNames:[n.componentName],downstreamComponentTypes:[n.componentType]}:{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(ShadowSourceDependency);class UnlinkedCopySourceDependency extends Dependency{static dependencyType="unlinkedCopySource";setUpParameters(){if(this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName,this.definition.variableNames){if(!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames}else this.originalDownstreamVariableNames=[];this.returnSingleComponent=!0,this.variablesOptional=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!e.unlinkedCopySource)return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};let t=e.unlinkedCopySource,n=this.dependencyHandler._components[t];return n?{success:!0,downstreamComponentNames:[n.componentName],downstreamComponentTypes:[n.componentType]}:{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(UnlinkedCopySourceDependency);class PrimaryShadowDependency extends Dependency{static dependencyType="primaryShadow";setUpParameters(){if(this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName,this.definition.variableNames){if(!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames}else this.originalDownstreamVariableNames=[];this.returnSingleComponent=!0,this.variablesOptional=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}let t=this.dependencyHandler.updateTriggers.primaryShadowDependencies[this.componentName];if(t||(t=this.dependencyHandler.updateTriggers.primaryShadowDependencies[this.componentName]=[]),t.includes(this)||t.push(this),!e.primaryShadow)return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};let n=e.primaryShadow,r=this.dependencyHandler._components[n];return r?{success:!0,downstreamComponentNames:[r.componentName],downstreamComponentTypes:[r.componentType]}:{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(PrimaryShadowDependency);class AdapterSourceStateVariableDependency extends Dependency{static dependencyType="adapterSourceStateVariable";setUpParameters(){if(this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName,!this.definition.variableName)throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: must have a variableName`);this.originalDownstreamVariableNames=[this.definition.variableName],this.returnSingleVariableValue=!0,this.variablesOptional=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!e.adaptedFrom)return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};let t=e.adaptedFrom;return{success:!0,downstreamComponentNames:[t.componentName],downstreamComponentTypes:[t.componentType]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(AdapterSourceStateVariableDependency);class AdapterSourceDependency extends Dependency{static dependencyType="adapterSource";setUpParameters(){if(this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName,this.definition.variableNames){if(!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames}else this.originalDownstreamVariableNames=[];this.returnSingleComponent=!0,this.variablesOptional=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!e.adaptedFrom)return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};let t=e.adaptedFrom;return{success:!0,downstreamComponentNames:[t.componentName],downstreamComponentTypes:[t.componentType]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(AdapterSourceDependency);class CountAmongSiblingsDependency extends Dependency{static dependencyType="countAmongSiblingsOfSameType";setUpParameters(){this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!e.parentName)return console.warn(`component ${this.componentName} does not have a parent for state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}.`),{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};this.parentName=e.parentName;let t=this.dependencyHandler._components[this.parentName];if(!t){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.parentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}let n=this.dependencyHandler.updateTriggers.childDependenciesByParent[this.parentName];if(n||(n=this.dependencyHandler.updateTriggers.childDependenciesByParent[this.parentName]=[]),n.includes(this)||n.push(this),!t.childrenMatched){if(!t.childrenMatchedWithPlaceholders){let e=t.unexpandedCompositesNotReady.length>0;if(!e&&t.unexpandedCompositesReady.length>0){for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.parentName,blockerType:"childMatches",blockerStateVariable:e,componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(e){for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.parentName,blockerType:"childMatches",blockerStateVariable:e,componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});for(let e of t.unexpandedCompositesNotReady)for(let t of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:e,blockerType:"stateVariable",blockerStateVariable:"readyToExpandWhenResolved",componentNameBlocked:this.upstreamComponentName,typeBlocked:"childMatches",stateVariableBlocked:t});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}}}return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]}}deleteFromUpdateTriggers(){let e=this.dependencyHandler.updateTriggers.childDependenciesByParent[this.parentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}let t=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName];if(t){let e=t.indexOf(this);-1!==e&&t.splice(e,1)}}async getValue(){let e=this.dependencyHandler.components[this.upstreamComponentName].componentType,t=this.dependencyHandler.components[this.parentName].activeChildren.filter((t=>t.componentType===e)),n=t.map((e=>e.componentName)).indexOf(this.upstreamComponentName)+1;if(this.parentName===this.dependencyHandler.core.documentName){let t=this.dependencyHandler.core.previousComponentTypeCounts[e];t&&(n+=t)}return{value:n,changes:{}}}}dependencyTypeArray.push(CountAmongSiblingsDependency);class AttributeTargetComponentNamesDependency extends StateVariableDependency{static dependencyType="attributeTargetComponentNames";setUpParameters(){this.attributeName=this.definition.attributeName,this.definition.parentName?(this.componentName=this.definition.parentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName}async getValue(){let e=null,t={};if(this.componentIdentitiesChanged&&(t.componentIdentitiesChanged=!0,this.componentIdentitiesChanged=!1),1===this.downstreamComponentNames.length){let t=this.dependencyHandler.components[this.componentName];t&&(e=t.attributes[this.attributeName],e=e?e.targetComponentNames:null)}return{value:e,changes:t}}}dependencyTypeArray.push(AttributeTargetComponentNamesDependency);class TargetComponentDependency extends Dependency{static dependencyType="targetComponent";setUpParameters(){let e=this.dependencyHandler._components[this.upstreamComponentName];if(this.target=e.doenetAttributes.target,this.target&&(this.targetComponentName=this.specifiedComponentName=e.doenetAttributes.targetComponentName),this.definition.variableNames){if(!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames}else this.originalDownstreamVariableNames=[];this.returnSingleComponent=!0}async determineDownstreamComponents(){if(!this.target)return{downstreamComponentNames:[],downstreamComponentTypes:[]};let e=this.dependencyHandler._components[this.targetComponentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.targetComponentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.targetComponentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.targetComponentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}return{success:!0,downstreamComponentNames:[this.targetComponentName],downstreamComponentTypes:[e.componentType]}}deleteFromUpdateTriggers(){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}dependencyTypeArray.push(TargetComponentDependency);class ValueDependency extends Dependency{static dependencyType="value";setUpParameters(){this.value=this.definition.value}async getValue(){return{value:this.value,changes:{}}}}dependencyTypeArray.push(ValueDependency);class FlagDependency extends ValueDependency{static dependencyType="flag";setUpParameters(){this.flagName=this.definition.flagName,this.value=this.dependencyHandler.core.flags[this.flagName]}}dependencyTypeArray.push(FlagDependency);class DoenetAttributeDependency extends StateVariableDependency{static dependencyType="doenetAttribute";setUpParameters(){this.attributeName=this.definition.attributeName,this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName}async getValue(){let e=null,t={};if(this.componentIdentitiesChanged&&(t.componentIdentitiesChanged=!0,this.componentIdentitiesChanged=!1),1===this.downstreamComponentNames.length){e=this.dependencyHandler.components[this.downstreamComponentNames[0]].doenetAttributes[this.attributeName]}return{value:e,changes:t}}}dependencyTypeArray.push(DoenetAttributeDependency);class AttributePrimitiveDependency extends StateVariableDependency{static dependencyType="attributePrimitive";setUpParameters(){this.attributeName=this.definition.attributeName,this.definition.parentName?(this.componentName=this.definition.parentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName}async getValue(){let e=null,t={};if(this.componentIdentitiesChanged&&(t.componentIdentitiesChanged=!0,this.componentIdentitiesChanged=!1),1===this.downstreamComponentNames.length){let t=this.dependencyHandler.components[this.componentName];t&&(e=t.attributes[this.attributeName],e=e?e.primitive:null)}return{value:e,changes:t}}}dependencyTypeArray.push(AttributePrimitiveDependency);class SerializedChildrenDependency extends Dependency{static dependencyType="serializedChildren";setUpParameters(){this.definition.parentName?(this.parentName=this.definition.parentName,this.specifiedComponentName=this.parentName):this.parentName=this.upstreamComponentName}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.parentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.parentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}return{success:!0,downstreamComponentNames:[this.parentName],downstreamComponentTypes:[e.componentType]}}async getValue(){return{value:this.dependencyHandler._components[this.parentName].serializedChildren,changes:{}}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(SerializedChildrenDependency);class DoenetMLDependency extends Dependency{static dependencyType="doenetML";setUpParameters(){this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName,this.displayOnlyChildren=this.definition.displayOnlyChildren}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}return{success:!0,downstreamComponentNames:[this.componentName],downstreamComponentTypes:[e.componentType]}}async getValue(){return{value:this.dependencyHandler.core.requestComponentDoenetML(this.componentName,this.displayOnlyChildren),changes:{}}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(DoenetMLDependency);class VariantsDependency extends Dependency{static dependencyType="variants";setUpParameters(){this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}return{success:!0,downstreamComponentNames:[this.componentName],downstreamComponentTypes:[e.componentType]}}async getValue(){return{value:this.dependencyHandler._components[this.componentName].variants,changes:{}}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(VariantsDependency);class CounterDependency extends Dependency{static dependencyType="counter";setUpParameters(){this.counterName=this.definition.counterName,this.componentName=this.upstreamComponentName}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName],t=e.counters[this.counterName];return t||(t=e.counters[this.counterName]={dependencies:[],componentList:[],value:null}),t.dependencies.includes(this)||t.dependencies.push(this),await this.dependencyHandler.collateCountersAndPropagateToAncestors(e),{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]}}async getValue(){return{value:this.dependencyHandler._components[this.componentName].counters[this.counterName].value,changes:{}}}}dependencyTypeArray.push(CounterDependency);class DetermineDependenciesDependency extends Dependency{static dependencyType="determineDependencies";setUpParameters(){if(this.recalculateDependencies=!0,this.definition.componentName?this.componentName=this.definition.componentName:this.componentName=this.upstreamComponentName,void 0===this.definition.variableNames)throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames is not defined`);this.originalDownstreamVariableNames=this.definition.variableNames,this.returnSingleComponent=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"determineDependencies",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!0,downstreamComponentNames:[this.componentName],downstreamComponentTypes:[e.componentType]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}async markStale(){let e=this.dependencyHandler._components[this.upstreamComponentName];for(let t of this.upstreamVariableNames)if(!(e&&e.state[t]&&e.state[t].currentlyResolving)){await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"determineDependencies",blockerStateVariable:t,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:t});for(let e in this.dependencyHandler.downstreamDependencies[this.upstreamComponentName][t]){"determineDependencies"!==this.dependencyHandler.downstreamDependencies[this.upstreamComponentName][t][e].dependencyType&&await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"determineDependencies",blockerStateVariable:t,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:t,dependencyBlocked:e})}}}}dependencyTypeArray.push(DetermineDependenciesDependency);class FileDependency extends Dependency{static dependencyType="file";setUpParameters(){this.cid=this.definition.cid,this.uri=this.definition.uri,this.fileType=this.definition.fileType}async getValue(){let e;if(this.cid){if("csv"!==this.fileType.toLowerCase())return{value:null,changes:{}};return e="csv",{value:await retrieveTextFileForCid(this.cid,e),changes:{}}}{let e=await fetch(this.uri);if(e.ok){return{value:await e.text(),changes:{}}}return{value:null,changes:{}}}}}dependencyTypeArray.push(FileDependency);var appliedFunctionSymbolsDefault=["abs","exp","log","ln","log10","sign","sqrt","erf","cos","cosh","acos","acosh","arccos","arccosh","cot","coth","acot","acoth","arccot","arccoth","csc","csch","acsc","acsch","arccsc","arccsch","sec","sech","asec","asech","arcsec","arcsech","sin","sinh","asin","asinh","arcsin","arcsinh","tan","tanh","atan","atan2","atanh","arctan","arctanh","arg","min","max","mean","median","floor","ceil","round","sum","prod","variance","std","count","mod","re","im","det","trace","nPr","nCr"],appliedFunctionSymbolsDefaultLatex=["abs","exp","log","ln","log10","sign","sqrt","erf","cos","cosh","acos","acosh","arccos","arccosh","cot","coth","acot","acoth","arccot","arccoth","csc","csch","acsc","acsch","arccsc","arccsch","sec","sech","asec","asech","arcsec","arcsech","sin","sinh","asin","asinh","arcsin","arcsinh","tan","tanh","atan","atan2","atanh","arctan","arctanh","arg","min","max","mean","median","floor","ceil","round","sum","prod","variance","std","count","mod","Re","Im","det","trace","nPr","nCr"];let allowedLatexSymbols=["alpha","beta","gamma","Gamma","delta","Delta","epsilon","zeta","eta","theta","Theta","iota","kappa","lambda","Lambda","mu","nu","xi","Xi","pi","Pi","rho","sigma","Sigma","tau","Tau","upsilon","Upsilon","phi","Phi","chi","psi","Psi","omega","Omega","partial","varnothing","emptyset","angle","circ","$","%"];var textToAst$1=new me$3.converters.textToAstObj({appliedFunctionSymbols:appliedFunctionSymbolsDefault});function getFromText({functionSymbols:e,appliedFunctionSymbols:t=appliedFunctionSymbolsDefault,splitSymbols:n=!0,parseScientificNotation:r=!1}){return a=>me$3.fromAst(new me$3.converters.textToAstObj({appliedFunctionSymbols:t,functionSymbols:e,splitSymbols:n,parseScientificNotation:r}).convert(a))}var latexToAst=new me$3.converters.latexToAstObj({appliedFunctionSymbols:appliedFunctionSymbolsDefaultLatex,allowedLatexSymbols:allowedLatexSymbols});function getFromLatex({functionSymbols:e,appliedFunctionSymbols:t=appliedFunctionSymbolsDefaultLatex,splitSymbols:n=!0,parseScientificNotation:r=!1}){return n?n=>me$3.fromAst(new me$3.converters.latexToAstObj({appliedFunctionSymbols:t,functionSymbols:e,allowedLatexSymbols:allowedLatexSymbols,parseScientificNotation:r}).convert(wrapWordIncludingNumberWithVar(n,r))):n=>me$3.fromAst(new me$3.converters.latexToAstObj({appliedFunctionSymbols:t,functionSymbols:e,allowedLatexSymbols:allowedLatexSymbols,parseScientificNotation:r}).convert(wrapWordWithVar(n,r)))}function normalizeMathExpression({value:e,simplify:t,expand:n=!1,createVectors:r=!1,createIntervals:a=!1}){return r&&(e=e.tuples_to_vectors()),a&&(e=e.to_intervals()),n&&(e=e.expand()),"full"===t?e.simplify():"numbers"===t?e.evaluate_numbers():"numberspreserveorder"===t?e.evaluate_numbers({skip_ordering:!0}):e}function findFiniteNumericalValue(e){if(void 0!==e)return Number.isFinite(e)||void 0!==e.evaluate_to_constant&&(e=e.evaluate_to_constant(),Number.isFinite(e))?e:null}function convertValueToMathExpression(e){return e instanceof me$3.class?e:"number"==typeof e||"string"==typeof e||Array.isArray(e)?me$3.fromAst(e):me$3.fromAst("_")}function returnNVariables(e,t){if(!Number.isInteger(e)||e<1)return[];let n=t.length;if(0===n){if(1===e)return[me$3.fromAst("x")];if(2===e)return[me$3.fromAst("x"),me$3.fromAst("y")];if(3===e)return[me$3.fromAst("x"),me$3.fromAst("y"),me$3.fromAst("z")];{let t=[];for(let n=1;n<=e;n++)t.push(me$3.fromAst(textToAst$1.convert(`x_${n}`)));return t}}if(new Set(t.map((e=>e.toString()))).sizee.toString()))],a=[...t];for(let t=n+1;t<=e;t++){let n;n=1==t?e>3?["x_1"]:["x"]:2==t?e>3?["x_2","y_2"]:["y","x_2"]:3==t?e>3?["x_3","y_3","z_3"]:["z","x_3","z_3"]:["x","y","z","u","v","w","X","Y","Z"].map((e=>`${e}_${t}`));let i=!1;for(let e of n)if(!r.includes(e)){a.push(me$3.fromAst(textToAst$1.convert(e))),r.push(e),i=!0;break}if(!i){let e=n[0];a.push(me$3.fromAst(textToAst$1.convert(e))),r.push(e),console.warn("Variables added were not unique")}}return a}async function preprocessMathInverseDefinition({desiredValue:e,stateValues:t,variableName:n="value",arrayKey:r,workspace:a}){if(!vectorOperators.includes(e.tree[0])||!e.tree.includes())return{desiredValue:e};let i,s=n+"Ast";if(void 0!==r&&(s+=`_${r}`),a[s])i=a[s].slice(0,e.tree.length);else{let a=await t[n];a&&void 0!==r&&(a=a[r]),a&&vectorOperators.includes(a.tree[0])&&(i=a.tree.slice(0,e.tree.length))}if(i){let t=[],n=!1;for(let[r,a]of e.tree.entries())void 0===a?(n=!0,t.push(r)):i[r]=a;return e=me$3.fromAst(i),a[s]=i,n?{desiredValue:e,vectorComponentsNotAffected:t}:{desiredValue:e}}{let t=[];for(let n of e.tree.slice(1))void 0===n?t.push("_"):t.push(n);return{desiredValue:e=me$3.fromAst([e.tree[0],...t])}}}function normalizeLatexString(e,{unionFromU:t=!1}={}){let n=[["α","\\alpha "],["β","\\beta "],["ϐ","\\beta "],["Γ","\\Gamma "],["γ","\\gamma "],["Δ","\\Delta "],["δ","\\delta "],["ε","\\epsilon "],["ϵ","\\epsilon "],["ζ","\\zeta "],["η","\\eta "],["Θ","\\Theta "],["ϴ","\\Theta "],["θ","\\theta "],["ᶿ","\\theta "],["ϑ","\\theta "],["ι","\\iota "],["κ","\\kappa "],["Λ","\\Lambda "],["λ","\\lambda "],["μ","\\mu "],["µ","\\mu "],["ν","\\nu "],["Ξ","\\Xi "],["ξ","\\xi "],["Π","\\Pi "],["π","\\pi "],["ϖ","\\pi "],["ρ","\\rho "],["ϱ","\\rho "],["Σ","\\Sigma "],["σ","\\sigma "],["ς","\\sigma "],["τ","\\tau "],["Υ","\\Upsilon "],["υ","\\upsilon "],["Φ","\\Phi "],["φ","\\phi "],["ϕ","\\phi "],["Ψ","\\Psi "],["ψ","\\psi "],["Ω","\\Omega "],["ω","\\omega "],["−","-"],["⋅"," \\cdot "],["·"," \\cdot "],["∪"," \\cup "],["∩"," \\cap "],["∞"," \\infty "],["∅"," \\emptyset "]];for(let t of n)e=e.replaceAll(t[0],t[1]);let r=e.match(/^(\\ )*(\\ldots|\.(\\ )*\.(\\ )*\.)(\\ )*(.*)$/);if(r){let t=r[6];e=","!==t[0]?"\\ldots,"+t:"\\ldots"+t}let a=e.match(/^(.*?)(\\ )*(\\ldots|\.(\\ )*\.(\\ )*\.)(\\ )*$/);if(a){let t=a[1];e=","!==t[t.length-1]?t+",\\ldots":t+"\\ldots"}return e=(e=e.replaceAll(/(\b|\\ )or(\b|\\ )/g,"$1\\lor$2")).replaceAll(/(\b|\\ )and(\b|\\ )/g,"$1\\land$2"),t&&(e=e.replaceAll(/(\b|\\ )U(\b|\\ )/g,"$1\\cup$2")),e}function isValidVariable(e){let t=e.tree,n=!0;return"string"==typeof t?"_"===t&&(n=!1):(!Array.isArray(t)||"_"!==t[0]||"string"!=typeof t[1]||"string"!=typeof t[2]&&"number"!=typeof t[2])&&(n=!1),n}function mathStateVariableFromNumberStateVariable({numberVariableName:e="number",mathVariableName:t="math",isPublic:n=!1}={}){let r={returnDependencies:()=>({number:{dependencyType:"stateVariable",variableName:e}}),definition:function({dependencyValues:e}){return{setValue:{[t]:numberToMathExpression(e.number)}}},inverseDefinition:function({desiredStateVariableValues:e}){let n=e[t].evaluate_to_constant();return null===n&&(n=NaN),{success:!0,instructions:[{setDependency:"number",desiredValue:n}]}}};return n&&(r.public=!0,r.shadowingInstructions={createComponentOfType:"math"}),r}function numberToMathExpression(e){let t;if("number"==typeof e?.re&&"number"==typeof e?.im)if(0===e.im)t=e.re;else{let n;n=1===e.im?"i":-1===e.im?["-","i"]:["*",e.im,"i"],t=0===e.re?n:["+",e.re,n]}else t=e;return me$3.fromAst(t)}function roundForDisplay({value:e,dependencyValues:t,usedDefault:n}){let r;return!n.displayDigits&&t.displayDigits>=1||n.displayDecimals||!Number.isFinite(t.displayDecimals)?(r=t.displayDigits>=1?me$3.round_numbers_to_precision(e,t.displayDigits):me$3.round_numbers_to_precision(e,10),t.displaySmallAsZero>0&&(r=me$3.evaluate_numbers(r,{skip_ordering:!0,set_small_zero:t.displaySmallAsZero}))):r=me$3.round_numbers_to_decimals(e,t.displayDecimals),r}function mergeListsWithOtherContainers(e){if(!Array.isArray(e))return e;let t=e[0],n=e.slice(1);return[...vectorOperators,"list","set"].includes(t)&&(n=n.reduce(((e,t)=>Array.isArray(t)&&"list"===t[0]?[...e,...t.slice(1)]:[...e,t]),[])),n=n.map((e=>mergeListsWithOtherContainers(e))),[t,...n]}function wrapWordWithVar(e,t){let n="",r=/\\operatorname\s*{[^{}]*}/,a=e.match(r);for(;a;){let i=a.index,s=i+a[0].length;n+=wrapWordWithVarSub(e.substring(0,i),t),n+=e.substring(i,s),a=(e=e.substring(s)).match(r)}return n+=wrapWordWithVarSub(e,t),n}function wrapWordWithVarSub(e,t){let n="";const r=/([^a-zA-Z0-9]?)([a-zA-Z][a-zA-Z0-9]+)([^a-zA-Z0-9]?)/;let a;if(t){const e="(E[+\\-]?[0-9]+\\s*($|(?=\\,|&|\\||\\\\\\||\\)|\\}|\\\\}|\\]|\\\\\\\\|\\\\end)))";a=new RegExp("([0-9]+(\\.[0-9]*)?"+e+")|(\\.[0-9]+"+e+")")}let i=e.match(r);for(;i;){let s=i.index,o=s+i[0].length-i[3].length;if(t){let t=e.match(a);if(t&&t.indexs){n+=e.substring(0,o),i=(e=e.substring(o)).match(r);continue}}if("\\"===i[1])n+=e.substring(0,o),e=e.substring(o);else{let t=s+i[1].length;n+=e.substring(0,t),n+=`\\operatorname{${i[2]}}`,e=e.substring(o)}i=e.match(r)}return n+=e,n}function wrapWordIncludingNumberWithVar(e,t){let n="",r=/\\operatorname\s*{[^{}]*}/,a=e.match(r);for(;a;){let i=a.index,s=i+a[0].length;n+=wrapWordIncludingNumberWithVarSub(e.substring(0,i),t),n+=e.substring(i,s),a=(e=e.substring(s)).match(r)}return n+=wrapWordIncludingNumberWithVarSub(e,t),n}function wrapWordIncludingNumberWithVarSub(e,t){let n="";const r=/([^a-zA-Z0-9\s]?\s*)([a-zA-Z][a-zA-Z0-9]*[0-9][a-zA-Z0-9]*)([^a-zA-Z0-9]?)/;let a;if(t){const e="(E[+\\-]?[0-9]+\\s*($|(?=\\,|&|\\||\\\\\\||\\)|\\}|\\\\}|\\]|\\\\\\\\|\\\\end)))";a=new RegExp("([0-9]+(\\.[0-9]*)?"+e+")|(\\.[0-9]+"+e+")")}let i=e.match(r);for(;i;){let s=i.index,o=s+i[0].length-i[3].length;if(t){let t=e.match(a);if(t&&t.indexs){n+=e.substring(0,o),i=(e=e.substring(o)).match(r);continue}}if("\\"===i[1]||"^"===i[1][0]||"_"===i[1][0])n+=e.substring(0,o),e=e.substring(o);else{let t=s+i[1].length;n+=e.substring(0,t),n+=`\\operatorname{${i[2]}}`,e=e.substring(o)}i=e.match(r)}return n+=e,n}function stripLatex(e){return e.replaceAll("\\,","").replaceAll(/\\operatorname{([^{}]*)}/g,"$1")}function superSubscriptsToUnicode(e){let t={0:"₀",1:"₁",2:"₂",3:"₃",4:"₄",5:"₅",6:"₆",7:"₇",8:"₈",9:"₉","+":"₊","-":"₋"," ":""},n={0:"⁰",1:"¹",2:"²",3:"³",4:"⁴",5:"⁵",6:"⁶",7:"⁷",8:"⁸",9:"⁹","+":"⁺","-":"⁻"," ":""};function r(e,n){let r="";for(let e of n)r+=t[e];return r}function a(e,t){let r="";for(let e of t)r+=n[e];return r}return e=(e=(e=(e=e.replaceAll(/_(\d+)/g,r)).replaceAll(/_\(([\d +-]+)\)/g,r)).replaceAll(/\^(\d+)/g,a)).replaceAll(/\^\(([\d +-]+)\)/g,a)}function unicodeToSuperSubscripts(e){let t={"₀":"0","₁":"1","₂":"2","₃":"3","₄":"4","₅":"5","₆":"6","₇":"7","₈":"8","₉":"9","₊":"+","₋":"-"},n={"⁰":"0","¹":"1","²":"2","³":"3","⁴":"4","⁵":"5","⁶":"6","⁷":"7","⁸":"8","⁹":"9","⁺":"+","⁻":"-"};return e=(e=e.replaceAll(/([\u2080\u2081\u2082\u2083\u2084\u2085\u2086\u2087\u2088\u2089\u208A\u208B]+)/g,(function(e,n){let r="";for(let e of n)r+=t[e];return"_("+r+")"}))).replaceAll(/([\u2070\u00B9\u00B2\u00B3\u2074\u2075\u2076\u2077\u2078\u2079\u207A\u207B]+)/g,(function(e,t){let r="";for(let e of t)r+=n[e];return"^("+r+")"}))}const vectorOperators=["vector","altvector","tuple"];function renameStateVariable({stateVariableDefinitions:e,oldName:t,newName:n}){let r=e[n]=e[t];if(delete e[t],r.additionalStateVariablesDefined){let e=r.additionalStateVariablesDefined.indexOf(t);-1!==e&&(r.additionalStateVariablesDefined[e]=n)}let a=r.definition,i=["setValue","useEssentialOrDefaultValue","setEssentialValue"],s=["noChanges"];r.definition=function(e){let r=a(e);for(let e of i)r[e]&&t in r[e]&&(r[e][n]=r[e][t],delete r[e][t]);for(let e of s)if(r[e]){let a=r[e].indexOf(t);-1!==a&&(r[e][a]=n)}return r};let o=r.inverseDefinition;o&&(r.inverseDefinition=async function(e){let r=e.desiredStateVariableValues;r[t]=r[n],delete r[n];let a=await o(e);if(a.success)for(let e of a.instructions)e.setEssentialValue===t&&(e.setEssentialValue=n);return a})}function returnDefaultGetArrayKeysFromVarName(e){return e>1?function({arrayEntryPrefix:e,varEnding:t,arraySize:n,nDimensions:r}){let a=t.split("_").map((e=>Number(e)-1));return a.length===r&&a.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?a.every(((e,t)=>e=0?n?rcrypto.getRandomValues(new Uint8Array(e)).reduce(((e,t)=>e+=(t&=63)<36?t.toString(36):t<62?(t-26).toString(36).toUpperCase():t>62?"-":"_"),""),core,queuedRequestActions=[];async function createCore(e){core=new Core(e),core.getInitializedPromise().then((()=>{for(let e of queuedRequestActions)core.requestAction(e);queuedRequestActions=[]}))}async function returnAllStateVariables(e){if(!e.components)return{};let t={};for(let n in e.components){let r=e.components[n],a=t[n]={componentName:n,componentType:r.componentType,stateValues:{}};for(let e in r.state)a.stateValues[e]=removeFunctionsMathExpressionClass(await r.state[e].value);a.activeChildren=r.activeChildren.map((e=>e.componentName?{componentName:e.componentName,componentType:e.componentType}:e)),r.replacements&&(a.replacements=r.replacements.map((e=>e.componentName?{componentName:e.componentName,componentType:e.componentType}:e)),void 0!==r.replacementsToWithhold&&(a.replacementsToWithhold=r.replacementsToWithhold)),a.sharedParameters=removeFunctionsMathExpressionClass(r.sharedParameters)}return t}function removeFunctionsMathExpressionClass(e){if(e instanceof me$3.class)e=e.tree;else if("function"==typeof e)e=void 0;else if(Array.isArray(e))e=e.map((e=>removeFunctionsMathExpressionClass(e)));else if("object"==typeof e&&null!==e){let t={};for(let n in e)t[n]=removeFunctionsMathExpressionClass(e[n]);e=t}return e}onmessage=function(e){"createCore"===e.data.messageType?createCore(e.data.args):"requestAction"===e.data.messageType?core?.initialized?core.requestAction(e.data.args):queuedRequestActions.push(e.data.args):"returnAllStateVariables"===e.data.messageType?(console.log("all components"),console.log(core._components),returnAllStateVariables(core).then((e=>{postMessage({messageType:"returnAllStateVariables",args:e})}))):"visibilityChange"===e.data.messageType?core.handleVisibilityChange(e.data.args):"terminate"===e.data.messageType?core.terminate().then((()=>{postMessage({messageType:"terminated"})})):"navigatingToComponent"===e.data.messageType?core.handleNavigatingToComponent(e.data.args.componentName):"submitAllAnswers"===e.data.messageType&&core.requestAction({componentName:core.documentName,actionName:"submitAllAnswers",args:e.data.args})};let styleAttributes={lineColor:{componentType:"text"},lineColorWord:{componentType:"text"},lineOpacity:{componentType:"number"},lineWidth:{componentType:"number"},lineWidthWord:{componentType:"text"},lineStyle:{componentType:"text"},lineStyleWord:{componentType:"text"},markerColor:{componentType:"text"},markerColorWord:{componentType:"text"},markerStyle:{componentType:"text"},markerStyleWord:{componentType:"text"},markerSize:{componentType:"number"},fillColor:{componentType:"text"},fillColorWord:{componentType:"text"},fillOpacity:{componentType:"number"}},defaultStyle={lineColor:"#648FFF",lineColorWord:"blue",lineOpacity:.7,lineWidth:4,lineWidthWord:"thick",lineStyle:"solid",lineStyleWord:"",markerColor:"#648FFF",markerColorWord:"blue",markerStyle:"circle",markerStyleWord:"point",markerSize:5,fillColor:"#648FFF",fillColorWord:"blue",fillOpacity:.3};function returnDefaultStyleDefinitions(){return{1:{lineColor:"#648FFF",lineColorWord:"blue",lineOpacity:.7,lineWidth:4,lineWidthWord:"thick",lineStyle:"solid",lineStyleWord:"",markerColor:"#648FFF",markerColorWord:"blue",markerStyle:"circle",markerStyleWord:"point",markerSize:5,fillColor:"#648FFF",fillColorWord:"blue",fillOpacity:.3},2:{lineColor:"#D4042D",lineColorWord:"red",lineOpacity:.7,lineWidth:2,lineWidthWord:"",lineStyle:"solid",lineStyleWord:"",markerColor:"#D4042D",markerColorWord:"red",markerStyle:"square",markerStyleWord:"square",markerSize:5,fillColor:"#D4042D",fillColorWord:"red",fillOpacity:.3},3:{lineColor:"#F19143",lineColorWord:"orange",lineOpacity:.7,lineWidth:3,lineWidthWord:"",lineStyle:"solid",lineStyleWord:"",markerColor:"#F19143",markerColorWord:"orange",markerStyle:"triangle",markerStyleWord:"triangle",markerSize:5,fillColor:"#F19143",fillColorWord:"orange",fillOpacity:.3},4:{lineColor:"#644CD6",lineColorWord:"purple",lineOpacity:.7,lineWidth:2,lineWidthWord:"",lineStyle:"solid",lineStyleWord:"",markerColor:"#644CD6",markerColorWord:"purple",markerStyle:"diamond",markerStyleWord:"diamond",markerSize:5,fillColor:"#644CD6",fillColorWord:"purple",fillOpacity:.3},5:{lineColor:"black",lineColorWord:"black",lineOpacity:.7,lineWidth:1,lineWidthWord:"thin",lineStyle:"solid",lineStyleWord:"",markerColor:"black",markerColorWord:"black",markerStyle:"circle",markerStyleWord:"point",markerSize:5,fillColor:"black",fillColorWord:"black",fillOpacity:.3},6:{lineColor:"gray",lineColorWord:"gray",lineOpacity:.7,lineWidth:1,lineWidthWord:"thin",lineStyle:"dotted",lineStyleWord:"dotted",markerColor:"gray",markerColorWord:"gray",markerStyle:"circle",markerStyleWord:"point",markerSize:5,fillColor:"gray",fillColorWord:"gray",fillOpacity:.3}}}function returnStyleDefinitionStateVariables(){let e={setupChildren:{returnDependencies:()=>({setupChildren:{dependencyType:"child",childGroups:["setups"],proceedIfAllChildrenNotMatched:!0}}),definition:({dependencyValues:e})=>({setValue:{setupChildren:e.setupChildren}})}};return e.styleDefinitions={stateVariablesDeterminingDependencies:["setupChildren"],returnDependencies({stateValues:e}){let t={ancestorWithStyle:{dependencyType:"ancestor",variableNames:["styleDefinitions"]},setupChildren:{dependencyType:"child",childGroups:["setups"],proceedIfAllChildrenNotMatched:!0}};for(let n of e.setupChildren)t[`styleDefinitionsOf${n.componentName}`]={dependencyType:"child",parentName:n.componentName,childGroups:["styleDefinitions"],variableNames:["value"]};return t},definition({dependencyValues:e}){let t,n={};e.ancestorWithStyle&&(t=e.ancestorWithStyle.stateValues.styleDefinitions),t||(t=returnDefaultStyleDefinitions());for(let e in t)n[e]=Object.assign({},t[e]);let r=[];for(let t of e.setupChildren)r.push(...e[`styleDefinitionsOf${t.componentName}`]);for(let e of r){let t=e.stateValues.value;for(let e in t){let r=n[e];r||(r=n[e]=Object.assign({},defaultStyle));let a=Object.assign({},t[e]);"markerColor"in a&&!("markerColorWord"in a)&&(a.markerColorWord=a.markerColor),"markerStyle"in a&&!("markerStyleWord"in a)&&(a.markerStyleWord=a.markerStyle,"circle"===a.markerStyleWord?a.markerStyleWord="point":"triangle"===a.markerStyleWord.slice(0,8)&&(a.markerStyleWord="triangle")),"lineColor"in a&&!("lineColorWord"in a)&&(a.lineColorWord=a.lineColor),"fillColor"in a&&!("fillColorWord"in a)&&(a.fillColorWord=a.fillColor),"lineWidth"in a&&!("lineWidthWord"in a)&&(a.lineWidth>=4?a.lineWidthWord="thick":a.lineWidth<=1?a.lineWidthWord="thin":a.lineWidthWord=""),"lineStyle"in a&&!("lineStyleWord"in a)&&("dashed"===a.lineStyle?a.lineStyleWord="dashed":"dotted"===a.lineStyle?a.lineStyleWord="dotted":a.lineStyleWord=""),Object.assign(r,a)}}return{setValue:{styleDefinitions:n}}}},e}function returnSelectedStyleStateVariableDefinition(){return{selectedStyle:{forRenderer:!0,willNeverBeEssential:!0,returnDependencies:()=>({styleNumber:{dependencyType:"stateVariable",variableName:"styleNumber"},ancestorWithStyle:{dependencyType:"ancestor",variableNames:["styleDefinitions"]}}),definition:function({dependencyValues:e}){let t=e.ancestorWithStyle.stateValues.styleDefinitions;t||(t=returnDefaultStyleDefinitions());let n=t[e.styleNumber];return void 0===n&&(n=defaultStyle),{setValue:{selectedStyle:n}}}}}}function enumerateSelectionCombinations({numberOfIndices:e,numberOfOptions:t,maxNumber:n=1/0,withReplacement:r=!1,skipZero:a=!1}){if(1===e){let e=[...Array(t).keys()];return e=e.slice(1),a||(e=[...e,0]),e=e.slice(0,n),e=e.map((e=>[e])),e}let i=enumerateSelectionCombinations({numberOfIndices:e-1,numberOfOptions:t,maxNumber:n,withReplacement:r,skipZero:!r}),s=[],o=0;for(let e of i)for(let r=1;r<=t;r++){let i=[r%t,...e.map((e=>(r+e)%t))];if((!a||!i.includes(0))&&(s.push(i),o++,o>=n))return s}return s}function enumerateCombinations({numberOfOptionsByIndex:e,maxNumber:t=1/0}){let n=e.length;if(0===n)return[];let r=[];for(let t=0;t[...t,...e]),[]).reduce(((e,t)=>Math.max(e,t)),1);if(1===a){let n=e.reduce(((e,t)=>e*t));n=Math.min(n,t);let r=[];for(let t=0;tt%e));r.push(n)}return r}if(2===n){let n=a,r=me$3.math.lcm(...e),i=[],s=0;for(let a=0;a=t)return i}return i}let i=[];for(let t=0;t1?n.push(me$3.math.lcm(e[t],e[a])):n.push(null);i.push(n)}let s,o=i.reduce(((e,t)=>[...t,...e]),[]).filter((e=>null!==e)).reduce(((e,t)=>Math.min(e,t)),1/0);for(let e=0;e{if(0===e.length)n.push(a);else for(let i=0;i=t)return}};return r(e),n}function returnStandardSequenceAttributes(){return{type:{createPrimitiveOfType:"string",createStateVariable:"type",defaultPrimitiveValue:"number",toLowerCase:!0,validValues:["number","math","letters"]},from:{createComponentOfType:"_componentWithSelectableType"},to:{createComponentOfType:"_componentWithSelectableType"},step:{createComponentOfType:"math"},length:{createComponentOfType:"number"},exclude:{createComponentOfType:"_componentListWithSelectableType"}}}function returnStandardSequenceStateVariableDefinitions(){let e={specifiedFrom:{returnDependencies:()=>({fromAttr:{dependencyType:"attributeComponent",attributeName:"from",variableNames:["value"]}}),defaultValue:null,hasEssential:!0,essentialVarName:"from",definition:function({dependencyValues:e}){return null===e.fromAttr?{useEssentialOrDefaultValue:{specifiedFrom:!0}}:null===e.fromAttr.stateValues.value?{setValue:{specifiedFrom:NaN}}:{setValue:{specifiedFrom:e.fromAttr.stateValues.value}}}},specifiedTo:{returnDependencies:()=>({toAttr:{dependencyType:"attributeComponent",attributeName:"to",variableNames:["value"]}}),defaultValue:null,hasEssential:!0,essentialVarName:"to",definition:function({dependencyValues:e}){return null===e.toAttr?{useEssentialOrDefaultValue:{specifiedTo:!0}}:null===e.toAttr.stateValues.value?{setValue:{specifiedTo:NaN}}:{setValue:{specifiedTo:e.toAttr.stateValues.value}}}},specifiedLength:{returnDependencies:()=>({lengthAttr:{dependencyType:"attributeComponent",attributeName:"length",variableNames:["value"]}}),defaultValue:null,hasEssential:!0,essentialVarName:"length",definition:function({dependencyValues:e}){return null===e.lengthAttr?{useEssentialOrDefaultValue:{specifiedLength:!0}}:null===e.lengthAttr.stateValues.value?{setValue:{specifiedLength:NaN}}:{setValue:{specifiedLength:e.lengthAttr.stateValues.value}}}},specifiedStep:{returnDependencies:()=>({stepAttr:{dependencyType:"attributeComponent",attributeName:"step",variableNames:["value"]},type:{dependencyType:"stateVariable",variableName:"type"}}),defaultValue:null,hasEssential:!0,essentialVarName:"step",definition:function({dependencyValues:e}){if(null===e.stepAttr)return{useEssentialOrDefaultValue:{specifiedStep:!0}};let t=e.stepAttr.stateValues.value;return null===t?{setValue:{specifiedStep:NaN}}:{setValue:{specifiedStep:t}}}},specifiedExclude:{returnDependencies:()=>({excludeAttr:{dependencyType:"attributeComponent",attributeName:"exclude",variableNames:["values"]}}),defaultValue:[],hasEssential:!0,essentialVarName:"exclude",definition:function({dependencyValues:e}){return null===e.excludeAttr?{useEssentialOrDefaultValue:{specifiedExclude:!0}}:{setValue:{specifiedExclude:e.excludeAttr.stateValues.values}}}},lowercase:{returnDependencies:()=>({specifiedTo:{dependencyType:"stateVariable",variableName:"specifiedTo"},specifiedFrom:{dependencyType:"stateVariable",variableName:"specifiedFrom"}}),definition:function({dependencyValues:e}){let t=/^[A-Z]*$/,n=!0;return null!==e.specifiedFrom?t.test(e.specifiedFrom)&&(n=!1):null!==e.specifiedTo&&t.test(e.specifiedTo)&&(n=!1),{setValue:{lowercase:n}}}}};return e.validSequence={returnDependencies:()=>({specifiedLength:{dependencyType:"stateVariable",variableName:"specifiedLength"},specifiedStep:{dependencyType:"stateVariable",variableName:"specifiedStep"},specifiedFrom:{dependencyType:"stateVariable",variableName:"specifiedFrom"},specifiedTo:{dependencyType:"stateVariable",variableName:"specifiedTo"},type:{dependencyType:"stateVariable",variableName:"type"},lowercase:{dependencyType:"stateVariable",variableName:"lowercase"}}),definition:function({dependencyValues:e}){let t=!0;if(null!==e.specifiedLength&&(!Number.isInteger(e.specifiedLength)||e.specifiedLength<0)&&(console.warn("Invalid length of sequence. Must be a non-negative integer."),t=!1),null!==e.specifiedStep&&"math"!==e.type){let n=findFiniteNumericalValue(e.specifiedStep);Number.isFinite(n)||(console.warn("Invalid step of sequence. Must be a number for sequence of type "+e.type+"."),t=!1)}if(null!==e.specifiedFrom)if("number"===e.type){let n=findFiniteNumericalValue(e.specifiedFrom);Number.isFinite(n)||(console.warn("Invalid from of number sequence. Must be a number"),t=!1)}else Number.isNaN(e.specifiedFrom)&&(console.warn("Invalid from of sequence"),t=!1);if(null!==e.specifiedTo)if("number"===e.type){let n=findFiniteNumericalValue(e.specifiedTo);Number.isFinite(n)||(console.warn("Invalid to of number sequence. Must be a number"),t=!1)}else Number.isNaN(e.specifiedTo)&&(console.warn("Invalid to of sequence"),t=!1);return{setValue:{validSequence:t}}}},e.from={additionalStateVariablesDefined:["step","length","exclude"],returnDependencies:()=>({specifiedFrom:{dependencyType:"stateVariable",variableName:"specifiedFrom"},specifiedTo:{dependencyType:"stateVariable",variableName:"specifiedTo"},specifiedLength:{dependencyType:"stateVariable",variableName:"specifiedLength"},specifiedStep:{dependencyType:"stateVariable",variableName:"specifiedStep"},type:{dependencyType:"stateVariable",variableName:"type"},specifiedExclude:{dependencyType:"stateVariable",variableName:"specifiedExclude"},validSequence:{dependencyType:"stateVariable",variableName:"validSequence"}}),definition:function({dependencyValues:e}){let t=e.specifiedFrom,n=e.specifiedTo,r=e.specifiedStep,a=e.specifiedLength,i=[...e.specifiedExclude],s=e.type;if("math"===e.type)null!==n&&(n instanceof me$3.class||(n=me$3.fromAst(n))),null!==t&&(t instanceof me$3.class||(t=me$3.fromAst(t))),null!==r&&(r instanceof me$3.class||(r=me$3.fromAst(r)));else if(null!==r&&r instanceof me$3.class&&(r=r.evaluate_to_constant()),"letters"===e.type)null!==t&&(t=lettersToNumber$1(t)),null!==n&&(n=lettersToNumber$1(n)),i=i.map(lettersToNumber$1);else if("number"===e.type){null!==n&&(n=n instanceof me$3.class?n.evaluate_to_constant():Number(n)),null!==t&&(t=t instanceof me$3.class?t.evaluate_to_constant():Number(t));for(let[e,t]of i.entries())t instanceof me$3.class?i[e]=t.evaluate_to_constant():i[e]=Number(t)}if(e.validSequence){let e=calculateSequenceParameters({from:t,to:n,step:r,length:a,type:s});return e.exclude=i,{setValue:e}}return(!Number.isInteger(a)||a<0)&&(a=0),{setValue:{from:t,step:r,length:a,exclude:i}}}},e}function calculateSequenceParameters({from:e,to:t,step:n,length:r,type:a}){if(null===e)null===t?(e="math"===a?me$3.fromAst(1):1,null===n?(n="math"===a?me$3.fromAst(1):1,null===r&&(r=10)):null===r&&(r=10)):(null===n&&(n="math"===a?me$3.fromAst(1):1),null===r&&(r="math"===a?Math.floor((t.subtract(1).divide(n).evaluate_to_constant()+1)*(1+1e-14)):Math.floor(((t-1)/n+1)*(1+1e-14))),"math"===a?e=t.subtract(n.multiply(r-1)).simplify():(e=t-n*(r-1),"letters"===a&&e<1&&(e=t-n*((r=Math.floor(((t-1)/n+1)*(1+1e-14)))-1))));else if(null===t)null===n&&(n="math"===a?me$3.fromAst(1):1),null===r&&(r=10);else if(null===n)null===r?"math"===a?(n=me$3.fromAst(1),r=Math.floor(t.subtract(e).add(1).evaluate_to_constant()*(1+1e-14))):(n=1,r=Math.floor((t-e+1)*(1+1e-14))):"math"===a?n=t.subtract(e).divide(r-1):(n=(t-e)/(r-1),"letters"===a&&(n=Math.floor(n)));else{if(null!==r)throw Error("Can't define from, to, step, and length for sequence");r="math"===a?Math.floor(t.subtract(e).divide(n).add(1).evaluate_to_constant()*(1+1e-14)):Math.floor(((t-e)/n+1)*(1+1e-14))}return(!Number.isInteger(r)||r<0)&&(console.warn("Invalid length of sequence. Must be a non-negative integer."),r=0),{from:e,step:n,length:r}}function returnSequenceValues({from:e,step:t,length:n,exclude:r,type:a,lowercase:i,maxNum:s},o=!1){let l=[],u=0;for(let c=0;c0&&("math"===a?n=n.add(t.multiply(me$3.fromAst(c))).expand().simplify():n+=t*c),"math"===a){if(r.some((e=>e&&e.equals(n))))continue}else if("number"===a){if(r.some((e=>Math.abs(e-n)<=1e-14*Math.max(Math.abs(e),Math.abs(n)))))continue}else if(r.includes(n))continue;if("letters"===a&&(n=numberToLetters(n,i)),o?l.push({value:n,originalIndex:c}):l.push(n),u++,u===s)break}return l}function returnSequenceValueForIndex({index:e,from:t,step:n,length:r,exclude:a,type:i,lowercase:s}){if(!(e>=0&&(void 0===r||e0&&("math"===i?o=o.add(n.multiply(me$3.fromAst(e))).expand().simplify():o+=n*e),"math"===i){if(a.some((e=>e&&e.equals(o))))return null}else if("number"===i){if(a.some((e=>Math.abs(e-o)<=1e-14*Math.max(Math.abs(e),Math.abs(o)))))return null}else if(a.includes(o))return null;return"letters"===i&&(o=numberToLetters(o,s)),o}function lettersToNumber$1(e){try{e=e.toUpperCase()}catch(t){return void console.warn("Cannot convert "+e+" to a number")}let t=0,n=e.length,r=n;for(;(r-=1)>-1;){let a=e.charCodeAt(r)-64;if(a<1||a>26)return void console.warn("Cannot convert "+e+" to a number");t+=a*Math.pow(26,n-1-r)}return t}function numberToLetters(e,t){e--;let n=65;t&&(n=97);let r="";for(;;){let t=e%26;if(r=String.fromCharCode(n+t)+r,e<26)break;e=Math.floor(e/26)-1}return r}function getVariantsForDescendantsForUniqueVariants({variantIndex:e,serializedComponent:t,componentInfoObjects:n}){let r=t.variants?.descendantVariantComponents;if(void 0===r)return{success:!1};let a=r.map((e=>e.variants.numberOfVariants)),i=enumerateCombinations({numberOfOptionsByIndex:a,maxNumber:e})[e-1],s=[];for(let[e,t]of r.entries()){let r=n.allComponentClasses[t.componentType].getUniqueVariant({serializedComponent:t,variantIndex:i[e]+1,componentInfoObjects:n});if(!r.success)return{succss:!1};s.push(r.desiredVariant)}return{success:!0,desiredVariants:s}}function setUpVariantSeedAndRng({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n,useSubpartVariantRng:r=!1}){let a,i;if(e.variants&&(i=e.variants.desiredVariant),a=void 0!==i?.seed?i.seed.toString():r?t.subpartVariantRng().toString().slice(2):t.variantRng().toString().slice(2),t.variantSeed=a,t.variantRng=new t.rngClass(t.variantSeed),t.subpartVariantRng=new t.rngClass(t.variantSeed+"s"),i?.subvariants&&n)for(let e in i.subvariants){let t=i.subvariants[e],r=n[e];if(void 0===r)break;r.variants.desiredVariant=t}}function gatherVariantComponents({serializedComponents:e,componentInfoObjects:t}){let n=[];for(let r of e){if("object"!=typeof r)continue;if(r.variants||(r.variants={}),r.variants.isVariantComponent){n.push(r);continue}if(r.componentType in t.componentTypesCreatingVariants){r.variants.isVariantComponent=!0,n.push(r);continue}if(!r.children)continue;if(r.children.some((e=>"variantControl"===e.componentType))){r.variants.isVariantComponent=!0,n.push(r);continue}let e=gatherVariantComponents({serializedComponents:r.children,componentInfoObjects:t});e.length>0&&(r.variants.descendantVariantComponents=e,n.push(...e))}return n}function getNumberOfVariants({serializedComponent:e,componentInfoObjects:t}){let n;e.variants||(e.variants={});for(let t of e.children)if("variantControl"===t.componentType){n=t;break}let r="document"===e.componentType;if(!n){if(!r)return{success:!1};let n=e.children.filter((e=>e.componentType||""!==e.trim()));if(1===n.length&&t.isInheritedComponentType({inheritedComponentType:n[0].componentType,baseComponentType:"_sectioningComponent"})){let r=n[0],a=getNumberOfVariants({serializedComponent:r,componentInfoObjects:t});if(a.success)return e.variants.descendantVariantComponents=gatherVariantComponents({serializedComponents:e.children,componentInfoObjects:t}),e.variants.uniqueVariants=!0,e.variants.numberOfVariants=r.variants.numberOfVariants,e.variants.allPossibleVariants=r.variants.allPossibleVariants,e.variants.allVariantNames=r.variants.allVariantNames,e.variants.allPossibleVariantUniqueIndices=[...r.variants.allPossibleVariants.keys()].map((e=>e+1)),e.variants.allPossibleVariantSeeds=[...r.variants.allPossibleVariants.keys()].map((e=>(e+1).toString())),a}}return determineVariantsForSection({serializedComponent:e,componentInfoObjects:t,isDocument:r})}function determineVariantsForSection({serializedComponent:e,componentInfoObjects:t,isDocument:n=!1}){let r;void 0===e.variants&&(e.variants={});for(let t of e.children)if("variantControl"===t.componentType){r=t;break}if(!r&&!n){return t.allComponentClasses._base.determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t})}let a=[];if(r?.attributes.variantNames&&(a=r.attributes.variantNames.component.children.map((e=>e.toLowerCase()))),a.length!==[...new Set(a)].length)throw Error("Duplicate variant names specified");let i=r?.attributes.nVariants?.primitive;Number.isFinite(i)||(i=100),i=Math.min(Math.max(i,1),1e3);let s=[...a];if(s.lengthe.toLowerCase())),o=[...new Set(o)];for(let e of o)if(!s.includes(e))throw Error(`Cannot include variant ${e} as ${e} is a not variant name`)}let l=r?.attributes.variantsToExclude?.component.children;if(l){l=l.map((e=>e.toLowerCase()));for(let e of l)if(!s.includes(e))throw Error(`Cannot exclude variant ${e} as ${e} is not a variant name`)}else l=[];o=o?o.filter((e=>!l.includes(e))):[...s].filter((e=>!l.includes(e)));let u=o.map((e=>s.indexOf(e)+1)),c=[];r?.attributes.seeds&&(c=r.attributes.seeds.component.children);let p=[...c];if(p.lengthp[e-1])),h=void 0!==r?.attributes.uniqueVariants,f=r?.attributes.uniqueVariants?.primitive;if(f||!h){d=t.allComponentClasses._base.determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t}),f=!!d.success&&(f||d.numberOfVariants<=i)}let y=[],g=[],b=[];if(f)for(let[e,t]of u.entries())t<=d.numberOfVariants&&(g.push(t),y.push(o[e]),b.push(m[e]));else y=o,g=u,b=m;let v=y.length;if(0===v)throw Error("No variants selected based on variantsToInclude, variantsToExclude, and the number of variants available");return e.variants.uniqueVariants=f,e.variants.numberOfVariants=v,e.variants.allPossibleVariants=y,e.variants.allVariantNames=s,e.variants.allPossibleVariantUniqueIndices=g,e.variants.allPossibleVariantSeeds=b,{success:!0,numberOfVariants:v}}function indexToLowercaseLetters(e){return numberToLetters(e,!0)}class BaseComponent{constructor({componentName:e,ancestors:t,serializedComponent:n,definingChildren:r,serializedChildren:a,attributes:i,stateVariableDefinitions:s,componentInfoObjects:o,coreFunctions:l,flags:u,shadow:c,numerics:p,parentSharedParameters:d,sharedParameters:m}){this.numerics=p,this.parentSharedParameters=d,this.sharedParameters=m,this.componentName=e,this.ancestors=t,this.counters={},this.componentInfoObjects=o,this.coreFunctions=l,this.flags=u,!0===c&&(this.isShadow=!0),this.definingChildren=r,void 0===this.definingChildren&&(this.definingChildren=[]),this.serializedChildren=a,this.attributes=i,this.state={};for(let e in s)this.state[e]=Object.assign({},s[e]);this.stateValues=new Proxy(this.state,createStateProxyHandler()),this.essentialState={},n.state&&(this.essentialState=deepClone(n.state)),this.doenetAttributes={},void 0!==n.doenetAttributes&&Object.assign(this.doenetAttributes,n.doenetAttributes),void 0!==n.variants&&(this.variants=n.variants),n.range&&(this.doenetMLrange=n.range),this.actions={copyDoenetMLToClipboard:this.copyDoenetMLToClipboard.bind(this)}}static componentType="_base";static get rendererType(){return this.componentType}get componentType(){return this.constructor.componentType}get componentOrAdaptedName(){return this.adaptedFrom?this.adaptedFrom.componentOrAdaptedName:this.componentName}get rendererType(){return this.constructor.rendererType}get allPotentialRendererTypes(){let e=[];this.rendererType&&e.push(this.rendererType);for(let t in this.state){let n=this.state[t];if(n.public){let t=n.componentType;Array.isArray(t)||(t=[t]),n.wrappingComponents&&t.push(...flattenDeep(n.wrappingComponents).map((e=>"object"==typeof e?e.componentType:e)));for(let n of t){let t=this.componentInfoObjects.allComponentClasses[n];if(t){let n=t.rendererType;n&&!e.includes(n)&&e.push(n)}}}}if(this.constructor.adapters)for(let t of this.constructor.adapters){let n;n="string"==typeof t?t:t.componentType;let r=this.componentInfoObjects.allComponentClasses[n];if(r){let t=r.rendererType;t&&!e.includes(t)&&e.push(t)}}if(!this.rendererType)return e;for(let t in this.allChildren){let n=this.allChildren[t].component;if("object"==typeof n)for(let t of n.allPotentialRendererTypes)e.includes(t)||e.push(t)}return e}potentialRendererTypesFromSerializedComponents(e){let t=[];for(let n of e){let e=this.componentInfoObjects.allComponentClasses[n.componentType];if(e){let n=e.rendererType;n&&!t.includes(n)&&t.push(n);let r=e.returnStateVariableInfo({onlyPublic:!0}).stateVariableDescriptions;for(let e in r){let n=r[e],a=n.shadowingInstructions?.createComponentOfType;Array.isArray(a)||(a=[a]),n.wrappingComponents&&a.push(...flattenDeep(n.wrappingComponents).map((e=>"object"==typeof e?e.componentType:e)));for(let e of a){let n=this.componentInfoObjects.allComponentClasses[e];if(n){let e=n.rendererType;e&&!t.includes(e)&&t.push(e)}}}if(e.adapters)for(let n of e.adapters){let e;e="string"==typeof n?n:n.componentType;let r=this.componentInfoObjects.allComponentClasses[e];if(r){let e=r.rendererType;e&&!t.includes(e)&&t.push(e)}}}if(n.children){let e=this.potentialRendererTypesFromSerializedComponents(n.children);for(let n of e)t.includes(n)||t.push(n)}}return t}get childrenMatched(){return this.childrenMatchedWithPlaceholders&&!this.placeholderActiveChildrenIndices}static createAttributesObject(){return{hide:{createComponentOfType:"boolean",createStateVariable:"hide",defaultValue:!1,public:!0},disabled:{createComponentOfType:"boolean"},fixed:{createComponentOfType:"boolean",ignoreFixed:!0},modifyIndirectly:{createComponentOfType:"boolean",createStateVariable:"modifyIndirectly",defaultValue:!0,public:!0,propagateToProps:!0},styleNumber:{createComponentOfType:"number",createStateVariable:"styleNumber",defaultValue:1,public:!0,fallBackToParentStateVariable:"styleNumber"},isResponse:{createPrimitiveOfType:"boolean",createStateVariable:"isResponse",defaultValue:!1,public:!0},newNamespace:{createPrimitiveOfType:"boolean",createStateVariable:"newNamespace",defaultValue:!1,public:!0}}}static returnSugarInstructions(){return[]}static returnChildGroups(){return[]}static get childGroups(){return this.hasOwnProperty("childGroupsData")||(this.childGroupsData=this.returnChildGroups()),this.childGroupsData}static childGroupOfComponentTypeData;static get childGroupOfComponentType(){return this.hasOwnProperty("childGroupOfComponentTypeData")||(this.childGroupOfComponentTypeData={}),this.childGroupOfComponentTypeData}static childGroupIndsByNameData;static get childGroupIndsByName(){if(this.hasOwnProperty("childGroupIndsByNameData"))return Object.assign({},this.childGroupIndsByNameData);this.childGroupIndsByNameData={};for(let[e,t]of this.childGroups.entries()){if(t.group in this.childGroupIndsByNameData)throw Error(`Invalid childGroups for componentClass ${this.componentType}: ${t} is repeated`);this.childGroupIndsByNameData[t.group]=e}return Object.assign({},this.childGroupIndsByNameData)}returnMatchedChildIndices(e){let t=[];for(let n of e){let e=this.childMatchesByGroup[n];if(!e)return;t.push(...e)}return t.sort(((e,t)=>e-t))}static returnStateVariableDefinitions(){let e={};return e.hidden={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,returnDependencies:()=>({hide:{dependencyType:"stateVariable",variableName:"hide",variablesOptional:!0},parentHidden:{dependencyType:"parentStateVariable",variableName:"hidden"},sourceCompositeHidden:{dependencyType:"sourceCompositeStateVariable",variableName:"hidden"},adapterSourceHidden:{dependencyType:"adapterSourceStateVariable",variableName:"hidden"}}),definition:({dependencyValues:e})=>({setValue:{hidden:Boolean(e.parentHidden||e.sourceCompositeHidden||e.adapterSourceHidden||e.hide)}}),markStale:()=>({updateParentRenderedChildren:!0}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setDependency:"hide",desiredValue:e.hidden}]})},e.disabled={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,hasEssential:!0,doNotShadowEssential:!0,defaultValue:!1,provideEssentialValuesInDefinition:!0,returnDependencies:()=>({disabledAttr:{dependencyType:"attributeComponent",attributeName:"disabled",variableNames:["value"]},readOnly:{dependencyType:"flag",flagName:"readOnly"},parentDisabled:{dependencyType:"parentStateVariable",variableName:"disabled"},sourceCompositeDisabled:{dependencyType:"sourceCompositeStateVariable",variableName:"disabled"},adapterSourceDisabled:{dependencyType:"adapterSourceStateVariable",variableName:"disabled"}}),definition({dependencyValues:e,usedDefault:t,essentialValues:n}){if(e.readOnly)return{setValue:{disabled:!0}};if(null!==e.disabledAttr)return{setValue:{disabled:e.disabledAttr.stateValues.value}};if(void 0!==n.disabled)return{useEssentialOrDefaultValue:{disabled:!0}};let r=!1,a=!0;return null===e.parentDisabled||t.parentDisabled||(r=r||e.parentDisabled,a=!1),null===e.sourceCompositeDisabled||t.sourceCompositeDisabled||(r=r||e.sourceCompositeDisabled,a=!1),null===e.adapterSourceDisabled||t.adapterSourceDisabled||(r=r||e.adapterSourceDisabled,a=!1),a?{useEssentialOrDefaultValue:{disabled:!0}}:{setValue:{disabled:r}}},inverseDefinition:({dependencyValues:e,desiredStateVariableValues:t})=>null!==e.disabledAttr?{success:!0,instructions:[{setDependency:"disabledAttr",desiredValue:t.disabled,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"disabled",value:t.disabled}]}},e.fixed={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,defaultValue:!1,hasEssential:!0,doNotShadowEssential:!0,ignoreFixed:!0,provideEssentialValuesInDefinition:!0,returnDependencies:()=>({fixedAttr:{dependencyType:"attributeComponent",attributeName:"fixed",variableNames:["value"]},parentFixed:{dependencyType:"parentStateVariable",variableName:"fixed"},sourceCompositeFixed:{dependencyType:"sourceCompositeStateVariable",variableName:"fixed"},adapterSourceFixed:{dependencyType:"adapterSourceStateVariable",variableName:"fixed"},ignoreParentFixed:{dependencyType:"doenetAttribute",attributeName:"ignoreParentFixed"}}),definition({dependencyValues:e,usedDefault:t,essentialValues:n}){if(null!==e.fixedAttr)return{setValue:{fixed:e.fixedAttr.stateValues.value}};if(void 0!==n.fixed)return{useEssentialOrDefaultValue:{fixed:!0}};let r=!1,a=!0;return null===e.parentFixed||t.parentFixed||e.ignoreParentFixed||(r=r||e.parentFixed,a=!1),null===e.sourceCompositeFixed||t.sourceCompositeFixed||(r=r||e.sourceCompositeFixed,a=!1),null===e.adapterSourceFixed||t.adapterSourceFixed||(r=r||e.adapterSourceFixed,a=!1),a?{useEssentialOrDefaultValue:{fixed:!0}}:{setValue:{fixed:r}}},inverseDefinition:({dependencyValues:e,desiredStateVariableValues:t})=>null!==e.fixedAttr?{success:!0,instructions:[{setDependency:"fixedAttr",desiredValue:t.fixed,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"fixed",value:t.fixed}]}},e.isInactiveCompositeReplacement={defaultValue:!1,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{isInactiveCompositeReplacement:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:{variableName:"isInactiveCompositeReplacement",value:e.isInactiveCompositeReplacement}}]})},e.doenetML={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({doenetML:{dependencyType:"doenetML"}}),definition({dependencyValues:e}){let t=e.doenetML;return t||(t=""),{setValue:{doenetML:t}}}},e}static returnNormalizedStateVariableDefinitions({attributeNames:e,numerics:t}){let n=this.returnStateVariableDefinitions({attributeNames:e,numerics:t});if(!n)throw Error(`Error in state variable definitions of ${this.componentType}: returnStateVariableDefinitions did not return anything`);let r=function(e){for(let[t,n]of e.entries())"object"==typeof n&&(e[t]=n.variableName)},a=["returnDependencies","definition","inverseDefinition","stateVariablesDeterminingDependencies","stateVariablesDeterminingArraySizeDependencies","isArray","nDimensions","returnArraySizeDependencies","returnArraySize","returnArrayDependenciesByKey","arrayDefinitionByKey","inverseArrayDefinitionByKey","basedOnArrayKeyStateVariables","markStale","getPreviousDependencyValuesForMarkStale","determineDependenciesImmediately","createWorkspace","workspace","provideEssentialValuesInDefinition","providePreviousValuesInDefinition"],i={};for(let e in n){let t=n[e];if(i[e]=t,t.createWorkspace&&(t.workspace={}),t.additionalStateVariablesDefined){for(let[n,s]of t.additionalStateVariablesDefined.entries()){let o={};for(let e of a)e in t&&(o[e]=t[e]);o.additionalStateVariablesDefined=[...t.additionalStateVariablesDefined],o.additionalStateVariablesDefined[n]=e,r(o.additionalStateVariablesDefined);let l=s;"object"==typeof s&&(l=s.variableName,s=Object.assign({},s),delete s.variableName,Object.assign(o,s)),i[l]=o}r(t.additionalStateVariablesDefined)}}return i}static returnStateVariableInfo({onlyPublic:e=!1,onlyForRenderer:t=!1}={}){let n=this.createAttributesObject(),r={},a={},i={};for(let a in n){let i=n[a],s=i.createStateVariable;if(s&&(!e||i.public)&&(!t||i.forRenderer))if(i.public){let e;!i.createComponentOfType?(e=i.createPrimitiveOfType,"string"===e&&(e="text")):e=i.createComponentOfType,r[s]={createComponentOfType:e,public:!0}}else r[s]={}}let s=this.returnNormalizedStateVariableDefinitions({attributeNames:Object.keys(r)});for(let n in s){let o=s[n];if(o.isAlias)i[n]=o.targetVariableName;else if((!e||o.public)&&(!t||o.forRenderer)&&(o.public?r[n]={createComponentOfType:o.shadowingInstructions.createComponentOfType,public:!0}:r[n]={},o.isArray)){let e;r[n].isArray=!0,r[n].nDimensions=void 0===o.nDimensions?1:o.nDimensions,r[n].wrappingComponents=o.shadowingInstructions?.returnWrappingComponents?o.shadowingInstructions.returnWrappingComponents():[],e=o.entryPrefixes?o.entryPrefixes:[n];for(let t of e)a[t]={arrayVariableName:n,nDimensions:o.returnEntryDimensions?o.returnEntryDimensions(t):1,wrappingComponents:o.shadowingInstructions?.returnWrappingComponents?o.shadowingInstructions.returnWrappingComponents(t):[]};o.getArrayKeysFromVarName?r[n].getArrayKeysFromVarName=o.getArrayKeysFromVarName:r[n].getArrayKeysFromVarName=returnDefaultGetArrayKeysFromVarName(r[n].nDimensions)}}return{stateVariableDescriptions:r,arrayEntryPrefixes:a,aliases:i}}get parentName(){if(void 0!==this.ancestors&&0!==this.ancestors.length)return this.ancestors[0].componentName}getAllChildrenDownstreamComponentNames(e=!1){const t=Object.keys(this.allChildren);let n=Object.keys(this.downstreamDependencies);return!0!==e&&(n=n.filter((e=>!0!==this.downstreamDependencies[e].inactive))),[...t,...n]}get allDescendants(){let e=[];for(let t in this.allChildren){let n=this.allChildren[t].component;e=[...e,t,...n.allDescendants]}return e}async serialize(e={}){let t,n={componentType:this.componentType},r=[],a={...e};t=e.sourceAttributesToIgnoreRecursively?[...e.sourceAttributesToIgnoreRecursively]:[],e.sourceAttributesToIgnore&&(t.push(...e.sourceAttributesToIgnore),delete a.sourceAttributesToIgnore);for(let e of this.definingChildren)"object"!=typeof e?r.push(e):r.push(await e.serialize(a));if(void 0!==this.serializedChildren)for(let e of this.serializedChildren)r.push(this.copySerializedComponent(e));r.length>0&&(n.children=r),n.attributes={};for(let r in this.attributes){let i=this.attributes[r];i.component?e.copyAll&&(n.attributes[r]={component:await i.component.serialize(a)}):t.includes(r)&&!e.copyAll||(n.attributes[r]=JSON.parse(JSON.stringify(i)))}return this.essentialState&&Object.keys(this.essentialState).length>0&&(n.state=deepClone(this.essentialState)),e.copyVariants&&this.state.generatedVariantInfo&&(n.variants={desiredVariant:await this.stateValues.generatedVariantInfo}),n.originalName=this.componentName,n.originalDoenetAttributes=deepClone(this.doenetAttributes),n.doenetAttributes=deepClone(this.doenetAttributes),n.originalAttributes=deepClone(n.attributes),delete n.doenetAttributes.prescribedName,delete n.doenetAttributes.assignNames,n}copySerializedComponent(e){if("object"!=typeof e)return e;let t=[];if(void 0!==e.children)for(let n of e.children)t.push(this.copySerializedComponent(n));let n={componentType:e.componentType,originalName:e.componentName,originalNameFromSerializedComponent:!0,children:t,state:{},doenetAttributes:{}};return void 0!==e.doenetAttributes&&(n.originalDoenetAttributes=deepClone(e.doenetAttributes),n.doenetAttributes=deepClone(e.doenetAttributes),n.originalAttributes=deepClone(e.attributes),n.attributes=deepClone(e.attributes),delete n.doenetAttributes.prescribedName,delete n.doenetAttributes.assignNames),void 0!==e.state&&Object.assign(n.state,e.state),n}static adapters=[];static get nAdapters(){return this.adapters.length}getAdapter(e){if(e>=this.constructor.adapters.length)return;let t,n,r,a,i=this.constructor.adapters[e];"string"==typeof i?t=i:(t=i.stateVariable,n=i.componentType,r=i.substituteForPrimaryStateVariable,a=i.stateVariablesToShadow);let s=this.state[t];if(void 0===s||!s.public&&!n)throw Error("Invalid adapter "+t+" in "+this.componentType);return void 0===n&&(n=s.shadowingInstructions.createComponentOfType),{componentType:n,downstreamDependencies:{[this.componentName]:[{dependencyType:"adapter",adapterVariable:t,adapterTargetIdentity:{componentName:this.componentName,componentType:this.componentType},substituteForPrimaryStateVariable:r,stateVariablesToShadow:a}]}}}static getAdapterComponentType(e,t){if(e>=this.adapters.length)return;let n,r,a=this.adapters[e];if("string"==typeof a?n=a:(n=a.stateVariable,r=a.componentType),void 0===r){let e=t[this.componentType].stateVariableDescriptions[n];if(!e)throw Error("Invalid adapter "+n+" in "+this.componentType);if(r=e.createComponentOfType,!r)throw Error(`Couldn't get adapter component type for ${n} of componentType ${this.componentType}`)}return r}static determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t}){let n=e.variants?.numberOfVariants;if(void 0!==n)return{success:!0,numberOfVariants:n};let r=[];e.children&&(r=gatherVariantComponents({serializedComponents:e.children,componentInfoObjects:t})),void 0===e.variants&&(e.variants={}),e.variants.descendantVariantComponents=r,n=1;let a=[];for(let e of r){let r=t.allComponentClasses[e.componentType].determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t});if(!r.success)return{success:!1};a.push(r.numberOfVariants),n*=r.numberOfVariants}return e.variants.numberOfVariants=n,e.variants.uniqueVariantData={numberOfVariantsByDescendant:a},{success:!0,numberOfVariants:n}}static getUniqueVariant({serializedComponent:e,variantIndex:t,componentInfoObjects:n}){let r=e.variants?.numberOfVariants;if(void 0===r)return{success:!1};if(!Number.isInteger(t)||t<1||t>r)return{success:!1};let a=!1,i=e.variants.uniqueVariantData.numberOfVariantsByDescendant,s=e.variants.descendantVariantComponents,o=[];if(s.length>0){let e=enumerateCombinations({numberOfOptionsByIndex:i,maxNumber:t})[t-1].map((e=>e+1));for(let t=0;t1){let r=s[t],i=n.allComponentClasses[r.componentType].getUniqueVariant({serializedComponent:r,variantIndex:e[t],componentInfoObjects:n});if(!i.success)return{success:!1};o.push(i.desiredVariant),a=!0}else o.push({})}let l={index:t};return a&&(l.subvariants=o),{success:!0,desiredVariant:l}}async copyDoenetMLToClipboard({actionId:e}){let t=await this.stateValues.doenetML;t?this.coreFunctions.copyToClipboard(t,e):this.coreFunctions.resolveAction({actionId:e})}}class InlineComponent extends BaseComponent{static componentType="_inline"}class Text extends InlineComponent{constructor(e){super(e),Object.assign(this.actions,{moveText:this.moveText.bind(this)})}static componentType="text";static includeBlankStringChildren=!0;static variableForPlainMacro="value";static descendantCompositesMustHaveAReplacement=!1;static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.layer={createComponentOfType:"number",createStateVariable:"layer",defaultValue:0,public:!0,forRenderer:!0},e.anchor={createComponentOfType:"point"},e.positionFromAnchor={createComponentOfType:"text",createStateVariable:"positionFromAnchor",defaultValue:"center",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft","top","bottom","left","right","center"]},e.styleNumber.defaultValue=0,e}static returnChildGroups(){return[{group:"textLike",componentTypes:["string","text","_singleCharacterInline","_inlineRenderInlineChildren"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnSelectedStyleStateVariableDefinition();return Object.assign(e,t),e.value={public:!0,shadowingInstructions:{createComponentOfType:this.componentType,addAttributeComponentsShadowingStateVariables:{fixed:{stateVariableToShadow:"fixed"}}},hasEssential:!0,returnDependencies:()=>({textLikeChildren:{dependencyType:"child",childGroups:["textLike"],variableNames:["text"]}}),defaultValue:"",set:e=>null===e?"":String(e),definition:function({dependencyValues:e}){if(0===e.textLikeChildren.length)return{useEssentialOrDefaultValue:{value:!0}};let t="";for(let n of e.textLikeChildren)t+="string"==typeof n?n:n.stateValues.text;return{setValue:{value:t}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){let n=t.textLikeChildren.length;return n>1?{success:!1}:1===n?{success:!0,instructions:[{setDependency:"textLikeChildren",desiredValue:e.value,childIndex:0,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"value",value:null===e.value?"":String(e.value)}]}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:({dependencyValues:e})=>({setValue:{text:e.value}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setDependency:"value",desiredValue:e.text}]})},e.anchor={defaultValue:me$3.fromText("(0,0)"),public:!0,forRenderer:!0,hasEssential:!0,shadowingInstructions:{createComponentOfType:"point"},returnDependencies:()=>({anchorAttr:{dependencyType:"attributeComponent",attributeName:"anchor",variableNames:["coords"]}}),definition:({dependencyValues:e})=>e.anchorAttr?{setValue:{anchor:e.anchorAttr.stateValues.coords}}:{useEssentialOrDefaultValue:{anchor:!0}},inverseDefinition:async({desiredStateVariableValues:e,dependencyValues:t,stateValues:n,initialChange:r})=>r&&!await n.draggable?{success:!1}:t.anchorAttr?{success:!0,instructions:[{setDependency:"anchorAttr",desiredValue:e.anchor,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"anchor",value:e.anchor}]}},e}async moveText({x:e,y:t,z:n,transient:r,actionId:a}){let i=["vector"];return void 0!==e&&(i[1]=e),void 0!==t&&(i[2]=t),void 0!==n&&(i[3]=n),r?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],transient:r,actionId:a}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],actionId:a,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{x:e,y:t,z:n}}})}}class TextOrInline extends InlineComponent{static componentType="_textOrInline";static renderChildren=!0;static rendererType="containerInline";static includeBlankStringChildren=!0;static returnChildGroups(){return[{group:"inlines",componentTypes:["_inline"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.value={public:!0,shadowingInstructions:{createComponentOfType:this.componentType},returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["inlines"],variableNames:["text"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let t="";for(let n of e.inlineChildren)"object"!=typeof n?t+=n.toString():"string"==typeof n.stateValues.text&&(t+=n.stateValues.text);return{setValue:{value:t}}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:({dependencyValues:e})=>({setValue:{text:e.value}})},e}}class CompositeComponent extends BaseComponent{constructor(e){super(e),this.replacementsWorkspace={}}static componentType="_composite";static rendererType=void 0;static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.replacements={returnDependencies:()=>({replacements:{dependencyType:"replacement"}}),definition:({dependencyValues:e})=>({setValue:{replacements:e.replacements}})},e.recursiveReplacements={returnDependencies:()=>({recursiveReplacements:{dependencyType:"replacement",recursive:!0}}),definition:({dependencyValues:e})=>({setValue:{recursiveReplacements:e.recursiveReplacements}})},e.fullRecursiveReplacements={returnDependencies:()=>({recursiveReplacements:{dependencyType:"replacement",recursive:!0,recurseNonStandardComposites:!0}}),definition:({dependencyValues:e})=>({setValue:{fullRecursiveReplacements:e.recursiveReplacements}})},e}static createSerializedReplacements(){return{replacements:[]}}static calculateReplacementChanges(){return[]}replacements=[];replacementsToWithhold=0;get allPotentialRendererTypes(){let e=super.allPotentialRendererTypes;for(let t in this.allChildren){let n=this.allChildren[t].component;for(let t of n.allPotentialRendererTypes)e.includes(t)||e.push(t)}if(this.replacements)for(let t of this.replacements)if("object"==typeof t)for(let n of t.allPotentialRendererTypes)e.includes(n)||e.push(n);return e}}class Template extends CompositeComponent{static componentType="template";static treatAsComponentForRecursiveReplacements=!0;static includeBlankStringChildren=!0;static renderedDefault=!1;static assignNamesToReplacements=!0;static createsVariants=!0;static keepChildrenSerialized({serializedComponent:e}){return void 0===e.children?[]:Object.keys(e.children)}static createAttributesObject(){let e=super.createAttributesObject();return e.rendered={createComponentOfType:"boolean",createStateVariable:"rendered",defaultValue:this.renderedDefault,public:!0},e.isResponse={leaveRaw:!0},e.createComponentOfType={createPrimitiveOfType:"string"},e.nComponents={createPrimitiveOfType:"number"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=this;return e.serializedChildren={returnDependencies:()=>({serializedChildren:{dependencyType:"serializedChildren",doNotProxy:!0}}),definition:function({dependencyValues:e}){return{setValue:{serializedChildren:e.serializedChildren}}}},e.newNamespace={returnDependencies:()=>({newNamespace:{dependencyType:"attributePrimitive",attributeName:"newNamespace"}}),definition:({dependencyValues:e})=>({setValue:{newNamespace:e.newNamespace}})},e.readyToExpandWhenResolved={returnDependencies:()=>({}),definition:function(){return{setValue:{readyToExpandWhenResolved:!0}}}},e.isVariantComponent={returnDependencies:()=>({}),definition:()=>({setValue:{isVariantComponent:!0}})},e.generatedVariantInfo={returnDependencies:({sharedParameters:e,componentInfoObjects:t})=>({variantSeed:{dependencyType:"value",value:e.variantSeed},variantDescendants:{dependencyType:"descendant",componentTypes:Object.keys(t.componentTypesCreatingVariants),variableNames:["isVariantComponent","generatedVariantInfo"],useReplacementsForComposites:!0,recurseToMatchedChildren:!1,variablesOptional:!0,includeNonActiveChildren:!0,ignoreReplacementsOfEncounteredComposites:!0}}),definition({dependencyValues:e,componentName:t}){let n={seed:e.variantSeed,meta:{createdBy:t}},r=n.subvariants=[];for(let t of e.variantDescendants)t.stateValues.isVariantComponent?r.push(t.stateValues.generatedVariantInfo):t.stateValues.generatedVariantInfo&&r.push(...t.stateValues.generatedVariantInfo.subvariants);return{setValue:{generatedVariantInfo:n}}}},e.nComponentsSpecified={returnDependencies:()=>({nComponentsAttr:{dependencyType:"attributePrimitive",attributeName:"nComponents"},typeAttr:{dependencyType:"attributePrimitive",attributeName:"createComponentOfType"}}),definition({dependencyValues:e,componentInfoObjects:n}){let r;if(e.typeAttr){if(!(n.componentTypeLowerCaseMapping[e.typeAttr.toLowerCase()]in n.allComponentClasses))throw Error(`Invalid componentType ${e.typeAttr} of copy.`);r=null!==e.nComponentsAttr?e.nComponentsAttr:1}else{if(null!==e.nComponentsAttr)throw Error(`You must specify createComponentOfType when specifying nComponents for a ${t.componentType}.`);r=null}return{setValue:{nComponentsSpecified:r}}}},e}static async createSerializedReplacements({component:e,componentInfoObjects:t,alwaysCreateReplacements:n,flags:r}){if(await e.stateValues.nComponentsSpecified,await e.stateValues.rendered||n){let n=deepClone(await e.state.serializedChildren.value),a=e.attributes.newNamespace?.primitive;if("isResponse"in e.attributes)for(let i of n){if("object"!=typeof i)continue;let n=convertAttributesForComponentType({attributes:{isResponse:e.attributes.isResponse},componentType:i.componentType,componentInfoObjects:t,compositeCreatesNewNamespace:a,flags:r});i.attributes||(i.attributes={}),Object.assign(i.attributes,n)}let i=processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:n,parentName:e.componentName,parentCreatesNewNamespace:a,componentInfoObjects:t,originalNamesAreConsistent:!0});return{replacements:(await verifyReplacementsMatchSpecifiedType({component:e,replacements:i.serializedComponents,assignNames:e.doenetAttributes.assignNames,componentInfoObjects:t,compositeAttributesObj:this.createAttributesObject(),flags:r})).replacements}}return{replacements:[]}}static setUpVariant({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n}){setUpVariantSeedAndRng({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n,useSubpartVariantRng:!0})}get allPotentialRendererTypes(){let e=super.allPotentialRendererTypes,t=this.potentialRendererTypesFromSerializedComponents(this.serializedChildren);for(let n of t)e.includes(n)||e.push(n);return e}}const vectorAndListOperators=["list",...vectorOperators];class MathComponent extends InlineComponent{constructor(e){super(e),Object.assign(this.actions,{moveMath:this.moveMath.bind(this)})}static componentType="math";static primaryStateVariableForDefinition="unnormalizedValue";static primaryEssentialStateVariable="value";static variableForPlainMacro="value";static descendantCompositesMustHaveAReplacement=!0;static descendantCompositesDefaultReplacementType="math";static createAttributesObject(){let e=super.createAttributesObject();return e.format={createComponentOfType:"text",createStateVariable:"format",defaultValue:"text",public:!0,toLowerCase:!0,validValues:["text","latex"]},e.simplify={createComponentOfType:"text",createStateVariable:"simplify",defaultValue:"none",public:!0,toLowerCase:!0,valueTransformations:{true:"full",false:"none"},validValues:["none","full","numbers","numberspreserveorder"]},e.expand={createComponentOfType:"boolean",createStateVariable:"expand",defaultValue:!1,public:!0},e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer"},e.displaySmallAsZero={createComponentOfType:"number",valueForTrue:1e-14,valueForFalse:0},e.padZeros={createComponentOfType:"boolean"},e.renderMode={createComponentOfType:"text",createStateVariable:"renderMode",defaultValue:"inline",public:!0,forRenderer:!0},e.unordered={createComponentOfType:"boolean"},e.createVectors={createComponentOfType:"boolean",createStateVariable:"createVectors",defaultValue:!1,public:!0},e.createIntervals={createComponentOfType:"boolean",createStateVariable:"createIntervals",defaultValue:!1,public:!0},e.functionSymbols={createComponentOfType:"textList",createStateVariable:"functionSymbols",defaultValue:["f","g"],public:!0},e.sourcesAreFunctionSymbols={createComponentOfType:"textList",createStateVariable:"sourcesAreFunctionSymbols",defaultValue:[]},e.splitSymbols={createComponentOfType:"boolean",createStateVariable:"splitSymbols",defaultValue:!0,public:!0,fallBackToParentStateVariable:"splitSymbols"},e.parseScientificNotation={createComponentOfType:"boolean",createStateVariable:"parseScientificNotation",defaultValue:!1,public:!0,fallBackToParentStateVariable:"parseScientificNotation"},e.groupCompositeReplacements={createPrimitiveOfType:"boolean",createStateVariable:"groupCompositeReplacements",defaultValue:!0},e.displayBlanks={createComponentOfType:"boolean",createStateVariable:"displayBlanks",defaultValue:!0,public:!0},e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.layer={createComponentOfType:"number",createStateVariable:"layer",defaultValue:0,public:!0,forRenderer:!0},e.anchor={createComponentOfType:"point"},e.positionFromAnchor={createComponentOfType:"text",createStateVariable:"positionFromAnchor",defaultValue:"center",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft","top","bottom","left","right","center"]},e.styleNumber.defaultValue=0,e}static returnChildGroups(){return[{group:"maths",componentTypes:["math"]},{group:"strings",componentTypes:["string"]},{group:"displayedMaths",componentTypes:["m","me","men"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnSelectedStyleStateVariableDefinition();return Object.assign(e,t),e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({mathListParentDisplayDigits:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"displayDigits"},numberListParentDisplayDigits:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"displayDigits"},mathListParentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"displayDecimals"},numberListParentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"displayDecimals"},displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["displayDigits"]},stringChildren:{dependencyType:"child",childGroups:["strings"]}}),definition({dependencyValues:e,usedDefault:t}){let n,r=!1;if(null!==e.mathListParentDisplayDigits){if(!t.mathListParentDisplayDigits)return{setValue:{displayDigits:e.mathListParentDisplayDigits}};r=!0,n=e.mathListParentDisplayDigits}if(null!==e.numberListParentDisplayDigits){if(!t.numberListParentDisplayDigits)return{setValue:{displayDigits:e.numberListParentDisplayDigits}};r=!0,n=e.numberListParentDisplayDigits}let a=null!==e.numberListParentDisplayDecimals&&!t.numberListParentDisplayDecimals||null!==e.mathListParentDisplayDecimals&&!t.mathListParentDisplayDecimals,i=null===e.displayDigitsAttr||t.displayDigitsAttr,s=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!i&&!s){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({mathListParentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"displayDecimals"},numberListParentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"displayDecimals"},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["displayDecimals"]},stringChildren:{dependencyType:"child",childGroups:["strings"]}}),definition({dependencyValues:e,usedDefault:t}){let n,r=!1;if(null!==e.mathListParentDisplayDecimals){if(!t.mathListParentDisplayDecimals)return{setValue:{displayDecimals:e.mathListParentDisplayDecimals}};r=!0,n=e.mathListParentDisplayDecimals}if(null!==e.numberListParentDisplayDecimals){if(!t.numberListParentDisplayDecimals)return{setValue:{displayDecimals:e.numberListParentDisplayDecimals}};r=!0,n=e.numberListParentDisplayDecimals}if(null!==e.displayDecimalsAttr){if(!t.displayDecimalsAttr)return{setValue:{displayDecimals:e.displayDecimalsAttr.stateValues.value}};r=!0,n=e.displayDecimalsAttr.stateValues.value}if(1===e.mathChildren.length&&0===e.stringChildren.length){if(!t.mathChildren[0]||!t.mathChildren[0].displayDecimals)return{setValue:{displayDecimals:e.mathChildren[0].stateValues.displayDecimals}};r=!0,n=e.mathChildren[0].stateValues.displayDecimals}return r?{useEssentialOrDefaultValue:{displayDecimals:{defaultValue:n}}}:{useEssentialOrDefaultValue:{displayDecimals:!0}}}},e.displaySmallAsZero={public:!0,shadowingInstructions:{createComponentOfType:"number"},hasEssential:!0,defaultValue:0,returnDependencies:()=>({mathListParentDisplaySmallAsZero:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"displaySmallAsZero"},numberListParentDisplaySmallAsZero:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"displaySmallAsZero"},displaySmallAsZeroAttr:{dependencyType:"attributeComponent",attributeName:"displaySmallAsZero",variableNames:["value"]},mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["displaySmallAsZero"]},stringChildren:{dependencyType:"child",childGroups:["strings"]}}),definition({dependencyValues:e,usedDefault:t}){let n,r=!1;if(null!==e.mathListParentDisplaySmallAsZero){if(!t.mathListParentDisplaySmallAsZero)return{setValue:{displaySmallAsZero:e.mathListParentDisplaySmallAsZero}};r=!0,n=e.mathListParentDisplaySmallAsZero}if(null!==e.numberListParentDisplaySmallAsZero){if(!t.numberListParentDisplaySmallAsZero)return{setValue:{displaySmallAsZero:e.numberListParentDisplaySmallAsZero}};r=!0,n=e.numberListParentDisplaySmallAsZero}if(null!==e.displaySmallAsZeroAttr){if(!t.displaySmallAsZeroAttr)return{setValue:{displaySmallAsZero:e.displaySmallAsZeroAttr.stateValues.value}};r=!0,n=e.displaySmallAsZeroAttr.stateValues.value}if(1===e.mathChildren.length&&0===e.stringChildren.length){if(!t.mathChildren[0]||!t.mathChildren[0].displaySmallAsZero)return{setValue:{displaySmallAsZero:e.mathChildren[0].stateValues.displaySmallAsZero}};r=!0,n=e.mathChildren[0].stateValues.displaySmallAsZero}return r?{useEssentialOrDefaultValue:{displaySmallAsZero:{defaultValue:n}}}:{useEssentialOrDefaultValue:{displaySmallAsZero:!0}}}},e.padZeros={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},hasEssential:!0,defaultValue:!1,returnDependencies:()=>({mathListParentPadZeros:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"padZeros"},numberListParentPadZeros:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"padZeros"},padZerosAttr:{dependencyType:"attributeComponent",attributeName:"padZeros",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["padZeros"]},stringChildren:{dependencyType:"child",childGroups:["strings"]}}),definition({dependencyValues:e,usedDefault:t}){let n,r=!1;if(null!==e.mathListParentPadZeros){if(!t.mathListParentPadZeros)return{setValue:{padZeros:e.mathListParentPadZeros}};r=!0,n=e.mathListParentPadZeros}if(null!==e.numberListParentPadZeros){if(!t.numberListParentPadZeros)return{setValue:{padZeros:e.numberListParentPadZeros}};r=!0,n=e.numberListParentPadZeros}if(null!==e.padZerosAttr){if(!t.padZerosAttr)return{setValue:{padZeros:e.padZerosAttr.stateValues.value}};r=!0,n=e.padZerosAttr.stateValues.value}if(1===e.mathChildren.length&&0==e.stringChildren.length){if(!t.mathChildren[0]||!t.mathChildren[0].padZeros)return{setValue:{padZeros:e.mathChildren[0].stateValues.padZeros}};r=!0,n=e.mathChildren[0].stateValues.padZeros}return r?{useEssentialOrDefaultValue:{padZeros:{defaultValue:n}}}:{useEssentialOrDefaultValue:{padZeros:!0}}}},e.valueShadow={defaultValue:me$3.fromAst("_"),hasEssential:!0,essentialVarName:"value",returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{valueShadow:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"valueShadow",value:e.valueShadow}]}}},e.unordered={defaultValue:!1,public:!0,shadowingInstructions:{createComponentOfType:"boolean"},hasEssential:!0,returnDependencies:()=>({unorderedAttr:{dependencyType:"attributeComponent",attributeName:"unordered",variableNames:["value"]},mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["unordered"]}}),definition({dependencyValues:e}){if(null===e.unorderedAttr){if(e.mathChildren.length>0){let t=e.mathChildren.every((e=>e.stateValues.unordered));return{setValue:{unordered:t}}}return{useEssentialOrDefaultValue:{unordered:!0}}}return{setValue:{unordered:e.unorderedAttr.stateValues.value}}}},e.codePre={returnDependencies:()=>({stringChildren:{dependencyType:"child",childGroups:["strings"]}}),definition({dependencyValues:e}){let t="math",n=!1;do{n=!1;for(let r of e.stringChildren)if(!0===r.includes(t)){n=!0,t+="m";break}}while(n);return{setValue:{codePre:t}}}},e.mathChildrenFunctionSymbols={returnDependencies:()=>({sourcesAreFunctionSymbols:{dependencyType:"stateVariable",variableName:"sourcesAreFunctionSymbols"},mathChildren:{dependencyType:"child",childGroups:["maths"]}}),definition({dependencyValues:e}){let t=[];if(e.mathChildren.compositeReplacementRange)for(let n of e.mathChildren.compositeReplacementRange)if(e.sourcesAreFunctionSymbols.includes(n.target))for(let e=n.firstInd;e<=n.lastInd;e++)t.push(e);return{setValue:{mathChildrenFunctionSymbols:t}}}},e.expressionWithCodes={hasEssential:!0,doNotShadowEssential:!0,returnDependencies:()=>({stringMathChildren:{dependencyType:"child",childGroups:["strings","maths"]},stringChildren:{dependencyType:"child",childGroups:["strings"]},mathChildren:{dependencyType:"child",childGroups:["maths"]},displayedMathChildren:{dependencyType:"child",childGroups:["displayedMaths"],variableNames:["latex"]},format:{dependencyType:"stateVariable",variableName:"format"},codePre:{dependencyType:"stateVariable",variableName:"codePre"},functionSymbols:{dependencyType:"stateVariable",variableName:"functionSymbols"},mathChildrenFunctionSymbols:{dependencyType:"stateVariable",variableName:"mathChildrenFunctionSymbols"},splitSymbols:{dependencyType:"stateVariable",variableName:"splitSymbols"},parseScientificNotation:{dependencyType:"stateVariable",variableName:"parseScientificNotation"},groupCompositeReplacements:{dependencyType:"stateVariable",variableName:"groupCompositeReplacements"}}),set:e=>null===e?null:convertValueToMathExpression(e),definition:calculateExpressionWithCodes,async inverseDefinition({desiredStateVariableValues:e,dependencyValues:t,stateValues:n,componentName:r}){let a=e.expressionWithCodes,i=[{setEssentialValue:"expressionWithCodes",value:a}],s=t.stringChildren.length;if(0===s)return{success:!1};if(0===t.mathChildren.length){let e;e="latex"===await n.format?a.toLatex():a.toString(),i.push({setDependency:"stringChildren",desiredValue:e,childIndex:0,variableIndex:0,ignoreChildChangeForComponent:!0});for(let e=1;e({mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["value","canBeModified"]}}),definition:({dependencyValues:e})=>({setValue:{mathChildrenWithCanBeModified:e.mathChildren}})},e.unnormalizedValue={returnDependencies:()=>({mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]},stringChildren:{dependencyType:"child",childGroups:["strings"],variableNames:["value"]},expressionWithCodes:{dependencyType:"stateVariable",variableName:"expressionWithCodes"},codePre:{dependencyType:"stateVariable",variableName:"codePre"},valueShadow:{dependencyType:"stateVariable",variableName:"valueShadow"}}),set:convertValueToMathExpression,defaultValue:me$3.fromAst("_"),definition:calculateMathValue,inverseDefinition:invertMath},e.value={public:!0,shadowingInstructions:{createComponentOfType:this.componentType,attributesToShadow:["unordered","displayDigits","displayDecimals","displaySmallAsZero","padZeros","simplify","expand"],addAttributeComponentsShadowingStateVariables:{fixed:{stateVariableToShadow:"fixed"}}},returnDependencies:()=>({unnormalizedValue:{dependencyType:"stateVariable",variableName:"unnormalizedValue"},simplify:{dependencyType:"stateVariable",variableName:"simplify"},expand:{dependencyType:"stateVariable",variableName:"expand"},createVectors:{dependencyType:"stateVariable",variableName:"createVectors"},createIntervals:{dependencyType:"stateVariable",variableName:"createIntervals"}}),definition:function({dependencyValues:e}){let t=e.unnormalizedValue,{simplify:n,expand:r,createVectors:a,createIntervals:i}=e;return t=normalizeMathExpression({value:t,simplify:n,expand:r,createVectors:a,createIntervals:i}),{setValue:{value:t}}},inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setDependency:"unnormalizedValue",desiredValue:e.value}]}}},e.number={public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:function({dependencyValues:e}){let t=e.value.evaluate_to_constant();return null===t&&(t=NaN),{setValue:{number:t}}},inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setDependency:"value",desiredValue:me$3.fromAst(e.number)}]}}},e.isNumber={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:function({dependencyValues:e}){return{setValue:{isNumber:Number.isFinite(e.value.tree)}}}},e.isNumeric={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({number:{dependencyType:"stateVariable",variableName:"number"}}),definition:function({dependencyValues:e}){return{setValue:{isNumeric:Number.isFinite(e.number)}}}},e.valueForDisplay={returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"},simplify:{dependencyType:"stateVariable",variableName:"simplify"},expand:{dependencyType:"stateVariable",variableName:"expand"}}),definition:function({dependencyValues:e,usedDefault:t}){return{setValue:{valueForDisplay:normalizeMathExpression({value:roundForDisplay({value:e.value,dependencyValues:e,usedDefault:t}),simplify:e.simplify,expand:e.expand})}}},inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setDependency:"value",desiredValue:e.valueForDisplay}]})},e.latex={public:!0,forRenderer:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({valueForDisplay:{dependencyType:"stateVariable",variableName:"valueForDisplay"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displayBlanks:{dependencyType:"stateVariable",variableName:"displayBlanks"}}),definition:function({dependencyValues:e,usedDefault:t}){let n,r={};e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(r.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(r.padToDigits=e.displayDigits)),e.displayBlanks||(r.showBlanks=!1);try{n=e.valueForDisplay.toLatex(r)}catch(t){n=e.displayBlanks?"_":""}return{setValue:{latex:n}}},inverseDefinition({desiredStateVariableValues:e}){let t;try{t=me$3.fromLatex(e.latex)}catch(e){return{success:!1}}return{success:!0,instructions:[{setDependency:"valueForDisplay",desiredValue:t}]}}},e.latexWithInputChildren={forRenderer:!0,returnDependencies:()=>({latex:{dependencyType:"stateVariable",variableName:"latex"}}),definition:function({dependencyValues:e}){return{setValue:{latexWithInputChildren:[e.latex]}}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({valueForDisplay:{dependencyType:"stateVariable",variableName:"valueForDisplay"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},value:{dependencyType:"stateVariable",variableName:"value"},displayBlanks:{dependencyType:"stateVariable",variableName:"displayBlanks"}}),definition:function({dependencyValues:e,usedDefault:t}){let n,r={};e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(r.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(r.padToDigits=e.displayDigits)),e.displayBlanks||(r.showBlanks=!1);try{n=e.valueForDisplay.toString(r)}catch(t){n=e.displayBlanks?"_":""}return{setValue:{text:superSubscriptsToUnicode(n.toString())}}},async inverseDefinition({desiredStateVariableValues:e,stateValues:t}){let n,r=getFromText({functionSymbols:await t.functionSymbols,splitSymbols:await t.splitSymbols,parseScientificNotation:await t.parseScientificNotation});try{n=r(unicodeToSuperSubscripts(e.text))}catch(e){return{success:!1}}return{success:!0,instructions:[{setDependency:"value",desiredValue:n}]}}},e.codesAdjacentToStrings={returnDependencies:()=>({stringMathChildren:{dependencyType:"child",childGroups:["strings","maths"]},codePre:{dependencyType:"stateVariable",variableName:"codePre"},format:{dependencyType:"stateVariable",variableName:"format"}}),definition:calculateCodesAdjacentToStrings},e.canBeModified={additionalStateVariablesDefined:["constantChildIndices","codeForExpression","inverseMaps","template","mathChildrenMapped"],returnDependencies:()=>({mathChildrenModifiable:{dependencyType:"child",childGroups:["maths"],variableNames:["canBeModified"]},displayedMathChildren:{dependencyType:"child",childGroups:["displayedMaths"]},expressionWithCodes:{dependencyType:"stateVariable",variableName:"expressionWithCodes"},modifyIndirectly:{dependencyType:"stateVariable",variableName:"modifyIndirectly"},fixed:{dependencyType:"stateVariable",variableName:"fixed"},codePre:{dependencyType:"stateVariable",variableName:"codePre"}}),definition:determineCanBeModified},e.mathChildrenByVectorComponent={returnDependencies:()=>({codePre:{dependencyType:"stateVariable",variableName:"codePre"},mathChildren:{dependencyType:"child",childGroups:["maths"]},expressionWithCodes:{dependencyType:"stateVariable",variableName:"expressionWithCodes"}}),definition:function({dependencyValues:e}){if(null===e.expressionWithCodes)return{setValue:{mathChildrenByVectorComponent:null}};let t=e.expressionWithCodes.tree,n=e.mathChildren.length;if(0===n||!Array.isArray(t)||!vectorOperators.includes(t[0]))return{setValue:{mathChildrenByVectorComponent:null}};let r={},a=0,i=e.codePre+a;for(let s=1;s=n)break}return{setValue:{mathChildrenByVectorComponent:r}}}},e.nDimensions={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition({dependencyValues:e}){let t=1,n=e.value.tree;if(Array.isArray(n))if(vectorAndListOperators.includes(n[0]))t=n.length-1;else if("matrix"===n[0]){let e=n[1].slice(1);1===e[0]?t=e[1]:1===e[1]&&(t=e[0])}else vectorOperators.includes(n[1][0])&&("^"===n[0]&&"T"===n[2]||"prime"===n[0])&&(t=n[1].length-1);return{setValue:{nDimensions:t}}}},e.vector={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"],returnWrappingComponents:e=>"x"===e?[]:[["vector",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,entryPrefixes:["x"],returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey:()=>({globalDependencies:{value:{dependencyType:"stateVariable",variableName:"value"}}}),arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t,arraySize:n}){let r=e.value.tree,a=!1,i={};if(Array.isArray(r))if(vectorAndListOperators.includes(r[0])){for(let e=0;ee.tree))]);else if("matrix"===s[0]){let e=s[1].slice(1);if(1===e[0]){let e=["tuple"];for(let t=0;te.tree))]],s[2]&&i.push(s[2]),i=me$3.fromAst(i));return i||(i=r.desiredVector[0]),{success:!0,instructions:[{setDependency:"value",desiredValue:i}]}}},e.x={isAlias:!0,targetVariableName:"x1"},e.y={isAlias:!0,targetVariableName:"x2"},e.z={isAlias:!0,targetVariableName:"x3"},e.matrixSize={public:!0,shadowingInstructions:{createComponentOfType:"numberList"},returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition({dependencyValues:e}){let t=[1,1],n=e.value.tree;return Array.isArray(n)&&(vectorAndListOperators.includes(n[0])?t=[n.length-1,1]:"matrix"===n[0]?t=n[1].slice(1):vectorOperators.includes(n[1][0])&&("^"===n[0]&&"T"===n[2]||"prime"===n[0])&&(t=[1,n[1].length-1])),{setValue:{matrixSize:t}}}},e.nRows={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({matrixSize:{dependencyType:"stateVariable",variableName:"matrixSize"}}),definition:({dependencyValues:e})=>({setValue:{nRows:e.matrixSize[0]}})},e.nColumns={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({matrixSize:{dependencyType:"stateVariable",variableName:"matrixSize"}}),definition:({dependencyValues:e})=>({setValue:{nColumns:e.matrixSize[1]}})},e.matrix={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"],returnWrappingComponents:e=>"matrixEntry"===e?[]:"row"===e?[["matrix","matrixRow"]]:"column"===e?[["matrix","matrixColumn"]]:[["matrixRow"],["matrix"]]},isArray:!0,nDimensions:2,entryPrefixes:["matrixEntry","row","column","rows","columns"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("matrixEntry"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}if("column"===e){let e=Number(t)-1;return Number.isInteger(e)&&e>=0?n?en+","+e)):[]:["0,"+e]:[]}if("rows"===e||"columns"===e){if(!n)return["0,0"];let e=[];for(let t=0;tt+","+n)));return e}},arrayVarNameFromPropIndex(e,t){if("matrix"===t||"rows"===t)return 1===e.length?"row"+e[0]:`matrixEntry${e[0]}_${e[1]}`;if("columns"===t)return 1===e.length?"column"+e[0]:`matrixEntry${e[1]}_${e[0]}`;if("row"===t.slice(0,3)){let n=Number(t.slice(3));if(Number.isInteger(n)&&n>0)return`matrixEntry${n}_${e[0]}`}if("column"===t.slice(0,6)){let n=Number(t.slice(6));if(Number.isInteger(n)&&n>0)return`matrixEntry${e[0]}_${n}`}return null},returnArraySizeDependencies:()=>({matrixSize:{dependencyType:"stateVariable",variableName:"matrixSize"}}),returnArraySize:({dependencyValues:e})=>e.matrixSize,returnArrayDependenciesByKey:()=>({globalDependencies:{value:{dependencyType:"stateVariable",variableName:"value"}}}),arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t,arraySize:n}){let r=e.value.tree,a=!1,i={};if(Array.isArray(r))if(vectorAndListOperators.includes(r[0])){for(let e=0;e({anchorAttr:{dependencyType:"attributeComponent",attributeName:"anchor",variableNames:["coords"]}}),definition:({dependencyValues:e})=>e.anchorAttr?{setValue:{anchor:e.anchorAttr.stateValues.coords}}:{useEssentialOrDefaultValue:{anchor:!0}},inverseDefinition:async({desiredStateVariableValues:e,dependencyValues:t,stateValues:n,initialChange:r})=>r&&!await n.draggable?{success:!1}:t.anchorAttr?{success:!0,instructions:[{setDependency:"anchorAttr",desiredValue:e.anchor,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"anchor",value:e.anchor}]}},e}static adapters=[{stateVariable:"number",stateVariablesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},"text",{componentType:"subsetOfReals",stateVariable:"value",substituteForPrimaryStateVariable:"subsetValue"}];async moveMath({x:e,y:t,z:n,transient:r,actionId:a}){let i=["vector"];return void 0!==e&&(i[1]=e),void 0!==t&&(i[2]=t),void 0!==n&&(i[3]=n),r?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],transient:r,actionId:a}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],actionId:a,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{x:e,y:t,z:n}}})}}function calculateExpressionWithCodes({dependencyValues:e,changes:t}){if(!("stringMathChildren"in t&&t.stringMathChildren.componentIdentitiesChanged||"displayedMathChildren"in t||"format"in t||"splitSymbols"in t||"parseScientificNotation"in t||"functionSymbols"in t||"mathChildrenFunctionSymbols"in t))return{useEssentialOrDefaultValue:{expressionWithCodes:!0}};if(0===e.stringMathChildren.length){if(e.displayedMathChildren.length>0){let t;try{t=me$3.fromLatex(e.displayedMathChildren[0].stateValues.latex)}catch(e){t=me$3.fromAst("_")}return{setValue:{expressionWithCodes:t},setEssentialValue:{expressionWithCodes:t}}}return{setValue:{expressionWithCodes:null},setEssentialValue:{expressionWithCodes:null}}}let n,r,a,i,s="",o=0,l="",u=e.stringMathChildren.compositeReplacementRange;e.groupCompositeReplacements&&u.length>0&&(a=0,i=u[a].firstInd);for(let[t,c]of e.stringMathChildren.entries()){if(void 0===n&&t===i){n=a,r=u[a].lastInd,l="";let s=r===t;if(!s)for(let n=t;n<=r;n++)if("string"==typeof e.stringMathChildren[n]){s=!0;break}s&&(u.length>n+1?(a=n+1,i=u[a].firstInd):(a=void 0,i=void 0),n=void 0,r=void 0)}if("string"==typeof c)s+=" "+c+" ";else{let t,r=e.codePre+o;o++,t="latex"===e.format?"\\operatorname{"+r+"}":" "+r+" ",void 0!==n?(l&&(l+=","),l+=t):s+=t}if(t===r){let o=s.trimEnd(),c=!1;if(0===o.length)c=!0;else{let n=o[o.length-1];if(["{","[","(","|",","].includes(n)){let n=e.stringMathChildren[t+1];if("string"!=typeof n)c=!0;else{let t=n.trimStart();if(0===t.length)c=!0;else{let n=t[0];"latex"===e.format&&"\\"===n&&t.length>1&&(n=t[1]),["}","]",")","|",","].includes(n)||(c=!0)}}}else c=!0}c&&(l="("+l+")"),s+=l,l="",u.length>n+1?(a=n+1,i=u[a].firstInd):(a=void 0,i=void 0),n=void 0,r=void 0}}let c=null,p=[...e.functionSymbols];if(p.push(...e.mathChildrenFunctionSymbols.map((t=>e.codePre+t))),""===s)c=me$3.fromAst("_");else if("text"===e.format){let t=getFromText({functionSymbols:p,splitSymbols:e.splitSymbols,parseScientificNotation:e.parseScientificNotation});try{c=t(s)}catch(e){c=me$3.fromAst("_"),console.log("Invalid value for a math of text format: "+s)}}else if("latex"===e.format){let t=getFromLatex({functionSymbols:p,splitSymbols:e.splitSymbols,parseScientificNotation:e.parseScientificNotation});try{c=t(s)}catch(e){c=me$3.fromAst("_"),console.log("Invalid value for a math of latex format: "+s)}}return{setValue:{expressionWithCodes:c},setEssentialValue:{expressionWithCodes:c}}}function calculateMathValue({dependencyValues:e}={}){if(null===e.expressionWithCodes)return{setValue:{unnormalizedValue:e.valueShadow}};let t={};for(let[n,r]of e.mathChildren.entries())t[e.codePre+n]=r.stateValues.value;let n=e.expressionWithCodes;return e.mathChildren.length>0&&(n=n.substitute(t)),n=me$3.fromAst(mergeListsWithOtherContainers(n.tree)),{setValue:{unnormalizedValue:n}}}function calculateCodesAdjacentToStrings({dependencyValues:e}){let t,n=[];for(let[r,a]of e.stringMathChildren.entries())if("string"==typeof a){let a=e.stringMathChildren[r+1];if(void 0!==a&&"string"==typeof a)continue;let i={};if(void 0!==t&&("latex"===e.format?i.prevCode="\\operatorname{"+e.codePre+t+"}":i.prevCode=e.codePre+t),void 0!==a){let n=0;void 0!==t&&(n=t+1),"latex"===e.format?i.nextCode="\\operatorname{"+e.codePre+n+"}":i.nextCode=e.codePre+n}n.push(i)}else void 0===t?t=0:t++;return{setValue:{codesAdjacentToStrings:n}}}function determineCanBeModified({dependencyValues:e}){if(!e.modifyIndirectly||e.fixed)return{setValue:{canBeModified:!1,constantChildIndices:null,codeForExpression:null,inverseMaps:null,template:null,mathChildrenMapped:null}};if(0===e.mathChildrenModifiable.length)return e.displayedMathChildren.length>0?{setValue:{canBeModified:!1,constantChildIndices:null,codeForExpression:null,inverseMaps:null,template:null,mathChildrenMapped:null}}:{setValue:{canBeModified:!0,constantChildIndices:null,codeForExpression:null,inverseMaps:null,template:null,mathChildrenMapped:null}};let t=[],n=[],r=[],a={};for(let[i,s]of e.mathChildrenModifiable.entries()){let o=e.codePre+i;!0===s.stateValues.canBeModified?(t.push(i),n.push(o)):(r.push(o),a[o]=i)}let i=e.codePre+"expr",s=checkForLinearExpression(me$3.utils.unflattenLeft(e.expressionWithCodes.tree),n,i,r);if(s.foundLinear){let e={},r=s.template,o=new Set;for(let r in s.mappings){e[r]=s.mappings[r];let a=e[r].mathChildSub;if(a){let i=t[n.indexOf(a)];e[r].mathChildInd=i,o.add(Number(i))}}return o.has=o.has.bind(o),{setValue:{canBeModified:!0,constantChildIndices:a,codeForExpression:i,inverseMaps:e,template:r,mathChildrenMapped:o}}}return{setValue:{canBeModified:!1,constantChildIndices:null,codeForExpression:null,inverseMaps:null,template:null,mathChildrenMapped:null}}}function checkForLinearExpression(e,t,n,r=[],a=[]){let i=me$3.variables(e);if(i.every((e=>!t.includes(e)))&&i.every((e=>!r.includes(e)))){let e={},t="x"+a.join("_");return e[t]={result:me$3.fromAst(n).simplify(),components:a},{foundLinear:!0,mappings:e,template:t}}if(!Array.isArray(e))return checkForScalarLinearExpression(e,t,n,a);let s=e[0],o=e.slice(1);if(vectorAndListOperators.includes(s)){let e={mappings:{},template:[s]},i=0;for(let s=0;s!t.includes(e)))?(n=["+",n,["-",i[0]]],checkForScalarLinearExpression(i[1],t,n,r)):me$3.variables(i[1]).every((e=>!t.includes(e)))?(n=["+",n,["-",i[1]]],checkForScalarLinearExpression(i[0],t,n,r)):{foundLinear:!1}:"*"===a?me$3.variables(i[0]).every((e=>!t.includes(e)))?(n=["/",n,i[0]],checkForScalarLinearExpression(i[1],t,n,r)):me$3.variables(i[1]).every((e=>!t.includes(e)))?(n=["/",n,i[1]],checkForScalarLinearExpression(i[0],t,n,r)):{foundLinear:!1}:"/"===a&&me$3.variables(i[1]).every((e=>!t.includes(e)))?(n=["*",n,i[1]],checkForScalarLinearExpression(i[0],t,n,r)):{foundLinear:!1}}async function invertMath({desiredStateVariableValues:e,dependencyValues:t,stateValues:n,workspace:r,overrideFixed:a,componentName:i}){if(!await n.canBeModified&&!a)return{success:!1};let s=t.mathChildren,o=t.stringChildren.length;if(1===s.length&&0===o)return{success:!0,instructions:[{setDependency:"mathChildren",desiredValue:e.unnormalizedValue,childIndex:0,variableIndex:0}]};let l=convertValueToMathExpression(e.unnormalizedValue),u=await preprocessMathInverseDefinition({desiredValue:l,stateValues:n,variableName:"value",workspace:r}),c=u.vectorComponentsNotAffected;if(l=u.desiredValue,0===s.length){let f=[];return o>0?f.push({setDependency:"expressionWithCodes",desiredValue:l}):f.push({setDependency:"valueShadow",desiredValue:l}),{success:!0,instructions:f}}let p=await getExpressionPieces({expression:l,stateValues:n});if(!p)return{success:!1};let d=[],m=[];if(c&&await n.mathChildrenByVectorComponent){let y=await n.mathChildrenByVectorComponent;for(let g of c)y[g]&&m.push(...y[g])}let h=await n.mathChildrenWithCanBeModified;for(let[b,v]of s.entries())if(n.mathChildrenMapped.has(b)&&h[b].stateValues.canBeModified){if(!m.includes(b)){let N=p[b],T={},C=!1,A=await n.constantChildIndices;for(let V in A){let x=A[V];T[V]=s[x].stateValues.value,C=!0}C&&(N=N.substitute(T)),N=N.simplify(),d.push({setDependency:"mathChildren",desiredValue:N,childIndex:b,variableIndex:0})}delete p[b]}if(o>0){let S=t.expressionWithCodes,w=t.codePre,E=w.length;function D(e){return"string"==typeof e&&e.substring(0,E)===w}function O(e){return Array.isArray(e)?flattenDeep(e.slice(1)).some(D):D(e)}if(vectorAndListOperators.includes(S.tree[0])&&!S.tree.slice(1).every(O)){let I=await n.inverseMaps;for(let R in p){let _=I[R];if(void 0!==_.mathChildInd)continue;let M=_.components;S=S.substitute_component(M,p[R])}d.push({setDependency:"expressionWithCodes",desiredValue:S})}}return{success:!0,instructions:d}}async function getExpressionPieces({expression:e,stateValues:t}){let n=await t.template,r=me$3.utils.match(e.tree,n);if(!(r||(r=me$3.utils.match(e.tuples_to_vectors().tree,me$3.fromAst(n).tuples_to_vectors().tree),r||(r=me$3.utils.match(e.to_intervals().tree,me$3.fromAst(n).to_intervals().tree),r||(r=me$3.utils.match(e.tuples_to_vectors().to_intervals().tree,me$3.fromAst(n).tuples_to_vectors().to_intervals().tree),r)))))return!1;let a={};for(let e in r){let n={};n[await t.codeForExpression]=r[e];let i=(await t.inverseMaps)[e];if(void 0!==i){let r=e;void 0!==i.mathChildInd&&(r=i.mathChildInd),a[r]=i.result.substitute(n),a[r]=normalizeMathExpression({value:a[r],simplify:await t.simplify,expand:await t.expand,createVectors:await t.createVectors,createIntervals:await t.createIntervals})}}return a}class Label extends InlineComponent{constructor(e){super(e),Object.assign(this.actions,{moveLabel:this.moveLabel.bind(this)})}static componentType="label";static renderChildren=!0;static rendererType="label";static includeBlankStringChildren=!0;static primaryStateVariableForDefinition="valueShadow";static createAttributesObject(){let e=super.createAttributesObject();return e.forObject={createTargetComponentNames:!0},e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.layer={createComponentOfType:"number",createStateVariable:"layer",defaultValue:0,public:!0,forRenderer:!0},e.anchor={createComponentOfType:"point"},e.positionFromAnchor={createComponentOfType:"text",createStateVariable:"positionFromAnchor",defaultValue:"center",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft","top","bottom","left","right","center"]},e.styleNumber.defaultValue=0,e}static returnChildGroups(){return[{group:"inlines",componentTypes:["_inline"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnSelectedStyleStateVariableDefinition();return Object.assign(e,t),e.valueShadow={hasEssential:!0,defaultValue:null,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{valueShadow:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"valueShadow",value:e.valueShadow}]})},e.hasLatex={public:!0,forRenderer:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["inlines"],variableNames:["text","latex","value","hasLatex","renderAsMath"],variablesOptional:!0},valueShadow:{dependencyType:"stateVariable",variableName:"valueShadow"}}),definition:function({dependencyValues:e}){if(0===e.inlineChildren.length&&null!==e.valueShadow){let t=e.valueShadow;return{setValue:{hasLatex:Boolean(/\\\(.*\\\)/.exec(t))}}}for(let t of e.inlineChildren)if("object"!=typeof t);else if("boolean"==typeof t.stateValues.hasLatex&&"string"==typeof t.stateValues.value&&"string"==typeof t.stateValues.text){if(t.stateValues.hasLatex)return{setValue:{hasLatex:!0}}}else if("boolean"==typeof t.stateValues.renderAsMath&&"string"==typeof t.stateValues.latex&&"string"==typeof t.stateValues.text){if(t.stateValues.renderAsMath)return{setValue:{hasLatex:!0}}}else if("string"==typeof t.stateValues.latex)return{setValue:{hasLatex:!0}};return{setValue:{hasLatex:!1}}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},additionalStateVariablesDefined:[{variableName:"latex",public:!0,shadowingInstructions:{createComponentOfType:"text"}},{variableName:"value",public:!0,forRenderer:!0,shadowingInstructions:{createComponentOfType:"label",addStateVariablesShadowingStateVariables:{hasLatex:{stateVariableToShadow:"hasLatex"}}}}],returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["inlines"],variableNames:["text","latex","value","hasLatex","renderAsMath"],variablesOptional:!0},valueShadow:{dependencyType:"stateVariable",variableName:"valueShadow"},hasLatex:{dependencyType:"stateVariable",variableName:"hasLatex"}}),definition:function({dependencyValues:e}){if(0===e.inlineChildren.length&&null!==e.valueShadow){let t=e.valueShadow,n=t;return e.hasLatex&&(n=n.replace(/\\\(/g,""),n=n.replace(/\\\)/g,"")),{setValue:{text:n,latex:n,value:t}}}let t="",n="";for(let r of e.inlineChildren)if("object"!=typeof r){let e=r.toString();t+=e,n+=e}else"boolean"==typeof r.stateValues.hasLatex&&"string"==typeof r.stateValues.value&&"string"==typeof r.stateValues.text?(t+=r.stateValues.text,n+=r.stateValues.value):"boolean"==typeof r.stateValues.renderAsMath&&"string"==typeof r.stateValues.latex&&"string"==typeof r.stateValues.text?r.stateValues.renderAsMath?(t+=r.stateValues.latex,n+="\\("+r.stateValues.latex+"\\)"):(t+=r.stateValues.text,n+=r.stateValues.text):"string"==typeof r.stateValues.latex?(t+=r.stateValues.latex,n+="\\("+r.stateValues.latex+"\\)"):"string"==typeof r.stateValues.text&&(t+=r.stateValues.text,n+=r.stateValues.text);return{setValue:{text:t,latex:t,value:n}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){let n;if("string"==typeof e.value)n=e.value;else if("string"==typeof e.text)n=e.text;else{if("string"!=typeof e.latex)return{success:!1};n=e.latex}if(0===t.inlineChildren.length&&null!==t.valueShadow)return{success:!0,instructions:[{setDependency:"valueShadow",desiredValue:n}]};if(1===t.inlineChildren.length){let n=t.inlineChildren[0],r=e.value;if("object"!=typeof n)return{success:!0,instructions:[{setDependency:"inlineChildren",desiredValue:r,childIndex:0}]};if("boolean"==typeof n.stateValues.hasLatex&&"string"==typeof n.stateValues.value&&"string"==typeof n.stateValues.text)return{success:!0,instructions:[{setDependency:"inlineChildren",desiredValue:r,childIndex:0,variableIndex:2}]};if("boolean"==typeof n.stateValues.renderAsMath&&"string"==typeof n.stateValues.latex&&"string"==typeof n.stateValues.text){if(n.stateValues.renderAsMath){let e=r.match(/^\\\((.*)\\\)/);return e&&(r=e[1]),{success:!0,instructions:[{setDependency:"inlineChildren",desiredValue:r,childIndex:0,variableIndex:1}]}}return{success:!0,instructions:[{setDependency:"inlineChildren",desiredValue:r,childIndex:0,variableIndex:0}]}}if("string"==typeof n.stateValues.latex){let e=r.match(/^\\\((.*)\\\)/);return e&&(r=e[1]),{success:!0,instructions:[{setDependency:"inlineChildren",desiredValue:r,childIndex:0,variableIndex:1}]}}return"string"==typeof n.stateValues.text?{success:!0,instructions:[{setDependency:"inlineChildren",desiredValue:r,childIndex:0,variableIndex:0}]}:{success:!1}}return{success:!1}}},e.forObjectComponentName={returnDependencies:()=>({forObject:{dependencyType:"attributeTargetComponentNames",attributeName:"forObject"}}),definition({dependencyValues:e}){let t;return t=1===e.forObject?.length?e.forObject[0].absoluteName:null,{setValue:{forObjectComponentName:t}}}},e.anchor={defaultValue:me$3.fromText("(0,0)"),public:!0,forRenderer:!0,hasEssential:!0,shadowingInstructions:{createComponentOfType:"point"},returnDependencies:()=>({anchorAttr:{dependencyType:"attributeComponent",attributeName:"anchor",variableNames:["coords"]}}),definition:({dependencyValues:e})=>e.anchorAttr?{setValue:{anchor:e.anchorAttr.stateValues.coords}}:{useEssentialOrDefaultValue:{anchor:!0}},inverseDefinition:async({desiredStateVariableValues:e,dependencyValues:t,stateValues:n,initialChange:r})=>r&&!await n.draggable?{success:!1}:t.anchorAttr?{success:!0,instructions:[{setDependency:"anchorAttr",desiredValue:e.anchor,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"anchor",value:e.anchor}]}},e}static adapters=["text"];async moveLabel({x:e,y:t,z:n,transient:r,actionId:a}){let i=["vector"];return void 0!==e&&(i[1]=e),void 0!==t&&(i[2]=t),void 0!==n&&(i[3]=n),r?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],transient:r,actionId:a}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],actionId:a,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{x:e,y:t,z:n}}})}}function returnGroupIntoComponentTypeSeparatedBySpaces({componentType:e,forceComponentType:t=!1}){return function({matchedChildren:n,componentInfoObjects:r}){let a=[],i=[];function s(){let n=!1;if(t){if(1===i.length){let t=i[0],s=t.componentType;"copy"===s&&t.attributes?.createComponentOfType&&(t.attributes.nComponents&&1!==t.attributes.nComponents.primitive||(s=t.attributes.createComponentOfType.primitive)),r.isInheritedComponentType({inheritedComponentType:s,baseComponentType:e})&&(a.push(t),n=!0)}}else 1===i.length&&"string"!=typeof i[0]&&(a.push(i[0]),n=!0);!n&&i.length>0&&a.push({componentType:e,children:i}),i=[]}for(let e of n)if("string"!=typeof e)i.push(e);else{let t=e.split(/\s+/),n=t[0];""===n?s():i.push(n);for(let e of t.slice(1))s(),""!==e&&i.push(e)}return s(),{success:!0,newChildren:a}}}function returnBreakStringsIntoComponentTypeBySpaces({componentType:e}){return function({matchedChildren:t}){let n=t.reduce((function(t,n){return"string"==typeof n?[...t,...n.split(/\s+/).filter((e=>e)).map((t=>({componentType:e,children:[t]})))]:[...t,n]}),[]);return{success:!0,newChildren:n}}}class MathList extends InlineComponent{static componentType="mathList";static renderChildren=!0;static includeBlankStringChildren=!0;static removeBlankStringChildrenPostSugar=!0;static stateVariableForAttributeValue="maths";static primaryStateVariableForDefinition="mathsShadow";static descendantCompositesMustHaveAReplacement=!1;static createAttributesObject(){let e=super.createAttributesObject();return e.unordered={createComponentOfType:"boolean",createStateVariable:"unordered",defaultValue:!1,public:!0},e.maximumNumber={createComponentOfType:"number",createStateVariable:"maximumNumber",defaultValue:null,public:!0},e.mergeMathLists={createComponentOfType:"boolean"},e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.padZeros={createComponentOfType:"boolean",createStateVariable:"padZeros",defaultValue:!1,public:!0},e}static returnSugarInstructions(){let e=super.returnSugarInstructions(),t=returnGroupIntoComponentTypeSeparatedBySpaces({componentType:"math"}),n=returnBreakStringsIntoComponentTypeBySpaces({componentType:"math"});return e.push({replacementFunction:function({matchedChildren:e,isAttributeComponent:r=!1,createdFromMacro:a=!1}){return r&&!a?t({matchedChildren:e}):n({matchedChildren:e})}}),e}static returnChildGroups(){return[{group:"maths",componentTypes:["math"]},{group:"mathLists",componentTypes:["mathList"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.overrideChildHide={returnDependencies:()=>({}),definition:()=>({setValue:{overrideChildHide:!0}})},e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.displayDigitsAttr){let n=t.displayDigitsAttr,r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!n&&!r){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({}),definition:()=>({useEssentialOrDefaultValue:{mathsShadow:!0}})},e.mergeMathLists={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({mergeMathListsAttr:{dependencyType:"attributeComponent",attributeName:"mergeMathLists",variableNames:["value"]},mathListChildren:{dependencyType:"child",childGroups:["mathLists"],skipComponentNames:!0},mathChildren:{dependencyType:"child",childGroups:["maths"],skipComponentNames:!0}}),definition:({dependencyValues:e})=>({setValue:{mergeMathLists:e.mergeMathListsAttr?.stateValues.value||0===e.mathListChildren.length&&1===e.mathChildren.length}})},e.nComponents={public:!0,shadowingInstructions:{createComponentOfType:"number"},stateVariablesDeterminingDependencies:["mergeMathLists"],additionalStateVariablesDefined:["childIndexByArrayKey"],returnDependencies({stateValues:e}){let t={maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"},mergeMathLists:{dependencyType:"stateVariable",variableName:"mergeMathLists"},mathsShadow:{dependencyType:"stateVariable",variableName:"mathsShadow"}};return e.mergeMathLists?t.mathAndMathListChildren={dependencyType:"child",childGroups:["maths","mathLists"],variableNames:["value","nComponents"],variablesOptional:!0}:(t.mathListChildren={dependencyType:"child",childGroups:["mathLists"],variableNames:["nComponents"]},t.mathAndMathListChildren={dependencyType:"child",childGroups:["maths","mathLists"],skipComponentNames:!0}),t},definition:function({dependencyValues:e,componentInfoObjects:t}){let n=0,r=[];if(e.mathAndMathListChildren.length>0)if(e.mergeMathLists)for(let[a,i]of e.mathAndMathListChildren.entries())if(t.isInheritedComponentType({inheritedComponentType:i.componentType,baseComponentType:"mathList"})){for(let e=0;ea&&(n=a,r=r.slice(0,a)),{setValue:{nComponents:n,childIndexByArrayKey:r},checkForActualChange:{nComponents:!0}}}},e.maths={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},isArray:!0,entryPrefixes:["math"],stateVariablesDeterminingDependencies:["mergeMathLists","childIndexByArrayKey"],returnArraySizeDependencies:()=>({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"}}),returnArraySize:({dependencyValues:e})=>[e.nComponents],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=[],a="1";t.childIndexByArrayKey[r]&&(e=[t.childIndexByArrayKey[r][0]],a=t.childIndexByArrayKey[r][1]+1),n[r]={mathAndMathListChildren:{dependencyType:"child",childGroups:["maths","mathLists"],variableNames:["value","math"+a],variablesOptional:!0,childIndices:e}}}return{globalDependencies:{mergeMathLists:{dependencyType:"stateVariable",variableName:"mergeMathLists"},childIndexByArrayKey:{dependencyType:"stateVariable",variableName:"childIndexByArrayKey"},mathsShadow:{dependencyType:"stateVariable",variableName:"mathsShadow"}},dependenciesByKey:n}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};for(let a of n){let n=t[a].mathAndMathListChildren[0];if(n)if(void 0!==n.stateValues.value){let t=n.stateValues.value;if(e.mergeMathLists&&Array.isArray(t.tree)&&"list"===t.tree[0]){let n=e.childIndexByArrayKey[a][1];r[a]=t.get_component(n)}else r[a]=t}else{let t=e.childIndexByArrayKey[a][1]+1;r[a]=n.stateValues["math"+t]}else null!==e.mathsShadow&&(r[a]=e.mathsShadow[a])}return{setValue:{maths:r}}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,stateValues:a,workspace:i}){if(t.mergeMathLists){let t=[],s=await a.childIndexByArrayKey,o=[];for(let l in e.maths){if(!n[l])continue;if(o.includes(l))continue;let u;if(void 0!==s[l][2]){let t=Number(l)-s[l][1],n=t+s[l][2]-1;i.desiredMaths||(i.desiredMaths=[]);let r=["list"];for(let s=t;s<=n;s++)void 0!==e.maths[s]?i.desiredMaths[s]=convertValueToMathExpression(e.maths[s]):void 0===i.desiredMaths[s]&&(i.desiredMaths[s]=(await a.maths)[s]),r.push(i.desiredMaths[s].tree),o.push(s.toString());u=me$3.fromAst(r)}else u=e.maths[l];let c=n[l].mathAndMathListChildren[0];c&&(void 0!==c.stateValues.value?t.push({setDependency:r[l].mathAndMathListChildren,desiredValue:u,childIndex:0,variableIndex:0}):t.push({setDependency:r[l].mathAndMathListChildren,desiredValue:u,childIndex:0,variableIndex:1}))}return{success:!0,instructions:t}}let s=[];for(let t in e.maths){if(!n[t])continue;let a=n[t].mathAndMathListChildren[0];a&&(void 0!==a.stateValues.value?s.push({setDependency:r[t].mathAndMathListChildren,desiredValue:e.maths[t],childIndex:0,variableIndex:0}):s.push({setDependency:r[t].mathAndMathListChildren,desiredValue:e.maths[t],childIndex:0,variableIndex:1}))}return{success:!0,instructions:s}}},e.math={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},returnDependencies:()=>({maths:{dependencyType:"stateVariable",variableName:"maths"}}),definition({dependencyValues:e}){let t;return t=0===e.maths.length?me$3.fromAst("_"):1===e.maths.length?e.maths[0]:me$3.fromAst(["list",...e.maths.map((e=>e.tree))]),{setValue:{math:t}}}},e.nValues={isAlias:!0,targetVariableName:"nComponents"},e.values={isAlias:!0,targetVariableName:"maths"},e.latex={additionalStateVariablesDefined:["latexs"],public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({mathAndMathListChildren:{dependencyType:"child",childGroups:["maths","mathLists"],variableNames:["valueForDisplay","latex","latexs"],variablesOptional:!0},maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"},mergeMathLists:{dependencyType:"stateVariable",variableName:"mergeMathLists"},mathsShadow:{dependencyType:"stateVariable",variableName:"mathsShadow"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"}}),definition:function({dependencyValues:e,usedDefault:t}){let n=[],r={};if(e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(r.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(r.padToDigits=e.displayDigits)),e.mathAndMathListChildren.length>0)for(let t of e.mathAndMathListChildren)if(t.stateValues.valueForDisplay){let a=t.stateValues.valueForDisplay;if(e.mergeMathLists&&Array.isArray(a.tree)&&"list"===a.tree[0])for(let e=0;eroundForDisplay({value:n,dependencyValues:e,usedDefault:t}).toLatex(r))));let a=e.maximumNumber;return null!==a&&n.length>a&&(a=Math.max(0,Math.floor(a)),n=n.slice(0,a)),{setValue:{latex:n.join(", "),latexs:n}}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},additionalStateVariablesDefined:["texts"],returnDependencies:()=>({mathAndMathListChildren:{dependencyType:"child",childGroups:["maths","mathLists"],variableNames:["valueForDisplay","text","texts"],variablesOptional:!0},maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"},mergeMathLists:{dependencyType:"stateVariable",variableName:"mergeMathLists"},mathsShadow:{dependencyType:"stateVariable",variableName:"mathsShadow"}}),definition:function({dependencyValues:e}){let t=[];if(e.mathAndMathListChildren.length>0)for(let n of e.mathAndMathListChildren)if(n.stateValues.valueForDisplay){let r=n.stateValues.valueForDisplay;if(e.mergeMathLists&&Array.isArray(r.tree)&&"list"===r.tree[0])for(let e=0;ee.toString())));let n=e.maximumNumber;return null!==n&&t.length>n&&(n=Math.max(0,Math.floor(n)),t=t.slice(0,n)),{setValue:{text:t.join(", "),texts:t}}}},e.componentNamesInList={returnDependencies:()=>({mathAndMathListChildren:{dependencyType:"child",childGroups:["maths","mathLists"],variableNames:["componentNamesInList"],variablesOptional:!0},maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=[];for(let r of e.mathAndMathListChildren)t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"mathList"})?n.push(...r.stateValues.componentNamesInList):n.push(r.componentName);let r=e.maximumNumber;return null!==r&&n.length>r&&(r=Math.max(0,Math.floor(r)),n=n.slice(0,r)),{setValue:{componentNamesInList:n}}}},e.nComponentsToDisplayByChild={additionalStateVariablesDefined:["nChildrenToRender"],returnDependencies:()=>({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"},mathListChildren:{dependencyType:"child",childGroups:["mathLists"],variableNames:["nComponents"]},mathAndMathListChildren:{dependencyType:"child",childGroups:["maths","mathLists"],skipComponentNames:!0},parentNComponentsToDisplayByChild:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"nComponentsToDisplayByChild"}}),definition:function({dependencyValues:e,componentInfoObjects:t,componentName:n}){let r=e.nComponents;null!==e.parentNComponentsToDisplayByChild&&(r=e.parentNComponentsToDisplayByChild[n]);let a={},i=0,s=0,o=0;for(let n of e.mathAndMathListChildren){let l=Math.max(0,r-i);if(l>0&&s++,t.isInheritedComponentType({inheritedComponentType:n.componentType,baseComponentType:"mathList"})){let t=e.mathListChildren[o];o++;let n=Math.min(l,t.stateValues.nComponents);a[t.componentName]=n,i+=n}else i+=1}return{setValue:{nComponentsToDisplayByChild:a,nChildrenToRender:s}}},markStale:()=>({updateRenderedChildren:!0})},e}static adapters=[{stateVariable:"math",stateVariablesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},"text"]}class Columns extends Text{static componentType="columns";static rendererType="text"}class Title extends TextOrInline{static componentType="title"}class RightHandSide extends MathComponent{static componentType="rightHandSide";static rendererType="math"}class Description extends TextOrInline{static componentType="description";static rendererType=void 0}class Else extends Template{static componentType="else"}class Xlabel extends Label{static componentType="xlabel";static rendererType="label"}class Ylabel extends Label{static componentType="ylabel";static rendererType="label"}class MatrixRow extends MathList{static componentType="matrixRow";static rendererType="mathList"}class MatrixColumn extends MathList{static componentType="matrixColumn";static rendererType="mathList"}var Aliases=Object.freeze({__proto__:null,Columns:Columns,Title:Title,RightHandSide:RightHandSide,Description:Description,Else:Else,Xlabel:Xlabel,Ylabel:Ylabel,MatrixRow:MatrixRow,MatrixColumn:MatrixColumn});class M$3 extends InlineComponent{constructor(e){super(e),Object.assign(this.actions,{moveMath:this.moveMath.bind(this)})}static componentType="m";static rendererType="math";static includeBlankStringChildren=!0;static primaryStateVariableForDefinition="latex";static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.layer={createComponentOfType:"number",createStateVariable:"layer",defaultValue:0,public:!0,forRenderer:!0},e.anchor={createComponentOfType:"point"},e.positionFromAnchor={createComponentOfType:"text",createStateVariable:"positionFromAnchor",defaultValue:"center",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft","top","bottom","left","right","center"]},e.styleNumber.defaultValue=0,e}static returnChildGroups(){return[{group:"inline",componentTypes:["_inline"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnSelectedStyleStateVariableDefinition();return Object.assign(e,t),e.latex={public:!0,shadowingInstructions:{createComponentOfType:"text"},defaultValue:"",hasEssential:!0,forRenderer:!0,returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["inline"],variableNames:["latex","text"],variablesOptional:!0}}),definition:function({dependencyValues:e}){if(0===e.inlineChildren.length)return{useEssentialOrDefaultValue:{latex:!0}};let t="";for(let n of e.inlineChildren)"object"!=typeof n?t+=n:"string"==typeof n.stateValues.latex?t+=n.stateValues.latex:"string"==typeof n.stateValues.text&&(t+=n.stateValues.text);return{setValue:{latex:t}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){if("string"!=typeof e.latex)return{success:!1};if(0===t.inlineChildren.length)return{success:!0,instructions:[{setEssentialValue:"latex",value:e.latex}]};if(1===t.inlineChildren.length){let n=t.inlineChildren[0];return"object"!=typeof n?{success:!0,instructions:[{setDependency:"inlineChildren",desiredValue:e.latex,childIndex:0}]}:"string"==typeof n.stateValues.latex?{success:!0,instructions:[{setDependency:"inlineChildren",desiredValue:e.latex,childIndex:0,variableIndex:0}]}:"string"==typeof n.stateValues.text?{success:!0,instructions:[{setDependency:"inlineChildren",desiredValue:e.latex,childIndex:0,variableIndex:1}]}:{success:!1}}return{success:!1}}},e.latexWithInputChildren={forRenderer:!0,returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["inline"],variableNames:["latex","text"],variablesOptional:!0},latex:{dependencyType:"stateVariable",variableName:"latex"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){if(0===e.inlineChildren.length)return{setValue:{latexWithInputChildren:[e.latex]}};let n=[],r="",a=0;for(let i of e.inlineChildren)"object"!=typeof i?r+=i:t.isInheritedComponentType({inheritedComponentType:i.componentType,baseComponentType:"input"})?(r.length>0&&(n.push(r),r=""),n.push(a),a++):"string"==typeof i.stateValues.latex?r+=i.stateValues.latex:"string"==typeof i.stateValues.text&&(r+=i.stateValues.text);return r.length>0&&n.push(r),{setValue:{latexWithInputChildren:n}}}},e.renderMode={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{renderMode:"inline"}})},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({latex:{dependencyType:"stateVariable",variableName:"latex"}}),definition:function({dependencyValues:e}){let t;try{t=me$3.fromAst(latexToAst.convert(e.latex))}catch(t){return{setValue:{text:e.latex}}}return{setValue:{text:superSubscriptsToUnicode(t.toString())}}}},e.anchor={defaultValue:me$3.fromText("(0,0)"),public:!0,forRenderer:!0,hasEssential:!0,shadowingInstructions:{createComponentOfType:"point"},returnDependencies:()=>({anchorAttr:{dependencyType:"attributeComponent",attributeName:"anchor",variableNames:["coords"]}}),definition:({dependencyValues:e})=>e.anchorAttr?{setValue:{anchor:e.anchorAttr.stateValues.coords}}:{useEssentialOrDefaultValue:{anchor:!0}},inverseDefinition:async({desiredStateVariableValues:e,dependencyValues:t,stateValues:n,initialChange:r})=>r&&!await n.draggable?{success:!1}:t.anchorAttr?{success:!0,instructions:[{setDependency:"anchorAttr",desiredValue:e.anchor,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"anchor",value:e.anchor}]}},e}async moveMath({x:e,y:t,z:n,transient:r,actionId:a}){let i=["vector"];return void 0!==e&&(i[1]=e),void 0!==t&&(i[2]=t),void 0!==n&&(i[3]=n),r?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],transient:r,actionId:a}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],actionId:a,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{x:e,y:t,z:n}}})}}class Me$2 extends M$3{static componentType="me";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.renderMode.definition=()=>({setValue:{renderMode:"display"}}),e}}class Men extends M$3{static componentType="men";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.renderMode.definition=()=>({setValue:{renderMode:"numbered"}}),e.equationTag={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({equationCounter:{dependencyType:"counter",counterName:"equation"}}),definition:({dependencyValues:e})=>({setValue:{equationTag:String(e.equationCounter)}})},e}}var MMeMen=Object.freeze({__proto__:null,M:M$3,Me:Me$2,Men:Men});class Md extends InlineComponent{constructor(e){super(e),Object.assign(this.actions,{moveMath:this.moveMath.bind(this)})}static componentType="md";static rendererType="math";static primaryStateVariableForDefinition="latex";static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.layer={createComponentOfType:"number",createStateVariable:"layer",defaultValue:0,public:!0,forRenderer:!0},e.anchor={createComponentOfType:"point"},e.positionFromAnchor={createComponentOfType:"text",createStateVariable:"positionFromAnchor",defaultValue:"center",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft","top","bottom","left","right","center"]},e.styleNumber.defaultValue=0,e}static returnChildGroups(){return[{group:"mrows",componentTypes:["mrow"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnSelectedStyleStateVariableDefinition();return Object.assign(e,t),e.mrowChildNames={forRenderer:!0,returnDependencies:()=>({mrowChildren:{dependencyType:"child",childGroups:["mrows"]}}),definition:({dependencyValues:e})=>({setValue:{mrowChildNames:e.mrowChildren.map((e=>e.componentName))}})},e.latex={public:!0,shadowingInstructions:{createComponentOfType:"text"},defaultValue:"",hasEssential:!0,shadowVariable:!0,forRenderer:!0,returnDependencies:()=>({mrowChildren:{dependencyType:"child",childGroups:["mrows"],variableNames:["latex","hide","equationTag","numbered"]}}),definition:function({dependencyValues:e}){if(e.mrowChildren.length>0){let t="";for(let n of e.mrowChildren)n.stateValues.hide||(t.length>0&&(t+="\\\\"),n.stateValues.numbered?t+=`\\tag{${n.stateValues.equationTag}}`:t+="\\notag ",t+=n.stateValues.latex);return{setValue:{latex:t}}}return{useEssentialOrDefaultValue:{latex:!0}}}},e.latexWithInputChildren={forRenderer:!0,returnDependencies:()=>({mrowChildren:{dependencyType:"child",childGroups:["mrows"],variableNames:["latexWithInputChildren","hide","equationTag","numbered"]},latex:{dependencyType:"stateVariable",variableName:"latex"}}),definition:function({dependencyValues:e}){if(e.mrowChildren.length>0){let t=[],n=0,r="";for(let a of e.mrowChildren)if(!a.stateValues.hide){r.length>0&&(r+="\\\\"),a.stateValues.numbered?r+=`\\tag{${a.stateValues.equationTag}}`:r+="\\notag ";for(let e of a.stateValues.latexWithInputChildren)"number"==typeof e?(r.length>0&&(t.push(r),r=""),t.push(n),n++):r+=e}return r.length>0&&t.push(r),{setValue:{latexWithInputChildren:t}}}return{setValue:{latexWithInputChildren:[e.latex]}}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({latex:{dependencyType:"stateVariable",variableName:"latex"}}),definition:function({dependencyValues:e}){let t;try{t=e.latex.replaceAll("\\notag","").replaceAll("\\amp","").split("\\\\").map((e=>me$3.fromAst(latexToAst.convert(e)).toString())).join("\\\\\n")}catch(t){return{setValue:{text:e.latex}}}return{setValue:{text:superSubscriptsToUnicode(t.toString())}}}},e.renderMode={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{renderMode:"align"}})},e.numbered={returnDependencies:()=>({}),definition:()=>({setValue:{numbered:!1}})},e.anchor={defaultValue:me$3.fromText("(0,0)"),public:!0,forRenderer:!0,hasEssential:!0,shadowingInstructions:{createComponentOfType:"point"},returnDependencies:()=>({anchorAttr:{dependencyType:"attributeComponent",attributeName:"anchor",variableNames:["coords"]}}),definition:({dependencyValues:e})=>e.anchorAttr?{setValue:{anchor:e.anchorAttr.stateValues.coords}}:{useEssentialOrDefaultValue:{anchor:!0}},inverseDefinition:async({desiredStateVariableValues:e,dependencyValues:t,stateValues:n,initialChange:r})=>r&&!await n.draggable?{success:!1}:t.anchorAttr?{success:!0,instructions:[{setDependency:"anchorAttr",desiredValue:e.anchor,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"anchor",value:e.anchor}]}},e}async moveMath({x:e,y:t,z:n,transient:r,actionId:a}){let i=["vector"];return void 0!==e&&(i[1]=e),void 0!==t&&(i[2]=t),void 0!==n&&(i[3]=n),r?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],transient:r,actionId:a}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],actionId:a,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{x:e,y:t,z:n}}})}}class Mdn extends Md{static componentType="mdn";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numbered={returnDependencies:()=>({}),definition:()=>({setValue:{numbered:!0}})},e}}class Mrow extends M$3{static componentType="mrow";static createAttributesObject(){let e=super.createAttributesObject();return e.number={createComponentOfType:"boolean"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.renderMode.definition=()=>({setValue:{renderMode:"display"}}),e.numbered={forRenderer:!0,returnDependencies:()=>({parentNumbered:{dependencyType:"parentStateVariable",variableName:"numbered"},numberAttr:{dependencyType:"attributeComponent",attributeName:"number",variableNames:["value"]}}),definition({dependencyValues:e}){let t;return t=null!==e.numberAttr?e.numberAttr.stateValues.value:e.parentNumbered,{setValue:{numbered:t}}}},e.equationTag={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,stateVariablesDeterminingDependencies:["numbered"],returnDependencies:({stateValues:e})=>e.numbered?{equationCounter:{dependencyType:"counter",counterName:"equation"}}:{},definition:({dependencyValues:e})=>void 0!==e.equationCounter?{setValue:{equationTag:String(e.equationCounter)}}:{setValue:{equationTag:null}}},e}}var MdMdnMrow=Object.freeze({__proto__:null,Md:Md,Mdn:Mdn,Mrow:Mrow});function periodicSetEquality(e,t,{min_elements_match:n=3,match_partial:r=!1}={}){if(!is_periodic_set(e))return!1;if(is_periodic_set(t)){if(r){let n=contained_in(e.tree,t.tree,r);if(!1===n)return 0;let a=contained_in(t.tree,e.tree,r);return!1===a?0:!0===n?!0===a?1:a:!0===a?n:Math.min(n,a)}return contained_in(e.tree,t.tree,r)&&contained_in(t.tree,e.tree,r)}{let a=e.tree.slice(1);if(a.length>1)return!1;let i=me$3.fromAst(a[0][1]).evaluate_to_constant(),s=me$3.fromAst(["apply","abs",a[0][2]]).evaluate_to_constant();if(!Number.isFinite(i)||!Number.isFinite(s))return!1;let o=a[0][3],l=a[0][4];if(o!==-1/0||l!==1/0)return!1;if("list"!==t.tree[0])return!1;let u=t.tree.slice(1),c=0;if("ldots"===u[0][0])c++,u=u.slice(1);else if(!r)return!1;if("ldots"===u[u.length-1][0])c++,u=u.slice(0,u.length-1);else if(!r)return!1;let p=u.length;if(0===p)return!1;if(!r&&pme$3.fromAst(e).evaluate_to_constant())).map((e=>Number.isFinite(e)?e:NaN));let d=me$3.math.mod(u[0]-i,s);if(!(me$3.math.min(d,s-d)<1e-10*s))return!1;let m=1;for(let e=1;e=n)return!0;let h=m/Math.max(p,n);return h*=(9+c/2)/10,h}}function is_periodic_set(e){var t=e.tree;if(!Array.isArray(t))return!1;if("periodic_set"!==t[0])return!1;var n=t.slice(1);for(var r of n){if(!Array.isArray(r))return!1;if("tuple"!==r[0])return!1;if(5!==r.length)return!1}return!0}function contained_in(e,t,n){if("periodic_set"===e[0]){if(n){let r=0;for(let a of e.slice(1)){let e=contained_in(a,t,n);!0===e?r++:!1!==e&&(r+=e)}let a=e.length-1;return r===a||0!==r&&r/a}return e.slice(1).every((e=>contained_in(e,t)))}var r=e[1],a=e[2],i=e[3],s=e[4];if(i!==-1/0||s!==1/0)return!1;r=me$3.fromAst(["/",r,a]).evaluate_to_constant();var o=t.slice(1),l=[];for(let e=0;e1e3)return!1;let c=s.d;l.push([u,c,r,i])}for(l.sort();;){if(1!==l[0][0])break;let e=l[0][2],t=l[0][3],n=me$3.fromAst(["+",e,["-",r]]).evaluate_to_constant();if(Number.isFinite(n)&&Number.isFinite(t)&&(n=me$3.math.mod(n,t),me$3.math.min(n,t-n)<1e-10*t))return!0;if(l.splice(0,1),0===l.length)return!1}var u=[...new Set(l.map((e=>e[0])))];let c=0;for(let e of u){let t=l.map((function(t,n){let r=e/t[0];return Number.isInteger(r)?[t[0],r,n]:void 0})).filter((e=>e)),a=[];for(let n of t){let t=n[0],i=n[1],s=n[2],o=l[s][2],u=l[s][3];for(let n=0;nc&&(c=t)}}return!!(n&&c>0)&&c}const nonTupleVectorOperators=["vector","altvector"];function checkEquality({object1:e,object2:t,isUnordered:n=!1,partialMatches:r=!1,matchByExactPositions:a=!1,symbolicEquality:i=!1,simplify:s="none",expand:o=!1,allowedErrorInNumbers:l=0,includeErrorInNumberExponents:u=!1,allowedErrorIsAbsolute:c=!1,nSignErrorsMatched:p=0,nPeriodicSetMatchesRequired:d=3,caseInsensitiveMatch:m=!1,matchBlanks:h=!1}){let f=!1;if(e instanceof me$3.class){if(f=!0,!(t instanceof me$3.class)){if("number"!=typeof t&&"string"!=typeof t)return{fraction_equal:0};t=me$3.fromAst(t)}}else if(t instanceof me$3.class){if(f=!0,"number"!=typeof e&&"string"!=typeof e)return{fraction_equal:0};e=me$3.fromAst(e)}let y,g=function(e,t=!1){e instanceof me$3.class||(e=me$3.fromAst(e)),e=e.normalize_function_names().normalize_applied_functions(),m&&(e=me$3.fromAst(setStringsInTreeToLowerCase(e.tree)));let n=s,r=o;return t&&(n="full",r=!0),"none"===n?l>0&&(e=e.constants_to_floats()):e="numberspreserveorder"===n?e.evaluate_numbers({max_digits:1/0,skip_ordering:!0}):"number"===n?e.evaluate_numbers({max_digits:1/0}):e.evaluate_numbers({max_digits:1/0,evaluate_functions:!0}),normalizeMathExpression({value:e,simplify:n,expand:r})};y=f?i?function(e,t){let n=e,r=t;if(e instanceof me$3.class||(n=me$3.fromAst(e)),t instanceof me$3.class||(r=me$3.fromAst(t)),p>0){r=JSON.parse(JSON.stringify(r),me$3.reviver);let e=function(e,t){return!e.variables().includes("_")&&!t.variables().includes("_")&&(e=g(e)).equalsViaSyntax(t,{allowed_error_in_numbers:l,include_error_in_number_exponents:u,allowed_error_is_absolute:c,allow_blanks:h})};return n.tree.im||r.tree.im?{fraction_equal:0}:{fraction_equal:me$3.equalSpecifiedSignErrors(r,n,{equalityFunction:e,n_sign_errors:p})?1:0}}if(n.variables().includes("_")||r.variables().includes("_"))return{fraction_equal:0};if(n.tree.im||r.tree.im)return{fraction_equal:0};return{fraction_equal:n.equalsViaSyntax(r,{allowed_error_in_numbers:l,include_error_in_number_exponents:u,allowed_error_is_absolute:c,allow_blanks:h})?1:0}}:function(e,t){let n=e,r=t;if(e instanceof me$3.class||(n=me$3.fromAst(e)),t instanceof me$3.class||(r=me$3.fromAst(t)),m&&(n=me$3.fromAst(setStringsInTreeToLowerCase(n.tree)),r=me$3.fromAst(setStringsInTreeToLowerCase(r.tree))),p>0){r=JSON.parse(JSON.stringify(r),me$3.reviver);let e=function(e,t){return e.equals(t,{allowed_error_in_numbers:l,include_error_in_number_exponents:u,allowed_error_is_absolute:c,allow_blanks:h})};return n.tree.im||r.tree.im?{fraction_equal:0}:{fraction_equal:me$3.equalSpecifiedSignErrors(r,n,{equalityFunction:e,n_sign_errors:p})?1:0}}if(n.tree.im||r.tree.im)return{fraction_equal:0};return{fraction_equal:n.equals(r,{allowed_error_in_numbers:l,include_error_in_number_exponents:u,allowed_error_is_absolute:c,allow_blanks:h})?1:0}}:(e,t)=>(m&&(e=convertStringsToLowerCase(e),t=convertStringsToLowerCase(t)),{fraction_equal:deepCompare(e,t)?1:0});let b=!1,v=!1;if(f){e=g(e,!i),t=g(t,!i);let s=e.tree[0],o=t.tree[0];if("periodic_set"===s||"periodic_set"===o){let n=e,a=t;"periodic_set"!==s&&(n=t,a=e);let i=periodicSetEquality(n,a,{match_partial:r,min_elements_match:d});return!0===i?{fraction_equal:1}:!1===i?{fraction_equal:0}:{fraction_equal:i}}if("list"===s)e=e.tree.slice(1),t="list"===o?t.tree.slice(1):[t.tree];else if("list"===o)t=t.tree.slice(1),e=[e.tree];else if(nonTupleVectorOperators.includes(s)){if(e=e.tree.slice(1),"interval"===o||"matrix"===o||"array"===o||"set"===o)return{fraction_equal:0};t=vectorOperators.includes(o)?t.tree.slice(1):[t.tree]}else if(nonTupleVectorOperators.includes(o)){if(t=t.tree.slice(1),"interval"===s||"matrix"===s||"array"===s||"set"===s)return{fraction_equal:0};e="tuple"===s?e.tree.slice(1):[e.tree]}else if("interval"===s){a=!0;let n=e.tree[2],r=n[1],i=n[2];if(e=e.tree[1].slice(1),"matrix"===o||"set"===o)return{fraction_equal:0};if("tuple"===o){let e=t.tree.slice(1);if(2!==e.length||!1!==r||!1!==i)return{fraction_equal:0};t=e}else if("array"===o){let e=t.tree.slice(1);if(2!==e.length||!0!==r||!0!==i)return{fraction_equal:0};t=e}else{if("interval"!==o)return{fraction_equal:0};{let e=t.tree[2];if(e[1]!==r||e[2]!==i)return{fraction_equal:0};t=t.tree[1].slice(1)}}}else if("interval"===o){a=!0;let n=t.tree[2],r=n[1],i=n[2];if(t=t.tree[1].slice(1),"matrix"===s||"set"===s)return{fraction_equal:0};if("tuple"===s){let t=e.tree.slice(1);if(2!==t.length||!1!==r||!1!==i)return{fraction_equal:0};e=t}else{if("array"!==s)return{fraction_equal:0};{let t=e.tree.slice(1);if(2!==t.length||!0!==r||!0!==i)return{fraction_equal:0};e=t}}}else if("matrix"===s){if("matrix"!==o)return{fraction_equal:0};e=convertMatrixToArrayOfTuples(e.tree.slice(1)),t=convertMatrixToArrayOfTuples(t.tree.slice(1)),a=!0,v=!0,b=!0}else{if("matrix"===o)return{fraction_equal:0};if("set"===s){let r=[];for(let t of e.tree.slice(1))r.some((e=>1===y(e,t).fraction_equal))||r.push(t);if(e=r,n=!0,"tuple"===o||"array"===o)return{fraction_equal:0};if("set"===o){r=[];for(let e of t.tree.slice(1))r.some((t=>1===y(t,e).fraction_equal))||r.push(e);t=r}else t=[t.tree]}else if("set"===o){let r=[];for(let e of t.tree.slice(1))r.some((t=>1===y(t,e).fraction_equal))||r.push(e);if(t=r,n=!0,"tuple"===s||"array"===s)return{fraction_equal:0};e=[e.tree]}else if("tuple"===s){if(e=e.tree.slice(1),"array"===o)return{fraction_equal:0};t="tuple"===o?t.tree.slice(1):[t.tree]}else if("tuple"===o){if(t=t.tree.slice(1),"array"===s)return{fraction_equal:0};e=[e.tree]}else if("array"===s)e=e.tree.slice(1),t="array"===o?t.tree.slice(1):[t.tree];else{if("array"!==o)return y(e.tree,t.tree);t=t.tree.slice(1),e=[e.tree]}}}else if(Array.isArray(e))Array.isArray(t)||(t="string"==typeof t&&e.every((e=>"string"==typeof e&&!e.includes(",")))?t.split(",").map((e=>e.trim())):[t]);else{if(!Array.isArray(t))return y(e,t);e="string"==typeof e&&t.every((e=>"string"==typeof e&&!e.includes(",")))?e.split(",").map((e=>e.trim())):[e]}let N=e.length,T=t.length,C={fraction_equal:0};if(a&&(n=!1),!n){let n=0,u=Math.min(N,T);for(let r=0;rArray(T+1).fill(0)));for(let n=0;nr&&(r=t.fraction_equal,e=a)}-1!==e&&(V+=r,A.add(e))}return N===T&&N===V?(C.fraction_equal=1,C):r?(C.fraction_equal=V/Math.max(N,T),C):C}function setStringsInTreeToLowerCase(e){return"string"==typeof e?e.toLowerCase():Array.isArray(e)?[e[0],...e.slice(1).map(setStringsInTreeToLowerCase)]:e}function convertStringsToLowerCase(e){return"string"==typeof e?e.toLowerCase():Array.isArray(e)?e.map(convertStringsToLowerCase):e}function convertMatrixToArrayOfTuples(e){let t=e[0][1],n=e[0][2];if(!Number.isInteger(t)||!Number.isInteger(n))return e;let r=[];for(let a=0;aevaluateLogic({logicTree:e,canOverrideUnorderedCompare:t,dependencyValues:n,valueOnInvalid:r});if(!Array.isArray(e)){if("string"==typeof e){let t=n.booleanChildrenByCode[e];if(t)return n.matchPartial&&void 0!==t.stateValues.fractionSatisfied?t.stateValues.fractionSatisfied:t.stateValues.value?1:0;{let t=n.mathChildrenByCode[e];if(t){let e=t.stateValues.value.simplify().evaluate_to_constant();return Number.isFinite(e)&&0!==e?1:0}{let t=n.numberChildrenByCode[e];if(t){let e=t.stateValues.value;return Number.isFinite(e)&&0!==e?1:0}if("true"===e.toLowerCase())return 1;if("false"===e.toLowerCase())return 0}}}else if("number"==typeof e)return 0===e?0:1;return console.warn("Invalid format for boolean condition"),r}let i=e[0],s=e.slice(1);if("not"===i)return 1!==s.length?(console.warn("Invalid format for boolean condition"),r):0===a(s[0])?1:0;if("and"===i)return n.matchPartial?s.reduce(((e,t)=>e+a(t)),0)/s.length:s.every((e=>1===a(e)))?1:0;if("or"===i)return n.matchPartial?s.reduce(((e,t)=>Math.max(a(t),e)),0):s.some((e=>1===a(e)))?1:0;let o=!1,l=!1,u=!1,c=!1;s.forEach((function(e){"string"==typeof e&&(e in n.mathChildrenByCode||e in n.mathListChildrenByCode||e in n.numberChildrenByCode||e in n.numberListChildrenByCode?o=!0:e in n.textChildrenByCode||e in n.textListChildrenByCode?l=!0:e in n.booleanChildrenByCode||e in n.booleanListChildrenByCode?u=!0:e in n.otherChildrenByCode&&(c=!0))}));let p,d=function(e){if("string"==typeof e){let t=n.mathChildrenByCode[e];return void 0!==t?t.stateValues.value.tree:(t=n.mathListChildrenByCode[e],void 0!==t?["list",...t.stateValues.maths.map((e=>e.tree))]:(t=n.numberChildrenByCode[e],void 0!==t?numberToMathExpression(t.stateValues.value).tree:(t=n.numberListChildrenByCode[e],void 0!==t?["list",...t.stateValues.numbers]:e)))}return Array.isArray(e)?[e[0],...e.slice(1).map(d)]:e};if("apply"===i&&["isnumber","isinteger"].includes(s[0])){if(l||u||c)return 0;let e=me$3.fromAst(d(s[1])).simplify().evaluate_to_constant();if(!Number.isFinite(e))return 0;if("isnumber"===s[0])return 1;{let t=Math.round(e);return Math.abs(t-e)<=1e-15*Math.abs(e)?1:0}}if(!["=","ne","<",">","le","ge","lts","gts","in","notin"].includes(i)){if(l||u||c)return console.warn("Invalid format for boolean condition"),r;let t=me$3.fromAst(d(e)).simplify().evaluate_to_constant();return Number.isFinite(t)&&0!==t?1:0}if(u){if(o||l||c)return console.warn("Invalid format for boolean condition"),r;let e=!1,a=!1;if(s=s.map((function(t){if("string"==typeof t){let i=n.booleanChildrenByCode[t];return void 0!==i?i.stateValues.value:(i=n.booleanListChildrenByCode[t],void 0!==i?(i.stateValues.unordered&&(a=!0),i.stateValues.booleans):"true"===(t=t.toLowerCase().trim())||"t"===t||"false"!==t&&"f"!==t&&(console.warn("Invalid format for boolean condition"),e=!0,r))}return console.warn("Invalid format for boolean condition"),e=!0,r})),e)return r;let u=n.unorderedCompare;if(t&&a&&(u=!0),"="===i){let e=s[0];if(n.matchPartial){let t=s.slice(1).map((t=>checkEquality({object1:e,object2:t,isUnordered:u,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions}))),r=t.reduce(((e,t)=>e+t.fraction_equal),0);return r/t.length}return s.slice(1).every((t=>1===checkEquality({object1:e,object2:t,isUnordered:u,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions}).fraction_equal))?1:0}if("ne"===i){if(2!==s.length)return console.warn("Invalid format for boolean condition"),r;return 0===checkEquality({object1:s[0],object2:s[1],isUnordered:u,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions}).fraction_equal?1:0}return console.warn("Invalid format for boolean condition"),r}if(l){if(o||c)return console.warn("Invalid format for boolean condition"),r;let e=!1,a=!1,l=function(t,r=!1){if("string"==typeof t){let e=n.textChildrenByCode[t];return void 0!==e?e.stateValues.value.trim().replace(/\s+/," "):(e=n.textListChildrenByCode[t],void 0!==e?(e.stateValues.unordered&&(a=!0),e.stateValues.texts.map((e=>e.trim().replace(/\s+/," ")))):t.trim())}return"number"==typeof t?t.toString():r&&Array.isArray(t)&&"*"===t[0]?t.slice(1).map(l).join(" "):(console.warn("Invalid format for boolean condition"),e=!0,"")};if(s=s.map((e=>l(e,!0))),e)return r;let u=n.unorderedCompare;if(t&&a&&(u=!0),"="===i){let e=s[0];if(n.matchPartial){let t=s.slice(1).map((t=>checkEquality({object1:e,object2:t,isUnordered:u,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions,caseInsensitiveMatch:n.caseInsensitiveMatch}))),r=t.reduce(((e,t)=>e+t.fraction_equal),0);return r/t.length}return s.slice(1).every((t=>1===checkEquality({object1:e,object2:t,isUnordered:u,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions,caseInsensitiveMatch:n.caseInsensitiveMatch}).fraction_equal))?1:0}if("ne"===i){if(2!==s.length)return console.warn("Invalid format for boolean condition"),0;return 0===checkEquality({object1:s[0],object2:s[1],isUnordered:u,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions,caseInsensitiveMatch:n.caseInsensitiveMatch}).fraction_equal?1:0}return console.warn("Invalid format for boolean condition"),r}if(c){if(o)return console.warn("Invalid format for boolean condition"),r;let e=!1;return s=s.map((function(t){if("string"==typeof t){let e=n.otherChildrenByCode[t];if(void 0!==e)return e.stateValues.value}return console.warn("Invalid format for boolean condition"),e=!0,null})),e?r:"="===i?s.slice(1).every((e=>deepCompare(e,s[0])))?1:0:"ne"===i?2!==s.length?(console.warn("Invalid format for boolean condition"),0):deepCompare(s[0],s[1])?0:1:(console.warn("Invalid format for boolean condition"),0)}"lts"!==i&&"gts"!==i||(p=s[1].slice(1),s=s[0].slice(1));let m=!1,h=function(e){if("string"==typeof e){let t=n.mathChildrenByCode[e];return void 0!==t?(t.stateValues.unordered&&(m=!0),t.stateValues.value.tree):(t=n.mathListChildrenByCode[e],void 0!==t?(t.stateValues.unordered&&(m=!0),["list",...t.stateValues.maths.map((e=>e.tree))]):(t=n.numberChildrenByCode[e],void 0!==t?numberToMathExpression(t.stateValues.value).tree:(t=n.numberListChildrenByCode[e],void 0!==t?(t.stateValues.unordered&&(m=!0),["list",...t.stateValues.numbers]):e)))}return Array.isArray(e)?[e[0],...e.slice(1).map(h)]:e},f=s.map((function(e){return me$3.fromAst(h(e))})),y=n.unorderedCompare;if(t&&m&&(y=!0),"="===i){let e=f[0];if(Number.isNaN(e.tree))return f.slice(1).every((e=>Number.isNaN(e.tree)))?1:0;if(n.matchPartial){let t=f.slice(1).map((t=>checkEquality({object1:e,object2:t,isUnordered:y,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions,symbolicEquality:n.symbolicEquality,simplify:n.simplifyOnCompare,expand:n.expandOnCompare,allowedErrorInNumbers:n.allowedErrorInNumbers,includeErrorInNumberExponents:n.includeErrorInNumberExponents,allowedErrorIsAbsolute:n.allowedErrorIsAbsolute,nSignErrorsMatched:n.nSignErrorsMatched,nPeriodicSetMatchesRequired:n.nPeriodicSetMatchesRequired,caseInsensitiveMatch:n.caseInsensitiveMatch,matchBlanks:n.matchBlanks}))),r=t.reduce(((e,t)=>e+t.fraction_equal),0);return r/t.length}return f.slice(1).every((t=>1===checkEquality({object1:e,object2:t,isUnordered:y,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions,symbolicEquality:n.symbolicEquality,simplify:n.simplifyOnCompare,expand:n.expandOnCompare,allowedErrorInNumbers:n.allowedErrorInNumbers,includeErrorInNumberExponents:n.includeErrorInNumberExponents,allowedErrorIsAbsolute:n.allowedErrorIsAbsolute,nSignErrorsMatched:n.nSignErrorsMatched,nPeriodicSetMatchesRequired:n.nPeriodicSetMatchesRequired,caseInsensitiveMatch:n.caseInsensitiveMatch,matchBlanks:n.matchBlanks}).fraction_equal))?1:0}if("ne"===i){return 0===checkEquality({object1:f[0],object2:f[1],isUnordered:y,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions,symbolicEquality:n.symbolicEquality,simplify:n.simplifyOnCompare,expand:n.expandOnCompare,allowedErrorInNumbers:n.allowedErrorInNumbers,includeErrorInNumberExponents:n.includeErrorInNumberExponents,allowedErrorIsAbsolute:n.allowedErrorIsAbsolute,nSignErrorsMatched:n.nSignErrorsMatched,nPeriodicSetMatchesRequired:n.nPeriodicSetMatchesRequired,caseInsensitiveMatch:n.caseInsensitiveMatch,matchBlanks:n.matchBlanks}).fraction_equal?1:0}if("in"===i||"notin"===i){let e=f[0],t=f[1].tree;if(!Array.isArray(t)||"set"!==t[0])return console.warn("Invalid format for boolean condition"),r;if(n.matchPartial){let r=t.slice(1).map((t=>checkEquality({object1:e,object2:me$3.fromAst(t),isUnordered:y,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions,symbolicEquality:n.symbolicEquality,simplify:n.simplifyOnCompare,expand:n.expandOnCompare,allowedErrorInNumbers:n.allowedErrorInNumbers,includeErrorInNumberExponents:n.includeErrorInNumberExponents,allowedErrorIsAbsolute:n.allowedErrorIsAbsolute,nSignErrorsMatched:n.nSignErrorsMatched,nPeriodicSetMatchesRequired:n.nPeriodicSetMatchesRequired,caseInsensitiveMatch:n.caseInsensitiveMatch,matchBlanks:n.matchBlanks}))),a=r.reduce(((e,t)=>Math.max(e,t.fraction_equal)),0);return"in"===i?a:1-a}{let r=t.slice(1).some((t=>1===checkEquality({object1:e,object2:me$3.fromAst(t),isUnordered:y,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions,symbolicEquality:n.symbolicEquality,simplify:n.simplifyOnCompare,expand:n.expandOnCompare,allowedErrorInNumbers:n.allowedErrorInNumbers,includeErrorInNumberExponents:n.includeErrorInNumberExponents,allowedErrorIsAbsolute:n.allowedErrorIsAbsolute,nSignErrorsMatched:n.nSignErrorsMatched,nPeriodicSetMatchesRequired:n.nPeriodicSetMatchesRequired,caseInsensitiveMatch:n.caseInsensitiveMatch,matchBlanks:n.matchBlanks}).fraction_equal));return"in"===i?r?1:0:r?0:1}}let g=f.map((e=>e.simplify().evaluate_to_constant()));if(g.some((e=>null===e||Number.isNaN(e))))return 0;if("<"===i)return g[0]"===i)return g[0]>g[1]?1:0;if("le"===i)return g[0]<=g[1]?1:0;if("ge"===i)return g[0]>=g[1]?1:0;for(let e=0;eg[e+1]))return 0}else if(!(g[e]>=g[e+1]))return 0;return 1}function splitSymbolsIfMath({logicTree:e,nonMathCodes:t,foundNonMath:n=!1,init:r=!0}){if(!Array.isArray(e))return"string"!=typeof e||n||r?e:fromTextSplit(e).tree;let a=e[0],i=e.slice(1);if(["and","not","or"].includes(a))return[a,...i.map((e=>splitSymbolsIfMath({logicTree:e,nonMathCodes:t,foundNonMath:n,init:r})))];if(i.some((e=>t.includes(e)))&&(n=!0),"apply"===a){i=[i[0],...i.slice(1).map((e=>splitSymbolsIfMath({logicTree:e,nonMathCodes:t,foundNonMath:n,init:!1})))];let e=!1;if("int"===i[0]?e=!0:Array.isArray(i[0])&&("^"===i[0][0]?("int"===i[0][1]||Array.isArray(i[0][1])&&"_"===i[0][1][0]&&"int"===i[0][1][1])&&(e=!0):"_"===i[0][0]&&"int"===i[0][1]&&(e=!0)),e){i=me$3.fromAst([a,...i]).tree.slice(1);let e=i[1];if(Array.isArray(e)&&"*"===e[0]){let t=[];for(let n=0;nsplitSymbolsIfMath({logicTree:e,nonMathCodes:t,foundNonMath:n,init:!1})))]}class BooleanComponent extends InlineComponent{static componentType="boolean";static variableForPlainMacro="value";static descendantCompositesMustHaveAReplacement=!0;static descendantCompositesDefaultReplacementType="math";static createAttributesObject(){let e=super.createAttributesObject();return e.symbolicEquality={createComponentOfType:"boolean",createStateVariable:"symbolicEquality",defaultValue:!1,public:!0},e.expandOnCompare={createComponentOfType:"boolean",createStateVariable:"expandOnCompare",defaultValue:!1,public:!0},e.simplifyOnCompare={createComponentOfType:"text",createStateVariable:"simplifyOnCompare",defaultValue:"none",toLowerCase:!0,valueTransformations:{"":"full",true:"full"},validValues:["none","full","numbers","numbersepreserveorder"],public:!0},e.unorderedCompare={createComponentOfType:"boolean",createStateVariable:"unorderedCompare",defaultValue:!1,public:!0},e.matchByExactPositions={createComponentOfType:"boolean",createStateVariable:"matchByExactPositions",defaultValue:!1,public:!0},e.allowedErrorInNumbers={createComponentOfType:"number",createStateVariable:"allowedErrorInNumbers",defaultValue:0,public:!0},e.includeErrorInNumberExponents={createComponentOfType:"boolean",createStateVariable:"includeErrorInNumberExponents",defaultValue:!1,public:!0},e.allowedErrorIsAbsolute={createComponentOfType:"boolean",createStateVariable:"allowedErrorIsAbsolute",defaultValue:!1,public:!0},e.nSignErrorsMatched={createComponentOfType:"number",createStateVariable:"nSignErrorsMatched",defaultValue:0,public:!0},e.nPeriodicSetMatchesRequired={createComponentOfType:"integer",createStateVariable:"nPeriodicSetMatchesRequired",defaultValue:3,public:!0},e.caseInsensitiveMatch={createComponentOfType:"boolean",createStateVariable:"caseInsensitiveMatch",defaultValue:!1,public:!0},e.matchBlanks={createComponentOfType:"boolean",createStateVariable:"matchBlanks",defaultValue:!1,public:!0},e}static returnChildGroups(){return[{group:"strings",componentTypes:["string"]},{group:"comparableTypes",componentTypes:["math","mathList","number","numberList","text","textList","boolean","booleanList","orbitalDiagram"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.parsedExpression={additionalStateVariablesDefined:["codePre"],returnDependencies:()=>({allChildren:{dependencyType:"child",childGroups:["strings","comparableTypes"]},stringChildren:{dependencyType:"child",childGroups:["strings"],variableNames:["value"]}}),definition:buildParsedExpression},e.mathChildrenByCode={additionalStateVariablesDefined:["mathListChildrenByCode","numberChildrenByCode","numberListChildrenByCode","textChildrenByCode","textListChildrenByCode","booleanChildrenByCode","booleanListChildrenByCode","otherChildrenByCode"],returnDependencies:()=>({allChildren:{dependencyType:"child",childGroups:["strings","comparableTypes"],variableNames:["value","texts","maths","numbers","booleans","fractionSatisfied","unordered"],variablesOptional:!0},codePre:{dependencyType:"stateVariable",variableName:"codePre"}}),definition({dependencyValues:e,componentInfoObjects:t}){let n={},r={},a={},i={},s={},o={},l={},u={},c={},p=0,d=e.codePre;for(let m of e.allChildren)if("string"!=typeof m){let e=d+p;t.isInheritedComponentType({inheritedComponentType:m.componentType,baseComponentType:"math"})?n[e]=m:t.isInheritedComponentType({inheritedComponentType:m.componentType,baseComponentType:"mathList"})?r[e]=m:t.isInheritedComponentType({inheritedComponentType:m.componentType,baseComponentType:"number"})?a[e]=m:t.isInheritedComponentType({inheritedComponentType:m.componentType,baseComponentType:"numberList"})?i[e]=m:t.isInheritedComponentType({inheritedComponentType:m.componentType,baseComponentType:"text"})?s[e]=m:t.isInheritedComponentType({inheritedComponentType:m.componentType,baseComponentType:"textList"})?o[e]=m:t.isInheritedComponentType({inheritedComponentType:m.componentType,baseComponentType:"boolean"})?l[e]=m:t.isInheritedComponentType({inheritedComponentType:m.componentType,baseComponentType:"booleanList"})?u[e]=m:c[e]=m,p+=1}return{setValue:{mathChildrenByCode:n,mathListChildrenByCode:r,numberChildrenByCode:a,numberListChildrenByCode:i,textChildrenByCode:s,textListChildrenByCode:o,booleanChildrenByCode:l,booleanListChildrenByCode:u,otherChildrenByCode:c}}}},e.value={public:!0,shadowingInstructions:{createComponentOfType:"boolean",attributesToShadow:["fixed"]},forRenderer:!0,hasEssential:!0,defaultValue:!1,set:Boolean,returnDependencies:()=>({symbolicEquality:{dependencyType:"stateVariable",variableName:"symbolicEquality"},expandOnCompare:{dependencyType:"stateVariable",variableName:"expandOnCompare"},simplifyOnCompare:{dependencyType:"stateVariable",variableName:"simplifyOnCompare"},unorderedCompare:{dependencyType:"stateVariable",variableName:"unorderedCompare"},matchByExactPositions:{dependencyType:"stateVariable",variableName:"matchByExactPositions"},allowedErrorInNumbers:{dependencyType:"stateVariable",variableName:"allowedErrorInNumbers"},includeErrorInNumberExponents:{dependencyType:"stateVariable",variableName:"includeErrorInNumberExponents"},allowedErrorIsAbsolute:{dependencyType:"stateVariable",variableName:"allowedErrorIsAbsolute"},nSignErrorsMatched:{dependencyType:"stateVariable",variableName:"nSignErrorsMatched"},nPeriodicSetMatchesRequired:{dependencyType:"stateVariable",variableName:"nPeriodicSetMatchesRequired"},caseInsensitiveMatch:{dependencyType:"stateVariable",variableName:"caseInsensitiveMatch"},matchBlanks:{dependencyType:"stateVariable",variableName:"matchBlanks"},parsedExpression:{dependencyType:"stateVariable",variableName:"parsedExpression"},allChildren:{dependencyType:"child",childGroups:["strings","comparableTypes"],variableNames:["value"],variablesOptional:!0},booleanChildrenByCode:{dependencyType:"stateVariable",variableName:"booleanChildrenByCode"},booleanListChildrenByCode:{dependencyType:"stateVariable",variableName:"booleanListChildrenByCode"},textChildrenByCode:{dependencyType:"stateVariable",variableName:"textChildrenByCode"},textListChildrenByCode:{dependencyType:"stateVariable",variableName:"textListChildrenByCode"},mathChildrenByCode:{dependencyType:"stateVariable",variableName:"mathChildrenByCode"},mathListChildrenByCode:{dependencyType:"stateVariable",variableName:"mathListChildrenByCode"},numberChildrenByCode:{dependencyType:"stateVariable",variableName:"numberChildrenByCode"},numberListChildrenByCode:{dependencyType:"stateVariable",variableName:"numberListChildrenByCode"},otherChildrenByCode:{dependencyType:"stateVariable",variableName:"otherChildrenByCode"}}),definition({dependencyValues:e,usedDefault:t}){if(0===e.allChildren.length)return{useEssentialOrDefaultValue:{value:!0}};if(null===e.parsedExpression)return{setValue:{value:!1}};let n=t.unorderedCompare;return{setValue:{value:1===evaluateLogic({logicTree:e.parsedExpression.tree,canOverrideUnorderedCompare:n,dependencyValues:e})}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t,componentInfoObjects:n}){if(0===t.allChildren.length)return{success:!0,instructions:[{setEssentialValue:"value",value:Boolean(e.value)}]};if(1===t.allChildren.length){let r=t.allChildren[0];if("string"==typeof r)return{success:!0,instructions:[{setDependency:"allChildren",desiredValue:e.value.toString(),childIndex:0,variableIndex:0}]};if(n.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"boolean"}))return{success:!0,instructions:[{setDependency:"allChildren",desiredValue:e.value,childIndex:0,variableIndex:0}]}}return{success:!1}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:function({dependencyValues:e}){return{setValue:{text:e.value?"true":"false"}}},inverseDefinition({desiredStateVariableValues:e}){let t,n=String(e.text).toLowerCase();return"true"===n?t=!0:"false"===n&&(t=!1),void 0!==t?{success:!0,instructions:[{setDependency:"value",desiredValue:t}]}:{success:!1}}},e}static adapters=["text"]}class BooleanOperator extends BooleanComponent{static componentType="_booleanOperator";static rendererType="boolean";static descendantCompositesMustHaveAReplacement=!1;static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e}){let t=e.reduce((function(e,t){return"string"==typeof t?[...e,...t.split(/\s+/).filter((e=>e)).map((e=>({componentType:"boolean",children:[e]})))]:[...e,t]}),[]);return{success:!0,newChildren:t}}}),e}static returnChildGroups(){return[{group:"booleans",componentTypes:["boolean"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();delete e.parsedExpression,delete e.mathChildrenByCode;let t=this;return e.value={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,returnDependencies:()=>({booleanChildren:{dependencyType:"child",childGroups:["booleans"],variableNames:["value"]}}),definition:function({dependencyValues:e}){return{setValue:{value:t.applyBooleanOperator(e.booleanChildren.map((e=>e.stateValues.value)))}}}},e}}class BooleanOperatorOneInput extends BooleanComponent{static componentType="_booleanOperatorOneInput";static rendererType="boolean";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=this;return renameStateVariable({stateVariableDefinitions:e,oldName:"value",newName:"valuePreOperator"}),e.value={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"valuePreOperator"}}),definition:function({dependencyValues:e}){return{setValue:{value:t.applyBooleanOperator(e.value)}}}},e}}class Not extends BooleanOperatorOneInput{static componentType="not";static applyBooleanOperator(e){return!e}}class And extends BooleanOperator{static componentType="and";static applyBooleanOperator(e){return e.every((e=>e))}}class Or$1 extends BooleanOperator{static componentType="or";static applyBooleanOperator(e){return e.some((e=>e))}}class Xor extends BooleanOperator{static componentType="xor";static applyBooleanOperator(e){return 1===e.reduce(((e,t)=>e+t),0)}}var BooleanOperators=Object.freeze({__proto__:null,Not:Not,And:And,Or:Or$1,Xor:Xor});class BooleanBaseOperatorOfMath extends BooleanComponent{static componentType="_booleanOperatorOfMath";static rendererType="boolean";static returnSugarInstructions(){let e=[];return e.push({replacementFunction:function({matchedChildren:e}){return e.every((e=>"string"==typeof e||e.doenetAttributes&&e.doenetAttributes.createdFromMacro))?1===e.length&&"string"!=typeof e[0]?{success:!1}:{success:!0,newChildren:[{componentType:"math",children:e}]}:{success:!1}}}),e}static returnChildGroups(){return[{group:"maths",componentTypes:["math"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return delete e.parsedExpression,delete e.mathChildrenByCode,e.booleanOperator={returnDependencies:()=>({}),definition:()=>({setValue:{booleanOperator:e=>!1}})},e.value={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,returnDependencies:()=>({mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]},booleanOperator:{dependencyType:"stateVariable",variableName:"booleanOperator"}}),definition:function({dependencyValues:e}){return{setValue:{value:e.booleanOperator(e.mathChildren.map((e=>e.stateValues.value)))}}}},e}}class IsInteger extends BooleanBaseOperatorOfMath{static componentType="isInteger";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.booleanOperator.definition=()=>({setValue:{booleanOperator:function(e){if(0===e.length)return!1;if(1!==e.length)return console.warn("IsInteger requires exactly one math child"),null;let t=e[0].evaluate_to_constant();if(!Number.isFinite(t))return!1;let n=Math.round(t);return Math.abs(n-t)<=1e-15*Math.abs(t)}}}),e}}class IsNumber extends BooleanBaseOperatorOfMath{static componentType="isNumber";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.booleanOperator.definition=()=>({setValue:{booleanOperator:function(e){if(0===e.length)return!1;if(1!==e.length)return console.warn("IsNumber requires exactly one math child"),null;let t=e[0].evaluate_to_constant();return Number.isFinite(t)}}}),e}}class IsBetween extends BooleanBaseOperatorOfMath{static componentType="isBetween";static createAttributesObject(){let e=super.createAttributesObject();return e.limits={createComponentOfType:"numberList",createStateVariable:"limits",defaultValue:[],public:!0},e.strict={createComponentOfType:"boolean",createStateVariable:"strict",defaultValue:!1,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.booleanOperator={returnDependencies:()=>({limits:{dependencyType:"stateVariable",variableName:"limits"},strict:{dependencyType:"stateVariable",variableName:"strict"}}),definition({dependencyValues:e}){let t,n,r=e.limits[0],a=e.limits[1];if(r!1}};n=a,t=r}let i=e.strict;return{setValue:{booleanOperator:function(e){if(0===e.length)return!1;if(1!==e.length)return console.warn("IsBetween requires exactly one math child"),null;let r=e[0].evaluate_to_constant();return i?r>n&&r=n&&r<=t}}}}},e}}var BooleanOperatorsOfMath=Object.freeze({__proto__:null,IsInteger:IsInteger,IsNumber:IsNumber,IsBetween:IsBetween});class MathOperator extends MathComponent{static componentType="_mathOperator";static rendererType="math";static descendantCompositesMustHaveAReplacement=!1;static createAttributesObject(){let e=super.createAttributesObject();return e.forceSymbolic={createComponentOfType:"boolean",createStateVariable:"forceSymbolic",defaultValue:!1,public:!0},e.forceNumeric={createComponentOfType:"boolean",createStateVariable:"forceNumeric",defaultValue:!1,public:!0},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e}){let t=e.reduce((function(e,t){return"string"==typeof t?[...e,...t.split(/\s+/).filter((e=>e)).map((e=>({componentType:Number.isFinite(Number(e))?"number":"math",children:[e]})))]:[...e,t]}),[]);return{success:!0,newChildren:t}}}),e}static returnChildGroups(){return[{group:"maths",componentTypes:["math"]},{group:"numbers",componentTypes:["number"]},{group:"mathLists",componentTypes:["mathList"]},{group:"numberLists",componentTypes:["numberList"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},mathLikeChildren:{dependencyType:"child",childGroups:["maths","numbers","mathLists","numberLists"],variableNames:["displayDigits"]}}),definition:({dependencyValues:e,usedDefault:t})=>null!==e.displayDigitsAttr?{setValue:{displayDigits:e.displayDigitsAttr.stateValues.value}}:null!==e.displayDecimalsAttr||1!==e.mathLikeChildren.length||t.mathLikeChildren[0]&&t.mathLikeChildren[0].displayDigits?{useEssentialOrDefaultValue:{displayDigits:!0}}:{setValue:{displayDigits:e.mathLikeChildren[0].stateValues.displayDigits}}},e.displayDecimals={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:null,returnDependencies:()=>({displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},mathLikeChildren:{dependencyType:"child",childGroups:["maths","numbers","mathLists","numberLists"],variableNames:["displayDecimals"]}}),definition:({dependencyValues:e,usedDefault:t})=>null!==e.displayDecimalsAttr?{setValue:{displayDecimals:e.displayDecimalsAttr.stateValues.value}}:1!==e.mathLikeChildren.length||t.mathLikeChildren[0]&&t.mathLikeChildren[0].displayDecimals?{useEssentialOrDefaultValue:{displayDecimals:!0}}:{setValue:{displayDecimals:e.mathLikeChildren[0].stateValues.displayDecimals}}},e.displaySmallAsZero={public:!0,shadowingInstructions:{createComponentOfType:"number"},hasEssential:!0,defaultValue:0,returnDependencies:()=>({displaySmallAsZeroAttr:{dependencyType:"attributeComponent",attributeName:"displaySmallAsZero",variableNames:["value"]},mathLikeChildren:{dependencyType:"child",childGroups:["maths","numbers","mathLists","numberLists"],variableNames:["displaySmallAsZero"]}}),definition:({dependencyValues:e,usedDefault:t})=>null!==e.displaySmallAsZeroAttr?{setValue:{displaySmallAsZero:e.displaySmallAsZeroAttr.stateValues.value}}:1!==e.mathLikeChildren.length||t.mathLikeChildren[0]&&t.mathLikeChildren[0].displaySmallAsZero?{useEssentialOrDefaultValue:{displaySmallAsZero:!0}}:{setValue:{displaySmallAsZero:e.mathLikeChildren[0].stateValues.displaySmallAsZero}}},e.padZeros={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},hasEssential:!0,defaultValue:!1,returnDependencies:()=>({padZerosAttr:{dependencyType:"attributeComponent",attributeName:"padZeros",variableNames:["value"]},mathLikeChildren:{dependencyType:"child",childGroups:["maths","numbers","mathLists","numberLists"],variableNames:["padZeros"]}}),definition:({dependencyValues:e,usedDefault:t})=>null!==e.padZerosAttr?{setValue:{padZeros:e.padZerosAttr.stateValues.value}}:1!==e.mathLikeChildren.length||t.mathLikeChildren[0]&&t.mathLikeChildren[0].padZeros?{useEssentialOrDefaultValue:{padZeros:!0}}:{setValue:{padZeros:e.mathLikeChildren[0].stateValues.padZeros}}},e.isNumericOperator={returnDependencies:()=>({forceNumeric:{dependencyType:"stateVariable",variableName:"forceNumeric"},forceSymbolic:{dependencyType:"stateVariable",variableName:"forceSymbolic"},mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["isNumber"],variablesOptional:!0},mathListChildren:{dependencyType:"child",childGroups:["mathLists"],variableNames:["maths"]}}),definition({dependencyValues:e}){let t;return t=!!e.forceNumeric||!e.forceSymbolic&&(0===e.mathChildren.length&&0===e.mathListChildren.length||e.mathChildren.every((e=>e.stateValues.isNumber))&&e.mathListChildren.every((e=>e.stateValues.maths.every((e=>Number.isFinite(e.tree)))))),{setValue:{isNumericOperator:t}}}},delete e.codePre,delete e.expressionWithCodes,delete e.mathChildrenFunctionSymbols,delete e.codesAdjacentToStrings,delete e.mathChildrenByVectorComponent,e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:e=>me$3.fromAst("_")}})},e.numericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{numericOperator:e=>me$3.fromAst("_")}})},e.inverseMathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseMathOperator:null}})},e.inverseNumericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseNumericOperator:null}})},e.unnormalizedValue={returnDependencies:()=>({mathNumberChildren:{dependencyType:"child",childGroups:["maths","numbers","mathLists","numberLists"],variableNames:["value","maths","numbers","canBeModified"],variablesOptional:!0},isNumericOperator:{dependencyType:"stateVariable",variableName:"isNumericOperator"},mathOperator:{dependencyType:"stateVariable",variableName:"mathOperator"},numericOperator:{dependencyType:"stateVariable",variableName:"numericOperator"},inverseMathOperator:{dependencyType:"stateVariable",variableName:"inverseMathOperator"},inverseNumericOperator:{dependencyType:"stateVariable",variableName:"inverseNumericOperator"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){if(0===e.mathNumberChildren.length)return{setValue:{unnormalizedValue:me$3.fromAst("_")}};if(e.isNumericOperator){let n=[];for(let r of e.mathNumberChildren)if(t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"number"}))n.push(r.stateValues.value);else if(t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"math"})){let e=r.stateValues.value.evaluate_to_constant();Number.isFinite(e)||(e=NaN),n.push(e)}else if(t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"numberList"}))n.push(...r.stateValues.numbers);else{let e=r.stateValues.maths.map((e=>{let t=e.evaluate_to_constant();return Number.isFinite(t)||(t=NaN),t}));n.push(...e)}return{setValue:{unnormalizedValue:me$3.fromAst(e.numericOperator(n))}}}{let n=[];for(let r of e.mathNumberChildren)t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"number"})?n.push(me$3.fromAst(r.stateValues.value)):t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"math"})?n.push(r.stateValues.value):t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"numberList"})?n.push(...r.stateValues.numbers.map((e=>me$3.fromAst(e)))):n.push(...r.stateValues.maths);return{setValue:{unnormalizedValue:e.mathOperator(n)}}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t,componentInfoObjects:n}){if(0===t.mathNumberChildren.length)return{success:!1};if(t.isNumericOperator){if(t.inverseNumericOperator){let r=[],a=[],i=[];for(let[e,s]of t.mathNumberChildren.entries())if(n.isInheritedComponentType({inheritedComponentType:s.componentType,baseComponentType:"number"}))r.push(s.stateValues.value),a.push(s.stateValues.canBeModified),i.push(e);else if(n.isInheritedComponentType({inheritedComponentType:s.componentType,baseComponentType:"math"})){let t=s.stateValues.value.evaluate_to_constant();Number.isFinite(t)||(t=NaN),r.push(t),a.push(s.stateValues.canBeModified),i.push(e)}else if(n.isInheritedComponentType({inheritedComponentType:s.componentType,baseComponentType:"numberList"}))r.push(...s.stateValues.numbers),a.push(...Array(s.stateValues.numbers.length).fill(s.stateValues.canBeModified)),1===s.stateValues.numbers.length?i.push(e):i.push(...Array(s.stateValues.numbers.length).fill(NaN));else{let t=s.stateValues.maths.map((e=>{let t=e.evaluate_to_constant();return Number.isFinite(t)||(t=NaN),t}));r.push(...t),a.push(...Array(s.stateValues.maths.length).fill(s.stateValues.canBeModified)),1===s.stateValues.maths.length?i.push(e):i.push(...Array(s.stateValues.maths.length).fill(NaN))}let s=t.inverseNumericOperator({desiredValue:e.unnormalizedValue.evaluate_to_constant(),inputs:r,canBeModified:a,desiredMathValue:e.unnormalizedValue});if(s.success){let e=i[s.inputNumber];if(Number.isFinite(e)){let r=s.inputValue,a=0,i=t.mathNumberChildren[e];return n.isInheritedComponentType({inheritedComponentType:i.componentType,baseComponentType:"numberList"})?(a=2,r={0:r}):n.isInheritedComponentType({inheritedComponentType:i.componentType,baseComponentType:"mathList"})&&(a=1,r={0:r}),{success:!0,instructions:[{setDependency:"mathNumberChildren",desiredValue:r,childIndex:e,variableIndex:a}]}}return{success:!1}}return{success:!1}}return{success:!1}}if(t.inverseMathOperator){let r=[],a=[],i=[];for(let[e,s]of t.mathNumberChildren.entries())n.isInheritedComponentType({inheritedComponentType:s.componentType,baseComponentType:"number"})?(r.push(me$3.fromAst(s.stateValues.value)),a.push(s.stateValues.canBeModified),i.push(e)):n.isInheritedComponentType({inheritedComponentType:s.componentType,baseComponentType:"math"})?(r.push(s.stateValues.value),a.push(s.stateValues.canBeModified),i.push(e)):n.isInheritedComponentType({inheritedComponentType:s.componentType,baseComponentType:"numberList"})?(r.push(...s.stateValues.numbers.map((e=>me$3.fromAst(e)))),a.push(...Array(s.stateValues.numbers.length).fill(s.stateValues.canBeModified)),1===s.stateValues.numbers.length?i.push(e):i.push(...Array(s.stateValues.numbers.length).fill(NaN))):(r.push(...s.stateValues.maths),a.push(...Array(s.stateValues.maths.length).fill(s.stateValues.canBeModified)),1===s.stateValues.maths.length?i.push(e):i.push(...Array(s.stateValues.maths.length).fill(NaN)));let s=t.inverseMathOperator({desiredValue:e.unnormalizedValue,inputs:r,canBeModified:a});if(s.success){let e=i[s.inputNumber];if(Number.isFinite(e)){let r=s.inputValue,a=0,i=t.mathNumberChildren[e];return n.isInheritedComponentType({inheritedComponentType:i.componentType,baseComponentType:"numberList"})?(a=2,r={0:r}):n.isInheritedComponentType({inheritedComponentType:i.componentType,baseComponentType:"mathList"})&&(a=1,r={0:r}),{success:!0,instructions:[{setDependency:"mathNumberChildren",desiredValue:r,childIndex:e,variableIndex:a}]}}return{success:!1}}return{success:!1}}return{success:!1}}},e.canBeModified={returnDependencies:()=>({modifyIndirectly:{dependencyType:"stateVariable",variableName:"modifyIndirectly"},fixed:{dependencyType:"stateVariable",variableName:"fixed"},mathNumberChildren:{dependencyType:"child",childGroups:["maths","numbers"],variableNames:["canBeModified"]},mathNumberListChildren:{dependencyType:"child",childGroups:["mathLists","numberLists"],variableNames:["nComponents"]},isNumericOperator:{dependencyType:"stateVariable",variableName:"isNumericOperator"},inverseMathOperator:{dependencyType:"stateVariable",variableName:"mathOperator"},inverseNumericOperator:{dependencyType:"stateVariable",variableName:"inverseNumericOperator"}}),definition:function({dependencyValues:e}){let t=e.modifyIndirectly&&!e.fixed&&Boolean(e.isNumericOperator?e.inverseNumericOperator:e.inverseMathOperator);if(t&&e.mathNumberChildren.length+e.mathNumberListChildren.length>0){let n=e.mathNumberChildren.filter((e=>e.stateValues.canBeModified)).length+e.mathNumberListChildren.reduce(((e,t)=>e+t.stateValues.nComponents),0);1!==n&&(t=!1)}return{setValue:{canBeModified:t}}}},e}}class MathOperatorOneInput extends MathComponent{static componentType="_mathOperatorOneInput";static rendererType="math";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:e=>me.fromAst("_")}})},e.inverseMathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseMathOperator:null}})},renameStateVariable({stateVariableDefinitions:e,oldName:"unnormalizedValue",newName:"unnormalizedValuePreOperator"}),e.unnormalizedValue={returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"unnormalizedValuePreOperator"},mathOperator:{dependencyType:"stateVariable",variableName:"mathOperator"},inverseMathOperator:{dependencyType:"stateVariable",variableName:"inverseMathOperator"}}),definition:function({dependencyValues:e}){return{setValue:{unnormalizedValue:e.mathOperator(e.value)}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t,componentName:n}){if(t.inverseMathOperator){return{success:!0,instructions:[{setDependency:"value",desiredValue:t.inverseMathOperator(e.unnormalizedValue)}]}}return{success:!1}}},renameStateVariable({stateVariableDefinitions:e,oldName:"canBeModified",newName:"canBeModifiedPreOperator"}),e.canBeModified={returnDependencies:()=>({canBeModifiedPreOperator:{dependencyType:"stateVariable",variableName:"canBeModifiedPreOperator"},inverseMathOperator:{dependencyType:"stateVariable",variableName:"mathOperator"}}),definition:function({dependencyValues:e}){let t=e.canBeModifiedPreOperator;return e.inverseMathOperator||(t=!1),{setValue:{canBeModified:t}}}},e}}class Sum extends MathOperator{static componentType="sum";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{numericOperator:function(e){return e.reduce(((e,t)=>e+t))}}})},e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){return e.reduce(((e,t)=>e.add(t)))}}})},e}}class Product extends MathOperator{static componentType="product";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{numericOperator:function(e){return e.reduce(((e,t)=>e*t))}}})},e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){return e.reduce(((e,t)=>e.multiply(t)))}}})},e}}class ClampNumber extends MathOperatorOneInput{static componentType="clampNumber";static createAttributesObject(){let e=super.createAttributesObject();return e.lowerValue={createComponentOfType:"number",createStateVariable:"lowerValue",defaultValue:0,public:!0},e.upperValue={createComponentOfType:"number",createStateVariable:"upperValue",defaultValue:1,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.isNumericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{isNumericOperator:!0}})},e.mathOperator={returnDependencies:()=>({lowerValue:{dependencyType:"stateVariable",variableName:"lowerValue"},upperValue:{dependencyType:"stateVariable",variableName:"upperValue"}}),definition:({dependencyValues:e})=>({setValue:{mathOperator:function(t){return clamp({value:t,lowerValue:e.lowerValue,upperValue:e.upperValue})}}})},e.inverseMathOperator={returnDependencies:()=>({lowerValue:{dependencyType:"stateVariable",variableName:"lowerValue"},upperValue:{dependencyType:"stateVariable",variableName:"upperValue"}}),definition:({dependencyValues:e})=>({setValue:{inverseMathOperator:function(t){return clamp({value:t,lowerValue:e.lowerValue,upperValue:e.upperValue})}}})},e}}function clamp({value:e,lowerValue:t,upperValue:n}){let r=e;return r instanceof me$3.class&&(r=r.evaluate_to_constant()),Number.isFinite(r)?me$3.fromAst(Math.max(t,Math.min(n,r))):me$3.fromAst(NaN)}class WrapNumberPeriodic extends MathOperatorOneInput{static componentType="wrapNumberPeriodic";static createAttributesObject(){let e=super.createAttributesObject();return e.lowerValue={createComponentOfType:"number",createStateVariable:"lowerValue",defaultValue:0,public:!0},e.upperValue={createComponentOfType:"number",createStateVariable:"upperValue",defaultValue:1,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.isNumericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{isNumericOperator:!0}})},e.mathOperator={returnDependencies:()=>({lowerValue:{dependencyType:"stateVariable",variableName:"lowerValue"},upperValue:{dependencyType:"stateVariable",variableName:"upperValue"}}),definition:({dependencyValues:e})=>({setValue:{mathOperator:function(t){return makePeriodic({value:t,lowerValue:e.lowerValue,upperValue:e.upperValue})}}})},e.inverseMathOperator={returnDependencies:()=>({lowerValue:{dependencyType:"stateVariable",variableName:"lowerValue"},upperValue:{dependencyType:"stateVariable",variableName:"upperValue"}}),definition:({dependencyValues:e})=>({setValue:{inverseMathOperator:function(t){return makePeriodic({value:t,lowerValue:e.lowerValue,upperValue:e.upperValue})}}})},e}}function makePeriodic({value:e,lowerValue:t,upperValue:n}){let r=e;return r instanceof me$3.class&&(r=r.evaluate_to_constant()),Number.isFinite(r)?t===n?me$3.fromAst(t):(t>n&&([n,t]=[t,n]),me$3.fromAst(t+me$3.math.mod(r-t,n-t))):me$3.fromAst(NaN)}class Round extends MathOperatorOneInput{static componentType="round";static createAttributesObject(){let e=super.createAttributesObject();return e.numberDecimals={createComponentOfType:"number",createStateVariable:"numberDecimals",defaultValue:0,public:!0},e.numberDigits={createComponentOfType:"number",createStateVariable:"numberDigits",defaultValue:null,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.mathOperator={returnDependencies:()=>({numberDecimals:{dependencyType:"stateVariable",variableName:"numberDecimals"},numberDigits:{dependencyType:"stateVariable",variableName:"numberDigits"}}),definition:({dependencyValues:e})=>({setValue:{mathOperator:function(t){let n=t.evaluate_numbers({max_digits:1/0,evaluate_functions:!0});return null!==e.numberDigits?n.round_numbers_to_precision(e.numberDigits):n.round_numbers_to_decimals(e.numberDecimals)}}})},e.inverseMathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseMathOperator:e=>e}})},e}}class setSmallToZero extends MathOperatorOneInput{static componentType="setSmallToZero";static createAttributesObject(){let e=super.createAttributesObject();return e.threshold={createComponentOfType:"number",createStateVariable:"threshold",defaultValue:1e-14,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.mathOperator={returnDependencies:()=>({threshold:{dependencyType:"stateVariable",variableName:"threshold"}}),definition:({dependencyValues:e})=>({setValue:{mathOperator:function(t){return t.evaluate_numbers({skip_ordering:!0,set_small_zero:e.threshold})}}})},e.inverseMathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseMathOperator:e=>e}})},e}}class ConvertSetToList extends MathOperatorOneInput{static componentType="convertSetToList";static createAttributesObject(){let e=super.createAttributesObject();return delete e.unordered,e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.unordered={returnDependencies:()=>({}),definition:()=>({setValue:{unordered:!0}})},e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){if(void 0!==e&&Array.isArray(e.tree)&&"set"===e.tree[0]){let t=[];for(let n of e.tree.slice(1))t.some((t=>e.context.equalsViaSyntax(e.context.fromAst(t),e.context.fromAst(n))))||t.push(n);return e.context.fromAst(["list",...t])}return e}}})},e}}class Ceil extends MathOperatorOneInput{static componentType="ceil";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){let t=e.evaluate_to_constant();if(!Number.isFinite(t))return me$3.fromAst(["apply","ceil",e.tree]);let n=Math.round(t);return Math.abs((n-t)/t)<1e-15?me$3.fromAst(n):me$3.fromAst(Math.ceil(t))}}})},e.inverseMathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseMathOperator:e=>e}})},e}}class Floor extends MathOperatorOneInput{static componentType="floor";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){let t=e.evaluate_to_constant();if(!Number.isFinite(t))return me$3.fromAst(["apply","floor",e.tree]);let n=Math.round(t);return Math.abs((n-t)/t)<1e-15?me$3.fromAst(n):me$3.fromAst(Math.floor(t))}}})},e.inverseMathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseMathOperator:e=>e}})},e}}class Abs extends MathOperatorOneInput{static componentType="abs";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){let t=e.evaluate_to_constant();return Number.isFinite(t)?me$3.fromAst(Math.abs(t)):me$3.fromAst(["apply","abs",e.tree])}}})},e.inverseMathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseMathOperator:function(e){let t=e,n=e.evaluate_to_constant();return Number.isFinite(n)?n<0&&(t=me$3.fromAst(0)):Array.isArray(e.tree)&&"apply"===e.tree[0]&&"abs"===e.tree[1]&&(t=me$3.fromAst(e.tree[2])),t}}})},e}}class Sign extends MathOperatorOneInput{static componentType="sign";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){let t=e.evaluate_to_constant();return Number.isFinite(t)?me$3.fromAst(Math.sign(t)):me$3.fromAst(["apply","sign",e.tree])}}})},e}}class Mean extends MathOperator{static componentType="mean";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{numericOperator:function(e){let t=e.reduce(((e,t)=>e+t));return t/=e.length,t}}})},e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){return e.reduce(((e,t)=>e.add(t))).divide(e.length)}}})},e}}class Variance extends MathOperator{static componentType="variance";static createAttributesObject(){let e=super.createAttributesObject();return e.population={createComponentOfType:"boolean",createStateVariable:"population",defaultValue:!1,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numericOperator={returnDependencies:()=>({population:{dependencyType:"stateVariable",variableName:"population"}}),definition:({dependencyValues:e})=>({setValue:{numericOperator:function(t){return calculateNumericVariance(t,e.population)}}})},e.mathOperator={returnDependencies:()=>({population:{dependencyType:"stateVariable",variableName:"population"}}),definition:({dependencyValues:e})=>({setValue:{mathOperator:function(t){return calculateSymbolicVariance(t,e.population)}}})},e}}function calculateNumericVariance(e,t){let n=0,r=0;for(let t of e)n+=t,r+=t*t;let a=e.length;return r-=n**2/a,r/=t?a:a-1,r}function calculateSymbolicVariance(e,t){let n=e.length,r=e.reduce(((e,t)=>e.add(t))),a=e.slice(1).reduce(((e,t)=>e.add(t.pow(2))),e[0].pow(2)).subtract(r.pow(2).divide(n));return a=t?a.divide(n):a.divide(n-1),a}class StandardDeviation extends Variance{static componentType="standardDeviation";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numericOperator.definition=({dependencyValues:e})=>({setValue:{numericOperator:function(t){return Math.sqrt(calculateNumericVariance(t,e.population))}}}),e.mathOperator.definition=({dependencyValues:e})=>({setValue:{mathOperator:function(t){return me$3.fromAst(["apply","sqrt",calculateSymbolicVariance(t,e.population).tree])}}}),e}}class Count extends MathOperator{static componentType="count";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.isNumericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{isNumericOperator:!0}})},e.numericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{numericOperator:function(e){return e.length}}})},e}}class Min extends MathOperator{static componentType="min";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{numericOperator:function(e){return e.reduce(((e,t)=>Math.min(e,t)),1/0)}}})},e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){return me$3.fromAst(["apply","min",["tuple",...e.map((e=>e.tree))]])}}})},e.inverseMathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseMathOperator:function({desiredValue:e,canBeModified:t}){if(1===t.filter((e=>e)).length){let n=t.indexOf(!0);if(n>=0)return{success:!0,inputValue:e,inputNumber:n}}return{success:!1}}}})},e.inverseNumericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseNumericOperator:function({desiredValue:e,canBeModified:t,desiredMathValue:n}){if(1===t.filter((e=>e)).length){let r=t.indexOf(!0);if(r>=0)return Number.isFinite(e)||(e=n),{success:!0,inputValue:e,inputNumber:r}}return{success:!1}}}})},e}}class Max extends MathOperator{static componentType="max";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{numericOperator:function(e){return e.reduce(((e,t)=>Math.max(e,t)),-1/0)}}})},e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){return me$3.fromAst(["apply","max",["tuple",...e.map((e=>e.tree))]])}}})},e.inverseMathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseMathOperator:function({desiredValue:e,canBeModified:t}){if(1===t.filter((e=>e)).length){let n=t.indexOf(!0);if(n>=0)return{success:!0,inputValue:e,inputNumber:n}}return{success:!1}}}})},e.inverseNumericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseNumericOperator:function({desiredValue:e,canBeModified:t,desiredMathValue:n}){if(1===t.filter((e=>e)).length){let r=t.indexOf(!0);if(r>=0)return Number.isFinite(e)||(e=n),{success:!0,inputValue:e,inputNumber:r}}return{success:!1}}}})},e}}class Mod extends MathOperator{static componentType="mod";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{numericOperator:function(e){return 2!==e.length?NaN:me$3.math.mod(e[0],e[1])}}})},e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){return 2!==e.length?me$3.fromAst("_"):me$3.fromAst(["apply","mod",["tuple",...e.map((e=>e.tree))]])}}})},e}}class Gcd extends MathOperator{static componentType="gcd";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{numericOperator:function(e){return e.every(Number.isInteger)?gcd(...e):NaN}}})},e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){return me$3.fromAst(["apply","gcd",["tuple",...e.map((e=>e.tree))]])}}})},e}}class ExtractMath extends MathOperatorOneInput{static componentType="extractMath";static createAttributesObject(){let e=super.createAttributesObject();return e.type={createComponentOfType:"text",createStateVariable:"type",defaultValue:null,toLowerCase:!0,validValues:["operand","function","functionargument","numberofoperands"]},e.operandNumber={createComponentOfType:"number",createStateVariable:"operandNumber",defaultValue:null,public:!0},e.argumentNumber={createComponentOfType:"number",createStateVariable:"argumentNumber",defaultValue:null,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.mathOperator={returnDependencies:()=>({type:{dependencyType:"stateVariable",variableName:"type"},operandNumber:{dependencyType:"stateVariable",variableName:"operandNumber"},argumentNumber:{dependencyType:"stateVariable",variableName:"argumentNumber"}}),definition:({dependencyValues:e})=>"operand"===e.type?null===e.operandNumber?(console.warn("Must specify a operandNumber when extracting a math operand"),{setValue:{mathOperator:e=>me$3.fromAst("_")}}):{setValue:{mathOperator:function(t){let n=t.tree;if(!Array.isArray(n))return 1===e.operandNumber?t:me$3.fromAst("_");if("apply"===n[0])return 1===e.operandNumber?t:me$3.fromAst("_");let r=n[e.operandNumber];return void 0===r?me$3.fromAst("_"):me$3.fromAst(r)}}}:"function"===e.type?{setValue:{mathOperator:function(e){let t=e.tree;return Array.isArray(t)?"apply"!==t[0]?me$3.fromAst("_"):me$3.fromAst(t[1]):me$3.fromAst("_")}}}:"functionargument"===e.type?{setValue:{mathOperator:function(t){let n=t.tree;if(!Array.isArray(n))return me$3.fromAst("_");if("apply"!==n[0])return me$3.fromAst("_");let r=n[2];if(null===e.argumentNumber)return me$3.fromAst(r);if(1===e.argumentNumber)return Array.isArray(r)&&"tuple"===r[0]?me$3.fromAst(r[1]):me$3.fromAst(r);if(Array.isArray(r)&&"tuple"===r[0]){let t=r[e.argumentNumber];return void 0===t?me$3.fromAst("_"):me$3.fromAst(t)}return me$3.fromAst("_")}}}:"numberofoperands"===e.type?{setValue:{mathOperator:function(e){let t=e.tree;return Array.isArray(t)?"apply"===t[0]?me$3.fromAst(1):me$3.fromAst(t.length-1):me$3.fromAst(1)}}}:{setValue:{mathOperator:e=>me$3.fromAst("_")}}},e}}function gcd(e,t,...n){return!t&&n.length>0?gcd(e,...n):t?gcd(t,e%t,...n):e}var MathOperators=Object.freeze({__proto__:null,Sum:Sum,Product:Product,ClampNumber:ClampNumber,WrapNumberPeriodic:WrapNumberPeriodic,Round:Round,setSmallToZero:setSmallToZero,ConvertSetToList:ConvertSetToList,Ceil:Ceil,Floor:Floor,Abs:Abs,Sign:Sign,Mean:Mean,Variance:Variance,StandardDeviation:StandardDeviation,Count:Count,Min:Min,Max:Max,Mod:Mod,Gcd:Gcd,ExtractMath:ExtractMath});function returnLabelStateVariableDefinitions(){let e={};return e.componentNameAndShadowSourceNames={returnDependencies:()=>({shadowSource:{dependencyType:"shadowSource",variableNames:["componentNameAndShadowSourceNames"]},unlinkedCopySource:{dependencyType:"unlinkedCopySource",variableNames:["componentNameAndShadowSourceNames"]}}),definition({dependencyValues:e,componentName:t}){let n=[t];return e.shadowSource?.stateValues.componentNameAndShadowSourceNames?n.push(...e.shadowSource.stateValues.componentNameAndShadowSourceNames):e.unlinkedCopySource?.stateValues.componentNameAndShadowSourceNames&&n.push(...e.unlinkedCopySource.stateValues.componentNameAndShadowSourceNames),{setValue:{componentNameAndShadowSourceNames:n}}}},e.label={forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"label",addStateVariablesShadowingStateVariables:{hasLatex:{stateVariableToShadow:"labelHasLatex"}}},hasEssential:!0,doNotShadowEssential:!0,defaultValue:"",provideEssentialValuesInDefinition:!0,additionalStateVariablesDefined:[{variableName:"labelHasLatex",forRenderer:!0}],returnDependencies:()=>({labelChild:{dependencyType:"child",childGroups:["labels"],variableNames:["value","hasLatex"]},labelIsName:{dependencyType:"stateVariable",variableName:"labelIsName"},labelIsNameAttr:{dependencyType:"attributeComponent",attributeName:"labelIsName"},componentNameAndShadowSourceNames:{dependencyType:"stateVariable",variableName:"componentNameAndShadowSourceNames"},shadowSource:{dependencyType:"shadowSource",variableNames:["label","labelHasLatex"]}}),definition({dependencyValues:e,essentialValues:t}){let n=e.labelChild[e.labelChild.length-1];if(n&&!n.shadowDepth)return{setValue:{label:n.stateValues.value,labelHasLatex:n.stateValues.hasLatex}};if(void 0!==t.label)return{useEssentialOrDefaultValue:{label:!0},setValue:{labelHasLatex:!1}};if(e.labelIsName&&!e.labelIsNameAttr.shadowDepth){let t="__",n=e.componentNameAndShadowSourceNames;for(let e of n){let n=e.lastIndexOf("/");if(t=e.substring(n+1),"__"!==t.slice(0,2))break}return"__"===t.slice(0,2)?{setValue:{label:"",labelHasLatex:!1}}:("_"!==t[0]&&(t.includes("_")||t.includes("-")?t=t.replace(/[_\-]/g," "):t.match(/^[a-z]/)?t.match(/[A-Z]/)&&(t=t.replace(/([A-Z])/g," $1").toLowerCase()):t.match(/^[A-Z]/)&&t.match(/[a-z]/)&&(t=t.replace(/([A-Z])/g," $1"),t=t.slice(1))),{setValue:{label:t,labelHasLatex:!1}})}return"string"==typeof e.shadowSource?.stateValues.label?{setValue:{label:e.shadowSource.stateValues.label,labelHasLatex:Boolean(e.shadowSource.stateValues.labelHasLatex)}}:{useEssentialOrDefaultValue:{label:!0},setValue:{labelHasLatex:!1}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){if("string"!=typeof e.label)return{success:!1};let n=t.labelChild.length-1,r=t.labelChild[n];return r&&!r.shadowDepth?{success:!0,instructions:[{setDependency:"labelChild",desiredValue:e.label,childIndex:n,variableIndex:0}]}:t.labelIsName&&!t.labelIsNameAttr.shadowDepth?{success:!0,instructions:[{setEssentialValue:"label",value:e.label}]}:"string"==typeof t.shadowSource?.stateValues.label?{success:!0,instructions:[{setDependency:"shadowSource",desiredValue:e.label,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"label",value:e.label}]}}},e.labelForGraph={forRenderer:!0,returnDependencies:()=>({label:{dependencyType:"stateVariable",variableName:"label"},labelHasLatex:{dependencyType:"stateVariable",variableName:"labelHasLatex"}}),definition({dependencyValues:e}){let t;if(e.labelHasLatex){let n=0;t="";for(let r of e.label)"("===r?n++:")"===r?n--:0===n&&("_"===r?r="_":"^"===r&&(r="^")),t+=r}else t=e.label.replaceAll("_","_").replaceAll("^","^");return{setValue:{labelForGraph:t}}}},e}class GraphicalComponent extends BaseComponent{static componentType="_graphical";static createAttributesObject(){let e=super.createAttributesObject();return e.labelIsName={createComponentOfType:"boolean",createStateVariable:"labelIsName",defaultValue:!1,public:!0},e.showLabel={createComponentOfType:"boolean",createStateVariable:"showLabel",defaultValue:!0,public:!0,forRenderer:!0},e.applyStyleToLabel={createComponentOfType:"boolean",createStateVariable:"applyStyleToLabel",defaultValue:!1,public:!0,forRenderer:!0},e.layer={createComponentOfType:"integer",createStateVariable:"layer",defaultValue:0,public:!0,forRenderer:!0},e}static returnChildGroups(){return[{group:"labels",componentTypes:["label"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnSelectedStyleStateVariableDefinition();Object.assign(e,t);let n=returnLabelStateVariableDefinitions();return Object.assign(e,n),e}}function returnNumericalFunctionFromFormula({formula:e,nInputs:t,variables:n,domain:r,component:a=0}){let i;if(a=Number(a),Array.isArray(e.tree)&&vectorOperators.includes(e.tree[0]))try{e=e.get_component(Number(a))}catch(e){return()=>NaN}else if(0!==a)return()=>NaN;try{i=e.subscripts_to_strings().f()}catch(e){return()=>NaN}if(1===t){let e=n[0].subscripts_to_strings().tree,t=-1/0,a=1/0,s=!1,o=!1;if(null!==r){let e=r[0];if(void 0!==e)try{t=me$3.fromAst(e.tree[1][1]).evaluate_to_constant(),Number.isFinite(t)?s=!e.tree[2][1]:t=-1/0,a=me$3.fromAst(e.tree[1][2]).evaluate_to_constant(),Number.isFinite(a)?o=!e.tree[2][2]:a=1/0}catch(e){}}return function(n,r=!1){if(r){if(isNaN(n))return NaN}else if(!(n>=t)||!(n<=a)||s&&n===t||o&&n===a)return NaN;try{return i({[e]:n})}catch(e){return NaN}}}let s=[];for(let e=0;eme$3.fromAst("_")}else if("0"!==t)return e=>me$3.fromAst("_");let r=e.simplify,a=e.expand,i=n.subscripts_to_strings();if(1===e.nInputs){let t=e.variables[0].subscripts_to_strings().tree;return e=>normalizeMathExpression({value:i.substitute({[t]:e}).strings_to_subscripts(),simplify:r,expand:a})}let s=[];for(let t=0;tNaN;let l=e-1;t[0][o];let u,c,p=t[l][o],d=n.map((e=>e[o]));return i&&(u=s[o]),r&&(c=a[o]),function(e){if(isNaN(e))return NaN;if(e<0)return i?(u[2]*e+u[1])*e+u[0]:NaN;if(e>=l)return r?(e-=l,(c[2]*e+c[1])*e+c[0]):e===l?p:NaN;let t=Math.floor(e);e-=t;let n=d[t];return((n[3]*e+n[2])*e+n[1])*e+n[0]}}function returnInterpolatedFunction({xs:e,coeffs:t,interpolationPoints:n,domain:r}){let a=[];if(n&&(a=n.map((e=>e.y))),null===e)return e=>NaN;let i=-1/0,s=1/0,o=!1,l=!1;if(null!==r){let e=r[0];if(void 0!==e)try{i=me$3.fromAst(e.tree[1][1]).evaluate_to_constant(),Number.isFinite(i)?o=!e.tree[2][1]:i=-1/0,s=me$3.fromAst(e.tree[1][2]).evaluate_to_constant(),Number.isFinite(s)?l=!e.tree[2][2]:s=1/0}catch(e){}}let u=e[0],c=e[e.length-1];return function(n,r=!1){if(r){if(isNaN(n))return NaN}else if(!(n>=i)||!(n<=s)||o&&n===i||l&&n===s)return NaN;if(n<=u){n-=u;let e=t[0];return((e[3]*n+e[2])*n+e[1])*n+e[0]}if(n>=c){let r=e.length-2;n-=e[r];let a=t[r];return((a[3]*n+a[2])*n+a[1])*n+a[0]}for(var p,d=0,m=e.length-1;d<=m;){p=Math.floor(.5*(d+m));let t=e[p];if(tn))return a[p];m=p-1}}let h=Math.max(0,m);n-=e[h];let f=t[h];return((f[3]*n+f[2])*n+f[1])*n+f[0]}}function returnReturnDerivativesOfInterpolatedFunction({xs:e,coeffs:t,variables:n}){if(!e)return e=>NaN;let r=n[0].subscripts_to_strings().tree,a=e[0],i=e[e.length-1];return function(n){let s=n.map((e=>e.subscripts_to_strings().tree)),o=s.length;return o>3||!s.every((e=>e===r))||s.includes("_")?e=>0:0===o||null===e?e=>NaN:function(n){if(isNaN(n))return NaN;if(n<=a){n-=a;let e=t[0];return 1===o?(3*e[3]*n+2*e[2])*n+e[1]:2===o?6*e[3]*n+2*e[2]:6*e[3]}if(n>=i){let r=e.length-2;n-=e[r];let a=t[r];return 1===o?(3*a[3]*n+2*a[2])*n+a[1]:2===o?6*a[3]*n+2*a[2]:6*a[3]}for(var r,s=0,l=e.length-1;s<=l;){r=Math.floor(.5*(s+l));let a=e[r];if(an))return 1===o?t[r][1]:2===o?2*t[r][2]:6*t[r][3];l=r-1}}let u=Math.max(0,l);n-=e[u];let c=t[u];return 1===o?(3*c[3]*n+2*c[2])*n+c[1]:2===o?6*c[3]*n+2*c[2]:6*c[3]}}}var functionOperatorDefinitions={clampFunction:function(e,t){return function(n){return Number.isFinite(n)?Math.max(e,Math.min(t,n)):NaN}},wrapFunctionPeriodic:function(e,t){return function(n){if(!Number.isFinite(n))return NaN;let r=e,a=t;return r===a?r:(r>a&&([a,r]=[r,a]),r+me$3.math.mod(n-r,a-r))}},derivative:function(e,t){if("interpolatedFunction"===e.derivativeType){let n=returnReturnDerivativesOfInterpolatedFunction({xs:e.xs,coeffs:e.coeffs,variables:e.variables.map(convertValueToMathExpression)}),r=t.map(convertValueToMathExpression);if(e.additionalDerivVariables){r=[...e.additionalDerivVariables.map(convertValueToMathExpression),...r]}if(e.variableMappings)for(let t of e.variableMappings){let e=[];for(let n of r){let r=t[n.subscripts_to_strings().tree];r?e.push(convertValueToMathExpression(r)):e.push(me$3.fromAst("_"))}r=e}return n(r)}return e=>NaN}};class Function$1 extends InlineComponent{static componentType="function";static rendererType="math";static primaryStateVariableForDefinition="numericalfShadow";static createAttributesObject(){let e=super.createAttributesObject();return e.simplify={createComponentOfType:"text",createStateVariable:"simplifySpecified",defaultValue:"none",toLowerCase:!0,valueTransformations:{true:"full"},validValues:["none","full","numbers","numberspreserveorder"]},e.expand={createComponentOfType:"boolean",createStateVariable:"expandSpecified",defaultValue:!1,public:!0},e.xscale={createComponentOfType:"number",createStateVariable:"xscale",defaultValue:1,public:!0},e.yscale={createComponentOfType:"number",createStateVariable:"yscale",defaultValue:1,public:!0},e.nInputs={createComponentOfType:"integer"},e.nOutputs={createComponentOfType:"integer"},e.domain={createComponentOfType:"_intervalListComponent"},e.labelIsName={createComponentOfType:"boolean",createStateVariable:"labelIsName",defaultValue:!1,public:!0},e.showLabel={createComponentOfType:"boolean",createStateVariable:"showLabel",defaultValue:!0,public:!0,forRenderer:!0},e.applyStyleToLabel={createComponentOfType:"boolean",createStateVariable:"applyStyleToLabel",defaultValue:!1,public:!0,forRenderer:!0},e.labelPosition={createComponentOfType:"text",createStateVariable:"labelPosition",defaultValue:"upperright",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft","top","bottom","left","right"]},e.layer={createComponentOfType:"number",createStateVariable:"layer",defaultValue:0,public:!0,forRenderer:!0},e.minima={createComponentOfType:"extrema"},e.maxima={createComponentOfType:"extrema"},e.extrema={createComponentOfType:"extrema"},e.through={createComponentOfType:"_pointListComponent"},e.throughSlopes={createComponentOfType:"mathList"},e.variables={createComponentOfType:"variables"},e.symbolic={createComponentOfType:"boolean"},e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer"},e.displaySmallAsZero={createComponentOfType:"number",valueForTrue:1e-14,valueForFalse:0},e.padZeros={createComponentOfType:"boolean"},e.nearestPointAsCurve={createComponentOfType:"boolean",createStateVariable:"nearestPointAsCurve",defaultValue:!1},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e,componentInfoObjects:t}){let n=e.map((e=>t.componentIsSpecifiedType(e,"label"))),r=[],a=[],i=[];if(0===n.filter((e=>e)).length)r=e;else{if(n[0]){let t=n.indexOf(!1);-1!==t&&(a=e.slice(0,t),e=e.slice(t),n=n.slice(t))}let t=n.indexOf(!0);-1===t?r=e:(r=e.slice(0,t),i=e.slice(t))}return 1===r.length&&"string"!=typeof r[0]||0===r.length?{success:!1}:{success:!0,newChildren:[...a,{componentType:"math",children:r},...i]}}}),e}static returnChildGroups(){return[{group:"maths",componentTypes:["math"]},{group:"functions",componentTypes:["function"]},{group:"labels",componentTypes:["label"]}]}static returnStateVariableDefinitions({numerics:e}){let t=GraphicalComponent.returnStateVariableDefinitions();return t.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){let t=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(t&&(t+=" "),t+=e.selectedStyle.lineStyleWord),t&&(t+=" "),t+=e.selectedStyle.lineColorWord,{setValue:{styleDescription:t}}}},t.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({styleDescription:{dependencyType:"stateVariable",variableName:"styleDescription"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescriptionWithNoun:e.styleDescription+" function"}}}},t.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},defaultValue:10,hasEssential:!0,returnDependencies:()=>({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["displayDigits"]}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.displayDigitsAttr){let n=t.displayDigitsAttr,r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!n&&!r){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth0){let n=t.functionChild[0],r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;return n||r||(n=!0),n?{useEssentialOrDefaultValue:{displayDigits:{defaultValue:e.functionChild[0].stateValues.displayDigits}}}:{setValue:{displayDigits:e.functionChild[0].stateValues.displayDigits}}}return{useEssentialOrDefaultValue:{displayDigits:!0}}}},t.displayDecimals={public:!0,shadowingInstructions:{createComponentOfType:"integer"},defaultValue:null,hasEssential:!0,returnDependencies:()=>({displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["displayDecimals"]}}),definition:({dependencyValues:e,usedDefault:t})=>null!==e.displayDecimalsAttr?{setValue:{displayDecimals:e.displayDecimalsAttr.stateValues.value}}:e.functionChild.length>0&&!t.functionChild[0]?{setValue:{displayDecimals:e.functionChild[0].stateValues.displayDecimals}}:{useEssentialOrDefaultValue:{displayDecimals:!0}}},t.displaySmallAsZero={public:!0,shadowingInstructions:{createComponentOfType:"number"},defaultValue:0,hasEssential:!0,returnDependencies:()=>({displaySmallAsZeroAttr:{dependencyType:"attributeComponent",attributeName:"displaySmallAsZero",variableNames:["value"]},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["displaySmallAsZero"]}}),definition:({dependencyValues:e,usedDefault:t})=>null!==e.displaySmallAsZeroAttr?{setValue:{displaySmallAsZero:e.displaySmallAsZeroAttr.stateValues.value}}:e.functionChild.length>0&&!t.functionChild[0]?{setValue:{displaySmallAsZero:e.functionChild[0].stateValues.displaySmallAsZero}}:{useEssentialOrDefaultValue:{displaySmallAsZero:!0}}},t.padZeros={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},defaultValue:!1,hasEssential:!0,returnDependencies:()=>({padZerosAttr:{dependencyType:"attributeComponent",attributeName:"padZeros",variableNames:["value"]},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["padZeros"]}}),definition:({dependencyValues:e,usedDefault:t})=>null!==e.padZerosAttr?{setValue:{padZeros:e.padZerosAttr.stateValues.value}}:e.functionChild.length>0&&!t.functionChild[0]?{setValue:{padZeros:e.functionChild[0].stateValues.padZeros}}:{useEssentialOrDefaultValue:{padZeros:!0}}},t.isInterpolatedFunction={returnDependencies:()=>({through:{dependencyType:"attributeComponent",attributeName:"through"},minima:{dependencyType:"attributeComponent",attributeName:"minima"},maxima:{dependencyType:"attributeComponent",attributeName:"maxima"},extrema:{dependencyType:"attributeComponent",attributeName:"extrema"}}),definition:({dependencyValues:e})=>({setValue:{isInterpolatedFunction:e.through||e.minima||e.maxima||e.extrema}})},t.nInputs={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({nInputsAttr:{dependencyType:"attributeComponent",attributeName:"nInputs",variableNames:["value"]},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["nInputs"]},variablesAttr:{dependencyType:"attributeComponent",attributeName:"variables",variableNames:["nComponents"]},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"}}),definition({dependencyValues:e}){if(e.isInterpolatedFunction)return{setValue:{nInputs:1}};if(null!==e.nInputsAttr){let t=e.nInputsAttr.stateValues.value;return t>=0||(t=1),{setValue:{nInputs:t}}}return null!==e.variablesAttr?{setValue:{nInputs:Math.max(1,e.variablesAttr.stateValues.nComponents)}}:e.functionChild.length>0?{setValue:{nInputs:e.functionChild[0].stateValues.nInputs}}:{setValue:{nInputs:1}}}},t.nOutputs={defaultValue:1,hasEssential:!0,public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({nOutputsAttr:{dependencyType:"attributeComponent",attributeName:"nOutputs",variableNames:["value"]},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["nOutputs"]},mathChild:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]}}),definition({dependencyValues:e}){if(e.functionChild.length>0)return{setValue:{nOutputs:e.functionChild[0].stateValues.nOutputs}};if(null!==e.nOutputsAttr){let t=e.nOutputsAttr.stateValues.value;return t>=0||(t=1),{setValue:{nOutputs:t}}}if(e.mathChild.length>0){let t=e.mathChild[0].stateValues.value,n=1;return Array.isArray(t.tree)&&vectorOperators.includes(t.tree[0])&&(n=t.tree.length-1),{setValue:{nOutputs:n}}}return{useEssentialOrDefaultValue:{nOutputs:!0}}}},t.domain={returnDependencies:()=>({domainAttr:{dependencyType:"attributeComponent",attributeName:"domain",variableNames:["intervals"]},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["domain"]},nInputs:{dependencyType:"stateVariable",variableName:"nInputs"}}),definition({dependencyValues:e}){if(null!==e.domainAttr){let t=e.nInputs,n=e.domainAttr.stateValues.intervals.slice(0,t);return n.length!==t?{setValue:{domain:null}}:n.every((e=>Array.isArray(e.tree)&&"interval"===e.tree[0]))?{setValue:{domain:n}}:{setValue:{domain:null}}}return e.functionChild.length>0?{setValue:{domain:e.functionChild[0].stateValues.domain}}:{setValue:{domain:null}}}},t.simplify={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({simplifySpecified:{dependencyType:"stateVariable",variableName:"simplifySpecified"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["simplify"]}}),definition:({dependencyValues:e,usedDefault:t})=>t.simplifySpecified&&e.functionChild.length>0?{setValue:{simplify:e.functionChild[0].stateValues.simplify}}:{setValue:{simplify:e.simplifySpecified}},inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t,usedDefault:n})=>n.simplifySpecified&&t.functionChild.length>0?{success:!0,instructions:[{setDependency:"functionChild",desiredValue:e.simplify,childIndex:0,variableIndex:0}]}:{success:!0,instructions:[{setDependency:"simplifySpecified",desiredValue:e.simplify}]}},t.expand={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({expandSpecified:{dependencyType:"stateVariable",variableName:"expandSpecified"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["expand"]}}),definition:({dependencyValues:e,usedDefault:t})=>t.expandSpecified&&e.functionChild.length>0?{setValue:{expand:e.functionChild[0].stateValues.expand}}:{setValue:{expand:e.expandSpecified}},inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t,usedDefault:n})=>n.expandSpecified&&t.functionChild.length>0?{success:!0,instructions:[{setDependency:"functionChild",desiredValue:e.expand,childIndex:0,variableIndex:0}]}:{success:!0,instructions:[{setDependency:"expandSpecified",desiredValue:e.expand}]}},t.numericalfShadow={defaultValue:null,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{numericalfShadow:!0}})},t.symbolicfShadow={defaultValue:null,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{symbolicfShadow:!0}})},t.symbolic={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},defaultValue:!1,hasEssential:!0,returnDependencies:()=>({symbolicAttr:{dependencyType:"attributeComponent",attributeName:"symbolic",variableNames:["value"]},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["symbolic"]},numericalfShadow:{dependencyType:"stateVariable",variableName:"numericalfShadow"},symbolicfShadow:{dependencyType:"stateVariable",variableName:"symbolicfShadow"}}),definition:({dependencyValues:e})=>null!==e.symbolicAttr?{setValue:{symbolic:e.symbolicAttr.stateValues.value}}:e.functionChild.length>0?{setValue:{symbolic:e.functionChild[0].stateValues.symbolic}}:e.numericalfShadow?{setValue:{symbolic:!1}}:e.symbolicfShadow?{setValue:{symbolic:!0}}:{useEssentialOrDefaultValue:{symbolic:!0}}},t.variables={isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"variable"},entryPrefixes:["variable"],returnArraySizeDependencies:()=>({nInputs:{dependencyType:"stateVariable",variableName:"nInputs"}}),returnArraySize:({dependencyValues:e})=>[e.nInputs],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["variable"+(Number(n)+1)]}};return{globalDependencies:{variablesAttr:{dependencyType:"attributeComponent",attributeName:"variables",variableNames:["variables"]},parentVariableForChild:{dependencyType:"parentStateVariable",variableName:"variableForChild"},functionChild:{dependencyType:"child",childGroups:["functions"]}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arraySize:n,arrayKeys:r,usedDefault:a}){if(null!==e.variablesAttr){let t=e.variablesAttr.stateValues.variables;return{setValue:{variables:returnNVariables(n[0],t)}}}if(e.functionChild.length>0){let e={};for(let n of r)e[n]=t[n].functionChild[0].stateValues["variable"+(Number(n)+1)];return{setValue:{variables:e}}}return e.parentVariableForChild&&!a.parentVariableForChild?{setValue:{variables:Array(n[0]).fill(e.parentVariableForChild)}}:{setValue:{variables:returnNVariables(n[0],[])}}}},t.variable={isAlias:!0,targetVariableName:"variable1"},t.unnormalizedFormula={defaultValue:me$3.fromAst(0),hasEssential:!0,returnDependencies:()=>({mathChild:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["formula"]},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"}}),definition:function({dependencyValues:e,usedDefault:t}){return e.isInterpolatedFunction?{setValue:{unnormalizedFormula:me$3.fromAst("_")}}:e.mathChild.length>0?{setValue:{unnormalizedFormula:e.mathChild[0].stateValues.value}}:e.functionChild.length>0&&!t.functionChild[0].formula?{setValue:{unnormalizedFormula:e.functionChild[0].stateValues.formula}}:{useEssentialOrDefaultValue:{unnormalizedFormula:!0}}}},t.formula={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},defaultValue:me$3.fromAst(0),hasEssential:!0,returnDependencies:()=>({unnormalizedFormula:{dependencyType:"stateVariable",variableName:"unnormalizedFormula"},simplify:{dependencyType:"stateVariable",variableName:"simplify"},expand:{dependencyType:"stateVariable",variableName:"expand"}}),definition:function({dependencyValues:e,usedDefault:t}){if(t.unnormalizedFormula)return{useEssentialOrDefaultValue:{formula:!0}};return{setValue:{formula:normalizeMathExpression({value:e.unnormalizedFormula,simplify:e.simplify,expand:e.expand})}}}},t.nPrescribedPoints={returnDependencies:()=>({through:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["nPoints"]}}),definition({dependencyValues:e}){let t=0;return null!==e.through&&(t=e.through.stateValues.nPoints),{setValue:{nPrescribedPoints:t}}}},t.prescribedPoints={isArray:!0,entryPrefixes:["prescribedPoint"],returnArraySizeDependencies:()=>({nPrescribedPoints:{dependencyType:"stateVariable",variableName:"nPrescribedPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nPrescribedPoints],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={through:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["point"+e]},throughSlopes:{dependencyType:"attributeComponent",attributeName:"throughSlopes",variableNames:["math"+e]}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].through;if(null!==t){let a=Number(r)+1,i=t.stateValues["point"+a],s=null,o=e[r].throughSlopes;null!==o&&(s=o.stateValues["math"+a],void 0===s&&(s=null)),n[r]={x:i[0],y:i[1],slope:s}}}return{setValue:{prescribedPoints:n}}}},t.prescribedMinima={returnDependencies:()=>({minima:{dependencyType:"attributeComponent",attributeName:"minima",variableNames:["extrema"]}}),definition({dependencyValues:e}){let t=[];return null!==e.minima&&(t=e.minima.stateValues.extrema.map((e=>({x:e[0],y:e[1]})))),{setValue:{prescribedMinima:t}}}},t.prescribedMaxima={returnDependencies:()=>({maxima:{dependencyType:"attributeComponent",attributeName:"maxima",variableNames:["extrema"]}}),definition({dependencyValues:e}){let t=[];return null!==e.maxima&&(t=e.maxima.stateValues.extrema.map((e=>({x:e[0],y:e[1]})))),{setValue:{prescribedMaxima:t}}}},t.prescribedExtrema={returnDependencies:()=>({extrema:{dependencyType:"attributeComponent",attributeName:"extrema",variableNames:["extrema"]}}),definition({dependencyValues:e}){let t=[];return null!==e.extrema&&(t=e.extrema.stateValues.extrema.map((e=>({x:e[0],y:e[1]})))),{setValue:{prescribedExtrema:t}}}},t.interpolationPoints={returnDependencies:()=>({xscale:{dependencyType:"stateVariable",variableName:"xscale"},yscale:{dependencyType:"stateVariable",variableName:"yscale"},prescribedPoints:{dependencyType:"stateVariable",variableName:"prescribedPoints"},prescribedMinima:{dependencyType:"stateVariable",variableName:"prescribedMinima"},prescribedMaxima:{dependencyType:"stateVariable",variableName:"prescribedMaxima"},prescribedExtrema:{dependencyType:"stateVariable",variableName:"prescribedExtrema"}}),definition:({dependencyValues:t})=>calculateInterpolationPoints({dependencyValues:t,numerics:e})},t.xs={additionalStateVariablesDefined:["coeffs"],returnDependencies:()=>({interpolationPoints:{dependencyType:"stateVariable",variableName:"interpolationPoints"}}),definition:computeSplineParamCoeffs},t.symbolicfs={isArray:!0,entryPrefixes:["symbolicf"],stateVariablesDeterminingDependencies:["isInterpolatedFunction"],returnArraySizeDependencies:()=>({nOutputs:{dependencyType:"stateVariable",variableName:"nOutputs"}}),returnArraySize:({dependencyValues:e})=>[e.nOutputs],returnArrayDependenciesByKey:({stateValues:e})=>e.isInterpolatedFunction?{globalDependencies:{xs:{dependencyType:"stateVariable",variableName:"xs"},coeffs:{dependencyType:"stateVariable",variableName:"coeffs"},interpolationPoints:{dependencyType:"stateVariable",variableName:"interpolationPoints"},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},domain:{dependencyType:"stateVariable",variableName:"domain"}}}:{globalDependencies:{formula:{dependencyType:"stateVariable",variableName:"formula"},variables:{dependencyType:"stateVariable",variableName:"variables"},nInputs:{dependencyType:"stateVariable",variableName:"nInputs"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["symbolicfs"]},simplify:{dependencyType:"stateVariable",variableName:"simplify"},expand:{dependencyType:"stateVariable",variableName:"expand"},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},symbolicfShadow:{dependencyType:"stateVariable",variableName:"symbolicfShadow"},numericalfShadow:{dependencyType:"stateVariable",variableName:"numericalfShadow"},domain:{dependencyType:"stateVariable",variableName:"domain"}}},arrayDefinitionByKey:function({globalDependencyValues:e,usedDefault:t,arrayKeys:n}){if(e.isInterpolatedFunction){let t={};for(let r of n)if("0"===r){let n=returnInterpolatedFunction({xs:e.xs,coeffs:e.coeffs,interpolationPoints:e.interpolationPoints,domain:e.domain});t[r]=function(e){me$3.fromAst(n(e.evaluate_to_constant()))}}else t[r]=e=>me$3.fromAst("_");return{setValue:{symbolicfs:t}}}if(t.formula||"_"===e.formula.tree&&0!==e.functionChild.length){if(e.functionChild.length>0){let t={};for(let r of n)t[r]=e.functionChild[0].stateValues.symbolicfs[r];return{setValue:{symbolicfs:t}}}if(e.symbolicfShadow){let t={};for(let r of n)t[r]="0"===r?e.symbolicfShadow:e=>me$3.fromAst("_");return{setValue:{symbolicfs:t}}}if(e.numericalfShadow){let t={};for(let r of n)t[r]="0"===r?function(t){let n=t.evaluate_to_constant();return null===n?NaN:me$3.fromAst(e.numericalfShadow(n))}:e=>me$3.fromAst("_");return{setValue:{symbolicfs:t}}}{let t={};for(let r of n)t[r]=returnSymbolicFunctionFromFormula(e,r);return{setValue:{symbolicfs:t}}}}{let t={};for(let r of n)t[r]=returnSymbolicFunctionFromFormula(e,r);return{setValue:{symbolicfs:t}}}}},t.symbolicf={isAlias:!0,targetVariableName:"symbolicf1"},t.numericalfs={isArray:!0,entryPrefixes:["numericalf"],stateVariablesDeterminingDependencies:["isInterpolatedFunction"],returnArraySizeDependencies:()=>({nOutputs:{dependencyType:"stateVariable",variableName:"nOutputs"}}),returnArraySize:({dependencyValues:e})=>[e.nOutputs],returnArrayDependenciesByKey:({stateValues:e})=>e.isInterpolatedFunction?{globalDependencies:{xs:{dependencyType:"stateVariable",variableName:"xs"},coeffs:{dependencyType:"stateVariable",variableName:"coeffs"},interpolationPoints:{dependencyType:"stateVariable",variableName:"interpolationPoints"},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},domain:{dependencyType:"stateVariable",variableName:"domain"}}}:{globalDependencies:{formula:{dependencyType:"stateVariable",variableName:"formula"},variables:{dependencyType:"stateVariable",variableName:"variables"},nInputs:{dependencyType:"stateVariable",variableName:"nInputs"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["numericalfs"]},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},symbolicfShadow:{dependencyType:"stateVariable",variableName:"symbolicfShadow"},numericalfShadow:{dependencyType:"stateVariable",variableName:"numericalfShadow"},domain:{dependencyType:"stateVariable",variableName:"domain"}}},arrayDefinitionByKey:function({globalDependencyValues:e,usedDefault:t,arrayKeys:n}){if(e.isInterpolatedFunction){let t={};for(let r of n)t[r]="0"===r?returnInterpolatedFunction({xs:e.xs,coeffs:e.coeffs,interpolationPoints:e.interpolationPoints,domain:e.domain}):e=>me$3.fromAst("_");return{setValue:{numericalfs:t}}}if(t.formula||"_"===e.formula.tree&&0!==e.functionChild.length){if(e.functionChild.length>0){let t={};for(let r of n)t[r]=e.functionChild[0].stateValues.numericalfs[r];return{setValue:{numericalfs:t}}}if(e.numericalfShadow){let t={};for(let r of n)t[r]="0"===r?e.numericalfShadow:()=>NaN;return{setValue:{numericalfs:t}}}if(e.symbolicfShadow){let e={};for(let t of n)e[t]="0"===t?function(e){let t=dependencyValues.symbolicfShadow(me$3.fromAst(e)).evaluate_to_constant();return null===t&&(t=NaN),t}:()=>NaN;return{setValue:{numericalfs:e}}}{let t={};for(let r of n)t[r]=returnNumericalFunctionFromFormula({formula:e.formula,nInputs:e.nInputs,variables:e.variables,domain:e.domain,component:r});return{setValue:{numericalfs:t}}}}{let t={};for(let r of n)t[r]=returnNumericalFunctionFromFormula({formula:e.formula,nInputs:e.nInputs,variables:e.variables,domain:e.domain,component:r});return{setValue:{numericalfs:t}}}}},t.numericalf={returnDependencies:()=>({numericalf1:{dependencyType:"stateVariable",variableName:"numericalf1"}}),definition:({dependencyValues:e})=>({setValue:{numericalf:e.numericalf1}})},t.fDefinitions={isArray:!0,entryPrefixes:["fDefinition"],stateVariablesDeterminingDependencies:["isInterpolatedFunction"],returnArraySizeDependencies:()=>({nOutputs:{dependencyType:"stateVariable",variableName:"nOutputs"}}),returnArraySize:({dependencyValues:e})=>[e.nOutputs],returnArrayDependenciesByKey:({stateValues:e})=>e.isInterpolatedFunction?{globalDependencies:{xs:{dependencyType:"stateVariable",variableName:"xs"},coeffs:{dependencyType:"stateVariable",variableName:"coeffs"},interpolationPoints:{dependencyType:"stateVariable",variableName:"interpolationPoints"},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},domain:{dependencyType:"stateVariable",variableName:"domain"}}}:{globalDependencies:{formula:{dependencyType:"stateVariable",variableName:"formula"},variables:{dependencyType:"stateVariable",variableName:"variables"},nInputs:{dependencyType:"stateVariable",variableName:"nInputs"},nOutputs:{dependencyType:"stateVariable",variableName:"nOutputs"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["fDefinitions"]},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},symbolicfShadow:{dependencyType:"stateVariable",variableName:"symbolicfShadow"},numericalfShadow:{dependencyType:"stateVariable",variableName:"numericalfShadow"},domain:{dependencyType:"stateVariable",variableName:"domain"}}},arrayDefinitionByKey:function({globalDependencyValues:e,usedDefault:t,arrayKeys:n}){if(e.isInterpolatedFunction){let t={};for(let r of n)t[r]="0"===r?{functionType:"interpolated",xs:e.xs,coeffs:e.coeffs,interpolationPoints:e.interpolationPoints,domain:e.domain}:{};return{setValue:{fDefinitions:t}}}if(t.formula||"_"===e.formula.tree&&0!==e.functionChild.length){if(e.functionChild.length>0){let t={};for(let r of n)t[r]=e.functionChild[0].stateValues.fDefinitions[r];return{setValue:{fDefinitions:t}}}if(e.numericalfShadow){let e={};for(let t of n)e[t]={};return{setValue:{fDefinitions:e}}}if(e.symbolicfShadow){let e={};for(let t of n)e[t]={};return{setValue:{fDefinitions:e}}}{let t={};for(let r of n)t[r]={functionType:"formula",formula:e.formula.tree,variables:e.variables.map((e=>e.tree)),nInputs:e.nInputs,nOutputs:e.nOutputs,domain:e.domain,component:r};return{setValue:{fDefinitions:t}}}}{let t={};for(let r of n)t[r]={functionType:"formula",formula:e.formula.tree,variables:e.variables.map((e=>e.tree)),nInputs:e.nInputs,nOutputs:e.nOutputs,domain:e.domain,component:r};return{setValue:{fDefinitions:t}}}}},t.fDefinition={isAlias:!0,targetVariableName:"fDefinition1"},t.fs={isArray:!0,entryPrefixes:["f"],returnArraySizeDependencies:()=>({nOutputs:{dependencyType:"stateVariable",variableName:"nOutputs"}}),returnArraySize:({dependencyValues:e})=>[e.nOutputs],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={symbolicf:{dependencyType:"stateVariable",variableName:"symbolicf"+e},numericalf:{dependencyType:"stateVariable",variableName:"numericalf"+e}}}return{globalDependencies:{symbolic:{dependencyType:"stateVariable",variableName:"symbolic"}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};if(e.symbolic)for(let e of n)r[e]=t[e].symbolicf;else for(let e of n)r[e]=t[e].numericalf;return{setValue:{fs:r}}}},t.f={isAlias:!0,targetVariableName:"f1"},t.latex={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({formula:{dependencyType:"stateVariable",variableName:"formula"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"}}),definition:function({dependencyValues:e,usedDefault:t}){let n={};return e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(n.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(n.padToDigits=e.displayDigits)),{setValue:{latex:roundForDisplay({value:e.formula,dependencyValues:e,usedDefault:t}).toLatex(n)}}}},t.latexWithInputChildren={forRenderer:!0,returnDependencies:()=>({latex:{dependencyType:"stateVariable",variableName:"latex"}}),definition:function({dependencyValues:e}){return{setValue:{latexWithInputChildren:[e.latex]}}}},t.allMinima={stateVariablesDeterminingDependencies:["isInterpolatedFunction"],returnDependencies:({stateValues:e})=>e.isInterpolatedFunction?{xs:{dependencyType:"stateVariable",variableName:"xs"},coeffs:{dependencyType:"stateVariable",variableName:"coeffs"},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},domain:{dependencyType:"stateVariable",variableName:"domain"}}:{numericalf:{dependencyType:"stateVariable",variableName:"numericalf"},formula:{dependencyType:"stateVariable",variableName:"formula"},variables:{dependencyType:"stateVariable",variableName:"variables"},xscale:{dependencyType:"stateVariable",variableName:"xscale"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["allMinima"]},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},nInputs:{dependencyType:"stateVariable",variableName:"nInputs"},nOutputs:{dependencyType:"stateVariable",variableName:"nOutputs"},domain:{dependencyType:"stateVariable",variableName:"domain"}},definition:function({dependencyValues:t}){if(t.isInterpolatedFunction){let n=t.xs,r=t.coeffs,a=e.eps,i=[];if(null===n)return{setValue:{allMinima:i}};let s=!1,o=-1/0,l=1/0,u=!1,c=!1;if(null!==t.domain){let e=t.domain[0];if(void 0!==e)try{o=me$3.fromAst(e.tree[1][1]).evaluate_to_constant(),Number.isFinite(o)?u=!e.tree[2][1]:o=-1/0,l=me$3.fromAst(e.tree[1][2]).evaluate_to_constant(),Number.isFinite(l)?c=!e.tree[2][2]:l=1/0}catch(e){}}let p=1e-14*Math.max(Math.abs(o),Math.abs(l)),d=r[0],m=n[1]-n[0];if(0===d[3]){if(d[2]>0){let e=-d[1]/(2*d[2]);e+n[0]>=o-p&&e+n[0]<=l+p&&(e<=m-a?u&&Math.abs(e+n[0]-o)0){let t=Math.sqrt(e),r=(-2*d[2]+t)/(6*d[3]);r+n[0]>=o-p&&r+n[0]<=l+p&&(r<=m-a?u&&Math.abs(r+n[0]-o)0){let t=-d[1]/(2*d[2]);if(t+n[e]>=o-p){if(!(t+n[e]<=l+p)){s=!1;continue}Math.abs(t)=a&&t<=m-a&&(u&&Math.abs(t+n[e]-o)0){let r=Math.sqrt(t),h=(-2*d[2]+r)/(6*d[3]);if(h+n[e]>=o-p){if(!(h+n[e]<=l+p)){s=!1;continue}Math.abs(h)=a&&h<=m-a&&(u&&Math.abs(h+n[e]-o)0){let e=-d[1]/(2*d[2]);e+n[n.length-2]>=o-p&&e+n[n.length-2]<=l+p&&(Math.abs(e)=a&&(u&&Math.abs(e+n[n.length-2]-o)0){let t=Math.sqrt(e),r=(-2*d[2]+t)/(6*d[3]);r+n[n.length-2]>=o-p&&r+n[n.length-2]<=l+p&&(r>=a||Math.abs(r)0)return{setValue:{allMinima:t.functionChild[0].stateValues.allMinima}};if(1!==t.nInputs||1!==t.nOutputs)return{setValue:{allMinima:[]}};let n,r,a=t.variables[0].subscripts_to_strings().tree,i=t.formula.subscripts_to_strings().derivative(a),s=!0;try{n=i.subscripts_to_strings().f()}catch(e){s=!1,r=()=>NaN}s&&(r=function(e){try{return n({[a]:e})}catch(e){return NaN}});let o=e=>t.numericalf(e,!0),l=-100*t.xscale,u=100*t.xscale,c=!1,p=!1;if(null!==t.domain){let e=t.domain[0];if(void 0!==e)try{l=me$3.fromAst(e.tree[1][1]).evaluate_to_constant(),Number.isFinite(l)?c=!e.tree[2][1]:l=-100*t.xscale,u=me$3.fromAst(e.tree[1][2]).evaluate_to_constant(),Number.isFinite(u)?p=!e.tree[2][2]:u=100*t.xscale}catch(e){}}let d=1e3,m=(u-l)/d,h=1e-10*Math.max(Math.abs(l),Math.abs(u)),f=[],y=!1,g=!1,b=o(l-m),v=r(l-m);for(let t=-1;t0&&(N=!0,y=!1,!(t>=l-h&&t<=u+h)||c&&Math.abs(t-l)({allMinima:{dependencyType:"stateVariable",variableName:"allMinima"}}),definition:({dependencyValues:e})=>({setValue:{numberMinima:e.allMinima.length},checkForActualChange:{numberMinima:!0}})},t.minima={stateVariablesDeterminingDependencies:["isInterpolatedFunction"],public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"],returnWrappingComponents:e=>"minimum"===e||void 0===e?[["point",{componentType:"mathList",isAttribute:"xs"}]]:[]},isArray:!0,nDimensions:2,entryPrefixes:["minimum","minimumLocations","minimumLocation","minimumValues","minimumValue"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if(["minimum","minimumLocation","minimumValue"].includes(e)){let r=Number(t)-1;return Number.isInteger(r)&&r>=0&&(!n||rt+",0")):["0,0"]:"minimumValues"===e?""!==t?[]:n?Array.from(Array(n[0]),((e,t)=>t+",1")):["0,1"]:[]},arrayVarNameFromArrayKey(e){let[t,n]=e.split(",");return"0"===n?"minimumLocation"+(Number(t)+1):"minimumValue"+(Number(t)+1)},arrayVarNameFromPropIndex(e,t){if("minima"===t){if(1===e.length)return"minimum"+e[0];{let t=Number(e[0]);if(Number.isInteger(t)&&t>0){if(1===e[1])return"minimumLocation"+t;if(2===e[1])return"minimumValue"+t}return null}}if("minimumLocations"===t)return"minimumLocation"+e[0];if("minimumValues"===t)return"minimumValue"+e[0];if("minimum"===t.slice(0,7)){let n=Number(t.slice(7));if(Number.isInteger(n)&&n>0){if(1===e[0])return"minimumLocation"+n;if(2===e[0])return"minimumValue"+n}}return null},returnArraySizeDependencies:()=>({numberMinima:{dependencyType:"stateVariable",variableName:"numberMinima"}}),returnArraySize:({dependencyValues:e})=>[e.numberMinima,2],returnArrayDependenciesByKey:()=>({globalDependencies:{allMinima:{dependencyType:"stateVariable",variableName:"allMinima"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n=0;ne.isInterpolatedFunction?{xs:{dependencyType:"stateVariable",variableName:"xs"},coeffs:{dependencyType:"stateVariable",variableName:"coeffs"},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},domain:{dependencyType:"stateVariable",variableName:"domain"}}:{numericalf:{dependencyType:"stateVariable",variableName:"numericalf"},formula:{dependencyType:"stateVariable",variableName:"formula"},variables:{dependencyType:"stateVariable",variableName:"variables"},xscale:{dependencyType:"stateVariable",variableName:"xscale"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["allMaxima"]},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},nInputs:{dependencyType:"stateVariable",variableName:"nInputs"},nOutputs:{dependencyType:"stateVariable",variableName:"nOutputs"},domain:{dependencyType:"stateVariable",variableName:"domain"}},definition:function({dependencyValues:t}){if(t.isInterpolatedFunction){let n=t.xs,r=t.coeffs,a=e.eps,i=[];if(null===n)return{setValue:{allMaxima:i}};let s=!1,o=-1/0,l=1/0,u=!1,c=!1;if(null!==t.domain){let e=t.domain[0];if(void 0!==e)try{o=me$3.fromAst(e.tree[1][1]).evaluate_to_constant(),Number.isFinite(o)?u=!e.tree[2][1]:o=-1/0,l=me$3.fromAst(e.tree[1][2]).evaluate_to_constant(),Number.isFinite(l)?c=!e.tree[2][2]:l=1/0}catch(e){}}let p=1e-14*Math.max(Math.abs(o),Math.abs(l)),d=r[0],m=n[1]-n[0];if(0===d[3]){if(d[2]<0){let e=-d[1]/(2*d[2]);e+n[0]>=o-p&&e+n[0]<=l+p&&(e<=m-a?u&&Math.abs(e+n[0]-o)0){let t=Math.sqrt(e),r=(-2*d[2]-t)/(6*d[3]);r+n[0]>=o-p&&r+n[0]<=l+p&&(r<=m-a?u&&Math.abs(r+n[0]-o)=o-p){if(!(t+n[e]<=l+p)){s=!1;continue}Math.abs(t)=a&&t<=m-a&&(u&&Math.abs(t+n[e]-o)0){let r=Math.sqrt(t),h=(-2*d[2]-r)/(6*d[3]);if(h+n[e]>=o-p){if(!(h+n[e]<=l+p)){s=!1;continue}Math.abs(h)=a&&h<=m-a&&(u&&Math.abs(h+n[e]-o)=o-p&&e+n[n.length-2]<=l+p&&(Math.abs(e)=a&&(u&&Math.abs(e+n[n.length-2]-o)0){let t=Math.sqrt(e),r=(-2*d[2]-t)/(6*d[3]);r+n[n.length-2]>=o-p&&r+n[n.length-2]<=l+p&&(r>=a||Math.abs(r)0)return{setValue:{allMaxima:t.functionChild[0].stateValues.allMaxima}};if(1!==t.nInputs||1!==t.nOutputs)return{setValue:{allMaxima:[]}};let n,r,a=t.variables[0].subscripts_to_strings().tree,i=t.formula.subscripts_to_strings().derivative(a),s=!0;try{n=i.subscripts_to_strings().f()}catch(e){s=!1,r=()=>NaN}s&&(r=function(e){try{return n({[a]:e})}catch(e){return NaN}});let o=e=>-t.numericalf(e,!0),l=-100*t.xscale,u=100*t.xscale,c=!1,p=!1;if(null!==t.domain){let e=t.domain[0];if(void 0!==e)try{l=me$3.fromAst(e.tree[1][1]).evaluate_to_constant(),Number.isFinite(l)?c=!e.tree[2][1]:l=-100*t.xscale,u=me$3.fromAst(e.tree[1][2]).evaluate_to_constant(),Number.isFinite(u)?p=!e.tree[2][2]:u=100*t.xscale}catch(e){}}let d=1e3,m=(u-l)/d,h=1e-10*Math.max(Math.abs(l),Math.abs(u)),f=[],y=!1,g=!1,b=o(l-m),v=r(l-m);for(let t=-1;t0&&r(t+i)<0&&(N=!0,y=!1,!(t>=l-h&&t<=u+h)||c&&Math.abs(t-l)({allMaxima:{dependencyType:"stateVariable",variableName:"allMaxima"}}),definition:({dependencyValues:e})=>({setValue:{numberMaxima:e.allMaxima.length},checkForActualChange:{numberMaxima:!0}})},t.maxima={stateVariablesDeterminingDependencies:["isInterpolatedFunction"],public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"],returnWrappingComponents:e=>"maximum"===e||void 0===e?[["point",{componentType:"mathList",isAttribute:"xs"}]]:[]},isArray:!0,nDimensions:2,entryPrefixes:["maximum","maximumLocations","maximumLocation","maximumValues","maximumValue"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if(["maximum","maximumLocation","maximumValue"].includes(e)){let r=Number(t)-1;return Number.isInteger(r)&&r>=0&&(!n||rt+",0")):["0,0"]:"maximumValues"===e?""!==t?[]:n?Array.from(Array(n[0]),((e,t)=>t+",1")):["0,1"]:[]},arrayVarNameFromArrayKey(e){let[t,n]=e.split(",");return"0"===n?"maximumLocation"+(Number(t)+1):"maximumValue"+(Number(t)+1)},arrayVarNameFromPropIndex(e,t){if("maxima"===t){if(1===e.length)return"maximum"+e[0];{let t=Number(e[0]);if(Number.isInteger(t)&&t>0){if(1===e[1])return"maximumLocation"+t;if(2===e[1])return"maximumValue"+t}return null}}if("maximumLocations"===t)return"maximumLocation"+e[0];if("maximumValues"===t)return"maximumValue"+e[0];if("maximum"===t.slice(0,7)){let n=Number(t.slice(7));if(Number.isInteger(n)&&n>0){if(1===e[0])return"maximumLocation"+n;if(2===e[0])return"maximumValue"+n}}return null},returnArraySizeDependencies:()=>({numberMaxima:{dependencyType:"stateVariable",variableName:"numberMaxima"}}),returnArraySize:({dependencyValues:e})=>[e.numberMaxima,2],returnArrayDependenciesByKey:()=>({globalDependencies:{allMaxima:{dependencyType:"stateVariable",variableName:"allMaxima"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n=0;n({numberMinima:{dependencyType:"stateVariable",variableName:"numberMinima"},numberMaxima:{dependencyType:"stateVariable",variableName:"numberMaxima"}}),definition:function({dependencyValues:e}){return{setValue:{numberExtrema:e.numberMinima+e.numberMaxima},checkForActualChange:{numberExtrema:!0}}}},t.allExtrema={returnDependencies:()=>({allMinima:{dependencyType:"stateVariable",variableName:"allMinima"},allMaxima:{dependencyType:"stateVariable",variableName:"allMaxima"}}),definition({dependencyValues:e}){let t=[...e.allMinima,...e.allMaxima].sort(((e,t)=>e[0]-t[0]));return{setValue:{allExtrema:t}}}},t.extrema={public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"],returnWrappingComponents:e=>"extremum"===e||void 0===e?[["point",{componentType:"mathList",isAttribute:"xs"}]]:[]},isArray:!0,nDimensions:2,entryPrefixes:["extremum","extremumLocations","extremumLocation","extremumValues","extremumValue"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if(["extremum","extremumLocation","extremumValue"].includes(e)){let r=Number(t)-1;return Number.isInteger(r)&&r>=0&&(!n||rt+",0")):["0,0"]:"extremumValues"===e?""!==t?[]:n?Array.from(Array(n[0]),((e,t)=>t+",1")):["0,1"]:[]},arrayVarNameFromArrayKey(e){let[t,n]=e.split(",");return"0"===n?"extremumLocation"+(Number(t)+1):"extremumValue"+(Number(t)+1)},arrayVarNameFromPropIndex(e,t){if("extrema"===t){if(1===e.length)return"extremum"+e[0];{let t=Number(e[0]);if(Number.isInteger(t)&&t>0){if(1===e[1])return"extremumLocation"+t;if(2===e[1])return"extremumValue"+t}return null}}if("extremumLocations"===t)return"extremumLocation"+e[0];if("extremumValues"===t)return"extremumValue"+e[0];if("extremum"===t.slice(0,8)){let n=Number(t.slice(8));if(Number.isInteger(n)&&n>0){if(1===e[0])return"extremumLocation"+n;if(2===e[0])return"extremumValue"+n}}return null},returnArraySizeDependencies:()=>({numberExtrema:{dependencyType:"stateVariable",variableName:"numberExtrema"}}),returnArraySize:({dependencyValues:e})=>[e.numberExtrema,2],returnArrayDependenciesByKey:()=>({globalDependencies:{allExtrema:{dependencyType:"stateVariable",variableName:"allExtrema"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n=0;ne.isInterpolatedFunction?{xs:{dependencyType:"stateVariable",variableName:"xs"},coeffs:{dependencyType:"stateVariable",variableName:"coeffs"},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},variables:{dependencyType:"stateVariable",variableName:"variables"}}:{functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["returnNumericalDerivatives","variables"]},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},variables:{dependencyType:"stateVariable",variableName:"variables"}},definition:function({dependencyValues:e}){if(e.isInterpolatedFunction)return{setValue:{returnNumericalDerivatives:returnReturnDerivativesOfInterpolatedFunction(e)}};if(e.functionChild.length>0&&e.functionChild[0].stateValues.returnNumericalDerivatives){let t=e.variables.map((e=>e.subscripts_to_strings().tree)),n=e.functionChild[0].stateValues.variables,r=n.map((e=>e.subscripts_to_strings().tree)),a={};for(let[e,i]of t.entries())r[e]&&r[e]!==i&&(a[i]=n[e]);if(0===Object.keys(a).length)return{setValue:{returnNumericalDerivatives:e.functionChild[0].stateValues.returnNumericalDerivatives}};return{setValue:{returnNumericalDerivatives:function(t){let n=[];for(let e of t){let t=a[e.subscripts_to_strings().tree];t?n.push(t):n.push(me$3.fromAst("_"))}return e.functionChild[0].stateValues.returnNumericalDerivatives(n)}}}}return{setValue:{returnNumericalDerivatives:null}}}},t.numericalDerivativesDefinition={stateVariablesDeterminingDependencies:["isInterpolatedFunction"],returnDependencies:({stateValues:e})=>e.isInterpolatedFunction?{xs:{dependencyType:"stateVariable",variableName:"xs"},coeffs:{dependencyType:"stateVariable",variableName:"coeffs"},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},variables:{dependencyType:"stateVariable",variableName:"variables"}}:{functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["numericalDerivativesDefinition","variables"]},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},variables:{dependencyType:"stateVariable",variableName:"variables"}},definition:function({dependencyValues:e}){if(e.isInterpolatedFunction)return{setValue:{numericalDerivativesDefinition:{derivativeType:"interpolatedFunction",xs:e.xs,coeffs:e.coeffs,variables:e.variables}}};if(e.functionChild.length>0&&e.functionChild[0].stateValues.numericalDerivativesDefinition){let t=e.variables.map((e=>e.subscripts_to_strings().tree)),n=e.functionChild[0].stateValues.variables,r=n.map((e=>e.subscripts_to_strings().tree)),a={};for(let[e,i]of t.entries())r[e]&&r[e]!==i&&(a[i]=n[e]);if(0===Object.keys(a).length)return{setValue:{numericalDerivativesDefinition:e.functionChild[0].stateValues.numericalDerivativesDefinition}};{let t={...e.functionChild[0].stateValues.numericalDerivativesDefinition};return t.variableMappings?t.variableMappings=[a,...t.variableMappings]:t.variableMappings=[a],{setValue:{numericalDerivativesDefinition:t}}}}return{setValue:{numericalDerivativesDefinition:{}}}}},t}static adapters=[{stateVariable:"numericalf",componentType:"curve",stateVariablesToShadow:["label","labelHasLatex"]},{stateVariable:"formula",componentType:"math",stateVariablesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]}]}function calculateInterpolationPoints({dependencyValues:e,numerics:t}){let n=[],r=[],a={maximum:e.prescribedMaxima,minimum:e.prescribedMinima,extremum:e.prescribedExtrema,point:e.prescribedPoints};for(let e in a)for(let t of a[e]){let a=null,i=null,s=null;if(null===t.x||(a=t.x.evaluate_to_constant(),Number.isFinite(a)))if(null===t.y||(i=t.y.evaluate_to_constant(),Number.isFinite(i)))if(null!==t.slope&&void 0!==t.slope&&(s=t.slope.evaluate_to_constant(),Number.isFinite(s)||(console.warn("Ignoring non-numerical slope"),s=null)),null===a){if(null===i){console.warn(`Ignoring empty ${e}`);continue}r.push({type:e,y:i,slope:s})}else n.push({type:e,x:a,y:i,slope:s});else console.warn(`Ignoring non-numerical ${e}`);else console.warn(`Ignoring non-numerical ${e}`)}n.sort(((e,t)=>e.x-t.x)),r.sort(((e,t)=>e.y-t.y));let i=-1/0,s=t.eps;for(let e=0;e0;){let e,t;void 0===l?e=v({allowedTypes:["maximum","minimum","extremum"],comparison:"atLeast",value:-1/0}):"maximum"===l?e=v({allowedTypes:["minimum","extremum"],comparison:"atMost",value:o-c}):"minimum"===l?e=v({allowedTypes:["maximum","extremum"],comparison:"atLeast",value:o+c}):"point"===l&&(e=v({allowedTypes:["maximum","extremum"],comparison:"atLeast",value:o+c}),!0!==e.success&&(e=v({allowedTypes:["minimum","extremum"],comparison:"atMost",value:o-c}))),!0===e.success?(t=e.point,r.splice(e.ind,1),m?(t.x=0,m=!1):t.x=i+u):(t=r.pop(),m?(t.x=0,m=!1):t.x=i+2*u);let n=y({p:t,typePrev:l,xPrev:i,yPrev:o});l=n.type,i=n.x,o=n.y}if(0===p.length&&p.push({type:"point",x:0,y:0,slope:0}),m=p[0],"maximum"===m.type){let e={type:"point",x:m.x-u,y:m.y-c,slope:2*c/u};p.splice(0,0,e)}else if("minimum"===m.type){let e={type:"point",x:m.x-u,y:m.y+c,slope:-2*c/u};p.splice(0,0,e)}else if("point"===m.type)if(1===p.length)null===m.slope&&(m.slope=0);else{let e=p[1],t=(e.y-m.y)/(e.x-m.x);if("maximum"===e.type||"minimum"===e.type)null===m.slope&&(m.slope=2*t);else{2===p.length?null===m.slope&&(m.slope=t):(null===e.slope&&(e.slope=f({point:e,prevPoint:m,nextPoint:p[2]})),null===m.slope&&(m.slope=2*(m.y-e.y)/(m.x-e.x)-e.slope));let n={x:m.x-u,y:m.y-u*m.slope,slope:m.slope};p.splice(0,0,n)}}let h=p[p.length-1];if("maximum"===h.type){let e={type:"point",x:h.x+u,y:h.y-c,slope:-2*c/u};p.push(e)}else if("minimum"===h.type){let e={type:"point",x:h.x+u,y:h.y+c,slope:2*c/u};p.push(e)}else if("point"===h.type)if(1===p.length){let e={type:"point",x:h.x+u,y:h.y+m.slope*u,slope:m.slope};p.push(e)}else{let e=p[p.length-2],t=(e.y-h.y)/(e.x-h.x);if("maximum"===e.type||"minimum"===e.type)null===h.slope&&(h.slope=2*t);else{2===p.length?null===h.slope&&(h.slope=t):(null===e.slope&&(e.slope=f({point:e,prevPoint:p[p.length-3],nextPoint:h})),null===h.slope&&(h.slope=2*(e.y-h.y)/(e.x-h.x)-e.slope));let n={x:h.x+u,y:h.y+u*h.slope,slope:h.slope};p.push(n)}}for(let e=1;ei-c||void 0!==r&&null!==e.y&&e.y>t.y-c?g({x:e.x,y:e.y,typePrev:n,xPrev:a,yPrev:i,yNext:s,pNext:t}):b({x:e.x,y:e.y,typePrev:n,xPrev:a,yPrev:i,yNext:s,pNext:t});if("minimum"===n||"minimum"===r)return null!==e.y&&e.yt.y+c?b({x:e.x,y:e.y,typePrev:n,xPrev:a,yPrev:i,yNext:s,pNext:t}):g({x:e.x,y:e.y,typePrev:n,xPrev:a,yPrev:i,yNext:s,pNext:t});if("point"===n||"point"===r){let o="maximum";return(null===e.y&&void 0!==t&&t.type===maximum||null!==e.y&&e.y<=i-c||void 0!==r&&null!==e.y&&e.y>=t.y-c)&&(o="minimum"),"minimum"===o?b({x:e.x,y:e.y,typePrev:n,xPrev:a,yPrev:i,yNext:s,pNext:t}):g({x:e.x,y:e.y,typePrev:n,xPrev:a,yPrev:i,yNext:s,pNext:t})}return null!==e.y&&e.ys-c){let n,a,o=(e+i)/2,l=null,u=v({allowedTypes:["minimum","extremum"],comparison:"atMost",value:Math.min(s,t)-c});!0===u.success?(a="minimum",n=u.point.y,r.splice(u.ind,1),l=0):(a="point",n=s-c),p.push({type:a,x:o,y:n,slope:l})}}else if("minimum"===a&&ti-c){let n=[(2*a+e)/3,(a+2*e)/3],s=[i-c,t+c],o=["atMost","atLeast"],l=[["minimum","extremum"],["maximum","extremum"]];for(let e=0;e<2;e++){let t,a,i=n[e],u=null,c=v({allowedTypes:l[e],comparison:o[e],value:s[e]});!0===c.success?(a=l[e][0],t=c.point.y,r.splice(c.ind,1),u=0):(a="point",t=s[e],u=null),p.push({type:a,x:i,y:t,slope:u})}}}else if("minimum"===n){null===t&&(t=void 0===s?i:"minimum"===o.type?Math.min(i,s):Math.min(i,s-c));let n,l,u=Math.max(i,t)+c,d=(e+a)/2,m=null,h=v({allowedTypes:["maximum","extremum"],comparison:"atLeast",value:u});!0===h.success?(l="maximum",n=h.point.y,r.splice(h.ind,1),m=0):(l="point",n=u),p.push({type:l,x:d,y:n,slope:m})}else if("point"===n)if(null===t)t=void 0===s?i-c:"minimum"===o.type?Math.min(i-c,s):Math.min(i,s)-c;else if(t>i-c){let n,i,s=(e+a)/2,o=null,l=v({allowedTypes:["maximum","extremum"],comparison:"atLeast",value:t+c});!0===l.success?(i="maximum",n=l.point.y,r.splice(l.ind,1),o=0):(i="point",n=t+c),p.push({type:i,x:s,y:n,slope:o})}let l={type:"minimum",x:e,y:t,slope:0};return p.push(l),l}function v({allowedTypes:e,comparison:t,value:n}){let a=[];if("atMost"===t)a=Object.keys(r).reverse();else{if("atLeast"!==t)return{success:!1};a=Object.keys(r)}for(let i of e)for(let e of a){let a=r[e];if(a.type===i)if("atMost"===t){if(a.y<=n)return{success:!0,ind:e,point:a}}else if(a.y>=n)return{success:!0,ind:e,point:a}}return{success:!1}}}function computeSplineParamCoeffs({dependencyValues:e}){let t=e.interpolationPoints;if(null===t)return{setValue:{xs:null,coeffs:null}};let n,r=[],a=[],i=t[0];a.push(i.x);for(let e=1;et.componentIsSpecifiedType(e,"label");if(0===e.length||!e.every((e=>"string"==typeof e||e.doenetAttributes?.createdFromMacro||n(e))))return{success:!1};let r=e.map(n),a=[],i=[],s=[];if(0===r.filter((e=>e)).length)a=e;else{if(r[0]){let t=r.indexOf(!1);-1!==t&&(i=e.slice(0,t),e=e.slice(t),r=r.slice(t))}let t=r.indexOf(!0);-1===t?a=e:(a=e.slice(0,t),s=e.slice(t))}return 0===a.length||1===a.length&&"string"!=typeof a[0]?{success:!1}:{success:!0,newChildren:[...i,{componentType:"math",children:a},...s]}}}),e}static returnStateVariableDefinitions({numerics:e}){let t=super.returnStateVariableDefinitions({numerics:e}),n=this.componentType;t.isInterpolatedFunction={returnDependencies:()=>({}),definition:()=>({setValue:{isInterpolatedFunction:!1}})},delete t.nPrescribedPoints,delete t.prescribedPoints,delete t.prescribedMinima,delete t.prescribedMaxima,delete t.prescribedExtrema,delete t.interpolationPoints,delete t.xs,t.operatorBasedOnFormulaIfAvailable={returnDependencies:()=>({}),definition:()=>({setValue:{operatorBasedOnFormulaIfAvailable:!1}})},t.formula.returnDependencies=()=>({}),t.formula.definition=()=>({setValue:{formula:me$3.fromAst("_")}}),t.operatorComposesWithOriginal={returnDependencies:()=>({}),definition:()=>({setValue:{operatorComposesWithOriginal:!0}})},t.symbolicFunctionOperator={returnDependencies:()=>({}),definition:()=>({setValue:{symbolicFunctionOperator:e=>me$3.fromAst("_")}})},t.numericalFunctionOperator={additionalStateVariablesDefined:["numericalFunctionOperatorArguments"],returnDependencies:()=>({}),definition:()=>({setValue:{numericalFunctionOperator:e=>NaN,numericalFunctionOperatorArguments:[]}})},t.numericalFunctionOperatorArguments={returnDependencies:()=>({}),definition:()=>({setValue:{numericalFunctionOperatorArguments:{}}})},t.formulaOperator={returnDependencies:()=>({}),definition:()=>({setValue:{formulaOperator:e=>me$3.fromAst("_")}})},t.returnNumericalDerivatives={returnDependencies:()=>({}),definition:()=>({setValue:{returnNumericalDerivatives:null}})},t.formula={public:!0,shadowingInstructions:{createComponentOfType:"math"},additionalStateVariablesDefined:["operatorBasedOnFormula"],returnDependencies:()=>({operatorBasedOnFormulaIfAvailable:{dependencyType:"stateVariable",variableName:"operatorBasedOnFormulaIfAvailable"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["formula"]},mathChild:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]},formulaOperator:{dependencyType:"stateVariable",variableName:"formulaOperator"}}),definition:function({dependencyValues:e}){if(!e.operatorBasedOnFormulaIfAvailable||(0===e.functionChild.length||"_"===e.functionChild[0].stateValues.formula.tree)&&(0===e.mathChild.length||"_"===e.mathChild[0].stateValues.value.tree))return{setValue:{formula:me$3.fromAst("_"),operatorBasedOnFormula:!1}};let t;return t=0===e.functionChild.length?e.mathChild[0].stateValues.value:e.functionChild[0].stateValues.formula,{setValue:{formula:e.formulaOperator(t),operatorBasedOnFormula:!0}}}},t.symbolicfs={isArray:!0,entryPrefixes:["symbolicf"],returnArraySizeDependencies:()=>({nOutputs:{dependencyType:"stateVariable",variableName:"nOutputs"}}),returnArraySize:({dependencyValues:e})=>[e.nOutputs],returnArrayDependenciesByKey:()=>({globalDependencies:{operatorBasedOnFormula:{dependencyType:"stateVariable",variableName:"operatorBasedOnFormula"},formula:{dependencyType:"stateVariable",variableName:"formula"},variables:{dependencyType:"stateVariable",variableName:"variables"},nInputs:{dependencyType:"stateVariable",variableName:"nInputs"},simplify:{dependencyType:"stateVariable",variableName:"simplify"},expand:{dependencyType:"stateVariable",variableName:"expand"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["symbolicfs"]},mathChild:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]},symbolicFunctionOperator:{dependencyType:"stateVariable",variableName:"symbolicFunctionOperator"},operatorComposesWithOriginal:{dependencyType:"stateVariable",variableName:"operatorComposesWithOriginal"},domain:{dependencyType:"stateVariable",variableName:"domain"}}}),arrayDefinitionByKey:function({globalDependencyValues:e,usedDefault:t,arrayKeys:n,arraySize:r}){if(!e.operatorBasedOnFormula){if(e.operatorComposesWithOriginal){if(0===e.functionChild.length){if(0===e.mathChild.length){let e={};for(let t of n)e[t]=e=>me$3.fromAst("_");return{setValue:{symbolicfs:e}}}{let t=Object.assign({},e);t.formula=e.mathChild[0].stateValues.value;let a=[];for(let e=0;ee.symbolicFunctionOperator(...a.map((e=>e(...t))));return{setValue:{symbolicfs:i}}}}{let t=[];for(let n=0;ne.symbolicFunctionOperator(...t.map((e=>e(...n))));return{setValue:{symbolicfs:a}}}}{let t={};for(let r of n)t[r]=(...t)=>e.symbolicFunctionOperator(...t);return{setValue:{symbolicfs:t}}}}{let t={};for(let r of n)return t[r]=returnSymbolicFunctionFromFormula(e,r),{setValue:{symbolicfs:t}}}}},t.numericalfs={isArray:!0,entryPrefixes:["numericalf"],returnArraySizeDependencies:()=>({nOutputs:{dependencyType:"stateVariable",variableName:"nOutputs"}}),returnArraySize:({dependencyValues:e})=>[e.nOutputs],returnArrayDependenciesByKey:()=>({globalDependencies:{operatorBasedOnFormula:{dependencyType:"stateVariable",variableName:"operatorBasedOnFormula"},formula:{dependencyType:"stateVariable",variableName:"formula"},variables:{dependencyType:"stateVariable",variableName:"variables"},nInputs:{dependencyType:"stateVariable",variableName:"nInputs"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["numericalfs"]},mathChild:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]},numericalFunctionOperator:{dependencyType:"stateVariable",variableName:"numericalFunctionOperator"},operatorComposesWithOriginal:{dependencyType:"stateVariable",variableName:"operatorComposesWithOriginal"},domain:{dependencyType:"stateVariable",variableName:"domain"}}}),arrayDefinitionByKey:function({globalDependencyValues:e,usedDefault:t,arrayKeys:n,arraySize:r}){if(!e.operatorBasedOnFormula){if(e.operatorComposesWithOriginal){if(0===e.functionChild.length){if(0===e.mathChild.length){let e={};for(let t of n)e[t]=e=>NaN;return{setValue:{numericalfs:e}}}{Object.assign({},e).formula=e.mathChild[0].stateValues.value;let t=[];for(let n=0;ne.numericalFunctionOperator(...t.map((e=>e(...n))));return{setValue:{numericalfs:a}}}}{let t=[];for(let n=0;ne.numericalFunctionOperator(...t.map((e=>e(...n))));return{setValue:{numericalfs:a}}}}{let t={};for(let r of n)t[r]=(...t)=>e.numericalFunctionOperator(...t);return{setValue:{numericalfs:t}}}}{let t={};for(let r of n)return t[r]=returnNumericalFunctionFromFormula({formula:e.formula,nInputs:e.nInputs,variables:e.variables,domain:e.domain,component:r}),{setValue:{numericalfs:t}}}}},t.fDefinitions={isArray:!0,entryPrefixes:["fDefinition"],returnArraySizeDependencies:()=>({nOutputs:{dependencyType:"stateVariable",variableName:"nOutputs"}}),returnArraySize:({dependencyValues:e})=>[e.nOutputs],returnArrayDependenciesByKey:()=>({globalDependencies:{operatorBasedOnFormula:{dependencyType:"stateVariable",variableName:"operatorBasedOnFormula"},formula:{dependencyType:"stateVariable",variableName:"formula"},variables:{dependencyType:"stateVariable",variableName:"variables"},nInputs:{dependencyType:"stateVariable",variableName:"nInputs"},nOutputs:{dependencyType:"stateVariable",variableName:"nOutputs"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["fDefinitions"]},mathChild:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]},numericalFunctionOperator:{dependencyType:"stateVariable",variableName:"numericalFunctionOperator"},numericalFunctionOperatorArguments:{dependencyType:"stateVariable",variableName:"numericalFunctionOperatorArguments"},operatorComposesWithOriginal:{dependencyType:"stateVariable",variableName:"operatorComposesWithOriginal"},domain:{dependencyType:"stateVariable",variableName:"domain"}}}),arrayDefinitionByKey:function({globalDependencyValues:e,usedDefault:t,arrayKeys:r,arraySize:a}){if(e.operatorBasedOnFormula){let t={};for(let n of r)t[n]={functionType:"formula",formula:e.formula.tree,variables:e.variables.map((e=>e.tree)),nInputs:e.nInputs,nOutputs:e.nOutputs,domain:e.domain,component:n};return{setValue:{fDefinitions:t}}}if(e.operatorComposesWithOriginal){if(0===e.functionChild.length){if(0===e.mathChild.length){let t={};for(let n of r)t[n]={functionType:"formula",formula:"_",variables:e.variables.map((e=>e.tree)),nInputs:e.nInputs,nOutputs:e.nOutputs,domain:e.domain};return{setValue:{fDefinitions:t}}}throw Error("function operator with math child not implemented yet")}{let t={};for(let a of r)t[a]={functionType:"functionOperator",componentType:n,nOutputs:e.nOutputs,functionOperatorArguments:e.numericalFunctionOperatorArguments,operatorComposesWithOriginal:!0,originalFDefinition:e.functionChild[0].stateValues.fDefinitions[a]};return{setValue:{fDefinitions:t}}}}if(0===e.functionChild.length){if(0===e.mathChild.length){let t={};for(let n of r)t[n]={functionType:"formula",formula:"_",variables:e.variables.map((e=>e.tree)),nInputs:e.nInputs,nOutputs:e.nOutputs,domain:e.domain};return{setValue:{fDefinitions:t}}}throw Error("function operator with math child not implemented yet")}{let t={};for(let a of r)t[a]={functionType:"functionOperator",componentType:n,nOutputs:e.nOutputs,functionOperatorArguments:e.numericalFunctionOperatorArguments,operatorComposesWithOriginal:!1,originalFDefinition:e.functionChild[0].stateValues.fDefinitions[a]};return{setValue:{fDefinitions:t}}}}};let r=t.allMinima.returnDependencies;t.allMinima.returnDependencies=function(e){let t=r(e);return delete t.functionChild,t};let a=t.allMaxima.returnDependencies;return t.allMaxima.returnDependencies=function(e){let t=a(e);return delete t.functionChild,t},t}}class ClampFunction extends FunctionOperator{static componentType="clampFunction";static createAttributesObject(){let e=super.createAttributesObject();return e.lowerValue={createComponentOfType:"number",createStateVariable:"lowerValue",defaultValue:0,public:!0},e.upperValue={createComponentOfType:"number",createStateVariable:"upperValue",defaultValue:1,public:!0},e}static returnStateVariableDefinitions({numerics:e}){let t=super.returnStateVariableDefinitions({numerics:e});return t.numericalFunctionOperator={additionalStateVariablesDefined:["numericalFunctionOperatorArguments"],returnDependencies:()=>({lowerValue:{dependencyType:"stateVariable",variableName:"lowerValue"},upperValue:{dependencyType:"stateVariable",variableName:"upperValue"}}),definition:function({dependencyValues:e}){return{setValue:{numericalFunctionOperator:functionOperatorDefinitions.clampFunction(e.lowerValue,e.upperValue),numericalFunctionOperatorArguments:[e.lowerValue,e.upperValue]}}}},t.symbolicFunctionOperator={returnDependencies:()=>({numericalFunctionOperator:{dependencyType:"stateVariable",variableName:"numericalFunctionOperator"}}),definition:({dependencyValues:e})=>({setValue:{symbolicFunctionOperator:t=>me$3.fromAst(e.numericalFunctionOperator(t.evaluate_to_constant()))}})},t}}class WrapFunctionPeriodic extends FunctionOperator{static componentType="wrapFunctionPeriodic";static createAttributesObject(){let e=super.createAttributesObject();return e.lowerValue={createComponentOfType:"number",createStateVariable:"lowerValue",defaultValue:0,public:!0},e.upperValue={createComponentOfType:"number",createStateVariable:"upperValue",defaultValue:1,public:!0},e}static returnStateVariableDefinitions({numerics:e}){let t=super.returnStateVariableDefinitions({numerics:e});return t.numericalFunctionOperator={additionalStateVariablesDefined:["numericalFunctionOperatorArguments"],returnDependencies:()=>({lowerValue:{dependencyType:"stateVariable",variableName:"lowerValue"},upperValue:{dependencyType:"stateVariable",variableName:"upperValue"}}),definition:function({dependencyValues:e}){return{setValue:{numericalFunctionOperator:functionOperatorDefinitions.wrapFunctionPeriodic(e.lowerValue,e.upperValue),numericalFunctionOperatorArguments:[e.lowerValue,e.upperValue]}}}},t.symbolicFunctionOperator={returnDependencies:()=>({numericalFunctionOperator:{dependencyType:"stateVariable",variableName:"numericalFunctionOperator"}}),definition:({dependencyValues:e})=>({setValue:{symbolicFunctionOperator:t=>me$3.fromAst(e.numericalFunctionOperator(t.evaluate_to_constant()))}})},t}}class Derivative extends FunctionOperator{static componentType="derivative";static createAttributesObject(){let e=super.createAttributesObject();return e.derivVariables={createComponentOfType:"variables"},e}static returnStateVariableDefinitions({numerics:e}){let t=super.returnStateVariableDefinitions({numerics:e});return t.operatorBasedOnFormulaIfAvailable={returnDependencies:()=>({}),definition:()=>({setValue:{operatorBasedOnFormulaIfAvailable:!0}})},t.operatorComposesWithOriginal={returnDependencies:()=>({}),definition:()=>({setValue:{operatorComposesWithOriginal:!1}})},t.haveFunctionChild={returnDependencies:()=>({functionChild:{dependencyType:"child",childGroups:["functions"]}}),definition:({dependencyValues:e})=>({setValue:{haveFunctionChild:e.functionChild.length>0}})},t.nInputs={defaultValue:1,hasEssential:!0,public:!0,shadowingInstructions:{createComponentOfType:"integer"},stateVariablesDeterminingDependencies:["haveFunctionChild"],returnDependencies({stateValues:e}){let t={nInputsAttr:{dependencyType:"attributeComponent",attributeName:"nInputs",variableNames:["value"]},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["nInputs"]},variablesAttr:{dependencyType:"attributeComponent",attributeName:"variables",variableNames:["nComponents"]}};return e.haveFunctionChild||(t.derivVariablesAttr={dependencyType:"attributeComponent",attributeName:"derivVariables",variableNames:["variables"]}),t},definition({dependencyValues:e}){if(null!==e.nInputsAttr){let t=e.nInputsAttr.stateValues.value;return t>=0||(t=1),{setValue:{nInputs:t}}}if(null!==e.variablesAttr)return{setValue:{nInputs:Math.max(1,e.variablesAttr.stateValues.nComponents)}};if(e.functionChild.length>0)return{setValue:{nInputs:e.functionChild[0].stateValues.nInputs}};if(null!==e.derivVariablesAttr){let t=[...new Set(e.derivVariablesAttr.stateValues.variables.map((e=>e.subscripts_to_strings().tree)))].length;return{setValue:{nInputs:t}}}return{useEssentialOrDefaultValue:{nInputs:!0}}}},t.variables={isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"variable"},entryPrefixes:["variable"],returnArraySizeDependencies:()=>({nInputs:{dependencyType:"stateVariable",variableName:"nInputs"}}),returnArraySize:({dependencyValues:e})=>[e.nInputs],stateVariablesDeterminingDependencies:["haveFunctionChild"],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={variablesAttr:{dependencyType:"attributeComponent",attributeName:"variables",variableNames:["variables"]},parentVariableForChild:{dependencyType:"parentStateVariable",variableName:"variableForChild"},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},haveFunctionChild:{dependencyType:"stateVariable",variableName:"haveFunctionChild"}},r={};if(t.haveFunctionChild)for(let t of e)r[t]={functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["variable"+(Number(t)+1)]}};else n.derivVariablesAttr={dependencyType:"attributeComponent",attributeName:"derivVariables",variableNames:["variables"]};return{globalDependencies:n,dependenciesByKey:r}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arraySize:n,arrayKeys:r,usedDefault:a}){if(null!==e.variablesAttr){let t=e.variablesAttr.stateValues.variables;return{setValue:{variables:returnNVariables(n[0],t)}}}if(e.haveFunctionChild){let e={};for(let n of r)e[n]=t[n].functionChild[0].stateValues["variable"+(Number(n)+1)];return{setValue:{variables:e}}}if(null!==e.derivVariablesAttr){let t=[],r=[];for(let n of e.derivVariablesAttr.stateValues.variables){let e=n.subscripts_to_strings().tree;r.includes(e)||(t.push(n),r.push(e))}return{setValue:{variables:returnNVariables(n[0],t)}}}return e.parentVariableForChild&&!a.parentVariableForChild?{setValue:{variables:Array(n[0]).fill(e.parentVariableForChild)}}:{setValue:{variables:returnNVariables(n[0],[])}}}},t.nDerivatives={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({derivVariablesAttr:{dependencyType:"attributeComponent",attributeName:"derivVariables",variableNames:["nComponents"]}}),definition:({dependencyValues:e})=>null!==e.derivVariablesAttr?{setValue:{nDerivatives:e.derivVariablesAttr.stateValues.nComponents}}:{setValue:{nDerivatives:1}}},t.derivVariables={isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"variable"},entryPrefixes:["derivVariable"],returnArraySizeDependencies:()=>({nDerivatives:{dependencyType:"stateVariable",variableName:"nDerivatives"}}),returnArraySize:({dependencyValues:e})=>[e.nDerivatives],returnArrayDependenciesByKey:()=>({globalDependencies:{derivVariablesAttr:{dependencyType:"attributeComponent",attributeName:"derivVariables",variableNames:["variables"]},variable1:{dependencyType:"stateVariable",variableName:"variable1"}}}),arrayDefinitionByKey:({globalDependencyValues:e})=>null!==e.derivVariablesAttr?{setValue:{derivVariables:e.derivVariablesAttr.stateValues.variables}}:{setValue:{derivVariables:{0:e.variable1}}}},t.formulaOperator={returnDependencies:()=>({derivVariables:{dependencyType:"stateVariable",variableName:"derivVariables"}}),definition:({dependencyValues:e})=>({setValue:{formulaOperator:function(t){let n=t.subscripts_to_strings();for(let t of e.derivVariables)n=n.derivative(t.subscripts_to_strings().tree);return n.strings_to_subscripts()}}})},t.numericalFunctionOperator={returnDependencies:()=>({functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["returnNumericalDerivatives"],variablesOptional:!0},derivVariables:{dependencyType:"stateVariable",variableName:"derivVariables"}}),additionalStateVariablesDefined:["returnNumericalDerivatives"],definition:function({dependencyValues:e}){if(0===e.functionChild.length||!e.functionChild[0].stateValues.returnNumericalDerivatives)return{setValue:{numericalFunctionOperator:e=>NaN,returnNumericalDerivatives:null}};return{setValue:{numericalFunctionOperator:e.functionChild[0].stateValues.returnNumericalDerivatives(e.derivVariables),returnNumericalDerivatives:function(t){let n=[...e.derivVariables,...t];return e.functionChild[0].stateValues.returnNumericalDerivatives(n)}}}}},t.numericalFunctionOperatorArguments={returnDependencies:()=>({functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["numericalDerivativesDefinition"],variablesOptional:!0},derivVariables:{dependencyType:"stateVariable",variableName:"derivVariables"}}),additionalStateVariablesDefined:["numericalDerivativesDefinition"],definition:function({dependencyValues:e}){if(0===e.functionChild.length||!e.functionChild[0].stateValues.numericalDerivativesDefinition)return{setValue:{numericalFunctionOperatorArguments:[],numericalDerivativesDefinition:{}}};let t=e.functionChild[0].stateValues.numericalDerivativesDefinition,n={...t};return n.additionalDerivVariables?n.additionalDerivVariables=[...e.derivVariables,...n.additionalDerivVariables]:n.additionalDerivVariables=[...e.derivVariables],{setValue:{numericalFunctionOperatorArguments:[t,e.derivVariables],numericalDerivativesDefinition:n}}}},t.symbolicFunctionOperator={returnDependencies:()=>({numericalFunctionOperator:{dependencyType:"stateVariable",variableName:"numericalFunctionOperator"}}),definition:({dependencyValues:e})=>({setValue:{symbolicFunctionOperator:t=>me$3.fromAst(e.numericalFunctionOperator(t.evaluate_to_constant()))}})},t}}var FunctionOperators=Object.freeze({__proto__:null,ClampFunction:ClampFunction,WrapFunctionPeriodic:WrapFunctionPeriodic,Derivative:Derivative});class TextBaseOperatorOfMath extends Text{static componentType="_textOperatorOfMath";static rendererType="text";static returnChildGroups(){return[{group:"maths",componentTypes:["math"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=this;return e.value={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]}}),definition:function({dependencyValues:e}){return{setValue:{value:t.applyTextOperator(e.mathChildren.map((e=>e.stateValues.value)))}}}},e}}class ExtractMathOperator extends TextBaseOperatorOfMath{static componentType="extractMathOperator";static applyTextOperator(e){return 0===e.length?"":1!==e.length?(console.warn("MathOperator requires exactly one math child"),""):Array.isArray(e[0].tree)?e[0].tree[0]:""}}var TextOperatorsOfMath=Object.freeze({__proto__:null,ExtractMathOperator:ExtractMathOperator});class Extremum extends BaseComponent{static componentType="extremum";static rendererType=void 0;static createAttributesObject(){let e=super.createAttributesObject();return e.location={createComponentOfType:"math"},e.value={createComponentOfType:"math"},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({childrenRegex:/s+(.*s)?/,replacementFunction:function({matchedChildren:e}){let t=returnBreakStringsSugarFunction({childrenToComponentFunction:e=>({componentType:"math",children:e}),mustStripOffOuterParentheses:!0}),n=t({matchedChildren:e});if(!n.success&&1===e.length)return{success:!0,newAttributes:{value:{component:{componentType:"math",children:e}}}};if(n.success){if(1===n.newChildren.length)return{success:!0,newAttributes:{value:{component:n.newChildren[0]}}};if(2===n.newChildren.length){let e=n.newChildren[0],t=n.newChildren[1],r={location:{component:e},value:{component:t}};return(0===e.children.length||1===e.children.length&&"string"==typeof e.children[0]&&""===e.children[0].trim())&&delete r.location,(0===t.children.length||1===t.children.length&&"string"==typeof t.children[0]&&""===t.children[0].trim())&&delete r.value,{success:!0,newAttributes:r}}return{success:!1}}return n}}),e}static returnChildGroups(){return[{group:"points",componentTypes:["point"]}]}static returnStateVariableDefinitions({numerics:e}){let t=super.returnStateVariableDefinitions({numerics:e}),n=this;return t.value={public:!0,shadowingInstructions:{createComponentOfType:"math"},defaultValue:null,hasEssential:!0,additionalStateVariablesDefined:[{variableName:"location",public:!0,shadowingInstructions:{createComponentOfType:"math"},defaultValue:null,hasEssential:!0}],returnDependencies:()=>({extremumChild:{dependencyType:"child",childGroups:["points"],variableNames:["nDimensions","xs"]},location:{dependencyType:"attributeComponent",attributeName:"location",variableNames:["value"]},value:{dependencyType:"attributeComponent",attributeName:"value",variableNames:["value"]}}),definition:function({dependencyValues:e}){let t,r;if(e.extremumChild.length>0){let a=e.extremumChild[0];2!==a.stateValues.nDimensions?(console.log("Cannot determine "+n.componentType+" from a point that isn't 2D"),t=null,r=null):(t=a.stateValues.xs[0],r=a.stateValues.xs[1])}else null!==e.location&&(t=e.location.stateValues.value),null!==e.value&&(r=e.value.stateValues.value);let a={},i={},s=!1,o=!1;void 0===t?(i.location=!0,o=!0):(a.location=t,s=!0),void 0===r?(i.value=!0,o=!0):(a.value=r,s=!0);let l={};return s&&(l.setValue=a),o&&(l.useEssentialOrDefaultValue=i),l}},t}}class Extrema extends BaseComponent{static componentType="extrema";static rendererType=void 0;static componentTypeSingular="extremum";static get componentTypeCapitalized(){return this.componentType.charAt(0).toUpperCase()+this.componentType.slice(1)}static returnSugarInstructions(){let e=super.returnSugarInstructions(),t=this;return e.push({replacementFunction:function({matchedChildren:e}){let n=breakEmbeddedStringsIntoParensPieces({componentList:e});return!0!==n.success?{success:!1}:{success:!0,newChildren:n.pieces.map((function(e){return e.length>1||"string"==typeof e[0]?{componentType:t.componentTypeSingular,children:e}:e[0]}))}}}),e}static returnChildGroups(){return[{group:"extrema",componentTypes:[this.componentTypeSingular]},{group:"points",componentTypes:["point"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=this;return e["n"+t.componentTypeCapitalized]={additionalStateVariablesDefined:["childIdentities"],returnDependencies:()=>({children:{dependencyType:"child",childGroups:["extrema","points"]}}),definition:function({dependencyValues:e}){return{setValue:{["n"+t.componentTypeCapitalized]:e.children.length,childIdentities:e.children}}}},e[t.componentType]={isArray:!0,nDimensions:2,entryPrefixes:[t.componentTypeSingular,t.componentTypeSingular+"Locations",t.componentTypeSingular+"Location",t.componentTypeSingular+"Values",t.componentTypeSingular+"Value"],stateVariablesDeterminingDependencies:["childIdentities"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:n,arraySize:r}){if([t.componentTypeSingular,t.componentTypeSingular+"Location",t.componentTypeSingular+"Value"].includes(e)){let a=Number(n)-1;return Number.isInteger(a)&&a>=0&&(!r||at+",0")):["0,0"]:e===t.componentTypeSingular+"Values"?""!==n?[]:r?Array.from(Array(r[0]),((e,t)=>t+",1")):["0,1"]:[]},arrayVarNameFromArrayKey(e){let[n,r]=e.split(",");return"0"===r?t.componentTypeSingular+"Location"+(Number(n)+1):t.componentTypeSingular+"Value"+(Number(n)+1)},arrayVarNameFromPropIndex(e,n){if(n===t.componentType){if(1===e.length)return t.componentTypeSingular+e[0];{let n=Number(e[0]);if(Number.isInteger(n)&&n>0){if(1===e[1])return t.componentTypeSingular+"Location"+n;if(2===e[1])return t.componentTypeSingular+"Value"+n}return null}}if(n===t.componentTypeSingular+"Locations")return t.componentTypeSingular+"Location"+e[0];if(n===t.componentTypeSingular+"Values")return t.componentTypeSingular+"Value"+e[0];let r=t.componentTypeSingular.length;if(n.slice(0,r)===t.componentTypeSingular){let a=Number(n.slice(r));if(Number.isInteger(a)&&a>0){if(1===e[0])return t.componentTypeSingular+"Location"+a;if(2===e[0])return t.componentTypeSingular+"Value"+a}}return null},returnArraySizeDependencies:()=>({nChildren:{dependencyType:"stateVariable",variableName:"n"+t.componentTypeCapitalized}}),returnArraySize:({dependencyValues:e})=>[e.nChildren,2],returnArrayDependenciesByKey({arrayKeys:e,stateValues:n}){let r={};for(let a of e){let e,[i,s]=a.split(",");e=n.childIdentities[i].componentType===t.componentTypeSingular?0===Number(s)?"location":"value":"x"+(Number(s)+1),r[a]={child:{dependencyType:"child",childGroups:["extrema","points"],variableNames:[e],childIndices:[i]}}}return{dependenciesByKey:r}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:n}){let r={};for(let t of n){let n=e[t].child[0];if(n){let e=t.split(",")[1],a=0===Number(e)?"location":"value";a in n.stateValues?r[t]=n.stateValues[a]:r[t]=n.stateValues["x"+(Number(e)+1)]}}return{setValue:{[t.componentType]:r}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:n}){let r=[];for(let a in e[t.componentType])r.push({setDependency:n[a].extremumChild,desiredValue:e[t.componentType][a],childIndex:0,variableIndex:0});return{success:!0,instructions:r}}},e}}var Extrema$1=Object.freeze({__proto__:null,Extremum:Extremum,Extrema:Extrema});class InlineRenderInlineChildren extends InlineComponent{static componentType="_inlineRenderInlineChildren";static renderChildren=!0;static includeBlankStringChildren=!0;static beginTextDelimiter="";static endTextDelimiter="";static returnChildGroups(){return[{group:"inlines",componentTypes:["_inline"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=this;return e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["inlines"],variableNames:["text"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let n="";for(let t of e.inlineChildren)"object"!=typeof t?n+=t.toString():"string"==typeof t.stateValues.text?n+=t.stateValues.text:n+=" ";return n=t.beginTextDelimiter+n+t.endTextDelimiter,{setValue:{text:n}}}},e}}class Em extends InlineRenderInlineChildren{static componentType="em"}class Alert extends InlineRenderInlineChildren{static componentType="alert"}class Q$2 extends InlineRenderInlineChildren{static componentType="q";static beginTextDelimiter='"';static endTextDelimiter='"'}class SQ extends InlineRenderInlineChildren{static componentType="sq";static beginTextDelimiter="'";static endTextDelimiter="'"}class Term extends InlineRenderInlineChildren{static componentType="term";static rendererType="alert"}class C$2 extends InlineRenderInlineChildren{static componentType="c"}class Tag extends InlineRenderInlineChildren{static componentType="tag";static rendererType="tag";static beginTextDelimiter="<";static endTextDelimiter=">"}class Tage extends InlineRenderInlineChildren{static componentType="tage";static rendererType="tag";static beginTextDelimiter="<";static endTextDelimiter="/>";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.selfClosed={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{selfClosed:!0}})},e}}class Attr extends InlineRenderInlineChildren{static componentType="attr";static rendererType="c"}var ParagraphMarkup=Object.freeze({__proto__:null,Em:Em,Alert:Alert,Q:Q$2,SQ:SQ,Term:Term,C:C$2,Tag:Tag,Tage:Tage,Attr:Attr});class SingleCharacter extends InlineComponent{static componentType="_singleCharacterInline";static unicodeCharacter="";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({}),definition:()=>({setValue:{text:this.unicodeCharacter}})},e}}class Ndash extends SingleCharacter{static componentType="ndash";static unicodeCharacter="–"}class Mdash extends SingleCharacter{static componentType="mdash";static unicodeCharacter="—"}class NBSP extends SingleCharacter{static componentType="nbsp";static unicodeCharacter=" "}class Ellipsis extends SingleCharacter{static componentType="ellipsis";static unicodeCharacter="…"}var SingleCharacterComponents=Object.freeze({__proto__:null,Ndash:Ndash,Mdash:Mdash,NBSP:NBSP,Ellipsis:Ellipsis});class BlockComponent extends BaseComponent{static componentType="_block"}function returnDefaultFeedbackDefinitions(){return{numericalerror:"Credit reduced because numbers in your answer weren't quite right. Did you round too much?",goodjob:"Good job!",onesignerror:"Credit reduced because it appears that you made a sign error.",twosignerrors:"Credit reduced because it appears that you made two sign errors."}}function returnFeedbackDefinitionStateVariables(){let e={setupChildren:{returnDependencies:()=>({setupChildren:{dependencyType:"child",childGroups:["setups"],proceedIfAllChildrenNotMatched:!0}}),definition:({dependencyValues:e})=>({setValue:{setupChildren:e.setupChildren}})}};return e.feedbackDefinitions={stateVariablesDeterminingDependencies:["setupChildren"],returnDependencies({stateValues:e}){let t={ancestorWithFeedback:{dependencyType:"ancestor",variableNames:["feedbackDefinitions"]},setupChildren:{dependencyType:"child",childGroups:["setups"],proceedIfAllChildrenNotMatched:!0}};for(let n of e.setupChildren)t[`feedbackDefinitionsOf${n.componentName}`]={dependencyType:"child",parentName:n.componentName,childGroups:["feedbackDefinitions"],variableNames:["value"]};return t},definition({dependencyValues:e}){let t,n={};e.ancestorWithFeedback&&(t=e.ancestorWithFeedback.stateValues.feedbackDefinitions),t||(t=returnDefaultFeedbackDefinitions()),Object.assign(n,t);let r=[];for(let t of e.setupChildren)r.push(...e[`feedbackDefinitionsOf${t.componentName}`]);for(let e of r)Object.assign(n,e.stateValues.value);return{setValue:{feedbackDefinitions:n}}}},e}class SectioningComponent extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{submitAllAnswers:this.submitAllAnswers.bind(this),revealSection:this.revealSection.bind(this),closeSection:this.closeSection.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="_sectioningComponent";static renderChildren=!0;static includeBlankStringChildren=!0;static createsVariants=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.aggregateScores={createComponentOfType:"boolean",createStateVariable:"aggregateScores",defaultValue:!1,public:!0},e.weight={createComponentOfType:"number",createStateVariable:"weight",defaultValue:1,public:!0},e.sectionWideCheckWork={createComponentOfType:"boolean",createStateVariable:"sectionWideCheckWork",defaultValue:!1,public:!0},e.submitLabel={createComponentOfType:"text",createStateVariable:"submitLabel",defaultValue:"Check Work",public:!0,forRenderer:!0},e.submitLabelNoCorrectness={createComponentOfType:"text",createStateVariable:"submitLabelNoCorrectness",defaultValue:"Submit Response",public:!0,forRenderer:!0},e.boxed={createComponentOfType:"boolean",createStateVariable:"boxed",defaultValue:!1,public:!0,forRenderer:!0},e.suppressAutoName={createComponentOfType:"boolean",createStateVariable:"suppressAutoName",defaultValue:!1,public:!0},e.suppressAutoNumber={createComponentOfType:"boolean",createStateVariable:"suppressAutoNumber",defaultValue:!1,public:!0},e.includeAutoName={createComponentOfType:"boolean",createStateVariable:"includeAutoName",defaultValue:!1,public:!0},e.includeAutoNumber={createComponentOfType:"boolean",createStateVariable:"includeAutoNumber",defaultValue:!1,public:!0},e.includeAutoNameNumberIfNoTitle={createComponentOfType:"boolean",createStateVariable:"includeAutoNameNumberIfNoTitle",defaultValue:!0,public:!0},e.includeParentNumber={createComponentOfType:"boolean",createStateVariable:"includeParentNumber",defaultValue:!1,public:!0},e.level={createComponentOfType:"integer"},e}static returnChildGroups(){return[{group:"variantControls",componentTypes:["variantControl"]},{group:"titles",componentTypes:["title"]},{group:"setups",componentTypes:["setup"]},{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnStyleDefinitionStateVariables();Object.assign(e,t);let n=returnFeedbackDefinitionStateVariables();return Object.assign(e,n),e.enumeration={additionalStateVariablesDefined:[{variableName:"sectionNumber",public:!0,shadowingInstructions:{createComponentOfType:"text"}}],returnDependencies:()=>({countAmongSiblings:{dependencyType:"countAmongSiblingsOfSameType"},sectionAncestor:{dependencyType:"ancestor",componentType:"_sectioningComponent",variableNames:["enumeration"]},includeParentNumber:{dependencyType:"stateVariable",variableName:"includeParentNumber"}}),definition({dependencyValues:e}){let t=[];return e.includeParentNumber&&e.sectionAncestor&&t.push(...e.sectionAncestor.stateValues.enumeration),t.push(e.countAmongSiblings),{setValue:{enumeration:t,sectionNumber:t.join(".")}}}},e.sectionName={returnDependencies:()=>({}),definition:()=>({setValue:{sectionName:"Section"}})},e.titleChildName={forRenderer:!0,returnDependencies:()=>({titleChild:{dependencyType:"child",childGroups:["titles"]}}),definition({dependencyValues:e}){let t=null;return e.titleChild.length>0&&(t=e.titleChild[e.titleChild.length-1].componentName),{setValue:{titleChildName:t}}}},e.childIndicesToRender={returnDependencies:()=>({titleChildren:{dependencyType:"child",childGroups:["titles"]},allChildren:{dependencyType:"child",childGroups:["anything","variantControls","titles","setups"]},titleChildName:{dependencyType:"stateVariable",variableName:"titleChildName"}}),definition({dependencyValues:e}){let t=[],n=e.titleChildren.map((e=>e.componentName));for(let[r,a]of e.allChildren.entries())"object"==typeof a&&n.includes(a.componentName)&&a.componentName!==e.titleChildName||t.push(r);return{setValue:{childIndicesToRender:t}}}},e.title={additionalStateVariablesDefined:[{variableName:"titlePrefix",forRenderer:!0,alwaysUpdateRenderer:!0}],public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,alwaysUpdateRenderer:!0,returnDependencies:({sharedParameters:e})=>({titleChild:{dependencyType:"child",childGroups:["titles"],variableNames:["text"]},sectionName:{dependencyType:"stateVariable",variableName:"sectionName"},sectionNumber:{dependencyType:"stateVariable",variableName:"sectionNumber"},includeAutoName:{dependencyType:"stateVariable",variableName:"includeAutoName"},includeAutoNumber:{dependencyType:"stateVariable",variableName:"includeAutoNumber"},prerender:{dependencyType:"value",value:e.prerender},includeAutoNameNumberIfNoTitle:{dependencyType:"stateVariable",variableName:"includeAutoNameNumberIfNoTitle"}}),definition({dependencyValues:e}){let t="",n="";const r=e.titleChild.length>0;let a=(e.includeAutoNumber||!r&&e.includeAutoNameNumberIfNoTitle)&&!e.prerender,i=e.includeAutoName||!r&&e.includeAutoNameNumberIfNoTitle;return a?(i&&(t=e.sectionName+" "),t+=e.sectionNumber):i&&(t=e.sectionName),r?(t&&(e.includeAutoName?t+=": ":t+=". "),n=e.titleChild[e.titleChild.length-1].stateValues.text):n=t,{setValue:{title:n,titlePrefix:t}}}},e.containerTag={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{containerTag:"section"}})},e.level={forRenderer:!0,returnDependencies:()=>({ancestorLevel:{dependencyType:"ancestor",componentType:"_sectioningComponent",variableNames:["level"]},levelAttr:{dependencyType:"attributeComponent",attributeName:"level",variableNames:["value"]}}),definition({dependencyValues:e}){let t=e.levelAttr?.stateValues.value;return t>0||(t=(e.ancestorLevel?.stateValues.level||0)+1),{setValue:{level:t}}}},e.viewedSolution={defaultValue:!1,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{viewedSolution:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"viewedSolution",value:e.viewedSolution}]})},e.scoredDescendants={returnDependencies:()=>({scoredDescendants:{dependencyType:"descendant",componentTypes:["_sectioningComponent","answer","setup"],variableNames:["scoredDescendants","aggregateScores","weight"],recurseToMatchedChildren:!1,variablesOptional:!0}}),definition({dependencyValues:e}){let t=[];for(let n of e.scoredDescendants)"setup"!==n.componentType&&(n.stateValues.aggregateScores||void 0===n.stateValues.scoredDescendants?t.push(n):t.push(...n.stateValues.scoredDescendants));return{setValue:{scoredDescendants:t}}}},e.answerDescendants={returnDependencies:()=>({answerDescendants:{dependencyType:"descendant",componentTypes:["answer"],variableNames:["justSubmitted"],recurseToMatchedChildren:!1}}),definition:({dependencyValues:e})=>({setValue:{answerDescendants:e.answerDescendants}})},e.justSubmitted={forRenderer:!0,returnDependencies:()=>({answerDescendants:{dependencyType:"stateVariable",variableName:"answerDescendants"}}),definition:({dependencyValues:e})=>({setValue:{justSubmitted:e.answerDescendants.every((e=>e.stateValues.justSubmitted))}})},e.showCorrectness={forRenderer:!0,returnDependencies:()=>({showCorrectnessFlag:{dependencyType:"flag",flagName:"showCorrectness"}}),definition:({dependencyValues:e})=>({setValue:{showCorrectness:!1!==e.showCorrectnessFlag}})},e.displayDigitsForCreditAchieved={returnDependencies:()=>({}),definition:()=>({setValue:{displayDigitsForCreditAchieved:3}})},e.creditAchieved={public:!0,shadowingInstructions:{createComponentOfType:"number",addAttributeComponentsShadowingStateVariables:{displayDigits:{stateVariableToShadow:"displayDigitsForCreditAchieved"}}},forRenderer:!0,defaultValue:0,hasEssential:!0,additionalStateVariablesDefined:[{variableName:"percentCreditAchieved",public:!0,shadowingInstructions:{createComponentOfType:"number",addAttributeComponentsShadowingStateVariables:{displayDigits:{stateVariableToShadow:"displayDigitsForCreditAchieved"}}},defaultValue:0,hasEssential:!0}],stateVariablesDeterminingDependencies:["aggregateScores","scoredDescendants"],returnDependencies({stateValues:e}){let t={aggregateScores:{dependencyType:"stateVariable",variableName:"aggregateScores"}};if(e.aggregateScores){t.scoredDescendants={dependencyType:"stateVariable",variableName:"scoredDescendants"};for(let[n,r]of e.scoredDescendants.entries())t["creditAchieved"+n]={dependencyType:"stateVariable",componentName:r.componentName,variableName:"creditAchieved"}}return t},definition({dependencyValues:e}){if(!e.aggregateScores)return{setValue:{creditAchieved:0,percentCreditAchieved:0}};let t,n=0,r=0;for(let[t,a]of e.scoredDescendants.entries()){let i=a.stateValues.weight;n+=e["creditAchieved"+t]*i,r+=i}return t=r>0?n/r:1,{setValue:{creditAchieved:t,percentCreditAchieved:100*t}}}},e.creditAchievedIfSubmit={defaultValue:0,stateVariablesDeterminingDependencies:["aggregateScores","scoredDescendants"],returnDependencies({stateValues:e}){let t={aggregateScores:{dependencyType:"stateVariable",variableName:"aggregateScores"}};if(e.aggregateScores){t.scoredDescendants={dependencyType:"stateVariable",variableName:"scoredDescendants"};for(let[n,r]of e.scoredDescendants.entries())t["creditAchievedIfSubmit"+n]={dependencyType:"stateVariable",componentName:r.componentName,variableName:"creditAchievedIfSubmit"}}return t},definition({dependencyValues:e}){if(!e.aggregateScores)return{setValue:{creditAchievedIfSubmit:0}};let t=0,n=0;for(let[r,a]of e.scoredDescendants.entries()){let i=a.stateValues.weight;t+=e["creditAchievedIfSubmit"+r]*i,n+=i}return{setValue:{creditAchievedIfSubmit:t/n}}}},e.generatedVariantInfo={additionalStateVariablesDefined:["isVariantComponent"],returnDependencies:({sharedParameters:e,componentInfoObjects:t})=>({variantSeed:{dependencyType:"value",value:e.variantSeed},variantIndex:{dependencyType:"value",value:e.variantIndex},variantName:{dependencyType:"value",value:e.variantName},variantDescendants:{dependencyType:"descendant",componentTypes:Object.keys(t.componentTypesCreatingVariants),variableNames:["isVariantComponent","generatedVariantInfo"],recurseToMatchedChildren:!1,variablesOptional:!0,includeNonActiveChildren:!0,ignoreReplacementsOfEncounteredComposites:!0}}),definition({dependencyValues:e,componentName:t}){let n={};e.variantName?(n.index=e.variantIndex,n.name=e.variantName):n.seed=e.variantSeed,n.meta={createdBy:t};let r=n.subvariants=[];for(let t of e.variantDescendants)t.stateValues.isVariantComponent?r.push(t.stateValues.generatedVariantInfo):t.stateValues.generatedVariantInfo&&r.push(...t.stateValues.generatedVariantInfo.subvariants);return{setValue:{generatedVariantInfo:n,isVariantComponent:!0}}}},e.collapsible={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{collapsible:!1}})},e.open={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,defaultValue:!0,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{open:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"open",value:e.open}]})},e.createSubmitAllButton={forRenderer:!0,additionalStateVariablesDefined:[{variableName:"suppressAnswerSubmitButtons",forRenderer:!0}],returnDependencies:()=>({sectionWideCheckWork:{dependencyType:"stateVariable",variableName:"sectionWideCheckWork"},aggregateScores:{dependencyType:"stateVariable",variableName:"aggregateScores"},sectionAncestor:{dependencyType:"ancestor",componentType:"_sectioningComponent",variableNames:["suppressAnswerSubmitButtons"]},documentAncestor:{dependencyType:"ancestor",componentType:"document",variableNames:["suppressAnswerSubmitButtons"]}}),definition({dependencyValues:e,componentName:t}){let n=!1,r=!1;return e.documentAncestor.stateValues.suppressAnswerSubmitButtons||e.sectionAncestor&&e.sectionAncestor.stateValues.suppressAnswerSubmitButtons?r=!0:e.sectionWideCheckWork&&(e.aggregateScores?(n=!0,r=!0):console.warn(`Cannot create submit all button for ${t} because it doesn't aggegrate scores`)),{setValue:{createSubmitAllButton:n,suppressAnswerSubmitButtons:r}}}},e.suppressCheckwork={forRenderer:!0,returnDependencies:()=>({autoSubmit:{dependencyType:"flag",flagName:"autoSubmit"}}),definition:({dependencyValues:e})=>({setValue:{suppressCheckwork:e.autoSubmit}})},e}async submitAllAnswers({actionId:e}){this.coreFunctions.requestRecordEvent({verb:"submitted",object:{componentName:this.componentName,componentType:this.componentType},result:{creditAchieved:await this.stateValues.creditAchievedIfSubmit}});for(let e of await this.stateValues.answerDescendants)await e.stateValues.justSubmitted||await this.coreFunctions.performAction({componentName:e.componentName,actionName:"submitAnswer"});this.coreFunctions.resolveAction({actionId:e})}async revealSection({actionId:e}){return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"open",value:!0}],overrideReadOnly:!0,actionId:e,event:{verb:"viewed",object:{componentName:this.componentName,componentType:this.componentType}}})}async closeSection({actionId:e}){return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"open",value:!1}],overrideReadOnly:!0,actionId:e,event:{verb:"closed",object:{componentName:this.componentName,componentType:this.componentType}}})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}static setUpVariant({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n}){if(!e.variants?.allPossibleVariants)return void setUpVariantSeedAndRng({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n,useSubpartVariantRng:!0});let r,a=e.variants.numberOfVariants,i=e.variants.desiredVariant;if(void 0!==i&&void 0!==i.index){let e=Number(i.index);if(Number.isFinite(e)){Number.isInteger(e)||(console.warn("Variant index "+i.index+" must be an integer"),e=Math.round(e));let t=(e-1)%a;t<0&&(t+=a),r=t+1}else console.warn("Variant index "+i.index+" must be a number"),r=1}if(void 0===r){let e=t.variantRng();r=Math.floor(e*a)+1}if(t.allPossibleVariants=e.variants.allPossibleVariants,t.allVariantNames=e.variants.allVariantNames,t.variantSeed=e.variants.allPossibleVariantSeeds[r-1],t.variantIndex=r,t.variantName=e.variants.allPossibleVariants[r-1],t.uniqueIndex=e.variants.allPossibleVariantUniqueIndices[r-1],t.variantRng=new t.rngClass(t.variantSeed),t.subpartVariantRng=new t.rngClass(t.variantSeed+"s"),i?.subvariants&&n)for(let e in i.subvariants){let t=i.subvariants[e],r=n[e];if(void 0===r)break;r.variants.desiredVariant=t}}static determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t}){return determineVariantsForSection({serializedComponent:e,componentInfoObjects:t})}static getUniqueVariant({serializedComponent:e,variantIndex:t,componentInfoObjects:n}){if(!e.variants.allPossibleVariants)return super.getUniqueVariant({serializedComponent:e,variantIndex:t,componentInfoObjects:n});let r=e.variants.allPossibleVariantUniqueIndices[t-1];if(void 0===r)return{success:!1};if(!e.variants.uniqueVariants)return{success:!0,desiredVariant:{index:t}};let a=getVariantsForDescendantsForUniqueVariants({variantIndex:r,serializedComponent:e,componentInfoObjects:n});return a.success?(e.variants.selectedUniqueVariant=!0,{success:!0,desiredVariant:{index:t,subvariants:a.desiredVariants}}):(console.log("Failed to get unique variant for section."),{success:!1})}}class Section extends SectioningComponent{static componentType="section";static rendererType="section";static createAttributesObject(){let e=super.createAttributesObject();return e.includeParentNumber.defaultValue=!0,e}}class Subsection extends Section{static componentType="subsection"}class Subsubsection extends Section{static componentType="subsubsection"}class Paragraphs extends SectioningComponent{static componentType="paragraphs";static rendererType="section";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.level.definition=()=>({setValue:{level:4}}),e.sectionName.definition=()=>({setValue:{sectionName:"Paragraphs"}}),e}}class Aside extends SectioningComponent{static componentType="aside";static rendererType="section";static createAttributesObject(){let e=super.createAttributesObject();return e.collapsible={createComponentOfType:"boolean",createStateVariable:"collapsible",defaultValue:!0,public:!0,forRenderer:!0},e.startOpen={createComponentOfType:"boolean",createStateVariable:"startOpen",defaultValue:!1},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return delete e.collapsible,e.open.returnDependencies=()=>({startOpen:{dependencyType:"stateVariable",variableName:"startOpen"}}),e.open.definition=({dependencyValues:e})=>({useEssentialOrDefaultValue:{open:{defaultValue:e.startOpen}}}),e.level.definition=()=>({setValue:{level:3}}),e.containerTag.definition=()=>({setValue:{containerTag:"aside"}}),e.sectionName.definition=()=>({setValue:{sectionName:"Aside"}}),e}}class Problem extends SectioningComponent{static componentType="problem";static rendererType="section";static createAttributesObject(){let e=super.createAttributesObject();return e.aggregateScores.defaultValue=!0,e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.sectionName.definition=()=>({setValue:{sectionName:"Problem"}}),e}}class Exercise extends Problem{static componentType="exercise";static rendererType="section";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.sectionName.definition=()=>({setValue:{sectionName:"Exercise"}}),e}}class Example extends SectioningComponent{static componentType="example";static rendererType="section";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.sectionName.definition=()=>({setValue:{sectionName:"Example"}}),e}}class StandinForFutureLayoutTag extends SectioningComponent{static componentType="standinForFutureLayoutTag";static rendererType="section";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.level.definition=()=>({setValue:{level:3}}),e.containerTag.definition=()=>({setValue:{containerTag:"aside"}}),e}}class externalContent extends SectioningComponent{static componentType="externalContent";static rendererType="section";static createAttributesObject(){let e=super.createAttributesObject();return e.includeAutoNameNumberIfNoTitle.defaultValue=!1,e}}var Sectioning=Object.freeze({__proto__:null,Section:Section,Subsection:Subsection,Subsubsection:Subsubsection,Paragraphs:Paragraphs,Aside:Aside,Problem:Problem,Exercise:Exercise,Example:Example,StandinForFutureLayoutTag:StandinForFutureLayoutTag,externalContent:externalContent});class Ol extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="ol";static rendererType="list";static renderChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.label={createComponentOfType:"text",createStateVariable:"label",defaultValue:null,public:!0,forRenderer:!0},e.level={createComponentOfType:"integer"},e}static returnChildGroups(){return[{group:"lis",componentTypes:["li"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numbered={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{numbered:!0}})},e.level={forRenderer:!0,returnDependencies:()=>({ancestorLevel:{dependencyType:"ancestor",componentType:"ol",variableNames:["level"]},levelAttr:{dependencyType:"attributeComponent",attributeName:"level",variableNames:["value"]}}),definition({dependencyValues:e}){let t=e.levelAttr?.stateValues.value;return t>0||(t=(e.ancestorLevel?.stateValues.level||0)+1),{setValue:{level:t}}}},e}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class Ul extends Ol{static componentType="ul";static rendererType="list";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numbered={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{numbered:!1}})},e}}class Li$1 extends BaseComponent{constructor(e){super(e),Object.assign(this.actions,{recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="li";static rendererType="list";static renderChildren=!0;static includeBlankStringChildren=!0;static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.item={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{item:!0}})},e}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}var Lists=Object.freeze({__proto__:null,Ol:Ol,Ul:Ul,Li:Li$1});class ODESystem extends InlineComponent{static componentType="odesystem";static rendererType="math";static createAttributesObject(){let e=super.createAttributesObject();return e.independentVariable={createComponentOfType:"variable",createStateVariable:"independentVariable",defaultValue:me$3.fromAst("t"),public:!0},e.initialIndependentVariableValue={createComponentOfType:"math",createStateVariable:"initialIndependentVariableValue",defaultValue:me$3.fromAst(0),public:!0},e.displayDigits={createComponentOfType:"integer",createStateVariable:"displayDigits",defaultValue:14,public:!0},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.padZeros={createComponentOfType:"boolean",createStateVariable:"padZeros",defaultValue:!1,public:!0},e.renderMode={createComponentOfType:"text",createStateVariable:"renderMode",defaultValue:"align",public:!0,forRenderer:!0},e.chunkSize={createComponentOfType:"number",createStateVariable:"chunkSize",defaultValue:10,public:!0},e.tolerance={createComponentOfType:"number",createStateVariable:"tolerance",defaultValue:1e-6,public:!0},e.maxIterations={createComponentOfType:"number",createStateVariable:"maxIterations",defaultValue:1e3,public:!0},e.hideInitialCondition={createComponentOfType:"boolean",createStateVariable:"hideInitialCondition",defaultValue:!1,public:!0},e.initialConditions={createComponentOfType:"mathList"},e.variables={createComponentOfType:"variables"},e.number={createComponentOfType:"boolean",createStateVariable:"number",defaultValue:!1,public:!0},e}static returnChildGroups(){return[{group:"rightHandSides",componentTypes:["rightHandSide"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.validIndependentVariable={returnDependencies:()=>({independentVarAttr:{dependencyType:"attributeComponent",attributeName:"independentVariable",variableNames:["validVariable"]}}),definition({dependencyValues:e}){let t=!0;return e.independentVarAttr&&(t=e.independentVarAttr.stateValues.validVariable),{setValue:{validIndependentVariable:t}}}},e.nDimensions={returnDependencies:()=>({rhsChildren:{dependencyType:"child",childGroups:["rightHandSides"],skipComponentNames:!0}}),definition:function({dependencyValues:e}){return{setValue:{nDimensions:e.rhsChildren.length},checkForActualChange:{nDimensions:!0}}}},e.variables={additionalStateVariablesDefined:[{variableName:"validVariables",isArray:!0,entryPrefixes:["validVar"]}],isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"variable"},entryPrefixes:["var"],returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey:()=>({globalDependencies:{nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},variables:{dependencyType:"attributeComponent",attributeName:"variables",variableNames:["variables","validVariables"]},independentVariable:{dependencyType:"stateVariable",variableName:"independentVariable"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t=[],n=[],r=e.nDimensions;null!==e.variables&&(t=e.variables.stateValues.variables,n=[...e.variables.stateValues.validVariables].slice(0,r));let a=returnNVariables(r,t);return a.some((t=>t.equals(e.independentVariable)))&&console.warn("Variables of odesystem must be different than independent variable."),n.length({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={rhsChild:{dependencyType:"child",childGroups:["rightHandSides"],variableNames:["value"],childIndices:[n]}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t)n[r]=e[r].rhsChild[0].stateValues.value;return{setValue:{rhss:n}}}},e.rhs={isAlias:!0,targetVariableName:"rhs1"},e.righthandside={isAlias:!0,targetVariableName:"rhs1"},e.righthandsides={isAlias:!0,targetVariableName:"rhss"},e.initialConditions={isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"math"},entryPrefixes:["initialCondition"],defaultValueByArrayKey:()=>me$3.fromAst(0),returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={initialConditionAttr:{dependencyType:"attributeComponent",attributeName:"initialConditions",variableNames:[`math${Number(n)+1}`]}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={},r={};for(let a of t){let t=!1;if(e[a].initialConditionAttr){let r=e[a].initialConditionAttr.stateValues[`math${Number(a)+1}`];void 0!==r&&(t=!0,n[a]=r)}t||(r[a]=!0)}let a={};return Object.keys(n).length>0&&(a.setValue={initialConditions:n}),Object.keys(r).length>0&&(a.useEssentialOrDefaultValue={initialConditions:r}),a}},e.initialCondition={isAlias:!0,targetVariableName:"initialCondition1"},e.equationTag={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,stateVariablesDeterminingDependencies:["number"],returnDependencies:({stateValues:e})=>e.number?{equationCounter:{dependencyType:"counter",counterName:"equation"}}:{},definition:({dependencyValues:e})=>void 0!==e.equationCounter?{setValue:{equationTag:String(e.equationCounter)}}:{setValue:{equationTag:null}}},e.latex={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},variables:{dependencyType:"stateVariable",variableName:"variables"},initialConditions:{dependencyType:"stateVariable",variableName:"initialConditions"},hideInitialCondition:{dependencyType:"stateVariable",variableName:"hideInitialCondition"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"},independentVariable:{dependencyType:"stateVariable",variableName:"independentVariable"},initialIndependentVariableValue:{dependencyType:"stateVariable",variableName:"initialIndependentVariableValue"},rhss:{dependencyType:"stateVariable",variableName:"rhss"},number:{dependencyType:"stateVariable",variableName:"number"},equationTag:{dependencyType:"stateVariable",variableName:"equationTag"}}),definition({dependencyValues:e,usedDefault:t}){let n={};e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(n.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(n.padToDigits=e.displayDigits));let r=[],a=e.independentVariable.toLatex();for(let i=0;i({latex:{dependencyType:"stateVariable",variableName:"latex"}}),definition:function({dependencyValues:e}){return{setValue:{latexWithInputChildren:[e.latex]}}}},e.numericalRHSf={additionalStateVariablesDefined:["numericalRHSfDefinitions"],returnDependencies:()=>({validIndependentVariable:{dependencyType:"stateVariable",variableName:"validIndependentVariable"},independentVariable:{dependencyType:"stateVariable",variableName:"independentVariable"},validVariables:{dependencyType:"stateVariable",variableName:"validVariables"},variables:{dependencyType:"stateVariable",variableName:"variables"},rhss:{dependencyType:"stateVariable",variableName:"rhss"}}),definition({dependencyValues:e}){let t=!0;e.validIndependentVariable||(console.warn("Can't define ODE RHS functions with invalid independent variable."),t=!1),e.validVariables.every((e=>e))||(console.warn("Can't define ODE RHS functions with an invalid variable."),t=!1);let n,r=e.independentVariable.subscripts_to_strings().tree,a=e.variables.map((e=>e.subscripts_to_strings().tree));a.includes(r)&&(console.warn("Can't define ODE RHS functions when independent variable is a dependent variable"),t=!1),[...new Set(a)].length!==a.length&&(console.warn("Can't define ODE RHS functions with duplicate dependent variable names"),t=!1);try{n=e.rhss.map((e=>e.subscripts_to_strings().f()))}catch(e){console.warn("Cannot define ODE RHS function. Error creating mathjs function"),t=!1}if(!t){let t=e.rhss.length;return{setValue:{numericalRHSf:()=>NaN,numericalRHSfDefinitions:Array(t).fill({})}}}return{setValue:{numericalRHSf:function(e,t){let i={[r]:e};Array.isArray(t)?t.forEach(((e,t)=>i[a[t]]=e)):i[a[0]]=t;try{return n.map((e=>e(i)))}catch(e){return NaN}},numericalRHSfDefinitions:e.rhss.map((e=>({functionType:"formula",formula:e,nInputs:a.length+1,variables:[r,...a]})))}}}},e.haveNumericalInitialConditions={additionalStateVariablesDefined:["t0","x0s"],returnDependencies:()=>({initialIndependentVariableValue:{dependencyType:"stateVariable",variableName:"initialIndependentVariableValue"},initialConditions:{dependencyType:"stateVariable",variableName:"initialConditions"}}),definition({dependencyValues:e}){let t=e.initialIndependentVariableValue.evaluate_to_constant(),n=e.initialConditions.map((e=>e.evaluate_to_constant())),r=Number.isFinite(t)&&n.every((e=>Number.isFinite(e)));return{setValue:{t0:t,x0s:n,haveNumericalInitialConditions:r}}}},e.numericalSolutions={isArray:!0,entryPrefixes:["numericalSolution"],public:!0,shadowingInstructions:{createComponentOfType:"function",addStateVariablesShadowingStateVariables:{fDefinitions:{stateVariableToShadow:"numericalSolutionFDefinitions"}}},createWorkspace:!0,returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey:()=>({globalDependencies:{nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},validIndependentVariable:{dependencyType:"stateVariable",variableName:"validIndependentVariable"},independentVariable:{dependencyType:"stateVariable",variableName:"independentVariable"},validVariables:{dependencyType:"stateVariable",variableName:"validVariables"},variables:{dependencyType:"stateVariable",variableName:"variables"},chunkSize:{dependencyType:"stateVariable",variableName:"chunkSize"},tolerance:{dependencyType:"stateVariable",variableName:"tolerance"},maxIterations:{dependencyType:"stateVariable",variableName:"maxIterations"},haveNumericalInitialConditions:{dependencyType:"stateVariable",variableName:"haveNumericalInitialConditions"},t0:{dependencyType:"stateVariable",variableName:"t0"},x0s:{dependencyType:"stateVariable",variableName:"x0s"},numericalRHSf:{dependencyType:"stateVariable",variableName:"numericalRHSf"}}}),arrayDefinitionByKey({globalDependencyValues:e,workspace:t,componentName:n}){let r={};if(t.calculatedNumericSolutions=[],t.endingNumericalValues=[],t.maxPossibleTime=void 0,!e.haveNumericalInitialConditions){for(let t=0;tNaN;return{setValue:{numericalSolutions:r}}}let a=e.t0,i=e.x0s,s=e.chunkSize,o=e.tolerance,l=e.numericalRHSf,u=e.maxIterations;for(let c=0;c=r)for(let e=r;e<=p;e++){let r=t.endingNumericalValues[e-1];void 0===r&&(r=i);let c=a+e*s,p=me$3.math.dopri(c,c+s,r,l,o,u);t.endingNumericalValues.push(p.y[p.y.length-1]),t.calculatedNumericSolutions.push(p.at.bind(p));let d=p.x[p.x.length-1];if(d<.999999*(c+s)){t.maxPossibleTime=d;let e="For chunksize "+s+" and tolerance "+o+", odesystem";void 0!==n&&(e+=" ("+n+")"),e+=" hit maxiterations ("+u+") at t = "+t.maxPossibleTime+". Will not calculate solution beyond that time. Decrease chunksize, increase maxiterations, or increase tolerance to calculate further.";break}}return e>t.maxPossibleTime?NaN:t.calculatedNumericSolutions[p](e)[c]};return{setValue:{numericalSolutions:r}}}},e.numericalSolution={isAlias:!0,targetVariableName:"numericalSolution1"},e.numericalSolutionFDefinitions={forRenderer:!0,isArray:!0,entryPrefixes:["numericalSolutionFDefinition"],returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey:()=>({globalDependencies:{nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},validIndependentVariable:{dependencyType:"stateVariable",variableName:"validIndependentVariable"},independentVariable:{dependencyType:"stateVariable",variableName:"independentVariable"},validVariables:{dependencyType:"stateVariable",variableName:"validVariables"},variables:{dependencyType:"stateVariable",variableName:"variables"},chunkSize:{dependencyType:"stateVariable",variableName:"chunkSize"},tolerance:{dependencyType:"stateVariable",variableName:"tolerance"},maxIterations:{dependencyType:"stateVariable",variableName:"maxIterations"},haveNumericalInitialConditions:{dependencyType:"stateVariable",variableName:"haveNumericalInitialConditions"},t0:{dependencyType:"stateVariable",variableName:"t0"},x0s:{dependencyType:"stateVariable",variableName:"x0s"},numericalRHSfDefinitions:{dependencyType:"stateVariable",variableName:"numericalRHSfDefinitions"}}}),arrayDefinitionByKey:({globalDependencyValues:e})=>e.haveNumericalInitialConditions?{setValue:{numericalSolutionFDefinitions:[...Array(e.nDimensions).keys()].map((t=>({functionType:"ODESolution",nDimensions:e.nDimensions,t0:e.t0,x0s:e.x0s,chunkSize:e.chunkSize,tolerance:e.tolerance,numericalRHSfDefinitions:e.numericalRHSfDefinitions,maxIterations:e.maxIterations,component:t})))}}:{setValue:{numericalSolutionFDefinitions:Array(e.nDimensions).fill({})}}},e}}class Polyline extends GraphicalComponent{constructor(e){super(e),Object.assign(this.actions,{movePolyline:this.movePolyline.bind(this),finalizePolylinePosition:this.finalizePolylinePosition.bind(this),polylineClicked:this.polylineClicked.bind(this),mouseDownOnPolyline:this.mouseDownOnPolyline.bind(this)})}static componentType="polyline";static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.verticesDraggable={createComponentOfType:"boolean"},e.vertices={createComponentOfType:"_pointListComponent"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){let t=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(t&&(t+=" "),t+=e.selectedStyle.lineStyleWord),t&&(t+=" "),t+=e.selectedStyle.lineColorWord,{setValue:{styleDescription:t}}}},e.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({styleDescription:{dependencyType:"stateVariable",variableName:"styleDescription"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescriptionWithNoun:e.styleDescription+" polyline"}}}},e.verticesDraggable={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},hasEssential:!0,forRenderer:!0,returnDependencies:()=>({verticesDraggableAttr:{dependencyType:"attributeComponent",attributeName:"verticesDraggable",variableNames:["value"]},draggable:{dependencyType:"stateVariable",variableName:"draggable"}}),definition:({dependencyValues:e})=>e.verticesDraggableAttr?{setValue:{verticesDraggable:e.verticesDraggableAttr.stateValues.value}}:{useEssentialOrDefaultValue:{verticesDraggable:{defaultValue:e.draggable}}}},e.nVertices={public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies:()=>({vertices:{dependencyType:"attributeComponent",attributeName:"vertices",variableNames:["nPoints"]}}),definition:function({dependencyValues:e}){return null!==e.vertices?{setValue:{nVertices:e.vertices.stateValues.nPoints}}:{setValue:{nVertices:0}}}},e.nDimensions={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({vertices:{dependencyType:"attributeComponent",attributeName:"vertices",variableNames:["nDimensions"]}}),definition:function({dependencyValues:e}){if(null!==e.vertices){return{setValue:{nDimensions:e.vertices.stateValues.nDimensions},checkForActualChange:{nDimensions:!0}}}return{setValue:{nDimensions:2}}}},e.vertices={public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"vertexX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,nDimensions:2,entryPrefixes:["vertexX","vertex"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("vertexX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},getAllArrayKeys(e,t=!0,n){function r(e){if(1===e.length)return Array.from(Array(e[0]),((e,t)=>String(t)));{let n=e[0],a=r(e.slice(1)),i=[];for(let e=0;ee+","+t))):i.push(a.map((t=>e+","+t)));return i}}if(n){if(0!==n.length&&e){let t=[...e];return t[0]=n[0],r(t)}return[]}return e&&0!==e.length?r(e):[]},arrayVarNameFromPropIndex(e,t){if("vertices"===t)return 1===e.length?"vertex"+e[0]:`vertexX${e[0]}_${e[1]}`;if("vertex"===t.slice(0,6)){let n=Number(t.slice(6));if(Number.isInteger(n)&&n>0)return`vertexX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nVertices:{dependencyType:"stateVariable",variableName:"nVertices"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nVertices,e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let[e,r]=n.split(","),a=Number(e)+1+"_"+(Number(r)+1);t[n]={vertices:{dependencyType:"attributeComponent",attributeName:"vertices",variableNames:["pointX"+a]}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let[t,a]=r.split(","),i=Number(t)+1+"_"+(Number(a)+1),s=e[r].vertices;null!==s&&s.stateValues["pointX"+i]?n[r]=s.stateValues["pointX"+i]:n[r]=me$3.fromAst("_")}return{setValue:{vertices:n}}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n,initialChange:r,stateValues:a}){let i=[];for(let r in e.vertices){let[a,s]=r.split(","),o=Number(a)+1+"_"+(Number(s)+1);if(null===t[r].vertices||!t[r].vertices.stateValues["pointX"+o])return{success:!1};i.push({setDependency:n[r].vertices,desiredValue:e.vertices[r],variableIndex:0})}return{success:!0,instructions:i}}},e.numericalVertices={isArray:!0,entryPrefixes:["numericalVertex"],forRenderer:!0,returnArraySizeDependencies:()=>({nVertices:{dependencyType:"stateVariable",variableName:"nVertices"}}),returnArraySize:({dependencyValues:e})=>[e.nVertices],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={vertex:{dependencyType:"stateVariable",variableName:"vertex"+(Number(n)+1)}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].vertex.map((e=>e.evaluate_to_constant()));t.every((e=>Number.isFinite(e)))||(t=Array(t.length).fill(NaN)),n[r]=t}return{setValue:{numericalVertices:n}}}},e.nearestPoint={returnDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},numericalVertices:{dependencyType:"stateVariable",variableName:"numericalVertices"},nVertices:{dependencyType:"stateVariable",variableName:"nVertices"}}),definition({dependencyValues:e}){let t,n,r=e.nDimensions,a=e.nVertices,i=e.numericalVertices,s=[],o=i[0]?.[0],l=i[0]?.[1];for(let e=1;e=1?{x1:h,x2:f}:{x1:l+g*a*n,x2:u+g*y*o};let b=Math.pow((d-r.x1)/n,2)+Math.pow((m-r.x2)/o,2);b0&&(p.x3=0),p}}}}},e}async movePolyline({pointCoords:e,transient:t,sourceInformation:n,actionId:r}){if(1===Object.keys(e).length){if(!await this.stateValues.verticesDraggable)return await this.coreFunctions.resolveAction({actionId:r})}else if(!await this.stateValues.draggable)return await this.coreFunctions.resolveAction({actionId:r});let a={};for(let t in e)a[t+",0"]=me$3.fromAst(e[t][0]),a[t+",1"]=me$3.fromAst(e[t][1]);return t?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"vertices",value:a,sourceInformation:n}],transient:t,actionId:r}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"vertices",value:a,sourceInformation:n}],actionId:r,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{pointCoordinates:e}}})}async finalizePolylinePosition(){return await this.actions.movePolyline({pointCoords:await this.stateValues.numericalVertices,transient:!1})}async polylineClicked({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"click",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}async mouseDownOnPolyline({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"down",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}}class CobwebPolyline extends Polyline{static componentType="cobwebPolyline";static rendererType="cobwebPolyline";static createAttributesObject(){let e=super.createAttributesObject();return e.attractThreshold={createComponentOfType:"number",createStateVariable:"attractThreshold",defaultValue:.5,public:!0},e.nPoints={createComponentOfType:"number",createStateVariable:"nPoints",defaultValue:1,public:!0,clamp:[0,1/0],forRenderer:!0},e.variable={createComponentOfType:"variable",createStateVariable:"variable",defaultValue:me$3.fromAst("x"),public:!0,forRenderer:!0},e.nIterationsRequired={createComponentOfType:"number",createStateVariable:"nIterationsRequired",defaultValue:0,public:!0},e.initialPoint={createComponentOfType:"point"},e.function={createComponentOfType:"function"},e.lockToSolution={createComponentOfType:"boolean",createStateVariable:"lockToSolution",defaultValue:!1},e.defaultPoint={createComponentOfType:"point"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nDimensions.returnDependencies=()=>({}),e.nDimensions.definition=()=>({setValue:{nDimensions:2}}),e.initialPoint={isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"initialPointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},entryPrefixes:["initialPointX"],defaultValueByArrayKey:()=>me$3.fromAst(0),hasEssential:!0,returnArraySizeDependencies:()=>({}),returnArraySize:()=>[2],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={initialPointAttr:{dependencyType:"attributeComponent",attributeName:"initialPoint",variableNames:["x"+e]}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={},r={};for(let a of t){let t=Number(a)+1;e[a].initialPointAttr?n[a]=e[a].initialPointAttr.stateValues["x"+t]:r[a]=!0}let a={};return Object.keys(n).length>0&&(a.setValue={initialPoint:n}),Object.keys(r).length>0&&(a.useEssentialOrDefaultValue={initialPoint:r}),a},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n}){let r=[];for(let a in e.initialPoint)t[a].initialPointAttr&&t[a].initialPointAttr.stateValues["x"+(Number(a)+1)]?r.push({setDependency:n[a].initialPointAttr,desiredValue:e.initialPoint[a],variableIndex:0}):r.push({setEssentialValue:"initialPoint",value:{[a]:e.initialPoint[a]}});return{success:!0,instructions:r}}},e.f={additionalStateVariablesDefined:[{variableName:"fDefinition",forRenderer:!0}],returnDependencies:()=>({functionAttr:{dependencyType:"attributeComponent",attributeName:"function",variableNames:["numericalf","fDefinition"]}}),definition:({dependencyValues:e})=>e.functionAttr?{setValue:{f:e.functionAttr.stateValues.numericalf,fDefinition:e.functionAttr.stateValues.fDefinition}}:{setValue:{f:null,fDefinition:null}}},e.nVertices={isAlias:!0,targetVariableName:"nPoints"},e.nOriginalVertices={providePreviousValuesInDefinition:!0,returnDependencies:()=>({nVertices:{dependencyType:"stateVariable",variableName:"nVertices"}}),definition({dependencyValues:e,previousValues:t}){let n=e.nVertices;return t.nOriginalVertices>n&&(n=t.nOriginalVertices),{setValue:{nOriginalVertices:n}}}},e.originalVertices={isArray:!0,nDimensions:2,hasEssential:!0,entryPrefixes:["originalVertexX","originalVertex"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("originalVertexX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("originalVertices"===t)return 1===e.length?"originalVertex"+e[0]:`originalVertexX${e[0]}_${e[1]}`;if("originalVertex"===t.slice(0,14)){let n=Number(t.slice(14));if(Number.isInteger(n)&&n>0)return`originalVertexX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nOriginalVertices:{dependencyType:"stateVariable",variableName:"nOriginalVertices"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nOriginalVertices-1,e.nDimensions],returnArrayDependenciesByKey:()=>({globalDependencies:{graphAncestor:{dependencyType:"ancestor",componentType:"graph",variableNames:["xmin","xmax","ymin","ymax"]},defaultPoint:{dependencyType:"attributeComponent",attributeName:"defaultPoint",variableNames:["xs"]}}}),arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t}){let n={};for(let r of t){let t=r.split(",").map(Number);n[r]={get defaultValue(){if(e.defaultPoint){let n=e.defaultPoint.stateValues.xs;if(2===n.length&&t[1]<2)return n[t[1]]}if(e.graphAncestor){if(0===t[1]){let t=e.graphAncestor.stateValues.xmin,n=e.graphAncestor.stateValues.xmax;return me$3.fromAst((t+n)/2)}if(1===t[1]){let t=e.graphAncestor.stateValues.ymin,n=e.graphAncestor.stateValues.ymax;return me$3.fromAst((t+n)/2)}}return me$3.fromAst(0)}}}return{useEssentialOrDefaultValue:{originalVertices:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e}){let t=[];for(let n in e.originalVertices)t.push({setEssentialValue:"originalVertices",value:{[n]:e.originalVertices[n]}});return{success:!0,instructions:t}}},e.vertices.additionalStateVariablesDefined=[{variableName:"prelimCorrectVertices",entryPrefixes:["prelimCorrectVertexX","prelimCorrectVertex"],getArrayKeysFromVarName:function({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("prelimCorrectVertexX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}}}],e.vertices.basedOnArrayKeyStateVariables=!0,e.vertices.returnArrayDependenciesByKey=function({arrayKeys:e}){let t={};for(let n of e){let[e,r]=n.split(",");t[n]="0"===e?{initialPoint:{dependencyType:"stateVariable",variableName:"initialPointX"+(Number(r)+1)}}:{originalVertexX1:{dependencyType:"stateVariable",variableName:"originalVertexX"+e+"_1"},originalVertexX2:{dependencyType:"stateVariable",variableName:"originalVertexX"+e+"_2"},previousVertexX1:{dependencyType:"stateVariable",variableName:"vertexX"+e+"_1"},previousVertexX2:{dependencyType:"stateVariable",variableName:"vertexX"+e+"_2"}}}return{globalDependencies:{f:{dependencyType:"stateVariable",variableName:"f"},attractThreshold:{dependencyType:"stateVariable",variableName:"attractThreshold"},lockToSolution:{dependencyType:"stateVariable",variableName:"lockToSolution"}},dependenciesByKey:t}},e.vertices.arrayDefinitionByKey=function({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={},a={};for(let i of n){let[n,s]=i.split(",");if("0"===n)r[i]=t[i].initialPoint,a[i]=null;else{let s,o,l;try{s=[t[i].originalVertexX1.evaluate_to_constant(),t[i].originalVertexX2.evaluate_to_constant()],o=[t[i].previousVertexX1.evaluate_to_constant(),t[i].previousVertexX2.evaluate_to_constant()]}catch(e){r[n+",0"]=me$3.fromAst(0),r[n+",1"]=me$3.fromAst(0),a[n+",0"]=!1;continue}if(Number(n)%2==1){let t=e.f(o[0]);l=[o[0],t]}else l=[o[1],o[1]];Math.pow(s[0]-l[0],2)+Math.pow(s[1]-l[1],2)({nVertices:{dependencyType:"stateVariable",variableName:"nVertices"}}),returnArraySize:({dependencyValues:e})=>[e.nVertices-1],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={prelimCorrectVertex:{dependencyType:"stateVariable",variableName:"prelimCorrectVertexX"+(Number(n)+2)+"_1"}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t)n[r]=e[r].prelimCorrectVertex;return{setValue:{correctVertices:n}}}},e.fractionCorrectVertices={public:!0,shadowingInstructions:{createComponentOfType:"number"},additionalStateVariablesDefined:[{variableName:"nGradedVertices",public:!0,shadowingInstructions:{createComponentOfType:"number"}},{variableName:"nCorrectVertices",public:!0,shadowingInstructions:{createComponentOfType:"number"}}],returnDependencies:()=>({correctVertices:{dependencyType:"stateVariable",variableName:"correctVertices"}}),definition({dependencyValues:e}){let t,n,r=e.correctVertices.length;return 0===r?(t=0,n=0):(n=e.correctVertices.reduce(((e,t)=>e+t),0),t=n/r),{setValue:{fractionCorrectVertices:t,nGradedVertices:r,nCorrectVertices:n}}}},e.fractionCorrectVerticesAdjusted={public:!0,shadowingInstructions:{createComponentOfType:"number"},additionalStateVariablesDefined:[{variableName:"nGradedVerticesAdjusted",public:!0,shadowingInstructions:{createComponentOfType:"number"}}],returnDependencies:()=>({nCorrectVertices:{dependencyType:"stateVariable",variableName:"nCorrectVertices"},nGradedVertices:{dependencyType:"stateVariable",variableName:"nGradedVertices"},nIterationsRequired:{dependencyType:"stateVariable",variableName:"nIterationsRequired"}}),definition({dependencyValues:e}){let t=0;e.nIterationsRequired>0&&(t=2*e.nIterationsRequired-1);let n,r=Math.max(e.nGradedVertices,t);return n=0===r?0:e.nCorrectVertices/r,{setValue:{fractionCorrectVerticesAdjusted:n,nGradedVerticesAdjusted:r}}}},e.nIterateValues={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({nVertices:{dependencyType:"stateVariable",variableName:"nVertices"}}),definition:({dependencyValues:e})=>({setValue:{nIterateValues:Math.ceil((e.nVertices+1)/2)}})},e.iterateValues={isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"math"},entryPrefixes:["iterateValue"],returnArraySizeDependencies:()=>({nIterateValues:{dependencyType:"stateVariable",variableName:"nIterateValues"}}),returnArraySize:({dependencyValues:e})=>[e.nIterateValues],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]="0"===n?{iterateValue:{dependencyType:"stateVariable",variableName:"vertexX1_1"}}:{iterateValue:{dependencyType:"stateVariable",variableName:"vertexX"+2*Number(n)+"_2"}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t)n[r]=e[r].iterateValue;return{setValue:{iterateValues:n}}}},e}}class Point extends GraphicalComponent{constructor(e){super(e),Object.assign(this.actions,{movePoint:this.movePoint.bind(this),switchPoint:this.switchPoint.bind(this),pointClicked:this.pointClicked.bind(this),mouseDownOnPoint:this.mouseDownOnPoint.bind(this)})}static componentType="point";static primaryStateVariableForDefinition="coordsShadow";static stateVariableForAttributeValue="coords";static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.x={createComponentOfType:"math"},e.y={createComponentOfType:"math"},e.z={createComponentOfType:"math"},e.xs={createComponentOfType:"mathList"},e.coords={createComponentOfType:"coords"},e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.padZeros={createComponentOfType:"boolean",createStateVariable:"padZeros",defaultValue:!1,public:!0},e.labelPosition={createComponentOfType:"text",createStateVariable:"labelPosition",defaultValue:"upperright",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft","top","bottom","left","right"]},e.showCoordsWhenDragging={createComponentOfType:"boolean",createStateVariable:"showCoordsWhenDragging",defaultValue:!0,public:!0,forRenderer:!0},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e,componentInfoObjects:t}){let n=returnBreakStringsSugarFunction({childrenToComponentFunction:e=>({componentType:"math",children:e}),mustStripOffOuterParentheses:!0}),r=e.map((e=>typeof e)),a=r.indexOf("string"),i=r.lastIndexOf("string");if(-1===a){let n=t.componentIsSpecifiedType,r=e.filter((e=>!(n(e,"point")||n(e,"vector")||n(e,"constraints")||n(e,"label"))));if(1===r.length){let t=r[0],n=e.indexOf(t);return{success:!0,newAttributes:{coords:{component:{componentType:"math",children:r}}},newChildren:[...e.slice(0,n),...e.slice(n+1)]}}return{success:!1}}let s=[...e.slice(0,a),...e.slice(i+1)],o=n({matchedChildren:e=e.slice(a,i+1)});return o.success||1!==e.length?o.success?{success:!0,newAttributes:{xs:{component:{componentType:"mathList",children:o.newChildren,skipSugar:!0}}},newChildren:s}:{success:!1}:{success:!0,newAttributes:{xs:{component:{componentType:"mathList",children:[{componentType:"math",children:e}]}}},newChildren:s}}}),e}static returnChildGroups(){let e=super.returnChildGroups();return e.push({group:"points",componentTypes:["point"]},{group:"vectors",componentTypes:["vector"]},{group:"constraints",componentTypes:["constraints"]}),e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescription:e.selectedStyle.markerColorWord}}}},e.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescriptionWithNoun:e.selectedStyle.markerColorWord+" "+e.selectedStyle.markerStyleWord}}}},e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.displayDigitsAttr){let n=null===e.displayDigitsAttr||t.displayDigitsAttr,r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!n&&!r){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({}),definition:()=>({useEssentialOrDefaultValue:{coordsShadow:!0}}),inverseDefinition:async function({desiredStateVariableValues:e,stateValues:t,workspace:n}){return{success:!0,instructions:[{setEssentialValue:"coordsShadow",value:e.coordsShadow}]}}},e.nDimensions={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({coordsShadow:{dependencyType:"stateVariable",variableName:"coordsShadow"},coords:{dependencyType:"attributeComponent",attributeName:"coords",variableNames:["value"]},x:{dependencyType:"attributeComponent",attributeName:"x"},y:{dependencyType:"attributeComponent",attributeName:"y"},z:{dependencyType:"attributeComponent",attributeName:"z"},xs:{dependencyType:"attributeComponent",attributeName:"xs",variableNames:["nComponents"]},pointChild:{dependencyType:"child",childGroups:["points"],variableNames:["nDimensions"]},vectorChild:{dependencyType:"child",childGroups:["vectors"],variableNames:["nDimensions"]}}),definition:function({dependencyValues:e}){let t,n,r=!1;if(n=null!==e.z?3:null!==e.y?2:0,null!==e.coords?(r=!0,t=e.coords.stateValues.value):e.coordsShadow&&(r=!0,t=e.coordsShadow),r){let e=t.tree;return n=Array.isArray(e)&&vectorOperators.includes(e[0])?Math.max(e.length-1,n):Math.max(1,n),{setValue:{nDimensions:n},checkForActualChange:{nDimensions:!0}}}return null!==e.xs?{setValue:{nDimensions:Math.max(e.xs.stateValues.nComponents,n)}}:e.pointChild.length>0?{setValue:{nDimensions:Math.max(e.pointChild[0].stateValues.nDimensions,n)}}:e.vectorChild.length>0?{setValue:{nDimensions:Math.max(e.vectorChild[0].stateValues.nDimensions,n)}}:(0===n&&(n=2),{setValue:{nDimensions:n},checkForActualChange:{nDimensions:!0}})}},e.arrayVariableForConstraints={returnDependencies:()=>({}),definition:()=>({setValue:{arrayVariableForConstraints:"unconstrainedXs"}})},e.arrayEntryPrefixForConstraints={returnDependencies:()=>({}),definition:()=>({setValue:{arrayEntryPrefixForConstraints:"unconstrainedX"}})},e.nDimensionsForConstraints={isAlias:!0,targetVariableName:"nDimensions"},e.unconstrainedXs={isArray:!0,entryPrefixes:["unconstrainedX"],defaultValueByArrayKey:()=>me$3.fromAst(0),hasEssential:!0,returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={xs:{dependencyType:"attributeComponent",attributeName:"xs",variableNames:["math"+e]},pointChild:{dependencyType:"child",childGroups:["points"],variableNames:["x"+e]},vectorChild:{dependencyType:"child",childGroups:["vectors"],variableNames:["x"+e]}},"0"===n?t[n].component={dependencyType:"attributeComponent",attributeName:"x",variableNames:["value"]}:"1"===n?t[n].component={dependencyType:"attributeComponent",attributeName:"y",variableNames:["value"]}:"2"===n&&(t[n].component={dependencyType:"attributeComponent",attributeName:"z",variableNames:["value"]})}return{globalDependencies:{coordsShadow:{dependencyType:"stateVariable",variableName:"coordsShadow"},coords:{dependencyType:"attributeComponent",attributeName:"coords",variableNames:["value"]}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r,a={},i={},s=!1;if(null!==e.coords?(s=!0,r=e.coords.stateValues.value):e.coordsShadow&&(s=!0,r=e.coordsShadow),s){let e=r.tree;if(Array.isArray(e)&&vectorOperators.includes(e[0]))for(let t of n){let n=Number(t);(n>=0||n0)a[e]=r[0].stateValues["x"+n];else{let r=t[e].vectorChild;r.length>0&&(a[e]=r[0].stateValues["x"+n])}}}for(let e of n){let n=t[e].component;n?a[e]=n.stateValues.value.simplify():void 0===a[e]&&(i[e]=!0)}let o={};return Object.keys(a).length>0&&(o.setValue={unconstrainedXs:a}),Object.keys(i).length>0&&(o.useEssentialOrDefaultValue={unconstrainedXs:i}),o},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i,s,o=[],l=!1,u=!1;null!==t.coords?(l=!0,i="coords",s=Array(a[0]+1)):null!==t.coordsShadow&&(l=!0,i="coordsShadow",s=Array(a[0]+1));for(let t of Object.keys(e.unconstrainedXs).reverse()){let a=convertValueToMathExpression(e.unconstrainedXs[t]);if(null!==n[t].component)o.push({setDependency:r[t].component,desiredValue:a,childIndex:0,variableIndex:0});else if(l)s[Number(t)+1]=a.tree,u=!0;else{if(null!==n[t].xs)o.push({setDependency:r[t].xs,desiredValue:a,childIndex:0,variableIndex:0});else{if(n[t].pointChild.length>0)o.push({setDependency:r[t].pointChild,desiredValue:a,childIndex:0,variableIndex:0});else{n[t].vectorChild.length>0?o.push({setDependency:r[t].vectorChild,desiredValue:a,childIndex:0,variableIndex:0}):o.push({setEssentialValue:"unconstrainedXs",value:{[t]:a}})}}}}if(u){let e;1===a[0]?e=me$3.fromAst(s[1]):(s[0]="vector",e=me$3.fromAst(s));let t={setDependency:i,desiredValue:e};"coords"===i&&(t.childIndex=0,t.variableIndex=0),o.push(t)}return{success:!0,instructions:o}}},e.xs={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},isArray:!0,entryPrefixes:["x"],returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1,r={};r.unconstrainedX={dependencyType:"stateVariable",variableName:`unconstrainedX${e}`},r.constraintsChild={dependencyType:"child",childGroups:["constraints"],variableNames:[`constraintResult${e}`]},t[n]=r}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t)if(e[r].constraintsChild.length>0){let t=Number(r)+1;n[r]=convertValueToMathExpression(e[r].constraintsChild[0].stateValues["constraintResult"+t])}else n[r]=convertValueToMathExpression(e[r].unconstrainedX);return t.length>0?{setValue:{xs:n}}:{}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n,initialChange:r,stateValues:a}){if(r&&!await a.draggable)return{success:!1};let i=[];for(let r of Object.keys(e.xs).reverse())t[r]&&(t[r].constraintsChild.length>0?i.push({setDependency:n[r].constraintsChild,desiredValue:e.xs[r],childIndex:0,variableIndex:0}):i.push({setDependency:n[r].unconstrainedX,desiredValue:e.xs[r]}));return{success:!0,instructions:i}}},e.x={isAlias:!0,targetVariableName:"x1"},e.y={isAlias:!0,targetVariableName:"x2"},e.z={isAlias:!0,targetVariableName:"x3"},e.coords={public:!0,shadowingInstructions:{createComponentOfType:"coords",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},returnDependencies:()=>({xs:{dependencyType:"stateVariable",variableName:"xs"}}),definition:function({dependencyValues:e}){let t=[];for(let n of e.xs)n?t.push(n.tree):t.push("_");return t=t.length>1?["vector",...t]:1===t.length?t[0]:"_",{setValue:{coords:me$3.fromAst(t)}}},inverseDefinition:async function({desiredStateVariableValues:e,stateValues:t,initialChange:n}){if(n&&!await t.draggable)return{success:!1};let r=[],a={},i=e.coords.tree;if(Array.isArray(i)&&vectorOperators.includes(i[0]))for(let t=0;t({coords:{dependencyType:"stateVariable",variableName:"coords"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"}}),definition:function({dependencyValues:e,usedDefault:t}){let n={};return e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(n.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(n.padToDigits=e.displayDigits)),{setValue:{latex:roundForDisplay({value:e.coords,dependencyValues:e,usedDefault:t}).toLatex(n)}}}},e.value={isAlias:!0,targetVariableName:"coords"},e.constraintUsed={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({constraintsChild:{dependencyType:"child",childGroups:["constraints"],variableNames:["constraintUsed"]}}),definition:function({dependencyValues:e}){return 0===e.constraintsChild.length?{setValue:{constraintUsed:!1}}:{setValue:{constraintUsed:e.constraintsChild[0].stateValues.constraintUsed}}}},e.numericalXs={isArray:!0,entryPrefixes:["numericalX"],forRenderer:!0,returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={x:{dependencyType:"stateVariable",variableName:`x${e}`}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].x;t?(t=e[r].x.evaluate_to_constant(),Number.isFinite(t)?n[r]=t:n[r]=NaN):n[r]=NaN}return{setValue:{numericalXs:n}}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,initialChange:n,stateValues:r}){if(n&&!await r.draggable)return{success:!1};let a=[];for(let n in e.numericalXs)dependencyValuesByKey[n]&&a.push({setDependency:t[n].xs,desiredValue:e.numericalXs[n]});return{success:!0,instructions:a}}},e.nearestPoint={returnDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},numericalXs:{dependencyType:"stateVariable",variableName:"numericalXs"}}),definition:({dependencyValues:e})=>({setValue:{nearestPoint:function(){let t={};for(let n=1;n<=e.nDimensions;n++){let r=e.numericalXs[n-1];if(!Number.isFinite(r))return{};t["x"+n]=r}return t}}})},e}static adapters=[{stateVariable:"coords",stateVariablesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]}];async movePoint({x:e,y:t,z:n,transient:r,actionId:a}){let i={};return void 0!==e&&(i[0]=me$3.fromAst(e)),void 0!==t&&(i[1]=me$3.fromAst(t)),void 0!==n&&(i[2]=me$3.fromAst(n)),r?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"xs",value:i}],transient:r,actionId:a}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"xs",value:i}],actionId:a,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{x:e,y:t,z:n}}})}switchPoint(){}async pointClicked({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"click",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}async mouseDownOnPoint({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"down",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}}class EquilibriumPoint extends Point{static componentType="equilibriumPoint";static rendererType="point";static createAttributesObject(){let e=super.createAttributesObject();return e.stable={createComponentOfType:"boolean",createStateVariable:"stable",defaultValue:!0,public:!0},e.switchable={createComponentOfType:"boolean",createStateVariable:"switchable",defaultValue:!1,public:!0,forRenderer:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.open={forRenderer:!0,returnDependencies:()=>({stable:{dependencyType:"stateVariable",variableName:"stable"}}),definition:({dependencyValues:e})=>({setValue:{open:!e.stable}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setDependency:"stable",desiredValue:!e.open}]})},e}async switchPoint({actionId:e}){if(await this.stateValues.switchable)return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"stable",value:!this.stateValues.stable}],actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{stable:!this.stateValues.stable}}});this.coreFunctions.resolveAction({actionId:e})}}class Line extends GraphicalComponent{constructor(e){super(e),Object.assign(this.actions,{moveLine:this.moveLine.bind(this),switchLine:this.switchLine.bind(this),lineClicked:this.lineClicked.bind(this),mouseDownOnLine:this.mouseDownOnLine.bind(this)})}static componentType="line";static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.equation={createComponentOfType:"math"},e.through={createComponentOfType:"_pointListComponent"},e.slope={createComponentOfType:"number"},e.variables={createComponentOfType:"variables"},e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.padZeros={createComponentOfType:"boolean",createStateVariable:"padZeros",defaultValue:!1,public:!0},e.labelPosition={createComponentOfType:"text",createStateVariable:"labelPosition",defaultValue:"upperright",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft"]},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e,componentInfoObjects:t}){if(0===e.length)return{success:!1};let n=e.map((e=>t.componentIsSpecifiedType(e,"label"))),r=[],a=[];if(0===n.filter((e=>e)).length)r=e;else{if(n[0]){let t=n.indexOf(!1);-1!==t&&(a.push(...e.slice(0,t)),e=e.slice(t),n=n.slice(t))}let t=n.indexOf(!0);-1===t?r=e:(r=e.slice(0,t),a.push(...e.slice(t)))}return 0===r.length?{success:!1}:{success:!0,newAttributes:{equation:{component:{componentType:"math",children:r}}},newChildren:a}}}),e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){let t=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(t&&(t+=" "),t+=e.selectedStyle.lineStyleWord),t&&(t+=" "),t+=e.selectedStyle.lineColorWord,{setValue:{styleDescription:t}}}},e.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({styleDescription:{dependencyType:"stateVariable",variableName:"styleDescription"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescriptionWithNoun:e.styleDescription+" line"}}}},e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){let n=null===e.displayDigitsAttr||t.displayDigitsAttr,r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!n&&!r){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({throughAttr:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["nPoints"]}}),definition:function({dependencyValues:e}){return null===e.throughAttr?{setValue:{nPointsPrescribed:0}}:{setValue:{nPointsPrescribed:e.throughAttr.stateValues.nPoints}}}},e.basedOnSlope={returnDependencies:()=>({slopeAttr:{dependencyType:"attributeComponent",attributeName:"slope"},nPointsPrescribed:{dependencyType:"stateVariable",variableName:"nPointsPrescribed"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),definition:({dependencyValues:e})=>({setValue:{basedOnSlope:e.nPointsPrescribed<2&&null!==e.slopeAttr&&2===e.nDimensions}})},e.dForSlope={defaultValue:1,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{dForSlope:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"dForSlope",value:e.dForSlope}]})},e.variables={isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"variable"},entryPrefixes:["var"],returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey:()=>({globalDependencies:{variables:{dependencyType:"attributeComponent",attributeName:"variables",variableNames:["variables"]}}}),arrayDefinitionByKey({globalDependencyValues:e,arraySize:t}){let n=[];return null!==e.variables&&(n=e.variables.stateValues.variables),{setValue:{variables:returnNVariables(t[0],n)}}}},e.equationIdentity={returnDependencies:()=>({equation:{dependencyType:"attributeComponent",attributeName:"equation"}}),definition:function({dependencyValues:e}){return null!==e.equation?{setValue:{equationIdentity:e.equation}}:{setValue:{equationIdentity:null}}}},e.essentialPoints={isArray:!0,nDimensions:"2",hasEssential:!0,entryPrefixes:["essentialPointX","essentialPoint"],set:convertValueToMathExpression,defaultValueByArrayKey:e=>me$3.fromAst("0,0"===e?1:0),getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("essentialPointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[2,e.nDimensions],returnArrayDependenciesByKey:()=>({}),arrayDefinitionByKey({arrayKeys:e}){let t={};for(let n of e)t[n]=!0;return{useEssentialOrDefaultValue:{essentialPoints:t}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e}){let t=[];for(let n in e.essentialPoints)t.push({setEssentialValue:"essentialPoints",value:{[n]:convertValueToMathExpression(e.essentialPoints[n])}});return{success:!0,instructions:t}}},e.points={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"],returnWrappingComponents:e=>"pointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,nDimensions:2,entryPrefixes:["pointX","point"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("pointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("points"===t)return 1===e.length?"point"+e[0]:`pointX${e[0]}_${e[1]}`;if("point"===t.slice(0,5)){let n=Number(t.slice(5));if(Number.isInteger(n)&&n>0)return`pointX${n}_${e[0]}`}return null},stateVariablesDeterminingDependencies:["equationIdentity","nPointsPrescribed","basedOnSlope"],returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[2,e.nDimensions],returnArrayDependenciesByKey({stateValues:e,arrayKeys:t}){if(null===e.equationIdentity){let n={};for(let r of t){let[t,a]=r.split(","),i=Number(t)+1+"_"+(Number(a)+1);n[r]={through:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["pointX"+i]}},e.basedOnSlope?("1"===t&&(1===e.nPointsPrescribed&&n[r].through.variableNames.push("pointX1_"+(Number(a)+1)),n[r].dForSlope={dependencyType:"stateVariable",variableName:"dForSlope"},n[r].slopeAttr={dependencyType:"attributeComponent",attributeName:"slope",variableNames:["value"]}),0===e.nPointsPrescribed&&(n[r].essentialPoint={dependencyType:"stateVariable",variableName:"essentialPointX2_"+(Number(a)+1)})):n[r].essentialPoint={dependencyType:"stateVariable",variableName:"essentialPointX"+i}}return{dependenciesByKey:n,globalDependencies:{nPointsPrescribed:{dependencyType:"stateVariable",variableName:"nPointsPrescribed"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},basedOnSlope:{dependencyType:"stateVariable",variableName:"basedOnSlope"}}}}return{globalDependencies:{coeff0:{dependencyType:"stateVariable",variableName:"coeff0"},coeffvar1:{dependencyType:"stateVariable",variableName:"coeffvar1"},coeffvar2:{dependencyType:"stateVariable",variableName:"coeffvar2"},variables:{dependencyType:"stateVariable",variableName:"variables"},lastPointsFromInverting:{dependencyType:"stateVariable",variableName:"lastPointsFromInverting"}}}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n,arraySize:r,componentName:a}){if("coeff0"in e){let t=calculatePointsFromCoeffs(e);if(t.success)return{setValue:{points:t.points}};{let e={};for(let t=0;te.toString()))];for(let e=0;e({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>Number.isNaN(e.nDimensions)?[0]:[2],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={point:{dependencyType:"stateVariable",variableName:"point"+(Number(n)+1)}};return{globalDependencies:{nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n,componentName:r}){if(Number.isNaN(e.nDimensions))return{};let a={};for(let r of n){let n=t[r].point;Array.isArray(n)||(n=[n]);let i=[];for(let t=0;t({coeff0:{dependencyType:"stateVariable",variableName:"coeff0"},coeffvar1:{dependencyType:"stateVariable",variableName:"coeffvar1"},coeffvar2:{dependencyType:"stateVariable",variableName:"coeffvar2"}}),definition:function({dependencyValues:e}){let t=e.coeff0.evaluate_to_constant();Number.isFinite(t)||(t=NaN);let n=e.coeffvar1.evaluate_to_constant();Number.isFinite(n)||(n=NaN);let r=e.coeffvar2.evaluate_to_constant();return Number.isFinite(r)||(r=NaN),{setValue:{numericalCoeff0:t,numericalCoeffvar1:n,numericalCoeffvar2:r}}}},e.slope={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},returnDependencies:()=>({coeffvar1:{dependencyType:"stateVariable",variableName:"coeffvar1"},coeffvar2:{dependencyType:"stateVariable",variableName:"coeffvar2"}}),definition:function({dependencyValues:e}){return{setValue:{slope:me$3.fromAst(["-",["/","a","b"]]).substitute({a:e.coeffvar1,b:e.coeffvar2}).simplify()}}}},e.xintercept={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},returnDependencies:()=>({coeff0:{dependencyType:"stateVariable",variableName:"coeff0"},coeffvar1:{dependencyType:"stateVariable",variableName:"coeffvar1"}}),definition:({dependencyValues:e})=>({setValue:{xintercept:me$3.fromAst(["-",["/","a","b"]]).substitute({a:e.coeff0,b:e.coeffvar1}).simplify()}})},e.yintercept={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},returnDependencies:()=>({coeff0:{dependencyType:"stateVariable",variableName:"coeff0"},coeffvar2:{dependencyType:"stateVariable",variableName:"coeffvar2"}}),definition:({dependencyValues:e})=>({setValue:{yintercept:me$3.fromAst(["-",["/","a","b"]]).substitute({a:e.coeff0,b:e.coeffvar2}).simplify()}})},e.lastPointsFromInverting={defaultValue:null,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{lastPointsFromInverting:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"lastPointsFromInverting",value:e.lastPointsFromInverting}]})},e.latex={forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({equation:{dependencyType:"stateVariable",variableName:"equation"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"}}),definition:function({dependencyValues:e,usedDefault:t}){let n={};return e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(n.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(n.padToDigits=e.displayDigits)),{setValue:{latex:roundForDisplay({value:e.equation,dependencyValues:e,usedDefault:t}).toLatex(n)}}}},e.nearestPoint={returnDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},numericalCoeff0:{dependencyType:"stateVariable",variableName:"numericalCoeff0"},numericalCoeffvar1:{dependencyType:"stateVariable",variableName:"numericalCoeffvar1"},numericalCoeffvar2:{dependencyType:"stateVariable",variableName:"numericalCoeffvar2"}}),definition({dependencyValues:e}){let t=e.numericalCoeffvar1,n=e.numericalCoeffvar2,r=e.numericalCoeff0,a=Number.isFinite(t)&&Number.isFinite(n)&&Number.isFinite(r),i=2!==e.nDimensions||!a||0===t&&0===n;return{setValue:{nearestPoint:function({variables:e,scales:a=[1,1]}){if(i)return{};let s=a[0],o=a[1],l=t*s,u=n*o,c=l*l+u*u,p=e.x1?.evaluate_to_constant(),d=e.x2?.evaluate_to_constant();if(!Number.isFinite(p)||!Number.isFinite(d))return{};let m=p/s,h=d/o,f={};return f.x1=(u*(u*m-l*h)-l*r)*s/c,f.x2=(l*(-u*m+l*h)-u*r)*o/c,void 0!==e.x3&&(f.x3=0),f}}}}},e}static adapters=[{stateVariable:"equation",stateVariablesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]}];async moveLine({point1coords:e,point2coords:t,transient:n,actionId:r}){let a={"0,0":me$3.fromAst(e[0]),"0,1":me$3.fromAst(e[1])};return await this.stateValues.basedOnSlope||(a["1,0"]=me$3.fromAst(t[0]),a["1,1"]=me$3.fromAst(t[1])),n?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"points",value:a}],transient:!0,actionId:r}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"points",value:a}],actionId:r,event:{verb:"interacted",object:{componentId:this.componentName},result:{point1:e,point2:t}}})}switchLine(){}async lineClicked({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"click",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}async mouseDownOnLine({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"down",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}}function calculateCoeffsFromEquation({equation:e,variables:t}){let n=t[0],r=t[1],a=n.toString(),i=r.toString();if(e=e.expand().simplify(),!Array.isArray(e.tree)||"="!==e.tree[0]||3!==e.tree.length)return{success:!1};let s=me$3.fromAst(["+",e.tree[2],["-",e.tree[1]]]).expand().simplify(),o=[];o=Array.isArray(s.tree)&&"+"===s.tree[0]?s.tree.slice(1):[s.tree];let l=me$3.fromAst(0),u=me$3.fromAst(0),c=me$3.fromAst(0);for(let e of o){let t=p(e);if(!t.success)return{success:!1};l=l.add(t.coeffvar1),u=u.add(t.coeffvar2),c=c.add(t.coeff0)}return l=l.simplify(),u=u.simplify(),c=c.simplify(),{success:!0,coeff0:c,coeffvar1:l,coeffvar2:u};function p(e){let t=0,s=0,o=0;if("string"==typeof e)e===a?t=1:e===i?s=1:o=e;else if("number"==typeof e)o=e;else{if(!Array.isArray(e))return console.warn("Invalid format for equation of line in variables "+n+" and "+r),{success:!1};{let a=e[0],i=e.slice(1);if("-"===a){let e=p(i[0]);if(!e.success)return{success:!1};t=["-",e.coeffvar1.tree],s=["-",e.coeffvar2.tree],o=["-",e.coeff0.tree]}else{if("+"===a)return console.warn("Invalid format for equation of line in variables "+n+" and "+r),{success:!1};if("*"===a){let a=-1,l=-1;for(let e=0;e({stable:{dependencyType:"stateVariable",variableName:"stable"}}),definition:({dependencyValues:e})=>({setValue:{dashed:!e.stable}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setDependency:"stable",desiredValue:!e.dashed}]})},e}async switchLine({actionId:e}){if(await this.stateValues.switchable)return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"stable",value:!this.stateValues.stable}],actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{stable:!this.stateValues.stable}}});this.coreFunctions.resolveAction({actionId:e})}}class Curve extends GraphicalComponent{constructor(e){super(e),Object.assign(this.actions,{moveControlVector:this.moveControlVector.bind(this),moveThroughPoint:this.moveThroughPoint.bind(this),changeVectorControlDirection:this.changeVectorControlDirection.bind(this),switchCurve:this.switchCurve.bind(this),curveClicked:this.curveClicked.bind(this),mouseDownOnCurve:this.mouseDownOnCurve.bind(this)})}static componentType="curve";static rendererType="curve";static primaryStateVariableForDefinition="fShadow";static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.labelPosition={createComponentOfType:"text",createStateVariable:"labelPosition",defaultValue:"upperright",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft","top","bottom","left","right"]},e.flipFunction={createComponentOfType:"boolean",createStateVariable:"flipFunction",defaultValue:!1,public:!0,forRenderer:!0},e.nDiscretizationPoints={createComponentOfType:"number",createStateVariable:"nDiscretizationPoints",defaultValue:1e3,public:!0},e.periodic={createComponentOfType:"boolean",createStateVariable:"periodic",defaultValue:!1,public:!0},e.splineTension={createComponentOfType:"number",createStateVariable:"splineTension",defaultValue:.8,clamp:[0,1],public:!0},e.extrapolateBackward={createComponentOfType:"boolean",createStateVariable:"extrapolateBackward",defaultValue:!1,public:!0,forRenderer:!0},e.extrapolateForward={createComponentOfType:"boolean",createStateVariable:"extrapolateForward",defaultValue:!1,public:!0,forRenderer:!0},e.splineForm={createComponentOfType:"text",createStateVariable:"splineForm",defaultValue:"centripetal",public:!0,toLowerCase:!0,validValues:["centripetal","uniform"]},e.variable={createComponentOfType:"variable",createStateVariable:"variableForChild",defaultValue:me$3.fromAst("x")},e.through={createComponentOfType:"_pointListComponent"},e.parMin={createComponentOfType:"math"},e.parMax={createComponentOfType:"math"},e.nearestPointAsCurve={createComponentOfType:"boolean",createStateVariable:"nearestPointAsCurvePrelim",defaultValue:!1},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e,componentInfoObjects:t}){let n=e=>t.componentIsSpecifiedType(e,"label");if(0===e.length||!e.every((e=>"string"==typeof e||e.doenetAttributes?.createdFromMacro||n(e))))return{success:!1};let r=e.map(n),a=[],i=[],s=[];if(0===r.filter((e=>e)).length)a=e;else{if(r[0]){let t=r.indexOf(!1);-1!==t&&(i=e.slice(0,t),e=e.slice(t),r=r.slice(t))}let t=r.indexOf(!0);-1===t?a=e:(a=e.slice(0,t),s=e.slice(t))}if(0===a.length)return{success:!1};let o=returnBreakStringsSugarFunction({childrenToComponentFunction:e=>({componentType:"function",children:e}),mustStripOffOuterParentheses:!0}),l=o({matchedChildren:a}),u=[];return u=l.success?l.newChildren:[{componentType:"function",children:a}],{success:!0,newChildren:[...i,...u,...s]}}}),e}static returnChildGroups(){let e=super.returnChildGroups();return e.push({group:"functions",componentTypes:["function"]},{group:"bezierControls",componentTypes:["bezierControls"]}),e}static returnStateVariableDefinitions({numerics:e}){let t=super.returnStateVariableDefinitions({numerics:e});return t.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){let t=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(t&&(t+=" "),t+=e.selectedStyle.lineStyleWord),t&&(t+=" "),t+=e.selectedStyle.lineColorWord,{setValue:{styleDescription:t}}}},t.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({styleDescription:{dependencyType:"stateVariable",variableName:"styleDescription"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescriptionWithNoun:e.styleDescription+" curve"}}}},t.curveType={forRenderer:!0,returnDependencies:()=>({functionChildren:{dependencyType:"child",childGroups:["functions"]},through:{dependencyType:"attributeComponent",attributeName:"through"}}),definition({dependencyValues:e}){let t="function";return null!==e.through?t="bezier":e.functionChildren.length>1&&(t="parameterization"),{setValue:{curveType:t}}}},t.fShadow={defaultValue:null,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{fShadow:!0}})},t.graphXmin={forRenderer:!0,additionalStateVariablesDefined:[{variableName:"graphXmax",forRenderer:!0},{variableName:"graphYmin",forRenderer:!0},{variableName:"graphYmax",forRenderer:!0}],returnDependencies:()=>({graphAncestor:{dependencyType:"ancestor",componentType:"graph",variableNames:["xmin","xmax","ymin","ymax"]}}),definition:({dependencyValues:e})=>e.graphAncestor?{setValue:{graphXmin:e.graphAncestor.stateValues.xmin,graphXmax:e.graphAncestor.stateValues.xmax,graphYmin:e.graphAncestor.stateValues.ymin,graphYmax:e.graphAncestor.stateValues.ymax}}:{setValue:{graphXmin:null,graphXmax:null,graphYmin:null,graphYmax:null}}},t.parMax={public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies:()=>({curveType:{dependencyType:"stateVariable",variableName:"curveType"},parMaxAttr:{dependencyType:"attributeComponent",attributeName:"parMax",variableNames:["value"]},nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"},extrapolateForward:{dependencyType:"stateVariable",variableName:"extrapolateForward"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["domain"]},adapterSourceDomain:{dependencyType:"adapterSourceStateVariable",variableName:"domain"},graphXmin:{dependencyType:"stateVariable",variableName:"graphXmin"},graphXmax:{dependencyType:"stateVariable",variableName:"graphXmax"},graphYmin:{dependencyType:"stateVariable",variableName:"graphYmin"},graphYmax:{dependencyType:"stateVariable",variableName:"graphYmax"},flipFunction:{dependencyType:"stateVariable",variableName:"flipFunction"}}),definition:function({dependencyValues:e}){let t;if("bezier"===e.curveType)t=e.nThroughPoints-1,e.extrapolateForward&&(t*=2);else if(null!==e.parMaxAttr)t=e.parMaxAttr.stateValues.value.evaluate_to_constant(),Number.isFinite(t)||(t=NaN);else if("function"===e.curveType){let n,r,a=null;if(a=1===e.functionChild.length?e.functionChild[0].stateValues.domain:e.adapterSourceDomain,null!==a){a=a[0];try{t=me$3.fromAst(a.tree[1][2]).evaluate_to_constant(),Number.isFinite(t)||t===1/0||(t=NaN)}catch(e){}}e.flipFunction?(r=e.graphYmax,n=e.graphYmin):(r=e.graphXmax,n=e.graphXmin),null!==r&&null!==n&&(t=void 0===t?r+.1*(r-n):Math.min(t,r+.1*(r-n))),void 0===t&&(t=1/0)}else t=10;return{setValue:{parMax:t}}}},t.parMin={forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({curveType:{dependencyType:"stateVariable",variableName:"curveType"},parMinAttr:{dependencyType:"attributeComponent",attributeName:"parMin",variableNames:["value"]},nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"},extrapolateBackward:{dependencyType:"stateVariable",variableName:"extrapolateBackward"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["domain"]},adapterSourceDomain:{dependencyType:"adapterSourceStateVariable",variableName:"domain"},graphXmin:{dependencyType:"stateVariable",variableName:"graphXmin"},graphXmax:{dependencyType:"stateVariable",variableName:"graphXmax"},graphYmin:{dependencyType:"stateVariable",variableName:"graphYmin"},graphYmax:{dependencyType:"stateVariable",variableName:"graphYmax"},flipFunction:{dependencyType:"stateVariable",variableName:"flipFunction"}}),definition:function({dependencyValues:e}){let t;if("bezier"===e.curveType)t=0,e.extrapolateBackward&&(t=-(e.nThroughPoints-1));else if(null!==e.parMinAttr)t=e.parMinAttr.stateValues.value.evaluate_to_constant(),Number.isFinite(t)||(t=NaN);else if("function"===e.curveType){let n,r,a=null;if(a=1===e.functionChild.length?e.functionChild[0].stateValues.domain:e.adapterSourceDomain,null!==a){a=a[0];try{t=me$3.fromAst(a.tree[1][1]).evaluate_to_constant(),Number.isFinite(t)||t===-1/0||(t=NaN)}catch(e){}}e.flipFunction?(r=e.graphYmax,n=e.graphYmin):(r=e.graphXmax,n=e.graphXmin),null!==r&&null!==n&&(t=void 0===t?n+.1*(n-r):Math.max(t,n+.1*(n-r))),void 0===t&&(t=-1/0)}else t=-10;return{setValue:{parMin:t}}}},t.domainForFunctions={returnDependencies:()=>({parMin:{dependencyType:"stateVariable",variableName:"parMin"},parMax:{dependencyType:"stateVariable",variableName:"parMax"}}),definition:({dependencyValues:e})=>({setValue:{domainForFunctions:[me$3.fromAst(["interval",["tuple",e.parMin,e.parMax],["tuple",!0,!0]])]}})},t.nThroughPoints={returnDependencies:()=>({through:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["nPoints"]}}),definition({dependencyValues:e}){let t=0;return null!==e.through&&(t=e.through.stateValues.nPoints),{setValue:{nThroughPoints:t}}}},t.nDimensions={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({through:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["nDimensions"]}}),definition:function({dependencyValues:e}){if(null!==e.through){return{setValue:{nDimensions:e.through.stateValues.nDimensions},checkForActualChange:{nDimensions:!0}}}return{setValue:{nDimensions:2}}}},t.throughPoints={public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"throughPointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,nDimensions:2,entryPrefixes:["throughPointX","throughPoint"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("throughPointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("throughPoints"===t)return 1===e.length?"throughPoint"+e[0]:`throughPointX${e[0]}_${e[1]}`;if("throughPoint"===t.slice(0,12)){let n=Number(t.slice(12));if(Number.isInteger(n)&&n>0)return`throughPointX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints,e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let[e,r]=n.split(","),a=Number(e)+1+"_"+(Number(r)+1);t[n]={through:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["pointX"+a]}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let[t,a]=r.split(","),i=Number(t)+1+"_"+(Number(a)+1),s=e[r].through;null!==s&&s.stateValues["pointX"+i]?n[r]=s.stateValues["pointX"+i]:n[r]=me$3.fromAst(0)}return{setValue:{throughPoints:n}}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n,initialChange:r,stateValues:a}){if(r&&!await a.draggable)return{success:!1};let i=[];for(let r in e.throughPoints){let[a,s]=r.split(","),o=Number(a)+1+"_"+(Number(s)+1);if(null===t[r].through||!t[r].through.stateValues["pointX"+o])return{success:!1};i.push({setDependency:n[r].through,desiredValue:e.throughPoints[r],childIndex:0,variableIndex:0})}return{success:!0,instructions:i}}},t.numericalThroughPoints={isArray:!0,entryPrefixes:["numericalThroughPoint"],forRenderer:!0,returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={throughPoint:{dependencyType:"stateVariable",variableName:"throughPoint"+(Number(n)+1)}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].throughPoint.map((e=>e.evaluate_to_constant()));t.every((e=>Number.isFinite(e)))||(t=Array(t.length).fill(NaN)),n[r]=t}return{setValue:{numericalThroughPoints:n}}}},t.haveBezierControls={forRenderer:!0,returnDependencies:()=>({controlChild:{dependencyType:"child",childGroups:["bezierControls"]}}),definition:({dependencyValues:e})=>({setValue:{haveBezierControls:e.controlChild.length>0}})},t.bezierControlsAlwaysVisible={forRenderer:!0,returnDependencies:()=>({controlChild:{dependencyType:"child",childGroups:["bezierControls"],variableNames:["alwaysVisible"]}}),definition:({dependencyValues:e})=>({setValue:{bezierControlsAlwaysVisible:e.controlChild.length>0&&e.controlChild[0].stateValues.alwaysVisible}})},t.vectorControlDirections={public:!0,shadowingInstructions:{createComponentOfType:"text"},isArray:!0,entryPrefixes:["vectorControlDirection"],forRenderer:!0,returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={controlChild:{dependencyType:"child",childGroups:["bezierControls"],variableNames:["direction"+(Number(n)+1)]}};return{dependenciesByKey:t,globalDependencies:{haveBezierControls:{dependencyType:"stateVariable",variableName:"haveBezierControls"}}}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].controlChild;t&&t.length>0?n[r]=t[0].stateValues["direction"+(Number(r)+1)]:n[r]="none"}return{setValue:{vectorControlDirections:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,dependencyValuesByKey:n,globalDependencyValues:r}){if(!r.haveBezierControls)return{success:!1};let a=[];for(let r in e.vectorControlDirections){let i=n[r].controlChild;i&&i.length>0&&a.push({setDependency:t[r].controlChild,desiredValue:e.vectorControlDirections[r],childIndex:0,variableIndex:0})}return{success:!0,instructions:a}}},t.hiddenControls={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},isArray:!0,entryPrefixes:["hiddenControl"],forRenderer:!0,returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={controlChild:{dependencyType:"child",childGroups:["bezierControls"],variableNames:["hiddenControl"+(Number(n)+1)]}};return{dependenciesByKey:t,globalDependencies:{haveBezierControls:{dependencyType:"stateVariable",variableName:"haveBezierControls"}}}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].controlChild;t&&t.length>0?n[r]=t[0].stateValues["hiddenControl"+(Number(r)+1)]:n[r]=!1}return{setValue:{hiddenControls:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,dependencyValuesByKey:n,globalDependencyValues:r}){if(!r.haveBezierControls)return{success:!1};let a=[];for(let r in e.hiddenControls){let i=n[r].controlChild;i&&i.length>0&&a.push({setDependency:t[r].controlChild,desiredValue:e.hiddenControls[r],childIndex:0,variableIndex:0})}return{success:!0,instructions:a}}},t.controlVectors={isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"controlVectorX"===e?[]:[["vector",{componentType:"mathList",isAttribute:"xs"}]]},entryPrefixes:["controlVectorX","controlVector"],nDimensions:3,stateVariablesDeterminingDependencies:["vectorControlDirections","nThroughPoints"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("controlVectorX"===e){let e=t.split("_").map((e=>Number(e)-1));return 3===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>eNumber(e)-1));return 2===e.length&&e.every((e=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>eString(e)+","+n)):[]:[String(e)+",0"]:[]}},returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints,2,e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=r.split(",").map((e=>Number(e))),a=e.map((e=>e+1)),i=a.join("_");n[r]={direction:{dependencyType:"stateVariable",variableName:"vectorControlDirection"+a[0]},controlChild:{dependencyType:"child",childGroups:["bezierControls"],variableNames:["control"+i]}};let s=e[0],o=t.vectorControlDirections[s],l=[];"none"===o?l=[s-1,s,s+1]:"previous"===o?l=[s,s+1]:"next"===o&&(l=[s-1,s]);for(let e of l)e>=0&&eNumber(e))),s=r.map((e=>e+1)),o=s.join("_"),l=r[0],u=r[1],c=n[i].direction;if("none"===c){let r,s,o=n[i]["throughPoint"+(l+1)];l>0&&(r=n[i]["throughPoint"+l]),lNumber(e))),s=i.map((e=>e+1)),o=s.join("_"),l=n[r].controlChild;if(l.length>0){l[0].stateValues["control"+o]&&a.push({setDependency:t[r].controlChild,desiredValue:e.controlVectors[r],childIndex:0,variableIndex:0})}}return{success:!0,instructions:a}}},t.numericalControlVectors={isArray:!0,entryPrefixes:["numericalControlVector"],forRenderer:!0,nDimensions:2,returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints,2],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=n.split(",").map((e=>Number(e))),r=e.map((e=>e+1)),a=r.join("_");t[n]={controlVector:{dependencyType:"stateVariable",variableName:"controlVector"+a}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].controlVector.map((e=>e.tree));n[r]=t}return{setValue:{numericalControlVectors:n}}}},t.controlPoints={isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"controlPointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},entryPrefixes:["controlPointX","controlPoint"],nDimensions:3,getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("controlPointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 3===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>eNumber(e)-1));return 2===e.length&&e.every((e=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>eString(e)+","+n)):[]:[String(e)+",0"]:[]}},returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints,2,e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=n.split(",").map((e=>Number(e))),r=e.map((e=>e+1)),a=r.join("_");t[n]={throughPointX:{dependencyType:"stateVariable",variableName:"throughPointX"+r[0]+"_"+r[2]},controlVectorX:{dependencyType:"stateVariable",variableName:"controlVectorX"+a}}}return{globalDependencies:{haveBezierControls:{dependencyType:"stateVariable",variableName:"haveBezierControls"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};for(let a of n)if(2!==e.nDimensions)r[a]=me$3.fromAst(NaN);else{let e=t[a].controlVectorX;if(e){let n=t[a].throughPointX.evaluate_to_constant();Number.isFinite(n)||(n=NaN),r[a]=me$3.fromAst(n+e.tree)}else r[a]=null}return{setValue:{controlPoints:r}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,dependencyValuesByKey:n,globalDependencyValues:r}){if(!r.haveBezierControls||2!==r.nDimensions)return{success:!1};let a=[];for(let r in e.controlPoints){if(n[r].controlVectorX){let i=n[r].throughPointX,s=e.controlPoints[r];s.tree&&(s=s.tree);let o=me$3.fromAst(["+",s,["-",i.tree]]);a.push({setDependency:t[r].controlVectorX,desiredValue:o})}}return{success:!0,instructions:a}}},t.numericalControlPoints={isArray:!0,entryPrefixes:["numericalControlPoint"],forRenderer:!0,nDimensions:2,returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints,2],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=n.split(",").map((e=>Number(e))),r=e.map((e=>e+1)),a=r.join("_");t[n]={controlPoint:{dependencyType:"stateVariable",variableName:"controlPoint"+a}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].controlPoint.map((e=>e.tree));n[r]=t}return{setValue:{numericalControlPoints:n}}}},t.splineCoeffs={isArray:!0,returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints-1],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1,r=e+1;t[n]={previousPoint:{dependencyType:"stateVariable",variableName:"numericalThroughPoint"+e},nextPoint:{dependencyType:"stateVariable",variableName:"numericalThroughPoint"+r},previousVector:{dependencyType:"stateVariable",variableName:"numericalControlVector"+e+"_2"},nextVector:{dependencyType:"stateVariable",variableName:"numericalControlVector"+r+"_1"}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].previousPoint,a=e[r].nextPoint,i=e[r].previousVector,s=e[r].nextVector,o=[];for(let e=0;e<2;e++)o.push(initCubicPoly(t[e],a[e],3*i[e],-3*s[e]));n[r]=o}return{setValue:{splineCoeffs:n}}}},t.extrapolateBackwardCoeffs={stateVariablesDeterminingDependencies:["extrapolateBackward"],additionalStateVariablesDefined:[{variableName:"extrapolateBackwardMode",public:!0,shadowingInstructions:{createComponentOfType:"text"}}],returnDependencies({stateValues:e}){let t={extrapolateBackward:{dependencyType:"stateVariable",variableName:"extrapolateBackward"},nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}};return e.extrapolateBackward&&(t.firstSplineCoeffs={dependencyType:"stateVariable",variableName:"splineCoeffs1"},t.graphXmin={dependencyType:"stateVariable",variableName:"graphXmin"},t.graphXmax={dependencyType:"stateVariable",variableName:"graphXmax"},t.graphYmin={dependencyType:"stateVariable",variableName:"graphYmin"},t.graphYmax={dependencyType:"stateVariable",variableName:"graphYmax"}),t},definition({dependencyValues:e}){if(!e.extrapolateBackward||!e.firstSplineCoeffs)return{setValue:{extrapolateBackwardCoeffs:null,extrapolateBackwardMode:""}};let t=e.firstSplineCoeffs[0],n=e.firstSplineCoeffs[1],r=t[0],a=t[1],i=2*t[2],s=n[0],o=n[1],l=a*a+o*o,u=(o*i-a*(2*n[2]))/(l*l);if(Math.abs(u)<1e-12||Math.abs(a)<1e-12||Math.abs(o)<1e-12){let t=a,n=o;if(null!==e.graphXmin&&null!==e.graphXmax&&null!==e.graphYmin&&null!==e.graphYmax){let r=e.graphXmax-e.graphXmin,a=e.graphYmax-e.graphYmin,i=e.nThroughPoints-1,s=r/i/Math.abs(t),o=a/i/Math.abs(n),l=Math.min(s,o);l>1&&(t*=l,n*=l)}return{setValue:{extrapolateBackwardCoeffs:[[r,t,0],[s,n,0]],extrapolateBackwardMode:"line"}}}let c=o*u,p=-a*u;if(c*a>0){let t=c/p,n=(1+t*t)**2,i=a;if(null!==e.graphXmin&&null!==e.graphXmax&&null!==e.graphYmin&&null!==e.graphYmax){let r=e.graphXmax-e.graphXmin,a=e.graphYmax-e.graphYmin,s=e.nThroughPoints-1,o=r/s,l=1/0;if(0!==p){let e=p*n/2*s*s,r=-t*s,i=Math.sqrt(r*r+4*Math.abs(e)*a);l=(Math.abs(r)+i)/(2*Math.abs(e))}let u=Math.min(o,l);u>Math.abs(i)&&(i*=u/Math.abs(i))}return{setValue:{extrapolateBackwardCoeffs:[[r,i,0],[s,-i*t,p*i*i*n/2]],extrapolateBackwardMode:"parabolaVertical"}}}{let t=p/c,n=(1+t*t)**2,a=o;if(null!==e.graphXmin&&null!==e.graphXmax&&null!==e.graphYmin&&null!==e.graphYmax){let r=e.graphXmax-e.graphXmin,i=e.graphYmax-e.graphYmin,s=e.nThroughPoints-1,o=i/s,l=1/0;if(0!==c){let e=c*n/2*s*s,a=-t*s,i=Math.sqrt(a*a+4*Math.abs(e)*r);l=(Math.abs(a)+i)/(2*Math.abs(e))}let u=Math.min(l,o);u>Math.abs(a)&&(a*=u/Math.abs(a))}return{setValue:{extrapolateBackwardCoeffs:[[r,-a*t,c*a*a*n/2],[s,a,0]],extrapolateBackwardMode:"parabolaHorizontal"}}}}},t.extrapolateForwardCoeffs={stateVariablesDeterminingDependencies:["nThroughPoints","extrapolateForward"],additionalStateVariablesDefined:[{variableName:"extrapolateForwardMode",public:!0,shadowingInstructions:{createComponentOfType:"text"}}],returnDependencies({stateValues:e}){let t={extrapolateForward:{dependencyType:"stateVariable",variableName:"extrapolateForward"},nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}};return e.extrapolateForward&&e.nThroughPoints>=2&&(t.lastSplineCoeffs={dependencyType:"stateVariable",variableName:"splineCoeffs"+(e.nThroughPoints-1)},t.graphXmin={dependencyType:"stateVariable",variableName:"graphXmin"},t.graphXmax={dependencyType:"stateVariable",variableName:"graphXmax"},t.graphYmin={dependencyType:"stateVariable",variableName:"graphYmin"},t.graphYmax={dependencyType:"stateVariable",variableName:"graphYmax"}),t},definition({dependencyValues:e}){if(!e.extrapolateForward||!e.lastSplineCoeffs)return{setValue:{extrapolateForwardCoeffs:null,extrapolateForwardMode:""}};let t=e.lastSplineCoeffs[0],n=e.lastSplineCoeffs[1],r=t[0]+t[1]+t[2]+t[3],a=t[1]+2*t[2]+3*t[3],i=2*t[2]+6*t[3],s=n[0]+n[1]+n[2]+n[3],o=n[1]+2*n[2]+3*n[3],l=a*a+o*o,u=(o*i-a*(2*n[2]+6*n[3]))/(l*l);if(Math.abs(u)<1e-12||Math.abs(a)<1e-12||Math.abs(o)<1e-12){let t=a,n=o;if(null!==e.graphXmin&&null!==e.graphXmax&&null!==e.graphYmin&&null!==e.graphYmax){let r=e.graphXmax-e.graphXmin,a=e.graphYmax-e.graphYmin,i=e.nThroughPoints-1,s=r/i/Math.abs(t),o=a/i/Math.abs(n),l=Math.min(s,o);l>1&&(t*=l,n*=l)}return{setValue:{extrapolateForwardCoeffs:[[r,t,0],[s,n,0]],extrapolateForwardMode:"line"}}}let c=o*u,p=-a*u;if(c*a<0){let t=c/p,n=(1+t*t)**2,i=a;if(null!==e.graphXmin&&null!==e.graphXmax&&null!==e.graphYmin&&null!==e.graphYmax){let r=e.graphXmax-e.graphXmin,a=e.graphYmax-e.graphYmin,s=e.nThroughPoints-1,o=r/s,l=1/0;if(0!==p){let e=p*n/2*s*s,r=-t*s,i=Math.sqrt(r*r+4*Math.abs(e)*a);l=(Math.abs(r)+i)/(2*Math.abs(e))}let u=Math.min(o,l);u>Math.abs(i)&&(i*=u/Math.abs(i))}return{setValue:{extrapolateForwardCoeffs:[[r,i,0],[s,-i*t,p*i*i*n/2]],extrapolateForwardMode:"parabolaVertical"}}}{let t=p/c,n=(1+t*t)**2,a=o;if(null!==e.graphXmin&&null!==e.graphXmax&&null!==e.graphYmin&&null!==e.graphYmax){let r=e.graphXmax-e.graphXmin,i=e.graphYmax-e.graphYmin,s=e.nThroughPoints-1,o=i/s,l=1/0;if(0!==c){let e=c*n/2*s*s,a=-t*s,i=Math.sqrt(a*a+4*Math.abs(e)*r);l=(Math.abs(a)+i)/(2*Math.abs(e))}let u=Math.min(l,o);u>Math.abs(a)&&(a*=u/Math.abs(a))}return{setValue:{extrapolateForwardCoeffs:[[r,-a*t,c*a*a*n/2],[s,a,0]],extrapolateForwardMode:"parabolaHorizontal"}}}}},t.fs={isArray:!0,entryPrefixes:["f"],additionalStateVariablesDefined:[{variableName:"fDefinitions",isArray:!0,forRenderer:!0,entryPrefixes:["fDefinition"]}],public:!0,shadowingInstructions:{createComponentOfType:"function",addStateVariablesShadowingStateVariables:{fDefinitions:{stateVariableToShadow:"fDefinitions"},domain:{stateVariableToShadow:"domainForFunctions"}}},returnArraySizeDependencies:()=>({functionChildren:{dependencyType:"child",childGroups:["functions"]},curveType:{dependencyType:"stateVariable",variableName:"curveType"}}),returnArraySize:({dependencyValues:e})=>"bezier"===e.curveType?[2]:[Math.max(1,e.functionChildren.length)],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["numericalf","fDefinition"],childIndices:[n]}},0===Number(n)&&(t[n].fShadow={dependencyType:"stateVariable",variableName:"fShadow"},t[n].fDefinitionAdapted={dependencyType:"adapterSourceStateVariable",variableName:"fDefinition"});return{globalDependencies:{curveType:{dependencyType:"stateVariable",variableName:"curveType"},numericalThroughPoints:{dependencyType:"stateVariable",variableName:"numericalThroughPoints"},splineCoeffs:{dependencyType:"stateVariable",variableName:"splineCoeffs"},nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"},extrapolateBackward:{dependencyType:"stateVariable",variableName:"extrapolateBackward"},extrapolateBackwardCoeffs:{dependencyType:"stateVariable",variableName:"extrapolateBackwardCoeffs"},extrapolateForward:{dependencyType:"stateVariable",variableName:"extrapolateForward"},extrapolateForwardCoeffs:{dependencyType:"stateVariable",variableName:"extrapolateForwardCoeffs"}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){if("bezier"===e.curveType){let t={functionType:"bezier",nThroughPoints:e.nThroughPoints,numericalThroughPoints:e.numericalThroughPoints,splineCoeffs:e.splineCoeffs,extrapolateForward:e.extrapolateForward,extrapolateForwardCoeffs:e.extrapolateForwardCoeffs,extrapolateBackward:e.extrapolateBackward,extrapolateBackwardCoeffs:e.extrapolateBackwardCoeffs},n={},r={};return t.component=0,n[0]=returnBezierFunctions(t),r[0]=t,t={...t},t.component=1,n[1]=returnBezierFunctions(t),r[1]=t,{setValue:{fs:n,fDefinitions:r}}}let r={},a={};for(let e of n){let n=t[e].functionChild;1===n.length?(r[e]=n[0].stateValues.numericalf,a[e]=n[0].stateValues.fDefinition):0===Number(e)&&t[e].fShadow?(r[e]=t[e].fShadow,a[e]=t[e].fDefinitionAdapted):(r[e]=()=>0,a[e]={functionType:"zero"})}return{setValue:{fs:r,fDefinitions:a}}}},t.f={isAlias:!0,targetVariableName:"f1"},t.allXCriticalPoints={returnDependencies:()=>({splineCoeffs:{dependencyType:"stateVariable",variableName:"splineCoeffs"},fs:{dependencyType:"stateVariable",variableName:"fs"},curveType:{dependencyType:"stateVariable",variableName:"curveType"}}),definition({dependencyValues:e}){let t=[];if("bezier"!==e.curveType)return{setValue:{allXCriticalPoints:t}};let n=e.fs[0],r=e.fs[1],a=[],i=!1;for(let[t,n]of e.splineCoeffs.entries()){let e=n[0],r=3*e[3],s=2*e[2],o=e[1];if(Math.abs(r)<1e-14){i=addTimePointBezier({t:-o/s,ind:t,ts:a,ignoreLeft:i})}else{let e=s*s-4*r*o;if(0==e){i=addTimePointBezier({t:-s/(2*r),ind:t,ts:a,ignoreLeft:i})}else if(e>0){let n=Math.sqrt(e),o=[(-s-n)/(2*r),(-s+n)/(2*r)];r<0&&(o=[o[1],o[0]]);let l=!1;for(let e of o){addTimePointBezier({t:e,ind:t,ts:a,ignoreLeft:i})&&(l=!0)}i=l}else i=!1}}for(let e of a)t.push([n(e),r(e)]);return{setValue:{allXCriticalPoints:t}}}},t.nXCriticalPoints={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({allXCriticalPoints:{dependencyType:"stateVariable",variableName:"allXCriticalPoints"}}),definition:({dependencyValues:e})=>({setValue:{nXCriticalPoints:e.allXCriticalPoints.length}})},t.xCriticalPoints={public:!0,shadowingInstructions:{createComponentOfType:"number",returnWrappingComponents:e=>"xCriticalPointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,nDimensions:2,entryPrefixes:["xCriticalPointX","xCriticalPoint"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("xCriticalPointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("xCriticalPoints"===t)return 1===e.length?"xCriticalPoint"+e[0]:`xCriticalPointX${e[0]}_${e[1]}`;if("xCriticalPoint"===t.slice(0,14)){let n=Number(t.slice(14));if(Number.isInteger(n)&&n>0)return`xCriticalPointX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nXCriticalPoints:{dependencyType:"stateVariable",variableName:"nXCriticalPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nXCriticalPoints,2],returnArrayDependenciesByKey:()=>({globalDependencies:{allXCriticalPoints:{dependencyType:"stateVariable",variableName:"allXCriticalPoints"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n=0;n({splineCoeffs:{dependencyType:"stateVariable",variableName:"splineCoeffs"},fs:{dependencyType:"stateVariable",variableName:"fs"},curveType:{dependencyType:"stateVariable",variableName:"curveType"}}),definition({dependencyValues:e}){let t=[];if("bezier"!==e.curveType)return{setValue:{allYCriticalPoints:t}};let n=e.fs[0],r=e.fs[1],a=[],i=!1;for(let[t,n]of e.splineCoeffs.entries()){let e=n[1],r=3*e[3],s=2*e[2],o=e[1];if(Math.abs(r)<1e-14){i=addTimePointBezier({t:-o/s,ind:t,ts:a,ignoreLeft:i})}else{let e=s*s-4*r*o;if(0==e){i=addTimePointBezier({t:-s/(2*r),ind:t,ts:a,ignoreLeft:i})}else if(e>0){let n=Math.sqrt(e),o=[(-s-n)/(2*r),(-s+n)/(2*r)];r<0&&(o=[o[1],o[0]]);let l=!1;for(let e of o){addTimePointBezier({t:e,ind:t,ts:a,ignoreLeft:i})&&(l=!0)}i=l}else i=!1}}for(let e of a)t.push([n(e),r(e)]);return{setValue:{allYCriticalPoints:t}}}},t.nYCriticalPoints={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({allYCriticalPoints:{dependencyType:"stateVariable",variableName:"allYCriticalPoints"}}),definition:({dependencyValues:e})=>({setValue:{nYCriticalPoints:e.allYCriticalPoints.length}})},t.yCriticalPoints={public:!0,shadowingInstructions:{createComponentOfType:"number",returnWrappingComponents:e=>"yCriticalPointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,nDimensions:2,entryPrefixes:["yCriticalPointX","yCriticalPoint"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("yCriticalPointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("yCriticalPoints"===t)return 1===e.length?"yCriticalPoint"+e[0]:`yCriticalPointX${e[0]}_${e[1]}`;if("yCriticalPoint"===t.slice(0,14)){let n=Number(t.slice(14));if(Number.isInteger(n)&&n>0)return`yCriticalPointX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nYCriticalPoints:{dependencyType:"stateVariable",variableName:"nYCriticalPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nYCriticalPoints,2],returnArrayDependenciesByKey:()=>({globalDependencies:{allYCriticalPoints:{dependencyType:"stateVariable",variableName:"allYCriticalPoints"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n=0;n({splineCoeffs:{dependencyType:"stateVariable",variableName:"splineCoeffs"},fs:{dependencyType:"stateVariable",variableName:"fs"},curveType:{dependencyType:"stateVariable",variableName:"curveType"}}),definition({dependencyValues:e}){let t=[];if("bezier"!==e.curveType)return{setValue:{allCurvatureChangePoints:t}};let n=e.fs[0],r=e.fs[1],a=[],i=!1;for(let[t,n]of e.splineCoeffs.entries()){let[e,r,s,o]=n[0],[l,u,c,p]=n[1],d=3*(s*p-c*o),m=3*(r*p-u*o),h=r*c-u*s;if(Math.abs(d)<1e-14){i=addTimePointBezier({t:-h/m,ind:t,ts:a,ignoreLeft:i})}else{let e=m*m-4*d*h;if(0==e){i=addTimePointBezier({t:-m/(2*d),ind:t,ts:a,ignoreLeft:i})}else if(e>0){let n=Math.sqrt(e),r=[(-m-n)/(2*d),(-m+n)/(2*d)];d<0&&(r=[r[1],r[0]]);let s=!1;for(let e of r){addTimePointBezier({t:e,ind:t,ts:a,ignoreLeft:i})&&(s=!0)}i=s}else i=!1}}for(let e of a)t.push([n(e),r(e)]);return{setValue:{allCurvatureChangePoints:t}}}},t.nCurvatureChangePoints={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({allCurvatureChangePoints:{dependencyType:"stateVariable",variableName:"allCurvatureChangePoints"}}),definition:({dependencyValues:e})=>({setValue:{nCurvatureChangePoints:e.allCurvatureChangePoints.length}})},t.curvatureChangePoints={public:!0,shadowingInstructions:{createComponentOfType:"number",returnWrappingComponents:e=>"curvatureChangePointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,nDimensions:2,entryPrefixes:["curvatureChangePointX","curvatureChangePoint"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("curvatureChangePointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("curvatureChangePoints"===t)return 1===e.length?"curvatureChangePoint"+e[0]:`curvatureChangePointX${e[0]}_${e[1]}`;if("curvatureChangePoint"===t.slice(0,20)){let n=Number(t.slice(20));if(Number.isInteger(n)&&n>0)return`curvatureChangePointX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nCurvatureChangePoints:{dependencyType:"stateVariable",variableName:"nCurvatureChangePoints"}}),returnArraySize:({dependencyValues:e})=>[e.nCurvatureChangePoints,2],returnArrayDependenciesByKey:()=>({globalDependencies:{allCurvatureChangePoints:{dependencyType:"stateVariable",variableName:"allCurvatureChangePoints"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n=0;n({nearestPointAsCurvePrelim:{dependencyType:"stateVariable",variableName:"nearestPointAsCurvePrelim"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["nearestPointAsCurve"]},adapterSourceValue:{dependencyType:"adapterSourceStateVariable",variableName:"nearestPointAsCurve"}}),definition({dependencyValues:e,usedDefault:t}){let n=e.nearestPointAsCurvePrelim;return t.nearestPointAsCurvePrelim&&(e.functionChild.length>0?n=e.functionChild[0].stateValues.nearestPointAsCurve:null!==e.adapterSourceValue&&(n=e.adapterSourceValue)),{setValue:{nearestPointAsCurve:n}}}},t.nearestPoint={returnDependencies:()=>({curveType:{dependencyType:"stateVariable",variableName:"curveType"},fs:{dependencyType:"stateVariable",variableName:"fs"},flipFunction:{dependencyType:"stateVariable",variableName:"flipFunction"},nDiscretizationPoints:{dependencyType:"stateVariable",variableName:"nDiscretizationPoints"},parMin:{dependencyType:"stateVariable",variableName:"parMin"},parMax:{dependencyType:"stateVariable",variableName:"parMax"},periodic:{dependencyType:"stateVariable",variableName:"periodic"},graphXmin:{dependencyType:"stateVariable",variableName:"graphXmin"},graphXmax:{dependencyType:"stateVariable",variableName:"graphXmax"},graphYmin:{dependencyType:"stateVariable",variableName:"graphYmin"},graphYmax:{dependencyType:"stateVariable",variableName:"graphYmax"},nearestPointAsCurve:{dependencyType:"stateVariable",variableName:"nearestPointAsCurve"}}),definition({dependencyValues:t}){let n=null;return"function"===t.curveType?n=getNearestPointFunctionCurve({dependencyValues:t,numerics:e}):["parameterization","bezier"].includes(t.curveType)&&(n=getNearestPointParametrizedCurve({dependencyValues:t,numerics:e})),{setValue:{nearestPoint:n}}}},t}async moveControlVector({controlVector:e,controlVectorInds:t,transient:n,actionId:r}){let a={[t+",0"]:me$3.fromAst(e[0]),[t+",1"]:me$3.fromAst(e[1])};return n?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"controlVectors",value:a,sourceInformation:{controlVectorMoved:t}}],transient:n,actionId:r}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"controlVectors",value:a,sourceInformation:{controlVectorMoved:t}}],actionId:r,event:{verb:"interacted",object:{componentId:this.componentName},result:{["controlVector"+t.join("_")]:e}}})}async moveThroughPoint({throughPoint:e,throughPointInd:t,transient:n,actionId:r}){let a={[t+",0"]:me$3.fromAst(e[0]),[t+",1"]:me$3.fromAst(e[1])};return n?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"throughPoints",value:a,sourceInformation:{throughPointMoved:t}}],transient:n,actionId:r}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"throughPoints",value:a,sourceInformation:{throughPointMoved:t}}],actionId:r,event:{verb:"interacted",object:{componentId:this.componentName},result:{["throughPoint"+t]:e}}})}async changeVectorControlDirection({direction:e,throughPointInd:t,actionId:n}){return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"vectorControlDirection",value:{[t]:e}}],actionId:n})}switchCurve(){}async curveClicked({actionId:e,name:t}){await this.coreFunctions.triggerChainedActions({triggeringAction:"click",componentName:t}),this.coreFunctions.resolveAction({actionId:e})}async mouseDownOnCurve({actionId:e,name:t}){await this.coreFunctions.triggerChainedActions({triggeringAction:"down",componentName:t}),this.coreFunctions.resolveAction({actionId:e})}}function getNearestPointFunctionCurve({dependencyValues:e,numerics:t}){let n=e.flipFunction,r=e.fs[0],a=e.nDiscretizationPoints,i=e.parMax,s=e.parMin;return function({variables:o,scales:l}){let u,c,p,d,m=o.x1?.evaluate_to_constant(),h=o.x2?.evaluate_to_constant(),f=l[0],y=l[1];if(s!==-1/0){if(u=s,c=r(s),!Number.isFinite(c)){let e=.99999*s+1e-5*i,t=r(e);Number.isFinite(t)&&(u=e,c=t)}if(n){let e=u;u=c,c=e}}if(i!==1/0){if(p=i,d=r(i),!Number.isFinite(d)){let e=1e-5*s+.99999*i,t=r(e);Number.isFinite(t)&&(p=e,d=t)}if(n){let e=p;p=d,d=e}}if(!e.nearestPointAsCurve||!Number.isFinite(m)||!Number.isFinite(h)){let e,t;if(n?(t=h,e=r(t)):(e=m,t=r(e)),!Number.isFinite(e)||!Number.isFinite(t)){let r,a;n?(r=Math.abs(s-h),a=Math.abs(i-h)):(r=Math.abs(s-m),a=Math.abs(i-m)),re.evaluate_to_constant())),a)l=a.map((e=>e.evaluate_to_constant())),s=n?n.map((e=>e.evaluate_to_constant())):[2*o[0]-l[0],2*o[1]-l[1]];else{if(!n)return{coordsNumeric:[me$3.fromAst(NaN),me$3.fromAst(NaN)],numericEntries:!1};s=n.map((e=>e.evaluate_to_constant())),l=[2*o[0]-s[0],2*o[1]-s[1]]}let c=[];if("centripetal"===i){let n=u(s,o),r=u(o,l);n=Math.sqrt(n),r=Math.sqrt(r),rme$3.fromAst(e)));return{coordsNumeric:p,numericEntries:Number.isFinite(c[0])&&Number.isFinite(c[1])}}function initCubicPoly(e,t,n,r){return[e,n,-3*e+3*t-2*n-r,2*e-2*t+n+r]}function addTimePointBezier({t:e,ind:t,ts:n,ignoreLeft:r=!1}){const a=1e-14;let i=!1;return e>=a?e<=.99999999999999?n.push(t+e):e<1.00000000000001&&(n.push(t+1),i=!0):e>-a&&!r&&n.push(t),i}class EquilibriumCurve extends Curve{static componentType="equilibriumCurve";static rendererType="curve";static createAttributesObject(){let e=super.createAttributesObject();return e.stable={createComponentOfType:"boolean",createStateVariable:"stable",defaultValue:!0,public:!0},e.switchable={createComponentOfType:"boolean",createStateVariable:"switchable",defaultValue:!1,public:!0,forRenderer:!0},e}static returnStateVariableDefinitions({numerics:e}){let t=super.returnStateVariableDefinitions({numerics:e});return t.dashed={forRenderer:!0,returnDependencies:()=>({stable:{dependencyType:"stateVariable",variableName:"stable"}}),definition:({dependencyValues:e})=>({setValue:{dashed:!e.stable}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setDependency:"stable",desiredValue:!e.dashed}]})},t}async switchCurve({actionId:e}){if(await this.stateValues.switchable)return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"stable",value:!this.stateValues.stable}],actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{stable:!this.stateValues.stable}}});this.coreFunctions.resolveAction({actionId:e})}}var DynamicalSystems=Object.freeze({__proto__:null,ODESystem:ODESystem,CobwebPolyline:CobwebPolyline,EquilibriumPoint:EquilibriumPoint,EquilibriumLine:EquilibriumLine,EquilibriumCurve:EquilibriumCurve});class Atom extends InlineComponent{static componentType="atom";static rendererType="math";static primaryStateVariableForDefinition="atomicNumberShadow";static createAttributesObject(){let e=super.createAttributesObject();return e.symbol={createComponentOfType:"text"},e.atomicNumber={createComponentOfType:"integer"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.atomicNumberShadow={defaultValue:null,hasEssential:!0,essentialVarName:"atomicNumber",returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{atomicNumberShadow:!0}}),inverseDefinition:async function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"atomicNumberShadow",value:e.atomicNumberShadow}]}}},e.dataForAtom={returnDependencies:()=>({fileContents:{dependencyType:"file",cid:"bafkreibilal4glrbpo7p7oodtwtnzkfhiylfoqa2td4ij6h6iqva57kzcy",fileType:"csv"},symbolAttr:{dependencyType:"attributeComponent",attributeName:"symbol",variableNames:["value"]},atomicNumberAttr:{dependencyType:"attributeComponent",attributeName:"atomicNumber",variableNames:["value"]},atomicNumberShadow:{dependencyType:"stateVariable",variableName:"atomicNumberShadow"}}),definition:function({dependencyValues:e}){let t=null,n=null;if(e.symbolAttr)t=e.symbolAttr.stateValues.value.toLowerCase();else if(e.atomicNumberAttr)n=e.atomicNumberAttr.stateValues.value;else{if(!e.atomicNumberShadow)return{setValue:{dataForAtom:null}};n=e.atomicNumberShadow}let r,a=e.fileContents.trim().split("\n");r=null!==n?n-1:["h","he","li","be","b","c","n","o","f","ne","na","mg","al","si","p","s","cl","ar","k","ca","sc","ti","v","cr","mn","fe","co","ni","cu","zn","ga","ge","as","se","br","kr","rb","sr","y","zr","nb","mo","tc","ru","rh","pd","ag","cd","in","sn","sb","te","i","xe","cs","ba","la","ce","pr","nd","pm","sm","eu","gd","tb","dy","ho","er","tm","yb","lu","hf","ta","w","re","os","ir","pt","au","hg","tl","pb","bi","po","at","rn","fr","ra","ac","th","pa","u","np","pu","am","cm","bk","cf","es","fm","md","no","lr","rf","db","sg","bh","hs","mt","ds","rg","cn","nh","fl","mc","lv","ts","og"].indexOf(t?.toLowerCase());let i=a.slice(1)[r];if(!i)return{setValue:{dataForAtom:null}};i=i.trim().split(",").map((e=>e.trim()));let s=a[0].trim().split(",").map((e=>e.trim())).map((e=>(['"',"'"].includes(e[0])&&e[e.length-1]===e[0]&&(e=e.substring(1,e.length-1).trim()),e))),o=s.length,l=["number","string","string","number","number","string","number","string","string","number","number","number","number","number","number","number","string"],u={};for(let e=0;e({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Atomic Number"]:null,{setValue:{atomicNumber:t}}}},e.symbol={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom.Symbol:null,{setValue:{symbol:t}}}},e.name={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom.Name:null,{setValue:{name:t}}}},e.group={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom.Group:null,{setValue:{group:t}}}},e.atomicMass={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Atomic Mass"]:null,{setValue:{atomicMass:t}}}},e.phaseAtSTP={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Phase at STP"]:null,{setValue:{phaseAtSTP:t}}}},e.chargeOfCommonIon={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Charge of Common Ion"]:null,{setValue:{chargeOfCommonIon:t}}}},e.metalCategory={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Metal/Nonmetal/Metalloid"]:null,{setValue:{metalCategory:t}}}},e.groupName={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Group Name"]:null,{setValue:{groupName:t}}}},e.period={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom.Period:null,{setValue:{period:t}}}},e.ionizationEnergy={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Ionization Energy"]:null,{setValue:{ionizationEnergy:t}}}},e.meltingPoint={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Melting Point"]:null,{setValue:{meltingPoint:t}}}},e.boilingPoint={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Boiling Point"]:null,{setValue:{boilingPoint:t}}}},e.atomicRadius={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Atomic Radius"]:null,{setValue:{atomicRadius:t}}}},e.density={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom.Density:null,{setValue:{density:t}}}},e.electronegativity={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom.Electronegativity:null,{setValue:{electronegativity:t}}}},e.electronConfiguration={public:!0,shadowingInstructions:{createComponentOfType:"electronConfiguration"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Electron Configuration"]:null,{setValue:{electronConfiguration:t}}}},e.orbitalDiagram={public:!0,shadowingInstructions:{createComponentOfType:"orbitalDiagram"},returnDependencies:()=>({electronConfiguration:{dependencyType:"stateVariable",variableName:"electronConfiguration"}}),definition({dependencyValues:e}){let t;return t=e.electronConfiguration?electronConfigurationToOrbitalDiagram(e.electronConfiguration):null,{setValue:{orbitalDiagram:t}}}},e.math={public:!0,shadowingInstructions:{createComponentOfType:"math"},returnDependencies:()=>({symbol:{dependencyType:"stateVariable",variableName:"symbol"}}),definition({dependencyValues:e}){let t;return t=e.symbol?["^",e.symbol]:"_",{setValue:{math:me$3.fromAst(t)}}}},e.latex={additionalStateVariablesDefined:[{variableName:"latexWithInputChildren",forRenderer:!0}],returnDependencies:()=>({symbol:{dependencyType:"stateVariable",variableName:"symbol"}}),definition({dependencyValues:e}){let t;return t=e.symbol?`\\text{${e.symbol}}`:"[\\text{Invalid Chemical Symbol}]",{setValue:{latex:t,latexWithInputChildren:[t]}}}},e}static adapters=["math","name",{stateVariable:"atomicNumber",componentType:"ion"}]}function electronConfigurationToOrbitalDiagram(e){let t=e.tree;if(!Array.isArray(t)||"*"!==t[0])return null;t=t.slice(1);let n=t.length/2;if(!Number.isInteger(n))return null;let r=[];for(let e=0;e0))return null;let a=t[2*e+1];if(!Array.isArray(a)||"^"!==a[0])return null;let i=a[1],s=a[2];if(!(["s","p","d","f"].includes(i)&&Number.isInteger(s)&&s>0))return null;let o,l=`${n}${i}`;o="s"===i?1:"p"===i?3:"d"===i?5:7;let u=Array(o).fill("");for(let e=0;e({}),definition:()=>({useEssentialOrDefaultValue:{atomicNumberShadow:!0}}),inverseDefinition:async function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"atomicNumberShadow",value:e.atomicNumberShadow}]}}},e.dataForAtom={returnDependencies:()=>({fileContents:{dependencyType:"file",cid:"bafkreibilal4glrbpo7p7oodtwtnzkfhiylfoqa2td4ij6h6iqva57kzcy",fileType:"csv"},symbolAttr:{dependencyType:"attributeComponent",attributeName:"symbol",variableNames:["value"]},atomicNumberAttr:{dependencyType:"attributeComponent",attributeName:"atomicNumber",variableNames:["value"]},atomChild:{dependencyType:"child",childGroups:["atoms"],variableNames:["atomicNumber"]},atomicNumberShadow:{dependencyType:"stateVariable",variableName:"atomicNumberShadow"}}),definition:function({dependencyValues:e}){let t=null,n=null;if(e.atomChild.length>0)n=e.atomChild[0].stateValues.atomicNumber;else if(e.symbolAttr)t=e.symbolAttr.stateValues.value.toLowerCase();else if(e.atomicNumberAttr)n=e.atomicNumberAttr.stateValues.value;else{if(!e.atomicNumberShadow)return{setValue:{dataForAtom:null}};n=e.atomicNumberShadow}let r,a=e.fileContents.trim().split("\n");r=null!==n?n-1:["h","he","li","be","b","c","n","o","f","ne","na","mg","al","si","p","s","cl","ar","k","ca","sc","ti","v","cr","mn","fe","co","ni","cu","zn","ga","ge","as","se","br","kr","rb","sr","y","zr","nb","mo","tc","ru","rh","pd","ag","cd","in","sn","sb","te","i","xe","cs","ba","la","ce","pr","nd","pm","sm","eu","gd","tb","dy","ho","er","tm","yb","lu","hf","ta","w","re","os","ir","pt","au","hg","tl","pb","bi","po","at","rn","fr","ra","ac","th","pa","u","np","pu","am","cm","bk","cf","es","fm","md","no","lr","rf","db","sg","bh","hs","mt","ds","rg","cn","nh","fl","mc","lv","ts","og"].indexOf(t?.toLowerCase());let i=a.slice(1)[r];if(!i)return{setValue:{dataForAtom:null}};i=i.trim().split(",").map((e=>e.trim()));let s=a[0].trim().split(",").map((e=>e.trim())).map((e=>(['"',"'"].includes(e[0])&&e[e.length-1]===e[0]&&(e=e.substring(1,e.length-1).trim()),e))),o=s.length,l=["number","string","string","number","number","string","number","string","string","number","number","number","number","number","number","number","string"],u={};for(let e=0;e({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Atomic Number"]:null,{setValue:{atomicNumber:t}}}},e.symbol={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom.Symbol:null,{setValue:{symbol:t}}}},e.charge={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"},chargeAttr:{dependencyType:"attributeComponent",attributeName:"charge",variableNames:["value"]}}),definition({dependencyValues:e}){let t;return e.chargeAttr?(t=e.chargeAttr.stateValues.value,Number.isFinite(t)||(t=0)):t=e.dataForAtom&&e.dataForAtom["Charge of Common Ion"]||0,{setValue:{charge:t}}}},e.name={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"},charge:{dependencyType:"stateVariable",variableName:"charge"},group:{dependencyType:"stateVariable",variableName:"group"},atomicNumber:{dependencyType:"stateVariable",variableName:"atomicNumber"}}),definition({dependencyValues:e}){let t;if(e.dataForAtom){if(t=e.dataForAtom.Name,e.charge<0){let e={Hydrogen:"Hydride",Oxygen:"Oxide",Sulfur:"Sulfide",Nitrogen:"Nitride",Phosphorus:"Phosphide",Carbon:"Carbide"},n=t.length;"ine"===t.substring(n-3,n)?t=t.substring(0,n-3)+"ide":t in e&&(t=e[t])}else if(e.charge>0&&(e.group>=3&&e.group<=12||101===e.group||102===e.group||[13,31,49,50,81,82,83,84].includes(e.atomicNumber))){let n="";switch(e.charge){case 1:n=" (I)";break;case 2:n=" (II)";break;case 3:n=" (III)";break;case 4:n=" (IV)";break;case 5:n=" (V)";break;case 6:n=" (VI)";break;case 7:n=" (VII)";break;case 8:n=" (VIII)"}t+=n}}else t=null;return{setValue:{name:t}}}},e.group={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom.Group:null,{setValue:{group:t}}}},e.metalCategory={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Metal/Nonmetal/Metalloid"]:null,{setValue:{metalCategory:t}}}},e.groupName={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Group Name"]:null,{setValue:{groupName:t}}}},e.period={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom.Period:null,{setValue:{period:t}}}},e.math={public:!0,shadowingInstructions:{createComponentOfType:"math"},returnDependencies:()=>({symbol:{dependencyType:"stateVariable",variableName:"symbol"},charge:{dependencyType:"stateVariable",variableName:"charge"}}),definition({dependencyValues:e}){let t;return e.symbol?(t=["^",e.symbol],-1===e.charge?t.push("-"):1===e.charge?t.push("+"):e.charge<0?t.push(Math.abs(e.charge)+"-"):e.charge>0&&t.push(Math.abs(e.charge)+"+")):t="_",{setValue:{math:me$3.fromAst(t)}}}},e.latex={additionalStateVariablesDefined:[{variableName:"latexWithInputChildren",forRenderer:!0}],returnDependencies:()=>({symbol:{dependencyType:"stateVariable",variableName:"symbol"},charge:{dependencyType:"stateVariable",variableName:"charge"}}),definition({dependencyValues:e}){let t;return e.symbol?(t=`\\text{${e.symbol}}`,-1===e.charge?t+="^-":1===e.charge?t+="^+":e.charge<0?t+=`^{${Math.abs(e.charge)}-}`:e.charge>0&&(t+=`^{${Math.abs(e.charge)}+}`)):t="[\\text{Invalid Chemical Symbol}]",{setValue:{latex:t,latexWithInputChildren:[t]}}}},e}static adapters=["math","name"]}class IonicCompound extends InlineComponent{static componentType="ionicCompound";static rendererType="math";static createAttributesObject(){let e=super.createAttributesObject();return e.symbol={createComponentOfType:"text"},e.atomicNumber={createComponentOfType:"integer"},e.charge={createComponentOfType:"integer"},e}static returnChildGroups(){return[{group:"ions",componentTypes:["ion"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.ionicCompound={returnDependencies:()=>({ionChildren:{dependencyType:"child",childGroups:["ions"],variableNames:["symbol","charge","atomicNumber","name"]}}),definition({dependencyValues:e}){let t=e.ionChildren.map((e=>e.stateValues.charge));if(2!==t.length)return console.warn("have not implemented ionic compound for anything other than two ions"),{setValue:{ionicCompound:null}};if(!(t[0]*t[1]<0))return console.warn("ionic compound implemented only for one cation and one anion"),{setValue:{ionicCompound:null}};let n=Math.abs(t[1]),r=Math.abs(t[0]),a=me$3.math.gcd(n,r);return n/=a,r/=a,{setValue:{ionicCompound:[{symbol:e.ionChildren[0].stateValues.symbol,atomicNumber:e.ionChildren[0].stateValues.atomicNumber,name:e.ionChildren[0].stateValues.name,charge:t[0],count:n},{symbol:e.ionChildren[1].stateValues.symbol,atomicNumber:e.ionChildren[1].stateValues.atomicNumber,name:e.ionChildren[1].stateValues.name,charge:t[1],count:r}]}}}},e.math={public:!0,shadowingInstructions:{createComponentOfType:"math"},returnDependencies:()=>({ionicCompound:{dependencyType:"stateVariable",variableName:"ionicCompound"}}),definition({dependencyValues:e}){let t;if(e.ionicCompound){t=[];for(let n of e.ionicCompound){let e=n.symbol;n.count>1&&(e=["_",e,n.count]),t.push(e)}t=t.length>1?["*",...t]:1===t.length?t[0]:"_"}else t="_";return{setValue:{math:me$3.fromAst(t)}}}},e.latex={additionalStateVariablesDefined:[{variableName:"latexWithInputChildren",forRenderer:!0}],returnDependencies:()=>({ionicCompound:{dependencyType:"stateVariable",variableName:"ionicCompound"}}),definition({dependencyValues:e}){let t;if(e.ionicCompound){t="";for(let n of e.ionicCompound)t+=`\\text{${n.symbol}}`,n.count>1&&(t+=`_{${n.count}}`)}else t="[\\text{Invalid Ionic Compound}]";return{setValue:{latex:t,latexWithInputChildren:[t]}}}},e}static adapters=["math"]}class ElectronConfiguration extends MathComponent{static componentType="electronConfiguration";static rendererType="math";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.latex={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({valueForDisplay:{dependencyType:"stateVariable",variableName:"valueForDisplay"}}),definition:function({dependencyValues:e,usedDefault:t}){let n;try{n=e.valueForDisplay.toLatex()}catch(e){n="_"}return n=n.replaceAll("\\,",""),n=n.replaceAll("\\cdot","~"),{setValue:{latex:n}}}},e}}class OrbitalDiagram extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="orbitalDiagram";static variableForPlainMacro="value";static createAttributesObject(){let e=super.createAttributesObject();return e.labels={createComponentOfType:"textList",createStateVariable:"labels",defaultValue:[]},e}static returnSugarInstructions(){return[{replacementFunction:function({matchedChildren:e}){return 1===e.length&&"string"!=typeof e[0]?{success:!1}:{success:!0,newChildren:[{componentType:"tupleList",children:e}]}}}]}static returnChildGroups(){return[{group:"tupleLists",componentTypes:["tupleList"]},{group:"orbitalDiagrams",componentTypes:["orbitalDiagram"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.value={defaultValue:[{orbitalText:"",boxes:[]}],public:!0,shadowingInstructions:{createComponentOfType:"orbitalDiagram"},forRenderer:!0,returnDependencies:()=>({orbitalDiagramChildren:{dependencyType:"child",childGroups:["orbitalDiagrams"],variableNames:["value"]},tupleListChildren:{dependencyType:"child",childGroups:["tupleLists"],variableNames:["maths"]},labels:{dependencyType:"stateVariable",variableName:"labels"}}),definition:function({dependencyValues:e}){return{setValue:{value:function(){function t(e){if("u"===e||"U"===e)return"U";if("d"===e||"D"===e)return"D";if("e"===e||"E"===e)return"";if(Array.isArray(e)&&"*"===e[0]){let t="";for(let n of e.slice(1))if("u"===n||"U"===n)t+="U";else{if("d"!==n&&"D"!==n)return"";t+="D"}return t}return""}if(1===e.orbitalDiagramChildren.length)return e.orbitalDiagramChildren[0].stateValues.value;let n=[];if(e.tupleListChildren[0]?.stateValues.maths.length>0){let r=e.tupleListChildren[0].stateValues.maths;for(let[a,i]of r.entries()){let r="";e.labels[a]&&(r=e.labels[a]);let s=[];if(Array.isArray(i.tree)&&"tuple"===i.tree[0])for(let e of i.tree.slice(1))s.push(t(e));else s.push(t(i.tree));n.push({orbitalText:r,boxes:s})}return n}return[{orbitalText:"",boxes:[]}]}()}}}},e}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class OrbitalDiagramInput extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{addRow:this.addRow.bind(this),removeRow:this.removeRow.bind(this),addBox:this.addBox.bind(this),removeBox:this.removeBox.bind(this),addUpArrow:this.addUpArrow.bind(this),addDownArrow:this.addDownArrow.bind(this),removeArrow:this.removeArrow.bind(this),updateRowText:this.updateRowText.bind(this),selectRow:this.selectRow.bind(this),selectBox:this.selectBox.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="orbitalDiagramInput";static variableForPlainMacro="value";static variableForPlainCopy="value";static createAttributesObject(){let e=super.createAttributesObject();return e.prefill={createComponentOfType:"orbitalDiagram",createStateVariable:"prefill",defaultValue:[]},e.prefillLabel={createComponentOfType:"textList",createStateVariable:"prefillLabel",defaultValue:[]},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.value={defaultValue:[{orbitalText:"",boxes:[]}],hasEssential:!0,forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"orbitalDiagram"},returnDependencies:()=>({prefill:{dependencyType:"stateVariable",variableName:"prefill"},prefillLabel:{dependencyType:"stateVariable",variableName:"prefillLabel"}}),definition:function({dependencyValues:e}){return{useEssentialOrDefaultValue:{value:{get defaultValue(){return function(){if(e.prefill?.length>0){let t=JSON.parse(JSON.stringify(e.prefill));for(let[n,r]of t.entries())e.prefillLabel[n]&&(r.orbitalText=e.prefillLabel[n]);return t}return[{orbitalText:"",boxes:[]}]}()}}}}},inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"value",value:e.value}]})},e.rows={public:!0,shadowingInstructions:{createComponentOfType:"orbitalDiagram"},forRenderer:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:({dependencyValues:e})=>({setValue:{rows:[...e.value].reverse()}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setDependency:"value",desiredValue:[...e.rows].reverse()}]})},e.numRows={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({rows:{dependencyType:"stateVariable",variableName:"rows"}}),definition:function({dependencyValues:e}){return{setValue:{numRows:e.rows.length}}}},e.selectedRowIndex={defaultValue:0,hasEssential:!0,forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({}),definition:function(){return{useEssentialOrDefaultValue:{selectedRowIndex:!0}}},async inverseDefinition({desiredStateVariableValues:e,stateValues:t}){let n=await t.numRows,r=e.selectedRowIndex;return r=Number.isFinite(r)?Math.min(n,Math.max(0,Math.round(r))):0,{success:!0,instructions:[{setEssentialValue:"selectedRowIndex",value:r}]}}},e.selectedBoxIndex={defaultValue:0,hasEssential:!0,forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({}),definition:function(){return{useEssentialOrDefaultValue:{selectedBoxIndex:!0}}},async inverseDefinition({desiredStateVariableValues:e}){let t=e.selectedBoxIndex;return t=Number.isFinite(t)?Math.max(0,Math.round(t)):0,{success:!0,instructions:[{setEssentialValue:"selectedBoxIndex",value:t}]}}},e}async addRow({actionId:e}){let t=await this.stateValues.rows,n=JSON.parse(JSON.stringify(t));t.length<20&&(n=[{orbitalText:"",boxes:[]},...t]);let r=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rows",value:n}];return-1!==await this.stateValues.selectedRowIndex-1&&r.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"selectedRowIndex",value:0}),-1!==await this.stateValues.selectedBoxIndex-1&&r.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"selectedBoxIndex",value:0}),await this.coreFunctions.performUpdate({updateInstructions:r,actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{rows:n}}})}async removeRow({actionId:e}){let t=await this.stateValues.rows,n=await this.stateValues.selectedRowIndex-1,r=JSON.parse(JSON.stringify(t));if(t.length>1){let e=t.length-1-n;-1===n&&(e=0),r.splice(e,1)}return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rows",value:r},{updateType:"updateValue",componentName:this.componentName,stateVariable:"selectedRowIndex",value:0},{updateType:"updateValue",componentName:this.componentName,stateVariable:"selectedBoxIndex",value:0}],actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{rows:r}}})}async addBox({actionId:e}){let t=await this.stateValues.rows,n=JSON.parse(JSON.stringify(t)),r=await this.stateValues.selectedRowIndex-1,a=t.length-r-1;-1===r&&(a=0),n[a].boxes.length<17&&n[a].boxes.push("");let i=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rows",value:n}];if(-1!==r){let e=0;i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"selectedBoxIndex",value:e})}return await this.coreFunctions.performUpdate({updateInstructions:i,actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{rows:n}}})}async removeBox({actionId:e}){let t=await this.stateValues.rows,n=JSON.parse(JSON.stringify(t)),r=await this.stateValues.selectedRowIndex-1,a=t.length-r-1;-1===r&&(a=0);let i=await this.stateValues.selectedBoxIndex-1,s=i;-1===i&&(s=n[a].boxes.length-1),n[a].boxes.splice(s,1);let o=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rows",value:n}];return-1!==i&&o.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"selectedBoxIndex",value:0}),await this.coreFunctions.performUpdate({updateInstructions:o,actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{rows:n}}})}async addUpArrow({actionId:e}){let t=await this.stateValues.rows,n=JSON.parse(JSON.stringify(t)),r=await this.stateValues.selectedRowIndex-1,a=t.length-r-1;-1===r&&(a=0);let i=await this.stateValues.selectedBoxIndex-1,s=i;-1===i&&(s=n[a].boxes.length-1),n[a].boxes.length>0&&n[a].boxes[s].length<3&&(n[a].boxes[s]=n[a].boxes[s]+"U");let o=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rows",value:n}];return await this.coreFunctions.performUpdate({updateInstructions:o,actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{rows:n}}})}async addDownArrow({actionId:e}){let t=await this.stateValues.rows,n=JSON.parse(JSON.stringify(t)),r=await this.stateValues.selectedRowIndex-1,a=t.length-r-1;-1===r&&(a=0);let i=await this.stateValues.selectedBoxIndex-1,s=i;-1===i&&(s=n[a].boxes.length-1),n[a].boxes.length>0&&n[a].boxes[s].length<3&&(n[a].boxes[s]=n[a].boxes[s]+"D");let o=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rows",value:n}];return await this.coreFunctions.performUpdate({updateInstructions:o,actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{rows:n}}})}async removeArrow({actionId:e}){let t=await this.stateValues.rows,n=JSON.parse(JSON.stringify(t)),r=await this.stateValues.selectedRowIndex-1,a=t.length-r-1;-1===r&&(a=0);let i=await this.stateValues.selectedBoxIndex-1,s=i;-1===i&&(s=n[a].boxes.length-1),n[a].boxes.length>0&&n[a].boxes[s].length>0&&(n[a].boxes[s]=n[a].boxes[s].slice(0,-1));let o=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rows",value:n}];return await this.coreFunctions.performUpdate({updateInstructions:o,actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{rows:n}}})}async updateRowText({newValue:e,actionId:t}){let n=await this.stateValues.rows,r=JSON.parse(JSON.stringify(n)),a=await this.stateValues.selectedRowIndex-1,i=n.length-a-1;-1===a&&(i=0),r[i].orbitalText=e;let s=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rows",value:r}];return await this.coreFunctions.performUpdate({updateInstructions:s,actionId:t,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{rows:r}}})}async selectRow({index:e,actionId:t}){return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"selectedRowIndex",value:e}],actionId:t,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{selectedRowIndex:e}}})}async selectBox({index:e,actionId:t}){return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"selectedBoxIndex",value:e}],actionId:t,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{selectedBoxIndex:e}}})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}var Chemistry=Object.freeze({__proto__:null,Atom:Atom,Ion:Ion,IonicCompound:IonicCompound,ElectronConfiguration:ElectronConfiguration,OrbitalDiagram:OrbitalDiagram,OrbitalDiagramInput:OrbitalDiagramInput});class FeedbackDefinition extends BaseComponent{static componentType="feedbackDefinition";static createAttributesObject(){let e=super.createAttributesObject();return e.code={createComponentOfType:"text"},e.text={createComponentOfType:"text"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.feedbackDefinition={returnDependencies:()=>({codeAttr:{dependencyType:"attributeComponent",attributeName:"code",variableNames:["value"]},textAttr:{dependencyType:"attributeComponent",attributeName:"text",variableNames:["value"]}}),definition({dependencyValues:e}){if(null!==e.codeAttr&&null!==e.textAttr){return{setValue:{feedbackDefinition:{[e.codeAttr.stateValues.value.toLowerCase()]:e.textAttr.stateValues.value}}}}return{setValue:{feedbackDefinition:null}}}},e}}class FeedbackDefinitions extends BaseComponent{static componentType="feedbackDefinitions";static rendererType=void 0;static returnChildGroups(){return[{group:"feedbackDefinition",componentTypes:["feedbackDefinition"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.value={returnDependencies:()=>({feedbackDefinitionChildren:{dependencyType:"child",childGroups:["feedbackDefinition"],variableNames:["feedbackDefinition"]}}),definition({dependencyValues:e}){let t={};for(let n of e.feedbackDefinitionChildren)n.stateValues.feedbackDefinition&&Object.assign(t,n.stateValues.feedbackDefinition);return{setValue:{value:t}}}},e}}var FeedbackDefinitions$1=Object.freeze({__proto__:null,FeedbackDefinition:FeedbackDefinition,FeedbackDefinitions:FeedbackDefinitions});class StyleDefinition extends BaseComponent{static componentType="styleDefinition";static rendererType=void 0;static createAttributesObject(){let e=super.createAttributesObject();e.styleNumber={createPrimitiveOfType:"number",createStateVariable:"styleNumber",defaultValue:1};for(let t in styleAttributes)e[t]={createComponentOfType:styleAttributes[t].componentType};return e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.styleDefinition={returnDependencies:function(){let e={};for(let t in styleAttributes)e[t]={dependencyType:"attributeComponent",attributeName:t,variableNames:["value"]};return e},definition:function({dependencyValues:e}){let t={};for(let n in styleAttributes)null!==e[n]&&(t[n]=e[n].stateValues.value,"string"==typeof t[n]&&(t[n]=t[n].toLowerCase()));return{setValue:{styleDefinition:t}}}},e}}class StyleDefinitions extends BaseComponent{static componentType="styleDefinitions";static rendererType=void 0;static returnChildGroups(){return[{group:"styleDefinition",componentTypes:["styleDefinition"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.value={returnDependencies:()=>({styleDefinitionChildren:{dependencyType:"child",childGroups:["styleDefinition"],variableNames:["styleNumber","styleDefinition"]}}),definition({dependencyValues:e}){let t={};for(let n of e.styleDefinitionChildren){let e=n.stateValues.styleNumber,r=t[e];r||(r=t[e]={}),Object.assign(r,n.stateValues.styleDefinition)}return{setValue:{value:t}}}},e}}var StyleDefinitions$1=Object.freeze({__proto__:null,StyleDefinition:StyleDefinition,StyleDefinitions:StyleDefinitions});class ComponentWithSelectableType extends BaseComponent{static componentType="_componentWithSelectableType";static rendererType=void 0;static includeBlankStringChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.type={createPrimitiveOfType:"string"},e}static returnSugarInstructions(){let e=[];return e.push({replacementFunction:function({matchedChildren:e,componentAttributes:t,parentAttributes:n}){let r=t.type;r||(r=n.type),r?["number","letters","math","text","boolean"].includes(r)||(console.warn(`Invalid type ${r}, setting type to number`),r="number"):r="number";let a="letters"===r?"text":r;return"text"!==a&&(e=e.filter((e=>"string"!=typeof e||""!==e.trim()))),{success:!0,newChildren:[{componentType:a,children:e}]}}}),e}static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.type={shadowVariable:!0,returnDependencies:()=>({type:{dependencyType:"doenetAttribute",attributeName:"type"},parentType:{dependencyType:"parentStateVariable",variableName:"type"}}),definition:function({dependencyValues:e,componentName:t}){let n=e.type;return n||(n=e.parentType),n?["number","letters","math","text","boolean"].includes(n)||(console.warn(`Invalid type ${n}, setting type to number`),n="number"):n="number",{setValue:{type:n}}}},e.value={public:!0,shadowingInstructions:{hasVariableComponentType:!0},shadowVariable:!0,returnDependencies:()=>({type:{dependencyType:"stateVariable",variableName:"type"},atMostOneChild:{dependencyType:"child",childGroups:["anything"],variableNames:["value"]}}),definition({dependencyValues:e}){let t;return t=e.atMostOneChild.length>0?e.atMostOneChild[0].stateValues.value:"text"===e.type||"letters"===e.type?"":"boolean"!==e.type&&("number"===e.type?NaN:me$3.fromAst("_")),{setValue:{value:t},setCreateComponentOfType:{value:e.type}}},inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t})=>t.atMostOneChild.length>0?{success:!0,instructions:[{setDependency:"atMostOneChild",desiredValue:e.value,childIndex:0,variableIndex:0}]}:{success:!1}},e}}class ComponentListWithSelectableType extends ComponentWithSelectableType{static componentType="_componentListWithSelectableType";static includeBlankStringChildren=!0;static removeBlankStringChildrenPostSugar=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.type={createPrimitiveOfType:"string"},e}static returnSugarInstructions(){let e=[];return e.push({replacementFunction:function({matchedChildren:e,componentAttributes:t,parentAttributes:n,isAttributeComponent:r=!1,createdFromMacro:a=!1,componentInfoObjects:i}){let s=t.type;s||(s=n.type),s?["number","letters","math","text","boolean"].includes(s)||(console.warn(`Invalid type ${s}, setting type to number`),s="number"):s="number";let o="letters"===s?"text":s;if(r&&!a){return returnGroupIntoComponentTypeSeparatedBySpaces({componentType:o})({matchedChildren:e})}return returnBreakStringsIntoComponentTypeBySpaces({componentType:o})({matchedChildren:e})}}),e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return delete e.value,e.nValues={additionalStateVariablesDefined:["childForValue"],returnDependencies:()=>({anythingForSelectedType:{dependencyType:"child",childGroups:["anything"],variableNames:["nValues"],variablesOptional:!0}}),definition({dependencyValues:e}){let t=0,n=[];for(let[r,a]of e.anythingForSelectedType.entries()){let e=Number.isInteger(a.stateValues.nValues)?a.stateValues.nValues:1;t+=e;for(let t=0;t({nValues:{dependencyType:"stateVariable",variableName:"nValues"}}),returnArraySize:({dependencyValues:e})=>[e.nValues],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=t.childForValue[r];n[r]={anythingForSelectedType:{dependencyType:"child",childGroups:["anything"],variableNames:["value","values"],childIndices:[e.child],variablesOptional:!0},valueIndex:{dependencyType:"value",value:e.valueIndex}}}return{globalDependencies:{type:{dependencyType:"stateVariable",variableName:"type"}},dependenciesByKey:n}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n,componentName:r}){let a={};for(let r of n)if(t[r].anythingForSelectedType&&1===t[r].anythingForSelectedType.length){let n,i=t[r].anythingForSelectedType[0];n=i.stateValues.values?i.stateValues.values[t[r].valueIndex]:i.stateValues.value,a[r]=convertValueToType(n,e.type)}return{setValue:{values:a},setCreateComponentOfType:{values:e.type}}}},e}}class ComponentListOfListsWithSelectableType extends ComponentWithSelectableType{static componentType="_componentListOfListsWithSelectableType";static createAttributesObject(){let e=super.createAttributesObject();return e.type={createPrimitiveOfType:"string"},e}static returnSugarInstructions(){let e=[];return e.push({replacementFunction:function({matchedChildren:e,componentAttributes:t,parentAttributes:n}){let r=breakEmbeddedStringsIntoParensPieces({componentList:e,removeParens:!0});if(!0!==r.success)return{success:!1};let a=t.type;return a||(a=n.type),a?["number","letters","math","text","boolean"].includes(a)||(console.warn(`Invalid type ${a}, setting type to number`),a="number"):a="number",{success:!0,newChildren:r.pieces.map((e=>({componentType:"_componentListWithSelectableType",attributes:{type:{primitive:a}},children:e})))}}}),e}static returnChildGroups(){return[{group:"lists",componentTypes:["_componentListWithSelectableType"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return delete e.value,e.nLists={returnDependencies:()=>({listChildren:{dependencyType:"child",childGroups:["lists"]}}),definition:({dependencyValues:e})=>({setValue:{nLists:e.listChildren.length}})},e.lists={isArray:!0,entryPrefixes:["list"],returnArraySizeDependencies:()=>({nLists:{dependencyType:"stateVariable",variableName:"nLists"}}),returnArraySize:({dependencyValues:e})=>[e.nLists],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={listChildren:{dependencyType:"child",childGroups:["lists"],variableNames:["values","type"],childIndices:[n]}};return{globalDependencies:{type:{dependencyType:"stateVariable",variableName:"type"}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};for(let a of n)if(t[a].listChildren&&1===t[a].listChildren.length){let n=t[a].listChildren[0];n.stateValues.type===e.type?r[a]=n.stateValues.values:r[a]=n.stateValues.values.map((t=>convertValueToType(t,e.type)))}return{setValue:{lists:r}}}},e}}function convertValueToType(e,t){if(Array.isArray(e)&&(e=e[0]),"number"===t){if(e instanceof me$3.class){let t=e.evaluate_to_constant();return Number.isFinite(t)||(t=NaN),t}return Number(e)}if("math"===t){if("string"==typeof e)try{return me$3.fromAst(textToAst$1.convert(e))}catch(e){}return convertValueToMathExpression(e)}return"boolean"===t?Boolean(e):String(e)}var ComponentWithSelectableType$1=Object.freeze({__proto__:null,ComponentWithSelectableType:ComponentWithSelectableType,ComponentListWithSelectableType:ComponentListWithSelectableType,ComponentListOfListsWithSelectableType:ComponentListOfListsWithSelectableType});class SideBySide extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="sideBySide";static renderChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.width={createComponentOfType:"_componentSize"},e.widths={createComponentOfType:"_componentSizeList"},e.margins={createComponentOfType:"_componentSizeList"},e.valign={createComponentOfType:"text"},e.valigns={createComponentOfType:"textList"},e}static returnChildGroups(){return[{group:"blocks",componentTypes:["_block"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nPanels={forRenderer:!0,returnDependencies:()=>({blockChildren:{dependencyType:"child",childGroups:["blocks"],skipComponentNames:!0}}),definition:({dependencyValues:e})=>({setValue:{nPanels:e.blockChildren.length},checkForActualChange:{nPanels:!0}})},e.essentialWidths={isArray:!0,entryPrefixes:["essentialWidth"],defaultValueByArrayKey:()=>null,hasEssential:!0,returnArraySizeDependencies:()=>({nPanels:{dependencyType:"stateVariable",variableName:"nPanels"}}),returnArraySize:({dependencyValues:e})=>[e.nPanels],returnArrayDependenciesByKey:()=>({}),arrayDefinitionByKey({arrayKeys:e}){let t={};for(let n of e)t[n]=!0;return{useEssentialOrDefaultValue:{essentialWidths:t}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e}){let t={};for(let n in e.essentialWidths)t[n]=e.essentialWidths[n];return{success:!0,instructions:[{setEssentialValue:"essentialWidths",value:t}]}}},e.allWidthsSpecified={additionalStateVariablesDefined:["widthsAbsolute"],returnDependencies:()=>({nPanels:{dependencyType:"stateVariable",variableName:"nPanels"},widthAttr:{dependencyType:"attributeComponent",attributeName:"width",variableNames:["componentSize"]},widthsAttr:{dependencyType:"attributeComponent",attributeName:"widths",variableNames:["nComponents","componentSizes"]},parentWidths:{dependencyType:"parentStateVariable",parentComponentType:"sbsGroup",variableName:"specifiedWidths"},parentWidthsAbsolute:{dependencyType:"parentStateVariable",parentComponentType:"sbsGroup",variableName:"widthsAbsolute"},essentialWidth:{dependencyType:"stateVariable",variableName:"essentialWidths"}}),definition({dependencyValues:e}){let t,n=[],r=null,a=!1;null!==e.widthsAttr?t=e.widthsAttr.stateValues.nComponents:null!==e.widthAttr?(t=e.nPanels,a=!0):t=0;for(let i=0;iNumber.isFinite(e)?e:null)),{setValue:{allWidthsSpecified:n,widthsAbsolute:r}}}},e.essentialMargins={isArray:!0,entryPrefixes:["essentialMargin"],hasEssential:!0,defaultValueByArrayKey:()=>null,returnArraySizeDependencies:()=>({}),returnArraySize:()=>[2],returnArrayDependenciesByKey:()=>({}),arrayDefinitionByKey({arrayKeys:e}){let t={};for(let n of e)t[n]=!0;return{useEssentialOrDefaultValue:{essentialMargins:t}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e}){let t={};for(let n in e.essentialMargins)t[n]=e.essentialMargins[n];return{success:!0,instructions:[{setEssentialValue:"essentialMargins",value:t}]}}},e.allMarginsSpecified={additionalStateVariablesDefined:["marginsAbsolute"],returnDependencies:()=>({nPanels:{dependencyType:"stateVariable",variableName:"nPanels"},marginsAttr:{dependencyType:"attributeComponent",attributeName:"margins",variableNames:["nComponents","componentSizes"]},parentMargins:{dependencyType:"parentStateVariable",parentComponentType:"sbsGroup",variableName:"specifiedMargins"},parentMarginsAbsolute:{dependencyType:"parentStateVariable",parentComponentType:"sbsGroup",variableName:"marginsAbsolute"},essentialMargins:{dependencyType:"stateVariable",variableName:"essentialMargins"}}),definition({dependencyValues:e}){let t=[],n=null;if(null===e.marginsAttr)if(e.parentMargins){n=e.parentMarginsAbsolute;for(let n=0;n<2;n++)null===e.essentialMargins[n]?t[n]=e.parentMargins[n]:t[n]=e.essentialMargins[n]}else for(let n=0;n<2;n++)t[n]=e.essentialMargins[n];else if(0===e.marginsAttr.stateValues.nComponents)for(let n=0;n<2;n++)t[n]=e.essentialMargins[n];else if(1===e.marginsAttr.stateValues.nComponents){let r=null;e.marginsAttr.stateValues.componentSizes[0]&&(r=e.marginsAttr.stateValues.componentSizes[0].size,Number.isFinite(r)||(r=null),n=Boolean(e.marginsAttr.stateValues.componentSizes[0].isAbsolute)),t=[r,r]}else{let r;if(n=!!e.marginsAttr.stateValues.componentSizes[0]&&Boolean(e.marginsAttr.stateValues.componentSizes[0].isAbsolute),r=!!e.marginsAttr.stateValues.componentSizes[1]&&Boolean(e.marginsAttr.stateValues.componentSizes[1].isAbsolute),r!==n)throw Error("SideBySide is not implemented for absolute measurements");t=e.marginsAttr.stateValues.componentSizes.slice(0,2).map((e=>e&&Number.isFinite(e.size)?e.size:null))}return{setValue:{allMarginsSpecified:t,marginsAbsolute:n}}}},e.absoluteMeasurements={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,returnDependencies:()=>({widthsAbsolute:{dependencyType:"stateVariable",variableName:"widthsAbsolute"},marginsAbsolute:{dependencyType:"stateVariable",variableName:"marginsAbsolute"}}),definition({dependencyValues:e}){let t;if(null===e.widthsAbsolute)t=null!==e.marginsAbsolute&&e.marginsAbsolute;else if(null===e.marginsAbsolute)t=e.widthsAbsolute;else{if(e.widthsAbsolute!==e.marginsAbsolute)throw Error("SideBySide is not implemented for absolute measurements");t=e.widthsAbsolute}if(!0===t)throw Error("SideBySide is not implemented for absolute measurements");return{setValue:{absoluteMeasurements:t}}}},e.allWidths={additionalStateVariablesDefined:["allMargins",{variableName:"gapWidth",public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0}],returnDependencies:()=>({nPanels:{dependencyType:"stateVariable",variableName:"nPanels"},allWidthsSpecified:{dependencyType:"stateVariable",variableName:"allWidthsSpecified"},allMarginsSpecified:{dependencyType:"stateVariable",variableName:"allMarginsSpecified"},absoluteMeasurements:{dependencyType:"stateVariable",variableName:"absoluteMeasurements"}}),definition({dependencyValues:e}){let t=0,n=[...e.allWidthsSpecified],r=[...e.allMarginsSpecified],a=0,i=0;for(let t=0;t=100){let t=100/(a+s);for(let r=0;r0){let t=(100-(a+s))/i;for(let r=0;r0){let t=(100-(a+s))/(o*e.nPanels);for(let e=0;e<2;e++)null===r[e]&&(r[e]=t)}else e.nPanels>1?t=(100-(a+s))/(e.nPanels-1):1===e.nPanels?r[1]=100-(r[0]+n[0]):console.warn("Invalid sideBySide, as it must have at least one block child");return{setValue:{allWidths:n,allMargins:r,gapWidth:t}}}},e.widths={public:!0,isArray:!0,shadowingInstructions:{createComponentOfType:"number"},entryPrefixes:["width"],forRenderer:!0,returnArraySizeDependencies:()=>({nPanels:{dependencyType:"stateVariable",variableName:"nPanels"}}),returnArraySize:({dependencyValues:e})=>[e.nPanels],returnArrayDependenciesByKey({arrayKeys:e}){let t={allWidths:{dependencyType:"stateVariable",variableName:"allWidths"},widthsAttr:{dependencyType:"attributeComponent",attributeName:"widths",variableNames:["nComponents"]},widthAttr:{dependencyType:"attributeComponent",attributeName:"width",variableNames:["componentSize"]},absoluteMeasurements:{dependencyType:"stateVariable",variableName:"absoluteMeasurements"}},n={};for(let t of e){let e=Number(t)+1;n[t]={widthsAttr:{dependencyType:"attributeComponent",attributeName:"widths",variableNames:[`componentSize${e}`]},essentialWidth:{dependencyType:"stateVariable",variableName:`essentialWidth${e}`}}}return{globalDependencies:t,dependenciesByKey:n}},arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t}){let n={};for(let r of t)n[r]=e.allWidths[r];return{setValue:{widths:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,dependencyValuesByKey:n,globalDependencyValues:r,arraySize:a}){let i,s=!1;null!==r.widthsAttr?i=r.widthsAttr.stateValues.nComponents:null!==r.widthAttr?(i=a[0],s=!0):i=0;let o=[];for(let n in e.widths){Number(n)({}),returnArraySize:()=>[2],returnArrayDependenciesByKey({arrayKeys:e}){let t={allMargins:{dependencyType:"stateVariable",variableName:"allMargins"},marginsAttr:{dependencyType:"attributeComponent",attributeName:"margins",variableNames:["componentSize1","componentSize2","nComponents"]},absoluteMeasurements:{dependencyType:"stateVariable",variableName:"absoluteMeasurements"}},n={};for(let t of e){let e=Number(t)+1;n[t]={essentialMargin:{dependencyType:"stateVariable",variableName:`essentialMargin${e}`}}}return{globalDependencies:t,dependenciesByKey:n}},arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t}){let n={};for(let r of t)n[r]=e.allMargins[r];return{setValue:{margins:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyNamesByKey:n}){let r=[];if(null===t.marginsAttr)for(let t in e.margins)r.push({setDependency:n[t].essentialMargin,desiredValue:e.margins[t]});else if(t.marginsAttr.stateValues.componentSize1&&Number.isFinite(t.marginsAttr.stateValues.componentSize1.size)){let n=1===t.marginsAttr.stateValues.nComponents;for(let a in e.margins)n?r.push({setDependency:"marginsAttr",desiredValue:{size:e.margins[a],isAbsolute:t.absoluteMeasurements},variableIndex:0}):r.push({setDependency:"marginsAttr",desiredValue:{size:e.margins[a],isAbsolute:t.absoluteMeasurements},variableIndex:a})}else"0"in e.margins?r.push({setDependency:"marginsAttr",desiredValue:{size:e.margins[0],isAbsolute:t.absoluteMeasurements},variableIndex:0}):r.push({setDependency:"marginsAttr",desiredValue:{size:e.margins[1],isAbsolute:t.absoluteMeasurements},variableIndex:0}),"1"in e.margins&&t.marginsAttr.stateValues.nComponents>1&&r.push({setDependency:"marginsAttr",desiredValue:{size:e.margins[1],isAbsolute:t.absoluteMeasurements},variableIndex:1});return{success:!0,instructions:r}}},e.essentialValigns={isArray:!0,entryPrefixes:["essentialValign"],defaultValueByArrayKey:()=>null,hasEssential:!0,returnArraySizeDependencies:()=>({nPanels:{dependencyType:"stateVariable",variableName:"nPanels"}}),returnArraySize:({dependencyValues:e})=>[e.nPanels],returnArrayDependenciesByKey:()=>({}),arrayDefinitionByKey({arrayKeys:e}){let t={};for(let n of e)t[n]=!0;return{useEssentialOrDefaultValue:{essentialValigns:t}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e}){let t={};for(let n in e.essentialValigns)t[n]=e.essentialValigns[n];return{success:!0,instructions:[{setEssentialValue:"essentialValigns",value:t}]}}},e.valigns={public:!0,isArray:!0,shadowingInstructions:{createComponentOfType:"text"},entryPrefixes:["valign"],forRenderer:!0,returnArraySizeDependencies:()=>({nPanels:{dependencyType:"stateVariable",variableName:"nPanels"}}),returnArraySize:({dependencyValues:e})=>[e.nPanels],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={valignsAttr:{dependencyType:"attributeComponent",attributeName:"valigns",variableNames:[`text${e}`]},parentValign:{dependencyType:"parentStateVariable",parentComponentType:"sbsGroup",variableName:`valign${e}`},parentValignAbsolute:{dependencyType:"parentStateVariable",parentComponentType:"sbsGroup",variableName:`valignAbsolute${e}`},essentialValign:{dependencyType:"stateVariable",variableName:`essentialValign${e}`}}}return{globalDependencies:{valignAttr:{dependencyType:"attributeComponent",attributeName:"valign",variableNames:["value"]},valignsAttr:{dependencyType:"attributeComponent",attributeName:"valigns",variableNames:["nComponents"]}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n,arraySize:r}){let a,i={},s=!1;null!==e.valignsAttr?a=e.valignsAttr.stateValues.nComponents:null!==e.valignAttr?(a=r[0],s=!0):a=0;for(let r of n){let n=Number(r);if(n({sideBySideChildren:{dependencyType:"child",childGroups:["sideBySides"],variableNames:["nPanels"]}}),definition:({dependencyValues:e})=>({setValue:{maxNPanelsPerRow:me$3.math.max(e.sideBySideChildren.map((e=>e.stateValues.nPanels)))},checkForActualChange:{maxNPanelsPerRow:!0}})},e.specifiedWidths={additionalStateVariablesDefined:[{variableName:"widthsAbsoluteArray",isArray:!0}],isArray:!0,entryPrefixes:["specifiedWidth"],hasEssential:!0,defaultValueByArrayKey:()=>null,returnArraySizeDependencies:()=>({maxNPanelsPerRow:{dependencyType:"stateVariable",variableName:"maxNPanelsPerRow"}}),returnArraySize:({dependencyValues:e})=>[e.maxNPanelsPerRow],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={widthsAttr:{dependencyType:"attributeComponent",attributeName:"widths",variableNames:[`componentSize${e}`]}}}return{globalDependencies:{widthAttr:{dependencyType:"attributeComponent",attributeName:"width",variableNames:["componentSize"]},widthsAttr:{dependencyType:"attributeComponent",attributeName:"widths",variableNames:["nComponents"]}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n,arraySize:r}){let a,i={},s={},o={},l=!1;null!==e.widthsAttr?a=e.widthsAttr.stateValues.nComponents:null!==e.widthAttr?(a=r[0],l=!0):a=0;for(let r of n){let n=Number(r);if(n0&&(u.useEssentialOrDefaultValue={specifiedWidths:s}),u},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,globalDependencyValues:n,stateValues:r,arraySize:a}){let i,s=!1;null!==n.widthsAttr?i=n.widthsAttr.stateValues.nComponents:null!==n.widthAttr?(i=a[0],s=!0):i=0;let o=[];for(let n in e.specifiedWidths){Number(n)({widthsAbsoluteArray:{dependencyType:"stateVariable",variableName:"widthsAbsoluteArray"}}),definition({dependencyValues:e}){let t=null;for(let n in e.widthsAbsoluteArray){let r=e.widthsAbsoluteArray[n];if(null!==r)if(r=Boolean(r),null===t)t=r;else if(t!==r)throw Error("SbsGroup is not implemented for absolute measurements")}return{setValue:{widthsAbsolute:t}}}},e.specifiedMargins={additionalStateVariablesDefined:[{variableName:"marginsAbsoluteArray",isArray:!0,entryPrefixes:["marginAbsolute"]}],isArray:!0,entryPrefixes:["specifiedMargin"],hasEssential:!0,defaultValueByArrayKey:()=>null,returnArraySizeDependencies:()=>({}),returnArraySize:()=>[2],returnArrayDependenciesByKey:({arrayKeys:e})=>({globalDependencies:{marginsAttr:{dependencyType:"attributeComponent",attributeName:"margins",variableNames:["componentSize1","componentSize2","nComponents"]}}}),arrayDefinitionByKey({dependencyValuesByKey:e,globalDependencyValues:t,arrayKeys:n}){let r={},a={},i={};if(null===t.marginsAttr||0===t.marginsAttr.stateValues.nComponents)for(let e of n)a[e]=!0,i[e]=null;else if(1===t.marginsAttr.stateValues.nComponents){let e=null,a=null;t.marginsAttr.stateValues.componentSize1&&(e=t.marginsAttr.stateValues.componentSize1.size,Number.isFinite(e)||(e=null),a=Boolean(t.marginsAttr.stateValues.componentSize1.isAbsolute));for(let t of n)r[t]=e,i[t]=a}else for(let e of n)if(t.marginsAttr.stateValues[`componentSize${Number(e)+1}`]){let n=t.marginsAttr.stateValues[`componentSize${Number(e)+1}`].size;Number.isFinite(n)||(n=null);let a=Boolean(t.marginsAttr.stateValues[`componentSize${Number(e)+1}`].isAbsolute);r[e]=n,i[e]=a}let s={setValue:{marginsAbsoluteArray:i,specifiedMargins:r}};return Object.keys(a).length>0&&(s.useEssentialOrDefaultValue={specifiedMargins:a}),s},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,globalDependencyValues:n,stateValues:r}){let a=[];if(null===n.marginsAttr)a.push({setEssentialValue:"specifiedMargins",value:e.specifiedMargins});else if(n.marginsAttr.stateValues.componentSize1&&Number.isFinite(n.marginsAttr.stateValues.componentSize1.size)){let t=1===n.marginsAttr.stateValues.nComponents;for(let n in e.specifiedMargins)t?a.push({setDependency:"marginsAttr",desiredValue:{size:e.specifiedMargins[n],isAbsolute:await r.marginsAbsolute},variableIndex:0}):a.push({setDependency:"marginsAttr",desiredValue:{size:e.specifiedMargins[n],isAbsolute:await r.marginsAbsolute},variableIndex:n})}else"0"in e.specifiedMargins?a.push({setDependency:"marginsAttr",desiredValue:{size:e.specifiedMargins[0],isAbsolute:await r.marginsAbsolute},variableIndex:0}):a.push({setDependency:"marginsAttr",desiredValue:{size:e.specifiedMargins[1],isAbsolute:await r.marginsAbsolute},variableIndex:0}),"1"in e.specifiedMargins&&n.marginsAttr.stateValues.nComponents>1&&a.push({setDependency:"marginsAttr",desiredValue:{size:e.specifiedMargins[1],isAbsolute:await r.marginsAbsolute},variableIndex:1});return{success:!0,instructions:a}}},e.marginsAbsolute={returnDependencies:()=>({marginsAbsoluteArray:{dependencyType:"stateVariable",variableName:"marginsAbsoluteArray"}}),definition({dependencyValues:e}){let t=null;for(let n in e.marginsAbsoluteArray){let r=e.marginsAbsoluteArray[n];if(null!==r)if(r=Boolean(r),null===t)t=r;else if(t!==r)throw Error("SbsGroup is not implemented for absolute measurements")}return{setValue:{marginsAbsolute:t}}}},e.absoluteMeasurements={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({widthsAbsolute:{dependencyType:"stateVariable",variableName:"widthsAbsolute"},marginsAbsolute:{dependencyType:"stateVariable",variableName:"marginsAbsolute"}}),definition({dependencyValues:e}){let t;if(null===e.widthsAbsolute)t=null!==e.marginsAbsolute&&e.marginsAbsolute;else if(null===e.marginsAbsolute)t=e.widthsAbsolute;else{if(e.widthsAbsolute!==e.marginsAbsolute)throw Error("SbsGroup is not implemented for absolute measurements");t=e.widthsAbsolute}if(!0===t)throw Error("SbsGroup is not implemented for absolute measurements");return{setValue:{absoluteMeasurements:t}}}},e.allWidths={additionalStateVariablesDefined:["allMargins",{variableName:"gapWidth",public:!0,shadowingInstructions:{createComponentOfType:"number"}}],returnDependencies:()=>({maxNPanelsPerRow:{dependencyType:"stateVariable",variableName:"maxNPanelsPerRow"},specifiedWidths:{dependencyType:"stateVariable",variableName:"specifiedWidths"},specifiedMargins:{dependencyType:"stateVariable",variableName:"specifiedMargins"},absoluteMeasurements:{dependencyType:"stateVariable",variableName:"absoluteMeasurements"}}),definition({dependencyValues:e}){let t=0,n=[...e.specifiedWidths],r=[...e.specifiedMargins],a=0,i=0;for(let t=0;t=100){let t=100/(a+s);for(let r=0;r0){let t=(100-(a+s))/i;for(let r=0;r0){let t=(100-(a+s))/(o*e.maxNPanelsPerRow);for(let e=0;e<2;e++)null===r[e]&&(r[e]=t)}else e.maxNPanelsPerRow>1?t=(100-(a+s))/(e.maxNPanelsPerRow-1):1===e.maxNPanelsPerRow?r[1]=100-(r[0]+n[0]):console.warn("Invalid sideBySide, as it must have at least one block child");return{setValue:{allWidths:n,allMargins:r,gapWidth:t}}}},e.widths={public:!0,isArray:!0,shadowingInstructions:{createComponentOfType:"number"},entryPrefixes:["width"],returnArraySizeDependencies:()=>({maxNPanelsPerRow:{dependencyType:"stateVariable",variableName:"maxNPanelsPerRow"}}),returnArraySize:({dependencyValues:e})=>[e.maxNPanelsPerRow],returnArrayDependenciesByKey({arrayKeys:e}){let t={allWidths:{dependencyType:"stateVariable",variableName:"allWidths"}},n={};for(let t of e){let e=Number(t)+1;n[t]={specifiedWidth:{dependencyType:"stateVariable",variableName:`specifiedWidth${e}`}}}return{globalDependencies:t,dependenciesByKey:n}},arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t}){let n={};for(let r of t)n[r]=e.allWidths[r];return{setValue:{widths:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t}){let n=[];for(let r in e.widths)n.push({setDependency:t[r].specifiedWidth,desiredValue:e.widths[r],variableIndex:0});return{success:!0,instructions:n}}},e.margins={public:!0,isArray:!0,shadowingInstructions:{createComponentOfType:"number"},entryPrefixes:["margin"],returnArraySizeDependencies:()=>({}),returnArraySize:()=>[2],returnArrayDependenciesByKey({arrayKeys:e}){let t={allMargins:{dependencyType:"stateVariable",variableName:"allMargins"}},n={};for(let t of e){let e=Number(t)+1;n[t]={specifiedMargin:{dependencyType:"stateVariable",variableName:`specifiedMargin${e}`}}}return{globalDependencies:t,dependenciesByKey:n}},arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t}){let n={};for(let r of t)n[r]=e.allMargins[r];return{setValue:{margins:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t}){let n=[];for(let r in e.margins)n.push({setDependency:t[r].specifiedMargin,desiredValue:e.margins[r],variableIndex:0});return{success:!0,instructions:n}}},e.valigns={public:!0,isArray:!0,shadowingInstructions:{createComponentOfType:"text"},entryPrefixes:["valign"],hasEssential:!0,defaultValueByArrayKey:()=>"top",returnArraySizeDependencies:()=>({maxNPanelsPerRow:{dependencyType:"stateVariable",variableName:"maxNPanelsPerRow"}}),returnArraySize:({dependencyValues:e})=>[e.maxNPanelsPerRow],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={valignsAttr:{dependencyType:"attributeComponent",attributeName:"valigns",variableNames:[`text${e}`]}}}return{globalDependencies:{valignAttr:{dependencyType:"attributeComponent",attributeName:"valign",variableNames:["value"]},valignsAttr:{dependencyType:"attributeComponent",attributeName:"valigns",variableNames:["nComponents"]}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n,arraySize:r}){let a,i={},s={},o=!1;null!==e.valignsAttr?a=e.valignsAttr.stateValues.nComponents:null!==e.valignAttr?(a=r[0],o=!0):a=0;for(let r of n){let n=Number(r);if(n0&&(l.setValue={valigns:i}),Object.keys(s).length>0&&(l.useEssentialOrDefaultValue={valigns:s}),l},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,globalDependencyValues:n,arraySize:r}){let a,i=!1;null!==n.valignsAttr?a=n.valignsAttr.stateValues.nComponents:null!==n.valignAttr?(a=r[0],i=!0):a=0;let s=[];for(let n in e.valigns){let r=e.valigns[n].toLowerCase();["top","middle","bottom"].includes(r)&&(Number(n)({stringTextChildren:{dependencyType:"child",childGroups:["stringsTexts"],variableNames:["value"]},hChildren:{dependencyType:"child",childGroups:["hs"],variableNames:["value"]}}),definition({dependencyValues:e}){let t;if(e.hChildren.length>0)t=e.hChildren.map((e=>e.stateValues.value));else{let n="";for(let t of e.stringTextChildren)n+="string"==typeof t?t:t.stateValues.value;t=[n]}return{setValue:{terms:t}}}},e}}var Indexing=Object.freeze({__proto__:null,H:H$2,Idx:Idx});class Div extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="div";static rendererType="containerBlock";static renderChildren=!0;static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class Span extends InlineComponent{static componentType="span";static rendererType="containerInline";static renderChildren=!0;static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}}var Divisions=Object.freeze({__proto__:null,Div:Div,Span:Span});class Pre extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="pre";static renderChildren=!0;static includeBlankStringChildren=!0;static returnChildGroups(){return[{group:"allChildren",componentTypes:["_base"]}]}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class DisplayDoenetML extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="displayDoenetML";static rendererType="text";static includeBlankStringChildren=!0;static returnChildGroups(){return[{group:"allChildren",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.value={returnDependencies:()=>({childrenDoenetML:{dependencyType:"doenetML",displayOnlyChildren:!0}}),definition:({dependencyValues:e})=>({setValue:{value:e.childrenDoenetML}})},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:({dependencyValues:e})=>({setValue:{text:e.value}})},e}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}var Verbatim=Object.freeze({__proto__:null,Pre:Pre,DisplayDoenetML:DisplayDoenetML});class Paginator extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{setPage:this.setPage.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="paginator";static rendererType="containerBlock";static renderChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.initialPage={createComponentOfType:"integer",createStateVariable:"initialPage",defaultValue:1},e}static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nPages={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({children:{dependencyType:"child",childGroups:["anything"]}}),definition:({dependencyValues:e})=>({setValue:{nPages:e.children.length}})},e.currentPage={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,returnDependencies:()=>({initialPage:{dependencyType:"stateVariable",variableName:"initialPage"},nPages:{dependencyType:"stateVariable",variableName:"nPages"}}),definition:({dependencyValues:e})=>({useEssentialOrDefaultValue:{currentPage:{get defaultValue(){let t=e.initialPage;return Number.isInteger(t)?Math.max(1,Math.min(e.nPages,t)):1}}}}),async inverseDefinition({desiredStateVariableValues:e,stateValues:t,sourceInformation:n={}}){if(!n.fromSetPage)return{success:!1};let r=Number(e.currentPage);return Number.isInteger(r)?(r=Math.max(1,Math.min(await t.nPages,r)),{success:!0,instructions:[{setEssentialValue:"currentPage",value:r}]}):{success:!1}}},e.childIndicesToRender={returnDependencies:()=>({currentPage:{dependencyType:"stateVariable",variableName:"currentPage"}}),definition:({dependencyValues:e})=>({setValue:{childIndicesToRender:[e.currentPage-1]}}),markStale:()=>({updateRenderedChildren:!0})},e}async setPage({number:e,actionId:t}){if(!Number.isInteger(e))return void this.coreFunctions.resolveAction({actionId:t});let n=Math.max(1,Math.min(await this.stateValues.nPages,e)),r=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"currentPage",value:n,sourceInformation:{fromSetPage:!0}}];await this.coreFunctions.performUpdate({updateInstructions:r,actionId:t,event:{verb:"selected",object:{componentName:this.componentName,componentType:this.componentType},result:{response:n,responseText:n.toString()}}})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class PaginatorControls extends BlockComponent{constructor(e){super(e),this.externalActions={},Object.defineProperty(this.externalActions,"setPage",{enumerable:!0,get:async function(){let e=await this.stateValues.paginatorComponentName;return e?{componentName:e,actionName:"setPage"}:void 0}.bind(this)})}static componentType="paginatorControls";static renderChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.previousLabel={createComponentOfType:"text",createStateVariable:"previousLabel",defaultValue:"Previous",forRenderer:!0,public:!0},e.nextLabel={createComponentOfType:"text",createStateVariable:"nextLabel",defaultValue:"Next",forRenderer:!0,public:!0},e.pageLabel={createComponentOfType:"text",createStateVariable:"pageLabel",defaultValue:"Page",forRenderer:!0,public:!0},e.paginator={createTargetComponentNames:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.paginatorComponentName={returnDependencies:()=>({paginator:{dependencyType:"attributeTargetComponentNames",attributeName:"paginator"}}),definition({dependencyValues:e}){let t;return t=1===e.paginator?.length?e.paginator[0].absoluteName:null,{setValue:{paginatorComponentName:t}}}},e.currentPage={forRenderer:!0,stateVariablesDeterminingDependencies:["paginatorComponentName"],returnDependencies:({stateValues:e})=>e.paginatorComponentName?{paginatorPage:{dependencyType:"stateVariable",componentName:e.paginatorComponentName,variableName:"currentPage"}}:{},definition:({dependencyValues:e})=>"paginatorPage"in e?{setValue:{currentPage:e.paginatorPage}}:{setValue:{currentPage:1}}},e.nPages={forRenderer:!0,stateVariablesDeterminingDependencies:["paginatorComponentName"],returnDependencies:({stateValues:e})=>e.paginatorComponentName?{paginatorNPages:{dependencyType:"stateVariable",componentName:e.paginatorComponentName,variableName:"nPages"}}:{},definition:({dependencyValues:e})=>"paginatorNPages"in e?{setValue:{nPages:e.paginatorNPages}}:{setValue:{nPages:1}}},e}}var Paginator$1=Object.freeze({__proto__:null,Paginator:Paginator,PaginatorControls:PaginatorControls});class Input extends InlineComponent{static componentType="_input";static createAttributesObject(){let e=super.createAttributesObject();return e.collaborateGroups={createComponentOfType:"collaborateGroups",createStateVariable:"collaborateGroups",defaultValue:null,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nValues={returnDependencies:()=>({}),definition:()=>({setValue:{nValues:1}})},e.answerAncestor={returnDependencies:()=>({answerAncestor:{dependencyType:"ancestor",componentType:"answer",variableNames:["delegateCheckWorkToInput","justSubmitted","creditAchieved","showCorrectness","numberOfAttemptsLeft"]}}),definition:function({dependencyValues:e}){return{setValue:{answerAncestor:e.answerAncestor}}}},e.includeCheckWork={forRenderer:!0,returnDependencies:()=>({answerAncestor:{dependencyType:"stateVariable",variableName:"answerAncestor"}}),definition:function({dependencyValues:e}){let t=!1;return e.answerAncestor&&(t=e.answerAncestor.stateValues.delegateCheckWorkToInput),{setValue:{includeCheckWork:t}}}},e.suppressCheckwork={forRenderer:!0,returnDependencies:()=>({autoSubmit:{dependencyType:"flag",flagName:"autoSubmit"}}),definition:({dependencyValues:e})=>({setValue:{suppressCheckwork:e.autoSubmit}})},e.creditAchieved={defaultValue:0,public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies:()=>({answerAncestor:{dependencyType:"stateVariable",variableName:"answerAncestor"}}),definition:function({dependencyValues:e}){let t=0;return e.answerAncestor&&(t=e.answerAncestor.stateValues.creditAchieved),{setValue:{creditAchieved:t}}}},e.valueHasBeenValidated={forRenderer:!0,returnDependencies:()=>({answerAncestor:{dependencyType:"stateVariable",variableName:"answerAncestor"}}),definition:function({dependencyValues:e}){let t=!1;return e.answerAncestor&&e.answerAncestor.stateValues.justSubmitted&&(t=!0),{setValue:{valueHasBeenValidated:t}}}},e.showCorrectness={forRenderer:!0,returnDependencies:()=>({showCorrectnessFlag:{dependencyType:"flag",flagName:"showCorrectness"},answerAncestor:{dependencyType:"stateVariable",variableName:"answerAncestor"}}),definition({dependencyValues:e}){let t;return t=e.answerAncestor?e.answerAncestor.stateValues.showCorrectness:!1!==e.showCorrectnessFlag,{setValue:{showCorrectness:t}}}},e.numberOfAttemptsLeft={forRenderer:!0,returnDependencies:()=>({answerAncestor:{dependencyType:"stateVariable",variableName:"answerAncestor"}}),definition({dependencyValues:e}){let t;return t=e.answerAncestor?e.answerAncestor.stateValues.numberOfAttemptsLeft:1/0,{setValue:{numberOfAttemptsLeft:t}}}},e}}class MatrixInput extends Input{constructor(e){super(e),Object.assign(this.actions,{updateNumRows:this.updateNumRows.bind(this),updateNumColumns:this.updateNumColumns.bind(this)}),this.externalActions={},Object.defineProperty(this.externalActions,"submitAnswer",{enumerable:!0,get:async function(){let e=await this.stateValues.answerAncestor;return null!==e?{componentName:e.componentName,actionName:"submitAnswer"}:void 0}.bind(this)})}static componentType="matrixInput";static variableForPlainMacro="value";static variableForPlainCopy="value";static processWhenJustUpdatedForNewComponent=!0;static renderChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.numRows={createComponentOfType:"integer",createStateVariable:"numRowsPreliminary",defaultValue:1,transformNonFiniteTo:0},e.numColumns={createComponentOfType:"integer",createStateVariable:"numColumnsPreliminary",defaultValue:1,transformNonFiniteTo:0},e.showSizeControls={createComponentOfType:"boolean",createStateVariable:"showSizeControls",defaultValue:!0,public:!0,forRenderer:!0},e.defaultEntry={createComponentOfType:"math",createStateVariable:"defaultEntry",defaultValue:me$3.fromAst("_")},e.prefill={createComponentOfType:"math",createStateVariable:"prefill",defaultValue:me$3.fromAst("_"),public:!0,copyComponentAttributesForCreatedComponent:["format","functionSymbols","splitSymbols","parseScientificNotation"]},e.format={createComponentOfType:"text",createStateVariable:"format",defaultValue:"text",public:!0},e.functionSymbols={createComponentOfType:"textList",createStateVariable:"functionSymbols",defaultValue:["f","g"],public:!0},e.splitSymbols={createComponentOfType:"boolean",createStateVariable:"splitSymbols",defaultValue:!0,public:!0},e.parseScientificNotation={createComponentOfType:"boolean",createStateVariable:"parseScientificNotation",defaultValue:!1,public:!0},e.displayDigits={createComponentOfType:"integer",createStateVariable:"displayDigits",defaultValue:10,public:!0},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.bindValueTo={createComponentOfType:"math"},e.unionFromU={createComponentOfType:"boolean",createStateVariable:"unionFromU",defaultValue:!1,public:!0},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e,componentAttributes:t}){if(e.length>0)return{success:!1};return{success:!0,newChildren:[{componentType:"matrixInputGrid"}]}}}),e}static returnChildGroups(){return[{group:"matrixComponentInputs",componentTypes:["matrixComponentInput"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.valueOriginal={hasEssential:!0,shadowVariable:!0,returnDependencies:()=>({bindValueTo:{dependencyType:"attributeComponent",attributeName:"bindValueTo",variableNames:["value"]},prefill:{dependencyType:"stateVariable",variableName:"prefill"}}),set:convertValueToMathExpression,definition:function({dependencyValues:e}){return e.bindValueTo?{setValue:{valueOriginal:e.bindValueTo.stateValues.value}}:{useEssentialOrDefaultValue:{valueOriginal:{defaultValue:e.prefill}}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){return t.bindValueTo?{success:!0,instructions:[{setDependency:"bindValueTo",desiredValue:e.valueOriginal,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"valueOriginal",value:e.valueOriginal}]}}},e.immediateValueOriginal={hasEssential:!0,shadowVariable:!0,returnDependencies:()=>({valueOriginal:{dependencyType:"stateVariable",variableName:"valueOriginal"}}),set:convertValueToMathExpression,definition:function({dependencyValues:e,changes:t,justUpdatedForNewComponent:n}){return t.valueOriginal&&!n?{setValue:{immediateValueOriginal:e.valueOriginal},setEssentialValue:{immediateValueOriginal:e.valueOriginal}}:{useEssentialOrDefaultValue:{immediateValueOriginal:{defaultValue:e.valueOriginal}}}},inverseDefinition:function({desiredStateVariableValues:e,initialChange:t,shadowedVariable:n}){let r=[{setEssentialValue:"immediateValueOriginal",value:e.immediateValueOriginal}];return t||n||r.push({setDependency:"valueOriginal",desiredValue:e.immediateValueOriginal}),{success:!0,instructions:r}}},e.haveBoundValue={returnDependencies:()=>({bindValueTo:{dependencyType:"attributeComponent",attributeName:"bindValueTo"}}),definition:({dependencyValues:e})=>({setValue:{haveBoundValue:null!==e.bindValueTo}})},e.numRows={public:!0,shadowingInstructions:{createComponentOfType:"integer"},forRenderer:!0,returnDependencies:()=>({numRowsPreliminary:{dependencyType:"stateVariable",variableName:"numRowsPreliminary"},valueOriginal:{dependencyType:"stateVariable",variableName:"valueOriginal"},haveBoundValue:{dependencyType:"stateVariable",variableName:"haveBoundValue"}}),definition({dependencyValues:e,usedDefault:t}){let n=e.numRowsPreliminary;if(t.numRowsPreliminary||e.haveBoundValue){let t=e.valueOriginal.tree;if(n=1,Array.isArray(t)){let e=t[0];"matrix"===e?n=t[1][1]:vectorOperators.includes(e)&&(n=t.length-1)}}return{setValue:{numRows:n}}},async inverseDefinition({desiredStateVariableValues:e,dependencyValues:t,stateValues:n}){let r=e.numRows;if(!Number.isInteger(r))return{success:!1};r=Math.max(0,r);let a=[{setDependency:"numRowsPreliminary",desiredValue:r}];if(t.haveBoundValue){let e=t.valueOriginal.tree,i=(await n.defaultEntry).tree;if(1===await n.numColumns&&Array.isArray(e)&&vectorOperators.includes(e[0])){let t=e.length-1;if(rt){let s=deepClone(e),o=await n.accumulatedComponents;for(let e=t;e({numColumnsPreliminary:{dependencyType:"stateVariable",variableName:"numColumnsPreliminary"},valueOriginal:{dependencyType:"stateVariable",variableName:"valueOriginal"},haveBoundValue:{dependencyType:"stateVariable",variableName:"haveBoundValue"}}),definition({dependencyValues:e,usedDefault:t}){let n=e.numColumnsPreliminary;if(t.numColumnsPreliminary||e.haveBoundValue){let t=e.valueOriginal.tree;if(n=1,Array.isArray(t)){let e=t[0];"matrix"===e?n=t[1][2]:Array.isArray(t[1])&&vectorOperators.includes(t[1][0])&&("^"===e&&"T"===t[2]||"prime"===e)&&(n=t[1].length-1)}}return{setValue:{numColumns:n}}},async inverseDefinition({desiredStateVariableValues:e,dependencyValues:t,stateValues:n}){let r=e.numColumns;if(!Number.isInteger(r))return{success:!1};r=Math.max(0,r);let a=[{setDependency:"numColumnsPreliminary",desiredValue:r}];if(t.haveBoundValue){let e=(await n.defaultEntry).tree,i=t.valueOriginal.tree,s=i[0];if(Array.isArray(i[1])&&vectorOperators.includes(i[1][0])&&("^"===s&&"T"===i[2]||"prime"===s)){let t=i[1].length-1;if(rt){let s=deepClone(i),o=(await n.accumulatedComponents)[0];o||(o=[]);for(let n=t;n({valueOriginal:{dependencyType:"stateVariable",variableName:"valueOriginal"}}),definition({dependencyValues:e,previousValues:t}){let n=[];t.accumulatedComponents&&(n=deepClone(t.accumulatedComponents));let r=e.valueOriginal.tree;if(Array.isArray(r)){let e=r[0];if("matrix"===e){let e=r[2];for(let[t,r]of e.slice(1).entries()){let e=n[t];e||(e=n[t]=[]);for(let[t,n]of r.slice(1).entries())e[t]=n}return{setValue:{accumulatedComponents:n}}}if(vectorOperators.includes(e)){for(let[e,t]of r.slice(1).entries()){let r=n[e];r||(r=n[e]=[]),r[0]=t}return{setValue:{accumulatedComponents:n}}}if(Array.isArray(r[1])&&vectorOperators.includes(r[1][0])&&("^"===e&&"T"===r[2]||"prime"===e)){let e=n[0];e||(e=n[0]=[]);for(let[t,n]of r[1].slice(1).entries())e[t]=n;return{setValue:{accumulatedComponents:n}}}}let a=n[0];return a||(a=n[0]=[]),a[0]=r,{setValue:{accumulatedComponents:n}}}},e.componentValues={isArray:!0,entryPrefixes:["componentValue"],nDimensions:2,returnArraySizeDependencies:()=>({numRows:{dependencyType:"stateVariable",variableName:"numRows"},numColumns:{dependencyType:"stateVariable",variableName:"numColumns"}}),returnArraySize:({dependencyValues:e})=>[e.numRows,e.numColumns],returnArrayDependenciesByKey:()=>({globalDependencies:{valueOriginal:{dependencyType:"stateVariable",variableName:"valueOriginal"},numRows:{dependencyType:"stateVariable",variableName:"numRows"},numColumns:{dependencyType:"stateVariable",variableName:"numColumns"},accumulatedComponents:{dependencyType:"stateVariable",variableName:"accumulatedComponents"},defaultEntry:{dependencyType:"stateVariable",variableName:"defaultEntry"}}}),arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t}){let n=e.valueOriginal.tree,r=e.accumulatedComponents,a=e.numRows,i=e.numColumns;if(Array.isArray(n)){let t=n[0];if("matrix"===t){if(n[1][1]===a&&n[1][2]===i){let e={},t=n[2];for(let n=0;ns)for(let t=0;tt)for(let n=t;n[...e]));else{let e=t.valueOriginal.tree;if(o){if(a=e.slice(1,1+i).map((e=>[e])),a.length1)for(let e=0;e1)for(let e=1;ee.slice(1,s+1))),a[0].length1&&a[0].push(...Array(s-1).fill("_")),i>1)for(let e=1;ee[0]))]);return{success:!0,instructions:[{setDependency:"valueOriginal",desiredValue:r,treatAsInitialChange:n}]}}if(1===i&&l){let e=t.valueOriginal.tree,r=e[0],i=[e[1][0],...a[0]];return i="^"===r?me$3.fromAst(["^",i,"T"]):me$3.fromAst(["prime",i]),{success:!0,instructions:[{setDependency:"valueOriginal",desiredValue:i,treatAsInitialChange:n}]}}{let e=["matrix",["tuple",t.numRows,t.numColumns],["tuple",...a.map((e=>["tuple",...e]))]];return{success:!0,instructions:[{setDependency:"valueOriginal",desiredValue:me$3.fromAst(e),treatAsInitialChange:n}]}}}},e.componentImmediateValues={isArray:!0,entryPrefixes:["componentImmediateValue"],nDimensions:2,returnArraySizeDependencies:()=>({numRows:{dependencyType:"stateVariable",variableName:"numRows"},numColumns:{dependencyType:"stateVariable",variableName:"numColumns"}}),returnArraySize:({dependencyValues:e})=>[e.numRows,e.numColumns],returnArrayDependenciesByKey:()=>({globalDependencies:{immediateValueOriginal:{dependencyType:"stateVariable",variableName:"immediateValueOriginal"},numRows:{dependencyType:"stateVariable",variableName:"numRows"},numColumns:{dependencyType:"stateVariable",variableName:"numColumns"},accumulatedComponents:{dependencyType:"stateVariable",variableName:"accumulatedComponents"},defaultEntry:{dependencyType:"stateVariable",variableName:"defaultEntry"}}}),arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t}){let n=e.immediateValueOriginal.tree,r=e.accumulatedComponents,a=e.numRows,i=e.numColumns;if(Array.isArray(n)){let t=n[0];if("matrix"===t){if(n[1][1]===a&&n[1][2]===i){let e={},t=n[2];for(let n=0;ns)for(let t=0;tt)for(let n=t;n[...e]));else{let e=t.immediateValueOriginal.tree;if(o){if(a=e.slice(1,1+i).map((e=>[e])),a.length1)for(let e=0;e1)for(let e=1;ee.slice(1,s+1))),a[0].length1&&a[0].push(...Array(s-1).fill("_")),i>1)for(let e=1;ee[0]))]);return{success:!0,instructions:[{setDependency:"immediateValueOriginal",desiredValue:r,treatAsInitialChange:n}]}}if(1===i&&l){let e=t.immediateValueOriginal.tree,r=e[0],i=[e[1][0],...a[0]];return i="^"===r?me$3.fromAst(["^",i,"T"]):me$3.fromAst(["prime",i]),{success:!0,instructions:[{setDependency:"immediateValueOriginal",desiredValue:i,treatAsInitialChange:n}]}}{let e=["matrix",["tuple",t.numRows,t.numColumns],["tuple",...a.map((e=>["tuple",...e]))]];return{success:!0,instructions:[{setDependency:"immediateValueOriginal",desiredValue:me$3.fromAst(e),treatAsInitialChange:n}]}}}},e.componentValuesForDisplay={isArray:!0,entryPrefixes:["componentValueForDisplay"],nDimensions:2,forRenderer:!0,returnArraySizeDependencies:()=>({numRows:{dependencyType:"stateVariable",variableName:"numRows"},numColumns:{dependencyType:"stateVariable",variableName:"numColumns"}}),returnArraySize:({dependencyValues:e})=>[e.numRows,e.numColumns],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let[e,r]=n.split(","),a=Number(e)+1+"_"+(Number(r)+1);t[n]={componentValue:{dependencyType:"stateVariable",variableName:`componentValue${a}`}}}return{globalDependencies:{displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n,usedDefault:r}){let a={};for(let i of n){let n=roundForDisplay({value:t[i].componentValue,dependencyValues:e,usedDefault:r});a[i]=n}return{setValue:{componentValuesForDisplay:a}}}},e.value={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]},returnDependencies:()=>({componentValues:{dependencyType:"stateVariable",variableName:"componentValues"},numRows:{dependencyType:"stateVariable",variableName:"numRows"},numColumns:{dependencyType:"stateVariable",variableName:"numColumns"},valueOriginal:{dependencyType:"stateVariable",variableName:"valueOriginal"}}),definition({dependencyValues:e}){let t=e.numRows,n=e.numColumns,r=["matrix",["tuple",t,n]],a=r[2]=["tuple"];for(let r=0;re[1]))]);return{success:!0,instructions:[{setDependency:"valueOriginal",desiredValue:e}]}}}}else if(1===t.numRows){let e=t.valueOriginal.tree;if(Array.isArray(e)){let t=e[0];if(Array.isArray(e[1])&&vectorOperators.includes(e[1][0])&&("^"===t&&"T"===e[2]||"prime"===t)){let r=[e[1][0],...n[2][1].slice(1)];return r="^"===t?me$3.fromAst(["^",r,"T"]):me$3.fromAst(["prime",r]),{success:!0,instructions:[{setDependency:"valueOriginal",desiredValue:r}]}}}}return{success:!0,instructions:[{setDependency:"valueOriginal",desiredValue:e.value}]}}return{success:!1}}},e.immediateValue={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]},returnDependencies:()=>({componentImmediateValues:{dependencyType:"stateVariable",variableName:"componentImmediateValues"},numRows:{dependencyType:"stateVariable",variableName:"numRows"},numColumns:{dependencyType:"stateVariable",variableName:"numColumns"},immediateValueOriginal:{dependencyType:"stateVariable",variableName:"immediateValueOriginal"}}),definition({dependencyValues:e}){let t=e.numRows,n=e.numColumns,r=["matrix",["tuple",t,n]],a=r[2]=["tuple"];for(let r=0;re[1]))]);return{success:!0,instructions:[{setDependency:"immediateValueOriginal",desiredValue:e}]}}}}else if(1===t.numRows){let e=t.immediateValueOriginal.tree;if(Array.isArray(e)){let t=e[0];if(Array.isArray(e[1])&&vectorOperators.includes(e[1][0])&&("^"===t&&"T"===e[2]||"prime"===t)){let r=[e[1][0],...n[2][1].slice(1)];return r="^"===t?me$3.fromAst(["^",r,"T"]):me$3.fromAst(["prime",r]),{success:!0,instructions:[{setDependency:"immediateValueOriginal",desiredValue:r}]}}}}return{success:!0,instructions:[{setDependency:"immediateValueOriginal",desiredValue:e.immediateValue}]}}return{success:!1}}},e.valueForDisplay={forRenderer:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"}}),definition:function({dependencyValues:e,usedDefault:t}){return{setValue:{valueForDisplay:roundForDisplay({value:e.value,dependencyValues:e,usedDefault:t})}}}},e.componentType={returnDependencies:()=>({}),definition:()=>({setValue:{componentType:"matrix"}})},e}async updateRawValues({rawRendererValues:e,transient:t=!1,actionId:n}){if(!await this.stateValues.disabled)return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rawRendererValues",value:e}],transient:t,actionId:n});this.coreFunctions.resolveAction({actionId:n})}async updateNumRows({numRows:e,actionId:t}){if(!await this.stateValues.disabled)return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"numRows",value:e}],actionId:t});this.coreFunctions.resolveAction({actionId:t})}async updateNumColumns({numColumns:e,actionId:t}){if(!await this.stateValues.disabled)return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"numColumns",value:e}],actionId:t});this.coreFunctions.resolveAction({actionId:t})}static adapters=[{stateVariable:"value",stateVariablesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]}]}class MatrixInputGrid extends CompositeComponent{static componentType="matrixInputGrid";static stateVariableToEvaluateAfterReplacements="readyToExpandWhenResolved";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numRows={returnDependencies:()=>({parentNumRows:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"numRows"}}),definition:({dependencyValues:e})=>({setValue:{numRows:e.parentNumRows}})},e.numColumns={returnDependencies:()=>({parentNumColumns:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"numColumns"}}),definition:({dependencyValues:e})=>({setValue:{numColumns:e.parentNumColumns}})},e.readyToExpandWhenResolved={returnDependencies:()=>({numRows:{dependencyType:"stateVariable",variableName:"numRows"},numColumns:{dependencyType:"stateVariable",variableName:"numColumns"}}),markStale:()=>({updateReplacements:!0}),definition:()=>({setValue:{readyToExpandWhenResolved:!0}})},e}static async createSerializedReplacements({component:e,componentInfoObjects:t,flags:n,workspace:r}){let a=[],i=await e.stateValues.numRows;r.previousNumRows=i;for(let e=0;eo&&(u=l-o,e.replacementsToWithhold>0))if(e.replacementsToWithhold>=u){i=e.replacementsToWithhold-u,o+=u,u=0;let t={changeType:"changeReplacementsToWithhold",replacementsToWithhold:i};s.push(t)}else u-=e.replacementsToWithhold,o+=e.replacementsToWithhold,i=0;if(u>0){let e=[];for(let t=o;t({}),definition:()=>({useEssentialOrDefaultValue:{rowInd:!0}})},e.numColumns={returnDependencies:()=>({parentNumColumns:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"numColumns"}}),definition:({dependencyValues:e})=>({setValue:{numColumns:e.parentNumColumns}})},e.readyToExpandWhenResolved={returnDependencies:()=>({numColumns:{dependencyType:"stateVariable",variableName:"numColumns"}}),markStale:()=>({updateReplacements:!0}),definition:()=>({setValue:{readyToExpandWhenResolved:!0}})},e}j;static async createSerializedReplacements({component:e,componentInfoObjects:t,flags:n,workspace:r}){let a=[],i=await e.stateValues.numColumns,s=await e.stateValues.rowInd;r.previousNumColumns=i;for(let e=0;eo&&(c=l-o,e.replacementsToWithhold>0))if(e.replacementsToWithhold>=c){i=e.replacementsToWithhold-c,o+=c,c=0;let t={changeType:"changeReplacementsToWithhold",replacementsToWithhold:i};s.push(t)}else c-=e.replacementsToWithhold,o+=e.replacementsToWithhold,i=0;if(c>0){let e=[];for(let t=o;t({}),definition:()=>({useEssentialOrDefaultValue:{rowInd:!0}})},e.colInd={hasEssential:!0,defaultValue:null,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{colInd:!0}})},e.format={returnDependencies:()=>({parentFormat:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"format"}}),definition:({dependencyValues:e})=>({setValue:{format:e.parentFormat}})},e.functionSymbols={returnDependencies:()=>({parentFunctionSymbols:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"functionSymbols"}}),definition:({dependencyValues:e})=>({setValue:{functionSymbols:e.parentFunctionSymbols}})},e.splitSymbols={returnDependencies:()=>({parentSplitSymbols:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"splitSymbols"}}),definition:({dependencyValues:e})=>({setValue:{splitSymbols:e.parentSplitSymbols}})},e.parseScientificNotation={returnDependencies:()=>({parentParseScientificNotation:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"parseScientificNotation"}}),definition:({dependencyValues:e})=>({setValue:{parseScientificNotation:e.parentParseScientificNotation}})},e.displayDigits={returnDependencies:()=>({parentDisplayDigits:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"displayDigits"}}),definition({dependencyValues:e,usedDefault:t}){let n={setValue:{displayDigits:e.parentDisplayDigits}};return t.parentDisplayDigits&&(n.markAsUsedDefault={displayDigits:!0}),n}},e.displayDecimals={returnDependencies:()=>({parentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"displayDecimals"}}),definition({dependencyValues:e,usedDefault:t}){let n={setValue:{displayDecimals:e.parentDisplayDecimals}};return t.parentDisplayDecimals&&(n.markAsUsedDefault={displayDecimals:!0}),n}},e.displaySmallAsZero={returnDependencies:()=>({parentDisplaySmallAsZero:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"displaySmallAsZero"}}),definition:({dependencyValues:e})=>({setValue:{displaySmallAsZero:e.parentDisplaySmallAsZero}})},e.unionFromU={returnDependencies:()=>({parentUnionFromU:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"unionFromU"}}),definition:({dependencyValues:e})=>({setValue:{unionFromU:e.parentUnionFromU}})},e.value={stateVariablesDeterminingDependencies:["rowInd","colInd"],returnDependencies:({stateValues:e})=>{let t="";return null!==e.rowInd&&null!==e.colInd&&(t=`${e.rowInd+1}_${e.colInd+1}`),{parentComponentValue:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:`componentValue${t}`}}},definition:function({dependencyValues:e}){return e.parentComponentValue?{setValue:{value:e.parentComponentValue}}:{setValue:{value:me$3.fromAst("_")}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){return{success:!0,instructions:[{setDependency:"parentComponentValue",desiredValue:e.value}]}}},e.immediateValue={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]},stateVariablesDeterminingDependencies:["rowInd","colInd"],returnDependencies:({stateValues:e})=>{let t="";return null!==e.rowInd&&null!==e.colInd&&(t=`${e.rowInd+1}_${e.colInd+1}`),{parentComponentImmediateValue:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:`componentImmediateValue${t}`}}},definition:function({dependencyValues:e}){return{setValue:{immediateValue:e.parentComponentImmediateValue}}},inverseDefinition:function({desiredStateVariableValues:e,initialChange:t}){return{success:!0,instructions:[{setDependency:"parentComponentImmediateValue",desiredValue:e.immediateValue,treatAsInitialChange:t}]}}},e.valueForDisplay={forRenderer:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"}}),definition:function({dependencyValues:e,usedDefault:t}){return{setValue:{valueForDisplay:roundForDisplay({value:e.value,dependencyValues:e,usedDefault:t})}}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({valueForDisplay:{dependencyType:"stateVariable",variableName:"valueForDisplay"}}),definition:function({dependencyValues:e}){return{setValue:{text:e.valueForDisplay.toString()}}}},e.rawRendererValue={forRenderer:!0,hasEssential:!0,shadowVariable:!0,defaultValue:"",provideEssentialValuesInDefinition:!0,public:!0,shadowingInstructions:{createComponentOfType:"text"},additionalStateVariablesDefined:[{variableName:"lastValueForDisplay",hasEssential:!0,shadowVariable:!0,defaultValue:null,set:convertValueToMathExpression}],returnDependencies:()=>({immediateValue:{dependencyType:"stateVariable",variableName:"immediateValue"},valueForDisplay:{dependencyType:"stateVariable",variableName:"valueForDisplay"}}),definition({dependencyValues:e,essentialValues:t}){if(void 0!==t.rawRendererValue&&deepCompare(t.lastValueForDisplay.tree,e.valueForDisplay.tree))return{useEssentialOrDefaultValue:{rawRendererValue:!0,lastValueForDisplay:!0}};{let t=stripLatex(e.valueForDisplay.toLatex());return"_"===t&&(t=""),{setValue:{rawRendererValue:t,lastValueForDisplay:e.valueForDisplay},setEssentialValue:{rawRendererValue:t,lastValueForDisplay:e.valueForDisplay}}}},async inverseDefinition({desiredStateVariableValues:e,stateValues:t,essentialValues:n}){const r=async e=>{let n;e=(e=normalizeLatexString(e,{unionFromU:await t.unionFromU})).replace(/\^(\w)/g,"^{$1}");let r=getFromLatex({functionSymbols:await t.functionSymbols,splitSymbols:await t.splitSymbols,parseScientificNotation:await t.parseScientificNotation});try{n=r(e)}catch(e){n=me$3.fromAst("_")}return n};let a=[];if("string"==typeof e.rawRendererValue){let t=n.rawRendererValue,i=e.rawRendererValue;t!==i&&a.push({setEssentialValue:"rawRendererValue",value:i});let s=await r(t),o=await r(i);deepCompare(o.tree,s.tree)||a.push({setDependency:"immediateValue",desiredValue:o,treatAsInitialChange:!0})}else{a.push({setEssentialValue:"lastValueForDisplay",value:e.rawRendererValue});let t=await r(n.rawRendererValue);if(!deepCompare(e.rawRendererValue.tree,t.tree)){let t=stripLatex(e.rawRendererValue.toLatex());"_"===t&&(t=""),a.push({setEssentialValue:"rawRendererValue",value:t})}}return{success:!0,instructions:a}}},e.componentType={returnDependencies:()=>({}),definition:()=>({setValue:{componentType:"math"}})},e}async updateRawValue({rawRendererValue:e,actionId:t}){if(!await this.stateValues.disabled)return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rawRendererValue",value:e},{updateType:"setComponentNeedingUpdateValue",componentName:this.componentName}],actionId:t});this.coreFunctions.resolveAction({actionId:t})}async updateValue({actionId:e}){if(await this.stateValues.disabled)this.coreFunctions.resolveAction({actionId:e});else{let t=await this.stateValues.immediateValue;if(!deepCompare((await this.stateValues.value).tree,t.tree)){let n=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"value",value:t},{updateType:"executeUpdate"},{updateType:"updateValue",componentName:this.componentName,stateVariable:"immediateValue",valueOfStateVariable:"value"},{updateType:"unsetComponentNeedingUpdateValue"}];"_"!==t.tree&&n.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"rawRendererValue",valueOfStateVariable:"valueForDisplay"});let r={verb:"answered",object:{componentName:this.componentName,componentType:this.componentType},result:{response:t,responseText:t.toString()}},a=await this.stateValues.answerAncestor;return a&&(r.context={answerAncestor:a.componentName}),await this.coreFunctions.performUpdate({updateInstructions:n,actionId:e,event:r}),await this.coreFunctions.triggerChainedActions({componentName:this.componentName})}await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rawRendererValue",valueOfStateVariable:"rawRendererValue"}],actionId:e})}}}var MatrixInput$1=Object.freeze({__proto__:null,MatrixInput:MatrixInput,MatrixInputGrid:MatrixInputGrid,MatrixInputRow:MatrixInputRow,default:MatrixComponentInput});class Document extends BaseComponent{constructor(e){super(e),Object.assign(this.actions,{submitAllAnswers:this.submitAllAnswers.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="document";static rendererType="section";static renderChildren=!0;static createsVariants=!0;static createAttributesObject(){let e=super.createAttributesObject();return delete e.hide,delete e.disabled,delete e.modifyIndirectly,delete e.fixed,delete e.styleNumber,delete e.isResponse,e.documentWideCheckWork={createComponentOfType:"boolean",createStateVariable:"documentWideCheckWork",defaultValue:!1,public:!0},e.submitLabel={createComponentOfType:"text",createStateVariable:"submitLabel",defaultValue:"Check Work",public:!0,forRenderer:!0},e.submitLabelNoCorrectness={createComponentOfType:"text",createStateVariable:"submitLabelNoCorrectness",defaultValue:"Submit Response",public:!0,forRenderer:!0},e.displayDigitsForCreditAchieved={createComponentOfType:"integer",createStateVariable:"displayDigitsForCreditAchieved",defaultValue:3,public:!0},e.xmlns={createPrimitiveOfType:"string"},e.type={createPrimitiveOfType:"string"},e}static returnChildGroups(){return[{group:"variantControl",componentTypes:["variantControl"]},{group:"title",componentTypes:["title"]},{group:"description",componentTypes:["description"]},{group:"setups",componentTypes:["setup"]},{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnStyleDefinitionStateVariables();Object.assign(e,t);let n=returnFeedbackDefinitionStateVariables();return Object.assign(e,n),e.titleChildName={forRenderer:!0,returnDependencies:()=>({titleChild:{dependencyType:"child",childGroups:["title"]}}),definition({dependencyValues:e}){let t=null;return e.titleChild.length>0&&(t=e.titleChild[0].componentName),{setValue:{titleChildName:t}}}},e.title={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({titleChild:{dependencyType:"child",childGroups:["title"],variableNames:["text"]}}),definition:({dependencyValues:e})=>0===e.titleChild.length?{setValue:{title:""}}:{setValue:{title:e.titleChild[0].stateValues.text}}},e.description={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({descriptionChild:{dependencyType:"child",childGroups:["description"],variableNames:["text"]}}),definition:({dependencyValues:e})=>0===e.descriptionChild.length?{setValue:{description:""}}:{setValue:{description:e.descriptionChild[0].stateValues.text}}},e.level={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{level:0}})},e.viewedSolution={defaultValue:!1,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{viewedSolution:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"viewedSolution",value:e.viewedSolution}]})},e.scoredDescendants={returnDependencies:()=>({scoredDescendants:{dependencyType:"descendant",componentTypes:["_sectioningComponent","answer","setup"],variableNames:["scoredDescendants","aggregateScores","weight"],recurseToMatchedChildren:!1,variablesOptional:!0}}),definition({dependencyValues:e}){let t=[];for(let n of e.scoredDescendants)"setup"!==n.componentType&&(n.stateValues.aggregateScores||void 0===n.stateValues.scoredDescendants?t.push(n):t.push(...n.stateValues.scoredDescendants));return{setValue:{scoredDescendants:t}}}},e.nScoredDescendants={returnDependencies:()=>({scoredDescendants:{dependencyType:"stateVariable",variableName:"scoredDescendants"}}),definition:({dependencyValues:e})=>({setValue:{nScoredDescendants:e.scoredDescendants.length}})},e.itemCreditAchieved={isArray:!0,returnArraySizeDependencies:()=>({nScoredDescendants:{dependencyType:"stateVariable",variableName:"nScoredDescendants"}}),returnArraySize:({dependencyValues:e})=>[e.nScoredDescendants],stateVariablesDeterminingDependencies:["scoredDescendants"],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=t.scoredDescendants[r];e&&(n[r]={creditAchieved:{dependencyType:"stateVariable",componentName:e.componentName,variableName:"creditAchieved"}})}return{dependenciesByKey:n}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t)n[r]=e[r].creditAchieved;return{setValue:{itemCreditAchieved:n}}}},e.itemNumberByAnswerName={stateVariablesDeterminingDependencies:["scoredDescendants"],returnDependencies({stateValues:e}){let t={scoredDescendants:{dependencyType:"stateVariable",variableName:"scoredDescendants"}};for(let n in e.scoredDescendants){let r=e.scoredDescendants[n];t[`descendantsOf${n}`]={dependencyType:"descendant",ancestorName:r.componentName,componentTypes:["answer"],recurseToMatchedChildren:!1}}return t},definition({dependencyValues:e,componentInfoObjects:t}){let n={};for(let[r,a]of e.scoredDescendants.entries()){let i=r+1;for(let t of e[`descendantsOf${r}`])n[t.componentName]=i;t.isInheritedComponentType({inheritedComponentType:a.componentType,baseComponentType:"answer"})&&(n[a.componentName]=i)}return{setValue:{itemNumberByAnswerName:n}}}},e.itemVariantInfo={isArray:!0,returnArraySizeDependencies:()=>({nScoredDescendants:{dependencyType:"stateVariable",variableName:"nScoredDescendants"}}),returnArraySize:({dependencyValues:e})=>[e.nScoredDescendants],stateVariablesDeterminingDependencies:["scoredDescendants"],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=t.scoredDescendants[r];e&&(n[r]={generatedVariantInfo:{dependencyType:"stateVariable",componentName:e.componentName,variableName:"generatedVariantInfo",variablesOptional:!0}})}return{dependenciesByKey:n}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t)n[r]=e[r].generatedVariantInfo;return{setValue:{itemVariantInfo:n}}}},e.answerDescendants={returnDependencies:()=>({answerDescendants:{dependencyType:"descendant",componentTypes:["answer"],variableNames:["justSubmitted"],recurseToMatchedChildren:!1}}),definition:({dependencyValues:e})=>({setValue:{answerDescendants:e.answerDescendants}})},e.justSubmitted={forRenderer:!0,returnDependencies:()=>({answerDescendants:{dependencyType:"stateVariable",variableName:"answerDescendants"}}),definition:({dependencyValues:e})=>({setValue:{justSubmitted:e.answerDescendants.every((e=>e.stateValues.justSubmitted))}})},e.showCorrectness={forRenderer:!0,returnDependencies:()=>({showCorrectnessFlag:{dependencyType:"flag",flagName:"showCorrectness"}}),definition:({dependencyValues:e})=>({setValue:{showCorrectness:!1!==e.showCorrectnessFlag}})},e.creditAchieved={public:!0,forRenderer:!0,defaultValue:0,shadowingInstructions:{createComponentOfType:"number",addAttributeComponentsShadowingStateVariables:{displayDigits:{stateVariableToShadow:"displayDigitsForCreditAchieved"}}},additionalStateVariablesDefined:[{variableName:"percentCreditAchieved",public:!0,shadowingInstructions:{createComponentOfType:"number",addAttributeComponentsShadowingStateVariables:{displayDigits:{stateVariableToShadow:"displayDigitsForCreditAchieved"}}}}],returnDependencies:()=>({scoredDescendants:{dependencyType:"stateVariable",variableName:"scoredDescendants"},itemCreditAchieved:{dependencyType:"stateVariable",variableName:"itemCreditAchieved"}}),definition({dependencyValues:e}){let t,n=0,r=0;for(let[t,a]of e.scoredDescendants.entries()){let i=a.stateValues.weight;n+=e.itemCreditAchieved[t]*i,r+=i}return t=r>0?n/r:1,{setValue:{creditAchieved:t,percentCreditAchieved:100*t}}}},e.creditAchievedIfSubmit={defaultValue:0,stateVariablesDeterminingDependencies:["scoredDescendants"],returnDependencies({stateValues:e}){let t={scoredDescendants:{dependencyType:"stateVariable",variableName:"scoredDescendants"}};for(let[n,r]of e.scoredDescendants.entries())t["creditAchievedIfSubmit"+n]={dependencyType:"stateVariable",componentName:r.componentName,variableName:"creditAchievedIfSubmit"};return t},definition({dependencyValues:e}){let t=0,n=0;for(let[r,a]of e.scoredDescendants.entries()){let i=a.stateValues.weight;t+=e["creditAchievedIfSubmit"+r]*i,n+=i}return{setValue:{creditAchievedIfSubmit:t/n}}}},e.generatedVariantInfo={providePreviousValuesInDefinition:!0,returnDependencies:({sharedParameters:e,componentInfoObjects:t})=>({variantIndex:{dependencyType:"value",value:e.variantIndex},variantName:{dependencyType:"value",value:e.variantName},variantDescendants:{dependencyType:"descendant",componentTypes:Object.keys(t.componentTypesCreatingVariants),variableNames:["isVariantComponent","generatedVariantInfo"],recurseToMatchedChildren:!1,variablesOptional:!0,includeNonActiveChildren:!0,ignoreReplacementsOfEncounteredComposites:!0}}),definition({dependencyValues:e,componentName:t,previousValues:n}){let r={index:e.variantIndex,name:e.variantName,meta:{createdBy:t}},a=r.subvariants=[];for(let t of e.variantDescendants)t.stateValues.isVariantComponent?a.push(t.stateValues.generatedVariantInfo):t.stateValues.generatedVariantInfo&&a.push(...t.stateValues.generatedVariantInfo.subvariants);for(let[e,t]of a.entries())if(!t.subvariants&&n.generatedVariantInfo){let t=n.generatedVariantInfo.subvariants;t[e]?.subvariants&&(a[e]=Object.assign({},a[e]),a[e].subvariants=t[e].subvariants)}return{setValue:{generatedVariantInfo:r}}}},e.createSubmitAllButton={forRenderer:!0,additionalStateVariablesDefined:[{variableName:"suppressAnswerSubmitButtons",forRenderer:!0}],returnDependencies:()=>({documentWideCheckWork:{dependencyType:"stateVariable",variableName:"documentWideCheckWork"}}),definition({dependencyValues:e,componentName:t}){let n=!1,r=!1;return e.documentWideCheckWork&&(n=!0,r=!0),{setValue:{createSubmitAllButton:n,suppressAnswerSubmitButtons:r}}}},e.suppressCheckwork={forRenderer:!0,returnDependencies:()=>({autoSubmit:{dependencyType:"flag",flagName:"autoSubmit"}}),definition:({dependencyValues:e})=>({setValue:{suppressCheckwork:e.autoSubmit}})},e}async submitAllAnswers({actionId:e}){this.coreFunctions.requestRecordEvent({verb:"submitted",object:{componentName:this.componentName,componentType:this.componentType}});for(let e of await this.stateValues.answerDescendants)await e.stateValues.justSubmitted||await this.coreFunctions.performAction({componentName:e.componentName,actionName:"submitAnswer"});this.coreFunctions.resolveAction({actionId:e})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}static setUpVariant({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n}){let r,a=e.variants.numberOfVariants,i=e.variants.desiredVariant;if(void 0!==i&&void 0!==i.index){let e=Number(i.index);if(Number.isFinite(e)){Number.isInteger(e)||(console.warn("Variant index "+i.index+" must be an integer"),e=Math.round(e));let t=(e-1)%a;t<0&&(t+=a),r=t+1}else console.warn("Variant index "+i.index+" must be a number"),r=1}if(void 0===r&&(r=1),t.allPossibleVariants=e.variants.allPossibleVariants,t.allVariantNames=e.variants.allVariantNames,t.variantSeed=e.variants.allPossibleVariantSeeds[r-1],t.variantIndex=r,t.variantName=e.variants.allPossibleVariants[r-1],t.uniqueIndex=e.variants.allPossibleVariantUniqueIndices[r-1],t.variantRng=new t.rngClass(t.variantSeed),t.subpartVariantRng=new t.rngClass(t.variantSeed+"s"),i?.subvariants&&n)for(let e in i.subvariants){let t=i.subvariants[e],r=n[e];if(void 0===r)break;r.variants.desiredVariant=t}}static determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t}){return determineVariantsForSection({serializedComponent:e,componentInfoObjects:t,isDocument:!0})}static getUniqueVariant({serializedComponent:e,variantIndex:t,componentInfoObjects:n}){let r=e.variants.allPossibleVariantUniqueIndices[t-1];if(void 0===r)return{success:!1};let a=getVariantsForDescendantsForUniqueVariants({variantIndex:r,serializedComponent:e,componentInfoObjects:n});return a.success?{success:!0,desiredVariant:{index:t,subvariants:a.desiredVariants}}:(console.log("Failed to get unique variant for document."),{success:!1})}static includeBlankStringChildren=!0}class TextList$1 extends InlineComponent{static componentType="textList";static renderChildren=!0;static includeBlankStringChildren=!0;static removeBlankStringChildrenPostSugar=!0;static stateVariableForAttributeValue="texts";static primaryStateVariableForDefinition="textsShadow";static descendantCompositesMustHaveAReplacement=!1;static createAttributesObject(){let e=super.createAttributesObject();return e.unordered={createComponentOfType:"boolean",createStateVariable:"unordered",defaultValue:!1,public:!0},e.maximumNumber={createComponentOfType:"number",createStateVariable:"maximumNumber",defaultValue:null,public:!0},e}static returnSugarInstructions(){let e=super.returnSugarInstructions(),t=returnGroupIntoComponentTypeSeparatedBySpaces({componentType:"text"}),n=returnBreakStringsIntoComponentTypeBySpaces({componentType:"text"});return e.push({replacementFunction:function({matchedChildren:e,isAttributeComponent:r=!1,createdFromMacro:a=!1}){return r&&!a?t({matchedChildren:e}):n({matchedChildren:e})}}),e}static returnChildGroups(){return[{group:"texts",componentTypes:["text"]},{group:"textLists",componentTypes:["textList"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.overrideChildHide={returnDependencies:()=>({}),definition:()=>({setValue:{overrideChildHide:!0}})},e.textsShadow={defaultValue:null,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{textsShadow:!0}})},e.nComponents={public:!0,shadowingInstructions:{createComponentOfType:"number"},additionalStateVariablesDefined:["childIndexByArrayKey"],returnDependencies:()=>({maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"},textListChildren:{dependencyType:"child",childGroups:["textLists"],variableNames:["nComponents"]},textAndTextListChildren:{dependencyType:"child",childGroups:["texts","textLists"],skipComponentNames:!0},textsShadow:{dependencyType:"stateVariable",variableName:"textsShadow"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=0,r=[];if(e.textAndTextListChildren.length>0){let a=0;for(let[i,s]of e.textAndTextListChildren.entries())if(t.isInheritedComponentType({inheritedComponentType:s.componentType,baseComponentType:"textList"})){let t=e.textListChildren[a];a++;for(let e=0;ea&&(n=a,r=r.slice(0,a)),{setValue:{nComponents:n,childIndexByArrayKey:r},checkForActualChange:{nComponents:!0}}}},e.texts={public:!0,shadowingInstructions:{createComponentOfType:"text"},isArray:!0,entryPrefixes:["text"],stateVariablesDeterminingDependencies:["childIndexByArrayKey"],returnArraySizeDependencies:()=>({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"}}),returnArraySize:({dependencyValues:e})=>[e.nComponents],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=[],a="1";t.childIndexByArrayKey[r]&&(e=[t.childIndexByArrayKey[r][0]],a=t.childIndexByArrayKey[r][1]+1),n[r]={textAndTextListChildren:{dependencyType:"child",childGroups:["texts","textLists"],variableNames:["value","text"+a],variablesOptional:!0,childIndices:e}}}return{globalDependencies:{childIndexByArrayKey:{dependencyType:"stateVariable",variableName:"childIndexByArrayKey"},textsShadow:{dependencyType:"stateVariable",variableName:"textsShadow"}},dependenciesByKey:n}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};for(let a of n){let n=t[a].textAndTextListChildren[0];if(n)if(void 0!==n.stateValues.value)r[a]=n.stateValues.value;else{let t=e.childIndexByArrayKey[a][1]+1;r[a]=n.stateValues["text"+t]}else null!==e.textsShadow&&(r[a]=e.textsShadow[a])}return{setValue:{texts:r}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i=[];for(let t in e.texts){if(!n[t])continue;let a=n[t].textAndTextListChildren[0];a&&(void 0!==a.stateValues.value?i.push({setDependency:r[t].textAndTextListChildren,desiredValue:e.texts[t],childIndex:0,variableIndex:0}):i.push({setDependency:r[t].textAndTextListChildren,desiredValue:e.texts[t],childIndex:0,variableIndex:1}))}return{success:!0,instructions:i}}},e.nValues={isAlias:!0,targetVariableName:"nComponents"},e.values={isAlias:!0,targetVariableName:"texts"},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({texts:{dependencyType:"stateVariable",variableName:"texts"}}),definition:({dependencyValues:e})=>({setValue:{text:e.texts.join(", ")}})},e.componentNamesInList={returnDependencies:()=>({textAndTextListChildren:{dependencyType:"child",childGroups:["texts","textLists"],variableNames:["componentNamesInList"],variablesOptional:!0},maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=[];for(let r of e.textAndTextListChildren)t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"textList"})?n.push(...r.stateValues.componentNamesInList):n.push(r.componentName);let r=e.maximumNumber;return null!==r&&n.length>r&&(r=Math.max(0,Math.floor(r)),n=n.slice(0,r)),{setValue:{componentNamesInList:n}}}},e.nComponentsToDisplayByChild={additionalStateVariablesDefined:["nChildrenToRender"],returnDependencies:()=>({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"},textListChildren:{dependencyType:"child",childGroups:["textLists"],variableNames:["nComponents"]},textAndTextListChildren:{dependencyType:"child",childGroups:["texts","textLists"],skipComponentNames:!0},parentNComponentsToDisplayByChild:{dependencyType:"parentStateVariable",parentComponentType:"textList",variableName:"nComponentsToDisplayByChild"}}),definition:function({dependencyValues:e,componentInfoObjects:t,componentName:n}){let r=e.nComponents;null!==e.parentNComponentsToDisplayByChild&&(r=e.parentNComponentsToDisplayByChild[n]);let a={},i=0,s=0,o=0;for(let n of e.textAndTextListChildren){let l=Math.max(0,r-i);if(l>0&&s++,t.isInheritedComponentType({inheritedComponentType:n.componentType,baseComponentType:"textList"})){let t=e.textListChildren[o];o++;let n=Math.min(l,t.stateValues.nComponents);a[t.componentName]=n,i+=n}else i+=1}return{setValue:{nComponentsToDisplayByChild:a,nChildrenToRender:s}}},markStale:()=>({updateRenderedChildren:!0})},e}static adapters=["text"]}class TextList extends InlineComponent{static componentType="randomizedTextList";static stateVariableForAttributeValue="texts";static createAttributesObject(){let e=super.createAttributesObject();return e.unordered={default:!1},e.maximumNumber={default:null},e}static returnChildLogic(e){let t=super.returnChildLogic(e),n=t.newLeaf({name:"atLeastZeroTexts",componentType:"text",comparison:"atLeast",number:0}),r=t.newLeaf({name:"atLeastZeroTextLists",componentType:"textList",comparison:"atLeast",number:0}),a=t.newLeaf({name:"exactlyOneString",componentType:"string",number:1,isSugar:!0,returnSugarDependencies:()=>({stringChildren:{dependencyType:"child",childLogicName:"exactlyOneString",variableNames:["value"]}}),logicToWaitOnSugar:["atLeastZeroTexts"],replacementFunction:function({dependencyValues:e}){let t=e.stringChildren[0],n=t.stateValues.value.split(",").map((e=>({componentType:"text",state:{value:e.trim()}})));return{success:!0,newChildren:n,toDelete:[t.componentName]}}}),i=t.newOperator({name:"textAndTextLists",operator:"and",propositions:[n,r]});return t.newOperator({name:"TextsXorSugar",operator:"xor",propositions:[a,i],setAsBase:!0}),t}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.texts={public:!0,shadowingInstructions:{createComponentOfType:"text"},isArray:!0,entryPrefixes:["text"],returnDependencies:()=>({textAndTextListChildren:{dependencyType:"child",childLogicName:"textAndTextLists",variableNames:["value","texts"],variablesOptional:!0},maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"},childrenToRender:{dependencyType:"stateVariable",variableName:"childrenToRender"}}),definition:function({dependencyValues:e}){let t=[],n=e.textAndTextListChildren.map((e=>e.componentName));for(let r of e.childrenToRender){let a=n.indexOf(r),i=e.textAndTextListChildren[a];i.stateValues.texts?t.push(...i.stateValues.texts):t.push(i.stateValues.value)}return{setValue:{texts:t}}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({texts:{dependencyType:"stateVariable",variableName:"texts"}}),definition:({dependencyValues:e})=>({setValue:{text:e.texts.join(", ")}})},e.nComponents={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({texts:{dependencyType:"stateVariable",variableName:"texts"}}),definition:function({dependencyValues:e}){return{setValue:{nComponents:e.texts.length}}}},e.childrenToRender={returnDependencies:({sharedParameters:e})=>({textAndTextListChildren:{dependencyType:"child",childLogicName:"textAndTextLists",variableNames:["childrenToRender"],variablesOptional:!0},maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"},selectRng:{dependencyType:"value",value:e.selectRng,doNotProxy:!0}}),definition:function({dependencyValues:e}){let t=[];for(let n of e.textAndTextListChildren)n.stateValues.childrenToRender?t.push(...n.stateValues.childrenToRender):t.push(n.componentName);let n=e.maximumNumber;null!==n&&t.length>n&&(n=Math.max(0,Math.floor(n)),t=t.slice(0,n)),console.log("randomizing children");for(let n=t.length-1;n>0;n--){const r=e.selectRng(),a=Math.floor(r*(n+1));[t[n],t[a]]=[t[a],t[n]]}let r=Math.ceil(e.selectRng()*t.length);return console.log(`numChildren: ${r}`),t=t.slice(0,r),{setValue:{childrenToRender:t}}}},e}initializeRenderer(){void 0===this.renderer&&(this.renderer=new this.availableRenderers.aslist({key:this.componentName}))}}class TupleList extends MathList{static componentType="tupleList";static rendererType="mathList";static includeBlankStringChildren=!1;static returnSugarInstructions(){let e=[];return e.push({replacementFunction:function({matchedChildren:e}){let t=breakEmbeddedStringsIntoParensPieces({componentList:e});return!0!==t.success?{success:!1}:{success:!0,newChildren:t.pieces.map((function(e){return e.length>1||"string"==typeof e[0]?{componentType:"math",children:e}:e[0]}))}}}),e}}class NumberList extends InlineComponent{static componentType="numberList";static renderChildren=!0;static includeBlankStringChildren=!0;static removeBlankStringChildrenPostSugar=!0;static stateVariableForAttributeValue="numbers";static primaryStateVariableForDefinition="numbersShadow";static createAttributesObject(){let e=super.createAttributesObject();return e.unordered={createComponentOfType:"boolean",createStateVariable:"unordered",defaultValue:!1,public:!0},e.maximumNumber={createComponentOfType:"number",createStateVariable:"maximumNumber",defaultValue:null,public:!0},e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.padZeros={createComponentOfType:"boolean",createStateVariable:"padZeros",defaultValue:!1,public:!0},e}static returnSugarInstructions(){let e=super.returnSugarInstructions(),t=returnGroupIntoComponentTypeSeparatedBySpaces({componentType:"number"}),n=returnBreakStringsIntoComponentTypeBySpaces({componentType:"number"});return e.push({replacementFunction:function({matchedChildren:e,isAttributeComponent:r=!1,createdFromMacro:a=!1}){return r&&!a?t({matchedChildren:e}):n({matchedChildren:e})}}),e}static returnChildGroups(){return[{group:"numbers",componentTypes:["number"]},{group:"numberLists",componentTypes:["numberList"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.overrideChildHide={returnDependencies:()=>({}),definition:()=>({setValue:{overrideChildHide:!0}})},e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.displayDigitsAttr){let n=t.displayDigitsAttr,r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!n&&!r){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({}),definition:()=>({useEssentialOrDefaultValue:{numbersShadow:!0}})},e.nComponents={public:!0,shadowingInstructions:{createComponentOfType:"number"},additionalStateVariablesDefined:["childIndexByArrayKey"],returnDependencies:()=>({maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"},numberListChildren:{dependencyType:"child",childGroups:["numberLists"],variableNames:["nComponents"]},numberAndNumberListChildren:{dependencyType:"child",childGroups:["numbers","numberLists"],skipComponentNames:!0},numbersShadow:{dependencyType:"stateVariable",variableName:"numbersShadow"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=0,r=[],a=0;if(e.numberAndNumberListChildren.length>0)for(let[i,s]of e.numberAndNumberListChildren.entries())if(t.isInheritedComponentType({inheritedComponentType:s.componentType,baseComponentType:"numberList"})){let t=e.numberListChildren[a];a++;for(let e=0;ei&&(n=i,r=r.slice(0,i)),{setValue:{nComponents:n,childIndexByArrayKey:r},checkForActualChange:{nComponents:!0}}}},e.numbers={public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},isArray:!0,entryPrefixes:["number"],stateVariablesDeterminingDependencies:["childIndexByArrayKey"],returnArraySizeDependencies:()=>({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"}}),returnArraySize:({dependencyValues:e})=>[e.nComponents],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=[],a="1";t.childIndexByArrayKey[r]&&(e=[t.childIndexByArrayKey[r][0]],a=t.childIndexByArrayKey[r][1]+1),n[r]={numberAndNumberListChildren:{dependencyType:"child",childGroups:["numbers","numberLists"],variableNames:["value","number"+a],variablesOptional:!0,childIndices:e}}}return{globalDependencies:{childIndexByArrayKey:{dependencyType:"stateVariable",variableName:"childIndexByArrayKey"},numbersShadow:{dependencyType:"stateVariable",variableName:"numbersShadow"}},dependenciesByKey:n}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};for(let a of n){let n=t[a].numberAndNumberListChildren[0];if(n)if(void 0!==n.stateValues.value)r[a]=n.stateValues.value;else{let t=e.childIndexByArrayKey[a][1]+1;r[a]=n.stateValues["number"+t]}else null!==e.numbersShadow&&(r[a]=e.numbersShadow[a])}return{setValue:{numbers:r}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i=[];for(let t in e.numbers){if(!n[t])continue;let a=n[t].numberAndNumberListChildren[0];a&&(void 0!==a.stateValues.value?i.push({setDependency:r[t].numberAndNumberListChildren,desiredValue:e.numbers[t],childIndex:0,variableIndex:0}):i.push({setDependency:r[t].numberAndNumberListChildren,desiredValue:e.numbers[t],childIndex:0,variableIndex:1}))}return{success:!0,instructions:i}}},e.nValues={isAlias:!0,targetVariableName:"nComponents"},e.values={isAlias:!0,targetVariableName:"numbers"},e.math={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},returnDependencies:()=>({numbers:{dependencyType:"stateVariable",variableName:"numbers"}}),definition({dependencyValues:e}){let t;return t=0===e.numbers.length?me$3.fromAst("_"):1===e.numbers.length?me$3.fromAst(e.numbers[0]):me$3.fromAst(["list",...e.numbers]),{setValue:{math:t}}}},e.text={public:!0,forRenderer:!0,shadowingInstructions:{createComponentOfType:"text"},additionalStateVariablesDefined:["texts"],returnDependencies:()=>({numberAndNumberListChildren:{dependencyType:"child",childGroups:["numbers","numberLists"],variableNames:["valueForDisplay","text","texts"],variablesOptional:!0},maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"},numbersShadow:{dependencyType:"stateVariable",variableName:"numbersShadow"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"}}),definition:function({dependencyValues:e,usedDefault:t}){let n=[],r={};if(e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(r.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(r.padToDigits=e.displayDigits)),e.numberAndNumberListChildren.length>0)for(let t of e.numberAndNumberListChildren)void 0!==t.stateValues.valueForDisplay?n.push(t.stateValues.text):n.push(...t.stateValues.texts);else null!==e.numbersShadow&&(n=e.numbersShadow.map((n=>roundForDisplay({value:me$3.fromAst(n),dependencyValues:e,usedDefault:t}).toString(r))));let a=e.maximumNumber;return null!==a&&n.length>a&&(a=Math.max(0,Math.floor(a)),n=n.slice(0,a)),{setValue:{text:n.join(", "),texts:n}}}},e.componentNamesInList={returnDependencies:()=>({numberAndNumberListChildren:{dependencyType:"child",childGroups:["numbers","numberLists"],variableNames:["componentNamesInList"],variablesOptional:!0},maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=[];for(let r of e.numberAndNumberListChildren)t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"numberList"})?n.push(...r.stateValues.componentNamesInList):n.push(r.componentName);let r=e.maximumNumber;return null!==r&&n.length>r&&(r=Math.max(0,Math.floor(r)),n=n.slice(0,r)),{setValue:{componentNamesInList:n}}}},e.nComponentsToDisplayByChild={additionalStateVariablesDefined:["nChildrenToRender"],returnDependencies:()=>({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"},numberListChildren:{dependencyType:"child",childGroups:["numberLists"],variableNames:["nComponents"]},numberAndNumberListChildren:{dependencyType:"child",childGroups:["numbers","numberLists"],skipComponentNames:!0},parentNComponentsToDisplayByChild:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"nComponentsToDisplayByChild"}}),definition:function({dependencyValues:e,componentInfoObjects:t,componentName:n}){let r=e.nComponents;null!==e.parentNComponentsToDisplayByChild&&(r=e.parentNComponentsToDisplayByChild[n]);let a={},i=0,s=0,o=0;for(let n of e.numberAndNumberListChildren){let l=Math.max(0,r-i);if(l>0&&s++,t.isInheritedComponentType({inheritedComponentType:n.componentType,baseComponentType:"numberList"})){let t=e.numberListChildren[o];o++;let n=Math.min(l,t.stateValues.nComponents);a[t.componentName]=n,i+=n}else i+=1}return{setValue:{nComponentsToDisplayByChild:a,nChildrenToRender:s}}},markStale:()=>({updateRenderedChildren:!0})},e}static adapters=[{stateVariable:"math",stateVariablesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},"text"]}class NumberListFromString extends InlineComponent{static componentType="numberListFromString";static rendererType="asList";static renderChildren=!0;static stateVariableForAttributeValue="numbers";static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e}){let t=e.reduce((function(e,t){return"string"==typeof t?[...e,...t.split(/\s+/).filter((e=>e))]:[...e,t]}),[]);return{success:!0,newChildren:t}}}),e}static returnChildGroups(){return[{group:"strings",componentTypes:["string"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nComponents={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({stringChildren:{dependencyType:"child",childGroups:["strings"]}}),definition:function({dependencyValues:e}){return{setValue:{nComponents:e.stringChildren.length}}}},e.numbers={public:!0,shadowingInstructions:{createComponentOfType:"number"},isArray:!0,entryPrefixes:["number"],returnArraySizeDependencies:()=>({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"}}),returnArraySize:({dependencyValues:e})=>[e.nComponents],returnArrayDependenciesByKey:()=>({globalDependencies:{stringChildren:{dependencyType:"child",childGroups:["strings"]}}}),arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t}){let n={};for(let[t,r]of e.stringChildren.entries())n[t]=Number(r);return{setValue:{numbers:n}}}},e.nValues={isAlias:!0,targetVariableName:"nComponents"},e.values={isAlias:!0,targetVariableName:"numbers"},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},additionalStateVariablesDefined:["texts"],returnDependencies:()=>({numbers:{dependencyType:"stateVariable",variableName:"numbers"}}),definition:function({dependencyValues:e}){let t=e.numbers.map((e=>e.toString()));return{setValue:{text:t.join(", "),texts:t}}}},e}}class P$2 extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="p";static renderChildren=!0;static includeBlankStringChildren=!0;static returnChildGroups(){return[{group:"inlines",componentTypes:["_inline"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["inlines"],variableNames:["text"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let t="";for(let n of e.inlineChildren)"object"!=typeof n?t+=n.toString():"string"==typeof n.stateValues.text?t+=n.stateValues.text:t+=" ";return{setValue:{text:t}}}},e}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class BooleanList extends InlineComponent{static componentType="booleanList";static rendererType="asList";static renderChildren=!0;static includeBlankStringChildren=!0;static removeBlankStringChildrenPostSugar=!0;static stateVariableForAttributeValue="booleans";static descendantCompositesMustHaveAReplacement=!1;static createAttributesObject(){let e=super.createAttributesObject();return e.unordered={createComponentOfType:"boolean",createStateVariable:"unordered",defaultValue:!1,public:!0},e.maximumNumber={createComponentOfType:"number",createStateVariable:"maximumNumber",defaultValue:null,public:!0},e}static returnSugarInstructions(){let e=super.returnSugarInstructions(),t=returnGroupIntoComponentTypeSeparatedBySpaces({componentType:"boolean"}),n=returnBreakStringsIntoComponentTypeBySpaces({componentType:"boolean"});return e.push({replacementFunction:function({matchedChildren:e,isAttributeComponent:r=!1,createdFromMacro:a=!1}){return r&&!a?t({matchedChildren:e}):n({matchedChildren:e})}}),e}static returnChildGroups(){return[{group:"booleans",componentTypes:["boolean"]},{group:"booleanLists",componentTypes:["booleanList"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.overrideChildHide={returnDependencies:()=>({}),definition:()=>({setValue:{overrideChildHide:!0}})},e.nComponents={public:!0,shadowingInstructions:{createComponentOfType:"number"},additionalStateVariablesDefined:["childIndexByArrayKey"],returnDependencies:()=>({maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"},booleanListChildren:{dependencyType:"child",childGroups:["booleanLists"],variableNames:["nComponents"]},booleanAndBooleanListChildren:{dependencyType:"child",childGroups:["booleans","booleanLists"],skipComponentNames:!0}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=0,r=[],a=0;for(let[i,s]of e.booleanAndBooleanListChildren.entries())if(t.isInheritedComponentType({inheritedComponentType:s.componentType,baseComponentType:"booleanList"})){let t=e.booleanListChildren[a];a++;for(let e=0;ei&&(n=i,r=r.slice(0,i)),{setValue:{nComponents:n,childIndexByArrayKey:r},checkForActualChange:{nComponents:!0}}}},e.booleans={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},isArray:!0,entryPrefixes:["boolean"],stateVariablesDeterminingDependencies:["childIndexByArrayKey"],returnArraySizeDependencies:()=>({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"}}),returnArraySize:({dependencyValues:e})=>[e.nComponents],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=[],a="1";t.childIndexByArrayKey[r]&&(e=[t.childIndexByArrayKey[r][0]],a=t.childIndexByArrayKey[r][1]+1),n[r]={booleanAndBooleanListChildren:{dependencyType:"child",childGroups:["booleans","booleanLists"],variableNames:["value","boolean"+a],variablesOptional:!0,childIndices:e}}}return{globalDependencies:{childIndexByArrayKey:{dependencyType:"stateVariable",variableName:"childIndexByArrayKey"}},dependenciesByKey:n}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};for(let a of n){let n=t[a].booleanAndBooleanListChildren[0];if(n)if(void 0!==n.stateValues.value)r[a]=n.stateValues.value;else{let t=e.childIndexByArrayKey[a][1]+1;r[a]=n.stateValues["boolean"+t]}}return{setValue:{booleans:r}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i=[];for(let t in e.booleans){if(!n[t])continue;let a=n[t].booleanAndBooleanListChildren[0];a&&(void 0!==a.stateValues.value?i.push({setDependency:r[t].booleanAndBooleanListChildren,desiredValue:e.booleans[t],childIndex:0,variableIndex:0}):i.push({setDependency:r[t].booleanAndBooleanListChildren,desiredValue:e.booleans[t],childIndex:0,variableIndex:1}))}return{success:!0,instructions:i}}},e.nValues={isAlias:!0,targetVariableName:"nComponents"},e.values={isAlias:!0,targetVariableName:"booleans"},e.componentNamesInList={returnDependencies:()=>({booleanAndBooleanListChildren:{dependencyType:"child",childGroups:["booleans","booleanLists"],variableNames:["componentNamesInList"],variablesOptional:!0},maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=[];for(let r of e.booleanAndBooleanListChildren)t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"booleanList"})?n.push(...r.stateValues.componentNamesInList):n.push(r.componentName);let r=e.maximumNumber;return null!==r&&n.length>r&&(r=Math.max(0,Math.floor(r)),n=n.slice(0,r)),{setValue:{componentNamesInList:n}}}},e.nComponentsToDisplayByChild={additionalStateVariablesDefined:["nChildrenToRender"],returnDependencies:()=>({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"},booleanListChildren:{dependencyType:"child",childGroups:["booleanLists"],variableNames:["nComponents"]},booleanAndBooleanListChildren:{dependencyType:"child",childGroups:["booleans","booleanLists"],skipComponentNames:!0},parentNComponentsToDisplayByChild:{dependencyType:"parentStateVariable",parentComponentType:"booleanList",variableName:"nComponentsToDisplayByChild"}}),definition:function({dependencyValues:e,componentInfoObjects:t,componentName:n}){let r=e.nComponents;null!==e.parentNComponentsToDisplayByChild&&(r=e.parentNComponentsToDisplayByChild[n]);let a={},i=0,s=0,o=0;for(let n of e.booleanAndBooleanListChildren){let l=Math.max(0,r-i);if(l>0&&s++,t.isInheritedComponentType({inheritedComponentType:n.componentType,baseComponentType:"booleanList"})){let t=e.booleanListChildren[o];o++;let n=Math.min(l,t.stateValues.nComponents);a[t.componentName]=n,i+=n}else i+=1}return{setValue:{nComponentsToDisplayByChild:a,nChildrenToRender:s}}},markStale:()=>({updateRenderedChildren:!0})},e}}class Copy extends CompositeComponent{static componentType="copy";static assignNamesToReplacements=!0;static acceptTarget=!0;static acceptAnyAttribute=!0;static includeBlankStringChildren=!0;static stateVariableToEvaluateAfterReplacements="needsReplacementsUpdatedWhenStale";static createAttributesObject(){let e=super.createAttributesObject();return delete e.disabled,delete e.modifyIndirectly,delete e.fixed,delete e.styleNumber,delete e.isResponse,e.assignNewNamespaces={createPrimitiveOfType:"boolean"},e.assignNamesSkip={createPrimitiveOfType:"number"},e.prop={createPrimitiveOfType:"string"},e.obtainPropFromComposite={createPrimitiveOfType:"boolean",createStateVariable:"obtainPropFromComposite",defaultValue:!1,public:!0},e.createComponentOfType={createPrimitiveOfType:"string"},e.nComponents={createPrimitiveOfType:"number"},e.componentIndex={createComponentOfType:"integer",createStateVariable:"componentIndex",defaultValue:null,public:!0},e.sourceSubnames={createPrimitiveOfType:"stringArray",createStateVariable:"targetSubnames",defaultValue:null,public:!0},e.sourceSubnamesComponentIndex={createComponentOfType:"numberList",createStateVariable:"targetSubnamesComponentIndex",defaultValue:null,public:!0},e.propIndex={createComponentOfType:"numberList",createStateVariable:"propIndex",defaultValue:null,public:!0},e.uri={createPrimitiveOfType:"string",createStateVariable:"uri",defaultValue:null,public:!0},e.sourceAttributesToIgnore={createPrimitiveOfType:"stringArray",createStateVariable:"sourceAttributesToIgnore",defaultValue:["hide"],public:!0},e.sourceAttributesToIgnoreRecursively={createPrimitiveOfType:"stringArray",createStateVariable:"sourceAttributesToIgnoreRecursively",defaultValue:["isResponse"],public:!0},e.link={createPrimitiveOfType:"boolean"},e.removeEmptyArrayEntries={createPrimitiveOfType:"boolean",createStateVariable:"removeEmptyArrayEntries",defaultValue:!1},e}static keepChildrenSerialized({serializedComponent:e}){return void 0===e.children?[]:Object.keys(e.children)}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.target={returnDependencies:()=>({target:{dependencyType:"doenetAttribute",attributeName:"target"}}),definition:({dependencyValues:e})=>({setValue:{target:e.target}})},e.targetSourcesName={additionalStateVariablesDefined:[{variableName:"sourcesChildNumber",hasEssential:!0,shadowVariable:!0}],stateVariablesDeterminingDependencies:["target"],determineDependenciesImmediately:!0,hasEssential:!0,shadowVariable:!0,returnDependencies:function({stateValues:e,sharedParameters:t}){let n=t.sourceNameMappings;if(!n)return{};let r=n[e.target];return r?{targetSourcesName:{dependencyType:"value",value:r.name},sourcesChildNumber:{dependencyType:"value",value:r.childNumber}}:{}},definition:function({dependencyValues:e}){let t=e.targetSourcesName,n=e.sourcesChildNumber;return t||(t=null,n=null),{setValue:{targetSourcesName:t,sourcesChildNumber:n},setEssentialValue:{targetSourcesName:t,sourcesChildNumber:n}}}},e.targetSources={stateVariablesDeterminingDependencies:["targetSourcesName"],determineDependenciesImmediately:!0,returnDependencies:({stateValues:e})=>e.targetSourcesName?{targetSourcesComponent:{dependencyType:"componentIdentity",componentName:e.targetSourcesName}}:{},definition:function({dependencyValues:e}){let t=e.targetSourcesComponent;return t||(t=null),{setValue:{targetSources:t}}}},e.sourceIndex={stateVariablesDeterminingDependencies:["target"],determineDependenciesImmediately:!0,hasEssential:!0,shadowVariable:!0,returnDependencies:function({stateValues:e,sharedParameters:t}){let n=t.sourceIndexMappings;if(!n)return{};let r=n[e.target];return void 0===r?{}:{sourceIndex:{dependencyType:"value",value:r}}},definition:function({dependencyValues:e}){let t=e.sourceIndex;return void 0===t&&(t=null),{setValue:{sourceIndex:t},setEssentialValue:{sourceIndex:t}}}},e.targetComponent={shadowVariable:!0,stateVariablesDeterminingDependencies:["targetSources","sourceIndex"],determineDependenciesImmediately:!0,returnDependencies:({stateValues:e})=>null!==e.sourceIndex?{}:null!==e.targetSources?{targetSourcesChildren:{dependencyType:"stateVariable",componentName:e.targetSources.componentName,variableName:"childIdentities"},sourcesChildNumber:{dependencyType:"stateVariable",variableName:"sourcesChildNumber"}}:{targetComponent:{dependencyType:"targetComponent"}},definition:function({dependencyValues:e}){let t=null;return e.targetSourcesChildren?(t=e.targetSourcesChildren[e.sourcesChildNumber],t||(t=null)):e.targetComponent&&(t=e.targetComponent),{setValue:{targetComponent:t}}}},e.targetInactive={stateVariablesDeterminingDependencies:["targetComponent"],returnDependencies:({stateValues:e})=>e.targetComponent?{targetIsInactiveCompositeReplacement:{dependencyType:"stateVariable",componentName:e.targetComponent.componentName,variableName:"isInactiveCompositeReplacement"}}:{},definition:function({dependencyValues:e}){return{setValue:{targetInactive:Boolean(e.targetIsInactiveCompositeReplacement)}}}},e.cid={additionalStateVariablesDefined:["doenetId"],returnDependencies:()=>({uri:{dependencyType:"stateVariable",variableName:"uri"}}),definition:function({dependencyValues:e}){if(!e.uri||"doenet:"!==e.uri.substring(0,7).toLowerCase())return{setValue:{cid:null,doenetId:null}};let t=null,n=null,r=e.uri.match(/[:&]cid=([^&]+)/i);return r&&(t=r[1]),r=e.uri.match(/[:&]doenetid=([^&]+)/i),r&&(n=r[1]),{setValue:{cid:t,doenetId:n}}}},e.serializedComponentsForCid={returnDependencies:()=>({cid:{dependencyType:"stateVariable",variableName:"cid"},serializedChildren:{dependencyType:"serializedChildren",doNotProxy:!0}}),definition:function({dependencyValues:e}){return e.cid&&e.serializedChildren?.length>0?{setValue:{serializedComponentsForCid:e.serializedChildren}}:{setValue:{serializedComponentsForCid:null}}}},e.propName={shadowVariable:!0,returnDependencies:()=>({propName:{dependencyType:"attributePrimitive",attributeName:"prop"}}),definition:function({dependencyValues:e}){return{setValue:{propName:e.propName}}}},e.isPlainMacro={returnDependencies:()=>({isPlainMacro:{dependencyType:"doenetAttribute",attributeName:"isPlainMacro"},targetComponent:{dependencyType:"stateVariable",variableName:"targetComponent"},typeAttr:{dependencyType:"attributePrimitive",attributeName:"createComponentOfType"},targetSubnames:{dependencyType:"stateVariable",variableName:"targetSubnames"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=e.isPlainMacro&&(!t.isCompositeComponent({componentType:e.targetComponent?.componentType})||e.targetSubnames);if(n&&e.typeAttr){n=!1;let r=t.componentTypeLowerCaseMapping[e.typeAttr.toLowerCase()],a=t.allComponentClasses[e.targetComponent?.componentType];if(a){let e=t.publicStateVariableInfo[a.componentType].stateVariableDescriptions[a.variableForPlainMacro];r===a.componentType||!e||void 0!==e.createComponentOfType&&e.createComponentOfType!==r||(n=!0)}}return{setValue:{isPlainMacro:n}}}},e.isPlainCopy={returnDependencies:()=>({isPlainCopy:{dependencyType:"doenetAttribute",attributeName:"isPlainCopy"},targetComponent:{dependencyType:"stateVariable",variableName:"targetComponent"},typeAttr:{dependencyType:"attributePrimitive",attributeName:"createComponentOfType"},targetSubnames:{dependencyType:"stateVariable",variableName:"targetSubnames"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=e.isPlainCopy&&(!t.isCompositeComponent({componentType:e.targetComponent?.componentType})||e.targetSubnames);if(n&&e.typeAttr){n=!1;let r=t.componentTypeLowerCaseMapping[e.typeAttr.toLowerCase()],a=t.allComponentClasses[e.targetComponent?.componentType];if(a){let e=t.publicStateVariableInfo[a.componentType].stateVariableDescriptions[a.variableForPlainCopy];r===a.componentType||!e||void 0!==e.createComponentOfType&&e.createComponentOfType!==r||(n=!0)}}return{setValue:{isPlainCopy:n}}}},e.linkAttrForDetermineDeps={returnDependencies:()=>({linkAttr:{dependencyType:"attributePrimitive",attributeName:"link"}}),definition({dependencyValues:e}){let t;return t=null===e.linkAttr||e.linkAttr,{setValue:{linkAttrForDetermineDeps:t}}}},e.replacementSourceIdentities={stateVariablesDeterminingDependencies:["targetComponent","componentIndex","propName","targetSubnames","targetSubnamesComponentIndex","obtainPropFromComposite","linkAttrForDetermineDeps"],additionalStateVariablesDefined:["addLevelToAssignNames"],returnDependencies:function({stateValues:e,componentInfoObjects:t}){let n={},r=!1,a=!1;if(null!==e.targetComponent){if(t.isCompositeComponent({componentType:e.targetComponent.componentType,includeNonStandard:!1})&&(!e.propName||!e.obtainPropFromComposite))if(e.linkAttrForDetermineDeps){a=!0;let t=e.targetSubnamesComponentIndex;t&&(t=[...t]),n.targets={dependencyType:"replacement",compositeName:e.targetComponent.componentName,recursive:!0,componentIndex:e.componentIndex,targetSubnames:e.targetSubnames,targetSubnamesComponentIndex:t}}else r=!0;a||null!==e.componentIndex&&1!==e.componentIndex||(n.targets={dependencyType:"stateVariable",variableName:"targetComponent"})}return n.addLevelToAssignNames={dependencyType:"value",value:r},n},definition({dependencyValues:e}){let t=null;return e.targets&&(t=e.targets,Array.isArray(t)||(t=[t])),{setValue:{replacementSourceIdentities:t,addLevelToAssignNames:e.addLevelToAssignNames}}}},e.replacementSources={stateVariablesDeterminingDependencies:["replacementSourceIdentities","propName","propIndex","isPlainMacro","isPlainCopy"],additionalStateVariablesDefined:["effectivePropNameBySource"],returnDependencies:function({stateValues:e,componentInfoObjects:t}){let n={replacementSourceIdentities:{dependencyType:"stateVariable",variableName:"replacementSourceIdentities"},propIndex:{dependencyType:"stateVariable",variableName:"propIndex"}};if(!e.propName&&null!==e.propIndex)throw Error("You cannot specify a propIndex without specifying a prop.");if(null!==e.replacementSourceIdentities)for(let[r,a]of e.replacementSourceIdentities.entries()){let i,s=e.propName;if(e.isPlainMacro?s=t.allComponentClasses[a.componentType].variableForPlainMacro:e.isPlainCopy&&(s=t.allComponentClasses[a.componentType].variableForPlainCopy),s){n["propName"+r]={dependencyType:"value",value:s};let t=e.propIndex;t&&(t=[...t]),i={dependencyType:"stateVariable",componentName:a.componentName,variableName:s,returnAsComponentObject:!0,variablesOptional:!0,propIndex:t,caseInsensitiveVariableMatch:!0,publicStateVariablesOnly:!0,useMappedVariableNames:!0}}else i={dependencyType:"componentIdentity",componentName:a.componentName};n["target"+r]=i}return n},definition({dependencyValues:e}){let t=null,n=null;if(null!==e.replacementSourceIdentities){t=[],n=[];for(let r in e.replacementSourceIdentities){let a=e["target"+r];if(a){let i;t.push(a),a.stateValues&&(i=Object.keys(a.stateValues)[0]),!i&&e["propName"+r]&&(i="__prop_name_not_found"),n.push(i)}}}return{setValue:{replacementSources:t,effectivePropNameBySource:n}}}},e.nComponentsSpecified={returnDependencies:()=>({nComponentsAttr:{dependencyType:"attributePrimitive",attributeName:"nComponents"},typeAttr:{dependencyType:"attributePrimitive",attributeName:"createComponentOfType"}}),definition({dependencyValues:e,componentInfoObjects:t}){let n;if(e.typeAttr){if(!(t.componentTypeLowerCaseMapping[e.typeAttr.toLowerCase()]in t.allComponentClasses))throw Error(`Invalid componentType ${e.typeAttr} of copy.`);n=null!==e.nComponentsAttr?e.nComponentsAttr:1}else{if(null!==e.nComponentsAttr)throw Error("You must specify createComponentOfType when specifying nComponents for a copy.");n=null}return{setValue:{nComponentsSpecified:n}}}},e.link={returnDependencies:()=>({linkAttr:{dependencyType:"attributePrimitive",attributeName:"link"},serializedComponentsForCid:{dependencyType:"stateVariable",variableName:"serializedComponentsForCid"},replacementSourceIdentities:{dependencyType:"stateVariable",variableName:"replacementSourceIdentities"}}),definition({dependencyValues:e,componentInfoObjects:t}){let n;return n=null===e.linkAttr?!(e.serializedComponentsForCid||e.replacementSourceIdentities&&e.replacementSourceIdentities.some((e=>t.isInheritedComponentType({inheritedComponentType:e.componentType,baseComponentType:"module"})))):!1!==e.linkAttr,{setValue:{link:n}}}},e.readyToExpandWhenResolved={stateVariablesDeterminingDependencies:["targetComponent","propName","obtainPropFromComposite","link"],returnDependencies({stateValues:e,componentInfoObjects:t}){let n={targetComponent:{dependencyType:"stateVariable",variableName:"targetComponent"},needsReplacementsUpdatedWhenStale:{dependencyType:"stateVariable",variableName:"needsReplacementsUpdatedWhenStale"},serializedComponentsForCid:{dependencyType:"stateVariable",variableName:"serializedComponentsForCid"},link:{dependencyType:"stateVariable",variableName:"link"}};return!e.targetComponent||!t.isCompositeComponent({componentType:e.targetComponent.componentType,includeNonStandard:!1})||e.propName&&e.obtainPropFromComposite||(n.targetReadyToExpandWhenResolved={dependencyType:"stateVariable",componentName:e.targetComponent.componentName,variableName:"readyToExpandWhenResolved"}),e.link||(n.replacementSources={dependencyType:"stateVariable",variableName:"replacementSources"}),n},definition:()=>({setValue:{readyToExpandWhenResolved:!0}})},e.needsReplacementsUpdatedWhenStale={stateVariablesDeterminingDependencies:["targetComponent","replacementSourceIdentities","effectivePropNameBySource","propName","obtainPropFromComposite","link","removeEmptyArrayEntries"],returnDependencies:function({stateValues:e,componentInfoObjects:t}){if(!e.link)return{};let n={targetComponent:{dependencyType:"stateVariable",variableName:"targetComponent"},targetInactive:{dependencyType:"stateVariable",variableName:"targetInactive"},replacementSourceIdentities:{dependencyType:"stateVariable",variableName:"replacementSourceIdentities"},propIndex:{dependencyType:"stateVariable",variableName:"propIndex"}};if(null!==e.effectivePropNameBySource)for(let[t,r]of e.effectivePropNameBySource.entries())if(r){let a=e.replacementSourceIdentities[t];n["sourceArraySize"+t]={dependencyType:"stateVariableArraySize",componentName:a.componentName,variableName:r,variablesOptional:!0,caseInsensitiveVariableMatch:!0},n["sourceComponentType"+t]={dependencyType:"stateVariableComponentType",componentName:a.componentName,variableName:r,variablesOptional:!0,caseInsensitiveVariableMatch:!0}}return null===e.targetComponent||!t.isCompositeComponent({componentType:e.targetComponent.componentType,includeNonStandard:!1})||e.propName&&e.obtainPropFromComposite||(n.allReplacementIdentities={dependencyType:"replacement",compositeName:e.targetComponent.componentName,recursive:!0,variableNames:["isInactiveCompositeReplacement"]}),e.removeEmptyArrayEntries&&(n.replacementSources={dependencyType:"stateVariable",variableName:"replacementSources"}),n},markStale:()=>({updateReplacements:!0}),definition:()=>({setValue:{needsReplacementsUpdatedWhenStale:!0}})},e.effectiveAssignNames={returnDependencies:()=>({assignNames:{dependencyType:"doenetAttribute",attributeName:"assignNames"},addLevelToAssignNames:{dependencyType:"stateVariable",variableName:"addLevelToAssignNames"}}),definition({dependencyValues:e}){let t=e.assignNames;return t&&e.addLevelToAssignNames&&(t=[t]),{setValue:{effectiveAssignNames:t}}}},e}static async createSerializedReplacements({component:e,components:t,workspace:n,componentInfoObjects:r,flags:a,resolveItem:i,publicCaseInsensitiveAliasSubstitutions:s}){await e.stateValues.nComponentsSpecified,n.numReplacementsBySource=[],n.numNonStringReplacementsBySource=[],n.propVariablesCopiedBySource=[],n.sourceNames=[],n.uniqueIdentifiersUsedBySource={};let o=e.attributes.newNamespace?.primitive,l=this.createAttributesObject(),u=await e.stateValues.effectiveAssignNames,c=await e.stateValues.serializedComponentsForCid;if(c){let t=deepClone([c[0]]),i=deepClone(c.slice(1));if(t[0].children){let n;if(n=t[0].componentName?t[0].componentName+"/":t[0].originalName+"/",e.doenetAttributes.keptNewNamespaceOfLastChild){n=n.slice(0,n.length-1);let e=n.lastIndexOf("/");n=n.slice(0,e+1)}restrictTNamesToNamespace({components:t[0].children,namespace:n,invalidateReferencesToBaseNamespace:e.doenetAttributes.keptNewNamespaceOfLastChild})}if("externalContent"===t[0].componentType)for(let n of t[0].children){if("object"!=typeof n)continue;n.attributes||(n.attributes={});let t=convertAttributesForComponentType({attributes:e.attributes,componentType:n.componentType,componentInfoObjects:r,compositeAttributesObj:l,compositeCreatesNewNamespace:o,flags:a});for(let e in t){let n=t[e];n.component?setTNamesToAbsolute([n.component]):n.childrenForComponent&&setTNamesToAbsolute(n.childrenForComponent)}Object.assign(n.attributes,t)}else{t[0].attributes||(t[0].attributes={});let n=convertAttributesForComponentType({attributes:e.attributes,componentType:t[0].componentType,componentInfoObjects:r,compositeAttributesObj:l,compositeCreatesNewNamespace:o,flags:a});for(let e in n){let t=n[e];t.component?setTNamesToAbsolute([t.component]):t.childrenForComponent&&setTNamesToAbsolute(t.childrenForComponent)}Object.assign(t[0].attributes,n)}return t=processAssignNames({assignNames:u,assignNewNamespaces:e.attributes.assignNewNamespaces?.primitive,serializedComponents:t,parentName:e.componentName,parentCreatesNewNamespace:o,componentInfoObjects:r}).serializedComponents,e.doenetAttributes.fromCopyFromURI&&i.length>0&&this.addChildrenFromComposite({replacements:t,children:i,assignNewNamespaces:e.attributes.assignNewNamespaces?.primitive,componentInfoObjects:r}),{replacements:(await verifyReplacementsMatchSpecifiedType({component:e,replacements:t,assignNames:u,workspace:n,componentInfoObjects:r,compositeAttributesObj:l,flags:a})).replacements}}let p=await e.stateValues.sourceIndex;if(null!==p){let t=processAssignNames({assignNames:u,serializedComponents:[{componentType:"number",attributes:convertAttributesForComponentType({attributes:e.attributes,componentType:"number",componentInfoObjects:r,compositeAttributesObj:l,compositeCreatesNewNamespace:o,flags:a}),state:{value:p,fixed:!0}}],parentName:e.componentName,parentCreatesNewNamespace:o,componentInfoObjects:r});return{replacements:(await verifyReplacementsMatchSpecifiedType({component:e,replacements:t.serializedComponents,assignNames:u,workspace:n,componentInfoObjects:r,compositeAttributesObj:l,flags:a})).replacements}}let d=await e.stateValues.replacementSourceIdentities;if(!await e.stateValues.targetComponent||!d){let t=[];if(e.doenetAttributes.fromCopyTarget){let i=r.componentTypeLowerCaseMapping[e.attributes.createComponentOfType.primitive.toLowerCase()],s=r.allComponentClasses[i],c=convertAttributesForComponentType({attributes:e.attributes,componentType:i,componentInfoObjects:r,compositeAttributesObj:l,compositeCreatesNewNamespace:o,flags:a});n.uniqueIdentifiersUsedBySource[0]=[];let p=getUniqueIdentifierFromBase(i+"|empty",n.uniqueIdentifiersUsedBySource[0]),d=deepClone(e.serializedChildren);s.includeBlankStringChildren||(d=d.filter((e=>"string"!=typeof e||""!==e.trim())));let m=c;e.attributes.assignNewNamespaces?.primitive&&(m.newNamespace={primitive:!0}),t=[{componentType:i,attributes:m,children:d,uniqueIdentifier:p}],t=processAssignNames({assignNames:u,serializedComponents:t,parentName:e.componentName,componentInfoObjects:r,originalNamesAreConsistent:!0}).serializedComponents,n.numReplacementsBySource.push(t.length),n.numNonStringReplacementsBySource.push(t.filter((e=>"string"!=typeof e)).length)}return{replacements:(await verifyReplacementsMatchSpecifiedType({component:e,replacements:t,assignNames:u,workspace:n,componentInfoObjects:r,compositeAttributesObj:l})).replacements}}let m=await i({componentName:e.componentName,type:"determineDependencies",stateVariable:"replacementSources",dependency:"__determine_dependencies",expandComposites:!1});if(!m.success)throw Error(`Couldn't resolve determineDependencies of replacementSources of ${e.componentName}`);let h=await e.stateValues.effectivePropNameBySource;for(let t in d){if(h[t]&&(m=await i({componentName:e.componentName,type:"recalculateDownstreamComponents",stateVariable:"replacementSources",dependency:"target"+t,expandComposites:!1}),!m.success))throw Error(`Couldn't resolve recalculateDownstreamComponents for target${t} of replacementSources of ${e.componentName}`)}let f=[],y=[],g=[],b=0,v=0;for(let i in d){let o,u=n.uniqueIdentifiersUsedBySource[i]=[];if(e.attributes.createComponentOfType?.primitive){let t=await e.stateValues.nComponentsSpecified,n=d.length;o=Math.floor(t/n),i"string"!=typeof e)).length,b+=y[i],v+=g[i],f.push(...p)}return n.numReplacementsBySource=y,n.numNonStringReplacementsBySource=g,n.sourceNames=d.map((e=>e.componentName)),{replacements:(await verifyReplacementsMatchSpecifiedType({component:e,replacements:f,assignNames:u,workspace:n,componentInfoObjects:r,compositeAttributesObj:l,flags:a})).replacements}}static async createReplacementForSource({component:e,sourceNum:t,components:n,numReplacementsSoFar:r,numNonStringReplacementsSoFar:a,uniqueIdentifiersUsed:i,compositeAttributesObj:s,componentInfoObjects:o,nComponentsForSource:l,publicCaseInsensitiveAliasSubstitutions:u,flags:c,fromCopyTarget:p}){let d=(await e.stateValues.replacementSourceIdentities)[t];if("object"!=typeof d)return{serializedReplacements:[d]};let m=n[d.componentName],h=await e.stateValues.link;h&&!await e.stateValues.removeEmptyArrayEntries||(d=(await e.stateValues.replacementSources)[t]);let f=e.attributes.newNamespace?.primitive,y=await e.stateValues.effectiveAssignNames,g=(await e.stateValues.effectivePropNameBySource)[t];if(g){let t=await replacementFromProp({component:e,components:n,replacementSource:d,propName:g,numReplacementsSoFar:r,numNonStringReplacementsSoFar:a,uniqueIdentifiersUsed:i,compositeAttributesObj:s,componentInfoObjects:o,nComponentsForSource:l,publicCaseInsensitiveAliasSubstitutions:u,flags:c});return{serializedReplacements:processAssignNames({assignNames:y,serializedComponents:t.serializedReplacements,parentName:e.componentName,parentCreatesNewNamespace:f,indOffset:a,componentInfoObjects:o}).serializedComponents,propVariablesCopiedByReplacement:t.propVariablesCopiedByReplacement}}let b=await e.stateValues.sourceAttributesToIgnore,v=await e.stateValues.sourceAttributesToIgnoreRecursively,N=[await m.serialize({copyAll:!h,copyVariants:!h,sourceAttributesToIgnore:b,sourceAttributesToIgnoreRecursively:v})];h||void 0===N[0].state?.fixed||delete N[0].state.fixed,N=postProcessCopy({serializedComponents:N,componentName:e.componentName,uniqueIdentifiersUsed:i,addShadowDependencies:h,unlinkExternalCopies:!h}),N.length>0&&delete N[0].doenetAttributes.haveNewNamespaceOnlyFromShadow;for(let t of N){if("object"!=typeof t)continue;t.attributes||(t.attributes={});let n=convertAttributesForComponentType({attributes:e.attributes,componentType:t.componentType,componentInfoObjects:o,compositeAttributesObj:s,compositeCreatesNewNamespace:f,flags:c});Object.assign(t.attributes,n)}return N[0].attributes.newNamespace?.primitive&&!e.attributes.assignNewNamespaces?.primitive&&(N[0].doenetAttributes.haveNewNamespaceOnlyFromShadow=!0),N=processAssignNames({assignNames:y,assignNewNamespaces:e.attributes.assignNewNamespaces?.primitive,serializedComponents:N,parentName:e.componentName,parentCreatesNewNamespace:f,indOffset:a,componentInfoObjects:o,originalNamesAreConsistent:f&&!y}).serializedComponents,p&&1===N.length&&e.serializedChildren.length>0&&this.addChildrenFromComposite({replacements:N,children:e.serializedChildren,assignNewNamespaces:e.attributes.assignNewNamespaces?.primitive,componentInfoObjects:o}),{serializedReplacements:N}}static addChildrenFromComposite({replacements:e,children:t,assignNewNamespaces:n,componentInfoObjects:r}){let a=e[0];a.children||(a.children=[]);let i=deepClone(t);if(r.allComponentClasses[a.componentType].includeBlankStringChildren||(i=i.filter((e=>"string"!=typeof e||""!==e.trim()))),e[0].attributes.newNamespace?.primitive&&n){renameAutonameBasedOnNewCounts(i,countRegularComponentTypesInNamespace(a.children))}let s=processAssignNames({serializedComponents:i,parentName:e[0].componentName,parentCreatesNewNamespace:n,componentInfoObjects:r,originalNamesAreConsistent:!0});if(e[0].attributes.newNamespace?.primitive&&!n)for(let e of s.serializedComponents)"object"==typeof e&&(e.doenetAttributes.ignoreParentNewNamespace=!0);a.children.push(...s.serializedComponents)}static async calculateReplacementChanges({component:e,componentChanges:t,components:n,workspace:r,componentInfoObjects:a,flags:i,resolveItem:s,publicCaseInsensitiveAliasSubstitutions:o}){if(await e.stateValues.serializedComponentsForCid)return[];if(null!==await e.stateValues.sourceIndex)return[];let l=this.createAttributesObject(),u=await e.stateValues.effectiveAssignNames,c=await e.stateValues.replacementSourceIdentities;if(!await e.stateValues.targetComponent||!c){if(await e.stateValues.targetSources)return[];{let t=[];if(e.replacements.length>0){let n={changeType:"delete",changeTopLevelReplacements:!0,firstReplacementInd:0,numberReplacementsToDelete:e.replacements.length};t.push(n)}let n=0===r.sourceNames.length;r.sourceNames=[],r.numReplacementsBySource=[],r.numNonStringReplacementsBySource=[],r.propVariablesCopiedBySource=[];let s=await verifyReplacementsMatchSpecifiedType({component:e,replacementChanges:t,assignNames:u,workspace:r,componentInfoObjects:a,compositeAttributesObj:l,flags:i});return n?[]:s.replacementChanges}}if(await e.stateValues.targetInactive){let t=[],n=e.replacements.length;if(n>0){if(e.replacementsToWithhold!==n){let e={changeType:"changeReplacementsToWithhold",replacementsToWithhold:n};t.push(e)}t=(await verifyReplacementsMatchSpecifiedType({component:e,replacementChanges:t,assignNames:u,workspace:r,componentInfoObjects:a,compositeAttributesObj:l,flags:i})).replacementChanges}return t}let p=await s({componentName:e.componentName,type:"determineDependencies",stateVariable:"replacementSources",dependency:"__determine_dependencies",expandComposites:!1});if(!p.success)throw Error(`Couldn't resolve determineDependencies of replacementSources of ${e.componentName}`);let d=await e.stateValues.effectivePropNameBySource;for(let t in c){if(d[t]&&(p=await s({componentName:e.componentName,type:"recalculateDownstreamComponents",stateVariable:"replacementSources",dependency:"target"+t,expandComposites:!1}),!p.success))throw Error(`Couldn't resolve recalculateDownstreamComponents for target${t} of replacementSources of ${e.componentName}`)}let m=[];if(e.replacementsToWithhold>0){let e={changeType:"changeReplacementsToWithhold",replacementsToWithhold:0};m.push(e)}let h=0,f=0,y=[],g=[],b=[],v=Math.max(c.length,r.numReplacementsBySource.length),N=!1;for(let t=0;t0){if(!N){let e=r.numReplacementsBySource.slice(t).reduce(((e,t)=>e+t),0);if(e>0){let t={changeType:"delete",changeTopLevelReplacements:!0,firstReplacementInd:h,numberReplacementsToDelete:e};m.push(t)}N=!0,r.numReplacementsBySource.slice(t).forEach(((e,t)=>r.numReplacementsBySource[t]=0)),r.numNonStringReplacementsBySource.slice(t).forEach(((e,t)=>r.numNonStringReplacementsBySource[t]=0))}r.uniqueIdentifiersUsedBySource[t]=[]}y[t]=0,g[t]=0,b.push([]);continue}let p=r.sourceNames[t],v=void 0===p||u.componentName!==p||N;if(!v)for(let n=0;ne+t),0);v.numberReplacementsToReplace=e,N=!0,r.numReplacementsBySource.slice(t).forEach(((e,t)=>r.numReplacementsBySource[t]=0)),r.numNonStringReplacementsBySource.slice(t).forEach(((e,t)=>r.numNonStringReplacementsBySource[t]=0))}m.push(v);continue}if(!d[t]&&r.numReplacementsBySource[t]>0){h+=r.numReplacementsBySource[t],f+=r.numNonStringReplacementsBySource[t],y[t]=r.numReplacementsBySource[t],g[t]=r.numNonStringReplacementsBySource[t];continue}let T=r.uniqueIdentifiersUsedBySource[t]=[],C=await this.createReplacementForSource({component:e,sourceNum:t,components:n,numReplacementsSoFar:h,numNonStringReplacementsSoFar:f,uniqueIdentifiersUsed:T,compositeAttributesObj:l,componentInfoObjects:a,nComponentsForSource:s,publicCaseInsensitiveAliasSubstitutions:o,flags:i}),A=C.propVariablesCopiedByReplacement,V=C.serializedReplacements,x=V.length;if(x!==r.numReplacementsBySource[t]){let e=r.numReplacementsBySource.slice(t).reduce(((e,t)=>e+t),0),n={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:h,numberReplacementsToReplace:e,serializedReplacements:V,assignNamesOffset:f};m.push(n),N=!0,r.numReplacementsBySource.slice(t).forEach(((e,t)=>r.numReplacementsBySource[t]=0)),r.numNonStringReplacementsBySource.slice(t).forEach(((e,t)=>r.numNonStringReplacementsBySource[t]=0))}else{let n=0;for(let a=0;ae!==A[a][t]))?(s=!1,i=!0):e.replacements[h+a].componentType!==V[a].componentType&&(i=!0)),0==a&&i&&s){1===await e.stateValues.nComponentsSpecified&&1===x&&!(e.replacementsToWithhold>0)&&1===r.sourceNames.length&&(i=!1)}if(i){let e={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:h+a,numberReplacementsToReplace:1,serializedReplacements:[V[a]],assignNamesOffset:f+n};m.push(e)}"string"!=typeof V[a]&&n++}}let S=V.filter((e=>"string"!=typeof e)).length;h+=x,f+=S,y[t]=x,g[t]=S,b[t]=A}let T=0===r.sourceNames.length;r.numReplacementsBySource=y,r.numNonStringReplacementsBySource=g,r.sourceNames=c.map((e=>e.componentName)),r.propVariablesCopiedBySource=b;let C=await verifyReplacementsMatchSpecifiedType({component:e,replacementChanges:m,assignNames:u,workspace:r,componentInfoObjects:a,compositeAttributesObj:l,flags:i});return T&&0===r.sourceNames.length?[]:C.replacementChanges}static async recreateReplacements({component:e,sourceNum:t,numReplacementsSoFar:n,numNonStringReplacementsSoFar:r,numReplacementsToDelete:a,uniqueIdentifiersUsed:i,components:s,compositeAttributesObj:o,componentInfoObjects:l,nComponentsForSource:u,publicCaseInsensitiveAliasSubstitutions:c,flags:p}){let d=await this.createReplacementForSource({component:e,sourceNum:t,numReplacementsSoFar:n,numNonStringReplacementsSoFar:r,components:s,uniqueIdentifiersUsed:i,compositeAttributesObj:o,componentInfoObjects:l,nComponentsForSource:u,publicCaseInsensitiveAliasSubstitutions:c,flags:p}),m=d.propVariablesCopiedByReplacement,h=d.serializedReplacements,f={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:n,numberReplacementsToReplace:a,serializedReplacements:h,assignNamesOffset:r};return{numReplacements:h.length,numNonStringReplacements:h.filter((e=>"string"!=typeof e)).length,propVariablesCopiedByReplacement:m,replacementInstruction:f}}}async function replacementFromProp({component:e,components:t,replacementSource:n,propName:r,uniqueIdentifiersUsed:a,compositeAttributesObj:i,componentInfoObjects:s,nComponentsForSource:o,publicCaseInsensitiveAliasSubstitutions:l,flags:u}){let c=[],p=[],d=e.attributes.newNamespace?.primitive,m=-1,h=t[n.componentName],f=l({stateVariables:[r],componentClass:h.constructor})[0];if(void 0===f||"__not_public"===f.slice(0,12))return"__prop_name_not_found"!==r&&console.warn(`Could not find prop ${r} on a component of type ${n.componentType}`),{serializedReplacements:[],propVariablesCopiedByReplacement:[]};let y=h.state[f],g=await y.value,b=await e.stateValues.link;if(y.isArray||y.isArrayEntry){let t,r,l,g;if(y.isArray?(t=y,l=await y.arraySize,r=y.getAllArrayKeys(l,!1)):(t=h.state[y.arrayStateVariable],r=await y.unflattenedArrayKeys,g=await y.arrayKeys),t.shadowingInstructions?.hasVariableComponentType&&(await e.stateValues.replacementSources,!t.shadowingInstructions.createComponentOfType))return{serializedReplacements:[],propVariablesCopiedByReplacement:[]};let v=y.wrappingComponents,N=v.length,T=o;if(y.isArray)T=l.slice(0,l.length-N).reduce(((e,t)=>e*t),1);else if(0===g.length)T=0;else if(0===N)T=g.length;else if(N>=y.nDimensions)T=1;else if(N===y.nDimensions-1)T=r.length;else{T=flattenLevels(r,y.nDimensions-N-1).length}if(0===N){let o=flattenDeep(r);for(let r=0;r1)for(let e of r){let t=await o(e,i-1);l.push(...t.pieces),c.push(...t.propVariablesCopiedByPiece)}else for(let i of r){let r,o,p=t.arrayVarNameFromArrayKey(i),d=[p],m=getUniqueIdentifierFromBase(n.componentName+"|shadow|"+p,a),f=t.shadowingInstructions.createComponentOfType;if(Array.isArray(f)&&(f=f[t.keyToIndex(i)]),t.shadowingInstructions.addAttributeComponentsShadowingStateVariables){r={};for(let e in t.shadowingInstructions.addAttributeComponentsShadowingStateVariables){let n=t.shadowingInstructions.addAttributeComponentsShadowingStateVariables[e].stateVariableToShadow,a=h.state[n];a.isArray&&(n=a.arrayVarNameFromArrayKey(i)),r[e]={stateVariableToShadow:n}}}if(t.shadowingInstructions.addStateVariablesShadowingStateVariables){o={};for(let e in t.shadowingInstructions.addStateVariablesShadowingStateVariables){let n=t.shadowingInstructions.addStateVariablesShadowingStateVariables[e].stateVariableToShadow,r=h.state[n];r.isArray&&(n=r.arrayVarNameFromArrayKey(i)),o[e]={stateVariableToShadow:n}}}if(b){let t={};if(r){let n=s.allComponentClasses[f].createAttributesObject();for(let a in r){let i=r[a].stateVariableToShadow,s={componentType:n[a].createComponentOfType,downstreamDependencies:{[h.componentName]:[{compositeName:e.componentName,dependencyType:"referenceShadow",propVariable:i}]}};t[a]={component:s}}}l.push({componentType:f,attributes:t,downstreamDependencies:{[n.componentName]:[{dependencyType:"referenceShadow",compositeName:e.componentName,propVariable:p,additionalStateVariableShadowing:o}]},uniqueIdentifier:m})}else{let e={};if(r){let t={};for(let e in r){let n=r[e].stateVariableToShadow,a=h.state[n],s=await a.value;a.isArray&&(s=s[a.keyToIndex[i]]),h.state[n].usedDefault||(t[e]=s)}let n=convertAttributesForComponentType({attributes:t,componentType:f,componentInfoObjects:s,flags:u});if(y.shadowingInstructions.attributesToShadow)for(let e of y.shadowingInstructions.attributesToShadow)h.attributes[e]?.component?n[e]={component:await(h.attributes[e]?.component.serialize({copyAll:!0,copyVariants:!0}))}:void 0!==h.attributes[e]?.primitive&&(n[e]={primitive:JSON.parse(JSON.stringify(h.attributes[e].primitive))});Object.assign(e,n)}let n="value",a=s.allComponentClasses[f];a.primaryEssentialStateVariable?n=a.primaryEssentialStateVariable:a.primaryStateVariableForDefinition&&(n=a.primaryStateVariableForDefinition);let o=t.keyToIndex(i);Array.isArray(o)||(o=[o]);let c=await t.value;for(let e of o)c=c[e];let p={componentType:f,attributes:e,state:{[n]:c},uniqueIdentifier:m};l.push(p)}c.push(d)}let p=v[i-1];if(l.length>0&&p&&p.length>0){for(let e=p.length-1;e>=0;e--){let t="object"==typeof p[e]?p[e].componentType:p[e],n=getUniqueIdentifierFromBase(t+"|wrapper",a),r=[],i={};for(let e of l)if(e.isAttribute){let t=e.isAttribute;delete e.isAttribute,i[t]={component:e}}else r.push(e);l=[{componentType:t,children:r,attributes:i,uniqueIdentifier:n,skipSugar:!0}],"object"==typeof p[e]&&(p[e].doenetAttributes&&(l[0].doenetAttributes=Object.assign({},p[e].doenetAttributes)),p[e].isAttribute&&(l[0].isAttribute=p[e].isAttribute))}c=[flattenDeep(c)]}return{pieces:l,propVariablesCopiedByPiece:c}},l=await o(r,y.nDimensions),N=l.pieces;p=l.propVariablesCopiedByPiece;for(let t of N){if("object"!=typeof t)continue;t.attributes||(t.attributes={});let r=convertAttributesForComponentType({attributes:e.attributes,componentType:t.componentType,componentInfoObjects:s,compositeAttributesObj:i,compositeCreatesNewNamespace:d,flags:u});Object.assign(t.attributes,r),b&&(t.downstreamDependencies={[n.componentName]:[{dependencyType:"referenceShadow",compositeName:e.componentName,propVariable:f,ignorePrimaryStateVariable:!0}]})}if(m+=N.length,c.push(...N),N.length0?"object"==typeof i[0]?(n=i[0].componentType,r=Object.assign({},i[0].doenetAttributes)):n=i[0]:(n=t.shadowingInstructions.createComponentOfType,Array.isArray(n)&&(n=y.isArrayEntry?n[t.keyToIndex(g[e])]:n[e]));let s={componentType:n,uniqueIdentifier:getUniqueIdentifierFromBase(n+"|empty",a)};r&&(s.doenetAttributes=r),c.push(s)}else if(N>T)throw Error(`Something went wrong when creating replacements for ${e.componentName} as we ended up with too many replacements`)}}else{if(y.shadowingInstructions?.hasVariableComponentType&&await y.value,!y.shadowingInstructions?.createComponentOfType)return{serializedReplacements:[],propVariablesCopiedByReplacement:[]};m++,(p[m]=[]).push(f);let t=getUniqueIdentifierFromBase(h.componentName+"|shadow|"+f,a);if("string"===y.shadowingInstructions.createComponentOfType)c.push(await y.value);else{let n=convertAttributesForComponentType({attributes:e.attributes,componentType:y.shadowingInstructions.createComponentOfType,componentInfoObjects:s,compositeAttributesObj:i,compositeCreatesNewNamespace:d,flags:u});if(b){let r={};if(y.shadowingInstructions.addAttributeComponentsShadowingStateVariables){let t=s.allComponentClasses[y.shadowingInstructions.createComponentOfType].createAttributesObject();for(let n in y.shadowingInstructions.addAttributeComponentsShadowingStateVariables){let a=y.shadowingInstructions.addAttributeComponentsShadowingStateVariables[n].stateVariableToShadow,i={componentType:t[n].createComponentOfType,downstreamDependencies:{[h.componentName]:[{compositeName:e.componentName,dependencyType:"referenceShadow",propVariable:a}]}};r[n]={component:i}}}Object.assign(r,n),c.push({componentType:y.shadowingInstructions.createComponentOfType,attributes:r,downstreamDependencies:{[h.componentName]:[{dependencyType:"referenceShadow",compositeName:e.componentName,propVariable:f,additionalStateVariableShadowing:y.shadowingInstructions.addStateVariablesShadowingStateVariables}]},uniqueIdentifier:t})}else{let e={};if(y.shadowingInstructions.addAttributeComponentsShadowingStateVariables){let t={};for(let e in y.shadowingInstructions.addAttributeComponentsShadowingStateVariables)if("fixed"!==e){let n=y.shadowingInstructions.addAttributeComponentsShadowingStateVariables[e].stateVariableToShadow,r=await h.state[n].value;h.state[n].usedDefault||(t[e]=r)}let n=convertAttributesForComponentType({attributes:t,componentType:y.shadowingInstructions.createComponentOfType,componentInfoObjects:s,flags:u});if(y.shadowingInstructions.attributesToShadow)for(let e of y.shadowingInstructions.attributesToShadow)h.attributes[e]?.component?n[e]={component:await(h.attributes[e]?.component.serialize({copyAll:!0,copyVariants:!0}))}:void 0!==h.attributes[e]?.primitive&&(n[e]={primitive:JSON.parse(JSON.stringify(h.attributes[e].primitive))});Object.assign(e,n)}Object.assign(e,n);let r="value",a=s.allComponentClasses[y.shadowingInstructions.createComponentOfType];a.primaryEssentialStateVariable?r=a.primaryEssentialStateVariable:a.primaryStateVariableForDefinition&&(r=a.primaryStateVariableForDefinition);let i={componentType:y.shadowingInstructions.createComponentOfType,attributes:e,state:{[r]:g},uniqueIdentifier:t};c.push(i)}}}return{serializedReplacements:c,propVariablesCopiedByReplacement:p}}class Extract extends CompositeComponent{static componentType="extract";static assignNamesToReplacements=!0;static acceptAnyAttribute=!0;static stateVariableToEvaluateAfterReplacements="needsReplacementsUpdatedWhenStale";static createAttributesObject(){let e=super.createAttributesObject();return delete e.disabled,delete e.modifyIndirectly,delete e.fixed,delete e.styleNumber,delete e.isResponse,e.assignNamesSkip={createPrimitiveOfType:"number"},e.prop={createPrimitiveOfType:"string"},e.createComponentOfType={createPrimitiveOfType:"string"},e.nComponents={createPrimitiveOfType:"number"},e.componentIndex={createComponentOfType:"integer",createStateVariable:"componentIndex",defaultValue:null,public:!0},e.propIndex={createComponentOfType:"numberList",createStateVariable:"propIndex",defaultValue:null,public:!0},e}static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nComponentsSpecified={returnDependencies:()=>({nComponentsAttr:{dependencyType:"attributePrimitive",attributeName:"nComponents"},typeAttr:{dependencyType:"attributePrimitive",attributeName:"createComponentOfType"}}),definition({dependencyValues:e,componentInfoObjects:t}){let n;if(e.typeAttr){if(!(t.componentTypeLowerCaseMapping[e.typeAttr.toLowerCase()]in t.allComponentClasses))throw Error(`Invalid componentType ${e.typeAttr} of copy.`);n=null!==e.nComponentsAttr?e.nComponentsAttr:1}else{if(null!==e.nComponentsAttr)throw Error("You must specify createComponentOfType when specifying nComponents for a copy.");n=null}return{setValue:{nComponentsSpecified:n}}}},e.link={returnDependencies:()=>({}),definition:()=>({setValue:{link:!0}})},e.propName={shadowVariable:!0,returnDependencies:()=>({propName:{dependencyType:"attributePrimitive",attributeName:"prop"}}),definition:function({dependencyValues:e}){return{setValue:{propName:e.propName}}}},e.sourceComponents={stateVariablesDeterminingDependencies:["propName","componentIndex","propIndex"],additionalStateVariablesDefined:["effectivePropNameBySource"],returnDependencies:function({stateValues:e}){let t,n;null!==e.componentIndex&&(n=Number(e.componentIndex),t=Number.isInteger(n)?[n-1]:[]);let r=e.propIndex;return r&&(r=[...r]),{children:{dependencyType:"child",childGroups:["anything"],variableNames:[e.propName],variablesOptional:!0,childIndices:t,propIndex:r,caseInsensitiveVariableMatch:!0,publicStateVariablesOnly:!0,useMappedVariableNames:!0},propName:{dependencyType:"stateVariable",variableName:"propName"}}},definition:function({dependencyValues:e}){let t=e.children,n=[];for(let e of t){let t;e.stateValues&&(t=Object.keys(e.stateValues)[0]),t||(t="__prop_name_not_found"),n.push(t)}return{setValue:{sourceComponents:t,effectivePropNameBySource:n}}}},e.readyToExpandWhenResolved={returnDependencies:()=>({replacementClasses:{dependencyType:"stateVariable",variableName:"sourceComponents"},needsReplacementsUpdatedWhenStale:{dependencyType:"stateVariable",variableName:"needsReplacementsUpdatedWhenStale"}}),definition:()=>({setValue:{readyToExpandWhenResolved:!0}})},e.needsReplacementsUpdatedWhenStale={returnDependencies:()=>({sourceComponents:{dependencyType:"stateVariable",variableName:"sourceComponents"}}),markStale:()=>({updateReplacements:!0}),definition:()=>({setValue:{needsReplacementsUpdatedWhenStale:!0}})},e}static async createSerializedReplacements({component:e,components:t,workspace:n,componentInfoObjects:r,flags:a,publicCaseInsensitiveAliasSubstitutions:i}){let s=[],o=[],l=0;n.propVariablesCopiedBySource=[],n.uniqueIdentifiersUsedBySource={};let u=this.createAttributesObject(),c=await e.stateValues.sourceComponents;for(let a=0;ae.componentName)),{replacements:(await verifyReplacementsMatchSpecifiedType({component:e,replacements:s,assignNames:e.doenetAttributes.assignNames,workspace:n,componentInfoObjects:r,compositeAttributesObj:u,flags:a})).replacements}}static async createReplacementForSource({component:e,components:t,sourceNum:n,numReplacementsSoFar:r,uniqueIdentifiersUsed:a,componentInfoObjects:i,compositeAttributesObj:s,publicCaseInsensitiveAliasSubstitutions:o}){let l=(await e.stateValues.effectivePropNameBySource)[n],u=await replacementFromProp({component:e,components:t,replacementSource:(await e.stateValues.sourceComponents)[n],propName:l,uniqueIdentifiersUsed:a,compositeAttributesObj:s,componentInfoObjects:i,publicCaseInsensitiveAliasSubstitutions:o}),c=u.serializedReplacements,p=u.propVariablesCopiedByReplacement,d=e.attributes.newNamespace?.primitive;return c=processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:c,parentName:e.componentName,indOffset:r,parentCreatesNewNamespace:d,componentInfoObjects:i}).serializedComponents,{serializedReplacements:c,propVariablesCopiedByReplacement:p}}static async calculateReplacementChanges({component:e,components:t,workspace:n,componentInfoObjects:r,flags:a,publicCaseInsensitiveAliasSubstitutions:i}){let s=[],o=0,l=[],u=[],c=this.createAttributesObject(),p=await e.stateValues.sourceComponents,d=Math.max(p.length,n.numReplacementsBySource.length),m=!1;for(let a=0;a0){if(!m){let e=n.numReplacementsBySource.slice(a).reduce(((e,t)=>e+t),0);if(e>0){let t={changeType:"delete",changeTopLevelReplacements:!0,firstReplacementInd:o,numberReplacementsToDelete:e};s.push(t)}m=!0,n.numReplacementsBySource.slice(a).forEach(((e,t)=>n.numReplacementsBySource[t]=0))}n.uniqueIdentifiersUsedBySource[a]=[]}l[a]=0,u.push([]);continue}let h=n.sourceNames[a],f=void 0===h||d.componentName!==h||m;if(!f)for(let t=0;te+t),0);g.numberReplacementsToReplace=e,m=!0,n.numReplacementsBySource.slice(a).forEach(((e,t)=>n.numReplacementsBySource[t]=0))}s.push(g);continue}let y=n.uniqueIdentifiersUsedBySource[a]=[],g=await this.createReplacementForSource({component:e,sourceNum:a,components:t,numReplacementsSoFar:o,uniqueIdentifiersUsed:y,componentInfoObjects:r,compositeAttributesObj:c,publicCaseInsensitiveAliasSubstitutions:i}),b=g.propVariablesCopiedByReplacement,v=g.serializedReplacements,N=v.length;if(N!==n.numReplacementsBySource[a]){let e=n.numReplacementsBySource.slice(a).reduce(((e,t)=>e+t),0),t={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:o,numberReplacementsToReplace:e,serializedReplacements:v,assignNamesOffset:o};s.push(t),m=!0,n.numReplacementsBySource.slice(a).forEach(((e,t)=>n.numReplacementsBySource[t]=0))}else for(let e=0;et!==b[e][n]))){let t={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:o+e,numberReplacementsToReplace:1,serializedReplacements:[v[e]],assignNamesOffset:o+e};s.push(t)}o+=N,l[a]=N,u[a]=b}return n.numReplacementsBySource=l,n.numNonStringReplacementsBySource=[...l],n.sourceNames=p.map((e=>e.componentName)),n.propVariablesCopiedBySource=u,(await verifyReplacementsMatchSpecifiedType({component:e,replacementChanges:s,assignNames:e.doenetAttributes.assignNames,workspace:n,componentInfoObjects:r,compositeAttributesObj:c,flags:a})).replacementChanges}static async recreateReplacements({component:e,sourceNum:t,numReplacementsSoFar:n,numReplacementsToDelete:r,uniqueIdentifiersUsed:a,components:i,componentInfoObjects:s,compositeAttributesObj:o,publicCaseInsensitiveAliasSubstitutions:l}){let u=await this.createReplacementForSource({component:e,sourceNum:t,numReplacementsSoFar:n,components:i,uniqueIdentifiersUsed:a,componentInfoObjects:s,compositeAttributesObj:o,publicCaseInsensitiveAliasSubstitutions:l}),c=u.propVariablesCopiedByReplacement,p=u.serializedReplacements,d={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:n,numberReplacementsToReplace:r,serializedReplacements:p,assignNamesOffset:n};return{numReplacements:p.length,propVariablesCopiedByReplacement:c,replacementInstruction:d}}}class Collect extends CompositeComponent{static componentType="collect";static assignNamesToReplacements=!0;static acceptTarget=!0;static acceptAnyAttribute=!0;static stateVariableToEvaluateAfterReplacements="needsReplacementsUpdatedWhenStale";static createAttributesObject(){let e=super.createAttributesObject();return delete e.disabled,delete e.modifyIndirectly,delete e.fixed,delete e.styleNumber,delete e.isResponse,e.assignNamesSkip={createPrimitiveOfType:"number"},e.prop={createPrimitiveOfType:"string"},e.maximumNumber={createComponentOfType:"number",createStateVariable:"maximumNumber",defaultValue:null,public:!0},e.componentIndex={createComponentOfType:"integer",createStateVariable:"componentIndex",defaultValue:null,public:!0},e.propIndex={createComponentOfType:"numberList",createStateVariable:"propIndex",defaultValue:null,public:!0},e.sourceAttributesToIgnore={createPrimitiveOfType:"stringArray",createStateVariable:"sourceAttributesToIgnore",defaultValue:[],public:!0},e.sourceAttributesToIgnoreRecursively={createPrimitiveOfType:"stringArray",createStateVariable:"sourceAttributesToIgnoreRecursively",defaultValue:["isResponse"],public:!0},e.componentTypes={createComponentOfType:"textList"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.link={returnDependencies:()=>({}),definition:()=>({setValue:{link:!0}})},e.targetComponent={shadowVariable:!0,returnDependencies:()=>({targetComponent:{dependencyType:"targetComponent"}}),definition:function({dependencyValues:e}){return{setValue:{targetComponent:e.targetComponent}}}},e.targetInactive={stateVariablesDeterminingDependencies:["targetComponent"],returnDependencies:({stateValues:e})=>e.targetComponent?{targetIsInactiveCompositeReplacement:{dependencyType:"stateVariable",componentName:e.targetComponent.componentName,variableName:"isInactiveCompositeReplacement"}}:{},definition:function({dependencyValues:e}){return{setValue:{targetInactive:Boolean(e.targetIsInactiveCompositeReplacement)}}}},e.targetName={returnDependencies:()=>({targetComponent:{dependencyType:"stateVariable",variableName:"targetComponent"}}),definition:function({dependencyValues:e}){return null===e.targetComponent?(console.warn("No copy target"),{setValue:{targetName:""}}):{setValue:{targetName:e.targetComponent.componentName}}}},e.propName={shadowVariable:!0,returnDependencies:()=>({propName:{dependencyType:"attributePrimitive",attributeName:"prop"}}),definition:function({dependencyValues:e}){return{setValue:{propName:e.propName}}}},e.componentTypesToCollect={shadowVariable:!0,additionalStateVariablesDefined:[{variableName:"componentClassesToCollect",shadowVariable:!0}],returnDependencies:()=>({componentTypesAttr:{dependencyType:"attributeComponent",attributeName:"componentTypes",variableNames:["texts"]}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=[],r=[];if(null!==e.componentTypesAttr)for(let a of e.componentTypesAttr.stateValues.texts){let e=t.componentTypeLowerCaseMapping[a.toLowerCase()],i=t.allComponentClasses[e];if(i)n.push(e),r.push(i);else{let e="Cannot collect component type "+a+". Component type not found.";console.warn(e)}}return{setValue:{componentTypesToCollect:n,componentClassesToCollect:r}}}},e.collectedComponents={stateVariablesDeterminingDependencies:["componentTypesToCollect","targetName","propName","componentIndex","propIndex"],additionalStateVariablesDefined:["effectivePropNameByComponent"],returnDependencies:function({stateValues:e}){if(!e.targetName)return{};let t={dependencyType:"descendant",ancestorName:e.targetName,componentTypes:e.componentTypesToCollect,useReplacementsForComposites:!0,includeNonActiveChildren:!0,recurseToMatchedChildren:!1,componentIndex:e.componentIndex};if(e.propName){let n=e.propIndex;n&&(n=[...n]),t.variableNames=[e.propName],t.variablesOptional=!0,t.propIndex=n,t.caseInsensitiveVariableMatch=!0,t.publicStateVariablesOnly=!0,t.useMappedVariableNames=!0}return{descendants:t,maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"},propName:{dependencyType:"stateVariable",variableName:"propName"}}},definition:function({dependencyValues:e}){let t=e.descendants;if(t||(t=[]),null!==e.maximumNumber&&t.length>e.maximumNumber){let n=Math.max(0,Math.floor(e.maximumNumber));t=t.slice(0,n)}let n=[];for(let r of t){let t;r.stateValues&&(t=Object.keys(r.stateValues)[0]),!t&&e.propName&&(t="__prop_name_not_found"),n.push(t)}return{setValue:{collectedComponents:t,effectivePropNameByComponent:n}}}},e.readyToExpandWhenResolved={returnDependencies:()=>({collectedComponents:{dependencyType:"stateVariable",variableName:"collectedComponents"},needsReplacementsUpdatedWhenStale:{dependencyType:"stateVariable",variableName:"needsReplacementsUpdatedWhenStale"}}),definition:()=>({setValue:{readyToExpandWhenResolved:!0}})},e.needsReplacementsUpdatedWhenStale={returnDependencies:()=>({collectedComponents:{dependencyType:"stateVariable",variableName:"collectedComponents"}}),markStale:()=>({updateReplacements:!0}),definition:()=>({setValue:{needsReplacementsUpdatedWhenStale:!0}})},e}static async createSerializedReplacements({component:e,components:t,workspace:n,componentInfoObjects:r,nComponentsForSource:a,publicCaseInsensitiveAliasSubstitutions:i,flags:s}){if(!await e.stateValues.targetComponent)return{replacements:[]};let o=[],l=[],u=0,c=[];n.propVariablesCopiedByCollected=[],n.uniqueIdentifiersUsedByCollected={};let p=this.createAttributesObject(),d=await e.stateValues.collectedComponents;for(let m=0;me.componentName))}else l[m]=0,c[m]=[],n.propVariablesCopiedByCollected[m]=[];return n.numReplacementsByCollected=l,n.collectedNames=d.map((e=>e.componentName)),n.replacementNamesByCollected=c,{replacements:o}}static async createReplacementForCollected({component:e,components:t,collectedNum:n,numReplacementsSoFar:r,uniqueIdentifiersUsed:a,componentInfoObjects:i,compositeAttributesObj:s,nComponentsForSource:o,publicCaseInsensitiveAliasSubstitutions:l,flags:u}){let c=(await e.stateValues.collectedComponents)[n],p=t[c.componentName],d=[],m=[];if(!p)return{serializedReplacements:d,propVariablesCopiedByReplacement:m};let h=e.attributes.newNamespace?.primitive,f=(await e.stateValues.effectivePropNameByComponent)[n];if(f){let n=await replacementFromProp({component:e,components:t,replacementSource:c,propName:f,uniqueIdentifiersUsed:a,compositeAttributesObj:s,componentInfoObjects:i,nComponentsForSource:o,publicCaseInsensitiveAliasSubstitutions:l});d=n.serializedReplacements,m=n.propVariablesCopiedByReplacement}else{let t=await e.stateValues.sourceAttributesToIgnore,r=await e.stateValues.sourceAttributesToIgnoreRecursively;d=postProcessCopy({serializedComponents:[await p.serialize({sourceAttributesToIgnore:t,sourceAttributesToIgnoreRecursively:r})],componentName:e.componentName,uniqueIdentifiersUsed:a,identifierPrefix:n+"|"});for(let t of d){t.attributes||(t.attributes={});let n=convertAttributesForComponentType({attributes:e.attributes,componentType:t.componentType,componentInfoObjects:i,compositeAttributesObj:s,compositeCreatesNewNamespace:h,flags:u});Object.assign(t.attributes,n)}}return d=processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:d,parentName:e.componentName,indOffset:r,parentCreatesNewNamespace:h,componentInfoObjects:i}).serializedComponents,{serializedReplacements:d,propVariablesCopiedByReplacement:m}}static async calculateReplacementChanges({component:e,componentChanges:t,components:n,workspace:r,componentInfoObjects:a,nComponentsForSource:i,publicCaseInsensitiveAliasSubstitutions:s,flags:o}){let l=0;for(let t=0;t0){if(!y){let e=r.numReplacementsByCollected.slice(t).reduce(((e,t)=>e+t),0);if(e>0){let t={changeType:"delete",changeTopLevelReplacements:!0,firstReplacementInd:c,numberReplacementsToDelete:e};u.push(t)}y=!0,r.numReplacementsByCollected.slice(t).forEach(((e,t)=>r.numReplacementsByCollected[t]=0))}r.uniqueIdentifiersUsedByCollected[t]=[]}p[t]=0,d.push([]),m.push([]);continue}let f=r.collectedNames[t];if(void 0===f||l.componentName!==f||y){let l=0;void 0!==f&&(l=r.numReplacementsByCollected[t]);let h=l;y&&(h=0);let b=r.uniqueIdentifiersUsedByCollected[t]=[],v=await this.recreateReplacements({component:e,collectedNum:t,numReplacementsSoFar:c,numReplacementsToDelete:h,components:n,uniqueIdentifiersUsed:b,componentInfoObjects:a,compositeAttributesObj:g,nComponentsForSource:i,publicCaseInsensitiveAliasSubstitutions:s,flags:o});c+=v.numReplacements,p[t]=v.numReplacements,d[t]=v.propVariablesCopiedByReplacement;let N=v.replacementInstruction;if(m[t]=N.serializedReplacements.map((e=>e.componentName)),!y&&v.numReplacements!==l){let e=r.numReplacementsByCollected.slice(t).reduce(((e,t)=>e+t),0);N.numberReplacementsToReplace=e,y=!0,r.numReplacementsByCollected.slice(t).forEach(((e,t)=>r.numReplacementsByCollected[t]=0))}u.push(N);continue}if(!await e.stateValues.propName){c+=r.numReplacementsByCollected[t],p[t]=r.numReplacementsByCollected[t],m[t]=r.replacementNamesByCollected[t],d[t]=[];continue}let b=r.uniqueIdentifiersUsedByCollected[t]=[],v=await this.createReplacementForCollected({component:e,collectedNum:t,components:n,numReplacementsSoFar:c,uniqueIdentifiersUsed:b,componentInfoObjects:a,compositeAttributesObj:g,nComponentsForSource:i,publicCaseInsensitiveAliasSubstitutions:s,flags:o}),N=v.propVariablesCopiedByReplacement,T=v.serializedReplacements,C=T.length;if(C!==r.numReplacementsByCollected[t]){let e=r.numReplacementsByCollected.slice(t).reduce(((e,t)=>e+t),0),n={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:c,numberReplacementsToReplace:e,serializedReplacements:T,assignNamesOffset:c};u.push(n),y=!0,r.numReplacementsByCollected.slice(t).forEach(((e,t)=>r.numReplacementsByCollected[t]=0))}else for(let e=0;et!==N[e][n]))){let t={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:c+e,numberReplacementsToReplace:1,serializedReplacements:[T[e]],assignNamesOffset:c+e};u.push(t)}c+=C,p[t]=C,d[t]=N,m[t]=T.map((e=>e.componentName))}return r.numReplacementsByCollected=p,r.collectedNames=h.map((e=>e.componentName)),r.propVariablesCopiedByCollected=d,r.replacementNamesByCollected=m,u}static async recreateReplacements({component:e,collectedNum:t,numReplacementsSoFar:n,numReplacementsToDelete:r,uniqueIdentifiersUsed:a,components:i,componentInfoObjects:s,compositeAttributesObj:o,nComponentsForSource:l,publicCaseInsensitiveAliasSubstitutions:u,flags:c}){let p=await this.createReplacementForCollected({component:e,collectedNum:t,components:i,numReplacementsSoFar:n,uniqueIdentifiersUsed:a,componentInfoObjects:s,compositeAttributesObj:o,nComponentsForSource:l,publicCaseInsensitiveAliasSubstitutions:u,flags:c}),d=p.propVariablesCopiedByReplacement,m=p.serializedReplacements,h={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:n,numberReplacementsToReplace:r,serializedReplacements:m,assignNamesOffset:n};return{numReplacements:m.length,propVariablesCopiedByReplacement:d,replacementInstruction:h}}}class Ref extends InlineComponent{constructor(e){super(e),Object.assign(this.actions,{navigateToTarget:this.navigateToTarget.bind(this)})}static componentType="ref";static renderChildren=!0;static acceptTarget=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.textType={createComponentOfType:"text",createStateVariable:"textType",defaultValue:"type-global",public:!0},e.uri={createPrimitiveOfType:"string",createStateVariable:"uri",defaultValue:null,public:!0,forRenderer:!0},e.page={createPrimitiveOfType:"integer",createStateVariable:"page",defaultValue:null,public:!0,forRenderer:!0},e.createButton={createComponentOfType:"boolean",createStateVariable:"createButton",defaultValue:!1,forRenderer:!0},e}static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.targetComponent={returnDependencies:()=>({targetComponent:{dependencyType:"targetComponent"}}),definition:function({dependencyValues:e}){return{setValue:{targetComponent:e.targetComponent}}}},e.targetInactive={stateVariablesDeterminingDependencies:["targetComponent"],returnDependencies:({stateValues:e})=>e.targetComponent?{targetIsInactiveCompositeReplacement:{dependencyType:"stateVariable",componentName:e.targetComponent.componentName,variableName:"isInactiveCompositeReplacement"}}:{},definition:function({dependencyValues:e}){return{setValue:{targetInactive:Boolean(e.targetIsInactiveCompositeReplacement)}}}},e.targetName={forRenderer:!0,returnDependencies:()=>({targetComponent:{dependencyType:"stateVariable",variableName:"targetComponent"},uri:{dependencyType:"stateVariable",variableName:"uri"},page:{dependencyType:"stateVariable",variableName:"page"},targetInactive:{dependencyType:"stateVariable",variableName:"targetInactive"},targetAttribute:{dependencyType:"doenetAttribute",attributeName:"target"}}),definition:function({dependencyValues:e}){if(e.uri||e.page){if(e.targetAttribute){let t=e.targetAttribute;return"/"!==t[0]&&(t="/"+t),{setValue:{targetName:t}}}return{setValue:{targetName:""}}}return null===e.targetComponent||e.targetInactive?{setValue:{targetName:""}}:{setValue:{targetName:e.targetComponent.componentName}}}},e.cid={forRenderer:!0,additionalStateVariablesDefined:[{variableName:"doenetId",forRenderer:!0},{variableName:"variantIndex",forRenderer:!0},{variableName:"edit",forRenderer:!0},{variableName:"draft",forRenderer:!0},{variableName:"hash",forRenderer:!0}],returnDependencies:()=>({uri:{dependencyType:"stateVariable",variableName:"uri"}}),definition:function({dependencyValues:e}){if(!e.uri||"doenet:"!==e.uri.substring(0,7).toLowerCase())return{setValue:{cid:null,doenetId:null,variantIndex:null,edit:null,draft:null,hash:null}};let t=null,n=null,r=null,a=null,i=null,s=null,o=e.uri.match(/[:&]cid=([^&^#]+)/i);return o&&(t=o[1]),o=e.uri.match(/[:&]doenetid=([^&^#]+)/i),o&&(n=o[1]),o=e.uri.match(/[:&]variant=([^&^#]+)/i),o&&(r=Number(o[1]),!Number.isInteger(r)&&r>=1&&(r=1)),o=e.uri.match(/[:&]edit=([^&^#]+)/i),o&&(i="true"===o[1].toLowerCase()),o=e.uri.match(/[:&]draft=([^&^#]+)/i),o&&(a="true"===o[1].toLowerCase()),o=e.uri.match(/(#.+)/i),o&&(s=o[1]),{setValue:{cid:t,doenetId:n,variantIndex:r,edit:i,draft:a,hash:s}}}},e.linkText={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,stateVariablesDeterminingDependencies:["targetName"],returnDependencies({stateValues:e}){let t={allChildren:{dependencyType:"child",childGroups:["anything"],variableNames:["text"],variablesOptional:!0},uri:{dependencyType:"stateVariable",variableName:"uri"},targetInactive:{dependencyType:"stateVariable",variableName:"targetInactive"}};return e.targetName&&(t.equationTag={dependencyType:"stateVariable",componentName:e.targetName,variableName:"equationTag",variablesOptional:!0},t.title={dependencyType:"stateVariable",componentName:e.targetName,variableName:"title",variablesOptional:!0}),t},definition:function({dependencyValues:e}){let t="";if(0===e.allChildren.length)null!==e.uri?t=e.uri:e.targetInactive||(null!==e.title?t=e.title:null!==e.equationTag&&(t="("+e.equationTag+")"));else for(let n of e.allChildren)"object"!=typeof n?t+=n.toString():"string"==typeof n.stateValues.text&&(t+=n.stateValues.text);return t||(t="???"),{setValue:{linkText:t}}}},e}async navigateToTarget({actionId:e}){if(await this.stateValues.disabled)this.coreFunctions.resolveAction({actionId:e});else{let t=await this.stateValues.cid,n=await this.stateValues.doenetId,r=await this.stateValues.variantIndex,a=await this.stateValues.edit,i=await this.stateValues.hash,s=await this.stateValues.page,o=await this.stateValues.uri,l=await this.stateValues.targetName,u=this.componentOrAdaptedName;this.coreFunctions.navigateToTarget({cid:t,doenetId:n,variantIndex:r,edit:a,hash:i,page:s,uri:o,targetName:l,actionId:e,componentName:this.componentName,effectiveName:u})}}}class Coords extends MathComponent{static componentType="coords";static rendererType="math";static createAttributesObject(){let e=super.createAttributesObject();return delete e.createVectors,e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.createVectors={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({}),definition:()=>({setValue:{createVectors:!0}})},e}}class LineSegment extends GraphicalComponent{constructor(e){super(e),Object.assign(this.actions,{moveLineSegment:this.moveLineSegment.bind(this),lineSegmentClicked:this.lineSegmentClicked.bind(this),mouseDownOnLineSegment:this.mouseDownOnLineSegment.bind(this)})}static componentType="lineSegment";static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.endpointsDraggable={createComponentOfType:"boolean"},e.endpoints={createComponentOfType:"_pointListComponent"},e.showCoordsWhenDragging={createComponentOfType:"boolean",createStateVariable:"showCoordsWhenDragging",defaultValue:!0,public:!0,forRenderer:!0},e.labelPosition={createComponentOfType:"text",createStateVariable:"labelPosition",defaultValue:"upperright",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft"]},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){let t=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(t&&(t+=" "),t+=e.selectedStyle.lineStyleWord),t&&(t+=" "),t+=e.selectedStyle.lineColorWord,{setValue:{styleDescription:t}}}},e.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({styleDescription:{dependencyType:"stateVariable",variableName:"styleDescription"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescriptionWithNoun:e.styleDescription+" line segment"}}}},e.endpointsDraggable={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},hasEssential:!0,forRenderer:!0,returnDependencies:()=>({endpointsDraggableAttr:{dependencyType:"attributeComponent",attributeName:"endpointsDraggable",variableNames:["value"]},draggable:{dependencyType:"stateVariable",variableName:"draggable"}}),definition:({dependencyValues:e})=>e.endpointsDraggableAttr?{setValue:{endpointsDraggable:e.endpointsDraggableAttr.stateValues.value}}:{useEssentialOrDefaultValue:{endpointsDraggable:{defaultValue:e.draggable}}}},e.nDimensions={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({endpointsAttr:{dependencyType:"attributeComponent",attributeName:"endpoints",variableNames:["nDimensions"]}}),definition:function({dependencyValues:e}){if(null!==e.endpointsAttr){return{setValue:{nDimensions:e.endpointsAttr.stateValues.nDimensions},checkForActualChange:{nDimensions:!0}}}return{setValue:{nDimensions:2}}}},e.endpoints={public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"endpointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,nDimensions:2,entryPrefixes:["endpointX","endpoint"],hasEssential:!0,set:convertValueToMathExpression,defaultValueByArrayKey:e=>me$3.fromAst("0,0"===e?1:0),getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("endpointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("endpoints"===t)return 1===e.length?"endpoint"+e[0]:`endpointX${e[0]}_${e[1]}`;if("endpoint"===t.slice(0,8)){let n=Number(t.slice(8));if(Number.isInteger(n)&&n>0)return`endpointX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[2,e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let[e,r]=n.split(","),a=Number(e)+1+"_"+(Number(r)+1);t[n]={endpointsAttr:{dependencyType:"attributeComponent",attributeName:"endpoints",variableNames:["pointX"+a]}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t,arraySize:n}){let r={},a={};for(let n of t){let[t,i]=n.split(","),s=Number(t)+1+"_"+(Number(i)+1);null!==e[n].endpointsAttr&&e[n].endpointsAttr.stateValues["pointX"+s]?r[n]=e[n].endpointsAttr.stateValues["pointX"+s]:a[n]=!0}let i={};return Object.keys(r).length>0&&(i.setValue={endpoints:r}),Object.keys(a).length>0&&(i.useEssentialOrDefaultValue={endpoints:a}),i},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n,initialChange:r,stateValues:a}){let i=[];for(let r in e.endpoints){let[a,s]=r.split(","),o=Number(a)+1+"_"+(Number(s)+1);null!==t[r].endpointsAttr&&t[r].endpointsAttr.stateValues["pointX"+o]?i.push({setDependency:n[r].endpointsAttr,desiredValue:e.endpoints[r],childIndex:0,variableIndex:0}):i.push({setEssentialValue:"endpoints",value:{[r]:e.endpoints[r]}})}return{success:!0,instructions:i}}},e.length={public:!0,shadowingInstructions:{createComponentOfType:"math"},returnDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},endpoints:{dependencyType:"stateVariable",variableName:"endpoints"}}),definition({dependencyValues:e}){let t=0,n=e.endpoints[0],r=e.endpoints[1],a=!0;for(let i=0;ie+t*t),0));r=r.map((e=>e/o));let l=e.length.evaluate_to_constant();if(!Number.isFinite(l)||l<0)return{success:!1};let u=[],c=[],p=l/2;for(let e=0;e({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>Number.isNaN(e.nDimensions)?[0]:[2],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={endpoint:{dependencyType:"stateVariable",variableName:"endpoint"+(Number(n)+1)}};return{globalDependencies:{nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){if(Number.isNaN(e.nDimensions))return{};let r={};for(let a of n){let n=t[a].endpoint,i=[];for(let t=0;t({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},numericalEndpoints:{dependencyType:"stateVariable",variableName:"numericalEndpoints"}}),definition({dependencyValues:e}){let t=e.numericalEndpoints[0][0],n=e.numericalEndpoints[0][1],r=e.numericalEndpoints[1][0],a=e.numericalEndpoints[1][1],i=Number.isFinite(t)&&Number.isFinite(n)&&Number.isFinite(r)&&Number.isFinite(a),s=2!==e.nDimensions||!i||r===t&&a===n;return{setValue:{nearestPoint:function({variables:e,scales:i}){if(s)return{};let o=i[0],l=i[1],u=(r-t)/o,c=(a-n)/l,p=u*u+c*c,d=((e.x1-t)/o*u+(e.x2-n)/l*c)/p,m={};return m=d<=0?{x1:t,x2:n}:d>=1?{x1:r,x2:a}:{x1:t+d*u*o,x2:n+d*c*l},void 0!==e.x3&&(m.x3=0),m}}}}},e.slope={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({numericalEndpoints:{dependencyType:"stateVariable",variableName:"numericalEndpoints"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),definition({dependencyValues:e}){if(2!==e.nDimensions)return{setValue:{slope:NaN}};let t=e.numericalEndpoints;return{setValue:{slope:(t[1][1]-t[0][1])/(t[1][0]-t[0][0])}}}},e}async moveLineSegment({point1coords:e,point2coords:t,transient:n,actionId:r}){if(void 0===e||void 0===t){if(!await this.stateValues.endpointsDraggable)return await this.coreFunctions.resolveAction({actionId:r})}else if(!await this.stateValues.draggable)return await this.coreFunctions.resolveAction({actionId:r});let a={};return void 0!==e&&(a["0,0"]=me$3.fromAst(e[0]),a["0,1"]=me$3.fromAst(e[1])),void 0!==t&&(a["1,0"]=me$3.fromAst(t[0]),a["1,1"]=me$3.fromAst(t[1])),n?await this.coreFunctions.performUpdate({updateInstructions:[{componentName:this.componentName,updateType:"updateValue",stateVariable:"endpoints",value:a}],transient:!0,actionId:r}):await this.coreFunctions.performUpdate({updateInstructions:[{componentName:this.componentName,updateType:"updateValue",stateVariable:"endpoints",value:a}],actionId:r,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{point1:e,point2:t}}})}async lineSegmentClicked({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"click",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}async mouseDownOnLineSegment({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"down",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}}class Ray extends GraphicalComponent{constructor(e){super(e),Object.assign(this.actions,{moveRay:this.moveRay.bind(this),rayClicked:this.rayClicked.bind(this),mouseDownOnRay:this.mouseDownOnRay.bind(this)})}static componentType="ray";static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.endpoint={createComponentOfType:"point"},e.through={createComponentOfType:"point"},e.direction={createComponentOfType:"vector"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){let t=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(t&&(t+=" "),t+=e.selectedStyle.lineStyleWord),t&&(t+=" "),t+=e.selectedStyle.lineColorWord,{setValue:{styleDescription:t}}}},e.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({styleDescription:{dependencyType:"stateVariable",variableName:"styleDescription"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescriptionWithNoun:e.styleDescription+" ray"}}}},e.directionShadow={defaultValue:null,hasEssential:!0,essentialVarName:"direction",set:convertValueToMathExpression,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{directionShadow:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"directionShadow",value:convertValueToMathExpression(e.directionShadow)}]}}},e.throughShadow={defaultValue:null,hasEssential:!0,essentialVarName:"through",set:convertValueToMathExpression,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{throughShadow:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"throughShadow",value:convertValueToMathExpression(e.throughShadow)}]}}},e.endpointShadow={defaultValue:null,hasEssential:!0,essentialVarName:"endpoint",set:convertValueToMathExpression,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{endpointShadow:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"endpointShadow",value:convertValueToMathExpression(e.endpointShadow)}]}}},e.basedOnThrough={returnDependencies:()=>({throughAttr:{dependencyType:"attributeComponent",attributeName:"through"},throughShadow:{dependencyType:"stateVariable",variableName:"throughShadow"},endpointAttr:{dependencyType:"attributeComponent",attributeName:"endpoint"},directionAttr:{dependencyType:"attributeComponent",attributeName:"direction"}}),definition:function({dependencyValues:e}){return null!==e.endpointAttr&&null!==e.directionAttr?(null!==e.throughAttr&&console.warn("Ray is prescribed by through, endpoint, and direction. Ignoring specified through."),{setValue:{basedOnThrough:!1},checkForActualChange:{basedOnThrough:!0}}):null!==e.throughAttr?{setValue:{basedOnThrough:!0},checkForActualChange:{basedOnThrough:!0}}:{setValue:{basedOnThrough:null!==e.throughShadow},checkForActualChange:{basedOnThrough:!0}}}},e.basedOnEndpoint={returnDependencies:()=>({endpointAttr:{dependencyType:"attributeComponent",attributeName:"endpoint"},endpointShadow:{dependencyType:"stateVariable",variableName:"endpointShadow"}}),definition:function({dependencyValues:e}){return null!==e.endpointAttr?{setValue:{basedOnEndpoint:!0},checkForActualChange:{basedOnEndpoint:!0}}:{setValue:{basedOnEndpoint:null!==e.endpointShadow},checkForActualChange:{basedOnEndpoint:!0}}}},e.basedOnDirection={returnDependencies:()=>({directionAttr:{dependencyType:"attributeComponent",attributeName:"direction"},directionShadow:{dependencyType:"stateVariable",variableName:"directionShadow"}}),definition:function({dependencyValues:e}){return null!==e.directionAttr?{setValue:{basedOnDirection:!0},checkForActualChange:{basedOnDirection:!0}}:{setValue:{basedOnDirection:null!==e.directionShadow},checkForActualChange:{basedOnDirection:!0}}}},e.nDimDirection={stateVariablesDeterminingDependencies:["basedOnDirection","basedOnThrough","basedOnEndpoint"],returnDependencies({stateValues:e}){let t={basedOnThrough:{dependencyType:"stateVariable",variableName:"basedOnThrough"},basedOnEndpoint:{dependencyType:"stateVariable",variableName:"basedOnEndpoint"},basedOnDirection:{dependencyType:"stateVariable",variableName:"basedOnDirection"},directionShadow:{dependencyType:"stateVariable",variableName:"directionShadow"},directionAttr:{dependencyType:"attributeComponent",attributeName:"direction",variableNames:["nDimensions"]}};return e.basedOnDirection||(e.basedOnThrough&&(t.nDimThrough={dependencyType:"stateVariable",variableName:"nDimThrough"}),e.basedOnEndpoint&&(t.nDimEndpoint={dependencyType:"stateVariable",variableName:"nDimEndpoint"})),t},definition:function({dependencyValues:e}){let t;if(e.basedOnDirection){if(null!==e.directionAttr)t=e.directionAttr.stateValues.nDimensions;else if(e.directionShadow){let n=e.directionShadow.tree;t=Array.isArray(n)&&vectorOperators.includes(n[0])?n.length-1:2}}else t=e.basedOnThrough?e.basedOnEndpoint?e.nDimThrough===e.nDimEndpoint?e.nDimThrough:NaN:e.nDimThrough:e.basedOnEndpoint?e.nDimEndpoint:2;return{setValue:{nDimDirection:t},checkForActualChange:{nDimDirection:!0}}}},e.nDimThrough={stateVariablesDeterminingDependencies:["basedOnDirection","basedOnThrough","basedOnEndpoint"],returnDependencies({stateValues:e}){let t={basedOnThrough:{dependencyType:"stateVariable",variableName:"basedOnThrough"},basedOnEndpoint:{dependencyType:"stateVariable",variableName:"basedOnEndpoint"},basedOnDirection:{dependencyType:"stateVariable",variableName:"basedOnDirection"},throughShadow:{dependencyType:"stateVariable",variableName:"throughShadow"},throughAttr:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["nDimensions"]}};return e.basedOnThrough||(e.basedOnEndpoint&&(t.nDimEndpoint={dependencyType:"stateVariable",variableName:"nDimEndpoint"}),e.basedOnDirection&&(t.nDimDirection={dependencyType:"stateVariable",variableName:"nDimDirection"})),t},definition:function({dependencyValues:e}){let t;if(e.basedOnThrough){if(null!==e.throughAttr)t=e.throughAttr.stateValues.nDimensions;else if(e.throughShadow){let n=e.throughShadow.tree;t=Array.isArray(n)&&vectorOperators.includes(n[0])?n.length-1:2}}else t=e.basedOnDirection?e.basedOnEndpoint?e.nDimDirection===e.nDimEndpoint?e.nDimDirection:NaN:e.nDimDirection:e.basedOnEndpoint?e.nDimEndpoint:2;return{setValue:{nDimThrough:t},checkForActualChange:{nDimThrough:!0}}}},e.nDimEndpoint={stateVariablesDeterminingDependencies:["basedOnDirection","basedOnThrough","basedOnEndpoint"],returnDependencies({stateValues:e}){let t={basedOnThrough:{dependencyType:"stateVariable",variableName:"basedOnThrough"},basedOnEndpoint:{dependencyType:"stateVariable",variableName:"basedOnEndpoint"},basedOnDirection:{dependencyType:"stateVariable",variableName:"basedOnDirection"},endpointShadow:{dependencyType:"stateVariable",variableName:"endpointShadow"},endpointAttr:{dependencyType:"attributeComponent",attributeName:"endpoint",variableNames:["nDimensions"]}};return e.basedOnEndpoint||(e.basedOnThrough&&(t.nDimThrough={dependencyType:"stateVariable",variableName:"nDimThrough"}),e.basedOnDirection&&(t.nDimDirection={dependencyType:"stateVariable",variableName:"nDimDirection"})),t},definition:function({dependencyValues:e}){let t;if(e.basedOnEndpoint){if(null!==e.endpointAttr)t=e.endpointAttr.stateValues.nDimensions;else if(e.endpointShadow){let n=e.endpointShadow.tree;t=Array.isArray(n)&&vectorOperators.includes(n[0])?n.length-1:2}}else t=e.basedOnDirection?e.basedOnThrough?e.nDimDirection===e.nDimThrough?e.nDimDirection:NaN:e.nDimDirection:e.basedOnThrough?e.nDimThrough:2;return{setValue:{nDimEndpoint:t},checkForActualChange:{nDimEndpoint:!0}}}},e.nDimensions={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({basedOnThrough:{dependencyType:"stateVariable",variableName:"basedOnThrough"},basedOnEndpoint:{dependencyType:"stateVariable",variableName:"basedOnEndpoint"},basedOnDirection:{dependencyType:"stateVariable",variableName:"basedOnDirection"},nDimDirection:{dependencyType:"stateVariable",variableName:"nDimDirection"},nDimThrough:{dependencyType:"stateVariable",variableName:"nDimThrough"},nDimEndpoint:{dependencyType:"stateVariable",variableName:"nDimEndpoint"}}),definition:function({dependencyValues:e}){let t;if(e.basedOnDirection){if(e.basedOnEndpoint){if(e.nDimDirection!==e.nDimEndpoint)return console.warn("nDimensions mismatch in vector"),{setValue:{nDimensions:NaN}}}else if(e.basedOnThrough&&e.nDimDirection!==e.nDimThrough)return console.warn("nDimensions mismatch in vector"),{setValue:{nDimensions:NaN}};t=e.nDimDirection}else if(e.basedOnEndpoint){if(e.basedOnThrough&&e.nDimEndpoint!==e.nDimThrough)return console.warn("nDimensions mismatch in vector"),{setValue:{nDimensions:NaN}};t=e.nDimEndpoint}else t=e.basedOnThrough?e.nDimThrough:2;return{setValue:{nDimensions:t},checkForActualChange:{nDimensions:!0}}}},e.direction={public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"directionX"===e?[]:[["vector",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,entryPrefixes:["directionX"],hasEssential:!0,essentialVarName:"direction2",set:convertValueToMathExpression,stateVariablesDeterminingDependencies:["basedOnDirection","basedOnThrough"],returnArraySizeDependencies:()=>({nDimDirection:{dependencyType:"stateVariable",variableName:"nDimDirection"}}),returnArraySize:({dependencyValues:e})=>[e.nDimDirection],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=Number(r)+1;n[r]={directionAttr:{dependencyType:"attributeComponent",attributeName:"direction",variableNames:["x"+e]}},!t.basedOnDirection&&t.basedOnThrough&&(n[r].endpointX={dependencyType:"stateVariable",variableName:"endpointX"+e},n[r].throughX={dependencyType:"stateVariable",variableName:"throughX"+e})}return{globalDependencies:{basedOnThrough:{dependencyType:"stateVariable",variableName:"basedOnThrough"},basedOnEndpoint:{dependencyType:"stateVariable",variableName:"basedOnEndpoint"},basedOnDirection:{dependencyType:"stateVariable",variableName:"basedOnDirection"},directionShadow:{dependencyType:"stateVariable",variableName:"directionShadow"}},dependenciesByKey:n}},arrayDefinitionByKey:function({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={},a={};for(let i of n){let n=Number(i)+1;e.basedOnDirection?null!==t[i].directionAttr?r[i]=t[i].directionAttr.stateValues["x"+n]:null!==e.directionShadow&&(r[i]=e.directionShadow.get_component(Number(i))):e.basedOnThrough?r[i]=t[i].throughX.subtract(t[i].endpointX).simplify():a[i]={defaultValue:me$3.fromAst("0"===i?1:0)}}let i={};return Object.keys(r).length>0&&(i.setValue={direction:r}),Object.keys(a).length>0&&(i.useEssentialOrDefaultValue={direction:a}),i},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i=[],s=!1;for(let a in e.direction)t.basedOnDirection?null!==n[a].directionAttr?i.push({setDependency:r[a].directionAttr,desiredValue:e.direction[a],variableIndex:0}):s=!0:t.basedOnThrough?i.push({setDependency:r[a].throughX,desiredValue:n[a].endpointX.add(e.direction[a]).simplify()}):i.push({setEssentialValue:"direction",value:{[a]:convertValueToMathExpression(e.direction[a])}});if(s)if(a[0]>1){let t=["vector"];for(let n in e.direction)t[Number(n)+1]=e.direction[n].tree;t.length=a[0]+1,i.push({setDependency:"directionShadow",desiredValue:me$3.fromAst(t)})}else 1===a[0]&&"0"in e.direction&&i.push({setDependency:"directionShadow",desiredValue:e.direction[0]});return{success:!0,instructions:i}}},e.through={public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"throughX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,entryPrefixes:["throughX"],set:convertValueToMathExpression,stateVariablesDeterminingDependencies:["basedOnThrough"],returnArraySizeDependencies:()=>({nDimThrough:{dependencyType:"stateVariable",variableName:"nDimThrough"}}),returnArraySize:({dependencyValues:e})=>[e.nDimThrough],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=Number(r)+1;n[r]={throughAttr:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["x"+e]}},t.basedOnThrough||(n[r].endpointX={dependencyType:"stateVariable",variableName:"endpointX"+e},n[r].directionX={dependencyType:"stateVariable",variableName:"directionX"+e})}return{globalDependencies:{basedOnDirection:{dependencyType:"stateVariable",variableName:"basedOnDirection"},basedOnEndpoint:{dependencyType:"stateVariable",variableName:"basedOnEndpoint"},basedOnThrough:{dependencyType:"stateVariable",variableName:"basedOnThrough"},throughShadow:{dependencyType:"stateVariable",variableName:"throughShadow"}},dependenciesByKey:n}},arrayDefinitionByKey:function({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};for(let a of n){let n=Number(a)+1;e.basedOnThrough?null!==t[a].throughAttr?r[a]=t[a].throughAttr.stateValues["x"+n]:null!==e.throughShadow&&(r[a]=e.throughShadow.get_component(Number(a))):r[a]=t[a].endpointX.add(t[a].directionX).simplify()}return{setValue:{through:r}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i=[],s=!1;for(let a in e.through)t.basedOnThrough?n[a].throughAttr&&null!==n[a].throughAttr?i.push({setDependency:r[a].throughAttr,desiredValue:e.through[a],variableIndex:0}):null!==t.throughShadow&&(s=!0):i.push({setDependency:r[a].directionX,desiredValue:e.through[a].subtract(n[a].endpointX).simplify()});if(s)if(a[0]>1){let t=["vector"];for(let n in e.through)t[Number(n)+1]=e.through[n].tree;t.length=a[0]+1,i.push({setDependency:"throughShadow",desiredValue:me$3.fromAst(t)})}else 1===a[0]&&"0"in e.through&&i.push({setDependency:"throughShadow",desiredValue:e.through[0]});return{success:!0,instructions:i}}},e.endpoint={public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"endpointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,entryPrefixes:["endpointX"],hasEssential:!0,defaultValueByArrayKey:()=>me$3.fromAst(0),essentialVarName:"endpoint2",set:convertValueToMathExpression,stateVariablesDeterminingDependencies:["basedOnEndpoint","basedOnThrough","basedOnDirection"],returnArraySizeDependencies:()=>({nDimEndpoint:{dependencyType:"stateVariable",variableName:"nDimEndpoint"}}),returnArraySize:({dependencyValues:e})=>[e.nDimEndpoint],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=Number(r)+1;n[r]={endpointAttr:{dependencyType:"attributeComponent",attributeName:"endpoint",variableNames:["x"+e]}},t.basedOnEndpoint||t.basedOnThrough&&t.basedOnDirection&&(n[r].throughX={dependencyType:"stateVariable",variableName:"throughX"+e},n[r].directionX={dependencyType:"stateVariable",variableName:"directionX"+e})}return{globalDependencies:{basedOnDirection:{dependencyType:"stateVariable",variableName:"basedOnDirection"},basedOnThrough:{dependencyType:"stateVariable",variableName:"basedOnThrough"},endpointShadow:{dependencyType:"stateVariable",variableName:"endpointShadow"}},dependenciesByKey:n}},arrayDefinitionByKey:function({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={},a={};for(let i of n){let n=Number(i)+1;null!==t[i].endpointAttr?r[i]=t[i].endpointAttr.stateValues["x"+n]:null!==e.endpointShadow?r[i]=e.endpointShadow.get_component(Number(i)):e.basedOnThrough&&e.basedOnDirection?r[i]=t[i].throughX.subtract(t[i].directionX).simplify():a[i]=!0}let i={};return Object.keys(r).length>0&&(i.setValue={endpoint:r}),Object.keys(a).length>0&&(i.useEssentialOrDefaultValue={endpoint:a}),i},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i=[],s=!1;for(let a in e.endpoint)n[a].endpointAttr&&null!==n[a].endpointAttr?i.push({setDependency:r[a].endpointAttr,desiredValue:e.endpoint[a],variableIndex:0}):null!==t.endpointShadow?s=!0:t.basedOnThrough&&t.basedOnDirection?i.push({setDependency:r[a].directionX,desiredValue:n[a].throughX.subtract(e.endpoint[a]).simplify()}):i.push({setEssentialValue:"endpoint",value:{[a]:convertValueToMathExpression(e.endpoint[a])}});if(s)if(a[0]>1){let t=["vector"];for(let n in e.endpoint)t[Number(n)+1]=e.endpoint[n].tree;t.length=a[0]+1,i.push({setDependency:"endpointShadow",desiredValue:me$3.fromAst(t)})}else 1===a[0]&&"0"in e.endpoint&&i.push({setDependency:"endpointShadow",desiredValue:e.endpoint[0]});return{success:!0,instructions:i}}},e.numericalEndpoint={forRenderer:!0,returnDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},endpoint:{dependencyType:"stateVariable",variableName:"endpoint"}}),definition({dependencyValues:e}){if(Number.isNaN(e.nDimensions))return null;let t=e.endpoint,n=[];for(let r=0;r({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},through:{dependencyType:"stateVariable",variableName:"through"}}),definition({dependencyValues:e}){if(Number.isNaN(e.nDimensions))return null;let t=e.through,n=[];for(let r=0;r({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},numericalEndpoint:{dependencyType:"stateVariable",variableName:"numericalEndpoint"},numericalThroughpoint:{dependencyType:"stateVariable",variableName:"numericalThroughpoint"}}),definition({dependencyValues:e}){let t=e.numericalEndpoint[0],n=e.numericalEndpoint[1],r=e.numericalThroughpoint[0],a=e.numericalThroughpoint[1],i=Number.isFinite(t)&&Number.isFinite(n)&&Number.isFinite(r)&&Number.isFinite(a),s=2!==e.nDimensions||!i||r===t&&a===n;return{setValue:{nearestPoint:function({variables:e,scales:i}){if(s)return{};let o=i[0],l=i[1],u=(r-t)/o,c=(a-n)/l,p=u*u+c*c,d=((e.x1-t)/o*u+(e.x2-n)/l*c)/p,m={};return m=d<=0?{x1:t,x2:n}:{x1:t+d*u*o,x2:n+d*c*l},void 0!==e.x3&&(m.x3=0),m}}}}},e}async moveRay({endpointcoords:e,throughcoords:t,transient:n,skippable:r,sourceInformation:a,actionId:i}){let s=[];if(void 0!==e){if(await this.stateValues.basedOnThrough&&await this.stateValues.basedOnDirection){let n;if(void 0===t){let t=await this.stateValues.numericalThroughpoint;n=e.map(((e,n)=>t[n]-e))}else n=e.map(((e,n)=>t[n]-e));s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"direction",value:n.map((e=>me$3.fromAst(e))),sourceInformation:a})}else s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"endpoint",value:e.map((e=>me$3.fromAst(e))),sourceInformation:a});if(void 0===t&&!await this.stateValues.basedOnThrough){let t=await this.stateValues.numericalThroughpoint,n=e.map(((e,n)=>t[n]-e));s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"direction",value:n.map((e=>me$3.fromAst(e))),sourceInformation:a})}}if(void 0!==t){if(await this.stateValues.basedOnThrough)s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"through",value:t.map((e=>me$3.fromAst(e))),sourceInformation:a});else{null==e&&(e=await this.stateValues.numericalEndpoint);let n=e.map(((e,n)=>t[n]-e));s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"direction",value:n.map((e=>me$3.fromAst(e))),sourceInformation:a})}if(void 0===e&&await this.stateValues.basedOnThrough&&await this.stateValues.basedOnDirection){let e=await this.stateValues.numericalEndpoint,n=t.map(((t,n)=>t-e[n]));s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"direction",value:n.map((e=>me$3.fromAst(e))),sourceInformation:a})}}return n?await this.coreFunctions.performUpdate({updateInstructions:s,transient:n,skippable:r,actionId:i}):await this.coreFunctions.performUpdate({updateInstructions:s,actionId:i,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{through:t,endpoint:e}}})}async rayClicked({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"click",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}async mouseDownOnRay({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"down",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}}class Polygon extends Polyline{constructor(e){super(e),Object.assign(this.actions,{movePolygon:this.movePolygon.bind(this),polygonClicked:this.polygonClicked.bind(this),mouseDownOnPolygon:this.mouseDownOnPolygon.bind(this)})}static componentType="polygon";static representsClosedPath=!0;get movePolygon(){return this.movePolyline}get polygonClicked(){return this.polylineClicked}get mouseDownOnPolygon(){return this.mouseDownOnPolyline}static createAttributesObject(){let e=super.createAttributesObject();return e.filled={createComponentOfType:"boolean",createStateVariable:"filled",defaultValue:!1,public:!0,forRenderer:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"},filled:{dependencyType:"stateVariable",variableName:"filled"}}),definition:function({dependencyValues:e}){let t,n=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(n&&(n+=" "),n+=e.selectedStyle.lineStyleWord),n&&(n+=" "),e.filled?e.selectedStyle.fillColorWord===e.selectedStyle.lineColorWord?(t="filled "+e.selectedStyle.fillColorWord,n&&(t+=" with "+n+"border")):t="filled "+e.selectedStyle.fillColorWord+" with "+n+e.selectedStyle.lineColorWord+" border":t=n+e.selectedStyle.lineColorWord,{setValue:{styleDescription:t}}}},e.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"},filled:{dependencyType:"stateVariable",variableName:"filled"}}),definition:function({dependencyValues:e}){let t,n=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(n&&(n+=" "),n+=e.selectedStyle.lineStyleWord),n&&(n+=" "),e.filled?e.selectedStyle.fillColorWord===e.selectedStyle.lineColorWord?(t="filled "+e.selectedStyle.fillColorWord+" polygon",n&&(t+=" with a "+n+"border")):t="filled "+e.selectedStyle.fillColorWord+" polygon with a "+n+e.selectedStyle.lineColorWord+" border":t=n+e.selectedStyle.lineColorWord+" polygon",{setValue:{styleDescriptionWithNoun:t}}}},e.borderStyleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){let t=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(t&&(t+=" "),t+=e.selectedStyle.lineStyleWord),t&&(t+=" "),t+=e.selectedStyle.lineColorWord,{setValue:{borderStyleDescription:t}}}},e.fillStyleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"},filled:{dependencyType:"stateVariable",variableName:"filled"}}),definition:function({dependencyValues:e}){let t;return t=e.filled?e.selectedStyle.fillColorWord:"unfilled",{setValue:{fillStyleDescription:t}}}},e.nearestPoint={returnDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},numericalVertices:{dependencyType:"stateVariable",variableName:"numericalVertices"},nVertices:{dependencyType:"stateVariable",variableName:"nVertices"}}),definition({dependencyValues:e}){let t,n,r=e.nDimensions,a=e.nVertices,i=e.numericalVertices,s=[],o=i[a-1]?.[0],l=i[a-1]?.[1];for(let e=0;e=1?{x1:h,x2:f}:{x1:l+g*a*n,x2:u+g*y*o};let b=Math.pow((d-r.x1)/n,2)+Math.pow((m-r.x2)/o,2);b0&&(p.x3=0),p}}}}},e}}class Triangle extends Polygon{static componentType="triangle";static rendererType="polygon";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=e.styleDescriptionWithNoun.definition;return e.styleDescriptionWithNoun.definition=function({dependencyValues:e}){let n=t({dependencyValues:e}).setValue.styleDescriptionWithNoun;return n=n.replaceAll("polygon","triangle"),{setValue:{styleDescriptionWithNoun:n}}},e.vertices.hasEssential=!0,e.vertices.defaultValueByArrayKey=function(e){return["0,1","1,0"].includes(e)?me$3.fromAst(1):me$3.fromAst(0)},e.vertices.returnArraySizeDependencies=()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),e.vertices.returnArraySize=function({dependencyValues:e}){return[3,e.nDimensions]},e.vertices.arrayDefinitionByKey=function({dependencyValuesByKey:e,arrayKeys:t}){let n={},r={};for(let a of t){let[t,i]=a.split(","),s=Number(t)+1+"_"+(Number(i)+1),o=e[a].vertices;null!==o&&o.stateValues["pointX"+s]?n[a]=o.stateValues["pointX"+s]:r[a]=!0}return{setValue:{vertices:n},useEssentialOrDefaultValue:{vertices:r}}},e.vertices.inverseArrayDefinitionByKey=async function({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n,initialChange:r,stateValues:a}){if(r&&!await a.draggable)return{success:!1};let i=[];for(let r in e.vertices){let[a,s]=r.split(","),o=Number(a)+1+"_"+(Number(s)+1);null!==t[r].vertices&&t[r].vertices.stateValues["pointX"+o]?i.push({setDependency:n[r].vertices,desiredValue:e.vertices[r],variableIndex:0}):i.push({setEssentialValue:"vertices",value:{[r]:e.vertices[r].simplify()}})}return{success:!0,instructions:i}},e.nVertices={public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{nVertices:3}})},e}}class Rectangle extends Polygon{static componentType="rectangle";static rendererType="polygon";static createAttributesObject(){let e=super.createAttributesObject();return e.center={createComponentOfType:"point"},e.width={createComponentOfType:"number"},e.height={createComponentOfType:"number"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=e.styleDescriptionWithNoun.definition;return e.styleDescriptionWithNoun.definition=function({dependencyValues:e}){let n=t({dependencyValues:e}).setValue.styleDescriptionWithNoun;return n=n.replaceAll("polygon","rectangle"),{setValue:{styleDescriptionWithNoun:n}}},e.nVerticesSpecified={returnDependencies:()=>({verticesAttr:{dependencyType:"attributeComponent",attributeName:"vertices",variableNames:["nPoints"]}}),definition:function({dependencyValues:e}){return null!==e.verticesAttr?{setValue:{nVerticesSpecified:e.verticesAttr.stateValues.nPoints}}:{setValue:{nVerticesSpecified:0}}}},e.essentialVertex={isArray:!0,entryPrefixes:["essentialVertexX"],defaultValueByArrayKey:()=>me$3.fromAst(0),hasEssential:!0,returnArraySizeDependencies:()=>({nVerticesSpecified:{dependencyType:"stateVariable",variableName:"nVerticesSpecified"}}),returnArraySize:({dependencyValues:e})=>[0===e.nVerticesSpecified?2:0],returnArrayDependenciesByKey:()=>({}),arrayDefinitionByKey:function({arrayKeys:e}){let t={};for(let n of e)t[n]=!0;return{useEssentialOrDefaultValue:{essentialVertex:t}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e}){let t=[];for(let n in e.essentialVertex)t.push({setEssentialValue:"essentialVertex",value:{[n]:e.essentialVertex[n]}});return{success:!0,instructions:t}}},e.haveSpecifiedCenter={returnDependencies:()=>({centerAttr:{dependencyType:"attributeComponent",attributeName:"center"}}),definition:({dependencyValues:e})=>({setValue:{haveSpecifiedCenter:null!==e.centerAttr}})},e.specifiedCenter={isArray:!0,entryPrefixes:["specifiedCenterX"],returnArraySizeDependencies:()=>({haveSpecifiedCenter:{dependencyType:"stateVariable",variableName:"haveSpecifiedCenter"}}),returnArraySize:({dependencyValues:e})=>[e.haveSpecifiedCenter?2:0],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={centerAttr:{dependencyType:"attributeComponent",attributeName:"center",variableNames:["x"+e]}}}return{dependenciesByKey:t}},arrayDefinitionByKey:function({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=Number(r)+1;null!==e[r].centerAttr&&(n[r]=e[r].centerAttr.stateValues["x"+t])}return{setValue:{specifiedCenter:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n}){let r=[];for(let a in e.specifiedCenter)t[a].centerAttr&&null!==t[a].centerAttr&&r.push({setDependency:n[a].centerAttr,desiredValue:e.specifiedCenter[a],variableIndex:0});return{success:!0,instructions:r}}},e.specifiedWidth={defaultValue:1,hasEssential:!0,essentialVarName:"width",returnDependencies:()=>({widthAttr:{dependencyType:"attributeComponent",attributeName:"width",variableNames:["value"]},nVerticesSpecified:{dependencyType:"stateVariable",variableName:"nVerticesSpecified"},haveSpecifiedCenter:{dependencyType:"stateVariable",variableName:"haveSpecifiedCenter"}}),definition:({dependencyValues:e})=>null!==e.widthAttr?{setValue:{specifiedWidth:e.widthAttr.stateValues.value}}:(e.haveSpecifiedCenter?1:0)+e.nVerticesSpecified<=1?{useEssentialOrDefaultValue:{specifiedWidth:!0}}:{setValue:{specifiedWidth:null}},inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t})=>null!==t.widthAttr?{success:!0,instructions:[{setDependency:"widthAttr",desiredValue:e.specifiedWidth,childIndex:0,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"specifiedWidth",value:e.specifiedWidth}]}},e.specifiedHeight={defaultValue:1,hasEssential:!0,essentialVarName:"height",returnDependencies:()=>({heightAttr:{dependencyType:"attributeComponent",attributeName:"height",variableNames:["value"]},nVerticesSpecified:{dependencyType:"stateVariable",variableName:"nVerticesSpecified"},haveSpecifiedCenter:{dependencyType:"stateVariable",variableName:"haveSpecifiedCenter"}}),definition:({dependencyValues:e})=>null!==e.heightAttr?{setValue:{specifiedHeight:e.heightAttr.stateValues.value}}:(e.haveSpecifiedCenter?1:0)+e.nVerticesSpecified<=1?{useEssentialOrDefaultValue:{specifiedHeight:!0}}:{setValue:{specifiedHeight:null}},inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t})=>null!==t.heightAttr?{success:!0,instructions:[{setDependency:"heightAttr",desiredValue:e.specifiedHeight,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"specifiedHeight",value:e.specifiedHeight}]}},e.center={public:!0,isArray:!0,entryPrefixes:["centerX"],shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"centerX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},returnArraySizeDependencies:()=>({}),returnArraySize:()=>[2],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={vertex0:{dependencyType:"stateVariable",variableName:"vertexX1_"+e},vertex2:{dependencyType:"stateVariable",variableName:"vertexX3_"+e}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].vertex0,a=e[r].vertex2;n[r]=t.add(a).divide(2).simplify()}return{setValue:{center:n}}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n,stateValues:r}){let a=[],i=await r.center;for(let r in e.center){let s=Number(r),o=t[r].vertex0,l=t[r].vertex2,u=e.center[s].subtract(i[s]),c=o.add(u).simplify(),p=l.add(u).simplify();a.push({setDependency:n[r].vertex0,desiredValue:c},{setDependency:n[r].vertex2,desiredValue:p})}return{success:!0,instructions:a}}},e.width={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:({})=>({vertex0:{dependencyType:"stateVariable",variableName:"vertexX1_1"},vertex2:{dependencyType:"stateVariable",variableName:"vertexX3_1"}}),definition({dependencyValues:e}){let t=e.vertex0.evaluate_to_constant(),n=e.vertex2.evaluate_to_constant();return{setValue:{width:Math.abs(t-n)}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){let n=t.vertex0.evaluate_to_constant(),r=t.vertex2.evaluate_to_constant(),a=(r+n)/2,i=(r-n<0?-1:1)*Math.max(0,e.width)/2;return{success:!0,instructions:[{setDependency:"vertex0",desiredValue:me$3.fromAst(a-i)},{setDependency:"vertex2",desiredValue:me$3.fromAst(a+i)}]}}},e.height={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:({})=>({vertex0:{dependencyType:"stateVariable",variableName:"vertexX1_2"},vertex2:{dependencyType:"stateVariable",variableName:"vertexX3_2"}}),definition({dependencyValues:e}){let t=e.vertex0.evaluate_to_constant(),n=e.vertex2.evaluate_to_constant();return{setValue:{height:Math.abs(t-n)}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){let n=t.vertex0.evaluate_to_constant(),r=t.vertex2.evaluate_to_constant(),a=(r+n)/2,i=(r-n<0?-1:1)*Math.max(0,e.height)/2;return{success:!0,instructions:[{setDependency:"vertex0",desiredValue:me$3.fromAst(a-i)},{setDependency:"vertex2",desiredValue:me$3.fromAst(a+i)}]}}},e.vertices={public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"vertexX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,nDimensions:2,entryPrefixes:["vertexX","vertex"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("vertexX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("vertices"===t)return 1===e.length?"vertex"+e[0]:`vertexX${e[0]}_${e[1]}`;if("vertex"===t.slice(0,6)){let n=Number(t.slice(6));if(Number.isInteger(n)&&n>0)return`vertexX${n}_${e[0]}`}return null},stateVariablesDeterminingDependencies:["nVerticesSpecified","haveSpecifiedCenter"],returnArraySizeDependencies:()=>({}),returnArraySize:()=>[4,2],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={},r={nVerticesSpecified:{dependencyType:"stateVariable",variableName:"nVerticesSpecified"}};if(0===t.nVerticesSpecified)if(r.haveSpecifiedCenter={dependencyType:"stateVariable",variableName:"haveSpecifiedCenter"},t.haveSpecifiedCenter)for(let t of e){let[e,r]=t.split(",");n[t]={specifiedCenter:{dependencyType:"stateVariable",variableName:"specifiedCenterX"+(Number(r)+1)}},"0"===r?n[t].specifiedWidth={dependencyType:"stateVariable",variableName:"specifiedWidth"}:n[t].specifiedHeight={dependencyType:"stateVariable",variableName:"specifiedHeight"}}else for(let t of e){let[e,r]=t.split(",");n[t]={essentialVertex:{dependencyType:"stateVariable",variableName:"essentialVertexX"+(Number(r)+1)}},"0"===r?"1"!==e&&"2"!==e||(n[t].specifiedWidth={dependencyType:"stateVariable",variableName:"specifiedWidth"}):"2"!==e&&"3"!==e||(n[t].specifiedHeight={dependencyType:"stateVariable",variableName:"specifiedHeight"})}else if(1===t.nVerticesSpecified)if(r.haveSpecifiedCenter={dependencyType:"stateVariable",variableName:"haveSpecifiedCenter"},t.haveSpecifiedCenter)for(let t of e){let[e,r]=t.split(","),a="1_"+(Number(r)+1);n[t]={verticesAttr:{dependencyType:"attributeComponent",attributeName:"vertices",variableNames:["pointX"+a]}},("0"===r&&"1"===e||"2"===e||"1"===r&&"2"===e||"3"===e)&&(n[t].specifiedCenter={dependencyType:"stateVariable",variableName:"specifiedCenterX"+(Number(r)+1)})}else for(let t of e){let[e,r]=t.split(","),a="1_"+(Number(r)+1);n[t]={verticesAttr:{dependencyType:"attributeComponent",attributeName:"vertices",variableNames:["pointX"+a]}},"0"===r?"1"!==e&&"2"!==e||(n[t].specifiedWidth={dependencyType:"stateVariable",variableName:"specifiedWidth"}):"2"!==e&&"3"!==e||(n[t].specifiedHeight={dependencyType:"stateVariable",variableName:"specifiedHeight"})}else for(let t of e){let e,[r,a]=t.split(","),i="1_"+(Number(a)+1),s="2_"+(Number(a)+1);e="0"===r?i:"2"===r?s:"1"===r?"0"===a?s:i:"0"===a?i:s,n[t]={verticesAttr:{dependencyType:"attributeComponent",attributeName:"vertices",variableNames:["pointX"+e]}}}return{dependenciesByKey:n,globalDependencies:r}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t,globalDependencyValues:n}){let r={};if(0===n.nVerticesSpecified)if(n.haveSpecifiedCenter)for(let n of t){let[t,a]=n.split(","),i=e[n].specifiedCenter;if("0"===a){let a=e[n].specifiedWidth;r[n]="0"===t||"3"===t?i.subtract(a/2):i.add(a/2)}else{let a=e[n].specifiedHeight;r[n]="0"===t||"1"===t?i.subtract(a/2):i.add(a/2)}}else for(let n of t){let[t,a]=n.split(","),i=e[n].essentialVertex;if("0"===a)if("0"===t||"3"===t)r[n]=i;else{let t=e[n].specifiedWidth;r[n]=i.add(t)}else if("0"===t||"1"===t)r[n]=i;else{let t=e[n].specifiedHeight;r[n]=i.add(t)}}else if(1===n.nVerticesSpecified)if(n.haveSpecifiedCenter)for(let n of t){let t,[a,i]=n.split(","),s=e[n].verticesAttr;if(t=null!==s&&1===Object.keys(s.stateValues).length?Object.values(s.stateValues)[0]:me$3.fromAst("_"),"0"===i&&("0"===a||"3"===a)||"1"===i&&("0"===a||"1"===a))r[n]=t;else{let a=e[n].specifiedCenter;r[n]=t.add(a.subtract(t).multiply(2))}}else for(let n of t){let t,[a,i]=n.split(","),s=e[n].verticesAttr;if(t=null!==s&&1===Object.keys(s.stateValues).length?Object.values(s.stateValues)[0]:me$3.fromAst("_"),"0"===i)if("0"===a||"3"===a)r[n]=t;else{let a=e[n].specifiedWidth;r[n]=t.add(a)}else if("0"===a||"1"===a)r[n]=t;else{let a=e[n].specifiedHeight;r[n]=t.add(a)}}else for(let n of t){let t=e[n].verticesAttr;null!==t&&1===Object.keys(t.stateValues).length?r[n]=Object.values(t.stateValues)[0]:r[n]=me$3.fromAst("_")}return{setValue:{vertices:r}}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,globalDependencyValues:n,stateValues:r,workspace:a,initialChange:i,dependencyNamesByKey:s}){if(i&&!await r.draggable)return{success:!1};if(!a.v0){let e=await r.vertices;a.v0=[...e[0]],a.v2=[...e[2]]}let o,l,u,c,p,d;for(let t in e.vertices){let[n,r]=t.split(","),i=e.vertices[t];"0"===n?a.v0[Number(r)]=i:"2"===n?a.v2[Number(r)]=i:"1"===n?"0"===r?a.v2[Number(r)]=i:a.v0[Number(r)]=i:"0"===r?a.v0[Number(r)]=i:a.v2[Number(r)]=i,"0"===r?(o=t,"0"===n||"3"===n?u=t:p=t):(l=t,"0"===n||"1"===n?c=t:d=t)}let m=[];if(0===n.nVerticesSpecified)if(n.haveSpecifiedCenter){if(void 0!==o){let e=a.v2[0].subtract(a.v0[0]).evaluate_to_constant(),t=a.v2[0].add(a.v0[0]).divide(2).simplify();m.push({setDependency:s[o].specifiedWidth,desiredValue:e},{setDependency:s[o].specifiedCenter,desiredValue:t})}if(void 0!==l){let e=a.v2[1].subtract(a.v0[1]).evaluate_to_constant(),t=a.v2[1].add(a.v0[1]).divide(2).simplify();m.push({setDependency:s[l].specifiedHeight,desiredValue:e},{setDependency:s[l].specifiedCenter,desiredValue:t})}}else{if(void 0!==u){let e=a.v0[0].simplify();m.push({setDependency:s[u].essentialVertex,desiredValue:e})}if(void 0!==p){let e=a.v2[0].subtract(a.v0[0]).evaluate_to_constant();m.push({setDependency:s[p].specifiedWidth,desiredValue:e})}if(void 0!==c){let e=a.v0[1].simplify();m.push({setDependency:s[c].essentialVertex,desiredValue:e})}if(void 0!==d){let e=a.v2[1].subtract(a.v0[1]).evaluate_to_constant();m.push({setDependency:s[d].specifiedHeight,desiredValue:e})}}else if(1===n.nVerticesSpecified)if(n.haveSpecifiedCenter){if(void 0!==u){let e=a.v0[0].simplify();m.push({setDependency:s[u].verticesAttr,desiredValue:e,variableIndex:0})}if(void 0!==p){let e=a.v2[0].add(a.v0[0]).divide(2).simplify();m.push({setDependency:s[p].specifiedCenter,desiredValue:e})}if(void 0!==c){let e=a.v0[1].simplify();m.push({setDependency:s[c].verticesAttr,desiredValue:e,variableIndex:0})}if(void 0!==d){let e=a.v2[1].add(a.v0[1]).divide(2).simplify();m.push({setDependency:s[d].specifiedCenter,desiredValue:e})}}else{if(void 0!==u){let e=a.v0[0].simplify();m.push({setDependency:s[u].verticesAttr,desiredValue:e,variableIndex:0})}if(void 0!==p){let e=a.v2[0].subtract(a.v0[0]).evaluate_to_constant();m.push({setDependency:s[p].specifiedWidth,desiredValue:e})}if(void 0!==c){let e=a.v0[1].simplify();m.push({setDependency:s[c].verticesAttr,desiredValue:e,variableIndex:0})}if(void 0!==d){let e=a.v2[1].subtract(a.v0[1]).evaluate_to_constant();m.push({setDependency:s[d].specifiedHeight,desiredValue:e})}}else void 0!==u&&m.push({setDependency:s[u].verticesAttr,desiredValue:a.v0[0],variableIndex:0}),void 0!==p&&m.push({setDependency:s[p].verticesAttr,desiredValue:a.v2[0],variableIndex:0}),void 0!==c&&m.push({setDependency:s[c].verticesAttr,desiredValue:a.v0[1],variableIndex:0}),void 0!==d&&m.push({setDependency:s[d].verticesAttr,desiredValue:a.v2[1],variableIndex:0});return{success:!0,instructions:m}}},e.nVertices={public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{nVertices:4}})},e}async movePolygon({pointCoords:e,transient:t,sourceInformation:n,actionId:r}){let a=[],i={};for(let t in e)i[t+",0"]=me$3.fromAst(e[t][0]),i[t+",1"]=me$3.fromAst(e[t][1]);if(a.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"vertices",value:i,sourceInformation:n}),1===Object.keys(e).length){let t=Number(Object.keys(e)[0]),n=me$3.fromAst(e[t][0]),r=me$3.fromAst(e[t][1]),i=(t+2)%4,s=await this.stateValues.vertices,o=s[i][0],l=s[i][1];if(await this.stateValues.nVerticesSpecified<2)if(await this.stateValues.haveSpecifiedCenter){let e,i;0===t?(e=n.add(o).divide(2),i=r.add(l).divide(2)):1===t?i=r.add(l).divide(2):3===t&&(e=n.add(o).divide(2)),void 0!==e&&a.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"specifiedCenter",value:{0:e.simplify()}}),void 0!==i&&a.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"specifiedCenter",value:{1:i.simplify()}})}else{let e,i;0===t?(e=o.subtract(n),i=l.subtract(r)):1===t?i=l.subtract(r):3===t&&(e=o.subtract(n)),void 0!==e&&a.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"specifiedWidth",value:e.simplify()}),void 0!==i&&a.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"specifiedHeight",value:i.simplify()})}}return t?await this.coreFunctions.performUpdate({updateInstructions:a,transient:t,actionId:r}):await this.coreFunctions.performUpdate({updateInstructions:a,actionId:r,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{pointCoordinates:e}}})}}class Circle extends Curve{constructor(e){super(e),Object.assign(this.actions,{moveCircle:this.moveCircle.bind(this),circleClicked:this.circleClicked.bind(this),mouseDownOnCircle:this.mouseDownOnCircle.bind(this)})}static componentType="circle";static rendererType="circle";static representsClosedPath=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.through={createComponentOfType:"_pointListComponent"},e.center={createComponentOfType:"point"},e.radius={createComponentOfType:"math"},e.filled={createComponentOfType:"boolean",createStateVariable:"filled",defaultValue:!1,public:!0,forRenderer:!0},delete e.parMin,delete e.parMax,delete e.variable,e}static returnChildGroups(){return GraphicalComponent.returnChildGroups()}static returnStateVariableDefinitions(e){let t=GraphicalComponent.returnStateVariableDefinitions(e);return t.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"},filled:{dependencyType:"stateVariable",variableName:"filled"}}),definition:function({dependencyValues:e}){let t,n=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(n&&(n+=" "),n+=e.selectedStyle.lineStyleWord),n&&(n+=" "),e.filled?e.selectedStyle.fillColorWord===e.selectedStyle.lineColorWord?(t="filled "+e.selectedStyle.fillColorWord,n&&(t+=" with "+n+"border")):t="filled "+e.selectedStyle.fillColorWord+" with "+n+e.selectedStyle.lineColorWord+" border":t=n+e.selectedStyle.lineColorWord,{setValue:{styleDescription:t}}}},t.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"},filled:{dependencyType:"stateVariable",variableName:"filled"}}),definition:function({dependencyValues:e}){let t,n=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(n&&(n+=" "),n+=e.selectedStyle.lineStyleWord),n&&(n+=" "),e.filled?e.selectedStyle.fillColorWord===e.selectedStyle.lineColorWord?(t="filled "+e.selectedStyle.fillColorWord+" circle",n&&(t+=" with a "+n+"border")):t="filled "+e.selectedStyle.fillColorWord+" circle with a "+n+e.selectedStyle.lineColorWord+" border":t=n+e.selectedStyle.lineColorWord+" circle",{setValue:{styleDescriptionWithNoun:t}}}},t.borderStyleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){let t=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(t&&(t+=" "),t+=e.selectedStyle.lineStyleWord),t&&(t+=" "),t+=e.selectedStyle.lineColorWord,{setValue:{borderStyleDescription:t}}}},t.fillStyleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"},filled:{dependencyType:"stateVariable",variableName:"filled"}}),definition:function({dependencyValues:e}){let t;return t=e.filled?e.selectedStyle.fillColorWord:"unfilled",{setValue:{fillStyleDescription:t}}}},t.curveType={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{curveType:"circle"}})},t.parMax={public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{parMax:NaN}})},t.parMin={public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{parMin:NaN}})},t.fs={forRenderer:!0,isArray:!0,entryPrefixes:["f"],returnArraySizeDependencies:()=>({}),returnArraySize:()=>[0],returnArrayDependenciesByKey:()=>({}),arrayDefinitionByKey:()=>({setValue:{fs:{}}})},t.nThroughPoints={returnDependencies:()=>({throughAttr:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["nPoints"]}}),definition:function({dependencyValues:e}){return null!==e.throughAttr?{setValue:{nThroughPoints:e.throughAttr.stateValues.nPoints}}:{setValue:{nThroughPoints:0}}}},t.throughPoints={public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"throughPointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,nDimensions:2,entryPrefixes:["throughPointX","throughPoint"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("throughPointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("throughPoints"===t)return 1===e.length?"throughPoint"+e[0]:`throughPointX${e[0]}_${e[1]}`;if("throughPoint"===t.slice(0,12)){let n=Number(t.slice(12));if(Number.isInteger(n)&&n>0)return`throughPointX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints,2],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let[e,r]=n.split(","),a=Number(e)+1+"_"+(Number(r)+1);t[n]={throughAttr:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["pointX"+a]}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let[t,a]=r.split(","),i=Number(t)+1+"_"+(Number(a)+1),s=e[r].throughAttr;null!==s&&s.stateValues["pointX"+i]?n[r]=s.stateValues["pointX"+i]:n[r]=me$3.fromAst("_")}return{setValue:{throughPoints:n}}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n,initialChange:r,stateValues:a}){if(r&&!await a.draggable)return{success:!1};let i=[];for(let r in e.throughPoints){let[a,s]=r.split(","),o=Number(a)+1+"_"+(Number(s)+1);if(null===t[r].throughAttr||!t[r].throughAttr.stateValues["pointX"+o])return{success:!1};i.push({setDependency:n[r].throughAttr,desiredValue:e.throughPoints[r],variableIndex:0})}return{success:!0,instructions:i}}},t.havePrescribedCenter={returnDependencies:()=>({centerAttr:{dependencyType:"attributeComponent",attributeName:"center"}}),definition:({dependencyValues:e})=>({setValue:{havePrescribedCenter:null!==e.centerAttr},checkForActualChange:{havePrescribedCenter:!0}})},t.prescribedCenter={isArray:!0,entryPrefixes:["prescribedCenterX"],returnArraySizeDependencies:()=>({havePrescribedCenter:{dependencyType:"stateVariable",variableName:"havePrescribedCenter"}}),returnArraySize:({dependencyValues:e})=>[e.havePrescribedCenter?2:0],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={centerAttr:{dependencyType:"attributeComponent",attributeName:"center",variableNames:["x"+e]}}}return{dependenciesByKey:t}},arrayDefinitionByKey:function({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};for(let e of n){let n=Number(e)+1;null!==t[e].centerAttr&&(r[e]=t[e].centerAttr.stateValues["x"+n],r[e]||(r[e]=me$3.fromAst("_")))}return{setValue:{prescribedCenter:r}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i=[];for(let t of Object.keys(e.prescribedCenter).reverse())null!==n[t].centerAttr&&i.push({setDependency:r[t].centerAttr,desiredValue:e.prescribedCenter[t],variableIndex:0});return{success:!0,instructions:i}}},t.prescribedRadius={defaultValue:null,returnDependencies:()=>({radiusAttr:{dependencyType:"attributeComponent",attributeName:"radius",variableNames:["value"]}}),definition:function({dependencyValues:e}){return null!==e.radiusAttr?{setValue:{prescribedRadius:e.radiusAttr.stateValues.value}}:{setValue:{prescribedRadius:null}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){return null!==t.radiusAttr?{success:!0,instructions:[{setDependency:"radiusAttr",desiredValue:e.prescribedRadius,childIndex:0,variableIndex:0}]}:{success:!1}}},t.havePrescribedRadius={returnDependencies:()=>({radiusAttr:{dependencyType:"attributeComponent",attributeName:"radius"}}),definition:({dependencyValues:e})=>({setValue:{havePrescribedRadius:null!==e.radiusAttr},checkForActualChange:{havePrescribedRadius:!0}})},t.numericalPrescribedRadius={returnDependencies:()=>({prescribedRadius:{dependencyType:"stateVariable",variableName:"prescribedRadius"}}),additionalStateVariablesDefined:["haveNonNumericalPrescribedRadius"],definition:function({dependencyValues:e}){let t,n=!1;return null===e.prescribedRadius?t=null:(t=e.prescribedRadius.evaluate_to_constant(),Number.isFinite(t)||(t=NaN,n=!0)),{setValue:{haveNonNumericalPrescribedRadius:n,numericalPrescribedRadius:t},checkForActualChange:{haveNonNumericalEntriesNumericalRadius:!0}}},inverseDefinition:async function({desiredStateVariableValues:e,dependencyValues:t,stateValues:n}){return await n.haveNonNumericalPrescribedRadius?{success:!1}:void 0!==e.numericalPrescribedRadius?null===t.prescribedRadius?{success:!1}:{success:!0,instructions:[{setDependency:"prescribedRadius",desiredValue:me$3.fromAst(e.numericalPrescribedRadius)}]}:{success:!1}}},t.numericalPrescribedCenter={isArray:!0,entryPrefixes:["numericalPrescribedCenterX"],returnArraySizeDependencies:()=>({havePrescribedCenter:{dependencyType:"stateVariable",variableName:"havePrescribedCenter"}}),returnArraySize:({dependencyValues:e})=>[e.havePrescribedCenter?2:0],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={prescribedCenterX:{dependencyType:"stateVariable",variableName:"prescribedCenterX"+e}}}return{dependenciesByKey:t}},arrayDefinitionByKey:function({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].prescribedCenterX;t?(n[r]=t.evaluate_to_constant(),Number.isFinite(n[r])||(n[r]=NaN)):n[r]=NaN}return{setValue:{numericalPrescribedCenter:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t}){let n=[];for(let r in e.numericalPrescribedCenter)n.push({setDependency:t[r].prescribedCenterX,desiredValue:me$3.fromAst(e.numericalPrescribedCenter[r])});return{success:!0,instructions:n}}},t.haveNonNumericalPrescribedCenter={returnDependencies:()=>({numericalPrescribedCenter:{dependencyType:"stateVariable",variableName:"numericalPrescribedCenter"}}),definition({dependencyValues:e}){let t=e.numericalPrescribedCenter.some((e=>!Number.isFinite(e)));return{setValue:{haveNonNumericalPrescribedCenter:t},checkForActualChange:{haveNonNumericalPrescribedCenter:!0}}}},t.numericalThroughPoints={returnDependencies:()=>({throughPoints:{dependencyType:"stateVariable",variableName:"throughPoints"}}),additionalStateVariablesDefined:["haveNonNumericalThroughPoints"],definition:function({dependencyValues:e}){let t=!1,n=[];for(let r of e.throughPoints){let e=[];for(let n=0;n<2;n++){let a;try{a=r[n].evaluate_to_constant()}catch(n){console.warn("Invalid point of circle"),t=!0,e=[];break}if(!Number.isFinite(a)){t=!0,e=[];break}e.push(a)}if(!(e.length>0)){n=[];break}n.push(e)}return{setValue:{haveNonNumericalThroughPoints:t,numericalThroughPoints:n},checkForActualChange:{haveNonNumericalThroughPoints:!0}}},inverseDefinition:async function({desiredStateVariableValues:e,dependencyValues:t,stateValues:n}){if(await n.haveNonNumericalThroughPoints)return{success:!1};if(void 0!==e.numericalThroughPoints){let t={};for(let[n,r]of e.numericalThroughPoints.entries())t[n+",0"]=me$3.fromAst(r[0]),t[n+",1"]=me$3.fromAst(r[1]);return{success:!0,instructions:[{setDependency:"throughPoints",desiredValue:t}]}}return{success:!1}}},t.haveNumericalEntries={returnDependencies:()=>({haveNonNumericalPrescribedCenter:{dependencyType:"stateVariable",variableName:"haveNonNumericalPrescribedCenter"},haveNonNumericalPrescribedRadius:{dependencyType:"stateVariable",variableName:"haveNonNumericalPrescribedRadius"},haveNonNumericalThroughPoints:{dependencyType:"stateVariable",variableName:"haveNonNumericalThroughPoints"}}),definition:({dependencyValues:e})=>({setValue:{haveNumericalEntries:!(e.haveNonNumericalPrescribedCenter||e.haveNonNumericalPrescribedRadius||e.haveNonNumericalThroughPoints)}})},t.numericalRadiusCalculatedWithCenter={additionalStateVariablesDefined:["numericalCenterCalculatedWithRadius"],returnDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"},numericalThroughPoints:{dependencyType:"stateVariable",variableName:"numericalThroughPoints"},haveNumericalEntries:{dependencyType:"stateVariable",variableName:"haveNonNumericalThroughPoints"}}),definition:function({dependencyValues:e}){if(e.haveNonNumericalThroughPoints){let t="Haven't implemented circle through "+e.nThroughPoints+" points";return t+=" in case where don't have numerical values.",console.warn(t),{setValue:{numericalRadiusCalculatedWithCenter:null,numericalCenterCalculatedWithRadius:null}}}if(2===e.nThroughPoints){let{numericalCenter:t,numericalRadius:n}=circleFromTwoNumericalPoints({point1:e.numericalThroughPoints[0],point2:e.numericalThroughPoints[1]});return{setValue:{numericalCenterCalculatedWithRadius:t,numericalRadiusCalculatedWithCenter:n}}}if(3===e.nThroughPoints){let t,n,r=e.numericalThroughPoints[0][0],a=e.numericalThroughPoints[1][0],i=e.numericalThroughPoints[2][0],s=e.numericalThroughPoints[0][1],o=e.numericalThroughPoints[1][1],l=e.numericalThroughPoints[2][1];if(r===a&&s===o)if(r===i&&s===l)t=[r,s],n=0;else{let e=circleFromTwoNumericalPoints({point1:[r,s],point2:[i,l]});t=e.numericalCenter,n=e.numericalRadius}else if(r===i&&s===l||a===i&&o===l){let e=circleFromTwoNumericalPoints({point1:[r,s],point2:[a,o]});t=e.numericalCenter,n=e.numericalRadius}else{let e=r*r+s*s,u=a*a+o*o,c=i*i+l*l,p=r*(o-l)-s*(a-i)+a*l-i*o,d=e*(l-o)+u*(s-l)+c*(o-s),m=e*(a-i)+u*(i-r)+c*(r-a),h=e*(i*o-a*l)+u*(r*l-i*s)+c*(a*s-r*o);0!==p?(t=[-d/(2*p),-m/(2*p)],n=Math.sqrt((d*d+m*m-4*p*h)/(4*p*p))):(t=[NaN,NaN],n=NaN)}return{setValue:{numericalCenterCalculatedWithRadius:t,numericalRadiusCalculatedWithCenter:n}}}return e.nThroughPoints>3?(console.warn("Can't calculate circle through more than 3 points"),{setValue:{numericalRadiusCalculatedWithCenter:null,numericalCenterCalculatedWithRadius:null}}):{setValue:{numericalRadiusCalculatedWithCenter:null,numericalCenterCalculatedWithRadius:null}}}},t.essentialRadius={defaultValue:1,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{essentialRadius:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"essentialRadius",value:e.essentialRadius}]}}},t.numericalRadius={forRenderer:!0,stateVariablesDeterminingDependencies:["nThroughPoints","havePrescribedCenter","havePrescribedRadius"],returnDependencies:function({stateValues:e}){let t={haveNonNumericalPrescribedRadius:{dependencyType:"stateVariable",variableName:"haveNonNumericalPrescribedRadius"},nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"},essentialRadius:{dependencyType:"stateVariable",variableName:"essentialRadius"}};return e.havePrescribedRadius?(t.numericalPrescribedRadius={dependencyType:"stateVariable",variableName:"numericalPrescribedRadius"},e.havePrescribedCenter&&e.nThroughPoints>0&&(t.haveCenterRadiusPoints={dependencyType:"value",value:!0})):e.havePrescribedCenter?1===e.nThroughPoints&&(t.haveNonNumericalPrescribedCenter={dependencyType:"stateVariable",variableName:"haveNonNumericalPrescribedCenter"},t.numericalPrescribedCenter={dependencyType:"stateVariable",variableName:"numericalPrescribedCenter"},t.haveNonNumericalThroughPoints={dependencyType:"stateVariable",variableName:"haveNonNumericalThroughPoints"},t.numericalThroughPoints={dependencyType:"stateVariable",variableName:"numericalThroughPoints"}):e.nThroughPoints>1&&(t.numericalRadiusCalculatedWithCenter={dependencyType:"stateVariable",variableName:"numericalRadiusCalculatedWithCenter"},t.numericalThroughPoints={dependencyType:"stateVariable",variableName:"numericalThroughPoints"}),t},definition:function({dependencyValues:e}){if(e.haveNonNumericalPrescribedRadius||e.haveNonNumericalPrescribedCenter||e.haveNonNumericalThroughPoints)return{setValue:{numericalRadius:NaN}};if(void 0!==e.numericalPrescribedRadius)return e.haveCenterRadiusPoints?(console.warn("Can't calculate circle with specified radius and center and through points"),{setValue:{numericalRadius:NaN}}):{setValue:{numericalRadius:Math.max(0,e.numericalPrescribedRadius)}};if(void 0!==e.numericalPrescribedCenter){if(0===e.nThroughPoints){let t=e.essentialRadius;if(t instanceof me$3.class){try{t=t.evaluate_to_constant()}catch(e){}Number.isFinite(t)||(t=NaN)}return{setValue:{numericalRadius:t}}}if(1===e.nThroughPoints){let t=e.numericalThroughPoints[0];return void 0===t?{setValue:{numericalRadius:NaN}}:{setValue:{numericalRadius:Math.sqrt(Math.pow(t[0]-e.numericalPrescribedCenter[0],2)+Math.pow(t[1]-e.numericalPrescribedCenter[1],2))}}}return console.warn("Can't calculate circle with specified center through more than 1 point"),{setValue:{numericalRadius:NaN}}}if(e.nThroughPoints<2){let t=e.essentialRadius;if(t instanceof me$3.class){try{t=t.evaluate_to_constant()}catch(e){}Number.isFinite(t)||(t=NaN)}return{setValue:{numericalRadius:t}}}return{setValue:{numericalRadius:e.numericalRadiusCalculatedWithCenter}}},inverseDefinition:async function({desiredStateVariableValues:e,dependencyValues:t,stateValues:n}){if(void 0!==t.numericalPrescribedRadius)return{success:!0,instructions:[{setDependency:"numericalPrescribedRadius",desiredValue:Math.max(0,e.numericalRadius)}]};if(void 0!==t.numericalPrescribedCenter){if(0===t.nThroughPoints)return{success:!0,instructions:[{setDependency:"essentialRadius",desiredValue:Math.max(0,e.numericalRadius)}]};if(1===t.nThroughPoints){let t=Math.max(0,e.numericalRadius),r=(await n.throughAngles)[0];if(!Number.isFinite(r))return{success:!1};let a=await n.numericalCenter;return{success:!0,instructions:[{setDependency:"numericalThroughPoints",desiredValue:[[a[0]+t*Math.cos(r),a[1]+t*Math.sin(r)]]}]}}return{success:!1}}if(t.nThroughPoints<2)return{success:!0,instructions:[{setDependency:"essentialRadius",desiredValue:Math.max(0,e.numericalRadius)}]};{let r=[],a=Math.max(0,e.numericalRadius);for(let e=0;e0,returnArraySizeDependencies:()=>({}),returnArraySize:()=>[2],returnArrayDependenciesByKey:()=>({}),arrayDefinitionByKey:function({arrayKeys:e}){let t={};for(let n of e)t[n]=!0;return{useEssentialOrDefaultValue:{essentialCenter:t}}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,stateValues:t,workspace:n}){let r=[];for(let t in e.essentialCenter)r.push({setEssentialValue:"essentialCenter",value:{[t]:e.essentialCenter[t]}});return{success:!0,instructions:r}}},t.numericalCenter={forRenderer:!0,isArray:!0,entryPrefixes:["numericalCenterX"],stateVariablesDeterminingDependencies:["nThroughPoints","havePrescribedCenter","havePrescribedRadius"],returnArraySizeDependencies:()=>({}),returnArraySize:()=>[2],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={},r={};if(t.havePrescribedCenter){for(let t of e){let e=Number(t)+1;r[t]={numericalPrescribedCenterX:{dependencyType:"stateVariable",variableName:"numericalPrescribedCenterX"+e}}}t.havePrescribedRadius&&t.nThroughPoints>0&&(n.haveCenterRadiusPoints={dependencyType:"value",value:!0})}else{for(let t of e){let e=Number(t)+1;r[t]={essentialCenterX:{dependencyType:"stateVariable",variableName:"essentialCenterX"+e}}}n.nThroughPoints={dependencyType:"stateVariable",variableName:"nThroughPoints"},n.numericalThroughPoints={dependencyType:"stateVariable",variableName:"numericalThroughPoints"},n.haveNonNumericalThroughPoints={dependencyType:"stateVariable",variableName:"haveNonNumericalThroughPoints"},t.havePrescribedRadius||1==t.nThroughPoints?n.numericalRadius={dependencyType:"stateVariable",variableName:"numericalRadius"}:t.nThroughPoints>1&&(n.numericalCenterCalculatedWithRadius={dependencyType:"stateVariable",variableName:"numericalCenterCalculatedWithRadius"})}return{globalDependencies:n,dependenciesByKey:r}},arrayDefinitionByKey:function({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};for(let a of n)if(void 0!==t[a].numericalPrescribedCenterX){if(e.haveCenterRadiusPoints)return console.warn("Can't calculate circle with specified radius and center and through points"),{setValue:{numericalCenter:[NaN,NaN]}};r[a]=t[a].numericalPrescribedCenterX}if(Object.keys(r).length>0)return{setValue:{numericalCenter:r}};if(e.haveNonNumericalPrescribedRadius||e.haveNonNumericalThroughPoints)return{setValue:{numericalCenter:[NaN,NaN]}};if(void 0!==e.numericalRadius){if(0===e.nThroughPoints){for(let e of n){let n=t[e].essentialCenterX;if(n instanceof me$3.class){try{n=n.evaluate_to_constant()}catch(e){}Number.isFinite(n)||(n=NaN)}r[e]=n}return{setValue:{numericalCenter:r}}}if(1===e.nThroughPoints){if(e.numericalThroughPoints.length<1)return{setValue:{numericalCenter:[NaN,NaN]}};return{setValue:{numericalCenter:[e.numericalThroughPoints[0][0],e.numericalThroughPoints[0][1]-e.numericalRadius]}}}if(2===e.nThroughPoints){if(e.numericalThroughPoints.length<2)return{setValue:{numericalCenter:[NaN,NaN]}};let t=e.numericalRadius,n=e.numericalThroughPoints[0][0],r=e.numericalThroughPoints[1][0],a=e.numericalThroughPoints[0][1],i=e.numericalThroughPoints[1][1],s=Math.pow(n-r,2)+Math.pow(a-i,2),o=t*t;return t<0||4*o0)return{success:!0,instructions:s};if(0===t.nThroughPoints){for(let t in e.numericalCenter)s.push({setDependency:r[t].essentialCenterX,desiredValue:e.numericalCenter[t]});return{success:!0,instructions:s}}{i.desiredCenter||(i.desiredCenter={});for(let t=0;t<2;t++)void 0!==e.numericalCenter[t]?i.desiredCenter[t]=e.numericalCenter[t]:void 0===i.desiredCenter[t]&&(i.desiredCenter[t]=a.numericalCenter[t]);let n=[],r=await a.throughAngles,s=await a.numericalRadius;for(let e=0;e({haveNumericalEntries:{dependencyType:"stateVariable",variableName:"haveNumericalEntries"},nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"},numericalThroughPoints:{dependencyType:"stateVariable",variableName:"numericalThroughPoints"},numericalRadius:{dependencyType:"stateVariable",variableName:"numericalRadius"},numericalCenter:{dependencyType:"stateVariable",variableName:"numericalCenter"}}),definition:function({dependencyValues:e}){if(!(e.haveNumericalEntries&&e.nThroughPoints>0&&e.numericalRadius>0&&e.numericalCenter.every((e=>Number.isFinite(e)))))return{useEssentialOrDefaultValue:{throughAngles:!0}};let t=[];for(let n of e.numericalThroughPoints)t.push(Math.atan2(n[1]-e.numericalCenter[1],n[0]-e.numericalCenter[0]));return{setValue:{throughAngles:t},setEssentialValue:{throughAngles:t}}}},t.radius={public:!0,shadowingInstructions:{createComponentOfType:"math"},stateVariablesDeterminingDependencies:["nThroughPoints","havePrescribedCenter","havePrescribedRadius"],returnDependencies:function({stateValues:e}){let t={numericalRadius:{dependencyType:"stateVariable",variableName:"numericalRadius"},nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"},essentialRadius:{dependencyType:"stateVariable",variableName:"essentialRadius"}};return e.havePrescribedRadius?(t.prescribedRadius={dependencyType:"stateVariable",variableName:"prescribedRadius"},e.havePrescribedCenter&&e.nThroughPoints>0&&(t.haveCenterRadiusPoints={dependencyType:"value",value:!0})):e.havePrescribedCenter&&1===e.nThroughPoints&&(t.prescribedCenter={dependencyType:"stateVariable",variableName:"prescribedCenter"},t.throughPoints={dependencyType:"stateVariable",variableName:"throughPoints"}),t},definition:function({dependencyValues:e}){if(Number.isFinite(e.numericalRadius))return{setValue:{radius:me$3.fromAst(e.numericalRadius)}};if(void 0!==e.prescribedRadius)return e.haveCenterRadiusPoints?(console.warn("Can't calculate circle with specified radius and center and through points"),{setValue:{radius:me$3.fromAst("_")}}):{setValue:{radius:e.prescribedRadius}};if(void 0!==e.prescribedCenter){if(0===e.nThroughPoints){let t=e.essentialRadius;return t instanceof me$3.class||(t=Number.isFinite(t)?me$3.fromAst(t):me$3.fromAst("_")),{setValue:{radius:t}}}if(1!==e.nThroughPoints)return console.warn("Can't calculate circle with specified center through more than 1 point"),{setValue:{radius:me$3.fromAst("_")}};try{let t=e.throughPoints[0],n=t[0],r=t[1],a=e.prescribedCenter[0],i=e.prescribedCenter[1];return{setValue:{radius:n.subtract(a).pow(2).add(r.subtract(i).pow(2)).pow(.5).simplify()}}}catch(e){return console.warn("Invalid center or through points of circle"),{setValue:{radius:me$3.fromAst("_")}}}}if(e.nThroughPoints<2){let t=e.essentialRadius;return t instanceof me$3.class||(t=Number.isFinite(t)?me$3.fromAst(t):me$3.fromAst("_")),{setValue:{radius:t}}}return console.warn(`Have not implemented circle through ${e.nThroughPoints} points when non-numerical values`),{setValue:{radius:me$3.fromAst("_")}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){let n=e.radius.evaluate_to_constant();if(Number.isFinite(n)&&Number.isFinite(t.numericalRadius))return{success:!0,instructions:[{setDependency:"numericalRadius",desiredValue:n}]};if(void 0!==t.prescribedRadius)return{success:!0,instructions:[{setDependency:"prescribedRadius",desiredValue:e.radius}]};if(0===t.nThroughPoints){return{success:!0,instructions:[{setDependency:"essentialRadius",desiredValue:e.radius}]}}return console.warn("Can't change radius of circle with non-numerical values through points"),{success:!1}}},t.diameter={public:!0,shadowingInstructions:{createComponentOfType:"math"},returnDependencies:()=>({radius:{dependencyType:"stateVariable",variableName:"radius"}}),definition:({dependencyValues:e})=>({setValue:{diameter:e.radius.multiply(2).simplify()}}),inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){return{success:!0,instructions:[{setDependency:"radius",desiredValue:e.diameter.divide(2).simplify()}]}}},t.center={forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"centerX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,entryPrefixes:["centerX"],stateVariablesDeterminingDependencies:["nThroughPoints","havePrescribedCenter","havePrescribedRadius"],returnArraySizeDependencies:()=>({}),returnArraySize:()=>[2],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={},r={};if(t.havePrescribedCenter){n.havePrescribedCenter={dependencyType:"value",value:!0};for(let t of e){let e=Number(t)+1;r[t]={numericalCenterX:{dependencyType:"stateVariable",variableName:"numericalCenterX"+e},prescribedCenterX:{dependencyType:"stateVariable",variableName:"prescribedCenterX"+e}}}t.havePrescribedRadius&&t.nThroughPoints>0&&(n.haveCenterRadiusPoints={dependencyType:"value",value:!0})}else{for(let t of e){let e=Number(t)+1;r[t]={essentialCenterX:{dependencyType:"stateVariable",variableName:"essentialCenterX"+e}}}n.numericalCenter={dependencyType:"stateVariable",variableName:"numericalCenter"},n.nThroughPoints={dependencyType:"stateVariable",variableName:"nThroughPoints"},n.throughPoints={dependencyType:"stateVariable",variableName:"throughPoints"},t.havePrescribedRadius?n.radius={dependencyType:"stateVariable",variableName:"prescribedRadius"}:1==t.nThroughPoints&&(n.radius={dependencyType:"stateVariable",variableName:"radius"})}return{dependenciesByKey:r,globalDependencies:n}},arrayDefinitionByKey:function({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){if(e.havePrescribedCenter){if(e.haveCenterRadiusPoints)return console.warn("Can't calculate circle with specified radius and center and through points"),{setValue:{center:[me$3.fromAst("_"),me$3.fromAst("_")]}};let r={};for(let e of n)Number.isFinite(t[e].numericalCenterX)?r[e]=me$3.fromAst(t[e].numericalCenterX):r[e]=t[e].prescribedCenterX;return{setValue:{center:r}}}if(e.numericalCenter.every((e=>Number.isFinite(e))))return{setValue:{center:e.numericalCenter.map((e=>me$3.fromAst(e)))}};if(void 0!==e.radius){if(0===e.nThroughPoints){let e={};for(let r of n){let n=t[r].essentialCenterX;n instanceof me$3.class||(n=Number.isFinite(n)?me$3.fromAst(n):me$3.fromAst("_")),e[r]=n}return{setValue:{center:e}}}if(1===e.nThroughPoints){let t;try{t=[e.throughPoints[0][0],e.throughPoints[0][1].subtract(e.radius).simplify()]}catch(e){t=[me$3.fromAst("_"),me$3.fromAst("_")]}return{setValue:{center:t}}}return console.warn("Can't create circle through more than one point with given radius when don't have numerical values"),{setValue:{center:[me$3.fromAst("_"),me$3.fromAst("_")]}}}if(0===e.nThroughPoints){let e={};for(let r of n){let n=t[r].essentialCenterX;n instanceof me$3.class||(n=Number.isFinite(n)?me$3.fromAst(n):me$3.fromAst("_")),e[r]=n}return{setValue:{center:e}}}return console.warn("Can't create circle through more than one point when don't have numerical values"),{setValue:{center:[me$3.fromAst("_"),me$3.fromAst("_")]}}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,stateValues:n,dependencyNamesByKey:r,workspace:a}){if(t.havePrescribedCenter){let t=[];for(let n in e.center)t.push({setDependency:r[n].prescribedCenterX,desiredValue:e.center[n],arrayKey:n});return{success:!0,instructions:t}}a.desiredCenter||(a.desiredCenter={});for(let t=0;t<2;t++)void 0!==e.center[t]?a.desiredCenter[t]=e.center[t]:void 0===a.desiredCenter[t]&&(a.desiredCenter[t]=(await n.center)[t]);let i=[],s=!0;for(let e=0;e<2;e++){let t=a.desiredCenter[e].evaluate_to_constant();if(!Number.isFinite(t)){s=!1;break}i.push(t)}if(s&&t.numericalCenter.every((e=>Number.isFinite(e))))return{success:!0,instructions:[{setDependency:"numericalCenter",desiredValue:i}]};if(0===t.nThroughPoints){let t=[];for(let n in e.center)t.push({setDependency:r[n].essentialCenterX,desiredValue:e.center[n],arrayKey:n});return{success:!0,instructions:t}}return console.warn("Haven't implemented changing center of circle through points with non numerical values"),{success:!1}}},t.nearestPoint={returnDependencies:()=>({numericalCenter:{dependencyType:"stateVariable",variableName:"numericalCenter"},numericalRadius:{dependencyType:"stateVariable",variableName:"numericalRadius"}}),definition({dependencyValues:e}){let t=e.numericalRadius,n=e.numericalCenter[0],r=e.numericalCenter[1];return{setValue:{nearestPoint:function({variables:e,scales:a}){let i=e.x1?.evaluate_to_constant(),s=e.x2?.evaluate_to_constant();if(!Number.isFinite(i)||!Number.isFinite(s))return{};if(!(Number.isFinite(n)&&Number.isFinite(r)&&Number.isFinite(t)))return{};let o=Math.atan2(s-r,i-n),l={x1:n+t*Math.cos(o),x2:r+t*Math.sin(o)};return void 0!==e.x3&&(l.x3=0),l}}}}},t}async moveCircle({center:e,radius:t,throughAngles:n,transient:r,actionId:a}){let i=[],s=await this.stateValues.nThroughPoints,o=await this.stateValues.numericalPrescribedCenter;if((s<=1||null!==o)&&i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"numericalCenter",value:e}),s>=1){let r=[];void 0===n&&(n=await this.stateValues.throughAngles),void 0===t&&(t=await this.stateValues.numericalRadius);for(let a=0;a({styleDescription:{dependencyType:"stateVariable",variableName:"styleDescription"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescriptionWithNoun:e.styleDescription+" parabola"}}}},t.curveType={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{curveType:"function"}})},t.parMax={public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{parMax:1/0}})},t.parMin={public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{parMin:-1/0}})},t.aShadow={defaultValue:1,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{aShadow:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"aShadow",value:e.aShadow}]}}},t.nThroughPoints={returnDependencies:()=>({throughAttr:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["nPoints"]}}),definition:function({dependencyValues:e}){return null===e.throughAttr?{setValue:{nThroughPoints:0}}:{setValue:{nThroughPoints:e.throughAttr.stateValues.nPoints}}}},t.throughPoints={public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"throughPointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,nDimensions:2,entryPrefixes:["throughPointX","throughPoint"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("throughPointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("throughPoints"===t)return 1===e.length?"throughPoint"+e[0]:`throughPointX${e[0]}_${e[1]}`;if("throughPoint"===t.slice(0,12)){let n=Number(t.slice(12));if(Number.isInteger(n)&&n>0)return`throughPointX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints,2],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let[e,r]=n.split(","),a=Number(e)+1+"_"+(Number(r)+1);t[n]={throughAttr:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["pointX"+a]}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let[t,a]=r.split(","),i=Number(t)+1+"_"+(Number(a)+1),s=e[r].throughAttr;if(null!==s&&s.stateValues["pointX"+i]){let e=s.stateValues["pointX"+i].evaluate_to_constant();Number.isFinite(e)?n[r]=me$3.fromAst(e):n[r]=me$3.fromAst("_")}else n[r]=me$3.fromAst("_")}return{setValue:{throughPoints:n}}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n,initialChange:r,stateValues:a}){if(r&&!await a.draggable)return{success:!1};let i=[];for(let r in e.throughPoints){let[a,s]=r.split(","),o=Number(a)+1+"_"+(Number(s)+1);if(null===t[r].throughAttr||!t[r].throughAttr.stateValues["pointX"+o])return{success:!1};i.push({setDependency:n[r].throughAttr,desiredValue:e.throughPoints[r],childIndex:0,variableIndex:0})}return{success:!0,instructions:i}}},t.numericalThroughPoints={isArray:!0,forRenderer:!0,returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={throughPoint:{dependencyType:"stateVariable",variableName:"throughPoint"+(Number(n)+1)}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].throughPoint.map((e=>e.tree));t.every((e=>Number.isFinite(e)))||(t=Array(t.length).fill(NaN)),n[r]=t}return{setValue:{numericalThroughPoints:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n}){let r=[];for(let a in e.numericalThroughPoints){if(!t[a].throughPoint)return{success:!1};r.push({setDependency:n[a].throughPoint,desiredValue:e.numericalThroughPoints[a].map((e=>me$3.fromAst(e)))})}return{success:!0,instructions:r}}},t.numericalPrescribedVertex={returnDependencies:()=>({prescribedVertex:{dependencyType:"stateVariable",variableName:"prescribedVertex"}}),definition({dependencyValues:e}){if(null===e.prescribedVertex)return{setValue:{numericalPrescribedVertex:null}};let t,n;try{t=e.prescribedVertex.get_component(0).evaluate_to_constant(),n=e.prescribedVertex.get_component(1).evaluate_to_constant(),Number.isFinite(t)&&Number.isFinite(n)||(t=NaN,n=NaN)}catch(e){t=NaN,n=NaN}return{setValue:{numericalPrescribedVertex:[t,n]}}}},t.pointsAreNumerical={returnDependencies:()=>({numericalThroughPoints:{dependencyType:"stateVariable",variableName:"numericalThroughPoints"},numericalPrescribedVertex:{dependencyType:"stateVariable",variableName:"numericalPrescribedVertex"}}),definition:({dependencyValues:e})=>({setValue:{pointsAreNumerical:e.numericalThroughPoints.every((e=>Number.isFinite(e[0])))&&(!e.numericalPrescribedVertex||Number.isFinite(e.numericalPrescribedVertex[0]))},checkForActualChange:{pointsAreNumerical:!0}})},t.a={public:!0,shadowingInstructions:{createComponentOfType:"number"},additionalStateVariablesDefined:[{variableName:"b",public:!0,shadowingInstructions:{createComponentOfType:"number"},hasEssential:!0,defaultValue:0},{variableName:"c",public:!0,shadowingInstructions:{createComponentOfType:"number"},hasEssential:!0,defaultValue:0},"realValued"],returnDependencies:()=>({numericalThroughPoints:{dependencyType:"stateVariable",variableName:"numericalThroughPoints"},numericalPrescribedVertex:{dependencyType:"stateVariable",variableName:"numericalPrescribedVertex"},pointsAreNumerical:{dependencyType:"stateVariable",variableName:"pointsAreNumerical"},aShadow:{dependencyType:"stateVariable",variableName:"aShadow"}}),definition:function({dependencyValues:e,componentName:t}){if(!e.pointsAreNumerical)return{setValue:{a:NaN,b:NaN,c:NaN,realValued:!1}};let n,r,a,i=!0;if(e.numericalPrescribedVertex){if(0===e.numericalThroughPoints.length){let t=e.numericalPrescribedVertex,i=t[0],s=t[1];return n=e.aShadow,r=-2*n*i,a=n*i*i+s,{setValue:{a:n,b:r,c:a,realValued:!0}}}{let t=e.numericalPrescribedVertex,i=t[0],s=t[1],o=e.numericalThroughPoints[0],l=o[0];return n=(o[1]-s)/(l-i)**2,r=-2*n*i,a=n*i*i+s,{setValue:{a:n,b:r,c:a,realValued:!0}}}}if(0===e.numericalThroughPoints.length)return{setValue:{a:e.aShadow,realValued:!0},useEssentialOrDefaultValue:{b:!0,c:!0}};if(1===e.numericalThroughPoints.length){let t=e.numericalThroughPoints[0],i=t[0],s=t[1];return n=e.aShadow,r=-2*n*i,a=n*i*i+s,{setValue:{a:n,b:r,c:a,realValued:!0}}}if(2===e.numericalThroughPoints.length){n=e.aShadow;let t=e.numericalThroughPoints[0],s=t[0],o=t[1],l=s*s,u=e.numericalThroughPoints[1],c=u[0],p=u[1],d=c*c;return s===c?o==p?(r=-2*n*s,a=n*l+o):(i=!1,n=NaN,r=NaN,a=NaN):(r=(o-p-n*(l-d))/(s-c),a=o-n*l-r*s),{setValue:{a:n,b:r,c:a,realValued:i}}}if(3===e.numericalThroughPoints.length){let t=e.numericalThroughPoints[0],s=t[0],o=t[1],l=s*s,u=e.numericalThroughPoints[1],c=u[0],p=u[1],d=c*c,m=e.numericalThroughPoints[2],h=m[0],f=m[1],y=h*h,g=l-y,b=d-y,v=s-h,N=c-h,T=o-f,C=p-f,A=g*N-b*v;if(0===A){let t,u,d,m=!1;s===c?o===p?s===h?o==f?t=1:m=!0:(t=2,u=h,d=f):m=!0:s===h?o===f?(t=2,u=c,d=p):m=!0:c===h&&p===f?(t=2,u=c,d=p):m=!0,m?(i=!1,n=NaN,r=NaN,a=NaN):1===t?(n=e.aShadow,r=-2*n*s,a=n*s*s+o):(n=e.aShadow,r=(o-d-n*(l-u*u))/(s-u),a=o-n*l-r*s)}else n=(T*N-C*v)/A,r=(C*g-T*b)/A,a=o-r*s-n*l;return{setValue:{a:n,b:r,c:a,realValued:i}}}return console.warn("Haven't implemented parabola through more than 3 points"),{setValue:{a:NaN,b:NaN,c:NaN,realValued:!1}}},inverseDefinition:async function({desiredStateVariableValues:e,dependencyValues:t,stateValues:n,workspace:r}){if(!t.pointsAreNumerical)return{success:!1};let a={},i=function(e){if(Number.isFinite(e))return{success:!0,value:e};if(e instanceof me$3.class){let t=e.evaluate_to_constant();if(Number.isFinite(t))return{success:!0,value:t}}return{success:!1}};if(void 0!==e.a){let t=i(e.a);if(!t.success)return{success:!1};a.a=t.value}if(void 0!==e.b){let t=i(e.b);if(!t.success)return{success:!1};a.b=t.value}if(void 0!==e.c){let t=i(e.c);if(!t.success)return{success:!1};a.c=t.value}Object.assign(r,a);let s=async function(e){return void 0!==r[e]?r[e]:await n[e]};if(0===t.numericalThroughPoints.length){let e=[];return void 0!==a.a&&e.push({setDependency:"aShadow",desiredValue:a.a}),void 0!==a.b&&e.push({setEssentialValue:"b",value:a.b}),void 0!==a.c&&e.push({setEssentialValue:"c",value:a.c}),{success:!0,instructions:e}}if(1===t.numericalThroughPoints.length){let e=await s("a"),t=await s("b"),n=await s("c"),r=[{setDependency:"numericalThroughPoints",desiredValue:[[-t/(2*e),n-t*t/(4*e)]]}];return void 0!==a.a&&r.push({setDependency:"aShadow",desiredValue:a.a}),{success:!0,instructions:r}}if(2===t.numericalThroughPoints.length){let e=await s("a"),n=await s("b"),r=await s("c"),i=t.numericalThroughPoints[0][0],o=t.numericalThroughPoints[1][0];if(i===o){i=-n/(2*e);let t=r-n*n/(4*e),s=[{setDependency:"numericalThroughPoints",desiredValue:[[i,t],[i,t]]}];return void 0!==a.a&&s.push({setDependency:"aShadow",desiredValue:a.a}),{success:!0,instructions:s}}{let t=[{setDependency:"numericalThroughPoints",desiredValue:[[i,e*i*i+n*i+r],[o,e*o*o+n*o+r]]}];return void 0!==a.a&&t.push({setDependency:"aShadow",desiredValue:a.a}),{success:!0,instructions:t}}}if(3===t.numericalThroughPoints.length){let e,n=await s("a"),r=await s("b"),i=await s("c"),o=t.numericalThroughPoints[0][0],l=t.numericalThroughPoints[1][0],u=t.numericalThroughPoints[2][0],c=3;if(o===l?o===u?c=1:(c=2,e=3):o===u?(c=2,e=2):l===u&&(c=2,e=1),3===c){let e=[{setDependency:"numericalThroughPoints",desiredValue:[[o,n*o*o+r*o+i],[l,n*l*l+r*l+i],[u,n*u*u+r*u+i]]}];return void 0!==a.a&&e.push({setDependency:"aShadow",desiredValue:a.a}),{success:!0,instructions:e}}if(2===c){if(1===e){let e=n*l*l+r*l+i,t=[{setDependency:"numericalThroughPoints",desiredValue:[[o,n*o*o+r*o+i],[l,e],[l,e]]}];return void 0!==a.a&&t.push({setDependency:"aShadow",desiredValue:a.a}),{success:!0,instructions:t}}if(2===e){let e=n*o*o+r*o+i,t=[{setDependency:"numericalThroughPoints",desiredValue:[[o,e],[l,n*l*l+r*l+i],[o,e]]}];return void 0!==a.a&&t.push({setDependency:"aShadow",desiredValue:a.a}),{success:!0,instructions:t}}{let e=n*o*o+r*o+i,t=[{setDependency:"numericalThroughPoints",desiredValue:[[o,e],[o,e],[u,n*u*u+r*u+i]]}];return void 0!==a.a&&t.push({setDependency:"aShadow",desiredValue:a.a}),{success:!0,instructions:t}}}{o=-r/(2*n);let e=i-r*r/(4*n),t=[{setDependency:"numericalThroughPoints",desiredValue:[[o,e],[o,e],[o,e]]}];return void 0!==a.a&&t.push({setDependency:"aShadow",desiredValue:a.a}),{success:!0,instructions:t}}}return{success:!1}}},t.vertex={public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"vertexX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,entryPrefixes:["vertexX"],returnArraySizeDependencies:()=>({}),returnArraySize:()=>[2],returnArrayDependenciesByKey:()=>({globalDependencies:{a:{dependencyType:"stateVariable",variableName:"a"},b:{dependencyType:"stateVariable",variableName:"b"},c:{dependencyType:"stateVariable",variableName:"c"},realValued:{dependencyType:"stateVariable",variableName:"realValued"}}}),arrayDefinitionByKey:function({globalDependencyValues:e}){let t={};return e.realValued&&0!==e.a?(t[0]=me$3.fromAst(-e.b/(2*e.a)),t[1]=me$3.fromAst(e.c-e.b**2/(4*e.a))):(t[0]=me$3.fromAst("_"),t[1]=me$3.fromAst("_")),{setValue:{vertex:t}}},inverseArrayDefinitionByKey:async function({desiredStateVariableValues:e,globalDependencyValues:t,workspace:n,stateValues:r}){let a,i;if(a="0"in e.vertex?e.vertex[0].evaluate_to_constant():void 0!==n.x?n.x:(await r.vertex)[0].tree,!Number.isFinite(a))return{success:!1};if(n.x=a,i="1"in e.vertex?e.vertex[1].evaluate_to_constant():void 0!==n.y?n.y:(await r.vertex)[1].tree,!Number.isFinite(i))return{success:!1};n.y=i;let s=t.a;return{success:!0,instructions:[{setDependency:"b",desiredValue:-2*s*a,additionalDependencyValues:{c:i+s*a*a}}]}}},t.equation={public:!0,shadowingInstructions:{createComponentOfType:"math"},additionalProperties:{simplify:"numberspreserveorder",displaysmallaszero:!0},returnDependencies:()=>({a:{dependencyType:"stateVariable",variableName:"a"},b:{dependencyType:"stateVariable",variableName:"b"},c:{dependencyType:"stateVariable",variableName:"c"}}),definition:function({dependencyValues:e}){let t=["=","y",["+",["*",e.a,["^","x",2]],["*",e.b,"x"],e.c]];return{setValue:{equation:me$3.fromAst(t).evaluate_numbers({skip_ordering:!0})}}}},t.fs={forRenderer:!0,isArray:!0,entryPrefixes:["f"],additionalStateVariablesDefined:[{variableName:"fDefinitions",isArray:!0,forRenderer:!0}],returnArraySizeDependencies:()=>({}),returnArraySize:()=>[1],returnArrayDependenciesByKey:()=>({globalDependencies:{a:{dependencyType:"stateVariable",variableName:"a"},b:{dependencyType:"stateVariable",variableName:"b"},c:{dependencyType:"stateVariable",variableName:"c"}}}),arrayDefinitionByKey:({globalDependencyValues:e})=>({setValue:{fs:[function(t){return e.a*t*t+e.b*t+e.c}],fDefinitions:[{functionType:"formula",formula:["+",["*",e.a,"x","x"],["*",e.b,"x"],e.c],variables:["x"],nInputs:1,nOutputs:1,domain:null}]}})},t.f={isAlias:!0,targetVariableName:"f1"},t.nearestPoint={returnDependencies:()=>({f:{dependencyType:"stateVariable",variableName:"f"},a:{dependencyType:"stateVariable",variableName:"a"},b:{dependencyType:"stateVariable",variableName:"b"},c:{dependencyType:"stateVariable",variableName:"c"}}),definition({dependencyValues:e,componentName:t}){let n=!(Number.isFinite(e.a)&&Number.isFinite(e.b)&&Number.isFinite(e.c));return{setValue:{nearestPoint:function({variables:t,scales:r}){if(n)return{};let a=r[0],i=r[1],s=t.x1?.evaluate_to_constant(),o=t.x2?.evaluate_to_constant();if(!Number.isFinite(s)||!Number.isFinite(o))return{};s/=a,o/=i;let l=e.a*a*a/i,u=e.b*a/i,c=e.c/i;if(0===l){let e=u*u+1,n={};return n.x1=(s+u*o-u*c)/e*a,n.x2=(u*(s+u*o)+c)/e*i,void 0!==t.x3&&(n.x3=0),n}let p=c-o,d=2*l**2,m=cardano(3*l*u/d,(2*l*p+u**2+1)/d,(u*p-s)/d,1e-14),h=m[0],f=e.f(h*a)/i,y=(s-h)**2+(o-f)**2;for(let t of m.slice(1)){let n=t,r=e.f(n*a)/i,l=(s-n)**2+(o-r)**2;l0){const t=Math.sqrt(s/108),n=2*Math.sqrt(Math.cbrt(i*i/4+s/108)),r=Math.atan2(t,-i/2);return[Math.cos(r/3),Math.cos(r/3+2*Math.PI/3),Math.cos(r/3-2*Math.PI/3)].sort(((e,t)=>e-t)).map((t=>n*t-e/3))}const o=Math.sqrt(-s/108);return[Math.cbrt(-i/2+o)+Math.cbrt(-i/2-o)-e/3]}class BezierControls extends InlineComponent{static componentType="bezierControls";static rendererType="containerInline";static createAttributesObject(){let e=super.createAttributesObject();return e.alwaysVisible={createComponentOfType:"boolean",createStateVariable:"alwaysVisible",defaultValue:!1,public:!0},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e}){let t=breakEmbeddedStringsIntoParensPieces({componentList:e});return!0!==t.success?{success:!1}:{success:!0,newChildren:t.pieces.map((function(e){return e.length>1||"string"==typeof e[0]?{componentType:"controlVectors",children:[{componentType:"vector",children:e}]}:e[0]}))}}}),e}static returnChildGroups(){return[{group:"controlVectors",componentTypes:["controlVectors"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nControls={returnDependencies:()=>({nParentPoints:{dependencyType:"parentStateVariable",variableName:"nThroughPoints",skipComponentNames:!0}}),definition({dependencyValues:e}){let t=e.nParentPoints;return Number.isInteger(t)&&t>=0||(t=0),{setValue:{nControls:t}}}},e.pointIndMap={returnDependencies:()=>({controlChildren:{dependencyType:"child",childGroups:["controlVectors"],variableNames:["pointNumber"]}}),definition:function({dependencyValues:e}){let t=[],n=-1;for(let[r,a]of e.controlChildren.entries()){let e=a.stateValues.pointNumber;Number.isFinite(e)?n=Math.round(e)-1:n+=1,t[n]=r}return{setValue:{pointIndMap:t}}}},e.directions={isArray:!0,entryPrefixes:["direction"],hasEssential:!0,defaultValueByArrayKey:()=>"none",stateVariablesDeterminingDependencies:["pointIndMap"],returnArraySizeDependencies:()=>({nControls:{dependencyType:"stateVariable",variableName:"nControls"}}),returnArraySize:({dependencyValues:e})=>[e.nControls],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=t.pointIndMap[r];void 0!==e&&(n[r]={controlChild:{dependencyType:"child",childGroups:["controlVectors"],variableNames:["direction"],childIndices:[e]}})}return{dependenciesByKey:n}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={},r={};for(let a of t){let t=e[a].controlChild;t&&1===t.length?n[a]=t[0].stateValues.direction:r[a]=!0}return{setValue:{directions:n},useEssentialOrDefaultValue:{directions:r}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,dependencyValuesByKey:n}){let r=[],a={};for(let i in e.directions){let s=n[i].controlChild;s&&1===s.length?r.push({setDependency:t[i].controlChild,desiredValue:e.directions[i],childIndex:0,variableIndex:0}):a[i]=e.directions[i]}return Object.keys(a).length>0&&r.push({setEssentialValue:"directions",value:a}),{success:!0,instructions:r}}},e.hiddenControls={isArray:!0,entryPrefixes:["hiddenControl"],hasEssential:!0,defaultValueByArrayKey:()=>!1,stateVariablesDeterminingDependencies:["pointIndMap"],returnArraySizeDependencies:()=>({nControls:{dependencyType:"stateVariable",variableName:"nControls"}}),returnArraySize:({dependencyValues:e})=>[e.nControls],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=t.pointIndMap[r];void 0!==e&&(n[r]={controlChild:{dependencyType:"child",childGroups:["controlVectors"],variableNames:["hide"],childIndices:[e]}})}return{dependenciesByKey:n}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={},r={};for(let a of t){let t=e[a].controlChild;t&&1===t.length?n[a]=t[0].stateValues.hide:r[a]=!0}return{setValue:{hiddenControls:n},useEssentialOrDefaultValue:{hiddenControls:r}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,dependencyValuesByKey:n}){let r=[],a={};for(let i in e.hiddenControls){let s=n[i].controlChild;s&&1===s.length?r.push({setDependency:t[i].controlChild,desiredValue:e.hiddenControls[i],childIndex:0,variableIndex:0}):a[i]=e.hiddenControls[i]}return Object.keys(a).length>0&&r.push({setEssentialValue:"hiddenControls",value:a}),{success:!0,instructions:r}}},e.nDimensions={returnDependencies:()=>({nParentDimensions:{dependencyType:"parentStateVariable",variableName:"nDimensions"}}),definition:function({dependencyValues:e}){let t=e.nParentDimensions;return Number.isInteger(t)&&t>=0||(t=0),{setValue:{nDimensions:t},checkForActualChange:{nDimensions:!0}}}},e.essentialSymmetricControls={isArray:!0,entryPrefixes:["essentialSymmetricControl"],nDimensions:2,hasEssential:!0,defaultValueByArrayKey:()=>me$3.fromAst(1),returnArraySizeDependencies:()=>({nControls:{dependencyType:"stateVariable",variableName:"nControls"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nControls,e.nDimensions],returnArrayDependenciesByKey:()=>({}),arrayDefinitionByKey({arrayKeys:e}){let t={};for(let n of e)n.split(",").map((e=>Number(e))),t[n]=!0;return{useEssentialOrDefaultValue:{essentialSymmetricControls:t}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e}){let t=[],n={};for(let t in e.essentialSymmetricControls)n[t]=e.essentialSymmetricControls[t];return Object.keys(n).length>0&&t.push({setEssentialValue:"essentialSymmetricControls",value:n}),{success:!0,instructions:t}}},e.controls={isArray:!0,entryPrefixes:["control"],nDimensions:3,hasEssential:!0,shadowVariable:!0,defaultValueByArrayKey:()=>me$3.fromAst(1),stateVariablesDeterminingDependencies:["pointIndMap","directions"],returnArraySizeDependencies:()=>({nControls:{dependencyType:"stateVariable",variableName:"nControls"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nControls,2,e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=r.split(",").map((e=>Number(e))),a=e.map((e=>e+1));n[r]={direction:{dependencyType:"stateVariable",variableName:"direction"+a[0]}};let i=t.directions[e[0]];if("none"!==i&&(0===e[1]||1===e[1])){let s=t.pointIndMap[e[0]];void 0!==s&&("symmetric"===i||"previous"===i&&0===e[1]||"next"===i&&1===e[1]?n[r].controlChild={dependencyType:"child",childGroups:["controlVectors"],variableNames:["vectorX1_"+a[2]],childIndices:[s]}:"both"===i&&(n[r].controlChild={dependencyType:"child",childGroups:["controlVectors"],variableNames:["vectorX"+a[1]+"_"+a[2]],childIndices:[s]})),"symmetric"===i&&(n[r].essentialSymmetricControl={dependencyType:"stateVariable",variableName:"essentialSymmetricControl"+a[0]+"_"+a[2]})}}return{dependenciesByKey:n}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t,componentName:n}){let r={},a={};for(let n of t){let t=n.split(",").map((e=>Number(e))),i=t.map((e=>e+1)),s=e[n].direction;if(0===t[1])if("none"===s||"next"===s)r[n]=null;else{let t=e[n].controlChild,o=!0;if(t&&1===t.length){let e=t[0].stateValues["vectorX1_"+i[2]];e&&(o=!1,e=e.evaluate_to_constant(),Number.isFinite(e)||(e=NaN),r[n]=me$3.fromAst(e))}o&&("symmetric"===s?r[n]=e[n].essentialSymmetricControl:a[n]=!0)}else if(1===t[1])if("none"===s||"previous"===s)r[n]=null;else{let t=e[n].controlChild,o=!0;if(t&&1===t.length)if("both"===s){let e=t[0].stateValues["vectorX2_"+i[2]];e&&(o=!1,e=e.evaluate_to_constant(),Number.isFinite(e)||(e=NaN),r[n]=me$3.fromAst(e))}else{let e=t[0].stateValues["vectorX1_"+i[2]];e&&(o=!1,e=e.evaluate_to_constant(),Number.isFinite(e)||(e=NaN),r[n]="symmetric"===s?me$3.fromAst(-e):me$3.fromAst(e))}o&&("symmetric"===s?e[n].essentialSymmetricControl&&(r[n]=me$3.fromAst(-e[n].essentialSymmetricControl.tree)):a[n]=!0)}}return{setValue:{controls:r},useEssentialOrDefaultValue:{controls:a}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,dependencyValuesByKey:n}){let r=[],a={};for(let i in e.controls){let s=i.split(",").map((e=>Number(e))),o=s.map((e=>e+1)),l=n[i].direction;if(l)if(0===s[1]){if("none"!==l&&"next"!==l){let s=n[i].controlChild,u=!0;if(s&&1===s.length){s[0].stateValues["vectorX1_"+o[2]]&&(u=!1,r.push({setDependency:t[i].controlChild,desiredValue:e.controls[i],childIndex:0,variableIndex:0}))}if(u){let n=e.controls[i].evaluate_to_constant();Number.isFinite(n)||(n=NaN),n=me$3.fromAst(n),"symmetric"===l?r.push({setDependency:t[i].essentialSymmetricControl,desiredValue:n}):a[i]=n}}}else if(1===s[1]&&"none"!==l&&"previous"!==l){let s,u=n[i].controlChild,c=!0;if(u&&1===u.length)if("both"===l){u[0].stateValues["vectorX2_"+o[2]]&&(c=!1)}else{u[0].stateValues["vectorX1_"+o[2]]&&(c=!1)}s="symmetric"===l?me$3.fromAst(["-",e.controls[i].tree]):e.controls[i],c?(s=s.evaluate_to_constant(),Number.isFinite(s)||(s=NaN),s=me$3.fromAst(s),"symmetric"===l?r.push({setDependency:t[i].essentialSymmetricControl,desiredValue:s}):a[i]=s):r.push({setDependency:t[i].controlChild,desiredValue:s,childIndex:0,variableIndex:0})}}return Object.keys(a).length>0&&r.push({setEssentialValue:"controls",value:a}),{success:!0,instructions:r}}},e}}class VectorListComponent extends BaseComponent{static componentType="_vectorListComponent";static rendererType="containerInline";static renderChildren=!0;static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e}){let t=breakEmbeddedStringsIntoParensPieces({componentList:e});return!0!==t.success?{success:!1}:{success:!0,newChildren:t.pieces.map((function(e){return e.length>1||"string"==typeof e[0]?{componentType:"vector",children:e}:e[0]}))}}}),e}static returnChildGroups(){return[{group:"vectors",componentTypes:["vector"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nVectors={returnDependencies:()=>({vectorChildren:{dependencyType:"child",childGroups:["vectors"],skipComponentNames:!0}}),definition:({dependencyValues:e})=>({setValue:{nVectors:e.vectorChildren.length},checkForActualChange:{nVectors:!0}})},e.nDimensions={returnDependencies:()=>({vectorChildren:{dependencyType:"child",childGroups:["vectors"],variableNames:["nDimensions"],skipPlaceholders:!0}}),definition:function({dependencyValues:e}){let t;if(0===e.vectorChildren.length)t=2;else{t=1;for(let n of e.vectorChildren)Number.isFinite(n.stateValues.nDimensions)&&(t=Math.max(t,n.stateValues.nDimensions))}return{setValue:{nDimensions:t},checkForActualChange:{nDimensions:!0}}}},e.vectors={isArray:!0,nDimensions:2,entryPrefixes:["vectorX","vector"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("vectorX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("vectors"===t)return 1===e.length?"vector"+e[0]:`vectorX${e[0]}_${e[1]}`;if("vector"===t.slice(0,6)){let n=Number(t.slice(6));if(Number.isInteger(n)&&n>0)return`vectorX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nVectors:{dependencyType:"stateVariable",variableName:"nVectors"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nVectors,e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let[e,r]=n.split(",");t[n]={vectorChild:{dependencyType:"child",childGroups:["vectors"],variableNames:["x"+(Number(r)+1)],childIndices:[e]}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=r.split(",")[1],a=e[r].vectorChild[0];a&&(n[r]=a.stateValues["x"+(Number(t)+1)])}return{setValue:{vectors:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t}){let n=[];for(let r in e.vectors)n.push({setDependency:t[r].vectorChild,desiredValue:e.vectors[r],childIndex:0,variableIndex:0});return{success:!0,instructions:n}}},e}}class ControlVectors extends VectorListComponent{static componentType="controlVectors";static createAttributesObject(){let e=super.createAttributesObject();return e.direction={createComponentOfType:"text",createStateVariable:"direction",defaultValue:"symmetric",public:!0,toLowerCase:!0,validValues:["symmetric","previous","next","both","none"]},e.pointNumber={createComponentOfType:"number",createStateVariable:"pointNumber",defaultValue:null,public:!0},e}}class PointListComponent extends BaseComponent{static componentType="_pointListComponent";static rendererType="containerInline";static renderChildren=!0;static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e}){let t=breakEmbeddedStringsIntoParensPieces({componentList:e});return!0!==t.success?{success:!1}:{success:!0,newChildren:t.pieces.map((function(e){return e.length>1||"string"==typeof e[0]?{componentType:"point",children:e}:e[0]}))}}}),e}static returnChildGroups(){return[{group:"points",componentTypes:["point"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nPoints={returnDependencies:()=>({pointChildren:{dependencyType:"child",childGroups:["points"],skipComponentNames:!0}}),definition:function({dependencyValues:e}){return{setValue:{nPoints:e.pointChildren.length},checkForActualChange:{nPoints:!0}}}},e.nDimensions={returnDependencies:()=>({pointChildren:{dependencyType:"child",childGroups:["points"],variableNames:["nDimensions"],skipPlaceholders:!0}}),definition:function({dependencyValues:e}){let t;if(0===e.pointChildren.length)t=2;else{t=1;for(let n of e.pointChildren)Number.isFinite(n.stateValues.nDimensions)&&(t=Math.max(t,n.stateValues.nDimensions))}return{setValue:{nDimensions:t},checkForActualChange:{nDimensions:!0}}}},e.points={isArray:!0,nDimensions:2,entryPrefixes:["pointX","point"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("pointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("points"===t)return 1===e.length?"point"+e[0]:`pointX${e[0]}_${e[1]}`;if("point"===t.slice(0,5)){let n=Number(t.slice(5));if(Number.isInteger(n)&&n>0)return`pointX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nPoints:{dependencyType:"stateVariable",variableName:"nPoints"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nPoints,e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let[e,r]=n.split(",");t[n]={pointChild:{dependencyType:"child",childGroups:["points"],variableNames:["x"+(Number(r)+1)],childIndices:[e]}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=r.split(",")[1],a=e[r].pointChild[0];a&&(n[r]=a.stateValues["x"+(Number(t)+1)])}return{setValue:{points:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t}){let n=[];for(let r in e.points)n.push({setDependency:t[r].pointChild,desiredValue:e.points[r],childIndex:0,variableIndex:0});return{success:!0,instructions:n}}},e}}class IntervalListComponent extends BaseComponent{static componentType="_intervalListComponent";static rendererType="containerInline";static renderChildren=!0;static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e}){let t=breakEmbeddedStringsIntoIntervalPieces({componentList:e});return!0!==t.success?{success:!1}:{success:!0,newChildren:t.pieces.map((function(e){return e.length>1||"string"==typeof e[0]?{componentType:"interval",children:e}:e[0]}))}}}),e}static returnChildGroups(){return[{group:"intervals",componentTypes:["interval"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nIntervals={returnDependencies:()=>({intervalChildren:{dependencyType:"child",childGroups:["intervals"],skipComponentNames:!0}}),definition:function({dependencyValues:e}){return{setValue:{nIntervals:e.intervalChildren.length},checkForActualChange:{nIntervals:!0}}}},e.intervals={isArray:!0,nDimensions:1,entryPrefixes:["interval"],returnArraySizeDependencies:()=>({nIntervals:{dependencyType:"stateVariable",variableName:"nIntervals"}}),returnArraySize:({dependencyValues:e})=>[e.nIntervals],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={intervalChild:{dependencyType:"child",childGroups:["intervals"],variableNames:["value"],childIndices:[n]}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].intervalChild[0];t&&(n[r]=t.stateValues.value)}return{setValue:{intervals:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t}){let n=[];for(let r in e.intervals)n.push({setDependency:t[r].intervalChild,desiredValue:e.intervals[r],childIndex:0,variableIndex:0});return{success:!0,instructions:n}}},e}}function breakEmbeddedStringsIntoIntervalPieces({componentList:e}){let t=0,n=[],r=[];for(let a of e){if("string"!=typeof a){if(0===t)return{success:!1};r.push(a);continue}let e=a.trim(),i=0;for(let a=0;ai){let t=a+1,n=e.substring(i,t).trim();n.length>0&&r.push(n)}n.push(r),r=[],i=a+1}t--}else if(0===t&&!s.match(/\s/))return{success:!1}}if(e.length>i){let t=e.substring(i,e.length).trim();r.push(t)}}return 0!==t||r.length>0?{success:!1}:{success:!0,pieces:n}}class LineListComponent extends BaseComponent{static componentType="_lineListComponent";static rendererType="containerInline";static renderChildren=!0;static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e}){let t=e.reduce((function(e,t){return"string"==typeof t?[...e,...t.split(/\s+/).filter((e=>e)).map((e=>({componentType:"line",children:[e]})))]:[...e,t]}),[]);return{success:!0,newChildren:t}}}),e}static returnChildGroups(){return[{group:"lines",componentTypes:["line"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nLines={returnDependencies:()=>({lineChildren:{dependencyType:"child",childGroups:["lines"],skipComponentNames:!0}}),definition:function({dependencyValues:e}){return{setValue:{nLines:e.lineChildren.length},checkForActualChange:{nLines:!0}}}},e.lineNames={isArray:!0,entryPrefixes:["lineName"],returnArraySizeDependencies:()=>({nLines:{dependencyType:"stateVariable",variableName:"nLines"}}),returnArraySize:({dependencyValues:e})=>[e.nLines],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={lineChild:{dependencyType:"child",childGroups:["lines"],childIndices:[n]}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].lineChild[0];t&&(n[r]=t.componentName)}return{setValue:{lineNames:n}}}},e}}class AngleListComponent extends BaseComponent{static componentType="_angleListComponent";static createAttributesObject(){let e=super.createAttributesObject();return e.hide={default:!0},e}static returnChildLogic(e){let t=super.returnChildLogic(e),n=t.newLeaf({name:"AtLeastZeroAngles",componentType:"angle",comparison:"atLeast",number:0}),r=breakStringsAndOthersIntoComponentsByStringCommas(),a=t.newLeaf({name:"AtLeastOneString",componentType:"string",comparison:"atLeast",number:1}),i=t.newLeaf({name:"AtLeastOneMath",componentType:"math",comparison:"atLeast",number:1}),s=t.newOperator({name:"StringsAndMaths",operator:"or",propositions:[a,i],requireConsecutive:!0,isSugar:!0,replacementFunction:r});return t.newOperator({name:"AnglesXorSugar",operator:"xor",propositions:[n,s],setAsBase:!0}),t}updateState(e={}){if(e.init&&(this._state.angles={trackChanges:!0}),super.updateState(e),!this.childLogicSatisfied)return this.unresolvedState.angles=!0,void(this.unresolvedState.nAngles=!0);if(this.currentTracker.trackChanges.childrenChanged(this.componentName)){delete this.unresolvedState.angles,delete this.unresolvedState.nAngles;let e=this.childLogic.returnMatches("AtLeastZeroAngles");this.state.nAngles=e.length,this.state.angles=e.map((e=>this.activeChildren[e]))}}initializeRenderer(){void 0===this.renderer&&(this.renderer=new this.availableRenderers.container({key:this.componentName}))}updateChildrenWhoRender(){this.childrenWhoRender=this.state.angles.map((e=>e.componentName))}}class Vector extends GraphicalComponent{constructor(e){super(e),Object.assign(this.actions,{moveVector:this.moveVector.bind(this),vectorClicked:this.vectorClicked.bind(this),mouseDownOnVector:this.mouseDownOnVector.bind(this)})}static componentType="vector";static primaryStateVariableForDefinition="displacementShadow";static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.headDraggable={createComponentOfType:"boolean"},e.tailDraggable={createComponentOfType:"boolean"},e.x={createComponentOfType:"math"},e.y={createComponentOfType:"math"},e.z={createComponentOfType:"math"},e.xs={createComponentOfType:"mathList"},e.displacement={createComponentOfType:"vector"},e.head={createComponentOfType:"point"},e.tail={createComponentOfType:"point"},e.displayDigits={createComponentOfType:"integer",createStateVariable:"displayDigits",defaultValue:10,public:!0},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.padZeros={createComponentOfType:"boolean",createStateVariable:"padZeros",defaultValue:!1,public:!0},e.displayWithAngleBrackets={createComponentOfType:"boolean",createStateVariable:"displayWithAngleBrackets",defaultValue:!1,public:!0},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e,componentInfoObjects:t}){let n=returnBreakStringsSugarFunction({childrenToComponentFunction:e=>({componentType:"math",children:e}),mustStripOffOuterParentheses:!0}),r=e.map((e=>typeof e)),a=r.indexOf("string"),i=r.lastIndexOf("string");if(-1===a){let n=t.componentIsSpecifiedType,r=e.filter((e=>!(n(e,"point")||n(e,"vector")||n(e,"label"))));if(1===r.length){let t=r[0],n=e.indexOf(t);return{success:!0,newAttributes:{displacement:{component:{componentType:"math",children:r}}},newChildren:[...e.slice(0,n),...e.slice(n+1)]}}return{success:!1}}let s=[...e.slice(0,a),...e.slice(i+1)],o=n({matchedChildren:e=e.slice(a,i+1)});return o.success||1!==e.length?o.success?{success:!0,newAttributes:{xs:{component:{componentType:"mathList",children:o.newChildren,skipSugar:!0}}},newChildren:s}:{success:!1}:{success:!0,newAttributes:{x:{component:{componentType:"math",children:e}}},newChildren:s}}}),e}static returnChildGroups(){let e=super.returnChildGroups();return e.push({group:"points",componentTypes:["point"]},{group:"vectors",componentTypes:["vector"]}),e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){let t=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(t&&(t+=" "),t+=e.selectedStyle.lineStyleWord),t&&(t+=" "),t+=e.selectedStyle.lineColorWord,{setValue:{styleDescription:t}}}},e.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({styleDescription:{dependencyType:"stateVariable",variableName:"styleDescription"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescriptionWithNoun:e.styleDescription+" vector"}}}},e.tailDraggable={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},hasEssential:!0,forRenderer:!0,returnDependencies:()=>({tailDraggableAttr:{dependencyType:"attributeComponent",attributeName:"tailDraggable",variableNames:["value"]},draggable:{dependencyType:"stateVariable",variableName:"draggable"}}),definition:({dependencyValues:e})=>e.tailDraggableAttr?{setValue:{tailDraggable:e.tailDraggableAttr.stateValues.value}}:{useEssentialOrDefaultValue:{tailDraggable:{defaultValue:e.draggable}}}},e.headDraggable={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},hasEssential:!0,forRenderer:!0,returnDependencies:()=>({headDraggableAttr:{dependencyType:"attributeComponent",attributeName:"headDraggable",variableNames:["value"]},draggable:{dependencyType:"stateVariable",variableName:"draggable"}}),definition:({dependencyValues:e})=>e.headDraggableAttr?{setValue:{headDraggable:e.headDraggableAttr.stateValues.value}}:{useEssentialOrDefaultValue:{headDraggable:{defaultValue:e.draggable}}}},e.displacementShadow={defaultValue:null,hasEssential:!0,essentialVarName:"displacement",set:convertValueToMathExpression,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{displacementShadow:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"displacementShadow",value:convertValueToMathExpression(e.displacementShadow)}]}}},e.headShadow={defaultValue:null,hasEssential:!0,essentialVarName:"head",set:convertValueToMathExpression,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{headShadow:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"headShadow",value:convertValueToMathExpression(e.headShadow)}]}}},e.tailShadow={defaultValue:null,hasEssential:!0,essentialVarName:"tail",set:convertValueToMathExpression,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{tailShadow:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"tailShadow",value:convertValueToMathExpression(e.tailShadow)}]}}},e.sourceOfDisplacement={returnDependencies:()=>({xAttr:{dependencyType:"attributeComponent",attributeName:"x"},yAttr:{dependencyType:"attributeComponent",attributeName:"y"},zAttr:{dependencyType:"attributeComponent",attributeName:"z"},xsAttr:{dependencyType:"attributeComponent",attributeName:"xs"},displacementAttr:{dependencyType:"attributeComponent",attributeName:"displacement"},pointChild:{dependencyType:"child",childGroups:["points"]},vectorChild:{dependencyType:"child",childGroups:["vectors"]}}),definition({dependencyValues:e}){let t=null;return e.vectorChild.length>0?t="vectorChild":e.pointChild.length>0?t="pointChild":null!==e.displacementAttr?t="displacementAttr":null!==e.xsAttr?t="xsAttr":null===e.xAttr&&null===e.yAttr&&null===e.zAttr||(t="componentAttrs"),{setValue:{sourceOfDisplacement:t}}}},e.basedOnHead={returnDependencies:()=>({headAttr:{dependencyType:"attributeComponent",attributeName:"head"},headShadow:{dependencyType:"stateVariable",variableName:"headShadow"},tailAttr:{dependencyType:"attributeComponent",attributeName:"tail"},sourceOfDisplacement:{dependencyType:"stateVariable",variableName:"sourceOfDisplacement"}}),definition:function({dependencyValues:e}){return null!==e.tailAttr&&null!==e.sourceOfDisplacement?(null!==e.headAttr&&console.warn("Vector is prescribed by head, tail, and displacement. Ignoring specified head."),{setValue:{basedOnHead:!1},checkForActualChange:{basedOnHead:!0}}):null!==e.headAttr?{setValue:{basedOnHead:!0},checkForActualChange:{basedOnHead:!0}}:{setValue:{basedOnHead:null!==e.headShadow},checkForActualChange:{basedOnHead:!0}}}},e.basedOnTail={returnDependencies:()=>({tailAttr:{dependencyType:"attributeComponent",attributeName:"tail"},tailShadow:{dependencyType:"stateVariable",variableName:"tailShadow"}}),definition:function({dependencyValues:e}){return null!==e.tailAttr?{setValue:{basedOnTail:!0},checkForActualChange:{basedOnTail:!0}}:{setValue:{basedOnTail:null!==e.tailShadow},checkForActualChange:{basedOnTail:!0}}}},e.basedOnDisplacement={returnDependencies:()=>({sourceOfDisplacement:{dependencyType:"stateVariable",variableName:"sourceOfDisplacement"},displacementShadow:{dependencyType:"stateVariable",variableName:"displacementShadow"}}),definition:function({dependencyValues:e}){return null!==e.sourceOfDisplacement?{setValue:{basedOnDisplacement:!0},checkForActualChange:{basedOnDisplacement:!0}}:{setValue:{basedOnDisplacement:null!==e.displacementShadow},checkForActualChange:{basedOnDisplacement:!0}}}},e.nDimDisplacement={stateVariablesDeterminingDependencies:["basedOnDisplacement","basedOnHead","basedOnTail"],returnDependencies({stateValues:e}){let t={basedOnHead:{dependencyType:"stateVariable",variableName:"basedOnHead"},basedOnTail:{dependencyType:"stateVariable",variableName:"basedOnTail"},basedOnDisplacement:{dependencyType:"stateVariable",variableName:"basedOnDisplacement"},sourceOfDisplacement:{dependencyType:"stateVariable",variableName:"sourceOfDisplacement"},displacementShadow:{dependencyType:"stateVariable",variableName:"displacementShadow"},displacementAttr:{dependencyType:"attributeComponent",attributeName:"displacement",variableNames:["nDimensions"]},vectorChild:{dependencyType:"child",childGroups:["vectors"],variableNames:["nDimensions"]},pointChild:{dependencyType:"child",childGroups:["points"],variableNames:["nDimensions"]},xAttr:{dependencyType:"attributeComponent",attributeName:"x"},yAttr:{dependencyType:"attributeComponent",attributeName:"y"},zAttr:{dependencyType:"attributeComponent",attributeName:"z"},xsAttr:{dependencyType:"attributeComponent",attributeName:"xs",variableNames:["nComponents"]}};return e.basedOnDisplacement||(e.basedOnHead&&(t.nDimHead={dependencyType:"stateVariable",variableName:"nDimHead"}),e.basedOnTail&&(t.nDimTail={dependencyType:"stateVariable",variableName:"nDimTail"})),t},definition:function({dependencyValues:e}){let t;if(e.basedOnDisplacement)switch(e.sourceOfDisplacement){case"vectorChild":t=e.vectorChild[0].stateValues.nDimensions;break;case"pointChild":t=e.pointChild[0].stateValues.nDimensions;break;case"displacementAttr":t=e.displacementAttr.stateValues.nDimensions;break;case"xsAttr":t=e.xsAttr.stateValues.nComponents;break;case"componentAttrs":t=null!==e.zAttr?3:null!==e.yAttr?2:1;break;default:let n=e.displacementShadow.tree;t=Array.isArray(n)&&vectorOperators.includes(n[0])?n.length-1:1}else t=e.basedOnHead?e.basedOnTail?e.nDimHead===e.nDimTail?e.nDimHead:NaN:e.nDimHead:e.basedOnTail?e.nDimTail:2;return{setValue:{nDimDisplacement:t},checkForActualChange:{nDimDisplacement:!0}}}},e.nDimHead={stateVariablesDeterminingDependencies:["basedOnDisplacement","basedOnHead","basedOnTail"],returnDependencies({stateValues:e}){let t={basedOnHead:{dependencyType:"stateVariable",variableName:"basedOnHead"},basedOnTail:{dependencyType:"stateVariable",variableName:"basedOnTail"},basedOnDisplacement:{dependencyType:"stateVariable",variableName:"basedOnDisplacement"},headShadow:{dependencyType:"stateVariable",variableName:"headShadow"},headAttr:{dependencyType:"attributeComponent",attributeName:"head",variableNames:["nDimensions"]}};return e.basedOnHead||(e.basedOnTail&&(t.nDimTail={dependencyType:"stateVariable",variableName:"nDimTail"}),e.basedOnDisplacement&&(t.nDimDisplacement={dependencyType:"stateVariable",variableName:"nDimDisplacement"})),t},definition:function({dependencyValues:e}){let t;if(e.basedOnHead){if(null!==e.headAttr)t=e.headAttr.stateValues.nDimensions;else if(e.headShadow){let n=e.headShadow.tree;t=Array.isArray(n)&&vectorOperators.includes(n[0])?n.length-1:2}}else t=e.basedOnDisplacement?e.basedOnTail?e.nDimDisplacement===e.nDimTail?e.nDimDisplacement:NaN:e.nDimDisplacement:e.basedOnTail?e.nDimTail:2;return{setValue:{nDimHead:t},checkForActualChange:{nDimHead:!0}}}},e.nDimTail={stateVariablesDeterminingDependencies:["basedOnDisplacement","basedOnHead","basedOnTail"],returnDependencies({stateValues:e}){let t={basedOnHead:{dependencyType:"stateVariable",variableName:"basedOnHead"},basedOnTail:{dependencyType:"stateVariable",variableName:"basedOnTail"},basedOnDisplacement:{dependencyType:"stateVariable",variableName:"basedOnDisplacement"},tailShadow:{dependencyType:"stateVariable",variableName:"tailShadow"},tailAttr:{dependencyType:"attributeComponent",attributeName:"tail",variableNames:["nDimensions"]}};return e.basedOnTail||(e.basedOnHead&&(t.nDimHead={dependencyType:"stateVariable",variableName:"nDimHead"}),e.basedOnDisplacement&&(t.nDimDisplacement={dependencyType:"stateVariable",variableName:"nDimDisplacement"})),t},definition:function({dependencyValues:e}){let t;if(e.basedOnTail){if(null!==e.tailAttr)t=e.tailAttr.stateValues.nDimensions;else if(e.tailShadow){let n=e.tailShadow.tree;t=Array.isArray(n)&&vectorOperators.includes(n[0])?n.length-1:2}}else t=e.basedOnDisplacement?e.basedOnHead?e.nDimDisplacement===e.nDimHead?e.nDimDisplacement:NaN:e.nDimDisplacement:e.basedOnHead?e.nDimHead:2;return{setValue:{nDimTail:t},checkForActualChange:{nDimTail:!0}}}},e.nDimensions={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({basedOnHead:{dependencyType:"stateVariable",variableName:"basedOnHead"},basedOnTail:{dependencyType:"stateVariable",variableName:"basedOnTail"},basedOnDisplacement:{dependencyType:"stateVariable",variableName:"basedOnDisplacement"},nDimDisplacement:{dependencyType:"stateVariable",variableName:"nDimDisplacement"},nDimHead:{dependencyType:"stateVariable",variableName:"nDimHead"},nDimTail:{dependencyType:"stateVariable",variableName:"nDimTail"}}),definition:function({dependencyValues:e}){let t;if(e.basedOnDisplacement){if(e.basedOnTail){if(e.nDimDisplacement!==e.nDimTail)return console.warn("nDimensions mismatch in vector"),{setValue:{nDimensions:NaN}}}else if(e.basedOnHead&&e.nDimDisplacement!==e.nDimHead)return console.warn("nDimensions mismatch in vector"),{setValue:{nDimensions:NaN}};t=e.nDimDisplacement}else if(e.basedOnTail){if(e.basedOnHead&&e.nDimTail!==e.nDimHead)return console.warn("nDimensions mismatch in vector"),{setValue:{nDimensions:NaN}};t=e.nDimTail}else t=e.basedOnHead?e.nDimHead:2;return{setValue:{nDimensions:t},checkForActualChange:{nDimensions:!0}}}},e.displacement={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros","displayWithAngleBrackets"],returnWrappingComponents:e=>"x"===e?[]:[["vector",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,entryPrefixes:["x"],hasEssential:!0,essentialVarName:"displacement2",set:convertValueToMathExpression,stateVariablesDeterminingDependencies:["basedOnDisplacement","basedOnHead","sourceOfDisplacement"],returnArraySizeDependencies:()=>({nDimDisplacement:{dependencyType:"stateVariable",variableName:"nDimDisplacement"}}),returnArraySize:({dependencyValues:e})=>[e.nDimDisplacement],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=Number(r)+1;n[r]={xsAttr:{dependencyType:"attributeComponent",attributeName:"xs",variableNames:["math"+e]},displacementAttr:{dependencyType:"attributeComponent",attributeName:"displacement",variableNames:["x"+e]},pointChild:{dependencyType:"child",childGroups:["points"],variableNames:["x"+e]},vectorChild:{dependencyType:"child",childGroups:["vectors"],variableNames:["x"+e]}},"0"===r?n[r].componentAttr={dependencyType:"attributeComponent",attributeName:"x",variableNames:["value"]}:"1"===r?n[r].componentAttr={dependencyType:"attributeComponent",attributeName:"y",variableNames:["value"]}:"2"===r&&(n[r].componentAttr={dependencyType:"attributeComponent",attributeName:"z",variableNames:["value"]}),!t.basedOnDisplacement&&t.basedOnHead&&(n[r].tailX={dependencyType:"stateVariable",variableName:"tailX"+e},n[r].headX={dependencyType:"stateVariable",variableName:"headX"+e})}return{globalDependencies:{basedOnHead:{dependencyType:"stateVariable",variableName:"basedOnHead"},basedOnTail:{dependencyType:"stateVariable",variableName:"basedOnTail"},basedOnDisplacement:{dependencyType:"stateVariable",variableName:"basedOnDisplacement"},displacementShadow:{dependencyType:"stateVariable",variableName:"displacementShadow"},sourceOfDisplacement:{dependencyType:"stateVariable",variableName:"sourceOfDisplacement"}},dependenciesByKey:n}},arrayDefinitionByKey:function({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={},a={};for(let i of n){let n=Number(i)+1;if(e.basedOnDisplacement)switch(e.sourceOfDisplacement){case"vectorChild":r[i]=t[i].vectorChild[0].stateValues["x"+n];break;case"pointChild":r[i]=t[i].pointChild[0].stateValues["x"+n];break;case"displacementAttr":r[i]=t[i].displacementAttr.stateValues["x"+n];break;case"xsAttr":r[i]=t[i].xsAttr.stateValues["math"+n].simplify();break;case"componentAttrs":let s=t[i].componentAttr;null===s?a[i]={defaultValue:me$3.fromAst(0)}:r[i]=s.stateValues.value.simplify();break;default:let o=e.displacementShadow.tree;Array.isArray(o)&&vectorOperators.includes(o[0])?r[i]=e.displacementShadow.get_component(Number(i)):r[i]=e.displacementShadow}else e.basedOnHead?r[i]=t[i].headX.subtract(t[i].tailX).simplify():a[i]={defaultValue:me$3.fromAst("0"===i?1:0)}}let i={};return Object.keys(r).length>0&&(i.setValue={displacement:r}),Object.keys(a).length>0&&(i.useEssentialOrDefaultValue={displacement:a}),i},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i=[],s=!1;for(let a in e.displacement)if(t.basedOnDisplacement)switch(t.sourceOfDisplacement){case"vectorChild":i.push({setDependency:r[a].vectorChild,desiredValue:e.displacement[a],childIndex:0,variableIndex:0});break;case"pointChild":i.push({setDependency:r[a].pointChild,desiredValue:e.displacement[a],childIndex:0,variableIndex:0});break;case"displacementAttr":i.push({setDependency:r[a].displacementAttr,desiredValue:e.displacement[a],variableIndex:0});break;case"xsAttr":i.push({setDependency:r[a].xsAttr,desiredValue:e.displacement[a],variableIndex:0});break;case"componentAttrs":null===n[a].componentAttr?i.push({setEssentialValue:"displacement",value:{[a]:convertValueToMathExpression(e.displacement[a])}}):i.push({setDependency:r[a].componentAttr,desiredValue:e.displacement[a],variableIndex:0});break;default:s=!0}else t.basedOnHead?i.push({setDependency:r[a].headX,desiredValue:n[a].tailX.add(e.displacement[a]).simplify()}):i.push({setEssentialValue:"displacement",value:{[a]:convertValueToMathExpression(e.displacement[a])}});if(s)if(a[0]>1){let t=["vector"];for(let n in e.displacement)t[Number(n)+1]=e.displacement[n].tree;t.length=a[0]+1,i.push({setDependency:"displacementShadow",desiredValue:me$3.fromAst(t)})}else 1===a[0]&&"0"in e.displacement&&i.push({setDependency:"displacementShadow",desiredValue:e.displacement[0]});return{success:!0,instructions:i}}},e.x={isAlias:!0,targetVariableName:"x1"},e.y={isAlias:!0,targetVariableName:"x2"},e.z={isAlias:!0,targetVariableName:"x3"},e.head={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"],returnWrappingComponents:e=>"headX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,entryPrefixes:["headX"],set:convertValueToMathExpression,stateVariablesDeterminingDependencies:["basedOnHead"],returnArraySizeDependencies:()=>({nDimHead:{dependencyType:"stateVariable",variableName:"nDimHead"}}),returnArraySize:({dependencyValues:e})=>[e.nDimHead],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=Number(r)+1;n[r]={headAttr:{dependencyType:"attributeComponent",attributeName:"head",variableNames:["x"+e]}},t.basedOnHead||(n[r].tailX={dependencyType:"stateVariable",variableName:"tailX"+e},n[r].x={dependencyType:"stateVariable",variableName:"x"+e})}return{globalDependencies:{basedOnDisplacement:{dependencyType:"stateVariable",variableName:"basedOnDisplacement"},basedOnTail:{dependencyType:"stateVariable",variableName:"basedOnTail"},basedOnHead:{dependencyType:"stateVariable",variableName:"basedOnHead"},headShadow:{dependencyType:"stateVariable",variableName:"headShadow"}},dependenciesByKey:n}},arrayDefinitionByKey:function({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};for(let a of n){let n=Number(a)+1;e.basedOnHead?null!==t[a].headAttr?r[a]=t[a].headAttr.stateValues["x"+n]:null!==e.headShadow&&(r[a]=e.headShadow.get_component(Number(a))):r[a]=t[a].tailX.add(t[a].x).simplify()}return{setValue:{head:r}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i=[],s=!1;for(let a in e.head)t.basedOnHead?n[a].headAttr&&null!==n[a].headAttr?i.push({setDependency:r[a].headAttr,desiredValue:e.head[a],variableIndex:0}):null!==t.headShadow&&(s=!0):i.push({setDependency:r[a].x,desiredValue:e.head[a].subtract(n[a].tailX).simplify()});if(s)if(a[0]>1){let t=["vector"];for(let n in e.head)t[Number(n)+1]=e.head[n].tree;t.length=a[0]+1,i.push({setDependency:"headShadow",desiredValue:me$3.fromAst(t)})}else 1===a[0]&&"0"in e.head&&i.push({setDependency:"headShadow",desiredValue:e.head[0]});return{success:!0,instructions:i}}},e.tail={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"],returnWrappingComponents:e=>"tailX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,entryPrefixes:["tailX"],hasEssential:!0,defaultValueByArrayKey:()=>me$3.fromAst(0),essentialVarName:"tail2",set:convertValueToMathExpression,stateVariablesDeterminingDependencies:["basedOnTail","basedOnHead","basedOnDisplacement"],returnArraySizeDependencies:()=>({nDimTail:{dependencyType:"stateVariable",variableName:"nDimTail"}}),returnArraySize:({dependencyValues:e})=>[e.nDimTail],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=Number(r)+1;n[r]={tailAttr:{dependencyType:"attributeComponent",attributeName:"tail",variableNames:["x"+e]}},t.basedOnTail||t.basedOnHead&&t.basedOnDisplacement&&(n[r].headX={dependencyType:"stateVariable",variableName:"headX"+e},n[r].x={dependencyType:"stateVariable",variableName:"x"+e})}return{globalDependencies:{basedOnDisplacement:{dependencyType:"stateVariable",variableName:"basedOnDisplacement"},basedOnHead:{dependencyType:"stateVariable",variableName:"basedOnHead"},tailShadow:{dependencyType:"stateVariable",variableName:"tailShadow"}},dependenciesByKey:n}},arrayDefinitionByKey:function({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={},a={};for(let i of n){let n=Number(i)+1;null!==t[i].tailAttr?r[i]=t[i].tailAttr.stateValues["x"+n]:null!==e.tailShadow?r[i]=e.tailShadow.get_component(Number(i)):e.basedOnHead&&e.basedOnDisplacement?r[i]=t[i].headX.subtract(t[i].x).simplify():a[i]=!0}let i={};return Object.keys(r).length>0&&(i.setValue={tail:r}),Object.keys(a).length>0&&(i.useEssentialOrDefaultValue={tail:a}),i},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i=[],s=!1;for(let a in e.tail)n[a].tailAttr&&null!==n[a].tailAttr?i.push({setDependency:r[a].tailAttr,desiredValue:e.tail[a],variableIndex:0}):null!==t.tailShadow?s=!0:t.basedOnHead&&t.basedOnDisplacement?i.push({setDependency:r[a].x,desiredValue:n[a].headX.subtract(e.tail[a]).simplify()}):i.push({setEssentialValue:"tail",value:{[a]:convertValueToMathExpression(e.tail[a])}});if(s)if(a[0]>1){let t=["vector"];for(let n in e.tail)t[Number(n)+1]=e.tail[n].tree;t.length=a[0]+1,i.push({setDependency:"tailShadow",desiredValue:me$3.fromAst(t)})}else 1===a[0]&&"0"in e.tail&&i.push({setDependency:"tailShadow",desiredValue:e.tail[0]});return{success:!0,instructions:i}}},e.magnitude={public:!0,shadowingInstructions:{createComponentOfType:"math"},returnDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},displacement:{dependencyType:"stateVariable",variableName:"displacement"}}),definition({dependencyValues:e}){let t=0,n=!0;for(let r=0;re/i));let s=e.magnitude.evaluate_to_constant();if(!Number.isFinite(s)||s<0)return{success:!1};let o=[];for(let e=0;e({head:{dependencyType:"stateVariable",variableName:"head"},tail:{dependencyType:"stateVariable",variableName:"tail"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),definition:function({dependencyValues:e}){let t,n;if(1===e.nDimensions)e.head[0].evaluate_to_constant(),n=e.tail[0].evaluate_to_constant(),Number.isFinite(n)||(n=NaN);else{t=[],n=[];for(let r=0;r({displacement:{dependencyType:"stateVariable",variableName:"displacement"},displayWithAngleBrackets:{dependencyType:"stateVariable",variableName:"displayWithAngleBrackets"}}),definition({dependencyValues:e}){let t=[];for(let n of e.displacement)n?t.push(n.tree):t.push("_");if(t.length>1){t=[e.displayWithAngleBrackets?"altvector":"vector",...t]}else t=1===t.length?t[0]:"_";return{setValue:{displacementCoords:me$3.fromAst(t)}}},inverseDefinition({desiredStateVariableValues:e}){let t,n=e.displacementCoords.tree;return t=Array.isArray(n)&&vectorOperators.includes(n[0])?n.slice(1).map((e=>me$3.fromAst(e))):[e.displacementCoords],{success:!0,instructions:[{setDependency:"displacement",desiredValue:t}]}}},e.latex={forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({displacementCoords:{dependencyType:"stateVariable",variableName:"displacementCoords"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"}}),definition:function({dependencyValues:e,usedDefault:t}){let n={};return e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(n.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(n.padToDigits=e.displayDigits)),{setValue:{latex:roundForDisplay({value:e.displacementCoords,dependencyValues:e,usedDefault:t}).toLatex(n)}}}},e.nearestPoint={returnDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},numericalEndpoints:{dependencyType:"stateVariable",variableName:"numericalEndpoints"}}),definition({dependencyValues:e}){let t=e.numericalEndpoints[0]?.[0],n=e.numericalEndpoints[0]?.[1],r=e.numericalEndpoints[1]?.[0],a=e.numericalEndpoints[1]?.[1],i=Number.isFinite(t)&&Number.isFinite(n)&&Number.isFinite(r)&&Number.isFinite(a),s=2!==e.nDimensions||!i||r===t&&a===n;return{setValue:{nearestPoint:function({variables:e,scales:i}){if(s)return{};let o=i[0],l=i[1],u=(r-t)/o,c=(a-n)/l,p=u*u+c*c,d=((e.x1-t)/o*u+(e.x2-n)/l*c)/p,m={};return m=d<=0?{x1:t,x2:n}:d>=1?{x1:r,x2:a}:{x1:t+d*u*o,x2:n+d*c*l},void 0!==e.x3&&(m.x3=0),m}}}}},e}static adapters=[{stateVariable:"displacementCoords",componentType:"coords",stateVariablesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]}];async moveVector({tailcoords:e,headcoords:t,transient:n,skippable:r,sourceInformation:a,actionId:i}){if(void 0!==e){if(void 0!==t){if(!await this.stateValues.draggable)return await this.coreFunctions.resolveAction({actionId:i})}else if(!await this.stateValues.tailDraggable)return await this.coreFunctions.resolveAction({actionId:i})}else if(!await this.stateValues.headDraggable)return await this.coreFunctions.resolveAction({actionId:i});let s=[];if(void 0!==e){if(await this.stateValues.basedOnHead&&await this.stateValues.basedOnDisplacement){let n;if(void 0===t){let t=await this.stateValues.numericalEndpoints;n=e.map(((e,n)=>t[1][n]-e))}else n=e.map(((e,n)=>t[n]-e));s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"displacement",value:n.map((e=>me$3.fromAst(e))),sourceInformation:a})}else s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"tail",value:e.map((e=>me$3.fromAst(e))),sourceInformation:a});if(void 0===t&&!await this.stateValues.basedOnHead){let t=await this.stateValues.numericalEndpoints,n=e.map(((e,n)=>t[1][n]-e));s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"displacement",value:n.map((e=>me$3.fromAst(e))),sourceInformation:a})}}if(void 0!==t){if(await this.stateValues.basedOnHead)s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"head",value:t.map((e=>me$3.fromAst(e))),sourceInformation:a});else{null==e&&(e=(await this.stateValues.numericalEndpoints)[0]);let n=e.map(((e,n)=>t[n]-e));s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"displacement",value:n.map((e=>me$3.fromAst(e))),sourceInformation:a})}if(void 0===e&&await this.stateValues.basedOnHead&&await this.stateValues.basedOnDisplacement){let e=await this.stateValues.numericalEndpoints,n=t.map(((t,n)=>t-e[0][n]));s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"displacement",value:n.map((e=>me$3.fromAst(e))),sourceInformation:a})}}return n?await this.coreFunctions.performUpdate({updateInstructions:s,transient:n,skippable:r,actionId:i}):await this.coreFunctions.performUpdate({updateInstructions:s,actionId:i,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{head:t,tail:e}}})}async vectorClicked({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"click",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}async mouseDownOnVector({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"down",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}}class Angle extends GraphicalComponent{static componentType="angle";static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.radius={createComponentOfType:"math",createStateVariable:"radius",defaultValue:me$3.fromAst(1),public:!0},e.chooseReflexAngle={createComponentOfType:"text",createStateVariable:"chooseReflexAngle",defaultValue:"never",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["never","allowed","always"]},e.inDegrees={createComponentOfType:"boolean",createStateVariable:"inDegrees",defaultValue:!1,public:!0,forRenderer:!0},e.radians={createComponentOfType:"math"},e.degrees={createComponentOfType:"math"},e.through={createComponentOfType:"_pointListComponent"},e.betweenLines={createComponentOfType:"_lineListComponent"},e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.padZeros={createComponentOfType:"boolean",createStateVariable:"padZeros",defaultValue:!1,public:!0},e.emphasizeRightAngle={createComponentOfType:"boolean",createStateVariable:"emphasizeRightAngle",defaultValue:!0,public:!0,forRenderer:!0},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e,componentInfoObjects:t}){let n=e.map((e=>t.componentIsSpecifiedType(e,"label"))),r=[],a=[];if(0===n.filter((e=>e)).length)r=e;else{if(n[0]){let t=n.indexOf(!1);-1!==t&&(a.push(...e.slice(0,t)),e=e.slice(t),n=n.slice(t))}let t=n.indexOf(!0);-1===t?r=e:(r=e.slice(0,t),a.push(...e.slice(t)))}return 0===r.length?{success:!1}:{success:!0,newAttributes:{radians:{component:{componentType:"math",children:r}}},newChildren:a}}}),e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.displayDigitsAttr){let n=t.displayDigitsAttr,r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!n&&!r){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({betweenLines:{dependencyType:"attributeComponent",attributeName:"betweenLines"}}),definition({dependencyValues:e}){let t=null;return null!==e.betweenLines&&(t=e.betweenLines.componentName),{setValue:{betweenLinesName:t}}}},e.nPointsSpecified={returnDependencies:()=>({through:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["nPoints"]}}),definition:({dependencyValues:e})=>null!==e.through?{setValue:{nPointsSpecified:e.through.stateValues.nPoints}}:{setValue:{nPointsSpecified:0}}},e.points={isArray:!0,nDimensions:2,entryPrefixes:["pointX","point"],stateVariablesDeterminingDependencies:["betweenLinesName"],returnArraySizeDependencies:()=>({}),returnArraySize:()=>[3,2],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("pointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},returnArrayDependenciesByKey({stateValues:e}){let t={nPointsSpecified:{dependencyType:"stateVariable",variableName:"nPointsSpecified"},throughAttr:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["points"]},radiansAttr:{dependencyType:"attributeComponent",attributeName:"radians",variableNames:["value"]},degreesAttr:{dependencyType:"attributeComponent",attributeName:"degrees",variableNames:["value"]}};return null!==e.betweenLinesName&&(t.lineChildren={dependencyType:"child",parentName:e.betweenLinesName,childGroups:["lines"],variableNames:["points","nDimensions","coeff0","coeffvar1","coeffvar2","nearestPoint"]}),{globalDependencies:t}},arrayDefinitionByKey({globalDependencyValues:e}){if(e.lineChildren){if(e.lineChildren.length>2){console.warn(`Cannot define an angle between ${e.lineChildren.length} line(s)`);let t={};for(let e=0;e<3;e++)for(let n=0;n<2;n++)t[e+","+n]=me$3.fromAst("_");return{setValue:{points:t}}}if(1===e.lineChildren.length){let t=e.lineChildren[0];if(2!==t.stateValues.nDimensions){let e={};for(let t=0;t<3;t++)for(let n=0;n<2;n++)e[t+","+n]=me$3.fromAst("_");return{setValue:{points:e}}}let n=t.stateValues.nearestPoint({variables:{x1:me$3.fromAst(0),x2:me$3.fromAst(0)}}),r=t.stateValues.points[0][0].evaluate_to_constant(),a=t.stateValues.points[0][1].evaluate_to_constant(),i=t.stateValues.points[1][0].evaluate_to_constant(),s=t.stateValues.points[1][1].evaluate_to_constant(),o=Math.atan2(s-a,i-r),l={"0,0":me$3.fromAst(n.x1+Math.cos(o)),"0,1":me$3.fromAst(n.x2+Math.sin(o)),"1,0":me$3.fromAst(n.x1),"1,1":me$3.fromAst(n.x2)},u=null;if(e.radiansAttr){if(u=e.radiansAttr.stateValues.value.evaluate_to_constant(),!Number.isFinite(u)){let e={};return e["2,0"]=me$3.fromAst("_"),e["2,1"]=me$3.fromAst("_"),{setValue:{points:e}}}}else if(e.degreesAttr){let t=e.degreesAttr.stateValues.value.evaluate_to_constant();if(!Number.isFinite(t))return l["2,0"]=me$3.fromAst("_"),l["2,1"]=me$3.fromAst("_"),{setValue:{points:l}};u=t/180*Math.PI}else u=Math.PI/2;let c=o+u;return l["2,0"]=me$3.fromAst(n.x1+Math.cos(c)),l["2,1"]=me$3.fromAst(n.x2+Math.sin(c)),{setValue:{points:l}}}{let t=e.lineChildren[0],n=e.lineChildren[1],r=calculateLineIntersection(t,n);if(void 0===r){let e={};for(let t=0;t<3;t++)for(let n=0;n<2;n++)e[t+","+n]=me$3.fromAst("_");return{setValue:{points:e}}}let a=r,i=t.stateValues.points[0][0].evaluate_to_constant(),s=t.stateValues.points[0][1].evaluate_to_constant(),o=t.stateValues.points[1][0].evaluate_to_constant(),l=t.stateValues.points[1][1].evaluate_to_constant(),u=[me$3.fromAst(a[0].tree+o-i),me$3.fromAst(a[1].tree+l-s)];i=n.stateValues.points[0][0].evaluate_to_constant(),s=n.stateValues.points[0][1].evaluate_to_constant(),o=n.stateValues.points[1][0].evaluate_to_constant(),l=n.stateValues.points[1][1].evaluate_to_constant();let c=[me$3.fromAst(a[0].tree+o-i),me$3.fromAst(a[1].tree+l-s)];return{setValue:{points:{"0,0":u[0],"0,1":u[1],"1,0":a[0],"1,1":a[1],"2,0":c[0],"2,1":c[1]}}}}}let t,n=e.nPointsSpecified;t=e.throughAttr?e.throughAttr.stateValues.points:[];let r={};for(let[e,n]of t.entries())r[e+",0"]=n[0],r[e+",1"]=n[1];if(0===n&&(r["0,0"]=me$3.fromAst(1),r["0,1"]=me$3.fromAst(0)),n<2&&(r["1,0"]=me$3.fromAst(0),r["1,1"]=me$3.fromAst(0)),n<3){let t=null;if(e.radiansAttr){if(t=e.radiansAttr.stateValues.value.evaluate_to_constant(),!Number.isFinite(t))return r["2,0"]=me$3.fromAst("_"),r["2,1"]=me$3.fromAst("_"),{setValue:{points:r}}}else if(e.degreesAttr){let n=e.degreesAttr.stateValues.value.evaluate_to_constant();if(!Number.isFinite(n))return r["2,0"]=me$3.fromAst("_"),r["2,1"]=me$3.fromAst("_"),{setValue:{points:r}};t=n/180*Math.PI}else t=Math.PI/2;let n=r["0,0"].evaluate_to_constant(),a=r["0,1"].evaluate_to_constant(),i=r["1,0"].evaluate_to_constant(),s=r["1,1"].evaluate_to_constant(),o=Math.atan2(a-s,n-i)+t;r["2,0"]=me$3.fromAst(i+Math.cos(o)),r["2,1"]=me$3.fromAst(s+Math.sin(o))}return{setValue:{points:r}}}},e.radians={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},additionalStateVariablesDefined:[{variableName:"swapPointOrder",forRenderer:!0}],returnDependencies:()=>({radians:{dependencyType:"attributeComponent",attributeName:"radians",variableNames:["value"]},degrees:{dependencyType:"attributeComponent",attributeName:"degrees",variableNames:["value"]},points:{dependencyType:"stateVariable",variableName:"points"},chooseReflexAngle:{dependencyType:"stateVariable",variableName:"chooseReflexAngle"}}),definition({dependencyValues:e}){let t=!1;if(null!==e.radians)return{setValue:{radians:e.radians.stateValues.value.simplify(),swapPointOrder:t}};if(null!==e.degrees)return{setValue:{radians:e.degrees.stateValues.value.divide(me$3.fromAst(180)).simplify().multiply(me$3.fromAst("pi")).simplify(),swapPointOrder:t}};let n,r=[],a=!1;for(let t=0;t<3;t++)r.push([e.points[t][0].evaluate_to_constant(),e.points[t][1].evaluate_to_constant()]),null!==r[t][0]&&null!==r[t][1]||(a=!0);return a?{setValue:{radians:me$3.fromAst("_"),swapPointOrder:t}}:(n=Math.atan2(r[2][1]-r[1][1],r[2][0]-r[1][0])-Math.atan2(r[0][1]-r[1][1],r[0][0]-r[1][0]),n<0&&(n+=2*Math.PI),n>Math.PI?"never"===e.chooseReflexAngle&&(n=2*Math.PI-n,t=!0):"always"===e.chooseReflexAngle&&(n=2*Math.PI-n,t=!0),{setValue:{radians:me$3.fromAst(n),swapPointOrder:t}})}},e.value={isAlias:!0,targetVariableName:"radians"},e.angle={isAlias:!0,targetVariableName:"radians"},e.degrees={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},returnDependencies:()=>({radians:{dependencyType:"stateVariable",variableName:"radians"}}),definition({dependencyValues:e}){let t;if("_"===e.radians.tree||Number.isNaN(e.radians.tree))t=e.radians;else{let n=e.radians.evaluate_to_constant();t=Number.isFinite(n)?me$3.fromAst(180*n/Math.PI):e.radians.multiply(me$3.fromAst(["/",180,"pi"])).simplify()}return{setValue:{degrees:t}}}},e.latexForRenderer={forRenderer:!0,returnDependencies:()=>({inDegrees:{dependencyType:"stateVariable",variableName:"inDegrees"},radians:{dependencyType:"stateVariable",variableName:"radians"},degrees:{dependencyType:"stateVariable",variableName:"degrees"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"}}),definition:function({dependencyValues:e,usedDefault:t}){let n={};e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(n.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(n.padToDigits=e.displayDigits));let r=roundForDisplay({value:e.inDegrees?e.degrees:e.radians,dependencyValues:e,usedDefault:t}).toLatex(n);return e.inDegrees&&(r+="^\\circ"),{setValue:{latexForRenderer:r}}}},e.numericalPoints={isArray:!0,entryPrefixes:["numericalPoint"],forRenderer:!0,returnArraySizeDependencies:()=>({}),returnArraySize:()=>[3],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={point:{dependencyType:"stateVariable",variableName:"point"+(Number(n)+1)}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].point,a=[];for(let e=0;e<2;e++){let n=t[e].evaluate_to_constant();Number.isFinite(n)||(n=NaN),a.push(n)}n[r]=a}return{setValue:{numericalPoints:n}}}},e.numericalRadius={forRenderer:!0,returnDependencies:()=>({radius:{dependencyType:"stateVariable",variableName:"radius"}}),definition({dependencyValues:e}){let t=e.radius.evaluate_to_constant();return Number.isFinite(t)||(t=NaN),{setValue:{numericalRadius:t}}}},e}static adapters=["radians"]}function calculateLineIntersection(e,t){if(2!==e.stateValues.nDimensions||2!==t.stateValues.nDimensions)return void console.log("Calculating angle between two lines implemented only in 2D");let n=e.stateValues.coeffvar1.evaluate_to_constant(),r=e.stateValues.coeffvar2.evaluate_to_constant(),a=e.stateValues.coeff0.evaluate_to_constant(),i=t.stateValues.coeffvar1.evaluate_to_constant(),s=t.stateValues.coeffvar2.evaluate_to_constant(),o=t.stateValues.coeff0.evaluate_to_constant();if(!(Number.isFinite(n)&&Number.isFinite(r)&&Number.isFinite(a)&&Number.isFinite(i)&&Number.isFinite(s)&&Number.isFinite(o)))return void console.log("Calculating angle between two lines implemented only for constant coefficients");let l=n*s-i*r;if(Math.abs(l)<1e-14)return Math.abs(o*n-a*i)>1e-14?void console.log("Cannot calculate angle between two parallel lines"):0===n&&0===r&&0===a||0===i&&0===s&&0===o?void 0:0!==r?[me$3.fromAst(0),me$3.fromAst(-a/r)]:[me$3.fromAst(-a/n),me$3.fromAst(0)];let u=(o*r-a*s)/l,c=(a*i-o*n)/l;return[me$3.fromAst(u),me$3.fromAst(c)]}var defaults$5={space:"",cycles:!1,replacer:(e,t)=>t,stringify:JSON.stringify},util$1={isArray:Array.isArray,assign:Object.assign,isObject:e=>"object"==typeof e,isFunction:e=>"function"==typeof e,isBoolean:e=>"boolean"==typeof e,isRegex:e=>e instanceof RegExp,keys:Object.keys};const DEFAULTS=defaults$5,isFunction$2=util$1.isFunction,isBoolean$1=util$1.isBoolean,isObject$2=util$1.isObject,isArray$3=util$1.isArray,isRegex=util$1.isRegex,assign$1=util$1.assign,keys$1=util$1.keys;function serialize(e){return null==e?e:isRegex(e)?e.toString():e.toJSON?e.toJSON():e}function stringifyDeterministic(e,t){t=t||assign$1({},DEFAULTS),isFunction$2(t)&&(t={compare:t});const n=t.space||DEFAULTS.space,r=isBoolean$1(t.cycles)?t.cycles:DEFAULTS.cycles,a=t.replacer||DEFAULTS.replacer,i=t.stringify||DEFAULTS.stringify,s=t.compare&&function(e){return function(t){return function(n,r){const a={key:n,value:t[n]},i={key:r,value:t[r]};return e(a,i)}}}(t.compare);r||i(e);const o=[];return function e(t,l,u,c){const p=n?"\n"+new Array(c+1).join(n):"",d=n?": ":":";if(u=serialize(u),void 0!==(u=a.call(t,l,u))){if(!isObject$2(u)||null===u)return i(u);if(isArray$3(u)){const t=[];for(let r=0;r0)for(let e of t.children)"object"!=typeof e?e.trim()&&(p=!0):i(e,"when")||(i(e,"math")||i(e,"number")||i(e,"mathList")||i(e,"numberList")?(s=!0,p=!0):i(e,"text")||i(e,"textList")?(o=!0,p=!0):i(e,"boolean")?(l=!0,p=!0):i(e,"booleanList")?l=!0:n.isInheritedComponentType({inheritedComponentType:e.componentType,baseComponentType:"_composite"})&&!e.attributes?.createComponentOfType?.primitive?p=!0:i(e,"orbitalDiagram")||(p=!0));else p=!0;else i(t,"mathInput")?(h.push(!1),s=!0,c=!0):i(t,"textInput")?(h.push(!1),o=!0,c=!0):i(t,"_input")||i(t,"considerAsResponses")?(h.push(!1),c=!0):(n.isInheritedComponentType({inheritedComponentType:t.componentType,baseComponentType:"_composite"})&&t.attributes?.createComponentOfType?.primitive,h.push(!0),p=!0);if(c&&(d=!0),u>0){if(e=e.filter((e=>"string"!=typeof e||""!==e.trim())),e.length!==u)return{success:!1};{let n={componentType:"choiceInput",children:e};return t.shuffleOrder&&(n.attributes={shuffleOrder:{primitive:!0}}),{success:!0,newChildren:[n]}}}if(t.handGraded&&!m&&(p=!0),!p&&!d){for(let t of e)if(i(t,"award")&&t.children?.length>0&&r(t.children)){d=!0;break}if(!d)for(let t of e)i(t,"award")&&t.children?.length>0&&a(t.children)}let f=[],y=[],g=[];if(0===h.filter((e=>!e)).length)f=e;else{if(!h[0]){let t=h.indexOf(!0);-1!==t&&(y=e.slice(0,t),e=e.slice(t),h=h.slice(t))}let t=h.indexOf(!1);-1===t?f=e:(f=e.slice(0,t),g=e.slice(t))}for(;"string"==typeof f[0]&&""===f[0].trim();)f=f.slice(1);let b,v,N=f.length;for(;"string"==typeof f[N-1]&&""===f[N-1].trim();)f=f.slice(0,N-1),N=f.length;if(t.type?(v=t.type,["math","text","boolean"].includes(v)||(console.warn(`Invalid type ${v}`),v="math")):v=s?"math":o?"text":l?"boolean":"math",0===f.length)b=[...y,...g];else{let e;e=f.length>1||n.isInheritedComponentType({inheritedComponentType:f[0].componentType,baseComponentType:"_composite"})&&!f[0].props?.componentType?[{componentType:v,children:f}]:f,b=[...y,{componentType:"award",children:e},...g]}if(p&&!c){b=[{componentType:v+"Input"},...b]}return{success:!0,newChildren:b}}}),e}static returnChildGroups(){return[{group:"awards",componentTypes:["award"]},{group:"inputs",componentTypes:["_input"]},{group:"responses",componentTypes:["considerAsResponses"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return renameStateVariable({stateVariableDefinitions:e,oldName:"disabled",newName:"disabledOriginal"}),e.showCorrectness={forRenderer:!0,returnDependencies:()=>({showCorrectnessPreliminary:{dependencyType:"stateVariable",variableName:"showCorrectnessPreliminary"},showCorrectnessFlag:{dependencyType:"flag",flagName:"showCorrectness"},handGraded:{dependencyType:"stateVariable",variableName:"handGraded"}}),definition({dependencyValues:e,usedDefault:t}){let n;return n=t.showCorrectnessPreliminary?!1!==e.showCorrectnessFlag&&!e.handGraded:e.showCorrectnessPreliminary,{setValue:{showCorrectness:n}}}},e.haveAwardThatRequiresInput={returnDependencies:()=>({awardChildren:{dependencyType:"child",childGroups:["awards"],variableNames:["requireInputInAnswer"]}}),definition:({dependencyValues:e})=>({setValue:{haveAwardThatRequiresInput:e.awardChildren.some((e=>e.stateValues.requireInputInAnswer))}})},e.allInputChildrenIncludingSugared={returnDependencies:()=>({allInputChildrenIncludingSugared:{dependencyType:"child",childGroups:["inputs"]}}),definition:({dependencyValues:e})=>({setValue:{allInputChildrenIncludingSugared:e.allInputChildrenIncludingSugared}})},e.inputChildren={stateVariablesDeterminingDependencies:["allInputChildrenIncludingSugared"],additionalStateVariablesDefined:["inputChildIndices","skippedFirstInput"],forRenderer:!0,returnDependencies({stateValues:e}){let t={allInputChildrenIncludingSugared:{dependencyType:"stateVariable",variableName:"allInputChildrenIncludingSugared"},haveAwardThatRequiresInput:{dependencyType:"stateVariable",variableName:"haveAwardThatRequiresInput"},handGraded:{dependencyType:"stateVariable",variableName:"handGraded"}};return e.allInputChildrenIncludingSugared.length>0&&(t.firstInputFromSugar={dependencyType:"doenetAttribute",componentName:e.allInputChildrenIncludingSugared[0].componentName,attributeName:"createdFromSugar"}),t},definition({dependencyValues:e}){let t=[...e.allInputChildrenIncludingSugared],n=[...e.allInputChildrenIncludingSugared.keys()],r=!1;return"choiceInput"!==t[0]?.componentType&&(!(e.haveAwardThatRequiresInput||e.handGraded)||e.allInputChildrenIncludingSugared.length>1)&&e.firstInputFromSugar&&(r=!0,t=t.slice(1),n=n.slice(1)),{setValue:{inputChildren:t,inputChildIndices:n,skippedFirstInput:r}}}},e.inputChildrenWithValues={stateVariablesDeterminingDependencies:["inputChildIndices"],forRenderer:!0,returnDependencies:({stateValues:e})=>({inputChildren:{dependencyType:"child",childGroups:["inputs"],variableNames:["valueToRecordOnSubmit","valueRecordedAtSubmit","value"],childIndices:e.inputChildIndices,variablesOptional:!0}}),definition:function({dependencyValues:e}){return{setValue:{inputChildrenWithValues:e.inputChildren}}}},e.inputChildWithValues={returnDependencies:()=>({inputChildrenWithValues:{dependencyType:"stateVariable",variableName:"inputChildrenWithValues"}}),definition({dependencyValues:e}){let t=null;return 1===e.inputChildrenWithValues.length&&(t=e.inputChildrenWithValues[0]),{setValue:{inputChildWithValues:t}}}},e.awardInputResponseChildren={returnDependencies:()=>({awardInputResponseChildren:{dependencyType:"child",childGroups:["awards","inputs","responses"]},skippedFirstInput:{dependencyType:"stateVariable",variableName:"skippedFirstInput"}}),definition({dependencyValues:e}){let t=[...e.awardInputResponseChildren];return e.skippedFirstInput&&(t=t.slice(1)),{setValue:{awardInputResponseChildren:t}}}},e.nResponses={public:!0,shadowingInstructions:{createComponentOfType:"number"},stateVariablesDeterminingDependencies:["awardInputResponseChildren"],returnDependencies({stateValues:e,componentInfoObjects:t}){let n={childTypes:{dependencyType:"value",value:e.awardInputResponseChildren.map((e=>e.componentType))}};for(let[r,a]of e.awardInputResponseChildren.entries())t.isInheritedComponentType({inheritedComponentType:a.componentType,baseComponentType:"award"})?n["child"+r]={dependencyType:"descendant",ancestorName:a.componentName,componentTypes:["_base"],variableNames:["isResponse","nValues"],variablesOptional:!0,recurseToMatchedChildren:!0,includeNonActiveChildren:!0,skipOverAdapters:!0}:t.isInheritedComponentType({inheritedComponentType:a.componentType,baseComponentType:"_input"})?n["childNValues"+r]={dependencyType:"stateVariable",componentName:a.componentName,variableName:"nValues",variablesOptional:!0}:n["child"+r]={dependencyType:"stateVariable",componentName:a.componentName,variableName:"childrenWithNValues"};return n},definition({dependencyValues:e,componentInfoObjects:t}){let n=0;for(let[r,a]of e.childTypes.entries())if(t.isInheritedComponentType({inheritedComponentType:a,baseComponentType:"award"}))for(let a of e["child"+r])a.stateValues.isResponse&&!t.isInheritedComponentType({inheritedComponentType:a.componentType,baseComponentType:"_composite"})&&(void 0===a.stateValues.nValues?n+=1:n+=a.stateValues.nValues);else if(t.isInheritedComponentType({inheritedComponentType:a,baseComponentType:"_input"})){let t=e["childNValues"+r];n+=void 0===t?1:t}else for(let t of e["child"+r])void 0===t.stateValues.nValues?n+=1:n+=t.stateValues.nValues;return{setValue:{nResponses:n}}}},e.currentResponses={public:!0,shadowingInstructions:{hasVariableComponentType:!0},isArray:!0,entryPrefixes:["currentResponse"],stateVariablesDeterminingDependencies:["awardInputResponseChildren"],returnArraySizeDependencies:()=>({nResponses:{dependencyType:"stateVariable",variableName:"nResponses"}}),returnArraySize:({dependencyValues:e})=>[e.nResponses],returnArrayDependenciesByKey({stateValues:e,componentInfoObjects:t}){let n={childTypes:{dependencyType:"value",value:e.awardInputResponseChildren.map((e=>e.componentType))}};for(let[r,a]of e.awardInputResponseChildren.entries())t.isInheritedComponentType({inheritedComponentType:a.componentType,baseComponentType:"award"})?n["child"+r]={dependencyType:"descendant",ancestorName:a.componentName,componentTypes:["_base"],variableNames:["isResponse","value","values","formula","componentType"],variablesOptional:!0,recurseToMatchedChildren:!0,includeAttributeChildren:!0,includeNonActiveChildren:!0,skipOverAdapters:!0}:t.isInheritedComponentType({inheritedComponentType:a.componentType,baseComponentType:"_input"})?(n["childValue"+r]={dependencyType:"stateVariable",componentName:a.componentName,variableName:"value",variablesOptional:!0},n["childValues"+r]={dependencyType:"stateVariable",componentName:a.componentName,variableName:"values",variablesOptional:!0},n["childComponentType"+r]={dependencyType:"stateVariable",componentName:a.componentName,variableName:"componentType",variablesOptional:!0}):n["child"+r]={dependencyType:"stateVariable",componentName:a.componentName,variableName:"childrenAsResponses"};return{globalDependencies:n}},arrayDefinitionByKey({globalDependencyValues:e,componentInfoObjects:t}){let n=[],r=[],a=[];for(let[n,r]of e.childTypes.entries())if(t.isInheritedComponentType({inheritedComponentType:r,baseComponentType:"award"}))for(let r of e["child"+n])r.stateValues.isResponse&&!t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"_composite"})&&a.push(r);else if(t.isInheritedComponentType({inheritedComponentType:r,baseComponentType:"_input"})){let t={componentType:r,stateValues:{value:e["childValue"+n],values:e["childValues"+n],componentType:e["childComponentType"+n]}};a.push(t)}else a.push(...e["child"+n]);for(let e of a){let t=e.stateValues.componentType;t||(t=e.componentType),"mathList"===t?t="math":"numberList"===t?t="number":"textList"===t?t="text":"booleanList"===t&&(t="boolean"),Array.isArray(e.stateValues.values)?(n.push(...e.stateValues.values),r.push(...Array(e.stateValues.values.length).fill(t))):void 0!==e.stateValues.value?(n.push(e.stateValues.value),r.push(t)):e.stateValues.formula instanceof me$3.class?(n.push(e.stateValues.formula),r.push("math")):(n.push(""),r.push("text"))}return{setValue:{currentResponses:n},setCreateComponentOfType:{currentResponses:r}}}},e.currentResponse={isAlias:!0,targetVariableName:"currentResponse1"},e.nSubmittedResponses={public:!0,shadowingInstructions:{createComponentOfType:"number"},hasEssential:!0,defaultValue:0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{nSubmittedResponses:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"nSubmittedResponses",value:e.nSubmittedResponses}]})},e.submittedResponsesComponentType={hasEssential:!0,defaultValue:null,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{submittedResponsesComponentType:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return e.submittedResponsesComponentType?{success:!0,instructions:[{setEssentialValue:"submittedResponsesComponentType",value:[...e.submittedResponsesComponentType]}]}:{success:!0,instructions:[{setEssentialValue:"submittedResponsesComponentType",value:[]}]}}},e.submittedResponses={public:!0,shadowingInstructions:{hasVariableComponentType:!0},isArray:!0,entryPrefixes:["submittedResponse"],defaultValueByArrayKey:()=>"_",hasEssential:!0,inverseShadowToSetEntireArray:!0,doNotCombineInverseArrayInstructions:!0,returnArraySizeDependencies:()=>({nSubmittedResponses:{dependencyType:"stateVariable",variableName:"nSubmittedResponses"}}),returnArraySize:({dependencyValues:e})=>[e.nSubmittedResponses],returnArrayDependenciesByKey:()=>({globalDependencies:{submittedResponsesComponentType:{dependencyType:"stateVariable",variableName:"submittedResponsesComponentType"},nSubmittedResponses:{dependencyType:"stateVariable",variableName:"nSubmittedResponses"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t=[];e.submittedResponsesComponentType&&t.push(...e.submittedResponsesComponentType.slice(0,e.nSubmittedResponses));let n={};for(let r=0;r({autoSubmit:{dependencyType:"flag",flagName:"autoSubmit"}}),definition:({dependencyValues:e})=>({setValue:{suppressCheckwork:e.autoSubmit}})},e.delegateCheckWork={additionalStateVariablesDefined:["delegateCheckWorkToInput","delegateCheckWorkToAncestor"],forRenderer:!0,returnDependencies:()=>({inputChildren:{dependencyType:"stateVariable",variableName:"inputChildren"},forceFullCheckworkButton:{dependencyType:"stateVariable",variableName:"forceFullCheckworkButton"},sectionAncestor:{dependencyType:"ancestor",componentType:"_sectioningComponent",variableNames:["suppressAnswerSubmitButtons"]},documentAncestor:{dependencyType:"ancestor",componentType:"document",variableNames:["suppressAnswerSubmitButtons"]}}),definition:function({dependencyValues:e}){let t=!1,n=!1,r=!1;return e.documentAncestor.stateValues.suppressAnswerSubmitButtons||e.sectionAncestor?.stateValues.suppressAnswerSubmitButtons?t=r=!0:1!==e.inputChildren.length||e.forceFullCheckworkButton||(n=r=!0),{setValue:{delegateCheckWork:r,delegateCheckWorkToAncestor:t,delegateCheckWorkToInput:n}}}},e.creditAchievedIfSubmit={additionalStateVariablesDefined:["awardsUsedIfSubmit","awardChildren","inputUsedIfSubmit"],stateVariablesDeterminingDependencies:["inputChildIndices"],returnDependencies:({stateValues:e})=>({awardChildren:{dependencyType:"child",childGroups:["awards"],variableNames:["credit","creditAchievedIfSubmit","fractionSatisfiedIfSubmit"]},inputChildren:{dependencyType:"child",childGroups:["inputs"],variableNames:["creditAchievedIfSubmit","value"],childIndices:e.inputChildIndices,variablesOptional:!0},nAwardsCredited:{dependencyType:"stateVariable",variableName:"nAwardsCredited"}}),definition:function({dependencyValues:e}){let t=0,n=e.nAwardsCredited,r=Array(n).fill(null),a=null;if(0===e.awardChildren.length){if(1===e.inputChildren.length){let n=e.inputChildren[0].stateValues.creditAchievedIfSubmit;n>=0&&(t=n,a=e.inputChildren[0].componentName)}}else{let a=Array(n).fill(null),i=0;for(let t of e.awardChildren){let e=t.stateValues.creditAchievedIfSubmit;if((e>i||null===r[n-1])&&t.stateValues.fractionSatisfiedIfSubmit>0)if(null===r[0])r[0]=t.componentName,a[0]=e,i=Math.min(...a);else for(let[s,o]of a.entries())if(e>o||null===o){r.splice(s,0,t.componentName),r=r.slice(0,n),a.splice(s,0,e),a=a.slice(0,n),i=Math.min(...a);break}}t=Math.min(1,a.reduce(((e,t)=>e+t),0))}return{setValue:{creditAchievedIfSubmit:t,awardsUsedIfSubmit:r,awardChildren:e.awardChildren,inputUsedIfSubmit:a}}}},e.creditAchieved={defaultValue:0,public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{creditAchieved:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"creditAchieved",value:e.creditAchieved}]}}},e.responseHasBeenSubmitted={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},defaultValue:!1,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{responseHasBeenSubmitted:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"responseHasBeenSubmitted",value:e.responseHasBeenSubmitted}]}}},e.autoSubmit={returnDependencies:()=>({autoSubmit:{dependencyType:"flag",flagName:"autoSubmit"}}),definition:({dependencyValues:e})=>({setValue:{autoSubmit:Boolean(e.autoSubmit)}})},e.creditAchievedDependencies={shadowVariable:!0,stateVariablesDeterminingDependencies:["autoSubmit"],returnDependencies:({stateValues:e})=>({currentCreditAchievedDependencies:{dependencyType:"recursiveDependencyValues",variableNames:["creditAchievedIfSubmit"],includeImmediateValueWithValue:!e.autoSubmit,includeRawValueWithImmediateValue:!e.autoSubmit,includeOnlyEssentialValues:!0}}),definition({dependencyValues:e}){let t=lib(e.currentCreditAchievedDependencies,{replacer:serializedComponentsReplacer});return{setValue:{creditAchievedDependencies:Base64.stringify(sha1(t))}}},markStale:()=>({answerCreditPotentiallyChanged:!0})},e.creditAchievedDependenciesAtSubmit={defaultValue:null,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{creditAchievedDependenciesAtSubmit:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"creditAchievedDependenciesAtSubmit",value:e.creditAchievedDependenciesAtSubmit}]}}},e.justSubmitted={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,defaultValue:!1,hasEssential:!0,shadowVariable:!0,returnDependencies:()=>({currentCreditAchievedDependencies:{dependencyType:"stateVariable",variableName:"creditAchievedDependencies"},creditAchievedDependenciesAtSubmit:{dependencyType:"stateVariable",variableName:"creditAchievedDependenciesAtSubmit"},disableAfterCorrect:{dependencyType:"stateVariable",variableName:"disableAfterCorrect"},hasBeenCorrect:{dependencyType:"stateVariable",variableName:"hasBeenCorrect"}}),definition:function({dependencyValues:e,justUpdatedForNewComponent:t,componentName:n}){if(e.disableAfterCorrect&&e.hasBeenCorrect)return{setValue:{justSubmitted:!0}};return e.creditAchievedDependenciesAtSubmit!==e.currentCreditAchievedDependencies&&!t?{setValue:{justSubmitted:!1},setEssentialValue:{justSubmitted:!1}}:{useEssentialOrDefaultValue:{justSubmitted:!0}}},inverseDefinition:({desiredStateVariableValues:e,componentName:t})=>({success:!0,instructions:[{setEssentialValue:"justSubmitted",value:e.justSubmitted}]})},e.allFeedbacks={returnDependencies:()=>({awardChildren:{dependencyType:"child",childGroups:["awards"],variableNames:["feedbacks"]},feedbackComponents:{dependencyType:"descendant",componentTypes:["_input"],variableNames:["feedbacks"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let t=[];for(let n of e.awardChildren)t.push(...n.stateValues.feedbacks);for(let n of e.feedbackComponents)Array.isArray(n.stateValues.feedbacks)&&t.push(...n.stateValues.feedbacks);return{setValue:{allFeedbacks:t}}}},e.numberFeedbacks={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({allFeedbacks:{dependencyType:"stateVariable",variableName:"allFeedbacks"}}),definition:({dependencyValues:e})=>({setValue:{numberFeedbacks:e.allFeedbacks.length},checkForActualChange:{numberFeedbacks:!0}})},e.feedbacks={public:!0,shadowingInstructions:{createComponentOfType:"feedback"},isArray:!0,entryPrefixes:["feedback"],returnArraySizeDependencies:()=>({numberFeedbacks:{dependencyType:"stateVariable",variableName:"numberFeedbacks"}}),returnArraySize:({dependencyValues:e})=>[e.numberFeedbacks],returnArrayDependenciesByKey:()=>({globalDependencies:{allFeedbacks:{dependencyType:"stateVariable",variableName:"allFeedbacks"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n=0;n({}),definition:()=>({useEssentialOrDefaultValue:{nSubmissions:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"nSubmissions",value:e.nSubmissions}]})},e.numberOfAttemptsLeft={public:!0,shadowingInstructions:{createComponentOfType:"integer"},forRenderer:!0,returnDependencies:()=>({nSubmissions:{dependencyType:"stateVariable",variableName:"nSubmissions"},maximumNumberOfAttempts:{dependencyType:"stateVariable",variableName:"maximumNumberOfAttempts"}}),definition:({dependencyValues:e})=>({setValue:{numberOfAttemptsLeft:e.maximumNumberOfAttempts-e.nSubmissions}})},e.hasBeenCorrect={defaultValue:!1,hasEssential:!0,shadowVariable:!0,returnDependencies:()=>({creditAchieved:{dependencyType:"stateVariable",variableName:"creditAchieved"}}),definition:({dependencyValues:e})=>1===e.creditAchieved?{setValue:{hasBeenCorrect:!0},setEssentialValue:{hasBeenCorrect:!0}}:{useEssentialOrDefaultValue:{hasBeenCorrect:!0}}},e.disabled={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,stateVariablesDeterminingDependencies:["disableAfterCorrect"],returnDependencies({stateValues:e}){let t={disabledOriginal:{dependencyType:"stateVariable",variableName:"disabledOriginal"},numberOfAttemptsLeft:{dependencyType:"stateVariable",variableName:"numberOfAttemptsLeft"},disableAfterCorrect:{dependencyType:"stateVariable",variableName:"disableAfterCorrect"}};return e.disableAfterCorrect&&(t.hasBeenCorrect={dependencyType:"stateVariable",variableName:"hasBeenCorrect"}),t},definition:({dependencyValues:e})=>({setValue:{disabled:e.disabledOriginal||e.numberOfAttemptsLeft<1||e.disableAfterCorrect&&e.hasBeenCorrect}})},e.inItemNumber={returnDependencies:()=>({documentAncestor:{dependencyType:"ancestor",componentType:"document",variableNames:["itemNumberByAnswerName"]}}),definition:({dependencyValues:e,componentName:t})=>({setValue:{inItemNumber:e.documentAncestor.stateValues.itemNumberByAnswerName[t]}})},e}async submitAnswer({actionId:e}){let t=await this.stateValues.numberOfAttemptsLeft;if(t<1)return void console.warn(`Cannot submit answer for ${this.componentName} as number of attempts left is ${t}`);let n=await this.stateValues.creditAchievedIfSubmit;await this.stateValues.handGraded&&(n=0);let r=await this.stateValues.awardsUsedIfSubmit,a=await this.stateValues.inputUsedIfSubmit,i=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"creditAchieved",value:n},{updateType:"updateValue",componentName:this.componentName,stateVariable:"responseHasBeenSubmitted",value:!0}],s=await this.stateValues.inputChildrenWithValues;if(1===s.length){let e=s[0];a===e.componentName&&"valueToRecordOnSubmit"in e.stateValues&&"valueRecordedAtSubmit"in e.stateValues&&i.push({updateType:"updateValue",componentName:e.componentName,stateVariable:"valueRecordedAtSubmit",value:e.stateValues.valueToRecordOnSubmit})}let o=await this.stateValues.currentResponses;i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"submittedResponses",value:o}),i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"submittedResponsesComponentType",value:this.state.currentResponses.shadowingInstructions.createComponentOfType}),i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"justSubmitted",value:!0}),i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"creditAchievedDependenciesAtSubmit",value:await this.stateValues.creditAchievedDependencies}),i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"nSubmissions",value:await this.stateValues.nSubmissions+1});for(let e of await this.stateValues.awardChildren){let t=r.includes(e.componentName);i.push({updateType:"updateValue",componentName:e.componentName,stateVariable:"awarded",value:t}),i.push({updateType:"updateValue",componentName:e.componentName,stateVariable:"creditAchieved",value:e.stateValues.creditAchievedIfSubmit}),i.push({updateType:"updateValue",componentName:e.componentName,stateVariable:"fractionSatisfied",value:e.stateValues.fractionSatisfiedIfSubmit})}let l=[];for(let e of o)if(e.toString)try{l.push(e.toString())}catch(e){l.push("_")}else l.push(e);return i.push({updateType:"recordItemSubmission",itemNumber:await this.stateValues.inItemNumber,submittedComponent:this.componentName,response:o,responseText:l,creditAchieved:n}),await this.coreFunctions.performUpdate({updateInstructions:i,actionId:e,event:{verb:"submitted",object:{componentName:this.componentName,componentType:this.componentType},result:{response:o,responseText:l,creditAchieved:n}},suppressToast:await this.stateValues.suppressToast}),await this.coreFunctions.triggerChainedActions({componentName:this.componentName})}}class Award extends BaseComponent{static componentType="award";static rendererType=void 0;static includeBlankStringChildren=!0;static removeBlankStringChildrenPostSugar=!0;static variableForPlainMacro="awarded";static variableForPlainCopy="awarded";static createAttributesObject(){let e=super.createAttributesObject();return e.credit={createComponentOfType:"number",createStateVariable:"credit",defaultValue:1,public:!0,attributesForCreatedComponent:{convertBoolean:!0}},e.matchPartial={createComponentOfType:"boolean",createStateVariable:"matchPartial",defaultValue:!1,public:!0,fallBackToParentStateVariable:"matchPartial"},e.symbolicEquality={createComponentOfType:"boolean",createStateVariable:"symbolicEquality",defaultValue:!1,public:!0,fallBackToParentStateVariable:"symbolicEquality"},e.expandOnCompare={createComponentOfType:"boolean",createStateVariable:"expandOnCompare",defaultValue:!1,public:!0,fallBackToParentStateVariable:"expandOnCompare"},e.simplifyOnCompare={createComponentOfType:"text",createStateVariable:"simplifyOnCompare",defaultValue:"none",toLowerCase:!0,valueTransformations:{"":"full",true:"full"},validValues:["none","full","numbers","numberspreserveorder"],public:!0,fallBackToParentStateVariable:"simplifyOnCompare"},e.unorderedCompare={createComponentOfType:"boolean",createStateVariable:"unorderedCompare",defaultValue:!1,public:!0,fallBackToParentStateVariable:"unorderedCompare"},e.matchByExactPositions={createComponentOfType:"boolean",createStateVariable:"matchByExactPositions",defaultValue:!1,public:!0,fallBackToParentStateVariable:"matchByExactPositions"},e.allowedErrorInNumbers={createComponentOfType:"number",createStateVariable:"allowedErrorInNumbers",defaultValue:0,public:!0,fallBackToParentStateVariable:"allowedErrorInNumbers"},e.includeErrorInNumberExponents={createComponentOfType:"boolean",createStateVariable:"includeErrorInNumberExponents",defaultValue:!1,public:!0,fallBackToParentStateVariable:"includeErrorInNumberExponents"},e.allowedErrorIsAbsolute={createComponentOfType:"boolean",createStateVariable:"allowedErrorIsAbsolute",defaultValue:!1,public:!0,fallBackToParentStateVariable:"allowedErrorIsAbsolute"},e.nSignErrorsMatched={createComponentOfType:"number",createStateVariable:"nSignErrorsMatched",defaultValue:0,public:!0,fallBackToParentStateVariable:"nSignErrorsMatched"},e.nPeriodicSetMatchesRequired={createComponentOfType:"integer",createStateVariable:"nPeriodicSetMatchesRequired",defaultValue:3,public:!0,fallBackToParentStateVariable:"nPeriodicSetMatchesRequired"},e.caseInsensitiveMatch={createComponentOfType:"boolean",createStateVariable:"caseInsensitiveMatch",defaultValue:!1,public:!0,fallBackToParentStateVariable:"caseInsensitiveMatch"},e.matchBlanks={createComponentOfType:"boolean",createStateVariable:"matchBlanks",defaultValue:!1,public:!0,fallBackToParentStateVariable:"matchBlanks"},e.feedbackCodes={createComponentOfType:"textList",createStateVariable:"feedbackCodes",defaultValue:[],public:!0},e.feedbackText={createComponentOfType:"text",createStateVariable:"feedbackText",defaultValue:null,public:!0},e.sourcesAreResponses={createPrimitiveOfType:"string"},e.splitSymbols={createComponentOfType:"boolean",createStateVariable:"splitSymbols",defaultValue:!0,public:!0,fallBackToParentStateVariable:"splitSymbols"},e.parseScientificNotation={createComponentOfType:"boolean",createStateVariable:"parseScientificNotation",defaultValue:!1,public:!0,fallBackToParentStateVariable:"parseScientificNotation"},e}static preprocessSerializedChildren({serializedChildren:e,attributes:t,componentName:n}){if(t.sourcesAreResponses){let r,a=t.sourcesAreResponses.primitive.split(/\s+/).filter((e=>e));r=t.newNamespace?.primitive?n+"/":getNamespaceFromName(n);for(let t of a){let n;if("/"===t[0])n=t;else if("../"===t.slice(0,3)){let e=getNamespaceFromName(r.slice(0,r.length-1)),a=t.slice(3);for(;"../"===a.slice(0,3);){if("/"===e){n=null;break}e=getNamespaceFromName(e.slice(0,e.length-1)),a=a.slice(3)}null!==n&&(n=e+a)}else n=r+t;addResponsesToDescendantsWithTarget(e,t,n)}}}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e,parentAttributes:t,componentInfoObjects:n}){for(;"string"==typeof e[0]&&""===e[0].trim();)e=e.slice(1);let r=e.length;for(;"string"==typeof e[r-1]&&""===e[r-1].trim();)r=(e=e.slice(0,r-1)).length;if(1===e.length&&"object"==typeof e[0])return{success:!1};let a,i=n.componentIsSpecifiedType,s=!1,o=!1,l=!1;for(let t of e)"object"==typeof t&&(i(t,"math")||i(t,"number")||i(t,"mathList")||i(t,"numberList")?s=!0:i(t,"text")||i(t,"textList")?o=!0:(i(t,"boolean")||i(t,"booleanList"))&&(l=!0));return t.type?(a=t.type,["math","text","boolean"].includes(a)||(console.warn(`Invalid type ${a}`),a="math")):a=s?"math":o?"text":l?"boolean":"math",{success:!0,newChildren:[{componentType:a,children:e}]}}}),e}static returnChildGroups(){return[{group:"whens",componentTypes:["when"]},{group:"maths",componentTypes:["math"]},{group:"numbers",componentTypes:["number"]},{group:"texts",componentTypes:["text"]},{group:"booleans",componentTypes:["boolean"]},{group:"mathLists",componentTypes:["mathList"]},{group:"numberLists",componentTypes:["numberList"]},{group:"textLists",componentTypes:["textList"]},{group:"booleanLists",componentTypes:["booleanList"]},{group:"otherComparableTypes",componentTypes:["orbitalDiagram"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.parsedExpression={additionalStateVariablesDefined:["requireInputInAnswer"],returnDependencies:()=>({whenChild:{dependencyType:"child",childGroups:["whens"]},typeChildren:{dependencyType:"child",childGroups:["maths","numbers","texts","booleans","mathLists","numberLists","textLists","booleanLists","otherComparableTypes"]}}),definition:function({dependencyValues:e}){let t=null,n=!1;return 0==e.whenChild.length&&e.typeChildren.length>0&&(n=!0,t=me$3.fromAst(["=","comp1","comp2"])),{setValue:{parsedExpression:t,requireInputInAnswer:n}}}},e.creditAchievedIfSubmit={public:!0,shadowingInstructions:{createComponentOfType:"number"},additionalStateVariablesDefined:[{variableName:"fractionSatisfiedIfSubmit",public:!0,shadowingInstructions:{createComponentOfType:"number"}}],returnDependencies:()=>({credit:{dependencyType:"stateVariable",variableName:"credit"},whenChild:{dependencyType:"child",childGroups:["whens"],variableNames:["fractionSatisfied"]},mathChild:{dependencyType:"child",childGroups:["maths"],variableNames:["value","unordered"]},numberChild:{dependencyType:"child",childGroups:["numbers"],variableNames:["value"]},textChild:{dependencyType:"child",childGroups:["texts"],variableNames:["value"]},booleanChild:{dependencyType:"child",childGroups:["booleans"],variableNames:["value"]},mathListChild:{dependencyType:"child",childGroups:["mathLists"],variableNames:["maths","unordered"]},numberListChild:{dependencyType:"child",childGroups:["numberLists"],variableNames:["numbers","unordered"]},textListChild:{dependencyType:"child",childGroups:["textLists"],variableNames:["texts","unordered"]},booleanListChild:{dependencyType:"child",childGroups:["booleanLists"],variableNames:["booleans","unordered"]},otherComparableChild:{dependencyType:"child",childGroups:["otherComparableTypes"],variableNames:["value"]},answerInput:{dependencyType:"parentStateVariable",variableName:"inputChildWithValues"},parsedExpression:{dependencyType:"stateVariable",variableName:"parsedExpression"},matchPartial:{dependencyType:"stateVariable",variableName:"matchPartial"},symbolicEquality:{dependencyType:"stateVariable",variableName:"symbolicEquality"},expandOnCompare:{dependencyType:"stateVariable",variableName:"expandOnCompare"},simplifyOnCompare:{dependencyType:"stateVariable",variableName:"simplifyOnCompare"},unorderedCompare:{dependencyType:"stateVariable",variableName:"unorderedCompare"},matchByExactPositions:{dependencyType:"stateVariable",variableName:"matchByExactPositions"},allowedErrorInNumbers:{dependencyType:"stateVariable",variableName:"allowedErrorInNumbers"},includeErrorInNumberExponents:{dependencyType:"stateVariable",variableName:"includeErrorInNumberExponents"},allowedErrorIsAbsolute:{dependencyType:"stateVariable",variableName:"allowedErrorIsAbsolute"},nSignErrorsMatched:{dependencyType:"stateVariable",variableName:"nSignErrorsMatched"},nPeriodicSetMatchesRequired:{dependencyType:"stateVariable",variableName:"nPeriodicSetMatchesRequired"},caseInsensitiveMatch:{dependencyType:"stateVariable",variableName:"caseInsensitiveMatch"},matchBlanks:{dependencyType:"stateVariable",variableName:"matchBlanks"}}),definition:function({dependencyValues:e,usedDefault:t}){let n;if(e.whenChild.length>0)n=e.whenChild[0].stateValues.fractionSatisfied;else{if(!e.answerInput||!e.parsedExpression)return{setValue:{creditAchievedIfSubmit:0,fractionSatisfiedIfSubmit:0}};n=evaluateLogicDirectlyFromChildren({dependencyValues:e,usedDefault:t})}n=Math.max(0,Math.min(1,n));let r=0;return Number.isFinite(e.credit)&&(r=Math.max(0,Math.min(1,e.credit))*n),{setValue:{fractionSatisfiedIfSubmit:n,creditAchievedIfSubmit:r}}}},e.fractionSatisfied={public:!0,shadowingInstructions:{createComponentOfType:"number"},defaultValue:0,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{fractionSatisfied:!0}}),inverseDefinition:function({desiredStateVariableValues:e,initialChange:t}){return t?{success:!0,instructions:[{setEssentialValue:"fractionSatisfied",value:e.fractionSatisfied}]}:{success:!1}}},e.creditAchieved={public:!0,shadowingInstructions:{createComponentOfType:"number"},defaultValue:0,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{creditAchieved:!0}}),inverseDefinition:function({desiredStateVariableValues:e,initialChange:t}){return t?{success:!0,instructions:[{setEssentialValue:"creditAchieved",value:e.creditAchieved}]}:{success:!1}}},e.awarded={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},defaultValue:!1,hasEssential:!0,doNotShadowEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{awarded:!0}}),inverseDefinition:function({desiredStateVariableValues:e,initialChange:t}){return t?{success:!0,instructions:[{setEssentialValue:"awarded",value:e.awarded}]}:{success:!1}}},e.allFeedbacks={returnDependencies:()=>({feedbackText:{dependencyType:"stateVariable",variableName:"feedbackText"},feedbackCodes:{dependencyType:"stateVariable",variableName:"feedbackCodes"},feedbackDefinitionAncestor:{dependencyType:"ancestor",variableNames:["feedbackDefinitions"]},awarded:{dependencyType:"stateVariable",variableName:"awarded"}}),definition:function({dependencyValues:e}){if(!e.awarded)return{setValue:{allFeedbacks:[]}};let t=[],n=e.feedbackDefinitionAncestor.stateValues.feedbackDefinitions;for(let r of e.feedbackCodes){let e=n[r.toLowerCase()];e&&t.push(e)}return null!==e.feedbackText&&t.push(e.feedbackText),{setValue:{allFeedbacks:t}}}},e.numberFeedbacks={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({allFeedbacks:{dependencyType:"stateVariable",variableName:"allFeedbacks"}}),definition:({dependencyValues:e})=>({setValue:{numberFeedbacks:e.allFeedbacks.length},checkForActualChange:{numberFeedbacks:!0}})},e.feedbacks={public:!0,shadowingInstructions:{createComponentOfType:"feedback"},isArray:!0,entryPrefixes:["feedback"],returnArraySizeDependencies:()=>({numberFeedbacks:{dependencyType:"stateVariable",variableName:"numberFeedbacks"}}),returnArraySize:({dependencyValues:e})=>[e.numberFeedbacks],returnArrayDependenciesByKey:()=>({globalDependencies:{allFeedbacks:{dependencyType:"stateVariable",variableName:"allFeedbacks"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n=0;n0?n.textChildrenByCode.comp2=e.textChild[0]:e.mathChild.length>0?n.mathChildrenByCode.comp2=e.mathChild[0]:e.numberChild.length>0?n.numberChildrenByCode.comp2=e.numberChild[0]:e.booleanChild.length>0?n.booleanChildrenByCode.comp2=e.booleanChild[0]:e.textListChild.length>0?n.textListChildrenByCode.comp2=e.textListChild[0]:e.mathListChild.length>0?n.mathListChildrenByCode.comp2=e.mathListChild[0]:e.numberListChild.length>0?n.numberListChildrenByCode.comp2=e.numberListChild[0]:e.booleanListChild.length>0?n.booleanListChildrenByCode.comp2=e.booleanListChild[0]:e.otherComparableChild.length>0&&(n.otherChildrenByCode.comp2=e.otherComparableChild[0]);let a=e.answerInput.stateValues.immediateValue;void 0===a&&(a=e.answerInput.stateValues.value);let i={stateValues:{value:a}};return"textInput"===e.answerInput.componentType?n.textChildrenByCode.comp1=i:"booleanInput"===e.answerInput.componentType?n.booleanChildrenByCode.comp1=i:n.mathChildrenByCode.comp1=i,evaluateLogic({logicTree:e.parsedExpression.tree,canOverrideUnorderedCompare:r,dependencyValues:n})}function addResponsesToDescendantsWithTarget(e,t,n){for(let r of e){let e=r.props;if(e&&0!==Object.keys(e).length||(e=r.doenetAttributes),e)for(let a in e)if("target"===a.toLowerCase()&&e[a]===t||"targetcomponentname"===a.toLowerCase()&&e[a]===n){r.attributes||(r.attributes={});let e=Object.keys(r.attributes).map((e=>e.toLowerCase())).includes("isresponse");e||(r.attributes.isResponse=!0)}r.children&&addResponsesToDescendantsWithTarget(r.children,t,n)}}class When extends BooleanComponent{static componentType="when";static rendererType=void 0;static stateVariableForAttributeValue="conditionSatisfied";static createAttributesObject(){let e=super.createAttributesObject();e.matchPartial={createComponentOfType:"boolean",createStateVariable:"matchPartial",defaultValue:!1,public:!0,fallBackToParentStateVariable:"matchPartial"};for(let t of["symbolicEquality","expandOnCompare","simplifyOnCompare","unorderedCompare","matchByExactPositions","allowedErrorInNumbers","includeErrorInNumberExponents","allowedErrorIsAbsolute","nSignErrorsMatched","nPeriodicSetMatchesRequired","caseInsensitiveMatch","matchBlanks"])e[t].fallBackToParentStateVariable=t;return e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.value={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},additionalStateVariablesDefined:[{variableName:"fractionSatisfied",public:!0,shadowingInstructions:{createComponentOfType:"number"}},{variableName:"conditionSatisfied",public:!0,shadowingInstructions:{createComponentOfType:"boolean"}}],returnDependencies:()=>({matchPartial:{dependencyType:"stateVariable",variableName:"matchPartial"},symbolicEquality:{dependencyType:"stateVariable",variableName:"symbolicEquality"},expandOnCompare:{dependencyType:"stateVariable",variableName:"expandOnCompare"},simplifyOnCompare:{dependencyType:"stateVariable",variableName:"simplifyOnCompare"},unorderedCompare:{dependencyType:"stateVariable",variableName:"unorderedCompare"},matchByExactPositions:{dependencyType:"stateVariable",variableName:"matchByExactPositions"},allowedErrorInNumbers:{dependencyType:"stateVariable",variableName:"allowedErrorInNumbers"},includeErrorInNumberExponents:{dependencyType:"stateVariable",variableName:"includeErrorInNumberExponents"},allowedErrorIsAbsolute:{dependencyType:"stateVariable",variableName:"allowedErrorIsAbsolute"},nSignErrorsMatched:{dependencyType:"stateVariable",variableName:"nSignErrorsMatched"},nPeriodicSetMatchesRequired:{dependencyType:"stateVariable",variableName:"nPeriodicSetMatchesRequired"},caseInsensitiveMatch:{dependencyType:"stateVariable",variableName:"caseInsensitiveMatch"},matchBlanks:{dependencyType:"stateVariable",variableName:"matchBlanks"},parsedExpression:{dependencyType:"stateVariable",variableName:"parsedExpression"},booleanChildrenByCode:{dependencyType:"stateVariable",variableName:"booleanChildrenByCode"},booleanListChildrenByCode:{dependencyType:"stateVariable",variableName:"booleanListChildrenByCode"},textChildrenByCode:{dependencyType:"stateVariable",variableName:"textChildrenByCode"},textListChildrenByCode:{dependencyType:"stateVariable",variableName:"textListChildrenByCode"},mathChildrenByCode:{dependencyType:"stateVariable",variableName:"mathChildrenByCode"},mathListChildrenByCode:{dependencyType:"stateVariable",variableName:"mathListChildrenByCode"},numberChildrenByCode:{dependencyType:"stateVariable",variableName:"numberChildrenByCode"},numberListChildrenByCode:{dependencyType:"stateVariable",variableName:"numberListChildrenByCode"},otherChildrenByCode:{dependencyType:"stateVariable",variableName:"otherChildrenByCode"}}),definition({dependencyValues:e,usedDefault:t}){if(null===e.parsedExpression)return{setValue:{conditionSatisfied:!1,value:!1,fractionSatisfied:0}};let n=t.unorderedCompare,r=evaluateLogic({logicTree:e.parsedExpression.tree,canOverrideUnorderedCompare:n,dependencyValues:e}),a=1===r;return{setValue:{fractionSatisfied:r,conditionSatisfied:a,value:a}}}},e}}class MathInput extends Input{constructor(e){super(e),Object.assign(this.actions,{updateRawValue:this.updateRawValue.bind(this),updateValue:this.updateValue.bind(this)}),this.externalActions={},Object.defineProperty(this.externalActions,"submitAnswer",{enumerable:!0,get:async function(){let e=await this.stateValues.answerAncestor;return null!==e?{componentName:e.componentName,actionName:"submitAnswer"}:void 0}.bind(this)})}static componentType="mathInput";static variableForPlainMacro="value";static variableForPlainCopy="value";static processWhenJustUpdatedForNewComponent=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.prefill={createComponentOfType:"math",createStateVariable:"prefill",defaultValue:me$3.fromAst("_"),public:!0,copyComponentAttributesForCreatedComponent:["format","functionSymbols","splitSymbols","parseScientificNotation"]},e.prefillLatex={createComponentOfType:"latex",createStateVariable:"prefillLatex",defaultValue:"",public:!0},e.format={createComponentOfType:"text",createStateVariable:"format",defaultValue:"text",public:!0},e.functionSymbols={createComponentOfType:"textList",createStateVariable:"functionSymbols",defaultValue:["f","g"],public:!0},e.splitSymbols={createComponentOfType:"boolean",createStateVariable:"splitSymbols",defaultValue:!0,public:!0,fallBackToParentStateVariable:"splitSymbols"},e.parseScientificNotation={createComponentOfType:"boolean",createStateVariable:"parseScientificNotation",defaultValue:!1,public:!0,fallBackToParentStateVariable:"parseScientificNotation"},e.displayDigits={createComponentOfType:"integer",createStateVariable:"displayDigits",defaultValue:10,public:!0},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.bindValueTo={createComponentOfType:"math"},e.unionFromU={createComponentOfType:"boolean",createStateVariable:"unionFromU",defaultValue:!1,public:!0},e.hideNaN={createComponentOfType:"boolean",createStateVariable:"hideNaN",defaultValue:!0,public:!0},e.removeStrings={createComponentOfType:"textList",createStateVariable:"removeStrings",defaultValue:null},e}static returnSugarInstructions(){let e=[];return e.push({replacementFunction:function({matchedChildren:e}){return 0===e.length?{success:!1}:{success:!0,newChildren:[{componentType:"math",children:e}]}}}),e}static returnChildGroups(){return[{group:"maths",componentTypes:["math"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.value={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]},hasEssential:!0,shadowVariable:!0,returnDependencies:()=>({mathChild:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]},bindValueTo:{dependencyType:"attributeComponent",attributeName:"bindValueTo",variableNames:["value"]},prefill:{dependencyType:"stateVariable",variableName:"prefill"},prefillLatex:{dependencyType:"stateVariable",variableName:"prefillLatex"},unionFromU:{dependencyType:"stateVariable",variableName:"unionFromU"},functionSymbols:{dependencyType:"stateVariable",variableName:"functionSymbols"},splitSymbols:{dependencyType:"stateVariable",variableName:"splitSymbols"},parseScientificNotation:{dependencyType:"stateVariable",variableName:"parseScientificNotation"}}),set:convertValueToMathExpression,definition:function({dependencyValues:e,usedDefault:t}){return e.mathChild.length>0?{setValue:{value:e.mathChild[0].stateValues.value}}:e.bindValueTo?{setValue:{value:e.bindValueTo.stateValues.value}}:{useEssentialOrDefaultValue:{value:{get defaultValue(){return!t.prefill||t.prefillLatex?e.prefill:calculateMathExpressionFromLatex({latex:e.prefillLatex,unionFromU:e.unionFromU,functionSymbols:e.functionSymbols,splitSymbols:e.splitSymbols,parseScientificNotation:e.parseScientificNotation})}}}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){return t.mathChild.length>0?{success:!0,instructions:[{setDependency:"mathChild",desiredValue:e.value,variableIndex:0,childIndex:0}]}:t.bindValueTo?{success:!0,instructions:[{setDependency:"bindValueTo",desiredValue:e.value,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"value",value:e.value}]}}},e.immediateValue={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]},hasEssential:!0,shadowVariable:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),set:convertValueToMathExpression,definition:function({dependencyValues:e,changes:t,justUpdatedForNewComponent:n,usedDefault:r}){return!t.value||n||r.value?{useEssentialOrDefaultValue:{immediateValue:{defaultValue:e.value}}}:{setValue:{immediateValue:e.value},setEssentialValue:{immediateValue:e.value}}},inverseDefinition:function({desiredStateVariableValues:e,initialChange:t,shadowedVariable:n}){let r=[{setEssentialValue:"immediateValue",value:e.immediateValue}];return t||n||r.push({setDependency:"value",desiredValue:e.immediateValue}),{success:!0,instructions:r}}},e.valueForDisplay={forRenderer:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"}}),set:convertValueToMathExpression,definition:function({dependencyValues:e,usedDefault:t}){return{setValue:{valueForDisplay:roundForDisplay({value:e.value,dependencyValues:e,usedDefault:t})}}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({valueForDisplay:{dependencyType:"stateVariable",variableName:"valueForDisplay"}}),definition:function({dependencyValues:e}){return{setValue:{text:e.valueForDisplay.toString()}}}},e.dontUpdateRawValueInDefinition={defaultValue:!1,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{dontUpdateRawValueInDefinition:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"dontUpdateRawValueInDefinition",value:e.dontUpdateRawValueInDefinition}]})},e.rawRendererValue={forRenderer:!0,hasEssential:!0,shadowVariable:!0,defaultValue:"",provideEssentialValuesInDefinition:!0,public:!0,shadowingInstructions:{createComponentOfType:"text"},additionalStateVariablesDefined:[{variableName:"lastValueForDisplay",hasEssential:!0,shadowVariable:!0,defaultValue:null,set:convertValueToMathExpression}],returnDependencies:()=>({immediateValue:{dependencyType:"stateVariable",variableName:"immediateValue"},valueForDisplay:{dependencyType:"stateVariable",variableName:"valueForDisplay"},hideNaN:{dependencyType:"stateVariable",variableName:"hideNaN"},dontUpdateRawValueInDefinition:{dependencyType:"stateVariable",variableName:"dontUpdateRawValueInDefinition"},prefill:{dependencyType:"stateVariable",variableName:"prefill"},prefillLatex:{dependencyType:"stateVariable",variableName:"prefillLatex"}}),definition({dependencyValues:e,essentialValues:t,justUpdatedForNewComponent:n,usedDefault:r}){if(void 0!==t.rawRendererValue&&(n||deepCompare(t.lastValueForDisplay.tree,e.valueForDisplay.tree)||e.dontUpdateRawValueInDefinition))return{useEssentialOrDefaultValue:{rawRendererValue:!0,lastValueForDisplay:!0}};{let t;return t=r.immediateValue&&r.prefill&&!r.prefillLatex?stripLatex(e.prefillLatex):stripLatex(e.valueForDisplay.toLatex({showBlanks:!1})),e.hideNaN&&"NaN"===t&&(t=""),{setValue:{rawRendererValue:t,lastValueForDisplay:e.valueForDisplay},setEssentialValue:{rawRendererValue:t,lastValueForDisplay:e.valueForDisplay}}}},async inverseDefinition({desiredStateVariableValues:e,stateValues:t,essentialValues:n,dependencyValues:r,componentName:a}){let i=[];if("string"==typeof e.rawRendererValue){let r=n.rawRendererValue,a=e.rawRendererValue;r!==a&&i.push({setEssentialValue:"rawRendererValue",value:a});let s=await t.unionFromU,o=await t.functionSymbols,l=await t.splitSymbols,u=await t.parseScientificNotation,c=await t.removeStrings,p=calculateMathExpressionFromLatex({latex:r,unionFromU:s,functionSymbols:o,splitSymbols:l,parseScientificNotation:u,removeStrings:c}),d=calculateMathExpressionFromLatex({latex:a,unionFromU:s,functionSymbols:o,splitSymbols:l,parseScientificNotation:u,removeStrings:c});deepCompare(d.tree,p.tree)||i.push({setDependency:"immediateValue",desiredValue:d,treatAsInitialChange:!0})}else if(e.rawRendererValue instanceof me$3.class){i.push({setEssentialValue:"lastValueForDisplay",value:e.rawRendererValue});let a=await t.unionFromU,s=await t.functionSymbols,o=await t.splitSymbols,l=await t.parseScientificNotation,u=await t.removeStrings,c=calculateMathExpressionFromLatex({latex:n.rawRendererValue,unionFromU:a,functionSymbols:s,splitSymbols:o,parseScientificNotation:l,removeStrings:u});if(!deepCompare(e.rawRendererValue.tree,c.tree)){let t=stripLatex(e.rawRendererValue.toLatex({showBlanks:!1}));r.hideNaN&&"NaN"===t&&(t=""),i.push({setEssentialValue:"rawRendererValue",value:t})}}else e.lastValueForDisplay instanceof me$3.class&&i.push({setEssentialValue:"lastValueForDisplay",value:e.lastValueForDisplay});return{success:!0,instructions:i}}},e.componentType={returnDependencies:()=>({}),definition:()=>({setValue:{componentType:"math"}})},e}async updateRawValue({rawRendererValue:e,actionId:t}){if(!await this.stateValues.disabled)return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rawRendererValue",value:e},{updateType:"setComponentNeedingUpdateValue",componentName:this.componentName}],transient:!0,actionId:t});this.coreFunctions.resolveAction({actionId:t})}async updateValue({actionId:e}){if(await this.stateValues.disabled)this.coreFunctions.resolveAction({actionId:e});else{let t=await this.stateValues.immediateValue;if(!deepCompare((await this.stateValues.value).tree,t.tree)){let n=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"dontUpdateRawValueInDefinition",value:!0},{updateType:"updateValue",componentName:this.componentName,stateVariable:"value",value:t},{updateType:"executeUpdate"},{updateType:"updateValue",componentName:this.componentName,stateVariable:"dontUpdateRawValueInDefinition",value:!1},{updateType:"updateValue",componentName:this.componentName,stateVariable:"immediateValue",valueOfStateVariable:"value"},{updateType:"unsetComponentNeedingUpdateValue"}];"_"!==t.tree?n.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"rawRendererValue",valueOfStateVariable:"valueForDisplay"}):n.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"lastValueForDisplay",valueOfStateVariable:"valueForDisplay"});let r={verb:"answered",object:{componentName:this.componentName,componentType:this.componentType},result:{response:t,responseText:t.toString()}},a=await this.stateValues.answerAncestor;return a&&(r.context={answerAncestor:a.componentName}),await this.coreFunctions.performUpdate({updateInstructions:n,actionId:e,event:r}),await this.coreFunctions.triggerChainedActions({componentName:this.componentName})}this.coreFunctions.resolveAction({actionId:e})}}static adapters=[{stateVariable:"value",stateVariablesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]}]}function calculateMathExpressionFromLatex({latex:e,unionFromU:t,functionSymbols:n,splitSymbols:r,parseScientificNotation:a,removeStrings:i}){let s;if(i)for(let t of i)["$","%"].includes(t)&&(t="\\"+t),e=e.replaceAll(t,"");e=normalizeLatexString(e,{unionFromU:t});let o=getFromLatex({functionSymbols:n,splitSymbols:r,parseScientificNotation:a});try{s=o(e)}catch(e){s=me$3.fromAst("_")}return s}class Textinput extends Input{constructor(e){super(e),Object.assign(this.actions,{updateImmediateValue:this.updateImmediateValue.bind(this),updateValue:this.updateValue.bind(this)}),this.externalActions={},Object.defineProperty(this.externalActions,"submitAnswer",{enumerable:!0,get:async function(){let e=await this.stateValues.answerAncestor;return null!==e?{componentName:e.componentName,actionName:"submitAnswer"}:void 0}.bind(this)})}static componentType="textInput";static variableForPlainMacro="value";static variableForPlainCopy="value";static processWhenJustUpdatedForNewComponent=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.prefill={createComponentOfType:"text",createStateVariable:"prefill",defaultValue:"",public:!0},e.size={createComponentOfType:"number",createStateVariable:"size",defaultValue:10,forRenderer:!0,public:!0},e.bindValueTo={createComponentOfType:"text"},e.expanded={createComponentOfType:"boolean",createStateVariable:"expanded",defaultValue:!1,forRenderer:!0,public:!0,fallBackToParentStateVariable:"expanded"},e.width={createComponentOfType:"_componentSize",createStateVariable:"width",defaultValue:{size:600,isAbsolute:!0},forRenderer:!0,public:!0},e.height={createComponentOfType:"_componentSize",createStateVariable:"height",defaultValue:{size:120,isAbsolute:!0},forRenderer:!0,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.value={public:!0,shadowingInstructions:{createComponentOfType:"text"},hasEssential:!0,shadowVariable:!0,returnDependencies:()=>({bindValueTo:{dependencyType:"attributeComponent",attributeName:"bindValueTo",variableNames:["value"]},prefill:{dependencyType:"stateVariable",variableName:"prefill"}}),definition:function({dependencyValues:e}){return e.bindValueTo?{setValue:{value:e.bindValueTo.stateValues.value}}:{useEssentialOrDefaultValue:{value:{defaultValue:e.prefill}}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){return t.bindValueTo?{success:!0,instructions:[{setDependency:"bindValueTo",desiredValue:e.value,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"value",value:e.value}]}}},e.immediateValue={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,hasEssential:!0,shadowVariable:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:function({dependencyValues:e,changes:t,justUpdatedForNewComponent:n}){return t.value&&!n?{setValue:{immediateValue:e.value},setEssentialValue:{immediateValue:e.value}}:{useEssentialOrDefaultValue:{immediateValue:{defaultValue:e.value}}}},inverseDefinition:function({desiredStateVariableValues:e,initialChange:t,shadowedVariable:n}){let r=[{setEssentialValue:"immediateValue",value:e.immediateValue}];return t||n||r.push({setDependency:"value",desiredValue:e.immediateValue}),{success:!0,instructions:r}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:function({dependencyValues:e}){return{setValue:{text:e.value}}}},e.componentType={returnDependencies:()=>({}),definition:()=>({setValue:{componentType:"text"}})},e}async updateImmediateValue({text:e,actionId:t}){if(!await this.stateValues.disabled)return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"immediateValue",value:e},{updateType:"setComponentNeedingUpdateValue",componentName:this.componentName}],transient:!0,actionId:t});this.coreFunctions.resolveAction({actionId:t})}async updateValue({actionId:e}){if(!await this.stateValues.disabled){let t=await this.stateValues.immediateValue;if(await this.stateValues.value!==t){let n=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"value",value:t},{updateType:"executeUpdate"},{updateType:"updateValue",componentName:this.componentName,stateVariable:"immediateValue",valueOfStateVariable:"value"},{updateType:"unsetComponentNeedingUpdateValue"}],r={verb:"answered",object:{componentName:this.componentName,componentType:this.componentType},result:{response:t,responseText:t}},a=await this.stateValues.answerAncestor;return a&&(r.context={answerAncestor:a.componentName}),await this.coreFunctions.performUpdate({updateInstructions:n,actionId:e,event:r}),await this.coreFunctions.triggerChainedActions({componentName:this.componentName})}}this.coreFunctions.resolveAction({actionId:e})}}class BooleanInput extends Input{constructor(e){super(e),Object.assign(this.actions,{updateBoolean:this.updateBoolean.bind(this)}),this.externalActions={},Object.defineProperty(this.externalActions,"submitAnswer",{enumerable:!0,get:async function(){let e=await this.stateValues.answerAncestor;return null!==e?{componentName:e.componentName,actionName:"submitAnswer"}:void 0}.bind(this)})}static componentType="booleanInput";static variableForPlainMacro="value";static variableForPlainCopy="value";static createAttributesObject(){let e=super.createAttributesObject();return e.prefill={createComponentOfType:"boolean",createStateVariable:"prefill",defaultValue:!1,public:!0},e.labelIsName={createComponentOfType:"boolean",createStateVariable:"labelIsName",defaultValue:!1,public:!0},e.asToggleButton={createComponentOfType:"boolean",createStateVariable:"asToggleButton",defaultValue:!1,forRenderer:!0,public:!0},e.bindValueTo={createComponentOfType:"boolean"},e}static returnChildGroups(){return[{group:"labels",componentTypes:["label"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnLabelStateVariableDefinitions();return Object.assign(e,t),e.value={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,hasEssential:!0,shadowVariable:!0,returnDependencies:()=>({bindValueTo:{dependencyType:"attributeComponent",attributeName:"bindValueTo",variableNames:["value"]},prefill:{dependencyType:"stateVariable",variableName:"prefill"}}),definition:function({dependencyValues:e}){return e.bindValueTo?{setValue:{value:e.bindValueTo.stateValues.value}}:{useEssentialOrDefaultValue:{value:{defaultValue:e.prefill}}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){return t.bindValueTo?{success:!0,instructions:[{setDependency:"bindValueTo",desiredValue:e.value,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"value",value:e.value}]}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:function({dependencyValues:e}){return{setValue:{text:e.value?"true":"false"}}}},e.componentType={returnDependencies:()=>({}),definition:()=>({setValue:{componentType:"boolean"}})},e}static adapters=["value"];async updateBoolean({boolean:e,actionId:t}){if(!await this.stateValues.disabled){let n=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"value",value:e}],r={verb:"selected",object:{componentName:this.componentName,componentType:this.componentType},result:{response:e,responseText:e.toString()}},a=await this.stateValues.answerAncestor;return a&&(r.context={answerAncestor:a.componentName}),await this.coreFunctions.performUpdate({updateInstructions:n,event:r,actionId:t}),await this.coreFunctions.triggerChainedActions({componentName:this.componentName})}this.coreFunctions.resolveAction({actionId:t})}}class Choiceinput extends Input{constructor(e){super(e),Object.assign(this.actions,{updateSelectedIndices:this.updateSelectedIndices.bind(this)}),this.externalActions={},Object.defineProperty(this.externalActions,"submitAnswer",{enumerable:!0,get:async function(){let e=await this.stateValues.answerAncestor;return null!==e?{componentName:e.componentName,actionName:"submitAnswer"}:void 0}.bind(this)})}static componentType="choiceInput";static renderChildren=!0;static variableForPlainMacro="values";static variableForPlainCopy="values";static createsVariants=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.selectMultiple={createComponentOfType:"boolean",createStateVariable:"selectMultiple",defaultValue:!1,public:!0,forRenderer:!0,fallBackToParentStateVariable:"selectMultiple"},e.matchPartial={createComponentOfType:"boolean",createStateVariable:"matchPartial",defaultValue:!1,public:!0,fallBackToParentStateVariable:"matchPartial"},e.inline={createComponentOfType:"boolean"},e.shuffleOrder={createPrimitiveOfType:"boolean",createStateVariable:"shuffleOrder",defaultValue:!1,public:!0},e.preselectChoice={createComponentOfType:"number",createStateVariable:"preselectChoice",defaultValue:null},e.bindValueTo={createComponentOfType:"text"},e.placeHolder={createComponentOfType:"text",createStateVariable:"placeHolder",defaultValue:"",forRenderer:!0},e.submitLabel={createComponentOfType:"text",createStateVariable:"submitLabel",defaultValue:"Check Work",public:!0,forRenderer:!0,fallBackToParentStateVariable:"submitLabel"},e.submitLabelNoCorrectness={createComponentOfType:"text",createStateVariable:"submitLabelNoCorrectness",defaultValue:"Submit Response",public:!0,forRenderer:!0,fallBackToParentStateVariable:"submitLabelNoCorrectness"},e}static returnChildGroups(){return[{group:"choices",componentTypes:["choice"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.inline={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,defaultValue:!1,hasEssential:!0,returnDependencies:()=>({inlineAttr:{dependencyType:"attributeComponent",attributeName:"inline",variableNames:["value"]},parentInline:{dependencyType:"parentStateVariable",variableName:"inline"}}),definition:({dependencyValues:e})=>e.inlineAttr?{setValue:{inline:e.inlineAttr.stateValues.value}}:null!==e.parentInline?{setValue:{inline:e.parentInline}}:{useEssentialOrDefaultValue:{inline:{}}}},e.numberChoices={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({choiceChildren:{dependencyType:"child",childGroups:["choices"]}}),definition:({dependencyValues:e})=>({setValue:{numberChoices:e.choiceChildren.length}})},e.choiceOrder={forRenderer:!0,shadowVariable:!0,returnDependencies:({sharedParameters:e})=>({choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["text"]},shuffleOrder:{dependencyType:"stateVariable",variableName:"shuffleOrder"},variantSeed:{dependencyType:"value",value:e.variantSeed},rngClass:{dependencyType:"value",value:e.rngClass,doNotProxy:!0},variants:{dependencyType:"variants"}}),definition:function({dependencyValues:e}){let t,n=e.choiceChildren.length;if(e.shuffleOrder){let r=e.variants?.desiredVariant?.indices;if(void 0!==r)if(r.length!==n)console.warn("Ignoring indices specified for choiceInput as number of indices doesn't match number of choice children.");else{if(r=r.map(Number),!r.every(Number.isInteger))throw Error("All indices specified for choiceInput must be integers");if(r.every((e=>e>=1&&e<=n)))return{setValue:{choiceOrder:r}};console.warn("Ignoring indices specified for choiceInput as some indices out of range.")}let a=e.rngClass(e.variantSeed+"co");t=[...Array(n).keys()].map((e=>e+1));for(let e=n-1;e>0;e--){const n=a(),r=Math.floor(n*(e+1));[t[e],t[r]]=[t[r],t[e]]}}else t=[...Array(n).keys()].map((e=>e+1));return{setValue:{choiceOrder:t}}}},e.generatedVariantInfo={additionalStateVariablesDefined:["isVariantComponent"],returnDependencies:({componentInfoObjects:e,sharedParameters:t})=>({variantSeed:{dependencyType:"value",value:t.variantSeed},choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},shuffleOrder:{dependencyType:"stateVariable",variableName:"shuffleOrder"},variantDescendants:{dependencyType:"descendant",componentTypes:Object.keys(e.componentTypesCreatingVariants),variableNames:["isVariantComponent","generatedVariantInfo"],useReplacementsForComposites:!0,recurseToMatchedChildren:!1,variablesOptional:!0,includeNonActiveChildren:!0,ignoreReplacementsOfEncounteredComposites:!0}}),definition({dependencyValues:e,componentName:t}){let n={seed:e.variantSeed,meta:{createdBy:t}};e.shuffleOrder&&(n.indices=e.choiceOrder);let r=n.subvariants=[];for(let t of e.variantDescendants)t.stateValues.isVariantComponent?r.push(t.stateValues.generatedVariantInfo):t.stateValues.generatedVariantInfo&&r.push(...t.stateValues.generatedVariantInfo.subvariants);return{setValue:{generatedVariantInfo:n,isVariantComponent:!0}}}},e.choiceChildrenOrdered={additionalStateVariablesDefined:[{variableName:"numberChoices",public:!0,shadowingInstructions:{createComponentOfType:"number"}}],returnDependencies:()=>({choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},choiceChildren:{dependencyType:"child",childGroups:["choices"]}}),definition:function({dependencyValues:e}){let t=e.choiceChildren.length,n=e.choiceOrder.map((t=>e.choiceChildren[t-1]));return{setValue:{choiceChildrenOrdered:n,numberChoices:t}}}},e.choiceTexts={public:!0,shadowingInstructions:{createComponentOfType:"text"},isArray:!0,entryPrefixes:["choiceText"],forRenderer:!0,returnArraySizeDependencies:()=>({numberChoices:{dependencyType:"stateVariable",variableName:"numberChoices"}}),returnArraySize:({dependencyValues:e})=>[e.numberChoices],returnArrayDependenciesByKey:()=>({globalDependencies:{choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["text"]}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t=e.choiceOrder.map((t=>e.choiceChildren[t-1]));return{setValue:{choiceTexts:t.map((e=>e.stateValues.text))}}}},e.choiceMaths={public:!0,shadowingInstructions:{createComponentOfType:"math"},isArray:!0,entryPrefixes:["choiceMath"],forRenderer:!0,returnArraySizeDependencies:()=>({numberChoices:{dependencyType:"stateVariable",variableName:"numberChoices"}}),returnArraySize:({dependencyValues:e})=>[e.numberChoices],returnArrayDependenciesByKey:()=>({globalDependencies:{choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["math"]}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t=e.choiceOrder.map((t=>e.choiceChildren[t-1]));return{setValue:{choiceMaths:t.map((e=>e.stateValues.math))}}}},e.choicePreselects={isArray:!0,returnArraySizeDependencies:()=>({numberChoices:{dependencyType:"stateVariable",variableName:"numberChoices"}}),returnArraySize:({dependencyValues:e})=>[e.numberChoices],returnArrayDependenciesByKey:()=>({globalDependencies:{choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["preSelect"]}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t=e.choiceOrder.map((t=>e.choiceChildren[t-1]));return{setValue:{choicePreselects:t.map((e=>e.stateValues.preSelect))}}}},e.choicesDisabled={isArray:!0,forRenderer:!0,returnArraySizeDependencies:()=>({numberChoices:{dependencyType:"stateVariable",variableName:"numberChoices"}}),returnArraySize:({dependencyValues:e})=>[e.numberChoices],returnArrayDependenciesByKey:()=>({globalDependencies:{choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["disabled"]}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t=e.choiceOrder.map((t=>e.choiceChildren[t-1]));return{setValue:{choicesDisabled:t.map((e=>e.stateValues.disabled))}}}},e.choicesHidden={isArray:!0,forRenderer:!0,returnArraySizeDependencies:()=>({numberChoices:{dependencyType:"stateVariable",variableName:"numberChoices"}}),returnArraySize:({dependencyValues:e})=>[e.numberChoices],returnArrayDependenciesByKey:()=>({globalDependencies:{choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["hidden"]}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t=e.choiceOrder.map((t=>e.choiceChildren[t-1]));return{setValue:{choicesHidden:t.map((e=>e.stateValues.hidden))}}}},e.componentType={returnDependencies:()=>({choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["math"]}}),definition({dependencyValues:e}){let t="text";return e.choiceChildren.length>0&&e.choiceChildren.every((e=>e.stateValues.math))&&(t="math"),{setValue:{componentType:t}}}},e.indicesMatchedByBoundValue={returnDependencies:()=>({choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["text"]},bindValueTo:{dependencyType:"attributeComponent",attributeName:"bindValueTo",variableNames:["value"]},selectMultiple:{dependencyType:"stateVariable",variableName:"selectMultiple"}}),definition({dependencyValues:e}){let t=e.choiceOrder.map((t=>e.choiceChildren[t-1]));if(null!==e.bindValueTo){let n=t.map((e=>e.stateValues.text.toLowerCase().trim()));if(e.bindValueTo.stateValues.value){if(e.selectMultiple){let t=e.bindValueTo.stateValues.value.toLowerCase().split(",").map((e=>e.trim())),r=[];for(let e of t){let t=n.indexOf(e);-1===t||r.includes(t+1)||r.push(t+1)}return r.sort(((e,t)=>e-t)),{setValue:{indicesMatchedByBoundValue:r}}}{let t=n.indexOf(e.bindValueTo.stateValues.value.toLowerCase().trim());if(-1!==t)return{setValue:{indicesMatchedByBoundValue:[t+1]}}}}}return{setValue:{indicesMatchedByBoundValue:[]}}}},e.allSelectedIndices={hasEssential:!0,returnDependencies:()=>({choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["text"]},indicesMatchedByBoundValue:{dependencyType:"stateVariable",variableName:"indicesMatchedByBoundValue"},preselectChoice:{dependencyType:"stateVariable",variableName:"preselectChoice"},choicePreselects:{dependencyType:"stateVariable",variableName:"choicePreselects"},bindValueTo:{dependencyType:"attributeComponent",attributeName:"bindValueTo",variableNames:["value"]}}),definition:({dependencyValues:e})=>null!==e.bindValueTo?{setValue:{allSelectedIndices:e.indicesMatchedByBoundValue}}:{useEssentialOrDefaultValue:{allSelectedIndices:{get defaultValue(){let t=e.choicePreselects.indexOf(!0);return-1!==t?[t+1]:null!==e.preselectChoice?[e.preselectChoice]:[]}}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){if(null===t.bindValueTo)return{success:!0,instructions:[{setEssentialValue:"allSelectedIndices",value:e.allSelectedIndices}]};{let n="";if(e.allSelectedIndices.length>0){let r=t.choiceOrder.map((e=>t.choiceChildren[e-1])),a=[];for(let t of e.allSelectedIndices){let e=r[t-1];e&&a.push(e.stateValues.text)}n=a.join(", ")}return{success:!0,instructions:[{setDependency:"bindValueTo",desiredValue:n,variableIndex:0}]}}}},e.nSelectedIndices={returnDependencies:()=>({allSelectedIndices:{dependencyType:"stateVariable",variableName:"allSelectedIndices"}}),definition:({dependencyValues:e})=>({setValue:{nSelectedIndices:e.allSelectedIndices.length}})},e.selectedIndices={public:!0,shadowingInstructions:{createComponentOfType:"number"},isArray:!0,entryPrefixes:["selectedIndex"],forRenderer:!0,returnArraySizeDependencies:()=>({nSelectedIndices:{dependencyType:"stateVariable",variableName:"nSelectedIndices"}}),returnArraySize:({dependencyValues:e})=>[e.nSelectedIndices],returnArrayDependenciesByKey:()=>({globalDependencies:{allSelectedIndices:{dependencyType:"stateVariable",variableName:"allSelectedIndices"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n in e.allSelectedIndices)t[n]=e.allSelectedIndices[n];return{setValue:{selectedIndices:t}}}},e.selectedIndex={isAlias:!0,targetVariableName:"selectedIndex1"},e.selectedValues={public:!0,shadowingInstructions:{hasVariableComponentType:!0},isArray:!0,entryPrefixes:["selectedValue"],returnArraySizeDependencies:()=>({nSelectedIndices:{dependencyType:"stateVariable",variableName:"nSelectedIndices"}}),returnArraySize:({dependencyValues:e})=>[e.nSelectedIndices],returnArrayDependenciesByKey:()=>({globalDependencies:{selectedIndices:{dependencyType:"stateVariable",variableName:"selectedIndices"},choiceTexts:{dependencyType:"stateVariable",variableName:"choiceTexts"},choiceMaths:{dependencyType:"stateVariable",variableName:"choiceMaths"},componentType:{dependencyType:"stateVariable",variableName:"componentType"}}}),arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t}){let n={},r=e.componentType;for(let a of t)n[a]="math"===r?e.choiceMaths[e.selectedIndices[a]-1]:e.choiceTexts[e.selectedIndices[a]-1];return{setValue:{selectedValues:n},setCreateComponentOfType:{selectedValues:r}}}},e.selectedValue={isAlias:!0,targetVariableName:"selectedValue1"},e.values={isAlias:!0,targetVariableName:"selectedValues"},e.nValues={isAlias:!0,targetVariableName:"nSelectedIndices"},e.childIndicesSelected={returnDependencies:()=>({selectedIndices:{dependencyType:"stateVariable",variableName:"selectedIndices"},choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"}}),definition({dependencyValues:e}){let t=e.selectedIndices.map((t=>e.choiceOrder[t-1]));return{setValue:{childIndicesSelected:t}}}},e.creditAchievedIfSubmit={returnDependencies:()=>({choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["selected","credit"]},selectMultiple:{dependencyType:"stateVariable",variableName:"selectMultiple"},matchPartial:{dependencyType:"stateVariable",variableName:"matchPartial"}}),definition:function({dependencyValues:e}){let t=0;if(e.selectMultiple){let n=0,r=0,a=0;for(let t of e.choiceChildren)t.stateValues.selected?1===t.stateValues.credit?n++:r++:1===t.stateValues.credit&&a++;if(e.matchPartial){let e=n+r+a;t=0===e?1:n/e}else r+a===0&&(t=1)}else for(let n of e.choiceChildren)if(n.stateValues.selected){t=n.stateValues.credit;break}return{setValue:{creditAchievedIfSubmit:t}}}},e.valueToRecordOnSubmit={isAlias:!0,targetVariableName:"selectedIndices"},e.submittedIndices={returnDependencies:()=>({choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["submitted"]}}),definition({dependencyValues:e}){let t=[],n=e.choiceOrder.map((t=>e.choiceChildren[t-1]));for(let[e,r]of n.entries())r.stateValues.submitted&&t.push(e+1);return{setValue:{submittedIndices:t}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){let n=[];for(let[r,a]of t.choiceOrder.entries())n.push({setDependency:"choiceChildren",desiredValue:e.submittedIndices.includes(r+1),variableIndex:0,childIndex:a-1});return{success:!0,instructions:n}}},e.valueRecordedAtSubmit={isAlias:!0,targetVariableName:"submittedIndices"},e.allFeedbacks={returnDependencies:()=>({choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["feedbacks"]}}),definition({dependencyValues:e}){let t=e.choiceOrder.map((t=>e.choiceChildren[t-1])),n=[];for(let e of t)n.push(...e.stateValues.feedbacks);return{setValue:{allFeedbacks:n}}}},e.numberFeedbacks={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({allFeedbacks:{dependencyType:"stateVariable",variableName:"allFeedbacks"}}),definition:({dependencyValues:e})=>({setValue:{numberFeedbacks:e.allFeedbacks.length},checkForActualChange:{numberFeedbacks:!0}})},e.feedbacks={public:!0,shadowingInstructions:{createComponentOfType:"feedback"},isArray:!0,entryPrefixes:["feedback"],returnArraySizeDependencies:()=>({numberFeedbacks:{dependencyType:"stateVariable",variableName:"numberFeedbacks"}}),returnArraySize:({dependencyValues:e})=>[e.numberFeedbacks],returnArrayDependenciesByKey:()=>({globalDependencies:{allFeedbacks:{dependencyType:"stateVariable",variableName:"allFeedbacks"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n=0;nr[e-1]))}},i=await this.stateValues.answerAncestor;return i&&(a.context={answerAncestor:i.componentName}),await this.coreFunctions.performUpdate({updateInstructions:n,actionId:t,event:a}),await this.coreFunctions.triggerChainedActions({componentName:this.componentName})}this.coreFunctions.resolveAction({actionId:t})}static setUpVariant({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n}){setUpVariantSeedAndRng({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n})}static determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t}){if(!e.attributes?.shuffleOrder?.primitive)return super.determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t});let n=0;for(let r of e.children)if("choice"===r.componentType)n++;else{if(!t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"_composite"})||"choice"!==r.attributes.createComponentOfType?.primitive)return{success:!1};if(void 0!==r.attributes.nComponents?.primitive){let e=Number(r.attributes.nComponents?.primitive);if(!(Number.isInteger(e)&&e>=0))return{success:!1};n+=e}else n++}let r=1;for(let e=2;e<=n;e++)r*=e;let a=super.determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t});if(!a.success)return{success:!1};let i=a.numberOfVariants*r;return e.variants.numberOfVariants=i,e.variants.uniqueVariantData={numberOfVariantsByDescendant:e.variants.uniqueVariantData.numberOfVariantsByDescendant,numberOfPermutations:r,numberOfChoices:n},{success:!0,numberOfVariants:i}}static getUniqueVariant({serializedComponent:e,variantIndex:t,componentInfoObjects:n}){let r=e.variants?.numberOfVariants;if(void 0===r)return{success:!1};if(!Number.isInteger(t)||t<1||t>r)return{success:!1};if(!e.attributes.shuffleOrder?.primitive)return super.getUniqueVariant({serializedComponent:e,variantIndex:t,componentInfoObjects:n});let a=e.variants.uniqueVariantData.numberOfVariantsByDescendant,i=e.variants.descendantVariantComponents,s=e.variants.uniqueVariantData.numberOfPermutations,o=e.variants.uniqueVariantData.numberOfChoices,l=[...a];l.push(s);let u=enumerateCombinations({numberOfOptionsByIndex:l,maxNumber:t})[t-1].map((e=>e+1)),c=u.pop(),p=u,d=[...Array(o).keys()].map((e=>e+1)),m=enumeratePermutations({values:d,maxNumber:c})[c-1],h=!1,f=[];for(let e=0;e1){let t=i[e],r=n.allComponentClasses[t.componentType].getUniqueVariant({serializedComponent:t,variantIndex:p[e],componentInfoObjects:n});if(!r.success)return{success:!1};f.push(r.desiredVariant),h=!0}else f.push({});let y={indices:m};return h&&(y.subvariants=f),{success:!0,desiredVariant:y}}}class Choice extends InlineComponent{static componentType="choice";static rendererType="containerInline";static renderChildren=!0;static variableForPlainMacro="submitted";static variableForPlainCopy="submitted";static createAttributesObject(){let e=super.createAttributesObject();return e.credit={createComponentOfType:"number",createStateVariable:"credit",defaultValue:0,public:!0,attributesForCreatedComponent:{convertBoolean:!0}},e.feedbackCodes={createComponentOfType:"textList",createStateVariable:"feedbackCodes",defaultValue:[],public:!0},e.feedbackText={createComponentOfType:"text",createStateVariable:"feedbackText",defaultValue:null,public:!0},e.preSelect={createComponentOfType:"boolean",createStateVariable:"preSelect",defaultValue:!1},e}static returnChildGroups(){return[{group:"children",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["children"],variableNames:["text"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let t="";for(let n of e.inlineChildren)"object"!=typeof n?t+=n.toString():"string"==typeof n.stateValues.text&&(t+=n.stateValues.text);return{setValue:{text:t}}}},e.math={public:!0,shadowingInstructions:{createComponentOfType:"math"},returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["children"],variableNames:["value","latex"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let t=null;if(1===e.inlineChildren.length){let n=e.inlineChildren[0];if("object"==typeof n){let e=n.stateValues.value;if(e instanceof me$3.class)t=e;else if("number"==typeof e)t=me$3.fromAst(e);else if("string"==typeof n.stateValues.latex)try{t=me$3.fromLatex(n.stateValues.latex)}catch(e){}}}return{setValue:{math:t}}}},e.selected={defaultValue:!1,public:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({countAmongSiblings:{dependencyType:"countAmongSiblingsOfSameType"},childIndicesSelected:{dependencyType:"parentStateVariable",parentComponentType:"choiceInput",variableName:"childIndicesSelected"},primaryShadow:{dependencyType:"primaryShadow",variableNames:["selected"]}}),definition({dependencyValues:e,componentName:t}){let n;return n=e.childIndicesSelected?e.childIndicesSelected.includes(e.countAmongSiblings):!!e.primaryShadow&&e.primaryShadow.stateValues.selected,{setValue:{selected:n}}}},e.submitted={defaultValue:!1,hasEssential:!0,public:!0,shadowingInstructions:{createComponentOfType:"boolean"},doNotShadowEssential:!0,returnDependencies:()=>({primaryShadow:{dependencyType:"primaryShadow",variableNames:["submitted"]}}),definition:({dependencyValues:e})=>e.primaryShadow?{setValue:{submitted:e.primaryShadow.stateValues.submitted}}:{useEssentialOrDefaultValue:{submitted:!0}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){return t.primaryShadow?{success:!1}:{success:!0,instructions:[{setEssentialValue:"submitted",value:e.submitted}]}}},e.feedbacks={public:!0,shadowingInstructions:{createComponentOfType:"feedbacktext"},returnDependencies:()=>({feedbackText:{dependencyType:"stateVariable",variableName:"feedbackText"},feedbackCodes:{dependencyType:"stateVariable",variableName:"feedbackCodes"},feedbackDefinitionAncestor:{dependencyType:"ancestor",variableNames:["feedbackDefinitions"]},submitted:{dependencyType:"stateVariable",variableName:"submitted"}}),definition({dependencyValues:e}){if(!e.submitted)return{setValue:{feedbacks:[]}};let t=[],n=e.feedbackDefinitionAncestor.stateValues.feedbackDefinitions;for(let r of e.feedbackCodes){let e=n[r.toLowerCase()];e&&t.push(e)}return null!==e.feedbackText&&t.push(e.feedbackText),{setValue:{feedbacks:t}}}},e}static includeBlankStringChildren=!0;static adapters=["text","math"]}class NumberComponent extends InlineComponent{static componentType="number";static variableForPlainMacro="value";static createAttributesObject(){let e=super.createAttributesObject();return e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer"},e.displaySmallAsZero={createComponentOfType:"number",valueForTrue:1e-14,valueForFalse:0},e.padZeros={createComponentOfType:"boolean"},e.renderAsMath={createComponentOfType:"boolean",createStateVariable:"renderAsMath",defaultValue:!1,public:!0,forRenderer:!0},e.convertBoolean={createPrimitiveOfType:"boolean",createStateVariable:"convertBoolean",defaultValue:!1},e.valueOnNaN={createPrimitiveOfType:"number",createStateVariable:"valueOnNaN",defaultValue:NaN},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({childrenRegex:/..+/,replacementFunction:({matchedChildren:e,componentAttributes:t})=>({success:!t.convertBoolean,newChildren:[{componentType:"math",children:e}]})}),e}static returnChildGroups(){return[{group:"strings",componentTypes:["string"]},{group:"numbers",componentTypes:["number"]},{group:"maths",componentTypes:["math"]},{group:"texts",componentTypes:["text"]},{group:"booleans",componentTypes:["boolean"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({numberListParentDisplayDigits:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"displayDigits"},mathListParentDisplayDigits:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"displayDigits"},numberListParentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"displayDecimals"},mathListParentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"displayDecimals"},displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},numberMathChildren:{dependencyType:"child",childGroups:["numbers","maths"],variableNames:["displayDigits"]},otherChildren:{dependencyType:"child",childGroups:["strings","texts","booleans"]}}),definition({dependencyValues:e,usedDefault:t}){let n,r=!1;if(null!==e.numberListParentDisplayDigits){if(!t.numberListParentDisplayDigits)return{setValue:{displayDigits:e.numberListParentDisplayDigits}};r=!0,n=e.numberListParentDisplayDigits}if(null!==e.mathListParentDisplayDigits){if(!t.mathListParentDisplayDigits)return{setValue:{displayDigits:e.mathListParentDisplayDigits}};r=!0,n=e.mathListParentDisplayDigits}let a=null!==e.numberListParentDisplayDecimals&&!t.numberListParentDisplayDecimals||null!==e.mathListParentDisplayDecimals&&!t.mathListParentDisplayDecimals,i=null===e.displayDigitsAttr||t.displayDigitsAttr,s=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!i&&!s){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({numberListParentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"displayDecimals"},mathListParentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"displayDecimals"},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},numberMathChildren:{dependencyType:"child",childGroups:["numbers","maths"],variableNames:["displayDecimals"]},otherChildren:{dependencyType:"child",childGroups:["strings","texts","booleans"]}}),definition({dependencyValues:e,usedDefault:t}){let n,r=!1;if(null!==e.numberListParentDisplayDecimals){if(!t.numberListParentDisplayDecimals)return{setValue:{displayDecimals:e.numberListParentDisplayDecimals}};r=!0,n=e.numberListParentDisplayDecimals}if(null!==e.mathListParentDisplayDecimals){if(!t.mathListParentDisplayDecimals)return{setValue:{displayDecimals:e.mathListParentDisplayDecimals}};r=!0,n=e.mathListParentDisplayDecimals}if(null!==e.displayDecimalsAttr){if(!t.displayDecimalsAttr)return{setValue:{displayDecimals:e.displayDecimalsAttr.stateValues.value}};r=!0,n=e.displayDecimalsAttr.stateValues.value}if(1===e.numberMathChildren.length&&0===e.otherChildren.length){if(!t.numberMathChildren[0]||!t.numberMathChildren[0].displayDecimals)return{setValue:{displayDecimals:e.numberMathChildren[0].stateValues.displayDecimals}};r=!0,n=e.numberMathChildren[0].stateValues.displayDecimals}return r?{useEssentialOrDefaultValue:{displayDecimals:{defaultValue:n}}}:{useEssentialOrDefaultValue:{displayDecimals:!0}}}},e.displaySmallAsZero={public:!0,shadowingInstructions:{createComponentOfType:"number"},hasEssential:!0,defaultValue:0,returnDependencies:()=>({numberListParentDisplaySmallAsZero:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"displaySmallAsZero"},mathListParentDisplaySmallAsZero:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"displaySmallAsZero"},displaySmallAsZeroAttr:{dependencyType:"attributeComponent",attributeName:"displaySmallAsZero",variableNames:["value"]},numberMathChildren:{dependencyType:"child",childGroups:["numbers","maths"],variableNames:["displaySmallAsZero"]},otherChildren:{dependencyType:"child",childGroups:["strings","texts","booleans"]}}),definition({dependencyValues:e,usedDefault:t}){let n,r=!1;if(null!==e.numberListParentDisplaySmallAsZero){if(!t.numberListParentDisplaySmallAsZero)return{setValue:{displaySmallAsZero:e.numberListParentDisplaySmallAsZero}};r=!0,n=e.numberListParentDisplaySmallAsZero}if(null!==e.mathListParentDisplaySmallAsZero){if(!t.mathListParentDisplaySmallAsZero)return{setValue:{displaySmallAsZero:e.mathListParentDisplaySmallAsZero}};r=!0,n=e.mathListParentDisplaySmallAsZero}if(null!==e.displaySmallAsZeroAttr){if(!t.displaySmallAsZeroAttr)return{setValue:{displaySmallAsZero:e.displaySmallAsZeroAttr.stateValues.value}};r=!0,n=e.displaySmallAsZeroAttr.stateValues.value}if(1===e.numberMathChildren.length&&0===e.otherChildren.length){if(!t.numberMathChildren[0]||!t.numberMathChildren[0].displaySmallAsZero)return{setValue:{displaySmallAsZero:e.numberMathChildren[0].stateValues.displaySmallAsZero}};r=!0,n=e.numberMathChildren[0].stateValues.displaySmallAsZero}return r?{useEssentialOrDefaultValue:{displaySmallAsZero:{defaultValue:n}}}:{useEssentialOrDefaultValue:{displaySmallAsZero:!0}}}},e.padZeros={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},hasEssential:!0,defaultValue:!1,returnDependencies:()=>({numberListParentPadZeros:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"padZeros"},mathListParentPadZeros:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"padZeros"},padZerosAttr:{dependencyType:"attributeComponent",attributeName:"padZeros",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},numberMathChildren:{dependencyType:"child",childGroups:["numbers","maths"],variableNames:["padZeros"]},otherChildren:{dependencyType:"child",childGroups:["strings","texts","booleans"]}}),definition({dependencyValues:e,usedDefault:t}){let n,r=!1;if(null!==e.numberListParentPadZeros){if(!t.numberListParentPadZeros)return{setValue:{padZeros:e.numberListParentPadZeros}};r=!0,n=e.numberListParentPadZeros}if(null!==e.mathListParentPadZeros){if(!t.mathListParentPadZeros)return{setValue:{padZeros:e.mathListParentPadZeros}};r=!0,n=e.mathListParentPadZeros}if(null!==e.padZerosAttr){if(!t.padZerosAttr)return{setValue:{padZeros:e.padZerosAttr.stateValues.value}};r=!0,n=e.padZerosAttr.stateValues.value}if(1===e.numberMathChildren.length&&0==e.otherChildren.length){if(!t.numberMathChildren[0]||!t.numberMathChildren[0].padZeros)return{setValue:{padZeros:e.numberMathChildren[0].stateValues.padZeros}};r=!0,n=e.numberMathChildren[0].stateValues.padZeros}return r?{useEssentialOrDefaultValue:{padZeros:{defaultValue:n}}}:{useEssentialOrDefaultValue:{padZeros:!0}}}},e.singleNumberOrStringChild={additionalStateVariablesDefined:["singleMathChild"],returnDependencies:()=>({numberChildren:{dependencyType:"child",childGroups:["numbers"]},stringChildren:{dependencyType:"child",childGroups:["strings"]},mathChildren:{dependencyType:"child",childGroups:["maths"]},booleanChildren:{dependencyType:"child",childGroups:["booleans"]},textChildren:{dependencyType:"child",childGroups:["texts"]}}),definition({dependencyValues:e}){let t=e.numberChildren.length+e.stringChildren.length,n=e.mathChildren.length,r=e.booleanChildren.length+e.textChildren.length;return{setValue:{singleNumberOrStringChild:t<=1&&n+r===0,singleMathChild:1===n&&t+r===0}}}},e.parsedExpression={additionalStateVariablesDefined:["codePre"],returnDependencies:()=>({allChildren:{dependencyType:"child",childGroups:["strings","numbers","maths","texts","booleans"]},stringChildren:{dependencyType:"child",childGroups:["strings"],variableNames:["value"]}}),definition:buildParsedExpression},e.mathChildrenByCode={additionalStateVariablesDefined:["textChildrenByCode","numberChildrenByCode","booleanChildrenByCode"],returnDependencies:()=>({allChildren:{dependencyType:"child",childGroups:["strings","numbers","maths","texts","booleans"],variableNames:["value","texts","maths","booleans"],variablesOptional:!0},codePre:{dependencyType:"stateVariable",variableName:"codePre"}}),definition({dependencyValues:e,componentInfoObjects:t}){let n={},r={},a={},i={},s=0,o=e.codePre;for(let l of e.allChildren)if("string"!=typeof l){let e=o+s;t.isInheritedComponentType({inheritedComponentType:l.componentType,baseComponentType:"math"})?n[e]=l:t.isInheritedComponentType({inheritedComponentType:l.componentType,baseComponentType:"number"})?r[e]=l:t.isInheritedComponentType({inheritedComponentType:l.componentType,baseComponentType:"text"})?a[e]=l:i[e]=l,s+=1}return{setValue:{mathChildrenByCode:n,numberChildrenByCode:r,textChildrenByCode:a,booleanChildrenByCode:i}}}},e.value={public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"],addAttributeComponentsShadowingStateVariables:{fixed:{stateVariableToShadow:"fixed"}}},hasEssential:!0,stateVariablesDeterminingDependencies:["singleNumberOrStringChild"],returnDependencies:({stateValues:e})=>e.singleNumberOrStringChild?{singleNumberOrStringChild:{dependencyType:"stateVariable",variableName:"singleNumberOrStringChild"},convertBoolean:{dependencyType:"stateVariable",variableName:"convertBoolean"},numberChild:{dependencyType:"child",childGroups:["numbers"],variableNames:["value"]},stringChild:{dependencyType:"child",childGroups:["strings"],variableNames:["value"]},valueOnNaN:{dependencyType:"stateVariable",variableName:"valueOnNaN"}}:{singleNumberOrStringChild:{dependencyType:"stateVariable",variableName:"singleNumberOrStringChild"},singleMathChild:{dependencyType:"stateVariable",variableName:"singleMathChild"},convertBoolean:{dependencyType:"stateVariable",variableName:"convertBoolean"},parsedExpression:{dependencyType:"stateVariable",variableName:"parsedExpression"},allChildren:{dependencyType:"child",childGroups:["strings","numbers","maths","texts","booleans"],variableNames:["value","texts","maths","unordered"],variablesOptional:!0},booleanChildrenByCode:{dependencyType:"stateVariable",variableName:"booleanChildrenByCode"},textChildrenByCode:{dependencyType:"stateVariable",variableName:"textChildrenByCode"},mathChildrenByCode:{dependencyType:"stateVariable",variableName:"mathChildrenByCode"},numberChildrenByCode:{dependencyType:"stateVariable",variableName:"numberChildrenByCode"},valueOnNaN:{dependencyType:"stateVariable",variableName:"valueOnNaN"}},definition({dependencyValues:e,componentInfoObjects:t}){if(e.singleNumberOrStringChild){if(0===e.numberChild.length){if(0===e.stringChild.length)return{useEssentialOrDefaultValue:{value:{defaultValue:e.valueOnNaN}}};let n=Number(e.stringChild[0]);if(Number.isNaN(n))try{if(n=me$3.fromAst(textToAst$1.convert(e.stringChild[0])).evaluate_to_constant(),"boolean"==typeof n)n=e.convertBoolean?n?1:0:e.valueOnNaN;else if(null===n||Number.isNaN(n))if(e.convertBoolean){n=evaluateLogic({logicTree:buildParsedExpression({dependencyValues:{stringChildren:e.stringChild,allChildren:e.stringChild},componentInfoObjects:t}).setValue.parsedExpression.tree,dependencyValues:{booleanChildrenByCode:{},booleanListChildrenByCode:{},textChildrenByCode:{},textListChildrenByCode:{},mathChildrenByCode:{},mathListChildrenByCode:{},numberChildrenByCode:{},numberListChildrenByCode:{},otherChildrenByCode:{}},valueOnInvalid:e.valueOnNaN})}else n=e.valueOnNaN;else n?.re===1/0||n?.re===-1/0||n?.im===1/0||n?.im===-1/0?n=numberToMathExpression(n).evaluate_to_constant():0===n?.im&&(n=n.re)}catch(t){n=e.valueOnNaN}return{setValue:{value:n}}}{let t=e.numberChild[0].stateValues.value;return Number.isNaN(t)&&(t=e.valueOnNaN),{setValue:{value:t}}}}if(null===e.parsedExpression)return{setValue:{value:e.valueOnNaN}};if(0===Object.keys(e.textChildrenByCode).length&&0===Object.keys(e.booleanChildrenByCode).length){let t,n=function(t){if("string"==typeof t){let n=e.mathChildrenByCode[t];return void 0!==n?n.stateValues.value.tree:(n=e.numberChildrenByCode[t],void 0!==n?numberToMathExpression(n.stateValues.value).tree:t)}return Array.isArray(t)?[t[0],...t.slice(1).map(n)]:t};try{t=me$3.fromAst(n(e.parsedExpression.tree)).evaluate_to_constant()}catch(n){t=e.valueOnNaN}if(!Number.isNaN(t)&&("number"==typeof t||"number"==typeof t?.re&&"number"==typeof t?.im))return t.re===1/0||t.re===-1/0||t.im===1/0||t.im===-1/0?t=numberToMathExpression(t).evaluate_to_constant():0===t.im&&(t=t.re),{setValue:{value:t}}}if(!e.convertBoolean)return{setValue:{value:e.valueOnNaN}};return(e=Object.assign({},e)).mathListChildrenByCode={},e.numberListChildrenByCode={},e.textListChildrenByCode={},e.booleanListChildrenByCode={},e.otherChildrenByCode={},{setValue:{value:evaluateLogic({logicTree:e.parsedExpression.tree,dependencyValues:e,valueOnInvalid:e.valueOnNaN})}}},set:function(e){if(null===e)return NaN;if("number"==typeof e||"number"==typeof e?.re&&"number"==typeof e?.im)return e;let t=Number(e);if(Number.isNaN(t))try{t=me$3.fromAst(textToAst$1.convert(e)).evaluate_to_constant(),null===t&&(t=NaN)}catch(e){t=NaN}return t},inverseDefinition:async function({desiredStateVariableValues:e,dependencyValues:t,stateValues:n,overrideFixed:r}){if(!await n.canBeModified&&!r)return{success:!1};let a,i=e.value;return i instanceof me$3.class?(i=i.evaluate_to_constant(),(Number.isNaN(i)||"number"!=typeof i&&("number"!=typeof i?.re||"number"!=typeof i?.im))&&(i=t.valueOnNaN)):(Number.isNaN(i)||"number"!=typeof i&&("number"!=typeof i?.re||"number"!=typeof i?.im))&&(i=Number(i),Number.isNaN(i)&&(i=t.valueOnNaN)),t.singleNumberOrStringChild?(a=0===t.numberChild.length?0===t.stringChild.length?[{setEssentialValue:"value",value:numberToMathExpression(i).evaluate_to_constant()}]:[{setDependency:"stringChild",desiredValue:numberToMathExpression(i).toString(),childIndex:0,variableIndex:0}]:[{setDependency:"numberChild",desiredValue:i,childIndex:0,variableIndex:0}],{success:!0,instructions:a}):t.singleMathChild?{success:!0,instructions:[{setDependency:"allChildren",desiredValue:numberToMathExpression(i),childIndex:0,variableIndex:0}]}:{success:!1}}},e.valueForDisplay={returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"}}),definition:function({dependencyValues:e,usedDefault:t}){return{setValue:{valueForDisplay:roundForDisplay({value:numberToMathExpression(e.value),dependencyValues:e,usedDefault:t}).evaluate_to_constant()}}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({valueForDisplay:{dependencyType:"stateVariable",variableName:"valueForDisplay"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},value:{dependencyType:"stateVariable",variableName:"value"}}),definition:function({dependencyValues:e,usedDefault:t}){let n={};return e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(n.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(n.padToDigits=e.displayDigits)),{setValue:{text:numberToMathExpression(e.valueForDisplay).toString(n)}}},async inverseDefinition({desiredStateVariableValues:e,stateValues:t}){let n=Number(e.text);if(Number.isFinite(n))return{success:!0,instructions:[{setDependency:"value",desiredValue:n}]};{let t,r=getFromText({parseScientificNotation:!1});try{t=r(e.text)}catch(e){return{success:!1}}return n=t.evaluate_to_constant(),Number.isFinite(n)?{success:!0,instructions:[{setDependency:"value",desiredValue:n}]}:{success:!1}}}},e.math=mathStateVariableFromNumberStateVariable({numberVariableName:"value",mathVariableName:"math",isPublic:!0}),e.math.shadowingInstructions.attributesToShadow=["displayDigits","displayDecimals","displaySmallAsZero","padZeros"],e.latex={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({valueForDisplay:{dependencyType:"stateVariable",variableName:"valueForDisplay"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"}}),definition({dependencyValues:e,usedDefault:t}){let n={};return e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(n.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(n.padToDigits=e.displayDigits)),{setValue:{latex:numberToMathExpression(e.valueForDisplay).toLatex(n)}}}},e.canBeModified={returnDependencies:()=>({numberChildModifiable:{dependencyType:"child",childGroups:["numbers"],variableNames:["canBeModified"]},modifyIndirectly:{dependencyType:"stateVariable",variableName:"modifyIndirectly"},fixed:{dependencyType:"stateVariable",variableName:"fixed"},singleNumberOrStringChild:{dependencyType:"stateVariable",variableName:"singleNumberOrStringChild"},singleMathChild:{dependencyType:"stateVariable",variableName:"singleMathChild"}}),definition:function({dependencyValues:e}){return!e.modifyIndirectly||e.fixed||!e.singleNumberOrStringChild&&!e.singleMathChild?{setValue:{canBeModified:!1}}:1!==e.numberChildModifiable.length||e.numberChildModifiable[0].stateValues.canBeModified?{setValue:{canBeModified:!0}}:{setValue:{canBeModified:!1}}}},e}static adapters=[{stateVariable:"math",stateVariablesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},"text"]}class Integer extends NumberComponent{static componentType="integer";static rendererType="number";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return renameStateVariable({stateVariableDefinitions:e,oldName:"value",newName:"valuePreRound"}),e.value={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({valuePreRound:{dependencyType:"stateVariable",variableName:"valuePreRound"}}),set:function(e){if(null===e)return NaN;let t=Number(e);if(Number.isNaN(t))try{t=me$3.fromAst(textToAst.convert(e)).evaluate_to_constant(),null===t&&(t=NaN)}catch(e){t=NaN}return Math.round(t)},definition:({dependencyValues:e})=>({setValue:{value:Math.round(e.valuePreRound)}}),inverseDefinition({desiredStateVariableValues:e}){let t=e.value;return t instanceof me$3.class?(t=t.evaluate_to_constant(),Number.isFinite(t)||(t=NaN)):t=Number(t),t=Math.round(t),{success:!0,instructions:[{setDependency:"valuePreRound",desiredValue:t}]}}},e}}const maxWidth=850,sizePossibilities=["tiny","small","medium","large","full"],widthFractions=[1/12,.3,.5,.7,1],fractionMidpoints=widthFractions.map(((e,t)=>(e+(widthFractions[t+1]||1/0))/2)),orderedWidthMidpoints=fractionMidpoints.map((e=>maxWidth*e)),orderedPercentWidthMidpoints=fractionMidpoints.map((e=>100*e)),widthsBySize={};sizePossibilities.forEach(((e,t)=>widthsBySize[e]=Math.floor(widthFractions[t]*maxWidth)));const percentWidthsBySize={};sizePossibilities.forEach(((e,t)=>percentWidthsBySize[e]=Math.round(100*widthFractions[t])));class Graph$1 extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{changeAxisLimits:this.changeAxisLimits.bind(this),addChildren:this.addChildren.bind(this),deleteChildren:this.deleteChildren.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="graph";static renderChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.xmin={createComponentOfType:"number",createStateVariable:"xminPrelim",defaultValue:-10},e.xmax={createComponentOfType:"number",createStateVariable:"xmaxPrelim",defaultValue:10},e.ymin={createComponentOfType:"number",createStateVariable:"yminPrelim",defaultValue:-10},e.ymax={createComponentOfType:"number",createStateVariable:"ymaxPrelim",defaultValue:10},e.width={createComponentOfType:"_componentSize"},e.size={createComponentOfType:"text"},e.aspectRatio={createComponentOfType:"number"},e.height={createComponentOfType:"_componentSize"},e.displayMode={createComponentOfType:"text",createStateVariable:"displayMode",validValues:["block","inline"],defaultValue:"block",forRenderer:!0,public:!0},e.horizontalAlign={createComponentOfType:"text",createStateVariable:"horizontalAlign",validValues:["center","left","right"],defaultValue:"center",forRenderer:!0,public:!0},e.identicalAxisScales={createPrimitiveOfType:"boolean",createStateVariable:"identicalAxisScales",defaultValue:!1,public:!0},e.displayXAxis={createComponentOfType:"boolean",createStateVariable:"displayXAxis",defaultValue:!0,public:!0,forRenderer:!0},e.displayYAxis={createComponentOfType:"boolean",createStateVariable:"displayYAxis",defaultValue:!0,public:!0,forRenderer:!0},e.displayXAxisTickLabels={createComponentOfType:"boolean",createStateVariable:"displayXAxisTickLabels",defaultValue:!0,public:!0,forRenderer:!0},e.displayYAxisTickLabels={createComponentOfType:"boolean",createStateVariable:"displayYAxisTickLabels",defaultValue:!0,public:!0,forRenderer:!0},e.xlabel={createComponentOfType:"label"},e.xlabelPosition={createComponentOfType:"text",createStateVariable:"xlabelPosition",defaultValue:"right",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["right","left"]},e.xTickScaleFactor={createComponentOfType:"math",createStateVariable:"xTickScaleFactor",defaultValue:null,public:!0,forRenderer:!0},e.ylabel={createComponentOfType:"label"},e.ylabelPosition={createComponentOfType:"text",createStateVariable:"ylabelPosition",defaultValue:"top",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["top","bottom"]},e.ylabelAlignment={createComponentOfType:"text",createStateVariable:"ylabelAlignment",defaultValue:"left",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["left","right"]},e.yTickScaleFactor={createComponentOfType:"math",createStateVariable:"yTickScaleFactor",defaultValue:null,public:!0,forRenderer:!0},e.showNavigation={createComponentOfType:"boolean",createStateVariable:"showNavigation",defaultValue:!0,public:!0,forRenderer:!0},e.fixAxes={createComponentOfType:"boolean",createStateVariable:"fixAxes",defaultValue:!1,public:!0,forRenderer:!0},e.grid={createComponentOfType:"text"},e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.padZeros={createComponentOfType:"boolean",createStateVariable:"padZeros",defaultValue:!1,public:!0},e}static returnChildGroups(){return[{group:"xlabels",componentTypes:["xlabel"]},{group:"ylabels",componentTypes:["ylabel"]},{group:"graphical",componentTypes:["_graphical","text","image","math","m","md","label"]},{group:"childrenThatShouldNotBeHere",componentTypes:["_base"],matchAfterAdapters:!0}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.displayDigitsAttr){let n=t.displayDigitsAttr,r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!n&&!r){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({xlabelAttr:{dependencyType:"attributeComponent",attributeName:"xlabel",variableNames:["value","hasLatex"]},xlabelChild:{dependencyType:"child",childGroups:["xlabels"],variableNames:["value","hasLatex"]}}),definition({dependencyValues:e}){if(e.xlabelChild.length>0){let t=e.xlabelChild[e.xlabelChild.length-1];return{setValue:{xlabel:t.stateValues.value,xlabelHasLatex:t.stateValues.hasLatex}}}return e.xlabelAttr?{setValue:{xlabel:e.xlabelAttr.stateValues.value,xlabelHasLatex:e.xlabelAttr.stateValues.hasLatex}}:{useEssentialOrDefaultValue:{xlabel:!0},setValue:{xlabelHasLatex:!1}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){if("string"!=typeof e.xlabel)return{success:!1};if(t.xlabelChild.length>0){let n=t.xlabelChild.length-1;return{success:!0,instructions:[{setDependency:"xlabelChild",desiredValue:e.xlabel,childIndex:n,variableIndex:0}]}}return{success:!0,instructions:[{setEssentialValue:"xlabel",value:e.xlabel}]}}},e.ylabel={forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"label",addStateVariablesShadowingStateVariables:{hasLatex:{stateVariableToShadow:"ylabelHasLatex"}}},hasEssential:!0,defaultValue:"",additionalStateVariablesDefined:[{variableName:"ylabelHasLatex",forRenderer:!0}],returnDependencies:()=>({ylabelAttr:{dependencyType:"attributeComponent",attributeName:"ylabel",variableNames:["value","hasLatex"]},ylabelChild:{dependencyType:"child",childGroups:["ylabels"],variableNames:["value","hasLatex"]}}),definition({dependencyValues:e}){if(e.ylabelChild.length>0){let t=e.ylabelChild[e.ylabelChild.length-1];return{setValue:{ylabel:t.stateValues.value,ylabelHasLatex:t.stateValues.hasLatex}}}return e.ylabelAttr?{setValue:{ylabel:e.ylabelAttr.stateValues.value,ylabelHasLatex:e.ylabelAttr.stateValues.hasLatex}}:{useEssentialOrDefaultValue:{ylabel:!0},setValue:{ylabelHasLatex:!1}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){if("string"!=typeof e.ylabel)return{success:!1};if(t.ylabelChild.length>0){let n=t.ylabelChild.length-1;return{success:!0,instructions:[{setDependency:"ylabelChild",desiredValue:e.ylabel,childIndex:n,variableIndex:0}]}}return{success:!0,instructions:[{setEssentialValue:"ylabel",value:e.ylabel}]}}},e.graphicalDescendants={forRenderer:!0,returnDependencies:()=>({graphicalDescendants:{dependencyType:"descendant",componentTypes:["_graphical"]}}),definition:function({dependencyValues:e}){return{setValue:{graphicalDescendants:e.graphicalDescendants}}}},e.childIndicesToRender={returnDependencies:()=>({graphicalChildren:{dependencyType:"child",childGroups:["graphical"]},allChildren:{dependencyType:"child",childGroups:["graphical","xlabels","ylabels","childrenThatShouldNotBeHere"]}}),definition({dependencyValues:e}){let t=[],n=e.graphicalChildren.map((e=>e.componentName));for(let[r,a]of e.allChildren.entries())n.includes(a.componentName)&&t.push(r);return{setValue:{childIndicesToRender:t}}}},e.nChildrenAdded={defaultValue:0,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{nChildrenAdded:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"nChildrenAdded",value:e.nChildrenAdded}]})},e.size={public:!0,defaultValue:"medium",hasEssential:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({sizeAttr:{dependencyType:"attributeComponent",attributeName:"size",variableNames:["value"]},widthAttr:{dependencyType:"attributeComponent",attributeName:"width",variableNames:["componentSize"]}}),definition({dependencyValues:e}){const t="medium";if(e.sizeAttr){let n=e.sizeAttr.stateValues.value.toLowerCase();return sizePossibilities.includes(n)||(n=t),{setValue:{size:n}}}if(e.widthAttr){let n=e.widthAttr.stateValues.componentSize;if(null===n)return{setValue:{size:t}};let r,{isAbsolute:a,size:i}=n;if(a){for(let[e,t]of orderedWidthMidpoints.entries())if(i<=t){r=sizePossibilities[e];break}r||(r=t)}else{for(let[e,t]of orderedPercentWidthMidpoints.entries())if(i<=t){r=sizePossibilities[e];break}r||(r=t)}return{setValue:{size:r}}}return{useEssentialOrDefaultValue:{size:!0}}}},e.width={public:!0,forRenderer:!0,shadowingInstructions:{createComponentOfType:"_componentSize"},returnDependencies:()=>({size:{dependencyType:"stateVariable",variableName:"size"}}),definition:({dependencyValues:e})=>({setValue:{width:{isAbsolute:!0,size:widthsBySize[e.size]}}})},e.aspectRatioFromAxisScales={returnDependencies:()=>({aspectRatioAttr:{dependencyType:"attributeComponent",attributeName:"aspectRatio",variableNames:["value"]},identicalAxisScales:{dependencyType:"stateVariable",variableName:"identicalAxisScales"},heightAttr:{dependencyType:"attributeComponent",attributeName:"height",variableNames:["componentSize"]}}),definition:({dependencyValues:e})=>(null!==e.heightAttr&&console.warn("Height attribute of graph is deprecated and is being ignored. Use aspectRatio attribute instead."),{setValue:{aspectRatioFromAxisScales:e.identicalAxisScales&&null===e.aspectRatioAttr},checkForActualChange:{aspectRatioFromAxisScales:!0}})},e.aspectRatio={public:!0,forRenderer:!0,defaultValue:1,hasEssential:!0,shadowingInstructions:{createComponentOfType:"number"},stateVariablesDeterminingDependencies:["aspectRatioFromAxisScales"],returnDependencies:({stateValues:e})=>e.aspectRatioFromAxisScales?{aspectRatioFromAxisScales:{dependencyType:"stateVariable",variableName:"aspectRatioFromAxisScales"},xscale:{dependencyType:"stateVariable",variableName:"xscale"},yscale:{dependencyType:"stateVariable",variableName:"yscale"}}:{aspectRatioFromAxisScales:{dependencyType:"stateVariable",variableName:"aspectRatioFromAxisScales"},aspectRatioAttr:{dependencyType:"attributeComponent",attributeName:"aspectRatio",variableNames:["value"]},width:{dependencyType:"stateVariable",variableName:"width"}},definition({dependencyValues:e}){if(e.aspectRatioFromAxisScales){return{setValue:{aspectRatio:e.xscale/e.yscale}}}if(null!==e.aspectRatioAttr){let t=e.aspectRatioAttr.stateValues.value;return Number.isFinite(t)||(t=1),{setValue:{aspectRatio:t}}}return{useEssentialOrDefaultValue:{aspectRatio:!0}}}},e.xmin={stateVariablesDeterminingDependencies:["identicalAxisScales","aspectRatioFromAxisScales"],public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},forRenderer:!0,returnDependencies({stateValues:e}){let t={identicalAxisScales:{dependencyType:"stateVariable",variableName:"identicalAxisScales"},aspectRatioFromAxisScales:{dependencyType:"stateVariable",variableName:"aspectRatioFromAxisScales"},xminPrelim:{dependencyType:"stateVariable",variableName:"xminPrelim"}};return e.identicalAxisScales&&!e.aspectRatioFromAxisScales&&(t.xmaxPrelim={dependencyType:"stateVariable",variableName:"xmaxPrelim"},t.yminPrelim={dependencyType:"stateVariable",variableName:"yminPrelim"},t.ymaxPrelim={dependencyType:"stateVariable",variableName:"ymaxPrelim"},t.aspectRatio={dependencyType:"stateVariable",variableName:"aspectRatio"}),t},definition({dependencyValues:e,usedDefault:t}){if(!e.identicalAxisScales||e.aspectRatioFromAxisScales)return{setValue:{xmin:e.xminPrelim}};if(!t.xminPrelim)return{setValue:{xmin:e.xminPrelim}};let n=!t.xmaxPrelim,r=!t.yminPrelim,a=!t.ymaxPrelim;if(r&&a){let t=e.aspectRatio,r=(e.ymaxPrelim-e.yminPrelim)*t;return n?{setValue:{xmin:e.xmaxPrelim-r}}:{setValue:{xmin:-r/2}}}return n?{setValue:{xmin:e.xmaxPrelim-20}}:{setValue:{xmin:-10}}},inverseDefinition:async({desiredStateVariableValues:e,stateValues:t})=>await t.fixAxes?{success:!1}:{success:!0,instructions:[{setDependency:"xminPrelim",desiredValue:e.xmin}]}},e.xmax={stateVariablesDeterminingDependencies:["identicalAxisScales","aspectRatioFromAxisScales"],public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},forRenderer:!0,returnDependencies({stateValues:e}){let t={identicalAxisScales:{dependencyType:"stateVariable",variableName:"identicalAxisScales"},aspectRatioFromAxisScales:{dependencyType:"stateVariable",variableName:"aspectRatioFromAxisScales"},xmaxPrelim:{dependencyType:"stateVariable",variableName:"xmaxPrelim"}};return e.identicalAxisScales&&!e.aspectRatioFromAxisScales&&(t.xminPrelim={dependencyType:"stateVariable",variableName:"xminPrelim"},t.yminPrelim={dependencyType:"stateVariable",variableName:"yminPrelim"},t.ymaxPrelim={dependencyType:"stateVariable",variableName:"ymaxPrelim"},t.aspectRatio={dependencyType:"stateVariable",variableName:"aspectRatio"}),t},definition({dependencyValues:e,usedDefault:t}){if(!e.identicalAxisScales||e.aspectRatioFromAxisScales)return{setValue:{xmax:e.xmaxPrelim}};let n=!t.xminPrelim,r=!t.xmaxPrelim,a=!t.yminPrelim,i=!t.ymaxPrelim,s=a&&i,o=n&&r,l=e.xminPrelim;if(s){let t=e.aspectRatio,a=(e.ymaxPrelim-e.yminPrelim)*t;if(o){let t=e.xmaxPrelim-l;return{setValue:{xmax:l+Math.max(t,a)}}}return n?{setValue:{xmax:l+a}}:r?{setValue:{xmax:e.xmaxPrelim}}:{setValue:{xmax:a/2}}}return r?{setValue:{xmax:e.xmaxPrelim}}:n?{setValue:{xmax:l+20}}:{setValue:{xmax:10}}},inverseDefinition:async({desiredStateVariableValues:e,stateValues:t})=>await t.fixAxes?{success:!1}:{success:!0,instructions:[{setDependency:"xmaxPrelim",desiredValue:e.xmax}]}},e.ymin={stateVariablesDeterminingDependencies:["identicalAxisScales","aspectRatioFromAxisScales"],public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},forRenderer:!0,returnDependencies({stateValues:e}){let t={identicalAxisScales:{dependencyType:"stateVariable",variableName:"identicalAxisScales"},aspectRatioFromAxisScales:{dependencyType:"stateVariable",variableName:"aspectRatioFromAxisScales"},yminPrelim:{dependencyType:"stateVariable",variableName:"yminPrelim"}};return e.identicalAxisScales&&!e.aspectRatioFromAxisScales&&(t.xmaxPrelim={dependencyType:"stateVariable",variableName:"xmaxPrelim"},t.xminPrelim={dependencyType:"stateVariable",variableName:"xminPrelim"},t.ymaxPrelim={dependencyType:"stateVariable",variableName:"ymaxPrelim"},t.aspectRatio={dependencyType:"stateVariable",variableName:"aspectRatio"}),t},definition({dependencyValues:e,usedDefault:t}){if(!e.identicalAxisScales||e.aspectRatioFromAxisScales)return{setValue:{ymin:e.yminPrelim}};if(!t.yminPrelim)return{setValue:{ymin:e.yminPrelim}};let n=!t.ymaxPrelim,r=!t.xminPrelim,a=!t.xmaxPrelim,i=r&&a,s=e.aspectRatio;if(i){let t=(e.xmaxPrelim-e.xminPrelim)/s;return n?{setValue:{ymin:e.ymaxPrelim-t}}:{setValue:{ymin:-t/2}}}return n?{setValue:{ymin:e.ymaxPrelim-20/s}}:{setValue:{ymin:-10/s}}},inverseDefinition:async({desiredStateVariableValues:e,stateValues:t})=>await t.fixAxes?{success:!1}:{success:!0,instructions:[{setDependency:"yminPrelim",desiredValue:e.ymin}]}},e.ymax={stateVariablesDeterminingDependencies:["identicalAxisScales","aspectRatioFromAxisScales"],public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},forRenderer:!0,returnDependencies({stateValues:e}){let t={identicalAxisScales:{dependencyType:"stateVariable",variableName:"identicalAxisScales"},aspectRatioFromAxisScales:{dependencyType:"stateVariable",variableName:"aspectRatioFromAxisScales"},ymaxPrelim:{dependencyType:"stateVariable",variableName:"ymaxPrelim"}};return e.identicalAxisScales&&!e.aspectRatioFromAxisScales&&(t.xminPrelim={dependencyType:"stateVariable",variableName:"xminPrelim"},t.yminPrelim={dependencyType:"stateVariable",variableName:"yminPrelim"},t.xmaxPrelim={dependencyType:"stateVariable",variableName:"xmaxPrelim"},t.aspectRatio={dependencyType:"stateVariable",variableName:"aspectRatio"}),t},definition({dependencyValues:e,usedDefault:t}){if(!e.identicalAxisScales||e.aspectRatioFromAxisScales)return{setValue:{ymax:e.ymaxPrelim}};let n=!t.xminPrelim,r=!t.xmaxPrelim,a=!t.yminPrelim,i=!t.ymaxPrelim,s=a&&i,o=n&&r,l=e.yminPrelim,u=e.aspectRatio;if(o){let t=(e.xmaxPrelim-e.xminPrelim)/u;if(s){let n=e.ymaxPrelim-l;return{setValue:{ymax:l+Math.max(n,t)}}}return a?{setValue:{ymax:l+t}}:i?{setValue:{ymax:e.ymaxPrelim}}:{setValue:{ymax:t/2}}}return i?{setValue:{ymax:e.ymaxPrelim}}:a?{setValue:{ymax:l+20/u}}:{setValue:{ymax:10/u}}},inverseDefinition:async({desiredStateVariableValues:e,stateValues:t})=>await t.fixAxes?{success:!1}:{success:!0,instructions:[{setDependency:"ymaxPrelim",desiredValue:e.ymax}]}},e.xscale={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({xmin:{dependencyType:"stateVariable",variableName:"xmin"},xmax:{dependencyType:"stateVariable",variableName:"xmax"}}),definition:({dependencyValues:e})=>({setValue:{xscale:e.xmax-e.xmin}})},e.yscale={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({ymin:{dependencyType:"stateVariable",variableName:"ymin"},ymax:{dependencyType:"stateVariable",variableName:"ymax"}}),definition:({dependencyValues:e})=>({setValue:{yscale:e.ymax-e.ymin}})},e.gridAttrCompName={returnDependencies:()=>({gridAttr:{dependencyType:"attributeComponent",attributeName:"grid"}}),definition:({dependencyValues:e})=>e.gridAttr?{setValue:{gridAttrCompName:e.gridAttr.componentName}}:{setValue:{gridAttrCompName:null}}},e.gridAttrCompChildren={stateVariablesDeterminingDependencies:["gridAttrCompName"],returnDependencies:({stateValues:e})=>e.gridAttrCompName?{gridAttrCompChildren:{dependencyType:"child",parentName:e.gridAttrCompName,childGroups:["textLike"],variableNames:["value"]}}:{},definition:({dependencyValues:e})=>e.gridAttrCompChildren?{setValue:{gridAttrCompChildren:e.gridAttrCompChildren}}:{setValue:{gridAttrCompChildren:null}}},e.grid={public:!0,shadowingInstructions:{hasVariableComponentType:!0,attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},forRenderer:!0,stateVariablesDeterminingDependencies:["gridAttrCompChildren"],returnDependencies({stateValues:e}){if(e.gridAttrCompChildren){let t={gridAttrCompChildren:{dependencyType:"stateVariable",variableName:"gridAttrCompChildren"},gridAttr:{dependencyType:"attributeComponent",attributeName:"grid",variableNames:["value"]}};for(let[n,r]of e.gridAttrCompChildren.entries())t["childAdapter"+n]={dependencyType:"adapterSourceStateVariable",componentName:r.componentName,variableName:"value"};return t}return{}},definition({dependencyValues:e}){if(!e.gridAttrCompChildren)return{setValue:{grid:"none"},setCreateComponentOfType:{grid:"text"}};let t=e.gridAttr.stateValues.value.toLowerCase().trim();if("true"===t?t="medium":"false"===t&&(t="none"),["medium","dense","none"].includes(t))return{setValue:{grid:t},setCreateComponentOfType:{grid:"text"}};let n=[],r=[];for(let t of e.gridAttrCompChildren)if("string"!=typeof t)r.push(t);else{let e=t.split(/\s+/),a=e[0];""===a?r.length>0&&(n.push(r),r=[]):r.push(a);for(let t of e.slice(1))r.length>0&&(n.push(r),r=[]),""!==t&&r.push(t)}if(r.length>0&&n.push(r),n.length<2)return{setValue:{grid:"none"},setCreateComponentOfType:{grid:"text"}};t=[];for(let r of n)if(1===r.length){let n=r[0];if("string"==typeof n){let e=me$3.fromText(n).evaluate_to_constant();if(!(e>0))return{setValue:{grid:"none"},setCreateComponentOfType:{grid:"text"}};t.push(e)}else{let r=e.gridAttrCompChildren.indexOf(n),a=e["childAdapter"+r];if(a instanceof me$3.class&&(a=a.evaluate_to_constant()),!(a>0))return{setValue:{grid:"none"},setCreateComponentOfType:{grid:"text"}};t.push(a)}}else{let n=1;for(let t of r)if("string"==typeof t)n*=me$3.fromText(t).evaluate_to_constant();else{let r=e.gridAttrCompChildren.indexOf(t),a=e["childAdapter"+r];a instanceof me$3.class&&(a=a.evaluate_to_constant()),n*=a}if(!(n>0))return{setValue:{grid:"none"},setCreateComponentOfType:{grid:"text"}};t.push(n)}return{setValue:{grid:t},setCreateComponentOfType:{grid:"numberList"}}}},e}async changeAxisLimits({xmin:e,xmax:t,ymin:n,ymax:r,actionId:a}){let i=[];return void 0!==e&&i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"xmin",value:e}),void 0!==t&&i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"xmax",value:t}),void 0!==n&&i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"ymin",value:n}),void 0!==r&&i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"ymax",value:r}),await this.coreFunctions.performUpdate({updateInstructions:i,actionId:a,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{xmin:e,xmax:t,ymin:n,ymax:r}}})}async addChildren({serializedComponents:e,actionId:t}){if(e&&e.length>0){let n=processAssignNames({serializedComponents:e,parentName:this.componentName,parentCreatesNewNamespace:this.attributes.newNamespace?.primitive,componentInfoObjects:this.componentInfoObjects,indOffset:await this.stateValues.nChildrenAdded});return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"addComponents",serializedComponents:n.serializedComponents,parentName:this.componentName,assignNamesOffset:await this.stateValues.nChildrenAdded},{updateType:"updateValue",componentName:this.componentName,stateVariable:"nChildrenAdded",value:await this.stateValues.nChildrenAdded+n.serializedComponents.length}],actionId:t})}this.coreFunctions.resolveAction({actionId:t})}async deleteChildren({number:e,actionId:t}){let n=Math.min(e,await this.stateValues.nChildrenAdded);if(n>0){let e=this.definingChildren.length,r=this.definingChildren.slice(e-n,e).map((e=>e.componentName));return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"deleteComponents",componentNames:r},{updateType:"updateValue",componentName:this.componentName,stateVariable:"nChildrenAdded",value:await this.stateValues.nChildrenAdded-n}],actionId:t})}this.coreFunctions.resolveAction({actionId:t})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class Variables extends MathList{static componentType="variables";static stateVariableForAttributeValue="variables";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();e.variables={public:!0,shadowingInstructions:{createComponentOfType:"variable"},isArray:!0,entryPrefixes:["var"],returnArraySizeDependencies:()=>({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"}}),returnArraySize:({dependencyValues:e})=>[e.nComponents],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={math:{dependencyType:"stateVariable",variableName:"math"+(Number(n)+1)}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t)n[r]=e[r].math;return{setValue:{variables:n}}}};let t=this.componentType;return e.validVariables={returnDependencies:()=>({variables:{dependencyType:"stateVariable",variableName:"variables"}}),definition:function({dependencyValues:e}){let n=[];for(let r of e.variables){let e=isValidVariable(r);e||(console.warn("Invalid value for "+t),e=!1),n.push(e)}return{setValue:{validVariables:n}}}},e}}class Variable extends MathComponent{static componentType="variable";static rendererType="math";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.validVariable={returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:function({dependencyValues:e}){let t=isValidVariable(e.value);return t||console.warn("Invalid value of a "+this.componentType),{setValue:{validVariable:t}}}},e}}class Interval extends MathComponent{static componentType="interval";static rendererType="math";static createAttributesObject(){let e=super.createAttributesObject();return delete e.createIntervals,e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.createIntervals={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({}),definition:()=>({setValue:{createIntervals:!0}})},e}}class Group extends Template{static componentType="group";static renderedDefault=!0}class Option$1 extends Group{static componentType="option";static renderedDefault=!1;static createAttributesObject(){let e=super.createAttributesObject();return e.selectForVariants={createComponentOfType:"textListFromString",createStateVariable:"selectForVariants",defaultValue:[],public:!0},e.selectWeight={createComponentOfType:"number",createStateVariable:"selectWeight",defaultValue:1,public:!0},e}}class Sequence extends CompositeComponent{static componentType="sequence";static assignNamesToReplacements=!0;static stateVariableToEvaluateAfterReplacements="readyToExpandWhenResolved";static createAttributesObject(){let e=super.createAttributesObject();e.fixed={leaveRaw:!0},e.displayDigits={leaveRaw:!0},e.displayDecimals={leaveRaw:!0},e.displaySmallAsZero={leaveRaw:!0},e.padZeros={leaveRaw:!0};let t=returnStandardSequenceAttributes();return Object.assign(e,t),e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnStandardSequenceStateVariableDefinitions();return Object.assign(e,t),e.readyToExpandWhenResolved={returnDependencies:()=>({from:{dependencyType:"stateVariable",variableName:"from"},length:{dependencyType:"stateVariable",variableName:"length"},step:{dependencyType:"stateVariable",variableName:"step"},type:{dependencyType:"stateVariable",variableName:"type"},exclude:{dependencyType:"stateVariable",variableName:"exclude"}}),markStale:()=>({updateReplacements:!0}),definition:function(){return{setValue:{readyToExpandWhenResolved:!0}}}},e}static async createSerializedReplacements({component:e,workspace:t,componentInfoObjects:n,flags:r}){if(!await e.stateValues.validSequence)return t.lastReplacementParameters={from:null,length:null,step:null,type:null,exclude:null},{replacements:[]};let a=await e.stateValues.from,i=await e.stateValues.length,s=await e.stateValues.step,o=await e.stateValues.type,l=await e.stateValues.exclude;t.lastReplacementParameters={from:a,length:i,step:s,type:o,exclude:l};let u=e.attributes.newNamespace?.primitive,c=returnSequenceValues({from:a,step:s,length:i,exclude:l,type:o,lowercase:await e.stateValues.lowercase}),p=o;"letters"===o&&(p="text");let d=[],m={};for(let t of["fixed","displayDigits","displaySmallAsZero","displayDecimals","padZeros"])t in e.attributes&&(m[t]=e.attributes[t]);for(let e of c){let t={};Object.keys(m).length>0&&(t=convertAttributesForComponentType({attributes:m,componentType:p,componentInfoObjects:n,compositeCreatesNewNamespace:u,flags:r}));let a={componentType:p,attributes:t,state:{value:e,fixed:!0}};d.push(a)}return{replacements:processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:d,parentName:e.componentName,parentCreatesNewNamespace:u,componentInfoObjects:n}).serializedComponents}}static async calculateReplacementChanges({component:e,workspace:t,componentInfoObjects:n,flags:r}){let a=t.lastReplacementParameters,i=[];if(!await e.stateValues.validSequence){let t=e.replacementsToWithhold;if(t||(t=0),e.replacements.length-t>0){let t={changeType:"changeReplacementsToWithhold",replacementsToWithhold:e.replacements.length};i.push(t)}return a.length=0,i}let s=await e.stateValues.from,o=await e.stateValues.length,l=await e.stateValues.step,u=await e.stateValues.type,c=await e.stateValues.exclude,p=await e.stateValues.lowercase;if(a.type!==u||a.exclude.length>0||c.length>0){let a=(await this.createSerializedReplacements({component:e,workspace:t,componentInfoObjects:n,flags:r})).replacements,s={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:0,numberReplacementsToReplace:e.replacements.length,serializedReplacements:a,replacementsToWithhold:0};i.push(s)}else{let t=!1;"math"===u?s.equals(a.from)&&l.equals(a.step)||(t=!0):s===a.from&&l===a.step||(t=!0);let c,d=a.length,m=0,h=0,f=d;if(od&&(m=o-d,e.replacementsToWithhold>0))if(e.replacementsToWithhold>=m){c=e.replacementsToWithhold-m,h+=m,d+=m,m=0;let t={changeType:"changeReplacementsToWithhold",replacementsToWithhold:c};i.push(t)}else m-=e.replacementsToWithhold,h+=e.replacementsToWithhold,d+=e.replacementsToWithhold,c=0;if(!0===t&&(h=d,f=0),h>0)for(let t=f;t0){let t=[],a=e.attributes.newNamespace?.primitive,o={};for(let t of["fixed","displayDigits","displaySmallAsZero","displayDecimals","padZeros"])t in e.attributes&&(o[t]=e.attributes[t]);for(let i=d;i0&&(m=convertAttributesForComponentType({attributes:o,componentType:d,componentInfoObjects:n,compositeCreatesNewNamespace:a,flags:r}));let h={componentType:d,attributes:m,state:{value:c,fixed:!0}};t.push(h)}let c={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:d,serializedReplacements:processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:t,parentName:e.componentName,parentCreatesNewNamespace:a,componentInfoObjects:n,indOffset:d}).serializedComponents,replacementsToWithhold:0,assignNamesOffset:d};i.push(c)}}return a.type=u,a.from=s,a.length=o,a.step=l,a.exclude=c,i}get allPotentialRendererTypes(){let e=super.allPotentialRendererTypes,t="number";this.attributes.type&&this.attributes.type.primitive&&(t=this.attributes.type.primitive);let n=this.componentInfoObjects.allComponentClasses["letters"===t?"text":t].rendererType;return e.includes(n)||e.push(n),e}}class Map$1 extends CompositeComponent{static componentType="map";static assignNamesToReplacements=!0;static createsVariants=!0;static stateVariableToEvaluateAfterReplacements="readyToExpandWhenResolved";static createAttributesObject(){let e=super.createAttributesObject();return e.assignNamesSkip={createPrimitiveOfType:"number"},e.behavior={createComponentOfType:"text",createStateVariable:"behavior",defaultValue:"combination",public:!0,trim:!0},e.isResponse={leaveRaw:!0},e}static returnChildGroups(){return[{group:"templates",componentTypes:["template"]},{group:"sources",componentTypes:["sources"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nSources={additionalStateVariablesDefined:["sourcesNames","sourceAliases","sourceIndexAliases"],returnDependencies:()=>({sourcesChildren:{dependencyType:"child",childGroups:["sources"],variableNames:["alias","indexAlias"]}}),definition:function({dependencyValues:e}){return{setValue:{nSources:e.sourcesChildren.length,sourcesNames:e.sourcesChildren.map((e=>e.componentName)),sourceAliases:e.sourcesChildren.map((e=>e.stateValues.alias)),sourceIndexAliases:e.sourcesChildren.map((e=>e.stateValues.indexAlias))}}}},e.nIterates={additionalStateVariablesDefined:["minNIterates","sourcesChildNames"],returnDependencies:()=>({sourcesChildren:{dependencyType:"child",childGroups:["sources"],variableNames:["numberOfChildren","childComponentNames"]}}),definition:function({dependencyValues:e}){let t=e.sourcesChildren.map((e=>e.stateValues.numberOfChildren)),n=Math.min(...t),r=e.sourcesChildren.map((e=>[...e.stateValues.childComponentNames]));return{setValue:{nIterates:t,minNIterates:n,sourcesChildNames:r}}}},e.template={returnDependencies:()=>({templateChild:{dependencyType:"child",childGroups:["templates"],variableNames:["serializedChildren","newNamespace"]}}),definition:function({dependencyValues:e}){let t=e.templateChild[0];if(!t)return{setValue:{template:null}};let n={componentType:"template",state:{rendered:!0},children:t.stateValues.serializedChildren,originalName:t.componentName};return t.stateValues.newNamespace&&(n.attributes={newNamespace:{primitive:!0}}),{setValue:{template:n}}}},e.validBehavior={returnDependencies:()=>({behavior:{dependencyType:"stateVariable",variableName:"behavior"},nIterates:{dependencyType:"stateVariable",variableName:"nIterates"}}),definition:function({dependencyValues:e}){let t=!0;return"parallel"===e.behavior?e.nIterates.slice(1).some((t=>t!=e.nIterates[0]))&&console.warn("Warning: map with parallel behavior and different numbers of iterates in sources activeChildren. Extra iterates will be ignored."):"combination"!==e.behavior&&(console.warn("Invalid map behavior: "+e.behavior),t=!1),{setValue:{validBehavior:t}}}},e.readyToExpandWhenResolved={returnDependencies:()=>({validBehavior:{dependencyType:"stateVariable",variableName:"validBehavior"}}),markStale:()=>({updateReplacements:!0}),definition:function(){return{setValue:{readyToExpandWhenResolved:!0}}}},e.isVariantComponent={returnDependencies:()=>({}),definition:()=>({setValue:{isVariantComponent:!0}})},e.generatedVariantInfo={returnDependencies:({sharedParameters:e,componentInfoObjects:t})=>({variantSeed:{dependencyType:"value",value:e.variantSeed},variantDescendants:{dependencyType:"descendant",componentTypes:Object.keys(t.componentTypesCreatingVariants),variableNames:["isVariantComponent","generatedVariantInfo"],useReplacementsForComposites:!0,recurseToMatchedChildren:!1,variablesOptional:!0,includeNonActiveChildren:!0,ignoreReplacementsOfEncounteredComposites:!0}}),definition({dependencyValues:e,componentName:t}){let n={seed:e.variantSeed,meta:{createdBy:t}},r=n.subvariants=[];for(let t of e.variantDescendants)t.stateValues.isVariantComponent?r.push(t.stateValues.generatedVariantInfo):t.stateValues.generatedVariantInfo&&r.push(...t.stateValues.generatedVariantInfo.subvariants);return{setValue:{generatedVariantInfo:n}}}},e}static async createSerializedReplacements({component:e,workspace:t,componentInfoObjects:n,flags:r}){if(!await e.stateValues.validBehavior)return t.lastReplacementParameters={sourcesNames:[],sourcesChildNames:[],behavior:void 0,nIterates:void 0,minNIterates:void 0},{replacements:[]};t.lastReplacementParameters={sourcesNames:await e.stateValues.sourcesNames,sourcesChildNames:await e.stateValues.sourcesChildNames,behavior:await e.stateValues.behavior,nIterates:await e.stateValues.nIterates,minNIterates:await e.stateValues.minNIterates,replacementsToWithhold:0,withheldSubstitutionChildNames:[]};let a=[];if("parallel"===await e.stateValues.behavior)for(let t=0;t=c-1){r++;let t=[deepClone(p)],n={};n=convertAttributesForComponentType({attributes:e.attributes,componentType:t[0].componentType,componentInfoObjects:a,compositeAttributesObj:d,compositeCreatesNewNamespace:l,flags:i}),t[0].attributes||(t[0].attributes={}),Object.assign(t[0].attributes,n),!t[0].attributes.newNamespace?.primitive&&t[0].children&&markToCreateAllUniqueNames(t[0].children);let u=processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:t,parentName:e.componentName,parentCreatesNewNamespace:l,componentInfoObjects:a,indOffset:r}).serializedComponents[0];await addSharedParameters(u,e,o),s.push(u)}else{let n=await this.recurseThroughCombinations({component:e,sourcesNumber:t+1,childnumberArray:o,iterateNumber:r,componentInfoObjects:a,flags:i});s.push(...n.replacements),r=n.iterateNumber}return{replacements:s,iterateNumber:r}}static async calculateReplacementChanges({component:e,components:t,workspace:n,componentInfoObjects:r,flags:a}){let i=[];if(!await e.stateValues.validBehavior){if(n.lastReplacementParameters={sourcesNames:[],sourcesChildNames:[],behavior:void 0,nIterates:void 0,minNIterates:void 0,replacementsToWithhold:0,withheldSubstitutionChildNames:[]},e.replacements.length>0){let t={changeType:"delete",changeTopLevelReplacements:!0,firstReplacementInd:0,numberReplacementsToDelete:e.replacements.length,replacementsToWithhold:0};i.push(t)}return i}let s=n.lastReplacementParameters,o=!1,l=!0,u=await e.stateValues.nSources,c=await e.stateValues.sourcesNames;if(u!==s.sourcesNames.length)l=!1;else for(let e=0;e1&&(o=!0)}else o=!0;if(o){let t=await this.createSerializedReplacements({component:e,workspace:n,componentInfoObjects:r,flags:a}).replacements,s={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:0,numberReplacementsToReplace:e.replacements.length,serializedReplacements:t,replacementsToWithhold:0};return i.push(s),n.lastReplacementParameters={sourcesNames:c,sourcesChildNames:d,behavior:m,nIterates:p,minNIterates:await e.stateValues.minNIterates,replacementsToWithhold:0,withheldSubstitutionChildNames:[]},i}let h=await e.stateValues.minNIterates,f=s.minNIterates,y=0,g=e.replacementsToWithhold;g||(g=0);let b=s.withheldSubstitutionChildNames,v=!1;if(hf){let t=h-f;if(g>0)if(g>=t){y=g-t,t=0;let e={changeType:"changeReplacementsToWithhold",replacementsToWithhold:y};i.push(e)}else t-=g,f+=g,y=0;if(t>0){let t=[];for(let n=f;nr?{success:!1}:{success:!0,desiredVariant:{index:t}}}}async function addSharedParameters(e,t,n){let r=e.doenetAttributes.addToSharedParameters=[],a=await t.stateValues.sourcesNames;for(let[e,i]of(await t.stateValues.sourceAliases).entries())if(i){let t=a[e];r.push({parameterName:"sourceNameMappings",key:i,value:{name:t,childNumber:n[e]}})}for(let[e,a]of(await t.stateValues.sourceIndexAliases).entries())a&&r.push({parameterName:"sourceIndexMappings",key:a,value:n[e]+1})}class Sources extends BaseComponent{static componentType="sources";static rendererType="containerInline";static renderChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.alias={createPrimitiveOfType:"string",validationFunction:function(e){if(!/[a-zA-Z_]/.test(e.substring(0,1)))throw Error("All aliases must begin with a letter or an underscore");if(!/^[a-zA-Z0-9_\-]+$/.test(e))throw Error("Aliases can contain only letters, numbers, hyphens, and underscores");return e}},e.indexAlias={createPrimitiveOfType:"string",validationFunction:function(e){if(!/[a-zA-Z_]/.test(e.substring(0,1)))throw Error("All index aliases must begin with a letter or an underscore");if(!/^[a-zA-Z0-9_\-]+$/.test(e))throw Error("Index aliases can contain only letters, numbers, hyphens, and underscores");return e}},e}static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.alias={returnDependencies:()=>({alias:{dependencyType:"attributePrimitive",attributeName:"alias"}}),definition:({dependencyValues:e})=>({setValue:{alias:e.alias}})},e.indexAlias={returnDependencies:()=>({indexAlias:{dependencyType:"attributePrimitive",attributeName:"indexAlias"}}),definition:({dependencyValues:e})=>({setValue:{indexAlias:e.indexAlias}})},e.numberOfChildren={additionalStateVariablesDefined:["childComponentNames","childIdentities"],returnDependencies:()=>({children:{dependencyType:"child",childGroups:["anything"]}}),definition:function({dependencyValues:e}){let t=e.children.length,n=e.children.map((e=>e.componentName));return{setValue:{numberOfChildren:t,childComponentNames:n,childIdentities:e.children}}}},e}}class Slider extends BaseComponent{constructor(e){super(e),this.changeValue=this.changeValue.bind(this),Object.assign(this.actions,{changeValue:this.changeValue})}static componentType="slider";static variableForPlainMacro="value";static variableForPlainCopy="value";static createAttributesObject(){let e=super.createAttributesObject();return e.type={createPrimitiveOfType:"string",createStateVariable:"type",defaultValue:"number",toLowerCase:!0,validValues:["number","text"],forRenderer:!0},e.width={createComponentOfType:"_componentSize",createStateVariable:"width",defaultValue:{size:300,isAbsolute:!0},public:!0,forRenderer:!0},e.height={createComponentOfType:"_componentSize",createStateVariable:"height",defaultValue:{size:100,isAbsolute:!0},public:!0,forRenderer:!0},e.initialValue={createComponentOfType:"_componentWithSelectableType",createStateVariable:"initialValue",defaultValue:null},e.labelIsName={createComponentOfType:"boolean",createStateVariable:"labelIsName",defaultValue:!1,public:!0},e.showControls={createComponentOfType:"boolean",createStateVariable:"showControls",defaultValue:!1,public:!0,forRenderer:!0},e.showTicks={createComponentOfType:"boolean",createStateVariable:"showTicks",defaultValue:!0,public:!0,forRenderer:!0},e.showValue={createComponentOfType:"boolean",createStateVariable:"showValue",defaultValue:!0,public:!0,forRenderer:!0},e.from={createComponentOfType:"number",createStateVariable:"from",defaultValue:0,public:!0,forRenderer:!0},e.to={createComponentOfType:"number",createStateVariable:"to",defaultValue:10,public:!0,forRenderer:!0},e.step={createComponentOfType:"number",createStateVariable:"step",defaultValue:1,public:!0,forRenderer:!0},e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.bindValueTo={createComponentOfType:"_componentWithSelectableType"},e}static returnChildGroups(){return[{group:"numbersTexts",componentTypes:["number","text"]},{group:"markers",componentTypes:["markers"]},{group:"labels",componentTypes:["label"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnLabelStateVariableDefinitions();return Object.assign(e,t),e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.displayDigitsAttr){let n=t.displayDigitsAttr,r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!n&&!r){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({numberAndTextChildren:{dependencyType:"child",childGroups:["numbersTexts"],variableNames:["value"]},type:{dependencyType:"stateVariable",variableName:"type"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=[];if("text"===e.type)for(let r of e.numberAndTextChildren)t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"text"})?n.push(r.stateValues.value):n.push(r.stateValues.value.toString());else if(e.numberAndTextChildren.length>0){for(let r of e.numberAndTextChildren)if(t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"number"}))n.push(r.stateValues.value);else{let e=Number(r.stateValues.value);Number.isFinite(e)&&n.push(e)}n.sort(((e,t)=>e-t))}return{setValue:{items:n},setCreateComponentOfType:{items:e.type}}}},e.nItems={forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({items:{dependencyType:"stateVariable",variableName:"items"},from:{dependencyType:"stateVariable",variableName:"from"},to:{dependencyType:"stateVariable",variableName:"to"},step:{dependencyType:"stateVariable",variableName:"step"},type:{dependencyType:"stateVariable",variableName:"type"}}),definition({dependencyValues:e}){let t=e.items.length;return 0===t&&"number"===e.type&&(t=Math.floor((e.to-e.from)/e.step+1e-10)+1,t>=0&&Number.isFinite(t)||(t=0)),{setValue:{nItems:t}}}},e.firstItem={forRenderer:!0,returnDependencies:()=>({items:{dependencyType:"stateVariable",variableName:"items"},from:{dependencyType:"stateVariable",variableName:"from"},type:{dependencyType:"stateVariable",variableName:"type"}}),definition({dependencyValues:e}){let t;return t=e.items.length>0?e.items[0]:"number"===e.type?e.from:null,{setValue:{firstItem:t}}}},e.lastItem={forRenderer:!0,returnDependencies:()=>({items:{dependencyType:"stateVariable",variableName:"items"},from:{dependencyType:"stateVariable",variableName:"from"},nItems:{dependencyType:"stateVariable",variableName:"nItems"},step:{dependencyType:"stateVariable",variableName:"step"},type:{dependencyType:"stateVariable",variableName:"type"}}),definition({dependencyValues:e}){let t;return t=e.items.length>0?e.items[e.items.length-1]:"number"===e.type?e.from+(e.nItems-1)*e.step:null,{setValue:{lastItem:t}}}},e.valueToIndex={forRenderer:!0,returnDependencies:()=>({items:{dependencyType:"stateVariable",variableName:"items"}}),definition:function({dependencyValues:e}){let t={};for(let[n,r]of e.items.entries())t[r]=n;return{setValue:{valueToIndex:t}}}},e.preliminaryValue={hasEssential:!0,returnDependencies:()=>({type:{dependencyType:"stateVariable",variableName:"type"},initialValue:{dependencyType:"stateVariable",variableName:"initialValue"},bindValueTo:{dependencyType:"attributeComponent",attributeName:"bindValueTo",variableNames:["value"]}}),definition:({dependencyValues:e})=>e.bindValueTo?{setValue:{preliminaryValue:e.bindValueTo.stateValues.value}}:{useEssentialOrDefaultValue:{preliminaryValue:{get defaultValue(){return e.initialValue}}}},inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t})=>t.bindValueTo?{success:!0,instructions:[{setDependency:"bindValueTo",desiredValue:e.preliminaryValue,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"preliminaryValue",value:e.preliminaryValue}]}},e.index={forRenderer:!0,returnDependencies:()=>({type:{dependencyType:"stateVariable",variableName:"type"},valueToIndex:{dependencyType:"stateVariable",variableName:"valueToIndex"},items:{dependencyType:"stateVariable",variableName:"items"},preliminaryValue:{dependencyType:"stateVariable",variableName:"preliminaryValue"},from:{dependencyType:"stateVariable",variableName:"from"},step:{dependencyType:"stateVariable",variableName:"step"},nItems:{dependencyType:"stateVariable",variableName:"nItems"}}),definition:function({dependencyValues:e}){let t=findIndexOfClosestValidValue(e);return void 0===t&&(t=0),{setValue:{index:t}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){if(0===t.items.length){let n=t.from,r=t.step,a=e.index;return Number.isInteger(a)&&(a>=0&&a({type:{dependencyType:"stateVariable",variableName:"type"},items:{dependencyType:"stateVariable",variableName:"items"},index:{dependencyType:"stateVariable",variableName:"index"},from:{dependencyType:"stateVariable",variableName:"from"},step:{dependencyType:"stateVariable",variableName:"step"}}),definition:function({dependencyValues:e}){let t;return t=e.items.length>0?e.items[e.index]:e.from+e.step*e.index,{setValue:{value:t},setCreateComponentOfType:{value:e.type}}},inverseDefinition:invertSliderValue},e.valueForDisplay={forRenderer:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"}}),definition:function({dependencyValues:e,usedDefault:t}){return{setValue:{valueForDisplay:roundForDisplay({value:e.value,dependencyValues:e,usedDefault:t}).tree}}}},e.markers={forRenderer:!0,returnDependencies:()=>({markersChild:{dependencyType:"child",childGroups:["markers"],variableNames:["markerType","markers"]},type:{dependencyType:"stateVariable",variableName:"type"},items:{dependencyType:"stateVariable",variableName:"items"}}),definition:function({dependencyValues:e}){let t=[];if(e.markersChild.length>0){let n=e.markersChild[0].stateValues.markerType;"empty"===n?t=[...e.items]:n!==e.type?(console.warn("Markers type doesn't match slider type."),t=[]):t=e.markersChild[0].stateValues.markers}return{setValue:{markers:t}}}},e}async changeValue({value:e,transient:t,actionId:n}){if(!await this.stateValues.disabled)return t?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"value",value:e}],transient:t,actionId:n}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"value",value:e}],actionId:n,event:{verb:"selected",object:{componentName:this.componentName,componentType:this.componentType},result:{response:e,responseText:e.toString()}}});this.coreFunctions.resolveAction({actionId:n})}}function findIndexOfClosestValidValue({preliminaryValue:e,valueToIndex:t,type:n,items:r,from:a,step:i,nItems:s}){let o=e;if(0===r.length){if(!Number.isFinite(o))return;let e=Math.round((o-a)/i);return e>=0?er[e]?t:e;let n=Math.round((t+e)/2);return o>r[n]?u(n,t):u(e,n)},c=u();if(0!==c){let e=r[c-1],t=r[c];Math.abs(o-e)({textChildren:{dependencyType:"child",childGroups:["texts"]},numberChildren:{dependencyType:"child",childGroups:["numbers"]}}),definition:function({dependencyValues:e}){let t;return t=e.textChildren.length>0?"text":e.numberChildren.length>0?"number":"empty",{setValue:{markerType:t}}}},e.markers={public:!0,isArray:!0,shadowingInstructions:{hasVariableComponentType:!0},entryPrefixes:["item"],returnDependencies:()=>({markerType:{dependencyType:"stateVariable",variableName:"markerType"},textChildren:{dependencyType:"child",childGroups:["texts"],variableNames:["value"]},numberChildren:{dependencyType:"child",childGroups:["numbers"],variableNames:["value"]}}),definition:function({dependencyValues:e}){let t=[],n=e.markerType;return"text"===e.markerType?t=e.textChildren.map((e=>e.stateValues.value)):"number"===e.markerType?(t=e.numberChildren.map((e=>e.stateValues.value)),t.sort(((e,t)=>e-t))):n="text",{setValue:{markers:t},setCreateComponentOfType:{markers:n}}}},e}}class Pegboard extends GraphicalComponent{static componentType="pegboard";static createAttributesObject(){let e=super.createAttributesObject();return e.dx={createComponentOfType:"number",createStateVariable:"dx",defaultValue:1,public:!0,forRenderer:!0},e.dy={createComponentOfType:"number",createStateVariable:"dy",defaultValue:1,public:!0,forRenderer:!0},e.xoffset={createComponentOfType:"number",createStateVariable:"xoffset",defaultValue:0,public:!0,forRenderer:!0},e.yoffset={createComponentOfType:"number",createStateVariable:"yoffset",defaultValue:0,public:!0,forRenderer:!0},e}}function applyConstraintFromComponentConstraints({variables:e,applyComponentConstraint:t,scales:n}){let r={},a=!1;for(let i in e){let s=t({variables:{[i]:e[i]},scales:n});s.constrained&&(a=!0,r[i]=s.variables[i])}return a?{constrained:a,variables:r}:{}}class Constraints extends BaseComponent{static componentType="constraints";static rendererType=void 0;static createAttributesObject(){let e=super.createAttributesObject();return e.baseOnGraph={createTargetComponentNames:!0},e}static returnChildGroups(){return[{group:"constraints",componentTypes:["_constraint"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.independentComponentConstraints={returnDependencies:()=>({constraintChildren:{dependencyType:"child",childGroups:["constraints"],variableNames:["independentComponentConstraints"]}}),definition:({dependencyValues:e})=>({setValue:{independentComponentConstraints:e.constraintChildren.every((e=>e.stateValues.independentComponentConstraints))}})},e.arrayEntryPrefixForConstraints={returnDependencies:()=>({arrayEntryPrefixForConstraints:{dependencyType:"parentStateVariable",variableName:"arrayEntryPrefixForConstraints"}}),definition:({dependencyValues:e})=>({setValue:{arrayEntryPrefixForConstraints:e.arrayEntryPrefixForConstraints}})},e.arrayVariableForConstraints={returnDependencies:()=>({arrayVariableForConstraints:{dependencyType:"parentStateVariable",variableName:"arrayVariableForConstraints"}}),definition:({dependencyValues:e})=>({setValue:{arrayVariableForConstraints:e.arrayVariableForConstraints}})},e.nDimensions={returnDependencies:()=>({nDimensions:{dependencyType:"parentStateVariable",variableName:"nDimensionsForConstraints"}}),definition:({dependencyValues:e})=>({setValue:{nDimensions:e.nDimensions}})},e.graphComponentName={returnDependencies:()=>({graphComponentName:{dependencyType:"attributeTargetComponentNames",attributeName:"baseOnGraph"}}),definition:({dependencyValues:e})=>1===e.graphComponentName?.length?{setValue:{graphComponentName:e.graphComponentName[0].absoluteName}}:{setValue:{graphComponentName:null}}},e.scales={public:!0,shadowingInstructions:{createComponentOfType:"number"},stateVariablesDeterminingDependencies:["graphComponentName"],returnDependencies:({stateValues:e})=>e.graphComponentName?{graph:{dependencyType:"multipleStateVariables",componentName:e.graphComponentName,variableNames:["xscale","yscale"],variablesOptional:!0}}:{},definition({dependencyValues:e}){if(e.graph){let t=e.graph.stateValues,n=[t.xscale,t.yscale,1];if(n.every((e=>Number.isFinite(e)&&e>0)))return{setValue:{scales:n}}}return{setValue:{scales:[1,1,1]}}}},e.graphXmin={additionalStateVariablesDefined:["graphXmax","graphYmin","graphYmax"],stateVariablesDeterminingDependencies:["graphComponentName"],returnDependencies:({stateValues:e})=>e.graphComponentName?{graph:{dependencyType:"multipleStateVariables",componentName:e.graphComponentName,variableNames:["xmin","xmax","ymin","ymax"],variablesOptional:!0}}:{},definition({dependencyValues:e}){if(!e.graph)return{setValue:{graphXmin:null,graphXmax:null,graphYmin:null,graphYmax:null}};let t=e.graph.stateValues.xmin,n=e.graph.stateValues.xmax,r=e.graph.stateValues.ymin,a=e.graph.stateValues.ymax;return[t,n,r,a].every(Number.isFinite)?{setValue:{graphXmin:t,graphXmax:n,graphYmin:r,graphYmax:a}}:{setValue:{graphXmin:null,graphXmax:null,graphYmin:null,graphYmax:null}}}},e.constraintResults={additionalStateVariablesDefined:[{variableName:"constraintUsedByComponent",isArray:!0,entryPrefixes:["constraintUsedByComponent"]}],isArray:!0,entryPrefixes:["constraintResult"],stateVariablesDeterminingDependencies:["independentComponentConstraints","arrayEntryPrefixForConstraints","arrayVariableForConstraints"],returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={constraintChildren:{dependencyType:"child",childGroups:["constraints"],variableNames:["applyConstraint","applyComponentConstraint"],variablesOptional:!0},independentComponentConstraints:{dependencyType:"stateVariable",variableName:"independentComponentConstraints"},scales:{dependencyType:"stateVariable",variableName:"scales"}},r=t.arrayEntryPrefixForConstraints,a={};if(t.independentComponentConstraints)for(let t of e)a[t]={x:{dependencyType:"parentStateVariable",variableName:r+(Number(t)+1)}};else{let e=t.arrayVariableForConstraints?t.arrayVariableForConstraints:"__null";n.xs={dependencyType:"parentStateVariable",variableName:e}}return{globalDependencies:n,dependenciesByKey:a}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){if(e.independentComponentConstraints){let r={},a={};for(let i of n){let n=Number(i)+1,s={["x"+n]:t[i].x},o=!1;for(let t of e.constraintChildren){let r=t.stateValues.applyComponentConstraint({variables:s,scales:e.scales});r.constrained&&(s["x"+n]=convertValueToMathExpression(r.variables["x"+n]),o=!0)}r[i]=s["x"+n],a[i]=o}return{setValue:{constraintResults:r,constraintUsedByComponent:a}}}{let t={},n=!1;for(let n in e.xs)t[`x${Number(n)+1}`]=e.xs[n];for(let r of e.constraintChildren){let a;if(a=r.stateValues.applyConstraint?r.stateValues.applyConstraint({variables:t,scales:e.scales}):applyConstraintFromComponentConstraints({variables:t,applyComponentConstraint:r.stateValues.applyComponentConstraint,scales:e.scales}),a.constrained){for(let e in a.variables)t[e]=convertValueToMathExpression(a.variables[e]);n=!0}}let r={},a={};for(let i in e.xs)r[i]=t[`x${Number(i)+1}`],a[i]=n;return{setValue:{constraintResults:r,constraintUsedByComponent:a}}}},inverseArrayDefinitionByKey:async function({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,stateValues:a,workspace:i}){if(t.independentComponentConstraints){let n=[];for(let a in e.constraintResults){let i=Number(a)+1,s={["x"+i]:convertValueToMathExpression(e.constraintResults[a])};for(let e of t.constraintChildren){let n=e.stateValues.applyComponentConstraint({variables:s,scales:t.scales});n.constrained&&(s["x"+i]=convertValueToMathExpression(n.variables["x"+i]))}n.push({setDependency:r[a].x,desiredValue:s["x"+i]})}return{success:!0,instructions:n}}{let n={};i.desiredConstraintResults||(i.desiredConstraintResults={}),Object.assign(i.desiredConstraintResults,e.constraintResults);let r=await a.constraintResults;for(let e in r){let t=Number(e)+1;e in i.desiredConstraintResults?n["x"+t]=convertValueToMathExpression(i.desiredConstraintResults[e]):n["x"+t]=convertValueToMathExpression(r[e])}for(let e of t.constraintChildren){let r;if(r=e.stateValues.applyConstraint?e.stateValues.applyConstraint({variables:n,scales:t.scales}):applyConstraintFromComponentConstraints({variables:n,applyComponentConstraint:e.stateValues.applyComponentConstraint,scales:t.scales}),r.constrained)for(let e in r.variables)n[e]=convertValueToMathExpression(r.variables[e])}let s={};for(let e in i.desiredConstraintResults)s[e]=n[`x${Number(e)+1}`];return{success:!0,instructions:[{setDependency:"xs",desiredValue:s}]}}}},e.constraintUsed={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({constraintUsedByComponent:{dependencyType:"stateVariable",variableName:"constraintUsedByComponent"}}),definition:function({dependencyValues:e}){let t=Object.values(e.constraintUsedByComponent).some((e=>e));return{setValue:{constraintUsed:t}}}},e}}class ConstraintComponent extends BaseComponent{static componentType="_constraint";static rendererType=void 0;static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.independentComponentConstraints={returnDependencies:()=>({}),definition:()=>({setValue:{independentComponentConstraints:!1}})},e}}class ConstrainToGrid extends ConstraintComponent{static componentType="constrainToGrid";static createAttributesObject(){let e=super.createAttributesObject();return e.dx={createComponentOfType:"number",createStateVariable:"dx",defaultValue:1,public:!0},e.dy={createComponentOfType:"number",createStateVariable:"dy",defaultValue:1,public:!0},e.dz={createComponentOfType:"number",createStateVariable:"dz",defaultValue:1,public:!0},e.xoffset={createComponentOfType:"number",createStateVariable:"xoffset",defaultValue:0,public:!0},e.yoffset={createComponentOfType:"number",createStateVariable:"yoffset",defaultValue:0,public:!0},e.zoffset={createComponentOfType:"number",createStateVariable:"zoffset",defaultValue:0,public:!0},e.ignoreGraphBounds={createComponentOfType:"boolean",createStateVariable:"ignoreGraphBounds",defaultValue:!1,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.independentComponentConstraints={returnDependencies:()=>({}),definition:()=>({setValue:{independentComponentConstraints:!0}})},e.applyComponentConstraint={returnDependencies:()=>({dx:{dependencyType:"stateVariable",variableName:"dx"},dy:{dependencyType:"stateVariable",variableName:"dy"},dz:{dependencyType:"stateVariable",variableName:"dz"},xoffset:{dependencyType:"stateVariable",variableName:"xoffset"},yoffset:{dependencyType:"stateVariable",variableName:"yoffset"},zoffset:{dependencyType:"stateVariable",variableName:"zoffset"},constraintAncestor:{dependencyType:"ancestor",componentType:"constraints",variableNames:["graphXmin","graphXmax","graphYmin","graphYmax"]},graphAncestor:{dependencyType:"ancestor",componentType:"graph",variableNames:["xmin","xmax","ymin","ymax"]},ignoreGraphBounds:{dependencyType:"stateVariable",variableName:"ignoreGraphBounds"}}),definition:({dependencyValues:e})=>({setValue:{applyComponentConstraint:function({variables:t,scales:n}){let r;if(null!==e.constraintAncestor&&null!==e.constraintAncestor.stateValues.graphXmin?r="constraints":null!==e.graphAncestor&&null!==e.graphAncestor.stateValues.xmin&&(r="graph"),"x1"in t){let n=findFiniteNumericalValue(t.x1);if(!Number.isFinite(n))return{};let a=e.dx,i=e.xoffset,s=Math.round((n-i)/a)*a+i;if(Number.isFinite(s)){if(!e.ignoreGraphBounds){let t,n;"constraints"===r?(t=e.constraintAncestor.stateValues.graphXmin,n=e.constraintAncestor.stateValues.graphXmax):"graph"===r&&(t=e.graphAncestor.stateValues.xmin,n=e.graphAncestor.stateValues.xmax),void 0!==t&&(sn&&(s=Math.floor((n-i)/a)*a+i))}return{constrained:!0,variables:{x1:s}}}return{}}if("x2"in t){let n=findFiniteNumericalValue(t.x2);if(!Number.isFinite(n))return{};let a=e.dy,i=e.yoffset,s=Math.round((n-i)/a)*a+i;if(Number.isFinite(s)){if(!e.ignoreGraphBounds){let t,n;"constraints"===r?(t=e.constraintAncestor.stateValues.graphYmin,n=e.constraintAncestor.stateValues.graphYmax):"graph"===r&&(t=e.graphAncestor.stateValues.ymin,n=e.graphAncestor.stateValues.ymax),void 0!==t&&(sn&&(s=Math.floor((n-i)/a)*a+i))}return{constrained:!0,variables:{x2:s}}}return{}}if("x3"in t){let n=findFiniteNumericalValue(t.x3);if(!Number.isFinite(n))return{};let r=e.dz,a=e.zoffset,i=Math.round((n-a)/r)*r+a;return Number.isFinite(i)?{constrained:!0,variables:{x3:i}}:{}}return{}}}})},e}}class ConstrainToGraph extends ConstraintComponent{static componentType="constrainToGraph";static createAttributesObject(){let e=super.createAttributesObject();return e.buffer={createComponentOfType:"number",createStateVariable:"buffer",defaultValue:.01,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.independentComponentConstraints={returnDependencies:()=>({}),definition:()=>({setValue:{independentComponentConstraints:!0}})},e.applyComponentConstraint={returnDependencies:()=>({constraintAncestor:{dependencyType:"ancestor",componentType:"constraints",variableNames:["graphXmin","graphXmax","graphYmin","graphYmax"]},buffer:{dependencyType:"stateVariable",variableName:"buffer"},graphAncestor:{dependencyType:"ancestor",componentType:"graph",variableNames:["xmin","xmax","ymin","ymax"]}}),definition:({dependencyValues:e})=>({setValue:{applyComponentConstraint:function({variables:t,scales:n}){let r;if(null!==e.constraintAncestor&&null!==e.constraintAncestor.stateValues.graphXmin?r="constraints":null!==e.graphAncestor&&null!==e.graphAncestor.stateValues.xmin&&(r="graph"),!r)return{};if("x1"in t){let n,a,i=findFiniteNumericalValue(t.x1);if(!Number.isFinite(i))return{};if("constraints"===r?(n=e.constraintAncestor.stateValues.graphXmin,a=e.constraintAncestor.stateValues.graphXmax):(n=e.graphAncestor.stateValues.xmin,a=e.graphAncestor.stateValues.xmax),!Number.isFinite(n)||!Number.isFinite(a))return{};let s=n,o=a,l=e.buffer;if(l>0){let e=l*(a-n);s+=e,o-=e}return{constrained:!0,variables:{x1:Math.max(s,Math.min(o,i))}}}if("x2"in t){let n,a,i=findFiniteNumericalValue(t.x2);if(!Number.isFinite(i))return{};if("constraints"===r?(n=e.constraintAncestor.stateValues.graphYmin,a=e.constraintAncestor.stateValues.graphYmax):(n=e.graphAncestor.stateValues.ymin,a=e.graphAncestor.stateValues.ymax),!Number.isFinite(n)||!Number.isFinite(a))return{};let s=n,o=a,l=e.buffer;if(l>0){let e=l*(a-n);s+=e,o-=e}return{constrained:!0,variables:{x2:Math.max(s,Math.min(o,i))}}}return{}}}})},e}}class AttractToGrid extends ConstraintComponent{static componentType="attractToGrid";static createAttributesObject(){let e=super.createAttributesObject();return e.dx={createComponentOfType:"number",createStateVariable:"dx",defaultValue:1,public:!0},e.dy={createComponentOfType:"number",createStateVariable:"dy",defaultValue:1,public:!0},e.dz={createComponentOfType:"number",createStateVariable:"dz",defaultValue:1,public:!0},e.xoffset={createComponentOfType:"number",createStateVariable:"xoffset",defaultValue:0,public:!0},e.yoffset={createComponentOfType:"number",createStateVariable:"yoffset",defaultValue:0,public:!0},e.zoffset={createComponentOfType:"number",createStateVariable:"zoffset",defaultValue:0,public:!0},e.xthreshold={createComponentOfType:"number",createStateVariable:"xthreshold",defaultValue:.2,public:!0},e.ythreshold={createComponentOfType:"number",createStateVariable:"ythreshold",defaultValue:.2,public:!0},e.zthreshold={createComponentOfType:"number",createStateVariable:"zthreshold",defaultValue:.2,public:!0},e.includeGridlines={createComponentOfType:"boolean",createStateVariable:"includeGridlines",defaultValue:!1,public:!0},e.ignoreGraphBounds={createComponentOfType:"boolean",createStateVariable:"ignoreGraphBounds",defaultValue:!1,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.independentComponentConstraints={returnDependencies:()=>({includeGridlines:{dependencyType:"stateVariable",variableName:"includeGridlines"}}),definition:({dependencyValues:e})=>({setValue:{independentComponentConstraints:e.includeGridlines}})},e.applyComponentConstraint={returnDependencies:()=>({dx:{dependencyType:"stateVariable",variableName:"dx"},dy:{dependencyType:"stateVariable",variableName:"dy"},dz:{dependencyType:"stateVariable",variableName:"dz"},xoffset:{dependencyType:"stateVariable",variableName:"xoffset"},yoffset:{dependencyType:"stateVariable",variableName:"yoffset"},zoffset:{dependencyType:"stateVariable",variableName:"zoffset"},xthreshold:{dependencyType:"stateVariable",variableName:"xthreshold"},ythreshold:{dependencyType:"stateVariable",variableName:"ythreshold"},zthreshold:{dependencyType:"stateVariable",variableName:"zthreshold"},constraintAncestor:{dependencyType:"ancestor",componentType:"constraints",variableNames:["graphXmin","graphXmax","graphYmin","graphYmax"]},graphAncestor:{dependencyType:"ancestor",componentType:"graph",variableNames:["xmin","xmax","ymin","ymax"]},ignoreGraphBounds:{dependencyType:"stateVariable",variableName:"ignoreGraphBounds"}}),definition:({dependencyValues:e})=>({setValue:{applyComponentConstraint:function({variables:t,scales:n}){let r;if(null!==e.constraintAncestor&&null!==e.constraintAncestor.stateValues.graphXmin?r="constraints":null!==e.graphAncestor&&null!==e.graphAncestor.stateValues.xmin&&(r="graph"),"x1"in t){let n=findFiniteNumericalValue(t.x1);if(!Number.isFinite(n))return{};let a=e.dx,i=e.xoffset,s=Math.round((n-i)/a)*a+i;if(!Number.isFinite(s))return{};if(!e.ignoreGraphBounds){let t,n;"constraints"===r?(t=e.constraintAncestor.stateValues.graphXmin,n=e.constraintAncestor.stateValues.graphXmax):"graph"===r&&(t=e.graphAncestor.stateValues.xmin,n=e.graphAncestor.stateValues.xmax),void 0!==t&&(sn&&(s=Math.floor((n-i)/a)*a+i))}return Math.abs(n-s)n&&(s=Math.floor((n-i)/a)*a+i))}return Math.abs(n-s)({dx:{dependencyType:"stateVariable",variableName:"dx"},dy:{dependencyType:"stateVariable",variableName:"dy"},dz:{dependencyType:"stateVariable",variableName:"dz"},xoffset:{dependencyType:"stateVariable",variableName:"xoffset"},yoffset:{dependencyType:"stateVariable",variableName:"yoffset"},zoffset:{dependencyType:"stateVariable",variableName:"zoffset"},xthreshold:{dependencyType:"stateVariable",variableName:"xthreshold"},ythreshold:{dependencyType:"stateVariable",variableName:"ythreshold"},zthreshold:{dependencyType:"stateVariable",variableName:"zthreshold"},includeGridlines:{dependencyType:"stateVariable",variableName:"includeGridlines"},applyComponentConstraint:{dependencyType:"stateVariable",variableName:"applyComponentConstraint"}}),definition:({dependencyValues:e})=>({setValue:{applyConstraint:function({variables:t,scales:n}){let r={},a=!1;for(let i in t){let s=e.applyComponentConstraint({variables:{[i]:t[i]},scales:n});s.constrained&&(a=!0,r[i]=s.variables[i])}if(!a)return{};if(!e.includeGridlines){if(void 0!==t.x1&&void 0===r.x1)return{};if(void 0!==t.x2&&void 0===r.x2)return{};if(void 0!==t.x3&&void 0===r.x3)return{}}return{constrained:a,variables:r}}}})},e}}class ConstrainTo extends ConstraintComponent{static componentType="constrainTo";static returnChildGroups(){return[{group:"graphical",componentTypes:["_graphical"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nearestPointFunctions={returnDependencies:()=>({graphicalChildren:{dependencyType:"child",childGroups:["graphical"],variableNames:["nearestPoint"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let t=[];for(let n of e.graphicalChildren)n.stateValues.nearestPoint?t.push(n.stateValues.nearestPoint):console.warn(`cannot attract to ${n.componentName} as it doesn't have a nearestPoint state variable`);return{setValue:{nearestPointFunctions:t}}}},e.applyConstraint={returnDependencies:()=>({nearestPointFunctions:{dependencyType:"stateVariable",variableName:"nearestPointFunctions"}}),definition:({dependencyValues:e})=>({setValue:{applyConstraint:function({variables:t,scales:n}){let r=1/0,a={},i=!1,s={};for(let e in t)s[e]=findFiniteNumericalValue(t[e]);for(let o of e.nearestPointFunctions){let e=o({variables:t,scales:n});if(void 0===e)continue;let l={},u=0;if(void 0!==s.x1){if(void 0===e.x1)continue;l.x1=e.x1,u+=Math.pow(s.x1-e.x1,2)}if(void 0!==s.x2){if(void 0===e.x2)continue;l.x2=e.x2,u+=Math.pow(s.x2-e.x2,2)}if(void 0!==s.x3){if(void 0===e.x3)continue;l.x3=e.x3,u+=Math.pow(s.x3-e.x3,2)}u({thresholdAttr:{dependencyType:"attributeComponent",attributeName:"threshold",variableNames:["value"]},constraintsAncestor:{dependencyType:"ancestor",componentType:"constraints",variableNames:["graphXmin"]}}),definition({dependencyValues:e}){if(e.thresholdAttr)return{setValue:{threshold:e.thresholdAttr.stateValues.value}};{let t=.02;return null!==e.constraintsAncestor&&null!==e.constraintsAncestor.stateValues.graphXmin||(t=.5),{useEssentialOrDefaultValue:{threshold:{defaultValue:t}}}}},inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t})=>t.thresholdAttr?{success:!0,instructions:[{setDependency:"thresholdAttr",desiredValue:e.threshold}]}:{success:!0,instructions:[{setEssentialValue:"threshold",value:e.threshold}]}},e.nearestPointFunctions={returnDependencies:()=>({graphicalChildren:{dependencyType:"child",childGroups:["graphical"],variableNames:["nearestPoint"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let t=[];for(let n of e.graphicalChildren)n.stateValues.nearestPoint?t.push(n.stateValues.nearestPoint):console.warn(`cannot attract to ${n.componentName} as it doesn't have a nearestPoint state variable`);return{setValue:{nearestPointFunctions:t}}}},e.graphXscale={additionalStateVariablesDefined:["graphYscale"],returnDependencies:()=>({graphAncestor:{dependencyType:"ancestor",componentType:"constraints",variableNames:["scales"]}}),definition({dependencyValues:e}){if(!e.graphAncestor)return{setValue:{graphXscale:null,graphYscale:null}};return{setValue:{graphXscale:e.graphAncestor.stateValues.xscale,graphYscale:e.graphAncestor.stateValues.yscale}}}},e.applyConstraint={returnDependencies:()=>({nearestPointFunctions:{dependencyType:"stateVariable",variableName:"nearestPointFunctions"},threshold:{dependencyType:"stateVariable",variableName:"threshold"},constraintsAncestor:{dependencyType:"ancestor",componentType:"constraints",variableNames:["scales"]}}),definition({dependencyValues:e}){let t=1,n=1;return e.constraintsAncestor&&([t,n]=e.constraintsAncestor.stateValues.scales),{setValue:{applyConstraint:function({variables:r,scales:a}){let i=1/0,s={},o={};for(let e in r)o[e]=findFiniteNumericalValue(r[e]);for(let l of e.nearestPointFunctions){let e=l({variables:r,scales:a});if(void 0===e)continue;let u={},c=0;if(void 0!==o.x1){if(void 0===e.x1)continue;u.x1=e.x1,c+=Math.pow((o.x1-e.x1)/t,2)}if(void 0!==o.x2){if(void 0===e.x2)continue;u.x2=e.x2,c+=Math.pow((o.x2-e.x2)/n,2)}if(void 0!==o.x3){if(void 0===e.x3)continue;u.x3=e.x3,c+=Math.pow(o.x3-e.x3,2)}ce.threshold*e.threshold?{}:{constrained:!0,variables:s}}}}}},e}}class ConstraintUnion extends ConstraintComponent{static componentType="constraintUnion";static returnChildGroups(){return[{group:"constraints",componentTypes:["_constraint"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.applyConstraint={returnDependencies:()=>({constraintChildren:{dependencyType:"child",childGroups:["constraints"],variableNames:["applyConstraint","applyComponentConstraint"],variablesOptional:!0}}),definition:({dependencyValues:e})=>({setValue:{applyConstraint:function({variables:t,scales:n}){let r;if(1===e.constraintChildren.length){let a=e.constraintChildren[0];return r=a.stateValues.applyConstraint?a.stateValues.applyConstraint({variables:t,scales:n}):applyConstraintFromComponentConstraints({variables:t,applyComponentConstraint:a.stateValues.applyComponentConstraint,scales:n}),r}let a,i=1/0,s={};for(let[o,l]of e.constraintChildren.entries()){if(r=l.stateValues.applyConstraint?l.stateValues.applyConstraint({variables:t,scales:n}):applyConstraintFromComponentConstraints({variables:t,applyComponentConstraint:l.stateValues.applyComponentConstraint,scales:n}),!r.constrained)continue;let e=0;for(let n in r.variables){let a=findFiniteNumericalValue(t[n]),i=findFiniteNumericalValue(r.variables[n]);if(!Number.isFinite(a)||!Number.isFinite(i)){e=1/0;break}e+=Math.pow(a-i,2)}e({constraintChild:{dependencyType:"child",childGroups:["constraints"],variableNames:["applyConstraint","applyComponentConstraint"],variablesOptional:!0},independentComponentConstraints:{dependencyType:"stateVariable",variableName:"independentComponentConstraints"},threshold:{dependencyType:"stateVariable",variableName:"threshold"}}),definition:({dependencyValues:e})=>({setValue:{applyConstraint:function({variables:t,scales:n}){let r,a=e.constraintChild[0];if(!a)return{};r=a.stateValues.applyConstraint?a.stateValues.applyConstraint({variables:t,scales:n}):applyConstraintFromComponentConstraints({variables:t,applyComponentConstraint:a.stateValues.applyComponentConstraint,scales:n});let i=0;for(let e in r.variables){let n=findFiniteNumericalValue(t[e]),a=findFiniteNumericalValue(r.variables[e]);if(!Number.isFinite(n)||!Number.isFinite(a))return{};i+=Math.pow(n-a,2)}return i>e.threshold*e.threshold?{}:r}}})},e}}class Intersection extends CompositeComponent{static componentType="intersection";static assignNamesToReplacements=!0;static stateVariableToEvaluateAfterReplacements="readyToExpandWhenResolved";static createAttributesObject(){let e=super.createAttributesObject();return e.assignNamesSkip={createPrimitiveOfType:"number"},e}static returnChildGroups(){return[{group:"lines",componentTypes:["line"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.lineChildren={returnDependencies:()=>({lineChildren:{dependencyType:"child",childGroups:["lines"],variableNames:["numericalCoeff0","numericalCoeffvar1","numericalCoeffvar2","nDimensions"]}}),definition:({dependencyValues:e})=>({setValue:{lineChildren:e.lineChildren}})},e.readyToExpandWhenResolved={returnDependencies:()=>({lineChildren:{dependencyType:"stateVariable",variableName:"lineChildren"}}),markStale:()=>({updateReplacements:!0}),definition:function(){return{setValue:{readyToExpandWhenResolved:!0}}}},e}static async createSerializedReplacements({component:e,components:t,componentInfoObjects:n}){let r=await e.stateValues.lineChildren,a=r.length;if(0===a)return{replacements:[]};if(1===a){let a=r[0].componentName,i=await t[a].serialize({sourceAttributesToIgnoreRecursively:["isResponse"]});i.state||(i.state={}),i.state.draggable=!1,i.state.fixed=!0;let s=postProcessCopy({serializedComponents:[i],componentName:e.componentName}),o=e.attributes.newNamespace?.primitive;return s=processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:s,parentName:e.componentName,parentCreatesNewNamespace:o,componentInfoObjects:n}).serializedComponents,{replacements:s}}if(a>2)return console.warn("Haven't implemented intersection for more than two objects"),{replacements:[]};let i=r[0],s=r[1];if(2!==i.stateValues.nDimensions||2!==s.stateValues.nDimensions)return console.log("Intersection of lines implemented only in 2D"),{replacements:[]};let o=i.stateValues.numericalCoeffvar1,l=i.stateValues.numericalCoeffvar2,u=i.stateValues.numericalCoeff0,c=s.stateValues.numericalCoeffvar1,p=s.stateValues.numericalCoeffvar2,d=s.stateValues.numericalCoeff0;if(!(Number.isFinite(o)&&Number.isFinite(l)&&Number.isFinite(u)&&Number.isFinite(c)&&Number.isFinite(p)&&Number.isFinite(d)))return console.log("Intersection of lines implemented only for constant coefficients"),{replacements:[]};let m=o*p-c*l;if(Math.abs(m)<1e-14){if(Math.abs(d*o-u*c)>1e-14)return{replacements:[]};if(0===o&&0===l&&0===u||0===c&&0===p&&0===d)return{replacements:[]};{let a=r[0].componentName,i=await t[a].serialize({sourceAttributesToIgnoreRecursively:["isResponse"]});i.state||(i.state={}),i.state.draggable=!1,i.state.fixed=!0;let s=postProcessCopy({serializedComponents:[i],componentName:e.componentName}),o=e.attributes.newNamespace?.primitive;return s=processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:s,parentName:e.componentName,parentCreatesNewNamespace:o,componentInfoObjects:n}).serializedComponents,{replacements:s}}}let h=(d*l-u*p)/m,f=(u*c-d*o)/m,y=[{componentType:"point",state:{coords:me$3.fromAst(["vector",h,f]),draggable:!1,fixed:!0}}],g=e.attributes.newNamespace?.primitive;return y=processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:y,parentName:e.componentName,parentCreatesNewNamespace:g,componentInfoObjects:n}).serializedComponents,{replacements:y}}static async calculateReplacementChanges({component:e,components:t,componentInfoObjects:n}){let r=[],a=(await this.createSerializedReplacements({component:e,components:t,componentInfoObjects:n})).replacements,i=a.length,s=!0;if(i===e.replacements.length){s=!1;for(let t=0;t({children:{dependencyType:"child",childGroups:["anything"],variableNames:["width"]},columns:{dependencyType:"stateVariable",variableName:"columns"}}),definition:function({dependencyValues:e}){let t=[],n=e.children.map((e=>e.stateValues.width));if(null!==e.columns){let r;if(-1!==e.columns.indexOf(","))r=e.columns.split(",").map(Number);else if(-1!==e.columns.indexOf("-")){let[t,n]=e.columns.split("-");r=[];for(let e=Number(t);e<=n;e++)r.push(e)}else r=[Number(e.columns)];let a={},i={};for(let e of r){let t=[],r=0;for(let a=0;ai&&(i=n[t]);t.push(i),r+=Number(i)}a[e]=t,i[e]=r}let s=-1;for(let e of r){let e=Number.POSITIVE_INFINITY,n=-1;for(let t of r)i[t]<=e&&t>s&&(e=i[t],n=t);e=this.state.threshold?{}:{variables:{x1:p,x2:d},constraintIndices:[i+1],constrained:!0}}}class ConditionalContent extends CompositeComponent{static componentType="conditionalContent";static includeBlankStringChildren=!0;static assignNamesToReplacements=!0;static createsVariants=!0;static stateVariableToEvaluateAfterReplacements="readyToExpandWhenResolved";static keepChildrenSerialized({serializedComponent:e,componentInfoObjects:t}){if(void 0===e.children)return[];let n=t.componentIsSpecifiedType,r=[];for(let[t,a]of e.children.entries())n(a,"case")||n(a,"else")||r.push(t);return r}static createAttributesObject(){let e=super.createAttributesObject();return e.assignNamesSkip={createPrimitiveOfType:"number"},e.maximumNumberToShow={createComponentOfType:"number",createStateVariable:"maximumNumberToShow",defaultValue:null,public:!0},e.condition={createComponentOfType:"boolean"},e}static returnChildGroups(){return[{group:"cases",componentTypes:["case"]},{group:"elses",componentTypes:["else"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.baseConditionSatisfied={returnDependencies:()=>({conditionAttr:{dependencyType:"attributeComponent",attributeName:"condition",variableNames:["value"]}}),definition:function({dependencyValues:e}){let t=!0;return e.conditionAttr&&(t=e.conditionAttr.stateValues.value),{setValue:{baseConditionSatisfied:t}}}},e.nCases={additionalStateVariablesDefined:["caseChildren"],returnDependencies:()=>({caseChildren:{dependencyType:"child",childGroups:["cases"]}}),definition:({dependencyValues:e})=>({setValue:{caseChildren:e.caseChildren,nCases:e.caseChildren.length}})},e.elseChild={returnDependencies:()=>({elseChild:{dependencyType:"child",childGroups:["elses"]}}),definition({dependencyValues:e}){let t=null;return e.elseChild.length>0&&(t=e.elseChild[0]),{setValue:{elseChild:t}}}},e.haveCasesOrElse={returnDependencies:()=>({nCases:{dependencyType:"stateVariable",variableName:"nCases"},elseChild:{dependencyType:"stateVariable",variableName:"elseChild"}}),definition:({dependencyValues:e})=>({setValue:{haveCasesOrElse:e.nCases>0||null!==e.elseChild}})},e.selectedIndices={returnDependencies:()=>({caseChildren:{dependencyType:"child",childGroups:["cases"],variableNames:["conditionSatisfied"]},elseChild:{dependencyType:"stateVariable",variableName:"elseChild"},maximumNumberToShow:{dependencyType:"stateVariable",variableName:"maximumNumberToShow"}}),definition({dependencyValues:e}){let t=[];for(let[n,r]of e.caseChildren.entries())r.stateValues.conditionSatisfied&&t.push(n);if(0===t.length&&e.elseChild&&t.push(e.caseChildren.length),null!==e.maximumNumberToShow&&t.length>e.maximumNumberToShow){let n=Math.max(0,Math.floor(e.maximumNumberToShow));t=t.slice(0,n)}return{setValue:{selectedIndices:t}}}},e.readyToExpandWhenResolved={returnDependencies:()=>({baseConditionSatisfied:{dependencyType:"stateVariable",variableName:"baseConditionSatisfied"},haveCasesOrElse:{dependencyType:"stateVariable",variableName:"haveCasesOrElse"},selectedIndices:{dependencyType:"stateVariable",variableName:"selectedIndices"}}),markStale:()=>({updateReplacements:!0}),definition:()=>({setValue:{readyToExpandWhenResolved:!0}})},e.isVariantComponent={returnDependencies:()=>({}),definition:()=>({setValue:{isVariantComponent:!0}})},e.generatedVariantInfo={returnDependencies:({sharedParameters:e,componentInfoObjects:t})=>({variantSeed:{dependencyType:"value",value:e.variantSeed},variantDescendants:{dependencyType:"descendant",componentTypes:Object.keys(t.componentTypesCreatingVariants),variableNames:["isVariantComponent","generatedVariantInfo"],useReplacementsForComposites:!0,recurseToMatchedChildren:!1,variablesOptional:!0,includeNonActiveChildren:!0,ignoreReplacementsOfEncounteredComposites:!0}}),definition({dependencyValues:e,componentName:t}){let n={seed:e.variantSeed,meta:{createdBy:t}},r=n.subvariants=[];for(let t of e.variantDescendants)t.stateValues.isVariantComponent?r.push(t.stateValues.generatedVariantInfo):t.stateValues.generatedVariantInfo&&r.push(...t.stateValues.generatedVariantInfo.subvariants);return{setValue:{generatedVariantInfo:n}}}},e}static async createSerializedReplacements({component:e,components:t,workspace:n,componentInfoObjects:r}){let a=await this.getReplacements(e,t,r);return n.previousSelectedIndices=[...await e.stateValues.selectedIndices],n.previousBaseConditionSatisfied=await e.stateValues.baseConditionSatisfied,{replacements:a}}static async getReplacements(e,t,n){if(!await e.stateValues.baseConditionSatisfied)return[];let r=[];if(await e.stateValues.haveCasesOrElse){let n=await e.stateValues.caseChildren;for(let[a,i]of(await e.stateValues.selectedIndices).entries()){let s,o,l;ie===i[t]))){if(r.previousBaseConditionSatisfied===s)return[];if(!s){let t={changeType:"changeReplacementsToWithhold",replacementsToWithhold:e.replacements.length};return r.previousBaseConditionSatisfied=s,[t]}if(e.replacements.length===e.serializedChildren.length){let e={changeType:"changeReplacementsToWithhold",replacementsToWithhold:0};return r.previousBaseConditionSatisfied=s,[e]}}let o=[],l=await this.getReplacements(e,n,a),u={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:0,numberReplacementsToReplace:e.replacements.length,serializedReplacements:l,replacementsToWithhold:0};return o.push(u),r.previousSelectedIndices=[...i],r.previousBaseConditionSatisfied=s,o}static setUpVariant({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n}){setUpVariantSeedAndRng({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n,useSubpartVariantRng:!0})}get allPotentialRendererTypes(){let e=super.allPotentialRendererTypes;if(this.serializedChildren){let t=this.potentialRendererTypesFromSerializedComponents(this.serializedChildren);for(let n of t)e.includes(n)||e.push(n)}return e}}class AsList extends InlineComponent{static componentType="asList";static renderChildren=!0;static returnChildGroups(){return[{group:"inline",componentTypes:["_inline"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["inline"],variableNames:["text"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let t=[];for(let n of e.inlineChildren)"object"!=typeof n?t.push(n.toString()):"string"==typeof n.stateValues.text?t.push(n.stateValues.text):t.push("");return{setValue:{text:t.join(", ")}}}},e.latex={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["inline"],variableNames:["text","latex"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let t=[];for(let n of e.inlineChildren)"object"!=typeof n?t.push(n.toString()):"string"==typeof n.stateValues.latex?t.push(n.stateValues.latex):"string"==typeof n.stateValues.text?t.push(n.stateValues.text):t.push("");return{setValue:{latex:t.join(", ")}}}},e}}function normalizeIndex(e){if(null!==e&&""!==e){if(Number.isFinite(Number(e)))return Number(e)-1;if("string"==typeof e)return lettersToNumber(e)}}function lettersToNumber(e){let t=0,n=(e=e.toUpperCase()).length,r=n;for(;(r-=1)>-1;){let a=e.charCodeAt(r)-64;if(a<1||a>26)return void console.warn("Cannot convert "+e+" to a number");t+=a*Math.pow(26,n-1-r)}return t--,t} /** * @license * Copyright (c) 2022 Handsoncode. All rights reserved. @@ -838,4 +838,4 @@ class MathPlugin extends FunctionPlugin{fact(e,t){return this.runFunction(e.args /** * @license * Copyright (c) 2022 Handsoncode. All rights reserved. - */class HyperFormulaNS extends HyperFormula{}HyperFormulaNS.HyperFormula=HyperFormula,HyperFormulaNS.ErrorType=ErrorType,HyperFormulaNS.CellType=CellType,HyperFormulaNS.CellValueType=CellValueType,HyperFormulaNS.CellValueDetailedType=CellValueDetailedType,HyperFormulaNS.DetailedCellError=DetailedCellError,HyperFormulaNS.ExportedCellChange=ExportedCellChange,HyperFormulaNS.ExportedNamedExpressionChange=ExportedNamedExpressionChange,HyperFormulaNS.ConfigValueTooBigError=ConfigValueTooBigError,HyperFormulaNS.ConfigValueTooSmallError=ConfigValueTooSmallError,HyperFormulaNS.EvaluationSuspendedError=EvaluationSuspendedError,HyperFormulaNS.ExpectedOneOfValuesError=ExpectedOneOfValuesError,HyperFormulaNS.ExpectedValueOfTypeError=ExpectedValueOfTypeError,HyperFormulaNS.FunctionPlugin=FunctionPlugin,HyperFormulaNS.FunctionPluginValidationError=FunctionPluginValidationError,HyperFormulaNS.InvalidAddressError=InvalidAddressError,HyperFormulaNS.InvalidArgumentsError=InvalidArgumentsError,HyperFormulaNS.LanguageNotRegisteredError=LanguageNotRegisteredError,HyperFormulaNS.LanguageAlreadyRegisteredError=LanguageAlreadyRegisteredError,HyperFormulaNS.MissingTranslationError=MissingTranslationError,HyperFormulaNS.NamedExpressionDoesNotExistError=NamedExpressionDoesNotExistError,HyperFormulaNS.NamedExpressionNameIsAlreadyTakenError=NamedExpressionNameIsAlreadyTakenError,HyperFormulaNS.NamedExpressionNameIsInvalidError=NamedExpressionNameIsInvalidError,HyperFormulaNS.NoOperationToRedoError=NoOperationToRedoError,HyperFormulaNS.NoOperationToUndoError=NoOperationToUndoError,HyperFormulaNS.NoRelativeAddressesAllowedError=NoRelativeAddressesAllowedError,HyperFormulaNS.NoSheetWithIdError=NoSheetWithIdError,HyperFormulaNS.NoSheetWithNameError=NoSheetWithNameError,HyperFormulaNS.NotAFormulaError=NotAFormulaError,HyperFormulaNS.NothingToPasteError=NothingToPasteError,HyperFormulaNS.ProtectedFunctionTranslationError=ProtectedFunctionTranslationError,HyperFormulaNS.SheetNameAlreadyTakenError=SheetNameAlreadyTakenError,HyperFormulaNS.SheetSizeLimitExceededError=SheetSizeLimitExceededError,HyperFormulaNS.SourceLocationHasArrayError=SourceLocationHasArrayError,HyperFormulaNS.TargetLocationHasArrayError=TargetLocationHasArrayError,HyperFormulaNS.UnableToParseError=UnableToParseError;const defaultLanguage=Config.defaultConfig.language;HyperFormula.registerLanguage(defaultLanguage,dictionary),HyperFormula.languages[dictionary.langCode]=dictionary;for(const e of Object.getOwnPropertyNames(plugins))e.startsWith("_")||HyperFormula.registerFunctionPlugin(plugins[e]);class Spreadsheet extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{onChange:this.onChange.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="spreadsheet";static createAttributesObject(){let e=super.createAttributesObject();return e.width={createComponentOfType:"_componentSize",createStateVariable:"width",defaultValue:{size:100,isAbsolute:!1},public:!0,forRenderer:!0},e.minNumRows={createComponentOfType:"number",createStateVariable:"minNumRows",defaultValue:4,public:!0,forRenderer:!0},e.minNumColumns={createComponentOfType:"number",createStateVariable:"minNumColumns",defaultValue:4,public:!0,forRenderer:!0},e.height={createComponentOfType:"_componentSize"},e.columnHeaders={createComponentOfType:"boolean",createStateVariable:"columnHeaders",defaultValue:!0,public:!0,forRenderer:!0},e.rowHeaders={createComponentOfType:"boolean",createStateVariable:"rowHeaders",defaultValue:!0,public:!0,forRenderer:!0},e.fixedRowsTop={createComponentOfType:"integer",createStateVariable:"fixedRowsTop",defaultValue:0,clamp:[0,1/0],public:!0,forRenderer:!0},e.fixedColumnsLeft={createComponentOfType:"integer",createStateVariable:"fixedColumnsLeft",defaultValue:0,clamp:[0,1/0],public:!0,forRenderer:!0},e.hiddenColumns={createComponentOfType:"numberList",createStateVariable:"hiddenColumns",defaultValue:[],public:!0,forRenderer:!0},e.hiddenRows={createComponentOfType:"numberList",createStateVariable:"hiddenRows",defaultValue:[],public:!0,forRenderer:!0},e}static returnChildGroups(){return[{group:"cells",componentTypes:["cell"]},{group:"rows",componentTypes:["row"]},{group:"columns",componentTypes:["column"]},{group:"cellBlocks",componentTypes:["cellBlock"]},{group:"dataFrames",componentTypes:["dataFrame"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.cellNameToRowCol={additionalStateVariablesDefined:["cellNamesByRowCol"],returnDependencies:()=>({cellRelatedChildren:{dependencyType:"child",childGroups:["cells","rows","columns","cellBlocks"],variableNames:["rowNum","colNum","prescribedCellsWithColNum","prescribedCellsWithRowNum","prescribedCellsRowsColumnsBlocks"],variablesOptional:!0}}),definition({dependencyValues:e,componentInfoObjects:t}){let n=determineCellMapping({cellRelatedChildren:e.cellRelatedChildren,componentInfoObjects:t});return{setValue:{cellNameToRowCol:n.cellNameToRowCol,cellNamesByRowCol:n.cellNamesByRowCol}}}},e.numRows={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({minNumRows:{dependencyType:"stateVariable",variableName:"minNumRows"},cellNamesByRowCol:{dependencyType:"stateVariable",variableName:"cellNamesByRowCol"},dataFrameChild:{dependencyType:"child",childGroups:["dataFrames"],variableNames:["numRows"]}}),definition({dependencyValues:e}){let t=e.minNumRows;return Number.isFinite(t)||(t=4),t=Math.max(t,e.cellNamesByRowCol.length),e.dataFrameChild.length>0&&(t=Math.max(t,e.dataFrameChild[0].stateValues.numRows)),{setValue:{numRows:t}}}},e.numColumns={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({minNumColumns:{dependencyType:"stateVariable",variableName:"minNumColumns"},cellNamesByRowCol:{dependencyType:"stateVariable",variableName:"cellNamesByRowCol"},dataFrameChild:{dependencyType:"child",childGroups:["dataFrames"],variableNames:["numColumns"]}}),definition({dependencyValues:e}){let t=e.minNumColumns;Number.isFinite(t)||(t=4);for(let n of e.cellNamesByRowCol)n&&(t=Math.max(t,n.length));return e.dataFrameChild.length>0&&(t=Math.max(t,e.dataFrameChild[0].stateValues.numColumns)),{setValue:{numColumns:t}}}},e.height={public:!0,shadowingInstructions:{createComponentOfType:"_componentSize"},forRenderer:!0,returnDependencies:()=>({heightAttr:{dependencyType:"attributeComponent",attributeName:"height",variableNames:["componentSize"]},numRows:{dependencyType:"stateVariable",variableName:"numRows"}}),definition({dependencyValues:e}){if(null===e.heightAttr){let t;return t=Number.isFinite(e.numRows)&&e.numRows>=0?40+23*e.numRows:132,{setValue:{height:{size:t,isAbsolute:!0}}}}return{setValue:{height:e.heightAttr.stateValues.componentSize}}}},e.cells={public:!0,shadowingInstructions:{createComponentOfType:"cell",returnWrappingComponents:e=>"cell"===e?[]:"row"===e?[["row"]]:"column"===e?[["column"]]:[["row"],["cellBlock"]]},forRenderer:!0,isArray:!0,entryPrefixes:["cell","row","column","range","rows","columns"],nDimensions:2,defaultValueByArrayKey:()=>"",hasEssential:!0,shadowVariable:!0,stateVariablesDeterminingDependencies:["cellNamesByRowCol"],returnArraySizeDependencies:()=>({numRows:{dependencyType:"stateVariable",variableName:"numRows"},numColumns:{dependencyType:"stateVariable",variableName:"numColumns"}}),returnArraySize:({dependencyValues:e})=>[e.numRows,e.numColumns],returnEntryDimensions:e=>["range","rows","columns"].includes(e)?2:1,getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("cell"===e){let e,r,a=/^([a-zA-Z]+)([1-9]\d*)$/,i=t.match(a);if(i)r=i[1],e=i[2];else{let n=/^\(([a-zA-Z]+|\d+),([a-zA-Z]+|\d+)\)$/;if(i=t.match(n),!i)return[];e=i[1],r=i[2]}let s=normalizeIndex(e),o=normalizeIndex(r);return s>=0&&o>=0&&(!n||s=0))return[];if(!n)return[String(e)+",0"];if(!(e=0))return[];if(!n)return["0,"+String(e)];if(!(e=0&&a>=0&&r>=0&&i>=0))return[];if(!n)return[String(e)+","+String(r)];let l=Math.min(Math.min(e,a),n[0]-1),u=Math.min(Math.max(e,a),n[0]-1),c=Math.min(Math.min(r,i),n[1]-1),p=Math.min(Math.max(r,i),n[1]-1),d=[];for(let e=l;e<=u;e++){let t=[],n=String(e)+",";for(let e=c;e<=p;e++)t.push(n+e);d.push(t)}return d}{if(!n)return[String(0)+","+String(0)];let e=[];for(let t=0;t"cell("+e.split(",").map((e=>Number(e)+1)).join(",")+")",arrayVarNameFromPropIndex(e,t){if("cells"===t||"rows"===t)return 1===e.length?"row"+e[0]:`cell(${e[0]},${e[1]})`;if("columns"===t)return 1===e.length?"column"+e[0]:`cell(${e[1]},${e[0]})`;if("row"===t.slice(0,3)){return`cell(${t.slice(3)},${e[0]})`}if("column"===t.slice(0,6)){let n=t.slice(6);return`cell(${e[0]},${n})`}return null},returnArrayDependenciesByKey({stateValues:e,arrayKeys:t}){let n={},r=e.cellNamesByRowCol;for(let e of t){let[t,a]=e.split(",");r[t]&&r[t][a]&&(n[e]={cellText:{dependencyType:"stateVariable",componentName:r[t][a],variableName:"text",variablesOptional:!0}})}return{dependenciesByKey:n,globalDependencies:{dataFrameChild:{dependencyType:"child",childGroups:["dataFrames"],variableNames:["dataFrame","numRows","numColumns"]}}}},arrayDefinitionByKey({dependencyValuesByKey:e,globalDependencyValues:t,arrayKeys:n}){let r,a,i={},s={},o=null;t.dataFrameChild.length>0&&(o=t.dataFrameChild[0],r=o.stateValues.numRows,a=o.stateValues.numColumns);for(let t of n){let[n,l]=t.split(",");void 0!==e[t].cellText?i[t]=e[t].cellText:n0&&(l.setValue={cells:i}),Object.keys(s).length>0&&(l.useEssentialOrDefaultValue={cells:s}),l},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t}){let n=[];for(let r in e.cells)if(void 0!==t[r].cellText)n.push({setDependency:t[r].cellText,desiredValue:e.cells[r]});else{let t=e.cells[r];n.push({setEssentialValue:"cells",value:{[r]:null===t?"":String(t)}})}return{success:!0,instructions:n}}},e.evaluatedCells={isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"cell",returnWrappingComponents:e=>"evaluatedCell"===e?[]:"evaluatedRow"===e?[["row"]]:"evaluatedColumn"===e?[["column"]]:[["row"],["cellBlock"]]},entryPrefixes:["evaluatedCell","evaluatedRow","evaluatedColumn","evaluatedRange","evaluatedRows","evaluatedColumns"],nDimensions:2,stateVariablesDeterminingDependencies:["cellNamesByRowCol"],returnArraySizeDependencies:()=>({numRows:{dependencyType:"stateVariable",variableName:"numRows"},numColumns:{dependencyType:"stateVariable",variableName:"numColumns"}}),returnArraySize:({dependencyValues:e})=>[e.numRows,e.numColumns],returnEntryDimensions:e=>["evaluatedRange","evaluatedRows","evaluatedColumns"].includes(e)?2:1,getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("evaluatedCell"===e){let e,r,a=/^([a-zA-Z]+)([1-9]\d*)$/,i=t.match(a);if(i)r=i[1],e=i[2];else{let n=/^\(([a-zA-Z]+|\d+),([a-zA-Z]+|\d+)\)$/;if(i=t.match(n),!i)return[];e=i[1],r=i[2]}let s=normalizeIndex(e),o=normalizeIndex(r);return s>=0&&o>=0&&(!n||s=0))return[];if(!n)return[String(e)+",0"];if(!(e=0))return[];if(!n)return["0,"+String(e)];if(!(e=0&&a>=0&&r>=0&&i>=0))return[];if(!n)return[String(e)+","+String(r)];let l=Math.min(Math.min(e,a),n[0]-1),u=Math.min(Math.max(e,a),n[0]-1),c=Math.min(Math.min(r,i),n[1]-1),p=Math.min(Math.max(r,i),n[1]-1),d=[];for(let e=l;e<=u;e++){let t=[],n=String(e)+",";for(let e=c;e<=p;e++)t.push(n+e);d.push(t)}return d}{if(!n)return[String(0)+","+String(0)];let e=[];for(let t=0;t"evaluatedCell("+e.split(",").map((e=>Number(e)+1)).join(",")+")",arrayVarNameFromPropIndex(e,t){if("evaluatedCells"===t||"evaluatedRows"===t)return 1===e.length?"evaluatedRow"+e[0]:`evaluatedCell(${e[0]},${e[1]})`;if("evaluatedColumns"===t)return 1===e.length?"evaluatedColumn"+e[0]:`evaluatedCell(${e[1]},${e[0]})`;if("evaluatedRow"===t.slice(0,12)){return`evaluatedCell(${t.slice(12)},${e[0]})`}if("evaluatedColumn"===t.slice(0,15)){let n=t.slice(15);return`evaluatedCell(${e[0]},${n})`}return null},returnArrayDependenciesByKey:()=>({globalDependencies:{cells:{dependencyType:"stateVariable",variableName:"cells"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t=HyperFormula.buildFromArray(e.cells,{licenseKey:"gpl-v3"}).getSheetValues(0),n={};for(let e in t){let r=t[e];for(let t in r)n[[e,t]]=r[t]}return{setValue:{evaluatedCells:n}}}},e.pointsInCells={isArray:!0,nDimensions:2,public:!0,shadowingInstructions:{createComponentOfType:"point"},entryPrefixes:["pointsInCell","pointsInRow","pointsInColumn","pointsInRange","pointsInRows","pointsInColumns"],returnArraySizeDependencies:()=>({numRows:{dependencyType:"stateVariable",variableName:"numRows"},numColumns:{dependencyType:"stateVariable",variableName:"numColumns"}}),returnArraySize:({dependencyValues:e})=>[e.numRows,e.numColumns],returnEntryDimensions:e=>["pointsInRange","pointsInRows","pointsInColumns"].includes(e)?2:1,getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("pointsInCell"===e){let e,r,a=/^([a-zA-Z]+)([1-9]\d*)$/,i=t.match(a);if(i)r=i[1],e=i[2];else{let n=/^\(([a-zA-Z]+|\d+),([a-zA-Z]+|\d+)\)$/;if(i=t.match(n),!i)return[];e=i[1],r=i[2]}let s=normalizeIndex(e),o=normalizeIndex(r);return s>=0&&o>=0&&(!n||s=0))return[];if(!n)return[String(e),",0"];if(!(e>=0&&e=0))return[];if(!n)return["0,"+String(e)];if(!(e=0&&a>=0&&r>=0&&i>=0))return[];if(!n)return[String(e)+","+String(r)];let l=Math.min(Math.min(e,a),n[0]-1),u=Math.min(Math.max(e,a),n[0]-1),c=Math.min(Math.min(r,i),n[1]-1),p=Math.min(Math.max(r,i),n[1]-1),d=[];for(let e=l;e<=u;e++){let t=[],n=String(e)+",";for(let e=c;e<=p;e++)t.push(n+e);d.push(t)}return d}{if(!n)return[String(0)+","+String(0)];let e=[];for(let t=0;t"pointsInCell("+e.split(",").map((e=>Number(e)+1)).join(",")+")",arrayVarNameFromPropIndex(e,t){if("pointsInCells"===t||"pointsInRows"===t)return 1===e.length?"pointsInRow"+e[0]:`pointsInCell(${e[0]},${e[1]})`;if("pointsInColumns"===t)return 1===e.length?"pointsInColumn"+e[0]:`pointsInCell(${e[1]},${e[0]})`;if("pointsInRow"===t.slice(0,11)){return`pointsInCell(${t.slice(11)},${e[0]})`}if("pointsInColumn"===t.slice(0,14)){let n=t.slice(14);return`pointsInCell(${e[0]},${n})`}return null},returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=n.split(",").map((e=>Number(e)+1)).join(",");t[n]={cellText:{dependencyType:"stateVariable",variableName:`evaluatedCell(${e})`,variablesOptional:!0}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t,a=e[r].cellText;if(a){try{t=me$3.fromAst(textToAst$1.convert(a))}catch(e){n[r]=null;continue}Array.isArray(t.tree)&&vectorOperators.includes(t.tree[0])?n[r]=t:n[r]=null}else n[r]=null}return{setValue:{pointsInCells:n}}}},e}async onChange({changes:e,source:t,actionId:n}){if(e){let t={};for(let n of e){let[e,r,a,i]=n;t[[e,r]]=null===i?"":i}return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"cells",value:t}],actionId:n,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:t}})}this.coreFunctions.resolveAction({actionId:n})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}function determineCellMapping({cellRelatedChildren:e,rowOffset:t=0,colOffset:n=0,cellNameToRowCol:r={},cellNamesByRowCol:a=[],componentInfoObjects:i}){var s=t,o=n,l=n,u=t,c=n,p=t,d=n;for(let m of e)if(i.isInheritedComponentType({inheritedComponentType:m.componentType,baseComponentType:"cell"})){let e=m,i=normalizeIndex(e.stateValues.rowNum),u=normalizeIndex(e.stateValues.colNum);void 0===i?(i=s,void 0===u?u=l:u+=n):(i+=t,void 0===u?u=o:u+=n),addCellToMapping({cell:e,rowIndex:i,colIndex:u,cellNameToRowCol:r,cellNamesByRowCol:a}),p=Math.max(i,p),d=Math.max(u,d),s=i,o=u,l=u+1}else if(i.isInheritedComponentType({inheritedComponentType:m.componentType,baseComponentType:"row"})){let e=m,i=normalizeIndex(e.stateValues.rowNum);void 0===i?i=u:i+=t;let c=e.stateValues.prescribedCellsWithColNum,h=n;for(let e of c){let t=normalizeIndex(e.stateValues.colNum);void 0===t?t=h:t+=n,addCellToMapping({cell:e,rowIndex:i,colIndex:t,cellNameToRowCol:r,cellNamesByRowCol:a}),h=t+1,p=Math.max(i,p),d=Math.max(t,d)}u=i+1,s=i+1,l=o=n}else if(i.isInheritedComponentType({inheritedComponentType:m.componentType,baseComponentType:"column"})){let e=m,i=normalizeIndex(e.stateValues.colNum);void 0===i?i=c:i+=n;let u=e.stateValues.prescribedCellsWithRowNum,h=t;for(let e of u){let n=normalizeIndex(e.stateValues.rowNum);void 0===n?n=h:n+=t,addCellToMapping({cell:e,rowIndex:n,colIndex:i,cellNameToRowCol:r,cellNamesByRowCol:a}),h=n+1,p=Math.max(n,p),d=Math.max(i,d)}c=i+1,s=t,l=o=i+1}else if(i.isInheritedComponentType({inheritedComponentType:m.componentType,baseComponentType:"cellBlock"})){let e=m,u=normalizeIndex(e.stateValues.rowNum),c=normalizeIndex(e.stateValues.colNum);void 0===u?(u=s,void 0===c?c=l:c+=n):(u+=t,void 0===c?c=o:c+=n);let h=determineCellMapping({cellRelatedChildren:e.stateValues.prescribedCellsRowsColumnsBlocks,rowOffset:u,colOffset:c,cellNameToRowCol:r,cellNamesByRowCol:a,componentInfoObjects:i});p=Math.max(h.maxRowIndex,p),d=Math.max(h.maxColIndex,d),s=u,o=c,l=h.maxColIndex+1}return{maxRowIndex:p,maxColIndex:d,cellNameToRowCol:r,cellNamesByRowCol:a}}function addCellToMapping({cell:e,rowIndex:t,colIndex:n,cellNameToRowCol:r,cellNamesByRowCol:a}){if(r[e.componentName]=[t,n],void 0===a[t]&&(a[t]=[]),void 0!==a[t][n]){console.warn(`Cell is overwriting previous cell at rowNum=${t+1}, colNum=${n+1}`),r[a[t][n]]=null}a[t][n]=e.componentName}class DiscreteSimulationResultList extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{onChange:this.onChange.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="DiscreteSimulationResultList";static rendererType="spreadsheet";static createAttributesObject(){let e=super.createAttributesObject();return e.width={createComponentOfType:"_componentSize",createStateVariable:"width",defaultValue:{size:100,isAbsolute:!1},public:!0,forRenderer:!0},e.minNumRows={createComponentOfType:"number",createStateVariable:"minNumRows",defaultValue:1,public:!0,forRenderer:!0},e.minNumColumns={createComponentOfType:"number",createStateVariable:"minNumColumns",defaultValue:1,public:!0,forRenderer:!0},e.height={createComponentOfType:"_componentSize"},e.columnHeaders={createComponentOfType:"boolean",createStateVariable:"columnHeaders",defaultValue:!0,public:!0,forRenderer:!0},e.rowHeaders={createComponentOfType:"boolean",createStateVariable:"rowHeaders",defaultValue:!0,public:!0,forRenderer:!0},e.fixedRowsTop={createComponentOfType:"integer",createStateVariable:"fixedRowsTop",defaultValue:0,clamp:[0,1/0],public:!0,forRenderer:!0},e.fixedColumnsLeft={createComponentOfType:"integer",createStateVariable:"fixedColumnsLeft",defaultValue:0,clamp:[0,1/0],public:!0,forRenderer:!0},e.hiddenColumns={createComponentOfType:"numberList",createStateVariable:"hiddenColumns",defaultValue:[],public:!0,forRenderer:!0},e.hiddenRows={createComponentOfType:"numberList",createStateVariable:"hiddenRows",defaultValue:[],public:!0,forRenderer:!0},e.allIterates={createComponentOfType:"mathList",createStateVariable:"allIterates",defaultValue:[]},e.headerRow={createComponentOfType:"textList",createStateVariable:"headerRow",defaultValue:null},e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.displayDigitsAttr){let n=null===e.displayDigitsAttr||t.displayDigitsAttr,r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!n&&!r){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({allIterates:{dependencyType:"stateVariable",variableName:"allIterates"},headerRow:{dependencyType:"stateVariable",variableName:"headerRow"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"}}),definition({dependencyValues:e,usedDefault:t}){let n=[],r=1,a=!1;if(e.allIterates.length>0&&Array.isArray(e.allIterates[0].tree)&&vectorOperators.includes(e.allIterates[0].tree[0])&&(r=e.allIterates[0].tree.length-1,a=!0),e.headerRow){let t=[],a=Math.min(e.headerRow.length,r+1);for(let n=0;n({minNumRows:{dependencyType:"stateVariable",variableName:"minNumRows"},cells:{dependencyType:"stateVariable",variableName:"cells"}}),definition({dependencyValues:e}){let t=e.minNumRows;return Number.isFinite(t)||(t=4),t=Math.max(t,e.cells.length),{setValue:{numRows:t}}}},e.numColumns={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({minNumColumns:{dependencyType:"stateVariable",variableName:"minNumColumns"},cells:{dependencyType:"stateVariable",variableName:"cells"}}),definition({dependencyValues:e}){let t=e.minNumColumns;Number.isFinite(t)||(t=4);for(let n of e.cells)n&&(t=Math.max(t,n.length));return{setValue:{numColumns:t}}}},e.height={public:!0,shadowingInstructions:{createComponentOfType:"_componentSize"},forRenderer:!0,returnDependencies:()=>({heightAttr:{dependencyType:"attributeComponent",attributeName:"height",variableNames:["componentSize"]},numRows:{dependencyType:"stateVariable",variableName:"numRows"}}),definition({dependencyValues:e}){if(null===e.heightAttr){let t;return t=Number.isFinite(e.numRows)&&e.numRows>=0?50+20*e.numRows:130,{setValue:{height:{size:t,isAbsolute:!0}}}}return{setValue:{height:e.heightAttr.stateValues.componentSize}}}},e}async onChange({changes:e,source:t,actionId:n}){if(e){let t={};for(let n of e){let[e,r,a,i]=n;t[[e,r]]=null===i?"":i}return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"cells",value:t}],actionId:n,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:t}})}this.coreFunctions.resolveAction({actionId:n})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class DiscreteSimulationResultPolyline extends GraphicalComponent{constructor(e){super(e),Object.assign(this.actions,{movePolyline:this.movePolyline.bind(this),finalizePolylinePosition:this.finalizePolylinePosition.bind(this)})}static componentType="discreteSimulationResultPolyline";static rendererType="polyline";static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.allIterates={createComponentOfType:"mathList",createStateVariable:"allIteratesSub",defaultValue:[]},e.seriesNumber={createComponentOfType:"number",createStateVariable:"seriesNumber",defaultValue:null},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){let t=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(t&&(t+=" "),t+=e.selectedStyle.lineStyleWord),t&&(t+=" "),t+=e.selectedStyle.lineColorWord,{setValue:{styleDescription:t}}}},e.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({styleDescription:{dependencyType:"stateVariable",variableName:"styleDescription"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescriptionWithNoun:e.styleDescription+" polyline"}}}},e.allIterates={returnDependencies:()=>({allIteratesSub:{dependencyType:"stateVariable",variableName:"allIteratesSub"}}),definition:function({dependencyValues:e}){return{setValue:{allIterates:e.allIteratesSub.filter((e=>Number.isFinite(e.tree)||Array.isArray(e.tree)&&vectorOperators.includes(e.tree[0])&&e.tree.slice(1).every(Number.isFinite)))}}}},e.nVertices={public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies:()=>({allIterates:{dependencyType:"stateVariable",variableName:"allIterates"}}),definition:function({dependencyValues:e}){return{setValue:{nVertices:e.allIterates.length}}}},e.nDimensions={public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies:()=>({}),definition:function({dependencyValues:e}){return{setValue:{nDimensions:2}}}},e.vertices={public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"vertexX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,nDimensions:2,entryPrefixes:["vertexX","vertex"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("vertexX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("vertices"===t)return 1===e.length?"vertex"+e[0]:`vertexX${e[0]}_${e[1]}`;if("vertex"===t.slice(0,6)){let n=Number(t.slice(6));if(Number.isInteger(n)&&n>0)return`vertexX${n}_${e[0]}`}return null},getAllArrayKeys(e,t=!0,n){function r(e){if(1===e.length)return Array.from(Array(e[0]),((e,t)=>String(t)));{let n=e[0],a=r(e.slice(1)),i=[];for(let e=0;ee+","+t))):i.push(a.map((t=>e+","+t)));return i}}if(n){if(0!==n.length&&e){let t=[...e];return t[0]=n[0],r(t)}return[]}return e&&0!==e.length?r(e):[]},returnArraySizeDependencies:()=>({nVertices:{dependencyType:"stateVariable",variableName:"nVertices"}}),returnArraySize:({dependencyValues:e})=>[e.nVertices,2],returnArrayDependenciesByKey:()=>({globalDependencies:{seriesNumber:{dependencyType:"stateVariable",variableName:"seriesNumber"},allIterates:{dependencyType:"stateVariable",variableName:"allIterates"}}}),arrayDefinitionByKey({globalDependencyValues:e,arraySize:t}){let n={};for(let r=0;r({nVertices:{dependencyType:"stateVariable",variableName:"nVertices"}}),returnArraySize:({dependencyValues:e})=>[e.nVertices],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={vertex:{dependencyType:"stateVariable",variableName:"vertex"+(Number(n)+1)}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].vertex.map((e=>e.evaluate_to_constant()));t.every((e=>Number.isFinite(e)))||(t=Array(t.length).fill(NaN)),n[r]=t}return{setValue:{numericalVertices:n}}}},e.nearestPoint={returnDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},numericalVertices:{dependencyType:"stateVariable",variableName:"numericalVertices"},nVertices:{dependencyType:"stateVariable",variableName:"nVertices"}}),definition({dependencyValues:e}){let t,n,r=e.nDimensions,a=e.nVertices,i=e.numericalVertices,s=[],o=i[0]?.[0],l=i[0]?.[1];for(let e=1;e=1?{x1:h,x2:f}:{x1:l+g*a*n,x2:u+g*y*o};let b=Math.pow((d-r.x1)/n,2)+Math.pow((m-r.x2)/o,2);b0&&(p.x3=0),p}}}}},e}async movePolyline({pointCoords:e,transient:t,sourceInformation:n,actionId:r}){let a={};for(let t in e)a[t+",0"]=me$3.fromAst(e[t][0]),a[t+",1"]=me$3.fromAst(e[t][1]);return t?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"vertices",value:a,sourceInformation:n}],transient:!0,actionId:r}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"vertices",value:a,sourceInformation:n}],actionId:r,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{pointCoordinates:e}}})}async finalizePolylinePosition(){return await this.actions.movePolyline({pointCoords:await this.stateValues.numericalVertices,transient:!1})}}class Cell extends BaseComponent{static componentType="cell";static rendererType="cell";static renderChildren=!0;static includeBlankStringChildren=!0;static primaryStateVariableForDefinition="text";static createAttributesObject(){let e=super.createAttributesObject();return e.rowNum={createComponentOfType:"text",createStateVariable:"rowNum",defaultValue:null,public:!0},e.colNum={createComponentOfType:"text",createStateVariable:"colNum",defaultValue:null,public:!0},e.colSpan={createComponentOfType:"integer",createStateVariable:"colSpan",defaultValue:1,public:!0,forRenderer:!0},e.halign={createComponentOfType:"text"},e.bottom={createComponentOfType:"text"},e.right={createComponentOfType:"text"},e.prefill={createComponentOfType:"text",createStateVariable:"prefill",defaultValue:"",public:!0},e}static returnChildGroups(){return[{group:"maths",componentTypes:["math"]},{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.halign={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,hasEssential:!0,defaultValue:"left",returnDependencies:()=>({halignAttr:{dependencyType:"attributeComponent",attributeName:"halign",variableNames:["value"]},parentHalign:{dependencyType:"parentStateVariable",variableName:"halign"},tabularHalign:{dependencyType:"ancestor",componentType:"tabular",variableNames:["halign"]}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.halignAttr){let t=e.halignAttr.stateValues.value;return["left","center","right","justify"].includes(t)||(t="left"),{setValue:{halign:t}}}return!t.parentHalign&&e.parentHalign?{setValue:{halign:e.parentHalign}}:!t.tabularHalign&&e.tabularHalign?{setValue:{halign:e.tabularHalign.stateValues.halign}}:{useEssentialOrDefaultValue:{halign:!0}}}},e.bottom={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,hasEssential:!0,defaultValue:"none",returnDependencies:()=>({bottomAttr:{dependencyType:"attributeComponent",attributeName:"bottom",variableNames:["value"]},parentBottom:{dependencyType:"parentStateVariable",variableName:"bottom"},tabularBottom:{dependencyType:"ancestor",componentType:"tabular",variableNames:["bottom"]}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.bottomAttr){let t=e.bottomAttr.stateValues.value;return["none","minor","medium","major"].includes(t)||(t="none"),{setValue:{bottom:t}}}return!t.parentBottom&&e.parentBottom?{setValue:{bottom:e.parentBottom}}:!t.tabularBottom&&e.tabularBottom?{setValue:{bottom:e.tabularBottom.stateValues.bottom}}:{useEssentialOrDefaultValue:{bottom:!0}}}},e.right={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,hasEssential:!0,defaultValue:"none",returnDependencies:()=>({rightAttr:{dependencyType:"attributeComponent",attributeName:"right",variableNames:["value"]},tabularRight:{dependencyType:"ancestor",componentType:"tabular",variableNames:["right"]}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.rightAttr){let t=e.rightAttr.stateValues.value;return["none","minor","medium","major"].includes(t)||(t="none"),{setValue:{right:t}}}return!t.tabularRight&&e.tabularRight?{setValue:{right:e.tabularRight.stateValues.right}}:{useEssentialOrDefaultValue:{right:!0}}}},e.inHeader={public:!0,shadowingInstructions:{createComponentOfType:"booloean"},forRenderer:!0,defaultValue:!1,returnDependencies:()=>({parentHeader:{dependencyType:"parentStateVariable",variableName:"header"}}),definition:({dependencyValues:e})=>({setValue:{inHeader:!0===e.parentHeader}})},e.onlyMathChild={returnDependencies:()=>({mathChild:{dependencyType:"child",childGroups:["maths"]},otherChildren:{dependencyType:"child",childGroups:["anything"]}}),definition:({dependencyValues:e})=>({setValue:{onlyMathChild:1===e.mathChild.length&&0===e.otherChildren.length}})},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},hasEssential:!0,forRenderer:!0,returnDependencies:()=>({children:{dependencyType:"child",childGroups:["maths","anything"],variableNames:["text"],variablesOptional:!0},prefill:{dependencyType:"stateVariable",variableName:"prefill"}}),definition({dependencyValues:e}){if(0===e.children.length)return{useEssentialOrDefaultValue:{text:{defaultValue:e.prefill}}};let t="";for(let n of e.children)"object"==typeof n?n.stateValues.text&&(t+=n.stateValues.text):t+=n.toString();return{setValue:{text:t}}},inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t})=>0===t.children.length?{success:!0,instructions:[{setEssentialValue:"text",value:null===e.text?"":String(e.text)}]}:1===t.children.length?"object"==typeof t.children[0]&&void 0===t.children[0].stateValues.text?{success:!1}:{success:!0,instructions:[{setDependency:"children",desiredValue:e.text,childIndex:0,variableIndex:0}]}:{success:!1}},e.math={public:!0,shadowingInstructions:{createComponentOfType:"math"},stateVariablesDeterminingDependencies:["onlyMathChild"],returnDependencies:({stateValues:e})=>e.onlyMathChild?{mathChild:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]}}:{text:{dependencyType:"stateVariable",variableName:"text"}},definition({dependencyValues:e}){if(e.mathChild)return{setValue:{math:e.mathChild[0].stateValues.value}};{let t;try{t=me$3.fromAst(textToAst$1.convert(e.text))}catch(e){t=me$3.fromAst("_")}return{setValue:{math:t}}}},async inverseDefinition({desiredStateVariableValues:e,dependencyValues:t,stateValues:n,workspace:r}){if(t.mathChild)return{success:!0,instructions:[{setDependency:"mathChild",desiredValue:e.math,childIndex:0,variableIndex:0}]};return{success:!0,instructions:[{setDependency:"text",desiredValue:(await preprocessMathInverseDefinition({desiredValue:e.math,stateValues:n,variableName:"math",workspace:r})).desiredValue.toString()}]}}},e.number={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({math:{dependencyType:"stateVariable",variableName:"math"}}),definition({dependencyValues:e}){let t=e.math.evaluate_to_constant();return Number.isFinite(t)||(t=NaN),{setValue:{number:t}}},inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setDependency:"math",desiredValue:me$3.fromAst(e.number)}]})},e}static adapters=["text","math","number"]}class Row extends BaseComponent{static componentType="row";static rendererType="row";static renderChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.rowNum={createComponentOfType:"text",createStateVariable:"rowNum",defaultValue:null,public:!0},e.header={createComponentOfType:"boolean",createStateVariable:"header",defaultValue:!1,public:!0,forRenderer:!0},e.halign={createComponentOfType:"text"},e.valign={createComponentOfType:"text"},e.left={createComponentOfType:"text"},e.bottom={createComponentOfType:"text"},e}static returnChildGroups(){return[{group:"cells",componentTypes:["cell"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.halign={public:!0,shadowingInstructions:{createComponentOfType:"text"},defaultValue:"left",hasEssential:!0,returnDependencies:()=>({halignAttr:{dependencyType:"attributeComponent",attributeName:"halign",variableNames:["value"]},parentHalign:{dependencyType:"parentStateVariable",variableName:"halign"}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.halignAttr){let t=e.halignAttr.stateValues.value;return["left","center","right","justify"].includes(t)||(t="left"),{setValue:{halign:t}}}return null===e.parentHalign||t.parentHalign?{useEssentialOrDefaultValue:{halign:!0}}:{setValue:{halign:e.parentHalign}}}},e.valign={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,defaultValue:"middle",hasEssential:!0,returnDependencies:()=>({valignAttr:{dependencyType:"attributeComponent",attributeName:"valign",variableNames:["value"]},parentValign:{dependencyType:"parentStateVariable",variableName:"valign"}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.valignAttr){let t=e.valignAttr.stateValues.value;return["top","middle","bottom"].includes(t)||(t="middle"),{setValue:{valign:t}}}return null===e.parentValign||t.parentValign?{useEssentialOrDefaultValue:{valign:!0}}:{setValue:{valign:e.parentValign}}}},e.left={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,defaultValue:"none",hasEssential:!0,returnDependencies:()=>({leftAttr:{dependencyType:"attributeComponent",attributeName:"left",variableNames:["value"]},parentLeft:{dependencyType:"parentStateVariable",variableName:"left"}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.leftAttr){let t=e.leftAttr.stateValues.value;return["none","minor","medium","major"].includes(t)||(t="none"),{setValue:{left:t}}}return null===e.parentLeft||t.parentLeft?{useEssentialOrDefaultValue:{left:!0}}:{setValue:{left:e.parentLeft}}}},e.bottom={public:!0,shadowingInstructions:{createComponentOfType:"text"},defaultValue:"none",hasEssential:!0,returnDependencies:()=>({bottomAttr:{dependencyType:"attributeComponent",attributeName:"bottom",variableNames:["value"]},parentBottom:{dependencyType:"parentStateVariable",variableName:"bottom"}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.bottomAttr){let t=e.bottomAttr.stateValues.value;return["none","minor","medium","major"].includes(t)||(t="none"),{setValue:{bottom:t}}}return null===e.parentBottom||t.parentBottom?{useEssentialOrDefaultValue:{bottom:!0}}:{setValue:{bottom:e.parentBottom}}}},e.prescribedCellsWithColNum={returnDependencies:()=>({cellChildren:{dependencyType:"child",childGroups:["cells"],variableNames:["colNum"]}}),definition:({dependencyValues:e})=>({setValue:{prescribedCellsWithColNum:e.cellChildren}})},e}}class Column extends BaseComponent{static componentType="column";static rendererType="containerBlock";static renderChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.colNum={createComponentOfType:"text",createStateVariable:"colNum",defaultValue:null,public:!0},e}static returnChildGroups(){return[{group:"cells",componentTypes:["cell"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.prescribedCellsWithRowNum={returnDependencies:()=>({cellChildren:{dependencyType:"child",childGroups:["cells"],variableNames:["rowNum"]}}),definition:({dependencyValues:e})=>({setValue:{prescribedCellsWithRowNum:e.cellChildren}})},e}}class CellBlock extends BaseComponent{static componentType="cellBlock";static rendererType="containerBlock";static createAttributesObject(){let e=super.createAttributesObject();return e.rowNum={createComponentOfType:"text",createStateVariable:"rowNum",defaultValue:null,public:!0},e.colNum={createComponentOfType:"text",createStateVariable:"colNum",defaultValue:null,public:!0},e}static returnChildGroups(){return[{group:"children",componentTypes:["cell","row","column","cellblock"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.prescribedCellsRowsColumnsBlocks={returnDependencies:()=>({cellRelatedChildren:{dependencyType:"child",childGroups:["children"],variableNames:["rowNum","colNum","prescribedCellsWithColNum","prescribedCellsWithRowNum","prescribedCellsRowsColumnsBlocks"],variablesOptional:!0}}),definition:({dependencyValues:e})=>({setValue:{prescribedCellsRowsColumnsBlocks:e.cellRelatedChildren}})},e}}class Tabular extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="tabular";static rendererType="tabular";static renderChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.width={createComponentOfType:"_componentSize",createStateVariable:"width",defaultValue:{size:100,isAbsolute:!1},public:!0,forRenderer:!0},e.height={createComponentOfType:"_componentSize",createStateVariable:"height",defaultValue:null,public:!0,forRenderer:!0},e.halign={createComponentOfType:"text",createStateVariable:"halign",defaultValue:"left",public:!0,validValues:["left","center","right","justify"]},e.valign={createComponentOfType:"text",createStateVariable:"valign",defaultValue:"middle",public:!0,validValues:["top","middle","bottom"]},e.top={createComponentOfType:"text",createStateVariable:"top",defaultValue:"none",public:!0,validValues:["none","minor","medium","major"],forRenderer:!0},e.left={createComponentOfType:"text",createStateVariable:"left",defaultValue:"none",public:!0,validValues:["none","minor","medium","major"]},e.bottom={createComponentOfType:"text",createStateVariable:"bottom",defaultValue:"none",public:!0,validValues:["none","minor","medium","major"]},e.right={createComponentOfType:"text",createStateVariable:"right",defaultValue:"none",public:!0,validValues:["none","minor","medium","major"]},e}static returnChildGroups(){return[{group:"rows",componentTypes:["row"]}]}static returnStateVariableDefinitions(){return super.returnStateVariableDefinitions()}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class Table extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="table";static renderChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.suppressTableNameInTitle={createComponentOfType:"boolean",createStateVariable:"suppressTableNameInTitle",defaultValue:!1,forRenderer:!0},e.number={createComponentOfType:"boolean",createStateVariable:"number",defaultValue:!0,forRenderer:!0},e}static returnChildGroups(){return[{group:"titles",componentTypes:["title"]},{group:"inlinesBlocks",componentTypes:["_inline","_block"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.tableEnumeration={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,stateVariablesDeterminingDependencies:["number"],additionalStateVariablesDefined:[{variableName:"tableName",public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0}],returnDependencies({stateValues:e}){let t={};return e.number&&(t.tableCounter={dependencyType:"counter",counterName:"table"}),t},definition({dependencyValues:e}){if(void 0===e.tableCounter)return{setValue:{tableEnumeration:null,tableName:"Table"}};let t=String(e.tableCounter);return{setValue:{tableEnumeration:t,tableName:"Table "+t}}}},e.titleChildName={forRenderer:!0,returnDependencies:()=>({titleChild:{dependencyType:"child",childGroups:["titles"]}}),definition({dependencyValues:e}){let t=null;return e.titleChild.length>0&&(t=e.titleChild[0].componentName),{setValue:{titleChildName:t}}}},e.title={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({titleChild:{dependencyType:"child",childGroups:["titles"],variableNames:["text"]}}),definition({dependencyValues:e}){let t=null;return e.titleChild.length>0&&(t=e.titleChild[0].stateValues.text),{setValue:{title:t}}}},e}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class Figure extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="figure";static renderChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.suppressFigureNameInCaption={createComponentOfType:"boolean",createStateVariable:"suppressFigureNameInCaption",defaultValue:!1,forRenderer:!0},e.number={createComponentOfType:"boolean",createStateVariable:"number",defaultValue:!0,forRenderer:!0},e}static returnChildGroups(){return[{group:"captions",componentTypes:["caption"]},{group:"inlinesBlocks",componentTypes:["_inline","_block"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.figureEnumeration={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,stateVariablesDeterminingDependencies:["number"],additionalStateVariablesDefined:[{variableName:"figureName",public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0}],returnDependencies({stateValues:e}){let t={};return e.number&&(t.figureCounter={dependencyType:"counter",counterName:"figure"}),t},definition({dependencyValues:e}){if(void 0===e.figureCounter)return{setValue:{figureEnumeration:null,figureName:"Figure"}};let t=String(e.figureCounter);return{setValue:{figureEnumeration:t,figureName:"Figure "+t}}}},e.captionChildName={forRenderer:!0,returnDependencies:()=>({captionChild:{dependencyType:"child",childGroups:["captions"]}}),definition({dependencyValues:e}){let t=null;return e.captionChild.length>0&&(t=e.captionChild[0].componentName),{setValue:{captionChildName:t}}}},e.caption={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({captionChild:{dependencyType:"child",childGroups:["captions"],variableNames:["text"]}}),definition({dependencyValues:e}){let t=null;return e.captionChild.length>0&&(t=e.captionChild[0].stateValues.text),{setValue:{caption:t}}}},e}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class TextListFromString extends InlineComponent{static componentType="textListFromString";static rendererType="asList";static renderChildren=!0;static stateVariableForAttributeValue="texts";static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e}){let t=e.reduce((function(e,t){return"string"==typeof t?[...e,...t.split(/\s+/).filter((e=>e))]:[...e,t]}),[]);return{success:!0,newChildren:t}}}),e}static returnChildGroups(){return[{group:"strings",componentTypes:["string"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nComponents={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({stringChildren:{dependencyType:"child",childGroups:["strings"]}}),definition:function({dependencyValues:e}){return{setValue:{nComponents:e.stringChildren.length}}}},e.texts={public:!0,shadowingInstructions:{createComponentOfType:"text"},isArray:!0,entryPrefixes:["text"],returnArraySizeDependencies:()=>({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"}}),returnArraySize:({dependencyValues:e})=>[e.nComponents],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={stringChild:{dependencyType:"child",childGroups:["strings"],variableNames:["value"],childIndices:[n]}};return{dependenciesByKey:t}},arrayDefinitionByKey:function({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t)1===e[r].stringChild.length&&(n[r]=e[r].stringChild[0]);return{setValue:{texts:n}}}},e.nValues={isAlias:!0,targetVariableName:"nComponents"},e.values={isAlias:!0,targetVariableName:"texts"},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({texts:{dependencyType:"stateVariable",variableName:"texts"}}),definition:({dependencyValues:e})=>({setValue:{text:e.texts.join(", ")}})},e}}class VariantControl extends BaseComponent{static componentType="variantControl";static rendererType=void 0;static createAttributesObject(){let e=super.createAttributesObject();return e.nVariants={createPrimitiveOfType:"integer"},e.uniqueVariants={createPrimitiveOfType:"boolean"},e.variantsToInclude={createComponentOfType:"textListFromString"},e.variantsToExclude={createComponentOfType:"textListFromString"},e.variantNames={createComponentOfType:"textListFromString"},e.seeds={createComponentOfType:"textListFromString"},e}}class SelectFromSequence extends Sequence{static componentType="selectFromSequence";static assignNamesToReplacements=!0;static createsVariants=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.assignNamesSkip={createPrimitiveOfType:"number"},e.numberToSelect={createComponentOfType:"integer",createStateVariable:"numberToSelect",defaultValue:1,public:!0},e.withReplacement={createComponentOfType:"boolean",createStateVariable:"withReplacement",defaultValue:!1,public:!0},e.sortResults={createComponentOfType:"boolean",createStateVariable:"sortResults",defaultValue:!1,public:!0},e.excludeCombinations={createComponentOfType:"_componentListOfListsWithSelectableType"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();e.excludedCombinations={returnDependencies:()=>({excludeCombinations:{dependencyType:"attributeComponent",attributeName:"excludeCombinations",variableNames:["lists"]},type:{dependencyType:"stateVariable",variableName:"type"},numberToSelect:{dependencyType:"stateVariable",variableName:"numberToSelect"}}),definition:function({dependencyValues:e}){if(null!==e.excludeCombinations){let t=e.excludeCombinations.stateValues.lists.map((t=>t.slice(0,e.numberToSelect))).filter((t=>t.length===e.numberToSelect));if("number"===e.type)for(;;){let e=mergeContainingCombinations(t);if(!e.merged)break;t=e.combinations}return{setValue:{excludedCombinations:t}}}return{setValue:{excludedCombinations:[]}}}},e.variants={returnDependencies:()=>({variants:{dependencyType:"variants"}}),definition:function({dependencyValues:e}){return{setValue:{variants:e.variants}}}},e.selectedValues={immutable:!0,hasEssential:!0,shadowVariable:!0,additionalStateVariablesDefined:[{variableName:"selectedIndices",hasEssential:!0,shadowVariable:!0,immutable:!0}],returnDependencies:({sharedParameters:e})=>({numberToSelect:{dependencyType:"stateVariable",variableName:"numberToSelect"},withReplacement:{dependencyType:"stateVariable",variableName:"withReplacement"},length:{dependencyType:"stateVariable",variableName:"length"},from:{dependencyType:"stateVariable",variableName:"from"},step:{dependencyType:"stateVariable",variableName:"step"},exclude:{dependencyType:"stateVariable",variableName:"exclude"},excludedCombinations:{dependencyType:"stateVariable",variableName:"excludedCombinations"},type:{dependencyType:"stateVariable",variableName:"type"},lowercase:{dependencyType:"stateVariable",variableName:"lowercase"},sortResults:{dependencyType:"stateVariable",variableName:"sortResults"},variants:{dependencyType:"stateVariable",variableName:"variants"},variantRng:{dependencyType:"value",value:e.variantRng,doNotProxy:!0}}),definition:makeSelection},e.isVariantComponent={returnDependencies:()=>({}),definition:()=>({setValue:{isVariantComponent:!0}})},e.generatedVariantInfo={returnDependencies:()=>({selectedIndices:{dependencyType:"stateVariable",variableName:"selectedIndices"}}),definition:({dependencyValues:e,componentName:t})=>({setValue:{generatedVariantInfo:{indices:e.selectedIndices,meta:{createdBy:t}}}})};let t=e.readyToExpandWhenResolved.returnDependencies;return e.readyToExpandWhenResolved.returnDependencies=function(){let e=t();return e.selectedValues={dependencyType:"stateVariable",variableName:"selectedValues"},e},e}static async createSerializedReplacements({component:e,componentInfoObjects:t,flags:n}){let r=await e.stateValues.type;"letters"===r&&(r="text");let a=e.attributes.newNamespace?.primitive,i={};for(let t of["fixed","displayDigits","displaySmallAsZero","displayDecimals","padZeros"])t in e.attributes&&(i[t]=e.attributes[t]);let s={};Object.keys(i).length>0&&(s=convertAttributesForComponentType({attributes:i,componentType:r,componentInfoObjects:t,compositeCreatesNewNamespace:a,flags:n}));let o=[];for(let t of await e.stateValues.selectedValues)o.push({componentType:r,attributes:s,state:{value:t,fixed:!0}});return{replacements:processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:o,parentName:e.componentName,parentCreatesNewNamespace:a,componentInfoObjects:t}).serializedComponents}}static calculateReplacementChanges(){return[]}static determineNumberOfUniqueVariants({serializedComponent:e}){let t=1,n=!1,r=e.attributes.type.primitive,a=e.attributes.numberToSelect?.component;if(a){if("integer"!==a.componentType||1!==a.children?.length||"string"!=typeof a.children[0])return console.log("cannot determine unique variants of selectFromSequence as numberToSelect isn't constant number."),{success:!1};if(t=Number(a.children[0]),!(Number.isInteger(t)&&t>=0))return console.log("cannot determine unique variants of selectFromSequence as numberToSelect isn't a non-negative integer."),{success:!1}}let i=e.attributes.withReplacement?.component;if(i){if("boolean"!==i.componentType)return console.log("cannot determine unique variants of selectFromSequence as withReplacement isn't constant boolean."),{success:!1};if(1===i.children?.length&&"string"==typeof i.children[0])n="true"===i.children[0].toLowerCase();else{if(void 0!==i.children&&0!==i.children.length||"boolean"!=typeof i.state?.value)return console.log("cannot determine unique variants of selectFromSequence as withReplacement isn't constant boolean."),{success:!1};n=i.state.value}}let s={from:null,to:null,step:null,length:null},o=e.attributes.from?.component;if(o){let e=o.children[0];if(1!==e.children?.length||"string"!=typeof e.children[0])return console.log("cannot determine unique variants of selectFromSequence as from isn't a constant."),{success:!1};{let t;if("number"===r){if(t=Number(e.children[0]),!Number.isFinite(t))return console.log("cannot determine unique variants of selectFromSequence of number type as from isn't a number."),{success:!1}}else if("letters"===r){if(t=lettersToNumber$1(e.children[0]),!Number.isFinite(t))return console.log("cannot determine unique variants of selectFromSequence of letters type as from isn't a combination of letters."),{success:!1}}else{let n=getFromText({functionSymbols:["f","g"]});try{t=n(e.children[0])}catch(e){return console.log("cannot determine unique variants of selectFromSequence of math type as from isn't a valid math expression."),{success:!1}}}s.from=t}}let l=e.attributes.to?.component;if(l){let e=l.children[0];if(1!==e.children?.length||"string"!=typeof e.children[0])return console.log("cannot determine unique variants of selectFromSequence as to isn't a constant."),{success:!1};{let t;if("number"===r){if(t=Number(e.children[0]),!Number.isFinite(t))return console.log("cannot determine unique variants of selectFromSequence of number type as to isn't a number."),{success:!1}}else if("letters"===r){if(t=lettersToNumber$1(e.children[0]),!Number.isFinite(t))return console.log("cannot determine unique variants of selectFromSequence of letters type as to isn't a combination of letters."),{success:!1}}else{let n=getFromText({functionSymbols:["f","g"]});try{t=n(e.children[0])}catch(e){return console.log("cannot determine unique variants of selectFromSequence of math type as to isn't a valid math expression."),{success:!1}}}s.to=t}}let u=e.attributes.step?.component;if(u){if(1!==u.children?.length||"string"!=typeof u.children[0])return console.log("cannot determine unique variants of selectFromSequence as step isn't a constant."),{success:!1};{let e;if("number"===r){if(e=Number(u.children[0]),!Number.isFinite(e))return console.log("cannot determine unique variants of selectFromSequence of number type as step isn't a number."),{success:!1}}else if("letters"===r){if(e=Number(u.children[0]),!Number.isInteger(e))return console.log("cannot determine unique variants of selectFromSequence of letters type as step isn't an integer."),{success:!1}}else{let t=getFromText({functionSymbols:["f","g"]});try{e=t(u.children[0])}catch(e){return console.log("cannot determine unique variants of selectFromSequence of math type as step isn't a valid math expression."),{success:!1}}}s.step=e}}let c=e.attributes.length?.component;if(c){if(1!==c.children?.length||"string"!=typeof c.children[0])return console.log("cannot determine unique variants of selectFromSequence as length isn't a constant."),{success:!1};{let e=Number(c.children[0]);if(!Number.isInteger(e))return console.log("cannot determine unique variants of selectFromSequence as length isn't an integer."),{success:!1};s.length=e}}if(e.attributes.excludeCombinations)return console.log("have not implemented unique variants of a selectFromSequence with excludeCombinations"),{success:!1};let p=[],d=e.attributes.exclude?.component;if(d){if("math"===r)return console.log("have not implemented unique variants of a selectFromSequence of type math with exclude"),{success:!1};if(!d.children.every((e=>1===e.children?.length&&"string"==typeof e.children[0])))return console.log("have not implemented unique variants of a selectFromSequence with non-constant exclude"),{success:!1};if(p="letters"===r?d.children.map((e=>lettersToNumber$1(e.children[0]))):d.children.map((e=>Number(e.children[0]))),!p.every(Number.isFinite))return console.log("have not implemented unique variants of a selectFromSequence with non-constant exclude"),{success:!1}}s=calculateSequenceParameters(s);let m=s.length,h=[];if(p.length>0&&"math"!==r){p.sort(((e,t)=>e-t)),p=p.filter(((e,t,n)=>e!=n[t-1]));for(let e of p){if(es.length-1+1e-10)break;Math.abs(t-Math.round(t))<1e-10&&(m--,h.push(t))}}if(m<=0)return{success:!1};let f,y={excludeIndices:h,nOptions:m,numberToSelect:t,withReplacement:n};if(e.variants.uniqueVariantData=y,n||1===t)f=Math.pow(m,t);else{f=m;for(let e=m-1;e>m-t;e--)f*=e}return e.variants.numberOfVariants=f,{success:!0,numberOfVariants:f}}static getUniqueVariant({serializedComponent:e,variantIndex:t}){let n=e.variants?.numberOfVariants;if(void 0===n)return{success:!1};if(!Number.isInteger(t)||t<1||t>n)return{success:!1};let r=e.variants.uniqueVariantData,a=r.excludeIndices,i=r.nOptions,s=r.numberToSelect,o=r.withReplacement,l=function(e){let t=e;for(let e of a)t>=e&&t++;return t};if(1===s)return{success:!0,desiredVariant:{indices:[l(t-1)+1]}};let u=enumerateSelectionCombinations({numberOfIndices:s,numberOfOptions:i,maxNumber:t,withReplacement:o})[t-1].map(l).map((e=>e+1));return{success:!0,desiredVariant:{indices:u}}}}function makeSelection({dependencyValues:e}){if(e.numberToSelect<1)return{setEssentialValue:{selectedValues:[],selectedIndices:[]},setValue:{selectedValues:[],selectedIndices:[]}};let t=1;if(e.withReplacement||(t=e.numberToSelect),t>e.length)throw Error("Cannot select "+t+" values from a sequence of length "+e.length);if(e.variants&&void 0!==e.variants.desiredVariant){let t=e.variants.desiredVariant.indices;if(void 0!==t){if(t.length!==e.numberToSelect)throw Error("Number of indices specified for select must match number to select");if(t=t.map(Number),!t.every(Number.isInteger))throw Error("All indices specified for select must be integers");let n=e.length;t=t.map((e=>((e-1)%n+n)%n+1));let r=[];for(let n of t){let t=returnSequenceValueForIndex({index:n-1,from:e.from,step:e.step,length:e.length,exclude:e.exclude,type:e.type,lowercase:e.lowercase});if(null===t)throw Error("Specified index of selectfromsequence that was excluded");r.push(t)}if(checkForExcludedCombination({type:e.type,excludedCombinations:e.excludedCombinations,values:r}))throw Error("Specified indices of selectfromsequence that was an excluded combination");return{setEssentialValue:{selectedValues:r,selectedIndices:t},setValue:{selectedValues:r,selectedIndices:t}}}}let n,r,a=e.excludedCombinations.length;if("number"===e.type){a=0;let t=e.length-e.exclude.length;for(let n of e.excludedCombinations){let r=n.reduce(((e,t)=>e+(Number.isNaN(t)?1:0)),0);if(r>0)if(e.withReplacement)a+=Math.pow(t,r);else{let n=t-e.numberToSelect+r,i=n;for(let e=1;e.7*i){let t=0;for(let n=0;n.7*t){if("number"!==e.type||!e.excludedCombinations.some((e=>e.some(Number.isNaN))))throw Error("Excluded over 70% of combinations in selectFromSequence");if(a-=estimateNumberOfDuplicateCombinations(e.excludedCombinations,e.length-e.exclude.length,e.withReplacement),a>.7*t)throw Error("Excluded over 70% of combinations in selectFromSequence")}}let s=!1;for(let a=0;a<200;a++){let a=selectValuesAndIndices({stateValues:e,numberUniqueRequired:t,numberToSelect:e.numberToSelect,withReplacement:e.withReplacement,rng:e.variantRng});if(n=a.selectedValues,r=a.selectedIndices,!checkForExcludedCombination({type:e.type,excludedCombinations:e.excludedCombinations,values:n})){s=!0;break}}if(!s)throw Error("By extremely unlikely fluke, couldn't select combination of random values")}if(e.sortResults){let t=[];for(let[e,a]of n.entries())t.push({value:a,index:r[e]});"number"===e.type?t.sort(((e,t)=>e.value-t.value)):"letters"===e.type&&t.sort(((e,t)=>lettersToNumber$1(e.value)-lettersToNumber$1(t.value))),n=t.map((e=>e.value)),r=t.map((e=>e.index))}return{setEssentialValue:{selectedValues:n,selectedIndices:r},setValue:{selectedValues:n,selectedIndices:r}}}function selectValuesAndIndices({stateValues:e,numberUniqueRequired:t=1,numberToSelect:n=1,withReplacement:r=!1,rng:a}){let i=[],s=[];if(e.exclude.length+t<.5*e.length){for(let t=0;tl)throw Error("Cannot select "+t+" unique values from sequence of length "+l);if(1===t){for(let e=0;e0;e--){const t=a(),n=Math.floor(t*(e+1));[o[e],o[n]]=[o[n],o[e]]}let u=o.slice(0,n);return i=u.map((e=>e.value)),s=u.map((e=>e.originalIndex+1)),{selectedValues:i,selectedIndices:s}}function checkForExcludedCombination({type:e,excludedCombinations:t,values:n}){return"math"===e?t.some((e=>e.every(((e,t)=>e.equals(n[t]))))):"number"===e?t.some((e=>e.every(((e,t)=>Number.isNaN(e)||Math.abs(e-n[t])<=1e-14*Math.max(Math.abs(e),Math.abs(n[t])))))):t.some((e=>e.every(((e,t)=>e===n[t]))))}function mergeContainingCombinations(e){if(0===e.length)return{merged:!1,combinations:[]};let t=[e[0]],n=!1;for(let r of e.slice(1)){let e=[],a=!1;for(let n of t){if(a){e.push(n);continue}let t=[];a=!0;let i=null;for(let e=0;e!Number.isNaN(e)));[...new Set(e)].length===e.length&&a.push(o)}}}for(;;){let e=mergeContainingCombinations(a);if(!e.merged)break;a=e.combinations}let i=0;if(a.length>0)for(let e of a){let r=e.reduce(((e,t)=>e+(Number.isNaN(t)?1:0)),0);if(r>0)if(n)i+=Math.pow(t,r);else{let n=t-e.length+r,a=n;for(let e=1;e"string"==typeof e||e.doenetAttributes&&e.doenetAttributes.createdFromMacro)))return{success:!1};let r;r=t.type?t.type:"math",["math","text","number","boolean"].includes(r)||(console.warn(`Invalid type ${r}`),r="math");let a=returnGroupIntoComponentTypeSeparatedBySpaces({componentType:r,forceComponentType:!0})({matchedChildren:e,componentInfoObjects:n});if(a.success){return{success:!0,newChildren:a.newChildren.map((e=>({componentType:"option",children:[e]}))),newAttributes:{addLevelToAssignNames:{primitive:!0}}}}return{success:!1}}}),e}static returnChildGroups(){return[{group:"options",componentTypes:["option"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.variants={returnDependencies:()=>({variants:{dependencyType:"variants"}}),definition:function({dependencyValues:e}){return{setValue:{variants:e.variants}}}},e.currentVariantName={returnDependencies:({sharedParameters:e})=>({variantName:{dependencyType:"value",value:e.variantName}}),definition:({dependencyValues:e})=>({setValue:{currentVariantName:e.variantName}})},e.allVariantNames={returnDependencies:({sharedParameters:e})=>({allVariantNames:{dependencyType:"value",value:e.allVariantNames}}),definition:({dependencyValues:e})=>({setValue:{allVariantNames:e.allVariantNames}})},e.nOptions={additionalStateVariablesDefined:["optionChildren"],returnDependencies:()=>({optionChildren:{dependencyType:"child",childGroups:["options"],variableNames:["selectForVariants","selectWeight"]}}),definition:({dependencyValues:e})=>({setValue:{optionChildren:e.optionChildren,nOptions:e.optionChildren.length}})},e.availableVariants={returnDependencies:()=>({optionChildren:{dependencyType:"stateVariable",variableName:"optionChildren"},numberToSelect:{dependencyType:"stateVariable",variableName:"numberToSelect"},allVariantNames:{dependencyType:"stateVariable",variableName:"allVariantNames"}}),definition:function({dependencyValues:e}){let t={};for(let[n,r]of e.optionChildren.entries())for(let e of r.stateValues.selectForVariants){let r=e.toLowerCase();void 0===t[r]&&(t[r]=[]),t[r].push(n+1)}for(let n in t)if(t[n].length!==e.numberToSelect)throw Error("Invalid variant name for select. Variant name "+n+" appears in "+t[n].length+" options but number to select is "+numberToSelect);if(Object.keys(t).length>0){for(let n of e.allVariantNames)if(!(n in t))throw Error("Some variants are specified for select but no options are specified for possible variant name: "+n);for(let n in t)if(!e.allVariantNames.includes(n))throw Error("Variant name "+n+" that is specified for select is not a possible variant name.")}return{setValue:{availableVariants:t}}}},e.selectedIndices={immutable:!0,hasEssential:!0,shadowVariable:!0,returnDependencies:({sharedParameters:e})=>({numberToSelect:{dependencyType:"stateVariable",variableName:"numberToSelect"},withReplacement:{dependencyType:"stateVariable",variableName:"withReplacement"},optionChildren:{dependencyType:"stateVariable",variableName:"optionChildren"},nOptions:{dependencyType:"stateVariable",variableName:"nOptions"},currentVariantName:{dependencyType:"stateVariable",variableName:"currentVariantName"},variants:{dependencyType:"stateVariable",variableName:"variants"},availableVariants:{dependencyType:"stateVariable",variableName:"availableVariants"},variantRng:{dependencyType:"value",value:e.variantRng,doNotProxy:!0}}),definition:function({dependencyValues:e}){if(!(e.numberToSelect>=1)||0===e.nOptions)return{setEssentialValue:{selectedIndices:[]},setValue:{selectedIndices:[]}};if(e.variants&&void 0!==e.variants.desiredVariant){let t=e.variants.desiredVariant.indices;if(void 0!==t){if(t.length!==e.numberToSelect)throw Error("Number of indices specified for select must match number to select");if(t=t.map(Number),!t.every(Number.isInteger))throw Error("All indices specified for select must be integers");let n=e.nOptions;return t=t.map((e=>((e-1)%n+n)%n+1)),{setEssentialValue:{selectedIndices:t},setValue:{selectedIndices:t}}}}let t=e.availableVariants[e.currentVariantName];if(void 0!==t){if(e.numberToSelect>1){t=[...t];for(let n=e.numberToSelect-1;n>0;n--){const r=e.variantRng(),a=Math.floor(r*(n+1));[t[n],t[a]]=[t[a],t[n]]}}return{setEssentialValue:{selectedIndices:t},setValue:{selectedIndices:t}}}let n=[],r=1;if(e.withReplacement||(r=e.numberToSelect),r>e.nOptions)throw Error("Cannot select "+r+" components from only "+e.nOptions);let a=e.optionChildren.map((e=>e.stateValues.selectWeight)),i=a.reduce(((e,t)=>e+t));a=a.map((e=>e/i));let s=a.reduce(((e,t,n)=>[...e,t+(e[n-1]||0)]),[]),o=[...Array(s.length).keys()].map((e=>e+1));for(let t=0;tr?u=e:l=e}let c=o[u];n.push(c),!e.withReplacement&&te+t)),a=a.map((e=>e/i)),s=a.reduce(((e,t,n)=>[...e,t+(e[n-1]||0)]),[]))}return{setEssentialValue:{selectedIndices:n},setValue:{selectedIndices:n}}}},e.isVariantComponent={returnDependencies:()=>({}),definition:()=>({setValue:{isVariantComponent:!0}})},e.generatedVariantInfo={providePreviousValuesInDefinition:!0,returnDependencies:({componentInfoObjects:e})=>({selectedIndices:{dependencyType:"stateVariable",variableName:"selectedIndices"},variantDescendants:{dependencyType:"descendant",componentTypes:Object.keys(e.componentTypesCreatingVariants),variableNames:["isVariantComponent","generatedVariantInfo"],useReplacementsForComposites:!0,recurseToMatchedChildren:!1,variablesOptional:!0,includeNonActiveChildren:!0,ignoreReplacementsOfEncounteredComposites:!0}}),definition({dependencyValues:e,componentName:t,previousValues:n}){let r={indices:e.selectedIndices,meta:{createdBy:t}},a=r.subvariants=[];for(let t of e.variantDescendants)t.stateValues.isVariantComponent?a.push(t.stateValues.generatedVariantInfo):t.stateValues.generatedVariantInfo&&a.push(...t.stateValues.generatedVariantInfo.subvariants);for(let[e,t]of a.entries())if(!t.subvariants&&n.generatedVariantInfo){let t=n.generatedVariantInfo.subvariants;t[e].subvariants&&(a[e]=Object.assign({},a[e]),a[e].subvariants=t[e].subvariants)}return{setValue:{generatedVariantInfo:r}}}},e.readyToExpandWhenResolved={returnDependencies:()=>({selectedIndices:{dependencyType:"stateVariable",variableName:"selectedIndices"}}),definition:()=>({setValue:{readyToExpandWhenResolved:!0}})},e}static async createSerializedReplacements({component:e,components:t,componentInfoObjects:n}){let r=[],a=await e.stateValues.optionChildren;for(let n of await e.stateValues.selectedIndices){let e=a[n-1].componentName,i=t[e],s=deepClone(await i.stateValues.serializedChildren),o={componentType:"option",state:{rendered:!0},doenetAttributes:Object.assign({},i.doenetAttributes),children:s,originalName:e};i.attributes.newNamespace&&(o.attributes={newNamespace:{primitive:!0}}),r.push(o)}let i=gatherVariantComponents({serializedComponents:r,componentInfoObjects:n});if(e.variants&&void 0!==e.variants.desiredVariant){let t=e.variants.desiredVariant;if(void 0!==t&&void 0!==t.subvariants)for(let e in t.subvariants){let n=t.subvariants[e],r=i[e];if(void 0===r)break;r.variants.desiredVariant=n}}let s=e.attributes.newNamespace?.primitive,o=e.doenetAttributes.assignNames;o&&await e.stateValues.addLevelToAssignNames&&(o=o.map((e=>[e])));for(let e of r)!e.attributes?.newNamespace?.primitive&&e.children&&markToCreateAllUniqueNames(e.children);let l=[];for(let[t,a]of r.entries()){let r=processAssignNames({assignNames:o,serializedComponents:[a],parentName:e.componentName,parentCreatesNewNamespace:s,componentInfoObjects:n,indOffset:t});l.push(r.serializedComponents[0])}return{replacements:l}}static calculateReplacementChanges(){return[]}static determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t}){let n=e.variants?.numberOfVariants;if(void 0!==n)return{success:!0,numberOfVariants:n};let r=1,a=!1,i=e.attributes.numberToSelect?.component;if(i){if("integer"!==i.componentType||1!==i.children?.length||"string"!=typeof i.children[0])return console.log("cannot determine unique variants of selectFromSequence as numberToSelect isn't constant number."),{success:!1};if(r=Number(i.children[0]),!(Number.isInteger(r)&&r>=0))return console.log("cannot determine unique variants of selectFromSequence as numberToSelect isn't a non-negative integer."),{success:!1}}let s=e.attributes.withReplacement?.component;if(s){if("boolean"!==s.componentType)return console.log("cannot determine unique variants of selectFromSequence as withReplacement isn't constant boolean."),{success:!1};if(1===s.children?.length&&"string"==typeof s.children[0])a="true"===s.children[0].toLowerCase();else{if(void 0!==s.children&&0!==s.children.length||"boolean"!=typeof s.state?.value)return console.log("cannot determine unique variants of selectFromSequence as withReplacement isn't constant boolean."),{success:!1};a=s.state.value}}for(let t of e.children)if(t.attributes?.selectWeight||t.attributes?.selectForVariants)return console.log("Unique variants for select disabled if have an option with selectWeight or selectForVariants specified"),{success:!1};void 0===e.variants&&(e.variants={});let o=gatherVariantComponents({serializedComponents:e.children,componentInfoObjects:t});e.variants.descendantVariantComponents=o;let l=[];for(let e of o){let n=t.allComponentClasses[e.componentType].determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t});if(!n.success)return{success:!1};l.push(n.numberOfVariants)}let u={numberOfVariantsByChild:l,numberToSelect:r,withReplacement:a};if(0===l.length)n=1;else if(a||1===r){let e=l.reduce(((e,t)=>e+t));n=Math.pow(e,r)}else{let e=l.length;if(r>e)return{success:!1};let t=l[0],a=l.slice(1).every((e=>e===t));if(a){let a=e;for(let t=e-1;t>e-r;t--)a*=t;n=a*Math.pow(t,r)}else n=countOptions(l,r)}return e.variants.numberOfVariants=n,e.variants.uniqueVariants=!0,e.variants.uniqueVariantData=u,{success:!0,numberOfVariants:n}}static getUniqueVariant({serializedComponent:e,variantIndex:t,componentInfoObjects:n}){let r=e.variants?.numberOfVariants;if(void 0===r)return{success:!1};if(!Number.isInteger(t)||t<1||t>r)return{success:!1};let a,i=e.variants.uniqueVariantData,s=i.numberOfVariantsByChild,o=i.numberToSelect,l=i.withReplacement,u=e.children.length,c=e.children;if(0===s.length)return{success:!0,desiredVariant:{indices:[]}};a=1===o?[...Array(u).keys()].map((e=>[e])):enumerateSelectionCombinations({numberOfIndices:o,numberOfOptions:u,withReplacement:l});let p,d,m=a.length,h=a.map((e=>({combination:e,numberOfPossibilities:e.reduce(((e,t)=>e*s[t]),1)}))),f=[...Array(m).keys()],y=0,g=f.length,b=t-1;for(;g>0;){let e=f.map((e=>h[e])).reduce(((e,t)=>Math.min(e,t.numberOfPossibilities)),1/0),t=e-y;if(bh[e].numberOfPossibilities>y)),g=f.length}let v=a[p],N=enumerateCombinations({numberOfOptionsByIndex:v.map((e=>s[e])),maxNumber:d})[d-1].map((e=>e+1)),T=[],C=!1;for(let[e,t]of v.entries())if(s[t]>1){let r=c[t],a=n.allComponentClasses[r.componentType].getUniqueVariant({serializedComponent:r,variantIndex:N[e],componentInfoObjects:n});if(!a.success)return{success:!1};T.push(a.desiredVariant),C=!0}else T.push({});let A={indices:v.map((e=>e+1))};return C&&(A.subvariants=T),{success:!0,desiredVariant:A}}}let countOptions=function(e,t){if(0===t)return 0;if(1===t)return e.reduce(((e,t)=>e+t));let n=0;for(let r in e){let a=e[r],i=[...e];i.splice(r,1),n+=a*countOptions(i,t-1)}return n};class AnimateFromSequence extends BaseComponent{constructor(e){super(e),Object.assign(this.actions,{changedAnimationOn:this.changedAnimationOn.bind(this),advanceAnimation:this.advanceAnimation.bind(this),startAnimation:this.startAnimation.bind(this),stopAnimation:this.stopAnimation.bind(this),toggleAnimation:this.toggleAnimation.bind(this)})}static componentType="animateFromSequence";static rendererType=void 0;static acceptTarget=!0;static createAttributesObject(){let e=super.createAttributesObject(),t=returnStandardSequenceAttributes();return Object.assign(e,t),e.prop={createPrimitiveOfType:"string"},e.componentIndex={createComponentOfType:"integer",createStateVariable:"componentIndex",defaultValue:null,public:!0},e.propIndex={createComponentOfType:"numberList",createStateVariable:"propIndex",defaultValue:null,public:!0},e.animationOn={createComponentOfType:"boolean",createStateVariable:"animationOn",defaultValue:!1,public:!0,triggerActionOnChange:"changedAnimationOn"},e.animationMode={createComponentOfType:"text",createStateVariable:"animationMode",defaultValue:"increase",validValues:["increase","decrease","increase once","decrease once","oscillate"],toLowerCase:!0,public:!0},e.animationInterval={createComponentOfType:"number",createStateVariable:"animationInterval",defaultValue:1e3,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnStandardSequenceStateVariableDefinitions();return Object.assign(e,t),e.possibleValues={additionalStateVariablesDefined:["numberValues"],returnDependencies:()=>({type:{dependencyType:"stateVariable",variableName:"type"},length:{dependencyType:"stateVariable",variableName:"length"},from:{dependencyType:"stateVariable",variableName:"from"},step:{dependencyType:"stateVariable",variableName:"step"},exclude:{dependencyType:"stateVariable",variableName:"exclude"},lowercase:{dependencyType:"stateVariable",variableName:"lowercase"}}),definition({dependencyValues:e}){let t=returnSequenceValues(e);return{setValue:{possibleValues:t,numberValues:t.length}}}},e.selectedIndex={public:!0,shadowingInstructions:{createComponentOfType:"number"},defaultValue:1,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{selectedIndex:!0}}),inverseDefinition:async({desiredStateVariableValues:e,stateValues:t})=>({success:!0,instructions:[{setEssentialValue:"selectedIndex",value:me$3.math.mod(e.selectedIndex-1,await t.numberValues)+1}]})},e.value={public:!0,shadowingInstructions:{hasVariableComponentType:!0},returnDependencies:()=>({possibleValues:{dependencyType:"stateVariable",variableName:"possibleValues"},selectedIndex:{dependencyType:"stateVariable",variableName:"selectedIndex"},type:{dependencyType:"stateVariable",variableName:"type"}}),definition:({dependencyValues:e})=>({setValue:{value:e.possibleValues[e.selectedIndex-1]},setCreateComponentOfType:{value:e.type}}),async inverseDefinition({desiredStateVariableValues:e,dependencyValues:t,stateValues:n}){if("number"===t.type){let r=e.value;if(r instanceof me$3.class&&(r=r.evaluate_to_constant()),!Number.isFinite(r))return{success:!1};let a=-1,i=t.possibleValues.length-1;for(;a0?i=e:a=e}let s=i;return-1!==a&&Math.abs(r-t.possibleValues[a])({animationMode:{dependencyType:"stateVariable",variableName:"animationMode"}}),definition:({dependencyValues:e})=>({useEssentialOrDefaultValue:{currentAnimationDirection:{get defaultValue(){return"decrease"===e.animationMode.substring(0,8)?"decrease":"increase"}}}}),inverseDefinition({desiredStateVariableValues:e}){let t=e.currentAnimationDirection.toLowerCase();return["increase","decrease"].includes(t)||(t="increase"),{success:!0,instructions:[{setEssentialValue:"currentAnimationDirection",value:t}]}}},e.target={returnDependencies:()=>({target:{dependencyType:"doenetAttribute",attributeName:"target"}}),definition:({dependencyValues:e})=>({setValue:{target:e.target}})},e.targetComponent={returnDependencies:()=>({targetComponent:{dependencyType:"targetComponent"}}),definition:function({dependencyValues:e}){let t=null;return e.targetComponent&&(t=e.targetComponent),{setValue:{targetComponent:t}}}},e.propName={returnDependencies:()=>({propName:{dependencyType:"attributePrimitive",attributeName:"prop"}}),definition:function({dependencyValues:e}){return{setValue:{propName:e.propName}}}},e.targetIdentities={stateVariablesDeterminingDependencies:["targetComponent","componentIndex"],returnDependencies:function({stateValues:e,componentInfoObjects:t}){let n={};return null!==e.targetComponent&&(t.isCompositeComponent({componentType:e.targetComponent.componentType,includeNonStandard:!1})?n.targets={dependencyType:"replacement",compositeName:e.targetComponent.componentName,recursive:!0,componentIndex:e.componentIndex}:null!==e.componentIndex&&1!==e.componentIndex||(n.targets={dependencyType:"stateVariable",variableName:"targetComponent"})),n},definition({dependencyValues:e}){let t=null;return e.targets&&(t=e.targets,Array.isArray(t)||(t=[t])),{setValue:{targetIdentities:t}}}},e.targets={stateVariablesDeterminingDependencies:["targetIdentities","propName","propIndex"],returnDependencies:function({stateValues:e}){let t={targetIdentities:{dependencyType:"stateVariable",variableName:"targetIdentities"}};if(null!==e.targetIdentities)for(let[n,r]of e.targetIdentities.entries()){let a;if(e.propName){let t=e.propIndex;t&&(t=[...t]),a={dependencyType:"stateVariable",componentName:r.componentName,variableName:e.propName,returnAsComponentObject:!0,variablesOptional:!0,propIndex:t,caseInsensitiveVariableMatch:!0,publicStateVariablesOnly:!0,useMappedVariableNames:!0}}else a={dependencyType:"stateVariable",componentName:r.componentName,variableName:"value",returnAsComponentObject:!0,variablesOptional:!0};t["target"+n]=a}return t},definition({dependencyValues:e}){let t=null;if(null!==e.targetIdentities){t=[];for(let n in e.targetIdentities)e["target"+n]&&t.push(e["target"+n])}return{setValue:{targets:t}}}},e.valueToIndex={returnDependencies:()=>({possibleValues:{dependencyType:"stateVariable",variableName:"possibleValues"}}),definition:function({dependencyValues:e}){let t={};for(let[n,r]of e.possibleValues.entries())t[r]=n;return{setValue:{valueToIndex:t}}}},e}async changedAnimationOn({stateValues:e,previousValues:t,actionId:n}){let r=[];if(e.animationOn)if(t.animationOn)this.coreFunctions.resolveAction({actionId:n});else{let e=await this.stateValues.currentAnimationDirection,t=await this.stateValues.animationMode,a=await this.stateValues.numberValues,i=await this.stateValues.selectedIndex,s=await this.findIndexFromTarget();"increase"===e?s===a&&("increase once"===t?s=1:"oscillate"===t&&(e="decrease",r.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"currentAnimationDirection",value:e}))):"decrease"===e&&1===s&&("decrease once"===t?s=a:"oscillate"===t&&(e="increase",r.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"currentAnimationDirection",value:e}))),s!==i&&r.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"selectedIndex",value:s});let o=await this.getUpdateInstructionsToSetTargetsToValue((await this.stateValues.possibleValues)[me$3.math.mod(s-1,a)]);r.push(...o),await this.coreFunctions.performUpdate({updateInstructions:r,actionId:n,event:{verb:"played",object:{componentName:this.componentName,componentType:this.componentType},context:{startIndex:s,animationDirection:e,animationMode:t}}}),await this.coreFunctions.triggerChainedActions({componentName:this.componentName}),this.animationId=nanoid(),await this.coreFunctions.requestAnimationFrame({action:{actionName:"advanceAnimation",componentName:this.componentName},delay:await this.stateValues.animationInterval,animationId:this.animationId,actionArgs:{previousAnimationId:this.animationId}})}else t.animationOn?(await this.coreFunctions.cancelAnimationFrame(this.animationId),this.canceledAnimationId=this.animationId,await this.coreFunctions.triggerChainedActions({componentName:this.componentName}),this.coreFunctions.requestRecordEvent({verb:"paused",object:{componentName:this.componentName,componentType:this.componentType},context:{endIndex:await this.stateValues.selectedIndex}})):this.coreFunctions.resolveAction({actionId:n})}async findIndexFromTarget(){let e=await this.stateValues.targets,t=await this.stateValues.selectedIndex;if(null===e)return t;let n,r=e[0];if(r?.stateValues&&(n=Object.keys(r.stateValues)[0]),!n)return t;let a=r.stateValues[n],i=await this.stateValues.type;if("number"===i&&a instanceof me$3.class&&(a=a.evaluate_to_constant(),!Number.isFinite(a)))return t;let s=(await this.stateValues.valueToIndex)[a];if(void 0!==s)return s+1;if("number"!==i)return t;let o=await this.stateValues.possibleValues,l=function(e=0,t=o.length-1){if(t<=e+1)return a>o[e]?t:e;let n=Math.round((t+e)/2);return a>o[n]?l(n,t):l(e,n)},u=l();if(0!==u){let e=o[u-1],t=o[u];Math.abs(a-e)=await this.stateValues.numberValues&&("increase once"===s?i=!1:"oscillate"===s&&(a="decrease")));let l=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"selectedIndex",value:n}],u=await this.getUpdateInstructionsToSetTargetsToValue((await this.stateValues.possibleValues)[me$3.math.mod(n-1,await this.stateValues.numberValues)]);l.push(...u),i||l.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"animationOn",value:!1}),a&&l.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"currentAnimationDirection",value:a}),await this.coreFunctions.performUpdate({updateInstructions:l,actionId:t}),i&&(this.animationId=nanoid(),await this.coreFunctions.requestAnimationFrame({action:{actionName:"advanceAnimation",componentName:this.componentName},delay:await this.stateValues.animationInterval,animationId:this.animationId,actionArgs:{previousAnimationId:this.animationId}}))}startAnimation({actionId:e}){this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"animationOn",value:!0}],actionId:e})}stopAnimation({actionId:e}){this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"animationOn",value:!1}],actionId:e})}async toggleAnimation({actionId:e}){this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"animationOn",value:!await this.stateValues.animationOn}],actionId:e})}async getUpdateInstructionsToSetTargetsToValue(e){let t=await this.stateValues.targets;if(null==t)return[];let n=[];for(let r of t){let t=Object.keys(r.stateValues)[0];void 0!==t?n.push({updateType:"updateValue",componentName:r.componentName,stateVariable:t,value:e}):await this.stateValues.propName?console.warn(`Cannot animate prop="${await this.stateValues.propName}" of ${await this.stateValues.target} as could not find prop ${await this.stateValues.propName} on a component of type ${r.componentType}`):console.warn(`Cannot animate ${await this.stateValues.target} as could not find a value state variable on a component of type ${r.componentType}`)}return n}}class Evaluate extends MathComponent{static componentType="evaluate";static rendererType="math";static createAttributesObject(){let e=super.createAttributesObject();return e.forceSymbolic={createComponentOfType:"boolean",createStateVariable:"forceSymbolic",defaultValue:!1,public:!0},e.forceNumeric={createComponentOfType:"boolean",createStateVariable:"forceNumeric",defaultValue:!1,public:!0},e.function={createComponentOfType:"function"},e.input={createComponentOfType:"mathList"},e.unordered={createComponentOfType:"boolean",createStateVariable:"unordered",defaultValue:!1,public:!0},e}static returnChildGroups(){return[]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return delete e.codePre,delete e.expressionWithCodes,delete e.mathChildrenFunctionSymbols,delete e.codesAdjacentToStrings,delete e.mathChildrenByVectorComponent,delete e.mathChildrenWithCanBeModified,delete e.unordered,e.canBeModified={returnDependencies:()=>({}),definition:()=>({setValue:{canBeModified:!1}})},e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},defaultValue:10,hasEssential:!0,returnDependencies:()=>({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},functionAttr:{dependencyType:"attributeComponent",attributeName:"function",variableNames:["displayDigits"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.displayDigitsAttr){let n=t.displayDigitsAttr,r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!n&&!r){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},functionAttr:{dependencyType:"attributeComponent",attributeName:"function",variableNames:["displayDecimals"]}}),definition:({dependencyValues:e,usedDefault:t})=>null!==e.displayDecimalsAttr?{setValue:{displayDecimals:e.displayDecimalsAttr.stateValues.value}}:e.functionAttr?t.functionAttr?{useEssentialOrDefaultValue:{displayDecimals:{defaultValue:e.functionAttr.stateValues.displayDecimals}}}:{setValue:{displayDecimals:e.functionAttr.stateValues.displayDecimals}}:{useEssentialOrDefaultValue:{displayDecimals:!0}}},e.displaySmallAsZero={public:!0,shadowingInstructions:{createComponentOfType:"number"},defaultValue:0,hasEssential:!0,returnDependencies:()=>({displaySmallAsZeroAttr:{dependencyType:"attributeComponent",attributeName:"displaySmallAsZero",variableNames:["value"]},functionAttr:{dependencyType:"attributeComponent",attributeName:"function",variableNames:["displaySmallAsZero"]}}),definition:({dependencyValues:e,usedDefault:t})=>null!==e.displaySmallAsZeroAttr?{setValue:{displaySmallAsZero:e.displaySmallAsZeroAttr.stateValues.value}}:e.functionAttr?t.functionAttr?{useEssentialOrDefaultValue:{displaySmallAsZero:{defaultValue:e.functionAttr.stateValues.displaySmallAsZero}}}:{setValue:{displaySmallAsZero:e.functionAttr.stateValues.displaySmallAsZero}}:{useEssentialOrDefaultValue:{displaySmallAsZero:!0}}},e.padZeros={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},defaultValue:!1,hasEssential:!0,returnDependencies:()=>({padZerosAttr:{dependencyType:"attributeComponent",attributeName:"padZeros",variableNames:["value"]},functionAttr:{dependencyType:"attributeComponent",attributeName:"function",variableNames:["padZeros"]}}),definition:({dependencyValues:e,usedDefault:t})=>null!==e.padZerosAttr?{setValue:{padZeros:e.padZerosAttr.stateValues.value}}:e.functionAttr?t.functionAttr?{useEssentialOrDefaultValue:{padZeros:{defaultValue:e.functionAttr.stateValues.padZeros}}}:{setValue:{padZeros:e.functionAttr.stateValues.padZeros}}:{useEssentialOrDefaultValue:{padZeros:!0}}},e.unnormalizedValue={public:!0,shadowingInstructions:{createComponentOfType:"math"},returnDependencies:()=>({inputAttr:{dependencyType:"attributeComponent",attributeName:"input",variableNames:["nComponents","maths"]},functionAttr:{dependencyType:"attributeComponent",attributeName:"function",variableNames:["symbolicfs","numericalfs","symbolic","nInputs","nOutputs"]},forceSymbolic:{dependencyType:"stateVariable",variableName:"forceSymbolic"},forceNumeric:{dependencyType:"stateVariable",variableName:"forceNumeric"}}),definition({dependencyValues:e}){if(!e.functionAttr||!e.inputAttr)return{setValue:{unnormalizedValue:me$3.fromAst("_")}};let t=e.inputAttr.stateValues.maths;if(1===t.length){let e=t[0].tree;Array.isArray(e)&&vectorOperators.includes(e[0])&&(t=e.slice(1).map((e=>me$3.fromAst(e))))}if(t.length!==e.functionAttr.stateValues.nInputs)return{setValue:{unnormalizedValue:me$3.fromAst("_")}};let n,r=[],a=e.functionAttr,i=a.stateValues.nOutputs;if(e.forceNumeric||!a.stateValues.symbolic&&!e.forceSymbolic){let e=t.map((e=>e.evaluate_to_constant())).map((e=>null===e?NaN:e));for(let t=0;t=0&&Number.isFinite(r))){let e="Invalid mean ("+r+") or standard deviation ("+n+") for a gaussian random variable.";return console.warn(e),Array(t).fill(NaN)}let e=[];for(let a=0;a0)for(let n=0;n({type:{dependencyType:"stateVariable",variableName:"type"},specifiedStep:{dependencyType:"stateVariable",variableName:"specifiedStep"}}),definition({dependencyValues:e}){let t;return t="discreteuniform"===e.type?e.specifiedStep:null,{setValue:{step:t}}}},e.from={public:!0,shadowingInstructions:{createComponentOfType:"number"},additionalStateVariablesDefined:[{variableName:"to",public:!0,shadowingInstructions:{createComponentOfType:"number"}},{variableName:"nDiscreteValues"}],returnDependencies:()=>({type:{dependencyType:"stateVariable",variableName:"type"},specifiedFrom:{dependencyType:"stateVariable",variableName:"specifiedFrom"},specifiedTo:{dependencyType:"stateVariable",variableName:"specifiedTo"},step:{dependencyType:"stateVariable",variableName:"step"}}),definition({dependencyValues:e}){if(!["discreteuniform","uniform"].includes(e.type))return{setValue:{from:null,to:null,nDiscreteValues:null}};let t=e.step,n=e.specifiedFrom,r=e.specifiedTo,a=null;if(null===r)null===n&&(n=0),"uniform"===e.type?r=n+1:(r=n+t,a=2);else if(null===n)if("uniform"===e.type)n=0;else{let e=0;a=Math.floor((r-e)/t+1),a<1?(a=0,n=null):n=r-(a-1)*t}else"discreteuniform"===e.type&&(a=Math.floor((r-n)/t+1),a<1?a=0:r=n+(a-1)*t);return{setValue:{from:n,to:r,nDiscreteValues:a}}}},e.mean={stateVariablesDeterminingDependencies:["type"],public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies({stateValues:e}){let t={type:{dependencyType:"stateVariable",variableName:"type"}};return"gaussian"===e.type?t.specifiedMean={dependencyType:"stateVariable",variableName:"specifiedMean"}:(t.from={dependencyType:"stateVariable",variableName:"from"},t.to={dependencyType:"stateVariable",variableName:"to"}),t},definition({dependencyValues:e}){let t;return t="gaussian"===e.type?e.specifiedMean:(e.from+e.to)/2,{setValue:{mean:t}}}},e.variance={stateVariablesDeterminingDependencies:["type"],public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies({stateValues:e}){let t={type:{dependencyType:"stateVariable",variableName:"type"}};return"gaussian"===e.type?(t.specifiedVariance={dependencyType:"stateVariable",variableName:"specifiedVariance"},t.specifiedStandardDeviation={dependencyType:"stateVariable",variableName:"specifiedStandardDeviation"}):(t.from={dependencyType:"stateVariable",variableName:"from"},t.to={dependencyType:"stateVariable",variableName:"to"},"discreteuniform"===e.type&&(t.step={dependencyType:"stateVariable",variableName:"step"},t.nDiscreteValues={dependencyType:"stateVariable",variableName:"nDiscreteValues"})),t},definition({dependencyValues:e,usedDefault:t}){let n;return n="gaussian"===e.type?t.specifiedVariance&&!t.specifiedStandardDeviation?e.specifiedStandardDeviation**2:e.specifiedVariance:"discreteuniform"===e.type?(e.nDiscreteValues**2-1)*e.step**2/12:(e.to-e.from)**2/12,{setValue:{variance:n}}}},e.standardDeviation={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({variance:{dependencyType:"stateVariable",variableName:"variance"}}),definition:({dependencyValues:e})=>({setValue:{standardDeviation:Math.sqrt(e.variance)}})},e.sampledValues={shadowVariable:!0,hasEssential:!0,stateVariablesDeterminingDependencies:["variantDeterminesSeed"],returnDependencies({stateValues:e,sharedParameters:t}){let n={numberOfSamples:{dependencyType:"stateVariable",variableName:"numberOfSamples"},type:{dependencyType:"stateVariable",variableName:"type"},from:{dependencyType:"stateVariable",variableName:"from"},to:{dependencyType:"stateVariable",variableName:"to"},step:{dependencyType:"stateVariable",variableName:"step"},nDiscreteValues:{dependencyType:"stateVariable",variableName:"nDiscreteValues"},mean:{dependencyType:"stateVariable",variableName:"mean"},standardDeviation:{dependencyType:"stateVariable",variableName:"standardDeviation"}};return e.variantDeterminesSeed?n.rng={dependencyType:"value",value:t.variantRng,doNotProxy:!0}:n.rng={dependencyType:"value",value:t.rngWithDateSeed,doNotProxy:!0},n},definition({dependencyValues:e}){if(e.numberOfSamples<1)return{setEssentialValue:{sampledValues:[]},setValue:{sampledValues:[]}};let t=sampleFromRandomNumbers(e);return{setEssentialValue:{sampledValues:t},setValue:{sampledValues:t}}},inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"sampledValues",value:e.sampledValues}]})},e.readyToExpandWhenResolved={returnDependencies:()=>({sampledValues:{dependencyType:"stateVariable",variableName:"sampledValues"}}),markStale:()=>({updateReplacements:!0}),definition:function(){return{setValue:{readyToExpandWhenResolved:!0}}}},e.isVariantComponent={returnDependencies:()=>({}),definition:()=>({setValue:{isVariantComponent:!0}})},e.generatedVariantInfo={returnDependencies:({sharedParameters:e})=>({variantSeed:{dependencyType:"value",value:e.variantSeed}}),definition:({dependencyValues:e,componentName:t})=>({setValue:{generatedVariantInfo:{seed:e.variantSeed,meta:{createdBy:t}}}})},e}static async createSerializedReplacements({component:e,componentInfoObjects:t,startNum:n=0,flags:r}){let a=e.attributes.newNamespace?.primitive,i={};for(let t of["displayDigits","displaySmallAsZero","displayDecimals","padZeros"])t in e.attributes&&(i[t]=e.attributes[t]);let s=[];for(let o of(await e.stateValues.sampledValues).slice(n)){let e={};Object.keys(i).length>0&&(e=convertAttributesForComponentType({attributes:i,componentType:"number",componentInfoObjects:t,compositeCreatesNewNamespace:a,flags:r})),s.push({componentType:"number",attributes:e,state:{value:o}})}return{replacements:processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:s,parentName:e.componentName,parentCreatesNewNamespace:a,indOffset:n,componentInfoObjects:t}).serializedComponents}}static async calculateReplacementChanges({component:e,componentInfoObjects:t,flags:n}){let r=[],a=await e.stateValues.sampledValues;if(a.length0){let e={changeType:"changeReplacementsToWithhold",replacementsToWithhold:0};r.push(e)}if(a.length>e.replacements.length){let a=await this.createSerializedReplacements({component:e,componentInfoObjects:t,startNum:e.replacements.length,flags:n}),i={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:e.replacements.length,numberReplacementsToReplace:0,serializedReplacements:a.replacements,assignNamesOffset:e.replacements.length};r.push(i)}}let i=Math.min(e.replacements.length,a.length);for(let t=0;t({variants:{dependencyType:"variants"}}),definition:function({dependencyValues:e}){return{setValue:{variants:e.variants}}}},e.step.immutable=!0,e.from.immutable=!0,e.from.additionalStateVariablesDefined[0].immutable=!0,e.from.additionalStateVariablesDefined[1].immutable=!0,e.mean.immutable=!0,e.variance.immutable=!0,e.standardDeviation.immutable=!0,delete e.sampledValues,e.selectedValues={immutable:!0,hasEssential:!0,shadowVariable:!0,returnDependencies:({sharedParameters:e})=>({numberOfSamples:{dependencyType:"stateVariable",variableName:"numberToSelect"},type:{dependencyType:"stateVariable",variableName:"type"},from:{dependencyType:"stateVariable",variableName:"from"},to:{dependencyType:"stateVariable",variableName:"to"},step:{dependencyType:"stateVariable",variableName:"step"},nDiscreteValues:{dependencyType:"stateVariable",variableName:"nDiscreteValues"},mean:{dependencyType:"stateVariable",variableName:"mean"},standardDeviation:{dependencyType:"stateVariable",variableName:"standardDeviation"},variants:{dependencyType:"stateVariable",variableName:"variants"},rng:{dependencyType:"value",value:e.variantRng,doNotProxy:!0}}),definition({dependencyValues:e}){if(e.numberOfSamples<1)return{setEssentialValue:{selectedValues:[]},setValue:{selectedValues:[]}};if(e.variants&&e.variants.desiredVariant){let t=e.variants.desiredVariant.values;if(t){if(t.length!==e.numberOfSamples)throw Error("Number of values specified for selectRandomNumber must match number to select");return{setEssentialValue:{selectedValues:t},setValue:{selectedValues:t}}}}let t=sampleFromRandomNumbers(e);return{setEssentialValue:{selectedValues:t},setValue:{selectedValues:t}}}},e.isVariantComponent={returnDependencies:()=>({}),definition:()=>({setValue:{isVariantComponent:!0}})},e.generatedVariantInfo={returnDependencies:()=>({selectedValues:{dependencyType:"stateVariable",variableName:"selectedValues"}}),definition:({dependencyValues:e,componentName:t})=>({setValue:{generatedVariantInfo:{values:e.selectedValues,meta:{createdBy:t}}}})},e.readyToExpandWhenResolved={returnDependencies:()=>({selectedValues:{dependencyType:"stateVariable",variableName:"selectedValues"}}),definition:function(){return{setValue:{readyToExpandWhenResolved:!0}}}},e}static async createSerializedReplacements({component:e,componentInfoObjects:t,flags:n}){let r=e.attributes.newNamespace?.primitive,a={};for(let t of["displayDigits","displaySmallAsZero","displayDecimals","padZeros"])t in e.attributes&&(a[t]=e.attributes[t]);let i=[];for(let s of await e.stateValues.selectedValues){let e={};Object.keys(a).length>0&&(e=convertAttributesForComponentType({attributes:a,componentType:"number",componentInfoObjects:t,compositeCreatesNewNamespace:r,flags:n})),i.push({componentType:"number",attributes:e,state:{value:s}})}return{replacements:processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:i,parentName:e.componentName,parentCreatesNewNamespace:r,componentInfoObjects:t}).serializedComponents}}}delete SelectRandomNumbers.stateVariableToEvaluateAfterReplacements,delete SelectRandomNumbers.calculateReplacementChanges;class Substitute extends CompositeComponent{static componentType="substitute";static assignNamesToReplacements=!0;static stateVariableToEvaluateAfterReplacements="readyToExpandWhenResolved";static createAttributesObject(){let e=super.createAttributesObject();return e.assignNamesSkip={createPrimitiveOfType:"number"},e.type={createPrimitiveOfType:"string",createStateVariable:"type",defaultPrimitiveValue:"math",toLowerCase:!0,validValues:["math","text"],public:!0},e.match={createComponentOfType:"_componentWithSelectableType",createStateVariable:"match",defaultValue:null},e.replacement={createComponentOfType:"_componentWithSelectableType",createStateVariable:"replacement",defaultValue:null},e.simplify={createComponentOfType:"text",createStateVariable:"simplify",defaultValue:"none",public:!0,toLowerCase:!0,valueTransformations:{true:"full"},validValues:["none","full","numbers","numberspreserveorder"]},e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer"},e.displaySmallAsZero={createComponentOfType:"number",valueForTrue:1e-14,valueForFalse:0},e.padZeros={createComponentOfType:"boolean"},e.matchWholeWord={createComponentOfType:"boolean",createStateVariable:"matchWholeWord",defaultValue:!1,public:!0},e.matchCase={createComponentOfType:"boolean",createStateVariable:"matchCase",defaultValue:!1,public:!0},e.preserveCase={createComponentOfType:"boolean",createStateVariable:"preserveCase",defaultValue:!1,public:!0},e}static returnSugarInstructions(){let e=[];return e.push({replacementFunction:function({matchedChildren:e,componentAttributes:t}){let n=t.type;return["math","text"].includes(n)||(n="math"),{success:!0,newChildren:[{componentType:n,children:e}]}}}),e}static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({type:{dependencyType:"stateVariable",variableName:"type"},displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},child:{dependencyType:"child",childGroups:["anything"],variableNames:["displayDigits"],variablesOptional:!0}}),definition({dependencyValues:e,usedDefault:t}){if("math"!==e.type)return{setValue:{displayDigits:null}};if(null!==e.displayDigitsAttr){let n=t.displayDigitsAttr,r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!n&&!r){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({type:{dependencyType:"stateVariable",variableName:"type"},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},child:{dependencyType:"child",childGroups:["anything"],variableNames:["displayDecimals"],variablesOptional:!0}}),definition:({dependencyValues:e,usedDefault:t})=>"math"!==e.type?{setValue:{displayDecimals:null}}:null===e.displayDecimalsAttr||t.displayDecimalsAttr?1!==e.child.length||t.child[0]&&t.child[0].displayDecimals?{useEssentialOrDefaultValue:{displayDecimals:!0}}:{setValue:{displayDecimals:e.child[0].stateValues.displayDecimals}}:{setValue:{displayDecimals:e.displayDecimalsAttr.stateValues.value}}},e.displaySmallAsZero={public:!0,shadowingInstructions:{createComponentOfType:"number"},hasEssential:!0,defaultValue:0,returnDependencies:()=>({type:{dependencyType:"stateVariable",variableName:"type"},displaySmallAsZeroAttr:{dependencyType:"attributeComponent",attributeName:"displaySmallAsZero",variableNames:["value"]},child:{dependencyType:"child",childGroups:["anything"],variableNames:["displaySmallAsZero"],variablesOptional:!0}}),definition:({dependencyValues:e,usedDefault:t})=>"math"!==e.type?{setValue:{displaySmallAsZero:null}}:null===e.displaySmallAsZeroAttr||t.displaySmallAsZeroAttr?1!==e.child.length||t.child[0]&&t.child[0].displaySmallAsZero?{useEssentialOrDefaultValue:{displaySmallAsZero:!0}}:{setValue:{displaySmallAsZero:e.child[0].stateValues.displaySmallAsZero}}:{setValue:{displaySmallAsZero:e.displaySmallAsZeroAttr.stateValues.value}}},e.padZeros={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},hasEssential:!0,defaultValue:!1,returnDependencies:()=>({type:{dependencyType:"stateVariable",variableName:"type"},padZerosAttr:{dependencyType:"attributeComponent",attributeName:"padZeros",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},child:{dependencyType:"child",childGroups:["anything"],variableNames:["padZeros"],variablesOptional:!0}}),definition:({dependencyValues:e,usedDefault:t})=>"math"!==e.type?{setValue:{padZeros:null}}:null===e.padZerosAttr||t.padZerosAttr?1!==e.child.length||t.child[0]&&t.child[0].padZeros?{useEssentialOrDefaultValue:{padZeros:!0}}:{setValue:{padZeros:e.child[0].stateValues.padZeros}}:{setValue:{padZeros:e.padZerosAttr.stateValues.value}}},e.originalValue={returnDependencies:()=>({child:{dependencyType:"child",childGroups:["anything"],variableNames:["value"]}}),definition:({dependencyValues:e})=>e.child.length>0?{setValue:{originalValue:e.child[0].stateValues.value}}:{setValue:{originalValue:null}},inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t})=>t.child.length>0?{success:!0,instructions:[{setDependency:"child",desiredValue:e.originalValue,childIndex:0,variableIndex:0}]}:{success:!1}},e.value={returnDependencies:()=>({type:{dependencyType:"stateVariable",variableName:"type"},originalValue:{dependencyType:"stateVariable",variableName:"originalValue"},match:{dependencyType:"stateVariable",variableName:"match"},replacement:{dependencyType:"stateVariable",variableName:"replacement"},simplify:{dependencyType:"stateVariable",variableName:"simplify"},matchWholeWord:{dependencyType:"stateVariable",variableName:"matchWholeWord"},matchCase:{dependencyType:"stateVariable",variableName:"matchCase"},preserveCase:{dependencyType:"stateVariable",variableName:"preserveCase"}}),definition({dependencyValues:e}){if(null===e.originalValue)return{setValue:{value:null}};if(null===e.match||null===e.replacement)return{setValue:{value:e.originalValue}};if("text"===e.type){let t,n=e.originalValue,r="g";e.matchCase||(r="gi"),t=e.matchWholeWord?new RegExp("\\b"+escapeRegExp(e.match)+"\\b",r):new RegExp(escapeRegExp(e.match),r);let a=e.replacement;if(e.preserveCase){let e=returnPreserveCaseReplacer(a);n=n.replace(t,e)}else n=n.replace(t,a);return{setValue:{value:n}}}{let t=e.originalValue.subscripts_to_strings();return t=t.substitute({[e.match.subscripts_to_strings().tree]:e.replacement.subscripts_to_strings()}),t=t.strings_to_subscripts(),t=normalizeMathExpression({value:t,simplify:e.simplify}),{setValue:{value:t}}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){if("text"===t.type){let n,r,a=e.value,i="g";t.matchCase||(i="gi");let s=t.match,o=t.replacement;if(t.matchWholeWord)if(n=new RegExp("\\b"+escapeRegExp(s)+"\\b",i),t.matchCase&&t.preserveCase){let e=returnPreserveCaseReplacer(o);r=new RegExp("\\b"+escapeRegExp(e(s))+"\\b",i)}else r=new RegExp("\\b"+escapeRegExp(o)+"\\b",i);else if(n=new RegExp(escapeRegExp(s),i),t.matchCase&&t.preserveCase){let e=returnPreserveCaseReplacer(o);r=new RegExp(escapeRegExp(e(s)),i)}else r=new RegExp(escapeRegExp(o),i);return-1!==t.originalValue.search(r)||-1!==a.search(n)?{success:!1}:(a=a.replace(r,s),{success:!0,instructions:[{setDependency:"originalValue",desiredValue:a}]})}{let n=e.value.subscripts_to_strings(),r=t.match.subscripts_to_strings(),a=t.replacement.subscripts_to_strings();return"string"!=typeof r.tree||"string"!=typeof a.tree||(t.originalValue.variables(!0).includes(a.tree)||n.variables().includes(r.tree))?{success:!1}:(n=n.substitute({[a.tree]:r}),n=n.strings_to_subscripts(),{success:!0,instructions:[{setDependency:"originalValue",desiredValue:n}]})}}},e.readyToExpandWhenResolved={returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),markStale:()=>({updateReplacements:!0}),definition:function(){return{setValue:{readyToExpandWhenResolved:!0}}}},e}static async createSerializedReplacements({component:e,componentInfoObjects:t,flags:n}){let r=e.attributes.newNamespace?.primitive,a=await e.stateValues.type,i={componentType:a,state:{value:await e.stateValues.value},downstreamDependencies:{[e.componentName]:[{dependencyType:"referenceShadow",compositeName:e.componentName,propVariable:"value"}]}};if("math"===a){let t={},n={displayDigits:"integer",displayDecimals:"integer",displaySmallAsZero:"number",padZeros:"boolean"};for(let r in n){let a={componentType:n[r],downstreamDependencies:{[e.componentName]:[{compositeName:e.componentName,dependencyType:"referenceShadow",propVariable:r}]}};t[r]={component:a}}i.attributes=t}return{replacements:processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:[i],parentName:e.componentName,parentCreatesNewNamespace:r,componentInfoObjects:t}).serializedComponents}}}function escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function returnPreserveCaseReplacer(e){return function(t){return t.toUpperCase()===t?e.toUpperCase():t.toLowerCase()===t?e.toLowerCase():t[0].match(/[a-z]/)?e[0].toLowerCase()+e.substring(1):t[0].match(/[A-Z]/)?e[0].toUpperCase()+e.substring(1):e}}class PeriodicSet extends MathComponent{static componentType="periodicSet";static rendererType=void 0;static createAttributesObject(){let e=super.createAttributesObject();return e.minIndex={createComponentOfType:"integer",createStateVariable:"minIndex",defaultValue:-1/0,public:!0},e.maxIndex={createComponentOfType:"integer",createStateVariable:"maxIndex",defaultValue:1/0,public:!0},e.offsets={createComponentOfType:"mathList",createStateVariable:"offsets",defaultValue:null,public:!0},e.period={createComponentOfType:"math",createStateVariable:"period",defaultValue:null,public:!0},e.minIndexAsList={createComponentOfType:"integer",createStateVariable:"minIndexAsList",defaultValue:-1,public:!0},e.maxIndexAsList={createComponentOfType:"integer",createStateVariable:"maxIndexAsList",defaultValue:1,public:!0},e}static returnChildGroups(){return[]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return delete e.codePre,delete e.expressionWithCodes,delete e.mathChildrenFunctionSymbols,delete e.codesAdjacentToStrings,delete e.mathChildrenByVectorComponent,delete e.mathChildrenWithCanBeModified,delete e.unordered,e.canBeModified={returnDependencies:()=>({}),definition:()=>({setValue:{canBeModified:!1}})},e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({mathListParentDisplayDigits:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"displayDigits"},numberListParentDisplayDigits:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"displayDigits"},mathListParentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"displayDecimals"},numberListParentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"displayDecimals"},displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){let n,r=!1;if(null!==e.mathListParentDisplayDigits){if(!t.mathListParentDisplayDigits)return{setValue:{displayDigits:e.mathListParentDisplayDigits}};r=!0,n=e.mathListParentDisplayDigits}if(null!==e.numberListParentDisplayDigits){if(!t.numberListParentDisplayDigits)return{setValue:{displayDigits:e.numberListParentDisplayDigits}};r=!0,n=e.numberListParentDisplayDigits}if(!(null!==e.numberListParentDisplayDecimals&&!t.numberListParentDisplayDecimals||null!==e.mathListParentDisplayDecimals&&!t.mathListParentDisplayDecimals)&&null!==e.displayDigitsAttr){if(!t.displayDigitsAttr)return{setValue:{displayDigits:e.displayDigitsAttr.stateValues.value}};r=!0,n=e.displayDigitsAttr.stateValues.value}return r?{useEssentialOrDefaultValue:{displayDigits:{defaultValue:n}}}:{useEssentialOrDefaultValue:{displayDigits:!0}}}},e.displayDecimals={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:null,returnDependencies:()=>({mathListParentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"displayDecimals"},numberListParentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"displayDecimals"},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){let n,r=!1;if(null!==e.mathListParentDisplayDecimals){if(!t.mathListParentDisplayDecimals)return{setValue:{displayDecimals:e.mathListParentDisplayDecimals}};r=!0,n=e.mathListParentDisplayDecimals}if(null!==e.numberListParentDisplayDecimals){if(!t.numberListParentDisplayDecimals)return{setValue:{displayDecimals:e.numberListParentDisplayDecimals}};r=!0,n=e.numberListParentDisplayDecimals}if(null!==e.displayDecimalsAttr){if(!t.displayDecimalsAttr)return{setValue:{displayDecimals:e.displayDecimalsAttr.stateValues.value}};r=!0,n=e.displayDecimalsAttr.stateValues.value}return r?{useEssentialOrDefaultValue:{displayDecimals:{defaultValue:n}}}:{useEssentialOrDefaultValue:{displayDecimals:!0}}}},e.displaySmallAsZero={public:!0,shadowingInstructions:{createComponentOfType:"number"},hasEssential:!0,defaultValue:0,returnDependencies:()=>({mathListParentDisplaySmallAsZero:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"displaySmallAsZero"},numberListParentDisplaySmallAsZero:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"displaySmallAsZero"},displaySmallAsZeroAttr:{dependencyType:"attributeComponent",attributeName:"displaySmallAsZero",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){let n,r=!1;if(null!==e.mathListParentDisplaySmallAsZero){if(!t.mathListParentDisplaySmallAsZero)return{setValue:{displaySmallAsZero:e.mathListParentDisplaySmallAsZero}};r=!0,n=e.mathListParentDisplaySmallAsZero}if(null!==e.numberListParentDisplaySmallAsZero){if(!t.numberListParentDisplaySmallAsZero)return{setValue:{displaySmallAsZero:e.numberListParentDisplaySmallAsZero}};r=!0,n=e.numberListParentDisplaySmallAsZero}if(null!==e.displaySmallAsZeroAttr){if(!t.displaySmallAsZeroAttr)return{setValue:{displaySmallAsZero:e.displaySmallAsZeroAttr.stateValues.value}};r=!0,n=e.displaySmallAsZeroAttr.stateValues.value}return r?{useEssentialOrDefaultValue:{displaySmallAsZero:{defaultValue:n}}}:{useEssentialOrDefaultValue:{displaySmallAsZero:!0}}}},e.padZeros={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},hasEssential:!0,defaultValue:!1,returnDependencies:()=>({mathListParentPadZeros:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"padZeros"},numberListParentPadZeros:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"padZeros"},padZerosAttr:{dependencyType:"attributeComponent",attributeName:"padZeros",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){let n,r=!1;if(null!==e.mathListParentPadZeros){if(!t.mathListParentPadZeros)return{setValue:{padZeros:e.mathListParentPadZeros}};r=!0,n=e.mathListParentPadZeros}if(null!==e.numberListParentPadZeros){if(!t.numberListParentPadZeros)return{setValue:{padZeros:e.numberListParentPadZeros}};r=!0,n=e.numberListParentPadZeros}if(null!==e.padZerosAttr){if(!t.padZerosAttr)return{setValue:{padZeros:e.padZerosAttr.stateValues.value}};r=!0,n=e.padZerosAttr.stateValues.value}return r?{useEssentialOrDefaultValue:{padZeros:{defaultValue:n}}}:{useEssentialOrDefaultValue:{padZeros:!0}}}},e.nOffsets={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({offsets:{dependencyType:"stateVariable",variableName:"offsets"}}),definition({dependencyValues:e}){let t=0;return null!==e.offsets&&(t=e.offsets.length),{setValue:{nOffsets:t}}}},e.unnormalizedValue={returnDependencies:()=>({offsets:{dependencyType:"stateVariable",variableName:"offsets"},period:{dependencyType:"stateVariable",variableName:"period"},minIndex:{dependencyType:"stateVariable",variableName:"minIndex"},maxIndex:{dependencyType:"stateVariable",variableName:"maxIndex"}}),definition({dependencyValues:e}){if(null===e.offsets||0===e.offsets.length||1===e.offsets.length&&"_"===e.offsets[0].tree||null===e.period||"_"===e.period.tree)return{setValue:{unnormalizedValue:me$3.fromAst("_")}};let t=[],n=e.period.tree,r=e.minIndex,a=e.maxIndex;for(let i of e.offsets)t.push(["tuple",i.tree,n,r,a]);return{setValue:{unnormalizedValue:me$3.fromAst(["periodic_set",...t])}}}},e.redundantOffsets={additionalStateVariablesDefined:["uniqueOffsets"],public:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({nOffsets:{dependencyType:"stateVariable",variableName:"nOffsets"},offsets:{dependencyType:"stateVariable",variableName:"offsets"},period:{dependencyType:"stateVariable",variableName:"period"}}),definition({dependencyValues:e}){let t=!1,n=[];if(null!==e.period){let r=e.period.evaluate_to_constant();if(null!==r)for(let a=0;a({uniqueOffsets:{dependencyType:"stateVariable",variableName:"uniqueOffsets"},period:{dependencyType:"stateVariable",variableName:"period"},minIndexAsList:{dependencyType:"stateVariable",variableName:"minIndexAsList"},maxIndexAsList:{dependencyType:"stateVariable",variableName:"maxIndexAsList"}}),definition({dependencyValues:e}){let t=[];if(null!==e.period){let n=e.period.evaluate_to_constant();if(null!==n){let r=e.period.simplify(),a=!0,i=[];for(let t of e.uniqueOffsets){let e=t.evaluate_to_constant();if(null===e){a=!1;break}{let a=t.subtract(r.multiply(Math.floor(e/n))).simplify(),s=a.evaluate_to_constant();i.push({num:s,offset:a})}}if(a){t.push(me$3.fromAst(["ldots"])),i.sort(((e,t)=>e.num-t.num));let n=-1,a=1;Number.isFinite(e.minIndexAsList)&&(n=e.minIndexAsList),Number.isFinite(e.maxIndexAsList)&&(a=e.maxIndexAsList);for(let e=n;e<=a;e++)for(let n of i)t.push(n.offset.add(r.multiply(e)).simplify());t.push(me$3.fromAst(["ldots"]))}}}return{setValue:{asList:t}}}},e}}class Image extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{moveImage:this.moveImage.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="image";static createAttributesObject(){let e=super.createAttributesObject();return e.width={createComponentOfType:"_componentSize",createStateVariable:"specifiedWidth",defaultValue:null},e.size={createComponentOfType:"text",createStateVariable:"specifiedSize",defaultValue:"medium",toLowerCase:!0,validValues:sizePossibilities},e.aspectRatio={createComponentOfType:"number"},e.height={createComponentOfType:"_componentSize"},e.displayMode={createComponentOfType:"text",createStateVariable:"displayMode",validValues:["block","inline"],defaultValue:"block",forRenderer:!0,public:!0},e.horizontalAlign={createComponentOfType:"text",createStateVariable:"horizontalAlign",toLowerCase:!0,validValues:["center","left","right"],defaultValue:"center",forRenderer:!0,public:!0},e.description={createComponentOfType:"text",createStateVariable:"description",defaultValue:"",public:!0,forRenderer:!0},e.source={createComponentOfType:"text",createStateVariable:"source",defaultValue:"",public:!0,forRenderer:!0},e.asFileName={createComponentOfType:"text",createStateVariable:"asFileName",defaultValue:null,public:!0,forRenderer:!0},e.mimeType={createComponentOfType:"text",createStateVariable:"mimeType",defaultValue:null,public:!0,forRenderer:!0},e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.layer={createComponentOfType:"number",createStateVariable:"layer",defaultValue:0,public:!0,forRenderer:!0},e.anchor={createComponentOfType:"point"},e.positionFromAnchor={createComponentOfType:"text",createStateVariable:"positionFromAnchor",defaultValue:"center",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft","top","bottom","left","right","center"]},e.rotate={createComponentOfType:"number",createStateVariable:"rotate",defaultValue:0,public:!0,forRenderer:!0},e.styleNumber.defaultValue=0,e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnSelectedStyleStateVariableDefinition();return Object.assign(e,t),e.size={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({specifiedSize:{dependencyType:"stateVariable",variableName:"specifiedSize"},specifiedWidth:{dependencyType:"stateVariable",variableName:"specifiedWidth"},graphAncestor:{dependencyType:"ancestor",componentType:"graph",variableNames:["xscale"]}}),definition({dependencyValues:e,usedDefault:t}){const n="medium";if(t.specifiedSize){if(t.specifiedWidth)return{setValue:{size:n}};{let t=e.specifiedWidth;if(null===t)return{setValue:{size:n}};let r,{isAbsolute:a,size:i}=t;if(a){let t;if(e.graphAncestor){let n=e.graphAncestor.stateValues.xscale;t=orderedPercentWidthMidpoints.map((e=>e/100*n))}else t=orderedWidthMidpoints;for(let[e,n]of t.entries())if(i<=n){r=sizePossibilities[e];break}r||(r=n)}else{for(let[e,t]of orderedPercentWidthMidpoints.entries())if(i<=t){r=sizePossibilities[e];break}r||(r=n)}return{setValue:{size:r}}}}return{setValue:{size:e.specifiedSize}}},inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setDependency:"specifiedSize",desiredValue:e.size}]})},e.width={public:!0,forRenderer:!0,shadowingInstructions:{createComponentOfType:"_componentSize"},returnDependencies:()=>({specifiedSize:{dependencyType:"stateVariable",variableName:"specifiedSize"},size:{dependencyType:"stateVariable",variableName:"size"},specifiedWidth:{dependencyType:"stateVariable",variableName:"specifiedWidth"},graphAncestor:{dependencyType:"ancestor",componentType:"graph",variableNames:["xscale"]}}),definition({dependencyValues:e,usedDefault:t}){if(e.graphAncestor){if(e.graphAncestor.stateValues.xscale,t.specifiedSize){if(t.specifiedWidth)return{setValue:{width:{isAbsolute:!1,size:percentWidthsBySize.medium}}};{let t,n=e.specifiedWidth;return t=n||{isAbsolute:!1,size:percentWidthsBySize.medium},{setValue:{width:t}}}}return{setValue:{width:{isAbsolute:!1,size:percentWidthsBySize[e.size]}}}}return{setValue:{width:{isAbsolute:!0,size:widthsBySize[e.size]}}}},inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setDependency:"specifiedWidth",desiredValue:e.width}]})},e.widthForGraph={forRenderer:!0,returnDependencies:()=>({width:{dependencyType:"stateVariable",variableName:"width"},graphAncestor:{dependencyType:"ancestor",componentType:"graph",variableNames:["xscale"]}}),definition({dependencyValues:e}){let t=e.width;return e.graphAncestor&&!t.isAbsolute&&(t={isAbsolute:!0,size:t.size/100*e.graphAncestor.stateValues.xscale}),{setValue:{widthForGraph:t}}}},e.aspectRatio={public:!0,forRenderer:!0,hasEssential:!0,defaultValue:null,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({aspectRatioAttr:{dependencyType:"attributeComponent",attributeName:"aspectRatio",variableNames:["value"]}}),definition({dependencyValues:e}){if(null!==e.aspectRatioAttr){let t=e.aspectRatioAttr.stateValues.value;return Number.isFinite(t)||(t=null),{setValue:{aspectRatio:t}}}return{useEssentialOrDefaultValue:{aspectRatio:!0}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){if(null!==t.aspectRatioAttr)return{success:!0,instructions:[{setDependency:"aspectRatioAttr",desiredValue:e.aspectRatio,variableIndex:0}]};{let t=e.aspectRatio;return t>0||(t=null),{success:!0,instructions:[{setEssentialValue:"aspectRatio",value:t}]}}}},e.cid={forRenderer:!0,returnDependencies:()=>({source:{dependencyType:"stateVariable",variableName:"source"}}),definition:function({dependencyValues:e}){if(!e.source||"doenet:"!==e.source.substring(0,7).toLowerCase())return{setValue:{cid:null}};let t=null,n=e.source.match(/[:&]cid=([^&]+)/i);return n&&(t=n[1]),{setValue:{cid:t}}}},e.anchor={defaultValue:me$3.fromText("(0,0)"),public:!0,forRenderer:!0,hasEssential:!0,shadowingInstructions:{createComponentOfType:"point"},returnDependencies:()=>({anchorAttr:{dependencyType:"attributeComponent",attributeName:"anchor",variableNames:["coords"]}}),definition:({dependencyValues:e})=>e.anchorAttr?{setValue:{anchor:e.anchorAttr.stateValues.coords}}:{useEssentialOrDefaultValue:{anchor:!0}},inverseDefinition:async({desiredStateVariableValues:e,dependencyValues:t,stateValues:n,initialChange:r})=>r&&!await n.draggable?{success:!1}:t.anchorAttr?{success:!0,instructions:[{setDependency:"anchorAttr",desiredValue:e.anchor,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"anchor",value:e.anchor}]}},e}async moveImage({x:e,y:t,z:n,transient:r,actionId:a}){let i=["vector"];return void 0!==e&&(i[1]=e),void 0!==t&&(i[2]=t),void 0!==n&&(i[3]=n),r?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],transient:r,actionId:a}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],actionId:a,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{x:e,y:t,z:n}}})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class Video extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{recordVideoStarted:this.recordVideoStarted.bind(this),recordVideoWatched:this.recordVideoWatched.bind(this),recordVideoPaused:this.recordVideoPaused.bind(this),recordVideoSkipped:this.recordVideoSkipped.bind(this),recordVideoCompleted:this.recordVideoCompleted.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this),recordVideoReady:this.recordVideoReady.bind(this),playVideo:this.playVideo.bind(this),pauseVideo:this.pauseVideo.bind(this),setTime:this.setTime.bind(this)})}static componentType="video";static createAttributesObject(){let e=super.createAttributesObject();return e.width={createComponentOfType:"_componentSize"},e.size={createComponentOfType:"text"},e.aspectRatio={createComponentOfType:"number"},e.height={createComponentOfType:"_componentSize"},e.displayMode={createComponentOfType:"text",createStateVariable:"displayMode",validValues:["block","inline"],defaultValue:"block",forRenderer:!0,public:!0},e.horizontalAlign={createComponentOfType:"text",createStateVariable:"horizontalAlign",validValues:["center","left","right"],defaultValue:"center",forRenderer:!0,public:!0},e.youtube={createComponentOfType:"text",createStateVariable:"youtube",defaultValue:null,public:!0,forRenderer:!0},e.source={createComponentOfType:"text",createStateVariable:"source",defaultValue:null,public:!0,forRenderer:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.size={public:!0,defaultValue:"full",hasEssential:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({sizeAttr:{dependencyType:"attributeComponent",attributeName:"size",variableNames:["value"]},widthAttr:{dependencyType:"attributeComponent",attributeName:"width",variableNames:["componentSize"]}}),definition({dependencyValues:e}){const t="full";if(e.sizeAttr){let n=e.sizeAttr.stateValues.value.toLowerCase();return sizePossibilities.includes(n)||(n=t),{setValue:{size:n}}}if(e.widthAttr){let n=e.widthAttr.stateValues.componentSize;if(null===n)return{setValue:{size:t}};let r,{isAbsolute:a,size:i}=n;if(a){for(let[e,t]of orderedWidthMidpoints.entries())if(i<=t){r=sizePossibilities[e];break}r||(r=t)}else{for(let[e,t]of orderedPercentWidthMidpoints.entries())if(i<=t){r=sizePossibilities[e];break}r||(r=t)}return{setValue:{size:r}}}return{useEssentialOrDefaultValue:{size:!0}}}},e.width={public:!0,forRenderer:!0,shadowingInstructions:{createComponentOfType:"_componentSize"},returnDependencies:()=>({size:{dependencyType:"stateVariable",variableName:"size"}}),definition:({dependencyValues:e})=>({setValue:{width:{isAbsolute:!0,size:widthsBySize[e.size]}}})},e.aspectRatio={public:!0,forRenderer:!0,defaultValue:"16 / 9",hasEssential:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({aspectRatioAttr:{dependencyType:"attributeComponent",attributeName:"aspectRatio",variableNames:["value"]},width:{dependencyType:"stateVariable",variableName:"width"}}),definition({dependencyValues:e}){if(null!==e.aspectRatioAttr){let t=e.aspectRatioAttr.stateValues.value;return Number.isFinite(t)||(t=1),{setValue:{aspectRatio:t}}}return{useEssentialOrDefaultValue:{aspectRatio:!0}}}},e.state={hasEssential:!0,defaultValue:"initializing",forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"text"},ignoreFixed:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{state:!0}}),inverseDefinition({desiredStateVariableValues:e}){let t=e.state.toLowerCase();return["stopped","playing"].includes(t)?{success:!0,instructions:[{setEssentialValue:"state",value:t}]}:{success:!1}}},e.time={hasEssential:!0,defaultValue:0,forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"number"},ignoreFixed:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{time:!0}}),inverseDefinition({desiredStateVariableValues:e}){let t=e.time;return t>=0?{success:!0,instructions:[{setEssentialValue:"time",value:t}]}:{success:!1}}},e.duration={hasEssential:!0,defaultValue:null,public:!0,shadowingInstructions:{createComponentOfType:"number"},ignoreFixed:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{duration:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"duration",value:e.duration}]})},e.segmentsWatched={hasEssential:!0,defaultValue:null,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{segmentsWatched:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"segmentsWatched",value:e.segmentsWatched}]})},e.secondsWatched={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({segmentsWatched:{dependencyType:"stateVariable",variableName:"segmentsWatched"}}),definition({dependencyValues:e}){let t=0;return e.segmentsWatched&&(t=e.segmentsWatched.reduce(((e,t)=>e+t[1]-t[0]),0)),{setValue:{secondsWatched:t}}}},e.fractionWatched={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({secondsWatched:{dependencyType:"stateVariable",variableName:"secondsWatched"},duration:{dependencyType:"stateVariable",variableName:"duration"}}),definition:({dependencyValues:e})=>({setValue:{fractionWatched:e.secondsWatched/e.duration}})},e}recordVideoStarted({beginTime:e,duration:t,rate:n}){this.coreFunctions.requestRecordEvent({verb:"played",object:{componentName:this.componentName,componentType:this.componentType,duration:t},context:{startingPoint:e,rate:n}}),this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"state",value:"playing"}],overrideReadOnly:!0})}async recordVideoWatched({beginTime:e,endTime:t,duration:n,rates:r}){this.coreFunctions.requestRecordEvent({verb:"watched",object:{componentName:this.componentName,componentType:this.componentType,duration:n},context:{startingPoint:e,endingPoint:t,rates:r}});let a,i=await this.stateValues.segmentsWatched;if(e<1?e=0:t>n-2&&(t=n),i){a=[];let n=!1;for(let[r,s]of i.entries()){if(ts[1]+1?a.push(s):(e=Math.min(s[0],e),t=Math.max(s[1],t))}n||a.push([e,t])}else a=[[e,t]];return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"segmentsWatched",value:a}],canSkipUpdatingRenderer:!0}),await this.coreFunctions.triggerChainedActions({componentName:this.componentName})}recordVideoPaused({endTime:e,duration:t}){this.coreFunctions.requestRecordEvent({verb:"paused",object:{componentName:this.componentName,componentType:this.componentType,duration:t},context:{endingPoint:e}}),this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"state",value:"stopped"}],overrideReadOnly:!0})}recordVideoSkipped({beginTime:e,endTime:t,duration:n}){this.coreFunctions.requestRecordEvent({verb:"skipped",object:{componentName:this.componentName,componentType:this.componentType,duration:n},context:{startingPoint:e,endingPoint:t}})}recordVideoCompleted({duration:e}){this.coreFunctions.requestRecordEvent({verb:"completed",object:{componentName:this.componentName,componentType:this.componentType,duration:e}}),this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"state",value:"stopped"}],overrideReadOnly:!0})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}recordVideoReady({duration:e}){this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"state",value:"stopped"},{updateType:"updateValue",componentName:this.componentName,stateVariable:"duration",value:e}],overrideReadOnly:!0,doNotSave:!0})}playVideo(){this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"state",value:"playing"}],overrideReadOnly:!0})}pauseVideo(){this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"state",value:"stopped"}],overrideReadOnly:!0})}setTime({time:e}){this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"time",value:e}],overrideReadOnly:!0})}}class Embed extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="embed";static createAttributesObject(){let e=super.createAttributesObject();return e.width={createComponentOfType:"_componentSize",createStateVariable:"width",defaultValue:{size:500,isAbsolute:!0},public:!0,forRenderer:!0},e.height={createComponentOfType:"_componentSize",createStateVariable:"height",defaultValue:{size:500,isAbsolute:!0},public:!0,forRenderer:!0},e.geogebra={createComponentOfType:"text",createStateVariable:"geogebra",defaultValue:null,public:!0,forRenderer:!0},e.encodedGeogebraContent={createComponentOfType:"text",createStateVariable:"encodedGeogebraContent",defaultValue:null,public:!0,forRenderer:!0},e.fromMathInsight={createComponentOfType:"text",createStateVariable:"fromMathInsight",defaultValue:null,public:!0,forRenderer:!0},e}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class Hint extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{revealHint:this.revealHint.bind(this),closeHint:this.closeHint.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="hint";static renderChildren=!0;static includeBlankStringChildren=!0;static returnChildGroups(){return[{group:"titles",componentTypes:["title"]},{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.showHints={forRenderer:!0,returnDependencies:()=>({hide:{dependencyType:"stateVariable",variableName:"hide"},showHintsFlag:{dependencyType:"flag",flagName:"showHints"}}),definition:({dependencyValues:e})=>({setValue:{showHints:e.showHintsFlag&&!e.hide}})},e.open={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,defaultValue:!1,hasEssential:!0,doNotShadowEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{open:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"open",value:e.open}]})},e.titleChildName={forRenderer:!0,returnDependencies:()=>({titleChild:{dependencyType:"child",childGroups:["titles"]}}),definition({dependencyValues:e}){let t=null;return e.titleChild.length>0&&(t=e.titleChild[e.titleChild.length-1].componentName),{setValue:{titleChildName:t}}}},e.childIndicesToRender={returnDependencies:()=>({titleChildren:{dependencyType:"child",childGroups:["titles"]},allChildren:{dependencyType:"child",childGroups:["anything","titles"]},titleChildName:{dependencyType:"stateVariable",variableName:"titleChildName"}}),definition({dependencyValues:e}){let t=[],n=e.titleChildren.map((e=>e.componentName));for(let[r,a]of e.allChildren.entries())"object"==typeof a&&n.includes(a.componentName)&&a.componentName!==e.titleChildName||t.push(r);return{setValue:{childIndicesToRender:t}}}},e.title={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({titleChild:{dependencyType:"child",childGroups:["titles"],variableNames:["text"]}}),definition:({dependencyValues:e})=>0===e.titleChild.length?{setValue:{title:"Hint"}}:{setValue:{title:e.titleChild[e.titleChild.length-1].stateValues.text}}},e}async revealHint({actionId:e}){return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"open",value:!0}],overrideReadOnly:!0,actionId:e,event:{verb:"viewed",object:{componentName:this.componentName,componentType:this.componentType}}})}async closeHint({actionId:e}){return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"open",value:!1}],overrideReadOnly:!0,actionId:e,event:{verb:"closed",object:{componentName:this.componentName,componentType:this.componentType}}})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class Solution extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{revealSolution:this.revealSolution.bind(this),closeSolution:this.closeSolution.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="solution";static renderChildren=!0;static sendToRendererEvenIfHidden=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.hide={createComponentOfType:"boolean"},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e}){return{success:!0,newChildren:[{componentType:"_solutionContainer",children:e}]}}}),e}static returnChildGroups(){return[{group:"inlinesBlocks",componentTypes:["_inline","_block"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.hide={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,defaultValue:!1,hasEssential:!0,returnDependencies:()=>({hideAttr:{dependencyType:"attributeComponent",attributeName:"hide",variableNames:["value"]},displayMode:{dependencyType:"flag",flagName:"solutionDisplayMode"}}),definition:({dependencyValues:e})=>"none"===e.displayMode?{setValue:{hide:!0}}:null!==e.hideAttr?{setValue:{hide:e.hideAttr.stateValues.value}}:{useEssentialOrDefaultValue:{hide:!0}},inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t})=>"none"===t.displayMode?{success:!1}:null!==t.hideAttr?{success:!0,instructions:[{setDependency:"hideAttr",desiredValue:e.hide,variableIndex:0}]}:{success:!0,instructions:[{setSetVariable:"hide",value:e.hide}]}},e.open={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,defaultValue:!1,hasEssential:!0,returnDependencies:()=>({displayMode:{dependencyType:"flag",flagName:"solutionDisplayMode"}}),definition:({dependencyValues:e})=>"displayed"===e.displayMode?{setValue:{open:!0}}:"none"===e.displayMode?{setValue:{open:!1}}:{useEssentialOrDefaultValue:{open:!0}},inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t})=>"displayed"===t.displayMode||"none"===t.displayMode?{success:!1}:{success:!0,instructions:[{setEssentialValue:"open",value:e.open}]}},e.canBeClosed={forRenderer:!0,returnDependencies:()=>({displayMode:{dependencyType:"flag",flagName:"solutionDisplayMode"}}),definition:({dependencyValues:e})=>"button"===e.displayMode?{setValue:{canBeClosed:!0}}:{setValue:{canBeClosed:!1}}},e.message={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,defaultValue:"",hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{message:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"message",value:e.message}]})},e}async revealSolution({actionId:e}){let t,{allowView:n,message:r,scoredComponent:a}=await this.coreFunctions.recordSolutionView(),i=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"open",value:n},{updateType:"updateValue",componentName:this.componentName,stateVariable:"message",value:r}];return n&&(i.push({updateType:"updateValue",componentName:a,stateVariable:"viewedSolution",value:!0}),t={verb:"viewed",object:{componentName:this.componentName,componentType:this.componentType}}),await this.coreFunctions.performUpdate({updateInstructions:i,actionId:e,event:t,overrideReadOnly:!0})}async closeSolution({actionId:e}){return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"open",value:!1}],overrideReadOnly:!0,actionId:e,event:{verb:"closed",object:{componentName:this.componentName,componentType:this.componentType}}})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}static includeBlankStringChildren=!0}class IntComma extends Text{static componentType="intcomma";static rendererType="text";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return renameStateVariable({stateVariableDefinitions:e,oldName:"value",newName:"originalValue"}),e.value={public:!0,shadowingInstructions:{createComponentOfType:this.componentType},returnDependencies:()=>({originalValue:{dependencyType:"stateVariable",variableName:"originalValue"}}),definition:function({dependencyValues:e}){let t=e.originalValue,n=/^(-?\d+)(\d{3})/,r=t.match(n);for(;null!==r;)t=t.replace(n,"$1,$2"),r=t.match(n);return{setValue:{value:t}}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:({dependencyValues:e})=>({setValue:{text:e.value}})},e}}const e$1="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".split("");var t$1=function(e){let t=(e=e||"_")+"-";for(let e=0;e<7;e++)t+=e$1[Math.floor(Math.random()*e$1.length)];return t};let r$1={"!":"¡","?":"¿Ɂ",'"':'“”"❝❞',"'":"‘‛❛❜","-":"—–",a:"ªÀÁÂÃÄÅàáâãäåĀāĂ㥹ǍǎǞǟǠǡǺǻȀȁȂȃȦȧȺΆΑΔΛάαλАадѦѧӐӑӒӓƛɅæ",b:"ßþƀƁƂƃƄƅɃΒβϐϦБВЪЬвъьѢѣҌҍ",c:"¢©ÇçĆćĈĉĊċČčƆƇƈȻȼͻͼͽϲϹϽϾСсєҀҁҪҫ",d:"ÐĎďĐđƉƊȡƋƌǷ",e:"ÈÉÊËèéêëĒēĔĕĖėĘęĚěƎƏƐǝȄȅȆȇȨȩɆɇΈΕΞΣέεξϱϵ϶ЀЁЕЭеѐёҼҽҾҿӖӗӘәӚӛӬӭ",f:"ƑƒϜϝӺӻҒғſ",g:"ĜĝĞğĠġĢģƓǤǥǦǧǴǵ",h:"ĤĥĦħƕǶȞȟΉΗЂЊЋНнђћҢңҤҥҺһӉӊ",I:"ÌÍÎÏ",i:"ìíîïĨĩĪīĬĭĮįİıƖƗȈȉȊȋΊΐΪίιϊІЇії",j:"ĴĵǰȷɈɉϳЈј",k:"ĶķĸƘƙǨǩΚκЌЖКжкќҚқҜҝҞҟҠҡ",l:"ĹĺĻļĽľĿŀŁłƚƪǀǏǐȴȽΙӀӏ",m:"ΜϺϻМмӍӎ",n:"ÑñŃńŅņŇňʼnŊŋƝƞǸǹȠȵΝΠήηϞЍИЙЛПийлпѝҊҋӅӆӢӣӤӥπ",o:"ÒÓÔÕÖØðòóôõöøŌōŎŏŐőƟƠơǑǒǪǫǬǭǾǿȌȍȎȏȪȫȬȭȮȯȰȱΌΘΟθοσόϕϘϙϬϭϴОФоѲѳӦӧӨөӪӫ",p:"ƤƿΡρϷϸϼРрҎҏÞ",q:"Ɋɋ",r:"ŔŕŖŗŘřƦȐȑȒȓɌɍЃГЯгяѓҐґ",s:"ŚśŜŝŞşŠšƧƨȘșȿЅѕ",t:"ŢţŤťŦŧƫƬƭƮȚțȶȾΓΤτϮТт",u:"µÙÚÛÜùúûüŨũŪūŬŭŮůŰűŲųƯưƱƲǓǔǕǖǗǘǙǚǛǜȔȕȖȗɄΰμυϋύ",v:"νѴѵѶѷ",w:"ŴŵƜωώϖϢϣШЩшщѡѿ",x:"×ΧχϗϰХхҲҳӼӽӾӿ",y:"ÝýÿŶŷŸƳƴȲȳɎɏΎΥΫγψϒϓϔЎУучўѰѱҮүҰұӮӯӰӱӲӳ",z:"ŹźŻżŽžƩƵƶȤȥɀΖζ"},a$1={};Object.keys(r$1).forEach((function(e){r$1[e].split("").forEach((function(t){a$1[t]=e}))}));var n$1=e=>{let t=e.split("");return t.forEach(((e,n)=>{a$1[e]&&(t[n]=a$1[e])})),t.join("")};const i$1=/([A-Z]\.)+[A-Z]?,?$/,o$1=/^[A-Z]\.,?$/,s$1=/[A-Z]{2,}('s|,)?$/,l$1=/([a-z]\.)+[a-z]\.?$/;var u$1=function(e){return!0===i$1.test(e)||!0===l$1.test(e)||!0===o$1.test(e)||!0===s$1.test(e)};const c$2=n$1,h$1=u$1,d$1=/[a-z\u00C0-\u00FF] ?\/ ?[a-z\u00C0-\u00FF]/,g$1=function(e){let t=e=(e=(e=e||"").toLowerCase()).trim();return e=c$2(e),!0===d$1.test(e)&&(e=e.replace(/\/.*/,"")),e=(e=(e=(e=(e=(e=(e=e.replace(/^[#@]/,"")).replace(/[,;.!?]+$/,"")).replace(/[\u0027\u0060\u00B4\u2018\u2019\u201A\u201B\u2032\u2035\u2039\u203A]+/g,"'")).replace(/[\u0022\u00AB\u00BB\u201C\u201D\u201E\u201F\u2033\u2034\u2036\u2037\u2E42\u301D\u301E\u301F\uFF02]+/g,'"')).replace(/\u2026/g,"...")).replace(/\u2013/g,"-")).replace(/([aeiou][ktrp])in$/,"$1ing"),!0===/^(re|un)-?[^aeiou]./.test(e)&&(e=e.replace("-","")),h$1(e)&&(e=e.replace(/\./g,"")),!1===/^[:;]/.test(e)&&(e=(e=(e=e.replace(/\.{3,}$/g,"")).replace(/[",\.!:;\?\)]+$/g,"")).replace(/^['"\(]+/g,"")),""===(e=(e=e.replace(/[\u200B-\u200D\uFEFF]/g,"")).trim())&&(e=t),e.replace(/([0-9]),([0-9])/g,"$1$2")},p$1=function(e){return(e=e.replace(/['’]s$/,"")).replace(/s['’]$/,"s")},m$1=/^[ \n\t\.\[\](){}⟨⟩:,،、‒–—―…!‹›«»‐\-?‘’;\/⁄·&*•^†‡°¡¿※№÷׺ª%‰+−=‱¶′″‴§~\|‖¦©℗®℠™¤₳฿\u0022\uFF02\u0027\u201C\u201F\u201B\u201E\u2E42\u201A\u2035\u2036\u2037\u301D\u0060\u301F]+/,f$1=/[ \n\t\.'\[\](){}⟨⟩:,،、‒–—―…!‹›«»‐\-?‘’;\/⁄·&*@•^†‡°¡¿※#№÷׺ª‰+−=‱¶′″‴§~\|‖¦©℗®℠™¤₳฿\u0022\uFF02\u201D\u00B4\u301E]+$/,b$1=/\//,y$1=/['’]/,v$1=/^[a-z]\.([a-z]\.)+/i,w$1=/^[-+\.][0-9]/,k$1=/^'[0-9]{2}/;var A$1=e=>{let t=e,n="",r="";""===(e=(e=e.replace(m$1,(t=>(n=t,"-"!==n&&"+"!==n&&"."!==n||!w$1.test(e)?"'"===n&&k$1.test(e)?(n="",t):"":(n="",t))))).replace(f$1,(a=>(r=a,y$1.test(a)&&/[sn]['’]$/.test(t)&&!1===y$1.test(n)?(r=r.replace(y$1,""),"'"):!0===v$1.test(e)?(r=r.replace(/\./,""),"."):""))))&&(t=t.replace(/ *$/,(e=>(r=e||"",""))),e=t,n="");let a=g$1(e);const i={text:e,clean:a,reduced:p$1(a),pre:n,post:r};return b$1.test(e)&&e.split(b$1).forEach((e=>{i.alias=i.alias||{},i.alias[e.trim()]=!0})),i},D$1={};!function(e){const t=/^[A-Z][a-z'\u00C0-\u00FF]/,n=/^[A-Z]+s?$/;e.toUpperCase=function(){return this.text=this.text.toUpperCase(),this},e.toLowerCase=function(){return this.text=this.text.toLowerCase(),this},e.toTitleCase=function(){return this.text=this.text.replace(/^ *[a-z\u00C0-\u00FF]/,(e=>e.toUpperCase())),this},e.isUpperCase=function(){return n.test(this.text)},e.isTitleCase=function(){return t.test(this.text)},e.titleCase=e.isTitleCase}(D$1);var $$1={};!function(e){const t=/(\u0022|\uFF02|\u0027|\u201C|\u2018|\u201F|\u201B|\u201E|\u2E42|\u201A|\u00AB|\u2039|\u2035|\u2036|\u2037|\u301D|\u0060|\u301F)/,n=/(\u0022|\uFF02|\u0027|\u201D|\u2019|\u201D|\u2019|\u201D|\u201D|\u2019|\u00BB|\u203A|\u2032|\u2033|\u2034|\u301E|\u00B4|\u301E)/;e.hasPost=function(e){return-1!==this.post.indexOf(e)},e.hasPre=function(e){return-1!==this.pre.indexOf(e)},e.hasQuote=function(){return t.test(this.pre)||n.test(this.post)},e.hasQuotation=e.hasQuote,e.hasComma=function(){return this.hasPost(",")},e.hasPeriod=function(){return!0===this.hasPost(".")&&!1===this.hasPost("...")},e.hasExclamation=function(){return this.hasPost("!")},e.hasQuestionMark=function(){return this.hasPost("?")||this.hasPost("¿")},e.hasEllipses=function(){return this.hasPost("..")||this.hasPost("…")||this.hasPre("..")||this.hasPre("…")},e.hasSemicolon=function(){return this.hasPost(";")},e.hasSlash=function(){return/\//.test(this.text)},e.hasHyphen=function(){const e=/^(-|–|—)$/;return e.test(this.post)||e.test(this.pre)},e.hasDash=function(){const e=/ (-|–|—) /;return e.test(this.post)||e.test(this.pre)},e.hasContraction=function(){return Boolean(this.implicit)},e.addPunctuation=function(e){return","!==e&&";"!==e||(this.post=this.post.replace(e,"")),this.post=e+this.post,this}}($$1);var P$1={};const E$1=function(e,t,n=3){if(e===t)return 1;if(e.lengthn?r:n)+1;if(Math.abs(n-r)>(a||100))return a||100;let i,s,o,l,u,c,p=[];for(let e=0;e4)return n;o=t[i-1],l=s===o?0:1,u=p[a-1][i]+1,(c=p[a][i-1]+1)1&&i>1&&s===t[i-2]&&e[a-2]===o&&(c=p[a-2][i-2]+l)t.fuzzy)return!0;if(!0===t.soft&&(n=E$1(t.word,e.root),n>t.fuzzy))return!0}return t.word===e.clean||t.word===e.text||t.word===e.reduced}return void 0!==t.tag?!0===e.tags[t.tag]:void 0!==t.method?"function"==typeof e[t.method]&&!0===e[t.method]():void 0!==t.regex?t.regex.test(e.clean):void 0!==t.fastOr?!(!e.implicit||!0!==t.fastOr.hasOwnProperty(e.implicit))||t.fastOr.hasOwnProperty(e.reduced)||t.fastOr.hasOwnProperty(e.text):void 0!==t.choices&&("and"===t.operator?t.choices.every((t=>H$1(e,t,n,r))):t.choices.some((t=>H$1(e,t,n,r))))}(e,t,n,r);return!0===t.negative?!a:a};const j$1=H$1,N$1=u$1,x$1={};P$1.doesMatch=function(e,t,n){return j$1(this,e,t,n)},P$1.isAcronym=function(){return N$1(this.text)},P$1.isImplicit=function(){return""===this.text&&Boolean(this.implicit)},P$1.isKnown=function(){return Object.keys(this.tags).some((e=>!0!==x$1[e]))},P$1.setRoot=function(e){let t=e.transforms,n=this.implicit||this.clean;if(this.tags.Plural&&(n=t.toSingular(n,e)),this.tags.Verb&&!this.tags.Negative&&!this.tags.Infinitive){let r=null;this.tags.PastTense?r="PastTense":this.tags.Gerund?r="Gerund":this.tags.PresentTense?r="PresentTense":this.tags.Participle?r="Participle":this.tags.Actor&&(r="Actor"),n=t.toInfinitive(n,e,r)}this.root=n};var F$1={};const C$1=n$1,B$1=/[\s-]/,G$1=/^[A-Z-]+$/;F$1.textOut=function(e,t,n){e=e||{};let r=this.text,a=this.pre,i=this.post;return!0===e.reduced&&(r=this.reduced||""),!0===e.root&&(r=this.root||""),!0===e.implicit&&this.implicit&&(r=this.implicit||""),!0===e.normal&&(r=this.clean||this.text||""),!0===e.root&&(r=this.root||this.reduced||""),!0===e.unicode&&(r=C$1(r)),!0===e.titlecase&&(this.tags.ProperNoun&&!this.titleCase()||(this.tags.Acronym?r=r.toUpperCase():G$1.test(r)&&!this.tags.Acronym&&(r=r.toLowerCase()))),!0===e.lowercase&&(r=r.toLowerCase()),!0===e.acronyms&&this.tags.Acronym&&(r=r.replace(/\./g,"")),!0!==e.whitespace&&!0!==e.root||(a="",i=" ",!1!==B$1.test(this.post)&&!e.last||this.implicit||(i="")),!0!==e.punctuation||e.root||(!0===this.hasPost(".")?i="."+i:!0===this.hasPost("?")?i="?"+i:!0===this.hasPost("!")?i="!"+i:!0===this.hasPost(",")?i=","+i:!0===this.hasEllipses()&&(i="..."+i)),!0!==t&&(a=""),!0!==n&&(i=""),!0===e.abbreviations&&this.tags.Abbreviation&&(i=i.replace(/^\./,"")),a+r+i};var z$1={};const I$1={Auxiliary:1,Possessive:1},O$1=function(e,t){let n=Object.keys(e.tags);const r=t.tags;return n=n.sort(((e,t)=>I$1[t]||!r[t]?-1:r[t]?r[e]?r[e].lineage.length>r[t].lineage.length?1:r[e].isA.length>r[t].isA.length?-1:0:0:1)),n},T$2={text:!0,tags:!0,implicit:!0,whitespace:!0,clean:!1,id:!1,index:!1,offset:!1,bestTag:!1};z$1.json=function(e,t){e=e||{};let n={};return(e=Object.assign({},T$2,e)).text&&(n.text=this.text),e.normal&&(n.normal=this.clean),e.tags&&(n.tags=Object.keys(this.tags)),e.clean&&(n.clean=this.clean),(e.id||e.offset)&&(n.id=this.id),e.implicit&&null!==this.implicit&&(n.implicit=this.implicit),e.whitespace&&(n.pre=this.pre,n.post=this.post),e.bestTag&&(n.bestTag=O$1(this,t)[0]),n};var V$1=Object.assign({},D$1,$$1,P$1,F$1,z$1),M$1={},J$1={};function L$1(){return"undefined"!=typeof window&&window.document}const S$1=function(e,t){for(e=e.toString();e.lengthe.charAt(0).toUpperCase()+e.substr(1);const _$1=J$1,K$1=function(e,t,n,r){let a=r.tags;if(""===t||"."===t||"-"===t)return;if("#"===t[0]&&(t=t.replace(/^#/,"")),t=_$1.titleCase(t),!0===e.tags[t])return;const i=r.isVerbose();!0===i&&_$1.logTag(e,t,n),e.tags[t]=!0,!0===a.hasOwnProperty(t)&&(a[t].isA.forEach((t=>{e.tags[t]=!0,!0===i&&_$1.logTag(e,"→ "+t)})),e.unTag(a[t].notA,"←",r))},q$1=J$1,W$1=/^[a-z]/,R$1=function(e,t,n,r){const a=r.isVerbose();if("*"===t)return e.tags={},e;var i;t=t.replace(/^#/,""),!0===W$1.test(t)&&(t=(i=t).charAt(0).toUpperCase()+i.substr(1)),!0===e.tags[t]&&(delete e.tags[t],!0===a&&q$1.logUntag(e,t,n));const s=r.tags;if(s[t]){let n=s[t].lineage;for(let t=0;te.clone()));return t.forEach(((e,n)=>{this.pool.add(e),t[n+1]&&(e.next=t[n+1].id),t[n-1]&&(e.prev=t[n-1].id)})),this.buildFrom(t[0].id,t.length)},lastTerm:function(){let e=this.terms();return e[e.length-1]},hasId:function(e){if(0===this.length||!e)return!1;if(this.start===e)return!0;if(this.cache.terms){let t=this.cache.terms;for(let n=0;n""!==e.text)).length},fullSentence:function(){let e=this.terms(0);for(;e.prev;)e=this.pool.get(e.prev);let t=e.id,n=1;for(;e.next;)e=this.pool.get(e.next),n+=1;return this.buildFrom(t,n)}},oe$1={text:function(e={},t,n){"string"==typeof e&&(e="normal"===e?{whitespace:!0,unicode:!0,lowercase:!0,punctuation:!0,acronyms:!0,abbreviations:!0,implicit:!0,normal:!0}:"clean"===e?{titlecase:!1,lowercase:!0,punctuation:!0,whitespace:!0,unicode:!0,implicit:!0,normal:!0}:"reduced"===e?{punctuation:!1,titlecase:!1,lowercase:!0,whitespace:!0,unicode:!0,implicit:!0,reduced:!0}:"implicit"===e?{punctuation:!0,implicit:!0,whitespace:!0,trim:!0}:"root"===e?{titlecase:!1,lowercase:!0,punctuation:!0,whitespace:!0,unicode:!0,implicit:!0,root:!0}:{});let r=this.terms(),a=!1;r[0]&&null===r[0].prev&&null===r[r.length-1].next&&(a=!0);let i=r.reduce(((i,s,o)=>{if(0===o&&""===s.text&&null!==s.implicit&&!e.implicit)return i;e.last=n&&o===r.length-1;let l=!0,u=!0;return!1===a&&(0===o&&t&&(l=!1),o===r.length-1&&n&&(u=!1)),i+s.textOut(e,l,u)}),"");return!0===a&&n&&(i=i.replace(/ +$/,"")),!0===e.trim&&(i=i.trim()),i}},se$1={trim:function(){let e=this.terms();if(e.length>0){e[0].pre=e[0].pre.replace(/^\s+/,"");let t=e[e.length-1];t.post=t.post.replace(/\s+$/,"")}return this}},le$1={};const ue$1=/[.?!]\s*$/,ce$1=function(e,t){t[0].pre=e[0].pre;let n=e[e.length-1],r=t[t.length-1];r.post=function(e,t){return ue$1.test(t)?t+e.match(/\s*$/):e}(n.post,r.post),n.post="",""===n.post&&(n.post+=" ")},he$1=/ /,de$1=function(e,t,n){let r=e.terms(),a=t.terms();ce$1(r,a),function(e,t,n){let r=e[e.length-1],a=t[t.length-1],i=r.next;r.next=t[0].id,a.next=i,i&&(n.get(i).prev=a.id);let s=e[0].id;s&&(t[0].prev=s)}(r,a,e.pool);let i=[e],s=e.start,o=[n];return o=o.concat(n.parents()),o.forEach((e=>{let t=e.list.filter((e=>e.hasId(s)));i=i.concat(t)})),i=function(e){return e.filter(((t,n)=>e.indexOf(t)===n))}(i),i.forEach((e=>{e.length+=t.length})),e.cache={},e},ge$1=function(e,t,n){const r=e.start;let a=t.terms();!function(e){let t=e[e.length-1];!1===he$1.test(t.post)&&(t.post+=" ")}(a),function(e,t,n){let r=n[n.length-1];r.next=e.start;let a=e.pool,i=a.get(e.start);i.prev&&(a.get(i.prev).next=t.start),n[0].prev=e.terms(0).prev,e.terms(0).prev=r.id}(e,t,a);let i=[e],s=[n];return s=s.concat(n.parents()),s.forEach((e=>{let n=e.list.filter((e=>e.hasId(r)||e.hasId(t.start)));i=i.concat(n)})),i=function(e){return e.filter(((t,n)=>e.indexOf(t)===n))}(i),i.forEach((e=>{e.length+=t.length,e.start===r&&(e.start=t.start),e.cache={}})),e},pe$1=function(e,t){let n=t.pool(),r=e.terms(),a=n.get(r[0].prev)||{},i=n.get(r[r.length-1].next)||{};r[0].implicit&&a.implicit&&(a.set(a.implicit),a.post+=" "),function(e,t,n,r){let a=e.parents();a.push(e),a.forEach((e=>{let a=e.list.find((e=>e.hasId(t)));a&&(a.length-=n,a.start===t&&(a.start=r.id),a.cache={})})),e.list=e.list.filter((e=>!(!e.start||!e.length)))}(t,e.start,e.length,i),a&&(a.next=i.id),i&&(i.prev=a.id)};le$1.append=function(e,t){return de$1(this,e,t),this},le$1.prepend=function(e,t){return ge$1(this,e,t),this},le$1.delete=function(e){return pe$1(this,e),this},le$1.replace=function(e,t){let n=this.length;de$1(this,e,t);let r=this.buildFrom(this.start,this.length);r.length=n,pe$1(r,t)},le$1.splitOn=function(e){let t=this.terms(),n={before:null,match:null,after:null},r=t.findIndex((t=>t.id===e.start));if(-1===r)return n;let a=t.slice(0,r);a.length>0&&(n.before=this.buildFrom(a[0].id,a.length));let i=t.slice(r,r+e.length);i.length>0&&(n.match=this.buildFrom(i[0].id,i.length));let s=t.slice(r+e.length,t.length);return s.length>0&&(n.after=this.buildFrom(s[0].id,s.length,this.pool)),n};var me$2={json:function(e={},t){let n={};return e.text&&(n.text=this.text()),e.normal&&(n.normal=this.text("normal")),e.clean&&(n.clean=this.text("clean")),e.reduced&&(n.reduced=this.text("reduced")),e.implicit&&(n.implicit=this.text("implicit")),e.root&&(n.root=this.text("root")),e.trim&&(n.text&&(n.text=n.text.trim()),n.normal&&(n.normal=n.normal.trim()),n.reduced&&(n.reduced=n.reduced.trim())),e.terms&&(!0===e.terms&&(e.terms={}),n.terms=this.terms().map((n=>n.json(e.terms,t)))),n}},fe$1={lookAhead:function(e){e||(e=".*");let t=this.pool,n=[];const r=function(e){let a=t.get(e);a&&(n.push(a),a.prev&&r(a.next))};let a=this.terms(),i=a[a.length-1];return r(i.next),0===n.length?[]:this.buildFrom(n[0].id,n.length).match(e)},lookBehind:function(e){e||(e=".*");let t=this.pool,n=[];const r=function(e){let a=t.get(e);a&&(n.push(a),a.prev&&r(a.prev))};let a=t.get(this.start);return r(a.prev),0===n.length?[]:this.buildFrom(n[n.length-1].id,n.length).match(e)}},be$1=Object.assign({},ie$1,oe$1,se$1,le$1,me$2,fe$1),ye$1={},ve$1,we$1=function(e,t){if(0===t.length)return!0;for(let e=0;e0)return!0;if(!0===n.anything&&!0===n.negative)return!0}return!1},ke$1={};(ve$1=ke$1).getGreedy=function(e,t){let n=Object.assign({},e.regs[e.r],{start:!1,end:!1}),r=e.t;for(;e.t{let a=0,i=e.t+r+t+a;if(void 0===e.terms[i])return!1;let s=e.terms[i].doesMatch(n,i+e.start_i,e.phrase_length);if(!0===s&&!0===n.greedy)for(let t=1;t{let r=n.every(((t,n)=>{let r=e.t+n;return void 0!==e.terms[r]&&e.terms[r].doesMatch(t,r,e.phrase_length)}));return!0===r&&n.length>t&&(t=n.length),r}))&&t},ve$1.getGroup=function(e,t,n){if(e.groups[e.groupId])return e.groups[e.groupId];const r=e.terms[t].id;return e.groups[e.groupId]={group:String(n),start:r,length:0},e.groups[e.groupId]};const Ae$1=t$1,De=ke$1;var $e$1=function(e,t,n,r){let a={t:0,terms:e,r:0,regs:t,groups:{},start_i:n,phrase_length:r,hasGroup:!1,groupId:null,previousGroup:null};for(;a.r!e.optional)))break;return null}if(!0===e.anything&&!0===e.greedy){let n=De.greedyTo(a,t[a.r+1]);if(null===n||0===n)return null;if(void 0!==e.min&&n-a.te.max){a.t=a.t+e.max;continue}!0===a.hasGroup&&(De.getGroup(a,a.t,e.named).length=n-a.t),a.t=n;continue}if(void 0!==e.choices&&"or"===e.operator){let t=De.doOrBlock(a);if(t){if(!0===e.negative)return null;!0===a.hasGroup&&(De.getGroup(a,a.t,e.named).length+=t),a.t+=t;continue}if(!e.optional)return null}if(void 0!==e.choices&&"and"===e.operator){let t=De.doAndBlock(a);if(t){if(!0===e.negative)return null;!0===a.hasGroup&&(De.getGroup(a,a.t,e.named).length+=t),a.t+=t;continue}if(!e.optional)return null}let n=a.terms[a.t],i=n.doesMatch(e,a.start_i+a.t,a.phrase_length);if(!0===e.anything||!0===i||De.isEndGreedy(e,a)){let i=a.t;if(e.optional&&t[a.r+1]&&e.negative)continue;if(e.optional&&t[a.r+1]){let r=n.doesMatch(t[a.r+1],a.start_i+a.t,a.phrase_length);if(e.negative||r){let e=a.terms[a.t+1];e&&e.doesMatch(t[a.r+1],a.start_i+a.t,a.phrase_length)||(a.r+=1)}}if(a.t+=1,!0===e.end&&a.t!==a.terms.length&&!0!==e.greedy)return null;if(!0===e.greedy){if(a.t=De.getGreedy(a,t[a.r+1]),null===a.t)return null;if(e.min&&e.min>a.t)return null;if(!0===e.end&&a.start_i+a.t!==r)return null}if(!0===a.hasGroup){const t=De.getGroup(a,i,e.named);a.t>1&&e.greedy?t.length+=a.t-i:t.length++}}else{if(e.negative){let t=Object.assign({},e);if(t.negative=!1,!0===a.terms[a.t].doesMatch(t,a.start_i+a.t,a.phrase_length))return null}if(!0!==e.optional){if(a.terms[a.t].isImplicit()&&t[a.r-1]&&a.terms[a.t+1]){if(a.terms[a.t-1]&&a.terms[a.t-1].implicit===t[a.r-1].word)return null;if(a.terms[a.t+1].doesMatch(e,a.start_i+a.t,a.phrase_length)){a.t+=2;continue}}return null}}}return{match:a.terms.slice(0,a.t),groups:a.groups}},Pe$1=function(e,t,n){if(!n||0===n.length)return n;if(t.some((e=>e.end))){let t=e[e.length-1];n=n.filter((({match:e})=>-1!==e.indexOf(t)))}return n};const Ee$1=/(?:^|\s)([\!\[\^]*(?:<[^<]*>)?\/.*?[^\\\/]\/[\?\]\+\*\$~]*)(?:\s|$)/,He=/([\!\[\^]*(?:<[^<]*>)?\([^\)]+[^\\\)]\)[\?\]\+\*\$~]*)(?:\s|$)/,je$1=/ /g,Ne$1=e=>/^[\!\[\^]*(<[^<]*>)?\//.test(e)&&/\/[\?\]\+\*\$~]*$/.test(e),xe$1=function(e){return(e=e.map((e=>e.trim()))).filter((e=>e))};var Fe$1=function(e){let t=e.split(Ee$1),n=[];t.forEach((e=>{Ne$1(e)?n.push(e):n=n.concat(e.split(He))})),n=xe$1(n);let r=[];return n.forEach((e=>{(e=>/^[\!\[\^]*(<[^<]*>)?\(/.test(e)&&/\)[\?\]\+\*\$~]*$/.test(e))(e)||Ne$1(e)?r.push(e):r=r.concat(e.split(je$1))})),r=xe$1(r),r};const Ce$1=/\{([0-9]+,?[0-9]*)\}/,Be=/&&/,Ge=new RegExp(/^<\s*?(\S+)\s*?>/),ze$1=function(e){return e[e.length-1]},Ie=function(e){return e[0]},Oe$1=function(e){return e.substr(1)},Te=function(e){return e.substr(0,e.length-1)},Ve$1=function(e){return e=Oe$1(e),Te(e)},Me$1=function(e){let t={};for(let n=0;n<2;n+=1){if("$"===ze$1(e)&&(t.end=!0,e=Te(e)),"^"===Ie(e)&&(t.start=!0,e=Oe$1(e)),("["===Ie(e)||"]"===ze$1(e))&&(t.named=!0,"["===Ie(e)?t.groupType="]"===ze$1(e)?"single":"start":t.groupType="end",e=(e=e.replace(/^\[/,"")).replace(/\]$/,""),"<"===Ie(e))){const n=Ge.exec(e);n.length>=2&&(t.named=n[1],e=e.replace(n[0],""))}if("+"===ze$1(e)&&(t.greedy=!0,e=Te(e)),"*"!==e&&"*"===ze$1(e)&&"\\*"!==e&&(t.greedy=!0,e=Te(e)),"?"===ze$1(e)&&(t.optional=!0,e=Te(e)),"!"===Ie(e)&&(t.negative=!0,e=Oe$1(e)),"("===Ie(e)&&")"===ze$1(e)){Be.test(e)?(t.choices=e.split(Be),t.operator="and"):(t.choices=e.split("|"),t.operator="or"),t.choices[0]=Oe$1(t.choices[0]);let n=t.choices.length-1;t.choices[n]=Te(t.choices[n]),t.choices=t.choices.map((e=>e.trim())),t.choices=t.choices.filter((e=>e)),t.choices=t.choices.map((e=>e.split(/ /g).map(Me$1))),e=""}if("/"===Ie(e)&&"/"===ze$1(e))return e=Ve$1(e),t.regex=new RegExp(e),t;if("~"===Ie(e)&&"~"===ze$1(e))return e=Ve$1(e),t.soft=!0,t.word=e,t}return!0===Ce$1.test(e)&&(e=e.replace(Ce$1,((e,n)=>{let r=n.split(/,/g);return 1===r.length?(t.min=Number(r[0]),t.max=Number(r[0])):(t.min=Number(r[0]),t.max=Number(r[1]||999)),t.greedy=!0,t.optional=!0,""}))),"#"===Ie(e)?(t.tag=Oe$1(e),t.tag=(n=t.tag).charAt(0).toUpperCase()+n.substr(1),t):"@"===Ie(e)?(t.method=Oe$1(e),t):"."===e?(t.anything=!0,t):"*"===e?(t.anything=!0,t.greedy=!0,t.optional=!0,t):(e&&(e=(e=e.replace("\\*","*")).replace("\\.","."),t.word=e.toLowerCase()),t);var n},Je=Fe$1,Le=Me$1,Se=function(e,t={}){return e.filter((e=>e.groupType)).length>0&&(e=function(e){let t,n=!1,r=-1;for(let a=0;a{if(void 0!==e.choices&&!0===e.choices.every((e=>{if(1!==e.length)return!1;let t=e[0];return void 0!==t.word&&!0!==t.negative&&!0!==t.optional&&!0!==t.method}))){let t={};e.choices.forEach((e=>{t[e[0].word]=!0})),e.fastOr=t,delete e.choices}return e}))}(e)),e};var _e=function(e,t={}){if(null==e||""===e)return[];if("object"==typeof e){if(function(e){return"[object Array]"===Object.prototype.toString.call(e)}(e)){if(0===e.length||!e[0])return[];if("object"==typeof e[0])return e;if("string"==typeof e[0])return function(e){return[{choices:e.map((e=>[{word:e}])),operator:"or"}]}(e)}return e&&"Doc"===e.isA?function(e){if(!e||!e.list||!e.list[0])return[];let t=[];return e.list.forEach((e=>{let n=[];e.terms().forEach((e=>{n.push(e.id)})),t.push(n)})),[{idBlocks:t}]}(e):[]}"number"==typeof e&&(e=String(e));let n=Je(e);return n=n.map((e=>Le(e))),n=Se(n,t),n=function(e,t){return!0===t.fuzzy&&(t.fuzzy=.85),"number"==typeof t.fuzzy&&(e=e.map((e=>(t.fuzzy>0&&e.word&&(e.fuzzy=t.fuzzy),e.choices&&e.choices.forEach((e=>{e.forEach((e=>{e.fuzzy=t.fuzzy}))})),e)))),e}(n,t),n};const Ke=we$1,qe=$e$1,We=Pe$1,Re=_e,Ue=function(e,t){let n=[],r=t[0].idBlocks;for(let t=0;t{0!==r.length&&r.every(((n,r)=>e[t+r].id===n))&&(n.push({match:e.slice(t,t+r.length)}),t+=r.length-1)}));return n};var Qe=function(e,t,n=!1){if("string"==typeof t&&(t=Re(t)),!0===Ke(e,t))return[];const r=t.filter((e=>!0!==e.optional&&!0!==e.negative)).length;let a=e.terms(),i=[];if(t[0].idBlocks){let e=Ue(a,t);if(e&&e.length>0)return We(a,t,e)}if(!0===t[0].start){let e=qe(a,t,0,a.length);return e&&e.match&&e.match.length>0&&(e.match=e.match.filter((e=>e)),i.push(e)),We(a,t,i)}for(let e=0;ea.length);e+=1){let r=qe(a.slice(e),t,e,a.length);if(r&&r.match&&r.match.length>0&&(e+=r.match.length-1,r.match=r.match.filter((e=>e)),i.push(r),!0===n))return We(a,t,i)}return We(a,t,i)};const Ze=Qe,Xe=Qe,Ye=function(e,t){let n={};Ze(e,t).forEach((({match:e})=>{e.forEach((e=>{n[e.id]=!0}))}));let r=e.terms(),a=[],i=[];return r.forEach((e=>{!0!==n[e.id]?i.push(e):i.length>0&&(a.push(i),i=[])})),i.length>0&&a.push(i),a};ye$1.match=function(e,t=!1){let n=Xe(this,e,t);return n=n.map((({match:e,groups:t})=>{let n=this.buildFrom(e[0].id,e.length,t);return n.cache.terms=e,n})),n},ye$1.has=function(e){return Xe(this,e,!0).length>0},ye$1.not=function(e){let t=Ye(this,e);return t=t.map((e=>this.buildFrom(e[0].id,e.length))),t},ye$1.canBe=function(e,t){let n=[],r=this.terms(),a=!1;for(let i=0;ie.length>0)).map((e=>this.buildFrom(e[0].id,e.length))),n};const et=be$1,tt=ye$1;class rt{constructor(e,t,n){this.start=e,this.length=t,this.isA="Phrase",Object.defineProperty(this,"pool",{enumerable:!1,writable:!0,value:n}),Object.defineProperty(this,"cache",{enumerable:!1,writable:!0,value:{}}),Object.defineProperty(this,"groups",{enumerable:!1,writable:!0,value:{}})}}rt.prototype.buildFrom=function(e,t,n){let r=new rt(e,t,this.pool);return n&&Object.keys(n).length>0?r.groups=n:r.groups=this.groups,r},Object.assign(rt.prototype,tt),Object.assign(rt.prototype,et);const at={term:"terms"};Object.keys(at).forEach((e=>rt.prototype[e]=rt.prototype[at[e]]));var nt=rt;class it{constructor(e={}){Object.defineProperty(this,"words",{enumerable:!1,value:e})}add(e){return this.words[e.id]=e,this}get(e){return this.words[e]}remove(e){delete this.words[e]}merge(e){return Object.assign(this.words,e.words),this}stats(){return{words:Object.keys(this.words).length}}}it.prototype.clone=function(){let e=Object.keys(this.words).reduce(((e,t)=>{let n=this.words[t].clone();return e[n.id]=n,e}),{});return new it(e)};var ot=it,st=e=>{e.forEach(((t,n)=>{n>0&&(t.prev=e[n-1].id),e[n+1]&&(t.next=e[n+1].id)}))};const lt=/(\S.+?[.!?\u203D\u2E18\u203C\u2047-\u2049])(?=\s+|$)/g,ut=/\S/,ct=/[ .][A-Z]\.? *$/i,ht=/(?:\u2026|\.{2,}) *$/,dt=/((?:\r?\n|\r)+)/,gt=/[a-z0-9\u00C0-\u00FF\u00a9\u00ae\u2000-\u3300\ud000-\udfff]/i,pt=/^\s+/,mt=function(e,t,n,r){if(r.hasLetter=function(e,t){return t||gt.test(e)}(t,r.hasLetter),!r.hasLetter)return!1;if(function(e,t){return-1!==t.indexOf(".")&&ct.test(e)}(e,t))return!1;if(function(e,t){return-1!==t.indexOf(".")&&ht.test(e)}(e,t))return!1;let a=e.replace(/[.!?\u203D\u2E18\u203C\u2047-\u2049] *$/,"").split(" "),i=a[a.length-1].toLowerCase();return!n.hasOwnProperty(i)};var ft=function(e,t){let n=t.cache.abbreviations;e=e||"";let r=[],a=[];if(!(e=String(e))||"string"!=typeof e||!1===ut.test(e))return r;let i=function(e){let t=[],n=e.split(dt);for(let e=0;e0&&(r.push(t),s=a[e+1]||"",o.hasLetter=!1),a[e]=""}if(0===r.length)return[e];for(let e=1;e(e[t]=!0,e)),{});const At=function(e){return!0!==/^(re|un|micro|macro|trans|bi|mono|over)-?[^aeiou]./.test(e)&&(!0!==/^([a-z\u00C0-\u00FF/]+)(-|–|—)(like|ish|less|able)/i.test(e)&&(!0===/^([a-z\u00C0-\u00FF`"'/]+)(-|–|—)([a-z0-9\u00C0-\u00FF].*)/i.test(e)||!0===/^([0-9]{1,4})(-|–|—)([a-z\u00C0-\u00FF`"'/-]+$)/i.test(e)))},Dt=function(e){let t=[];const n=e.split(/[-–—]/);let r="-",a=e.match(/[-–—]/);a&&a[0]&&(r=a);for(let e=0;e0?(t[t.length-1]+=a,t.push(r)):t.push(a+r),a=""):a+=r}return a&&(0===t.length&&(t[0]=""),t[t.length-1]+=a),t=function(e){for(let t=1;te)),t};var xt=function(e="",t,n){let r=null;return"string"!=typeof e&&("number"==typeof e?e=String(e):function(e){return"[object Array]"===Object.prototype.toString.call(e)}(e)&&(r=e)),r=r||jt(e,t),r=r.map((e=>Nt(e))),n=n||new Et,r.map((e=>{e=e.map((e=>{let t=new $t(e);return n.add(t),t})),Ht(e);let t=new Pt(e[0].id,e.length,n);return t.cache.terms=e,t}))};const Ft=ne$1,Ct=nt,Bt=ot,Gt=st;var zt=function(e,t){let n=new Bt;return e.map(((e,r)=>{let a=e.terms.map(((a,i)=>{let s=new Ft(a.text);return s.pre=void 0!==a.pre?a.pre:"",void 0===a.post&&(a.post=" ",i>=e.terms.length-1&&(a.post=". ",r>=e.terms.length-1&&(a.post="."))),s.post=void 0!==a.post?a.post:" ",a.tags&&a.tags.forEach((e=>s.tag(e,"",t))),n.add(s),s}));return Gt(a),new Ct(a[0].id,a.length,n)}))};const It=["Person","Place","Organization"],Ot=["Noun","Verb","Adjective","Adverb","Value","QuestionWord"],Tt={Noun:"blue",Verb:"green",Negative:"green",Date:"red",Value:"red",Adjective:"magenta",Preposition:"cyan",Conjunction:"cyan",Determiner:"cyan",Adverb:"cyan"},Vt=function(e){return Object.keys(e).forEach((t=>{e[t].color?e[t].color=e[t].color:Tt[t]?e[t].color=Tt[t]:e[t].isA.some((n=>!!Tt[n]&&(e[t].color=Tt[n],!0)))})),e},Mt=function(e){return Object.keys(e).forEach((t=>{let n=e[t],r=n.isA.length;for(let t=0;tn.indexOf(e)===t))}(n.isA)})),e},Jt=function(e){let t=Object.keys(e);return t.forEach((n=>{let r=e[n];r.notA=r.notA||[],r.isA.forEach((t=>{if(e[t]&&e[t].notA){let n="string"==typeof e[t].notA?[e[t].isA]:e[t].notA||[];r.notA=r.notA.concat(n)}}));for(let a=0;an.indexOf(e)===t))}(r.notA)})),e},Lt=function(e){let t=Object.keys(e);return t.forEach((n=>{let r=e[n];r.lineage=[];for(let a=0;a{let n=e[t];n.isA=n.isA||[],"string"==typeof n.isA&&(n.isA=[n.isA]),n.notA=n.notA||[],"string"==typeof n.notA&&(n.notA=[n.notA])})),e}(e),e=Mt(e),e=Jt(e),e=Vt(e),Lt(e)};const _t={Noun:{notA:["Verb","Adjective","Adverb"]},Singular:{isA:"Noun",notA:"Plural"},ProperNoun:{isA:"Noun"},Person:{isA:["ProperNoun","Singular"],notA:["Place","Organization","Date"]},FirstName:{isA:"Person"},MaleName:{isA:"FirstName",notA:["FemaleName","LastName"]},FemaleName:{isA:"FirstName",notA:["MaleName","LastName"]},LastName:{isA:"Person",notA:["FirstName"]},NickName:{isA:"Person",notA:["FirstName","LastName"]},Honorific:{isA:"Noun",notA:["FirstName","LastName","Value"]},Place:{isA:"Singular",notA:["Person","Organization"]},Country:{isA:["Place","ProperNoun"],notA:["City"]},City:{isA:["Place","ProperNoun"],notA:["Country"]},Region:{isA:["Place","ProperNoun"]},Address:{isA:"Place"},Organization:{isA:["Singular","ProperNoun"],notA:["Person","Place"]},SportsTeam:{isA:"Organization"},School:{isA:"Organization"},Company:{isA:"Organization"},Plural:{isA:"Noun",notA:["Singular"]},Uncountable:{isA:"Noun"},Pronoun:{isA:"Noun",notA:It},Actor:{isA:"Noun",notA:It},Activity:{isA:"Noun",notA:["Person","Place"]},Unit:{isA:"Noun",notA:It},Demonym:{isA:["Noun","ProperNoun"],notA:It},Possessive:{isA:"Noun"}},Kt={Verb:{notA:["Noun","Adjective","Adverb","Value","Expression"]},PresentTense:{isA:"Verb",notA:["PastTense","FutureTense"]},Infinitive:{isA:"PresentTense",notA:["PastTense","Gerund"]},Imperative:{isA:"Infinitive"},Gerund:{isA:"PresentTense",notA:["PastTense","Copula","FutureTense"]},PastTense:{isA:"Verb",notA:["FutureTense"]},FutureTense:{isA:"Verb"},Copula:{isA:"Verb"},Modal:{isA:"Verb",notA:["Infinitive"]},PerfectTense:{isA:"Verb",notA:"Gerund"},Pluperfect:{isA:"Verb"},Participle:{isA:"PastTense"},PhrasalVerb:{isA:"Verb"},Particle:{isA:"PhrasalVerb"},Auxiliary:{notA:["Noun","Adjective","Value"]}},qt={Value:{notA:["Verb","Adjective","Adverb"]},Ordinal:{isA:"Value",notA:["Cardinal"]},Cardinal:{isA:"Value",notA:["Ordinal"]},Fraction:{isA:"Value",notA:["Noun"]},RomanNumeral:{isA:"Cardinal",notA:["Ordinal","TextValue"]},TextValue:{isA:"Value",notA:["NumericValue"]},NumericValue:{isA:"Value",notA:["TextValue"]},Money:{isA:"Cardinal"},Percent:{isA:"Value"}},Wt={Adjective:{notA:["Noun","Verb","Adverb","Value"]},Comparable:{isA:["Adjective"]},Comparative:{isA:["Adjective"]},Superlative:{isA:["Adjective"],notA:["Comparative"]},NumberRange:{},Adverb:{notA:["Noun","Verb","Adjective","Value"]},Date:{notA:["Verb","Adverb","Preposition","Adjective"]},Month:{isA:["Date","Singular"],notA:["Year","WeekDay","Time"]},WeekDay:{isA:["Date","Noun"]},Timezone:{isA:["Date","Noun"],notA:["Adjective","ProperNoun"]},Time:{isA:["Date"],notA:["AtMention"]},Determiner:{notA:Ot},Conjunction:{notA:Ot},Preposition:{notA:Ot},QuestionWord:{notA:["Determiner"]},Currency:{isA:["Noun"]},Expression:{notA:["Noun","Adjective","Verb","Adverb"]},Abbreviation:{},Url:{notA:["HashTag","PhoneNumber","Verb","Adjective","Value","AtMention","Email"]},PhoneNumber:{notA:["HashTag","Verb","Adjective","Value","AtMention","Email"]},HashTag:{},AtMention:{isA:["Noun"],notA:["HashTag","Verb","Adjective","Value","Email"]},Emoji:{notA:["HashTag","Verb","Adjective","Value","AtMention"]},Emoticon:{notA:["HashTag","Verb","Adjective","Value","AtMention"]},Email:{notA:["HashTag","Verb","Adjective","Value","AtMention"]},Acronym:{notA:["Plural","RomanNumeral"]},Negative:{notA:["Noun","Adjective","Value"]},Condition:{notA:["Verb","Adjective","Noun","Value"]}},Rt=St,Ut=function(e,t){Object.keys(e).forEach((n=>{t[n]=e[n]}))};var Qt=(()=>{let e={};return Ut(_t,e),Ut(Kt,e),Ut(qt,e),Ut(Wt,e),e=Rt(e),e})();const Zt="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ",Xt=Zt.split("").reduce((function(e,t,n){return e[t]=n,e}),{});var Yt=function(e){if(void 0!==Xt[e])return Xt[e];let t=0,n=1,r=36,a=1;for(;n=0;n--,a*=36){let r=e.charCodeAt(n)-48;r>10&&(r-=7),t+=r*a}return t};const er=function(e,t,n){const r=Yt(t);return r{let i=e.nodes[r];"!"===i[0]&&(t.push(a),i=i.slice(1));const s=i.split(/([A-Z0-9,]+)/g);for(let i=0;i{const n=t.split("¦");return e[n[0]]=n[1],e}),{}),n={};return Object.keys(t).forEach((function(e){const r=tr(t[e]);"true"===e&&(e=!0);for(let t=0;t{e[t]=["Abbreviation","Unit"]},Cardinal:(e,t)=>{e[t]=["TextValue","Cardinal"]},TextOrdinal:(e,t)=>{e[t]=["Ordinal","TextValue"],e[t+"s"]=["TextValue","Fraction"]},Singular:(e,t,n)=>{e[t]="Singular";let r=n.transforms.toPlural(t,n);e[r]=e[r]||"Plural"},Infinitive:(e,t,n)=>{e[t]="Infinitive";let r=n.transforms.conjugate(t,n),a=Object.keys(r);for(let t=0;t{e[t]="Comparable";let r=n.transforms.adjectives(t),a=Object.keys(r);for(let t=0;t{e[t]=["PhrasalVerb","Infinitive"];let r=t.split(" "),a=n.transforms.conjugate(r[0],n),i=Object.keys(a);for(let t=0;t{e[t]="Demonym";let r=n.transforms.toPlural(t,n);e[r]=e[r]||["Demonym","Plural"]}},or=function(e,t,n){Object.keys(e).forEach((r=>{let a=e[r];"Abbreviation"!==a&&"Unit"!==a||(n.cache.abbreviations[r]=!0);let i=r.split(" ");i.length>1&&(n.hasCompound[i[0]]=!0),void 0===ir[a]?void 0!==t[r]?("string"==typeof t[r]&&(t[r]=[t[r]]),"string"==typeof a?t[r].push(a):t[r]=t[r].concat(a)):t[r]=a:ir[a](t,r,n)}))};var sr={buildOut:function(e){let t=Object.assign({},nr);return Object.keys(rr).forEach((n=>{let r=ar(rr[n]);Object.keys(r).forEach((e=>{r[e]=n})),or(r,t,e)})),t},addWords:or},lr=function(e){let t=e.irregulars.nouns,n=Object.keys(t);for(let r=0;r{e.words[i[t]]=e.words[i[t]]||t,"Participle"===e.words[i[t]]&&(e.words[i[t]]=t)}))}};const ur={g:"Gerund",prt:"Participle",perf:"PerfectTense",pst:"PastTense",fut:"FuturePerfect",pres:"PresentTense",pluperf:"Pluperfect",a:"Actor"};let cr={act:{a:"_or"},ache:{pst:"ached",g:"aching"},age:{g:"ageing",pst:"aged",pres:"ages"},aim:{a:"_er",g:"_ing",pst:"_ed"},arise:{prt:"_n",pst:"arose"},babysit:{a:"_ter",pst:"babysat"},ban:{a:"",g:"_ning",pst:"_ned"},be:{a:"",g:"am",prt:"been",pst:"was",pres:"is"},beat:{a:"_er",g:"_ing",prt:"_en"},become:{prt:"_"},begin:{g:"_ning",prt:"begun",pst:"began"},being:{g:"are",pst:"were",pres:"are"},bend:{prt:"bent"},bet:{a:"_ter",prt:"_"},bind:{pst:"bound"},bite:{g:"biting",prt:"bitten",pst:"bit"},bleed:{pst:"bled",prt:"bled"},blow:{prt:"_n",pst:"blew"},boil:{a:"_er"},brake:{prt:"broken"},break:{pst:"broke"},breed:{pst:"bred"},bring:{pst:"brought",prt:"brought"},broadcast:{pst:"_"},budget:{pst:"_ed"},build:{pst:"built",prt:"built"},burn:{prt:"_ed"},burst:{prt:"_"},buy:{pst:"bought",prt:"bought"},can:{a:"",fut:"_",g:"",pst:"could",perf:"could",pluperf:"could",pres:"_"},catch:{pst:"caught"},choose:{g:"choosing",prt:"chosen",pst:"chose"},cling:{prt:"clung"},come:{prt:"_",pst:"came",g:"coming"},compete:{a:"competitor",g:"competing",pst:"_d"},cost:{pst:"_"},creep:{prt:"crept"},cut:{prt:"_"},deal:{pst:"_t",prt:"_t"},develop:{a:"_er",g:"_ing",pst:"_ed"},die:{g:"dying",pst:"_d"},dig:{g:"_ging",pst:"dug",prt:"dug"},dive:{prt:"_d"},do:{pst:"did",pres:"_es"},draw:{prt:"_n",pst:"drew"},dream:{prt:"_t"},drink:{prt:"drunk",pst:"drank"},drive:{g:"driving",prt:"_n",pst:"drove"},drop:{g:"_ping",pst:"_ped"},eat:{a:"_er",g:"_ing",prt:"_en",pst:"ate"},edit:{pst:"_ed",g:"_ing"},egg:{pst:"_ed"},fall:{prt:"_en",pst:"fell"},feed:{prt:"fed",pst:"fed"},feel:{a:"_er",pst:"felt"},fight:{pst:"fought",prt:"fought"},find:{pst:"found"},flee:{g:"_ing",prt:"fled"},fling:{prt:"flung"},fly:{prt:"flown",pst:"flew"},forbid:{pst:"forbade"},forget:{g:"_ing",prt:"forgotten",pst:"forgot"},forgive:{g:"forgiving",prt:"_n",pst:"forgave"},free:{a:"",g:"_ing"},freeze:{g:"freezing",prt:"frozen",pst:"froze"},get:{pst:"got",prt:"gotten"},give:{g:"giving",prt:"_n",pst:"gave"},go:{prt:"_ne",pst:"went",pres:"goes"},grow:{prt:"_n"},guide:{pst:"_d"},hang:{pst:"hung",prt:"hung"},have:{g:"having",pst:"had",prt:"had",pres:"has"},hear:{pst:"_d",prt:"_d"},hide:{prt:"hidden",pst:"hid"},hit:{prt:"_"},hold:{pst:"held",prt:"held"},hurt:{pst:"_",prt:"_"},ice:{g:"icing",pst:"_d"},imply:{pst:"implied",pres:"implies"},is:{a:"",g:"being",pst:"was",pres:"_"},keep:{prt:"kept"},kneel:{prt:"knelt"},know:{prt:"_n"},lay:{pst:"laid",prt:"laid"},lead:{pst:"led",prt:"led"},leap:{prt:"_t"},leave:{pst:"left",prt:"left"},lend:{prt:"lent"},lie:{g:"lying",pst:"lay"},light:{pst:"lit",prt:"lit"},log:{g:"_ging",pst:"_ged"},loose:{prt:"lost"},lose:{g:"losing",pst:"lost"},make:{pst:"made",prt:"made"},mean:{pst:"_t",prt:"_t"},meet:{a:"_er",g:"_ing",pst:"met",prt:"met"},miss:{pres:"_"},name:{g:"naming"},patrol:{g:"_ling",pst:"_led"},pay:{pst:"paid",prt:"paid"},prove:{prt:"_n"},puke:{g:"puking"},put:{prt:"_"},quit:{prt:"_"},read:{pst:"_",prt:"_"},ride:{prt:"ridden"},reside:{pst:"_d"},ring:{pst:"rang",prt:"rung"},rise:{fut:"will have _n",g:"rising",prt:"_n",pst:"rose",pluperf:"had _n"},rub:{g:"_bing",pst:"_bed"},run:{g:"_ning",prt:"_",pst:"ran"},say:{pst:"said",prt:"said",pres:"_s"},seat:{pst:"sat",prt:"sat"},see:{g:"_ing",prt:"_n",pst:"saw"},seek:{prt:"sought"},sell:{pst:"sold",prt:"sold"},send:{prt:"sent"},set:{prt:"_"},sew:{prt:"_n"},shake:{prt:"_n"},shave:{prt:"_d"},shed:{g:"_ding",pst:"_",pres:"_s"},shine:{pst:"shone",prt:"shone"},shoot:{pst:"shot",prt:"shot"},show:{pst:"_ed"},shut:{prt:"_"},sing:{prt:"sung",pst:"sang"},sink:{pst:"sank",pluperf:"had sunk"},sit:{pst:"sat"},ski:{pst:"_ied"},slay:{prt:"slain"},sleep:{prt:"slept"},slide:{pst:"slid",prt:"slid"},smash:{pres:"_es"},sneak:{prt:"snuck"},speak:{fut:"will have spoken",prt:"spoken",pst:"spoke",perf:"have spoken",pluperf:"had spoken"},speed:{prt:"sped"},spend:{prt:"spent"},spill:{prt:"_ed",pst:"spilt"},spin:{g:"_ning",pst:"spun",prt:"spun"},spit:{prt:"spat"},split:{prt:"_"},spread:{pst:"_"},spring:{prt:"sprung"},stand:{pst:"stood"},steal:{a:"_er",pst:"stole"},stick:{pst:"stuck"},sting:{pst:"stung"},stink:{pst:"stunk",prt:"stunk"},stream:{a:"_er"},strew:{prt:"_n"},strike:{g:"striking",pst:"struck"},suit:{a:"_er",g:"_ing",pst:"_ed"},sware:{prt:"sworn"},swear:{pst:"swore"},sweep:{prt:"swept"},swim:{g:"_ming",pst:"swam"},swing:{pst:"swung"},take:{fut:"will have _n",pst:"took",perf:"have _n",pluperf:"had _n"},teach:{pst:"taught",pres:"_es"},tear:{pst:"tore"},tell:{pst:"told"},think:{pst:"thought"},thrive:{prt:"_d"},tie:{g:"tying",pst:"_d"},undergo:{prt:"_ne"},understand:{pst:"understood"},upset:{prt:"_"},wait:{a:"_er",g:"_ing",pst:"_ed"},wake:{pst:"woke"},wear:{pst:"wore"},weave:{prt:"woven"},wed:{pst:"wed"},weep:{prt:"wept"},win:{g:"_ning",pst:"won"},wind:{prt:"wound"},withdraw:{pst:"withdrew"},wring:{prt:"wrung"},write:{g:"writing",prt:"written",pst:"wrote"}},hr=Object.keys(cr);for(let e=0;e{let r=cr[t][e];r=r.replace("_",t),n[ur[e]]=r})),cr[t]=n}var dr=cr;const gr={b:[{reg:/([^aeiou][aeiou])b$/i,repl:{pr:"$1bs",pa:"$1bbed",gr:"$1bbing"}}],d:[{reg:/(end)$/i,repl:{pr:"$1s",pa:"ent",gr:"$1ing",ar:"$1er"}},{reg:/(eed)$/i,repl:{pr:"$1s",pa:"$1ed",gr:"$1ing",ar:"$1er"}},{reg:/(ed)$/i,repl:{pr:"$1s",pa:"$1ded",ar:"$1der",gr:"$1ding"}},{reg:/([^aeiou][ou])d$/i,repl:{pr:"$1ds",pa:"$1dded",gr:"$1dding"}}],e:[{reg:/(eave)$/i,repl:{pr:"$1s",pa:"$1d",gr:"eaving",ar:"$1r"}},{reg:/(ide)$/i,repl:{pr:"$1s",pa:"ode",gr:"iding",ar:"ider"}},{reg:/(t|sh?)(ake)$/i,repl:{pr:"$1$2s",pa:"$1ook",gr:"$1aking",ar:"$1$2r"}},{reg:/w(ake)$/i,repl:{pr:"w$1s",pa:"woke",gr:"waking",ar:"w$1r"}},{reg:/m(ake)$/i,repl:{pr:"m$1s",pa:"made",gr:"making",ar:"m$1r"}},{reg:/(a[tg]|i[zn]|ur|nc|gl|is)e$/i,repl:{pr:"$1es",pa:"$1ed",gr:"$1ing"}},{reg:/([bd]l)e$/i,repl:{pr:"$1es",pa:"$1ed",gr:"$1ing"}},{reg:/(om)e$/i,repl:{pr:"$1es",pa:"ame",gr:"$1ing"}}],g:[{reg:/([^aeiou][aou])g$/i,repl:{pr:"$1gs",pa:"$1gged",gr:"$1gging"}}],h:[{reg:/(..)([cs]h)$/i,repl:{pr:"$1$2es",pa:"$1$2ed",gr:"$1$2ing"}}],k:[{reg:/(ink)$/i,repl:{pr:"$1s",pa:"unk",gr:"$1ing",ar:"$1er"}}],m:[{reg:/([^aeiou][aeiou])m$/i,repl:{pr:"$1ms",pa:"$1mmed",gr:"$1mming"}}],n:[{reg:/(en)$/i,repl:{pr:"$1s",pa:"$1ed",gr:"$1ing"}}],p:[{reg:/(e)(ep)$/i,repl:{pr:"$1$2s",pa:"$1pt",gr:"$1$2ing",ar:"$1$2er"}},{reg:/([^aeiou][aeiou])p$/i,repl:{pr:"$1ps",pa:"$1pped",gr:"$1pping"}},{reg:/([aeiu])p$/i,repl:{pr:"$1ps",pa:"$1p",gr:"$1pping"}}],r:[{reg:/([td]er)$/i,repl:{pr:"$1s",pa:"$1ed",gr:"$1ing"}},{reg:/(er)$/i,repl:{pr:"$1s",pa:"$1ed",gr:"$1ing"}}],s:[{reg:/(ish|tch|ess)$/i,repl:{pr:"$1es",pa:"$1ed",gr:"$1ing"}}],t:[{reg:/(ion|end|e[nc]t)$/i,repl:{pr:"$1s",pa:"$1ed",gr:"$1ing"}},{reg:/(.eat)$/i,repl:{pr:"$1s",pa:"$1ed",gr:"$1ing"}},{reg:/([aeiu])t$/i,repl:{pr:"$1ts",pa:"$1t",gr:"$1tting"}},{reg:/([^aeiou][aeiou])t$/i,repl:{pr:"$1ts",pa:"$1tted",gr:"$1tting"}}],w:[{reg:/(.llow)$/i,repl:{pr:"$1s",pa:"$1ed"}},{reg:/(..)(ow)$/i,repl:{pr:"$1$2s",pa:"$1ew",gr:"$1$2ing",prt:"$1$2n"}}],y:[{reg:/(i|f|rr)y$/i,repl:{pr:"$1ies",pa:"$1ied",gr:"$1ying"}}],z:[{reg:/([aeiou]zz)$/i,repl:{pr:"$1es",pa:"$1ed",gr:"$1ing"}}]},pr={pr:"PresentTense",pa:"PastTense",gr:"Gerund",prt:"Participle",ar:"Actor"},mr=function(e,t){let n={},r=Object.keys(t.repl);for(let a=0;a"e"===e.charAt(e.length-1)?e.replace(/e$/,"ing"):e+"ing",PresentTense:e=>"s"===e.charAt(e.length-1)?e+"es":!0===fr.test(e)?e.slice(0,-1)+"ies":e+"s",PastTense:e=>"e"===e.charAt(e.length-1)?e+"d":"ed"===e.substr(-2)?e:!0===fr.test(e)?e.slice(0,-1)+"ied":e+"ed"};var vr=function(e="",t){let n={};return t&&t.irregulars&&!0===t.irregulars.verbs.hasOwnProperty(e)&&(n=Object.assign({},t.irregulars.verbs[e])),n=Object.assign({},br(e),n),void 0===n.Gerund&&(n.Gerund=yr.Gerund(e)),void 0===n.PastTense&&(n.PastTense=yr.PastTense(e)),void 0===n.PresentTense&&(n.PresentTense=yr.PresentTense(e)),n};const wr=[/ght$/,/nge$/,/ough$/,/ain$/,/uel$/,/[au]ll$/,/ow$/,/oud$/,/...p$/],kr=[/ary$/],Ar={nice:"nicest",late:"latest",hard:"hardest",inner:"innermost",outer:"outermost",far:"furthest",worse:"worst",bad:"worst",good:"best",big:"biggest",large:"largest"},Dr=[{reg:/y$/i,repl:"iest"},{reg:/([aeiou])t$/i,repl:"$1ttest"},{reg:/([aeou])de$/i,repl:"$1dest"},{reg:/nge$/i,repl:"ngest"},{reg:/([aeiou])te$/i,repl:"$1test"}],$r=[/ght$/,/nge$/,/ough$/,/ain$/,/uel$/,/[au]ll$/,/ow$/,/old$/,/oud$/,/e[ae]p$/],Pr=[/ary$/,/ous$/],Er={grey:"greyer",gray:"grayer",green:"greener",yellow:"yellower",red:"redder",good:"better",well:"better",bad:"worse",sad:"sadder",big:"bigger"},Hr=[{reg:/y$/i,repl:"ier"},{reg:/([aeiou])t$/i,repl:"$1tter"},{reg:/([aeou])de$/i,repl:"$1der"},{reg:/nge$/i,repl:"nger"}],jr={toSuperlative:function(e){if(Ar.hasOwnProperty(e))return Ar[e];for(let t=0;t(e[a[t]]=t,e)),{}));var a;if(r.hasOwnProperty(e))return r[e];for(let t=0;t(Ir[t].forEach((n=>e[n]=t)),e)),{});const Or=zr,Tr=Ir,Vr=Qt,Mr=sr,Jr=lr,Lr=St,Sr={nouns:{addendum:"addenda",alga:"algae",alumna:"alumnae",alumnus:"alumni",analysis:"analyses",antenna:"antennae",appendix:"appendices",avocado:"avocados",axis:"axes",bacillus:"bacilli",barracks:"barracks",beau:"beaux",bus:"buses",cactus:"cacti",chateau:"chateaux",child:"children",circus:"circuses",clothes:"clothes",corpus:"corpora",criterion:"criteria",curriculum:"curricula",database:"databases",deer:"deer",diagnosis:"diagnoses",echo:"echoes",embargo:"embargoes",epoch:"epochs",foot:"feet",formula:"formulae",fungus:"fungi",genus:"genera",goose:"geese",halo:"halos",hippopotamus:"hippopotami",index:"indices",larva:"larvae",leaf:"leaves",libretto:"libretti",loaf:"loaves",man:"men",matrix:"matrices",memorandum:"memoranda",modulus:"moduli",mosquito:"mosquitoes",mouse:"mice",nebula:"nebulae",nucleus:"nuclei",octopus:"octopi",opus:"opera",ovum:"ova",ox:"oxen",parenthesis:"parentheses",person:"people",phenomenon:"phenomena",prognosis:"prognoses",quiz:"quizzes",radius:"radii",referendum:"referenda",rodeo:"rodeos",sex:"sexes",shoe:"shoes",sombrero:"sombreros",stimulus:"stimuli",stomach:"stomachs",syllabus:"syllabi",synopsis:"synopses",tableau:"tableaux",thesis:"theses",thief:"thieves",tooth:"teeth",tornado:"tornados",tuxedo:"tuxedos",vertebra:"vertebrae"},verbs:dr},_r={conjugate:vr,adjectives:Nr,toPlural:Cr,toSingular:Gr,toInfinitive:function(e,t,n){if(!e)return"";if(!0===t.words.hasOwnProperty(e)){let n=t.irregulars.verbs,r=Object.keys(n);for(let t=0;t{let r=e[n];n=n.toLowerCase().trim(),t[n]=r})),Mr.addWords(t,this.words,this)}addConjugations(e){return Object.assign(this.irregulars.verbs,e),this}addPlurals(e){return Object.assign(this.irregulars.nouns,e),this}addTags(e){return e=Object.assign({},e),this.tags=Object.assign(this.tags,e),this.tags=Lr(this.tags),this}postProcess(e){return this.taggers.push(e),this}stats(){return{words:Object.keys(this.words).length,plurals:Object.keys(this.irregulars.nouns).length,conjugations:Object.keys(this.irregulars.verbs).length,compounds:Object.keys(this.hasCompound).length,postProcessors:this.taggers.length}}}const Wr=function(e){return JSON.parse(JSON.stringify(e))};qr.prototype.clone=function(){let e=new qr;return e.words=Object.assign({},this.words),e.hasCompound=Object.assign({},this.hasCompound),e.irregulars=Wr(this.irregulars),e.tags=Wr(this.tags),e.transforms=this.transforms,e.taggers=this.taggers,e};var Rr=qr,Ur={};!function(e){e.all=function(){return this.parents()[0]||this},e.parent=function(){return this.from?this.from:this},e.parents=function(e){let t=[];const n=function(e){e.from&&(t.push(e.from),n(e.from))};return n(this),t=t.reverse(),"number"==typeof e?t[e]:t},e.clone=function(e){let t=this.list.map((t=>t.clone(e)));return this.buildFrom(t)},e.wordCount=function(){return this.list.reduce(((e,t)=>e+t.wordCount()),0)},e.wordcount=e.wordCount}(Ur);var Qr={};!function(e){e.first=function(e){return void 0===e?this.get(0):this.slice(0,e)},e.last=function(e){if(void 0===e)return this.get(this.list.length-1);let t=this.list.length;return this.slice(t-e,t)},e.slice=function(e,t){let n=this.list.slice(e,t);return this.buildFrom(n)},e.eq=function(e){let t=this.list[e];return void 0===t?this.buildFrom([]):this.buildFrom([t])},e.get=e.eq,e.firstTerms=function(){return this.match("^.")},e.firstTerm=e.firstTerms,e.lastTerms=function(){return this.match(".$")},e.lastTerm=e.lastTerms,e.termList=function(e){let t=[];for(let n=0;nr.groups[e]));for(let e=0;ea.groups[e].group===t)),i.forEach((e=>{n.push(a.buildFrom(a.groups[e].start,a.groups[e].length))}))}return e.buildFrom(n)}(this,e)||this.buildFrom([]))},e.group=e.groups,e.sentences=function(e){let t=[];return this.list.forEach((e=>{t.push(e.fullSentence())})),"number"==typeof e?this.buildFrom([t[e]]):this.buildFrom(t)},e.sentence=e.sentences}(Qr);var Zr={},Xr=function(e,t){if(e._cache&&!0===e._cache.set){let{words:n,tags:r}=function(e){let t=[],n=[];return e.forEach((e=>{!0!==e.optional&&!0!==e.negative&&(void 0!==e.tag&&t.push(e.tag),void 0!==e.word&&n.push(e.word))})),{tags:t,words:n}}(t);for(let t=0;te.concat(t.match(a))),[]);return void 0!==r.group&&null!==r.group&&""!==r.group?this.buildFrom(i).groups(r.group):this.buildFrom(i)},e.not=function(e,r={}){let a=t(e,r);if(0===a.length||!1===n(this,a))return this;let i=this.list.reduce(((e,t)=>e.concat(t.not(a))),[]);return this.buildFrom(i)},e.matchOne=function(e,r={}){let a=t(e,r);if(!1===n(this,a))return this.buildFrom([]);for(let e=0;e!0===e.has(a)));return this.buildFrom(i)},e.ifNo=function(e,n={}){let r=t(e,n),a=this.list.filter((e=>!1===e.has(r)));return this.buildFrom(a)},e.has=function(e,r={}){let a=t(e,r);return!1!==n(this,a)&&this.list.some((e=>!0===e.has(a)))},e.lookAhead=function(e,n={}){e||(e=".*");let r=t(e,n),a=[];return this.list.forEach((e=>{a=a.concat(e.lookAhead(r))})),a=a.filter((e=>e)),this.buildFrom(a)},e.lookAfter=e.lookAhead,e.lookBehind=function(e,n={}){e||(e=".*");let r=t(e,n),a=[];return this.list.forEach((e=>{a=a.concat(e.lookBehind(r))})),a=a.filter((e=>e)),this.buildFrom(a)},e.lookBefore=e.lookBehind,e.before=function(e,n={}){let r=t(e,n),a=this.if(r).list.map((e=>{let t=e.terms().map((e=>e.id)),n=e.match(r)[0],a=t.indexOf(n.start);return 0===a||-1===a?null:e.buildFrom(e.start,a)}));return a=a.filter((e=>null!==e)),this.buildFrom(a)},e.after=function(e,n={}){let r=t(e,n),a=this.if(r).list.map((e=>{let t=e.terms(),n=t.map((e=>e.id)),a=e.match(r)[0],i=n.indexOf(a.start);if(-1===i||!t[i+a.length])return null;let s=t[i+a.length].id,o=e.length-i-a.length;return e.buildFrom(s,o)}));return a=a.filter((e=>null!==e)),this.buildFrom(a)},e.hasAfter=function(e,t={}){return this.filter((n=>n.lookAfter(e,t).found))},e.hasBefore=function(e,t={}){return this.filter((n=>n.lookBefore(e,t).found))}}(Zr);var Yr={};const ea=function(e,t,n,r){let a=[];"string"==typeof e&&(a=e.split(" ")),t.list.forEach((i=>{let s=i.terms();!0===n&&(s=s.filter((n=>n.canBe(e,t.world)))),s.forEach(((n,i)=>{a.length>1?a[i]&&"."!==a[i]&&n.tag(a[i],r,t.world):n.tag(e,r,t.world)}))}))};Yr.tag=function(e,t){return e?(ea(e,this,!1,t),this):this},Yr.tagSafe=function(e,t){return e?(ea(e,this,!0,t),this):this},Yr.unTag=function(e,t){return this.list.forEach((n=>{n.terms().forEach((n=>n.unTag(e,t,this.world)))})),this},Yr.canBe=function(e){if(!e)return this;let t=this.world,n=this.list.reduce(((n,r)=>n.concat(r.canBe(e,t))),[]);return this.buildFrom(n)};var ta={map:function(e){if(!e)return this;let t=this.list.map(((t,n)=>{let r=this.buildFrom([t]);r.from=null;let a=e(r,n);return a&&a.list&&a.list[0]?a.list[0]:a}));return t=t.filter((e=>e)),0===t.length?this.buildFrom(t):"object"!=typeof t[0]||"Phrase"!==t[0].isA?t:this.buildFrom(t)},forEach:function(e,t){return e?(this.list.forEach(((n,r)=>{let a=this.buildFrom([n]);!0===t&&(a.from=null),e(a,r)})),this):this},filter:function(e){if(!e)return this;let t=this.list.filter(((t,n)=>{let r=this.buildFrom([t]);return r.from=null,e(r,n)}));return this.buildFrom(t)},find:function(e){if(!e)return this;let t=this.list.find(((t,n)=>{let r=this.buildFrom([t]);return r.from=null,e(r,n)}));return t?this.buildFrom([t]):void 0},some:function(e){return e?this.list.some(((t,n)=>{let r=this.buildFrom([t]);return r.from=null,e(r,n)})):this},random:function(e){if(!this.found)return this;let t=Math.floor(Math.random()*this.list.length);if(void 0===e){let e=[this.list[t]];return this.buildFrom(e)}return t+e>this.length&&(t=this.length-e,t=t<0?0:t),this.slice(t,t+e)}},ra={},aa=function(e,t,n){let r=function(e,t=[]){let n={};return e.forEach(((e,r)=>{let a=!0;void 0!==t[r]&&(a=t[r]);let i=function(e){return e.split(/[ -]/g)}(e=(e=(e||"").toLowerCase()).replace(/[,;.!?]+$/,"")).map((e=>e.trim()));n[i[0]]=n[i[0]]||{},1===i.length?n[i[0]].value=a:(n[i[0]].more=n[i[0]].more||[],n[i[0]].more.push({rest:i.slice(1),value:a}))})),n}(e,t),a=[];for(let e=0;ee.reduced));for(let e=0;e{void 0!==i[e+n.rest.length]&&!0===n.rest.every(((t,n)=>t===i[e+n+1]))&&a.push({id:t.terms()[e].id,value:n.value,length:n.rest.length+1})})),void 0!==r[i[e]].value&&a.push({id:t.terms()[e].id,value:r[i[e]].value,length:1}))}return a};!function(e){const t=aa;e.lookup=function(e){let n=[],r=(a=e)&&"[object Object]"===Object.prototype.toString.call(a);var a;!0===r&&(e=Object.keys(e).map((t=>(n.push(e[t]),t)))),"string"==typeof e&&(e=[e]),!0!==this._cache.set&&this.cache();let i=t(e,n,this),s=this.list[0];if(!0===r){let e={};return i.forEach((t=>{e[t.value]=e[t.value]||[],e[t.value].push(s.buildFrom(t.id,t.length))})),Object.keys(e).forEach((t=>{e[t]=this.buildFrom(e[t])})),e}return i=i.map((e=>s.buildFrom(e.id,e.length))),this.buildFrom(i)},e.lookUp=e.lookup}(ra);var na={cache:function(e){e=e||{};let t={},n={};return this._cache.words=t,this._cache.tags=n,this._cache.set=!0,this.list.forEach(((r,a)=>{r.cache=r.cache||{},r.terms().forEach((r=>{t[r.reduced]&&!t.hasOwnProperty(r.reduced)||(t[r.reduced]=t[r.reduced]||[],t[r.reduced].push(a),Object.keys(r.tags).forEach((e=>{n[e]=n[e]||[],n[e].push(a)})),e.root&&(r.setRoot(this.world),t[r.root]=[a]))}))})),this},uncache:function(){return this._cache={},this.list.forEach((e=>{e.cache={}})),this.parents().forEach((e=>{e._cache={},e.list.forEach((e=>{e.cache={}}))})),this}},ia={};const oa=xt;ia.replaceWith=function(e,t={}){return e?(!0===t&&(t={keepTags:!0}),!1===t&&(t={keepTags:!1}),t=t||{},this.uncache(),this.list.forEach((n=>{let r,a=e;if("function"==typeof e&&(a=e(n)),a&&"object"==typeof a&&"Doc"===a.isA)r=a.list,this.pool().merge(a.pool());else{if("string"!=typeof a)return;{!1!==t.keepCase&&n.terms(0).isTitleCase()&&(a=(i=a).charAt(0).toUpperCase()+i.substr(1)),r=oa(a,this.world,this.pool());let e=this.buildFrom(r);e.tagger(),r=e.list}}var i;if(!0===t.keepTags){let e=n.json({terms:{tags:!0}}).terms;r[0].terms().forEach(((t,n)=>{e[n]&&t.tagSafe(e[n].tags,"keptTag",this.world)}))}n.replace(r[0],this)})),this):this.delete()},ia.replace=function(e,t,n){return void 0===t?this.replaceWith(e,n):(this.match(e).replaceWith(t,n),this)};var sa={};!function(e){const t=xt,n=function(e){return e&&"[object Object]"===Object.prototype.toString.call(e)},r=function(e,n){let r=t(e,n.world)[0],a=n.buildFrom([r]);return a.tagger(),n.list=a.list,n};e.append=function(e=""){return e?this.found?(this.uncache(),this.list.forEach((r=>{let a;n(e)&&"Doc"===e.isA?a=e.list[0].clone():"string"==typeof e&&(a=t(e,this.world,this.pool())[0]),this.buildFrom([a]).tagger(),r.append(a,this)})),this):r(e,this):this},e.insertAfter=e.append,e.insertAt=e.append,e.prepend=function(e){return e?this.found?(this.uncache(),this.list.forEach((r=>{let a;n(e)&&"Doc"===e.isA?a=e.list[0].clone():"string"==typeof e&&(a=t(e,this.world,this.pool())[0]),this.buildFrom([a]).tagger(),r.prepend(a,this)})),this):r(e,this):this},e.insertBefore=e.prepend,e.concat=function(){this.uncache();let e=this.list.slice(0);for(let n=0;ne.delete(this))),this},e.remove=e.delete}(sa);var la={};const ua={clean:!0,reduced:!0,root:!0};la.text=function(e){e=e||{};let t=!1;0===this.parents().length&&(t=!0),("root"===e||"object"==typeof e&&e.root)&&this.list.forEach((e=>{e.terms().forEach((e=>{null===e.root&&e.setRoot(this.world)}))}));let n=this.list.reduce(((n,r,a)=>{const i=!t&&0===a,s=!t&&a===this.list.length-1;return n+r.text(e,i,s)}),"");return!0!==ua[e]&&!0!==e.reduced&&!0!==e.clean&&!0!==e.root||(n=n.trim()),n};var ca={},ha=function(e,t,n){let r=function(e){let t=0,n=0,r={};return e.termList().forEach((e=>{r[e.id]={index:n,start:t+e.pre.length,length:e.text.length},t+=e.pre.length+e.text.length+e.post.length,n+=1})),r}(e.all());(n.terms.index||n.index)&&t.forEach((e=>{e.terms.forEach((e=>{e.index=r[e.id].index})),e.index=e.terms[0].index})),(n.terms.offset||n.offset)&&t.forEach((e=>{e.terms.forEach((e=>{e.offset=r[e.id]||{}})),e.offset={index:e.terms[0].offset.index,start:e.terms[0].offset.start-e.text.indexOf(e.terms[0].text),length:e.text.length}}))};!function(e){const t=ha,n={text:!0,terms:!0,trim:!0};e.json=function(e={}){if("number"==typeof e&&this.list[e])return this.list[e].json(n);!0===(e=function(e){return(e=Object.assign({},n,e)).unique&&(e.reduced=!0),e.offset&&(e.text=!0,e.terms&&!0!==e.terms||(e.terms={}),e.terms.offset=!0),(e.index||e.terms.index)&&(e.terms=!0===e.terms?{}:e.terms,e.terms.id=!0),e}(e)).root&&this.list.forEach((e=>{e.terms().forEach((e=>{null===e.root&&e.setRoot(this.world)}))}));let r=this.list.map((t=>t.json(e,this.world)));if((e.terms.offset||e.offset||e.terms.index||e.index)&&t(this,r,e),e.frequency||e.freq||e.count){let e={};this.list.forEach((t=>{let n=t.text("reduced");e[n]=e[n]||0,e[n]+=1})),this.list.forEach(((t,n)=>{r[n].count=e[t.text("reduced")]}))}if(e.unique){let e={};r=r.filter((t=>!0!==e[t.reduced]&&(e[t.reduced]=!0,!0)))}return r},e.data=e.json}(ca);var da={},ga={exports:{}};!function(e){const t="",n=function(e,t){for(e=e.toString();e.length{console.log('\n%c"'+e.text()+'"',"color: #e6d7b3;"),e.terms().forEach((e=>{let a=Object.keys(e.tags),i=e.text||"-";e.implicit&&(i="["+e.implicit+"]");let s="'"+i+"'";s=n(s,8);let o=a.find((e=>t[e]&&t[e].color)),l="steelblue";t[o]&&(l=t[o].color,l=r[l]),console.log(` ${s} - %c${a.join(", ")}`,`color: ${l||"steelblue"};`)}))}))}(e),e):(console.log(a.blue("=====")),e.list.forEach((t=>{console.log(a.blue(" -----")),t.terms().forEach((t=>{let r=Object.keys(t.tags),i=t.text||"-";t.implicit&&(i="["+t.implicit+"]"),i=a.yellow(i);let s="'"+i+"'";s=n(s,18);let o=a.blue(" | ")+s+" - "+function(e,t){return(e=e.map((e=>{if(!t.tags.hasOwnProperty(e))return e;const n=t.tags[e].color||"blue";return a[n](e)}))).join(", ")}(r,e.world);console.log(o)}))})),console.log(""),e)}}();const pa=ga.exports,ma=function(e){let t=e.json({text:!1,terms:!1,reduced:!0}),n={};t.forEach((e=>{n[e.reduced]||(e.count=0,n[e.reduced]=e),n[e.reduced].count+=1}));let r=Object.keys(n).map((e=>n[e]));return r.sort(((e,t)=>e.count>t.count?-1:e.counte.text)).filter((e=>e));if("freq"===e||"frequency"===e)return ma(this);if("terms"===e){let e=[];return this.json({text:!1,terms:{text:!0}}).forEach((t=>{let n=t.terms.map((e=>e.text));n=n.filter((e=>e)),e=e.concat(n)})),e}return"tags"===e?this.list.map((e=>e.terms().reduce(((e,t)=>(e[t.clean||t.implicit]=Object.keys(t.tags),e)),{}))):"debug"===e?(pa(this),this):this.text()};var fa={};const ba={alpha:(e,t)=>{let n=e.text("clean"),r=t.text("clean");return nr?1:0},length:(e,t)=>{let n=e.text().trim().length,r=t.text().trim().length;return nr?-1:0},wordCount:(e,t)=>{let n=e.wordCount(),r=t.wordCount();return nr?-1:0}};ba.alphabetical=ba.alpha,ba.wordcount=ba.wordCount;const ya={index:!0,sequence:!0,seq:!0,sequential:!0,chron:!0,chronological:!0};fa.sort=function(e){return"freq"===(e=e||"alpha")||"frequency"===e||"topk"===e?function(e){let t={};const n={case:!0,punctuation:!1,whitespace:!0,unicode:!0};return e.list.forEach((e=>{let r=e.text(n);t[r]=t[r]||0,t[r]+=1})),e.list.sort(((e,r)=>{let a=t[e.text(n)],i=t[r.text(n)];return ai?-1:0})),e}(this):ya.hasOwnProperty(e)?function(e){let t={};return e.json({terms:{offset:!0}}).forEach((e=>{t[e.terms[0].id]=e.terms[0].offset.start})),e.list=e.list.sort(((e,n)=>t[e.start]>t[n.start]?1:t[e.start]{let n=e.text("reduced").trim()||e.text("implicit").trim();return!0!==t.hasOwnProperty(n)&&(t[n]=!0,!0)})),this.buildFrom(e)};var va={};const wa=n$1,ka=/[\[\]{}⟨⟩:,،、‒–—―…‹›«»‐\-;\/⁄·*\•^†‡°¡¿※№÷׺ª%‰=‱¶§~|‖¦©℗®℠™¤₳฿]/g,Aa=/['‘’“”"′″‴]+/g,Da={whitespace:function(e){let t=e.list.map((e=>e.terms()));t.forEach(((e,n)=>{e.forEach(((r,a)=>{!0!==r.hasDash()?(r.pre=r.pre.replace(/\s/g,""),r.post=r.post.replace(/\s/g,""),(e.length-1!==a||t[n+1])&&(r.implicit&&!0===Boolean(r.text)||!0!==r.hasHyphen()&&(r.post+=" "))):r.post=" - "}))}))},punctuation:function(e){e.forEach((e=>{!0===e.hasHyphen()&&(e.post=" "),e.pre=e.pre.replace(ka,""),e.post=e.post.replace(ka,""),e.post=e.post.replace(/\.\.\./,""),!0===/!/.test(e.post)&&(e.post=e.post.replace(/!/g,""),e.post="!"+e.post),!0===/\?/.test(e.post)&&(e.post=e.post.replace(/[\?!]*/,""),e.post="?"+e.post)}))},unicode:function(e){e.forEach((e=>{!0!==e.isImplicit()&&(e.text=wa(e.text))}))},quotations:function(e){e.forEach((e=>{e.post=e.post.replace(Aa,""),e.pre=e.pre.replace(Aa,"")}))},adverbs:function(e){e.match("#Adverb").not("(not|nary|seldom|never|barely|almost|basically|so)").remove()},abbreviations:function(e){e.list.forEach((e=>{let t=e.terms();t.forEach(((e,n)=>{!0===e.tags.Abbreviation&&t[n+1]&&(e.post=e.post.replace(/^\./,""))}))}))}},$a={whitespace:!0,unicode:!0,punctuation:!0,emoji:!0,acronyms:!0,abbreviations:!0,case:!1,contractions:!1,parentheses:!1,quotations:!1,adverbs:!1,possessives:!1,verbs:!1,nouns:!1,honorifics:!1},Pa={light:{},medium:{case:!0,contractions:!0,parentheses:!0,quotations:!0,adverbs:!0}};Pa.heavy=Object.assign({},Pa.medium,{possessives:!0,verbs:!0,nouns:!0,honorifics:!0}),va.normalize=function(e){"string"==typeof(e=e||{})&&(e=Pa[e]||{}),e=Object.assign({},$a,e),this.uncache();let t=this.termList();return e.case&&this.toLowerCase(),e.whitespace&&Da.whitespace(this),e.unicode&&Da.unicode(t),e.punctuation&&Da.punctuation(t),e.emoji&&this.remove("(#Emoji|#Emoticon)"),e.acronyms&&this.acronyms().strip(),e.abbreviations&&Da.abbreviations(this),(e.contraction||e.contractions)&&this.contractions().expand(),e.parentheses&&this.parentheses().unwrap(),(e.quotations||e.quotes)&&Da.quotations(t),e.adverbs&&Da.adverbs(this),(e.possessive||e.possessives)&&this.possessives().strip(),e.verbs&&this.verbs().toInfinitive(),(e.nouns||e.plurals)&&this.nouns().toSingular(),e.honorifics&&this.remove("#Honorific"),this};var Ea={};!function(e){const t=_e;e.splitOn=function(e){if(!e)return this.parent().splitOn(this);let n=t(e),r=[];return this.list.forEach((e=>{let t=e.match(n);if(0===t.length)return void r.push(e);let a=e;t.forEach((e=>{let t=a.splitOn(e);t.before&&r.push(t.before),t.match&&r.push(t.match),a=t.after})),a&&r.push(a)})),this.buildFrom(r)},e.splitAfter=function(e){if(!e)return this.parent().splitAfter(this);let n=t(e),r=[];return this.list.forEach((e=>{let t=e.match(n);if(0===t.length)return void r.push(e);let a=e;t.forEach((e=>{let t=a.splitOn(e);t.before&&t.match?(t.before.length+=t.match.length,r.push(t.before)):t.match&&r.push(t.match),a=t.after})),a&&r.push(a)})),this.buildFrom(r)},e.split=e.splitAfter,e.splitBefore=function(e){if(!e)return this.parent().splitBefore(this);let n=t(e),r=[];return this.list.forEach((e=>{let t=e.match(n);if(0===t.length)return void r.push(e);let a=e;t.forEach((e=>{let t=a.splitOn(e);t.before&&r.push(t.before),t.match&&t.after&&(t.match.length+=t.after.length),a=t.match})),a&&r.push(a)})),this.buildFrom(r)},e.segment=function(e,t){e=e||{},t=t||{text:!0};let n=this,r=Object.keys(e);return r.forEach((e=>{n=n.splitOn(e)})),n.list.forEach((t=>{for(let n=0;n{let n=e.json(t);return n.segment=e.segment||null,n}))}}(Ea);var Ha={};const ja=function(e,t){let n=e.world;return e.list.forEach((e=>{e.terms().forEach((e=>e[t](n)))})),e};Ha.toLowerCase=function(){return ja(this,"toLowerCase")},Ha.toUpperCase=function(){return ja(this,"toUpperCase")},Ha.toTitleCase=function(){return ja(this,"toTitleCase")},Ha.toCamelCase=function(){return this.list.forEach((e=>{let t=e.terms();t.forEach(((e,n)=>{0!==n&&e.toTitleCase(),n!==t.length-1&&(e.post="")}))})),this};var Na={};!function(e){e.pre=function(e,t){return void 0===e?this.list[0].terms(0).pre:(this.list.forEach((n=>{let r=n.terms(0);!0===t?r.pre+=e:r.pre=e})),this)},e.post=function(e,t){return void 0===e?this.list.map((e=>{let t=e.terms();return t[t.length-1].post})):(this.list.forEach((n=>{let r=n.terms(),a=r[r.length-1];!0===t?a.post+=e:a.post=e})),this)},e.trim=function(){return this.list=this.list.map((e=>e.trim())),this},e.hyphenate=function(){return this.list.forEach((e=>{let t=e.terms();t.forEach(((e,n)=>{0!==n&&(e.pre=""),t[n+1]&&(e.post="-")}))})),this},e.dehyphenate=function(){const e=/(-|–|—)/;return this.list.forEach((t=>{t.terms().forEach((t=>{e.test(t.post)&&(t.post=" ")}))})),this},e.deHyphenate=e.dehyphenate,e.toQuotations=function(e,t){return e=e||'"',t=t||'"',this.list.forEach((n=>{let r=n.terms();r[0].pre=e+r[0].pre;let a=r[r.length-1];a.post=t+a.post})),this},e.toQuotation=e.toQuotations,e.toParentheses=function(e,t){return e=e||"(",t=t||")",this.list.forEach((n=>{let r=n.terms();r[0].pre=e+r[0].pre;let a=r[r.length-1];a.post=t+a.post})),this}}(Na);var xa={join:function(e){this.uncache();let t=this.list[0],n=t.length,r={};for(let n=1;n{e.list.forEach((e=>{let n=e.terms();for(let r=0;r!0!==r[e.start]))})),this.buildFrom([t])}},Fa={};const Ca=/[,\)"';:\-–—\.…]/,Ba=function(e,t){if(!e.found)return;let n=e.termList();for(let e=0;e{e.implicit=e.clean})),n[0].text+=t,n.slice(1).forEach((e=>{e.text=""}));for(let e=0;e{za[e[0]]=function(t){let n=this.match(e[1]);return"number"==typeof t&&(n=n.get(t)),n}})),za.emojis=za.emoji,za.atmentions=za.atMentions,za.words=za.terms,za.phoneNumbers=function(e){let t=this.splitAfter("@hasComma");return t=t.match("#PhoneNumber+"),"number"==typeof e&&(t=t.get(e)),t},za.money=function(e){let t=this.match("#Money #Currency?");return"number"==typeof e&&(t=t.get(e)),t},za.places=function(e){let t=this.match("(#City && @hasComma) (#Region|#Country)"),n=this.not(t).splitAfter("@hasComma");return n=n.concat(t),n.sort("index"),n=n.match("#Place+"),"number"==typeof e&&(n=n.get(e)),n},za.organizations=function(e){let t=this.clauses();return t=t.match("#Organization+"),"number"==typeof e&&(t=t.get(e)),t},za.entities=function(e){let t=this.clauses(),n=t.people();return n=n.concat(t.places()),n=n.concat(t.organizations()),n=n.not(["someone","man","woman","mother","brother","sister","father"]),n.sort("sequence"),"number"==typeof e&&(n=n.get(e)),n},za.things=za.entities,za.topics=za.entities;var Ia=za;const Oa=/^(under|over)-?.{3}/,Ta=function(e,t,n){let r=n.words,a=e[t].reduced+" "+e[t+1].reduced;return void 0!==r[a]&&!0===r.hasOwnProperty(a)?(e[t].tag(r[a],"lexicon-two",n),e[t+1].tag(r[a],"lexicon-two",n),1):t+20){a+=n;continue}}if(void 0===n[i]||!0!==n.hasOwnProperty(i))if(i===e[a].reduced||!0!==n.hasOwnProperty(e[a].reduced)){if(!0===Oa.test(i)){let r=i.replace(/^(under|over)-?/,"");!0===n.hasOwnProperty(r)&&e[a].tag(n[r],"noprefix-lexicon",t)}}else e[a].tag(n[e[a].reduced],"lexicon",t);else e[a].tag(n[i],"lexicon",t)}return e};const Ma=/[\'‘’‛‵′`´]$/,Ja=/^(m|k|cm|km|m)\/(s|h|hr)$/,La=[[/^[\w\.]+@[\w\.]+\.[a-z]{2,3}$/,"Email"],[/^#[a-z0-9_\u00C0-\u00FF]{2,}$/,"HashTag"],[/^@1?[0-9](am|pm)$/i,"Time"],[/^@1?[0-9]:[0-9]{2}(am|pm)?$/i,"Time"],[/^@\w{2,}$/,"AtMention"],[/^(https?:\/\/|www\.)+\w+\.[a-z]{2,3}/,"Url"],[/^[a-z0-9./].+\.(com|net|gov|org|ly|edu|info|biz|dev|ru|jp|de|in|uk|br|io|ai)/,"Url"],[/^'[0-9]{2}$/,"Year"],[/^[012]?[0-9](:[0-5][0-9])(:[0-5][0-9])$/,"Time"],[/^[012]?[0-9](:[0-5][0-9])?(:[0-5][0-9])? ?(am|pm)$/i,"Time"],[/^[012]?[0-9](:[0-5][0-9])(:[0-5][0-9])? ?(am|pm)?$/i,"Time"],[/^[PMCE]ST$/,"Time"],[/^utc ?[+-]?[0-9]+?$/,"Time"],[/^[a-z0-9]*? o\'?clock$/,"Time"],[/^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}/i,"Date"],[/^[0-9]{1,4}-[0-9]{1,2}-[0-9]{1,4}$/,"Date"],[/^[0-9]{1,4}\/[0-9]{1,2}\/[0-9]{1,4}$/,"Date"],[/^[0-9]{1,4}-[a-z]{2,9}-[0-9]{1,4}$/i,"Date"],[/^gmt[+-][0-9][0-9]?$/i,"Timezone"],[/^utc[+-][0-9][0-9]?$/i,"Timezone"],[/^ma?c\'.*/,"LastName"],[/^o\'[drlkn].*/,"LastName"],[/^ma?cd[aeiou]/,"LastName"],[/^(lol)+[sz]$/,"Expression"],[/^woo+a*?h?$/,"Expression"],[/^(un|de|re)\\-[a-z\u00C0-\u00FF]{2}/,"Verb"],[/^[0-9]{1,4}\.[0-9]{1,2}\.[0-9]{1,4}$/,"Date"],[/^[0-9]{3}-[0-9]{4}$/,"PhoneNumber"],[/^(\+?[0-9][ -])?[0-9]{3}[ -]?[0-9]{3}-[0-9]{4}$/,"PhoneNumber"],[/^[-+]?[\$\xA2-\xA5\u058F\u060B\u09F2\u09F3\u09FB\u0AF1\u0BF9\u0E3F\u17DB\u20A0-\u20BD\uA838\uFDFC\uFE69\uFF04\uFFE0\uFFE1\uFFE5\uFFE6][-+]?[0-9]+(,[0-9]{3})*(\.[0-9]+)?(k|m|b|bn)?\+?$/,["Money","Value"]],[/^[-+]?[0-9]+(,[0-9]{3})*(\.[0-9]+)?[\$\xA2-\xA5\u058F\u060B\u09F2\u09F3\u09FB\u0AF1\u0BF9\u0E3F\u17DB\u20A0-\u20BD\uA838\uFDFC\uFE69\uFF04\uFFE0\uFFE1\uFFE5\uFFE6]\+?$/,["Money","Value"]],[/^[-+]?[\$£]?[0-9]([0-9,.])+?(usd|eur|jpy|gbp|cad|aud|chf|cny|hkd|nzd|kr|rub)$/i,["Money","Value"]],[/^[-+]?[0-9]+(,[0-9]{3})*(\.[0-9]+)?\+?$/,["Cardinal","NumericValue"]],[/^[-+]?[0-9]+(,[0-9]{3})*(\.[0-9]+)?(st|nd|rd|r?th)$/,["Ordinal","NumericValue"]],[/^\.[0-9]+\+?$/,["Cardinal","NumericValue"]],[/^[-+]?[0-9]+(,[0-9]{3})*(\.[0-9]+)?%\+?$/,["Percent","Cardinal","NumericValue"]],[/^\.[0-9]+%$/,["Percent","Cardinal","NumericValue"]],[/^[0-9]{1,4}\/[0-9]{1,4}(st|nd|rd|th)?s?$/,["Fraction","NumericValue"]],[/^[0-9.]{1,3}[a-z]{0,2}[-–—][0-9]{1,3}[a-z]{0,2}$/,["Value","NumberRange"]],[/^[0-9][0-9]?(:[0-9][0-9])?(am|pm)? ?[-–—] ?[0-9][0-9]?(:[0-9][0-9])?(am|pm)?$/,["Time","NumberRange"]],[/^[0-9.]+([a-z]{1,4})$/,"Value"]],Sa=/^[IVXLCDM]{2,}$/,_a=/^M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$/,Ka="Adjective",qa="Infinitive",Wa="PresentTense",Ra="Singular",Ua="PastTense",Qa="Expression",Za="Adjective",Xa="Infinitive",Ya="PresentTense",en="Singular",tn="PastTense",rn="Adverb",an="Plural",nn="Verb",on="LastName",sn={a:[[/.[aeiou]na$/,"Noun"],[/.[oau][wvl]ska$/,"LastName"],[/.[^aeiou]ica$/,Ra],[/^([hyj]a)+$/,Qa]],c:[[/.[^aeiou]ic$/,Ka]],d:[[/[aeiou](pp|ll|ss|ff|gg|tt|rr|bb|nn|mm)ed$/,Ua],[/.[aeo]{2}[bdgmnprvz]ed$/,Ua],[/.[aeiou][sg]hed$/,Ua],[/.[aeiou]red$/,Ua],[/.[aeiou]r?ried$/,Ua],[/.[bcdgtr]led$/,Ua],[/.[aoui]f?led$/,Ua],[/.[iao]sed$/,Ua],[/[aeiou]n?[cs]ed$/,Ua],[/[aeiou][rl]?[mnf]ed$/,Ua],[/[aeiou][ns]?c?ked$/,Ua],[/[aeiou][nl]?ged$/,Ua],[/.[tdbwxz]ed$/,Ua],[/[^aeiou][aeiou][tvx]ed$/,Ua],[/.[cdlmnprstv]ied$/,Ua],[/[^aeiou]ard$/,Ra],[/[aeiou][^aeiou]id$/,Ka],[/.[vrl]id$/,Ka]],e:[[/.[lnr]ize$/,qa],[/.[^aeiou]ise$/,qa],[/.[aeiou]te$/,qa],[/.[^aeiou][ai]ble$/,Ka],[/.[^aeiou]eable$/,Ka],[/.[ts]ive$/,Ka],[/[a-z]-like$/,Ka]],h:[[/.[^aeiouf]ish$/,Ka],[/.v[iy]ch$/,"LastName"],[/^ug?h+$/,Qa],[/^uh[ -]?oh$/,Qa],[/[a-z]-ish$/,Ka]],i:[[/.[oau][wvl]ski$/,"LastName"]],k:[[/^(k){2}$/,Qa]],l:[[/.[gl]ial$/,Ka],[/.[^aeiou]ful$/,Ka],[/.[nrtumcd]al$/,Ka],[/.[^aeiou][ei]al$/,Ka]],m:[[/.[^aeiou]ium$/,Ra],[/[^aeiou]ism$/,Ra],[/^h*u*m+$/,Qa],[/^\d+ ?[ap]m$/,"Date"]],n:[[/.[lsrnpb]ian$/,Ka],[/[^aeiou]ician$/,"Actor"],[/[aeiou][ktrp]in$/,"Gerund"]],o:[[/^no+$/,Qa],[/^(yo)+$/,Qa],[/^woo+[pt]?$/,Qa]],r:[[/.[bdfklmst]ler$/,"Noun"],[/[aeiou][pns]er$/,Ra],[/[^i]fer$/,qa],[/.[^aeiou][ao]pher$/,"Actor"],[/.[lk]er$/,"Noun"],[/.ier$/,"Comparative"]],t:[[/.[di]est$/,"Superlative"],[/.[icldtgrv]ent$/,Ka],[/[aeiou].*ist$/,Ka],[/^[a-z]et$/,"Verb"]],s:[[/.[^aeiou]ises$/,Wa],[/.[rln]ates$/,Wa],[/.[^z]ens$/,"Verb"],[/.[lstrn]us$/,Ra],[/.[aeiou]sks$/,Wa],[/.[aeiou]kes$/,Wa],[/[aeiou][^aeiou]is$/,Ra],[/[a-z]\'s$/,"Noun"],[/^yes+$/,Qa]],v:[[/.[^aeiou][ai][kln]ov$/,"LastName"]],y:[[/.[cts]hy$/,Ka],[/.[st]ty$/,Ka],[/.[gk]y$/,Ka],[/.[tnl]ary$/,Ka],[/.[oe]ry$/,Ra],[/[rdntkbhs]ly$/,"Adverb"],[/...lly$/,"Adverb"],[/[bszmp]{2}y$/,Ka],[/.(gg|bb|zz)ly$/,Ka],[/.[ai]my$/,Ka],[/[ea]{2}zy$/,Ka],[/.[^aeiou]ity$/,Ra]]},ln=[null,null,{ea:en,ia:"Noun",ic:Za,ly:rn,"'n":nn,"'t":nn},{oed:tn,ued:tn,xed:tn," so":rn,"'ll":"Modal","'re":"Copula",azy:Za,eer:"Noun",end:nn,ped:tn,ffy:Za,ify:Xa,ing:"Gerund",ize:Xa,lar:Za,mum:Za,nes:Ya,nny:Za,oid:Za,ous:Za,que:Za,rol:en,sis:en,zes:Ya},{amed:tn,aped:tn,ched:tn,lked:tn,nded:tn,cted:tn,dged:tn,akis:on,cede:Xa,chuk:on,czyk:on,ects:Ya,ends:nn,enko:on,ette:en,fies:Ya,fore:rn,gate:Xa,gone:Za,ices:an,ints:an,ines:an,ions:an,less:rn,llen:Za,made:Za,nsen:on,oses:Ya,ould:"Modal",some:Za,sson:on,tage:Xa,teen:"Value",tion:en,tive:Za,tors:"Noun",vice:en},{tized:tn,urned:tn,eased:tn,ances:an,bound:Za,ettes:an,fully:rn,ishes:Ya,ities:an,marek:on,nssen:on,ology:"Noun",ports:an,rough:Za,tches:Ya,tieth:"Ordinal",tures:an,wards:rn,where:rn},{auskas:on,keeper:"Actor",logist:"Actor",teenth:"Value"},{opoulos:on,borough:"Place",sdottir:on}],un=/^(\u00a9|\u00ae|[\u2319-\u3300]|\ud83c[\ud000-\udfff]|\ud83d[\ud000-\udfff]|\ud83e[\ud000-\udfff])/,cn={":(":!0,":)":!0,":P":!0,":p":!0,":O":!0,":3":!0,":|":!0,":/":!0,":\\":!0,":$":!0,":*":!0,":@":!0,":-(":!0,":-)":!0,":-P":!0,":-p":!0,":-O":!0,":-3":!0,":-|":!0,":-/":!0,":-\\":!0,":-$":!0,":-*":!0,":-@":!0,":^(":!0,":^)":!0,":^P":!0,":^p":!0,":^O":!0,":^3":!0,":^|":!0,":^/":!0,":^\\":!0,":^$":!0,":^*":!0,":^@":!0,"):":!0,"(:":!0,"$:":!0,"*:":!0,")-:":!0,"(-:":!0,"$-:":!0,"*-:":!0,")^:":!0,"(^:":!0,"$^:":!0,"*^:":!0,"<3":!0,"2){let e=r.clean[r.clean.length-2];if("s"===e)return void r.tag(["Possessive","Noun"],"end-tick",n);"n"===e&&r.tag(["Gerund"],"chillin",n)}Ja.test(r.text)&&r.tag("Unit","per-sec",n)},regex:function(e,t){let n=e.text;for(let r=0;r=2&&Sa.test(n)&&_a.test(n)&&e.tag("RomanNumeral","xvii",t)},suffix:function(e,t){!function(e,t){const n=e.clean.length;let r=7;n<=r&&(r=n-1);for(let a=r;a>1;a-=1){let r=e.clean.substr(n-a,n);if(!0===ln[r.length].hasOwnProperty(r)){let n=ln[r.length][r];e.tagSafe(n,"suffix -"+r,t);break}}}(e,t),function(e,t){let n=e.clean,r=n[n.length-1];if(!0===sn.hasOwnProperty(r)){let a=sn[r];for(let i=0;i{let n=e.pre+e.text+e.post;var r;n=n.trim(),n=n.replace(/[.!?,]$/,""),!0===(e=>!(":"!==e.charAt(0)||null===e.match(/:.?$/)||e.match(" ")||e.length>35))(n)&&(e.tag("Emoji","comma-emoji",t),e.text=n,e.pre=e.pre.replace(":",""),e.post=e.post.replace(":","")),e.text.match(un)&&(e.tag("Emoji","unicode-emoji",t),e.text=n),!0===(r=(r=n).replace(/^[:;]/,":"),cn.hasOwnProperty(r))&&(e.tag("Emoticon","emoticon-emoji",t),e.text=n)}};var dn=function(e,t){let n=e.world;hn.lexicon(t,n);for(let e=0;ea.tags[e]));if(void 0!==e){let n=gn.afterThisPos[e];r.tag(n,"after-"+e,t);continue}}let i=e[n+1];if(i){if(!0===gn.beforeThisWord.hasOwnProperty(i.clean)){let e=gn.beforeThisWord[i.clean];r.tag(e,"before-"+i.clean,t);continue}let e=mn.find((e=>i.tags[e]));if(void 0!==e){let n=gn.beforeThisPos[e];r.tag(n,"before-"+e,t);continue}}}};const bn=/^[A-Z][a-z'\u00C0-\u00FF]/,yn=/[0-9]/;var vn=function(e){let t=e.world;e.list.forEach((e=>{let n=e.terms();for(let e=1;e{if(!0!==e.isKnown()&&!0===wn.test(e.clean)){let r=e.clean.replace(kn,"");r&&r.length>3&&void 0!==n[r]&&!0===n.hasOwnProperty(r)&&e.tag(n[r],"stem-"+r,t)}}))};const Dn=["Uncountable","Pronoun","Place","Value","Person","Month","WeekDay","Holiday"],$n={isSingular:[/(ax|test)is$/i,/(octop|vir|radi|nucle|fung|cact|stimul)us$/i,/(octop|vir)i$/i,/(rl)f$/i,/(alias|status)$/i,/(bu)s$/i,/(al|ad|at|er|et|ed|ad)o$/i,/(ti)um$/i,/(ti)a$/i,/sis$/i,/(?:(^f)fe|(lr)f)$/i,/hive$/i,/s[aeiou]+ns$/i,/(^aeiouy|qu)y$/i,/(x|ch|ss|sh|z)$/i,/(matr|vert|ind|cort)(ix|ex)$/i,/(m|l)ouse$/i,/(m|l)ice$/i,/(antenn|formul|nebul|vertebr|vit)a$/i,/.sis$/i,/^(?!talis|.*hu)(.*)man$/i],isPlural:[/(^v)ies$/i,/ises$/i,/ives$/i,/(antenn|formul|nebul|vertebr|vit)ae$/i,/(octop|vir|radi|nucle|fung|cact|stimul)i$/i,/(buffal|tomat|tornad)oes$/i,/(analy|ba|diagno|parenthe|progno|synop|the)ses$/i,/(vert|ind|cort)ices$/i,/(matr|append)ices$/i,/(x|ch|ss|sh|s|z|o)es$/i,/is$/i,/men$/i,/news$/i,/.tia$/i,/(^f)ves$/i,/(lr)ves$/i,/(^aeiouy|qu)ies$/i,/(m|l)ice$/i,/(cris|ax|test)es$/i,/(alias|status)es$/i,/ics$/i]},Pn=[/ss$/,/sis$/,/[^aeiou][uo]s$/,/'s$/],En=[/i$/,/ae$/];var Hn=function(e,t){if(e.tags.Noun&&!e.tags.Acronym){let n=e.clean;if(e.tags.Singular||e.tags.Plural)return;if(n.length<=3)return void e.tag("Singular","short-singular",t);if(Dn.find((t=>e.tags[t])))return;if($n.isPlural.find((e=>e.test(n))))return void e.tag("Plural","plural-rules",t);if($n.isSingular.find((e=>e.test(n))))return void e.tag("Singular","singular-rules",t);if(!0===/s$/.test(n)){if(Pn.find((e=>e.test(n))))return;return void e.tag("Plural","plural-fallback",t)}if(En.find((e=>e.test(n))))return;e.tag("Singular","singular-fallback",t)}};let jn=["academy","administration","agence","agences","agencies","agency","airlines","airways","army","assoc","associates","association","assurance","authority","autorite","aviation","bank","banque","board","boys","brands","brewery","brotherhood","brothers","building society","bureau","cafe","caisse","capital","care","cathedral","center","central bank","centre","chemicals","choir","chronicle","church","circus","clinic","clinique","club","co","coalition","coffee","collective","college","commission","committee","communications","community","company","comprehensive","computers","confederation","conference","conseil","consulting","containers","corporation","corps","corp","council","crew","daily news","data","departement","department","department store","departments","design","development","directorate","division","drilling","education","eglise","electric","electricity","energy","ensemble","enterprise","enterprises","entertainment","estate","etat","evening news","faculty","federation","financial","fm","foundation","fund","gas","gazette","girls","government","group","guild","health authority","herald","holdings","hospital","hotel","hotels","inc","industries","institut","institute","institute of technology","institutes","insurance","international","interstate","investment","investments","investors","journal","laboratory","labs","liberation army","limited","local authority","local health authority","machines","magazine","management","marine","marketing","markets","media","memorial","mercantile exchange","ministere","ministry","military","mobile","motor","motors","musee","museum","news","news service","observatory","office","oil","optical","orchestra","organization","partners","partnership","people's party","petrol","petroleum","pharmacare","pharmaceutical","pharmaceuticals","pizza","plc","police","polytechnic","post","power","press","productions","quartet","radio","regional authority","regional health authority","reserve","resources","restaurant","restaurants","savings","school","securities","service","services","social club","societe","society","sons","standard","state police","state university","stock exchange","subcommittee","syndicat","systems","telecommunications","telegraph","television","times","tribunal","tv","union","university","utilities","workers"].reduce((function(e,t){return e[t]="Noun",e}),{});const Nn=function(e){return!(!e.tags.Noun||e.tags.Pronoun||e.tags.Comma||e.tags.Possessive||!(e.tags.Organization||e.tags.Acronym||e.tags.Place||e.titleCase()))},xn=/^[A-Z]('s|,)?$/,Fn=/([A-Z]\.){2}[A-Z]?/i,Cn={I:!0,A:!0},Bn={neighbours:fn,case:vn,stem:An,plural:Hn,organizations:function(e,t){for(let n=0;n{!0!==e.tags.RomanNumeral&&(!0===Fn.test(e.text)&&e.tag("Acronym","period-acronym",t),e.isUpperCase()&&function(e,t){let n=e.reduced;return!!e.tags.Acronym||!t.words[n]&&!(n.length>5)&&e.isAcronym()}(e,t)?(e.tag("Acronym","acronym-step",t),e.tag("Noun","acronym-infer",t)):!Cn.hasOwnProperty(e.text)&&xn.test(e.text)&&(e.tag("Acronym","one-letter-acronym",t),e.tag("Noun","one-letter-infer",t)),e.tags.Organization&&e.text.length<=3&&e.tag("Acronym","acronym-org",t),e.tags.Organization&&e.isUpperCase()&&e.text.length<=6&&e.tag("Acronym","acronym-org-case",t))}))}};var Gn=function(e,t){let n=e.world;return Bn.neighbours(t,n),Bn.case(e),Bn.stem(t,n),t.forEach((t=>{!1===t.isKnown()&&t.tag("Noun","noun-fallback",e.world)})),Bn.organizations(t,n),Bn.acronyms(t,n),t.forEach((t=>{Bn.plural(t,e.world)})),e};const zn=/n't$/,In={"won't":["will","not"],wont:["will","not"],"can't":["can","not"],cant:["can","not"],cannot:["can","not"],"shan't":["should","not"],dont:["do","not"],dun:["do","not"]},On=/([a-z\u00C0-\u00FF]+)[\u0027\u0060\u00B4\u2018\u2019\u201A\u201B\u2032\u2035\u2039\u203A]([a-z]{1,2})$/i,Tn={ll:"will",ve:"have",re:"are",m:"am","n't":"not"},Vn={wanna:["want","to"],gonna:["going","to"],im:["i","am"],alot:["a","lot"],ive:["i","have"],imma:["I","will"],"where'd":["where","did"],whered:["where","did"],"when'd":["when","did"],whend:["when","did"],howd:["how","did"],whatd:["what","did"],dunno:["do","not","know"],brb:["be","right","back"],gtg:["got","to","go"],irl:["in","real","life"],tbh:["to","be","honest"],imo:["in","my","opinion"],til:["today","i","learned"],rn:["right","now"],twas:["it","was"],"@":["at"]},Mn=/([a-z\u00C0-\u00FF]+)[\u0027\u0060\u00B4\u2018\u2019\u201A\u201B\u2032\u2035\u2039\u203A]s$/i,Jn={that:!0,there:!0},Ln={here:!0,there:!0,everywhere:!0},Sn=/[a-z\u00C0-\u00FF]'d$/,_n={how:!0,what:!0},Kn=/^([0-9.]{1,3}[a-z]{0,2}) ?[-–—] ?([0-9]{1,3}[a-z]{0,2})$/i,qn=/^([0-9][0-9]?(:[0-9][0-9])?(am|pm)?) ?[-–—] ?([0-9][0-9]?(:[0-9][0-9])?(am|pm)?)$/i,Wn=/^(l|c|d|j|m|n|qu|s|t)[\u0027\u0060\u00B4\u2018\u2019\u201A\u201B\u2032\u2035\u2039\u203A]([a-z\u00C0-\u00FF]+)$/i,Rn={l:"le",c:"ce",d:"de",j:"je",m:"me",n:"ne",qu:"que",s:"se",t:"tu"},Un=Va,Qn=xt,Zn=function(e,t){return!0===In.hasOwnProperty(e.clean)?In[e.clean]:"ain't"===e.clean||"aint"===e.clean?function(e,t){let n=t.terms(),r=n.indexOf(e),a=n.slice(0,r).find((e=>e.tags.Noun));return a&&a.tags.Plural?["are","not"]:["is","not"]}(e,t):!0===zn.test(e.clean)?[e.clean.replace(zn,""),"not"]:null},Xn=function(e){let t=e.text.match(On);return null===t?null:Tn.hasOwnProperty(t[2])?[t[1],Tn[t[2]]]:null},Yn=function(e){return Vn.hasOwnProperty(e.clean)?Vn[e.clean]:null},ei=function(e,t,n){let r=e.text.match(Mn);if(null!==r){if(!0===((e,t)=>{if(e.tags.Possessive)return!0;if(e.tags.Pronoun||e.tags.QuestionWord)return!1;if(Jn.hasOwnProperty(e.reduced))return!1;let n=t.get(e.next);if(!n)return!0;if(n.tags.Verb)return!!n.tags.Infinitive||!!n.tags.PresentTense;if(n.tags.Noun)return!0!==Ln.hasOwnProperty(n.reduced);let r=t.get(n.next);return!(!r||!r.tags.Noun||r.tags.Pronoun)||(n.tags.Adjective||n.tags.Adverb||n.tags.Verb,!1)})(e,t.pool))return e.tag("#Possessive","isPossessive",n),null;if(null!==r)return((e,t)=>{let n=t.terms(),r=n.indexOf(e);return n.slice(r+1,r+3).find((e=>e.tags.PastTense))})(e,t)?[r[1],"has"]:[r[1],"is"]}return null},ti=function(e,t){if(Sn.test(e.clean)){let n=e.clean.replace(/'d$/,""),r=t.terms(),a=r.indexOf(e),i=r.slice(a+1,a+4);for(let e=0;e{e.implicit=e.text,e.text="",e.clean="",e.pre="",e.post="",0===Object.keys(e.tags).length&&(e.tags.Noun=!0)})),n};var li=function(e){let t=e.world;return e.list.forEach((n=>{let r=n.terms();for(let a=0;ae.list[t])),e.buildFrom(n)};var ci=function(e){let t=ui(e,"Infinitive");return t.found&&(t=t.ifNo("@hasQuestionMark"),t=t.ifNo("(i|we|they)"),t.not("will be").match("[#Infinitive] (#Determiner|#Possessive) #Noun").notIf("(our|their)").match("#Infinitive").tag("Imperative","shut-the"),t.match("^[#Infinitive] #Adverb?$",0).tag("Imperative","go-fast"),t.match("[(do && #Infinitive)] not? #Verb",0).tag("Imperative","do-not"),t.match("[#Infinitive] (it|some) (#Comparative|#Preposition|please|now|again)",0).tag("Imperative","do-it")),t=function(e,t){let n=e._cache.words.like||[];return n=n.map((t=>e.list[t])),e.buildFrom(n)}(e),t.match("#Adverb like").notIf("(really|generally|typically|usually|sometimes|often|just) [like]").tag("Adverb","adverb-like"),t=ui(e,"Adjective"),t.match("#Determiner #Adjective$").notIf("(#Comparative|#Superlative)").terms(1).tag("Noun","the-adj-1"),t=ui(e,"FirstName"),t.match("#FirstName (#Noun|@titleCase)").ifNo("^#Possessive").ifNo("(#Pronoun|#Plural)").ifNo("@hasComma .").lastTerm().tag("#LastName","firstname-noun"),t=ui(e,"Value"),t=t.match("#Value #PresentTense").ifNo("#Copula"),t.found&&(!0===t.has("(one|1)")?t.terms(1).tag("Singular","one-presentTense"):t.terms(1).tag("Plural","value-presentTense")),e.match("^(well|so|okay)").tag("Expression","well-"),e.match("#Value [of a second]",0).unTag("Value","of-a-second"),e.match("#Value [seconds]",0).unTag("Value","30-seconds").tag(["Unit","Plural"]),t=ui(e,"Gerund"),t.match("(be|been) (#Adverb|not)+? #Gerund").not("#Verb$").tag("Auxiliary","be-walking"),e.match("(try|use|attempt|build|make) #Verb").ifNo("(@hasComma|#Negative|#PhrasalVerb|#Copula|will|be)").lastTerm().tag("#Noun","do-verb"),t=ui(e,"Possessive"),t=t.match("#Possessive [#Infinitive]",0),t.lookBehind("(let|made|make|force|ask)").found||t.tag("Noun","her-match"),e},hi=function(e){let t={};for(let n=0;n{e.reg=ji(e.match);let t=function(e){let t=[];if(1===e.reg.filter((e=>void 0!==e.fastOr)).length){let n=e.reg.findIndex((e=>void 0!==e.fastOr));Object.keys(e.reg[n].fastOr).forEach((r=>{let a=Object.assign({},e);a.reg=a.reg.slice(0),a.reg[n]=Object.assign({},a.reg[n]),a.reg[n].word=r,delete a.reg[n].operator,delete a.reg[n].fastOr,t.push(a)}))}return t}(e);t.length>0?Fi=Fi.concat(t):Fi.push(e)})),Fi.forEach((e=>(e.required=function(e){let t=[],n=[];return e.forEach((e=>{!0!==e.optional&&!0!==e.negative&&(void 0!==e.tag&&t.push(e.tag),void 0!==e.word&&n.push(e.word))})),{tags:Ni(t),words:Ni(n)}}(e.reg),e)));const Ci=Fi,Bi=hi,Gi=ci,zi=function(e){Ci.forEach((t=>{let n=[];t.required.words.forEach((t=>{n.push(e._cache.words[t]||[])})),t.required.tags.forEach((t=>{n.push(e._cache.tags[t]||[])}));let r=function(e){if(0===e.length)return[];let t={};e.forEach((e=>{e=Bi(e);for(let n=0;nt[n]===e.length)),n=n.map((e=>Number(e))),n}(n);if(0===r.length)return;let a=r.map((t=>e.list[t])),i=e.buildFrom(a).match(t.reg,t.group);i.found&&(!0===t.safe?i.tagSafe(t.tag,t.reason):i.tag(t.tag,t.reason))}))},Ii=dn,Oi=Gn,Ti=li,Vi=function(e){return zi(e),Gi(e),e};var Mi=function(e){let t=e.termList();return e=Ii(e,t),e=Oi(e,t),(e=Ti(e)).cache(),(e=Vi(e)).uncache(),e.world.taggers.forEach((t=>{t(e)})),e},Ji=function(e){class t extends e{stripPeriods(){return this.termList().forEach((e=>{!0===e.tags.Abbreviation&&e.next&&(e.post=e.post.replace(/^\./,""));let t=e.text.replace(/\./,"");e.set(t)})),this}addPeriods(){return this.termList().forEach((e=>{e.post=e.post.replace(/^\./,""),e.post="."+e.post})),this}}return t.prototype.unwrap=t.prototype.stripPeriods,e.prototype.abbreviations=function(e){let n=this.match("#Abbreviation");return"number"==typeof e&&(n=n.get(e)),new t(n.list,this,this.world)},e};const Li=/\./;var Si=function(e){class t extends e{stripPeriods(){return this.termList().forEach((e=>{let t=e.text.replace(/\./g,"");e.set(t)})),this}addPeriods(){return this.termList().forEach((e=>{let t=e.text.replace(/\./g,"");t=t.split("").join("."),!1===Li.test(e.post)&&(t+="."),e.set(t)})),this}}return t.prototype.unwrap=t.prototype.stripPeriods,t.prototype.strip=t.prototype.stripPeriods,e.prototype.acronyms=function(e){let n=this.match("#Acronym");return"number"==typeof e&&(n=n.get(e)),new t(n.list,this,this.world)},e},_i=function(e){return e.prototype.clauses=function(t){let n=this.if("@hasComma").notIf("@hasComma @hasComma").notIf("@hasComma . .? (and|or) .").notIf("(#City && @hasComma) #Country").notIf("(#WeekDay && @hasComma) #Date").notIf("(#Date && @hasComma) #Year").notIf("@hasComma (too|also)$").match("@hasComma"),r=this.splitAfter(n),a=r.quotations();r=r.splitOn(a);let i=r.parentheses();r=r.splitOn(i);let s=r.if("#Copula #Adjective #Conjunction (#Pronoun|#Determiner) #Verb").match("#Conjunction");r=r.splitBefore(s);let o=r.if("if .{2,9} then .").match("then");r=r.splitBefore(o),r=r.splitBefore("as well as ."),r=r.splitBefore("such as ."),r=r.splitBefore("in addition to ."),r=r.splitAfter("@hasSemicolon"),r=r.splitAfter("@hasDash");let l=r.filter((e=>e.wordCount()>5&&e.match("#Verb+").length>=2));if(l.found){let e=l.splitAfter("#Noun .* #Verb .* #Noun+");r=r.splitOn(e.eq(0))}return"number"==typeof t&&(r=r.get(t)),new e(r.list,this,this.world)},e},Ki=function(e){class t extends e{constructor(e,t,n){super(e,t,n),this.contracted=null}expand(){return this.list.forEach((e=>{let t=e.terms(),n=t[0].isTitleCase();t.forEach(((e,n)=>{e.set(e.implicit||e.text),e.implicit=void 0,n{let r=t(n).beforeLast;r.append(e),r.termList(0).addPunctuation(",")})),this}remove(e){return this.items().if(e).remove()}hasOxfordComma(){return this.filter((e=>t(e).hasOxford))}addOxfordComma(){let e=this.items(),t=e.eq(e.length-2);return t.found&&!1===t.has("@hasComma")&&t.post(", "),this}removeOxfordComma(){let e=this.items(),t=e.eq(e.length-2);return t.found&&!0===t.has("@hasComma")&&t.post(" "),this}}return n.prototype.things=n.prototype.items,e.prototype.lists=function(e){let t=this.if("@hasComma+ .? (and|or) not? ."),r=t.match("(#Noun|#Adjective|#Determiner|#Article)+ #Conjunction not? (#Article|#Determiner)? #Adjective? #Noun+").if("#Noun"),a=t.match("(#Adjective|#Adverb)+ #Conjunction not? #Adverb? #Adjective+"),i=t.match("(#Verb|#Adverb)+ #Conjunction not? #Adverb? #Verb+"),s=r.concat(a);return s=s.concat(i),s=s.if("@hasComma"),"number"==typeof e&&(s=t.get(e)),new n(s.list,this,this.world)},e};const Wi={hour:"an",heir:"an",heirloom:"an",honest:"an",honour:"an",honor:"an",uber:"an"},Ri={a:!0,e:!0,f:!0,h:!0,i:!0,l:!0,m:!0,n:!0,o:!0,r:!0,s:!0,x:!0},Ui=[/^onc?e/i,/^u[bcfhjkqrstn][aeiou]/i,/^eul/i],Qi={isSingular:[/(ax|test)is$/i,/(octop|vir|radi|nucle|fung|cact|stimul)us$/i,/(octop|vir)i$/i,/(rl)f$/i,/(alias|status)$/i,/(bu)s$/i,/(al|ad|at|er|et|ed|ad)o$/i,/(ti)um$/i,/(ti)a$/i,/sis$/i,/(?:(^f)fe|(lr)f)$/i,/hive$/i,/(^aeiouy|qu)y$/i,/(x|ch|ss|sh|z)$/i,/(matr|vert|ind|cort)(ix|ex)$/i,/(m|l)ouse$/i,/(m|l)ice$/i,/(antenn|formul|nebul|vertebr|vit)a$/i,/.sis$/i,/^(?!talis|.*hu)(.*)man$/i],isPlural:[/(antenn|formul|nebul|vertebr|vit)ae$/i,/(octop|vir|radi|nucle|fung|cact|stimul)i$/i,/men$/i,/.tia$/i,/(m|l)ice$/i]},Zi=/s$/,Xi={he:"his",she:"hers",they:"theirs",we:"ours",i:"mine",you:"yours",her:"hers",their:"theirs",our:"ours",my:"mine",your:"yours"},Yi=function(e){return!0===e.has("#Plural")||!0!==e.has("(#Pronoun|#Place|#Value|#Person|#Uncountable|#Month|#WeekDay|#Holiday|#Possessive)")},eo=function(e){if(e.has("#Person")||e.has("#Place"))return"";if(e.has("#Plural"))return"the";let t=e.text("normal").trim();if(Wi.hasOwnProperty(t))return Wi[t];let n=t.substr(0,1);if(e.has("^@isAcronym")&&Ri.hasOwnProperty(n))return"an";for(let e=0;et.test(e)))&&(!0===Zi.test(e)||!!Qi.isPlural.find((t=>t.test(e)))||null)},ro=function(e){let t=e.text("text").trim();return Xi.hasOwnProperty(t)?(e.replaceWith(Xi[t],!0),void e.tag("Possessive","toPossessive")):/s$/.test(t)?(t+="'",e.replaceWith(t,!0),void e.tag("Possessive","toPossessive")):(t+="'s",e.replaceWith(t,!0),void e.tag("Possessive","toPossessive"))},ao=function(e){let t={main:e};if(e.has("#Noun (of|by|for) .")){let n=e.splitAfter("[#Noun+]",0);t.main=n.eq(0),t.post=n.eq(1)}return t},no={json:function(e){let t=null;"number"==typeof e&&(t=e,e=null),e=e||{text:!0,normal:!0,trim:!0,terms:!0};let n=[];return this.forEach((t=>{let r=t.json(e)[0];r.article=eo(t),n.push(r)})),null!==t?n[t]:n},adjectives:function(){let e=this.lookAhead("^(that|who|which)? (was|is|will)? be? #Adverb? #Adjective+");return e=e.concat(this.lookBehind("#Adjective+ #Adverb?$")),e=e.match("#Adjective"),e.sort("index")},isPlural:function(){return this.if("#Plural")},hasPlural:function(){return this.filter((e=>Yi(e)))},toPlural:function(e){let t=this.world.transforms.toPlural;return this.forEach((n=>{if(n.has("#Plural")||!1===Yi(n))return;let r=ao(n).main,a=r.text("reduced");if((r.has("#Singular")||!0!==to(a))&&(a=t(a,this.world),r.replace(a).tag("#Plural"),e)){let e=r.lookBefore("(an|a) #Adjective?$").not("#Adjective");!0===e.found&&e.remove()}})),this},toSingular:function(e){let t=this.world.transforms.toSingular;return this.forEach((n=>{if(n.has("^#Singular+$")||!1===Yi(n))return;let r=ao(n).main,a=r.text("reduced");if((r.has("#Plural")||!0===to(a))&&(a=t(a,this.world),r.replace(a).tag("#Singular"),e)){let e=n,t=n.lookBefore("#Adjective");t.found&&(e=t);let r=eo(e);e.insertBefore(r)}})),this},toPossessive:function(){return this.forEach((e=>{ro(e)})),this}};var io=function(e){class t extends e{}return Object.assign(t.prototype,no),e.prototype.nouns=function(e,n={}){let r=this.match("(#City && @hasComma) (#Region|#Country)"),a=this.not(r).splitAfter("@hasComma");a=a.concat(r);let i=a.quotations();return i.found&&(a=a.splitOn(i.eq(0))),a=a.match("#Noun+ (of|by)? the? #Noun+?"),!0!==n.keep_anaphora&&(a=a.not("#Pronoun"),a=a.not("(there|these)"),a=a.not("(#Month|#WeekDay)"),a=a.not("(my|our|your|their|her|his)")),a=a.not("(of|for|by|the)$"),"number"==typeof e&&(a=a.get(e)),new t(a.list,this,this.world)},e};const oo=/\(/,so=/\)/;var lo=function(e){class t extends e{unwrap(){return this.list.forEach((e=>{let t=e.terms(0);t.pre=t.pre.replace(oo,"");let n=e.lastTerm();n.post=n.post.replace(so,"")})),this}}return e.prototype.parentheses=function(e){let n=[];return this.list.forEach((e=>{let t=e.terms();for(let r=0;r{e.terms().forEach((e=>{let t=e.text.replace(/'s$/,"");e.set(t||e.text)}))})),this}}return e.prototype.possessives=function(e){let n=this.match("#Noun+? #Possessive");return"number"==typeof e&&(n=n.get(e)),new t(n.list,this,this.world)},e};const co={'"':'"',""":""","'":"'","“":"”","‘":"’","‟":"”","‛":"’","„":"”","⹂":"”","‚":"’","«":"»","‹":"›","‵":"′","‶":"″","‷":"‴","〝":"〞","`":"´","〟":"〞"},ho=RegExp("("+Object.keys(co).join("|")+")");var go=function(e){class t extends e{unwrap(){return this}}return e.prototype.quotations=function(e){let n=[];return this.list.forEach((e=>{let t=e.terms();for(let r=0;r{let t=!1,n=wo(e),r=e.negative.found;e.verb.lookBehind("i (#Adverb|#Verb)?$").found&&(t=!0);let a={PastTense:"was",PresentTense:"is",FutureTense:"will be",Infinitive:"is",Gerund:"being",Actor:"",PerfectTense:"been",Pluperfect:"been"};return n&&(a.PastTense="were",a.PresentTense="are",a.Infinitive="are"),!0===t&&(a.PastTense="was",a.PresentTense="am",a.Infinitive="am"),r&&(a.PastTense+=" not",a.PresentTense+=" not",a.FutureTense="will not be",a.Infinitive+=" not",a.PerfectTense="not "+a.PerfectTense,a.Pluperfect="not "+a.Pluperfect,a.Gerund="not "+a.Gerund),a},Do=function(e){let t=e.verb.text();return{PastTense:t+" have",PresentTense:t,FutureTense:t,Infinitive:t}},$o=mo;var Po=function(e,t){let n=e.verb;if(n.has("#Copula")||"be"===n.out("normal")&&e.auxiliary.has("will"))return Ao(e);if(e.auxiliary.has("are")&&n.has("#Gerund")){let n=e.original.clone(),r=n.clone().replace("are","were"),a=n.clone().replace("are","will be"),i=ko(e,t);return{PastTense:r.text(),PresentTense:n.text(),FutureTense:a.text(),Infinitive:i}}if(n.has("#Modal"))return Do(e);let r=ko(e,t);if(!r)return{};let a=t.transforms.conjugate(r,t);a.Infinitive=r;let i=$o(e);!0===i&&(a.PresentTense=a.Infinitive);let s=e.verb.termList(0).hasHyphen();if(e.particle.found){let t=e.particle.text(),n=!0===s?"-":" ";Object.keys(a).forEach((e=>a[e]+=n+t))}const o=e.negative.found;return a.FutureTense=a.FutureTense||"will "+a.Infinitive,o&&(a.PastTense="did not "+a.Infinitive,a.FutureTense="will not "+a.Infinitive,i?(a.PresentTense="do not "+a.Infinitive,a.Infinitive="do not "+a.Infinitive):(a.PresentTense="does not "+a.Infinitive,a.Infinitive="does not "+a.Infinitive),a.Gerund="not "+a.Gerund),a};const Eo=Po;var Ho={useParticiple:function(e){return!!e.auxiliary.has("(could|should|would|may|can|must)")||!!e.auxiliary.has("am .+? being")||!!e.auxiliary.has("had .+? been")},toParticiple:function(e,t){if(e.auxiliary.has("(have|had)")&&e.verb.has("#Participle"))return;let n=Eo(e,t),r=n.Participle||n.PastTense;r&&e.verb.replaceWith(r,!1),e.auxiliary.has("am .+? being")&&(e.auxiliary.remove("am"),e.auxiliary.replace("being","have been")),e.auxiliary.has("have")||e.auxiliary.append("have"),e.verb.tag("Participle","toParticiple"),e.auxiliary.replace("can","could"),e.auxiliary.replace("be have","have been"),e.auxiliary.replace("not have","have not"),e.auxiliary.tag("Auxiliary")}};const jo=function(e,t){let n=e.verb;if(!e.negative.found){if(e.auxiliary.found)return e.auxiliary.eq(0).append("not"),void(e.auxiliary.has("#Modal have not")&&e.auxiliary.replace("have not","not have"));if(n.has("(#Copula|will|has|had|do)"))n.append("not");else{if(n.has("#PastTense")){let r=fo(e,t);return n.replaceWith(r,!0),void n.prepend("did not")}if(n.has("#PresentTense")){let r=fo(e,t);return n.replaceWith(r,!0),void(bo(e)?n.prepend("do not"):n.prepend("does not"))}if(n.has("#Gerund")){let r=fo(e,t);return n.replaceWith(r,!0),void n.prepend("not")}bo(e)?n.prepend("does not"):n.prepend("do not")}}},No=function(e){let t={adverb:e.match("#Adverb+"),negative:e.match("#Negative"),auxiliary:e.match("#Auxiliary+").not("(#Negative|#Adverb)"),particle:e.match("#Particle"),verb:e.match("#Verb+").not("(#Adverb|#Negative|#Auxiliary|#Particle)"),original:e,subject:vo(e)};if(t.verb.has("(#PresentTense|#PastTense|#Infinitive) #Gerund$")&&(t.verb=t.verb.not("#Gerund$")),!t.verb.found)return Object.keys(t).forEach((e=>{t[e]=t[e].not(".")})),t.verb=e,t;if(t.adverb&&t.adverb.found){let n=t.adverb.text("reduced")+"$";e.has(n)&&(t.adverbAfter=!0)}return t},xo=mo,Fo=yo,Co=Po,{toParticiple:Bo,useParticiple:Go}=Ho,zo=function(e){return e.auxiliary.remove("(will|are|am|being)"),e.auxiliary.remove("(did|does)"),e.auxiliary.remove("(had|has|have)"),e.particle.remove(),e.negative.remove(),e},Io={json:function(e){let t=null;"number"==typeof e&&(t=e,e=null),e=e||{text:!0,normal:!0,trim:!0,terms:!0};let n=[];return this.forEach((t=>{let r=t.json(e)[0],a=No(t);r.parts={},Object.keys(a).forEach((e=>{a[e]&&"Doc"===a[e].isA?r.parts[e]=a[e].text("normal"):r.parts[e]=a[e]})),r.isNegative=t.has("#Negative"),r.conjugations=Co(a,this.world),n.push(r)})),null!==t?n[t]:n},adverbs:function(){let e=[];this.forEach((t=>{let n=No(t).adverb;n.found&&(e=e.concat(n.list))}));let t=this.lookBehind("#Adverb+$");return t.found&&(e=t.list.concat(e)),t=this.lookAhead("^#Adverb+"),t.found&&(e=e.concat(t.list)),this.buildFrom(e)},isPlural:function(){let e=[];return this.forEach((t=>{let n=No(t);!0===xo(n,this.world)&&e.push(t.list[0])})),this.buildFrom(e)},isSingular:function(){let e=[];return this.forEach((t=>{let n=No(t);!1===xo(n,this.world)&&e.push(t.list[0])})),this.buildFrom(e)},conjugate:function(){let e=[];return this.forEach((t=>{let n=No(t),r=Co(n,this.world);e.push(r)})),e},toPastTense:function(){return this.forEach((e=>{let t=No(e);if(Go(t))return void Bo(t,this.world);if(e.has("#Imperative"))return;if(e.has("be")&&e.lookBehind("to$").found)return;if(t.verb.has("#Gerund")&&t.auxiliary.has("(is|will|was)"))return void e.replace("is","was");let n=Co(t,this.world).PastTense;n&&(t=zo(t),t.verb.replaceWith(n,!1),t.auxiliary.remove("(do|did|will)"))})),this},toPresentTense:function(){return this.forEach((e=>{if(e.has("#Imperative"))return;let t=No(e),n=Co(t,this.world),r=n.PresentTense;if(e.lookBehind("(i|we) (#Adverb|#Verb)?$").found&&(r=n.Infinitive),r){if(t.auxiliary.has("(have|had) been"))return t.auxiliary.replace("(have|had) been","am being"),void(n.Particle&&(r=n.Particle||n.PastTense));t.verb.replaceWith(r,!1),t.verb.tag("PresentTense"),t=zo(t),t.auxiliary.remove("#Modal"),t.auxiliary.remove("(do|did|will)")}})),this},toFutureTense:function(){return this.forEach((e=>{let t=No(e);if(Go(t))return;if(e.has("#Imperative"))return;let n=Co(t,this.world).FutureTense;n&&(t=zo(t),t.auxiliary.remove("#Modal"),t.verb.replaceWith(n,!1),t.verb.tag("FutureTense"),t.auxiliary.remove("(do|did|will)"))})),this},toInfinitive:function(){return this.forEach((e=>{let t=No(e),n=Co(t,this.world).Infinitive;n&&(e.replaceWith(n,!1),e.tag("Infinitive"))})),this},toGerund:function(){return this.forEach((e=>{let t=No(e),n=Co(t,this.world).Gerund;n&&(e.replaceWith(n,!1),e.tag("Gerund"))})),this},toParticiple:function(){return this.forEach((e=>{let t=No(e),n=!t.auxiliary.found;Bo(t,this.world),n&&(t.verb.prepend(t.auxiliary.text()),t.auxiliary.remove())})),this},isNegative:function(){return this.if("#Negative")},isPositive:function(){return this.ifNo("#Negative")},isImperative:function(){return this.if("#Imperative")},toNegative:function(){return this.list.forEach((e=>{let t=this.buildFrom([e]),n=No(t);jo(n,t.world)})),this},toPositive:function(){let e=this.match("do not #Verb");return e.found&&e.remove("do not"),this.remove("#Negative")},subject:function(){let e=[];return this.forEach((t=>{let n=Fo(t);n.list[0]&&e.push(n.list[0])})),this.buildFrom(e)}},Oo=Ia,To=[Ji,Si,_i,Ki,qi,io,lo,uo,go,function(e){class t extends e{}return Object.assign(t.prototype,Io),t.prototype.negate=t.prototype.toNegative,e.prototype.verbs=function(e){let n=this.match("(#Adverb|#Auxiliary|#Verb|#Negative|#Particle)+");n=n.not("^#Adverb+"),n=n.not("#Adverb+$");let r=n.match("(#Adverb && @hasComma) #Adverb"),a=n.not(r).splitAfter("@hasComma");return a=a.concat(r),a.sort("index"),a=a.if("#Verb"),a.has("(is|was)$")&&(a=a.splitBefore("(is|was)$")),a.has("#PresentTense #Adverb #PresentTense")&&(a=a.splitBefore("#Adverb #PresentTense")),"number"==typeof e&&(a=a.get(e)),new t(a.list,this,this.world)},e},function(e){class t extends e{}return e.prototype.people=function(e){let n=this.splitAfter("@hasComma");return n=n.match("#Person+"),"number"==typeof e&&(n=n.get(e)),new t(n.list,this,this.world)},e}],Vo={misc:Ga,selections:Ia},Mo=Mi,Jo=xt,Lo=function(e){return Object.keys(Oo).forEach((t=>e.prototype[t]=Oo[t])),To.forEach((t=>t(e))),e};class So{constructor(e,t,n){this.list=e,Object.defineProperty(this,"from",{enumerable:!1,value:t,writable:!0}),void 0===n&&void 0!==t&&(n=t.world),Object.defineProperty(this,"world",{enumerable:!1,value:n,writable:!0}),Object.defineProperty(this,"_cache",{enumerable:!1,writable:!0,value:{}}),Object.defineProperty(this,"found",{get:()=>this.list.length>0}),Object.defineProperty(this,"length",{get:()=>this.list.length}),Object.defineProperty(this,"isA",{get:()=>"Doc"})}tagger(){return Mo(this)}pool(){return this.list.length>0?this.list[0].pool:this.all().list[0].pool}}So.prototype.buildFrom=function(e){return e=e.map((e=>e.clone(!0))),new So(e,this,this.world)},So.prototype.fromText=function(e){let t=Jo(e,this.world,this.pool());return this.buildFrom(t)},Object.assign(So.prototype,Vo.misc),Object.assign(So.prototype,Vo.selections),Lo(So);const _o={untag:"unTag",and:"match",notIf:"ifNo",only:"if",onlyIf:"if"};Object.keys(_o).forEach((e=>So.prototype[e]=So.prototype[_o[e]]));const Ko=Va,qo=xt,Wo=zt,Ro=So,Uo=nt,Qo=ne$1,Zo=ot,Xo=function(e){let t=e.termList();return Ko(t,e.world),e.world.taggers.forEach((t=>{t(e)})),e},Yo=_e;var es=function e(t){let n=t;const r=function(e="",t){t&&n.addWords(t);let r=qo(e,n),a=new Ro(r,null,n);return a.tagger(),a};return r.tokenize=function(e="",t){let r=n;t&&(r=r.clone(),r.words={},r.addWords(t));let a=qo(e,r),i=new Ro(a,null,r);return(t||i.world.taggers.length>0)&&Xo(i),i},r.extend=function(e){return e(Ro,n,this,Uo,Qo,Zo),this},r.fromJSON=function(e){let t=Wo(e,n);return new Ro(t,null,n)},r.clone=function(){return e(n.clone())},r.verbose=function(e=!0){return n.verbose(e),this},r.world=function(){return n},r.parseMatch=function(e,t){return Yo(e,t)},r.version="13.11.4",r.import=r.load,r.plugin=r.extend,r}(new Rr),nlp=es,e=function(e,t){let n=e.match("#Value+? #Money+ #Currency+ (and #Money+ #Currency+)+?");return e.match("#Money").forEach((e=>{e.lookAfter("#Currency").found||(n=n.concat(e))})),"number"==typeof t&&(n=n.get(t)),n};const n="twenty|thirty|forty|fifty|sixty|seventy|eighty|ninety|fourty";var t=function(e,t){let r=e.match("#Value+");if(r.has("#NumericValue #NumericValue")&&(r.has("#Value @hasComma #Value")?r.splitAfter("@hasComma"):r.has("#NumericValue #Fraction")?r.splitAfter("#NumericValue #Fraction"):r=r.splitAfter("#NumericValue")),r.has("#Value #Value #Value")&&!r.has("#Multiple")&&r.has("("+n+") #Cardinal #Cardinal")&&(r=r.splitAfter("("+n+") #Cardinal")),r.has("#Value #Value")){r.has("#NumericValue #NumericValue")&&(r=r.splitOn("#Year")),r.has("("+n+") (eleven|twelve|thirteen|fourteen|fifteen|sixteen|seventeen|eighteen|nineteen)")&&(r=r.splitAfter("("+n+")"));let e=r.match("#Cardinal #Cardinal");if(e.found&&!r.has("(point|decimal|#Fraction)")&&!e.has("#Cardinal (#Multiple|point|decimal)")){let t=r.has(`(one|two|three|four|five|six|seven|eight|nine) (${n})`),a=e.has("("+n+") #Cardinal"),i=e.has("#Multiple #Value");t||a||i||e.terms().forEach((e=>{r=r.splitOn(e)}))}r.match("#Ordinal #Ordinal").match("#TextValue").found&&!r.has("#Multiple")&&(r.has("("+n+") #Ordinal")||(r=r.splitAfter("#Ordinal"))),r.has("#Ordinal #Cardinal")&&(r=r.splitBefore("#Cardinal+")),r.has("#TextValue #NumericValue")&&!r.has("("+n+"|#Multiple)")&&(r=r.splitBefore("#NumericValue+"))}return r.has("#NumberRange")&&(r=r.splitAfter("#NumberRange")),"number"==typeof t&&(r=r.get(t)),r},r=function(e,t){let n=e.match("#Fraction+");return n=n.filter((e=>!e.lookBehind("#Value and$").found)),"number"==typeof t&&(n=n.eq(t)),n},a=function(e,t){let n=e.match("#Percent+");return n=n.concat(e.match("[#Cardinal] percent",0)),"number"==typeof t&&(n=n.eq(t)),n},i={ones:{zeroth:0,first:1,second:2,third:3,fourth:4,fifth:5,sixth:6,seventh:7,eighth:8,ninth:9,zero:0,one:1,two:2,three:3,four:4,five:5,six:6,seven:7,eight:8,nine:9},teens:{tenth:10,eleventh:11,twelfth:12,thirteenth:13,fourteenth:14,fifteenth:15,sixteenth:16,seventeenth:17,eighteenth:18,nineteenth:19,ten:10,eleven:11,twelve:12,thirteen:13,fourteen:14,fifteen:15,sixteen:16,seventeen:17,eighteen:18,nineteen:19},tens:{twentieth:20,thirtieth:30,fortieth:40,fourtieth:40,fiftieth:50,sixtieth:60,seventieth:70,eightieth:80,ninetieth:90,twenty:20,thirty:30,forty:40,fourty:40,fifty:50,sixty:60,seventy:70,eighty:80,ninety:90},multiples:{hundredth:100,thousandth:1e3,millionth:1e6,billionth:1e9,trillionth:1e12,quadrillionth:1e15,quintillionth:1e18,sextillionth:1e21,septillionth:1e24,hundred:100,thousand:1e3,million:1e6,billion:1e9,trillion:1e12,quadrillion:1e15,quintillion:1e18,sextillion:1e21,septillion:1e24,grand:1e3}};const s=i,o=i,u=e=>{const t=[{reg:/^(minus|negative)[\s\-]/i,mult:-1},{reg:/^(a\s)?half[\s\-](of\s)?/i,mult:.5}];for(let n=0;n{if(s.ones.hasOwnProperty(e)){if(t.ones||t.teens)return!1}else if(s.teens.hasOwnProperty(e)){if(t.ones||t.teens||t.tens)return!1}else if(s.tens.hasOwnProperty(e)&&(t.ones||t.teens||t.tens))return!1;return!0},c$1=function(e){let t="0.";for(let n=0;n(e=(e=(e=(e=(e=(e=(e=e.replace(/1st$/,"1")).replace(/2nd$/,"2")).replace(/3rd$/,"3")).replace(/([4567890])r?th$/,"$1")).replace(/^[$€¥£¢]/,"")).replace(/[%$€¥£¢]$/,"")).replace(/,/g,"")).replace(/([0-9])([a-z\u00C0-\u00FF]{1,2})$/,"$1"),f=/^([0-9,\. ]+)\/([0-9,\. ]+)$/,d={"a few":3,"a couple":2,"a dozen":12,"two dozen":24,zero:0},y=e=>Object.keys(e).reduce(((t,n)=>t+e[n]),0);var p=function(e){if(!0===d.hasOwnProperty(e))return d[e];if("a"===e||"an"===e)return 1;const t=u(e);let n=null,r={},a=0,i=!1;const s=(e=t.str).split(/[ -]/);for(let e=0;e#Value+] out of every? [#Value+]");if(!0!==t.found)return null;let{num:n,den:r}=t.groups();return n&&r?(n=x(n),r=x(r),"number"==typeof n&&"number"==typeof r?{numerator:n,denominator:r}:null):null}(e)||function(e){let t=e.match("[(#Cardinal|a)+] [#Fraction+]");if(!0!==t.found)return null;let{num:n,dem:r}=t.groups();n=n.has("a")?1:x(n);let a=r.text("reduced");return b.test(a)&&(a=a.replace(b,""),r.replaceWith(a)),r=$.hasOwnProperty(a)?$[a]:x(r),"number"==typeof n&&"number"==typeof r?{numerator:n,denominator:r}:null}(e)||function(e){let t=e.match("^#Ordinal$");return!0!==t.found?null:e.lookAhead("^of .")?{numerator:1,denominator:x(t)}:null}(e)||null;return null!==t&&t.numerator&&t.denominator&&(t.decimal=t.numerator/t.denominator,t.decimal=(e=>{let t=Math.round(1e3*e)/1e3;return 0===t&&0!==e?e:t})(t.decimal)),t};const w=p,k=v;var C=function(e){let t=e.text("reduced"),n=/[0-9],[0-9]/.test(e.text("text")),r=function(e,t,n){let r=(e=e.replace(/,/g,"")).split(/^([^0-9]*)([0-9.,]*)([^0-9]*)$/);if(r&&r[2]&&t.terms().length<2){let t=parseFloat(r[2]||e);"number"!=typeof t&&(t=null);let n=r[3]||"";return"st"!==n&&"nd"!==n&&"rd"!==n&&"th"!==n||(n=""),"m"!==n&&"M"!==n||(t*=1e6,n=""),"k"!==n&&"k"!==n||(t*=1e3,n=""),{prefix:r[1]||"",num:t,suffix:n}}return null}(t,e);if(null!==r)return r.hasComma=n,r;let a=e.match("#Fraction #Fraction+$");a=!1===a.found?e.match("^#Fraction$"):a;let i=null;a.found&&(i=k(a),t=(e=(e=e.not(a)).not("and$")).text("reduced"));let s=0;return t&&(s=w(t)||0),i&&i.decimal&&(s+=i.decimal),{hasComma:n,prefix:"",num:s,suffix:""}},O=function(e){if(e<1e6)return String(e);let t;return t="number"==typeof e?e.toFixed(0):e,-1===t.indexOf("e+")?t:t.replace(".","").split("e+").reduce((function(e,t){return e+Array(t-e.length+2).join(0)}))};const V=O,F=[["ninety",90],["eighty",80],["seventy",70],["sixty",60],["fifty",50],["forty",40],["thirty",30],["twenty",20]],M=["","one","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"],E=[[1e24,"septillion"],[1e20,"hundred sextillion"],[1e21,"sextillion"],[1e20,"hundred quintillion"],[1e18,"quintillion"],[1e17,"hundred quadrillion"],[1e15,"quadrillion"],[1e14,"hundred trillion"],[1e12,"trillion"],[1e11,"hundred billion"],[1e9,"billion"],[1e8,"hundred million"],[1e6,"million"],[1e5,"hundred thousand"],[1e3,"thousand"],[100,"hundred"],[1,"one"]],N=function(e){let t=[];if(e>100)return t;for(let n=0;n=F[n][1]&&(e-=F[n][1],t.push(F[n][0]));return M[e]&&t.push(M[e]),t};var P=function(e){if(0===e||"0"===e)return"zero";e>1e21&&(e=V(e));let t=[];e<0&&(t.push("minus"),e=Math.abs(e));let n=function(e){let t=e,n=[];return E.forEach((r=>{if(e>=r[0]){let e=Math.floor(t/r[0]);t-=e*r[0],e&&n.push({unit:r[1],count:e})}})),n}(e);for(let e=0;e1&&t.push("and")),t=t.concat(N(n[e].count)),t.push(r)}return t=t.concat((e=>{const t=["zero","one","two","three","four","five","six","seven","eight","nine"];let n=[],r=V(e).match(/\.([0-9]+)/);if(!r||!r[0])return n;n.push("point");let a=r[0].split("");for(let e=0;ee)),0===t.length&&(t[0]=""),t.join(" ")};const z=O,A=P,j={one:"first",two:"second",three:"third",five:"fifth",eight:"eighth",nine:"ninth",twelve:"twelfth",twenty:"twentieth",thirty:"thirtieth",forty:"fortieth",fourty:"fourtieth",fifty:"fiftieth",sixty:"sixtieth",seventy:"seventieth",eighty:"eightieth",ninety:"ninetieth"};var q=e=>{let t=A(e).split(" "),n=t[t.length-1];return j.hasOwnProperty(n)?t[t.length-1]=j[n]:t[t.length-1]=n.replace(/y$/,"i")+"th",t.join(" ")},S={prefixes:{"¢":"cents",$:"dollars","£":"pounds","¥":"yen","€":"euros","₡":"colón","฿":"baht","₭":"kip","₩":"won","₹":"rupees","₽":"ruble","₺":"liras"},suffixes:{"%":"percent",s:"seconds",cm:"centimetres",km:"kilometres"}};const T$1=O,R=P,L=function(e){if(!e&&0!==e)return null;let t=e%100;if(t>10&&t<20)return String(e)+"th";const n={0:"th",1:"st",2:"nd",3:"rd"};let r=z(e),a=r.slice(r.length-1,r.length);return r+=n[a]?n[a]:"th",r},W=q,B=S.prefixes,D=S.suffixes,U={usd:!0,eur:!0,jpy:!0,gbp:!0,cad:!0,aud:!0,chf:!0,cny:!0,hkd:!0,nzd:!0,kr:!0,rub:!0},K=function(e){return B.hasOwnProperty(e.prefix)&&(e.suffix+=B[e.prefix],e.prefix=""),D.hasOwnProperty(e.suffix)&&(e.suffix=D[e.suffix]),U.hasOwnProperty(e.suffix)&&(e.suffix=e.suffix.toUpperCase()),e.suffix&&(e.suffix=" "+e.suffix),e};var Y=function(e,t,n){let r=String(e.num);return t?(e=K(e),n?(r=W(r),`${e.prefix||""}${r}${e.suffix||""}`):(r=R(r),`${e.prefix||""}${r}${e.suffix||""}`)):n?(r=L(r),`${(e=K(e)).prefix||""}${r}${e.suffix||""}`):(!0===e.hasComma&&(r=e.num.toLocaleString()),r=T$1(r),`${e.prefix||""}${r}${e.suffix||""}`)};const G=C,H=function(e,t,n){if(!1===e)return;let r=t.lookAhead("^(#Unit|#Noun)");r.has("(#Address|#Money|#Percent)")||t.has("#Ordinal")||(1===n.num?r.nouns().toSingular():r.has("#Singular")&&r.nouns().toPlural())},I=Y,Q=p;let Z={json:function(e){let t=null;"number"==typeof e&&(t=e,e=null),e=e||{text:!0,normal:!0,trim:!0,terms:!0};let n=[];return this.forEach((t=>{let r=t.json(e)[0],a=G(t);r.prefix=a.prefix,r.number=a.num,r.suffix=a.suffix,r.cardinal=I(a,!1,!1),r.ordinal=I(a,!1,!0),r.textCardinal=I(a,!0,!1),r.textOrdinal=I(a,!0,!0),n.push(r)})),null!==t?n[t]:n},units:function(){let e=this.lookAhead("(#Unit|#Noun)+");return e=e.splitAfter("@hasComma").first(),e=e.not("#Pronoun"),e.first()},isOrdinal:function(){return this.if("#Ordinal")},isCardinal:function(){return this.if("#Cardinal")},toNumber:function(){return this.forEach((e=>{let t=G(e);if(null===t.num)return;let n=I(t,!1,e.has("#Ordinal"));e.replaceWith(n,!0),e.tag("NumericValue")})),this},toLocaleString:function(){return this.forEach((e=>{let t=G(e);if(null===t.num)return;t.num=t.num.toLocaleString();let n=I(t,!1,e.has("#Ordinal"));e.replaceWith(n,!0)})),this},toText:function(){return this.forEach((e=>{let t=G(e);if(null===t.num)return;let n=I(t,!0,e.has("#Ordinal"));e.replaceWith(n,!0),e.tag("TextValue")})),this},toCardinal:function(e){return this.if("#Ordinal").forEach((t=>{let n=G(t);if(null===n.num)return;let r=I(n,t.has("#TextValue"),!1);if(t.has("#NumberRange")){let e=t.termList()[0];e.text&&""===e.post&&(e.post=" ")}t.replaceWith(r,!0),t.tag("Cardinal"),H(e,t,n)})),this},toOrdinal:function(){return this.if("#Cardinal").forEach((e=>{let t=G(e);if(null===t.num)return;let n=I(t,e.has("#TextValue"),!0);if(e.has("#NumberRange")){let t=e.termList()[0];t.text&&""===t.post&&(t.post=" ")}e.replaceWith(n,!0),e.tag("Ordinal");let r=this.lookAhead("^#Plural");r.found&&r.nouns().toSingular()})),this},isEqual:function(e){return this.filter((t=>G(t).num===e))},greaterThan:function(e){return this.filter((t=>G(t).num>e))},lessThan:function(e){return this.filter((t=>G(t).num{let r=G(n).num;return r>e&&r{let r=G(n);if(r.num=e,null===r.num)return;let a=I(r,n.has("#TextValue"),n.has("#Ordinal"));(n=n.not("#Currency")).replaceWith(a,!0),H(t,n,r)}))),this},add:function(e,t){return e?("string"==typeof e&&(e=Q(e)),this.forEach((n=>{let r=G(n);if(null===r.num)return;r.num+=e;let a=I(r,n.has("#TextValue"),n.has("#Ordinal"));(n=n.not("#Currency")).replaceWith(a,!0),H(t,n,r)})),this):this},subtract:function(e,t){return this.add(-1*e,t)},increment:function(e){return this.add(1,e),this},decrement:function(e){return this.add(-1,e),this},romanNumerals:function(e){let t=this.match("#RomanNumeral").numbers();return"number"==typeof e&&(t=t.get(e)),t},normalize:function(){const e={"%":!0};return this.forEach((t=>{let n=G(t);if(null!==n.num&&n.suffix&&!0!==e[n.suffix]){let e=n.prefix||"";t=t.replaceWith(e+n.num+" "+n.suffix)}})),this},get:function(e){let t=[];return this.forEach((e=>{t.push(G(e).num)})),void 0!==e?t[e]||null:t||null}};Z.toNice=Z.toLocaleString,Z.isBetween=Z.between,Z.minus=Z.subtract,Z.plus=Z.add,Z.equals=Z.isEqual;var J=Z;const X=C,_=function(e){let t=X(e).num;return"number"==typeof t?t/100:null};var ee={get:function(e){let t=[];return this.forEach((e=>{let n=_(e);null!==n&&t.push(n)})),void 0!==e?t[e]||null:t||null},json:function(e){let t=null;"number"==typeof e&&(t=e,e=null),e=e||{text:!0,normal:!0,trim:!0,terms:!0};let n=[];return this.forEach((t=>{let r=t.json(e)[0],a=_(t);if(r.number=a,null!==a){let e=100*a;r.textNumber=`${e} percent`,r.cardinal=`${e}%`}n.push(r)})),null!==t?n[t]||{}:n},toFraction:function(){return this.forEach((e=>{let t=_(e);if(null!==t){t*=100,t=Math.round(100*t)/100;let n=`${t}/100`;this.replace(e,n)}})),this}},ne=[{dem:"american",name:"dollar",iso:"usd",sub:"cent",sym:["$","US$","U$"]},{name:"euro",iso:"eur",sub:"cent",sym:["€"]},{dem:"british",name:"pound",iso:"gbp",sub:"penny",alias:{sterling:!0},sym:["£"]},{name:"renminbi",iso:"cny",plural:"yuán",alias:{yuan:!0},sym:["元"]},{dem:"japanese",name:"yen",iso:"jpy",sub:"sen",sym:["¥","円","圓"]},{dem:"swedish",name:"krona",iso:"sek",sub:"öre",alias:{ore:!0,kronor:!0},sym:["kr"]},{dem:"estonian",name:"kroon",iso:"eek",sub:"sent",sym:["kr"]},{dem:"norwegian",name:"krone",iso:"nok",sub:"øre",sym:["kr"]},{dem:"icelandic",name:"króna",iso:"isk",sym:["kr"]},{dem:"danish",name:"krone",iso:"dkk",sub:"øre",sym:["kr."]},{dem:"zambian",name:"kwacha",iso:"zmw",sub:"ngwee",sym:["K"]},{dem:"malawian",name:"kwacha",iso:"mwk",sub:"tambala",sym:["K"]},{dem:"greek",name:"drachma",iso:"grd",sub:"leptοn",sym:["Δρχ.","Δρ.","₯"]},{dem:"eastern caribbean",name:"dollar",iso:"xcd",sub:"cent",sym:["$"]},{dem:"finnish",name:"markka",iso:"fim",sub:"penni",sym:["mk"]},{dem:"polish",name:"złoty",iso:"pln",sub:"grosz",sym:["zł"]},{dem:"slovenian",name:"tolar",iso:"sit",sub:"stotin",sym:[]},{dem:"australian",name:"dollar",iso:"aud",sub:"cent",sym:["$","A$","AU$"]},{dem:"deutsche",name:"mark",iso:"dem",sub:"pfennig",sym:["DM"]},{dem:"thai",name:"baht",iso:"thb",sub:"satang",sym:["฿"]},{dem:"canadian",name:"dollar",iso:"cad",sub:"cent",sym:["$","Can$","C$","CA$","CAD"]},{dem:"mexican",name:"peso",iso:"mxn",sub:"centavo",sym:["$","Mex$"]},{dem:"spanish",name:"peseta",iso:"esp",sub:"céntimo",sym:["Pta"]},{dem:"new zealand",name:"dollar",iso:"nzd",sub:"cent",sym:["$","NZ$"]},{dem:"chilean",name:"peso",iso:"clp",sub:"centavo",sym:["Cifrão","$"]},{dem:"nigerian",name:"naira",iso:"ngn",sub:"kobo",sym:["₦"]},{dem:"austrian",name:"schilling",iso:"ats",sub:"groschen",sym:["S","öS"]},{dem:"guatemalan",name:"quetzal",iso:"gtq",sub:"centavo",sym:["Q"]},{dem:"philippine",name:"peso",iso:"php",sub:"sentimo",sym:["₱"]},{dem:"hungarian",name:"forint",iso:"huf",sym:["Ft"]},{dem:"russian",name:"ruble",iso:"rub",sub:"kopeyka",sym:["₽","руб","р."]},{dem:"kuwaiti",name:"dinar",iso:"kwd",sub:"fils",sym:["د.ك","KD"]},{dem:"israeli",name:"new shekel",iso:"ils",sub:"agora",sym:["₪"]},{dem:"latvian",name:"lats",iso:"lvl",sub:"santīms",sym:["Ls"]},{dem:"kazakhstani",name:"tenge",iso:"kzt",sub:"tıyn",sym:["₸"]},{dem:"iraqi",name:"dinar",iso:"iqd",sub:"fils",sym:["د.ع"]},{dem:"bahamian",name:"dollar",iso:"bsd",sub:"cent",sym:["$","B$"]},{dem:"seychellois",name:"rupee",iso:"scr",sub:"cent",sym:["SCR","SR"]},{dem:"albanian",name:"lek",iso:"all",sub:"qindarkë",sym:["L"]},{dem:"bulgarian",name:"lev",iso:"bgn",sub:"stotinka",sym:["лв."]},{dem:"irish",name:"pound",iso:"iep",sym:["£","IR£"]},{name:"cfp franc",iso:"xpf",sym:["f"]},{dem:"south african",name:"rand",iso:"zar",sub:"cent",sym:["R"]},{dem:"south korean",name:"won",iso:"krw",sub:"jeon",plural:"won",sym:["₩"]},{dem:"north korean",name:"won",iso:"kpw",sub:"chon",plural:"won",sym:["₩"]},{dem:"portuguese",name:"escudo",iso:"pte",sub:"centavo",sym:[]},{dem:"ghanaian",name:"cedi",iso:"ghs",sub:"pesewa",sym:["GH₵"]},{dem:"hong kong",name:"dollar",iso:"hkd",sub:"毫",sym:["$"]},{dem:"new taiwan",name:"dollar",iso:"twd",sub:"dime",sym:["NT$"]},{dem:"east german",name:"mark",iso:"ddm",sub:"pfennig",sym:["M"]},{dem:"namibian",name:"dollar",iso:"nad",sub:"cent",sym:["$"]},{dem:"malaysian",name:"ringgit",iso:"myr",sub:"sen",sym:["RM"]},{dem:"swiss",name:"franc",iso:"chf",sym:["Rp."]},{dem:"panamanian",name:"balboa",iso:"pab",sub:"centésimo",sym:["B/."]},{dem:"indonesian",name:"rupiah",iso:"idr",sub:"sen",sym:["Rp"]},{dem:"brunei",name:"dollar",iso:"bnd",sub:"sen",sym:["$","B$"]},{dem:"venezuelan",name:"bolívar",iso:"vef",sub:"céntimo",sym:["Bs.F","Bs."]},{dem:"macedonian",name:"denar",iso:"mkd",sub:"deni",sym:["den"]},{dem:"mauritanian",name:"ouguiya",iso:"mru",sub:"khoums",sym:["UM"]},{dem:"argentine",name:"peso",iso:"ars",sub:"centavo",sym:["$"]},{dem:"libyan",name:"dinar",iso:"lyd",sub:"dirham",sym:["LD","ل.د"]},{dem:"jordanian",name:"dinar",iso:"jod",sub:"dirham",sym:["د.أ"]},{dem:"french",name:"franc",iso:"frf",sub:"centime",sym:["F","Fr","FF","₣"]},{dem:"syrian",name:"pound",iso:"syp",sub:"piastre",sym:["LS","£S"]},{dem:"belize",name:"dollar",iso:"bzd",sub:"cent",sym:["$"]},{dem:"saudi",name:"riyal",iso:"sar",sub:"halalah",sym:["SAR","ر.س"," ﷼"]},{dem:"surinamese",name:"dollar",iso:"srd",sub:"cent",sym:["$"]},{dem:"singapore",name:"dollar",iso:"sgd",sub:"cent",sym:["S$","$"]},{dem:"nepalese",name:"rupee",iso:"npr",sub:"paisa",sym:["रु ₨","Re"]},{dem:"nicaraguan",name:"córdoba",iso:"nio",sub:"centavo",sym:["C$"]},{dem:"bangladeshi",name:"taka",iso:"bdt",sub:"poysha",sym:["৳"]},{dem:"indian",name:"rupee",iso:"inr",sub:"paisa",sym:["₹"]},{dem:"maldivian",name:"rufiyaa",iso:"mvr",sub:"laari",sym:["Rf","MRf","MVR",".ރ "]},{dem:"sri lankan",name:"rupee",iso:"lkr",sub:"cents",sym:["Rs","රු","ரூ"]},{dem:"bhutanese",name:"ngultrum",iso:"btn",sub:"chhertum",sym:["Nu."]},{dem:"turkish",name:"lira",iso:"try",sub:"kuruş",sym:["YTL"]},{dem:"serbian",name:"dinar",iso:"rsd",sub:"para",sym:["din","дин"]},{dem:"bosnia and herzegovina",name:"convertible mark",iso:"bam",sub:"fening",sym:["KM"]},{dem:"botswana",name:"pula",iso:"bwp",sub:"thebe",sym:["p"]},{dem:"swazi",name:"lilangeni",iso:"szl",sub:"cent",sym:["L","E"]},{dem:"lithuanian",name:"litas",iso:"ltl",sub:"centas",sym:["Lt","ct"]},{dem:"mauritian",name:"rupee",iso:"mur",sub:"cent",sym:["₨"]},{dem:"pakistani",name:"rupee",iso:"pkr",sub:"paisa",sym:["₨"]},{dem:"maltese",name:"lira",iso:"mtl",sub:"cent",sym:["₤","Lm"]},{dem:"cypriot",name:"pound",iso:"cyp",sub:"cent",sym:["£"]},{dem:"moldovan",name:"leu",iso:"mdl",sym:["l"]},{dem:"croatian",name:"kuna",iso:"hrk",sub:"lipa",sym:["kn"]},{dem:"afghan",name:"afghani",iso:"afn",sub:"pul",sym:["؋","Af","Afs"]},{dem:"ecuadorian",name:"sucre",iso:"ecs",sub:"centavo",sym:["S/."]},{dem:"sierra leonean",name:"leone",iso:"sll",sub:"cent",sym:["Le"]}];const te=ne,re=C,ae={};let ie={};te.forEach((e=>{e.sym.forEach((t=>{ae[t]=ae[t]||e.iso})),ae[e.iso]=ae[e.iso]||e.iso,e.sub&&(ie[e.sub]=!0)}));let se=`(${Object.keys(ie).join("|")})`;const oe=Y,ue=function(e){let t=0,n=e.match(`and #Money+ ${se}`);if(n.found){e=e.not(n);let r=re(n.match("#Value+"));r&&r.num&&(t=r.num/100)}let r=re(e),a=r.num||0;a+=t;let i=((s=r).suffix&&ae.hasOwnProperty(s.suffix)?te.find((e=>e.iso===ae[s.suffix])):s.prefix&&ae.hasOwnProperty(s.prefix)?te.find((e=>e.iso===ae[s.prefix])):null)||function(e){let t=e.match("#Currency+");t.nouns().toSingular();let n=t.text("reduced");return te.find((e=>(n===`${e.dem} ${e.name}`||n===e.iso||n===e.sub||n===e.name||!(!e.alias||!0!==e.alias[n]))&&e))}(e)||{};var s;let o="";return i&&i.sym&&(o=i.sym[0],a&&e.has(`${se}`)&&(a/=100)),{num:a,iso:i.iso,demonym:i.dem,currency:i.name,plural:i.plural,symbol:o}},le=function(e=""){return e.replace(/\w\S*/g,(function(e){return e.charAt(0).toUpperCase()+e.substr(1).toLowerCase()}))};var me$1={get:function(e){let t=[];return this.forEach((e=>{t.push(ue(e))})),void 0!==e?t[e]||null:t||null},currency:function(e){let t=[];return this.forEach((e=>{let n=ue(e);n&&t.push(n)})),"number"==typeof e?t[e]||null:t||null},json:function(e){let t=null;"number"==typeof e&&(t=e,e=null),e=e||{text:!0,normal:!0,trim:!0,terms:!0};let n=[];return this.forEach((t=>{let r=t.json(e)[0],a=ue(t);if(r.number=a.num,a.iso&&(r.iso=a.iso.toUpperCase(),r.symbol=a.symbol,r.currency=le(a.demonym)+" "+le(a.currency)),r.textFmt=oe(a,!0,!1),a.currency){let e=a.currency;1!==a.num&&(e=a.plural||e+"s"),r.textFmt+=" "+e}n.push(r)})),null!==t?n[t]||{}:n}},ce={};const he=P,fe=q;ce.toText=function(e){if(!e.numerator||!e.denominator)return"";let t=he(e.numerator),n=fe(e.denominator);return 2===e.denominator&&(n="half"),t&&n?(1!==e.numerator&&(n+="s"),`${t} ${n}`):""},ce.textCardinal=function(e){return e.numerator&&e.denominator?`${he(e.numerator)} out of ${he(e.denominator)}`:""},ce.toDecimal=function(e){return e.decimal};const de=v,ye=ce,pe={get:function(e){let t=[];return this.forEach((e=>{t.push(de(e))})),void 0!==e?t[e]||null:t||null},toDecimal(){return this.forEach((e=>{let t=de(e);if(t){let n=ye.toDecimal(t);e.replaceWith(String(n),!0),e.tag("NumericValue"),e.unTag("Fraction")}})),this},json:function(e){let t=null;"number"==typeof e&&(t=e,e=null),e=e||{text:!0,normal:!0,trim:!0,terms:!0};let n=[];return this.forEach((t=>{let r=t.json(e)[0],a=de(t)||{},i=ye.toDecimal(a);r.numerator=a.numerator,r.denominator=a.denominator,r.number=i,r.textOrdinal=ye.toText(a),r.textCardinal=ye.textCardinal(a),n.push(r)})),null!==t?n[t]||{}:n},normalize:function(){return this.forEach((e=>{let t=de(e);if(t&&"number"==typeof t.numerator&&"number"==typeof t.denominator){let n=`${t.numerator}/${t.denominator}`;this.replace(e,n)}})),this},toText:function(e){let t=[];return this.forEach((e=>{let t=de(e)||{},n=ye.toText(t);e.replaceWith(n,!0),e.tag("Fraction")})),void 0!==e?t[e]:t},toPercentage:function(){return this.forEach((e=>{let t=de(e);if(t.decimal||0===t.decimal){let n=100*t.decimal;n=Math.round(100*n)/100,this.replace(e,`${n}%`)}})),this}};pe.toNumber=pe.toDecimal;var be=pe;const ge=function(e){return e.match("(hundred|thousand|million|billion|trillion|quadrillion|quintillion|sextillion|septillion)").tag("#Multiple","fraction-tagger"),e.match("[(half|quarter)] of? (a|an)",0).tag("Fraction","millionth"),e.match("#Adverb [half]",0).tag("Fraction","nearly-half"),e.match("[half] the",0).tag("Fraction","half-the"),e.match("#Value (halves|halfs|quarters)").tag("Fraction","two-halves"),e.match("a #Ordinal").tag("Fraction","a-quarter"),e.match("(#Fraction && /s$/)").lookBefore("#Cardinal+$").tag("Fraction"),e.match("[#Cardinal+ #Ordinal] of .",0).tag("Fraction","ordinal-of"),e.match("[(#NumericValue && #Ordinal)] of .",0).tag("Fraction","num-ordinal-of"),e.match("(a|one) #Cardinal?+ #Ordinal").tag("Fraction","a-ordinal"),e.match("#Cardinal+ out? of every? #Cardinal").tag("Fraction","fraction-tagger"),e},xe=function(e){const t="money-tagger";e.match("#Money and #Money #Currency?").tag("Money","money-and-money"),e.match("#Money").not("#TextValue").match("/\\.[0-9]{3}$/").unTag("#Money","three-decimal money"),e.ifNo("#Value").match("#Currency #Verb").unTag("Currency","no-currency"),e.match("#Value #Currency [and] #Value (cents|ore|centavos|sens)",0).tag("Money",t);let n=e.match("[#Value] [(mark|rand|won|rub|ore)]");return n.group("num").tag("Money",t),n.group("currency").tag("Currency",t),e};var $e=function(e){(e=xe(e)).match("the [/[0-9]+s$/]").tag("#Plural","number-tag"),e.match("half a? #Value").tag("Value","half-a-value"),e.match("#Value [and a (half|quarter)]",0).tag(["TextValue","#Fraction"],"value-and-a-half"),(e=ge(e)).match("#Cardinal and #Fraction #Fraction").tag("Value","number-tag")};const ve={mark:!0,sucre:!0,leone:!0,afghani:!0,rand:!0,try:!0,mop:!0,won:!0,all:!0,rub:!0,eek:!0,sit:!0,bam:!0,npr:!0,leu:!0};let we={kronor:"Currency"};ne.forEach((e=>{e.iso&&!ve[e.iso]&&(we[e.iso]=["Acronym","Currency"]);let t=e.name;if(t&&!ve[t]&&(we[t]="Currency",we[t+"s"]="Currency"),e.dem){let n=e.dem;we[`${n} ${t}`]="Currency",we[`${n} ${t}s`]="Currency"}e.sub&&(we[e.sub]="Currency")}));const ke=e,Ce=t,Oe=r,Ve=a,Fe=J,Me=ee,Ee=me$1,Ne=be,Pe=$e,ze={Fraction:{isA:["Value"]},Multiple:{isA:"Value"}},Ae=we;var je=function(e,t){t.addWords(Ae),t.addTags(ze),t.postProcess(Pe);class n extends e{}Object.assign(n.prototype,Fe);class r extends n{}Object.assign(r.prototype,Ee);class a extends n{}Object.assign(a.prototype,Ne);class i extends n{}Object.assign(i.prototype,Me);const s={numbers:function(e){let t=Ce(this,e);return new n(t.list,this,this.world)},percentages:function(e){let t=Ve(this,e);return new i(t.list,this,this.world)},fractions:function(e){let t=Oe(this,e);return new a(t.list,this,this.world)},money:function(e){let t=ke(this,e);return new r(t.list,this,this.world)}};return s.values=s.numbers,s.percents=s.percentages,Object.assign(e.prototype,s),e},compromise_numbers=je;nlp.extend(compromise_numbers);class Pluralize extends Text{static componentType="pluralize";static rendererType="text";static createAttributesObject(){let e=super.createAttributesObject();return e.pluralForm={createComponentOfType:"text",createStateVariable:"pluralForm",defaultValue:null,public:!0},e.basedOnNumber={createComponentOfType:"number",createStateVariable:"basedOnNumber",defaultValue:null,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return renameStateVariable({stateVariableDefinitions:e,oldName:"value",newName:"valuePrePluralize"}),e.value={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({valuePrePluralize:{dependencyType:"stateVariable",variableName:"valuePrePluralize"},pluralForm:{dependencyType:"stateVariable",variableName:"pluralForm"},basedOnNumber:{dependencyType:"stateVariable",variableName:"basedOnNumber"}}),definition:function({dependencyValues:e}){let t,n=nlp(e.valuePrePluralize),r=n.values().toNumber().all().terms().json();if(0===r.length)return{setValue:{value:e.valuePrePluralize}};if(null!==e.basedOnNumber&&(t=numberDesignatesPlural(e.basedOnNumber)),1===r.length)return void 0===t&&(t=!0),t?null!==e.pluralForm?{setValue:{value:e.pluralForm}}:{setValue:{value:n.nouns().toPlural().all().out("text")}}:{setValue:{value:e.valuePrePluralize}};if(void 0===t){let e=[],a=[],i=n.nouns().json();for(let[t,n]of r.entries()){let r=i[e.length];n.terms[0].tags.includes("Value")&&a.push(t),void 0!==r&&r.text===n.text&&e.push(t)}t=[];let s=n.values().numbers().json(),o=-1;for(let n of e){for(;Number(a[o+1])({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:({dependencyValues:e})=>({setValue:{text:e.value}})},e}}function numberDesignatesPlural(e){return 1!==e}class Feedback extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{updateHide:this.updateHide.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="feedback";static renderChildren=!0;static primaryStateVariableForDefinition="feedbackText";static createAttributesObject(){let e=super.createAttributesObject();return delete e.hide,e.condition={createComponentOfType:"boolean"},e.updateWith={createTargetComponentNames:!0},e}static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.updateWithComponentNames={chainActionOnActionOfStateVariableTargets:{triggeredAction:"updateHide"},returnDependencies:()=>({updateWith:{dependencyType:"attributeTargetComponentNames",attributeName:"updateWith"}}),definition:({dependencyValues:e})=>e.updateWith?{setValue:{updateWithComponentNames:e.updateWith.map((e=>e.absoluteName))}}:{setValue:{updateWithComponentNames:[]}}},e.hideWhenUpdated={returnDependencies:()=>({condition:{dependencyType:"attributeComponent",attributeName:"condition",variableNames:["value"]},showFeedback:{dependencyType:"flag",flagName:"showFeedback"}}),definition:function({dependencyValues:e}){if(!e.showFeedback)return{setValue:{hideWhenUpdated:!0}};let t;return t=null!==e.condition&&!e.condition.stateValues.value,{setValue:{hideWhenUpdated:t}}}},e.hide={forRenderer:!0,defaultValue:!0,hasEssential:!0,returnDependencies:()=>({updateWith:{dependencyType:"attributeTargetComponentNames",attributeName:"updateWith"},condition:{dependencyType:"attributeComponent",attributeName:"condition",variableNames:["value"]},showFeedback:{dependencyType:"flag",flagName:"showFeedback"}}),definition:function({dependencyValues:e}){if(e.updateWith)return{useEssentialOrDefaultValue:{hide:!0}};if(!e.showFeedback)return{setValue:{hide:!0}};let t;return t=null!==e.condition&&!e.condition.stateValues.value,{setValue:{hide:t}}},inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t})=>t.updateWith?{success:!0,instructions:[{setEssentialValue:"hide",value:e.hide}]}:{success:!1}},e.feedbackText={forRenderer:!0,defaultValue:null,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{feedbackText:!0}})},e}async updateHide({actionId:e}){let t=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"hide",value:await this.stateValues.hideWhenUpdated}];return await this.coreFunctions.performUpdate({updateInstructions:t,actionId:e})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class CollaborateGroups extends BaseComponent{static componentType="collaborateGroups";static rendererType=void 0;static stateVariableForAttributeValue="collaborateGroups";static returnChildLogic(e){let t=super.returnChildLogic(e),n=t.newLeaf({name:"atLeastZeroPoints",componentType:"point",comparison:"atLeast",number:0}),r=breakStringsAndOthersIntoComponentsByStringCommas(),a=t.newLeaf({name:"exactlyOneString",componentType:"string",number:1,isSugar:!0,logicToWaitOnSugar:["atLeastZeroPoints"],replacementFunction:r});return t.newOperator({name:"pointsXorSugar",operator:"xor",propositions:[a,n],setAsBase:!0}),t}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.collaborateGroups={returnDependencies:()=>({pointChildren:{dependencyType:"child",childLogicName:"atLeastZeroPoints",variableNames:["xs","coords","nDimensions"]}}),definition:function({dependencyValues:e}){let t={};for(let n of e.pointChildren)if(2!==n.stateValues.nDimensions)console.warn(`invalid collaborate group: ${n.stateValues.coords.toString()}`);else{let e=n.stateValues.xs[0].evaluate_to_constant(),r=n.stateValues.xs[1].evaluate_to_constant();Number.isInteger(e)&&e>0&&Number.isInteger(r)&&r>0?(void 0===t[e]&&(t[e]=[]),t[e].push(r)):console.warn(`invalid collaborate group: ${n.stateValues.coords.toString()}`)}return{setValue:{collaborateGroups:{groups:t,matchGroup:function({groupNumber:e,numberOfGroups:n}={}){if(n>1){let r=t[n];return void 0!==r&&r.includes(e)}return!0}}}}}},e}}class CollaborateGroupSetup extends BaseComponent{static componentType="collaborateGroupSetup";static returnChildLogic(e){let t=super.returnChildLogic(e);return t.newLeaf({name:"atMostOnePossibleNumberOfGroups",componentType:"possibleNumberOfGroups",comparison:"atMost",number:1,setAsBase:!0}),t}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.possibleNumberOfGroups={returnDependencies:()=>({pngChild:{dependencyType:"child",childLogicName:"atMostOnePossibleNumberOfGroups",variableNames:["numbers"]}}),definition:function({dependencyValues:e}){return 0===e.pngChild.length?{setValue:{possibleNumberOfGroups:[1]}}:{setValue:{possibleNumberOfGroups:e.pngChild[0].stateValues.numbers}}}},e}}class ConsiderAsResponses extends BaseComponent{static componentType="considerAsResponses";static rendererType=void 0;static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.childrenWithNValues={returnDependencies:()=>({children:{dependencyType:"child",childGroups:["anything"],variableNames:["nValues"],variablesOptional:!0}}),definition:({dependencyValues:e})=>({setValue:{childrenWithNValues:e.children}})},e.childrenAsResponses={returnDependencies:()=>({children:{dependencyType:"child",childGroups:["anything"],variableNames:["value","values","componentType"],variablesOptional:!0}}),definition:({dependencyValues:e})=>({setValue:{childrenAsResponses:e.children}})},e}}class Case extends Template{static componentType="case";static createAttributesObject(){let e=super.createAttributesObject();return e.condition={createComponentOfType:"boolean"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.conditionSatisfied={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({condition:{dependencyType:"attributeComponent",attributeName:"condition",variableNames:["value"]}}),definition:function({dependencyValues:e}){let t;return t=null===e.condition||e.condition.stateValues.value,{setValue:{conditionSatisfied:t}}}},e}static createSerializedReplacements({component:e,componentInfoObjects:t}){return e.stateValues.conditionSatisfied?super.createSerializedReplacements({component:e,componentInfoObjects:t}):{replacements:[]}}}var dist={},formats={};Object.defineProperty(formats,"__esModule",{value:!0}),formats.FORMAT_PLAIN=formats.FORMAT_HTML=formats.FORMATS=void 0;var FORMAT_HTML="html";formats.FORMAT_HTML=FORMAT_HTML;var FORMAT_PLAIN="plain";formats.FORMAT_PLAIN=FORMAT_PLAIN;var FORMATS=[FORMAT_HTML,FORMAT_PLAIN];formats.FORMATS=FORMATS;var units={};Object.defineProperty(units,"__esModule",{value:!0}),units.UNIT_WORDS=units.UNIT_WORD=units.UNIT_SENTENCES=units.UNIT_SENTENCE=units.UNIT_PARAGRAPHS=units.UNIT_PARAGRAPH=units.UNITS=void 0;var UNIT_WORDS="words";units.UNIT_WORDS=UNIT_WORDS;var UNIT_WORD="word";units.UNIT_WORD=UNIT_WORD;var UNIT_SENTENCES="sentences";units.UNIT_SENTENCES=UNIT_SENTENCES;var UNIT_SENTENCE="sentence";units.UNIT_SENTENCE=UNIT_SENTENCE;var UNIT_PARAGRAPHS="paragraphs";units.UNIT_PARAGRAPHS=UNIT_PARAGRAPHS;var UNIT_PARAGRAPH="paragraph";units.UNIT_PARAGRAPH=UNIT_PARAGRAPH;var UNITS=[UNIT_WORDS,UNIT_WORD,UNIT_SENTENCES,UNIT_SENTENCE,UNIT_PARAGRAPHS,UNIT_PARAGRAPH];units.UNITS=UNITS;var words={};Object.defineProperty(words,"__esModule",{value:!0}),words.WORDS=void 0;var WORDS=["ad","adipisicing","aliqua","aliquip","amet","anim","aute","cillum","commodo","consectetur","consequat","culpa","cupidatat","deserunt","do","dolor","dolore","duis","ea","eiusmod","elit","enim","esse","est","et","eu","ex","excepteur","exercitation","fugiat","id","in","incididunt","ipsum","irure","labore","laboris","laborum","Lorem","magna","minim","mollit","nisi","non","nostrud","nulla","occaecat","officia","pariatur","proident","qui","quis","reprehenderit","sint","sit","sunt","tempor","ullamco","ut","velit","veniam","voluptate"];words.WORDS=WORDS;var LoremIpsum={},lineEndings={};Object.defineProperty(lineEndings,"__esModule",{value:!0}),lineEndings.LINE_ENDINGS=void 0;var LINE_ENDINGS={POSIX:"\n",WIN32:"\r\n"};lineEndings.LINE_ENDINGS=LINE_ENDINGS;var generator={},util={},capitalize={};!function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var t=function(e){var t=e.trim();return t.charAt(0).toUpperCase()+t.slice(1)};e.default=t}(capitalize);var isNode={exports:{}};!function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var n=function(){return!!e.exports};t.default=n}(isNode,isNode.exports);var isReactNative={};!function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var t=function(){var e=!1;try{e="ReactNative"===navigator.product}catch(t){e=!1}return e};e.default=t}(isReactNative);var isWindows={},platforms={};Object.defineProperty(platforms,"__esModule",{value:!0}),platforms.SUPPORTED_PLATFORMS=void 0;var SUPPORTED_PLATFORMS={DARWIN:"darwin",LINUX:"linux",WIN32:"win32"};platforms.SUPPORTED_PLATFORMS=SUPPORTED_PLATFORMS,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var t=platforms,n=function(){var e=!1;try{e=browser$1.platform===t.SUPPORTED_PLATFORMS.WIN32}catch(t){e=!1}return e};e.default=n}(isWindows);var makeArrayOfLength={};!function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var t=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;return Array.apply(null,Array(e)).map((function(e,t){return t}))};e.default=t}(makeArrayOfLength);var makeArrayOfStrings={};!function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var t,n=(t=makeArrayOfLength)&&t.__esModule?t:{default:t};var r=function(e,t){return(0,n.default)(e).map((function(){return t()}))};e.default=r}(makeArrayOfStrings),function(e){Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"capitalize",{enumerable:!0,get:function(){return t.default}}),Object.defineProperty(e,"isNode",{enumerable:!0,get:function(){return n.default}}),Object.defineProperty(e,"isReactNative",{enumerable:!0,get:function(){return r.default}}),Object.defineProperty(e,"isWindows",{enumerable:!0,get:function(){return a.default}}),Object.defineProperty(e,"makeArrayOfLength",{enumerable:!0,get:function(){return i.default}}),Object.defineProperty(e,"makeArrayOfStrings",{enumerable:!0,get:function(){return s.default}});var t=o(capitalize),n=o(isNode.exports),r=o(isReactNative),a=o(isWindows),i=o(makeArrayOfLength),s=o(makeArrayOfStrings);function o(e){return e&&e.__esModule?e:{default:e}}}(util),function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var t=words,n=util;function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:{},a=n.sentencesPerParagraph,s=void 0===a?{max:7,min:3}:a,o=n.wordsPerSentence,l=void 0===o?{max:15,min:5}:o,u=n.random;n.seed;var c=n.words,p=void 0===c?t.WORDS:c;if(r(this,e),i(this,"sentencesPerParagraph",void 0),i(this,"wordsPerSentence",void 0),i(this,"random",void 0),i(this,"words",void 0),s.min>s.max)throw new Error("Minimum number of sentences per paragraph (".concat(s.min,") cannot exceed maximum (").concat(s.max,")."));if(l.min>l.max)throw new Error("Minimum number of words per sentence (".concat(l.min,") cannot exceed maximum (").concat(l.max,")."));this.sentencesPerParagraph=s,this.words=p,this.wordsPerSentence=l,this.random=u||Math.random}var s,o,l;return s=e,(o=[{key:"generateRandomInteger",value:function(e,t){return Math.floor(this.random()*(t-e+1)+e)}},{key:"generateRandomWords",value:function(e){var t=this,r=this.wordsPerSentence,a=r.min,i=r.max,s=e||this.generateRandomInteger(a,i);return(0,n.makeArrayOfLength)(s).reduce((function(e,n){return"".concat(t.pluckRandomWord()," ").concat(e)}),"").trim()}},{key:"generateRandomSentence",value:function(e){return"".concat((0,n.capitalize)(this.generateRandomWords(e)),".")}},{key:"generateRandomParagraph",value:function(e){var t=this,r=this.sentencesPerParagraph,a=r.min,i=r.max,s=e||this.generateRandomInteger(a,i);return(0,n.makeArrayOfLength)(s).reduce((function(e,n){return"".concat(t.generateRandomSentence()," ").concat(e)}),"").trim()}},{key:"pluckRandomWord",value:function(){var e=this.words.length-1,t=this.generateRandomInteger(0,e);return this.words[t]}}])&&a(s.prototype,o),l&&a(s,l),Object.defineProperty(s,"prototype",{writable:!1}),e}(),o=s;e.default=o}(generator),function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var t,n=formats,r=lineEndings,a=(t=generator)&&t.__esModule?t:{default:t},i=util;function s(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:{},r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:n.FORMAT_PLAIN,i=arguments.length>2?arguments[2]:void 0;if(s(this,e),this.format=r,this.suffix=i,l(this,"generator",void 0),-1===n.FORMATS.indexOf(r.toLowerCase()))throw new Error("".concat(r," is an invalid format. Please use ").concat(n.FORMATS.join(" or "),"."));this.generator=new a.default(t)}var t,u,c;return t=e,(u=[{key:"getLineEnding",value:function(){return this.suffix?this.suffix:!(0,i.isReactNative)()&&(0,i.isNode)()&&(0,i.isWindows)()?r.LINE_ENDINGS.WIN32:r.LINE_ENDINGS.POSIX}},{key:"formatString",value:function(e){return this.format===n.FORMAT_HTML?"

".concat(e,"

"):e}},{key:"formatStrings",value:function(e){var t=this;return e.map((function(e){return t.formatString(e)}))}},{key:"generateWords",value:function(e){return this.formatString(this.generator.generateRandomWords(e))}},{key:"generateSentences",value:function(e){return this.formatString(this.generator.generateRandomParagraph(e))}},{key:"generateParagraphs",value:function(e){var t=this.generator.generateRandomParagraph.bind(this.generator);return this.formatStrings((0,i.makeArrayOfStrings)(e,t)).join(this.getLineEnding())}}])&&o(t.prototype,u),c&&o(t,c),Object.defineProperty(t,"prototype",{writable:!1}),e}(),c=u;e.default=c}(LoremIpsum),function(e){Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"LoremIpsum",{enumerable:!0,get:function(){return i.default}}),e.loremIpsum=void 0;var t,n=formats,r=units,a=words,i=(t=LoremIpsum)&&t.__esModule?t:{default:t};e.loremIpsum=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.count,s=void 0===t?1:t,o=e.format,l=void 0===o?n.FORMAT_PLAIN:o,u=e.paragraphLowerBound,c=void 0===u?3:u,p=e.paragraphUpperBound,d=void 0===p?7:p,m=e.random,h=e.sentenceLowerBound,f=void 0===h?5:h,y=e.sentenceUpperBound,g=void 0===y?15:y,b=e.units,v=void 0===b?r.UNIT_SENTENCES:b,N=e.words,T=void 0===N?a.WORDS:N,C=e.suffix,A=void 0===C?"":C,V={random:m,sentencesPerParagraph:{max:d,min:c},words:T,wordsPerSentence:{max:g,min:f}},x=new i.default(V,l,A);switch(v){case r.UNIT_PARAGRAPHS:case r.UNIT_PARAGRAPH:return x.generateParagraphs(s);case r.UNIT_SENTENCES:case r.UNIT_SENTENCE:return x.generateSentences(s);case r.UNIT_WORDS:case r.UNIT_WORD:return x.generateWords(s);default:return""}}}(dist);class Lorem extends CompositeComponent{static componentType="lorem";static assignNamesToReplacements=!0;static createsVariants=!0;static stateVariableToEvaluateAfterReplacements="readyToExpandWhenResolved";static createAttributesObject(){let e=super.createAttributesObject();return e.minSentencesPerParagraph={createComponentOfType:"number",createStateVariable:"minSentencesPerParagraph",defaultValue:4,public:!0},e.maxSentencesPerParagraph={createComponentOfType:"number",createStateVariable:"maxSentencesPerParagraph",defaultValue:8,public:!0},e.minWordsPerSentence={createComponentOfType:"number",createStateVariable:"minWordsPerSentence",defaultValue:4,public:!0},e.maxWordsPerSentence={createComponentOfType:"number",createStateVariable:"maxWordsPerSentence",defaultValue:8,public:!0},e.generateWords={createComponentOfType:"number",createStateVariable:"generateWords",defaultValue:null},e.generateSentences={createComponentOfType:"number",createStateVariable:"generateSentences",defaultValue:null},e.generateParagraphs={createComponentOfType:"number",createStateVariable:"generateParagraphs",defaultValue:null},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.readyToExpandWhenResolved={returnDependencies:()=>({minSentencesPerParagraph:{dependencyType:"stateVariable",variableName:"minSentencesPerParagraph"},maxSentencesPerParagraph:{dependencyType:"stateVariable",variableName:"maxSentencesPerParagraph"},minWordsPerSentence:{dependencyType:"stateVariable",variableName:"minWordsPerSentence"},maxWordsPerSentence:{dependencyType:"stateVariable",variableName:"maxWordsPerSentence"},generateWords:{dependencyType:"stateVariable",variableName:"generateWords"},generateSentences:{dependencyType:"stateVariable",variableName:"generateSentences"},generateParagraphs:{dependencyType:"stateVariable",variableName:"generateParagraphs"}}),markStale:()=>({updateReplacements:!0}),definition:()=>({setValue:{readyToExpandWhenResolved:!0}})},e.isVariantComponent={returnDependencies:()=>({}),definition:()=>({setValue:{isVariantComponent:!0}})},e.generatedVariantInfo={returnDependencies:({sharedParameters:e,componentInfoObjects:t})=>({variantSeed:{dependencyType:"value",value:e.variantSeed}}),definition:({dependencyValues:e,componentName:t})=>({setValue:{generatedVariantInfo:{seed:e.variantSeed,meta:{createdBy:t}}}})},e}static async createSerializedReplacements({component:e,componentInfoObjects:t}){const n=new dist.LoremIpsum({sentencesPerParagraph:{max:await e.stateValues.maxSentencesPerParagraph,min:await e.stateValues.minSentencesPerParagraph},wordsPerSentence:{max:await e.stateValues.maxWordsPerSentence,min:await e.stateValues.minWordsPerSentence},random:e.sharedParameters.variantRng});let r=[];if(null!==await e.stateValues.generateParagraphs){let t=await e.stateValues.generateParagraphs;if(Number.isInteger(t)&&t>0){r=n.generateParagraphs(t).split("\n").map((e=>({componentType:"p",children:[e]})))}}else if(null!==await e.stateValues.generateSentences){let t=await e.stateValues.generateSentences;if(Number.isInteger(t)&&t>0){let e=n.generateSentences(t).split(". ");for(let t of e.slice(0,e.length-1))r.push({componentType:"text",children:[t+"."]}),r.push(" ");r.push({componentType:"text",children:[e[e.length-1]]})}}else if(null!==await e.stateValues.generateWords){let t=await e.stateValues.generateWords;if(Number.isInteger(t)&&t>0){let e=n.generateWords(t).split(" ").map((e=>({componentType:"text",children:[e]})));r.push(e[0]);for(let t of e.slice(1))r.push(" "),r.push(t)}}let a=e.attributes.newNamespace?.primitive;return{replacements:processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:r,parentName:e.componentName,parentCreatesNewNamespace:a,componentInfoObjects:t}).serializedComponents}}static async calculateReplacementChanges({component:e,componentInfoObjects:t}){let n=await this.createSerializedReplacements({component:e,componentInfoObjects:t});return[{changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:0,numberReplacementsToReplace:e.replacements.length,serializedReplacements:n.replacements}]}static setUpVariant({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n}){setUpVariantSeedAndRng({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n})}}function returnStandardTriggeringAttributes(e){return{triggerWhen:{createComponentOfType:"boolean",createStateVariable:"triggerWhen",defaultValue:!1,triggerActionOnChange:e},triggerWith:{createTargetComponentNames:!0},triggerWhenObjectsClicked:{createTargetComponentNames:!0},triggerWhenObjectsFocused:{createTargetComponentNames:!0}}}function addStandardTriggeringStateVariableDefinitions(e,t){e.insideTriggerSet={returnDependencies:()=>({parentTriggerSet:{dependencyType:"parentStateVariable",parentComponentType:"triggerSet",variableName:"updateValueAndActionsToTrigger"}}),definition:({dependencyValues:e})=>({setValue:{insideTriggerSet:null!==e.parentTriggerSet}})},e.triggerWith={returnDependencies:()=>({triggerWith:{dependencyType:"attributeTargetComponentNames",attributeName:"triggerWith"},triggerWhenObjectsClicked:{dependencyType:"attributeTargetComponentNames",attributeName:"triggerWhenObjectsClicked"},triggerWhenObjectsFocused:{dependencyType:"attributeTargetComponentNames",attributeName:"triggerWhenObjectsFocused"},triggerWhen:{dependencyType:"attributeComponent",attributeName:"triggerWhen"},insideTriggerSet:{dependencyType:"stateVariable",variableName:"insideTriggerSet"}}),definition({dependencyValues:e}){if(e.triggerWhen||e.insideTriggerSet)return{setValue:{triggerWith:null}};{let t=[];if(null!==e.triggerWith)for(let n of e.triggerWith)t.push({target:n.absoluteName});if(null!==e.triggerWhenObjectsClicked)for(let n of e.triggerWhenObjectsClicked)t.push({target:n.absoluteName,triggeringAction:"click"});if(null!==e.triggerWhenObjectsFocused)for(let n of e.triggerWhenObjectsFocused)t.push({target:n.absoluteName,triggeringAction:"down"});return 0===t.length&&(t=null),{setValue:{triggerWith:t}}}}},e.triggerWithTargetIds={chainActionOnActionOfStateVariableTargets:{triggeredAction:t},returnDependencies:()=>({triggerWith:{dependencyType:"stateVariable",variableName:"triggerWith"}}),definition({dependencyValues:e}){let t=[];if(e.triggerWith)for(let n of e.triggerWith){let e=n.target;n.triggeringAction&&(e+="|"+n.triggeringAction),t.includes(e)||t.push(e)}return{setValue:{triggerWithTargetIds:t}}},markStale:()=>({updateActionChaining:!0})};let n=e.hidden.returnDependencies,r=e.hidden.definition;e.hidden.returnDependencies=function(e){let t=n(e);return t.triggerWhen={dependencyType:"attributeComponent",attributeName:"triggerWhen"},t.triggerWith={dependencyType:"stateVariable",variableName:"triggerWith"},t.insideTriggerSet={dependencyType:"stateVariable",variableName:"insideTriggerSet"},t},e.hidden.definition=function(e){return e.dependencyValues.triggerWhen||e.dependencyValues.triggerWith||e.dependencyValues.insideTriggerSet?{setValue:{hidden:!0}}:r(e)}}class UpdateValue extends InlineComponent{constructor(e){super(e),Object.assign(this.actions,{updateValue:this.updateValue.bind(this),updateValueIfTriggerNewlyTrue:this.updateValueIfTriggerNewlyTrue.bind(this)})}static componentType="updateValue";static acceptTarget=!0;static createAttributesObject(){let e=super.createAttributesObject();e.labelIsName={createComponentOfType:"boolean",createStateVariable:"labelIsName",defaultValue:!1,public:!0},e.type={createPrimitiveOfType:"string",createStateVariable:"type",defaultPrimitiveValue:"math",toLowerCase:!0,validValues:["math","number","boolean","text"]},e.prop={createPrimitiveOfType:"string"},e.newValue={createComponentOfType:"_componentWithSelectableType"},e.componentIndex={createComponentOfType:"integer",createStateVariable:"componentIndex",defaultValue:null,public:!0},e.propIndex={createComponentOfType:"numberList",createStateVariable:"propIndex",defaultValue:null,public:!0};let t=returnStandardTriggeringAttributes("updateValueIfTriggerNewlyTrue");return Object.assign(e,t),e.simplify={createComponentOfType:"text",createStateVariable:"simplify",defaultValue:"none",public:!0,toLowerCase:!0,valueTransformations:{true:"full"},validValues:["none","full","numbers","numberspreserveorder"]},e}static returnChildGroups(){return[{group:"labels",componentTypes:["label"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();addStandardTriggeringStateVariableDefinitions(e,"updateValue");let t=returnLabelStateVariableDefinitions();return Object.assign(e,t),e.target={returnDependencies:()=>({target:{dependencyType:"doenetAttribute",attributeName:"target"}}),definition:({dependencyValues:e})=>({setValue:{target:e.target}})},e.targetComponent={returnDependencies:()=>({targetComponent:{dependencyType:"targetComponent"}}),definition:function({dependencyValues:e}){let t=null;return e.targetComponent&&(t=e.targetComponent),{setValue:{targetComponent:t}}}},e.propName={returnDependencies:()=>({propName:{dependencyType:"attributePrimitive",attributeName:"prop"}}),definition:function({dependencyValues:e}){return{setValue:{propName:e.propName}}}},e.targetIdentities={stateVariablesDeterminingDependencies:["targetComponent","componentIndex"],returnDependencies:function({stateValues:e,componentInfoObjects:t}){let n={};return null!==e.targetComponent&&(t.isCompositeComponent({componentType:e.targetComponent.componentType,includeNonStandard:!1})?n.targets={dependencyType:"replacement",compositeName:e.targetComponent.componentName,recursive:!0,componentIndex:e.componentIndex}:null!==e.componentIndex&&1!==e.componentIndex||(n.targets={dependencyType:"stateVariable",variableName:"targetComponent"})),n},definition({dependencyValues:e}){let t=null;return e.targets&&(t=e.targets,Array.isArray(t)||(t=[t])),{setValue:{targetIdentities:t}}}},e.targets={stateVariablesDeterminingDependencies:["targetIdentities","propName","propIndex"],returnDependencies:function({stateValues:e}){let t={targetIdentities:{dependencyType:"stateVariable",variableName:"targetIdentities"}};if(null!==e.targetIdentities)for(let[n,r]of e.targetIdentities.entries()){let a;if(e.propName){let t=e.propIndex;t&&(t=[...t]),a={dependencyType:"stateVariable",componentName:r.componentName,variableName:e.propName,returnAsComponentObject:!0,variablesOptional:!0,propIndex:t,caseInsensitiveVariableMatch:!0,publicStateVariablesOnly:!0,useMappedVariableNames:!0}}else a={dependencyType:"componentIdentity",componentName:r.componentName};t["target"+n]=a}return t},definition({dependencyValues:e}){let t=null;if(null!==e.targetIdentities){t=[];for(let n in e.targetIdentities)e["target"+n]&&t.push(e["target"+n])}return{setValue:{targets:t}}}},e.newValue={returnDependencies:()=>({newValueAttr:{dependencyType:"attributeComponent",attributeName:"newValue",variableNames:["value"]},type:{dependencyType:"stateVariable",variableName:"type"},simplify:{dependencyType:"stateVariable",variableName:"simplify"}}),definition:function({dependencyValues:e}){if(null===e.newValueAttr)return{setValue:{newValue:null}};let t=e.newValueAttr.stateValues.value;return"math"===e.type&&(t=normalizeMathExpression({value:t,simplify:e.simplify})),{setValue:{newValue:t}}}},e}async updateValue({actionId:e}){let t=await this.stateValues.targets,n=await this.stateValues.newValue;if(null===t||null===n)return;let r=[];for(let e of t){let t="value";e.stateValues&&(t=Object.keys(e.stateValues)[0],void 0===t)?console.warn(`Cannot update prop="${await this.stateValues.propName}" of ${await this.stateValues.target} as could not find prop ${await this.stateValues.propName} on a component of type ${e.componentType}`):r.push({updateType:"updateValue",componentName:e.componentName,stateVariable:t,value:n})}return await this.coreFunctions.performUpdate({updateInstructions:r,actionId:e,event:{verb:"selected",object:{componentName:this.componentName,componentType:this.componentType},result:{response:n,responseText:n.toString()}}}),await this.coreFunctions.triggerChainedActions({componentName:this.componentName})}async updateValueIfTriggerNewlyTrue({stateValues:e,previousValues:t,actionId:n}){if(await e.triggerWhen&&!1===t.triggerWhen&&!await this.stateValues.insideTriggerSet)return await this.updateValue({actionId:n});this.coreFunctions.resolveAction({actionId:n})}}class CallAction extends InlineComponent{constructor(e){super(e),Object.assign(this.actions,{callAction:this.callAction.bind(this),callActionIfTriggerNewlyTrue:this.callActionIfTriggerNewlyTrue.bind(this)})}static componentType="callAction";static acceptTarget=!0;static keepChildrenSerialized({serializedComponent:e,componentInfoObjects:t}){if(void 0===e.children)return[];{let n=[];for(let[r,a]of e.children.entries())t.componentIsSpecifiedType(a,"label")||n.push(r);return n}}static createAttributesObject(){let e=super.createAttributesObject();e.labelIsName={createComponentOfType:"boolean",createStateVariable:"labelIsName",defaultValue:!1,public:!0},e.actionName={createComponentOfType:"text",createStateVariable:"actionName",defaultValue:null,public:!0};let t=returnStandardTriggeringAttributes("callActionIfTriggerNewlyTrue");return Object.assign(e,t),e.numbers={createComponentOfType:"numberList"},e.number={createComponentOfType:"number"},e}static returnChildGroups(){return[{group:"labels",componentTypes:["label"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();addStandardTriggeringStateVariableDefinitions(e,"callAction");let t=returnLabelStateVariableDefinitions();return Object.assign(e,t),e.target={returnDependencies:()=>({target:{dependencyType:"doenetAttribute",attributeName:"target"}}),definition:({dependencyValues:e})=>({setValue:{target:e.target}})},e.targetComponent={returnDependencies:()=>({targetComponent:{dependencyType:"targetComponent"}}),definition:function({dependencyValues:e}){let t=null;return e.targetComponent&&(t=e.targetComponent),{setValue:{targetComponent:t}}}},e.targetName={returnDependencies:()=>({targetComponent:{dependencyType:"stateVariable",variableName:"targetComponent"}}),definition({dependencyValues:e}){let t=null;return e.targetComponent&&(t=e.targetComponent.componentName),{setValue:{targetName:t}}}},e}async callAction({actionId:e}){let t=await this.stateValues.targetName,n=await this.stateValues.actionName;if(null!==t&&null!==n){let r={};this.serializedChildren.length>0&&(r.serializedComponents=deepClone(this.serializedChildren)),this.attributes.number&&(r.number=await this.attributes.number.component.stateValues.value),this.attributes.numbers&&(r.numbers=await this.attributes.numbers.component.stateValues.numbers),e&&(r.actionId=e),await this.coreFunctions.performAction({componentName:t,actionName:n,args:r,event:{verb:"selected",object:{componentName:this.componentName,componentType:this.componentType}},caseInsensitiveMatch:!0}),await this.coreFunctions.triggerChainedActions({componentName:this.componentName})}else this.coreFunctions.resolveAction({actionId:e})}async callActionIfTriggerNewlyTrue({stateValues:e,previousValues:t,actionId:n}){if(e.triggerWhen&&!1===t.triggerWhen&&!await this.stateValues.insideTriggerSet)return await this.callAction({actionId:n});this.coreFunctions.resolveAction({actionId:n})}}class triggerSet extends InlineComponent{constructor(e){super(e),Object.assign(this.actions,{triggerActions:this.triggerActions.bind(this),triggerActionsIfTriggerNewlyTrue:this.triggerActionsIfTriggerNewlyTrue.bind(this)})}static componentType="triggerSet";static createAttributesObject(){let e=super.createAttributesObject();e.labelIsName={createComponentOfType:"boolean",createStateVariable:"labelIsName",defaultValue:!1,public:!0};let t=returnStandardTriggeringAttributes("triggerActionsIfTriggerNewlyTrue");return Object.assign(e,t),e}static returnChildGroups(){return[{group:"updateValuesCallActions",componentTypes:["updateValue","callAction"]},{group:"labels",componentTypes:["label"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();addStandardTriggeringStateVariableDefinitions(e,"triggerActions");let t=returnLabelStateVariableDefinitions();return Object.assign(e,t),e.updateValueAndActionsToTrigger={returnDependencies:()=>({updateValueAndCallActionChildren:{dependencyType:"child",childGroups:["updateValuesCallActions"]}}),definition:({dependencyValues:e})=>({setValue:{updateValueAndActionsToTrigger:e.updateValueAndCallActionChildren}})},e}async triggerActions({actionId:e}){for(let e of await this.stateValues.updateValueAndActionsToTrigger)this.componentInfoObjects.isInheritedComponentType({inheritedComponentType:e.componentType,baseComponentType:"updateValue"})?await this.coreFunctions.performAction({componentName:e.componentName,actionName:"updateValue"}):this.componentInfoObjects.isInheritedComponentType({inheritedComponentType:e.componentType,baseComponentType:"callAction"})&&await this.coreFunctions.performAction({componentName:e.componentName,actionName:"callAction"});return this.coreFunctions.resolveAction({actionId:e}),await this.coreFunctions.triggerChainedActions({componentName:this.componentName})}async triggerActionsIfTriggerNewlyTrue({stateValues:e,previousValues:t,actionId:n}){if(e.triggerWhen&&!1===t.triggerWhen)return await this.triggerActions({actionId:n});this.coreFunctions.resolveAction({actionId:n})}}class FunctionIterates extends InlineComponent{static componentType="functionIterates";static rendererType=void 0;static createAttributesObject(){let e=super.createAttributesObject();return e.nIterates={createComponentOfType:"integer",createStateVariable:"nIterates",defaultValue:0,public:!0},e.forceSymbolic={createComponentOfType:"boolean",createStateVariable:"forceSymbolic",defaultValue:!1,public:!0},e.forceNumeric={createComponentOfType:"boolean",createStateVariable:"forceNumeric",defaultValue:!1,public:!0},e.initialValue={createComponentOfType:"math",createStateVariable:"initialValue",defaultValue:me$3.fromAst("_")},e.function={createComponentOfType:"function"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nDimensions={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({functionAttr:{dependencyType:"attributeComponent",attributeName:"function",variableNames:["nInputs","nOutputs"]}}),definition:({dependencyValues:e})=>e.functionAttr?e.functionAttr.stateValues.nInputs!==e.functionAttr.stateValues.nOutputs?(console.warn("Function iterates are possible only if the number of inputs is equal to the number of outputs"),{setValue:{nDimensions:0}}):{setValue:{nDimensions:e.functionAttr.stateValues.nInputs}}:{setValue:{nDimensions:0}}},e.allIterates={public:!0,shadowingInstructions:{createComponentOfType:"mathList"},returnDependencies:()=>({functionAttr:{dependencyType:"attributeComponent",attributeName:"function",variableNames:["symbolicfs","numericalfs","symbolic"]},forceSymbolic:{dependencyType:"stateVariable",variableName:"forceSymbolic"},forceNumeric:{dependencyType:"stateVariable",variableName:"forceNumeric"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},initialValue:{dependencyType:"stateVariable",variableName:"initialValue"},nIterates:{dependencyType:"stateVariable",variableName:"nIterates"}}),definition({dependencyValues:e}){let t=[],n=e.functionAttr,r=e.initialValue,a=!e.forceNumeric&&(n.stateValues.symbolic||e.forceSymbolic),i=e.nIterates;if(!n||0===e.nDimensions||!(1===e.nDimensions||Array.isArray(r.tree)&&vectorOperators.includes(r.tree[0])&&r.tree.length===e.nDimensions+1))return t=Array(i).fill(me$3.fromAst("_")),{setValue:{allIterates:t}};if(a)if(1===e.nDimensions){let e=n.stateValues.symbolicfs[0],a=r;for(let n=0;nme$3.fromAst(e).evaluate_to_constant())).map((e=>null==e?NaN:e));for(let n=0;n({initialValue:{dependencyType:"stateVariable",variableName:"initialValue"},allIterates:{dependencyType:"stateVariable",variableName:"allIterates"}}),definition:({dependencyValues:e})=>({setValue:{allIteratesWithInitial:[e.initialValue,...e.allIterates]}})},e.iterates={isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"math"},entryPrefixes:["iterate"],returnArraySizeDependencies:()=>({nIterates:{dependencyType:"stateVariable",variableName:"nIterates"}}),returnArraySize:({dependencyValues:e})=>[e.nIterates],returnArrayDependenciesByKey:()=>({globalDependencies:{allIterates:{dependencyType:"stateVariable",variableName:"allIterates"}}}),arrayDefinitionByKey({globalDependencyValues:e,arraySize:t}){let n={};for(let r=0;r!Number.isFinite(e.nIterates)||e.nIterates<0?{}:e.nIterates>0?{finalIterate:{dependencyType:"stateVariable",variableName:`iterate${e.nIterates}`}}:{finalIterate:{dependencyType:"stateVariable",variableName:"initialValue"}},definition:({dependencyValues:e})=>({setValue:{finalIterate:e.finalIterate}})},e}}class Module extends Template{static componentType="module";static renderedDefault=!0;static acceptAnyAttribute=!0;static createAttributesObject(){let e=super.createAttributesObject();return delete e.styleNumber,e}}class CustomAttribute extends CompositeComponent{static componentType="customAttribute";static assignNamesToReplacements=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.componentType={createPrimitiveOfType:"string"},e.attribute={createPrimitiveOfType:"string"},e.defaultValue={leaveRaw:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.componentNameForAttributes={returnDependencies:()=>({parentVariableContainingName:{dependencyType:"parentStateVariable",variableName:"componentNameForAttributes"}}),definition:({dependencyValues:e})=>({setValue:{componentNameForAttributes:e.parentVariableContainingName}})},e.attributeName={returnDependencies:()=>({attribute:{dependencyType:"attributePrimitive",attributeName:"attribute"}}),definition:({dependencyValues:e})=>({setValue:{attributeName:e.attribute}})},e.readyToExpandWhenResolved={stateVariablesDeterminingDependencies:["componentNameForAttributes"],returnDependencies:({stateValues:e})=>({componentIdentity:{dependencyType:"componentIdentity",componentName:e.componentNameForAttributes}}),definition:()=>({setValue:{readyToExpandWhenResolved:!0}})},e}static async createSerializedReplacements({component:e,components:t,workspace:n,componentInfoObjects:r,flags:a}){let i=e.attributes.newNamespace?.primitive,s=r.componentTypeLowerCaseMapping[e.attributes.componentType.primitive.toLowerCase()];if(!r.allComponentClasses[s])return console.warn(`Could not find component type ${s}`),{replacements:[]};let o=t[await e.stateValues.componentNameForAttributes],l={};for(let e in o.attributes)l[e.toLowerCase()]=e;let u=await e.stateValues.attributeName,c=l[u.toLowerCase()],p=o.attributes[c];if(void 0===p){if(void 0===e.attributes.defaultValue)return console.warn("Cannot create component from attribute if neither attribute nor default value specified"),{replacements:[]};p=e.attributes.defaultValue}let d=o.constructor,m=Object.keys(d.createAttributesObject()).map((e=>e.toLowerCase()));if(m.push("name","target","assignnames"),m.includes(u.toLowerCase()))return console.warn(`Cannot add attribute ${u} of a ${d.componentType} as it already exists in ${d.componentType} class`),{replacements:[]};let h=componentFromAttribute({attrObj:{createComponentOfType:s},value:p,componentInfoObjects:r}).component;if(h.children&&(applyMacros(h.children,r),i))for(let e of h.children)if("copy"===e.componentType){let t=e.doenetAttributes.target;/[a-zA-Z_]/.test(t[0])&&(e.doenetAttributes.target="../"+t)}return applySugar({serializedComponents:[h],isAttributeComponent:!0,componentInfoObjects:r}),setTNamesToAbsolute([h]),{replacements:processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:[h],parentName:e.componentName,parentCreatesNewNamespace:i,componentInfoObjects:r}).serializedComponents}}}class Setup extends CompositeComponent{static componentType="setup";static returnChildGroups(){return[{group:"styleDefinitions",componentTypes:["styleDefinitions"]},{group:"feedbackDefinitions",componentTypes:["feedbackDefinitions"]},{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.componentNameForAttributes={returnDependencies:()=>({sourceCompositeIdentity:{dependencyType:"sourceCompositeIdentity"}}),definition({dependencyValues:e}){let t=null;return e.sourceCompositeIdentity&&(t=e.sourceCompositeIdentity.componentName),{setValue:{componentNameForAttributes:t}}}},e.readyToExpandWhenResolved={returnDependencies:()=>({}),definition:()=>({setValue:{readyToExpandWhenResolved:!0}})},e}}class Footnote extends InlineComponent{static componentType="footnote";static renderChildren=!0;static includeBlankStringChildren=!0;static returnChildGroups(){return[{group:"inlines",componentTypes:["_inline"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["inlines"],variableNames:["text"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let t="";for(let n of e.inlineChildren)"object"!=typeof n?t+=n.toString():"string"==typeof n.stateValues.text?t+=n.stateValues.text:t+=" ";return{setValue:{text:t}}}},e.footnoteTag={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({footnoteCounter:{dependencyType:"counter",counterName:"footnote"}}),definition:({dependencyValues:e})=>({setValue:{footnoteTag:String(e.footnoteCounter)}})},e}}class Caption extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="caption";static rendererType="containerInline";static renderChildren=!0;static includeBlankStringChildren=!0;static returnChildGroups(){return[{group:"inlinesBlocks",componentTypes:["_inline","_block"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["inlinesBlocks"],variableNames:["text"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let t="";for(let n of e.inlineChildren)"object"!=typeof n?t+=n.toString():"string"==typeof n.stateValues.text?t+=n.stateValues.text:t+=" ";return{setValue:{text:t}}}},e}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class Endpoint extends Point{static componentType="endpoint";static rendererType="point";static createAttributesObject(){let e=super.createAttributesObject();return e.open={createComponentOfType:"boolean",createStateVariable:"open",defaultValue:!1,public:!0,forRenderer:!0},e.switchable={createComponentOfType:"boolean",createStateVariable:"switchable",defaultValue:!1,public:!0,forRenderer:!0},e}async switchPoint({actionId:e}){if(await this.stateValues.switchable)return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"open",value:!await this.stateValues.open}],actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{open:!await this.stateValues.open}}});this.coreFunctions.resolveAction({actionId:e})}}class Sort extends CompositeComponent{static componentType="sort";static stateVariableToEvaluateAfterReplacements="readyToExpandWhenResolved";static assignNamesToReplacements=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.assignNamesSkip={createPrimitiveOfType:"number"},e.sortVectorsBy={createComponentOfType:"text",createStateVariable:"sortVectorsBy",defaultValue:"displacement",public:!0,toLowerCase:!0,validValues:["displacement","tail"]},e.sortByComponent={createComponentOfType:"integer",createStateVariable:"sortByComponent",defaultValue:"1",public:!0},e.sortByProp={createPrimitiveOfType:"string"},e}static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.propName={returnDependencies:()=>({propName:{dependencyType:"attributePrimitive",attributeName:"sortByProp"}}),definition:function({dependencyValues:e}){return{setValue:{propName:e.propName}}}},e.componentNamesForValues={returnDependencies:()=>({children:{dependencyType:"child",childGroups:["anything"],variableNames:["componentNamesInList"],variablesOptional:!0}}),definition({dependencyValues:e}){let t=[];for(let n of e.children)n.stateValues.componentNamesInList?t.push(...n.stateValues.componentNamesInList):t.push(n.componentName);return{setValue:{componentNamesForValues:t}}}},e.sortedValues={stateVariablesDeterminingDependencies:["componentNamesForValues","sortByComponent","propName"],returnDependencies({stateValues:e}){let t={sortVectorsBy:{dependencyType:"stateVariable",variableName:"sortVectorsBy"},sortByComponent:{dependencyType:"stateVariable",variableName:"sortByComponent"},propName:{dependencyType:"stateVariable",variableName:"propName"}};if(e.propName)for(let[n,r]of e.componentNamesForValues.entries())t[`component${n}`]={dependencyType:"stateVariable",componentName:r,variableName:e.propName,variablesOptional:!0,caseInsensitiveVariableMatch:!0,publicStateVariablesOnly:!0,returnAsComponentObject:!0};else for(let[n,r]of e.componentNamesForValues.entries())t[`component${n}`]={dependencyType:"multipleStateVariables",componentName:r,variableNames:["value",`x${e.sortByComponent}`,`tailX${e.sortByComponent}`],variablesOptional:!0};return t},definition({dependencyValues:e,componentInfoObjects:t}){let n=[],r=!0;for(let a in e){if("component"!==a.substring(0,9))continue;let i=e[a];if(e.propName){let e=Object.values(i.stateValues)[0];n.push({componentName:i.componentName,numericalValue:Number(e),textValue:String(e)}),Number.isFinite(e)||(r=!1)}else if(t.isInheritedComponentType({inheritedComponentType:i.componentType,baseComponentType:"number"}))n.push({componentName:i.componentName,numericalValue:i.stateValues.value,textValue:String(i.stateValues.value)});else if(t.isInheritedComponentType({inheritedComponentType:i.componentType,baseComponentType:"text"})){let e=NaN,t=i.stateValues.value;n.push({componentName:i.componentName,numericalValue:e,textValue:t}),r=!1}else if(t.isInheritedComponentType({inheritedComponentType:i.componentType,baseComponentType:"math"})){let e=i.stateValues.value.evaluate_to_constant();null===e&&(e=NaN,r=!1),n.push({componentName:i.componentName,numericalValue:e,textValue:i.stateValues.value.toString()})}else if(t.isInheritedComponentType({inheritedComponentType:i.componentType,baseComponentType:"point"})){let t=i.stateValues[`x${e.sortByComponent}`],a=NaN,s="";t&&(a=t.evaluate_to_constant(),null===a&&(a=NaN,r=!1),s=t.toString()),n.push({componentName:i.componentName,numericalValue:a,textValue:s})}else if(t.isInheritedComponentType({inheritedComponentType:i.componentType,baseComponentType:"vector"})){let t=NaN,a="",s=i.stateValues[`x${e.sortByComponent}`];s="displacement"===e.sortVectorsBy?i.stateValues[`x${e.sortByComponent}`]:i.stateValues[`tailX${e.sortByComponent}`],s&&(t=s.evaluate_to_constant(),null===t&&(t=NaN,r=!1),a=s.toString()),n.push({componentName:i.componentName,numericalValue:t,textValue:a})}}return r?n.sort(((e,t)=>e.numericalValue-t.numericalValue)):n.sort(((e,t)=>e.textValue>t.textValue?1:e.textValue({sortedValues:{dependencyType:"stateVariable",variableName:"sortedValues"}}),markStale:()=>({updateReplacements:!0}),definition:function(){return{setValue:{readyToExpandWhenResolved:!0}}}},e}static async createSerializedReplacements({component:e,components:t,componentInfoObjects:n,workspace:r}){let a=[],i=[];for(let n of await e.stateValues.sortedValues){let e;if(void 0===n.listInd)e=t[n.componentName];else{e=t[n.componentName].activeChildren[n.listInd]}e&&(i.push(e.componentName),a.push(await e.serialize({sourceAttributesToIgnoreRecursively:["isResponse"]})))}r.uniqueIdentifiersUsed=[],a=postProcessCopy({serializedComponents:a,componentName:e.componentName,uniqueIdentifiersUsed:r.uniqueIdentifiersUsed,addShadowDependencies:!0,markAsPrimaryShadow:!0});let s=processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:a,parentName:e.componentName,parentCreatesNewNamespace:await e.stateValues.newNamespace,componentInfoObjects:n});return r.componentsCopied=i,{replacements:s.serializedComponents}}static async calculateReplacementChanges({component:e,components:t,componentInfoObjects:n,workspace:r}){let a=[];for(let n of await e.stateValues.sortedValues){let e;if(void 0===n.listInd)e=t[n.componentName];else{e=t[n.componentName].activeChildren[n.listInd]}e&&a.push(e.componentName)}if(a.length==r.componentsCopied.length&&r.componentsCopied.every(((e,t)=>e===a[t])))return[];let i=(await this.createSerializedReplacements({component:e,components:t,componentInfoObjects:n,workspace:r})).replacements;return[{changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:0,numberReplacementsToReplace:e.replacements.length,serializedReplacements:i}]}}class Shuffle extends CompositeComponent{static componentType="shuffle";static createsVariants=!0;static stateVariableToEvaluateAfterReplacements="readyToExpandWhenResolved";static assignNamesToReplacements=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.assignNamesSkip={createPrimitiveOfType:"number"},e}static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.originalComponentNames={additionalStateVariablesDefined:["nComponents"],returnDependencies:()=>({children:{dependencyType:"child",childGroups:["anything"],variableNames:["componentNamesInList"],variablesOptional:!0}}),definition({dependencyValues:e}){let t=[];for(let n of e.children)n.stateValues.componentNamesInList?t.push(...n.stateValues.componentNamesInList):t.push(n.componentName);return{setValue:{originalComponentNames:t,nComponents:t.length}}}},e.componentOrder={returnDependencies:({sharedParameters:e})=>({variantSeed:{dependencyType:"value",value:e.variantSeed},rngClass:{dependencyType:"value",value:e.rngClass,doNotProxy:!0},nComponents:{dependencyType:"stateVariable",variableName:"nComponents"},variants:{dependencyType:"variants"}}),definition({dependencyValues:e}){let t=e.nComponents,n=e.variants?.desiredVariant?.indices;if(void 0!==n)if(n.length!==t)console.warn("Ignoring indices specified for shuffle as number of indices doesn't match number of components.");else{if(n=n.map(Number),!n.every(Number.isInteger))throw Error("All indices specified for shuffle must be integers");if(n.every((e=>e>=1&&e<=t)))return{setValue:{componentOrder:n}};console.warn("Ignoring indices specified for shuffle as some indices out of range.")}let r=e.rngClass(e.variantSeed+"co"),a=[...Array(t).keys()].map((e=>e+1));for(let e=t-1;e>0;e--){const t=r(),n=Math.floor(t*(e+1));[a[e],a[n]]=[a[n],a[e]]}return{setValue:{componentOrder:a}}}},e.readyToExpandWhenResolved={returnDependencies:()=>({sortedValues:{dependencyType:"stateVariable",variableName:"componentOrder"}}),markStale:()=>({updateReplacements:!0}),definition:function(){return{setValue:{readyToExpandWhenResolved:!0}}}},e.generatedVariantInfo={additionalStateVariablesDefined:["isVariantComponent"],returnDependencies:({componentInfoObjects:e,sharedParameters:t})=>({variantSeed:{dependencyType:"value",value:t.variantSeed},componentOrder:{dependencyType:"stateVariable",variableName:"componentOrder"},variantDescendants:{dependencyType:"descendant",componentTypes:Object.keys(e.componentTypesCreatingVariants),variableNames:["isVariantComponent","generatedVariantInfo"],useReplacementsForComposites:!0,recurseToMatchedChildren:!1,variablesOptional:!0,includeNonActiveChildren:!0,ignoreReplacementsOfEncounteredComposites:!0}}),definition({dependencyValues:e,componentName:t}){let n={seed:e.variantSeed,meta:{createdBy:t},indices:e.componentOrder},r=n.subvariants=[];for(let t of e.variantDescendants)t.stateValues.isVariantComponent?r.push(t.stateValues.generatedVariantInfo):t.stateValues.generatedVariantInfo&&r.push(...t.stateValues.generatedVariantInfo.subvariants);return{setValue:{generatedVariantInfo:n,isVariantComponent:!0}}}},e}static setUpVariant({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n}){setUpVariantSeedAndRng({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n})}static async createSerializedReplacements({component:e,components:t,componentInfoObjects:n,workspace:r}){let a=[],i=[],s=await e.stateValues.originalComponentNames;for(let n of await e.stateValues.componentOrder){let e=t[s[n-1]];e&&(i.push(e.componentName),a.push(await e.serialize({sourceAttributesToIgnoreRecursively:["isResponse"]})))}r.uniqueIdentifiersUsed=[],a=postProcessCopy({serializedComponents:a,componentName:e.componentName,uniqueIdentifiersUsed:r.uniqueIdentifiersUsed,addShadowDependencies:!0,markAsPrimaryShadow:!0});let o=processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:a,parentName:e.componentName,parentCreatesNewNamespace:await e.stateValues.newNamespace,componentInfoObjects:n});return r.componentsCopied=i,{replacements:o.serializedComponents}}static async calculateReplacementChanges({component:e,components:t,componentInfoObjects:n,workspace:r}){let a=[],i=await e.stateValues.originalComponentNames;for(let n of await e.stateValues.componentOrder){let e=t[i[n-1]];e&&a.push(e.componentName)}if(a.length==r.componentsCopied.length&&r.componentsCopied.every(((e,t)=>e===a[t])))return[];let s=(await this.createSerializedReplacements({component:e,components:t,componentInfoObjects:n,workspace:r})).replacements;return[{changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:0,numberReplacementsToReplace:e.replacements.length,serializedReplacements:s}]}static determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t}){let n=0;for(let r of e.children)if(t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"_composite"})){if(!r.attributes.createComponentOfType?.primitive)return{success:!1};if(void 0!==r.attributes.nComponents?.primitive){let e=Number(r.attributes.nComponents?.primitive);if(!(Number.isInteger(e)&&e>=0))return{success:!1};n+=e}else n++}else n++;let r=1;for(let e=2;e<=n;e++)r*=e;let a=super.determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t});if(!a.success)return{success:!1};let i=a.numberOfVariants*r;return e.variants.numberOfVariants=i,e.variants.uniqueVariantData={numberOfVariantsByDescendant:e.variants.uniqueVariantData.numberOfVariantsByDescendant,numberOfPermutations:r,nComponents:n},{success:!0,numberOfVariants:i}}static getUniqueVariant({serializedComponent:e,variantIndex:t,componentInfoObjects:n}){let r=e.variants?.numberOfVariants;if(void 0===r)return{success:!1};if(!Number.isInteger(t)||t<1||t>r)return{success:!1};let a=e.variants.uniqueVariantData.numberOfVariantsByDescendant,i=e.variants.descendantVariantComponents,s=e.variants.uniqueVariantData.numberOfPermutations,o=e.variants.uniqueVariantData.nComponents,l=[...a];l.push(s);let u=enumerateCombinations({numberOfOptionsByIndex:l,maxNumber:t})[t-1].map((e=>e+1)),c=u.pop(),p=u,d=[...Array(o).keys()].map((e=>e+1)),m=enumeratePermutations({values:d,maxNumber:c})[c-1],h=!1,f=[];for(let e=0;e1){let t=i[e],r=n.allComponentClasses[t.componentType].getUniqueVariant({serializedComponent:t,variantIndex:p[e],componentInfoObjects:n});if(!r.success)return{success:!1};f.push(r.desiredVariant),h=!0}else f.push({});let y={indices:m};return h&&(y.subvariants=f),{success:!0,desiredVariant:y}}}class SolveEquations extends InlineComponent{static componentType="solveEquations";static rendererType=void 0;static createAttributesObject(){let e=super.createAttributesObject();return e.variables={createComponentOfType:"variables"},e.nDiscretizationPoints={createComponentOfType:"number",createStateVariable:"nDiscretizationPoints",defaultValue:100,public:!0},e.minVar={createComponentOfType:"number",createStateVariable:"minVar",defaultValue:null},e.maxVar={createComponentOfType:"number",createStateVariable:"maxVar",defaultValue:null},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e}){return e.every((e=>"string"==typeof e||e.doenetAttributes&&e.doenetAttributes.createdFromMacro))?1===e.length&&"string"!=typeof e[0]?{success:!1}:{success:!0,newChildren:[{componentType:"math",children:e}]}:{success:!1}}}),e}static returnChildGroups(){return[{group:"maths",componentTypes:["math"]},{group:"strings",componentTypes:["string"]}]}static returnStateVariableDefinitions({numerics:e}){let t=super.returnStateVariableDefinitions({numerics:e});return t.variables={isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"variable"},entryPrefixes:["variable"],returnArraySizeDependencies:()=>({}),returnArraySize:({dependencyValues:e})=>[1],returnArrayDependenciesByKey:({arrayKeys:e})=>({globalDependencies:{variablesAttr:{dependencyType:"attributeComponent",attributeName:"variables",variableNames:["variables"]}}}),arrayDefinitionByKey({globalDependencyValues:e,arraySize:t,arrayKeys:n,usedDefault:r}){let a=[];return null!==e.variablesAttr&&(a=e.variablesAttr.stateValues.variables),{setValue:{variables:returnNVariables(t[0],a)}}}},t.variable={isAlias:!0,targetVariableName:"variable1"},t.allSolutions={returnDependencies:()=>({mathChild:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]},variables:{dependencyType:"stateVariable",variableName:"variables"},minVar:{dependencyType:"stateVariable",variableName:"minVar"},maxVar:{dependencyType:"stateVariable",variableName:"maxVar"},nDiscretizationPoints:{dependencyType:"stateVariable",variableName:"nDiscretizationPoints"}}),definition({dependencyValues:t}){if(0===t.mathChild.length)return{setValue:{allSolutions:[]}};let n=t.mathChild[0].stateValues.value;if(!Array.isArray(n.tree)||3!==n.tree.length||"="!==n.tree[0])return{setValue:{allSolutions:[]}};let r=t.minVar,a=t.maxVar,i=[],s=t.variables[0].subscripts_to_strings().tree,o=me$3.fromAst(["+",n.tree[1],["-",n.tree[2]]]).subscripts_to_strings(),l=o.f(),u=e=>l({[s]:e}),c=function(e){try{return u(e)}catch(e){return NaN}};if(Number.isFinite(r)||(r=-10),Number.isFinite(a)||(a=10),r>a)return{setValue:{allSolutions:[]}};let p=[r,a],d=[r];for(let e=0;enormalizeMathExpression({value:o.substitute({[s]:e}).strings_to_subscripts(),simplify:!0,expand:!0}).evaluate_to_constant())(e);return null!==n?n:NaN}})),y=d[0],g=f[0];for(let e=0;e0)for(let t=0;t<10;t++)if(y=.1*y+.9*n,s=.1*s+.9*n,g=c(y),o=c(s),g*o<0){g*u<0?(i.push(e.fzero(c,[l,y])),i.push(n)):(i.includes(n)||i.push(n),n=s,r=o),a=!0;break}}a||i.includes(n)||i.push(n)}else if(r*g<0)i.push(e.fzero(c,[y,n]));else if(0!==g&&t0&&(r>0&&g>r||r<0&&gr?c:e=>-c(e);let s=e.fminbr(t,[y,a],void 0,1e-10);if(s.success){let t=s.x,a=c(t);a*g<0?(i.push(e.fzero(c,[y,t])),n=t,r=a):0===a&&i.push(t)}}}y=n,g=r}i=i.filter((e=>e>=r&&e<=a));let b=i.map((e=>me$3.fromAst(e)));return{setValue:{allSolutions:b}}}},t.numberSolutions={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({allSolutions:{dependencyType:"stateVariable",variableName:"allSolutions"}}),definition:({dependencyValues:e})=>({setValue:{numberSolutions:e.allSolutions.length}})},t.solutions={public:!0,shadowingInstructions:{createComponentOfType:"math"},isArray:!0,entryPrefixes:["solution"],returnArraySizeDependencies:()=>({numberSolutions:{dependencyType:"stateVariable",variableName:"numberSolutions"}}),returnArraySize:({dependencyValues:e})=>[e.numberSolutions],returnArrayDependenciesByKey:()=>({globalDependencies:{allSolutions:{dependencyType:"stateVariable",variableName:"allSolutions"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n=0;n({parentOpen:{dependencyType:"parentStateVariable",variableName:"open"}}),markStale:()=>({updateReplacements:!0}),definition:({dependencyValues:e})=>({setValue:{rendered:Boolean(e.parentOpen)}})},e}static async calculateReplacementChanges({component:e,componentInfoObjects:t}){if(await e.stateValues.rendered&&0===e.replacements.length){let n=(await this.createSerializedReplacements({component:e,componentInfoObjects:t})).replacements;if(n.length>0){return[{changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:0,numberReplacementsToReplace:0,serializedReplacements:n}]}return[]}return[]}}class SubsetOfRealsInput extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{addPoint:this.addPoint.bind(this),deletePoint:this.deletePoint.bind(this),movePoint:this.movePoint.bind(this),togglePoint:this.togglePoint.bind(this),toggleInterval:this.toggleInterval.bind(this),clear:this.clear.bind(this),setToR:this.setToR.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="subsetOfRealsInput";static variableForPlainMacro="subsetValue";static variableForPlainCopy="subsetValue";static createAttributesObject(){let e=super.createAttributesObject();return e.xmin={createComponentOfType:"number",createStateVariable:"xmin",defaultValue:-10,public:!0,forRenderer:!0},e.xmax={createComponentOfType:"number",createStateVariable:"xmax",defaultValue:10,public:!0,forRenderer:!0},e.width={createComponentOfType:"_componentSize",createStateVariable:"width",defaultValue:800,public:!0,forRenderer:!0},e.height={createComponentOfType:"_componentSize",createStateVariable:"height",defaultValue:300,public:!0,forRenderer:!0},e.xlabel={createComponentOfType:"text",createStateVariable:"xlabel",defaultValue:"",public:!0,forRenderer:!0},e.dx={createComponentOfType:"number",createStateVariable:"dx",defaultValue:.5,public:!0},e.variable={createComponentOfType:"variable",createStateVariable:"variable",defaultValue:me$3.fromAst("x"),public:!0},e.format={createComponentOfType:"text",createStateVariable:"format",defaultValue:"text",public:!0},e.prefill={createComponentOfType:"text",createStateVariable:"prefill",defaultValue:"",public:!0},e.bindValueTo={createComponentOfType:"subsetOfReals"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.subsetValue={public:!0,shadowingInstructions:{createComponentOfType:"subsetOfReals"},hasEssential:!0,returnDependencies:()=>({bindValueTo:{dependencyType:"attributeComponent",attributeName:"bindValueTo",variableNames:["subsetValue"]},prefill:{dependencyType:"stateVariable",variableName:"prefill"},variable:{dependencyType:"stateVariable",variableName:"variable"},format:{dependencyType:"stateVariable",variableName:"format"}}),definition:function({dependencyValues:e}){return e.bindValueTo?{setValue:{subsetValue:e.bindValueTo.stateValues.subsetValue}}:{useEssentialOrDefaultValue:{subsetValue:{get defaultValue(){return parseValueIntoSubset({inputString:e.prefill,format:e.format,variable:e.variable})}}}}},inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t})=>t.bindValueTo?{success:!0,instructions:[{setDependency:"bindValueTo",desiredValue:e.subsetValue,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"subsetValue",value:e.subsetValue}]}},e.pointsFromSubset={additionalStateVariablesDefined:["intervalsFromSubset"],returnDependencies:()=>({subsetValue:{dependencyType:"stateVariable",variableName:"subsetValue"}}),definition({dependencyValues:e}){function t(e,t){let n=[],r=[];if(e.points&&(n=e.points),e.intervals&&(r=e.intervals),t.points){let e=n.map((e=>e.value));for(let r of t.points){let t=e.indexOf(r.value);-1===t?n.push(r):n[t].inSubset||=r.inSubset}}return t.intervals&&r.push(...t.intervals),{points:n,intervals:r}}let{points:n,intervals:r}=function e(n){if(null===n||n.isEmpty())return{};if(n instanceof theModule.Union){let r=[],a=[];for(let i of n.subsets){let n=e(i);({points:r,intervals:a}=t({points:r,intervals:a},n))}return{points:r,intervals:a}}if(n instanceof theModule.RealLine)return{intervals:[[-1/0,1/0]]};if(n instanceof theModule.Singleton)return{points:[{value:n.element,inSubset:!0}]};if(n instanceof theModule.OpenInterval){let e=[[n.left,n.right]],t=[];return Number.isFinite(n.left)&&t.push({value:n.left,inSubset:!1}),Number.isFinite(n.right)&&t.push({value:n.right,inSubset:!1}),{intervals:e,points:t}}return{}}(e.subsetValue),a=n||[],i=r||[];return a.sort(((e,t)=>e.value-t.value)),i.sort(((e,t)=>e[0]-t[0])),{setValue:{pointsFromSubset:a,intervalsFromSubset:i}}}},e.additionalPoints={defaultValue:[],hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{additionalPoints:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>e.additionalPoints.every(Number.isFinite)?{success:!0,instructions:[{setEssentialValue:"additionalPoints",value:[...e.additionalPoints].sort(((e,t)=>e-t))}]}:{success:!1}},e.points={additionalStateVariablesDefined:[{variableName:"intervals",forRenderer:!0}],forRenderer:!0,returnDependencies:()=>({pointsFromSubset:{dependencyType:"stateVariable",variableName:"pointsFromSubset"},intervalsFromSubset:{dependencyType:"stateVariable",variableName:"intervalsFromSubset"},additionalPoints:{dependencyType:"stateVariable",variableName:"additionalPoints"}}),definition({dependencyValues:e}){let t=[...e.pointsFromSubset],n=[...e.intervalsFromSubset],r=[...e.additionalPoints].sort(((e,t)=>e-t)),a=[],i=[],s=0,o=1/0,l=0;r.length>0&&(o=r[0]);let u=n[0],c=-1/0;t.push({value:1/0,inSubset:!1});for(let e of t){let t=!1;for(u&&u[0]e.value));if(!e.includes(r)){let e=!1;for(let t of i)if(t[0]r){e=!0;break}if(e)return s.push(r),await this.coreFunctions.performUpdate({updateInstructions:[{componentName:this.componentName,updateType:"updateValue",stateVariable:"additionalPoints",value:s}],actionId:t,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{addedPoint:r,intervalsFromSubset:i,pointsFromSubset:a,additionalPoints:s}}});{a.push({value:r,inSubset:!0});let e=await this.createUpdateInstructions({intervalsFromSubset:i,pointsFromSubset:a,modifiedAdditionalPoints:!1,additionalPoints:s});return await this.coreFunctions.performUpdate({updateInstructions:e,actionId:t,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{addedPoint:r,intervalsFromSubset:i,pointsFromSubset:a,additionalPoints:s}}})}}}this.coreFunctions.resolveAction({actionId:t})}async deletePoint({pointInd:e,actionId:t}){let n=await this.stateValues.points[e],r=[...await this.stateValues.additionalPoints],a=[...await this.stateValues.pointsFromSubset],i=[...await this.stateValues.intervalsFromSubset];if(n.isAdditional)return r.splice(n.additionalPointInd,1),await this.coreFunctions.performUpdate({updateInstructions:[{componentName:this.componentName,updateType:"updateValue",stateVariable:"additionalPoints",value:r}],actionId:t,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{deletedPoint:n.value,intervalsFromSubset:i,pointsFromSubset:a,additionalPoints:r}}});{let s=!1,o=a.map((e=>e.value)).indexOf(n.value),l=i.map((e=>e[1])).indexOf(n.value),u=i.map((e=>e[0])).indexOf(n.value);if(-1!==l)if(-1!==u)i[l]=[i[l][0],i[u][1]],i.splice(u,1),a.splice(o,1);else{let t=(await this.stateValues.points)[e-1];if(t&&t.isAdditional)i[l]=[i[l][0],t.value],r.splice(n.additionalPointInd,1),s=!0,a.splice(o,1,t);else if(i.splice(l,1),a.splice(o,1),t&&!t.inSubset){let e=i.map((e=>e[1])).indexOf(t.value);-1===e&&(r.push(t.value),s=!0)}}else if(-1!==u){let t=(await this.stateValues.points)[e+1];if(t&&t.isAdditional)i[u]=[t.value,i[u][1]],r.splice(n.additionalPointInd,1),s=!0,a.splice(o,1,t);else if(i.splice(u,1),a.splice(o,1),t&&!t.inSubset){let e=i.map((e=>e[0])).indexOf(t.value);-1===e&&(r.push(t.value),s=!0)}}else a.splice(o,1);let c=await this.createUpdateInstructions({intervalsFromSubset:i,pointsFromSubset:a,modifiedAdditionalPoints:s,additionalPoints:r});return await this.coreFunctions.performUpdate({updateInstructions:c,actionId:t,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{deletedPoint:n.value,intervalsFromSubset:i,pointsFromSubset:a,additionalPoints:r}}})}}async createUpdateInstructions({intervalsFromSubset:e,pointsFromSubset:t,modifiedAdditionalPoints:n,additionalPoints:r}){let a,i=await this.stateValues.dx,s=e=>Math.round(e/i)*i,o=[];for(let t of e)o.push(new theModule.OpenInterval(s(t[0]),s(t[1])));for(let e of t)e.inSubset&&o.push(new theModule.Singleton(s(e.value)));a=0===o.length?new theModule.EmptySet:1===o.length?o[0]:new theModule.Union(o);let l=[{componentName:this.componentName,updateType:"updateValue",stateVariable:"subsetValue",value:a}];return n&&l.push({componentName:this.componentName,updateType:"updateValue",stateVariable:"additionalPoints",value:r.map(s)}),l}async movePoint({pointInd:e,value:t,transient:n,actionId:r}){let a=await this.stateValues.dx,i=Math.round(Math.max(await this.stateValues.xmin,Math.min(await this.stateValues.xmax,t))/a)*a,s=await this.stateValues.points,o=s[e],l=s[e-1];l&&(i=Math.max(i,l.value+a));let u=s[e+1];u&&(i=Math.min(i,u.value-a));let c=[...await this.stateValues.additionalPoints],p=[...await this.stateValues.pointsFromSubset],d=[...await this.stateValues.intervalsFromSubset];if(o.isAdditional)return c[o.additionalPointInd]=i,n?await this.coreFunctions.performUpdate({updateInstructions:[{componentName:this.componentName,updateType:"updateValue",stateVariable:"additionalPoints",value:c}],transient:!0,actionId:r}):await this.coreFunctions.performUpdate({updateInstructions:[{componentName:this.componentName,updateType:"updateValue",stateVariable:"additionalPoints",value:c}],actionId:r,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{movedPoint:i,intervalsFromSubset:d,pointsFromSubset:p,additionalPoints:c}}});{let e=p.map((e=>e.value)).indexOf(o.value),t=d.map((e=>e[1])).indexOf(o.value),a=d.map((e=>e[0])).indexOf(o.value);p[e]={value:i,inSubset:p[e].inSubset},-1!==t&&(d[t]=[d[t][0],i]),-1!==a&&(d[a]=[i,d[a][1]]);let s=await this.createUpdateInstructions({intervalsFromSubset:d,pointsFromSubset:p,modifiedAdditionalPoints:!1});return n?await this.coreFunctions.performUpdate({updateInstructions:s,transient:!0,actionId:r}):await this.coreFunctions.performUpdate({updateInstructions:s,actionId:r,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{movedPoint:i,intervalsFromSubset:d,pointsFromSubset:p,additionalPoints:c}}})}}async togglePoint({pointInd:e,actionId:t}){let n=(await this.stateValues.points)[e],r=[...await this.stateValues.pointsFromSubset],a=[...await this.stateValues.intervalsFromSubset],i=[...await this.stateValues.additionalPoints],s=!1;if(n.isAdditional)if(i.splice(n.additionalPointInd,1),s=!0,n.inSubset){for(let[e,t]of a.entries())if(t[0]n.value){let r=[[t[0],n.value],[n.value,t[1]]];a.splice(e,1,...r);break}}else r.push({value:n.value,inSubset:!0});else{let e=r.map((e=>e.value)).indexOf(n.value),t=a.map((e=>e[1])).indexOf(n.value),o=a.map((e=>e[0])).indexOf(n.value);-1!==t?-1!==o?(a[t]=[a[t][0],a[o][1]],a.splice(o,1),r.splice(e,1),i.push(n.value),s=!0):r[e]={value:n.value,inSubset:!n.inSubset}:-1!==o?r[e]={value:n.value,inSubset:!n.inSubset}:(r.splice(e,1),i.push(n.value),s=!0)}let o=await this.createUpdateInstructions({intervalsFromSubset:a,pointsFromSubset:r,modifiedAdditionalPoints:s,additionalPoints:i});return await this.coreFunctions.performUpdate({updateInstructions:o,actionId:t,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{toggledPoint:n.value,intervalsFromSubset:a,pointsFromSubset:r,additionalPoints:i}}})}async toggleInterval({intervalInd:e,actionId:t}){let n=(await this.stateValues.intervals)[e],r=await this.stateValues.points,a=r[e-1],i=r[e],s=[...await this.stateValues.pointsFromSubset],o=[...await this.stateValues.intervalsFromSubset],l=[...await this.stateValues.additionalPoints],u=!1;if(n.inSubset){let e,t;for(let[r,a]of o.entries())if(a[0]<=n.left&&a[1]>=n.right){t=a,e=r;break}if(n.left===t[0])if(n.right===t[1]){if(o.splice(e,1),a&&!a.inSubset){let e=o.map((e=>e[1])).indexOf(a.value);if(-1===e){let e=s.map((e=>e.value)).indexOf(a.value);s.splice(e,1),l.push(a.value),u=!0}}if(i&&!i.inSubset){let e=o.map((e=>e[0])).indexOf(i.value);if(-1===e){let e=s.map((e=>e.value)).indexOf(i.value);s.splice(e,1),l.push(i.value),u=!0}}}else{if(o[e]=[n.right,t[1]],a&&!a.inSubset){let e=o.map((e=>e[1])).indexOf(a.value);if(-1===e){let e=s.map((e=>e.value)).indexOf(a.value);s.splice(e,1),l.push(a.value),u=!0}}s.push({value:i.value,inSubset:!0}),l.splice(i.additionalPointInd,1),u=!0}else if(n.right===t[1]){if(o[e]=[t[0],n.left],i&&!i.inSubset){let e=o.map((e=>e[0])).indexOf(i.value);if(-1===e){let e=s.map((e=>e.value)).indexOf(i.value);s.splice(e,1),l.push(i.value),u=!0}}s.push({value:a.value,inSubset:!0}),l.splice(a.additionalPointInd,1),u=!0}else{let r=[[t[0],n.left],[n.right,t[1]]];o.splice(e,1,...r),s.push({value:a.value,inSubset:!0}),s.push({value:i.value,inSubset:!0}),l.splice(i.additionalPointInd,1),l.splice(a.additionalPointInd,1),u=!0}}else{let e=o.map((e=>e[1])).indexOf(n.left),t=o.map((e=>e[0])).indexOf(n.right);if(-1===e)-1===t?(o.push([n.left,n.right]),i&&i.isAdditional&&(l.splice(i.additionalPointInd,1),u=!0),a&&a.isAdditional&&(l.splice(a.additionalPointInd,1),u=!0)):(i.inSubset?(o[t]=[n.left,o[t][1]],l.push(i.value),u=!0):o.push([n.left,n.right]),a&&a.isAdditional&&(l.splice(a.additionalPointInd,1),u=!0));else if(-1===t)a.inSubset?(o[e]=[o[e][0],n.right],l.push(a.value),u=!0):o.push([n.left,n.right]),i&&i.isAdditional&&(l.splice(i.additionalPointInd,1),u=!0);else if(a.inSubset)if(i.inSubset){let n=[o[e][0],o[t][1]];o.splice(e,2,n),l.push(a.value),l.push(i.value),u=!0}else o[e]=[o[e][0],n.right],l.push(a.value),u=!0;else i.inSubset?(o[t]=[n.left,o[t][1]],l.push(i.value),u=!0):o.push([n.left,n.right])}let c=await this.createUpdateInstructions({intervalsFromSubset:o,pointsFromSubset:s,modifiedAdditionalPoints:u,additionalPoints:l});return await this.coreFunctions.performUpdate({updateInstructions:c,actionId:t,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{toggledInterval:[n.left,n.right],intervalsFromSubset:o,pointsFromSubset:s,additionalPoints:l}}})}async clear({actionId:e}){let t=await this.createUpdateInstructions({intervalsFromSubset:[],pointsFromSubset:[],modifiedAdditionalPoints:!0,additionalPoints:[]});return await this.coreFunctions.performUpdate({updateInstructions:t,actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{cleared:!0,intervalsFromSubset:[],pointsFromSubset:[],additionalPoints:[]}}})}async setToR({actionId:e}){let t=await this.createUpdateInstructions({intervalsFromSubset:[[-1/0,1/0]],pointsFromSubset:[],modifiedAdditionalPoints:!0,additionalPoints:[]});return await this.coreFunctions.performUpdate({updateInstructions:t,actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{setToR:!0,intervalsFromSubset:[[-1/0,1/0]],pointsFromSubset:[],additionalPoints:[]}}})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}function parseValueIntoSubset({inputString:e,format:t,variable:n}){if(!e)return new theModule.EmptySet;let r;if("latex"===t)try{r=me$3.fromLatex(e)}catch(t){return console.warn(`Invalid latex for subsetOfRealsInput: ${e}`),new theModule.EmptySet}else if("text"===t)try{r=me$3.fromText(e)}catch(t){return console.warn(`Invalid text for subsetOfRealsInput: ${e}`),new theModule.EmptySet}return buildSubsetFromMathExpression(r,n)}class SubsetOfReals extends MathComponent{static componentType="subsetOfReals";static rendererType="math";static primaryStateVariableForDefinition="subsetValue";static createAttributesObject(){let e=super.createAttributesObject();return e.createIntervals.defaultValue=!0,e.variable={createComponentOfType:"variable",createStateVariable:"variable",defaultValue:me$3.fromAst("x")},e.displayMode={createComponentOfType:"text",createStateVariable:"displayMode",defaultValue:"intervals",public:!0,toLowerCase:!0,validValues:["intervals","inequalities"]},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return renameStateVariable({stateVariableDefinitions:e,oldName:"unnormalizedValue",newName:"unnormalizedValuePreliminary"}),e.value.shadowingInstructions.createComponentOfType="math",e.haveSingleSubsetChild={returnDependencies:()=>({mathChildren:{dependencyType:"child",childGroups:["maths"]}}),definition:({dependencyValues:e,componentInfoObjects:t})=>({setValue:{haveSingleSubsetChild:1===e.mathChildren.length&&1===e.mathChildren.filter((e=>t.isInheritedComponentType({inheritedComponentType:e.componentType,baseComponentType:"subsetOfReals"}))).length}})},e.subsetValue={stateVariablesDeterminingDependencies:["haveSingleSubsetChild"],returnDependencies({stateValues:e}){let t={haveSingleSubsetChild:{dependencyType:"stateVariable",variableName:"haveSingleSubsetChild"}};return e.haveSingleSubsetChild?t.subsetChild={dependencyType:"child",childGroups:["maths"],variableNames:["subsetValue"]}:(t.unnormalizedValuePreliminary={dependencyType:"stateVariable",variableName:"unnormalizedValuePreliminary"},t.variable={dependencyType:"stateVariable",variableName:"variable"}),t},definition({dependencyValues:e}){let t;return t=e.haveSingleSubsetChild?e.subsetChild[0].stateValues.subsetValue:buildSubsetFromMathExpression(e.unnormalizedValuePreliminary,e.variable),{setValue:{subsetValue:t}}},async inverseDefinition({desiredStateVariableValues:e,dependencyValues:t,stateValues:n}){if(t.haveSingleSubsetChild)return{success:!0,instructions:[{setDependency:"subsetChild",desiredValue:e.subsetValue,childIndex:0,variableIndex:0}]};return{success:!0,instructions:[{setDependency:"unnormalizedValuePreliminary",desiredValue:mathExpressionFromSubsetValue({subsetValue:e.subsetValue,variable:t.variable,displayMode:await n.displayMode})}]}}},e.unnormalizedValue={returnDependencies:()=>({subsetValue:{dependencyType:"stateVariable",variableName:"subsetValue"},displayMode:{dependencyType:"stateVariable",variableName:"displayMode"},variable:{dependencyType:"stateVariable",variableName:"variable"}}),definition:({dependencyValues:e})=>({setValue:{unnormalizedValue:mathExpressionFromSubsetValue(e)}}),inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t})=>({success:!0,instructions:[{setDependency:"subsetValue",desiredValue:buildSubsetFromMathExpression(e.unnormalizedValue,t.variable)}]})},e}}function mathExpressionFromSubsetValue({subsetValue:e,variable:t,displayMode:n="intervals"}){function r(e){return null===e?"_":"intervals"===n?e.closedInterval?["interval",["tuple",e.left,e.right],["tuple",!0,!0]]:e.openClosedInterval?["interval",["tuple",e.left,e.right],["tuple",!1,!0]]:e.closedOpenInterval?["interval",["tuple",e.left,e.right],["tuple",!0,!1]]:e.toMathExpression().tree:e.closedInterval?["lts",["tuple",e.left,t,e.right],["tuple",!1,!1]]:e.openClosedInterval?e.left===-1/0?["le",t,e.right]:["lts",["tuple",e.left,t,e.right],["tuple",!0,!1]]:e.closedOpenInterval?e.right===1/0?["ge",t,e.left]:["lts",["tuple",e.left,t,e.right],["tuple",!1,!0]]:e instanceof theModule.OpenInterval?e.left===-1/0?["<",t,e.right]:e.right===1/0?[">",t,e.left]:["lts",["tuple",e.left,t,e.right],["tuple",!0,!0]]:e instanceof theModule.Singleton?["=",t,e.element]:e.isEmpty()?["in",t,"∅"]:e instanceof theModule.RealLine?["in",t,"R"]:null}let a;if(e instanceof theModule.Union){let t=e.subsets.filter((e=>e instanceof theModule.Singleton)),i=e.subsets.filter((e=>e instanceof theModule.OpenInterval));for(let e=0;e(void 0===e.left?e.element:e.left)-(void 0===t.left?t.element:t.left))).map((e=>r(e)));a=s.length>1?"intervals"===n?me$3.fromAst(["union",...s]):me$3.fromAst(["or",...s]):me$3.fromAst(s[0])}else a=me$3.fromAst(r(e));return a}class Split extends CompositeComponent{static componentType="split";static assignNamesToReplacements=!0;static stateVariableToEvaluateAfterReplacements="readyToExpandWhenResolved";static createAttributesObject(){let e=super.createAttributesObject();return e.assignNamesSkip={createPrimitiveOfType:"number"},e.type={createPrimitiveOfType:"string",createStateVariable:"type",defaultPrimitiveValue:"text",toLowerCase:!0,validValues:["text"]},e.splitBy={createComponentOfType:"text",createStateVariable:"splitBy",defaultValue:"letter",toLowerCase:!0,validValues:["letter","word","comma"]},e}static returnSugarInstructions(){let e=[];return e.push({replacementFunction:function({matchedChildren:e,componentAttributes:t}){let n=t.type;return["text"].includes(n)||(n="text"),{success:!0,newChildren:[{componentType:n,children:e}]}}}),e}static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.originalValue={returnDependencies:()=>({child:{dependencyType:"child",childGroups:["anything"],variableNames:["value"]}}),definition:({dependencyValues:e})=>e.child.length>0?{setValue:{originalValue:e.child[0].stateValues.value}}:{setValue:{originalValue:null}},inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t})=>t.child.length>0?{success:!0,instructions:[{setDependency:"child",desiredValue:e.originalValue,childIndex:0,variableIndex:0}]}:{success:!1}},e.splitValues={returnDependencies:()=>({type:{dependencyType:"stateVariable",variableName:"type"},originalValue:{dependencyType:"stateVariable",variableName:"originalValue"},splitBy:{dependencyType:"stateVariable",variableName:"splitBy"}}),definition({dependencyValues:e}){if(null===e.originalValue)return{setValue:{splitValues:[]}};let t=[];return t="letter"===e.splitBy?[...e.originalValue]:"word"===e.splitBy?e.originalValue.split(/\s+/):"comma"===e.splitBy?e.originalValue.split(/\s*,\s*/):[e.originalValue],{setValue:{splitValues:t}}}},e.readyToExpandWhenResolved={returnDependencies:()=>({splitValues:{dependencyType:"stateVariable",variableName:"splitValues"}}),markStale:()=>({updateReplacements:!0}),definition:function(){return{setValue:{readyToExpandWhenResolved:!0}}}},e}static async createSerializedReplacements({component:e,componentInfoObjects:t}){let n=e.attributes.newNamespace?.primitive,r={componentType:"textList",state:{textsShadow:await e.stateValues.splitValues},downstreamDependencies:{[e.componentName]:[{dependencyType:"referenceShadow",compositeName:e.componentName,propVariable:"splitValues"}]}};return{replacements:processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:[r],parentName:e.componentName,parentCreatesNewNamespace:n,componentInfoObjects:t}).serializedComponents}}}class BestFitLine extends Line{static componentType="bestFitLine";static rendererType="line";static createAttributesObject(){let e=super.createAttributesObject();return delete e.draggable,delete e.equation,delete e.through,delete e.slope,e.points={createComponentOfType:"_pointListComponent"},e}static returnSugarInstructions(){return[]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.draggable={shadowingInstructions:{createComponentOfType:"boolean"},public:!0,forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{draggable:!1}})},e.nDimensions={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({}),definition:()=>({setValue:{nDimensions:2}})},delete e.nPointsPrescribed,delete e.basedOnSlope,delete e.dForSlope,delete e.essentialPoint1x,delete e.essentialPoint1y,delete e.equationIdentity,delete e.equation.stateVariablesDeterminingDependencies,e.equation.returnDependencies=()=>({points:{dependencyType:"attributeComponent",attributeName:"points",variableNames:["points","nDimensions"]},variables:{dependencyType:"stateVariable",variableName:"variables"}}),e.equation.definition=function({dependencyValues:e}){if(!e.points||e.points.stateValues.nDimensions<2||e.points.stateValues.points.length<1){let e=me$3.fromAst("_");return{setValue:{equation:e,coeff0:e,coeffvar1:e,coeffvar2:e}}}let t=[],n=[];for(let r of e.points.stateValues.points){let e=r.slice(0,2).map((e=>e&&e.evaluate_to_constant()));e.every(Number.isFinite)&&(t.push([1,e[0]]),n.push([e[1]]))}if(0===t.length){let e=me$3.fromAst("_");return{setValue:{equation:e,coeff0:e,coeffvar1:e,coeffvar2:e}}}t=me$3.math.matrix(t),n=me$3.math.matrix(n);let r=me$3.math.transpose(t),a=me$3.math.multiply(r,n),i=me$3.math.multiply(r,t),s=me$3.math.lusolve(i,a),o=me$3.fromAst(me$3.math.subset(s,me$3.math.index(0,0))),l=me$3.fromAst(me$3.math.subset(s,me$3.math.index(1,0))),u=me$3.fromAst(-1),c=e.variables,p=me$3.fromAst(["+",["*","a","x"],"c"]).substitute({a:l,c:o,x:c[0],y:c[1]}).simplify();return{setValue:{equation:me$3.fromAst(["=","y","r"]).substitute({r:p}),coeff0:o,coeffvar1:l,coeffvar2:u}}},delete e.equation.inverseDefinition,delete e.points.stateVariablesDeterminingDependencies,e.points.returnArrayDependenciesByKey=function(){return{globalDependencies:{coeff0:{dependencyType:"stateVariable",variableName:"coeff0"},coeffvar1:{dependencyType:"stateVariable",variableName:"coeffvar1"},coeffvar2:{dependencyType:"stateVariable",variableName:"coeffvar2"},variables:{dependencyType:"stateVariable",variableName:"variables"},lastPointsFromInverting:{dependencyType:"stateVariable",variableName:"lastPointsFromInverting"}}}},e}}class RegionBetweenCurveXAxis extends GraphicalComponent{static componentType="regionBetweenCurveXAxis";static createAttributesObject(){let e=super.createAttributesObject();return e.boundaryValues={createComponentOfType:"numberList",createStateVariable:"boundaryValues",defaultValue:[0,1],forRenderer:!0,public:!0},e.function={createComponentOfType:"function"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescription:e.selectedStyle.fillColorWord}}}},e.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({styleDescription:{dependencyType:"stateVariable",variableName:"styleDescription"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescriptionWithNoun:e.styleDescription+" region"}}}},e.function={additionalStateVariablesDefined:[{variableName:"haveFunction",forRenderer:!0},{variableName:"fDefinition",forRenderer:!0}],returnDependencies:()=>({functionAttr:{dependencyType:"attributeComponent",attributeName:"function",variableNames:["numericalfs","nInputs","nOutputs","fDefinition"]}}),definition:({dependencyValues:e})=>null===e.functionAttr||1!==e.functionAttr.stateValues.nInputs||1!==e.functionAttr.stateValues.nOutputs?{setValue:{function:()=>NaN,haveFunction:!1,fDefinition:{}}}:{setValue:{function:e.functionAttr.stateValues.numericalfs[0],haveFunction:!0,fDefinition:e.functionAttr.stateValues.fDefinition}}},e}}class RegionHalfPlane extends GraphicalComponent{static componentType="regionHalfPlane";static rendererType=void 0;static createAttributesObject(){let e=super.createAttributesObject();return e.horizontal={createComponentOfType:"boolean",createStateVariable:"horizontal",defaultValue:!0,public:!0},e.boundaryValue={createComponentOfType:"number",createStateVariable:"boundaryValue",defaultValue:0,public:!0},e.greaterThan={createComponentOfType:"boolean",createStateVariable:"greaterThan",defaultValue:!0,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nearestPoint={returnDependencies:()=>({horizontal:{dependencyType:"stateVariable",variableName:"horizontal"},boundaryValue:{dependencyType:"stateVariable",variableName:"boundaryValue"},greaterThan:{dependencyType:"stateVariable",variableName:"greaterThan"}}),definition({dependencyValues:e}){let t=e.boundaryValue;return{setValue:{nearestPoint:function({variables:n,scales:r}){if(!Number.isFinite(t))return{};if(e.horizontal){if(e.greaterThan){if(n.x1t){let e=Object.assign({},n);return e.x1=t,e}return{}}if(e.greaterThan){if(n.x2t){let e=Object.assign({},n);return e.x2=t,e}return{}}}}}},e}}class CodeEditor extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{updateImmediateValue:this.updateImmediateValue.bind(this),updateValue:this.updateValue.bind(this),updateComponents:this.updateComponents.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="codeEditor";static variableForPlainMacro="value";static variableForPlainCopy="value";static renderChildren=!0;static processWhenJustUpdatedForNewComponent=!0;static get stateVariablesShadowedForReference(){return["value"]}static createAttributesObject(){let e=super.createAttributesObject();return e.prefill={createComponentOfType:"text",createStateVariable:"prefill",defaultValue:"",public:!0},e.bindValueTo={createComponentOfType:"text"},e.width={createComponentOfType:"_componentSize",createStateVariable:"width",defaultValue:{size:600,isAbsolute:!0},forRenderer:!0,public:!0},e.height={createComponentOfType:"_componentSize",createStateVariable:"height",defaultValue:{size:400,isAbsolute:!0},forRenderer:!0,public:!0},e.viewerRatio={createComponentOfType:"number",createStateVariable:"viewerRatio",defaultValue:.5,forRenderer:!0,public:!0},e.showResults={createComponentOfType:"boolean",createStateVariable:"showResults",defaultValue:!1,forRenderer:!0,public:!0},e.renderedName={createPrimitiveOfType:"string"},e.staticName={createPrimitiveOfType:"string"},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e,componentAttributes:t}){if(e.length>0)return{success:!1};let n={componentType:"codeViewer",children:[{componentType:"renderDoenetML"}]},r=[n];if(t.renderedName&&(n.attributes={renderedName:{primitive:t.renderedName}},n.children[0].props={name:t.renderedName}),t.staticName){let e={componentType:"codeViewer",attributes:{hide:{component:{componentType:"boolean",state:{value:!0}}}},children:[{componentType:"renderDoenetML",props:{name:t.staticName}}]};r.push(e)}return{success:!0,newChildren:r}}}),e}static returnChildGroups(){return[{group:"codeViewers",componentTypes:["codeViewer"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.viewerHeight={returnDependencies:()=>({height:{dependencyType:"stateVariable",variableName:"height"},viewerRatio:{dependencyType:"stateVariable",variableName:"viewerRatio"}}),definition:function({dependencyValues:e}){if(!e.height.isAbsolute)throw Error("Codeeditor relative height not implemented");return{setValue:{viewerHeight:{size:e.height.size*e.viewerRatio,isAbsolute:!0}}}}},e.value={public:!0,shadowingInstructions:{createComponentOfType:"text"},hasEssential:!0,forRenderer:!0,returnDependencies:()=>({bindValueTo:{dependencyType:"attributeComponent",attributeName:"bindValueTo",variableNames:["value"]},prefill:{dependencyType:"stateVariable",variableName:"prefill"}}),definition:function({dependencyValues:e}){return e.bindValueTo?{setValue:{value:e.bindValueTo.stateValues.value}}:{useEssentialOrDefaultValue:{value:{variablesToCheck:"value",defaultValue:e.prefill}}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){return t.bindValueTo?{success:!0,instructions:[{setDependency:"bindValueTo",desiredValue:e.value,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"value",value:e.value}]}}},e.immediateValue={public:!0,shadowingInstructions:{createComponentOfType:"text"},hasEssential:!0,forRenderer:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:function({dependencyValues:e,changes:t,justUpdatedForNewComponent:n}){return t.value&&!n?{setValue:{immediateValue:e.value},makeEssential:{immediateValue:!0}}:{useEssentialOrDefaultValue:{immediateValue:{variablesToCheck:"immediateValue",defaultValue:e.value}}}},inverseDefinition:function({desiredStateVariableValues:e,initialChange:t,shadowedVariable:n}){let r=[{setEssentialValue:"immediateValue",value:e.immediateValue}];return t||n||r.push({setDependency:"value",desiredValue:e.immediateValue}),{success:!0,instructions:r}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:function({dependencyValues:e}){return{setValue:{text:e.value}}}},e.componentType={returnDependencies:()=>({}),definition:()=>({setValue:{componentType:"text"}})},e.viewerChild={returnDependencies:()=>({viewerChild:{dependencyType:"child",childGroups:["codeViewers"]}}),definition:({dependencyValues:e})=>e.viewerChild.length>0?{setValue:{viewerChild:e.viewerChild}}:{setValue:{viewerChild:null}}},e}updateImmediateValue({text:e,actionId:t}){if(!this.stateValues.disabled)return this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"immediateValue",value:e},{updateType:"setComponentNeedingUpdateValue",componentName:this.componentName}],actionId:t});this.coreFunctions.resolveAction({actionId:t})}updateValue({actionId:e}){if(!this.stateValues.disabled&&this.stateValues.immediateValue!==this.stateValues.value){let t=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"value",value:this.stateValues.immediateValue},{updateType:"executeUpdate"},{updateType:"updateValue",componentName:this.componentName,stateVariable:"immediateValue",valueOfStateVariable:"value"},{updateType:"unsetComponentNeedingUpdateValue"}],n={verb:"answered",object:{componentName:this.componentName,componentType:this.componentType},result:{response:this.stateValues.immediateValue,responseText:this.stateValues.immediateValue}};return this.stateValues.answerAncestor&&(n.context={answerAncestor:this.stateValues.answerAncestor.componentName}),this.coreFunctions.performUpdate({updateInstructions:t,actionId:e,event:n}).then((()=>{this.coreFunctions.triggerChainedActions({componentName:this.componentName}),this.attributes.staticName&&2===this.definingChildren.length&&"codeViewer"===this.definingChildren[1].componentType&&this.coreFunctions.performAction({componentName:this.definingChildren[1].componentName,actionName:"updateComponents"})}))}this.coreFunctions.resolveAction({actionId:e})}async updateComponents(){1===this.definingChildren.length&&"codeViewer"===this.definingChildren[0].componentType&&await this.coreFunctions.performAction({componentName:this.definingChildren[0].componentName,actionName:"updateComponents"})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class CodeViewer extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{updateComponents:this.updateComponents.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="codeViewer";static renderChildren=!0;static includeBlankStringChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.codeSource={createTargetComponentNames:!0},e.width={createComponentOfType:"_componentSize"},e.height={createComponentOfType:"_componentSize"},e.hasCodeEditorParent={createComponentOfType:"boolean"},e.renderedName={createPrimitiveOfType:"string"},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e,componentAttributes:t}){if(e.length>0)return{success:!1};let n={componentType:"renderDoenetML"};return t.codeSource&&(n.attributes={codeSource:{targetComponentNames:t.codeSource}}),t.renderedName&&(n.props={name:t.renderedName}),{success:!0,newChildren:[n]}}}),e}static returnChildGroups(){return[{group:"children",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.hasCodeEditorParent={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,returnDependencies:()=>({codeEditorParent:{dependencyType:"parentIdentity",parentComponentType:"codeEditor"}}),definition:function({dependencyValues:e}){return e.codeEditorParent?{setValue:{hasCodeEditorParent:!0}}:{setValue:{hasCodeEditorParent:!1}}}},e.width={public:!0,shadowingInstructions:{createComponentOfType:"_componentSize"},hasEssential:!0,forRenderer:!0,defaultValue:{size:600,isAbsolute:!0},returnDependencies:()=>({widthAttr:{dependencyType:"attributeComponent",attributeName:"width",variableNames:["componentSize"]},parentWidth:{dependencyType:"parentStateVariable",variableName:"width",parentComponentType:"codeEditor"}}),definition:function({dependencyValues:e}){return e.widthAttr?{setValue:{width:e.widthAttr.stateValues.componentSize}}:e.parentWidth?{setValue:{width:e.parentWidth}}:{useEssentialOrDefaultValue:{width:!0}}}},e.height={public:!0,shadowingInstructions:{createComponentOfType:"_componentSize"},hasEssential:!0,forRenderer:!0,defaultValue:{size:400,isAbsolute:!0},returnDependencies:()=>({heightAttr:{dependencyType:"attributeComponent",attributeName:"height",variableNames:["componentSize"]},parentViewerHeight:{dependencyType:"parentStateVariable",variableName:"viewerHeight",parentComponentType:"codeEditor"}}),definition:function({dependencyValues:e}){return e.heightAttr?{setValue:{height:e.heightAttr.stateValues.componentSize}}:e.parentViewerHeight?{setValue:{height:e.parentViewerHeight}}:{useEssentialOrDefaultValue:{height:!0}}}},e.codeSourceComponentName={returnDependencies:()=>({codeSource:{dependencyType:"attributeTargetComponentNames",attributeName:"codeSource"}}),definition({dependencyValues:e}){let t;return t=1===e.codeSource?.length?e.codeSource[0].absoluteName:null,{setValue:{codeSourceComponentName:t}}}},e.codeSource={returnDependencies:()=>({codeSourceComponentName:{dependencyType:"stateVariable",variableName:"codeSourceComponentName"},codeEditorParent:{dependencyType:"parentIdentity",parentComponentType:"codeEditor"}}),definition:function({dependencyValues:e}){return e.codeSourceComponentName?{setValue:{codeSource:e.codeSourceComponentName}}:e.codeEditorParent?{setValue:{codeSource:e.codeEditorParent.componentName}}:{setValue:{codeSource:null}}}},e}async updateComponents(){1===this.definingChildren.length&&"renderDoenetML"===this.definingChildren[0].componentType&&await this.coreFunctions.performAction({componentName:this.definingChildren[0].componentName,actionName:"updateComponents"})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class RenderDoenetML extends CompositeComponent{constructor(e){super(e),Object.assign(this.actions,{updateComponents:this.updateComponents.bind(this)})}static componentType="renderDoenetML";static assignNamesToReplacements=!0;static createsVariants=!0;static stateVariableToEvaluateAfterReplacements="triggerUpdates";static createAttributesObject(){let e=super.createAttributesObject();return e.assignNamesSkip={createPrimitiveOfType:"number"},e.codeSource={createTargetComponentNames:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.codeSourceComponentName={returnDependencies:()=>({codeSource:{dependencyType:"attributeTargetComponentNames",attributeName:"codeSource"}}),definition({dependencyValues:e}){let t;return t=1===e.codeSource?.length?e.codeSource[0].absoluteName:null,{setValue:{codeSourceComponentName:t}}}},e.codeSource={returnDependencies:()=>({codeSourceComponentName:{dependencyType:"stateVariable",variableName:"codeSourceComponentName"},parentCodeSource:{dependencyType:"parentStateVariable",parentComponentType:"codeViewer",variableName:"codeSource"}}),definition:function({dependencyValues:e}){return e.codeSourceComponentName?{setValue:{codeSource:e.codeSourceComponentName}}:e.parentCodeSource?{setValue:{codeSource:e.parentCodeSource}}:{setValue:{codeSource:null}}}},e.doenetML={stateVariablesDeterminingDependencies:["codeSource"],returnDependencies:({stateValues:e})=>({doenetML:{dependencyType:"stateVariable",componentName:e.codeSource,variableName:"text",variablesOptional:!0}}),definition({dependencyValues:e}){let t="";return e.doenetML&&(t=e.doenetML,"string"!=typeof t&&(t="")),{setValue:{doenetML:t}}}},e.readyToExpandWhenResolved={returnDependencies:()=>({doenetML:{dependencyType:"stateVariable",variableName:"doenetML"}}),definition:()=>({setValue:{readyToExpandWhenResolved:!0}})},e.triggerUpdates={defaultValue:!0,hasEssential:!0,returnDependencies:()=>({}),markStale:()=>({updateReplacements:!0}),definition:()=>({useEssentialOrDefaultValue:{triggerUpdates:{}}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"triggerUpdates",value:e.triggerUpdates}]})},e.isVariantComponent={returnDependencies:()=>({}),definition:()=>({setValue:{isVariantComponent:!0}})},e.generatedVariantInfo={returnDependencies:({sharedParameters:e,componentInfoObjects:t})=>({variantSeed:{dependencyType:"value",value:e.variantSeed},variantDescendants:{dependencyType:"descendant",componentTypes:Object.keys(t.componentTypesCreatingVariants),variableNames:["isVariantComponent","generatedVariantInfo"],useReplacementsForComposites:!0,recurseToMatchedChildren:!1,variablesOptional:!0,includeNonActiveChildren:!0,ignoreReplacementsOfEncounteredComposites:!0}}),definition({dependencyValues:e,componentName:t}){let n={seed:e.variantSeed,meta:{createdBy:t}},r=n.subvariants=[];for(let t of e.variantDescendants)t.stateValues.isVariantComponent?r.push(t.stateValues.generatedVariantInfo):t.stateValues.generatedVariantInfo&&r.push(...t.stateValues.generatedVariantInfo.subvariants);return{setValue:{generatedVariantInfo:n}}}},e}static async createSerializedReplacements({component:e,componentInfoObjects:t,flags:n,workspace:r}){let a=[],i=(await e.stateValues.doenetML).trim();r.previousDoenetML=i;try{a=(await expandDoenetMLsToFullSerializedComponents({cids:[],doenetMLs:[i],componentInfoObjects:t,flags:n})).fullSerializedComponents[0]}catch(e){return console.warn("error in user entered doenetML"),console.warn(e.message),{replacements:[]}}let s=e.componentName.split("/").map((e=>({namespace:e,componentCounts:{},namesUsed:{}})));return createComponentNames({serializedComponents:a,componentInfoObjects:t,namespaceStack:s}),restrictTNamesToNamespace({components:a,namespace:`${e.componentName}/`}),{replacements:processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:a,parentName:e.componentName,parentCreatesNewNamespace:!0,componentInfoObjects:t,originalNamesAreConsistent:!0}).serializedComponents}}static async calculateReplacementChanges({component:e,componentChanges:t,componentInfoObjects:n,flags:r,workspace:a}){let i=(await e.stateValues.doenetML).trim();if(a.previousDoenetML===i)return[];a.previousDoenetML=i;let s=(await this.createSerializedReplacements({component:e,componentInfoObjects:n,flags:r,workspace:a})).replacements;return[{changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:0,numberReplacementsToReplace:e.replacements.length,serializedReplacements:s}]}static setUpVariant({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n}){setUpVariantSeedAndRng({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n,useSubpartVariantRng:!0})}async updateComponents({actionId:e}){let t=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"triggerUpdates",value:!0}];await this.coreFunctions.performUpdate({updateInstructions:t,actionId:e})}}class HasSameFactoring extends BooleanComponent{static componentType="hasSameFactoring";static rendererType="boolean";static createAttributesObject(){let e=super.createAttributesObject();return e.variable={createComponentOfType:"variable",createStateVariable:"variable",defaultValue:me$3.fromAst("x")},e.restrictDivision={createComponentOfType:"boolean",createStateVariable:"restrictDivision",defaultValue:!1},e.monomialFactorMustMatch={createComponentOfType:"boolean",createStateVariable:"monomialFactorMustMatch",defaultValue:!1},e.allowOnlySignDifferences={createComponentOfType:"boolean",createStateVariable:"allowOnlySignDifferences",defaultValue:!1},e}static returnChildGroups(){return[{group:"maths",componentTypes:["math"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return delete e.parsedExpression,delete e.mathChildrenByCode,e.value={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,returnDependencies:()=>({mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]},allowedErrorInNumbers:{dependencyType:"stateVariable",variableName:"allowedErrorInNumbers"},includeErrorInNumberExponents:{dependencyType:"stateVariable",variableName:"includeErrorInNumberExponents"},allowedErrorIsAbsolute:{dependencyType:"stateVariable",variableName:"allowedErrorIsAbsolute"},nSignErrorsMatched:{dependencyType:"stateVariable",variableName:"nSignErrorsMatched"},variable:{dependencyType:"stateVariable",variableName:"variable"},restrictDivision:{dependencyType:"stateVariable",variableName:"restrictDivision"},monomialFactorMustMatch:{dependencyType:"stateVariable",variableName:"monomialFactorMustMatch"},allowOnlySignDifferences:{dependencyType:"stateVariable",variableName:"allowOnlySignDifferences"}}),definition:function({dependencyValues:e}){if(2!==e.mathChildren.length)return{setValue:{value:!1}};let t=e.mathChildren[0].stateValues.value,n=e.mathChildren[1].stateValues.value;if(1!==checkEquality({object1:t,object2:n,isUnordered:!1,partialMatches:!1,symbolicEquality:!1,allowedErrorInNumbers:e.allowedErrorInNumbers,includeErrorInNumberExponents:e.includeErrorInNumberExponents,allowedErrorIsAbsolute:e.allowedErrorIsAbsolute,nSignErrorsMatched:e.nSignErrorsMatched}).fraction_equal)return{setValue:{value:!1}};if(Array.isArray(t.tree)&&"-"===t.tree[0]&&(t=me$3.fromAst(t.tree[1])),Array.isArray(n.tree)&&"-"===n.tree[0]&&(n=me$3.fromAst(n.tree[1])),e.restrictDivision||e.monomialFactorMustMatch||e.allowOnlySignDifferences||(Array.isArray(t.tree)&&"/"===t.tree[0]&&0===me$3.fromAst(t.tree[2]).variables().length&&(t=me$3.fromAst(t.tree[1]),Array.isArray(t.tree)&&"-"===t.tree[0]&&(t=me$3.fromAst(t.tree[1]))),Array.isArray(n.tree)&&"/"===n.tree[0]&&0===me$3.fromAst(n.tree[2]).variables().length&&(n=me$3.fromAst(n.tree[1]),Array.isArray(n.tree)&&"-"===n.tree[0]&&(n=me$3.fromAst(n.tree[1])))),t=me$3.fromAst(expandPositiveIntegerPowers(t.tree)),n=me$3.fromAst(expandPositiveIntegerPowers(n.tree)),!Array.isArray(t.tree)||"*"!==t.tree[0])return Array.isArray(n.tree)&&"*"===n.tree[0]?{setValue:{value:!1}}:{setValue:{value:!0}};if(!Array.isArray(n.tree)||"*"!==n.tree[0])return{setValue:{value:!1}};if(e.monomialFactorMustMatch||e.allowOnlySignDifferences){let e=findMonomialFromFactors(t.tree.slice(1)),r=findMonomialFromFactors(n.tree.slice(1));if(!e.equals(r)){let t=me$3.fromAst(["-",r.tree]);if(!e.equals(t))return{setValue:{value:!1}}}}if(e.allowOnlySignDifferences){let r=normalizeFactorSigns(t),a=normalizeFactorSigns(n);return{setValue:{value:r.equalsViaSyntax(a,{allowed_error_in_numbers:e.allowedErrorInNumbers,include_error_in_number_exponents:e.includeErrorInNumberExponents,allowed_error_is_absolute:e.allowedErrorIsAbsolute})}}}let r=t.tree.slice(1).filter((e=>me$3.fromAst(e).variables().length>0)),a=n.tree.slice(1).filter((e=>me$3.fromAst(e).variables().length>0));if(r.length!==a.length)return{setValue:{value:!1}};let i=0,s=0,o=0,l=0,u=e.variable.subscripts_to_strings().tree;for(let e of r){let t=me$3.fromAst(e).subscripts_to_strings().derivative(u).derivative(u).simplify();if(0===t.tree)s++;else{if(0!==t.variables().length)return{setValue:{value:!1}};i++}}for(let e of a){let t=me$3.fromAst(e).subscripts_to_strings().derivative(u).derivative(u).simplify();if(0===t.tree)l++;else{if(0!==t.variables().length)return{setValue:{value:!1}};o++}}return{setValue:{value:s===l&&i===o}}}},e}}function expandPositiveIntegerPowers(e){if(!Array.isArray(e))return e;if("^"===e[0]){let t=e[1],n=e[2];Number.isInteger(n)&&n>0&&(e=["*",...Array(n).fill(t)])}if("*"===e[0]){let t=e;e=["*"];for(let n of t.slice(1))if(Array.isArray(n)&&"^"===n[0]){let t=n[1],r=n[2];Number.isInteger(r)&&r>0?e.push(...Array(r).fill(t)):e.push(n)}else e.push(n)}return e}function findMonomialFromFactors(e){let t,n=[],r=!1;for(let t of e)if("string"==typeof t||0===me$3.fromAst(t).variables().length){if(!r){if(n.length>0)return me$3.fromAst("_");r=!0}n.push(t)}else r=!1;return t=0===n.length?1:1===n.length?n[0]:["*",...n],me$3.fromAst(t)}function normalizeFactorSigns(e){let t=e.simplify().tree;if("-"===t[0]&&(t=t[1]),"*"!==t[0])return me$3.fromAst(t).simplify();let n=["*"];for(let e of t.slice(1))if("number"==typeof e)e<0?n.push(-e):n.push(e);else if(Array.isArray(e))if("-"===e[0])n.push(e[1]);else if("+"===e[0]){let t=!1,r=e[1];if("number"==typeof r)r<0&&(t=!0);else if(Array.isArray(r))if("-"===r[0])t=!0;else if("*"===r[0]){let e=r[1];"number"==typeof e?e<0&&(t=!0):Array.isArray(e)&&"-"===e[0]&&(t=!0)}t?n.push(me$3.fromAst(["-",e]).simplify().tree):n.push(e)}else n.push(e);else n.push(e);return me$3.fromAst(n).simplify()}class DataFrame extends BaseComponent{static componentType="dataFrame";static rendererType=void 0;static createAttributesObject(){let e=super.createAttributesObject();return e.source={createComponentOfType:"text",createStateVariable:"source",required:!0,public:!0,forRenderer:!0},e.hasHeader={createComponentOfType:"boolean",createStateVariable:"hasHeader",defaultValue:!0,public:!0},e.columnTypes={createComponentOfType:"textList",createStateVariable:"columnTypesPrelim",defaultValue:[]},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.cid={forRenderer:!0,returnDependencies:()=>({source:{dependencyType:"stateVariable",variableName:"source"}}),definition:function({dependencyValues:e}){if(!e.source||"doenet:"!==e.source.substring(0,7).toLowerCase())return{setValue:{cid:null}};let t=null,n=e.source.match(/[:&]cid=([^&]+)/i);return n&&(t=n[1]),{setValue:{cid:t}}}},e.dataFrame={stateVariablesDeterminingDependencies:["cid","source"],additionalStateVariablesDefined:[{variableName:"numRows",public:!0,shadowingInstructions:{createComponentOfType:"integer"}},{variableName:"numColumns",public:!0,shadowingInstructions:{createComponentOfType:"integer"}},{variableName:"columnTypes",public:!0,shadowingInstructions:{createComponentOfType:"textList"}},{variableName:"columnNames",public:!0,shadowingInstructions:{createComponentOfType:"textList"}}],returnDependencies:({stateValues:e})=>({fileContents:{dependencyType:"file",cid:e.cid,uri:e.source,fileType:"csv"},hasHeader:{dependencyType:"stateVariable",variableName:"hasHeader"},columnTypesPrelim:{dependencyType:"stateVariable",variableName:"columnTypesPrelim"}}),definition:function({dependencyValues:e,componentName:t}){let n=[],r=[],a=e.fileContents.trim().split("\n").map((e=>e.trim().split(",").map((e=>e.trim())))),i=a[0]?.length,s=!1;for(let e of a.slice(1))if(e.length!==i){s=!0;break}if(s)return console.warn(`Data has invalid shape. Rows has inconsistent lengths. Found in componentName :${t}`),{setValue:{dataFrame:null,numRows:u,numColumns:i,columnTypes:n,columnNames:r}};let o={},l=[];if(e.hasHeader?(o.columnNames=a[0].map((e=>(['"',"'"].includes(e[0])&&e[e.length-1]===e[0]&&(e=e.substring(1,e.length-1)),e))),l=a.slice(1)):(o.columnNames=[...Array(i).keys()].map((e=>`col${e+1}`)),l=a),[...new Set(o.columnNames)].length({numColumns:{dependencyType:"stateVariable",variableName:"numColumns"}}),returnArraySize:({dependencyValues:e})=>[e.numColumns],returnArrayDependenciesByKey:()=>({globalDependencies:{dataFrame:{dependencyType:"stateVariable",variableName:"dataFrame"},numColumns:{dependencyType:"stateVariable",variableName:"numColumns"},numRows:{dependencyType:"stateVariable",variableName:"numRows"},columnTypes:{dependencyType:"stateVariable",variableName:"columnTypes"}}}),arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t}){let n={};for(let r of t){let t=0,a=0;if("number"===e.columnTypes[r]){for(let n=0;n({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.displayDigitsAttr){let n=t.displayDigitsAttr,r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!n&&!r){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({statisticsToDisplayPrelim:{dependencyType:"stateVariable",variableName:"statisticsToDisplayPrelim"}}),definition:function({dependencyValues:e}){let t=["mean","stdev","variance","stderr","count","minimum","quartile1","median","quartile3","maximum","range","sum"],n=[],r=e.statisticsToDisplayPrelim.map((e=>e.toLowerCase()));if(r.includes("default"))n=["mean","stdev","count","minimum","quartile1","median","quartile3","maximum"];else if(r.includes("all"))n=[...t];else for(let e of t)r.includes(e)&&n.push(e);return{setValue:{statisticsToDisplay:n}}}},e.sourceName={returnDependencies:()=>({source:{dependencyType:"attributeTargetComponentNames",attributeName:"source"}}),definition({dependencyValues:e}){let t;return t=1===e.source?.length?e.source[0].absoluteName:null,{setValue:{sourceName:t}}}},e.dataColumn={stateVariablesDeterminingDependencies:["sourceName"],additionalStateVariablesDefined:[{variableName:"columnName",public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0}],returnDependencies:({stateValues:e})=>({dataFrame:{dependencyType:"stateVariable",componentName:e.sourceName,variableName:"dataFrame",variableOptional:!0},desiredColumn:{dependencyType:"stateVariable",variableName:"desiredColumn"}}),definition({dependencyValues:e}){let t=null,n=null;if(e.dataFrame){let r=e.dataFrame,a=r.columnNames.indexOf(e.desiredColumn);if(-1!==a){n=e.desiredColumn,t=[];for(let e of r.data)null!==e[a]&&t.push(e[a])}}return{setValue:{dataColumn:t,columnName:n}}}},e.count={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({dataColumn:{dependencyType:"stateVariable",variableName:"dataColumn"}}),definition({dependencyValues:e}){let t=null;return e.dataColumn&&(t=e.dataColumn.length),{setValue:{count:t}}}},e.sum={public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]},returnDependencies:()=>({dataColumn:{dependencyType:"stateVariable",variableName:"dataColumn"}}),definition({dependencyValues:e}){let t=null;return e.dataColumn&&(t=e.dataColumn.reduce(((e,t)=>e+t))),{setValue:{sum:t}}}},e.mean={public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]},returnDependencies:()=>({dataColumn:{dependencyType:"stateVariable",variableName:"dataColumn"}}),definition({dependencyValues:e}){let t=null;return null!==e.dataColumn&&(t=me$3.math.mean(e.dataColumn)),{setValue:{mean:t}}}},e.stdev={public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]},returnDependencies:()=>({dataColumn:{dependencyType:"stateVariable",variableName:"dataColumn"}}),definition({dependencyValues:e}){let t=null;return e.dataColumn&&(t=me$3.math.std(e.dataColumn)),{setValue:{stdev:t}}}},e.variance={public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]},returnDependencies:()=>({dataColumn:{dependencyType:"stateVariable",variableName:"dataColumn"}}),definition({dependencyValues:e}){let t=null;return e.dataColumn&&(t=me$3.math.variance(e.dataColumn)),{setValue:{variance:t}}}},e.stderr={public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]},returnDependencies:()=>({stdev:{dependencyType:"stateVariable",variableName:"stdev"},count:{dependencyType:"stateVariable",variableName:"count"}}),definition({dependencyValues:e}){let t=null;return null!==e.stdev&&(t=e.stdev/Math.sqrt(e.count)),{setValue:{stderr:t}}}},e.minimum={public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]},returnDependencies:()=>({dataColumn:{dependencyType:"stateVariable",variableName:"dataColumn"}}),definition({dependencyValues:e}){let t=null;return e.dataColumn&&(t=Math.min(...e.dataColumn)),{setValue:{minimum:t}}}},e.maximum={public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]},returnDependencies:()=>({dataColumn:{dependencyType:"stateVariable",variableName:"dataColumn"}}),definition({dependencyValues:e}){let t=null;return e.dataColumn&&(t=Math.max(...e.dataColumn)),{setValue:{maximum:t}}}},e.median={public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]},returnDependencies:()=>({dataColumn:{dependencyType:"stateVariable",variableName:"dataColumn"}}),definition({dependencyValues:e}){let t=null;return e.dataColumn&&(t=me$3.math.median(e.dataColumn)),{setValue:{median:t}}}},e.quartile1={public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]},returnDependencies:()=>({dataColumn:{dependencyType:"stateVariable",variableName:"dataColumn"}}),definition({dependencyValues:e}){let t=null;return e.dataColumn&&(t=me$3.math.quantileSeq(e.dataColumn,.25)),{setValue:{quartile1:t}}}},e.quartile3={public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]},returnDependencies:()=>({dataColumn:{dependencyType:"stateVariable",variableName:"dataColumn"}}),definition({dependencyValues:e}){let t=null;return e.dataColumn&&(t=me$3.math.quantileSeq(e.dataColumn,.75)),{setValue:{quartile3:t}}}},e.range={public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]},returnDependencies:()=>({minimum:{dependencyType:"stateVariable",variableName:"minimum"},maximum:{dependencyType:"stateVariable",variableName:"maximum"}}),definition({dependencyValues:e}){let t=null;return null!==e.minimum&&(t=e.maximum-e.minimum),{setValue:{range:t}}}},e.summaryStatistics={forRenderer:!0,stateVariablesDeterminingDependencies:["statisticsToDisplay"],returnDependencies({stateValues:e}){let t={displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"}};return e.statisticsToDisplay.includes("mean")&&(t.mean={dependencyType:"stateVariable",variableName:"mean"}),e.statisticsToDisplay.includes("stdev")&&(t.stdev={dependencyType:"stateVariable",variableName:"stdev"}),e.statisticsToDisplay.includes("variance")&&(t.variance={dependencyType:"stateVariable",variableName:"variance"}),e.statisticsToDisplay.includes("stderr")&&(t.stderr={dependencyType:"stateVariable",variableName:"stderr"}),e.statisticsToDisplay.includes("count")&&(t.count={dependencyType:"stateVariable",variableName:"count"}),e.statisticsToDisplay.includes("minimum")&&(t.minimum={dependencyType:"stateVariable",variableName:"minimum"}),e.statisticsToDisplay.includes("quartile1")&&(t.quartile1={dependencyType:"stateVariable",variableName:"quartile1"}),e.statisticsToDisplay.includes("median")&&(t.median={dependencyType:"stateVariable",variableName:"median"}),e.statisticsToDisplay.includes("quartile3")&&(t.quartile3={dependencyType:"stateVariable",variableName:"quartile3"}),e.statisticsToDisplay.includes("maximum")&&(t.maximum={dependencyType:"stateVariable",variableName:"maximum"}),e.statisticsToDisplay.includes("range")&&(t.range={dependencyType:"stateVariable",variableName:"range"}),e.statisticsToDisplay.includes("sum")&&(t.sum={dependencyType:"stateVariable",variableName:"sum"}),t},definition({dependencyValues:e,usedDefault:t}){let n={};return void 0!==e.mean&&(n.mean=roundForDisplay({value:e.mean,dependencyValues:e,usedDefault:t})),void 0!==e.stdev&&(n.stdev=roundForDisplay({value:e.stdev,dependencyValues:e,usedDefault:t})),void 0!==e.variance&&(n.variance=roundForDisplay({value:e.variance,dependencyValues:e,usedDefault:t})),void 0!==e.stderr&&(n.stderr=roundForDisplay({value:e.stderr,dependencyValues:e,usedDefault:t})),void 0!==e.count&&(n.count=roundForDisplay({value:e.count,dependencyValues:e,usedDefault:t})),void 0!==e.minimum&&(n.minimum=roundForDisplay({value:e.minimum,dependencyValues:e,usedDefault:t})),void 0!==e.quartile1&&(n.quartile1=roundForDisplay({value:e.quartile1,dependencyValues:e,usedDefault:t})),void 0!==e.median&&(n.median=roundForDisplay({value:e.median,dependencyValues:e,usedDefault:t})),void 0!==e.quartile3&&(n.quartile3=roundForDisplay({value:e.quartile3,dependencyValues:e,usedDefault:t})),void 0!==e.maximum&&(n.maximum=roundForDisplay({value:e.maximum,dependencyValues:e,usedDefault:t})),void 0!==e.range&&(n.range=roundForDisplay({value:e.range,dependencyValues:e,usedDefault:t})),void 0!==e.sum&&(n.sum=roundForDisplay({value:e.sum,dependencyValues:e,usedDefault:t})),{setValue:{summaryStatistics:n}}}},e}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class Chart extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{changeAxisLimits:this.changeAxisLimits.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="chart";static acceptTarget=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.type={createComponentOfType:"text",createStateVariable:"type",defaultValue:"histogram",toLowerCase:!0,validValues:["histogram","dotplot","frequencytable","box","bar"],forRenderer:!0},e.column={createComponentOfType:"text",createStateVariable:"desiredColumn",defaultValue:null},e.xmin={createComponentOfType:"number",createStateVariable:"xminPrelim",defaultValue:-10},e.xmax={createComponentOfType:"number",createStateVariable:"xmaxPrelim",defaultValue:10},e.ymin={createComponentOfType:"number",createStateVariable:"yminPrelim",defaultValue:-10},e.ymax={createComponentOfType:"number",createStateVariable:"ymaxPrelim",defaultValue:10},e.width={createComponentOfType:"_componentSize",createStateVariable:"width",defaultValue:{size:300,isAbsolute:!0},public:!0,forRenderer:!0},e.height={createComponentOfType:"_componentSize",createStateVariable:"height",defaultValue:{size:300,isAbsolute:!0},public:!0,forRenderer:!0},e.identicalAxisScales={createComponentOfType:"boolean",createStateVariable:"identicalAxisScales",defaultValue:!1,public:!0,forRenderer:!0},e.displayXAxis={createComponentOfType:"boolean",createStateVariable:"displayXAxis",defaultValue:!0,public:!0,forRenderer:!0},e.displayYAxis={createComponentOfType:"boolean",createStateVariable:"displayYAxis",defaultValue:!0,public:!0,forRenderer:!0},e.displayXAxisTickLabels={createComponentOfType:"boolean",createStateVariable:"displayXAxisTickLabels",defaultValue:!0,public:!0,forRenderer:!0},e.displayYAxisTickLabels={createComponentOfType:"boolean",createStateVariable:"displayYAxisTickLabels",defaultValue:!0,public:!0,forRenderer:!0},e.xlabel={createComponentOfType:"text",createStateVariable:"xlabel",defaultValue:"",public:!0,forRenderer:!0},e.xlabelPosition={createComponentOfType:"text",createStateVariable:"xlabelPosition",defaultValue:"right",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["right","left"]},e.ylabel={createComponentOfType:"text",createStateVariable:"ylabel",defaultValue:"",public:!0,forRenderer:!0},e.ylabelPosition={createComponentOfType:"text",createStateVariable:"ylabelPosition",defaultValue:"top",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["top","bottom"]},e.ylabelAlignment={createComponentOfType:"text",createStateVariable:"ylabelAlignment",defaultValue:"left",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["left","right"]},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.dataFrame={forRenderer:!0,returnDependencies:()=>({targetComponent:{dependencyType:"targetComponent",variableNames:["dataFrame"],variablesOptional:!0}}),definition({dependencyValues:e}){console.log("definition of dataFrame",e);let t=null;return e.targetComponent?.stateValues.dataFrame&&(t=e.targetComponent.stateValues.dataFrame),{setValue:{dataFrame:t}}}},e.columnName={public:!0,shadowingInstructions:{createComponentOfType:"text"},additionalStateVariablesDefined:[{variableName:"colInd",forRenderer:!0}],returnDependencies:()=>({desiredColumn:{dependencyType:"stateVariable",variableName:"desiredColumn"},dataFrame:{dependencyType:"stateVariable",variableName:"dataFrame"}}),definition({dependencyValues:e}){let t=null,n=null;return e.dataFrame&&(n=e.dataFrame.columnNames.indexOf(e.desiredColumn),-1!==n?t=e.desiredColumn:n=null),{setValue:{columnName:t,colInd:n}}}},e.xmin={stateVariablesDeterminingDependencies:["identicalAxisScales"],defaultValue:-10,public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies({stateValues:e}){let t={identicalAxisScales:{dependencyType:"stateVariable",variableName:"identicalAxisScales"},xminPrelim:{dependencyType:"stateVariable",variableName:"xminPrelim"}};return e.identicalAxisScales&&(t.xmaxPrelim={dependencyType:"stateVariable",variableName:"xmaxPrelim"},t.yminPrelim={dependencyType:"stateVariable",variableName:"yminPrelim"},t.ymaxPrelim={dependencyType:"stateVariable",variableName:"ymaxPrelim"},t.width={dependencyType:"stateVariable",variableName:"width"},t.height={dependencyType:"stateVariable",variableName:"height"}),t},definition({dependencyValues:e,usedDefault:t}){if(!e.identicalAxisScales)return{setValue:{xmin:e.xminPrelim}};if(!t.xminPrelim)return{setValue:{xmin:e.xminPrelim}};let n=!t.xmaxPrelim,r=!t.yminPrelim,a=!t.ymaxPrelim;if(r&&a){let t=e.width.size/e.height.size,r=(e.ymaxPrelim-e.yminPrelim)*t;return n?{setValue:{xmin:e.xmaxPrelim-r}}:{setValue:{xmin:-r/2}}}return n?{setValue:{xmin:e.xmaxPrelim-20}}:{setValue:{xmin:-10}}},inverseDefinition:async({desiredStateVariableValues:e,stateValues:t})=>await t.fixAxes?{success:!1}:{success:!0,instructions:[{setDependency:"xminPrelim",desiredValue:e.xmin}]}},e.xmax={stateVariablesDeterminingDependencies:["identicalAxisScales"],defaultValue:-10,public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies({stateValues:e}){let t={identicalAxisScales:{dependencyType:"stateVariable",variableName:"identicalAxisScales"},xmaxPrelim:{dependencyType:"stateVariable",variableName:"xmaxPrelim"}};return e.identicalAxisScales&&(t.xminPrelim={dependencyType:"stateVariable",variableName:"xminPrelim"},t.yminPrelim={dependencyType:"stateVariable",variableName:"yminPrelim"},t.ymaxPrelim={dependencyType:"stateVariable",variableName:"ymaxPrelim"},t.width={dependencyType:"stateVariable",variableName:"width"},t.height={dependencyType:"stateVariable",variableName:"height"}),t},definition({dependencyValues:e,usedDefault:t}){if(!e.identicalAxisScales)return{setValue:{xmax:e.xmaxPrelim}};let n=!t.xminPrelim,r=!t.xmaxPrelim,a=!t.yminPrelim,i=!t.ymaxPrelim,s=a&&i,o=n&&r,l=e.xminPrelim;if(s){let t=e.width.size/e.height.size,a=(e.ymaxPrelim-e.yminPrelim)*t;if(o){let t=e.xmaxPrelim-l;return{setValue:{xmax:l+Math.max(t,a)}}}return n?{setValue:{xmax:l+a}}:r?{setValue:{xmax:e.xmaxPrelim}}:{setValue:{xmax:a/2}}}return r?{setValue:{xmax:e.xmaxPrelim}}:n?{setValue:{xmax:l+20}}:{setValue:{xmax:10}}},inverseDefinition:async({desiredStateVariableValues:e,stateValues:t})=>await t.fixAxes?{success:!1}:{success:!0,instructions:[{setDependency:"xmaxPrelim",desiredValue:e.xmax}]}},e.ymin={stateVariablesDeterminingDependencies:["identicalAxisScales"],defaultValue:-10,public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies({stateValues:e}){let t={identicalAxisScales:{dependencyType:"stateVariable",variableName:"identicalAxisScales"},yminPrelim:{dependencyType:"stateVariable",variableName:"yminPrelim"}};return e.identicalAxisScales&&(t.xmaxPrelim={dependencyType:"stateVariable",variableName:"xmaxPrelim"},t.xminPrelim={dependencyType:"stateVariable",variableName:"xminPrelim"},t.ymaxPrelim={dependencyType:"stateVariable",variableName:"ymaxPrelim"},t.width={dependencyType:"stateVariable",variableName:"width"},t.height={dependencyType:"stateVariable",variableName:"height"}),t},definition({dependencyValues:e,usedDefault:t}){if(!e.identicalAxisScales)return{setValue:{ymin:e.yminPrelim}};if(!t.yminPrelim)return{setValue:{ymin:e.yminPrelim}};let n=!t.ymaxPrelim,r=!t.xminPrelim,a=!t.xmaxPrelim,i=r&&a,s=e.width.size/e.height.size;if(i){let t=(e.xmaxPrelim-e.xminPrelim)/s;return n?{setValue:{ymin:e.ymaxPrelim-t}}:{setValue:{ymin:-t/2}}}return n?{setValue:{ymin:e.ymaxPrelim-20/s}}:{setValue:{ymin:-10/s}}},inverseDefinition:async({desiredStateVariableValues:e,stateValues:t})=>await t.fixAxes?{success:!1}:{success:!0,instructions:[{setDependency:"yminPrelim",desiredValue:e.ymin}]}},e.ymax={stateVariablesDeterminingDependencies:["identicalAxisScales"],defaultValue:-10,public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies({stateValues:e}){let t={identicalAxisScales:{dependencyType:"stateVariable",variableName:"identicalAxisScales"},ymaxPrelim:{dependencyType:"stateVariable",variableName:"ymaxPrelim"}};return e.identicalAxisScales&&(t.xminPrelim={dependencyType:"stateVariable",variableName:"xminPrelim"},t.yminPrelim={dependencyType:"stateVariable",variableName:"yminPrelim"},t.xmaxPrelim={dependencyType:"stateVariable",variableName:"xmaxPrelim"},t.width={dependencyType:"stateVariable",variableName:"width"},t.height={dependencyType:"stateVariable",variableName:"height"}),t},definition({dependencyValues:e,usedDefault:t}){if(!e.identicalAxisScales)return{setValue:{ymax:e.ymaxPrelim}};let n=!t.xminPrelim,r=!t.xmaxPrelim,a=!t.yminPrelim,i=!t.ymaxPrelim,s=a&&i,o=n&&r,l=e.yminPrelim,u=e.width.size/e.height.size;if(o){let t=(e.xmaxPrelim-e.xminPrelim)/u;if(s){let n=e.ymaxPrelim-l;return{setValue:{ymax:l+Math.max(n,t)}}}return a?{setValue:{ymax:l+t}}:i?{setValue:{ymax:e.ymaxPrelim}}:{setValue:{ymax:t/2}}}return i?{setValue:{ymax:e.ymaxPrelim}}:a?{setValue:{ymax:l+20/u}}:{setValue:{ymax:10/u}}},inverseDefinition:async({desiredStateVariableValues:e,stateValues:t})=>await t.fixAxes?{success:!1}:{success:!0,instructions:[{setDependency:"ymaxPrelim",desiredValue:e.ymax}]}},e.xscale={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({xmin:{dependencyType:"stateVariable",variableName:"xmin"},xmax:{dependencyType:"stateVariable",variableName:"xmax"}}),definition:({dependencyValues:e})=>({setValue:{xscale:e.xmax-e.xmin}})},e.yscale={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({ymin:{dependencyType:"stateVariable",variableName:"ymin"},ymax:{dependencyType:"stateVariable",variableName:"ymax"}}),definition:({dependencyValues:e})=>({setValue:{yscale:e.ymax-e.ymin}})},e}async changeAxisLimits({xmin:e,xmax:t,ymin:n,ymax:r,actionId:a}){let i=[];return void 0!==e&&i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"xmin",value:e}),void 0!==t&&i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"xmax",value:t}),void 0!==n&&i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"ymin",value:n}),void 0!==r&&i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"ymax",value:r}),await this.coreFunctions.performUpdate({updateInstructions:i,actionId:a,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{xmin:e,xmax:t,ymin:n,ymax:r}}})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class Legend extends GraphicalComponent{static componentType="legend";static createAttributesObject(){let e=super.createAttributesObject();return e.position={createComponentOfType:"text",createStateVariable:"position",defaultValue:"upperright",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft"]},e.displayClosedSwatches={createComponentOfType:"boolean",createStateVariable:"displayClosedSwatches",defaultValue:!1,public:!0},e}static returnChildGroups(){return[{group:"labels",componentTypes:["label"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.graphicalElementNames={returnDependencies:()=>({graphAncestor:{dependencyType:"ancestor",componentType:"graph",variableNames:["graphicalDescendants"]}}),definition:({dependencyValues:e})=>e.graphAncestor?{setValue:{graphicalElementNames:e.graphAncestor.stateValues.graphicalDescendants.map((e=>e.componentName))}}:{setValue:{graphicalElementNames:null}}},e.legendElements={forRenderer:!0,stateVariablesDeterminingDependencies:["graphicalElementNames"],returnDependencies:({stateValues:e})=>{let t={labelChildren:{dependencyType:"child",childGroups:["labels"],variableNames:["value","hasLatex","forObjectComponentName"]},displayClosedSwatches:{dependencyType:"stateVariable",variableName:"displayClosedSwatches"}};if(e.graphicalElementNames){t.numGraphicalElements={dependencyType:"value",value:e.graphicalElementNames.length};for(let[n,r]of e.graphicalElementNames.entries())t[`graphicalElement${n}`]={dependencyType:"multipleStateVariables",componentName:r,variableNames:["selectedStyle","styleNumber","filled"],variablesOptional:!0},t[`graphicalElement${n}AdapterSource`]={dependencyType:"adapterSource",componentName:r},t[`graphicalElement${n}ShadowSource`]={dependencyType:"shadowSource",componentName:r}}return t},definition({dependencyValues:e,componentInfoObjects:t}){let n=[];if(e.numGraphicalElements>0){let r=[],a=[],i=[],s=[];for(let t=0;te.componentName)),l=[],u={};for(let n of e.labelChildren){let c={value:n.stateValues.value,hasLatex:n.stateValues.hasLatex};if(n.stateValues.forObjectComponentName){u[n.stateValues.forObjectComponentName]=c;let l=o.indexOf(n.stateValues.forObjectComponentName);if(-1!==l){let n=s[l];t.isInheritedComponentType({inheritedComponentType:n.componentType,baseComponentType:"point"})?r.push(n.stateValues.styleNumber):e.displayClosedSwatches&&t.allComponentClasses[n.componentType].representsClosedPath?a.push(n.stateValues.styleNumber):"legend"!==n.componentType&&i.push(n.stateValues.styleNumber)}}l.push({labelInfo:c,forObject:n.stateValues.forObjectComponentName})}for(let c of l){let l;if(c.forObject){let e=o.indexOf(c.forObject);-1!==e&&(l=s[e],s.splice(e,1),o.splice(e,1))}else for(let n=0;n({graphAncestor:{dependencyType:"ancestor",componentType:"graph",variableNames:["xmin","xmax","ymin","ymax"]}}),definition:({dependencyValues:e})=>e.graphAncestor?{setValue:{graphLimits:e.graphAncestor.stateValues}}:{setValue:{graphLimits:null}}},e}}class MatchesPattern extends BooleanComponent{static componentType="matchesPattern";static rendererType="boolean";static createAttributesObject(){let e=super.createAttributesObject();return e.pattern={createComponentOfType:"math"},e.allowImplicitIdentities={createComponentOfType:"boolean",createStateVariable:"allowImplicitIdentities",defaultValue:!1,public:!0},e.allowPermutations={createComponentOfType:"boolean",createStateVariable:"allowPermutations",defaultValue:!0,public:!0},e.requireNumericMatches={createComponentOfType:"boolean",createStateVariable:"requireNumericMatches",defaultValue:!1,public:!0},e.requireVariableMatches={createComponentOfType:"boolean",createStateVariable:"requireVariableMatches",defaultValue:!1,public:!0},e.excludeMatches={createComponentOfType:"mathList",createStateVariable:"excludeMatches",defaultValue:[],public:!0},e.matchExpressionWithBlanks={createComponentOfType:"boolean",createStateVariable:"matchExpressionWithBlanks",defaultValue:!1,public:!0},e}static returnSugarInstructions(){let e=[];return e.push({replacementFunction:function({matchedChildren:e,componentInfoObjects:t}){return 0===e.length||1===e.length&&t.componentIsSpecifiedType(e[0],"math")?{success:!1}:{success:!0,newChildren:[{componentType:"math",children:e}]}}}),e}static returnChildGroups(){return[{group:"maths",componentTypes:["math"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return delete e.parsedExpression,delete e.mathChildrenByCode,e.pattern={additionalStateVariablesDefined:["patternVariables"],returnDependencies:()=>({patternAttr:{dependencyType:"attributeComponent",attributeName:"pattern",variableNames:["value"]}}),definition({dependencyValues:e}){let t=[];if(!e.patternAttr)return{setValue:{pattern:"_",patternVariables:t}};let n=e.patternAttr.stateValues.value.variables(),r=703;let a=function e(a){if("_"===a){let e=numberToLetters(r);for(r++;n.includes(e);)e=numberToLetters(r),r++;return t.push(e),e}return Array.isArray(a)?[a[0],...a.slice(1).map(e)]:a}(e.patternAttr.stateValues.value.tree);return{setValue:{pattern:a,patternVariables:t}}}},e.value={additionalStateVariablesDefined:[{variableName:"allPatternMatches"}],public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,returnDependencies:()=>({pattern:{dependencyType:"stateVariable",variableName:"pattern"},patternVariables:{dependencyType:"stateVariable",variableName:"patternVariables"},mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]},allowImplicitIdentities:{dependencyType:"stateVariable",variableName:"allowImplicitIdentities"},allowPermutations:{dependencyType:"stateVariable",variableName:"allowPermutations"},requireNumericMatches:{dependencyType:"stateVariable",variableName:"requireNumericMatches"},requireVariableMatches:{dependencyType:"stateVariable",variableName:"requireVariableMatches"},excludeMatches:{dependencyType:"stateVariable",variableName:"excludeMatches"},matchExpressionWithBlanks:{dependencyType:"stateVariable",variableName:"matchExpressionWithBlanks"}}),definition:function({dependencyValues:e}){if(0===e.mathChildren.length)return{setValue:{value:!1,allPatternMatches:[]}};let t=e.mathChildren[0].stateValues.value;if(t.variables().includes("_")&&!e.matchExpressionWithBlanks)return{setValue:{value:!1,allPatternMatches:[]}};let n={};if(e.requireNumericMatches){let t=e=>null!==me$3.fromAst(e).evaluate_to_constant();e.patternVariables.forEach((e=>n[e]=t))}else if(e.requireVariableMatches){let t=e=>"string"==typeof e;e.patternVariables.forEach((e=>n[e]=t))}else e.patternVariables.forEach((e=>n[e]=!0));let r={variables:n,allow_permutations:e.allowPermutations};e.allowImplicitIdentities&&(r.allow_implicit_identities=e.patternVariables);let a=t.match(e.pattern,r),i=!1,s=[];return a&&(Object.values(a).map((e=>me$3.fromAst(e))).some((t=>e.excludeMatches.some((e=>t.variables().some((t=>e.equalsViaSyntax(me$3.fromAst(t))))))))||(i=!0,s=e.patternVariables.map((e=>me$3.fromAst(a[e]))))),{setValue:{value:i,allPatternMatches:s}}}},e.nMatches={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({allPatternMatches:{dependencyType:"stateVariable",variableName:"allPatternMatches"}}),definition:({dependencyValues:e})=>({setValue:{nMatches:e.allPatternMatches.length},checkForActualChange:{nMatches:!0}})},e.patternMatches={public:!0,shadowingInstructions:{createComponentOfType:"math"},isArray:!0,nDimensions:1,entryPrefixes:["patternMatch"],returnArraySizeDependencies:()=>({nMatches:{dependencyType:"stateVariable",variableName:"nMatches"}}),returnArraySize:({dependencyValues:e})=>[e.nMatches],returnArrayDependenciesByKey:()=>({globalDependencies:{allPatternMatches:{dependencyType:"stateVariable",variableName:"allPatternMatches"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n=0;n({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.displayDigitsAttr){let n=t.displayDigitsAttr,r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!n&&!r){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({}),definition:()=>({setValue:{unordered:!1}})},e.matrixSizePre={returnDependencies:()=>({rowChildren:{dependencyType:"child",childGroups:["rows"],variableNames:["nComponents"]},colChildren:{dependencyType:"child",childGroups:["columns"],variableNames:["nComponents"]},mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["matrixSize"]},nRowsAttr:{dependencyType:"attributeComponent",attributeName:"nRows",variableNames:["value"]},nColumnsAttr:{dependencyType:"attributeComponent",attributeName:"nColumns",variableNames:["value"]}}),definition({dependencyValues:e}){let t=null,n=null;return e.nRowsAttr&&(t=e.nRowsAttr.stateValues.value,Number.isFinite(t)&&t>0||(t=null)),e.nColumnsAttr&&(n=e.nColumnsAttr.stateValues.value,Number.isFinite(n)&&n>0||(n=null)),e.rowChildren.length>0?(null===t&&(t=e.rowChildren.length),null===n&&(n=Math.max(1,...e.rowChildren.map((e=>e.stateValues.nComponents))))):e.colChildren.length>0?(null===n&&(n=e.colChildren.length),null===t&&(t=Math.max(1,...e.colChildren.map((e=>e.stateValues.nComponents))))):1===e.mathChildren.length?(null===t&&(t=e.mathChildren[0].stateValues.matrixSize[0]),null===n&&(n=e.mathChildren[0].stateValues.matrixSize[1])):null===t?null===n?(t=0,n=0):t=1:null===n&&(n=1),{setValue:{matrixSizePre:[t,n]}}}},e.matrixPre={isArray:!0,nDimensions:2,hasEssential:!0,returnArraySizeDependencies:()=>({matrixSizePre:{dependencyType:"stateVariable",variableName:"matrixSizePre"}}),returnArraySize:({dependencyValues:e})=>e.matrixSizePre,returnArrayDependenciesByKey:({arrayKeys:e})=>{let t={};for(let n of e){let[e,r]=n.split(",");t[n]={rowChild:{dependencyType:"child",childGroups:["rows"],childIndices:[e],variableNames:["math"+(Number(r)+1)]},colChild:{dependencyType:"child",childGroups:["columns"],childIndices:[r],variableNames:["math"+(Number(e)+1)]},mathChild:{dependencyType:"child",childGroups:["maths"],childIndices:[0],variableNames:["matrixEntry"+(Number(e)+1)+"_"+(Number(r)+1)]}}}return{globalDependencies:{defaultEntry:{dependencyType:"stateVariable",variableName:"defaultEntry"},rowChildIdentities:{dependencyType:"child",childGroups:["rows"]},colChildIdentities:{dependencyType:"child",childGroups:["columns"]}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n,arraySize:r}){let a={},i={},s=e.rowChildIdentities.length>0,o=e.colChildIdentities.length>0;for(let r of n){let n,[l,u]=r.split(",");n=s?t[r].rowChild[0]?.stateValues["math"+(Number(u)+1)]:o?t[r].colChild[0]?.stateValues["math"+(Number(l)+1)]:t[r].mathChild[0]?.stateValues["matrixEntry"+(Number(l)+1)+"_"+(Number(u)+1)],void 0===n?i[r]={defaultValue:e.defaultEntry}:a[r]=n}return{setValue:{matrixPre:a},useEssentialOrDefaultValue:{matrixPre:i}}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r}){let a=[],i={},s=t.rowChildIdentities.length>0,o=t.colChildIdentities.length>0;for(let t in e.matrixPre){let[l,u]=t.split(",");if(s){let s=n[t].rowChild[0]?.stateValues["math"+(Number(u)+1)];void 0===s?i[t]=e.matrixPre[t]:a.push({setDependency:r[t].rowChild,desiredValue:e.matrixPre[t],childIndex:0,variableIndex:0})}else if(o){let s=n[t].colChild[0]?.stateValues["math"+(Number(l)+1)];void 0===s?i[t]=e.matrixPre[t]:a.push({setDependency:r[t].colChild,desiredValue:e.matrixPre[t],childIndex:0,variableIndex:0})}else{let s=n[t].mathChild[0]?.stateValues["matrixEntry"+(Number(l)+1)+"_"+(Number(u)+1)];void 0===s?i[t]=e.matrixPre[t]:a.push({setDependency:r[t].mathChild,desiredValue:e.matrixPre[t],childIndex:0,variableIndex:0})}}return Object.keys(i).length>0&&a.push({setEssentialValue:"matrixPre",value:i}),{success:!0,instructions:a}}},e.unnormalizedValue={returnDependencies:()=>({matrixPre:{dependencyType:"stateVariable",variableName:"matrixPre"},matrixSizePre:{dependencyType:"stateVariable",variableName:"matrixSizePre"}}),definition({dependencyValues:e}){let t=["tuple"];for(let n=0;ne.tree))]);return{setValue:{unnormalizedValue:me$3.fromAst(["matrix",["tuple",...e.matrixSizePre],t])}}},inverseDefinition({dependencyValues:e,desiredStateVariableValues:t}){let n=t.unnormalizedValue.tree;if(!Array.isArray(n)||"matrix"!==n[0]||n[1]?.[1]!==e.matrixSizePre[0]||n[1]?.[2]!==e.matrixSizePre[1])return{success:!1};let r={};for(let t=0;t({modifyIndirectly:{dependencyType:"stateVariable",variableName:"modifyIndirectly"},fixed:{dependencyType:"stateVariable",variableName:"fixed"}}),definition:({dependencyValues:e})=>({setValue:{canBeModified:e.modifyIndirectly&&!e.fixed}})},e}}class EigenDecomposition extends BaseComponent{static componentType="eigenDecomposition";static rendererType=void 0;static createAttributesObject(){let e=super.createAttributesObject();return e.displayDigits={createComponentOfType:"integer",createStateVariable:"displayDigits",defaultValue:14,public:!0},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.padZeros={createComponentOfType:"boolean",createStateVariable:"padZeros",defaultValue:!1,public:!0},e}static returnChildGroups(){return[{group:"maths",componentTypes:["math"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.decomposition={returnDependencies:()=>({mathChild:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]}}),definition({dependencyValues:e}){if(0===e.mathChild.length)return{setValue:{decomposition:null}};let t=e.mathChild[0].stateValues.value.tree;if(!Array.isArray(t)||"matrix"!==t[0])return{setValue:{decomposition:null}};let n=t[1][1],r=t[1][2];if(!Number.isInteger(n)||r!==n)return{setValue:{decomposition:null}};let a,i=[];for(let e=0;e({decomposition:{dependencyType:"stateVariable",variableName:"decomposition"}}),returnArraySize({dependencyValues:e}){let t;return t=e.decomposition?e.decomposition.values.length:0,[t]},returnArrayDependenciesByKey:()=>({globalDependencies:{decomposition:{dependencyType:"stateVariable",variableName:"decomposition"}}}),arrayDefinitionByKey({globalDependencyValues:e,arraySize:t}){let n=[];for(let r=0;r"eigenvectorX"===e?[]:[["vector",{componentType:"mathList",isAttribute:"xs"}]]},getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("eigenvectorX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("eigenvectors"===t)return 1===e.length?"eigenvector"+e[0]:`eigenvectorX${e[0]}_${e[1]}`;if("eigenvector"===t.slice(0,11)){let n=Number(t.slice(11));if(Number.isInteger(n)&&n>0)return`eigenvectorX${n}_${e[0]}`}return null},entryPrefixes:["eigenvectorX","eigenvector"],returnArraySizeDependencies:()=>({decomposition:{dependencyType:"stateVariable",variableName:"decomposition"}}),returnArraySize({dependencyValues:e}){let t;return t=e.decomposition?e.decomposition.values.length:0,[t,t]},returnArrayDependenciesByKey:()=>({globalDependencies:{decomposition:{dependencyType:"stateVariable",variableName:"decomposition"}}}),arrayDefinitionByKey({globalDependencyValues:e,arraySize:t}){let n={};for(let r=0;rme$3.math.divide(e,i)));for(let e=0;e({mathTextLikeChildren:{dependencyType:"child",childGroups:["mathTextLike"],variableNames:["text","latex"]}}),e.value.definition=function({dependencyValues:e}){if(0===e.mathTextLikeChildren.length)return{useEssentialOrDefaultValue:{value:!0}};let t="";for(let n of e.mathTextLikeChildren)"string"==typeof n?t+=n:void 0!==n.stateValues.latex?t+=n.stateValues.latex:t+=n.stateValues.text;return{setValue:{value:t}}},e.value.inverseDefinition=function({desiredStateVariableValues:e,dependencyValues:t}){let n=t.mathTextLikeChildren.length;return n>1?{success:!1}:1===n?{success:!0,instructions:[{setDependency:"textLikeChildren",desiredValue:e.value,childIndex:0,variableIndex:void 0===t.textLikeChildren[0].stateValues?.latex?0:1}]}:{success:!0,instructions:[{setEssentialValue:"value",value:null===e.value?"":String(e.value)}]}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:({dependencyValues:e})=>({setValue:{text:e.value}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setDependency:"value",desiredValue:e.text}]})},e.latex={isAlias:!0,targetVariableName:"value"},e}}const unitConversions={"":1,px:1,pixel:1,pixels:1,"%":1,em:100,in:96,inch:96,inches:96,pt:1.333333333333,mm:3.7795296,millimeter:3.7795296,millimeters:3.7795296,cm:37.795296,centimeter:37.795296,centimeters:37.795296};class ComponentSize extends InlineComponent{static componentType="_componentSize";static rendererType="text";static primaryStateVariableForDefinition="componentSize";static stateVariableForAttributeValue="componentSize";static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({childrenRegex:/..+/,replacementFunction:function({matchedChildren:e}){let t=e[e.length-1];if("string"==typeof t){let n=/([a-zA-z]+|%)$/,r=t.trim(),a=r.match(n);if(a){let t=a[1];if(t in unitConversions){let n=r.slice(0,a.index),i=e.slice(0,e.length-1);return n.length>0&&i.push(n),{success:!0,newChildren:[{componentType:"number",children:i},t]}}}}return{success:!0,newChildren:[{componentType:"number",children:e}]}}}),e}static returnChildGroups(){return[{group:"strings",componentTypes:["string"]},{group:"numbers",componentTypes:["number"]},{group:"componentSizes",componentTypes:["_componentSize"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.componentSize={public:!0,shadowingInstructions:{createComponentOfType:"_componentSize"},hasEssential:!0,returnDependencies:()=>({componentSizeChild:{dependencyType:"child",childGroups:["componentSizes"],variableNames:["componentSize"]},numberChild:{dependencyType:"child",childGroups:["numbers"],variableNames:["value"]},stringChild:{dependencyType:"child",childGroups:["strings"],variableNames:["value"]},parentDefaultAbsoluteSize:{dependencyType:"parentStateVariable",variableName:"defaultAbsoluteSize"}}),definition({dependencyValues:e}){let t=void 0!==e.parentDefaultAbsoluteSize&&e.parentDefaultAbsoluteSize;if(0===e.stringChild.length)return 0===e.numberChild.length?0===e.componentSizeChild.length?{useEssentialOrDefaultValue:{componentSize:{defaultValue:{size:100,isAbsolute:t}}}}:{setValue:{componentSize:e.componentSizeChild[0].stateValues.componentSize}}:{setValue:{componentSize:{size:e.numberChild[0].stateValues.value,isAbsolute:!0}}};{let t,n;if(e.numberChild.length>0)t=e.numberChild[0].stateValues.value,n=e.stringChild[0].trim();else{let r=e.stringChild[0].trim().match(/^(-?[\d.]+)\s*(.*)$/);if(null===r)return{setValue:{componentSize:null}};t=r[1],n=r[2].trim()}if(t=Number(t),!Number.isFinite(t))return{setValue:{componentSize:null}};let r=!("%"===n||"em"===n),a=unitConversions[n];return void 0===a&&(a=1),{setValue:{componentSize:{size:a*t,isAbsolute:r}}}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){if(0===t.stringChild.length)return 0===t.numberChild.length?0===t.componentSizeChild.length?{success:!0,instructions:[{setEssentialValue:"componentSize",value:e.componentSize}]}:{success:!0,instructions:[{setDependency:"componentSizeChild",desiredValue:e.componentSize,childIndex:0,variableIndex:0}]}:e.componentSize.isAbsolute?{success:!0,instructions:[{setDependency:"numberChild",desiredValue:e.componentSize.size,childIndex:0,variableIndex:0}]}:{success:!1};if(t.numberChild.length>0){let n=t.stringChild[0].trim(),r=!("%"===n||"em"===n);if(e.componentSize.isAbsolute!==r)return{success:!1};let a=unitConversions[n];return void 0===a&&(a=1),{success:!0,instructions:[{setDependency:"numberChild",desiredValue:e.componentSize.size/a,childIndex:0,variableIndex:0}]}}{let t=e.componentSize.size;return e.componentSize.isAbsolute?t+="px":t+="%",{success:!0,instructions:[{setDependency:"stringChild",desiredValue:t,childIndex:0,variableIndex:0}]}}}},e.number={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({componentSize:{dependencyType:"stateVariable",variableName:"componentSize"}}),definition({dependencyValues:e}){let t=null;return e.componentSize&&(t=e.componentSize.size),{setValue:{number:t}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){if(!t.componentSize)return{success:!1};return{success:!0,instructions:[{setDependency:"componentSize",desiredValue:{size:e.number,isAbsolute:t.componentSize.isAbsolute}}]}}},e.math=mathStateVariableFromNumberStateVariable({numberVariableName:"number",mathVariableName:"math",isPublic:!0}),e.isAbsolute={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({componentSize:{dependencyType:"stateVariable",variableName:"componentSize"}}),definition({dependencyValues:e}){let t=null;return e.componentSize&&(t=e.componentSize.isAbsolute),{setValue:{isAbsolute:t}}}},e.text={forRenderer:!0,returnDependencies:()=>({componentSize:{dependencyType:"stateVariable",variableName:"componentSize"}}),definition({dependencyValues:e}){let t="";return e.componentSize&&(t=e.componentSize.size,e.componentSize.isAbsolute?t+="px":t+="%"),{setValue:{text:t}}}},e}static adapters=["number","math"]}class ComponentSizeList extends BaseComponent{static componentType="_componentSizeList";static rendererType="asList";static renderChildren=!0;static stateVariableForAttributeValue="componentSizes";static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e}){let t=[],n=[],r=function(){n.length>0&&(t.push({componentType:"_componentSize",children:n}),n=[])};for(let t of e)if("string"==typeof t){let e=t.split(/\s+/);0===e[0].length&&(r(),e=e.slice(1));for(let[t,a]of e.entries())a.length>0?(n.push(a),t({}),definition:()=>({setValue:{overrideChildHide:!0}})},e.nComponents={public:!0,shadowingInstructions:{createComponentOfType:"number"},additionalStateVariablesDefined:["childIndexByArrayKey"],returnDependencies:()=>({componentSizeListChildren:{dependencyType:"child",childGroups:["componentSizeLists"],variableNames:["nComponents"]},componentSizeAndComponentSizeListChildren:{dependencyType:"child",childGroups:["componentSizes","componentSizeLists"],skipComponentNames:!0}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=0,r=[],a=0;for(let[i,s]of e.componentSizeAndComponentSizeListChildren.entries())if(t.isInheritedComponentType({inheritedComponentType:s.componentType,baseComponentType:"_componentSizeList"})){let t=e.componentSizeListChildren[a];a++;for(let e=0;e({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"}}),returnArraySize:({dependencyValues:e})=>[e.nComponents],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=[],a="1";t.childIndexByArrayKey[r]&&(e=[t.childIndexByArrayKey[r][0]],a=t.childIndexByArrayKey[r][1]+1),n[r]={componentSizeAndComponentSizeListChildren:{dependencyType:"child",childGroups:["componentSizes","componentSizeLists"],variableNames:["componentSize","componentSize"+a],variablesOptional:!0,childIndices:e}}}return{globalDependencies:{childIndexByArrayKey:{dependencyType:"stateVariable",variableName:"childIndexByArrayKey"}},dependenciesByKey:n}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n,componentInfoObjects:r}){let a={};for(let i of n){let n=t[i].componentSizeAndComponentSizeListChildren[0];if(n)if(r.isInheritedComponentType({inheritedComponentType:n.componentType,baseComponentType:"_componentSizeList"})){let t=e.childIndexByArrayKey[i][1]+1;a[i]=n.stateValues["componentSize"+t]}else a[i]=n.stateValues.componentSize}return{setValue:{componentSizes:a}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a,componentInfoObjects:i}){let s=[];for(let t in e.componentSizes){if(!n[t])continue;let a=n[t].componentSizeAndComponentSizeListChildren[0];a&&(i.isInheritedComponentType({inheritedComponentType:a.componentType,baseComponentType:"_componentSizeList"})?s.push({setDependency:r[t].componentSizeAndComponentSizeListChildren,desiredValue:e.componentSizes[t],childIndex:0,variableIndex:1}):s.push({setDependency:r[t].componentSizeAndComponentSizeListChildren,desiredValue:e.componentSizes[t],childIndex:0,variableIndex:0}))}return{success:!0,instructions:s}}},e.nValues={isAlias:!0,targetVariableName:"nComponents"},e.values={isAlias:!0,targetVariableName:"componentSizes"},e}}var ComponentSize$1=Object.freeze({__proto__:null,ComponentSize:ComponentSize,ComponentSizeList:ComponentSizeList});const componentTypeArray=[...Object.values(Aliases),...Object.values(MMeMen),...Object.values(MdMdnMrow),...Object.values(BooleanOperators),...Object.values(BooleanOperatorsOfMath),...Object.values(MathOperators),...Object.values(FunctionOperators),...Object.values(TextOperatorsOfMath),...Object.values(Extrema$1),...Object.values(ParagraphMarkup),...Object.values(SingleCharacterComponents),...Object.values(Sectioning),...Object.values(Lists),...Object.values(DynamicalSystems),...Object.values(Chemistry),...Object.values(FeedbackDefinitions$1),...Object.values(StyleDefinitions$1),...Object.values(SideBySide$1),...Object.values(ComponentWithSelectableType$1),...Object.values(Indexing),...Object.values(Divisions),...Object.values(Verbatim),...Object.values(Paginator$1),...Object.values(MatrixInput$1),Document,Text,TextList$1,TextList,P$2,BooleanComponent,BooleanList,MathComponent,MathList,TupleList,NumberList,NumberListFromString,Copy,Extract,Collect,Ref,Point,Coords,Line,LineSegment,Ray,Polyline,Polygon,Triangle,Rectangle,Circle,Parabola,Curve,BezierControls,ControlVectors,Vector,Angle,Answer,Award,When,MathInput,Textinput,BooleanInput,Choiceinput,Choice,NumberComponent,Integer,Graph$1,Variables,Variable,Function$1,Interval,Template,Option$1,Sequence,Slider,Spreadsheet,DiscreteSimulationResultList,DiscreteSimulationResultPolyline,Cell,Row,Column,CellBlock,Tabular,Table,Figure,Markers,Panel,Map$1,Sources,Constraints,ConstrainToGrid,ConstrainToGraph,AttractToGrid,ConstrainTo,AttractTo,ConstraintUnion,AttractToConstraint,Intersection,ConstrainToAngles,AttractToAngles,ConditionalContent,AsList,VariantControl,TextListFromString,SelectFromSequence,Select,Group,AnimateFromSequence,Evaluate,SelectRandomNumbers,SampleRandomNumbers,Substitute,PeriodicSet,Image,Video,Embed,Hint,Solution,IntComma,Pluralize,Feedback,CollaborateGroups,CollaborateGroupSetup,ConsiderAsResponses,Case,Lorem,UpdateValue,CallAction,triggerSet,FunctionIterates,Module,CustomAttribute,Setup,Footnote,Caption,Endpoint,Sort,Shuffle,SolveEquations,SolutionContainer,SubsetOfRealsInput,SubsetOfReals,Split,BestFitLine,RegionBetweenCurveXAxis,RegionHalfPlane,CodeEditor,CodeViewer,RenderDoenetML,HasSameFactoring,DataFrame,SummaryStatistics,Chart,Legend,Label,MatchesPattern,Matrix,EigenDecomposition,Latex,BaseComponent,InlineComponent,BlockComponent,GraphicalComponent,ConstraintComponent,Input,CompositeComponent,PointListComponent,IntervalListComponent,LineListComponent,VectorListComponent,AngleListComponent,BooleanOperator,BooleanBaseOperatorOfMath,MathOperator,MathOperatorOneInput,FunctionOperator,...Object.values(ComponentSize$1),SectioningComponent,InlineRenderInlineChildren,TextOrInline,SingleCharacter];function allComponentClasses(){const e={},t=new Set;for(let n of componentTypeArray){let r=n.componentType;if(void 0===r)throw Error("Cannot create component as componentType is undefined for class "+n);let a=r.toLowerCase();if(t.has(a))throw Error("component type "+r+" defined in two classes");e[r]=n,t.add(a)}return e}function componentTypesCreatingVariants(){const e={},t=new Set;for(let n of componentTypeArray)if(n.createsVariants){let r=n.componentType;if(void 0===r)throw Error("Cannot create component as componentType is undefined for class "+n);let a=r.toLowerCase();if(t.has(a))throw Error("component type "+r+" defined in two classes");e[r]=n,t.add(a)}return e}function createComponentInfoObjects(){let e=allComponentClasses(),t=componentTypesCreatingVariants(),n={};for(let t in e)n[t.toLowerCase()]=t;let r={};for(let t in e)Object.defineProperty(r,t,{get:function(){let n=e[t].returnStateVariableInfo();return delete r[t],r[t]=n}.bind(this),configurable:!0});let a={};for(let t in e)Object.defineProperty(a,t,{get:function(){let n=e[t].returnStateVariableInfo({onlyPublic:!0});return delete a[t],a[t]=n}.bind(this),configurable:!0});function i({inheritedComponentType:t,baseComponentType:n}){if(t===n)return!0;if("string"===t)return"_base"===n||"_inline"===n;if("string"===n)return!1;let r=e[n];return!!r&&r.isPrototypeOf(e[t])}let s=(e,t)=>i({inheritedComponentType:e,baseComponentType:t});return{allComponentClasses:e,componentTypesCreatingVariants:t,componentTypeLowerCaseMapping:n,isInheritedComponentType:i,isCompositeComponent:function({componentType:t,includeNonStandard:n=!0}){let r=e[t];return!!r&&(i({inheritedComponentType:t,baseComponentType:"_composite"})&&(n||!r.treatAsComponentForRecursiveReplacements))},stateVariableInfo:r,publicStateVariableInfo:a,componentIsSpecifiedType:(e,t)=>s(e.componentType,t)||s(e.attributes?.createComponentOfType?.primitive,t)}}function promisifyRequest(e){return new Promise(((t,n)=>{e.oncomplete=e.onsuccess=()=>t(e.result),e.onabort=e.onerror=()=>n(e.error)}))}function createStore(e,t){const n=indexedDB.open(e);n.onupgradeneeded=()=>n.result.createObjectStore(t);const r=promisifyRequest(n);return(e,n)=>r.then((r=>n(r.transaction(t,e).objectStore(t))))}let defaultGetStoreFunc;function defaultGetStore(){return defaultGetStoreFunc||(defaultGetStoreFunc=createStore("keyval-store","keyval")),defaultGetStoreFunc}function set(e,t,n=defaultGetStore()){return n("readwrite",(n=>(n.put(t,e),promisifyRequest(n.transaction))))}const toastType=Object.freeze({ERROR:{timeout:-1,background:"rgba(193, 41, 46, 1)",gradientEnd:"rgba()"},ALERT:{timeout:-1,background:"rgba(255, 230, 0, 1)"},ACTION:{timeout:-1,background:"rgba()"},INFO:{timeout:3e3,background:"rgba(26, 90, 153,1)"},SUCCESS:{timeout:3e3,background:"rgba(41, 193, 67, 1)"},CONFIRMATION:{timeout:5e3,background:"rgba(26,90,153,1)"}});var axios$3={exports:{}},axios$2={exports:{}},bind$2=function(e,t){return function(){for(var n=new Array(arguments.length),r=0;r0;)s[i=r[a]]||(t[i]=e[i],s[i]=!0);e=Object.getPrototypeOf(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t}function endsWith(e,t,n){e=String(e),(void 0===n||n>e.length)&&(n=e.length),n-=t.length;var r=e.indexOf(t,n);return-1!==r&&r===n}function toArray(e){if(!e)return null;var t=e.length;if(isUndefined(t))return null;for(var n=new Array(t);t-- >0;)n[t]=e[t];return n}var isTypedArray=(TypedArray="undefined"!=typeof Uint8Array&&Object.getPrototypeOf(Uint8Array),function(e){return TypedArray&&e instanceof TypedArray}),TypedArray,utils$9={isArray:isArray$1,isArrayBuffer:isArrayBuffer,isBuffer:isBuffer$1,isFormData:isFormData,isArrayBufferView:isArrayBufferView,isString:isString,isNumber:isNumber,isObject:isObject,isPlainObject:isPlainObject,isUndefined:isUndefined,isDate:isDate,isFile:isFile,isBlob:isBlob,isFunction:isFunction,isStream:isStream,isURLSearchParams:isURLSearchParams,isStandardBrowserEnv:isStandardBrowserEnv,forEach:forEach,merge:merge,extend:extend,trim:trim,stripBOM:stripBOM,inherits:inherits,toFlatObject:toFlatObject,kindOf:kindOf,kindOfTest:kindOfTest,endsWith:endsWith,toArray:toArray,isTypedArray:isTypedArray,isFileList:isFileList},utils$8=utils$9;function encode(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}var buildURL$1=function(e,t,n){if(!t)return e;var r;if(n)r=n(t);else if(utils$8.isURLSearchParams(t))r=t.toString();else{var a=[];utils$8.forEach(t,(function(e,t){null!=e&&(utils$8.isArray(e)?t+="[]":e=[e],utils$8.forEach(e,(function(e){utils$8.isDate(e)?e=e.toISOString():utils$8.isObject(e)&&(e=JSON.stringify(e)),a.push(encode(t)+"="+encode(e))})))})),r=a.join("&")}if(r){var i=e.indexOf("#");-1!==i&&(e=e.slice(0,i)),e+=(-1===e.indexOf("?")?"?":"&")+r}return e},utils$7=utils$9;function InterceptorManager$1(){this.handlers=[]}InterceptorManager$1.prototype.use=function(e,t,n){return this.handlers.push({fulfilled:e,rejected:t,synchronous:!!n&&n.synchronous,runWhen:n?n.runWhen:null}),this.handlers.length-1},InterceptorManager$1.prototype.eject=function(e){this.handlers[e]&&(this.handlers[e]=null)},InterceptorManager$1.prototype.forEach=function(e){utils$7.forEach(this.handlers,(function(t){null!==t&&e(t)}))};var InterceptorManager_1=InterceptorManager$1,utils$6=utils$9,normalizeHeaderName$1=function(e,t){utils$6.forEach(e,(function(n,r){r!==t&&r.toUpperCase()===t.toUpperCase()&&(e[t]=n,delete e[r])}))},AxiosError_1,hasRequiredAxiosError;function requireAxiosError(){if(hasRequiredAxiosError)return AxiosError_1;hasRequiredAxiosError=1;var e=utils$9;function t(e,t,n,r,a){Error.call(this),this.message=e,this.name="AxiosError",t&&(this.code=t),n&&(this.config=n),r&&(this.request=r),a&&(this.response=a)}e.inherits(t,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:this.config,code:this.code,status:this.response&&this.response.status?this.response.status:null}}});var n=t.prototype,r={};return["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED"].forEach((function(e){r[e]={value:e}})),Object.defineProperties(t,r),Object.defineProperty(n,"isAxiosError",{value:!0}),t.from=function(r,a,i,s,o,l){var u=Object.create(n);return e.toFlatObject(r,u,(function(e){return e!==Error.prototype})),t.call(u,r.message,a,i,s,o),u.name=r.name,l&&Object.assign(u,l),u},AxiosError_1=t}var transitional={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},lookup=[],revLookup=[],Arr="undefined"!=typeof Uint8Array?Uint8Array:Array,inited=!1;function init(){inited=!0;for(var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",t=0,n=e.length;t0)throw new Error("Invalid string. Length must be a multiple of 4");i="="===e[o-2]?2:"="===e[o-1]?1:0,s=new Arr(3*o/4-i),r=i>0?o-4:o;var l=0;for(t=0,n=0;t>16&255,s[l++]=a>>8&255,s[l++]=255&a;return 2===i?(a=revLookup[e.charCodeAt(t)]<<2|revLookup[e.charCodeAt(t+1)]>>4,s[l++]=255&a):1===i&&(a=revLookup[e.charCodeAt(t)]<<10|revLookup[e.charCodeAt(t+1)]<<4|revLookup[e.charCodeAt(t+2)]>>2,s[l++]=a>>8&255,s[l++]=255&a),s}function tripletToBase64(e){return lookup[e>>18&63]+lookup[e>>12&63]+lookup[e>>6&63]+lookup[63&e]}function encodeChunk(e,t,n){for(var r,a=[],i=t;il?l:o+s));return 1===r?(t=e[n-1],a+=lookup[t>>2],a+=lookup[t<<4&63],a+="=="):2===r&&(t=(e[n-2]<<8)+e[n-1],a+=lookup[t>>10],a+=lookup[t>>4&63],a+=lookup[t<<2&63],a+="="),i.push(a),i.join("")}function read(e,t,n,r,a){var i,s,o=8*a-r-1,l=(1<>1,c=-7,p=n?a-1:0,d=n?-1:1,m=e[t+p];for(p+=d,i=m&(1<<-c)-1,m>>=-c,c+=o;c>0;i=256*i+e[t+p],p+=d,c-=8);for(s=i&(1<<-c)-1,i>>=-c,c+=r;c>0;s=256*s+e[t+p],p+=d,c-=8);if(0===i)i=1-u;else{if(i===l)return s?NaN:1/0*(m?-1:1);s+=Math.pow(2,r),i-=u}return(m?-1:1)*s*Math.pow(2,i-r)}function write(e,t,n,r,a,i){var s,o,l,u=8*i-a-1,c=(1<>1,d=23===a?Math.pow(2,-24)-Math.pow(2,-77):0,m=r?0:i-1,h=r?1:-1,f=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(o=isNaN(t)?1:0,s=c):(s=Math.floor(Math.log(t)/Math.LN2),t*(l=Math.pow(2,-s))<1&&(s--,l*=2),(t+=s+p>=1?d/l:d*Math.pow(2,1-p))*l>=2&&(s++,l/=2),s+p>=c?(o=0,s=c):s+p>=1?(o=(t*l-1)*Math.pow(2,a),s+=p):(o=t*Math.pow(2,p-1)*Math.pow(2,a),s=0));a>=8;e[n+m]=255&o,m+=h,o/=256,a-=8);for(s=s<0;e[n+m]=255&s,m+=h,s/=256,u-=8);e[n+m-h]|=128*f}var toString={}.toString,isArray=Array.isArray||function(e){return"[object Array]"==toString.call(e)},INSPECT_MAX_BYTES=50;function kMaxLength(){return Buffer.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function createBuffer(e,t){if(kMaxLength()=kMaxLength())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+kMaxLength().toString(16)+" bytes");return 0|e}function internalIsBuffer(e){return!(null==e||!e._isBuffer)}function byteLength(e,t){if(internalIsBuffer(e))return e.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e.byteLength;"string"!=typeof e&&(e=""+e);var n=e.length;if(0===n)return 0;for(var r=!1;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":case void 0:return utf8ToBytes(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return base64ToBytes(e).length;default:if(r)return utf8ToBytes(e).length;t=(""+t).toLowerCase(),r=!0}}function slowToString(e,t,n){var r=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if((n>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return hexSlice(this,t,n);case"utf8":case"utf-8":return utf8Slice(this,t,n);case"ascii":return asciiSlice(this,t,n);case"latin1":case"binary":return latin1Slice(this,t,n);case"base64":return base64Slice(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return utf16leSlice(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}function swap(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}function bidirectionalIndexOf(e,t,n,r,a){if(0===e.length)return-1;if("string"==typeof n?(r=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),n=+n,isNaN(n)&&(n=a?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(a)return-1;n=e.length-1}else if(n<0){if(!a)return-1;n=0}if("string"==typeof t&&(t=Buffer.from(t,r)),internalIsBuffer(t))return 0===t.length?-1:arrayIndexOf(e,t,n,r,a);if("number"==typeof t)return t&=255,Buffer.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?a?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):arrayIndexOf(e,[t],n,r,a);throw new TypeError("val must be string, number or Buffer")}function arrayIndexOf(e,t,n,r,a){var i,s=1,o=e.length,l=t.length;if(void 0!==r&&("ucs2"===(r=String(r).toLowerCase())||"ucs-2"===r||"utf16le"===r||"utf-16le"===r)){if(e.length<2||t.length<2)return-1;s=2,o/=2,l/=2,n/=2}function u(e,t){return 1===s?e[t]:e.readUInt16BE(t*s)}if(a){var c=-1;for(i=n;io&&(n=o-l),i=n;i>=0;i--){for(var p=!0,d=0;da&&(r=a):r=a;var i=t.length;if(i%2!=0)throw new TypeError("Invalid hex string");r>i/2&&(r=i/2);for(var s=0;s239?4:u>223?3:u>191?2:1;if(a+p<=n)switch(p){case 1:u<128&&(c=u);break;case 2:128==(192&(i=e[a+1]))&&(l=(31&u)<<6|63&i)>127&&(c=l);break;case 3:i=e[a+1],s=e[a+2],128==(192&i)&&128==(192&s)&&(l=(15&u)<<12|(63&i)<<6|63&s)>2047&&(l<55296||l>57343)&&(c=l);break;case 4:i=e[a+1],s=e[a+2],o=e[a+3],128==(192&i)&&128==(192&s)&&128==(192&o)&&(l=(15&u)<<18|(63&i)<<12|(63&s)<<6|63&o)>65535&&l<1114112&&(c=l)}null===c?(c=65533,p=1):c>65535&&(c-=65536,r.push(c>>>10&1023|55296),c=56320|1023&c),r.push(c),a+=p}return decodeCodePointsArray(r)}Buffer.TYPED_ARRAY_SUPPORT=void 0===global$1.TYPED_ARRAY_SUPPORT||global$1.TYPED_ARRAY_SUPPORT,kMaxLength(),Buffer.poolSize=8192,Buffer._augment=function(e){return e.__proto__=Buffer.prototype,e},Buffer.from=function(e,t,n){return from(null,e,t,n)},Buffer.TYPED_ARRAY_SUPPORT&&(Buffer.prototype.__proto__=Uint8Array.prototype,Buffer.__proto__=Uint8Array),Buffer.alloc=function(e,t,n){return alloc(null,e,t,n)},Buffer.allocUnsafe=function(e){return allocUnsafe(null,e)},Buffer.allocUnsafeSlow=function(e){return allocUnsafe(null,e)},Buffer.isBuffer=isBuffer,Buffer.compare=function(e,t){if(!internalIsBuffer(e)||!internalIsBuffer(t))throw new TypeError("Arguments must be Buffers");if(e===t)return 0;for(var n=e.length,r=t.length,a=0,i=Math.min(n,r);a0&&(e=this.toString("hex",0,t).match(/.{2}/g).join(" "),this.length>t&&(e+=" ... ")),""},Buffer.prototype.compare=function(e,t,n,r,a){if(!internalIsBuffer(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===n&&(n=e?e.length:0),void 0===r&&(r=0),void 0===a&&(a=this.length),t<0||n>e.length||r<0||a>this.length)throw new RangeError("out of range index");if(r>=a&&t>=n)return 0;if(r>=a)return-1;if(t>=n)return 1;if(this===e)return 0;for(var i=(a>>>=0)-(r>>>=0),s=(n>>>=0)-(t>>>=0),o=Math.min(i,s),l=this.slice(r,a),u=e.slice(t,n),c=0;ca)&&(n=a),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");for(var i=!1;;)switch(r){case"hex":return hexWrite(this,e,t,n);case"utf8":case"utf-8":return utf8Write(this,e,t,n);case"ascii":return asciiWrite(this,e,t,n);case"latin1":case"binary":return latin1Write(this,e,t,n);case"base64":return base64Write(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ucs2Write(this,e,t,n);default:if(i)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),i=!0}},Buffer.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var MAX_ARGUMENTS_LENGTH=4096;function decodeCodePointsArray(e){var t=e.length;if(t<=MAX_ARGUMENTS_LENGTH)return String.fromCharCode.apply(String,e);for(var n="",r=0;rr)&&(n=r);for(var a="",i=t;in)throw new RangeError("Trying to access beyond buffer length")}function checkInt(e,t,n,r,a,i){if(!internalIsBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>a||te.length)throw new RangeError("Index out of range")}function objectWriteUInt16(e,t,n,r){t<0&&(t=65535+t+1);for(var a=0,i=Math.min(e.length-n,2);a>>8*(r?a:1-a)}function objectWriteUInt32(e,t,n,r){t<0&&(t=4294967295+t+1);for(var a=0,i=Math.min(e.length-n,4);a>>8*(r?a:3-a)&255}function checkIEEE754(e,t,n,r,a,i){if(n+r>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function writeFloat(e,t,n,r,a){return a||checkIEEE754(e,t,n,4),write(e,t,n,r,23,4),n+4}function writeDouble(e,t,n,r,a){return a||checkIEEE754(e,t,n,8),write(e,t,n,r,52,8),n+8}Buffer.prototype.slice=function(e,t){var n,r=this.length;if((e=~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),(t=void 0===t?r:~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),t0&&(a*=256);)r+=this[e+--t]*a;return r},Buffer.prototype.readUInt8=function(e,t){return t||checkOffset(e,1,this.length),this[e]},Buffer.prototype.readUInt16LE=function(e,t){return t||checkOffset(e,2,this.length),this[e]|this[e+1]<<8},Buffer.prototype.readUInt16BE=function(e,t){return t||checkOffset(e,2,this.length),this[e]<<8|this[e+1]},Buffer.prototype.readUInt32LE=function(e,t){return t||checkOffset(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},Buffer.prototype.readUInt32BE=function(e,t){return t||checkOffset(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},Buffer.prototype.readIntLE=function(e,t,n){e|=0,t|=0,n||checkOffset(e,t,this.length);for(var r=this[e],a=1,i=0;++i=(a*=128)&&(r-=Math.pow(2,8*t)),r},Buffer.prototype.readIntBE=function(e,t,n){e|=0,t|=0,n||checkOffset(e,t,this.length);for(var r=t,a=1,i=this[e+--r];r>0&&(a*=256);)i+=this[e+--r]*a;return i>=(a*=128)&&(i-=Math.pow(2,8*t)),i},Buffer.prototype.readInt8=function(e,t){return t||checkOffset(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},Buffer.prototype.readInt16LE=function(e,t){t||checkOffset(e,2,this.length);var n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},Buffer.prototype.readInt16BE=function(e,t){t||checkOffset(e,2,this.length);var n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},Buffer.prototype.readInt32LE=function(e,t){return t||checkOffset(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},Buffer.prototype.readInt32BE=function(e,t){return t||checkOffset(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},Buffer.prototype.readFloatLE=function(e,t){return t||checkOffset(e,4,this.length),read(this,e,!0,23,4)},Buffer.prototype.readFloatBE=function(e,t){return t||checkOffset(e,4,this.length),read(this,e,!1,23,4)},Buffer.prototype.readDoubleLE=function(e,t){return t||checkOffset(e,8,this.length),read(this,e,!0,52,8)},Buffer.prototype.readDoubleBE=function(e,t){return t||checkOffset(e,8,this.length),read(this,e,!1,52,8)},Buffer.prototype.writeUIntLE=function(e,t,n,r){(e=+e,t|=0,n|=0,r)||checkInt(this,e,t,n,Math.pow(2,8*n)-1,0);var a=1,i=0;for(this[t]=255&e;++i=0&&(i*=256);)this[t+a]=e/i&255;return t+n},Buffer.prototype.writeUInt8=function(e,t,n){return e=+e,t|=0,n||checkInt(this,e,t,1,255,0),Buffer.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},Buffer.prototype.writeUInt16LE=function(e,t,n){return e=+e,t|=0,n||checkInt(this,e,t,2,65535,0),Buffer.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):objectWriteUInt16(this,e,t,!0),t+2},Buffer.prototype.writeUInt16BE=function(e,t,n){return e=+e,t|=0,n||checkInt(this,e,t,2,65535,0),Buffer.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):objectWriteUInt16(this,e,t,!1),t+2},Buffer.prototype.writeUInt32LE=function(e,t,n){return e=+e,t|=0,n||checkInt(this,e,t,4,4294967295,0),Buffer.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e):objectWriteUInt32(this,e,t,!0),t+4},Buffer.prototype.writeUInt32BE=function(e,t,n){return e=+e,t|=0,n||checkInt(this,e,t,4,4294967295,0),Buffer.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):objectWriteUInt32(this,e,t,!1),t+4},Buffer.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t|=0,!r){var a=Math.pow(2,8*n-1);checkInt(this,e,t,n,a-1,-a)}var i=0,s=1,o=0;for(this[t]=255&e;++i>0)-o&255;return t+n},Buffer.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t|=0,!r){var a=Math.pow(2,8*n-1);checkInt(this,e,t,n,a-1,-a)}var i=n-1,s=1,o=0;for(this[t+i]=255&e;--i>=0&&(s*=256);)e<0&&0===o&&0!==this[t+i+1]&&(o=1),this[t+i]=(e/s>>0)-o&255;return t+n},Buffer.prototype.writeInt8=function(e,t,n){return e=+e,t|=0,n||checkInt(this,e,t,1,127,-128),Buffer.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=255&e,t+1},Buffer.prototype.writeInt16LE=function(e,t,n){return e=+e,t|=0,n||checkInt(this,e,t,2,32767,-32768),Buffer.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):objectWriteUInt16(this,e,t,!0),t+2},Buffer.prototype.writeInt16BE=function(e,t,n){return e=+e,t|=0,n||checkInt(this,e,t,2,32767,-32768),Buffer.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):objectWriteUInt16(this,e,t,!1),t+2},Buffer.prototype.writeInt32LE=function(e,t,n){return e=+e,t|=0,n||checkInt(this,e,t,4,2147483647,-2147483648),Buffer.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):objectWriteUInt32(this,e,t,!0),t+4},Buffer.prototype.writeInt32BE=function(e,t,n){return e=+e,t|=0,n||checkInt(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),Buffer.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):objectWriteUInt32(this,e,t,!1),t+4},Buffer.prototype.writeFloatLE=function(e,t,n){return writeFloat(this,e,t,!0,n)},Buffer.prototype.writeFloatBE=function(e,t,n){return writeFloat(this,e,t,!1,n)},Buffer.prototype.writeDoubleLE=function(e,t,n){return writeDouble(this,e,t,!0,n)},Buffer.prototype.writeDoubleBE=function(e,t,n){return writeDouble(this,e,t,!1,n)},Buffer.prototype.copy=function(e,t,n,r){if(n||(n=0),r||0===r||(r=this.length),t>=e.length&&(t=e.length),t||(t=0),r>0&&r=this.length)throw new RangeError("sourceStart out of bounds");if(r<0)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),e.length-t=0;--a)e[a+t]=this[a+n];else if(i<1e3||!Buffer.TYPED_ARRAY_SUPPORT)for(a=0;a>>=0,n=void 0===n?this.length:n>>>0,e||(e=0),"number"==typeof e)for(i=t;i55295&&n<57344){if(!a){if(n>56319){(t-=3)>-1&&i.push(239,191,189);continue}if(s+1===r){(t-=3)>-1&&i.push(239,191,189);continue}a=n;continue}if(n<56320){(t-=3)>-1&&i.push(239,191,189),a=n;continue}n=65536+(a-55296<<10|n-56320)}else a&&(t-=3)>-1&&i.push(239,191,189);if(a=null,n<128){if((t-=1)<0)break;i.push(n)}else if(n<2048){if((t-=2)<0)break;i.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;i.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;i.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return i}function asciiToBytes(e){for(var t=[],n=0;n>8,a=n%256,i.push(a),i.push(r);return i}function base64ToBytes(e){return toByteArray(base64clean(e))}function blitBuffer(e,t,n,r){for(var a=0;a=t.length||a>=e.length);++a)t[a+n]=e[a];return a}function isnan(e){return e!=e}function isBuffer(e){return null!=e&&(!!e._isBuffer||isFastBuffer(e)||isSlowBuffer(e))}function isFastBuffer(e){return!!e.constructor&&"function"==typeof e.constructor.isBuffer&&e.constructor.isBuffer(e)}function isSlowBuffer(e){return"function"==typeof e.readFloatLE&&"function"==typeof e.slice&&isFastBuffer(e.slice(0,0))}function requireToFormData(){if(hasRequiredToFormData)return toFormData_1;hasRequiredToFormData=1;var e=utils$9;return toFormData_1=function(t,n){n=n||new FormData;var r=[];function a(t){return null===t?"":e.isDate(t)?t.toISOString():e.isArrayBuffer(t)||e.isTypedArray(t)?"function"==typeof Blob?new Blob([t]):Buffer.from(t):t}return function t(i,s){if(e.isPlainObject(i)||e.isArray(i)){if(-1!==r.indexOf(i))throw Error("Circular reference detected in "+s);r.push(i),e.forEach(i,(function(r,i){if(!e.isUndefined(r)){var o,l=s?s+"."+i:i;if(r&&!s&&"object"==typeof r)if(e.endsWith(i,"{}"))r=JSON.stringify(r);else if(e.endsWith(i,"[]")&&(o=e.toArray(r)))return void o.forEach((function(t){!e.isUndefined(t)&&n.append(l,a(t))}));t(r,l)}})),r.pop()}else n.append(s,a(i))}(t),n},toFormData_1}function requireSettle(){if(hasRequiredSettle)return settle;hasRequiredSettle=1;var e=requireAxiosError();return settle=function(t,n,r){var a=r.config.validateStatus;r.status&&a&&!a(r.status)?n(new e("Request failed with status code "+r.status,[e.ERR_BAD_REQUEST,e.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r)):t(r)},settle}function requireCookies(){if(hasRequiredCookies)return cookies;hasRequiredCookies=1;var e=utils$9;return cookies=e.isStandardBrowserEnv()?{write:function(t,n,r,a,i,s){var o=[];o.push(t+"="+encodeURIComponent(n)),e.isNumber(r)&&o.push("expires="+new Date(r).toGMTString()),e.isString(a)&&o.push("path="+a),e.isString(i)&&o.push("domain="+i),!0===s&&o.push("secure"),document.cookie=o.join("; ")},read:function(e){var t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove:function(e){this.write(e,"",Date.now()-864e5)}}:{write:function(){},read:function(){return null},remove:function(){}}}var isAbsoluteURL$1=function(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)},combineURLs$1=function(e,t){return t?e.replace(/\/+$/,"")+"/"+t.replace(/^\/+/,""):e},isAbsoluteURL=isAbsoluteURL$1,combineURLs=combineURLs$1,buildFullPath$1=function(e,t){return e&&!isAbsoluteURL(t)?combineURLs(e,t):t},parseHeaders,hasRequiredParseHeaders,isURLSameOrigin,hasRequiredIsURLSameOrigin,CanceledError_1,hasRequiredCanceledError,parseProtocol,hasRequiredParseProtocol,xhr,hasRequiredXhr,_null,hasRequired_null;function requireParseHeaders(){if(hasRequiredParseHeaders)return parseHeaders;hasRequiredParseHeaders=1;var e=utils$9,t=["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"];return parseHeaders=function(n){var r,a,i,s={};return n?(e.forEach(n.split("\n"),(function(n){if(i=n.indexOf(":"),r=e.trim(n.substr(0,i)).toLowerCase(),a=e.trim(n.substr(i+1)),r){if(s[r]&&t.indexOf(r)>=0)return;s[r]="set-cookie"===r?(s[r]?s[r]:[]).concat([a]):s[r]?s[r]+", "+a:a}})),s):s},parseHeaders}function requireIsURLSameOrigin(){if(hasRequiredIsURLSameOrigin)return isURLSameOrigin;hasRequiredIsURLSameOrigin=1;var e=utils$9;return isURLSameOrigin=e.isStandardBrowserEnv()?function(){var t,n=/(msie|trident)/i.test(navigator.userAgent),r=document.createElement("a");function a(e){var t=e;return n&&(r.setAttribute("href",t),t=r.href),r.setAttribute("href",t),{href:r.href,protocol:r.protocol?r.protocol.replace(/:$/,""):"",host:r.host,search:r.search?r.search.replace(/^\?/,""):"",hash:r.hash?r.hash.replace(/^#/,""):"",hostname:r.hostname,port:r.port,pathname:"/"===r.pathname.charAt(0)?r.pathname:"/"+r.pathname}}return t=a(window.location.href),function(n){var r=e.isString(n)?a(n):n;return r.protocol===t.protocol&&r.host===t.host}}():function(){return!0}}function requireCanceledError(){if(hasRequiredCanceledError)return CanceledError_1;hasRequiredCanceledError=1;var e=requireAxiosError();function t(t){e.call(this,null==t?"canceled":t,e.ERR_CANCELED),this.name="CanceledError"}return utils$9.inherits(t,e,{__CANCEL__:!0}),CanceledError_1=t}function requireParseProtocol(){return hasRequiredParseProtocol?parseProtocol:(hasRequiredParseProtocol=1,parseProtocol=function(e){var t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""})}function requireXhr(){if(hasRequiredXhr)return xhr;hasRequiredXhr=1;var e=utils$9,t=requireSettle(),n=requireCookies(),r=buildURL$1,a=buildFullPath$1,i=requireParseHeaders(),s=requireIsURLSameOrigin(),o=transitional,l=requireAxiosError(),u=requireCanceledError(),c=requireParseProtocol();return xhr=function(p){return new Promise((function(d,m){var h,f=p.data,y=p.headers,g=p.responseType;function b(){p.cancelToken&&p.cancelToken.unsubscribe(h),p.signal&&p.signal.removeEventListener("abort",h)}e.isFormData(f)&&e.isStandardBrowserEnv()&&delete y["Content-Type"];var v=new XMLHttpRequest;if(p.auth){var N=p.auth.username||"",T=p.auth.password?unescape(encodeURIComponent(p.auth.password)):"";y.Authorization="Basic "+btoa(N+":"+T)}var C=a(p.baseURL,p.url);function A(){if(v){var e="getAllResponseHeaders"in v?i(v.getAllResponseHeaders()):null,n={data:g&&"text"!==g&&"json"!==g?v.response:v.responseText,status:v.status,statusText:v.statusText,headers:e,config:p,request:v};t((function(e){d(e),b()}),(function(e){m(e),b()}),n),v=null}}if(v.open(p.method.toUpperCase(),r(C,p.params,p.paramsSerializer),!0),v.timeout=p.timeout,"onloadend"in v?v.onloadend=A:v.onreadystatechange=function(){v&&4===v.readyState&&(0!==v.status||v.responseURL&&0===v.responseURL.indexOf("file:"))&&setTimeout(A)},v.onabort=function(){v&&(m(new l("Request aborted",l.ECONNABORTED,p,v)),v=null)},v.onerror=function(){m(new l("Network Error",l.ERR_NETWORK,p,v,v)),v=null},v.ontimeout=function(){var e=p.timeout?"timeout of "+p.timeout+"ms exceeded":"timeout exceeded",t=p.transitional||o;p.timeoutErrorMessage&&(e=p.timeoutErrorMessage),m(new l(e,t.clarifyTimeoutError?l.ETIMEDOUT:l.ECONNABORTED,p,v)),v=null},e.isStandardBrowserEnv()){var V=(p.withCredentials||s(C))&&p.xsrfCookieName?n.read(p.xsrfCookieName):void 0;V&&(y[p.xsrfHeaderName]=V)}"setRequestHeader"in v&&e.forEach(y,(function(e,t){void 0===f&&"content-type"===t.toLowerCase()?delete y[t]:v.setRequestHeader(t,e)})),e.isUndefined(p.withCredentials)||(v.withCredentials=!!p.withCredentials),g&&"json"!==g&&(v.responseType=p.responseType),"function"==typeof p.onDownloadProgress&&v.addEventListener("progress",p.onDownloadProgress),"function"==typeof p.onUploadProgress&&v.upload&&v.upload.addEventListener("progress",p.onUploadProgress),(p.cancelToken||p.signal)&&(h=function(e){v&&(m(!e||e&&e.type?new u:e),v.abort(),v=null)},p.cancelToken&&p.cancelToken.subscribe(h),p.signal&&(p.signal.aborted?h():p.signal.addEventListener("abort",h))),f||(f=null);var x=c(C);x&&-1===["http","https","file"].indexOf(x)?m(new l("Unsupported protocol "+x+":",l.ERR_BAD_REQUEST,p)):v.send(f)}))},xhr}function require_null(){return hasRequired_null?_null:(hasRequired_null=1,_null=null)}var utils$5=utils$9,normalizeHeaderName=normalizeHeaderName$1,AxiosError$1=requireAxiosError(),transitionalDefaults=transitional,toFormData=requireToFormData(),DEFAULT_CONTENT_TYPE={"Content-Type":"application/x-www-form-urlencoded"};function setContentTypeIfUnset(e,t){!utils$5.isUndefined(e)&&utils$5.isUndefined(e["Content-Type"])&&(e["Content-Type"]=t)}function getDefaultAdapter(){var e;return("undefined"!=typeof XMLHttpRequest||void 0!==browser$1&&"[object process]"===Object.prototype.toString.call(browser$1))&&(e=requireXhr()),e}function stringifySafely(e,t,n){if(utils$5.isString(e))try{return(t||JSON.parse)(e),utils$5.trim(e)}catch(e){if("SyntaxError"!==e.name)throw e}return(n||JSON.stringify)(e)}var defaults$3={transitional:transitionalDefaults,adapter:getDefaultAdapter(),transformRequest:[function(e,t){if(normalizeHeaderName(t,"Accept"),normalizeHeaderName(t,"Content-Type"),utils$5.isFormData(e)||utils$5.isArrayBuffer(e)||utils$5.isBuffer(e)||utils$5.isStream(e)||utils$5.isFile(e)||utils$5.isBlob(e))return e;if(utils$5.isArrayBufferView(e))return e.buffer;if(utils$5.isURLSearchParams(e))return setContentTypeIfUnset(t,"application/x-www-form-urlencoded;charset=utf-8"),e.toString();var n,r=utils$5.isObject(e),a=t&&t["Content-Type"];if((n=utils$5.isFileList(e))||r&&"multipart/form-data"===a){var i=this.env&&this.env.FormData;return toFormData(n?{"files[]":e}:e,i&&new i)}return r||"application/json"===a?(setContentTypeIfUnset(t,"application/json"),stringifySafely(e)):e}],transformResponse:[function(e){var t=this.transitional||defaults$3.transitional,n=t&&t.silentJSONParsing,r=t&&t.forcedJSONParsing,a=!n&&"json"===this.responseType;if(a||r&&utils$5.isString(e)&&e.length)try{return JSON.parse(e)}catch(e){if(a){if("SyntaxError"===e.name)throw AxiosError$1.from(e,AxiosError$1.ERR_BAD_RESPONSE,this,null,this.response);throw e}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:require_null()},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*"}}};utils$5.forEach(["delete","get","head"],(function(e){defaults$3.headers[e]={}})),utils$5.forEach(["post","put","patch"],(function(e){defaults$3.headers[e]=utils$5.merge(DEFAULT_CONTENT_TYPE)}));var defaults_1=defaults$3,utils$4=utils$9,defaults$2=defaults_1,transformData$1=function(e,t,n){var r=this||defaults$2;return utils$4.forEach(n,(function(n){e=n.call(r,e,t)})),e},isCancel$1,hasRequiredIsCancel;function requireIsCancel(){return hasRequiredIsCancel?isCancel$1:(hasRequiredIsCancel=1,isCancel$1=function(e){return!(!e||!e.__CANCEL__)})}var utils$3=utils$9,transformData=transformData$1,isCancel=requireIsCancel(),defaults$1=defaults_1,CanceledError=requireCanceledError();function throwIfCancellationRequested(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new CanceledError}var dispatchRequest$1=function(e){return throwIfCancellationRequested(e),e.headers=e.headers||{},e.data=transformData.call(e,e.data,e.headers,e.transformRequest),e.headers=utils$3.merge(e.headers.common||{},e.headers[e.method]||{},e.headers),utils$3.forEach(["delete","get","head","post","put","patch","common"],(function(t){delete e.headers[t]})),(e.adapter||defaults$1.adapter)(e).then((function(t){return throwIfCancellationRequested(e),t.data=transformData.call(e,t.data,t.headers,e.transformResponse),t}),(function(t){return isCancel(t)||(throwIfCancellationRequested(e),t&&t.response&&(t.response.data=transformData.call(e,t.response.data,t.response.headers,e.transformResponse))),Promise.reject(t)}))},utils$2=utils$9,mergeConfig$2=function(e,t){t=t||{};var n={};function r(e,t){return utils$2.isPlainObject(e)&&utils$2.isPlainObject(t)?utils$2.merge(e,t):utils$2.isPlainObject(t)?utils$2.merge({},t):utils$2.isArray(t)?t.slice():t}function a(n){return utils$2.isUndefined(t[n])?utils$2.isUndefined(e[n])?void 0:r(void 0,e[n]):r(e[n],t[n])}function i(e){if(!utils$2.isUndefined(t[e]))return r(void 0,t[e])}function s(n){return utils$2.isUndefined(t[n])?utils$2.isUndefined(e[n])?void 0:r(void 0,e[n]):r(void 0,t[n])}function o(n){return n in t?r(e[n],t[n]):n in e?r(void 0,e[n]):void 0}var l={url:i,method:i,data:i,baseURL:s,transformRequest:s,transformResponse:s,paramsSerializer:s,timeout:s,timeoutMessage:s,withCredentials:s,adapter:s,responseType:s,xsrfCookieName:s,xsrfHeaderName:s,onUploadProgress:s,onDownloadProgress:s,decompress:s,maxContentLength:s,maxBodyLength:s,beforeRedirect:s,transport:s,httpAgent:s,httpsAgent:s,cancelToken:s,socketPath:s,responseEncoding:s,validateStatus:o};return utils$2.forEach(Object.keys(e).concat(Object.keys(t)),(function(e){var t=l[e]||a,r=t(e);utils$2.isUndefined(r)&&t!==o||(n[e]=r)})),n},data,hasRequiredData;function requireData(){return hasRequiredData?data:(hasRequiredData=1,data={version:"0.27.2"})}var VERSION=requireData().version,AxiosError=requireAxiosError(),validators$1={};["object","boolean","number","function","string","symbol"].forEach((function(e,t){validators$1[e]=function(n){return typeof n===e||"a"+(t<1?"n ":" ")+e}}));var deprecatedWarnings={};function assertOptions(e,t,n){if("object"!=typeof e)throw new AxiosError("options must be an object",AxiosError.ERR_BAD_OPTION_VALUE);for(var r=Object.keys(e),a=r.length;a-- >0;){var i=r[a],s=t[i];if(s){var o=e[i],l=void 0===o||s(o,i,e);if(!0!==l)throw new AxiosError("option "+i+" must be "+l,AxiosError.ERR_BAD_OPTION_VALUE)}else if(!0!==n)throw new AxiosError("Unknown option "+i,AxiosError.ERR_BAD_OPTION)}}validators$1.transitional=function(e,t,n){function r(e,t){return"[Axios v"+VERSION+"] Transitional option '"+e+"'"+t+(n?". "+n:"")}return function(n,a,i){if(!1===e)throw new AxiosError(r(a," has been removed"+(t?" in "+t:"")),AxiosError.ERR_DEPRECATED);return t&&!deprecatedWarnings[a]&&(deprecatedWarnings[a]=!0,console.warn(r(a," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(n,a,i)}};var validator$1={assertOptions:assertOptions,validators:validators$1},utils$1=utils$9,buildURL=buildURL$1,InterceptorManager=InterceptorManager_1,dispatchRequest=dispatchRequest$1,mergeConfig$1=mergeConfig$2,buildFullPath=buildFullPath$1,validator=validator$1,validators=validator.validators;function Axios$1(e){this.defaults=e,this.interceptors={request:new InterceptorManager,response:new InterceptorManager}}Axios$1.prototype.request=function(e,t){"string"==typeof e?(t=t||{}).url=e:t=e||{},(t=mergeConfig$1(this.defaults,t)).method?t.method=t.method.toLowerCase():this.defaults.method?t.method=this.defaults.method.toLowerCase():t.method="get";var n=t.transitional;void 0!==n&&validator.assertOptions(n,{silentJSONParsing:validators.transitional(validators.boolean),forcedJSONParsing:validators.transitional(validators.boolean),clarifyTimeoutError:validators.transitional(validators.boolean)},!1);var r=[],a=!0;this.interceptors.request.forEach((function(e){"function"==typeof e.runWhen&&!1===e.runWhen(t)||(a=a&&e.synchronous,r.unshift(e.fulfilled,e.rejected))}));var i,s=[];if(this.interceptors.response.forEach((function(e){s.push(e.fulfilled,e.rejected)})),!a){var o=[dispatchRequest,void 0];for(Array.prototype.unshift.apply(o,r),o=o.concat(s),i=Promise.resolve(t);o.length;)i=i.then(o.shift(),o.shift());return i}for(var l=t;r.length;){var u=r.shift(),c=r.shift();try{l=u(l)}catch(e){c(e);break}}try{i=dispatchRequest(l)}catch(e){return Promise.reject(e)}for(;s.length;)i=i.then(s.shift(),s.shift());return i},Axios$1.prototype.getUri=function(e){e=mergeConfig$1(this.defaults,e);var t=buildFullPath(e.baseURL,e.url);return buildURL(t,e.params,e.paramsSerializer)},utils$1.forEach(["delete","get","head","options"],(function(e){Axios$1.prototype[e]=function(t,n){return this.request(mergeConfig$1(n||{},{method:e,url:t,data:(n||{}).data}))}})),utils$1.forEach(["post","put","patch"],(function(e){function t(t){return function(n,r,a){return this.request(mergeConfig$1(a||{},{method:e,headers:t?{"Content-Type":"multipart/form-data"}:{},url:n,data:r}))}}Axios$1.prototype[e]=t(),Axios$1.prototype[e+"Form"]=t(!0)}));var Axios_1=Axios$1,CancelToken_1,hasRequiredCancelToken,spread,hasRequiredSpread,isAxiosError,hasRequiredIsAxiosError;function requireCancelToken(){if(hasRequiredCancelToken)return CancelToken_1;hasRequiredCancelToken=1;var e=requireCanceledError();function t(t){if("function"!=typeof t)throw new TypeError("executor must be a function.");var n;this.promise=new Promise((function(e){n=e}));var r=this;this.promise.then((function(e){if(r._listeners){var t,n=r._listeners.length;for(t=0;t{this.initializedPromiseResolves.forEach((e=>e(!0))),this.initialized=!0},this.getInitializedPromise=()=>this.initialized?Promise.resolve(!0):new Promise(((e,t)=>{this.initializedPromiseResolves.push(e)})),cidFromText(e).then((t=>expandDoenetMLsToFullSerializedComponents({cids:[t],doenetMLs:[e],componentInfoObjects:this.componentInfoObjects,flags:this.flags}))).then(this.finishCoreConstruction).catch((e=>{postMessage({messageType:"inErrorState",coreId:this.coreId,args:{errMsg:e.message}})}))}async finishCoreConstruction({cids:e,fullSerializedComponents:t}){this.cid=e[0];let n=t[0];addDocumentIfItsMissing(n),createComponentNames({serializedComponents:n,componentInfoObjects:this.componentInfoObjects}),this.componentIndexArray=extractComponentNamesAndIndices(n);let{rangePieces:r}=extractRangeIndexPieces({componentArray:this.componentIndexArray});this.componentRangePieces=r,postMessage({messageType:"componentRangePieces",coreId:this.coreId,args:{componentRangePieces:this.componentRangePieces}}),this.documentName=n[0].componentName,n[0].doenetAttributes.cid=this.cid,this._components={},this.componentsToRender={},this.componentsWithChangedChildrenToRender=new Set([]),this.stateVariableChangeTriggers={},this.actionsChangedToActions={},this.originsOfActionsChangedToActions={},this.essentialValuesSavedInDefinition={},this.saveStateToDBTimerId=null,this.rendererState={__componentNeedingUpdateValue:null},this.rendererVariablesByComponentType={};for(let e in this.componentInfoObjects.allComponentClasses)Object.defineProperty(this.rendererVariablesByComponentType,e,{get:function(){let t=this.componentInfoObjects.allComponentClasses[e].returnStateVariableInfo({onlyForRenderer:!0}).stateVariableDescriptions;return delete this.rendererVariablesByComponentType[e],this.rendererVariablesByComponentType[e]=t}.bind(this),configurable:!0});this.processQueue=[],this.stopProcessingRequests=!1,this.dependencies=new DependencyHandler({_components:this._components,componentInfoObjects:this.componentInfoObjects,core:this}),this.unmatchedChildren={};let a=getNumberOfVariants({serializedComponent:n[0],componentInfoObjects:this.componentInfoObjects}).numberOfVariants;if(!this.requestedVariant){if(this.requestedVariantIndex=((this.requestedVariantIndex-1)%a+a)%a+1,n[0].variants.uniqueVariants){let e=this.componentInfoObjects.allComponentClasses[n[0].componentType].getUniqueVariant({serializedComponent:n[0],variantIndex:this.requestedVariantIndex,componentInfoObjects:this.componentInfoObjects});e.success&&(this.requestedVariant=e.desiredVariant)}this.requestedVariant||(this.requestedVariant={index:this.requestedVariantIndex})}this.parameterStack.parameters.variant=this.requestedVariant,n[0].variants.desiredVariant=this.parameterStack.parameters.variant,await this.addComponents({serializedComponents:n,initialAdd:!0}),this.updateInfo.componentsToUpdateRenderers.clear(),await this.document.stateValues.itemCreditAchieved,this.canonicalGeneratedVariantString=JSON.stringify(await this.document.stateValues.generatedVariantInfo,serializedComponentsReplacer),this.canonicalItemVariantStrings=(await this.document.stateValues.itemVariantInfo).map((e=>JSON.stringify(e,serializedComponentsReplacer))),this.coreInfo={generatedVariantString:this.canonicalGeneratedVariantString,allPossibleVariants:deepClone(await this.document.sharedParameters.allPossibleVariants),rendererTypesInDocument:deepClone(this.rendererTypesInDocument),documentToRender:this.documentRendererInstructions},this.coreInfoString=JSON.stringify(this.coreInfo,serializedComponentsReplacer),this.messageViewerReady(),this.resolveInitialized()}async onDocumentFirstVisible(){this.requestRecordEvent({verb:"experienced",object:{componentName:this.document.componentName,componentType:"document"}});let e=function(t){let n=t.stateValues.scoredDescendants;if(Array.isArray(n))for(let t of n){if("answer"===t.componentType)return!0;if(e(t))return!0}return!1};await this.document.stateValues.scoredDescendants,e(this.document)||this.saveSubmissions({pageCreditAchieved:await this.document.stateValues.creditAchieved,suppressToast:!0}),setTimeout(this.sendVisibilityChangedEvents.bind(this),this.visibilityInfo.saveDelay)}async messageViewerReady(){postMessage({messageType:"initializeRenderers",coreId:this.coreId,args:{coreInfo:this.coreInfo}}),postMessage({messageType:"coreCreated",coreId:this.coreId})}async postUpdateRenderers(e,t=!1){postMessage({messageType:"updateRenderers",coreId:this.coreId,args:e,init:t})}async addComponents({serializedComponents:e,parentName:t,indexOfDefiningChildren:n,initialAdd:r=!1,assignNamesOffset:a}){let i;Array.isArray(e)||(e=[e]);let s=[],o="";if(!r){if(i=this._components[t],!i)return console.warn(`Cannot add children to parent ${t} as ${t} does not exist`),[];s=[{componentName:t,componentClass:i.constructor},...i.ancestors],this.parameterStack.push(i.sharedParameters,!1),this.nTimesAddedComponents?this.nTimesAddedComponents++:this.nTimesAddedComponents=1,o=`addComponents${this.nTimesAddedComponents}`}let l=await this.createIsolatedComponents({serializedComponents:e,ancestors:s,createNameContext:o});if(r||this.parameterStack.pop(),!0!==l.success)throw Error(l.message);const u=l.components;let c={},p={};if(u.forEach((e=>p[e.componentName]=e)),r){if(1!==u.length)throw Error("Initial components need to be an array of just one component.");if(this.document=u[0],await this.expandAllComposites(this.document),await this.expandAllComposites(this.document,!0),this.updateInfo.stateVariablesToEvaluate){let e=this.updateInfo.stateVariablesToEvaluate;this.updateInfo.stateVariablesToEvaluate=[];for(let{componentName:t,stateVariable:n}of e){let e=this._components[t];e&&e.state[n]&&await this.getStateVariableValue({component:e,stateVariable:n})}}await this.replacementChangesFromCompositesToUpdate();let e=await this.initializeRenderedComponentInstruction(this.document);if(this.updateInfo.compositesToUpdateReplacements.size>0){await this.replacementChangesFromCompositesToUpdate();let e=[...this.updateInfo.componentsToUpdateRenderers];this.updateInfo.componentsToUpdateRenderers.clear(),await this.updateRendererInstructions({componentNamesToUpdate:e})}this.documentRendererInstructions=e.componentToRender;let t=[{instructionType:"updateRendererStates",rendererStatesToUpdate:e.rendererStatesToUpdate}];if(this.postUpdateRenderers({updateInstructions:t},!0),e.rendererStatesToForceUpdate.length>0){let t=[{instructionType:"updateRendererStates",rendererStatesToUpdate:e.rendererStatesToForceUpdate}];this.postUpdateRenderers({updateInstructions:t})}await this.processStateVariableTriggers()}else{if(void 0===i)throw Error("Must specify parent when adding components.");void 0===n&&(n=i.definingChildren.length);let e=await this.addChildrenAndRecurseToShadows({parent:i,indexOfDefiningChildren:n,newChildren:u,assignNamesOffset:a});if(!e.success)throw Error("Couldn't satisfy child logic result. Need informative error message");if(Object.assign(p,e.addedComponents),Object.assign(c,e.deletedComponents),await this.expandAllComposites(this.document),await this.expandAllComposites(this.document,!0),this.updateInfo.stateVariablesToEvaluate){let e=this.updateInfo.stateVariablesToEvaluate;this.updateInfo.stateVariablesToEvaluate=[];for(let{componentName:t,stateVariable:n}of e){let e=this._components[t];e&&e.state[n]&&await this.getStateVariableValue({component:e,stateVariable:n})}}if(await this.replacementChangesFromCompositesToUpdate(),await this.updateRendererInstructions({componentNamesToUpdate:await this.componentAndRenderedDescendants(i)}),this.updateInfo.compositesToUpdateReplacements.size>0){await this.replacementChangesFromCompositesToUpdate();let e=[...this.updateInfo.componentsToUpdateRenderers];this.updateInfo.componentsToUpdateRenderers.clear(),await this.updateRendererInstructions({componentNamesToUpdate:e})}await this.processStateVariableTriggers()}return u}async updateRendererInstructions({componentNamesToUpdate:e,sourceOfUpdate:t={},actionId:n}){let r=[],a=[],i=[],s={},o=this.componentsWithChangedChildrenToRender;this.componentsWithChangedChildrenToRender=new Set([]);for(let t of o)if(t in this.componentsToRender){let n=[],a=this._components[t],l=[];if(a&&a.constructor.renderChildren){a.childrenMatched||await this.deriveChildResultsFromDefiningChildren({parent:a,expandComposites:!0,forceExpandComposites:!0}),l=await this.returnActiveChildrenIndicesToRender(a);let e=0;for(let[t,r]of a.activeChildren.entries())l.includes(t)&&(r.rendererType?(n.push(`nameType:${r.componentName};${r.componentType}`),e++):"string"==typeof r?(n.push(`string${e}:${r}`),e++):"number"==typeof r&&(n.push(`number${e}:${r.toString()}`),e++))}let u=this.componentsToRender[t].children,c=[];for(let[e,t]of u.entries())t.componentName?c.push(`nameType:${t.componentName};${t.componentType}`):"string"==typeof t?c.push(`string${e}:${t}`):"number"==typeof t&&c.push(`number${e}:${t.toString()}`);if(n.length!==c.length||n.some(((e,t)=>e!==c[t]))){for(let e of u)if(e.componentName){let t=this.deleteFromComponentsToRender({componentName:e.componentName,recurseToChildren:!0,componentsWithChangedChildrenToRenderInProgress:o});r.push(...t)}let n=[];if(l.length>0)for(let[e,t]of a.activeChildren.entries())if(l.includes(e))if(t.rendererType){let e=await this.initializeRenderedComponentInstruction(t,o);n.push(e.componentToRender),i.push(...e.rendererStatesToUpdate)}else"string"==typeof t?n.push(t):"number"==typeof t&&n.push(t.toString());this.componentsToRender[t].children=n,s[t]=n,o.delete(t),e.includes(t)||e.push(t)}}for(let t of e)if(t in this.componentsToRender){let e=this._components[t];if(e){let n={};for(let t in e.state)if(e.state[t].forRenderer){let r=removeFunctionsMathExpressionClass(await e.state[t].value);n[t]=r}let r={componentName:t,stateValues:n,rendererType:e.rendererType};this.rendererState[t]||(this.rendererState[t]={}),this.rendererState[t].stateValues=n,s[t]&&(r.childrenInstructions=s[t],this.rendererState[t].childrenInstructions=s[t]),i.push(r)}}if(i.length>0){let e={instructionType:"updateRendererStates",rendererStatesToUpdate:i,sourceOfUpdate:t};a.splice(0,0,e)}this.postUpdateRenderers({updateInstructions:a,actionId:n})}async initializeRenderedComponentInstruction(e,t=new Set([])){if(void 0===e.rendererType)return;e.childrenMatched||await this.deriveChildResultsFromDefiningChildren({parent:e,expandComposites:!0});let n=[],r=[],a={},i={},s=!1;for(let t in e.state)e.state[t].forRenderer&&(a[t]=removeFunctionsMathExpressionClass(await e.state[t].value),e.state[t].alwaysUpdateRenderer&&(s=!0));s&&(i=a);let o=e.componentName,l=[];if(e.constructor.renderChildren){let a=await this.returnActiveChildrenIndicesToRender(e);for(let[i,s]of e.activeChildren.entries())if(a.includes(i))if(s.rendererType){let e=await this.initializeRenderedComponentInstruction(s,t);l.push(e.componentToRender),n.push(...e.rendererStatesToUpdate),r.push(...e.rendererStatesToForceUpdate)}else"string"==typeof s?l.push(s):"number"==typeof s&&l.push(s.toString())}n.push({componentName:o,stateValues:a,childrenInstructions:l}),Object.keys(i).length>0&&r.push({componentName:o,stateValues:i}),this.rendererState[o]={stateValues:a,childrenInstructions:l},t.delete(o);let u={};for(let t in e.actions)u[t]={actionName:t,componentName:e.componentName};for(let t in e.externalActions){let n=await e.externalActions[t];n&&(u[t]={actionName:t,componentName:n.componentName})}let c={componentName:o,effectiveName:e.componentOrAdaptedName,componentType:e.componentType,rendererType:e.rendererType,actions:u};return this.componentsToRender[o]={children:l},{componentToRender:c,rendererStatesToUpdate:n,rendererStatesToForceUpdate:r}}deleteFromComponentsToRender({componentName:e,recurseToChildren:t=!0,componentsWithChangedChildrenToRenderInProgress:n}){let r=[e];if(t){let a=this.componentsToRender[e];if(a)for(let e of a.children){let a=this.deleteFromComponentsToRender({componentName:e.componentName,recurseToChildren:t,componentsWithChangedChildrenToRenderInProgress:n});r.push(...a)}}return delete this.componentsToRender[e],n.delete(e),r}async processStateVariableTriggers(){for(let e in this.stateVariableChangeTriggers){let t=this._components[e];for(let n in this.stateVariableChangeTriggers[e]){let r=this.stateVariableChangeTriggers[e][n],a=await t.state[n].value;if(a!==r.previousValue){let i=r.previousValue;r.previousValue=a,t.actions[r.action]&&await this.performAction({componentName:e,actionName:r.action,args:{stateValues:{[n]:a},previousValues:{[n]:i}}})}}}}async expandAllComposites(e,t=!1){let n=await this.expandCompositesOfDescendants(e,t),r=!0;for(;r;){r=!1;for(let e of n){let n=this._components[e],a=!1;for(let e of n.unexpandedCompositesNotReady){let n=this._components[e];if(n.state.readyToExpandWhenResolved.isResolved){a=!0;break}if((await this.dependencies.resolveItem({componentName:n.componentName,type:"stateVariable",stateVariable:"readyToExpandWhenResolved",force:t,recurseUpstream:!0})).success){a=!0;break}}if(a){let n=this._components[e];await this.deriveChildResultsFromDefiningChildren({parent:n,expandComposites:!0,forceExpandComposites:t}),r=!0}}}}async expandCompositesOfDescendants(e,t=!1){let n=[];e.childrenMatched||(await this.deriveChildResultsFromDefiningChildren({parent:e,expandComposites:!0,forceExpandComposites:t}),e.unexpandedCompositesNotReady.length>0?n.push(e.componentName):await this.dependencies.resolveBlockersFromChangedActiveChildren(e,t));for(let r in e.attributes){let a=e.attributes[r].component;if(a){let e=await this.expandCompositesOfDescendants(a,t);n.push(...e)}}for(let r in e.allChildren){let a=e.allChildren[r].component;if("object"!=typeof a)continue;let i=await this.expandCompositesOfDescendants(a,t);n.push(...i)}return n}async componentAndRenderedDescendants(e){if(!e?.componentName)return[];let t=[e.componentName];if(e.constructor.renderChildren){e.childrenMatched||await this.deriveChildResultsFromDefiningChildren({parent:e,expandComposites:!0});for(let n of e.activeChildren)t.push(...await this.componentAndRenderedDescendants(n))}return t}async createIsolatedComponents({serializedComponents:e,ancestors:t,shadow:n=!1,createNameContext:r=""}){let a="/";if(t.length>0){let e=t[0].componentName,n=this.components[e];a=n.attributes.newNamespace?.primitive?n.componentName+"/":getNamespaceFromName(n.componentName)}return{success:!0,components:(await this.createIsolatedComponentsSub({serializedComponents:e,ancestors:t,shadow:n,namespaceForUnamed:a,createNameContext:r})).components}}async createIsolatedComponentsSub({serializedComponents:e,ancestors:t,shadow:n=!1,createNameContext:r="",namespaceForUnamed:a="/",componentsReplacementOf:i}){let s=[];for(let[o,l]of e.entries()){if("object"!=typeof l){s.push(l);continue}if(!0===l.createdComponent){let e=this._components[l.componentName];s.push(e),this.setAncestors(e,t);continue}let e=this.componentInfoObjects.allComponentClasses[l.componentType];if(void 0===e)throw Error("Cannot create component of type "+l.componentType);l.doenetAttributes||(l.doenetAttributes={});let u=l.componentName;if(void 0===u){let e=t[0].componentName+"|"+r+"|";l.uniqueIdentifier?e+=l.uniqueIdentifier:e+=o,u=createUniqueName(l.componentType.toLowerCase(),e),u=a+u}let c=(await this.createChildrenThenComponent({serializedComponent:l,componentName:u,ancestors:t,componentClass:e,shadow:n,namespaceForUnamed:a,componentsReplacementOf:i})).newComponent;s.push(c)}return{components:s}}async createChildrenThenComponent({serializedComponent:e,componentName:t,ancestors:n,componentClass:r,shadow:a=!1,namespaceForUnamed:i="/",componentsReplacementOf:s}){let o=e.children,l=[],u=[],c=[{componentName:t,componentClass:r},...n],p=this.parameterStack.parameters;this.parameterStack.push();let d=this.parameterStack.parameters;if(r.descendantCompositesMustHaveAReplacement&&!a?(d.compositesMustHaveAReplacement=!0,d.compositesDefaultReplacementType=r.descendantCompositesDefaultReplacementType):(!1===r.descendantCompositesMustHaveAReplacement||a)&&(d.compositesMustHaveAReplacement=!1),r.modifySharedParameters&&r.modifySharedParameters({sharedParameters:d,serializedComponent:e}),e.doenetAttributes.pushSharedParameters)for(let t of e.doenetAttributes.pushSharedParameters){let e=t.parameterName;d[e]=e in d?[...d[e]]:[],d[e].push(t.value)}if(e.doenetAttributes.addToSharedParameters)for(let t of e.doenetAttributes.addToSharedParameters){let e=t.parameterName;d[e]=e in d?Object.assign({},d[e]):{},d[e][t.key]=t.value}if(void 0!==o){if(r.preprocessSerializedChildren&&r.preprocessSerializedChildren({serializedChildren:o,attributes:e.attributes,componentName:t}),r.setUpVariant){let t=gatherVariantComponents({serializedComponents:o,componentInfoObjects:this.componentInfoObjects});r.setUpVariant({serializedComponent:e,sharedParameters:d,descendantVariantComponents:t})}if(r.keepChildrenSerialized){let t=new Set([]),n=r.keepChildrenSerialized({serializedComponent:e,componentInfoObjects:this.componentInfoObjects});for(let e of n){if(t.has(Number(e)))throw Error("Invalid instructions to keep children serialized from "+r.componentType+": child repeated");t.add(Number(e)),u.push(o[e])}let s=[];for(let[e,n]of o.entries())t.has(e)||s.push(n);if(s.length>0){l=(await this.createIsolatedComponentsSub({serializedComponents:s,ancestors:c,shadow:a,namespaceForUnamed:i})).components}}else{l=(await this.createIsolatedComponentsSub({serializedComponents:o,ancestors:c,shadow:a,namespaceForUnamed:i})).components}}let m={};if(e.attributes)for(let t in e.attributes){if(e.attributes[t].component){let n=await this.createIsolatedComponentsSub({serializedComponents:[e.attributes[t].component],ancestors:c,shadow:a,namespaceForUnamed:i,createNameContext:`attribute|${t}`});m[t]={component:n.components[0]}}else m[t]=e.attributes[t]}let h={};e.downstreamDependencies&&Object.assign(h,e.downstreamDependencies);let f=await this.createStateVariableDefinitions({componentClass:r,prescribedDependencies:h,componentName:t});delete this.updateInfo.deletedComponents[t],delete this.updateInfo.deletedStateVariables[t];let y=new r({componentName:t,ancestors:n,definingChildren:l,stateVariableDefinitions:f,serializedChildren:u,serializedComponent:e,attributes:m,componentInfoObjects:this.componentInfoObjects,coreFunctions:this.coreFunctions,flags:this.flags,shadow:a,numerics:this.numerics,sharedParameters:d,parentSharedParameters:p});this.registerComponent(y),s&&(y.replacementOf=s),e.adaptedFrom&&(y.adaptedFrom=this._components[e.adaptedFrom],y.adaptedFrom.adapterUsed=y);for(let e in h){let t=h[e];for(let n of t)if("referenceShadow"===n.dependencyType){let t={componentName:e};Object.assign(t,n),delete t.dependencyType,y.shadows=t;let r=this._components[e];if(r.shadowedBy||(r.shadowedBy=[]),r.shadowedBy.push(y),n.isPrimaryShadow&&(r.primaryShadow=y.componentName,this.dependencies.updateTriggers.primaryShadowDependencies[e]))for(let t of this.dependencies.updateTriggers.primaryShadowDependencies[e])await t.recalculateDownstreamComponents();break}}e.unlinkedCopySource&&(y.unlinkedCopySource=e.unlinkedCopySource),await this.deriveChildResultsFromDefiningChildren({parent:y,expandComposites:!1}),await this.initializeComponentStateVariables(y),await this.dependencies.setUpComponentDependencies(y);let g=await this.dependencies.checkForDependenciesOnNewComponent(t);for(let e of g)await this.markStateVariableAndUpstreamDependentsStale({component:this._components[e.componentName],varName:e.varName});return await this.checkForStateVariablesUpdatesForNewComponent(t),await this.dependencies.resolveStateVariablesIfReady({component:y}),await this.checkForActionChaining({component:y}),this.parameterStack.pop(),{newComponent:y}}async checkForStateVariablesUpdatesForNewComponent(e){if(e in this.updateInfo.stateVariableUpdatesForMissingComponents){let t=await this.processNewStateVariableValues({[e]:this.updateInfo.stateVariableUpdatesForMissingComponents[e]}),n=this._components[e];if(n.constructor.processWhenJustUpdatedForNewComponent||t.foundIgnore)for(let r in this.updateInfo.stateVariableUpdatesForMissingComponents[e])n.state[r]&&(this.updateInfo.stateVariablesToEvaluate.push({componentName:e,stateVariable:r}),n.state[r].justUpdatedForNewComponent=!0,t.foundIgnore&&(n.reprocessAfterEvaluate=this.updateInfo.stateVariableUpdatesForMissingComponents[e]));delete this.updateInfo.stateVariableUpdatesForMissingComponents[e]}}async deriveChildResultsFromDefiningChildren({parent:e,expandComposites:t=!0,forceExpandComposites:n=!1}){if(this.derivingChildResults||(this.derivingChildResults=[]),this.derivingChildResults.includes(e.componentName))return{success:!1,skipping:!0};this.derivingChildResults.push(e.componentName);let r,a=await this.expandCompositeOfDefiningChildren(e,e.definingChildren,t,n);e.unexpandedCompositesReady=a.unexpandedCompositesReady,e.unexpandedCompositesNotReady=a.unexpandedCompositesNotReady,e.activeChildren&&(r=e.activeChildren.map((e=>e.componentName?e.componentName:e))),e.activeChildren=e.definingChildren.slice(),e.allChildren={},e.allChildrenOrdered=[];for(let t=0;te.componentType)).join(", ");this.unmatchedChildren[e.componentName]={message:`invalid children of type(s): ${t}`}}await this.dependencies.addBlockersFromChangedActiveChildren({parent:e});let s=this.derivingChildResults.indexOf(e.componentName);if(this.derivingChildResults.splice(s,1),e.constructor.renderChildren){let t=r&&r.length==e.activeChildren.length&&e.activeChildren.every(((e,t)=>e.componentName?e.componentName===r[t]:e===r[t]));t||this.componentsWithChangedChildrenToRender.add(e.componentName)}return i}async expandCompositeOfDefiningChildren(e,t,n,r){let a=[],i=[];for(let s=0;s=n)break;if(!r||r.includes(a))if("object"==typeof i)!i.constructor.sendToRendererEvenIfHidden&&await i.stateValues.hidden||t.push(a);else{let n=!1;if(e.compositeReplacementActiveRange)for(let t of e.compositeReplacementActiveRange){let e=this._components[t.compositeName];if(await e.stateValues.hidden&&t.firstInd<=a&&t.lastInd>=a){n=!0;break}}n||t.push(a)}}return t}async substituteAdapter({parent:e,childInd:t,adapterIndUsed:n}){let r,a=e.activeChildren[t];r=a.componentName?a.getAdapter(n):{componentType:this.componentInfoObjects.allComponentClasses[a.componentType].getAdapterComponentType(n,this.componentInfoObjects.publicStateVariableInfo),placeholderInd:a.placeholderInd+"adapt"};let i=a.adapterUsed;if(void 0===i||i.componentType!==r.componentType)if(a.componentName){let t;t=e.attributes.newNamespace?.primitive?e.componentName+"/":getNamespaceFromName(e.componentName),r.adaptedFrom=a.componentName,i=(await this.createIsolatedComponentsSub({serializedComponents:[r],shadow:!0,ancestors:a.ancestors,createNameContext:a.componentName+"|adapter",namespaceForUnamed:t})).components[0]}else r.adaptedFrom=a,i=r;if(e.activeChildren.splice(t,1,i),a.componentName&&(delete e.allChildren[a.componentName].activeChildrenIndex,e.allChildren[i.componentName]={activeChildrenIndex:t,component:i}),a.componentName){let t=e.allChildrenOrdered.indexOf(a.componentName);e.allChildrenOrdered.splice(t+1,0,i.componentName)}else{let t=e.allChildrenOrdered.indexOf(a.placeholderInd);e.allChildrenOrdered.splice(t+1,0,i.placeholderInd)}}async expandCompositeComponent(e){if(!("readyToExpandWhenResolved"in e.state))throw Error(`Could not find state variable readyToExpandWhenResolved of composite ${e.componentName}`);if(!e.state.readyToExpandWhenResolved.isResolved)return this.updateInfo.compositesToExpand.add(e.componentName),{success:!1};if(this.updateInfo.compositesToExpand.delete(e.componentName),this.updateInfo.compositesBeingExpanded.push(e.componentName),e.parent){if(e.parent.unexpandedCompositesReady){let t=e.parent.unexpandedCompositesReady.indexOf(e.componentName);-1!==t&&e.parent.unexpandedCompositesReady.splice(t,1)}if(e.parent.unexpandedCompositesNotReady){let t=e.parent.unexpandedCompositesNotReady.indexOf(e.componentName);-1!==t&&e.parent.unexpandedCompositesNotReady.splice(t,1)}}if(e.shadows)return await this.expandShadowingComposite(e);let t=await e.constructor.createSerializedReplacements({component:this.components[e.componentName],components:this.components,workspace:e.replacementsWorkspace,componentInfoObjects:this.componentInfoObjects,flags:this.flags,resolveItem:this.dependencies.resolveItem.bind(this.dependencies),publicCaseInsensitiveAliasSubstitutions:this.publicCaseInsensitiveAliasSubstitutions.bind(this)});if(e.constructor.stateVariableToEvaluateAfterReplacements&&await e.stateValues[e.constructor.stateVariableToEvaluateAfterReplacements],!t.replacements)throw Error(`Invalid createSerializedReplacements of ${e.componentName}`);{let n=t.replacements;await this.createAndSetReplacements({component:e,serializedReplacements:n})}let n=this.updateInfo.compositesBeingExpanded.indexOf(e.componentName);if(-1===n)throw Error(`Something is wrong as we lost track that we were expanding ${e.componentName}`);return this.updateInfo.compositesBeingExpanded.splice(n,1),{success:!0,compositesExpanded:[e.componentName]}}async expandShadowingComposite(e){if(this.updateInfo.compositesBeingExpanded.includes(e.shadows.componentName)){let t=this._components[e.shadows.componentName];for(;t.shadows;)t=this._components[t.shadows.componentName];throw Error(`Circular reference involving ${t.componentName}`)}let t=this._components[e.shadows.componentName],n=[];if(!t.isExpanded){let r=await this.expandCompositeComponent(t);if(!r.success)throw Error(`expand result of ${e.componentName} was not a success even though ready to expand.`);n.push(...r.compositesExpanded)}let r=[],a=await e.stateValues.sourceAttributesToIgnore,i=await e.stateValues.sourceAttributesToIgnoreRecursively;for(let e of t.replacements)"object"==typeof e?r.push(await e.serialize({sourceAttributesToIgnore:a,sourceAttributesToIgnoreRecursively:i})):r.push(e);let s=e.replacementsWorkspace.uniqueIdentifiersUsed=[],o=e.shadows.compositeName;r=postProcessCopy({serializedComponents:r,componentName:o,uniqueIdentifiersUsed:s});let l=e.attributes.newNamespace?.primitive;if(e.attributes.isResponse){let t=e.constructor.createAttributesObject();for(let n of r){if("object"!=typeof n)continue;n.attributes||(n.attributes={});let r=convertAttributesForComponentType({attributes:{isResponse:e.attributes.isResponse},componentType:n.componentType,componentInfoObjects:this.componentInfoObjects,compositeAttributesObj:t,compositeCreatesNewNamespace:l});Object.assign(n.attributes,r)}}if(e.constructor.assignNamesToReplacements){let n,a=this.components[o],i=a.attributes.newNamespace?.primitive,s=a.doenetAttributes.assignNames,u=s?.some(Array.isArray),c=a.attributes.assignNewNamespaces?.primitive,p=this._components[a.doenetAttributes.targetComponentName];p&&(n=!this.componentInfoObjects.isCompositeComponent({componentType:p.componentType,includeNonStandard:!1})&&p.attributes.newNamespace?.primitive);let d=!u&&(l||n||i&&!s||c),m=e.doenetAttributes.assignNames;if(m&&await e.stateValues.addLevelToAssignNames&&(m=m.map((e=>[e]))),r=processAssignNames({assignNames:m,serializedComponents:r,parentName:e.componentName,parentCreatesNewNamespace:l,componentInfoObjects:this.componentInfoObjects,originalNamesAreConsistent:d,shadowingComposite:!0}).serializedComponents,p?.componentName===t.componentName&&a.doenetAttributes.fromCopyTarget){let t=deepClone(a.serializedChildren);this.componentInfoObjects.allComponentClasses[e.componentType].includeBlankStringChildren||(t=t.filter((e=>"string"!=typeof e||""!==e.trim())));let n=processAssignNames({assignNames:m,serializedComponents:t,parentName:e.componentName,parentCreatesNewNamespace:a.attributes.assignNewNamespaces?.primitive,indOffset:r.length,componentInfoObjects:this.componentInfoObjects,originalNamesAreConsistent:!0});r.push(...n.serializedComponents)}}else{let t=l;r=processAssignNames({serializedComponents:r,parentName:e.componentName,parentCreatesNewNamespace:l,componentInfoObjects:this.componentInfoObjects,originalNamesAreConsistent:t,shadowingComposite:!0}).serializedComponents}r=(await verifyReplacementsMatchSpecifiedType({component:e,replacements:r,assignNames:e.doenetAttributes.assignNames,componentInfoObjects:this.componentInfoObjects,compositeAttributesObj:e.constructor.createAttributesObject(),flags:this.flags})).replacements,await this.createAndSetReplacements({component:e,serializedReplacements:r}),t.replacementsToWithhold>0&&(e.replacementsToWithhold=t.replacementsToWithhold);let u=this.updateInfo.compositesBeingExpanded.indexOf(e.componentName);if(-1===u)throw Error(`Something is wrong as we lost track that we were expanding ${e.componentName}`);return this.updateInfo.compositesBeingExpanded.splice(u,1),n.push(e.componentName),{success:!0,compositesExpanded:n}}async createAndSetReplacements({component:e,serializedReplacements:t}){let n;this.parameterStack.push(e.sharedParameters,!1),n=e.attributes.newNamespace?.primitive?e.componentName+"/":getNamespaceFromName(e.componentName);let r=await this.createIsolatedComponentsSub({serializedComponents:t,ancestors:e.ancestors,shadow:!0,createNameContext:e.componentName+"|replacements",namespaceForUnamed:n,componentsReplacementOf:e});this.parameterStack.pop(),e.replacements=r.components,await this.dependencies.addBlockersFromChangedReplacements(e),e.isExpanded=!0}async replaceCompositeChildren(e){delete e.placeholderActiveChildrenIndices,delete e.placeholderActiveChildrenIndicesByComposite,delete e.compositeReplacementActiveRange;let t=0;for(let n=0;ne+n));e.placeholderActiveChildrenIndices||(e.placeholderActiveChildrenIndices=[]),e.placeholderActiveChildrenIndices.push(...o),e.placeholderActiveChildrenIndicesByComposite||(e.placeholderActiveChildrenIndicesByComposite={}),e.placeholderActiveChildrenIndicesByComposite[r.componentName]=o}else await this.markWithheldReplacementsInactive(r),a=r.replacements,r.replacementsToWithhold>0&&(a=a.slice(0,-r.replacementsToWithhold)),e.constructor.includeBlankStringChildren&&!e.constructor.removeBlankStringChildrenPostSugar||(a=a.filter((e=>"string"!=typeof e||/\S/.test(e))));e.compositeReplacementActiveRange||(e.compositeReplacementActiveRange=[]);for(let t of e.compositeReplacementActiveRange)t.lastInd>=n&&(t.lastInd+=a.length-1);e.compositeReplacementActiveRange.push({compositeName:r.componentName,target:await r.stateValues.target,firstInd:n,lastInd:n+a.length-1}),e.activeChildren.splice(n,1,...a),delete e.allChildren[r.componentName].activeChildrenIndex;for(let t=0;t"object"==typeof e)).map((e=>e.componentName?e.componentName:e.placeholderInd))),1!==a.length){let t=a.length-1;for(let r=n+a.length;r0&&(t-=e.replacementsToWithhold);for(let n of e.replacements.slice(0,t))await this.changeInactiveComponentAndDescendants(n,!1);for(let n of e.replacements.slice(t))await this.changeInactiveComponentAndDescendants(n,!0);if(!await e.stateValues.isInactiveCompositeReplacement){let t=e.componentName;this.updateInfo.inactiveCompositesToUpdateReplacements.has(t)&&(this.updateInfo.inactiveCompositesToUpdateReplacements.delete(t),this.updateInfo.compositesToUpdateReplacements.add(t))}}async changeInactiveComponentAndDescendants(e,t){if("object"==typeof e&&await e.stateValues.isInactiveCompositeReplacement!==t){e.state.isInactiveCompositeReplacement.value=t,await this.markUpstreamDependentsStale({component:e,varName:"isInactiveCompositeReplacement"}),this.dependencies.recordActualChangeInUpstreamDependencies({component:e,varName:"isInactiveCompositeReplacement"});for(let n in e.allChildren)await this.changeInactiveComponentAndDescendants(this._components[n],t);for(let n in e.attributes){let r=e.attributes[n].component;r&&await this.changeInactiveComponentAndDescendants(this._components[r.componentName],t)}e.replacements&&await this.markWithheldReplacementsInactive(e)}}findShadowedChildInSerializedComponents({serializedComponents:e,shadowedComponentName:t}){for(let n of e){if(n.originalName===t)return n;if(n.children){let e=this.findShadowedChildInSerializedComponents({serializedComponents:n.children,shadowedComponentName:t});if(e)return e}}}async createStateVariableDefinitions({componentClass:e,prescribedDependencies:t,componentName:n}){let r;if(t)for(let e in t){let a=t[e];for(let t of a)if("referenceShadow"===t.dependencyType){if(e===n)throw Error(`circular reference involving ${n}`);r={linkSource:"referenceShadow",targetName:e,compositeName:t.compositeName,propVariable:t.propVariable,arrayStateVariable:t.arrayStateVariable,arrayKey:t.arrayKey,ignorePrimaryStateVariable:t.ignorePrimaryStateVariable,substituteForPrimaryStateVariable:t.substituteForPrimaryStateVariable,firstLevelReplacement:t.firstLevelReplacement,additionalStateVariableShadowing:t.additionalStateVariableShadowing}}else"adapter"===t.dependencyType&&(r={linkSource:"adapter",adapterTargetIdentity:t.adapterTargetIdentity,adapterVariable:t.adapterVariable,substituteForPrimaryStateVariable:t.substituteForPrimaryStateVariable,stateVariablesToShadow:t.stateVariablesToShadow})}let a={};r||this.createAttributeStateVariableDefinitions({stateVariableDefinitions:a,componentClass:e});let i=e.returnNormalizedStateVariableDefinitions({attributeNames:Object.keys(a),numerics:this.numerics});return Object.assign(a,i),r&&("adapter"===r.linkSource?this.createAdapterStateVariableDefinitions({redefineDependencies:r,stateVariableDefinitions:a,componentClass:e}):await this.createReferenceShadowStateVariableDefinitions({redefineDependencies:r,stateVariableDefinitions:a,componentClass:e})),a}createAttributeStateVariableDefinitions({componentClass:e,stateVariableDefinitions:t}){let n=e.createAttributesObject();for(let r in n){let a=n[r];if(!a.createStateVariable)continue;let i,s=a.createStateVariable,o=t[s]={isAttribute:!0,hasEssential:!0};if(a.public)if(o.public=!0,o.shadowingInstructions={},a.createPrimitiveOfType)o.shadowingInstructions.createComponentOfType=a.createPrimitiveOfType,"string"===o.shadowingInstructions.createComponentOfType?o.shadowingInstructions.createComponentOfType="text":"stringArray"===o.shadowingInstructions.createComponentOfType?o.shadowingInstructions.createComponentOfType="textList":"numberArray"===o.shadowingInstructions.createComponentOfType&&(o.shadowingInstructions.createComponentOfType="numberList");else{if(a.createTargetComponentNames)throw Error("Cannot make a public state variable from an attribute with createTargetComponentNames");o.shadowingInstructions.createComponentOfType=a.createComponentOfType}if(a.createComponentOfType){let t=this.componentInfoObjects.allComponentClasses[a.createComponentOfType];if(!t)throw Error(`Component type ${a.createComponentOfType} does not exist so cannot create state variable for attribute ${r} of componentType ${e.componentType}.`);i=a.componentStateVariableForAttributeValue,void 0===i&&(i=t.stateVariableForAttributeValue,void 0===i&&(i="value"))}o.returnDependencies=function(){let e={};return a.fallBackToParentStateVariable&&(e.parentValue={dependencyType:"parentStateVariable",variableName:a.fallBackToParentStateVariable}),a.createPrimitiveOfType?e.attributePrimitive={dependencyType:"attributePrimitive",attributeName:r}:a.createTargetComponentNames?e.attributeTargetComponentNames={dependencyType:"attributeTargetComponentNames",attributeName:r}:e.attributeComponent={dependencyType:"attributeComponent",attributeName:r,variableNames:[i]},e},o.definition=function({dependencyValues:e,usedDefault:t}){let n;if(e.attributeComponent)n=e.attributeComponent.stateValues[i];else if(void 0!==e.attributePrimitive&&null!==e.attributePrimitive)n=e.attributePrimitive;else{if(void 0===e.attributeTargetComponentNames||null===e.attributeTargetComponentNames){return void 0!==e.parentValue&&null!==e.parentValue&&!t.parentValue?{setValue:{[s]:e.parentValue},checkForActualChange:{[s]:!0}}:{useEssentialOrDefaultValue:{[s]:!0},checkForActualChange:{[s]:!0}}}n=e.attributeTargetComponentNames}return n=validateAttributeValue({value:n,attributeSpecification:a,attribute:r}),{setValue:{[s]:n},checkForActualChange:{[s]:!0}}},a.noInverse||(o.inverseDefinition=async function({desiredStateVariableValues:e,dependencyValues:t,usedDefault:n}){if(!t.attributeComponent){if(void 0!==t.attributePrimitive&&null!==t.attributePrimitive)return{success:!1};if(void 0!==t.attributeTargetComponentNames&&null!==t.attributeTargetComponentNames)return{success:!1};if(void 0!==t.parentValue&&null!==t.parentValue&&!n.parentValue)return{success:!0,instructions:[{setDependency:"parentValue",desiredValue:e[s]}]};{let t=validateAttributeValue({value:e[s],attributeSpecification:a,attribute:r});return{success:!0,instructions:[{setEssentialValue:s,value:t}]}}}return{success:!0,instructions:[{setDependency:"attributeComponent",desiredValue:e[s],variableIndex:0}]}});let l=["forRenderer","defaultValue","propagateToProps","triggerActionOnChange"];for(let e of l)e in a&&(o[e]=a[e])}}createAdapterStateVariableDefinitions({redefineDependencies:e,stateVariableDefinitions:t,componentClass:n}){let r=this._components[e.adapterTargetIdentity.componentName],a=n.createAttributesObject();for(let n in a){let i=a[n];if(!i.createStateVariable)continue;let s=i.createStateVariable,o=t[s]={isAttribute:!0,hasEssential:!0};if(i.public)if(o.public=!0,o.shadowingInstructions={},i.createPrimitiveOfType)o.shadowingInstructions.createComponentOfType=i.createPrimitiveOfType,"string"===o.shadowingInstructions.createComponentOfType?o.shadowingInstructions.createComponentOfType="text":"stringArray"===o.shadowingInstructions.createComponentOfType?o.shadowingInstructions.createComponentOfType="textList":"numberArray"===o.shadowingInstructions.createComponentOfType&&(o.shadowingInstructions.createComponentOfType="numberList");else{if(i.createTargetComponentNames)throw Error("Cannot make a public state variable from an attribute with createTargetComponentNames");o.shadowingInstructions.createComponentOfType=i.createComponentOfType}s in r.state?o.returnDependencies=()=>({adapterTargetVariable:{dependencyType:"stateVariable",componentName:e.adapterTargetIdentity.componentName,variableName:s}}):o.returnDependencies=()=>({}),o.definition=function({dependencyValues:e,usedDefault:t}){return void 0===e.adapterTargetVariable||t.adapterTargetVariable?{useEssentialOrDefaultValue:{[s]:!0},checkForActualChange:{[s]:!0}}:{setValue:{[s]:e.adapterTargetVariable},checkForActualChange:{[s]:!0}}},i.noInverse||(o.inverseDefinition=async function({desiredStateVariableValues:e,dependencyValues:t}){return void 0===t.adapterTargetVariable?{success:!0,instructions:[{setEssentialValue:s,value:e[s]}]}:{success:!0,instructions:[{setDependency:"adapterTargetVariable",desiredValue:e[s]}]}});let l=["forRenderer","defaultValue","propagateToProps"];for(let e of l)e in i&&(o[e]=i[e])}let i="value";e.substituteForPrimaryStateVariable?i=e.substituteForPrimaryStateVariable:n.primaryStateVariableForDefinition&&(i=n.primaryStateVariableForDefinition);let s=t[i];s.returnDependencies=()=>({adapterTargetVariable:{dependencyType:"stateVariable",componentName:e.adapterTargetIdentity.componentName,variableName:e.adapterVariable}}),s.set?s.definition=function({dependencyValues:e}){return{setValue:{[i]:s.set(e.adapterTargetVariable)}}}:s.definition=function({dependencyValues:e}){return{setValue:{[i]:e.adapterTargetVariable}}},s.inverseDefinition=function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setDependency:"adapterTargetVariable",desiredValue:e[i]}]}},e.stateVariablesToShadow&&this.modifyStateDefsToBeShadows({stateVariablesToShadow:e.stateVariablesToShadow,stateVariableDefinitions:t,targetComponent:r})}async createReferenceShadowStateVariableDefinitions({redefineDependencies:e,stateVariableDefinitions:t,componentClass:n}){let r=this._components[e.targetName];e.propVariable&&!r.state[e.propVariable]&&this.checkIfArrayEntry({stateVariable:e.propVariable,component:r})&&await this.createFromArrayEntry({stateVariable:e.propVariable,component:r});let a=n.createAttributesObject();for(let e in a){let r=a[e],i=r.createStateVariable;if(!i)continue;let s,o=t[i]={isAttribute:!0,hasEssential:!0};if(r.createComponentOfType,r.public)if(o.public=!0,o.shadowingInstructions={},r.createPrimitiveOfType)o.shadowingInstructions.createComponentOfType=r.createPrimitiveOfType,"string"===o.shadowingInstructions.createComponentOfType?o.shadowingInstructions.createComponentOfType="text":"stringArray"===o.shadowingInstructions.createComponentOfType?o.shadowingInstructions.createComponentOfType="textList":"numberArray"===o.shadowingInstructions.createComponentOfType&&(o.shadowingInstructions.createComponentOfType="numberList");else{if(r.createTargetComponentNames)throw Error("Cannot make a public state variable from an attribute with createTargetComponentNames");o.shadowingInstructions.createComponentOfType=r.createComponentOfType}if(r.createComponentOfType){let t=this.componentInfoObjects.allComponentClasses[r.createComponentOfType];if(!t)throw Error(`Component type ${r.createComponentOfType} does not exist so cannot create state variable for attribute ${e} of componentType ${n.componentType}.`);s=r.componentStateVariableForAttributeValue,void 0===s&&(s=t.stateVariableForAttributeValue,void 0===s&&(s="value"))}let l={};r.createPrimitiveOfType?l.attributePrimitive={dependencyType:"attributePrimitive",attributeName:e}:r.createTargetComponentNames?l.attributeTargetComponentNames={dependencyType:"attributeTargetComponentNames",attributeName:e}:l.attributeComponent={dependencyType:"attributeComponent",attributeName:e,variableNames:[s]},r.fallBackToParentStateVariable&&(l.parentValue={dependencyType:"parentStateVariable",variableName:r.fallBackToParentStateVariable}),o.returnDependencies=()=>l,o.definition=function({dependencyValues:t,usedDefault:n}){let a;if(t.attributeComponent)a=t.attributeComponent.stateValues[s];else if(void 0!==t.attributePrimitive&&null!==t.attributePrimitive)a=t.attributePrimitive;else{if(void 0===t.attributeTargetComponentNames||null===t.attributeTargetComponentNames){return void 0!==t.parentValue&&null!==t.parentValue&&!n.parentValue?{setValue:{[i]:t.parentValue},checkForActualChange:{[i]:!0}}:{useEssentialOrDefaultValue:{[i]:!0},checkForActualChange:{[i]:!0}}}a=t.attributeTargetComponentNames}return a=validateAttributeValue({value:a,attributeSpecification:r,attribute:e}),{setValue:{[i]:a},checkForActualChange:{[i]:!0}}},r.noInverse||(o.inverseDefinition=async function({desiredStateVariableValues:t,dependencyValues:n,stateValues:a,workspace:s}){if(!n.attributeComponent){if(void 0!==n.attributePrimitive&&null!==n.attributePrimitive)return{success:!1};if(void 0!==n.attributeTargetComponentNames&&null!==n.attributeTargetComponentNames)return{success:!1};if(void 0!==n.parentValue&&null!==n.parentValue&&!usedDefault.parentValue)return{success:!0,instructions:[{setDependency:"parentValue",desiredValue:t[i]}]};{let n=validateAttributeValue({value:t[i],attributeSpecification:r,attribute:e});return{success:!0,instructions:[{setEssentialValue:i,value:n}]}}}return{success:!0,instructions:[{setDependency:"attributeComponent",desiredValue:t[i],variableIndex:0}]}});let u=["forRenderer","defaultValue","propagateToProps"];for(let e of u)e in r&&(o[e]=r[e])}if(e.propVariable){if(!e.ignorePrimaryStateVariable){let a="value";e.substituteForPrimaryStateVariable?a=e.substituteForPrimaryStateVariable:n.primaryStateVariableForDefinition&&(a=n.primaryStateVariableForDefinition);let i=t[a];if(!i)throw e.substituteForPrimaryStateVariable?Error(`Invalid public state variable of componentType ${n.componentType}: substituteForPrimaryStateVariable ${e.substituteForPrimaryStateVariable} does not exist`):Error(`Cannot have a public state variable with componentType ${n.componentType} as the class doesn't have a primary state variable for definition`);i.isShadow=!0,i.returnDependencies=()=>({targetVariable:{dependencyType:"stateVariable",componentName:r.componentName,variableName:e.propVariable}});let s=!1;void 0!==r.state[e.propVariable].defaultValue&&(i.defaultValue=r.state[e.propVariable].defaultValue,i.set&&(i.defaultValue=i.set(i.defaultValue)),i.hasEssential=!0,s=!0),i.set?i.definition=function({dependencyValues:e,usedDefault:t}){let n=i.set(e.targetVariable);return s&&t.targetVariable?{useEssentialOrDefaultValue:{[a]:{defaultValue:n}},alwaysShadow:[a]}:{setValue:{[a]:n},alwaysShadow:[a]}}:i.definition=function({dependencyValues:e,usedDefault:t}){return s&&t.targetVariable?{useEssentialOrDefaultValue:{[a]:{defaultValue:e.targetVariable}},alwaysShadow:[a]}:{setValue:{[a]:e.targetVariable},alwaysShadow:[a]}},i.inverseDefinition=function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setDependency:"targetVariable",desiredValue:e[a]}]}}}if(e.additionalStateVariableShadowing){let n=[],a=[];for(let t in e.additionalStateVariableShadowing)n.push(t),a.push(e.additionalStateVariableShadowing[t].stateVariableToShadow);this.modifyStateDefsToBeShadows({stateVariablesToShadow:n,stateVariableDefinitions:t,targetComponent:r,differentStateVariablesInTarget:a})}return}let i=!1;if("readyToExpandWhenResolved"in t){i=!0;let e=t.readyToExpandWhenResolved,n=e.returnDependencies.bind(e),a=e.definition;e.returnDependencies=function(e){let t=n(e);return t.targetReadyToExpandWhenResolved={dependencyType:"stateVariable",componentName:r.componentName,variableName:"readyToExpandWhenResolved"},t},e.definition=function(e){let t=a(e);return t.setValue&&t.setValue.readyToExpandWhenResolved&&(e.dependencyValues.targetReadyToExpandWhenResolved||(t.setValue.readyToExpandWhenResolved=!1)),t}}let s=[];for(let e in r.state){let t=r.state[e];(t.shadowVariable||t.isShadow)&&s.push(e)}this.modifyStateDefsToBeShadows({stateVariablesToShadow:s,stateVariableDefinitions:t,foundReadyToExpandWhenResolved:i,targetComponent:r})}modifyStateDefsToBeShadows({stateVariablesToShadow:e,stateVariableDefinitions:t,foundReadyToExpandWhenResolved:n,targetComponent:r,differentStateVariablesInTarget:a=[]}){let i={};for(let[s,o]of e.entries()){let l=t[o];if(void 0===l){if("__array_"!==o.slice(0,8))continue;l=t[o]={}}if(l.isShadow=!0,l.additionalStateVariablesDefined)for(let t of l.additionalStateVariablesDefined)e.includes(t)||(i[t]||(i[t]=[]),i[t].push(o));delete l.additionalStateVariablesDefined,n||delete l.stateVariablesDeterminingDependencies;let u=l.public&&l.shadowingInstructions.hasVariableComponentType;if(l.isArray)l.returnArrayDependenciesByKey=function({arrayKeys:e}){let t={};for(let n of e)t[n]={targetVariable:{dependencyType:"stateVariable",componentName:r.componentName,variableName:this.arrayVarNameFromArrayKey(n)}};let n={};return u&&(n.targetVariableComponentType={dependencyType:"stateVariableComponentType",componentName:r.componentName,variableName:o}),l.inverseShadowToSetEntireArray&&(n.targetArray={dependencyType:"stateVariable",componentName:r.componentName,variableName:o}),{globalDependencies:n,dependenciesByKey:t}},l.arrayDefinitionByKey=function({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};for(let e of n)"targetVariable"in t[e]?r[e]=t[e].targetVariable:r[e]=l.defaultValueByArrayKey?.(e);let a={setValue:{[o]:r},alwaysShadow:[o]};return"targetVariableComponentType"in e&&(a.setCreateComponentOfType={[o]:e.targetVariableComponentType}),a},l.inverseArrayDefinitionByKey=function({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n,arraySize:r,initialChange:a}){if(l.inverseShadowToSetEntireArray)return{success:!0,instructions:[{setDependency:"targetArray",desiredValue:e[o],treatAsInitialChange:a}]};let i=[];for(let r in e[o])t[r]&&i.push({setDependency:n[r].targetVariable,desiredValue:e[o][r],shadowedVariable:!0});return{success:!0,instructions:i}};else{let e=()=>({});n&&(e=l.returnDependencies.bind(l));let t=a[s];t||(t=o),l.returnDependencies=function(n){let a=Object.assign({},e(n));return a.targetVariable={dependencyType:"stateVariable",componentName:r.componentName,variableName:t},u&&(a.targetVariableComponentType={dependencyType:"stateVariableComponentType",componentName:r.componentName,variableName:t}),a},l.definition=function({dependencyValues:e,usedDefault:t}){let n={alwaysShadow:[o]};return"targetVariableComponentType"in e&&(n.setCreateComponentOfType={[o]:e.targetVariableComponentType}),t.targetVariable&&"defaultValue"in l&&l.hasEssential?n.useEssentialOrDefaultValue={[o]:{defaultValue:e.targetVariable}}:n.setValue={[o]:e.targetVariable},n},l.excludeDependencyValuesInInverseDefinition=!0,l.inverseDefinition=function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setDependency:"targetVariable",desiredValue:e[o],shadowedVariable:!0}]}}}}for(let e in i)this.modifyStateDefToDeleteVariableReferences({varNamesToDelete:i[e],stateDef:t[e]})}modifyStateDefToDeleteVariableReferences({varNamesToDelete:e,stateDef:t}){for(let n of e){let e=t.additionalStateVariablesDefined.indexOf(n);t.additionalStateVariablesDefined.splice(e,1)}let n=t.definition;t.definition=function(t){let r=n(t);for(let t in r)if(Array.isArray(r[t]))for(let n of e){let e=r[t].indexOf(n);-1!==e&&r[t].splice(e,1)}else for(let n of e)delete r[t][n];return r}}async initializeComponentStateVariables(e){for(let t in e.state)e.state[t].isAlias?(e.stateVarAliases||(e.stateVarAliases={}),e.stateVarAliases[t]=e.state[t].targetVariableName,delete e.state[t]):await this.initializeStateVariable({component:e,stateVariable:t})}async initializeStateVariable({component:e,stateVariable:t,arrayStateVariable:n,arrayEntryPrefix:r}){let a=this.getStateVariableValue;e.state[t]||(e.state[t]={});let i=e.state[t];if(i.isResolved=!1,Object.defineProperty(i,"value",{get:()=>a({component:e,stateVariable:t}),configurable:!0}),void 0!==r?await this.initializeArrayEntryStateVariable({stateVarObj:i,arrayStateVariable:n,arrayEntryPrefix:r,component:e,stateVariable:t}):i.isArray&&await this.initializeArrayStateVariable({stateVarObj:i,component:e,stateVariable:t}),i.triggerActionOnChange){let n=this.stateVariableChangeTriggers[e.componentName];n||(n=this.stateVariableChangeTriggers[e.componentName]={}),n[t]={action:i.triggerActionOnChange}}}async checkForActionChaining({component:e,stateVariables:t}){if(e){t||(t=Object.keys(e.state));for(let n of t){let t=e.state[n];if(t.chainActionOnActionOfStateVariableTargets){let r,a=t.chainActionOnActionOfStateVariableTargets,i=await t.value,s=this.originsOfActionsChangedToActions[e.componentName];s&&(r=s[n]),r||(r=[]);let o=[];if(Array.isArray(i)){o=[...i];for(let t of o){let i=r.indexOf(t);if(-1===i){let r=this.actionsChangedToActions[t];r||(r=this.actionsChangedToActions[t]=[]),r.push({componentName:e.componentName,actionName:a.triggeredAction,stateVariableDefiningChain:n,args:{}})}else r.splice(i,1)}}for(let t of r){let r=this.actionsChangedToActions[t];if(r){let a=[];for(let t of r)t.componentName===e.componentName&&t.stateVariableDefiningChain===n||a.push(t);this.actionsChangedToActions[t]=a}}o.length>0?(s||(s=this.originsOfActionsChangedToActions[e.componentName]={}),s[n]=o):s&&(delete s[n],0===Object.keys(s).length&&delete this.originsOfActionsChangedToActions[e.componentName])}}}}async initializeArrayEntryStateVariable({stateVarObj:e,arrayStateVariable:t,arrayEntryPrefix:n,component:r,stateVariable:a}){e.isArrayEntry=!0,e.arrayStateVariable=t;let i=r.state[t];if(e.definition=i.definition,e.inverseDefinition=i.inverseDefinition,e.markStale=i.markStale,e.freshnessInfo=i.freshnessInfo,e.getPreviousDependencyValuesForMarkStale=i.getPreviousDependencyValuesForMarkStale,e.provideEssentialValuesInDefinition=i.provideEssentialValuesInDefinition,e.providePreviousValuesInDefinition=i.providePreviousValuesInDefinition,e.nDimensions=i.returnEntryDimensions(n),e.entryPrefix=n,e.varEnding=a.slice(n.length),i.createWorkspace&&(e.createWorkspace=!0,e.workspace=i.workspace),i.basedOnArrayKeyStateVariables&&(e.basedOnArrayKeyStateVariables=!0),i.additionalStateVariablesDefined){e.additionalStateVariablesDefined=[];let t=i.entryPrefixes.indexOf(n);for(let n of i.additionalStateVariablesDefined){let a=r.state[n];if(a.isArray){let n=a.entryPrefixes[t]+e.varEnding;e.additionalStateVariablesDefined.push(n)}else e.additionalStateVariablesDefined.push(n)}}if(i.shadowingInstructions&&(e.shadowingInstructions={},e.wrappingComponents=i.shadowingInstructions.returnWrappingComponents(n),i.shadowingInstructions.attributesToShadow&&(e.shadowingInstructions.attributesToShadow=i.shadowingInstructions.attributesToShadow),i.shadowingInstructions.createComponentOfType)){let t=i.entryPrefixes.indexOf(n);i.shadowingInstructions.createComponentOfType[t]&&(e.shadowingInstructions.createComponentOfType=[i.shadowingInstructions.createComponentOfType[t]])}if(i.getEntryValues?e.getValueFromArrayValues=async function(){return await i.getEntryValues({varName:a})}:e.getValueFromArrayValues=async function(){let t=await e.arrayKeys;if(0===t.length)return;let n=[];for(let e of t)n.push(i.getArrayValue({arrayKey:e}));return 1===n.length?n[0]:n},e.arraySizeStateVariable=i.arraySizeStateVariable,e._arrayKeys=[],e._unflattenedArrayKeys=[],Object.defineProperty(e,"arrayKeys",{get:function(){return(async()=>(await i.arraySize,e._arrayKeys))()}}),Object.defineProperty(e,"unflattenedArrayKeys",{get:function(){return(async()=>(await i.arraySize,e._unflattenedArrayKeys))()}}),r.state[e.arraySizeStateVariable].initiallyResolved){let t=await i.arraySize,n=i.getArrayKeysFromVarName({arrayEntryPrefix:e.entryPrefix,varEnding:e.varEnding,arraySize:t,nDimensions:i.nDimensions});e._unflattenedArrayKeys=n,e._arrayKeys=flattenDeep(n);let r=i.varNamesIncludingArrayKeys;for(let t of e._arrayKeys)r[t]||(r[t]=[]),r[t].push(a)}if(i.arrayEntryNames.push(a),Object.defineProperty(e,"arraySize",{get:()=>i.arraySize}),Object.defineProperty(e,"arrayEntrySize",{get:function(){return(async()=>{let t=[],n=[await e.unflattenedArrayKeys];for(let r=0;r1?(e.keyToIndex=e=>e.split(",").map((e=>Number(e))),e.setArrayValue=function({value:t,arrayKey:n,arraySize:r,arrayValues:a=e.arrayValues}){let i=e.keyToIndex(n),s=i.length;if(!s>e.nDimensions)return console.warn("Cannot set array value. Number of dimensions is too large."),{nFailures:1};let o=a,l=r;for(let c of i.slice(0,i.length-1)){if(!(c>=0&&ca&&(console.warn("ignoring array values of out bounds"),r+=e.length-a,e=e.slice(0,a)),1===n.length)for(let[n,r]of e.entries())t[n]=r;else for(let[a,i]of e.entries()){t[a]||(t=[]),r+=p(i,t[a],n[a]).nFailures}return{nFailures:r}}u+=p(t,o,l).nFailures}else o[i[i.length-1]]=t;return{nFailures:u}},e.getArrayValue=function({arrayKey:t,arrayValues:n=e.arrayValues}){let r=e.keyToIndex(t),a=n;for(let e of r.slice(0,r.length-1))if(a=a[e],!a)return;return a[r[r.length-1]]},e.getAllArrayKeys||(e.getAllArrayKeys=function(e,t=!0,n){function r(e,t){for(let[n,a]of e.entries())Array.isArray(a)?r(a,t):e[n]=t+","+a}function a(e){if(1===e.length)return Array.from(Array(e[0]),((e,t)=>String(t)));{let n=e[0],i=a(e.slice(1)),s=[];for(let e=0;ee+","+t)));else{let t=deepClone(i);r(t,e),s.push(t)}return s}}return n?0===n.length?[]:a(n):e&&0!==e.length?a(e):[]}),e.arrayVarNameFromArrayKey||(e.arrayVarNameFromArrayKey=function(e){return r[0]+e.split(",").map((e=>Number(e)+1)).join("_")}),e.arrayVarNameFromPropIndex||(e.arrayVarNameFromPropIndex=function(t,n){return r[0]+[...t.map((e=>Math.round(Number(e)))),...Array(e.nDimensions-t.length).fill(1)].join("_")}),e.adjustArrayToNewArraySize=async function(){let t=await e.arraySize;!function e(t,n){if(t.length=n[0],n.length>1){let r=n.slice(1);for(let[n,a]of t.entries())a||(a=t[n]=[]),e(a,r)}}(e.arrayValues,t)}):(e.keyToIndex=e=>Number(e),e.setArrayValue=function({value:t,arrayKey:r,arraySize:a,arrayValues:i=e.arrayValues}){let s=e.keyToIndex(r);return s>=0&&sString(t))):e&&0!==e.length?Array.from(Array(e[0]),((e,t)=>String(t))):[]}),e.arrayVarNameFromArrayKey||(e.arrayVarNameFromArrayKey=function(e){return r[0]+String(Number(e)+1)}),e.arrayVarNameFromPropIndex||(e.arrayVarNameFromPropIndex=function(e,t){return r[0]+e[0]}),e.adjustArrayToNewArraySize=async function(){let t=await e.arraySize;e.arrayValues.length=t[0]}),e.getArrayKeysFromVarName||(e.getArrayKeysFromVarName=returnDefaultGetArrayKeysFromVarName(e.nDimensions)),e.indexToKey=e=>String(e);let r=e.entryPrefixes;r||(r=e.entryPrefixes=[n]),t.arrayEntryPrefixes||(t.arrayEntryPrefixes={});for(let e of r)t.arrayEntryPrefixes[e]=n;e.returnEntryDimensions||(e.returnEntryDimensions=()=>1),e.shadowingInstructions&&(e.shadowingInstructions.returnWrappingComponents||(e.shadowingInstructions.returnWrappingComponents=e=>[]),e.wrappingComponents=e.shadowingInstructions.returnWrappingComponents()),e.usedDefaultByArrayKey={},e.arrayEntryNames=[],e.varNamesIncludingArrayKeys={};let a=[n];function i(t,n,r){let a={},i={};for(let n of e.dependencyNames.global)a[n]=t[n],i[n]=r[n];let s={},o={},l={};for(let a of n)if(s[a]={},o[a]={},a in e.dependencyNames.namesByKey){l[a]=!0;for(let n in e.dependencyNames.namesByKey[a]){let i=e.dependencyNames.namesByKey[a][n];i in t?(s[a][n]=t[i],o[a][n]=r[i]):l[a]=!1}}return{globalDependencyValues:a,globalUsedDefault:i,dependencyValuesByKey:s,usedDefaultByKey:o,foundAllDependencyValuesForKey:l}}if(e.additionalStateVariablesDefined&&a.push(...e.additionalStateVariablesDefined),e.returnDependencies=async function(n){n.arraySize=await e.arraySize;for(let e in n.stateValues)"__array_"===e.slice(0,8)&&delete n.stateValues[e];if(void 0===n.arrayKeys&&(n.arrayKeys=e.getAllArrayKeys(n.arraySize)),!e.dependencyNames&&(e.dependencyNames={namesByKey:{},keysByName:{},global:[]},e.additionalStateVariablesDefined))for(let n of e.additionalStateVariablesDefined)t.state[n].dependencyNames=e.dependencyNames;let r={};if(e.basedOnArrayKeyStateVariables&&n.arrayKeys.length>1)for(let e of n.arrayKeys)for(let n of a){let a=t.state[n];r[n+"_"+e]={dependencyType:"stateVariable",variableName:a.arrayVarNameFromArrayKey(e)}}else{let t=e.returnArrayDependenciesByKey(n);t.globalDependencies&&(e.dependencyNames.global=Object.keys(t.globalDependencies),Object.assign(r,t.globalDependencies)),t.dependenciesByKey||(t.dependenciesByKey={});for(let a of n.arrayKeys){a in e.dependencyNames.namesByKey||(n.changedDependency=!0),e.dependencyNames.namesByKey[a]={};for(let n in t.dependenciesByKey[a]){let i="__"+a+"_"+n;r[i]=t.dependenciesByKey[a][n],e.dependencyNames.namesByKey[a][n]=i,e.dependencyNames.keysByName[i]||(e.dependencyNames.keysByName[i]=[]),e.dependencyNames.keysByName[i].includes(a)||e.dependencyNames.keysByName[i].push(a)}}e.dependencyNames.global.push("__array_size")}return r.__array_size={dependencyType:"stateVariable",variableName:e.arraySizeStateVariable},r},e.getCurrentFreshness=function({freshnessInfo:t,arrayKeys:r,arraySize:a}){void 0===r&&(r=e.getAllArrayKeys(a));let i=t.freshByKey,s=t.freshArraySize?1:0;for(let e of r)i[e]&&(s+=1);return s>0?s===r.length+1?{fresh:{[n]:!0}}:{partiallyFresh:{[n]:s}}:{fresh:{[n]:!1}}},e.markStale=function({freshnessInfo:t,changes:r,arrayKeys:a,arraySize:i}){let s={};void 0===a&&(a=e.getAllArrayKeys(i)),e.markStaleByKey&&(s=e.markStaleByKey({arrayKeys:a,changes:r}));let o=t.freshByKey;if(r.__array_size)return t.freshArraySize=!1,t.freshByKey={},s.fresh={[n]:!1},s;if(0===Object.keys(o).length)return t.freshByKey={},t.freshArraySize?(s.partiallyFresh={[n]:1},s):(s.fresh={[n]:!1},s);for(let i in r){if(e.dependencyNames.global.includes(i))return t.freshByKey={},t.freshArraySize?(s.partiallyFresh={[n]:1},s):(s.fresh={[n]:!1},s);if(e.basedOnArrayKeyStateVariables&&a.length>1)delete o[i];else for(let t of e.dependencyNames.keysByName[i])delete o[t]}let l=t.freshArraySize?1:0;for(let e of a)o[e]&&(l+=1);return l>0?l===a.length+1?(s.fresh={[n]:!0},s):(s.partiallyFresh={[n]:l},s):(s.fresh={[n]:!1},s)},e.freshenOnNoChanges=function({arrayKeys:t,freshnessInfo:n,arraySize:r}){let a=n.freshByKey;void 0===t&&(t=e.getAllArrayKeys(r));for(let e of t)a[e]=!0},e.definition=function(r){if(void 0===r.arrayKeys&&(r.arrayKeys=e.getAllArrayKeys(r.arraySize)),e.basedOnArrayKeyStateVariables&&r.arrayKeys.length>1)return{};{let a=i(r.dependencyValues,r.arrayKeys,r.usedDefault),s=a.globalDependencyValues,o=a.globalUsedDefault,l=a.dependencyValuesByKey,u=a.usedDefaultByKey,c=a.foundAllDependencyValuesForKey;delete r.dependencyValues,r.globalDependencyValues=s,r.globalUsedDefault=o,r.dependencyValuesByKey=l,r.usedDefaultByKey=u;let p,d=[],m=r.freshnessInfo.freshByKey;for(let e of r.arrayKeys)!m[e]&&c[e]&&(m[e]=!0,d.push(e));if(0===d.length)p={};else{if(r.arrayKeys=d,!e.arrayDefinitionByKey)throw Error(`For ${n} of ${t.componentType}, arrayDefinitionByKey must be a function`);if(p=e.arrayDefinitionByKey(r),p.setValue&&p.setValue[n])for(let e in p.setValue[n])m[e]=!0;if(p.useEssentialOrDefaultValue&&p.useEssentialOrDefaultValue[n])for(let e in p.useEssentialOrDefaultValue[n])m[e]=!0}if(!r.freshnessInfo.freshArraySize){if(r.changes.__array_size&&(p.arraySizeChanged=[n],e.additionalStateVariablesDefined))for(let n of e.additionalStateVariablesDefined)t.state[n].isArray&&p.arraySizeChanged.push(n);r.freshnessInfo.freshArraySize=!0}return p}},e.inverseDefinition=function(t){if(!e.inverseArrayDefinitionByKey)return{success:!1};if(void 0===t.arrayKeys&&(t.arrayKeys=e.getAllArrayKeys(t.arraySize)),e.basedOnArrayKeyStateVariables&&t.arrayKeys.length>1){let e=[];for(let n of a)for(let r in t.desiredStateVariableValues[n]){let a=n+"_"+r;a in t.dependencyValues&&e.push({setDependency:a,desiredValue:t.desiredStateVariableValues[n][r],treatAsInitialChange:t.initialChange})}return{success:!0,instructions:e}}{let n=i(t.dependencyValues,t.arrayKeys,t.usedDefault),r=n.globalDependencyValues,a=n.globalUsedDefault,s=n.dependencyValuesByKey,o=n.usedDefaultByKey;delete t.dependencyValues,t.globalDependencyValues=r,t.globalUsedDefault=a,t.dependencyValuesByKey=s,t.usedDefaultByKey=o,t.dependencyNamesByKey=e.dependencyNames.namesByKey;let l={};for(let e in t.desiredStateVariableValues)if(Array.isArray(t.desiredStateVariableValues[e]))l[e]=t.desiredStateVariableValues[e];else{l[e]={};for(let n in t.desiredStateVariableValues[e])t.arrayKeys.includes(n)&&(l[e][n]=t.desiredStateVariableValues[e][n])}return t.desiredStateVariableValues=l,e.inverseArrayDefinitionByKey(t)}},await this.createArraySizeStateVariable({stateVarObj:e,component:t,stateVariable:n}),e.arraySizeStale=!0,e.previousArraySize=[],Object.defineProperty(e,"arraySize",{get:function(){return(async()=>t.state[e.arraySizeStateVariable].initiallyResolved?(e.arraySizeStale&&await e.recalculateArraySizeDependentQuantities(),await t.stateValues[e.arraySizeStateVariable]):[])()}}),e.recalculateArraySizeDependentQuantities=async function(){let n=await t.stateValues[e.arraySizeStateVariable];if(e.previousArraySize.length!==n.length||e.previousArraySize.some(((e,t)=>e!=n[t]))){e.previousArraySize=[...n];let r=e.varNamesIncludingArrayKeys={};for(let a of e.arrayEntryNames){let i=t.state[a],s=e.getArrayKeysFromVarName({arrayEntryPrefix:i.entryPrefix,varEnding:i.varEnding,arraySize:n,nDimensions:e.nDimensions});i._unflattenedArrayKeys=s,i._arrayKeys=flattenDeep(s);for(let e of i._arrayKeys)r[e]||(r[e]=[]),r[e].push(a)}}e.arraySizeStale=!1},!e.freshnessInfo&&(e.freshnessInfo={freshByKey:{}},e.additionalStateVariablesDefined))for(let n of e.additionalStateVariablesDefined)t.state[n]||(t.state[n]={}),t.state[n].freshnessInfo=e.freshnessInfo}async createArraySizeStateVariable({stateVarObj:e,component:t,stateVariable:n}){let r=[n];e.additionalStateVariablesDefined&&r.push(...e.additionalStateVariablesDefined),r.sort();let a="__array_size_"+r.join("_");if(e.arraySizeStateVariable=a,e.stateVariablesDeterminingDependencies?(e.stateVariablesDeterminingDependencies,e.stateVariablesDeterminingDependencies.push(a)):e.stateVariablesDeterminingDependencies=[a],t.state[a]){if(t.state[a].isShadow){t.state[a].markStale=function(){for(let e of r)t.state[e].arraySizeStale=!0;return{}}}}else t.state[a]={returnDependencies:e.returnArraySizeDependencies,definition({dependencyValues:t}){let n=e.returnArraySize({dependencyValues:t});for(let[e,t]of n.entries())Number.isInteger(t)&&t>=0||(n[e]=0);return{setValue:{[a]:n}}},markStale(){for(let e of r)t.state[e].arraySizeStale=!0;return{}}},e.stateVariablesDeterminingArraySizeDependencies&&(t.state[a].stateVariablesDeterminingDependencies=e.stateVariablesDeterminingArraySizeDependencies),await this.initializeStateVariable({component:t,stateVariable:a})}async arrayEntryNamesFromPropIndex({stateVariables:e,component:t,propIndex:n}){let r=[];for(let a of e){let e,i=t.state[a];if(!i){if(!this.checkIfArrayEntry({stateVariable:a,component:t})){r.push(a);continue}await this.createFromArrayEntry({stateVariable:a,component:t}),i=t.state[a]}if(i.isArray)e=i.arrayVarNameFromPropIndex(n,a);else if(i.isArrayEntry){e=t.state[i.arrayStateVariable].arrayVarNameFromPropIndex(n,a)}else console.warn(`Cannot get propIndex from ${a} of ${t.componentName} as it is not an array or array entry state variable`),e=a;e?r.push(e):(console.warn(`Cannot get propIndex from ${a} of ${t.componentName}`),r.push(a))}return r}recursivelyReplaceCompositesWithReplacements({replacements:e,recurseNonStandardComposites:t=!1,forceExpandComposites:n=!1,includeWithheldReplacements:r=!1}){let a=[],i=[],s=[],o=[];for(let l of e)if(this.componentInfoObjects.isCompositeComponent({componentType:l.componentType,includeNonStandard:t}))if(a.push(l.componentName),l.isExpanded||(l.state.readyToExpandWhenResolved.isResolved?s.push(l.componentName):o.push(l.componentName)),l.isExpanded){let e=l.replacements;!r&&l.replacementsToWithhold>0&&(e=e.slice(0,-l.replacementsToWithhold));let u=this.recursivelyReplaceCompositesWithReplacements({replacements:e,recurseNonStandardComposites:t,forceExpandComposites:n,includeWithheldReplacements:r});a.push(...u.compositesFound),i.push(...u.newReplacements),s.push(...u.unexpandedCompositesReady),o.push(...u.unexpandedCompositesNotReady)}else i.push(l);else i.push(l);return{compositesFound:a,newReplacements:i,unexpandedCompositesReady:s,unexpandedCompositesNotReady:o}}async getStateVariableValue({component:e,stateVariable:t}){let n=e.state[t];if(!n)throw Error(`Can't get value of ${t} of ${e.componentName} as it doesn't exist.`);if(e.reprocessAfterEvaluate){let t=e.reprocessAfterEvaluate;delete this._components[e.componentName].reprocessAfterEvaluate;for(let n in t)e.state[n]&&await this.getStateVariableValue({component:e,stateVariable:n});await this.processNewStateVariableValues({[e.componentName]:t})}let r=n.additionalStateVariablesDefined,a=[t];r&&a.push(...r);let i=!1;for(let n of a){if(!e.state[n].isResolved){if(!(await this.dependencies.resolveItem({componentName:e.componentName,type:"stateVariable",stateVariable:n,force:!0})).success)throw Error(`Can't get value of ${t} of ${e.componentName} as ${n} couldn't be resolved.`)}e.state[n].justUpdatedForNewComponent&&(delete this._components[e.componentName].state[n].justUpdatedForNewComponent,i=!0)}let s=await this.getStateVariableDefinitionArguments({component:e,stateVariable:t});s.componentInfoObjects=this.componentInfoObjects,s.justUpdatedForNewComponent=i,s.freshnessInfo=n.freshnessInfo;let o,l=s.arraySize;if(0!==Object.keys(s.changes).length||void 0===n._previousValue||n.forceRecalculation)delete n.forceRecalculation,o=n.definition(s);else{let e=[t];r&&e.push(...r),o={noChanges:e},n.freshenOnNoChanges&&n.freshenOnNoChanges(s)}let u={[t]:!1},c={};if(r)for(let e of r)u[e]=!1;for(let n in o.setValue){if(!(n in e.state))throw Error(`Definition of state variable ${t} of ${e.componentName} returned value of ${n}, which isn't a state variable.`);let r;if(n in u)u[n]=!0,e.state[n].isArray?c[n]||(c[n]={arrayKeysChanged:{}}):c[n]=!0;else{if(e.state[n].isArray&&e.state[n].arrayEntryNames)for(let t of e.state[n].arrayEntryNames)if(t in u){r=t,u[t]=!0,c[t]=!0;break}if(!r)throw Error(`Attempting to set value of stateVariable ${n} in definition of ${t} of ${e.componentName}, but it's not listed as an additional state variable defined.`)}if(!(e.state[n].isResolved||r&&e.state[r].isResolved))throw Error(`Attempting to set value of stateVariable ${n} of ${e.componentName} while it is still unresolved!`);if(e.state[n].isArray){c[n]||(c[n]={arrayKeysChanged:{}});let t={};o.checkForActualChange&&o.checkForActualChange[n]&&(t=o.checkForActualChange[n]);for(let r in o.setValue[n])if(t[r]){e.state[n].getArrayValue({arrayKey:r})!==o.setValue[n][r]&&(e.state[n].setArrayValue({value:o.setValue[n][r],arrayKey:r,arraySize:l}),e.state[n].usedDefaultByArrayKey[r]=!1,c[n].arrayKeysChanged[r]=!0)}else e.state[n].setArrayValue({value:o.setValue[n][r],arrayKey:r,arraySize:l}),e.state[n].usedDefaultByArrayKey[r]=!1,c[n].arrayKeysChanged[r]=!0}else if(delete e.state[n].value,e.state[n].value=o.setValue[n],delete e.state[n].usedDefault,o.checkForActualChange?.[n]){let t=e.state[n].value,r=e.state[n]._previousValue;(t===r||Array.isArray(t)&&Array.isArray(r)&&t.length===r.length&&t.every(((e,t)=>e===r[t])))&&delete c[n]}}for(let n in o.useEssentialOrDefaultValue){if(!(n in e.state))throw Error(`Definition of state variable ${t} of ${e.componentName} requested essential or default value of ${n}, which isn't a state variable.`);if(!e.state[n].hasEssential)throw Error(`Definition of state variable ${t} of ${e.componentName} requested essential or default value of ${n}, but hasEssential is not set.`);let r;if(n in u)u[n]=!0,e.state[n].isArray?c[n]||(c[n]={arrayKeysChanged:{}}):c[n]=!0;else{if(e.state[n].isArray&&e.state[n].arrayEntryNames)for(let t of e.state[n].arrayEntryNames)if(t in u){r=t,u[t]=!0,c[t]=!0;break}if(!r)throw Error(`Attempting to set value of stateVariable ${n} in definition of ${t} of ${e.componentName}, but it's not listed as an additional state variable defined.`)}if(!(e.state[n].isResolved||r&&e.state[r].isResolved))throw Error(`Attempting to set value of stateVariable ${n} of ${e.componentName} while it is still unresolved!`);let a=n;e.state[n].essentialVarName&&(a=e.state[n].essentialVarName);let i=e.essentialState[a];if(e.state[n].isArray){c[n]||(c[n]={arrayKeysChanged:{}});let t={};o.checkForActualChange&&o.checkForActualChange[n]&&(t=o.checkForActualChange[n]);for(let r in o.useEssentialOrDefaultValue[n]){let s,u;if(t[r]&&(s=e.state[n].getArrayValue({arrayKey:r})),Array.isArray(i)?u=e.state[n].getArrayValue({arrayKey:r,arrayValues:i}):i=e.essentialState[a]=[],void 0!==u)e.state[n].setArrayValue({value:u,arrayKey:r,arraySize:l});else{let t=o.useEssentialOrDefaultValue[n][r].defaultValue;if(void 0!==t)e.state[n].setArrayValue({value:t,arrayKey:r,arraySize:l}),e.state[n].usedDefaultByArrayKey[r]=!0;else{if(void 0===e.state[n].defaultValueByArrayKey?.(r))throw Error(`Neither value nor default value specified; state variable: ${n}, component: ${e.componentName}, arrayKey: ${r}.`);e.state[n].setArrayValue({value:e.state[n].defaultValueByArrayKey(r),arrayKey:r,arraySize:l}),e.state[n].usedDefaultByArrayKey[r]=!0}}if(t[r]){e.state[n].getArrayValue({arrayKey:r})!==s&&(c[n].arrayKeysChanged[r]=!0)}else c[n].arrayKeysChanged[r]=!0}}else{if(void 0!==i)delete e.state[n].value,e.state[n].value=i;else{let t=o.useEssentialOrDefaultValue[n].defaultValue;if(void 0!==t)delete e.state[n].value,e.state[n].value=t,e.state[n].usedDefault=!0;else{if(void 0===e.state[n].defaultValue)throw Error(`Neither value nor default value specified; state variable: ${n}, component: ${e.componentName}.`);delete e.state[n].value,e.state[n].value=e.state[n].defaultValue,e.state[n].usedDefault=!0}}if(o.checkForActualChange?.[n]){let t=e.state[n].value,r=e.state[n]._previousValue;(t===r||Array.isArray(t)&&Array.isArray(r)&&t.length===r.length&&t.every(((e,t)=>e===r[t])))&&delete c[n]}}}for(let n in o.markAsUsedDefault){if(!e.state[n].isResolved)throw Error(`Marking state variable as used default when it isn't yet resolved: ${n} of ${e.componentName}`);if(!(n in u)){let r;if(e.state[n].isArray&&e.state[n].arrayEntryNames)for(let t of e.state[n].arrayEntryNames)if(t in u){r=t;break}if(!r)throw Error(`Marking state variable ${n} as used default in definition of ${t} of ${e.componentName}, but it's not listed as an additional state variable defined.`)}if(Array.isArray())for(let t in o.markAsUsedDefault[n])o.markAsUsedDefault[n][t]&&(e.state[n].usedDefaultByArrayKey[t]=!0);else o.markAsUsedDefault[n]&&(e.state[n].usedDefault=!0)}if(o.noChanges)for(let n of o.noChanges){if(e.state[n].isResolved||(e.state[n].isResolved=!0),!(n in u)){let r;if(e.state[n].isArray&&e.state[n].arrayEntryNames)for(let t of e.state[n].arrayEntryNames)if(t in u){r=t;break}if(!r)throw Error(`Claiming stateVariable ${n} is unchanged in definition of ${t} of ${e.componentName}, but it's not listed as an additional state variable defined.`)}u[n]=!0,(Object.getOwnPropertyDescriptor(e.state[n],"value").get||e.state[n].immutable)&&(delete e.state[n].value,e.state[n].value=e.state[n]._previousValue)}for(let n in o.setEssentialValue){if(!(n in e.state))throw Error(`Definition of state variable ${t} of ${e.componentName} tried to make ${n} essential, which isn't a state variable.`);if(!(n in u)){let r;if(e.state[n].isArray&&e.state[n].arrayEntryNames)for(let t of e.state[n].arrayEntryNames)if(t in u){r=t;break}if(!r)throw Error(`Attempting to set essential value of stateVariable ${n} in definition of ${t} of ${e.componentName}, but it's not listed as an additional state variable defined.`)}if(!e.state[n].hasEssential)throw Error(`Attempting to set the essential value of stateVariable ${n} in definition of ${t} of ${e.componentName}, but it does not have an essential value`);if(!e.state[n].shadowVariable&&!e.state[n].doNotShadowEssential)throw Error(`Attempting to set the essential value of stateVariable ${n} in definition of ${t} of ${e.componentName}, but it is not allowed unless the state variable is shadowed or the essential state is not shadowed.`);this.essentialValuesSavedInDefinition[e.componentName]||(this.essentialValuesSavedInDefinition[e.componentName]={});let r=n;if(e.state[n].essentialVarName&&(r=e.state[n].essentialVarName),e.state[n].isArray){let t=e.essentialState[r];Array.isArray(t)||(t=e.essentialState[r]=[]),this.essentialValuesSavedInDefinition[e.componentName][n]||(this.essentialValuesSavedInDefinition[e.componentName][n]={mergeObject:!0});for(let r in o.setEssentialValue[n])e.state[n].setArrayValue({value:o.setEssentialValue[n][r],arrayKey:r,arraySize:l,arrayValues:t}),this.essentialValuesSavedInDefinition[e.componentName][n][r]=o.setEssentialValue[n][r]}else e.essentialState[r]=o.setEssentialValue[n],this.essentialValuesSavedInDefinition[e.componentName][n]=o.setEssentialValue[n]}if(o.setCreateComponentOfType)for(let t in o.setCreateComponentOfType){if(!e.state[t].shadowingInstructions?.hasVariableComponentType)throw Error(`Cannot set type of ${t} of ${e.componentName} as it it does not have the hasVariableComponentType attribute.`);let n=!1,r=e.state[t].shadowingInstructions;r||(r=e.state[t].shadowingInstructions={});let a=r.createComponentOfType,i=o.setCreateComponentOfType[t];if(Array.isArray(a)?Array.isArray(i)?(a.length!==i.length||a.some(((e,t)=>e!=i[t])))&&(n=!0):n=!0:n=!!Array.isArray(i)||a!==i,n&&(c[t]=!0),r.createComponentOfType=o.setCreateComponentOfType[t],e.state[t].isArray&&e.state[t].arrayEntryNames){let n=o.setCreateComponentOfType[t],r=Array.isArray(n);for(let a of e.state[t].arrayEntryNames)if(r){let r=await e.state[a].arrayKeys,i=[];for(let a of r){let r=e.state[t].keyToIndex(a);i.push(n[r])}e.state[a].shadowingInstructions.createComponentOfType=i}else e.state[a].shadowingInstructions.createComponentOfType=n}}if(o.arraySizeChanged)for(let t of o.arraySizeChanged)await e.state[t].adjustArrayToNewArraySize(),void 0===c[t]?c[t]={arrayKeysChanged:{}}:!0===c[t]&&(c[t]={allArrayKeysChanged:!0,arrayKeysChanged:{}}),c[t].arraySizeChanged=!0;for(let n in u){if(!(u[n]||e.state[n].isArrayEntry||e.state[n].isArray))throw Error(`definition of ${t} of ${e.componentName} didn't return value of ${n}`);e.state[n].isArray?(delete e.state[n].value,e.state[n].value=e.state[n].arrayValues):e.state[n].isArrayEntry&&(delete e.state[n].value,e.state[n].value=await e.state[n].getValueFromArrayValues())}for(let t in c)if(this.dependencies.recordActualChangeInUpstreamDependencies({component:e,varName:t,changes:c[t]}),e.state[t].isArray){let n=[];if(!0===c[t]||c[t].allArrayKeysChanged||c.arraySizeChanged)e.state[t].arrayEntryNames&&(n=e.state[t].arrayEntryNames);else{let r=e.state[t].varNamesIncludingArrayKeys;for(let e in c[t].arrayKeysChanged){let t=r[e];t&&n.push(...t)}}n=[...new Set(n)];for(let t of n)this.dependencies.recordActualChangeInUpstreamDependencies({component:e,varName:t})}return await n.value}async getStateVariableDefinitionArguments({component:e,stateVariable:t,excludeDependencyValues:n}){let r;r=n?{}:await this.dependencies.getStateVariableDependencyValues({component:e,stateVariable:t}),r.componentName=e.componentName;let a=e.state[t];if(a.isArrayEntry?(r.arrayKeys=await a.arrayKeys,r.arraySize=await a.arraySize):a.isArray&&(r.arraySize=await a.arraySize),a.createWorkspace&&(r.workspace=a.workspace),a.providePreviousValuesInDefinition||a.provideEssentialValuesInDefinition){let n=[t];if(a.additionalStateVariablesDefined&&n.push(...a.additionalStateVariablesDefined),a.providePreviousValuesInDefinition){let t={};for(let r of n)e.state[r].isArrayEntry&&(r=e.state[r].arrayStateVariable),t[r]=e.state[r]._previousValue;r.previousValues=t}if(a.provideEssentialValuesInDefinition){let t={};for(let r of n){e.state[r].isArrayEntry&&(r=e.state[r].arrayStateVariable);let n=r;e.state[r].essentialVarName&&(n=e.state[r].essentialVarName),t[r]=e.essentialState[n]}r.essentialValues=t}}return r}async recordActualChangeInStateVariable({componentName:e,varName:t}){let n=this._components[e];await this.markStateVariableAndUpstreamDependentsStale({component:n,varName:t});let r=[t];n.state[t].additionalStateVariablesDefined&&r.push(...n.state[t].additionalStateVariablesDefined);for(let e of r)n.state[e].forceRecalculation=!0,this.dependencies.recordActualChangeInUpstreamDependencies({component:n,varName:e})}findCaseInsensitiveMatches({stateVariables:e,componentClass:t}){let n=this.componentInfoObjects.stateVariableInfo[t.componentType],r=[];for(let t of e){let e=!1,a=t.toLowerCase();for(let t in n.stateVariableDescriptions)if(a===t.toLowerCase()){e=!0,r.push(t);break}if(e)continue;let i=!1,s=a;"__array_size_"===a.substring(0,13)&&(i=!0,s=a.substring(13));for(let t in n.aliases)if(s===t.toLowerCase()){i&&(t="__array_size_"+t),r.push(t),e=!0;break}if(e)continue;let o=Object.keys(n.arrayEntryPrefixes).sort(((e,t)=>t.length-e.length));for(let i of o)if(a.substring(0,i.length)===i.toLowerCase()){let s=n.arrayEntryPrefixes[i].arrayVariableName,o=n.stateVariableDescriptions[s];if(o.getArrayKeysFromVarName({arrayEntryPrefix:i,varEnding:t.substring(i.length),nDimensions:o.nDimensions}).length>0){let t=i+a.substring(i.length);e=!0,r.push(t);break}}e||r.push(t)}return r}matchPublicStateVariables({stateVariables:e,componentClass:t}){let n=this.componentInfoObjects.publicStateVariableInfo[t.componentType],r=[];for(let t of e){if(t in n.stateVariableDescriptions){r.push(t);continue}let e=t;if(e in n.aliases&&(e=n.aliases[e],e in n.stateVariableDescriptions)){r.push(e);continue}let a=!1,i=Object.keys(n.arrayEntryPrefixes).sort(((e,t)=>t.length-e.length));for(let t of i)if(e.substring(0,t.length)===t){let r=n.arrayEntryPrefixes[t].arrayVariableName,i=n.stateVariableDescriptions[r];if(i.getArrayKeysFromVarName({arrayEntryPrefix:t,varEnding:e.substring(t.length),nDimensions:i.nDimensions}).length>0){a=!0;break}}a?r.push(t):r.push("__not_public_"+t)}return r}substituteAliases({stateVariables:e,componentClass:t}){let n=[],r=this.componentInfoObjects.stateVariableInfo[t.componentType];for(let t of e){let e=!1;"__array_size_"===t.substring(0,13)&&(e=!0,t=t.substring(13)),t=t in r.aliases?r.aliases[t]:t,e&&(t="__array_size_"+t),n.push(t)}return n}publicCaseInsensitiveAliasSubstitutions({stateVariables:e,componentClass:t}){let n=this.findCaseInsensitiveMatches({stateVariables:e,componentClass:t});return n=this.matchPublicStateVariables({stateVariables:n,componentClass:t}),n=this.substituteAliases({stateVariables:n,componentClass:t}),n}checkIfArrayEntry({stateVariable:e,component:t}){for(let n in t.arrayEntryPrefixes)if(e.substring(0,n.length)===n){let r=t.arrayEntryPrefixes[n],a=t.state[r];if(a.getArrayKeysFromVarName({arrayEntryPrefix:n,varEnding:e.substring(n.length),nDimensions:a.nDimensions}).length>0)return!0}return!1}async createFromArrayEntry({stateVariable:e,component:t,initializeOnly:n=!1}){if(!t.arrayEntryPrefixes)throw Error(`Unknown state variable ${e} of ${t.componentName}`);let r=Object.keys(t.arrayEntryPrefixes).sort(((e,t)=>t.length-e.length));for(let a of r)if(e.substring(0,a.length)===a){let r=t.arrayEntryPrefixes[a],i=t.state[r];if(i.getArrayKeysFromVarName({arrayEntryPrefix:a,varEnding:e.substring(a.length),nDimensions:i.nDimensions}).length>0){let r=t.arrayEntryPrefixes[a];if(await this.initializeStateVariable({component:t,stateVariable:e,arrayStateVariable:r,arrayEntryPrefix:a}),n)return;let i=[e];if(t.state[e].additionalStateVariablesDefined){i.push(...t.state[e].additionalStateVariablesDefined);for(let n of t.state[e].additionalStateVariablesDefined)t.state[n]||await this.createFromArrayEntry({stateVariable:n,component:t,initializeOnly:!0})}await this.dependencies.setUpStateVariableDependencies({component:t,stateVariable:e,allStateVariablesAffected:i,core:this});let s=[];for(let e of i)this.dependencies.checkForCircularDependency({componentName:t.componentName,varName:e}),s.push(e),t.state[e].determineDependenciesStateVariable&&s.push(t.state[e].determineDependenciesStateVariable);return void await this.dependencies.resolveStateVariablesIfReady({component:t,stateVariables:s})}}throw Error(`Unknown state variable ${e} of ${t.componentName}`)}async markStateVariableAndUpstreamDependentsStale({component:e,varName:t}){t in this.rendererVariablesByComponentType[e.componentType]&&this.updateInfo.componentsToUpdateRenderers.add(e.componentName);let n={[t]:e.state[t]};e.state[t].additionalStateVariablesDefined&&e.state[t].additionalStateVariablesDefined.forEach((t=>n[t]=e.state[t]));let r=await this.lookUpCurrentFreshness({component:e,varName:t,allStateVariablesAffectedObj:n}),a=[],i=[],s=0;for(let e in n){let t=n[e];Object.getOwnPropertyDescriptor(t,"value").get||t.immutable?r&&(r.fresh&&r.fresh[e]?i.push(e):r.partiallyFresh&&r.partiallyFresh[e]&&(s+=r.partiallyFresh[e])):a.push(e)}i.push(...a);let o=i.length>0||s>0,l={};for(let e in n)l[e]=!0;let u=!1;if(o){let r=await this.processMarkStale({component:e,varName:t,allStateVariablesAffectedObj:n});if(r.fresh)for(let e in r.fresh)r.fresh[e]&&delete l[e];let a=0;for(let e in n){if(i.includes(e)&&(!r.fresh||!r.fresh[e])){u=!0;break}r.partiallyFresh&&r.partiallyFresh[e]&&(a+=r.partiallyFresh[e])}if(an({component:e,stateVariable:t}),configurable:!0})}}if(u)for(let t in l)await this.markUpstreamDependentsStale({component:e,varName:t})}async lookUpCurrentFreshness({component:e,varName:t,allStateVariablesAffectedObj:n}){let r=e.state[t];if(!r.getCurrentFreshness)return;let a,i,s=r.freshnessInfo;if(r.isArrayEntry&&(a=r._arrayKeys),r.isArrayEntry||r.isArray){let t=e.state[r.arraySizeStateVariable];i=t._previousValue,!(Object.getOwnPropertyDescriptor(t,"value").get||t.immutable)&&(i=await t.value),Array.isArray(i)||(i=[])}let o=r.getCurrentFreshness({freshnessInfo:s,arrayKeys:a,arraySize:i});if(o.partiallyFresh)for(let e in n)if(n[e].isArrayEntry){let t=n[e].arrayStateVariable;o.partiallyFresh[e]=o.partiallyFresh[t],delete o.partiallyFresh[t]}if(o.fresh)for(let e in n)if(n[e].isArrayEntry){let t=n[e].arrayStateVariable;t in o.fresh&&(o.fresh[e]=o.fresh[t],delete o.fresh[t])}return o}async processMarkStale({component:e,varName:t,allStateVariablesAffectedObj:n}){let r=e.state[t];if(!r.markStale||!r.initiallyResolved){let e={};return Object.keys(n).forEach((t=>e[t]=!1)),{fresh:e}}let a={},i=this.dependencies.downstreamDependencies[e.componentName][t];for(let e in i){let t=i[e],n={},r=!1;t.componentIdentityChanged&&(n.componentIdentityChanged=!0,r=!0),t.componentIdentitiesChanged&&(n.componentIdentitiesChanged=!0,r=!0),t.valuesChanged&&(n.valuesChanged=t.valuesChanged,r=!0),r&&(a[e]=n)}let s,o,l=r.freshnessInfo;if(r.isArrayEntry&&(s=r._arrayKeys),r.isArrayEntry||r.isArray){let t=e.state[r.arraySizeStateVariable];o=t._previousValue,!(Object.getOwnPropertyDescriptor(t,"value").get||t.immutable)&&(o=await t.value),Array.isArray(o)||(o=[])}let u=r.markStale({freshnessInfo:l,changes:a,arrayKeys:s,arraySize:o});if(u.partiallyFresh)for(let e in n)if(n[e].isArrayEntry){let t=n[e].arrayStateVariable;u.partiallyFresh[e]=u.partiallyFresh[t],delete u.partiallyFresh[t]}if(u.fresh)for(let e in n)if(n[e].isArrayEntry){let t=n[e].arrayStateVariable;t in u.fresh&&(u.fresh[e]=u.fresh[t],delete u.fresh[t])}return u}async markUpstreamDependentsStale({component:e,varName:t}){let n,r=e.componentName,a=this.getStateVariableValue,i=this.dependencies.upstreamDependencies[r][t];if(e.state[t]&&(n=e.state[t].freshnessInfo),i)for(let s of i){let i=!1;if(s.markStale&&await s.markStale(),s.downstreamComponentNames){let e=s.downstreamComponentNames.indexOf(r);if(-1===e)continue;if(s.mappedDownstreamVariableNamesByComponent){if(-1===s.mappedDownstreamVariableNamesByComponent[e].indexOf(t))throw Error(`something went wrong as ${t} not a downstreamVariable of ${s.dependencyName}`);"determineDependencies"===s.dependencyType&&(s.recalculateDependencies=!0),s.valuesChanged||(s.valuesChanged=[]),s.valuesChanged[e]||(s.valuesChanged[e]={}),s.valuesChanged[e][t]||(s.valuesChanged[e][t]={}),s.valuesChanged[e][t].potentialChange=!0,n&&(s.valuesChanged[e][t].freshnessInfo=n),i=!0}else t===s.downstreamVariableNameIfNoVariables&&(s.valuesChanged||(s.valuesChanged={[s.downstreamVariableNameIfNoVariables]:{}}),s.componentIdentityChanged=!0,s.valuesChanged[s.downstreamVariableNameIfNoVariables].potentialChange=!0,i=!0)}if(i){for(let e of s.upstreamVariableNames)if(e in this.rendererVariablesByComponentType[this.components[s.upstreamComponentName].componentType]){this.updateInfo.componentsToUpdateRenderers.add(s.upstreamComponentName);break}let t=s.upstreamVariableNames[0],n=this._components[s.upstreamComponentName],r={};s.upstreamVariableNames.forEach((e=>r[e]=n.state[e]));let i=await this.lookUpCurrentFreshness({component:n,varName:t,allStateVariablesAffectedObj:r}),o=[],l=[],u=0;for(let e in r){let t=r[e];Object.getOwnPropertyDescriptor(t,"value").get||t.immutable?i&&(i.fresh&&i.fresh[e]?l.push(e):i.partiallyFresh&&i.partiallyFresh[e]&&(u+=i.partiallyFresh[e])):o.push(e)}l.push(...o);let c=l.length>0||u>0,p={};for(let e in r)p[e]=!0;let d=!1;if(c){let a=await this.processMarkStale({component:n,varName:t,allStateVariablesAffectedObj:r});if(a.fresh)for(let e in a.fresh)a.fresh[e]&&delete p[e];let i=0;for(let e in r){if(l.includes(e)&&(!a.fresh||!a.fresh[e])){d=!0;break}a.partiallyFresh&&a.partiallyFresh[e]&&(i+=a.partiallyFresh[e])}if(ia({component:n,stateVariable:e}),configurable:!0}))}if(d)for(let e in p)await this.markUpstreamDependentsStale({component:n,varName:e})}}}registerComponent(e){if(e.componentName in this._components)throw Error(`Duplicate componentName: ${e.componentName}`);this._components[e.componentName]=e}deregisterComponent(e,t=!0){if(!0===t)for(let t in e.allChildren)this.deregisterComponent(e.allChildren[t].component);delete this._components[e.componentName]}setAncestors(e,t=[]){e.ancestors=t;let n=[{componentName:e.componentName,componentClass:e.constructor},...e.ancestors];for(let t in e.allChildren){let e=this._components[t];this.setAncestors(e,n)}for(let t in e.attributes){let r=e.attributes[t].component;r&&this.setAncestors(r,n)}}async addChildrenAndRecurseToShadows({parent:e,indexOfDefiningChildren:t,newChildren:n,assignNamesOffset:r}){this.spliceChildren(e,t,n);let a=await this.processNewDefiningChildren({parent:e}),i={};if(!a.success)return a;for(let e of n)"object"==typeof e&&(i[e.componentName]=e);if(e.shadowedBy)for(let a of e.shadowedBy){if(a.shadows.propVariable)continue;let e=this._components[a.shadows.compositeName],s=await e.stateValues.sourceAttributesToIgnore,o=await e.stateValues.sourceAttributesToIgnoreRecursively,l=[];for(let e of n)"object"==typeof e?l.push(await e.serialize({sourceAttributesToIgnore:s,sourceAttributesToIgnoreRecursively:o})):l.push(e);l=postProcessCopy({serializedComponents:l,componentName:a.shadows.compositeName});let u=a.attributes.newNamespace?.primitive,c=u;l=processAssignNames({indOffset:r,serializedComponents:l,parentName:a.componentName,parentCreatesNewNamespace:u,componentInfoObjects:this.componentInfoObjects,originalNamesAreConsistent:c}).serializedComponents;let p,d=this._components[a.componentName];this.parameterStack.push(d.sharedParameters,!1),p=u?a.componentName+"/":getNamespaceFromName(a.componentName);let m=await this.createIsolatedComponentsSub({serializedComponents:l,ancestors:a.ancestors,createNameContext:a.componentName+"|addChildren|"+r,namespaceForUnamed:p});this.parameterStack.pop();let h=await this.addChildrenAndRecurseToShadows({parent:d,indexOfDefiningChildren:t,newChildren:m.components,assignNamesOffset:r});if(!h.success)throw Error("was able to add components to parent but not shadows!");Object.assign(i,h.addedComponents)}return{success:!0,deletedComponents:{},addedComponents:i}}async processNewDefiningChildren({parent:e,expandComposites:t=!0}){this.parameterStack.push(e.sharedParameters,!1);let n=await this.deriveChildResultsFromDefiningChildren({parent:e,expandComposites:t});this.parameterStack.pop();let r=[{componentName:e.componentName,componentClass:e.constructor},...e.ancestors];for(let t in e.allChildren){let e=this._components[t];this.setAncestors(e,r)}return n}spliceChildren(e,t,n){let r=e.definingChildren.length;if(!Number.isInteger(t)||t>r||t<0)throw Error("Can't add children at index "+t+". Invalid index.");e.definingChildren.splice(t,0,...n)}async deleteComponents({components:e,deleteUpstreamDependencies:t=!0,skipProcessingChildrenOfParents:n=[]}){Array.isArray(e)||(e=[e]);const r={};this.determineComponentsToDelete({components:e,deleteUpstreamDependencies:t,componentsToDelete:r});const a={};for(let e in r){let t=r[e],n=this.components[t.parentName];if(void 0===n||n.componentName in r)continue;let i=a[t.parentName];void 0===i&&(i={parent:this._components[t.parentName],childNamesToBeDeleted:new Set},a[t.parentName]=i),i.childNamesToBeDeleted.add(e)}let i=[];for(let e in r){let t=this._components[e];if(t.replacementOf){let n=t.replacementOf,r=n.replacements.map((e=>e.componentName)),a=r.indexOf(e);-1!==a&&(n.replacements.splice(a,1),i.includes(n.componentName)||i.push(n.componentName))}}for(let e of i)e in r||await this.dependencies.addBlockersFromChangedReplacements(this._components[e]);let s=[];for(let e in a){let t=a[e],r=t.parent;s.push(r);for(let e=r.definingChildren.length-1;e>=0;e--){let n=r.definingChildren[e];t.childNamesToBeDeleted.has(n.componentName)&&r.definingChildren.splice(e,1)}n.includes(r.componentName)||await this.processNewDefiningChildren({parent:r,expandComposites:!1})}for(let e in r){let t=this._components[e];if(t.shadows){let e=this._components[t.shadows.componentName];1===e.shadowedBy.length?delete e.shadowedBy:e.shadowedBy.splice(e.shadowedBy.indexOf(t),1)}this.dependencies.deleteAllDownstreamDependencies({component:t});for(let e in this.dependencies.upstreamDependencies[t.componentName]){let n=this.dependencies.upstreamDependencies[t.componentName][e];for(let e of n)if(e.specifiedComponentName&&e.specifiedComponentName in r){let t=this.dependencies.updateTriggers.dependenciesMissingComponentBySpecifiedName[e.specifiedComponentName];t||(t=this.dependencies.updateTriggers.dependenciesMissingComponentBySpecifiedName[e.specifiedComponentName]=[]),t.includes(e)||t.push(e)}}await this.dependencies.deleteAllUpstreamDependencies({component:t}),this.updateInfo.deletedStateVariables[t.componentName]||(this.updateInfo.deletedStateVariables[t.componentName]=[]),this.updateInfo.deletedStateVariables[t.componentName].push(...Object.keys(t.state)),this.updateInfo.deletedComponents[t.componentName]=!0,delete this.unmatchedChildren[t.componentName],delete this.stateVariableChangeTriggers[t.componentName]}for(let e in r){let t=this._components[e];this.deregisterComponent(t,!1),this.updateInfo.componentsToUpdateRenderers.delete(e),this.updateInfo.compositesToUpdateReplacements.delete(e),this.updateInfo.inactiveCompositesToUpdateReplacements.delete(e)}return{success:!0,deletedComponents:r,parentsOfDeleted:s}}determineComponentsToDelete({components:e,deleteUpstreamDependencies:t,componentsToDelete:n}){for(let r of e){if("object"!=typeof r)continue;if(r.componentName in n)continue;n[r.componentName]=this._components[r.componentName];let e=Object.values(r.allChildren).map((e=>e.component));for(let t in r.attributes){let n=r.attributes[t].component;n&&e.push(n)}void 0!==r.adaptedFrom&&e.push(r.adaptedFrom),!0===t&&(r.shadowedBy&&e.push(...r.shadowedBy),r.adapterUsed&&e.push(r.adapterUsed),r.replacements&&e.push(...r.replacements)),this.determineComponentsToDelete({components:e,deleteUpstreamDependencies:t,componentsToDelete:n})}}async updateCompositeReplacements({component:e,componentChanges:t,sourceOfUpdate:n}){let r={},a={},i=new Set;if(e.shadows){return{success:!0,deletedComponents:r,addedComponents:a,parentsOfDeleted:i}}let s=this.components[e.componentName];e.replacements||(e.replacements=[]),await e.stateValues.readyToExpandWhenResolved;const o=await e.constructor.calculateReplacementChanges({component:s,componentChanges:t,components:this.components,workspace:e.replacementsWorkspace,componentInfoObjects:this.componentInfoObjects,flags:this.flags,resolveItem:this.dependencies.resolveItem.bind(this.dependencies),publicCaseInsensitiveAliasSubstitutions:this.publicCaseInsensitiveAliasSubstitutions.bind(this)});e.constructor.stateVariableToEvaluateAfterReplacements&&await e.stateValues[e.constructor.stateVariableToEvaluateAfterReplacements];for(let s of o)if("add"===s.changeType){void 0!==s.replacementsToWithhold&&await this.adjustReplacementsToWithhold({component:e,change:s,componentChanges:t});let o,l=this._components[e.componentName];this.parameterStack.push(l.sharedParameters,!1);let u={[e.componentName]:calculateAllComponentsShadowing(e)},c=s.numberReplacementsToReplace,p=s.firstReplacementInd;if(c>0&&s.changeTopLevelReplacements&&await this.deleteReplacementsFromShadowsThenComposite({change:s,composite:e,componentChanges:t,sourceOfUpdate:n,parentsOfDeleted:i,deletedComponents:r,addedComponents:a,processNewChildren:!1}),!s.serializedReplacements)throw Error("Invalid replacement change.");{let t,n=s.serializedReplacements;t=e.attributes.newNamespace?.primitive?e.componentName+"/":getNamespaceFromName(e.componentName),o=(await this.createIsolatedComponentsSub({serializedComponents:n,ancestors:e.ancestors,createNameContext:e.componentName+"|replacements",namespaceForUnamed:t,componentsReplacementOf:e})).components}this.parameterStack.pop();let d={[e.componentName]:{newComponents:o,parent:s.parent}};if(l.shadowedBy&&u[l.componentName].length>0){let e=await this.createShadowedReplacements({replacementsToShadow:o,componentToShadow:l,parentToShadow:s.parent,currentShadowedBy:u,assignNamesOffset:s.assignNamesOffset,componentChanges:t,sourceOfUpdate:n,parentsOfDeleted:i,deletedComponents:r,addedComponents:a});Object.assign(d,e)}for(let e in d){let n=this._components[e];if(!n)continue;let r=d[e].newComponents;if(n.isExpanded){for(let e of r)"object"==typeof e&&(a[e.componentName]=e);if(!0===s.changeTopLevelReplacements){let e=this._components[n.parentName];n.replacements.splice(p,0,...r),await this.dependencies.addBlockersFromChangedReplacements(n);let a={changeType:"addedReplacements",composite:n,newReplacements:r,topLevel:!0,firstIndex:p,numberDeleted:c};t.push(a),await this.processNewDefiningChildren({parent:e,expandComposites:!1}),(await this.componentAndRenderedDescendants(e)).forEach((e=>this.updateInfo.componentsToUpdateRenderers.add(e)))}else{let i=this._components[d[e].parent.componentName];this.spliceChildren(i,s.indexOfDefiningChildren,r),await this.processNewDefiningChildren({parent:i});for(let e of r)"object"==typeof e&&(a[e.componentName]=e);(await this.componentAndRenderedDescendants(i)).forEach((e=>this.updateInfo.componentsToUpdateRenderers.add(e)));let o={changeType:"addedReplacements",composite:n,newReplacements:r};t.push(o)}}else{await this.expandCompositeComponent(n);let e={changeType:"addedReplacements",composite:n,newReplacements:n.replacements,topLevel:!0,firstIndex:0,numberDeleted:0};t.push(e)}}}else if("delete"===s.changeType)void 0!==s.replacementsToWithhold&&await this.adjustReplacementsToWithhold({component:e,change:s,componentChanges:t}),await this.deleteReplacementsFromShadowsThenComposite({change:s,composite:e,componentsToDelete:s.components,componentChanges:t,sourceOfUpdate:n,parentsOfDeleted:i,deletedComponents:r,addedComponents:a});else if("updateStateVariables"===s.changeType){let e={},t={};for(let n in s.stateChanges){let r={componentName:s.component.componentName,stateVariable:n,value:s.stateChanges[n],overrideFixed:!0};await this.requestComponentChanges({instruction:r,initialChange:!1,workspace:e,newStateVariableValues:t})}await this.processNewStateVariableValues(t)}else"changeReplacementsToWithhold"===s.changeType&&(void 0!==s.replacementsToWithhold&&await this.adjustReplacementsToWithhold({component:e,change:s,componentChanges:t}),await this.processChildChangesAndRecurseToShadows(e));return{success:!0,deletedComponents:r,addedComponents:a,parentsOfDeleted:i}}async deleteReplacementsFromShadowsThenComposite({change:e,composite:t,componentsToDelete:n,componentChanges:r,sourceOfUpdate:a,parentsOfDeleted:i,deletedComponents:s,addedComponents:o,processNewChildren:l=!0}){let u=[];if(!t.isExpanded)return u;if(t.shadowedBy)for(let c of t.shadowedBy){if(c.shadows.propVariable)continue;let t;if(n){t=[];for(let e of n){let n;if(e.shadowedBy)for(let t of e.shadowedBy)if(!t.shadows.propVariable&&t.shadows.compositeName===c.shadows.compositeName){n=t;break}n?t.push(n):console.error(`could not find shadowing component of ${e.componentName}`)}}let p=await this.deleteReplacementsFromShadowsThenComposite({change:e,composite:c,componentsToDelete:t,componentChanges:r,sourceOfUpdate:a,parentsOfDeleted:i,deletedComponents:s,addedComponents:o,processNewChildren:l});u.push(...p)}if(e.changeTopLevelReplacements){let n=e.firstReplacementInd,o=e.numberReplacementsToDelete;"add"===e.changeType&&(o=e.numberReplacementsToReplace);let u=t.replacements.splice(n,o);await this.dependencies.addBlockersFromChangedReplacements(t);let c=await this.deleteComponents({components:u,componentChanges:r,sourceOfUpdate:a,skipProcessingChildrenOfParents:[t.parentName]});if(l&&await this.processNewDefiningChildren({parent:this._components[t.parentName],expandComposites:!1}),!1===c.success)throw Error("Couldn't delete components on composite update");for(let e of c.parentsOfDeleted){i.add(e.componentName),(await this.componentAndRenderedDescendants(e)).forEach((e=>this.updateInfo.componentsToUpdateRenderers.add(e)))}let p={};for(let e in c.deletedComponents){let t=c.deletedComponents[e].parentName;void 0===p[t]&&(p[t]=[]),p[t].push(e)}let d={changeType:"deletedReplacements",composite:t,topLevel:!0,firstIndex:n,numberDeleted:o,deletedNamesByParent:p,deletedComponents:c.deletedComponents};r.push(d),Object.assign(s,c.deletedComponents);let m=this._components[t.parentName];(await this.componentAndRenderedDescendants(m)).forEach((e=>this.updateInfo.componentsToUpdateRenderers.add(e)))}else{let e=n.length,l=await this.deleteComponents({components:n,deleteUpstreamDependencies:!1,componentChanges:r,sourceOfUpdate:a});if(!1===l.success)throw Error("Couldn't delete components prescribed by composite");for(let e of l.parentsOfDeleted){i.add(e.componentName),(await this.componentAndRenderedDescendants(e)).forEach((e=>this.updateInfo.componentsToUpdateRenderers.add(e)))}let u={};for(let e in l.deletedComponents){let t=l.deletedComponents[e].parentName;void 0===u[t]&&(u[t]=[]),u[t].push(e)}let c={changeType:"deletedReplacements",composite:t,numberDeleted:e,deletedNamesByParent:u,deletedComponents:l.deletedComponents};r.push(c),Object.assign(s,l.deletedComponents),Object.assign(o,l.addedComponents)}return u}async processChildChangesAndRecurseToShadows(e){let t=this._components[e.parentName];if(await this.processNewDefiningChildren({parent:t,expandComposites:!1}),(await this.componentAndRenderedDescendants(t)).forEach((e=>this.updateInfo.componentsToUpdateRenderers.add(e))),e.shadowedBy)for(let t of e.shadowedBy)t.shadows.propVariable||await this.processChildChangesAndRecurseToShadows(t)}async createShadowedReplacements({replacementsToShadow:e,componentToShadow:t,parentToShadow:n,currentShadowedBy:r,assignNamesOffset:a,componentChanges:i,sourceOfUpdate:s,parentsOfDeleted:o,deletedComponents:l,addedComponents:u}){let c=calculateAllComponentsShadowing(t);if(!r[t.componentName]||!c.every((e=>r[t.componentName].includes(e))))throw Error(`circular reference involving ${t.componentName}`);this.updateInfo.compositesBeingExpanded.push(t.componentName);let p={};for(let c of t.shadowedBy)if(!c.shadows.propVariable){if(this.updateInfo.compositesBeingExpanded.includes(c.componentName))throw Error(`circular dependence involving ${c.componentName}`);if(c.shadowedBy&&(r[c.componentName]=calculateAllComponentsShadowing(c)),c.isExpanded){let t=[],d=this._components[c.shadows.compositeName],m=await d.stateValues.sourceAttributesToIgnore,h=await d.stateValues.sourceAttributesToIgnoreRecursively;for(let n of e)"object"==typeof n?t.push(await n.serialize({sourceAttributesToIgnore:m,sourceAttributesToIgnoreRecursively:h})):t.push(n);t=postProcessCopy({serializedComponents:t,componentName:c.shadows.compositeName});let f,y=c.attributes.newNamespace?.primitive;if(c.attributes.isResponse){let e=c.constructor.createAttributesObject();for(let n of t){if("object"!=typeof n)continue;n.attributes||(n.attributes={});let t=convertAttributesForComponentType({attributes:{isResponse:c.attributes.isResponse},componentType:n.componentType,componentInfoObjects:this.componentInfoObjects,compositeAttributesObj:e,compositeCreatesNewNamespace:y});Object.assign(n.attributes,t)}}if(c.constructor.assignNamesToReplacements){let e=c.shadows.compositeName,n=this.components[e],r=n.attributes.newNamespace?.primitive,i=n.doenetAttributes.assignNames,s=y||r&&!i,o=c.doenetAttributes.assignNames;o&&await c.stateValues.addLevelToAssignNames&&(o=o.map((e=>[e]))),t=processAssignNames({assignNames:o,indOffset:a,serializedComponents:t,parentName:c.componentName,parentCreatesNewNamespace:y,componentInfoObjects:this.componentInfoObjects,originalNamesAreConsistent:s}).serializedComponents}else{let e=y;t=processAssignNames({indOffset:a,serializedComponents:t,parentName:c.componentName,parentCreatesNewNamespace:y,componentInfoObjects:this.componentInfoObjects,originalNamesAreConsistent:e}).serializedComponents}let g,b=this._components[c.componentName];this.parameterStack.push(b.sharedParameters,!1),g=y?c.componentName+"/":getNamespaceFromName(c.componentName);let v,N=await this.createIsolatedComponentsSub({serializedComponents:t,ancestors:c.ancestors,createNameContext:c.componentName+"|replacements",namespaceForUnamed:g,componentsReplacementOf:c});if(this.parameterStack.pop(),f=N.components,n){if(n.shadowedBy)for(let e of n.shadowedBy)if(!e.shadows.propVariable&&e.shadows.compositeName===c.shadows.compositeName){v=e;break}v||console.error(`could not find shadowing parent of ${n.componentName}`)}if(p[c.componentName]={newComponents:f,parent:v},c.shadowedBy&&r[c.componentName].length>0){let e=await this.createShadowedReplacements({replacementsToShadow:f,componentToShadow:c,parentToShadow:v,currentShadowedBy:r,assignNamesOffset:a,componentChanges:i,sourceOfUpdate:s,parentsOfDeleted:o,deletedComponents:l,addedComponents:u});Object.assign(p,e)}}}let d=this.updateInfo.compositesBeingExpanded.indexOf(t.componentName);if(-1===d)throw Error(`Something is wrong as we lost track that we were expanding ${component.componentName}`);return this.updateInfo.compositesBeingExpanded.splice(d,1),p}async adjustReplacementsToWithhold({component:e,change:t,componentChanges:n}){let r,a=[],i=t.replacementsToWithhold;if(r=void 0!==e.replacementsToWithhold?i-e.replacementsToWithhold:i,r<0){a.push(e.componentName);let t=e.replacements.length-i,s=e.replacements.length-i+r,o=e.replacements.slice(s,t),l={changeType:"addedReplacements",composite:e,topLevel:!0,newReplacements:o,firstIndex:s,numberDeleted:0};n.push(l)}else if(r>0){a.push(e.componentName);let t=e.replacements.length-i,s=t+r,o=e.replacements.slice(t,s),l={};for(let e of o){let t=e.parentName;void 0===l[t]&&(l[t]=[]),l[t].push(e.componentName)}let u={changeType:"deletedReplacements",composite:e,topLevel:!0,firstIndex:t,numberDeleted:r,deletedNamesByParent:l,deletedComponents:o};n.push(u)}if(e.replacementsToWithhold=i,await this.dependencies.addBlockersFromChangedReplacements(e),e.shadowedBy)for(let r of e.shadowedBy){if(r.shadows.propVariable)continue;let e=await this.adjustReplacementsToWithhold({component:r,change:t,componentChanges:n});a.push(...e)}return a}get rendererTypesInDocument(){return this.document.allPotentialRendererTypes}get components(){return this._components}set components(e){return null}async executeProcesses(){if(!this.stopProcessingRequests){for(;this.processQueue.length>0;){let e,t=this.processQueue.splice(0,1)[0];if("update"===t.type)(!t.skippable||this.processQueue.length<2)&&(e=await this.performUpdate(t));else if("action"===t.type)(!t.skippable||this.processQueue.length<2)&&(e=await this.performAction(t));else{if("recordEvent"!==t.type)throw Error(`Unrecognized process type: ${t.type}`);e=await this.performRecordEvent(t)}t.resolve(e)}this.processing=!1}}requestAction({componentName:e,actionName:t,args:n,event:r}){return new Promise(((a,i)=>{let s=n?.skippable;this.processQueue.push({type:"action",componentName:e,actionName:t,args:n,skippable:s,event:r,resolve:a,reject:i}),this.processing||(this.processing=!0,this.executeProcesses())}))}async performAction({componentName:e,actionName:t,args:n,event:r,caseInsensitiveMatch:a}){let i=this.components[e];if(i&&i.actions){let e=i.actions[t];if(!e&&a){let n=t.toLowerCase();for(let r in i.actions)if(r.toLowerCase()===n){e=i.actions[r],t=r;break}}if(e)return r&&this.requestRecordEvent(r),n||(n={}),await e(n)}if(!i&&"recordVisibilityChange"===t&&!1===n?.isVisible)return this.requestRecordEvent({verb:"visibilityChanged",object:{componentName:e},result:{isVisible:!1}}),this.resolveAction({actionId:n.actionId});i&&console.warn(`Cannot run action ${t} on component ${e}`)}resolveAction({actionId:e}){e&&postMessage({messageType:"resolveAction",coreId:this.coreId,args:{actionId:e}})}async triggerChainedActions({componentName:e,triggeringAction:t}){for(let e in this.updateInfo.componentsToUpdateActionChaining)await this.checkForActionChaining({component:this.components[e],stateVariables:this.updateInfo.componentsToUpdateActionChaining[e]});this.updateInfo.componentsToUpdateActionChaining={};let n=e;if(t&&(n+="|"+t),this.actionsChangedToActions[n])for(let e of this.actionsChangedToActions[n])await this.performAction(e)}async requestUpdate({updateInstructions:e,transient:t=!1,event:n,skippable:r=!1,overrideReadOnly:a=!1}){if(!this.flags.readOnly||a)return new Promise(((a,i)=>{this.processQueue.push({type:"update",updateInstructions:e,transient:t,event:n,skippable:r,resolve:a,reject:i}),this.processing||(this.processing=!0,this.executeProcesses())}));{let t={};for(let n of e){let e=t[n.componentName];e||(e=t[n.componentName]={}),n.sourceInformation&&Object.assign(e,n.sourceInformation)}await this.updateRendererInstructions({componentNamesToUpdate:e.map((e=>e.componentName)),sourceOfUpdate:{sourceInformation:t}})}}async performUpdate({updateInstructions:e,actionId:t,event:n,overrideReadOnly:r=!1,doNotSave:a=!1,canSkipUpdatingRenderer:i=!1,suppressToast:s=!1}){if(this.flags.readOnly&&!r){if(!i){let n={};for(let t of e){let e=n[t.componentName];e||(e=n[t.componentName]={}),t.sourceInformation&&Object.assign(e,t.sourceInformation)}await this.updateRendererInstructions({componentNamesToUpdate:e.map((e=>e.componentName)),sourceOfUpdate:{sourceInformation:n},actionId:t})}return}let o={},l=[],u={},c={},p=[];for(let t of e){if(t.componentName){let e=u[t.componentName];e||(e=u[t.componentName]={}),t.sourceInformation&&Object.assign(e,t.sourceInformation)}if("updateValue"===t.updateType)await this.requestComponentChanges({instruction:t,workspace:c,newStateVariableValues:o});else if("addComponents"===t.updateType)await this.addComponents({serializedComponents:t.serializedComponents,parentName:t.parentName,assignNamesOffset:t.assignNamesOffset});else if("deleteComponents"===t.updateType){if(t.componentNames.length>0){let e=[];for(let n of t.componentNames){let t=this._components[n];t?e.push(t):console.warn(`Cannot delete ${n} as it doesn't exist.`)}e.length>0&&await this.deleteComponents({components:e})}}else"executeUpdate"===t.updateType?(await this.executeUpdateStateVariables(o),l.push(o),o={}):"recordItemSubmission"===t.updateType?p.push(t):"setComponentNeedingUpdateValue"===t.updateType?this.rendererState.__componentNeedingUpdateValue=t.componentName:"unsetComponentNeedingUpdateValue"===t.updateType&&(this.rendererState.__componentNeedingUpdateValue=null)}await this.executeUpdateStateVariables(o),l.push(o),i||e.forEach((e=>{e.componentName&&this.updateInfo.componentsToUpdateRenderers.add(e.componentName)}));let d=[...this.updateInfo.componentsToUpdateRenderers];if(this.updateInfo.componentsToUpdateRenderers.clear(),await this.updateRendererInstructions({componentNamesToUpdate:d,sourceOfUpdate:{sourceInformation:u,local:!0},actionId:t}),this.updateInfo.compositesToUpdateReplacements.size>0){await this.replacementChangesFromCompositesToUpdate();let e=[...this.updateInfo.componentsToUpdateRenderers];this.updateInfo.componentsToUpdateRenderers.clear(),await this.updateRendererInstructions({componentNamesToUpdate:e,sourceOfUpdate:{sourceInformation:u,local:!0},actionId:t})}if(await this.processStateVariableTriggers(),Object.keys(this.unmatchedChildren).length>0){let e="";for(let t in this.unmatchedChildren)this._components[t].isShadow||(e+=`Invalid children for ${t}: ${this.unmatchedChildren[t].message} `);e&&console.warn(e)}if(p.length>0){let e=[...new Set(p.map((e=>e.itemNumber)))],t=await this.document.stateValues.creditAchieved,r=await this.document.stateValues.itemCreditAchieved;if(n){if(n.context||(n.context={}),n.context.item=e[0],n.context.itemCreditAchieved=r[e[0]-1],e.length>1){n.context.additionalItemCreditAchieved={};for(let t of e)n.context.additionalItemCreditAchieved[t]=r[t-1]}n.context.pageCreditAchieved=await this.document.stateValues.creditAchieved}this.itemNumber>0&&this.saveSubmissions({pageCreditAchieved:t,suppressToast:s})}if(Object.keys(this.essentialValuesSavedInDefinition).length>0){for(let e in this.essentialValuesSavedInDefinition){let t=this._components[e]?.essentialState;if(t){this.cumulativeStateVariableChanges[e]||(this.cumulativeStateVariableChanges[e]={});for(let n in this.essentialValuesSavedInDefinition[e])if(void 0!==t[n]){let r=this.cumulativeStateVariableChanges[e][n];"object"==typeof r&&null!==r&&r.mergeObject?Object.assign(r,removeFunctionsMathExpressionClass(t[n])):this.cumulativeStateVariableChanges[e][n]=removeFunctionsMathExpressionClass(t[n])}}}this.essentialValuesSavedInDefinition={}}for(let e of l)for(let t in e){this.cumulativeStateVariableChanges[t]||(this.cumulativeStateVariableChanges[t]={});for(let n in e[t]){let r=this.cumulativeStateVariableChanges[t][n];"object"==typeof r&&null!==r&&r.mergeObject?Object.assign(r,removeFunctionsMathExpressionClass(e[t][n])):this.cumulativeStateVariableChanges[t][n]=removeFunctionsMathExpressionClass(e[t][n])}}a||(clearTimeout(this.savePageStateTimeoutID),this.savePageStateTimeoutID=setTimeout((()=>{this.saveState()}),1e3)),await this.document.stateValues.itemCreditAchieved,n&&this.requestRecordEvent(n)}requestRecordEvent(e){return this.resumeVisibilityMeasuring(),"visibilityChanged"===e.verb?this.processVisibilityChangedEvent(e):new Promise(((t,n)=>{this.processQueue.push({type:"recordEvent",event:e,resolve:t,reject:n}),this.processing||(this.processing=!0,this.executeProcesses())}))}async performRecordEvent({event:e}){if(!this.flags.allowSaveEvents)return;e.result||(e.result={}),e.context||(e.context={});const t={doenetId:this.doenetId,activityCid:this.activityCid,pageCid:this.cid,pageNumber:this.pageNumber,attemptNumber:this.attemptNumber,activityVariantIndex:this.activityVariantIndex,pageVariantIndex:this.requestedVariant.index,verb:e.verb,object:JSON.stringify(e.object,serializedComponentsReplacer),result:JSON.stringify(removeFunctionsMathExpressionClass(e.result),serializedComponentsReplacer),context:JSON.stringify(e.context,serializedComponentsReplacer),timestamp:(new Date).toISOString().slice(0,19).replace("T"," "),version:"0.1.1"};try{await axios.post("/api/recordEvent.php",t)}catch(e){console.error(`Error saving event: ${e.message}`)}}processVisibilityChangedEvent(e){let t=e.object.componentName;if(e.result.isVisible)this.visibilityInfo.componentsCurrentlyVisible[t]||(this.visibilityInfo.componentsCurrentlyVisible[t]=new Date),t===this.documentName&&(this.visibilityInfo.documentHasBeenVisible||(this.visibilityInfo.documentHasBeenVisible=!0,this.onDocumentFirstVisible()));else{let e=this.visibilityInfo.componentsCurrentlyVisible[t];if(e){delete this.visibilityInfo.componentsCurrentlyVisible[t];let n=(new Date-Math.max(e,this.visibilityInfo.timeLastSent))/1e3;this.visibilityInfo.infoToSend[t]?this.visibilityInfo.infoToSend[t]+=n:this.visibilityInfo.infoToSend[t]=n}}}sendVisibilityChangedEvents(){let e={...this.visibilityInfo.infoToSend};this.visibilityInfo.infoToSend={};let t=this.visibilityInfo.timeLastSent;this.visibilityInfo.timeLastSent=new Date;let n,r={...this.visibilityInfo.componentsCurrentlyVisible};for(let n in r){let a=(this.visibilityInfo.timeLastSent-Math.max(t,r[n]))/1e3;e[n]?e[n]+=a:e[n]=a}for(let t in e)e[t]=Math.round(e[t]),e[t]||delete e[t];if(Object.keys(e).length>0){let t={object:{componentName:this.documentName,componentType:"document"},verb:"isVisible",result:e};n=new Promise(((e,n)=>{this.processQueue.push({type:"recordEvent",event:t,resolve:e,reject:n}),this.processing||(this.processing=!0,this.executeProcesses())}))}return this.visibilityInfo.suspended||(clearTimeout(this.visibilityInfo.saveTimerId),this.visibilityInfo.saveTimerId=setTimeout(this.sendVisibilityChangedEvents.bind(this),this.visibilityInfo.saveDelay)),n}async suspendVisibilityMeasuring(){clearTimeout(this.visibilityInfo.saveTimerId),clearTimeout(this.visibilityInfo.suspendTimerId),this.visibilityInfo.suspended||(this.visibilityInfo.suspended=!0,await this.sendVisibilityChangedEvents())}resumeVisibilityMeasuring(){this.visibilityInfo.suspended&&(this.visibilityInfo.suspended=!1,this.visibilityInfo.timeLastSent=new Date,clearTimeout(this.visibilityInfo.saveTimerId),this.visibilityInfo.saveTimerId=setTimeout(this.sendVisibilityChangedEvents.bind(this),this.visibilityInfo.saveDelay)),clearTimeout(this.visibilityInfo.suspendTimerId),this.visibilityInfo.suspendTimerId=setTimeout(this.suspendVisibilityMeasuring.bind(this),this.visibilityInfo.suspendDelay)}async executeUpdateStateVariables(e){if(await this.processNewStateVariableValues(e),(await this.replacementChangesFromCompositesToUpdate()).updatedComposites&&(await this.expandAllComposites(this.document),await this.expandAllComposites(this.document,!0),this.updateInfo.stateVariablesToEvaluate)){let e=this.updateInfo.stateVariablesToEvaluate;this.updateInfo.stateVariablesToEvaluate=[];for(let{componentName:t,stateVariable:n}of e){let e=this._components[t];e&&e.state[n]&&await this.getStateVariableValue({component:e,stateVariable:n})}}await this.replacementChangesFromCompositesToUpdate()}async replacementChangesFromCompositesToUpdate(){let e=[...this.updateInfo.compositesToUpdateReplacements];this.updateInfo.compositesToUpdateReplacements.clear();let t=new Set([]),n=0,r=!1,a=[];for(;e.length>0;){for(let n of e){let e=this._components[n];if(e instanceof this.componentInfoObjects.allComponentClasses._composite&&e.isExpanded)if(e.state.readyToExpandWhenResolved.initiallyResolved)if(await e.stateValues.isInactiveCompositeReplacement)this.updateInfo.inactiveCompositesToUpdateReplacements.add(n);else{let t=await this.updateCompositeReplacements({component:e,componentChanges:a});Object.keys(t.addedComponents).length>0&&(r=!0),Object.keys(t.deletedComponents).length>0&&(r=!0)}else t.add(n)}if(e=[...this.updateInfo.compositesToUpdateReplacements],this.updateInfo.compositesToUpdateReplacements.clear(),n++,n>100)throw Error("Seem to have an infinite loop while calculating replacement changes")}return this.updateInfo.compositesToUpdateReplacements=t,{updatedComposites:r}}async processNewStateVariableValues(e){let t=0,n=!1;for(let r in e){let a=this._components[r];if(void 0===a){let t=this.updateInfo.stateVariableUpdatesForMissingComponents[r];void 0===t&&(t=this.updateInfo.stateVariableUpdatesForMissingComponents[r]={}),Object.assign(t,e[r]);continue}let i=e[r];for(let e in i){let s=a.state[e];if(void 0===s){let t=e.match(/^__def_primitive_(\d+)$/);if(t){let n=Number(t[1]);a.definingChildren[n]=i[e],await this.processNewDefiningChildren({parent:a,expandComposites:!1});continue}if(t=e.match(/^__def_primitive_ignore_(\d+)$/),t){let r=Number(t[1]);a.definingChildren[r]=i[e],n=!0;continue}console.warn(`can't update state variable ${e} of component ${r}, as it doesn't exist.`);continue}if(!s.hasEssential){console.warn(`can't update state variable ${e} of component ${r}, as it does not have an essential state variable.`);continue}let o=e;if(a.state[e].essentialVarName&&(o=a.state[e].essentialVarName),e in this.rendererVariablesByComponentType[a.componentType]&&this.updateInfo.componentsToUpdateRenderers.add(a.componentName),s.isArray){let n=a.essentialState[o];Array.isArray(n)||(n=a.essentialState[o]=[]);let l=[];a.state[s.arraySizeStateVariable].initiallyResolved||await a.state[s.arraySizeStateVariable].value;let u=await s.arraySize;for(let r in i[e]){if("mergeObject"===r)continue;let a=e=>e;s.set&&(a=s.set);let o=s.setArrayValue({value:a(i[e][r]),arrayKey:r,arraySize:u,arrayValues:n});s.usedDefaultByArrayKey[r]=!1,t+=o.nFailures;let c=s.varNamesIncludingArrayKeys[r];c&&l.push(...c)}for(let e of l)await this.recordActualChangeInStateVariable({componentName:r,varName:e})}else{if(!s.hasEssential){console.warn(`can't update state variable ${e} of component ${r}, as it does not have an essential state variable.`);continue}s.set?a.essentialState[o]=s.set(i[e]):a.essentialState[o]=i[e],delete s.usedDefault}await this.recordActualChangeInStateVariable({componentName:r,varName:e})}}return{nFailures:t,foundIgnore:n}}async requestComponentChanges({instruction:e,initialChange:t=!0,workspace:n,newStateVariableValues:r}){let a=this._components[e.componentName],i=this.substituteAliases({stateVariables:[e.stateVariable],componentClass:a.constructor})[0];void 0===n[e.componentName]&&(n[e.componentName]={});let s=n[e.componentName],o=a.state[i],l=o.additionalStateVariablesDefined,u=[i];l&&u.push(...l);for(let e of u)if(!a.state[e].isResolved){if(!(await this.dependencies.resolveItem({componentName:a.componentName,type:"stateVariable",stateVariable:e,force:!0})).success)throw Error(`Can't get value of ${i} of ${a.componentName} as ${e} couldn't be resolved.`)}let c=await this.getStateVariableDefinitionArguments({component:a,stateVariable:i,excludeDependencyValues:o.excludeDependencyValuesInInverseDefinition});c.componentInfoObjects=this.componentInfoObjects,c.initialChange=t,c.stateValues=a.stateValues,c.overrideFixed=e.overrideFixed,c.shadowedVariable=e.shadowedVariable,c.sourceInformation=e.sourceInformation;let p=i;if(o.isArrayEntry){let t=o.arrayStateVariable;p=t;let n={};if(1===c.arrayKeys.length){if("value"in e)n[c.arrayKeys[0]]=e.value;else if("valueOfStateVariable"in e){let t=this.substituteAliases({stateVariables:[e.valueOfStateVariable],componentClass:a.constructor})[0],r=a.state[t];if(!r)throw Error(`Invalid instruction to change ${e.stateVariable} of ${e.componentName}, value of state variable ${e.valueOfStateVariable} not found.`);n[c.arrayKeys[0]]=await r.value}}else for(let[t,r]of c.arrayKeys.entries())if(Array.isArray(e.value))n[r]=e.value[t];else if(e.value instanceof me$3.class)try{n[r]=e.value.get_component(t)}catch(e){}c.desiredStateVariableValues={[t]:n}}else if("value"in e)c.desiredStateVariableValues={[i]:e.value};else if("valueOfStateVariable"in e){let t=this.substituteAliases({stateVariables:[e.valueOfStateVariable],componentClass:a.constructor})[0],n=a.state[t];if(!n)throw Error(`Invalid instruction to change ${e.stateVariable} of ${e.componentName}, value of state variable ${e.valueOfStateVariable} not found.`);c.desiredStateVariableValues={[i]:await n.value}}let d=s[p];if(void 0===d&&(d=s[p]={}),o.additionalStateVariablesDefined)for(let e of o.additionalStateVariablesDefined){let t=e;a.state[e].isArray&&(t=o.arrayStateVariable);let n=s[t];n&&(Object.assign(d,n),s[t]=d)}if(c.workspace=d,e.additionalStateVariableValues)for(let t in e.additionalStateVariableValues)o.additionalStateVariablesDefined.includes(t)?c.desiredStateVariableValues[t]=e.additionalStateVariableValues[t]:console.warn(`Can't invert ${t} at the same time as ${i}, as not an additional state variable defined`);if(!o.inverseDefinition)return void console.warn(`Cannot change state variable ${i} of ${a.componentName} as it doesn't have an inverse definition`);if(await a.stateValues.fixed&&!e.overrideFixed&&!o.ignoreFixed)return void console.log(`Changing ${i} of ${a.componentName} did not succeed because fixed is true.`);if(!t&&!1===await a.stateValues.modifyIndirectly)return void console.log(`Changing ${i} of ${a.componentName} did not succeed because modifyIndirectly is false.`);let m=await o.inverseDefinition(c);if(!m.success)return;let h,f=[];for(let e of m.instructions){let t=!1;if(e.setDependency){let n=e.setDependency,r=this.dependencies.downstreamDependencies[a.componentName][i][n];if(["stateVariable","parentStateVariable"].includes(r.dependencyType)&&1===r.downstreamComponentNames.length){let n=r.downstreamComponentNames[0],a=r.mappedDownstreamVariableNamesByComponent[0][0],i=this._components[n].state[a];if((i.isArrayEntry||i.isArray)&&!i.doNotCombineInverseArrayInstructions){let r=i.isArrayEntry?i.arrayStateVariable:a;if(!h||h.componentName===n&&h.stateVariable===r&&h.shadowedVariable===e.shadowedVariable&&h.treatAsInitialChange===e.treatAsInitialChange||(f.push(h),h=void 0),!e.additionalDependencyValues&&!i.basedOnArrayKeyStateVariables)if(t=!0,h||(h={combinedArray:!0,componentName:n,stateVariable:r,shadowedVariable:e.shadowedVariable,treatAsInitialChange:e.treatAsInitialChange,desiredValue:{}}),i.isArrayEntry){let t=await i.arrayKeys;if(1===t.length)h.desiredValue[t[0]]=e.desiredValue;else for(let[n,r]of t.entries())h.desiredValue[r]=e.desiredValue[n]}else if(1!==i.nDimensions&&Array.isArray(e.desiredValue)){let t=(e,n)=>{if(1===n)return Object.assign({},e);{let r={};for(let a in e){let i=t(e[a],n-1);for(let e in i)r[`${a},${e}`]=i[e]}return r}};Object.assign(h.desiredValue,t(e.desiredValue,i.nDimensions))}else Object.assign(h.desiredValue,e.desiredValue)}}}t||(h&&(f.push(h),h=void 0),f.push(e))}h&&(f.push(h),h=void 0);for(let t of f)if(t.setEssentialValue){if(!u.includes(t.setEssentialValue)){let e=!1;if(o.isArrayEntry){let n=[o.arrayStateVariable];if(o.additionalStateVariablesDefined)for(let e of o.additionalStateVariablesDefined){let t=a.state[e];t.isArrayEntry&&n.push(t.arrayStateVariable)}e=n.includes(t.setEssentialValue)}if(!e)throw Error(`Invalid inverse definition of ${i} of ${a.componentName}: specified changing value of ${t.setEssentialValue}, which is not a state variable defined with ${i}.`)}if(!a.state[t.setEssentialValue].hasEssential)throw Error(`Invalid inverse definition of ${i} of ${a.componentName}: can't set essential value of ${t.setEssentialValue} if it is does not have an essential value.`);if(!("value"in t))throw Error(`Invalid inverse definition of ${i} of ${a.componentName}: setEssentialValue must specify a value`);let e=t.value;if(e instanceof me$3.class){e=(await preprocessMathInverseDefinition({desiredValue:e,stateValues:a.stateValues,variableName:t.setEssentialValue,workspace:d})).desiredValue}if(a.state[t.setEssentialValue].doNotShadowEssential||a.state[t.setEssentialValue].shadowVariable)this.calculateEssentialVariableChanges({component:a,varName:t.setEssentialValue,value:e,newStateVariableValues:r,recurseToShadows:!1});else{let n=a;for(;n.shadows&&void 0===n.shadows.propVariable;)n=this._components[n.shadows.componentName];this.calculateEssentialVariableChanges({component:n,varName:t.setEssentialValue,value:e,newStateVariableValues:r})}}else if(t.setDependency){let s=t.setDependency,o=this.dependencies.downstreamDependencies[a.componentName][i][s];if("child"===o.dependencyType){let l=t.childIndex;if(null!==o.downstreamPrimitives[l]){if(typeof t.desiredValue==typeof o.downstreamPrimitives[l]){let e=this._components[o.parentName],n=o.activeChildrenIndices[l];if(e.compositeReplacementActiveRange)for(let r of e.compositeReplacementActiveRange)if(r.firstInd<=n&&r.lastInd>=n)throw console.log(`parent: ${e.componentName}, activeChildInd: ${n}`),console.log(e.compositeReplacementActiveRange),console.log(t),Error("Need to implement changing primitive replacements from composite");let a=n;if(e.compositeReplacementActiveRange)for(let t of e.compositeReplacementActiveRange)t.lastInd!e)).length-1,c=o.downstreamComponentNames[u];if(!c)throw Error(`Invalid inverse definition of ${i} of ${a.componentName}: ${s} child of index ${t.childIndex} does not exist.`);let p=o.mappedDownstreamVariableNamesByComponent[t.childIndex][t.variableIndex];if(!p)throw Error(`Invalid inverse definition of ${i} of ${a.componentName}: ${s} variable of index ${t.variableIndex} does not exist.`);let d={componentName:c,stateVariable:p,value:t.desiredValue,overrideFixed:e.overrideFixed,arrayKey:t.arrayKey};await this.requestComponentChanges({instruction:d,initialChange:!0===t.treatAsInitialChange,workspace:n,newStateVariableValues:r})}}else if(["attributeComponent","shadowSource","adapterSource","targetComponent"].includes(o.dependencyType)){let l=o.downstreamComponentNames[0],u=o.mappedDownstreamVariableNamesByComponent[0][t.variableIndex];if(!u)throw Error(`Invalid inverse definition of ${i} of ${a.componentName}: ${s} variable of index ${t.variableIndex} does not exist.`);let c={componentName:l,stateVariable:u,value:t.desiredValue,overrideFixed:e.overrideFixed,arrayKey:t.arrayKey};await this.requestComponentChanges({instruction:c,initialChange:!0===t.treatAsInitialChange,workspace:n,newStateVariableValues:r})}else{if(!["stateVariable","parentStateVariable","adapterSourceStateVariable","sourceCompositeStateVariable"].includes(o.dependencyType)||1!==o.downstreamComponentNames.length)throw Error(`unimplemented dependency type ${o.dependencyType} in requestComponentChanges`);{let l=o.downstreamComponentNames[0],u=o.mappedDownstreamVariableNamesByComponent[0][0],c={componentName:l,stateVariable:u,value:t.desiredValue,overrideFixed:e.overrideFixed,shadowedVariable:t.shadowedVariable};if(t.additionalDependencyValues){let e=this.components[l].state[u];for(let n in t.additionalDependencyValues){let r=this.dependencies.downstreamDependencies[a.componentName][i][n];if(!["stateVariable","parentStateVariable"].includes(r.dependencyType)||1!==r.downstreamComponentNames.length){console.warn(`Can't simultaneously set additional dependency value ${n} if it isn't a state variable`);continue}let o=r.mappedDownstreamVariableNamesByComponent[0][0];r.downstreamComponentNames[0]===l&&e.additionalStateVariablesDefined.includes(o)?(c.additionalStateVariableValues||(c.additionalStateVariableValues={}),c.additionalStateVariableValues[o]=t.additionalDependencyValues[n]):console.warn(`Can't simultaneously set additional dependency value ${n} if it doesn't correspond to additional state variable defined of ${s}'s state variable`)}}await this.requestComponentChanges({instruction:c,initialChange:!0===t.treatAsInitialChange,workspace:n,newStateVariableValues:r})}}}else{if(!t.combinedArray)throw console.log(t),Error(`Unrecognized instruction in inverse definition of ${i} of ${a.componentName}`);{let a={componentName:t.componentName,stateVariable:t.stateVariable,value:t.desiredValue,overrideFixed:e.overrideFixed,shadowedVariable:t.shadowedVariable};await this.requestComponentChanges({instruction:a,initialChange:!0===t.treatAsInitialChange,workspace:n,newStateVariableValues:r})}}}calculateEssentialVariableChanges({component:e,varName:t,value:n,newStateVariableValues:r,recurseToShadows:a=!0}){if(r[e.componentName]||(r[e.componentName]={}),e.state[t].isArray?(r[e.componentName][t]||(r[e.componentName][t]={mergeObject:!0}),Object.assign(r[e.componentName][t],n)):r[e.componentName][t]=n,a&&e.shadowedBy)for(let a of e.shadowedBy)void 0===a.shadows.propVariable&&this.calculateEssentialVariableChanges({component:a,varName:t,value:n,newStateVariableValues:r})}calculatePrimitiveChildChanges({parent:e,definingInd:t,newValue:n,newStateVariableValues:r,markToIgnoreForParent:a}){if(r[e.componentName]||(r[e.componentName]={}),e.componentName===a?r[e.componentName][`__def_primitive_ignore_${t}`]=n:r[e.componentName][`__def_primitive_${t}`]=n,e.shadowedBy)for(let i of e.shadowedBy)void 0===i.shadows.propVariable&&this.calculatePrimitiveChildChanges({parent:i,definingInd:t,newValue:n,newStateVariableValues:r,markToIgnoreForParent:a})}async saveState(e=!1){if(this.savePageStateTimeoutID=null,!this.flags.allowSaveState&&!this.flags.allowLocalState)return;let t=nanoid();this.flags.allowLocalState&&await set(`${this.doenetId}|${this.pageNumber}|${this.attemptNumber}|${this.cid}`,{coreState:this.cumulativeStateVariableChanges,rendererState:this.rendererState,coreInfo:this.coreInfo,saveId:t}),postMessage({messageType:"savedState",coreId:this.coreId}),this.flags.allowSaveState&&(this.pageStateToBeSavedToDatabase={cid:this.cid,coreInfo:this.coreInfoString,coreState:JSON.stringify(this.cumulativeStateVariableChanges,serializedComponentsReplacer),rendererState:JSON.stringify(this.rendererState,serializedComponentsReplacer),pageNumber:this.pageNumber,attemptNumber:this.attemptNumber,doenetId:this.doenetId,saveId:t,serverSaveId:this.serverSaveId,updateDataOnContentChange:this.updateDataOnContentChange},this.changesToBeSaved=!0,await this.saveChangesToDatabase(e))}async saveChangesToDatabase(e){if(!this.changesToBeSaved)return;if(null!==this.saveStateToDBTimerId){if(!e)return;clearTimeout(this.saveStateToDBTimerId)}let t;this.changesToBeSaved=!1,this.saveStateToDBTimerId=setTimeout((()=>{this.saveStateToDBTimerId=null,this.saveChangesToDatabase()}),6e4);try{t=await axios.post("/api/savePageState.php",this.pageStateToBeSavedToDatabase)}catch(e){return void postMessage({messageType:"sendToast",coreId:this.coreId,args:{message:"Error synchronizing data. Changes not saved to the server.",toastType:toastType.ERROR}})}if(console.log("result from saving to database:",t.data),null===t.status)return void postMessage({messageType:"sendToast",coreId:this.coreId,args:{message:"Error synchronizing data. Changes not saved to the server. Are you connected to the internet?",toastType:toastType.ERROR}});let n=t.data;n.success?(this.serverSaveId=n.saveId,this.flags.allowLocalState&&await set(`${this.doenetId}|${this.pageNumber}|${this.attemptNumber}|${this.cid}|ServerSaveId`,n.saveId),n.stateOverwritten&&(this.attemptNumber!==Number(n.attemptNumber)||this.cid===n.cid?(this.flags.allowLocalState&&await set(`${this.doenetId}|${this.pageNumber}|${n.attemptNumber}|${n.cid}`,{coreState:JSON.parse(n.coreState,serializedComponentsReviver),rendererState:JSON.parse(n.rendererState,serializedComponentsReviver),coreInfo:JSON.parse(n.coreInfo,serializedComponentsReviver),saveId:n.saveId}),postMessage({messageType:"resetPage",coreId:this.coreId,args:{changedOnDevice:n.device,newCid:n.cid,newAttemptNumber:Number(n.attemptNumber)}})):postMessage({messageType:"inErrorState",coreId:this.coreId,args:{errMsg:"Content changed unexpectedly!"}}))):postMessage({messageType:"sendToast",coreId:this.coreId,args:{message:n.message,toastType:toastType.ERROR}})}saveSubmissions({pageCreditAchieved:e,suppressToast:t=!1}){if(!this.flags.allowSaveSubmissions)return;const n={doenetId:this.doenetId,attemptNumber:this.attemptNumber,credit:e,itemNumber:this.itemNumber};console.log("payload for save credit for item",n),axios.post("/api/saveCreditForItem.php",n).then((e=>{if(null===e.status)postMessage({messageType:"sendToast",coreId:this.coreId,args:{message:"Credit not saved due to error. Are you connected to the internet?",toastType:toastType.ERROR}});else if(e.data.success){let n=e.data;postMessage({messageType:"updateCreditAchieved",coreId:this.coreId,args:{creditByItem:n.creditByItem.map(Number),creditForAssignment:Number(n.creditForAssignment),creditForAttempt:Number(n.creditForAttempt),showCorrectness:"1"===n.showCorrectness,totalPointsOrPercent:Number(n.totalPointsOrPercent)}}),n.viewedSolution&&(t||postMessage({messageType:"sendToast",coreId:this.coreId,args:{message:"No credit awarded since solution was viewed.",toastType:toastType.INFO}})),n.timeExpired&&(t||postMessage({messageType:"sendToast",coreId:this.coreId,args:{message:"No credit awarded since the time allowed has expired.",toastType:toastType.INFO}})),n.pastDueDate&&(t||postMessage({messageType:"sendToast",coreId:this.coreId,args:{message:"No credit awarded since the due date has passed.",toastType:toastType.INFO}})),n.exceededAttemptsAllowed&&(t||postMessage({messageType:"sendToast",coreId:this.coreId,args:{message:"No credit awarded since no more attempts are allowed.",toastType:toastType.INFO}})),n.databaseError&&postMessage({messageType:"sendToast",coreId:this.coreId,args:{message:"Credit not saved due to database error.",toastType:toastType.ERROR}})}else postMessage({messageType:"sendToast",coreId:this.coreId,args:{message:`Credit not saved due to error: ${e.data.message}`,toastType:toastType.ERROR}})})).catch((e=>{postMessage({messageType:"sendToast",coreId:this.coreId,args:{message:`Credit not saved due to error: ${e.message}`,toastType:toastType.ERROR}})}))}async recordSolutionView(){if(!this.flags.allowSaveSubmissions)return{allowView:!0,message:"",scoredComponent:this.documentName};try{const e=await axios.post("/api/reportSolutionViewed.php",{doenetId:this.doenetId,itemNumber:this.itemNumber,pageNumber:this.pageNumber,attemptNumber:this.attemptNumber});if(null===e.status){let e="Cannot show solution due to error. Are you connected to the internet?";return postMessage({messageType:"sendToast",coreId:this.coreId,args:{message:e,toastType:toastType.ERROR}}),{allowView:!1,message:e,scoredComponent:this.documentName}}{let t=e.data;if(t.success)return{allowView:!0,message:"",scoredComponent:this.documentName};return{allowView:!1,message:`Cannot show solution due to error: ${t.message}`,scoredComponent:this.documentName}}}catch(e){let t="Cannot show solution due to error.";return postMessage({messageType:"sendToast",coreId:this.coreId,args:{message:t,toastType:toastType.ERROR}}),{allowView:!1,message:t,scoredComponent:this.documentName}}}get scoredItemWeights(){return(async()=>(await this.document.stateValues.scoredDescendants).map((e=>e.stateValues.weight)))()}requestAnimationFrame(e){postMessage({messageType:"requestAnimationFrame",coreId:this.coreId,args:e})}cancelAnimationFrame(e){postMessage({messageType:"cancelAnimationFrame",coreId:this.coreId,args:e})}handleVisibilityChange({visible:e}){e?this.resumeVisibilityMeasuring():this.suspendVisibilityMeasuring()}handleNavigatingToComponent(e){let t=this._components[e];t?.actions?.revealSection&&this.requestAction({componentName:t.componentName,actionName:"revealSection"})}async terminate(){if(await this.suspendVisibilityMeasuring(),this.submitAnswersTimeout&&(clearTimeout(this.submitAnswersTimeout),await this.autoSubmitAnswers()),this.stopProcessingRequests=!0,this.processing)for(let e=0;e<10&&(await new Promise(((e,t)=>{setTimeout(e,100)})),this.processing);e++);this.savePageStateTimeoutID?(clearTimeout(this.savePageStateTimeoutID),await this.saveState(!0)):await this.saveChangesToDatabase(!0)}recordAnswerToAutoSubmit(e){this.answersToSubmit||(this.answersToSubmit=[]),this.answersToSubmit.includes(e)||this.answersToSubmit.push(e),clearTimeout(this.submitAnswersTimeout),this.submitAnswersTimeout=setTimeout((()=>{this.autoSubmitAnswers()}),1e3)}async autoSubmitAnswers(){let e=this.answersToSubmit;this.answersToSubmit=[];for(let t of e){this._components[t].actions.submitAnswer&&await this.requestAction({componentName:t,actionName:"submitAnswer"})}}requestComponentDoenetML(e,t){let n=this.components[e];if(!n)return null;let r,a,i=n.doenetMLrange;if(!i)return null;if(t){if(void 0!==i.selfCloseBegin)return"";r=i.openEnd+1,a=i.closeBegin}else r=void 0!==i.openBegin?i.openBegin:i.selfCloseBegin,a=void 0!==i.closeEnd?i.closeEnd:i.selfCloseEnd+1;let s=this.doenetML.slice(r-1,a);t&&("\n"===s[0]&&(s=s.slice(1)),s=s.replace(/\n[ \t]*$(?!\n)/,""));let o=s.split("\n"),l=o.slice(1).reduce(((e,t)=>Math.min(e,t.trim().length>1?t.search(/\S|$/):1/0)),1/0);return Number.isFinite(l)&&l>0&&(o=o.map((e=>{let t=Math.min(l,e.search(/\S|$/));return e.slice(t)})),s=o.join("\n")),s+="\n",s}copyToClipboard(e,t){"string"!=typeof e?this.resolveAction({actionId:t}):postMessage({messageType:"copyToClipboard",coreId:this.coreId,args:{text:e,actionId:t}})}navigateToTarget(e){postMessage({messageType:"navigateToTarget",coreId:this.coreId,args:e})}}function validateAttributeValue({value:e,attributeSpecification:t,attribute:n}){return t.valueTransformations&&e in t.valueTransformations&&(e=t.valueTransformations[e]),void 0===t.transformNonFiniteTo||Number.isFinite(e)||(e=t.transformNonFiniteTo),t.toLowerCase&&(e=e.toLowerCase()),t.trim&&(e=e.trim()),t.validValues?t.validValues.includes(e)||(console.warn(`Invalid value ${e} for attribute ${n}, using value ${t.defaultValue}`),e=t.defaultValue):t.clamp&&(et.clamp[1]?e=t.clamp[1]:Number.isFinite(e)||(e=t.defaultValue)),e}function calculateAllComponentsShadowing(e){let t=[];if(e.shadowedBy)for(let n of e.shadowedBy)if(!n.shadows.propVariable){t.push(n.componentName);let e=calculateAllComponentsShadowing(n);t.push(...e)}if(e.replacementOf){let n=calculateAllComponentsShadowing(e.replacementOf);t.push(...n)}return t}return Core}(); + */class HyperFormulaNS extends HyperFormula{}HyperFormulaNS.HyperFormula=HyperFormula,HyperFormulaNS.ErrorType=ErrorType,HyperFormulaNS.CellType=CellType,HyperFormulaNS.CellValueType=CellValueType,HyperFormulaNS.CellValueDetailedType=CellValueDetailedType,HyperFormulaNS.DetailedCellError=DetailedCellError,HyperFormulaNS.ExportedCellChange=ExportedCellChange,HyperFormulaNS.ExportedNamedExpressionChange=ExportedNamedExpressionChange,HyperFormulaNS.ConfigValueTooBigError=ConfigValueTooBigError,HyperFormulaNS.ConfigValueTooSmallError=ConfigValueTooSmallError,HyperFormulaNS.EvaluationSuspendedError=EvaluationSuspendedError,HyperFormulaNS.ExpectedOneOfValuesError=ExpectedOneOfValuesError,HyperFormulaNS.ExpectedValueOfTypeError=ExpectedValueOfTypeError,HyperFormulaNS.FunctionPlugin=FunctionPlugin,HyperFormulaNS.FunctionPluginValidationError=FunctionPluginValidationError,HyperFormulaNS.InvalidAddressError=InvalidAddressError,HyperFormulaNS.InvalidArgumentsError=InvalidArgumentsError,HyperFormulaNS.LanguageNotRegisteredError=LanguageNotRegisteredError,HyperFormulaNS.LanguageAlreadyRegisteredError=LanguageAlreadyRegisteredError,HyperFormulaNS.MissingTranslationError=MissingTranslationError,HyperFormulaNS.NamedExpressionDoesNotExistError=NamedExpressionDoesNotExistError,HyperFormulaNS.NamedExpressionNameIsAlreadyTakenError=NamedExpressionNameIsAlreadyTakenError,HyperFormulaNS.NamedExpressionNameIsInvalidError=NamedExpressionNameIsInvalidError,HyperFormulaNS.NoOperationToRedoError=NoOperationToRedoError,HyperFormulaNS.NoOperationToUndoError=NoOperationToUndoError,HyperFormulaNS.NoRelativeAddressesAllowedError=NoRelativeAddressesAllowedError,HyperFormulaNS.NoSheetWithIdError=NoSheetWithIdError,HyperFormulaNS.NoSheetWithNameError=NoSheetWithNameError,HyperFormulaNS.NotAFormulaError=NotAFormulaError,HyperFormulaNS.NothingToPasteError=NothingToPasteError,HyperFormulaNS.ProtectedFunctionTranslationError=ProtectedFunctionTranslationError,HyperFormulaNS.SheetNameAlreadyTakenError=SheetNameAlreadyTakenError,HyperFormulaNS.SheetSizeLimitExceededError=SheetSizeLimitExceededError,HyperFormulaNS.SourceLocationHasArrayError=SourceLocationHasArrayError,HyperFormulaNS.TargetLocationHasArrayError=TargetLocationHasArrayError,HyperFormulaNS.UnableToParseError=UnableToParseError;const defaultLanguage=Config.defaultConfig.language;HyperFormula.registerLanguage(defaultLanguage,dictionary),HyperFormula.languages[dictionary.langCode]=dictionary;for(const e of Object.getOwnPropertyNames(plugins))e.startsWith("_")||HyperFormula.registerFunctionPlugin(plugins[e]);class Spreadsheet extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{onChange:this.onChange.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="spreadsheet";static createAttributesObject(){let e=super.createAttributesObject();return e.width={createComponentOfType:"_componentSize",createStateVariable:"width",defaultValue:{size:100,isAbsolute:!1},public:!0,forRenderer:!0},e.minNumRows={createComponentOfType:"number",createStateVariable:"minNumRows",defaultValue:4,public:!0,forRenderer:!0},e.minNumColumns={createComponentOfType:"number",createStateVariable:"minNumColumns",defaultValue:4,public:!0,forRenderer:!0},e.height={createComponentOfType:"_componentSize"},e.columnHeaders={createComponentOfType:"boolean",createStateVariable:"columnHeaders",defaultValue:!0,public:!0,forRenderer:!0},e.rowHeaders={createComponentOfType:"boolean",createStateVariable:"rowHeaders",defaultValue:!0,public:!0,forRenderer:!0},e.fixedRowsTop={createComponentOfType:"integer",createStateVariable:"fixedRowsTop",defaultValue:0,clamp:[0,1/0],public:!0,forRenderer:!0},e.fixedColumnsLeft={createComponentOfType:"integer",createStateVariable:"fixedColumnsLeft",defaultValue:0,clamp:[0,1/0],public:!0,forRenderer:!0},e.hiddenColumns={createComponentOfType:"numberList",createStateVariable:"hiddenColumns",defaultValue:[],public:!0,forRenderer:!0},e.hiddenRows={createComponentOfType:"numberList",createStateVariable:"hiddenRows",defaultValue:[],public:!0,forRenderer:!0},e}static returnChildGroups(){return[{group:"cells",componentTypes:["cell"]},{group:"rows",componentTypes:["row"]},{group:"columns",componentTypes:["column"]},{group:"cellBlocks",componentTypes:["cellBlock"]},{group:"dataFrames",componentTypes:["dataFrame"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.cellNameToRowCol={additionalStateVariablesDefined:["cellNamesByRowCol"],returnDependencies:()=>({cellRelatedChildren:{dependencyType:"child",childGroups:["cells","rows","columns","cellBlocks"],variableNames:["rowNum","colNum","prescribedCellsWithColNum","prescribedCellsWithRowNum","prescribedCellsRowsColumnsBlocks"],variablesOptional:!0}}),definition({dependencyValues:e,componentInfoObjects:t}){let n=determineCellMapping({cellRelatedChildren:e.cellRelatedChildren,componentInfoObjects:t});return{setValue:{cellNameToRowCol:n.cellNameToRowCol,cellNamesByRowCol:n.cellNamesByRowCol}}}},e.numRows={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({minNumRows:{dependencyType:"stateVariable",variableName:"minNumRows"},cellNamesByRowCol:{dependencyType:"stateVariable",variableName:"cellNamesByRowCol"},dataFrameChild:{dependencyType:"child",childGroups:["dataFrames"],variableNames:["numRows"]}}),definition({dependencyValues:e}){let t=e.minNumRows;return Number.isFinite(t)||(t=4),t=Math.max(t,e.cellNamesByRowCol.length),e.dataFrameChild.length>0&&(t=Math.max(t,e.dataFrameChild[0].stateValues.numRows)),{setValue:{numRows:t}}}},e.numColumns={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({minNumColumns:{dependencyType:"stateVariable",variableName:"minNumColumns"},cellNamesByRowCol:{dependencyType:"stateVariable",variableName:"cellNamesByRowCol"},dataFrameChild:{dependencyType:"child",childGroups:["dataFrames"],variableNames:["numColumns"]}}),definition({dependencyValues:e}){let t=e.minNumColumns;Number.isFinite(t)||(t=4);for(let n of e.cellNamesByRowCol)n&&(t=Math.max(t,n.length));return e.dataFrameChild.length>0&&(t=Math.max(t,e.dataFrameChild[0].stateValues.numColumns)),{setValue:{numColumns:t}}}},e.height={public:!0,shadowingInstructions:{createComponentOfType:"_componentSize"},forRenderer:!0,returnDependencies:()=>({heightAttr:{dependencyType:"attributeComponent",attributeName:"height",variableNames:["componentSize"]},numRows:{dependencyType:"stateVariable",variableName:"numRows"}}),definition({dependencyValues:e}){if(null===e.heightAttr){let t;return t=Number.isFinite(e.numRows)&&e.numRows>=0?40+23*e.numRows:132,{setValue:{height:{size:t,isAbsolute:!0}}}}return{setValue:{height:e.heightAttr.stateValues.componentSize}}}},e.cells={public:!0,shadowingInstructions:{createComponentOfType:"cell",returnWrappingComponents:e=>"cell"===e?[]:"row"===e?[["row"]]:"column"===e?[["column"]]:[["row"],["cellBlock"]]},forRenderer:!0,isArray:!0,entryPrefixes:["cell","row","column","range","rows","columns"],nDimensions:2,defaultValueByArrayKey:()=>"",hasEssential:!0,shadowVariable:!0,stateVariablesDeterminingDependencies:["cellNamesByRowCol"],returnArraySizeDependencies:()=>({numRows:{dependencyType:"stateVariable",variableName:"numRows"},numColumns:{dependencyType:"stateVariable",variableName:"numColumns"}}),returnArraySize:({dependencyValues:e})=>[e.numRows,e.numColumns],returnEntryDimensions:e=>["range","rows","columns"].includes(e)?2:1,getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("cell"===e){let e,r,a=/^([a-zA-Z]+)([1-9]\d*)$/,i=t.match(a);if(i)r=i[1],e=i[2];else{let n=/^\(([a-zA-Z]+|\d+),([a-zA-Z]+|\d+)\)$/;if(i=t.match(n),!i)return[];e=i[1],r=i[2]}let s=normalizeIndex(e),o=normalizeIndex(r);return s>=0&&o>=0&&(!n||s=0))return[];if(!n)return[String(e)+",0"];if(!(e=0))return[];if(!n)return["0,"+String(e)];if(!(e=0&&a>=0&&r>=0&&i>=0))return[];if(!n)return[String(e)+","+String(r)];let l=Math.min(Math.min(e,a),n[0]-1),u=Math.min(Math.max(e,a),n[0]-1),c=Math.min(Math.min(r,i),n[1]-1),p=Math.min(Math.max(r,i),n[1]-1),d=[];for(let e=l;e<=u;e++){let t=[],n=String(e)+",";for(let e=c;e<=p;e++)t.push(n+e);d.push(t)}return d}{if(!n)return[String(0)+","+String(0)];let e=[];for(let t=0;t"cell("+e.split(",").map((e=>Number(e)+1)).join(",")+")",arrayVarNameFromPropIndex(e,t){if("cells"===t||"rows"===t)return 1===e.length?"row"+e[0]:`cell(${e[0]},${e[1]})`;if("columns"===t)return 1===e.length?"column"+e[0]:`cell(${e[1]},${e[0]})`;if("row"===t.slice(0,3)){return`cell(${t.slice(3)},${e[0]})`}if("column"===t.slice(0,6)){let n=t.slice(6);return`cell(${e[0]},${n})`}return null},returnArrayDependenciesByKey({stateValues:e,arrayKeys:t}){let n={},r=e.cellNamesByRowCol;for(let e of t){let[t,a]=e.split(",");r[t]&&r[t][a]&&(n[e]={cellText:{dependencyType:"stateVariable",componentName:r[t][a],variableName:"text",variablesOptional:!0}})}return{dependenciesByKey:n,globalDependencies:{dataFrameChild:{dependencyType:"child",childGroups:["dataFrames"],variableNames:["dataFrame","numRows","numColumns"]}}}},arrayDefinitionByKey({dependencyValuesByKey:e,globalDependencyValues:t,arrayKeys:n}){let r,a,i={},s={},o=null;t.dataFrameChild.length>0&&(o=t.dataFrameChild[0],r=o.stateValues.numRows,a=o.stateValues.numColumns);for(let t of n){let[n,l]=t.split(",");void 0!==e[t].cellText?i[t]=e[t].cellText:n0&&(l.setValue={cells:i}),Object.keys(s).length>0&&(l.useEssentialOrDefaultValue={cells:s}),l},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t}){let n=[];for(let r in e.cells)if(void 0!==t[r].cellText)n.push({setDependency:t[r].cellText,desiredValue:e.cells[r]});else{let t=e.cells[r];n.push({setEssentialValue:"cells",value:{[r]:null===t?"":String(t)}})}return{success:!0,instructions:n}}},e.evaluatedCells={isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"cell",returnWrappingComponents:e=>"evaluatedCell"===e?[]:"evaluatedRow"===e?[["row"]]:"evaluatedColumn"===e?[["column"]]:[["row"],["cellBlock"]]},entryPrefixes:["evaluatedCell","evaluatedRow","evaluatedColumn","evaluatedRange","evaluatedRows","evaluatedColumns"],nDimensions:2,stateVariablesDeterminingDependencies:["cellNamesByRowCol"],returnArraySizeDependencies:()=>({numRows:{dependencyType:"stateVariable",variableName:"numRows"},numColumns:{dependencyType:"stateVariable",variableName:"numColumns"}}),returnArraySize:({dependencyValues:e})=>[e.numRows,e.numColumns],returnEntryDimensions:e=>["evaluatedRange","evaluatedRows","evaluatedColumns"].includes(e)?2:1,getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("evaluatedCell"===e){let e,r,a=/^([a-zA-Z]+)([1-9]\d*)$/,i=t.match(a);if(i)r=i[1],e=i[2];else{let n=/^\(([a-zA-Z]+|\d+),([a-zA-Z]+|\d+)\)$/;if(i=t.match(n),!i)return[];e=i[1],r=i[2]}let s=normalizeIndex(e),o=normalizeIndex(r);return s>=0&&o>=0&&(!n||s=0))return[];if(!n)return[String(e)+",0"];if(!(e=0))return[];if(!n)return["0,"+String(e)];if(!(e=0&&a>=0&&r>=0&&i>=0))return[];if(!n)return[String(e)+","+String(r)];let l=Math.min(Math.min(e,a),n[0]-1),u=Math.min(Math.max(e,a),n[0]-1),c=Math.min(Math.min(r,i),n[1]-1),p=Math.min(Math.max(r,i),n[1]-1),d=[];for(let e=l;e<=u;e++){let t=[],n=String(e)+",";for(let e=c;e<=p;e++)t.push(n+e);d.push(t)}return d}{if(!n)return[String(0)+","+String(0)];let e=[];for(let t=0;t"evaluatedCell("+e.split(",").map((e=>Number(e)+1)).join(",")+")",arrayVarNameFromPropIndex(e,t){if("evaluatedCells"===t||"evaluatedRows"===t)return 1===e.length?"evaluatedRow"+e[0]:`evaluatedCell(${e[0]},${e[1]})`;if("evaluatedColumns"===t)return 1===e.length?"evaluatedColumn"+e[0]:`evaluatedCell(${e[1]},${e[0]})`;if("evaluatedRow"===t.slice(0,12)){return`evaluatedCell(${t.slice(12)},${e[0]})`}if("evaluatedColumn"===t.slice(0,15)){let n=t.slice(15);return`evaluatedCell(${e[0]},${n})`}return null},returnArrayDependenciesByKey:()=>({globalDependencies:{cells:{dependencyType:"stateVariable",variableName:"cells"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t=HyperFormula.buildFromArray(e.cells,{licenseKey:"gpl-v3"}).getSheetValues(0),n={};for(let e in t){let r=t[e];for(let t in r)n[[e,t]]=r[t]}return{setValue:{evaluatedCells:n}}}},e.pointsInCells={isArray:!0,nDimensions:2,public:!0,shadowingInstructions:{createComponentOfType:"point"},entryPrefixes:["pointsInCell","pointsInRow","pointsInColumn","pointsInRange","pointsInRows","pointsInColumns"],returnArraySizeDependencies:()=>({numRows:{dependencyType:"stateVariable",variableName:"numRows"},numColumns:{dependencyType:"stateVariable",variableName:"numColumns"}}),returnArraySize:({dependencyValues:e})=>[e.numRows,e.numColumns],returnEntryDimensions:e=>["pointsInRange","pointsInRows","pointsInColumns"].includes(e)?2:1,getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("pointsInCell"===e){let e,r,a=/^([a-zA-Z]+)([1-9]\d*)$/,i=t.match(a);if(i)r=i[1],e=i[2];else{let n=/^\(([a-zA-Z]+|\d+),([a-zA-Z]+|\d+)\)$/;if(i=t.match(n),!i)return[];e=i[1],r=i[2]}let s=normalizeIndex(e),o=normalizeIndex(r);return s>=0&&o>=0&&(!n||s=0))return[];if(!n)return[String(e),",0"];if(!(e>=0&&e=0))return[];if(!n)return["0,"+String(e)];if(!(e=0&&a>=0&&r>=0&&i>=0))return[];if(!n)return[String(e)+","+String(r)];let l=Math.min(Math.min(e,a),n[0]-1),u=Math.min(Math.max(e,a),n[0]-1),c=Math.min(Math.min(r,i),n[1]-1),p=Math.min(Math.max(r,i),n[1]-1),d=[];for(let e=l;e<=u;e++){let t=[],n=String(e)+",";for(let e=c;e<=p;e++)t.push(n+e);d.push(t)}return d}{if(!n)return[String(0)+","+String(0)];let e=[];for(let t=0;t"pointsInCell("+e.split(",").map((e=>Number(e)+1)).join(",")+")",arrayVarNameFromPropIndex(e,t){if("pointsInCells"===t||"pointsInRows"===t)return 1===e.length?"pointsInRow"+e[0]:`pointsInCell(${e[0]},${e[1]})`;if("pointsInColumns"===t)return 1===e.length?"pointsInColumn"+e[0]:`pointsInCell(${e[1]},${e[0]})`;if("pointsInRow"===t.slice(0,11)){return`pointsInCell(${t.slice(11)},${e[0]})`}if("pointsInColumn"===t.slice(0,14)){let n=t.slice(14);return`pointsInCell(${e[0]},${n})`}return null},returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=n.split(",").map((e=>Number(e)+1)).join(",");t[n]={cellText:{dependencyType:"stateVariable",variableName:`evaluatedCell(${e})`,variablesOptional:!0}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t,a=e[r].cellText;if(a){try{t=me$3.fromAst(textToAst$1.convert(a))}catch(e){n[r]=null;continue}Array.isArray(t.tree)&&vectorOperators.includes(t.tree[0])?n[r]=t:n[r]=null}else n[r]=null}return{setValue:{pointsInCells:n}}}},e}async onChange({changes:e,source:t,actionId:n}){if(e){let t={};for(let n of e){let[e,r,a,i]=n;t[[e,r]]=null===i?"":i}return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"cells",value:t}],actionId:n,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:t}})}this.coreFunctions.resolveAction({actionId:n})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}function determineCellMapping({cellRelatedChildren:e,rowOffset:t=0,colOffset:n=0,cellNameToRowCol:r={},cellNamesByRowCol:a=[],componentInfoObjects:i}){var s=t,o=n,l=n,u=t,c=n,p=t,d=n;for(let m of e)if(i.isInheritedComponentType({inheritedComponentType:m.componentType,baseComponentType:"cell"})){let e=m,i=normalizeIndex(e.stateValues.rowNum),u=normalizeIndex(e.stateValues.colNum);void 0===i?(i=s,void 0===u?u=l:u+=n):(i+=t,void 0===u?u=o:u+=n),addCellToMapping({cell:e,rowIndex:i,colIndex:u,cellNameToRowCol:r,cellNamesByRowCol:a}),p=Math.max(i,p),d=Math.max(u,d),s=i,o=u,l=u+1}else if(i.isInheritedComponentType({inheritedComponentType:m.componentType,baseComponentType:"row"})){let e=m,i=normalizeIndex(e.stateValues.rowNum);void 0===i?i=u:i+=t;let c=e.stateValues.prescribedCellsWithColNum,h=n;for(let e of c){let t=normalizeIndex(e.stateValues.colNum);void 0===t?t=h:t+=n,addCellToMapping({cell:e,rowIndex:i,colIndex:t,cellNameToRowCol:r,cellNamesByRowCol:a}),h=t+1,p=Math.max(i,p),d=Math.max(t,d)}u=i+1,s=i+1,l=o=n}else if(i.isInheritedComponentType({inheritedComponentType:m.componentType,baseComponentType:"column"})){let e=m,i=normalizeIndex(e.stateValues.colNum);void 0===i?i=c:i+=n;let u=e.stateValues.prescribedCellsWithRowNum,h=t;for(let e of u){let n=normalizeIndex(e.stateValues.rowNum);void 0===n?n=h:n+=t,addCellToMapping({cell:e,rowIndex:n,colIndex:i,cellNameToRowCol:r,cellNamesByRowCol:a}),h=n+1,p=Math.max(n,p),d=Math.max(i,d)}c=i+1,s=t,l=o=i+1}else if(i.isInheritedComponentType({inheritedComponentType:m.componentType,baseComponentType:"cellBlock"})){let e=m,u=normalizeIndex(e.stateValues.rowNum),c=normalizeIndex(e.stateValues.colNum);void 0===u?(u=s,void 0===c?c=l:c+=n):(u+=t,void 0===c?c=o:c+=n);let h=determineCellMapping({cellRelatedChildren:e.stateValues.prescribedCellsRowsColumnsBlocks,rowOffset:u,colOffset:c,cellNameToRowCol:r,cellNamesByRowCol:a,componentInfoObjects:i});p=Math.max(h.maxRowIndex,p),d=Math.max(h.maxColIndex,d),s=u,o=c,l=h.maxColIndex+1}return{maxRowIndex:p,maxColIndex:d,cellNameToRowCol:r,cellNamesByRowCol:a}}function addCellToMapping({cell:e,rowIndex:t,colIndex:n,cellNameToRowCol:r,cellNamesByRowCol:a}){if(r[e.componentName]=[t,n],void 0===a[t]&&(a[t]=[]),void 0!==a[t][n]){console.warn(`Cell is overwriting previous cell at rowNum=${t+1}, colNum=${n+1}`),r[a[t][n]]=null}a[t][n]=e.componentName}class DiscreteSimulationResultList extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{onChange:this.onChange.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="DiscreteSimulationResultList";static rendererType="spreadsheet";static createAttributesObject(){let e=super.createAttributesObject();return e.width={createComponentOfType:"_componentSize",createStateVariable:"width",defaultValue:{size:100,isAbsolute:!1},public:!0,forRenderer:!0},e.minNumRows={createComponentOfType:"number",createStateVariable:"minNumRows",defaultValue:1,public:!0,forRenderer:!0},e.minNumColumns={createComponentOfType:"number",createStateVariable:"minNumColumns",defaultValue:1,public:!0,forRenderer:!0},e.height={createComponentOfType:"_componentSize"},e.columnHeaders={createComponentOfType:"boolean",createStateVariable:"columnHeaders",defaultValue:!0,public:!0,forRenderer:!0},e.rowHeaders={createComponentOfType:"boolean",createStateVariable:"rowHeaders",defaultValue:!0,public:!0,forRenderer:!0},e.fixedRowsTop={createComponentOfType:"integer",createStateVariable:"fixedRowsTop",defaultValue:0,clamp:[0,1/0],public:!0,forRenderer:!0},e.fixedColumnsLeft={createComponentOfType:"integer",createStateVariable:"fixedColumnsLeft",defaultValue:0,clamp:[0,1/0],public:!0,forRenderer:!0},e.hiddenColumns={createComponentOfType:"numberList",createStateVariable:"hiddenColumns",defaultValue:[],public:!0,forRenderer:!0},e.hiddenRows={createComponentOfType:"numberList",createStateVariable:"hiddenRows",defaultValue:[],public:!0,forRenderer:!0},e.allIterates={createComponentOfType:"mathList",createStateVariable:"allIterates",defaultValue:[]},e.headerRow={createComponentOfType:"textList",createStateVariable:"headerRow",defaultValue:null},e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.displayDigitsAttr){let n=null===e.displayDigitsAttr||t.displayDigitsAttr,r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!n&&!r){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({allIterates:{dependencyType:"stateVariable",variableName:"allIterates"},headerRow:{dependencyType:"stateVariable",variableName:"headerRow"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"}}),definition({dependencyValues:e,usedDefault:t}){let n=[],r=1,a=!1;if(e.allIterates.length>0&&Array.isArray(e.allIterates[0].tree)&&vectorOperators.includes(e.allIterates[0].tree[0])&&(r=e.allIterates[0].tree.length-1,a=!0),e.headerRow){let t=[],a=Math.min(e.headerRow.length,r+1);for(let n=0;n({minNumRows:{dependencyType:"stateVariable",variableName:"minNumRows"},cells:{dependencyType:"stateVariable",variableName:"cells"}}),definition({dependencyValues:e}){let t=e.minNumRows;return Number.isFinite(t)||(t=4),t=Math.max(t,e.cells.length),{setValue:{numRows:t}}}},e.numColumns={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({minNumColumns:{dependencyType:"stateVariable",variableName:"minNumColumns"},cells:{dependencyType:"stateVariable",variableName:"cells"}}),definition({dependencyValues:e}){let t=e.minNumColumns;Number.isFinite(t)||(t=4);for(let n of e.cells)n&&(t=Math.max(t,n.length));return{setValue:{numColumns:t}}}},e.height={public:!0,shadowingInstructions:{createComponentOfType:"_componentSize"},forRenderer:!0,returnDependencies:()=>({heightAttr:{dependencyType:"attributeComponent",attributeName:"height",variableNames:["componentSize"]},numRows:{dependencyType:"stateVariable",variableName:"numRows"}}),definition({dependencyValues:e}){if(null===e.heightAttr){let t;return t=Number.isFinite(e.numRows)&&e.numRows>=0?50+20*e.numRows:130,{setValue:{height:{size:t,isAbsolute:!0}}}}return{setValue:{height:e.heightAttr.stateValues.componentSize}}}},e}async onChange({changes:e,source:t,actionId:n}){if(e){let t={};for(let n of e){let[e,r,a,i]=n;t[[e,r]]=null===i?"":i}return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"cells",value:t}],actionId:n,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:t}})}this.coreFunctions.resolveAction({actionId:n})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class DiscreteSimulationResultPolyline extends GraphicalComponent{constructor(e){super(e),Object.assign(this.actions,{movePolyline:this.movePolyline.bind(this),finalizePolylinePosition:this.finalizePolylinePosition.bind(this)})}static componentType="discreteSimulationResultPolyline";static rendererType="polyline";static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.allIterates={createComponentOfType:"mathList",createStateVariable:"allIteratesSub",defaultValue:[]},e.seriesNumber={createComponentOfType:"number",createStateVariable:"seriesNumber",defaultValue:null},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){let t=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(t&&(t+=" "),t+=e.selectedStyle.lineStyleWord),t&&(t+=" "),t+=e.selectedStyle.lineColorWord,{setValue:{styleDescription:t}}}},e.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({styleDescription:{dependencyType:"stateVariable",variableName:"styleDescription"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescriptionWithNoun:e.styleDescription+" polyline"}}}},e.allIterates={returnDependencies:()=>({allIteratesSub:{dependencyType:"stateVariable",variableName:"allIteratesSub"}}),definition:function({dependencyValues:e}){return{setValue:{allIterates:e.allIteratesSub.filter((e=>Number.isFinite(e.tree)||Array.isArray(e.tree)&&vectorOperators.includes(e.tree[0])&&e.tree.slice(1).every(Number.isFinite)))}}}},e.nVertices={public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies:()=>({allIterates:{dependencyType:"stateVariable",variableName:"allIterates"}}),definition:function({dependencyValues:e}){return{setValue:{nVertices:e.allIterates.length}}}},e.nDimensions={public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies:()=>({}),definition:function({dependencyValues:e}){return{setValue:{nDimensions:2}}}},e.vertices={public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"vertexX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,nDimensions:2,entryPrefixes:["vertexX","vertex"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("vertexX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("vertices"===t)return 1===e.length?"vertex"+e[0]:`vertexX${e[0]}_${e[1]}`;if("vertex"===t.slice(0,6)){let n=Number(t.slice(6));if(Number.isInteger(n)&&n>0)return`vertexX${n}_${e[0]}`}return null},getAllArrayKeys(e,t=!0,n){function r(e){if(1===e.length)return Array.from(Array(e[0]),((e,t)=>String(t)));{let n=e[0],a=r(e.slice(1)),i=[];for(let e=0;ee+","+t))):i.push(a.map((t=>e+","+t)));return i}}if(n){if(0!==n.length&&e){let t=[...e];return t[0]=n[0],r(t)}return[]}return e&&0!==e.length?r(e):[]},returnArraySizeDependencies:()=>({nVertices:{dependencyType:"stateVariable",variableName:"nVertices"}}),returnArraySize:({dependencyValues:e})=>[e.nVertices,2],returnArrayDependenciesByKey:()=>({globalDependencies:{seriesNumber:{dependencyType:"stateVariable",variableName:"seriesNumber"},allIterates:{dependencyType:"stateVariable",variableName:"allIterates"}}}),arrayDefinitionByKey({globalDependencyValues:e,arraySize:t}){let n={};for(let r=0;r({nVertices:{dependencyType:"stateVariable",variableName:"nVertices"}}),returnArraySize:({dependencyValues:e})=>[e.nVertices],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={vertex:{dependencyType:"stateVariable",variableName:"vertex"+(Number(n)+1)}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].vertex.map((e=>e.evaluate_to_constant()));t.every((e=>Number.isFinite(e)))||(t=Array(t.length).fill(NaN)),n[r]=t}return{setValue:{numericalVertices:n}}}},e.nearestPoint={returnDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},numericalVertices:{dependencyType:"stateVariable",variableName:"numericalVertices"},nVertices:{dependencyType:"stateVariable",variableName:"nVertices"}}),definition({dependencyValues:e}){let t,n,r=e.nDimensions,a=e.nVertices,i=e.numericalVertices,s=[],o=i[0]?.[0],l=i[0]?.[1];for(let e=1;e=1?{x1:h,x2:f}:{x1:l+g*a*n,x2:u+g*y*o};let b=Math.pow((d-r.x1)/n,2)+Math.pow((m-r.x2)/o,2);b0&&(p.x3=0),p}}}}},e}async movePolyline({pointCoords:e,transient:t,sourceInformation:n,actionId:r}){let a={};for(let t in e)a[t+",0"]=me$3.fromAst(e[t][0]),a[t+",1"]=me$3.fromAst(e[t][1]);return t?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"vertices",value:a,sourceInformation:n}],transient:!0,actionId:r}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"vertices",value:a,sourceInformation:n}],actionId:r,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{pointCoordinates:e}}})}async finalizePolylinePosition(){return await this.actions.movePolyline({pointCoords:await this.stateValues.numericalVertices,transient:!1})}}class Cell extends BaseComponent{static componentType="cell";static rendererType="cell";static renderChildren=!0;static includeBlankStringChildren=!0;static primaryStateVariableForDefinition="text";static createAttributesObject(){let e=super.createAttributesObject();return e.rowNum={createComponentOfType:"text",createStateVariable:"rowNum",defaultValue:null,public:!0},e.colNum={createComponentOfType:"text",createStateVariable:"colNum",defaultValue:null,public:!0},e.colSpan={createComponentOfType:"integer",createStateVariable:"colSpan",defaultValue:1,public:!0,forRenderer:!0},e.halign={createComponentOfType:"text"},e.bottom={createComponentOfType:"text"},e.right={createComponentOfType:"text"},e.prefill={createComponentOfType:"text",createStateVariable:"prefill",defaultValue:"",public:!0},e}static returnChildGroups(){return[{group:"maths",componentTypes:["math"]},{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.halign={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,hasEssential:!0,defaultValue:"left",returnDependencies:()=>({halignAttr:{dependencyType:"attributeComponent",attributeName:"halign",variableNames:["value"]},parentHalign:{dependencyType:"parentStateVariable",variableName:"halign"},tabularHalign:{dependencyType:"ancestor",componentType:"tabular",variableNames:["halign"]}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.halignAttr){let t=e.halignAttr.stateValues.value;return["left","center","right","justify"].includes(t)||(t="left"),{setValue:{halign:t}}}return!t.parentHalign&&e.parentHalign?{setValue:{halign:e.parentHalign}}:!t.tabularHalign&&e.tabularHalign?{setValue:{halign:e.tabularHalign.stateValues.halign}}:{useEssentialOrDefaultValue:{halign:!0}}}},e.bottom={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,hasEssential:!0,defaultValue:"none",returnDependencies:()=>({bottomAttr:{dependencyType:"attributeComponent",attributeName:"bottom",variableNames:["value"]},parentBottom:{dependencyType:"parentStateVariable",variableName:"bottom"},tabularBottom:{dependencyType:"ancestor",componentType:"tabular",variableNames:["bottom"]}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.bottomAttr){let t=e.bottomAttr.stateValues.value;return["none","minor","medium","major"].includes(t)||(t="none"),{setValue:{bottom:t}}}return!t.parentBottom&&e.parentBottom?{setValue:{bottom:e.parentBottom}}:!t.tabularBottom&&e.tabularBottom?{setValue:{bottom:e.tabularBottom.stateValues.bottom}}:{useEssentialOrDefaultValue:{bottom:!0}}}},e.right={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,hasEssential:!0,defaultValue:"none",returnDependencies:()=>({rightAttr:{dependencyType:"attributeComponent",attributeName:"right",variableNames:["value"]},tabularRight:{dependencyType:"ancestor",componentType:"tabular",variableNames:["right"]}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.rightAttr){let t=e.rightAttr.stateValues.value;return["none","minor","medium","major"].includes(t)||(t="none"),{setValue:{right:t}}}return!t.tabularRight&&e.tabularRight?{setValue:{right:e.tabularRight.stateValues.right}}:{useEssentialOrDefaultValue:{right:!0}}}},e.inHeader={public:!0,shadowingInstructions:{createComponentOfType:"booloean"},forRenderer:!0,defaultValue:!1,returnDependencies:()=>({parentHeader:{dependencyType:"parentStateVariable",variableName:"header"}}),definition:({dependencyValues:e})=>({setValue:{inHeader:!0===e.parentHeader}})},e.onlyMathChild={returnDependencies:()=>({mathChild:{dependencyType:"child",childGroups:["maths"]},otherChildren:{dependencyType:"child",childGroups:["anything"]}}),definition:({dependencyValues:e})=>({setValue:{onlyMathChild:1===e.mathChild.length&&0===e.otherChildren.length}})},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},hasEssential:!0,forRenderer:!0,returnDependencies:()=>({children:{dependencyType:"child",childGroups:["maths","anything"],variableNames:["text"],variablesOptional:!0},prefill:{dependencyType:"stateVariable",variableName:"prefill"}}),definition({dependencyValues:e}){if(0===e.children.length)return{useEssentialOrDefaultValue:{text:{defaultValue:e.prefill}}};let t="";for(let n of e.children)"object"==typeof n?n.stateValues.text&&(t+=n.stateValues.text):t+=n.toString();return{setValue:{text:t}}},inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t})=>0===t.children.length?{success:!0,instructions:[{setEssentialValue:"text",value:null===e.text?"":String(e.text)}]}:1===t.children.length?"object"==typeof t.children[0]&&void 0===t.children[0].stateValues.text?{success:!1}:{success:!0,instructions:[{setDependency:"children",desiredValue:e.text,childIndex:0,variableIndex:0}]}:{success:!1}},e.math={public:!0,shadowingInstructions:{createComponentOfType:"math"},stateVariablesDeterminingDependencies:["onlyMathChild"],returnDependencies:({stateValues:e})=>e.onlyMathChild?{mathChild:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]}}:{text:{dependencyType:"stateVariable",variableName:"text"}},definition({dependencyValues:e}){if(e.mathChild)return{setValue:{math:e.mathChild[0].stateValues.value}};{let t;try{t=me$3.fromAst(textToAst$1.convert(e.text))}catch(e){t=me$3.fromAst("_")}return{setValue:{math:t}}}},async inverseDefinition({desiredStateVariableValues:e,dependencyValues:t,stateValues:n,workspace:r}){if(t.mathChild)return{success:!0,instructions:[{setDependency:"mathChild",desiredValue:e.math,childIndex:0,variableIndex:0}]};return{success:!0,instructions:[{setDependency:"text",desiredValue:(await preprocessMathInverseDefinition({desiredValue:e.math,stateValues:n,variableName:"math",workspace:r})).desiredValue.toString()}]}}},e.number={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({math:{dependencyType:"stateVariable",variableName:"math"}}),definition({dependencyValues:e}){let t=e.math.evaluate_to_constant();return Number.isFinite(t)||(t=NaN),{setValue:{number:t}}},inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setDependency:"math",desiredValue:me$3.fromAst(e.number)}]})},e}static adapters=["text","math","number"]}class Row extends BaseComponent{static componentType="row";static rendererType="row";static renderChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.rowNum={createComponentOfType:"text",createStateVariable:"rowNum",defaultValue:null,public:!0},e.header={createComponentOfType:"boolean",createStateVariable:"header",defaultValue:!1,public:!0,forRenderer:!0},e.halign={createComponentOfType:"text"},e.valign={createComponentOfType:"text"},e.left={createComponentOfType:"text"},e.bottom={createComponentOfType:"text"},e}static returnChildGroups(){return[{group:"cells",componentTypes:["cell"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.halign={public:!0,shadowingInstructions:{createComponentOfType:"text"},defaultValue:"left",hasEssential:!0,returnDependencies:()=>({halignAttr:{dependencyType:"attributeComponent",attributeName:"halign",variableNames:["value"]},parentHalign:{dependencyType:"parentStateVariable",variableName:"halign"}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.halignAttr){let t=e.halignAttr.stateValues.value;return["left","center","right","justify"].includes(t)||(t="left"),{setValue:{halign:t}}}return null===e.parentHalign||t.parentHalign?{useEssentialOrDefaultValue:{halign:!0}}:{setValue:{halign:e.parentHalign}}}},e.valign={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,defaultValue:"middle",hasEssential:!0,returnDependencies:()=>({valignAttr:{dependencyType:"attributeComponent",attributeName:"valign",variableNames:["value"]},parentValign:{dependencyType:"parentStateVariable",variableName:"valign"}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.valignAttr){let t=e.valignAttr.stateValues.value;return["top","middle","bottom"].includes(t)||(t="middle"),{setValue:{valign:t}}}return null===e.parentValign||t.parentValign?{useEssentialOrDefaultValue:{valign:!0}}:{setValue:{valign:e.parentValign}}}},e.left={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,defaultValue:"none",hasEssential:!0,returnDependencies:()=>({leftAttr:{dependencyType:"attributeComponent",attributeName:"left",variableNames:["value"]},parentLeft:{dependencyType:"parentStateVariable",variableName:"left"}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.leftAttr){let t=e.leftAttr.stateValues.value;return["none","minor","medium","major"].includes(t)||(t="none"),{setValue:{left:t}}}return null===e.parentLeft||t.parentLeft?{useEssentialOrDefaultValue:{left:!0}}:{setValue:{left:e.parentLeft}}}},e.bottom={public:!0,shadowingInstructions:{createComponentOfType:"text"},defaultValue:"none",hasEssential:!0,returnDependencies:()=>({bottomAttr:{dependencyType:"attributeComponent",attributeName:"bottom",variableNames:["value"]},parentBottom:{dependencyType:"parentStateVariable",variableName:"bottom"}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.bottomAttr){let t=e.bottomAttr.stateValues.value;return["none","minor","medium","major"].includes(t)||(t="none"),{setValue:{bottom:t}}}return null===e.parentBottom||t.parentBottom?{useEssentialOrDefaultValue:{bottom:!0}}:{setValue:{bottom:e.parentBottom}}}},e.prescribedCellsWithColNum={returnDependencies:()=>({cellChildren:{dependencyType:"child",childGroups:["cells"],variableNames:["colNum"]}}),definition:({dependencyValues:e})=>({setValue:{prescribedCellsWithColNum:e.cellChildren}})},e}}class Column extends BaseComponent{static componentType="column";static rendererType="containerBlock";static renderChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.colNum={createComponentOfType:"text",createStateVariable:"colNum",defaultValue:null,public:!0},e}static returnChildGroups(){return[{group:"cells",componentTypes:["cell"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.prescribedCellsWithRowNum={returnDependencies:()=>({cellChildren:{dependencyType:"child",childGroups:["cells"],variableNames:["rowNum"]}}),definition:({dependencyValues:e})=>({setValue:{prescribedCellsWithRowNum:e.cellChildren}})},e}}class CellBlock extends BaseComponent{static componentType="cellBlock";static rendererType="containerBlock";static createAttributesObject(){let e=super.createAttributesObject();return e.rowNum={createComponentOfType:"text",createStateVariable:"rowNum",defaultValue:null,public:!0},e.colNum={createComponentOfType:"text",createStateVariable:"colNum",defaultValue:null,public:!0},e}static returnChildGroups(){return[{group:"children",componentTypes:["cell","row","column","cellblock"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.prescribedCellsRowsColumnsBlocks={returnDependencies:()=>({cellRelatedChildren:{dependencyType:"child",childGroups:["children"],variableNames:["rowNum","colNum","prescribedCellsWithColNum","prescribedCellsWithRowNum","prescribedCellsRowsColumnsBlocks"],variablesOptional:!0}}),definition:({dependencyValues:e})=>({setValue:{prescribedCellsRowsColumnsBlocks:e.cellRelatedChildren}})},e}}class Tabular extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="tabular";static rendererType="tabular";static renderChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.width={createComponentOfType:"_componentSize",createStateVariable:"width",defaultValue:{size:100,isAbsolute:!1},public:!0,forRenderer:!0},e.height={createComponentOfType:"_componentSize",createStateVariable:"height",defaultValue:null,public:!0,forRenderer:!0},e.halign={createComponentOfType:"text",createStateVariable:"halign",defaultValue:"left",public:!0,validValues:["left","center","right","justify"]},e.valign={createComponentOfType:"text",createStateVariable:"valign",defaultValue:"middle",public:!0,validValues:["top","middle","bottom"]},e.top={createComponentOfType:"text",createStateVariable:"top",defaultValue:"none",public:!0,validValues:["none","minor","medium","major"],forRenderer:!0},e.left={createComponentOfType:"text",createStateVariable:"left",defaultValue:"none",public:!0,validValues:["none","minor","medium","major"]},e.bottom={createComponentOfType:"text",createStateVariable:"bottom",defaultValue:"none",public:!0,validValues:["none","minor","medium","major"]},e.right={createComponentOfType:"text",createStateVariable:"right",defaultValue:"none",public:!0,validValues:["none","minor","medium","major"]},e}static returnChildGroups(){return[{group:"rows",componentTypes:["row"]}]}static returnStateVariableDefinitions(){return super.returnStateVariableDefinitions()}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class Table extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="table";static renderChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.suppressTableNameInTitle={createComponentOfType:"boolean",createStateVariable:"suppressTableNameInTitle",defaultValue:!1,forRenderer:!0},e.number={createComponentOfType:"boolean",createStateVariable:"number",defaultValue:!0,forRenderer:!0},e}static returnChildGroups(){return[{group:"titles",componentTypes:["title"]},{group:"inlinesBlocks",componentTypes:["_inline","_block"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.tableEnumeration={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,stateVariablesDeterminingDependencies:["number"],additionalStateVariablesDefined:[{variableName:"tableName",public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0}],returnDependencies({stateValues:e}){let t={};return e.number&&(t.tableCounter={dependencyType:"counter",counterName:"table"}),t},definition({dependencyValues:e}){if(void 0===e.tableCounter)return{setValue:{tableEnumeration:null,tableName:"Table"}};let t=String(e.tableCounter);return{setValue:{tableEnumeration:t,tableName:"Table "+t}}}},e.titleChildName={forRenderer:!0,returnDependencies:()=>({titleChild:{dependencyType:"child",childGroups:["titles"]}}),definition({dependencyValues:e}){let t=null;return e.titleChild.length>0&&(t=e.titleChild[0].componentName),{setValue:{titleChildName:t}}}},e.title={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({titleChild:{dependencyType:"child",childGroups:["titles"],variableNames:["text"]}}),definition({dependencyValues:e}){let t=null;return e.titleChild.length>0&&(t=e.titleChild[0].stateValues.text),{setValue:{title:t}}}},e}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class Figure extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="figure";static renderChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.suppressFigureNameInCaption={createComponentOfType:"boolean",createStateVariable:"suppressFigureNameInCaption",defaultValue:!1,forRenderer:!0},e.number={createComponentOfType:"boolean",createStateVariable:"number",defaultValue:!0,forRenderer:!0},e}static returnChildGroups(){return[{group:"captions",componentTypes:["caption"]},{group:"inlinesBlocks",componentTypes:["_inline","_block"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.figureEnumeration={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,stateVariablesDeterminingDependencies:["number"],additionalStateVariablesDefined:[{variableName:"figureName",public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0}],returnDependencies({stateValues:e}){let t={};return e.number&&(t.figureCounter={dependencyType:"counter",counterName:"figure"}),t},definition({dependencyValues:e}){if(void 0===e.figureCounter)return{setValue:{figureEnumeration:null,figureName:"Figure"}};let t=String(e.figureCounter);return{setValue:{figureEnumeration:t,figureName:"Figure "+t}}}},e.captionChildName={forRenderer:!0,returnDependencies:()=>({captionChild:{dependencyType:"child",childGroups:["captions"]}}),definition({dependencyValues:e}){let t=null;return e.captionChild.length>0&&(t=e.captionChild[0].componentName),{setValue:{captionChildName:t}}}},e.caption={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({captionChild:{dependencyType:"child",childGroups:["captions"],variableNames:["text"]}}),definition({dependencyValues:e}){let t=null;return e.captionChild.length>0&&(t=e.captionChild[0].stateValues.text),{setValue:{caption:t}}}},e}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class TextListFromString extends InlineComponent{static componentType="textListFromString";static rendererType="asList";static renderChildren=!0;static stateVariableForAttributeValue="texts";static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e}){let t=e.reduce((function(e,t){return"string"==typeof t?[...e,...t.split(/\s+/).filter((e=>e))]:[...e,t]}),[]);return{success:!0,newChildren:t}}}),e}static returnChildGroups(){return[{group:"strings",componentTypes:["string"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nComponents={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({stringChildren:{dependencyType:"child",childGroups:["strings"]}}),definition:function({dependencyValues:e}){return{setValue:{nComponents:e.stringChildren.length}}}},e.texts={public:!0,shadowingInstructions:{createComponentOfType:"text"},isArray:!0,entryPrefixes:["text"],returnArraySizeDependencies:()=>({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"}}),returnArraySize:({dependencyValues:e})=>[e.nComponents],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={stringChild:{dependencyType:"child",childGroups:["strings"],variableNames:["value"],childIndices:[n]}};return{dependenciesByKey:t}},arrayDefinitionByKey:function({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t)1===e[r].stringChild.length&&(n[r]=e[r].stringChild[0]);return{setValue:{texts:n}}}},e.nValues={isAlias:!0,targetVariableName:"nComponents"},e.values={isAlias:!0,targetVariableName:"texts"},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({texts:{dependencyType:"stateVariable",variableName:"texts"}}),definition:({dependencyValues:e})=>({setValue:{text:e.texts.join(", ")}})},e}}class VariantControl extends BaseComponent{static componentType="variantControl";static rendererType=void 0;static createAttributesObject(){let e=super.createAttributesObject();return e.nVariants={createPrimitiveOfType:"integer"},e.uniqueVariants={createPrimitiveOfType:"boolean"},e.variantsToInclude={createComponentOfType:"textListFromString"},e.variantsToExclude={createComponentOfType:"textListFromString"},e.variantNames={createComponentOfType:"textListFromString"},e.seeds={createComponentOfType:"textListFromString"},e}}class SelectFromSequence extends Sequence{static componentType="selectFromSequence";static assignNamesToReplacements=!0;static createsVariants=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.assignNamesSkip={createPrimitiveOfType:"number"},e.numberToSelect={createComponentOfType:"integer",createStateVariable:"numberToSelect",defaultValue:1,public:!0},e.withReplacement={createComponentOfType:"boolean",createStateVariable:"withReplacement",defaultValue:!1,public:!0},e.sortResults={createComponentOfType:"boolean",createStateVariable:"sortResults",defaultValue:!1,public:!0},e.excludeCombinations={createComponentOfType:"_componentListOfListsWithSelectableType"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();e.excludedCombinations={returnDependencies:()=>({excludeCombinations:{dependencyType:"attributeComponent",attributeName:"excludeCombinations",variableNames:["lists"]},type:{dependencyType:"stateVariable",variableName:"type"},numberToSelect:{dependencyType:"stateVariable",variableName:"numberToSelect"}}),definition:function({dependencyValues:e}){if(null!==e.excludeCombinations){let t=e.excludeCombinations.stateValues.lists.map((t=>t.slice(0,e.numberToSelect))).filter((t=>t.length===e.numberToSelect));if("number"===e.type)for(;;){let e=mergeContainingCombinations(t);if(!e.merged)break;t=e.combinations}return{setValue:{excludedCombinations:t}}}return{setValue:{excludedCombinations:[]}}}},e.variants={returnDependencies:()=>({variants:{dependencyType:"variants"}}),definition:function({dependencyValues:e}){return{setValue:{variants:e.variants}}}},e.selectedValues={immutable:!0,hasEssential:!0,shadowVariable:!0,additionalStateVariablesDefined:[{variableName:"selectedIndices",hasEssential:!0,shadowVariable:!0,immutable:!0}],returnDependencies:({sharedParameters:e})=>({numberToSelect:{dependencyType:"stateVariable",variableName:"numberToSelect"},withReplacement:{dependencyType:"stateVariable",variableName:"withReplacement"},length:{dependencyType:"stateVariable",variableName:"length"},from:{dependencyType:"stateVariable",variableName:"from"},step:{dependencyType:"stateVariable",variableName:"step"},exclude:{dependencyType:"stateVariable",variableName:"exclude"},excludedCombinations:{dependencyType:"stateVariable",variableName:"excludedCombinations"},type:{dependencyType:"stateVariable",variableName:"type"},lowercase:{dependencyType:"stateVariable",variableName:"lowercase"},sortResults:{dependencyType:"stateVariable",variableName:"sortResults"},variants:{dependencyType:"stateVariable",variableName:"variants"},variantRng:{dependencyType:"value",value:e.variantRng,doNotProxy:!0}}),definition:makeSelection},e.isVariantComponent={returnDependencies:()=>({}),definition:()=>({setValue:{isVariantComponent:!0}})},e.generatedVariantInfo={returnDependencies:()=>({selectedIndices:{dependencyType:"stateVariable",variableName:"selectedIndices"}}),definition:({dependencyValues:e,componentName:t})=>({setValue:{generatedVariantInfo:{indices:e.selectedIndices,meta:{createdBy:t}}}})};let t=e.readyToExpandWhenResolved.returnDependencies;return e.readyToExpandWhenResolved.returnDependencies=function(){let e=t();return e.selectedValues={dependencyType:"stateVariable",variableName:"selectedValues"},e},e}static async createSerializedReplacements({component:e,componentInfoObjects:t,flags:n}){let r=await e.stateValues.type;"letters"===r&&(r="text");let a=e.attributes.newNamespace?.primitive,i={};for(let t of["fixed","displayDigits","displaySmallAsZero","displayDecimals","padZeros"])t in e.attributes&&(i[t]=e.attributes[t]);let s={};Object.keys(i).length>0&&(s=convertAttributesForComponentType({attributes:i,componentType:r,componentInfoObjects:t,compositeCreatesNewNamespace:a,flags:n}));let o=[];for(let t of await e.stateValues.selectedValues)o.push({componentType:r,attributes:s,state:{value:t,fixed:!0}});return{replacements:processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:o,parentName:e.componentName,parentCreatesNewNamespace:a,componentInfoObjects:t}).serializedComponents}}static calculateReplacementChanges(){return[]}static determineNumberOfUniqueVariants({serializedComponent:e}){let t=1,n=!1,r=e.attributes.type.primitive,a=e.attributes.numberToSelect?.component;if(a){if("integer"!==a.componentType||1!==a.children?.length||"string"!=typeof a.children[0])return console.log("cannot determine unique variants of selectFromSequence as numberToSelect isn't constant number."),{success:!1};if(t=Number(a.children[0]),!(Number.isInteger(t)&&t>=0))return console.log("cannot determine unique variants of selectFromSequence as numberToSelect isn't a non-negative integer."),{success:!1}}let i=e.attributes.withReplacement?.component;if(i){if("boolean"!==i.componentType)return console.log("cannot determine unique variants of selectFromSequence as withReplacement isn't constant boolean."),{success:!1};if(1===i.children?.length&&"string"==typeof i.children[0])n="true"===i.children[0].toLowerCase();else{if(void 0!==i.children&&0!==i.children.length||"boolean"!=typeof i.state?.value)return console.log("cannot determine unique variants of selectFromSequence as withReplacement isn't constant boolean."),{success:!1};n=i.state.value}}let s={from:null,to:null,step:null,length:null},o=e.attributes.from?.component;if(o){let e=o.children[0];if(1!==e.children?.length||"string"!=typeof e.children[0])return console.log("cannot determine unique variants of selectFromSequence as from isn't a constant."),{success:!1};{let t;if("number"===r){if(t=Number(e.children[0]),!Number.isFinite(t))return console.log("cannot determine unique variants of selectFromSequence of number type as from isn't a number."),{success:!1}}else if("letters"===r){if(t=lettersToNumber$1(e.children[0]),!Number.isFinite(t))return console.log("cannot determine unique variants of selectFromSequence of letters type as from isn't a combination of letters."),{success:!1}}else{let n=getFromText({functionSymbols:["f","g"]});try{t=n(e.children[0])}catch(e){return console.log("cannot determine unique variants of selectFromSequence of math type as from isn't a valid math expression."),{success:!1}}}s.from=t}}let l=e.attributes.to?.component;if(l){let e=l.children[0];if(1!==e.children?.length||"string"!=typeof e.children[0])return console.log("cannot determine unique variants of selectFromSequence as to isn't a constant."),{success:!1};{let t;if("number"===r){if(t=Number(e.children[0]),!Number.isFinite(t))return console.log("cannot determine unique variants of selectFromSequence of number type as to isn't a number."),{success:!1}}else if("letters"===r){if(t=lettersToNumber$1(e.children[0]),!Number.isFinite(t))return console.log("cannot determine unique variants of selectFromSequence of letters type as to isn't a combination of letters."),{success:!1}}else{let n=getFromText({functionSymbols:["f","g"]});try{t=n(e.children[0])}catch(e){return console.log("cannot determine unique variants of selectFromSequence of math type as to isn't a valid math expression."),{success:!1}}}s.to=t}}let u=e.attributes.step?.component;if(u){if(1!==u.children?.length||"string"!=typeof u.children[0])return console.log("cannot determine unique variants of selectFromSequence as step isn't a constant."),{success:!1};{let e;if("number"===r){if(e=Number(u.children[0]),!Number.isFinite(e))return console.log("cannot determine unique variants of selectFromSequence of number type as step isn't a number."),{success:!1}}else if("letters"===r){if(e=Number(u.children[0]),!Number.isInteger(e))return console.log("cannot determine unique variants of selectFromSequence of letters type as step isn't an integer."),{success:!1}}else{let t=getFromText({functionSymbols:["f","g"]});try{e=t(u.children[0])}catch(e){return console.log("cannot determine unique variants of selectFromSequence of math type as step isn't a valid math expression."),{success:!1}}}s.step=e}}let c=e.attributes.length?.component;if(c){if(1!==c.children?.length||"string"!=typeof c.children[0])return console.log("cannot determine unique variants of selectFromSequence as length isn't a constant."),{success:!1};{let e=Number(c.children[0]);if(!Number.isInteger(e))return console.log("cannot determine unique variants of selectFromSequence as length isn't an integer."),{success:!1};s.length=e}}if(e.attributes.excludeCombinations)return console.log("have not implemented unique variants of a selectFromSequence with excludeCombinations"),{success:!1};let p=[],d=e.attributes.exclude?.component;if(d){if("math"===r)return console.log("have not implemented unique variants of a selectFromSequence of type math with exclude"),{success:!1};if(!d.children.every((e=>1===e.children?.length&&"string"==typeof e.children[0])))return console.log("have not implemented unique variants of a selectFromSequence with non-constant exclude"),{success:!1};if(p="letters"===r?d.children.map((e=>lettersToNumber$1(e.children[0]))):d.children.map((e=>Number(e.children[0]))),!p.every(Number.isFinite))return console.log("have not implemented unique variants of a selectFromSequence with non-constant exclude"),{success:!1}}s=calculateSequenceParameters(s);let m=s.length,h=[];if(p.length>0&&"math"!==r){p.sort(((e,t)=>e-t)),p=p.filter(((e,t,n)=>e!=n[t-1]));for(let e of p){if(es.length-1+1e-10)break;Math.abs(t-Math.round(t))<1e-10&&(m--,h.push(t))}}if(m<=0)return{success:!1};let f,y={excludeIndices:h,nOptions:m,numberToSelect:t,withReplacement:n};if(e.variants.uniqueVariantData=y,n||1===t)f=Math.pow(m,t);else{f=m;for(let e=m-1;e>m-t;e--)f*=e}return e.variants.numberOfVariants=f,{success:!0,numberOfVariants:f}}static getUniqueVariant({serializedComponent:e,variantIndex:t}){let n=e.variants?.numberOfVariants;if(void 0===n)return{success:!1};if(!Number.isInteger(t)||t<1||t>n)return{success:!1};let r=e.variants.uniqueVariantData,a=r.excludeIndices,i=r.nOptions,s=r.numberToSelect,o=r.withReplacement,l=function(e){let t=e;for(let e of a)t>=e&&t++;return t};if(1===s)return{success:!0,desiredVariant:{indices:[l(t-1)+1]}};let u=enumerateSelectionCombinations({numberOfIndices:s,numberOfOptions:i,maxNumber:t,withReplacement:o})[t-1].map(l).map((e=>e+1));return{success:!0,desiredVariant:{indices:u}}}}function makeSelection({dependencyValues:e}){if(e.numberToSelect<1)return{setEssentialValue:{selectedValues:[],selectedIndices:[]},setValue:{selectedValues:[],selectedIndices:[]}};let t=1;if(e.withReplacement||(t=e.numberToSelect),t>e.length)throw Error("Cannot select "+t+" values from a sequence of length "+e.length);if(e.variants&&void 0!==e.variants.desiredVariant){let t=e.variants.desiredVariant.indices;if(void 0!==t){if(t.length!==e.numberToSelect)throw Error("Number of indices specified for select must match number to select");if(t=t.map(Number),!t.every(Number.isInteger))throw Error("All indices specified for select must be integers");let n=e.length;t=t.map((e=>((e-1)%n+n)%n+1));let r=[];for(let n of t){let t=returnSequenceValueForIndex({index:n-1,from:e.from,step:e.step,length:e.length,exclude:e.exclude,type:e.type,lowercase:e.lowercase});if(null===t)throw Error("Specified index of selectfromsequence that was excluded");r.push(t)}if(checkForExcludedCombination({type:e.type,excludedCombinations:e.excludedCombinations,values:r}))throw Error("Specified indices of selectfromsequence that was an excluded combination");return{setEssentialValue:{selectedValues:r,selectedIndices:t},setValue:{selectedValues:r,selectedIndices:t}}}}let n,r,a=e.excludedCombinations.length;if("number"===e.type){a=0;let t=e.length-e.exclude.length;for(let n of e.excludedCombinations){let r=n.reduce(((e,t)=>e+(Number.isNaN(t)?1:0)),0);if(r>0)if(e.withReplacement)a+=Math.pow(t,r);else{let n=t-e.numberToSelect+r,i=n;for(let e=1;e.7*i){let t=0;for(let n=0;n.7*t){if("number"!==e.type||!e.excludedCombinations.some((e=>e.some(Number.isNaN))))throw Error("Excluded over 70% of combinations in selectFromSequence");if(a-=estimateNumberOfDuplicateCombinations(e.excludedCombinations,e.length-e.exclude.length,e.withReplacement),a>.7*t)throw Error("Excluded over 70% of combinations in selectFromSequence")}}let s=!1;for(let a=0;a<200;a++){let a=selectValuesAndIndices({stateValues:e,numberUniqueRequired:t,numberToSelect:e.numberToSelect,withReplacement:e.withReplacement,rng:e.variantRng});if(n=a.selectedValues,r=a.selectedIndices,!checkForExcludedCombination({type:e.type,excludedCombinations:e.excludedCombinations,values:n})){s=!0;break}}if(!s)throw Error("By extremely unlikely fluke, couldn't select combination of random values")}if(e.sortResults){let t=[];for(let[e,a]of n.entries())t.push({value:a,index:r[e]});"number"===e.type?t.sort(((e,t)=>e.value-t.value)):"letters"===e.type&&t.sort(((e,t)=>lettersToNumber$1(e.value)-lettersToNumber$1(t.value))),n=t.map((e=>e.value)),r=t.map((e=>e.index))}return{setEssentialValue:{selectedValues:n,selectedIndices:r},setValue:{selectedValues:n,selectedIndices:r}}}function selectValuesAndIndices({stateValues:e,numberUniqueRequired:t=1,numberToSelect:n=1,withReplacement:r=!1,rng:a}){let i=[],s=[];if(e.exclude.length+t<.5*e.length){for(let t=0;tl)throw Error("Cannot select "+t+" unique values from sequence of length "+l);if(1===t){for(let e=0;e0;e--){const t=a(),n=Math.floor(t*(e+1));[o[e],o[n]]=[o[n],o[e]]}let u=o.slice(0,n);return i=u.map((e=>e.value)),s=u.map((e=>e.originalIndex+1)),{selectedValues:i,selectedIndices:s}}function checkForExcludedCombination({type:e,excludedCombinations:t,values:n}){return"math"===e?t.some((e=>e.every(((e,t)=>e.equals(n[t]))))):"number"===e?t.some((e=>e.every(((e,t)=>Number.isNaN(e)||Math.abs(e-n[t])<=1e-14*Math.max(Math.abs(e),Math.abs(n[t])))))):t.some((e=>e.every(((e,t)=>e===n[t]))))}function mergeContainingCombinations(e){if(0===e.length)return{merged:!1,combinations:[]};let t=[e[0]],n=!1;for(let r of e.slice(1)){let e=[],a=!1;for(let n of t){if(a){e.push(n);continue}let t=[];a=!0;let i=null;for(let e=0;e!Number.isNaN(e)));[...new Set(e)].length===e.length&&a.push(o)}}}for(;;){let e=mergeContainingCombinations(a);if(!e.merged)break;a=e.combinations}let i=0;if(a.length>0)for(let e of a){let r=e.reduce(((e,t)=>e+(Number.isNaN(t)?1:0)),0);if(r>0)if(n)i+=Math.pow(t,r);else{let n=t-e.length+r,a=n;for(let e=1;e"string"==typeof e||e.doenetAttributes&&e.doenetAttributes.createdFromMacro)))return{success:!1};let r;r=t.type?t.type:"math",["math","text","number","boolean"].includes(r)||(console.warn(`Invalid type ${r}`),r="math");let a=returnGroupIntoComponentTypeSeparatedBySpaces({componentType:r,forceComponentType:!0})({matchedChildren:e,componentInfoObjects:n});if(a.success){return{success:!0,newChildren:a.newChildren.map((e=>({componentType:"option",children:[e]}))),newAttributes:{addLevelToAssignNames:{primitive:!0}}}}return{success:!1}}}),e}static returnChildGroups(){return[{group:"options",componentTypes:["option"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.variants={returnDependencies:()=>({variants:{dependencyType:"variants"}}),definition:function({dependencyValues:e}){return{setValue:{variants:e.variants}}}},e.currentVariantName={returnDependencies:({sharedParameters:e})=>({variantName:{dependencyType:"value",value:e.variantName}}),definition:({dependencyValues:e})=>({setValue:{currentVariantName:e.variantName}})},e.allVariantNames={returnDependencies:({sharedParameters:e})=>({allVariantNames:{dependencyType:"value",value:e.allVariantNames}}),definition:({dependencyValues:e})=>({setValue:{allVariantNames:e.allVariantNames}})},e.nOptions={additionalStateVariablesDefined:["optionChildren"],returnDependencies:()=>({optionChildren:{dependencyType:"child",childGroups:["options"],variableNames:["selectForVariants","selectWeight"]}}),definition:({dependencyValues:e})=>({setValue:{optionChildren:e.optionChildren,nOptions:e.optionChildren.length}})},e.availableVariants={returnDependencies:()=>({optionChildren:{dependencyType:"stateVariable",variableName:"optionChildren"},numberToSelect:{dependencyType:"stateVariable",variableName:"numberToSelect"},allVariantNames:{dependencyType:"stateVariable",variableName:"allVariantNames"}}),definition:function({dependencyValues:e}){let t={};for(let[n,r]of e.optionChildren.entries())for(let e of r.stateValues.selectForVariants){let r=e.toLowerCase();void 0===t[r]&&(t[r]=[]),t[r].push(n+1)}for(let n in t)if(t[n].length!==e.numberToSelect)throw Error("Invalid variant name for select. Variant name "+n+" appears in "+t[n].length+" options but number to select is "+numberToSelect);if(Object.keys(t).length>0){for(let n of e.allVariantNames)if(!(n in t))throw Error("Some variants are specified for select but no options are specified for possible variant name: "+n);for(let n in t)if(!e.allVariantNames.includes(n))throw Error("Variant name "+n+" that is specified for select is not a possible variant name.")}return{setValue:{availableVariants:t}}}},e.selectedIndices={immutable:!0,hasEssential:!0,shadowVariable:!0,returnDependencies:({sharedParameters:e})=>({numberToSelect:{dependencyType:"stateVariable",variableName:"numberToSelect"},withReplacement:{dependencyType:"stateVariable",variableName:"withReplacement"},optionChildren:{dependencyType:"stateVariable",variableName:"optionChildren"},nOptions:{dependencyType:"stateVariable",variableName:"nOptions"},currentVariantName:{dependencyType:"stateVariable",variableName:"currentVariantName"},variants:{dependencyType:"stateVariable",variableName:"variants"},availableVariants:{dependencyType:"stateVariable",variableName:"availableVariants"},variantRng:{dependencyType:"value",value:e.variantRng,doNotProxy:!0}}),definition:function({dependencyValues:e}){if(!(e.numberToSelect>=1)||0===e.nOptions)return{setEssentialValue:{selectedIndices:[]},setValue:{selectedIndices:[]}};if(e.variants&&void 0!==e.variants.desiredVariant){let t=e.variants.desiredVariant.indices;if(void 0!==t){if(t.length!==e.numberToSelect)throw Error("Number of indices specified for select must match number to select");if(t=t.map(Number),!t.every(Number.isInteger))throw Error("All indices specified for select must be integers");let n=e.nOptions;return t=t.map((e=>((e-1)%n+n)%n+1)),{setEssentialValue:{selectedIndices:t},setValue:{selectedIndices:t}}}}let t=e.availableVariants[e.currentVariantName];if(void 0!==t){if(e.numberToSelect>1){t=[...t];for(let n=e.numberToSelect-1;n>0;n--){const r=e.variantRng(),a=Math.floor(r*(n+1));[t[n],t[a]]=[t[a],t[n]]}}return{setEssentialValue:{selectedIndices:t},setValue:{selectedIndices:t}}}let n=[],r=1;if(e.withReplacement||(r=e.numberToSelect),r>e.nOptions)throw Error("Cannot select "+r+" components from only "+e.nOptions);let a=e.optionChildren.map((e=>e.stateValues.selectWeight)),i=a.reduce(((e,t)=>e+t));a=a.map((e=>e/i));let s=a.reduce(((e,t,n)=>[...e,t+(e[n-1]||0)]),[]),o=[...Array(s.length).keys()].map((e=>e+1));for(let t=0;tr?u=e:l=e}let c=o[u];n.push(c),!e.withReplacement&&te+t)),a=a.map((e=>e/i)),s=a.reduce(((e,t,n)=>[...e,t+(e[n-1]||0)]),[]))}return{setEssentialValue:{selectedIndices:n},setValue:{selectedIndices:n}}}},e.isVariantComponent={returnDependencies:()=>({}),definition:()=>({setValue:{isVariantComponent:!0}})},e.generatedVariantInfo={providePreviousValuesInDefinition:!0,returnDependencies:({componentInfoObjects:e})=>({selectedIndices:{dependencyType:"stateVariable",variableName:"selectedIndices"},variantDescendants:{dependencyType:"descendant",componentTypes:Object.keys(e.componentTypesCreatingVariants),variableNames:["isVariantComponent","generatedVariantInfo"],useReplacementsForComposites:!0,recurseToMatchedChildren:!1,variablesOptional:!0,includeNonActiveChildren:!0,ignoreReplacementsOfEncounteredComposites:!0}}),definition({dependencyValues:e,componentName:t,previousValues:n}){let r={indices:e.selectedIndices,meta:{createdBy:t}},a=r.subvariants=[];for(let t of e.variantDescendants)t.stateValues.isVariantComponent?a.push(t.stateValues.generatedVariantInfo):t.stateValues.generatedVariantInfo&&a.push(...t.stateValues.generatedVariantInfo.subvariants);for(let[e,t]of a.entries())if(!t.subvariants&&n.generatedVariantInfo){let t=n.generatedVariantInfo.subvariants;t[e].subvariants&&(a[e]=Object.assign({},a[e]),a[e].subvariants=t[e].subvariants)}return{setValue:{generatedVariantInfo:r}}}},e.readyToExpandWhenResolved={returnDependencies:()=>({selectedIndices:{dependencyType:"stateVariable",variableName:"selectedIndices"}}),definition:()=>({setValue:{readyToExpandWhenResolved:!0}})},e}static async createSerializedReplacements({component:e,components:t,componentInfoObjects:n}){let r=[],a=await e.stateValues.optionChildren;for(let n of await e.stateValues.selectedIndices){let e=a[n-1].componentName,i=t[e],s=deepClone(await i.stateValues.serializedChildren),o={componentType:"option",state:{rendered:!0},doenetAttributes:Object.assign({},i.doenetAttributes),children:s,originalName:e};i.attributes.newNamespace&&(o.attributes={newNamespace:{primitive:!0}}),r.push(o)}let i=gatherVariantComponents({serializedComponents:r,componentInfoObjects:n});if(e.variants&&void 0!==e.variants.desiredVariant){let t=e.variants.desiredVariant;if(void 0!==t&&void 0!==t.subvariants)for(let e in t.subvariants){let n=t.subvariants[e],r=i[e];if(void 0===r)break;r.variants.desiredVariant=n}}let s=e.attributes.newNamespace?.primitive,o=e.doenetAttributes.assignNames;o&&await e.stateValues.addLevelToAssignNames&&(o=o.map((e=>[e])));for(let e of r)!e.attributes?.newNamespace?.primitive&&e.children&&markToCreateAllUniqueNames(e.children);let l=[];for(let[t,a]of r.entries()){let r=processAssignNames({assignNames:o,serializedComponents:[a],parentName:e.componentName,parentCreatesNewNamespace:s,componentInfoObjects:n,indOffset:t});l.push(r.serializedComponents[0])}return{replacements:l}}static calculateReplacementChanges(){return[]}static determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t}){let n=e.variants?.numberOfVariants;if(void 0!==n)return{success:!0,numberOfVariants:n};let r=1,a=!1,i=e.attributes.numberToSelect?.component;if(i){if("integer"!==i.componentType||1!==i.children?.length||"string"!=typeof i.children[0])return console.log("cannot determine unique variants of selectFromSequence as numberToSelect isn't constant number."),{success:!1};if(r=Number(i.children[0]),!(Number.isInteger(r)&&r>=0))return console.log("cannot determine unique variants of selectFromSequence as numberToSelect isn't a non-negative integer."),{success:!1}}let s=e.attributes.withReplacement?.component;if(s){if("boolean"!==s.componentType)return console.log("cannot determine unique variants of selectFromSequence as withReplacement isn't constant boolean."),{success:!1};if(1===s.children?.length&&"string"==typeof s.children[0])a="true"===s.children[0].toLowerCase();else{if(void 0!==s.children&&0!==s.children.length||"boolean"!=typeof s.state?.value)return console.log("cannot determine unique variants of selectFromSequence as withReplacement isn't constant boolean."),{success:!1};a=s.state.value}}for(let t of e.children)if(t.attributes?.selectWeight||t.attributes?.selectForVariants)return console.log("Unique variants for select disabled if have an option with selectWeight or selectForVariants specified"),{success:!1};void 0===e.variants&&(e.variants={});let o=gatherVariantComponents({serializedComponents:e.children,componentInfoObjects:t});e.variants.descendantVariantComponents=o;let l=[];for(let e of o){let n=t.allComponentClasses[e.componentType].determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t});if(!n.success)return{success:!1};l.push(n.numberOfVariants)}let u={numberOfVariantsByChild:l,numberToSelect:r,withReplacement:a};if(0===l.length)n=1;else if(a||1===r){let e=l.reduce(((e,t)=>e+t));n=Math.pow(e,r)}else{let e=l.length;if(r>e)return{success:!1};let t=l[0],a=l.slice(1).every((e=>e===t));if(a){let a=e;for(let t=e-1;t>e-r;t--)a*=t;n=a*Math.pow(t,r)}else n=countOptions(l,r)}return e.variants.numberOfVariants=n,e.variants.uniqueVariants=!0,e.variants.uniqueVariantData=u,{success:!0,numberOfVariants:n}}static getUniqueVariant({serializedComponent:e,variantIndex:t,componentInfoObjects:n}){let r=e.variants?.numberOfVariants;if(void 0===r)return{success:!1};if(!Number.isInteger(t)||t<1||t>r)return{success:!1};let a,i=e.variants.uniqueVariantData,s=i.numberOfVariantsByChild,o=i.numberToSelect,l=i.withReplacement,u=e.children.length,c=e.children;if(0===s.length)return{success:!0,desiredVariant:{indices:[]}};a=1===o?[...Array(u).keys()].map((e=>[e])):enumerateSelectionCombinations({numberOfIndices:o,numberOfOptions:u,withReplacement:l});let p,d,m=a.length,h=a.map((e=>({combination:e,numberOfPossibilities:e.reduce(((e,t)=>e*s[t]),1)}))),f=[...Array(m).keys()],y=0,g=f.length,b=t-1;for(;g>0;){let e=f.map((e=>h[e])).reduce(((e,t)=>Math.min(e,t.numberOfPossibilities)),1/0),t=e-y;if(bh[e].numberOfPossibilities>y)),g=f.length}let v=a[p],N=enumerateCombinations({numberOfOptionsByIndex:v.map((e=>s[e])),maxNumber:d})[d-1].map((e=>e+1)),T=[],C=!1;for(let[e,t]of v.entries())if(s[t]>1){let r=c[t],a=n.allComponentClasses[r.componentType].getUniqueVariant({serializedComponent:r,variantIndex:N[e],componentInfoObjects:n});if(!a.success)return{success:!1};T.push(a.desiredVariant),C=!0}else T.push({});let A={indices:v.map((e=>e+1))};return C&&(A.subvariants=T),{success:!0,desiredVariant:A}}}let countOptions=function(e,t){if(0===t)return 0;if(1===t)return e.reduce(((e,t)=>e+t));let n=0;for(let r in e){let a=e[r],i=[...e];i.splice(r,1),n+=a*countOptions(i,t-1)}return n};class AnimateFromSequence extends BaseComponent{constructor(e){super(e),Object.assign(this.actions,{changedAnimationOn:this.changedAnimationOn.bind(this),advanceAnimation:this.advanceAnimation.bind(this),startAnimation:this.startAnimation.bind(this),stopAnimation:this.stopAnimation.bind(this),toggleAnimation:this.toggleAnimation.bind(this)})}static componentType="animateFromSequence";static rendererType=void 0;static acceptTarget=!0;static createAttributesObject(){let e=super.createAttributesObject(),t=returnStandardSequenceAttributes();return Object.assign(e,t),e.prop={createPrimitiveOfType:"string"},e.componentIndex={createComponentOfType:"integer",createStateVariable:"componentIndex",defaultValue:null,public:!0},e.propIndex={createComponentOfType:"numberList",createStateVariable:"propIndex",defaultValue:null,public:!0},e.animationOn={createComponentOfType:"boolean",createStateVariable:"animationOn",defaultValue:!1,public:!0,triggerActionOnChange:"changedAnimationOn"},e.animationMode={createComponentOfType:"text",createStateVariable:"animationMode",defaultValue:"increase",validValues:["increase","decrease","increase once","decrease once","oscillate"],toLowerCase:!0,public:!0},e.animationInterval={createComponentOfType:"number",createStateVariable:"animationInterval",defaultValue:1e3,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnStandardSequenceStateVariableDefinitions();return Object.assign(e,t),e.possibleValues={additionalStateVariablesDefined:["numberValues"],returnDependencies:()=>({type:{dependencyType:"stateVariable",variableName:"type"},length:{dependencyType:"stateVariable",variableName:"length"},from:{dependencyType:"stateVariable",variableName:"from"},step:{dependencyType:"stateVariable",variableName:"step"},exclude:{dependencyType:"stateVariable",variableName:"exclude"},lowercase:{dependencyType:"stateVariable",variableName:"lowercase"}}),definition({dependencyValues:e}){let t=returnSequenceValues(e);return{setValue:{possibleValues:t,numberValues:t.length}}}},e.selectedIndex={public:!0,shadowingInstructions:{createComponentOfType:"number"},defaultValue:1,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{selectedIndex:!0}}),inverseDefinition:async({desiredStateVariableValues:e,stateValues:t})=>({success:!0,instructions:[{setEssentialValue:"selectedIndex",value:me$3.math.mod(e.selectedIndex-1,await t.numberValues)+1}]})},e.value={public:!0,shadowingInstructions:{hasVariableComponentType:!0},returnDependencies:()=>({possibleValues:{dependencyType:"stateVariable",variableName:"possibleValues"},selectedIndex:{dependencyType:"stateVariable",variableName:"selectedIndex"},type:{dependencyType:"stateVariable",variableName:"type"}}),definition:({dependencyValues:e})=>({setValue:{value:e.possibleValues[e.selectedIndex-1]},setCreateComponentOfType:{value:e.type}}),async inverseDefinition({desiredStateVariableValues:e,dependencyValues:t,stateValues:n}){if("number"===t.type){let r=e.value;if(r instanceof me$3.class&&(r=r.evaluate_to_constant()),!Number.isFinite(r))return{success:!1};let a=-1,i=t.possibleValues.length-1;for(;a0?i=e:a=e}let s=i;return-1!==a&&Math.abs(r-t.possibleValues[a])({animationMode:{dependencyType:"stateVariable",variableName:"animationMode"}}),definition:({dependencyValues:e})=>({useEssentialOrDefaultValue:{currentAnimationDirection:{get defaultValue(){return"decrease"===e.animationMode.substring(0,8)?"decrease":"increase"}}}}),inverseDefinition({desiredStateVariableValues:e}){let t=e.currentAnimationDirection.toLowerCase();return["increase","decrease"].includes(t)||(t="increase"),{success:!0,instructions:[{setEssentialValue:"currentAnimationDirection",value:t}]}}},e.target={returnDependencies:()=>({target:{dependencyType:"doenetAttribute",attributeName:"target"}}),definition:({dependencyValues:e})=>({setValue:{target:e.target}})},e.targetComponent={returnDependencies:()=>({targetComponent:{dependencyType:"targetComponent"}}),definition:function({dependencyValues:e}){let t=null;return e.targetComponent&&(t=e.targetComponent),{setValue:{targetComponent:t}}}},e.propName={returnDependencies:()=>({propName:{dependencyType:"attributePrimitive",attributeName:"prop"}}),definition:function({dependencyValues:e}){return{setValue:{propName:e.propName}}}},e.targetIdentities={stateVariablesDeterminingDependencies:["targetComponent","componentIndex"],returnDependencies:function({stateValues:e,componentInfoObjects:t}){let n={};return null!==e.targetComponent&&(t.isCompositeComponent({componentType:e.targetComponent.componentType,includeNonStandard:!1})?n.targets={dependencyType:"replacement",compositeName:e.targetComponent.componentName,recursive:!0,componentIndex:e.componentIndex}:null!==e.componentIndex&&1!==e.componentIndex||(n.targets={dependencyType:"stateVariable",variableName:"targetComponent"})),n},definition({dependencyValues:e}){let t=null;return e.targets&&(t=e.targets,Array.isArray(t)||(t=[t])),{setValue:{targetIdentities:t}}}},e.targets={stateVariablesDeterminingDependencies:["targetIdentities","propName","propIndex"],returnDependencies:function({stateValues:e}){let t={targetIdentities:{dependencyType:"stateVariable",variableName:"targetIdentities"}};if(null!==e.targetIdentities)for(let[n,r]of e.targetIdentities.entries()){let a;if(e.propName){let t=e.propIndex;t&&(t=[...t]),a={dependencyType:"stateVariable",componentName:r.componentName,variableName:e.propName,returnAsComponentObject:!0,variablesOptional:!0,propIndex:t,caseInsensitiveVariableMatch:!0,publicStateVariablesOnly:!0,useMappedVariableNames:!0}}else a={dependencyType:"stateVariable",componentName:r.componentName,variableName:"value",returnAsComponentObject:!0,variablesOptional:!0};t["target"+n]=a}return t},definition({dependencyValues:e}){let t=null;if(null!==e.targetIdentities){t=[];for(let n in e.targetIdentities)e["target"+n]&&t.push(e["target"+n])}return{setValue:{targets:t}}}},e.valueToIndex={returnDependencies:()=>({possibleValues:{dependencyType:"stateVariable",variableName:"possibleValues"}}),definition:function({dependencyValues:e}){let t={};for(let[n,r]of e.possibleValues.entries())t[r]=n;return{setValue:{valueToIndex:t}}}},e}async changedAnimationOn({stateValues:e,previousValues:t,actionId:n}){let r=[];if(e.animationOn)if(t.animationOn)this.coreFunctions.resolveAction({actionId:n});else{let e=await this.stateValues.currentAnimationDirection,t=await this.stateValues.animationMode,a=await this.stateValues.numberValues,i=await this.stateValues.selectedIndex,s=await this.findIndexFromTarget();"increase"===e?s===a&&("increase once"===t?s=1:"oscillate"===t&&(e="decrease",r.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"currentAnimationDirection",value:e}))):"decrease"===e&&1===s&&("decrease once"===t?s=a:"oscillate"===t&&(e="increase",r.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"currentAnimationDirection",value:e}))),s!==i&&r.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"selectedIndex",value:s});let o=await this.getUpdateInstructionsToSetTargetsToValue((await this.stateValues.possibleValues)[me$3.math.mod(s-1,a)]);r.push(...o),await this.coreFunctions.performUpdate({updateInstructions:r,actionId:n,event:{verb:"played",object:{componentName:this.componentName,componentType:this.componentType},context:{startIndex:s,animationDirection:e,animationMode:t}}}),await this.coreFunctions.triggerChainedActions({componentName:this.componentName}),this.animationId=nanoid(),await this.coreFunctions.requestAnimationFrame({action:{actionName:"advanceAnimation",componentName:this.componentName},delay:await this.stateValues.animationInterval,animationId:this.animationId,actionArgs:{previousAnimationId:this.animationId}})}else t.animationOn?(await this.coreFunctions.cancelAnimationFrame(this.animationId),this.canceledAnimationId=this.animationId,await this.coreFunctions.triggerChainedActions({componentName:this.componentName}),this.coreFunctions.requestRecordEvent({verb:"paused",object:{componentName:this.componentName,componentType:this.componentType},context:{endIndex:await this.stateValues.selectedIndex}})):this.coreFunctions.resolveAction({actionId:n})}async findIndexFromTarget(){let e=await this.stateValues.targets,t=await this.stateValues.selectedIndex;if(null===e)return t;let n,r=e[0];if(r?.stateValues&&(n=Object.keys(r.stateValues)[0]),!n)return t;let a=r.stateValues[n],i=await this.stateValues.type;if("number"===i&&a instanceof me$3.class&&(a=a.evaluate_to_constant(),!Number.isFinite(a)))return t;let s=(await this.stateValues.valueToIndex)[a];if(void 0!==s)return s+1;if("number"!==i)return t;let o=await this.stateValues.possibleValues,l=function(e=0,t=o.length-1){if(t<=e+1)return a>o[e]?t:e;let n=Math.round((t+e)/2);return a>o[n]?l(n,t):l(e,n)},u=l();if(0!==u){let e=o[u-1],t=o[u];Math.abs(a-e)=await this.stateValues.numberValues&&("increase once"===s?i=!1:"oscillate"===s&&(a="decrease")));let l=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"selectedIndex",value:n}],u=await this.getUpdateInstructionsToSetTargetsToValue((await this.stateValues.possibleValues)[me$3.math.mod(n-1,await this.stateValues.numberValues)]);l.push(...u),i||l.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"animationOn",value:!1}),a&&l.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"currentAnimationDirection",value:a}),await this.coreFunctions.performUpdate({updateInstructions:l,actionId:t}),i&&(this.animationId=nanoid(),await this.coreFunctions.requestAnimationFrame({action:{actionName:"advanceAnimation",componentName:this.componentName},delay:await this.stateValues.animationInterval,animationId:this.animationId,actionArgs:{previousAnimationId:this.animationId}}))}startAnimation({actionId:e}){this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"animationOn",value:!0}],actionId:e})}stopAnimation({actionId:e}){this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"animationOn",value:!1}],actionId:e})}async toggleAnimation({actionId:e}){this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"animationOn",value:!await this.stateValues.animationOn}],actionId:e})}async getUpdateInstructionsToSetTargetsToValue(e){let t=await this.stateValues.targets;if(null==t)return[];let n=[];for(let r of t){let t=Object.keys(r.stateValues)[0];void 0!==t?n.push({updateType:"updateValue",componentName:r.componentName,stateVariable:t,value:e}):await this.stateValues.propName?console.warn(`Cannot animate prop="${await this.stateValues.propName}" of ${await this.stateValues.target} as could not find prop ${await this.stateValues.propName} on a component of type ${r.componentType}`):console.warn(`Cannot animate ${await this.stateValues.target} as could not find a value state variable on a component of type ${r.componentType}`)}return n}}class Evaluate extends MathComponent{static componentType="evaluate";static rendererType="math";static createAttributesObject(){let e=super.createAttributesObject();return e.forceSymbolic={createComponentOfType:"boolean",createStateVariable:"forceSymbolic",defaultValue:!1,public:!0},e.forceNumeric={createComponentOfType:"boolean",createStateVariable:"forceNumeric",defaultValue:!1,public:!0},e.function={createComponentOfType:"function"},e.input={createComponentOfType:"mathList"},e.unordered={createComponentOfType:"boolean",createStateVariable:"unordered",defaultValue:!1,public:!0},e}static returnChildGroups(){return[]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return delete e.codePre,delete e.expressionWithCodes,delete e.mathChildrenFunctionSymbols,delete e.codesAdjacentToStrings,delete e.mathChildrenByVectorComponent,delete e.mathChildrenWithCanBeModified,delete e.unordered,e.canBeModified={returnDependencies:()=>({}),definition:()=>({setValue:{canBeModified:!1}})},e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},defaultValue:10,hasEssential:!0,returnDependencies:()=>({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},functionAttr:{dependencyType:"attributeComponent",attributeName:"function",variableNames:["displayDigits"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.displayDigitsAttr){let n=t.displayDigitsAttr,r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!n&&!r){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},functionAttr:{dependencyType:"attributeComponent",attributeName:"function",variableNames:["displayDecimals"]}}),definition:({dependencyValues:e,usedDefault:t})=>null!==e.displayDecimalsAttr?{setValue:{displayDecimals:e.displayDecimalsAttr.stateValues.value}}:e.functionAttr?t.functionAttr?{useEssentialOrDefaultValue:{displayDecimals:{defaultValue:e.functionAttr.stateValues.displayDecimals}}}:{setValue:{displayDecimals:e.functionAttr.stateValues.displayDecimals}}:{useEssentialOrDefaultValue:{displayDecimals:!0}}},e.displaySmallAsZero={public:!0,shadowingInstructions:{createComponentOfType:"number"},defaultValue:0,hasEssential:!0,returnDependencies:()=>({displaySmallAsZeroAttr:{dependencyType:"attributeComponent",attributeName:"displaySmallAsZero",variableNames:["value"]},functionAttr:{dependencyType:"attributeComponent",attributeName:"function",variableNames:["displaySmallAsZero"]}}),definition:({dependencyValues:e,usedDefault:t})=>null!==e.displaySmallAsZeroAttr?{setValue:{displaySmallAsZero:e.displaySmallAsZeroAttr.stateValues.value}}:e.functionAttr?t.functionAttr?{useEssentialOrDefaultValue:{displaySmallAsZero:{defaultValue:e.functionAttr.stateValues.displaySmallAsZero}}}:{setValue:{displaySmallAsZero:e.functionAttr.stateValues.displaySmallAsZero}}:{useEssentialOrDefaultValue:{displaySmallAsZero:!0}}},e.padZeros={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},defaultValue:!1,hasEssential:!0,returnDependencies:()=>({padZerosAttr:{dependencyType:"attributeComponent",attributeName:"padZeros",variableNames:["value"]},functionAttr:{dependencyType:"attributeComponent",attributeName:"function",variableNames:["padZeros"]}}),definition:({dependencyValues:e,usedDefault:t})=>null!==e.padZerosAttr?{setValue:{padZeros:e.padZerosAttr.stateValues.value}}:e.functionAttr?t.functionAttr?{useEssentialOrDefaultValue:{padZeros:{defaultValue:e.functionAttr.stateValues.padZeros}}}:{setValue:{padZeros:e.functionAttr.stateValues.padZeros}}:{useEssentialOrDefaultValue:{padZeros:!0}}},e.unnormalizedValue={public:!0,shadowingInstructions:{createComponentOfType:"math"},returnDependencies:()=>({inputAttr:{dependencyType:"attributeComponent",attributeName:"input",variableNames:["nComponents","maths"]},functionAttr:{dependencyType:"attributeComponent",attributeName:"function",variableNames:["symbolicfs","numericalfs","symbolic","nInputs","nOutputs"]},forceSymbolic:{dependencyType:"stateVariable",variableName:"forceSymbolic"},forceNumeric:{dependencyType:"stateVariable",variableName:"forceNumeric"}}),definition({dependencyValues:e}){if(!e.functionAttr||!e.inputAttr)return{setValue:{unnormalizedValue:me$3.fromAst("_")}};let t=e.inputAttr.stateValues.maths;if(1===t.length){let e=t[0].tree;Array.isArray(e)&&vectorOperators.includes(e[0])&&(t=e.slice(1).map((e=>me$3.fromAst(e))))}if(t.length!==e.functionAttr.stateValues.nInputs)return{setValue:{unnormalizedValue:me$3.fromAst("_")}};let n,r=[],a=e.functionAttr,i=a.stateValues.nOutputs;if(e.forceNumeric||!a.stateValues.symbolic&&!e.forceSymbolic){let e=t.map((e=>e.evaluate_to_constant())).map((e=>null===e?NaN:e));for(let t=0;t=0&&Number.isFinite(r))){let e="Invalid mean ("+r+") or standard deviation ("+n+") for a gaussian random variable.";return console.warn(e),Array(t).fill(NaN)}let e=[];for(let a=0;a0)for(let n=0;n({type:{dependencyType:"stateVariable",variableName:"type"},specifiedStep:{dependencyType:"stateVariable",variableName:"specifiedStep"}}),definition({dependencyValues:e}){let t;return t="discreteuniform"===e.type?e.specifiedStep:null,{setValue:{step:t}}}},e.from={public:!0,shadowingInstructions:{createComponentOfType:"number"},additionalStateVariablesDefined:[{variableName:"to",public:!0,shadowingInstructions:{createComponentOfType:"number"}},{variableName:"nDiscreteValues"}],returnDependencies:()=>({type:{dependencyType:"stateVariable",variableName:"type"},specifiedFrom:{dependencyType:"stateVariable",variableName:"specifiedFrom"},specifiedTo:{dependencyType:"stateVariable",variableName:"specifiedTo"},step:{dependencyType:"stateVariable",variableName:"step"}}),definition({dependencyValues:e}){if(!["discreteuniform","uniform"].includes(e.type))return{setValue:{from:null,to:null,nDiscreteValues:null}};let t=e.step,n=e.specifiedFrom,r=e.specifiedTo,a=null;if(null===r)null===n&&(n=0),"uniform"===e.type?r=n+1:(r=n+t,a=2);else if(null===n)if("uniform"===e.type)n=0;else{let e=0;a=Math.floor((r-e)/t+1),a<1?(a=0,n=null):n=r-(a-1)*t}else"discreteuniform"===e.type&&(a=Math.floor((r-n)/t+1),a<1?a=0:r=n+(a-1)*t);return{setValue:{from:n,to:r,nDiscreteValues:a}}}},e.mean={stateVariablesDeterminingDependencies:["type"],public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies({stateValues:e}){let t={type:{dependencyType:"stateVariable",variableName:"type"}};return"gaussian"===e.type?t.specifiedMean={dependencyType:"stateVariable",variableName:"specifiedMean"}:(t.from={dependencyType:"stateVariable",variableName:"from"},t.to={dependencyType:"stateVariable",variableName:"to"}),t},definition({dependencyValues:e}){let t;return t="gaussian"===e.type?e.specifiedMean:(e.from+e.to)/2,{setValue:{mean:t}}}},e.variance={stateVariablesDeterminingDependencies:["type"],public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies({stateValues:e}){let t={type:{dependencyType:"stateVariable",variableName:"type"}};return"gaussian"===e.type?(t.specifiedVariance={dependencyType:"stateVariable",variableName:"specifiedVariance"},t.specifiedStandardDeviation={dependencyType:"stateVariable",variableName:"specifiedStandardDeviation"}):(t.from={dependencyType:"stateVariable",variableName:"from"},t.to={dependencyType:"stateVariable",variableName:"to"},"discreteuniform"===e.type&&(t.step={dependencyType:"stateVariable",variableName:"step"},t.nDiscreteValues={dependencyType:"stateVariable",variableName:"nDiscreteValues"})),t},definition({dependencyValues:e,usedDefault:t}){let n;return n="gaussian"===e.type?t.specifiedVariance&&!t.specifiedStandardDeviation?e.specifiedStandardDeviation**2:e.specifiedVariance:"discreteuniform"===e.type?(e.nDiscreteValues**2-1)*e.step**2/12:(e.to-e.from)**2/12,{setValue:{variance:n}}}},e.standardDeviation={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({variance:{dependencyType:"stateVariable",variableName:"variance"}}),definition:({dependencyValues:e})=>({setValue:{standardDeviation:Math.sqrt(e.variance)}})},e.sampledValues={shadowVariable:!0,hasEssential:!0,stateVariablesDeterminingDependencies:["variantDeterminesSeed"],returnDependencies({stateValues:e,sharedParameters:t}){let n={numberOfSamples:{dependencyType:"stateVariable",variableName:"numberOfSamples"},type:{dependencyType:"stateVariable",variableName:"type"},from:{dependencyType:"stateVariable",variableName:"from"},to:{dependencyType:"stateVariable",variableName:"to"},step:{dependencyType:"stateVariable",variableName:"step"},nDiscreteValues:{dependencyType:"stateVariable",variableName:"nDiscreteValues"},mean:{dependencyType:"stateVariable",variableName:"mean"},standardDeviation:{dependencyType:"stateVariable",variableName:"standardDeviation"}};return e.variantDeterminesSeed?n.rng={dependencyType:"value",value:t.variantRng,doNotProxy:!0}:n.rng={dependencyType:"value",value:t.rngWithDateSeed,doNotProxy:!0},n},definition({dependencyValues:e}){if(e.numberOfSamples<1)return{setEssentialValue:{sampledValues:[]},setValue:{sampledValues:[]}};let t=sampleFromRandomNumbers(e);return{setEssentialValue:{sampledValues:t},setValue:{sampledValues:t}}},inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"sampledValues",value:e.sampledValues}]})},e.readyToExpandWhenResolved={returnDependencies:()=>({sampledValues:{dependencyType:"stateVariable",variableName:"sampledValues"}}),markStale:()=>({updateReplacements:!0}),definition:function(){return{setValue:{readyToExpandWhenResolved:!0}}}},e.isVariantComponent={returnDependencies:()=>({}),definition:()=>({setValue:{isVariantComponent:!0}})},e.generatedVariantInfo={returnDependencies:({sharedParameters:e})=>({variantSeed:{dependencyType:"value",value:e.variantSeed}}),definition:({dependencyValues:e,componentName:t})=>({setValue:{generatedVariantInfo:{seed:e.variantSeed,meta:{createdBy:t}}}})},e}static async createSerializedReplacements({component:e,componentInfoObjects:t,startNum:n=0,flags:r}){let a=e.attributes.newNamespace?.primitive,i={};for(let t of["displayDigits","displaySmallAsZero","displayDecimals","padZeros"])t in e.attributes&&(i[t]=e.attributes[t]);let s=[];for(let o of(await e.stateValues.sampledValues).slice(n)){let e={};Object.keys(i).length>0&&(e=convertAttributesForComponentType({attributes:i,componentType:"number",componentInfoObjects:t,compositeCreatesNewNamespace:a,flags:r})),s.push({componentType:"number",attributes:e,state:{value:o}})}return{replacements:processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:s,parentName:e.componentName,parentCreatesNewNamespace:a,indOffset:n,componentInfoObjects:t}).serializedComponents}}static async calculateReplacementChanges({component:e,componentInfoObjects:t,flags:n}){let r=[],a=await e.stateValues.sampledValues;if(a.length0){let e={changeType:"changeReplacementsToWithhold",replacementsToWithhold:0};r.push(e)}if(a.length>e.replacements.length){let a=await this.createSerializedReplacements({component:e,componentInfoObjects:t,startNum:e.replacements.length,flags:n}),i={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:e.replacements.length,numberReplacementsToReplace:0,serializedReplacements:a.replacements,assignNamesOffset:e.replacements.length};r.push(i)}}let i=Math.min(e.replacements.length,a.length);for(let t=0;t({variants:{dependencyType:"variants"}}),definition:function({dependencyValues:e}){return{setValue:{variants:e.variants}}}},e.step.immutable=!0,e.from.immutable=!0,e.from.additionalStateVariablesDefined[0].immutable=!0,e.from.additionalStateVariablesDefined[1].immutable=!0,e.mean.immutable=!0,e.variance.immutable=!0,e.standardDeviation.immutable=!0,delete e.sampledValues,e.selectedValues={immutable:!0,hasEssential:!0,shadowVariable:!0,returnDependencies:({sharedParameters:e})=>({numberOfSamples:{dependencyType:"stateVariable",variableName:"numberToSelect"},type:{dependencyType:"stateVariable",variableName:"type"},from:{dependencyType:"stateVariable",variableName:"from"},to:{dependencyType:"stateVariable",variableName:"to"},step:{dependencyType:"stateVariable",variableName:"step"},nDiscreteValues:{dependencyType:"stateVariable",variableName:"nDiscreteValues"},mean:{dependencyType:"stateVariable",variableName:"mean"},standardDeviation:{dependencyType:"stateVariable",variableName:"standardDeviation"},variants:{dependencyType:"stateVariable",variableName:"variants"},rng:{dependencyType:"value",value:e.variantRng,doNotProxy:!0}}),definition({dependencyValues:e}){if(e.numberOfSamples<1)return{setEssentialValue:{selectedValues:[]},setValue:{selectedValues:[]}};if(e.variants&&e.variants.desiredVariant){let t=e.variants.desiredVariant.values;if(t){if(t.length!==e.numberOfSamples)throw Error("Number of values specified for selectRandomNumber must match number to select");return{setEssentialValue:{selectedValues:t},setValue:{selectedValues:t}}}}let t=sampleFromRandomNumbers(e);return{setEssentialValue:{selectedValues:t},setValue:{selectedValues:t}}}},e.isVariantComponent={returnDependencies:()=>({}),definition:()=>({setValue:{isVariantComponent:!0}})},e.generatedVariantInfo={returnDependencies:()=>({selectedValues:{dependencyType:"stateVariable",variableName:"selectedValues"}}),definition:({dependencyValues:e,componentName:t})=>({setValue:{generatedVariantInfo:{values:e.selectedValues,meta:{createdBy:t}}}})},e.readyToExpandWhenResolved={returnDependencies:()=>({selectedValues:{dependencyType:"stateVariable",variableName:"selectedValues"}}),definition:function(){return{setValue:{readyToExpandWhenResolved:!0}}}},e}static async createSerializedReplacements({component:e,componentInfoObjects:t,flags:n}){let r=e.attributes.newNamespace?.primitive,a={};for(let t of["displayDigits","displaySmallAsZero","displayDecimals","padZeros"])t in e.attributes&&(a[t]=e.attributes[t]);let i=[];for(let s of await e.stateValues.selectedValues){let e={};Object.keys(a).length>0&&(e=convertAttributesForComponentType({attributes:a,componentType:"number",componentInfoObjects:t,compositeCreatesNewNamespace:r,flags:n})),i.push({componentType:"number",attributes:e,state:{value:s}})}return{replacements:processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:i,parentName:e.componentName,parentCreatesNewNamespace:r,componentInfoObjects:t}).serializedComponents}}}delete SelectRandomNumbers.stateVariableToEvaluateAfterReplacements,delete SelectRandomNumbers.calculateReplacementChanges;class Substitute extends CompositeComponent{static componentType="substitute";static assignNamesToReplacements=!0;static stateVariableToEvaluateAfterReplacements="readyToExpandWhenResolved";static createAttributesObject(){let e=super.createAttributesObject();return e.assignNamesSkip={createPrimitiveOfType:"number"},e.type={createPrimitiveOfType:"string",createStateVariable:"type",defaultPrimitiveValue:"math",toLowerCase:!0,validValues:["math","text"],public:!0},e.match={createComponentOfType:"_componentWithSelectableType",createStateVariable:"match",defaultValue:null},e.replacement={createComponentOfType:"_componentWithSelectableType",createStateVariable:"replacement",defaultValue:null},e.simplify={createComponentOfType:"text",createStateVariable:"simplify",defaultValue:"none",public:!0,toLowerCase:!0,valueTransformations:{true:"full"},validValues:["none","full","numbers","numberspreserveorder"]},e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer"},e.displaySmallAsZero={createComponentOfType:"number",valueForTrue:1e-14,valueForFalse:0},e.padZeros={createComponentOfType:"boolean"},e.matchWholeWord={createComponentOfType:"boolean",createStateVariable:"matchWholeWord",defaultValue:!1,public:!0},e.matchCase={createComponentOfType:"boolean",createStateVariable:"matchCase",defaultValue:!1,public:!0},e.preserveCase={createComponentOfType:"boolean",createStateVariable:"preserveCase",defaultValue:!1,public:!0},e}static returnSugarInstructions(){let e=[];return e.push({replacementFunction:function({matchedChildren:e,componentAttributes:t}){let n=t.type;return["math","text"].includes(n)||(n="math"),{success:!0,newChildren:[{componentType:n,children:e}]}}}),e}static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({type:{dependencyType:"stateVariable",variableName:"type"},displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},child:{dependencyType:"child",childGroups:["anything"],variableNames:["displayDigits"],variablesOptional:!0}}),definition({dependencyValues:e,usedDefault:t}){if("math"!==e.type)return{setValue:{displayDigits:null}};if(null!==e.displayDigitsAttr){let n=t.displayDigitsAttr,r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!n&&!r){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({type:{dependencyType:"stateVariable",variableName:"type"},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},child:{dependencyType:"child",childGroups:["anything"],variableNames:["displayDecimals"],variablesOptional:!0}}),definition:({dependencyValues:e,usedDefault:t})=>"math"!==e.type?{setValue:{displayDecimals:null}}:null===e.displayDecimalsAttr||t.displayDecimalsAttr?1!==e.child.length||t.child[0]&&t.child[0].displayDecimals?{useEssentialOrDefaultValue:{displayDecimals:!0}}:{setValue:{displayDecimals:e.child[0].stateValues.displayDecimals}}:{setValue:{displayDecimals:e.displayDecimalsAttr.stateValues.value}}},e.displaySmallAsZero={public:!0,shadowingInstructions:{createComponentOfType:"number"},hasEssential:!0,defaultValue:0,returnDependencies:()=>({type:{dependencyType:"stateVariable",variableName:"type"},displaySmallAsZeroAttr:{dependencyType:"attributeComponent",attributeName:"displaySmallAsZero",variableNames:["value"]},child:{dependencyType:"child",childGroups:["anything"],variableNames:["displaySmallAsZero"],variablesOptional:!0}}),definition:({dependencyValues:e,usedDefault:t})=>"math"!==e.type?{setValue:{displaySmallAsZero:null}}:null===e.displaySmallAsZeroAttr||t.displaySmallAsZeroAttr?1!==e.child.length||t.child[0]&&t.child[0].displaySmallAsZero?{useEssentialOrDefaultValue:{displaySmallAsZero:!0}}:{setValue:{displaySmallAsZero:e.child[0].stateValues.displaySmallAsZero}}:{setValue:{displaySmallAsZero:e.displaySmallAsZeroAttr.stateValues.value}}},e.padZeros={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},hasEssential:!0,defaultValue:!1,returnDependencies:()=>({type:{dependencyType:"stateVariable",variableName:"type"},padZerosAttr:{dependencyType:"attributeComponent",attributeName:"padZeros",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},child:{dependencyType:"child",childGroups:["anything"],variableNames:["padZeros"],variablesOptional:!0}}),definition:({dependencyValues:e,usedDefault:t})=>"math"!==e.type?{setValue:{padZeros:null}}:null===e.padZerosAttr||t.padZerosAttr?1!==e.child.length||t.child[0]&&t.child[0].padZeros?{useEssentialOrDefaultValue:{padZeros:!0}}:{setValue:{padZeros:e.child[0].stateValues.padZeros}}:{setValue:{padZeros:e.padZerosAttr.stateValues.value}}},e.originalValue={returnDependencies:()=>({child:{dependencyType:"child",childGroups:["anything"],variableNames:["value"]}}),definition:({dependencyValues:e})=>e.child.length>0?{setValue:{originalValue:e.child[0].stateValues.value}}:{setValue:{originalValue:null}},inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t})=>t.child.length>0?{success:!0,instructions:[{setDependency:"child",desiredValue:e.originalValue,childIndex:0,variableIndex:0}]}:{success:!1}},e.value={returnDependencies:()=>({type:{dependencyType:"stateVariable",variableName:"type"},originalValue:{dependencyType:"stateVariable",variableName:"originalValue"},match:{dependencyType:"stateVariable",variableName:"match"},replacement:{dependencyType:"stateVariable",variableName:"replacement"},simplify:{dependencyType:"stateVariable",variableName:"simplify"},matchWholeWord:{dependencyType:"stateVariable",variableName:"matchWholeWord"},matchCase:{dependencyType:"stateVariable",variableName:"matchCase"},preserveCase:{dependencyType:"stateVariable",variableName:"preserveCase"}}),definition({dependencyValues:e}){if(null===e.originalValue)return{setValue:{value:null}};if(null===e.match||null===e.replacement)return{setValue:{value:e.originalValue}};if("text"===e.type){let t,n=e.originalValue,r="g";e.matchCase||(r="gi"),t=e.matchWholeWord?new RegExp("\\b"+escapeRegExp(e.match)+"\\b",r):new RegExp(escapeRegExp(e.match),r);let a=e.replacement;if(e.preserveCase){let e=returnPreserveCaseReplacer(a);n=n.replace(t,e)}else n=n.replace(t,a);return{setValue:{value:n}}}{let t=e.originalValue.subscripts_to_strings();return t=t.substitute({[e.match.subscripts_to_strings().tree]:e.replacement.subscripts_to_strings()}),t=t.strings_to_subscripts(),t=normalizeMathExpression({value:t,simplify:e.simplify}),{setValue:{value:t}}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){if("text"===t.type){let n,r,a=e.value,i="g";t.matchCase||(i="gi");let s=t.match,o=t.replacement;if(t.matchWholeWord)if(n=new RegExp("\\b"+escapeRegExp(s)+"\\b",i),t.matchCase&&t.preserveCase){let e=returnPreserveCaseReplacer(o);r=new RegExp("\\b"+escapeRegExp(e(s))+"\\b",i)}else r=new RegExp("\\b"+escapeRegExp(o)+"\\b",i);else if(n=new RegExp(escapeRegExp(s),i),t.matchCase&&t.preserveCase){let e=returnPreserveCaseReplacer(o);r=new RegExp(escapeRegExp(e(s)),i)}else r=new RegExp(escapeRegExp(o),i);return-1!==t.originalValue.search(r)||-1!==a.search(n)?{success:!1}:(a=a.replace(r,s),{success:!0,instructions:[{setDependency:"originalValue",desiredValue:a}]})}{let n=e.value.subscripts_to_strings(),r=t.match.subscripts_to_strings(),a=t.replacement.subscripts_to_strings();return"string"!=typeof r.tree||"string"!=typeof a.tree||(t.originalValue.variables(!0).includes(a.tree)||n.variables().includes(r.tree))?{success:!1}:(n=n.substitute({[a.tree]:r}),n=n.strings_to_subscripts(),{success:!0,instructions:[{setDependency:"originalValue",desiredValue:n}]})}}},e.readyToExpandWhenResolved={returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),markStale:()=>({updateReplacements:!0}),definition:function(){return{setValue:{readyToExpandWhenResolved:!0}}}},e}static async createSerializedReplacements({component:e,componentInfoObjects:t,flags:n}){let r=e.attributes.newNamespace?.primitive,a=await e.stateValues.type,i={componentType:a,state:{value:await e.stateValues.value},downstreamDependencies:{[e.componentName]:[{dependencyType:"referenceShadow",compositeName:e.componentName,propVariable:"value"}]}};if("math"===a){let t={},n={displayDigits:"integer",displayDecimals:"integer",displaySmallAsZero:"number",padZeros:"boolean"};for(let r in n){let a={componentType:n[r],downstreamDependencies:{[e.componentName]:[{compositeName:e.componentName,dependencyType:"referenceShadow",propVariable:r}]}};t[r]={component:a}}i.attributes=t}return{replacements:processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:[i],parentName:e.componentName,parentCreatesNewNamespace:r,componentInfoObjects:t}).serializedComponents}}}function escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function returnPreserveCaseReplacer(e){return function(t){return t.toUpperCase()===t?e.toUpperCase():t.toLowerCase()===t?e.toLowerCase():t[0].match(/[a-z]/)?e[0].toLowerCase()+e.substring(1):t[0].match(/[A-Z]/)?e[0].toUpperCase()+e.substring(1):e}}class PeriodicSet extends MathComponent{static componentType="periodicSet";static rendererType=void 0;static createAttributesObject(){let e=super.createAttributesObject();return e.minIndex={createComponentOfType:"integer",createStateVariable:"minIndex",defaultValue:-1/0,public:!0},e.maxIndex={createComponentOfType:"integer",createStateVariable:"maxIndex",defaultValue:1/0,public:!0},e.offsets={createComponentOfType:"mathList",createStateVariable:"offsets",defaultValue:null,public:!0},e.period={createComponentOfType:"math",createStateVariable:"period",defaultValue:null,public:!0},e.minIndexAsList={createComponentOfType:"integer",createStateVariable:"minIndexAsList",defaultValue:-1,public:!0},e.maxIndexAsList={createComponentOfType:"integer",createStateVariable:"maxIndexAsList",defaultValue:1,public:!0},e}static returnChildGroups(){return[]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return delete e.codePre,delete e.expressionWithCodes,delete e.mathChildrenFunctionSymbols,delete e.codesAdjacentToStrings,delete e.mathChildrenByVectorComponent,delete e.mathChildrenWithCanBeModified,delete e.unordered,e.canBeModified={returnDependencies:()=>({}),definition:()=>({setValue:{canBeModified:!1}})},e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({mathListParentDisplayDigits:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"displayDigits"},numberListParentDisplayDigits:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"displayDigits"},mathListParentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"displayDecimals"},numberListParentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"displayDecimals"},displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){let n,r=!1;if(null!==e.mathListParentDisplayDigits){if(!t.mathListParentDisplayDigits)return{setValue:{displayDigits:e.mathListParentDisplayDigits}};r=!0,n=e.mathListParentDisplayDigits}if(null!==e.numberListParentDisplayDigits){if(!t.numberListParentDisplayDigits)return{setValue:{displayDigits:e.numberListParentDisplayDigits}};r=!0,n=e.numberListParentDisplayDigits}if(!(null!==e.numberListParentDisplayDecimals&&!t.numberListParentDisplayDecimals||null!==e.mathListParentDisplayDecimals&&!t.mathListParentDisplayDecimals)&&null!==e.displayDigitsAttr){if(!t.displayDigitsAttr)return{setValue:{displayDigits:e.displayDigitsAttr.stateValues.value}};r=!0,n=e.displayDigitsAttr.stateValues.value}return r?{useEssentialOrDefaultValue:{displayDigits:{defaultValue:n}}}:{useEssentialOrDefaultValue:{displayDigits:!0}}}},e.displayDecimals={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:null,returnDependencies:()=>({mathListParentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"displayDecimals"},numberListParentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"displayDecimals"},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){let n,r=!1;if(null!==e.mathListParentDisplayDecimals){if(!t.mathListParentDisplayDecimals)return{setValue:{displayDecimals:e.mathListParentDisplayDecimals}};r=!0,n=e.mathListParentDisplayDecimals}if(null!==e.numberListParentDisplayDecimals){if(!t.numberListParentDisplayDecimals)return{setValue:{displayDecimals:e.numberListParentDisplayDecimals}};r=!0,n=e.numberListParentDisplayDecimals}if(null!==e.displayDecimalsAttr){if(!t.displayDecimalsAttr)return{setValue:{displayDecimals:e.displayDecimalsAttr.stateValues.value}};r=!0,n=e.displayDecimalsAttr.stateValues.value}return r?{useEssentialOrDefaultValue:{displayDecimals:{defaultValue:n}}}:{useEssentialOrDefaultValue:{displayDecimals:!0}}}},e.displaySmallAsZero={public:!0,shadowingInstructions:{createComponentOfType:"number"},hasEssential:!0,defaultValue:0,returnDependencies:()=>({mathListParentDisplaySmallAsZero:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"displaySmallAsZero"},numberListParentDisplaySmallAsZero:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"displaySmallAsZero"},displaySmallAsZeroAttr:{dependencyType:"attributeComponent",attributeName:"displaySmallAsZero",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){let n,r=!1;if(null!==e.mathListParentDisplaySmallAsZero){if(!t.mathListParentDisplaySmallAsZero)return{setValue:{displaySmallAsZero:e.mathListParentDisplaySmallAsZero}};r=!0,n=e.mathListParentDisplaySmallAsZero}if(null!==e.numberListParentDisplaySmallAsZero){if(!t.numberListParentDisplaySmallAsZero)return{setValue:{displaySmallAsZero:e.numberListParentDisplaySmallAsZero}};r=!0,n=e.numberListParentDisplaySmallAsZero}if(null!==e.displaySmallAsZeroAttr){if(!t.displaySmallAsZeroAttr)return{setValue:{displaySmallAsZero:e.displaySmallAsZeroAttr.stateValues.value}};r=!0,n=e.displaySmallAsZeroAttr.stateValues.value}return r?{useEssentialOrDefaultValue:{displaySmallAsZero:{defaultValue:n}}}:{useEssentialOrDefaultValue:{displaySmallAsZero:!0}}}},e.padZeros={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},hasEssential:!0,defaultValue:!1,returnDependencies:()=>({mathListParentPadZeros:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"padZeros"},numberListParentPadZeros:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"padZeros"},padZerosAttr:{dependencyType:"attributeComponent",attributeName:"padZeros",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){let n,r=!1;if(null!==e.mathListParentPadZeros){if(!t.mathListParentPadZeros)return{setValue:{padZeros:e.mathListParentPadZeros}};r=!0,n=e.mathListParentPadZeros}if(null!==e.numberListParentPadZeros){if(!t.numberListParentPadZeros)return{setValue:{padZeros:e.numberListParentPadZeros}};r=!0,n=e.numberListParentPadZeros}if(null!==e.padZerosAttr){if(!t.padZerosAttr)return{setValue:{padZeros:e.padZerosAttr.stateValues.value}};r=!0,n=e.padZerosAttr.stateValues.value}return r?{useEssentialOrDefaultValue:{padZeros:{defaultValue:n}}}:{useEssentialOrDefaultValue:{padZeros:!0}}}},e.nOffsets={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({offsets:{dependencyType:"stateVariable",variableName:"offsets"}}),definition({dependencyValues:e}){let t=0;return null!==e.offsets&&(t=e.offsets.length),{setValue:{nOffsets:t}}}},e.unnormalizedValue={returnDependencies:()=>({offsets:{dependencyType:"stateVariable",variableName:"offsets"},period:{dependencyType:"stateVariable",variableName:"period"},minIndex:{dependencyType:"stateVariable",variableName:"minIndex"},maxIndex:{dependencyType:"stateVariable",variableName:"maxIndex"}}),definition({dependencyValues:e}){if(null===e.offsets||0===e.offsets.length||1===e.offsets.length&&"_"===e.offsets[0].tree||null===e.period||"_"===e.period.tree)return{setValue:{unnormalizedValue:me$3.fromAst("_")}};let t=[],n=e.period.tree,r=e.minIndex,a=e.maxIndex;for(let i of e.offsets)t.push(["tuple",i.tree,n,r,a]);return{setValue:{unnormalizedValue:me$3.fromAst(["periodic_set",...t])}}}},e.redundantOffsets={additionalStateVariablesDefined:["uniqueOffsets"],public:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({nOffsets:{dependencyType:"stateVariable",variableName:"nOffsets"},offsets:{dependencyType:"stateVariable",variableName:"offsets"},period:{dependencyType:"stateVariable",variableName:"period"}}),definition({dependencyValues:e}){let t=!1,n=[];if(null!==e.period){let r=e.period.evaluate_to_constant();if(null!==r)for(let a=0;a({uniqueOffsets:{dependencyType:"stateVariable",variableName:"uniqueOffsets"},period:{dependencyType:"stateVariable",variableName:"period"},minIndexAsList:{dependencyType:"stateVariable",variableName:"minIndexAsList"},maxIndexAsList:{dependencyType:"stateVariable",variableName:"maxIndexAsList"}}),definition({dependencyValues:e}){let t=[];if(null!==e.period){let n=e.period.evaluate_to_constant();if(null!==n){let r=e.period.simplify(),a=!0,i=[];for(let t of e.uniqueOffsets){let e=t.evaluate_to_constant();if(null===e){a=!1;break}{let a=t.subtract(r.multiply(Math.floor(e/n))).simplify(),s=a.evaluate_to_constant();i.push({num:s,offset:a})}}if(a){t.push(me$3.fromAst(["ldots"])),i.sort(((e,t)=>e.num-t.num));let n=-1,a=1;Number.isFinite(e.minIndexAsList)&&(n=e.minIndexAsList),Number.isFinite(e.maxIndexAsList)&&(a=e.maxIndexAsList);for(let e=n;e<=a;e++)for(let n of i)t.push(n.offset.add(r.multiply(e)).simplify());t.push(me$3.fromAst(["ldots"]))}}}return{setValue:{asList:t}}}},e}}class Image extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{moveImage:this.moveImage.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="image";static createAttributesObject(){let e=super.createAttributesObject();return e.width={createComponentOfType:"_componentSize",createStateVariable:"specifiedWidth",defaultValue:null},e.size={createComponentOfType:"text",createStateVariable:"specifiedSize",defaultValue:"medium",toLowerCase:!0,validValues:sizePossibilities},e.aspectRatio={createComponentOfType:"number"},e.height={createComponentOfType:"_componentSize"},e.displayMode={createComponentOfType:"text",createStateVariable:"displayMode",validValues:["block","inline"],defaultValue:"block",forRenderer:!0,public:!0},e.horizontalAlign={createComponentOfType:"text",createStateVariable:"horizontalAlign",toLowerCase:!0,validValues:["center","left","right"],defaultValue:"center",forRenderer:!0,public:!0},e.description={createComponentOfType:"text",createStateVariable:"description",defaultValue:"",public:!0,forRenderer:!0},e.source={createComponentOfType:"text",createStateVariable:"source",defaultValue:"",public:!0,forRenderer:!0},e.asFileName={createComponentOfType:"text",createStateVariable:"asFileName",defaultValue:null,public:!0,forRenderer:!0},e.mimeType={createComponentOfType:"text",createStateVariable:"mimeType",defaultValue:null,public:!0,forRenderer:!0},e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.layer={createComponentOfType:"number",createStateVariable:"layer",defaultValue:0,public:!0,forRenderer:!0},e.anchor={createComponentOfType:"point"},e.positionFromAnchor={createComponentOfType:"text",createStateVariable:"positionFromAnchor",defaultValue:"center",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft","top","bottom","left","right","center"]},e.rotate={createComponentOfType:"number",createStateVariable:"rotate",defaultValue:0,public:!0,forRenderer:!0},e.styleNumber.defaultValue=0,e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnSelectedStyleStateVariableDefinition();return Object.assign(e,t),e.size={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({specifiedSize:{dependencyType:"stateVariable",variableName:"specifiedSize"},specifiedWidth:{dependencyType:"stateVariable",variableName:"specifiedWidth"},graphAncestor:{dependencyType:"ancestor",componentType:"graph",variableNames:["xscale"]}}),definition({dependencyValues:e,usedDefault:t}){const n="medium";if(t.specifiedSize){if(t.specifiedWidth)return{setValue:{size:n}};{let t=e.specifiedWidth;if(null===t)return{setValue:{size:n}};let r,{isAbsolute:a,size:i}=t;if(a){let t;if(e.graphAncestor){let n=e.graphAncestor.stateValues.xscale;t=orderedPercentWidthMidpoints.map((e=>e/100*n))}else t=orderedWidthMidpoints;for(let[e,n]of t.entries())if(i<=n){r=sizePossibilities[e];break}r||(r=n)}else{for(let[e,t]of orderedPercentWidthMidpoints.entries())if(i<=t){r=sizePossibilities[e];break}r||(r=n)}return{setValue:{size:r}}}}return{setValue:{size:e.specifiedSize}}},inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setDependency:"specifiedSize",desiredValue:e.size}]})},e.width={public:!0,forRenderer:!0,shadowingInstructions:{createComponentOfType:"_componentSize"},returnDependencies:()=>({specifiedSize:{dependencyType:"stateVariable",variableName:"specifiedSize"},size:{dependencyType:"stateVariable",variableName:"size"},specifiedWidth:{dependencyType:"stateVariable",variableName:"specifiedWidth"},graphAncestor:{dependencyType:"ancestor",componentType:"graph",variableNames:["xscale"]}}),definition({dependencyValues:e,usedDefault:t}){if(e.graphAncestor){if(e.graphAncestor.stateValues.xscale,t.specifiedSize){if(t.specifiedWidth)return{setValue:{width:{isAbsolute:!1,size:percentWidthsBySize.medium}}};{let t,n=e.specifiedWidth;return t=n||{isAbsolute:!1,size:percentWidthsBySize.medium},{setValue:{width:t}}}}return{setValue:{width:{isAbsolute:!1,size:percentWidthsBySize[e.size]}}}}return{setValue:{width:{isAbsolute:!0,size:widthsBySize[e.size]}}}},inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setDependency:"specifiedWidth",desiredValue:e.width}]})},e.widthForGraph={forRenderer:!0,returnDependencies:()=>({width:{dependencyType:"stateVariable",variableName:"width"},graphAncestor:{dependencyType:"ancestor",componentType:"graph",variableNames:["xscale"]}}),definition({dependencyValues:e}){let t=e.width;return e.graphAncestor&&!t.isAbsolute&&(t={isAbsolute:!0,size:t.size/100*e.graphAncestor.stateValues.xscale}),{setValue:{widthForGraph:t}}}},e.aspectRatio={public:!0,forRenderer:!0,hasEssential:!0,defaultValue:null,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({aspectRatioAttr:{dependencyType:"attributeComponent",attributeName:"aspectRatio",variableNames:["value"]}}),definition({dependencyValues:e}){if(null!==e.aspectRatioAttr){let t=e.aspectRatioAttr.stateValues.value;return Number.isFinite(t)||(t=null),{setValue:{aspectRatio:t}}}return{useEssentialOrDefaultValue:{aspectRatio:!0}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){if(null!==t.aspectRatioAttr)return{success:!0,instructions:[{setDependency:"aspectRatioAttr",desiredValue:e.aspectRatio,variableIndex:0}]};{let t=e.aspectRatio;return t>0||(t=null),{success:!0,instructions:[{setEssentialValue:"aspectRatio",value:t}]}}}},e.cid={forRenderer:!0,returnDependencies:()=>({source:{dependencyType:"stateVariable",variableName:"source"}}),definition:function({dependencyValues:e}){if(!e.source||"doenet:"!==e.source.substring(0,7).toLowerCase())return{setValue:{cid:null}};let t=null,n=e.source.match(/[:&]cid=([^&]+)/i);return n&&(t=n[1]),{setValue:{cid:t}}}},e.anchor={defaultValue:me$3.fromText("(0,0)"),public:!0,forRenderer:!0,hasEssential:!0,shadowingInstructions:{createComponentOfType:"point"},returnDependencies:()=>({anchorAttr:{dependencyType:"attributeComponent",attributeName:"anchor",variableNames:["coords"]}}),definition:({dependencyValues:e})=>e.anchorAttr?{setValue:{anchor:e.anchorAttr.stateValues.coords}}:{useEssentialOrDefaultValue:{anchor:!0}},inverseDefinition:async({desiredStateVariableValues:e,dependencyValues:t,stateValues:n,initialChange:r})=>r&&!await n.draggable?{success:!1}:t.anchorAttr?{success:!0,instructions:[{setDependency:"anchorAttr",desiredValue:e.anchor,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"anchor",value:e.anchor}]}},e}async moveImage({x:e,y:t,z:n,transient:r,actionId:a}){let i=["vector"];return void 0!==e&&(i[1]=e),void 0!==t&&(i[2]=t),void 0!==n&&(i[3]=n),r?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],transient:r,actionId:a}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],actionId:a,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{x:e,y:t,z:n}}})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class Video extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{recordVideoStarted:this.recordVideoStarted.bind(this),recordVideoWatched:this.recordVideoWatched.bind(this),recordVideoPaused:this.recordVideoPaused.bind(this),recordVideoSkipped:this.recordVideoSkipped.bind(this),recordVideoCompleted:this.recordVideoCompleted.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this),recordVideoReady:this.recordVideoReady.bind(this),playVideo:this.playVideo.bind(this),pauseVideo:this.pauseVideo.bind(this),setTime:this.setTime.bind(this)})}static componentType="video";static createAttributesObject(){let e=super.createAttributesObject();return e.width={createComponentOfType:"_componentSize"},e.size={createComponentOfType:"text"},e.aspectRatio={createComponentOfType:"number"},e.height={createComponentOfType:"_componentSize"},e.displayMode={createComponentOfType:"text",createStateVariable:"displayMode",validValues:["block","inline"],defaultValue:"block",forRenderer:!0,public:!0},e.horizontalAlign={createComponentOfType:"text",createStateVariable:"horizontalAlign",validValues:["center","left","right"],defaultValue:"center",forRenderer:!0,public:!0},e.youtube={createComponentOfType:"text",createStateVariable:"youtube",defaultValue:null,public:!0,forRenderer:!0},e.source={createComponentOfType:"text",createStateVariable:"source",defaultValue:null,public:!0,forRenderer:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.size={public:!0,defaultValue:"full",hasEssential:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({sizeAttr:{dependencyType:"attributeComponent",attributeName:"size",variableNames:["value"]},widthAttr:{dependencyType:"attributeComponent",attributeName:"width",variableNames:["componentSize"]}}),definition({dependencyValues:e}){const t="full";if(e.sizeAttr){let n=e.sizeAttr.stateValues.value.toLowerCase();return sizePossibilities.includes(n)||(n=t),{setValue:{size:n}}}if(e.widthAttr){let n=e.widthAttr.stateValues.componentSize;if(null===n)return{setValue:{size:t}};let r,{isAbsolute:a,size:i}=n;if(a){for(let[e,t]of orderedWidthMidpoints.entries())if(i<=t){r=sizePossibilities[e];break}r||(r=t)}else{for(let[e,t]of orderedPercentWidthMidpoints.entries())if(i<=t){r=sizePossibilities[e];break}r||(r=t)}return{setValue:{size:r}}}return{useEssentialOrDefaultValue:{size:!0}}}},e.width={public:!0,forRenderer:!0,shadowingInstructions:{createComponentOfType:"_componentSize"},returnDependencies:()=>({size:{dependencyType:"stateVariable",variableName:"size"}}),definition:({dependencyValues:e})=>({setValue:{width:{isAbsolute:!0,size:widthsBySize[e.size]}}})},e.aspectRatio={public:!0,forRenderer:!0,defaultValue:"16 / 9",hasEssential:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({aspectRatioAttr:{dependencyType:"attributeComponent",attributeName:"aspectRatio",variableNames:["value"]},width:{dependencyType:"stateVariable",variableName:"width"}}),definition({dependencyValues:e}){if(null!==e.aspectRatioAttr){let t=e.aspectRatioAttr.stateValues.value;return Number.isFinite(t)||(t=1),{setValue:{aspectRatio:t}}}return{useEssentialOrDefaultValue:{aspectRatio:!0}}}},e.state={hasEssential:!0,defaultValue:"initializing",forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"text"},ignoreFixed:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{state:!0}}),inverseDefinition({desiredStateVariableValues:e}){let t=e.state.toLowerCase();return["stopped","playing"].includes(t)?{success:!0,instructions:[{setEssentialValue:"state",value:t}]}:{success:!1}}},e.time={hasEssential:!0,defaultValue:0,forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"number"},ignoreFixed:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{time:!0}}),inverseDefinition({desiredStateVariableValues:e}){let t=e.time;return t>=0?{success:!0,instructions:[{setEssentialValue:"time",value:t}]}:{success:!1}}},e.duration={hasEssential:!0,defaultValue:null,public:!0,shadowingInstructions:{createComponentOfType:"number"},ignoreFixed:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{duration:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"duration",value:e.duration}]})},e.segmentsWatched={hasEssential:!0,defaultValue:null,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{segmentsWatched:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"segmentsWatched",value:e.segmentsWatched}]})},e.secondsWatched={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({segmentsWatched:{dependencyType:"stateVariable",variableName:"segmentsWatched"}}),definition({dependencyValues:e}){let t=0;return e.segmentsWatched&&(t=e.segmentsWatched.reduce(((e,t)=>e+t[1]-t[0]),0)),{setValue:{secondsWatched:t}}}},e.fractionWatched={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({secondsWatched:{dependencyType:"stateVariable",variableName:"secondsWatched"},duration:{dependencyType:"stateVariable",variableName:"duration"}}),definition:({dependencyValues:e})=>({setValue:{fractionWatched:e.secondsWatched/e.duration}})},e}recordVideoStarted({beginTime:e,duration:t,rate:n}){this.coreFunctions.requestRecordEvent({verb:"played",object:{componentName:this.componentName,componentType:this.componentType,duration:t},context:{startingPoint:e,rate:n}}),this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"state",value:"playing"}],overrideReadOnly:!0})}async recordVideoWatched({beginTime:e,endTime:t,duration:n,rates:r}){this.coreFunctions.requestRecordEvent({verb:"watched",object:{componentName:this.componentName,componentType:this.componentType,duration:n},context:{startingPoint:e,endingPoint:t,rates:r}});let a,i=await this.stateValues.segmentsWatched;if(e<1?e=0:t>n-2&&(t=n),i){a=[];let n=!1;for(let[r,s]of i.entries()){if(ts[1]+1?a.push(s):(e=Math.min(s[0],e),t=Math.max(s[1],t))}n||a.push([e,t])}else a=[[e,t]];return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"segmentsWatched",value:a}],canSkipUpdatingRenderer:!0}),await this.coreFunctions.triggerChainedActions({componentName:this.componentName})}recordVideoPaused({endTime:e,duration:t}){this.coreFunctions.requestRecordEvent({verb:"paused",object:{componentName:this.componentName,componentType:this.componentType,duration:t},context:{endingPoint:e}}),this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"state",value:"stopped"}],overrideReadOnly:!0})}recordVideoSkipped({beginTime:e,endTime:t,duration:n}){this.coreFunctions.requestRecordEvent({verb:"skipped",object:{componentName:this.componentName,componentType:this.componentType,duration:n},context:{startingPoint:e,endingPoint:t}})}recordVideoCompleted({duration:e}){this.coreFunctions.requestRecordEvent({verb:"completed",object:{componentName:this.componentName,componentType:this.componentType,duration:e}}),this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"state",value:"stopped"}],overrideReadOnly:!0})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}recordVideoReady({duration:e}){this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"state",value:"stopped"},{updateType:"updateValue",componentName:this.componentName,stateVariable:"duration",value:e}],overrideReadOnly:!0,doNotSave:!0})}playVideo(){this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"state",value:"playing"}],overrideReadOnly:!0})}pauseVideo(){this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"state",value:"stopped"}],overrideReadOnly:!0})}setTime({time:e}){this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"time",value:e}],overrideReadOnly:!0})}}class Embed extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="embed";static createAttributesObject(){let e=super.createAttributesObject();return e.width={createComponentOfType:"_componentSize",createStateVariable:"width",defaultValue:{size:500,isAbsolute:!0},public:!0,forRenderer:!0},e.height={createComponentOfType:"_componentSize",createStateVariable:"height",defaultValue:{size:500,isAbsolute:!0},public:!0,forRenderer:!0},e.geogebra={createComponentOfType:"text",createStateVariable:"geogebra",defaultValue:null,public:!0,forRenderer:!0},e.encodedGeogebraContent={createComponentOfType:"text",createStateVariable:"encodedGeogebraContent",defaultValue:null,public:!0,forRenderer:!0},e.fromMathInsight={createComponentOfType:"text",createStateVariable:"fromMathInsight",defaultValue:null,public:!0,forRenderer:!0},e}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class Hint extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{revealHint:this.revealHint.bind(this),closeHint:this.closeHint.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="hint";static renderChildren=!0;static includeBlankStringChildren=!0;static returnChildGroups(){return[{group:"titles",componentTypes:["title"]},{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.showHints={forRenderer:!0,returnDependencies:()=>({hide:{dependencyType:"stateVariable",variableName:"hide"},showHintsFlag:{dependencyType:"flag",flagName:"showHints"}}),definition:({dependencyValues:e})=>({setValue:{showHints:e.showHintsFlag&&!e.hide}})},e.open={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,defaultValue:!1,hasEssential:!0,doNotShadowEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{open:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"open",value:e.open}]})},e.titleChildName={forRenderer:!0,returnDependencies:()=>({titleChild:{dependencyType:"child",childGroups:["titles"]}}),definition({dependencyValues:e}){let t=null;return e.titleChild.length>0&&(t=e.titleChild[e.titleChild.length-1].componentName),{setValue:{titleChildName:t}}}},e.childIndicesToRender={returnDependencies:()=>({titleChildren:{dependencyType:"child",childGroups:["titles"]},allChildren:{dependencyType:"child",childGroups:["anything","titles"]},titleChildName:{dependencyType:"stateVariable",variableName:"titleChildName"}}),definition({dependencyValues:e}){let t=[],n=e.titleChildren.map((e=>e.componentName));for(let[r,a]of e.allChildren.entries())"object"==typeof a&&n.includes(a.componentName)&&a.componentName!==e.titleChildName||t.push(r);return{setValue:{childIndicesToRender:t}}}},e.title={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({titleChild:{dependencyType:"child",childGroups:["titles"],variableNames:["text"]}}),definition:({dependencyValues:e})=>0===e.titleChild.length?{setValue:{title:"Hint"}}:{setValue:{title:e.titleChild[e.titleChild.length-1].stateValues.text}}},e}async revealHint({actionId:e}){return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"open",value:!0}],overrideReadOnly:!0,actionId:e,event:{verb:"viewed",object:{componentName:this.componentName,componentType:this.componentType}}})}async closeHint({actionId:e}){return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"open",value:!1}],overrideReadOnly:!0,actionId:e,event:{verb:"closed",object:{componentName:this.componentName,componentType:this.componentType}}})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class Solution extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{revealSolution:this.revealSolution.bind(this),closeSolution:this.closeSolution.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="solution";static renderChildren=!0;static sendToRendererEvenIfHidden=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.hide={createComponentOfType:"boolean"},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e}){return{success:!0,newChildren:[{componentType:"_solutionContainer",children:e}]}}}),e}static returnChildGroups(){return[{group:"inlinesBlocks",componentTypes:["_inline","_block"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.hide={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,defaultValue:!1,hasEssential:!0,returnDependencies:()=>({hideAttr:{dependencyType:"attributeComponent",attributeName:"hide",variableNames:["value"]},displayMode:{dependencyType:"flag",flagName:"solutionDisplayMode"}}),definition:({dependencyValues:e})=>"none"===e.displayMode?{setValue:{hide:!0}}:null!==e.hideAttr?{setValue:{hide:e.hideAttr.stateValues.value}}:{useEssentialOrDefaultValue:{hide:!0}},inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t})=>"none"===t.displayMode?{success:!1}:null!==t.hideAttr?{success:!0,instructions:[{setDependency:"hideAttr",desiredValue:e.hide,variableIndex:0}]}:{success:!0,instructions:[{setSetVariable:"hide",value:e.hide}]}},e.open={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,defaultValue:!1,hasEssential:!0,returnDependencies:()=>({displayMode:{dependencyType:"flag",flagName:"solutionDisplayMode"}}),definition:({dependencyValues:e})=>"displayed"===e.displayMode?{setValue:{open:!0}}:"none"===e.displayMode?{setValue:{open:!1}}:{useEssentialOrDefaultValue:{open:!0}},inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t})=>"displayed"===t.displayMode||"none"===t.displayMode?{success:!1}:{success:!0,instructions:[{setEssentialValue:"open",value:e.open}]}},e.canBeClosed={forRenderer:!0,returnDependencies:()=>({displayMode:{dependencyType:"flag",flagName:"solutionDisplayMode"}}),definition:({dependencyValues:e})=>"button"===e.displayMode?{setValue:{canBeClosed:!0}}:{setValue:{canBeClosed:!1}}},e.message={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,defaultValue:"",hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{message:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"message",value:e.message}]})},e}async revealSolution({actionId:e}){let t,{allowView:n,message:r,scoredComponent:a}=await this.coreFunctions.recordSolutionView(),i=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"open",value:n},{updateType:"updateValue",componentName:this.componentName,stateVariable:"message",value:r}];return n&&(i.push({updateType:"updateValue",componentName:a,stateVariable:"viewedSolution",value:!0}),t={verb:"viewed",object:{componentName:this.componentName,componentType:this.componentType}}),await this.coreFunctions.performUpdate({updateInstructions:i,actionId:e,event:t,overrideReadOnly:!0})}async closeSolution({actionId:e}){return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"open",value:!1}],overrideReadOnly:!0,actionId:e,event:{verb:"closed",object:{componentName:this.componentName,componentType:this.componentType}}})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}static includeBlankStringChildren=!0}class IntComma extends Text{static componentType="intcomma";static rendererType="text";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return renameStateVariable({stateVariableDefinitions:e,oldName:"value",newName:"originalValue"}),e.value={public:!0,shadowingInstructions:{createComponentOfType:this.componentType},returnDependencies:()=>({originalValue:{dependencyType:"stateVariable",variableName:"originalValue"}}),definition:function({dependencyValues:e}){let t=e.originalValue,n=/^(-?\d+)(\d{3})/,r=t.match(n);for(;null!==r;)t=t.replace(n,"$1,$2"),r=t.match(n);return{setValue:{value:t}}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:({dependencyValues:e})=>({setValue:{text:e.value}})},e}}const e$1="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".split("");var t$1=function(e){let t=(e=e||"_")+"-";for(let e=0;e<7;e++)t+=e$1[Math.floor(Math.random()*e$1.length)];return t};let r$1={"!":"¡","?":"¿Ɂ",'"':'“”"❝❞',"'":"‘‛❛❜","-":"—–",a:"ªÀÁÂÃÄÅàáâãäåĀāĂ㥹ǍǎǞǟǠǡǺǻȀȁȂȃȦȧȺΆΑΔΛάαλАадѦѧӐӑӒӓƛɅæ",b:"ßþƀƁƂƃƄƅɃΒβϐϦБВЪЬвъьѢѣҌҍ",c:"¢©ÇçĆćĈĉĊċČčƆƇƈȻȼͻͼͽϲϹϽϾСсєҀҁҪҫ",d:"ÐĎďĐđƉƊȡƋƌǷ",e:"ÈÉÊËèéêëĒēĔĕĖėĘęĚěƎƏƐǝȄȅȆȇȨȩɆɇΈΕΞΣέεξϱϵ϶ЀЁЕЭеѐёҼҽҾҿӖӗӘәӚӛӬӭ",f:"ƑƒϜϝӺӻҒғſ",g:"ĜĝĞğĠġĢģƓǤǥǦǧǴǵ",h:"ĤĥĦħƕǶȞȟΉΗЂЊЋНнђћҢңҤҥҺһӉӊ",I:"ÌÍÎÏ",i:"ìíîïĨĩĪīĬĭĮįİıƖƗȈȉȊȋΊΐΪίιϊІЇії",j:"ĴĵǰȷɈɉϳЈј",k:"ĶķĸƘƙǨǩΚκЌЖКжкќҚқҜҝҞҟҠҡ",l:"ĹĺĻļĽľĿŀŁłƚƪǀǏǐȴȽΙӀӏ",m:"ΜϺϻМмӍӎ",n:"ÑñŃńŅņŇňʼnŊŋƝƞǸǹȠȵΝΠήηϞЍИЙЛПийлпѝҊҋӅӆӢӣӤӥπ",o:"ÒÓÔÕÖØðòóôõöøŌōŎŏŐőƟƠơǑǒǪǫǬǭǾǿȌȍȎȏȪȫȬȭȮȯȰȱΌΘΟθοσόϕϘϙϬϭϴОФоѲѳӦӧӨөӪӫ",p:"ƤƿΡρϷϸϼРрҎҏÞ",q:"Ɋɋ",r:"ŔŕŖŗŘřƦȐȑȒȓɌɍЃГЯгяѓҐґ",s:"ŚśŜŝŞşŠšƧƨȘșȿЅѕ",t:"ŢţŤťŦŧƫƬƭƮȚțȶȾΓΤτϮТт",u:"µÙÚÛÜùúûüŨũŪūŬŭŮůŰűŲųƯưƱƲǓǔǕǖǗǘǙǚǛǜȔȕȖȗɄΰμυϋύ",v:"νѴѵѶѷ",w:"ŴŵƜωώϖϢϣШЩшщѡѿ",x:"×ΧχϗϰХхҲҳӼӽӾӿ",y:"ÝýÿŶŷŸƳƴȲȳɎɏΎΥΫγψϒϓϔЎУучўѰѱҮүҰұӮӯӰӱӲӳ",z:"ŹźŻżŽžƩƵƶȤȥɀΖζ"},a$1={};Object.keys(r$1).forEach((function(e){r$1[e].split("").forEach((function(t){a$1[t]=e}))}));var n$1=e=>{let t=e.split("");return t.forEach(((e,n)=>{a$1[e]&&(t[n]=a$1[e])})),t.join("")};const i$1=/([A-Z]\.)+[A-Z]?,?$/,o$1=/^[A-Z]\.,?$/,s$1=/[A-Z]{2,}('s|,)?$/,l$1=/([a-z]\.)+[a-z]\.?$/;var u$1=function(e){return!0===i$1.test(e)||!0===l$1.test(e)||!0===o$1.test(e)||!0===s$1.test(e)};const c$2=n$1,h$1=u$1,d$1=/[a-z\u00C0-\u00FF] ?\/ ?[a-z\u00C0-\u00FF]/,g$1=function(e){let t=e=(e=(e=e||"").toLowerCase()).trim();return e=c$2(e),!0===d$1.test(e)&&(e=e.replace(/\/.*/,"")),e=(e=(e=(e=(e=(e=(e=e.replace(/^[#@]/,"")).replace(/[,;.!?]+$/,"")).replace(/[\u0027\u0060\u00B4\u2018\u2019\u201A\u201B\u2032\u2035\u2039\u203A]+/g,"'")).replace(/[\u0022\u00AB\u00BB\u201C\u201D\u201E\u201F\u2033\u2034\u2036\u2037\u2E42\u301D\u301E\u301F\uFF02]+/g,'"')).replace(/\u2026/g,"...")).replace(/\u2013/g,"-")).replace(/([aeiou][ktrp])in$/,"$1ing"),!0===/^(re|un)-?[^aeiou]./.test(e)&&(e=e.replace("-","")),h$1(e)&&(e=e.replace(/\./g,"")),!1===/^[:;]/.test(e)&&(e=(e=(e=e.replace(/\.{3,}$/g,"")).replace(/[",\.!:;\?\)]+$/g,"")).replace(/^['"\(]+/g,"")),""===(e=(e=e.replace(/[\u200B-\u200D\uFEFF]/g,"")).trim())&&(e=t),e.replace(/([0-9]),([0-9])/g,"$1$2")},p$1=function(e){return(e=e.replace(/['’]s$/,"")).replace(/s['’]$/,"s")},m$1=/^[ \n\t\.\[\](){}⟨⟩:,،、‒–—―…!‹›«»‐\-?‘’;\/⁄·&*•^†‡°¡¿※№÷׺ª%‰+−=‱¶′″‴§~\|‖¦©℗®℠™¤₳฿\u0022\uFF02\u0027\u201C\u201F\u201B\u201E\u2E42\u201A\u2035\u2036\u2037\u301D\u0060\u301F]+/,f$1=/[ \n\t\.'\[\](){}⟨⟩:,،、‒–—―…!‹›«»‐\-?‘’;\/⁄·&*@•^†‡°¡¿※#№÷׺ª‰+−=‱¶′″‴§~\|‖¦©℗®℠™¤₳฿\u0022\uFF02\u201D\u00B4\u301E]+$/,b$1=/\//,y$1=/['’]/,v$1=/^[a-z]\.([a-z]\.)+/i,w$1=/^[-+\.][0-9]/,k$1=/^'[0-9]{2}/;var A$1=e=>{let t=e,n="",r="";""===(e=(e=e.replace(m$1,(t=>(n=t,"-"!==n&&"+"!==n&&"."!==n||!w$1.test(e)?"'"===n&&k$1.test(e)?(n="",t):"":(n="",t))))).replace(f$1,(a=>(r=a,y$1.test(a)&&/[sn]['’]$/.test(t)&&!1===y$1.test(n)?(r=r.replace(y$1,""),"'"):!0===v$1.test(e)?(r=r.replace(/\./,""),"."):""))))&&(t=t.replace(/ *$/,(e=>(r=e||"",""))),e=t,n="");let a=g$1(e);const i={text:e,clean:a,reduced:p$1(a),pre:n,post:r};return b$1.test(e)&&e.split(b$1).forEach((e=>{i.alias=i.alias||{},i.alias[e.trim()]=!0})),i},D$1={};!function(e){const t=/^[A-Z][a-z'\u00C0-\u00FF]/,n=/^[A-Z]+s?$/;e.toUpperCase=function(){return this.text=this.text.toUpperCase(),this},e.toLowerCase=function(){return this.text=this.text.toLowerCase(),this},e.toTitleCase=function(){return this.text=this.text.replace(/^ *[a-z\u00C0-\u00FF]/,(e=>e.toUpperCase())),this},e.isUpperCase=function(){return n.test(this.text)},e.isTitleCase=function(){return t.test(this.text)},e.titleCase=e.isTitleCase}(D$1);var $$1={};!function(e){const t=/(\u0022|\uFF02|\u0027|\u201C|\u2018|\u201F|\u201B|\u201E|\u2E42|\u201A|\u00AB|\u2039|\u2035|\u2036|\u2037|\u301D|\u0060|\u301F)/,n=/(\u0022|\uFF02|\u0027|\u201D|\u2019|\u201D|\u2019|\u201D|\u201D|\u2019|\u00BB|\u203A|\u2032|\u2033|\u2034|\u301E|\u00B4|\u301E)/;e.hasPost=function(e){return-1!==this.post.indexOf(e)},e.hasPre=function(e){return-1!==this.pre.indexOf(e)},e.hasQuote=function(){return t.test(this.pre)||n.test(this.post)},e.hasQuotation=e.hasQuote,e.hasComma=function(){return this.hasPost(",")},e.hasPeriod=function(){return!0===this.hasPost(".")&&!1===this.hasPost("...")},e.hasExclamation=function(){return this.hasPost("!")},e.hasQuestionMark=function(){return this.hasPost("?")||this.hasPost("¿")},e.hasEllipses=function(){return this.hasPost("..")||this.hasPost("…")||this.hasPre("..")||this.hasPre("…")},e.hasSemicolon=function(){return this.hasPost(";")},e.hasSlash=function(){return/\//.test(this.text)},e.hasHyphen=function(){const e=/^(-|–|—)$/;return e.test(this.post)||e.test(this.pre)},e.hasDash=function(){const e=/ (-|–|—) /;return e.test(this.post)||e.test(this.pre)},e.hasContraction=function(){return Boolean(this.implicit)},e.addPunctuation=function(e){return","!==e&&";"!==e||(this.post=this.post.replace(e,"")),this.post=e+this.post,this}}($$1);var P$1={};const E$1=function(e,t,n=3){if(e===t)return 1;if(e.lengthn?r:n)+1;if(Math.abs(n-r)>(a||100))return a||100;let i,s,o,l,u,c,p=[];for(let e=0;e4)return n;o=t[i-1],l=s===o?0:1,u=p[a-1][i]+1,(c=p[a][i-1]+1)1&&i>1&&s===t[i-2]&&e[a-2]===o&&(c=p[a-2][i-2]+l)t.fuzzy)return!0;if(!0===t.soft&&(n=E$1(t.word,e.root),n>t.fuzzy))return!0}return t.word===e.clean||t.word===e.text||t.word===e.reduced}return void 0!==t.tag?!0===e.tags[t.tag]:void 0!==t.method?"function"==typeof e[t.method]&&!0===e[t.method]():void 0!==t.regex?t.regex.test(e.clean):void 0!==t.fastOr?!(!e.implicit||!0!==t.fastOr.hasOwnProperty(e.implicit))||t.fastOr.hasOwnProperty(e.reduced)||t.fastOr.hasOwnProperty(e.text):void 0!==t.choices&&("and"===t.operator?t.choices.every((t=>H$1(e,t,n,r))):t.choices.some((t=>H$1(e,t,n,r))))}(e,t,n,r);return!0===t.negative?!a:a};const j$1=H$1,N$1=u$1,x$1={};P$1.doesMatch=function(e,t,n){return j$1(this,e,t,n)},P$1.isAcronym=function(){return N$1(this.text)},P$1.isImplicit=function(){return""===this.text&&Boolean(this.implicit)},P$1.isKnown=function(){return Object.keys(this.tags).some((e=>!0!==x$1[e]))},P$1.setRoot=function(e){let t=e.transforms,n=this.implicit||this.clean;if(this.tags.Plural&&(n=t.toSingular(n,e)),this.tags.Verb&&!this.tags.Negative&&!this.tags.Infinitive){let r=null;this.tags.PastTense?r="PastTense":this.tags.Gerund?r="Gerund":this.tags.PresentTense?r="PresentTense":this.tags.Participle?r="Participle":this.tags.Actor&&(r="Actor"),n=t.toInfinitive(n,e,r)}this.root=n};var F$1={};const C$1=n$1,B$1=/[\s-]/,G$1=/^[A-Z-]+$/;F$1.textOut=function(e,t,n){e=e||{};let r=this.text,a=this.pre,i=this.post;return!0===e.reduced&&(r=this.reduced||""),!0===e.root&&(r=this.root||""),!0===e.implicit&&this.implicit&&(r=this.implicit||""),!0===e.normal&&(r=this.clean||this.text||""),!0===e.root&&(r=this.root||this.reduced||""),!0===e.unicode&&(r=C$1(r)),!0===e.titlecase&&(this.tags.ProperNoun&&!this.titleCase()||(this.tags.Acronym?r=r.toUpperCase():G$1.test(r)&&!this.tags.Acronym&&(r=r.toLowerCase()))),!0===e.lowercase&&(r=r.toLowerCase()),!0===e.acronyms&&this.tags.Acronym&&(r=r.replace(/\./g,"")),!0!==e.whitespace&&!0!==e.root||(a="",i=" ",!1!==B$1.test(this.post)&&!e.last||this.implicit||(i="")),!0!==e.punctuation||e.root||(!0===this.hasPost(".")?i="."+i:!0===this.hasPost("?")?i="?"+i:!0===this.hasPost("!")?i="!"+i:!0===this.hasPost(",")?i=","+i:!0===this.hasEllipses()&&(i="..."+i)),!0!==t&&(a=""),!0!==n&&(i=""),!0===e.abbreviations&&this.tags.Abbreviation&&(i=i.replace(/^\./,"")),a+r+i};var z$1={};const I$1={Auxiliary:1,Possessive:1},O$1=function(e,t){let n=Object.keys(e.tags);const r=t.tags;return n=n.sort(((e,t)=>I$1[t]||!r[t]?-1:r[t]?r[e]?r[e].lineage.length>r[t].lineage.length?1:r[e].isA.length>r[t].isA.length?-1:0:0:1)),n},T$2={text:!0,tags:!0,implicit:!0,whitespace:!0,clean:!1,id:!1,index:!1,offset:!1,bestTag:!1};z$1.json=function(e,t){e=e||{};let n={};return(e=Object.assign({},T$2,e)).text&&(n.text=this.text),e.normal&&(n.normal=this.clean),e.tags&&(n.tags=Object.keys(this.tags)),e.clean&&(n.clean=this.clean),(e.id||e.offset)&&(n.id=this.id),e.implicit&&null!==this.implicit&&(n.implicit=this.implicit),e.whitespace&&(n.pre=this.pre,n.post=this.post),e.bestTag&&(n.bestTag=O$1(this,t)[0]),n};var V$1=Object.assign({},D$1,$$1,P$1,F$1,z$1),M$1={},J$1={};function L$1(){return"undefined"!=typeof window&&window.document}const S$1=function(e,t){for(e=e.toString();e.lengthe.charAt(0).toUpperCase()+e.substr(1);const _$1=J$1,K$1=function(e,t,n,r){let a=r.tags;if(""===t||"."===t||"-"===t)return;if("#"===t[0]&&(t=t.replace(/^#/,"")),t=_$1.titleCase(t),!0===e.tags[t])return;const i=r.isVerbose();!0===i&&_$1.logTag(e,t,n),e.tags[t]=!0,!0===a.hasOwnProperty(t)&&(a[t].isA.forEach((t=>{e.tags[t]=!0,!0===i&&_$1.logTag(e,"→ "+t)})),e.unTag(a[t].notA,"←",r))},q$1=J$1,W$1=/^[a-z]/,R$1=function(e,t,n,r){const a=r.isVerbose();if("*"===t)return e.tags={},e;var i;t=t.replace(/^#/,""),!0===W$1.test(t)&&(t=(i=t).charAt(0).toUpperCase()+i.substr(1)),!0===e.tags[t]&&(delete e.tags[t],!0===a&&q$1.logUntag(e,t,n));const s=r.tags;if(s[t]){let n=s[t].lineage;for(let t=0;te.clone()));return t.forEach(((e,n)=>{this.pool.add(e),t[n+1]&&(e.next=t[n+1].id),t[n-1]&&(e.prev=t[n-1].id)})),this.buildFrom(t[0].id,t.length)},lastTerm:function(){let e=this.terms();return e[e.length-1]},hasId:function(e){if(0===this.length||!e)return!1;if(this.start===e)return!0;if(this.cache.terms){let t=this.cache.terms;for(let n=0;n""!==e.text)).length},fullSentence:function(){let e=this.terms(0);for(;e.prev;)e=this.pool.get(e.prev);let t=e.id,n=1;for(;e.next;)e=this.pool.get(e.next),n+=1;return this.buildFrom(t,n)}},oe$1={text:function(e={},t,n){"string"==typeof e&&(e="normal"===e?{whitespace:!0,unicode:!0,lowercase:!0,punctuation:!0,acronyms:!0,abbreviations:!0,implicit:!0,normal:!0}:"clean"===e?{titlecase:!1,lowercase:!0,punctuation:!0,whitespace:!0,unicode:!0,implicit:!0,normal:!0}:"reduced"===e?{punctuation:!1,titlecase:!1,lowercase:!0,whitespace:!0,unicode:!0,implicit:!0,reduced:!0}:"implicit"===e?{punctuation:!0,implicit:!0,whitespace:!0,trim:!0}:"root"===e?{titlecase:!1,lowercase:!0,punctuation:!0,whitespace:!0,unicode:!0,implicit:!0,root:!0}:{});let r=this.terms(),a=!1;r[0]&&null===r[0].prev&&null===r[r.length-1].next&&(a=!0);let i=r.reduce(((i,s,o)=>{if(0===o&&""===s.text&&null!==s.implicit&&!e.implicit)return i;e.last=n&&o===r.length-1;let l=!0,u=!0;return!1===a&&(0===o&&t&&(l=!1),o===r.length-1&&n&&(u=!1)),i+s.textOut(e,l,u)}),"");return!0===a&&n&&(i=i.replace(/ +$/,"")),!0===e.trim&&(i=i.trim()),i}},se$1={trim:function(){let e=this.terms();if(e.length>0){e[0].pre=e[0].pre.replace(/^\s+/,"");let t=e[e.length-1];t.post=t.post.replace(/\s+$/,"")}return this}},le$1={};const ue$1=/[.?!]\s*$/,ce$1=function(e,t){t[0].pre=e[0].pre;let n=e[e.length-1],r=t[t.length-1];r.post=function(e,t){return ue$1.test(t)?t+e.match(/\s*$/):e}(n.post,r.post),n.post="",""===n.post&&(n.post+=" ")},he$1=/ /,de$1=function(e,t,n){let r=e.terms(),a=t.terms();ce$1(r,a),function(e,t,n){let r=e[e.length-1],a=t[t.length-1],i=r.next;r.next=t[0].id,a.next=i,i&&(n.get(i).prev=a.id);let s=e[0].id;s&&(t[0].prev=s)}(r,a,e.pool);let i=[e],s=e.start,o=[n];return o=o.concat(n.parents()),o.forEach((e=>{let t=e.list.filter((e=>e.hasId(s)));i=i.concat(t)})),i=function(e){return e.filter(((t,n)=>e.indexOf(t)===n))}(i),i.forEach((e=>{e.length+=t.length})),e.cache={},e},ge$1=function(e,t,n){const r=e.start;let a=t.terms();!function(e){let t=e[e.length-1];!1===he$1.test(t.post)&&(t.post+=" ")}(a),function(e,t,n){let r=n[n.length-1];r.next=e.start;let a=e.pool,i=a.get(e.start);i.prev&&(a.get(i.prev).next=t.start),n[0].prev=e.terms(0).prev,e.terms(0).prev=r.id}(e,t,a);let i=[e],s=[n];return s=s.concat(n.parents()),s.forEach((e=>{let n=e.list.filter((e=>e.hasId(r)||e.hasId(t.start)));i=i.concat(n)})),i=function(e){return e.filter(((t,n)=>e.indexOf(t)===n))}(i),i.forEach((e=>{e.length+=t.length,e.start===r&&(e.start=t.start),e.cache={}})),e},pe$1=function(e,t){let n=t.pool(),r=e.terms(),a=n.get(r[0].prev)||{},i=n.get(r[r.length-1].next)||{};r[0].implicit&&a.implicit&&(a.set(a.implicit),a.post+=" "),function(e,t,n,r){let a=e.parents();a.push(e),a.forEach((e=>{let a=e.list.find((e=>e.hasId(t)));a&&(a.length-=n,a.start===t&&(a.start=r.id),a.cache={})})),e.list=e.list.filter((e=>!(!e.start||!e.length)))}(t,e.start,e.length,i),a&&(a.next=i.id),i&&(i.prev=a.id)};le$1.append=function(e,t){return de$1(this,e,t),this},le$1.prepend=function(e,t){return ge$1(this,e,t),this},le$1.delete=function(e){return pe$1(this,e),this},le$1.replace=function(e,t){let n=this.length;de$1(this,e,t);let r=this.buildFrom(this.start,this.length);r.length=n,pe$1(r,t)},le$1.splitOn=function(e){let t=this.terms(),n={before:null,match:null,after:null},r=t.findIndex((t=>t.id===e.start));if(-1===r)return n;let a=t.slice(0,r);a.length>0&&(n.before=this.buildFrom(a[0].id,a.length));let i=t.slice(r,r+e.length);i.length>0&&(n.match=this.buildFrom(i[0].id,i.length));let s=t.slice(r+e.length,t.length);return s.length>0&&(n.after=this.buildFrom(s[0].id,s.length,this.pool)),n};var me$2={json:function(e={},t){let n={};return e.text&&(n.text=this.text()),e.normal&&(n.normal=this.text("normal")),e.clean&&(n.clean=this.text("clean")),e.reduced&&(n.reduced=this.text("reduced")),e.implicit&&(n.implicit=this.text("implicit")),e.root&&(n.root=this.text("root")),e.trim&&(n.text&&(n.text=n.text.trim()),n.normal&&(n.normal=n.normal.trim()),n.reduced&&(n.reduced=n.reduced.trim())),e.terms&&(!0===e.terms&&(e.terms={}),n.terms=this.terms().map((n=>n.json(e.terms,t)))),n}},fe$1={lookAhead:function(e){e||(e=".*");let t=this.pool,n=[];const r=function(e){let a=t.get(e);a&&(n.push(a),a.prev&&r(a.next))};let a=this.terms(),i=a[a.length-1];return r(i.next),0===n.length?[]:this.buildFrom(n[0].id,n.length).match(e)},lookBehind:function(e){e||(e=".*");let t=this.pool,n=[];const r=function(e){let a=t.get(e);a&&(n.push(a),a.prev&&r(a.prev))};let a=t.get(this.start);return r(a.prev),0===n.length?[]:this.buildFrom(n[n.length-1].id,n.length).match(e)}},be$1=Object.assign({},ie$1,oe$1,se$1,le$1,me$2,fe$1),ye$1={},ve$1,we$1=function(e,t){if(0===t.length)return!0;for(let e=0;e0)return!0;if(!0===n.anything&&!0===n.negative)return!0}return!1},ke$1={};(ve$1=ke$1).getGreedy=function(e,t){let n=Object.assign({},e.regs[e.r],{start:!1,end:!1}),r=e.t;for(;e.t{let a=0,i=e.t+r+t+a;if(void 0===e.terms[i])return!1;let s=e.terms[i].doesMatch(n,i+e.start_i,e.phrase_length);if(!0===s&&!0===n.greedy)for(let t=1;t{let r=n.every(((t,n)=>{let r=e.t+n;return void 0!==e.terms[r]&&e.terms[r].doesMatch(t,r,e.phrase_length)}));return!0===r&&n.length>t&&(t=n.length),r}))&&t},ve$1.getGroup=function(e,t,n){if(e.groups[e.groupId])return e.groups[e.groupId];const r=e.terms[t].id;return e.groups[e.groupId]={group:String(n),start:r,length:0},e.groups[e.groupId]};const Ae$1=t$1,De=ke$1;var $e$1=function(e,t,n,r){let a={t:0,terms:e,r:0,regs:t,groups:{},start_i:n,phrase_length:r,hasGroup:!1,groupId:null,previousGroup:null};for(;a.r!e.optional)))break;return null}if(!0===e.anything&&!0===e.greedy){let n=De.greedyTo(a,t[a.r+1]);if(null===n||0===n)return null;if(void 0!==e.min&&n-a.te.max){a.t=a.t+e.max;continue}!0===a.hasGroup&&(De.getGroup(a,a.t,e.named).length=n-a.t),a.t=n;continue}if(void 0!==e.choices&&"or"===e.operator){let t=De.doOrBlock(a);if(t){if(!0===e.negative)return null;!0===a.hasGroup&&(De.getGroup(a,a.t,e.named).length+=t),a.t+=t;continue}if(!e.optional)return null}if(void 0!==e.choices&&"and"===e.operator){let t=De.doAndBlock(a);if(t){if(!0===e.negative)return null;!0===a.hasGroup&&(De.getGroup(a,a.t,e.named).length+=t),a.t+=t;continue}if(!e.optional)return null}let n=a.terms[a.t],i=n.doesMatch(e,a.start_i+a.t,a.phrase_length);if(!0===e.anything||!0===i||De.isEndGreedy(e,a)){let i=a.t;if(e.optional&&t[a.r+1]&&e.negative)continue;if(e.optional&&t[a.r+1]){let r=n.doesMatch(t[a.r+1],a.start_i+a.t,a.phrase_length);if(e.negative||r){let e=a.terms[a.t+1];e&&e.doesMatch(t[a.r+1],a.start_i+a.t,a.phrase_length)||(a.r+=1)}}if(a.t+=1,!0===e.end&&a.t!==a.terms.length&&!0!==e.greedy)return null;if(!0===e.greedy){if(a.t=De.getGreedy(a,t[a.r+1]),null===a.t)return null;if(e.min&&e.min>a.t)return null;if(!0===e.end&&a.start_i+a.t!==r)return null}if(!0===a.hasGroup){const t=De.getGroup(a,i,e.named);a.t>1&&e.greedy?t.length+=a.t-i:t.length++}}else{if(e.negative){let t=Object.assign({},e);if(t.negative=!1,!0===a.terms[a.t].doesMatch(t,a.start_i+a.t,a.phrase_length))return null}if(!0!==e.optional){if(a.terms[a.t].isImplicit()&&t[a.r-1]&&a.terms[a.t+1]){if(a.terms[a.t-1]&&a.terms[a.t-1].implicit===t[a.r-1].word)return null;if(a.terms[a.t+1].doesMatch(e,a.start_i+a.t,a.phrase_length)){a.t+=2;continue}}return null}}}return{match:a.terms.slice(0,a.t),groups:a.groups}},Pe$1=function(e,t,n){if(!n||0===n.length)return n;if(t.some((e=>e.end))){let t=e[e.length-1];n=n.filter((({match:e})=>-1!==e.indexOf(t)))}return n};const Ee$1=/(?:^|\s)([\!\[\^]*(?:<[^<]*>)?\/.*?[^\\\/]\/[\?\]\+\*\$~]*)(?:\s|$)/,He=/([\!\[\^]*(?:<[^<]*>)?\([^\)]+[^\\\)]\)[\?\]\+\*\$~]*)(?:\s|$)/,je$1=/ /g,Ne$1=e=>/^[\!\[\^]*(<[^<]*>)?\//.test(e)&&/\/[\?\]\+\*\$~]*$/.test(e),xe$1=function(e){return(e=e.map((e=>e.trim()))).filter((e=>e))};var Fe$1=function(e){let t=e.split(Ee$1),n=[];t.forEach((e=>{Ne$1(e)?n.push(e):n=n.concat(e.split(He))})),n=xe$1(n);let r=[];return n.forEach((e=>{(e=>/^[\!\[\^]*(<[^<]*>)?\(/.test(e)&&/\)[\?\]\+\*\$~]*$/.test(e))(e)||Ne$1(e)?r.push(e):r=r.concat(e.split(je$1))})),r=xe$1(r),r};const Ce$1=/\{([0-9]+,?[0-9]*)\}/,Be=/&&/,Ge=new RegExp(/^<\s*?(\S+)\s*?>/),ze$1=function(e){return e[e.length-1]},Ie=function(e){return e[0]},Oe$1=function(e){return e.substr(1)},Te=function(e){return e.substr(0,e.length-1)},Ve$1=function(e){return e=Oe$1(e),Te(e)},Me$1=function(e){let t={};for(let n=0;n<2;n+=1){if("$"===ze$1(e)&&(t.end=!0,e=Te(e)),"^"===Ie(e)&&(t.start=!0,e=Oe$1(e)),("["===Ie(e)||"]"===ze$1(e))&&(t.named=!0,"["===Ie(e)?t.groupType="]"===ze$1(e)?"single":"start":t.groupType="end",e=(e=e.replace(/^\[/,"")).replace(/\]$/,""),"<"===Ie(e))){const n=Ge.exec(e);n.length>=2&&(t.named=n[1],e=e.replace(n[0],""))}if("+"===ze$1(e)&&(t.greedy=!0,e=Te(e)),"*"!==e&&"*"===ze$1(e)&&"\\*"!==e&&(t.greedy=!0,e=Te(e)),"?"===ze$1(e)&&(t.optional=!0,e=Te(e)),"!"===Ie(e)&&(t.negative=!0,e=Oe$1(e)),"("===Ie(e)&&")"===ze$1(e)){Be.test(e)?(t.choices=e.split(Be),t.operator="and"):(t.choices=e.split("|"),t.operator="or"),t.choices[0]=Oe$1(t.choices[0]);let n=t.choices.length-1;t.choices[n]=Te(t.choices[n]),t.choices=t.choices.map((e=>e.trim())),t.choices=t.choices.filter((e=>e)),t.choices=t.choices.map((e=>e.split(/ /g).map(Me$1))),e=""}if("/"===Ie(e)&&"/"===ze$1(e))return e=Ve$1(e),t.regex=new RegExp(e),t;if("~"===Ie(e)&&"~"===ze$1(e))return e=Ve$1(e),t.soft=!0,t.word=e,t}return!0===Ce$1.test(e)&&(e=e.replace(Ce$1,((e,n)=>{let r=n.split(/,/g);return 1===r.length?(t.min=Number(r[0]),t.max=Number(r[0])):(t.min=Number(r[0]),t.max=Number(r[1]||999)),t.greedy=!0,t.optional=!0,""}))),"#"===Ie(e)?(t.tag=Oe$1(e),t.tag=(n=t.tag).charAt(0).toUpperCase()+n.substr(1),t):"@"===Ie(e)?(t.method=Oe$1(e),t):"."===e?(t.anything=!0,t):"*"===e?(t.anything=!0,t.greedy=!0,t.optional=!0,t):(e&&(e=(e=e.replace("\\*","*")).replace("\\.","."),t.word=e.toLowerCase()),t);var n},Je=Fe$1,Le=Me$1,Se=function(e,t={}){return e.filter((e=>e.groupType)).length>0&&(e=function(e){let t,n=!1,r=-1;for(let a=0;a{if(void 0!==e.choices&&!0===e.choices.every((e=>{if(1!==e.length)return!1;let t=e[0];return void 0!==t.word&&!0!==t.negative&&!0!==t.optional&&!0!==t.method}))){let t={};e.choices.forEach((e=>{t[e[0].word]=!0})),e.fastOr=t,delete e.choices}return e}))}(e)),e};var _e=function(e,t={}){if(null==e||""===e)return[];if("object"==typeof e){if(function(e){return"[object Array]"===Object.prototype.toString.call(e)}(e)){if(0===e.length||!e[0])return[];if("object"==typeof e[0])return e;if("string"==typeof e[0])return function(e){return[{choices:e.map((e=>[{word:e}])),operator:"or"}]}(e)}return e&&"Doc"===e.isA?function(e){if(!e||!e.list||!e.list[0])return[];let t=[];return e.list.forEach((e=>{let n=[];e.terms().forEach((e=>{n.push(e.id)})),t.push(n)})),[{idBlocks:t}]}(e):[]}"number"==typeof e&&(e=String(e));let n=Je(e);return n=n.map((e=>Le(e))),n=Se(n,t),n=function(e,t){return!0===t.fuzzy&&(t.fuzzy=.85),"number"==typeof t.fuzzy&&(e=e.map((e=>(t.fuzzy>0&&e.word&&(e.fuzzy=t.fuzzy),e.choices&&e.choices.forEach((e=>{e.forEach((e=>{e.fuzzy=t.fuzzy}))})),e)))),e}(n,t),n};const Ke=we$1,qe=$e$1,We=Pe$1,Re=_e,Ue=function(e,t){let n=[],r=t[0].idBlocks;for(let t=0;t{0!==r.length&&r.every(((n,r)=>e[t+r].id===n))&&(n.push({match:e.slice(t,t+r.length)}),t+=r.length-1)}));return n};var Qe=function(e,t,n=!1){if("string"==typeof t&&(t=Re(t)),!0===Ke(e,t))return[];const r=t.filter((e=>!0!==e.optional&&!0!==e.negative)).length;let a=e.terms(),i=[];if(t[0].idBlocks){let e=Ue(a,t);if(e&&e.length>0)return We(a,t,e)}if(!0===t[0].start){let e=qe(a,t,0,a.length);return e&&e.match&&e.match.length>0&&(e.match=e.match.filter((e=>e)),i.push(e)),We(a,t,i)}for(let e=0;ea.length);e+=1){let r=qe(a.slice(e),t,e,a.length);if(r&&r.match&&r.match.length>0&&(e+=r.match.length-1,r.match=r.match.filter((e=>e)),i.push(r),!0===n))return We(a,t,i)}return We(a,t,i)};const Ze=Qe,Xe=Qe,Ye=function(e,t){let n={};Ze(e,t).forEach((({match:e})=>{e.forEach((e=>{n[e.id]=!0}))}));let r=e.terms(),a=[],i=[];return r.forEach((e=>{!0!==n[e.id]?i.push(e):i.length>0&&(a.push(i),i=[])})),i.length>0&&a.push(i),a};ye$1.match=function(e,t=!1){let n=Xe(this,e,t);return n=n.map((({match:e,groups:t})=>{let n=this.buildFrom(e[0].id,e.length,t);return n.cache.terms=e,n})),n},ye$1.has=function(e){return Xe(this,e,!0).length>0},ye$1.not=function(e){let t=Ye(this,e);return t=t.map((e=>this.buildFrom(e[0].id,e.length))),t},ye$1.canBe=function(e,t){let n=[],r=this.terms(),a=!1;for(let i=0;ie.length>0)).map((e=>this.buildFrom(e[0].id,e.length))),n};const et=be$1,tt=ye$1;class rt{constructor(e,t,n){this.start=e,this.length=t,this.isA="Phrase",Object.defineProperty(this,"pool",{enumerable:!1,writable:!0,value:n}),Object.defineProperty(this,"cache",{enumerable:!1,writable:!0,value:{}}),Object.defineProperty(this,"groups",{enumerable:!1,writable:!0,value:{}})}}rt.prototype.buildFrom=function(e,t,n){let r=new rt(e,t,this.pool);return n&&Object.keys(n).length>0?r.groups=n:r.groups=this.groups,r},Object.assign(rt.prototype,tt),Object.assign(rt.prototype,et);const at={term:"terms"};Object.keys(at).forEach((e=>rt.prototype[e]=rt.prototype[at[e]]));var nt=rt;class it{constructor(e={}){Object.defineProperty(this,"words",{enumerable:!1,value:e})}add(e){return this.words[e.id]=e,this}get(e){return this.words[e]}remove(e){delete this.words[e]}merge(e){return Object.assign(this.words,e.words),this}stats(){return{words:Object.keys(this.words).length}}}it.prototype.clone=function(){let e=Object.keys(this.words).reduce(((e,t)=>{let n=this.words[t].clone();return e[n.id]=n,e}),{});return new it(e)};var ot=it,st=e=>{e.forEach(((t,n)=>{n>0&&(t.prev=e[n-1].id),e[n+1]&&(t.next=e[n+1].id)}))};const lt=/(\S.+?[.!?\u203D\u2E18\u203C\u2047-\u2049])(?=\s+|$)/g,ut=/\S/,ct=/[ .][A-Z]\.? *$/i,ht=/(?:\u2026|\.{2,}) *$/,dt=/((?:\r?\n|\r)+)/,gt=/[a-z0-9\u00C0-\u00FF\u00a9\u00ae\u2000-\u3300\ud000-\udfff]/i,pt=/^\s+/,mt=function(e,t,n,r){if(r.hasLetter=function(e,t){return t||gt.test(e)}(t,r.hasLetter),!r.hasLetter)return!1;if(function(e,t){return-1!==t.indexOf(".")&&ct.test(e)}(e,t))return!1;if(function(e,t){return-1!==t.indexOf(".")&&ht.test(e)}(e,t))return!1;let a=e.replace(/[.!?\u203D\u2E18\u203C\u2047-\u2049] *$/,"").split(" "),i=a[a.length-1].toLowerCase();return!n.hasOwnProperty(i)};var ft=function(e,t){let n=t.cache.abbreviations;e=e||"";let r=[],a=[];if(!(e=String(e))||"string"!=typeof e||!1===ut.test(e))return r;let i=function(e){let t=[],n=e.split(dt);for(let e=0;e0&&(r.push(t),s=a[e+1]||"",o.hasLetter=!1),a[e]=""}if(0===r.length)return[e];for(let e=1;e(e[t]=!0,e)),{});const At=function(e){return!0!==/^(re|un|micro|macro|trans|bi|mono|over)-?[^aeiou]./.test(e)&&(!0!==/^([a-z\u00C0-\u00FF/]+)(-|–|—)(like|ish|less|able)/i.test(e)&&(!0===/^([a-z\u00C0-\u00FF`"'/]+)(-|–|—)([a-z0-9\u00C0-\u00FF].*)/i.test(e)||!0===/^([0-9]{1,4})(-|–|—)([a-z\u00C0-\u00FF`"'/-]+$)/i.test(e)))},Dt=function(e){let t=[];const n=e.split(/[-–—]/);let r="-",a=e.match(/[-–—]/);a&&a[0]&&(r=a);for(let e=0;e0?(t[t.length-1]+=a,t.push(r)):t.push(a+r),a=""):a+=r}return a&&(0===t.length&&(t[0]=""),t[t.length-1]+=a),t=function(e){for(let t=1;te)),t};var xt=function(e="",t,n){let r=null;return"string"!=typeof e&&("number"==typeof e?e=String(e):function(e){return"[object Array]"===Object.prototype.toString.call(e)}(e)&&(r=e)),r=r||jt(e,t),r=r.map((e=>Nt(e))),n=n||new Et,r.map((e=>{e=e.map((e=>{let t=new $t(e);return n.add(t),t})),Ht(e);let t=new Pt(e[0].id,e.length,n);return t.cache.terms=e,t}))};const Ft=ne$1,Ct=nt,Bt=ot,Gt=st;var zt=function(e,t){let n=new Bt;return e.map(((e,r)=>{let a=e.terms.map(((a,i)=>{let s=new Ft(a.text);return s.pre=void 0!==a.pre?a.pre:"",void 0===a.post&&(a.post=" ",i>=e.terms.length-1&&(a.post=". ",r>=e.terms.length-1&&(a.post="."))),s.post=void 0!==a.post?a.post:" ",a.tags&&a.tags.forEach((e=>s.tag(e,"",t))),n.add(s),s}));return Gt(a),new Ct(a[0].id,a.length,n)}))};const It=["Person","Place","Organization"],Ot=["Noun","Verb","Adjective","Adverb","Value","QuestionWord"],Tt={Noun:"blue",Verb:"green",Negative:"green",Date:"red",Value:"red",Adjective:"magenta",Preposition:"cyan",Conjunction:"cyan",Determiner:"cyan",Adverb:"cyan"},Vt=function(e){return Object.keys(e).forEach((t=>{e[t].color?e[t].color=e[t].color:Tt[t]?e[t].color=Tt[t]:e[t].isA.some((n=>!!Tt[n]&&(e[t].color=Tt[n],!0)))})),e},Mt=function(e){return Object.keys(e).forEach((t=>{let n=e[t],r=n.isA.length;for(let t=0;tn.indexOf(e)===t))}(n.isA)})),e},Jt=function(e){let t=Object.keys(e);return t.forEach((n=>{let r=e[n];r.notA=r.notA||[],r.isA.forEach((t=>{if(e[t]&&e[t].notA){let n="string"==typeof e[t].notA?[e[t].isA]:e[t].notA||[];r.notA=r.notA.concat(n)}}));for(let a=0;an.indexOf(e)===t))}(r.notA)})),e},Lt=function(e){let t=Object.keys(e);return t.forEach((n=>{let r=e[n];r.lineage=[];for(let a=0;a{let n=e[t];n.isA=n.isA||[],"string"==typeof n.isA&&(n.isA=[n.isA]),n.notA=n.notA||[],"string"==typeof n.notA&&(n.notA=[n.notA])})),e}(e),e=Mt(e),e=Jt(e),e=Vt(e),Lt(e)};const _t={Noun:{notA:["Verb","Adjective","Adverb"]},Singular:{isA:"Noun",notA:"Plural"},ProperNoun:{isA:"Noun"},Person:{isA:["ProperNoun","Singular"],notA:["Place","Organization","Date"]},FirstName:{isA:"Person"},MaleName:{isA:"FirstName",notA:["FemaleName","LastName"]},FemaleName:{isA:"FirstName",notA:["MaleName","LastName"]},LastName:{isA:"Person",notA:["FirstName"]},NickName:{isA:"Person",notA:["FirstName","LastName"]},Honorific:{isA:"Noun",notA:["FirstName","LastName","Value"]},Place:{isA:"Singular",notA:["Person","Organization"]},Country:{isA:["Place","ProperNoun"],notA:["City"]},City:{isA:["Place","ProperNoun"],notA:["Country"]},Region:{isA:["Place","ProperNoun"]},Address:{isA:"Place"},Organization:{isA:["Singular","ProperNoun"],notA:["Person","Place"]},SportsTeam:{isA:"Organization"},School:{isA:"Organization"},Company:{isA:"Organization"},Plural:{isA:"Noun",notA:["Singular"]},Uncountable:{isA:"Noun"},Pronoun:{isA:"Noun",notA:It},Actor:{isA:"Noun",notA:It},Activity:{isA:"Noun",notA:["Person","Place"]},Unit:{isA:"Noun",notA:It},Demonym:{isA:["Noun","ProperNoun"],notA:It},Possessive:{isA:"Noun"}},Kt={Verb:{notA:["Noun","Adjective","Adverb","Value","Expression"]},PresentTense:{isA:"Verb",notA:["PastTense","FutureTense"]},Infinitive:{isA:"PresentTense",notA:["PastTense","Gerund"]},Imperative:{isA:"Infinitive"},Gerund:{isA:"PresentTense",notA:["PastTense","Copula","FutureTense"]},PastTense:{isA:"Verb",notA:["FutureTense"]},FutureTense:{isA:"Verb"},Copula:{isA:"Verb"},Modal:{isA:"Verb",notA:["Infinitive"]},PerfectTense:{isA:"Verb",notA:"Gerund"},Pluperfect:{isA:"Verb"},Participle:{isA:"PastTense"},PhrasalVerb:{isA:"Verb"},Particle:{isA:"PhrasalVerb"},Auxiliary:{notA:["Noun","Adjective","Value"]}},qt={Value:{notA:["Verb","Adjective","Adverb"]},Ordinal:{isA:"Value",notA:["Cardinal"]},Cardinal:{isA:"Value",notA:["Ordinal"]},Fraction:{isA:"Value",notA:["Noun"]},RomanNumeral:{isA:"Cardinal",notA:["Ordinal","TextValue"]},TextValue:{isA:"Value",notA:["NumericValue"]},NumericValue:{isA:"Value",notA:["TextValue"]},Money:{isA:"Cardinal"},Percent:{isA:"Value"}},Wt={Adjective:{notA:["Noun","Verb","Adverb","Value"]},Comparable:{isA:["Adjective"]},Comparative:{isA:["Adjective"]},Superlative:{isA:["Adjective"],notA:["Comparative"]},NumberRange:{},Adverb:{notA:["Noun","Verb","Adjective","Value"]},Date:{notA:["Verb","Adverb","Preposition","Adjective"]},Month:{isA:["Date","Singular"],notA:["Year","WeekDay","Time"]},WeekDay:{isA:["Date","Noun"]},Timezone:{isA:["Date","Noun"],notA:["Adjective","ProperNoun"]},Time:{isA:["Date"],notA:["AtMention"]},Determiner:{notA:Ot},Conjunction:{notA:Ot},Preposition:{notA:Ot},QuestionWord:{notA:["Determiner"]},Currency:{isA:["Noun"]},Expression:{notA:["Noun","Adjective","Verb","Adverb"]},Abbreviation:{},Url:{notA:["HashTag","PhoneNumber","Verb","Adjective","Value","AtMention","Email"]},PhoneNumber:{notA:["HashTag","Verb","Adjective","Value","AtMention","Email"]},HashTag:{},AtMention:{isA:["Noun"],notA:["HashTag","Verb","Adjective","Value","Email"]},Emoji:{notA:["HashTag","Verb","Adjective","Value","AtMention"]},Emoticon:{notA:["HashTag","Verb","Adjective","Value","AtMention"]},Email:{notA:["HashTag","Verb","Adjective","Value","AtMention"]},Acronym:{notA:["Plural","RomanNumeral"]},Negative:{notA:["Noun","Adjective","Value"]},Condition:{notA:["Verb","Adjective","Noun","Value"]}},Rt=St,Ut=function(e,t){Object.keys(e).forEach((n=>{t[n]=e[n]}))};var Qt=(()=>{let e={};return Ut(_t,e),Ut(Kt,e),Ut(qt,e),Ut(Wt,e),e=Rt(e),e})();const Zt="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ",Xt=Zt.split("").reduce((function(e,t,n){return e[t]=n,e}),{});var Yt=function(e){if(void 0!==Xt[e])return Xt[e];let t=0,n=1,r=36,a=1;for(;n=0;n--,a*=36){let r=e.charCodeAt(n)-48;r>10&&(r-=7),t+=r*a}return t};const er=function(e,t,n){const r=Yt(t);return r{let i=e.nodes[r];"!"===i[0]&&(t.push(a),i=i.slice(1));const s=i.split(/([A-Z0-9,]+)/g);for(let i=0;i{const n=t.split("¦");return e[n[0]]=n[1],e}),{}),n={};return Object.keys(t).forEach((function(e){const r=tr(t[e]);"true"===e&&(e=!0);for(let t=0;t{e[t]=["Abbreviation","Unit"]},Cardinal:(e,t)=>{e[t]=["TextValue","Cardinal"]},TextOrdinal:(e,t)=>{e[t]=["Ordinal","TextValue"],e[t+"s"]=["TextValue","Fraction"]},Singular:(e,t,n)=>{e[t]="Singular";let r=n.transforms.toPlural(t,n);e[r]=e[r]||"Plural"},Infinitive:(e,t,n)=>{e[t]="Infinitive";let r=n.transforms.conjugate(t,n),a=Object.keys(r);for(let t=0;t{e[t]="Comparable";let r=n.transforms.adjectives(t),a=Object.keys(r);for(let t=0;t{e[t]=["PhrasalVerb","Infinitive"];let r=t.split(" "),a=n.transforms.conjugate(r[0],n),i=Object.keys(a);for(let t=0;t{e[t]="Demonym";let r=n.transforms.toPlural(t,n);e[r]=e[r]||["Demonym","Plural"]}},or=function(e,t,n){Object.keys(e).forEach((r=>{let a=e[r];"Abbreviation"!==a&&"Unit"!==a||(n.cache.abbreviations[r]=!0);let i=r.split(" ");i.length>1&&(n.hasCompound[i[0]]=!0),void 0===ir[a]?void 0!==t[r]?("string"==typeof t[r]&&(t[r]=[t[r]]),"string"==typeof a?t[r].push(a):t[r]=t[r].concat(a)):t[r]=a:ir[a](t,r,n)}))};var sr={buildOut:function(e){let t=Object.assign({},nr);return Object.keys(rr).forEach((n=>{let r=ar(rr[n]);Object.keys(r).forEach((e=>{r[e]=n})),or(r,t,e)})),t},addWords:or},lr=function(e){let t=e.irregulars.nouns,n=Object.keys(t);for(let r=0;r{e.words[i[t]]=e.words[i[t]]||t,"Participle"===e.words[i[t]]&&(e.words[i[t]]=t)}))}};const ur={g:"Gerund",prt:"Participle",perf:"PerfectTense",pst:"PastTense",fut:"FuturePerfect",pres:"PresentTense",pluperf:"Pluperfect",a:"Actor"};let cr={act:{a:"_or"},ache:{pst:"ached",g:"aching"},age:{g:"ageing",pst:"aged",pres:"ages"},aim:{a:"_er",g:"_ing",pst:"_ed"},arise:{prt:"_n",pst:"arose"},babysit:{a:"_ter",pst:"babysat"},ban:{a:"",g:"_ning",pst:"_ned"},be:{a:"",g:"am",prt:"been",pst:"was",pres:"is"},beat:{a:"_er",g:"_ing",prt:"_en"},become:{prt:"_"},begin:{g:"_ning",prt:"begun",pst:"began"},being:{g:"are",pst:"were",pres:"are"},bend:{prt:"bent"},bet:{a:"_ter",prt:"_"},bind:{pst:"bound"},bite:{g:"biting",prt:"bitten",pst:"bit"},bleed:{pst:"bled",prt:"bled"},blow:{prt:"_n",pst:"blew"},boil:{a:"_er"},brake:{prt:"broken"},break:{pst:"broke"},breed:{pst:"bred"},bring:{pst:"brought",prt:"brought"},broadcast:{pst:"_"},budget:{pst:"_ed"},build:{pst:"built",prt:"built"},burn:{prt:"_ed"},burst:{prt:"_"},buy:{pst:"bought",prt:"bought"},can:{a:"",fut:"_",g:"",pst:"could",perf:"could",pluperf:"could",pres:"_"},catch:{pst:"caught"},choose:{g:"choosing",prt:"chosen",pst:"chose"},cling:{prt:"clung"},come:{prt:"_",pst:"came",g:"coming"},compete:{a:"competitor",g:"competing",pst:"_d"},cost:{pst:"_"},creep:{prt:"crept"},cut:{prt:"_"},deal:{pst:"_t",prt:"_t"},develop:{a:"_er",g:"_ing",pst:"_ed"},die:{g:"dying",pst:"_d"},dig:{g:"_ging",pst:"dug",prt:"dug"},dive:{prt:"_d"},do:{pst:"did",pres:"_es"},draw:{prt:"_n",pst:"drew"},dream:{prt:"_t"},drink:{prt:"drunk",pst:"drank"},drive:{g:"driving",prt:"_n",pst:"drove"},drop:{g:"_ping",pst:"_ped"},eat:{a:"_er",g:"_ing",prt:"_en",pst:"ate"},edit:{pst:"_ed",g:"_ing"},egg:{pst:"_ed"},fall:{prt:"_en",pst:"fell"},feed:{prt:"fed",pst:"fed"},feel:{a:"_er",pst:"felt"},fight:{pst:"fought",prt:"fought"},find:{pst:"found"},flee:{g:"_ing",prt:"fled"},fling:{prt:"flung"},fly:{prt:"flown",pst:"flew"},forbid:{pst:"forbade"},forget:{g:"_ing",prt:"forgotten",pst:"forgot"},forgive:{g:"forgiving",prt:"_n",pst:"forgave"},free:{a:"",g:"_ing"},freeze:{g:"freezing",prt:"frozen",pst:"froze"},get:{pst:"got",prt:"gotten"},give:{g:"giving",prt:"_n",pst:"gave"},go:{prt:"_ne",pst:"went",pres:"goes"},grow:{prt:"_n"},guide:{pst:"_d"},hang:{pst:"hung",prt:"hung"},have:{g:"having",pst:"had",prt:"had",pres:"has"},hear:{pst:"_d",prt:"_d"},hide:{prt:"hidden",pst:"hid"},hit:{prt:"_"},hold:{pst:"held",prt:"held"},hurt:{pst:"_",prt:"_"},ice:{g:"icing",pst:"_d"},imply:{pst:"implied",pres:"implies"},is:{a:"",g:"being",pst:"was",pres:"_"},keep:{prt:"kept"},kneel:{prt:"knelt"},know:{prt:"_n"},lay:{pst:"laid",prt:"laid"},lead:{pst:"led",prt:"led"},leap:{prt:"_t"},leave:{pst:"left",prt:"left"},lend:{prt:"lent"},lie:{g:"lying",pst:"lay"},light:{pst:"lit",prt:"lit"},log:{g:"_ging",pst:"_ged"},loose:{prt:"lost"},lose:{g:"losing",pst:"lost"},make:{pst:"made",prt:"made"},mean:{pst:"_t",prt:"_t"},meet:{a:"_er",g:"_ing",pst:"met",prt:"met"},miss:{pres:"_"},name:{g:"naming"},patrol:{g:"_ling",pst:"_led"},pay:{pst:"paid",prt:"paid"},prove:{prt:"_n"},puke:{g:"puking"},put:{prt:"_"},quit:{prt:"_"},read:{pst:"_",prt:"_"},ride:{prt:"ridden"},reside:{pst:"_d"},ring:{pst:"rang",prt:"rung"},rise:{fut:"will have _n",g:"rising",prt:"_n",pst:"rose",pluperf:"had _n"},rub:{g:"_bing",pst:"_bed"},run:{g:"_ning",prt:"_",pst:"ran"},say:{pst:"said",prt:"said",pres:"_s"},seat:{pst:"sat",prt:"sat"},see:{g:"_ing",prt:"_n",pst:"saw"},seek:{prt:"sought"},sell:{pst:"sold",prt:"sold"},send:{prt:"sent"},set:{prt:"_"},sew:{prt:"_n"},shake:{prt:"_n"},shave:{prt:"_d"},shed:{g:"_ding",pst:"_",pres:"_s"},shine:{pst:"shone",prt:"shone"},shoot:{pst:"shot",prt:"shot"},show:{pst:"_ed"},shut:{prt:"_"},sing:{prt:"sung",pst:"sang"},sink:{pst:"sank",pluperf:"had sunk"},sit:{pst:"sat"},ski:{pst:"_ied"},slay:{prt:"slain"},sleep:{prt:"slept"},slide:{pst:"slid",prt:"slid"},smash:{pres:"_es"},sneak:{prt:"snuck"},speak:{fut:"will have spoken",prt:"spoken",pst:"spoke",perf:"have spoken",pluperf:"had spoken"},speed:{prt:"sped"},spend:{prt:"spent"},spill:{prt:"_ed",pst:"spilt"},spin:{g:"_ning",pst:"spun",prt:"spun"},spit:{prt:"spat"},split:{prt:"_"},spread:{pst:"_"},spring:{prt:"sprung"},stand:{pst:"stood"},steal:{a:"_er",pst:"stole"},stick:{pst:"stuck"},sting:{pst:"stung"},stink:{pst:"stunk",prt:"stunk"},stream:{a:"_er"},strew:{prt:"_n"},strike:{g:"striking",pst:"struck"},suit:{a:"_er",g:"_ing",pst:"_ed"},sware:{prt:"sworn"},swear:{pst:"swore"},sweep:{prt:"swept"},swim:{g:"_ming",pst:"swam"},swing:{pst:"swung"},take:{fut:"will have _n",pst:"took",perf:"have _n",pluperf:"had _n"},teach:{pst:"taught",pres:"_es"},tear:{pst:"tore"},tell:{pst:"told"},think:{pst:"thought"},thrive:{prt:"_d"},tie:{g:"tying",pst:"_d"},undergo:{prt:"_ne"},understand:{pst:"understood"},upset:{prt:"_"},wait:{a:"_er",g:"_ing",pst:"_ed"},wake:{pst:"woke"},wear:{pst:"wore"},weave:{prt:"woven"},wed:{pst:"wed"},weep:{prt:"wept"},win:{g:"_ning",pst:"won"},wind:{prt:"wound"},withdraw:{pst:"withdrew"},wring:{prt:"wrung"},write:{g:"writing",prt:"written",pst:"wrote"}},hr=Object.keys(cr);for(let e=0;e{let r=cr[t][e];r=r.replace("_",t),n[ur[e]]=r})),cr[t]=n}var dr=cr;const gr={b:[{reg:/([^aeiou][aeiou])b$/i,repl:{pr:"$1bs",pa:"$1bbed",gr:"$1bbing"}}],d:[{reg:/(end)$/i,repl:{pr:"$1s",pa:"ent",gr:"$1ing",ar:"$1er"}},{reg:/(eed)$/i,repl:{pr:"$1s",pa:"$1ed",gr:"$1ing",ar:"$1er"}},{reg:/(ed)$/i,repl:{pr:"$1s",pa:"$1ded",ar:"$1der",gr:"$1ding"}},{reg:/([^aeiou][ou])d$/i,repl:{pr:"$1ds",pa:"$1dded",gr:"$1dding"}}],e:[{reg:/(eave)$/i,repl:{pr:"$1s",pa:"$1d",gr:"eaving",ar:"$1r"}},{reg:/(ide)$/i,repl:{pr:"$1s",pa:"ode",gr:"iding",ar:"ider"}},{reg:/(t|sh?)(ake)$/i,repl:{pr:"$1$2s",pa:"$1ook",gr:"$1aking",ar:"$1$2r"}},{reg:/w(ake)$/i,repl:{pr:"w$1s",pa:"woke",gr:"waking",ar:"w$1r"}},{reg:/m(ake)$/i,repl:{pr:"m$1s",pa:"made",gr:"making",ar:"m$1r"}},{reg:/(a[tg]|i[zn]|ur|nc|gl|is)e$/i,repl:{pr:"$1es",pa:"$1ed",gr:"$1ing"}},{reg:/([bd]l)e$/i,repl:{pr:"$1es",pa:"$1ed",gr:"$1ing"}},{reg:/(om)e$/i,repl:{pr:"$1es",pa:"ame",gr:"$1ing"}}],g:[{reg:/([^aeiou][aou])g$/i,repl:{pr:"$1gs",pa:"$1gged",gr:"$1gging"}}],h:[{reg:/(..)([cs]h)$/i,repl:{pr:"$1$2es",pa:"$1$2ed",gr:"$1$2ing"}}],k:[{reg:/(ink)$/i,repl:{pr:"$1s",pa:"unk",gr:"$1ing",ar:"$1er"}}],m:[{reg:/([^aeiou][aeiou])m$/i,repl:{pr:"$1ms",pa:"$1mmed",gr:"$1mming"}}],n:[{reg:/(en)$/i,repl:{pr:"$1s",pa:"$1ed",gr:"$1ing"}}],p:[{reg:/(e)(ep)$/i,repl:{pr:"$1$2s",pa:"$1pt",gr:"$1$2ing",ar:"$1$2er"}},{reg:/([^aeiou][aeiou])p$/i,repl:{pr:"$1ps",pa:"$1pped",gr:"$1pping"}},{reg:/([aeiu])p$/i,repl:{pr:"$1ps",pa:"$1p",gr:"$1pping"}}],r:[{reg:/([td]er)$/i,repl:{pr:"$1s",pa:"$1ed",gr:"$1ing"}},{reg:/(er)$/i,repl:{pr:"$1s",pa:"$1ed",gr:"$1ing"}}],s:[{reg:/(ish|tch|ess)$/i,repl:{pr:"$1es",pa:"$1ed",gr:"$1ing"}}],t:[{reg:/(ion|end|e[nc]t)$/i,repl:{pr:"$1s",pa:"$1ed",gr:"$1ing"}},{reg:/(.eat)$/i,repl:{pr:"$1s",pa:"$1ed",gr:"$1ing"}},{reg:/([aeiu])t$/i,repl:{pr:"$1ts",pa:"$1t",gr:"$1tting"}},{reg:/([^aeiou][aeiou])t$/i,repl:{pr:"$1ts",pa:"$1tted",gr:"$1tting"}}],w:[{reg:/(.llow)$/i,repl:{pr:"$1s",pa:"$1ed"}},{reg:/(..)(ow)$/i,repl:{pr:"$1$2s",pa:"$1ew",gr:"$1$2ing",prt:"$1$2n"}}],y:[{reg:/(i|f|rr)y$/i,repl:{pr:"$1ies",pa:"$1ied",gr:"$1ying"}}],z:[{reg:/([aeiou]zz)$/i,repl:{pr:"$1es",pa:"$1ed",gr:"$1ing"}}]},pr={pr:"PresentTense",pa:"PastTense",gr:"Gerund",prt:"Participle",ar:"Actor"},mr=function(e,t){let n={},r=Object.keys(t.repl);for(let a=0;a"e"===e.charAt(e.length-1)?e.replace(/e$/,"ing"):e+"ing",PresentTense:e=>"s"===e.charAt(e.length-1)?e+"es":!0===fr.test(e)?e.slice(0,-1)+"ies":e+"s",PastTense:e=>"e"===e.charAt(e.length-1)?e+"d":"ed"===e.substr(-2)?e:!0===fr.test(e)?e.slice(0,-1)+"ied":e+"ed"};var vr=function(e="",t){let n={};return t&&t.irregulars&&!0===t.irregulars.verbs.hasOwnProperty(e)&&(n=Object.assign({},t.irregulars.verbs[e])),n=Object.assign({},br(e),n),void 0===n.Gerund&&(n.Gerund=yr.Gerund(e)),void 0===n.PastTense&&(n.PastTense=yr.PastTense(e)),void 0===n.PresentTense&&(n.PresentTense=yr.PresentTense(e)),n};const wr=[/ght$/,/nge$/,/ough$/,/ain$/,/uel$/,/[au]ll$/,/ow$/,/oud$/,/...p$/],kr=[/ary$/],Ar={nice:"nicest",late:"latest",hard:"hardest",inner:"innermost",outer:"outermost",far:"furthest",worse:"worst",bad:"worst",good:"best",big:"biggest",large:"largest"},Dr=[{reg:/y$/i,repl:"iest"},{reg:/([aeiou])t$/i,repl:"$1ttest"},{reg:/([aeou])de$/i,repl:"$1dest"},{reg:/nge$/i,repl:"ngest"},{reg:/([aeiou])te$/i,repl:"$1test"}],$r=[/ght$/,/nge$/,/ough$/,/ain$/,/uel$/,/[au]ll$/,/ow$/,/old$/,/oud$/,/e[ae]p$/],Pr=[/ary$/,/ous$/],Er={grey:"greyer",gray:"grayer",green:"greener",yellow:"yellower",red:"redder",good:"better",well:"better",bad:"worse",sad:"sadder",big:"bigger"},Hr=[{reg:/y$/i,repl:"ier"},{reg:/([aeiou])t$/i,repl:"$1tter"},{reg:/([aeou])de$/i,repl:"$1der"},{reg:/nge$/i,repl:"nger"}],jr={toSuperlative:function(e){if(Ar.hasOwnProperty(e))return Ar[e];for(let t=0;t(e[a[t]]=t,e)),{}));var a;if(r.hasOwnProperty(e))return r[e];for(let t=0;t(Ir[t].forEach((n=>e[n]=t)),e)),{});const Or=zr,Tr=Ir,Vr=Qt,Mr=sr,Jr=lr,Lr=St,Sr={nouns:{addendum:"addenda",alga:"algae",alumna:"alumnae",alumnus:"alumni",analysis:"analyses",antenna:"antennae",appendix:"appendices",avocado:"avocados",axis:"axes",bacillus:"bacilli",barracks:"barracks",beau:"beaux",bus:"buses",cactus:"cacti",chateau:"chateaux",child:"children",circus:"circuses",clothes:"clothes",corpus:"corpora",criterion:"criteria",curriculum:"curricula",database:"databases",deer:"deer",diagnosis:"diagnoses",echo:"echoes",embargo:"embargoes",epoch:"epochs",foot:"feet",formula:"formulae",fungus:"fungi",genus:"genera",goose:"geese",halo:"halos",hippopotamus:"hippopotami",index:"indices",larva:"larvae",leaf:"leaves",libretto:"libretti",loaf:"loaves",man:"men",matrix:"matrices",memorandum:"memoranda",modulus:"moduli",mosquito:"mosquitoes",mouse:"mice",nebula:"nebulae",nucleus:"nuclei",octopus:"octopi",opus:"opera",ovum:"ova",ox:"oxen",parenthesis:"parentheses",person:"people",phenomenon:"phenomena",prognosis:"prognoses",quiz:"quizzes",radius:"radii",referendum:"referenda",rodeo:"rodeos",sex:"sexes",shoe:"shoes",sombrero:"sombreros",stimulus:"stimuli",stomach:"stomachs",syllabus:"syllabi",synopsis:"synopses",tableau:"tableaux",thesis:"theses",thief:"thieves",tooth:"teeth",tornado:"tornados",tuxedo:"tuxedos",vertebra:"vertebrae"},verbs:dr},_r={conjugate:vr,adjectives:Nr,toPlural:Cr,toSingular:Gr,toInfinitive:function(e,t,n){if(!e)return"";if(!0===t.words.hasOwnProperty(e)){let n=t.irregulars.verbs,r=Object.keys(n);for(let t=0;t{let r=e[n];n=n.toLowerCase().trim(),t[n]=r})),Mr.addWords(t,this.words,this)}addConjugations(e){return Object.assign(this.irregulars.verbs,e),this}addPlurals(e){return Object.assign(this.irregulars.nouns,e),this}addTags(e){return e=Object.assign({},e),this.tags=Object.assign(this.tags,e),this.tags=Lr(this.tags),this}postProcess(e){return this.taggers.push(e),this}stats(){return{words:Object.keys(this.words).length,plurals:Object.keys(this.irregulars.nouns).length,conjugations:Object.keys(this.irregulars.verbs).length,compounds:Object.keys(this.hasCompound).length,postProcessors:this.taggers.length}}}const Wr=function(e){return JSON.parse(JSON.stringify(e))};qr.prototype.clone=function(){let e=new qr;return e.words=Object.assign({},this.words),e.hasCompound=Object.assign({},this.hasCompound),e.irregulars=Wr(this.irregulars),e.tags=Wr(this.tags),e.transforms=this.transforms,e.taggers=this.taggers,e};var Rr=qr,Ur={};!function(e){e.all=function(){return this.parents()[0]||this},e.parent=function(){return this.from?this.from:this},e.parents=function(e){let t=[];const n=function(e){e.from&&(t.push(e.from),n(e.from))};return n(this),t=t.reverse(),"number"==typeof e?t[e]:t},e.clone=function(e){let t=this.list.map((t=>t.clone(e)));return this.buildFrom(t)},e.wordCount=function(){return this.list.reduce(((e,t)=>e+t.wordCount()),0)},e.wordcount=e.wordCount}(Ur);var Qr={};!function(e){e.first=function(e){return void 0===e?this.get(0):this.slice(0,e)},e.last=function(e){if(void 0===e)return this.get(this.list.length-1);let t=this.list.length;return this.slice(t-e,t)},e.slice=function(e,t){let n=this.list.slice(e,t);return this.buildFrom(n)},e.eq=function(e){let t=this.list[e];return void 0===t?this.buildFrom([]):this.buildFrom([t])},e.get=e.eq,e.firstTerms=function(){return this.match("^.")},e.firstTerm=e.firstTerms,e.lastTerms=function(){return this.match(".$")},e.lastTerm=e.lastTerms,e.termList=function(e){let t=[];for(let n=0;nr.groups[e]));for(let e=0;ea.groups[e].group===t)),i.forEach((e=>{n.push(a.buildFrom(a.groups[e].start,a.groups[e].length))}))}return e.buildFrom(n)}(this,e)||this.buildFrom([]))},e.group=e.groups,e.sentences=function(e){let t=[];return this.list.forEach((e=>{t.push(e.fullSentence())})),"number"==typeof e?this.buildFrom([t[e]]):this.buildFrom(t)},e.sentence=e.sentences}(Qr);var Zr={},Xr=function(e,t){if(e._cache&&!0===e._cache.set){let{words:n,tags:r}=function(e){let t=[],n=[];return e.forEach((e=>{!0!==e.optional&&!0!==e.negative&&(void 0!==e.tag&&t.push(e.tag),void 0!==e.word&&n.push(e.word))})),{tags:t,words:n}}(t);for(let t=0;te.concat(t.match(a))),[]);return void 0!==r.group&&null!==r.group&&""!==r.group?this.buildFrom(i).groups(r.group):this.buildFrom(i)},e.not=function(e,r={}){let a=t(e,r);if(0===a.length||!1===n(this,a))return this;let i=this.list.reduce(((e,t)=>e.concat(t.not(a))),[]);return this.buildFrom(i)},e.matchOne=function(e,r={}){let a=t(e,r);if(!1===n(this,a))return this.buildFrom([]);for(let e=0;e!0===e.has(a)));return this.buildFrom(i)},e.ifNo=function(e,n={}){let r=t(e,n),a=this.list.filter((e=>!1===e.has(r)));return this.buildFrom(a)},e.has=function(e,r={}){let a=t(e,r);return!1!==n(this,a)&&this.list.some((e=>!0===e.has(a)))},e.lookAhead=function(e,n={}){e||(e=".*");let r=t(e,n),a=[];return this.list.forEach((e=>{a=a.concat(e.lookAhead(r))})),a=a.filter((e=>e)),this.buildFrom(a)},e.lookAfter=e.lookAhead,e.lookBehind=function(e,n={}){e||(e=".*");let r=t(e,n),a=[];return this.list.forEach((e=>{a=a.concat(e.lookBehind(r))})),a=a.filter((e=>e)),this.buildFrom(a)},e.lookBefore=e.lookBehind,e.before=function(e,n={}){let r=t(e,n),a=this.if(r).list.map((e=>{let t=e.terms().map((e=>e.id)),n=e.match(r)[0],a=t.indexOf(n.start);return 0===a||-1===a?null:e.buildFrom(e.start,a)}));return a=a.filter((e=>null!==e)),this.buildFrom(a)},e.after=function(e,n={}){let r=t(e,n),a=this.if(r).list.map((e=>{let t=e.terms(),n=t.map((e=>e.id)),a=e.match(r)[0],i=n.indexOf(a.start);if(-1===i||!t[i+a.length])return null;let s=t[i+a.length].id,o=e.length-i-a.length;return e.buildFrom(s,o)}));return a=a.filter((e=>null!==e)),this.buildFrom(a)},e.hasAfter=function(e,t={}){return this.filter((n=>n.lookAfter(e,t).found))},e.hasBefore=function(e,t={}){return this.filter((n=>n.lookBefore(e,t).found))}}(Zr);var Yr={};const ea=function(e,t,n,r){let a=[];"string"==typeof e&&(a=e.split(" ")),t.list.forEach((i=>{let s=i.terms();!0===n&&(s=s.filter((n=>n.canBe(e,t.world)))),s.forEach(((n,i)=>{a.length>1?a[i]&&"."!==a[i]&&n.tag(a[i],r,t.world):n.tag(e,r,t.world)}))}))};Yr.tag=function(e,t){return e?(ea(e,this,!1,t),this):this},Yr.tagSafe=function(e,t){return e?(ea(e,this,!0,t),this):this},Yr.unTag=function(e,t){return this.list.forEach((n=>{n.terms().forEach((n=>n.unTag(e,t,this.world)))})),this},Yr.canBe=function(e){if(!e)return this;let t=this.world,n=this.list.reduce(((n,r)=>n.concat(r.canBe(e,t))),[]);return this.buildFrom(n)};var ta={map:function(e){if(!e)return this;let t=this.list.map(((t,n)=>{let r=this.buildFrom([t]);r.from=null;let a=e(r,n);return a&&a.list&&a.list[0]?a.list[0]:a}));return t=t.filter((e=>e)),0===t.length?this.buildFrom(t):"object"!=typeof t[0]||"Phrase"!==t[0].isA?t:this.buildFrom(t)},forEach:function(e,t){return e?(this.list.forEach(((n,r)=>{let a=this.buildFrom([n]);!0===t&&(a.from=null),e(a,r)})),this):this},filter:function(e){if(!e)return this;let t=this.list.filter(((t,n)=>{let r=this.buildFrom([t]);return r.from=null,e(r,n)}));return this.buildFrom(t)},find:function(e){if(!e)return this;let t=this.list.find(((t,n)=>{let r=this.buildFrom([t]);return r.from=null,e(r,n)}));return t?this.buildFrom([t]):void 0},some:function(e){return e?this.list.some(((t,n)=>{let r=this.buildFrom([t]);return r.from=null,e(r,n)})):this},random:function(e){if(!this.found)return this;let t=Math.floor(Math.random()*this.list.length);if(void 0===e){let e=[this.list[t]];return this.buildFrom(e)}return t+e>this.length&&(t=this.length-e,t=t<0?0:t),this.slice(t,t+e)}},ra={},aa=function(e,t,n){let r=function(e,t=[]){let n={};return e.forEach(((e,r)=>{let a=!0;void 0!==t[r]&&(a=t[r]);let i=function(e){return e.split(/[ -]/g)}(e=(e=(e||"").toLowerCase()).replace(/[,;.!?]+$/,"")).map((e=>e.trim()));n[i[0]]=n[i[0]]||{},1===i.length?n[i[0]].value=a:(n[i[0]].more=n[i[0]].more||[],n[i[0]].more.push({rest:i.slice(1),value:a}))})),n}(e,t),a=[];for(let e=0;ee.reduced));for(let e=0;e{void 0!==i[e+n.rest.length]&&!0===n.rest.every(((t,n)=>t===i[e+n+1]))&&a.push({id:t.terms()[e].id,value:n.value,length:n.rest.length+1})})),void 0!==r[i[e]].value&&a.push({id:t.terms()[e].id,value:r[i[e]].value,length:1}))}return a};!function(e){const t=aa;e.lookup=function(e){let n=[],r=(a=e)&&"[object Object]"===Object.prototype.toString.call(a);var a;!0===r&&(e=Object.keys(e).map((t=>(n.push(e[t]),t)))),"string"==typeof e&&(e=[e]),!0!==this._cache.set&&this.cache();let i=t(e,n,this),s=this.list[0];if(!0===r){let e={};return i.forEach((t=>{e[t.value]=e[t.value]||[],e[t.value].push(s.buildFrom(t.id,t.length))})),Object.keys(e).forEach((t=>{e[t]=this.buildFrom(e[t])})),e}return i=i.map((e=>s.buildFrom(e.id,e.length))),this.buildFrom(i)},e.lookUp=e.lookup}(ra);var na={cache:function(e){e=e||{};let t={},n={};return this._cache.words=t,this._cache.tags=n,this._cache.set=!0,this.list.forEach(((r,a)=>{r.cache=r.cache||{},r.terms().forEach((r=>{t[r.reduced]&&!t.hasOwnProperty(r.reduced)||(t[r.reduced]=t[r.reduced]||[],t[r.reduced].push(a),Object.keys(r.tags).forEach((e=>{n[e]=n[e]||[],n[e].push(a)})),e.root&&(r.setRoot(this.world),t[r.root]=[a]))}))})),this},uncache:function(){return this._cache={},this.list.forEach((e=>{e.cache={}})),this.parents().forEach((e=>{e._cache={},e.list.forEach((e=>{e.cache={}}))})),this}},ia={};const oa=xt;ia.replaceWith=function(e,t={}){return e?(!0===t&&(t={keepTags:!0}),!1===t&&(t={keepTags:!1}),t=t||{},this.uncache(),this.list.forEach((n=>{let r,a=e;if("function"==typeof e&&(a=e(n)),a&&"object"==typeof a&&"Doc"===a.isA)r=a.list,this.pool().merge(a.pool());else{if("string"!=typeof a)return;{!1!==t.keepCase&&n.terms(0).isTitleCase()&&(a=(i=a).charAt(0).toUpperCase()+i.substr(1)),r=oa(a,this.world,this.pool());let e=this.buildFrom(r);e.tagger(),r=e.list}}var i;if(!0===t.keepTags){let e=n.json({terms:{tags:!0}}).terms;r[0].terms().forEach(((t,n)=>{e[n]&&t.tagSafe(e[n].tags,"keptTag",this.world)}))}n.replace(r[0],this)})),this):this.delete()},ia.replace=function(e,t,n){return void 0===t?this.replaceWith(e,n):(this.match(e).replaceWith(t,n),this)};var sa={};!function(e){const t=xt,n=function(e){return e&&"[object Object]"===Object.prototype.toString.call(e)},r=function(e,n){let r=t(e,n.world)[0],a=n.buildFrom([r]);return a.tagger(),n.list=a.list,n};e.append=function(e=""){return e?this.found?(this.uncache(),this.list.forEach((r=>{let a;n(e)&&"Doc"===e.isA?a=e.list[0].clone():"string"==typeof e&&(a=t(e,this.world,this.pool())[0]),this.buildFrom([a]).tagger(),r.append(a,this)})),this):r(e,this):this},e.insertAfter=e.append,e.insertAt=e.append,e.prepend=function(e){return e?this.found?(this.uncache(),this.list.forEach((r=>{let a;n(e)&&"Doc"===e.isA?a=e.list[0].clone():"string"==typeof e&&(a=t(e,this.world,this.pool())[0]),this.buildFrom([a]).tagger(),r.prepend(a,this)})),this):r(e,this):this},e.insertBefore=e.prepend,e.concat=function(){this.uncache();let e=this.list.slice(0);for(let n=0;ne.delete(this))),this},e.remove=e.delete}(sa);var la={};const ua={clean:!0,reduced:!0,root:!0};la.text=function(e){e=e||{};let t=!1;0===this.parents().length&&(t=!0),("root"===e||"object"==typeof e&&e.root)&&this.list.forEach((e=>{e.terms().forEach((e=>{null===e.root&&e.setRoot(this.world)}))}));let n=this.list.reduce(((n,r,a)=>{const i=!t&&0===a,s=!t&&a===this.list.length-1;return n+r.text(e,i,s)}),"");return!0!==ua[e]&&!0!==e.reduced&&!0!==e.clean&&!0!==e.root||(n=n.trim()),n};var ca={},ha=function(e,t,n){let r=function(e){let t=0,n=0,r={};return e.termList().forEach((e=>{r[e.id]={index:n,start:t+e.pre.length,length:e.text.length},t+=e.pre.length+e.text.length+e.post.length,n+=1})),r}(e.all());(n.terms.index||n.index)&&t.forEach((e=>{e.terms.forEach((e=>{e.index=r[e.id].index})),e.index=e.terms[0].index})),(n.terms.offset||n.offset)&&t.forEach((e=>{e.terms.forEach((e=>{e.offset=r[e.id]||{}})),e.offset={index:e.terms[0].offset.index,start:e.terms[0].offset.start-e.text.indexOf(e.terms[0].text),length:e.text.length}}))};!function(e){const t=ha,n={text:!0,terms:!0,trim:!0};e.json=function(e={}){if("number"==typeof e&&this.list[e])return this.list[e].json(n);!0===(e=function(e){return(e=Object.assign({},n,e)).unique&&(e.reduced=!0),e.offset&&(e.text=!0,e.terms&&!0!==e.terms||(e.terms={}),e.terms.offset=!0),(e.index||e.terms.index)&&(e.terms=!0===e.terms?{}:e.terms,e.terms.id=!0),e}(e)).root&&this.list.forEach((e=>{e.terms().forEach((e=>{null===e.root&&e.setRoot(this.world)}))}));let r=this.list.map((t=>t.json(e,this.world)));if((e.terms.offset||e.offset||e.terms.index||e.index)&&t(this,r,e),e.frequency||e.freq||e.count){let e={};this.list.forEach((t=>{let n=t.text("reduced");e[n]=e[n]||0,e[n]+=1})),this.list.forEach(((t,n)=>{r[n].count=e[t.text("reduced")]}))}if(e.unique){let e={};r=r.filter((t=>!0!==e[t.reduced]&&(e[t.reduced]=!0,!0)))}return r},e.data=e.json}(ca);var da={},ga={exports:{}};!function(e){const t="",n=function(e,t){for(e=e.toString();e.length{console.log('\n%c"'+e.text()+'"',"color: #e6d7b3;"),e.terms().forEach((e=>{let a=Object.keys(e.tags),i=e.text||"-";e.implicit&&(i="["+e.implicit+"]");let s="'"+i+"'";s=n(s,8);let o=a.find((e=>t[e]&&t[e].color)),l="steelblue";t[o]&&(l=t[o].color,l=r[l]),console.log(` ${s} - %c${a.join(", ")}`,`color: ${l||"steelblue"};`)}))}))}(e),e):(console.log(a.blue("=====")),e.list.forEach((t=>{console.log(a.blue(" -----")),t.terms().forEach((t=>{let r=Object.keys(t.tags),i=t.text||"-";t.implicit&&(i="["+t.implicit+"]"),i=a.yellow(i);let s="'"+i+"'";s=n(s,18);let o=a.blue(" | ")+s+" - "+function(e,t){return(e=e.map((e=>{if(!t.tags.hasOwnProperty(e))return e;const n=t.tags[e].color||"blue";return a[n](e)}))).join(", ")}(r,e.world);console.log(o)}))})),console.log(""),e)}}();const pa=ga.exports,ma=function(e){let t=e.json({text:!1,terms:!1,reduced:!0}),n={};t.forEach((e=>{n[e.reduced]||(e.count=0,n[e.reduced]=e),n[e.reduced].count+=1}));let r=Object.keys(n).map((e=>n[e]));return r.sort(((e,t)=>e.count>t.count?-1:e.counte.text)).filter((e=>e));if("freq"===e||"frequency"===e)return ma(this);if("terms"===e){let e=[];return this.json({text:!1,terms:{text:!0}}).forEach((t=>{let n=t.terms.map((e=>e.text));n=n.filter((e=>e)),e=e.concat(n)})),e}return"tags"===e?this.list.map((e=>e.terms().reduce(((e,t)=>(e[t.clean||t.implicit]=Object.keys(t.tags),e)),{}))):"debug"===e?(pa(this),this):this.text()};var fa={};const ba={alpha:(e,t)=>{let n=e.text("clean"),r=t.text("clean");return nr?1:0},length:(e,t)=>{let n=e.text().trim().length,r=t.text().trim().length;return nr?-1:0},wordCount:(e,t)=>{let n=e.wordCount(),r=t.wordCount();return nr?-1:0}};ba.alphabetical=ba.alpha,ba.wordcount=ba.wordCount;const ya={index:!0,sequence:!0,seq:!0,sequential:!0,chron:!0,chronological:!0};fa.sort=function(e){return"freq"===(e=e||"alpha")||"frequency"===e||"topk"===e?function(e){let t={};const n={case:!0,punctuation:!1,whitespace:!0,unicode:!0};return e.list.forEach((e=>{let r=e.text(n);t[r]=t[r]||0,t[r]+=1})),e.list.sort(((e,r)=>{let a=t[e.text(n)],i=t[r.text(n)];return ai?-1:0})),e}(this):ya.hasOwnProperty(e)?function(e){let t={};return e.json({terms:{offset:!0}}).forEach((e=>{t[e.terms[0].id]=e.terms[0].offset.start})),e.list=e.list.sort(((e,n)=>t[e.start]>t[n.start]?1:t[e.start]{let n=e.text("reduced").trim()||e.text("implicit").trim();return!0!==t.hasOwnProperty(n)&&(t[n]=!0,!0)})),this.buildFrom(e)};var va={};const wa=n$1,ka=/[\[\]{}⟨⟩:,،、‒–—―…‹›«»‐\-;\/⁄·*\•^†‡°¡¿※№÷׺ª%‰=‱¶§~|‖¦©℗®℠™¤₳฿]/g,Aa=/['‘’“”"′″‴]+/g,Da={whitespace:function(e){let t=e.list.map((e=>e.terms()));t.forEach(((e,n)=>{e.forEach(((r,a)=>{!0!==r.hasDash()?(r.pre=r.pre.replace(/\s/g,""),r.post=r.post.replace(/\s/g,""),(e.length-1!==a||t[n+1])&&(r.implicit&&!0===Boolean(r.text)||!0!==r.hasHyphen()&&(r.post+=" "))):r.post=" - "}))}))},punctuation:function(e){e.forEach((e=>{!0===e.hasHyphen()&&(e.post=" "),e.pre=e.pre.replace(ka,""),e.post=e.post.replace(ka,""),e.post=e.post.replace(/\.\.\./,""),!0===/!/.test(e.post)&&(e.post=e.post.replace(/!/g,""),e.post="!"+e.post),!0===/\?/.test(e.post)&&(e.post=e.post.replace(/[\?!]*/,""),e.post="?"+e.post)}))},unicode:function(e){e.forEach((e=>{!0!==e.isImplicit()&&(e.text=wa(e.text))}))},quotations:function(e){e.forEach((e=>{e.post=e.post.replace(Aa,""),e.pre=e.pre.replace(Aa,"")}))},adverbs:function(e){e.match("#Adverb").not("(not|nary|seldom|never|barely|almost|basically|so)").remove()},abbreviations:function(e){e.list.forEach((e=>{let t=e.terms();t.forEach(((e,n)=>{!0===e.tags.Abbreviation&&t[n+1]&&(e.post=e.post.replace(/^\./,""))}))}))}},$a={whitespace:!0,unicode:!0,punctuation:!0,emoji:!0,acronyms:!0,abbreviations:!0,case:!1,contractions:!1,parentheses:!1,quotations:!1,adverbs:!1,possessives:!1,verbs:!1,nouns:!1,honorifics:!1},Pa={light:{},medium:{case:!0,contractions:!0,parentheses:!0,quotations:!0,adverbs:!0}};Pa.heavy=Object.assign({},Pa.medium,{possessives:!0,verbs:!0,nouns:!0,honorifics:!0}),va.normalize=function(e){"string"==typeof(e=e||{})&&(e=Pa[e]||{}),e=Object.assign({},$a,e),this.uncache();let t=this.termList();return e.case&&this.toLowerCase(),e.whitespace&&Da.whitespace(this),e.unicode&&Da.unicode(t),e.punctuation&&Da.punctuation(t),e.emoji&&this.remove("(#Emoji|#Emoticon)"),e.acronyms&&this.acronyms().strip(),e.abbreviations&&Da.abbreviations(this),(e.contraction||e.contractions)&&this.contractions().expand(),e.parentheses&&this.parentheses().unwrap(),(e.quotations||e.quotes)&&Da.quotations(t),e.adverbs&&Da.adverbs(this),(e.possessive||e.possessives)&&this.possessives().strip(),e.verbs&&this.verbs().toInfinitive(),(e.nouns||e.plurals)&&this.nouns().toSingular(),e.honorifics&&this.remove("#Honorific"),this};var Ea={};!function(e){const t=_e;e.splitOn=function(e){if(!e)return this.parent().splitOn(this);let n=t(e),r=[];return this.list.forEach((e=>{let t=e.match(n);if(0===t.length)return void r.push(e);let a=e;t.forEach((e=>{let t=a.splitOn(e);t.before&&r.push(t.before),t.match&&r.push(t.match),a=t.after})),a&&r.push(a)})),this.buildFrom(r)},e.splitAfter=function(e){if(!e)return this.parent().splitAfter(this);let n=t(e),r=[];return this.list.forEach((e=>{let t=e.match(n);if(0===t.length)return void r.push(e);let a=e;t.forEach((e=>{let t=a.splitOn(e);t.before&&t.match?(t.before.length+=t.match.length,r.push(t.before)):t.match&&r.push(t.match),a=t.after})),a&&r.push(a)})),this.buildFrom(r)},e.split=e.splitAfter,e.splitBefore=function(e){if(!e)return this.parent().splitBefore(this);let n=t(e),r=[];return this.list.forEach((e=>{let t=e.match(n);if(0===t.length)return void r.push(e);let a=e;t.forEach((e=>{let t=a.splitOn(e);t.before&&r.push(t.before),t.match&&t.after&&(t.match.length+=t.after.length),a=t.match})),a&&r.push(a)})),this.buildFrom(r)},e.segment=function(e,t){e=e||{},t=t||{text:!0};let n=this,r=Object.keys(e);return r.forEach((e=>{n=n.splitOn(e)})),n.list.forEach((t=>{for(let n=0;n{let n=e.json(t);return n.segment=e.segment||null,n}))}}(Ea);var Ha={};const ja=function(e,t){let n=e.world;return e.list.forEach((e=>{e.terms().forEach((e=>e[t](n)))})),e};Ha.toLowerCase=function(){return ja(this,"toLowerCase")},Ha.toUpperCase=function(){return ja(this,"toUpperCase")},Ha.toTitleCase=function(){return ja(this,"toTitleCase")},Ha.toCamelCase=function(){return this.list.forEach((e=>{let t=e.terms();t.forEach(((e,n)=>{0!==n&&e.toTitleCase(),n!==t.length-1&&(e.post="")}))})),this};var Na={};!function(e){e.pre=function(e,t){return void 0===e?this.list[0].terms(0).pre:(this.list.forEach((n=>{let r=n.terms(0);!0===t?r.pre+=e:r.pre=e})),this)},e.post=function(e,t){return void 0===e?this.list.map((e=>{let t=e.terms();return t[t.length-1].post})):(this.list.forEach((n=>{let r=n.terms(),a=r[r.length-1];!0===t?a.post+=e:a.post=e})),this)},e.trim=function(){return this.list=this.list.map((e=>e.trim())),this},e.hyphenate=function(){return this.list.forEach((e=>{let t=e.terms();t.forEach(((e,n)=>{0!==n&&(e.pre=""),t[n+1]&&(e.post="-")}))})),this},e.dehyphenate=function(){const e=/(-|–|—)/;return this.list.forEach((t=>{t.terms().forEach((t=>{e.test(t.post)&&(t.post=" ")}))})),this},e.deHyphenate=e.dehyphenate,e.toQuotations=function(e,t){return e=e||'"',t=t||'"',this.list.forEach((n=>{let r=n.terms();r[0].pre=e+r[0].pre;let a=r[r.length-1];a.post=t+a.post})),this},e.toQuotation=e.toQuotations,e.toParentheses=function(e,t){return e=e||"(",t=t||")",this.list.forEach((n=>{let r=n.terms();r[0].pre=e+r[0].pre;let a=r[r.length-1];a.post=t+a.post})),this}}(Na);var xa={join:function(e){this.uncache();let t=this.list[0],n=t.length,r={};for(let n=1;n{e.list.forEach((e=>{let n=e.terms();for(let r=0;r!0!==r[e.start]))})),this.buildFrom([t])}},Fa={};const Ca=/[,\)"';:\-–—\.…]/,Ba=function(e,t){if(!e.found)return;let n=e.termList();for(let e=0;e{e.implicit=e.clean})),n[0].text+=t,n.slice(1).forEach((e=>{e.text=""}));for(let e=0;e{za[e[0]]=function(t){let n=this.match(e[1]);return"number"==typeof t&&(n=n.get(t)),n}})),za.emojis=za.emoji,za.atmentions=za.atMentions,za.words=za.terms,za.phoneNumbers=function(e){let t=this.splitAfter("@hasComma");return t=t.match("#PhoneNumber+"),"number"==typeof e&&(t=t.get(e)),t},za.money=function(e){let t=this.match("#Money #Currency?");return"number"==typeof e&&(t=t.get(e)),t},za.places=function(e){let t=this.match("(#City && @hasComma) (#Region|#Country)"),n=this.not(t).splitAfter("@hasComma");return n=n.concat(t),n.sort("index"),n=n.match("#Place+"),"number"==typeof e&&(n=n.get(e)),n},za.organizations=function(e){let t=this.clauses();return t=t.match("#Organization+"),"number"==typeof e&&(t=t.get(e)),t},za.entities=function(e){let t=this.clauses(),n=t.people();return n=n.concat(t.places()),n=n.concat(t.organizations()),n=n.not(["someone","man","woman","mother","brother","sister","father"]),n.sort("sequence"),"number"==typeof e&&(n=n.get(e)),n},za.things=za.entities,za.topics=za.entities;var Ia=za;const Oa=/^(under|over)-?.{3}/,Ta=function(e,t,n){let r=n.words,a=e[t].reduced+" "+e[t+1].reduced;return void 0!==r[a]&&!0===r.hasOwnProperty(a)?(e[t].tag(r[a],"lexicon-two",n),e[t+1].tag(r[a],"lexicon-two",n),1):t+20){a+=n;continue}}if(void 0===n[i]||!0!==n.hasOwnProperty(i))if(i===e[a].reduced||!0!==n.hasOwnProperty(e[a].reduced)){if(!0===Oa.test(i)){let r=i.replace(/^(under|over)-?/,"");!0===n.hasOwnProperty(r)&&e[a].tag(n[r],"noprefix-lexicon",t)}}else e[a].tag(n[e[a].reduced],"lexicon",t);else e[a].tag(n[i],"lexicon",t)}return e};const Ma=/[\'‘’‛‵′`´]$/,Ja=/^(m|k|cm|km|m)\/(s|h|hr)$/,La=[[/^[\w\.]+@[\w\.]+\.[a-z]{2,3}$/,"Email"],[/^#[a-z0-9_\u00C0-\u00FF]{2,}$/,"HashTag"],[/^@1?[0-9](am|pm)$/i,"Time"],[/^@1?[0-9]:[0-9]{2}(am|pm)?$/i,"Time"],[/^@\w{2,}$/,"AtMention"],[/^(https?:\/\/|www\.)+\w+\.[a-z]{2,3}/,"Url"],[/^[a-z0-9./].+\.(com|net|gov|org|ly|edu|info|biz|dev|ru|jp|de|in|uk|br|io|ai)/,"Url"],[/^'[0-9]{2}$/,"Year"],[/^[012]?[0-9](:[0-5][0-9])(:[0-5][0-9])$/,"Time"],[/^[012]?[0-9](:[0-5][0-9])?(:[0-5][0-9])? ?(am|pm)$/i,"Time"],[/^[012]?[0-9](:[0-5][0-9])(:[0-5][0-9])? ?(am|pm)?$/i,"Time"],[/^[PMCE]ST$/,"Time"],[/^utc ?[+-]?[0-9]+?$/,"Time"],[/^[a-z0-9]*? o\'?clock$/,"Time"],[/^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}/i,"Date"],[/^[0-9]{1,4}-[0-9]{1,2}-[0-9]{1,4}$/,"Date"],[/^[0-9]{1,4}\/[0-9]{1,2}\/[0-9]{1,4}$/,"Date"],[/^[0-9]{1,4}-[a-z]{2,9}-[0-9]{1,4}$/i,"Date"],[/^gmt[+-][0-9][0-9]?$/i,"Timezone"],[/^utc[+-][0-9][0-9]?$/i,"Timezone"],[/^ma?c\'.*/,"LastName"],[/^o\'[drlkn].*/,"LastName"],[/^ma?cd[aeiou]/,"LastName"],[/^(lol)+[sz]$/,"Expression"],[/^woo+a*?h?$/,"Expression"],[/^(un|de|re)\\-[a-z\u00C0-\u00FF]{2}/,"Verb"],[/^[0-9]{1,4}\.[0-9]{1,2}\.[0-9]{1,4}$/,"Date"],[/^[0-9]{3}-[0-9]{4}$/,"PhoneNumber"],[/^(\+?[0-9][ -])?[0-9]{3}[ -]?[0-9]{3}-[0-9]{4}$/,"PhoneNumber"],[/^[-+]?[\$\xA2-\xA5\u058F\u060B\u09F2\u09F3\u09FB\u0AF1\u0BF9\u0E3F\u17DB\u20A0-\u20BD\uA838\uFDFC\uFE69\uFF04\uFFE0\uFFE1\uFFE5\uFFE6][-+]?[0-9]+(,[0-9]{3})*(\.[0-9]+)?(k|m|b|bn)?\+?$/,["Money","Value"]],[/^[-+]?[0-9]+(,[0-9]{3})*(\.[0-9]+)?[\$\xA2-\xA5\u058F\u060B\u09F2\u09F3\u09FB\u0AF1\u0BF9\u0E3F\u17DB\u20A0-\u20BD\uA838\uFDFC\uFE69\uFF04\uFFE0\uFFE1\uFFE5\uFFE6]\+?$/,["Money","Value"]],[/^[-+]?[\$£]?[0-9]([0-9,.])+?(usd|eur|jpy|gbp|cad|aud|chf|cny|hkd|nzd|kr|rub)$/i,["Money","Value"]],[/^[-+]?[0-9]+(,[0-9]{3})*(\.[0-9]+)?\+?$/,["Cardinal","NumericValue"]],[/^[-+]?[0-9]+(,[0-9]{3})*(\.[0-9]+)?(st|nd|rd|r?th)$/,["Ordinal","NumericValue"]],[/^\.[0-9]+\+?$/,["Cardinal","NumericValue"]],[/^[-+]?[0-9]+(,[0-9]{3})*(\.[0-9]+)?%\+?$/,["Percent","Cardinal","NumericValue"]],[/^\.[0-9]+%$/,["Percent","Cardinal","NumericValue"]],[/^[0-9]{1,4}\/[0-9]{1,4}(st|nd|rd|th)?s?$/,["Fraction","NumericValue"]],[/^[0-9.]{1,3}[a-z]{0,2}[-–—][0-9]{1,3}[a-z]{0,2}$/,["Value","NumberRange"]],[/^[0-9][0-9]?(:[0-9][0-9])?(am|pm)? ?[-–—] ?[0-9][0-9]?(:[0-9][0-9])?(am|pm)?$/,["Time","NumberRange"]],[/^[0-9.]+([a-z]{1,4})$/,"Value"]],Sa=/^[IVXLCDM]{2,}$/,_a=/^M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$/,Ka="Adjective",qa="Infinitive",Wa="PresentTense",Ra="Singular",Ua="PastTense",Qa="Expression",Za="Adjective",Xa="Infinitive",Ya="PresentTense",en="Singular",tn="PastTense",rn="Adverb",an="Plural",nn="Verb",on="LastName",sn={a:[[/.[aeiou]na$/,"Noun"],[/.[oau][wvl]ska$/,"LastName"],[/.[^aeiou]ica$/,Ra],[/^([hyj]a)+$/,Qa]],c:[[/.[^aeiou]ic$/,Ka]],d:[[/[aeiou](pp|ll|ss|ff|gg|tt|rr|bb|nn|mm)ed$/,Ua],[/.[aeo]{2}[bdgmnprvz]ed$/,Ua],[/.[aeiou][sg]hed$/,Ua],[/.[aeiou]red$/,Ua],[/.[aeiou]r?ried$/,Ua],[/.[bcdgtr]led$/,Ua],[/.[aoui]f?led$/,Ua],[/.[iao]sed$/,Ua],[/[aeiou]n?[cs]ed$/,Ua],[/[aeiou][rl]?[mnf]ed$/,Ua],[/[aeiou][ns]?c?ked$/,Ua],[/[aeiou][nl]?ged$/,Ua],[/.[tdbwxz]ed$/,Ua],[/[^aeiou][aeiou][tvx]ed$/,Ua],[/.[cdlmnprstv]ied$/,Ua],[/[^aeiou]ard$/,Ra],[/[aeiou][^aeiou]id$/,Ka],[/.[vrl]id$/,Ka]],e:[[/.[lnr]ize$/,qa],[/.[^aeiou]ise$/,qa],[/.[aeiou]te$/,qa],[/.[^aeiou][ai]ble$/,Ka],[/.[^aeiou]eable$/,Ka],[/.[ts]ive$/,Ka],[/[a-z]-like$/,Ka]],h:[[/.[^aeiouf]ish$/,Ka],[/.v[iy]ch$/,"LastName"],[/^ug?h+$/,Qa],[/^uh[ -]?oh$/,Qa],[/[a-z]-ish$/,Ka]],i:[[/.[oau][wvl]ski$/,"LastName"]],k:[[/^(k){2}$/,Qa]],l:[[/.[gl]ial$/,Ka],[/.[^aeiou]ful$/,Ka],[/.[nrtumcd]al$/,Ka],[/.[^aeiou][ei]al$/,Ka]],m:[[/.[^aeiou]ium$/,Ra],[/[^aeiou]ism$/,Ra],[/^h*u*m+$/,Qa],[/^\d+ ?[ap]m$/,"Date"]],n:[[/.[lsrnpb]ian$/,Ka],[/[^aeiou]ician$/,"Actor"],[/[aeiou][ktrp]in$/,"Gerund"]],o:[[/^no+$/,Qa],[/^(yo)+$/,Qa],[/^woo+[pt]?$/,Qa]],r:[[/.[bdfklmst]ler$/,"Noun"],[/[aeiou][pns]er$/,Ra],[/[^i]fer$/,qa],[/.[^aeiou][ao]pher$/,"Actor"],[/.[lk]er$/,"Noun"],[/.ier$/,"Comparative"]],t:[[/.[di]est$/,"Superlative"],[/.[icldtgrv]ent$/,Ka],[/[aeiou].*ist$/,Ka],[/^[a-z]et$/,"Verb"]],s:[[/.[^aeiou]ises$/,Wa],[/.[rln]ates$/,Wa],[/.[^z]ens$/,"Verb"],[/.[lstrn]us$/,Ra],[/.[aeiou]sks$/,Wa],[/.[aeiou]kes$/,Wa],[/[aeiou][^aeiou]is$/,Ra],[/[a-z]\'s$/,"Noun"],[/^yes+$/,Qa]],v:[[/.[^aeiou][ai][kln]ov$/,"LastName"]],y:[[/.[cts]hy$/,Ka],[/.[st]ty$/,Ka],[/.[gk]y$/,Ka],[/.[tnl]ary$/,Ka],[/.[oe]ry$/,Ra],[/[rdntkbhs]ly$/,"Adverb"],[/...lly$/,"Adverb"],[/[bszmp]{2}y$/,Ka],[/.(gg|bb|zz)ly$/,Ka],[/.[ai]my$/,Ka],[/[ea]{2}zy$/,Ka],[/.[^aeiou]ity$/,Ra]]},ln=[null,null,{ea:en,ia:"Noun",ic:Za,ly:rn,"'n":nn,"'t":nn},{oed:tn,ued:tn,xed:tn," so":rn,"'ll":"Modal","'re":"Copula",azy:Za,eer:"Noun",end:nn,ped:tn,ffy:Za,ify:Xa,ing:"Gerund",ize:Xa,lar:Za,mum:Za,nes:Ya,nny:Za,oid:Za,ous:Za,que:Za,rol:en,sis:en,zes:Ya},{amed:tn,aped:tn,ched:tn,lked:tn,nded:tn,cted:tn,dged:tn,akis:on,cede:Xa,chuk:on,czyk:on,ects:Ya,ends:nn,enko:on,ette:en,fies:Ya,fore:rn,gate:Xa,gone:Za,ices:an,ints:an,ines:an,ions:an,less:rn,llen:Za,made:Za,nsen:on,oses:Ya,ould:"Modal",some:Za,sson:on,tage:Xa,teen:"Value",tion:en,tive:Za,tors:"Noun",vice:en},{tized:tn,urned:tn,eased:tn,ances:an,bound:Za,ettes:an,fully:rn,ishes:Ya,ities:an,marek:on,nssen:on,ology:"Noun",ports:an,rough:Za,tches:Ya,tieth:"Ordinal",tures:an,wards:rn,where:rn},{auskas:on,keeper:"Actor",logist:"Actor",teenth:"Value"},{opoulos:on,borough:"Place",sdottir:on}],un=/^(\u00a9|\u00ae|[\u2319-\u3300]|\ud83c[\ud000-\udfff]|\ud83d[\ud000-\udfff]|\ud83e[\ud000-\udfff])/,cn={":(":!0,":)":!0,":P":!0,":p":!0,":O":!0,":3":!0,":|":!0,":/":!0,":\\":!0,":$":!0,":*":!0,":@":!0,":-(":!0,":-)":!0,":-P":!0,":-p":!0,":-O":!0,":-3":!0,":-|":!0,":-/":!0,":-\\":!0,":-$":!0,":-*":!0,":-@":!0,":^(":!0,":^)":!0,":^P":!0,":^p":!0,":^O":!0,":^3":!0,":^|":!0,":^/":!0,":^\\":!0,":^$":!0,":^*":!0,":^@":!0,"):":!0,"(:":!0,"$:":!0,"*:":!0,")-:":!0,"(-:":!0,"$-:":!0,"*-:":!0,")^:":!0,"(^:":!0,"$^:":!0,"*^:":!0,"<3":!0,"2){let e=r.clean[r.clean.length-2];if("s"===e)return void r.tag(["Possessive","Noun"],"end-tick",n);"n"===e&&r.tag(["Gerund"],"chillin",n)}Ja.test(r.text)&&r.tag("Unit","per-sec",n)},regex:function(e,t){let n=e.text;for(let r=0;r=2&&Sa.test(n)&&_a.test(n)&&e.tag("RomanNumeral","xvii",t)},suffix:function(e,t){!function(e,t){const n=e.clean.length;let r=7;n<=r&&(r=n-1);for(let a=r;a>1;a-=1){let r=e.clean.substr(n-a,n);if(!0===ln[r.length].hasOwnProperty(r)){let n=ln[r.length][r];e.tagSafe(n,"suffix -"+r,t);break}}}(e,t),function(e,t){let n=e.clean,r=n[n.length-1];if(!0===sn.hasOwnProperty(r)){let a=sn[r];for(let i=0;i{let n=e.pre+e.text+e.post;var r;n=n.trim(),n=n.replace(/[.!?,]$/,""),!0===(e=>!(":"!==e.charAt(0)||null===e.match(/:.?$/)||e.match(" ")||e.length>35))(n)&&(e.tag("Emoji","comma-emoji",t),e.text=n,e.pre=e.pre.replace(":",""),e.post=e.post.replace(":","")),e.text.match(un)&&(e.tag("Emoji","unicode-emoji",t),e.text=n),!0===(r=(r=n).replace(/^[:;]/,":"),cn.hasOwnProperty(r))&&(e.tag("Emoticon","emoticon-emoji",t),e.text=n)}};var dn=function(e,t){let n=e.world;hn.lexicon(t,n);for(let e=0;ea.tags[e]));if(void 0!==e){let n=gn.afterThisPos[e];r.tag(n,"after-"+e,t);continue}}let i=e[n+1];if(i){if(!0===gn.beforeThisWord.hasOwnProperty(i.clean)){let e=gn.beforeThisWord[i.clean];r.tag(e,"before-"+i.clean,t);continue}let e=mn.find((e=>i.tags[e]));if(void 0!==e){let n=gn.beforeThisPos[e];r.tag(n,"before-"+e,t);continue}}}};const bn=/^[A-Z][a-z'\u00C0-\u00FF]/,yn=/[0-9]/;var vn=function(e){let t=e.world;e.list.forEach((e=>{let n=e.terms();for(let e=1;e{if(!0!==e.isKnown()&&!0===wn.test(e.clean)){let r=e.clean.replace(kn,"");r&&r.length>3&&void 0!==n[r]&&!0===n.hasOwnProperty(r)&&e.tag(n[r],"stem-"+r,t)}}))};const Dn=["Uncountable","Pronoun","Place","Value","Person","Month","WeekDay","Holiday"],$n={isSingular:[/(ax|test)is$/i,/(octop|vir|radi|nucle|fung|cact|stimul)us$/i,/(octop|vir)i$/i,/(rl)f$/i,/(alias|status)$/i,/(bu)s$/i,/(al|ad|at|er|et|ed|ad)o$/i,/(ti)um$/i,/(ti)a$/i,/sis$/i,/(?:(^f)fe|(lr)f)$/i,/hive$/i,/s[aeiou]+ns$/i,/(^aeiouy|qu)y$/i,/(x|ch|ss|sh|z)$/i,/(matr|vert|ind|cort)(ix|ex)$/i,/(m|l)ouse$/i,/(m|l)ice$/i,/(antenn|formul|nebul|vertebr|vit)a$/i,/.sis$/i,/^(?!talis|.*hu)(.*)man$/i],isPlural:[/(^v)ies$/i,/ises$/i,/ives$/i,/(antenn|formul|nebul|vertebr|vit)ae$/i,/(octop|vir|radi|nucle|fung|cact|stimul)i$/i,/(buffal|tomat|tornad)oes$/i,/(analy|ba|diagno|parenthe|progno|synop|the)ses$/i,/(vert|ind|cort)ices$/i,/(matr|append)ices$/i,/(x|ch|ss|sh|s|z|o)es$/i,/is$/i,/men$/i,/news$/i,/.tia$/i,/(^f)ves$/i,/(lr)ves$/i,/(^aeiouy|qu)ies$/i,/(m|l)ice$/i,/(cris|ax|test)es$/i,/(alias|status)es$/i,/ics$/i]},Pn=[/ss$/,/sis$/,/[^aeiou][uo]s$/,/'s$/],En=[/i$/,/ae$/];var Hn=function(e,t){if(e.tags.Noun&&!e.tags.Acronym){let n=e.clean;if(e.tags.Singular||e.tags.Plural)return;if(n.length<=3)return void e.tag("Singular","short-singular",t);if(Dn.find((t=>e.tags[t])))return;if($n.isPlural.find((e=>e.test(n))))return void e.tag("Plural","plural-rules",t);if($n.isSingular.find((e=>e.test(n))))return void e.tag("Singular","singular-rules",t);if(!0===/s$/.test(n)){if(Pn.find((e=>e.test(n))))return;return void e.tag("Plural","plural-fallback",t)}if(En.find((e=>e.test(n))))return;e.tag("Singular","singular-fallback",t)}};let jn=["academy","administration","agence","agences","agencies","agency","airlines","airways","army","assoc","associates","association","assurance","authority","autorite","aviation","bank","banque","board","boys","brands","brewery","brotherhood","brothers","building society","bureau","cafe","caisse","capital","care","cathedral","center","central bank","centre","chemicals","choir","chronicle","church","circus","clinic","clinique","club","co","coalition","coffee","collective","college","commission","committee","communications","community","company","comprehensive","computers","confederation","conference","conseil","consulting","containers","corporation","corps","corp","council","crew","daily news","data","departement","department","department store","departments","design","development","directorate","division","drilling","education","eglise","electric","electricity","energy","ensemble","enterprise","enterprises","entertainment","estate","etat","evening news","faculty","federation","financial","fm","foundation","fund","gas","gazette","girls","government","group","guild","health authority","herald","holdings","hospital","hotel","hotels","inc","industries","institut","institute","institute of technology","institutes","insurance","international","interstate","investment","investments","investors","journal","laboratory","labs","liberation army","limited","local authority","local health authority","machines","magazine","management","marine","marketing","markets","media","memorial","mercantile exchange","ministere","ministry","military","mobile","motor","motors","musee","museum","news","news service","observatory","office","oil","optical","orchestra","organization","partners","partnership","people's party","petrol","petroleum","pharmacare","pharmaceutical","pharmaceuticals","pizza","plc","police","polytechnic","post","power","press","productions","quartet","radio","regional authority","regional health authority","reserve","resources","restaurant","restaurants","savings","school","securities","service","services","social club","societe","society","sons","standard","state police","state university","stock exchange","subcommittee","syndicat","systems","telecommunications","telegraph","television","times","tribunal","tv","union","university","utilities","workers"].reduce((function(e,t){return e[t]="Noun",e}),{});const Nn=function(e){return!(!e.tags.Noun||e.tags.Pronoun||e.tags.Comma||e.tags.Possessive||!(e.tags.Organization||e.tags.Acronym||e.tags.Place||e.titleCase()))},xn=/^[A-Z]('s|,)?$/,Fn=/([A-Z]\.){2}[A-Z]?/i,Cn={I:!0,A:!0},Bn={neighbours:fn,case:vn,stem:An,plural:Hn,organizations:function(e,t){for(let n=0;n{!0!==e.tags.RomanNumeral&&(!0===Fn.test(e.text)&&e.tag("Acronym","period-acronym",t),e.isUpperCase()&&function(e,t){let n=e.reduced;return!!e.tags.Acronym||!t.words[n]&&!(n.length>5)&&e.isAcronym()}(e,t)?(e.tag("Acronym","acronym-step",t),e.tag("Noun","acronym-infer",t)):!Cn.hasOwnProperty(e.text)&&xn.test(e.text)&&(e.tag("Acronym","one-letter-acronym",t),e.tag("Noun","one-letter-infer",t)),e.tags.Organization&&e.text.length<=3&&e.tag("Acronym","acronym-org",t),e.tags.Organization&&e.isUpperCase()&&e.text.length<=6&&e.tag("Acronym","acronym-org-case",t))}))}};var Gn=function(e,t){let n=e.world;return Bn.neighbours(t,n),Bn.case(e),Bn.stem(t,n),t.forEach((t=>{!1===t.isKnown()&&t.tag("Noun","noun-fallback",e.world)})),Bn.organizations(t,n),Bn.acronyms(t,n),t.forEach((t=>{Bn.plural(t,e.world)})),e};const zn=/n't$/,In={"won't":["will","not"],wont:["will","not"],"can't":["can","not"],cant:["can","not"],cannot:["can","not"],"shan't":["should","not"],dont:["do","not"],dun:["do","not"]},On=/([a-z\u00C0-\u00FF]+)[\u0027\u0060\u00B4\u2018\u2019\u201A\u201B\u2032\u2035\u2039\u203A]([a-z]{1,2})$/i,Tn={ll:"will",ve:"have",re:"are",m:"am","n't":"not"},Vn={wanna:["want","to"],gonna:["going","to"],im:["i","am"],alot:["a","lot"],ive:["i","have"],imma:["I","will"],"where'd":["where","did"],whered:["where","did"],"when'd":["when","did"],whend:["when","did"],howd:["how","did"],whatd:["what","did"],dunno:["do","not","know"],brb:["be","right","back"],gtg:["got","to","go"],irl:["in","real","life"],tbh:["to","be","honest"],imo:["in","my","opinion"],til:["today","i","learned"],rn:["right","now"],twas:["it","was"],"@":["at"]},Mn=/([a-z\u00C0-\u00FF]+)[\u0027\u0060\u00B4\u2018\u2019\u201A\u201B\u2032\u2035\u2039\u203A]s$/i,Jn={that:!0,there:!0},Ln={here:!0,there:!0,everywhere:!0},Sn=/[a-z\u00C0-\u00FF]'d$/,_n={how:!0,what:!0},Kn=/^([0-9.]{1,3}[a-z]{0,2}) ?[-–—] ?([0-9]{1,3}[a-z]{0,2})$/i,qn=/^([0-9][0-9]?(:[0-9][0-9])?(am|pm)?) ?[-–—] ?([0-9][0-9]?(:[0-9][0-9])?(am|pm)?)$/i,Wn=/^(l|c|d|j|m|n|qu|s|t)[\u0027\u0060\u00B4\u2018\u2019\u201A\u201B\u2032\u2035\u2039\u203A]([a-z\u00C0-\u00FF]+)$/i,Rn={l:"le",c:"ce",d:"de",j:"je",m:"me",n:"ne",qu:"que",s:"se",t:"tu"},Un=Va,Qn=xt,Zn=function(e,t){return!0===In.hasOwnProperty(e.clean)?In[e.clean]:"ain't"===e.clean||"aint"===e.clean?function(e,t){let n=t.terms(),r=n.indexOf(e),a=n.slice(0,r).find((e=>e.tags.Noun));return a&&a.tags.Plural?["are","not"]:["is","not"]}(e,t):!0===zn.test(e.clean)?[e.clean.replace(zn,""),"not"]:null},Xn=function(e){let t=e.text.match(On);return null===t?null:Tn.hasOwnProperty(t[2])?[t[1],Tn[t[2]]]:null},Yn=function(e){return Vn.hasOwnProperty(e.clean)?Vn[e.clean]:null},ei=function(e,t,n){let r=e.text.match(Mn);if(null!==r){if(!0===((e,t)=>{if(e.tags.Possessive)return!0;if(e.tags.Pronoun||e.tags.QuestionWord)return!1;if(Jn.hasOwnProperty(e.reduced))return!1;let n=t.get(e.next);if(!n)return!0;if(n.tags.Verb)return!!n.tags.Infinitive||!!n.tags.PresentTense;if(n.tags.Noun)return!0!==Ln.hasOwnProperty(n.reduced);let r=t.get(n.next);return!(!r||!r.tags.Noun||r.tags.Pronoun)||(n.tags.Adjective||n.tags.Adverb||n.tags.Verb,!1)})(e,t.pool))return e.tag("#Possessive","isPossessive",n),null;if(null!==r)return((e,t)=>{let n=t.terms(),r=n.indexOf(e);return n.slice(r+1,r+3).find((e=>e.tags.PastTense))})(e,t)?[r[1],"has"]:[r[1],"is"]}return null},ti=function(e,t){if(Sn.test(e.clean)){let n=e.clean.replace(/'d$/,""),r=t.terms(),a=r.indexOf(e),i=r.slice(a+1,a+4);for(let e=0;e{e.implicit=e.text,e.text="",e.clean="",e.pre="",e.post="",0===Object.keys(e.tags).length&&(e.tags.Noun=!0)})),n};var li=function(e){let t=e.world;return e.list.forEach((n=>{let r=n.terms();for(let a=0;ae.list[t])),e.buildFrom(n)};var ci=function(e){let t=ui(e,"Infinitive");return t.found&&(t=t.ifNo("@hasQuestionMark"),t=t.ifNo("(i|we|they)"),t.not("will be").match("[#Infinitive] (#Determiner|#Possessive) #Noun").notIf("(our|their)").match("#Infinitive").tag("Imperative","shut-the"),t.match("^[#Infinitive] #Adverb?$",0).tag("Imperative","go-fast"),t.match("[(do && #Infinitive)] not? #Verb",0).tag("Imperative","do-not"),t.match("[#Infinitive] (it|some) (#Comparative|#Preposition|please|now|again)",0).tag("Imperative","do-it")),t=function(e,t){let n=e._cache.words.like||[];return n=n.map((t=>e.list[t])),e.buildFrom(n)}(e),t.match("#Adverb like").notIf("(really|generally|typically|usually|sometimes|often|just) [like]").tag("Adverb","adverb-like"),t=ui(e,"Adjective"),t.match("#Determiner #Adjective$").notIf("(#Comparative|#Superlative)").terms(1).tag("Noun","the-adj-1"),t=ui(e,"FirstName"),t.match("#FirstName (#Noun|@titleCase)").ifNo("^#Possessive").ifNo("(#Pronoun|#Plural)").ifNo("@hasComma .").lastTerm().tag("#LastName","firstname-noun"),t=ui(e,"Value"),t=t.match("#Value #PresentTense").ifNo("#Copula"),t.found&&(!0===t.has("(one|1)")?t.terms(1).tag("Singular","one-presentTense"):t.terms(1).tag("Plural","value-presentTense")),e.match("^(well|so|okay)").tag("Expression","well-"),e.match("#Value [of a second]",0).unTag("Value","of-a-second"),e.match("#Value [seconds]",0).unTag("Value","30-seconds").tag(["Unit","Plural"]),t=ui(e,"Gerund"),t.match("(be|been) (#Adverb|not)+? #Gerund").not("#Verb$").tag("Auxiliary","be-walking"),e.match("(try|use|attempt|build|make) #Verb").ifNo("(@hasComma|#Negative|#PhrasalVerb|#Copula|will|be)").lastTerm().tag("#Noun","do-verb"),t=ui(e,"Possessive"),t=t.match("#Possessive [#Infinitive]",0),t.lookBehind("(let|made|make|force|ask)").found||t.tag("Noun","her-match"),e},hi=function(e){let t={};for(let n=0;n{e.reg=ji(e.match);let t=function(e){let t=[];if(1===e.reg.filter((e=>void 0!==e.fastOr)).length){let n=e.reg.findIndex((e=>void 0!==e.fastOr));Object.keys(e.reg[n].fastOr).forEach((r=>{let a=Object.assign({},e);a.reg=a.reg.slice(0),a.reg[n]=Object.assign({},a.reg[n]),a.reg[n].word=r,delete a.reg[n].operator,delete a.reg[n].fastOr,t.push(a)}))}return t}(e);t.length>0?Fi=Fi.concat(t):Fi.push(e)})),Fi.forEach((e=>(e.required=function(e){let t=[],n=[];return e.forEach((e=>{!0!==e.optional&&!0!==e.negative&&(void 0!==e.tag&&t.push(e.tag),void 0!==e.word&&n.push(e.word))})),{tags:Ni(t),words:Ni(n)}}(e.reg),e)));const Ci=Fi,Bi=hi,Gi=ci,zi=function(e){Ci.forEach((t=>{let n=[];t.required.words.forEach((t=>{n.push(e._cache.words[t]||[])})),t.required.tags.forEach((t=>{n.push(e._cache.tags[t]||[])}));let r=function(e){if(0===e.length)return[];let t={};e.forEach((e=>{e=Bi(e);for(let n=0;nt[n]===e.length)),n=n.map((e=>Number(e))),n}(n);if(0===r.length)return;let a=r.map((t=>e.list[t])),i=e.buildFrom(a).match(t.reg,t.group);i.found&&(!0===t.safe?i.tagSafe(t.tag,t.reason):i.tag(t.tag,t.reason))}))},Ii=dn,Oi=Gn,Ti=li,Vi=function(e){return zi(e),Gi(e),e};var Mi=function(e){let t=e.termList();return e=Ii(e,t),e=Oi(e,t),(e=Ti(e)).cache(),(e=Vi(e)).uncache(),e.world.taggers.forEach((t=>{t(e)})),e},Ji=function(e){class t extends e{stripPeriods(){return this.termList().forEach((e=>{!0===e.tags.Abbreviation&&e.next&&(e.post=e.post.replace(/^\./,""));let t=e.text.replace(/\./,"");e.set(t)})),this}addPeriods(){return this.termList().forEach((e=>{e.post=e.post.replace(/^\./,""),e.post="."+e.post})),this}}return t.prototype.unwrap=t.prototype.stripPeriods,e.prototype.abbreviations=function(e){let n=this.match("#Abbreviation");return"number"==typeof e&&(n=n.get(e)),new t(n.list,this,this.world)},e};const Li=/\./;var Si=function(e){class t extends e{stripPeriods(){return this.termList().forEach((e=>{let t=e.text.replace(/\./g,"");e.set(t)})),this}addPeriods(){return this.termList().forEach((e=>{let t=e.text.replace(/\./g,"");t=t.split("").join("."),!1===Li.test(e.post)&&(t+="."),e.set(t)})),this}}return t.prototype.unwrap=t.prototype.stripPeriods,t.prototype.strip=t.prototype.stripPeriods,e.prototype.acronyms=function(e){let n=this.match("#Acronym");return"number"==typeof e&&(n=n.get(e)),new t(n.list,this,this.world)},e},_i=function(e){return e.prototype.clauses=function(t){let n=this.if("@hasComma").notIf("@hasComma @hasComma").notIf("@hasComma . .? (and|or) .").notIf("(#City && @hasComma) #Country").notIf("(#WeekDay && @hasComma) #Date").notIf("(#Date && @hasComma) #Year").notIf("@hasComma (too|also)$").match("@hasComma"),r=this.splitAfter(n),a=r.quotations();r=r.splitOn(a);let i=r.parentheses();r=r.splitOn(i);let s=r.if("#Copula #Adjective #Conjunction (#Pronoun|#Determiner) #Verb").match("#Conjunction");r=r.splitBefore(s);let o=r.if("if .{2,9} then .").match("then");r=r.splitBefore(o),r=r.splitBefore("as well as ."),r=r.splitBefore("such as ."),r=r.splitBefore("in addition to ."),r=r.splitAfter("@hasSemicolon"),r=r.splitAfter("@hasDash");let l=r.filter((e=>e.wordCount()>5&&e.match("#Verb+").length>=2));if(l.found){let e=l.splitAfter("#Noun .* #Verb .* #Noun+");r=r.splitOn(e.eq(0))}return"number"==typeof t&&(r=r.get(t)),new e(r.list,this,this.world)},e},Ki=function(e){class t extends e{constructor(e,t,n){super(e,t,n),this.contracted=null}expand(){return this.list.forEach((e=>{let t=e.terms(),n=t[0].isTitleCase();t.forEach(((e,n)=>{e.set(e.implicit||e.text),e.implicit=void 0,n{let r=t(n).beforeLast;r.append(e),r.termList(0).addPunctuation(",")})),this}remove(e){return this.items().if(e).remove()}hasOxfordComma(){return this.filter((e=>t(e).hasOxford))}addOxfordComma(){let e=this.items(),t=e.eq(e.length-2);return t.found&&!1===t.has("@hasComma")&&t.post(", "),this}removeOxfordComma(){let e=this.items(),t=e.eq(e.length-2);return t.found&&!0===t.has("@hasComma")&&t.post(" "),this}}return n.prototype.things=n.prototype.items,e.prototype.lists=function(e){let t=this.if("@hasComma+ .? (and|or) not? ."),r=t.match("(#Noun|#Adjective|#Determiner|#Article)+ #Conjunction not? (#Article|#Determiner)? #Adjective? #Noun+").if("#Noun"),a=t.match("(#Adjective|#Adverb)+ #Conjunction not? #Adverb? #Adjective+"),i=t.match("(#Verb|#Adverb)+ #Conjunction not? #Adverb? #Verb+"),s=r.concat(a);return s=s.concat(i),s=s.if("@hasComma"),"number"==typeof e&&(s=t.get(e)),new n(s.list,this,this.world)},e};const Wi={hour:"an",heir:"an",heirloom:"an",honest:"an",honour:"an",honor:"an",uber:"an"},Ri={a:!0,e:!0,f:!0,h:!0,i:!0,l:!0,m:!0,n:!0,o:!0,r:!0,s:!0,x:!0},Ui=[/^onc?e/i,/^u[bcfhjkqrstn][aeiou]/i,/^eul/i],Qi={isSingular:[/(ax|test)is$/i,/(octop|vir|radi|nucle|fung|cact|stimul)us$/i,/(octop|vir)i$/i,/(rl)f$/i,/(alias|status)$/i,/(bu)s$/i,/(al|ad|at|er|et|ed|ad)o$/i,/(ti)um$/i,/(ti)a$/i,/sis$/i,/(?:(^f)fe|(lr)f)$/i,/hive$/i,/(^aeiouy|qu)y$/i,/(x|ch|ss|sh|z)$/i,/(matr|vert|ind|cort)(ix|ex)$/i,/(m|l)ouse$/i,/(m|l)ice$/i,/(antenn|formul|nebul|vertebr|vit)a$/i,/.sis$/i,/^(?!talis|.*hu)(.*)man$/i],isPlural:[/(antenn|formul|nebul|vertebr|vit)ae$/i,/(octop|vir|radi|nucle|fung|cact|stimul)i$/i,/men$/i,/.tia$/i,/(m|l)ice$/i]},Zi=/s$/,Xi={he:"his",she:"hers",they:"theirs",we:"ours",i:"mine",you:"yours",her:"hers",their:"theirs",our:"ours",my:"mine",your:"yours"},Yi=function(e){return!0===e.has("#Plural")||!0!==e.has("(#Pronoun|#Place|#Value|#Person|#Uncountable|#Month|#WeekDay|#Holiday|#Possessive)")},eo=function(e){if(e.has("#Person")||e.has("#Place"))return"";if(e.has("#Plural"))return"the";let t=e.text("normal").trim();if(Wi.hasOwnProperty(t))return Wi[t];let n=t.substr(0,1);if(e.has("^@isAcronym")&&Ri.hasOwnProperty(n))return"an";for(let e=0;et.test(e)))&&(!0===Zi.test(e)||!!Qi.isPlural.find((t=>t.test(e)))||null)},ro=function(e){let t=e.text("text").trim();return Xi.hasOwnProperty(t)?(e.replaceWith(Xi[t],!0),void e.tag("Possessive","toPossessive")):/s$/.test(t)?(t+="'",e.replaceWith(t,!0),void e.tag("Possessive","toPossessive")):(t+="'s",e.replaceWith(t,!0),void e.tag("Possessive","toPossessive"))},ao=function(e){let t={main:e};if(e.has("#Noun (of|by|for) .")){let n=e.splitAfter("[#Noun+]",0);t.main=n.eq(0),t.post=n.eq(1)}return t},no={json:function(e){let t=null;"number"==typeof e&&(t=e,e=null),e=e||{text:!0,normal:!0,trim:!0,terms:!0};let n=[];return this.forEach((t=>{let r=t.json(e)[0];r.article=eo(t),n.push(r)})),null!==t?n[t]:n},adjectives:function(){let e=this.lookAhead("^(that|who|which)? (was|is|will)? be? #Adverb? #Adjective+");return e=e.concat(this.lookBehind("#Adjective+ #Adverb?$")),e=e.match("#Adjective"),e.sort("index")},isPlural:function(){return this.if("#Plural")},hasPlural:function(){return this.filter((e=>Yi(e)))},toPlural:function(e){let t=this.world.transforms.toPlural;return this.forEach((n=>{if(n.has("#Plural")||!1===Yi(n))return;let r=ao(n).main,a=r.text("reduced");if((r.has("#Singular")||!0!==to(a))&&(a=t(a,this.world),r.replace(a).tag("#Plural"),e)){let e=r.lookBefore("(an|a) #Adjective?$").not("#Adjective");!0===e.found&&e.remove()}})),this},toSingular:function(e){let t=this.world.transforms.toSingular;return this.forEach((n=>{if(n.has("^#Singular+$")||!1===Yi(n))return;let r=ao(n).main,a=r.text("reduced");if((r.has("#Plural")||!0===to(a))&&(a=t(a,this.world),r.replace(a).tag("#Singular"),e)){let e=n,t=n.lookBefore("#Adjective");t.found&&(e=t);let r=eo(e);e.insertBefore(r)}})),this},toPossessive:function(){return this.forEach((e=>{ro(e)})),this}};var io=function(e){class t extends e{}return Object.assign(t.prototype,no),e.prototype.nouns=function(e,n={}){let r=this.match("(#City && @hasComma) (#Region|#Country)"),a=this.not(r).splitAfter("@hasComma");a=a.concat(r);let i=a.quotations();return i.found&&(a=a.splitOn(i.eq(0))),a=a.match("#Noun+ (of|by)? the? #Noun+?"),!0!==n.keep_anaphora&&(a=a.not("#Pronoun"),a=a.not("(there|these)"),a=a.not("(#Month|#WeekDay)"),a=a.not("(my|our|your|their|her|his)")),a=a.not("(of|for|by|the)$"),"number"==typeof e&&(a=a.get(e)),new t(a.list,this,this.world)},e};const oo=/\(/,so=/\)/;var lo=function(e){class t extends e{unwrap(){return this.list.forEach((e=>{let t=e.terms(0);t.pre=t.pre.replace(oo,"");let n=e.lastTerm();n.post=n.post.replace(so,"")})),this}}return e.prototype.parentheses=function(e){let n=[];return this.list.forEach((e=>{let t=e.terms();for(let r=0;r{e.terms().forEach((e=>{let t=e.text.replace(/'s$/,"");e.set(t||e.text)}))})),this}}return e.prototype.possessives=function(e){let n=this.match("#Noun+? #Possessive");return"number"==typeof e&&(n=n.get(e)),new t(n.list,this,this.world)},e};const co={'"':'"',""":""","'":"'","“":"”","‘":"’","‟":"”","‛":"’","„":"”","⹂":"”","‚":"’","«":"»","‹":"›","‵":"′","‶":"″","‷":"‴","〝":"〞","`":"´","〟":"〞"},ho=RegExp("("+Object.keys(co).join("|")+")");var go=function(e){class t extends e{unwrap(){return this}}return e.prototype.quotations=function(e){let n=[];return this.list.forEach((e=>{let t=e.terms();for(let r=0;r{let t=!1,n=wo(e),r=e.negative.found;e.verb.lookBehind("i (#Adverb|#Verb)?$").found&&(t=!0);let a={PastTense:"was",PresentTense:"is",FutureTense:"will be",Infinitive:"is",Gerund:"being",Actor:"",PerfectTense:"been",Pluperfect:"been"};return n&&(a.PastTense="were",a.PresentTense="are",a.Infinitive="are"),!0===t&&(a.PastTense="was",a.PresentTense="am",a.Infinitive="am"),r&&(a.PastTense+=" not",a.PresentTense+=" not",a.FutureTense="will not be",a.Infinitive+=" not",a.PerfectTense="not "+a.PerfectTense,a.Pluperfect="not "+a.Pluperfect,a.Gerund="not "+a.Gerund),a},Do=function(e){let t=e.verb.text();return{PastTense:t+" have",PresentTense:t,FutureTense:t,Infinitive:t}},$o=mo;var Po=function(e,t){let n=e.verb;if(n.has("#Copula")||"be"===n.out("normal")&&e.auxiliary.has("will"))return Ao(e);if(e.auxiliary.has("are")&&n.has("#Gerund")){let n=e.original.clone(),r=n.clone().replace("are","were"),a=n.clone().replace("are","will be"),i=ko(e,t);return{PastTense:r.text(),PresentTense:n.text(),FutureTense:a.text(),Infinitive:i}}if(n.has("#Modal"))return Do(e);let r=ko(e,t);if(!r)return{};let a=t.transforms.conjugate(r,t);a.Infinitive=r;let i=$o(e);!0===i&&(a.PresentTense=a.Infinitive);let s=e.verb.termList(0).hasHyphen();if(e.particle.found){let t=e.particle.text(),n=!0===s?"-":" ";Object.keys(a).forEach((e=>a[e]+=n+t))}const o=e.negative.found;return a.FutureTense=a.FutureTense||"will "+a.Infinitive,o&&(a.PastTense="did not "+a.Infinitive,a.FutureTense="will not "+a.Infinitive,i?(a.PresentTense="do not "+a.Infinitive,a.Infinitive="do not "+a.Infinitive):(a.PresentTense="does not "+a.Infinitive,a.Infinitive="does not "+a.Infinitive),a.Gerund="not "+a.Gerund),a};const Eo=Po;var Ho={useParticiple:function(e){return!!e.auxiliary.has("(could|should|would|may|can|must)")||!!e.auxiliary.has("am .+? being")||!!e.auxiliary.has("had .+? been")},toParticiple:function(e,t){if(e.auxiliary.has("(have|had)")&&e.verb.has("#Participle"))return;let n=Eo(e,t),r=n.Participle||n.PastTense;r&&e.verb.replaceWith(r,!1),e.auxiliary.has("am .+? being")&&(e.auxiliary.remove("am"),e.auxiliary.replace("being","have been")),e.auxiliary.has("have")||e.auxiliary.append("have"),e.verb.tag("Participle","toParticiple"),e.auxiliary.replace("can","could"),e.auxiliary.replace("be have","have been"),e.auxiliary.replace("not have","have not"),e.auxiliary.tag("Auxiliary")}};const jo=function(e,t){let n=e.verb;if(!e.negative.found){if(e.auxiliary.found)return e.auxiliary.eq(0).append("not"),void(e.auxiliary.has("#Modal have not")&&e.auxiliary.replace("have not","not have"));if(n.has("(#Copula|will|has|had|do)"))n.append("not");else{if(n.has("#PastTense")){let r=fo(e,t);return n.replaceWith(r,!0),void n.prepend("did not")}if(n.has("#PresentTense")){let r=fo(e,t);return n.replaceWith(r,!0),void(bo(e)?n.prepend("do not"):n.prepend("does not"))}if(n.has("#Gerund")){let r=fo(e,t);return n.replaceWith(r,!0),void n.prepend("not")}bo(e)?n.prepend("does not"):n.prepend("do not")}}},No=function(e){let t={adverb:e.match("#Adverb+"),negative:e.match("#Negative"),auxiliary:e.match("#Auxiliary+").not("(#Negative|#Adverb)"),particle:e.match("#Particle"),verb:e.match("#Verb+").not("(#Adverb|#Negative|#Auxiliary|#Particle)"),original:e,subject:vo(e)};if(t.verb.has("(#PresentTense|#PastTense|#Infinitive) #Gerund$")&&(t.verb=t.verb.not("#Gerund$")),!t.verb.found)return Object.keys(t).forEach((e=>{t[e]=t[e].not(".")})),t.verb=e,t;if(t.adverb&&t.adverb.found){let n=t.adverb.text("reduced")+"$";e.has(n)&&(t.adverbAfter=!0)}return t},xo=mo,Fo=yo,Co=Po,{toParticiple:Bo,useParticiple:Go}=Ho,zo=function(e){return e.auxiliary.remove("(will|are|am|being)"),e.auxiliary.remove("(did|does)"),e.auxiliary.remove("(had|has|have)"),e.particle.remove(),e.negative.remove(),e},Io={json:function(e){let t=null;"number"==typeof e&&(t=e,e=null),e=e||{text:!0,normal:!0,trim:!0,terms:!0};let n=[];return this.forEach((t=>{let r=t.json(e)[0],a=No(t);r.parts={},Object.keys(a).forEach((e=>{a[e]&&"Doc"===a[e].isA?r.parts[e]=a[e].text("normal"):r.parts[e]=a[e]})),r.isNegative=t.has("#Negative"),r.conjugations=Co(a,this.world),n.push(r)})),null!==t?n[t]:n},adverbs:function(){let e=[];this.forEach((t=>{let n=No(t).adverb;n.found&&(e=e.concat(n.list))}));let t=this.lookBehind("#Adverb+$");return t.found&&(e=t.list.concat(e)),t=this.lookAhead("^#Adverb+"),t.found&&(e=e.concat(t.list)),this.buildFrom(e)},isPlural:function(){let e=[];return this.forEach((t=>{let n=No(t);!0===xo(n,this.world)&&e.push(t.list[0])})),this.buildFrom(e)},isSingular:function(){let e=[];return this.forEach((t=>{let n=No(t);!1===xo(n,this.world)&&e.push(t.list[0])})),this.buildFrom(e)},conjugate:function(){let e=[];return this.forEach((t=>{let n=No(t),r=Co(n,this.world);e.push(r)})),e},toPastTense:function(){return this.forEach((e=>{let t=No(e);if(Go(t))return void Bo(t,this.world);if(e.has("#Imperative"))return;if(e.has("be")&&e.lookBehind("to$").found)return;if(t.verb.has("#Gerund")&&t.auxiliary.has("(is|will|was)"))return void e.replace("is","was");let n=Co(t,this.world).PastTense;n&&(t=zo(t),t.verb.replaceWith(n,!1),t.auxiliary.remove("(do|did|will)"))})),this},toPresentTense:function(){return this.forEach((e=>{if(e.has("#Imperative"))return;let t=No(e),n=Co(t,this.world),r=n.PresentTense;if(e.lookBehind("(i|we) (#Adverb|#Verb)?$").found&&(r=n.Infinitive),r){if(t.auxiliary.has("(have|had) been"))return t.auxiliary.replace("(have|had) been","am being"),void(n.Particle&&(r=n.Particle||n.PastTense));t.verb.replaceWith(r,!1),t.verb.tag("PresentTense"),t=zo(t),t.auxiliary.remove("#Modal"),t.auxiliary.remove("(do|did|will)")}})),this},toFutureTense:function(){return this.forEach((e=>{let t=No(e);if(Go(t))return;if(e.has("#Imperative"))return;let n=Co(t,this.world).FutureTense;n&&(t=zo(t),t.auxiliary.remove("#Modal"),t.verb.replaceWith(n,!1),t.verb.tag("FutureTense"),t.auxiliary.remove("(do|did|will)"))})),this},toInfinitive:function(){return this.forEach((e=>{let t=No(e),n=Co(t,this.world).Infinitive;n&&(e.replaceWith(n,!1),e.tag("Infinitive"))})),this},toGerund:function(){return this.forEach((e=>{let t=No(e),n=Co(t,this.world).Gerund;n&&(e.replaceWith(n,!1),e.tag("Gerund"))})),this},toParticiple:function(){return this.forEach((e=>{let t=No(e),n=!t.auxiliary.found;Bo(t,this.world),n&&(t.verb.prepend(t.auxiliary.text()),t.auxiliary.remove())})),this},isNegative:function(){return this.if("#Negative")},isPositive:function(){return this.ifNo("#Negative")},isImperative:function(){return this.if("#Imperative")},toNegative:function(){return this.list.forEach((e=>{let t=this.buildFrom([e]),n=No(t);jo(n,t.world)})),this},toPositive:function(){let e=this.match("do not #Verb");return e.found&&e.remove("do not"),this.remove("#Negative")},subject:function(){let e=[];return this.forEach((t=>{let n=Fo(t);n.list[0]&&e.push(n.list[0])})),this.buildFrom(e)}},Oo=Ia,To=[Ji,Si,_i,Ki,qi,io,lo,uo,go,function(e){class t extends e{}return Object.assign(t.prototype,Io),t.prototype.negate=t.prototype.toNegative,e.prototype.verbs=function(e){let n=this.match("(#Adverb|#Auxiliary|#Verb|#Negative|#Particle)+");n=n.not("^#Adverb+"),n=n.not("#Adverb+$");let r=n.match("(#Adverb && @hasComma) #Adverb"),a=n.not(r).splitAfter("@hasComma");return a=a.concat(r),a.sort("index"),a=a.if("#Verb"),a.has("(is|was)$")&&(a=a.splitBefore("(is|was)$")),a.has("#PresentTense #Adverb #PresentTense")&&(a=a.splitBefore("#Adverb #PresentTense")),"number"==typeof e&&(a=a.get(e)),new t(a.list,this,this.world)},e},function(e){class t extends e{}return e.prototype.people=function(e){let n=this.splitAfter("@hasComma");return n=n.match("#Person+"),"number"==typeof e&&(n=n.get(e)),new t(n.list,this,this.world)},e}],Vo={misc:Ga,selections:Ia},Mo=Mi,Jo=xt,Lo=function(e){return Object.keys(Oo).forEach((t=>e.prototype[t]=Oo[t])),To.forEach((t=>t(e))),e};class So{constructor(e,t,n){this.list=e,Object.defineProperty(this,"from",{enumerable:!1,value:t,writable:!0}),void 0===n&&void 0!==t&&(n=t.world),Object.defineProperty(this,"world",{enumerable:!1,value:n,writable:!0}),Object.defineProperty(this,"_cache",{enumerable:!1,writable:!0,value:{}}),Object.defineProperty(this,"found",{get:()=>this.list.length>0}),Object.defineProperty(this,"length",{get:()=>this.list.length}),Object.defineProperty(this,"isA",{get:()=>"Doc"})}tagger(){return Mo(this)}pool(){return this.list.length>0?this.list[0].pool:this.all().list[0].pool}}So.prototype.buildFrom=function(e){return e=e.map((e=>e.clone(!0))),new So(e,this,this.world)},So.prototype.fromText=function(e){let t=Jo(e,this.world,this.pool());return this.buildFrom(t)},Object.assign(So.prototype,Vo.misc),Object.assign(So.prototype,Vo.selections),Lo(So);const _o={untag:"unTag",and:"match",notIf:"ifNo",only:"if",onlyIf:"if"};Object.keys(_o).forEach((e=>So.prototype[e]=So.prototype[_o[e]]));const Ko=Va,qo=xt,Wo=zt,Ro=So,Uo=nt,Qo=ne$1,Zo=ot,Xo=function(e){let t=e.termList();return Ko(t,e.world),e.world.taggers.forEach((t=>{t(e)})),e},Yo=_e;var es=function e(t){let n=t;const r=function(e="",t){t&&n.addWords(t);let r=qo(e,n),a=new Ro(r,null,n);return a.tagger(),a};return r.tokenize=function(e="",t){let r=n;t&&(r=r.clone(),r.words={},r.addWords(t));let a=qo(e,r),i=new Ro(a,null,r);return(t||i.world.taggers.length>0)&&Xo(i),i},r.extend=function(e){return e(Ro,n,this,Uo,Qo,Zo),this},r.fromJSON=function(e){let t=Wo(e,n);return new Ro(t,null,n)},r.clone=function(){return e(n.clone())},r.verbose=function(e=!0){return n.verbose(e),this},r.world=function(){return n},r.parseMatch=function(e,t){return Yo(e,t)},r.version="13.11.4",r.import=r.load,r.plugin=r.extend,r}(new Rr),nlp=es,e=function(e,t){let n=e.match("#Value+? #Money+ #Currency+ (and #Money+ #Currency+)+?");return e.match("#Money").forEach((e=>{e.lookAfter("#Currency").found||(n=n.concat(e))})),"number"==typeof t&&(n=n.get(t)),n};const n="twenty|thirty|forty|fifty|sixty|seventy|eighty|ninety|fourty";var t=function(e,t){let r=e.match("#Value+");if(r.has("#NumericValue #NumericValue")&&(r.has("#Value @hasComma #Value")?r.splitAfter("@hasComma"):r.has("#NumericValue #Fraction")?r.splitAfter("#NumericValue #Fraction"):r=r.splitAfter("#NumericValue")),r.has("#Value #Value #Value")&&!r.has("#Multiple")&&r.has("("+n+") #Cardinal #Cardinal")&&(r=r.splitAfter("("+n+") #Cardinal")),r.has("#Value #Value")){r.has("#NumericValue #NumericValue")&&(r=r.splitOn("#Year")),r.has("("+n+") (eleven|twelve|thirteen|fourteen|fifteen|sixteen|seventeen|eighteen|nineteen)")&&(r=r.splitAfter("("+n+")"));let e=r.match("#Cardinal #Cardinal");if(e.found&&!r.has("(point|decimal|#Fraction)")&&!e.has("#Cardinal (#Multiple|point|decimal)")){let t=r.has(`(one|two|three|four|five|six|seven|eight|nine) (${n})`),a=e.has("("+n+") #Cardinal"),i=e.has("#Multiple #Value");t||a||i||e.terms().forEach((e=>{r=r.splitOn(e)}))}r.match("#Ordinal #Ordinal").match("#TextValue").found&&!r.has("#Multiple")&&(r.has("("+n+") #Ordinal")||(r=r.splitAfter("#Ordinal"))),r.has("#Ordinal #Cardinal")&&(r=r.splitBefore("#Cardinal+")),r.has("#TextValue #NumericValue")&&!r.has("("+n+"|#Multiple)")&&(r=r.splitBefore("#NumericValue+"))}return r.has("#NumberRange")&&(r=r.splitAfter("#NumberRange")),"number"==typeof t&&(r=r.get(t)),r},r=function(e,t){let n=e.match("#Fraction+");return n=n.filter((e=>!e.lookBehind("#Value and$").found)),"number"==typeof t&&(n=n.eq(t)),n},a=function(e,t){let n=e.match("#Percent+");return n=n.concat(e.match("[#Cardinal] percent",0)),"number"==typeof t&&(n=n.eq(t)),n},i={ones:{zeroth:0,first:1,second:2,third:3,fourth:4,fifth:5,sixth:6,seventh:7,eighth:8,ninth:9,zero:0,one:1,two:2,three:3,four:4,five:5,six:6,seven:7,eight:8,nine:9},teens:{tenth:10,eleventh:11,twelfth:12,thirteenth:13,fourteenth:14,fifteenth:15,sixteenth:16,seventeenth:17,eighteenth:18,nineteenth:19,ten:10,eleven:11,twelve:12,thirteen:13,fourteen:14,fifteen:15,sixteen:16,seventeen:17,eighteen:18,nineteen:19},tens:{twentieth:20,thirtieth:30,fortieth:40,fourtieth:40,fiftieth:50,sixtieth:60,seventieth:70,eightieth:80,ninetieth:90,twenty:20,thirty:30,forty:40,fourty:40,fifty:50,sixty:60,seventy:70,eighty:80,ninety:90},multiples:{hundredth:100,thousandth:1e3,millionth:1e6,billionth:1e9,trillionth:1e12,quadrillionth:1e15,quintillionth:1e18,sextillionth:1e21,septillionth:1e24,hundred:100,thousand:1e3,million:1e6,billion:1e9,trillion:1e12,quadrillion:1e15,quintillion:1e18,sextillion:1e21,septillion:1e24,grand:1e3}};const s=i,o=i,u=e=>{const t=[{reg:/^(minus|negative)[\s\-]/i,mult:-1},{reg:/^(a\s)?half[\s\-](of\s)?/i,mult:.5}];for(let n=0;n{if(s.ones.hasOwnProperty(e)){if(t.ones||t.teens)return!1}else if(s.teens.hasOwnProperty(e)){if(t.ones||t.teens||t.tens)return!1}else if(s.tens.hasOwnProperty(e)&&(t.ones||t.teens||t.tens))return!1;return!0},c$1=function(e){let t="0.";for(let n=0;n(e=(e=(e=(e=(e=(e=(e=e.replace(/1st$/,"1")).replace(/2nd$/,"2")).replace(/3rd$/,"3")).replace(/([4567890])r?th$/,"$1")).replace(/^[$€¥£¢]/,"")).replace(/[%$€¥£¢]$/,"")).replace(/,/g,"")).replace(/([0-9])([a-z\u00C0-\u00FF]{1,2})$/,"$1"),f=/^([0-9,\. ]+)\/([0-9,\. ]+)$/,d={"a few":3,"a couple":2,"a dozen":12,"two dozen":24,zero:0},y=e=>Object.keys(e).reduce(((t,n)=>t+e[n]),0);var p=function(e){if(!0===d.hasOwnProperty(e))return d[e];if("a"===e||"an"===e)return 1;const t=u(e);let n=null,r={},a=0,i=!1;const s=(e=t.str).split(/[ -]/);for(let e=0;e#Value+] out of every? [#Value+]");if(!0!==t.found)return null;let{num:n,den:r}=t.groups();return n&&r?(n=x(n),r=x(r),"number"==typeof n&&"number"==typeof r?{numerator:n,denominator:r}:null):null}(e)||function(e){let t=e.match("[(#Cardinal|a)+] [#Fraction+]");if(!0!==t.found)return null;let{num:n,dem:r}=t.groups();n=n.has("a")?1:x(n);let a=r.text("reduced");return b.test(a)&&(a=a.replace(b,""),r.replaceWith(a)),r=$.hasOwnProperty(a)?$[a]:x(r),"number"==typeof n&&"number"==typeof r?{numerator:n,denominator:r}:null}(e)||function(e){let t=e.match("^#Ordinal$");return!0!==t.found?null:e.lookAhead("^of .")?{numerator:1,denominator:x(t)}:null}(e)||null;return null!==t&&t.numerator&&t.denominator&&(t.decimal=t.numerator/t.denominator,t.decimal=(e=>{let t=Math.round(1e3*e)/1e3;return 0===t&&0!==e?e:t})(t.decimal)),t};const w=p,k=v;var C=function(e){let t=e.text("reduced"),n=/[0-9],[0-9]/.test(e.text("text")),r=function(e,t,n){let r=(e=e.replace(/,/g,"")).split(/^([^0-9]*)([0-9.,]*)([^0-9]*)$/);if(r&&r[2]&&t.terms().length<2){let t=parseFloat(r[2]||e);"number"!=typeof t&&(t=null);let n=r[3]||"";return"st"!==n&&"nd"!==n&&"rd"!==n&&"th"!==n||(n=""),"m"!==n&&"M"!==n||(t*=1e6,n=""),"k"!==n&&"k"!==n||(t*=1e3,n=""),{prefix:r[1]||"",num:t,suffix:n}}return null}(t,e);if(null!==r)return r.hasComma=n,r;let a=e.match("#Fraction #Fraction+$");a=!1===a.found?e.match("^#Fraction$"):a;let i=null;a.found&&(i=k(a),t=(e=(e=e.not(a)).not("and$")).text("reduced"));let s=0;return t&&(s=w(t)||0),i&&i.decimal&&(s+=i.decimal),{hasComma:n,prefix:"",num:s,suffix:""}},O=function(e){if(e<1e6)return String(e);let t;return t="number"==typeof e?e.toFixed(0):e,-1===t.indexOf("e+")?t:t.replace(".","").split("e+").reduce((function(e,t){return e+Array(t-e.length+2).join(0)}))};const V=O,F=[["ninety",90],["eighty",80],["seventy",70],["sixty",60],["fifty",50],["forty",40],["thirty",30],["twenty",20]],M=["","one","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"],E=[[1e24,"septillion"],[1e20,"hundred sextillion"],[1e21,"sextillion"],[1e20,"hundred quintillion"],[1e18,"quintillion"],[1e17,"hundred quadrillion"],[1e15,"quadrillion"],[1e14,"hundred trillion"],[1e12,"trillion"],[1e11,"hundred billion"],[1e9,"billion"],[1e8,"hundred million"],[1e6,"million"],[1e5,"hundred thousand"],[1e3,"thousand"],[100,"hundred"],[1,"one"]],N=function(e){let t=[];if(e>100)return t;for(let n=0;n=F[n][1]&&(e-=F[n][1],t.push(F[n][0]));return M[e]&&t.push(M[e]),t};var P=function(e){if(0===e||"0"===e)return"zero";e>1e21&&(e=V(e));let t=[];e<0&&(t.push("minus"),e=Math.abs(e));let n=function(e){let t=e,n=[];return E.forEach((r=>{if(e>=r[0]){let e=Math.floor(t/r[0]);t-=e*r[0],e&&n.push({unit:r[1],count:e})}})),n}(e);for(let e=0;e1&&t.push("and")),t=t.concat(N(n[e].count)),t.push(r)}return t=t.concat((e=>{const t=["zero","one","two","three","four","five","six","seven","eight","nine"];let n=[],r=V(e).match(/\.([0-9]+)/);if(!r||!r[0])return n;n.push("point");let a=r[0].split("");for(let e=0;ee)),0===t.length&&(t[0]=""),t.join(" ")};const z=O,A=P,j={one:"first",two:"second",three:"third",five:"fifth",eight:"eighth",nine:"ninth",twelve:"twelfth",twenty:"twentieth",thirty:"thirtieth",forty:"fortieth",fourty:"fourtieth",fifty:"fiftieth",sixty:"sixtieth",seventy:"seventieth",eighty:"eightieth",ninety:"ninetieth"};var q=e=>{let t=A(e).split(" "),n=t[t.length-1];return j.hasOwnProperty(n)?t[t.length-1]=j[n]:t[t.length-1]=n.replace(/y$/,"i")+"th",t.join(" ")},S={prefixes:{"¢":"cents",$:"dollars","£":"pounds","¥":"yen","€":"euros","₡":"colón","฿":"baht","₭":"kip","₩":"won","₹":"rupees","₽":"ruble","₺":"liras"},suffixes:{"%":"percent",s:"seconds",cm:"centimetres",km:"kilometres"}};const T$1=O,R=P,L=function(e){if(!e&&0!==e)return null;let t=e%100;if(t>10&&t<20)return String(e)+"th";const n={0:"th",1:"st",2:"nd",3:"rd"};let r=z(e),a=r.slice(r.length-1,r.length);return r+=n[a]?n[a]:"th",r},W=q,B=S.prefixes,D=S.suffixes,U={usd:!0,eur:!0,jpy:!0,gbp:!0,cad:!0,aud:!0,chf:!0,cny:!0,hkd:!0,nzd:!0,kr:!0,rub:!0},K=function(e){return B.hasOwnProperty(e.prefix)&&(e.suffix+=B[e.prefix],e.prefix=""),D.hasOwnProperty(e.suffix)&&(e.suffix=D[e.suffix]),U.hasOwnProperty(e.suffix)&&(e.suffix=e.suffix.toUpperCase()),e.suffix&&(e.suffix=" "+e.suffix),e};var Y=function(e,t,n){let r=String(e.num);return t?(e=K(e),n?(r=W(r),`${e.prefix||""}${r}${e.suffix||""}`):(r=R(r),`${e.prefix||""}${r}${e.suffix||""}`)):n?(r=L(r),`${(e=K(e)).prefix||""}${r}${e.suffix||""}`):(!0===e.hasComma&&(r=e.num.toLocaleString()),r=T$1(r),`${e.prefix||""}${r}${e.suffix||""}`)};const G=C,H=function(e,t,n){if(!1===e)return;let r=t.lookAhead("^(#Unit|#Noun)");r.has("(#Address|#Money|#Percent)")||t.has("#Ordinal")||(1===n.num?r.nouns().toSingular():r.has("#Singular")&&r.nouns().toPlural())},I=Y,Q=p;let Z={json:function(e){let t=null;"number"==typeof e&&(t=e,e=null),e=e||{text:!0,normal:!0,trim:!0,terms:!0};let n=[];return this.forEach((t=>{let r=t.json(e)[0],a=G(t);r.prefix=a.prefix,r.number=a.num,r.suffix=a.suffix,r.cardinal=I(a,!1,!1),r.ordinal=I(a,!1,!0),r.textCardinal=I(a,!0,!1),r.textOrdinal=I(a,!0,!0),n.push(r)})),null!==t?n[t]:n},units:function(){let e=this.lookAhead("(#Unit|#Noun)+");return e=e.splitAfter("@hasComma").first(),e=e.not("#Pronoun"),e.first()},isOrdinal:function(){return this.if("#Ordinal")},isCardinal:function(){return this.if("#Cardinal")},toNumber:function(){return this.forEach((e=>{let t=G(e);if(null===t.num)return;let n=I(t,!1,e.has("#Ordinal"));e.replaceWith(n,!0),e.tag("NumericValue")})),this},toLocaleString:function(){return this.forEach((e=>{let t=G(e);if(null===t.num)return;t.num=t.num.toLocaleString();let n=I(t,!1,e.has("#Ordinal"));e.replaceWith(n,!0)})),this},toText:function(){return this.forEach((e=>{let t=G(e);if(null===t.num)return;let n=I(t,!0,e.has("#Ordinal"));e.replaceWith(n,!0),e.tag("TextValue")})),this},toCardinal:function(e){return this.if("#Ordinal").forEach((t=>{let n=G(t);if(null===n.num)return;let r=I(n,t.has("#TextValue"),!1);if(t.has("#NumberRange")){let e=t.termList()[0];e.text&&""===e.post&&(e.post=" ")}t.replaceWith(r,!0),t.tag("Cardinal"),H(e,t,n)})),this},toOrdinal:function(){return this.if("#Cardinal").forEach((e=>{let t=G(e);if(null===t.num)return;let n=I(t,e.has("#TextValue"),!0);if(e.has("#NumberRange")){let t=e.termList()[0];t.text&&""===t.post&&(t.post=" ")}e.replaceWith(n,!0),e.tag("Ordinal");let r=this.lookAhead("^#Plural");r.found&&r.nouns().toSingular()})),this},isEqual:function(e){return this.filter((t=>G(t).num===e))},greaterThan:function(e){return this.filter((t=>G(t).num>e))},lessThan:function(e){return this.filter((t=>G(t).num{let r=G(n).num;return r>e&&r{let r=G(n);if(r.num=e,null===r.num)return;let a=I(r,n.has("#TextValue"),n.has("#Ordinal"));(n=n.not("#Currency")).replaceWith(a,!0),H(t,n,r)}))),this},add:function(e,t){return e?("string"==typeof e&&(e=Q(e)),this.forEach((n=>{let r=G(n);if(null===r.num)return;r.num+=e;let a=I(r,n.has("#TextValue"),n.has("#Ordinal"));(n=n.not("#Currency")).replaceWith(a,!0),H(t,n,r)})),this):this},subtract:function(e,t){return this.add(-1*e,t)},increment:function(e){return this.add(1,e),this},decrement:function(e){return this.add(-1,e),this},romanNumerals:function(e){let t=this.match("#RomanNumeral").numbers();return"number"==typeof e&&(t=t.get(e)),t},normalize:function(){const e={"%":!0};return this.forEach((t=>{let n=G(t);if(null!==n.num&&n.suffix&&!0!==e[n.suffix]){let e=n.prefix||"";t=t.replaceWith(e+n.num+" "+n.suffix)}})),this},get:function(e){let t=[];return this.forEach((e=>{t.push(G(e).num)})),void 0!==e?t[e]||null:t||null}};Z.toNice=Z.toLocaleString,Z.isBetween=Z.between,Z.minus=Z.subtract,Z.plus=Z.add,Z.equals=Z.isEqual;var J=Z;const X=C,_=function(e){let t=X(e).num;return"number"==typeof t?t/100:null};var ee={get:function(e){let t=[];return this.forEach((e=>{let n=_(e);null!==n&&t.push(n)})),void 0!==e?t[e]||null:t||null},json:function(e){let t=null;"number"==typeof e&&(t=e,e=null),e=e||{text:!0,normal:!0,trim:!0,terms:!0};let n=[];return this.forEach((t=>{let r=t.json(e)[0],a=_(t);if(r.number=a,null!==a){let e=100*a;r.textNumber=`${e} percent`,r.cardinal=`${e}%`}n.push(r)})),null!==t?n[t]||{}:n},toFraction:function(){return this.forEach((e=>{let t=_(e);if(null!==t){t*=100,t=Math.round(100*t)/100;let n=`${t}/100`;this.replace(e,n)}})),this}},ne=[{dem:"american",name:"dollar",iso:"usd",sub:"cent",sym:["$","US$","U$"]},{name:"euro",iso:"eur",sub:"cent",sym:["€"]},{dem:"british",name:"pound",iso:"gbp",sub:"penny",alias:{sterling:!0},sym:["£"]},{name:"renminbi",iso:"cny",plural:"yuán",alias:{yuan:!0},sym:["元"]},{dem:"japanese",name:"yen",iso:"jpy",sub:"sen",sym:["¥","円","圓"]},{dem:"swedish",name:"krona",iso:"sek",sub:"öre",alias:{ore:!0,kronor:!0},sym:["kr"]},{dem:"estonian",name:"kroon",iso:"eek",sub:"sent",sym:["kr"]},{dem:"norwegian",name:"krone",iso:"nok",sub:"øre",sym:["kr"]},{dem:"icelandic",name:"króna",iso:"isk",sym:["kr"]},{dem:"danish",name:"krone",iso:"dkk",sub:"øre",sym:["kr."]},{dem:"zambian",name:"kwacha",iso:"zmw",sub:"ngwee",sym:["K"]},{dem:"malawian",name:"kwacha",iso:"mwk",sub:"tambala",sym:["K"]},{dem:"greek",name:"drachma",iso:"grd",sub:"leptοn",sym:["Δρχ.","Δρ.","₯"]},{dem:"eastern caribbean",name:"dollar",iso:"xcd",sub:"cent",sym:["$"]},{dem:"finnish",name:"markka",iso:"fim",sub:"penni",sym:["mk"]},{dem:"polish",name:"złoty",iso:"pln",sub:"grosz",sym:["zł"]},{dem:"slovenian",name:"tolar",iso:"sit",sub:"stotin",sym:[]},{dem:"australian",name:"dollar",iso:"aud",sub:"cent",sym:["$","A$","AU$"]},{dem:"deutsche",name:"mark",iso:"dem",sub:"pfennig",sym:["DM"]},{dem:"thai",name:"baht",iso:"thb",sub:"satang",sym:["฿"]},{dem:"canadian",name:"dollar",iso:"cad",sub:"cent",sym:["$","Can$","C$","CA$","CAD"]},{dem:"mexican",name:"peso",iso:"mxn",sub:"centavo",sym:["$","Mex$"]},{dem:"spanish",name:"peseta",iso:"esp",sub:"céntimo",sym:["Pta"]},{dem:"new zealand",name:"dollar",iso:"nzd",sub:"cent",sym:["$","NZ$"]},{dem:"chilean",name:"peso",iso:"clp",sub:"centavo",sym:["Cifrão","$"]},{dem:"nigerian",name:"naira",iso:"ngn",sub:"kobo",sym:["₦"]},{dem:"austrian",name:"schilling",iso:"ats",sub:"groschen",sym:["S","öS"]},{dem:"guatemalan",name:"quetzal",iso:"gtq",sub:"centavo",sym:["Q"]},{dem:"philippine",name:"peso",iso:"php",sub:"sentimo",sym:["₱"]},{dem:"hungarian",name:"forint",iso:"huf",sym:["Ft"]},{dem:"russian",name:"ruble",iso:"rub",sub:"kopeyka",sym:["₽","руб","р."]},{dem:"kuwaiti",name:"dinar",iso:"kwd",sub:"fils",sym:["د.ك","KD"]},{dem:"israeli",name:"new shekel",iso:"ils",sub:"agora",sym:["₪"]},{dem:"latvian",name:"lats",iso:"lvl",sub:"santīms",sym:["Ls"]},{dem:"kazakhstani",name:"tenge",iso:"kzt",sub:"tıyn",sym:["₸"]},{dem:"iraqi",name:"dinar",iso:"iqd",sub:"fils",sym:["د.ع"]},{dem:"bahamian",name:"dollar",iso:"bsd",sub:"cent",sym:["$","B$"]},{dem:"seychellois",name:"rupee",iso:"scr",sub:"cent",sym:["SCR","SR"]},{dem:"albanian",name:"lek",iso:"all",sub:"qindarkë",sym:["L"]},{dem:"bulgarian",name:"lev",iso:"bgn",sub:"stotinka",sym:["лв."]},{dem:"irish",name:"pound",iso:"iep",sym:["£","IR£"]},{name:"cfp franc",iso:"xpf",sym:["f"]},{dem:"south african",name:"rand",iso:"zar",sub:"cent",sym:["R"]},{dem:"south korean",name:"won",iso:"krw",sub:"jeon",plural:"won",sym:["₩"]},{dem:"north korean",name:"won",iso:"kpw",sub:"chon",plural:"won",sym:["₩"]},{dem:"portuguese",name:"escudo",iso:"pte",sub:"centavo",sym:[]},{dem:"ghanaian",name:"cedi",iso:"ghs",sub:"pesewa",sym:["GH₵"]},{dem:"hong kong",name:"dollar",iso:"hkd",sub:"毫",sym:["$"]},{dem:"new taiwan",name:"dollar",iso:"twd",sub:"dime",sym:["NT$"]},{dem:"east german",name:"mark",iso:"ddm",sub:"pfennig",sym:["M"]},{dem:"namibian",name:"dollar",iso:"nad",sub:"cent",sym:["$"]},{dem:"malaysian",name:"ringgit",iso:"myr",sub:"sen",sym:["RM"]},{dem:"swiss",name:"franc",iso:"chf",sym:["Rp."]},{dem:"panamanian",name:"balboa",iso:"pab",sub:"centésimo",sym:["B/."]},{dem:"indonesian",name:"rupiah",iso:"idr",sub:"sen",sym:["Rp"]},{dem:"brunei",name:"dollar",iso:"bnd",sub:"sen",sym:["$","B$"]},{dem:"venezuelan",name:"bolívar",iso:"vef",sub:"céntimo",sym:["Bs.F","Bs."]},{dem:"macedonian",name:"denar",iso:"mkd",sub:"deni",sym:["den"]},{dem:"mauritanian",name:"ouguiya",iso:"mru",sub:"khoums",sym:["UM"]},{dem:"argentine",name:"peso",iso:"ars",sub:"centavo",sym:["$"]},{dem:"libyan",name:"dinar",iso:"lyd",sub:"dirham",sym:["LD","ل.د"]},{dem:"jordanian",name:"dinar",iso:"jod",sub:"dirham",sym:["د.أ"]},{dem:"french",name:"franc",iso:"frf",sub:"centime",sym:["F","Fr","FF","₣"]},{dem:"syrian",name:"pound",iso:"syp",sub:"piastre",sym:["LS","£S"]},{dem:"belize",name:"dollar",iso:"bzd",sub:"cent",sym:["$"]},{dem:"saudi",name:"riyal",iso:"sar",sub:"halalah",sym:["SAR","ر.س"," ﷼"]},{dem:"surinamese",name:"dollar",iso:"srd",sub:"cent",sym:["$"]},{dem:"singapore",name:"dollar",iso:"sgd",sub:"cent",sym:["S$","$"]},{dem:"nepalese",name:"rupee",iso:"npr",sub:"paisa",sym:["रु ₨","Re"]},{dem:"nicaraguan",name:"córdoba",iso:"nio",sub:"centavo",sym:["C$"]},{dem:"bangladeshi",name:"taka",iso:"bdt",sub:"poysha",sym:["৳"]},{dem:"indian",name:"rupee",iso:"inr",sub:"paisa",sym:["₹"]},{dem:"maldivian",name:"rufiyaa",iso:"mvr",sub:"laari",sym:["Rf","MRf","MVR",".ރ "]},{dem:"sri lankan",name:"rupee",iso:"lkr",sub:"cents",sym:["Rs","රු","ரூ"]},{dem:"bhutanese",name:"ngultrum",iso:"btn",sub:"chhertum",sym:["Nu."]},{dem:"turkish",name:"lira",iso:"try",sub:"kuruş",sym:["YTL"]},{dem:"serbian",name:"dinar",iso:"rsd",sub:"para",sym:["din","дин"]},{dem:"bosnia and herzegovina",name:"convertible mark",iso:"bam",sub:"fening",sym:["KM"]},{dem:"botswana",name:"pula",iso:"bwp",sub:"thebe",sym:["p"]},{dem:"swazi",name:"lilangeni",iso:"szl",sub:"cent",sym:["L","E"]},{dem:"lithuanian",name:"litas",iso:"ltl",sub:"centas",sym:["Lt","ct"]},{dem:"mauritian",name:"rupee",iso:"mur",sub:"cent",sym:["₨"]},{dem:"pakistani",name:"rupee",iso:"pkr",sub:"paisa",sym:["₨"]},{dem:"maltese",name:"lira",iso:"mtl",sub:"cent",sym:["₤","Lm"]},{dem:"cypriot",name:"pound",iso:"cyp",sub:"cent",sym:["£"]},{dem:"moldovan",name:"leu",iso:"mdl",sym:["l"]},{dem:"croatian",name:"kuna",iso:"hrk",sub:"lipa",sym:["kn"]},{dem:"afghan",name:"afghani",iso:"afn",sub:"pul",sym:["؋","Af","Afs"]},{dem:"ecuadorian",name:"sucre",iso:"ecs",sub:"centavo",sym:["S/."]},{dem:"sierra leonean",name:"leone",iso:"sll",sub:"cent",sym:["Le"]}];const te=ne,re=C,ae={};let ie={};te.forEach((e=>{e.sym.forEach((t=>{ae[t]=ae[t]||e.iso})),ae[e.iso]=ae[e.iso]||e.iso,e.sub&&(ie[e.sub]=!0)}));let se=`(${Object.keys(ie).join("|")})`;const oe=Y,ue=function(e){let t=0,n=e.match(`and #Money+ ${se}`);if(n.found){e=e.not(n);let r=re(n.match("#Value+"));r&&r.num&&(t=r.num/100)}let r=re(e),a=r.num||0;a+=t;let i=((s=r).suffix&&ae.hasOwnProperty(s.suffix)?te.find((e=>e.iso===ae[s.suffix])):s.prefix&&ae.hasOwnProperty(s.prefix)?te.find((e=>e.iso===ae[s.prefix])):null)||function(e){let t=e.match("#Currency+");t.nouns().toSingular();let n=t.text("reduced");return te.find((e=>(n===`${e.dem} ${e.name}`||n===e.iso||n===e.sub||n===e.name||!(!e.alias||!0!==e.alias[n]))&&e))}(e)||{};var s;let o="";return i&&i.sym&&(o=i.sym[0],a&&e.has(`${se}`)&&(a/=100)),{num:a,iso:i.iso,demonym:i.dem,currency:i.name,plural:i.plural,symbol:o}},le=function(e=""){return e.replace(/\w\S*/g,(function(e){return e.charAt(0).toUpperCase()+e.substr(1).toLowerCase()}))};var me$1={get:function(e){let t=[];return this.forEach((e=>{t.push(ue(e))})),void 0!==e?t[e]||null:t||null},currency:function(e){let t=[];return this.forEach((e=>{let n=ue(e);n&&t.push(n)})),"number"==typeof e?t[e]||null:t||null},json:function(e){let t=null;"number"==typeof e&&(t=e,e=null),e=e||{text:!0,normal:!0,trim:!0,terms:!0};let n=[];return this.forEach((t=>{let r=t.json(e)[0],a=ue(t);if(r.number=a.num,a.iso&&(r.iso=a.iso.toUpperCase(),r.symbol=a.symbol,r.currency=le(a.demonym)+" "+le(a.currency)),r.textFmt=oe(a,!0,!1),a.currency){let e=a.currency;1!==a.num&&(e=a.plural||e+"s"),r.textFmt+=" "+e}n.push(r)})),null!==t?n[t]||{}:n}},ce={};const he=P,fe=q;ce.toText=function(e){if(!e.numerator||!e.denominator)return"";let t=he(e.numerator),n=fe(e.denominator);return 2===e.denominator&&(n="half"),t&&n?(1!==e.numerator&&(n+="s"),`${t} ${n}`):""},ce.textCardinal=function(e){return e.numerator&&e.denominator?`${he(e.numerator)} out of ${he(e.denominator)}`:""},ce.toDecimal=function(e){return e.decimal};const de=v,ye=ce,pe={get:function(e){let t=[];return this.forEach((e=>{t.push(de(e))})),void 0!==e?t[e]||null:t||null},toDecimal(){return this.forEach((e=>{let t=de(e);if(t){let n=ye.toDecimal(t);e.replaceWith(String(n),!0),e.tag("NumericValue"),e.unTag("Fraction")}})),this},json:function(e){let t=null;"number"==typeof e&&(t=e,e=null),e=e||{text:!0,normal:!0,trim:!0,terms:!0};let n=[];return this.forEach((t=>{let r=t.json(e)[0],a=de(t)||{},i=ye.toDecimal(a);r.numerator=a.numerator,r.denominator=a.denominator,r.number=i,r.textOrdinal=ye.toText(a),r.textCardinal=ye.textCardinal(a),n.push(r)})),null!==t?n[t]||{}:n},normalize:function(){return this.forEach((e=>{let t=de(e);if(t&&"number"==typeof t.numerator&&"number"==typeof t.denominator){let n=`${t.numerator}/${t.denominator}`;this.replace(e,n)}})),this},toText:function(e){let t=[];return this.forEach((e=>{let t=de(e)||{},n=ye.toText(t);e.replaceWith(n,!0),e.tag("Fraction")})),void 0!==e?t[e]:t},toPercentage:function(){return this.forEach((e=>{let t=de(e);if(t.decimal||0===t.decimal){let n=100*t.decimal;n=Math.round(100*n)/100,this.replace(e,`${n}%`)}})),this}};pe.toNumber=pe.toDecimal;var be=pe;const ge=function(e){return e.match("(hundred|thousand|million|billion|trillion|quadrillion|quintillion|sextillion|septillion)").tag("#Multiple","fraction-tagger"),e.match("[(half|quarter)] of? (a|an)",0).tag("Fraction","millionth"),e.match("#Adverb [half]",0).tag("Fraction","nearly-half"),e.match("[half] the",0).tag("Fraction","half-the"),e.match("#Value (halves|halfs|quarters)").tag("Fraction","two-halves"),e.match("a #Ordinal").tag("Fraction","a-quarter"),e.match("(#Fraction && /s$/)").lookBefore("#Cardinal+$").tag("Fraction"),e.match("[#Cardinal+ #Ordinal] of .",0).tag("Fraction","ordinal-of"),e.match("[(#NumericValue && #Ordinal)] of .",0).tag("Fraction","num-ordinal-of"),e.match("(a|one) #Cardinal?+ #Ordinal").tag("Fraction","a-ordinal"),e.match("#Cardinal+ out? of every? #Cardinal").tag("Fraction","fraction-tagger"),e},xe=function(e){const t="money-tagger";e.match("#Money and #Money #Currency?").tag("Money","money-and-money"),e.match("#Money").not("#TextValue").match("/\\.[0-9]{3}$/").unTag("#Money","three-decimal money"),e.ifNo("#Value").match("#Currency #Verb").unTag("Currency","no-currency"),e.match("#Value #Currency [and] #Value (cents|ore|centavos|sens)",0).tag("Money",t);let n=e.match("[#Value] [(mark|rand|won|rub|ore)]");return n.group("num").tag("Money",t),n.group("currency").tag("Currency",t),e};var $e=function(e){(e=xe(e)).match("the [/[0-9]+s$/]").tag("#Plural","number-tag"),e.match("half a? #Value").tag("Value","half-a-value"),e.match("#Value [and a (half|quarter)]",0).tag(["TextValue","#Fraction"],"value-and-a-half"),(e=ge(e)).match("#Cardinal and #Fraction #Fraction").tag("Value","number-tag")};const ve={mark:!0,sucre:!0,leone:!0,afghani:!0,rand:!0,try:!0,mop:!0,won:!0,all:!0,rub:!0,eek:!0,sit:!0,bam:!0,npr:!0,leu:!0};let we={kronor:"Currency"};ne.forEach((e=>{e.iso&&!ve[e.iso]&&(we[e.iso]=["Acronym","Currency"]);let t=e.name;if(t&&!ve[t]&&(we[t]="Currency",we[t+"s"]="Currency"),e.dem){let n=e.dem;we[`${n} ${t}`]="Currency",we[`${n} ${t}s`]="Currency"}e.sub&&(we[e.sub]="Currency")}));const ke=e,Ce=t,Oe=r,Ve=a,Fe=J,Me=ee,Ee=me$1,Ne=be,Pe=$e,ze={Fraction:{isA:["Value"]},Multiple:{isA:"Value"}},Ae=we;var je=function(e,t){t.addWords(Ae),t.addTags(ze),t.postProcess(Pe);class n extends e{}Object.assign(n.prototype,Fe);class r extends n{}Object.assign(r.prototype,Ee);class a extends n{}Object.assign(a.prototype,Ne);class i extends n{}Object.assign(i.prototype,Me);const s={numbers:function(e){let t=Ce(this,e);return new n(t.list,this,this.world)},percentages:function(e){let t=Ve(this,e);return new i(t.list,this,this.world)},fractions:function(e){let t=Oe(this,e);return new a(t.list,this,this.world)},money:function(e){let t=ke(this,e);return new r(t.list,this,this.world)}};return s.values=s.numbers,s.percents=s.percentages,Object.assign(e.prototype,s),e},compromise_numbers=je;nlp.extend(compromise_numbers);class Pluralize extends Text{static componentType="pluralize";static rendererType="text";static createAttributesObject(){let e=super.createAttributesObject();return e.pluralForm={createComponentOfType:"text",createStateVariable:"pluralForm",defaultValue:null,public:!0},e.basedOnNumber={createComponentOfType:"number",createStateVariable:"basedOnNumber",defaultValue:null,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return renameStateVariable({stateVariableDefinitions:e,oldName:"value",newName:"valuePrePluralize"}),e.value={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({valuePrePluralize:{dependencyType:"stateVariable",variableName:"valuePrePluralize"},pluralForm:{dependencyType:"stateVariable",variableName:"pluralForm"},basedOnNumber:{dependencyType:"stateVariable",variableName:"basedOnNumber"}}),definition:function({dependencyValues:e}){let t,n=nlp(e.valuePrePluralize),r=n.values().toNumber().all().terms().json();if(0===r.length)return{setValue:{value:e.valuePrePluralize}};if(null!==e.basedOnNumber&&(t=numberDesignatesPlural(e.basedOnNumber)),1===r.length)return void 0===t&&(t=!0),t?null!==e.pluralForm?{setValue:{value:e.pluralForm}}:{setValue:{value:n.nouns().toPlural().all().out("text")}}:{setValue:{value:e.valuePrePluralize}};if(void 0===t){let e=[],a=[],i=n.nouns().json();for(let[t,n]of r.entries()){let r=i[e.length];n.terms[0].tags.includes("Value")&&a.push(t),void 0!==r&&r.text===n.text&&e.push(t)}t=[];let s=n.values().numbers().json(),o=-1;for(let n of e){for(;Number(a[o+1])({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:({dependencyValues:e})=>({setValue:{text:e.value}})},e}}function numberDesignatesPlural(e){return 1!==e}class Feedback extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{updateHide:this.updateHide.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="feedback";static renderChildren=!0;static primaryStateVariableForDefinition="feedbackText";static createAttributesObject(){let e=super.createAttributesObject();return delete e.hide,e.condition={createComponentOfType:"boolean"},e.updateWith={createTargetComponentNames:!0},e}static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.updateWithComponentNames={chainActionOnActionOfStateVariableTargets:{triggeredAction:"updateHide"},returnDependencies:()=>({updateWith:{dependencyType:"attributeTargetComponentNames",attributeName:"updateWith"}}),definition:({dependencyValues:e})=>e.updateWith?{setValue:{updateWithComponentNames:e.updateWith.map((e=>e.absoluteName))}}:{setValue:{updateWithComponentNames:[]}}},e.hideWhenUpdated={returnDependencies:()=>({condition:{dependencyType:"attributeComponent",attributeName:"condition",variableNames:["value"]},showFeedback:{dependencyType:"flag",flagName:"showFeedback"}}),definition:function({dependencyValues:e}){if(!e.showFeedback)return{setValue:{hideWhenUpdated:!0}};let t;return t=null!==e.condition&&!e.condition.stateValues.value,{setValue:{hideWhenUpdated:t}}}},e.hide={forRenderer:!0,defaultValue:!0,hasEssential:!0,returnDependencies:()=>({updateWith:{dependencyType:"attributeTargetComponentNames",attributeName:"updateWith"},condition:{dependencyType:"attributeComponent",attributeName:"condition",variableNames:["value"]},showFeedback:{dependencyType:"flag",flagName:"showFeedback"}}),definition:function({dependencyValues:e}){if(e.updateWith)return{useEssentialOrDefaultValue:{hide:!0}};if(!e.showFeedback)return{setValue:{hide:!0}};let t;return t=null!==e.condition&&!e.condition.stateValues.value,{setValue:{hide:t}}},inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t})=>t.updateWith?{success:!0,instructions:[{setEssentialValue:"hide",value:e.hide}]}:{success:!1}},e.feedbackText={forRenderer:!0,defaultValue:null,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{feedbackText:!0}})},e}async updateHide({actionId:e}){let t=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"hide",value:await this.stateValues.hideWhenUpdated}];return await this.coreFunctions.performUpdate({updateInstructions:t,actionId:e})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class CollaborateGroups extends BaseComponent{static componentType="collaborateGroups";static rendererType=void 0;static stateVariableForAttributeValue="collaborateGroups";static returnChildLogic(e){let t=super.returnChildLogic(e),n=t.newLeaf({name:"atLeastZeroPoints",componentType:"point",comparison:"atLeast",number:0}),r=breakStringsAndOthersIntoComponentsByStringCommas(),a=t.newLeaf({name:"exactlyOneString",componentType:"string",number:1,isSugar:!0,logicToWaitOnSugar:["atLeastZeroPoints"],replacementFunction:r});return t.newOperator({name:"pointsXorSugar",operator:"xor",propositions:[a,n],setAsBase:!0}),t}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.collaborateGroups={returnDependencies:()=>({pointChildren:{dependencyType:"child",childLogicName:"atLeastZeroPoints",variableNames:["xs","coords","nDimensions"]}}),definition:function({dependencyValues:e}){let t={};for(let n of e.pointChildren)if(2!==n.stateValues.nDimensions)console.warn(`invalid collaborate group: ${n.stateValues.coords.toString()}`);else{let e=n.stateValues.xs[0].evaluate_to_constant(),r=n.stateValues.xs[1].evaluate_to_constant();Number.isInteger(e)&&e>0&&Number.isInteger(r)&&r>0?(void 0===t[e]&&(t[e]=[]),t[e].push(r)):console.warn(`invalid collaborate group: ${n.stateValues.coords.toString()}`)}return{setValue:{collaborateGroups:{groups:t,matchGroup:function({groupNumber:e,numberOfGroups:n}={}){if(n>1){let r=t[n];return void 0!==r&&r.includes(e)}return!0}}}}}},e}}class CollaborateGroupSetup extends BaseComponent{static componentType="collaborateGroupSetup";static returnChildLogic(e){let t=super.returnChildLogic(e);return t.newLeaf({name:"atMostOnePossibleNumberOfGroups",componentType:"possibleNumberOfGroups",comparison:"atMost",number:1,setAsBase:!0}),t}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.possibleNumberOfGroups={returnDependencies:()=>({pngChild:{dependencyType:"child",childLogicName:"atMostOnePossibleNumberOfGroups",variableNames:["numbers"]}}),definition:function({dependencyValues:e}){return 0===e.pngChild.length?{setValue:{possibleNumberOfGroups:[1]}}:{setValue:{possibleNumberOfGroups:e.pngChild[0].stateValues.numbers}}}},e}}class ConsiderAsResponses extends BaseComponent{static componentType="considerAsResponses";static rendererType=void 0;static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.childrenWithNValues={returnDependencies:()=>({children:{dependencyType:"child",childGroups:["anything"],variableNames:["nValues"],variablesOptional:!0}}),definition:({dependencyValues:e})=>({setValue:{childrenWithNValues:e.children}})},e.childrenAsResponses={returnDependencies:()=>({children:{dependencyType:"child",childGroups:["anything"],variableNames:["value","values","componentType"],variablesOptional:!0}}),definition:({dependencyValues:e})=>({setValue:{childrenAsResponses:e.children}})},e}}class Case extends Template{static componentType="case";static createAttributesObject(){let e=super.createAttributesObject();return e.condition={createComponentOfType:"boolean"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.conditionSatisfied={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({condition:{dependencyType:"attributeComponent",attributeName:"condition",variableNames:["value"]}}),definition:function({dependencyValues:e}){let t;return t=null===e.condition||e.condition.stateValues.value,{setValue:{conditionSatisfied:t}}}},e}static createSerializedReplacements({component:e,componentInfoObjects:t}){return e.stateValues.conditionSatisfied?super.createSerializedReplacements({component:e,componentInfoObjects:t}):{replacements:[]}}}var dist={},formats={};Object.defineProperty(formats,"__esModule",{value:!0}),formats.FORMAT_PLAIN=formats.FORMAT_HTML=formats.FORMATS=void 0;var FORMAT_HTML="html";formats.FORMAT_HTML=FORMAT_HTML;var FORMAT_PLAIN="plain";formats.FORMAT_PLAIN=FORMAT_PLAIN;var FORMATS=[FORMAT_HTML,FORMAT_PLAIN];formats.FORMATS=FORMATS;var units={};Object.defineProperty(units,"__esModule",{value:!0}),units.UNIT_WORDS=units.UNIT_WORD=units.UNIT_SENTENCES=units.UNIT_SENTENCE=units.UNIT_PARAGRAPHS=units.UNIT_PARAGRAPH=units.UNITS=void 0;var UNIT_WORDS="words";units.UNIT_WORDS=UNIT_WORDS;var UNIT_WORD="word";units.UNIT_WORD=UNIT_WORD;var UNIT_SENTENCES="sentences";units.UNIT_SENTENCES=UNIT_SENTENCES;var UNIT_SENTENCE="sentence";units.UNIT_SENTENCE=UNIT_SENTENCE;var UNIT_PARAGRAPHS="paragraphs";units.UNIT_PARAGRAPHS=UNIT_PARAGRAPHS;var UNIT_PARAGRAPH="paragraph";units.UNIT_PARAGRAPH=UNIT_PARAGRAPH;var UNITS=[UNIT_WORDS,UNIT_WORD,UNIT_SENTENCES,UNIT_SENTENCE,UNIT_PARAGRAPHS,UNIT_PARAGRAPH];units.UNITS=UNITS;var words={};Object.defineProperty(words,"__esModule",{value:!0}),words.WORDS=void 0;var WORDS=["ad","adipisicing","aliqua","aliquip","amet","anim","aute","cillum","commodo","consectetur","consequat","culpa","cupidatat","deserunt","do","dolor","dolore","duis","ea","eiusmod","elit","enim","esse","est","et","eu","ex","excepteur","exercitation","fugiat","id","in","incididunt","ipsum","irure","labore","laboris","laborum","Lorem","magna","minim","mollit","nisi","non","nostrud","nulla","occaecat","officia","pariatur","proident","qui","quis","reprehenderit","sint","sit","sunt","tempor","ullamco","ut","velit","veniam","voluptate"];words.WORDS=WORDS;var LoremIpsum={},lineEndings={};Object.defineProperty(lineEndings,"__esModule",{value:!0}),lineEndings.LINE_ENDINGS=void 0;var LINE_ENDINGS={POSIX:"\n",WIN32:"\r\n"};lineEndings.LINE_ENDINGS=LINE_ENDINGS;var generator={},util={},capitalize={};!function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var t=function(e){var t=e.trim();return t.charAt(0).toUpperCase()+t.slice(1)};e.default=t}(capitalize);var isNode={exports:{}};!function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var n=function(){return!!e.exports};t.default=n}(isNode,isNode.exports);var isReactNative={};!function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var t=function(){var e=!1;try{e="ReactNative"===navigator.product}catch(t){e=!1}return e};e.default=t}(isReactNative);var isWindows={},platforms={};Object.defineProperty(platforms,"__esModule",{value:!0}),platforms.SUPPORTED_PLATFORMS=void 0;var SUPPORTED_PLATFORMS={DARWIN:"darwin",LINUX:"linux",WIN32:"win32"};platforms.SUPPORTED_PLATFORMS=SUPPORTED_PLATFORMS,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var t=platforms,n=function(){var e=!1;try{e=browser$1.platform===t.SUPPORTED_PLATFORMS.WIN32}catch(t){e=!1}return e};e.default=n}(isWindows);var makeArrayOfLength={};!function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var t=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;return Array.apply(null,Array(e)).map((function(e,t){return t}))};e.default=t}(makeArrayOfLength);var makeArrayOfStrings={};!function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var t,n=(t=makeArrayOfLength)&&t.__esModule?t:{default:t};var r=function(e,t){return(0,n.default)(e).map((function(){return t()}))};e.default=r}(makeArrayOfStrings),function(e){Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"capitalize",{enumerable:!0,get:function(){return t.default}}),Object.defineProperty(e,"isNode",{enumerable:!0,get:function(){return n.default}}),Object.defineProperty(e,"isReactNative",{enumerable:!0,get:function(){return r.default}}),Object.defineProperty(e,"isWindows",{enumerable:!0,get:function(){return a.default}}),Object.defineProperty(e,"makeArrayOfLength",{enumerable:!0,get:function(){return i.default}}),Object.defineProperty(e,"makeArrayOfStrings",{enumerable:!0,get:function(){return s.default}});var t=o(capitalize),n=o(isNode.exports),r=o(isReactNative),a=o(isWindows),i=o(makeArrayOfLength),s=o(makeArrayOfStrings);function o(e){return e&&e.__esModule?e:{default:e}}}(util),function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var t=words,n=util;function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:{},a=n.sentencesPerParagraph,s=void 0===a?{max:7,min:3}:a,o=n.wordsPerSentence,l=void 0===o?{max:15,min:5}:o,u=n.random;n.seed;var c=n.words,p=void 0===c?t.WORDS:c;if(r(this,e),i(this,"sentencesPerParagraph",void 0),i(this,"wordsPerSentence",void 0),i(this,"random",void 0),i(this,"words",void 0),s.min>s.max)throw new Error("Minimum number of sentences per paragraph (".concat(s.min,") cannot exceed maximum (").concat(s.max,")."));if(l.min>l.max)throw new Error("Minimum number of words per sentence (".concat(l.min,") cannot exceed maximum (").concat(l.max,")."));this.sentencesPerParagraph=s,this.words=p,this.wordsPerSentence=l,this.random=u||Math.random}var s,o,l;return s=e,(o=[{key:"generateRandomInteger",value:function(e,t){return Math.floor(this.random()*(t-e+1)+e)}},{key:"generateRandomWords",value:function(e){var t=this,r=this.wordsPerSentence,a=r.min,i=r.max,s=e||this.generateRandomInteger(a,i);return(0,n.makeArrayOfLength)(s).reduce((function(e,n){return"".concat(t.pluckRandomWord()," ").concat(e)}),"").trim()}},{key:"generateRandomSentence",value:function(e){return"".concat((0,n.capitalize)(this.generateRandomWords(e)),".")}},{key:"generateRandomParagraph",value:function(e){var t=this,r=this.sentencesPerParagraph,a=r.min,i=r.max,s=e||this.generateRandomInteger(a,i);return(0,n.makeArrayOfLength)(s).reduce((function(e,n){return"".concat(t.generateRandomSentence()," ").concat(e)}),"").trim()}},{key:"pluckRandomWord",value:function(){var e=this.words.length-1,t=this.generateRandomInteger(0,e);return this.words[t]}}])&&a(s.prototype,o),l&&a(s,l),Object.defineProperty(s,"prototype",{writable:!1}),e}(),o=s;e.default=o}(generator),function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var t,n=formats,r=lineEndings,a=(t=generator)&&t.__esModule?t:{default:t},i=util;function s(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:{},r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:n.FORMAT_PLAIN,i=arguments.length>2?arguments[2]:void 0;if(s(this,e),this.format=r,this.suffix=i,l(this,"generator",void 0),-1===n.FORMATS.indexOf(r.toLowerCase()))throw new Error("".concat(r," is an invalid format. Please use ").concat(n.FORMATS.join(" or "),"."));this.generator=new a.default(t)}var t,u,c;return t=e,(u=[{key:"getLineEnding",value:function(){return this.suffix?this.suffix:!(0,i.isReactNative)()&&(0,i.isNode)()&&(0,i.isWindows)()?r.LINE_ENDINGS.WIN32:r.LINE_ENDINGS.POSIX}},{key:"formatString",value:function(e){return this.format===n.FORMAT_HTML?"

".concat(e,"

"):e}},{key:"formatStrings",value:function(e){var t=this;return e.map((function(e){return t.formatString(e)}))}},{key:"generateWords",value:function(e){return this.formatString(this.generator.generateRandomWords(e))}},{key:"generateSentences",value:function(e){return this.formatString(this.generator.generateRandomParagraph(e))}},{key:"generateParagraphs",value:function(e){var t=this.generator.generateRandomParagraph.bind(this.generator);return this.formatStrings((0,i.makeArrayOfStrings)(e,t)).join(this.getLineEnding())}}])&&o(t.prototype,u),c&&o(t,c),Object.defineProperty(t,"prototype",{writable:!1}),e}(),c=u;e.default=c}(LoremIpsum),function(e){Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"LoremIpsum",{enumerable:!0,get:function(){return i.default}}),e.loremIpsum=void 0;var t,n=formats,r=units,a=words,i=(t=LoremIpsum)&&t.__esModule?t:{default:t};e.loremIpsum=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.count,s=void 0===t?1:t,o=e.format,l=void 0===o?n.FORMAT_PLAIN:o,u=e.paragraphLowerBound,c=void 0===u?3:u,p=e.paragraphUpperBound,d=void 0===p?7:p,m=e.random,h=e.sentenceLowerBound,f=void 0===h?5:h,y=e.sentenceUpperBound,g=void 0===y?15:y,b=e.units,v=void 0===b?r.UNIT_SENTENCES:b,N=e.words,T=void 0===N?a.WORDS:N,C=e.suffix,A=void 0===C?"":C,V={random:m,sentencesPerParagraph:{max:d,min:c},words:T,wordsPerSentence:{max:g,min:f}},x=new i.default(V,l,A);switch(v){case r.UNIT_PARAGRAPHS:case r.UNIT_PARAGRAPH:return x.generateParagraphs(s);case r.UNIT_SENTENCES:case r.UNIT_SENTENCE:return x.generateSentences(s);case r.UNIT_WORDS:case r.UNIT_WORD:return x.generateWords(s);default:return""}}}(dist);class Lorem extends CompositeComponent{static componentType="lorem";static assignNamesToReplacements=!0;static createsVariants=!0;static stateVariableToEvaluateAfterReplacements="readyToExpandWhenResolved";static createAttributesObject(){let e=super.createAttributesObject();return e.minSentencesPerParagraph={createComponentOfType:"number",createStateVariable:"minSentencesPerParagraph",defaultValue:4,public:!0},e.maxSentencesPerParagraph={createComponentOfType:"number",createStateVariable:"maxSentencesPerParagraph",defaultValue:8,public:!0},e.minWordsPerSentence={createComponentOfType:"number",createStateVariable:"minWordsPerSentence",defaultValue:4,public:!0},e.maxWordsPerSentence={createComponentOfType:"number",createStateVariable:"maxWordsPerSentence",defaultValue:8,public:!0},e.generateWords={createComponentOfType:"number",createStateVariable:"generateWords",defaultValue:null},e.generateSentences={createComponentOfType:"number",createStateVariable:"generateSentences",defaultValue:null},e.generateParagraphs={createComponentOfType:"number",createStateVariable:"generateParagraphs",defaultValue:null},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.readyToExpandWhenResolved={returnDependencies:()=>({minSentencesPerParagraph:{dependencyType:"stateVariable",variableName:"minSentencesPerParagraph"},maxSentencesPerParagraph:{dependencyType:"stateVariable",variableName:"maxSentencesPerParagraph"},minWordsPerSentence:{dependencyType:"stateVariable",variableName:"minWordsPerSentence"},maxWordsPerSentence:{dependencyType:"stateVariable",variableName:"maxWordsPerSentence"},generateWords:{dependencyType:"stateVariable",variableName:"generateWords"},generateSentences:{dependencyType:"stateVariable",variableName:"generateSentences"},generateParagraphs:{dependencyType:"stateVariable",variableName:"generateParagraphs"}}),markStale:()=>({updateReplacements:!0}),definition:()=>({setValue:{readyToExpandWhenResolved:!0}})},e.isVariantComponent={returnDependencies:()=>({}),definition:()=>({setValue:{isVariantComponent:!0}})},e.generatedVariantInfo={returnDependencies:({sharedParameters:e,componentInfoObjects:t})=>({variantSeed:{dependencyType:"value",value:e.variantSeed}}),definition:({dependencyValues:e,componentName:t})=>({setValue:{generatedVariantInfo:{seed:e.variantSeed,meta:{createdBy:t}}}})},e}static async createSerializedReplacements({component:e,componentInfoObjects:t}){const n=new dist.LoremIpsum({sentencesPerParagraph:{max:await e.stateValues.maxSentencesPerParagraph,min:await e.stateValues.minSentencesPerParagraph},wordsPerSentence:{max:await e.stateValues.maxWordsPerSentence,min:await e.stateValues.minWordsPerSentence},random:e.sharedParameters.variantRng});let r=[];if(null!==await e.stateValues.generateParagraphs){let t=await e.stateValues.generateParagraphs;if(Number.isInteger(t)&&t>0){r=n.generateParagraphs(t).split("\n").map((e=>({componentType:"p",children:[e]})))}}else if(null!==await e.stateValues.generateSentences){let t=await e.stateValues.generateSentences;if(Number.isInteger(t)&&t>0){let e=n.generateSentences(t).split(". ");for(let t of e.slice(0,e.length-1))r.push({componentType:"text",children:[t+"."]}),r.push(" ");r.push({componentType:"text",children:[e[e.length-1]]})}}else if(null!==await e.stateValues.generateWords){let t=await e.stateValues.generateWords;if(Number.isInteger(t)&&t>0){let e=n.generateWords(t).split(" ").map((e=>({componentType:"text",children:[e]})));r.push(e[0]);for(let t of e.slice(1))r.push(" "),r.push(t)}}let a=e.attributes.newNamespace?.primitive;return{replacements:processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:r,parentName:e.componentName,parentCreatesNewNamespace:a,componentInfoObjects:t}).serializedComponents}}static async calculateReplacementChanges({component:e,componentInfoObjects:t}){let n=await this.createSerializedReplacements({component:e,componentInfoObjects:t});return[{changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:0,numberReplacementsToReplace:e.replacements.length,serializedReplacements:n.replacements}]}static setUpVariant({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n}){setUpVariantSeedAndRng({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n})}}function returnStandardTriggeringAttributes(e){return{triggerWhen:{createComponentOfType:"boolean",createStateVariable:"triggerWhen",defaultValue:!1,triggerActionOnChange:e},triggerWith:{createTargetComponentNames:!0},triggerWhenObjectsClicked:{createTargetComponentNames:!0},triggerWhenObjectsFocused:{createTargetComponentNames:!0}}}function addStandardTriggeringStateVariableDefinitions(e,t){e.insideTriggerSet={returnDependencies:()=>({parentTriggerSet:{dependencyType:"parentStateVariable",parentComponentType:"triggerSet",variableName:"updateValueAndActionsToTrigger"}}),definition:({dependencyValues:e})=>({setValue:{insideTriggerSet:null!==e.parentTriggerSet}})},e.triggerWith={returnDependencies:()=>({triggerWith:{dependencyType:"attributeTargetComponentNames",attributeName:"triggerWith"},triggerWhenObjectsClicked:{dependencyType:"attributeTargetComponentNames",attributeName:"triggerWhenObjectsClicked"},triggerWhenObjectsFocused:{dependencyType:"attributeTargetComponentNames",attributeName:"triggerWhenObjectsFocused"},triggerWhen:{dependencyType:"attributeComponent",attributeName:"triggerWhen"},insideTriggerSet:{dependencyType:"stateVariable",variableName:"insideTriggerSet"}}),definition({dependencyValues:e}){if(e.triggerWhen||e.insideTriggerSet)return{setValue:{triggerWith:null}};{let t=[];if(null!==e.triggerWith)for(let n of e.triggerWith)t.push({target:n.absoluteName});if(null!==e.triggerWhenObjectsClicked)for(let n of e.triggerWhenObjectsClicked)t.push({target:n.absoluteName,triggeringAction:"click"});if(null!==e.triggerWhenObjectsFocused)for(let n of e.triggerWhenObjectsFocused)t.push({target:n.absoluteName,triggeringAction:"down"});return 0===t.length&&(t=null),{setValue:{triggerWith:t}}}}},e.triggerWithTargetIds={chainActionOnActionOfStateVariableTargets:{triggeredAction:t},returnDependencies:()=>({triggerWith:{dependencyType:"stateVariable",variableName:"triggerWith"}}),definition({dependencyValues:e}){let t=[];if(e.triggerWith)for(let n of e.triggerWith){let e=n.target;n.triggeringAction&&(e+="|"+n.triggeringAction),t.includes(e)||t.push(e)}return{setValue:{triggerWithTargetIds:t}}},markStale:()=>({updateActionChaining:!0})};let n=e.hidden.returnDependencies,r=e.hidden.definition;e.hidden.returnDependencies=function(e){let t=n(e);return t.triggerWhen={dependencyType:"attributeComponent",attributeName:"triggerWhen"},t.triggerWith={dependencyType:"stateVariable",variableName:"triggerWith"},t.insideTriggerSet={dependencyType:"stateVariable",variableName:"insideTriggerSet"},t},e.hidden.definition=function(e){return e.dependencyValues.triggerWhen||e.dependencyValues.triggerWith||e.dependencyValues.insideTriggerSet?{setValue:{hidden:!0}}:r(e)}}class UpdateValue extends InlineComponent{constructor(e){super(e),Object.assign(this.actions,{updateValue:this.updateValue.bind(this),updateValueIfTriggerNewlyTrue:this.updateValueIfTriggerNewlyTrue.bind(this)})}static componentType="updateValue";static acceptTarget=!0;static createAttributesObject(){let e=super.createAttributesObject();e.labelIsName={createComponentOfType:"boolean",createStateVariable:"labelIsName",defaultValue:!1,public:!0},e.type={createPrimitiveOfType:"string",createStateVariable:"type",defaultPrimitiveValue:"math",toLowerCase:!0,validValues:["math","number","boolean","text"]},e.prop={createPrimitiveOfType:"string"},e.newValue={createComponentOfType:"_componentWithSelectableType"},e.componentIndex={createComponentOfType:"integer",createStateVariable:"componentIndex",defaultValue:null,public:!0},e.propIndex={createComponentOfType:"numberList",createStateVariable:"propIndex",defaultValue:null,public:!0};let t=returnStandardTriggeringAttributes("updateValueIfTriggerNewlyTrue");return Object.assign(e,t),e.simplify={createComponentOfType:"text",createStateVariable:"simplify",defaultValue:"none",public:!0,toLowerCase:!0,valueTransformations:{true:"full"},validValues:["none","full","numbers","numberspreserveorder"]},e}static returnChildGroups(){return[{group:"labels",componentTypes:["label"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();addStandardTriggeringStateVariableDefinitions(e,"updateValue");let t=returnLabelStateVariableDefinitions();return Object.assign(e,t),e.target={returnDependencies:()=>({target:{dependencyType:"doenetAttribute",attributeName:"target"}}),definition:({dependencyValues:e})=>({setValue:{target:e.target}})},e.targetComponent={returnDependencies:()=>({targetComponent:{dependencyType:"targetComponent"}}),definition:function({dependencyValues:e}){let t=null;return e.targetComponent&&(t=e.targetComponent),{setValue:{targetComponent:t}}}},e.propName={returnDependencies:()=>({propName:{dependencyType:"attributePrimitive",attributeName:"prop"}}),definition:function({dependencyValues:e}){return{setValue:{propName:e.propName}}}},e.targetIdentities={stateVariablesDeterminingDependencies:["targetComponent","componentIndex"],returnDependencies:function({stateValues:e,componentInfoObjects:t}){let n={};return null!==e.targetComponent&&(t.isCompositeComponent({componentType:e.targetComponent.componentType,includeNonStandard:!1})?n.targets={dependencyType:"replacement",compositeName:e.targetComponent.componentName,recursive:!0,componentIndex:e.componentIndex}:null!==e.componentIndex&&1!==e.componentIndex||(n.targets={dependencyType:"stateVariable",variableName:"targetComponent"})),n},definition({dependencyValues:e}){let t=null;return e.targets&&(t=e.targets,Array.isArray(t)||(t=[t])),{setValue:{targetIdentities:t}}}},e.targets={stateVariablesDeterminingDependencies:["targetIdentities","propName","propIndex"],returnDependencies:function({stateValues:e}){let t={targetIdentities:{dependencyType:"stateVariable",variableName:"targetIdentities"}};if(null!==e.targetIdentities)for(let[n,r]of e.targetIdentities.entries()){let a;if(e.propName){let t=e.propIndex;t&&(t=[...t]),a={dependencyType:"stateVariable",componentName:r.componentName,variableName:e.propName,returnAsComponentObject:!0,variablesOptional:!0,propIndex:t,caseInsensitiveVariableMatch:!0,publicStateVariablesOnly:!0,useMappedVariableNames:!0}}else a={dependencyType:"componentIdentity",componentName:r.componentName};t["target"+n]=a}return t},definition({dependencyValues:e}){let t=null;if(null!==e.targetIdentities){t=[];for(let n in e.targetIdentities)e["target"+n]&&t.push(e["target"+n])}return{setValue:{targets:t}}}},e.newValue={returnDependencies:()=>({newValueAttr:{dependencyType:"attributeComponent",attributeName:"newValue",variableNames:["value"]},type:{dependencyType:"stateVariable",variableName:"type"},simplify:{dependencyType:"stateVariable",variableName:"simplify"}}),definition:function({dependencyValues:e}){if(null===e.newValueAttr)return{setValue:{newValue:null}};let t=e.newValueAttr.stateValues.value;return"math"===e.type&&(t=normalizeMathExpression({value:t,simplify:e.simplify})),{setValue:{newValue:t}}}},e}async updateValue({actionId:e}){let t=await this.stateValues.targets,n=await this.stateValues.newValue;if(null===t||null===n)return;let r=[];for(let e of t){let t="value";e.stateValues&&(t=Object.keys(e.stateValues)[0],void 0===t)?console.warn(`Cannot update prop="${await this.stateValues.propName}" of ${await this.stateValues.target} as could not find prop ${await this.stateValues.propName} on a component of type ${e.componentType}`):r.push({updateType:"updateValue",componentName:e.componentName,stateVariable:t,value:n})}return await this.coreFunctions.performUpdate({updateInstructions:r,actionId:e,event:{verb:"selected",object:{componentName:this.componentName,componentType:this.componentType},result:{response:n,responseText:n.toString()}}}),await this.coreFunctions.triggerChainedActions({componentName:this.componentName})}async updateValueIfTriggerNewlyTrue({stateValues:e,previousValues:t,actionId:n}){if(await e.triggerWhen&&!1===t.triggerWhen&&!await this.stateValues.insideTriggerSet)return await this.updateValue({actionId:n});this.coreFunctions.resolveAction({actionId:n})}}class CallAction extends InlineComponent{constructor(e){super(e),Object.assign(this.actions,{callAction:this.callAction.bind(this),callActionIfTriggerNewlyTrue:this.callActionIfTriggerNewlyTrue.bind(this)})}static componentType="callAction";static acceptTarget=!0;static keepChildrenSerialized({serializedComponent:e,componentInfoObjects:t}){if(void 0===e.children)return[];{let n=[];for(let[r,a]of e.children.entries())t.componentIsSpecifiedType(a,"label")||n.push(r);return n}}static createAttributesObject(){let e=super.createAttributesObject();e.labelIsName={createComponentOfType:"boolean",createStateVariable:"labelIsName",defaultValue:!1,public:!0},e.actionName={createComponentOfType:"text",createStateVariable:"actionName",defaultValue:null,public:!0};let t=returnStandardTriggeringAttributes("callActionIfTriggerNewlyTrue");return Object.assign(e,t),e.numbers={createComponentOfType:"numberList"},e.number={createComponentOfType:"number"},e}static returnChildGroups(){return[{group:"labels",componentTypes:["label"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();addStandardTriggeringStateVariableDefinitions(e,"callAction");let t=returnLabelStateVariableDefinitions();return Object.assign(e,t),e.target={returnDependencies:()=>({target:{dependencyType:"doenetAttribute",attributeName:"target"}}),definition:({dependencyValues:e})=>({setValue:{target:e.target}})},e.targetComponent={returnDependencies:()=>({targetComponent:{dependencyType:"targetComponent"}}),definition:function({dependencyValues:e}){let t=null;return e.targetComponent&&(t=e.targetComponent),{setValue:{targetComponent:t}}}},e.targetName={returnDependencies:()=>({targetComponent:{dependencyType:"stateVariable",variableName:"targetComponent"}}),definition({dependencyValues:e}){let t=null;return e.targetComponent&&(t=e.targetComponent.componentName),{setValue:{targetName:t}}}},e}async callAction({actionId:e}){let t=await this.stateValues.targetName,n=await this.stateValues.actionName;if(null!==t&&null!==n){let r={};this.serializedChildren.length>0&&(r.serializedComponents=deepClone(this.serializedChildren)),this.attributes.number&&(r.number=await this.attributes.number.component.stateValues.value),this.attributes.numbers&&(r.numbers=await this.attributes.numbers.component.stateValues.numbers),e&&(r.actionId=e),await this.coreFunctions.performAction({componentName:t,actionName:n,args:r,event:{verb:"selected",object:{componentName:this.componentName,componentType:this.componentType}},caseInsensitiveMatch:!0}),await this.coreFunctions.triggerChainedActions({componentName:this.componentName})}else this.coreFunctions.resolveAction({actionId:e})}async callActionIfTriggerNewlyTrue({stateValues:e,previousValues:t,actionId:n}){if(e.triggerWhen&&!1===t.triggerWhen&&!await this.stateValues.insideTriggerSet)return await this.callAction({actionId:n});this.coreFunctions.resolveAction({actionId:n})}}class triggerSet extends InlineComponent{constructor(e){super(e),Object.assign(this.actions,{triggerActions:this.triggerActions.bind(this),triggerActionsIfTriggerNewlyTrue:this.triggerActionsIfTriggerNewlyTrue.bind(this)})}static componentType="triggerSet";static createAttributesObject(){let e=super.createAttributesObject();e.labelIsName={createComponentOfType:"boolean",createStateVariable:"labelIsName",defaultValue:!1,public:!0};let t=returnStandardTriggeringAttributes("triggerActionsIfTriggerNewlyTrue");return Object.assign(e,t),e}static returnChildGroups(){return[{group:"updateValuesCallActions",componentTypes:["updateValue","callAction"]},{group:"labels",componentTypes:["label"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();addStandardTriggeringStateVariableDefinitions(e,"triggerActions");let t=returnLabelStateVariableDefinitions();return Object.assign(e,t),e.updateValueAndActionsToTrigger={returnDependencies:()=>({updateValueAndCallActionChildren:{dependencyType:"child",childGroups:["updateValuesCallActions"]}}),definition:({dependencyValues:e})=>({setValue:{updateValueAndActionsToTrigger:e.updateValueAndCallActionChildren}})},e}async triggerActions({actionId:e}){for(let e of await this.stateValues.updateValueAndActionsToTrigger)this.componentInfoObjects.isInheritedComponentType({inheritedComponentType:e.componentType,baseComponentType:"updateValue"})?await this.coreFunctions.performAction({componentName:e.componentName,actionName:"updateValue"}):this.componentInfoObjects.isInheritedComponentType({inheritedComponentType:e.componentType,baseComponentType:"callAction"})&&await this.coreFunctions.performAction({componentName:e.componentName,actionName:"callAction"});return this.coreFunctions.resolveAction({actionId:e}),await this.coreFunctions.triggerChainedActions({componentName:this.componentName})}async triggerActionsIfTriggerNewlyTrue({stateValues:e,previousValues:t,actionId:n}){if(e.triggerWhen&&!1===t.triggerWhen)return await this.triggerActions({actionId:n});this.coreFunctions.resolveAction({actionId:n})}}class FunctionIterates extends InlineComponent{static componentType="functionIterates";static rendererType=void 0;static createAttributesObject(){let e=super.createAttributesObject();return e.nIterates={createComponentOfType:"integer",createStateVariable:"nIterates",defaultValue:0,public:!0},e.forceSymbolic={createComponentOfType:"boolean",createStateVariable:"forceSymbolic",defaultValue:!1,public:!0},e.forceNumeric={createComponentOfType:"boolean",createStateVariable:"forceNumeric",defaultValue:!1,public:!0},e.initialValue={createComponentOfType:"math",createStateVariable:"initialValue",defaultValue:me$3.fromAst("_")},e.function={createComponentOfType:"function"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nDimensions={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({functionAttr:{dependencyType:"attributeComponent",attributeName:"function",variableNames:["nInputs","nOutputs"]}}),definition:({dependencyValues:e})=>e.functionAttr?e.functionAttr.stateValues.nInputs!==e.functionAttr.stateValues.nOutputs?(console.warn("Function iterates are possible only if the number of inputs is equal to the number of outputs"),{setValue:{nDimensions:0}}):{setValue:{nDimensions:e.functionAttr.stateValues.nInputs}}:{setValue:{nDimensions:0}}},e.allIterates={public:!0,shadowingInstructions:{createComponentOfType:"mathList"},returnDependencies:()=>({functionAttr:{dependencyType:"attributeComponent",attributeName:"function",variableNames:["symbolicfs","numericalfs","symbolic"]},forceSymbolic:{dependencyType:"stateVariable",variableName:"forceSymbolic"},forceNumeric:{dependencyType:"stateVariable",variableName:"forceNumeric"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},initialValue:{dependencyType:"stateVariable",variableName:"initialValue"},nIterates:{dependencyType:"stateVariable",variableName:"nIterates"}}),definition({dependencyValues:e}){let t=[],n=e.functionAttr,r=e.initialValue,a=!e.forceNumeric&&(n.stateValues.symbolic||e.forceSymbolic),i=e.nIterates;if(!n||0===e.nDimensions||!(1===e.nDimensions||Array.isArray(r.tree)&&vectorOperators.includes(r.tree[0])&&r.tree.length===e.nDimensions+1))return t=Array(i).fill(me$3.fromAst("_")),{setValue:{allIterates:t}};if(a)if(1===e.nDimensions){let e=n.stateValues.symbolicfs[0],a=r;for(let n=0;nme$3.fromAst(e).evaluate_to_constant())).map((e=>null==e?NaN:e));for(let n=0;n({initialValue:{dependencyType:"stateVariable",variableName:"initialValue"},allIterates:{dependencyType:"stateVariable",variableName:"allIterates"}}),definition:({dependencyValues:e})=>({setValue:{allIteratesWithInitial:[e.initialValue,...e.allIterates]}})},e.iterates={isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"math"},entryPrefixes:["iterate"],returnArraySizeDependencies:()=>({nIterates:{dependencyType:"stateVariable",variableName:"nIterates"}}),returnArraySize:({dependencyValues:e})=>[e.nIterates],returnArrayDependenciesByKey:()=>({globalDependencies:{allIterates:{dependencyType:"stateVariable",variableName:"allIterates"}}}),arrayDefinitionByKey({globalDependencyValues:e,arraySize:t}){let n={};for(let r=0;r!Number.isFinite(e.nIterates)||e.nIterates<0?{}:e.nIterates>0?{finalIterate:{dependencyType:"stateVariable",variableName:`iterate${e.nIterates}`}}:{finalIterate:{dependencyType:"stateVariable",variableName:"initialValue"}},definition:({dependencyValues:e})=>({setValue:{finalIterate:e.finalIterate}})},e}}class Module extends Template{static componentType="module";static renderedDefault=!0;static acceptAnyAttribute=!0;static createAttributesObject(){let e=super.createAttributesObject();return delete e.styleNumber,e}}class CustomAttribute extends CompositeComponent{static componentType="customAttribute";static assignNamesToReplacements=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.componentType={createPrimitiveOfType:"string"},e.attribute={createPrimitiveOfType:"string"},e.defaultValue={leaveRaw:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.componentNameForAttributes={returnDependencies:()=>({parentVariableContainingName:{dependencyType:"parentStateVariable",variableName:"componentNameForAttributes"}}),definition:({dependencyValues:e})=>({setValue:{componentNameForAttributes:e.parentVariableContainingName}})},e.attributeName={returnDependencies:()=>({attribute:{dependencyType:"attributePrimitive",attributeName:"attribute"}}),definition:({dependencyValues:e})=>({setValue:{attributeName:e.attribute}})},e.readyToExpandWhenResolved={stateVariablesDeterminingDependencies:["componentNameForAttributes"],returnDependencies:({stateValues:e})=>({componentIdentity:{dependencyType:"componentIdentity",componentName:e.componentNameForAttributes}}),definition:()=>({setValue:{readyToExpandWhenResolved:!0}})},e}static async createSerializedReplacements({component:e,components:t,workspace:n,componentInfoObjects:r,flags:a}){let i=e.attributes.newNamespace?.primitive,s=r.componentTypeLowerCaseMapping[e.attributes.componentType.primitive.toLowerCase()];if(!r.allComponentClasses[s])return console.warn(`Could not find component type ${s}`),{replacements:[]};let o=t[await e.stateValues.componentNameForAttributes],l={};for(let e in o.attributes)l[e.toLowerCase()]=e;let u=await e.stateValues.attributeName,c=l[u.toLowerCase()],p=o.attributes[c];if(void 0===p){if(void 0===e.attributes.defaultValue)return console.warn("Cannot create component from attribute if neither attribute nor default value specified"),{replacements:[]};p=e.attributes.defaultValue}let d=o.constructor,m=Object.keys(d.createAttributesObject()).map((e=>e.toLowerCase()));if(m.push("name","target","assignnames"),m.includes(u.toLowerCase()))return console.warn(`Cannot add attribute ${u} of a ${d.componentType} as it already exists in ${d.componentType} class`),{replacements:[]};let h=componentFromAttribute({attrObj:{createComponentOfType:s},value:p,componentInfoObjects:r}).component;if(h.children&&(applyMacros(h.children,r),i))for(let e of h.children)if("copy"===e.componentType){let t=e.doenetAttributes.target;/[a-zA-Z_]/.test(t[0])&&(e.doenetAttributes.target="../"+t)}return applySugar({serializedComponents:[h],isAttributeComponent:!0,componentInfoObjects:r}),setTNamesToAbsolute([h]),{replacements:processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:[h],parentName:e.componentName,parentCreatesNewNamespace:i,componentInfoObjects:r}).serializedComponents}}}class Setup extends CompositeComponent{static componentType="setup";static returnChildGroups(){return[{group:"styleDefinitions",componentTypes:["styleDefinitions"]},{group:"feedbackDefinitions",componentTypes:["feedbackDefinitions"]},{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.componentNameForAttributes={returnDependencies:()=>({sourceCompositeIdentity:{dependencyType:"sourceCompositeIdentity"}}),definition({dependencyValues:e}){let t=null;return e.sourceCompositeIdentity&&(t=e.sourceCompositeIdentity.componentName),{setValue:{componentNameForAttributes:t}}}},e.readyToExpandWhenResolved={returnDependencies:()=>({}),definition:()=>({setValue:{readyToExpandWhenResolved:!0}})},e}}class Footnote extends InlineComponent{static componentType="footnote";static renderChildren=!0;static includeBlankStringChildren=!0;static returnChildGroups(){return[{group:"inlines",componentTypes:["_inline"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["inlines"],variableNames:["text"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let t="";for(let n of e.inlineChildren)"object"!=typeof n?t+=n.toString():"string"==typeof n.stateValues.text?t+=n.stateValues.text:t+=" ";return{setValue:{text:t}}}},e.footnoteTag={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({footnoteCounter:{dependencyType:"counter",counterName:"footnote"}}),definition:({dependencyValues:e})=>({setValue:{footnoteTag:String(e.footnoteCounter)}})},e}}class Caption extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="caption";static rendererType="containerInline";static renderChildren=!0;static includeBlankStringChildren=!0;static returnChildGroups(){return[{group:"inlinesBlocks",componentTypes:["_inline","_block"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["inlinesBlocks"],variableNames:["text"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let t="";for(let n of e.inlineChildren)"object"!=typeof n?t+=n.toString():"string"==typeof n.stateValues.text?t+=n.stateValues.text:t+=" ";return{setValue:{text:t}}}},e}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class Endpoint extends Point{static componentType="endpoint";static rendererType="point";static createAttributesObject(){let e=super.createAttributesObject();return e.open={createComponentOfType:"boolean",createStateVariable:"open",defaultValue:!1,public:!0,forRenderer:!0},e.switchable={createComponentOfType:"boolean",createStateVariable:"switchable",defaultValue:!1,public:!0,forRenderer:!0},e}async switchPoint({actionId:e}){if(await this.stateValues.switchable)return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"open",value:!await this.stateValues.open}],actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{open:!await this.stateValues.open}}});this.coreFunctions.resolveAction({actionId:e})}}class Sort extends CompositeComponent{static componentType="sort";static stateVariableToEvaluateAfterReplacements="readyToExpandWhenResolved";static assignNamesToReplacements=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.assignNamesSkip={createPrimitiveOfType:"number"},e.sortVectorsBy={createComponentOfType:"text",createStateVariable:"sortVectorsBy",defaultValue:"displacement",public:!0,toLowerCase:!0,validValues:["displacement","tail"]},e.sortByComponent={createComponentOfType:"integer",createStateVariable:"sortByComponent",defaultValue:"1",public:!0},e.sortByProp={createPrimitiveOfType:"string"},e}static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.propName={returnDependencies:()=>({propName:{dependencyType:"attributePrimitive",attributeName:"sortByProp"}}),definition:function({dependencyValues:e}){return{setValue:{propName:e.propName}}}},e.componentNamesForValues={returnDependencies:()=>({children:{dependencyType:"child",childGroups:["anything"],variableNames:["componentNamesInList"],variablesOptional:!0}}),definition({dependencyValues:e}){let t=[];for(let n of e.children)n.stateValues.componentNamesInList?t.push(...n.stateValues.componentNamesInList):t.push(n.componentName);return{setValue:{componentNamesForValues:t}}}},e.sortedValues={stateVariablesDeterminingDependencies:["componentNamesForValues","sortByComponent","propName"],returnDependencies({stateValues:e}){let t={sortVectorsBy:{dependencyType:"stateVariable",variableName:"sortVectorsBy"},sortByComponent:{dependencyType:"stateVariable",variableName:"sortByComponent"},propName:{dependencyType:"stateVariable",variableName:"propName"}};if(e.propName)for(let[n,r]of e.componentNamesForValues.entries())t[`component${n}`]={dependencyType:"stateVariable",componentName:r,variableName:e.propName,variablesOptional:!0,caseInsensitiveVariableMatch:!0,publicStateVariablesOnly:!0,returnAsComponentObject:!0};else for(let[n,r]of e.componentNamesForValues.entries())t[`component${n}`]={dependencyType:"multipleStateVariables",componentName:r,variableNames:["value",`x${e.sortByComponent}`,`tailX${e.sortByComponent}`],variablesOptional:!0};return t},definition({dependencyValues:e,componentInfoObjects:t}){let n=[],r=!0;for(let a in e){if("component"!==a.substring(0,9))continue;let i=e[a];if(e.propName){let e=Object.values(i.stateValues)[0];n.push({componentName:i.componentName,numericalValue:Number(e),textValue:String(e)}),Number.isFinite(e)||(r=!1)}else if(t.isInheritedComponentType({inheritedComponentType:i.componentType,baseComponentType:"number"}))n.push({componentName:i.componentName,numericalValue:i.stateValues.value,textValue:String(i.stateValues.value)});else if(t.isInheritedComponentType({inheritedComponentType:i.componentType,baseComponentType:"text"})){let e=NaN,t=i.stateValues.value;n.push({componentName:i.componentName,numericalValue:e,textValue:t}),r=!1}else if(t.isInheritedComponentType({inheritedComponentType:i.componentType,baseComponentType:"math"})){let e=i.stateValues.value.evaluate_to_constant();null===e&&(e=NaN,r=!1),n.push({componentName:i.componentName,numericalValue:e,textValue:i.stateValues.value.toString()})}else if(t.isInheritedComponentType({inheritedComponentType:i.componentType,baseComponentType:"point"})){let t=i.stateValues[`x${e.sortByComponent}`],a=NaN,s="";t&&(a=t.evaluate_to_constant(),null===a&&(a=NaN,r=!1),s=t.toString()),n.push({componentName:i.componentName,numericalValue:a,textValue:s})}else if(t.isInheritedComponentType({inheritedComponentType:i.componentType,baseComponentType:"vector"})){let t=NaN,a="",s=i.stateValues[`x${e.sortByComponent}`];s="displacement"===e.sortVectorsBy?i.stateValues[`x${e.sortByComponent}`]:i.stateValues[`tailX${e.sortByComponent}`],s&&(t=s.evaluate_to_constant(),null===t&&(t=NaN,r=!1),a=s.toString()),n.push({componentName:i.componentName,numericalValue:t,textValue:a})}}return r?n.sort(((e,t)=>e.numericalValue-t.numericalValue)):n.sort(((e,t)=>e.textValue>t.textValue?1:e.textValue({sortedValues:{dependencyType:"stateVariable",variableName:"sortedValues"}}),markStale:()=>({updateReplacements:!0}),definition:function(){return{setValue:{readyToExpandWhenResolved:!0}}}},e}static async createSerializedReplacements({component:e,components:t,componentInfoObjects:n,workspace:r}){let a=[],i=[];for(let n of await e.stateValues.sortedValues){let e;if(void 0===n.listInd)e=t[n.componentName];else{e=t[n.componentName].activeChildren[n.listInd]}e&&(i.push(e.componentName),a.push(await e.serialize({sourceAttributesToIgnoreRecursively:["isResponse"]})))}r.uniqueIdentifiersUsed=[],a=postProcessCopy({serializedComponents:a,componentName:e.componentName,uniqueIdentifiersUsed:r.uniqueIdentifiersUsed,addShadowDependencies:!0,markAsPrimaryShadow:!0});let s=processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:a,parentName:e.componentName,parentCreatesNewNamespace:await e.stateValues.newNamespace,componentInfoObjects:n});return r.componentsCopied=i,{replacements:s.serializedComponents}}static async calculateReplacementChanges({component:e,components:t,componentInfoObjects:n,workspace:r}){let a=[];for(let n of await e.stateValues.sortedValues){let e;if(void 0===n.listInd)e=t[n.componentName];else{e=t[n.componentName].activeChildren[n.listInd]}e&&a.push(e.componentName)}if(a.length==r.componentsCopied.length&&r.componentsCopied.every(((e,t)=>e===a[t])))return[];let i=(await this.createSerializedReplacements({component:e,components:t,componentInfoObjects:n,workspace:r})).replacements;return[{changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:0,numberReplacementsToReplace:e.replacements.length,serializedReplacements:i}]}}class Shuffle extends CompositeComponent{static componentType="shuffle";static createsVariants=!0;static stateVariableToEvaluateAfterReplacements="readyToExpandWhenResolved";static assignNamesToReplacements=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.assignNamesSkip={createPrimitiveOfType:"number"},e}static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.originalComponentNames={additionalStateVariablesDefined:["nComponents"],returnDependencies:()=>({children:{dependencyType:"child",childGroups:["anything"],variableNames:["componentNamesInList"],variablesOptional:!0}}),definition({dependencyValues:e}){let t=[];for(let n of e.children)n.stateValues.componentNamesInList?t.push(...n.stateValues.componentNamesInList):t.push(n.componentName);return{setValue:{originalComponentNames:t,nComponents:t.length}}}},e.componentOrder={returnDependencies:({sharedParameters:e})=>({variantSeed:{dependencyType:"value",value:e.variantSeed},rngClass:{dependencyType:"value",value:e.rngClass,doNotProxy:!0},nComponents:{dependencyType:"stateVariable",variableName:"nComponents"},variants:{dependencyType:"variants"}}),definition({dependencyValues:e}){let t=e.nComponents,n=e.variants?.desiredVariant?.indices;if(void 0!==n)if(n.length!==t)console.warn("Ignoring indices specified for shuffle as number of indices doesn't match number of components.");else{if(n=n.map(Number),!n.every(Number.isInteger))throw Error("All indices specified for shuffle must be integers");if(n.every((e=>e>=1&&e<=t)))return{setValue:{componentOrder:n}};console.warn("Ignoring indices specified for shuffle as some indices out of range.")}let r=e.rngClass(e.variantSeed+"co"),a=[...Array(t).keys()].map((e=>e+1));for(let e=t-1;e>0;e--){const t=r(),n=Math.floor(t*(e+1));[a[e],a[n]]=[a[n],a[e]]}return{setValue:{componentOrder:a}}}},e.readyToExpandWhenResolved={returnDependencies:()=>({sortedValues:{dependencyType:"stateVariable",variableName:"componentOrder"}}),markStale:()=>({updateReplacements:!0}),definition:function(){return{setValue:{readyToExpandWhenResolved:!0}}}},e.generatedVariantInfo={additionalStateVariablesDefined:["isVariantComponent"],returnDependencies:({componentInfoObjects:e,sharedParameters:t})=>({variantSeed:{dependencyType:"value",value:t.variantSeed},componentOrder:{dependencyType:"stateVariable",variableName:"componentOrder"},variantDescendants:{dependencyType:"descendant",componentTypes:Object.keys(e.componentTypesCreatingVariants),variableNames:["isVariantComponent","generatedVariantInfo"],useReplacementsForComposites:!0,recurseToMatchedChildren:!1,variablesOptional:!0,includeNonActiveChildren:!0,ignoreReplacementsOfEncounteredComposites:!0}}),definition({dependencyValues:e,componentName:t}){let n={seed:e.variantSeed,meta:{createdBy:t},indices:e.componentOrder},r=n.subvariants=[];for(let t of e.variantDescendants)t.stateValues.isVariantComponent?r.push(t.stateValues.generatedVariantInfo):t.stateValues.generatedVariantInfo&&r.push(...t.stateValues.generatedVariantInfo.subvariants);return{setValue:{generatedVariantInfo:n,isVariantComponent:!0}}}},e}static setUpVariant({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n}){setUpVariantSeedAndRng({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n})}static async createSerializedReplacements({component:e,components:t,componentInfoObjects:n,workspace:r}){let a=[],i=[],s=await e.stateValues.originalComponentNames;for(let n of await e.stateValues.componentOrder){let e=t[s[n-1]];e&&(i.push(e.componentName),a.push(await e.serialize({sourceAttributesToIgnoreRecursively:["isResponse"]})))}r.uniqueIdentifiersUsed=[],a=postProcessCopy({serializedComponents:a,componentName:e.componentName,uniqueIdentifiersUsed:r.uniqueIdentifiersUsed,addShadowDependencies:!0,markAsPrimaryShadow:!0});let o=processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:a,parentName:e.componentName,parentCreatesNewNamespace:await e.stateValues.newNamespace,componentInfoObjects:n});return r.componentsCopied=i,{replacements:o.serializedComponents}}static async calculateReplacementChanges({component:e,components:t,componentInfoObjects:n,workspace:r}){let a=[],i=await e.stateValues.originalComponentNames;for(let n of await e.stateValues.componentOrder){let e=t[i[n-1]];e&&a.push(e.componentName)}if(a.length==r.componentsCopied.length&&r.componentsCopied.every(((e,t)=>e===a[t])))return[];let s=(await this.createSerializedReplacements({component:e,components:t,componentInfoObjects:n,workspace:r})).replacements;return[{changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:0,numberReplacementsToReplace:e.replacements.length,serializedReplacements:s}]}static determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t}){let n=0;for(let r of e.children)if(t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"_composite"})){if(!r.attributes.createComponentOfType?.primitive)return{success:!1};if(void 0!==r.attributes.nComponents?.primitive){let e=Number(r.attributes.nComponents?.primitive);if(!(Number.isInteger(e)&&e>=0))return{success:!1};n+=e}else n++}else n++;let r=1;for(let e=2;e<=n;e++)r*=e;let a=super.determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t});if(!a.success)return{success:!1};let i=a.numberOfVariants*r;return e.variants.numberOfVariants=i,e.variants.uniqueVariantData={numberOfVariantsByDescendant:e.variants.uniqueVariantData.numberOfVariantsByDescendant,numberOfPermutations:r,nComponents:n},{success:!0,numberOfVariants:i}}static getUniqueVariant({serializedComponent:e,variantIndex:t,componentInfoObjects:n}){let r=e.variants?.numberOfVariants;if(void 0===r)return{success:!1};if(!Number.isInteger(t)||t<1||t>r)return{success:!1};let a=e.variants.uniqueVariantData.numberOfVariantsByDescendant,i=e.variants.descendantVariantComponents,s=e.variants.uniqueVariantData.numberOfPermutations,o=e.variants.uniqueVariantData.nComponents,l=[...a];l.push(s);let u=enumerateCombinations({numberOfOptionsByIndex:l,maxNumber:t})[t-1].map((e=>e+1)),c=u.pop(),p=u,d=[...Array(o).keys()].map((e=>e+1)),m=enumeratePermutations({values:d,maxNumber:c})[c-1],h=!1,f=[];for(let e=0;e1){let t=i[e],r=n.allComponentClasses[t.componentType].getUniqueVariant({serializedComponent:t,variantIndex:p[e],componentInfoObjects:n});if(!r.success)return{success:!1};f.push(r.desiredVariant),h=!0}else f.push({});let y={indices:m};return h&&(y.subvariants=f),{success:!0,desiredVariant:y}}}class SolveEquations extends InlineComponent{static componentType="solveEquations";static rendererType=void 0;static createAttributesObject(){let e=super.createAttributesObject();return e.variables={createComponentOfType:"variables"},e.nDiscretizationPoints={createComponentOfType:"number",createStateVariable:"nDiscretizationPoints",defaultValue:100,public:!0},e.minVar={createComponentOfType:"number",createStateVariable:"minVar",defaultValue:null},e.maxVar={createComponentOfType:"number",createStateVariable:"maxVar",defaultValue:null},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e}){return e.every((e=>"string"==typeof e||e.doenetAttributes&&e.doenetAttributes.createdFromMacro))?1===e.length&&"string"!=typeof e[0]?{success:!1}:{success:!0,newChildren:[{componentType:"math",children:e}]}:{success:!1}}}),e}static returnChildGroups(){return[{group:"maths",componentTypes:["math"]},{group:"strings",componentTypes:["string"]}]}static returnStateVariableDefinitions({numerics:e}){let t=super.returnStateVariableDefinitions({numerics:e});return t.variables={isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"variable"},entryPrefixes:["variable"],returnArraySizeDependencies:()=>({}),returnArraySize:({dependencyValues:e})=>[1],returnArrayDependenciesByKey:({arrayKeys:e})=>({globalDependencies:{variablesAttr:{dependencyType:"attributeComponent",attributeName:"variables",variableNames:["variables"]}}}),arrayDefinitionByKey({globalDependencyValues:e,arraySize:t,arrayKeys:n,usedDefault:r}){let a=[];return null!==e.variablesAttr&&(a=e.variablesAttr.stateValues.variables),{setValue:{variables:returnNVariables(t[0],a)}}}},t.variable={isAlias:!0,targetVariableName:"variable1"},t.allSolutions={returnDependencies:()=>({mathChild:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]},variables:{dependencyType:"stateVariable",variableName:"variables"},minVar:{dependencyType:"stateVariable",variableName:"minVar"},maxVar:{dependencyType:"stateVariable",variableName:"maxVar"},nDiscretizationPoints:{dependencyType:"stateVariable",variableName:"nDiscretizationPoints"}}),definition({dependencyValues:t}){if(0===t.mathChild.length)return{setValue:{allSolutions:[]}};let n=t.mathChild[0].stateValues.value;if(!Array.isArray(n.tree)||3!==n.tree.length||"="!==n.tree[0])return{setValue:{allSolutions:[]}};let r=t.minVar,a=t.maxVar,i=[],s=t.variables[0].subscripts_to_strings().tree,o=me$3.fromAst(["+",n.tree[1],["-",n.tree[2]]]).subscripts_to_strings(),l=o.f(),u=e=>l({[s]:e}),c=function(e){try{return u(e)}catch(e){return NaN}};if(Number.isFinite(r)||(r=-10),Number.isFinite(a)||(a=10),r>a)return{setValue:{allSolutions:[]}};let p=[r,a],d=[r];for(let e=0;enormalizeMathExpression({value:o.substitute({[s]:e}).strings_to_subscripts(),simplify:!0,expand:!0}).evaluate_to_constant())(e);return null!==n?n:NaN}})),y=d[0],g=f[0];for(let e=0;e0)for(let t=0;t<10;t++)if(y=.1*y+.9*n,s=.1*s+.9*n,g=c(y),o=c(s),g*o<0){g*u<0?(i.push(e.fzero(c,[l,y])),i.push(n)):(i.includes(n)||i.push(n),n=s,r=o),a=!0;break}}a||i.includes(n)||i.push(n)}else if(r*g<0)i.push(e.fzero(c,[y,n]));else if(0!==g&&t0&&(r>0&&g>r||r<0&&gr?c:e=>-c(e);let s=e.fminbr(t,[y,a],void 0,1e-10);if(s.success){let t=s.x,a=c(t);a*g<0?(i.push(e.fzero(c,[y,t])),n=t,r=a):0===a&&i.push(t)}}}y=n,g=r}i=i.filter((e=>e>=r&&e<=a));let b=i.map((e=>me$3.fromAst(e)));return{setValue:{allSolutions:b}}}},t.numberSolutions={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({allSolutions:{dependencyType:"stateVariable",variableName:"allSolutions"}}),definition:({dependencyValues:e})=>({setValue:{numberSolutions:e.allSolutions.length}})},t.solutions={public:!0,shadowingInstructions:{createComponentOfType:"math"},isArray:!0,entryPrefixes:["solution"],returnArraySizeDependencies:()=>({numberSolutions:{dependencyType:"stateVariable",variableName:"numberSolutions"}}),returnArraySize:({dependencyValues:e})=>[e.numberSolutions],returnArrayDependenciesByKey:()=>({globalDependencies:{allSolutions:{dependencyType:"stateVariable",variableName:"allSolutions"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n=0;n({parentOpen:{dependencyType:"parentStateVariable",variableName:"open"}}),markStale:()=>({updateReplacements:!0}),definition:({dependencyValues:e})=>({setValue:{rendered:Boolean(e.parentOpen)}})},e}static async calculateReplacementChanges({component:e,componentInfoObjects:t}){if(await e.stateValues.rendered&&0===e.replacements.length){let n=(await this.createSerializedReplacements({component:e,componentInfoObjects:t})).replacements;if(n.length>0){return[{changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:0,numberReplacementsToReplace:0,serializedReplacements:n}]}return[]}return[]}}class SubsetOfRealsInput extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{addPoint:this.addPoint.bind(this),deletePoint:this.deletePoint.bind(this),movePoint:this.movePoint.bind(this),togglePoint:this.togglePoint.bind(this),toggleInterval:this.toggleInterval.bind(this),clear:this.clear.bind(this),setToR:this.setToR.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="subsetOfRealsInput";static variableForPlainMacro="subsetValue";static variableForPlainCopy="subsetValue";static createAttributesObject(){let e=super.createAttributesObject();return e.xmin={createComponentOfType:"number",createStateVariable:"xmin",defaultValue:-10,public:!0,forRenderer:!0},e.xmax={createComponentOfType:"number",createStateVariable:"xmax",defaultValue:10,public:!0,forRenderer:!0},e.width={createComponentOfType:"_componentSize",createStateVariable:"width",defaultValue:800,public:!0,forRenderer:!0},e.height={createComponentOfType:"_componentSize",createStateVariable:"height",defaultValue:300,public:!0,forRenderer:!0},e.xlabel={createComponentOfType:"text",createStateVariable:"xlabel",defaultValue:"",public:!0,forRenderer:!0},e.dx={createComponentOfType:"number",createStateVariable:"dx",defaultValue:.5,public:!0},e.variable={createComponentOfType:"variable",createStateVariable:"variable",defaultValue:me$3.fromAst("x"),public:!0},e.format={createComponentOfType:"text",createStateVariable:"format",defaultValue:"text",public:!0},e.prefill={createComponentOfType:"text",createStateVariable:"prefill",defaultValue:"",public:!0},e.bindValueTo={createComponentOfType:"subsetOfReals"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.subsetValue={public:!0,shadowingInstructions:{createComponentOfType:"subsetOfReals"},hasEssential:!0,returnDependencies:()=>({bindValueTo:{dependencyType:"attributeComponent",attributeName:"bindValueTo",variableNames:["subsetValue"]},prefill:{dependencyType:"stateVariable",variableName:"prefill"},variable:{dependencyType:"stateVariable",variableName:"variable"},format:{dependencyType:"stateVariable",variableName:"format"}}),definition:function({dependencyValues:e}){return e.bindValueTo?{setValue:{subsetValue:e.bindValueTo.stateValues.subsetValue}}:{useEssentialOrDefaultValue:{subsetValue:{get defaultValue(){return parseValueIntoSubset({inputString:e.prefill,format:e.format,variable:e.variable})}}}}},inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t})=>t.bindValueTo?{success:!0,instructions:[{setDependency:"bindValueTo",desiredValue:e.subsetValue,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"subsetValue",value:e.subsetValue}]}},e.pointsFromSubset={additionalStateVariablesDefined:["intervalsFromSubset"],returnDependencies:()=>({subsetValue:{dependencyType:"stateVariable",variableName:"subsetValue"}}),definition({dependencyValues:e}){function t(e,t){let n=[],r=[];if(e.points&&(n=e.points),e.intervals&&(r=e.intervals),t.points){let e=n.map((e=>e.value));for(let r of t.points){let t=e.indexOf(r.value);-1===t?n.push(r):n[t].inSubset||=r.inSubset}}return t.intervals&&r.push(...t.intervals),{points:n,intervals:r}}let{points:n,intervals:r}=function e(n){if(null===n||n.isEmpty())return{};if(n instanceof theModule.Union){let r=[],a=[];for(let i of n.subsets){let n=e(i);({points:r,intervals:a}=t({points:r,intervals:a},n))}return{points:r,intervals:a}}if(n instanceof theModule.RealLine)return{intervals:[[-1/0,1/0]]};if(n instanceof theModule.Singleton)return{points:[{value:n.element,inSubset:!0}]};if(n instanceof theModule.OpenInterval){let e=[[n.left,n.right]],t=[];return Number.isFinite(n.left)&&t.push({value:n.left,inSubset:!1}),Number.isFinite(n.right)&&t.push({value:n.right,inSubset:!1}),{intervals:e,points:t}}return{}}(e.subsetValue),a=n||[],i=r||[];return a.sort(((e,t)=>e.value-t.value)),i.sort(((e,t)=>e[0]-t[0])),{setValue:{pointsFromSubset:a,intervalsFromSubset:i}}}},e.additionalPoints={defaultValue:[],hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{additionalPoints:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>e.additionalPoints.every(Number.isFinite)?{success:!0,instructions:[{setEssentialValue:"additionalPoints",value:[...e.additionalPoints].sort(((e,t)=>e-t))}]}:{success:!1}},e.points={additionalStateVariablesDefined:[{variableName:"intervals",forRenderer:!0}],forRenderer:!0,returnDependencies:()=>({pointsFromSubset:{dependencyType:"stateVariable",variableName:"pointsFromSubset"},intervalsFromSubset:{dependencyType:"stateVariable",variableName:"intervalsFromSubset"},additionalPoints:{dependencyType:"stateVariable",variableName:"additionalPoints"}}),definition({dependencyValues:e}){let t=[...e.pointsFromSubset],n=[...e.intervalsFromSubset],r=[...e.additionalPoints].sort(((e,t)=>e-t)),a=[],i=[],s=0,o=1/0,l=0;r.length>0&&(o=r[0]);let u=n[0],c=-1/0;t.push({value:1/0,inSubset:!1});for(let e of t){let t=!1;for(u&&u[0]e.value));if(!e.includes(r)){let e=!1;for(let t of i)if(t[0]r){e=!0;break}if(e)return s.push(r),await this.coreFunctions.performUpdate({updateInstructions:[{componentName:this.componentName,updateType:"updateValue",stateVariable:"additionalPoints",value:s}],actionId:t,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{addedPoint:r,intervalsFromSubset:i,pointsFromSubset:a,additionalPoints:s}}});{a.push({value:r,inSubset:!0});let e=await this.createUpdateInstructions({intervalsFromSubset:i,pointsFromSubset:a,modifiedAdditionalPoints:!1,additionalPoints:s});return await this.coreFunctions.performUpdate({updateInstructions:e,actionId:t,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{addedPoint:r,intervalsFromSubset:i,pointsFromSubset:a,additionalPoints:s}}})}}}this.coreFunctions.resolveAction({actionId:t})}async deletePoint({pointInd:e,actionId:t}){let n=await this.stateValues.points[e],r=[...await this.stateValues.additionalPoints],a=[...await this.stateValues.pointsFromSubset],i=[...await this.stateValues.intervalsFromSubset];if(n.isAdditional)return r.splice(n.additionalPointInd,1),await this.coreFunctions.performUpdate({updateInstructions:[{componentName:this.componentName,updateType:"updateValue",stateVariable:"additionalPoints",value:r}],actionId:t,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{deletedPoint:n.value,intervalsFromSubset:i,pointsFromSubset:a,additionalPoints:r}}});{let s=!1,o=a.map((e=>e.value)).indexOf(n.value),l=i.map((e=>e[1])).indexOf(n.value),u=i.map((e=>e[0])).indexOf(n.value);if(-1!==l)if(-1!==u)i[l]=[i[l][0],i[u][1]],i.splice(u,1),a.splice(o,1);else{let t=(await this.stateValues.points)[e-1];if(t&&t.isAdditional)i[l]=[i[l][0],t.value],r.splice(n.additionalPointInd,1),s=!0,a.splice(o,1,t);else if(i.splice(l,1),a.splice(o,1),t&&!t.inSubset){let e=i.map((e=>e[1])).indexOf(t.value);-1===e&&(r.push(t.value),s=!0)}}else if(-1!==u){let t=(await this.stateValues.points)[e+1];if(t&&t.isAdditional)i[u]=[t.value,i[u][1]],r.splice(n.additionalPointInd,1),s=!0,a.splice(o,1,t);else if(i.splice(u,1),a.splice(o,1),t&&!t.inSubset){let e=i.map((e=>e[0])).indexOf(t.value);-1===e&&(r.push(t.value),s=!0)}}else a.splice(o,1);let c=await this.createUpdateInstructions({intervalsFromSubset:i,pointsFromSubset:a,modifiedAdditionalPoints:s,additionalPoints:r});return await this.coreFunctions.performUpdate({updateInstructions:c,actionId:t,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{deletedPoint:n.value,intervalsFromSubset:i,pointsFromSubset:a,additionalPoints:r}}})}}async createUpdateInstructions({intervalsFromSubset:e,pointsFromSubset:t,modifiedAdditionalPoints:n,additionalPoints:r}){let a,i=await this.stateValues.dx,s=e=>Math.round(e/i)*i,o=[];for(let t of e)o.push(new theModule.OpenInterval(s(t[0]),s(t[1])));for(let e of t)e.inSubset&&o.push(new theModule.Singleton(s(e.value)));a=0===o.length?new theModule.EmptySet:1===o.length?o[0]:new theModule.Union(o);let l=[{componentName:this.componentName,updateType:"updateValue",stateVariable:"subsetValue",value:a}];return n&&l.push({componentName:this.componentName,updateType:"updateValue",stateVariable:"additionalPoints",value:r.map(s)}),l}async movePoint({pointInd:e,value:t,transient:n,actionId:r}){let a=await this.stateValues.dx,i=Math.round(Math.max(await this.stateValues.xmin,Math.min(await this.stateValues.xmax,t))/a)*a,s=await this.stateValues.points,o=s[e],l=s[e-1];l&&(i=Math.max(i,l.value+a));let u=s[e+1];u&&(i=Math.min(i,u.value-a));let c=[...await this.stateValues.additionalPoints],p=[...await this.stateValues.pointsFromSubset],d=[...await this.stateValues.intervalsFromSubset];if(o.isAdditional)return c[o.additionalPointInd]=i,n?await this.coreFunctions.performUpdate({updateInstructions:[{componentName:this.componentName,updateType:"updateValue",stateVariable:"additionalPoints",value:c}],transient:!0,actionId:r}):await this.coreFunctions.performUpdate({updateInstructions:[{componentName:this.componentName,updateType:"updateValue",stateVariable:"additionalPoints",value:c}],actionId:r,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{movedPoint:i,intervalsFromSubset:d,pointsFromSubset:p,additionalPoints:c}}});{let e=p.map((e=>e.value)).indexOf(o.value),t=d.map((e=>e[1])).indexOf(o.value),a=d.map((e=>e[0])).indexOf(o.value);p[e]={value:i,inSubset:p[e].inSubset},-1!==t&&(d[t]=[d[t][0],i]),-1!==a&&(d[a]=[i,d[a][1]]);let s=await this.createUpdateInstructions({intervalsFromSubset:d,pointsFromSubset:p,modifiedAdditionalPoints:!1});return n?await this.coreFunctions.performUpdate({updateInstructions:s,transient:!0,actionId:r}):await this.coreFunctions.performUpdate({updateInstructions:s,actionId:r,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{movedPoint:i,intervalsFromSubset:d,pointsFromSubset:p,additionalPoints:c}}})}}async togglePoint({pointInd:e,actionId:t}){let n=(await this.stateValues.points)[e],r=[...await this.stateValues.pointsFromSubset],a=[...await this.stateValues.intervalsFromSubset],i=[...await this.stateValues.additionalPoints],s=!1;if(n.isAdditional)if(i.splice(n.additionalPointInd,1),s=!0,n.inSubset){for(let[e,t]of a.entries())if(t[0]n.value){let r=[[t[0],n.value],[n.value,t[1]]];a.splice(e,1,...r);break}}else r.push({value:n.value,inSubset:!0});else{let e=r.map((e=>e.value)).indexOf(n.value),t=a.map((e=>e[1])).indexOf(n.value),o=a.map((e=>e[0])).indexOf(n.value);-1!==t?-1!==o?(a[t]=[a[t][0],a[o][1]],a.splice(o,1),r.splice(e,1),i.push(n.value),s=!0):r[e]={value:n.value,inSubset:!n.inSubset}:-1!==o?r[e]={value:n.value,inSubset:!n.inSubset}:(r.splice(e,1),i.push(n.value),s=!0)}let o=await this.createUpdateInstructions({intervalsFromSubset:a,pointsFromSubset:r,modifiedAdditionalPoints:s,additionalPoints:i});return await this.coreFunctions.performUpdate({updateInstructions:o,actionId:t,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{toggledPoint:n.value,intervalsFromSubset:a,pointsFromSubset:r,additionalPoints:i}}})}async toggleInterval({intervalInd:e,actionId:t}){let n=(await this.stateValues.intervals)[e],r=await this.stateValues.points,a=r[e-1],i=r[e],s=[...await this.stateValues.pointsFromSubset],o=[...await this.stateValues.intervalsFromSubset],l=[...await this.stateValues.additionalPoints],u=!1;if(n.inSubset){let e,t;for(let[r,a]of o.entries())if(a[0]<=n.left&&a[1]>=n.right){t=a,e=r;break}if(n.left===t[0])if(n.right===t[1]){if(o.splice(e,1),a&&!a.inSubset){let e=o.map((e=>e[1])).indexOf(a.value);if(-1===e){let e=s.map((e=>e.value)).indexOf(a.value);s.splice(e,1),l.push(a.value),u=!0}}if(i&&!i.inSubset){let e=o.map((e=>e[0])).indexOf(i.value);if(-1===e){let e=s.map((e=>e.value)).indexOf(i.value);s.splice(e,1),l.push(i.value),u=!0}}}else{if(o[e]=[n.right,t[1]],a&&!a.inSubset){let e=o.map((e=>e[1])).indexOf(a.value);if(-1===e){let e=s.map((e=>e.value)).indexOf(a.value);s.splice(e,1),l.push(a.value),u=!0}}s.push({value:i.value,inSubset:!0}),l.splice(i.additionalPointInd,1),u=!0}else if(n.right===t[1]){if(o[e]=[t[0],n.left],i&&!i.inSubset){let e=o.map((e=>e[0])).indexOf(i.value);if(-1===e){let e=s.map((e=>e.value)).indexOf(i.value);s.splice(e,1),l.push(i.value),u=!0}}s.push({value:a.value,inSubset:!0}),l.splice(a.additionalPointInd,1),u=!0}else{let r=[[t[0],n.left],[n.right,t[1]]];o.splice(e,1,...r),s.push({value:a.value,inSubset:!0}),s.push({value:i.value,inSubset:!0}),l.splice(i.additionalPointInd,1),l.splice(a.additionalPointInd,1),u=!0}}else{let e=o.map((e=>e[1])).indexOf(n.left),t=o.map((e=>e[0])).indexOf(n.right);if(-1===e)-1===t?(o.push([n.left,n.right]),i&&i.isAdditional&&(l.splice(i.additionalPointInd,1),u=!0),a&&a.isAdditional&&(l.splice(a.additionalPointInd,1),u=!0)):(i.inSubset?(o[t]=[n.left,o[t][1]],l.push(i.value),u=!0):o.push([n.left,n.right]),a&&a.isAdditional&&(l.splice(a.additionalPointInd,1),u=!0));else if(-1===t)a.inSubset?(o[e]=[o[e][0],n.right],l.push(a.value),u=!0):o.push([n.left,n.right]),i&&i.isAdditional&&(l.splice(i.additionalPointInd,1),u=!0);else if(a.inSubset)if(i.inSubset){let n=[o[e][0],o[t][1]];o.splice(e,2,n),l.push(a.value),l.push(i.value),u=!0}else o[e]=[o[e][0],n.right],l.push(a.value),u=!0;else i.inSubset?(o[t]=[n.left,o[t][1]],l.push(i.value),u=!0):o.push([n.left,n.right])}let c=await this.createUpdateInstructions({intervalsFromSubset:o,pointsFromSubset:s,modifiedAdditionalPoints:u,additionalPoints:l});return await this.coreFunctions.performUpdate({updateInstructions:c,actionId:t,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{toggledInterval:[n.left,n.right],intervalsFromSubset:o,pointsFromSubset:s,additionalPoints:l}}})}async clear({actionId:e}){let t=await this.createUpdateInstructions({intervalsFromSubset:[],pointsFromSubset:[],modifiedAdditionalPoints:!0,additionalPoints:[]});return await this.coreFunctions.performUpdate({updateInstructions:t,actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{cleared:!0,intervalsFromSubset:[],pointsFromSubset:[],additionalPoints:[]}}})}async setToR({actionId:e}){let t=await this.createUpdateInstructions({intervalsFromSubset:[[-1/0,1/0]],pointsFromSubset:[],modifiedAdditionalPoints:!0,additionalPoints:[]});return await this.coreFunctions.performUpdate({updateInstructions:t,actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{setToR:!0,intervalsFromSubset:[[-1/0,1/0]],pointsFromSubset:[],additionalPoints:[]}}})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}function parseValueIntoSubset({inputString:e,format:t,variable:n}){if(!e)return new theModule.EmptySet;let r;if("latex"===t)try{r=me$3.fromLatex(e)}catch(t){return console.warn(`Invalid latex for subsetOfRealsInput: ${e}`),new theModule.EmptySet}else if("text"===t)try{r=me$3.fromText(e)}catch(t){return console.warn(`Invalid text for subsetOfRealsInput: ${e}`),new theModule.EmptySet}return buildSubsetFromMathExpression(r,n)}class SubsetOfReals extends MathComponent{static componentType="subsetOfReals";static rendererType="math";static primaryStateVariableForDefinition="subsetValue";static createAttributesObject(){let e=super.createAttributesObject();return e.createIntervals.defaultValue=!0,e.variable={createComponentOfType:"variable",createStateVariable:"variable",defaultValue:me$3.fromAst("x")},e.displayMode={createComponentOfType:"text",createStateVariable:"displayMode",defaultValue:"intervals",public:!0,toLowerCase:!0,validValues:["intervals","inequalities"]},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return renameStateVariable({stateVariableDefinitions:e,oldName:"unnormalizedValue",newName:"unnormalizedValuePreliminary"}),e.value.shadowingInstructions.createComponentOfType="math",e.haveSingleSubsetChild={returnDependencies:()=>({mathChildren:{dependencyType:"child",childGroups:["maths"]}}),definition:({dependencyValues:e,componentInfoObjects:t})=>({setValue:{haveSingleSubsetChild:1===e.mathChildren.length&&1===e.mathChildren.filter((e=>t.isInheritedComponentType({inheritedComponentType:e.componentType,baseComponentType:"subsetOfReals"}))).length}})},e.subsetValue={stateVariablesDeterminingDependencies:["haveSingleSubsetChild"],returnDependencies({stateValues:e}){let t={haveSingleSubsetChild:{dependencyType:"stateVariable",variableName:"haveSingleSubsetChild"}};return e.haveSingleSubsetChild?t.subsetChild={dependencyType:"child",childGroups:["maths"],variableNames:["subsetValue"]}:(t.unnormalizedValuePreliminary={dependencyType:"stateVariable",variableName:"unnormalizedValuePreliminary"},t.variable={dependencyType:"stateVariable",variableName:"variable"}),t},definition({dependencyValues:e}){let t;return t=e.haveSingleSubsetChild?e.subsetChild[0].stateValues.subsetValue:buildSubsetFromMathExpression(e.unnormalizedValuePreliminary,e.variable),{setValue:{subsetValue:t}}},async inverseDefinition({desiredStateVariableValues:e,dependencyValues:t,stateValues:n}){if(t.haveSingleSubsetChild)return{success:!0,instructions:[{setDependency:"subsetChild",desiredValue:e.subsetValue,childIndex:0,variableIndex:0}]};return{success:!0,instructions:[{setDependency:"unnormalizedValuePreliminary",desiredValue:mathExpressionFromSubsetValue({subsetValue:e.subsetValue,variable:t.variable,displayMode:await n.displayMode})}]}}},e.unnormalizedValue={returnDependencies:()=>({subsetValue:{dependencyType:"stateVariable",variableName:"subsetValue"},displayMode:{dependencyType:"stateVariable",variableName:"displayMode"},variable:{dependencyType:"stateVariable",variableName:"variable"}}),definition:({dependencyValues:e})=>({setValue:{unnormalizedValue:mathExpressionFromSubsetValue(e)}}),inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t})=>({success:!0,instructions:[{setDependency:"subsetValue",desiredValue:buildSubsetFromMathExpression(e.unnormalizedValue,t.variable)}]})},e}}function mathExpressionFromSubsetValue({subsetValue:e,variable:t,displayMode:n="intervals"}){function r(e){return null===e?"_":"intervals"===n?e.closedInterval?["interval",["tuple",e.left,e.right],["tuple",!0,!0]]:e.openClosedInterval?["interval",["tuple",e.left,e.right],["tuple",!1,!0]]:e.closedOpenInterval?["interval",["tuple",e.left,e.right],["tuple",!0,!1]]:e.toMathExpression().tree:e.closedInterval?["lts",["tuple",e.left,t,e.right],["tuple",!1,!1]]:e.openClosedInterval?e.left===-1/0?["le",t,e.right]:["lts",["tuple",e.left,t,e.right],["tuple",!0,!1]]:e.closedOpenInterval?e.right===1/0?["ge",t,e.left]:["lts",["tuple",e.left,t,e.right],["tuple",!1,!0]]:e instanceof theModule.OpenInterval?e.left===-1/0?["<",t,e.right]:e.right===1/0?[">",t,e.left]:["lts",["tuple",e.left,t,e.right],["tuple",!0,!0]]:e instanceof theModule.Singleton?["=",t,e.element]:e.isEmpty()?["in",t,"∅"]:e instanceof theModule.RealLine?["in",t,"R"]:null}let a;if(e instanceof theModule.Union){let t=e.subsets.filter((e=>e instanceof theModule.Singleton)),i=e.subsets.filter((e=>e instanceof theModule.OpenInterval));for(let e=0;e(void 0===e.left?e.element:e.left)-(void 0===t.left?t.element:t.left))).map((e=>r(e)));a=s.length>1?"intervals"===n?me$3.fromAst(["union",...s]):me$3.fromAst(["or",...s]):me$3.fromAst(s[0])}else a=me$3.fromAst(r(e));return a}class Split extends CompositeComponent{static componentType="split";static assignNamesToReplacements=!0;static stateVariableToEvaluateAfterReplacements="readyToExpandWhenResolved";static createAttributesObject(){let e=super.createAttributesObject();return e.assignNamesSkip={createPrimitiveOfType:"number"},e.type={createPrimitiveOfType:"string",createStateVariable:"type",defaultPrimitiveValue:"text",toLowerCase:!0,validValues:["text"]},e.splitBy={createComponentOfType:"text",createStateVariable:"splitBy",defaultValue:"letter",toLowerCase:!0,validValues:["letter","word","comma"]},e}static returnSugarInstructions(){let e=[];return e.push({replacementFunction:function({matchedChildren:e,componentAttributes:t}){let n=t.type;return["text"].includes(n)||(n="text"),{success:!0,newChildren:[{componentType:n,children:e}]}}}),e}static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.originalValue={returnDependencies:()=>({child:{dependencyType:"child",childGroups:["anything"],variableNames:["value"]}}),definition:({dependencyValues:e})=>e.child.length>0?{setValue:{originalValue:e.child[0].stateValues.value}}:{setValue:{originalValue:null}},inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t})=>t.child.length>0?{success:!0,instructions:[{setDependency:"child",desiredValue:e.originalValue,childIndex:0,variableIndex:0}]}:{success:!1}},e.splitValues={returnDependencies:()=>({type:{dependencyType:"stateVariable",variableName:"type"},originalValue:{dependencyType:"stateVariable",variableName:"originalValue"},splitBy:{dependencyType:"stateVariable",variableName:"splitBy"}}),definition({dependencyValues:e}){if(null===e.originalValue)return{setValue:{splitValues:[]}};let t=[];return t="letter"===e.splitBy?[...e.originalValue]:"word"===e.splitBy?e.originalValue.split(/\s+/):"comma"===e.splitBy?e.originalValue.split(/\s*,\s*/):[e.originalValue],{setValue:{splitValues:t}}}},e.readyToExpandWhenResolved={returnDependencies:()=>({splitValues:{dependencyType:"stateVariable",variableName:"splitValues"}}),markStale:()=>({updateReplacements:!0}),definition:function(){return{setValue:{readyToExpandWhenResolved:!0}}}},e}static async createSerializedReplacements({component:e,componentInfoObjects:t}){let n=e.attributes.newNamespace?.primitive,r={componentType:"textList",state:{textsShadow:await e.stateValues.splitValues},downstreamDependencies:{[e.componentName]:[{dependencyType:"referenceShadow",compositeName:e.componentName,propVariable:"splitValues"}]}};return{replacements:processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:[r],parentName:e.componentName,parentCreatesNewNamespace:n,componentInfoObjects:t}).serializedComponents}}}class BestFitLine extends Line{static componentType="bestFitLine";static rendererType="line";static createAttributesObject(){let e=super.createAttributesObject();return delete e.draggable,delete e.equation,delete e.through,delete e.slope,e.points={createComponentOfType:"_pointListComponent"},e}static returnSugarInstructions(){return[]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.draggable={shadowingInstructions:{createComponentOfType:"boolean"},public:!0,forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{draggable:!1}})},e.nDimensions={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({}),definition:()=>({setValue:{nDimensions:2}})},delete e.nPointsPrescribed,delete e.basedOnSlope,delete e.dForSlope,delete e.essentialPoint1x,delete e.essentialPoint1y,delete e.equationIdentity,delete e.equation.stateVariablesDeterminingDependencies,e.equation.returnDependencies=()=>({points:{dependencyType:"attributeComponent",attributeName:"points",variableNames:["points","nDimensions"]},variables:{dependencyType:"stateVariable",variableName:"variables"}}),e.equation.definition=function({dependencyValues:e}){if(!e.points||e.points.stateValues.nDimensions<2||e.points.stateValues.points.length<1){let e=me$3.fromAst("_");return{setValue:{equation:e,coeff0:e,coeffvar1:e,coeffvar2:e}}}let t=[],n=[];for(let r of e.points.stateValues.points){let e=r.slice(0,2).map((e=>e&&e.evaluate_to_constant()));e.every(Number.isFinite)&&(t.push([1,e[0]]),n.push([e[1]]))}if(0===t.length){let e=me$3.fromAst("_");return{setValue:{equation:e,coeff0:e,coeffvar1:e,coeffvar2:e}}}t=me$3.math.matrix(t),n=me$3.math.matrix(n);let r=me$3.math.transpose(t),a=me$3.math.multiply(r,n),i=me$3.math.multiply(r,t),s=me$3.math.lusolve(i,a),o=me$3.fromAst(me$3.math.subset(s,me$3.math.index(0,0))),l=me$3.fromAst(me$3.math.subset(s,me$3.math.index(1,0))),u=me$3.fromAst(-1),c=e.variables,p=me$3.fromAst(["+",["*","a","x"],"c"]).substitute({a:l,c:o,x:c[0],y:c[1]}).simplify();return{setValue:{equation:me$3.fromAst(["=","y","r"]).substitute({r:p}),coeff0:o,coeffvar1:l,coeffvar2:u}}},delete e.equation.inverseDefinition,delete e.points.stateVariablesDeterminingDependencies,e.points.returnArrayDependenciesByKey=function(){return{globalDependencies:{coeff0:{dependencyType:"stateVariable",variableName:"coeff0"},coeffvar1:{dependencyType:"stateVariable",variableName:"coeffvar1"},coeffvar2:{dependencyType:"stateVariable",variableName:"coeffvar2"},variables:{dependencyType:"stateVariable",variableName:"variables"},lastPointsFromInverting:{dependencyType:"stateVariable",variableName:"lastPointsFromInverting"}}}},e}}class RegionBetweenCurveXAxis extends GraphicalComponent{static componentType="regionBetweenCurveXAxis";static createAttributesObject(){let e=super.createAttributesObject();return e.boundaryValues={createComponentOfType:"numberList",createStateVariable:"boundaryValues",defaultValue:[0,1],forRenderer:!0,public:!0},e.function={createComponentOfType:"function"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescription:e.selectedStyle.fillColorWord}}}},e.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({styleDescription:{dependencyType:"stateVariable",variableName:"styleDescription"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescriptionWithNoun:e.styleDescription+" region"}}}},e.function={additionalStateVariablesDefined:[{variableName:"haveFunction",forRenderer:!0},{variableName:"fDefinition",forRenderer:!0}],returnDependencies:()=>({functionAttr:{dependencyType:"attributeComponent",attributeName:"function",variableNames:["numericalfs","nInputs","nOutputs","fDefinition"]}}),definition:({dependencyValues:e})=>null===e.functionAttr||1!==e.functionAttr.stateValues.nInputs||1!==e.functionAttr.stateValues.nOutputs?{setValue:{function:()=>NaN,haveFunction:!1,fDefinition:{}}}:{setValue:{function:e.functionAttr.stateValues.numericalfs[0],haveFunction:!0,fDefinition:e.functionAttr.stateValues.fDefinition}}},e}}class RegionHalfPlane extends GraphicalComponent{static componentType="regionHalfPlane";static rendererType=void 0;static createAttributesObject(){let e=super.createAttributesObject();return e.horizontal={createComponentOfType:"boolean",createStateVariable:"horizontal",defaultValue:!0,public:!0},e.boundaryValue={createComponentOfType:"number",createStateVariable:"boundaryValue",defaultValue:0,public:!0},e.greaterThan={createComponentOfType:"boolean",createStateVariable:"greaterThan",defaultValue:!0,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nearestPoint={returnDependencies:()=>({horizontal:{dependencyType:"stateVariable",variableName:"horizontal"},boundaryValue:{dependencyType:"stateVariable",variableName:"boundaryValue"},greaterThan:{dependencyType:"stateVariable",variableName:"greaterThan"}}),definition({dependencyValues:e}){let t=e.boundaryValue;return{setValue:{nearestPoint:function({variables:n,scales:r}){if(!Number.isFinite(t))return{};if(e.horizontal){if(e.greaterThan){if(n.x1t){let e=Object.assign({},n);return e.x1=t,e}return{}}if(e.greaterThan){if(n.x2t){let e=Object.assign({},n);return e.x2=t,e}return{}}}}}},e}}class CodeEditor extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{updateImmediateValue:this.updateImmediateValue.bind(this),updateValue:this.updateValue.bind(this),updateComponents:this.updateComponents.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="codeEditor";static variableForPlainMacro="value";static variableForPlainCopy="value";static renderChildren=!0;static processWhenJustUpdatedForNewComponent=!0;static get stateVariablesShadowedForReference(){return["value"]}static createAttributesObject(){let e=super.createAttributesObject();return e.prefill={createComponentOfType:"text",createStateVariable:"prefill",defaultValue:"",public:!0},e.bindValueTo={createComponentOfType:"text"},e.width={createComponentOfType:"_componentSize",createStateVariable:"width",defaultValue:{size:600,isAbsolute:!0},forRenderer:!0,public:!0},e.height={createComponentOfType:"_componentSize",createStateVariable:"height",defaultValue:{size:400,isAbsolute:!0},forRenderer:!0,public:!0},e.viewerRatio={createComponentOfType:"number",createStateVariable:"viewerRatio",defaultValue:.5,forRenderer:!0,public:!0},e.showResults={createComponentOfType:"boolean",createStateVariable:"showResults",defaultValue:!1,forRenderer:!0,public:!0},e.renderedName={createPrimitiveOfType:"string"},e.staticName={createPrimitiveOfType:"string"},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e,componentAttributes:t}){if(e.length>0)return{success:!1};let n={componentType:"codeViewer",children:[{componentType:"renderDoenetML"}]},r=[n];if(t.renderedName&&(n.attributes={renderedName:{primitive:t.renderedName}},n.children[0].props={name:t.renderedName}),t.staticName){let e={componentType:"codeViewer",attributes:{hide:{component:{componentType:"boolean",state:{value:!0}}}},children:[{componentType:"renderDoenetML",props:{name:t.staticName}}]};r.push(e)}return{success:!0,newChildren:r}}}),e}static returnChildGroups(){return[{group:"codeViewers",componentTypes:["codeViewer"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.viewerHeight={returnDependencies:()=>({height:{dependencyType:"stateVariable",variableName:"height"},viewerRatio:{dependencyType:"stateVariable",variableName:"viewerRatio"}}),definition:function({dependencyValues:e}){if(!e.height.isAbsolute)throw Error("Codeeditor relative height not implemented");return{setValue:{viewerHeight:{size:e.height.size*e.viewerRatio,isAbsolute:!0}}}}},e.value={public:!0,shadowingInstructions:{createComponentOfType:"text"},hasEssential:!0,forRenderer:!0,returnDependencies:()=>({bindValueTo:{dependencyType:"attributeComponent",attributeName:"bindValueTo",variableNames:["value"]},prefill:{dependencyType:"stateVariable",variableName:"prefill"}}),definition:function({dependencyValues:e}){return e.bindValueTo?{setValue:{value:e.bindValueTo.stateValues.value}}:{useEssentialOrDefaultValue:{value:{variablesToCheck:"value",defaultValue:e.prefill}}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){return t.bindValueTo?{success:!0,instructions:[{setDependency:"bindValueTo",desiredValue:e.value,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"value",value:e.value}]}}},e.immediateValue={public:!0,shadowingInstructions:{createComponentOfType:"text"},hasEssential:!0,forRenderer:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:function({dependencyValues:e,changes:t,justUpdatedForNewComponent:n}){return t.value&&!n?{setValue:{immediateValue:e.value},makeEssential:{immediateValue:!0}}:{useEssentialOrDefaultValue:{immediateValue:{variablesToCheck:"immediateValue",defaultValue:e.value}}}},inverseDefinition:function({desiredStateVariableValues:e,initialChange:t,shadowedVariable:n}){let r=[{setEssentialValue:"immediateValue",value:e.immediateValue}];return t||n||r.push({setDependency:"value",desiredValue:e.immediateValue}),{success:!0,instructions:r}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:function({dependencyValues:e}){return{setValue:{text:e.value}}}},e.componentType={returnDependencies:()=>({}),definition:()=>({setValue:{componentType:"text"}})},e.viewerChild={returnDependencies:()=>({viewerChild:{dependencyType:"child",childGroups:["codeViewers"]}}),definition:({dependencyValues:e})=>e.viewerChild.length>0?{setValue:{viewerChild:e.viewerChild}}:{setValue:{viewerChild:null}}},e}updateImmediateValue({text:e,actionId:t}){if(!this.stateValues.disabled)return this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"immediateValue",value:e},{updateType:"setComponentNeedingUpdateValue",componentName:this.componentName}],actionId:t});this.coreFunctions.resolveAction({actionId:t})}updateValue({actionId:e}){if(!this.stateValues.disabled&&this.stateValues.immediateValue!==this.stateValues.value){let t=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"value",value:this.stateValues.immediateValue},{updateType:"executeUpdate"},{updateType:"updateValue",componentName:this.componentName,stateVariable:"immediateValue",valueOfStateVariable:"value"},{updateType:"unsetComponentNeedingUpdateValue"}],n={verb:"answered",object:{componentName:this.componentName,componentType:this.componentType},result:{response:this.stateValues.immediateValue,responseText:this.stateValues.immediateValue}};return this.stateValues.answerAncestor&&(n.context={answerAncestor:this.stateValues.answerAncestor.componentName}),this.coreFunctions.performUpdate({updateInstructions:t,actionId:e,event:n}).then((()=>{this.coreFunctions.triggerChainedActions({componentName:this.componentName}),this.attributes.staticName&&2===this.definingChildren.length&&"codeViewer"===this.definingChildren[1].componentType&&this.coreFunctions.performAction({componentName:this.definingChildren[1].componentName,actionName:"updateComponents"})}))}this.coreFunctions.resolveAction({actionId:e})}async updateComponents(){1===this.definingChildren.length&&"codeViewer"===this.definingChildren[0].componentType&&await this.coreFunctions.performAction({componentName:this.definingChildren[0].componentName,actionName:"updateComponents"})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class CodeViewer extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{updateComponents:this.updateComponents.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="codeViewer";static renderChildren=!0;static includeBlankStringChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.codeSource={createTargetComponentNames:!0},e.width={createComponentOfType:"_componentSize"},e.height={createComponentOfType:"_componentSize"},e.hasCodeEditorParent={createComponentOfType:"boolean"},e.renderedName={createPrimitiveOfType:"string"},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e,componentAttributes:t}){if(e.length>0)return{success:!1};let n={componentType:"renderDoenetML"};return t.codeSource&&(n.attributes={codeSource:{targetComponentNames:t.codeSource}}),t.renderedName&&(n.props={name:t.renderedName}),{success:!0,newChildren:[n]}}}),e}static returnChildGroups(){return[{group:"children",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.hasCodeEditorParent={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,returnDependencies:()=>({codeEditorParent:{dependencyType:"parentIdentity",parentComponentType:"codeEditor"}}),definition:function({dependencyValues:e}){return e.codeEditorParent?{setValue:{hasCodeEditorParent:!0}}:{setValue:{hasCodeEditorParent:!1}}}},e.width={public:!0,shadowingInstructions:{createComponentOfType:"_componentSize"},hasEssential:!0,forRenderer:!0,defaultValue:{size:600,isAbsolute:!0},returnDependencies:()=>({widthAttr:{dependencyType:"attributeComponent",attributeName:"width",variableNames:["componentSize"]},parentWidth:{dependencyType:"parentStateVariable",variableName:"width",parentComponentType:"codeEditor"}}),definition:function({dependencyValues:e}){return e.widthAttr?{setValue:{width:e.widthAttr.stateValues.componentSize}}:e.parentWidth?{setValue:{width:e.parentWidth}}:{useEssentialOrDefaultValue:{width:!0}}}},e.height={public:!0,shadowingInstructions:{createComponentOfType:"_componentSize"},hasEssential:!0,forRenderer:!0,defaultValue:{size:400,isAbsolute:!0},returnDependencies:()=>({heightAttr:{dependencyType:"attributeComponent",attributeName:"height",variableNames:["componentSize"]},parentViewerHeight:{dependencyType:"parentStateVariable",variableName:"viewerHeight",parentComponentType:"codeEditor"}}),definition:function({dependencyValues:e}){return e.heightAttr?{setValue:{height:e.heightAttr.stateValues.componentSize}}:e.parentViewerHeight?{setValue:{height:e.parentViewerHeight}}:{useEssentialOrDefaultValue:{height:!0}}}},e.codeSourceComponentName={returnDependencies:()=>({codeSource:{dependencyType:"attributeTargetComponentNames",attributeName:"codeSource"}}),definition({dependencyValues:e}){let t;return t=1===e.codeSource?.length?e.codeSource[0].absoluteName:null,{setValue:{codeSourceComponentName:t}}}},e.codeSource={returnDependencies:()=>({codeSourceComponentName:{dependencyType:"stateVariable",variableName:"codeSourceComponentName"},codeEditorParent:{dependencyType:"parentIdentity",parentComponentType:"codeEditor"}}),definition:function({dependencyValues:e}){return e.codeSourceComponentName?{setValue:{codeSource:e.codeSourceComponentName}}:e.codeEditorParent?{setValue:{codeSource:e.codeEditorParent.componentName}}:{setValue:{codeSource:null}}}},e}async updateComponents(){1===this.definingChildren.length&&"renderDoenetML"===this.definingChildren[0].componentType&&await this.coreFunctions.performAction({componentName:this.definingChildren[0].componentName,actionName:"updateComponents"})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class RenderDoenetML extends CompositeComponent{constructor(e){super(e),Object.assign(this.actions,{updateComponents:this.updateComponents.bind(this)})}static componentType="renderDoenetML";static assignNamesToReplacements=!0;static createsVariants=!0;static stateVariableToEvaluateAfterReplacements="triggerUpdates";static createAttributesObject(){let e=super.createAttributesObject();return e.assignNamesSkip={createPrimitiveOfType:"number"},e.codeSource={createTargetComponentNames:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.codeSourceComponentName={returnDependencies:()=>({codeSource:{dependencyType:"attributeTargetComponentNames",attributeName:"codeSource"}}),definition({dependencyValues:e}){let t;return t=1===e.codeSource?.length?e.codeSource[0].absoluteName:null,{setValue:{codeSourceComponentName:t}}}},e.codeSource={returnDependencies:()=>({codeSourceComponentName:{dependencyType:"stateVariable",variableName:"codeSourceComponentName"},parentCodeSource:{dependencyType:"parentStateVariable",parentComponentType:"codeViewer",variableName:"codeSource"}}),definition:function({dependencyValues:e}){return e.codeSourceComponentName?{setValue:{codeSource:e.codeSourceComponentName}}:e.parentCodeSource?{setValue:{codeSource:e.parentCodeSource}}:{setValue:{codeSource:null}}}},e.doenetML={stateVariablesDeterminingDependencies:["codeSource"],returnDependencies:({stateValues:e})=>({doenetML:{dependencyType:"stateVariable",componentName:e.codeSource,variableName:"text",variablesOptional:!0}}),definition({dependencyValues:e}){let t="";return e.doenetML&&(t=e.doenetML,"string"!=typeof t&&(t="")),{setValue:{doenetML:t}}}},e.readyToExpandWhenResolved={returnDependencies:()=>({doenetML:{dependencyType:"stateVariable",variableName:"doenetML"}}),definition:()=>({setValue:{readyToExpandWhenResolved:!0}})},e.triggerUpdates={defaultValue:!0,hasEssential:!0,returnDependencies:()=>({}),markStale:()=>({updateReplacements:!0}),definition:()=>({useEssentialOrDefaultValue:{triggerUpdates:{}}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"triggerUpdates",value:e.triggerUpdates}]})},e.isVariantComponent={returnDependencies:()=>({}),definition:()=>({setValue:{isVariantComponent:!0}})},e.generatedVariantInfo={returnDependencies:({sharedParameters:e,componentInfoObjects:t})=>({variantSeed:{dependencyType:"value",value:e.variantSeed},variantDescendants:{dependencyType:"descendant",componentTypes:Object.keys(t.componentTypesCreatingVariants),variableNames:["isVariantComponent","generatedVariantInfo"],useReplacementsForComposites:!0,recurseToMatchedChildren:!1,variablesOptional:!0,includeNonActiveChildren:!0,ignoreReplacementsOfEncounteredComposites:!0}}),definition({dependencyValues:e,componentName:t}){let n={seed:e.variantSeed,meta:{createdBy:t}},r=n.subvariants=[];for(let t of e.variantDescendants)t.stateValues.isVariantComponent?r.push(t.stateValues.generatedVariantInfo):t.stateValues.generatedVariantInfo&&r.push(...t.stateValues.generatedVariantInfo.subvariants);return{setValue:{generatedVariantInfo:n}}}},e}static async createSerializedReplacements({component:e,componentInfoObjects:t,flags:n,workspace:r}){let a=[],i=(await e.stateValues.doenetML).trim();r.previousDoenetML=i;try{a=(await expandDoenetMLsToFullSerializedComponents({cids:[],doenetMLs:[i],componentInfoObjects:t,flags:n})).fullSerializedComponents[0]}catch(e){return console.warn("error in user entered doenetML"),console.warn(e.message),{replacements:[]}}let s=e.componentName.split("/").map((e=>({namespace:e,componentCounts:{},namesUsed:{}})));return createComponentNames({serializedComponents:a,componentInfoObjects:t,namespaceStack:s}),restrictTNamesToNamespace({components:a,namespace:`${e.componentName}/`}),{replacements:processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:a,parentName:e.componentName,parentCreatesNewNamespace:!0,componentInfoObjects:t,originalNamesAreConsistent:!0}).serializedComponents}}static async calculateReplacementChanges({component:e,componentChanges:t,componentInfoObjects:n,flags:r,workspace:a}){let i=(await e.stateValues.doenetML).trim();if(a.previousDoenetML===i)return[];a.previousDoenetML=i;let s=(await this.createSerializedReplacements({component:e,componentInfoObjects:n,flags:r,workspace:a})).replacements;return[{changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:0,numberReplacementsToReplace:e.replacements.length,serializedReplacements:s}]}static setUpVariant({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n}){setUpVariantSeedAndRng({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n,useSubpartVariantRng:!0})}async updateComponents({actionId:e}){let t=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"triggerUpdates",value:!0}];await this.coreFunctions.performUpdate({updateInstructions:t,actionId:e})}}class HasSameFactoring extends BooleanComponent{static componentType="hasSameFactoring";static rendererType="boolean";static createAttributesObject(){let e=super.createAttributesObject();return e.variable={createComponentOfType:"variable",createStateVariable:"variable",defaultValue:me$3.fromAst("x")},e.restrictDivision={createComponentOfType:"boolean",createStateVariable:"restrictDivision",defaultValue:!1},e.monomialFactorMustMatch={createComponentOfType:"boolean",createStateVariable:"monomialFactorMustMatch",defaultValue:!1},e.allowOnlySignDifferences={createComponentOfType:"boolean",createStateVariable:"allowOnlySignDifferences",defaultValue:!1},e}static returnChildGroups(){return[{group:"maths",componentTypes:["math"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return delete e.parsedExpression,delete e.mathChildrenByCode,e.value={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,returnDependencies:()=>({mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]},allowedErrorInNumbers:{dependencyType:"stateVariable",variableName:"allowedErrorInNumbers"},includeErrorInNumberExponents:{dependencyType:"stateVariable",variableName:"includeErrorInNumberExponents"},allowedErrorIsAbsolute:{dependencyType:"stateVariable",variableName:"allowedErrorIsAbsolute"},nSignErrorsMatched:{dependencyType:"stateVariable",variableName:"nSignErrorsMatched"},variable:{dependencyType:"stateVariable",variableName:"variable"},restrictDivision:{dependencyType:"stateVariable",variableName:"restrictDivision"},monomialFactorMustMatch:{dependencyType:"stateVariable",variableName:"monomialFactorMustMatch"},allowOnlySignDifferences:{dependencyType:"stateVariable",variableName:"allowOnlySignDifferences"}}),definition:function({dependencyValues:e}){if(2!==e.mathChildren.length)return{setValue:{value:!1}};let t=e.mathChildren[0].stateValues.value,n=e.mathChildren[1].stateValues.value;if(1!==checkEquality({object1:t,object2:n,isUnordered:!1,partialMatches:!1,symbolicEquality:!1,allowedErrorInNumbers:e.allowedErrorInNumbers,includeErrorInNumberExponents:e.includeErrorInNumberExponents,allowedErrorIsAbsolute:e.allowedErrorIsAbsolute,nSignErrorsMatched:e.nSignErrorsMatched}).fraction_equal)return{setValue:{value:!1}};if(Array.isArray(t.tree)&&"-"===t.tree[0]&&(t=me$3.fromAst(t.tree[1])),Array.isArray(n.tree)&&"-"===n.tree[0]&&(n=me$3.fromAst(n.tree[1])),e.restrictDivision||e.monomialFactorMustMatch||e.allowOnlySignDifferences||(Array.isArray(t.tree)&&"/"===t.tree[0]&&0===me$3.fromAst(t.tree[2]).variables().length&&(t=me$3.fromAst(t.tree[1]),Array.isArray(t.tree)&&"-"===t.tree[0]&&(t=me$3.fromAst(t.tree[1]))),Array.isArray(n.tree)&&"/"===n.tree[0]&&0===me$3.fromAst(n.tree[2]).variables().length&&(n=me$3.fromAst(n.tree[1]),Array.isArray(n.tree)&&"-"===n.tree[0]&&(n=me$3.fromAst(n.tree[1])))),t=me$3.fromAst(expandPositiveIntegerPowers(t.tree)),n=me$3.fromAst(expandPositiveIntegerPowers(n.tree)),!Array.isArray(t.tree)||"*"!==t.tree[0])return Array.isArray(n.tree)&&"*"===n.tree[0]?{setValue:{value:!1}}:{setValue:{value:!0}};if(!Array.isArray(n.tree)||"*"!==n.tree[0])return{setValue:{value:!1}};if(e.monomialFactorMustMatch||e.allowOnlySignDifferences){let e=findMonomialFromFactors(t.tree.slice(1)),r=findMonomialFromFactors(n.tree.slice(1));if(!e.equals(r)){let t=me$3.fromAst(["-",r.tree]);if(!e.equals(t))return{setValue:{value:!1}}}}if(e.allowOnlySignDifferences){let r=normalizeFactorSigns(t),a=normalizeFactorSigns(n);return{setValue:{value:r.equalsViaSyntax(a,{allowed_error_in_numbers:e.allowedErrorInNumbers,include_error_in_number_exponents:e.includeErrorInNumberExponents,allowed_error_is_absolute:e.allowedErrorIsAbsolute})}}}let r=t.tree.slice(1).filter((e=>me$3.fromAst(e).variables().length>0)),a=n.tree.slice(1).filter((e=>me$3.fromAst(e).variables().length>0));if(r.length!==a.length)return{setValue:{value:!1}};let i=0,s=0,o=0,l=0,u=e.variable.subscripts_to_strings().tree;for(let e of r){let t=me$3.fromAst(e).subscripts_to_strings().derivative(u).derivative(u).simplify();if(0===t.tree)s++;else{if(0!==t.variables().length)return{setValue:{value:!1}};i++}}for(let e of a){let t=me$3.fromAst(e).subscripts_to_strings().derivative(u).derivative(u).simplify();if(0===t.tree)l++;else{if(0!==t.variables().length)return{setValue:{value:!1}};o++}}return{setValue:{value:s===l&&i===o}}}},e}}function expandPositiveIntegerPowers(e){if(!Array.isArray(e))return e;if("^"===e[0]){let t=e[1],n=e[2];Number.isInteger(n)&&n>0&&(e=["*",...Array(n).fill(t)])}if("*"===e[0]){let t=e;e=["*"];for(let n of t.slice(1))if(Array.isArray(n)&&"^"===n[0]){let t=n[1],r=n[2];Number.isInteger(r)&&r>0?e.push(...Array(r).fill(t)):e.push(n)}else e.push(n)}return e}function findMonomialFromFactors(e){let t,n=[],r=!1;for(let t of e)if("string"==typeof t||0===me$3.fromAst(t).variables().length){if(!r){if(n.length>0)return me$3.fromAst("_");r=!0}n.push(t)}else r=!1;return t=0===n.length?1:1===n.length?n[0]:["*",...n],me$3.fromAst(t)}function normalizeFactorSigns(e){let t=e.simplify().tree;if("-"===t[0]&&(t=t[1]),"*"!==t[0])return me$3.fromAst(t).simplify();let n=["*"];for(let e of t.slice(1))if("number"==typeof e)e<0?n.push(-e):n.push(e);else if(Array.isArray(e))if("-"===e[0])n.push(e[1]);else if("+"===e[0]){let t=!1,r=e[1];if("number"==typeof r)r<0&&(t=!0);else if(Array.isArray(r))if("-"===r[0])t=!0;else if("*"===r[0]){let e=r[1];"number"==typeof e?e<0&&(t=!0):Array.isArray(e)&&"-"===e[0]&&(t=!0)}t?n.push(me$3.fromAst(["-",e]).simplify().tree):n.push(e)}else n.push(e);else n.push(e);return me$3.fromAst(n).simplify()}class DataFrame extends BaseComponent{static componentType="dataFrame";static rendererType=void 0;static createAttributesObject(){let e=super.createAttributesObject();return e.source={createComponentOfType:"text",createStateVariable:"source",required:!0,public:!0,forRenderer:!0},e.hasHeader={createComponentOfType:"boolean",createStateVariable:"hasHeader",defaultValue:!0,public:!0},e.columnTypes={createComponentOfType:"textList",createStateVariable:"columnTypesPrelim",defaultValue:[]},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.cid={forRenderer:!0,returnDependencies:()=>({source:{dependencyType:"stateVariable",variableName:"source"}}),definition:function({dependencyValues:e}){if(!e.source||"doenet:"!==e.source.substring(0,7).toLowerCase())return{setValue:{cid:null}};let t=null,n=e.source.match(/[:&]cid=([^&]+)/i);return n&&(t=n[1]),{setValue:{cid:t}}}},e.dataFrame={stateVariablesDeterminingDependencies:["cid","source"],additionalStateVariablesDefined:[{variableName:"numRows",public:!0,shadowingInstructions:{createComponentOfType:"integer"}},{variableName:"numColumns",public:!0,shadowingInstructions:{createComponentOfType:"integer"}},{variableName:"columnTypes",public:!0,shadowingInstructions:{createComponentOfType:"textList"}},{variableName:"columnNames",public:!0,shadowingInstructions:{createComponentOfType:"textList"}}],returnDependencies:({stateValues:e})=>({fileContents:{dependencyType:"file",cid:e.cid,uri:e.source,fileType:"csv"},hasHeader:{dependencyType:"stateVariable",variableName:"hasHeader"},columnTypesPrelim:{dependencyType:"stateVariable",variableName:"columnTypesPrelim"}}),definition:function({dependencyValues:e,componentName:t}){let n=[],r=[],a=e.fileContents.trim().split("\n").map((e=>e.trim().split(",").map((e=>e.trim())))),i=a[0]?.length,s=!1;for(let e of a.slice(1))if(e.length!==i){s=!0;break}if(s)return console.warn(`Data has invalid shape. Rows has inconsistent lengths. Found in componentName :${t}`),{setValue:{dataFrame:null,numRows:u,numColumns:i,columnTypes:n,columnNames:r}};let o={},l=[];if(e.hasHeader?(o.columnNames=a[0].map((e=>(['"',"'"].includes(e[0])&&e[e.length-1]===e[0]&&(e=e.substring(1,e.length-1)),e))),l=a.slice(1)):(o.columnNames=[...Array(i).keys()].map((e=>`col${e+1}`)),l=a),[...new Set(o.columnNames)].length({numColumns:{dependencyType:"stateVariable",variableName:"numColumns"}}),returnArraySize:({dependencyValues:e})=>[e.numColumns],returnArrayDependenciesByKey:()=>({globalDependencies:{dataFrame:{dependencyType:"stateVariable",variableName:"dataFrame"},numColumns:{dependencyType:"stateVariable",variableName:"numColumns"},numRows:{dependencyType:"stateVariable",variableName:"numRows"},columnTypes:{dependencyType:"stateVariable",variableName:"columnTypes"}}}),arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t}){let n={};for(let r of t){let t=0,a=0;if("number"===e.columnTypes[r]){for(let n=0;n({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.displayDigitsAttr){let n=t.displayDigitsAttr,r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!n&&!r){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({statisticsToDisplayPrelim:{dependencyType:"stateVariable",variableName:"statisticsToDisplayPrelim"}}),definition:function({dependencyValues:e}){let t=["mean","stdev","variance","stderr","count","minimum","quartile1","median","quartile3","maximum","range","sum"],n=[],r=e.statisticsToDisplayPrelim.map((e=>e.toLowerCase()));if(r.includes("default"))n=["mean","stdev","count","minimum","quartile1","median","quartile3","maximum"];else if(r.includes("all"))n=[...t];else for(let e of t)r.includes(e)&&n.push(e);return{setValue:{statisticsToDisplay:n}}}},e.sourceName={returnDependencies:()=>({source:{dependencyType:"attributeTargetComponentNames",attributeName:"source"}}),definition({dependencyValues:e}){let t;return t=1===e.source?.length?e.source[0].absoluteName:null,{setValue:{sourceName:t}}}},e.dataColumn={stateVariablesDeterminingDependencies:["sourceName"],additionalStateVariablesDefined:[{variableName:"columnName",public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0}],returnDependencies:({stateValues:e})=>({dataFrame:{dependencyType:"stateVariable",componentName:e.sourceName,variableName:"dataFrame",variableOptional:!0},desiredColumn:{dependencyType:"stateVariable",variableName:"desiredColumn"}}),definition({dependencyValues:e}){let t=null,n=null;if(e.dataFrame){let r=e.dataFrame,a=r.columnNames.indexOf(e.desiredColumn);if(-1!==a){n=e.desiredColumn,t=[];for(let e of r.data)null!==e[a]&&t.push(e[a])}}return{setValue:{dataColumn:t,columnName:n}}}},e.count={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({dataColumn:{dependencyType:"stateVariable",variableName:"dataColumn"}}),definition({dependencyValues:e}){let t=null;return e.dataColumn&&(t=e.dataColumn.length),{setValue:{count:t}}}},e.sum={public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]},returnDependencies:()=>({dataColumn:{dependencyType:"stateVariable",variableName:"dataColumn"}}),definition({dependencyValues:e}){let t=null;return e.dataColumn&&(t=e.dataColumn.reduce(((e,t)=>e+t))),{setValue:{sum:t}}}},e.mean={public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]},returnDependencies:()=>({dataColumn:{dependencyType:"stateVariable",variableName:"dataColumn"}}),definition({dependencyValues:e}){let t=null;return null!==e.dataColumn&&(t=me$3.math.mean(e.dataColumn)),{setValue:{mean:t}}}},e.stdev={public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]},returnDependencies:()=>({dataColumn:{dependencyType:"stateVariable",variableName:"dataColumn"}}),definition({dependencyValues:e}){let t=null;return e.dataColumn&&(t=me$3.math.std(e.dataColumn)),{setValue:{stdev:t}}}},e.variance={public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]},returnDependencies:()=>({dataColumn:{dependencyType:"stateVariable",variableName:"dataColumn"}}),definition({dependencyValues:e}){let t=null;return e.dataColumn&&(t=me$3.math.variance(e.dataColumn)),{setValue:{variance:t}}}},e.stderr={public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]},returnDependencies:()=>({stdev:{dependencyType:"stateVariable",variableName:"stdev"},count:{dependencyType:"stateVariable",variableName:"count"}}),definition({dependencyValues:e}){let t=null;return null!==e.stdev&&(t=e.stdev/Math.sqrt(e.count)),{setValue:{stderr:t}}}},e.minimum={public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]},returnDependencies:()=>({dataColumn:{dependencyType:"stateVariable",variableName:"dataColumn"}}),definition({dependencyValues:e}){let t=null;return e.dataColumn&&(t=Math.min(...e.dataColumn)),{setValue:{minimum:t}}}},e.maximum={public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]},returnDependencies:()=>({dataColumn:{dependencyType:"stateVariable",variableName:"dataColumn"}}),definition({dependencyValues:e}){let t=null;return e.dataColumn&&(t=Math.max(...e.dataColumn)),{setValue:{maximum:t}}}},e.median={public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]},returnDependencies:()=>({dataColumn:{dependencyType:"stateVariable",variableName:"dataColumn"}}),definition({dependencyValues:e}){let t=null;return e.dataColumn&&(t=me$3.math.median(e.dataColumn)),{setValue:{median:t}}}},e.quartile1={public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]},returnDependencies:()=>({dataColumn:{dependencyType:"stateVariable",variableName:"dataColumn"}}),definition({dependencyValues:e}){let t=null;return e.dataColumn&&(t=me$3.math.quantileSeq(e.dataColumn,.25)),{setValue:{quartile1:t}}}},e.quartile3={public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]},returnDependencies:()=>({dataColumn:{dependencyType:"stateVariable",variableName:"dataColumn"}}),definition({dependencyValues:e}){let t=null;return e.dataColumn&&(t=me$3.math.quantileSeq(e.dataColumn,.75)),{setValue:{quartile3:t}}}},e.range={public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]},returnDependencies:()=>({minimum:{dependencyType:"stateVariable",variableName:"minimum"},maximum:{dependencyType:"stateVariable",variableName:"maximum"}}),definition({dependencyValues:e}){let t=null;return null!==e.minimum&&(t=e.maximum-e.minimum),{setValue:{range:t}}}},e.summaryStatistics={forRenderer:!0,stateVariablesDeterminingDependencies:["statisticsToDisplay"],returnDependencies({stateValues:e}){let t={displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"}};return e.statisticsToDisplay.includes("mean")&&(t.mean={dependencyType:"stateVariable",variableName:"mean"}),e.statisticsToDisplay.includes("stdev")&&(t.stdev={dependencyType:"stateVariable",variableName:"stdev"}),e.statisticsToDisplay.includes("variance")&&(t.variance={dependencyType:"stateVariable",variableName:"variance"}),e.statisticsToDisplay.includes("stderr")&&(t.stderr={dependencyType:"stateVariable",variableName:"stderr"}),e.statisticsToDisplay.includes("count")&&(t.count={dependencyType:"stateVariable",variableName:"count"}),e.statisticsToDisplay.includes("minimum")&&(t.minimum={dependencyType:"stateVariable",variableName:"minimum"}),e.statisticsToDisplay.includes("quartile1")&&(t.quartile1={dependencyType:"stateVariable",variableName:"quartile1"}),e.statisticsToDisplay.includes("median")&&(t.median={dependencyType:"stateVariable",variableName:"median"}),e.statisticsToDisplay.includes("quartile3")&&(t.quartile3={dependencyType:"stateVariable",variableName:"quartile3"}),e.statisticsToDisplay.includes("maximum")&&(t.maximum={dependencyType:"stateVariable",variableName:"maximum"}),e.statisticsToDisplay.includes("range")&&(t.range={dependencyType:"stateVariable",variableName:"range"}),e.statisticsToDisplay.includes("sum")&&(t.sum={dependencyType:"stateVariable",variableName:"sum"}),t},definition({dependencyValues:e,usedDefault:t}){let n={};return void 0!==e.mean&&(n.mean=roundForDisplay({value:e.mean,dependencyValues:e,usedDefault:t})),void 0!==e.stdev&&(n.stdev=roundForDisplay({value:e.stdev,dependencyValues:e,usedDefault:t})),void 0!==e.variance&&(n.variance=roundForDisplay({value:e.variance,dependencyValues:e,usedDefault:t})),void 0!==e.stderr&&(n.stderr=roundForDisplay({value:e.stderr,dependencyValues:e,usedDefault:t})),void 0!==e.count&&(n.count=roundForDisplay({value:e.count,dependencyValues:e,usedDefault:t})),void 0!==e.minimum&&(n.minimum=roundForDisplay({value:e.minimum,dependencyValues:e,usedDefault:t})),void 0!==e.quartile1&&(n.quartile1=roundForDisplay({value:e.quartile1,dependencyValues:e,usedDefault:t})),void 0!==e.median&&(n.median=roundForDisplay({value:e.median,dependencyValues:e,usedDefault:t})),void 0!==e.quartile3&&(n.quartile3=roundForDisplay({value:e.quartile3,dependencyValues:e,usedDefault:t})),void 0!==e.maximum&&(n.maximum=roundForDisplay({value:e.maximum,dependencyValues:e,usedDefault:t})),void 0!==e.range&&(n.range=roundForDisplay({value:e.range,dependencyValues:e,usedDefault:t})),void 0!==e.sum&&(n.sum=roundForDisplay({value:e.sum,dependencyValues:e,usedDefault:t})),{setValue:{summaryStatistics:n}}}},e}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class Chart extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{changeAxisLimits:this.changeAxisLimits.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="chart";static acceptTarget=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.type={createComponentOfType:"text",createStateVariable:"type",defaultValue:"histogram",toLowerCase:!0,validValues:["histogram","dotplot","frequencytable","box","bar"],forRenderer:!0},e.column={createComponentOfType:"text",createStateVariable:"desiredColumn",defaultValue:null},e.xmin={createComponentOfType:"number",createStateVariable:"xminPrelim",defaultValue:-10},e.xmax={createComponentOfType:"number",createStateVariable:"xmaxPrelim",defaultValue:10},e.ymin={createComponentOfType:"number",createStateVariable:"yminPrelim",defaultValue:-10},e.ymax={createComponentOfType:"number",createStateVariable:"ymaxPrelim",defaultValue:10},e.width={createComponentOfType:"_componentSize",createStateVariable:"width",defaultValue:{size:300,isAbsolute:!0},public:!0,forRenderer:!0},e.height={createComponentOfType:"_componentSize",createStateVariable:"height",defaultValue:{size:300,isAbsolute:!0},public:!0,forRenderer:!0},e.identicalAxisScales={createComponentOfType:"boolean",createStateVariable:"identicalAxisScales",defaultValue:!1,public:!0,forRenderer:!0},e.displayXAxis={createComponentOfType:"boolean",createStateVariable:"displayXAxis",defaultValue:!0,public:!0,forRenderer:!0},e.displayYAxis={createComponentOfType:"boolean",createStateVariable:"displayYAxis",defaultValue:!0,public:!0,forRenderer:!0},e.displayXAxisTickLabels={createComponentOfType:"boolean",createStateVariable:"displayXAxisTickLabels",defaultValue:!0,public:!0,forRenderer:!0},e.displayYAxisTickLabels={createComponentOfType:"boolean",createStateVariable:"displayYAxisTickLabels",defaultValue:!0,public:!0,forRenderer:!0},e.xlabel={createComponentOfType:"text",createStateVariable:"xlabel",defaultValue:"",public:!0,forRenderer:!0},e.xlabelPosition={createComponentOfType:"text",createStateVariable:"xlabelPosition",defaultValue:"right",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["right","left"]},e.ylabel={createComponentOfType:"text",createStateVariable:"ylabel",defaultValue:"",public:!0,forRenderer:!0},e.ylabelPosition={createComponentOfType:"text",createStateVariable:"ylabelPosition",defaultValue:"top",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["top","bottom"]},e.ylabelAlignment={createComponentOfType:"text",createStateVariable:"ylabelAlignment",defaultValue:"left",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["left","right"]},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.dataFrame={forRenderer:!0,returnDependencies:()=>({targetComponent:{dependencyType:"targetComponent",variableNames:["dataFrame"],variablesOptional:!0}}),definition({dependencyValues:e}){console.log("definition of dataFrame",e);let t=null;return e.targetComponent?.stateValues.dataFrame&&(t=e.targetComponent.stateValues.dataFrame),{setValue:{dataFrame:t}}}},e.columnName={public:!0,shadowingInstructions:{createComponentOfType:"text"},additionalStateVariablesDefined:[{variableName:"colInd",forRenderer:!0}],returnDependencies:()=>({desiredColumn:{dependencyType:"stateVariable",variableName:"desiredColumn"},dataFrame:{dependencyType:"stateVariable",variableName:"dataFrame"}}),definition({dependencyValues:e}){let t=null,n=null;return e.dataFrame&&(n=e.dataFrame.columnNames.indexOf(e.desiredColumn),-1!==n?t=e.desiredColumn:n=null),{setValue:{columnName:t,colInd:n}}}},e.xmin={stateVariablesDeterminingDependencies:["identicalAxisScales"],defaultValue:-10,public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies({stateValues:e}){let t={identicalAxisScales:{dependencyType:"stateVariable",variableName:"identicalAxisScales"},xminPrelim:{dependencyType:"stateVariable",variableName:"xminPrelim"}};return e.identicalAxisScales&&(t.xmaxPrelim={dependencyType:"stateVariable",variableName:"xmaxPrelim"},t.yminPrelim={dependencyType:"stateVariable",variableName:"yminPrelim"},t.ymaxPrelim={dependencyType:"stateVariable",variableName:"ymaxPrelim"},t.width={dependencyType:"stateVariable",variableName:"width"},t.height={dependencyType:"stateVariable",variableName:"height"}),t},definition({dependencyValues:e,usedDefault:t}){if(!e.identicalAxisScales)return{setValue:{xmin:e.xminPrelim}};if(!t.xminPrelim)return{setValue:{xmin:e.xminPrelim}};let n=!t.xmaxPrelim,r=!t.yminPrelim,a=!t.ymaxPrelim;if(r&&a){let t=e.width.size/e.height.size,r=(e.ymaxPrelim-e.yminPrelim)*t;return n?{setValue:{xmin:e.xmaxPrelim-r}}:{setValue:{xmin:-r/2}}}return n?{setValue:{xmin:e.xmaxPrelim-20}}:{setValue:{xmin:-10}}},inverseDefinition:async({desiredStateVariableValues:e,stateValues:t})=>await t.fixAxes?{success:!1}:{success:!0,instructions:[{setDependency:"xminPrelim",desiredValue:e.xmin}]}},e.xmax={stateVariablesDeterminingDependencies:["identicalAxisScales"],defaultValue:-10,public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies({stateValues:e}){let t={identicalAxisScales:{dependencyType:"stateVariable",variableName:"identicalAxisScales"},xmaxPrelim:{dependencyType:"stateVariable",variableName:"xmaxPrelim"}};return e.identicalAxisScales&&(t.xminPrelim={dependencyType:"stateVariable",variableName:"xminPrelim"},t.yminPrelim={dependencyType:"stateVariable",variableName:"yminPrelim"},t.ymaxPrelim={dependencyType:"stateVariable",variableName:"ymaxPrelim"},t.width={dependencyType:"stateVariable",variableName:"width"},t.height={dependencyType:"stateVariable",variableName:"height"}),t},definition({dependencyValues:e,usedDefault:t}){if(!e.identicalAxisScales)return{setValue:{xmax:e.xmaxPrelim}};let n=!t.xminPrelim,r=!t.xmaxPrelim,a=!t.yminPrelim,i=!t.ymaxPrelim,s=a&&i,o=n&&r,l=e.xminPrelim;if(s){let t=e.width.size/e.height.size,a=(e.ymaxPrelim-e.yminPrelim)*t;if(o){let t=e.xmaxPrelim-l;return{setValue:{xmax:l+Math.max(t,a)}}}return n?{setValue:{xmax:l+a}}:r?{setValue:{xmax:e.xmaxPrelim}}:{setValue:{xmax:a/2}}}return r?{setValue:{xmax:e.xmaxPrelim}}:n?{setValue:{xmax:l+20}}:{setValue:{xmax:10}}},inverseDefinition:async({desiredStateVariableValues:e,stateValues:t})=>await t.fixAxes?{success:!1}:{success:!0,instructions:[{setDependency:"xmaxPrelim",desiredValue:e.xmax}]}},e.ymin={stateVariablesDeterminingDependencies:["identicalAxisScales"],defaultValue:-10,public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies({stateValues:e}){let t={identicalAxisScales:{dependencyType:"stateVariable",variableName:"identicalAxisScales"},yminPrelim:{dependencyType:"stateVariable",variableName:"yminPrelim"}};return e.identicalAxisScales&&(t.xmaxPrelim={dependencyType:"stateVariable",variableName:"xmaxPrelim"},t.xminPrelim={dependencyType:"stateVariable",variableName:"xminPrelim"},t.ymaxPrelim={dependencyType:"stateVariable",variableName:"ymaxPrelim"},t.width={dependencyType:"stateVariable",variableName:"width"},t.height={dependencyType:"stateVariable",variableName:"height"}),t},definition({dependencyValues:e,usedDefault:t}){if(!e.identicalAxisScales)return{setValue:{ymin:e.yminPrelim}};if(!t.yminPrelim)return{setValue:{ymin:e.yminPrelim}};let n=!t.ymaxPrelim,r=!t.xminPrelim,a=!t.xmaxPrelim,i=r&&a,s=e.width.size/e.height.size;if(i){let t=(e.xmaxPrelim-e.xminPrelim)/s;return n?{setValue:{ymin:e.ymaxPrelim-t}}:{setValue:{ymin:-t/2}}}return n?{setValue:{ymin:e.ymaxPrelim-20/s}}:{setValue:{ymin:-10/s}}},inverseDefinition:async({desiredStateVariableValues:e,stateValues:t})=>await t.fixAxes?{success:!1}:{success:!0,instructions:[{setDependency:"yminPrelim",desiredValue:e.ymin}]}},e.ymax={stateVariablesDeterminingDependencies:["identicalAxisScales"],defaultValue:-10,public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies({stateValues:e}){let t={identicalAxisScales:{dependencyType:"stateVariable",variableName:"identicalAxisScales"},ymaxPrelim:{dependencyType:"stateVariable",variableName:"ymaxPrelim"}};return e.identicalAxisScales&&(t.xminPrelim={dependencyType:"stateVariable",variableName:"xminPrelim"},t.yminPrelim={dependencyType:"stateVariable",variableName:"yminPrelim"},t.xmaxPrelim={dependencyType:"stateVariable",variableName:"xmaxPrelim"},t.width={dependencyType:"stateVariable",variableName:"width"},t.height={dependencyType:"stateVariable",variableName:"height"}),t},definition({dependencyValues:e,usedDefault:t}){if(!e.identicalAxisScales)return{setValue:{ymax:e.ymaxPrelim}};let n=!t.xminPrelim,r=!t.xmaxPrelim,a=!t.yminPrelim,i=!t.ymaxPrelim,s=a&&i,o=n&&r,l=e.yminPrelim,u=e.width.size/e.height.size;if(o){let t=(e.xmaxPrelim-e.xminPrelim)/u;if(s){let n=e.ymaxPrelim-l;return{setValue:{ymax:l+Math.max(n,t)}}}return a?{setValue:{ymax:l+t}}:i?{setValue:{ymax:e.ymaxPrelim}}:{setValue:{ymax:t/2}}}return i?{setValue:{ymax:e.ymaxPrelim}}:a?{setValue:{ymax:l+20/u}}:{setValue:{ymax:10/u}}},inverseDefinition:async({desiredStateVariableValues:e,stateValues:t})=>await t.fixAxes?{success:!1}:{success:!0,instructions:[{setDependency:"ymaxPrelim",desiredValue:e.ymax}]}},e.xscale={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({xmin:{dependencyType:"stateVariable",variableName:"xmin"},xmax:{dependencyType:"stateVariable",variableName:"xmax"}}),definition:({dependencyValues:e})=>({setValue:{xscale:e.xmax-e.xmin}})},e.yscale={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({ymin:{dependencyType:"stateVariable",variableName:"ymin"},ymax:{dependencyType:"stateVariable",variableName:"ymax"}}),definition:({dependencyValues:e})=>({setValue:{yscale:e.ymax-e.ymin}})},e}async changeAxisLimits({xmin:e,xmax:t,ymin:n,ymax:r,actionId:a}){let i=[];return void 0!==e&&i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"xmin",value:e}),void 0!==t&&i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"xmax",value:t}),void 0!==n&&i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"ymin",value:n}),void 0!==r&&i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"ymax",value:r}),await this.coreFunctions.performUpdate({updateInstructions:i,actionId:a,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{xmin:e,xmax:t,ymin:n,ymax:r}}})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class Legend extends GraphicalComponent{static componentType="legend";static createAttributesObject(){let e=super.createAttributesObject();return e.position={createComponentOfType:"text",createStateVariable:"position",defaultValue:"upperright",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft"]},e.displayClosedSwatches={createComponentOfType:"boolean",createStateVariable:"displayClosedSwatches",defaultValue:!1,public:!0},e}static returnChildGroups(){return[{group:"labels",componentTypes:["label"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.graphicalElementNames={returnDependencies:()=>({graphAncestor:{dependencyType:"ancestor",componentType:"graph",variableNames:["graphicalDescendants"]}}),definition:({dependencyValues:e})=>e.graphAncestor?{setValue:{graphicalElementNames:e.graphAncestor.stateValues.graphicalDescendants.map((e=>e.componentName))}}:{setValue:{graphicalElementNames:null}}},e.legendElements={forRenderer:!0,stateVariablesDeterminingDependencies:["graphicalElementNames"],returnDependencies:({stateValues:e})=>{let t={labelChildren:{dependencyType:"child",childGroups:["labels"],variableNames:["value","hasLatex","forObjectComponentName"]},displayClosedSwatches:{dependencyType:"stateVariable",variableName:"displayClosedSwatches"}};if(e.graphicalElementNames){t.numGraphicalElements={dependencyType:"value",value:e.graphicalElementNames.length};for(let[n,r]of e.graphicalElementNames.entries())t[`graphicalElement${n}`]={dependencyType:"multipleStateVariables",componentName:r,variableNames:["selectedStyle","styleNumber","filled"],variablesOptional:!0},t[`graphicalElement${n}AdapterSource`]={dependencyType:"adapterSource",componentName:r},t[`graphicalElement${n}ShadowSource`]={dependencyType:"shadowSource",componentName:r}}return t},definition({dependencyValues:e,componentInfoObjects:t}){let n=[];if(e.numGraphicalElements>0){let r=[],a=[],i=[],s=[];for(let t=0;te.componentName)),l=[],u={};for(let n of e.labelChildren){let c={value:n.stateValues.value,hasLatex:n.stateValues.hasLatex};if(n.stateValues.forObjectComponentName){u[n.stateValues.forObjectComponentName]=c;let l=o.indexOf(n.stateValues.forObjectComponentName);if(-1!==l){let n=s[l];t.isInheritedComponentType({inheritedComponentType:n.componentType,baseComponentType:"point"})?r.push(n.stateValues.styleNumber):e.displayClosedSwatches&&t.allComponentClasses[n.componentType].representsClosedPath?a.push(n.stateValues.styleNumber):"legend"!==n.componentType&&i.push(n.stateValues.styleNumber)}}l.push({labelInfo:c,forObject:n.stateValues.forObjectComponentName})}for(let c of l){let l;if(c.forObject){let e=o.indexOf(c.forObject);-1!==e&&(l=s[e],s.splice(e,1),o.splice(e,1))}else for(let n=0;n({graphAncestor:{dependencyType:"ancestor",componentType:"graph",variableNames:["xmin","xmax","ymin","ymax"]}}),definition:({dependencyValues:e})=>e.graphAncestor?{setValue:{graphLimits:e.graphAncestor.stateValues}}:{setValue:{graphLimits:null}}},e}}class MatchesPattern extends BooleanComponent{static componentType="matchesPattern";static rendererType="boolean";static createAttributesObject(){let e=super.createAttributesObject();return e.pattern={createComponentOfType:"math"},e.allowImplicitIdentities={createComponentOfType:"boolean",createStateVariable:"allowImplicitIdentities",defaultValue:!1,public:!0},e.allowPermutations={createComponentOfType:"boolean",createStateVariable:"allowPermutations",defaultValue:!0,public:!0},e.requireNumericMatches={createComponentOfType:"boolean",createStateVariable:"requireNumericMatches",defaultValue:!1,public:!0},e.requireVariableMatches={createComponentOfType:"boolean",createStateVariable:"requireVariableMatches",defaultValue:!1,public:!0},e.excludeMatches={createComponentOfType:"mathList",createStateVariable:"excludeMatches",defaultValue:[],public:!0},e.matchExpressionWithBlanks={createComponentOfType:"boolean",createStateVariable:"matchExpressionWithBlanks",defaultValue:!1,public:!0},e}static returnSugarInstructions(){let e=[];return e.push({replacementFunction:function({matchedChildren:e,componentInfoObjects:t}){return 0===e.length||1===e.length&&t.componentIsSpecifiedType(e[0],"math")?{success:!1}:{success:!0,newChildren:[{componentType:"math",children:e}]}}}),e}static returnChildGroups(){return[{group:"maths",componentTypes:["math"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return delete e.parsedExpression,delete e.mathChildrenByCode,e.pattern={additionalStateVariablesDefined:["patternVariables"],returnDependencies:()=>({patternAttr:{dependencyType:"attributeComponent",attributeName:"pattern",variableNames:["value"]}}),definition({dependencyValues:e}){let t=[];if(!e.patternAttr)return{setValue:{pattern:"_",patternVariables:t}};let n=e.patternAttr.stateValues.value.variables(),r=703;let a=function e(a){if("_"===a){let e=numberToLetters(r);for(r++;n.includes(e);)e=numberToLetters(r),r++;return t.push(e),e}return Array.isArray(a)?[a[0],...a.slice(1).map(e)]:a}(e.patternAttr.stateValues.value.tree);return{setValue:{pattern:a,patternVariables:t}}}},e.value={additionalStateVariablesDefined:[{variableName:"allPatternMatches"}],public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,returnDependencies:()=>({pattern:{dependencyType:"stateVariable",variableName:"pattern"},patternVariables:{dependencyType:"stateVariable",variableName:"patternVariables"},mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]},allowImplicitIdentities:{dependencyType:"stateVariable",variableName:"allowImplicitIdentities"},allowPermutations:{dependencyType:"stateVariable",variableName:"allowPermutations"},requireNumericMatches:{dependencyType:"stateVariable",variableName:"requireNumericMatches"},requireVariableMatches:{dependencyType:"stateVariable",variableName:"requireVariableMatches"},excludeMatches:{dependencyType:"stateVariable",variableName:"excludeMatches"},matchExpressionWithBlanks:{dependencyType:"stateVariable",variableName:"matchExpressionWithBlanks"}}),definition:function({dependencyValues:e}){if(0===e.mathChildren.length)return{setValue:{value:!1,allPatternMatches:[]}};let t=e.mathChildren[0].stateValues.value;if(t.variables().includes("_")&&!e.matchExpressionWithBlanks)return{setValue:{value:!1,allPatternMatches:[]}};let n={};if(e.requireNumericMatches){let t=e=>null!==me$3.fromAst(e).evaluate_to_constant();e.patternVariables.forEach((e=>n[e]=t))}else if(e.requireVariableMatches){let t=e=>"string"==typeof e;e.patternVariables.forEach((e=>n[e]=t))}else e.patternVariables.forEach((e=>n[e]=!0));let r={variables:n,allow_permutations:e.allowPermutations};e.allowImplicitIdentities&&(r.allow_implicit_identities=e.patternVariables);let a=t.match(e.pattern,r),i=!1,s=[];return a&&(Object.values(a).map((e=>me$3.fromAst(e))).some((t=>e.excludeMatches.some((e=>t.variables().some((t=>e.equalsViaSyntax(me$3.fromAst(t))))))))||(i=!0,s=e.patternVariables.map((e=>me$3.fromAst(a[e]))))),{setValue:{value:i,allPatternMatches:s}}}},e.nMatches={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({allPatternMatches:{dependencyType:"stateVariable",variableName:"allPatternMatches"}}),definition:({dependencyValues:e})=>({setValue:{nMatches:e.allPatternMatches.length},checkForActualChange:{nMatches:!0}})},e.patternMatches={public:!0,shadowingInstructions:{createComponentOfType:"math"},isArray:!0,nDimensions:1,entryPrefixes:["patternMatch"],returnArraySizeDependencies:()=>({nMatches:{dependencyType:"stateVariable",variableName:"nMatches"}}),returnArraySize:({dependencyValues:e})=>[e.nMatches],returnArrayDependenciesByKey:()=>({globalDependencies:{allPatternMatches:{dependencyType:"stateVariable",variableName:"allPatternMatches"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n=0;n({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.displayDigitsAttr){let n=t.displayDigitsAttr,r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!n&&!r){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({}),definition:()=>({setValue:{unordered:!1}})},e.matrixSizePre={returnDependencies:()=>({rowChildren:{dependencyType:"child",childGroups:["rows"],variableNames:["nComponents"]},colChildren:{dependencyType:"child",childGroups:["columns"],variableNames:["nComponents"]},mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["matrixSize"]},nRowsAttr:{dependencyType:"attributeComponent",attributeName:"nRows",variableNames:["value"]},nColumnsAttr:{dependencyType:"attributeComponent",attributeName:"nColumns",variableNames:["value"]}}),definition({dependencyValues:e}){let t=null,n=null;return e.nRowsAttr&&(t=e.nRowsAttr.stateValues.value,Number.isFinite(t)&&t>0||(t=null)),e.nColumnsAttr&&(n=e.nColumnsAttr.stateValues.value,Number.isFinite(n)&&n>0||(n=null)),e.rowChildren.length>0?(null===t&&(t=e.rowChildren.length),null===n&&(n=Math.max(1,...e.rowChildren.map((e=>e.stateValues.nComponents))))):e.colChildren.length>0?(null===n&&(n=e.colChildren.length),null===t&&(t=Math.max(1,...e.colChildren.map((e=>e.stateValues.nComponents))))):1===e.mathChildren.length?(null===t&&(t=e.mathChildren[0].stateValues.matrixSize[0]),null===n&&(n=e.mathChildren[0].stateValues.matrixSize[1])):null===t?null===n?(t=0,n=0):t=1:null===n&&(n=1),{setValue:{matrixSizePre:[t,n]}}}},e.matrixPre={isArray:!0,nDimensions:2,hasEssential:!0,returnArraySizeDependencies:()=>({matrixSizePre:{dependencyType:"stateVariable",variableName:"matrixSizePre"}}),returnArraySize:({dependencyValues:e})=>e.matrixSizePre,returnArrayDependenciesByKey:({arrayKeys:e})=>{let t={};for(let n of e){let[e,r]=n.split(",");t[n]={rowChild:{dependencyType:"child",childGroups:["rows"],childIndices:[e],variableNames:["math"+(Number(r)+1)]},colChild:{dependencyType:"child",childGroups:["columns"],childIndices:[r],variableNames:["math"+(Number(e)+1)]},mathChild:{dependencyType:"child",childGroups:["maths"],childIndices:[0],variableNames:["matrixEntry"+(Number(e)+1)+"_"+(Number(r)+1)]}}}return{globalDependencies:{defaultEntry:{dependencyType:"stateVariable",variableName:"defaultEntry"},rowChildIdentities:{dependencyType:"child",childGroups:["rows"]},colChildIdentities:{dependencyType:"child",childGroups:["columns"]}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n,arraySize:r}){let a={},i={},s=e.rowChildIdentities.length>0,o=e.colChildIdentities.length>0;for(let r of n){let n,[l,u]=r.split(",");n=s?t[r].rowChild[0]?.stateValues["math"+(Number(u)+1)]:o?t[r].colChild[0]?.stateValues["math"+(Number(l)+1)]:t[r].mathChild[0]?.stateValues["matrixEntry"+(Number(l)+1)+"_"+(Number(u)+1)],void 0===n?i[r]={defaultValue:e.defaultEntry}:a[r]=n}return{setValue:{matrixPre:a},useEssentialOrDefaultValue:{matrixPre:i}}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r}){let a=[],i={},s=t.rowChildIdentities.length>0,o=t.colChildIdentities.length>0;for(let t in e.matrixPre){let[l,u]=t.split(",");if(s){let s=n[t].rowChild[0]?.stateValues["math"+(Number(u)+1)];void 0===s?i[t]=e.matrixPre[t]:a.push({setDependency:r[t].rowChild,desiredValue:e.matrixPre[t],childIndex:0,variableIndex:0})}else if(o){let s=n[t].colChild[0]?.stateValues["math"+(Number(l)+1)];void 0===s?i[t]=e.matrixPre[t]:a.push({setDependency:r[t].colChild,desiredValue:e.matrixPre[t],childIndex:0,variableIndex:0})}else{let s=n[t].mathChild[0]?.stateValues["matrixEntry"+(Number(l)+1)+"_"+(Number(u)+1)];void 0===s?i[t]=e.matrixPre[t]:a.push({setDependency:r[t].mathChild,desiredValue:e.matrixPre[t],childIndex:0,variableIndex:0})}}return Object.keys(i).length>0&&a.push({setEssentialValue:"matrixPre",value:i}),{success:!0,instructions:a}}},e.unnormalizedValue={returnDependencies:()=>({matrixPre:{dependencyType:"stateVariable",variableName:"matrixPre"},matrixSizePre:{dependencyType:"stateVariable",variableName:"matrixSizePre"}}),definition({dependencyValues:e}){let t=["tuple"];for(let n=0;ne.tree))]);return{setValue:{unnormalizedValue:me$3.fromAst(["matrix",["tuple",...e.matrixSizePre],t])}}},inverseDefinition({dependencyValues:e,desiredStateVariableValues:t}){let n=t.unnormalizedValue.tree;if(!Array.isArray(n)||"matrix"!==n[0]||n[1]?.[1]!==e.matrixSizePre[0]||n[1]?.[2]!==e.matrixSizePre[1])return{success:!1};let r={};for(let t=0;t({modifyIndirectly:{dependencyType:"stateVariable",variableName:"modifyIndirectly"},fixed:{dependencyType:"stateVariable",variableName:"fixed"}}),definition:({dependencyValues:e})=>({setValue:{canBeModified:e.modifyIndirectly&&!e.fixed}})},e}}class EigenDecomposition extends BaseComponent{static componentType="eigenDecomposition";static rendererType=void 0;static createAttributesObject(){let e=super.createAttributesObject();return e.displayDigits={createComponentOfType:"integer",createStateVariable:"displayDigits",defaultValue:14,public:!0},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.padZeros={createComponentOfType:"boolean",createStateVariable:"padZeros",defaultValue:!1,public:!0},e}static returnChildGroups(){return[{group:"maths",componentTypes:["math"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.decomposition={returnDependencies:()=>({mathChild:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]}}),definition({dependencyValues:e}){if(0===e.mathChild.length)return{setValue:{decomposition:null}};let t=e.mathChild[0].stateValues.value.tree;if(!Array.isArray(t)||"matrix"!==t[0])return{setValue:{decomposition:null}};let n=t[1][1],r=t[1][2];if(!Number.isInteger(n)||r!==n)return{setValue:{decomposition:null}};let a,i=[];for(let e=0;e({decomposition:{dependencyType:"stateVariable",variableName:"decomposition"}}),returnArraySize({dependencyValues:e}){let t;return t=e.decomposition?e.decomposition.values.length:0,[t]},returnArrayDependenciesByKey:()=>({globalDependencies:{decomposition:{dependencyType:"stateVariable",variableName:"decomposition"}}}),arrayDefinitionByKey({globalDependencyValues:e,arraySize:t}){let n=[];for(let r=0;r"eigenvectorX"===e?[]:[["vector",{componentType:"mathList",isAttribute:"xs"}]]},getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("eigenvectorX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("eigenvectors"===t)return 1===e.length?"eigenvector"+e[0]:`eigenvectorX${e[0]}_${e[1]}`;if("eigenvector"===t.slice(0,11)){let n=Number(t.slice(11));if(Number.isInteger(n)&&n>0)return`eigenvectorX${n}_${e[0]}`}return null},entryPrefixes:["eigenvectorX","eigenvector"],returnArraySizeDependencies:()=>({decomposition:{dependencyType:"stateVariable",variableName:"decomposition"}}),returnArraySize({dependencyValues:e}){let t;return t=e.decomposition?e.decomposition.values.length:0,[t,t]},returnArrayDependenciesByKey:()=>({globalDependencies:{decomposition:{dependencyType:"stateVariable",variableName:"decomposition"}}}),arrayDefinitionByKey({globalDependencyValues:e,arraySize:t}){let n={};for(let r=0;rme$3.math.divide(e,i)));for(let e=0;e({mathTextLikeChildren:{dependencyType:"child",childGroups:["mathTextLike"],variableNames:["text","latex"]}}),e.value.definition=function({dependencyValues:e}){if(0===e.mathTextLikeChildren.length)return{useEssentialOrDefaultValue:{value:!0}};let t="";for(let n of e.mathTextLikeChildren)"string"==typeof n?t+=n:void 0!==n.stateValues.latex?t+=n.stateValues.latex:t+=n.stateValues.text;return{setValue:{value:t}}},e.value.inverseDefinition=function({desiredStateVariableValues:e,dependencyValues:t}){let n=t.mathTextLikeChildren.length;return n>1?{success:!1}:1===n?{success:!0,instructions:[{setDependency:"textLikeChildren",desiredValue:e.value,childIndex:0,variableIndex:void 0===t.textLikeChildren[0].stateValues?.latex?0:1}]}:{success:!0,instructions:[{setEssentialValue:"value",value:null===e.value?"":String(e.value)}]}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:({dependencyValues:e})=>({setValue:{text:e.value}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setDependency:"value",desiredValue:e.text}]})},e.latex={isAlias:!0,targetVariableName:"value"},e}}const unitConversions={"":1,px:1,pixel:1,pixels:1,"%":1,em:100,in:96,inch:96,inches:96,pt:1.333333333333,mm:3.7795296,millimeter:3.7795296,millimeters:3.7795296,cm:37.795296,centimeter:37.795296,centimeters:37.795296};class ComponentSize extends InlineComponent{static componentType="_componentSize";static rendererType="text";static primaryStateVariableForDefinition="componentSize";static stateVariableForAttributeValue="componentSize";static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({childrenRegex:/..+/,replacementFunction:function({matchedChildren:e}){let t=e[e.length-1];if("string"==typeof t){let n=/([a-zA-z]+|%)$/,r=t.trim(),a=r.match(n);if(a){let t=a[1];if(t in unitConversions){let n=r.slice(0,a.index),i=e.slice(0,e.length-1);return n.length>0&&i.push(n),{success:!0,newChildren:[{componentType:"number",children:i},t]}}}}return{success:!0,newChildren:[{componentType:"number",children:e}]}}}),e}static returnChildGroups(){return[{group:"strings",componentTypes:["string"]},{group:"numbers",componentTypes:["number"]},{group:"componentSizes",componentTypes:["_componentSize"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.componentSize={public:!0,shadowingInstructions:{createComponentOfType:"_componentSize"},hasEssential:!0,returnDependencies:()=>({componentSizeChild:{dependencyType:"child",childGroups:["componentSizes"],variableNames:["componentSize"]},numberChild:{dependencyType:"child",childGroups:["numbers"],variableNames:["value"]},stringChild:{dependencyType:"child",childGroups:["strings"],variableNames:["value"]},parentDefaultAbsoluteSize:{dependencyType:"parentStateVariable",variableName:"defaultAbsoluteSize"}}),definition({dependencyValues:e}){let t=void 0!==e.parentDefaultAbsoluteSize&&e.parentDefaultAbsoluteSize;if(0===e.stringChild.length)return 0===e.numberChild.length?0===e.componentSizeChild.length?{useEssentialOrDefaultValue:{componentSize:{defaultValue:{size:100,isAbsolute:t}}}}:{setValue:{componentSize:e.componentSizeChild[0].stateValues.componentSize}}:{setValue:{componentSize:{size:e.numberChild[0].stateValues.value,isAbsolute:!0}}};{let t,n;if(e.numberChild.length>0)t=e.numberChild[0].stateValues.value,n=e.stringChild[0].trim();else{let r=e.stringChild[0].trim().match(/^(-?[\d.]+)\s*(.*)$/);if(null===r)return{setValue:{componentSize:null}};t=r[1],n=r[2].trim()}if(t=Number(t),!Number.isFinite(t))return{setValue:{componentSize:null}};let r=!("%"===n||"em"===n),a=unitConversions[n];return void 0===a&&(a=1),{setValue:{componentSize:{size:a*t,isAbsolute:r}}}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){if(0===t.stringChild.length)return 0===t.numberChild.length?0===t.componentSizeChild.length?{success:!0,instructions:[{setEssentialValue:"componentSize",value:e.componentSize}]}:{success:!0,instructions:[{setDependency:"componentSizeChild",desiredValue:e.componentSize,childIndex:0,variableIndex:0}]}:e.componentSize.isAbsolute?{success:!0,instructions:[{setDependency:"numberChild",desiredValue:e.componentSize.size,childIndex:0,variableIndex:0}]}:{success:!1};if(t.numberChild.length>0){let n=t.stringChild[0].trim(),r=!("%"===n||"em"===n);if(e.componentSize.isAbsolute!==r)return{success:!1};let a=unitConversions[n];return void 0===a&&(a=1),{success:!0,instructions:[{setDependency:"numberChild",desiredValue:e.componentSize.size/a,childIndex:0,variableIndex:0}]}}{let t=e.componentSize.size;return e.componentSize.isAbsolute?t+="px":t+="%",{success:!0,instructions:[{setDependency:"stringChild",desiredValue:t,childIndex:0,variableIndex:0}]}}}},e.number={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({componentSize:{dependencyType:"stateVariable",variableName:"componentSize"}}),definition({dependencyValues:e}){let t=null;return e.componentSize&&(t=e.componentSize.size),{setValue:{number:t}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){if(!t.componentSize)return{success:!1};return{success:!0,instructions:[{setDependency:"componentSize",desiredValue:{size:e.number,isAbsolute:t.componentSize.isAbsolute}}]}}},e.math=mathStateVariableFromNumberStateVariable({numberVariableName:"number",mathVariableName:"math",isPublic:!0}),e.isAbsolute={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({componentSize:{dependencyType:"stateVariable",variableName:"componentSize"}}),definition({dependencyValues:e}){let t=null;return e.componentSize&&(t=e.componentSize.isAbsolute),{setValue:{isAbsolute:t}}}},e.text={forRenderer:!0,returnDependencies:()=>({componentSize:{dependencyType:"stateVariable",variableName:"componentSize"}}),definition({dependencyValues:e}){let t="";return e.componentSize&&(t=e.componentSize.size,e.componentSize.isAbsolute?t+="px":t+="%"),{setValue:{text:t}}}},e}static adapters=["number","math"]}class ComponentSizeList extends BaseComponent{static componentType="_componentSizeList";static rendererType="asList";static renderChildren=!0;static stateVariableForAttributeValue="componentSizes";static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e}){let t=[],n=[],r=function(){n.length>0&&(t.push({componentType:"_componentSize",children:n}),n=[])};for(let t of e)if("string"==typeof t){let e=t.split(/\s+/);0===e[0].length&&(r(),e=e.slice(1));for(let[t,a]of e.entries())a.length>0?(n.push(a),t({}),definition:()=>({setValue:{overrideChildHide:!0}})},e.nComponents={public:!0,shadowingInstructions:{createComponentOfType:"number"},additionalStateVariablesDefined:["childIndexByArrayKey"],returnDependencies:()=>({componentSizeListChildren:{dependencyType:"child",childGroups:["componentSizeLists"],variableNames:["nComponents"]},componentSizeAndComponentSizeListChildren:{dependencyType:"child",childGroups:["componentSizes","componentSizeLists"],skipComponentNames:!0}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=0,r=[],a=0;for(let[i,s]of e.componentSizeAndComponentSizeListChildren.entries())if(t.isInheritedComponentType({inheritedComponentType:s.componentType,baseComponentType:"_componentSizeList"})){let t=e.componentSizeListChildren[a];a++;for(let e=0;e({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"}}),returnArraySize:({dependencyValues:e})=>[e.nComponents],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=[],a="1";t.childIndexByArrayKey[r]&&(e=[t.childIndexByArrayKey[r][0]],a=t.childIndexByArrayKey[r][1]+1),n[r]={componentSizeAndComponentSizeListChildren:{dependencyType:"child",childGroups:["componentSizes","componentSizeLists"],variableNames:["componentSize","componentSize"+a],variablesOptional:!0,childIndices:e}}}return{globalDependencies:{childIndexByArrayKey:{dependencyType:"stateVariable",variableName:"childIndexByArrayKey"}},dependenciesByKey:n}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n,componentInfoObjects:r}){let a={};for(let i of n){let n=t[i].componentSizeAndComponentSizeListChildren[0];if(n)if(r.isInheritedComponentType({inheritedComponentType:n.componentType,baseComponentType:"_componentSizeList"})){let t=e.childIndexByArrayKey[i][1]+1;a[i]=n.stateValues["componentSize"+t]}else a[i]=n.stateValues.componentSize}return{setValue:{componentSizes:a}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a,componentInfoObjects:i}){let s=[];for(let t in e.componentSizes){if(!n[t])continue;let a=n[t].componentSizeAndComponentSizeListChildren[0];a&&(i.isInheritedComponentType({inheritedComponentType:a.componentType,baseComponentType:"_componentSizeList"})?s.push({setDependency:r[t].componentSizeAndComponentSizeListChildren,desiredValue:e.componentSizes[t],childIndex:0,variableIndex:1}):s.push({setDependency:r[t].componentSizeAndComponentSizeListChildren,desiredValue:e.componentSizes[t],childIndex:0,variableIndex:0}))}return{success:!0,instructions:s}}},e.nValues={isAlias:!0,targetVariableName:"nComponents"},e.values={isAlias:!0,targetVariableName:"componentSizes"},e}}var ComponentSize$1=Object.freeze({__proto__:null,ComponentSize:ComponentSize,ComponentSizeList:ComponentSizeList});const componentTypeArray=[...Object.values(Aliases),...Object.values(MMeMen),...Object.values(MdMdnMrow),...Object.values(BooleanOperators),...Object.values(BooleanOperatorsOfMath),...Object.values(MathOperators),...Object.values(FunctionOperators),...Object.values(TextOperatorsOfMath),...Object.values(Extrema$1),...Object.values(ParagraphMarkup),...Object.values(SingleCharacterComponents),...Object.values(Sectioning),...Object.values(Lists),...Object.values(DynamicalSystems),...Object.values(Chemistry),...Object.values(FeedbackDefinitions$1),...Object.values(StyleDefinitions$1),...Object.values(SideBySide$1),...Object.values(ComponentWithSelectableType$1),...Object.values(Indexing),...Object.values(Divisions),...Object.values(Verbatim),...Object.values(Paginator$1),...Object.values(MatrixInput$1),Document,Text,TextList$1,TextList,P$2,BooleanComponent,BooleanList,MathComponent,MathList,TupleList,NumberList,NumberListFromString,Copy,Extract,Collect,Ref,Point,Coords,Line,LineSegment,Ray,Polyline,Polygon,Triangle,Rectangle,Circle,Parabola,Curve,BezierControls,ControlVectors,Vector,Angle,Answer,Award,When,MathInput,Textinput,BooleanInput,Choiceinput,Choice,NumberComponent,Integer,Graph$1,Variables,Variable,Function$1,Interval,Template,Option$1,Sequence,Slider,Spreadsheet,DiscreteSimulationResultList,DiscreteSimulationResultPolyline,Cell,Row,Column,CellBlock,Tabular,Table,Figure,Markers,Panel,Map$1,Sources,Pegboard,Constraints,ConstrainToGrid,ConstrainToGraph,AttractToGrid,ConstrainTo,AttractTo,ConstraintUnion,AttractToConstraint,Intersection,ConstrainToAngles,AttractToAngles,ConditionalContent,AsList,VariantControl,TextListFromString,SelectFromSequence,Select,Group,AnimateFromSequence,Evaluate,SelectRandomNumbers,SampleRandomNumbers,Substitute,PeriodicSet,Image,Video,Embed,Hint,Solution,IntComma,Pluralize,Feedback,CollaborateGroups,CollaborateGroupSetup,ConsiderAsResponses,Case,Lorem,UpdateValue,CallAction,triggerSet,FunctionIterates,Module,CustomAttribute,Setup,Footnote,Caption,Endpoint,Sort,Shuffle,SolveEquations,SolutionContainer,SubsetOfRealsInput,SubsetOfReals,Split,BestFitLine,RegionBetweenCurveXAxis,RegionHalfPlane,CodeEditor,CodeViewer,RenderDoenetML,HasSameFactoring,DataFrame,SummaryStatistics,Chart,Legend,Label,MatchesPattern,Matrix,EigenDecomposition,Latex,BaseComponent,InlineComponent,BlockComponent,GraphicalComponent,ConstraintComponent,Input,CompositeComponent,PointListComponent,IntervalListComponent,LineListComponent,VectorListComponent,AngleListComponent,BooleanOperator,BooleanBaseOperatorOfMath,MathOperator,MathOperatorOneInput,FunctionOperator,...Object.values(ComponentSize$1),SectioningComponent,InlineRenderInlineChildren,TextOrInline,SingleCharacter];function allComponentClasses(){const e={},t=new Set;for(let n of componentTypeArray){let r=n.componentType;if(void 0===r)throw Error("Cannot create component as componentType is undefined for class "+n);let a=r.toLowerCase();if(t.has(a))throw Error("component type "+r+" defined in two classes");e[r]=n,t.add(a)}return e}function componentTypesCreatingVariants(){const e={},t=new Set;for(let n of componentTypeArray)if(n.createsVariants){let r=n.componentType;if(void 0===r)throw Error("Cannot create component as componentType is undefined for class "+n);let a=r.toLowerCase();if(t.has(a))throw Error("component type "+r+" defined in two classes");e[r]=n,t.add(a)}return e}function createComponentInfoObjects(){let e=allComponentClasses(),t=componentTypesCreatingVariants(),n={};for(let t in e)n[t.toLowerCase()]=t;let r={};for(let t in e)Object.defineProperty(r,t,{get:function(){let n=e[t].returnStateVariableInfo();return delete r[t],r[t]=n}.bind(this),configurable:!0});let a={};for(let t in e)Object.defineProperty(a,t,{get:function(){let n=e[t].returnStateVariableInfo({onlyPublic:!0});return delete a[t],a[t]=n}.bind(this),configurable:!0});function i({inheritedComponentType:t,baseComponentType:n}){if(t===n)return!0;if("string"===t)return"_base"===n||"_inline"===n;if("string"===n)return!1;let r=e[n];return!!r&&r.isPrototypeOf(e[t])}let s=(e,t)=>i({inheritedComponentType:e,baseComponentType:t});return{allComponentClasses:e,componentTypesCreatingVariants:t,componentTypeLowerCaseMapping:n,isInheritedComponentType:i,isCompositeComponent:function({componentType:t,includeNonStandard:n=!0}){let r=e[t];return!!r&&(i({inheritedComponentType:t,baseComponentType:"_composite"})&&(n||!r.treatAsComponentForRecursiveReplacements))},stateVariableInfo:r,publicStateVariableInfo:a,componentIsSpecifiedType:(e,t)=>s(e.componentType,t)||s(e.attributes?.createComponentOfType?.primitive,t)}}function promisifyRequest(e){return new Promise(((t,n)=>{e.oncomplete=e.onsuccess=()=>t(e.result),e.onabort=e.onerror=()=>n(e.error)}))}function createStore(e,t){const n=indexedDB.open(e);n.onupgradeneeded=()=>n.result.createObjectStore(t);const r=promisifyRequest(n);return(e,n)=>r.then((r=>n(r.transaction(t,e).objectStore(t))))}let defaultGetStoreFunc;function defaultGetStore(){return defaultGetStoreFunc||(defaultGetStoreFunc=createStore("keyval-store","keyval")),defaultGetStoreFunc}function set(e,t,n=defaultGetStore()){return n("readwrite",(n=>(n.put(t,e),promisifyRequest(n.transaction))))}const toastType=Object.freeze({ERROR:{timeout:-1,background:"rgba(193, 41, 46, 1)",gradientEnd:"rgba()"},ALERT:{timeout:-1,background:"rgba(255, 230, 0, 1)"},ACTION:{timeout:-1,background:"rgba()"},INFO:{timeout:3e3,background:"rgba(26, 90, 153,1)"},SUCCESS:{timeout:3e3,background:"rgba(41, 193, 67, 1)"},CONFIRMATION:{timeout:5e3,background:"rgba(26,90,153,1)"}});var axios$3={exports:{}},axios$2={exports:{}},bind$2=function(e,t){return function(){for(var n=new Array(arguments.length),r=0;r0;)s[i=r[a]]||(t[i]=e[i],s[i]=!0);e=Object.getPrototypeOf(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t}function endsWith(e,t,n){e=String(e),(void 0===n||n>e.length)&&(n=e.length),n-=t.length;var r=e.indexOf(t,n);return-1!==r&&r===n}function toArray(e){if(!e)return null;var t=e.length;if(isUndefined(t))return null;for(var n=new Array(t);t-- >0;)n[t]=e[t];return n}var isTypedArray=(TypedArray="undefined"!=typeof Uint8Array&&Object.getPrototypeOf(Uint8Array),function(e){return TypedArray&&e instanceof TypedArray}),TypedArray,utils$9={isArray:isArray$1,isArrayBuffer:isArrayBuffer,isBuffer:isBuffer$1,isFormData:isFormData,isArrayBufferView:isArrayBufferView,isString:isString,isNumber:isNumber,isObject:isObject,isPlainObject:isPlainObject,isUndefined:isUndefined,isDate:isDate,isFile:isFile,isBlob:isBlob,isFunction:isFunction,isStream:isStream,isURLSearchParams:isURLSearchParams,isStandardBrowserEnv:isStandardBrowserEnv,forEach:forEach,merge:merge,extend:extend,trim:trim,stripBOM:stripBOM,inherits:inherits,toFlatObject:toFlatObject,kindOf:kindOf,kindOfTest:kindOfTest,endsWith:endsWith,toArray:toArray,isTypedArray:isTypedArray,isFileList:isFileList},utils$8=utils$9;function encode(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}var buildURL$1=function(e,t,n){if(!t)return e;var r;if(n)r=n(t);else if(utils$8.isURLSearchParams(t))r=t.toString();else{var a=[];utils$8.forEach(t,(function(e,t){null!=e&&(utils$8.isArray(e)?t+="[]":e=[e],utils$8.forEach(e,(function(e){utils$8.isDate(e)?e=e.toISOString():utils$8.isObject(e)&&(e=JSON.stringify(e)),a.push(encode(t)+"="+encode(e))})))})),r=a.join("&")}if(r){var i=e.indexOf("#");-1!==i&&(e=e.slice(0,i)),e+=(-1===e.indexOf("?")?"?":"&")+r}return e},utils$7=utils$9;function InterceptorManager$1(){this.handlers=[]}InterceptorManager$1.prototype.use=function(e,t,n){return this.handlers.push({fulfilled:e,rejected:t,synchronous:!!n&&n.synchronous,runWhen:n?n.runWhen:null}),this.handlers.length-1},InterceptorManager$1.prototype.eject=function(e){this.handlers[e]&&(this.handlers[e]=null)},InterceptorManager$1.prototype.forEach=function(e){utils$7.forEach(this.handlers,(function(t){null!==t&&e(t)}))};var InterceptorManager_1=InterceptorManager$1,utils$6=utils$9,normalizeHeaderName$1=function(e,t){utils$6.forEach(e,(function(n,r){r!==t&&r.toUpperCase()===t.toUpperCase()&&(e[t]=n,delete e[r])}))},AxiosError_1,hasRequiredAxiosError;function requireAxiosError(){if(hasRequiredAxiosError)return AxiosError_1;hasRequiredAxiosError=1;var e=utils$9;function t(e,t,n,r,a){Error.call(this),this.message=e,this.name="AxiosError",t&&(this.code=t),n&&(this.config=n),r&&(this.request=r),a&&(this.response=a)}e.inherits(t,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:this.config,code:this.code,status:this.response&&this.response.status?this.response.status:null}}});var n=t.prototype,r={};return["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED"].forEach((function(e){r[e]={value:e}})),Object.defineProperties(t,r),Object.defineProperty(n,"isAxiosError",{value:!0}),t.from=function(r,a,i,s,o,l){var u=Object.create(n);return e.toFlatObject(r,u,(function(e){return e!==Error.prototype})),t.call(u,r.message,a,i,s,o),u.name=r.name,l&&Object.assign(u,l),u},AxiosError_1=t}var transitional={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},lookup=[],revLookup=[],Arr="undefined"!=typeof Uint8Array?Uint8Array:Array,inited=!1;function init(){inited=!0;for(var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",t=0,n=e.length;t0)throw new Error("Invalid string. Length must be a multiple of 4");i="="===e[o-2]?2:"="===e[o-1]?1:0,s=new Arr(3*o/4-i),r=i>0?o-4:o;var l=0;for(t=0,n=0;t>16&255,s[l++]=a>>8&255,s[l++]=255&a;return 2===i?(a=revLookup[e.charCodeAt(t)]<<2|revLookup[e.charCodeAt(t+1)]>>4,s[l++]=255&a):1===i&&(a=revLookup[e.charCodeAt(t)]<<10|revLookup[e.charCodeAt(t+1)]<<4|revLookup[e.charCodeAt(t+2)]>>2,s[l++]=a>>8&255,s[l++]=255&a),s}function tripletToBase64(e){return lookup[e>>18&63]+lookup[e>>12&63]+lookup[e>>6&63]+lookup[63&e]}function encodeChunk(e,t,n){for(var r,a=[],i=t;il?l:o+s));return 1===r?(t=e[n-1],a+=lookup[t>>2],a+=lookup[t<<4&63],a+="=="):2===r&&(t=(e[n-2]<<8)+e[n-1],a+=lookup[t>>10],a+=lookup[t>>4&63],a+=lookup[t<<2&63],a+="="),i.push(a),i.join("")}function read(e,t,n,r,a){var i,s,o=8*a-r-1,l=(1<>1,c=-7,p=n?a-1:0,d=n?-1:1,m=e[t+p];for(p+=d,i=m&(1<<-c)-1,m>>=-c,c+=o;c>0;i=256*i+e[t+p],p+=d,c-=8);for(s=i&(1<<-c)-1,i>>=-c,c+=r;c>0;s=256*s+e[t+p],p+=d,c-=8);if(0===i)i=1-u;else{if(i===l)return s?NaN:1/0*(m?-1:1);s+=Math.pow(2,r),i-=u}return(m?-1:1)*s*Math.pow(2,i-r)}function write(e,t,n,r,a,i){var s,o,l,u=8*i-a-1,c=(1<>1,d=23===a?Math.pow(2,-24)-Math.pow(2,-77):0,m=r?0:i-1,h=r?1:-1,f=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(o=isNaN(t)?1:0,s=c):(s=Math.floor(Math.log(t)/Math.LN2),t*(l=Math.pow(2,-s))<1&&(s--,l*=2),(t+=s+p>=1?d/l:d*Math.pow(2,1-p))*l>=2&&(s++,l/=2),s+p>=c?(o=0,s=c):s+p>=1?(o=(t*l-1)*Math.pow(2,a),s+=p):(o=t*Math.pow(2,p-1)*Math.pow(2,a),s=0));a>=8;e[n+m]=255&o,m+=h,o/=256,a-=8);for(s=s<0;e[n+m]=255&s,m+=h,s/=256,u-=8);e[n+m-h]|=128*f}var toString={}.toString,isArray=Array.isArray||function(e){return"[object Array]"==toString.call(e)},INSPECT_MAX_BYTES=50;function kMaxLength(){return Buffer.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function createBuffer(e,t){if(kMaxLength()=kMaxLength())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+kMaxLength().toString(16)+" bytes");return 0|e}function internalIsBuffer(e){return!(null==e||!e._isBuffer)}function byteLength(e,t){if(internalIsBuffer(e))return e.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e.byteLength;"string"!=typeof e&&(e=""+e);var n=e.length;if(0===n)return 0;for(var r=!1;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":case void 0:return utf8ToBytes(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return base64ToBytes(e).length;default:if(r)return utf8ToBytes(e).length;t=(""+t).toLowerCase(),r=!0}}function slowToString(e,t,n){var r=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if((n>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return hexSlice(this,t,n);case"utf8":case"utf-8":return utf8Slice(this,t,n);case"ascii":return asciiSlice(this,t,n);case"latin1":case"binary":return latin1Slice(this,t,n);case"base64":return base64Slice(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return utf16leSlice(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}function swap(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}function bidirectionalIndexOf(e,t,n,r,a){if(0===e.length)return-1;if("string"==typeof n?(r=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),n=+n,isNaN(n)&&(n=a?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(a)return-1;n=e.length-1}else if(n<0){if(!a)return-1;n=0}if("string"==typeof t&&(t=Buffer.from(t,r)),internalIsBuffer(t))return 0===t.length?-1:arrayIndexOf(e,t,n,r,a);if("number"==typeof t)return t&=255,Buffer.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?a?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):arrayIndexOf(e,[t],n,r,a);throw new TypeError("val must be string, number or Buffer")}function arrayIndexOf(e,t,n,r,a){var i,s=1,o=e.length,l=t.length;if(void 0!==r&&("ucs2"===(r=String(r).toLowerCase())||"ucs-2"===r||"utf16le"===r||"utf-16le"===r)){if(e.length<2||t.length<2)return-1;s=2,o/=2,l/=2,n/=2}function u(e,t){return 1===s?e[t]:e.readUInt16BE(t*s)}if(a){var c=-1;for(i=n;io&&(n=o-l),i=n;i>=0;i--){for(var p=!0,d=0;da&&(r=a):r=a;var i=t.length;if(i%2!=0)throw new TypeError("Invalid hex string");r>i/2&&(r=i/2);for(var s=0;s239?4:u>223?3:u>191?2:1;if(a+p<=n)switch(p){case 1:u<128&&(c=u);break;case 2:128==(192&(i=e[a+1]))&&(l=(31&u)<<6|63&i)>127&&(c=l);break;case 3:i=e[a+1],s=e[a+2],128==(192&i)&&128==(192&s)&&(l=(15&u)<<12|(63&i)<<6|63&s)>2047&&(l<55296||l>57343)&&(c=l);break;case 4:i=e[a+1],s=e[a+2],o=e[a+3],128==(192&i)&&128==(192&s)&&128==(192&o)&&(l=(15&u)<<18|(63&i)<<12|(63&s)<<6|63&o)>65535&&l<1114112&&(c=l)}null===c?(c=65533,p=1):c>65535&&(c-=65536,r.push(c>>>10&1023|55296),c=56320|1023&c),r.push(c),a+=p}return decodeCodePointsArray(r)}Buffer.TYPED_ARRAY_SUPPORT=void 0===global$1.TYPED_ARRAY_SUPPORT||global$1.TYPED_ARRAY_SUPPORT,kMaxLength(),Buffer.poolSize=8192,Buffer._augment=function(e){return e.__proto__=Buffer.prototype,e},Buffer.from=function(e,t,n){return from(null,e,t,n)},Buffer.TYPED_ARRAY_SUPPORT&&(Buffer.prototype.__proto__=Uint8Array.prototype,Buffer.__proto__=Uint8Array),Buffer.alloc=function(e,t,n){return alloc(null,e,t,n)},Buffer.allocUnsafe=function(e){return allocUnsafe(null,e)},Buffer.allocUnsafeSlow=function(e){return allocUnsafe(null,e)},Buffer.isBuffer=isBuffer,Buffer.compare=function(e,t){if(!internalIsBuffer(e)||!internalIsBuffer(t))throw new TypeError("Arguments must be Buffers");if(e===t)return 0;for(var n=e.length,r=t.length,a=0,i=Math.min(n,r);a0&&(e=this.toString("hex",0,t).match(/.{2}/g).join(" "),this.length>t&&(e+=" ... ")),""},Buffer.prototype.compare=function(e,t,n,r,a){if(!internalIsBuffer(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===n&&(n=e?e.length:0),void 0===r&&(r=0),void 0===a&&(a=this.length),t<0||n>e.length||r<0||a>this.length)throw new RangeError("out of range index");if(r>=a&&t>=n)return 0;if(r>=a)return-1;if(t>=n)return 1;if(this===e)return 0;for(var i=(a>>>=0)-(r>>>=0),s=(n>>>=0)-(t>>>=0),o=Math.min(i,s),l=this.slice(r,a),u=e.slice(t,n),c=0;ca)&&(n=a),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");for(var i=!1;;)switch(r){case"hex":return hexWrite(this,e,t,n);case"utf8":case"utf-8":return utf8Write(this,e,t,n);case"ascii":return asciiWrite(this,e,t,n);case"latin1":case"binary":return latin1Write(this,e,t,n);case"base64":return base64Write(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ucs2Write(this,e,t,n);default:if(i)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),i=!0}},Buffer.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var MAX_ARGUMENTS_LENGTH=4096;function decodeCodePointsArray(e){var t=e.length;if(t<=MAX_ARGUMENTS_LENGTH)return String.fromCharCode.apply(String,e);for(var n="",r=0;rr)&&(n=r);for(var a="",i=t;in)throw new RangeError("Trying to access beyond buffer length")}function checkInt(e,t,n,r,a,i){if(!internalIsBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>a||te.length)throw new RangeError("Index out of range")}function objectWriteUInt16(e,t,n,r){t<0&&(t=65535+t+1);for(var a=0,i=Math.min(e.length-n,2);a>>8*(r?a:1-a)}function objectWriteUInt32(e,t,n,r){t<0&&(t=4294967295+t+1);for(var a=0,i=Math.min(e.length-n,4);a>>8*(r?a:3-a)&255}function checkIEEE754(e,t,n,r,a,i){if(n+r>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function writeFloat(e,t,n,r,a){return a||checkIEEE754(e,t,n,4),write(e,t,n,r,23,4),n+4}function writeDouble(e,t,n,r,a){return a||checkIEEE754(e,t,n,8),write(e,t,n,r,52,8),n+8}Buffer.prototype.slice=function(e,t){var n,r=this.length;if((e=~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),(t=void 0===t?r:~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),t0&&(a*=256);)r+=this[e+--t]*a;return r},Buffer.prototype.readUInt8=function(e,t){return t||checkOffset(e,1,this.length),this[e]},Buffer.prototype.readUInt16LE=function(e,t){return t||checkOffset(e,2,this.length),this[e]|this[e+1]<<8},Buffer.prototype.readUInt16BE=function(e,t){return t||checkOffset(e,2,this.length),this[e]<<8|this[e+1]},Buffer.prototype.readUInt32LE=function(e,t){return t||checkOffset(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},Buffer.prototype.readUInt32BE=function(e,t){return t||checkOffset(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},Buffer.prototype.readIntLE=function(e,t,n){e|=0,t|=0,n||checkOffset(e,t,this.length);for(var r=this[e],a=1,i=0;++i=(a*=128)&&(r-=Math.pow(2,8*t)),r},Buffer.prototype.readIntBE=function(e,t,n){e|=0,t|=0,n||checkOffset(e,t,this.length);for(var r=t,a=1,i=this[e+--r];r>0&&(a*=256);)i+=this[e+--r]*a;return i>=(a*=128)&&(i-=Math.pow(2,8*t)),i},Buffer.prototype.readInt8=function(e,t){return t||checkOffset(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},Buffer.prototype.readInt16LE=function(e,t){t||checkOffset(e,2,this.length);var n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},Buffer.prototype.readInt16BE=function(e,t){t||checkOffset(e,2,this.length);var n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},Buffer.prototype.readInt32LE=function(e,t){return t||checkOffset(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},Buffer.prototype.readInt32BE=function(e,t){return t||checkOffset(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},Buffer.prototype.readFloatLE=function(e,t){return t||checkOffset(e,4,this.length),read(this,e,!0,23,4)},Buffer.prototype.readFloatBE=function(e,t){return t||checkOffset(e,4,this.length),read(this,e,!1,23,4)},Buffer.prototype.readDoubleLE=function(e,t){return t||checkOffset(e,8,this.length),read(this,e,!0,52,8)},Buffer.prototype.readDoubleBE=function(e,t){return t||checkOffset(e,8,this.length),read(this,e,!1,52,8)},Buffer.prototype.writeUIntLE=function(e,t,n,r){(e=+e,t|=0,n|=0,r)||checkInt(this,e,t,n,Math.pow(2,8*n)-1,0);var a=1,i=0;for(this[t]=255&e;++i=0&&(i*=256);)this[t+a]=e/i&255;return t+n},Buffer.prototype.writeUInt8=function(e,t,n){return e=+e,t|=0,n||checkInt(this,e,t,1,255,0),Buffer.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},Buffer.prototype.writeUInt16LE=function(e,t,n){return e=+e,t|=0,n||checkInt(this,e,t,2,65535,0),Buffer.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):objectWriteUInt16(this,e,t,!0),t+2},Buffer.prototype.writeUInt16BE=function(e,t,n){return e=+e,t|=0,n||checkInt(this,e,t,2,65535,0),Buffer.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):objectWriteUInt16(this,e,t,!1),t+2},Buffer.prototype.writeUInt32LE=function(e,t,n){return e=+e,t|=0,n||checkInt(this,e,t,4,4294967295,0),Buffer.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e):objectWriteUInt32(this,e,t,!0),t+4},Buffer.prototype.writeUInt32BE=function(e,t,n){return e=+e,t|=0,n||checkInt(this,e,t,4,4294967295,0),Buffer.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):objectWriteUInt32(this,e,t,!1),t+4},Buffer.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t|=0,!r){var a=Math.pow(2,8*n-1);checkInt(this,e,t,n,a-1,-a)}var i=0,s=1,o=0;for(this[t]=255&e;++i>0)-o&255;return t+n},Buffer.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t|=0,!r){var a=Math.pow(2,8*n-1);checkInt(this,e,t,n,a-1,-a)}var i=n-1,s=1,o=0;for(this[t+i]=255&e;--i>=0&&(s*=256);)e<0&&0===o&&0!==this[t+i+1]&&(o=1),this[t+i]=(e/s>>0)-o&255;return t+n},Buffer.prototype.writeInt8=function(e,t,n){return e=+e,t|=0,n||checkInt(this,e,t,1,127,-128),Buffer.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=255&e,t+1},Buffer.prototype.writeInt16LE=function(e,t,n){return e=+e,t|=0,n||checkInt(this,e,t,2,32767,-32768),Buffer.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):objectWriteUInt16(this,e,t,!0),t+2},Buffer.prototype.writeInt16BE=function(e,t,n){return e=+e,t|=0,n||checkInt(this,e,t,2,32767,-32768),Buffer.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):objectWriteUInt16(this,e,t,!1),t+2},Buffer.prototype.writeInt32LE=function(e,t,n){return e=+e,t|=0,n||checkInt(this,e,t,4,2147483647,-2147483648),Buffer.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):objectWriteUInt32(this,e,t,!0),t+4},Buffer.prototype.writeInt32BE=function(e,t,n){return e=+e,t|=0,n||checkInt(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),Buffer.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):objectWriteUInt32(this,e,t,!1),t+4},Buffer.prototype.writeFloatLE=function(e,t,n){return writeFloat(this,e,t,!0,n)},Buffer.prototype.writeFloatBE=function(e,t,n){return writeFloat(this,e,t,!1,n)},Buffer.prototype.writeDoubleLE=function(e,t,n){return writeDouble(this,e,t,!0,n)},Buffer.prototype.writeDoubleBE=function(e,t,n){return writeDouble(this,e,t,!1,n)},Buffer.prototype.copy=function(e,t,n,r){if(n||(n=0),r||0===r||(r=this.length),t>=e.length&&(t=e.length),t||(t=0),r>0&&r=this.length)throw new RangeError("sourceStart out of bounds");if(r<0)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),e.length-t=0;--a)e[a+t]=this[a+n];else if(i<1e3||!Buffer.TYPED_ARRAY_SUPPORT)for(a=0;a>>=0,n=void 0===n?this.length:n>>>0,e||(e=0),"number"==typeof e)for(i=t;i55295&&n<57344){if(!a){if(n>56319){(t-=3)>-1&&i.push(239,191,189);continue}if(s+1===r){(t-=3)>-1&&i.push(239,191,189);continue}a=n;continue}if(n<56320){(t-=3)>-1&&i.push(239,191,189),a=n;continue}n=65536+(a-55296<<10|n-56320)}else a&&(t-=3)>-1&&i.push(239,191,189);if(a=null,n<128){if((t-=1)<0)break;i.push(n)}else if(n<2048){if((t-=2)<0)break;i.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;i.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;i.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return i}function asciiToBytes(e){for(var t=[],n=0;n>8,a=n%256,i.push(a),i.push(r);return i}function base64ToBytes(e){return toByteArray(base64clean(e))}function blitBuffer(e,t,n,r){for(var a=0;a=t.length||a>=e.length);++a)t[a+n]=e[a];return a}function isnan(e){return e!=e}function isBuffer(e){return null!=e&&(!!e._isBuffer||isFastBuffer(e)||isSlowBuffer(e))}function isFastBuffer(e){return!!e.constructor&&"function"==typeof e.constructor.isBuffer&&e.constructor.isBuffer(e)}function isSlowBuffer(e){return"function"==typeof e.readFloatLE&&"function"==typeof e.slice&&isFastBuffer(e.slice(0,0))}function requireToFormData(){if(hasRequiredToFormData)return toFormData_1;hasRequiredToFormData=1;var e=utils$9;return toFormData_1=function(t,n){n=n||new FormData;var r=[];function a(t){return null===t?"":e.isDate(t)?t.toISOString():e.isArrayBuffer(t)||e.isTypedArray(t)?"function"==typeof Blob?new Blob([t]):Buffer.from(t):t}return function t(i,s){if(e.isPlainObject(i)||e.isArray(i)){if(-1!==r.indexOf(i))throw Error("Circular reference detected in "+s);r.push(i),e.forEach(i,(function(r,i){if(!e.isUndefined(r)){var o,l=s?s+"."+i:i;if(r&&!s&&"object"==typeof r)if(e.endsWith(i,"{}"))r=JSON.stringify(r);else if(e.endsWith(i,"[]")&&(o=e.toArray(r)))return void o.forEach((function(t){!e.isUndefined(t)&&n.append(l,a(t))}));t(r,l)}})),r.pop()}else n.append(s,a(i))}(t),n},toFormData_1}function requireSettle(){if(hasRequiredSettle)return settle;hasRequiredSettle=1;var e=requireAxiosError();return settle=function(t,n,r){var a=r.config.validateStatus;r.status&&a&&!a(r.status)?n(new e("Request failed with status code "+r.status,[e.ERR_BAD_REQUEST,e.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r)):t(r)},settle}function requireCookies(){if(hasRequiredCookies)return cookies;hasRequiredCookies=1;var e=utils$9;return cookies=e.isStandardBrowserEnv()?{write:function(t,n,r,a,i,s){var o=[];o.push(t+"="+encodeURIComponent(n)),e.isNumber(r)&&o.push("expires="+new Date(r).toGMTString()),e.isString(a)&&o.push("path="+a),e.isString(i)&&o.push("domain="+i),!0===s&&o.push("secure"),document.cookie=o.join("; ")},read:function(e){var t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove:function(e){this.write(e,"",Date.now()-864e5)}}:{write:function(){},read:function(){return null},remove:function(){}}}var isAbsoluteURL$1=function(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)},combineURLs$1=function(e,t){return t?e.replace(/\/+$/,"")+"/"+t.replace(/^\/+/,""):e},isAbsoluteURL=isAbsoluteURL$1,combineURLs=combineURLs$1,buildFullPath$1=function(e,t){return e&&!isAbsoluteURL(t)?combineURLs(e,t):t},parseHeaders,hasRequiredParseHeaders,isURLSameOrigin,hasRequiredIsURLSameOrigin,CanceledError_1,hasRequiredCanceledError,parseProtocol,hasRequiredParseProtocol,xhr,hasRequiredXhr,_null,hasRequired_null;function requireParseHeaders(){if(hasRequiredParseHeaders)return parseHeaders;hasRequiredParseHeaders=1;var e=utils$9,t=["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"];return parseHeaders=function(n){var r,a,i,s={};return n?(e.forEach(n.split("\n"),(function(n){if(i=n.indexOf(":"),r=e.trim(n.substr(0,i)).toLowerCase(),a=e.trim(n.substr(i+1)),r){if(s[r]&&t.indexOf(r)>=0)return;s[r]="set-cookie"===r?(s[r]?s[r]:[]).concat([a]):s[r]?s[r]+", "+a:a}})),s):s},parseHeaders}function requireIsURLSameOrigin(){if(hasRequiredIsURLSameOrigin)return isURLSameOrigin;hasRequiredIsURLSameOrigin=1;var e=utils$9;return isURLSameOrigin=e.isStandardBrowserEnv()?function(){var t,n=/(msie|trident)/i.test(navigator.userAgent),r=document.createElement("a");function a(e){var t=e;return n&&(r.setAttribute("href",t),t=r.href),r.setAttribute("href",t),{href:r.href,protocol:r.protocol?r.protocol.replace(/:$/,""):"",host:r.host,search:r.search?r.search.replace(/^\?/,""):"",hash:r.hash?r.hash.replace(/^#/,""):"",hostname:r.hostname,port:r.port,pathname:"/"===r.pathname.charAt(0)?r.pathname:"/"+r.pathname}}return t=a(window.location.href),function(n){var r=e.isString(n)?a(n):n;return r.protocol===t.protocol&&r.host===t.host}}():function(){return!0}}function requireCanceledError(){if(hasRequiredCanceledError)return CanceledError_1;hasRequiredCanceledError=1;var e=requireAxiosError();function t(t){e.call(this,null==t?"canceled":t,e.ERR_CANCELED),this.name="CanceledError"}return utils$9.inherits(t,e,{__CANCEL__:!0}),CanceledError_1=t}function requireParseProtocol(){return hasRequiredParseProtocol?parseProtocol:(hasRequiredParseProtocol=1,parseProtocol=function(e){var t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""})}function requireXhr(){if(hasRequiredXhr)return xhr;hasRequiredXhr=1;var e=utils$9,t=requireSettle(),n=requireCookies(),r=buildURL$1,a=buildFullPath$1,i=requireParseHeaders(),s=requireIsURLSameOrigin(),o=transitional,l=requireAxiosError(),u=requireCanceledError(),c=requireParseProtocol();return xhr=function(p){return new Promise((function(d,m){var h,f=p.data,y=p.headers,g=p.responseType;function b(){p.cancelToken&&p.cancelToken.unsubscribe(h),p.signal&&p.signal.removeEventListener("abort",h)}e.isFormData(f)&&e.isStandardBrowserEnv()&&delete y["Content-Type"];var v=new XMLHttpRequest;if(p.auth){var N=p.auth.username||"",T=p.auth.password?unescape(encodeURIComponent(p.auth.password)):"";y.Authorization="Basic "+btoa(N+":"+T)}var C=a(p.baseURL,p.url);function A(){if(v){var e="getAllResponseHeaders"in v?i(v.getAllResponseHeaders()):null,n={data:g&&"text"!==g&&"json"!==g?v.response:v.responseText,status:v.status,statusText:v.statusText,headers:e,config:p,request:v};t((function(e){d(e),b()}),(function(e){m(e),b()}),n),v=null}}if(v.open(p.method.toUpperCase(),r(C,p.params,p.paramsSerializer),!0),v.timeout=p.timeout,"onloadend"in v?v.onloadend=A:v.onreadystatechange=function(){v&&4===v.readyState&&(0!==v.status||v.responseURL&&0===v.responseURL.indexOf("file:"))&&setTimeout(A)},v.onabort=function(){v&&(m(new l("Request aborted",l.ECONNABORTED,p,v)),v=null)},v.onerror=function(){m(new l("Network Error",l.ERR_NETWORK,p,v,v)),v=null},v.ontimeout=function(){var e=p.timeout?"timeout of "+p.timeout+"ms exceeded":"timeout exceeded",t=p.transitional||o;p.timeoutErrorMessage&&(e=p.timeoutErrorMessage),m(new l(e,t.clarifyTimeoutError?l.ETIMEDOUT:l.ECONNABORTED,p,v)),v=null},e.isStandardBrowserEnv()){var V=(p.withCredentials||s(C))&&p.xsrfCookieName?n.read(p.xsrfCookieName):void 0;V&&(y[p.xsrfHeaderName]=V)}"setRequestHeader"in v&&e.forEach(y,(function(e,t){void 0===f&&"content-type"===t.toLowerCase()?delete y[t]:v.setRequestHeader(t,e)})),e.isUndefined(p.withCredentials)||(v.withCredentials=!!p.withCredentials),g&&"json"!==g&&(v.responseType=p.responseType),"function"==typeof p.onDownloadProgress&&v.addEventListener("progress",p.onDownloadProgress),"function"==typeof p.onUploadProgress&&v.upload&&v.upload.addEventListener("progress",p.onUploadProgress),(p.cancelToken||p.signal)&&(h=function(e){v&&(m(!e||e&&e.type?new u:e),v.abort(),v=null)},p.cancelToken&&p.cancelToken.subscribe(h),p.signal&&(p.signal.aborted?h():p.signal.addEventListener("abort",h))),f||(f=null);var x=c(C);x&&-1===["http","https","file"].indexOf(x)?m(new l("Unsupported protocol "+x+":",l.ERR_BAD_REQUEST,p)):v.send(f)}))},xhr}function require_null(){return hasRequired_null?_null:(hasRequired_null=1,_null=null)}var utils$5=utils$9,normalizeHeaderName=normalizeHeaderName$1,AxiosError$1=requireAxiosError(),transitionalDefaults=transitional,toFormData=requireToFormData(),DEFAULT_CONTENT_TYPE={"Content-Type":"application/x-www-form-urlencoded"};function setContentTypeIfUnset(e,t){!utils$5.isUndefined(e)&&utils$5.isUndefined(e["Content-Type"])&&(e["Content-Type"]=t)}function getDefaultAdapter(){var e;return("undefined"!=typeof XMLHttpRequest||void 0!==browser$1&&"[object process]"===Object.prototype.toString.call(browser$1))&&(e=requireXhr()),e}function stringifySafely(e,t,n){if(utils$5.isString(e))try{return(t||JSON.parse)(e),utils$5.trim(e)}catch(e){if("SyntaxError"!==e.name)throw e}return(n||JSON.stringify)(e)}var defaults$3={transitional:transitionalDefaults,adapter:getDefaultAdapter(),transformRequest:[function(e,t){if(normalizeHeaderName(t,"Accept"),normalizeHeaderName(t,"Content-Type"),utils$5.isFormData(e)||utils$5.isArrayBuffer(e)||utils$5.isBuffer(e)||utils$5.isStream(e)||utils$5.isFile(e)||utils$5.isBlob(e))return e;if(utils$5.isArrayBufferView(e))return e.buffer;if(utils$5.isURLSearchParams(e))return setContentTypeIfUnset(t,"application/x-www-form-urlencoded;charset=utf-8"),e.toString();var n,r=utils$5.isObject(e),a=t&&t["Content-Type"];if((n=utils$5.isFileList(e))||r&&"multipart/form-data"===a){var i=this.env&&this.env.FormData;return toFormData(n?{"files[]":e}:e,i&&new i)}return r||"application/json"===a?(setContentTypeIfUnset(t,"application/json"),stringifySafely(e)):e}],transformResponse:[function(e){var t=this.transitional||defaults$3.transitional,n=t&&t.silentJSONParsing,r=t&&t.forcedJSONParsing,a=!n&&"json"===this.responseType;if(a||r&&utils$5.isString(e)&&e.length)try{return JSON.parse(e)}catch(e){if(a){if("SyntaxError"===e.name)throw AxiosError$1.from(e,AxiosError$1.ERR_BAD_RESPONSE,this,null,this.response);throw e}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:require_null()},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*"}}};utils$5.forEach(["delete","get","head"],(function(e){defaults$3.headers[e]={}})),utils$5.forEach(["post","put","patch"],(function(e){defaults$3.headers[e]=utils$5.merge(DEFAULT_CONTENT_TYPE)}));var defaults_1=defaults$3,utils$4=utils$9,defaults$2=defaults_1,transformData$1=function(e,t,n){var r=this||defaults$2;return utils$4.forEach(n,(function(n){e=n.call(r,e,t)})),e},isCancel$1,hasRequiredIsCancel;function requireIsCancel(){return hasRequiredIsCancel?isCancel$1:(hasRequiredIsCancel=1,isCancel$1=function(e){return!(!e||!e.__CANCEL__)})}var utils$3=utils$9,transformData=transformData$1,isCancel=requireIsCancel(),defaults$1=defaults_1,CanceledError=requireCanceledError();function throwIfCancellationRequested(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new CanceledError}var dispatchRequest$1=function(e){return throwIfCancellationRequested(e),e.headers=e.headers||{},e.data=transformData.call(e,e.data,e.headers,e.transformRequest),e.headers=utils$3.merge(e.headers.common||{},e.headers[e.method]||{},e.headers),utils$3.forEach(["delete","get","head","post","put","patch","common"],(function(t){delete e.headers[t]})),(e.adapter||defaults$1.adapter)(e).then((function(t){return throwIfCancellationRequested(e),t.data=transformData.call(e,t.data,t.headers,e.transformResponse),t}),(function(t){return isCancel(t)||(throwIfCancellationRequested(e),t&&t.response&&(t.response.data=transformData.call(e,t.response.data,t.response.headers,e.transformResponse))),Promise.reject(t)}))},utils$2=utils$9,mergeConfig$2=function(e,t){t=t||{};var n={};function r(e,t){return utils$2.isPlainObject(e)&&utils$2.isPlainObject(t)?utils$2.merge(e,t):utils$2.isPlainObject(t)?utils$2.merge({},t):utils$2.isArray(t)?t.slice():t}function a(n){return utils$2.isUndefined(t[n])?utils$2.isUndefined(e[n])?void 0:r(void 0,e[n]):r(e[n],t[n])}function i(e){if(!utils$2.isUndefined(t[e]))return r(void 0,t[e])}function s(n){return utils$2.isUndefined(t[n])?utils$2.isUndefined(e[n])?void 0:r(void 0,e[n]):r(void 0,t[n])}function o(n){return n in t?r(e[n],t[n]):n in e?r(void 0,e[n]):void 0}var l={url:i,method:i,data:i,baseURL:s,transformRequest:s,transformResponse:s,paramsSerializer:s,timeout:s,timeoutMessage:s,withCredentials:s,adapter:s,responseType:s,xsrfCookieName:s,xsrfHeaderName:s,onUploadProgress:s,onDownloadProgress:s,decompress:s,maxContentLength:s,maxBodyLength:s,beforeRedirect:s,transport:s,httpAgent:s,httpsAgent:s,cancelToken:s,socketPath:s,responseEncoding:s,validateStatus:o};return utils$2.forEach(Object.keys(e).concat(Object.keys(t)),(function(e){var t=l[e]||a,r=t(e);utils$2.isUndefined(r)&&t!==o||(n[e]=r)})),n},data,hasRequiredData;function requireData(){return hasRequiredData?data:(hasRequiredData=1,data={version:"0.27.2"})}var VERSION=requireData().version,AxiosError=requireAxiosError(),validators$1={};["object","boolean","number","function","string","symbol"].forEach((function(e,t){validators$1[e]=function(n){return typeof n===e||"a"+(t<1?"n ":" ")+e}}));var deprecatedWarnings={};function assertOptions(e,t,n){if("object"!=typeof e)throw new AxiosError("options must be an object",AxiosError.ERR_BAD_OPTION_VALUE);for(var r=Object.keys(e),a=r.length;a-- >0;){var i=r[a],s=t[i];if(s){var o=e[i],l=void 0===o||s(o,i,e);if(!0!==l)throw new AxiosError("option "+i+" must be "+l,AxiosError.ERR_BAD_OPTION_VALUE)}else if(!0!==n)throw new AxiosError("Unknown option "+i,AxiosError.ERR_BAD_OPTION)}}validators$1.transitional=function(e,t,n){function r(e,t){return"[Axios v"+VERSION+"] Transitional option '"+e+"'"+t+(n?". "+n:"")}return function(n,a,i){if(!1===e)throw new AxiosError(r(a," has been removed"+(t?" in "+t:"")),AxiosError.ERR_DEPRECATED);return t&&!deprecatedWarnings[a]&&(deprecatedWarnings[a]=!0,console.warn(r(a," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(n,a,i)}};var validator$1={assertOptions:assertOptions,validators:validators$1},utils$1=utils$9,buildURL=buildURL$1,InterceptorManager=InterceptorManager_1,dispatchRequest=dispatchRequest$1,mergeConfig$1=mergeConfig$2,buildFullPath=buildFullPath$1,validator=validator$1,validators=validator.validators;function Axios$1(e){this.defaults=e,this.interceptors={request:new InterceptorManager,response:new InterceptorManager}}Axios$1.prototype.request=function(e,t){"string"==typeof e?(t=t||{}).url=e:t=e||{},(t=mergeConfig$1(this.defaults,t)).method?t.method=t.method.toLowerCase():this.defaults.method?t.method=this.defaults.method.toLowerCase():t.method="get";var n=t.transitional;void 0!==n&&validator.assertOptions(n,{silentJSONParsing:validators.transitional(validators.boolean),forcedJSONParsing:validators.transitional(validators.boolean),clarifyTimeoutError:validators.transitional(validators.boolean)},!1);var r=[],a=!0;this.interceptors.request.forEach((function(e){"function"==typeof e.runWhen&&!1===e.runWhen(t)||(a=a&&e.synchronous,r.unshift(e.fulfilled,e.rejected))}));var i,s=[];if(this.interceptors.response.forEach((function(e){s.push(e.fulfilled,e.rejected)})),!a){var o=[dispatchRequest,void 0];for(Array.prototype.unshift.apply(o,r),o=o.concat(s),i=Promise.resolve(t);o.length;)i=i.then(o.shift(),o.shift());return i}for(var l=t;r.length;){var u=r.shift(),c=r.shift();try{l=u(l)}catch(e){c(e);break}}try{i=dispatchRequest(l)}catch(e){return Promise.reject(e)}for(;s.length;)i=i.then(s.shift(),s.shift());return i},Axios$1.prototype.getUri=function(e){e=mergeConfig$1(this.defaults,e);var t=buildFullPath(e.baseURL,e.url);return buildURL(t,e.params,e.paramsSerializer)},utils$1.forEach(["delete","get","head","options"],(function(e){Axios$1.prototype[e]=function(t,n){return this.request(mergeConfig$1(n||{},{method:e,url:t,data:(n||{}).data}))}})),utils$1.forEach(["post","put","patch"],(function(e){function t(t){return function(n,r,a){return this.request(mergeConfig$1(a||{},{method:e,headers:t?{"Content-Type":"multipart/form-data"}:{},url:n,data:r}))}}Axios$1.prototype[e]=t(),Axios$1.prototype[e+"Form"]=t(!0)}));var Axios_1=Axios$1,CancelToken_1,hasRequiredCancelToken,spread,hasRequiredSpread,isAxiosError,hasRequiredIsAxiosError;function requireCancelToken(){if(hasRequiredCancelToken)return CancelToken_1;hasRequiredCancelToken=1;var e=requireCanceledError();function t(t){if("function"!=typeof t)throw new TypeError("executor must be a function.");var n;this.promise=new Promise((function(e){n=e}));var r=this;this.promise.then((function(e){if(r._listeners){var t,n=r._listeners.length;for(t=0;t{this.initializedPromiseResolves.forEach((e=>e(!0))),this.initialized=!0},this.getInitializedPromise=()=>this.initialized?Promise.resolve(!0):new Promise(((e,t)=>{this.initializedPromiseResolves.push(e)})),cidFromText(e).then((t=>expandDoenetMLsToFullSerializedComponents({cids:[t],doenetMLs:[e],componentInfoObjects:this.componentInfoObjects,flags:this.flags}))).then(this.finishCoreConstruction).catch((e=>{postMessage({messageType:"inErrorState",coreId:this.coreId,args:{errMsg:e.message}})}))}async finishCoreConstruction({cids:e,fullSerializedComponents:t}){this.cid=e[0];let n=t[0];addDocumentIfItsMissing(n),createComponentNames({serializedComponents:n,componentInfoObjects:this.componentInfoObjects}),this.componentIndexArray=extractComponentNamesAndIndices(n);let{rangePieces:r}=extractRangeIndexPieces({componentArray:this.componentIndexArray});this.componentRangePieces=r,postMessage({messageType:"componentRangePieces",coreId:this.coreId,args:{componentRangePieces:this.componentRangePieces}}),this.documentName=n[0].componentName,n[0].doenetAttributes.cid=this.cid,this._components={},this.componentsToRender={},this.componentsWithChangedChildrenToRender=new Set([]),this.stateVariableChangeTriggers={},this.actionsChangedToActions={},this.originsOfActionsChangedToActions={},this.essentialValuesSavedInDefinition={},this.saveStateToDBTimerId=null,this.rendererState={__componentNeedingUpdateValue:null},this.rendererVariablesByComponentType={};for(let e in this.componentInfoObjects.allComponentClasses)Object.defineProperty(this.rendererVariablesByComponentType,e,{get:function(){let t=this.componentInfoObjects.allComponentClasses[e].returnStateVariableInfo({onlyForRenderer:!0}).stateVariableDescriptions;return delete this.rendererVariablesByComponentType[e],this.rendererVariablesByComponentType[e]=t}.bind(this),configurable:!0});this.processQueue=[],this.stopProcessingRequests=!1,this.dependencies=new DependencyHandler({_components:this._components,componentInfoObjects:this.componentInfoObjects,core:this}),this.unmatchedChildren={};let a=getNumberOfVariants({serializedComponent:n[0],componentInfoObjects:this.componentInfoObjects}).numberOfVariants;if(!this.requestedVariant){if(this.requestedVariantIndex=((this.requestedVariantIndex-1)%a+a)%a+1,n[0].variants.uniqueVariants){let e=this.componentInfoObjects.allComponentClasses[n[0].componentType].getUniqueVariant({serializedComponent:n[0],variantIndex:this.requestedVariantIndex,componentInfoObjects:this.componentInfoObjects});e.success&&(this.requestedVariant=e.desiredVariant)}this.requestedVariant||(this.requestedVariant={index:this.requestedVariantIndex})}this.parameterStack.parameters.variant=this.requestedVariant,n[0].variants.desiredVariant=this.parameterStack.parameters.variant,await this.addComponents({serializedComponents:n,initialAdd:!0}),this.updateInfo.componentsToUpdateRenderers.clear(),await this.document.stateValues.itemCreditAchieved,this.canonicalGeneratedVariantString=JSON.stringify(await this.document.stateValues.generatedVariantInfo,serializedComponentsReplacer),this.canonicalItemVariantStrings=(await this.document.stateValues.itemVariantInfo).map((e=>JSON.stringify(e,serializedComponentsReplacer))),this.coreInfo={generatedVariantString:this.canonicalGeneratedVariantString,allPossibleVariants:deepClone(await this.document.sharedParameters.allPossibleVariants),rendererTypesInDocument:deepClone(this.rendererTypesInDocument),documentToRender:this.documentRendererInstructions},this.coreInfoString=JSON.stringify(this.coreInfo,serializedComponentsReplacer),this.messageViewerReady(),this.resolveInitialized()}async onDocumentFirstVisible(){this.requestRecordEvent({verb:"experienced",object:{componentName:this.document.componentName,componentType:"document"}});let e=function(t){let n=t.stateValues.scoredDescendants;if(Array.isArray(n))for(let t of n){if("answer"===t.componentType)return!0;if(e(t))return!0}return!1};await this.document.stateValues.scoredDescendants,e(this.document)||this.saveSubmissions({pageCreditAchieved:await this.document.stateValues.creditAchieved,suppressToast:!0}),setTimeout(this.sendVisibilityChangedEvents.bind(this),this.visibilityInfo.saveDelay)}async messageViewerReady(){postMessage({messageType:"initializeRenderers",coreId:this.coreId,args:{coreInfo:this.coreInfo}}),postMessage({messageType:"coreCreated",coreId:this.coreId})}async postUpdateRenderers(e,t=!1){postMessage({messageType:"updateRenderers",coreId:this.coreId,args:e,init:t})}async addComponents({serializedComponents:e,parentName:t,indexOfDefiningChildren:n,initialAdd:r=!1,assignNamesOffset:a}){let i;Array.isArray(e)||(e=[e]);let s=[],o="";if(!r){if(i=this._components[t],!i)return console.warn(`Cannot add children to parent ${t} as ${t} does not exist`),[];s=[{componentName:t,componentClass:i.constructor},...i.ancestors],this.parameterStack.push(i.sharedParameters,!1),this.nTimesAddedComponents?this.nTimesAddedComponents++:this.nTimesAddedComponents=1,o=`addComponents${this.nTimesAddedComponents}`}let l=await this.createIsolatedComponents({serializedComponents:e,ancestors:s,createNameContext:o});if(r||this.parameterStack.pop(),!0!==l.success)throw Error(l.message);const u=l.components;let c={},p={};if(u.forEach((e=>p[e.componentName]=e)),r){if(1!==u.length)throw Error("Initial components need to be an array of just one component.");if(this.document=u[0],await this.expandAllComposites(this.document),await this.expandAllComposites(this.document,!0),this.updateInfo.stateVariablesToEvaluate){let e=this.updateInfo.stateVariablesToEvaluate;this.updateInfo.stateVariablesToEvaluate=[];for(let{componentName:t,stateVariable:n}of e){let e=this._components[t];e&&e.state[n]&&await this.getStateVariableValue({component:e,stateVariable:n})}}await this.replacementChangesFromCompositesToUpdate();let e=await this.initializeRenderedComponentInstruction(this.document);if(this.updateInfo.compositesToUpdateReplacements.size>0){await this.replacementChangesFromCompositesToUpdate();let e=[...this.updateInfo.componentsToUpdateRenderers];this.updateInfo.componentsToUpdateRenderers.clear(),await this.updateRendererInstructions({componentNamesToUpdate:e})}this.documentRendererInstructions=e.componentToRender;let t=[{instructionType:"updateRendererStates",rendererStatesToUpdate:e.rendererStatesToUpdate}];if(this.postUpdateRenderers({updateInstructions:t},!0),e.rendererStatesToForceUpdate.length>0){let t=[{instructionType:"updateRendererStates",rendererStatesToUpdate:e.rendererStatesToForceUpdate}];this.postUpdateRenderers({updateInstructions:t})}await this.processStateVariableTriggers()}else{if(void 0===i)throw Error("Must specify parent when adding components.");void 0===n&&(n=i.definingChildren.length);let e=await this.addChildrenAndRecurseToShadows({parent:i,indexOfDefiningChildren:n,newChildren:u,assignNamesOffset:a});if(!e.success)throw Error("Couldn't satisfy child logic result. Need informative error message");if(Object.assign(p,e.addedComponents),Object.assign(c,e.deletedComponents),await this.expandAllComposites(this.document),await this.expandAllComposites(this.document,!0),this.updateInfo.stateVariablesToEvaluate){let e=this.updateInfo.stateVariablesToEvaluate;this.updateInfo.stateVariablesToEvaluate=[];for(let{componentName:t,stateVariable:n}of e){let e=this._components[t];e&&e.state[n]&&await this.getStateVariableValue({component:e,stateVariable:n})}}if(await this.replacementChangesFromCompositesToUpdate(),await this.updateRendererInstructions({componentNamesToUpdate:await this.componentAndRenderedDescendants(i)}),this.updateInfo.compositesToUpdateReplacements.size>0){await this.replacementChangesFromCompositesToUpdate();let e=[...this.updateInfo.componentsToUpdateRenderers];this.updateInfo.componentsToUpdateRenderers.clear(),await this.updateRendererInstructions({componentNamesToUpdate:e})}await this.processStateVariableTriggers()}return u}async updateRendererInstructions({componentNamesToUpdate:e,sourceOfUpdate:t={},actionId:n}){let r=[],a=[],i=[],s={},o=this.componentsWithChangedChildrenToRender;this.componentsWithChangedChildrenToRender=new Set([]);for(let t of o)if(t in this.componentsToRender){let n=[],a=this._components[t],l=[];if(a&&a.constructor.renderChildren){a.childrenMatched||await this.deriveChildResultsFromDefiningChildren({parent:a,expandComposites:!0,forceExpandComposites:!0}),l=await this.returnActiveChildrenIndicesToRender(a);let e=0;for(let[t,r]of a.activeChildren.entries())l.includes(t)&&(r.rendererType?(n.push(`nameType:${r.componentName};${r.componentType}`),e++):"string"==typeof r?(n.push(`string${e}:${r}`),e++):"number"==typeof r&&(n.push(`number${e}:${r.toString()}`),e++))}let u=this.componentsToRender[t].children,c=[];for(let[e,t]of u.entries())t.componentName?c.push(`nameType:${t.componentName};${t.componentType}`):"string"==typeof t?c.push(`string${e}:${t}`):"number"==typeof t&&c.push(`number${e}:${t.toString()}`);if(n.length!==c.length||n.some(((e,t)=>e!==c[t]))){for(let e of u)if(e.componentName){let t=this.deleteFromComponentsToRender({componentName:e.componentName,recurseToChildren:!0,componentsWithChangedChildrenToRenderInProgress:o});r.push(...t)}let n=[];if(l.length>0)for(let[e,t]of a.activeChildren.entries())if(l.includes(e))if(t.rendererType){let e=await this.initializeRenderedComponentInstruction(t,o);n.push(e.componentToRender),i.push(...e.rendererStatesToUpdate)}else"string"==typeof t?n.push(t):"number"==typeof t&&n.push(t.toString());this.componentsToRender[t].children=n,s[t]=n,o.delete(t),e.includes(t)||e.push(t)}}for(let t of e)if(t in this.componentsToRender){let e=this._components[t];if(e){let n={};for(let t in e.state)if(e.state[t].forRenderer){let r=removeFunctionsMathExpressionClass(await e.state[t].value);n[t]=r}let r={componentName:t,stateValues:n,rendererType:e.rendererType};this.rendererState[t]||(this.rendererState[t]={}),this.rendererState[t].stateValues=n,s[t]&&(r.childrenInstructions=s[t],this.rendererState[t].childrenInstructions=s[t]),i.push(r)}}if(i.length>0){let e={instructionType:"updateRendererStates",rendererStatesToUpdate:i,sourceOfUpdate:t};a.splice(0,0,e)}this.postUpdateRenderers({updateInstructions:a,actionId:n})}async initializeRenderedComponentInstruction(e,t=new Set([])){if(void 0===e.rendererType)return;e.childrenMatched||await this.deriveChildResultsFromDefiningChildren({parent:e,expandComposites:!0});let n=[],r=[],a={},i={},s=!1;for(let t in e.state)e.state[t].forRenderer&&(a[t]=removeFunctionsMathExpressionClass(await e.state[t].value),e.state[t].alwaysUpdateRenderer&&(s=!0));s&&(i=a);let o=e.componentName,l=[];if(e.constructor.renderChildren){let a=await this.returnActiveChildrenIndicesToRender(e);for(let[i,s]of e.activeChildren.entries())if(a.includes(i))if(s.rendererType){let e=await this.initializeRenderedComponentInstruction(s,t);l.push(e.componentToRender),n.push(...e.rendererStatesToUpdate),r.push(...e.rendererStatesToForceUpdate)}else"string"==typeof s?l.push(s):"number"==typeof s&&l.push(s.toString())}n.push({componentName:o,stateValues:a,childrenInstructions:l}),Object.keys(i).length>0&&r.push({componentName:o,stateValues:i}),this.rendererState[o]={stateValues:a,childrenInstructions:l},t.delete(o);let u={};for(let t in e.actions)u[t]={actionName:t,componentName:e.componentName};for(let t in e.externalActions){let n=await e.externalActions[t];n&&(u[t]={actionName:t,componentName:n.componentName})}let c={componentName:o,effectiveName:e.componentOrAdaptedName,componentType:e.componentType,rendererType:e.rendererType,actions:u};return this.componentsToRender[o]={children:l},{componentToRender:c,rendererStatesToUpdate:n,rendererStatesToForceUpdate:r}}deleteFromComponentsToRender({componentName:e,recurseToChildren:t=!0,componentsWithChangedChildrenToRenderInProgress:n}){let r=[e];if(t){let a=this.componentsToRender[e];if(a)for(let e of a.children){let a=this.deleteFromComponentsToRender({componentName:e.componentName,recurseToChildren:t,componentsWithChangedChildrenToRenderInProgress:n});r.push(...a)}}return delete this.componentsToRender[e],n.delete(e),r}async processStateVariableTriggers(){for(let e in this.stateVariableChangeTriggers){let t=this._components[e];for(let n in this.stateVariableChangeTriggers[e]){let r=this.stateVariableChangeTriggers[e][n],a=await t.state[n].value;if(a!==r.previousValue){let i=r.previousValue;r.previousValue=a,t.actions[r.action]&&await this.performAction({componentName:e,actionName:r.action,args:{stateValues:{[n]:a},previousValues:{[n]:i}}})}}}}async expandAllComposites(e,t=!1){let n=await this.expandCompositesOfDescendants(e,t),r=!0;for(;r;){r=!1;for(let e of n){let n=this._components[e],a=!1;for(let e of n.unexpandedCompositesNotReady){let n=this._components[e];if(n.state.readyToExpandWhenResolved.isResolved){a=!0;break}if((await this.dependencies.resolveItem({componentName:n.componentName,type:"stateVariable",stateVariable:"readyToExpandWhenResolved",force:t,recurseUpstream:!0})).success){a=!0;break}}if(a){let n=this._components[e];await this.deriveChildResultsFromDefiningChildren({parent:n,expandComposites:!0,forceExpandComposites:t}),r=!0}}}}async expandCompositesOfDescendants(e,t=!1){let n=[];e.childrenMatched||(await this.deriveChildResultsFromDefiningChildren({parent:e,expandComposites:!0,forceExpandComposites:t}),e.unexpandedCompositesNotReady.length>0?n.push(e.componentName):await this.dependencies.resolveBlockersFromChangedActiveChildren(e,t));for(let r in e.attributes){let a=e.attributes[r].component;if(a){let e=await this.expandCompositesOfDescendants(a,t);n.push(...e)}}for(let r in e.allChildren){let a=e.allChildren[r].component;if("object"!=typeof a)continue;let i=await this.expandCompositesOfDescendants(a,t);n.push(...i)}return n}async componentAndRenderedDescendants(e){if(!e?.componentName)return[];let t=[e.componentName];if(e.constructor.renderChildren){e.childrenMatched||await this.deriveChildResultsFromDefiningChildren({parent:e,expandComposites:!0});for(let n of e.activeChildren)t.push(...await this.componentAndRenderedDescendants(n))}return t}async createIsolatedComponents({serializedComponents:e,ancestors:t,shadow:n=!1,createNameContext:r=""}){let a="/";if(t.length>0){let e=t[0].componentName,n=this.components[e];a=n.attributes.newNamespace?.primitive?n.componentName+"/":getNamespaceFromName(n.componentName)}return{success:!0,components:(await this.createIsolatedComponentsSub({serializedComponents:e,ancestors:t,shadow:n,namespaceForUnamed:a,createNameContext:r})).components}}async createIsolatedComponentsSub({serializedComponents:e,ancestors:t,shadow:n=!1,createNameContext:r="",namespaceForUnamed:a="/",componentsReplacementOf:i}){let s=[];for(let[o,l]of e.entries()){if("object"!=typeof l){s.push(l);continue}if(!0===l.createdComponent){let e=this._components[l.componentName];s.push(e),this.setAncestors(e,t);continue}let e=this.componentInfoObjects.allComponentClasses[l.componentType];if(void 0===e)throw Error("Cannot create component of type "+l.componentType);l.doenetAttributes||(l.doenetAttributes={});let u=l.componentName;if(void 0===u){let e=t[0].componentName+"|"+r+"|";l.uniqueIdentifier?e+=l.uniqueIdentifier:e+=o,u=createUniqueName(l.componentType.toLowerCase(),e),u=a+u}let c=(await this.createChildrenThenComponent({serializedComponent:l,componentName:u,ancestors:t,componentClass:e,shadow:n,namespaceForUnamed:a,componentsReplacementOf:i})).newComponent;s.push(c)}return{components:s}}async createChildrenThenComponent({serializedComponent:e,componentName:t,ancestors:n,componentClass:r,shadow:a=!1,namespaceForUnamed:i="/",componentsReplacementOf:s}){let o=e.children,l=[],u=[],c=[{componentName:t,componentClass:r},...n],p=this.parameterStack.parameters;this.parameterStack.push();let d=this.parameterStack.parameters;if(r.descendantCompositesMustHaveAReplacement&&!a?(d.compositesMustHaveAReplacement=!0,d.compositesDefaultReplacementType=r.descendantCompositesDefaultReplacementType):(!1===r.descendantCompositesMustHaveAReplacement||a)&&(d.compositesMustHaveAReplacement=!1),r.modifySharedParameters&&r.modifySharedParameters({sharedParameters:d,serializedComponent:e}),e.doenetAttributes.pushSharedParameters)for(let t of e.doenetAttributes.pushSharedParameters){let e=t.parameterName;d[e]=e in d?[...d[e]]:[],d[e].push(t.value)}if(e.doenetAttributes.addToSharedParameters)for(let t of e.doenetAttributes.addToSharedParameters){let e=t.parameterName;d[e]=e in d?Object.assign({},d[e]):{},d[e][t.key]=t.value}if(void 0!==o){if(r.preprocessSerializedChildren&&r.preprocessSerializedChildren({serializedChildren:o,attributes:e.attributes,componentName:t}),r.setUpVariant){let t=gatherVariantComponents({serializedComponents:o,componentInfoObjects:this.componentInfoObjects});r.setUpVariant({serializedComponent:e,sharedParameters:d,descendantVariantComponents:t})}if(r.keepChildrenSerialized){let t=new Set([]),n=r.keepChildrenSerialized({serializedComponent:e,componentInfoObjects:this.componentInfoObjects});for(let e of n){if(t.has(Number(e)))throw Error("Invalid instructions to keep children serialized from "+r.componentType+": child repeated");t.add(Number(e)),u.push(o[e])}let s=[];for(let[e,n]of o.entries())t.has(e)||s.push(n);if(s.length>0){l=(await this.createIsolatedComponentsSub({serializedComponents:s,ancestors:c,shadow:a,namespaceForUnamed:i})).components}}else{l=(await this.createIsolatedComponentsSub({serializedComponents:o,ancestors:c,shadow:a,namespaceForUnamed:i})).components}}let m={};if(e.attributes)for(let t in e.attributes){if(e.attributes[t].component){let n=await this.createIsolatedComponentsSub({serializedComponents:[e.attributes[t].component],ancestors:c,shadow:a,namespaceForUnamed:i,createNameContext:`attribute|${t}`});m[t]={component:n.components[0]}}else m[t]=e.attributes[t]}let h={};e.downstreamDependencies&&Object.assign(h,e.downstreamDependencies);let f=await this.createStateVariableDefinitions({componentClass:r,prescribedDependencies:h,componentName:t});delete this.updateInfo.deletedComponents[t],delete this.updateInfo.deletedStateVariables[t];let y=new r({componentName:t,ancestors:n,definingChildren:l,stateVariableDefinitions:f,serializedChildren:u,serializedComponent:e,attributes:m,componentInfoObjects:this.componentInfoObjects,coreFunctions:this.coreFunctions,flags:this.flags,shadow:a,numerics:this.numerics,sharedParameters:d,parentSharedParameters:p});this.registerComponent(y),s&&(y.replacementOf=s),e.adaptedFrom&&(y.adaptedFrom=this._components[e.adaptedFrom],y.adaptedFrom.adapterUsed=y);for(let e in h){let t=h[e];for(let n of t)if("referenceShadow"===n.dependencyType){let t={componentName:e};Object.assign(t,n),delete t.dependencyType,y.shadows=t;let r=this._components[e];if(r.shadowedBy||(r.shadowedBy=[]),r.shadowedBy.push(y),n.isPrimaryShadow&&(r.primaryShadow=y.componentName,this.dependencies.updateTriggers.primaryShadowDependencies[e]))for(let t of this.dependencies.updateTriggers.primaryShadowDependencies[e])await t.recalculateDownstreamComponents();break}}e.unlinkedCopySource&&(y.unlinkedCopySource=e.unlinkedCopySource),await this.deriveChildResultsFromDefiningChildren({parent:y,expandComposites:!1}),await this.initializeComponentStateVariables(y),await this.dependencies.setUpComponentDependencies(y);let g=await this.dependencies.checkForDependenciesOnNewComponent(t);for(let e of g)await this.markStateVariableAndUpstreamDependentsStale({component:this._components[e.componentName],varName:e.varName});return await this.checkForStateVariablesUpdatesForNewComponent(t),await this.dependencies.resolveStateVariablesIfReady({component:y}),await this.checkForActionChaining({component:y}),this.parameterStack.pop(),{newComponent:y}}async checkForStateVariablesUpdatesForNewComponent(e){if(e in this.updateInfo.stateVariableUpdatesForMissingComponents){let t=await this.processNewStateVariableValues({[e]:this.updateInfo.stateVariableUpdatesForMissingComponents[e]}),n=this._components[e];if(n.constructor.processWhenJustUpdatedForNewComponent||t.foundIgnore)for(let r in this.updateInfo.stateVariableUpdatesForMissingComponents[e])n.state[r]&&(this.updateInfo.stateVariablesToEvaluate.push({componentName:e,stateVariable:r}),n.state[r].justUpdatedForNewComponent=!0,t.foundIgnore&&(n.reprocessAfterEvaluate=this.updateInfo.stateVariableUpdatesForMissingComponents[e]));delete this.updateInfo.stateVariableUpdatesForMissingComponents[e]}}async deriveChildResultsFromDefiningChildren({parent:e,expandComposites:t=!0,forceExpandComposites:n=!1}){if(this.derivingChildResults||(this.derivingChildResults=[]),this.derivingChildResults.includes(e.componentName))return{success:!1,skipping:!0};this.derivingChildResults.push(e.componentName);let r,a=await this.expandCompositeOfDefiningChildren(e,e.definingChildren,t,n);e.unexpandedCompositesReady=a.unexpandedCompositesReady,e.unexpandedCompositesNotReady=a.unexpandedCompositesNotReady,e.activeChildren&&(r=e.activeChildren.map((e=>e.componentName?e.componentName:e))),e.activeChildren=e.definingChildren.slice(),e.allChildren={},e.allChildrenOrdered=[];for(let t=0;te.componentType)).join(", ");this.unmatchedChildren[e.componentName]={message:`invalid children of type(s): ${t}`}}await this.dependencies.addBlockersFromChangedActiveChildren({parent:e});let s=this.derivingChildResults.indexOf(e.componentName);if(this.derivingChildResults.splice(s,1),e.constructor.renderChildren){let t=r&&r.length==e.activeChildren.length&&e.activeChildren.every(((e,t)=>e.componentName?e.componentName===r[t]:e===r[t]));t||this.componentsWithChangedChildrenToRender.add(e.componentName)}return i}async expandCompositeOfDefiningChildren(e,t,n,r){let a=[],i=[];for(let s=0;s=n)break;if(!r||r.includes(a))if("object"==typeof i)!i.constructor.sendToRendererEvenIfHidden&&await i.stateValues.hidden||t.push(a);else{let n=!1;if(e.compositeReplacementActiveRange)for(let t of e.compositeReplacementActiveRange){let e=this._components[t.compositeName];if(await e.stateValues.hidden&&t.firstInd<=a&&t.lastInd>=a){n=!0;break}}n||t.push(a)}}return t}async substituteAdapter({parent:e,childInd:t,adapterIndUsed:n}){let r,a=e.activeChildren[t];r=a.componentName?a.getAdapter(n):{componentType:this.componentInfoObjects.allComponentClasses[a.componentType].getAdapterComponentType(n,this.componentInfoObjects.publicStateVariableInfo),placeholderInd:a.placeholderInd+"adapt"};let i=a.adapterUsed;if(void 0===i||i.componentType!==r.componentType)if(a.componentName){let t;t=e.attributes.newNamespace?.primitive?e.componentName+"/":getNamespaceFromName(e.componentName),r.adaptedFrom=a.componentName,i=(await this.createIsolatedComponentsSub({serializedComponents:[r],shadow:!0,ancestors:a.ancestors,createNameContext:a.componentName+"|adapter",namespaceForUnamed:t})).components[0]}else r.adaptedFrom=a,i=r;if(e.activeChildren.splice(t,1,i),a.componentName&&(delete e.allChildren[a.componentName].activeChildrenIndex,e.allChildren[i.componentName]={activeChildrenIndex:t,component:i}),a.componentName){let t=e.allChildrenOrdered.indexOf(a.componentName);e.allChildrenOrdered.splice(t+1,0,i.componentName)}else{let t=e.allChildrenOrdered.indexOf(a.placeholderInd);e.allChildrenOrdered.splice(t+1,0,i.placeholderInd)}}async expandCompositeComponent(e){if(!("readyToExpandWhenResolved"in e.state))throw Error(`Could not find state variable readyToExpandWhenResolved of composite ${e.componentName}`);if(!e.state.readyToExpandWhenResolved.isResolved)return this.updateInfo.compositesToExpand.add(e.componentName),{success:!1};if(this.updateInfo.compositesToExpand.delete(e.componentName),this.updateInfo.compositesBeingExpanded.push(e.componentName),e.parent){if(e.parent.unexpandedCompositesReady){let t=e.parent.unexpandedCompositesReady.indexOf(e.componentName);-1!==t&&e.parent.unexpandedCompositesReady.splice(t,1)}if(e.parent.unexpandedCompositesNotReady){let t=e.parent.unexpandedCompositesNotReady.indexOf(e.componentName);-1!==t&&e.parent.unexpandedCompositesNotReady.splice(t,1)}}if(e.shadows)return await this.expandShadowingComposite(e);let t=await e.constructor.createSerializedReplacements({component:this.components[e.componentName],components:this.components,workspace:e.replacementsWorkspace,componentInfoObjects:this.componentInfoObjects,flags:this.flags,resolveItem:this.dependencies.resolveItem.bind(this.dependencies),publicCaseInsensitiveAliasSubstitutions:this.publicCaseInsensitiveAliasSubstitutions.bind(this)});if(e.constructor.stateVariableToEvaluateAfterReplacements&&await e.stateValues[e.constructor.stateVariableToEvaluateAfterReplacements],!t.replacements)throw Error(`Invalid createSerializedReplacements of ${e.componentName}`);{let n=t.replacements;await this.createAndSetReplacements({component:e,serializedReplacements:n})}let n=this.updateInfo.compositesBeingExpanded.indexOf(e.componentName);if(-1===n)throw Error(`Something is wrong as we lost track that we were expanding ${e.componentName}`);return this.updateInfo.compositesBeingExpanded.splice(n,1),{success:!0,compositesExpanded:[e.componentName]}}async expandShadowingComposite(e){if(this.updateInfo.compositesBeingExpanded.includes(e.shadows.componentName)){let t=this._components[e.shadows.componentName];for(;t.shadows;)t=this._components[t.shadows.componentName];throw Error(`Circular reference involving ${t.componentName}`)}let t=this._components[e.shadows.componentName],n=[];if(!t.isExpanded){let r=await this.expandCompositeComponent(t);if(!r.success)throw Error(`expand result of ${e.componentName} was not a success even though ready to expand.`);n.push(...r.compositesExpanded)}let r=[],a=await e.stateValues.sourceAttributesToIgnore,i=await e.stateValues.sourceAttributesToIgnoreRecursively;for(let e of t.replacements)"object"==typeof e?r.push(await e.serialize({sourceAttributesToIgnore:a,sourceAttributesToIgnoreRecursively:i})):r.push(e);let s=e.replacementsWorkspace.uniqueIdentifiersUsed=[],o=e.shadows.compositeName;r=postProcessCopy({serializedComponents:r,componentName:o,uniqueIdentifiersUsed:s});let l=e.attributes.newNamespace?.primitive;if(e.attributes.isResponse){let t=e.constructor.createAttributesObject();for(let n of r){if("object"!=typeof n)continue;n.attributes||(n.attributes={});let r=convertAttributesForComponentType({attributes:{isResponse:e.attributes.isResponse},componentType:n.componentType,componentInfoObjects:this.componentInfoObjects,compositeAttributesObj:t,compositeCreatesNewNamespace:l});Object.assign(n.attributes,r)}}if(e.constructor.assignNamesToReplacements){let n,a=this.components[o],i=a.attributes.newNamespace?.primitive,s=a.doenetAttributes.assignNames,u=s?.some(Array.isArray),c=a.attributes.assignNewNamespaces?.primitive,p=this._components[a.doenetAttributes.targetComponentName];p&&(n=!this.componentInfoObjects.isCompositeComponent({componentType:p.componentType,includeNonStandard:!1})&&p.attributes.newNamespace?.primitive);let d=!u&&(l||n||i&&!s||c),m=e.doenetAttributes.assignNames;if(m&&await e.stateValues.addLevelToAssignNames&&(m=m.map((e=>[e]))),r=processAssignNames({assignNames:m,serializedComponents:r,parentName:e.componentName,parentCreatesNewNamespace:l,componentInfoObjects:this.componentInfoObjects,originalNamesAreConsistent:d,shadowingComposite:!0}).serializedComponents,p?.componentName===t.componentName&&a.doenetAttributes.fromCopyTarget){let t=deepClone(a.serializedChildren);this.componentInfoObjects.allComponentClasses[e.componentType].includeBlankStringChildren||(t=t.filter((e=>"string"!=typeof e||""!==e.trim())));let n=processAssignNames({assignNames:m,serializedComponents:t,parentName:e.componentName,parentCreatesNewNamespace:a.attributes.assignNewNamespaces?.primitive,indOffset:r.length,componentInfoObjects:this.componentInfoObjects,originalNamesAreConsistent:!0});r.push(...n.serializedComponents)}}else{let t=l;r=processAssignNames({serializedComponents:r,parentName:e.componentName,parentCreatesNewNamespace:l,componentInfoObjects:this.componentInfoObjects,originalNamesAreConsistent:t,shadowingComposite:!0}).serializedComponents}r=(await verifyReplacementsMatchSpecifiedType({component:e,replacements:r,assignNames:e.doenetAttributes.assignNames,componentInfoObjects:this.componentInfoObjects,compositeAttributesObj:e.constructor.createAttributesObject(),flags:this.flags})).replacements,await this.createAndSetReplacements({component:e,serializedReplacements:r}),t.replacementsToWithhold>0&&(e.replacementsToWithhold=t.replacementsToWithhold);let u=this.updateInfo.compositesBeingExpanded.indexOf(e.componentName);if(-1===u)throw Error(`Something is wrong as we lost track that we were expanding ${e.componentName}`);return this.updateInfo.compositesBeingExpanded.splice(u,1),n.push(e.componentName),{success:!0,compositesExpanded:n}}async createAndSetReplacements({component:e,serializedReplacements:t}){let n;this.parameterStack.push(e.sharedParameters,!1),n=e.attributes.newNamespace?.primitive?e.componentName+"/":getNamespaceFromName(e.componentName);let r=await this.createIsolatedComponentsSub({serializedComponents:t,ancestors:e.ancestors,shadow:!0,createNameContext:e.componentName+"|replacements",namespaceForUnamed:n,componentsReplacementOf:e});this.parameterStack.pop(),e.replacements=r.components,await this.dependencies.addBlockersFromChangedReplacements(e),e.isExpanded=!0}async replaceCompositeChildren(e){delete e.placeholderActiveChildrenIndices,delete e.placeholderActiveChildrenIndicesByComposite,delete e.compositeReplacementActiveRange;let t=0;for(let n=0;ne+n));e.placeholderActiveChildrenIndices||(e.placeholderActiveChildrenIndices=[]),e.placeholderActiveChildrenIndices.push(...o),e.placeholderActiveChildrenIndicesByComposite||(e.placeholderActiveChildrenIndicesByComposite={}),e.placeholderActiveChildrenIndicesByComposite[r.componentName]=o}else await this.markWithheldReplacementsInactive(r),a=r.replacements,r.replacementsToWithhold>0&&(a=a.slice(0,-r.replacementsToWithhold)),e.constructor.includeBlankStringChildren&&!e.constructor.removeBlankStringChildrenPostSugar||(a=a.filter((e=>"string"!=typeof e||/\S/.test(e))));e.compositeReplacementActiveRange||(e.compositeReplacementActiveRange=[]);for(let t of e.compositeReplacementActiveRange)t.lastInd>=n&&(t.lastInd+=a.length-1);e.compositeReplacementActiveRange.push({compositeName:r.componentName,target:await r.stateValues.target,firstInd:n,lastInd:n+a.length-1}),e.activeChildren.splice(n,1,...a),delete e.allChildren[r.componentName].activeChildrenIndex;for(let t=0;t"object"==typeof e)).map((e=>e.componentName?e.componentName:e.placeholderInd))),1!==a.length){let t=a.length-1;for(let r=n+a.length;r0&&(t-=e.replacementsToWithhold);for(let n of e.replacements.slice(0,t))await this.changeInactiveComponentAndDescendants(n,!1);for(let n of e.replacements.slice(t))await this.changeInactiveComponentAndDescendants(n,!0);if(!await e.stateValues.isInactiveCompositeReplacement){let t=e.componentName;this.updateInfo.inactiveCompositesToUpdateReplacements.has(t)&&(this.updateInfo.inactiveCompositesToUpdateReplacements.delete(t),this.updateInfo.compositesToUpdateReplacements.add(t))}}async changeInactiveComponentAndDescendants(e,t){if("object"==typeof e&&await e.stateValues.isInactiveCompositeReplacement!==t){e.state.isInactiveCompositeReplacement.value=t,await this.markUpstreamDependentsStale({component:e,varName:"isInactiveCompositeReplacement"}),this.dependencies.recordActualChangeInUpstreamDependencies({component:e,varName:"isInactiveCompositeReplacement"});for(let n in e.allChildren)await this.changeInactiveComponentAndDescendants(this._components[n],t);for(let n in e.attributes){let r=e.attributes[n].component;r&&await this.changeInactiveComponentAndDescendants(this._components[r.componentName],t)}e.replacements&&await this.markWithheldReplacementsInactive(e)}}findShadowedChildInSerializedComponents({serializedComponents:e,shadowedComponentName:t}){for(let n of e){if(n.originalName===t)return n;if(n.children){let e=this.findShadowedChildInSerializedComponents({serializedComponents:n.children,shadowedComponentName:t});if(e)return e}}}async createStateVariableDefinitions({componentClass:e,prescribedDependencies:t,componentName:n}){let r;if(t)for(let e in t){let a=t[e];for(let t of a)if("referenceShadow"===t.dependencyType){if(e===n)throw Error(`circular reference involving ${n}`);r={linkSource:"referenceShadow",targetName:e,compositeName:t.compositeName,propVariable:t.propVariable,arrayStateVariable:t.arrayStateVariable,arrayKey:t.arrayKey,ignorePrimaryStateVariable:t.ignorePrimaryStateVariable,substituteForPrimaryStateVariable:t.substituteForPrimaryStateVariable,firstLevelReplacement:t.firstLevelReplacement,additionalStateVariableShadowing:t.additionalStateVariableShadowing}}else"adapter"===t.dependencyType&&(r={linkSource:"adapter",adapterTargetIdentity:t.adapterTargetIdentity,adapterVariable:t.adapterVariable,substituteForPrimaryStateVariable:t.substituteForPrimaryStateVariable,stateVariablesToShadow:t.stateVariablesToShadow})}let a={};r||this.createAttributeStateVariableDefinitions({stateVariableDefinitions:a,componentClass:e});let i=e.returnNormalizedStateVariableDefinitions({attributeNames:Object.keys(a),numerics:this.numerics});return Object.assign(a,i),r&&("adapter"===r.linkSource?this.createAdapterStateVariableDefinitions({redefineDependencies:r,stateVariableDefinitions:a,componentClass:e}):await this.createReferenceShadowStateVariableDefinitions({redefineDependencies:r,stateVariableDefinitions:a,componentClass:e})),a}createAttributeStateVariableDefinitions({componentClass:e,stateVariableDefinitions:t}){let n=e.createAttributesObject();for(let r in n){let a=n[r];if(!a.createStateVariable)continue;let i,s=a.createStateVariable,o=t[s]={isAttribute:!0,hasEssential:!0};if(a.public)if(o.public=!0,o.shadowingInstructions={},a.createPrimitiveOfType)o.shadowingInstructions.createComponentOfType=a.createPrimitiveOfType,"string"===o.shadowingInstructions.createComponentOfType?o.shadowingInstructions.createComponentOfType="text":"stringArray"===o.shadowingInstructions.createComponentOfType?o.shadowingInstructions.createComponentOfType="textList":"numberArray"===o.shadowingInstructions.createComponentOfType&&(o.shadowingInstructions.createComponentOfType="numberList");else{if(a.createTargetComponentNames)throw Error("Cannot make a public state variable from an attribute with createTargetComponentNames");o.shadowingInstructions.createComponentOfType=a.createComponentOfType}if(a.createComponentOfType){let t=this.componentInfoObjects.allComponentClasses[a.createComponentOfType];if(!t)throw Error(`Component type ${a.createComponentOfType} does not exist so cannot create state variable for attribute ${r} of componentType ${e.componentType}.`);i=a.componentStateVariableForAttributeValue,void 0===i&&(i=t.stateVariableForAttributeValue,void 0===i&&(i="value"))}o.returnDependencies=function(){let e={};return a.fallBackToParentStateVariable&&(e.parentValue={dependencyType:"parentStateVariable",variableName:a.fallBackToParentStateVariable}),a.createPrimitiveOfType?e.attributePrimitive={dependencyType:"attributePrimitive",attributeName:r}:a.createTargetComponentNames?e.attributeTargetComponentNames={dependencyType:"attributeTargetComponentNames",attributeName:r}:e.attributeComponent={dependencyType:"attributeComponent",attributeName:r,variableNames:[i]},e},o.definition=function({dependencyValues:e,usedDefault:t}){let n;if(e.attributeComponent)n=e.attributeComponent.stateValues[i];else if(void 0!==e.attributePrimitive&&null!==e.attributePrimitive)n=e.attributePrimitive;else{if(void 0===e.attributeTargetComponentNames||null===e.attributeTargetComponentNames){return void 0!==e.parentValue&&null!==e.parentValue&&!t.parentValue?{setValue:{[s]:e.parentValue},checkForActualChange:{[s]:!0}}:{useEssentialOrDefaultValue:{[s]:!0},checkForActualChange:{[s]:!0}}}n=e.attributeTargetComponentNames}return n=validateAttributeValue({value:n,attributeSpecification:a,attribute:r}),{setValue:{[s]:n},checkForActualChange:{[s]:!0}}},a.noInverse||(o.inverseDefinition=async function({desiredStateVariableValues:e,dependencyValues:t,usedDefault:n}){if(!t.attributeComponent){if(void 0!==t.attributePrimitive&&null!==t.attributePrimitive)return{success:!1};if(void 0!==t.attributeTargetComponentNames&&null!==t.attributeTargetComponentNames)return{success:!1};if(void 0!==t.parentValue&&null!==t.parentValue&&!n.parentValue)return{success:!0,instructions:[{setDependency:"parentValue",desiredValue:e[s]}]};{let t=validateAttributeValue({value:e[s],attributeSpecification:a,attribute:r});return{success:!0,instructions:[{setEssentialValue:s,value:t}]}}}return{success:!0,instructions:[{setDependency:"attributeComponent",desiredValue:e[s],variableIndex:0}]}});let l=["forRenderer","defaultValue","propagateToProps","triggerActionOnChange"];for(let e of l)e in a&&(o[e]=a[e])}}createAdapterStateVariableDefinitions({redefineDependencies:e,stateVariableDefinitions:t,componentClass:n}){let r=this._components[e.adapterTargetIdentity.componentName],a=n.createAttributesObject();for(let n in a){let i=a[n];if(!i.createStateVariable)continue;let s=i.createStateVariable,o=t[s]={isAttribute:!0,hasEssential:!0};if(i.public)if(o.public=!0,o.shadowingInstructions={},i.createPrimitiveOfType)o.shadowingInstructions.createComponentOfType=i.createPrimitiveOfType,"string"===o.shadowingInstructions.createComponentOfType?o.shadowingInstructions.createComponentOfType="text":"stringArray"===o.shadowingInstructions.createComponentOfType?o.shadowingInstructions.createComponentOfType="textList":"numberArray"===o.shadowingInstructions.createComponentOfType&&(o.shadowingInstructions.createComponentOfType="numberList");else{if(i.createTargetComponentNames)throw Error("Cannot make a public state variable from an attribute with createTargetComponentNames");o.shadowingInstructions.createComponentOfType=i.createComponentOfType}s in r.state?o.returnDependencies=()=>({adapterTargetVariable:{dependencyType:"stateVariable",componentName:e.adapterTargetIdentity.componentName,variableName:s}}):o.returnDependencies=()=>({}),o.definition=function({dependencyValues:e,usedDefault:t}){return void 0===e.adapterTargetVariable||t.adapterTargetVariable?{useEssentialOrDefaultValue:{[s]:!0},checkForActualChange:{[s]:!0}}:{setValue:{[s]:e.adapterTargetVariable},checkForActualChange:{[s]:!0}}},i.noInverse||(o.inverseDefinition=async function({desiredStateVariableValues:e,dependencyValues:t}){return void 0===t.adapterTargetVariable?{success:!0,instructions:[{setEssentialValue:s,value:e[s]}]}:{success:!0,instructions:[{setDependency:"adapterTargetVariable",desiredValue:e[s]}]}});let l=["forRenderer","defaultValue","propagateToProps"];for(let e of l)e in i&&(o[e]=i[e])}let i="value";e.substituteForPrimaryStateVariable?i=e.substituteForPrimaryStateVariable:n.primaryStateVariableForDefinition&&(i=n.primaryStateVariableForDefinition);let s=t[i];s.returnDependencies=()=>({adapterTargetVariable:{dependencyType:"stateVariable",componentName:e.adapterTargetIdentity.componentName,variableName:e.adapterVariable}}),s.set?s.definition=function({dependencyValues:e}){return{setValue:{[i]:s.set(e.adapterTargetVariable)}}}:s.definition=function({dependencyValues:e}){return{setValue:{[i]:e.adapterTargetVariable}}},s.inverseDefinition=function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setDependency:"adapterTargetVariable",desiredValue:e[i]}]}},e.stateVariablesToShadow&&this.modifyStateDefsToBeShadows({stateVariablesToShadow:e.stateVariablesToShadow,stateVariableDefinitions:t,targetComponent:r})}async createReferenceShadowStateVariableDefinitions({redefineDependencies:e,stateVariableDefinitions:t,componentClass:n}){let r=this._components[e.targetName];e.propVariable&&!r.state[e.propVariable]&&this.checkIfArrayEntry({stateVariable:e.propVariable,component:r})&&await this.createFromArrayEntry({stateVariable:e.propVariable,component:r});let a=n.createAttributesObject();for(let e in a){let r=a[e],i=r.createStateVariable;if(!i)continue;let s,o=t[i]={isAttribute:!0,hasEssential:!0};if(r.createComponentOfType,r.public)if(o.public=!0,o.shadowingInstructions={},r.createPrimitiveOfType)o.shadowingInstructions.createComponentOfType=r.createPrimitiveOfType,"string"===o.shadowingInstructions.createComponentOfType?o.shadowingInstructions.createComponentOfType="text":"stringArray"===o.shadowingInstructions.createComponentOfType?o.shadowingInstructions.createComponentOfType="textList":"numberArray"===o.shadowingInstructions.createComponentOfType&&(o.shadowingInstructions.createComponentOfType="numberList");else{if(r.createTargetComponentNames)throw Error("Cannot make a public state variable from an attribute with createTargetComponentNames");o.shadowingInstructions.createComponentOfType=r.createComponentOfType}if(r.createComponentOfType){let t=this.componentInfoObjects.allComponentClasses[r.createComponentOfType];if(!t)throw Error(`Component type ${r.createComponentOfType} does not exist so cannot create state variable for attribute ${e} of componentType ${n.componentType}.`);s=r.componentStateVariableForAttributeValue,void 0===s&&(s=t.stateVariableForAttributeValue,void 0===s&&(s="value"))}let l={};r.createPrimitiveOfType?l.attributePrimitive={dependencyType:"attributePrimitive",attributeName:e}:r.createTargetComponentNames?l.attributeTargetComponentNames={dependencyType:"attributeTargetComponentNames",attributeName:e}:l.attributeComponent={dependencyType:"attributeComponent",attributeName:e,variableNames:[s]},r.fallBackToParentStateVariable&&(l.parentValue={dependencyType:"parentStateVariable",variableName:r.fallBackToParentStateVariable}),o.returnDependencies=()=>l,o.definition=function({dependencyValues:t,usedDefault:n}){let a;if(t.attributeComponent)a=t.attributeComponent.stateValues[s];else if(void 0!==t.attributePrimitive&&null!==t.attributePrimitive)a=t.attributePrimitive;else{if(void 0===t.attributeTargetComponentNames||null===t.attributeTargetComponentNames){return void 0!==t.parentValue&&null!==t.parentValue&&!n.parentValue?{setValue:{[i]:t.parentValue},checkForActualChange:{[i]:!0}}:{useEssentialOrDefaultValue:{[i]:!0},checkForActualChange:{[i]:!0}}}a=t.attributeTargetComponentNames}return a=validateAttributeValue({value:a,attributeSpecification:r,attribute:e}),{setValue:{[i]:a},checkForActualChange:{[i]:!0}}},r.noInverse||(o.inverseDefinition=async function({desiredStateVariableValues:t,dependencyValues:n,stateValues:a,workspace:s}){if(!n.attributeComponent){if(void 0!==n.attributePrimitive&&null!==n.attributePrimitive)return{success:!1};if(void 0!==n.attributeTargetComponentNames&&null!==n.attributeTargetComponentNames)return{success:!1};if(void 0!==n.parentValue&&null!==n.parentValue&&!usedDefault.parentValue)return{success:!0,instructions:[{setDependency:"parentValue",desiredValue:t[i]}]};{let n=validateAttributeValue({value:t[i],attributeSpecification:r,attribute:e});return{success:!0,instructions:[{setEssentialValue:i,value:n}]}}}return{success:!0,instructions:[{setDependency:"attributeComponent",desiredValue:t[i],variableIndex:0}]}});let u=["forRenderer","defaultValue","propagateToProps"];for(let e of u)e in r&&(o[e]=r[e])}if(e.propVariable){if(!e.ignorePrimaryStateVariable){let a="value";e.substituteForPrimaryStateVariable?a=e.substituteForPrimaryStateVariable:n.primaryStateVariableForDefinition&&(a=n.primaryStateVariableForDefinition);let i=t[a];if(!i)throw e.substituteForPrimaryStateVariable?Error(`Invalid public state variable of componentType ${n.componentType}: substituteForPrimaryStateVariable ${e.substituteForPrimaryStateVariable} does not exist`):Error(`Cannot have a public state variable with componentType ${n.componentType} as the class doesn't have a primary state variable for definition`);i.isShadow=!0,i.returnDependencies=()=>({targetVariable:{dependencyType:"stateVariable",componentName:r.componentName,variableName:e.propVariable}});let s=!1;void 0!==r.state[e.propVariable].defaultValue&&(i.defaultValue=r.state[e.propVariable].defaultValue,i.set&&(i.defaultValue=i.set(i.defaultValue)),i.hasEssential=!0,s=!0),i.set?i.definition=function({dependencyValues:e,usedDefault:t}){let n=i.set(e.targetVariable);return s&&t.targetVariable?{useEssentialOrDefaultValue:{[a]:{defaultValue:n}},alwaysShadow:[a]}:{setValue:{[a]:n},alwaysShadow:[a]}}:i.definition=function({dependencyValues:e,usedDefault:t}){return s&&t.targetVariable?{useEssentialOrDefaultValue:{[a]:{defaultValue:e.targetVariable}},alwaysShadow:[a]}:{setValue:{[a]:e.targetVariable},alwaysShadow:[a]}},i.inverseDefinition=function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setDependency:"targetVariable",desiredValue:e[a]}]}}}if(e.additionalStateVariableShadowing){let n=[],a=[];for(let t in e.additionalStateVariableShadowing)n.push(t),a.push(e.additionalStateVariableShadowing[t].stateVariableToShadow);this.modifyStateDefsToBeShadows({stateVariablesToShadow:n,stateVariableDefinitions:t,targetComponent:r,differentStateVariablesInTarget:a})}return}let i=!1;if("readyToExpandWhenResolved"in t){i=!0;let e=t.readyToExpandWhenResolved,n=e.returnDependencies.bind(e),a=e.definition;e.returnDependencies=function(e){let t=n(e);return t.targetReadyToExpandWhenResolved={dependencyType:"stateVariable",componentName:r.componentName,variableName:"readyToExpandWhenResolved"},t},e.definition=function(e){let t=a(e);return t.setValue&&t.setValue.readyToExpandWhenResolved&&(e.dependencyValues.targetReadyToExpandWhenResolved||(t.setValue.readyToExpandWhenResolved=!1)),t}}let s=[];for(let e in r.state){let t=r.state[e];(t.shadowVariable||t.isShadow)&&s.push(e)}this.modifyStateDefsToBeShadows({stateVariablesToShadow:s,stateVariableDefinitions:t,foundReadyToExpandWhenResolved:i,targetComponent:r})}modifyStateDefsToBeShadows({stateVariablesToShadow:e,stateVariableDefinitions:t,foundReadyToExpandWhenResolved:n,targetComponent:r,differentStateVariablesInTarget:a=[]}){let i={};for(let[s,o]of e.entries()){let l=t[o];if(void 0===l){if("__array_"!==o.slice(0,8))continue;l=t[o]={}}if(l.isShadow=!0,l.additionalStateVariablesDefined)for(let t of l.additionalStateVariablesDefined)e.includes(t)||(i[t]||(i[t]=[]),i[t].push(o));delete l.additionalStateVariablesDefined,n||delete l.stateVariablesDeterminingDependencies;let u=l.public&&l.shadowingInstructions.hasVariableComponentType;if(l.isArray){let e=a[s];l.returnArrayDependenciesByKey=function({arrayKeys:t}){let n={};for(let a of t)n[a]={targetVariable:{dependencyType:"stateVariable",componentName:r.componentName,variableName:e||this.arrayVarNameFromArrayKey(a)}};let a={};return u&&(a.targetVariableComponentType={dependencyType:"stateVariableComponentType",componentName:r.componentName,variableName:o}),l.inverseShadowToSetEntireArray&&(a.targetArray={dependencyType:"stateVariable",componentName:r.componentName,variableName:o}),{globalDependencies:a,dependenciesByKey:n}},l.arrayDefinitionByKey=function({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};for(let e of n)"targetVariable"in t[e]?r[e]=t[e].targetVariable:r[e]=l.defaultValueByArrayKey?.(e);let a={setValue:{[o]:r},alwaysShadow:[o]};return"targetVariableComponentType"in e&&(a.setCreateComponentOfType={[o]:e.targetVariableComponentType}),a},l.inverseArrayDefinitionByKey=function({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n,arraySize:r,initialChange:a}){if(l.inverseShadowToSetEntireArray)return{success:!0,instructions:[{setDependency:"targetArray",desiredValue:e[o],treatAsInitialChange:a}]};let i=[];for(let r in e[o])t[r]&&i.push({setDependency:n[r].targetVariable,desiredValue:e[o][r],shadowedVariable:!0});return{success:!0,instructions:i}}}else{let e=()=>({});n&&(e=l.returnDependencies.bind(l));let t=a[s];t||(t=o),l.returnDependencies=function(n){let a=Object.assign({},e(n));return a.targetVariable={dependencyType:"stateVariable",componentName:r.componentName,variableName:t},u&&(a.targetVariableComponentType={dependencyType:"stateVariableComponentType",componentName:r.componentName,variableName:t}),a},l.definition=function({dependencyValues:e,usedDefault:t}){let n={alwaysShadow:[o]};return"targetVariableComponentType"in e&&(n.setCreateComponentOfType={[o]:e.targetVariableComponentType}),t.targetVariable&&"defaultValue"in l&&l.hasEssential?n.useEssentialOrDefaultValue={[o]:{defaultValue:e.targetVariable}}:n.setValue={[o]:e.targetVariable},n},l.excludeDependencyValuesInInverseDefinition=!0,l.inverseDefinition=function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setDependency:"targetVariable",desiredValue:e[o],shadowedVariable:!0}]}}}}for(let e in i)this.modifyStateDefToDeleteVariableReferences({varNamesToDelete:i[e],stateDef:t[e]})}modifyStateDefToDeleteVariableReferences({varNamesToDelete:e,stateDef:t}){for(let n of e){let e=t.additionalStateVariablesDefined.indexOf(n);t.additionalStateVariablesDefined.splice(e,1)}let n=t.definition;t.definition=function(t){let r=n(t);for(let t in r)if(Array.isArray(r[t]))for(let n of e){let e=r[t].indexOf(n);-1!==e&&r[t].splice(e,1)}else for(let n of e)delete r[t][n];return r}}async initializeComponentStateVariables(e){for(let t in e.state)e.state[t].isAlias?(e.stateVarAliases||(e.stateVarAliases={}),e.stateVarAliases[t]=e.state[t].targetVariableName,delete e.state[t]):await this.initializeStateVariable({component:e,stateVariable:t})}async initializeStateVariable({component:e,stateVariable:t,arrayStateVariable:n,arrayEntryPrefix:r}){let a=this.getStateVariableValue;e.state[t]||(e.state[t]={});let i=e.state[t];if(i.isResolved=!1,Object.defineProperty(i,"value",{get:()=>a({component:e,stateVariable:t}),configurable:!0}),void 0!==r?await this.initializeArrayEntryStateVariable({stateVarObj:i,arrayStateVariable:n,arrayEntryPrefix:r,component:e,stateVariable:t}):i.isArray&&await this.initializeArrayStateVariable({stateVarObj:i,component:e,stateVariable:t}),i.triggerActionOnChange){let n=this.stateVariableChangeTriggers[e.componentName];n||(n=this.stateVariableChangeTriggers[e.componentName]={}),n[t]={action:i.triggerActionOnChange}}}async checkForActionChaining({component:e,stateVariables:t}){if(e){t||(t=Object.keys(e.state));for(let n of t){let t=e.state[n];if(t.chainActionOnActionOfStateVariableTargets){let r,a=t.chainActionOnActionOfStateVariableTargets,i=await t.value,s=this.originsOfActionsChangedToActions[e.componentName];s&&(r=s[n]),r||(r=[]);let o=[];if(Array.isArray(i)){o=[...i];for(let t of o){let i=r.indexOf(t);if(-1===i){let r=this.actionsChangedToActions[t];r||(r=this.actionsChangedToActions[t]=[]),r.push({componentName:e.componentName,actionName:a.triggeredAction,stateVariableDefiningChain:n,args:{}})}else r.splice(i,1)}}for(let t of r){let r=this.actionsChangedToActions[t];if(r){let a=[];for(let t of r)t.componentName===e.componentName&&t.stateVariableDefiningChain===n||a.push(t);this.actionsChangedToActions[t]=a}}o.length>0?(s||(s=this.originsOfActionsChangedToActions[e.componentName]={}),s[n]=o):s&&(delete s[n],0===Object.keys(s).length&&delete this.originsOfActionsChangedToActions[e.componentName])}}}}async initializeArrayEntryStateVariable({stateVarObj:e,arrayStateVariable:t,arrayEntryPrefix:n,component:r,stateVariable:a}){e.isArrayEntry=!0,e.arrayStateVariable=t;let i=r.state[t];if(e.definition=i.definition,e.inverseDefinition=i.inverseDefinition,e.markStale=i.markStale,e.freshnessInfo=i.freshnessInfo,e.getPreviousDependencyValuesForMarkStale=i.getPreviousDependencyValuesForMarkStale,e.provideEssentialValuesInDefinition=i.provideEssentialValuesInDefinition,e.providePreviousValuesInDefinition=i.providePreviousValuesInDefinition,e.nDimensions=i.returnEntryDimensions(n),e.entryPrefix=n,e.varEnding=a.slice(n.length),i.createWorkspace&&(e.createWorkspace=!0,e.workspace=i.workspace),i.basedOnArrayKeyStateVariables&&(e.basedOnArrayKeyStateVariables=!0),i.additionalStateVariablesDefined){e.additionalStateVariablesDefined=[];let t=i.entryPrefixes.indexOf(n);for(let n of i.additionalStateVariablesDefined){let a=r.state[n];if(a.isArray){let n=a.entryPrefixes[t]+e.varEnding;e.additionalStateVariablesDefined.push(n)}else e.additionalStateVariablesDefined.push(n)}}if(i.shadowingInstructions&&(e.shadowingInstructions={},e.wrappingComponents=i.shadowingInstructions.returnWrappingComponents(n),i.shadowingInstructions.attributesToShadow&&(e.shadowingInstructions.attributesToShadow=i.shadowingInstructions.attributesToShadow),i.shadowingInstructions.createComponentOfType)){let t=i.entryPrefixes.indexOf(n);i.shadowingInstructions.createComponentOfType[t]&&(e.shadowingInstructions.createComponentOfType=[i.shadowingInstructions.createComponentOfType[t]])}if(i.getEntryValues?e.getValueFromArrayValues=async function(){return await i.getEntryValues({varName:a})}:e.getValueFromArrayValues=async function(){let t=await e.arrayKeys;if(0===t.length)return;let n=[];for(let e of t)n.push(i.getArrayValue({arrayKey:e}));return 1===n.length?n[0]:n},e.arraySizeStateVariable=i.arraySizeStateVariable,e._arrayKeys=[],e._unflattenedArrayKeys=[],Object.defineProperty(e,"arrayKeys",{get:function(){return(async()=>(await i.arraySize,e._arrayKeys))()}}),Object.defineProperty(e,"unflattenedArrayKeys",{get:function(){return(async()=>(await i.arraySize,e._unflattenedArrayKeys))()}}),r.state[e.arraySizeStateVariable].initiallyResolved){let t=await i.arraySize,n=i.getArrayKeysFromVarName({arrayEntryPrefix:e.entryPrefix,varEnding:e.varEnding,arraySize:t,nDimensions:i.nDimensions});e._unflattenedArrayKeys=n,e._arrayKeys=flattenDeep(n);let r=i.varNamesIncludingArrayKeys;for(let t of e._arrayKeys)r[t]||(r[t]=[]),r[t].push(a)}if(i.arrayEntryNames.push(a),Object.defineProperty(e,"arraySize",{get:()=>i.arraySize}),Object.defineProperty(e,"arrayEntrySize",{get:function(){return(async()=>{let t=[],n=[await e.unflattenedArrayKeys];for(let r=0;r1?(e.keyToIndex=e=>e.split(",").map((e=>Number(e))),e.setArrayValue=function({value:t,arrayKey:n,arraySize:r,arrayValues:a=e.arrayValues}){let i=e.keyToIndex(n),s=i.length;if(!s>e.nDimensions)return console.warn("Cannot set array value. Number of dimensions is too large."),{nFailures:1};let o=a,l=r;for(let c of i.slice(0,i.length-1)){if(!(c>=0&&ca&&(console.warn("ignoring array values of out bounds"),r+=e.length-a,e=e.slice(0,a)),1===n.length)for(let[n,r]of e.entries())t[n]=r;else for(let[a,i]of e.entries()){t[a]||(t=[]),r+=p(i,t[a],n[a]).nFailures}return{nFailures:r}}u+=p(t,o,l).nFailures}else o[i[i.length-1]]=t;return{nFailures:u}},e.getArrayValue=function({arrayKey:t,arrayValues:n=e.arrayValues}){let r=e.keyToIndex(t),a=n;for(let e of r.slice(0,r.length-1))if(a=a[e],!a)return;return a[r[r.length-1]]},e.getAllArrayKeys||(e.getAllArrayKeys=function(e,t=!0,n){function r(e,t){for(let[n,a]of e.entries())Array.isArray(a)?r(a,t):e[n]=t+","+a}function a(e){if(1===e.length)return Array.from(Array(e[0]),((e,t)=>String(t)));{let n=e[0],i=a(e.slice(1)),s=[];for(let e=0;ee+","+t)));else{let t=deepClone(i);r(t,e),s.push(t)}return s}}return n?0===n.length?[]:a(n):e&&0!==e.length?a(e):[]}),e.arrayVarNameFromArrayKey||(e.arrayVarNameFromArrayKey=function(e){return r[0]+e.split(",").map((e=>Number(e)+1)).join("_")}),e.arrayVarNameFromPropIndex||(e.arrayVarNameFromPropIndex=function(t,n){return r[0]+[...t.map((e=>Math.round(Number(e)))),...Array(e.nDimensions-t.length).fill(1)].join("_")}),e.adjustArrayToNewArraySize=async function(){let t=await e.arraySize;!function e(t,n){if(t.length=n[0],n.length>1){let r=n.slice(1);for(let[n,a]of t.entries())a||(a=t[n]=[]),e(a,r)}}(e.arrayValues,t)}):(e.keyToIndex=e=>Number(e),e.setArrayValue=function({value:t,arrayKey:r,arraySize:a,arrayValues:i=e.arrayValues}){let s=e.keyToIndex(r);return s>=0&&sString(t))):e&&0!==e.length?Array.from(Array(e[0]),((e,t)=>String(t))):[]}),e.arrayVarNameFromArrayKey||(e.arrayVarNameFromArrayKey=function(e){return r[0]+String(Number(e)+1)}),e.arrayVarNameFromPropIndex||(e.arrayVarNameFromPropIndex=function(e,t){return r[0]+e[0]}),e.adjustArrayToNewArraySize=async function(){let t=await e.arraySize;e.arrayValues.length=t[0]}),e.getArrayKeysFromVarName||(e.getArrayKeysFromVarName=returnDefaultGetArrayKeysFromVarName(e.nDimensions)),e.indexToKey=e=>String(e);let r=e.entryPrefixes;r||(r=e.entryPrefixes=[n]),t.arrayEntryPrefixes||(t.arrayEntryPrefixes={});for(let e of r)t.arrayEntryPrefixes[e]=n;e.returnEntryDimensions||(e.returnEntryDimensions=()=>1),e.shadowingInstructions&&(e.shadowingInstructions.returnWrappingComponents||(e.shadowingInstructions.returnWrappingComponents=e=>[]),e.wrappingComponents=e.shadowingInstructions.returnWrappingComponents()),e.usedDefaultByArrayKey={},e.arrayEntryNames=[],e.varNamesIncludingArrayKeys={};let a=[n];function i(t,n,r){let a={},i={};for(let n of e.dependencyNames.global)a[n]=t[n],i[n]=r[n];let s={},o={},l={};for(let a of n)if(s[a]={},o[a]={},a in e.dependencyNames.namesByKey){l[a]=!0;for(let n in e.dependencyNames.namesByKey[a]){let i=e.dependencyNames.namesByKey[a][n];i in t?(s[a][n]=t[i],o[a][n]=r[i]):l[a]=!1}}return{globalDependencyValues:a,globalUsedDefault:i,dependencyValuesByKey:s,usedDefaultByKey:o,foundAllDependencyValuesForKey:l}}if(e.additionalStateVariablesDefined&&a.push(...e.additionalStateVariablesDefined),e.returnDependencies=async function(n){n.arraySize=await e.arraySize;for(let e in n.stateValues)"__array_"===e.slice(0,8)&&delete n.stateValues[e];if(void 0===n.arrayKeys&&(n.arrayKeys=e.getAllArrayKeys(n.arraySize)),!e.dependencyNames&&(e.dependencyNames={namesByKey:{},keysByName:{},global:[]},e.additionalStateVariablesDefined))for(let n of e.additionalStateVariablesDefined)t.state[n].dependencyNames=e.dependencyNames;let r={};if(e.basedOnArrayKeyStateVariables&&n.arrayKeys.length>1)for(let e of n.arrayKeys)for(let n of a){let a=t.state[n];r[n+"_"+e]={dependencyType:"stateVariable",variableName:a.arrayVarNameFromArrayKey(e)}}else{let t=e.returnArrayDependenciesByKey(n);t.globalDependencies&&(e.dependencyNames.global=Object.keys(t.globalDependencies),Object.assign(r,t.globalDependencies)),t.dependenciesByKey||(t.dependenciesByKey={});for(let a of n.arrayKeys){a in e.dependencyNames.namesByKey||(n.changedDependency=!0),e.dependencyNames.namesByKey[a]={};for(let n in t.dependenciesByKey[a]){let i="__"+a+"_"+n;r[i]=t.dependenciesByKey[a][n],e.dependencyNames.namesByKey[a][n]=i,e.dependencyNames.keysByName[i]||(e.dependencyNames.keysByName[i]=[]),e.dependencyNames.keysByName[i].includes(a)||e.dependencyNames.keysByName[i].push(a)}}e.dependencyNames.global.push("__array_size")}return r.__array_size={dependencyType:"stateVariable",variableName:e.arraySizeStateVariable},r},e.getCurrentFreshness=function({freshnessInfo:t,arrayKeys:r,arraySize:a}){void 0===r&&(r=e.getAllArrayKeys(a));let i=t.freshByKey,s=t.freshArraySize?1:0;for(let e of r)i[e]&&(s+=1);return s>0?s===r.length+1?{fresh:{[n]:!0}}:{partiallyFresh:{[n]:s}}:{fresh:{[n]:!1}}},e.markStale=function({freshnessInfo:t,changes:r,arrayKeys:a,arraySize:i}){let s={};void 0===a&&(a=e.getAllArrayKeys(i)),e.markStaleByKey&&(s=e.markStaleByKey({arrayKeys:a,changes:r}));let o=t.freshByKey;if(r.__array_size)return t.freshArraySize=!1,t.freshByKey={},s.fresh={[n]:!1},s;if(0===Object.keys(o).length)return t.freshByKey={},t.freshArraySize?(s.partiallyFresh={[n]:1},s):(s.fresh={[n]:!1},s);for(let i in r){if(e.dependencyNames.global.includes(i))return t.freshByKey={},t.freshArraySize?(s.partiallyFresh={[n]:1},s):(s.fresh={[n]:!1},s);if(e.basedOnArrayKeyStateVariables&&a.length>1)delete o[i];else for(let t of e.dependencyNames.keysByName[i])delete o[t]}let l=t.freshArraySize?1:0;for(let e of a)o[e]&&(l+=1);return l>0?l===a.length+1?(s.fresh={[n]:!0},s):(s.partiallyFresh={[n]:l},s):(s.fresh={[n]:!1},s)},e.freshenOnNoChanges=function({arrayKeys:t,freshnessInfo:n,arraySize:r}){let a=n.freshByKey;void 0===t&&(t=e.getAllArrayKeys(r));for(let e of t)a[e]=!0},e.definition=function(r){if(void 0===r.arrayKeys&&(r.arrayKeys=e.getAllArrayKeys(r.arraySize)),e.basedOnArrayKeyStateVariables&&r.arrayKeys.length>1)return{};{let a=i(r.dependencyValues,r.arrayKeys,r.usedDefault),s=a.globalDependencyValues,o=a.globalUsedDefault,l=a.dependencyValuesByKey,u=a.usedDefaultByKey,c=a.foundAllDependencyValuesForKey;delete r.dependencyValues,r.globalDependencyValues=s,r.globalUsedDefault=o,r.dependencyValuesByKey=l,r.usedDefaultByKey=u;let p,d=[],m=r.freshnessInfo.freshByKey;for(let e of r.arrayKeys)!m[e]&&c[e]&&(m[e]=!0,d.push(e));if(0===d.length)p={};else{if(r.arrayKeys=d,!e.arrayDefinitionByKey)throw Error(`For ${n} of ${t.componentType}, arrayDefinitionByKey must be a function`);if(p=e.arrayDefinitionByKey(r),p.setValue&&p.setValue[n])for(let e in p.setValue[n])m[e]=!0;if(p.useEssentialOrDefaultValue&&p.useEssentialOrDefaultValue[n])for(let e in p.useEssentialOrDefaultValue[n])m[e]=!0}if(!r.freshnessInfo.freshArraySize){if(r.changes.__array_size&&(p.arraySizeChanged=[n],e.additionalStateVariablesDefined))for(let n of e.additionalStateVariablesDefined)t.state[n].isArray&&p.arraySizeChanged.push(n);r.freshnessInfo.freshArraySize=!0}return p}},e.inverseDefinition=function(t){if(!e.inverseArrayDefinitionByKey)return{success:!1};if(void 0===t.arrayKeys&&(t.arrayKeys=e.getAllArrayKeys(t.arraySize)),e.basedOnArrayKeyStateVariables&&t.arrayKeys.length>1){let e=[];for(let n of a)for(let r in t.desiredStateVariableValues[n]){let a=n+"_"+r;a in t.dependencyValues&&e.push({setDependency:a,desiredValue:t.desiredStateVariableValues[n][r],treatAsInitialChange:t.initialChange})}return{success:!0,instructions:e}}{let n=i(t.dependencyValues,t.arrayKeys,t.usedDefault),r=n.globalDependencyValues,a=n.globalUsedDefault,s=n.dependencyValuesByKey,o=n.usedDefaultByKey;delete t.dependencyValues,t.globalDependencyValues=r,t.globalUsedDefault=a,t.dependencyValuesByKey=s,t.usedDefaultByKey=o,t.dependencyNamesByKey=e.dependencyNames.namesByKey;let l={};for(let e in t.desiredStateVariableValues)if(Array.isArray(t.desiredStateVariableValues[e]))l[e]=t.desiredStateVariableValues[e];else{l[e]={};for(let n in t.desiredStateVariableValues[e])t.arrayKeys.includes(n)&&(l[e][n]=t.desiredStateVariableValues[e][n])}return t.desiredStateVariableValues=l,e.inverseArrayDefinitionByKey(t)}},await this.createArraySizeStateVariable({stateVarObj:e,component:t,stateVariable:n}),e.arraySizeStale=!0,e.previousArraySize=[],Object.defineProperty(e,"arraySize",{get:function(){return(async()=>t.state[e.arraySizeStateVariable].initiallyResolved?(e.arraySizeStale&&await e.recalculateArraySizeDependentQuantities(),await t.stateValues[e.arraySizeStateVariable]):[])()}}),e.recalculateArraySizeDependentQuantities=async function(){let n=await t.stateValues[e.arraySizeStateVariable];if(e.previousArraySize.length!==n.length||e.previousArraySize.some(((e,t)=>e!=n[t]))){e.previousArraySize=[...n];let r=e.varNamesIncludingArrayKeys={};for(let a of e.arrayEntryNames){let i=t.state[a],s=e.getArrayKeysFromVarName({arrayEntryPrefix:i.entryPrefix,varEnding:i.varEnding,arraySize:n,nDimensions:e.nDimensions});i._unflattenedArrayKeys=s,i._arrayKeys=flattenDeep(s);for(let e of i._arrayKeys)r[e]||(r[e]=[]),r[e].push(a)}}e.arraySizeStale=!1},!e.freshnessInfo&&(e.freshnessInfo={freshByKey:{}},e.additionalStateVariablesDefined))for(let n of e.additionalStateVariablesDefined)t.state[n]||(t.state[n]={}),t.state[n].freshnessInfo=e.freshnessInfo}async createArraySizeStateVariable({stateVarObj:e,component:t,stateVariable:n}){let r=[n];e.additionalStateVariablesDefined&&r.push(...e.additionalStateVariablesDefined),r.sort();let a="__array_size_"+r.join("_");if(e.arraySizeStateVariable=a,e.stateVariablesDeterminingDependencies?(e.stateVariablesDeterminingDependencies,e.stateVariablesDeterminingDependencies.push(a)):e.stateVariablesDeterminingDependencies=[a],t.state[a]){if(t.state[a].isShadow){t.state[a].markStale=function(){for(let e of r)t.state[e].arraySizeStale=!0;return{}}}}else t.state[a]={returnDependencies:e.returnArraySizeDependencies,definition({dependencyValues:t}){let n=e.returnArraySize({dependencyValues:t});for(let[e,t]of n.entries())Number.isInteger(t)&&t>=0||(n[e]=0);return{setValue:{[a]:n}}},markStale(){for(let e of r)t.state[e].arraySizeStale=!0;return{}}},e.stateVariablesDeterminingArraySizeDependencies&&(t.state[a].stateVariablesDeterminingDependencies=e.stateVariablesDeterminingArraySizeDependencies),await this.initializeStateVariable({component:t,stateVariable:a})}async arrayEntryNamesFromPropIndex({stateVariables:e,component:t,propIndex:n}){let r=[];for(let a of e){let e,i=t.state[a];if(!i){if(!this.checkIfArrayEntry({stateVariable:a,component:t})){r.push(a);continue}await this.createFromArrayEntry({stateVariable:a,component:t}),i=t.state[a]}if(i.isArray)e=i.arrayVarNameFromPropIndex(n,a);else if(i.isArrayEntry){e=t.state[i.arrayStateVariable].arrayVarNameFromPropIndex(n,a)}else console.warn(`Cannot get propIndex from ${a} of ${t.componentName} as it is not an array or array entry state variable`),e=a;e?r.push(e):(console.warn(`Cannot get propIndex from ${a} of ${t.componentName}`),r.push(a))}return r}recursivelyReplaceCompositesWithReplacements({replacements:e,recurseNonStandardComposites:t=!1,forceExpandComposites:n=!1,includeWithheldReplacements:r=!1}){let a=[],i=[],s=[],o=[];for(let l of e)if(this.componentInfoObjects.isCompositeComponent({componentType:l.componentType,includeNonStandard:t}))if(a.push(l.componentName),l.isExpanded||(l.state.readyToExpandWhenResolved.isResolved?s.push(l.componentName):o.push(l.componentName)),l.isExpanded){let e=l.replacements;!r&&l.replacementsToWithhold>0&&(e=e.slice(0,-l.replacementsToWithhold));let u=this.recursivelyReplaceCompositesWithReplacements({replacements:e,recurseNonStandardComposites:t,forceExpandComposites:n,includeWithheldReplacements:r});a.push(...u.compositesFound),i.push(...u.newReplacements),s.push(...u.unexpandedCompositesReady),o.push(...u.unexpandedCompositesNotReady)}else i.push(l);else i.push(l);return{compositesFound:a,newReplacements:i,unexpandedCompositesReady:s,unexpandedCompositesNotReady:o}}async getStateVariableValue({component:e,stateVariable:t}){let n=e.state[t];if(!n)throw Error(`Can't get value of ${t} of ${e.componentName} as it doesn't exist.`);if(e.reprocessAfterEvaluate){let t=e.reprocessAfterEvaluate;delete this._components[e.componentName].reprocessAfterEvaluate;for(let n in t)e.state[n]&&await this.getStateVariableValue({component:e,stateVariable:n});await this.processNewStateVariableValues({[e.componentName]:t})}let r=n.additionalStateVariablesDefined,a=[t];r&&a.push(...r);let i=!1;for(let n of a){if(!e.state[n].isResolved){if(!(await this.dependencies.resolveItem({componentName:e.componentName,type:"stateVariable",stateVariable:n,force:!0})).success)throw Error(`Can't get value of ${t} of ${e.componentName} as ${n} couldn't be resolved.`)}e.state[n].justUpdatedForNewComponent&&(delete this._components[e.componentName].state[n].justUpdatedForNewComponent,i=!0)}let s=await this.getStateVariableDefinitionArguments({component:e,stateVariable:t});s.componentInfoObjects=this.componentInfoObjects,s.justUpdatedForNewComponent=i,s.freshnessInfo=n.freshnessInfo;let o,l=s.arraySize;if(0!==Object.keys(s.changes).length||void 0===n._previousValue||n.forceRecalculation)delete n.forceRecalculation,o=n.definition(s);else{let e=[t];r&&e.push(...r),o={noChanges:e},n.freshenOnNoChanges&&n.freshenOnNoChanges(s)}let u={[t]:!1},c={};if(r)for(let e of r)u[e]=!1;for(let n in o.setValue){if(!(n in e.state))throw Error(`Definition of state variable ${t} of ${e.componentName} returned value of ${n}, which isn't a state variable.`);let r;if(n in u)u[n]=!0,e.state[n].isArray?c[n]||(c[n]={arrayKeysChanged:{}}):c[n]=!0;else{if(e.state[n].isArray&&e.state[n].arrayEntryNames)for(let t of e.state[n].arrayEntryNames)if(t in u){r=t,u[t]=!0,c[t]=!0;break}if(!r)throw Error(`Attempting to set value of stateVariable ${n} in definition of ${t} of ${e.componentName}, but it's not listed as an additional state variable defined.`)}if(!(e.state[n].isResolved||r&&e.state[r].isResolved))throw Error(`Attempting to set value of stateVariable ${n} of ${e.componentName} while it is still unresolved!`);if(e.state[n].isArray){c[n]||(c[n]={arrayKeysChanged:{}});let t={};o.checkForActualChange&&o.checkForActualChange[n]&&(t=o.checkForActualChange[n]);for(let r in o.setValue[n])if(t[r]){e.state[n].getArrayValue({arrayKey:r})!==o.setValue[n][r]&&(e.state[n].setArrayValue({value:o.setValue[n][r],arrayKey:r,arraySize:l}),e.state[n].usedDefaultByArrayKey[r]=!1,c[n].arrayKeysChanged[r]=!0)}else e.state[n].setArrayValue({value:o.setValue[n][r],arrayKey:r,arraySize:l}),e.state[n].usedDefaultByArrayKey[r]=!1,c[n].arrayKeysChanged[r]=!0}else if(delete e.state[n].value,e.state[n].value=o.setValue[n],delete e.state[n].usedDefault,o.checkForActualChange?.[n]){let t=e.state[n].value,r=e.state[n]._previousValue;(t===r||Array.isArray(t)&&Array.isArray(r)&&t.length===r.length&&t.every(((e,t)=>e===r[t])))&&delete c[n]}}for(let n in o.useEssentialOrDefaultValue){if(!(n in e.state))throw Error(`Definition of state variable ${t} of ${e.componentName} requested essential or default value of ${n}, which isn't a state variable.`);if(!e.state[n].hasEssential)throw Error(`Definition of state variable ${t} of ${e.componentName} requested essential or default value of ${n}, but hasEssential is not set.`);let r;if(n in u)u[n]=!0,e.state[n].isArray?c[n]||(c[n]={arrayKeysChanged:{}}):c[n]=!0;else{if(e.state[n].isArray&&e.state[n].arrayEntryNames)for(let t of e.state[n].arrayEntryNames)if(t in u){r=t,u[t]=!0,c[t]=!0;break}if(!r)throw Error(`Attempting to set value of stateVariable ${n} in definition of ${t} of ${e.componentName}, but it's not listed as an additional state variable defined.`)}if(!(e.state[n].isResolved||r&&e.state[r].isResolved))throw Error(`Attempting to set value of stateVariable ${n} of ${e.componentName} while it is still unresolved!`);let a=n;e.state[n].essentialVarName&&(a=e.state[n].essentialVarName);let i=e.essentialState[a];if(e.state[n].isArray){c[n]||(c[n]={arrayKeysChanged:{}});let t={};o.checkForActualChange&&o.checkForActualChange[n]&&(t=o.checkForActualChange[n]);for(let r in o.useEssentialOrDefaultValue[n]){let s,u;if(t[r]&&(s=e.state[n].getArrayValue({arrayKey:r})),Array.isArray(i)?u=e.state[n].getArrayValue({arrayKey:r,arrayValues:i}):i=e.essentialState[a]=[],void 0!==u)e.state[n].setArrayValue({value:u,arrayKey:r,arraySize:l});else{let t=o.useEssentialOrDefaultValue[n][r].defaultValue;if(void 0!==t)e.state[n].setArrayValue({value:t,arrayKey:r,arraySize:l}),e.state[n].usedDefaultByArrayKey[r]=!0;else{if(void 0===e.state[n].defaultValueByArrayKey?.(r))throw Error(`Neither value nor default value specified; state variable: ${n}, component: ${e.componentName}, arrayKey: ${r}.`);e.state[n].setArrayValue({value:e.state[n].defaultValueByArrayKey(r),arrayKey:r,arraySize:l}),e.state[n].usedDefaultByArrayKey[r]=!0}}if(t[r]){e.state[n].getArrayValue({arrayKey:r})!==s&&(c[n].arrayKeysChanged[r]=!0)}else c[n].arrayKeysChanged[r]=!0}}else{if(void 0!==i)delete e.state[n].value,e.state[n].value=i;else{let t=o.useEssentialOrDefaultValue[n].defaultValue;if(void 0!==t)delete e.state[n].value,e.state[n].value=t,e.state[n].usedDefault=!0;else{if(void 0===e.state[n].defaultValue)throw Error(`Neither value nor default value specified; state variable: ${n}, component: ${e.componentName}.`);delete e.state[n].value,e.state[n].value=e.state[n].defaultValue,e.state[n].usedDefault=!0}}if(o.checkForActualChange?.[n]){let t=e.state[n].value,r=e.state[n]._previousValue;(t===r||Array.isArray(t)&&Array.isArray(r)&&t.length===r.length&&t.every(((e,t)=>e===r[t])))&&delete c[n]}}}for(let n in o.markAsUsedDefault){if(!e.state[n].isResolved)throw Error(`Marking state variable as used default when it isn't yet resolved: ${n} of ${e.componentName}`);if(!(n in u)){let r;if(e.state[n].isArray&&e.state[n].arrayEntryNames)for(let t of e.state[n].arrayEntryNames)if(t in u){r=t;break}if(!r)throw Error(`Marking state variable ${n} as used default in definition of ${t} of ${e.componentName}, but it's not listed as an additional state variable defined.`)}if(Array.isArray())for(let t in o.markAsUsedDefault[n])o.markAsUsedDefault[n][t]&&(e.state[n].usedDefaultByArrayKey[t]=!0);else o.markAsUsedDefault[n]&&(e.state[n].usedDefault=!0)}if(o.noChanges)for(let n of o.noChanges){if(e.state[n].isResolved||(e.state[n].isResolved=!0),!(n in u)){let r;if(e.state[n].isArray&&e.state[n].arrayEntryNames)for(let t of e.state[n].arrayEntryNames)if(t in u){r=t;break}if(!r)throw Error(`Claiming stateVariable ${n} is unchanged in definition of ${t} of ${e.componentName}, but it's not listed as an additional state variable defined.`)}u[n]=!0,(Object.getOwnPropertyDescriptor(e.state[n],"value").get||e.state[n].immutable)&&(delete e.state[n].value,e.state[n].value=e.state[n]._previousValue)}for(let n in o.setEssentialValue){if(!(n in e.state))throw Error(`Definition of state variable ${t} of ${e.componentName} tried to make ${n} essential, which isn't a state variable.`);if(!(n in u)){let r;if(e.state[n].isArray&&e.state[n].arrayEntryNames)for(let t of e.state[n].arrayEntryNames)if(t in u){r=t;break}if(!r)throw Error(`Attempting to set essential value of stateVariable ${n} in definition of ${t} of ${e.componentName}, but it's not listed as an additional state variable defined.`)}if(!e.state[n].hasEssential)throw Error(`Attempting to set the essential value of stateVariable ${n} in definition of ${t} of ${e.componentName}, but it does not have an essential value`);if(!e.state[n].shadowVariable&&!e.state[n].doNotShadowEssential)throw Error(`Attempting to set the essential value of stateVariable ${n} in definition of ${t} of ${e.componentName}, but it is not allowed unless the state variable is shadowed or the essential state is not shadowed.`);this.essentialValuesSavedInDefinition[e.componentName]||(this.essentialValuesSavedInDefinition[e.componentName]={});let r=n;if(e.state[n].essentialVarName&&(r=e.state[n].essentialVarName),e.state[n].isArray){let t=e.essentialState[r];Array.isArray(t)||(t=e.essentialState[r]=[]),this.essentialValuesSavedInDefinition[e.componentName][n]||(this.essentialValuesSavedInDefinition[e.componentName][n]={mergeObject:!0});for(let r in o.setEssentialValue[n])e.state[n].setArrayValue({value:o.setEssentialValue[n][r],arrayKey:r,arraySize:l,arrayValues:t}),this.essentialValuesSavedInDefinition[e.componentName][n][r]=o.setEssentialValue[n][r]}else e.essentialState[r]=o.setEssentialValue[n],this.essentialValuesSavedInDefinition[e.componentName][n]=o.setEssentialValue[n]}if(o.setCreateComponentOfType)for(let t in o.setCreateComponentOfType){if(!e.state[t].shadowingInstructions?.hasVariableComponentType)throw Error(`Cannot set type of ${t} of ${e.componentName} as it it does not have the hasVariableComponentType attribute.`);let n=!1,r=e.state[t].shadowingInstructions;r||(r=e.state[t].shadowingInstructions={});let a=r.createComponentOfType,i=o.setCreateComponentOfType[t];if(Array.isArray(a)?Array.isArray(i)?(a.length!==i.length||a.some(((e,t)=>e!=i[t])))&&(n=!0):n=!0:n=!!Array.isArray(i)||a!==i,n&&(c[t]=!0),r.createComponentOfType=o.setCreateComponentOfType[t],e.state[t].isArray&&e.state[t].arrayEntryNames){let n=o.setCreateComponentOfType[t],r=Array.isArray(n);for(let a of e.state[t].arrayEntryNames)if(r){let r=await e.state[a].arrayKeys,i=[];for(let a of r){let r=e.state[t].keyToIndex(a);i.push(n[r])}e.state[a].shadowingInstructions.createComponentOfType=i}else e.state[a].shadowingInstructions.createComponentOfType=n}}if(o.arraySizeChanged)for(let t of o.arraySizeChanged)await e.state[t].adjustArrayToNewArraySize(),void 0===c[t]?c[t]={arrayKeysChanged:{}}:!0===c[t]&&(c[t]={allArrayKeysChanged:!0,arrayKeysChanged:{}}),c[t].arraySizeChanged=!0;for(let n in u){if(!(u[n]||e.state[n].isArrayEntry||e.state[n].isArray))throw Error(`definition of ${t} of ${e.componentName} didn't return value of ${n}`);e.state[n].isArray?(delete e.state[n].value,e.state[n].value=e.state[n].arrayValues):e.state[n].isArrayEntry&&(delete e.state[n].value,e.state[n].value=await e.state[n].getValueFromArrayValues())}for(let t in c)if(this.dependencies.recordActualChangeInUpstreamDependencies({component:e,varName:t,changes:c[t]}),e.state[t].isArray){let n=[];if(!0===c[t]||c[t].allArrayKeysChanged||c.arraySizeChanged)e.state[t].arrayEntryNames&&(n=e.state[t].arrayEntryNames);else{let r=e.state[t].varNamesIncludingArrayKeys;for(let e in c[t].arrayKeysChanged){let t=r[e];t&&n.push(...t)}}n=[...new Set(n)];for(let t of n)this.dependencies.recordActualChangeInUpstreamDependencies({component:e,varName:t})}return await n.value}async getStateVariableDefinitionArguments({component:e,stateVariable:t,excludeDependencyValues:n}){let r;r=n?{}:await this.dependencies.getStateVariableDependencyValues({component:e,stateVariable:t}),r.componentName=e.componentName;let a=e.state[t];if(a.isArrayEntry?(r.arrayKeys=await a.arrayKeys,r.arraySize=await a.arraySize):a.isArray&&(r.arraySize=await a.arraySize),a.createWorkspace&&(r.workspace=a.workspace),a.providePreviousValuesInDefinition||a.provideEssentialValuesInDefinition){let n=[t];if(a.additionalStateVariablesDefined&&n.push(...a.additionalStateVariablesDefined),a.providePreviousValuesInDefinition){let t={};for(let r of n)e.state[r].isArrayEntry&&(r=e.state[r].arrayStateVariable),t[r]=e.state[r]._previousValue;r.previousValues=t}if(a.provideEssentialValuesInDefinition){let t={};for(let r of n){e.state[r].isArrayEntry&&(r=e.state[r].arrayStateVariable);let n=r;e.state[r].essentialVarName&&(n=e.state[r].essentialVarName),t[r]=e.essentialState[n]}r.essentialValues=t}}return r}async recordActualChangeInStateVariable({componentName:e,varName:t}){let n=this._components[e];await this.markStateVariableAndUpstreamDependentsStale({component:n,varName:t});let r=[t];n.state[t].additionalStateVariablesDefined&&r.push(...n.state[t].additionalStateVariablesDefined);for(let e of r)n.state[e].forceRecalculation=!0,this.dependencies.recordActualChangeInUpstreamDependencies({component:n,varName:e})}findCaseInsensitiveMatches({stateVariables:e,componentClass:t}){let n=this.componentInfoObjects.stateVariableInfo[t.componentType],r=[];for(let t of e){let e=!1,a=t.toLowerCase();for(let t in n.stateVariableDescriptions)if(a===t.toLowerCase()){e=!0,r.push(t);break}if(e)continue;let i=!1,s=a;"__array_size_"===a.substring(0,13)&&(i=!0,s=a.substring(13));for(let t in n.aliases)if(s===t.toLowerCase()){i&&(t="__array_size_"+t),r.push(t),e=!0;break}if(e)continue;let o=Object.keys(n.arrayEntryPrefixes).sort(((e,t)=>t.length-e.length));for(let i of o)if(a.substring(0,i.length)===i.toLowerCase()){let s=n.arrayEntryPrefixes[i].arrayVariableName,o=n.stateVariableDescriptions[s];if(o.getArrayKeysFromVarName({arrayEntryPrefix:i,varEnding:t.substring(i.length),nDimensions:o.nDimensions}).length>0){let t=i+a.substring(i.length);e=!0,r.push(t);break}}e||r.push(t)}return r}matchPublicStateVariables({stateVariables:e,componentClass:t}){let n=this.componentInfoObjects.publicStateVariableInfo[t.componentType],r=[];for(let t of e){if(t in n.stateVariableDescriptions){r.push(t);continue}let e=t;if(e in n.aliases&&(e=n.aliases[e],e in n.stateVariableDescriptions)){r.push(e);continue}let a=!1,i=Object.keys(n.arrayEntryPrefixes).sort(((e,t)=>t.length-e.length));for(let t of i)if(e.substring(0,t.length)===t){let r=n.arrayEntryPrefixes[t].arrayVariableName,i=n.stateVariableDescriptions[r];if(i.getArrayKeysFromVarName({arrayEntryPrefix:t,varEnding:e.substring(t.length),nDimensions:i.nDimensions}).length>0){a=!0;break}}a?r.push(t):r.push("__not_public_"+t)}return r}substituteAliases({stateVariables:e,componentClass:t}){let n=[],r=this.componentInfoObjects.stateVariableInfo[t.componentType];for(let t of e){let e=!1;"__array_size_"===t.substring(0,13)&&(e=!0,t=t.substring(13)),t=t in r.aliases?r.aliases[t]:t,e&&(t="__array_size_"+t),n.push(t)}return n}publicCaseInsensitiveAliasSubstitutions({stateVariables:e,componentClass:t}){let n=this.findCaseInsensitiveMatches({stateVariables:e,componentClass:t});return n=this.matchPublicStateVariables({stateVariables:n,componentClass:t}),n=this.substituteAliases({stateVariables:n,componentClass:t}),n}checkIfArrayEntry({stateVariable:e,component:t}){for(let n in t.arrayEntryPrefixes)if(e.substring(0,n.length)===n){let r=t.arrayEntryPrefixes[n],a=t.state[r];if(a.getArrayKeysFromVarName({arrayEntryPrefix:n,varEnding:e.substring(n.length),nDimensions:a.nDimensions}).length>0)return!0}return!1}async createFromArrayEntry({stateVariable:e,component:t,initializeOnly:n=!1}){if(!t.arrayEntryPrefixes)throw Error(`Unknown state variable ${e} of ${t.componentName}`);let r=Object.keys(t.arrayEntryPrefixes).sort(((e,t)=>t.length-e.length));for(let a of r)if(e.substring(0,a.length)===a){let r=t.arrayEntryPrefixes[a],i=t.state[r];if(i.getArrayKeysFromVarName({arrayEntryPrefix:a,varEnding:e.substring(a.length),nDimensions:i.nDimensions}).length>0){let r=t.arrayEntryPrefixes[a];if(await this.initializeStateVariable({component:t,stateVariable:e,arrayStateVariable:r,arrayEntryPrefix:a}),n)return;let i=[e];if(t.state[e].additionalStateVariablesDefined){i.push(...t.state[e].additionalStateVariablesDefined);for(let n of t.state[e].additionalStateVariablesDefined)t.state[n]||await this.createFromArrayEntry({stateVariable:n,component:t,initializeOnly:!0})}await this.dependencies.setUpStateVariableDependencies({component:t,stateVariable:e,allStateVariablesAffected:i,core:this});let s=[];for(let e of i)this.dependencies.checkForCircularDependency({componentName:t.componentName,varName:e}),s.push(e),t.state[e].determineDependenciesStateVariable&&s.push(t.state[e].determineDependenciesStateVariable);return void await this.dependencies.resolveStateVariablesIfReady({component:t,stateVariables:s})}}throw Error(`Unknown state variable ${e} of ${t.componentName}`)}async markStateVariableAndUpstreamDependentsStale({component:e,varName:t}){t in this.rendererVariablesByComponentType[e.componentType]&&this.updateInfo.componentsToUpdateRenderers.add(e.componentName);let n={[t]:e.state[t]};e.state[t].additionalStateVariablesDefined&&e.state[t].additionalStateVariablesDefined.forEach((t=>n[t]=e.state[t]));let r=await this.lookUpCurrentFreshness({component:e,varName:t,allStateVariablesAffectedObj:n}),a=[],i=[],s=0;for(let e in n){let t=n[e];Object.getOwnPropertyDescriptor(t,"value").get||t.immutable?r&&(r.fresh&&r.fresh[e]?i.push(e):r.partiallyFresh&&r.partiallyFresh[e]&&(s+=r.partiallyFresh[e])):a.push(e)}i.push(...a);let o=i.length>0||s>0,l={};for(let e in n)l[e]=!0;let u=!1;if(o){let r=await this.processMarkStale({component:e,varName:t,allStateVariablesAffectedObj:n});if(r.fresh)for(let e in r.fresh)r.fresh[e]&&delete l[e];let a=0;for(let e in n){if(i.includes(e)&&(!r.fresh||!r.fresh[e])){u=!0;break}r.partiallyFresh&&r.partiallyFresh[e]&&(a+=r.partiallyFresh[e])}if(an({component:e,stateVariable:t}),configurable:!0})}}if(u)for(let t in l)await this.markUpstreamDependentsStale({component:e,varName:t})}async lookUpCurrentFreshness({component:e,varName:t,allStateVariablesAffectedObj:n}){let r=e.state[t];if(!r.getCurrentFreshness)return;let a,i,s=r.freshnessInfo;if(r.isArrayEntry&&(a=r._arrayKeys),r.isArrayEntry||r.isArray){let t=e.state[r.arraySizeStateVariable];i=t._previousValue,!(Object.getOwnPropertyDescriptor(t,"value").get||t.immutable)&&(i=await t.value),Array.isArray(i)||(i=[])}let o=r.getCurrentFreshness({freshnessInfo:s,arrayKeys:a,arraySize:i});if(o.partiallyFresh)for(let e in n)if(n[e].isArrayEntry){let t=n[e].arrayStateVariable;o.partiallyFresh[e]=o.partiallyFresh[t],delete o.partiallyFresh[t]}if(o.fresh)for(let e in n)if(n[e].isArrayEntry){let t=n[e].arrayStateVariable;t in o.fresh&&(o.fresh[e]=o.fresh[t],delete o.fresh[t])}return o}async processMarkStale({component:e,varName:t,allStateVariablesAffectedObj:n}){let r=e.state[t];if(!r.markStale||!r.initiallyResolved){let e={};return Object.keys(n).forEach((t=>e[t]=!1)),{fresh:e}}let a={},i=this.dependencies.downstreamDependencies[e.componentName][t];for(let e in i){let t=i[e],n={},r=!1;t.componentIdentityChanged&&(n.componentIdentityChanged=!0,r=!0),t.componentIdentitiesChanged&&(n.componentIdentitiesChanged=!0,r=!0),t.valuesChanged&&(n.valuesChanged=t.valuesChanged,r=!0),r&&(a[e]=n)}let s,o,l=r.freshnessInfo;if(r.isArrayEntry&&(s=r._arrayKeys),r.isArrayEntry||r.isArray){let t=e.state[r.arraySizeStateVariable];o=t._previousValue,!(Object.getOwnPropertyDescriptor(t,"value").get||t.immutable)&&(o=await t.value),Array.isArray(o)||(o=[])}let u=r.markStale({freshnessInfo:l,changes:a,arrayKeys:s,arraySize:o});if(u.partiallyFresh)for(let e in n)if(n[e].isArrayEntry){let t=n[e].arrayStateVariable;u.partiallyFresh[e]=u.partiallyFresh[t],delete u.partiallyFresh[t]}if(u.fresh)for(let e in n)if(n[e].isArrayEntry){let t=n[e].arrayStateVariable;t in u.fresh&&(u.fresh[e]=u.fresh[t],delete u.fresh[t])}return u}async markUpstreamDependentsStale({component:e,varName:t}){let n,r=e.componentName,a=this.getStateVariableValue,i=this.dependencies.upstreamDependencies[r][t];if(e.state[t]&&(n=e.state[t].freshnessInfo),i)for(let s of i){let i=!1;if(s.markStale&&await s.markStale(),s.downstreamComponentNames){let e=s.downstreamComponentNames.indexOf(r);if(-1===e)continue;if(s.mappedDownstreamVariableNamesByComponent){if(-1===s.mappedDownstreamVariableNamesByComponent[e].indexOf(t))throw Error(`something went wrong as ${t} not a downstreamVariable of ${s.dependencyName}`);"determineDependencies"===s.dependencyType&&(s.recalculateDependencies=!0),s.valuesChanged||(s.valuesChanged=[]),s.valuesChanged[e]||(s.valuesChanged[e]={}),s.valuesChanged[e][t]||(s.valuesChanged[e][t]={}),s.valuesChanged[e][t].potentialChange=!0,n&&(s.valuesChanged[e][t].freshnessInfo=n),i=!0}else t===s.downstreamVariableNameIfNoVariables&&(s.valuesChanged||(s.valuesChanged={[s.downstreamVariableNameIfNoVariables]:{}}),s.componentIdentityChanged=!0,s.valuesChanged[s.downstreamVariableNameIfNoVariables].potentialChange=!0,i=!0)}if(i){for(let e of s.upstreamVariableNames)if(e in this.rendererVariablesByComponentType[this.components[s.upstreamComponentName].componentType]){this.updateInfo.componentsToUpdateRenderers.add(s.upstreamComponentName);break}let t=s.upstreamVariableNames[0],n=this._components[s.upstreamComponentName],r={};s.upstreamVariableNames.forEach((e=>r[e]=n.state[e]));let i=await this.lookUpCurrentFreshness({component:n,varName:t,allStateVariablesAffectedObj:r}),o=[],l=[],u=0;for(let e in r){let t=r[e];Object.getOwnPropertyDescriptor(t,"value").get||t.immutable?i&&(i.fresh&&i.fresh[e]?l.push(e):i.partiallyFresh&&i.partiallyFresh[e]&&(u+=i.partiallyFresh[e])):o.push(e)}l.push(...o);let c=l.length>0||u>0,p={};for(let e in r)p[e]=!0;let d=!1;if(c){let a=await this.processMarkStale({component:n,varName:t,allStateVariablesAffectedObj:r});if(a.fresh)for(let e in a.fresh)a.fresh[e]&&delete p[e];let i=0;for(let e in r){if(l.includes(e)&&(!a.fresh||!a.fresh[e])){d=!0;break}a.partiallyFresh&&a.partiallyFresh[e]&&(i+=a.partiallyFresh[e])}if(ia({component:n,stateVariable:e}),configurable:!0}))}if(d)for(let e in p)await this.markUpstreamDependentsStale({component:n,varName:e})}}}registerComponent(e){if(e.componentName in this._components)throw Error(`Duplicate componentName: ${e.componentName}`);this._components[e.componentName]=e}deregisterComponent(e,t=!0){if(!0===t)for(let t in e.allChildren)this.deregisterComponent(e.allChildren[t].component);delete this._components[e.componentName]}setAncestors(e,t=[]){e.ancestors=t;let n=[{componentName:e.componentName,componentClass:e.constructor},...e.ancestors];for(let t in e.allChildren){let e=this._components[t];this.setAncestors(e,n)}for(let t in e.attributes){let r=e.attributes[t].component;r&&this.setAncestors(r,n)}}async addChildrenAndRecurseToShadows({parent:e,indexOfDefiningChildren:t,newChildren:n,assignNamesOffset:r}){this.spliceChildren(e,t,n);let a=await this.processNewDefiningChildren({parent:e}),i={};if(!a.success)return a;for(let e of n)"object"==typeof e&&(i[e.componentName]=e);if(e.shadowedBy)for(let a of e.shadowedBy){if(a.shadows.propVariable)continue;let e=this._components[a.shadows.compositeName],s=await e.stateValues.sourceAttributesToIgnore,o=await e.stateValues.sourceAttributesToIgnoreRecursively,l=[];for(let e of n)"object"==typeof e?l.push(await e.serialize({sourceAttributesToIgnore:s,sourceAttributesToIgnoreRecursively:o})):l.push(e);l=postProcessCopy({serializedComponents:l,componentName:a.shadows.compositeName});let u=a.attributes.newNamespace?.primitive,c=u;l=processAssignNames({indOffset:r,serializedComponents:l,parentName:a.componentName,parentCreatesNewNamespace:u,componentInfoObjects:this.componentInfoObjects,originalNamesAreConsistent:c}).serializedComponents;let p,d=this._components[a.componentName];this.parameterStack.push(d.sharedParameters,!1),p=u?a.componentName+"/":getNamespaceFromName(a.componentName);let m=await this.createIsolatedComponentsSub({serializedComponents:l,ancestors:a.ancestors,createNameContext:a.componentName+"|addChildren|"+r,namespaceForUnamed:p});this.parameterStack.pop();let h=await this.addChildrenAndRecurseToShadows({parent:d,indexOfDefiningChildren:t,newChildren:m.components,assignNamesOffset:r});if(!h.success)throw Error("was able to add components to parent but not shadows!");Object.assign(i,h.addedComponents)}return{success:!0,deletedComponents:{},addedComponents:i}}async processNewDefiningChildren({parent:e,expandComposites:t=!0}){this.parameterStack.push(e.sharedParameters,!1);let n=await this.deriveChildResultsFromDefiningChildren({parent:e,expandComposites:t});this.parameterStack.pop();let r=[{componentName:e.componentName,componentClass:e.constructor},...e.ancestors];for(let t in e.allChildren){let e=this._components[t];this.setAncestors(e,r)}return n}spliceChildren(e,t,n){let r=e.definingChildren.length;if(!Number.isInteger(t)||t>r||t<0)throw Error("Can't add children at index "+t+". Invalid index.");e.definingChildren.splice(t,0,...n)}async deleteComponents({components:e,deleteUpstreamDependencies:t=!0,skipProcessingChildrenOfParents:n=[]}){Array.isArray(e)||(e=[e]);const r={};this.determineComponentsToDelete({components:e,deleteUpstreamDependencies:t,componentsToDelete:r});const a={};for(let e in r){let t=r[e],n=this.components[t.parentName];if(void 0===n||n.componentName in r)continue;let i=a[t.parentName];void 0===i&&(i={parent:this._components[t.parentName],childNamesToBeDeleted:new Set},a[t.parentName]=i),i.childNamesToBeDeleted.add(e)}let i=[];for(let e in r){let t=this._components[e];if(t.replacementOf){let n=t.replacementOf,r=n.replacements.map((e=>e.componentName)),a=r.indexOf(e);-1!==a&&(n.replacements.splice(a,1),i.includes(n.componentName)||i.push(n.componentName))}}for(let e of i)e in r||await this.dependencies.addBlockersFromChangedReplacements(this._components[e]);let s=[];for(let e in a){let t=a[e],r=t.parent;s.push(r);for(let e=r.definingChildren.length-1;e>=0;e--){let n=r.definingChildren[e];t.childNamesToBeDeleted.has(n.componentName)&&r.definingChildren.splice(e,1)}n.includes(r.componentName)||await this.processNewDefiningChildren({parent:r,expandComposites:!1})}for(let e in r){let t=this._components[e];if(t.shadows){let e=this._components[t.shadows.componentName];1===e.shadowedBy.length?delete e.shadowedBy:e.shadowedBy.splice(e.shadowedBy.indexOf(t),1)}this.dependencies.deleteAllDownstreamDependencies({component:t});for(let e in this.dependencies.upstreamDependencies[t.componentName]){let n=this.dependencies.upstreamDependencies[t.componentName][e];for(let e of n)if(e.specifiedComponentName&&e.specifiedComponentName in r){let t=this.dependencies.updateTriggers.dependenciesMissingComponentBySpecifiedName[e.specifiedComponentName];t||(t=this.dependencies.updateTriggers.dependenciesMissingComponentBySpecifiedName[e.specifiedComponentName]=[]),t.includes(e)||t.push(e)}}await this.dependencies.deleteAllUpstreamDependencies({component:t}),this.updateInfo.deletedStateVariables[t.componentName]||(this.updateInfo.deletedStateVariables[t.componentName]=[]),this.updateInfo.deletedStateVariables[t.componentName].push(...Object.keys(t.state)),this.updateInfo.deletedComponents[t.componentName]=!0,delete this.unmatchedChildren[t.componentName],delete this.stateVariableChangeTriggers[t.componentName]}for(let e in r){let t=this._components[e];this.deregisterComponent(t,!1),this.updateInfo.componentsToUpdateRenderers.delete(e),this.updateInfo.compositesToUpdateReplacements.delete(e),this.updateInfo.inactiveCompositesToUpdateReplacements.delete(e)}return{success:!0,deletedComponents:r,parentsOfDeleted:s}}determineComponentsToDelete({components:e,deleteUpstreamDependencies:t,componentsToDelete:n}){for(let r of e){if("object"!=typeof r)continue;if(r.componentName in n)continue;n[r.componentName]=this._components[r.componentName];let e=Object.values(r.allChildren).map((e=>e.component));for(let t in r.attributes){let n=r.attributes[t].component;n&&e.push(n)}void 0!==r.adaptedFrom&&e.push(r.adaptedFrom),!0===t&&(r.shadowedBy&&e.push(...r.shadowedBy),r.adapterUsed&&e.push(r.adapterUsed),r.replacements&&e.push(...r.replacements)),this.determineComponentsToDelete({components:e,deleteUpstreamDependencies:t,componentsToDelete:n})}}async updateCompositeReplacements({component:e,componentChanges:t,sourceOfUpdate:n}){let r={},a={},i=new Set;if(e.shadows){return{success:!0,deletedComponents:r,addedComponents:a,parentsOfDeleted:i}}let s=this.components[e.componentName];e.replacements||(e.replacements=[]),await e.stateValues.readyToExpandWhenResolved;const o=await e.constructor.calculateReplacementChanges({component:s,componentChanges:t,components:this.components,workspace:e.replacementsWorkspace,componentInfoObjects:this.componentInfoObjects,flags:this.flags,resolveItem:this.dependencies.resolveItem.bind(this.dependencies),publicCaseInsensitiveAliasSubstitutions:this.publicCaseInsensitiveAliasSubstitutions.bind(this)});e.constructor.stateVariableToEvaluateAfterReplacements&&await e.stateValues[e.constructor.stateVariableToEvaluateAfterReplacements];for(let s of o)if("add"===s.changeType){void 0!==s.replacementsToWithhold&&await this.adjustReplacementsToWithhold({component:e,change:s,componentChanges:t});let o,l=this._components[e.componentName];this.parameterStack.push(l.sharedParameters,!1);let u={[e.componentName]:calculateAllComponentsShadowing(e)},c=s.numberReplacementsToReplace,p=s.firstReplacementInd;if(c>0&&s.changeTopLevelReplacements&&await this.deleteReplacementsFromShadowsThenComposite({change:s,composite:e,componentChanges:t,sourceOfUpdate:n,parentsOfDeleted:i,deletedComponents:r,addedComponents:a,processNewChildren:!1}),!s.serializedReplacements)throw Error("Invalid replacement change.");{let t,n=s.serializedReplacements;t=e.attributes.newNamespace?.primitive?e.componentName+"/":getNamespaceFromName(e.componentName),o=(await this.createIsolatedComponentsSub({serializedComponents:n,ancestors:e.ancestors,createNameContext:e.componentName+"|replacements",namespaceForUnamed:t,componentsReplacementOf:e})).components}this.parameterStack.pop();let d={[e.componentName]:{newComponents:o,parent:s.parent}};if(l.shadowedBy&&u[l.componentName].length>0){let e=await this.createShadowedReplacements({replacementsToShadow:o,componentToShadow:l,parentToShadow:s.parent,currentShadowedBy:u,assignNamesOffset:s.assignNamesOffset,componentChanges:t,sourceOfUpdate:n,parentsOfDeleted:i,deletedComponents:r,addedComponents:a});Object.assign(d,e)}for(let e in d){let n=this._components[e];if(!n)continue;let r=d[e].newComponents;if(n.isExpanded){for(let e of r)"object"==typeof e&&(a[e.componentName]=e);if(!0===s.changeTopLevelReplacements){let e=this._components[n.parentName];n.replacements.splice(p,0,...r),await this.dependencies.addBlockersFromChangedReplacements(n);let a={changeType:"addedReplacements",composite:n,newReplacements:r,topLevel:!0,firstIndex:p,numberDeleted:c};t.push(a),await this.processNewDefiningChildren({parent:e,expandComposites:!1}),(await this.componentAndRenderedDescendants(e)).forEach((e=>this.updateInfo.componentsToUpdateRenderers.add(e)))}else{let i=this._components[d[e].parent.componentName];this.spliceChildren(i,s.indexOfDefiningChildren,r),await this.processNewDefiningChildren({parent:i});for(let e of r)"object"==typeof e&&(a[e.componentName]=e);(await this.componentAndRenderedDescendants(i)).forEach((e=>this.updateInfo.componentsToUpdateRenderers.add(e)));let o={changeType:"addedReplacements",composite:n,newReplacements:r};t.push(o)}}else{await this.expandCompositeComponent(n);let e={changeType:"addedReplacements",composite:n,newReplacements:n.replacements,topLevel:!0,firstIndex:0,numberDeleted:0};t.push(e)}}}else if("delete"===s.changeType)void 0!==s.replacementsToWithhold&&await this.adjustReplacementsToWithhold({component:e,change:s,componentChanges:t}),await this.deleteReplacementsFromShadowsThenComposite({change:s,composite:e,componentsToDelete:s.components,componentChanges:t,sourceOfUpdate:n,parentsOfDeleted:i,deletedComponents:r,addedComponents:a});else if("updateStateVariables"===s.changeType){let e={},t={};for(let n in s.stateChanges){let r={componentName:s.component.componentName,stateVariable:n,value:s.stateChanges[n],overrideFixed:!0};await this.requestComponentChanges({instruction:r,initialChange:!1,workspace:e,newStateVariableValues:t})}await this.processNewStateVariableValues(t)}else"changeReplacementsToWithhold"===s.changeType&&(void 0!==s.replacementsToWithhold&&await this.adjustReplacementsToWithhold({component:e,change:s,componentChanges:t}),await this.processChildChangesAndRecurseToShadows(e));return{success:!0,deletedComponents:r,addedComponents:a,parentsOfDeleted:i}}async deleteReplacementsFromShadowsThenComposite({change:e,composite:t,componentsToDelete:n,componentChanges:r,sourceOfUpdate:a,parentsOfDeleted:i,deletedComponents:s,addedComponents:o,processNewChildren:l=!0}){let u=[];if(!t.isExpanded)return u;if(t.shadowedBy)for(let c of t.shadowedBy){if(c.shadows.propVariable)continue;let t;if(n){t=[];for(let e of n){let n;if(e.shadowedBy)for(let t of e.shadowedBy)if(!t.shadows.propVariable&&t.shadows.compositeName===c.shadows.compositeName){n=t;break}n?t.push(n):console.error(`could not find shadowing component of ${e.componentName}`)}}let p=await this.deleteReplacementsFromShadowsThenComposite({change:e,composite:c,componentsToDelete:t,componentChanges:r,sourceOfUpdate:a,parentsOfDeleted:i,deletedComponents:s,addedComponents:o,processNewChildren:l});u.push(...p)}if(e.changeTopLevelReplacements){let n=e.firstReplacementInd,o=e.numberReplacementsToDelete;"add"===e.changeType&&(o=e.numberReplacementsToReplace);let u=t.replacements.splice(n,o);await this.dependencies.addBlockersFromChangedReplacements(t);let c=await this.deleteComponents({components:u,componentChanges:r,sourceOfUpdate:a,skipProcessingChildrenOfParents:[t.parentName]});if(l&&await this.processNewDefiningChildren({parent:this._components[t.parentName],expandComposites:!1}),!1===c.success)throw Error("Couldn't delete components on composite update");for(let e of c.parentsOfDeleted){i.add(e.componentName),(await this.componentAndRenderedDescendants(e)).forEach((e=>this.updateInfo.componentsToUpdateRenderers.add(e)))}let p={};for(let e in c.deletedComponents){let t=c.deletedComponents[e].parentName;void 0===p[t]&&(p[t]=[]),p[t].push(e)}let d={changeType:"deletedReplacements",composite:t,topLevel:!0,firstIndex:n,numberDeleted:o,deletedNamesByParent:p,deletedComponents:c.deletedComponents};r.push(d),Object.assign(s,c.deletedComponents);let m=this._components[t.parentName];(await this.componentAndRenderedDescendants(m)).forEach((e=>this.updateInfo.componentsToUpdateRenderers.add(e)))}else{let e=n.length,l=await this.deleteComponents({components:n,deleteUpstreamDependencies:!1,componentChanges:r,sourceOfUpdate:a});if(!1===l.success)throw Error("Couldn't delete components prescribed by composite");for(let e of l.parentsOfDeleted){i.add(e.componentName),(await this.componentAndRenderedDescendants(e)).forEach((e=>this.updateInfo.componentsToUpdateRenderers.add(e)))}let u={};for(let e in l.deletedComponents){let t=l.deletedComponents[e].parentName;void 0===u[t]&&(u[t]=[]),u[t].push(e)}let c={changeType:"deletedReplacements",composite:t,numberDeleted:e,deletedNamesByParent:u,deletedComponents:l.deletedComponents};r.push(c),Object.assign(s,l.deletedComponents),Object.assign(o,l.addedComponents)}return u}async processChildChangesAndRecurseToShadows(e){let t=this._components[e.parentName];if(await this.processNewDefiningChildren({parent:t,expandComposites:!1}),(await this.componentAndRenderedDescendants(t)).forEach((e=>this.updateInfo.componentsToUpdateRenderers.add(e))),e.shadowedBy)for(let t of e.shadowedBy)t.shadows.propVariable||await this.processChildChangesAndRecurseToShadows(t)}async createShadowedReplacements({replacementsToShadow:e,componentToShadow:t,parentToShadow:n,currentShadowedBy:r,assignNamesOffset:a,componentChanges:i,sourceOfUpdate:s,parentsOfDeleted:o,deletedComponents:l,addedComponents:u}){let c=calculateAllComponentsShadowing(t);if(!r[t.componentName]||!c.every((e=>r[t.componentName].includes(e))))throw Error(`circular reference involving ${t.componentName}`);this.updateInfo.compositesBeingExpanded.push(t.componentName);let p={};for(let c of t.shadowedBy)if(!c.shadows.propVariable){if(this.updateInfo.compositesBeingExpanded.includes(c.componentName))throw Error(`circular dependence involving ${c.componentName}`);if(c.shadowedBy&&(r[c.componentName]=calculateAllComponentsShadowing(c)),c.isExpanded){let t=[],d=this._components[c.shadows.compositeName],m=await d.stateValues.sourceAttributesToIgnore,h=await d.stateValues.sourceAttributesToIgnoreRecursively;for(let n of e)"object"==typeof n?t.push(await n.serialize({sourceAttributesToIgnore:m,sourceAttributesToIgnoreRecursively:h})):t.push(n);t=postProcessCopy({serializedComponents:t,componentName:c.shadows.compositeName});let f,y=c.attributes.newNamespace?.primitive;if(c.attributes.isResponse){let e=c.constructor.createAttributesObject();for(let n of t){if("object"!=typeof n)continue;n.attributes||(n.attributes={});let t=convertAttributesForComponentType({attributes:{isResponse:c.attributes.isResponse},componentType:n.componentType,componentInfoObjects:this.componentInfoObjects,compositeAttributesObj:e,compositeCreatesNewNamespace:y});Object.assign(n.attributes,t)}}if(c.constructor.assignNamesToReplacements){let e=c.shadows.compositeName,n=this.components[e],r=n.attributes.newNamespace?.primitive,i=n.doenetAttributes.assignNames,s=y||r&&!i,o=c.doenetAttributes.assignNames;o&&await c.stateValues.addLevelToAssignNames&&(o=o.map((e=>[e]))),t=processAssignNames({assignNames:o,indOffset:a,serializedComponents:t,parentName:c.componentName,parentCreatesNewNamespace:y,componentInfoObjects:this.componentInfoObjects,originalNamesAreConsistent:s}).serializedComponents}else{let e=y;t=processAssignNames({indOffset:a,serializedComponents:t,parentName:c.componentName,parentCreatesNewNamespace:y,componentInfoObjects:this.componentInfoObjects,originalNamesAreConsistent:e}).serializedComponents}let g,b=this._components[c.componentName];this.parameterStack.push(b.sharedParameters,!1),g=y?c.componentName+"/":getNamespaceFromName(c.componentName);let v,N=await this.createIsolatedComponentsSub({serializedComponents:t,ancestors:c.ancestors,createNameContext:c.componentName+"|replacements",namespaceForUnamed:g,componentsReplacementOf:c});if(this.parameterStack.pop(),f=N.components,n){if(n.shadowedBy)for(let e of n.shadowedBy)if(!e.shadows.propVariable&&e.shadows.compositeName===c.shadows.compositeName){v=e;break}v||console.error(`could not find shadowing parent of ${n.componentName}`)}if(p[c.componentName]={newComponents:f,parent:v},c.shadowedBy&&r[c.componentName].length>0){let e=await this.createShadowedReplacements({replacementsToShadow:f,componentToShadow:c,parentToShadow:v,currentShadowedBy:r,assignNamesOffset:a,componentChanges:i,sourceOfUpdate:s,parentsOfDeleted:o,deletedComponents:l,addedComponents:u});Object.assign(p,e)}}}let d=this.updateInfo.compositesBeingExpanded.indexOf(t.componentName);if(-1===d)throw Error(`Something is wrong as we lost track that we were expanding ${component.componentName}`);return this.updateInfo.compositesBeingExpanded.splice(d,1),p}async adjustReplacementsToWithhold({component:e,change:t,componentChanges:n}){let r,a=[],i=t.replacementsToWithhold;if(r=void 0!==e.replacementsToWithhold?i-e.replacementsToWithhold:i,r<0){a.push(e.componentName);let t=e.replacements.length-i,s=e.replacements.length-i+r,o=e.replacements.slice(s,t),l={changeType:"addedReplacements",composite:e,topLevel:!0,newReplacements:o,firstIndex:s,numberDeleted:0};n.push(l)}else if(r>0){a.push(e.componentName);let t=e.replacements.length-i,s=t+r,o=e.replacements.slice(t,s),l={};for(let e of o){let t=e.parentName;void 0===l[t]&&(l[t]=[]),l[t].push(e.componentName)}let u={changeType:"deletedReplacements",composite:e,topLevel:!0,firstIndex:t,numberDeleted:r,deletedNamesByParent:l,deletedComponents:o};n.push(u)}if(e.replacementsToWithhold=i,await this.dependencies.addBlockersFromChangedReplacements(e),e.shadowedBy)for(let r of e.shadowedBy){if(r.shadows.propVariable)continue;let e=await this.adjustReplacementsToWithhold({component:r,change:t,componentChanges:n});a.push(...e)}return a}get rendererTypesInDocument(){return this.document.allPotentialRendererTypes}get components(){return this._components}set components(e){return null}async executeProcesses(){if(!this.stopProcessingRequests){for(;this.processQueue.length>0;){let e,t=this.processQueue.splice(0,1)[0];if("update"===t.type)(!t.skippable||this.processQueue.length<2)&&(e=await this.performUpdate(t));else if("action"===t.type)(!t.skippable||this.processQueue.length<2)&&(e=await this.performAction(t));else{if("recordEvent"!==t.type)throw Error(`Unrecognized process type: ${t.type}`);e=await this.performRecordEvent(t)}t.resolve(e)}this.processing=!1}}requestAction({componentName:e,actionName:t,args:n,event:r}){return new Promise(((a,i)=>{let s=n?.skippable;this.processQueue.push({type:"action",componentName:e,actionName:t,args:n,skippable:s,event:r,resolve:a,reject:i}),this.processing||(this.processing=!0,this.executeProcesses())}))}async performAction({componentName:e,actionName:t,args:n,event:r,caseInsensitiveMatch:a}){let i=this.components[e];if(i&&i.actions){let e=i.actions[t];if(!e&&a){let n=t.toLowerCase();for(let r in i.actions)if(r.toLowerCase()===n){e=i.actions[r],t=r;break}}if(e)return r&&this.requestRecordEvent(r),n||(n={}),await e(n)}if(!i&&"recordVisibilityChange"===t&&!1===n?.isVisible)return this.requestRecordEvent({verb:"visibilityChanged",object:{componentName:e},result:{isVisible:!1}}),this.resolveAction({actionId:n.actionId});i&&console.warn(`Cannot run action ${t} on component ${e}`)}resolveAction({actionId:e}){e&&postMessage({messageType:"resolveAction",coreId:this.coreId,args:{actionId:e}})}async triggerChainedActions({componentName:e,triggeringAction:t}){for(let e in this.updateInfo.componentsToUpdateActionChaining)await this.checkForActionChaining({component:this.components[e],stateVariables:this.updateInfo.componentsToUpdateActionChaining[e]});this.updateInfo.componentsToUpdateActionChaining={};let n=e;if(t&&(n+="|"+t),this.actionsChangedToActions[n])for(let e of this.actionsChangedToActions[n])await this.performAction(e)}async requestUpdate({updateInstructions:e,transient:t=!1,event:n,skippable:r=!1,overrideReadOnly:a=!1}){if(!this.flags.readOnly||a)return new Promise(((a,i)=>{this.processQueue.push({type:"update",updateInstructions:e,transient:t,event:n,skippable:r,resolve:a,reject:i}),this.processing||(this.processing=!0,this.executeProcesses())}));{let t={};for(let n of e){let e=t[n.componentName];e||(e=t[n.componentName]={}),n.sourceInformation&&Object.assign(e,n.sourceInformation)}await this.updateRendererInstructions({componentNamesToUpdate:e.map((e=>e.componentName)),sourceOfUpdate:{sourceInformation:t}})}}async performUpdate({updateInstructions:e,actionId:t,event:n,overrideReadOnly:r=!1,doNotSave:a=!1,canSkipUpdatingRenderer:i=!1,suppressToast:s=!1}){if(this.flags.readOnly&&!r){if(!i){let n={};for(let t of e){let e=n[t.componentName];e||(e=n[t.componentName]={}),t.sourceInformation&&Object.assign(e,t.sourceInformation)}await this.updateRendererInstructions({componentNamesToUpdate:e.map((e=>e.componentName)),sourceOfUpdate:{sourceInformation:n},actionId:t})}return}let o={},l=[],u={},c={},p=[];for(let t of e){if(t.componentName){let e=u[t.componentName];e||(e=u[t.componentName]={}),t.sourceInformation&&Object.assign(e,t.sourceInformation)}if("updateValue"===t.updateType)await this.requestComponentChanges({instruction:t,workspace:c,newStateVariableValues:o});else if("addComponents"===t.updateType)await this.addComponents({serializedComponents:t.serializedComponents,parentName:t.parentName,assignNamesOffset:t.assignNamesOffset});else if("deleteComponents"===t.updateType){if(t.componentNames.length>0){let e=[];for(let n of t.componentNames){let t=this._components[n];t?e.push(t):console.warn(`Cannot delete ${n} as it doesn't exist.`)}e.length>0&&await this.deleteComponents({components:e})}}else"executeUpdate"===t.updateType?(await this.executeUpdateStateVariables(o),l.push(o),o={}):"recordItemSubmission"===t.updateType?p.push(t):"setComponentNeedingUpdateValue"===t.updateType?this.rendererState.__componentNeedingUpdateValue=t.componentName:"unsetComponentNeedingUpdateValue"===t.updateType&&(this.rendererState.__componentNeedingUpdateValue=null)}await this.executeUpdateStateVariables(o),l.push(o),i||e.forEach((e=>{e.componentName&&this.updateInfo.componentsToUpdateRenderers.add(e.componentName)}));let d=[...this.updateInfo.componentsToUpdateRenderers];if(this.updateInfo.componentsToUpdateRenderers.clear(),await this.updateRendererInstructions({componentNamesToUpdate:d,sourceOfUpdate:{sourceInformation:u,local:!0},actionId:t}),this.updateInfo.compositesToUpdateReplacements.size>0){await this.replacementChangesFromCompositesToUpdate();let e=[...this.updateInfo.componentsToUpdateRenderers];this.updateInfo.componentsToUpdateRenderers.clear(),await this.updateRendererInstructions({componentNamesToUpdate:e,sourceOfUpdate:{sourceInformation:u,local:!0},actionId:t})}if(await this.processStateVariableTriggers(),Object.keys(this.unmatchedChildren).length>0){let e="";for(let t in this.unmatchedChildren)this._components[t].isShadow||(e+=`Invalid children for ${t}: ${this.unmatchedChildren[t].message} `);e&&console.warn(e)}if(p.length>0){let e=[...new Set(p.map((e=>e.itemNumber)))],t=await this.document.stateValues.creditAchieved,r=await this.document.stateValues.itemCreditAchieved;if(n){if(n.context||(n.context={}),n.context.item=e[0],n.context.itemCreditAchieved=r[e[0]-1],e.length>1){n.context.additionalItemCreditAchieved={};for(let t of e)n.context.additionalItemCreditAchieved[t]=r[t-1]}n.context.pageCreditAchieved=await this.document.stateValues.creditAchieved}this.itemNumber>0&&this.saveSubmissions({pageCreditAchieved:t,suppressToast:s})}if(Object.keys(this.essentialValuesSavedInDefinition).length>0){for(let e in this.essentialValuesSavedInDefinition){let t=this._components[e]?.essentialState;if(t){this.cumulativeStateVariableChanges[e]||(this.cumulativeStateVariableChanges[e]={});for(let n in this.essentialValuesSavedInDefinition[e])if(void 0!==t[n]){let r=this.cumulativeStateVariableChanges[e][n];"object"==typeof r&&null!==r&&r.mergeObject?Object.assign(r,removeFunctionsMathExpressionClass(t[n])):this.cumulativeStateVariableChanges[e][n]=removeFunctionsMathExpressionClass(t[n])}}}this.essentialValuesSavedInDefinition={}}for(let e of l)for(let t in e){this.cumulativeStateVariableChanges[t]||(this.cumulativeStateVariableChanges[t]={});for(let n in e[t]){let r=this.cumulativeStateVariableChanges[t][n];"object"==typeof r&&null!==r&&r.mergeObject?Object.assign(r,removeFunctionsMathExpressionClass(e[t][n])):this.cumulativeStateVariableChanges[t][n]=removeFunctionsMathExpressionClass(e[t][n])}}a||(clearTimeout(this.savePageStateTimeoutID),this.savePageStateTimeoutID=setTimeout((()=>{this.saveState()}),1e3)),await this.document.stateValues.itemCreditAchieved,n&&this.requestRecordEvent(n)}requestRecordEvent(e){return this.resumeVisibilityMeasuring(),"visibilityChanged"===e.verb?this.processVisibilityChangedEvent(e):new Promise(((t,n)=>{this.processQueue.push({type:"recordEvent",event:e,resolve:t,reject:n}),this.processing||(this.processing=!0,this.executeProcesses())}))}async performRecordEvent({event:e}){if(!this.flags.allowSaveEvents)return;e.result||(e.result={}),e.context||(e.context={});const t={doenetId:this.doenetId,activityCid:this.activityCid,pageCid:this.cid,pageNumber:this.pageNumber,attemptNumber:this.attemptNumber,activityVariantIndex:this.activityVariantIndex,pageVariantIndex:this.requestedVariant.index,verb:e.verb,object:JSON.stringify(e.object,serializedComponentsReplacer),result:JSON.stringify(removeFunctionsMathExpressionClass(e.result),serializedComponentsReplacer),context:JSON.stringify(e.context,serializedComponentsReplacer),timestamp:(new Date).toISOString().slice(0,19).replace("T"," "),version:"0.1.1"};try{await axios.post("/api/recordEvent.php",t)}catch(e){console.error(`Error saving event: ${e.message}`)}}processVisibilityChangedEvent(e){let t=e.object.componentName;if(e.result.isVisible)this.visibilityInfo.componentsCurrentlyVisible[t]||(this.visibilityInfo.componentsCurrentlyVisible[t]=new Date),t===this.documentName&&(this.visibilityInfo.documentHasBeenVisible||(this.visibilityInfo.documentHasBeenVisible=!0,this.onDocumentFirstVisible()));else{let e=this.visibilityInfo.componentsCurrentlyVisible[t];if(e){delete this.visibilityInfo.componentsCurrentlyVisible[t];let n=(new Date-Math.max(e,this.visibilityInfo.timeLastSent))/1e3;this.visibilityInfo.infoToSend[t]?this.visibilityInfo.infoToSend[t]+=n:this.visibilityInfo.infoToSend[t]=n}}}sendVisibilityChangedEvents(){let e={...this.visibilityInfo.infoToSend};this.visibilityInfo.infoToSend={};let t=this.visibilityInfo.timeLastSent;this.visibilityInfo.timeLastSent=new Date;let n,r={...this.visibilityInfo.componentsCurrentlyVisible};for(let n in r){let a=(this.visibilityInfo.timeLastSent-Math.max(t,r[n]))/1e3;e[n]?e[n]+=a:e[n]=a}for(let t in e)e[t]=Math.round(e[t]),e[t]||delete e[t];if(Object.keys(e).length>0){let t={object:{componentName:this.documentName,componentType:"document"},verb:"isVisible",result:e};n=new Promise(((e,n)=>{this.processQueue.push({type:"recordEvent",event:t,resolve:e,reject:n}),this.processing||(this.processing=!0,this.executeProcesses())}))}return this.visibilityInfo.suspended||(clearTimeout(this.visibilityInfo.saveTimerId),this.visibilityInfo.saveTimerId=setTimeout(this.sendVisibilityChangedEvents.bind(this),this.visibilityInfo.saveDelay)),n}async suspendVisibilityMeasuring(){clearTimeout(this.visibilityInfo.saveTimerId),clearTimeout(this.visibilityInfo.suspendTimerId),this.visibilityInfo.suspended||(this.visibilityInfo.suspended=!0,await this.sendVisibilityChangedEvents())}resumeVisibilityMeasuring(){this.visibilityInfo.suspended&&(this.visibilityInfo.suspended=!1,this.visibilityInfo.timeLastSent=new Date,clearTimeout(this.visibilityInfo.saveTimerId),this.visibilityInfo.saveTimerId=setTimeout(this.sendVisibilityChangedEvents.bind(this),this.visibilityInfo.saveDelay)),clearTimeout(this.visibilityInfo.suspendTimerId),this.visibilityInfo.suspendTimerId=setTimeout(this.suspendVisibilityMeasuring.bind(this),this.visibilityInfo.suspendDelay)}async executeUpdateStateVariables(e){if(await this.processNewStateVariableValues(e),(await this.replacementChangesFromCompositesToUpdate()).updatedComposites&&(await this.expandAllComposites(this.document),await this.expandAllComposites(this.document,!0),this.updateInfo.stateVariablesToEvaluate)){let e=this.updateInfo.stateVariablesToEvaluate;this.updateInfo.stateVariablesToEvaluate=[];for(let{componentName:t,stateVariable:n}of e){let e=this._components[t];e&&e.state[n]&&await this.getStateVariableValue({component:e,stateVariable:n})}}await this.replacementChangesFromCompositesToUpdate()}async replacementChangesFromCompositesToUpdate(){let e=[...this.updateInfo.compositesToUpdateReplacements];this.updateInfo.compositesToUpdateReplacements.clear();let t=new Set([]),n=0,r=!1,a=[];for(;e.length>0;){for(let n of e){let e=this._components[n];if(e instanceof this.componentInfoObjects.allComponentClasses._composite&&e.isExpanded)if(e.state.readyToExpandWhenResolved.initiallyResolved)if(await e.stateValues.isInactiveCompositeReplacement)this.updateInfo.inactiveCompositesToUpdateReplacements.add(n);else{let t=await this.updateCompositeReplacements({component:e,componentChanges:a});Object.keys(t.addedComponents).length>0&&(r=!0),Object.keys(t.deletedComponents).length>0&&(r=!0)}else t.add(n)}if(e=[...this.updateInfo.compositesToUpdateReplacements],this.updateInfo.compositesToUpdateReplacements.clear(),n++,n>100)throw Error("Seem to have an infinite loop while calculating replacement changes")}return this.updateInfo.compositesToUpdateReplacements=t,{updatedComposites:r}}async processNewStateVariableValues(e){let t=0,n=!1;for(let r in e){let a=this._components[r];if(void 0===a){let t=this.updateInfo.stateVariableUpdatesForMissingComponents[r];void 0===t&&(t=this.updateInfo.stateVariableUpdatesForMissingComponents[r]={}),Object.assign(t,e[r]);continue}let i=e[r];for(let e in i){let s=a.state[e];if(void 0===s){let t=e.match(/^__def_primitive_(\d+)$/);if(t){let n=Number(t[1]);a.definingChildren[n]=i[e],await this.processNewDefiningChildren({parent:a,expandComposites:!1});continue}if(t=e.match(/^__def_primitive_ignore_(\d+)$/),t){let r=Number(t[1]);a.definingChildren[r]=i[e],n=!0;continue}console.warn(`can't update state variable ${e} of component ${r}, as it doesn't exist.`);continue}if(!s.hasEssential){console.warn(`can't update state variable ${e} of component ${r}, as it does not have an essential state variable.`);continue}let o=e;if(a.state[e].essentialVarName&&(o=a.state[e].essentialVarName),e in this.rendererVariablesByComponentType[a.componentType]&&this.updateInfo.componentsToUpdateRenderers.add(a.componentName),s.isArray){let n=a.essentialState[o];Array.isArray(n)||(n=a.essentialState[o]=[]);let l=[];a.state[s.arraySizeStateVariable].initiallyResolved||await a.state[s.arraySizeStateVariable].value;let u=await s.arraySize;for(let r in i[e]){if("mergeObject"===r)continue;let a=e=>e;s.set&&(a=s.set);let o=s.setArrayValue({value:a(i[e][r]),arrayKey:r,arraySize:u,arrayValues:n});s.usedDefaultByArrayKey[r]=!1,t+=o.nFailures;let c=s.varNamesIncludingArrayKeys[r];c&&l.push(...c)}for(let e of l)await this.recordActualChangeInStateVariable({componentName:r,varName:e})}else{if(!s.hasEssential){console.warn(`can't update state variable ${e} of component ${r}, as it does not have an essential state variable.`);continue}s.set?a.essentialState[o]=s.set(i[e]):a.essentialState[o]=i[e],delete s.usedDefault}await this.recordActualChangeInStateVariable({componentName:r,varName:e})}}return{nFailures:t,foundIgnore:n}}async requestComponentChanges({instruction:e,initialChange:t=!0,workspace:n,newStateVariableValues:r}){let a=this._components[e.componentName],i=this.substituteAliases({stateVariables:[e.stateVariable],componentClass:a.constructor})[0];void 0===n[e.componentName]&&(n[e.componentName]={});let s=n[e.componentName],o=a.state[i],l=o.additionalStateVariablesDefined,u=[i];l&&u.push(...l);for(let e of u)if(!a.state[e].isResolved){if(!(await this.dependencies.resolveItem({componentName:a.componentName,type:"stateVariable",stateVariable:e,force:!0})).success)throw Error(`Can't get value of ${i} of ${a.componentName} as ${e} couldn't be resolved.`)}let c=await this.getStateVariableDefinitionArguments({component:a,stateVariable:i,excludeDependencyValues:o.excludeDependencyValuesInInverseDefinition});c.componentInfoObjects=this.componentInfoObjects,c.initialChange=t,c.stateValues=a.stateValues,c.overrideFixed=e.overrideFixed,c.shadowedVariable=e.shadowedVariable,c.sourceInformation=e.sourceInformation;let p=i;if(o.isArrayEntry){let t=o.arrayStateVariable;p=t;let n={};if(1===c.arrayKeys.length){if("value"in e)n[c.arrayKeys[0]]=e.value;else if("valueOfStateVariable"in e){let t=this.substituteAliases({stateVariables:[e.valueOfStateVariable],componentClass:a.constructor})[0],r=a.state[t];if(!r)throw Error(`Invalid instruction to change ${e.stateVariable} of ${e.componentName}, value of state variable ${e.valueOfStateVariable} not found.`);n[c.arrayKeys[0]]=await r.value}}else for(let[t,r]of c.arrayKeys.entries())if(Array.isArray(e.value))n[r]=e.value[t];else if(e.value instanceof me$3.class)try{n[r]=e.value.get_component(t)}catch(e){}c.desiredStateVariableValues={[t]:n}}else if("value"in e)c.desiredStateVariableValues={[i]:e.value};else if("valueOfStateVariable"in e){let t=this.substituteAliases({stateVariables:[e.valueOfStateVariable],componentClass:a.constructor})[0],n=a.state[t];if(!n)throw Error(`Invalid instruction to change ${e.stateVariable} of ${e.componentName}, value of state variable ${e.valueOfStateVariable} not found.`);c.desiredStateVariableValues={[i]:await n.value}}let d=s[p];if(void 0===d&&(d=s[p]={}),o.additionalStateVariablesDefined)for(let e of o.additionalStateVariablesDefined){let t=e;a.state[e].isArray&&(t=o.arrayStateVariable);let n=s[t];n&&(Object.assign(d,n),s[t]=d)}if(c.workspace=d,e.additionalStateVariableValues)for(let t in e.additionalStateVariableValues)o.additionalStateVariablesDefined.includes(t)?c.desiredStateVariableValues[t]=e.additionalStateVariableValues[t]:console.warn(`Can't invert ${t} at the same time as ${i}, as not an additional state variable defined`);if(!o.inverseDefinition)return void console.warn(`Cannot change state variable ${i} of ${a.componentName} as it doesn't have an inverse definition`);if(await a.stateValues.fixed&&!e.overrideFixed&&!o.ignoreFixed)return void console.log(`Changing ${i} of ${a.componentName} did not succeed because fixed is true.`);if(!t&&!1===await a.stateValues.modifyIndirectly)return void console.log(`Changing ${i} of ${a.componentName} did not succeed because modifyIndirectly is false.`);let m=await o.inverseDefinition(c);if(!m.success)return;let h,f=[];for(let e of m.instructions){let t=!1;if(e.setDependency){let n=e.setDependency,r=this.dependencies.downstreamDependencies[a.componentName][i][n];if(["stateVariable","parentStateVariable"].includes(r.dependencyType)&&1===r.downstreamComponentNames.length){let n=r.downstreamComponentNames[0],a=r.mappedDownstreamVariableNamesByComponent[0][0],i=this._components[n].state[a];if((i.isArrayEntry||i.isArray)&&!i.doNotCombineInverseArrayInstructions){let r=i.isArrayEntry?i.arrayStateVariable:a;if(!h||h.componentName===n&&h.stateVariable===r&&h.shadowedVariable===e.shadowedVariable&&h.treatAsInitialChange===e.treatAsInitialChange||(f.push(h),h=void 0),!e.additionalDependencyValues&&!i.basedOnArrayKeyStateVariables)if(t=!0,h||(h={combinedArray:!0,componentName:n,stateVariable:r,shadowedVariable:e.shadowedVariable,treatAsInitialChange:e.treatAsInitialChange,desiredValue:{}}),i.isArrayEntry){let t=await i.arrayKeys;if(1===t.length)h.desiredValue[t[0]]=e.desiredValue;else for(let[n,r]of t.entries())h.desiredValue[r]=e.desiredValue[n]}else if(1!==i.nDimensions&&Array.isArray(e.desiredValue)){let t=(e,n)=>{if(1===n)return Object.assign({},e);{let r={};for(let a in e){let i=t(e[a],n-1);for(let e in i)r[`${a},${e}`]=i[e]}return r}};Object.assign(h.desiredValue,t(e.desiredValue,i.nDimensions))}else Object.assign(h.desiredValue,e.desiredValue)}}}t||(h&&(f.push(h),h=void 0),f.push(e))}h&&(f.push(h),h=void 0);for(let t of f)if(t.setEssentialValue){if(!u.includes(t.setEssentialValue)){let e=!1;if(o.isArrayEntry){let n=[o.arrayStateVariable];if(o.additionalStateVariablesDefined)for(let e of o.additionalStateVariablesDefined){let t=a.state[e];t.isArrayEntry&&n.push(t.arrayStateVariable)}e=n.includes(t.setEssentialValue)}if(!e)throw Error(`Invalid inverse definition of ${i} of ${a.componentName}: specified changing value of ${t.setEssentialValue}, which is not a state variable defined with ${i}.`)}if(!a.state[t.setEssentialValue].hasEssential)throw Error(`Invalid inverse definition of ${i} of ${a.componentName}: can't set essential value of ${t.setEssentialValue} if it is does not have an essential value.`);if(!("value"in t))throw Error(`Invalid inverse definition of ${i} of ${a.componentName}: setEssentialValue must specify a value`);let e=t.value;if(e instanceof me$3.class){e=(await preprocessMathInverseDefinition({desiredValue:e,stateValues:a.stateValues,variableName:t.setEssentialValue,workspace:d})).desiredValue}if(a.state[t.setEssentialValue].doNotShadowEssential||a.state[t.setEssentialValue].shadowVariable)this.calculateEssentialVariableChanges({component:a,varName:t.setEssentialValue,value:e,newStateVariableValues:r,recurseToShadows:!1});else{let n=a;for(;n.shadows&&void 0===n.shadows.propVariable;)n=this._components[n.shadows.componentName];this.calculateEssentialVariableChanges({component:n,varName:t.setEssentialValue,value:e,newStateVariableValues:r})}}else if(t.setDependency){let s=t.setDependency,o=this.dependencies.downstreamDependencies[a.componentName][i][s];if("child"===o.dependencyType){let l=t.childIndex;if(null!==o.downstreamPrimitives[l]){if(typeof t.desiredValue==typeof o.downstreamPrimitives[l]){let e=this._components[o.parentName],n=o.activeChildrenIndices[l];if(e.compositeReplacementActiveRange)for(let r of e.compositeReplacementActiveRange)if(r.firstInd<=n&&r.lastInd>=n)throw console.log(`parent: ${e.componentName}, activeChildInd: ${n}`),console.log(e.compositeReplacementActiveRange),console.log(t),Error("Need to implement changing primitive replacements from composite");let a=n;if(e.compositeReplacementActiveRange)for(let t of e.compositeReplacementActiveRange)t.lastInd!e)).length-1,c=o.downstreamComponentNames[u];if(!c)throw Error(`Invalid inverse definition of ${i} of ${a.componentName}: ${s} child of index ${t.childIndex} does not exist.`);let p=o.mappedDownstreamVariableNamesByComponent[t.childIndex][t.variableIndex];if(!p)throw Error(`Invalid inverse definition of ${i} of ${a.componentName}: ${s} variable of index ${t.variableIndex} does not exist.`);let d={componentName:c,stateVariable:p,value:t.desiredValue,overrideFixed:e.overrideFixed,arrayKey:t.arrayKey};await this.requestComponentChanges({instruction:d,initialChange:!0===t.treatAsInitialChange,workspace:n,newStateVariableValues:r})}}else if(["attributeComponent","shadowSource","adapterSource","targetComponent"].includes(o.dependencyType)){let l=o.downstreamComponentNames[0],u=o.mappedDownstreamVariableNamesByComponent[0][t.variableIndex];if(!u)throw Error(`Invalid inverse definition of ${i} of ${a.componentName}: ${s} variable of index ${t.variableIndex} does not exist.`);let c={componentName:l,stateVariable:u,value:t.desiredValue,overrideFixed:e.overrideFixed,arrayKey:t.arrayKey};await this.requestComponentChanges({instruction:c,initialChange:!0===t.treatAsInitialChange,workspace:n,newStateVariableValues:r})}else{if(!["stateVariable","parentStateVariable","adapterSourceStateVariable","sourceCompositeStateVariable"].includes(o.dependencyType)||1!==o.downstreamComponentNames.length)throw Error(`unimplemented dependency type ${o.dependencyType} in requestComponentChanges`);{let l=o.downstreamComponentNames[0],u=o.mappedDownstreamVariableNamesByComponent[0][0],c={componentName:l,stateVariable:u,value:t.desiredValue,overrideFixed:e.overrideFixed,shadowedVariable:t.shadowedVariable};if(t.additionalDependencyValues){let e=this.components[l].state[u];for(let n in t.additionalDependencyValues){let r=this.dependencies.downstreamDependencies[a.componentName][i][n];if(!["stateVariable","parentStateVariable"].includes(r.dependencyType)||1!==r.downstreamComponentNames.length){console.warn(`Can't simultaneously set additional dependency value ${n} if it isn't a state variable`);continue}let o=r.mappedDownstreamVariableNamesByComponent[0][0];r.downstreamComponentNames[0]===l&&e.additionalStateVariablesDefined.includes(o)?(c.additionalStateVariableValues||(c.additionalStateVariableValues={}),c.additionalStateVariableValues[o]=t.additionalDependencyValues[n]):console.warn(`Can't simultaneously set additional dependency value ${n} if it doesn't correspond to additional state variable defined of ${s}'s state variable`)}}await this.requestComponentChanges({instruction:c,initialChange:!0===t.treatAsInitialChange,workspace:n,newStateVariableValues:r})}}}else{if(!t.combinedArray)throw console.log(t),Error(`Unrecognized instruction in inverse definition of ${i} of ${a.componentName}`);{let a={componentName:t.componentName,stateVariable:t.stateVariable,value:t.desiredValue,overrideFixed:e.overrideFixed,shadowedVariable:t.shadowedVariable};await this.requestComponentChanges({instruction:a,initialChange:!0===t.treatAsInitialChange,workspace:n,newStateVariableValues:r})}}}calculateEssentialVariableChanges({component:e,varName:t,value:n,newStateVariableValues:r,recurseToShadows:a=!0}){if(r[e.componentName]||(r[e.componentName]={}),e.state[t].isArray?(r[e.componentName][t]||(r[e.componentName][t]={mergeObject:!0}),Object.assign(r[e.componentName][t],n)):r[e.componentName][t]=n,a&&e.shadowedBy)for(let a of e.shadowedBy)void 0===a.shadows.propVariable&&this.calculateEssentialVariableChanges({component:a,varName:t,value:n,newStateVariableValues:r})}calculatePrimitiveChildChanges({parent:e,definingInd:t,newValue:n,newStateVariableValues:r,markToIgnoreForParent:a}){if(r[e.componentName]||(r[e.componentName]={}),e.componentName===a?r[e.componentName][`__def_primitive_ignore_${t}`]=n:r[e.componentName][`__def_primitive_${t}`]=n,e.shadowedBy)for(let i of e.shadowedBy)void 0===i.shadows.propVariable&&this.calculatePrimitiveChildChanges({parent:i,definingInd:t,newValue:n,newStateVariableValues:r,markToIgnoreForParent:a})}async saveState(e=!1){if(this.savePageStateTimeoutID=null,!this.flags.allowSaveState&&!this.flags.allowLocalState)return;let t=nanoid();this.flags.allowLocalState&&await set(`${this.doenetId}|${this.pageNumber}|${this.attemptNumber}|${this.cid}`,{coreState:this.cumulativeStateVariableChanges,rendererState:this.rendererState,coreInfo:this.coreInfo,saveId:t}),postMessage({messageType:"savedState",coreId:this.coreId}),this.flags.allowSaveState&&(this.pageStateToBeSavedToDatabase={cid:this.cid,coreInfo:this.coreInfoString,coreState:JSON.stringify(this.cumulativeStateVariableChanges,serializedComponentsReplacer),rendererState:JSON.stringify(this.rendererState,serializedComponentsReplacer),pageNumber:this.pageNumber,attemptNumber:this.attemptNumber,doenetId:this.doenetId,saveId:t,serverSaveId:this.serverSaveId,updateDataOnContentChange:this.updateDataOnContentChange},this.changesToBeSaved=!0,await this.saveChangesToDatabase(e))}async saveChangesToDatabase(e){if(!this.changesToBeSaved)return;if(null!==this.saveStateToDBTimerId){if(!e)return;clearTimeout(this.saveStateToDBTimerId)}let t;this.changesToBeSaved=!1,this.saveStateToDBTimerId=setTimeout((()=>{this.saveStateToDBTimerId=null,this.saveChangesToDatabase()}),6e4);try{t=await axios.post("/api/savePageState.php",this.pageStateToBeSavedToDatabase)}catch(e){return void postMessage({messageType:"sendToast",coreId:this.coreId,args:{message:"Error synchronizing data. Changes not saved to the server.",toastType:toastType.ERROR}})}if(console.log("result from saving to database:",t.data),null===t.status)return void postMessage({messageType:"sendToast",coreId:this.coreId,args:{message:"Error synchronizing data. Changes not saved to the server. Are you connected to the internet?",toastType:toastType.ERROR}});let n=t.data;n.success?(this.serverSaveId=n.saveId,this.flags.allowLocalState&&await set(`${this.doenetId}|${this.pageNumber}|${this.attemptNumber}|${this.cid}|ServerSaveId`,n.saveId),n.stateOverwritten&&(this.attemptNumber!==Number(n.attemptNumber)||this.cid===n.cid?(this.flags.allowLocalState&&await set(`${this.doenetId}|${this.pageNumber}|${n.attemptNumber}|${n.cid}`,{coreState:JSON.parse(n.coreState,serializedComponentsReviver),rendererState:JSON.parse(n.rendererState,serializedComponentsReviver),coreInfo:JSON.parse(n.coreInfo,serializedComponentsReviver),saveId:n.saveId}),postMessage({messageType:"resetPage",coreId:this.coreId,args:{changedOnDevice:n.device,newCid:n.cid,newAttemptNumber:Number(n.attemptNumber)}})):postMessage({messageType:"inErrorState",coreId:this.coreId,args:{errMsg:"Content changed unexpectedly!"}}))):postMessage({messageType:"sendToast",coreId:this.coreId,args:{message:n.message,toastType:toastType.ERROR}})}saveSubmissions({pageCreditAchieved:e,suppressToast:t=!1}){if(!this.flags.allowSaveSubmissions)return;const n={doenetId:this.doenetId,attemptNumber:this.attemptNumber,credit:e,itemNumber:this.itemNumber};console.log("payload for save credit for item",n),axios.post("/api/saveCreditForItem.php",n).then((e=>{if(null===e.status)postMessage({messageType:"sendToast",coreId:this.coreId,args:{message:"Credit not saved due to error. Are you connected to the internet?",toastType:toastType.ERROR}});else if(e.data.success){let n=e.data;postMessage({messageType:"updateCreditAchieved",coreId:this.coreId,args:{creditByItem:n.creditByItem.map(Number),creditForAssignment:Number(n.creditForAssignment),creditForAttempt:Number(n.creditForAttempt),showCorrectness:"1"===n.showCorrectness,totalPointsOrPercent:Number(n.totalPointsOrPercent)}}),n.viewedSolution&&(t||postMessage({messageType:"sendToast",coreId:this.coreId,args:{message:"No credit awarded since solution was viewed.",toastType:toastType.INFO}})),n.timeExpired&&(t||postMessage({messageType:"sendToast",coreId:this.coreId,args:{message:"No credit awarded since the time allowed has expired.",toastType:toastType.INFO}})),n.pastDueDate&&(t||postMessage({messageType:"sendToast",coreId:this.coreId,args:{message:"No credit awarded since the due date has passed.",toastType:toastType.INFO}})),n.exceededAttemptsAllowed&&(t||postMessage({messageType:"sendToast",coreId:this.coreId,args:{message:"No credit awarded since no more attempts are allowed.",toastType:toastType.INFO}})),n.databaseError&&postMessage({messageType:"sendToast",coreId:this.coreId,args:{message:"Credit not saved due to database error.",toastType:toastType.ERROR}})}else postMessage({messageType:"sendToast",coreId:this.coreId,args:{message:`Credit not saved due to error: ${e.data.message}`,toastType:toastType.ERROR}})})).catch((e=>{postMessage({messageType:"sendToast",coreId:this.coreId,args:{message:`Credit not saved due to error: ${e.message}`,toastType:toastType.ERROR}})}))}async recordSolutionView(){if(!this.flags.allowSaveSubmissions)return{allowView:!0,message:"",scoredComponent:this.documentName};try{const e=await axios.post("/api/reportSolutionViewed.php",{doenetId:this.doenetId,itemNumber:this.itemNumber,pageNumber:this.pageNumber,attemptNumber:this.attemptNumber});if(null===e.status){let e="Cannot show solution due to error. Are you connected to the internet?";return postMessage({messageType:"sendToast",coreId:this.coreId,args:{message:e,toastType:toastType.ERROR}}),{allowView:!1,message:e,scoredComponent:this.documentName}}{let t=e.data;if(t.success)return{allowView:!0,message:"",scoredComponent:this.documentName};return{allowView:!1,message:`Cannot show solution due to error: ${t.message}`,scoredComponent:this.documentName}}}catch(e){let t="Cannot show solution due to error.";return postMessage({messageType:"sendToast",coreId:this.coreId,args:{message:t,toastType:toastType.ERROR}}),{allowView:!1,message:t,scoredComponent:this.documentName}}}get scoredItemWeights(){return(async()=>(await this.document.stateValues.scoredDescendants).map((e=>e.stateValues.weight)))()}requestAnimationFrame(e){postMessage({messageType:"requestAnimationFrame",coreId:this.coreId,args:e})}cancelAnimationFrame(e){postMessage({messageType:"cancelAnimationFrame",coreId:this.coreId,args:e})}handleVisibilityChange({visible:e}){e?this.resumeVisibilityMeasuring():this.suspendVisibilityMeasuring()}handleNavigatingToComponent(e){let t=this._components[e];t?.actions?.revealSection&&this.requestAction({componentName:t.componentName,actionName:"revealSection"})}async terminate(){if(await this.suspendVisibilityMeasuring(),this.submitAnswersTimeout&&(clearTimeout(this.submitAnswersTimeout),await this.autoSubmitAnswers()),this.stopProcessingRequests=!0,this.processing)for(let e=0;e<10&&(await new Promise(((e,t)=>{setTimeout(e,100)})),this.processing);e++);this.savePageStateTimeoutID?(clearTimeout(this.savePageStateTimeoutID),await this.saveState(!0)):await this.saveChangesToDatabase(!0)}recordAnswerToAutoSubmit(e){this.answersToSubmit||(this.answersToSubmit=[]),this.answersToSubmit.includes(e)||this.answersToSubmit.push(e),clearTimeout(this.submitAnswersTimeout),this.submitAnswersTimeout=setTimeout((()=>{this.autoSubmitAnswers()}),1e3)}async autoSubmitAnswers(){let e=this.answersToSubmit;this.answersToSubmit=[];for(let t of e){this._components[t].actions.submitAnswer&&await this.requestAction({componentName:t,actionName:"submitAnswer"})}}requestComponentDoenetML(e,t){let n=this.components[e];if(!n)return null;let r,a,i=n.doenetMLrange;if(!i)return null;if(t){if(void 0!==i.selfCloseBegin)return"";r=i.openEnd+1,a=i.closeBegin}else r=void 0!==i.openBegin?i.openBegin:i.selfCloseBegin,a=void 0!==i.closeEnd?i.closeEnd:i.selfCloseEnd+1;let s=this.doenetML.slice(r-1,a);t&&("\n"===s[0]&&(s=s.slice(1)),s=s.replace(/\n[ \t]*$(?!\n)/,""));let o=s.split("\n"),l=o.slice(1).reduce(((e,t)=>Math.min(e,t.trim().length>1?t.search(/\S|$/):1/0)),1/0);return Number.isFinite(l)&&l>0&&(o=o.map((e=>{let t=Math.min(l,e.search(/\S|$/));return e.slice(t)})),s=o.join("\n")),s+="\n",s}copyToClipboard(e,t){"string"!=typeof e?this.resolveAction({actionId:t}):postMessage({messageType:"copyToClipboard",coreId:this.coreId,args:{text:e,actionId:t}})}navigateToTarget(e){postMessage({messageType:"navigateToTarget",coreId:this.coreId,args:e})}}function validateAttributeValue({value:e,attributeSpecification:t,attribute:n}){return t.valueTransformations&&e in t.valueTransformations&&(e=t.valueTransformations[e]),void 0===t.transformNonFiniteTo||Number.isFinite(e)||(e=t.transformNonFiniteTo),t.toLowerCase&&(e=e.toLowerCase()),t.trim&&(e=e.trim()),t.validValues?t.validValues.includes(e)||(console.warn(`Invalid value ${e} for attribute ${n}, using value ${t.defaultValue}`),e=t.defaultValue):t.clamp&&(et.clamp[1]?e=t.clamp[1]:Number.isFinite(e)||(e=t.defaultValue)),e}function calculateAllComponentsShadowing(e){let t=[];if(e.shadowedBy)for(let n of e.shadowedBy)if(!n.shadows.propVariable){t.push(n.componentName);let e=calculateAllComponentsShadowing(n);t.push(...e)}if(e.replacementOf){let n=calculateAllComponentsShadowing(e.replacementOf);t.push(...n)}return t}return Core}(); diff --git a/src/Viewer/renderers/graph.jsx b/src/Viewer/renderers/graph.jsx index baec28fbdc..5ce030ff10 100644 --- a/src/Viewer/renderers/graph.jsx +++ b/src/Viewer/renderers/graph.jsx @@ -228,12 +228,12 @@ export default React.memo(function Graph(props) { let displayXAxisChanged = SVs.displayXAxis ? !Boolean(xaxis.current) : Boolean(xaxis.current); let displayYAxisChanged = SVs.displayYAxis ? !Boolean(yaxis.current) : Boolean(yaxis.current); - if(displayYAxisChanged && !displayXAxisChanged && SVs.displayXAxis) { + if (displayYAxisChanged && !displayXAxisChanged && SVs.displayXAxis) { board.removeObject(xaxis.current); xaxis.current = null; } - if(displayXAxisChanged && !displayYAxisChanged && SVs.displayYAxis) { + if (displayXAxisChanged && !displayYAxisChanged && SVs.displayYAxis) { board.removeObject(yaxis.current); yaxis.current = null; } @@ -370,7 +370,7 @@ export default React.memo(function Graph(props) { ); function createYAxis(theBoard) { - let yaxisOptions = {}; + let yaxisOptions = { highlight: false, fixed: true }; if (SVs.ylabel) { let position = 'rt'; let offset = [-10, -5]; @@ -405,7 +405,7 @@ export default React.memo(function Graph(props) { ticksDistance: 2, label: { offset: [12, -2], - layer: 2, + layer: 2, strokeColor: "var(--canvastext)" }, // minorTicks: 4, @@ -532,7 +532,7 @@ export default React.memo(function Graph(props) { } function createXAxis(theBoard) { - let xaxisOptions = {}; + let xaxisOptions = { highlight: false, fixed: true }; if (SVs.xlabel) { let position = 'rt'; let offset = [5, 10]; diff --git a/src/Viewer/renderers/pegboard.jsx b/src/Viewer/renderers/pegboard.jsx index 400d9bf46f..1453489f6a 100644 --- a/src/Viewer/renderers/pegboard.jsx +++ b/src/Viewer/renderers/pegboard.jsx @@ -1,6 +1,7 @@ import React, { useContext, useEffect, useState, useRef } from 'react'; import useDoenetRender from './useDoenetRenderer'; import { BoardContext } from './graph'; +import me from 'math-expressions'; export default React.memo(function Pegboard(props) { let { name, id, SVs, actions, sourceOfUpdate, callAction } = useDoenetRender(props); @@ -28,8 +29,8 @@ export default React.memo(function Pegboard(props) { fixed: true, withlabel: false, layer: 10 * SVs.layer, - fillColor: "var(--canvastext)", - strokeColor: "var(--canvastext)", + fillColor: "darkgray", + strokeColor: "darkgray", size: 0.1, face: "circle", highlight: false, @@ -57,10 +58,11 @@ export default React.memo(function Pegboard(props) { let yind1 = (ymin - yoffset.current) / dy.current; let yind2 = (ymax - yoffset.current) / dy.current; - let minXind = Math.floor(Math.min(xind1, xind2)); - let maxXind = Math.ceil(Math.max(xind1, xind2)); - let minYind = Math.floor(Math.min(yind1, yind2)); - let maxYind = Math.ceil(Math.max(yind1, yind2)); + // Note: use round from mathjs so that it rounds -0.5 to -1, not 0. + let minXind = me.math.round(Math.min(xind1, xind2) + 1); + let maxXind = me.math.round(Math.max(xind1, xind2) - 1); + let minYind = me.math.round(Math.min(yind1, yind2) + 1); + let maxYind = me.math.round(Math.max(yind1, yind2) - 1); previousBounds.current = [minXind, maxXind, minYind, maxYind]; @@ -91,10 +93,11 @@ export default React.memo(function Pegboard(props) { let yind1 = (ymin - yoffset.current) / dy.current; let yind2 = (ymax - yoffset.current) / dy.current; - let minXind = Math.floor(Math.min(xind1, xind2)); - let maxXind = Math.ceil(Math.max(xind1, xind2)); - let minYind = Math.floor(Math.min(yind1, yind2)); - let maxYind = Math.ceil(Math.max(yind1, yind2)); + // Note: use round from mathjs so that it rounds -0.5 to -1, not 0. + let minXind = me.math.round(Math.min(xind1, xind2) + 1); + let maxXind = me.math.round(Math.max(xind1, xind2) - 1); + let minYind = me.math.round(Math.min(yind1, yind2) + 1); + let maxYind = me.math.round(Math.max(yind1, yind2) - 1); let [prevXmin, prevXmax, prevYmin, prevYmax] = previousBounds.current; @@ -200,10 +203,11 @@ export default React.memo(function Pegboard(props) { let yind1 = (ymin - yoffset.current) / dy.current; let yind2 = (ymax - yoffset.current) / dy.current; - let minXind = Math.floor(Math.min(xind1, xind2)); - let maxXind = Math.ceil(Math.max(xind1, xind2)); - let minYind = Math.floor(Math.min(yind1, yind2)); - let maxYind = Math.ceil(Math.max(yind1, yind2)); + // Note: use round from mathjs so that it rounds -0.5 to -1, not 0. + let minXind = me.math.round(Math.min(xind1, xind2) + 1); + let maxXind = me.math.round(Math.max(xind1, xind2) - 1); + let minYind = me.math.round(Math.min(yind1, yind2) + 1); + let maxYind = me.math.round(Math.max(yind1, yind2) - 1); recalculatePegboard(minXind, maxXind, minYind, maxYind)