markuno_lib 1.2.82 → 1.2.84
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 +1 -76
- package/bin/markcad.js +1 -1121
- package/bin/marked.js +1 -21
- package/bin/markuno.js +1 -268
- package/bin/proto.js +1 -184
- package/package.json +1 -1
- package/types/bus_utils.d.ts +15 -45
- package/types/markcad.d.ts +2151 -484
- package/types/marked.d.ts +43 -43
- package/types/markuno.d.ts +169 -363
package/bin/markuno.js
CHANGED
|
@@ -1,268 +1 @@
|
|
|
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 seedarray(arr,seed){if(arr&&arr.length){let cl=[];for(let i=0;i<arr.length;i++){let a=arr[i];if(a.p)for(let j=0;j<a.p;j++)cl.push(i);else cl.push(i)}return arr[cl[seeder(cl.length,seed)]]}}function seeder(n,seed="seed42"){const rand=function mulberry32(a){return function(){a=(a|=0)+1831565813|0;let t=Math.imul(a^a>>>15,1|a);return t=t+Math.imul(t^t>>>7,61|t)^t,((t^t>>>14)>>>0)/4294967296}}(function xmur3(str){let h=1779033703^str.length;for(let i=0;i<str.length;i++)h=Math.imul(h^str.charCodeAt(i),3432918353),h=h<<13|h>>>19;return function(){return h=Math.imul(h^h>>>16,2246822507),h=Math.imul(h^h>>>13,3266489909),(h^=h>>>16)>>>0}}(String(seed))());return Math.floor(rand()*n)}function isJsonStr(str){if("string"!=typeof str)return!1;const trimmed=str.trim();return trimmed.startsWith("{")&&trimmed.endsWith("}")||trimmed.startsWith("[")&&trimmed.endsWith("]")}const isObject=value=>!(!value||!Array.isArray(value)&&"object"!=typeof value);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 noquote(e){return(e=e.trim()).startsWith('"')&&e.endsWith('"')||e.startsWith("(")&&e.endsWith(")")?e.slice(1,-1):e}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){const 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){const 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
|
-
* @param {boolean} vuoto - Default false: Accetta valori vuoti!
|
|
56
|
-
* @throws {Error} Se l'identificatore contiene caratteri non validi
|
|
57
|
-
* @returns {string} Identificatore validato in minuscolo
|
|
58
|
-
*/function checkname(id,vuoto=!1){if(id=(id||"").trim(),vuoto&&!id)return"";if(!id||!/^[a-zA-Z_][a-z0-9A-Z_+-]*$/gim.test(id))throw new Error(`nome non valido: "${id}" \n deve contenere solo lettere, _, -, e numeri`);return id.toLowerCase()}
|
|
59
|
-
/**
|
|
60
|
-
* Converte una stringa in array di colonne, gestendo diversi formati
|
|
61
|
-
* @param {string} value - Stringa da convertire
|
|
62
|
-
* @returns {string[]} Array di colonne
|
|
63
|
-
*/function getcolonne(value,keepquote=!1){value=String(value||"");const pp=/^(\d+)\.\.(\d+)$/.exec(value);if(pp){let n1=parseInt(pp[1]),n2=parseInt(pp[2]);const cl=[];n1>n2&&([n1,n2]=[n2,n1]);for(let 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)))}
|
|
64
|
-
/**
|
|
65
|
-
* Analizza variabili in un'espressione usando delimitatori
|
|
66
|
-
* @param {string} ex - Espressione da analizzare
|
|
67
|
-
* @param {number} k0 - Posizione iniziale
|
|
68
|
-
* @param {string} inipar - Delimitatore iniziale ([, (, {)
|
|
69
|
-
* @param {string} endpar - Delimitatore finale (], ), })
|
|
70
|
-
* @param {boolean} [nonewline=false] - Se true, termina all'incontro di un newline
|
|
71
|
-
* @returns {{i: number, res: string[]}} Risultato dell'analisi con posizione finale e array risultati
|
|
72
|
-
*/const parsevar=(ex,k0,inipar,endpar,nonewline=!1)=>{const pars1=["[","(","{"],pars2=["]",")","}"];endpar||(endpar="["==inipar?"]":"("==inipar?")":"}");const mp=pars1.includes(inipar);let par=1,nres=0;const res=[];for(let 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(par--,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)}};
|
|
73
|
-
/**
|
|
74
|
-
* Classe per la gestione degli errori con funzionalità di accumulo e formattazione
|
|
75
|
-
*/
|
|
76
|
-
/**
|
|
77
|
-
* Copia le proprietà non-funzione da un oggetto sorgente a uno destinazione
|
|
78
|
-
* @param {Object} objDestinazione - Oggetto destinazione
|
|
79
|
-
* @param {Object} objSorgente - Oggetto sorgente
|
|
80
|
-
*/
|
|
81
|
-
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])}))}
|
|
82
|
-
/**
|
|
83
|
-
* Estrae le proprietà non-funzione da un oggetto, escludendo chiavi specificate
|
|
84
|
-
* @param {Object} obj - Oggetto da cui estrarre le proprietà
|
|
85
|
-
* @param {string[]} [exclude] - Array di chiavi da escludere
|
|
86
|
-
* @returns {Object} Nuovo oggetto con le proprietà estratte
|
|
87
|
-
*/function getOggetto(obj,exclude=[]){if(Array.isArray(obj))return obj.map((item=>getOggetto(item,exclude)));if(obj&&"object"==typeof obj){const result={};for(const[key,value]of Object.entries(obj))"function"==typeof value||exclude&&exclude.includes(key)||(result[key]=getOggetto(value,exclude));return result}return obj}
|
|
88
|
-
/**
|
|
89
|
-
* Converte una stringa in un oggetto JSON, gestendo errori e restituendo un valore di default se non valido
|
|
90
|
-
* @param {string|Array|Object} str - Stringa da convertire in JSON, array o oggetto da restituire direttamente
|
|
91
|
-
* @param {*} [def={}] - Valore di default da restituire in caso di errore di parsing
|
|
92
|
-
* @throws {Error} Non genera eccezioni, gli errori vengono loggati internamente
|
|
93
|
-
* @returns {*} L'oggetto JSON convertito dalla stringa, l'input originale se è un array/oggetto, o il valore di default in caso di errore
|
|
94
|
-
* @example
|
|
95
|
-
* fromjson('{"a": 1}') // returns {a: 1}
|
|
96
|
-
* fromjson([1,2,3]) // returns [1,2,3]
|
|
97
|
-
* fromjson('invalid json', {}) // returns {}
|
|
98
|
-
*/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()}
|
|
99
|
-
/**
|
|
100
|
-
* Azzera la lista degli errori
|
|
101
|
-
*/azzera(){this.err=[]}
|
|
102
|
-
/**
|
|
103
|
-
* Aggiunge un errore alla lista
|
|
104
|
-
* @param {string} msg - Messaggio di errore
|
|
105
|
-
* @param {Object} row - Informazioni aggiuntive sull'errore
|
|
106
|
-
*/add(msg,row){this.err.push({msg:msg,row:row})}
|
|
107
|
-
/**
|
|
108
|
-
* Restituisce la lista completa degli errori
|
|
109
|
-
* @returns {Array} Lista degli errori
|
|
110
|
-
*/get(){return this.err}
|
|
111
|
-
/**
|
|
112
|
-
* Restituisce il numero di errori presenti
|
|
113
|
-
* @returns {number} Numero di errori
|
|
114
|
-
*/get length(){return this.err.length}
|
|
115
|
-
/**
|
|
116
|
-
* Converte la lista degli errori in stringa
|
|
117
|
-
* @returns {string} Rappresentazione testuale degli errori
|
|
118
|
-
*/toString(){const cl=[];for(const e of this.err){const m="object"==typeof e.msg?JSON.stringify(e.msg):e.msg||"";cl.push(`${e.row?e.row+":":""}${m}`)}return cl.join("\n")}},toNum=(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};function getheaddims(dims){let res;try{res="object"==typeof dims&&dims?dims:JSON.parse(dims||"{}")}catch(error){res={}}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}function sortrows(rows){const k2=Object.keys(rows).sort(),out={};for(let i=0;i<k2.length;i++){const k=k2[i],kk=rows[k];i+1<k2.length&&k2[i+1].startsWith(k+".")?kk.hasliv=1:delete kk.hasliv,out[k]=kk}return out}const REGEX_PARENTESI=/(?<!\w)\(/g,REGEX_NUMERO=/^-?[0-9.]+$/,REGEX_FUNZIONE=/^(\w+)(!)?\[(.*)?\]$/,REGEX_DIGIT=/[0-9.]/,REGEX_OPERATOR=/[+\-*/^%]/,REGEX_ALPHA=/[a-zA-Z]/i;function valutaparentesi(expression){for(expression=(expression+"").trim();;){const tm=REGEX_PARENTESI.exec(expression);if(!tm)break;{const{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 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)};let operatorIndex=-1,op="";for(const operator in operators)if(operatorIndex=expression.indexOf(operator),operatorIndex>=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=function valutainsiemi(expression){if(expression.includes("[")){function resinisiemi(rr){const v1=rr[1],fl=!!rr[2],vv=getcolonne(rr[3]);for(const v of vv)if(v==v1)return fl?"0":"1";return fl?"1":"0"}for(;;){const rr=REGEX_FUNZIONE.exec(expression);if(!rr)break;{const tm=resinisiemi(rr);expression=expression.substring(0,rr.index)+tm+expression.substring(rr.index+rr[0].length)}}}return expression}(expression))}const mathFunctions={sqrt:x=>Math.sqrt(x),sqr:x=>Math.sqrt(x),pow:(x,y)=>Math.pow(x,y),int:x=>Math.floor(x),floor:(x,d=0)=>Math.floor((Number.parseFloat(x)||0)*10**d)/10**d,round:(x,d=0)=>Math.round((Number.parseFloat(x)||0)*10**d)/10**d,dec:(x,d=0)=>Math.floor((Number.parseFloat(x)||0)*10**d)/10**d,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),asin:x=>180*Math.asin(x)/Math.PI,acos:x=>180*Math.acos(x)/Math.PI,atan:x=>180*Math.atan(x)/Math.PI,atan2:(y,x)=>180*Math.atan2(y,x)/Math.PI,seeder:(x,seed)=>seeder(x,seed),log:x=>Math.log(x),log10:x=>Math.log10(x),min:(...args)=>Math.min(...args),max:(...args)=>Math.max(...args),clamp:(x,x1,x2)=>Math.max(x1,Math.min(x2,x)),rnd:(a,b)=>a?b?Math.floor(Math.random()*(b-a+1))+a:Math.floor(Math.random()*a):Math.random(),cas:(a,b)=>Math.floor(Math.random()*(b-a+1))+a};function muCalcbase(expression){let index=0;function parseOperator(){const op=expression[index];return REGEX_OPERATOR.test(op)?(index++,op):null}function parsePrimary(){if("+"===expression[index]||"-"===expression[index]){return("-"===expression[index++]?-1:1)*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(){const 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;let pars=[];for(;;){let tm=parseExpr();if(pars.push(tm),")"===expression[index]){index++;break}if(","!=expression[index])break;index++}return func(...pars)}}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()}
|
|
119
|
-
/**
|
|
120
|
-
* Valuta un'espressione matematica o logica e restituisce il risultato
|
|
121
|
-
* @param {string|number} expression - L'espressione da valutare
|
|
122
|
-
* @returns {number} Il risultato della valutazione dell'espressione
|
|
123
|
-
* @description
|
|
124
|
-
* Supporta operazioni matematiche di base, funzioni trigonometriche,
|
|
125
|
-
* operatori di confronto e operazioni logiche.
|
|
126
|
-
* Le funzioni supportate includono: sqrt, floor, abs, sin, cos, random, clamp, round
|
|
127
|
-
*/function muCalc(expression){if(!expression)return 0;if("number"==typeof expression)return expression||0;if("string"!=typeof expression)return 0;const s=expression.replaceAll(",",".");return REGEX_NUMERO.test(s)?Number(s)||0:valutaparentesi(expression)||0}function valutavar(sh,res){const vv=res[0]||"";if(!vv)return"";if(sh.counter>=100)return vv;const tmps1=valuta0(sh,vv);let vx;if(sh.stl[tmps1])vx=`-- R:${tmps1} --`;else{const tmps=sh.var(tmps1);if(isObject(tmps))return tmps;sh.stl[tmps1]=!0,vx=valutabase(sh,tmps),delete sh.stl[tmps1]}if(sh.counter>=100)return vv;if(res[1]){const cols=getcolonne(vx);if("l"==res[1])return String(cols.length);const col=muCalc(valuta0(sh,res[1]));if(!(col>=0&&col<cols.length))return"";vx=valuta0(sh,cols[col])}if(res[2]){const c1=muCalc(valuta0(sh,res[2]));if(c1){let 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){let vv=getcolonne(res||"");const 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":{const m1=valuta0(sh,vv[1]||""),m2=valuta0(sh,vv[2]||"");sh.add(m1,sh.var(m2))}break;case"ex":{const m1=valuta0(sh,vv[1]||"");let m2=valuta0(sh,vv[2]||"");m2||(m2=",");const m3=muCalc(valuta0(sh,vv[3]||"")),tm=m1.split(m2);return m3>0&&tm[m3-1]||""}case"ex2":{const sep=replacecharcode(vv[1]||""),pos=muCalc(valuta0(sh,vv[2]||""));vv.splice(0,3);return 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{let search=replacecharcode(vv[1]||"x");const replace=replacecharcode(vv[2]||"").trim();vv.splice(0,3),search=search.replace(/&(\d+)/g,((match,code)=>`\\u${parseInt(code).toString(16).padStart(4,"0")}`));return vv.join(";").replace(new RegExp(search,"im"),replace)}catch(error){return""}case"look":case"lookb":{const 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":{let pos=muCalc(valuta0(sh,vv[1]||""))||0;if(!pos){pos=muCalc(valuta0(sh,vv[2]||""));const sep=vv[1]||"";return pos?vv[3].split(sep)[pos-1]:""}return vv[pos>0?pos+1:2]||""}case"totab":return vv.splice(0,1),vv.join("\t");case"tosep":{const 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":{const str=valuta0(sh,vv[1]||""),pos=muCalc(valuta0(sh,vv[2]||"")),len=muCalc(valuta0(sh,vv[3]||""));return str.substring(pos-1,pos+len-1)}case"arrotonda":{const 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 muCalc(valuta0(sh,vv[1]))?vv[2]||1:vv[3]||0;case"instr":case"instr2a":{const str1=vv[1]||"",str2=vv[2]||"";return str1.toLowerCase().indexOf(str2.toLowerCase())+1}case"instr2":{const str2=vv[1]||"";return vv.splice(0,2),vv.join(";").toLowerCase().indexOf(str2.toLowerCase())+1}default:return r1.startsWith(".")?{fun:res,pars:[]}:{fun:r1,pars:vv}}}function valuta0(sh,ex){if(ex+="",sh.counter>=100)return ex;for(;;){const rt=/\$([{(])/im.exec(ex);if(!rt)break;{const i1=rt.index,{i:i,res:res}="("==rt[1]?parsevar(ex,i1+2,"(",")"):parsevar(ex,i1+2,"{","}"),tm=valutavar(sh,res);if(isObject(tm))return tm;ex=valuta0(sh,ex.substring(0,i1))+tm+(i>=0?valuta0(sh,ex.substring(i+1)):"")}}return ex=(ex=ex.replace(/\$([a-z|][\w|.]*)/gi,((match,m1)=>{let m2="";for(;m1.length;){let tm;if(sh.stl[m1]?tm=`--R: ${m1} --`:(sh.stl[m1]=!0,tm=valutabase(sh,sh.var(m1)),delete sh.stl[m1]),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;const cl=[];for(let i=+p1;i<=+p2;i+=p4)cl.push(i.toString());return cl.join(";")}))}function valutabase(sh,ex){return ex&&(sh.counter++,sh.counter<=100&&(ex=valuta0(sh,ex)),sh.counter--),ex}class Variabile{constructor(){this.stl={},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}
|
|
128
|
-
/**
|
|
129
|
-
* Salva lo stato corrente delle variabili nello stack
|
|
130
|
-
*/push(){this.vec.push({saves:[],dic:{...this.dictionary}})}
|
|
131
|
-
/**
|
|
132
|
-
* Ripristina l'ultimo stato salvato delle variabili
|
|
133
|
-
*/pop(){if(this.vec.length>0){let tm=this.vec.pop(),cl={};if(tm.saves&&tm.saves.length)for(let t of tm.saves)cl[t]=this.dictionary[t];if(this.dictionary=tm.dic,tm.saves&&tm.saves.length)for(let t of tm.saves)this.dictionary[t]=cl[t]}}savevars(str){if(!this.vec.length>0)return;let tm=this.vec[this.vec.length-1];tm.saves||(tm.saves=[]);let cl=str.split(",");for(let c of cl){const k=Variabile.sanitizeKey(c);k&&!tm.saves.includes(k)&&tm.saves.push(k)}}
|
|
134
|
-
/**
|
|
135
|
-
* Rimuove tutte le variabili e pulisce lo stack
|
|
136
|
-
*/clear(){this.vec=[],this.dictionary={}}azzera=()=>this.clear()
|
|
137
|
-
/**
|
|
138
|
-
* Recupera il valore di una variabile
|
|
139
|
-
*/;var(key){let fmt="";const pp=/^(\d+)\.\.(\d+)$/.exec(key);if(pp){let n1=parseInt(pp[1]),n2=parseInt(pp[2]);const cl=[];n1>n2&&([n1,n2]=[n2,n1]);for(let i=n1;i<=n2;i++)cl.push(i+"");return cl}if(key.indexOf("|")>=0){const tm=key.split("|");key=tm[0],fmt=tm[1]}function toformat(val,fmt){switch(fmt.trim().toLowerCase()){case"0":return String(parseInt(val)||0);case"-":return String((parseInt(val)||1)-1);case"+":return String((parseInt(val)||0)+1);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){let xx=Intl.NumberFormat("en",{style:"currency",currency:"EUR"}).format(n);return xx=xx.replace(/€/g,"").replace(/\./g,";").replace(/,/g,".").replace(/;/g,",")+"€",xx}return valorezero})(parseFloat(val));case"num":return toNum(parseFloat(val));case"n":case"n0":case"n1":case"n2":case"n3":case"n4":{const dec=parseInt(fmt.slice(1))||0;return toNum(parseFloat(val),dec)}case"u":return String(val).toUpperCase();case"l":return String(val).toLowerCase();default:return val}var date}const sanitizedKey=Variabile.sanitizeKey(key);if(sanitizedKey.startsWith(".")&&this.fndotcallback){const tm=this.fndotcallback(sanitizedKey.toLowerCase());if(tm)return toformat(tm,fmt)}if(Variabile.isValidKey(sanitizedKey)){const lowercaseKey=sanitizedKey.toLowerCase(),rr=/^([\w][\w\d]*)[.[]/.exec(lowercaseKey);if(rr){const tm=this.dictionary[rr[1]];if(tm&&"object"==typeof tm)return toformat(function objval(tm,key){const parts=key.split(".");let obj=tm;for(let i=0;i<parts.length;i++){const part=parts[i],match=part.match(/(.*?)\[(\d*)\]/);if(match){if(obj=obj[match[1]],void 0===obj)return"";obj=obj[parseInt(match[2],10)||0]}else switch(part){case"_k":obj=(Object.keys(obj)||[]).join(",");break;case"_v":obj=Object.values(obj)||[];break;case"_l":obj=obj.length||0;break;default: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}
|
|
140
|
-
/**
|
|
141
|
-
* Restituisce un dump delle variabili
|
|
142
|
-
*/dump(isstr=!1){let cl=[];for(const 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} = ${isObject(e.val)?JSON.stringify(e.val,null,2):e.val}`)):cl}
|
|
143
|
-
/**
|
|
144
|
-
* Aggiunge o rimuove una variabile
|
|
145
|
-
*/add(key,value){if("number"==typeof value&&(value=String(value)),key.includes("*")){const sanitizedKey=Variabile.sanitizeKey(key.split("*")[0]);if(Variabile.isValidKey(sanitizedKey)){const lowercaseKey=sanitizedKey.toLowerCase();let cl=Object.keys(this.dictionary).filter((e=>e.startsWith(lowercaseKey)));for(let c of cl)value?this.dictionary[c]=value:delete this.dictionary[c]}}else{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}`)}}removeallvars(exclude){if(Array.isArray(exclude)){let tm=Object.keys(this.dictionary);for(let t of tm)exclude.includes(t)||delete this.dictionary[t]}else this.dictionary={}}
|
|
146
|
-
/**
|
|
147
|
-
* Valuta un'espressione con supporto per callback asincroni
|
|
148
|
-
*/valutasync(str){return valutabase(this,str)}async valuta(ex,callback){this.stl={};let tm=await async function valutafunc(sh,ex,callback){if(ex){for(let ii=0;ii<20;ii++){const i1=ex.lastIndexOf("$[");if(!(i1>=0)){ex=valutabase(sh,ex);break}{const{i:i,res:res}=parsevar(ex,i1+2,"[","]"),t1=valutabase(sh,ex.substring(0,i1)),t2=res?res[0].startsWith(".")?valutabase(sh,res.join(":")):valutabase(sh,res[0]):"",t3=i>=0?valutabase(sh,ex.substring(i+1)):"";let t4=valutaquadra(sh,t2);if("object"==typeof t4&&(t4=callback?await callback(t4?.fun,t4.pars):`** fun: ${t4.fun} ** `),isObject(t4))return t4;ex=t1+t4+t3}}return ex}return""}(this,ex,callback);return isObject(tm)||(tm=(ex=>{for(;;){const i1=ex.indexOf("{");if(!(i1>=0))break;{const{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("string"!=typeof p)return{};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||"";const getcode0=async(codicebarra,liv)=>{let barra=this.barre[codicebarra];if(!barra&&callback&&(barra=await callback(codicebarra),barra||(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};const{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:""};let bx=barra.r;if(z){const 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){const t=bx.find((e=>e.x>=x));if(t)return{c:t.c,fm:t.x==x?0:1,x1:t.x,x:x,extra:extra}}else{let t=bx.find((e=>e.x==x&&e.y==y));if(t)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)),t))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)),t))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={});const barre={};if(Array.isArray(vettore)){for(const 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);const 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(const 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}}
|
|
149
|
-
/**
|
|
150
|
-
* Costanti e espressioni regolari utilizzate nel modulo
|
|
151
|
-
*/const keys="IFDEF|IFNDEF|SETDEF|CACHE|RET|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){const t0=muClComments(str),t2=[];for(const row of t0){const t1=row.includes("(")||row.includes("[")?[row]:getcolonne(row,!0);let fl=!1;for(const t of t1)!t.startsWith('"')&&t.includes("=")?(t2.push(t),fl=!0):fl&&(t2[t2.length-1]+=","+t)}const pars={};for(const x of t2){let{v:v,o:o}=getcouple(x,"=",!1);o=o||"",v&&(/^[-+]?\d*\.?\d+$/.test(o)&&(o=parseFloat(o)),pars[v]=o)}return pars}
|
|
152
|
-
/**
|
|
153
|
-
* Rimuove i commenti dal codice sorgente mantenendo la struttura del codice
|
|
154
|
-
* @param {string} codice - Il codice sorgente da processare
|
|
155
|
-
* @param {boolean} tienivuoti - Se true mantiene le righe vuote
|
|
156
|
-
* @returns {string[]} Array di righe di codice senza commenti
|
|
157
|
-
*/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;if(/(^|[^:])\/\/.*/.test(rigaTrim)&&(rigaTrim=rigaTrim.replace(/(^|[^:])\/\/.*/,((match,p1)=>p1.trim()))),rigaTrim=rigaTrim.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}
|
|
158
|
-
/**
|
|
159
|
-
* Analizza e organizza il codice in una struttura dati gerarchica
|
|
160
|
-
* @param {string[]} tt - Array di righe di codice da analizzare
|
|
161
|
-
* @param {boolean} acapo - Se true mantiene i ritorni a capo nel contenuto
|
|
162
|
-
* @returns {Object[]} Array di oggetti rappresentanti la struttura del codice
|
|
163
|
-
* @throws {Error} Se tt non è un array
|
|
164
|
-
*/function muClean(tt,acapo=!1){if(!Array.isArray(tt))return void errori.add("muClean: expected array!");const tm=[];
|
|
165
|
-
/**
|
|
166
|
-
* Aggiunge una riga generica alla struttura
|
|
167
|
-
* @param {string} r - Riga da aggiungere
|
|
168
|
-
*/function addgen(r){if(tm.length>0&&""==tm[tm.length-1].tipo){const 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})}for(const rigaTrim of tt){const matchComando=rigaTrim.match(/^#([\w.]+)\s*(.*)$/);if(matchComando){let tipo=matchComando[1].toUpperCase().trim(),tipo2="";if(tipo.includes(".")){const 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("#")){const tmx={tipo:tipo,contenuto:matchComando[2]};tipo2&&(tmx.tipo2=tipo2),tm.push(tmx)}else{let 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*(.*)$/),matchInline?(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)}let nn=0,nf=0,ns=0,lev=[],lef=[],les=[];for(let i=0;i<tm.length;i++){const t=tm[i];switch(t.i=i,t.tipo){case"FOR":case"FORVAR":case"VARIANTE":case"DO":nf++,lef[nf]={pos:i,bk:[]};break;case"LOOP":case"ENDFOR":if(nf>0){const{pos:pos}=lef[nf];for(const 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":nn++,lev[nn]={pos:i,bk:[t]};break;case"SELECT":ns++,les[ns]={pos:i,bk:[t],first:i};break;case"ELSEIF":case"ELSEIFDEF":case"ELSEIFNDEF":case"ELSE":if(nn>0){const{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){const{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){const{pos:pos,next:next}=lev[nn];tm[pos].next=i;for(const b of lev[nn].bk)b.last=i;nn--}break;case"ENDSELECT":if(ns>0){const{pos:pos,next:next}=les[ns];tm[pos].next=i;for(const b of les[ns].bk)b.last=i;ns--}}}return tm}
|
|
169
|
-
/**
|
|
170
|
-
* Analizza e processa i limiti definiti nel codice
|
|
171
|
-
* @param {string} dati - Dati contenenti le definizioni dei limiti
|
|
172
|
-
* @returns {Object[]} Array di oggetti rappresentanti i limiti processati
|
|
173
|
-
*/function muLimits(dati){const rr=muClComments(dati),tm=[];let tk;const parsa=v=>v?[...new Set(v.split(",").map((e=>e.trim())).sort().filter((e=>e)))]:void 0;for(const r of rr){let 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),m))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(const 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;const{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(const 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){const rs={},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(const d of data)addres0(key,d);else addres0(key,data)}for(const v of vec){const tm=rx1.exec(v);if(tm)switch(tm[1]){case"var":case"v":case"variante":{const i=(tm[2]||"").indexOf(" ");if(i>0){const 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));tv||(tv={v:v1,o:[]},rs.v.push(tv));for(const o of v2)tv.o.includes(o)||tv.o.push(o)}}}break;case"d":case"dt":case"data":case"date":{const 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(const ll of limvec){const 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}
|
|
174
|
-
/**
|
|
175
|
-
* Classe per gestire le varianti di un prodotto.
|
|
176
|
-
* Permette di caricare, manipolare e convertire varianti di prodotto con relativi attributi e limiti.
|
|
177
|
-
* @class
|
|
178
|
-
* @exports
|
|
179
|
-
*/class Variante{
|
|
180
|
-
/**
|
|
181
|
-
* Crea una nuova istanza di Variante
|
|
182
|
-
* @param {Object} amb - Ambiente di esecuzione contenente il contesto applicativo
|
|
183
|
-
*/
|
|
184
|
-
constructor(amb){this.rows={},this.name="$",this.key="$",this.limits=void 0,
|
|
185
|
-
/** @type {Ambiente} */
|
|
186
|
-
this.amb=amb}
|
|
187
|
-
/**
|
|
188
|
-
* Imposta i dati principali della variante
|
|
189
|
-
* @param {string} id - Identificativo univoco della variante
|
|
190
|
-
* @param {string} cat - Categoria di appartenenza
|
|
191
|
-
* @returns {Object} Oggetto contenente nome e categoria normalizzati
|
|
192
|
-
*/setheader(id,_cat){const{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}}
|
|
193
|
-
/**
|
|
194
|
-
* Cerca la riga con dimensione più vicina a quella richiesta
|
|
195
|
-
* @param {number|string} dim - Dimensione target da cercare
|
|
196
|
-
* @param {number} colonna - Indice della colonna (1-based) contenente la dimensione
|
|
197
|
-
* @returns {string} Riga formattata nel formato CSV
|
|
198
|
-
*/fromdim(dim,colonna=2){"number"!=typeof dim&&(dim=muCalc(dim)),colonna>0&&colonna--;let rsel,max=1e9;for(const kk in this.rows){const row=this.rows[kk];if(!row.annulla){const dd=parseFloat(row.v[colonna])||0;dd<=max&&dd>=dim&&(max=dd,rsel=row)}}return this.#torow(dim,rsel)}
|
|
199
|
-
/**
|
|
200
|
-
* Carica una variante dal database o da file
|
|
201
|
-
* @param {string} id - Identificativo della variante
|
|
202
|
-
* @param {string} cat - Categoria della variante
|
|
203
|
-
* @param {boolean} nofilter - Se true, non carica i filtri associati
|
|
204
|
-
* @returns {Promise<boolean>} Promise che risolve a true se il caricamento ha successo
|
|
205
|
-
*/async load(id,_cat,nofilter=!1){const{name:name,cat:cat}=this.setheader(id,_cat);if(cbGetVariante){const content=await cbGetVariante(cat,name);if(content){if(await this.loadContentExtended(content),content.filter)this.limits=parselimitifromdb(content.filter);else if(cbInfo&&!nofilter){const tm=await cbInfo("filter",cat,name);tm&&tm.length&&(this.limits=parselimitifromdb(tm))}return!0}}return!1}
|
|
206
|
-
/**
|
|
207
|
-
* Carica il contenuto della variante da array di stringhe
|
|
208
|
-
* @private
|
|
209
|
-
* @param {string[]} lines - Array di stringhe contenenti la definizione della variante
|
|
210
|
-
* @returns {Promise<boolean>} Promise che risolve a true se il caricamento ha successo
|
|
211
|
-
*/async _loadContent(lines){const regx=/^\s*[!:]\s*(\w+)\s*(.*)$/i;let ky="";const limits=[];let limit,modelimit=!1;for(const currentLine of lines){const tm=currentLine.toLowerCase();if("{limit}"==tm)limit=[],limits.push(limit),modelimit=!0;else if("{:limit}"==tm)modelimit=!1;else if(modelimit)limit.push(currentLine);else{let rr=regx.exec(clean(currentLine));if(rr)if(ky&&"extra"==rr[1].toLowerCase()){const tm=getcolonne(rr[2]);for(const t of tm){const q=t.indexOf("=");if(q>0){const a=clean(t.substring(0,q));"v"!=a&&(this.rows[ky][a]=t.substring(q+1).trim())}}}else switch(rr[1].toLowerCase()){case"alias":{const vv=rr[2].toLowerCase().split(";");if(vv[0].trim()!=this.name)if(1==vv.length)this.alias=vv[0];else{let vx;if(this.amb?vx=await this.amb.getvariante(vv[0]):(vx=new Variante,await vx.load(vv[0],this.cat)),rr=vx?.rows,rr){let kky=Object.keys(rr);if(kky.length){vv.splice(0,1);const addrows=kk=>{kk&&kk.forEach((k=>this.rows[k]=rr[k]))};for(const t of vv){const rx=/([ei])\s*:\s*(.*)\s*$/im.exec(t);if(rx){const k3=rx[2].split(",");for(let i=0;i<k3.length;i++)k3[i]=k3[i].trim();kky="e"==rx[1]?kky.filter((k=>{for(const k2 of k3)if(k.startsWith(k2))return!1;return!0})):kky.filter((k=>{for(const 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":{const 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{const tm=getcolonne(currentLine),k=clean(tm[0]);k&&(ky=k,this.rows[ky]={annulla:0,v:tm})}}}const kk=Object.keys(this.rows);for(const k of kk)if(k.includes(".")){const vv=k.split(".");for(let i=0;i<vv.length-1;i++){const k1=vv.slice(0,i+1).join(".");this.rows[k1]||(this.rows[k1]={annulla:0,v:[k1]})}}return this.limits=parselimitifromrule(limits),!0}
|
|
212
|
-
/**
|
|
213
|
-
* Converte la variante in un vettore di righe
|
|
214
|
-
* @returns {string[]} Array di righe formattate
|
|
215
|
-
*/tovec(){const tm=this.rows,cl=[],xx=Object.keys(tm).sort();for(const x of xx)this.rows[x].annulla<2&&cl.push(this.#torow(x,this.rows[x]));return cl}
|
|
216
|
-
/**
|
|
217
|
-
* Converte una riga in una stringa CSV
|
|
218
|
-
* @private
|
|
219
|
-
* @param {string} cod - Codice della riga
|
|
220
|
-
* @param {Object} tm - Oggetto contenente i dati della riga
|
|
221
|
-
* @returns {string} Stringa CSV formattata
|
|
222
|
-
*/#torow(cod,tm){const cl=[cod];if(tm)for(const t of tm.v)"string"==typeof t&&(t.includes(",")||t.includes(";"))?cl.push(quote(t)):cl.push(t||"");return cl.join(",")}
|
|
223
|
-
/**
|
|
224
|
-
* Converte un codice nella sua rappresentazione CSV
|
|
225
|
-
* @param {string} cod - Codice da convertire
|
|
226
|
-
* @returns {string} Stringa CSV o codice originale se non trovato
|
|
227
|
-
*/tovar(cod,vcod=""){const c1=clean(cod);if(!this.rows[c1])return vcod||cod;const tm=this.rows[c1];return 2==tm.annulla?"":this.#torow(vcod||cod,tm)}
|
|
228
|
-
/**
|
|
229
|
-
* Verifica se un'opzione è valida
|
|
230
|
-
* @param {string} opz - Opzione da verificare
|
|
231
|
-
* @returns {boolean} True se l'opzione è valida
|
|
232
|
-
*/isvalidopz(opz){const c1=clean(opz),t=this.rows[c1];return!!t&&(1!=t.annulla&&!t.hasliv)}
|
|
233
|
-
/**
|
|
234
|
-
* Trova la prima opzione valida tra quelle disponibili
|
|
235
|
-
* @param {string} opz - Opzione da controllare per prima
|
|
236
|
-
* @returns {string|undefined} Prima opzione valida trovata o undefined
|
|
237
|
-
*/firstvalid(opz,defs=void 0){const i=opz.indexOf(",");if(i>0&&(opz=opz.slice(0,i).trim()),opz&&this.isvalidopz(opz))return opz;if(defs&&defs.length)for(const o of defs)if(this.isvalidopz(o))return o;if(this.vdef&&this.vdef.length)for(const o of this.vdef)if(this.isvalidopz(o))return o;const tm=Object.keys(this.rows).sort();for(let i=0;i<tm.length;i++){const x=tm[i];if(!(i<tm.length-1&&tm[i+1].startsWith(x+"."))&&this.isvalidopz(x))return x}}
|
|
238
|
-
/**
|
|
239
|
-
* Resetta tutti i filtri applicati alla variante
|
|
240
|
-
*/resetfilter(){delete this._valids;for(const x in this.rows)this.rows[x].annulla=0}
|
|
241
|
-
/**
|
|
242
|
-
* Restituisce le chiavi valide ordinate alfabeticamente
|
|
243
|
-
* @returns {string[]} Array di chiavi valide
|
|
244
|
-
*/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());const tm=[];for(const f of filtra){const rr=/^#([iex])(\d*)\s+(.+)$/i.exec(f);if(rr){const t={ex:rr[1],col:(parseInt(rr[2])||1)-1,val:"x"==rr[1]?rr[3]:getcolonne(rr[3])};t.val.length&&tm.push(t)}}if(tm.length)for(const x in this.rows){const r=this.rows[x];for(const t of tm)if("e"==t.ex){if(_check((r.v[t.col]+"").toLowerCase(),t.val)){r.annulla=1;break}}else if("x"==t.ex){const vt=(r.v[t.col]+"").toLowerCase().split(/[,;]/).map((e=>e.trim()));if(!_check((t.val+"").toLowerCase(),vt)){r.annulla=1;break}}else if(!_check((r.v[t.col]+"").toLowerCase(),t.val)){r.annulla=1;break}}function _check(value,valori){return!!valori.find((e=>e.startsWith(value)))}}
|
|
245
|
-
/**
|
|
246
|
-
* Applica i limiti configurati alle opzioni della variante
|
|
247
|
-
* @returns {Array|void} Array di limiti applicati o void se reset
|
|
248
|
-
*/limita(filtra){if(filtra&&filtra.length)return this.limitfiltra(filtra);if(!this.limits||!this.amb)return this.resetfilter();const{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(const v of e.v){const 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();const incstar=new Set,exstar=new Set,incaltri=new Set,exaltri=new Set;let isinc=!1,isex=!1;for(const 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(const x in this.rows){const r=this.rows[x];let flinc=!1,flex=!1;if(isinc){for(const i of incstar)if(x.startsWith(i)){flinc=!0;break}!flinc&&incaltri.has(x)&&(flinc=!0)}if(isex){for(const 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}
|
|
249
|
-
/**
|
|
250
|
-
* Carica il contenuto esteso della variante
|
|
251
|
-
* @param {Object|string} content - Contenuto da caricare, può essere un oggetto o una stringa
|
|
252
|
-
* @returns {Promise<void>} Promise che si risolve al completamento del caricamento
|
|
253
|
-
*/async loadContentExtended(content){if("object"==typeof content){for(const 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}}}const _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 isObject(a)||(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)=>{switch(fun){case"dim":{let 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}case"seed":{let n1=pars[1],cl=getcolonne(pars[2]);return cl[seeder(cl.length,n1)]||""}case"seedvar":{let vv=await dammivariante(amb,mac,pars[2]),n1=pars[1],cl=vv.validkeys();if(pars[3]&&pars[4]){let idcol=muCalc(pars[3])-1;if(idcol>=0){let pcol=getcolonne(pars[4]);cl=cl.filter((e=>{let t=vv.rows[e];if(t&&t.v&&t.v[idcol]){let v=getcolonne(t.v[idcol]);if(v)for(let p of pcol)if(v.includes(p))return!0}return!1}))}}let id=seeder(cl.length,n1);return id>=0&&vv.tovar(cl[id])||""}default:return await getcbfunc(`**fun:${fun}**`,fun,pars,amb.vari,amb)}}))}async function dammivariante(amb,macro,ky){let tm;return tm=macro&¯o?.localvar&¯o.localvar[ky]?macro.localvar[ky]:await amb.getvariante(ky),tm}async function impostavariante(amb,macro,a,b,head){let tm,ky=a;if((b=b||"")&&"string"==typeof b){const k=b.indexOf(":");k>=0&&(k>0&&(ky=clean(b.slice(0,k))),b=b.slice(k+1))}
|
|
254
|
-
/** @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){let col=2;if(b.includes(":")){const xx=b.split(":");col=parseInt(xx[1]),b=xx[0]}tm.limita(x8),b=tm.fromdim(parseFloat(b),col)}else{tm.limita(x8);const b1=tm.firstvalid(b,getcolonne(head.def));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){const fatti={},vals=[];if(parsfunzione)for(const x of parsfunzione){const{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(const x of parsinit){const{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}function poppars(amb,tm){if(tm)for(const x of tm)amb.vari.add(x.v,x.o)}const outpush=(output,a)=>{null!=a&&null!=a&&("object"==typeof a?output.push(JSON.stringify(a,null,2)):"string"==typeof a&&a.startsWith("_ ")&&output.length>0&&"string"==typeof output[output.length-1]?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");const vari=amb.vari;amb.maxdelays,amb.cat;const output=[];let macro,pars,xid;tk();for(let ii=0;ii<codice.length;){let riga=codice[ii];switch(riga.tipo){case"IFDEF":case"IFNDEF":case"IF":{const 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{let vv,tm=1;const _getvv=async()=>{let vv=await intvaluta(amb,mac,riga.contenuto);return vv=vv.includes(":")&&!vv.includes(",")?vv.split(":").map((e=>(e||"").trim())):getcolonne(vv),vv};if("CASE"==riga.tipo){tm=0,vv=await _getvv();const tmx=muCalc(riga.t1||"");vv.find((v=>muCalc(v)==tmx))&&(tm=1)}else if("CASES"==riga.tipo){tm=0,vv=await _getvv();const 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{const 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"INC":case"I":if(options._stackmacro>500)errori.add("stack chiamate macro troppo profondo!",riga);else if(({macro:macro,pars:pars,xid:xid}=await amb.getmacro(riga)||{}),macro){options._inc=!0,options._stackmacro++;const saved={},parametri=macro.parametri?._;if(parametri&¶metri.length)for(const x of parametri){const x1=clean(x.split("=")[0]||"",!0);x1&&(saved[x1]=vari.dictionary[x1])}await macro.impostaparametri(parametri,pars);const rs1=await muEval(amb,macro,macro.codice,options);for(const v in saved)saved[v]?vari.dictionary[v]=saved[v]:delete vari.dictionary[v];output.push(...rs1),options._stackmacro--,options._inc=!1}break;case"RET":{const a=await intvaluta(amb,mac,riga.contenuto);amb.vari.savevars(a)}break;case"MACRO":case"M":case"FUNC":case"F":if(options._stackmacro>500)errori.add("stack chiamate macro troppo profondo!",riga);else{let{macro:macro,pars:pars,xid:xid}=await amb.getmacro(riga)||{};if(macro){const ismacro=!!options.grafica||["F","FUNC"].includes(riga.tipo),optid=options.id||"",parametri=macro.parametri?._,saved={};if(ismacro)vari.push();else{if(macro.head)for(const x of macro.head)saved[x.cod]=amb.vari.var(x.cod);if(parametri&¶metri.length)for(const x of parametri){const 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(4)),f.startsWith("#")?options.id=f: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 tm=amb.pick.key;amb.pick.key=options.id;const out=await options.grafica({tipo:riga.tipo,id:xid,pars:pars,parametri:parametri,macro:macro,options:options,vari:amb.vari,amb:amb});amb.pick.key=tm,output.push(out)}else{await macro.impostaparametri(parametri,pars);let tm=amb.vari.var("_rootnode");amb.vari.add("_rootnode","0");const rs1=await muEval(amb,macro,macro.codice,options);amb.vari.add("_rootnode",tm),output.push(...rs1)}options._stackmacro--}if(ismacro)vari.pop();else for(const 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"SETDEF":{let cl=getcolonne(riga.contenuto.toLowerCase()),tm=await dammivariante(amb,macro,cl[0]),prf=cl[1]||"def_",filtra=cl[2];if(prf.endsWith("_")||(prf+="_"),tm&&tm.rows){cl=Object.keys(tm.rows),filtra&&(cl=cl.filter((e=>e.startsWith(filtra))));for(let c of cl){let ky=`${prf}${c}`;if(!vari.dictionary[ky]){function torow(tm){const cl=[];if(tm)for(const t of tm.v.slice(1))"string"==typeof t&&(t.includes(",")||t.includes(";"))?cl.push(quote(t)):cl.push(t||"");return cl.join(",")}vari.add(ky,await intvaluta(amb,mac,torow(tm.rows[c])))}}}}break;case"LET":case"LETS":{let i=riga.contenuto.indexOf("="),j=-1;if(i>=0&&(j=riga.contenuto.indexOf("=",i+1)),j<0){const v=riga.contenuto;if(i=v.indexOf("="),i>0){const a=await intvaluta(amb,mac,v.slice(0,i).trim());let 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{const vv=getcolonne(riga.contenuto);for(const v of vv)if(i=v.indexOf("="),i>0){const a=await intvaluta(amb,mac,v.slice(0,i));let 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":{const i=riga.contenuto.indexOf("=");if(i>0){const a=await intvaluta(amb,mac,riga.contenuto.slice(0,i).trim()),b=await intvaluta(amb,mac,riga.contenuto.slice(i+1).trim());vari.add(a,b)}}break;case"LOOK":case"LOOKB":{const 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){const rr=Object.values(ww.rows).reduce(((t,e)=>{const 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":{const tm=getcolonne(riga.contenuto);if(tm)for(const x of tm){let{v:v,o:o,fl:fl}=getcouple(x);if(fl){v=await vari.valuta(v),o=await intvaluta(amb,mac,o);const 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":{const valido=(riga.contenuto||"").trim();let fl=!0;valido&&!muCalc(await intvaluta(amb,mac,valido))&&(fl=!1),riga.next&&(fl||(ii=riga.next+1))}break;case"VARIANTE":case"FORVAR":case"FOR":{let vv,valido,elenco,v;if(options.oldstyle?(vv=riga.contenuto.split(","),v=vv[2]||"i",elenco=vv[0],valido=vv[1]):(vv=getcolonne(riga.contenuto||""),v=vv[0]||"",elenco=clean(vv[1],!0),valido=vv[2]||""),v=v.includes("$")?await intvaluta(amb,mac,v):v||"","FORVAR"==riga.tipo||"VARIANTE"==riga.tipo){const tm=await intvaluta(amb,mac,elenco),xx=tm?await dammivariante(amb,mac,tm):void 0;xx?elenco=xx.tovec():(elenco=[],errori.add("getvariante not found!",riga))}else{const txx=await intvaluta(amb,mac,elenco||"");elenco=elenco?getcolonne(txx):void 0}elenco=elenco||[];const nc=0;if(riga.next){codice[riga.next].for={v:v,elenco:elenco,nc:nc,valido:valido};let 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":{let 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){const{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":{const 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);let a="";const rr=/^!(.\w+)[\s;,]\s*(.+)?$/gim.exec(tm);if(rr)if(rr[1].startsWith("."))await getcbfunc(tm,tm.slice(1),[],vari,amb),a="";else{const 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){const output={counter:0,keys:{},isTestmode:isTestmode};if(genera){if(!macro.genera[genera])return!1;await muGenerate_0(macro,amb,genera,callback,output)}else for(const gg in macro.genera)await muGenerate_0(macro,amb,gg,callback,output);return!0}}async function muGenerate_0(mac,amb,genera,callback,output){const xgen=mac.genera[genera];if(xgen){output.counter2=0;const working_variant={};async function processavariante(liv){if(output.isTestmode&&output.counter>output.isTestmode)return;if(liv<xgen.vars.length){const xx=xgen.vars[liv];if(!working_variant[xx]){const xvar=await dammivariante(amb,mac,xx),keys=xvar?Object.keys(xvar.rows):void 0;if(keys&&keys.length>0){for(const k of keys)amb.vari.add(xvar.name,xvar.tovar(k)),working_variant[xx]=!0,await processavariante(liv+1),working_variant[xx]=!1;return}logga("manca la variante",xx)}}for(const x of xgen.calcola)mac.formula[x]&&await muEval(amb,mac,mac.formula[x],{limited:!0});for(const x of xgen.exclude)if(mac.formula[x]){const vvv=await muEval(amb,mac,mac.formula[x],{limited:!0});if(vvv)for(const v of vvv){if(muCalc(v))return}}const out1=await muEval(amb,mac,xgen.codice,{limited:!0,localvar:mac.localvar}),bb={};for(const x of xgen.bom)if(mac.formula[x]){let vvv=await muEval(amb,mac,mac.formula[x],{limited:!0});vvv=vvv.join("\n").split("\n");for(const v of vvv)if(v){const tm=getcolonne(v);bb[x]||(bb[x]=[]);const t={};for(let 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){let fl=!0;for(const x of out1){const tm=getcolonne(x);if(tm[0]&&!output[tm[0]]){output[tm[0]]=1,output.counter++,output.counter2++;const o={__id:output.counter};for(let i=0;i<tm.length;i++){let key=xgen.head[i]?xgen.head[i]:`c${i}`;"#"==key[0]?(key=key.substr(1),o[key]=Math.round(1e3*muCalc(tm[i]))/1e3):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){const vv=str.split("\n");for(const v of vv)if(v.trim()){if(muCalc(vari.valutasync(v)))return!0}return!1}class Macro{constructor(amb,_name){const{name:name,cat:cat}=checkmu(_name,amb.cat||"");this.name=name,this.cat=cat,
|
|
255
|
-
/** @type {Ambiente} */
|
|
256
|
-
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(){const cl=[];return this.errori.forEach((e=>cl.push({e:e}))),cl}getparametri(op={}){const{noderiva:noderiva}=op,s={};if(this.dims&&DIMS.forEach((k=>{const t=muCalc(this.amb.vari.var(k));t&&(s[k]=String(t))})),this.head){for(const x of this.head)if(!x._h){if(noderiva&&x._d&&x._d.cod)continue;let 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(const x of this.parametri._){const x1=(x.split("=")[0]||"").trim().toLowerCase();let tm=this.amb.vari.var[x1];tm=(tm||"").split(",")[0],s[x1]=tm}return s}async setparametri(pars){const ff={},ruleset=this.amb.ruleset||{};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)}));for(const x of this.head){const tm=ruleset[x.cod];tm&&(tm.islock?(x.visible="0",pars[x.cod]=tm.opz,x._islock=!0):pars[x.cod]||(pars[x.cod]=tm.opz)),"g"!=x.t&&("z"!=x.t||pars[x.cod]||(pars[x.cod]="1"),x._v=pars[x.cod]||"",ff[x.cod]=!0)}for(const 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,pars),this.getparametri()}async setparametro(name,value,propaga=!1,pars={}){if(value&&"string"==typeof value&&value.includes("$")&&(value=await intvaluta(this.amb,this,value)),pars||(pars={}),this.head){const _imposta=async(riga,vv,id,propaga)=>{const nn=riga?.cod;if(riga.valid&&!riga._h1){const 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++){const 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){const 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++){const 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)||"";"thlm".includes(riga.t)&&"string"==typeof tx&&(tx=tx.split(",")[0]);let txold=tx;if("z"!=riga.t||tx||(this.amb.vari.add(nn,"1"),tx="1"),"m"==riga.t&&riga.spars){const 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)}const tmimposta=await impostavariante(this.amb,this,nn,vv||riga._v||tx,riga);if(riga._v=void 0,tx=this.amb.vari.var(nn)||"","thl".includes(riga.t)&&"string"==typeof tx&&(tx=tx.split(",")[0],this.amb&&this.amb.deriva&&this.amb.deriva.length>0)){const t2=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==tx))))));t2.length&&t2.forEach((e=>{let t=this.head.find((h=>h.cod==e.tocod));if(t){let t1=this.amb.vari.var(t.cod);pars&&pars[t.cod]&&(t1=pars[t.cod]),"string"==typeof t1&&(t1=t1.split(",")[0],t1&&t1!=txold&&t1!=tx?delete t._d:(t._v=e.toopz||tx,t._d={cod:riga.cod,opz:e.toopz}))}}))}return tmimposta}};let tm,i0=-1;if("#dim"==name)propaga=1;else{if(i0=this.head.findIndex((e=>e.cod===name)),i0<0)return;const hh=this.head[i0];tm=await _imposta(hh,value,i0),propaga&&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)}isderivato(hd){return"string"==typeof hd&&(hd=this.head.find((e=>e.cod==hd))),!!(hd&&hd._d&&hd._d.cod)}async impostaparametri(parimposta,parcall,ismacro=!1,progettokeys){if(this.head){this.paralias||(this.paralias={}),Array.isArray(this.head)||(this.head=[]);for(const i of this.head)i._v="",delete i._h,delete i._h1,delete i._h2,i.alias&&(this.paralias[i.cod]=i.alias)}progettokeys||(progettokeys={}),parimposta||(parimposta=[]),parcall||(parcall=[]);for(const x of[...parimposta,...parcall]){const i=x.indexOf("=");if(i>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(const 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,progettokeys[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(const x in this.localvar){const vv=new Variante;setOggetto(vv,this.localvar[x]),this.localvar[x]=vv}}async load(xname,xcat){let name,cat;try{let tm;if(({name:name,cat:cat}=checkmu(xname||this.name,xcat||this.cat||"")),this.name||(this.name=name),this.cat||(this.cat=cat),this.azzera(),cbGetMacro&&(tm=await cbGetMacro(cat,name),"string"==typeof tm&&(tm.startsWith("{")||tm.startsWith("["))&&(tm=fromjson(tm)),tm&&tm.head&&!Array.isArray(tm.head)&&(tm.head=[]),this.amb.checkscripts(tm.linkscript),delete tm.linkscript,tm.head&&(tm.dims=getheaddims(tm.dims))),tm){if("string"==typeof tm)await this.parsedata(tm);else for(const 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){let res;const{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){let res;const{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(let i=1;i<pp.length;i++)res=res.replaceAll(`$${i}`,pp[i]);let tm=muClComments(res);const t2=[];flin&&(tm=tm.filter((t=>!/^\{(:?(var|valid|formula|header|genera|v|f|h))[\s|}]/im.test(t))));for(const 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){const pp=getcolonne(r1[1]);if(!stak.includes(pp[0])){stak.push(pp[0]);const 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;const t2=[];let tm=muClComments(res),flin=!1;const lochead=[];for(const 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){const 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;let out=this.codice;for(const 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":{let r2=/^\s*\{(genera|g)\s+(.+)?\}/im.exec(t);if(r2){const name=checkname(getcolonne(r2[2])[0]);this.genera[name]=[],out=this.genera[name]}else out=this.errori,out.push(t)}break;case"valid":out=this.valid;break;case"var":case"v":{const r2=/^\s*\{(var|v)\s+(.+)?\}/im.exec(t);if(r2){const 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,out.push(t)}break;case"formula":case"f":{const r2=/^\s*\{(formula|f)\s+(.+)?\}/im.exec(t);if(r2){const name=checkname(r2[2]);this.formula[name]=[],out=this.formula[name]}else out=this.errori,out.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)}this.parametri={},this.codice=this.cleanfiltraparametri("_",this.codice,acapo);for(const f in this.formula)this.formula[f]=this.cleanfiltraparametri(f,this.formula[f],acapo);for(const f in this.localvar){const vv=new Variante,v=this.localvar[f];vv.setheader(f,this.cat),vv.rows={};for(const x of v.rows){const c=getcolonne(x),k=c[0].trim().toLowerCase();vv.rows[k]={annulla:0,v:c}}v.des&&(vv.des=v.des),this.localvar[f]=vv}tm=this.valid,this.valid=[];for(const t of tm){let p=getcouple(t,",");p={v:p.v,msg:p.o},p.v&&(p.v.startsWith("#")?this.formula[p.v.substring(1)]&&this.valid.push(p):this.valid.push(p))}tm=lochead;const head=[];for(const t of tm){const rr=/^\s*([\w\-_]+)+[;,\s]\s*(.*)?$/im.exec(t);if(rr){const pp=getcolonne(rr[2]),c=clean(rr[1]);let ht;if(c){ht=head.find((e=>e.cod==c)),ht||(ht={cod:c,t:"t"},head.push(ht));for(const tp of pp){const p=getcouple(tp);switch(p.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;const genera={};for(const kk in tm)if(Array.isArray(tm[kk])){const gen={codice:[],head:"",calcola:[],bom:[],vars:[],exclude:[]},regx=/^\s*[!:]\s*(\w+)\s*(.*)$/i;for(const k2 of tm[kk]){const rr=regx.exec(clean(k2));if(rr)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){let fl=!1;const getparalias=dati=>{const cl=[],co=getcolonne(dati);for(const c of co)if(c.includes(":")){const v=c.split(":");this.paralias[v[0]]=v[1],cl.push(v[0])}else cl.push(c);return cl};for(let i=0;i<codice.length;i++){const rr=/^:p[;,\s]+(.*)?$/im.exec(codice[i]);if(rr)codice[i]=null,fl=!0,this.parametri[key]=getparalias(rr[1]);else{const 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){let fl=!1;const tk=[];for(;;){const m=/\$([{[(])/m.exec(text);if(!m){text&&fl&&tk.push({class:"",text:text});break}{fl=!0;const classe="["==m[1]?"inline":"variabile";m.index>0&&tk.push({class:"",text:text.substring(0,m.index)});const{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");let fl=!1;const tk=[];for(;;){const 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}}
|
|
257
|
-
/**
|
|
258
|
-
* Analizza il codice sorgente e restituisce un array di token con classi CSS
|
|
259
|
-
* @param {string} tt - Il codice sorgente da analizzare
|
|
260
|
-
* @param {boolean} isvar - Flag che indica se analizzare come variabile
|
|
261
|
-
* @returns {Array<{class: string, text: string}>} Array di token con classi CSS
|
|
262
|
-
*/function muParsecode(tt,isvar){tt||(tt=" "),tt.endsWith("\n")&&(tt+=" ");const tm=[{class:"",text:tt}];for(let i=0;i<tm.length;i++)if(!tm[i].class){{const{fl:fl,tk:tk}=parseexp(tm[i].text,/(\/\*[^]+?\*\/)/im,(m=>[{class:"comment",text:m[1]}]));fl&&tm.splice(i,1,...tk)}if(!tm[i].class){{const{fl:fl,tk:tk}=parseexp(tm[i].text,/(\/\/.*)$/im,(m=>[{class:"commento2",text:m[1]}]));fl&&tm.splice(i,1,...tk)}if(!tm[i].class){{const{fl:fl,tk:tk}=parseexp(tm[i].text,/(^\s*\{.+?\})/m,(m=>[{class:"header",text:m[1]}]));fl&&tm.splice(i,1,...tk)}if(!tm[i].class){{const{fl:fl,tk:tk}=parseexp(tm[i].text,/(^\s*:\w+)(.*?$)/m,(m=>[{class:"param",text:m[1]},{class:"param2",text:m[2]}]));fl&&tm.splice(i,1,...tk)}if(!isvar){if(tm[i].class)continue;{const{fl:fl,tk:tk}=parseexp(tm[i].text,/(^\s*!\w+)/m,(m=>[{class:"function",text:m[1]}]));fl&&tm.splice(i,1,...tk)}if(tm[i].class)continue;{const{fl:fl,tk:tk}=parseexp(tm[i].text,/(#let.? +)([\w_.]+)/im,(m=>[{class:"comando",text:m[1]},{class:"variabile",text:m[2]}]));fl&&tm.splice(i,1,...tk)}if(tm[i].class)continue;{const{fl:fl,tk:tk}=parseexp(tm[i].text,/(#(push|pop|ret|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]}]));fl&&tm.splice(i,1,...tk)}if(tm[i].class)continue;{const{fl:fl,tk:tk}=parseexp(tm[i].text,/(#(if\s*|elseif\s*))/im,(m=>[{class:"comando",text:m[1]}]));fl&&tm.splice(i,1,...tk)}if(tm[i].class)continue;{const{fl:fl,tk:tk}=parseexp(tm[i].text,/(#(else|i |m |f |j |case|def ))/im,(m=>[{class:"comando",text:m[1]}]));fl&&tm.splice(i,1,...tk)}if(tm[i].class)continue;{const{fl:fl,tk:tk}=parsevariabili(tm[i].text);fl&&tm.splice(i,1,...tk)}if(tm[i].class)continue;{const{fl:fl,tk:tk}=parseexp(tm[i].text,/(\$[\w_.]+)/im,(m=>[{class:"variabile",text:m[1]}]));fl&&tm.splice(i,1,...tk)}}}}}}return tm}class Pickers{constructor(){this.clear()}clear(){this.d={},this.keypics={},this.key="",this.keypics[this.key]=0}reset(){this.keypics={},this.key="";for(let k in this.d)this.d[k]._invalid=!0}pack(){let cl=[];Object.entries(this.d).forEach((([k,v])=>{v._invalid&&cl.push(k),delete v._invalid}));for(let c of cl)delete this.d[c]}setkey(k){this.key=k,this.keypics[k]||(this.keypics[k]=0)}add(data){let _id=this.keypics[this.key]||0,k=`${this.key}_${_id}`;this.keypics[this.key]=_id+1;let d=this.d[k]??{};return data=data??{},this.d[k]={...d,...data,_invalid:!1,_key:this.key,_id:_id},k}}function toruleset(rs){const o={};if(rs&&rs.length)for(const r of rs)o[r.cod]=r;return o}function headerconvert(tt){const rr=muClComments(tt,!1);tt={};let grp={r:[]},fl=!1;for(const r of rr){const 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)){const v=r.split(","),t={cod:clean(v[0])};let tm;tm=(v[1]||"").trim(),tm&&(t.des=tm),tm=clean(v[2]),tm&&(t.tipo=tm),tm=clean(v[3]),tm&&(t.alias=tm),tm=clean(v[4]),tm&&(t.valid=tm),tm=clean(v[5]),tm&&(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){const rr=muClComments(tt.toLowerCase(),!1),tx={};for(const r of rr)if(!/^\s*:/.exec(r)){const 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,this.pick=new Pickers}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){
|
|
263
|
-
/** @type {Variabile} */
|
|
264
|
-
this.imgpreview={},this.vari=new Variabile,this.ruleset={},this.fndotcallback&&this.vari.setfndot(this.fndotcallback),this.ruleheader="",mode&&(
|
|
265
|
-
/** @type {Object.<string, Macro>} */
|
|
266
|
-
this.macro={},
|
|
267
|
-
/** @type {Object.<string, Variante>} */
|
|
268
|
-
this.varianti={},this.varelenco={},this.macroelenco={},this.scripts={},this.#headers=void 0,this.#alias=void 0,this.#deriva=void 0,this.#typos=void 0)}setimgpreview(cod,img){img?this.imgpreview[cod]=img:delete this.imgpreview[cod]}getimgpreview(cod){return this?.imgpreview[cod||""]}setfndot(fndotcallback){this.fndotcallback=fndotcallback,this.vari.setfndot(fndotcallback)}async#checkelencovar(cat){if(cbInfo&&!this.varelenco[cat]){const 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(const t of tm)switch(t.tipo){case"_headers":"string"==typeof t.value&&(t.value=headerconvert(t.value)),this.#headers=t.value||{};break;case"_alias":"string"==typeof t.value&&(t.value=aliasconvert(t.value)),this.#alias=t.value||{};break;case"_typos":if("string"==typeof t.value){const tips=fromjson(t.value);for(const tp in tips){const 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,ruleset=[],datadelgiorno=0){this.item=clean(item,!0),this.rule=clean(rule,!0),this.model=clean(model,!0),this.ruleset=toruleset(ruleset),this.data=datadelgiorno||(new Date).toInt()}async getheader(cod){let tm;return!this.#headers&&cbInfo&&(tm=await cbInfo("headers",this.cat,"_headers"),this.parseheaderfrominfo(tm)),this.#headers||(this.#headers={}),this.#headers[cod]}async getalias(){let tm;return!this.#alias&&cbInfo&&(tm=await cbInfo("headers",this.cat,"_alias"),this.parseheaderfrominfo(tm)),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;let ct=riga.contenuto;ct.startsWith("$")&&(ct=await this.vari.valuta(ct));const rr=/^([({}):$\w.\\/]+)[\s;,]*(.*)?$/im.exec(ct);if(!rr)return void errori.add("Macro non valida:"+ct,riga);let macro=clean(rr[1],!0);macro.includes("$")&&(macro=await this.vari.valuta(macro));const pars=getcolonne(rr[2]),{name:name,cat:cat}=checkmu(macro,this.cat);this.cat=cat;const ky=`${cat}/${name}`;if(!this.macro[ky]){const 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:macro,pars:pars}:(errori.add(`macro non trovata ${ky}`,riga),{})}catch(error){errori.add(geterrdes(error),`ambiente.getmacro: ${riga?.contenuto}`)}}async getvariante(cod){const{name:name,cat:cat}=checkmu(cod,this.cat);let n2=name,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;const 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){const xx=new Variante(this);if(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){const mac=new Macro(this,v);await mac.loadAndCompile(`${v}.mu`);const 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){const cc=new CodiceBarra;await cc.compila(articolibarre,titolibarre);for(const x in 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(const v of info.var)await this.varcompila(v,callback);for(const 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){const 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 checkvarianti(cat,vars){if(!cat||!vars?.length)return;cat=checkname(cat),await this.#checkelencovar(cat);const t=this.varelenco[cat],vn=[];for(let v of vars){v=clean(v,!0);const nn=`${cat}/${v}`;this.varianti[nn]||t&&t.includes(v)&&vn.push(v)}if(vn.length&&cbGetVariante){const xv=await cbGetVariante(cat,vn);if(xv&&xv.length)for(const x of xv){const{name:name,content:content}=x,vv=new Variante(this);vv.setheader(name,cat),content&&await vv.loadContentExtended(content),this.varianti[vv.key]=vv}}}async getheaderfromdb(name){const totale=await cbInfo("header",this.cat,name,!this.#deriva);let{head:head,rows:rows,macros:macros,deriva:deriva,llvars:llvars}=totale;for(const r of rows)r.cod=clean(r.cod),r.alias=clean(r.alias),r.t=clean(r.t);if(!llvars){llvars=new Set;for(const r of rows)if("p"==r.tipo);else{const 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||[];const vn=[],t=this.varelenco[this.cat];for(const nn of llvars)this.varianti[`${this.cat}/${nn}`]||t&&t.includes(nn)&&vn.push(nn);if(vn.length&&cbGetVariante){const vars=await cbGetVariante(this.cat,vn);if(vars&&vars.length)for(const x of vars){const{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){const getkey=n=>n.includes("/")?n:`${this.cat}/${n}`,cl=[];let k;if(rule&&(k=getkey(rule),this.macro[k]||cl.push(rule)),macros&&"string"==typeof macros){const vv=macros.split(";");for(const v of vv)k=getkey(v),this.macro[k]||cl.push(v)}if(cl&&cl.length>0&&cbGetMacro){const tm=await cbGetMacro(this.cat,cl);if(tm&&tm.length>0)for(const x of tm){this.checkscripts(x.content?.linkscript),delete x.content?.linkscript;const m=new Macro(this,x.name);for(const t in x.content){const contenuto=x.content[t];m[t]=contenuto}this.macro[m.key]=m}}}checkscripts(vv){if(Array.isArray(vv)&&vv.length)for(let v of vv)this.scripts[v.name]||(this.scripts[v.name]=v.value)}async setruleheader(rule,pars,ruleset){const{name:name,cat:cat}=checkmu(rule,this.cat);ruleset&&ruleset.length&&(this.ruleset=toruleset(ruleset));const ky=`${cat}/${name}`;if(!this.macro[ky]){const totale=await this.getheaderfromdb(name),{head:head,rows:rows,macros:macros}=totale;await this.getlinkedmacros(head.rule,macros);const tm=new Macro(this,name);if(!head)return void errori.add("Missing rule: "+rule);if(head.rule){const k2=this.macro[`${cat}/${head.rule}`];if(k2)for(const 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;const 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)}async splitteroggetti(name){let data=await this.getvariante(name),cl=[];return data?.rows&&Object.values(data.rows).forEach((v=>{cl.push({tipo:v.v[2]||"",cod:v.v[0]||"",des:v.v[1]||"",macro:v.v[4]||"",sps:parseInt(v.v[3])||0,isshape:parseInt(v.v[5])})})),cl.length||cl.push({tipo:"avob",cod:"__",des:"Vuoto",macro:"",sps:0}),cl}}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){const 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){azzera&&mu.azzera();return mu.valuta(codice)}function muInit(cat,cbGetMacro,cbGetVariante,cbFunc,cbInfo,cbGetFile,cbLogga){const 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(const p of pars){const{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){const 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,isJsonStr,isObject,muInit as jsTest,logga,muCalc,muClComments,muClean,muCompileScript,muEval,muEvalScript,muGenerate,muInit,muLimits,muParsecode,muValuta,mustr,newAmbiente,newMacro,newVariabile,newVariante,noquote,parselimitifromdb,parselimitifromrule,parsevar,poppars,pushpars,quote,seedarray,seeder,setOggetto,sortrows,testsync,tipicolonna,tipifree,tipiheader,tk,toCadPars,toJson,tonum,xdt};
|
|
1
|
+
function testsync(t,e){return t+e}const tk=()=>(new Date).valueOf();function seedarray(t,e){if(t&&t.length){let a=[];for(let e=0;e<t.length;e++){let s=t[e];if(s.p)for(let t=0;t<s.p;t++)a.push(e);else a.push(e)}return t[a[seeder(a.length,e)]]}}function seeder(t,e="seed42"){const a=function mulberry32(t){return function(){t=(t|=0)+1831565813|0;let e=Math.imul(t^t>>>15,1|t);return e=e+Math.imul(e^e>>>7,61|e)^e,((e^e>>>14)>>>0)/4294967296}}(function xmur3(t){let e=1779033703^t.length;for(let a=0;a<t.length;a++)e=Math.imul(e^t.charCodeAt(a),3432918353),e=e<<13|e>>>19;return function(){return e=Math.imul(e^e>>>16,2246822507),e=Math.imul(e^e>>>13,3266489909),(e^=e>>>16)>>>0}}(String(e))());return Math.floor(a()*t)}function isJsonStr(t){if("string"!=typeof t)return!1;const e=t.trim();return e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")}const isObject=t=>!(!t||!Array.isArray(t)&&"object"!=typeof t);function quote(t){if((t=(t||"").trim()).length>1){if(t.startsWith('"')&&t.endsWith('"'))return t;if(t.startsWith("(")&&t.endsWith(")"))return t}return`"${t}"`}function noquote(t){return(t=t.trim()).startsWith('"')&&t.endsWith('"')||t.startsWith("(")&&t.endsWith(")")?t.slice(1,-1):t}function hash(t){let e="";if("string"==typeof t||"number"==typeof t)e=t+"";else if("object"==typeof t&&t){const a=Object.keys(t).sort(),s="\0";e=a.map((e=>`${e}${s}${String(t[e])}`)).join(s)}let a=2166136261,s=2218511855;for(let t=0;t<e.length;t++){const i=e.charCodeAt(t);a^=i,a+=a<<5^2779096485,s^=a,s=((s<<3)+i^2134516169)>>>0}return a>>>=0,a.toString(16)+s.toString(16)}function geterrdes(t){if(t&&"object"==typeof t){let e=t.stack?.toString().replace(/^.*?node_modules.*$/gim,"")||t.message||"";e=e.replaceAll("/","_").replaceAll(".js","").replaceAll("\n\n","\n").replace(/;\s+/gi,"\n"),t=e}return(t=t.replace(/sqlite/gi,"SQL ")).replaceAll(";",",").trim()}let t,e,a,s,i,r;const logga=(...t)=>{r?r(t):console.log(...t)};function setcallbacks(n,o,c,l,u,h){e=n,t=o,a=c,s=l,i=u,r=h}const xdt=()=>(new Date).valueOf();function clean(t,e=!1){return e?(t||"").trim().toLowerCase():(t||"").trim()}function getcouple(t,e="=",a=!0){const s=(t=t||"").indexOf(e);return s>=0?{v:clean(t.substring(0,s),a),o:t.substring(s+e.length).trim(),fl:!0}:{v:clean(t,a),o:"",fl:!1}}function checkmu(t,e){if((t=(t||"").trim()).indexOf("/")>0){const a=t.split("/");e=a[0]||"",t=a[1]||""}if(!e)throw new Error("manca il catalogo per "+t);return{name:t,cat:e=checkname(e)}}function checkname(t,e=!1){if(t=(t||"").trim(),e&&!t)return"";if(!t||!/^[a-zA-Z_][a-z0-9A-Z_+-]*$/gim.test(t))throw new Error(`nome non valido: "${t}" \n deve contenere solo lettere, _, -, e numeri`);return t.toLowerCase()}function getcolonne(t,e=!1){t=String(t||"");const a=/^(\d*)\.\.(\d*)$/.exec(t);if(a){let t=parseInt(a[1])||0,e=parseInt(a[2])||0;const s=[];for(let a=t;a<=e;a++)s.push(a+"");return s}if(!/["({[]/.test(t))return t.split(/[,;]/).map((t=>t.trim()));const s=[];let i="",r=0,n=!1;for(let e=0;e<t.length;e++){const a=t[e];if(0===r&&'"'===a&&(0!==e&&"\\"===t[e-1]||(n=!n)),n||("("===a||"["===a||"{"===a?r++:")"!==a&&"]"!==a&&"}"!==a||(r=Math.max(0,r-1))),","!==a&&";"!==a||0!==r||n)i+=a;else{const t=i.trim();s.push(t),i=""}}const o=i.trim();return o&&s.push(o),s.map((t=>(t=t.trim(),!e&&(t.startsWith('"')&&t.endsWith('"')||t.startsWith("(")&&t.endsWith(")"))?t.slice(1,-1):t)))}const parsevar=(t,e,a,s,i=!1)=>{const r=["[","(","{"],n=["]",")","}"];s||(s="["==a?"]":"("==a?")":"}");const o=r.includes(a);let c=1,l=0;const u=[];for(let h=e;h<t.length;h++)if(o&&r.includes(t[h])||t[h]==a)c++;else if(o&&n.includes(t[h])||t[h]==s){if(c--,0==c&&t[h]==s)return u[l]=t.substring(e,h),{i:h,res:u}}else if(":"==t[h])1==c&&(u[l]=t.substring(e,h),e=h+1,l++);else if("\n"==t[h]&&i)return{i:h,res:u};return{i:-1,res:t.substring(e)}};function setOggetto(t,e){"object"==typeof t&&"object"==typeof e&&Object.keys(e).forEach((a=>{Object.hasOwn(t,a)&&"function"!=typeof t[a]&&(t[a]=e[a])}))}function getOggetto(t,e=[]){if(Array.isArray(t))return t.map((t=>getOggetto(t,e)));if(t&&"object"==typeof t){const a={};for(const[s,i]of Object.entries(t))"function"==typeof i||e&&e.includes(s)||(a[s]=getOggetto(i,e));return a}return t}function fromjson(t,e){if(Array.isArray(t))return t;if("string"!=typeof t)return t;if(""==t)return e||{};try{return JSON.parse(t)}catch(a){return logga(`Errore parsing JSON: ${a}\n${t}`),e||{}}}const n=new class Errori{constructor(){this.azzera()}azzera(){this.err=[]}add(t,e){this.err.push({msg:t,row:e})}get(){return this.err}get length(){return this.err.length}toString(){const t=[];for(const e of this.err){const a="object"==typeof e.msg?JSON.stringify(e.msg):e.msg||"";t.push(`${e.row?e.row+":":""}${a}`)}return t.join("\n")}},toNum=(t,e=-1)=>{const a="string"==typeof t?parseFloat(t)||0:t;if(e<0)return a||0;const s=Math.pow(10,e);return Math.round(a*s)/s||0};function getheaddims(t){let e;try{e="object"==typeof t&&t?t:JSON.parse(t||"{}")}catch(t){e={}}return e||(e={}),e.l||(e.l={visible:1,val:1e3,min:0,max:1e4}),e.a||(e.a={visible:1,val:1e3,min:0,max:1e4}),e.p||(e.p={visible:1,val:1e3,min:0,max:1e4}),e}function sortrows(t){const e=Object.keys(t).sort(),a={};for(let s=0;s<e.length;s++){const i=e[s],r=t[i];s+1<e.length&&e[s+1].startsWith(i+".")?r.hasliv=1:delete r.hasliv,a[i]=r}return a}const o=/(?<!\w)\(/g,c=/^-?[0-9.]+$/,l=/^(\w+)(!)?\[(.*)?\]$/,u=/[0-9.]/,h=/[+\-*/^%]/,f=/[a-zA-Z]/i;function valutaparentesi(t){for(t=(t+"").trim();;){const e=o.exec(t);if(!e)break;{const{i:a,res:s}=parsevar(t,e.index+1,"(",")");if(a<=0)break;t=t.substring(0,e.index)+valutaparentesi(s[0])+(a>=0?t.substring(a+1):"")}}return function operatoricomparazione(t){let e,a;const s={"||":()=>valutaparentesi(e)||valutaparentesi(a)?1:0,"|":()=>valutaparentesi(e)||valutaparentesi(a)?1:0,"&&":()=>valutaparentesi(e)&&valutaparentesi(a)?1:0,"&":()=>valutaparentesi(e)&&valutaparentesi(a)?1:0,"<<=":()=>clean(e)<=clean(a),">>=":()=>clean(e)>=clean(a),"===":()=>clean(e)==clean(a),"==":()=>clean(e)==clean(a),"!!":()=>clean(e)!=clean(a),"<<":()=>clean(e)<clean(a),">>":()=>clean(e)>clean(a),"<=":()=>muCalcbase(e)<=muCalcbase(a),">=":()=>muCalcbase(e)>=muCalcbase(a),"<":()=>muCalcbase(e)<muCalcbase(a),">":()=>muCalcbase(e)>muCalcbase(a),"=":()=>muCalcbase(e)==muCalcbase(a),"!":()=>muCalcbase(e)!=muCalcbase(a)};let i=-1,r="";for(const e in s)if(i=t.indexOf(e),i>=0){r=e;break}return-1!==i?(e=t.slice(0,i),a=t.slice(i+r.length),s[r]&&s[r]()?1:0):muCalcbase(t)}(t=function valutainsiemi(t){if(t.includes("[")){function resinisiemi(t){const e=t[1],a=!!t[2],s=getcolonne(t[3]);for(const t of s)if(t==e)return a?"0":"1";return a?"1":"0"}for(;;){const e=l.exec(t);if(!e)break;{const a=resinisiemi(e);t=t.substring(0,e.index)+a+t.substring(e.index+e[0].length)}}}return t}(t))}const d={sqrt:t=>Math.sqrt(t),sqr:t=>Math.sqrt(t),pow:(t,e)=>Math.pow(t,e),int:t=>Math.floor(t),floor:(t,e=0)=>Math.floor((Number.parseFloat(t)||0)*10**e)/10**e,round:(t,e=0)=>Math.round((Number.parseFloat(t)||0)*10**e)/10**e,dec:(t,e=0)=>Math.floor((Number.parseFloat(t)||0)*10**e)/10**e,abs:t=>Math.abs(t),sin:t=>Math.sin(t*Math.PI/180),cos:t=>Math.cos(t*Math.PI/180),tan:t=>Math.tan(t*Math.PI/180),asin:t=>180*Math.asin(t)/Math.PI,acos:t=>180*Math.acos(t)/Math.PI,atan:t=>180*Math.atan(t)/Math.PI,atan2:(t,e)=>180*Math.atan2(t,e)/Math.PI,seeder:(t,e)=>seeder(t,e),log:t=>Math.log(t),log10:t=>Math.log10(t),min:(...t)=>Math.min(...t),max:(...t)=>Math.max(...t),clamp:(t,e,a)=>Math.max(e,Math.min(a,t)),rnd:(t,e)=>t?e?Math.floor(Math.random()*(e-t+1))+t:Math.floor(Math.random()*t):Math.random(),cas:(t,e)=>Math.floor(Math.random()*(e-t+1))+t};function muCalcbase(t){let e=0;function parseOperator(){const a=t[e];return h.test(a)?(e++,a):null}function parsePrimary(){if("+"===t[e]||"-"===t[e]){return("-"===t[e++]?-1:1)*parsePrimary()}if(u.test(t[e]))return function parseNumber(){const a=e;for(;e<t.length&&u.test(t[e]);)e++;return Number(t.slice(a,e))}();if("("===t[e]){e++;const a=parseExpr();return")"===t[e]&&e++,a}return f.test(t[e])?function parseFunctions(){const a=t.slice(e);if(!a)return 0;for(const[s,i]of Object.entries(d)){const r=new RegExp(`^(${s})\\(`,"i").exec(a);if(r){e+=r[0].length;let a=[];for(;;){let s=parseExpr();if(a.push(s),")"===t[e]){e++;break}if(","!=t[e])break;e++}return i(...a)}}return e++,parseExpr()}():0}function parseFactor(){let a=parsePrimary();for(;e<t.length&&/[/*^%]/.test(t[e]);){const t=parseOperator(),e=parsePrimary();"*"===t?a*=e:"/"===t?a=e?a/e:0:"%"===t?a=e?a%e:0:"^"===t&&(a=Math.pow(a,e))}return a}function parseExpr(){let a=parseFactor();for(;e<t.length&&/[+-]/.test(t[e]);){const t=parseOperator(),e=parseFactor();"+"===t?a+=e:"-"===t&&(a-=e)}return a}return t=t.replace(/\s/g,""),parseExpr()}function muCalc(t){if(!t)return 0;if("number"==typeof t)return t||0;if("string"!=typeof t)return 0;const e=t.replaceAll(",",".");return c.test(e)?Number(e)||0:valutaparentesi(t)||0}const m=100;function valutavar(t,e){const a=e[0]||"";if(!a)return"";if(t.counter>=m)return a;const s=valuta0(t,a);let i;if(t.stl[s])i=`-- R:${s} --`;else{const e=t.var(s);if(isObject(e))return e;t.stl[s]=!0,i=valutabase(t,e),delete t.stl[s]}if(t.counter>=m)return a;if(e[1]){const a=getcolonne(i);if("l"==e[1])return String(a.length);const s=muCalc(valuta0(t,e[1]));if(!(s>=0&&s<a.length))return"";i=valuta0(t,a[s])}if(e[2]){const a=muCalc(valuta0(t,e[2]));if(a){let s=0;return e[3]&&(s=muCalc(valuta0(t,e[3]))),a<0?i.slice(a):s?i.substring(a-1,a+s-1):i.substring(a-1)}}return i}function valutaquadra(t,e){let a=getcolonne(e||"");const s=clean(a[0]);function replacecharcode(t){return"\\t"==t?"\t":"\\n"==t?"\n":(t||"").replace(/&(\d+)/g,((t,e)=>String.fromCharCode(parseInt(e))))}switch(s){case"set":{const e=valuta0(t,a[1]||""),s=valuta0(t,a[2]||"");t.add(e,t.var(s))}break;case"ex":{const e=valuta0(t,a[1]||"");let s=valuta0(t,a[2]||"");s||(s=",");const i=muCalc(valuta0(t,a[3]||"")),r=e.split(s);return i>0&&r[i-1]||""}case"ex2":{const e=replacecharcode(a[1]||""),s=muCalc(valuta0(t,a[2]||""));a.splice(0,3);return a.join(";").split(e)[s>0?s-1:0]||""}case"replace":return a[1].replace(new RegExp(a[2]||"x","gim"),(a[3]||"").trim());case"replace2":case"rp2":try{let t=replacecharcode(a[1]||"x");const e=replacecharcode(a[2]||"").trim();a.splice(0,3),t=t.replace(/&(\d+)/g,((t,e)=>`\\u${parseInt(e).toString(16).padStart(4,"0")}`));return a.join(";").replace(new RegExp(t,"im"),e)}catch(t){return""}case"look":case"lookb":{const t=parseFloat(a[1]||"");if(a=a.slice(2).map((t=>parseFloat(t)||0)),"lookb"==s){const e=a.filter((e=>e<=t));return e.length?Math.max(...e):t}{const e=a.filter((e=>e>=t));return e.length?Math.min(...e):t}}case"tk":{let e=muCalc(valuta0(t,a[1]||""))||0;if(!e){e=muCalc(valuta0(t,a[2]||""));const s=a[1]||"";return e?a[3].split(s)[e-1]:""}return a[e>0?e+1:2]||""}case"totab":return a.splice(0,1),a.join("\t");case"tosep":{const t=replacecharcode(a[1]||"")||";";return a.splice(0,2),a.join(t)}case"len":{let t;return a.length>2?(a.shift(),t=a.join(";")):t=a[1]||"",t.length}case"mid":{const e=valuta0(t,a[1]||""),s=muCalc(valuta0(t,a[2]||"")),i=muCalc(valuta0(t,a[3]||""));return e.substring(s-1,s+i-1)}case"arrotonda":{const t=muCalc(a[1]);let e=1;return["0","1","2","3","4","5","6"].includes(a[2])?e=Math.pow(10,parseInt(a[2])):(e=muCalc(a[2]),0==e&&(e=1e3)),Math.round(t*e)/e}case"iif":return muCalc(valuta0(t,a[1]))?a[2]||1:a[3]||0;case"instr":case"instr2a":{const t=a[1]||"",e=a[2]||"";return t.toLowerCase().indexOf(e.toLowerCase())+1}case"instr2":{const t=a[1]||"";return a.splice(0,2),a.join(";").toLowerCase().indexOf(t.toLowerCase())+1}default:return s.startsWith(".")?{fun:e,pars:[]}:{fun:s,pars:a}}}function valuta0(t,e){if(e+="",t.counter>=m)return e;for(;;){const a=/\$([{(])/im.exec(e);if(!a)break;{const s=a.index,{i:i,res:r}="("==a[1]?parsevar(e,s+2,"(",")"):parsevar(e,s+2,"{","}"),n=valutavar(t,r);if(isObject(n))return n;e=valuta0(t,e.substring(0,s))+n+(i>=0?valuta0(t,e.substring(i+1)):"")}}return e=(e=e.replace(/\$([a-z|][\w|.]*)/gi,((e,a)=>{let s="";for(;a.length;){let e;if(t.stl[a]?e=`--R: ${a} --`:(t.stl[a]=!0,e=valutabase(t,t.var(a)),delete t.stl[a]),e||!(a.length>1)){s=e+s;break}s=a.slice(-1)+s,a=a.substring(0,a.length-1)}return s}))).replace(/\$(\d+):(\d+)(:(\d+))?/g,((t,e,a,s,i)=>{i=i?+i:1;const r=[];for(let t=+e;t<=+a;t+=i)r.push(t.toString());return r.join(";")}))}function valutabase(t,e){return e&&(t.counter++,t.counter<=m&&(e=valuta0(t,e)),t.counter--),e}class Variabile{constructor(){this.stl={},this.dictionary={},this.vec=[],this.counter=0,this.fndotcallback=void 0}static isValidKey(t){return/^[\w][\w\d.[\]]*$/.test(t)}static sanitizeKey(t){return t.replace(/[^a-zA-Z0-9_.[\]]/g,"_")}setfndot(t){this.fndotcallback=t}push(){this.vec.push({saves:[],dic:{...this.dictionary}})}pop(){if(this.vec.length>0){let t=this.vec.pop(),e={};if(t.saves&&t.saves.length)for(let a of t.saves)e[a]=this.dictionary[a];if(this.dictionary=t.dic,t.saves&&t.saves.length)for(let a of t.saves)this.dictionary[a]=e[a]}}savevars(t){if(!this.vec.length>0)return;let e=this.vec[this.vec.length-1];e.saves||(e.saves=[]);let a=t.split(",");for(let t of a){const a=Variabile.sanitizeKey(t);a&&!e.saves.includes(a)&&e.saves.push(a)}}clear(){this.vec=[],this.dictionary={}}azzera=()=>this.clear();var(t){let e="";const a=/^(\d*)\.\.(\d*)$/.exec(t);if(a){let t=parseInt(a[1])||0,e=parseInt(a[2])||0;const s=[];for(let a=t;a<=e;a++)s.push(a+"");return s}if(t.indexOf("|")>=0){const a=t.split("|");t=a[0],e=a[1]}function toformat(t,e){switch(e.trim().toLowerCase()){case"0":return String(parseInt(t)||0);case"-":return String((parseInt(t)||1)-1);case"+":return String((parseInt(t)||0)+1);case"data":return a=parseFloat(t)||0,new Intl.DateTimeFormat("it",{day:"2-digit",month:"short",year:"2-digit"}).format(a.toDate());case"euro":return((t,e="")=>{if(t){let e=Intl.NumberFormat("en",{style:"currency",currency:"EUR"}).format(t);return e=e.replace(/€/g,"").replace(/\./g,";").replace(/,/g,".").replace(/;/g,",")+"€",e}return e})(parseFloat(t));case"num":return toNum(parseFloat(t));case"n":case"n0":case"n1":case"n2":case"n3":case"n4":{const a=parseInt(e.slice(1))||0;return toNum(parseFloat(t),a)}case"u":return String(t).toUpperCase();case"l":return String(t).toLowerCase();default:return t}var a}const s=Variabile.sanitizeKey(t);if(s.startsWith(".")&&this.fndotcallback){const t=this.fndotcallback(s.toLowerCase());if(t)return toformat(t,e)}if(Variabile.isValidKey(s)){const t=s.toLowerCase(),a=/^([\w][\w\d]*)([.[])/.exec(t);if(a){const s=this.dictionary[a[1]];if(s&&"object"==typeof s)return toformat(function objval(t,e){const a=e.split(".");let s=t;for(let t=0;t<a.length;t++){const e=a[t],i=e.match(/(.*?)\[(\d*)\]/);if(i){if(i[1]&&(s=s[i[1]]),void 0===s)return"";s=s[parseInt(i[2],10)||0]}else switch(e){case"_k":s=(Object.keys(s)||[]).join(",");break;case"_v":s=Object.values(s)||[];break;case"_l":s=s.length||0;break;default:s=s[e]}if(void 0===s)return""}return"number"==typeof s?s+"":s}(s,("["==a[2]?a[2]:"")+t.substring(a[0].length)),e)}return toformat(this.dictionary[t]||"",e)}return""}getvar(t){return this.var(t)}colonna(t,e){return getcolonne[e]||t}dump(t=!1){let e=[];for(const t in this.dictionary)e.push({cod:t,val:this.dictionary[t]});return e=e.sort(((t,e)=>t.cod>e.cod)),t?e.map((t=>`${t.cod} = ${isObject(t.val)?JSON.stringify(t.val,null,2):t.val}`)):e}add(t,e){if("number"==typeof e&&(e=String(e)),t.includes("*")){const a=Variabile.sanitizeKey(t.split("*")[0]);if(Variabile.isValidKey(a)){const t=a.toLowerCase();let s=Object.keys(this.dictionary).filter((e=>e.startsWith(t)));for(let t of s)e?this.dictionary[t]=e:delete this.dictionary[t]}}else{const a=Variabile.sanitizeKey(t);if(Variabile.isValidKey(a)){const t=a.toLowerCase();0===e||e?this.dictionary[t]=e:delete this.dictionary[t]}else logga(`Invalid key: ${t}`)}}removeallvars(t){if(Array.isArray(t)){let e=Object.keys(this.dictionary);for(let a of e)t.includes(a)||delete this.dictionary[a]}else this.dictionary={}}valutasync(t){return valutabase(this,t)}async valuta(t,e){this.stl={};let a=await async function valutafunc(t,e,a){if(e){for(let s=0;s<20;s++){const s=e.lastIndexOf("$[");if(!(s>=0)){e=valutabase(t,e);break}{const{i:i,res:r}=parsevar(e,s+2,"[","]"),n=valutabase(t,e.substring(0,s)),o=r?r[0].startsWith(".")?valutabase(t,r.join(":")):valutabase(t,r[0]):"",c=i>=0?valutabase(t,e.substring(i+1)):"";let l=valutaquadra(t,o);if("object"==typeof l&&(l=a?await a(l?.fun,l.pars):`** fun: ${l.fun} ** `),isObject(l))return l;e=n+l+c}}return e}return""}(this,t,e);return isObject(a)||(a=(t=>{for(;;){const e=t.indexOf("{");if(!(e>=0))break;{const{i:a,res:s}=parsevar(t,e+1,"{","}");if(a<0)return t;t=t.substring(0,e)+muCalc(s[0])+(a>=0?t.substring(a+1):"")}}return t})(a)),a}async parametrokeyval(t){if("string"!=typeof t)return{};if(!(t=t.trim()))return{};let e,a,s,i=!1;return t.startsWith("#")&&(i=!0,t=t.slice(1)),s=t.indexOf("="),s>0?(e=clean(t.slice(0,s)),a=t.slice(s+1)):(s=t.indexOf(":"),s>0?(e=clean(t.slice(0,s)),a=t.slice(s+1),a=this.var(a)):(e=clean(t),a=this.var(e))),a&&"string"==typeof a&&a.includes("$")&&(a=await this.valuta(a)),["l","a","p"].includes(e)&&(i=!0),i&&(a=muCalc(a)),{k:e,v:a}}}class CodiceBarra{constructor(){this.barre={}}azzera(){this.barre={}}oriented(t,e,a,s){switch(t=(t||"1").substr(0,1).toLowerCase()){case"0":break;case"l":return{t:"l",x:e};case"a":return{t:"a",x:a};case"p":return{t:"p",x:s};case"2":return{t:t,x:e,y:s,z:a};case"5":return{t:t,x:e,y:a,z:s};case"4":return{t:t,x:s,y:e,z:a};case"3":return{t:t,x:a,y:s,z:e};case"6":return{t:t,x:s,y:a,z:e};default:return{t:"1",x:a,y:e,z:s}}}async getcode(t,e,a,s,i){let[r,n]=t.split(":");n=n||"";const getcode0=async(t,r)=>{let n=this.barre[t];if(!n&&i&&(n=await i(t),n||(n={t:"1",r:[]}),this.barre[t]=n,n.coderr&&"errore"!=n.coderr||(n.coderr=`#err_${t}`)),!n||0==n.r.length)return{extra:{err:"missing codicebarra"},c:`#err_${t}`,fm:10};const{t:o,x:c,y:l,z:u}=this.oriented(t,e,a,s),h={barra:t,fm:n.fm,t:o,liv:r,items:n.r.length,err:""};let f=n.r;if(u){const t=f.filter((t=>t.z===u||!t.z));t.length>0?f=t:h.err=`spessore non coerente: ${u}`}if("l"==o||"a"==o||"p"==o){const t=f.find((t=>t.x>=c));if(t)return{c:t.c,fm:t.x==c?0:1,x1:t.x,x:c,extra:h}}else{let t=f.find((t=>t.x==c&&t.y==l));if(t)return{c:t.c,fm:0,x:c,y:l,z:u,x1:t.x,y1:t.y,z1:t.z,extra:h};if(0!=n.fm&&(t=f.find((t=>t.x>=c&&t.y==l)),t))return{c:t.c,fm:1,x:c,y:l,z:u,x1:t.x,y1:t.y,z1:t.z,extra:h};if(0!=n.fm&&2!=n.fm&&(t=f.find((t=>t.x>=c&&t.y>=l)),t))return{c:t.c,fm:2,x:c,y:l,z:u,x1:t.x,y1:t.y,z1:t.z,extra:h}}return n.codalt&&r<5?await getcode0(n.codalt,r+1):{c:n.coderr,fm:9,x:c,y:l,z:u,extra:h}};return await getcode0(r,0)}compila(t,e){e||(e={});const a={};if(Array.isArray(t)){for(const s of t)if(s.cod=clean(s.cod),s.barcode=clean(s.barcode),s.barcode.length>2&&"+"==s.barcode[0]){s.barcode=s.barcode.substr(1);const t=this.oriented(s.barcode.substr(0,1),s.l,s.a,s.p);t.c=s.modello?{c:s.cod,m:s.modello}:s.cod,a[s.barcode]||(a[s.barcode]={t:s.barcode.substr(0,1),r:[]},e[s.barcode]&&(a[s.barcode]=Object.assign(e[s.barcode],a[s.barcode]))),a[s.barcode].r.push(t)}for(const t in a){a[t].r.sort(((t,e)=>t.y?1e4*(t.x-e.x)+(t.y-e.y):t.x-e.x))}}this.barre=a}}const p="IFDEF|IFNDEF|SETDEF|CACHE|RET|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(t){const e=muClComments(t),a=[];for(const t of e){const e=t.includes("(")||t.includes("[")?[t]:getcolonne(t,!0);let s=!1;for(const t of e)!t.startsWith('"')&&t.includes("=")?(a.push(t),s=!0):s&&(a[a.length-1]+=","+t)}const s={};for(const t of a){let{v:e,o:a}=getcouple(t,"=",!1);a=a||"",e&&(/^[-+]?\d*\.?\d+$/.test(a)&&(a=parseFloat(a)),s[e]=a)}return s}function muClComments(t,e){const a=(s=t,s.replace(/("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*')|\/\*[\s\S]*?\*\//g,((t,e)=>e||""))).split(/\r?\n/);var s;const i=[];let r="";for(const t of a){let a=t;if(/(^|[^:])\/\/.*/.test(a)&&(a=a.replace(/(^|[^:])\/\/.*/,((t,e)=>e.trim()))),a=a.trim(),0!==a.length||e)if(r.length>0&&(a=r+" "+a,r=""),a.endsWith("\\")){a=a.slice(0,-1);const t=a.lastIndexOf("//");-1!==t&&(a=a.slice(0,t).trim()),r=a}else i.push(a)}return i}function muClean(t,e=!1){if(!Array.isArray(t))return void n.add("muClean: expected array!");const a=[];function addgen(t){if(a.length>0&&""==a[a.length-1].tipo){const s=a[a.length-1];e||!(!t.startsWith("!")&!t.startsWith("."))||t.startsWith("$")||t.startsWith("{")||t.startsWith("#")||s.contenuto.startsWith("!")||s.contenuto.startsWith(".")||s.contenuto.startsWith("$")||s.contenuto.startsWith("{")||s.contenuto.startsWith("#")?a.push({tipo:"",contenuto:t}):s.contenuto=s.contenuto+"\n"+t}else a.push({tipo:"",contenuto:t})}for(const e of t){const t=e.match(/^#([\w.]+)\s*(.*)$/);if(t){let s=t[1].toUpperCase().trim(),i="";if(s.includes(".")){const t=s.split(".");s=t[0],i=t[1]}if(p.includes(s)){const e=t[2];if("IF"!==s&&"IFDEF"!=s&&"IFNDEF"!=s||!e.includes("#")){const e={tipo:s,contenuto:t[2]};i&&(e.tipo2=i),a.push(e)}else{let i=e.match(/^(.*?)\s*#\s*(\w+)\s*(.*?)\s*#\s*(\w+)\s*(.*)$/);i?(a.push({tipo:s,contenuto:i[1].trim()}),a.push({tipo:i[2].toUpperCase(),contenuto:i[3]}),a.push({tipo:"ELSE",contenuto:""}),a.push({tipo:i[4].toUpperCase(),contenuto:i[5]}),a.push({tipo:"ENDIF",contenuto:""})):(i=e.match(/^(.*?)\s*#\s*(\w+)\s*(.*)$/),i?(a.push({tipo:s,contenuto:i[1].trim()}),a.push({tipo:i[2].toUpperCase(),contenuto:i[3]}),a.push({tipo:"ENDIF",contenuto:""})):a.push({tipo:t[1].toUpperCase(),contenuto:t[2]}))}}else addgen(e)}else addgen(e)}let s=0,i=0,r=0,o=[],c=[],l=[];for(let t=0;t<a.length;t++){const e=a[t];switch(e.i=t,e.tipo){case"FOR":case"FORVAR":case"VARIANTE":case"DO":i++,c[i]={pos:t,bk:[]};break;case"LOOP":case"ENDFOR":if(i>0){const{pos:s}=c[i];for(const e of c[i].bk)e.next=t,e.prev=s;e.prev=s,a[s].next=t,i--}break;case"BREAK":case"EXIT":case"EXITFOR":case"CONTINUE":i>0&&c[i].bk.push(e);break;case"IF":case"IFDEF":case"IFNDEF":s++,o[s]={pos:t,bk:[e]};break;case"SELECT":r++,l[r]={pos:t,bk:[e],first:t};break;case"ELSEIF":case"ELSEIFDEF":case"ELSEIFNDEF":case"ELSE":if(s>0){const{pos:i}=o[s];o[s].bk.push(e),a[i].next=t,o[s].pos=t}break;case"CASE":case"CASES":case"DEFAULT":if(r>0){const{pos:s,first:i}=l[r];l[r].bk.push(e),a[s].next=t,e.first=i,l[r].pos=t}break;case"ENDIF":if(s>0){const{pos:e,next:i}=o[s];a[e].next=t;for(const e of o[s].bk)e.last=t;s--}break;case"ENDSELECT":if(r>0){const{pos:e,next:s}=l[r];a[e].next=t;for(const e of l[r].bk)e.last=t;r--}}}return a}function muLimits(t){const e=muClComments(t),a=[];let s;const parsa=t=>t?[...new Set(t.split(",").map((t=>t.trim())).sort().filter((t=>t)))]:void 0;for(const t of e){let e=/^\s*\{(.*)?\}/im.exec(t);if(e)"limit"==clean(e[1])?(s={},a.push(s)):s=void 0;else if(s&&(e=/^\s*:(\w+)\s*(.*)/.exec(t),e))switch(e[1].toLowerCase()){case"opz":case"o":s.opz=parsa(e[2]);break;case"obs":case"obsolete":s.obsolete=parsa(e[2]);break;case"scons":case"sconsigliate":s.scons=parsa(e[2]);break;case"neutri":s.neutri=parsa(e[2]);break;case"art":s.art=parsa(e[2]);break;case"mod":s.mod=parsa(e[2]);break;default:logga("missing:",e[1])}}return a}function parselimitifromdb(t){let e,a=[];if(t&&t.length)for(const s of t){e={},s.varfilter=fromjson(s.varfilter,[]),s.result=fromjson(s.result,[]),s.result2=fromjson(s.result2,[]),s.exclude=parseInt(s.exclude)?1:0,s.exclude2=parseInt(s.exclude2)?1:0;const{item:i,model:r,rule:n,varfilter:o,result:c,result2:l,exclude:u,exclude2:h,datai:f,dataf:d}=s;function remap(t){return t.map((t=>clean("string"==typeof t?t:t.Value,!0))).filter((t=>t))}if(c.length||l.length){if(c.length&&(u?e.ex=remap(c):e.valid=remap(c)),l.length&&(h?e.ex2=remap(l):e.valid2=remap(l)),i&&(e.i=clean(i).split(";")),r&&(e.m=clean(r).split(";")),n&&(e.r=clean(n).split(";")),(f||d)&&f<d&&(e.datai=parseInt(f),e.dataf=parseInt(d)),o&&o.length){e.v=[];for(const m of o){let p=e.v.find((t=>t.v==clean(m.Variant)));p||(p={v:clean(m.Variant),o:[]},e.v.push(p)),p.o=[...p.o,...clean(m.Value).split(";")],p.o=[...new Set(p.o.filter((t=>t)))]}}setlevelimite(e),a.push(e)}}return a=a.sort(((t,e)=>e.l-t.l)),a}function setlevelimite(t){let e=0;t.i&&t.i.length&&(e+=5),t.m&&t.m.length&&(e+=3),t.r&&t.r.length&&(e+=2),t.v&&t.v.length&&(e+=3),t.datai&&t.dataf&&(e+=1),t.l=e}function parselimitifromrule(t){function parsevettorelimiti(t){const e={},a=/^\s*[!:]\s*(\w+)\s*(.*)$/i;function addres(t,a){function addres0(t,a){(a=clean(a))&&(e[t]||(e[t]=[]),e[t].includes(a)||e[t].push(a))}if(Array.isArray(a))for(const e of a)addres0(t,e);else addres0(t,a)}for(const s of t){const t=a.exec(s);if(t)switch(t[1]){case"var":case"v":case"variante":{const a=(t[2]||"").indexOf(" ");if(a>0){const s=clean(t[2].substring(0,a)),i=getcolonne(t[2].substring(a+1));if(s&&i&&i.length){e.v||(e.v=[]);let t=e.v.find((t=>t.v==s));t||(t={v:s,o:[]},e.v.push(t));for(const e of i)t.o.includes(e)||t.o.push(e)}}}break;case"d":case"dt":case"data":case"date":{const a=t[2].split(" "),s=parseInt(a[0]),i=parseInt(a[1]);(s||i)&&(e.datai=s,e.dataf=i)}break;case"rule":case"r":case"mu":addres("r",getcolonne(t[2]));break;case"item":case"i":addres("i",getcolonne(t[2]));break;case"model":case"m":addres("m",getcolonne(t[2]));break;case"e":case"escludi":case"exclude":addres("ex",getcolonne(t[2]))}else addres("valid",getcolonne(s))}return setlevelimite(e),e}let e;if(t&&t.length){for(const a of t){const t=parsevettorelimiti(a);if(t&&(t.valid&&t.valid.length||t.ex&&t.ex.length)){let a=0;t.i&&t.i.length&&(a+=5),t.m&&t.m.length&&(a+=3),t.r&&t.r.length&&(a+=2),t.v&&t.v.length&&(a+=3),t.datai&&t.dataf&&(a+=1),t.l=a,e||(e=[]),e.push(t)}}e&&(e=e.sort(((t,e)=>e.l-t.l)))}return e}class Variante{constructor(t){this.rows={},this.name="$",this.key="$",this.limits=void 0,this.amb=t}setheader(t,e){const{name:a,cat:s}=checkmu(t,e);return this.cat=s,this.name=a,this.alias="",this.obbligo=!1,this.des=a,this.vdef=[],this.rows={},this.h=[],this.key=`${s}/${a}`,{name:a,cat:s}}fromdim(t,e=2){"number"!=typeof t&&(t=muCalc(t)),e>0&&e--;let a,s=1e9;for(const i in this.rows){const r=this.rows[i];if(!r.annulla){const i=parseFloat(r.v[e])||0;i<=s&&i>=t&&(s=i,a=r)}}return this.#t(t,a)}async load(e,a,i=!1){const{name:r,cat:n}=this.setheader(e,a);if(t){const e=await t(n,r);if(e){if(await this.loadContentExtended(e),e.filter)this.limits=parselimitifromdb(e.filter);else if(s&&!i){const t=await s("filter",n,r);t&&t.length&&(this.limits=parselimitifromdb(t))}return!0}}return!1}async _loadContent(t){const e=/^\s*[!:]\s*(\w+)\s*(.*)$/i;let a="";const s=[];let i,r=!1;for(const n of t){const t=n.toLowerCase();if("{limit}"==t)i=[],s.push(i),r=!0;else if("{:limit}"==t)r=!1;else if(r)i.push(n);else{let t=e.exec(clean(n));if(t)if(a&&"extra"==t[1].toLowerCase()){const e=getcolonne(t[2]);for(const t of e){const e=t.indexOf("=");if(e>0){const s=clean(t.substring(0,e));"v"!=s&&(this.rows[a][s]=t.substring(e+1).trim())}}}else switch(t[1].toLowerCase()){case"alias":{const e=t[2].toLowerCase().split(";");if(e[0].trim()!=this.name)if(1==e.length)this.alias=e[0];else{let a;if(this.amb?a=await this.amb.getvariante(e[0]):(a=new Variante,await a.load(e[0],this.cat)),t=a?.rows,t){let a=Object.keys(t);if(a.length){e.splice(0,1);const addrows=e=>{e&&e.forEach((e=>this.rows[e]=t[e]))};for(const t of e){const e=/([ei])\s*:\s*(.*)\s*$/im.exec(t);if(e){const t=e[2].split(",");for(let e=0;e<t.length;e++)t[e]=t[e].trim();a="e"==e[1]?a.filter((e=>{for(const a of t)if(e.startsWith(a))return!1;return!0})):a.filter((e=>{for(const a of t)if(e.startsWith(a))return!0;return!1}))}}addrows(a)}}}}break;case"h":this.h=getcolonne(t[2]).map((t=>({des:t})));break;case"t":{const e=getcolonne(t[2]);if(this.h)for(let t=0;t<this.h.length;t++)this.h[t].t=e[t]||""}break;case"des":this.des=t[2];break;case"default":case"vdef":this.vdef=getcolonne(t[2]);break;case"obbligo":this.obbligo=!0;break;case"noerp":this.noerp=!0;break;case"noobbligo":this.obbligo=!1}else{const t=getcolonne(n),e=clean(t[0]);e&&(a=e,this.rows[a]={annulla:0,v:t})}}}const n=Object.keys(this.rows);for(const t of n)if(t.includes(".")){const e=t.split(".");for(let t=0;t<e.length-1;t++){const a=e.slice(0,t+1).join(".");this.rows[a]||(this.rows[a]={annulla:0,v:[a]})}}return this.limits=parselimitifromrule(s),!0}tovec(){const t=this.rows,e=[],a=Object.keys(t).sort();for(const t of a)this.rows[t].annulla<2&&e.push(this.#t(t,this.rows[t]));return e}#t(t,e){const a=[t];if(e)for(const t of e.v)"string"==typeof t&&(t.includes(",")||t.includes(";"))?a.push(quote(t)):a.push(t||"");return a.join(",")}tovar(t,e=""){const a=clean(t);if(!this.rows[a])return e||t;const s=this.rows[a];return 2==s.annulla?"":this.#t(e||t,s)}isvalidopz(t){const e=clean(t),a=this.rows[e];return!!a&&(1!=a.annulla&&!a.hasliv)}firstvalid(t,e=void 0){const a=t.indexOf(",");if(a>0&&(t=t.slice(0,a).trim()),t&&this.isvalidopz(t))return t;if(e&&e.length)for(const t of e)if(this.isvalidopz(t))return t;if(this.vdef&&this.vdef.length)for(const t of this.vdef)if(this.isvalidopz(t))return t;const s=Object.keys(this.rows).sort();for(let t=0;t<s.length;t++){const e=s[t];if(!(t<s.length-1&&s[t+1].startsWith(e+"."))&&this.isvalidopz(e))return e}}resetfilter(){delete this._valids;for(const t in this.rows)this.rows[t].annulla=0}validkeys(){let t=Object.keys(this.rows)||[];return t=t.filter((t=>0==this.rows[t].annulla)).sort(),t}limitfiltra(t){if(this.resetfilter(),!t)return;t=muClComments(t.toLowerCase());const e=[];for(const a of t){const t=/^#([iex])(\d*)\s+(.+)$/i.exec(a);if(t){const a={ex:t[1],col:(parseInt(t[2])||1)-1,val:"x"==t[1]?t[3]:getcolonne(t[3])};a.val.length&&e.push(a)}}if(e.length)for(const t in this.rows){const a=this.rows[t];for(const t of e)if("e"==t.ex){if(_check((a.v[t.col]+"").toLowerCase(),t.val)){a.annulla=1;break}}else if("x"==t.ex){const e=(a.v[t.col]+"").toLowerCase().split(/[,;]/).map((t=>t.trim()));if(!_check((t.val+"").toLowerCase(),e)){a.annulla=1;break}}else if(!_check((a.v[t.col]+"").toLowerCase(),t.val)){a.annulla=1;break}}function _check(t,e){if(1==e?.length&&"."==e[0])return!!t;return!!e.find((e=>e.startsWith(t)))}}limita(t){if(t&&t.length)return this.limitfiltra(t);if(!this.limits||!this.amb)return this.resetfilter();const{item:e,rule:a,model:s,vari:i,data:r}=this.amb,valid=(t,e)=>!e||!e.length||!!t&&e.includes(t),n=this.limits.filter((t=>{if(!valid(e,t.i))return!1;if(!valid(a,t.r))return!1;if(!valid(s,t.m))return!1;if(r&&t.datai&&r<t.datai)return!1;if(r&&t.dataf&&r>t.dataf)return!1;if(t.v&&t.v.length)for(const e of t.v){const t=clean(i.var(e.v).split(",")[0],!0);if(t&&!e.o.includes(t))return!1}return!0}));if(!n||!n.length)return this.resetfilter();const o=new Set,c=new Set,l=new Set,u=new Set;let h=!1,f=!1;for(const t of n){if(t.valid&&t.valid.length){h=!0;t.valid.filter((t=>t.indexOf("*")>0)).map((t=>t.split("*")[0])).forEach((t=>o.add(t))),t.valid.filter((t=>!t.includes("*"))).forEach((t=>l.add(t)))}if(t.ex&&t.ex.length){f=!0;t.ex.filter((t=>t.indexOf("*")>0)).map((t=>t.split("*")[0])).forEach((t=>c.add(t))),t.ex.filter((t=>!t.includes("*"))).forEach((t=>u.add(t)))}}for(const t in this.rows){const e=this.rows[t];let a=!1,s=!1;if(h){for(const e of o)if(t.startsWith(e)){a=!0;break}!a&&l.has(t)&&(a=!0)}if(f){for(const e of c)if(t.startsWith(e)){s=!0;break}!s&&u.has(t)&&(s=!0)}e.annulla=0,h&&!a&&(e.annulla=1),f&&s&&(e.annulla=1)}return n}async loadContentExtended(t){if("object"==typeof t){for(const e in t)["rows","des","h","alias","obbligo"].includes(e)&&(this[e]=t[e]);"string"==typeof t.def&&t.def.length&&(this.vdef=getcolonne(t.def.trim().toLowerCase())),t.filter&&t.filter.length&&(this.limits=parselimitifromdb(t.filter))}else await this._loadContent(muClComments(t,!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}}}const v={};async function getcbfunc(t,e,s,i,r,n){if(a){if(v[e])return"";let t=await a(e,s,i,r,n);return isObject(t)||(t=(t||"").trim(),"!"==t&&(v[e]=!0,t="")),t}return t}async function intvaluta(t,e,a){return await t.vari.valuta(a,(async(a,s)=>{switch(a){case"dim":{let a=muCalc(s[1]),i=await dammivariante(t,e,s[2]),r=parseInt(s[3])||2;return i&&i.fromdim?i.fromdim(a,r):a}case"seed":{let t=s[1],e=getcolonne(s[2]);return e[seeder(e.length,t)]||""}case"seedvar":{let a=await dammivariante(t,e,s[2]),i=s[1],r=a.validkeys();if(s[3]&&s[4]){let t=muCalc(s[3])-1;if(t>=0){let e=getcolonne(s[4]);r=r.filter((s=>{let i=a.rows[s];if(i&&i.v&&i.v[t]){let a=getcolonne(i.v[t]);if(a)for(let t of e)if(a.includes(t))return!0}return!1}))}}let n=seeder(r.length,i);return n>=0&&a.tovar(r[n])||""}default:return await getcbfunc(`**fun:${a}**`,a,s,t.vari,t)}}))}async function dammivariante(t,e,a){let s;return s=e&&e?.localvar&&e.localvar[a]?e.localvar[a]:await t.getvariante(a),s}async function impostavariante(t,e,a,s,i){let r,n=a;if((s=s||"")&&"string"==typeof s){const t=s.indexOf(":");t>=0&&(t>0&&(n=clean(s.slice(0,t))),s=s.slice(t+1))}if(i&&i.alias&&(n=i.alias),e&&e.paralias&&e.paralias[a]&&(n=e.paralias[a]),r=await dammivariante(t,e,n),r)if(i&&i.t){i.des||(i.des=r.des);let e=i?.filtra||"";if(e.includes("$")&&(e=await t.vari.valuta(e)),"m"===i.t){let t=2;if(s.includes(":")){const e=s.split(":");t=parseInt(e[1]),s=e[0]}r.limita(e),s=r.fromdim(parseFloat(s),t)}else{r.limita(e);const t=r.firstvalid(s,getcolonne(i.def));s=r.tovar(t)}}else r.resetfilter(),s=r.firstvalid(s),s=r.tovar(s);else i&&i.t&&i.t;return t.vari.add(a,s),s}async function pushpars(t,e,a,s){const i={},r=[];if(a)for(const s of a){const{v:a,o:n,fl:o}=getcouple(s);i[a]||(i[a]=!0,r.push({v:a,o:t.vari.var[a]}),o&&await impostavariante(t,e,a,n))}if(s)for(const a of s){const{v:s,o:n,fl:o}=getcouple(a);i[s]||(i[s]=!0,r.push({v:s,o:t.vari.var[s]}),o&&await impostavariante(t,e,s,n))}return r}function poppars(t,e){if(e)for(const a of e)t.vari.add(a.v,a.o)}const outpush=(t,e)=>{null!=e&&null!=e&&("object"==typeof e?t.push(JSON.stringify(e,null,2)):"string"==typeof e&&e.startsWith("_ ")&&t.length>0&&"string"==typeof t[t.length-1]?t[t.length-1]+=e.slice(2):t.push(...e.split("\n")))};async function muEval(t,e,a,s){if(!Array.isArray(a))return n.add("codice is not a valid parsed array"),[];s||(s={}),s.id||(s.id="_"),s._stackmacro||(s._stackmacro=0),s.limited||(s.limited=!1),t||n.add("amb deve essere definito");const i=t.vari;t.maxdelays,t.cat;const r=[];let o,c,l;tk();for(let u=0;u<a.length;){let h=a[u];switch(h.tipo){case"IFDEF":case"IFNDEF":case"IF":{const f="IF"==h.tipo?muCalc(await intvaluta(t,e,h.contenuto)):"IFDEF"==h.tipo?""!=await intvaluta(t,e,h.contenuto):""==await intvaluta(t,e,h.contenuto);h.next?(a[h.next].jlast=f?1:0,f||(u=h.next-1)):n.add("Troppo tempo",h)}break;case"SELECT":h.next?(a[h.next].t1=await intvaluta(t,e,h.contenuto),u=h.next-1):n.add("manca endselect",h);break;case"CASE":case"CASES":case"DEFAULT":if(h.next)if(h.jlast)h.jlast=0,u=h.last-1;else{let d,m=1;const _getvv=async()=>{let a=await intvaluta(t,e,h.contenuto);return a=a.includes(":")&&!a.includes(",")?a.split(":").map((t=>(t||"").trim())):getcolonne(a),a};if("CASE"==h.tipo){m=0,d=await _getvv();const p=muCalc(h.t1||"");d.find((t=>muCalc(t)==p))&&(m=1)}else if("CASES"==h.tipo){m=0,d=await _getvv();const v=h.t1||"";d.find((t=>t==v))&&(m=1)}a[h.next].jlast=m?1:0,a[h.next].t1=h.t1,m||(u=h.next-1)}else n.add("manca select",h);break;case"ELSEIF":case"ELSEIFDEF":case"ELSEIFNDEF":case"ELSE":if(h.next)if(h.jlast)h.jlast=0,u=h.last-1;else{const g="ELSE"==h.tipo?1:"ELSEIF"==h.tipo?muCalc(await intvaluta(t,e,h.contenuto)):"ELSEIFDEF"==h.tipo?""!=await intvaluta(t,e,h.contenuto):""==await intvaluta(t,e,h.contenuto);a[h.next].jlast=g?1:0,g||(u=h.next-1)}else n.add("manca endif",h);break;case"ENDIF":case"ENDSELECT":case"CACHE":case"CVAR":break;case"PUSH":i.push();break;case"POP":i.pop();break;case"INC":case"I":if(s._stackmacro>500)n.add("stack chiamate macro troppo profondo!",h);else if(({macro:o,pars:c,xid:l}=await t.getmacro(h)||{}),o){s._inc=!0,s._stackmacro++;const b={},w=o.parametri?._;if(w&&w.length)for(const k of w){const x=clean(k.split("=")[0]||"",!0);x&&(b[x]=i.dictionary[x])}await o.impostaparametri(w,c);const y=await muEval(t,o,o.codice,s);for(const C in b)b[C]?i.dictionary[C]=b[C]:delete i.dictionary[C];r.push(...y),s._stackmacro--,s._inc=!1}break;case"RET":{const E=await intvaluta(t,e,h.contenuto);t.vari.savevars(E)}break;case"MACRO":case"M":case"FUNC":case"F":if(s._stackmacro>500)n.add("stack chiamate macro troppo profondo!",h);else{let{macro:O,pars:_,xid:$}=await t.getmacro(h)||{};if(O){const F=!!s.grafica||["F","FUNC"].includes(h.tipo),S=s.id||"",I=O.parametri?._,L={};if(F)i.push();else{if(O.head)for(const A of O.head)L[A.cod]=t.vari.var(A.cod);if(I&&I.length)for(const M of I){const z=(M.split("=")[0]||"").trim().toLowerCase();z&&(L[z]=i.dictionary[z])}}if(O.codice.length){if(s._stackmacro++,s.grafica&&"function"==typeof s.grafica){let j="",W="";_&&_.length?(j=_.find((t=>t.startsWith("#id"))),j?(j=await i.valuta(j.slice(4)),j.startsWith("#")?s.id=j:s.id=hash(`${u}${O.name}${S}${j}`),_=_.filter((t=>!t.startsWith("#id"))),W=s.id):s.id=hash(`z${S}${u}`)):s.id=hash(`z${S}${u}`);let N=t.pick.key;t.pick.key=s.id;const T=await s.grafica({tipo:h.tipo,id:W,pars:_,parametri:I,macro:O,options:s,vari:t.vari,amb:t});t.pick.key=N,r.push(T)}else{await O.impostaparametri(I,_);let V=t.vari.var("_rootnode");t.vari.add("_rootnode","0");const D=await muEval(t,O,O.codice,s);t.vari.add("_rootnode",V),r.push(...D)}s._stackmacro--}if(F)i.pop();else for(const R in L)L[R]?i.dictionary[R]=L[R]:delete i.dictionary[R];s.id=S}else n.add("Macro non trovata!",h)}break;case"SETDEF":{let P=getcolonne(h.contenuto.toLowerCase()),J=await dammivariante(t,o,P[0]),K=P[1]||"def_",U=P[2];if(K.endsWith("_")||(K+="_"),J&&J.rows){P=Object.keys(J.rows),U&&(P=P.filter((t=>t.startsWith(U))));for(let q of P){let G=`${K}${q}`;if(!i.dictionary[G]){function torow(t){const e=[];if(t)for(const a of t.v.slice(1))"string"==typeof a&&(a.includes(",")||a.includes(";"))?e.push(quote(a)):e.push(a||"");return e.join(",")}i.add(G,await intvaluta(t,e,torow(J.rows[q])))}}}}break;case"LET":case"LETS":{let B=h.contenuto.indexOf("="),H=-1;if(B>=0&&(H=h.contenuto.indexOf("=",B+1)),H<0){const X=h.contenuto;if(B=X.indexOf("="),B>0){const Z=await intvaluta(t,e,X.slice(0,B).trim());let Q=X.slice(B+1).trim();Q="LET"==h.tipo?muCalc(await intvaluta(t,e,Q))||"":await intvaluta(t,e,Q),i.add(Z,Q)}}else{const Y=getcolonne(h.contenuto);for(const tt of Y)if(B=tt.indexOf("="),B>0){const et=await intvaluta(t,e,tt.slice(0,B));let at=tt.slice(B+1).trim();at="LET"==h.tipo?muCalc(await intvaluta(t,e,at))||"":await intvaluta(t,e,at),i.add(et,at)}}}break;case"LETT":{const st=h.contenuto.indexOf("=");if(st>0){const it=await intvaluta(t,e,h.contenuto.slice(0,st).trim()),rt=await intvaluta(t,e,h.contenuto.slice(st+1).trim());i.add(it,rt)}}break;case"LOOK":case"LOOKB":{const nt=getcolonne(await intvaluta(t,e,h.contenuto)),ot=muCalc(nt[1]),ct=muCalc(nt[3]),lt=await dammivariante(t,o,nt[2]);if(lt&<.rows){const ut=Object.values(lt.rows).reduce(((t,e)=>{const a=parseInt(e.v[ct?ct-1:0]);return a&&("LOOKB"==h.tipo?a<=ot&&a>t.v&&(t.v=a,t.c=e.v[0]):a>=ot&&a<t.v&&(t.v=a,t.c=e.v[0])),t}),{v:"LOOKB"==h.tipo?0:1/0,c:""});ut&&ut.c&&(t.vari.add(nt[0],lt.tovar(ut.c)),s.checkheader&&"function"==typeof s.checkheader&&await s.checkheader({variante:nt[0],valore:lt.tovar(ut.c),riga:h}))}else t.vari.add(nt[0],`${ot},no,no`)}break;case"LETV":case"LETM":case"DEF":{const ht=getcolonne(h.contenuto);if(ht)for(const ft of ht){let{v:dt,o:mt,fl:pt}=getcouple(ft);if(pt){dt=await i.valuta(dt),mt=await intvaluta(t,e,mt);const vt=await impostavariante(t,e,dt.trim().toLowerCase(),mt.trim().toLowerCase(),"LETM"==h.tipo?{t:"m"}:{t:"v"});s._stackmacro<=0&&s.checkheader&&"function"==typeof s.checkheader&&await s.checkheader({variante:dt,valore:vt,riga:h})}}}break;case"DO":{const gt=(h.contenuto||"").trim();let bt=!0;gt&&!muCalc(await intvaluta(t,e,gt))&&(bt=!1),h.next&&(bt||(u=h.next+1))}break;case"VARIANTE":case"FORVAR":case"FOR":{let wt,yt,kt,xt;if(s.oldstyle?(wt=h.contenuto.split(","),xt=wt[2]||"i",kt=wt[0],yt=wt[1]):(wt=getcolonne(h.contenuto||""),xt=wt[0]||"",kt=clean(wt[1],!0),yt=wt[2]||""),xt=xt.includes("$")?await intvaluta(t,e,xt):xt||"","FORVAR"==h.tipo||"VARIANTE"==h.tipo){const Et=await intvaluta(t,e,kt),Ot=Et?await dammivariante(t,e,Et):void 0;Ot?kt=Ot.tovec():(kt=[],n.add("getvariante not found!",h))}else{const _t=await intvaluta(t,e,kt||"");kt=kt?getcolonne(_t):void 0}kt=kt||[];const Ct=0;if(h.next){a[h.next].for={v:xt,elenco:kt,nc:Ct,valido:yt};let $t,Ft=!0;xt&&kt.length>0?Ct>=kt.length?Ft=!1:($t=kt[Ct],i.add(xt,$t),yt&&(Ft=!muCalc(await intvaluta(t,e,yt)))):Ft=!1,Ft||(u=h.next-1)}else n.add("manca endfor/loop",h)}break;case"LOOP":{let St=!0;h.contenuto&&!muCalc(await intvaluta(t,e,h.contenuto))&&(St=!1),St&&(u=h.prev-1);break}case"ENDFOR":if(!h.contenuto||muCalc(await intvaluta(t,e,h.contenuto)))if(h.for){const{v:It,elenco:Lt,valido:At}=h.for;if(It&&Lt.length>0&&h.for.nc<500)for(;;){if(h.for.nc++,h.for.nc<Lt.length){if(i.add(It,Lt[h.for.nc]),At&&muCalc(await intvaluta(t,e,At)))continue;u=h.prev;break}break}}else n.add("manca istruzione for",h);break;case"BREAK":case"EXIT":case"EXITFOR":h.next?h.contenuto.trim()?muCalc(await intvaluta(t,e,h.contenuto))&&(u=h.next):u=h.next:n.add("break outside loop",h);break;case"CONTINUE":h.next?h.contenuto&&!muCalc(await intvaluta(t,e,h.contenuto))||(u=h.next-1):n.add("continue outside loop",h);break;case"MSG":case"LOG":{const Mt=await intvaluta(t,e,h.contenuto);logga(Mt),n.add(Mt)}break;default:{let zt;if(h.contenuto.startsWith("!")){zt=await intvaluta(t,e,h.contenuto);let jt="";const Wt=/^!(.\w+)[\s;,]\s*(.+)?$/gim.exec(zt);if(Wt)if(Wt[1].startsWith("."))await getcbfunc(zt,zt.slice(1),[],i,t),jt="";else{const Nt=Wt[1].toLowerCase(),Tt=getcolonne(Wt[2]||"");jt=await getcbfunc(zt,Nt,Tt,i,t)}jt&&outpush(r,jt)}else s.parsefnpunto&&"function"==typeof s.parsefnpunto&&h.contenuto.startsWith(".")?await s.parsefnpunto({dati:h.contenuto,output:r,id:s.id,vari:t.vari,amb:t}):(zt=await intvaluta(t,e,h.contenuto),outpush(r,zt))}}u++}return r}async function muGenerate(t,e,a,s,i=0){if(t.isgenera&&s){const r={counter:0,keys:{},isTestmode:i};if(a){if(!t.genera[a])return!1;await muGenerate_0(t,e,a,s,r)}else for(const a in t.genera)await muGenerate_0(t,e,a,s,r);return!0}}async function muGenerate_0(t,e,a,s,i){const r=t.genera[a];if(r){i.counter2=0;const n={};async function processavariante(o){if(i.isTestmode&&i.counter>i.isTestmode)return;if(o<r.vars.length){const a=r.vars[o];if(!n[a]){const s=await dammivariante(e,t,a),i=s?Object.keys(s.rows):void 0;if(i&&i.length>0){for(const t of i)e.vari.add(s.name,s.tovar(t)),n[a]=!0,await processavariante(o+1),n[a]=!1;return}logga("manca la variante",a)}}for(const a of r.calcola)t.formula[a]&&await muEval(e,t,t.formula[a],{limited:!0});for(const a of r.exclude)if(t.formula[a]){const s=await muEval(e,t,t.formula[a],{limited:!0});if(s)for(const t of s){if(muCalc(t))return}}const c=await muEval(e,t,r.codice,{limited:!0,localvar:t.localvar}),l={};for(const a of r.bom)if(t.formula[a]){let s=await muEval(e,t,t.formula[a],{limited:!0});s=s.join("\n").split("\n");for(const t of s)if(t){const e=getcolonne(t);l[a]||(l[a]=[]);const s={};for(let t=0;t<e.length;t++)s[`c${t}`]=e[t];l[a].push(s)}}await async function docallback(t,e,a,s,i,r){let n=!0;for(const o of e){const e=getcolonne(o);if(e[0]&&!r[e[0]]){r[e[0]]=1,r.counter++,r.counter2++;const o={__id:r.counter};for(let t=0;t<e.length;t++){let a=s.head[t]?s.head[t]:`c${t}`;"#"==a[0]?(a=a.substr(1),o[a]=Math.round(1e3*muCalc(e[t]))/1e3):o[a]=e[t]}await t(i,o,n?a:void 0,r.counter,r.counter2),n=!1}}}(s,c,l,r,a,i)}await processavariante(0)}}const g=["l","a","p"],b=/^\{(:?(var|valid|formula|genera|header|v|f|g|h))[\s|}]/im,w=["s","g","h","p","q"],y=[{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"}],k=[{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(t,e){const a=e.split("\n");for(const e of a)if(e.trim()){if(muCalc(t.valutasync(e)))return!0}return!1}class Macro{constructor(t,e){const{name:a,cat:s}=checkmu(e,t.cat||"");this.name=a,this.cat=s,this.amb=t,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(){const t=[];return this.errori.forEach((e=>t.push({e:e}))),t}getparametri(t={}){const{noderiva:e}=t,a={};if(this.dims&&g.forEach((t=>{const e=muCalc(this.amb.vari.var(t));e&&(a[t]=String(e))})),this.head){for(const t of this.head)if(!t._h){if(e&&t._d&&t._d.cod)continue;let s=this.amb.vari.var(t.cod);w.includes(t.t)||"string"==typeof s&&(s=s.split(",")[0]),a[t.cod]=s}}else if(this.parametri?._)for(const t of this.parametri._){const e=(t.split("=")[0]||"").trim().toLowerCase();let s=this.amb.vari.var[e];s=(s||"").split(",")[0],a[e]=s}return a}async setparametri(t){const e={},a=this.amb.ruleset||{};t||(t={}),this.dims&&g.forEach((e=>{let a=t[e]||this.dims[e].val;a=parseFloat(a)||0,this.dims[e].visible&&(a<this.dims[e].min&&(a=this.dims[e].min),a>this.dims[e].max&&(a=this.dims[e].max)),t[e]=String(a)}));for(const s of this.head){const i=a[s.cod];i&&(i.islock?(s.visible="0",t[s.cod]=i.opz,s._islock=!0):t[s.cod]||(t[s.cod]=i.opz)),"g"!=s.t&&("z"!=s.t||t[s.cod]||(t[s.cod]="1"),s._v=t[s.cod]||"",e[s.cod]=!0)}for(const a in t)e[a]||(e[a]=!0,await impostavariante(this.amb,this,a,t[a]));return this.head?.length>0&&await this.setparametro(this.head[0].cod,t[this.head[0].cod]||void 0,!0,t),this.getparametri()}async setparametro(t,e,a=!1,s={}){if(e&&"string"==typeof e&&e.includes("$")&&(e=await intvaluta(this.amb,this,e)),s||(s={}),this.head){const _imposta=async(t,e,a,i)=>{const r=t?.cod;if(t.valid&&!t._h1){const e=!valutaCondizioniTestata(this.amb.vari,t.valid);if(t._h!=e&&(t._h=e,["g","g1","g2"].includes(t.t)))for(let e=a+1;e<this.head.length;e++){const a=this.head[e];if(a){if(["g","g1","g2"].includes(a.t))break;a._h1=t._h}}}if(t._h||t._h1)return this.amb.vari.add(r,""),t._v=void 0,"";{if(delete t._h2,t.visible){const e=!valutaCondizioniTestata(this.amb.vari,t.visible);if(e&&(t._h2=e),["g","g1","g2"].includes(t.t))for(let e=a+1;e<this.head.length;e++){const a=this.head[e];if(a){if(["g","g1","g2"].includes(a.t))break;t._h2?a._h3=t._h2:delete a._h3}}}let i=this.amb.vari.var(r)||"";"thlm".includes(t.t)&&"string"==typeof i&&(i=i.split(",")[0]);let n=i;if("z"!=t.t||i||(this.amb.vari.add(r,"1"),i="1"),"m"==t.t&&t.spars){const e=getcolonne(t.spars);i=parseFloat(i||e[0])||0,e[1]&&parseFloat(i)<e[1]&&(i=parseFloat(e[1])||0),e[2]&&parseFloat(i)>e[2]&&(i=parseFloat(e[2])||0),i=String(i),this.amb.vari.add(r,i)}const o=await impostavariante(this.amb,this,r,e||t._v||i,t);if(t._v=void 0,i=this.amb.vari.var(r)||"","thl".includes(t.t)&&"string"==typeof i&&(i=i.split(",")[0],this.amb&&this.amb.deriva&&this.amb.deriva.length>0)){const e=this.amb.deriva.filter((t=>t.cod==r&&((!t.item||t.item==this.amb.item)&&((!t.model||t.model==this.amb.model)&&((!t.rule||t.rule==this.amb.rule)&&(!t.opz||t.opz==i))))));e.length&&e.forEach((e=>{let a=this.head.find((t=>t.cod==e.tocod));if(a){let r=this.amb.vari.var(a.cod);s&&s[a.cod]&&(r=s[a.cod]),"string"==typeof r&&(r=r.split(",")[0],r&&r!=n&&r!=i?delete a._d:(a._v=e.toopz||i,a._d={cod:t.cod,opz:e.toopz}))}}))}return o}};let i,r=-1;if("#dim"==t)a=1;else{if(r=this.head.findIndex((e=>e.cod===t)),r<0)return;const s=this.head[r];i=await _imposta(s,e,r),a&&delete s._d}if(a)for(let t=r+1;t<this.head.length;t++)await _imposta(this.head[t],void 0,t);return i}return await impostavariante(this.amb,this,t,e)}getmarker(){let t;if(this.head&&this.head.length){let e=this.head.find((t=>"marker"==(t.stipo||"").trim().toLowerCase().split(/[;,]/)[0].trim()));e&&e.cod&&(t=e.cod)}return t}isderivato(t){return"string"==typeof t&&(t=this.head.find((e=>e.cod==t))),!!(t&&t._d&&t._d.cod)}async impostaparametri(t,e,a=!1,s){if(this.head){this.paralias||(this.paralias={}),Array.isArray(this.head)||(this.head=[]);for(const t of this.head)t._v="",delete t._h,delete t._h1,delete t._h2,t.alias&&(this.paralias[t.cod]=t.alias)}s||(s={}),t||(t=[]),e||(e=[]);for(const a of[...t,...e]){const t=a.indexOf("=");if(t>0){let e=clean(a.substr(0,t));e.includes("$")&&(e=await intvaluta(this.amb,this,e));let s,i=a.substr(t+1);i.includes("$")&&(i=await intvaluta(this.amb,this,i)),this.head&&(s=this.head.find((t=>t.cod==e)))?s._v=i:await impostavariante(this.amb,this,e,i)}}if(this.head){let t=!0;for(const e of this.head){let i=await this.checkvalid(e.valid);a&&(i=!0),["g","g1","g2"].includes(e.t)?t=i:t&&i&&await this.setparametro(e.cod,s[e.cod]||e._v)}}}async checkvalid(t){if(!t)return!0;return!!muCalc(await intvaluta(this.amb,this,t))}getmacrostr(){return JSON.stringify(this.getmacro())}getmacro(){return getOggetto(this,["amb"])}setmacro(t){if(setOggetto(this,fromjson(t,{})),this.localvar)for(const t in this.localvar){const e=new Variante;setOggetto(e,this.localvar[t]),this.localvar[t]=e}}async load(t,a){let s,i;try{let r;if(({name:s,cat:i}=checkmu(t||this.name,a||this.cat||"")),this.name||(this.name=s),this.cat||(this.cat=i),this.azzera(),e&&(r=await e(i,s),"string"==typeof r&&(r.startsWith("{")||r.startsWith("["))&&(r=fromjson(r)),r&&r.head&&!Array.isArray(r.head)&&(r.head=[]),this.amb.checkscripts(r.linkscript),delete r.linkscript,r.head&&(r.dims=getheaddims(r.dims))),r){if("string"==typeof r)await this.parsedata(r);else for(const t in r)this[t]=r[t];return!0}n.add(`missing cbGetFile: ${i}/${s}`)}catch(t){n.add(geterrdes(t),`macro.load: ${s}/${i}`)}}async loadAndCompile(t,e,a=!1){let s;const{name:r,cat:o}=checkmu(t,this.cat||e);return this.azzera(),i&&(s=await i(o,r)),s?(await this.parsedata(s,a),this.getmacro()):void n.add(`missing cbGetFile: ${r}/${o}`)}async#e(t,e,a,s){let r;const{name:n,cat:o}=checkmu(t,this.cat);if(i&&(r=await i(o,n)),!r)return[];if(r.includes("$1")&&s&&s.length>0)for(let t=1;t<s.length;t++)r=r.replaceAll(`$${t}`,s[t]);let c=muClComments(r);const l=[];e&&(c=c.filter((t=>!/^\{(:?(var|valid|formula|header|genera|v|f|h))[\s|}]/im.test(t))));for(const t of c){const s=b.exec(t);if(s)e=!s[1].startsWith(":"),l.push(t);else{const s=/^\s*\{i\s(.+)?\}/im.exec(t);if(s){const t=getcolonne(s[1]);if(!a.includes(t[0])){a.push(t[0]);const s=await this.loadinclude(t[0],e,a,t);Array.isArray(s)&&l.push(...s),a.pop()}}else l.push(t)}}return l}async parsedata(t,e=!1){if(this.azzera(),!t)return;const a=[];let s=muClComments(t),i=!1;const r=[];for(const t of s){const e=b.exec(t);if(e)i=!e[1].startsWith(":"),a.push(t);else{const e=/^\s*\{i\s(.+)?\}/im.exec(t);if(e){const t=getcolonne(e[1]),s=await this.#e(t[0],i,[t[0]],t);Array.isArray(s)&&a.push(...s)}else a.push(t)}}i=!1;let n=this.codice;for(const t of a){const e=b.exec(t);if(e)if(e[1].startsWith(":"))n=this.codice;else switch(e[1]){case"genera":case"g":{let e=/^\s*\{(genera|g)\s+(.+)?\}/im.exec(t);if(e){const t=checkname(getcolonne(e[2])[0]);this.genera[t]=[],n=this.genera[t]}else n=this.errori,n.push(t)}break;case"valid":n=this.valid;break;case"var":case"v":{const e=/^\s*\{(var|v)\s+(.+)?\}/im.exec(t);if(e){const t=getcolonne(e[2]),a=checkname(t[0]);this.localvar[a]={name:a,des:t[1]||"",rows:[]},n=this.localvar[a].rows}else n=this.errori,n.push(t)}break;case"formula":case"f":{const e=/^\s*\{(formula|f)\s+(.+)?\}/im.exec(t);if(e){const t=checkname(e[2]);this.formula[t]=[],n=this.formula[t]}else n=this.errori,n.push(t)}break;case"h":case"header":n=r;break;default:this.errori.push(t),n=this.errori}else t.startsWith("{")&&(n=this.codice),n.push(t)}this.parametri={},this.codice=this.cleanfiltraparametri("_",this.codice,e);for(const t in this.formula)this.formula[t]=this.cleanfiltraparametri(t,this.formula[t],e);for(const t in this.localvar){const e=new Variante,a=this.localvar[t];e.setheader(t,this.cat),e.rows={};for(const t of a.rows){const a=getcolonne(t),s=a[0].trim().toLowerCase();e.rows[s]={annulla:0,v:a}}a.des&&(e.des=a.des),this.localvar[t]=e}s=this.valid,this.valid=[];for(const t of s){let e=getcouple(t,",");e={v:e.v,msg:e.o},e.v&&(e.v.startsWith("#")?this.formula[e.v.substring(1)]&&this.valid.push(e):this.valid.push(e))}s=r;const o=[];for(const t of s){const e=/^\s*([\w\-_]+)+[;,\s]\s*(.*)?$/im.exec(t);if(e){const t=getcolonne(e[2]),a=clean(e[1]);let s;if(a){s=o.find((t=>t.cod==a)),s||(s={cod:a,t:"t"},o.push(s));for(const e of t){const t=getcouple(e);switch(t.v){case"t":s.t=t.o;break;case"def":case"default":s.def=t.o;break;case"valid":case"colonna":case"hidden":t.o.startsWith("#")?this.formula[t.o.substring(1)]&&(s[t.v]=t.o):s[t.v]=t.o;break;default:s[t.v]=t.o}}}}}this.head=o,s=this.genera;const c={};for(const t in s)if(Array.isArray(s[t])){const e={codice:[],head:"",calcola:[],bom:[],vars:[],exclude:[]},a=/^\s*[!:]\s*(\w+)\s*(.*)$/i;for(const i of s[t]){const s=a.exec(clean(i));if(s)switch(s[1]){case"calcola":case"c":e.calcola=[...e.calcola,...getcolonne(s[2])];break;case"exclude":case"e":case"escludi":e.exclude=[...e.exclude,...getcolonne(s[2])];break;case"bom":case"db":e.bom=[...e.bom,...getcolonne(s[2])];break;case"vars":case"v":e.vars=[...e.vars,...getcolonne(s[2])];break;case"head":case"h":e.head=getcolonne(s[2]);break;default:this.errori.push(`genera ${t} => ${i}`)}else e.codice.push(i)}e.codice=muClean(e.codice,!0),c[t]=e}this.genera=c}cleanfiltraparametri(t,e,a){if(this.paralias||(this.paralias={}),e&&e.length){let a=!1;const getparalias=t=>{const e=[],a=getcolonne(t);for(const t of a)if(t.includes(":")){const a=t.split(":");this.paralias[a[0]]=a[1],e.push(a[0])}else e.push(t);return e};for(let s=0;s<e.length;s++){const i=/^:p[;,\s]+(.*)?$/im.exec(e[s]);if(i)e[s]=null,a=!0,this.parametri[t]=getparalias(i[1]);else{const i=/^!(parametri|pars|p)[;,\s]+(.*)?$/im.exec(e[s]);i&&(e[s]=null,a=!0,this.parametri[t]=getparalias(i[2]))}}a&&(e=e.filter((t=>null!=t)))}return e=muClean(e,a)}}function parsevariabili(t){let e=!1;const a=[];for(;;){const s=/\$([{[(])/m.exec(t);if(!s){t&&e&&a.push({class:"",text:t});break}{e=!0;const i="["==s[1]?"inline":"variabile";s.index>0&&a.push({class:"",text:t.substring(0,s.index)});const{i:r}=parsevar(t,s.index+2,s[1],null);if(!(r>s.index)){a.push({class:i,text:t.substring(s.index)});break}a.push({class:i,text:t.substring(s.index,r+1)}),t=t.substring(r+1)}}return{fl:e,tk:a}}function parseexp(t,e,a){if(!a)throw new Error("missing callback");let s=!1;const i=[];for(;;){const r=e.exec(t);if(!r){t&&s&&i.push({class:"",text:t});break}r.index>0&&i.push({class:"",text:t.substring(0,r.index)}),i.push(...a(r)),s=!0,t=t.substring(r.index+r[0].length)}return{fl:s,tk:i}}function muParsecode(t,e){t||(t=" "),t.endsWith("\n")&&(t+=" ");const a=[{class:"",text:t}];for(let t=0;t<a.length;t++)if(!a[t].class){{const{fl:e,tk:s}=parseexp(a[t].text,/(\/\*[^]+?\*\/)/im,(t=>[{class:"comment",text:t[1]}]));e&&a.splice(t,1,...s)}if(!a[t].class){{const{fl:e,tk:s}=parseexp(a[t].text,/(\/\/.*)$/im,(t=>[{class:"commento2",text:t[1]}]));e&&a.splice(t,1,...s)}if(!a[t].class){{const{fl:e,tk:s}=parseexp(a[t].text,/(^\s*\{.+?\})/m,(t=>[{class:"header",text:t[1]}]));e&&a.splice(t,1,...s)}if(!a[t].class){{const{fl:e,tk:s}=parseexp(a[t].text,/(^\s*:\w+)(.*?$)/m,(t=>[{class:"param",text:t[1]},{class:"param2",text:t[2]}]));e&&a.splice(t,1,...s)}if(!e){if(a[t].class)continue;{const{fl:e,tk:s}=parseexp(a[t].text,/(^\s*!\w+)/m,(t=>[{class:"function",text:t[1]}]));e&&a.splice(t,1,...s)}if(a[t].class)continue;{const{fl:e,tk:s}=parseexp(a[t].text,/(#let.? +)([\w_.]+)/im,(t=>[{class:"comando",text:t[1]},{class:"variabile",text:t[2]}]));e&&a.splice(t,1,...s)}if(a[t].class)continue;{const{fl:e,tk:s}=parseexp(a[t].text,/(#(push|pop|ret|select|cases|endselect|ifndef|elseifndef|ifdef|endif|elseifdef|variante|forvar|for|endfor|continue|break|inc|macro|default|letm|lets|letv|lett|leto|cat))/im,(t=>[{class:"comando",text:t[1]}]));e&&a.splice(t,1,...s)}if(a[t].class)continue;{const{fl:e,tk:s}=parseexp(a[t].text,/(#(if\s*|elseif\s*))/im,(t=>[{class:"comando",text:t[1]}]));e&&a.splice(t,1,...s)}if(a[t].class)continue;{const{fl:e,tk:s}=parseexp(a[t].text,/(#(else|i |m |f |j |case|def ))/im,(t=>[{class:"comando",text:t[1]}]));e&&a.splice(t,1,...s)}if(a[t].class)continue;{const{fl:e,tk:s}=parsevariabili(a[t].text);e&&a.splice(t,1,...s)}if(a[t].class)continue;{const{fl:e,tk:s}=parseexp(a[t].text,/(\$[\w_.]+)/im,(t=>[{class:"variabile",text:t[1]}]));e&&a.splice(t,1,...s)}}}}}}return a}class Pickers{constructor(){this.clear()}clear(){this.d={},this.keypics={},this.key="",this.keypics[this.key]=0}reset(){this.keypics={},this.key="";for(let t in this.d)this.d[t]._invalid=!0}pack(){let t=[];Object.entries(this.d).forEach((([e,a])=>{a._invalid&&t.push(e),delete a._invalid}));for(let e of t)delete this.d[e]}setkey(t){this.key=t,this.keypics[t]||(this.keypics[t]=0)}add(t){let e=this.keypics[this.key]||0,a=`${this.key}_${e}`;this.keypics[this.key]=e+1;let s=this.d[a]??{};return t=t??{},this.d[a]={...s,...t,_invalid:!1,_key:this.key,_id:e},a}}function toruleset(t){const e={};if(t&&t.length)for(const a of t)e[a.cod]=a;return e}function headerconvert(t){const e=muClComments(t,!1);t={};let a={r:[]},s=!1;for(const i of e){const e=/^\s*\{(h|head|header)\s+(\w+)\}/im.exec(i);if(e)a={cod:e[2],des:e[2],r:[]},s=!1,t[e[2]]=a;else if(!/^\s*:/.exec(i)){const t=i.split(","),e={cod:clean(t[0])};let r;r=(t[1]||"").trim(),r&&(e.des=r),r=clean(t[2]),r&&(e.tipo=r),r=clean(t[3]),r&&(e.alias=r),r=clean(t[4]),r&&(e.valid=r),r=clean(t[5]),r&&(e.visible=r),e.cod&&(s||"sep"!=e.tipo?a.r.push(e):(a.des=e.des,a.valid=e.valid,a.visible=e.visible,s=!0))}}return t}function aliasconvert(t){const e=muClComments(t.toLowerCase(),!1),a={};for(const t of e)if(!/^\s*:/.exec(t)){const e=getcolonne(t);e[0]&&e[1]&&(a[e[0]]={cod:e[1]})}return a}class Ambiente{#a=void 0;#s=void 0;#i=void 0;#r=void 0;constructor(t=".",e=100,a=!1){this.righevuote=a,this.maxdelays=e,this.setcatalog(t),this.fndotcallback=void 0,this.pick=new Pickers}setcatalog(t){return t=clean(t),this.cat!=t&&(this.cat=t,this.item=this.rule=this.model="",this.azzera(!0)),t}get muvalutatore(){return{getcolonne:getcolonne,muCalc:muCalc,muEval:muEval,tipifree:w}}azzera(t=!1){this.imgpreview={},this.vari=new Variabile,this.ruleset={},this.fndotcallback&&this.vari.setfndot(this.fndotcallback),this.ruleheader="",t&&(this.macro={},this.varianti={},this.varelenco={},this.macroelenco={},this.scripts={},this.#a=void 0,this.#s=void 0,this.#i=void 0,this.#r=void 0)}setimgpreview(t,e){e?this.imgpreview[t]=e:delete this.imgpreview[t]}getimgpreview(t){return this?.imgpreview[t||""]}setfndot(t){this.fndotcallback=t,this.vari.setfndot(t)}async#n(t){if(s&&!this.varelenco[t]){const e=await s("headers",t,"_varianti");Array.isArray(e)?this.varelenco[t]=e:e.vars&&(this.varelenco[t]=e.vars,e.alias&&(this.#s=e.alias)),this.varelenco[t]||(this.varelenco[t]=[])}}parseheaderfrominfo(t){if(t&&t.length>0)for(const e of t)switch(e.tipo){case"_headers":"string"==typeof e.value&&(e.value=headerconvert(e.value)),this.#a=e.value||{};break;case"_alias":"string"==typeof e.value&&(e.value=aliasconvert(e.value)),this.#s=e.value||{};break;case"_typos":if("string"==typeof e.value){const t=fromjson(e.value);for(const e in t){const a=t[e];a.db&&(a.db=muClean(muClComments(a.db))),a.list&&(a.list=muClean(muClComments(a.list)))}e.value=t}this.#r=e.value||{}}}setitem(t,e,a,s=[],i=0){this.item=clean(t,!0),this.rule=clean(e,!0),this.model=clean(a,!0),this.ruleset=toruleset(s),this.data=i||(new Date).toInt()}async getheader(t){let e;return!this.#a&&s&&(e=await s("headers",this.cat,"_headers"),this.parseheaderfrominfo(e)),this.#a||(this.#a={}),this.#a[t]}async getalias(){let t;return!this.#s&&s&&(t=await s("headers",this.cat,"_alias"),this.parseheaderfrominfo(t)),this.#s||(this.#s={}),this.#s}get deriva(){return this.#i,this.#i||[]}async getmacro(t){try{if("string"==typeof t&&(t={tipo:"M",contenuto:t}),!t||!t.contenuto)return;let e=t.contenuto;e.startsWith("$")&&(e=await this.vari.valuta(e));const a=/^([({}):$\w.\\/]+)[\s;,]*(.*)?$/im.exec(e);if(!a)return void n.add("Macro non valida:"+e,t);let s=clean(a[1],!0);s.includes("$")&&(s=await this.vari.valuta(s));const i=getcolonne(a[2]),{name:r,cat:o}=checkmu(s,this.cat);this.cat=o;const c=`${o}/${r}`;if(!this.macro[c]){const e=new Macro(this,r);await e.load()?this.macro[c]=e:n.add(`macro fail to load ${c}`,t)}return s=this.macro[c],s?{macro:s,pars:i}:(n.add(`macro non trovata ${c}`,t),{})}catch(e){n.add(geterrdes(e),`ambiente.getmacro: ${t?.contenuto}`)}}async getvariante(t){const{name:e,cat:a}=checkmu(t,this.cat);let s=e,i={};if(a==this.cat&&this.#s&&this.#s[e]&&(i=this.#s[e]||{},s=i.cod),await this.#n(a),this.varelenco[a]&&!this.varelenco[a].includes(e))return;const r=`${a}/${s}`;let n;return this.varianti[r]?n=this.varianti[r]:(n=new Variante(this),await n.load(r,a),this.varianti[r]=n),i&&(i.des&&(n.des=i.des),i.vdef&&(n.vdef=i.vdef)),n}async varcompila(t,e){const a=new Variante(this);if(await a.load(t,this.cat,!0),a.alias){(await this.getalias())[t]=a.alias}e("variants",{cod:t,des:a.des||"",alias:a.alias,info:a.alias?"":JSON.stringify(getOggetto(a,["amb"]))})}async macrocompila(t,e){const a=new Macro(this,t);await a.loadAndCompile(`${t}.mu`);const s=a.getmacro();e("macros",{cod:t,info:JSON.stringify(s),isgenera:a.isgenera,isheader:a.isheader,iscodice:a.iscodice})}async barrecompila(t,e,a){const s=new CodiceBarra;await s.compila(t,e);for(const t in s.barre){a("barcodes",{cod:t,des:"",info:JSON.stringify(s.barre[t])})}return s}async tojson(t){let e;return a&&(e=await a("json",t)),e}async compila(t,e){if(e){for(const a of t.var)await this.varcompila(a,e);for(const a of t.mu)await this.macrocompila(a,e);if(e("infos",{cod:"info",des:t.cat,info:JSON.stringify({cat:t.cat,md:t.info})}),this.#a=void 0,this.#s=void 0,this.#i=void 0,this.#r=void 0,s){const t=await s("headers",this.cat,["_headers","_alias","_deriva","_typos"]);this.parseheaderfrominfo(t)}this.#a?e("infos",{cod:"headers",des:"",info:JSON.stringify(this.#a)}):logga("missing headers"),this.#s&&e("infos",{cod:"alias",des:"",info:JSON.stringify(this.#s)}),this.#i&&e("infos",{cod:"deriva",des:"",info:JSON.stringify(this.#i)}),this.#r&&e("infos",{cod:"typos",des:"tipologie",info:JSON.stringify(this.#r)})}}async checkvarianti(e,a){if(!e||!a?.length)return;e=checkname(e),await this.#n(e);const s=this.varelenco[e],i=[];for(let t of a){t=clean(t,!0);const a=`${e}/${t}`;this.varianti[a]||s&&s.includes(t)&&i.push(t)}if(i.length&&t){const a=await t(e,i);if(a&&a.length)for(const t of a){const{name:a,content:s}=t,i=new Variante(this);i.setheader(a,e),s&&await i.loadContentExtended(s),this.varianti[i.key]=i}}}async getheaderfromdb(e){const a=await s("header",this.cat,e,!this.#i);let{head:i,rows:r,macros:n,deriva:o,llvars:c}=a;for(const t of r)t.cod=clean(t.cod),t.alias=clean(t.alias),t.t=clean(t.t);if(!c){c=new Set;for(const t of r)if("p"==t.tipo);else{const e=t.alias?t.alias:t.cod;c.add(e)}c=[...c]}this.#i||(this.#i=o),await this.#n(this.cat),i.cod=clean(i.cod),i.rule=clean(i.rule),i.ruledef=i.ruledef||[];const l=[],u=this.varelenco[this.cat];for(const t of c)this.varianti[`${this.cat}/${t}`]||u&&u.includes(t)&&l.push(t);if(l.length&&t){const e=await t(this.cat,l);if(e&&e.length)for(const t of e){const{name:e,content:a}=t,s=new Variante(this);s.setheader(e,this.cat),a&&await s.loadContentExtended(a),this.varianti[s.key]=s}}return{head:i,rows:r,macros:n}}async getlinkedmacros(t,a){const getkey=t=>t.includes("/")?t:`${this.cat}/${t}`,s=[];let i;if(t&&(i=getkey(t),this.macro[i]||s.push(t)),a&&"string"==typeof a){const t=a.split(";");for(const e of t)i=getkey(e),this.macro[i]||s.push(e)}if(s&&s.length>0&&e){const t=await e(this.cat,s);if(t&&t.length>0)for(const e of t){this.checkscripts(e.content?.linkscript),delete e.content?.linkscript;const t=new Macro(this,e.name);for(const a in e.content){const s=e.content[a];t[a]=s}this.macro[t.key]=t}}}checkscripts(t){if(Array.isArray(t)&&t.length)for(let e of t)this.scripts[e.name]||(this.scripts[e.name]=e.value)}async setruleheader(t,e,a){const{name:s,cat:i}=checkmu(t,this.cat);a&&a.length&&(this.ruleset=toruleset(a));const r=`${i}/${s}`;if(!this.macro[r]){const e=await this.getheaderfromdb(s),{head:a,rows:o,macros:c}=e;await this.getlinkedmacros(a.rule,c);const l=new Macro(this,s);if(!a)return void n.add("Missing rule: "+t);if(a.rule){const t=this.macro[`${i}/${a.rule}`];if(t)for(const e in t)["cat","name","key"].includes(e)||(l[e]=t[e])}o&&o.length&&(l.head=o),this.macro[r]=l}this.ruleheader=r;const o=this.macro[r];return n.azzera(),await o.setparametri(e),o}getruleheader(){return this.macro[this.ruleheader]}async setvariante(t,e){return await impostavariante(this,null,t,e)}async valuta(t){let e;return"string"==typeof t&&(t=muClean(muClComments(t,this.righevuote))),Array.isArray(t)&&(logga("m1",t),e=await muEval(this,null,t)),e}setinfos(t){t&&(this.#a=t.headers,this.#s=t.alias,this.#i=void 0,this.#r=t.typos)}async splitteroggetti(t){let e=await this.getvariante(t),a=[];return e?.rows&&Object.values(e.rows).forEach((t=>{a.push({tipo:t.v[2]||"",cod:t.v[0]||"",des:t.v[1]||"",macro:t.v[4]||"",sps:parseInt(t.v[3])||0,isshape:parseInt(t.v[5])})})),a.length||a.push({tipo:"avob",cod:"__",des:"Vuoto",macro:"",sps:0}),a}}function toJson(t){return JSON.stringify(t,null,2)}function clamp(t,e=-1/0,a=1/0){return(t=Number(t)||0)<e&&(t=e),t>a&&(t=a),t}function gettipocolonna(t){return k.find((e=>e.cod==t))?.des||k[0].des}function gettipofolder(t){return k.find((e=>e.cod==t))?.folder||""}function newVariabile(){return new Variabile}async function newVariante(t,e,a){const s=new Variante(a);return await s.load(t,e),s}function newAmbiente(t,e=100){return new Ambiente(t,e)}function newMacro(t,e){return new Macro(t,e)}function muValuta(t,e,a){a&&t.azzera();return t.valuta(e)}function muInit(t,e,a,s,i,r,n){const o=new Ambiente(t);return setcallbacks(e,a,s,i,r,n),o}function muCompileScript(t){return t&&"object"==typeof t?t:t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]")?JSON.stringify(t):muClean(muClComments(t))}async function muEvalScript(t,e,a,s=!0){if(e=muCompileScript(e),s&&t.azzera(),a)for(const e of a){const{v:a,o:s}=getcouple(e);t.vari.add(a,s)}return{output:await muEval(t,null,e,{}),vari:t.vari.dictionary,errori:n}}const tonum=(t,e=-1)=>{if(!t)return 0;let a=0;if("number"==typeof t)a=t||0;else if("string"==typeof t){const e=(t=t.replaceAll(",",".")).match(/^-?[0-9.]+$/);a=e&&e.length>0?Number(e[0])||0:muCalc(t)}if(e>=0)switch(e){case 0:a=Math.round(a);break;case 1:a=Math.round(10*a)/10;break;case 2:a=Math.round(100*a)/100;break;case 3:a=Math.round(1e3*a)/1e3;break;case 4:a=Math.round(1e4*a)/1e4;break;case 5:a=Math.round(1e5*a)/1e5;break;case 6:a=Math.round(1e6*a)/1e6}return a||0};Date.prototype.toInt||(Date.prototype.toInt=function(){const t=this;return t.getDate()+100*(t.getMonth()+1)+1e4*t.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 x={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,n as errori,fromjson,getOggetto,getcolonne,getcouple,geterrdes,getheaddims,gettipocolonna,gettipofolder,hash,impostavariante,intvaluta,isJsonStr,isObject,muInit as jsTest,logga,muCalc,muClComments,muClean,muCompileScript,muEval,muEvalScript,muGenerate,muInit,muLimits,muParsecode,muValuta,x as mustr,newAmbiente,newMacro,newVariabile,newVariante,noquote,parselimitifromdb,parselimitifromrule,parsevar,poppars,pushpars,quote,seedarray,seeder,setOggetto,sortrows,testsync,k as tipicolonna,w as tipifree,y as tipiheader,tk,toCadPars,toJson,tonum,xdt};
|