markuno_lib 1.1.25 → 1.1.26
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/bus_utils.js +76 -1
- package/bin/markcad.js +505 -1
- package/bin/markcad3d.js +13 -1723
- package/bin/marked.js +21 -1
- package/bin/markuno.js +267 -1
- package/bin/proto.js +184 -1
- package/package.json +1 -1
package/bin/markuno.js
CHANGED
|
@@ -1 +1,267 @@
|
|
|
1
|
-
function testsync(a,b){return a+b}const tk=()=>(new Date).valueOf();function quote(v){if((v=(v||"").trim()).length>1){if(v.startsWith('"')&&v.endsWith('"'))return v;if(v.startsWith("(")&&v.endsWith(")"))return v}return`"${v}"`}function hash(obj){let str="";if("string"==typeof obj||"number"==typeof obj)str=obj+"";else if("object"==typeof obj&&obj){const chiaviOrdinati=Object.keys(obj).sort(),separatore="\0";str=chiaviOrdinati.map((key=>`${key}${separatore}${String(obj[key])}`)).join(separatore)}let h1=2166136261,h2=2218511855;for(let i=0;i<str.length;i++){const char=str.charCodeAt(i);h1^=char,h1+=h1<<5^2779096485,h2^=h1,h2=((h2<<3)+char^2134516169)>>>0}return h1>>>=0,h1.toString(16)+h2.toString(16)}function geterrdes(err){if(err&&"object"==typeof err){let errMsg=err.stack?.toString().replace(/^.*?node_modules.*$/gim,"")||err.message||"";errMsg=errMsg.replaceAll("/","_").replaceAll(".js","").replaceAll("\n\n","\n").replace(/\;\s+/gi,"\n"),err=errMsg}return(err=err.replace(/sqlite/gi,"SQL ")).replaceAll(";",",").trim()}let cbGetVariante,cbGetMacro,cbFunc,cbInfo,cbGetFile,cbLogga;const logga=(...args)=>{cbLogga?cbLogga(args):console.log(...args)};function setcallbacks(cbGetMacro1,cbGetVariante1,cbFunc1,cbInfo1,cbGetFile1,cbLogga1){cbGetMacro=cbGetMacro1,cbGetVariante=cbGetVariante1,cbFunc=cbFunc1,cbInfo=cbInfo1,cbGetFile=cbGetFile1,cbLogga=cbLogga1}const xdt=()=>(new Date).valueOf();function clean(k,locase=!1){return locase?(k||"").trim().toLowerCase():(k||"").trim()}function getcouple(r,sep="=",locase=!0){var q=(r=r||"").indexOf(sep);return q>=0?{v:clean(r.substring(0,q),locase),o:r.substring(q+sep.length).trim(),fl:!0}:{v:clean(r,locase),o:"",fl:!1}}function checkmu(id,cat){if((id=(id||"").trim()).indexOf("/")>0){var vv=id.split("/");cat=vv[0]||"",id=vv[1]||""}if(!cat)throw new Error("manca il catalogo per "+id);return{name:id,cat:cat=checkname(cat)}}function checkname(id){if(!(id=(id||"").trim())||!/^(?:(\w|\-|\_|\+|\.))+$/im.test(id)){throw new Error(`nome non valido: |${id}| \n deve contenere solo lettere, _, e numeri`)}return id.toLowerCase()}function getcolonne(value,keepquote=!1){value=String(value||"");const pp=/^(\d+)\.\.(\d+)$/.exec(value);if(pp){var n1=parseInt(pp[1]),n2=parseInt(pp[2]),cl=[];n1>n2&&([n1,n2]=[n2,n1]);for(var i=n1;i<=n2;i++)cl.push(i+"");return cl}if(!/["({[]/.test(value))return value.split(/[,;]/).map((e=>e.trim()));const risultato=[];let buffer="",livelloParentesi=0,inVirgolette=!1;for(let i=0;i<value.length;i++){const char=value[i];if(0===livelloParentesi&&'"'===char&&(0!==i&&"\\"===value[i-1]||(inVirgolette=!inVirgolette)),inVirgolette||("("===char||"["===char||"{"===char?livelloParentesi++:")"!==char&&"]"!==char&&"}"!==char||(livelloParentesi=Math.max(0,livelloParentesi-1))),","!==char&&";"!==char||0!==livelloParentesi||inVirgolette)buffer+=char;else{const trimmed=buffer.trim();risultato.push(trimmed),buffer=""}}const trimmed=buffer.trim();return trimmed&&risultato.push(trimmed),risultato.map((e=>(e=e.trim(),!keepquote&&(e.startsWith('"')&&e.endsWith('"')||e.startsWith("(")&&e.endsWith(")"))?e.slice(1,-1):e)))}const parsevar=(ex,k0,inipar,endpar,nonewline=!1)=>{const pars1=["[","(","{"],pars2=["]",")","}"];endpar||(endpar="["==inipar?"]":"("==inipar?")":"}");for(var mp=pars1.includes(inipar),par=1,res=[],nres=0,i=k0;i<ex.length;i++)if(mp&&pars1.includes(ex[i])||ex[i]==inipar)par++;else if(mp&&pars2.includes(ex[i])||ex[i]==endpar){if(0==--par&&ex[i]==endpar)return res[nres]=ex.substring(k0,i),{i:i,res:res}}else if(":"==ex[i])1==par&&(res[nres]=ex.substring(k0,i),k0=i+1,nres++);else if("\n"==ex[i]&&nonewline)return{i:i,res:res};return{i:-1,res:ex.substring(k0)}};function setOggetto(objDestinazione,objSorgente){"object"==typeof objDestinazione&&"object"==typeof objSorgente&&Object.keys(objSorgente).forEach((key=>{Object.hasOwn(objDestinazione,key)&&"function"!=typeof objDestinazione[key]&&(objDestinazione[key]=objSorgente[key])}))}function getOggetto(obj,exclude){return"object"==typeof obj?Object.keys(obj).reduce(((acc,key)=>("function"!=typeof obj[key]&&(exclude&&exclude.length>0&&exclude.includes(key)||(acc[key]=obj[key])),acc)),{}):{}}function fromjson(str,def){if(Array.isArray(str))return str;if("string"!=typeof str)return str;if(""==str)return def||{};try{return JSON.parse(str)}catch(e){return logga(`Errore parsing JSON: ${e}\n${str}`),def||{}}}const errori=new class Errori{constructor(){this.azzera()}azzera(){this.err=[]}add(msg,row){this.err.push({msg:msg,row:row})}get(){return this.err}get length(){return this.err.length}toString(){var cl=[];for(var e of this.err){let m="object"==typeof e.msg?JSON.stringify(e.msg):e.msg||"";cl.push(`${e.row?e.row+":":""}${m}`)}return cl.join("\n")}};function getheaddims(dims){let res;try{res="object"==typeof dims&&dims?dims:JSON.parse(dims||"{}")}catch(error){}return res||(res={}),res.l||(res.l={visible:1,val:1e3,min:0,max:1e4}),res.a||(res.a={visible:1,val:1e3,min:0,max:1e4}),res.p||(res.p={visible:1,val:1e3,min:0,max:1e4}),res}const REGEX_PARENTESI=/(?<!\w)\(/g,REGEX_NUMERO=/^-?[0-9.]+$/,REGEX_FUNZIONE=/^(\w+)(\!)?\[(.*)?\]$/,REGEX_RANDOM=/^(rnd|random|cas)\(/i,REGEX_CLAMP=/^clamp\(/i,REGEX_ROUND=/^(dec|round)\(/i,REGEX_DIGIT=/[0-9.]/,REGEX_OPERATOR=/[+\-*/\^\%]/,REGEX_ALPHA=/[a-zA-Z]/i;function valutaparentesi(expression){for(expression=(expression+"").trim();;){var tm=REGEX_PARENTESI.exec(expression);if(!tm)break;var{i:i,res:res}=parsevar(expression,tm.index+1,"(",")");if(i<=0)break;expression=expression.substring(0,tm.index)+valutaparentesi(res[0])+(i>=0?expression.substring(i+1):"")}return expression=function valutainsiemi(expression){if(expression.includes("[")){function resinisiemi(rr){let v1=rr[1],fl=!!rr[2],vv=getcolonne(rr[3]);for(var v of vv)if(v==v1)return fl?"0":"1";return fl?"1":"0"}for(;;){var rr=REGEX_FUNZIONE.exec(expression);if(!rr)break;var tm=resinisiemi(rr);expression=expression.substring(0,rr.index)+tm+expression.substring(rr.index+rr[0].length)}}return expression}(expression),function operatoricomparazione(expression){let left,right;const operators={"||":()=>valutaparentesi(left)||valutaparentesi(right)?1:0,"|":()=>valutaparentesi(left)||valutaparentesi(right)?1:0,"&&":()=>valutaparentesi(left)&&valutaparentesi(right)?1:0,"&":()=>valutaparentesi(left)&&valutaparentesi(right)?1:0,"<<=":()=>clean(left)<=clean(right),">>=":()=>clean(left)>=clean(right),"===":()=>clean(left)==clean(right),"==":()=>clean(left)==clean(right),"!!":()=>clean(left)!=clean(right),"<<":()=>clean(left)<clean(right),">>":()=>clean(left)>clean(right),"<=":()=>muCalcbase(left)<=muCalcbase(right),">=":()=>muCalcbase(left)>=muCalcbase(right),"<":()=>muCalcbase(left)<muCalcbase(right),">":()=>muCalcbase(left)>muCalcbase(right),"=":()=>muCalcbase(left)==muCalcbase(right),"!":()=>muCalcbase(left)!=muCalcbase(right)};var operatorIndex=-1,op="";for(var operator in operators)if((operatorIndex=expression.indexOf(operator))>=0){op=operator;break}return-1!==operatorIndex?(left=expression.slice(0,operatorIndex),right=expression.slice(operatorIndex+op.length),operators[op]&&operators[op]()?1:0):muCalcbase(expression)}(expression)}const mathFunctions={sqr:x=>Math.sqrt(x),sqrt:x=>Math.sqrt(x),int:x=>Math.floor(x),floor:x=>Math.floor(x),round:x=>Math.round(x),abs:x=>Math.abs(x),sin:x=>Math.sin(x*(Math.PI/180)),cos:x=>Math.cos(x*(Math.PI/180)),tan:x=>Math.tan(x*(Math.PI/180)),atan:x=>Math.atan(x*(Math.PI/180)),atan2:(x,y)=>Math.atan2(x,y)*(Math.PI/180),asin:x=>Math.asin(x*(Math.PI/180)),acos:x=>Math.acos(x*(Math.PI/180))};function muCalcbase(expression){let index=0;function parseOperator(){const op=expression[index];return REGEX_OPERATOR.test(op)?(index++,op):null}function parsePrimary(){if(REGEX_DIGIT.test(expression[index]))return function parseNumber(){const start=index;for(;index<expression.length&®EX_DIGIT.test(expression[index]);)index++;return Number(expression.slice(start,index))}();if("("===expression[index]){index++;const result=parseExpr();return")"===expression[index]&&index++,result}return REGEX_ALPHA.test(expression[index])?function parseFunctions(){var ex=expression.slice(index);if(!ex)return 0;for(const[name,func]of Object.entries(mathFunctions)){const match=new RegExp(`^(${name})\\(`,"i").exec(ex);if(match){index+=match[0].length;const result=func(parseExpr());return")"===expression[index]&&index++,result}}let fn;if(fn=REGEX_RANDOM.exec(ex),fn){index+=fn[0].length;let min=0,max=1;return")"!==expression[index]&&(min=parseExpr(),","===expression[index]?(index++,max=parseExpr()):(max=min,min=0)),")"===expression[index]&&index++,Math.random()*(max-min)+min}if(fn=REGEX_CLAMP.exec(ex),fn){index+=fn[0].length;const a=parseExpr();","===expression[index]&&index++;const b=parseExpr();","===expression[index]&&index++;const c=parseExpr();return")"===expression[index]&&index++,Math.min(Math.max(a,b),c)}if(fn=REGEX_ROUND.exec(ex),fn){index+=fn[0].length;const value=parseExpr();let decimals=0;return","===expression[index]&&(index++,decimals=parseExpr()),")"===expression[index]&&index++,parseFloat(value.toFixed(decimals))}return index++,parseExpr()}():0}function parseFactor(){let left=parsePrimary();for(;index<expression.length&&/[\/\*\^\%]/.test(expression[index]);){const op=parseOperator(),right=parsePrimary();"*"===op?left*=right:"/"===op?left=right?left/right:0:"%"===op?left=right?left%right:0:"^"===op&&(left=Math.pow(left,right))}return left}function parseExpr(){let left=parseFactor();for(;index<expression.length&&/[+\-]/.test(expression[index]);){const op=parseOperator(),right=parseFactor();"+"===op?left+=right:"-"===op&&(left-=right)}return left}return expression=expression.replace(/\s/g,""),parseExpr()}function muCalc(expression){if(!expression)return 0;if("number"==typeof expression)return expression||0;if("string"!=typeof expression)return 0;var s=expression.replaceAll(",",".");return REGEX_NUMERO.test(s)?Number(s)||0:valutaparentesi(expression)||0}function valutavar(sh,res){var vv=res[0]||"";if(!vv)return"";if(sh.counter>=500)return vv;var vx=valutabase(sh,sh.var(valuta0(sh,vv)));if(sh.counter>=500)return vv;if(res[1]){var cols=getcolonne(vx);if("l"==res[1])return String(cols.length);var col=muCalc(valuta0(sh,res[1]));if(!(col>=0&&col<cols.length))return"";vx=valuta0(sh,cols[col])}if(res[2]){var c1=muCalc(valuta0(sh,res[2]));if(c1){var c2=0;return res[3]&&(c2=muCalc(valuta0(sh,res[3]))),c1<0?vx.slice(c1):c2?vx.substring(c1-1,c1+c2-1):vx.substring(c1-1)}}return vx}function valutaquadra(sh,res){var vv=getcolonne(res||""),r1=clean(vv[0]);function replacecharcode(str){return"\\t"==str?"\t":"\\n"==str?"\n":(str||"").replace(/&(\d+)/g,((match,m1)=>String.fromCharCode(parseInt(m1))))}switch(r1){case"set":var m1=valuta0(sh,vv[1]||""),m2=valuta0(sh,vv[2]||"");sh.add(m1,sh.vars(m2));break;case"ex":m1=valuta0(sh,vv[1]||"");(m2=valuta0(sh,vv[2]||""))||(m2=",");var m3=muCalc(valuta0(sh,vv[3]||"")),tm=m1.split(m2);return m3>0&&tm[m3-1]||"";case"ex2":var sep=replacecharcode(vv[1]||""),pos=muCalc(valuta0(sh,vv[2]||""));return vv.splice(0,3),(str=vv.join(";")).split(sep)[pos>0?pos-1:0]||"";case"replace":return vv[1].replace(new RegExp(vv[2]||"x","gim"),(vv[3]||"").trim());case"replace2":case"rp2":try{var search=replacecharcode(vv[1]||"x"),replace=replacecharcode(vv[2]||"").trim();return vv.splice(0,3),search=search.replace(/&(\d+)/g,((match,code)=>`\\u${parseInt(code).toString(16).padStart(4,"0")}`)),vv.join(";").replace(new RegExp(search,"im"),replace)}catch(error){return""}case"look":case"lookb":{let val=parseFloat(vv[1]||"");if(vv=vv.slice(2).map((e=>parseFloat(e)||0)),"lookb"==r1){const filtered=vv.filter((v=>v<=val));return filtered.length?Math.max(...filtered):val}{const filtered=vv.filter((v=>v>=val));return filtered.length?Math.min(...filtered):val}}case"tk":return(pos=muCalc(valuta0(sh,vv[1]||""))||0)?vv[pos>0?pos+1:2]||"":(pos=muCalc(valuta0(sh,vv[2]||"")),sep=vv[1]||"",pos?vv[3].split(sep)[pos-1]:"");case"totab":return vv.splice(0,1),vv.join("\t");case"tosep":sep=replacecharcode(vv[1]||"")||";";return vv.splice(0,2),vv.join(sep);case"len":{let tm;return vv.length>2?(vv.shift(),tm=vv.join(";")):tm=vv[1]||"",tm.length}case"mid":var str=valuta0(sh,vv[1]||""),len=(pos=muCalc(valuta0(sh,vv[2]||"")),muCalc(valuta0(sh,vv[3]||"")));return str.substring(pos-1,pos+len-1);case"arrotonda":{str=muCalc(vv[1]);let coeff=1;return["0","1","2","3","4","5","6"].includes(vv[2])?coeff=Math.pow(10,parseInt(vv[2])):(coeff=muCalc(vv[2]),0==coeff&&(coeff=1e3)),Math.round(str*coeff)/coeff}case"iif":return(str=muCalc(valuta0(sh,vv[1])))?vv[2]||1:vv[3]||0;case"instr":case"instr2":var str1=vv[1]||"",str2=vv[2]||"";return str1.toLowerCase().indexOf(str2.toLowerCase())+1;case"instr2":str2=vv[1]||"";return vv.splice(0,2),vv.join(";").toLowerCase().indexOf(str2.toLowerCase())+1;default:return{fun:r1,pars:vv}}}function valuta0(sh,ex){if(ex+="",sh.counter>=500)return ex;for(;;){const rt=/\$([\{\(])/im.exec(ex);if(!rt)break;var i1=rt.index,{i:i,res:res}="("==rt[1]?parsevar(ex,i1+2,"(",")"):parsevar(ex,i1+2,"{","}");ex=valuta0(sh,ex.substring(0,i1))+valutavar(sh,res)+(i>=0?valuta0(sh,ex.substring(i+1)):"")}return ex=(ex=ex.replace(/\$([a-z|][\w|\.]*)/gi,((match,m1)=>{for(var m2="";m1.length;){var tm=valutabase(sh,sh.var(m1));if(tm||!(m1.length>1)){m2=tm+m2;break}m2=m1.slice(-1)+m2,m1=m1.substring(0,m1.length-1)}return m2}))).replace(/\$(\d+)\:(\d+)(\:(\d+))?/g,((p0,p1,p2,p3,p4)=>{p4=p4?+p4:1;let cl=[];for(let i=+p1;i<=+p2;i+=p4)cl.push(i.toString());return cl.join(";")})),ex}function valutabase(sh,ex){return ex&&(sh.counter++,sh.counter<=500&&(ex=valuta0(sh,ex)),sh.counter--),ex}class Variabile{constructor(){this.dictionary={},this.vec=[],this.counter=0,this.fndotcallback=void 0}static isValidKey(key){return/^[\w][\w\d\.\[\]]*$/.test(key)}static sanitizeKey(key){return key.replace(/[^a-zA-Z0-9_\.\[\]]/g,"_")}setfndot(fndotcallback){this.fndotcallback=fndotcallback}push(){this.vec.push({...this.dictionary})}pop(){this.vec.length>0&&(this.dictionary=this.vec.pop())}clear(){this.vec=[],this.dictionary={}}azzera=()=>this.clear();var(key){let fmt="";const pp=/^(\d+)\.\.(\d+)$/.exec(key);if(pp){var n1=parseInt(pp[1]),n2=parseInt(pp[2]),cl=[];n1>n2&&([n1,n2]=[n2,n1]);for(var i=n1;i<=n2;i++)cl.push(i+"");return cl}if(key.indexOf("|")>=0){let tm=key.split("|");key=tm[0],fmt=tm[1]}function toformat(val,fmt){switch(fmt.trim().toLowerCase()){case"data":return date=parseFloat(val)||0,new Intl.DateTimeFormat("it",{day:"2-digit",month:"short",year:"2-digit"}).format(date.toDate());case"euro":return((n,valorezero="")=>{if(n){var xx=Intl.NumberFormat("en",{style:"currency",currency:"EUR"}).format(n);return xx.replace(/€/g,"").replace(/\./g,";").replace(/,/g,".").replace(/;/g,",")+"€"}return valorezero})(parseFloat(val));case"num":return((n,dec=-1)=>{const num="string"==typeof n?parseFloat(n)||0:n;if(dec<0)return num||0;const factor=Math.pow(10,dec);return Math.round(num*factor)/factor||0})(parseFloat(val));default:return val}var date}const sanitizedKey=Variabile.sanitizeKey(key);if(sanitizedKey.startsWith(".")&&this.fndotcallback){let tm=this.fndotcallback(sanitizedKey.toLowerCase());if(tm)return toformat(tm,fmt)}if(Variabile.isValidKey(sanitizedKey)){const lowercaseKey=sanitizedKey.toLowerCase();var rr=/^([\w][\w\d]*)[\.\[]/.exec(lowercaseKey);if(rr){var tm=this.dictionary[rr[1]];if(tm&&"object"==typeof tm)return toformat(function objval(tm,key){for(var parts=key.split("."),obj=tm,i=0;i<parts.length;i++){var part=parts[i],match=part.match(/(.*?)\[(\d+)\]/);if(match){if(void 0===(obj=obj[match[1]]))return"";obj=obj[parseInt(match[2],10)]}else obj=obj[part];if(void 0===obj)return""}return"number"==typeof obj?obj+"":obj}(tm,lowercaseKey.substring(rr[0].length)),fmt)}return toformat(this.dictionary[lowercaseKey]||"",fmt)}return""}getvar(key){return this.var(key)}colonna(value,index){return getcolonne[index]||value}dump(isstr=!1){var cl=[];for(var t in this.dictionary)cl.push({cod:t,val:this.dictionary[t]});return cl=cl.sort(((a,b)=>a.cod>b.cod)),isstr?cl.map((e=>`${e.cod} = ${e.val}`)):cl}add(key,value){"number"==typeof value&&(value=String(value));const sanitizedKey=Variabile.sanitizeKey(key);if(Variabile.isValidKey(sanitizedKey)){const lowercaseKey=sanitizedKey.toLowerCase();0===value||value?this.dictionary[lowercaseKey]=value:delete this.dictionary[lowercaseKey]}else logga(`Invalid key: ${key}`)}valutasync(str){return valutabase(this,str)}async valuta(ex,callback){var tm=await async function valutafunc(sh,ex,callback){if(ex){for(var ii=0;ii<20;ii++){var i1=ex.lastIndexOf("$[");if(!(i1>=0)){ex=valutabase(sh,ex);break}var{i:i,res:res}=parsevar(ex,i1+2,"[","]"),t1=valutabase(sh,ex.substring(0,i1)),t2=res?valutabase(sh,res[0]):"",t3=i>=0?valutabase(sh,ex.substring(i+1)):"",t4=valutaquadra(sh,t2);"object"==typeof t4&&(t4=callback?await callback(t4?.fun,t4.pars):`** fun: ${t4.fun} ** `),ex=t1+(t4="object"==typeof t4?"**str**":t4+""||"")+t3}return ex}return""}(this,ex,callback);return tm=(ex=>{for(;;){var i1=ex.indexOf("{");if(!(i1>=0))break;var{i:i,res:res}=parsevar(ex,i1+1,"{","}");if(i<0)return ex;ex=ex.substring(0,i1)+muCalc(res[0])+(i>=0?ex.substring(i+1):"")}return ex})(tm),tm}async parametrokeyval(p){if(!(p=p.trim()))return{};let k,v,q,isnum=!1;return p.startsWith("#")&&(isnum=!0,p=p.slice(1)),q=p.indexOf("="),q>0?(k=clean(p.slice(0,q)),v=p.slice(q+1)):(q=p.indexOf(":"),q>0?(k=clean(p.slice(0,q)),v=p.slice(q+1),v=this.var(v)):(k=clean(p),v=this.var(k))),v&&"string"==typeof v&&v.includes("$")&&(v=await this.valuta(v)),["l","a","p"].includes(k)&&(isnum=!0),isnum&&(v=muCalc(v)),{k:k,v:v}}}class CodiceBarra{constructor(){this.barre={}}azzera(){this.barre={}}oriented(t,l,a,p){switch(t=(t||"1").substr(0,1).toLowerCase()){case"0":break;case"l":return{t:"l",x:l};case"a":return{t:"a",x:a};case"p":return{t:"p",x:p};case"2":return{t:t,x:l,y:p,z:a};case"5":return{t:t,x:l,y:a,z:p};case"4":return{t:t,x:p,y:l,z:a};case"3":return{t:t,x:a,y:p,z:l};case"6":return{t:t,x:p,y:a,z:l};default:return{t:"1",x:a,y:l,z:p}}}async getcode(codicebarratot,l,a,p,callback){let[codicebarra,modello]=codicebarratot.split(":");modello=modello||"";var getcode0=async(codicebarra,liv)=>{var barra=this.barre[codicebarra];if(!barra&&callback&&((barra=await callback(codicebarra))||(barra={t:"1",r:[]}),this.barre[codicebarra]=barra,barra.coderr&&"errore"!=barra.coderr||(barra.coderr=`#err_${codicebarra}`)),!barra||0==barra.r.length)return{extra:{err:"missing codicebarra"},c:`#err_${codicebarra}`,fm:10};var{t:t,x:x,y:y,z:z}=this.oriented(codicebarra,l,a,p),extra={barra:codicebarra,fm:barra.fm,t:t,liv:liv,items:barra.r.length,err:""},bx=barra.r;if(z){var t2=bx.filter((e=>e.z===z||!e.z));t2.length>0?bx=t2:extra.err=`spessore non coerente: ${z}`}if("l"==t||"a"==t||"p"==t){if(t=bx.find((e=>e.x>=x)))return{c:t.c,fm:t.x==x?0:1,x1:t.x,x:x,extra:extra}}else{var t;if(t=bx.find((e=>e.x==x&&e.y==y)))return{c:t.c,fm:0,x:x,y:y,z:z,x1:t.x,y1:t.y,z1:t.z,extra:extra};if(0!=barra.fm&&(t=bx.find((e=>e.x>=x&&e.y==y))))return{c:t.c,fm:1,x:x,y:y,z:z,x1:t.x,y1:t.y,z1:t.z,extra:extra};if(0!=barra.fm&&2!=barra.fm&&(t=bx.find((e=>e.x>=x&&e.y>=y))))return{c:t.c,fm:2,x:x,y:y,z:z,x1:t.x,y1:t.y,z1:t.z,extra:extra}}return barra.codalt&&liv<5?await getcode0(barra.codalt,liv+1):{c:barra.coderr,fm:9,x:x,y:y,z:z,extra:extra}};return await getcode0(codicebarra,0)}compila(vettore,headers){headers||(headers={});var barre={};if(Array.isArray(vettore)){for(var r of vettore)if(r.cod=clean(r.cod),r.barcode=clean(r.barcode),r.barcode.length>2&&"+"==r.barcode[0]){r.barcode=r.barcode.substr(1);var tm=this.oriented(r.barcode.substr(0,1),r.l,r.a,r.p);tm.c=r.modello?{c:r.cod,m:r.modello}:r.cod,barre[r.barcode]||(barre[r.barcode]={t:r.barcode.substr(0,1),r:[]},headers[r.barcode]&&(barre[r.barcode]=Object.assign(headers[r.barcode],barre[r.barcode]))),barre[r.barcode].r.push(tm)}for(var x in barre){barre[x].r.sort(((a,b)=>a.y?1e4*(a.x-b.x)+(a.y-b.y):a.x-b.x))}}this.barre=barre}}const keys="IFDEF|IFNDEF|CACHE|CVAR|LOOK|LOOKB|SELECT|CASES|CASE|LOG|MSG|DEFAULT|ELSEIFDEF|ELSEIFNDEF|ELSEIF|ELSE|ENDIF|ENDSELECT|PUSH|POP|FUNC|MACRO|LETS|LETO|LETM|LETT|LETV|LETM|LET|DEF|DO|VARIANTE|FORVAR|FOR|LOOP|ENDFOR|BREAK|EXIT|EXITFOR|CONTINUE|IF|INC|I|F|M|J|:P".split("|");function toCadPars(str){let t0=muClComments(str),t2=[];for(var row of t0){let t1=getcolonne(row,!0),fl=!1;for(var t of t1)!t.startsWith('"')&&t.includes("=")?(t2.push(t),fl=!0):fl&&(t2[t2.length-1]+=","+t)}let pars={};for(var x of t2){let{v:v,o:o}=getcouple(x,"=",!1);v&&o&&(/^[\-+]?\d*\.?\d+$/.test(o)&&(o=parseFloat(o)),pars[v]=o)}return pars}function muClComments(codice,tienivuoti){const righe=(code=codice,code.replace(/("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*')|\/\*[\s\S]*?\*\//g,((match,quoted)=>quoted||""))).split(/\r?\n/);var code;const tm=[];let rigaContinua="";for(const riga of righe){let rigaTrim=riga.trim();if(rigaTrim.includes("//")&&(rigaTrim=rigaTrim.split("//")[0].trim()),0!==rigaTrim.length||tienivuoti)if(rigaContinua.length>0&&(rigaTrim=rigaContinua+" "+rigaTrim,rigaContinua=""),rigaTrim.endsWith("\\")){rigaTrim=rigaTrim.slice(0,-1);const indiceCommento=rigaTrim.lastIndexOf("//");-1!==indiceCommento&&(rigaTrim=rigaTrim.slice(0,indiceCommento).trim()),rigaContinua=rigaTrim}else tm.push(rigaTrim)}return tm}function muClean(tt,acapo=!1){if(Array.isArray(tt)){var tm=[];for(var rigaTrim of tt){const matchComando=rigaTrim.match(/^#([\w\.]+)\s*(.*)$/);if(matchComando){var tipo=matchComando[1].toUpperCase().trim(),tipo2="";if(tipo.includes(".")){var vv=tipo.split(".");tipo=vv[0],tipo2=vv[1]}if(keys.includes(tipo)){const contenuto=matchComando[2];if("IF"!==tipo&&"IFDEF"!=tipo&&"IFNDEF"!=tipo||!contenuto.includes("#")){let tmx={tipo:tipo,contenuto:matchComando[2]};tipo2&&(tmx.tipo2=tipo2),tm.push(tmx)}else{var matchInline=contenuto.match(/^(.*?)\s*#\s*(\w+)\s*(.*?)\s*#\s*(\w+)\s*(.*)$/);matchInline?(tm.push({tipo:tipo,contenuto:matchInline[1].trim()}),tm.push({tipo:matchInline[2].toUpperCase(),contenuto:matchInline[3]}),tm.push({tipo:"ELSE",contenuto:""}),tm.push({tipo:matchInline[4].toUpperCase(),contenuto:matchInline[5]}),tm.push({tipo:"ENDIF",contenuto:""})):(matchInline=contenuto.match(/^(.*?)\s*#\s*(\w+)\s*(.*)$/))?(tm.push({tipo:tipo,contenuto:matchInline[1].trim()}),tm.push({tipo:matchInline[2].toUpperCase(),contenuto:matchInline[3]}),tm.push({tipo:"ENDIF",contenuto:""})):tm.push({tipo:matchComando[1].toUpperCase(),contenuto:matchComando[2]})}}else addgen(rigaTrim)}else addgen(rigaTrim)}for(var nn=0,nf=0,ns=0,lev=[],lef=[],les=[],i=0;i<tm.length;i++){var t=tm[i];switch(t.i=i,t.tipo){case"FOR":case"FORVAR":case"VARIANTE":case"DO":lef[++nf]={pos:i,bk:[]};break;case"LOOP":case"ENDFOR":if(nf>0){var{pos:pos}=lef[nf];for(var b of lef[nf].bk)b.next=i,b.prev=pos;t.prev=pos,tm[pos].next=i,nf--}break;case"BREAK":case"EXIT":case"EXITFOR":case"CONTINUE":nf>0&&lef[nf].bk.push(t);break;case"IF":case"IFDEF":case"IFNDEF":lev[++nn]={pos:i,bk:[t]};break;case"SELECT":les[++ns]={pos:i,bk:[t],first:i};break;case"ELSEIF":case"ELSEIFDEF":case"ELSEIFNDEF":case"ELSE":if(nn>0){var{pos:pos}=lev[nn];lev[nn].bk.push(t),tm[pos].next=i,lev[nn].pos=i}break;case"CASE":case"CASES":case"DEFAULT":if(ns>0){var{pos:pos,first:first}=les[ns];les[ns].bk.push(t),tm[pos].next=i,t.first=first,les[ns].pos=i}break;case"ENDIF":if(nn>0){var{pos:pos,next:next}=lev[nn];for(var b of(tm[pos].next=i,lev[nn].bk))b.last=i;nn--}break;case"ENDSELECT":if(ns>0){var{pos:pos,next:next}=les[ns];for(var b of(tm[pos].next=i,les[ns].bk))b.last=i;ns--}}}return tm}function addgen(r){if(tm.length>0&&""==tm[tm.length-1].tipo){var x=tm[tm.length-1];acapo||!(!r.startsWith("!")&!r.startsWith("."))||r.startsWith("$")||r.startsWith("{")||r.startsWith("#")||x.contenuto.startsWith("!")||x.contenuto.startsWith(".")||x.contenuto.startsWith("$")||x.contenuto.startsWith("{")||x.contenuto.startsWith("#")?tm.push({tipo:"",contenuto:r}):x.contenuto=x.contenuto+"\n"+r}else tm.push({tipo:"",contenuto:r})}errori.add("muClean: expected array!")}function muLimits(dati){var tk,rr=muClComments(dati),tm=[],parsa=v=>v?[...new Set(v.split(",").map((e=>e.trim())).sort().filter((e=>e)))]:void 0;for(var r of rr){var m=/^\s*\{(.*)?\}/im.exec(r);if(m)"limit"==clean(m[1])?(tk={},tm.push(tk)):tk=void 0;else if(tk&&(m=/^\s*\:(\w+)\s*(.*)/.exec(r)))switch(m[1].toLowerCase()){case"opz":case"o":tk.opz=parsa(m[2]);break;case"obs":case"obsolete":tk.obsolete=parsa(m[2]);break;case"scons":case"sconsigliate":tk.scons=parsa(m[2]);break;case"neutri":tk.neutri=parsa(m[2]);break;case"art":tk.art=parsa(m[2]);break;case"mod":tk.mod=parsa(m[2]);break;default:logga("missing:",m[1])}}return tm}function parselimitifromdb(rr){let c,cl=[];if(rr&&rr.length)for(var r of rr){c={},r.varfilter=fromjson(r.varfilter,[]),r.result=fromjson(r.result,[]),r.result2=fromjson(r.result2,[]),r.exclude=parseInt(r.exclude)?1:0,r.exclude2=parseInt(r.exclude2)?1:0;let{item:item,model:model,rule:rule,varfilter:varfilter,result:result,result2:result2,exclude:exclude,exclude2:exclude2,datai:datai,dataf:dataf}=r;function remap(res){return res.map((e=>clean("string"==typeof e?e:e.Value,!0))).filter((e=>e))}if(result.length||result2.length){if(result.length&&(exclude?c.ex=remap(result):c.valid=remap(result)),result2.length&&(exclude2?c.ex2=remap(result2):c.valid2=remap(result2)),item&&(c.i=clean(item).split(";")),model&&(c.m=clean(model).split(";")),rule&&(c.r=clean(rule).split(";")),(datai||dataf)&&datai<dataf&&(c.datai=parseInt(datai),c.dataf=parseInt(dataf)),varfilter&&varfilter.length){c.v=[];for(let x of varfilter){let tm=c.v.find((e=>e.v==clean(x.Variant)));tm||(tm={v:clean(x.Variant),o:[]},c.v.push(tm)),tm.o=[...tm.o,...clean(x.Value).split(";")],tm.o=[...new Set(tm.o.filter((x=>x)))]}}setlevelimite(c),cl.push(c)}}return cl=cl.sort(((a,b)=>b.l-a.l)),cl}function setlevelimite(rs){let l=0;rs.i&&rs.i.length&&(l+=5),rs.m&&rs.m.length&&(l+=3),rs.r&&rs.r.length&&(l+=2),rs.v&&rs.v.length&&(l+=3),rs.datai&&rs.dataf&&(l+=1),rs.l=l}function parselimitifromrule(limvec){function parsevettorelimiti(vec){let rs={};const rx1=/^\s*[\!\:]\s*(\w+)\s*(.*)$/i;function addres(key,data){function addres0(key,d){(d=clean(d))&&(rs[key]||(rs[key]=[]),rs[key].includes(d)||rs[key].push(d))}if(Array.isArray(data))for(var d of data)addres0(key,d);else addres0(key,data)}for(var v of vec){var tm=rx1.exec(v);if(tm)switch(tm[1]){case"var":case"v":case"variante":let i=(tm[2]||"").indexOf(" ");if(i>0){let v1=clean(tm[2].substring(0,i)),v2=getcolonne(tm[2].substring(i+1));if(v1&&v2&&v2.length){rs.v||(rs.v=[]);let tv=rs.v.find((e=>e.v==v1));for(var o of(tv||(tv={v:v1,o:[]},rs.v.push(tv)),v2))tv.o.includes(o)||tv.o.push(o)}}break;case"d":case"dt":case"data":case"date":let vv=tm[2].split(" "),d1=parseInt(vv[0]),d2=parseInt(vv[1]);(d1||d2)&&(rs.datai=d1,rs.dataf=d2);break;case"rule":case"r":case"mu":addres("r",getcolonne(tm[2]));break;case"item":case"i":addres("i",getcolonne(tm[2]));break;case"model":case"m":addres("m",getcolonne(tm[2]));break;case"e":case"escludi":case"exclude":addres("ex",getcolonne(tm[2]))}else addres("valid",getcolonne(v))}return setlevelimite(rs),rs}let limits;if(limvec&&limvec.length){for(var ll of limvec){let rs=parsevettorelimiti(ll);if(rs&&(rs.valid&&rs.valid.length||rs.ex&&rs.ex.length)){let l=0;rs.i&&rs.i.length&&(l+=5),rs.m&&rs.m.length&&(l+=3),rs.r&&rs.r.length&&(l+=2),rs.v&&rs.v.length&&(l+=3),rs.datai&&rs.dataf&&(l+=1),rs.l=l,limits||(limits=[]),limits.push(rs)}}limits&&(limits=limits.sort(((a,b)=>b.l-a.l)))}return limits}class Variante{constructor(amb){this.rows={},this.name="$",this.key="$",this.limits=void 0,this.amb=amb}setheader(id,cat){var{name:name,cat:cat}=checkmu(id,cat);return this.cat=cat,this.name=name,this.alias="",this.obbligo=!1,this.des=name,this.vdef=[],this.rows={},this.h=[],this.key=`${cat}/${name}`,{name:name,cat:cat}}fromdim(dim,colonna=2){"number"!=typeof dim&&(dim=muCalc(dim)),colonna>0&&colonna--;var rsel,max=1e9;for(var kk in this.rows){var row=this.rows[kk];if(!row.annulla){var dd=parseFloat(row.v[colonna])||0;dd<=max&&dd>=dim&&(max=dd,rsel=row)}}return this.#torow(dim,rsel)}async load(id,cat,nofilter=!1){var{name:name,cat:cat}=this.setheader(id,cat);if(cbGetVariante){var content=await cbGetVariante(cat,name);if(content){if(await this.loadContentExtended(content),content.filter)this.limits=parselimitifromdb(content.filter);else if(cbInfo&&!nofilter){let tm=await cbInfo("filter",cat,name);tm&&tm.length&&(this.limits=parselimitifromdb(tm))}return!0}}return!1}async _loadContent(lines){const regx=/^\s*[\!\:]\s*(\w+)\s*(.*)$/i;var ky="";let limit,limits=[],modelimit=!1;for(var currentLine of lines){if("{limit}"==(tm=currentLine.toLowerCase()))limit=[],limits.push(limit),modelimit=!0;else if("{:limit}"==tm)modelimit=!1;else if(modelimit)limit.push(currentLine);else{if(rr=regx.exec(clean(currentLine)))if(ky&&"extra"==rr[1].toLowerCase()){var tm=getcolonne(rr[2]);for(var t of tm){var q=t.indexOf("=");if(q>0){var a=clean(t.substring(0,q));"v"!=a&&(this.rows[ky][a]=t.substring(q+1).trim())}}}else switch(rr[1].toLowerCase()){case"alias":if((vv=rr[2].toLowerCase().split(";"))[0].trim()!=this.name)if(1==vv.length)this.alias=vv[0];else{var vx;this.amb?vx=await this.amb.getvariante(vv[0]):(vx=new Variante,await vx.load(vv[0],this.cat));var rr=vx?.rows;if(rr){var kky=Object.keys(rr);if(kky.length){vv.splice(0,1);const addrows=kk=>{kk&&kk.forEach((k=>this.rows[k]=rr[k]))};for(var t of vv){var rx=/([ei])\s*:\s*(.*)\s*$/im.exec(t);if(rx){for(var k3=rx[2].split(","),i=0;i<k3.length;i++)k3[i]=k3[i].trim();kky="e"==rx[1]?kky.filter((k=>{for(var k2 of k3)if(k.startsWith(k2))return!1;return!0})):kky.filter((k=>{for(var k2 of k3)if(k.startsWith(k2))return!0;return!1}))}}addrows(kky)}}}break;case"h":this.h=getcolonne(rr[2]).map((e=>({des:e})));break;case"t":let tt=getcolonne(rr[2]);if(this.h)for(let i=0;i<this.h.length;i++)this.h[i].t=tt[i]||"";break;case"des":this.des=rr[2];break;case"default":case"vdef":this.vdef=getcolonne(rr[2]);break;case"obbligo":this.obbligo=!0;break;case"noerp":this.noerp=!0;break;case"noobbligo":this.obbligo=!1}else(k=clean((tm=getcolonne(currentLine))[0]))&&(ky=k,this.rows[ky]={annulla:0,v:tm})}}var kk=Object.keys(this.rows);for(var k of kk)if(k.includes(".")){var vv=k.split(".");for(i=0;i<vv.length-1;i++){var k1=vv.slice(0,i+1).join(".");this.rows[k1]||(this.rows[k1]={annulla:0,v:[k1]})}}return this.limits=parselimitifromrule(limits),!0}tovec(){var tm=this.rows,cl=[],xx=Object.keys(tm).sort();for(var x of xx)this.rows[x].annulla<2&&cl.push(this.#torow(x,this.rows[x]));return cl}#torow(cod,tm){var cl=[cod];if(tm)for(var t of tm.v)"string"==typeof t&&(t.includes(",")||t.includes(";"))?cl.push(quote(t)):cl.push(t||"");return cl.join(",")}tovar(cod,vcod=""){var c1=clean(cod);if(!this.rows[c1])return vcod||cod;var tm=this.rows[c1];return 2==tm.annulla?"":this.#torow(vcod||cod,tm)}isvalidopz(opz){let c1=clean(opz),t=this.rows[c1];return!!t&&(1!=t.annulla&&!t.hasliv)}firstvalid(opz){if(opz&&this.isvalidopz(opz))return opz;if(this.vdef&&this.vdef.length)for(var o of this.vdef)if(this.isvalidopz(o))return o;for(var x in this.rows)if(this.isvalidopz(x))return x}resetfilter(){for(var x in delete this._valids,this.rows)this.rows[x].annulla=0}validkeys(){let kk=Object.keys(this.rows)||[];return kk=kk.filter((k=>0==this.rows[k].annulla)).sort(),kk}limitfiltra(filtra){if(this.resetfilter(),!filtra)return;filtra=muClComments(filtra.toLowerCase());let tm=[];for(var f of filtra){let rr=/^\#([ie])(\d*)\s+(.+)$/i.exec(f);if(rr){let t={ex:"e"==rr[1],col:(parseInt(rr[2])||1)-1,val:getcolonne(rr[3])};t.val.length&&tm.push(t)}}if(tm.length)for(var x in this.rows){let r=this.rows[x];for(var t of tm)if(t.ex){if(_check(r.v[t.col]||"",t.val)){r.annulla=1;break}}else if(!_check(r.v[t.col]||"",t.val)){r.annulla=1;break}}function _check(value,valori){return!!valori.find((e=>e.startsWith(value)))}}limita(filtra){if(filtra&&filtra.length)return this.limitfiltra(filtra);if(!this.limits||!this.amb)return this.resetfilter();let{item:item,rule:rule,model:model,vari:vari,data:data}=this.amb,valid=(v,values)=>!values||!values.length||!!v&&values.includes(v),tm=this.limits.filter((e=>{if(!valid(item,e.i))return!1;if(!valid(rule,e.r))return!1;if(!valid(model,e.m))return!1;if(data&&e.datai&&data<e.datai)return!1;if(data&&e.dataf&&data>e.dataf)return!1;if(e.v&&e.v.length)for(var v of e.v){let x=clean(vari.var(v.v).split(",")[0],!0);if(x&&!v.o.includes(x))return!1}return!0}));if(!tm||!tm.length)return this.resetfilter();let incstar=new Set,exstar=new Set,incaltri=new Set,exaltri=new Set,isinc=!1,isex=!1;for(var t of tm){if(t.valid&&t.valid.length){isinc=!0,t.valid.filter((e=>e.indexOf("*")>0)).map((e=>e.split("*")[0])).forEach((item=>incstar.add(item))),t.valid.filter((e=>!e.includes("*"))).forEach((item=>incaltri.add(item)))}if(t.ex&&t.ex.length){isex=!0,t.ex.filter((e=>e.indexOf("*")>0)).map((e=>e.split("*")[0])).forEach((item=>exstar.add(item))),t.ex.filter((e=>!e.includes("*"))).forEach((item=>exaltri.add(item)))}}for(var x in this.rows){let r=this.rows[x],flinc=!1,flex=!1;if(isinc){for(let i of incstar)if(x.startsWith(i)){flinc=!0;break}!flinc&&incaltri.has(x)&&(flinc=!0)}if(isex){for(let i of exstar)if(x.startsWith(i)){flex=!0;break}!flex&&exaltri.has(x)&&(flex=!0)}r.annulla=0,isinc&&!flinc&&(r.annulla=1),isex&&flex&&(r.annulla=1)}return tm}async loadContentExtended(content){if("object"==typeof content){for(var x in content)["rows","des","h","alias","obbligo"].includes(x)&&(this[x]=content[x]);"string"==typeof content.def&&content.def.length&&(this.vdef=getcolonne(content.def.trim().toLowerCase())),content.filter&&content.filter.length&&(this.limits=parselimitifromdb(content.filter))}else await this._loadContent(muClComments(content,!1))}todata(){return{name:this.name,des:this.des,alias:this.alias,obbligo:this.obbligo,h:this.h,rows:this.rows,limits:this.limits,key:this.key}}}let _nofunc={};async function getcbfunc(tm,cmd,pars,vari,amb,output){if(cbFunc){if(_nofunc[cmd])return"";let a=await cbFunc(cmd,pars,vari,amb,output);return a=(a||"").trim(),"!"==a&&(_nofunc[cmd]=!0,a=""),a}return tm}async function intvaluta(amb,mac,str){return await amb.vari.valuta(str,(async(fun,pars)=>{if("dim"===fun){var dm=muCalc(pars[1]),vv=await dammivariante(amb,mac,pars[2]),col=parseInt(pars[3])||2;return vv&&vv.fromdim?vv.fromdim(dm,col):dm}return await getcbfunc(`**fun:${fun}**`,fun,pars,amb.vari,amb)}))}async function dammivariante(amb,macro,ky){return macro&¯o?.localvar&¯o.localvar[ky]?macro.localvar[ky]:await amb.getvariante(ky)}async function impostavariante(amb,macro,a,b,head){let tm,ky=a;if((b=b||"")&&"string"==typeof b){var k=b.indexOf(":");k>=0&&(k>0&&(ky=clean(b.slice(0,k))),b=b.slice(k+1))}if(head&&head.alias&&(ky=head.alias),macro&¯o.paralias&¯o.paralias[a]&&(ky=macro.paralias[a]),tm=await dammivariante(amb,macro,ky),tm)if(head&&head.t){head.des||(head.des=tm.des);let x8=head?.filtra||"";if(x8.includes("$")&&(x8=await amb.vari.valuta(x8)),"m"===head.t){var col=2;if(b.includes(":")){var xx=b.split(":");col=parseInt(xx[1]),b=xx[0]}tm.limita(x8),b=tm.fromdim(parseFloat(b),col)}else{tm.limita(x8);let b1=tm.firstvalid(b);b=tm.tovar(b1)}}else tm.resetfilter(),b=tm.firstvalid(b),b=tm.tovar(b);else head&&head.t&&head.t;return amb.vari.add(a,b),b}async function pushpars(amb,macro,parsfunzione,parsinit){var fatti={},vals=[];if(parsfunzione)for(var x of parsfunzione){var{v:v,o:o,fl:fl}=getcouple(x);fatti[v]||(fatti[v]=!0,vals.push({v:v,o:amb.vari.var[v]}),fl&&await impostavariante(amb,macro,v,o))}if(parsinit)for(var x of parsinit){var{v:v,o:o,fl:fl}=getcouple(x);fatti[v]||(fatti[v]=!0,vals.push({v:v,o:amb.vari.var[v]}),fl&&await impostavariante(amb,macro,v,o))}return vals}async function poppars(amb,tm){if(tm)for(var x of tm)amb.vari.add(x.v,x.o)}const outpush=(output,a)=>{null!=a&&null!=a&&("string"==typeof a&&a.startsWith("_ ")&&output.length>0&&"string"==typeof output[output.length-1]&&!tipo?output[output.length-1]+=a.slice(2):output.push(...a.split("\n")))};async function muEval(amb,mac,codice,options){if(!Array.isArray(codice))return errori.add("codice is not a valid parsed array"),[];options||(options={}),options.id||(options.id="_"),options._stackmacro||(options._stackmacro=0),options.limited||(options.limited=!1),amb||errori.add("amb deve essere definito");let vari=amb.vari;amb.maxdelays,amb.cat;let output=[];xdt();for(var ii=0;ii<codice.length;){var riga=codice[ii];switch(riga.tipo){case"IFDEF":case"IFNDEF":case"IF":var tm="IF"==riga.tipo?muCalc(await intvaluta(amb,mac,riga.contenuto)):"IFDEF"==riga.tipo?""!=await intvaluta(amb,mac,riga.contenuto):""==await intvaluta(amb,mac,riga.contenuto);riga.next?(codice[riga.next].jlast=tm?1:0,tm||(ii=riga.next-1)):errori.add("Troppo tempo",riga);break;case"SELECT":riga.next?(codice[riga.next].t1=await intvaluta(amb,mac,riga.contenuto),ii=riga.next-1):errori.add("manca endselect",riga);break;case"CASE":case"CASES":case"DEFAULT":if(riga.next)if(riga.jlast)riga.jlast=0,ii=riga.last-1;else{tm=1;let vv;var _getvv=async()=>{var vv=await intvaluta(amb,mac,riga.contenuto);return vv=vv.includes(":")&&!vv.includes(",")?vv.split(":").map((e=>(e||"").trim())):getcolonne(vv)};if("CASE"==riga.tipo){tm=0,vv=await _getvv();var tmx=muCalc(riga.t1||"");vv.find((v=>muCalc(v)==tmx))&&(tm=1)}else if("CASES"==riga.tipo){tm=0,vv=await _getvv();tmx=riga.t1||"";vv.find((v=>v==tmx))&&(tm=1)}codice[riga.next].jlast=tm?1:0,codice[riga.next].t1=riga.t1,tm||(ii=riga.next-1)}else errori.add("manca select",riga);break;case"ELSEIF":case"ELSEIFDEF":case"ELSEIFNDEF":case"ELSE":if(riga.next)if(riga.jlast)riga.jlast=0,ii=riga.last-1;else{tm="ELSE"==riga.tipo?1:"ELSEIF"==riga.tipo?muCalc(await intvaluta(amb,mac,riga.contenuto)):"ELSEIFDEF"==riga.tipo?""!=await intvaluta(amb,mac,riga.contenuto):""==await intvaluta(amb,mac,riga.contenuto);codice[riga.next].jlast=tm?1:0,tm||(ii=riga.next-1)}else errori.add("manca endif",riga);break;case"ENDIF":case"ENDSELECT":case"CACHE":case"CVAR":break;case"PUSH":vari.push();break;case"POP":vari.pop();break;case"J":await getcbfunc("$$","$$",await intvaluta(amb,mac,riga.contenuto),vari,amb,output);break;case"INC":case"I":if(options._stackmacro>500)errori.add("stack chiamate macro troppo profondo!",riga);else{var{macro:macro,pars:pars,xid:xid}=await amb.getmacro(riga)||{};if(macro){options._inc=!0,options._stackmacro++;let saved={},parametri=macro.parametri?._;if(parametri&¶metri.length)for(var x of parametri){let x1=clean(x.split("=")[0]||"",!0);x1&&(saved[x1]=vari.dictionary[x1])}await macro.impostaparametri(parametri,pars);let rs1=await muEval(amb,macro,macro.codice,options);for(var v in saved)saved[v]?vari.dictionary[v]=saved[v]:delete vari.dictionary[v];output.push(...rs1),options._stackmacro--,options._inc=!1}}break;case"MACRO":case"M":case"FUNC":case"F":if(options._stackmacro>500)errori.add("stack chiamate macro troppo profondo!",riga);else{var{macro:macro,pars:pars,xid:xid}=await amb.getmacro(riga)||{};if(macro){let ismacro=options.grafica||["F","FUNC"].includes(riga.tipo),optid=options.id||"",parametri=macro.parametri?._,saved={};if(ismacro)vari.push();else{if(macro.head)for(var x in macro.head)saved[x]=amb.vari.var(x);if(parametri&¶metri.length)for(var x of parametri){let x1=(x.split("=")[0]||"").trim().toLowerCase();x1&&(saved[x1]=vari.dictionary[x1])}}if(macro.codice.length){if(options._stackmacro++,options.grafica&&"function"==typeof options.grafica){let f="",xid="";pars&&pars.length?(f=pars.find((e=>e.startsWith("#id"))),f?(f=await vari.valuta(f.slice(3)),options.id=hash(`${ii}${macro.name}${optid}${f}`),pars=pars.filter((e=>!e.startsWith("#id"))),xid=options.id):options.id=hash(`z${optid}${ii}`)):options.id=hash(`z${optid}${ii}`);let out=await options.grafica({tipo:riga.tipo,id:xid,pars:pars,parametri:parametri,macro:macro,options:options,vari:amb.vari,amb:amb});output.push(out)}else{await macro.impostaparametri(parametri,pars);let rs1=await muEval(amb,macro,macro.codice,options);output.push(...rs1)}options._stackmacro--}if(ismacro)vari.pop();else for(var v in saved)saved[v]?vari.dictionary[v]=saved[v]:delete vari.dictionary[v];options.id=optid}else errori.add("Macro non trovata!",riga)}break;case"LET":case"LETS":var j=-1;if((i=riga.contenuto.indexOf("="))>=0&&(j=riga.contenuto.indexOf("=",i+1)),j<0){if((i=(v=riga.contenuto).indexOf("="))>0){var a=await intvaluta(amb,mac,v.slice(0,i).trim()),b=v.slice(i+1).trim();b="LET"==riga.tipo?muCalc(await intvaluta(amb,mac,b))||"":await intvaluta(amb,mac,b),vari.add(a,b)}}else{var vv=getcolonne(riga.contenuto);for(var v of vv){if((i=v.indexOf("="))>0){a=await intvaluta(amb,mac,v.slice(0,i)),b=v.slice(i+1).trim();b="LET"==riga.tipo?muCalc(await intvaluta(amb,mac,b))||"":await intvaluta(amb,mac,b),vari.add(a,b)}}}break;case"LETT":var i;if((i=riga.contenuto.indexOf("="))>0){a=await intvaluta(amb,mac,riga.contenuto.slice(0,i).trim()),b=riga.contenuto.slice(i+1).trim();vari.add(a,b)}break;case"LOOK":case"LOOKB":{let cc=getcolonne(await intvaluta(amb,mac,riga.contenuto)),base=muCalc(cc[1]),col=muCalc(cc[3]),ww=await dammivariante(amb,macro,cc[2]);if(ww&&ww.rows){let rr=Object.values(ww.rows).reduce(((t,e)=>{let val=parseInt(e.v[col?col-1:0]);return val&&("LOOKB"==riga.tipo?val<=base&&val>t.v&&(t.v=val,t.c=e.v[0]):val>=base&&val<t.v&&(t.v=val,t.c=e.v[0])),t}),{v:"LOOKB"==riga.tipo?0:1/0,c:""});rr&&rr.c&&(amb.vari.add(cc[0],ww.tovar(rr.c)),options.checkheader&&"function"==typeof options.checkheader&&await options.checkheader({variante:cc[0],valore:ww.tovar(rr.c),riga:riga}))}else amb.vari.add(cc[0],`${base},no,no`)}break;case"LETV":case"LETM":case"DEF":if(tm=getcolonne(riga.contenuto))for(var x of tm){var{v:v,o:o,fl:fl}=getcouple(x);if(fl){v=await vari.valuta(v),o=await intvaluta(amb,mac,o);let valore=await impostavariante(amb,mac,v.trim().toLowerCase(),o.trim().toLowerCase(),"LETM"==riga.tipo?{t:"m"}:{t:"v"});options._stackmacro<=0&&options.checkheader&&"function"==typeof options.checkheader&&await options.checkheader({variante:v,valore:valore,riga:riga})}}break;case"DO":fl=!0;(valido=(riga.contenuto||"").trim())&&!muCalc(await intvaluta(amb,mac,valido))&&(fl=!1),riga.next&&(fl||(ii=riga.next+1));break;case"VARIANTE":case"FORVAR":case"FOR":{var valido,elenco;if(options.oldstyle)v=(vv=riga.contenuto.split(","))[2]||"i",elenco=vv[0],valido=vv[1];else v=(vv=getcolonne(riga.contenuto||""))[0]||"",elenco=clean(vv[1],!0),valido=vv[2]||"";if(v=v.includes("$")?await intvaluta(amb,mac,v):v||"","FORVAR"==riga.tipo||"VARIANTE"==riga.tipo){var xx=(tm=await intvaluta(amb,mac,elenco))?await dammivariante(amb,mac,tm):void 0;xx?elenco=xx.tovec():(elenco=[],errori.add("getvariante not found!",riga))}else{var txx=await intvaluta(amb,mac,elenco||"");elenco=elenco?getcolonne(txx):void 0}elenco=elenco||[];let nc=0;if(riga.next){(rr=codice[riga.next]).for={v:v,elenco:elenco,nc:nc,valido:valido};var voce;fl=!0;v&&elenco.length>0?nc>=elenco.length?fl=!1:(voce=elenco[nc],vari.add(v,voce),valido&&(fl=!muCalc(await intvaluta(amb,mac,valido)))):fl=!1,fl||(ii=riga.next-1)}else errori.add("manca endfor/loop",riga)}break;case"LOOP":var fl=!0;riga.contenuto&&!muCalc(await intvaluta(amb,mac,riga.contenuto))&&(fl=!1),fl&&(ii=riga.prev-1);break;case"ENDFOR":if(!riga.contenuto||muCalc(await intvaluta(amb,mac,riga.contenuto)))if(riga.for){var{v:v,elenco:elenco,valido:valido}=riga.for;if(v&&elenco.length>0&&riga.for.nc<500)for(;;){if(riga.for.nc++,riga.for.nc<elenco.length){if(vari.add(v,elenco[riga.for.nc]),valido&&muCalc(await intvaluta(amb,mac,valido)))continue;ii=riga.prev;break}break}}else errori.add("manca istruzione for",riga);break;case"BREAK":case"EXIT":case"EXITFOR":riga.next?riga.contenuto.trim()?muCalc(await intvaluta(amb,mac,riga.contenuto))&&(ii=riga.next):ii=riga.next:errori.add("break outside loop",riga);break;case"CONTINUE":riga.next?riga.contenuto&&!muCalc(await intvaluta(amb,mac,riga.contenuto))||(ii=riga.next-1):errori.add("continue outside loop",riga);break;case"MSG":case"LOG":let tm99=await intvaluta(amb,mac,riga.contenuto);logga(tm99),errori.add(tm99);break;default:{let tm;if(riga.contenuto.startsWith("!")){tm=await intvaluta(amb,mac,riga.contenuto);var rr;a="";if(rr=/^\!(\w+)[\s;,]\s*(.+)?$/gim.exec(tm)){var cmd=rr[1].toLowerCase(),pars=getcolonne(rr[2]||"");a=await getcbfunc(tm,cmd,pars,vari,amb)}a&&outpush(output,a)}else options.parsefnpunto&&"function"==typeof options.parsefnpunto&&riga.contenuto.startsWith(".")?await options.parsefnpunto({dati:riga.contenuto,output:output,id:options.id,vari:amb.vari,amb:amb}):(tm=await intvaluta(amb,mac,riga.contenuto),outpush(output,tm))}}ii++}return output}async function muGenerate(macro,amb,genera,callback,isTestmode=0){if(macro.isgenera&&callback){var output={counter:0,keys:{},isTestmode:isTestmode};if(genera){if(!macro.genera[genera])return!1;await muGenerate_0(macro,amb,genera,callback,output)}else for(var gg in macro.genera)await muGenerate_0(macro,amb,gg,callback,output);return!0}}async function muGenerate_0(mac,amb,genera,callback,output){var xgen=mac.genera[genera];if(xgen){output.counter2=0;var working_variant={},levels=[];async function processavariante(liv){if(!(output.isTestmode&&output.counter>output.isTestmode)){if(liv<xgen.vars.length){var xx=xgen.vars[liv];if(!working_variant[xx]){var xvar=await dammivariante(amb,mac,xx),keys=Object.keys(xvar.rows);if(keys&&keys.length>0){for(var k of keys)levels.push(k),amb.vari.add(xvar.name,xvar.tovar(k)),working_variant[xx]=!0,await processavariante(liv+1),working_variant[xx]=!1,levels.pop();return}logga("manca la variante",xx)}}for(var x of xgen.calcola)mac.formula[x]&&await muEval(amb,mac,mac.formula[x],{limited:!0});for(var x of xgen.exclude){if(mac.formula[x])if(vvv=await muEval(amb,mac,mac.formula[x],{limited:!0}))for(var v of vvv){if(muCalc(v))return}}var out1=await muEval(amb,mac,xgen.codice,{limited:!0,localvar:mac.localvar}),bb={};for(var x of xgen.bom)if(mac.formula[x]){var vvv=await muEval(amb,mac,mac.formula[x],{limited:!0});for(var v of vvv=vvv.join("\n").split("\n"))if(v){var tm=getcolonne(v);bb[x]||(bb[x]=[]);for(var t={},i=0;i<tm.length;i++)t[`c${i}`]=tm[i];bb[x].push(t)}}await async function docallback(callback,out1,bom,xgen,genera,output){var fl=!0;for(var x of out1){var tm=getcolonne(x);if(tm[0]&&!output[tm[0]]){output[tm[0]]=1,output.counter++,output.counter2++;for(var o={__id:output.counter},i=0;i<tm.length;i++){var key=xgen.head[i]?xgen.head[i]:`c${i}`;"#"==key[0]?o[key=key.substr(1)]=muCalc(tm[i]):o[key]=tm[i]}await callback(genera,o,fl?bom:void 0,output.counter,output.counter2),fl=!1}}}(callback,out1,bb,xgen,genera,output)}}await processavariante(0)}}const DIMS=["l","a","p"],rx1=/^\{(\:?(var|valid|formula|genera|header|v|f|g|h))[\s|\}]/im,tipifree=["s","g","h","p","q"],tipiheader=[{cod:"t",des:"Variante"},{cod:"q",des:"V.Query"},{cod:"f",des:"Valore Fisso"},{cod:"g",des:"Gruppo"},{cod:"s",des:"Libero"},{cod:"m",des:"Misura"},{cod:"c",des:"Check (no/si)"},{cod:"z",des:"Check (si/no)"},{cod:"h",des:"Hidden"},{cod:"p",des:"Programmato"}],tipicolonna=[{cod:"",des:"Libero"},{cod:"a",des:"Area"},{cod:"t",des:"Thumb",folder:"thumbs"},{cod:"i",des:"Image",folder:"textures"},{cod:"x",des:"3D file",folder:"3d"},{cod:"f",des:"Funzione",folder:"script"}];function valutaCondizioniTestata(vari,str){var vv=str.split("\n");for(var v of vv)if(v.trim()){if(muCalc(vari.valutasync(v)))return!0}return!1}class Macro{constructor(amb,name){var{name:name,cat:cat}=checkmu(name,amb.cat||"");this.name=name,this.cat=cat,this.amb=amb,this.azzera()}azzera(){this.key=`${this.cat}/${this.name}`,this.localvar={},this.head=[],this.frontend=!1,this.valid=[],this.parametri={},this.paralias={},this.formula={},this.settings={},this.errori=[],this.codice=[],this.genera={}}get isgenera(){return Object.keys(this.genera).length||0}get iscodice(){return this.codice.length||0}get isheader(){return this.head?.length||0}geterrori(){var cl=[];return this.errori.forEach((e=>cl.push({e:e}))),cl}getparametri(){let s={};if(this.dims&&DIMS.forEach((k=>{let t=muCalc(this.amb.vari.var(k));t&&(s[k]=String(t))})),this.head){for(var x of this.head)if(!x._h){var tm=this.amb.vari.var(x.cod);tipifree.includes(x.t)||"string"==typeof tm&&(tm=tm.split(",")[0]),s[x.cod]=tm}}else if(this.parametri?._)for(var x of this.parametri._){let x1=(x.split("=")[0]||"").trim().toLowerCase();tm=((tm=this.amb.vari.var[x1])||"").split(",")[0],s[x1]=tm}return s}async setparametri(pars){let ff={};for(var x of(pars||(pars={}),this.dims&&DIMS.forEach((e=>{let t=pars[e]||this.dims[e].val;t=parseFloat(t)||0,this.dims[e].visible&&(t<this.dims[e].min&&(t=this.dims[e].min),t>this.dims[e].max&&(t=this.dims[e].max)),pars[e]=String(t)})),this.head))"g"!=x.t&&("z"!=x.t||pars[x.cod]||(pars[x.cod]="1"),x._v=pars[x.cod],ff[x.cod]=!0);for(var x in pars)ff[x]||(ff[x]=!0,await impostavariante(this.amb,this,x,pars[x]));return this.head?.length>0&&await this.setparametro(this.head[0].cod,pars[this.head[0].cod]||void 0,!0),this.getparametri()}async setparametro(name,value,propaga=!1){if(value&&value.includes("$")&&(value=await intvaluta(this.amb,this,value)),this.head){const _imposta=async(riga,vv,id)=>{let nn=riga?.cod;if(riga.valid&&!riga._h1){let t0=!valutaCondizioniTestata(this.amb.vari,riga.valid);if(riga._h!=t0&&(riga._h=t0,["g","g1","g2"].includes(riga.t)))for(let i=id+1;i<this.head.length;i++){let tm1=this.head[i];if(tm1){if(["g","g1","g2"].includes(tm1.t))break;tm1._h1=riga._h}}}if(riga._h||riga._h1)return this.amb.vari.add(nn,""),riga._v=void 0,"";{if(delete riga._h2,riga.visible){let t0=!valutaCondizioniTestata(this.amb.vari,riga.visible);if(t0&&(riga._h2=t0),["g","g1","g2"].includes(riga.t))for(let i=id+1;i<this.head.length;i++){let tm1=this.head[i];if(tm1){if(["g","g1","g2"].includes(tm1.t))break;riga._h2?tm1._h3=riga._h2:delete tm1._h3}}}let tx=this.amb.vari.var(nn)||"";if("string"==typeof tx&&(tx=tx.split(",")[0]),"z"!=riga.t||tx||(this.amb.vari.add(nn,"1"),tx="1"),"m"==riga.t&&riga.spars){let vspars=getcolonne(riga.spars);tx=parseFloat(tx||vspars[0])||0,vspars[1]&&parseFloat(tx)<vspars[1]&&(tx=parseFloat(vspars[1])||0),vspars[2]&&parseFloat(tx)>vspars[2]&&(tx=parseFloat(vspars[2])||0),tx=String(tx),this.amb.vari.add(nn,tx)}let tmimposta=await impostavariante(this.amb,this,nn,vv||riga._v||tx,riga);return riga._v=void 0,tx=this.amb.vari.var(nn)||"",this.amb&&this.amb.deriva&&this.amb.deriva.length>0&&this.amb.deriva.filter((e=>e.cod==nn&&((!e.item||e.item==this.amb.item)&&((!e.model||e.model==this.amb.model)&&((!e.rule||e.rule==this.amb.rule)&&(!e.opz||e.opz==vv)))))),tmimposta}};let tm,i0=-1;if("#dim"==name)propaga=1;else{if(i0=this.head.findIndex((e=>e.cod===name)),i0<0)return;let hh=this.head[i0];tm=await _imposta(hh,value,i0),delete hh._d}if(propaga)for(let i=i0+1;i<this.head.length;i++)await _imposta(this.head[i],void 0,i);return tm}return await impostavariante(this.amb,this,name,value)}async impostaparametri(parimposta,parcall,ismacro=!1){if(this.head)for(var i of(this.paralias||(this.paralias={}),Array.isArray(this.head)||(this.head=[]),this.head))i._v="",delete i._h,delete i._h1,delete i._h2,i.alias&&(this.paralias[i.cod]=i.alias);for(var x of(parimposta||(parimposta=[]),parcall||(parcall=[]),[...parimposta,...parcall])){if((i=x.indexOf("="))>0){let a=clean(x.substr(0,i));a.includes("$")&&(a=await intvaluta(this.amb,this,a));let t,b=x.substr(i+1);b.includes("$")&&(b=await intvaluta(this.amb,this,b)),this.head&&(t=this.head.find((e=>e.cod==a)))?t._v=b:await impostavariante(this.amb,this,a,b)}}if(this.head){let fl=!0;for(var h of this.head){let fl2=await this.checkvalid(h.valid);ismacro&&(fl2=!0),["g","g1","g2"].includes(h.t)?fl=fl2:fl&&fl2&&await this.setparametro(h.cod,h._v)}}}async checkvalid(formula){if(!formula)return!0;return!!muCalc(await intvaluta(this.amb,this,formula))}getmacrostr(){return JSON.stringify(this.getmacro())}getmacro(){return getOggetto(this,["amb"])}setmacro(vv){if(setOggetto(this,fromjson(vv,{})),this.localvar)for(var x in this.localvar){setOggetto(vv=new Variante,this.localvar[x]),this.localvar[x]=vv}}async load(xname,xcat){try{var tm,{name:name,cat:cat}=checkmu(xname||this.name,xcat||this.cat||"");if(this.name||(this.name=name),this.cat||(this.cat=cat),this.azzera(),cbGetMacro&&("string"==typeof(tm=await cbGetMacro(cat,name))&&(tm.startsWith("{")||tm.startsWith("["))&&(tm=fromjson(tm)),tm&&tm.head&&!Array.isArray(tm.head)&&(tm.head=[]),tm.head&&(tm.dims=getheaddims(tm.dims))),tm){if("string"==typeof tm)await this.parsedata(tm);else for(var x in tm)this[x]=tm[x];return!0}errori.add(`missing cbGetFile: ${cat}/${name}`)}catch(error){errori.add(geterrdes(error),`macro.load: ${name}/${cat}`)}}async loadAndCompile(file,cat,acapo=!1){var res,{name:name,cat:cat}=checkmu(file,this.cat||cat);return this.azzera(),cbGetFile&&(res=await cbGetFile(cat,name)),res?(await this.parsedata(res,acapo),this.getmacro()):void errori.add(`missing cbGetFile: ${name}/${cat}`)}async#loadinclude(file,flin,stak,pp){var res,{name:name,cat:cat}=checkmu(file,this.cat);if(cbGetFile&&(res=await cbGetFile(cat,name)),!res)return[];if(res.includes("$1")&&pp&&pp.length>0)for(var i=1;i<pp.length;i++)res=res.replaceAll(`$${i}`,pp[i]);var tm=muClComments(res),t2=[];for(var t of(flin&&(tm=tm.filter((t=>!/^\{(\:?(var|valid|formula|header|genera|v|f|h))[\s|\}]/im.test(t)))),tm)){const rr=rx1.exec(t);if(rr)flin=!rr[1].startsWith(":"),t2.push(t);else{const r1=/^\s*\{i\s(.+)?\}/im.exec(t);if(r1){pp=getcolonne(r1[1]);if(!stak.includes(pp[0])){stak.push(pp[0]);var t3=await this.loadinclude(pp[0],flin,stak,pp);Array.isArray(t3)&&t2.push(...t3),stak.pop()}}else t2.push(t)}}return t2}async parsedata(res,acapo=!1){if(this.azzera(),!res)return;var t2=[],tm=muClComments(res),flin=!1;let lochead=[];for(var t of tm){const rr=rx1.exec(t);if(rr)flin=!rr[1].startsWith(":"),t2.push(t);else{const r1=/^\s*\{i\s(.+)?\}/im.exec(t);if(r1){var pp=getcolonne(r1[1]),t3=await this.#loadinclude(pp[0],flin,[pp[0]],pp);Array.isArray(t3)&&t2.push(...t3)}else t2.push(t)}}flin=!1;var out=this.codice;for(var t of t2){const rr=rx1.exec(t);if(rr)if(rr[1].startsWith(":"))out=this.codice;else switch(rr[1]){case"genera":case"g":if(r2=/^\s*\{(genera|g)\s+(.+)?\}/im.exec(t)){var name=checkname(getcolonne(r2[2])[0]);this.genera[name]=[],out=this.genera[name]}else(out=this.errori).push(t);break;case"valid":out=this.valid;break;case"var":case"v":if(r2=/^\s*\{(var|v)\s+(.+)?\}/im.exec(t)){var nn=getcolonne(r2[2]);name=checkname(nn[0]);this.localvar[name]={name:name,des:nn[1]||"",rows:[]},out=this.localvar[name].rows}else(out=this.errori).push(t);break;case"formula":case"f":var r2;if(r2=/^\s*\{(formula|f)\s+(.+)?\}/im.exec(t)){name=checkname(r2[2]);this.formula[name]=[],out=this.formula[name]}else(out=this.errori).push(t);break;case"h":case"header":out=lochead;break;default:this.errori.push(t),out=this.errori}else t.startsWith("{")&&(out=this.codice),out.push(t)}for(var f in this.parametri={},this.codice=this.cleanfiltraparametri("_",this.codice,acapo),this.formula)this.formula[f]=this.cleanfiltraparametri(f,this.formula[f],acapo);for(var f in this.localvar){var vv=new Variante,v=this.localvar[f];for(var x of(vv.setheader(f,this.cat),vv.rows={},v.rows)){var k=(c=getcolonne(x))[0].trim().toLowerCase();vv.rows[k]={annulla:0,v:c}}v.des&&(vv.des=v.des),this.localvar[f]=vv}tm=this.valid;for(var t of(this.valid=[],tm)){(p={v:(p=getcouple(t,",")).v,msg:p.o}).v&&(p.v.startsWith("#")?this.formula[p.v.substring(1)]&&this.valid.push(p):this.valid.push(p))}tm=lochead;var head=[];for(var t of tm){if(rr=/^\s*([\w\-\_]+)+[\;\,\s]\s*(.*)?$/im.exec(t)){var c;pp=getcolonne(rr[2]);let ht;if(c=clean(rr[1]))for(var tp of(ht=head.find((e=>e.cod==c)),ht||(ht={cod:c,t:"t"},head.push(ht)),pp)){var p;switch((p=getcouple(tp)).v){case"t":ht.t=p.o;break;case"def":case"default":ht.def=p.o;break;case"valid":case"colonna":case"hidden":p.o.startsWith("#")?this.formula[p.o.substring(1)]&&(ht[p.v]=p.o):ht[p.v]=p.o;break;default:ht[p.v]=p.o}}}}this.head=head;tm=this.genera;var genera={};for(var kk in tm)if(Array.isArray(tm[kk])){var gen={codice:[],head:"",calcola:[],bom:[],vars:[],exclude:[]};const regx=/^\s*[\!\:]\s*(\w+)\s*(.*)$/i;for(var k2 of tm[kk]){var rr;if(rr=regx.exec(clean(k2)))switch(rr[1]){case"calcola":case"c":gen.calcola=[...gen.calcola,...getcolonne(rr[2])];break;case"exclude":case"e":case"escludi":gen.exclude=[...gen.exclude,...getcolonne(rr[2])];break;case"bom":case"db":gen.bom=[...gen.bom,...getcolonne(rr[2])];break;case"vars":case"v":gen.vars=[...gen.vars,...getcolonne(rr[2])];break;case"head":case"h":gen.head=getcolonne(rr[2]);break;default:this.errori.push(`genera ${kk} => ${k2}`)}else gen.codice.push(k2)}gen.codice=muClean(gen.codice,!0),genera[kk]=gen}this.genera=genera}cleanfiltraparametri(key,codice,acapo){if(this.paralias||(this.paralias={}),codice&&codice.length){var fl=!1;const getparalias=dati=>{let cl=[],co=getcolonne(dati);for(var c of co)if(c.includes(":")){let v=c.split(":");this.paralias[v[0]]=v[1],cl.push(v[0])}else cl.push(c);return cl};for(var i=0;i<codice.length;i++){let rr=/^\:p[;,\s]+(.*)?$/im.exec(codice[i]);if(rr)codice[i]=null,fl=!0,this.parametri[key]=getparalias(rr[1]);else{let rr=/^!(parametri|pars|p)[;,\s]+(.*)?$/im.exec(codice[i]);rr&&(codice[i]=null,fl=!0,this.parametri[key]=getparalias(rr[2]))}}fl&&(codice=codice.filter((e=>null!=e)))}return codice=muClean(codice,acapo)}}function parsevariabili(text){for(var fl=!1,tk=[];;){let m=/\$([\{\[\(])/m.exec(text);if(!m){text&&fl&&tk.push({class:"",text:text});break}fl=!0;var classe="["==m[1]?"inline":"variabile";m.index>0&&tk.push({class:"",text:text.substring(0,m.index)});var{i:i}=parsevar(text,m.index+2,m[1],null);if(!(i>m.index)){tk.push({class:classe,text:text.substring(m.index)});break}tk.push({class:classe,text:text.substring(m.index,i+1)}),text=text.substring(i+1)}return{fl:fl,tk:tk}}function parseexp(text,exp,callback){if(!callback)throw new Error("missing callback");for(var fl=!1,tk=[];;){let m=exp.exec(text);if(!m){text&&fl&&tk.push({class:"",text:text});break}m.index>0&&tk.push({class:"",text:text.substring(0,m.index)}),tk.push(...callback(m)),fl=!0,text=text.substring(m.index+m[0].length)}return{fl:fl,tk:tk}}function muParsecode(tt,isvar){tt||(tt=" "),tt.endsWith("\n")&&(tt+=" ");for(var tm=[{class:"",text:tt}],i=0;i<tm.length;i++)if(!tm[i].class){var{fl:fl,tk:tk}=parseexp(tm[i].text,/(\/\*[^]+?\*\/)/im,(m=>[{class:"comment",text:m[1]}]));if(fl&&tm.splice(i,1,...tk),!tm[i].class){var{fl:fl,tk:tk}=parseexp(tm[i].text,/(\/\/.*)$/im,(m=>[{class:"commento2",text:m[1]}]));if(fl&&tm.splice(i,1,...tk),!tm[i].class){var{fl:fl,tk:tk}=parseexp(tm[i].text,/(^\s*\{.+?\})/m,(m=>[{class:"header",text:m[1]}]));if(fl&&tm.splice(i,1,...tk),!tm[i].class){var{fl:fl,tk:tk}=parseexp(tm[i].text,/(^\s*\:\w+)(.*?$)/m,(m=>[{class:"param",text:m[1]},{class:"param2",text:m[2]}]));if(fl&&tm.splice(i,1,...tk),!isvar){if(tm[i].class)continue;var{fl:fl,tk:tk}=parseexp(tm[i].text,/(^\s*\!\w+)/m,(m=>[{class:"function",text:m[1]}]));if(fl&&tm.splice(i,1,...tk),tm[i].class)continue;var{fl:fl,tk:tk}=parseexp(tm[i].text,/(#let.? +)([\w_\.]+)/im,(m=>[{class:"comando",text:m[1]},{class:"variabile",text:m[2]}]));if(fl&&tm.splice(i,1,...tk),tm[i].class)continue;var{fl:fl,tk:tk}=parseexp(tm[i].text,/(#(push|pop|select|cases|endselect|ifndef|elseifndef|ifdef|endif|elseifdef|variante|forvar|for|endfor|continue|break|inc|macro|default|letm|lets|letv|lett|leto|cat))/im,(m=>[{class:"comando",text:m[1]}]));if(fl&&tm.splice(i,1,...tk),tm[i].class)continue;var{fl:fl,tk:tk}=parseexp(tm[i].text,/(#(if\s*|elseif\s*))/im,(m=>[{class:"comando",text:m[1]}]));if(fl&&tm.splice(i,1,...tk),tm[i].class)continue;var{fl:fl,tk:tk}=parseexp(tm[i].text,/(#(else|i |m |f |j |case|def ))/im,(m=>[{class:"comando",text:m[1]}]));if(fl&&tm.splice(i,1,...tk),tm[i].class)continue;var{fl:fl,tk:tk}=parsevariabili(tm[i].text);if(fl&&tm.splice(i,1,...tk),tm[i].class)continue;var{fl:fl,tk:tk}=parseexp(tm[i].text,/(\$[\w_\.]+)/im,(m=>[{class:"variabile",text:m[1]}]));fl&&tm.splice(i,1,...tk)}}}}}return tm}function headerconvert(tt){var rr=muClComments(tt,!1),grp=(tt={},{r:[]}),fl=!1;for(var r of rr){var m=/^\s*\{(h|head|header)\s+(\w+)\}/im.exec(r);if(m)grp={cod:m[2],des:m[2],r:[]},fl=!1,tt[m[2]]=grp;else if(!/^\s*\:/.exec(r)){var tm,v=r.split(","),t={cod:clean(v[0])};(tm=(v[1]||"").trim())&&(t.des=tm),(tm=clean(v[2]))&&(t.tipo=tm),(tm=clean(v[3]))&&(t.alias=tm),(tm=clean(v[4]))&&(t.valid=tm),(tm=clean(v[5]))&&(t.visible=tm),t.cod&&(fl||"sep"!=t.tipo?grp.r.push(t):(grp.des=t.des,grp.valid=t.valid,grp.visible=t.visible,fl=!0))}}return tt}function aliasconvert(tt){var rr=muClComments(tt.toLowerCase(),!1),tx={};for(var r of rr)if(!/^\s*\:/.exec(r)){var v=getcolonne(r);v[0]&&v[1]&&(tx[v[0]]={cod:v[1]})}return tx}class Ambiente{#headers=void 0;#alias=void 0;#deriva=void 0;#typos=void 0;constructor(cat=".",maxdelays=100,righevuote=!1){this.righevuote=righevuote,this.maxdelays=maxdelays,this.setcatalog(cat),this.fndotcallback=void 0}setcatalog(cat){return cat=clean(cat),this.cat!=cat&&(this.cat=cat,this.item=this.rule=this.model="",this.azzera(!0)),cat}get muvalutatore(){return{getcolonne:getcolonne,muCalc:muCalc,muEval:muEval,tipifree:tipifree}}azzera(mode=!1){this.vari=new Variabile,this.fndotcallback&&this.vari.setfndot(this.fndotcallback),this.ruleheader="",mode&&(this.macro={},this.varianti={},this.varelenco={},this.macroelenco={},this.scripts={},this.#headers=void 0,this.#alias=void 0,this.#deriva=void 0,this.#typos=void 0)}async setfndot(fndotcallback){this.fndotcallback=fndotcallback,this.vari.setfndot(fndotcallback)}async#checkelencovar(cat){if(cbInfo&&!this.varelenco[cat]){let tm=await cbInfo("headers",cat,"_varianti");Array.isArray(tm)?this.varelenco[cat]=tm:tm.vars&&(this.varelenco[cat]=tm.vars,tm.alias&&(this.#alias=tm.alias)),this.varelenco[cat]||(this.varelenco[cat]=[])}}parseheaderfrominfo(tm){if(tm&&tm.length>0)for(var t of tm)switch(t.tipo){case"_headers":t.value,t.value=headerconvert(t.value),this.#headers=t.value||{};break;case"_alias":t.value,t.value=aliasconvert(t.value),this.#alias=t.value||{};break;case"_typos":t.value;var tips=fromjson(t.value);for(var tp in tips){var tq=tips[tp];tq.db&&(tq.db=muClean(muClComments(tq.db))),tq.list&&(tq.list=muClean(muClComments(tq.list)))}t.value=tips,this.#typos=t.value||{}}}setitem(item,rule,model,datadelgiorno){this.item=clean(item,!0),this.rule=clean(rule,!0),this.model=clean(model,!0),this.data=datadelgiorno||(new Date).toInt()}async getheader(cod){if(!this.#headers&&cbInfo){var tm=await cbInfo("headers",this.cat,"_headers");this.parseheaderfrominfo(tm)}return this.#headers||(this.#headers={}),this.#headers[cod]}async getalias(){if(!this.#alias&&cbInfo){var tm=await cbInfo("headers",this.cat,"_alias");this.parseheaderfrominfo(tm)}return this.#alias||(this.#alias={}),this.#alias}get deriva(){return this.#deriva,this.#deriva||[]}async getmacro(riga){try{if("string"==typeof riga&&(riga={tipo:"M",contenuto:riga}),!riga||!riga.contenuto)return;var rr=/^([\(\{\}\)\:\$\w\.\\\/]+)[\s\;\,]*(.*)?$/im.exec(riga.contenuto);if(!rr)return void errori.add("Macro non valida:"+riga.contenuto,riga);(macro=clean(rr[1],!0)).includes("$")&&(macro=await this.vari.valuta(macro));var pars=getcolonne(rr[2]),{name:name,cat:cat}=checkmu(macro,this.cat);this.cat=cat;var macro,ky=`${cat}/${name}`;if(!this.macro[ky]){var tm=new Macro(this,name);await tm.load()?this.macro[ky]=tm:errori.add(`macro fail to load ${ky}`,riga)}return(macro=this.macro[ky])?{macro:macro,pars:pars}:(errori.add(`macro non trovata ${ky}`,riga),{})}catch(error){errori.add(geterrdes(error),`ambiente.getmacro: ${riga?.contenuto}`)}}async getvariante(cod){var{name:name,cat:cat}=checkmu(cod,this.cat),n2=name;let altri={};if(cat==this.cat&&this.#alias&&this.#alias[name]&&(altri=this.#alias[name]||{},n2=altri.cod),await this.#checkelencovar(cat),this.varelenco[cat]&&!this.varelenco[cat].includes(name))return;var key=`${cat}/${n2}`;let vv;return this.varianti[key]?vv=this.varianti[key]:(vv=new Variante(this),await vv.load(key,cat),this.varianti[key]=vv),altri&&(altri.des&&(vv.des=altri.des),altri.vdef&&(vv.vdef=altri.vdef)),vv}async varcompila(v,callback){var xx=new Variante(this);(await xx.load(v,this.cat,!0),xx.alias)&&((await this.getalias())[v]=xx.alias);callback("variants",{cod:v,des:xx.des||"",alias:xx.alias,info:xx.alias?"":JSON.stringify(getOggetto(xx,["amb"]))})}async macrocompila(v,callback){var mac=new Macro(this,v);await mac.loadAndCompile(`${v}.mu`);var t=mac.getmacro();callback("macros",{cod:v,info:JSON.stringify(t),isgenera:mac.isgenera,isheader:mac.isheader,iscodice:mac.iscodice})}async barrecompila(articolibarre,titolibarre,callback){var cc=new CodiceBarra;for(var x in cc.compila(articolibarre,titolibarre),cc.barre){callback("barcodes",{cod:x,des:"",info:JSON.stringify(cc.barre[x])})}return cc}async tojson(d){let tm;return cbFunc&&(tm=await cbFunc("json",d)),tm}async compila(info,callback){if(callback){for(var v of info.var)await this.varcompila(v,callback);for(var v of info.mu)await this.macrocompila(v,callback);if(callback("infos",{cod:"info",des:info.cat,info:JSON.stringify({cat:info.cat,md:info.info})}),this.#headers=void 0,this.#alias=void 0,this.#deriva=void 0,this.#typos=void 0,cbInfo){var tm=await cbInfo("headers",this.cat,["_headers","_alias","_deriva","_typos"]);this.parseheaderfrominfo(tm)}this.#headers?callback("infos",{cod:"headers",des:"",info:JSON.stringify(this.#headers)}):logga("missing headers"),this.#alias&&callback("infos",{cod:"alias",des:"",info:JSON.stringify(this.#alias)}),this.#deriva&&callback("infos",{cod:"deriva",des:"",info:JSON.stringify(this.#deriva)}),this.#typos&&callback("infos",{cod:"typos",des:"tipologie",info:JSON.stringify(this.#typos)})}}async getheaderfromdb(name){let totale=await cbInfo("header",this.cat,name,!this.#deriva),{head:head,rows:rows,macros:macros,deriva:deriva,llvars:llvars}=totale;for(var r of rows)r.cod=clean(r.cod),r.alias=clean(r.alias),r.t=clean(r.t);if(!llvars){for(var r of(llvars=new Set,rows)){let nn=r.alias?r.alias:r.cod;llvars.add(nn)}llvars=[...llvars]}this.#deriva||(this.#deriva=deriva),await this.#checkelencovar(this.cat),head.cod=clean(head.cod),head.rule=clean(head.rule),head.ruledef=head.ruledef||[];let vn=[],t=this.varelenco[this.cat];for(var nn of llvars)this.varianti[`${this.cat}/${nn}`]||t&&t.includes(nn)&&vn.push(nn);if(vn.length&&cbGetVariante){var vars=await cbGetVariante(this.cat,vn);if(vars&&vars.length)for(var x of vars){let{name:name,content:content}=x,vv=new Variante(this);vv.setheader(name,this.cat),content&&await vv.loadContentExtended(content),this.varianti[vv.key]=vv}}return{head:head,rows:rows,macros:macros}}async getlinkedmacros(rule,macros){var getkey=n=>n.includes("/")?n:`${this.cat}/${n}`;let k,cl=[];if(rule&&(k=getkey(rule),this.macro[k]||cl.push(rule)),macros&&"string"==typeof macros){let vv=macros.split(";");for(var v of vv)k=getkey(v),this.macro[k]||cl.push(v)}if(cl&&cl.length>0&&cbGetMacro){let tm=await cbGetMacro(this.cat,cl);if(tm&&tm.length>0)for(var x of tm){let m=new Macro(this,x.name);for(var t in x.content){let contenuto=x.content[t];m[t]=contenuto}this.macro[m.key]=m}}}async setruleheader(rule,pars){var{name:name,cat:cat}=checkmu(rule,this.cat),ky=`${cat}/${name}`;if(!this.macro[ky]){let totale=await this.getheaderfromdb(name),{head:head,rows:rows,macros:macros}=totale;await this.getlinkedmacros(head.rule,macros);var tm=new Macro(this,name);if(!head)return void errori.add("Missing rule: "+rule);if(head.rule){let k2=this.macro[`${cat}/${head.rule}`];if(k2)for(var x in k2)["cat","name","key"].includes(x)||(tm[x]=k2[x])}rows&&rows.length&&(tm.head=rows),this.macro[ky]=tm}this.ruleheader=ky;let mc=this.macro[ky];return errori.azzera(),await mc.setparametri(pars),mc}getruleheader(){return this.macro[this.ruleheader]}async setvariante(cod,opz){return await impostavariante(this,null,cod,opz)}async valuta(codice){let output;return"string"==typeof codice&&(codice=muClean(muClComments(codice,this.righevuote))),Array.isArray(codice)&&(logga("m1",codice),output=await muEval(this,null,codice)),output}setinfos(tm){tm&&(this.#headers=tm.headers,this.#alias=tm.alias,this.#deriva=void 0,this.#typos=tm.typos)}}function toJson(t){return JSON.stringify(t,null,2)}function clamp(n,min=-1/0,max=1/0){return(n=Number(n)||0)<min&&(n=min),n>max&&(n=max),n}function gettipocolonna(cod){return tipicolonna.find((x=>x.cod==cod))?.des||tipicolonna[0].des}function gettipofolder(cod){return tipicolonna.find((x=>x.cod==cod))?.folder||""}function newVariabile(){return new Variabile}async function newVariante(cod,cat,amb){var xx=new Variante(amb);return await xx.load(cod,cat),xx}function newAmbiente(cat,maxmillis=100){return new Ambiente(cat,maxmillis)}function newMacro(amb,name){return new Macro(amb,name)}function muValuta(mu,codice,azzera){return azzera&&mu.azzera(),mu.valuta(codice)}function muInit(cat,cbGetMacro,cbGetVariante,cbFunc,cbInfo,cbGetFile,cbLogga){var mu=new Ambiente(cat);return setcallbacks(cbGetMacro,cbGetVariante,cbFunc,cbInfo,cbGetFile,cbLogga),mu}function muCompileScript(codice){return codice&&"object"==typeof codice?codice:codice.startsWith("{")&&codice.endsWith("}")||codice.startsWith("[")&&codice.endsWith("]")?JSON.stringify(codice):muClean(muClComments(codice))}async function muEvalScript(amb,codice,pars,reset=!0){if(codice=muCompileScript(codice),reset&&amb.azzera(),pars)for(var p of pars){var{v:v,o:o}=getcouple(p);amb.vari.add(v,o)}return{output:await muEval(amb,null,codice,{}),vari:amb.vari.dictionary,errori:errori}}const tonum=(s,dec=-1)=>{if(!s)return 0;let n=0;if("number"==typeof s)n=s||0;else if("string"==typeof s){let x=(s=s.replaceAll(",",".")).match(/^-?[0-9.]+$/);n=x&&x.length>0?Number(x[0])||0:muCalc(s)}if(dec>=0)switch(dec){case 0:n=Math.round(n);break;case 1:n=Math.round(10*n)/10;break;case 2:n=Math.round(100*n)/100;break;case 3:n=Math.round(1e3*n)/1e3;break;case 4:n=Math.round(1e4*n)/1e4;break;case 5:n=Math.round(1e5*n)/1e5;break;case 6:n=Math.round(1e6*n)/1e6}return n||0};Date.prototype.toInt||(Date.prototype.toInt=function(){return this.getDate()+100*(this.getMonth()+1)+1e4*this.getFullYear()}),Date.prototype.toFloat||(Date.prototype.toFloat=function(){return Math.floor(1e4*this.getDate()+1e6*(this.getMonth()+1)+1e8*this.getFullYear()+100*this.getHours()+this.getMinutes()+.5)/1e4});const mustr={mus:{variants:{cod:"s",des:"s",alias:"s",info:"s",md:"s",__pk:"cod"},extras:{tipo:"s",cod:"s",info:"s",__pk:"tipo, cod"},macros:{cod:"s",des:"s",info:"s",md:"s",def:"s",isgenera:"i",iscodice:"i",isheader:"i",__pk:"cod"},infos:{cod:"s",des:"s",info:"s",__pk:"cod"},barcodes:{cod:"s",des:"s",info:"s",__pk:"cod"}}};export{Ambiente,CodiceBarra,Macro,Variabile,Variante,checkmu,checkname,clamp,clean,dammivariante,errori,fromjson,getOggetto,getcolonne,getcouple,geterrdes,getheaddims,gettipocolonna,gettipofolder,hash,impostavariante,intvaluta,muInit as jsTest,logga,muCalc,muClComments,muClean,muCompileScript,muEval,muEvalScript,muGenerate,muInit,muLimits,muParsecode,muValuta,mustr,newAmbiente,newMacro,newVariabile,newVariante,parselimitifromdb,parselimitifromrule,parsevar,poppars,pushpars,quote,setOggetto,testsync,tipicolonna,tipifree,tipiheader,tk,toCadPars,toJson,tonum,xdt};
|
|
1
|
+
/**
|
|
2
|
+
* Esegue una semplice somma sincrona di due numeri
|
|
3
|
+
* @param {number} a - Primo numero da sommare
|
|
4
|
+
* @param {number} b - Secondo numero da sommare
|
|
5
|
+
* @returns {number} La somma dei due numeri
|
|
6
|
+
*/
|
|
7
|
+
function testsync(a,b){return a+b}
|
|
8
|
+
/**
|
|
9
|
+
* Restituisce il timestamp corrente in millisecondi
|
|
10
|
+
* @returns {number} Timestamp corrente
|
|
11
|
+
*/const tk=()=>(new Date).valueOf();function quote(v){if((v=(v||"").trim()).length>1){if(v.startsWith('"')&&v.endsWith('"'))return v;if(v.startsWith("(")&&v.endsWith(")"))return v}return`"${v}"`}function hash(obj){let str="";if("string"==typeof obj||"number"==typeof obj)str=obj+"";else if("object"==typeof obj&&obj){const chiaviOrdinati=Object.keys(obj).sort(),separatore="\0";str=chiaviOrdinati.map((key=>`${key}${separatore}${String(obj[key])}`)).join(separatore)}let h1=2166136261,h2=2218511855;for(let i=0;i<str.length;i++){const char=str.charCodeAt(i);h1^=char,h1+=h1<<5^2779096485,h2^=h1,h2=((h2<<3)+char^2134516169)>>>0}return h1>>>=0,h1.toString(16)+h2.toString(16)}
|
|
12
|
+
/**
|
|
13
|
+
* Formatta un messaggio di errore rimuovendo informazioni non necessarie
|
|
14
|
+
* @param {Error|string} err - L'errore da formattare
|
|
15
|
+
* @returns {string} Il messaggio di errore formattato
|
|
16
|
+
*/function geterrdes(err){if(err&&"object"==typeof err){let errMsg=err.stack?.toString().replace(/^.*?node_modules.*$/gim,"")||err.message||"";errMsg=errMsg.replaceAll("/","_").replaceAll(".js","").replaceAll("\n\n","\n").replace(/\;\s+/gi,"\n"),err=errMsg}return(err=err.replace(/sqlite/gi,"SQL ")).replaceAll(";",",").trim()}let cbGetVariante,cbGetMacro,cbFunc,cbInfo,cbGetFile,cbLogga;
|
|
17
|
+
/**
|
|
18
|
+
* Funzione di logging che utilizza un callback personalizzato se disponibile
|
|
19
|
+
* @param {...any} args - Argomenti da loggare
|
|
20
|
+
*/const logga=(...args)=>{cbLogga?cbLogga(args):console.log(...args)};
|
|
21
|
+
/**
|
|
22
|
+
* Configura i callback utilizzati dal modulo
|
|
23
|
+
* @param {Function} cbGetMacro1 - Callback per recuperare macro
|
|
24
|
+
* @param {Function} cbGetVariante1 - Callback per recuperare varianti
|
|
25
|
+
* @param {Function} cbFunc1 - Callback per funzioni generiche
|
|
26
|
+
* @param {Function} cbInfo1 - Callback per informazioni
|
|
27
|
+
* @param {Function} cbGetFile1 - Callback per accesso ai file
|
|
28
|
+
* @param {Function} cbLogga1 - Callback per logging
|
|
29
|
+
*/function setcallbacks(cbGetMacro1,cbGetVariante1,cbFunc1,cbInfo1,cbGetFile1,cbLogga1){cbGetMacro=cbGetMacro1,cbGetVariante=cbGetVariante1,cbFunc=cbFunc1,cbInfo=cbInfo1,cbGetFile=cbGetFile1,cbLogga=cbLogga1}
|
|
30
|
+
/**
|
|
31
|
+
* Restituisce il timestamp corrente in millisecondi
|
|
32
|
+
* @returns {number} Timestamp corrente
|
|
33
|
+
*/const xdt=()=>(new Date).valueOf()
|
|
34
|
+
/**
|
|
35
|
+
* Normalizza una stringa rimuovendo spazi e convertendo in minuscolo
|
|
36
|
+
* @param {string} k - Stringa da normalizzare
|
|
37
|
+
* @returns {string} Stringa normalizzata
|
|
38
|
+
*/;function clean(k,locase=!1){return locase?(k||"").trim().toLowerCase():(k||"").trim()}
|
|
39
|
+
/**
|
|
40
|
+
* Analizza una stringa per estrarre una coppia chiave-valore
|
|
41
|
+
* @param {string} r - Stringa da analizzare (es: "chiave=valore")
|
|
42
|
+
* @param {string} [sep='='] - Carattere separatore
|
|
43
|
+
* @returns {{v: string, o: string, fl: boolean}} Oggetto contenente chiave (v), valore (o) e flag presenza separatore (fl)
|
|
44
|
+
*/function getcouple(r,sep="=",locase=!0){var q=(r=r||"").indexOf(sep);return q>=0?{v:clean(r.substring(0,q),locase),o:r.substring(q+sep.length).trim(),fl:!0}:{v:clean(r,locase),o:"",fl:!1}}
|
|
45
|
+
/**
|
|
46
|
+
* Valida e separa un identificatore e una categoria
|
|
47
|
+
* @param {string} id - Identificatore da validare (formato: "categoria/nome" o solo "nome")
|
|
48
|
+
* @param {string} cat - Categoria di default
|
|
49
|
+
* @throws {Error} Se manca la categoria
|
|
50
|
+
* @returns {{name: string, cat: string}} Oggetto con nome e categoria validati
|
|
51
|
+
*/function checkmu(id,cat){if((id=(id||"").trim()).indexOf("/")>0){var vv=id.split("/");cat=vv[0]||"",id=vv[1]||""}if(!cat)throw new Error("manca il catalogo per "+id);return{name:id,cat:cat=checkname(cat)}}
|
|
52
|
+
/**
|
|
53
|
+
* Valida un identificatore verificando che contenga solo caratteri permessi
|
|
54
|
+
* @param {string} id - Identificatore da validare
|
|
55
|
+
* @throws {Error} Se l'identificatore contiene caratteri non validi
|
|
56
|
+
* @returns {string} Identificatore validato in minuscolo
|
|
57
|
+
*/function checkname(id){if(!(id=(id||"").trim())||!/^(?:(\w|\-|\_|\+|\.))+$/im.test(id)){throw new Error(`nome non valido: |${id}| \n deve contenere solo lettere, _, e numeri`)}return id.toLowerCase()}
|
|
58
|
+
/**
|
|
59
|
+
* Converte una stringa in array di colonne, gestendo diversi formati
|
|
60
|
+
* @param {string} value - Stringa da convertire
|
|
61
|
+
* @returns {string[]} Array di colonne
|
|
62
|
+
*/function getcolonne(value,keepquote=!1){value=String(value||"");const pp=/^(\d+)\.\.(\d+)$/.exec(value);if(pp){var n1=parseInt(pp[1]),n2=parseInt(pp[2]),cl=[];n1>n2&&([n1,n2]=[n2,n1]);for(var i=n1;i<=n2;i++)cl.push(i+"");return cl}if(!/["({[]/.test(value))return value.split(/[,;]/).map((e=>e.trim()));const risultato=[];let buffer="",livelloParentesi=0,inVirgolette=!1;for(let i=0;i<value.length;i++){const char=value[i];if(0===livelloParentesi&&'"'===char&&(0!==i&&"\\"===value[i-1]||(inVirgolette=!inVirgolette)),inVirgolette||("("===char||"["===char||"{"===char?livelloParentesi++:")"!==char&&"]"!==char&&"}"!==char||(livelloParentesi=Math.max(0,livelloParentesi-1))),","!==char&&";"!==char||0!==livelloParentesi||inVirgolette)buffer+=char;else{const trimmed=buffer.trim();risultato.push(trimmed),buffer=""}}const trimmed=buffer.trim();return trimmed&&risultato.push(trimmed),risultato.map((e=>(e=e.trim(),!keepquote&&(e.startsWith('"')&&e.endsWith('"')||e.startsWith("(")&&e.endsWith(")"))?e.slice(1,-1):e)))}
|
|
63
|
+
/**
|
|
64
|
+
* Analizza variabili in un'espressione usando delimitatori
|
|
65
|
+
* @param {string} ex - Espressione da analizzare
|
|
66
|
+
* @param {number} k0 - Posizione iniziale
|
|
67
|
+
* @param {string} inipar - Delimitatore iniziale ([, (, {)
|
|
68
|
+
* @param {string} endpar - Delimitatore finale (], ), })
|
|
69
|
+
* @param {boolean} [nonewline=false] - Se true, termina all'incontro di un newline
|
|
70
|
+
* @returns {{i: number, res: string[]}} Risultato dell'analisi con posizione finale e array risultati
|
|
71
|
+
*/const parsevar=(ex,k0,inipar,endpar,nonewline=!1)=>{const pars1=["[","(","{"],pars2=["]",")","}"];endpar||(endpar="["==inipar?"]":"("==inipar?")":"}");for(var mp=pars1.includes(inipar),par=1,res=[],nres=0,i=k0;i<ex.length;i++)if(mp&&pars1.includes(ex[i])||ex[i]==inipar)par++;else if(mp&&pars2.includes(ex[i])||ex[i]==endpar){if(0==--par&&ex[i]==endpar)return res[nres]=ex.substring(k0,i),{i:i,res:res}}else if(":"==ex[i])1==par&&(res[nres]=ex.substring(k0,i),k0=i+1,nres++);else if("\n"==ex[i]&&nonewline)return{i:i,res:res};return{i:-1,res:ex.substring(k0)}};
|
|
72
|
+
/**
|
|
73
|
+
* Classe per la gestione degli errori con funzionalità di accumulo e formattazione
|
|
74
|
+
*/
|
|
75
|
+
/**
|
|
76
|
+
* Copia le proprietà non-funzione da un oggetto sorgente a uno destinazione
|
|
77
|
+
* @param {Object} objDestinazione - Oggetto destinazione
|
|
78
|
+
* @param {Object} objSorgente - Oggetto sorgente
|
|
79
|
+
*/
|
|
80
|
+
function setOggetto(objDestinazione,objSorgente){"object"==typeof objDestinazione&&"object"==typeof objSorgente&&Object.keys(objSorgente).forEach((key=>{Object.hasOwn(objDestinazione,key)&&"function"!=typeof objDestinazione[key]&&(objDestinazione[key]=objSorgente[key])}))}
|
|
81
|
+
/**
|
|
82
|
+
* Estrae le proprietà non-funzione da un oggetto, escludendo chiavi specificate
|
|
83
|
+
* @param {Object} obj - Oggetto da cui estrarre le proprietà
|
|
84
|
+
* @param {string[]} [exclude] - Array di chiavi da escludere
|
|
85
|
+
* @returns {Object} Nuovo oggetto con le proprietà estratte
|
|
86
|
+
*/function getOggetto(obj,exclude){return"object"==typeof obj?Object.keys(obj).reduce(((acc,key)=>("function"!=typeof obj[key]&&(exclude&&exclude.length>0&&exclude.includes(key)||(acc[key]=obj[key])),acc)),{}):{}}
|
|
87
|
+
/**
|
|
88
|
+
* Converte una stringa in un oggetto JSON, gestendo errori e restituendo un valore di default se non valido
|
|
89
|
+
* @param {string|Array|Object} str - Stringa da convertire in JSON, array o oggetto da restituire direttamente
|
|
90
|
+
* @param {*} [def={}] - Valore di default da restituire in caso di errore di parsing
|
|
91
|
+
* @throws {Error} Non genera eccezioni, gli errori vengono loggati internamente
|
|
92
|
+
* @returns {*} L'oggetto JSON convertito dalla stringa, l'input originale se è un array/oggetto, o il valore di default in caso di errore
|
|
93
|
+
* @example
|
|
94
|
+
* fromjson('{"a": 1}') // returns {a: 1}
|
|
95
|
+
* fromjson([1,2,3]) // returns [1,2,3]
|
|
96
|
+
* fromjson('invalid json', {}) // returns {}
|
|
97
|
+
*/function fromjson(str,def){if(Array.isArray(str))return str;if("string"!=typeof str)return str;if(""==str)return def||{};try{return JSON.parse(str)}catch(e){return logga(`Errore parsing JSON: ${e}\n${str}`),def||{}}}const errori=new class Errori{constructor(){this.azzera()}
|
|
98
|
+
/**
|
|
99
|
+
* Azzera la lista degli errori
|
|
100
|
+
*/azzera(){this.err=[]}
|
|
101
|
+
/**
|
|
102
|
+
* Aggiunge un errore alla lista
|
|
103
|
+
* @param {string} msg - Messaggio di errore
|
|
104
|
+
* @param {Object} row - Informazioni aggiuntive sull'errore
|
|
105
|
+
*/add(msg,row){this.err.push({msg:msg,row:row})}
|
|
106
|
+
/**
|
|
107
|
+
* Restituisce la lista completa degli errori
|
|
108
|
+
* @returns {Array} Lista degli errori
|
|
109
|
+
*/get(){return this.err}
|
|
110
|
+
/**
|
|
111
|
+
* Restituisce il numero di errori presenti
|
|
112
|
+
* @returns {number} Numero di errori
|
|
113
|
+
*/get length(){return this.err.length}
|
|
114
|
+
/**
|
|
115
|
+
* Converte la lista degli errori in stringa
|
|
116
|
+
* @returns {string} Rappresentazione testuale degli errori
|
|
117
|
+
*/toString(){var cl=[];for(var e of this.err){let m="object"==typeof e.msg?JSON.stringify(e.msg):e.msg||"";cl.push(`${e.row?e.row+":":""}${m}`)}return cl.join("\n")}};function getheaddims(dims){let res;try{res="object"==typeof dims&&dims?dims:JSON.parse(dims||"{}")}catch(error){}return res||(res={}),res.l||(res.l={visible:1,val:1e3,min:0,max:1e4}),res.a||(res.a={visible:1,val:1e3,min:0,max:1e4}),res.p||(res.p={visible:1,val:1e3,min:0,max:1e4}),res}const REGEX_PARENTESI=/(?<!\w)\(/g,REGEX_NUMERO=/^-?[0-9.]+$/,REGEX_FUNZIONE=/^(\w+)(\!)?\[(.*)?\]$/,REGEX_RANDOM=/^(rnd|random|cas)\(/i,REGEX_CLAMP=/^clamp\(/i,REGEX_ROUND=/^(dec|round)\(/i,REGEX_DIGIT=/[0-9.]/,REGEX_OPERATOR=/[+\-*/\^\%]/,REGEX_ALPHA=/[a-zA-Z]/i;function valutaparentesi(expression){for(expression=(expression+"").trim();;){var tm=REGEX_PARENTESI.exec(expression);if(!tm)break;var{i:i,res:res}=parsevar(expression,tm.index+1,"(",")");if(i<=0)break;expression=expression.substring(0,tm.index)+valutaparentesi(res[0])+(i>=0?expression.substring(i+1):"")}return expression=function valutainsiemi(expression){if(expression.includes("[")){function resinisiemi(rr){let v1=rr[1],fl=!!rr[2],vv=getcolonne(rr[3]);for(var v of vv)if(v==v1)return fl?"0":"1";return fl?"1":"0"}for(;;){var rr=REGEX_FUNZIONE.exec(expression);if(!rr)break;var tm=resinisiemi(rr);expression=expression.substring(0,rr.index)+tm+expression.substring(rr.index+rr[0].length)}}return expression}(expression),function operatoricomparazione(expression){let left,right;const operators={"||":()=>valutaparentesi(left)||valutaparentesi(right)?1:0,"|":()=>valutaparentesi(left)||valutaparentesi(right)?1:0,"&&":()=>valutaparentesi(left)&&valutaparentesi(right)?1:0,"&":()=>valutaparentesi(left)&&valutaparentesi(right)?1:0,"<<=":()=>clean(left)<=clean(right),">>=":()=>clean(left)>=clean(right),"===":()=>clean(left)==clean(right),"==":()=>clean(left)==clean(right),"!!":()=>clean(left)!=clean(right),"<<":()=>clean(left)<clean(right),">>":()=>clean(left)>clean(right),"<=":()=>muCalcbase(left)<=muCalcbase(right),">=":()=>muCalcbase(left)>=muCalcbase(right),"<":()=>muCalcbase(left)<muCalcbase(right),">":()=>muCalcbase(left)>muCalcbase(right),"=":()=>muCalcbase(left)==muCalcbase(right),"!":()=>muCalcbase(left)!=muCalcbase(right)};var operatorIndex=-1,op="";for(var operator in operators)if((operatorIndex=expression.indexOf(operator))>=0){op=operator;break}return-1!==operatorIndex?(left=expression.slice(0,operatorIndex),right=expression.slice(operatorIndex+op.length),operators[op]&&operators[op]()?1:0):muCalcbase(expression)}(expression)}const mathFunctions={sqr:x=>Math.sqrt(x),sqrt:x=>Math.sqrt(x),int:x=>Math.floor(x),floor:x=>Math.floor(x),round:x=>Math.round(x),abs:x=>Math.abs(x),sin:x=>Math.sin(x*(Math.PI/180)),cos:x=>Math.cos(x*(Math.PI/180)),tan:x=>Math.tan(x*(Math.PI/180)),atan:x=>Math.atan(x*(Math.PI/180)),atan2:(x,y)=>Math.atan2(x,y)*(Math.PI/180),asin:x=>Math.asin(x*(Math.PI/180)),acos:x=>Math.acos(x*(Math.PI/180))};function muCalcbase(expression){let index=0;function parseOperator(){const op=expression[index];return REGEX_OPERATOR.test(op)?(index++,op):null}function parsePrimary(){if(REGEX_DIGIT.test(expression[index]))return function parseNumber(){const start=index;for(;index<expression.length&®EX_DIGIT.test(expression[index]);)index++;return Number(expression.slice(start,index))}();if("("===expression[index]){index++;const result=parseExpr();return")"===expression[index]&&index++,result}return REGEX_ALPHA.test(expression[index])?function parseFunctions(){var ex=expression.slice(index);if(!ex)return 0;for(const[name,func]of Object.entries(mathFunctions)){const match=new RegExp(`^(${name})\\(`,"i").exec(ex);if(match){index+=match[0].length;const result=func(parseExpr());return")"===expression[index]&&index++,result}}let fn;if(fn=REGEX_RANDOM.exec(ex),fn){index+=fn[0].length;let min=0,max=1;return")"!==expression[index]&&(min=parseExpr(),","===expression[index]?(index++,max=parseExpr()):(max=min,min=0)),")"===expression[index]&&index++,Math.random()*(max-min)+min}if(fn=REGEX_CLAMP.exec(ex),fn){index+=fn[0].length;const a=parseExpr();","===expression[index]&&index++;const b=parseExpr();","===expression[index]&&index++;const c=parseExpr();return")"===expression[index]&&index++,Math.min(Math.max(a,b),c)}if(fn=REGEX_ROUND.exec(ex),fn){index+=fn[0].length;const value=parseExpr();let decimals=0;return","===expression[index]&&(index++,decimals=parseExpr()),")"===expression[index]&&index++,parseFloat(value.toFixed(decimals))}return index++,parseExpr()}():0}function parseFactor(){let left=parsePrimary();for(;index<expression.length&&/[\/\*\^\%]/.test(expression[index]);){const op=parseOperator(),right=parsePrimary();"*"===op?left*=right:"/"===op?left=right?left/right:0:"%"===op?left=right?left%right:0:"^"===op&&(left=Math.pow(left,right))}return left}function parseExpr(){let left=parseFactor();for(;index<expression.length&&/[+\-]/.test(expression[index]);){const op=parseOperator(),right=parseFactor();"+"===op?left+=right:"-"===op&&(left-=right)}return left}return expression=expression.replace(/\s/g,""),parseExpr()}
|
|
118
|
+
/**
|
|
119
|
+
* Valuta un'espressione matematica o logica e restituisce il risultato
|
|
120
|
+
* @param {string|number} expression - L'espressione da valutare
|
|
121
|
+
* @returns {number} Il risultato della valutazione dell'espressione
|
|
122
|
+
* @description
|
|
123
|
+
* Supporta operazioni matematiche di base, funzioni trigonometriche,
|
|
124
|
+
* operatori di confronto e operazioni logiche.
|
|
125
|
+
* Le funzioni supportate includono: sqrt, floor, abs, sin, cos, random, clamp, round
|
|
126
|
+
*/function muCalc(expression){if(!expression)return 0;if("number"==typeof expression)return expression||0;if("string"!=typeof expression)return 0;var s=expression.replaceAll(",",".");return REGEX_NUMERO.test(s)?Number(s)||0:valutaparentesi(expression)||0}function valutavar(sh,res){var vv=res[0]||"";if(!vv)return"";if(sh.counter>=500)return vv;var vx=valutabase(sh,sh.var(valuta0(sh,vv)));if(sh.counter>=500)return vv;if(res[1]){var cols=getcolonne(vx);if("l"==res[1])return String(cols.length);var col=muCalc(valuta0(sh,res[1]));if(!(col>=0&&col<cols.length))return"";vx=valuta0(sh,cols[col])}if(res[2]){var c1=muCalc(valuta0(sh,res[2]));if(c1){var c2=0;return res[3]&&(c2=muCalc(valuta0(sh,res[3]))),c1<0?vx.slice(c1):c2?vx.substring(c1-1,c1+c2-1):vx.substring(c1-1)}}return vx}function valutaquadra(sh,res){var vv=getcolonne(res||""),r1=clean(vv[0]);function replacecharcode(str){return"\\t"==str?"\t":"\\n"==str?"\n":(str||"").replace(/&(\d+)/g,((match,m1)=>String.fromCharCode(parseInt(m1))))}switch(r1){case"set":var m1=valuta0(sh,vv[1]||""),m2=valuta0(sh,vv[2]||"");sh.add(m1,sh.vars(m2));break;case"ex":m1=valuta0(sh,vv[1]||"");(m2=valuta0(sh,vv[2]||""))||(m2=",");var m3=muCalc(valuta0(sh,vv[3]||"")),tm=m1.split(m2);return m3>0&&tm[m3-1]||"";case"ex2":var sep=replacecharcode(vv[1]||""),pos=muCalc(valuta0(sh,vv[2]||""));return vv.splice(0,3),(str=vv.join(";")).split(sep)[pos>0?pos-1:0]||"";case"replace":return vv[1].replace(new RegExp(vv[2]||"x","gim"),(vv[3]||"").trim());case"replace2":case"rp2":try{var search=replacecharcode(vv[1]||"x"),replace=replacecharcode(vv[2]||"").trim();return vv.splice(0,3),search=search.replace(/&(\d+)/g,((match,code)=>`\\u${parseInt(code).toString(16).padStart(4,"0")}`)),vv.join(";").replace(new RegExp(search,"im"),replace)}catch(error){return""}case"look":case"lookb":{let val=parseFloat(vv[1]||"");if(vv=vv.slice(2).map((e=>parseFloat(e)||0)),"lookb"==r1){const filtered=vv.filter((v=>v<=val));return filtered.length?Math.max(...filtered):val}{const filtered=vv.filter((v=>v>=val));return filtered.length?Math.min(...filtered):val}}case"tk":return(pos=muCalc(valuta0(sh,vv[1]||""))||0)?vv[pos>0?pos+1:2]||"":(pos=muCalc(valuta0(sh,vv[2]||"")),sep=vv[1]||"",pos?vv[3].split(sep)[pos-1]:"");case"totab":return vv.splice(0,1),vv.join("\t");case"tosep":sep=replacecharcode(vv[1]||"")||";";return vv.splice(0,2),vv.join(sep);case"len":{let tm;return vv.length>2?(vv.shift(),tm=vv.join(";")):tm=vv[1]||"",tm.length}case"mid":var str=valuta0(sh,vv[1]||""),len=(pos=muCalc(valuta0(sh,vv[2]||"")),muCalc(valuta0(sh,vv[3]||"")));return str.substring(pos-1,pos+len-1);case"arrotonda":{str=muCalc(vv[1]);let coeff=1;return["0","1","2","3","4","5","6"].includes(vv[2])?coeff=Math.pow(10,parseInt(vv[2])):(coeff=muCalc(vv[2]),0==coeff&&(coeff=1e3)),Math.round(str*coeff)/coeff}case"iif":return(str=muCalc(valuta0(sh,vv[1])))?vv[2]||1:vv[3]||0;case"instr":case"instr2":var str1=vv[1]||"",str2=vv[2]||"";return str1.toLowerCase().indexOf(str2.toLowerCase())+1;case"instr2":str2=vv[1]||"";return vv.splice(0,2),vv.join(";").toLowerCase().indexOf(str2.toLowerCase())+1;default:return{fun:r1,pars:vv}}}function valuta0(sh,ex){if(ex+="",sh.counter>=500)return ex;for(;;){const rt=/\$([\{\(])/im.exec(ex);if(!rt)break;var i1=rt.index,{i:i,res:res}="("==rt[1]?parsevar(ex,i1+2,"(",")"):parsevar(ex,i1+2,"{","}");ex=valuta0(sh,ex.substring(0,i1))+valutavar(sh,res)+(i>=0?valuta0(sh,ex.substring(i+1)):"")}return ex=(ex=ex.replace(/\$([a-z|][\w|\.]*)/gi,((match,m1)=>{for(var m2="";m1.length;){var tm=valutabase(sh,sh.var(m1));if(tm||!(m1.length>1)){m2=tm+m2;break}m2=m1.slice(-1)+m2,m1=m1.substring(0,m1.length-1)}return m2}))).replace(/\$(\d+)\:(\d+)(\:(\d+))?/g,((p0,p1,p2,p3,p4)=>{p4=p4?+p4:1;let cl=[];for(let i=+p1;i<=+p2;i+=p4)cl.push(i.toString());return cl.join(";")})),ex}function valutabase(sh,ex){return ex&&(sh.counter++,sh.counter<=500&&(ex=valuta0(sh,ex)),sh.counter--),ex}class Variabile{constructor(){this.dictionary={},this.vec=[],this.counter=0,this.fndotcallback=void 0}static isValidKey(key){return/^[\w][\w\d\.\[\]]*$/.test(key)}static sanitizeKey(key){return key.replace(/[^a-zA-Z0-9_\.\[\]]/g,"_")}setfndot(fndotcallback){this.fndotcallback=fndotcallback}
|
|
127
|
+
/**
|
|
128
|
+
* Salva lo stato corrente delle variabili nello stack
|
|
129
|
+
*/push(){this.vec.push({...this.dictionary})}
|
|
130
|
+
/**
|
|
131
|
+
* Ripristina l'ultimo stato salvato delle variabili
|
|
132
|
+
*/pop(){this.vec.length>0&&(this.dictionary=this.vec.pop())}
|
|
133
|
+
/**
|
|
134
|
+
* Rimuove tutte le variabili e pulisce lo stack
|
|
135
|
+
*/clear(){this.vec=[],this.dictionary={}}azzera=()=>this.clear()
|
|
136
|
+
/**
|
|
137
|
+
* Recupera il valore di una variabile
|
|
138
|
+
*/;var(key){let fmt="";const pp=/^(\d+)\.\.(\d+)$/.exec(key);if(pp){var n1=parseInt(pp[1]),n2=parseInt(pp[2]),cl=[];n1>n2&&([n1,n2]=[n2,n1]);for(var i=n1;i<=n2;i++)cl.push(i+"");return cl}if(key.indexOf("|")>=0){let tm=key.split("|");key=tm[0],fmt=tm[1]}function toformat(val,fmt){switch(fmt.trim().toLowerCase()){case"data":return date=parseFloat(val)||0,new Intl.DateTimeFormat("it",{day:"2-digit",month:"short",year:"2-digit"}).format(date.toDate());case"euro":return((n,valorezero="")=>{if(n){var xx=Intl.NumberFormat("en",{style:"currency",currency:"EUR"}).format(n);return xx.replace(/€/g,"").replace(/\./g,";").replace(/,/g,".").replace(/;/g,",")+"€"}return valorezero})(parseFloat(val));case"num":return((n,dec=-1)=>{const num="string"==typeof n?parseFloat(n)||0:n;if(dec<0)return num||0;const factor=Math.pow(10,dec);return Math.round(num*factor)/factor||0})(parseFloat(val));default:return val}var date}const sanitizedKey=Variabile.sanitizeKey(key);if(sanitizedKey.startsWith(".")&&this.fndotcallback){let tm=this.fndotcallback(sanitizedKey.toLowerCase());if(tm)return toformat(tm,fmt)}if(Variabile.isValidKey(sanitizedKey)){const lowercaseKey=sanitizedKey.toLowerCase();var rr=/^([\w][\w\d]*)[\.\[]/.exec(lowercaseKey);if(rr){var tm=this.dictionary[rr[1]];if(tm&&"object"==typeof tm)return toformat(function objval(tm,key){for(var parts=key.split("."),obj=tm,i=0;i<parts.length;i++){var part=parts[i],match=part.match(/(.*?)\[(\d+)\]/);if(match){if(void 0===(obj=obj[match[1]]))return"";obj=obj[parseInt(match[2],10)]}else obj=obj[part];if(void 0===obj)return""}return"number"==typeof obj?obj+"":obj}(tm,lowercaseKey.substring(rr[0].length)),fmt)}return toformat(this.dictionary[lowercaseKey]||"",fmt)}return""}getvar(key){return this.var(key)}colonna(value,index){return getcolonne[index]||value}
|
|
139
|
+
/**
|
|
140
|
+
* Restituisce un dump delle variabili
|
|
141
|
+
*/dump(isstr=!1){var cl=[];for(var t in this.dictionary)cl.push({cod:t,val:this.dictionary[t]});return cl=cl.sort(((a,b)=>a.cod>b.cod)),isstr?cl.map((e=>`${e.cod} = ${e.val}`)):cl}
|
|
142
|
+
/**
|
|
143
|
+
* Aggiunge o rimuove una variabile
|
|
144
|
+
*/add(key,value){"number"==typeof value&&(value=String(value));const sanitizedKey=Variabile.sanitizeKey(key);if(Variabile.isValidKey(sanitizedKey)){const lowercaseKey=sanitizedKey.toLowerCase();0===value||value?this.dictionary[lowercaseKey]=value:delete this.dictionary[lowercaseKey]}else logga(`Invalid key: ${key}`)}
|
|
145
|
+
/**
|
|
146
|
+
* Valuta un'espressione con supporto per callback asincroni
|
|
147
|
+
*/valutasync(str){return valutabase(this,str)}async valuta(ex,callback){var tm=await async function valutafunc(sh,ex,callback){if(ex){for(var ii=0;ii<20;ii++){var i1=ex.lastIndexOf("$[");if(!(i1>=0)){ex=valutabase(sh,ex);break}var{i:i,res:res}=parsevar(ex,i1+2,"[","]"),t1=valutabase(sh,ex.substring(0,i1)),t2=res?valutabase(sh,res[0]):"",t3=i>=0?valutabase(sh,ex.substring(i+1)):"",t4=valutaquadra(sh,t2);"object"==typeof t4&&(t4=callback?await callback(t4?.fun,t4.pars):`** fun: ${t4.fun} ** `),ex=t1+(t4="object"==typeof t4?"**str**":t4+""||"")+t3}return ex}return""}(this,ex,callback);return tm=(ex=>{for(;;){var i1=ex.indexOf("{");if(!(i1>=0))break;var{i:i,res:res}=parsevar(ex,i1+1,"{","}");if(i<0)return ex;ex=ex.substring(0,i1)+muCalc(res[0])+(i>=0?ex.substring(i+1):"")}return ex})(tm),tm}async parametrokeyval(p){if(!(p=p.trim()))return{};let k,v,q,isnum=!1;return p.startsWith("#")&&(isnum=!0,p=p.slice(1)),q=p.indexOf("="),q>0?(k=clean(p.slice(0,q)),v=p.slice(q+1)):(q=p.indexOf(":"),q>0?(k=clean(p.slice(0,q)),v=p.slice(q+1),v=this.var(v)):(k=clean(p),v=this.var(k))),v&&"string"==typeof v&&v.includes("$")&&(v=await this.valuta(v)),["l","a","p"].includes(k)&&(isnum=!0),isnum&&(v=muCalc(v)),{k:k,v:v}}}class CodiceBarra{constructor(){this.barre={}}azzera(){this.barre={}}oriented(t,l,a,p){switch(t=(t||"1").substr(0,1).toLowerCase()){case"0":break;case"l":return{t:"l",x:l};case"a":return{t:"a",x:a};case"p":return{t:"p",x:p};case"2":return{t:t,x:l,y:p,z:a};case"5":return{t:t,x:l,y:a,z:p};case"4":return{t:t,x:p,y:l,z:a};case"3":return{t:t,x:a,y:p,z:l};case"6":return{t:t,x:p,y:a,z:l};default:return{t:"1",x:a,y:l,z:p}}}async getcode(codicebarratot,l,a,p,callback){let[codicebarra,modello]=codicebarratot.split(":");modello=modello||"";var getcode0=async(codicebarra,liv)=>{var barra=this.barre[codicebarra];if(!barra&&callback&&((barra=await callback(codicebarra))||(barra={t:"1",r:[]}),this.barre[codicebarra]=barra,barra.coderr&&"errore"!=barra.coderr||(barra.coderr=`#err_${codicebarra}`)),!barra||0==barra.r.length)return{extra:{err:"missing codicebarra"},c:`#err_${codicebarra}`,fm:10};var{t:t,x:x,y:y,z:z}=this.oriented(codicebarra,l,a,p),extra={barra:codicebarra,fm:barra.fm,t:t,liv:liv,items:barra.r.length,err:""},bx=barra.r;if(z){var t2=bx.filter((e=>e.z===z||!e.z));t2.length>0?bx=t2:extra.err=`spessore non coerente: ${z}`}if("l"==t||"a"==t||"p"==t){if(t=bx.find((e=>e.x>=x)))return{c:t.c,fm:t.x==x?0:1,x1:t.x,x:x,extra:extra}}else{var t;if(t=bx.find((e=>e.x==x&&e.y==y)))return{c:t.c,fm:0,x:x,y:y,z:z,x1:t.x,y1:t.y,z1:t.z,extra:extra};if(0!=barra.fm&&(t=bx.find((e=>e.x>=x&&e.y==y))))return{c:t.c,fm:1,x:x,y:y,z:z,x1:t.x,y1:t.y,z1:t.z,extra:extra};if(0!=barra.fm&&2!=barra.fm&&(t=bx.find((e=>e.x>=x&&e.y>=y))))return{c:t.c,fm:2,x:x,y:y,z:z,x1:t.x,y1:t.y,z1:t.z,extra:extra}}return barra.codalt&&liv<5?await getcode0(barra.codalt,liv+1):{c:barra.coderr,fm:9,x:x,y:y,z:z,extra:extra}};return await getcode0(codicebarra,0)}compila(vettore,headers){headers||(headers={});var barre={};if(Array.isArray(vettore)){for(var r of vettore)if(r.cod=clean(r.cod),r.barcode=clean(r.barcode),r.barcode.length>2&&"+"==r.barcode[0]){r.barcode=r.barcode.substr(1);var tm=this.oriented(r.barcode.substr(0,1),r.l,r.a,r.p);tm.c=r.modello?{c:r.cod,m:r.modello}:r.cod,barre[r.barcode]||(barre[r.barcode]={t:r.barcode.substr(0,1),r:[]},headers[r.barcode]&&(barre[r.barcode]=Object.assign(headers[r.barcode],barre[r.barcode]))),barre[r.barcode].r.push(tm)}for(var x in barre){barre[x].r.sort(((a,b)=>a.y?1e4*(a.x-b.x)+(a.y-b.y):a.x-b.x))}}this.barre=barre}}
|
|
148
|
+
/**
|
|
149
|
+
* Costanti e espressioni regolari utilizzate nel modulo
|
|
150
|
+
*/const keys="IFDEF|IFNDEF|CACHE|CVAR|LOOK|LOOKB|SELECT|CASES|CASE|LOG|MSG|DEFAULT|ELSEIFDEF|ELSEIFNDEF|ELSEIF|ELSE|ENDIF|ENDSELECT|PUSH|POP|FUNC|MACRO|LETS|LETO|LETM|LETT|LETV|LETM|LET|DEF|DO|VARIANTE|FORVAR|FOR|LOOP|ENDFOR|BREAK|EXIT|EXITFOR|CONTINUE|IF|INC|I|F|M|J|:P".split("|");function toCadPars(str){let t0=muClComments(str),t2=[];for(var row of t0){let t1=getcolonne(row,!0),fl=!1;for(var t of t1)!t.startsWith('"')&&t.includes("=")?(t2.push(t),fl=!0):fl&&(t2[t2.length-1]+=","+t)}let pars={};for(var x of t2){let{v:v,o:o}=getcouple(x,"=",!1);v&&o&&(/^[\-+]?\d*\.?\d+$/.test(o)&&(o=parseFloat(o)),pars[v]=o)}return pars}
|
|
151
|
+
/**
|
|
152
|
+
* Rimuove i commenti dal codice sorgente mantenendo la struttura del codice
|
|
153
|
+
* @param {string} codice - Il codice sorgente da processare
|
|
154
|
+
* @param {boolean} tienivuoti - Se true mantiene le righe vuote
|
|
155
|
+
* @returns {string[]} Array di righe di codice senza commenti
|
|
156
|
+
*/function muClComments(codice,tienivuoti){const righe=(code=codice,code.replace(/("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*')|\/\*[\s\S]*?\*\//g,((match,quoted)=>quoted||""))).split(/\r?\n/);var code;const tm=[];let rigaContinua="";for(const riga of righe){let rigaTrim=riga.trim();if(rigaTrim.includes("//")&&(rigaTrim=rigaTrim.split("//")[0].trim()),0!==rigaTrim.length||tienivuoti)if(rigaContinua.length>0&&(rigaTrim=rigaContinua+" "+rigaTrim,rigaContinua=""),rigaTrim.endsWith("\\")){rigaTrim=rigaTrim.slice(0,-1);const indiceCommento=rigaTrim.lastIndexOf("//");-1!==indiceCommento&&(rigaTrim=rigaTrim.slice(0,indiceCommento).trim()),rigaContinua=rigaTrim}else tm.push(rigaTrim)}return tm}
|
|
157
|
+
/**
|
|
158
|
+
* Analizza e organizza il codice in una struttura dati gerarchica
|
|
159
|
+
* @param {string[]} tt - Array di righe di codice da analizzare
|
|
160
|
+
* @param {boolean} acapo - Se true mantiene i ritorni a capo nel contenuto
|
|
161
|
+
* @returns {Object[]} Array di oggetti rappresentanti la struttura del codice
|
|
162
|
+
* @throws {Error} Se tt non è un array
|
|
163
|
+
*/function muClean(tt,acapo=!1){if(Array.isArray(tt)){var tm=[];
|
|
164
|
+
/**
|
|
165
|
+
* Aggiunge una riga generica alla struttura
|
|
166
|
+
* @param {string} r - Riga da aggiungere
|
|
167
|
+
*/for(var rigaTrim of tt){const matchComando=rigaTrim.match(/^#([\w\.]+)\s*(.*)$/);if(matchComando){var tipo=matchComando[1].toUpperCase().trim(),tipo2="";if(tipo.includes(".")){var vv=tipo.split(".");tipo=vv[0],tipo2=vv[1]}if(keys.includes(tipo)){const contenuto=matchComando[2];if("IF"!==tipo&&"IFDEF"!=tipo&&"IFNDEF"!=tipo||!contenuto.includes("#")){let tmx={tipo:tipo,contenuto:matchComando[2]};tipo2&&(tmx.tipo2=tipo2),tm.push(tmx)}else{var matchInline=contenuto.match(/^(.*?)\s*#\s*(\w+)\s*(.*?)\s*#\s*(\w+)\s*(.*)$/);matchInline?(tm.push({tipo:tipo,contenuto:matchInline[1].trim()}),tm.push({tipo:matchInline[2].toUpperCase(),contenuto:matchInline[3]}),tm.push({tipo:"ELSE",contenuto:""}),tm.push({tipo:matchInline[4].toUpperCase(),contenuto:matchInline[5]}),tm.push({tipo:"ENDIF",contenuto:""})):(matchInline=contenuto.match(/^(.*?)\s*#\s*(\w+)\s*(.*)$/))?(tm.push({tipo:tipo,contenuto:matchInline[1].trim()}),tm.push({tipo:matchInline[2].toUpperCase(),contenuto:matchInline[3]}),tm.push({tipo:"ENDIF",contenuto:""})):tm.push({tipo:matchComando[1].toUpperCase(),contenuto:matchComando[2]})}}else addgen(rigaTrim)}else addgen(rigaTrim)}for(var nn=0,nf=0,ns=0,lev=[],lef=[],les=[],i=0;i<tm.length;i++){var t=tm[i];switch(t.i=i,t.tipo){case"FOR":case"FORVAR":case"VARIANTE":case"DO":lef[++nf]={pos:i,bk:[]};break;case"LOOP":case"ENDFOR":if(nf>0){var{pos:pos}=lef[nf];for(var b of lef[nf].bk)b.next=i,b.prev=pos;t.prev=pos,tm[pos].next=i,nf--}break;case"BREAK":case"EXIT":case"EXITFOR":case"CONTINUE":nf>0&&lef[nf].bk.push(t);break;case"IF":case"IFDEF":case"IFNDEF":lev[++nn]={pos:i,bk:[t]};break;case"SELECT":les[++ns]={pos:i,bk:[t],first:i};break;case"ELSEIF":case"ELSEIFDEF":case"ELSEIFNDEF":case"ELSE":if(nn>0){var{pos:pos}=lev[nn];lev[nn].bk.push(t),tm[pos].next=i,lev[nn].pos=i}break;case"CASE":case"CASES":case"DEFAULT":if(ns>0){var{pos:pos,first:first}=les[ns];les[ns].bk.push(t),tm[pos].next=i,t.first=first,les[ns].pos=i}break;case"ENDIF":if(nn>0){var{pos:pos,next:next}=lev[nn];for(var b of(tm[pos].next=i,lev[nn].bk))b.last=i;nn--}break;case"ENDSELECT":if(ns>0){var{pos:pos,next:next}=les[ns];for(var b of(tm[pos].next=i,les[ns].bk))b.last=i;ns--}}}return tm}function addgen(r){if(tm.length>0&&""==tm[tm.length-1].tipo){var x=tm[tm.length-1];acapo||!(!r.startsWith("!")&!r.startsWith("."))||r.startsWith("$")||r.startsWith("{")||r.startsWith("#")||x.contenuto.startsWith("!")||x.contenuto.startsWith(".")||x.contenuto.startsWith("$")||x.contenuto.startsWith("{")||x.contenuto.startsWith("#")?tm.push({tipo:"",contenuto:r}):x.contenuto=x.contenuto+"\n"+r}else tm.push({tipo:"",contenuto:r})}errori.add("muClean: expected array!")}
|
|
168
|
+
/**
|
|
169
|
+
* Analizza e processa i limiti definiti nel codice
|
|
170
|
+
* @param {string} dati - Dati contenenti le definizioni dei limiti
|
|
171
|
+
* @returns {Object[]} Array di oggetti rappresentanti i limiti processati
|
|
172
|
+
*/function muLimits(dati){var tk,rr=muClComments(dati),tm=[],parsa=v=>v?[...new Set(v.split(",").map((e=>e.trim())).sort().filter((e=>e)))]:void 0;for(var r of rr){var m=/^\s*\{(.*)?\}/im.exec(r);if(m)"limit"==clean(m[1])?(tk={},tm.push(tk)):tk=void 0;else if(tk&&(m=/^\s*\:(\w+)\s*(.*)/.exec(r)))switch(m[1].toLowerCase()){case"opz":case"o":tk.opz=parsa(m[2]);break;case"obs":case"obsolete":tk.obsolete=parsa(m[2]);break;case"scons":case"sconsigliate":tk.scons=parsa(m[2]);break;case"neutri":tk.neutri=parsa(m[2]);break;case"art":tk.art=parsa(m[2]);break;case"mod":tk.mod=parsa(m[2]);break;default:logga("missing:",m[1])}}return tm}function parselimitifromdb(rr){let c,cl=[];if(rr&&rr.length)for(var r of rr){c={},r.varfilter=fromjson(r.varfilter,[]),r.result=fromjson(r.result,[]),r.result2=fromjson(r.result2,[]),r.exclude=parseInt(r.exclude)?1:0,r.exclude2=parseInt(r.exclude2)?1:0;let{item:item,model:model,rule:rule,varfilter:varfilter,result:result,result2:result2,exclude:exclude,exclude2:exclude2,datai:datai,dataf:dataf}=r;function remap(res){return res.map((e=>clean("string"==typeof e?e:e.Value,!0))).filter((e=>e))}if(result.length||result2.length){if(result.length&&(exclude?c.ex=remap(result):c.valid=remap(result)),result2.length&&(exclude2?c.ex2=remap(result2):c.valid2=remap(result2)),item&&(c.i=clean(item).split(";")),model&&(c.m=clean(model).split(";")),rule&&(c.r=clean(rule).split(";")),(datai||dataf)&&datai<dataf&&(c.datai=parseInt(datai),c.dataf=parseInt(dataf)),varfilter&&varfilter.length){c.v=[];for(let x of varfilter){let tm=c.v.find((e=>e.v==clean(x.Variant)));tm||(tm={v:clean(x.Variant),o:[]},c.v.push(tm)),tm.o=[...tm.o,...clean(x.Value).split(";")],tm.o=[...new Set(tm.o.filter((x=>x)))]}}setlevelimite(c),cl.push(c)}}return cl=cl.sort(((a,b)=>b.l-a.l)),cl}function setlevelimite(rs){let l=0;rs.i&&rs.i.length&&(l+=5),rs.m&&rs.m.length&&(l+=3),rs.r&&rs.r.length&&(l+=2),rs.v&&rs.v.length&&(l+=3),rs.datai&&rs.dataf&&(l+=1),rs.l=l}function parselimitifromrule(limvec){function parsevettorelimiti(vec){let rs={};const rx1=/^\s*[\!\:]\s*(\w+)\s*(.*)$/i;function addres(key,data){function addres0(key,d){(d=clean(d))&&(rs[key]||(rs[key]=[]),rs[key].includes(d)||rs[key].push(d))}if(Array.isArray(data))for(var d of data)addres0(key,d);else addres0(key,data)}for(var v of vec){var tm=rx1.exec(v);if(tm)switch(tm[1]){case"var":case"v":case"variante":let i=(tm[2]||"").indexOf(" ");if(i>0){let v1=clean(tm[2].substring(0,i)),v2=getcolonne(tm[2].substring(i+1));if(v1&&v2&&v2.length){rs.v||(rs.v=[]);let tv=rs.v.find((e=>e.v==v1));for(var o of(tv||(tv={v:v1,o:[]},rs.v.push(tv)),v2))tv.o.includes(o)||tv.o.push(o)}}break;case"d":case"dt":case"data":case"date":let vv=tm[2].split(" "),d1=parseInt(vv[0]),d2=parseInt(vv[1]);(d1||d2)&&(rs.datai=d1,rs.dataf=d2);break;case"rule":case"r":case"mu":addres("r",getcolonne(tm[2]));break;case"item":case"i":addres("i",getcolonne(tm[2]));break;case"model":case"m":addres("m",getcolonne(tm[2]));break;case"e":case"escludi":case"exclude":addres("ex",getcolonne(tm[2]))}else addres("valid",getcolonne(v))}return setlevelimite(rs),rs}let limits;if(limvec&&limvec.length){for(var ll of limvec){let rs=parsevettorelimiti(ll);if(rs&&(rs.valid&&rs.valid.length||rs.ex&&rs.ex.length)){let l=0;rs.i&&rs.i.length&&(l+=5),rs.m&&rs.m.length&&(l+=3),rs.r&&rs.r.length&&(l+=2),rs.v&&rs.v.length&&(l+=3),rs.datai&&rs.dataf&&(l+=1),rs.l=l,limits||(limits=[]),limits.push(rs)}}limits&&(limits=limits.sort(((a,b)=>b.l-a.l)))}return limits}
|
|
173
|
+
/**
|
|
174
|
+
* Classe per gestire le varianti di un prodotto.
|
|
175
|
+
* Permette di caricare, manipolare e convertire varianti di prodotto con relativi attributi e limiti.
|
|
176
|
+
* @class
|
|
177
|
+
* @exports
|
|
178
|
+
*/class Variante{
|
|
179
|
+
/**
|
|
180
|
+
* Crea una nuova istanza di Variante
|
|
181
|
+
* @param {Object} amb - Ambiente di esecuzione contenente il contesto applicativo
|
|
182
|
+
*/
|
|
183
|
+
constructor(amb){this.rows={},this.name="$",this.key="$",this.limits=void 0,
|
|
184
|
+
/** @type {Ambiente} */
|
|
185
|
+
this.amb=amb}
|
|
186
|
+
/**
|
|
187
|
+
* Imposta i dati principali della variante
|
|
188
|
+
* @param {string} id - Identificativo univoco della variante
|
|
189
|
+
* @param {string} cat - Categoria di appartenenza
|
|
190
|
+
* @returns {Object} Oggetto contenente nome e categoria normalizzati
|
|
191
|
+
*/setheader(id,cat){var{name:name,cat:cat}=checkmu(id,cat);return this.cat=cat,this.name=name,this.alias="",this.obbligo=!1,this.des=name,this.vdef=[],this.rows={},this.h=[],this.key=`${cat}/${name}`,{name:name,cat:cat}}
|
|
192
|
+
/**
|
|
193
|
+
* Cerca la riga con dimensione più vicina a quella richiesta
|
|
194
|
+
* @param {number|string} dim - Dimensione target da cercare
|
|
195
|
+
* @param {number} colonna - Indice della colonna (1-based) contenente la dimensione
|
|
196
|
+
* @returns {string} Riga formattata nel formato CSV
|
|
197
|
+
*/fromdim(dim,colonna=2){"number"!=typeof dim&&(dim=muCalc(dim)),colonna>0&&colonna--;var rsel,max=1e9;for(var kk in this.rows){var row=this.rows[kk];if(!row.annulla){var dd=parseFloat(row.v[colonna])||0;dd<=max&&dd>=dim&&(max=dd,rsel=row)}}return this.#torow(dim,rsel)}
|
|
198
|
+
/**
|
|
199
|
+
* Carica una variante dal database o da file
|
|
200
|
+
* @param {string} id - Identificativo della variante
|
|
201
|
+
* @param {string} cat - Categoria della variante
|
|
202
|
+
* @param {boolean} nofilter - Se true, non carica i filtri associati
|
|
203
|
+
* @returns {Promise<boolean>} Promise che risolve a true se il caricamento ha successo
|
|
204
|
+
*/async load(id,cat,nofilter=!1){var{name:name,cat:cat}=this.setheader(id,cat);if(cbGetVariante){var content=await cbGetVariante(cat,name);if(content){if(await this.loadContentExtended(content),content.filter)this.limits=parselimitifromdb(content.filter);else if(cbInfo&&!nofilter){let tm=await cbInfo("filter",cat,name);tm&&tm.length&&(this.limits=parselimitifromdb(tm))}return!0}}return!1}
|
|
205
|
+
/**
|
|
206
|
+
* Carica il contenuto della variante da array di stringhe
|
|
207
|
+
* @private
|
|
208
|
+
* @param {string[]} lines - Array di stringhe contenenti la definizione della variante
|
|
209
|
+
* @returns {Promise<boolean>} Promise che risolve a true se il caricamento ha successo
|
|
210
|
+
*/async _loadContent(lines){const regx=/^\s*[\!\:]\s*(\w+)\s*(.*)$/i;var ky="";let limit,limits=[],modelimit=!1;for(var currentLine of lines){if("{limit}"==(tm=currentLine.toLowerCase()))limit=[],limits.push(limit),modelimit=!0;else if("{:limit}"==tm)modelimit=!1;else if(modelimit)limit.push(currentLine);else{if(rr=regx.exec(clean(currentLine)))if(ky&&"extra"==rr[1].toLowerCase()){var tm=getcolonne(rr[2]);for(var t of tm){var q=t.indexOf("=");if(q>0){var a=clean(t.substring(0,q));"v"!=a&&(this.rows[ky][a]=t.substring(q+1).trim())}}}else switch(rr[1].toLowerCase()){case"alias":if((vv=rr[2].toLowerCase().split(";"))[0].trim()!=this.name)if(1==vv.length)this.alias=vv[0];else{var vx;this.amb?vx=await this.amb.getvariante(vv[0]):(vx=new Variante,await vx.load(vv[0],this.cat));var rr=vx?.rows;if(rr){var kky=Object.keys(rr);if(kky.length){vv.splice(0,1);const addrows=kk=>{kk&&kk.forEach((k=>this.rows[k]=rr[k]))};for(var t of vv){var rx=/([ei])\s*:\s*(.*)\s*$/im.exec(t);if(rx){for(var k3=rx[2].split(","),i=0;i<k3.length;i++)k3[i]=k3[i].trim();kky="e"==rx[1]?kky.filter((k=>{for(var k2 of k3)if(k.startsWith(k2))return!1;return!0})):kky.filter((k=>{for(var k2 of k3)if(k.startsWith(k2))return!0;return!1}))}}addrows(kky)}}}break;case"h":this.h=getcolonne(rr[2]).map((e=>({des:e})));break;case"t":let tt=getcolonne(rr[2]);if(this.h)for(let i=0;i<this.h.length;i++)this.h[i].t=tt[i]||"";break;case"des":this.des=rr[2];break;case"default":case"vdef":this.vdef=getcolonne(rr[2]);break;case"obbligo":this.obbligo=!0;break;case"noerp":this.noerp=!0;break;case"noobbligo":this.obbligo=!1}else(k=clean((tm=getcolonne(currentLine))[0]))&&(ky=k,this.rows[ky]={annulla:0,v:tm})}}var kk=Object.keys(this.rows);for(var k of kk)if(k.includes(".")){var vv=k.split(".");for(i=0;i<vv.length-1;i++){var k1=vv.slice(0,i+1).join(".");this.rows[k1]||(this.rows[k1]={annulla:0,v:[k1]})}}return this.limits=parselimitifromrule(limits),!0}
|
|
211
|
+
/**
|
|
212
|
+
* Converte la variante in un vettore di righe
|
|
213
|
+
* @returns {string[]} Array di righe formattate
|
|
214
|
+
*/tovec(){var tm=this.rows,cl=[],xx=Object.keys(tm).sort();for(var x of xx)this.rows[x].annulla<2&&cl.push(this.#torow(x,this.rows[x]));return cl}
|
|
215
|
+
/**
|
|
216
|
+
* Converte una riga in una stringa CSV
|
|
217
|
+
* @private
|
|
218
|
+
* @param {string} cod - Codice della riga
|
|
219
|
+
* @param {Object} tm - Oggetto contenente i dati della riga
|
|
220
|
+
* @returns {string} Stringa CSV formattata
|
|
221
|
+
*/#torow(cod,tm){var cl=[cod];if(tm)for(var t of tm.v)"string"==typeof t&&(t.includes(",")||t.includes(";"))?cl.push(quote(t)):cl.push(t||"");return cl.join(",")}
|
|
222
|
+
/**
|
|
223
|
+
* Converte un codice nella sua rappresentazione CSV
|
|
224
|
+
* @param {string} cod - Codice da convertire
|
|
225
|
+
* @returns {string} Stringa CSV o codice originale se non trovato
|
|
226
|
+
*/tovar(cod,vcod=""){var c1=clean(cod);if(!this.rows[c1])return vcod||cod;var tm=this.rows[c1];return 2==tm.annulla?"":this.#torow(vcod||cod,tm)}
|
|
227
|
+
/**
|
|
228
|
+
* Verifica se un'opzione è valida
|
|
229
|
+
* @param {string} opz - Opzione da verificare
|
|
230
|
+
* @returns {boolean} True se l'opzione è valida
|
|
231
|
+
*/isvalidopz(opz){let c1=clean(opz),t=this.rows[c1];return!!t&&(1!=t.annulla&&!t.hasliv)}
|
|
232
|
+
/**
|
|
233
|
+
* Trova la prima opzione valida tra quelle disponibili
|
|
234
|
+
* @param {string} opz - Opzione da controllare per prima
|
|
235
|
+
* @returns {string|undefined} Prima opzione valida trovata o undefined
|
|
236
|
+
*/firstvalid(opz){if(opz&&this.isvalidopz(opz))return opz;if(this.vdef&&this.vdef.length)for(var o of this.vdef)if(this.isvalidopz(o))return o;for(var x in this.rows)if(this.isvalidopz(x))return x}
|
|
237
|
+
/**
|
|
238
|
+
* Resetta tutti i filtri applicati alla variante
|
|
239
|
+
*/resetfilter(){for(var x in delete this._valids,this.rows)this.rows[x].annulla=0}
|
|
240
|
+
/**
|
|
241
|
+
* Restituisce le chiavi valide ordinate alfabeticamente
|
|
242
|
+
* @returns {string[]} Array di chiavi valide
|
|
243
|
+
*/validkeys(){let kk=Object.keys(this.rows)||[];return kk=kk.filter((k=>0==this.rows[k].annulla)).sort(),kk}limitfiltra(filtra){if(this.resetfilter(),!filtra)return;filtra=muClComments(filtra.toLowerCase());let tm=[];for(var f of filtra){let rr=/^\#([ie])(\d*)\s+(.+)$/i.exec(f);if(rr){let t={ex:"e"==rr[1],col:(parseInt(rr[2])||1)-1,val:getcolonne(rr[3])};t.val.length&&tm.push(t)}}if(tm.length)for(var x in this.rows){let r=this.rows[x];for(var t of tm)if(t.ex){if(_check(r.v[t.col]||"",t.val)){r.annulla=1;break}}else if(!_check(r.v[t.col]||"",t.val)){r.annulla=1;break}}function _check(value,valori){return!!valori.find((e=>e.startsWith(value)))}}
|
|
244
|
+
/**
|
|
245
|
+
* Applica i limiti configurati alle opzioni della variante
|
|
246
|
+
* @returns {Array|void} Array di limiti applicati o void se reset
|
|
247
|
+
*/limita(filtra){if(filtra&&filtra.length)return this.limitfiltra(filtra);if(!this.limits||!this.amb)return this.resetfilter();let{item:item,rule:rule,model:model,vari:vari,data:data}=this.amb,valid=(v,values)=>!values||!values.length||!!v&&values.includes(v),tm=this.limits.filter((e=>{if(!valid(item,e.i))return!1;if(!valid(rule,e.r))return!1;if(!valid(model,e.m))return!1;if(data&&e.datai&&data<e.datai)return!1;if(data&&e.dataf&&data>e.dataf)return!1;if(e.v&&e.v.length)for(var v of e.v){let x=clean(vari.var(v.v).split(",")[0],!0);if(x&&!v.o.includes(x))return!1}return!0}));if(!tm||!tm.length)return this.resetfilter();let incstar=new Set,exstar=new Set,incaltri=new Set,exaltri=new Set,isinc=!1,isex=!1;for(var t of tm){if(t.valid&&t.valid.length){isinc=!0,t.valid.filter((e=>e.indexOf("*")>0)).map((e=>e.split("*")[0])).forEach((item=>incstar.add(item))),t.valid.filter((e=>!e.includes("*"))).forEach((item=>incaltri.add(item)))}if(t.ex&&t.ex.length){isex=!0,t.ex.filter((e=>e.indexOf("*")>0)).map((e=>e.split("*")[0])).forEach((item=>exstar.add(item))),t.ex.filter((e=>!e.includes("*"))).forEach((item=>exaltri.add(item)))}}for(var x in this.rows){let r=this.rows[x],flinc=!1,flex=!1;if(isinc){for(let i of incstar)if(x.startsWith(i)){flinc=!0;break}!flinc&&incaltri.has(x)&&(flinc=!0)}if(isex){for(let i of exstar)if(x.startsWith(i)){flex=!0;break}!flex&&exaltri.has(x)&&(flex=!0)}r.annulla=0,isinc&&!flinc&&(r.annulla=1),isex&&flex&&(r.annulla=1)}return tm}
|
|
248
|
+
/**
|
|
249
|
+
* Carica il contenuto esteso della variante
|
|
250
|
+
* @param {Object|string} content - Contenuto da caricare, può essere un oggetto o una stringa
|
|
251
|
+
* @returns {Promise<void>} Promise che si risolve al completamento del caricamento
|
|
252
|
+
*/async loadContentExtended(content){if("object"==typeof content){for(var x in content)["rows","des","h","alias","obbligo"].includes(x)&&(this[x]=content[x]);"string"==typeof content.def&&content.def.length&&(this.vdef=getcolonne(content.def.trim().toLowerCase())),content.filter&&content.filter.length&&(this.limits=parselimitifromdb(content.filter))}else await this._loadContent(muClComments(content,!1))}todata(){return{name:this.name,des:this.des,alias:this.alias,obbligo:this.obbligo,h:this.h,rows:this.rows,limits:this.limits,key:this.key}}}let _nofunc={};async function getcbfunc(tm,cmd,pars,vari,amb,output){if(cbFunc){if(_nofunc[cmd])return"";let a=await cbFunc(cmd,pars,vari,amb,output);return a=(a||"").trim(),"!"==a&&(_nofunc[cmd]=!0,a=""),a}return tm}async function intvaluta(amb,mac,str){return await amb.vari.valuta(str,(async(fun,pars)=>{if("dim"===fun){var dm=muCalc(pars[1]),vv=await dammivariante(amb,mac,pars[2]),col=parseInt(pars[3])||2;return vv&&vv.fromdim?vv.fromdim(dm,col):dm}return await getcbfunc(`**fun:${fun}**`,fun,pars,amb.vari,amb)}))}async function dammivariante(amb,macro,ky){return macro&¯o?.localvar&¯o.localvar[ky]?macro.localvar[ky]:await amb.getvariante(ky)}async function impostavariante(amb,macro,a,b,head){let tm,ky=a;if((b=b||"")&&"string"==typeof b){var k=b.indexOf(":");k>=0&&(k>0&&(ky=clean(b.slice(0,k))),b=b.slice(k+1))}
|
|
253
|
+
/** @type {Variante} */if(head&&head.alias&&(ky=head.alias),macro&¯o.paralias&¯o.paralias[a]&&(ky=macro.paralias[a]),tm=await dammivariante(amb,macro,ky),tm)if(head&&head.t){head.des||(head.des=tm.des);let x8=head?.filtra||"";if(x8.includes("$")&&(x8=await amb.vari.valuta(x8)),"m"===head.t){var col=2;if(b.includes(":")){var xx=b.split(":");col=parseInt(xx[1]),b=xx[0]}tm.limita(x8),b=tm.fromdim(parseFloat(b),col)}else{tm.limita(x8);let b1=tm.firstvalid(b);b=tm.tovar(b1)}}else tm.resetfilter(),b=tm.firstvalid(b),b=tm.tovar(b);else head&&head.t&&head.t;return amb.vari.add(a,b),b}async function pushpars(amb,macro,parsfunzione,parsinit){var fatti={},vals=[];if(parsfunzione)for(var x of parsfunzione){var{v:v,o:o,fl:fl}=getcouple(x);fatti[v]||(fatti[v]=!0,vals.push({v:v,o:amb.vari.var[v]}),fl&&await impostavariante(amb,macro,v,o))}if(parsinit)for(var x of parsinit){var{v:v,o:o,fl:fl}=getcouple(x);fatti[v]||(fatti[v]=!0,vals.push({v:v,o:amb.vari.var[v]}),fl&&await impostavariante(amb,macro,v,o))}return vals}async function poppars(amb,tm){if(tm)for(var x of tm)amb.vari.add(x.v,x.o)}const outpush=(output,a)=>{null!=a&&null!=a&&("string"==typeof a&&a.startsWith("_ ")&&output.length>0&&"string"==typeof output[output.length-1]&&!tipo?output[output.length-1]+=a.slice(2):output.push(...a.split("\n")))};async function muEval(amb,mac,codice,options){if(!Array.isArray(codice))return errori.add("codice is not a valid parsed array"),[];options||(options={}),options.id||(options.id="_"),options._stackmacro||(options._stackmacro=0),options.limited||(options.limited=!1),amb||errori.add("amb deve essere definito");let vari=amb.vari;amb.maxdelays,amb.cat;let output=[];xdt();for(var ii=0;ii<codice.length;){var riga=codice[ii];switch(riga.tipo){case"IFDEF":case"IFNDEF":case"IF":var tm="IF"==riga.tipo?muCalc(await intvaluta(amb,mac,riga.contenuto)):"IFDEF"==riga.tipo?""!=await intvaluta(amb,mac,riga.contenuto):""==await intvaluta(amb,mac,riga.contenuto);riga.next?(codice[riga.next].jlast=tm?1:0,tm||(ii=riga.next-1)):errori.add("Troppo tempo",riga);break;case"SELECT":riga.next?(codice[riga.next].t1=await intvaluta(amb,mac,riga.contenuto),ii=riga.next-1):errori.add("manca endselect",riga);break;case"CASE":case"CASES":case"DEFAULT":if(riga.next)if(riga.jlast)riga.jlast=0,ii=riga.last-1;else{tm=1;let vv;var _getvv=async()=>{var vv=await intvaluta(amb,mac,riga.contenuto);return vv=vv.includes(":")&&!vv.includes(",")?vv.split(":").map((e=>(e||"").trim())):getcolonne(vv)};if("CASE"==riga.tipo){tm=0,vv=await _getvv();var tmx=muCalc(riga.t1||"");vv.find((v=>muCalc(v)==tmx))&&(tm=1)}else if("CASES"==riga.tipo){tm=0,vv=await _getvv();tmx=riga.t1||"";vv.find((v=>v==tmx))&&(tm=1)}codice[riga.next].jlast=tm?1:0,codice[riga.next].t1=riga.t1,tm||(ii=riga.next-1)}else errori.add("manca select",riga);break;case"ELSEIF":case"ELSEIFDEF":case"ELSEIFNDEF":case"ELSE":if(riga.next)if(riga.jlast)riga.jlast=0,ii=riga.last-1;else{tm="ELSE"==riga.tipo?1:"ELSEIF"==riga.tipo?muCalc(await intvaluta(amb,mac,riga.contenuto)):"ELSEIFDEF"==riga.tipo?""!=await intvaluta(amb,mac,riga.contenuto):""==await intvaluta(amb,mac,riga.contenuto);codice[riga.next].jlast=tm?1:0,tm||(ii=riga.next-1)}else errori.add("manca endif",riga);break;case"ENDIF":case"ENDSELECT":case"CACHE":case"CVAR":break;case"PUSH":vari.push();break;case"POP":vari.pop();break;case"J":await getcbfunc("$$","$$",await intvaluta(amb,mac,riga.contenuto),vari,amb,output);break;case"INC":case"I":if(options._stackmacro>500)errori.add("stack chiamate macro troppo profondo!",riga);else{var{macro:macro,pars:pars,xid:xid}=await amb.getmacro(riga)||{};if(macro){options._inc=!0,options._stackmacro++;let saved={},parametri=macro.parametri?._;if(parametri&¶metri.length)for(var x of parametri){let x1=clean(x.split("=")[0]||"",!0);x1&&(saved[x1]=vari.dictionary[x1])}await macro.impostaparametri(parametri,pars);let rs1=await muEval(amb,macro,macro.codice,options);for(var v in saved)saved[v]?vari.dictionary[v]=saved[v]:delete vari.dictionary[v];output.push(...rs1),options._stackmacro--,options._inc=!1}}break;case"MACRO":case"M":case"FUNC":case"F":if(options._stackmacro>500)errori.add("stack chiamate macro troppo profondo!",riga);else{var{macro:macro,pars:pars,xid:xid}=await amb.getmacro(riga)||{};if(macro){let ismacro=options.grafica||["F","FUNC"].includes(riga.tipo),optid=options.id||"",parametri=macro.parametri?._,saved={};if(ismacro)vari.push();else{if(macro.head)for(var x in macro.head)saved[x]=amb.vari.var(x);if(parametri&¶metri.length)for(var x of parametri){let x1=(x.split("=")[0]||"").trim().toLowerCase();x1&&(saved[x1]=vari.dictionary[x1])}}if(macro.codice.length){if(options._stackmacro++,options.grafica&&"function"==typeof options.grafica){let f="",xid="";pars&&pars.length?(f=pars.find((e=>e.startsWith("#id"))),f?(f=await vari.valuta(f.slice(3)),options.id=hash(`${ii}${macro.name}${optid}${f}`),pars=pars.filter((e=>!e.startsWith("#id"))),xid=options.id):options.id=hash(`z${optid}${ii}`)):options.id=hash(`z${optid}${ii}`);let out=await options.grafica({tipo:riga.tipo,id:xid,pars:pars,parametri:parametri,macro:macro,options:options,vari:amb.vari,amb:amb});output.push(out)}else{await macro.impostaparametri(parametri,pars);let rs1=await muEval(amb,macro,macro.codice,options);output.push(...rs1)}options._stackmacro--}if(ismacro)vari.pop();else for(var v in saved)saved[v]?vari.dictionary[v]=saved[v]:delete vari.dictionary[v];options.id=optid}else errori.add("Macro non trovata!",riga)}break;case"LET":case"LETS":var j=-1;if((i=riga.contenuto.indexOf("="))>=0&&(j=riga.contenuto.indexOf("=",i+1)),j<0){if((i=(v=riga.contenuto).indexOf("="))>0){var a=await intvaluta(amb,mac,v.slice(0,i).trim()),b=v.slice(i+1).trim();b="LET"==riga.tipo?muCalc(await intvaluta(amb,mac,b))||"":await intvaluta(amb,mac,b),vari.add(a,b)}}else{var vv=getcolonne(riga.contenuto);for(var v of vv){if((i=v.indexOf("="))>0){a=await intvaluta(amb,mac,v.slice(0,i)),b=v.slice(i+1).trim();b="LET"==riga.tipo?muCalc(await intvaluta(amb,mac,b))||"":await intvaluta(amb,mac,b),vari.add(a,b)}}}break;case"LETT":var i;if((i=riga.contenuto.indexOf("="))>0){a=await intvaluta(amb,mac,riga.contenuto.slice(0,i).trim()),b=riga.contenuto.slice(i+1).trim();vari.add(a,b)}break;case"LOOK":case"LOOKB":{let cc=getcolonne(await intvaluta(amb,mac,riga.contenuto)),base=muCalc(cc[1]),col=muCalc(cc[3]),ww=await dammivariante(amb,macro,cc[2]);if(ww&&ww.rows){let rr=Object.values(ww.rows).reduce(((t,e)=>{let val=parseInt(e.v[col?col-1:0]);return val&&("LOOKB"==riga.tipo?val<=base&&val>t.v&&(t.v=val,t.c=e.v[0]):val>=base&&val<t.v&&(t.v=val,t.c=e.v[0])),t}),{v:"LOOKB"==riga.tipo?0:1/0,c:""});rr&&rr.c&&(amb.vari.add(cc[0],ww.tovar(rr.c)),options.checkheader&&"function"==typeof options.checkheader&&await options.checkheader({variante:cc[0],valore:ww.tovar(rr.c),riga:riga}))}else amb.vari.add(cc[0],`${base},no,no`)}break;case"LETV":case"LETM":case"DEF":if(tm=getcolonne(riga.contenuto))for(var x of tm){var{v:v,o:o,fl:fl}=getcouple(x);if(fl){v=await vari.valuta(v),o=await intvaluta(amb,mac,o);let valore=await impostavariante(amb,mac,v.trim().toLowerCase(),o.trim().toLowerCase(),"LETM"==riga.tipo?{t:"m"}:{t:"v"});options._stackmacro<=0&&options.checkheader&&"function"==typeof options.checkheader&&await options.checkheader({variante:v,valore:valore,riga:riga})}}break;case"DO":fl=!0;(valido=(riga.contenuto||"").trim())&&!muCalc(await intvaluta(amb,mac,valido))&&(fl=!1),riga.next&&(fl||(ii=riga.next+1));break;case"VARIANTE":case"FORVAR":case"FOR":{var valido,elenco;if(options.oldstyle)v=(vv=riga.contenuto.split(","))[2]||"i",elenco=vv[0],valido=vv[1];else v=(vv=getcolonne(riga.contenuto||""))[0]||"",elenco=clean(vv[1],!0),valido=vv[2]||"";if(v=v.includes("$")?await intvaluta(amb,mac,v):v||"","FORVAR"==riga.tipo||"VARIANTE"==riga.tipo){var xx=(tm=await intvaluta(amb,mac,elenco))?await dammivariante(amb,mac,tm):void 0;xx?elenco=xx.tovec():(elenco=[],errori.add("getvariante not found!",riga))}else{var txx=await intvaluta(amb,mac,elenco||"");elenco=elenco?getcolonne(txx):void 0}elenco=elenco||[];let nc=0;if(riga.next){(rr=codice[riga.next]).for={v:v,elenco:elenco,nc:nc,valido:valido};var voce;fl=!0;v&&elenco.length>0?nc>=elenco.length?fl=!1:(voce=elenco[nc],vari.add(v,voce),valido&&(fl=!muCalc(await intvaluta(amb,mac,valido)))):fl=!1,fl||(ii=riga.next-1)}else errori.add("manca endfor/loop",riga)}break;case"LOOP":var fl=!0;riga.contenuto&&!muCalc(await intvaluta(amb,mac,riga.contenuto))&&(fl=!1),fl&&(ii=riga.prev-1);break;case"ENDFOR":if(!riga.contenuto||muCalc(await intvaluta(amb,mac,riga.contenuto)))if(riga.for){var{v:v,elenco:elenco,valido:valido}=riga.for;if(v&&elenco.length>0&&riga.for.nc<500)for(;;){if(riga.for.nc++,riga.for.nc<elenco.length){if(vari.add(v,elenco[riga.for.nc]),valido&&muCalc(await intvaluta(amb,mac,valido)))continue;ii=riga.prev;break}break}}else errori.add("manca istruzione for",riga);break;case"BREAK":case"EXIT":case"EXITFOR":riga.next?riga.contenuto.trim()?muCalc(await intvaluta(amb,mac,riga.contenuto))&&(ii=riga.next):ii=riga.next:errori.add("break outside loop",riga);break;case"CONTINUE":riga.next?riga.contenuto&&!muCalc(await intvaluta(amb,mac,riga.contenuto))||(ii=riga.next-1):errori.add("continue outside loop",riga);break;case"MSG":case"LOG":let tm99=await intvaluta(amb,mac,riga.contenuto);logga(tm99),errori.add(tm99);break;default:{let tm;if(riga.contenuto.startsWith("!")){tm=await intvaluta(amb,mac,riga.contenuto);var rr;a="";if(rr=/^\!(\w+)[\s;,]\s*(.+)?$/gim.exec(tm)){var cmd=rr[1].toLowerCase(),pars=getcolonne(rr[2]||"");a=await getcbfunc(tm,cmd,pars,vari,amb)}a&&outpush(output,a)}else options.parsefnpunto&&"function"==typeof options.parsefnpunto&&riga.contenuto.startsWith(".")?await options.parsefnpunto({dati:riga.contenuto,output:output,id:options.id,vari:amb.vari,amb:amb}):(tm=await intvaluta(amb,mac,riga.contenuto),outpush(output,tm))}}ii++}return output}async function muGenerate(macro,amb,genera,callback,isTestmode=0){if(macro.isgenera&&callback){var output={counter:0,keys:{},isTestmode:isTestmode};if(genera){if(!macro.genera[genera])return!1;await muGenerate_0(macro,amb,genera,callback,output)}else for(var gg in macro.genera)await muGenerate_0(macro,amb,gg,callback,output);return!0}}async function muGenerate_0(mac,amb,genera,callback,output){var xgen=mac.genera[genera];if(xgen){output.counter2=0;var working_variant={},levels=[];async function processavariante(liv){if(!(output.isTestmode&&output.counter>output.isTestmode)){if(liv<xgen.vars.length){var xx=xgen.vars[liv];if(!working_variant[xx]){var xvar=await dammivariante(amb,mac,xx),keys=Object.keys(xvar.rows);if(keys&&keys.length>0){for(var k of keys)levels.push(k),amb.vari.add(xvar.name,xvar.tovar(k)),working_variant[xx]=!0,await processavariante(liv+1),working_variant[xx]=!1,levels.pop();return}logga("manca la variante",xx)}}for(var x of xgen.calcola)mac.formula[x]&&await muEval(amb,mac,mac.formula[x],{limited:!0});for(var x of xgen.exclude){if(mac.formula[x])if(vvv=await muEval(amb,mac,mac.formula[x],{limited:!0}))for(var v of vvv){if(muCalc(v))return}}var out1=await muEval(amb,mac,xgen.codice,{limited:!0,localvar:mac.localvar}),bb={};for(var x of xgen.bom)if(mac.formula[x]){var vvv=await muEval(amb,mac,mac.formula[x],{limited:!0});for(var v of vvv=vvv.join("\n").split("\n"))if(v){var tm=getcolonne(v);bb[x]||(bb[x]=[]);for(var t={},i=0;i<tm.length;i++)t[`c${i}`]=tm[i];bb[x].push(t)}}await async function docallback(callback,out1,bom,xgen,genera,output){var fl=!0;for(var x of out1){var tm=getcolonne(x);if(tm[0]&&!output[tm[0]]){output[tm[0]]=1,output.counter++,output.counter2++;for(var o={__id:output.counter},i=0;i<tm.length;i++){var key=xgen.head[i]?xgen.head[i]:`c${i}`;"#"==key[0]?o[key=key.substr(1)]=muCalc(tm[i]):o[key]=tm[i]}await callback(genera,o,fl?bom:void 0,output.counter,output.counter2),fl=!1}}}(callback,out1,bb,xgen,genera,output)}}await processavariante(0)}}const DIMS=["l","a","p"],rx1=/^\{(\:?(var|valid|formula|genera|header|v|f|g|h))[\s|\}]/im,tipifree=["s","g","h","p","q"],tipiheader=[{cod:"t",des:"Variante"},{cod:"q",des:"V.Query"},{cod:"f",des:"Valore Fisso"},{cod:"g",des:"Gruppo"},{cod:"s",des:"Libero"},{cod:"m",des:"Misura"},{cod:"c",des:"Check (no/si)"},{cod:"z",des:"Check (si/no)"},{cod:"h",des:"Hidden"},{cod:"p",des:"Programmato"}],tipicolonna=[{cod:"",des:"Libero"},{cod:"a",des:"Area"},{cod:"t",des:"Thumb",folder:"thumbs"},{cod:"i",des:"Image",folder:"textures"},{cod:"x",des:"3D file",folder:"3d"},{cod:"f",des:"Funzione",folder:"script"}];function valutaCondizioniTestata(vari,str){var vv=str.split("\n");for(var v of vv)if(v.trim()){if(muCalc(vari.valutasync(v)))return!0}return!1}class Macro{constructor(amb,name){var{name:name,cat:cat}=checkmu(name,amb.cat||"");this.name=name,this.cat=cat,
|
|
254
|
+
/** @type {Ambiente} */
|
|
255
|
+
this.amb=amb,this.azzera()}azzera(){this.key=`${this.cat}/${this.name}`,this.localvar={},this.head=[],this.frontend=!1,this.valid=[],this.parametri={},this.paralias={},this.formula={},this.settings={},this.errori=[],this.codice=[],this.genera={}}get isgenera(){return Object.keys(this.genera).length||0}get iscodice(){return this.codice.length||0}get isheader(){return this.head?.length||0}geterrori(){var cl=[];return this.errori.forEach((e=>cl.push({e:e}))),cl}getparametri(){let s={};if(this.dims&&DIMS.forEach((k=>{let t=muCalc(this.amb.vari.var(k));t&&(s[k]=String(t))})),this.head){for(var x of this.head)if(!x._h){var tm=this.amb.vari.var(x.cod);tipifree.includes(x.t)||"string"==typeof tm&&(tm=tm.split(",")[0]),s[x.cod]=tm}}else if(this.parametri?._)for(var x of this.parametri._){let x1=(x.split("=")[0]||"").trim().toLowerCase();tm=((tm=this.amb.vari.var[x1])||"").split(",")[0],s[x1]=tm}return s}async setparametri(pars){let ff={};for(var x of(pars||(pars={}),this.dims&&DIMS.forEach((e=>{let t=pars[e]||this.dims[e].val;t=parseFloat(t)||0,this.dims[e].visible&&(t<this.dims[e].min&&(t=this.dims[e].min),t>this.dims[e].max&&(t=this.dims[e].max)),pars[e]=String(t)})),this.head))"g"!=x.t&&("z"!=x.t||pars[x.cod]||(pars[x.cod]="1"),x._v=pars[x.cod],ff[x.cod]=!0);for(var x in pars)ff[x]||(ff[x]=!0,await impostavariante(this.amb,this,x,pars[x]));return this.head?.length>0&&await this.setparametro(this.head[0].cod,pars[this.head[0].cod]||void 0,!0),this.getparametri()}async setparametro(name,value,propaga=!1){if(value&&value.includes("$")&&(value=await intvaluta(this.amb,this,value)),this.head){const _imposta=async(riga,vv,id)=>{let nn=riga?.cod;if(riga.valid&&!riga._h1){let t0=!valutaCondizioniTestata(this.amb.vari,riga.valid);if(riga._h!=t0&&(riga._h=t0,["g","g1","g2"].includes(riga.t)))for(let i=id+1;i<this.head.length;i++){let tm1=this.head[i];if(tm1){if(["g","g1","g2"].includes(tm1.t))break;tm1._h1=riga._h}}}if(riga._h||riga._h1)return this.amb.vari.add(nn,""),riga._v=void 0,"";{if(delete riga._h2,riga.visible){let t0=!valutaCondizioniTestata(this.amb.vari,riga.visible);if(t0&&(riga._h2=t0),["g","g1","g2"].includes(riga.t))for(let i=id+1;i<this.head.length;i++){let tm1=this.head[i];if(tm1){if(["g","g1","g2"].includes(tm1.t))break;riga._h2?tm1._h3=riga._h2:delete tm1._h3}}}let tx=this.amb.vari.var(nn)||"";if("string"==typeof tx&&(tx=tx.split(",")[0]),"z"!=riga.t||tx||(this.amb.vari.add(nn,"1"),tx="1"),"m"==riga.t&&riga.spars){let vspars=getcolonne(riga.spars);tx=parseFloat(tx||vspars[0])||0,vspars[1]&&parseFloat(tx)<vspars[1]&&(tx=parseFloat(vspars[1])||0),vspars[2]&&parseFloat(tx)>vspars[2]&&(tx=parseFloat(vspars[2])||0),tx=String(tx),this.amb.vari.add(nn,tx)}let tmimposta=await impostavariante(this.amb,this,nn,vv||riga._v||tx,riga);return riga._v=void 0,tx=this.amb.vari.var(nn)||"",this.amb&&this.amb.deriva&&this.amb.deriva.length>0&&this.amb.deriva.filter((e=>e.cod==nn&&((!e.item||e.item==this.amb.item)&&((!e.model||e.model==this.amb.model)&&((!e.rule||e.rule==this.amb.rule)&&(!e.opz||e.opz==vv)))))),tmimposta}};let tm,i0=-1;if("#dim"==name)propaga=1;else{if(i0=this.head.findIndex((e=>e.cod===name)),i0<0)return;let hh=this.head[i0];tm=await _imposta(hh,value,i0),delete hh._d}if(propaga)for(let i=i0+1;i<this.head.length;i++)await _imposta(this.head[i],void 0,i);return tm}return await impostavariante(this.amb,this,name,value)}async impostaparametri(parimposta,parcall,ismacro=!1){if(this.head)for(var i of(this.paralias||(this.paralias={}),Array.isArray(this.head)||(this.head=[]),this.head))i._v="",delete i._h,delete i._h1,delete i._h2,i.alias&&(this.paralias[i.cod]=i.alias);for(var x of(parimposta||(parimposta=[]),parcall||(parcall=[]),[...parimposta,...parcall])){if((i=x.indexOf("="))>0){let a=clean(x.substr(0,i));a.includes("$")&&(a=await intvaluta(this.amb,this,a));let t,b=x.substr(i+1);b.includes("$")&&(b=await intvaluta(this.amb,this,b)),this.head&&(t=this.head.find((e=>e.cod==a)))?t._v=b:await impostavariante(this.amb,this,a,b)}}if(this.head){let fl=!0;for(var h of this.head){let fl2=await this.checkvalid(h.valid);ismacro&&(fl2=!0),["g","g1","g2"].includes(h.t)?fl=fl2:fl&&fl2&&await this.setparametro(h.cod,h._v)}}}async checkvalid(formula){if(!formula)return!0;return!!muCalc(await intvaluta(this.amb,this,formula))}getmacrostr(){return JSON.stringify(this.getmacro())}getmacro(){return getOggetto(this,["amb"])}setmacro(vv){if(setOggetto(this,fromjson(vv,{})),this.localvar)for(var x in this.localvar){setOggetto(vv=new Variante,this.localvar[x]),this.localvar[x]=vv}}async load(xname,xcat){try{var tm,{name:name,cat:cat}=checkmu(xname||this.name,xcat||this.cat||"");if(this.name||(this.name=name),this.cat||(this.cat=cat),this.azzera(),cbGetMacro&&("string"==typeof(tm=await cbGetMacro(cat,name))&&(tm.startsWith("{")||tm.startsWith("["))&&(tm=fromjson(tm)),tm&&tm.head&&!Array.isArray(tm.head)&&(tm.head=[]),tm.head&&(tm.dims=getheaddims(tm.dims))),tm){if("string"==typeof tm)await this.parsedata(tm);else for(var x in tm)this[x]=tm[x];return!0}errori.add(`missing cbGetFile: ${cat}/${name}`)}catch(error){errori.add(geterrdes(error),`macro.load: ${name}/${cat}`)}}async loadAndCompile(file,cat,acapo=!1){var res,{name:name,cat:cat}=checkmu(file,this.cat||cat);return this.azzera(),cbGetFile&&(res=await cbGetFile(cat,name)),res?(await this.parsedata(res,acapo),this.getmacro()):void errori.add(`missing cbGetFile: ${name}/${cat}`)}async#loadinclude(file,flin,stak,pp){var res,{name:name,cat:cat}=checkmu(file,this.cat);if(cbGetFile&&(res=await cbGetFile(cat,name)),!res)return[];if(res.includes("$1")&&pp&&pp.length>0)for(var i=1;i<pp.length;i++)res=res.replaceAll(`$${i}`,pp[i]);var tm=muClComments(res),t2=[];for(var t of(flin&&(tm=tm.filter((t=>!/^\{(\:?(var|valid|formula|header|genera|v|f|h))[\s|\}]/im.test(t)))),tm)){const rr=rx1.exec(t);if(rr)flin=!rr[1].startsWith(":"),t2.push(t);else{const r1=/^\s*\{i\s(.+)?\}/im.exec(t);if(r1){pp=getcolonne(r1[1]);if(!stak.includes(pp[0])){stak.push(pp[0]);var t3=await this.loadinclude(pp[0],flin,stak,pp);Array.isArray(t3)&&t2.push(...t3),stak.pop()}}else t2.push(t)}}return t2}async parsedata(res,acapo=!1){if(this.azzera(),!res)return;var t2=[],tm=muClComments(res),flin=!1;let lochead=[];for(var t of tm){const rr=rx1.exec(t);if(rr)flin=!rr[1].startsWith(":"),t2.push(t);else{const r1=/^\s*\{i\s(.+)?\}/im.exec(t);if(r1){var pp=getcolonne(r1[1]),t3=await this.#loadinclude(pp[0],flin,[pp[0]],pp);Array.isArray(t3)&&t2.push(...t3)}else t2.push(t)}}flin=!1;var out=this.codice;for(var t of t2){const rr=rx1.exec(t);if(rr)if(rr[1].startsWith(":"))out=this.codice;else switch(rr[1]){case"genera":case"g":if(r2=/^\s*\{(genera|g)\s+(.+)?\}/im.exec(t)){var name=checkname(getcolonne(r2[2])[0]);this.genera[name]=[],out=this.genera[name]}else(out=this.errori).push(t);break;case"valid":out=this.valid;break;case"var":case"v":if(r2=/^\s*\{(var|v)\s+(.+)?\}/im.exec(t)){var nn=getcolonne(r2[2]);name=checkname(nn[0]);this.localvar[name]={name:name,des:nn[1]||"",rows:[]},out=this.localvar[name].rows}else(out=this.errori).push(t);break;case"formula":case"f":var r2;if(r2=/^\s*\{(formula|f)\s+(.+)?\}/im.exec(t)){name=checkname(r2[2]);this.formula[name]=[],out=this.formula[name]}else(out=this.errori).push(t);break;case"h":case"header":out=lochead;break;default:this.errori.push(t),out=this.errori}else t.startsWith("{")&&(out=this.codice),out.push(t)}for(var f in this.parametri={},this.codice=this.cleanfiltraparametri("_",this.codice,acapo),this.formula)this.formula[f]=this.cleanfiltraparametri(f,this.formula[f],acapo);for(var f in this.localvar){var vv=new Variante,v=this.localvar[f];for(var x of(vv.setheader(f,this.cat),vv.rows={},v.rows)){var k=(c=getcolonne(x))[0].trim().toLowerCase();vv.rows[k]={annulla:0,v:c}}v.des&&(vv.des=v.des),this.localvar[f]=vv}tm=this.valid;for(var t of(this.valid=[],tm)){(p={v:(p=getcouple(t,",")).v,msg:p.o}).v&&(p.v.startsWith("#")?this.formula[p.v.substring(1)]&&this.valid.push(p):this.valid.push(p))}tm=lochead;var head=[];for(var t of tm){if(rr=/^\s*([\w\-\_]+)+[\;\,\s]\s*(.*)?$/im.exec(t)){var c;pp=getcolonne(rr[2]);let ht;if(c=clean(rr[1]))for(var tp of(ht=head.find((e=>e.cod==c)),ht||(ht={cod:c,t:"t"},head.push(ht)),pp)){var p;switch((p=getcouple(tp)).v){case"t":ht.t=p.o;break;case"def":case"default":ht.def=p.o;break;case"valid":case"colonna":case"hidden":p.o.startsWith("#")?this.formula[p.o.substring(1)]&&(ht[p.v]=p.o):ht[p.v]=p.o;break;default:ht[p.v]=p.o}}}}this.head=head;tm=this.genera;var genera={};for(var kk in tm)if(Array.isArray(tm[kk])){var gen={codice:[],head:"",calcola:[],bom:[],vars:[],exclude:[]};const regx=/^\s*[\!\:]\s*(\w+)\s*(.*)$/i;for(var k2 of tm[kk]){var rr;if(rr=regx.exec(clean(k2)))switch(rr[1]){case"calcola":case"c":gen.calcola=[...gen.calcola,...getcolonne(rr[2])];break;case"exclude":case"e":case"escludi":gen.exclude=[...gen.exclude,...getcolonne(rr[2])];break;case"bom":case"db":gen.bom=[...gen.bom,...getcolonne(rr[2])];break;case"vars":case"v":gen.vars=[...gen.vars,...getcolonne(rr[2])];break;case"head":case"h":gen.head=getcolonne(rr[2]);break;default:this.errori.push(`genera ${kk} => ${k2}`)}else gen.codice.push(k2)}gen.codice=muClean(gen.codice,!0),genera[kk]=gen}this.genera=genera}cleanfiltraparametri(key,codice,acapo){if(this.paralias||(this.paralias={}),codice&&codice.length){var fl=!1;const getparalias=dati=>{let cl=[],co=getcolonne(dati);for(var c of co)if(c.includes(":")){let v=c.split(":");this.paralias[v[0]]=v[1],cl.push(v[0])}else cl.push(c);return cl};for(var i=0;i<codice.length;i++){let rr=/^\:p[;,\s]+(.*)?$/im.exec(codice[i]);if(rr)codice[i]=null,fl=!0,this.parametri[key]=getparalias(rr[1]);else{let rr=/^!(parametri|pars|p)[;,\s]+(.*)?$/im.exec(codice[i]);rr&&(codice[i]=null,fl=!0,this.parametri[key]=getparalias(rr[2]))}}fl&&(codice=codice.filter((e=>null!=e)))}return codice=muClean(codice,acapo)}}function parsevariabili(text){for(var fl=!1,tk=[];;){let m=/\$([\{\[\(])/m.exec(text);if(!m){text&&fl&&tk.push({class:"",text:text});break}fl=!0;var classe="["==m[1]?"inline":"variabile";m.index>0&&tk.push({class:"",text:text.substring(0,m.index)});var{i:i}=parsevar(text,m.index+2,m[1],null);if(!(i>m.index)){tk.push({class:classe,text:text.substring(m.index)});break}tk.push({class:classe,text:text.substring(m.index,i+1)}),text=text.substring(i+1)}return{fl:fl,tk:tk}}function parseexp(text,exp,callback){if(!callback)throw new Error("missing callback");for(var fl=!1,tk=[];;){let m=exp.exec(text);if(!m){text&&fl&&tk.push({class:"",text:text});break}m.index>0&&tk.push({class:"",text:text.substring(0,m.index)}),tk.push(...callback(m)),fl=!0,text=text.substring(m.index+m[0].length)}return{fl:fl,tk:tk}}
|
|
256
|
+
/**
|
|
257
|
+
* Analizza il codice sorgente e restituisce un array di token con classi CSS
|
|
258
|
+
* @param {string} tt - Il codice sorgente da analizzare
|
|
259
|
+
* @param {boolean} isvar - Flag che indica se analizzare come variabile
|
|
260
|
+
* @returns {Array<{class: string, text: string}>} Array di token con classi CSS
|
|
261
|
+
*/function muParsecode(tt,isvar){tt||(tt=" "),tt.endsWith("\n")&&(tt+=" ");for(var tm=[{class:"",text:tt}],i=0;i<tm.length;i++)if(!tm[i].class){var{fl:fl,tk:tk}=parseexp(tm[i].text,/(\/\*[^]+?\*\/)/im,(m=>[{class:"comment",text:m[1]}]));if(fl&&tm.splice(i,1,...tk),!tm[i].class){var{fl:fl,tk:tk}=parseexp(tm[i].text,/(\/\/.*)$/im,(m=>[{class:"commento2",text:m[1]}]));if(fl&&tm.splice(i,1,...tk),!tm[i].class){var{fl:fl,tk:tk}=parseexp(tm[i].text,/(^\s*\{.+?\})/m,(m=>[{class:"header",text:m[1]}]));if(fl&&tm.splice(i,1,...tk),!tm[i].class){var{fl:fl,tk:tk}=parseexp(tm[i].text,/(^\s*\:\w+)(.*?$)/m,(m=>[{class:"param",text:m[1]},{class:"param2",text:m[2]}]));if(fl&&tm.splice(i,1,...tk),!isvar){if(tm[i].class)continue;var{fl:fl,tk:tk}=parseexp(tm[i].text,/(^\s*\!\w+)/m,(m=>[{class:"function",text:m[1]}]));if(fl&&tm.splice(i,1,...tk),tm[i].class)continue;var{fl:fl,tk:tk}=parseexp(tm[i].text,/(#let.? +)([\w_\.]+)/im,(m=>[{class:"comando",text:m[1]},{class:"variabile",text:m[2]}]));if(fl&&tm.splice(i,1,...tk),tm[i].class)continue;var{fl:fl,tk:tk}=parseexp(tm[i].text,/(#(push|pop|select|cases|endselect|ifndef|elseifndef|ifdef|endif|elseifdef|variante|forvar|for|endfor|continue|break|inc|macro|default|letm|lets|letv|lett|leto|cat))/im,(m=>[{class:"comando",text:m[1]}]));if(fl&&tm.splice(i,1,...tk),tm[i].class)continue;var{fl:fl,tk:tk}=parseexp(tm[i].text,/(#(if\s*|elseif\s*))/im,(m=>[{class:"comando",text:m[1]}]));if(fl&&tm.splice(i,1,...tk),tm[i].class)continue;var{fl:fl,tk:tk}=parseexp(tm[i].text,/(#(else|i |m |f |j |case|def ))/im,(m=>[{class:"comando",text:m[1]}]));if(fl&&tm.splice(i,1,...tk),tm[i].class)continue;var{fl:fl,tk:tk}=parsevariabili(tm[i].text);if(fl&&tm.splice(i,1,...tk),tm[i].class)continue;var{fl:fl,tk:tk}=parseexp(tm[i].text,/(\$[\w_\.]+)/im,(m=>[{class:"variabile",text:m[1]}]));fl&&tm.splice(i,1,...tk)}}}}}return tm}function headerconvert(tt){var rr=muClComments(tt,!1),grp=(tt={},{r:[]}),fl=!1;for(var r of rr){var m=/^\s*\{(h|head|header)\s+(\w+)\}/im.exec(r);if(m)grp={cod:m[2],des:m[2],r:[]},fl=!1,tt[m[2]]=grp;else if(!/^\s*\:/.exec(r)){var tm,v=r.split(","),t={cod:clean(v[0])};(tm=(v[1]||"").trim())&&(t.des=tm),(tm=clean(v[2]))&&(t.tipo=tm),(tm=clean(v[3]))&&(t.alias=tm),(tm=clean(v[4]))&&(t.valid=tm),(tm=clean(v[5]))&&(t.visible=tm),t.cod&&(fl||"sep"!=t.tipo?grp.r.push(t):(grp.des=t.des,grp.valid=t.valid,grp.visible=t.visible,fl=!0))}}return tt}function aliasconvert(tt){var rr=muClComments(tt.toLowerCase(),!1),tx={};for(var r of rr)if(!/^\s*\:/.exec(r)){var v=getcolonne(r);v[0]&&v[1]&&(tx[v[0]]={cod:v[1]})}return tx}class Ambiente{#headers=void 0;#alias=void 0;#deriva=void 0;#typos=void 0;constructor(cat=".",maxdelays=100,righevuote=!1){this.righevuote=righevuote,this.maxdelays=maxdelays,this.setcatalog(cat),this.fndotcallback=void 0}setcatalog(cat){return cat=clean(cat),this.cat!=cat&&(this.cat=cat,this.item=this.rule=this.model="",this.azzera(!0)),cat}get muvalutatore(){return{getcolonne:getcolonne,muCalc:muCalc,muEval:muEval,tipifree:tipifree}}azzera(mode=!1){
|
|
262
|
+
/** @type {Variabile} */
|
|
263
|
+
this.vari=new Variabile,this.fndotcallback&&this.vari.setfndot(this.fndotcallback),this.ruleheader="",mode&&(
|
|
264
|
+
/** @type {Object.<string, Macro>} */
|
|
265
|
+
this.macro={},
|
|
266
|
+
/** @type {Object.<string, Variante>} */
|
|
267
|
+
this.varianti={},this.varelenco={},this.macroelenco={},this.scripts={},this.#headers=void 0,this.#alias=void 0,this.#deriva=void 0,this.#typos=void 0)}async setfndot(fndotcallback){this.fndotcallback=fndotcallback,this.vari.setfndot(fndotcallback)}async#checkelencovar(cat){if(cbInfo&&!this.varelenco[cat]){let tm=await cbInfo("headers",cat,"_varianti");Array.isArray(tm)?this.varelenco[cat]=tm:tm.vars&&(this.varelenco[cat]=tm.vars,tm.alias&&(this.#alias=tm.alias)),this.varelenco[cat]||(this.varelenco[cat]=[])}}parseheaderfrominfo(tm){if(tm&&tm.length>0)for(var t of tm)switch(t.tipo){case"_headers":t.value,t.value=headerconvert(t.value),this.#headers=t.value||{};break;case"_alias":t.value,t.value=aliasconvert(t.value),this.#alias=t.value||{};break;case"_typos":t.value;var tips=fromjson(t.value);for(var tp in tips){var tq=tips[tp];tq.db&&(tq.db=muClean(muClComments(tq.db))),tq.list&&(tq.list=muClean(muClComments(tq.list)))}t.value=tips,this.#typos=t.value||{}}}setitem(item,rule,model,datadelgiorno){this.item=clean(item,!0),this.rule=clean(rule,!0),this.model=clean(model,!0),this.data=datadelgiorno||(new Date).toInt()}async getheader(cod){if(!this.#headers&&cbInfo){var tm=await cbInfo("headers",this.cat,"_headers");this.parseheaderfrominfo(tm)}return this.#headers||(this.#headers={}),this.#headers[cod]}async getalias(){if(!this.#alias&&cbInfo){var tm=await cbInfo("headers",this.cat,"_alias");this.parseheaderfrominfo(tm)}return this.#alias||(this.#alias={}),this.#alias}get deriva(){return this.#deriva,this.#deriva||[]}async getmacro(riga){try{if("string"==typeof riga&&(riga={tipo:"M",contenuto:riga}),!riga||!riga.contenuto)return;var rr=/^([\(\{\}\)\:\$\w\.\\\/]+)[\s\;\,]*(.*)?$/im.exec(riga.contenuto);if(!rr)return void errori.add("Macro non valida:"+riga.contenuto,riga);(macro=clean(rr[1],!0)).includes("$")&&(macro=await this.vari.valuta(macro));var pars=getcolonne(rr[2]),{name:name,cat:cat}=checkmu(macro,this.cat);this.cat=cat;var macro,ky=`${cat}/${name}`;if(!this.macro[ky]){var tm=new Macro(this,name);await tm.load()?this.macro[ky]=tm:errori.add(`macro fail to load ${ky}`,riga)}return(macro=this.macro[ky])?{macro:macro,pars:pars}:(errori.add(`macro non trovata ${ky}`,riga),{})}catch(error){errori.add(geterrdes(error),`ambiente.getmacro: ${riga?.contenuto}`)}}async getvariante(cod){var{name:name,cat:cat}=checkmu(cod,this.cat),n2=name;let altri={};if(cat==this.cat&&this.#alias&&this.#alias[name]&&(altri=this.#alias[name]||{},n2=altri.cod),await this.#checkelencovar(cat),this.varelenco[cat]&&!this.varelenco[cat].includes(name))return;var key=`${cat}/${n2}`;let vv;return this.varianti[key]?vv=this.varianti[key]:(vv=new Variante(this),await vv.load(key,cat),this.varianti[key]=vv),altri&&(altri.des&&(vv.des=altri.des),altri.vdef&&(vv.vdef=altri.vdef)),vv}async varcompila(v,callback){var xx=new Variante(this);(await xx.load(v,this.cat,!0),xx.alias)&&((await this.getalias())[v]=xx.alias);callback("variants",{cod:v,des:xx.des||"",alias:xx.alias,info:xx.alias?"":JSON.stringify(getOggetto(xx,["amb"]))})}async macrocompila(v,callback){var mac=new Macro(this,v);await mac.loadAndCompile(`${v}.mu`);var t=mac.getmacro();callback("macros",{cod:v,info:JSON.stringify(t),isgenera:mac.isgenera,isheader:mac.isheader,iscodice:mac.iscodice})}async barrecompila(articolibarre,titolibarre,callback){var cc=new CodiceBarra;for(var x in cc.compila(articolibarre,titolibarre),cc.barre){callback("barcodes",{cod:x,des:"",info:JSON.stringify(cc.barre[x])})}return cc}async tojson(d){let tm;return cbFunc&&(tm=await cbFunc("json",d)),tm}async compila(info,callback){if(callback){for(var v of info.var)await this.varcompila(v,callback);for(var v of info.mu)await this.macrocompila(v,callback);if(callback("infos",{cod:"info",des:info.cat,info:JSON.stringify({cat:info.cat,md:info.info})}),this.#headers=void 0,this.#alias=void 0,this.#deriva=void 0,this.#typos=void 0,cbInfo){var tm=await cbInfo("headers",this.cat,["_headers","_alias","_deriva","_typos"]);this.parseheaderfrominfo(tm)}this.#headers?callback("infos",{cod:"headers",des:"",info:JSON.stringify(this.#headers)}):logga("missing headers"),this.#alias&&callback("infos",{cod:"alias",des:"",info:JSON.stringify(this.#alias)}),this.#deriva&&callback("infos",{cod:"deriva",des:"",info:JSON.stringify(this.#deriva)}),this.#typos&&callback("infos",{cod:"typos",des:"tipologie",info:JSON.stringify(this.#typos)})}}async getheaderfromdb(name){let totale=await cbInfo("header",this.cat,name,!this.#deriva),{head:head,rows:rows,macros:macros,deriva:deriva,llvars:llvars}=totale;for(var r of rows)r.cod=clean(r.cod),r.alias=clean(r.alias),r.t=clean(r.t);if(!llvars){for(var r of(llvars=new Set,rows)){let nn=r.alias?r.alias:r.cod;llvars.add(nn)}llvars=[...llvars]}this.#deriva||(this.#deriva=deriva),await this.#checkelencovar(this.cat),head.cod=clean(head.cod),head.rule=clean(head.rule),head.ruledef=head.ruledef||[];let vn=[],t=this.varelenco[this.cat];for(var nn of llvars)this.varianti[`${this.cat}/${nn}`]||t&&t.includes(nn)&&vn.push(nn);if(vn.length&&cbGetVariante){var vars=await cbGetVariante(this.cat,vn);if(vars&&vars.length)for(var x of vars){let{name:name,content:content}=x,vv=new Variante(this);vv.setheader(name,this.cat),content&&await vv.loadContentExtended(content),this.varianti[vv.key]=vv}}return{head:head,rows:rows,macros:macros}}async getlinkedmacros(rule,macros){var getkey=n=>n.includes("/")?n:`${this.cat}/${n}`;let k,cl=[];if(rule&&(k=getkey(rule),this.macro[k]||cl.push(rule)),macros&&"string"==typeof macros){let vv=macros.split(";");for(var v of vv)k=getkey(v),this.macro[k]||cl.push(v)}if(cl&&cl.length>0&&cbGetMacro){let tm=await cbGetMacro(this.cat,cl);if(tm&&tm.length>0)for(var x of tm){let m=new Macro(this,x.name);for(var t in x.content){let contenuto=x.content[t];m[t]=contenuto}this.macro[m.key]=m}}}async setruleheader(rule,pars){var{name:name,cat:cat}=checkmu(rule,this.cat),ky=`${cat}/${name}`;if(!this.macro[ky]){let totale=await this.getheaderfromdb(name),{head:head,rows:rows,macros:macros}=totale;await this.getlinkedmacros(head.rule,macros);var tm=new Macro(this,name);if(!head)return void errori.add("Missing rule: "+rule);if(head.rule){let k2=this.macro[`${cat}/${head.rule}`];if(k2)for(var x in k2)["cat","name","key"].includes(x)||(tm[x]=k2[x])}rows&&rows.length&&(tm.head=rows),this.macro[ky]=tm}this.ruleheader=ky;let mc=this.macro[ky];return errori.azzera(),await mc.setparametri(pars),mc}getruleheader(){return this.macro[this.ruleheader]}async setvariante(cod,opz){return await impostavariante(this,null,cod,opz)}async valuta(codice){let output;return"string"==typeof codice&&(codice=muClean(muClComments(codice,this.righevuote))),Array.isArray(codice)&&(logga("m1",codice),output=await muEval(this,null,codice)),output}setinfos(tm){tm&&(this.#headers=tm.headers,this.#alias=tm.alias,this.#deriva=void 0,this.#typos=tm.typos)}}function toJson(t){return JSON.stringify(t,null,2)}function clamp(n,min=-1/0,max=1/0){return(n=Number(n)||0)<min&&(n=min),n>max&&(n=max),n}function gettipocolonna(cod){return tipicolonna.find((x=>x.cod==cod))?.des||tipicolonna[0].des}function gettipofolder(cod){return tipicolonna.find((x=>x.cod==cod))?.folder||""}function newVariabile(){return new Variabile}async function newVariante(cod,cat,amb){var xx=new Variante(amb);return await xx.load(cod,cat),xx}function newAmbiente(cat,maxmillis=100){return new Ambiente(cat,maxmillis)}function newMacro(amb,name){return new Macro(amb,name)}function muValuta(mu,codice,azzera){return azzera&&mu.azzera(),mu.valuta(codice)}function muInit(cat,cbGetMacro,cbGetVariante,cbFunc,cbInfo,cbGetFile,cbLogga){var mu=new Ambiente(cat);return setcallbacks(cbGetMacro,cbGetVariante,cbFunc,cbInfo,cbGetFile,cbLogga),mu}function muCompileScript(codice){return codice&&"object"==typeof codice?codice:codice.startsWith("{")&&codice.endsWith("}")||codice.startsWith("[")&&codice.endsWith("]")?JSON.stringify(codice):muClean(muClComments(codice))}async function muEvalScript(/** @type {Ambiente} */amb,codice,pars,reset=!0){if(codice=muCompileScript(codice),reset&&amb.azzera(),pars)for(var p of pars){var{v:v,o:o}=getcouple(p);amb.vari.add(v,o)}return{output:await muEval(amb,null,codice,{}),vari:amb.vari.dictionary,errori:errori}}const tonum=(s,dec=-1)=>{if(!s)return 0;let n=0;if("number"==typeof s)n=s||0;else if("string"==typeof s){let x=(s=s.replaceAll(",",".")).match(/^-?[0-9.]+$/);n=x&&x.length>0?Number(x[0])||0:muCalc(s)}if(dec>=0)switch(dec){case 0:n=Math.round(n);break;case 1:n=Math.round(10*n)/10;break;case 2:n=Math.round(100*n)/100;break;case 3:n=Math.round(1e3*n)/1e3;break;case 4:n=Math.round(1e4*n)/1e4;break;case 5:n=Math.round(1e5*n)/1e5;break;case 6:n=Math.round(1e6*n)/1e6}return n||0};Date.prototype.toInt||(Date.prototype.toInt=function(){return this.getDate()+100*(this.getMonth()+1)+1e4*this.getFullYear()}),Date.prototype.toFloat||(Date.prototype.toFloat=function(){return Math.floor(1e4*this.getDate()+1e6*(this.getMonth()+1)+1e8*this.getFullYear()+100*this.getHours()+this.getMinutes()+.5)/1e4});const mustr={mus:{variants:{cod:"s",des:"s",alias:"s",info:"s",md:"s",__pk:"cod"},extras:{tipo:"s",cod:"s",info:"s",__pk:"tipo, cod"},macros:{cod:"s",des:"s",info:"s",md:"s",def:"s",isgenera:"i",iscodice:"i",isheader:"i",__pk:"cod"},infos:{cod:"s",des:"s",info:"s",__pk:"cod"},barcodes:{cod:"s",des:"s",info:"s",__pk:"cod"}}};export{Ambiente,CodiceBarra,Macro,Variabile,Variante,checkmu,checkname,clamp,clean,dammivariante,errori,fromjson,getOggetto,getcolonne,getcouple,geterrdes,getheaddims,gettipocolonna,gettipofolder,hash,impostavariante,intvaluta,muInit as jsTest,logga,muCalc,muClComments,muClean,muCompileScript,muEval,muEvalScript,muGenerate,muInit,muLimits,muParsecode,muValuta,mustr,newAmbiente,newMacro,newVariabile,newVariante,parselimitifromdb,parselimitifromrule,parsevar,poppars,pushpars,quote,setOggetto,testsync,tipicolonna,tipifree,tipiheader,tk,toCadPars,toJson,tonum,xdt};
|