croswil_markuno 2.1.25 → 2.1.27

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/mu-convcad.js CHANGED
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import{init as e,database as t}from"croswil_lib";import o from"fs";import r from"path";import i from"minimist";function s(e,t=!1){e=String(e||"");const o=/^(\d+)\.\.(\d+)$/.exec(e);if(o){let e=parseInt(o[1]),t=parseInt(o[2]);const r=[];e>t&&([e,t]=[t,e]);for(let o=e;o<=t;o++)r.push(o+"");return r}if(!/["({[]/.test(e))return e.split(/[,;]/).map((e=>e.trim()));const r=[];let i="",s=0,a=!1;for(let l=0;l<e.length;l++){const t=e[l];if(0===s&&'"'===t&&(0!==l&&"\\"===e[l-1]||(a=!a)),a||("("===t||"["===t||"{"===t?s++:")"!==t&&"]"!==t&&"}"!==t||(s=Math.max(0,s-1))),","!==t&&";"!==t||0!==s||a)i+=t;else{const e=i.trim();r.push(e),i=""}}const n=i.trim();return n&&r.push(n),r.map((e=>(e=e.trim(),!t&&(e.startsWith('"')&&e.endsWith('"')||e.startsWith("(")&&e.endsWith(")"))?e.slice(1,-1):e)))}function a(e,t){const o=(e=>e.replace(/("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*')|\/\*[\s\S]*?\*\//g,((e,t)=>t||"")))(e).split(/\r?\n/),r=[];let i="";for(const s of o){let e=s;if(/(^|[^:])\/\/.*/.test(e)&&(e=e.replace(/(^|[^:])\/\/.*/,((e,t)=>t.trim()))),e=e.trim(),0!==e.length)if(i.length>0&&(e=i+" "+e,i=""),e.endsWith("\\")){e=e.slice(0,-1);const t=e.lastIndexOf("//");-1!==t&&(e=e.slice(0,t).trim()),i=e}else r.push(e)}return r}new class{constructor(){this.azzera()}azzera(){this.err=[]}add(e,t){this.err.push({msg:e,row:t})}get(){return this.err}get length(){return this.err.length}toString(){const e=[];for(const t of this.err){const o="object"==typeof t.msg?JSON.stringify(t.msg):t.msg||"";e.push(`${t.row?t.row+":":""}${o}`)}return e.join("\n")}};const n=/^\s*\{(:)?(var|deriva|valid|formula|header|genera|g|v|f|h)(\s.*)?\}/i;function l(e,t){let o=!1;const r=[];for(let i=e;i<t.length;i++){const e=t[i].trim();let a=e.split("//")[0].trim();if(e.startsWith("/*"))o=!0;else if(o&&e.endsWith("*/"))o=!1;else if(!o){if(n.test(e))return{fl:!0,i2:i-1,cols:r};if(a.endsWith("\\"))return{fl:!1};if(e.startsWith(":h ")&&(a=a.substr(3).trim()),!a.startsWith(":")){const e=s(a);for(let t=0;t<e.length;t++){let o=e[t].length;e[t].includes(",")&&(o+=2),(!r[t]||r[t]<o)&&(r[t]=o)}}}}return{fl:!0,i2:t.length-1,cols:r}}Date.prototype.toInt||(Date.prototype.toInt=function(){const e=this;return e.getDate()+100*(e.getMonth()+1)+1e4*e.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{Clear:c,Reset:d,Bold:p,Reverse:h,Red:f,Green:u,Yellow:m,Blue:v,Magenta:g,Cyan:$,White:b}=e();var w={FOLDERBASE:"./",DBWORK:"./data/app.db",FOLDERCAT:"./data/mu",FOLDEROUT:"./out",CAT:"cat"};const C=".lasts.markuno";o.existsSync(C)&&(w=JSON.parse(o.readFileSync(C))),w.FOLDERCAD||(w.FOLDERCAD="./cat3cad");var L=i(process.argv);console.log(`----------------------------------------------------------------------------------------\n${p}${$}${p}mu-convcad:${d} Convert data from 3CAD (c) Croswil 2024 v. ${m}2.1.33${d}\n----------------------------------------------------------------------------------------`);const F=`uso: ${p} mu-convcad <nomecatalogo> [opzioni]\n${u}Opzioni:${d}\n ${b} -h, --help${d}${u} mostra l'help\n ${b} -i, --init <folder>${d}${u} cartella di lavoro (default='${w.FOLDERCAT}' ) \n ${b} -c, --cad <folder>${d}${u} cartella cad (default='${w.FOLDERCAD}' ) \n ${b} -r, --reset${d}${u} Cancella tutti i dati precedenti\n ${b} -t, --tipologie${d}${u} Tipologie e Macro tip\n ${b} -a, --abilita${d}${u} Processa abilitazioni\n`;w.FOLDERCAT=L.i||L.init||w.FOLDERCAT,w.FOLDERCAD=L.c||L.cad||w.FOLDERCAD;const S=L._[2]||void 0;(L.h||L.help||!S)&&(console.log(F),process.exit(0)),w.CAT=S;const y=r.join(w.FOLDERCAT,S),D=r.join(w.FOLDERCAD,S);var E=r.join(D,`${S}.ddb`);o.existsSync(E)||(console.log("manca il database di origine: "+S),process.exit(1)),o.writeFileSync(C,JSON.stringify(w,null,2));const j=[],O=e=>j.push(e),A="select cod cod,des des,memo info from speciali where cat='pro'";function W(e){var t=[];for(var o of e)!o.startsWith('"')&&o.includes(",")&&(o=`"${o}"`),t.push(o);return t.join(",")}function R(e,t){var o=(e=e.replaceAll("\t",",").replaceAll("\r","").replace(/\#vb/gim,"/* VB !not supported").replace(/#endvb/gim,"*/").replace(/\#msg /gim,"!msg ")).split("\n"),r=[],i=!1;return o.forEach(((e,o)=>{e.startsWith("/*")&&(i=!0),i?r.push(e):/^\s*$/.test(e)||(t?(e=e.replace(/\s*\#m\s+(\w+)/im,((e,t)=>"#m ++"+t)),r.push(e)):(/^\s*\d+/.test(e)?e="!t "+e.trim():/^\s*\!parametri/i.test(e)?e=e.replace(/\!parametri /gi,":p "):/^\s*\w+/.test(e)&&(e="#m +"+e.replace(/\s*\_*/,"")),r.push(e))),i&&e.trim().endsWith("*/")&&(i=!1)})),function(e){const t=e.split("\n"),o=[];let r,i=0,a=!1,c=!1,d=[];if(r){const e=l(0,t);r=e.fl,r&&(d=e.cols)}for(let p=0;p<t.length;p++){const e=t[p];let h=e.trim();const f=h.split("//");let u=f[0].trim();f.splice(0,1);const m=f.length?` // ${f.join("//").trim()} `:"";if(h.startsWith("/*"))a=!0,o.push(h);else if(a&&h.endsWith("*/"))a=!1,o.push(h);else if(a)o.push(e);else{const e=n.exec(h);if(e){if(o.push(h),i=e[1]?0:1,/^\s*\{(var|deriva|header|v|h)(\s.*)?\}/i.test(h)){const e=l(p+1,t);r=e.fl,r&&(d=e.cols)}else r=!1;c=!1;continue}if(r)if(u.startsWith(":")&&!u.startsWith(":h ")||!u)o.push(h);else{let e=" ";u.startsWith(":h ")&&(u=u.substr(3).trim(),e=":h ");const t=s(u);for(let o=0;o<t.length;o++)t[o].includes(",")&&(t[o]=`"${t[o]}"`),t[o]=t[o].padEnd(d[o]," ");o.push(`${e}${t.join(" , ")} ${m}`)}else{const e=" ".repeat(i>=0?i:0);if(c)o.push(`${e} ${h}`);else{let t="";h.startsWith("#")&&(t=h.substring(1).split(" ")[0].toUpperCase(),h="#"+t+h.substring(t.length+1)),["IF","IFDEF","IFNDEF"].includes(t)?h.indexOf("#",2)<0?(o.push(`${e}${h}`),i++):(h=h.replace(/#([\w]+)/g,((e,t)=>"#"+t.toUpperCase())),o.push(`${e}${h}`)):["FOR","SELECT","FORVAR","VARIANTE","DO"].includes(t)?(o.push(`${e}${h}`),i++):["ELSEIF","ELSE","ELSEIFDEF","ELSEIFNDEF","CASE","CASES","DEFAULT"].includes(t)&&i>0?o.push(" ".repeat(i>0?i-1:0)+h):["ENDIF","ENDSELECT","LOOP","ENDFOR"].includes(t)?(o.push(" ".repeat(i>0?i-1:0)+h),i--,i<0&&(i=0)):h.startsWith("_ ")||h.startsWith(":")?o.push(h):o.push(e+h)}c=u.endsWith("\\")}}}return o.join("\n")}(r.join("\n"))}const x={"-":"sep",T:"var",M:"num",S:"str",C:"yn",L:"hidden",Z:"ny"};function z(e){var t=[];if(!e)return"";for(var o in e)"cod"!=o&&t.push(`${o}=${e[o]}`);return`${e.cod} ${t.join(",")}`}function T(e){var t=e.split(",");if(t[1]||t[2]){var o={};return o.cod=(t[2]||t[1]).trim().toLowerCase(),t[2]&&(o.alias=t[2].trim().toLowerCase()),t[3]&&(o.valid=t[3].trim().toLowerCase()),t[4]&&(o.des=t[4].trim()),t[5]&&(o.visible=t[5].trim().toLowerCase()),x[t[0]]?o.tipo=x[t[0]]:"D"==t[0]?o.tipo="sp."+t[6]:o.tipo=t[0].trim().toUpperCase(),o}}L.r||L.reset?console.log("-> crea catalogo e copia"):console.log("-> aggiorna catalogo");var I=`${w.FOLDERCAT}/mu_${S}.db`;(L.r||L.reset)&&(o.existsSync(y)&&o.rmSync(y,{recursive:!0}),o.existsSync(I)&&o.unlinkSync(I)),o.existsSync(y)||o.mkdirSync(y,{recursive:!0}),o.copyFileSync(E,y+"/"+S+".db");var _=t.db(E),k=(new Date).valueOf(),M=[],N=_.all("select cod cod,des des ,codmet alias,obbl obbligo, memo info from codvar ");for(var B of(console.log("-> varianti",N.length),N)){for(var U=B.info.split(""),J=[],V=[],Y=1;Y<U.length&&U[Y];Y+=2)V.push(U[Y]);if(J.push(`:des ${B.des.trim().toLowerCase()}`),B.obbl&&J.push(":obbligo"),B.alias)M.push(`${B.cod.trim().toLowerCase()} , ${B.alias.trim().toLowerCase()}`);else{J.push(""),J.push(":h "+W(V));var G=_.all("select codopz cod,des des,memo info from varianti where codvar=? order by ordinamento,codopz",B.cod);for(var P of G)V=W([P.cod.trim().toLowerCase(),P.des.trim().toLowerCase(),...P.info.trim().toLowerCase().split("\t")]),J.push(" "+V);B.cod=B.cod.trim().toLowerCase(),O("var: "+B.cod),o.writeFileSync(`${y}/${B.cod}.var`,J.join("\n"))}}for(var B of(N=_.all("select cod cod,des des,fldef defs from modelli order by cod"),(J=[]).push(":des Modelli\n\n:h Cod, Descrizione\n"),N))J.push(" "+W([B.cod.trim().toLowerCase(),B.des]));o.writeFileSync(`${y}/modelli.var`,J.join("\n")),M=["// Alias Varianti\n\n{v __aliasvar}\n:h variante, alias",...M.sort()],o.writeFileSync(`${y}/_alias.inc`,M.join("\n")),console.log("-> gruppi.ini");var H=r.join(D,"gruppi.ini");if(o.existsSync(H)){N=a(re=o.readFileSync(H).toString().replaceAll("�","'"));var K={},Z=[];for(var B of N)(de=/^\s*\[(\w+)\]/i.exec(B))?(Z=[],K[de[1].trim().toLowerCase()]=Z):(he=T(B))&&Z.push(z(he))}var q=Object.keys(K).sort();for(var Q of((J=[]).push("// includes headers"),q))J.push(""),J.push(`{h ${Q}}`),J.push(...K[Q]);if(o.writeFileSync(r.join(y,"_headers.inc"),J.join("\n")),console.log("-> deriva"),(B=_.get(`${A} and cod='deriva'`)).cod&&B.info){B.info=B.info.trim().toLowerCase().replaceAll("","\n");var X=B.info.split("\n").map((e=>e.trim())).sort();o.writeFileSync(r.join(y,"_deriva.inc"),`// derivazione varianti \n{v deriva}\n:des deriva delle varianti\n :h var=opz,-> var=opz\n \n${X.join("\n")}`)}for(var B of(N=_.all(`${A} and cod like ?`,">>%"),console.log("-> macro",N.length),N)){O("mac "+(ge=(ge=B.cod.substr(2).trim().toLowerCase()).replace(/^_*/,"")));var ee=R(B.info.toLowerCase());J=`// ${B.des}\n${ee} \n `,o.writeFileSync(r.join(y,`+${ge}.mu`),J)}var te=o.readdirSync(D);te=te.filter((e=>e.toLowerCase().endsWith(".erg")));var oe=0;for(var N of(console.log("-> regole",te.length),te)){var re=o.readFileSync(r.join(D,N)).toString().replaceAll("\r",""),ie=r.extname(N),se=r.basename(N,ie).trim().toLowerCase();if(!se.includes(".")&&"gene"!=se){var ae={cod:se,des:"",codice:[],header:[],formule:{}},ne=[],le=(J=re.split("\n"),-1);for(var ce of J){var de;if(de=/^\s*\[(\w+)\]/.exec(ce)){var pe=de[1].toLowerCase();switch(pe){case"info":le=0;break;case"gene":le=1;break;case"grafica":le=2;break;default:ne=[],ae.formule[pe]=ne,le=3}}else 0==le?/^\s*descrizione\s*=/i.test(ce)&&(ae.des=ce.split("=")[1].trim().toLowerCase()):1==le?ce.trim()&&ae.header.push(ce):2==le?ae.codice.push(ce):ne.push(ce)}if(ae.tm=a(ae.codice.join("\n")),ae.tm.length){if(J=[`// rule ${ae.cod}\n :des ${ae.des||ae.cod}\n `],ae.header.length){for(var B of(J.push("{header}"),ae.header)){var he;(he=T(B))&&("G"==he.tipo?(delete he.tipo,J.push(`:g ${z(he)}`)):he.tipo.length>1&&J.push(z(he)))}J.push("{:header}")}for(var fe in ae.formule)X=R((ue=ae.formule[fe]).join("\n")),J.push(`\n{f ${fe}}\n${X}\n{:f}`);var ue=ae.codice.join("\n");J.push(R(ue)),o.writeFileSync(r.join(y,se+".mu"),J.join("\n")),O(`reg ${++oe}: ${ae.cod} - ${ae.des}`)}}}if(L.t||L.tipologie){N=(B=_.get(`${A} and cod=?`,"tipologie")).info.split("").sort(),console.log("-> tipologie",N.length);var me={};for(var ve of N)(ce=(P=ve.trim().toLowerCase()).split(",")[0].trim())&&(ce.includes(".")?me[(B=ce.split("."))[0]]?me[B[0]][B[1]]=P:console.log("errore tipo",ce):(me[ce]={v:P},(B=_.get(`${A} and cod=?`,`db_${ce}`)).info&&(me[ce].db=R(B.info.trim().toLowerCase().replaceAll("","\n"),!0)),(B=_.get(`${A} and cod=?`,`ll_${ce}`)).info&&(me[ce].list=R(B.info.trim().toLowerCase().replaceAll("","\n"),!0))));for(var B of(o.writeFileSync(y+"/typos.json",JSON.stringify(me,null,2)),N=_.all(`${A} and cod like ?`,"M>%"),console.log("-> macro tip",N.length),N)){var ge;O("macdb "+(ge=B.cod.substr(2).trim().toLowerCase())),ee=R(B.info.toLowerCase(),!0),J=`// ${B.des}\n${ee} \n `,o.writeFileSync(r.join(y,`++${ge}.mu`),J)}}if(L.a||L.abilita){function Oe(e){for(var t=[],o="";;){var r=e.lastIndexOf(",",100);if(e.length<100||r<0){t.push(o+e),o.length&&t.push("");break}t.push(o+e.substr(0,r)+", \\"),o=" ",e=e.substr(r+1)}return t.join("\n")}function Ae(e){var t=e.toLowerCase().split(";"),o=e=>e?[...new Set(e.split("*").sort().filter((e=>e.trim())))].join(","):"";return{abilit:o(t[0]),scons:o(t[1]),obs:o(t[2])}}console.log("-> abilitazioni"),q={};var $e=(N=_.all("select var var,abilit abilit,codart codart from valartopz order by var,abilit")).length;for(var B of N)if(B.var&&B.abilit&&B.codart){var be=B.var.trim().toLowerCase(),{abilit:we,scons:Ce,obs:Le}=Ae(B.abilit),Fe=B.codart.trim().toLowerCase();q[be]||(q[be]={}),(De=q[be])[we]||(De[we]={scons:Ce,obs:Le,neutri:[],art:[],mod:[]}),De[we].neutri.push(Fe)}var Se=(N=_.all("select var var,abilit abilit,codmod codart from valmodopz order by var,abilit")).length;for(var B of N)if(B.var&&B.abilit&&B.codart){be=B.var.trim().toLowerCase();var{abilit:we,scons:Ce,obs:Le}=Ae(B.abilit);Fe=B.codart.trim().toLowerCase(),q[be]||(q[be]={}),(De=q[be])[we]||(De[we]={scons:Ce,obs:Le,neutri:[],art:[],mod:[]}),De[we].mod.push(Fe)}var ye=(N=_.all("select var var,abilit abilit,cod codart from valmodartopz order by var,abilit")).length;for(var B of N)if(B.var&&B.abilit&&B.codart){be=B.var.trim().toLowerCase();var De,{abilit:we,scons:Ce,obs:Le}=Ae(B.abilit);Fe=B.codart.trim().toLowerCase(),q[be]||(q[be]={}),(De=q[be])[we]||(De[we]={scons:Ce,obs:Le,neutri:[],art:[],mod:[]}),De[we].art.push(Fe)}for(var be in console.log("-> ab trasforma",$e,Se,ye),q)if(o.existsSync(r.join(y,be+".var"))){J=[];var Ee=q[be];for(var je in Ee)X=Ee[je],J.push("\n\n{limit}"),X.neutri.length&&J.push(Oe(":neutri "+X.neutri.join(","))),X.art.length&&J.push(Oe(":art "+X.art.join(","))),X.mod.length&&J.push(Oe(":mod "+X.mod.join(","))),X.obs&&J.push(Oe(":obs "+X.obs)),X.scons&&J.push(Oe(":scons "+X.obs)),J.push(Oe(":opz "+je));o.writeFileSync(r.join(y,be+".var.txt"),J.join("\n"))}}k=(new Date).valueOf()-k,console.log("Tempo: ",k+"ms"),_.chiudi();
2
+ import{init as e,database as t}from"croswil_lib";import o from"fs";import r from"path";import i from"minimist";function s(e,t=!1){e=String(e||"");const o=/^(\d*)\.\.(\d*)$/.exec(e);if(o){let e=parseInt(o[1])||0,t=parseInt(o[2])||0;const r=[];for(let o=e;o<=t;o++)r.push(o+"");return r}if(!/["({[]/.test(e))return e.split(/[,;]/).map((e=>e.trim()));const r=[];let i="",s=0,a=!1;for(let l=0;l<e.length;l++){const t=e[l];if(0===s&&'"'===t&&(0!==l&&"\\"===e[l-1]||(a=!a)),a||("("===t||"["===t||"{"===t?s++:")"!==t&&"]"!==t&&"}"!==t||(s=Math.max(0,s-1))),","!==t&&";"!==t||0!==s||a)i+=t;else{const e=i.trim();r.push(e),i=""}}const n=i.trim();return n&&r.push(n),r.map((e=>(e=e.trim(),!t&&(e.startsWith('"')&&e.endsWith('"')||e.startsWith("(")&&e.endsWith(")"))?e.slice(1,-1):e)))}function a(e,t){const o=(e=>e.replace(/("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*')|\/\*[\s\S]*?\*\//g,((e,t)=>t||"")))(e).split(/\r?\n/),r=[];let i="";for(const s of o){let e=s;if(/(^|[^:])\/\/.*/.test(e)&&(e=e.replace(/(^|[^:])\/\/.*/,((e,t)=>t.trim()))),e=e.trim(),0!==e.length)if(i.length>0&&(e=i+" "+e,i=""),e.endsWith("\\")){e=e.slice(0,-1);const t=e.lastIndexOf("//");-1!==t&&(e=e.slice(0,t).trim()),i=e}else r.push(e)}return r}new class{constructor(){this.azzera()}azzera(){this.err=[]}add(e,t){this.err.push({msg:e,row:t})}get(){return this.err}get length(){return this.err.length}toString(){const e=[];for(const t of this.err){const o="object"==typeof t.msg?JSON.stringify(t.msg):t.msg||"";e.push(`${t.row?t.row+":":""}${o}`)}return e.join("\n")}};const n=/^\s*\{(:)?(var|deriva|valid|formula|header|genera|g|v|f|h)(\s.*)?\}/i;function l(e,t){let o=!1;const r=[];for(let i=e;i<t.length;i++){const e=t[i].trim();let a=e.split("//")[0].trim();if(e.startsWith("/*"))o=!0;else if(o&&e.endsWith("*/"))o=!1;else if(!o){if(n.test(e))return{fl:!0,i2:i-1,cols:r};if(a.endsWith("\\"))return{fl:!1};if(e.startsWith(":h ")&&(a=a.substr(3).trim()),!a.startsWith(":")){const e=s(a);for(let t=0;t<e.length;t++){let o=e[t].length;e[t].includes(",")&&(o+=2),(!r[t]||r[t]<o)&&(r[t]=o)}}}}return{fl:!0,i2:t.length-1,cols:r}}Date.prototype.toInt||(Date.prototype.toInt=function(){const e=this;return e.getDate()+100*(e.getMonth()+1)+1e4*e.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{Clear:c,Reset:d,Bold:p,Reverse:h,Red:f,Green:u,Yellow:m,Blue:v,Magenta:g,Cyan:$,White:b}=e();var w={FOLDERBASE:"./",DBWORK:"./data/app.db",FOLDERCAT:"./data/mu",FOLDEROUT:"./out",CAT:"cat"};const C=".lasts.markuno";o.existsSync(C)&&(w=JSON.parse(o.readFileSync(C))),w.FOLDERCAD||(w.FOLDERCAD="./cat3cad");var L=i(process.argv);console.log(`----------------------------------------------------------------------------------------\n${p}${$}${p}mu-convcad:${d} Convert data from 3CAD (c) Croswil 2024 v. ${m}2.1.34${d}\n----------------------------------------------------------------------------------------`);const F=`uso: ${p} mu-convcad <nomecatalogo> [opzioni]\n${u}Opzioni:${d}\n ${b} -h, --help${d}${u} mostra l'help\n ${b} -i, --init <folder>${d}${u} cartella di lavoro (default='${w.FOLDERCAT}' ) \n ${b} -c, --cad <folder>${d}${u} cartella cad (default='${w.FOLDERCAD}' ) \n ${b} -r, --reset${d}${u} Cancella tutti i dati precedenti\n ${b} -t, --tipologie${d}${u} Tipologie e Macro tip\n ${b} -a, --abilita${d}${u} Processa abilitazioni\n`;w.FOLDERCAT=L.i||L.init||w.FOLDERCAT,w.FOLDERCAD=L.c||L.cad||w.FOLDERCAD;const S=L._[2]||void 0;(L.h||L.help||!S)&&(console.log(F),process.exit(0)),w.CAT=S;const y=r.join(w.FOLDERCAT,S),D=r.join(w.FOLDERCAD,S);var E=r.join(D,`${S}.ddb`);o.existsSync(E)||(console.log("manca il database di origine: "+S),process.exit(1)),o.writeFileSync(C,JSON.stringify(w,null,2));const j=[],O=e=>j.push(e),A="select cod cod,des des,memo info from speciali where cat='pro'";function W(e){var t=[];for(var o of e)!o.startsWith('"')&&o.includes(",")&&(o=`"${o}"`),t.push(o);return t.join(",")}function R(e,t){var o=(e=e.replaceAll("\t",",").replaceAll("\r","").replace(/\#vb/gim,"/* VB !not supported").replace(/#endvb/gim,"*/").replace(/\#msg /gim,"!msg ")).split("\n"),r=[],i=!1;return o.forEach(((e,o)=>{e.startsWith("/*")&&(i=!0),i?r.push(e):/^\s*$/.test(e)||(t?(e=e.replace(/\s*\#m\s+(\w+)/im,((e,t)=>"#m ++"+t)),r.push(e)):(/^\s*\d+/.test(e)?e="!t "+e.trim():/^\s*\!parametri/i.test(e)?e=e.replace(/\!parametri /gi,":p "):/^\s*\w+/.test(e)&&(e="#m +"+e.replace(/\s*\_*/,"")),r.push(e))),i&&e.trim().endsWith("*/")&&(i=!1)})),function(e){const t=e.split("\n"),o=[];let r,i=0,a=!1,c=!1,d=[];if(r){const e=l(0,t);r=e.fl,r&&(d=e.cols)}for(let p=0;p<t.length;p++){const e=t[p];let h=e.trim();const f=h.split("//");let u=f[0].trim();f.splice(0,1);const m=f.length?` // ${f.join("//").trim()} `:"";if(h.startsWith("/*"))a=!0,o.push(h);else if(a&&h.endsWith("*/"))a=!1,o.push(h);else if(a)o.push(e);else{const e=n.exec(h);if(e){if(o.push(h),i=e[1]?0:1,/^\s*\{(var|deriva|header|v|h)(\s.*)?\}/i.test(h)){const e=l(p+1,t);r=e.fl,r&&(d=e.cols)}else r=!1;c=!1;continue}if(r)if(u.startsWith(":")&&!u.startsWith(":h ")||!u)o.push(h);else{let e=" ";u.startsWith(":h ")&&(u=u.substr(3).trim(),e=":h ");const t=s(u);for(let o=0;o<t.length;o++)t[o].includes(",")&&(t[o]=`"${t[o]}"`),t[o]=t[o].padEnd(d[o]," ");o.push(`${e}${t.join(" , ")} ${m}`)}else{const e=" ".repeat(i>=0?i:0);if(c)o.push(`${e} ${h}`);else{let t="";h.startsWith("#")&&(t=h.substring(1).split(" ")[0].toUpperCase(),h="#"+t+h.substring(t.length+1)),["IF","IFDEF","IFNDEF"].includes(t)?h.indexOf("#",2)<0?(o.push(`${e}${h}`),i++):(h=h.replace(/#([\w]+)/g,((e,t)=>"#"+t.toUpperCase())),o.push(`${e}${h}`)):["FOR","SELECT","FORVAR","VARIANTE","DO"].includes(t)?(o.push(`${e}${h}`),i++):["ELSEIF","ELSE","ELSEIFDEF","ELSEIFNDEF","CASE","CASES","DEFAULT"].includes(t)&&i>0?o.push(" ".repeat(i>0?i-1:0)+h):["ENDIF","ENDSELECT","LOOP","ENDFOR"].includes(t)?(o.push(" ".repeat(i>0?i-1:0)+h),i--,i<0&&(i=0)):h.startsWith("_ ")||h.startsWith(":")?o.push(h):o.push(e+h)}c=u.endsWith("\\")}}}return o.join("\n")}(r.join("\n"))}const x={"-":"sep",T:"var",M:"num",S:"str",C:"yn",L:"hidden",Z:"ny"};function z(e){var t=[];if(!e)return"";for(var o in e)"cod"!=o&&t.push(`${o}=${e[o]}`);return`${e.cod} ${t.join(",")}`}function T(e){var t=e.split(",");if(t[1]||t[2]){var o={};return o.cod=(t[2]||t[1]).trim().toLowerCase(),t[2]&&(o.alias=t[2].trim().toLowerCase()),t[3]&&(o.valid=t[3].trim().toLowerCase()),t[4]&&(o.des=t[4].trim()),t[5]&&(o.visible=t[5].trim().toLowerCase()),x[t[0]]?o.tipo=x[t[0]]:"D"==t[0]?o.tipo="sp."+t[6]:o.tipo=t[0].trim().toUpperCase(),o}}L.r||L.reset?console.log("-> crea catalogo e copia"):console.log("-> aggiorna catalogo");var I=`${w.FOLDERCAT}/mu_${S}.db`;(L.r||L.reset)&&(o.existsSync(y)&&o.rmSync(y,{recursive:!0}),o.existsSync(I)&&o.unlinkSync(I)),o.existsSync(y)||o.mkdirSync(y,{recursive:!0}),o.copyFileSync(E,y+"/"+S+".db");var _=t.db(E),k=(new Date).valueOf(),M=[],N=_.all("select cod cod,des des ,codmet alias,obbl obbligo, memo info from codvar ");for(var B of(console.log("-> varianti",N.length),N)){for(var U=B.info.split(""),J=[],V=[],Y=1;Y<U.length&&U[Y];Y+=2)V.push(U[Y]);if(J.push(`:des ${B.des.trim().toLowerCase()}`),B.obbl&&J.push(":obbligo"),B.alias)M.push(`${B.cod.trim().toLowerCase()} , ${B.alias.trim().toLowerCase()}`);else{J.push(""),J.push(":h "+W(V));var G=_.all("select codopz cod,des des,memo info from varianti where codvar=? order by ordinamento,codopz",B.cod);for(var P of G)V=W([P.cod.trim().toLowerCase(),P.des.trim().toLowerCase(),...P.info.trim().toLowerCase().split("\t")]),J.push(" "+V);B.cod=B.cod.trim().toLowerCase(),O("var: "+B.cod),o.writeFileSync(`${y}/${B.cod}.var`,J.join("\n"))}}for(var B of(N=_.all("select cod cod,des des,fldef defs from modelli order by cod"),(J=[]).push(":des Modelli\n\n:h Cod, Descrizione\n"),N))J.push(" "+W([B.cod.trim().toLowerCase(),B.des]));o.writeFileSync(`${y}/modelli.var`,J.join("\n")),M=["// Alias Varianti\n\n{v __aliasvar}\n:h variante, alias",...M.sort()],o.writeFileSync(`${y}/_alias.inc`,M.join("\n")),console.log("-> gruppi.ini");var H=r.join(D,"gruppi.ini");if(o.existsSync(H)){N=a(re=o.readFileSync(H).toString().replaceAll("�","'"));var K={},Z=[];for(var B of N)(de=/^\s*\[(\w+)\]/i.exec(B))?(Z=[],K[de[1].trim().toLowerCase()]=Z):(he=T(B))&&Z.push(z(he))}var q=Object.keys(K).sort();for(var Q of((J=[]).push("// includes headers"),q))J.push(""),J.push(`{h ${Q}}`),J.push(...K[Q]);if(o.writeFileSync(r.join(y,"_headers.inc"),J.join("\n")),console.log("-> deriva"),(B=_.get(`${A} and cod='deriva'`)).cod&&B.info){B.info=B.info.trim().toLowerCase().replaceAll("","\n");var X=B.info.split("\n").map((e=>e.trim())).sort();o.writeFileSync(r.join(y,"_deriva.inc"),`// derivazione varianti \n{v deriva}\n:des deriva delle varianti\n :h var=opz,-> var=opz\n \n${X.join("\n")}`)}for(var B of(N=_.all(`${A} and cod like ?`,">>%"),console.log("-> macro",N.length),N)){O("mac "+(ge=(ge=B.cod.substr(2).trim().toLowerCase()).replace(/^_*/,"")));var ee=R(B.info.toLowerCase());J=`// ${B.des}\n${ee} \n `,o.writeFileSync(r.join(y,`+${ge}.mu`),J)}var te=o.readdirSync(D);te=te.filter((e=>e.toLowerCase().endsWith(".erg")));var oe=0;for(var N of(console.log("-> regole",te.length),te)){var re=o.readFileSync(r.join(D,N)).toString().replaceAll("\r",""),ie=r.extname(N),se=r.basename(N,ie).trim().toLowerCase();if(!se.includes(".")&&"gene"!=se){var ae={cod:se,des:"",codice:[],header:[],formule:{}},ne=[],le=(J=re.split("\n"),-1);for(var ce of J){var de;if(de=/^\s*\[(\w+)\]/.exec(ce)){var pe=de[1].toLowerCase();switch(pe){case"info":le=0;break;case"gene":le=1;break;case"grafica":le=2;break;default:ne=[],ae.formule[pe]=ne,le=3}}else 0==le?/^\s*descrizione\s*=/i.test(ce)&&(ae.des=ce.split("=")[1].trim().toLowerCase()):1==le?ce.trim()&&ae.header.push(ce):2==le?ae.codice.push(ce):ne.push(ce)}if(ae.tm=a(ae.codice.join("\n")),ae.tm.length){if(J=[`// rule ${ae.cod}\n :des ${ae.des||ae.cod}\n `],ae.header.length){for(var B of(J.push("{header}"),ae.header)){var he;(he=T(B))&&("G"==he.tipo?(delete he.tipo,J.push(`:g ${z(he)}`)):he.tipo.length>1&&J.push(z(he)))}J.push("{:header}")}for(var fe in ae.formule)X=R((ue=ae.formule[fe]).join("\n")),J.push(`\n{f ${fe}}\n${X}\n{:f}`);var ue=ae.codice.join("\n");J.push(R(ue)),o.writeFileSync(r.join(y,se+".mu"),J.join("\n")),O(`reg ${++oe}: ${ae.cod} - ${ae.des}`)}}}if(L.t||L.tipologie){N=(B=_.get(`${A} and cod=?`,"tipologie")).info.split("").sort(),console.log("-> tipologie",N.length);var me={};for(var ve of N)(ce=(P=ve.trim().toLowerCase()).split(",")[0].trim())&&(ce.includes(".")?me[(B=ce.split("."))[0]]?me[B[0]][B[1]]=P:console.log("errore tipo",ce):(me[ce]={v:P},(B=_.get(`${A} and cod=?`,`db_${ce}`)).info&&(me[ce].db=R(B.info.trim().toLowerCase().replaceAll("","\n"),!0)),(B=_.get(`${A} and cod=?`,`ll_${ce}`)).info&&(me[ce].list=R(B.info.trim().toLowerCase().replaceAll("","\n"),!0))));for(var B of(o.writeFileSync(y+"/typos.json",JSON.stringify(me,null,2)),N=_.all(`${A} and cod like ?`,"M>%"),console.log("-> macro tip",N.length),N)){var ge;O("macdb "+(ge=B.cod.substr(2).trim().toLowerCase())),ee=R(B.info.toLowerCase(),!0),J=`// ${B.des}\n${ee} \n `,o.writeFileSync(r.join(y,`++${ge}.mu`),J)}}if(L.a||L.abilita){function Oe(e){for(var t=[],o="";;){var r=e.lastIndexOf(",",100);if(e.length<100||r<0){t.push(o+e),o.length&&t.push("");break}t.push(o+e.substr(0,r)+", \\"),o=" ",e=e.substr(r+1)}return t.join("\n")}function Ae(e){var t=e.toLowerCase().split(";"),o=e=>e?[...new Set(e.split("*").sort().filter((e=>e.trim())))].join(","):"";return{abilit:o(t[0]),scons:o(t[1]),obs:o(t[2])}}console.log("-> abilitazioni"),q={};var $e=(N=_.all("select var var,abilit abilit,codart codart from valartopz order by var,abilit")).length;for(var B of N)if(B.var&&B.abilit&&B.codart){var be=B.var.trim().toLowerCase(),{abilit:we,scons:Ce,obs:Le}=Ae(B.abilit),Fe=B.codart.trim().toLowerCase();q[be]||(q[be]={}),(De=q[be])[we]||(De[we]={scons:Ce,obs:Le,neutri:[],art:[],mod:[]}),De[we].neutri.push(Fe)}var Se=(N=_.all("select var var,abilit abilit,codmod codart from valmodopz order by var,abilit")).length;for(var B of N)if(B.var&&B.abilit&&B.codart){be=B.var.trim().toLowerCase();var{abilit:we,scons:Ce,obs:Le}=Ae(B.abilit);Fe=B.codart.trim().toLowerCase(),q[be]||(q[be]={}),(De=q[be])[we]||(De[we]={scons:Ce,obs:Le,neutri:[],art:[],mod:[]}),De[we].mod.push(Fe)}var ye=(N=_.all("select var var,abilit abilit,cod codart from valmodartopz order by var,abilit")).length;for(var B of N)if(B.var&&B.abilit&&B.codart){be=B.var.trim().toLowerCase();var De,{abilit:we,scons:Ce,obs:Le}=Ae(B.abilit);Fe=B.codart.trim().toLowerCase(),q[be]||(q[be]={}),(De=q[be])[we]||(De[we]={scons:Ce,obs:Le,neutri:[],art:[],mod:[]}),De[we].art.push(Fe)}for(var be in console.log("-> ab trasforma",$e,Se,ye),q)if(o.existsSync(r.join(y,be+".var"))){J=[];var Ee=q[be];for(var je in Ee)X=Ee[je],J.push("\n\n{limit}"),X.neutri.length&&J.push(Oe(":neutri "+X.neutri.join(","))),X.art.length&&J.push(Oe(":art "+X.art.join(","))),X.mod.length&&J.push(Oe(":mod "+X.mod.join(","))),X.obs&&J.push(Oe(":obs "+X.obs)),X.scons&&J.push(Oe(":scons "+X.obs)),J.push(Oe(":opz "+je));o.writeFileSync(r.join(y,be+".var.txt"),J.join("\n"))}}k=(new Date).valueOf()-k,console.log("Tempo: ",k+"ms"),_.chiudi();
package/bin/mu-glb.js CHANGED
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import e from"fs";import o from"path";import{init as t}from"croswil_lib";import{NodeIO as n}from"@gltf-transform/core";import{ALL_EXTENSIONS as a}from"@gltf-transform/extensions";import{textureCompress as i,dedup as r,weld as s,draco as l,prune as c}from"@gltf-transform/functions";import d from"draco3dgltf";import $ from"sharp";import m from"minimist";const{Clear:u,Reset:f,Bold:g,Reverse:p,Red:w,Green:h,Yellow:b,Blue:z,Magenta:y,Cyan:S,White:C}=t(),q=(new n).registerExtensions(a).registerDependencies({"draco3d.encoder":await d.createEncoderModule(),"draco3d.decoder":await d.createDecoderModule()});var x=m(process.argv);console.log("----------------------------------------------------------------------------------------"),console.log(`${g}${S}${g}mu-glb:${f} Info/Compressione files GLB e immagini (c) Croswil 2025 v. ${b}2.1.33${f}`),console.log("----------------------------------------------------------------------------------------");let N=1024;if(x.s||x.size){const e=parseInt(x.s||x.size,10);[256,512,1024,2048].includes(e)?N=e:console.log(`${b}Valore -s non valido. Usa 256/512/1024/2048 (default 1024).${f}`)}let O="balanced";if(void 0!==x.d||void 0!==x.draco){const e=(!0===x.d?"balanced":x.d)||(!0===x.draco?"balanced":x.draco),o=String(e).toLowerCase();["balanced","fast","small"].includes(o)?O=o:console.log(`${b}Valore -d non valido. Usa balanced|fast|small (default balanced).${f}`)}let T=(x.o||x.out||"out").toString().trim();var v=x._;function E(e){return"fast"===e?{method:"edgebreaker",encodeSpeed:8,decodeSpeed:8,quantizationVolume:"mesh",quantizePosition:14,quantizeNormal:10,quantizeTexcoord:12,quantizeColor:8,quantizeGeneric:12}:"small"===e?{method:"edgebreaker",encodeSpeed:4,decodeSpeed:5,quantizationVolume:"mesh",quantizePosition:12,quantizeNormal:8,quantizeTexcoord:10,quantizeColor:8,quantizeGeneric:10}:{method:"edgebreaker",encodeSpeed:5,decodeSpeed:5,quantizationVolume:"mesh",quantizePosition:14,quantizeNormal:10,quantizeTexcoord:12,quantizeColor:8,quantizeGeneric:12}}function M(t){const n=o.join(t,T);return e.existsSync(n)||e.mkdirSync(n,{recursive:!0}),n}function R(e,o){return e?`${((e-o)/e*100).toFixed(1)}%`:"0.0%"}async function A(t,n){const a=o.join(t,n),d=e.statSync(a).size;if(x.c||x.compress){const m=await async function(e,o,t=!0,n="balanced"){const a=await q.read(e),d=async(e,o)=>{try{await a.transform(o)}catch(t){console.warn(`${e} fallita: ${t.message}`)}};!function(e){const o=e.getRoot();for(const t of o.listNodes())t.getCamera()&&t.setCamera(null);for(const t of o.listCameras())t.dispose()}(a),t&&await d("textureCompress",i({encoder:e=>$(e).resize(o,o,{withoutEnlargement:!0}).webp({quality:88,effort:4}),targetFormat:"webp"})),await d("dedup",r()),await d("weld",s({tolerance:1e-4}));const m=function(e){const o=e.getRoot(),t=new Set(["NORMAL","TEXCOORD_0"]);for(const n of o.listMeshes())for(const e of n.listPrimitives())e.getAttribute("TANGENT")&&t.add("TANGENT"),e.getAttribute("TEXCOORD_1")&&t.add("TEXCOORD_1"),e.getAttribute("COLOR_0")&&t.add("COLOR_0"),e.getAttribute("JOINTS_0")&&e.getAttribute("WEIGHTS_0")&&(t.add("JOINTS_0"),t.add("WEIGHTS_0"));return Array.from(t)}(a),u={...E(n),preserveAttributes:m};return await d("draco",l(u)),await d("prune",c()),await q.writeBinary(a)}(a,N,!0,O),u=M(t),g=o.join(u,o.basename(n));e.writeFileSync(g,m);const p=Math.round(d/1024),w=Math.round(m.length/1024);console.log(`${b}${n} ${C}${p}K => ${w}K (${R(d,m.length)}) ${S}-> ${g}${f}`)}else console.log(`${S}${a}:${f}`),await async function(e){const o=(await q.read(e)).getRoot(),t=o.listNodes(),n=o.listMeshes(),a=o.listMaterials(),i=o.listTextures();console.log(` ${C}Nodes:${f}`),t.forEach(((e,o)=>{console.log(` ${b}${o}${f}: ${e.getName()||"(no name)"}`)})),console.log(` ${C}Meshes:${f}`),n.forEach(((e,o)=>{const t=e.listPrimitives(),n=t.reduce(((e,o)=>{const t=o.getAttribute("POSITION");return e+(t?t.getCount():0)}),0);console.log(` ${b}${o}${f}: ${e.getName()||"(no name)"} - ${t.length}/${n} vert`)})),console.log(` ${C}Materials:${f}`),a.forEach(((e,o)=>{console.log(` ${b}${o}${f}: ${e.getName()||"(no name)"} `)})),console.log(` ${C}Textures:${f}`);for(let r=0;r<i.length;r++){const e=i[r],o=await e.getImage(),t=e.getName()||"(no name)";let n=o?` ${g}${S}${Math.round(o.byteLength/1024)}Kb${C}`.slice(-20):"";console.log(` ${b}${r}${f}: ${n} ${t}`)}console.log("")}(a)}async function I(t,n){const a=o.extname(n);[".glb"].includes(a)?await A(t,n):[".png",".jpeg",".jpg",".bmp",".tif",".tiff"].includes(a.trim().toLocaleLowerCase())&&await async function(t,n){const a=o.join(t,n),i=e.statSync(a).size;if(!x.c&&!x.compress){const e=await $(a).metadata();return console.log(`${S}Image Info:${f} ${n}`),void console.log(`${C}Size:${b} ${e.width}×${e.height} ${C}Format:${b} ${e.format} ${C}Channels:${b} ${e.channels}`)}const r=M(t),s=o.basename(n,o.extname(n))+".webp",l=o.join(r,s);await $(a).resize(N,N,{withoutEnlargement:!0}).webp({quality:88,effort:4}).toFile(l);const c=e.statSync(l).size,d=Math.round(i/1048576),m=Math.round(c/1048576);console.log(`${b}${n} => .webp ${C}${d}M => ${m}M (${R(i,c)}) ${S}-> ${l}${f}`)}(t,n)}(x.h||x.help||!v[2])&&(console.log(`Uso: ${g}mu-glb <file|cartella> [opzioni]${f} \n${g}${S}Opzioni:${f}${h}\n ${C} -h, --help${f}${h} mostra l'help\n ${C} -c, --compress${f}${h} comprime GLB/immagini\n ${C} -s, --size <px>${f}${h} lato max texture (256/512/1024/2048, default 1024)\n ${C} -d, --draco <profilo>${f}${h} balanced | fast | small (default: balanced)\n ${C} -o, --out <dir>${f}${h} cartella di output (default: "out")\n${f}\n `),process.exit(0)),await async function(){var t,n=v[2].trim().toLowerCase();if(e.existsSync(n)||(t=n,console.log(`${w}${g}ERRORE! manca il file: ${C}${t||""}${f}`),process.exit(1)),e.statSync(n).isDirectory()){const o=e.readdirSync(n);for(const e of o)await I(n,e)}else await I(o.dirname(n),o.basename(n))}();
2
+ import e from"fs";import o from"path";import{init as t}from"croswil_lib";import{NodeIO as n}from"@gltf-transform/core";import{ALL_EXTENSIONS as a}from"@gltf-transform/extensions";import{textureCompress as i,dedup as r,weld as s,draco as l,prune as c}from"@gltf-transform/functions";import d from"draco3dgltf";import $ from"sharp";import m from"minimist";const{Clear:u,Reset:f,Bold:g,Reverse:p,Red:w,Green:h,Yellow:b,Blue:z,Magenta:y,Cyan:S,White:C}=t(),q=(new n).registerExtensions(a).registerDependencies({"draco3d.encoder":await d.createEncoderModule(),"draco3d.decoder":await d.createDecoderModule()});var x=m(process.argv);console.log("----------------------------------------------------------------------------------------"),console.log(`${g}${S}${g}mu-glb:${f} Info/Compressione files GLB e immagini (c) Croswil 2025 v. ${b}2.1.34${f}`),console.log("----------------------------------------------------------------------------------------");let N=1024;if(x.s||x.size){const e=parseInt(x.s||x.size,10);[256,512,1024,2048].includes(e)?N=e:console.log(`${b}Valore -s non valido. Usa 256/512/1024/2048 (default 1024).${f}`)}let O="balanced";if(void 0!==x.d||void 0!==x.draco){const e=(!0===x.d?"balanced":x.d)||(!0===x.draco?"balanced":x.draco),o=String(e).toLowerCase();["balanced","fast","small"].includes(o)?O=o:console.log(`${b}Valore -d non valido. Usa balanced|fast|small (default balanced).${f}`)}let T=(x.o||x.out||"out").toString().trim();var v=x._;function E(e){return"fast"===e?{method:"edgebreaker",encodeSpeed:8,decodeSpeed:8,quantizationVolume:"mesh",quantizePosition:14,quantizeNormal:10,quantizeTexcoord:12,quantizeColor:8,quantizeGeneric:12}:"small"===e?{method:"edgebreaker",encodeSpeed:4,decodeSpeed:5,quantizationVolume:"mesh",quantizePosition:12,quantizeNormal:8,quantizeTexcoord:10,quantizeColor:8,quantizeGeneric:10}:{method:"edgebreaker",encodeSpeed:5,decodeSpeed:5,quantizationVolume:"mesh",quantizePosition:14,quantizeNormal:10,quantizeTexcoord:12,quantizeColor:8,quantizeGeneric:12}}function M(t){const n=o.join(t,T);return e.existsSync(n)||e.mkdirSync(n,{recursive:!0}),n}function R(e,o){return e?`${((e-o)/e*100).toFixed(1)}%`:"0.0%"}async function A(t,n){const a=o.join(t,n),d=e.statSync(a).size;if(x.c||x.compress){const m=await async function(e,o,t=!0,n="balanced"){const a=await q.read(e),d=async(e,o)=>{try{await a.transform(o)}catch(t){console.warn(`${e} fallita: ${t.message}`)}};!function(e){const o=e.getRoot();for(const t of o.listNodes())t.getCamera()&&t.setCamera(null);for(const t of o.listCameras())t.dispose()}(a),t&&await d("textureCompress",i({encoder:e=>$(e).resize(o,o,{withoutEnlargement:!0}).webp({quality:88,effort:4}),targetFormat:"webp"})),await d("dedup",r()),await d("weld",s({tolerance:1e-4}));const m=function(e){const o=e.getRoot(),t=new Set(["NORMAL","TEXCOORD_0"]);for(const n of o.listMeshes())for(const e of n.listPrimitives())e.getAttribute("TANGENT")&&t.add("TANGENT"),e.getAttribute("TEXCOORD_1")&&t.add("TEXCOORD_1"),e.getAttribute("COLOR_0")&&t.add("COLOR_0"),e.getAttribute("JOINTS_0")&&e.getAttribute("WEIGHTS_0")&&(t.add("JOINTS_0"),t.add("WEIGHTS_0"));return Array.from(t)}(a),u={...E(n),preserveAttributes:m};return await d("draco",l(u)),await d("prune",c()),await q.writeBinary(a)}(a,N,!0,O),u=M(t),g=o.join(u,o.basename(n));e.writeFileSync(g,m);const p=Math.round(d/1024),w=Math.round(m.length/1024);console.log(`${b}${n} ${C}${p}K => ${w}K (${R(d,m.length)}) ${S}-> ${g}${f}`)}else console.log(`${S}${a}:${f}`),await async function(e){const o=(await q.read(e)).getRoot(),t=o.listNodes(),n=o.listMeshes(),a=o.listMaterials(),i=o.listTextures();console.log(` ${C}Nodes:${f}`),t.forEach(((e,o)=>{console.log(` ${b}${o}${f}: ${e.getName()||"(no name)"}`)})),console.log(` ${C}Meshes:${f}`),n.forEach(((e,o)=>{const t=e.listPrimitives(),n=t.reduce(((e,o)=>{const t=o.getAttribute("POSITION");return e+(t?t.getCount():0)}),0);console.log(` ${b}${o}${f}: ${e.getName()||"(no name)"} - ${t.length}/${n} vert`)})),console.log(` ${C}Materials:${f}`),a.forEach(((e,o)=>{console.log(` ${b}${o}${f}: ${e.getName()||"(no name)"} `)})),console.log(` ${C}Textures:${f}`);for(let r=0;r<i.length;r++){const e=i[r],o=await e.getImage(),t=e.getName()||"(no name)";let n=o?` ${g}${S}${Math.round(o.byteLength/1024)}Kb${C}`.slice(-20):"";console.log(` ${b}${r}${f}: ${n} ${t}`)}console.log("")}(a)}async function I(t,n){const a=o.extname(n);[".glb"].includes(a)?await A(t,n):[".png",".jpeg",".jpg",".bmp",".tif",".tiff"].includes(a.trim().toLocaleLowerCase())&&await async function(t,n){const a=o.join(t,n),i=e.statSync(a).size;if(!x.c&&!x.compress){const e=await $(a).metadata();return console.log(`${S}Image Info:${f} ${n}`),void console.log(`${C}Size:${b} ${e.width}×${e.height} ${C}Format:${b} ${e.format} ${C}Channels:${b} ${e.channels}`)}const r=M(t),s=o.basename(n,o.extname(n))+".webp",l=o.join(r,s);await $(a).resize(N,N,{withoutEnlargement:!0}).webp({quality:88,effort:4}).toFile(l);const c=e.statSync(l).size,d=Math.round(i/1048576),m=Math.round(c/1048576);console.log(`${b}${n} => .webp ${C}${d}M => ${m}M (${R(i,c)}) ${S}-> ${l}${f}`)}(t,n)}(x.h||x.help||!v[2])&&(console.log(`Uso: ${g}mu-glb <file|cartella> [opzioni]${f} \n${g}${S}Opzioni:${f}${h}\n ${C} -h, --help${f}${h} mostra l'help\n ${C} -c, --compress${f}${h} comprime GLB/immagini\n ${C} -s, --size <px>${f}${h} lato max texture (256/512/1024/2048, default 1024)\n ${C} -d, --draco <profilo>${f}${h} balanced | fast | small (default: balanced)\n ${C} -o, --out <dir>${f}${h} cartella di output (default: "out")\n${f}\n `),process.exit(0)),await async function(){var t,n=v[2].trim().toLowerCase();if(e.existsSync(n)||(t=n,console.log(`${w}${g}ERRORE! manca il file: ${C}${t||""}${f}`),process.exit(1)),e.statSync(n).isDirectory()){const o=e.readdirSync(n);for(const e of o)await I(n,e)}else await I(o.dirname(n),o.basename(n))}();
package/bin/mu.js CHANGED
@@ -1,266 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import fs from"fs";import path from"path";import{init,database,insertorupdate,checkdb,setstruttura}from"croswil_lib";import minimist from"minimist";
3
- /**
4
- * Esegue una semplice somma sincrona di due numeri
5
- * @param {number} a - Primo numero da sommare
6
- * @param {number} b - Secondo numero da sommare
7
- * @returns {number} La somma dei due numeri
8
- */
9
- /**
10
- * Restituisce il timestamp corrente in millisecondi
11
- * @returns {number} Timestamp corrente
12
- */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)}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 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)}
13
- /**
14
- * Formatta un messaggio di errore rimuovendo informazioni non necessarie
15
- * @param {Error|string} err - L'errore da formattare
16
- * @returns {string} Il messaggio di errore formattato
17
- */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$1,cbGetMacro$1,cbFunc$1,cbInfo$1,cbGetFile$1,cbLogga;
18
- /**
19
- * Funzione di logging che utilizza un callback personalizzato se disponibile
20
- * @param {...any} args - Argomenti da loggare
21
- */const logga=(...args)=>{cbLogga?cbLogga(args):console.log(...args)};
22
- /**
23
- * Configura i callback utilizzati dal modulo
24
- * @param {Function} cbGetMacro1 - Callback per recuperare macro
25
- * @param {Function} cbGetVariante1 - Callback per recuperare varianti
26
- * @param {Function} cbFunc1 - Callback per funzioni generiche
27
- * @param {Function} cbInfo1 - Callback per informazioni
28
- * @param {Function} cbGetFile1 - Callback per accesso ai file
29
- * @param {Function} cbLogga1 - Callback per logging
30
- */function setcallbacks(cbGetMacro1,cbGetVariante1,cbFunc1,cbInfo1,cbGetFile1,cbLogga1){cbGetMacro$1=cbGetMacro1,cbGetVariante$1=cbGetVariante1,cbFunc$1=cbFunc1,cbInfo$1=cbInfo1,cbGetFile$1=cbGetFile1,cbLogga=cbLogga1}
31
- /**
32
- * Normalizza una stringa rimuovendo spazi e convertendo in minuscolo
33
- * @param {string} k - Stringa da normalizzare
34
- * @returns {string} Stringa normalizzata
35
- */function clean(k,locase=!1){return locase?(k||"").trim().toLowerCase():(k||"").trim()}
36
- /**
37
- * Analizza una stringa per estrarre una coppia chiave-valore
38
- * @param {string} r - Stringa da analizzare (es: "chiave=valore")
39
- * @param {string} [sep='='] - Carattere separatore
40
- * @returns {{v: string, o: string, fl: boolean}} Oggetto contenente chiave (v), valore (o) e flag presenza separatore (fl)
41
- */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}}
42
- /**
43
- * Valida e separa un identificatore e una categoria
44
- * @param {string} id - Identificatore da validare (formato: "categoria/nome" o solo "nome")
45
- * @param {string} cat - Categoria di default
46
- * @throws {Error} Se manca la categoria
47
- * @returns {{name: string, cat: string}} Oggetto con nome e categoria validati
48
- */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)}}
49
- /**
50
- * Valida un identificatore verificando che contenga solo caratteri permessi
51
- * @param {string} id - Identificatore da validare
52
- * @param {boolean} vuoto - Default false: Accetta valori vuoti!
53
- * @throws {Error} Se l'identificatore contiene caratteri non validi
54
- * @returns {string} Identificatore validato in minuscolo
55
- */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()}
56
- /**
57
- * Converte una stringa in array di colonne, gestendo diversi formati
58
- * @param {string} value - Stringa da convertire
59
- * @returns {string[]} Array di colonne
60
- */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)))}
61
- /**
62
- * Analizza variabili in un'espressione usando delimitatori
63
- * @param {string} ex - Espressione da analizzare
64
- * @param {number} k0 - Posizione iniziale
65
- * @param {string} inipar - Delimitatore iniziale ([, (, {)
66
- * @param {string} endpar - Delimitatore finale (], ), })
67
- * @param {boolean} [nonewline=false] - Se true, termina all'incontro di un newline
68
- * @returns {{i: number, res: string[]}} Risultato dell'analisi con posizione finale e array risultati
69
- */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)}};
70
- /**
71
- * Classe per la gestione degli errori con funzionalità di accumulo e formattazione
72
- */
73
- /**
74
- * Copia le proprietà non-funzione da un oggetto sorgente a uno destinazione
75
- * @param {Object} objDestinazione - Oggetto destinazione
76
- * @param {Object} objSorgente - Oggetto sorgente
77
- */
78
- 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])}))}
79
- /**
80
- * Estrae le proprietà non-funzione da un oggetto, escludendo chiavi specificate
81
- * @param {Object} obj - Oggetto da cui estrarre le proprietà
82
- * @param {string[]} [exclude] - Array di chiavi da escludere
83
- * @returns {Object} Nuovo oggetto con le proprietà estratte
84
- */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}
85
- /**
86
- * Converte una stringa in un oggetto JSON, gestendo errori e restituendo un valore di default se non valido
87
- * @param {string|Array|Object} str - Stringa da convertire in JSON, array o oggetto da restituire direttamente
88
- * @param {*} [def={}] - Valore di default da restituire in caso di errore di parsing
89
- * @throws {Error} Non genera eccezioni, gli errori vengono loggati internamente
90
- * @returns {*} L'oggetto JSON convertito dalla stringa, l'input originale se è un array/oggetto, o il valore di default in caso di errore
91
- * @example
92
- * fromjson('{"a": 1}') // returns {a: 1}
93
- * fromjson([1,2,3]) // returns [1,2,3]
94
- * fromjson('invalid json', {}) // returns {}
95
- */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()}
96
- /**
97
- * Azzera la lista degli errori
98
- */azzera(){this.err=[]}
99
- /**
100
- * Aggiunge un errore alla lista
101
- * @param {string} msg - Messaggio di errore
102
- * @param {Object} row - Informazioni aggiuntive sull'errore
103
- */add(msg,row){this.err.push({msg:msg,row:row})}
104
- /**
105
- * Restituisce la lista completa degli errori
106
- * @returns {Array} Lista degli errori
107
- */get(){return this.err}
108
- /**
109
- * Restituisce il numero di errori presenti
110
- * @returns {number} Numero di errori
111
- */get length(){return this.err.length}
112
- /**
113
- * Converte la lista degli errori in stringa
114
- * @returns {string} Rappresentazione testuale degli errori
115
- */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};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&&REGEX_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()}
116
- /**
117
- * Valuta un'espressione matematica o logica e restituisce il risultato
118
- * @param {string|number} expression - L'espressione da valutare
119
- * @returns {number} Il risultato della valutazione dell'espressione
120
- * @description
121
- * Supporta operazioni matematiche di base, funzioni trigonometriche,
122
- * operatori di confronto e operazioni logiche.
123
- * Le funzioni supportate includono: sqrt, floor, abs, sin, cos, random, clamp, round
124
- */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}
125
- /**
126
- * Salva lo stato corrente delle variabili nello stack
127
- */push(){this.vec.push({saves:[],dic:{...this.dictionary}})}
128
- /**
129
- * Ripristina l'ultimo stato salvato delle variabili
130
- */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)}}
131
- /**
132
- * Rimuove tutte le variabili e pulisce lo stack
133
- */clear(){this.vec=[],this.dictionary={}}azzera=()=>this.clear()
134
- /**
135
- * Recupera il valore di una variabile
136
- */;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}
137
- /**
138
- * Restituisce un dump delle variabili
139
- */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}
140
- /**
141
- * Aggiunge o rimuove una variabile
142
- */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={}}
143
- /**
144
- * Valuta un'espressione con supporto per callback asincroni
145
- */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}}
146
- /**
147
- * Costanti e espressioni regolari utilizzate nel modulo
148
- */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("|");
149
- /**
150
- * Rimuove i commenti dal codice sorgente mantenendo la struttura del codice
151
- * @param {string} codice - Il codice sorgente da processare
152
- * @param {boolean} tienivuoti - Se true mantiene le righe vuote
153
- * @returns {string[]} Array di righe di codice senza commenti
154
- */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}
155
- /**
156
- * Analizza e organizza il codice in una struttura dati gerarchica
157
- * @param {string[]} tt - Array di righe di codice da analizzare
158
- * @param {boolean} acapo - Se true mantiene i ritorni a capo nel contenuto
159
- * @returns {Object[]} Array di oggetti rappresentanti la struttura del codice
160
- * @throws {Error} Se tt non è un array
161
- */function muClean(tt,acapo=!1){if(!Array.isArray(tt))return void errori.add("muClean: expected array!");const tm=[];
162
- /**
163
- * Aggiunge una riga generica alla struttura
164
- * @param {string} r - Riga da aggiungere
165
- */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}
166
- /**
167
- * Analizza e processa i limiti definiti nel codice
168
- * @param {string} dati - Dati contenenti le definizioni dei limiti
169
- * @returns {Object[]} Array di oggetti rappresentanti i limiti processati
170
- */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}
171
- /**
172
- * Classe per gestire le varianti di un prodotto.
173
- * Permette di caricare, manipolare e convertire varianti di prodotto con relativi attributi e limiti.
174
- * @class
175
- * @exports
176
- */
177
- class Variante{
178
- /**
179
- * Crea una nuova istanza di Variante
180
- * @param {Object} amb - Ambiente di esecuzione contenente il contesto applicativo
181
- */
182
- constructor(amb){this.rows={},this.name="$",this.key="$",this.limits=void 0,
183
- /** @type {Ambiente} */
184
- this.amb=amb}
185
- /**
186
- * Imposta i dati principali della variante
187
- * @param {string} id - Identificativo univoco della variante
188
- * @param {string} cat - Categoria di appartenenza
189
- * @returns {Object} Oggetto contenente nome e categoria normalizzati
190
- */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}}
191
- /**
192
- * Cerca la riga con dimensione più vicina a quella richiesta
193
- * @param {number|string} dim - Dimensione target da cercare
194
- * @param {number} colonna - Indice della colonna (1-based) contenente la dimensione
195
- * @returns {string} Riga formattata nel formato CSV
196
- */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)}
197
- /**
198
- * Carica una variante dal database o da file
199
- * @param {string} id - Identificativo della variante
200
- * @param {string} cat - Categoria della variante
201
- * @param {boolean} nofilter - Se true, non carica i filtri associati
202
- * @returns {Promise<boolean>} Promise che risolve a true se il caricamento ha successo
203
- */async load(id,_cat,nofilter=!1){const{name:name,cat:cat}=this.setheader(id,_cat);if(cbGetVariante$1){const content=await cbGetVariante$1(cat,name);if(content){if(await this.loadContentExtended(content),content.filter)this.limits=parselimitifromdb(content.filter);else if(cbInfo$1&&!nofilter){const tm=await cbInfo$1("filter",cat,name);tm&&tm.length&&(this.limits=parselimitifromdb(tm))}return!0}}return!1}
204
- /**
205
- * Carica il contenuto della variante da array di stringhe
206
- * @private
207
- * @param {string[]} lines - Array di stringhe contenenti la definizione della variante
208
- * @returns {Promise<boolean>} Promise che risolve a true se il caricamento ha successo
209
- */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=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}(limits),!0}
210
- /**
211
- * Converte la variante in un vettore di righe
212
- * @returns {string[]} Array di righe formattate
213
- */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}
214
- /**
215
- * Converte una riga in una stringa CSV
216
- * @private
217
- * @param {string} cod - Codice della riga
218
- * @param {Object} tm - Oggetto contenente i dati della riga
219
- * @returns {string} Stringa CSV formattata
220
- */#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(",")}
221
- /**
222
- * Converte un codice nella sua rappresentazione CSV
223
- * @param {string} cod - Codice da convertire
224
- * @returns {string} Stringa CSV o codice originale se non trovato
225
- */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)}
226
- /**
227
- * Verifica se un'opzione è valida
228
- * @param {string} opz - Opzione da verificare
229
- * @returns {boolean} True se l'opzione è valida
230
- */isvalidopz(opz){const c1=clean(opz),t=this.rows[c1];return!!t&&(1!=t.annulla&&!t.hasliv)}
231
- /**
232
- * Trova la prima opzione valida tra quelle disponibili
233
- * @param {string} opz - Opzione da controllare per prima
234
- * @returns {string|undefined} Prima opzione valida trovata o undefined
235
- */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}}
236
- /**
237
- * Resetta tutti i filtri applicati alla variante
238
- */resetfilter(){delete this._valids;for(const x in this.rows)this.rows[x].annulla=0}
239
- /**
240
- * Restituisce le chiavi valide ordinate alfabeticamente
241
- * @returns {string[]} Array di chiavi valide
242
- */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)))}}
243
- /**
244
- * Applica i limiti configurati alle opzioni della variante
245
- * @returns {Array|void} Array di limiti applicati o void se reset
246
- */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}
247
- /**
248
- * Carica il contenuto esteso della variante
249
- * @param {Object|string} content - Contenuto da caricare, può essere un oggetto o una stringa
250
- * @returns {Promise<void>} Promise che si risolve al completamento del caricamento
251
- */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$1){if(_nofunc[cmd])return"";let a=await cbFunc$1(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&&macro?.localvar&&macro.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))}
252
- /** @type {Variante} */if(head&&head.alias&&(ky=head.alias),macro&&macro.paralias&&macro.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}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;(new Date).valueOf();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&&parametri.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&&parametri.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_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"];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,
253
- /** @type {Ambiente} */
254
- 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$1&&(tm=await cbGetMacro$1(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=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}(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$1&&(res=await cbGetFile$1(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$1&&(res=await cbGetFile$1(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)}}const regex=/^\s*\{(:)?(var|deriva|valid|formula|header|genera|g|v|f|h)(\s.*)?\}/i;function verificaisvar(i1,lines){let inBloccoCommento=!1;const cols=[];for(let i=i1;i<lines.length;i++){const line=lines[i].trim();let linenc=line.split("//")[0].trim();if(line.startsWith("/*"))inBloccoCommento=!0;else if(inBloccoCommento&&line.endsWith("*/"))inBloccoCommento=!1;else if(!inBloccoCommento){if(regex.test(line))return{fl:!0,i2:i-1,cols:cols};if(linenc.endsWith("\\"))return{fl:!1};if(line.startsWith(":h ")&&(linenc=linenc.substr(3).trim()),!linenc.startsWith(":")){const cl=getcolonne(linenc);for(let j=0;j<cl.length;j++){let l=cl[j].length;cl[j].includes(",")&&(l+=2),(!cols[j]||cols[j]<l)&&(cols[j]=l)}}}}return{fl:!0,i2:lines.length-1,cols:cols}}
255
- /**
256
- * Formatta il codice sorgente applicando indentazione e allineamento
257
- * @param {string} code - Il codice sorgente da formattare
258
- * @param {boolean} gisvar - Flag che indica se formattare come variabile
259
- * @returns {string} Il codice formattato
260
- */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){
261
- /** @type {Variabile} */
262
- this.imgpreview={},this.vari=new Variabile,this.ruleset={},this.fndotcallback&&this.vari.setfndot(this.fndotcallback),this.ruleheader="",mode&&(
263
- /** @type {Object.<string, Macro>} */
264
- this.macro={},
265
- /** @type {Object.<string, Variante>} */
266
- 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$1&&!this.varelenco[cat]){const tm=await cbInfo$1("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$1&&(tm=await cbInfo$1("headers",this.cat,"_headers"),this.parseheaderfrominfo(tm)),this.#headers||(this.#headers={}),this.#headers[cod]}async getalias(){let tm;return!this.#alias&&cbInfo$1&&(tm=await cbInfo$1("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$1&&(tm=await cbFunc$1("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$1){const tm=await cbInfo$1("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$1){const xv=await cbGetVariante$1(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$1("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$1){const vars=await cbGetVariante$1(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$1){const tm=await cbGetMacro$1(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}}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"}}},{Clear:Clear,Reset:Reset,Bold:Bold,Reverse:Reverse,Red:Red,Green:Green,Yellow:Yellow,Blue:Blue,Magenta:Magenta,Cyan:Cyan,White:White}=init();var mi=minimist(process.argv);console.log("----------------------------------------------------------------------------------------"),console.log(`${Bold}${Cyan}${Bold}Markuno:${Reset} command line utility del linguaggio (c) Croswil 2024 v. ${Yellow}2.1.33${Reset}`),console.log("----------------------------------------------------------------------------------------");var inidata={FOLDERBASE:"./",DBWORK:"./data/app.db",FOLDERCAT:"./data/mu",FOLDEROUT:"./out",CAT:"cat"};const fini=".lasts.markuno";fs.existsSync(fini)&&(inidata=JSON.parse(fs.readFileSync(fini)));var pars=mi._;(mi.h||mi.help||!pars[2])&&(console.log(`Uso: ${Bold}markuno <funzioni> <[catalogo/]markuno> [opzioni]${Reset} \n${Bold}${Cyan}Funzioni:${Reset} (seleziona una tra le seguenti)\n ${White} c, compila ${Reset}${Green} compila un catalogo/Markuno + Codici Barra\n ${White} d, dump ${Reset}${Green} compila e salva il compilato in formato json\n ${White} e, esegui ${Reset}${Green} esegui un file markuno \n ${White} f, formatta ${Reset}${Green} Formattazione di un file .mu o .var\n ${White} g, genera${Reset}${Green} generatore di codice \n ${White} w, watch ${Reset}${Green} abilita il watch su un file markuno \n ${White} gw <markuno> <maxele> ${Reset}${Green} Genera con wath (solo i primi maxele=20 elementi senza salvare\n${Bold}${Cyan}Opzioni:${Reset}${Green}\n ${White} -h, --help${Reset}${Green} mostra l'help\n ${White} -c, --cat <cat>${Reset}${Green} catalogo (default='${inidata.CAT}' ) \n ${White} -d, --dbwork ${Reset}${Green} database principale (default='${inidata.DBWORK}')\n ${White} -i, --init <folder>${Reset}${Green} cartella di lavoro (default='${inidata.FOLDERCAT}' ) \n ${White} -o, --out <folder>${Reset}${Green} cartella di output (default='${inidata.FOLDEROUT}' ) \n ${White} -x, --xlsx${Reset}${Green} output in formato excel (generatore)\n `),process.exit(0));let counter=0;const DBWORK=mi.d||mi.dbwork||inidata.DBWORK,FOLDERCAT=mi.i||mi.init||inidata.FOLDERCAT,FOLDEROUT=mi.o||mi.out||inidata.FOLDEROUT,CAT=mi.c||mi.cat||inidata.CAT;var dberp=void 0,erp3cad=!1;fs.existsSync(FOLDERCAT)||writeerror(`Manca la cartella di lavoro: ${FOLDERCAT}`),inidata=Object.assign(inidata,{FOLDERBASE:"./",DBWORK:DBWORK,FOLDERCAT:FOLDERCAT,FOLDEROUT:FOLDEROUT,CAT:CAT}),fs.writeFileSync(fini,JSON.stringify(inidata,null,2)),fs.existsSync(FOLDERCAT)||fs.mkdirSync(FOLDERCAT,{recursive:!0});const ISXLS=mi.x||mi.xlsx;function writeerror(err){var tm=err.stack.toString().split("\n");tm.splice(0,1),tm=tm.filter((e=>!/module/.test(e)&&!/node\:/.test(e))),console.log(`${Red}${err.message}${Reset}\n${tm.join("\n")}`),process.exit(1)}function dbmu(cat){var ff=path.join(FOLDERCAT,`mu_${cat}.db`);fs.existsSync(ff)||checkdb(ff,mustr,"mus");var d=database.db(ff);return setstruttura(mustr),d}function getinfofile(file){var def="",md="",f2=`${file}.txt`;fs.existsSync(f2)&&(def=fs.readFileSync(f2).toString());f2=`${file}.md`;return fs.existsSync(f2)&&(md=fs.readFileSync(f2).toString()),{def:def,md:md}}function getinfo(cat,folder){var vv=fs.readdirSync(folder),out={cat:cat,info:"",mu:[],var:[],inc:[]};for(var v of vv){var f=path.join(folder,v),extname=path.extname(v),basename=path.basename(v,extname);"__info.md"==v?out.info=fs.readFileSync(f).toString():".mu"==extname?out.mu.push(basename):".var"==extname?out.var.push(basename):".inc"==extname&&out.inc.push(basename)}return out}async function xlsexport(rq,f2,file){const XLSX=await import("xlsx"),worksheet=XLSX.utils.json_to_sheet(rq),workbook=XLSX.utils.book_new();XLSX.utils.book_append_sheet(workbook,worksheet,f2),XLSX.writeFile(workbook,`${file}.xlsx`,{compression:!0})}async function xlsimport(file,r0){const XLSX=await import("xlsx");var ws=XLSX.readFile(file).Sheets[r0];return XLSX.utils.sheet_to_json(ws)}async function cbGetMacro(cat,name){var file=`${FOLDERCAT}/${cat}/${name}.mu`;return fs.existsSync(file)?fs.readFileSync(file).toString():""}async function cbGetVariante(cat,name){var file=`${FOLDERCAT}/${cat}/${name}.var`;return fs.existsSync(file)?fs.readFileSync(file).toString():(errori.add(`missing var: ${cat}, ${name}`,{t:"cbGetVariante"}),"")}async function cbFunc(cmd,pars,vars){errori.add(`missing fun: ${cmd}`,{t:"cbFunc"})}async function cbInfo(tipo,cat,name){if(Array.isArray(name)){var tt=[];for(var n of name){var value=await cbInfo(tipo,cat,n);value&&tt.push({tipo:n,value:value})}return tt}switch(tipo){case"filter":if(!dberp||!name&&!name[0])return[];if(erp3cad)return[];var rr=dberp.all("select item,model,rule,varfilter,result,result2,exclude,exclude2 from limits where variant=?",name[0]);for(var r of rr)r.valfilter=JSON.parse(r.varfilter||"{}"),r.result=JSON.parse(r.result||"[]"),r.result2=JSON.parse(r.result2||"[]");return rr;case"headers":var f;return f="_typos"==name?`${FOLDERCAT}/${cat}/typos.json`:`${FOLDERCAT}/${cat}/${name}.inc`,fs.existsSync(f)?fs.readFileSync(f).toString():""}}async function cbGetFile(cat,file){if(fs.existsSync(path.join("./",file)))return fs.readFileSync(path.join("./",file)).toString();const ff=`${FOLDERCAT}/${cat}/${file}`;if(fs.existsSync(ff))return fs.readFileSync(ff).toString();errori.add(`missing file: ${ff}`,{t:"cbGetFile"})}function checkfilemu(cat,file){var ext=path.extname(file);[".mu",".var",".inc"].includes(ext)||(ext=".mu",file+=".mu");var folder=path.join(FOLDERCAT,cat||CAT),ff=path.join("./",file);if(fs.existsSync(ff))return{file:ff,folder:folder,diversi:!0};var i=file.indexOf("/");if(i>0&&(cat=file.substr(0,i),file=file.substr(i+1),folder=path.join(FOLDERCAT,cat||CAT),!fs.existsSync(folder)))throw new Error("missing folder: "+folder);if(ff=path.join(folder,file),fs.existsSync(ff))return{file:ff,folder:folder,diversi:!1,ext:ext};throw new Error(`non trovato il file: ${file} su ${folder}`)}async function dowatch(amb,funzione){var{file:file,folder:folder,diversi:diversi}=checkfilemu(amb.cat,pars[3]||""),maxele=parseInt(pars[4]||"10");console.log(`Start Watching: ${Cyan}${Bold}${file}${Reset}`),fs.watch(folder,(async(eventType,filename)=>{filename&&await funzione(amb,maxele)})),diversi&&fs.watch(file,(async(eventType,filename)=>{filename&&await funzione(amb,maxele)})),await funzione(amb,maxele)}async function genera(amb,maxele){var{file:file,folder:folder,diversi:diversi}=checkfilemu(amb.cat,pars[3]||"");if(!fs.existsSync(file))throw new Error("Manca il file: "+file);var tm=path.extname(file),base=path.basename(file,tm),mac=new Macro(amb,base),dt=(new Date).valueOf();await mac.loadAndCompile(`${base}${tm}`);var dt1=(new Date).valueOf(),tot={},issort={},tm2=[],ll2=[],tmh=[];if(await async function muGenerate(macro,amb,genera,callback,isTestmode=0){if(macro.isgenera&&callback){const output={counter:0,keys:{},isTestmode:isTestmode};for(const gg in macro.genera)await muGenerate_0(macro,amb,gg,callback,output);return!0}}(mac,amb,0,((generator,out,db,cc1,cc2)=>{if(maxele){var cl=[];for(var i in out){var t=out[i];if("number"==typeof t&&(t=Math.round(1e4*t)/1e4+""),"__id"!=i){var l=cl.length;tmh[l]||(tmh[l]=i,ll2[l]=i.length),ll2[l]<t.length&&(ll2[l]=t.length),cl.push(t)}}tm2.push(cl)}else{var gen=generator.split("_")[0]||gen;if(tot[gen]||(tot[gen]=[]),tot[gen].push(out),out.cod&&(issort[gen]=!0,db))for(var x in db){var ky=`${gen}_${x}`;tot[ky]||(tot[ky]=[]);var dblist=db[x];for(i=0;i<dblist.length;i++){var d=dblist[i];tot[ky].push({padre:out.cod,i:i,comp:d.c0,qt:muCalc(d.c1),des:d.c2})}}}}),maxele),maxele){for(var i=0;i<tmh.length;i++)tmh[i]=tmh[i].padEnd(ll2[i]," ");for(var tt of(console.log(`${Yellow}${tmh.join(" | ")}${Reset}`),tm2)){for(i=0;i<tt.length;i++)tt[i]=tt[i].padEnd(ll2[i]," ");console.log(tt.join(" | "))}}else{var dt2=(new Date).valueOf(),count=0;for(var ss in issort)count+=tot[ss].length,tot[ss].sort(((a,b)=>(a.cod||"").localeCompare(b.cod||"")));tot._errori=mac.geterrori(),fs.writeFileSync(path.join(FOLDEROUT,`gen_${base}.json`),JSON.stringify(tot,null,2));const fex=path.join(FOLDEROUT,`gen_${base}.xlsx`);var dt3=(new Date).valueOf();if(ISXLS){const XLSX=await import("xlsx"),wb=XLSX.utils.book_new();for(var ky in tot){const ws=XLSX.utils.json_to_sheet(tot[ky]);XLSX.utils.book_append_sheet(wb,ws,ky)}XLSX.writeFile(wb,fex,{compression:!0})}else fs.existsSync(fex)&&fs.unlinkSync(fex);var dt4=(new Date).valueOf();console.log(`${Yellow}${Bold}EVAL........: ${count}${Reset}${Cyan} rows\n${Cyan}load/compile: ${Bold}${Yellow}${dt1-dt}${Reset}${Cyan} ms.\n${Cyan}generate....: ${Bold}${Yellow}${dt2-dt1}${Reset}${Cyan} ms.\n${Cyan}save JSON...: ${Bold}${Yellow}${dt3-dt2}${Reset}${Cyan} ms.\n${Cyan}save XLSX...: ${Bold}${Yellow}${dt4-dt3}${Reset}${Cyan} ms.\n--------------------------------\n${Cyan}${Bold}TOTALE......: ${Yellow}${dt4-dt}${Reset}${Cyan} ms.`)}}async function doesegui(amb){var{file:file,folder:folder,diversi:diversi}=checkfilemu(amb.cat,pars[3]||""),dt=(new Date).valueOf(),data=fs.readFileSync(file).toString(),mac=new Macro(amb,pars[3]||"");counter++,mac.parsedata(data);var dt1=(new Date).valueOf(),out=await muEval(amb,mac,mac.codice,{limited:!1,oldstyle:!0,localvar:mac.localvar}),dt2=(new Date).valueOf();console.log(`${out.join("\n")}`),console.log(`${Yellow}${Bold}EVAL ${counter}${Reset}: ${file} => ${Cyan}load:${Bold}${Yellow}${dt1-dt}${Reset}${Cyan}ms. -- exec:${Bold}${Yellow}${dt2-dt1}${Reset}${Cyan}ms.${Reset}\n----------------------------------------------\n${errori.toString()}`),fs.writeFileSync(path.join(FOLDEROUT,"logs.json"),JSON.stringify({loadandcompile:dt1-dt,execute:dt2-dt1,vari:amb.vari.dump(),codice:mac.codice,errori:mac.errori},null,2)),fs.writeFileSync(path.join(FOLDEROUT,"out.txt"),out.join("\n"))}await async function main(){try{var amb=function muInit(cat,cbGetMacro,cbGetVariante,cbFunc,cbInfo,cbGetFile,cbLogga){const mu=new Ambiente(cat);return setcallbacks(cbGetMacro,cbGetVariante,cbFunc,cbInfo,cbGetFile,cbLogga),mu}(CAT,cbGetMacro,cbGetVariante,cbFunc,cbInfo,cbGetFile),fcat=path.join(FOLDERCAT,CAT);if(fs.mkdirSync(FOLDEROUT,{recursive:!0}),!fs.existsSync(fcat))throw new Error(`Manca il catalogo: ${CAT} su ${FOLDERCAT}`);var dt=(new Date).valueOf();switch(pars[2].trim().toLowerCase()){case"g":case"genera":await genera(amb,0);break;case"d":case"dump":await async function dump(amb){var{file:file,folder:folder,diversi:diversi}=checkfilemu(amb.cat,pars[3]||"");if(!fs.existsSync(file))throw new Error("Manca il file: "+file);var xx,fileout,tm=path.extname(file),base=path.basename(file,tm);if(console.log(base,tm),".mu"==tm){var mac=new Macro(amb,base);await mac.loadAndCompile(`${base}${tm}`),xx=mac.getmacro(),fileout=path.join(FOLDEROUT,base+".json")}else".var"==tm&&(xx=await async function newVariante(cod,cat,amb){const xx=new Variante(amb);return await xx.load(cod,cat),xx}(base,CAT,amb),fileout=path.join(FOLDEROUT,base+".var.json"));xx&&(fs.writeFileSync(fileout,JSON.stringify(xx,null,2)),console.log(`${Cyan}${Bold}Dump: ${Reset}${Yellow}${fileout}`))}(amb);break;case"gw":await dowatch(amb,genera);break;case"c":case"compila":await async function compila(amb){var articolibarre,titolibarre,folder=path.join(FOLDERCAT,CAT);if(!fs.existsSync(folder))throw new Error("Manca il catalogo "+CAT);if(!fs.existsSync(DBWORK))throw new Error("Manca il database di lavoro: "+DBWORK);if(fs.existsSync(DBWORK))if((dberp=database.db(DBWORK)).esisteTabella("artbarre")){erp3cad=!0;var rr=dberp.all("select cod cod,des des,flfm fm,coderr coderr,codalt codalt from artbarre order by cod ");for(var r of(titolibarre={},rr)){(tm=r.cod.trim().toLowerCase().substr(1))&&(titolibarre[tm]={des:r.des,fm:r.fm,coderr:r.coderr.trim().toLowerCase(),codalt:r.codalt.trim().toLowerCase()})}articolibarre=dberp.all("select codicebarra barcode,diml l,dima a,dimp p,cod cod from articoli where codicebarra like ? order by codicebarra","+%")}else articolibarre=dberp.all("select barcode,l,a,p,cod from items where barcode>'' order by barcode"),titolibarre={};else console.warn("MISSING DBWORK (barre e limits)");var db=dbmu(CAT);db.begin(),db.run("delete from variants"),db.run("delete from macros"),db.run("delete from barcodes"),db.run("delete from extras");var info=getinfo(CAT,folder);for(var x of(await amb.compila(info,((table,data)=>{if(data){if("macros"===table){var{def:def,md:md}=getinfofile(`${data.cod}.mu`);data.def=def,data.md=md}insertorupdate(db,table,data,"mus")}})),info.var)){var tm,ff=`${folder}/${x}.var.txt`;if(fs.existsSync(ff))(tm=muLimits(fs.readFileSync(ff).toString()))&&tm.length&&insertorupdate(db,"extras",{tipo:"l",cod:x,info:JSON.stringify(tm)},"mus")}await amb.barrecompila(articolibarre,titolibarre,((table,data)=>{insertorupdate(db,table,data,"mus")})),insertorupdate(db,"infos",{cod:"info",des:info.cat,info:JSON.stringify({cat:info.cat,md:info.info})},"mus"),dberp&&dberp.chiudi();db.commit(),db.chiudi()}(amb),console.log(`Compilazione catalogo: ${Red}${Bold}${CAT}${Reset}: ${Yellow}${(new Date).valueOf()-dt}ms.`);break;case"x":case"e":case"esegui":await doesegui(amb);break;case"f":case"format":!function formatta(amb){var{file:file,folder:folder,diversi:diversi,ext:ext}=checkfilemu(amb.cat,pars[3]||"");if(fs.existsSync(file)){var data=fs.readFileSync(file).toString(),isvar=".var"==ext;data=function muFormatcode(code,gisvar){const lines=code.split("\n"),formattedCode=[];let indentLevel=0,inBloccoCommento=!1,inAcapo=!1,cols=[],isvar=gisvar;if(isvar){const tm=verificaisvar(0,lines);isvar=tm.fl,isvar&&(cols=tm.cols)}for(let i=0;i<lines.length;i++){const ltot=lines[i];let line=ltot.trim();const tt=line.split("//");let linenc=tt[0].trim();tt.splice(0,1);const commento=tt.length?` // ${tt.join("//").trim()} `:"";if(line.startsWith("/*"))inBloccoCommento=!0,formattedCode.push(line);else if(inBloccoCommento&&line.endsWith("*/"))inBloccoCommento=!1,formattedCode.push(line);else if(inBloccoCommento)formattedCode.push(ltot);else{const rr=regex.exec(line);if(rr){if(formattedCode.push(line),indentLevel=rr[1]?0:1,/^\s*\{(var|deriva|header|v|h)(\s.*)?\}/i.test(line)){const tm=verificaisvar(i+1,lines);isvar=tm.fl,isvar&&(cols=tm.cols)}else isvar=!1;inAcapo=!1;continue}if(isvar)if(linenc.startsWith(":")&&!linenc.startsWith(":h ")||!linenc)formattedCode.push(line);else{let lba=" ";linenc.startsWith(":h ")&&(linenc=linenc.substr(3).trim(),lba=":h ");const cl=getcolonne(linenc);for(let j=0;j<cl.length;j++)cl[j].includes(",")&&(cl[j]=`"${cl[j]}"`),cl[j]=cl[j].padEnd(cols[j]," ");formattedCode.push(`${lba}${cl.join(" , ")} ${commento}`)}else{const indent=" ".repeat(indentLevel>=0?indentLevel:0);if(inAcapo)formattedCode.push(`${indent} ${line}`);else{let command="";line.startsWith("#")&&(command=line.substring(1).split(" ")[0].toUpperCase(),line="#"+command+line.substring(command.length+1)),["IF","IFDEF","IFNDEF"].includes(command)?line.indexOf("#",2)<0?(formattedCode.push(`${indent}${line}`),indentLevel++):(line=line.replace(/#([\w]+)/g,((match,m1)=>"#"+m1.toUpperCase())),formattedCode.push(`${indent}${line}`)):["FOR","SELECT","FORVAR","VARIANTE","DO"].includes(command)?(formattedCode.push(`${indent}${line}`),indentLevel++):["ELSEIF","ELSE","ELSEIFDEF","ELSEIFNDEF","CASE","CASES","DEFAULT"].includes(command)&&indentLevel>0?formattedCode.push(" ".repeat(indentLevel>0?indentLevel-1:0)+line):["ENDIF","ENDSELECT","LOOP","ENDFOR"].includes(command)?(formattedCode.push(" ".repeat(indentLevel>0?indentLevel-1:0)+line),indentLevel--,indentLevel<0&&(indentLevel=0)):line.startsWith("_ ")||line.startsWith(":")?formattedCode.push(line):formattedCode.push(indent+line)}inAcapo=linenc.endsWith("\\")}}}return formattedCode.join("\n")}(data,isvar),fs.writeFileSync(file,data),console.log(`formatted: ${isvar} ${Cyan}${Bold}${file}${Reset}`)}}(amb);break;case"w":case"watch":await dowatch(amb,doesegui);break;default:throw new Error("Funzione non contemplata (g,c,b,x)")}}catch(e){writeerror(e)}}();export{dbmu,getinfo,getinfofile,xlsexport,xlsimport};
2
+ import t from"fs";import e from"path";import{init as a,database as i,insertorupdate as s,checkdb as r,setstruttura as n}from"croswil_lib";import o from"minimist";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)}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 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(),i="\0";e=a.map((e=>`${e}${i}${String(t[e])}`)).join(i)}let a=2166136261,i=2218511855;for(let t=0;t<e.length;t++){const s=e.charCodeAt(t);a^=s,a+=a<<5^2779096485,i^=a,i=((i<<3)+s^2134516169)>>>0}return a>>>=0,a.toString(16)+i.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 c,l,u,f,h,d;const logga=(...t)=>{d?d(t):console.log(...t)};function setcallbacks(t,e,a,i,s,r){l=t,c=e,u=a,f=i,h=s,d=r}function clean(t,e=!1){return e?(t||"").trim().toLowerCase():(t||"").trim()}function getcouple(t,e="=",a=!0){const i=(t=t||"").indexOf(e);return i>=0?{v:clean(t.substring(0,i),a),o:t.substring(i+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 i=[];for(let a=t;a<=e;a++)i.push(a+"");return i}if(!/["({[]/.test(t))return t.split(/[,;]/).map((t=>t.trim()));const i=[];let s="",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)s+=a;else{const t=s.trim();i.push(t),s=""}}const o=s.trim();return o&&i.push(o),i.map((t=>(t=t.trim(),!e&&(t.startsWith('"')&&t.endsWith('"')||t.startsWith("(")&&t.endsWith(")"))?t.slice(1,-1):t)))}const parsevar=(t,e,a,i,s=!1)=>{const r=["[","(","{"],n=["]",")","}"];i||(i="["==a?"]":"("==a?")":"}");const o=r.includes(a);let c=1,l=0;const u=[];for(let f=e;f<t.length;f++)if(o&&r.includes(t[f])||t[f]==a)c++;else if(o&&n.includes(t[f])||t[f]==i){if(c--,0==c&&t[f]==i)return u[l]=t.substring(e,f),{i:f,res:u}}else if(":"==t[f])1==c&&(u[l]=t.substring(e,f),e=f+1,l++);else if("\n"==t[f]&&s)return{i:f,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[i,s]of Object.entries(t))"function"==typeof s||e&&e.includes(i)||(a[i]=getOggetto(s,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 m=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 i=Math.pow(10,e);return Math.round(a*i)/i||0};const p=/(?<!\w)\(/g,v=/^-?[0-9.]+$/,g=/^(\w+)(!)?\[(.*)?\]$/,b=/[0-9.]/,w=/[+\-*/^%]/,y=/[a-zA-Z]/i;function valutaparentesi(t){for(t=(t+"").trim();;){const e=p.exec(t);if(!e)break;{const{i:a,res:i}=parsevar(t,e.index+1,"(",")");if(a<=0)break;t=t.substring(0,e.index)+valutaparentesi(i[0])+(a>=0?t.substring(a+1):"")}}return function operatoricomparazione(t){let e,a;const i={"||":()=>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 s=-1,r="";for(const e in i)if(s=t.indexOf(e),s>=0){r=e;break}return-1!==s?(e=t.slice(0,s),a=t.slice(s+r.length),i[r]&&i[r]()?1:0):muCalcbase(t)}(t=function valutainsiemi(t){if(t.includes("[")){function resinisiemi(t){const e=t[1],a=!!t[2],i=getcolonne(t[3]);for(const t of i)if(t==e)return a?"0":"1";return a?"1":"0"}for(;;){const e=g.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 $={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 w.test(a)?(e++,a):null}function parsePrimary(){if("+"===t[e]||"-"===t[e]){return("-"===t[e++]?-1:1)*parsePrimary()}if(b.test(t[e]))return function parseNumber(){const a=e;for(;e<t.length&&b.test(t[e]);)e++;return Number(t.slice(a,e))}();if("("===t[e]){e++;const a=parseExpr();return")"===t[e]&&e++,a}return y.test(t[e])?function parseFunctions(){const a=t.slice(e);if(!a)return 0;for(const[i,s]of Object.entries($)){const r=new RegExp(`^(${i})\\(`,"i").exec(a);if(r){e+=r[0].length;let a=[];for(;;){let i=parseExpr();if(a.push(i),")"===t[e]){e++;break}if(","!=t[e])break;e++}return s(...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 v.test(e)?Number(e)||0:valutaparentesi(t)||0}const k=100;function valutavar(t,e){const a=e[0]||"";if(!a)return"";if(t.counter>=k)return a;const i=valuta0(t,a);let s;if(t.stl[i])s=`-- R:${i} --`;else{const e=t.var(i);if(isObject(e))return e;t.stl[i]=!0,s=valutabase(t,e),delete t.stl[i]}if(t.counter>=k)return a;if(e[1]){const a=getcolonne(s);if("l"==e[1])return String(a.length);const i=muCalc(valuta0(t,e[1]));if(!(i>=0&&i<a.length))return"";s=valuta0(t,a[i])}if(e[2]){const a=muCalc(valuta0(t,e[2]));if(a){let i=0;return e[3]&&(i=muCalc(valuta0(t,e[3]))),a<0?s.slice(a):i?s.substring(a-1,a+i-1):s.substring(a-1)}}return s}function valutaquadra(t,e){let a=getcolonne(e||"");const i=clean(a[0]);function replacecharcode(t){return"\\t"==t?"\t":"\\n"==t?"\n":(t||"").replace(/&(\d+)/g,((t,e)=>String.fromCharCode(parseInt(e))))}switch(i){case"set":{const e=valuta0(t,a[1]||""),i=valuta0(t,a[2]||"");t.add(e,t.var(i))}break;case"ex":{const e=valuta0(t,a[1]||"");let i=valuta0(t,a[2]||"");i||(i=",");const s=muCalc(valuta0(t,a[3]||"")),r=e.split(i);return s>0&&r[s-1]||""}case"ex2":{const e=replacecharcode(a[1]||""),i=muCalc(valuta0(t,a[2]||""));a.splice(0,3);return a.join(";").split(e)[i>0?i-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"==i){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 i=a[1]||"";return e?a[3].split(i)[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]||""),i=muCalc(valuta0(t,a[2]||"")),s=muCalc(valuta0(t,a[3]||""));return e.substring(i-1,i+s-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 i.startsWith(".")?{fun:e,pars:[]}:{fun:i,pars:a}}}function valuta0(t,e){if(e+="",t.counter>=k)return e;for(;;){const a=/\$([{(])/im.exec(e);if(!a)break;{const i=a.index,{i:s,res:r}="("==a[1]?parsevar(e,i+2,"(",")"):parsevar(e,i+2,"{","}"),n=valutavar(t,r);if(isObject(n))return n;e=valuta0(t,e.substring(0,i))+n+(s>=0?valuta0(t,e.substring(s+1)):"")}}return e=(e=e.replace(/\$([a-z|][\w|.]*)/gi,((e,a)=>{let i="";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)){i=e+i;break}i=a.slice(-1)+i,a=a.substring(0,a.length-1)}return i}))).replace(/\$(\d+):(\d+)(:(\d+))?/g,((t,e,a,i,s)=>{s=s?+s:1;const r=[];for(let t=+e;t<=+a;t+=s)r.push(t.toString());return r.join(";")}))}function valutabase(t,e){return e&&(t.counter++,t.counter<=k&&(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 i=[];for(let a=t;a<=e;a++)i.push(a+"");return i}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 i=Variabile.sanitizeKey(t);if(i.startsWith(".")&&this.fndotcallback){const t=this.fndotcallback(i.toLowerCase());if(t)return toformat(t,e)}if(Variabile.isValidKey(i)){const t=i.toLowerCase(),a=/^([\w][\w\d]*)([.[])/.exec(t);if(a){const i=this.dictionary[a[1]];if(i&&"object"==typeof i)return toformat(function objval(t,e){const a=e.split(".");let i=t;for(let t=0;t<a.length;t++){const e=a[t],s=e.match(/(.*?)\[(\d*)\]/);if(s){if(s[1]&&(i=i[s[1]]),void 0===i)return"";i=i[parseInt(s[2],10)||0]}else switch(e){case"_k":i=(Object.keys(i)||[]).join(",");break;case"_v":i=Object.values(i)||[];break;case"_l":i=i.length||0;break;default:i=i[e]}if(void 0===i)return""}return"number"==typeof i?i+"":i}(i,("["==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 i=Object.keys(this.dictionary).filter((e=>e.startsWith(t)));for(let t of i)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 i=0;i<20;i++){const i=e.lastIndexOf("$[");if(!(i>=0)){e=valutabase(t,e);break}{const{i:s,res:r}=parsevar(e,i+2,"[","]"),n=valutabase(t,e.substring(0,i)),o=r?r[0].startsWith(".")?valutabase(t,r.join(":")):valutabase(t,r[0]):"",c=s>=0?valutabase(t,e.substring(s+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:i}=parsevar(t,e+1,"{","}");if(a<0)return t;t=t.substring(0,e)+muCalc(i[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,i,s=!1;return t.startsWith("#")&&(s=!0,t=t.slice(1)),i=t.indexOf("="),i>0?(e=clean(t.slice(0,i)),a=t.slice(i+1)):(i=t.indexOf(":"),i>0?(e=clean(t.slice(0,i)),a=t.slice(i+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)&&(s=!0),s&&(a=muCalc(a)),{k:e,v:a}}}class CodiceBarra{constructor(){this.barre={}}azzera(){this.barre={}}oriented(t,e,a,i){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:i};case"2":return{t:t,x:e,y:i,z:a};case"5":return{t:t,x:e,y:a,z:i};case"4":return{t:t,x:i,y:e,z:a};case"3":return{t:t,x:a,y:i,z:e};case"6":return{t:t,x:i,y:a,z:e};default:return{t:"1",x:a,y:e,z:i}}}async getcode(t,e,a,i,s){let[r,n]=t.split(":");n=n||"";const getcode0=async(t,r)=>{let n=this.barre[t];if(!n&&s&&(n=await s(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,i),f={barra:t,fm:n.fm,t:o,liv:r,items:n.r.length,err:""};let h=n.r;if(u){const t=h.filter((t=>t.z===u||!t.z));t.length>0?h=t:f.err=`spessore non coerente: ${u}`}if("l"==o||"a"==o||"p"==o){const t=h.find((t=>t.x>=c));if(t)return{c:t.c,fm:t.x==c?0:1,x1:t.x,x:c,extra:f}}else{let t=h.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:f};if(0!=n.fm&&(t=h.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:f};if(0!=n.fm&&2!=n.fm&&(t=h.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:f}}return n.codalt&&r<5?await getcode0(n.codalt,r+1):{c:n.coderr,fm:9,x:c,y:l,z:u,extra:f}};return await getcode0(r,0)}compila(t,e){e||(e={});const a={};if(Array.isArray(t)){for(const i of t)if(i.cod=clean(i.cod),i.barcode=clean(i.barcode),i.barcode.length>2&&"+"==i.barcode[0]){i.barcode=i.barcode.substr(1);const t=this.oriented(i.barcode.substr(0,1),i.l,i.a,i.p);t.c=i.modello?{c:i.cod,m:i.modello}:i.cod,a[i.barcode]||(a[i.barcode]={t:i.barcode.substr(0,1),r:[]},e[i.barcode]&&(a[i.barcode]=Object.assign(e[i.barcode],a[i.barcode]))),a[i.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 x="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 muClComments(t,e){const a=(i=t,i.replace(/("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*')|\/\*[\s\S]*?\*\//g,((t,e)=>e||""))).split(/\r?\n/);var i;const s=[];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 s.push(a)}return s}function muClean(t,e=!1){if(!Array.isArray(t))return void m.add("muClean: expected array!");const a=[];function addgen(t){if(a.length>0&&""==a[a.length-1].tipo){const i=a[a.length-1];e||!(!t.startsWith("!")&!t.startsWith("."))||t.startsWith("$")||t.startsWith("{")||t.startsWith("#")||i.contenuto.startsWith("!")||i.contenuto.startsWith(".")||i.contenuto.startsWith("$")||i.contenuto.startsWith("{")||i.contenuto.startsWith("#")?a.push({tipo:"",contenuto:t}):i.contenuto=i.contenuto+"\n"+t}else a.push({tipo:"",contenuto:t})}for(const e of t){const t=e.match(/^#([\w.]+)\s*(.*)$/);if(t){let i=t[1].toUpperCase().trim(),s="";if(i.includes(".")){const t=i.split(".");i=t[0],s=t[1]}if(x.includes(i)){const e=t[2];if("IF"!==i&&"IFDEF"!=i&&"IFNDEF"!=i||!e.includes("#")){const e={tipo:i,contenuto:t[2]};s&&(e.tipo2=s),a.push(e)}else{let s=e.match(/^(.*?)\s*#\s*(\w+)\s*(.*?)\s*#\s*(\w+)\s*(.*)$/);s?(a.push({tipo:i,contenuto:s[1].trim()}),a.push({tipo:s[2].toUpperCase(),contenuto:s[3]}),a.push({tipo:"ELSE",contenuto:""}),a.push({tipo:s[4].toUpperCase(),contenuto:s[5]}),a.push({tipo:"ENDIF",contenuto:""})):(s=e.match(/^(.*?)\s*#\s*(\w+)\s*(.*)$/),s?(a.push({tipo:i,contenuto:s[1].trim()}),a.push({tipo:s[2].toUpperCase(),contenuto:s[3]}),a.push({tipo:"ENDIF",contenuto:""})):a.push({tipo:t[1].toUpperCase(),contenuto:t[2]}))}}else addgen(e)}else addgen(e)}let i=0,s=0,r=0,n=[],o=[],c=[];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":s++,o[s]={pos:t,bk:[]};break;case"LOOP":case"ENDFOR":if(s>0){const{pos:i}=o[s];for(const e of o[s].bk)e.next=t,e.prev=i;e.prev=i,a[i].next=t,s--}break;case"BREAK":case"EXIT":case"EXITFOR":case"CONTINUE":s>0&&o[s].bk.push(e);break;case"IF":case"IFDEF":case"IFNDEF":i++,n[i]={pos:t,bk:[e]};break;case"SELECT":r++,c[r]={pos:t,bk:[e],first:t};break;case"ELSEIF":case"ELSEIFDEF":case"ELSEIFNDEF":case"ELSE":if(i>0){const{pos:s}=n[i];n[i].bk.push(e),a[s].next=t,n[i].pos=t}break;case"CASE":case"CASES":case"DEFAULT":if(r>0){const{pos:i,first:s}=c[r];c[r].bk.push(e),a[i].next=t,e.first=s,c[r].pos=t}break;case"ENDIF":if(i>0){const{pos:e,next:s}=n[i];a[e].next=t;for(const e of n[i].bk)e.last=t;i--}break;case"ENDSELECT":if(r>0){const{pos:e,next:i}=c[r];a[e].next=t;for(const e of c[r].bk)e.last=t;r--}}}return a}function muLimits(t){const e=muClComments(t),a=[];let i;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])?(i={},a.push(i)):i=void 0;else if(i&&(e=/^\s*:(\w+)\s*(.*)/.exec(t),e))switch(e[1].toLowerCase()){case"opz":case"o":i.opz=parsa(e[2]);break;case"obs":case"obsolete":i.obsolete=parsa(e[2]);break;case"scons":case"sconsigliate":i.scons=parsa(e[2]);break;case"neutri":i.neutri=parsa(e[2]);break;case"art":i.art=parsa(e[2]);break;case"mod":i.mod=parsa(e[2]);break;default:logga("missing:",e[1])}}return a}function parselimitifromdb(t){let e,a=[];if(t&&t.length)for(const i of t){e={},i.varfilter=fromjson(i.varfilter,[]),i.result=fromjson(i.result,[]),i.result2=fromjson(i.result2,[]),i.exclude=parseInt(i.exclude)?1:0,i.exclude2=parseInt(i.exclude2)?1:0;const{item:s,model:r,rule:n,varfilter:o,result:c,result2:l,exclude:u,exclude2:f,datai:h,dataf:d}=i;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&&(f?e.ex2=remap(l):e.valid2=remap(l)),s&&(e.i=clean(s).split(";")),r&&(e.m=clean(r).split(";")),n&&(e.r=clean(n).split(";")),(h||d)&&h<d&&(e.datai=parseInt(h),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}class Variante{constructor(t){this.rows={},this.name="$",this.key="$",this.limits=void 0,this.amb=t}setheader(t,e){const{name:a,cat:i}=checkmu(t,e);return this.cat=i,this.name=a,this.alias="",this.obbligo=!1,this.des=a,this.vdef=[],this.rows={},this.h=[],this.key=`${i}/${a}`,{name:a,cat:i}}fromdim(t,e=2){"number"!=typeof t&&(t=muCalc(t)),e>0&&e--;let a,i=1e9;for(const s in this.rows){const r=this.rows[s];if(!r.annulla){const s=parseFloat(r.v[e])||0;s<=i&&s>=t&&(i=s,a=r)}}return this.#t(t,a)}async load(t,e,a=!1){const{name:i,cat:s}=this.setheader(t,e);if(c){const t=await c(s,i);if(t){if(await this.loadContentExtended(t),t.filter)this.limits=parselimitifromdb(t.filter);else if(f&&!a){const t=await f("filter",s,i);t&&t.length&&(this.limits=parselimitifromdb(t))}return!0}}return!1}async _loadContent(t){const e=/^\s*[!:]\s*(\w+)\s*(.*)$/i;let a="";const i=[];let s,r=!1;for(const n of t){const t=n.toLowerCase();if("{limit}"==t)s=[],i.push(s),r=!0;else if("{:limit}"==t)r=!1;else if(r)s.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 i=clean(t.substring(0,e));"v"!=i&&(this.rows[a][i]=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=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 i of t){const t=a.exec(i);if(t)switch(t[1]){case"var":case"v":case"variante":{const a=(t[2]||"").indexOf(" ");if(a>0){const i=clean(t[2].substring(0,a)),s=getcolonne(t[2].substring(a+1));if(i&&s&&s.length){e.v||(e.v=[]);let t=e.v.find((t=>t.v==i));t||(t={v:i,o:[]},e.v.push(t));for(const e of s)t.o.includes(e)||t.o.push(e)}}}break;case"d":case"dt":case"data":case"date":{const a=t[2].split(" "),i=parseInt(a[0]),s=parseInt(a[1]);(i||s)&&(e.datai=i,e.dataf=s)}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(i))}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}(i),!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 i=this.rows[a];return 2==i.annulla?"":this.#t(e||t,i)}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 i=Object.keys(this.rows).sort();for(let t=0;t<i.length;t++){const e=i[t];if(!(t<i.length-1&&i[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:i,vari:s,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(i,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(s.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 f=!1,h=!1;for(const t of n){if(t.valid&&t.valid.length){f=!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){h=!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,i=!1;if(f){for(const e of o)if(t.startsWith(e)){a=!0;break}!a&&l.has(t)&&(a=!0)}if(h){for(const e of c)if(t.startsWith(e)){i=!0;break}!i&&u.has(t)&&(i=!0)}e.annulla=0,f&&!a&&(e.annulla=1),h&&i&&(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 E={};async function getcbfunc(t,e,a,i,s,r){if(u){if(E[e])return"";let t=await u(e,a,i,s,r);return isObject(t)||(t=(t||"").trim(),"!"==t&&(E[e]=!0,t="")),t}return t}async function intvaluta(t,e,a){return await t.vari.valuta(a,(async(a,i)=>{switch(a){case"dim":{let a=muCalc(i[1]),s=await dammivariante(t,e,i[2]),r=parseInt(i[3])||2;return s&&s.fromdim?s.fromdim(a,r):a}case"seed":{let t=i[1],e=getcolonne(i[2]);return e[seeder(e.length,t)]||""}case"seedvar":{let a=await dammivariante(t,e,i[2]),s=i[1],r=a.validkeys();if(i[3]&&i[4]){let t=muCalc(i[3])-1;if(t>=0){let e=getcolonne(i[4]);r=r.filter((i=>{let s=a.rows[i];if(s&&s.v&&s.v[t]){let a=getcolonne(s.v[t]);if(a)for(let t of e)if(a.includes(t))return!0}return!1}))}}let n=seeder(r.length,s);return n>=0&&a.tovar(r[n])||""}default:return await getcbfunc(`**fun:${a}**`,a,i,t.vari,t)}}))}async function dammivariante(t,e,a){let i;return i=e&&e?.localvar&&e.localvar[a]?e.localvar[a]:await t.getvariante(a),i}async function impostavariante(t,e,a,i,s){let r,n=a;if((i=i||"")&&"string"==typeof i){const t=i.indexOf(":");t>=0&&(t>0&&(n=clean(i.slice(0,t))),i=i.slice(t+1))}if(s&&s.alias&&(n=s.alias),e&&e.paralias&&e.paralias[a]&&(n=e.paralias[a]),r=await dammivariante(t,e,n),r)if(s&&s.t){s.des||(s.des=r.des);let e=s?.filtra||"";if(e.includes("$")&&(e=await t.vari.valuta(e)),"m"===s.t){let t=2;if(i.includes(":")){const e=i.split(":");t=parseInt(e[1]),i=e[0]}r.limita(e),i=r.fromdim(parseFloat(i),t)}else{r.limita(e);const t=r.firstvalid(i,getcolonne(s.def));i=r.tovar(t)}}else r.resetfilter(),i=r.firstvalid(i),i=r.tovar(i);else s&&s.t&&s.t;return t.vari.add(a,i),i}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,i){if(!Array.isArray(a))return m.add("codice is not a valid parsed array"),[];i||(i={}),i.id||(i.id="_"),i._stackmacro||(i._stackmacro=0),i.limited||(i.limited=!1),t||m.add("amb deve essere definito");const s=t.vari;t.maxdelays,t.cat;const r=[];let n,o,c;(new Date).valueOf();for(let l=0;l<a.length;){let u=a[l];switch(u.tipo){case"IFDEF":case"IFNDEF":case"IF":{const f="IF"==u.tipo?muCalc(await intvaluta(t,e,u.contenuto)):"IFDEF"==u.tipo?""!=await intvaluta(t,e,u.contenuto):""==await intvaluta(t,e,u.contenuto);u.next?(a[u.next].jlast=f?1:0,f||(l=u.next-1)):m.add("Troppo tempo",u)}break;case"SELECT":u.next?(a[u.next].t1=await intvaluta(t,e,u.contenuto),l=u.next-1):m.add("manca endselect",u);break;case"CASE":case"CASES":case"DEFAULT":if(u.next)if(u.jlast)u.jlast=0,l=u.last-1;else{let h,d=1;const _getvv=async()=>{let a=await intvaluta(t,e,u.contenuto);return a=a.includes(":")&&!a.includes(",")?a.split(":").map((t=>(t||"").trim())):getcolonne(a),a};if("CASE"==u.tipo){d=0,h=await _getvv();const p=muCalc(u.t1||"");h.find((t=>muCalc(t)==p))&&(d=1)}else if("CASES"==u.tipo){d=0,h=await _getvv();const v=u.t1||"";h.find((t=>t==v))&&(d=1)}a[u.next].jlast=d?1:0,a[u.next].t1=u.t1,d||(l=u.next-1)}else m.add("manca select",u);break;case"ELSEIF":case"ELSEIFDEF":case"ELSEIFNDEF":case"ELSE":if(u.next)if(u.jlast)u.jlast=0,l=u.last-1;else{const g="ELSE"==u.tipo?1:"ELSEIF"==u.tipo?muCalc(await intvaluta(t,e,u.contenuto)):"ELSEIFDEF"==u.tipo?""!=await intvaluta(t,e,u.contenuto):""==await intvaluta(t,e,u.contenuto);a[u.next].jlast=g?1:0,g||(l=u.next-1)}else m.add("manca endif",u);break;case"ENDIF":case"ENDSELECT":case"CACHE":case"CVAR":break;case"PUSH":s.push();break;case"POP":s.pop();break;case"INC":case"I":if(i._stackmacro>500)m.add("stack chiamate macro troppo profondo!",u);else if(({macro:n,pars:o,xid:c}=await t.getmacro(u)||{}),n){i._inc=!0,i._stackmacro++;const b={},w=n.parametri?._;if(w&&w.length)for(const $ of w){const k=clean($.split("=")[0]||"",!0);k&&(b[k]=s.dictionary[k])}await n.impostaparametri(w,o);const y=await muEval(t,n,n.codice,i);for(const x in b)b[x]?s.dictionary[x]=b[x]:delete s.dictionary[x];r.push(...y),i._stackmacro--,i._inc=!1}break;case"RET":{const E=await intvaluta(t,e,u.contenuto);t.vari.savevars(E)}break;case"MACRO":case"M":case"FUNC":case"F":if(i._stackmacro>500)m.add("stack chiamate macro troppo profondo!",u);else{let{macro:C,pars:S,xid:O}=await t.getmacro(u)||{};if(C){const F=!!i.grafica||["F","FUNC"].includes(u.tipo),_=i.id||"",L=C.parametri?._,A={};if(F)s.push();else{if(C.head)for(const I of C.head)A[I.cod]=t.vari.var(I.cod);if(L&&L.length)for(const j of L){const M=(j.split("=")[0]||"").trim().toLowerCase();M&&(A[M]=s.dictionary[M])}}if(C.codice.length){if(i._stackmacro++,i.grafica&&"function"==typeof i.grafica){let z="",D="";S&&S.length?(z=S.find((t=>t.startsWith("#id"))),z?(z=await s.valuta(z.slice(4)),z.startsWith("#")?i.id=z:i.id=hash(`${l}${C.name}${_}${z}`),S=S.filter((t=>!t.startsWith("#id"))),D=i.id):i.id=hash(`z${_}${l}`)):i.id=hash(`z${_}${l}`);let N=t.pick.key;t.pick.key=i.id;const T=await i.grafica({tipo:u.tipo,id:D,pars:S,parametri:L,macro:C,options:i,vari:t.vari,amb:t});t.pick.key=N,r.push(T)}else{await C.impostaparametri(L,S);let W=t.vari.var("_rootnode");t.vari.add("_rootnode","0");const R=await muEval(t,C,C.codice,i);t.vari.add("_rootnode",W),r.push(...R)}i._stackmacro--}if(F)s.pop();else for(const V in A)A[V]?s.dictionary[V]=A[V]:delete s.dictionary[V];i.id=_}else m.add("Macro non trovata!",u)}break;case"SETDEF":{let J=getcolonne(u.contenuto.toLowerCase()),U=await dammivariante(t,n,J[0]),P=J[1]||"def_",K=J[2];if(P.endsWith("_")||(P+="_"),U&&U.rows){J=Object.keys(U.rows),K&&(J=J.filter((t=>t.startsWith(K))));for(let G of J){let B=`${P}${G}`;if(!s.dictionary[B]){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(",")}s.add(B,await intvaluta(t,e,torow(U.rows[G])))}}}}break;case"LET":case"LETS":{let q=u.contenuto.indexOf("="),X=-1;if(q>=0&&(X=u.contenuto.indexOf("=",q+1)),X<0){const H=u.contenuto;if(q=H.indexOf("="),q>0){const Z=await intvaluta(t,e,H.slice(0,q).trim());let Y=H.slice(q+1).trim();Y="LET"==u.tipo?muCalc(await intvaluta(t,e,Y))||"":await intvaluta(t,e,Y),s.add(Z,Y)}}else{const Q=getcolonne(u.contenuto);for(const tt of Q)if(q=tt.indexOf("="),q>0){const et=await intvaluta(t,e,tt.slice(0,q));let at=tt.slice(q+1).trim();at="LET"==u.tipo?muCalc(await intvaluta(t,e,at))||"":await intvaluta(t,e,at),s.add(et,at)}}}break;case"LETT":{const it=u.contenuto.indexOf("=");if(it>0){const st=await intvaluta(t,e,u.contenuto.slice(0,it).trim()),rt=await intvaluta(t,e,u.contenuto.slice(it+1).trim());s.add(st,rt)}}break;case"LOOK":case"LOOKB":{const nt=getcolonne(await intvaluta(t,e,u.contenuto)),ot=muCalc(nt[1]),ct=muCalc(nt[3]),lt=await dammivariante(t,n,nt[2]);if(lt&&lt.rows){const ut=Object.values(lt.rows).reduce(((t,e)=>{const a=parseInt(e.v[ct?ct-1:0]);return a&&("LOOKB"==u.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"==u.tipo?0:1/0,c:""});ut&&ut.c&&(t.vari.add(nt[0],lt.tovar(ut.c)),i.checkheader&&"function"==typeof i.checkheader&&await i.checkheader({variante:nt[0],valore:lt.tovar(ut.c),riga:u}))}else t.vari.add(nt[0],`${ot},no,no`)}break;case"LETV":case"LETM":case"DEF":{const ft=getcolonne(u.contenuto);if(ft)for(const ht of ft){let{v:dt,o:mt,fl:pt}=getcouple(ht);if(pt){dt=await s.valuta(dt),mt=await intvaluta(t,e,mt);const vt=await impostavariante(t,e,dt.trim().toLowerCase(),mt.trim().toLowerCase(),"LETM"==u.tipo?{t:"m"}:{t:"v"});i._stackmacro<=0&&i.checkheader&&"function"==typeof i.checkheader&&await i.checkheader({variante:dt,valore:vt,riga:u})}}}break;case"DO":{const gt=(u.contenuto||"").trim();let bt=!0;gt&&!muCalc(await intvaluta(t,e,gt))&&(bt=!1),u.next&&(bt||(l=u.next+1))}break;case"VARIANTE":case"FORVAR":case"FOR":{let wt,yt,$t,kt;if(i.oldstyle?(wt=u.contenuto.split(","),kt=wt[2]||"i",$t=wt[0],yt=wt[1]):(wt=getcolonne(u.contenuto||""),kt=wt[0]||"",$t=clean(wt[1],!0),yt=wt[2]||""),kt=kt.includes("$")?await intvaluta(t,e,kt):kt||"","FORVAR"==u.tipo||"VARIANTE"==u.tipo){const Et=await intvaluta(t,e,$t),Ct=Et?await dammivariante(t,e,Et):void 0;Ct?$t=Ct.tovec():($t=[],m.add("getvariante not found!",u))}else{const St=await intvaluta(t,e,$t||"");$t=$t?getcolonne(St):void 0}$t=$t||[];const xt=0;if(u.next){a[u.next].for={v:kt,elenco:$t,nc:xt,valido:yt};let Ot,Ft=!0;kt&&$t.length>0?xt>=$t.length?Ft=!1:(Ot=$t[xt],s.add(kt,Ot),yt&&(Ft=!muCalc(await intvaluta(t,e,yt)))):Ft=!1,Ft||(l=u.next-1)}else m.add("manca endfor/loop",u)}break;case"LOOP":{let _t=!0;u.contenuto&&!muCalc(await intvaluta(t,e,u.contenuto))&&(_t=!1),_t&&(l=u.prev-1);break}case"ENDFOR":if(!u.contenuto||muCalc(await intvaluta(t,e,u.contenuto)))if(u.for){const{v:Lt,elenco:At,valido:It}=u.for;if(Lt&&At.length>0&&u.for.nc<500)for(;;){if(u.for.nc++,u.for.nc<At.length){if(s.add(Lt,At[u.for.nc]),It&&muCalc(await intvaluta(t,e,It)))continue;l=u.prev;break}break}}else m.add("manca istruzione for",u);break;case"BREAK":case"EXIT":case"EXITFOR":u.next?u.contenuto.trim()?muCalc(await intvaluta(t,e,u.contenuto))&&(l=u.next):l=u.next:m.add("break outside loop",u);break;case"CONTINUE":u.next?u.contenuto&&!muCalc(await intvaluta(t,e,u.contenuto))||(l=u.next-1):m.add("continue outside loop",u);break;case"MSG":case"LOG":{const jt=await intvaluta(t,e,u.contenuto);logga(jt),m.add(jt)}break;default:{let Mt;if(u.contenuto.startsWith("!")){Mt=await intvaluta(t,e,u.contenuto);let zt="";const Dt=/^!(.\w+)[\s;,]\s*(.+)?$/gim.exec(Mt);if(Dt)if(Dt[1].startsWith("."))await getcbfunc(Mt,Mt.slice(1),[],s,t),zt="";else{const Nt=Dt[1].toLowerCase(),Tt=getcolonne(Dt[2]||"");zt=await getcbfunc(Mt,Nt,Tt,s,t)}zt&&outpush(r,zt)}else i.parsefnpunto&&"function"==typeof i.parsefnpunto&&u.contenuto.startsWith(".")?await i.parsefnpunto({dati:u.contenuto,output:r,id:i.id,vari:t.vari,amb:t}):(Mt=await intvaluta(t,e,u.contenuto),outpush(r,Mt))}}l++}return r}async function muGenerate_0(t,e,a,i,s){const r=t.genera[a];if(r){s.counter2=0;const n={};async function processavariante(o){if(s.isTestmode&&s.counter>s.isTestmode)return;if(o<r.vars.length){const a=r.vars[o];if(!n[a]){const i=await dammivariante(e,t,a),s=i?Object.keys(i.rows):void 0;if(s&&s.length>0){for(const t of s)e.vari.add(i.name,i.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 i=await muEval(e,t,t.formula[a],{limited:!0});if(i)for(const t of i){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 i=await muEval(e,t,t.formula[a],{limited:!0});i=i.join("\n").split("\n");for(const t of i)if(t){const e=getcolonne(t);l[a]||(l[a]=[]);const i={};for(let t=0;t<e.length;t++)i[`c${t}`]=e[t];l[a].push(i)}}await async function docallback(t,e,a,i,s,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=i.head[t]?i.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(s,o,n?a:void 0,r.counter,r.counter2),n=!1}}}(i,c,l,r,a,s)}await processavariante(0)}}const C=["l","a","p"],S=/^\{(:?(var|valid|formula|genera|header|v|f|g|h))[\s|}]/im,O=["s","g","h","p","q"];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:i}=checkmu(e,t.cat||"");this.name=a,this.cat=i,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&&C.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 i=this.amb.vari.var(t.cod);O.includes(t.t)||"string"==typeof i&&(i=i.split(",")[0]),a[t.cod]=i}}else if(this.parametri?._)for(const t of this.parametri._){const e=(t.split("=")[0]||"").trim().toLowerCase();let i=this.amb.vari.var[e];i=(i||"").split(",")[0],a[e]=i}return a}async setparametri(t){const e={},a=this.amb.ruleset||{};t||(t={}),this.dims&&C.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 i of this.head){const s=a[i.cod];s&&(s.islock?(i.visible="0",t[i.cod]=s.opz,i._islock=!0):t[i.cod]||(t[i.cod]=s.opz)),"g"!=i.t&&("z"!=i.t||t[i.cod]||(t[i.cod]="1"),i._v=t[i.cod]||"",e[i.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,i={}){if(e&&"string"==typeof e&&e.includes("$")&&(e=await intvaluta(this.amb,this,e)),i||(i={}),this.head){const _imposta=async(t,e,a,s)=>{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 s=this.amb.vari.var(r)||"";"thlm".includes(t.t)&&"string"==typeof s&&(s=s.split(",")[0]);let n=s;if("z"!=t.t||s||(this.amb.vari.add(r,"1"),s="1"),"m"==t.t&&t.spars){const e=getcolonne(t.spars);s=parseFloat(s||e[0])||0,e[1]&&parseFloat(s)<e[1]&&(s=parseFloat(e[1])||0),e[2]&&parseFloat(s)>e[2]&&(s=parseFloat(e[2])||0),s=String(s),this.amb.vari.add(r,s)}const o=await impostavariante(this.amb,this,r,e||t._v||s,t);if(t._v=void 0,s=this.amb.vari.var(r)||"","thl".includes(t.t)&&"string"==typeof s&&(s=s.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==s))))));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);i&&i[a.cod]&&(r=i[a.cod]),"string"==typeof r&&(r=r.split(",")[0],r&&r!=n&&r!=s?delete a._d:(a._v=e.toopz||s,a._d={cod:t.cod,opz:e.toopz}))}}))}return o}};let s,r=-1;if("#dim"==t)a=1;else{if(r=this.head.findIndex((e=>e.cod===t)),r<0)return;const i=this.head[r];s=await _imposta(i,e,r),a&&delete i._d}if(a)for(let t=r+1;t<this.head.length;t++)await _imposta(this.head[t],void 0,t);return s}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,i){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)}i||(i={}),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 i,s=a.substr(t+1);s.includes("$")&&(s=await intvaluta(this.amb,this,s)),this.head&&(i=this.head.find((t=>t.cod==e)))?i._v=s:await impostavariante(this.amb,this,e,s)}}if(this.head){let t=!0;for(const e of this.head){let s=await this.checkvalid(e.valid);a&&(s=!0),["g","g1","g2"].includes(e.t)?t=s:t&&s&&await this.setparametro(e.cod,i[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,e){let a,i;try{let s;if(({name:a,cat:i}=checkmu(t||this.name,e||this.cat||"")),this.name||(this.name=a),this.cat||(this.cat=i),this.azzera(),l&&(s=await l(i,a),"string"==typeof s&&(s.startsWith("{")||s.startsWith("["))&&(s=fromjson(s)),s&&s.head&&!Array.isArray(s.head)&&(s.head=[]),this.amb.checkscripts(s.linkscript),delete s.linkscript,s.head&&(s.dims=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}(s.dims))),s){if("string"==typeof s)await this.parsedata(s);else for(const t in s)this[t]=s[t];return!0}m.add(`missing cbGetFile: ${i}/${a}`)}catch(t){m.add(geterrdes(t),`macro.load: ${a}/${i}`)}}async loadAndCompile(t,e,a=!1){let i;const{name:s,cat:r}=checkmu(t,this.cat||e);return this.azzera(),h&&(i=await h(r,s)),i?(await this.parsedata(i,a),this.getmacro()):void m.add(`missing cbGetFile: ${s}/${r}`)}async#e(t,e,a,i){let s;const{name:r,cat:n}=checkmu(t,this.cat);if(h&&(s=await h(n,r)),!s)return[];if(s.includes("$1")&&i&&i.length>0)for(let t=1;t<i.length;t++)s=s.replaceAll(`$${t}`,i[t]);let o=muClComments(s);const c=[];e&&(o=o.filter((t=>!/^\{(:?(var|valid|formula|header|genera|v|f|h))[\s|}]/im.test(t))));for(const t of o){const i=S.exec(t);if(i)e=!i[1].startsWith(":"),c.push(t);else{const i=/^\s*\{i\s(.+)?\}/im.exec(t);if(i){const t=getcolonne(i[1]);if(!a.includes(t[0])){a.push(t[0]);const i=await this.loadinclude(t[0],e,a,t);Array.isArray(i)&&c.push(...i),a.pop()}}else c.push(t)}}return c}async parsedata(t,e=!1){if(this.azzera(),!t)return;const a=[];let i=muClComments(t),s=!1;const r=[];for(const t of i){const e=S.exec(t);if(e)s=!e[1].startsWith(":"),a.push(t);else{const e=/^\s*\{i\s(.+)?\}/im.exec(t);if(e){const t=getcolonne(e[1]),i=await this.#e(t[0],s,[t[0]],t);Array.isArray(i)&&a.push(...i)}else a.push(t)}}s=!1;let n=this.codice;for(const t of a){const e=S.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),i=a[0].trim().toLowerCase();e.rows[i]={annulla:0,v:a}}a.des&&(e.des=a.des),this.localvar[t]=e}i=this.valid,this.valid=[];for(const t of i){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))}i=r;const o=[];for(const t of i){const e=/^\s*([\w\-_]+)+[;,\s]\s*(.*)?$/im.exec(t);if(e){const t=getcolonne(e[2]),a=clean(e[1]);let i;if(a){i=o.find((t=>t.cod==a)),i||(i={cod:a,t:"t"},o.push(i));for(const e of t){const t=getcouple(e);switch(t.v){case"t":i.t=t.o;break;case"def":case"default":i.def=t.o;break;case"valid":case"colonna":case"hidden":t.o.startsWith("#")?this.formula[t.o.substring(1)]&&(i[t.v]=t.o):i[t.v]=t.o;break;default:i[t.v]=t.o}}}}}this.head=o,i=this.genera;const c={};for(const t in i)if(Array.isArray(i[t])){const e={codice:[],head:"",calcola:[],bom:[],vars:[],exclude:[]},a=/^\s*[!:]\s*(\w+)\s*(.*)$/i;for(const s of i[t]){const i=a.exec(clean(s));if(i)switch(i[1]){case"calcola":case"c":e.calcola=[...e.calcola,...getcolonne(i[2])];break;case"exclude":case"e":case"escludi":e.exclude=[...e.exclude,...getcolonne(i[2])];break;case"bom":case"db":e.bom=[...e.bom,...getcolonne(i[2])];break;case"vars":case"v":e.vars=[...e.vars,...getcolonne(i[2])];break;case"head":case"h":e.head=getcolonne(i[2]);break;default:this.errori.push(`genera ${t} => ${s}`)}else e.codice.push(s)}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 i=0;i<e.length;i++){const s=/^:p[;,\s]+(.*)?$/im.exec(e[i]);if(s)e[i]=null,a=!0,this.parametri[t]=getparalias(s[1]);else{const s=/^!(parametri|pars|p)[;,\s]+(.*)?$/im.exec(e[i]);s&&(e[i]=null,a=!0,this.parametri[t]=getparalias(s[2]))}}a&&(e=e.filter((t=>null!=t)))}return e=muClean(e,a)}}const F=/^\s*\{(:)?(var|deriva|valid|formula|header|genera|g|v|f|h)(\s.*)?\}/i;function verificaisvar(t,e){let a=!1;const i=[];for(let s=t;s<e.length;s++){const t=e[s].trim();let r=t.split("//")[0].trim();if(t.startsWith("/*"))a=!0;else if(a&&t.endsWith("*/"))a=!1;else if(!a){if(F.test(t))return{fl:!0,i2:s-1,cols:i};if(r.endsWith("\\"))return{fl:!1};if(t.startsWith(":h ")&&(r=r.substr(3).trim()),!r.startsWith(":")){const t=getcolonne(r);for(let e=0;e<t.length;e++){let a=t[e].length;t[e].includes(",")&&(a+=2),(!i[e]||i[e]<a)&&(i[e]=a)}}}}return{fl:!0,i2:e.length-1,cols:i}}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 i=this.d[a]??{};return t=t??{},this.d[a]={...i,...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:[]},i=!1;for(const s of e){const e=/^\s*\{(h|head|header)\s+(\w+)\}/im.exec(s);if(e)a={cod:e[2],des:e[2],r:[]},i=!1,t[e[2]]=a;else if(!/^\s*:/.exec(s)){const t=s.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&&(i||"sep"!=e.tipo?a.r.push(e):(a.des=e.des,a.valid=e.valid,a.visible=e.visible,i=!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;#i=void 0;#s=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:O}}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.#i=void 0,this.#s=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(f&&!this.varelenco[t]){const e=await f("headers",t,"_varianti");Array.isArray(e)?this.varelenco[t]=e:e.vars&&(this.varelenco[t]=e.vars,e.alias&&(this.#i=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.#i=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,i=[],s=0){this.item=clean(t,!0),this.rule=clean(e,!0),this.model=clean(a,!0),this.ruleset=toruleset(i),this.data=s||(new Date).toInt()}async getheader(t){let e;return!this.#a&&f&&(e=await f("headers",this.cat,"_headers"),this.parseheaderfrominfo(e)),this.#a||(this.#a={}),this.#a[t]}async getalias(){let t;return!this.#i&&f&&(t=await f("headers",this.cat,"_alias"),this.parseheaderfrominfo(t)),this.#i||(this.#i={}),this.#i}get deriva(){return this.#s,this.#s||[]}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 m.add("Macro non valida:"+e,t);let i=clean(a[1],!0);i.includes("$")&&(i=await this.vari.valuta(i));const s=getcolonne(a[2]),{name:r,cat:n}=checkmu(i,this.cat);this.cat=n;const o=`${n}/${r}`;if(!this.macro[o]){const e=new Macro(this,r);await e.load()?this.macro[o]=e:m.add(`macro fail to load ${o}`,t)}return i=this.macro[o],i?{macro:i,pars:s}:(m.add(`macro non trovata ${o}`,t),{})}catch(e){m.add(geterrdes(e),`ambiente.getmacro: ${t?.contenuto}`)}}async getvariante(t){const{name:e,cat:a}=checkmu(t,this.cat);let i=e,s={};if(a==this.cat&&this.#i&&this.#i[e]&&(s=this.#i[e]||{},i=s.cod),await this.#n(a),this.varelenco[a]&&!this.varelenco[a].includes(e))return;const r=`${a}/${i}`;let n;return this.varianti[r]?n=this.varianti[r]:(n=new Variante(this),await n.load(r,a),this.varianti[r]=n),s&&(s.des&&(n.des=s.des),s.vdef&&(n.vdef=s.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 i=a.getmacro();e("macros",{cod:t,info:JSON.stringify(i),isgenera:a.isgenera,isheader:a.isheader,iscodice:a.iscodice})}async barrecompila(t,e,a){const i=new CodiceBarra;await i.compila(t,e);for(const t in i.barre){a("barcodes",{cod:t,des:"",info:JSON.stringify(i.barre[t])})}return i}async tojson(t){let e;return u&&(e=await u("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.#i=void 0,this.#s=void 0,this.#r=void 0,f){const t=await f("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.#i&&e("infos",{cod:"alias",des:"",info:JSON.stringify(this.#i)}),this.#s&&e("infos",{cod:"deriva",des:"",info:JSON.stringify(this.#s)}),this.#r&&e("infos",{cod:"typos",des:"tipologie",info:JSON.stringify(this.#r)})}}async checkvarianti(t,e){if(!t||!e?.length)return;t=checkname(t),await this.#n(t);const a=this.varelenco[t],i=[];for(let s of e){s=clean(s,!0);const e=`${t}/${s}`;this.varianti[e]||a&&a.includes(s)&&i.push(s)}if(i.length&&c){const e=await c(t,i);if(e&&e.length)for(const a of e){const{name:e,content:i}=a,s=new Variante(this);s.setheader(e,t),i&&await s.loadContentExtended(i),this.varianti[s.key]=s}}}async getheaderfromdb(t){const e=await f("header",this.cat,t,!this.#s);let{head:a,rows:i,macros:s,deriva:r,llvars:n}=e;for(const t of i)t.cod=clean(t.cod),t.alias=clean(t.alias),t.t=clean(t.t);if(!n){n=new Set;for(const t of i)if("p"==t.tipo);else{const e=t.alias?t.alias:t.cod;n.add(e)}n=[...n]}this.#s||(this.#s=r),await this.#n(this.cat),a.cod=clean(a.cod),a.rule=clean(a.rule),a.ruledef=a.ruledef||[];const o=[],l=this.varelenco[this.cat];for(const t of n)this.varianti[`${this.cat}/${t}`]||l&&l.includes(t)&&o.push(t);if(o.length&&c){const t=await c(this.cat,o);if(t&&t.length)for(const e of t){const{name:t,content:a}=e,i=new Variante(this);i.setheader(t,this.cat),a&&await i.loadContentExtended(a),this.varianti[i.key]=i}}return{head:a,rows:i,macros:s}}async getlinkedmacros(t,e){const getkey=t=>t.includes("/")?t:`${this.cat}/${t}`,a=[];let i;if(t&&(i=getkey(t),this.macro[i]||a.push(t)),e&&"string"==typeof e){const t=e.split(";");for(const e of t)i=getkey(e),this.macro[i]||a.push(e)}if(a&&a.length>0&&l){const t=await l(this.cat,a);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 i=e.content[a];t[a]=i}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:i,cat:s}=checkmu(t,this.cat);a&&a.length&&(this.ruleset=toruleset(a));const r=`${s}/${i}`;if(!this.macro[r]){const e=await this.getheaderfromdb(i),{head:a,rows:n,macros:o}=e;await this.getlinkedmacros(a.rule,o);const c=new Macro(this,i);if(!a)return void m.add("Missing rule: "+t);if(a.rule){const t=this.macro[`${s}/${a.rule}`];if(t)for(const e in t)["cat","name","key"].includes(e)||(c[e]=t[e])}n&&n.length&&(c.head=n),this.macro[r]=c}this.ruleheader=r;const n=this.macro[r];return m.azzera(),await n.setparametri(e),n}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.#i=t.alias,this.#s=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}}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 _={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"}}},{Clear:L,Reset:A,Bold:I,Reverse:j,Red:M,Green:z,Yellow:D,Blue:N,Magenta:T,Cyan:W,White:R}=a();var V=o(process.argv);console.log("----------------------------------------------------------------------------------------"),console.log(`${I}${W}${I}Markuno:${A} command line utility del linguaggio (c) Croswil 2024 v. ${D}2.1.34${A}`),console.log("----------------------------------------------------------------------------------------");var J={FOLDERBASE:"./",DBWORK:"./data/app.db",FOLDERCAT:"./data/mu",FOLDEROUT:"./out",CAT:"cat"};const U=".lasts.markuno";t.existsSync(U)&&(J=JSON.parse(t.readFileSync(U)));var P=V._;(V.h||V.help||!P[2])&&(console.log(`Uso: ${I}markuno <funzioni> <[catalogo/]markuno> [opzioni]${A} \n${I}${W}Funzioni:${A} (seleziona una tra le seguenti)\n ${R} c, compila ${A}${z} compila un catalogo/Markuno + Codici Barra\n ${R} d, dump ${A}${z} compila e salva il compilato in formato json\n ${R} e, esegui ${A}${z} esegui un file markuno \n ${R} f, formatta ${A}${z} Formattazione di un file .mu o .var\n ${R} g, genera${A}${z} generatore di codice \n ${R} w, watch ${A}${z} abilita il watch su un file markuno \n ${R} gw <markuno> <maxele> ${A}${z} Genera con wath (solo i primi maxele=20 elementi senza salvare\n${I}${W}Opzioni:${A}${z}\n ${R} -h, --help${A}${z} mostra l'help\n ${R} -c, --cat <cat>${A}${z} catalogo (default='${J.CAT}' ) \n ${R} -d, --dbwork ${A}${z} database principale (default='${J.DBWORK}')\n ${R} -i, --init <folder>${A}${z} cartella di lavoro (default='${J.FOLDERCAT}' ) \n ${R} -o, --out <folder>${A}${z} cartella di output (default='${J.FOLDEROUT}' ) \n ${R} -x, --xlsx${A}${z} output in formato excel (generatore)\n `),process.exit(0));let K=0;const G="./",B=V.d||V.dbwork||J.DBWORK,q=V.i||V.init||J.FOLDERCAT,X=V.o||V.out||J.FOLDEROUT,H=V.c||V.cat||J.CAT;var Z=void 0,Y=!1;t.existsSync(q)||writeerror(`Manca la cartella di lavoro: ${q}`),J=Object.assign(J,{FOLDERBASE:G,DBWORK:B,FOLDERCAT:q,FOLDEROUT:X,CAT:H}),t.writeFileSync(U,JSON.stringify(J,null,2)),t.existsSync(q)||t.mkdirSync(q,{recursive:!0});const Q=V.x||V.xlsx;function writeerror(t){var e=t.stack.toString().split("\n");e.splice(0,1),e=e.filter((t=>!/module/.test(t)&&!/node\:/.test(t))),console.log(`${M}${t.message}${A}\n${e.join("\n")}`),process.exit(1)}function dbmu(a){var s=e.join(q,`mu_${a}.db`);t.existsSync(s)||r(s,_,"mus");var o=i.db(s);return n(_),o}function getinfofile(e){var a="",i="",s=`${e}.txt`;t.existsSync(s)&&(a=t.readFileSync(s).toString());s=`${e}.md`;return t.existsSync(s)&&(i=t.readFileSync(s).toString()),{def:a,md:i}}function getinfo(a,i){var s=t.readdirSync(i),r={cat:a,info:"",mu:[],var:[],inc:[]};for(var n of s){var o=e.join(i,n),c=e.extname(n),l=e.basename(n,c);"__info.md"==n?r.info=t.readFileSync(o).toString():".mu"==c?r.mu.push(l):".var"==c?r.var.push(l):".inc"==c&&r.inc.push(l)}return r}async function xlsexport(t,e,a){const i=await import("xlsx"),s=i.utils.json_to_sheet(t),r=i.utils.book_new();i.utils.book_append_sheet(r,s,e),i.writeFile(r,`${a}.xlsx`,{compression:!0})}async function xlsimport(t,e){const a=await import("xlsx");var i=a.readFile(t).Sheets[e];return a.utils.sheet_to_json(i)}async function cbGetMacro(e,a){var i=`${q}/${e}/${a}.mu`;return t.existsSync(i)?t.readFileSync(i).toString():""}async function cbGetVariante(e,a){var i=`${q}/${e}/${a}.var`;return t.existsSync(i)?t.readFileSync(i).toString():(m.add(`missing var: ${e}, ${a}`,{t:"cbGetVariante"}),"")}async function cbFunc(t,e,a){m.add(`missing fun: ${t}`,{t:"cbFunc"})}async function cbInfo(e,a,i){if(Array.isArray(i)){var s=[];for(var r of i){var n=await cbInfo(e,a,r);n&&s.push({tipo:r,value:n})}return s}switch(e){case"filter":if(!Z||!i&&!i[0])return[];if(Y)return[];var o=Z.all("select item,model,rule,varfilter,result,result2,exclude,exclude2 from limits where variant=?",i[0]);for(var c of o)c.valfilter=JSON.parse(c.varfilter||"{}"),c.result=JSON.parse(c.result||"[]"),c.result2=JSON.parse(c.result2||"[]");return o;case"headers":var l;return l="_typos"==i?`${q}/${a}/typos.json`:`${q}/${a}/${i}.inc`,t.existsSync(l)?t.readFileSync(l).toString():""}}async function cbGetFile(a,i){if(t.existsSync(e.join(G,i)))return t.readFileSync(e.join(G,i)).toString();const s=`${q}/${a}/${i}`;if(t.existsSync(s))return t.readFileSync(s).toString();m.add(`missing file: ${s}`,{t:"cbGetFile"})}function checkfilemu(a,i){var s=e.extname(i);[".mu",".var",".inc"].includes(s)||(s=".mu",i+=".mu");var r=e.join(q,a||H),n=e.join(G,i);if(t.existsSync(n))return{file:n,folder:r,diversi:!0};var o=i.indexOf("/");if(o>0&&(a=i.substr(0,o),i=i.substr(o+1),r=e.join(q,a||H),!t.existsSync(r)))throw new Error("missing folder: "+r);if(n=e.join(r,i),t.existsSync(n))return{file:n,folder:r,diversi:!1,ext:s};throw new Error(`non trovato il file: ${i} su ${r}`)}async function dowatch(e,a){var{file:i,folder:s,diversi:r}=checkfilemu(e.cat,P[3]||""),n=parseInt(P[4]||"10");console.log(`Start Watching: ${W}${I}${i}${A}`),t.watch(s,(async(t,i)=>{i&&await a(e,n)})),r&&t.watch(i,(async(t,i)=>{i&&await a(e,n)})),await a(e,n)}async function genera(a,i){var{file:s,folder:r,diversi:n}=checkfilemu(a.cat,P[3]||"");if(!t.existsSync(s))throw new Error("Manca il file: "+s);var o=e.extname(s),c=e.basename(s,o),l=new Macro(a,c),u=(new Date).valueOf();await l.loadAndCompile(`${c}${o}`);var f=(new Date).valueOf(),h={},d={},m=[],p=[],v=[];if(await async function muGenerate(t,e,a,i,s=0){if(t.isgenera&&i){const a={counter:0,keys:{},isTestmode:s};for(const s in t.genera)await muGenerate_0(t,e,s,i,a);return!0}}(l,a,0,((t,e,a,s,r)=>{if(i){var n=[];for(var o in e){var c=e[o];if("number"==typeof c&&(c=Math.round(1e4*c)/1e4+""),"__id"!=o){var l=n.length;v[l]||(v[l]=o,p[l]=o.length),p[l]<c.length&&(p[l]=c.length),n.push(c)}}m.push(n)}else{var u=t.split("_")[0]||u;if(h[u]||(h[u]=[]),h[u].push(e),e.cod&&(d[u]=!0,a))for(var f in a){var g=`${u}_${f}`;h[g]||(h[g]=[]);var b=a[f];for(o=0;o<b.length;o++){var w=b[o];h[g].push({padre:e.cod,i:o,comp:w.c0,qt:muCalc(w.c1),des:w.c2})}}}}),i),i){for(var g=0;g<v.length;g++)v[g]=v[g].padEnd(p[g]," ");for(var b of(console.log(`${D}${v.join(" | ")}${A}`),m)){for(g=0;g<b.length;g++)b[g]=b[g].padEnd(p[g]," ");console.log(b.join(" | "))}}else{var w=(new Date).valueOf(),y=0;for(var $ in d)y+=h[$].length,h[$].sort(((t,e)=>(t.cod||"").localeCompare(e.cod||"")));h._errori=l.geterrori(),t.writeFileSync(e.join(X,`gen_${c}.json`),JSON.stringify(h,null,2));const a=e.join(X,`gen_${c}.xlsx`);var k=(new Date).valueOf();if(Q){const t=await import("xlsx"),e=t.utils.book_new();for(var x in h){const a=t.utils.json_to_sheet(h[x]);t.utils.book_append_sheet(e,a,x)}t.writeFile(e,a,{compression:!0})}else t.existsSync(a)&&t.unlinkSync(a);var E=(new Date).valueOf();console.log(`${D}${I}EVAL........: ${y}${A}${W} rows\n${W}load/compile: ${I}${D}${f-u}${A}${W} ms.\n${W}generate....: ${I}${D}${w-f}${A}${W} ms.\n${W}save JSON...: ${I}${D}${k-w}${A}${W} ms.\n${W}save XLSX...: ${I}${D}${E-k}${A}${W} ms.\n--------------------------------\n${W}${I}TOTALE......: ${D}${E-u}${A}${W} ms.`)}}async function doesegui(a){var{file:i,folder:s,diversi:r}=checkfilemu(a.cat,P[3]||""),n=(new Date).valueOf(),o=t.readFileSync(i).toString(),c=new Macro(a,P[3]||"");K++,c.parsedata(o);var l=(new Date).valueOf(),u=await muEval(a,c,c.codice,{limited:!1,oldstyle:!0,localvar:c.localvar}),f=(new Date).valueOf();console.log(`${u.join("\n")}`),console.log(`${D}${I}EVAL ${K}${A}: ${i} => ${W}load:${I}${D}${l-n}${A}${W}ms. -- exec:${I}${D}${f-l}${A}${W}ms.${A}\n----------------------------------------------\n${m.toString()}`),t.writeFileSync(e.join(X,"logs.json"),JSON.stringify({loadandcompile:l-n,execute:f-l,vari:a.vari.dump(),codice:c.codice,errori:c.errori},null,2)),t.writeFileSync(e.join(X,"out.txt"),u.join("\n"))}await async function main(){try{var a=function muInit(t,e,a,i,s,r,n){const o=new Ambiente(t);return setcallbacks(e,a,i,s,r,n),o}(H,cbGetMacro,cbGetVariante,cbFunc,cbInfo,cbGetFile),r=e.join(q,H);if(t.mkdirSync(X,{recursive:!0}),!t.existsSync(r))throw new Error(`Manca il catalogo: ${H} su ${q}`);var n=(new Date).valueOf();switch(P[2].trim().toLowerCase()){case"g":case"genera":await genera(a,0);break;case"d":case"dump":await async function dump(a){var{file:i,folder:s,diversi:r}=checkfilemu(a.cat,P[3]||"");if(!t.existsSync(i))throw new Error("Manca il file: "+i);var n,o,c=e.extname(i),l=e.basename(i,c);if(console.log(l,c),".mu"==c){var u=new Macro(a,l);await u.loadAndCompile(`${l}${c}`),n=u.getmacro(),o=e.join(X,l+".json")}else".var"==c&&(n=await async function newVariante(t,e,a){const i=new Variante(a);return await i.load(t,e),i}(l,H,a),o=e.join(X,l+".var.json"));n&&(t.writeFileSync(o,JSON.stringify(n,null,2)),console.log(`${W}${I}Dump: ${A}${D}${o}`))}(a);break;case"gw":await dowatch(a,genera);break;case"c":case"compila":await async function compila(a){var r,n,o=e.join(q,H);if(!t.existsSync(o))throw new Error("Manca il catalogo "+H);if(!t.existsSync(B))throw new Error("Manca il database di lavoro: "+B);if(t.existsSync(B))if((Z=i.db(B)).esisteTabella("artbarre")){Y=!0;var c=Z.all("select cod cod,des des,flfm fm,coderr coderr,codalt codalt from artbarre order by cod ");for(var l of(n={},c)){(d=l.cod.trim().toLowerCase().substr(1))&&(n[d]={des:l.des,fm:l.fm,coderr:l.coderr.trim().toLowerCase(),codalt:l.codalt.trim().toLowerCase()})}r=Z.all("select codicebarra barcode,diml l,dima a,dimp p,cod cod from articoli where codicebarra like ? order by codicebarra","+%")}else r=Z.all("select barcode,l,a,p,cod from items where barcode>'' order by barcode"),n={};else console.warn("MISSING DBWORK (barre e limits)");var u=dbmu(H);u.begin(),u.run("delete from variants"),u.run("delete from macros"),u.run("delete from barcodes"),u.run("delete from extras");var f=getinfo(H,o);for(var h of(await a.compila(f,((t,e)=>{if(e){if("macros"===t){var{def:a,md:i}=getinfofile(`${e.cod}.mu`);e.def=a,e.md=i}s(u,t,e,"mus")}})),f.var)){var d,m=`${o}/${h}.var.txt`;if(t.existsSync(m))(d=muLimits(t.readFileSync(m).toString()))&&d.length&&s(u,"extras",{tipo:"l",cod:h,info:JSON.stringify(d)},"mus")}await a.barrecompila(r,n,((t,e)=>{s(u,t,e,"mus")})),s(u,"infos",{cod:"info",des:f.cat,info:JSON.stringify({cat:f.cat,md:f.info})},"mus"),Z&&Z.chiudi();u.commit(),u.chiudi()}(a),console.log(`Compilazione catalogo: ${M}${I}${H}${A}: ${D}${(new Date).valueOf()-n}ms.`);break;case"x":case"e":case"esegui":await doesegui(a);break;case"f":case"format":!function formatta(e){var{file:a,folder:i,diversi:s,ext:r}=checkfilemu(e.cat,P[3]||"");if(t.existsSync(a)){var n=t.readFileSync(a).toString(),o=".var"==r;n=function muFormatcode(t,e){const a=t.split("\n"),i=[];let s=0,r=!1,n=!1,o=[],c=e;if(c){const t=verificaisvar(0,a);c=t.fl,c&&(o=t.cols)}for(let t=0;t<a.length;t++){const e=a[t];let l=e.trim();const u=l.split("//");let f=u[0].trim();u.splice(0,1);const h=u.length?` // ${u.join("//").trim()} `:"";if(l.startsWith("/*"))r=!0,i.push(l);else if(r&&l.endsWith("*/"))r=!1,i.push(l);else if(r)i.push(e);else{const e=F.exec(l);if(e){if(i.push(l),s=e[1]?0:1,/^\s*\{(var|deriva|header|v|h)(\s.*)?\}/i.test(l)){const e=verificaisvar(t+1,a);c=e.fl,c&&(o=e.cols)}else c=!1;n=!1;continue}if(c)if(f.startsWith(":")&&!f.startsWith(":h ")||!f)i.push(l);else{let t=" ";f.startsWith(":h ")&&(f=f.substr(3).trim(),t=":h ");const e=getcolonne(f);for(let t=0;t<e.length;t++)e[t].includes(",")&&(e[t]=`"${e[t]}"`),e[t]=e[t].padEnd(o[t]," ");i.push(`${t}${e.join(" , ")} ${h}`)}else{const t=" ".repeat(s>=0?s:0);if(n)i.push(`${t} ${l}`);else{let e="";l.startsWith("#")&&(e=l.substring(1).split(" ")[0].toUpperCase(),l="#"+e+l.substring(e.length+1)),["IF","IFDEF","IFNDEF"].includes(e)?l.indexOf("#",2)<0?(i.push(`${t}${l}`),s++):(l=l.replace(/#([\w]+)/g,((t,e)=>"#"+e.toUpperCase())),i.push(`${t}${l}`)):["FOR","SELECT","FORVAR","VARIANTE","DO"].includes(e)?(i.push(`${t}${l}`),s++):["ELSEIF","ELSE","ELSEIFDEF","ELSEIFNDEF","CASE","CASES","DEFAULT"].includes(e)&&s>0?i.push(" ".repeat(s>0?s-1:0)+l):["ENDIF","ENDSELECT","LOOP","ENDFOR"].includes(e)?(i.push(" ".repeat(s>0?s-1:0)+l),s--,s<0&&(s=0)):l.startsWith("_ ")||l.startsWith(":")?i.push(l):i.push(t+l)}n=f.endsWith("\\")}}}return i.join("\n")}(n,o),t.writeFileSync(a,n),console.log(`formatted: ${o} ${W}${I}${a}${A}`)}}(a);break;case"w":case"watch":await dowatch(a,doesegui);break;default:throw new Error("Funzione non contemplata (g,c,b,x)")}}catch(t){writeerror(t)}}();export{dbmu,getinfo,getinfofile,xlsexport,xlsimport};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "croswil_markuno",
3
- "version": "2.1.25",
3
+ "version": "2.1.27",
4
4
  "private": false,
5
5
  "dependencies": {
6
6
  "@gltf-transform/core": "^4.2.1",