@forgenex/cli 0.2.1 → 0.4.0
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/GUIA-IA.md +87 -2
- package/README.md +3 -1
- package/REFERENCIA.md +13 -2
- package/dist/forgenex.js +24 -16
- package/ejemplos/archivos-ficha/extension.json +18 -0
- package/ejemplos/archivos-ficha/interfaz/index.html +100 -0
- package/extension.schema.json +17 -0
- package/licencias.txt +1 -1
- package/package.json +1 -1
- package/puente-extension.d.ts +37 -0
- package/puente-extension.mjs +15 -2
- package/solucion.schema.json +1 -0
package/dist/forgenex.js
CHANGED
|
@@ -1,37 +1,45 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __fgxRequire } from "node:module"; const require = __fgxRequire(import.meta.url);
|
|
3
|
-
var Zh=Object.defineProperty;var m=(e,o,t)=>()=>{if(t)throw t[0];try{return e&&(o=e(e=0)),o}catch(n){throw t=[n],n}};var eg=(e,o)=>{for(var t in o)Zh(e,t,{get:o[t],enumerable:!0})};import{AsyncLocalStorage as og}from"node:async_hooks";import{readdirSync as tg}from"node:fs";import{createRequire as rg}from"node:module";import{fileURLToPath as ng}from"node:url";function eo(e,o){let n=Nc[e]?.[o];if(n!==void 0)return n;for(let r of sg[e]??[]){let a=r.regex.exec(o);if(a)return r.traduccion.replace(/%\{([\w]+)\}/g,(s,l)=>{let d=r.nombres.indexOf(l);return d<0?s:a[d+1]})}return o}var ig,ag,Nc,sg,cg,Eo,Br=m(()=>{ig=tg(new URL("./locales/",import.meta.url)).filter(e=>/\.(?:ts|js)$/.test(e)&&!e.endsWith(".d.ts")),ag=rg(import.meta.url),Nc=Object.fromEntries(ig.map(e=>[e.replace(/\.(?:ts|js)$/,""),ag(ng(new URL(`./locales/${e}`,import.meta.url))).default])),sg=Object.fromEntries(Object.entries(Nc).map(([e,o])=>[e,Object.entries(o).filter(([t])=>t.includes("%{")).map(([t,n])=>{let r=[],a=0,s="";for(let l of t.matchAll(/%\{([\w]+)\}/g)){let d=l.index;s+=t.slice(a,d).replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"([\\s\\S]*?)",r.push(l[1]),a=d+l[0].length}return s+=t.slice(a).replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),{regex:new RegExp(`^${s}$`),nombres:r,traduccion:n,especificidad:t.replace(/%\{[\w]+\}/g,"").length}}).sort((t,n)=>n.especificidad-t.especificidad)])),cg=new og,Eo=()=>cg.getStore()?.idioma??"es"});var z,i,q=m(()=>{Br();z=class extends Error{constructor(t,n,r,a=!0,s){super(a?eo(Eo(),r):r);this.estado=t;this.codigo=n;this.datos=s}estado;codigo;datos},i=(e,o=!0)=>new z(400,"peticion_invalida",e,o)});var U,lg,$c,xc=m(()=>{U={id:"Id del registro."},lg=[{nombre:"contacto.creado",descripcion:"Se ha creado un contacto.",datos:U},{nombre:"contacto.actualizado",descripcion:"Han cambiado datos de un contacto.",datos:{...U,campos:"Qu\xE9 columnas (si se sabe).",lote:"La acci\xF3n, si fue en lote."}},{nombre:"contacto.borrado",descripcion:"Se ha borrado un contacto (tambi\xE9n al fusionarlo en otro).",datos:{...U,fusionado_en:"Si se fusion\xF3: en cu\xE1l."}},{nombre:"empresa.creada",descripcion:"Se ha creado una empresa.",datos:U},{nombre:"empresa.actualizada",descripcion:"Han cambiado datos de una empresa.",datos:{...U,campos:"Qu\xE9 columnas (si se sabe)."}},{nombre:"empresa.borrada",descripcion:"Se ha borrado una empresa.",datos:U},{nombre:"contacto.fusionado",descripcion:"Un contacto se ha fusionado en otro: quien guarde su id, que lo cambie por el que queda.",datos:{...U,se_va:"El que se fue.",queda:"El que queda (= id)."}},{nombre:"empresa.fusionada",descripcion:"Una empresa se ha fusionado en otra: quien guarde su id, que lo cambie por la que queda.",datos:{...U,se_va:"La que se fue.",queda:"La que queda (= id)."}},{nombre:"oportunidad.creada",descripcion:"Se ha creado una oportunidad.",datos:U},{nombre:"oportunidad.actualizada",descripcion:"Han cambiado datos de una oportunidad (no la etapa).",datos:{...U,campos:"Qu\xE9 columnas (si se sabe)."}},{nombre:"oportunidad.etapa_cambiada",descripcion:"Una oportunidad ha cambiado de etapa.",datos:{...U,de:"Etapa anterior.",a:"Etapa nueva."}},{nombre:"oportunidad.ganada",descripcion:"Una oportunidad ha pasado a ganada (adem\xE1s de etapa_cambiada).",datos:{...U,de:"Etapa anterior.",a:"won",origen:"\xABcrm\xBB (una persona o la API) o \xABfacturacion\xBB (su presupuesto principal se acept\xF3).",quien:"Nombre de quien la movi\xF3 (persona del espacio o due\xF1o de la clave), si se sabe."}},{nombre:"oportunidad.perdida",descripcion:"Una oportunidad ha pasado a perdida (adem\xE1s de etapa_cambiada).",datos:{...U,de:"Etapa anterior.",a:"lost",origen:"\xABcrm\xBB o \xABfacturacion\xBB (su presupuesto principal se rechaz\xF3).",motivo:"El motivo de p\xE9rdida, si se dio.",quien:"Nombre de quien la movi\xF3 (persona del espacio o due\xF1o de la clave), si se sabe."}},{nombre:"oportunidad.archivada",descripcion:"Una oportunidad ha salido del embudo al archivo.",datos:U},{nombre:"oportunidad.borrada",descripcion:"Se ha borrado una oportunidad.",datos:U},{nombre:"nota.creada",descripcion:"Nueva nota en el hilo de un contacto o de una oportunidad.",datos:{...U,contacto_id:"Si es de un contacto.",oportunidad_id:"Si es de una oportunidad."}},{nombre:"nota.actualizada",descripcion:"Se ha editado una nota.",datos:U},{nombre:"nota.borrada",descripcion:"Se ha borrado una nota.",datos:U},{nombre:"nota.mencion",descripcion:"Una nota menciona (@) a miembros del espacio: al crearla, o al editarla con menciones nuevas. Solo miembros activos (la base filtra el resto).",datos:{...U,contacto_id:"Si es de un contacto.",oportunidad_id:"Si es de una oportunidad.",mencionados:"Ids de los miembros mencionados por primera vez en esta nota (miembros.listar)."}},{nombre:"tarea.creada",descripcion:"Se ha creado una tarea.",datos:{...U,contacto_id:"Su contacto."}},{nombre:"tarea.actualizada",descripcion:"Ha cambiado una tarea (o se ha reabierto).",datos:{...U,campos:"Qu\xE9 columnas (si se sabe)."}},{nombre:"tarea.completada",descripcion:"Se ha completado una tarea.",datos:U},{nombre:"tarea.borrada",descripcion:"Se ha borrado una tarea.",datos:U},{nombre:"contacto.etiquetado",descripcion:"Una Persona ha recibido una etiqueta (una vez por etiqueta a\xF1adida, venga de donde venga).",datos:{...U,etiqueta:"El nombre de la etiqueta.",etiqueta_id:"Su id."}},{nombre:"lead.recibido",descripcion:"Ha entrado un lead desde una web (leads.crear): el id es el de su Persona.",datos:{...U,origen:"De d\xF3nde viene (\xABlanding:<slug>\xBB).",oportunidad_id:"La oportunidad que abri\xF3."}},{nombre:"formulario.respuesta",descripcion:"Alguien ha respondido un formulario p\xFAblico del CRM.",datos:{...U,formulario_id:"El formulario.",contacto_id:"Su contacto.",oportunidad_id:"La oportunidad, si el formulario la abre."}},{nombre:"registro.creado",descripcion:"Se ha creado un registro de un m\xF3dulo del cliente.",datos:{...U,modulo:"La clave del m\xF3dulo (mod_<clave> en la API v1).",origen:"\xABformulario\xBB o \xABimportacion\xBB, si no vino de la interfaz o la API."}},{nombre:"registro.actualizado",descripcion:"Han cambiado datos de un registro de un m\xF3dulo.",datos:{...U,modulo:"La clave del m\xF3dulo.",campos:"Qu\xE9 campos."}},{nombre:"registro.borrado",descripcion:"Se ha borrado un registro de un m\xF3dulo.",datos:{...U,modulo:"La clave del m\xF3dulo."}}],$c=lg.map(e=>e.nombre)});function dg(e,[o,t]){let n=new Set;for(let r of e.split(",")){let a=/^(\*|(\d{1,2})(?:-(\d{1,2}))?)(?:\/(\d{1,2}))?$/.exec(r);if(!a)return null;let s=a[1]==="*"?o:Number(a[2]),l=a[1]==="*"?t:a[3]!==void 0?Number(a[3]):a[4]!==void 0?t:s,d=a[4]!==void 0?Number(a[4]):1;if(s<o||l>t||s>l||d<1)return null;for(let u=s;u<=l;u+=d)n.add(u)}return n}function Cc(e){let o=e.trim().split(/\s+/);if(o.length!==5)return null;let t=o.map((r,a)=>dg(r,ug[a]));if(t.some(r=>!r))return null;let n=new Set([...t[4]].map(r=>r===7?0:r));return{minutos:t[0],horas:t[1],dias:t[2],meses:t[3],semana:n,diaLibre:o[2]==="*",semanaLibre:o[4]==="*"}}function Oc(e){let o=[...e.horas].sort((a,s)=>a-s),t=[...e.minutos].sort((a,s)=>a-s),n=o.flatMap(a=>t.map(s=>a*60+s));if(n.length<=1)return 1440;let r=1440-n.at(-1)+n[0];for(let a=1;a<n.length;a++)r=Math.min(r,n[a]-n[a-1]);return r}var ug,sy,Sc=m(()=>{ug=[[0,59],[0,23],[1,31],[1,12],[0,7]];sy=new Intl.DateTimeFormat("en-GB",{timeZone:"Europe/Madrid",hourCycle:"h23",minute:"numeric",hour:"numeric",day:"numeric",month:"numeric",weekday:"short"})});function jc(e){let o=(t,n)=>Number.isInteger(t)?Math.min(n.max,Math.max(n.min,t)):n.defecto;return{ms:o(e?.tope?.ms,L.ms),memoriaMb:o(e?.tope?.memoria_mb,L.memoriaMb)}}var L,ar=m(()=>{L={simultaneas:2,ms:{defecto:5e3,min:100,max:3e4},memoriaMb:{defecto:64,min:16,max:256},pilaBytes:1048576,margenMs:2e3,llamadasApi:100,llamadasRed:10,llamadaCaracteres:327680,llamadasEnVuelo:8,codigoBytes:262144,entradaBytes:65536,salidaBytes:65536,red:{cuerpoBytes:262144,respuestaBytes:1048576,plazoMs:5e3},webhookBytes:65536,cronMinutos:15}});function Ac(e){if(!e.startsWith("*."))return!1;let o=e.slice(2).toLowerCase();if(mg.has(o)||fg.test(o))return!0;let t=o.split(".");return t.length===2&&t[1].length===2&&pg.has(t[0])}var pg,mg,fg,Ec=m(()=>{pg=new Set(["co","com","net","org","gov","gob","edu","ac","nom","mil","ltd","plc","me","or","ne","go","info","biz","int"]),mg=new Set(["github.io","gitlab.io","pages.dev","workers.dev","vercel.app","netlify.app","web.app","firebaseapp.com","herokuapp.com","appspot.com","azurewebsites.net","cloudfront.net","amazonaws.com","blogspot.com","wordpress.com","glitch.me","onrender.com","fly.dev","repl.co","ngrok.io","ngrok-free.app","trycloudflare.com","r2.dev","supabase.co","myshopify.com","firebaseio.com","duckdns.org","no-ip.org","ddns.net","netlify.com","blob.core.windows.net","web.core.windows.net"]),fg=/^(s3([.-][a-z0-9-]+)?\.amazonaws\.com|blogspot\.[a-z]{2,3}(\.[a-z]{2})?)$/});function Ei(e,o=0){if(o>20)throw i("El manifiesto anida demasiado.");if(Array.isArray(e))return e.forEach(t=>Ei(t,o+1));if(fe(e))for(let t of Object.keys(e)){if(hg.has(t))throw i(`Clave no admitida \xAB${t}\xBB.`);Ei(e[t],o+1)}}function xe(e,o,t){for(let n of Object.keys(e))if(!o.includes(n))throw i(`${t}: clave no admitida \xAB${n.slice(0,40)}\xBB.`)}function $g(e,o,t={}){return _g.test(e.replace(Ng,""))?`\xAB${o}\xBB: lleva caracteres de control, invisibles o de direcci\xF3n del texto.`:t.reservar&&!t.firmada&&ki(e)?`\xAB${o}\xBB: \xABForgeNEX\xBB est\xE1 reservado a lo que publica ForgeNEX.`:null}function V(e,o,t,n=!0){if(e!=null&&typeof e!="string")throw i(`\xAB${o}\xBB: texto de hasta ${t} caracteres.`);let r=typeof e=="string"?e.trim():"";if(r===""){if(n)throw i(`Falta \xAB${o}\xBB.`);return""}if(r.length>t)throw i(`\xAB${o}\xBB: texto de hasta ${t} caracteres.`);let a=$g(r,o);if(a)throw i(a);return r}function Og(e){return e.normalize("NFKC").replace(new RegExp("(\\p{Ll})(?=\\p{Lu})","gu"),"$1 ").replace(new RegExp("(\\p{Lu})(?=\\p{Lu}\\p{Ll})","gu"),"$1 ").split(/[^\p{L}\p{N}\p{M}]+/u).map(qi).filter(Boolean)}function zc(e,o,t){let n=oe(e,o,Mc,t);if(Ac(n))throw i(`\xAB${o}\xBB: \xAB${n}\xBB abarca dominios de cualquiera; pon el dominio de tu servicio (\xAB*.api.ejemplo.co.uk\xBB o \xABapi.ejemplo.co.uk\xBB).`);return n}function oe(e,o,t,n){if(typeof e!="string"||!t.test(e))throw i(`\xAB${o}\xBB: ${n}.`);return e}function be(e,o,t){if(e==null)return[];if(!Array.isArray(e))throw i(`\xAB${o}\xBB: una lista.`);if(e.length>t)throw i(`\xAB${o}\xBB: como mucho ${t}.`);return e}function Ce(e,o,t){let n=new Set;for(let r of e){let a=o(r);if(n.has(a))throw i(`\xAB${t}\xBB: \xAB${a}\xBB est\xE1 repetido.`);n.add(a)}return e}function Rc(e,o){let t=V(e,o,500),n;try{n=new URL(t)}catch{throw i(`\xAB${o}\xBB: una direcci\xF3n https.`)}if(n.protocol!=="https:"||n.username||n.password||!Mc.test(n.hostname)||n.hostname.startsWith("*."))throw i(`\xAB${o}\xBB: una direcci\xF3n https con nombre de dominio (ni IP ni localhost).`);return n.toString()}function Sg(e){let[o,t]=e.split(".");return qi(o??"")==="forgenex"||qi(t??"")==="forgenex"}function St(e){if(Object.hasOwn(Gr,e))return e;let o=e.startsWith("mod_")?e.slice(4):e;return vg.test(o)?`mod_${o}`:null}function jg(e){if(e===void 0)return{modulos:{},almacen:!1,red_hacia:[],eventos:[]};if(!fe(e))throw i("\xABpermisos\xBB: un objeto.");xe(e,["modulos","almacen","red_hacia","eventos"],"Permisos");let o={};if(e.modulos!==void 0){if(!fe(e.modulos))throw i("\xABpermisos.modulos\xBB: un objeto { m\xF3dulo: [operaciones] }.");let r=Object.entries(e.modulos);if(r.length>40)throw i("\xABpermisos.modulos\xBB: como mucho 40 m\xF3dulos.");for(let[a,s]of r){let l=St(a);if(!l)throw i(`\xABpermisos.modulos\xBB: \xAB${a.slice(0,60)}\xBB no es un m\xF3dulo (min\xFAsculas, n\xFAmeros y _).`);if(o[l])throw i(`\xABpermisos.modulos\xBB: \xAB${a}\xBB est\xE1 repetido.`);let d=Gr[l]?.ops??sr,u=be(s,`permisos.modulos.${a}`,4);if(!u.length)throw i(`\xABpermisos.modulos.${a}\xBB: di qu\xE9 operaciones (${d.join(", ")}).`);for(let f of u)if(typeof f!="string"||!d.includes(f))throw i(`\xABpermisos.modulos.${a}\xBB: operaciones ${d.join(", ")}.`);let p=new Set(u);if((p.has("editar")||p.has("borrar"))&&!p.has("ver"))throw i(`\xABpermisos.modulos.${a}\xBB: para \xABeditar\xBB o \xABborrar\xBB hace falta \xABver\xBB.`);o[l]=sr.filter(f=>p.has(f))}}if(e.almacen!==void 0&&typeof e.almacen!="boolean")throw i("\xABpermisos.almacen\xBB: s\xED o no (true/false).");let t=Ce(be(e.red_hacia,"permisos.red_hacia",20).map((r,a)=>zc(r,`permisos.red_hacia[${a}]`,"un dominio (\xABapi.ejemplo.com\xBB o \xAB*.ejemplo.com\xBB; ni IP ni localhost)")),r=>r,"permisos.red_hacia").sort(),n=Ce(be(e.eventos,"permisos.eventos",40).map((r,a)=>{if(typeof r!="string"||!$c.includes(r))throw i(`\xABpermisos.eventos[${a}]\xBB: un evento del cat\xE1logo (GET /api/v1/eventos).`);return r}),r=>r,"permisos.eventos").sort();return{modulos:Object.fromEntries(Object.entries(o).sort(([r],[a])=>r.localeCompare(a))),almacen:e.almacen===!0,red_hacia:t,eventos:n}}function Pc(e,o){let t=o.lastIndexOf(".");if(t<1)return!1;let n=St(o.slice(0,t));return!!n&&(e.modulos[n]??[]).includes(o.slice(t+1))}function Tc(e,o){let t={};if(e===void 0)return t;if(!fe(e)||Object.keys(e).length>20)throw i(`\xAB${o}\xBB: { campo: { tipo, desc } }, como mucho 20.`);for(let[n,r]of Object.entries(e)){if(oe(n,o,qo,"nombres de campo en min\xFAsculas y _"),!fe(r))throw i(`\xAB${o}.${n}\xBB: { tipo, desc }.`);xe(r,["tipo","desc","requerido"],`${o}.${n}`);let a=V(r.tipo,`${o}.${n}.tipo`,10);if(!["texto","numero","si_no","fecha"].includes(a))throw i(`\xAB${o}.${n}.tipo\xBB: texto, numero, si_no o fecha.`);t[n]={tipo:a,desc:V(r.desc,`${o}.${n}.desc`,200),requerido:r.requerido===!0}}return t}function Xr(e,o={}){if(typeof e=="string"){if(e.length>Ur)throw i("El manifiesto pasa de 256 KB.");try{e=JSON.parse(e)}catch{throw i("El manifiesto no es un JSON v\xE1lido.")}}else if(JSON.stringify(e??null).length>Ur)throw i("El manifiesto pasa de 256 KB.");if(!fe(e))throw i("El manifiesto tiene que ser un objeto.");if(Ei(e),e.formato!==Xo)throw i(`No es una app (formato \xAB${Xo}\xBB).`);if(xe(e,["$schema","formato","formato_version","id","nombre","descripcion","version","autor","icono","idiomas","compatible_crm","licencia","depende_de","ofrece","usa","solucion","montajes","funciones","servidor","herramientas_ia","ajustes","secretos","permisos"],"App"),!Number.isInteger(e.formato_version)||e.formato_version<1)throw i("\xABformato_version\xBB: un entero (1).");if(e.formato_version>Qr)throw i("La app es de una versi\xF3n del formato m\xE1s nueva que este CRM.");let t=oe(e.id,"id",ji,"dominio inverso en min\xFAsculas (\xABcom.tuempresa.mi-extension\xBB)");if(t.length>200)throw i("\xABid\xBB: como mucho 200 caracteres.");if(!o.firmada&&Sg(t))throw i("\xABid\xBB: los que empiezan por \xABcom.forgenex.\xBB o \xABforgenex.\xBB est\xE1n reservados a lo que publica ForgeNEX; usa el dominio de tu empresa (\xABcom.tuempresa.mi-extension\xBB).");let n=V(e.nombre,"nombre",80),r=oe(e.version,"version",gg,"versi\xF3n semver (\xAB1.0.0\xBB)"),a;if(typeof e.autor=="string")a={nombre:V(e.autor,"autor",120)};else if(fe(e.autor))xe(e.autor,["nombre","web"],"Autor"),a={nombre:V(e.autor.nombre,"autor.nombre",120),...e.autor.web!==void 0?{web:Rc(e.autor.web,"autor.web")}:{}};else throw i("Falta \xABautor\xBB (un nombre, o { nombre, web }).");if(!o.firmada){if(ki(n))throw i("\xABnombre\xBB: \xABForgeNEX\xBB est\xE1 reservado a lo que publica ForgeNEX.");if(ki(a.nombre))throw i("\xABautor\xBB: \xABForgeNEX\xBB est\xE1 reservado a lo que publica ForgeNEX.")}let s=e.icono===void 0?"puzzle":oe(e.icono,"icono",kc,"un icono de lucide (\xABpuzzle\xBB)"),l=Ce(be(e.idiomas,"idiomas",30).map((v,A)=>oe(v,`idiomas[${A}]`,bg,"un c\xF3digo de idioma (\xABes\xBB, \xABen\xBB, \xABpt-BR\xBB)")),v=>v,"idiomas"),d=null;if(e.compatible_crm!==void 0){let A=V(e.compatible_crm,"compatible_crm",80).split(/\s+/);if(A.length>2||!A.every(x=>qc.test(x)))throw i("\xABcompatible_crm\xBB: un rango (\xAB>=1.6.0-284\xBB, \xAB>=1.6.0-284 <2.0.0\xBB).");d=A.join(" ")}let u=e.licencia===void 0?null:V(e.licencia,"licencia",40),p=Ce(be(e.depende_de,"depende_de",20).map((v,A)=>{if(typeof v=="string")return{id:oe(v,`depende_de[${A}]`,ji,"el id de otra app"),version:null};if(!fe(v))throw i(`\xABdepende_de[${A}]\xBB: el id de otra app, o { id, version }.`);xe(v,["id","version"],`depende_de[${A}]`);let x=v.version===void 0?null:V(v.version,`depende_de[${A}].version`,80);if(x!==null&&!x.split(/\s+/).every(M=>qc.test(M)))throw i(`\xABdepende_de[${A}].version\xBB: un rango (\xAB>=1.0.0\xBB).`);return{id:oe(v.id,`depende_de[${A}].id`,ji,"el id de otra app"),version:x}}),v=>v.id,"depende_de");if(p.some(v=>v.id===t))throw i("\xABdepende_de\xBB: una app no depende de s\xED misma.");let f=(v,A)=>Ce(be(v,A,20).map((x,M)=>oe(x,`${A}[${M}]`,wg,"un nombre de contrato (\xABtaller.citas\xBB)")),x=>x,A),h=f(e.ofrece,"ofrece"),b=f(e.usa,"usa"),y=e.solucion===void 0||e.solucion===null?null:oe(e.solucion,"solucion",Ai,"el fichero de la soluci\xF3n dentro del paquete (\xABsolucion.json\xBB)");if(y!==null&&!y.endsWith(".json"))throw i("\xABsolucion\xBB: un fichero .json del paquete.");let w=jg(e.permisos),g=Ce(be(e.montajes,"montajes",20).map((v,A)=>{let x=`montajes[${A}]`;if(!fe(v))throw i(`\xAB${x}\xBB: un objeto.`);xe(v,["id","punto","entrada","titulo","icono","modulo","permiso","funciones"],x);let M=V(v.punto,`${x}.punto`,20);if(!Ot.includes(M))throw i(`\xAB${x}.punto\xBB: ${Ot.join(", ")}.`);let B=null;if(cr.has(M)){if(B=St(V(v.modulo,`${x}.modulo`,64)),!B)throw i(`\xAB${x}.modulo\xBB: el m\xF3dulo donde se cuelga.`);if(!(w.modulos[B]??[]).includes("ver"))throw i(`\xAB${x}\xBB: se cuelga de \xAB${v.modulo}\xBB, as\xED que \xABpermisos.modulos\xBB tiene que pedir verlo.`)}else if(v.modulo!==void 0)throw i(`\xAB${x}.modulo\xBB: solo en ${[...cr].join(", ")}.`);let I=v.permiso===void 0?null:V(v.permiso,`${x}.permiso`,80);if(I!==null&&!Pc(w,I))throw i(`\xAB${x}.permiso\xBB: \xAB${I}\xBB no est\xE1 en \xABpermisos.modulos\xBB.`);if(M==="publica"&&I!==null)throw i(`\xAB${x}.permiso\xBB: la p\xE1gina p\xFAblica no lleva permiso (la ve cualquiera con el enlace).`);let ae;if(M==="publica")ae=Ce(be(v.funciones,`${x}.funciones`,10).map((J,ge)=>oe(J,`${x}.funciones[${ge}]`,qo,"el nombre de una funci\xF3n")),J=>J,`${x}.funciones`);else if(v.funciones!==void 0)throw i(`\xAB${x}.funciones\xBB: solo en el montaje \xABpublica\xBB.`);return{id:oe(v.id,`${x}.id`,/^[a-z][a-z0-9_-]{0,40}$/,"min\xFAsculas, n\xFAmeros, _ y -"),punto:M,entrada:oe(v.entrada,`${x}.entrada`,Ai,"un fichero del paquete (\xABinterfaz/index.html\xBB)"),titulo:V(v.titulo,`${x}.titulo`,60),icono:v.icono===void 0?null:oe(v.icono,`${x}.icono`,kc,"un icono de lucide"),modulo:B,permiso:I,...ae?{funciones:ae}:{}}}),v=>v.id,"montajes");if(g.filter(v=>v.punto==="publica").length>1)throw i("\xABmontajes\xBB: una app tiene como mucho una p\xE1gina p\xFAblica.");let N=Ce(be(e.funciones,"funciones",20).map((v,A)=>{let x=`funciones[${A}]`;if(!fe(v))throw i(`\xAB${x}\xBB: un objeto.`);if(xe(v,["nombre","titulo","descripcion","entrada","disparador","tope","red","parametros","salida"],x),!fe(v.disparador))throw i(`\xAB${x}.disparador\xBB: { tipo, \u2026 }.`);xe(v.disparador,["tipo","evento","cron"],`${x}.disparador`);let M=V(v.disparador.tipo,`${x}.disparador.tipo`,20);if(!Vr.includes(M))throw i(`\xAB${x}.disparador.tipo\xBB: ${Vr.join(", ")}.`);let B={tipo:M};if(M==="evento"){let G=V(v.disparador.evento,`${x}.disparador.evento`,80);if(!w.eventos.includes(G))throw i(`\xAB${x}.disparador.evento\xBB: \xAB${G}\xBB tiene que estar en \xABpermisos.eventos\xBB.`);B.evento=G}if(M==="programada"){B.cron=oe(v.disparador.cron,`${x}.disparador.cron`,yg,"un cron de 5 campos (\xAB0 7 * * 1-5\xBB)");let G=Cc(B.cron);if(!G)throw i(`\xAB${x}.disparador.cron\xBB: un cron de 5 campos v\xE1lido (minuto 0-59, hora 0-23, d\xEDa 1-31, mes 1-12, semana 0-7).`);if(Oc(G)<L.cronMinutos)throw i(`\xAB${x}.disparador.cron\xBB: como mucho una vez cada ${L.cronMinutos} minutos.`)}let I=fe(v.tope)?v.tope:{};v.tope!==void 0&&xe(I,["ms","memoria_mb"],`${x}.tope`);let ae=I.ms===void 0?5e3:Number(I.ms),J=I.memoria_mb===void 0?64:Number(I.memoria_mb);if(!Number.isInteger(ae)||ae<L.ms.min||ae>L.ms.max)throw i(`\xAB${x}.tope.ms\xBB: de ${L.ms.min} a ${L.ms.max}.`);if(!Number.isInteger(J)||J<L.memoriaMb.min||J>L.memoriaMb.max)throw i(`\xAB${x}.tope.memoria_mb\xBB: de ${L.memoriaMb.min} a ${L.memoriaMb.max}.`);let ge=be(v.red,`${x}.red`,10).map((G,fo)=>zc(G,`${x}.red[${fo}]`,"un dominio"));for(let G of ge)if(!Ag(w.red_hacia,G))throw i(`\xAB${x}.red\xBB: \xAB${G}\xBB tiene que estar en \xABpermisos.red_hacia\xBB.`);let Be=Tc(v.parametros,`${x}.parametros`),Go={},Ho=Ce(be(v.salida,`${x}.salida`,30).map((G,fo)=>{let $e=`${x}.salida[${fo}]`;if(!fe(G))return oe(G,$e,qo,"nombres en min\xFAsculas y _ (o { clave, titulo })");xe(G,["clave","titulo"],$e);let De=oe(G.clave,`${$e}.clave`,qo,"nombres en min\xFAsculas y _");return G.titulo!==void 0&&(Go[De]=V(G.titulo,`${$e}.titulo`,60)),De}),G=>G,`${x}.salida`);if(M==="publica"&&ge.length)throw i(`\xAB${x}.red\xBB: una funci\xF3n \xABpublica\xBB no sale a la red (solo lee el CRM).`);if(Object.keys(Be).length&&M!=="automatizacion")throw i(`\xAB${x}.parametros\xBB: solo en las de disparador \xABautomatizacion\xBB (las dem\xE1s reciben su evento, su minuto o su webhook).`);return{nombre:oe(v.nombre,`${x}.nombre`,qo,"min\xFAsculas, n\xFAmeros y _"),titulo:v.titulo===void 0?null:V(v.titulo,`${x}.titulo`,80),descripcion:v.descripcion===void 0?null:V(v.descripcion,`${x}.descripcion`,300,!1),entrada:oe(v.entrada,`${x}.entrada`,Ai,"un fichero del paquete (\xABfunciones/calcular.js\xBB)"),disparador:B,tope:{ms:ae,memoria_mb:J},red:ge,parametros:Be,salida:Ho,titulos_salida:Go}}),v=>v.nombre,"funciones"),C=null;if(e.servidor!==void 0&&e.servidor!==null){if(!fe(e.servidor))throw i("\xABservidor\xBB: { url, webhooks }.");xe(e.servidor,["url","webhooks"],"Servidor");let v=Ce(be(e.servidor.webhooks,"servidor.webhooks",40).map((A,x)=>{if(typeof A!="string"||!w.eventos.includes(A))throw i(`\xABservidor.webhooks[${x}]\xBB: un evento que est\xE9 en \xABpermisos.eventos\xBB.`);return A}),A=>A,"servidor.webhooks");C={url:Rc(e.servidor.url,"servidor.url"),webhooks:v}}let S=new Set(N.map(v=>v.nombre));for(let v of g)for(let[A,x]of(v.funciones??[]).entries()){let M=N.find(B=>B.nombre===x);if(!M)throw i(`\xABmontajes\xBB.\xAB${v.id}\xBB.funciones[${A}]: \xAB${x}\xBB tiene que estar en \xABfunciones\xBB.`);if(M.disparador.tipo!=="publica")throw i(`\xABmontajes\xBB.\xAB${v.id}\xBB.funciones[${A}]: \xAB${x}\xBB tiene que ser de disparador \xABpublica\xBB.`)}let T=Ce(be(e.herramientas_ia,"herramientas_ia",20).map((v,A)=>{let x=`herramientas_ia[${A}]`;if(!fe(v))throw i(`\xAB${x}\xBB: un objeto.`);xe(v,["nombre","descripcion","entrada","salida","riesgo","funcion","escribe","permiso"],x);let M=Tc(v.entrada,`${x}.entrada`),B=V(v.riesgo,`${x}.riesgo`,10);if(!["bajo","medio","alto"].includes(B))throw i(`\xAB${x}.riesgo\xBB: bajo, medio o alto.`);let I=V(v.funcion,`${x}.funcion`,41);if(!S.has(I))throw i(`\xAB${x}.funcion\xBB: \xAB${I}\xBB tiene que estar en \xABfunciones\xBB.`);if(!["herramienta","calculo"].includes(N.find(J=>J.nombre===I)?.disparador.tipo??""))throw i(`\xAB${x}.funcion\xBB: \xAB${I}\xBB tiene que ser de disparador \xABherramienta\xBB (o \xABcalculo\xBB).`);if(v.escribe!==void 0&&typeof v.escribe!="boolean")throw i(`\xAB${x}.escribe\xBB: true o false.`);let ae=null;if(v.permiso!==void 0){let J=V(v.permiso,`${x}.permiso`,80),ge=J.lastIndexOf("."),Be=ge>0?St(J.slice(0,ge)):null;if(!Be||!Pc(w,J))throw i(`\xAB${x}.permiso\xBB: \xAB${J}\xBB no est\xE1 en \xABpermisos.modulos\xBB.`);ae=`${Be}.${J.slice(ge+1)}`}return{nombre:oe(v.nombre,`${x}.nombre`,/^[a-z][a-z0-9_]{2,40}$/,"min\xFAsculas, n\xFAmeros y _ (3 a 41)"),descripcion:V(v.descripcion,`${x}.descripcion`,500),entrada:M,salida:Ce(be(v.salida,`${x}.salida`,30).map((J,ge)=>oe(J,`${x}.salida[${ge}]`,qo,"nombres de campo")),J=>J,`${x}.salida`),riesgo:B,funcion:I,escribe:v.escribe===!0,permiso:ae}}),v=>v.nombre,"herramientas_ia"),Y=Ce(be(e.ajustes,"ajustes",40).map((v,A)=>{let x=`ajustes[${A}]`;if(!fe(v))throw i(`\xAB${x}\xBB: un objeto.`);xe(v,["clave","etiqueta","tipo","opciones","requerido"],x);let M=V(v.tipo,`${x}.tipo`,10);if(!Jr.includes(M))throw i(`\xAB${x}.tipo\xBB: ${Jr.join(", ")}.`);let B=be(v.opciones,`${x}.opciones`,50).map((I,ae)=>{if(!fe(I))throw i(`\xAB${x}.opciones[${ae}]\xBB: { valor, etiqueta }.`);return xe(I,["valor","etiqueta"],`${x}.opciones[${ae}]`),{valor:V(I.valor,`${x}.opciones[${ae}].valor`,60),etiqueta:V(I.etiqueta,`${x}.opciones[${ae}].etiqueta`,80)}});if(M==="opcion"&&!B.length)throw i(`\xAB${x}.opciones\xBB: un ajuste de tipo opci\xF3n necesita sus opciones.`);if(M!=="opcion"&&B.length)throw i(`\xAB${x}.opciones\xBB: solo en los de tipo opci\xF3n.`);return{clave:oe(v.clave,`${x}.clave`,qo,"min\xFAsculas, n\xFAmeros y _"),etiqueta:V(v.etiqueta,`${x}.etiqueta`,80),tipo:M,opciones:Ce(B,I=>I.valor,`${x}.opciones`),requerido:v.requerido===!0}}),v=>v.clave,"ajustes"),$=Ce(be(e.secretos,"secretos",10).map((v,A)=>{let x=`secretos[${A}]`;if(!fe(v))throw i(`\xAB${x}\xBB: un objeto.`);return xe(v,["clave","etiqueta","descripcion"],x),{clave:oe(v.clave,`${x}.clave`,qo,"min\xFAsculas, n\xFAmeros y _"),etiqueta:V(v.etiqueta,`${x}.etiqueta`,80),descripcion:V(v.descripcion,`${x}.descripcion`,300,!1)}}),v=>v.clave,"secretos");return{formato:Xo,formato_version:e.formato_version,id:t,nombre:n,descripcion:V(e.descripcion,"descripcion",500,!1),version:r,autor:a,icono:s,idiomas:l,compatible_crm:d,licencia:u,depende_de:p,ofrece:h,usa:b,solucion:y,montajes:g,funciones:N,servidor:C,herramientas_ia:T,ajustes:Y,secretos:$,permisos:w}}var Xo,Qr,Ur,Gr,sr,Ot,Hr,cr,Vr,Jr,hg,ji,gg,qc,kc,bg,wg,qo,vg,Ai,Mc,yg,fe,Ic,_g,gy,Ng,Dc,Lc,xg,Cg,qi,ki,Ag,Yr=m(()=>{q();xc();Sc();ar();Ec();Xo="forgenex.extension",Qr=1,Ur=256e3,Gr={contactos:{nombre:"Personas",ops:["ver","crear","editar","borrar"]},empresas:{nombre:"Empresas",ops:["ver","crear","editar","borrar"]},oportunidades:{nombre:"Oportunidades",ops:["ver","crear","editar","borrar"]},tareas:{nombre:"Tareas",ops:["ver","crear","editar","borrar"]},notas:{nombre:"Notas",ops:["ver","editar"]}},sr=["ver","crear","editar","borrar"],Ot=["pagina","ficha_pestana","ficha_bloque","inicio_bloque","accion_ficha","accion_tabla","vista","ajustes","publica"],Hr=new Set(["pagina","ficha_pestana","ficha_bloque","inicio_bloque","accion_ficha","accion_tabla","vista","ajustes","publica"]),cr=new Set(["ficha_pestana","ficha_bloque","accion_ficha","accion_tabla","vista"]),Vr=["evento","programada","webhook","automatizacion","calculo","herramienta","publica"],Jr=["texto","numero","si_no","opcion","modulo","campo"],hg=new Set(["__proto__","constructor","prototype"]),ji=/^[a-z][a-z0-9-]{0,62}(\.[a-z0-9][a-z0-9-]{0,62}){1,6}$/,gg=/^(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})(-[0-9a-z.-]{1,30})?$/,qc=/^(>=|<=|>|<|=|\^|~)?(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})(-[0-9a-z.-]{1,30})?$/,kc=/^[a-z0-9-]{1,40}$/,bg=/^[a-z]{2,3}(-[A-Z]{2})?$/,wg=/^[a-z][a-z0-9_.-]{0,79}$/,qo=/^[a-z][a-z0-9_]{0,40}$/,vg=/^[a-z][a-z0-9_]{0,59}$/,Ai=/^(?!\/)(?!.*\/\/)(?!.*(^|\/)\.\.?(\/|$))[A-Za-z0-9_.\/-]{1,200}$/,Mc=/^(\*\.)?([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/,yg=/^[0-9*,\/-]+( [0-9*,\/-]+){4}$/,fe=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);Ic=String.raw`[\p{Cc}\p{Cf}\u2028\u2029\u034F\u115F\u1160\u2800\u3164\uFFA0]|(?<!\p{Emoji})[\uFE00-\uFE0F]|(?<=[0-9#*])[\uFE00-\uFE0F](?!\u20E3)`,_g=new RegExp(Ic,"u"),gy=new RegExp(Ic,"gu"),Ng=new RegExp("(?<=\\p{Extended_Pictographic}[\\uFE0F\\p{Emoji_Modifier}]?)\\u200D(?=\\p{Extended_Pictographic})","gu");Dc={\u0391:"a",\u0392:"b",\u0395:"e",\u0396:"z",\u0397:"h",\u0399:"i",\u039A:"k",\u039C:"m",\u039D:"n",\u039F:"o",\u03A1:"p",\u03A4:"t",\u03A5:"y",\u03A7:"x",\u0410:"a",\u0412:"b",\u0415:"e",\u0405:"s",\u0406:"i",\u0408:"j",\u041A:"k",\u041C:"m",\u041D:"h",\u041E:"o",\u0420:"p",\u0421:"c",\u0422:"t",\u0425:"x",\u04AE:"y","\u050C":"g","\u051A":"q","\u051C":"w"},Lc={\u03B1:"a",\u03B2:"b",\u03B3:"y",\u03B5:"e",\u03B7:"n",\u03B9:"i",\u03BA:"k",\u03BD:"v",\u03BF:"o",\u03C1:"p",\u03C4:"t",\u03C5:"u",\u03C7:"x",\u03C9:"w",\u0430:"a",\u0435:"e",\u0451:"e",\u043E:"o",\u0440:"p",\u0441:"c",\u0443:"y",\u0445:"x",\u0455:"s",\u0456:"i",\u0457:"i",\u0458:"j","\u0501":"d",\u04BB:"h","\u04CF":"l","\u051B":"q","\u051D":"w",\u0261:"g",\u0433:"r",\u043F:"n",\u049D:"k",\u043A:"k",\u0131:"i","\u0237":"j",0:"o","\u1D00":"a",\u0299:"b","\u1D04":"c","\u1D05":"d","\u1D07":"e","\uA730":"f",\u0262:"g",\u029C:"h",\u026A:"i","\u1D0A":"j","\u1D0B":"k",\u029F:"l","\u1D0D":"m",\u0274:"n","\u1D0F":"o","\u1D18":"p",\u0280:"r","\uA731":"s","\u1D1B":"t","\u1D1C":"u","\u1D20":"v","\u1D21":"w",\u028F:"y","\u1D22":"z",\u0585:"o","\uA4EE":"a","\uA4D0":"b","\uA4DA":"c","\uA4D3":"d","\uA4F0":"e","\uA4DD":"f","\uA4D6":"g","\uA4E7":"h","\uA4F2":"i","\uA4D9":"j","\uA4D7":"k","\uA4E1":"l","\uA4DF":"m","\uA4E0":"n","\uA4F3":"o","\uA4D1":"p","\uA4E3":"r","\uA4E2":"s","\uA4D4":"t","\uA4F4":"u","\uA4E6":"v","\uA4EA":"w","\uA4EB":"x","\uA4EC":"y","\uA4DC":"z"},xg=new RegExp(`[${Object.keys(Dc).join("")}]`,"gu"),Cg=new RegExp(`[${Object.keys(Lc).join("")}]`,"gu"),qi=e=>e.normalize("NFKC").replace(xg,o=>Dc[o]).toLowerCase().normalize("NFD").replace(new RegExp("\\p{M}","gu"),"").replace(Cg,o=>Lc[o]).replace(/[^\p{L}\p{N}]/gu,"");ki=e=>{let o=Og(e);for(let t=0;t<o.length;t++){let n="";for(let r=t;r<o.length&&n.length<8;r++)if(n+=o[r],n==="forgenex")return!0}return!1};Ag=(e,o)=>e.some(t=>t===o||t.startsWith("*.")&&o.endsWith(t.slice(1)))});function ho(e){return typeof e>"u"||e===void 0}function W(e){return typeof e=="string"}function oo(e){return typeof e=="number"}function Yo(e){return typeof e=="boolean"}function Ko(e){return e===null}function Ri(e){return e instanceof Date}function Zo(e){return typeof e=="bigint"}function Fc(e){return typeof Buffer<"u"&&Buffer.isBuffer(e)}function ve(e){return typeof e=="function"}function Oe(e){return typeof e=="object"&&e!==null}function c(e){return Object.freeze(e)}function lr(e){return qe(e)?e:[e]}function qe(e){return Array.isArray(e)}function Wc(e){return e instanceof Error?e.message:String(e)}var _=m(()=>{});var yy,Bc=m(()=>{_();yy=c({is(e){return e.kind==="AlterTableNode"},create(e){return c({kind:"AlterTableNode",table:e})},cloneWithTableProps(e,o){return c({...e,...o})},cloneWithColumnAlteration(e,o){return c({...e,columnAlterations:e.columnAlterations?[...e.columnAlterations,o]:[o]})}})});var R,te=m(()=>{_();R=c({is(e){return e.kind==="IdentifierNode"},create(e){return c({kind:"IdentifierNode",name:e})}})});var Oy,Uc=m(()=>{_();te();Oy=c({is(e){return e.kind==="CreateIndexNode"},create(e){return c({kind:"CreateIndexNode",name:R.create(e)})},cloneWith(e,o){return c({...e,...o})},cloneWithColumns(e,o){return c({...e,columns:[...e.columns||[],...o]})}})});var Ey,Vc=m(()=>{_();te();Ey=c({is(e){return e.kind==="CreateSchemaNode"},create(e,o){return c({kind:"CreateSchemaNode",schema:R.create(e),...o})},cloneWith(e,o){return c({...e,...o})}})});var Ry,Jc=m(()=>{_();Ry=c({is(e){return e.kind==="CreateTableNode"},create(e){return c({kind:"CreateTableNode",table:e,columns:c([])})},cloneWithColumn(e,o){return c({...e,columns:c([...e.columns,o])})},cloneWithConstraint(e,o){return c({...e,constraints:e.constraints?c([...e.constraints,o]):c([o])})},cloneWithIndex(e,o){return c({...e,indexes:e.indexes?c([...e.indexes,o]):c([o])})},cloneWithFrontModifier(e,o){return c({...e,frontModifiers:e.frontModifiers?c([...e.frontModifiers,o]):c([o])})},cloneWithEndModifier(e,o){return c({...e,endModifiers:e.endModifiers?c([...e.endModifiers,o]):c([o])})},cloneWith(e,o){return c({...e,...o})}})});var Ue,et=m(()=>{_();te();Ue=c({is(e){return e.kind==="SchemableIdentifierNode"},create(e){return c({kind:"SchemableIdentifierNode",identifier:R.create(e)})},createWithSchema(e,o){return c({kind:"SchemableIdentifierNode",schema:R.create(e),identifier:R.create(o)})}})});var zy,Qc=m(()=>{_();et();zy=c({is(e){return e.kind==="DropIndexNode"},create(e,o){return c({kind:"DropIndexNode",name:Ue.create(e),...o})},cloneWith(e,o){return c({...e,...o})}})});var Uy,Gc=m(()=>{_();te();Uy=c({is(e){return e.kind==="DropSchemaNode"},create(e,o){return c({kind:"DropSchemaNode",schema:R.create(e),...o})},cloneWith(e,o){return c({...e,...o})}})});var Qy,Hc=m(()=>{_();Qy=c({is(e){return e.kind==="DropTableNode"},create(e,o){return c({kind:"DropTableNode",table:e,...o})},cloneWith(e,o){return c({...e,...o})}})});var ke,go=m(()=>{_();ke=c({is(e){return e.kind==="AliasNode"},create(e,o){return c({kind:"AliasNode",node:e,alias:o})}})});var ko,ur=m(()=>{_();et();ko=c({is(e){return e.kind==="TableNode"},create(e){return c({kind:"TableNode",table:Ue.create(e)})},createWithSchema(e,o){return c({kind:"TableNode",table:Ue.createWithSchema(e,o)})}})});function re(e){return Oe(e)&&ve(e.toOperationNode)}var Le=m(()=>{_()});function Kr(e){return Oe(e)&&"expressionType"in e&&re(e)}function Xc(e){return Oe(e)&&"expression"in e&&W(e.alias)&&re(e)}var Zr=m(()=>{Le();_()});var to,Pi=m(()=>{_();to=c({is(e){return e.kind==="SelectModifierNode"},create(e,o){return c({kind:"SelectModifierNode",modifier:e,of:o})},createWithExpression(e){return c({kind:"SelectModifierNode",rawModifier:e})}})});var Re,Ro=m(()=>{_();Re=c({is(e){return e.kind==="AndNode"},create(e,o){return c({kind:"AndNode",left:e,right:o})}})});var Ve,ot=m(()=>{_();Ve=c({is(e){return e.kind==="OrNode"},create(e,o){return c({kind:"OrNode",left:e,right:o})}})});var en,Ti=m(()=>{_();Ro();ot();en=c({is(e){return e.kind==="OnNode"},create(e){return c({kind:"OnNode",on:e})},cloneWithOperation(e,o,t){return c({...e,on:o==="And"?Re.create(e.on,t):Ve.create(e.on,t)})}})});var bo,dr=m(()=>{_();Ti();bo=c({is(e){return e.kind==="JoinNode"},create(e,o){return c({kind:"JoinNode",joinType:e,table:o,on:void 0})},createWithOn(e,o,t){return c({kind:"JoinNode",joinType:e,table:o,on:en.create(t)})},cloneWithOn(e,o){return c({...e,on:e.on?en.cloneWithOperation(e.on,"And",o):en.create(o)})}})});var Po,on=m(()=>{_();Po=c({is(e){return e.kind==="BinaryOperationNode"},create(e,o,t){return c({kind:"BinaryOperationNode",leftOperand:e,operator:o,rightOperand:t})}})});function rl(e){return W(e)&&el[e]}function nl(e){return W(e)&&Zc[e]}function il(e){return W(e)&&tl[e]}var Yc,__,Kc,N_,Zc,Eg,el,qg,ol,$_,tl,kg,x_,Je,jt=m(()=>{_();Yc=c({"=":!0,"==":!0,"!=":!0,"<>":!0,">":!0,">=":!0,"<":!0,"<=":!0,in:!0,"not in":!0,is:!0,"is not":!0,like:!0,"not like":!0,match:!0,ilike:!0,"not ilike":!0,"@>":!0,"<@":!0,"^@":!0,"&&":!0,"?":!0,"?&":!0,"?|":!0,"!<":!0,"!>":!0,"<=>":!0,"!~":!0,"~":!0,"~*":!0,"!~*":!0,"@@":!0,"@@@":!0,"!!":!0,"<->":!0,regexp:!0,"is distinct from":!0,"is not distinct from":!0}),__=Object.keys(Yc),Kc=c({"+":!0,"-":!0,"*":!0,"/":!0,"%":!0,"^":!0,"&":!0,"|":!0,"#":!0,"<<":!0,">>":!0}),N_=Object.keys(Kc),Zc=c({"->":!0,"->>":!0}),Eg=Object.keys(Zc),el=c({...Yc,...Kc,"||":!0}),qg=Object.keys(el),ol=c({exists:!0,"not exists":!0}),$_=Object.keys(ol),tl=c({...ol,"-":!0,not:!0}),kg=Object.keys(tl),x_=[...qg,...Eg,...kg,"between","between symmetric"],Je=c({is(e){return e.kind==="OperatorNode"},create(e){return c({kind:"OperatorNode",operator:e})}})});var se,Qe=m(()=>{_();te();se=c({is(e){return e.kind==="ColumnNode"},create(e){return c({kind:"ColumnNode",column:R.create(e)})}})});var tn,rn=m(()=>{_();tn=c({is(e){return e.kind==="SelectAllNode"},create(){return c({kind:"SelectAllNode"})}})});var At,nn=m(()=>{rn();_();At=c({is(e){return e.kind==="ReferenceNode"},create(e,o){return c({kind:"ReferenceNode",table:o,column:e})},createSelectAll(e){return c({kind:"ReferenceNode",table:e,column:tn.create()})}})});function an(e){return Oe(e)&&re(e)&&W(e.dynamicReference)}var sn=m(()=>{Le();_()});var Ge,cn=m(()=>{_();Ge=c({is(e){return e.kind==="OrderByItemNode"},create(e,o){return c({kind:"OrderByItemNode",orderBy:e,direction:o})},cloneWith(e,o){return c({...e,...o})}})});var ce,tt=m(()=>{_();ce=c({is(e){return e.kind==="RawNode"},create(e,o){return c({kind:"RawNode",sqlFragments:c(e),parameters:c(o)})},createWithSql(e){return ce.create([e],[])},createWithChild(e){return ce.create(["",""],[e])},createWithChildren(e){return ce.create(new Array(e.length+1).fill(""),e)}})});var al,Mi=m(()=>{_();te();al=c({is(e){return e.kind==="CollateNode"},create(e){return c({kind:"CollateNode",collation:R.create(e)})}})});var ln,Ii=m(()=>{Mi();cn();tt();_();ln=class e{#e;constructor(o){this.#e=c(o)}desc(){return new e({node:Ge.cloneWith(this.#e.node,{direction:ce.createWithSql("desc")})})}asc(){return new e({node:Ge.cloneWith(this.#e.node,{direction:ce.createWithSql("asc")})})}nullsLast(){return new e({node:Ge.cloneWith(this.#e.node,{nulls:"last"})})}nullsFirst(){return new e({node:Ge.cloneWith(this.#e.node,{nulls:"first"})})}collate(o){return new e({node:Ge.cloneWith(this.#e.node,{collation:al.create(o)})})}toOperationNode(){return this.#e.node}}});function Et(e){sl.has(e)||(sl.add(e),console.log(e))}var sl,Di=m(()=>{sl=new Set});function Rg(e){return e==="asc"||e==="desc"}function He(e){if(e.length===2)return[Li(e[0],e[1])];if(e.length===1){let[o]=e;return Array.isArray(o)?(Et("orderBy(array) is deprecated, use multiple orderBy calls instead."),o.map(t=>Li(t))):[Li(o)]}throw new Error(`Invalid number of arguments at order by! expected 1-2, received ${e.length}`)}function Li(e,o){let t=Pg(e);if(Ge.is(t)){if(o)throw new Error("Cannot specify direction twice!");return t}return cl(t,o)}function Pg(e){if(rt(e))return To(e);if(an(e))return e.toOperationNode();let[o,t]=e.split(" ");return t?(Et("`orderBy('column asc')` is deprecated. Use `orderBy('column', 'asc')` instead."),cl(ze(o),t)):ze(e)}function cl(e,o){if(typeof o=="string"){if(!Rg(o))throw new Error(`Invalid order by direction: ${o}`);return Ge.create(e,ce.createWithSql(o))}if(Kr(o))return Et("`orderBy(..., expr)` is deprecated. Use `orderBy(..., 'asc')` or `orderBy(..., (ob) => ...)` instead."),Ge.create(e,o.toOperationNode());let t=Ge.create(e);return o?o(new ln({node:t})).toOperationNode():t}var qt=m(()=>{sn();Zr();cn();tt();Ii();Di();nt();Pe()});var kt,un=m(()=>{_();kt=c({is(e){return e.kind==="JSONReferenceNode"},create(e,o){return c({kind:"JSONReferenceNode",reference:e,traversal:o})},cloneWithTraversal(e,o){return c({...e,traversal:o})}})});var dn,pn=m(()=>{_();dn=c({is(e){return e.kind==="JSONOperatorChainNode"},create(e){return c({kind:"JSONOperatorChainNode",operator:e,values:c([])})},cloneWithValue(e,o){return c({...e,values:c([...e.values,o])})}})});var Mo,pr=m(()=>{_();Mo=c({is(e){return e.kind==="JSONPathNode"},create(e){return c({kind:"JSONPathNode",inOperator:e,pathLegs:c([])})},cloneWithLeg(e,o){return c({...e,pathLegs:c([...e.pathLegs,o])})}})});function Tg(e){return W(e)?ze(e):e.toOperationNode()}function wo(e){return qe(e)?e.map(o=>ue(o)):[ue(e)]}function ue(e){return rt(e)?To(e):Tg(e)}function ll(e,o){if(nl(o))return kt.create(ze(e),dn.create(Je.create(o)));if(o==="->$"||o==="->>$")return kt.create(ze(e),Mo.create(Je.create(o.slice(0,-1))));throw new Error(`Invalid JSON operator: ${o}`)}function ze(e){if(!e.includes("."))return At.create(se.create(e));let t=e.split(".").map(dl);if(t.length===3)return Mg(t);if(t.length===2)return Ig(t);throw new Error(`invalid column reference ${e}`)}function ul(e){let o=" as ";if(e.includes(o)){let[t,n]=e.split(o).map(dl);return ke.create(ze(t),R.create(n))}else return ze(e)}function Mg(e){let[o,t,n]=e;return At.create(se.create(n),ko.createWithSchema(o,t))}function Ig(e){let[o,t]=e;return At.create(se.create(t),ko.create(o))}function dl(e){return e.trim()}var Pe=m(()=>{go();Qe();nn();ur();_();nt();te();jt();un();pn();pr()});var pl,zi=m(()=>{_();pl=c({is(e){return e.kind==="PrimitiveValueListNode"},create(e){return c({kind:"PrimitiveValueListNode",values:c([...e])})}})});var mn,fn=m(()=>{_();mn=c({is(e){return e.kind==="ValueListNode"},create(e){return c({kind:"ValueListNode",values:c(e)})}})});var Se,Io=m(()=>{_();Se=c({is(e){return e.kind==="ValueNode"},create(e){return c({kind:"ValueNode",value:e})},createImmediate(e){return c({kind:"ValueNode",value:e,immediate:!0})}})});function ml(e){return qe(e)?Dg(e):Q(e)}function Q(e){return rt(e)?To(e):Se.create(e)}function hn(e){return oo(e)||Yo(e)||Ko(e)}function mr(e){if(!hn(e))throw new Error(`unsafe immediate value ${JSON.stringify(e)}`);return Se.createImmediate(e)}function Dg(e){return e.some(rt)?mn.create(e.map(o=>Q(o))):pl.create(e)}var vo=m(()=>{zi();fn();Io();_();nt()});var Do,fr=m(()=>{_();Do=c({is(e){return e.kind==="ParensNode"},create(e){return c({kind:"ParensNode",node:e})}})});function le(e){if(e.length===3)return gn(e[0],e[1],e[2]);if(e.length===1)return Q(e[0]);throw new Error(`invalid arguments: ${JSON.stringify(e)}`)}function gn(e,o,t){return Lg(o)&&hl(t)?Po.create(ue(e),Fi(o),Se.createImmediate(t)):Po.create(ue(e),Fi(o),ml(t))}function ye(e,o,t){return Po.create(ue(e),Fi(o),ue(t))}function Wi(e,o){return bn(Object.entries(e).filter(([,t])=>!ho(t)).map(([t,n])=>gn(t,hl(n)?"is":"=",n)),o)}function bn(e,o,t=!0){let n=o==="and"?Re.create:Ve.create;if(e.length===0)return Po.create(Se.createImmediate(1),Je.create("="),Se.createImmediate(o==="and"?1:0));let r=fl(e[0]);for(let a=1;a<e.length;++a)r=n(r,fl(e[a]));return e.length>1&&t?Do.create(r):r}function Lg(e){return e==="is"||e==="is not"}function hl(e){return Ko(e)||Yo(e)}function Fi(e){if(rl(e))return Je.create(e);if(re(e))return e.toOperationNode();throw new Error(`invalid operator ${JSON.stringify(e)}`)}function fl(e){return re(e)?e.toOperationNode():e}var ro=m(()=>{on();_();Le();jt();Pe();vo();Io();Ro();fr();ot()});var yo,hr=m(()=>{_();yo=c({is(e){return e.kind==="OrderByNode"},create(e){return c({kind:"OrderByNode",items:c([...e])})},cloneWithItems(e,o){return c({...e,items:c([...e.items,...o])})}})});var Bi,Ui=m(()=>{_();Bi=c({is(e){return e.kind==="PartitionByNode"},create(e){return c({kind:"PartitionByNode",items:c(e)})},cloneWithItems(e,o){return c({...e,items:c([...e.items,...o])})}})});var gr,wn=m(()=>{_();hr();Ui();gr=c({is(e){return e.kind==="OverNode"},create(){return c({kind:"OverNode"})},cloneWithOrderByItems(e,o){return c({...e,orderBy:e.orderBy?yo.cloneWithItems(e.orderBy,o):yo.create(o)})},cloneWithPartitionByItems(e,o){return c({...e,partitionBy:e.partitionBy?Bi.cloneWithItems(e.partitionBy,o):Bi.create(o)})}})});var it,br=m(()=>{_();it=c({is(e){return e.kind==="FromNode"},create(e){return c({kind:"FromNode",froms:c(e)})},cloneWithFroms(e,o){return c({...e,froms:c([...e.froms,...o])})}})});var Vi,Ji=m(()=>{_();Vi=c({is(e){return e.kind==="GroupByNode"},create(e){return c({kind:"GroupByNode",items:c(e)})},cloneWithItems(e,o){return c({...e,items:c([...e.items,...o])})}})});var Qi,Gi=m(()=>{_();Ro();ot();Qi=c({is(e){return e.kind==="HavingNode"},create(e){return c({kind:"HavingNode",having:e})},cloneWithOperation(e,o,t){return c({...e,having:o==="And"?Re.create(e.having,t):Ve.create(e.having,t)})}})});var gl,Hi=m(()=>{_();gl=c({is(e){return e.kind==="InsertQueryNode"},create(e,o,t){return c({kind:"InsertQueryNode",into:e,...o&&{with:o},replace:t})},createWithoutInto(){return c({kind:"InsertQueryNode"})},cloneWith(e,o){return c({...e,...o})}})});var bl,Xi=m(()=>{_();bl=c({is(e){return e.kind==="ListNode"},create(e){return c({kind:"ListNode",items:c(e)})}})});var Rt,vn=m(()=>{_();br();Xi();Rt=c({is(e){return e.kind==="UpdateQueryNode"},create(e,o){return c({kind:"UpdateQueryNode",table:e.length===1?e[0]:bl.create(e),...o&&{with:o}})},createWithoutTable(){return c({kind:"UpdateQueryNode"})},cloneWithFromItems(e,o){return c({...e,from:e.from?it.cloneWithFroms(e.from,o):it.create(o)})},cloneWithUpdates(e,o){return c({...e,updates:e.updates?c([...e.updates,...o]):o})},cloneWithLimit(e,o){return c({...e,limit:o})}})});var Yi,Ki=m(()=>{_();Yi=c({is(e){return e.kind==="UsingNode"},create(e){return c({kind:"UsingNode",tables:c(e)})},cloneWithTables(e,o){return c({...e,tables:c([...e.tables,...o])})}})});var Pt,yn=m(()=>{_();br();Ki();_o();Pt=c({is(e){return e.kind==="DeleteQueryNode"},create(e,o){return c({kind:"DeleteQueryNode",from:it.create(e),...o&&{with:o}})},cloneWithOrderByItems:(e,o)=>E.cloneWithOrderByItems(e,o),cloneWithoutOrderBy:e=>E.cloneWithoutOrderBy(e),cloneWithLimit(e,o){return c({...e,limit:o})},cloneWithoutLimit(e){return c({...e,limit:void 0})},cloneWithUsing(e,o){return c({...e,using:e.using!==void 0?Yi.cloneWithTables(e.using,o):Yi.create(o)})}})});var we,wr=m(()=>{_();Ro();ot();we=c({is(e){return e.kind==="WhereNode"},create(e){return c({kind:"WhereNode",where:e})},cloneWithOperation(e,o,t){return c({...e,where:o==="And"?Re.create(e.where,t):Ve.create(e.where,t)})}})});var Zi,ea=m(()=>{_();Zi=c({is(e){return e.kind==="ReturningNode"},create(e){return c({kind:"ReturningNode",selections:c(e)})},cloneWithSelections(e,o){return c({...e,selections:e.selections?c([...e.selections,...o]):c(o)})}})});var wl,oa=m(()=>{_();wl=c({is(e){return e.kind==="ExplainNode"},create(e,o){return c({kind:"ExplainNode",format:e,options:o})}})});var No,vr=m(()=>{_();No=c({is(e){return e.kind==="WhenNode"},create(e){return c({kind:"WhenNode",condition:e})},cloneWithResult(e,o){return c({...e,result:o})}})});var vl,ta=m(()=>{_();vr();vl=c({is(e){return e.kind==="MergeQueryNode"},create(e,o){return c({kind:"MergeQueryNode",into:e,...o&&{with:o}})},cloneWithUsing(e,o){return c({...e,using:o})},cloneWithWhen(e,o){return c({...e,whens:e.whens?c([...e.whens,o]):c([o])})},cloneWithThen(e,o){return c({...e,whens:e.whens?c([...e.whens.slice(0,-1),No.cloneWithResult(e.whens[e.whens.length-1],o)]):void 0})}})});var ra,na=m(()=>{_();ra=c({is(e){return e.kind==="OutputNode"},create(e){return c({kind:"OutputNode",selections:c(e)})},cloneWithSelections(e,o){return c({...e,selections:e.selections?c([...e.selections,...o]):c(o)})}})});var E,_o=m(()=>{Hi();yr();vn();yn();wr();_();ea();oa();ta();na();hr();E=c({is(e){return H.is(e)||gl.is(e)||Rt.is(e)||Pt.is(e)||vl.is(e)},cloneWithEndModifier(e,o){return c({...e,endModifiers:e.endModifiers?c([...e.endModifiers,o]):c([o])})},cloneWithWhere(e,o){return c({...e,where:e.where?we.cloneWithOperation(e.where,"And",o):we.create(o)})},cloneWithJoin(e,o){return c({...e,joins:e.joins?c([...e.joins,o]):c([o])})},cloneWithReturning(e,o){return c({...e,returning:e.returning?Zi.cloneWithSelections(e.returning,o):Zi.create(o)})},cloneWithoutReturning(e){return c({...e,returning:void 0})},cloneWithoutWhere(e){return c({...e,where:void 0})},cloneWithExplain(e,o,t){return c({...e,explain:wl.create(o,t?.toOperationNode())})},cloneWithTop(e,o){return c({...e,top:o})},cloneWithOutput(e,o){return c({...e,output:e.output?ra.cloneWithSelections(e.output,o):ra.create(o)})},cloneWithOrderByItems(e,o){return c({...e,orderBy:e.orderBy?yo.cloneWithItems(e.orderBy,o):yo.create(o)})},cloneWithoutOrderBy(e){return c({...e,orderBy:void 0})}})});var H,yr=m(()=>{_();br();Ji();Gi();_o();H=c({is(e){return e.kind==="SelectQueryNode"},create(e){return c({kind:"SelectQueryNode",...e&&{with:e}})},createFrom(e,o){return c({kind:"SelectQueryNode",from:it.create(e),...o&&{with:o}})},cloneWithSelections(e,o){return c({...e,selections:e.selections?c([...e.selections,...o]):c(o)})},cloneWithDistinctOn(e,o){return c({...e,distinctOn:e.distinctOn?c([...e.distinctOn,...o]):c(o)})},cloneWithFrontModifier(e,o){return c({...e,frontModifiers:e.frontModifiers?c([...e.frontModifiers,o]):c([o])})},cloneWithOrderByItems:(e,o)=>E.cloneWithOrderByItems(e,o),cloneWithGroupByItems(e,o){return c({...e,groupBy:e.groupBy?Vi.cloneWithItems(e.groupBy,o):Vi.create(o)})},cloneWithLimit(e,o){return c({...e,limit:o})},cloneWithOffset(e,o){return c({...e,offset:o})},cloneWithFetch(e,o){return c({...e,fetch:o})},cloneWithHaving(e,o){return c({...e,having:e.having?Qi.cloneWithOperation(e.having,"And",o):Qi.create(o)})},cloneWithSetOperations(e,o){return c({...e,setOperations:e.setOperations?c([...e.setOperations,...o]):c([...o])})},cloneWithoutSelections(e){return c({...e,selections:[]})},cloneWithoutLimit(e){return c({...e,limit:void 0})},cloneWithoutOffset(e){return c({...e,offset:void 0})},cloneWithoutOrderBy:e=>E.cloneWithoutOrderBy(e),cloneWithoutGroupBy(e){return c({...e,groupBy:void 0})}})});var _n,ia=m(()=>{dr();tt();ro();_();_n=class e{#e;constructor(o){this.#e=c(o)}on(...o){return new e({...this.#e,joinNode:bo.cloneWithOn(this.#e.joinNode,le(o))})}onRef(o,t,n){return new e({...this.#e,joinNode:bo.cloneWithOn(this.#e.joinNode,ye(o,t,n))})}onTrue(){return new e({...this.#e,joinNode:bo.cloneWithOn(this.#e.joinNode,ce.createWithSql("true"))})}$call(o){return o(this)}toOperationNode(){return this.#e.joinNode}}});var yl,aa=m(()=>{_();yl=c({is(e){return e.kind==="PartitionByItemNode"},create(e){return c({kind:"PartitionByItemNode",partitionBy:e})}})});function _l(e){return wo(e).map(yl.create)}var Nl=m(()=>{aa();Pe()});var Nn,$l=m(()=>{wn();_o();qt();Nl();_();Nn=class e{#e;constructor(o){this.#e=c(o)}orderBy(...o){return new e({overNode:gr.cloneWithOrderByItems(this.#e.overNode,He(o))})}clearOrderBy(){return new e({overNode:E.cloneWithoutOrderBy(this.#e.overNode)})}partitionBy(o){return new e({overNode:gr.cloneWithPartitionByItems(this.#e.overNode,_l(o))})}$call(o){return o(this)}toOperationNode(){return this.#e.overNode}}});var Tt,sa=m(()=>{_();nn();rn();Tt=c({is(e){return e.kind==="SelectionNode"},create(e){return c({kind:"SelectionNode",selection:e})},createSelectAll(){return c({kind:"SelectionNode",selection:tn.create()})},createSelectAllFromTable(e){return c({kind:"SelectionNode",selection:At.createSelectAll(e)})}})});function $o(e){return ve(e)?$o(e(xo())):qe(e)?e.map(o=>xl(o)):[xl(e)]}function xl(e){return W(e)?Tt.create(ul(e)):an(e)?Tt.create(e.toOperationNode()):Tt.create($n(e))}function no(e){return e?Array.isArray(e)?e.map(Cl):[Cl(e)]:[Tt.createSelectAll()]}function Cl(e){if(W(e))return Tt.createSelectAllFromTable(_e(e));throw new Error(`invalid value selectAll expression: ${JSON.stringify(e)}`)}var _r=m(()=>{_();sa();Pe();sn();nt();io();Mt()});var R$,Ol=m(()=>{_();R$=c({is(e){return e.kind==="ValuesNode"},create(e){return c({kind:"ValuesNode",values:c(e)})}})});var M$,Sl=m(()=>{_();M$=c({is(e){return e.kind==="DefaultInsertValueNode"},create(){return c({kind:"DefaultInsertValueNode"})}})});var ca,la=m(()=>{_();ca=c({is(e){return e.kind==="ColumnUpdateNode"},create(e,o){return c({kind:"ColumnUpdateNode",column:e,value:o})}})});function jl(...e){return e.length===2?[ca.create(ue(e[0]),Q(e[1]))]:zg(e[0])}function zg(e){let o=ve(e)?e(xo()):e;return Object.entries(o).filter(([t,n])=>n!==void 0).map(([t,n])=>ca.create(se.create(t),Q(n)))}var Al=m(()=>{Qe();la();Mt();_();vo();Pe()});var G$,El=m(()=>{_();G$=c({is(e){return e.kind==="OnDuplicateKeyNode"},create(e){return c({kind:"OnDuplicateKeyNode",updates:e})}})});var ql=m(()=>{});function It(e){return Object.prototype.hasOwnProperty.call(e,"prototype")}var Lo,Nr=m(()=>{Lo=class extends Error{node;constructor(o){super("no result"),this.node=o}}});var ex,kl=m(()=>{_();wr();ex=c({is(e){return e.kind==="OnConflictNode"},create(){return c({kind:"OnConflictNode"})},cloneWith(e,o){return c({...e,...o})},cloneWithIndexWhere(e,o){return c({...e,indexWhere:e.indexWhere?we.cloneWithOperation(e.indexWhere,"And",o):we.create(o)})},cloneWithIndexOrWhere(e,o){return c({...e,indexWhere:e.indexWhere?we.cloneWithOperation(e.indexWhere,"Or",o):we.create(o)})},cloneWithUpdateWhere(e,o){return c({...e,updateWhere:e.updateWhere?we.cloneWithOperation(e.updateWhere,"And",o):we.create(o)})},cloneWithUpdateOrWhere(e,o){return c({...e,updateWhere:e.updateWhere?we.cloneWithOperation(e.updateWhere,"Or",o):we.create(o)})},cloneWithoutIndexWhere(e){return c({...e,indexWhere:void 0})},cloneWithoutUpdateWhere(e){return c({...e,updateWhere:void 0})}})});var Rl=m(()=>{});var Pl,ua=m(()=>{_();Pl=c({is(e){return e.kind==="TopNode"},create(e,o){return c({kind:"TopNode",expression:e,modifiers:o})}})});function Dt(e,o){if(!oo(e)&&!Zo(e))throw new Error(`Invalid top expression: ${e}`);if(!ho(o)&&!Fg(o))throw new Error(`Invalid top modifiers: ${o}`);return Pl.create(e,o)}function Fg(e){return e==="percent"||e==="with ties"||e==="percent with ties"}var xn=m(()=>{ua();_()});var lx,Tl=m(()=>{_();lx=c({is(e){return e.kind==="OrActionNode"},create(e){return c({kind:"OrActionNode",action:e})}})});var Ml=m(()=>{});var Cn,da=m(()=>{Cn=class{numDeletedRows;constructor(o){this.numDeletedRows=o}}});var Lt,$r=m(()=>{_();Lt=c({is(e){return e.kind==="LimitNode"},create(e){return c({kind:"LimitNode",limit:e})}})});var ne,pa,Il=m(()=>{On();io();_r();_o();_();Nr();da();yn();$r();qt();ro();vo();xn();pa=class{#e;constructor(o){this.#e=c(o)}where(...o){return new ne({...this.#e,queryNode:E.cloneWithWhere(this.#e.queryNode,le(o))})}whereRef(o,t,n){return new ne({...this.#e,queryNode:E.cloneWithWhere(this.#e.queryNode,ye(o,t,n))})}clearWhere(){return new ne({...this.#e,queryNode:E.cloneWithoutWhere(this.#e.queryNode)})}top(o,t){return new ne({...this.#e,queryNode:E.cloneWithTop(this.#e.queryNode,Dt(o,t))})}using(o){return new ne({...this.#e,queryNode:Pt.cloneWithUsing(this.#e.queryNode,at(o))})}innerJoin(...o){return this.#o("InnerJoin",o)}leftJoin(...o){return this.#o("LeftJoin",o)}rightJoin(...o){return this.#o("RightJoin",o)}fullJoin(...o){return this.#o("FullJoin",o)}#o(o,t){return new ne({...this.#e,queryNode:E.cloneWithJoin(this.#e.queryNode,zt(o,t))})}returning(o){return new ne({...this.#e,queryNode:E.cloneWithReturning(this.#e.queryNode,$o(o))})}returningAll(o){return new ne({...this.#e,queryNode:E.cloneWithReturning(this.#e.queryNode,no(o))})}output(o){return new ne({...this.#e,queryNode:E.cloneWithOutput(this.#e.queryNode,$o(o))})}outputAll(o){return new ne({...this.#e,queryNode:E.cloneWithOutput(this.#e.queryNode,no(o))})}clearReturning(){return new ne({...this.#e,queryNode:E.cloneWithoutReturning(this.#e.queryNode)})}clearLimit(){return new ne({...this.#e,queryNode:Pt.cloneWithoutLimit(this.#e.queryNode)})}orderBy(...o){return new ne({...this.#e,queryNode:E.cloneWithOrderByItems(this.#e.queryNode,He(o))})}clearOrderBy(){return new ne({...this.#e,queryNode:E.cloneWithoutOrderBy(this.#e.queryNode)})}limit(o){return new ne({...this.#e,queryNode:Pt.cloneWithLimit(this.#e.queryNode,Lt.create(Q(o)))})}modifyEnd(o){return new ne({...this.#e,queryNode:E.cloneWithEndModifier(this.#e.queryNode,o.toOperationNode())})}$call(o){return o(this)}$if(o,t){return o?t(this):new ne({...this.#e})}$castTo(){return new ne(this.#e)}$narrowType(){return new ne(this.#e)}$assertType(){return new ne(this.#e)}withPlugin(o){return new ne({...this.#e,executor:this.#e.executor.withPlugin(o)})}toOperationNode(){return this.#e.executor.transformQuery(this.#e.queryNode,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(o){let t=this.compile(),n=await this.#e.executor.executeQuery(t,o),{adapter:r}=this.#e.executor,a=t.query;return a.returning&&r.supportsReturning||a.output&&r.supportsOutput?n.rows:[new Cn(n.numAffectedRows??BigInt(0))]}async executeTakeFirst(o){let[t]=await this.execute(o);return t}async executeTakeFirstOrThrow(o){typeof o=="function"&&(o={errorConstructor:o});let t=await this.executeTakeFirst(o);if(t===void 0){let n=o?.errorConstructor??Lo;throw It(n)?new n(this.toOperationNode()):n(this.toOperationNode())}return t}async*stream(o){typeof o!="object"&&(o={chunkSize:o});let t=this.compile(),n=this.#e.executor.stream(t,o.chunkSize??100,o);for await(let r of n)yield*r.rows}async explain(o,t){return await new ne({...this.#e,queryNode:E.cloneWithExplain(this.#e.queryNode,o,t)}).execute()}};ne=pa});var Sn,ma=m(()=>{Sn=class{numUpdatedRows;numChangedRows;constructor(o,t){this.numUpdatedRows=o,this.numChangedRows=t}}});var ie,fa,Dl=m(()=>{On();io();_r();_o();vn();Al();_();ma();Nr();ro();vo();$r();xn();qt();fa=class{#e;constructor(o){this.#e=c(o)}where(...o){return new ie({...this.#e,queryNode:E.cloneWithWhere(this.#e.queryNode,le(o))})}whereRef(o,t,n){return new ie({...this.#e,queryNode:E.cloneWithWhere(this.#e.queryNode,ye(o,t,n))})}clearWhere(){return new ie({...this.#e,queryNode:E.cloneWithoutWhere(this.#e.queryNode)})}top(o,t){return new ie({...this.#e,queryNode:E.cloneWithTop(this.#e.queryNode,Dt(o,t))})}from(o){return new ie({...this.#e,queryNode:Rt.cloneWithFromItems(this.#e.queryNode,at(o))})}innerJoin(...o){return this.#o("InnerJoin",o)}leftJoin(...o){return this.#o("LeftJoin",o)}rightJoin(...o){return this.#o("RightJoin",o)}fullJoin(...o){return this.#o("FullJoin",o)}#o(o,t){return new ie({...this.#e,queryNode:E.cloneWithJoin(this.#e.queryNode,zt(o,t))})}orderBy(...o){return new ie({...this.#e,queryNode:E.cloneWithOrderByItems(this.#e.queryNode,He(o))})}clearOrderBy(){return new ie({...this.#e,queryNode:E.cloneWithoutOrderBy(this.#e.queryNode)})}limit(o){return new ie({...this.#e,queryNode:Rt.cloneWithLimit(this.#e.queryNode,Lt.create(Q(o)))})}set(...o){return new ie({...this.#e,queryNode:Rt.cloneWithUpdates(this.#e.queryNode,jl(...o))})}returning(o){return new ie({...this.#e,queryNode:E.cloneWithReturning(this.#e.queryNode,$o(o))})}returningAll(o){return new ie({...this.#e,queryNode:E.cloneWithReturning(this.#e.queryNode,no(o))})}output(o){return new ie({...this.#e,queryNode:E.cloneWithOutput(this.#e.queryNode,$o(o))})}outputAll(o){return new ie({...this.#e,queryNode:E.cloneWithOutput(this.#e.queryNode,no(o))})}modifyEnd(o){return new ie({...this.#e,queryNode:E.cloneWithEndModifier(this.#e.queryNode,o.toOperationNode())})}clearReturning(){return new ie({...this.#e,queryNode:E.cloneWithoutReturning(this.#e.queryNode)})}$call(o){return o(this)}$if(o,t){return o?t(this):new ie({...this.#e})}$castTo(){return new ie(this.#e)}$narrowType(){return new ie(this.#e)}$assertType(){return new ie(this.#e)}withPlugin(o){return new ie({...this.#e,executor:this.#e.executor.withPlugin(o)})}toOperationNode(){return this.#e.executor.transformQuery(this.#e.queryNode,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(o){let t=this.compile(),n=await this.#e.executor.executeQuery(t,o),{adapter:r}=this.#e.executor,a=t.query;return a.returning&&r.supportsReturning||a.output&&r.supportsOutput?n.rows:[new Sn(n.numAffectedRows??BigInt(0),n.numChangedRows)]}async executeTakeFirst(o){let[t]=await this.execute(o);return t}async executeTakeFirstOrThrow(o){typeof o=="function"&&(o={errorConstructor:o});let t=await this.executeTakeFirst(o);if(t===void 0){let n=o?.errorConstructor??Lo;throw It(n)?new n(this.toOperationNode()):n(this.toOperationNode())}return t}async*stream(o){typeof o!="object"&&(o={chunkSize:o});let t=this.compile(),n=this.#e.executor.stream(t,o.chunkSize??100,o);for await(let r of n)yield*r.rows}async explain(o,t){return await new ie({...this.#e,queryNode:E.cloneWithExplain(this.#e.queryNode,o,t)}).execute()}};ie=fa});var Gx,Ll=m(()=>{_();Qe();ur();Gx=c({is(e){return e.kind==="CommonTableExpressionNameNode"},create(e,o){return c({kind:"CommonTableExpressionNameNode",table:ko.create(e),columns:o?c(o.map(se.create)):void 0})}})});var Yx,zl=m(()=>{_();Yx=c({is(e){return e.kind==="CommonTableExpressionNode"},create(e,o){return c({kind:"CommonTableExpressionNode",name:e,expression:o})},cloneWith(e,o){return c({...e,...o})}})});var eC,Fl=m(()=>{_();eC=c({is(e){return e.kind==="WithNode"},create(e,o){return c({kind:"WithNode",expressions:c([e]),...o})},cloneWithExpression(e,o){return c({...e,expressions:c([...e.expressions,o])})}})});function jn(e){let o="";for(let t=0;t<e;++t)o+=Wg();return o}function Wg(){return Wl[~~(Math.random()*Wl.length)]}var Wl,ha=m(()=>{Wl=["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","0","1","2","3","4","5","6","7","8","9"]});function Te(){return new ga}var ga,An=m(()=>{ha();ga=class{#e;get queryId(){return this.#e===void 0&&(this.#e=jn(8)),this.#e}}});var Bl=m(()=>{});var Ul=m(()=>{});var cC,Vl=m(()=>{_();cC=c({is(e){return e.kind==="MatchedNode"},create(e,o=!1){return c({kind:"MatchedNode",not:e,bySource:o})}})});var je,xr=m(()=>{je=class{#e;#o;#r;constructor(){this.#e=new Promise((o,t)=>{this.#r=t,this.#o=o})}get promise(){return this.#e}resolve=o=>{this.#o?.(o),this.#o=this.#r=void 0};reject=o=>{this.#r?.(o),this.#r=this.#o=void 0}}});async function En(e,o){let t=new je,n=new je;return e.provideConnection(async r=>(t.resolve(r),await n.promise),o).catch(r=>t.reject(r)),c({connection:await t.promise,release:n.resolve})}var Jl=m(()=>{xr();_()});function Gl(e="ignore query",o,t){if(e!=="ignore query"){if(e==="cancel query"){let n=o.cancelQuery;return n||(t(),Ql(e,o.killSession?"kill session":void 0)),n.bind(o)}if(e==="kill session"){let n=o.killSession;return n||(t(),Ql(e,o.cancelQuery?"cancel query":void 0)),n.bind(o)}throw t(),new Error(`Unexpected \`inflightQueryAbortStrategy\`: "${e}"`)}}function Ql(e,o){throw new Error(`This dialect doesn't support \`inflightQueryAbortStrategy\` "${e}". Use "ignore query"${o?` or "${o}"`:""} instead.`)}function st(e,o,t){e?.aborted&&(t?.(),ct(e.reason,o))}function ct(e,o){throw Bg(e,o),e}function lt(e){return o=>console.error(`\`${e}\` failed in the background after abortion: ${Wc(o)}`)}function Bg(e,o){e!==null&&typeof e=="object"&&!Object.isFrozen(e)&&Object.defineProperty(e,"__kysely_timing__",{configurable:!0,enumerable:!1,value:o,writable:!1})}var ao,Hl=m(()=>{_();ao={}});var Ug,qn,Xl=m(()=>{_();Jl();Hl();xr();Ug=c([]),qn=class{#e;constructor(o=Ug){this.#e=o}get plugins(){return this.#e}transformQuery(o,t){for(let n of this.#e){let r=n.transformQuery({node:o,queryId:t});if(r.kind===o.kind)o=r;else throw new Error(["KyselyPlugin.transformQuery must return a node","of the same kind that was given to it.",`The plugin was given a ${o.kind}`,`but it returned a ${r.kind}`].join(" "))}return o}async executeQuery(o,t){let{inflightQueryAbortStrategy:n="ignore query",signal:r}=t||{};if(!r){let f=await this.provideConnection(async h=>await h.executeQuery(o),t);return await this.#o(f,o.queryId)}st(r,"before query execution"),t=c({signal:r});let{connection:a,release:s}=await En(this,t),l=this.provideConnection.bind(this),{promise:d,resolve:u}=new je,p=()=>u(ao);r.addEventListener("abort",p,{once:!0});try{st(r,"before query execution",s);let f=Gl(n,a,s);if(f&&a.collectSessionInfo){st(r,"before query execution",s);let g=a.collectSessionInfo();await Promise.race([d,g]).catch(C=>{throw s(),C})===ao&&(g.catch(lt("collectSessionInfo")).finally(s),ct(r.reason,"before query execution"))}let h=a.executeQuery(o,t),b=await Promise.race([d,h]).catch(g=>{throw s(),g});b===ao?(Promise.allSettled([h.catch(lt("query")),f?.(l).catch(lt("inflightQueryAbortHandler"))]).finally(s),ct(r.reason,"during query execution")):s();let y=this.#o(b,o.queryId,t),w=await Promise.race([d,y]);return w===ao&&(y.catch(lt("plugins.transformResult")),ct(r.reason,"during result transformation")),w}finally{u(ao),r.removeEventListener("abort",p)}}async*stream(o,t,n){let{signal:r}=n||{};if(!r){let{connection:b,release:y}=await En(this);try{for await(let w of b.streamQuery(o,t))yield await this.#o(w,o.queryId,n)}finally{y()}return}n=c({signal:r}),st(r,"before connection acquisition");let{connection:a,release:s}=await En(this,n),{promise:l,resolve:d}=new je,u=()=>d(ao);r.addEventListener("abort",u,{once:!0});let p,f;st(r,"before query streaming",s);let{queryId:h}=o;try{for(p=a.streamQuery(o,t,n);;){st(r,"during query streaming");let b=p.next(),y=await Promise.race([l,b]);if(y===ao&&(f=b.catch(lt("iterator.next")),ct(r.reason,"during query streaming")),y.done)break;let w=this.#o(y.value,h,n),g=await Promise.race([l,w]);g===ao&&(f=w.catch(lt("plugins.transformResult")),ct(r.reason,"during result transformation")),yield g}}finally{d(ao),r.removeEventListener("abort",u);let b=(p?.return?.()||Promise.resolve()).finally(()=>f).finally(s);f||await b}}async#o(o,t,n){let{signal:r}=n||{};for(let a of this.#e)o=await a.transformResult(c({queryId:t,result:o,signal:r}));return o}}});var ba,kn,Rn=m(()=>{Xl();ba=class e extends qn{get adapter(){throw new Error("this query cannot be compiled to SQL")}compileQuery(){throw new Error("this query cannot be compiled to SQL")}provideConnection(){throw new Error("this query cannot be executed")}withConnectionProvider(){throw new Error("this query cannot have a connection provider")}withPlugin(o){return new e([...this.plugins,o])}withPlugins(o){return new e([...this.plugins,...o])}withPluginAtFront(o){return new e([o,...this.plugins])}withoutPlugins(){return new e([])}},kn=new ba});var Yl=m(()=>{});var Kl=m(()=>{});var Zl=m(()=>{});function eu(e,o){return new _n({joinNode:bo.create(e,ut(o))})}function ou(){return new Nn({overNode:gr.create()})}var wa=m(()=>{dr();wn();ia();$l();io()});function zt(e,o){if(o.length===3)return Jg(e,o[0],o[1],o[2]);if(o.length===2)return Vg(e,o[0],o[1]);if(o.length===1)return Qg(e,o[0]);throw new Error("not implemented")}function Vg(e,o,t){return t(eu(e,o)).toOperationNode()}function Jg(e,o,t,n){return bo.createWithOn(e,ut(o),ye(t,"=",n))}function Qg(e,o){return bo.create(e,ut(o))}var On=m(()=>{dr();ro();wa();io()});var tu,va=m(()=>{_();tu=c({is(e){return e.kind==="OffsetNode"},create(e){return c({kind:"OffsetNode",offset:e})}})});var ru,ya=m(()=>{_();ru=c({is(e){return e.kind==="GroupByItemNode"},create(e){return c({kind:"GroupByItemNode",groupBy:e})}})});function nu(e){return e=ve(e)?e(xo()):e,wo(e).map(ru.create)}var iu=m(()=>{ya();Mt();_();Pe()});var au,_a=m(()=>{_();au=c({is(e){return e.kind==="SetOperationNode"},create(e,o,t){return c({kind:"SetOperationNode",operator:e,expression:o,all:t})}})});function dt(e,o,t){return ve(o)&&(o=o(Na())),qe(o)||(o=[o]),o.map(n=>au.create(e,To(n),t))}var su=m(()=>{Mt();_a();_();nt()});var F,Cr,$a,xa,Ft=m(()=>{go();Ro();te();Le();ot();fr();ro();F=class e{#e;constructor(o){this.#e=o}get expressionType(){}as(o){return new Cr(this,o)}or(...o){return new $a(Ve.create(this.#e,le(o)))}and(...o){return new xa(Re.create(this.#e,le(o)))}$castTo(){return new e(this.#e)}$notNull(){return new e(this.#e)}toOperationNode(){return this.#e}},Cr=class{#e;#o;constructor(o,t){this.#e=o,this.#o=t}get expression(){return this.#e}get alias(){return this.#o}toOperationNode(){return ke.create(this.#e.toOperationNode(),re(this.#o)?this.#o.toOperationNode():R.create(this.#o))}},$a=class e{#e;constructor(o){this.#e=o}get expressionType(){}as(o){return new Cr(this,o)}or(...o){return new e(Ve.create(this.#e,le(o)))}$castTo(){return new e(this.#e)}toOperationNode(){return Do.create(this.#e)}},xa=class e{#e;constructor(o){this.#e=o}get expressionType(){}as(o){return new Cr(this,o)}and(...o){return new e(Re.create(this.#e,le(o)))}$castTo(){return new e(this.#e)}toOperationNode(){return Do.create(this.#e)}}});var cu,Ca=m(()=>{_();Io();cu=c({is(e){return e.kind==="FetchNode"},create(e,o){return{kind:"FetchNode",rowCount:Se.create(e),modifier:o}}})});function lu(e,o){if(!oo(e)&&!Zo(e))throw new Error(`Invalid fetch row count: ${e}`);if(!Gg(o))throw new Error(`Invalid fetch modifier: ${o}`);return cu.create(e,o)}function Gg(e){return e==="only"||e==="with ties"}var uu=m(()=>{Ca();_()});function du(e){return new Pn(e)}var P,Pn,Oa,Sa=m(()=>{go();Pi();On();io();_r();Pe();yr();_o();qt();$r();va();_();iu();Nr();te();su();ro();Ft();vo();uu();xn();Pn=class{#e;constructor(o){this.#e=c(o)}get expressionType(){}get isSelectQueryBuilder(){return!0}where(...o){return new P({...this.#e,queryNode:E.cloneWithWhere(this.#e.queryNode,le(o))})}whereRef(o,t,n){return new P({...this.#e,queryNode:E.cloneWithWhere(this.#e.queryNode,ye(o,t,n))})}having(...o){return new P({...this.#e,queryNode:H.cloneWithHaving(this.#e.queryNode,le(o))})}havingRef(o,t,n){return new P({...this.#e,queryNode:H.cloneWithHaving(this.#e.queryNode,ye(o,t,n))})}select(o){return new P({...this.#e,queryNode:H.cloneWithSelections(this.#e.queryNode,$o(o))})}distinctOn(o){return new P({...this.#e,queryNode:H.cloneWithDistinctOn(this.#e.queryNode,wo(o))})}modifyFront(o){return new P({...this.#e,queryNode:H.cloneWithFrontModifier(this.#e.queryNode,to.createWithExpression(o.toOperationNode()))})}modifyEnd(o){return new P({...this.#e,queryNode:E.cloneWithEndModifier(this.#e.queryNode,to.createWithExpression(o.toOperationNode()))})}distinct(){return new P({...this.#e,queryNode:H.cloneWithFrontModifier(this.#e.queryNode,to.create("Distinct"))})}forUpdate(o){return new P({...this.#e,queryNode:E.cloneWithEndModifier(this.#e.queryNode,to.create("ForUpdate",o?lr(o).map(_e):void 0))})}forShare(o){return new P({...this.#e,queryNode:E.cloneWithEndModifier(this.#e.queryNode,to.create("ForShare",o?lr(o).map(_e):void 0))})}forKeyShare(o){return new P({...this.#e,queryNode:E.cloneWithEndModifier(this.#e.queryNode,to.create("ForKeyShare",o?lr(o).map(_e):void 0))})}forNoKeyUpdate(o){return new P({...this.#e,queryNode:E.cloneWithEndModifier(this.#e.queryNode,to.create("ForNoKeyUpdate",o?lr(o).map(_e):void 0))})}skipLocked(){return new P({...this.#e,queryNode:E.cloneWithEndModifier(this.#e.queryNode,to.create("SkipLocked"))})}noWait(){return new P({...this.#e,queryNode:E.cloneWithEndModifier(this.#e.queryNode,to.create("NoWait"))})}selectAll(o){return new P({...this.#e,queryNode:H.cloneWithSelections(this.#e.queryNode,no(o))})}innerJoin(...o){return this.#o("InnerJoin",o)}leftJoin(...o){return this.#o("LeftJoin",o)}rightJoin(...o){return this.#o("RightJoin",o)}fullJoin(...o){return this.#o("FullJoin",o)}crossJoin(...o){return this.#o("CrossJoin",o)}innerJoinLateral(...o){return this.#o("LateralInnerJoin",o)}leftJoinLateral(...o){return this.#o("LateralLeftJoin",o)}crossJoinLateral(...o){return this.#o("LateralCrossJoin",o)}crossApply(...o){return this.#o("CrossApply",o)}outerApply(...o){return this.#o("OuterApply",o)}#o(o,t){return new P({...this.#e,queryNode:E.cloneWithJoin(this.#e.queryNode,zt(o,t))})}orderBy(...o){return new P({...this.#e,queryNode:E.cloneWithOrderByItems(this.#e.queryNode,He(o))})}groupBy(o){return new P({...this.#e,queryNode:H.cloneWithGroupByItems(this.#e.queryNode,nu(o))})}limit(o){return new P({...this.#e,queryNode:H.cloneWithLimit(this.#e.queryNode,Lt.create(Q(o)))})}offset(o){return new P({...this.#e,queryNode:H.cloneWithOffset(this.#e.queryNode,tu.create(Q(o)))})}fetch(o,t="only"){return new P({...this.#e,queryNode:H.cloneWithFetch(this.#e.queryNode,lu(o,t))})}top(o,t){return new P({...this.#e,queryNode:E.cloneWithTop(this.#e.queryNode,Dt(o,t))})}union(o){return new P({...this.#e,queryNode:H.cloneWithSetOperations(this.#e.queryNode,dt("union",o,!1))})}unionAll(o){return new P({...this.#e,queryNode:H.cloneWithSetOperations(this.#e.queryNode,dt("union",o,!0))})}intersect(o){return new P({...this.#e,queryNode:H.cloneWithSetOperations(this.#e.queryNode,dt("intersect",o,!1))})}intersectAll(o){return new P({...this.#e,queryNode:H.cloneWithSetOperations(this.#e.queryNode,dt("intersect",o,!0))})}except(o){return new P({...this.#e,queryNode:H.cloneWithSetOperations(this.#e.queryNode,dt("except",o,!1))})}exceptAll(o){return new P({...this.#e,queryNode:H.cloneWithSetOperations(this.#e.queryNode,dt("except",o,!0))})}as(o){return new Oa(this,o)}clearSelect(){return new P({...this.#e,queryNode:H.cloneWithoutSelections(this.#e.queryNode)})}clearWhere(){return new P({...this.#e,queryNode:E.cloneWithoutWhere(this.#e.queryNode)})}clearLimit(){return new P({...this.#e,queryNode:H.cloneWithoutLimit(this.#e.queryNode)})}clearOffset(){return new P({...this.#e,queryNode:H.cloneWithoutOffset(this.#e.queryNode)})}clearOrderBy(){return new P({...this.#e,queryNode:E.cloneWithoutOrderBy(this.#e.queryNode)})}clearGroupBy(){return new P({...this.#e,queryNode:H.cloneWithoutGroupBy(this.#e.queryNode)})}$call(o){return o(this)}$if(o,t){return o?t(this):new P({...this.#e})}$castTo(){return new P(this.#e)}$narrowType(){return new P(this.#e)}$assertType(){return new P(this.#e)}$asTuple(){return new F(this.toOperationNode())}$asScalar(){return new F(this.toOperationNode())}withPlugin(o){return new P({...this.#e,executor:this.#e.executor.withPlugin(o)})}toOperationNode(){return this.#e.executor.transformQuery(this.#e.queryNode,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(o){let t=this.compile();return(await this.#e.executor.executeQuery(t,o)).rows}async executeTakeFirst(o){let[t]=await this.execute(o);return t}async executeTakeFirstOrThrow(o){typeof o=="function"&&(o={errorConstructor:o});let t=await this.executeTakeFirst(o);if(t===void 0){let n=o?.errorConstructor??Lo;throw It(n)?new n(this.toOperationNode()):n(this.toOperationNode())}return t}async*stream(o){typeof o!="object"&&(o={chunkSize:o});let t=this.compile(),n=this.#e.executor.stream(t,o.chunkSize??100,o);for await(let r of n)yield*r.rows}async explain(o,t){return await new P({...this.#e,queryNode:E.cloneWithExplain(this.#e.queryNode,o,t)}).execute()}};P=Pn;Oa=class{#e;#o;constructor(o,t){this.#e=o,this.#o=t}get expression(){return this.#e}get alias(){return this.#o}get isAliasedSelectQueryBuilder(){return!0}toOperationNode(){return ke.create(this.#e.toOperationNode(),R.create(this.#o))}}});var so,Tn=m(()=>{_();wr();hr();so=c({is(e){return e.kind==="AggregateFunctionNode"},create(e,o=[]){return c({kind:"AggregateFunctionNode",func:e,aggregated:o})},cloneWithDistinct(e){return c({...e,distinct:!0})},cloneWithOrderBy(e,o,t=!1){let n=t?"withinGroup":"orderBy";return c({...e,[n]:e[n]?yo.cloneWithItems(e[n],o):yo.create(o)})},cloneWithFilter(e,o){return c({...e,filter:e.filter?we.cloneWithOperation(e.filter,"And",o):we.create(o)})},cloneWithOrFilter(e,o){return c({...e,filter:e.filter?we.cloneWithOperation(e.filter,"Or",o):we.create(o)})},cloneWithOver(e,o){return c({...e,over:o})}})});var ja,Aa=m(()=>{_();ja=c({is(e){return e.kind==="FunctionNode"},create(e,o){return c({kind:"FunctionNode",func:e,arguments:o})}})});var Wt,Ea,qa=m(()=>{_();Tn();go();te();wa();ro();qt();_o();Wt=class e{#e;constructor(o){this.#e=c(o)}get expressionType(){}as(o){return new Ea(this,o)}distinct(){return new e({...this.#e,aggregateFunctionNode:so.cloneWithDistinct(this.#e.aggregateFunctionNode)})}orderBy(...o){return new e({...this.#e,aggregateFunctionNode:E.cloneWithOrderByItems(this.#e.aggregateFunctionNode,He(o))})}clearOrderBy(){return new e({...this.#e,aggregateFunctionNode:E.cloneWithoutOrderBy(this.#e.aggregateFunctionNode)})}withinGroupOrderBy(...o){return new e({...this.#e,aggregateFunctionNode:so.cloneWithOrderBy(this.#e.aggregateFunctionNode,He(o),!0)})}filterWhere(...o){return new e({...this.#e,aggregateFunctionNode:so.cloneWithFilter(this.#e.aggregateFunctionNode,le(o))})}filterWhereRef(o,t,n){return new e({...this.#e,aggregateFunctionNode:so.cloneWithFilter(this.#e.aggregateFunctionNode,ye(o,t,n))})}over(o){let t=ou();return new e({...this.#e,aggregateFunctionNode:so.cloneWithOver(this.#e.aggregateFunctionNode,(o?o(t):t).toOperationNode())})}$call(o){return o(this)}$castTo(){return new e(this.#e)}$notNull(){return new e(this.#e)}toOperationNode(){return this.#e.aggregateFunctionNode}},Ea=class{#e;#o;constructor(o,t){this.#e=o,this.#o=t}get expression(){return this.#e}get alias(){return this.#o}toOperationNode(){return ke.create(this.#e.toOperationNode(),R.create(this.#o))}}});function pu(){let e=(t,n)=>new F(ja.create(t,wo(n??[]))),o=(t,n)=>new Wt({aggregateFunctionNode:so.create(t,n?wo(n):void 0)});return Object.assign(e,{agg:o,avg(t){return o("avg",[t])},coalesce(...t){return e("coalesce",t)},count(t){return o("count",[t])},countAll(t){return new Wt({aggregateFunctionNode:so.create("count",no(t))})},max(t){return o("max",[t])},min(t){return o("min",[t])},sum(t){return o("sum",[t])},any(t){return e("any",[t])},jsonAgg(t){return new Wt({aggregateFunctionNode:so.create("json_agg",[W(t)?_e(t):t.toOperationNode()])})},toJson(t){return new F(ja.create("to_json",[W(t)?_e(t):t.toOperationNode()]))}})}var ka=m(()=>{Ft();Tn();Aa();Pe();_r();qa();_();io()});var mu,Ra=m(()=>{_();mu=c({is(e){return e.kind==="UnaryOperationNode"},create(e,o){return c({kind:"UnaryOperationNode",operator:e,operand:o})}})});function fu(e,o){if(il(e))return mu.create(Je.create(e),ue(o));throw new Error(`invalid unary operator ${JSON.stringify(e)}`)}var hu=m(()=>{jt();Ra();Pe()});var Ae,Mn=m(()=>{_();vr();Ae=c({is(e){return e.kind==="CaseNode"},create(e){return c({kind:"CaseNode",value:e})},cloneWithWhen(e,o){return c({...e,when:c(e.when?[...e.when,o]:[o])})},cloneWithThen(e,o){return c({...e,when:e.when?c([...e.when.slice(0,-1),No.cloneWithResult(e.when[e.when.length-1],o)]):void 0})},cloneWith(e,o){return c({...e,...o})}})});var In,Bt,Dn,Ln,Pa=m(()=>{Ft();_();Pe();Mn();vr();ro();vo();In=class{#e;constructor(o){this.#e=c(o)}when(...o){return new Bt({...this.#e,node:Ae.cloneWithWhen(this.#e.node,No.create(le(o)))})}whenRef(o,t,n){return new Bt({...this.#e,node:Ae.cloneWithWhen(this.#e.node,No.create(ye(o,t,n)))})}},Bt=class{#e;constructor(o){this.#e=c(o)}then(o){return new Dn({...this.#e,node:Ae.cloneWithThen(this.#e.node,hn(o)?mr(o):Q(o))})}thenRef(o){return new Dn({...this.#e,node:Ae.cloneWithThen(this.#e.node,ue(o))})}},Dn=class{#e;constructor(o){this.#e=c(o)}when(...o){return new Bt({...this.#e,node:Ae.cloneWithWhen(this.#e.node,No.create(le(o)))})}whenRef(o,t,n){return new Bt({...this.#e,node:Ae.cloneWithWhen(this.#e.node,No.create(ye(o,t,n)))})}else(o){return new Ln({...this.#e,node:Ae.cloneWith(this.#e.node,{else:hn(o)?mr(o):Q(o)})})}elseRef(o){return new Ln({...this.#e,node:Ae.cloneWith(this.#e.node,{else:ue(o)})})}end(){return new F(Ae.cloneWith(this.#e.node,{isStatement:!1}))}endCase(){return new F(Ae.cloneWith(this.#e.node,{isStatement:!0}))}},Ln=class{#e;constructor(o){this.#e=c(o)}end(){return new F(Ae.cloneWith(this.#e.node,{isStatement:!1}))}endCase(){return new F(Ae.cloneWith(this.#e.node,{isStatement:!0}))}}});var Ta,Ma=m(()=>{_();Ta=c({is(e){return e.kind==="JSONPathLegNode"},create(e,o){return c({kind:"JSONPathLegNode",type:e,value:o})}})});var Hg,Ut,zn,Ia,Da=m(()=>{go();te();pn();Ma();pr();un();Le();Io();Hg=/^#-\d+$/,Ut=class{#e;constructor(o){this.#e=o}at(o){if(typeof o!="number"&&typeof o!="string"||typeof o=="number"&&!Number.isInteger(o)||typeof o=="string"&&o!=="last"&&!Hg.test(o))throw new Error(`Unexpected index value in .at(...): ${o}`);return this.#o("ArrayLocation",o)}key(o){return this.#o("Member",o)}#o(o,t){return kt.is(this.#e)?new zn(kt.cloneWithTraversal(this.#e,Mo.is(this.#e.traversal)?Mo.cloneWithLeg(this.#e.traversal,Ta.create(o,t)):dn.cloneWithValue(this.#e.traversal,Se.createImmediate(t)))):new zn(Mo.cloneWithLeg(this.#e,Ta.create(o,t)))}},zn=class e extends Ut{#e;constructor(o){super(o),this.#e=o}get expressionType(){}as(o){return new Ia(this,o)}$castTo(){return new e(this.#e)}$notNull(){return new e(this.#e)}toOperationNode(){return this.#e}},Ia=class{#e;#o;constructor(o,t){this.#e=o,this.#o=t}get expression(){return this.#e}get alias(){return this.#o}toOperationNode(){return ke.create(this.#e.toOperationNode(),re(this.#o)?this.#o.toOperationNode():R.create(this.#o))}}});var La,za=m(()=>{_();La=c({is(e){return e.kind==="TupleNode"},create(e){return c({kind:"TupleNode",values:c(e)})}})});function bu(e){return Xg[e]||Yg.some(o=>o.test(e))}var Xg,Yg,gu,Fa=m(()=>{_();Xg=c({bigint:!0,bigserial:!0,binary:!0,blob:!0,boolean:!0,bytea:!0,char:!0,date:!0,datemultirange:!0,daterange:!0,datetime:!0,datetime2:!0,decimal:!0,"double precision":!0,float4:!0,float8:!0,int2:!0,int4:!0,int4multirange:!0,int4range:!0,int8:!0,int8multirange:!0,int8range:!0,integer:!0,json:!0,jsonb:!0,numeric:!0,nummultirange:!0,numrange:!0,real:!0,serial:!0,smallint:!0,text:!0,time:!0,timestamp:!0,timestamptz:!0,timetz:!0,tsmultirange:!0,tsrange:!0,tstzmultirange:!0,tstzrange:!0,uuid:!0,varbinary:!0,varchar:!0}),Yg=c([/^varchar\(\d+\)$/,/^char\(\d+\)$/,/^decimal\(\d+, \d+\)$/,/^numeric\(\d+, \d+\)$/,/^binary\(\d+\)$/,/^datetime\(\d+\)$/,/^time\(\d+\)$/,/^timetz\(\d+\)$/,/^timestamp\(\d+\)$/,/^timestamptz\(\d+\)$/,/^datetime2\(\d+\)$/,/^varbinary\(\d+\)$/]),gu=c({is(e){return e.kind==="DataTypeNode"},create(e){return c({kind:"DataTypeNode",dataType:e})}})});function wu(e){if(re(e))return e.toOperationNode();if(bu(e))return gu.create(e);throw new Error(`invalid column data type ${JSON.stringify(e)}`)}var vu=m(()=>{Fa();Le()});var yu,Wa=m(()=>{_();yu=c({is(e){return e.kind==="CastNode"},create(e,o){return c({kind:"CastNode",expression:e,dataType:o})}})});function Na(e=kn){function o(r,a,s){return new F(gn(r,a,s))}function t(r,a){return new F(fu(r,a))}let n=Object.assign(o,{fn:void 0,eb:void 0,selectFrom(r){return du({queryId:Te(),executor:e,queryNode:H.createFrom(at(r))})},case(r){return new In({node:Ae.create(ho(r)?void 0:ue(r))})},ref(r,a){return ho(a)?new F(ze(r)):new Ut(ll(r,a))},jsonPath(){return new Ut(Mo.create())},table(r){return new F(_e(r))},val(r){return new F(Q(r))},refTuple(...r){return new F(La.create(r.map(ue)))},tuple(...r){return new F(La.create(r.map(Q)))},lit(r){return new F(mr(r))},unary:t,not(r){return t("not",r)},exists(r){return t("exists",r)},neg(r){return t("-",r)},between(r,a,s){return new F(Po.create(ue(r),Je.create("between"),Re.create(Q(a),Q(s))))},betweenSymmetric(r,a,s){return new F(Po.create(ue(r),Je.create("between symmetric"),Re.create(Q(a),Q(s))))},and(r){return qe(r)?new F(bn(r,"and")):new F(Wi(r,"and"))},or(r){return qe(r)?new F(bn(r,"or")):new F(Wi(r,"or"))},parens(...r){let a=le(r);return Do.is(a)?new F(a):new F(Do.create(a))},cast(r,a){return new F(yu.create(ue(r),wu(a)))}});return n.fn=pu(),n.eb=n,n}function xo(e){return Na()}var Mt=m(()=>{Sa();yr();io();An();ka();Pe();ro();fr();Ft();jt();hu();vo();Rn();Pa();Mn();_();Da();on();Ro();za();pr();vu();Wa()});function To(e){if(re(e))return e.toOperationNode();if(ve(e))return e(xo()).toOperationNode();throw new Error(`invalid expression: ${JSON.stringify(e)}`)}function $n(e){if(re(e))return e.toOperationNode();if(ve(e))return e(xo()).toOperationNode();throw new Error(`invalid aliased expression: ${JSON.stringify(e)}`)}function rt(e){return Kr(e)||Xc(e)||ve(e)}var nt=m(()=>{Zr();Le();Mt();_()});function _u(e){return Oe(e)&&re(e)&&W(e.table)&&W(e.alias)}var Ba=m(()=>{Le();_()});function at(e){return qe(e)?e.map(o=>ut(o)):[ut(e)]}function ut(e){return W(e)?Kg(e):_u(e)?e.toOperationNode():$n(e)}function Kg(e){let o=" as ";if(e.includes(o)){let[t,n]=e.split(o).map(Nu);return ke.create(_e(t),R.create(n))}else return _e(e)}function _e(e){if(e.includes(".")){let[t,n]=e.split(".").map(Nu);return ko.createWithSchema(t,n)}else return ko.create(e)}function Nu(e){return e.trim()}var io=m(()=>{_();go();ur();nt();te();Ba()});var jj,$u=m(()=>{_();jj=c({is(e){return e.kind==="AddColumnNode"},create(e){return c({kind:"AddColumnNode",column:e})}})});var kj,xu=m(()=>{_();Qe();kj=c({is(e){return e.kind==="ColumnDefinitionNode"},create(e,o){return c({kind:"ColumnDefinitionNode",column:se.create(e),dataType:o})},cloneWithFrontModifier(e,o){return c({...e,frontModifiers:e.frontModifiers?c([...e.frontModifiers,o]):[o]})},cloneWithEndModifier(e,o){return c({...e,endModifiers:e.endModifiers?c([...e.endModifiers,o]):[o]})},cloneWith(e,o){return c({...e,...o})}})});var Mj,Cu=m(()=>{_();Qe();Mj=c({is(e){return e.kind==="DropColumnNode"},create(e){return c({kind:"DropColumnNode",column:se.create(e)})},cloneWith(e,o){return c({...e,...o})}})});var zj,Ou=m(()=>{_();Qe();zj=c({is(e){return e.kind==="RenameColumnNode"},create(e,o){return c({kind:"RenameColumnNode",column:se.create(e),renameTo:se.create(o)})}})});var Uj,Su=m(()=>{_();te();Uj=c({is(e){return e.kind==="CheckConstraintNode"},create(e,o){return c({kind:"CheckConstraintNode",expression:e,name:o?R.create(o):void 0})}})});var Zg,Qj,ju,Ua=m(()=>{_();Zg=c({cascade:!0,"no action":!0,restrict:!0,"set default":!0,"set null":!0}),Qj=Object.keys(Zg),ju=c({is(e){return e.kind==="ReferencesNode"},create(e,o){return c({kind:"ReferencesNode",table:e,columns:c([...o])})},cloneWithOnDelete(e,o){return c({...e,onDelete:o})},cloneWithOnUpdate(e,o){return c({...e,onUpdate:o})}})});var Xj,Au=m(()=>{_();Xj=c({is(e){return e.kind==="GeneratedNode"},create(e){return c({kind:"GeneratedNode",...e})},createWithExpression(e){return c({kind:"GeneratedNode",always:!0,expression:e})},cloneWith(e,o){return c({...e,...o})}})});var Zj,Eu=m(()=>{_();Zj=c({is(e){return e.kind==="DefaultValueNode"},create(e){return c({kind:"DefaultValueNode",defaultValue:e})}})});var qu=m(()=>{});var rA,ku=m(()=>{_();rA=c({is(e){return e.kind==="ModifyColumnNode"},create(e){return c({kind:"ModifyColumnNode",column:e})}})});var cA,Ru=m(()=>{_();te();Ua();cA=c({is(e){return e.kind==="ForeignKeyConstraintNode"},create(e,o,t,n){return c({kind:"ForeignKeyConstraintNode",columns:e,references:ju.create(o,t),name:n?R.create(n):void 0})},cloneWith(e,o){return c({...e,...o})}})});var Pu=m(()=>{});var pA,Tu=m(()=>{_();pA=c({is(e){return e.kind==="AddConstraintNode"},create(e){return c({kind:"AddConstraintNode",constraint:e})}})});var wA,Mu=m(()=>{Di();_();Qe();te();wA=c({is(e){return e.kind==="UniqueConstraintNode"},create(e,o,t){return W(e.at(0))&&(Et("`UniqueConstraintNode.create(columns: string[], ...)` is deprecated - pass `ColumnNode[]` instead."),e=e.map(se.create)),c({kind:"UniqueConstraintNode",columns:c(e),name:o?R.create(o):void 0,nullsNotDistinct:t})},cloneWith(e,o){return c({...e,...o})}})});var NA,Iu=m(()=>{_();te();NA=c({is(e){return e.kind==="DropConstraintNode"},create(e){return c({kind:"DropConstraintNode",constraintName:R.create(e)})},cloneWith(e,o){return c({...e,...o})}})});var OA,Du=m(()=>{_();Qe();OA=c({is(e){return e.kind==="AlterColumnNode"},create(e,o,t){return c({kind:"AlterColumnNode",column:se.create(e),[o]:t})}})});var Lu=m(()=>{});var kA,zu=m(()=>{_();Qe();te();kA=c({is(e){return e.kind==="PrimaryKeyConstraintNode"},create(e,o){return c({kind:"PrimaryKeyConstraintNode",columns:c(e.map(se.create)),name:o?R.create(o):void 0})},cloneWith(e,o){return c({...e,...o})}})});var MA,Fu=m(()=>{_();te();MA=c({is(e){return e.kind==="AddIndexNode"},create(e){return c({kind:"AddIndexNode",name:R.create(e)})},cloneWith(e,o){return c({...e,...o})},cloneWithColumns(e,o){return c({...e,columns:[...e.columns||[],...o]})}})});var zA,Wu=m(()=>{_();te();zA=c({is(e){return e.kind==="RenameConstraintNode"},create(e,o){return c({kind:"RenameConstraintNode",oldName:R.create(e),newName:R.create(o)})}})});var Bu=m(()=>{});var Uu=m(()=>{});var Vu=m(()=>{});var Ju=m(()=>{});var Qu=m(()=>{});var Gu=m(()=>{});var Hu=m(()=>{});var Xu=m(()=>{});var KA,Yu=m(()=>{_();et();KA=c({is(e){return e.kind==="CreateViewNode"},create(e){return c({kind:"CreateViewNode",name:Ue.create(e)})},cloneWith(e,o){return c({...e,...o})}})});var Ku=m(()=>{});var rE,Zu=m(()=>{_();et();rE=c({is(e){return e.kind==="DropViewNode"},create(e){return c({kind:"DropViewNode",name:Ue.create(e)})},cloneWith(e,o){return c({...e,...o})}})});var ed=m(()=>{});var lE,od=m(()=>{_();fn();Io();lE=c({is(e){return e.kind==="CreateTypeNode"},create(e){return c({kind:"CreateTypeNode",name:e})},cloneWithEnum(e,o){return c({...e,enum:mn.create(o.map(Se.createImmediate))})}})});var td=m(()=>{});var mE,rd=m(()=>{_();mE=c({is(e){return e.kind==="DropTypeNode"},create(e){return Array.isArray(e)||(e=[e]),c({kind:"DropTypeNode",name:e[0],additionalNames:e.slice(1)})},cloneWith(e,o){return c({...e,...o})}})});var nd=m(()=>{});var wE,id=m(()=>{_();et();wE=c({is(e){return e.kind==="RefreshMaterializedViewNode"},create(e){return c({kind:"RefreshMaterializedViewNode",name:Ue.create(e)})},cloneWith(e,o){return c({...e,...o})}})});var ad=m(()=>{});var NE,sd=m(()=>{_();NE=c({is(e){return e.kind==="AlterTypeNode"},create(e){return c({kind:"AlterTypeNode",name:e})},cloneWith(e,o){return c({...e,...o})}})});var CE,cd=m(()=>{_();CE=c({is(e){return e.kind==="AddValueNode"},create(e){return c({kind:"AddValueNode",value:e})},cloneWith(e,o){return c({...e,...o})}})});var ld=m(()=>{});var AE,ud=m(()=>{_();AE=c({is(e){return e.kind==="RenameValueNode"},create(e,o){return c({kind:"RenameValueNode",oldValue:e,newValue:o})}})});var dd=m(()=>{});var pd=m(()=>{});var md=m(()=>{});var fd=m(()=>{});var hd=m(()=>{});var gd=m(()=>{});var eb,DE,bd=m(()=>{_();eb=["query","error"],DE=c(eb)});var wd=m(()=>{});var vd=m(()=>{Symbol.asyncDispose??=Symbol("Symbol.asyncDispose")});function Co(e){return new Va(e)}var Va,Ja,Qa=m(()=>{go();_();Rn();te();Le();Va=class e{#e;constructor(o){this.#e=c(o)}get expressionType(){}get isRawBuilder(){return!0}as(o){return new Ja(this,o)}$castTo(){return new e({...this.#e})}$notNull(){return new e(this.#e)}withPlugin(o){return new e({...this.#e,plugins:this.#e.plugins!==void 0?c([...this.#e.plugins,o]):c([o])})}toOperationNode(){return this.#r(this.#o())}compile(o){return this.#t(this.#o(o))}async execute(o,t){let n=this.#o(o);return n.executeQuery(this.#t(n),t)}#o(o){let t=o!==void 0?o.getExecutor():kn;return this.#e.plugins!==void 0?t.withPlugins(this.#e.plugins):t}#r(o){return o.transformQuery(this.#e.rawNode,this.#e.queryId)}#t(o){return o.compileQuery(this.#r(o),this.#e.queryId)}};Ja=class{#e;#o;constructor(o,t){this.#e=o,this.#o=t}get expression(){return this.#e}get alias(){return this.#o}get rawBuilder(){return this.#e}toOperationNode(){return ke.create(this.#e.toOperationNode(),re(this.#o)?this.#o.toOperationNode():R.create(this.#o))}}});function yd(e){return re(e)?e.toOperationNode():Q(e)}var j,_d=m(()=>{te();Le();tt();Io();Pe();io();vo();An();Qa();j=Object.assign((e,...o)=>Co({queryId:Te(),rawNode:ce.create(e,o?.map(yd)??[])}),{ref(e){return Co({queryId:Te(),rawNode:ce.createWithChild(ze(e))})},val(e){return Co({queryId:Te(),rawNode:ce.createWithChild(Q(e))})},table(e){return Co({queryId:Te(),rawNode:ce.createWithChild(_e(e))})},id(...e){let o=new Array(e.length+1).fill(".");return o[0]="",o[o.length-1]="",Co({queryId:Te(),rawNode:ce.create(o,e.map(R.create))})},lit(e){return Co({queryId:Te(),rawNode:ce.createWithChild(Se.createImmediate(e))})},raw(e){return Co({queryId:Te(),rawNode:ce.createWithSql(e)})},join(e,o=j`, `){let t=new Array(Math.max(2*e.length-1,0)),n=o.toOperationNode();for(let r=0;r<e.length;++r)t[2*r]=yd(e[r]),r!==e.length-1&&(t[2*r+1]=n);return Co({queryId:Te(),rawNode:ce.createWithChildren(t)})}})});var Nd=m(()=>{});var aq,sq,cq,Ga=m(()=>{_();aq=c({ForKeyShare:"for key share",ForNoKeyUpdate:"for no key update",ForUpdate:"for update",ForShare:"for share",NoWait:"nowait",SkipLocked:"skip locked",Distinct:"distinct"}),sq=c({ForKeyShare:1,ForNoKeyUpdate:1,ForUpdate:1,ForShare:1,NoWait:2,SkipLocked:2,Distinct:0}),cq=c({InnerJoin:"inner join",LeftJoin:"left join",RightJoin:"right join",FullJoin:"full join",CrossJoin:"cross join",LateralInnerJoin:"inner join lateral",LateralLeftJoin:"left join lateral",LateralCrossJoin:"cross join lateral",OuterApply:"outer apply",CrossApply:"cross apply",Using:"using"})});var pt,Or=m(()=>{tt();_();An();pt=c({raw(e,o=[]){return c({sql:e,query:ce.createWithSql(e),parameters:c(o),queryId:Te()})}})});var $d=m(()=>{});var xd=m(()=>{});var Cd=m(()=>{});var Od=m(()=>{});var Sd=m(()=>{});var jd=m(()=>{});var Ad=m(()=>{});function zo(e,o){if(ob(e)&&o.stack){let t=o.stack.split(`
|
|
3
|
+
var gg=Object.defineProperty;var m=(e,o,t)=>()=>{if(t)throw t[0];try{return e&&(o=e(e=0)),o}catch(r){throw t=[r],r}};var bg=(e,o)=>{for(var t in o)gg(e,t,{get:o[t],enumerable:!0})};import{AsyncLocalStorage as wg}from"node:async_hooks";import{readdirSync as vg}from"node:fs";import{createRequire as yg}from"node:module";import{fileURLToPath as _g}from"node:url";function to(e,o){let r=Tc[e]?.[o];if(r!==void 0)return r;for(let n of xg[e]??[]){let a=n.regex.exec(o);if(a)return n.traduccion.replace(/%\{([\w]+)\}/g,(s,c)=>{let d=n.nombres.indexOf(c);return d<0?s:a[d+1]})}return o}var Ng,$g,Tc,xg,Cg,To,on=m(()=>{Ng=vg(new URL("./locales/",import.meta.url)).filter(e=>/\.(?:ts|js)$/.test(e)&&!e.endsWith(".d.ts")),$g=yg(import.meta.url),Tc=Object.fromEntries(Ng.map(e=>[e.replace(/\.(?:ts|js)$/,""),$g(_g(new URL(`./locales/${e}`,import.meta.url))).default])),xg=Object.fromEntries(Object.entries(Tc).map(([e,o])=>[e,Object.entries(o).filter(([t])=>t.includes("%{")).map(([t,r])=>{let n=[],a=0,s="";for(let c of t.matchAll(/%\{([\w]+)\}/g)){let d=c.index;s+=t.slice(a,d).replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"([\\s\\S]*?)",n.push(c[1]),a=d+c[0].length}return s+=t.slice(a).replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),{regex:new RegExp(`^${s}$`),nombres:n,traduccion:r,especificidad:t.replace(/%\{[\w]+\}/g,"").length}}).sort((t,r)=>r.especificidad-t.especificidad)])),Cg=new wg,To=()=>Cg.getStore()?.idioma??"es"});var F,i,R=m(()=>{on();F=class extends Error{constructor(t,r,n,a=!0,s){super(a?to(To(),n):n);this.estado=t;this.codigo=r;this.datos=s}estado;codigo;datos},i=(e,o=!0)=>new F(400,"peticion_invalida",e,o)});var V,jg,Mc,Ic=m(()=>{V={id:"Id del registro."},jg=[{nombre:"contacto.creado",descripcion:"Se ha creado un contacto.",datos:V},{nombre:"contacto.actualizado",descripcion:"Han cambiado datos de un contacto.",datos:{...V,campos:"Qu\xE9 columnas (si se sabe).",lote:"La acci\xF3n, si fue en lote."}},{nombre:"contacto.borrado",descripcion:"Se ha borrado un contacto (tambi\xE9n al fusionarlo en otro).",datos:{...V,fusionado_en:"Si se fusion\xF3: en cu\xE1l."}},{nombre:"empresa.creada",descripcion:"Se ha creado una empresa.",datos:V},{nombre:"empresa.actualizada",descripcion:"Han cambiado datos de una empresa.",datos:{...V,campos:"Qu\xE9 columnas (si se sabe)."}},{nombre:"empresa.borrada",descripcion:"Se ha borrado una empresa.",datos:V},{nombre:"contacto.fusionado",descripcion:"Un contacto se ha fusionado en otro: quien guarde su id, que lo cambie por el que queda.",datos:{...V,se_va:"El que se fue.",queda:"El que queda (= id)."}},{nombre:"empresa.fusionada",descripcion:"Una empresa se ha fusionado en otra: quien guarde su id, que lo cambie por la que queda.",datos:{...V,se_va:"La que se fue.",queda:"La que queda (= id)."}},{nombre:"oportunidad.creada",descripcion:"Se ha creado una oportunidad.",datos:V},{nombre:"oportunidad.actualizada",descripcion:"Han cambiado datos de una oportunidad (no la etapa).",datos:{...V,campos:"Qu\xE9 columnas (si se sabe)."}},{nombre:"oportunidad.etapa_cambiada",descripcion:"Una oportunidad ha cambiado de etapa.",datos:{...V,de:"Etapa anterior.",a:"Etapa nueva."}},{nombre:"oportunidad.ganada",descripcion:"Una oportunidad ha pasado a ganada (adem\xE1s de etapa_cambiada).",datos:{...V,de:"Etapa anterior.",a:"won",origen:"\xABcrm\xBB (una persona o la API) o \xABfacturacion\xBB (su presupuesto principal se acept\xF3).",quien:"Nombre de quien la movi\xF3 (persona del espacio o due\xF1o de la clave), si se sabe."}},{nombre:"oportunidad.perdida",descripcion:"Una oportunidad ha pasado a perdida (adem\xE1s de etapa_cambiada).",datos:{...V,de:"Etapa anterior.",a:"lost",origen:"\xABcrm\xBB o \xABfacturacion\xBB (su presupuesto principal se rechaz\xF3).",motivo:"El motivo de p\xE9rdida, si se dio.",quien:"Nombre de quien la movi\xF3 (persona del espacio o due\xF1o de la clave), si se sabe."}},{nombre:"oportunidad.archivada",descripcion:"Una oportunidad ha salido del embudo al archivo.",datos:V},{nombre:"oportunidad.borrada",descripcion:"Se ha borrado una oportunidad.",datos:V},{nombre:"nota.creada",descripcion:"Nueva nota en el hilo de un contacto o de una oportunidad.",datos:{...V,contacto_id:"Si es de un contacto.",oportunidad_id:"Si es de una oportunidad."}},{nombre:"nota.actualizada",descripcion:"Se ha editado una nota.",datos:V},{nombre:"nota.borrada",descripcion:"Se ha borrado una nota.",datos:V},{nombre:"nota.mencion",descripcion:"Una nota menciona (@) a miembros del espacio: al crearla, o al editarla con menciones nuevas. Solo miembros activos (la base filtra el resto).",datos:{...V,contacto_id:"Si es de un contacto.",oportunidad_id:"Si es de una oportunidad.",mencionados:"Ids de los miembros mencionados por primera vez en esta nota (miembros.listar)."}},{nombre:"tarea.creada",descripcion:"Se ha creado una tarea.",datos:{...V,contacto_id:"Su contacto."}},{nombre:"tarea.actualizada",descripcion:"Ha cambiado una tarea (o se ha reabierto).",datos:{...V,campos:"Qu\xE9 columnas (si se sabe)."}},{nombre:"tarea.completada",descripcion:"Se ha completado una tarea.",datos:V},{nombre:"tarea.borrada",descripcion:"Se ha borrado una tarea.",datos:V},{nombre:"contacto.etiquetado",descripcion:"Una Persona ha recibido una etiqueta (una vez por etiqueta a\xF1adida, venga de donde venga).",datos:{...V,etiqueta:"El nombre de la etiqueta.",etiqueta_id:"Su id."}},{nombre:"lead.recibido",descripcion:"Ha entrado un lead desde una web (leads.crear): el id es el de su Persona.",datos:{...V,origen:"De d\xF3nde viene (\xABlanding:<slug>\xBB).",oportunidad_id:"La oportunidad que abri\xF3."}},{nombre:"formulario.respuesta",descripcion:"Alguien ha respondido un formulario p\xFAblico del CRM.",datos:{...V,formulario_id:"El formulario.",contacto_id:"Su contacto.",oportunidad_id:"La oportunidad, si el formulario la abre."}},{nombre:"registro.creado",descripcion:"Se ha creado un registro de un m\xF3dulo del cliente.",datos:{...V,modulo:"La clave del m\xF3dulo (mod_<clave> en la API v1).",origen:"\xABformulario\xBB o \xABimportacion\xBB, si no vino de la interfaz o la API."}},{nombre:"registro.actualizado",descripcion:"Han cambiado datos de un registro de un m\xF3dulo.",datos:{...V,modulo:"La clave del m\xF3dulo.",campos:"Qu\xE9 campos."}},{nombre:"registro.borrado",descripcion:"Se ha borrado un registro de un m\xF3dulo.",datos:{...V,modulo:"La clave del m\xF3dulo."}}],Mc=jg.map(e=>e.nombre)});function Sg(e,[o,t]){let r=new Set;for(let n of e.split(",")){let a=/^(\*|(\d{1,2})(?:-(\d{1,2}))?)(?:\/(\d{1,2}))?$/.exec(n);if(!a)return null;let s=a[1]==="*"?o:Number(a[2]),c=a[1]==="*"?t:a[3]!==void 0?Number(a[3]):a[4]!==void 0?t:s,d=a[4]!==void 0?Number(a[4]):1;if(s<o||c>t||s>c||d<1)return null;for(let u=s;u<=c;u+=d)r.add(u)}return r}function Lc(e){let o=e.trim().split(/\s+/);if(o.length!==5)return null;let t=o.map((n,a)=>Sg(n,Og[a]));if(t.some(n=>!n))return null;let r=new Set([...t[4]].map(n=>n===7?0:n));return{minutos:t[0],horas:t[1],dias:t[2],meses:t[3],semana:r,diaLibre:o[2]==="*",semanaLibre:o[4]==="*"}}function Dc(e){let o=[...e.horas].sort((a,s)=>a-s),t=[...e.minutos].sort((a,s)=>a-s),r=o.flatMap(a=>t.map(s=>a*60+s));if(r.length<=1)return 1440;let n=1440-r.at(-1)+r[0];for(let a=1;a<r.length;a++)n=Math.min(n,r[a]-r[a-1]);return n}var Og,By,zc=m(()=>{Og=[[0,59],[0,23],[1,31],[1,12],[0,7]];By=new Intl.DateTimeFormat("en-GB",{timeZone:"Europe/Madrid",hourCycle:"h23",minute:"numeric",hour:"numeric",day:"numeric",month:"numeric",weekday:"short"})});function Fc(e){let o=(t,r)=>Number.isInteger(t)?Math.min(r.max,Math.max(r.min,t)):r.defecto;return{ms:o(e?.tope?.ms,D.ms),memoriaMb:o(e?.tope?.memoria_mb,D.memoriaMb)}}var D,pr=m(()=>{D={simultaneas:2,ms:{defecto:5e3,min:100,max:3e4},memoriaMb:{defecto:64,min:16,max:256},pilaBytes:1048576,margenMs:2e3,llamadasApi:100,llamadasRed:10,llamadaCaracteres:327680,llamadasEnVuelo:8,codigoBytes:262144,entradaBytes:65536,salidaBytes:65536,red:{cuerpoBytes:262144,respuestaBytes:1048576,plazoMs:5e3},webhookBytes:65536,cronMinutos:15}});function Wc(e){if(!e.startsWith("*."))return!1;let o=e.slice(2).toLowerCase();if(Eg.has(o)||qg.test(o))return!0;let t=o.split(".");return t.length===2&&t[1].length===2&&Ag.has(t[0])}var Ag,Eg,qg,Bc=m(()=>{Ag=new Set(["co","com","net","org","gov","gob","edu","ac","nom","mil","ltd","plc","me","or","ne","go","info","biz","int"]),Eg=new Set(["github.io","gitlab.io","pages.dev","workers.dev","vercel.app","netlify.app","web.app","firebaseapp.com","herokuapp.com","appspot.com","azurewebsites.net","cloudfront.net","amazonaws.com","blogspot.com","wordpress.com","glitch.me","onrender.com","fly.dev","repl.co","ngrok.io","ngrok-free.app","trycloudflare.com","r2.dev","supabase.co","myshopify.com","firebaseio.com","duckdns.org","no-ip.org","ddns.net","netlify.com","blob.core.windows.net","web.core.windows.net"]),qg=/^(s3([.-][a-z0-9-]+)?\.amazonaws\.com|blogspot\.[a-z]{2,3}(\.[a-z]{2})?)$/});function Li(e,o=0){if(o>20)throw i("El manifiesto anida demasiado.");if(Array.isArray(e))return e.forEach(t=>Li(t,o+1));if(ge(e))for(let t of Object.keys(e)){if(Rg.has(t))throw i(`Clave no admitida \xAB${t}\xBB.`);Li(e[t],o+1)}}function xe(e,o,t){for(let r of Object.keys(e))if(!o.includes(r))throw i(`${t}: clave no admitida \xAB${r.slice(0,40)}\xBB.`)}function zg(e,o,t={}){return Lg.test(e.replace(Dg,""))?`\xAB${o}\xBB: lleva caracteres de control, invisibles o de direcci\xF3n del texto.`:t.reservar&&!t.firmada&&zi(e)?`\xAB${o}\xBB: \xABForgeNEX\xBB est\xE1 reservado a lo que publica ForgeNEX.`:null}function J(e,o,t,r=!0){if(e!=null&&typeof e!="string")throw i(`\xAB${o}\xBB: texto de hasta ${t} caracteres.`);let n=typeof e=="string"?e.trim():"";if(n===""){if(r)throw i(`Falta \xAB${o}\xBB.`);return""}if(n.length>t)throw i(`\xAB${o}\xBB: texto de hasta ${t} caracteres.`);let a=zg(n,o);if(a)throw i(a);return n}function Bg(e){return e.normalize("NFKC").replace(new RegExp("(\\p{Ll})(?=\\p{Lu})","gu"),"$1 ").replace(new RegExp("(\\p{Lu})(?=\\p{Lu}\\p{Ll})","gu"),"$1 ").split(/[^\p{L}\p{N}\p{M}]+/u).map(Di).filter(Boolean)}function Zc(e,o,t){let r=re(e,o,Hc,t);if(Wc(r))throw i(`\xAB${o}\xBB: \xAB${r}\xBB abarca dominios de cualquiera; pon el dominio de tu servicio (\xAB*.api.ejemplo.co.uk\xBB o \xABapi.ejemplo.co.uk\xBB).`);return r}function re(e,o,t,r){if(typeof e!="string"||!t.test(e))throw i(`\xAB${o}\xBB: ${r}.`);return e}function he(e,o,t){if(e==null)return[];if(!Array.isArray(e))throw i(`\xAB${o}\xBB: una lista.`);if(e.length>t)throw i(`\xAB${o}\xBB: como mucho ${t}.`);return e}function Ce(e,o,t){let r=new Set;for(let n of e){let a=o(n);if(r.has(a))throw i(`\xAB${t}\xBB: \xAB${a}\xBB est\xE1 repetido.`);r.add(a)}return e}function Ii(e,o){let t=J(e,o,500),r;try{r=new URL(t)}catch{throw i(`\xAB${o}\xBB: una direcci\xF3n https.`)}if(r.protocol!=="https:"||r.username||r.password||!Hc.test(r.hostname)||r.hostname.startsWith("*."))throw i(`\xAB${o}\xBB: una direcci\xF3n https con nombre de dominio (ni IP ni localhost).`);return r.toString()}function Ug(e){let[o,t]=e.split(".");return Di(o??"")==="forgenex"||Di(t??"")==="forgenex"}function wo(e){if(Object.hasOwn(Io,e))return e;let o=e.startsWith("mod_")?e.slice(4):e;return Mg.test(o)?`mod_${o}`:null}function Vg(e){if(e===void 0)return{modulos:{},almacen:!1,red_hacia:[],eventos:[],archivos:[]};if(!ge(e))throw i("\xABpermisos\xBB: un objeto.");xe(e,["modulos","almacen","red_hacia","eventos","archivos"],"Permisos");let o={};if(e.modulos!==void 0){if(!ge(e.modulos))throw i("\xABpermisos.modulos\xBB: un objeto { m\xF3dulo: [operaciones] }.");let a=Object.entries(e.modulos);if(a.length>40)throw i("\xABpermisos.modulos\xBB: como mucho 40 m\xF3dulos.");for(let[s,c]of a){let d=wo(s);if(!d)throw i(`\xABpermisos.modulos\xBB: \xAB${s.slice(0,60)}\xBB no es un m\xF3dulo (min\xFAsculas, n\xFAmeros y _).`);if(o[d])throw i(`\xABpermisos.modulos\xBB: \xAB${s}\xBB est\xE1 repetido.`);let u=Io[d]?.ops??mr,p=he(c,`permisos.modulos.${s}`,4);if(!p.length)throw i(`\xABpermisos.modulos.${s}\xBB: di qu\xE9 operaciones (${u.join(", ")}).`);for(let h of p)if(typeof h!="string"||!u.includes(h))throw i(`\xABpermisos.modulos.${s}\xBB: operaciones ${u.join(", ")}.`);let f=new Set(p);if((f.has("editar")||f.has("borrar"))&&!f.has("ver"))throw i(`\xABpermisos.modulos.${s}\xBB: para \xABeditar\xBB o \xABborrar\xBB hace falta \xABver\xBB.`);o[d]=mr.filter(h=>f.has(h))}}if(e.almacen!==void 0&&typeof e.almacen!="boolean")throw i("\xABpermisos.almacen\xBB: s\xED o no (true/false).");let t=Ce(he(e.red_hacia,"permisos.red_hacia",20).map((a,s)=>Zc(a,`permisos.red_hacia[${s}]`,"un dominio (\xABapi.ejemplo.com\xBB o \xAB*.ejemplo.com\xBB; ni IP ni localhost)")),a=>a,"permisos.red_hacia").sort(),r=Ce(he(e.eventos,"permisos.eventos",40).map((a,s)=>{if(typeof a!="string"||!Mc.includes(a))throw i(`\xABpermisos.eventos[${s}]\xBB: un evento del cat\xE1logo (GET /api/v1/eventos).`);return a}),a=>a,"permisos.eventos").sort(),n=he(e.archivos,"permisos.archivos",2);for(let a of n)if(typeof a!="string"||!Uc.includes(a))throw i('\xABpermisos.archivos\xBB: ["leer"] o ["leer", "escribir"].');if(n.includes("escribir")&&!n.includes("leer"))throw i("\xABpermisos.archivos\xBB: para \xABescribir\xBB hace falta \xABleer\xBB.");return{modulos:Object.fromEntries(Object.entries(o).sort(([a],[s])=>a.localeCompare(s))),almacen:e.almacen===!0,red_hacia:t,eventos:r,archivos:Uc.filter(a=>n.includes(a))}}function Qc(e,o){let t=o.lastIndexOf(".");if(t<1)return!1;let r=wo(o.slice(0,t));return!!r&&(e.modulos[r]??[]).includes(o.slice(t+1))}function Gc(e,o){let t={};if(e===void 0)return t;if(!ge(e)||Object.keys(e).length>20)throw i(`\xAB${o}\xBB: { campo: { tipo, desc } }, como mucho 20.`);for(let[r,n]of Object.entries(e)){if(re(r,o,Mo,"nombres de campo en min\xFAsculas y _"),!ge(n))throw i(`\xAB${o}.${r}\xBB: { tipo, desc }.`);xe(n,["tipo","desc","requerido"],`${o}.${r}`);let a=J(n.tipo,`${o}.${r}.tipo`,10);if(!["texto","numero","si_no","fecha"].includes(a))throw i(`\xAB${o}.${r}.tipo\xBB: texto, numero, si_no o fecha.`);t[r]={tipo:a,desc:J(n.desc,`${o}.${r}.desc`,200),requerido:n.requerido===!0}}return t}function tt(e,o={}){if(typeof e=="string"){if(e.length>tn)throw i("El manifiesto pasa de 256 KB.");try{e=JSON.parse(e)}catch{throw i("El manifiesto no es un JSON v\xE1lido.")}}else if(JSON.stringify(e??null).length>tn)throw i("El manifiesto pasa de 256 KB.");if(!ge(e))throw i("El manifiesto tiene que ser un objeto.");if(Li(e),e.formato!==ot)throw i(`No es una app (formato \xAB${ot}\xBB).`);if(xe(e,["$schema","formato","formato_version","id","nombre","descripcion","version","autor","icono","idiomas","compatible_crm","licencia","politica_datos","depende_de","ofrece","usa","solucion","montajes","funciones","servidor","herramientas_ia","ajustes","secretos","permisos"],"App"),!Number.isInteger(e.formato_version)||e.formato_version<1)throw i("\xABformato_version\xBB: un entero (1).");if(e.formato_version>an)throw i("La app es de una versi\xF3n del formato m\xE1s nueva que este CRM.");let t=re(e.id,"id",Ti,"dominio inverso en min\xFAsculas (\xABcom.tuempresa.mi-extension\xBB)");if(t.length>200)throw i("\xABid\xBB: como mucho 200 caracteres.");if(!o.firmada&&Ug(t))throw i("\xABid\xBB: los que empiezan por \xABcom.forgenex.\xBB o \xABforgenex.\xBB est\xE1n reservados a lo que publica ForgeNEX; usa el dominio de tu empresa (\xABcom.tuempresa.mi-extension\xBB).");let r=J(e.nombre,"nombre",80),n=re(e.version,"version",kg,"versi\xF3n semver (\xAB1.0.0\xBB)"),a;if(typeof e.autor=="string")a={nombre:J(e.autor,"autor",120)};else if(ge(e.autor))xe(e.autor,["nombre","web"],"Autor"),a={nombre:J(e.autor.nombre,"autor.nombre",120),...e.autor.web!==void 0?{web:Ii(e.autor.web,"autor.web")}:{}};else throw i("Falta \xABautor\xBB (un nombre, o { nombre, web }).");if(!o.firmada){if(zi(r))throw i("\xABnombre\xBB: \xABForgeNEX\xBB est\xE1 reservado a lo que publica ForgeNEX.");if(zi(a.nombre))throw i("\xABautor\xBB: \xABForgeNEX\xBB est\xE1 reservado a lo que publica ForgeNEX.")}let s=e.icono===void 0?"puzzle":re(e.icono,"icono",Jc,"un icono de lucide (\xABpuzzle\xBB)"),c=Ce(he(e.idiomas,"idiomas",30).map((N,k)=>re(N,`idiomas[${k}]`,Pg,"un c\xF3digo de idioma (\xABes\xBB, \xABen\xBB, \xABpt-BR\xBB)")),N=>N,"idiomas"),d=null;if(e.compatible_crm!==void 0){let k=J(e.compatible_crm,"compatible_crm",80).split(/\s+/);if(k.length>2||!k.every(x=>Vc.test(x)))throw i("\xABcompatible_crm\xBB: un rango (\xAB>=1.6.0-284\xBB, \xAB>=1.6.0-284 <2.0.0\xBB).");d=k.join(" ")}let u=e.licencia===void 0?null:J(e.licencia,"licencia",40),p=e.politica_datos===void 0?{}:{politica_datos:Ii(e.politica_datos,"politica_datos")},f=Ce(he(e.depende_de,"depende_de",20).map((N,k)=>{if(typeof N=="string")return{id:re(N,`depende_de[${k}]`,Ti,"el id de otra app"),version:null};if(!ge(N))throw i(`\xABdepende_de[${k}]\xBB: el id de otra app, o { id, version }.`);xe(N,["id","version"],`depende_de[${k}]`);let x=N.version===void 0?null:J(N.version,`depende_de[${k}].version`,80);if(x!==null&&!x.split(/\s+/).every(I=>Vc.test(I)))throw i(`\xABdepende_de[${k}].version\xBB: un rango (\xAB>=1.0.0\xBB).`);return{id:re(N.id,`depende_de[${k}].id`,Ti,"el id de otra app"),version:x}}),N=>N.id,"depende_de");if(f.some(N=>N.id===t))throw i("\xABdepende_de\xBB: una app no depende de s\xED misma.");let h=(N,k)=>Ce(he(N,k,20).map((x,I)=>re(x,`${k}[${I}]`,Tg,"un nombre de contrato (\xABtaller.citas\xBB)")),x=>x,k),b=h(e.ofrece,"ofrece"),v=h(e.usa,"usa"),w=e.solucion===void 0||e.solucion===null?null:re(e.solucion,"solucion",Mi,"el fichero de la soluci\xF3n dentro del paquete (\xABsolucion.json\xBB)");if(w!==null&&!w.endsWith(".json"))throw i("\xABsolucion\xBB: un fichero .json del paquete.");let g=Vg(e.permisos),y=Ce(he(e.montajes,"montajes",20).map((N,k)=>{let x=`montajes[${k}]`;if(!ge(N))throw i(`\xAB${x}\xBB: un objeto.`);xe(N,["id","punto","entrada","titulo","icono","modulo","permiso","funciones"],x);let I=J(N.punto,`${x}.punto`,20);if(!Rt.includes(I))throw i(`\xAB${x}.punto\xBB: ${Rt.join(", ")}.`);let z=null;if(fr.has(I)){if(z=wo(J(N.modulo,`${x}.modulo`,64)),!z)throw i(`\xAB${x}.modulo\xBB: el m\xF3dulo donde se cuelga.`);if(!(g.modulos[z]??[]).includes("ver"))throw i(`\xAB${x}\xBB: se cuelga de \xAB${N.modulo}\xBB, as\xED que \xABpermisos.modulos\xBB tiene que pedir verlo.`)}else if(N.modulo!==void 0)throw i(`\xAB${x}.modulo\xBB: solo en ${[...fr].join(", ")}.`);let U=N.permiso===void 0?null:J(N.permiso,`${x}.permiso`,80);if(U!==null&&!Qc(g,U))throw i(`\xAB${x}.permiso\xBB: \xAB${U}\xBB no est\xE1 en \xABpermisos.modulos\xBB.`);if(I==="publica"&&U!==null)throw i(`\xAB${x}.permiso\xBB: la p\xE1gina p\xFAblica no lleva permiso (la ve cualquiera con el enlace).`);let ee;if(I==="publica")ee=Ce(he(N.funciones,`${x}.funciones`,10).map((H,we)=>re(H,`${x}.funciones[${we}]`,Mo,"el nombre de una funci\xF3n")),H=>H,`${x}.funciones`);else if(N.funciones!==void 0)throw i(`\xAB${x}.funciones\xBB: solo en el montaje \xABpublica\xBB.`);return{id:re(N.id,`${x}.id`,/^[a-z][a-z0-9_-]{0,40}$/,"min\xFAsculas, n\xFAmeros, _ y -"),punto:I,entrada:re(N.entrada,`${x}.entrada`,Mi,"un fichero del paquete (\xABinterfaz/index.html\xBB)"),titulo:J(N.titulo,`${x}.titulo`,60),icono:N.icono===void 0?null:re(N.icono,`${x}.icono`,Jc,"un icono de lucide"),modulo:z,permiso:U,...ee?{funciones:ee}:{}}}),N=>N.id,"montajes");if(y.filter(N=>N.punto==="publica").length>1)throw i("\xABmontajes\xBB: una app tiene como mucho una p\xE1gina p\xFAblica.");let C=Ce(he(e.funciones,"funciones",20).map((N,k)=>{let x=`funciones[${k}]`;if(!ge(N))throw i(`\xAB${x}\xBB: un objeto.`);if(xe(N,["nombre","titulo","descripcion","entrada","disparador","tope","red","parametros","salida"],x),!ge(N.disparador))throw i(`\xAB${x}.disparador\xBB: { tipo, \u2026 }.`);xe(N.disparador,["tipo","evento","cron"],`${x}.disparador`);let I=J(N.disparador.tipo,`${x}.disparador.tipo`,20);if(!rn.includes(I))throw i(`\xAB${x}.disparador.tipo\xBB: ${rn.join(", ")}.`);let z={tipo:I};if(I==="evento"){let X=J(N.disparador.evento,`${x}.disparador.evento`,80);if(!g.eventos.includes(X))throw i(`\xAB${x}.disparador.evento\xBB: \xAB${X}\xBB tiene que estar en \xABpermisos.eventos\xBB.`);z.evento=X}if(I==="programada"){z.cron=re(N.disparador.cron,`${x}.disparador.cron`,Ig,"un cron de 5 campos (\xAB0 7 * * 1-5\xBB)");let X=Lc(z.cron);if(!X)throw i(`\xAB${x}.disparador.cron\xBB: un cron de 5 campos v\xE1lido (minuto 0-59, hora 0-23, d\xEDa 1-31, mes 1-12, semana 0-7).`);if(Dc(X)<D.cronMinutos)throw i(`\xAB${x}.disparador.cron\xBB: como mucho una vez cada ${D.cronMinutos} minutos.`)}let U=ge(N.tope)?N.tope:{};N.tope!==void 0&&xe(U,["ms","memoria_mb"],`${x}.tope`);let ee=U.ms===void 0?5e3:Number(U.ms),H=U.memoria_mb===void 0?64:Number(U.memoria_mb);if(!Number.isInteger(ee)||ee<D.ms.min||ee>D.ms.max)throw i(`\xAB${x}.tope.ms\xBB: de ${D.ms.min} a ${D.ms.max}.`);if(!Number.isInteger(H)||H<D.memoriaMb.min||H>D.memoriaMb.max)throw i(`\xAB${x}.tope.memoria_mb\xBB: de ${D.memoriaMb.min} a ${D.memoriaMb.max}.`);let we=he(N.red,`${x}.red`,10).map((X,qe)=>Zc(X,`${x}.red[${qe}]`,"un dominio"));for(let X of we)if(!Jg(g.red_hacia,X))throw i(`\xAB${x}.red\xBB: \xAB${X}\xBB tiene que estar en \xABpermisos.red_hacia\xBB.`);let oo=Gc(N.parametros,`${x}.parametros`),Po={},et=Ce(he(N.salida,`${x}.salida`,30).map((X,qe)=>{let Re=`${x}.salida[${qe}]`;if(!ge(X))return re(X,Re,Mo,"nombres en min\xFAsculas y _ (o { clave, titulo })");xe(X,["clave","titulo"],Re);let q=re(X.clave,`${Re}.clave`,Mo,"nombres en min\xFAsculas y _");return X.titulo!==void 0&&(Po[q]=J(X.titulo,`${Re}.titulo`,60)),q}),X=>X,`${x}.salida`);if(I==="publica"&&we.length)throw i(`\xAB${x}.red\xBB: una funci\xF3n \xABpublica\xBB no sale a la red (solo lee el CRM).`);if(Object.keys(oo).length&&I!=="automatizacion")throw i(`\xAB${x}.parametros\xBB: solo en las de disparador \xABautomatizacion\xBB (las dem\xE1s reciben su evento, su minuto o su webhook).`);return{nombre:re(N.nombre,`${x}.nombre`,Mo,"min\xFAsculas, n\xFAmeros y _"),titulo:N.titulo===void 0?null:J(N.titulo,`${x}.titulo`,80),descripcion:N.descripcion===void 0?null:J(N.descripcion,`${x}.descripcion`,300,!1),entrada:re(N.entrada,`${x}.entrada`,Mi,"un fichero del paquete (\xABfunciones/calcular.js\xBB)"),disparador:z,tope:{ms:ee,memoria_mb:H},red:we,parametros:oo,salida:et,titulos_salida:Po}}),N=>N.nombre,"funciones"),O=null;if(e.servidor!==void 0&&e.servidor!==null){if(!ge(e.servidor))throw i("\xABservidor\xBB: { url, webhooks }.");xe(e.servidor,["url","webhooks"],"Servidor");let N=Ce(he(e.servidor.webhooks,"servidor.webhooks",40).map((k,x)=>{if(typeof k!="string"||!g.eventos.includes(k))throw i(`\xABservidor.webhooks[${x}]\xBB: un evento que est\xE9 en \xABpermisos.eventos\xBB.`);return k}),k=>k,"servidor.webhooks");O={url:Ii(e.servidor.url,"servidor.url"),webhooks:N}}let M=new Set(C.map(N=>N.nombre));for(let N of y)for(let[k,x]of(N.funciones??[]).entries()){let I=C.find(z=>z.nombre===x);if(!I)throw i(`\xABmontajes\xBB.\xAB${N.id}\xBB.funciones[${k}]: \xAB${x}\xBB tiene que estar en \xABfunciones\xBB.`);if(I.disparador.tipo!=="publica")throw i(`\xABmontajes\xBB.\xAB${N.id}\xBB.funciones[${k}]: \xAB${x}\xBB tiene que ser de disparador \xABpublica\xBB.`)}let Z=Ce(he(e.herramientas_ia,"herramientas_ia",20).map((N,k)=>{let x=`herramientas_ia[${k}]`;if(!ge(N))throw i(`\xAB${x}\xBB: un objeto.`);xe(N,["nombre","descripcion","entrada","salida","riesgo","funcion","escribe","permiso"],x);let I=Gc(N.entrada,`${x}.entrada`),z=J(N.riesgo,`${x}.riesgo`,10);if(!["bajo","medio","alto"].includes(z))throw i(`\xAB${x}.riesgo\xBB: bajo, medio o alto.`);let U=J(N.funcion,`${x}.funcion`,41);if(!M.has(U))throw i(`\xAB${x}.funcion\xBB: \xAB${U}\xBB tiene que estar en \xABfunciones\xBB.`);if(!["herramienta","calculo"].includes(C.find(H=>H.nombre===U)?.disparador.tipo??""))throw i(`\xAB${x}.funcion\xBB: \xAB${U}\xBB tiene que ser de disparador \xABherramienta\xBB (o \xABcalculo\xBB).`);if(N.escribe!==void 0&&typeof N.escribe!="boolean")throw i(`\xAB${x}.escribe\xBB: true o false.`);let ee=null;if(N.permiso!==void 0){let H=J(N.permiso,`${x}.permiso`,80),we=H.lastIndexOf("."),oo=we>0?wo(H.slice(0,we)):null;if(!oo||!Qc(g,H))throw i(`\xAB${x}.permiso\xBB: \xAB${H}\xBB no est\xE1 en \xABpermisos.modulos\xBB.`);ee=`${oo}.${H.slice(we+1)}`}return{nombre:re(N.nombre,`${x}.nombre`,/^[a-z][a-z0-9_]{2,40}$/,"min\xFAsculas, n\xFAmeros y _ (3 a 41)"),descripcion:J(N.descripcion,`${x}.descripcion`,500),entrada:I,salida:Ce(he(N.salida,`${x}.salida`,30).map((H,we)=>re(H,`${x}.salida[${we}]`,Mo,"nombres de campo")),H=>H,`${x}.salida`),riesgo:z,funcion:U,escribe:N.escribe===!0,permiso:ee}}),N=>N.nombre,"herramientas_ia"),$=Ce(he(e.ajustes,"ajustes",40).map((N,k)=>{let x=`ajustes[${k}]`;if(!ge(N))throw i(`\xAB${x}\xBB: un objeto.`);xe(N,["clave","etiqueta","tipo","opciones","requerido"],x);let I=J(N.tipo,`${x}.tipo`,10);if(!nn.includes(I))throw i(`\xAB${x}.tipo\xBB: ${nn.join(", ")}.`);let z=he(N.opciones,`${x}.opciones`,50).map((U,ee)=>{if(!ge(U))throw i(`\xAB${x}.opciones[${ee}]\xBB: { valor, etiqueta }.`);return xe(U,["valor","etiqueta"],`${x}.opciones[${ee}]`),{valor:J(U.valor,`${x}.opciones[${ee}].valor`,60),etiqueta:J(U.etiqueta,`${x}.opciones[${ee}].etiqueta`,80)}});if(I==="opcion"&&!z.length)throw i(`\xAB${x}.opciones\xBB: un ajuste de tipo opci\xF3n necesita sus opciones.`);if(I!=="opcion"&&z.length)throw i(`\xAB${x}.opciones\xBB: solo en los de tipo opci\xF3n.`);return{clave:re(N.clave,`${x}.clave`,Mo,"min\xFAsculas, n\xFAmeros y _"),etiqueta:J(N.etiqueta,`${x}.etiqueta`,80),tipo:I,opciones:Ce(z,U=>U.valor,`${x}.opciones`),requerido:N.requerido===!0}}),N=>N.clave,"ajustes"),A=Ce(he(e.secretos,"secretos",10).map((N,k)=>{let x=`secretos[${k}]`;if(!ge(N))throw i(`\xAB${x}\xBB: un objeto.`);return xe(N,["clave","etiqueta","descripcion"],x),{clave:re(N.clave,`${x}.clave`,Mo,"min\xFAsculas, n\xFAmeros y _"),etiqueta:J(N.etiqueta,`${x}.etiqueta`,80),descripcion:J(N.descripcion,`${x}.descripcion`,300,!1)}}),N=>N.clave,"secretos");return{formato:ot,formato_version:e.formato_version,id:t,nombre:r,descripcion:J(e.descripcion,"descripcion",500,!1),version:n,autor:a,icono:s,idiomas:c,compatible_crm:d,licencia:u,...p,depende_de:f,ofrece:b,usa:v,solucion:w,montajes:y,funciones:C,servidor:O,herramientas_ia:Z,ajustes:$,secretos:A,permisos:g}}var ot,an,tn,Io,mr,Rt,sn,fr,rn,nn,Uc,Rg,Ti,kg,Vc,Jc,Pg,Tg,Mo,Mg,Mi,Hc,Ig,ge,Xc,Lg,Ky,Dg,Yc,Kc,Fg,Wg,Di,zi,Jg,kt=m(()=>{R();Ic();zc();pr();Bc();ot="forgenex.extension",an=1,tn=256e3,Io={contactos:{nombre:"Personas",ops:["ver","crear","editar","borrar"]},empresas:{nombre:"Empresas",ops:["ver","crear","editar","borrar"]},oportunidades:{nombre:"Oportunidades",ops:["ver","crear","editar","borrar"]},tareas:{nombre:"Tareas",ops:["ver","crear","editar","borrar"]},notas:{nombre:"Notas",ops:["ver","editar"]}},mr=["ver","crear","editar","borrar"],Rt=["pagina","ficha_pestana","ficha_bloque","inicio_bloque","accion_ficha","accion_tabla","vista","ajustes","publica"],sn=new Set(["pagina","ficha_pestana","ficha_bloque","inicio_bloque","accion_ficha","accion_tabla","vista","ajustes","publica"]),fr=new Set(["ficha_pestana","ficha_bloque","accion_ficha","accion_tabla","vista"]),rn=["evento","programada","webhook","automatizacion","calculo","herramienta","publica"],nn=["texto","numero","si_no","opcion","modulo","campo"],Uc=["leer","escribir"],Rg=new Set(["__proto__","constructor","prototype"]),Ti=/^[a-z][a-z0-9-]{0,62}(\.[a-z0-9][a-z0-9-]{0,62}){1,6}$/,kg=/^(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})(-[0-9a-z.-]{1,30})?$/,Vc=/^(>=|<=|>|<|=|\^|~)?(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})(-[0-9a-z.-]{1,30})?$/,Jc=/^[a-z0-9-]{1,40}$/,Pg=/^[a-z]{2,3}(-[A-Z]{2})?$/,Tg=/^[a-z][a-z0-9_.-]{0,79}$/,Mo=/^[a-z][a-z0-9_]{0,40}$/,Mg=/^[a-z][a-z0-9_]{0,59}$/,Mi=/^(?!\/)(?!.*\/\/)(?!.*(^|\/)\.\.?(\/|$))[A-Za-z0-9_.\/-]{1,200}$/,Hc=/^(\*\.)?([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/,Ig=/^[0-9*,\/-]+( [0-9*,\/-]+){4}$/,ge=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);Xc=String.raw`[\p{Cc}\p{Cf}\u2028\u2029\u034F\u115F\u1160\u2800\u3164\uFFA0]|(?<!\p{Emoji})[\uFE00-\uFE0F]|(?<=[0-9#*])[\uFE00-\uFE0F](?!\u20E3)`,Lg=new RegExp(Xc,"u"),Ky=new RegExp(Xc,"gu"),Dg=new RegExp("(?<=\\p{Extended_Pictographic}[\\uFE0F\\p{Emoji_Modifier}]?)\\u200D(?=\\p{Extended_Pictographic})","gu");Yc={\u0391:"a",\u0392:"b",\u0395:"e",\u0396:"z",\u0397:"h",\u0399:"i",\u039A:"k",\u039C:"m",\u039D:"n",\u039F:"o",\u03A1:"p",\u03A4:"t",\u03A5:"y",\u03A7:"x",\u0410:"a",\u0412:"b",\u0415:"e",\u0405:"s",\u0406:"i",\u0408:"j",\u041A:"k",\u041C:"m",\u041D:"h",\u041E:"o",\u0420:"p",\u0421:"c",\u0422:"t",\u0425:"x",\u04AE:"y","\u050C":"g","\u051A":"q","\u051C":"w"},Kc={\u03B1:"a",\u03B2:"b",\u03B3:"y",\u03B5:"e",\u03B7:"n",\u03B9:"i",\u03BA:"k",\u03BD:"v",\u03BF:"o",\u03C1:"p",\u03C4:"t",\u03C5:"u",\u03C7:"x",\u03C9:"w",\u0430:"a",\u0435:"e",\u0451:"e",\u043E:"o",\u0440:"p",\u0441:"c",\u0443:"y",\u0445:"x",\u0455:"s",\u0456:"i",\u0457:"i",\u0458:"j","\u0501":"d",\u04BB:"h","\u04CF":"l","\u051B":"q","\u051D":"w",\u0261:"g",\u0433:"r",\u043F:"n",\u049D:"k",\u043A:"k",\u0131:"i","\u0237":"j",0:"o","\u1D00":"a",\u0299:"b","\u1D04":"c","\u1D05":"d","\u1D07":"e","\uA730":"f",\u0262:"g",\u029C:"h",\u026A:"i","\u1D0A":"j","\u1D0B":"k",\u029F:"l","\u1D0D":"m",\u0274:"n","\u1D0F":"o","\u1D18":"p",\u0280:"r","\uA731":"s","\u1D1B":"t","\u1D1C":"u","\u1D20":"v","\u1D21":"w",\u028F:"y","\u1D22":"z",\u0585:"o","\uA4EE":"a","\uA4D0":"b","\uA4DA":"c","\uA4D3":"d","\uA4F0":"e","\uA4DD":"f","\uA4D6":"g","\uA4E7":"h","\uA4F2":"i","\uA4D9":"j","\uA4D7":"k","\uA4E1":"l","\uA4DF":"m","\uA4E0":"n","\uA4F3":"o","\uA4D1":"p","\uA4E3":"r","\uA4E2":"s","\uA4D4":"t","\uA4F4":"u","\uA4E6":"v","\uA4EA":"w","\uA4EB":"x","\uA4EC":"y","\uA4DC":"z"},Fg=new RegExp(`[${Object.keys(Yc).join("")}]`,"gu"),Wg=new RegExp(`[${Object.keys(Kc).join("")}]`,"gu"),Di=e=>e.normalize("NFKC").replace(Fg,o=>Yc[o]).toLowerCase().normalize("NFD").replace(new RegExp("\\p{M}","gu"),"").replace(Wg,o=>Kc[o]).replace(/[^\p{L}\p{N}]/gu,"");zi=e=>{let o=Bg(e);for(let t=0;t<o.length;t++){let r="";for(let n=t;n<o.length&&r.length<8;n++)if(r+=o[n],r==="forgenex")return!0}return!1};Jg=(e,o)=>e.some(t=>t===o||t.startsWith("*.")&&o.endsWith(t.slice(1)))});function vo(e){return typeof e>"u"||e===void 0}function B(e){return typeof e=="string"}function ro(e){return typeof e=="number"}function rt(e){return typeof e=="boolean"}function nt(e){return e===null}function Fi(e){return e instanceof Date}function it(e){return typeof e=="bigint"}function el(e){return typeof Buffer<"u"&&Buffer.isBuffer(e)}function ye(e){return typeof e=="function"}function je(e){return typeof e=="object"&&e!==null}function l(e){return Object.freeze(e)}function hr(e){return ke(e)?e:[e]}function ke(e){return Array.isArray(e)}function ol(e){return e instanceof Error?e.message:String(e)}var _=m(()=>{});var t_,tl=m(()=>{_();t_=l({is(e){return e.kind==="AlterTableNode"},create(e){return l({kind:"AlterTableNode",table:e})},cloneWithTableProps(e,o){return l({...e,...o})},cloneWithColumnAlteration(e,o){return l({...e,columnAlterations:e.columnAlterations?[...e.columnAlterations,o]:[o]})}})});var P,ne=m(()=>{_();P=l({is(e){return e.kind==="IdentifierNode"},create(e){return l({kind:"IdentifierNode",name:e})}})});var c_,rl=m(()=>{_();ne();c_=l({is(e){return e.kind==="CreateIndexNode"},create(e){return l({kind:"CreateIndexNode",name:P.create(e)})},cloneWith(e,o){return l({...e,...o})},cloneWithColumns(e,o){return l({...e,columns:[...e.columns||[],...o]})}})});var p_,nl=m(()=>{_();ne();p_=l({is(e){return e.kind==="CreateSchemaNode"},create(e,o){return l({kind:"CreateSchemaNode",schema:P.create(e),...o})},cloneWith(e,o){return l({...e,...o})}})});var h_,il=m(()=>{_();h_=l({is(e){return e.kind==="CreateTableNode"},create(e){return l({kind:"CreateTableNode",table:e,columns:l([])})},cloneWithColumn(e,o){return l({...e,columns:l([...e.columns,o])})},cloneWithConstraint(e,o){return l({...e,constraints:e.constraints?l([...e.constraints,o]):l([o])})},cloneWithIndex(e,o){return l({...e,indexes:e.indexes?l([...e.indexes,o]):l([o])})},cloneWithFrontModifier(e,o){return l({...e,frontModifiers:e.frontModifiers?l([...e.frontModifiers,o]):l([o])})},cloneWithEndModifier(e,o){return l({...e,endModifiers:e.endModifiers?l([...e.endModifiers,o]):l([o])})},cloneWith(e,o){return l({...e,...o})}})});var Ve,at=m(()=>{_();ne();Ve=l({is(e){return e.kind==="SchemableIdentifierNode"},create(e){return l({kind:"SchemableIdentifierNode",identifier:P.create(e)})},createWithSchema(e,o){return l({kind:"SchemableIdentifierNode",schema:P.create(e),identifier:P.create(o)})}})});var N_,al=m(()=>{_();at();N_=l({is(e){return e.kind==="DropIndexNode"},create(e,o){return l({kind:"DropIndexNode",name:Ve.create(e),...o})},cloneWith(e,o){return l({...e,...o})}})});var j_,sl=m(()=>{_();ne();j_=l({is(e){return e.kind==="DropSchemaNode"},create(e,o){return l({kind:"DropSchemaNode",schema:P.create(e),...o})},cloneWith(e,o){return l({...e,...o})}})});var A_,cl=m(()=>{_();A_=l({is(e){return e.kind==="DropTableNode"},create(e,o){return l({kind:"DropTableNode",table:e,...o})},cloneWith(e,o){return l({...e,...o})}})});var Pe,yo=m(()=>{_();Pe=l({is(e){return e.kind==="AliasNode"},create(e,o){return l({kind:"AliasNode",node:e,alias:o})}})});var Lo,gr=m(()=>{_();at();Lo=l({is(e){return e.kind==="TableNode"},create(e){return l({kind:"TableNode",table:Ve.create(e)})},createWithSchema(e,o){return l({kind:"TableNode",table:Ve.createWithSchema(e,o)})}})});function ie(e){return je(e)&&ye(e.toOperationNode)}var ze=m(()=>{_()});function cn(e){return je(e)&&"expressionType"in e&&ie(e)}function ll(e){return je(e)&&"expression"in e&&B(e.alias)&&ie(e)}var ln=m(()=>{ze();_()});var no,Wi=m(()=>{_();no=l({is(e){return e.kind==="SelectModifierNode"},create(e,o){return l({kind:"SelectModifierNode",modifier:e,of:o})},createWithExpression(e){return l({kind:"SelectModifierNode",rawModifier:e})}})});var Te,Do=m(()=>{_();Te=l({is(e){return e.kind==="AndNode"},create(e,o){return l({kind:"AndNode",left:e,right:o})}})});var Je,st=m(()=>{_();Je=l({is(e){return e.kind==="OrNode"},create(e,o){return l({kind:"OrNode",left:e,right:o})}})});var un,Bi=m(()=>{_();Do();st();un=l({is(e){return e.kind==="OnNode"},create(e){return l({kind:"OnNode",on:e})},cloneWithOperation(e,o,t){return l({...e,on:o==="And"?Te.create(e.on,t):Je.create(e.on,t)})}})});var _o,br=m(()=>{_();Bi();_o=l({is(e){return e.kind==="JoinNode"},create(e,o){return l({kind:"JoinNode",joinType:e,table:o,on:void 0})},createWithOn(e,o,t){return l({kind:"JoinNode",joinType:e,table:o,on:un.create(t)})},cloneWithOn(e,o){return l({...e,on:e.on?un.cloneWithOperation(e.on,"And",o):un.create(o)})}})});var zo,dn=m(()=>{_();zo=l({is(e){return e.kind==="BinaryOperationNode"},create(e,o,t){return l({kind:"BinaryOperationNode",leftOperand:e,operator:o,rightOperand:t})}})});function gl(e){return B(e)&&ml[e]}function bl(e){return B(e)&&pl[e]}function wl(e){return B(e)&&hl[e]}var ul,rN,dl,nN,pl,Qg,ml,Gg,fl,iN,hl,Hg,aN,Qe,Pt=m(()=>{_();ul=l({"=":!0,"==":!0,"!=":!0,"<>":!0,">":!0,">=":!0,"<":!0,"<=":!0,in:!0,"not in":!0,is:!0,"is not":!0,like:!0,"not like":!0,match:!0,ilike:!0,"not ilike":!0,"@>":!0,"<@":!0,"^@":!0,"&&":!0,"?":!0,"?&":!0,"?|":!0,"!<":!0,"!>":!0,"<=>":!0,"!~":!0,"~":!0,"~*":!0,"!~*":!0,"@@":!0,"@@@":!0,"!!":!0,"<->":!0,regexp:!0,"is distinct from":!0,"is not distinct from":!0}),rN=Object.keys(ul),dl=l({"+":!0,"-":!0,"*":!0,"/":!0,"%":!0,"^":!0,"&":!0,"|":!0,"#":!0,"<<":!0,">>":!0}),nN=Object.keys(dl),pl=l({"->":!0,"->>":!0}),Qg=Object.keys(pl),ml=l({...ul,...dl,"||":!0}),Gg=Object.keys(ml),fl=l({exists:!0,"not exists":!0}),iN=Object.keys(fl),hl=l({...fl,"-":!0,not:!0}),Hg=Object.keys(hl),aN=[...Gg,...Qg,...Hg,"between","between symmetric"],Qe=l({is(e){return e.kind==="OperatorNode"},create(e){return l({kind:"OperatorNode",operator:e})}})});var ce,Ge=m(()=>{_();ne();ce=l({is(e){return e.kind==="ColumnNode"},create(e){return l({kind:"ColumnNode",column:P.create(e)})}})});var pn,mn=m(()=>{_();pn=l({is(e){return e.kind==="SelectAllNode"},create(){return l({kind:"SelectAllNode"})}})});var Tt,fn=m(()=>{mn();_();Tt=l({is(e){return e.kind==="ReferenceNode"},create(e,o){return l({kind:"ReferenceNode",table:o,column:e})},createSelectAll(e){return l({kind:"ReferenceNode",table:e,column:pn.create()})}})});function hn(e){return je(e)&&ie(e)&&B(e.dynamicReference)}var gn=m(()=>{ze();_()});var He,bn=m(()=>{_();He=l({is(e){return e.kind==="OrderByItemNode"},create(e,o){return l({kind:"OrderByItemNode",orderBy:e,direction:o})},cloneWith(e,o){return l({...e,...o})}})});var le,ct=m(()=>{_();le=l({is(e){return e.kind==="RawNode"},create(e,o){return l({kind:"RawNode",sqlFragments:l(e),parameters:l(o)})},createWithSql(e){return le.create([e],[])},createWithChild(e){return le.create(["",""],[e])},createWithChildren(e){return le.create(new Array(e.length+1).fill(""),e)}})});var vl,Ui=m(()=>{_();ne();vl=l({is(e){return e.kind==="CollateNode"},create(e){return l({kind:"CollateNode",collation:P.create(e)})}})});var wn,Vi=m(()=>{Ui();bn();ct();_();wn=class e{#e;constructor(o){this.#e=l(o)}desc(){return new e({node:He.cloneWith(this.#e.node,{direction:le.createWithSql("desc")})})}asc(){return new e({node:He.cloneWith(this.#e.node,{direction:le.createWithSql("asc")})})}nullsLast(){return new e({node:He.cloneWith(this.#e.node,{nulls:"last"})})}nullsFirst(){return new e({node:He.cloneWith(this.#e.node,{nulls:"first"})})}collate(o){return new e({node:He.cloneWith(this.#e.node,{collation:vl.create(o)})})}toOperationNode(){return this.#e.node}}});function Mt(e){yl.has(e)||(yl.add(e),console.log(e))}var yl,Ji=m(()=>{yl=new Set});function Xg(e){return e==="asc"||e==="desc"}function Xe(e){if(e.length===2)return[Qi(e[0],e[1])];if(e.length===1){let[o]=e;return Array.isArray(o)?(Mt("orderBy(array) is deprecated, use multiple orderBy calls instead."),o.map(t=>Qi(t))):[Qi(o)]}throw new Error(`Invalid number of arguments at order by! expected 1-2, received ${e.length}`)}function Qi(e,o){let t=Yg(e);if(He.is(t)){if(o)throw new Error("Cannot specify direction twice!");return t}return _l(t,o)}function Yg(e){if(lt(e))return Fo(e);if(hn(e))return e.toOperationNode();let[o,t]=e.split(" ");return t?(Mt("`orderBy('column asc')` is deprecated. Use `orderBy('column', 'asc')` instead."),_l(Fe(o),t)):Fe(e)}function _l(e,o){if(typeof o=="string"){if(!Xg(o))throw new Error(`Invalid order by direction: ${o}`);return He.create(e,le.createWithSql(o))}if(cn(o))return Mt("`orderBy(..., expr)` is deprecated. Use `orderBy(..., 'asc')` or `orderBy(..., (ob) => ...)` instead."),He.create(e,o.toOperationNode());let t=He.create(e);return o?o(new wn({node:t})).toOperationNode():t}var It=m(()=>{gn();ln();bn();ct();Vi();Ji();ut();Me()});var Lt,vn=m(()=>{_();Lt=l({is(e){return e.kind==="JSONReferenceNode"},create(e,o){return l({kind:"JSONReferenceNode",reference:e,traversal:o})},cloneWithTraversal(e,o){return l({...e,traversal:o})}})});var yn,_n=m(()=>{_();yn=l({is(e){return e.kind==="JSONOperatorChainNode"},create(e){return l({kind:"JSONOperatorChainNode",operator:e,values:l([])})},cloneWithValue(e,o){return l({...e,values:l([...e.values,o])})}})});var Wo,wr=m(()=>{_();Wo=l({is(e){return e.kind==="JSONPathNode"},create(e){return l({kind:"JSONPathNode",inOperator:e,pathLegs:l([])})},cloneWithLeg(e,o){return l({...e,pathLegs:l([...e.pathLegs,o])})}})});function Kg(e){return B(e)?Fe(e):e.toOperationNode()}function No(e){return ke(e)?e.map(o=>de(o)):[de(e)]}function de(e){return lt(e)?Fo(e):Kg(e)}function Nl(e,o){if(bl(o))return Lt.create(Fe(e),yn.create(Qe.create(o)));if(o==="->$"||o==="->>$")return Lt.create(Fe(e),Wo.create(Qe.create(o.slice(0,-1))));throw new Error(`Invalid JSON operator: ${o}`)}function Fe(e){if(!e.includes("."))return Tt.create(ce.create(e));let t=e.split(".").map(xl);if(t.length===3)return Zg(t);if(t.length===2)return eb(t);throw new Error(`invalid column reference ${e}`)}function $l(e){let o=" as ";if(e.includes(o)){let[t,r]=e.split(o).map(xl);return Pe.create(Fe(t),P.create(r))}else return Fe(e)}function Zg(e){let[o,t,r]=e;return Tt.create(ce.create(r),Lo.createWithSchema(o,t))}function eb(e){let[o,t]=e;return Tt.create(ce.create(t),Lo.create(o))}function xl(e){return e.trim()}var Me=m(()=>{yo();Ge();fn();gr();_();ut();ne();Pt();vn();_n();wr()});var Cl,Gi=m(()=>{_();Cl=l({is(e){return e.kind==="PrimitiveValueListNode"},create(e){return l({kind:"PrimitiveValueListNode",values:l([...e])})}})});var Nn,$n=m(()=>{_();Nn=l({is(e){return e.kind==="ValueListNode"},create(e){return l({kind:"ValueListNode",values:l(e)})}})});var Oe,Bo=m(()=>{_();Oe=l({is(e){return e.kind==="ValueNode"},create(e){return l({kind:"ValueNode",value:e})},createImmediate(e){return l({kind:"ValueNode",value:e,immediate:!0})}})});function jl(e){return ke(e)?ob(e):G(e)}function G(e){return lt(e)?Fo(e):Oe.create(e)}function xn(e){return ro(e)||rt(e)||nt(e)}function vr(e){if(!xn(e))throw new Error(`unsafe immediate value ${JSON.stringify(e)}`);return Oe.createImmediate(e)}function ob(e){return e.some(lt)?Nn.create(e.map(o=>G(o))):Cl.create(e)}var $o=m(()=>{Gi();$n();Bo();_();ut()});var Uo,yr=m(()=>{_();Uo=l({is(e){return e.kind==="ParensNode"},create(e){return l({kind:"ParensNode",node:e})}})});function ue(e){if(e.length===3)return Cn(e[0],e[1],e[2]);if(e.length===1)return G(e[0]);throw new Error(`invalid arguments: ${JSON.stringify(e)}`)}function Cn(e,o,t){return tb(o)&&Sl(t)?zo.create(de(e),Hi(o),Oe.createImmediate(t)):zo.create(de(e),Hi(o),jl(t))}function _e(e,o,t){return zo.create(de(e),Hi(o),de(t))}function Xi(e,o){return jn(Object.entries(e).filter(([,t])=>!vo(t)).map(([t,r])=>Cn(t,Sl(r)?"is":"=",r)),o)}function jn(e,o,t=!0){let r=o==="and"?Te.create:Je.create;if(e.length===0)return zo.create(Oe.createImmediate(1),Qe.create("="),Oe.createImmediate(o==="and"?1:0));let n=Ol(e[0]);for(let a=1;a<e.length;++a)n=r(n,Ol(e[a]));return e.length>1&&t?Uo.create(n):n}function tb(e){return e==="is"||e==="is not"}function Sl(e){return nt(e)||rt(e)}function Hi(e){if(gl(e))return Qe.create(e);if(ie(e))return e.toOperationNode();throw new Error(`invalid operator ${JSON.stringify(e)}`)}function Ol(e){return ie(e)?e.toOperationNode():e}var io=m(()=>{dn();_();ze();Pt();Me();$o();Bo();Do();yr();st()});var xo,_r=m(()=>{_();xo=l({is(e){return e.kind==="OrderByNode"},create(e){return l({kind:"OrderByNode",items:l([...e])})},cloneWithItems(e,o){return l({...e,items:l([...e.items,...o])})}})});var Yi,Ki=m(()=>{_();Yi=l({is(e){return e.kind==="PartitionByNode"},create(e){return l({kind:"PartitionByNode",items:l(e)})},cloneWithItems(e,o){return l({...e,items:l([...e.items,...o])})}})});var Nr,On=m(()=>{_();_r();Ki();Nr=l({is(e){return e.kind==="OverNode"},create(){return l({kind:"OverNode"})},cloneWithOrderByItems(e,o){return l({...e,orderBy:e.orderBy?xo.cloneWithItems(e.orderBy,o):xo.create(o)})},cloneWithPartitionByItems(e,o){return l({...e,partitionBy:e.partitionBy?Yi.cloneWithItems(e.partitionBy,o):Yi.create(o)})}})});var dt,$r=m(()=>{_();dt=l({is(e){return e.kind==="FromNode"},create(e){return l({kind:"FromNode",froms:l(e)})},cloneWithFroms(e,o){return l({...e,froms:l([...e.froms,...o])})}})});var Zi,ea=m(()=>{_();Zi=l({is(e){return e.kind==="GroupByNode"},create(e){return l({kind:"GroupByNode",items:l(e)})},cloneWithItems(e,o){return l({...e,items:l([...e.items,...o])})}})});var oa,ta=m(()=>{_();Do();st();oa=l({is(e){return e.kind==="HavingNode"},create(e){return l({kind:"HavingNode",having:e})},cloneWithOperation(e,o,t){return l({...e,having:o==="And"?Te.create(e.having,t):Je.create(e.having,t)})}})});var Al,ra=m(()=>{_();Al=l({is(e){return e.kind==="InsertQueryNode"},create(e,o,t){return l({kind:"InsertQueryNode",into:e,...o&&{with:o},replace:t})},createWithoutInto(){return l({kind:"InsertQueryNode"})},cloneWith(e,o){return l({...e,...o})}})});var El,na=m(()=>{_();El=l({is(e){return e.kind==="ListNode"},create(e){return l({kind:"ListNode",items:l(e)})}})});var Dt,Sn=m(()=>{_();$r();na();Dt=l({is(e){return e.kind==="UpdateQueryNode"},create(e,o){return l({kind:"UpdateQueryNode",table:e.length===1?e[0]:El.create(e),...o&&{with:o}})},createWithoutTable(){return l({kind:"UpdateQueryNode"})},cloneWithFromItems(e,o){return l({...e,from:e.from?dt.cloneWithFroms(e.from,o):dt.create(o)})},cloneWithUpdates(e,o){return l({...e,updates:e.updates?l([...e.updates,...o]):o})},cloneWithLimit(e,o){return l({...e,limit:o})}})});var ia,aa=m(()=>{_();ia=l({is(e){return e.kind==="UsingNode"},create(e){return l({kind:"UsingNode",tables:l(e)})},cloneWithTables(e,o){return l({...e,tables:l([...e.tables,...o])})}})});var zt,An=m(()=>{_();$r();aa();Co();zt=l({is(e){return e.kind==="DeleteQueryNode"},create(e,o){return l({kind:"DeleteQueryNode",from:dt.create(e),...o&&{with:o}})},cloneWithOrderByItems:(e,o)=>E.cloneWithOrderByItems(e,o),cloneWithoutOrderBy:e=>E.cloneWithoutOrderBy(e),cloneWithLimit(e,o){return l({...e,limit:o})},cloneWithoutLimit(e){return l({...e,limit:void 0})},cloneWithUsing(e,o){return l({...e,using:e.using!==void 0?ia.cloneWithTables(e.using,o):ia.create(o)})}})});var ve,xr=m(()=>{_();Do();st();ve=l({is(e){return e.kind==="WhereNode"},create(e){return l({kind:"WhereNode",where:e})},cloneWithOperation(e,o,t){return l({...e,where:o==="And"?Te.create(e.where,t):Je.create(e.where,t)})}})});var sa,ca=m(()=>{_();sa=l({is(e){return e.kind==="ReturningNode"},create(e){return l({kind:"ReturningNode",selections:l(e)})},cloneWithSelections(e,o){return l({...e,selections:e.selections?l([...e.selections,...o]):l(o)})}})});var ql,la=m(()=>{_();ql=l({is(e){return e.kind==="ExplainNode"},create(e,o){return l({kind:"ExplainNode",format:e,options:o})}})});var jo,Cr=m(()=>{_();jo=l({is(e){return e.kind==="WhenNode"},create(e){return l({kind:"WhenNode",condition:e})},cloneWithResult(e,o){return l({...e,result:o})}})});var Rl,ua=m(()=>{_();Cr();Rl=l({is(e){return e.kind==="MergeQueryNode"},create(e,o){return l({kind:"MergeQueryNode",into:e,...o&&{with:o}})},cloneWithUsing(e,o){return l({...e,using:o})},cloneWithWhen(e,o){return l({...e,whens:e.whens?l([...e.whens,o]):l([o])})},cloneWithThen(e,o){return l({...e,whens:e.whens?l([...e.whens.slice(0,-1),jo.cloneWithResult(e.whens[e.whens.length-1],o)]):void 0})}})});var da,pa=m(()=>{_();da=l({is(e){return e.kind==="OutputNode"},create(e){return l({kind:"OutputNode",selections:l(e)})},cloneWithSelections(e,o){return l({...e,selections:e.selections?l([...e.selections,...o]):l(o)})}})});var E,Co=m(()=>{ra();jr();Sn();An();xr();_();ca();la();ua();pa();_r();E=l({is(e){return Y.is(e)||Al.is(e)||Dt.is(e)||zt.is(e)||Rl.is(e)},cloneWithEndModifier(e,o){return l({...e,endModifiers:e.endModifiers?l([...e.endModifiers,o]):l([o])})},cloneWithWhere(e,o){return l({...e,where:e.where?ve.cloneWithOperation(e.where,"And",o):ve.create(o)})},cloneWithJoin(e,o){return l({...e,joins:e.joins?l([...e.joins,o]):l([o])})},cloneWithReturning(e,o){return l({...e,returning:e.returning?sa.cloneWithSelections(e.returning,o):sa.create(o)})},cloneWithoutReturning(e){return l({...e,returning:void 0})},cloneWithoutWhere(e){return l({...e,where:void 0})},cloneWithExplain(e,o,t){return l({...e,explain:ql.create(o,t?.toOperationNode())})},cloneWithTop(e,o){return l({...e,top:o})},cloneWithOutput(e,o){return l({...e,output:e.output?da.cloneWithSelections(e.output,o):da.create(o)})},cloneWithOrderByItems(e,o){return l({...e,orderBy:e.orderBy?xo.cloneWithItems(e.orderBy,o):xo.create(o)})},cloneWithoutOrderBy(e){return l({...e,orderBy:void 0})}})});var Y,jr=m(()=>{_();$r();ea();ta();Co();Y=l({is(e){return e.kind==="SelectQueryNode"},create(e){return l({kind:"SelectQueryNode",...e&&{with:e}})},createFrom(e,o){return l({kind:"SelectQueryNode",from:dt.create(e),...o&&{with:o}})},cloneWithSelections(e,o){return l({...e,selections:e.selections?l([...e.selections,...o]):l(o)})},cloneWithDistinctOn(e,o){return l({...e,distinctOn:e.distinctOn?l([...e.distinctOn,...o]):l(o)})},cloneWithFrontModifier(e,o){return l({...e,frontModifiers:e.frontModifiers?l([...e.frontModifiers,o]):l([o])})},cloneWithOrderByItems:(e,o)=>E.cloneWithOrderByItems(e,o),cloneWithGroupByItems(e,o){return l({...e,groupBy:e.groupBy?Zi.cloneWithItems(e.groupBy,o):Zi.create(o)})},cloneWithLimit(e,o){return l({...e,limit:o})},cloneWithOffset(e,o){return l({...e,offset:o})},cloneWithFetch(e,o){return l({...e,fetch:o})},cloneWithHaving(e,o){return l({...e,having:e.having?oa.cloneWithOperation(e.having,"And",o):oa.create(o)})},cloneWithSetOperations(e,o){return l({...e,setOperations:e.setOperations?l([...e.setOperations,...o]):l([...o])})},cloneWithoutSelections(e){return l({...e,selections:[]})},cloneWithoutLimit(e){return l({...e,limit:void 0})},cloneWithoutOffset(e){return l({...e,offset:void 0})},cloneWithoutOrderBy:e=>E.cloneWithoutOrderBy(e),cloneWithoutGroupBy(e){return l({...e,groupBy:void 0})}})});var En,ma=m(()=>{br();ct();io();_();En=class e{#e;constructor(o){this.#e=l(o)}on(...o){return new e({...this.#e,joinNode:_o.cloneWithOn(this.#e.joinNode,ue(o))})}onRef(o,t,r){return new e({...this.#e,joinNode:_o.cloneWithOn(this.#e.joinNode,_e(o,t,r))})}onTrue(){return new e({...this.#e,joinNode:_o.cloneWithOn(this.#e.joinNode,le.createWithSql("true"))})}$call(o){return o(this)}toOperationNode(){return this.#e.joinNode}}});var kl,fa=m(()=>{_();kl=l({is(e){return e.kind==="PartitionByItemNode"},create(e){return l({kind:"PartitionByItemNode",partitionBy:e})}})});function Pl(e){return No(e).map(kl.create)}var Tl=m(()=>{fa();Me()});var qn,Ml=m(()=>{On();Co();It();Tl();_();qn=class e{#e;constructor(o){this.#e=l(o)}orderBy(...o){return new e({overNode:Nr.cloneWithOrderByItems(this.#e.overNode,Xe(o))})}clearOrderBy(){return new e({overNode:E.cloneWithoutOrderBy(this.#e.overNode)})}partitionBy(o){return new e({overNode:Nr.cloneWithPartitionByItems(this.#e.overNode,Pl(o))})}$call(o){return o(this)}toOperationNode(){return this.#e.overNode}}});var Ft,ha=m(()=>{_();fn();mn();Ft=l({is(e){return e.kind==="SelectionNode"},create(e){return l({kind:"SelectionNode",selection:e})},createSelectAll(){return l({kind:"SelectionNode",selection:pn.create()})},createSelectAllFromTable(e){return l({kind:"SelectionNode",selection:Tt.createSelectAll(e)})}})});function Oo(e){return ye(e)?Oo(e(So())):ke(e)?e.map(o=>Il(o)):[Il(e)]}function Il(e){return B(e)?Ft.create($l(e)):hn(e)?Ft.create(e.toOperationNode()):Ft.create(Rn(e))}function ao(e){return e?Array.isArray(e)?e.map(Ll):[Ll(e)]:[Ft.createSelectAll()]}function Ll(e){if(B(e))return Ft.createSelectAllFromTable(Ne(e));throw new Error(`invalid value selectAll expression: ${JSON.stringify(e)}`)}var Or=m(()=>{_();ha();Me();gn();ut();so();Wt()});var hx,Dl=m(()=>{_();hx=l({is(e){return e.kind==="ValuesNode"},create(e){return l({kind:"ValuesNode",values:l(e)})}})});var wx,zl=m(()=>{_();wx=l({is(e){return e.kind==="DefaultInsertValueNode"},create(){return l({kind:"DefaultInsertValueNode"})}})});var ga,ba=m(()=>{_();ga=l({is(e){return e.kind==="ColumnUpdateNode"},create(e,o){return l({kind:"ColumnUpdateNode",column:e,value:o})}})});function Fl(...e){return e.length===2?[ga.create(de(e[0]),G(e[1]))]:rb(e[0])}function rb(e){let o=ye(e)?e(So()):e;return Object.entries(o).filter(([t,r])=>r!==void 0).map(([t,r])=>ga.create(ce.create(t),G(r)))}var Wl=m(()=>{Ge();ba();Wt();_();$o();Me()});var Ex,Bl=m(()=>{_();Ex=l({is(e){return e.kind==="OnDuplicateKeyNode"},create(e){return l({kind:"OnDuplicateKeyNode",updates:e})}})});var Ul=m(()=>{});function Bt(e){return Object.prototype.hasOwnProperty.call(e,"prototype")}var Vo,Sr=m(()=>{Vo=class extends Error{node;constructor(o){super("no result"),this.node=o}}});var Mx,Vl=m(()=>{_();xr();Mx=l({is(e){return e.kind==="OnConflictNode"},create(){return l({kind:"OnConflictNode"})},cloneWith(e,o){return l({...e,...o})},cloneWithIndexWhere(e,o){return l({...e,indexWhere:e.indexWhere?ve.cloneWithOperation(e.indexWhere,"And",o):ve.create(o)})},cloneWithIndexOrWhere(e,o){return l({...e,indexWhere:e.indexWhere?ve.cloneWithOperation(e.indexWhere,"Or",o):ve.create(o)})},cloneWithUpdateWhere(e,o){return l({...e,updateWhere:e.updateWhere?ve.cloneWithOperation(e.updateWhere,"And",o):ve.create(o)})},cloneWithUpdateOrWhere(e,o){return l({...e,updateWhere:e.updateWhere?ve.cloneWithOperation(e.updateWhere,"Or",o):ve.create(o)})},cloneWithoutIndexWhere(e){return l({...e,indexWhere:void 0})},cloneWithoutUpdateWhere(e){return l({...e,updateWhere:void 0})}})});var Jl=m(()=>{});var Ql,wa=m(()=>{_();Ql=l({is(e){return e.kind==="TopNode"},create(e,o){return l({kind:"TopNode",expression:e,modifiers:o})}})});function Ut(e,o){if(!ro(e)&&!it(e))throw new Error(`Invalid top expression: ${e}`);if(!vo(o)&&!nb(o))throw new Error(`Invalid top modifiers: ${o}`);return Ql.create(e,o)}function nb(e){return e==="percent"||e==="with ties"||e==="percent with ties"}var kn=m(()=>{wa();_()});var Vx,Gl=m(()=>{_();Vx=l({is(e){return e.kind==="OrActionNode"},create(e){return l({kind:"OrActionNode",action:e})}})});var Hl=m(()=>{});var Pn,va=m(()=>{Pn=class{numDeletedRows;constructor(o){this.numDeletedRows=o}}});var Vt,Ar=m(()=>{_();Vt=l({is(e){return e.kind==="LimitNode"},create(e){return l({kind:"LimitNode",limit:e})}})});var ae,ya,Xl=m(()=>{Tn();so();Or();Co();_();Sr();va();An();Ar();It();io();$o();kn();ya=class{#e;constructor(o){this.#e=l(o)}where(...o){return new ae({...this.#e,queryNode:E.cloneWithWhere(this.#e.queryNode,ue(o))})}whereRef(o,t,r){return new ae({...this.#e,queryNode:E.cloneWithWhere(this.#e.queryNode,_e(o,t,r))})}clearWhere(){return new ae({...this.#e,queryNode:E.cloneWithoutWhere(this.#e.queryNode)})}top(o,t){return new ae({...this.#e,queryNode:E.cloneWithTop(this.#e.queryNode,Ut(o,t))})}using(o){return new ae({...this.#e,queryNode:zt.cloneWithUsing(this.#e.queryNode,pt(o))})}innerJoin(...o){return this.#o("InnerJoin",o)}leftJoin(...o){return this.#o("LeftJoin",o)}rightJoin(...o){return this.#o("RightJoin",o)}fullJoin(...o){return this.#o("FullJoin",o)}#o(o,t){return new ae({...this.#e,queryNode:E.cloneWithJoin(this.#e.queryNode,Jt(o,t))})}returning(o){return new ae({...this.#e,queryNode:E.cloneWithReturning(this.#e.queryNode,Oo(o))})}returningAll(o){return new ae({...this.#e,queryNode:E.cloneWithReturning(this.#e.queryNode,ao(o))})}output(o){return new ae({...this.#e,queryNode:E.cloneWithOutput(this.#e.queryNode,Oo(o))})}outputAll(o){return new ae({...this.#e,queryNode:E.cloneWithOutput(this.#e.queryNode,ao(o))})}clearReturning(){return new ae({...this.#e,queryNode:E.cloneWithoutReturning(this.#e.queryNode)})}clearLimit(){return new ae({...this.#e,queryNode:zt.cloneWithoutLimit(this.#e.queryNode)})}orderBy(...o){return new ae({...this.#e,queryNode:E.cloneWithOrderByItems(this.#e.queryNode,Xe(o))})}clearOrderBy(){return new ae({...this.#e,queryNode:E.cloneWithoutOrderBy(this.#e.queryNode)})}limit(o){return new ae({...this.#e,queryNode:zt.cloneWithLimit(this.#e.queryNode,Vt.create(G(o)))})}modifyEnd(o){return new ae({...this.#e,queryNode:E.cloneWithEndModifier(this.#e.queryNode,o.toOperationNode())})}$call(o){return o(this)}$if(o,t){return o?t(this):new ae({...this.#e})}$castTo(){return new ae(this.#e)}$narrowType(){return new ae(this.#e)}$assertType(){return new ae(this.#e)}withPlugin(o){return new ae({...this.#e,executor:this.#e.executor.withPlugin(o)})}toOperationNode(){return this.#e.executor.transformQuery(this.#e.queryNode,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(o){let t=this.compile(),r=await this.#e.executor.executeQuery(t,o),{adapter:n}=this.#e.executor,a=t.query;return a.returning&&n.supportsReturning||a.output&&n.supportsOutput?r.rows:[new Pn(r.numAffectedRows??BigInt(0))]}async executeTakeFirst(o){let[t]=await this.execute(o);return t}async executeTakeFirstOrThrow(o){typeof o=="function"&&(o={errorConstructor:o});let t=await this.executeTakeFirst(o);if(t===void 0){let r=o?.errorConstructor??Vo;throw Bt(r)?new r(this.toOperationNode()):r(this.toOperationNode())}return t}async*stream(o){typeof o!="object"&&(o={chunkSize:o});let t=this.compile(),r=this.#e.executor.stream(t,o.chunkSize??100,o);for await(let n of r)yield*n.rows}async explain(o,t){return await new ae({...this.#e,queryNode:E.cloneWithExplain(this.#e.queryNode,o,t)}).execute()}};ae=ya});var Mn,_a=m(()=>{Mn=class{numUpdatedRows;numChangedRows;constructor(o,t){this.numUpdatedRows=o,this.numChangedRows=t}}});var se,Na,Yl=m(()=>{Tn();so();Or();Co();Sn();Wl();_();_a();Sr();io();$o();Ar();kn();It();Na=class{#e;constructor(o){this.#e=l(o)}where(...o){return new se({...this.#e,queryNode:E.cloneWithWhere(this.#e.queryNode,ue(o))})}whereRef(o,t,r){return new se({...this.#e,queryNode:E.cloneWithWhere(this.#e.queryNode,_e(o,t,r))})}clearWhere(){return new se({...this.#e,queryNode:E.cloneWithoutWhere(this.#e.queryNode)})}top(o,t){return new se({...this.#e,queryNode:E.cloneWithTop(this.#e.queryNode,Ut(o,t))})}from(o){return new se({...this.#e,queryNode:Dt.cloneWithFromItems(this.#e.queryNode,pt(o))})}innerJoin(...o){return this.#o("InnerJoin",o)}leftJoin(...o){return this.#o("LeftJoin",o)}rightJoin(...o){return this.#o("RightJoin",o)}fullJoin(...o){return this.#o("FullJoin",o)}#o(o,t){return new se({...this.#e,queryNode:E.cloneWithJoin(this.#e.queryNode,Jt(o,t))})}orderBy(...o){return new se({...this.#e,queryNode:E.cloneWithOrderByItems(this.#e.queryNode,Xe(o))})}clearOrderBy(){return new se({...this.#e,queryNode:E.cloneWithoutOrderBy(this.#e.queryNode)})}limit(o){return new se({...this.#e,queryNode:Dt.cloneWithLimit(this.#e.queryNode,Vt.create(G(o)))})}set(...o){return new se({...this.#e,queryNode:Dt.cloneWithUpdates(this.#e.queryNode,Fl(...o))})}returning(o){return new se({...this.#e,queryNode:E.cloneWithReturning(this.#e.queryNode,Oo(o))})}returningAll(o){return new se({...this.#e,queryNode:E.cloneWithReturning(this.#e.queryNode,ao(o))})}output(o){return new se({...this.#e,queryNode:E.cloneWithOutput(this.#e.queryNode,Oo(o))})}outputAll(o){return new se({...this.#e,queryNode:E.cloneWithOutput(this.#e.queryNode,ao(o))})}modifyEnd(o){return new se({...this.#e,queryNode:E.cloneWithEndModifier(this.#e.queryNode,o.toOperationNode())})}clearReturning(){return new se({...this.#e,queryNode:E.cloneWithoutReturning(this.#e.queryNode)})}$call(o){return o(this)}$if(o,t){return o?t(this):new se({...this.#e})}$castTo(){return new se(this.#e)}$narrowType(){return new se(this.#e)}$assertType(){return new se(this.#e)}withPlugin(o){return new se({...this.#e,executor:this.#e.executor.withPlugin(o)})}toOperationNode(){return this.#e.executor.transformQuery(this.#e.queryNode,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(o){let t=this.compile(),r=await this.#e.executor.executeQuery(t,o),{adapter:n}=this.#e.executor,a=t.query;return a.returning&&n.supportsReturning||a.output&&n.supportsOutput?r.rows:[new Mn(r.numAffectedRows??BigInt(0),r.numChangedRows)]}async executeTakeFirst(o){let[t]=await this.execute(o);return t}async executeTakeFirstOrThrow(o){typeof o=="function"&&(o={errorConstructor:o});let t=await this.executeTakeFirst(o);if(t===void 0){let r=o?.errorConstructor??Vo;throw Bt(r)?new r(this.toOperationNode()):r(this.toOperationNode())}return t}async*stream(o){typeof o!="object"&&(o={chunkSize:o});let t=this.compile(),r=this.#e.executor.stream(t,o.chunkSize??100,o);for await(let n of r)yield*n.rows}async explain(o,t){return await new se({...this.#e,queryNode:E.cloneWithExplain(this.#e.queryNode,o,t)}).execute()}};se=Na});var EC,Kl=m(()=>{_();Ge();gr();EC=l({is(e){return e.kind==="CommonTableExpressionNameNode"},create(e,o){return l({kind:"CommonTableExpressionNameNode",table:Lo.create(e),columns:o?l(o.map(ce.create)):void 0})}})});var kC,Zl=m(()=>{_();kC=l({is(e){return e.kind==="CommonTableExpressionNode"},create(e,o){return l({kind:"CommonTableExpressionNode",name:e,expression:o})},cloneWith(e,o){return l({...e,...o})}})});var MC,eu=m(()=>{_();MC=l({is(e){return e.kind==="WithNode"},create(e,o){return l({kind:"WithNode",expressions:l([e]),...o})},cloneWithExpression(e,o){return l({...e,expressions:l([...e.expressions,o])})}})});function In(e){let o="";for(let t=0;t<e;++t)o+=ib();return o}function ib(){return ou[~~(Math.random()*ou.length)]}var ou,$a=m(()=>{ou=["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","0","1","2","3","4","5","6","7","8","9"]});function Ie(){return new xa}var xa,Ln=m(()=>{$a();xa=class{#e;get queryId(){return this.#e===void 0&&(this.#e=In(8)),this.#e}}});var tu=m(()=>{});var ru=m(()=>{});var UC,nu=m(()=>{_();UC=l({is(e){return e.kind==="MatchedNode"},create(e,o=!1){return l({kind:"MatchedNode",not:e,bySource:o})}})});var Se,Er=m(()=>{Se=class{#e;#o;#r;constructor(){this.#e=new Promise((o,t)=>{this.#r=t,this.#o=o})}get promise(){return this.#e}resolve=o=>{this.#o?.(o),this.#o=this.#r=void 0};reject=o=>{this.#r?.(o),this.#r=this.#o=void 0}}});async function Dn(e,o){let t=new Se,r=new Se;return e.provideConnection(async n=>(t.resolve(n),await r.promise),o).catch(n=>t.reject(n)),l({connection:await t.promise,release:r.resolve})}var iu=m(()=>{Er();_()});function su(e="ignore query",o,t){if(e!=="ignore query"){if(e==="cancel query"){let r=o.cancelQuery;return r||(t(),au(e,o.killSession?"kill session":void 0)),r.bind(o)}if(e==="kill session"){let r=o.killSession;return r||(t(),au(e,o.cancelQuery?"cancel query":void 0)),r.bind(o)}throw t(),new Error(`Unexpected \`inflightQueryAbortStrategy\`: "${e}"`)}}function au(e,o){throw new Error(`This dialect doesn't support \`inflightQueryAbortStrategy\` "${e}". Use "ignore query"${o?` or "${o}"`:""} instead.`)}function mt(e,o,t){e?.aborted&&(t?.(),ft(e.reason,o))}function ft(e,o){throw ab(e,o),e}function ht(e){return o=>console.error(`\`${e}\` failed in the background after abortion: ${ol(o)}`)}function ab(e,o){e!==null&&typeof e=="object"&&!Object.isFrozen(e)&&Object.defineProperty(e,"__kysely_timing__",{configurable:!0,enumerable:!1,value:o,writable:!1})}var co,cu=m(()=>{_();co={}});var sb,zn,lu=m(()=>{_();iu();cu();Er();sb=l([]),zn=class{#e;constructor(o=sb){this.#e=o}get plugins(){return this.#e}transformQuery(o,t){for(let r of this.#e){let n=r.transformQuery({node:o,queryId:t});if(n.kind===o.kind)o=n;else throw new Error(["KyselyPlugin.transformQuery must return a node","of the same kind that was given to it.",`The plugin was given a ${o.kind}`,`but it returned a ${n.kind}`].join(" "))}return o}async executeQuery(o,t){let{inflightQueryAbortStrategy:r="ignore query",signal:n}=t||{};if(!n){let f=await this.provideConnection(async h=>await h.executeQuery(o),t);return await this.#o(f,o.queryId)}mt(n,"before query execution"),t=l({signal:n});let{connection:a,release:s}=await Dn(this,t),c=this.provideConnection.bind(this),{promise:d,resolve:u}=new Se,p=()=>u(co);n.addEventListener("abort",p,{once:!0});try{mt(n,"before query execution",s);let f=su(r,a,s);if(f&&a.collectSessionInfo){mt(n,"before query execution",s);let g=a.collectSessionInfo();await Promise.race([d,g]).catch(C=>{throw s(),C})===co&&(g.catch(ht("collectSessionInfo")).finally(s),ft(n.reason,"before query execution"))}let h=a.executeQuery(o,t),b=await Promise.race([d,h]).catch(g=>{throw s(),g});b===co?(Promise.allSettled([h.catch(ht("query")),f?.(c).catch(ht("inflightQueryAbortHandler"))]).finally(s),ft(n.reason,"during query execution")):s();let v=this.#o(b,o.queryId,t),w=await Promise.race([d,v]);return w===co&&(v.catch(ht("plugins.transformResult")),ft(n.reason,"during result transformation")),w}finally{u(co),n.removeEventListener("abort",p)}}async*stream(o,t,r){let{signal:n}=r||{};if(!n){let{connection:b,release:v}=await Dn(this);try{for await(let w of b.streamQuery(o,t))yield await this.#o(w,o.queryId,r)}finally{v()}return}r=l({signal:n}),mt(n,"before connection acquisition");let{connection:a,release:s}=await Dn(this,r),{promise:c,resolve:d}=new Se,u=()=>d(co);n.addEventListener("abort",u,{once:!0});let p,f;mt(n,"before query streaming",s);let{queryId:h}=o;try{for(p=a.streamQuery(o,t,r);;){mt(n,"during query streaming");let b=p.next(),v=await Promise.race([c,b]);if(v===co&&(f=b.catch(ht("iterator.next")),ft(n.reason,"during query streaming")),v.done)break;let w=this.#o(v.value,h,r),g=await Promise.race([c,w]);g===co&&(f=w.catch(ht("plugins.transformResult")),ft(n.reason,"during result transformation")),yield g}}finally{d(co),n.removeEventListener("abort",u);let b=(p?.return?.()||Promise.resolve()).finally(()=>f).finally(s);f||await b}}async#o(o,t,r){let{signal:n}=r||{};for(let a of this.#e)o=await a.transformResult(l({queryId:t,result:o,signal:n}));return o}}});var Ca,Fn,Wn=m(()=>{lu();Ca=class e extends zn{get adapter(){throw new Error("this query cannot be compiled to SQL")}compileQuery(){throw new Error("this query cannot be compiled to SQL")}provideConnection(){throw new Error("this query cannot be executed")}withConnectionProvider(){throw new Error("this query cannot have a connection provider")}withPlugin(o){return new e([...this.plugins,o])}withPlugins(o){return new e([...this.plugins,...o])}withPluginAtFront(o){return new e([o,...this.plugins])}withoutPlugins(){return new e([])}},Fn=new Ca});var uu=m(()=>{});var du=m(()=>{});var pu=m(()=>{});function mu(e,o){return new En({joinNode:_o.create(e,gt(o))})}function fu(){return new qn({overNode:Nr.create()})}var ja=m(()=>{br();On();ma();Ml();so()});function Jt(e,o){if(o.length===3)return lb(e,o[0],o[1],o[2]);if(o.length===2)return cb(e,o[0],o[1]);if(o.length===1)return ub(e,o[0]);throw new Error("not implemented")}function cb(e,o,t){return t(mu(e,o)).toOperationNode()}function lb(e,o,t,r){return _o.createWithOn(e,gt(o),_e(t,"=",r))}function ub(e,o){return _o.create(e,gt(o))}var Tn=m(()=>{br();io();ja();so()});var hu,Oa=m(()=>{_();hu=l({is(e){return e.kind==="OffsetNode"},create(e){return l({kind:"OffsetNode",offset:e})}})});var gu,Sa=m(()=>{_();gu=l({is(e){return e.kind==="GroupByItemNode"},create(e){return l({kind:"GroupByItemNode",groupBy:e})}})});function bu(e){return e=ye(e)?e(So()):e,No(e).map(gu.create)}var wu=m(()=>{Sa();Wt();_();Me()});var vu,Aa=m(()=>{_();vu=l({is(e){return e.kind==="SetOperationNode"},create(e,o,t){return l({kind:"SetOperationNode",operator:e,expression:o,all:t})}})});function bt(e,o,t){return ye(o)&&(o=o(Ea())),ke(o)||(o=[o]),o.map(r=>vu.create(e,Fo(r),t))}var yu=m(()=>{Wt();Aa();_();ut()});var W,qr,qa,Ra,Qt=m(()=>{yo();Do();ne();ze();st();yr();io();W=class e{#e;constructor(o){this.#e=o}get expressionType(){}as(o){return new qr(this,o)}or(...o){return new qa(Je.create(this.#e,ue(o)))}and(...o){return new Ra(Te.create(this.#e,ue(o)))}$castTo(){return new e(this.#e)}$notNull(){return new e(this.#e)}toOperationNode(){return this.#e}},qr=class{#e;#o;constructor(o,t){this.#e=o,this.#o=t}get expression(){return this.#e}get alias(){return this.#o}toOperationNode(){return Pe.create(this.#e.toOperationNode(),ie(this.#o)?this.#o.toOperationNode():P.create(this.#o))}},qa=class e{#e;constructor(o){this.#e=o}get expressionType(){}as(o){return new qr(this,o)}or(...o){return new e(Je.create(this.#e,ue(o)))}$castTo(){return new e(this.#e)}toOperationNode(){return Uo.create(this.#e)}},Ra=class e{#e;constructor(o){this.#e=o}get expressionType(){}as(o){return new qr(this,o)}and(...o){return new e(Te.create(this.#e,ue(o)))}$castTo(){return new e(this.#e)}toOperationNode(){return Uo.create(this.#e)}}});var _u,ka=m(()=>{_();Bo();_u=l({is(e){return e.kind==="FetchNode"},create(e,o){return{kind:"FetchNode",rowCount:Oe.create(e),modifier:o}}})});function Nu(e,o){if(!ro(e)&&!it(e))throw new Error(`Invalid fetch row count: ${e}`);if(!db(o))throw new Error(`Invalid fetch modifier: ${o}`);return _u.create(e,o)}function db(e){return e==="only"||e==="with ties"}var $u=m(()=>{ka();_()});function xu(e){return new Bn(e)}var T,Bn,Pa,Ta=m(()=>{yo();Wi();Tn();so();Or();Me();jr();Co();It();Ar();Oa();_();wu();Sr();ne();yu();io();Qt();$o();$u();kn();Bn=class{#e;constructor(o){this.#e=l(o)}get expressionType(){}get isSelectQueryBuilder(){return!0}where(...o){return new T({...this.#e,queryNode:E.cloneWithWhere(this.#e.queryNode,ue(o))})}whereRef(o,t,r){return new T({...this.#e,queryNode:E.cloneWithWhere(this.#e.queryNode,_e(o,t,r))})}having(...o){return new T({...this.#e,queryNode:Y.cloneWithHaving(this.#e.queryNode,ue(o))})}havingRef(o,t,r){return new T({...this.#e,queryNode:Y.cloneWithHaving(this.#e.queryNode,_e(o,t,r))})}select(o){return new T({...this.#e,queryNode:Y.cloneWithSelections(this.#e.queryNode,Oo(o))})}distinctOn(o){return new T({...this.#e,queryNode:Y.cloneWithDistinctOn(this.#e.queryNode,No(o))})}modifyFront(o){return new T({...this.#e,queryNode:Y.cloneWithFrontModifier(this.#e.queryNode,no.createWithExpression(o.toOperationNode()))})}modifyEnd(o){return new T({...this.#e,queryNode:E.cloneWithEndModifier(this.#e.queryNode,no.createWithExpression(o.toOperationNode()))})}distinct(){return new T({...this.#e,queryNode:Y.cloneWithFrontModifier(this.#e.queryNode,no.create("Distinct"))})}forUpdate(o){return new T({...this.#e,queryNode:E.cloneWithEndModifier(this.#e.queryNode,no.create("ForUpdate",o?hr(o).map(Ne):void 0))})}forShare(o){return new T({...this.#e,queryNode:E.cloneWithEndModifier(this.#e.queryNode,no.create("ForShare",o?hr(o).map(Ne):void 0))})}forKeyShare(o){return new T({...this.#e,queryNode:E.cloneWithEndModifier(this.#e.queryNode,no.create("ForKeyShare",o?hr(o).map(Ne):void 0))})}forNoKeyUpdate(o){return new T({...this.#e,queryNode:E.cloneWithEndModifier(this.#e.queryNode,no.create("ForNoKeyUpdate",o?hr(o).map(Ne):void 0))})}skipLocked(){return new T({...this.#e,queryNode:E.cloneWithEndModifier(this.#e.queryNode,no.create("SkipLocked"))})}noWait(){return new T({...this.#e,queryNode:E.cloneWithEndModifier(this.#e.queryNode,no.create("NoWait"))})}selectAll(o){return new T({...this.#e,queryNode:Y.cloneWithSelections(this.#e.queryNode,ao(o))})}innerJoin(...o){return this.#o("InnerJoin",o)}leftJoin(...o){return this.#o("LeftJoin",o)}rightJoin(...o){return this.#o("RightJoin",o)}fullJoin(...o){return this.#o("FullJoin",o)}crossJoin(...o){return this.#o("CrossJoin",o)}innerJoinLateral(...o){return this.#o("LateralInnerJoin",o)}leftJoinLateral(...o){return this.#o("LateralLeftJoin",o)}crossJoinLateral(...o){return this.#o("LateralCrossJoin",o)}crossApply(...o){return this.#o("CrossApply",o)}outerApply(...o){return this.#o("OuterApply",o)}#o(o,t){return new T({...this.#e,queryNode:E.cloneWithJoin(this.#e.queryNode,Jt(o,t))})}orderBy(...o){return new T({...this.#e,queryNode:E.cloneWithOrderByItems(this.#e.queryNode,Xe(o))})}groupBy(o){return new T({...this.#e,queryNode:Y.cloneWithGroupByItems(this.#e.queryNode,bu(o))})}limit(o){return new T({...this.#e,queryNode:Y.cloneWithLimit(this.#e.queryNode,Vt.create(G(o)))})}offset(o){return new T({...this.#e,queryNode:Y.cloneWithOffset(this.#e.queryNode,hu.create(G(o)))})}fetch(o,t="only"){return new T({...this.#e,queryNode:Y.cloneWithFetch(this.#e.queryNode,Nu(o,t))})}top(o,t){return new T({...this.#e,queryNode:E.cloneWithTop(this.#e.queryNode,Ut(o,t))})}union(o){return new T({...this.#e,queryNode:Y.cloneWithSetOperations(this.#e.queryNode,bt("union",o,!1))})}unionAll(o){return new T({...this.#e,queryNode:Y.cloneWithSetOperations(this.#e.queryNode,bt("union",o,!0))})}intersect(o){return new T({...this.#e,queryNode:Y.cloneWithSetOperations(this.#e.queryNode,bt("intersect",o,!1))})}intersectAll(o){return new T({...this.#e,queryNode:Y.cloneWithSetOperations(this.#e.queryNode,bt("intersect",o,!0))})}except(o){return new T({...this.#e,queryNode:Y.cloneWithSetOperations(this.#e.queryNode,bt("except",o,!1))})}exceptAll(o){return new T({...this.#e,queryNode:Y.cloneWithSetOperations(this.#e.queryNode,bt("except",o,!0))})}as(o){return new Pa(this,o)}clearSelect(){return new T({...this.#e,queryNode:Y.cloneWithoutSelections(this.#e.queryNode)})}clearWhere(){return new T({...this.#e,queryNode:E.cloneWithoutWhere(this.#e.queryNode)})}clearLimit(){return new T({...this.#e,queryNode:Y.cloneWithoutLimit(this.#e.queryNode)})}clearOffset(){return new T({...this.#e,queryNode:Y.cloneWithoutOffset(this.#e.queryNode)})}clearOrderBy(){return new T({...this.#e,queryNode:E.cloneWithoutOrderBy(this.#e.queryNode)})}clearGroupBy(){return new T({...this.#e,queryNode:Y.cloneWithoutGroupBy(this.#e.queryNode)})}$call(o){return o(this)}$if(o,t){return o?t(this):new T({...this.#e})}$castTo(){return new T(this.#e)}$narrowType(){return new T(this.#e)}$assertType(){return new T(this.#e)}$asTuple(){return new W(this.toOperationNode())}$asScalar(){return new W(this.toOperationNode())}withPlugin(o){return new T({...this.#e,executor:this.#e.executor.withPlugin(o)})}toOperationNode(){return this.#e.executor.transformQuery(this.#e.queryNode,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(o){let t=this.compile();return(await this.#e.executor.executeQuery(t,o)).rows}async executeTakeFirst(o){let[t]=await this.execute(o);return t}async executeTakeFirstOrThrow(o){typeof o=="function"&&(o={errorConstructor:o});let t=await this.executeTakeFirst(o);if(t===void 0){let r=o?.errorConstructor??Vo;throw Bt(r)?new r(this.toOperationNode()):r(this.toOperationNode())}return t}async*stream(o){typeof o!="object"&&(o={chunkSize:o});let t=this.compile(),r=this.#e.executor.stream(t,o.chunkSize??100,o);for await(let n of r)yield*n.rows}async explain(o,t){return await new T({...this.#e,queryNode:E.cloneWithExplain(this.#e.queryNode,o,t)}).execute()}};T=Bn;Pa=class{#e;#o;constructor(o,t){this.#e=o,this.#o=t}get expression(){return this.#e}get alias(){return this.#o}get isAliasedSelectQueryBuilder(){return!0}toOperationNode(){return Pe.create(this.#e.toOperationNode(),P.create(this.#o))}}});var lo,Un=m(()=>{_();xr();_r();lo=l({is(e){return e.kind==="AggregateFunctionNode"},create(e,o=[]){return l({kind:"AggregateFunctionNode",func:e,aggregated:o})},cloneWithDistinct(e){return l({...e,distinct:!0})},cloneWithOrderBy(e,o,t=!1){let r=t?"withinGroup":"orderBy";return l({...e,[r]:e[r]?xo.cloneWithItems(e[r],o):xo.create(o)})},cloneWithFilter(e,o){return l({...e,filter:e.filter?ve.cloneWithOperation(e.filter,"And",o):ve.create(o)})},cloneWithOrFilter(e,o){return l({...e,filter:e.filter?ve.cloneWithOperation(e.filter,"Or",o):ve.create(o)})},cloneWithOver(e,o){return l({...e,over:o})}})});var Ma,Ia=m(()=>{_();Ma=l({is(e){return e.kind==="FunctionNode"},create(e,o){return l({kind:"FunctionNode",func:e,arguments:o})}})});var Gt,La,Da=m(()=>{_();Un();yo();ne();ja();io();It();Co();Gt=class e{#e;constructor(o){this.#e=l(o)}get expressionType(){}as(o){return new La(this,o)}distinct(){return new e({...this.#e,aggregateFunctionNode:lo.cloneWithDistinct(this.#e.aggregateFunctionNode)})}orderBy(...o){return new e({...this.#e,aggregateFunctionNode:E.cloneWithOrderByItems(this.#e.aggregateFunctionNode,Xe(o))})}clearOrderBy(){return new e({...this.#e,aggregateFunctionNode:E.cloneWithoutOrderBy(this.#e.aggregateFunctionNode)})}withinGroupOrderBy(...o){return new e({...this.#e,aggregateFunctionNode:lo.cloneWithOrderBy(this.#e.aggregateFunctionNode,Xe(o),!0)})}filterWhere(...o){return new e({...this.#e,aggregateFunctionNode:lo.cloneWithFilter(this.#e.aggregateFunctionNode,ue(o))})}filterWhereRef(o,t,r){return new e({...this.#e,aggregateFunctionNode:lo.cloneWithFilter(this.#e.aggregateFunctionNode,_e(o,t,r))})}over(o){let t=fu();return new e({...this.#e,aggregateFunctionNode:lo.cloneWithOver(this.#e.aggregateFunctionNode,(o?o(t):t).toOperationNode())})}$call(o){return o(this)}$castTo(){return new e(this.#e)}$notNull(){return new e(this.#e)}toOperationNode(){return this.#e.aggregateFunctionNode}},La=class{#e;#o;constructor(o,t){this.#e=o,this.#o=t}get expression(){return this.#e}get alias(){return this.#o}toOperationNode(){return Pe.create(this.#e.toOperationNode(),P.create(this.#o))}}});function Cu(){let e=(t,r)=>new W(Ma.create(t,No(r??[]))),o=(t,r)=>new Gt({aggregateFunctionNode:lo.create(t,r?No(r):void 0)});return Object.assign(e,{agg:o,avg(t){return o("avg",[t])},coalesce(...t){return e("coalesce",t)},count(t){return o("count",[t])},countAll(t){return new Gt({aggregateFunctionNode:lo.create("count",ao(t))})},max(t){return o("max",[t])},min(t){return o("min",[t])},sum(t){return o("sum",[t])},any(t){return e("any",[t])},jsonAgg(t){return new Gt({aggregateFunctionNode:lo.create("json_agg",[B(t)?Ne(t):t.toOperationNode()])})},toJson(t){return new W(Ma.create("to_json",[B(t)?Ne(t):t.toOperationNode()]))}})}var za=m(()=>{Qt();Un();Ia();Me();Or();Da();_();so()});var ju,Fa=m(()=>{_();ju=l({is(e){return e.kind==="UnaryOperationNode"},create(e,o){return l({kind:"UnaryOperationNode",operator:e,operand:o})}})});function Ou(e,o){if(wl(e))return ju.create(Qe.create(e),de(o));throw new Error(`invalid unary operator ${JSON.stringify(e)}`)}var Su=m(()=>{Pt();Fa();Me()});var Ae,Vn=m(()=>{_();Cr();Ae=l({is(e){return e.kind==="CaseNode"},create(e){return l({kind:"CaseNode",value:e})},cloneWithWhen(e,o){return l({...e,when:l(e.when?[...e.when,o]:[o])})},cloneWithThen(e,o){return l({...e,when:e.when?l([...e.when.slice(0,-1),jo.cloneWithResult(e.when[e.when.length-1],o)]):void 0})},cloneWith(e,o){return l({...e,...o})}})});var Jn,Ht,Qn,Gn,Wa=m(()=>{Qt();_();Me();Vn();Cr();io();$o();Jn=class{#e;constructor(o){this.#e=l(o)}when(...o){return new Ht({...this.#e,node:Ae.cloneWithWhen(this.#e.node,jo.create(ue(o)))})}whenRef(o,t,r){return new Ht({...this.#e,node:Ae.cloneWithWhen(this.#e.node,jo.create(_e(o,t,r)))})}},Ht=class{#e;constructor(o){this.#e=l(o)}then(o){return new Qn({...this.#e,node:Ae.cloneWithThen(this.#e.node,xn(o)?vr(o):G(o))})}thenRef(o){return new Qn({...this.#e,node:Ae.cloneWithThen(this.#e.node,de(o))})}},Qn=class{#e;constructor(o){this.#e=l(o)}when(...o){return new Ht({...this.#e,node:Ae.cloneWithWhen(this.#e.node,jo.create(ue(o)))})}whenRef(o,t,r){return new Ht({...this.#e,node:Ae.cloneWithWhen(this.#e.node,jo.create(_e(o,t,r)))})}else(o){return new Gn({...this.#e,node:Ae.cloneWith(this.#e.node,{else:xn(o)?vr(o):G(o)})})}elseRef(o){return new Gn({...this.#e,node:Ae.cloneWith(this.#e.node,{else:de(o)})})}end(){return new W(Ae.cloneWith(this.#e.node,{isStatement:!1}))}endCase(){return new W(Ae.cloneWith(this.#e.node,{isStatement:!0}))}},Gn=class{#e;constructor(o){this.#e=l(o)}end(){return new W(Ae.cloneWith(this.#e.node,{isStatement:!1}))}endCase(){return new W(Ae.cloneWith(this.#e.node,{isStatement:!0}))}}});var Ba,Ua=m(()=>{_();Ba=l({is(e){return e.kind==="JSONPathLegNode"},create(e,o){return l({kind:"JSONPathLegNode",type:e,value:o})}})});var pb,Xt,Hn,Va,Ja=m(()=>{yo();ne();_n();Ua();wr();vn();ze();Bo();pb=/^#-\d+$/,Xt=class{#e;constructor(o){this.#e=o}at(o){if(typeof o!="number"&&typeof o!="string"||typeof o=="number"&&!Number.isInteger(o)||typeof o=="string"&&o!=="last"&&!pb.test(o))throw new Error(`Unexpected index value in .at(...): ${o}`);return this.#o("ArrayLocation",o)}key(o){return this.#o("Member",o)}#o(o,t){return Lt.is(this.#e)?new Hn(Lt.cloneWithTraversal(this.#e,Wo.is(this.#e.traversal)?Wo.cloneWithLeg(this.#e.traversal,Ba.create(o,t)):yn.cloneWithValue(this.#e.traversal,Oe.createImmediate(t)))):new Hn(Wo.cloneWithLeg(this.#e,Ba.create(o,t)))}},Hn=class e extends Xt{#e;constructor(o){super(o),this.#e=o}get expressionType(){}as(o){return new Va(this,o)}$castTo(){return new e(this.#e)}$notNull(){return new e(this.#e)}toOperationNode(){return this.#e}},Va=class{#e;#o;constructor(o,t){this.#e=o,this.#o=t}get expression(){return this.#e}get alias(){return this.#o}toOperationNode(){return Pe.create(this.#e.toOperationNode(),ie(this.#o)?this.#o.toOperationNode():P.create(this.#o))}}});var Qa,Ga=m(()=>{_();Qa=l({is(e){return e.kind==="TupleNode"},create(e){return l({kind:"TupleNode",values:l(e)})}})});function Eu(e){return mb[e]||fb.some(o=>o.test(e))}var mb,fb,Au,Ha=m(()=>{_();mb=l({bigint:!0,bigserial:!0,binary:!0,blob:!0,boolean:!0,bytea:!0,char:!0,date:!0,datemultirange:!0,daterange:!0,datetime:!0,datetime2:!0,decimal:!0,"double precision":!0,float4:!0,float8:!0,int2:!0,int4:!0,int4multirange:!0,int4range:!0,int8:!0,int8multirange:!0,int8range:!0,integer:!0,json:!0,jsonb:!0,numeric:!0,nummultirange:!0,numrange:!0,real:!0,serial:!0,smallint:!0,text:!0,time:!0,timestamp:!0,timestamptz:!0,timetz:!0,tsmultirange:!0,tsrange:!0,tstzmultirange:!0,tstzrange:!0,uuid:!0,varbinary:!0,varchar:!0}),fb=l([/^varchar\(\d+\)$/,/^char\(\d+\)$/,/^decimal\(\d+, \d+\)$/,/^numeric\(\d+, \d+\)$/,/^binary\(\d+\)$/,/^datetime\(\d+\)$/,/^time\(\d+\)$/,/^timetz\(\d+\)$/,/^timestamp\(\d+\)$/,/^timestamptz\(\d+\)$/,/^datetime2\(\d+\)$/,/^varbinary\(\d+\)$/]),Au=l({is(e){return e.kind==="DataTypeNode"},create(e){return l({kind:"DataTypeNode",dataType:e})}})});function qu(e){if(ie(e))return e.toOperationNode();if(Eu(e))return Au.create(e);throw new Error(`invalid column data type ${JSON.stringify(e)}`)}var Ru=m(()=>{Ha();ze()});var ku,Xa=m(()=>{_();ku=l({is(e){return e.kind==="CastNode"},create(e,o){return l({kind:"CastNode",expression:e,dataType:o})}})});function Ea(e=Fn){function o(n,a,s){return new W(Cn(n,a,s))}function t(n,a){return new W(Ou(n,a))}let r=Object.assign(o,{fn:void 0,eb:void 0,selectFrom(n){return xu({queryId:Ie(),executor:e,queryNode:Y.createFrom(pt(n))})},case(n){return new Jn({node:Ae.create(vo(n)?void 0:de(n))})},ref(n,a){return vo(a)?new W(Fe(n)):new Xt(Nl(n,a))},jsonPath(){return new Xt(Wo.create())},table(n){return new W(Ne(n))},val(n){return new W(G(n))},refTuple(...n){return new W(Qa.create(n.map(de)))},tuple(...n){return new W(Qa.create(n.map(G)))},lit(n){return new W(vr(n))},unary:t,not(n){return t("not",n)},exists(n){return t("exists",n)},neg(n){return t("-",n)},between(n,a,s){return new W(zo.create(de(n),Qe.create("between"),Te.create(G(a),G(s))))},betweenSymmetric(n,a,s){return new W(zo.create(de(n),Qe.create("between symmetric"),Te.create(G(a),G(s))))},and(n){return ke(n)?new W(jn(n,"and")):new W(Xi(n,"and"))},or(n){return ke(n)?new W(jn(n,"or")):new W(Xi(n,"or"))},parens(...n){let a=ue(n);return Uo.is(a)?new W(a):new W(Uo.create(a))},cast(n,a){return new W(ku.create(de(n),qu(a)))}});return r.fn=Cu(),r.eb=r,r}function So(e){return Ea()}var Wt=m(()=>{Ta();jr();so();Ln();za();Me();io();yr();Qt();Pt();Su();$o();Wn();Wa();Vn();_();Ja();dn();Do();Ga();wr();Ru();Xa()});function Fo(e){if(ie(e))return e.toOperationNode();if(ye(e))return e(So()).toOperationNode();throw new Error(`invalid expression: ${JSON.stringify(e)}`)}function Rn(e){if(ie(e))return e.toOperationNode();if(ye(e))return e(So()).toOperationNode();throw new Error(`invalid aliased expression: ${JSON.stringify(e)}`)}function lt(e){return cn(e)||ll(e)||ye(e)}var ut=m(()=>{ln();ze();Wt();_()});function Pu(e){return je(e)&&ie(e)&&B(e.table)&&B(e.alias)}var Ya=m(()=>{ze();_()});function pt(e){return ke(e)?e.map(o=>gt(o)):[gt(e)]}function gt(e){return B(e)?hb(e):Pu(e)?e.toOperationNode():Rn(e)}function hb(e){let o=" as ";if(e.includes(o)){let[t,r]=e.split(o).map(Tu);return Pe.create(Ne(t),P.create(r))}else return Ne(e)}function Ne(e){if(e.includes(".")){let[t,r]=e.split(".").map(Tu);return Lo.createWithSchema(t,r)}else return Lo.create(e)}function Tu(e){return e.trim()}var so=m(()=>{_();yo();gr();ut();ne();Ya()});var uA,Mu=m(()=>{_();uA=l({is(e){return e.kind==="AddColumnNode"},create(e){return l({kind:"AddColumnNode",column:e})}})});var fA,Iu=m(()=>{_();Ge();fA=l({is(e){return e.kind==="ColumnDefinitionNode"},create(e,o){return l({kind:"ColumnDefinitionNode",column:ce.create(e),dataType:o})},cloneWithFrontModifier(e,o){return l({...e,frontModifiers:e.frontModifiers?l([...e.frontModifiers,o]):[o]})},cloneWithEndModifier(e,o){return l({...e,endModifiers:e.endModifiers?l([...e.endModifiers,o]):[o]})},cloneWith(e,o){return l({...e,...o})}})});var wA,Lu=m(()=>{_();Ge();wA=l({is(e){return e.kind==="DropColumnNode"},create(e){return l({kind:"DropColumnNode",column:ce.create(e)})},cloneWith(e,o){return l({...e,...o})}})});var NA,Du=m(()=>{_();Ge();NA=l({is(e){return e.kind==="RenameColumnNode"},create(e,o){return l({kind:"RenameColumnNode",column:ce.create(e),renameTo:ce.create(o)})}})});var jA,zu=m(()=>{_();ne();jA=l({is(e){return e.kind==="CheckConstraintNode"},create(e,o){return l({kind:"CheckConstraintNode",expression:e,name:o?P.create(o):void 0})}})});var gb,AA,Fu,Ka=m(()=>{_();gb=l({cascade:!0,"no action":!0,restrict:!0,"set default":!0,"set null":!0}),AA=Object.keys(gb),Fu=l({is(e){return e.kind==="ReferencesNode"},create(e,o){return l({kind:"ReferencesNode",table:e,columns:l([...o])})},cloneWithOnDelete(e,o){return l({...e,onDelete:o})},cloneWithOnUpdate(e,o){return l({...e,onUpdate:o})}})});var RA,Wu=m(()=>{_();RA=l({is(e){return e.kind==="GeneratedNode"},create(e){return l({kind:"GeneratedNode",...e})},createWithExpression(e){return l({kind:"GeneratedNode",always:!0,expression:e})},cloneWith(e,o){return l({...e,...o})}})});var TA,Bu=m(()=>{_();TA=l({is(e){return e.kind==="DefaultValueNode"},create(e){return l({kind:"DefaultValueNode",defaultValue:e})}})});var Uu=m(()=>{});var DA,Vu=m(()=>{_();DA=l({is(e){return e.kind==="ModifyColumnNode"},create(e){return l({kind:"ModifyColumnNode",column:e})}})});var UA,Ju=m(()=>{_();ne();Ka();UA=l({is(e){return e.kind==="ForeignKeyConstraintNode"},create(e,o,t,r){return l({kind:"ForeignKeyConstraintNode",columns:e,references:Fu.create(o,t),name:r?P.create(r):void 0})},cloneWith(e,o){return l({...e,...o})}})});var Qu=m(()=>{});var GA,Gu=m(()=>{_();GA=l({is(e){return e.kind==="AddConstraintNode"},create(e){return l({kind:"AddConstraintNode",constraint:e})}})});var eE,Hu=m(()=>{Ji();_();Ge();ne();eE=l({is(e){return e.kind==="UniqueConstraintNode"},create(e,o,t){return B(e.at(0))&&(Mt("`UniqueConstraintNode.create(columns: string[], ...)` is deprecated - pass `ColumnNode[]` instead."),e=e.map(ce.create)),l({kind:"UniqueConstraintNode",columns:l(e),name:o?P.create(o):void 0,nullsNotDistinct:t})},cloneWith(e,o){return l({...e,...o})}})});var nE,Xu=m(()=>{_();ne();nE=l({is(e){return e.kind==="DropConstraintNode"},create(e){return l({kind:"DropConstraintNode",constraintName:P.create(e)})},cloneWith(e,o){return l({...e,...o})}})});var cE,Yu=m(()=>{_();Ge();cE=l({is(e){return e.kind==="AlterColumnNode"},create(e,o,t){return l({kind:"AlterColumnNode",column:ce.create(e),[o]:t})}})});var Ku=m(()=>{});var fE,Zu=m(()=>{_();Ge();ne();fE=l({is(e){return e.kind==="PrimaryKeyConstraintNode"},create(e,o){return l({kind:"PrimaryKeyConstraintNode",columns:l(e.map(ce.create)),name:o?P.create(o):void 0})},cloneWith(e,o){return l({...e,...o})}})});var wE,ed=m(()=>{_();ne();wE=l({is(e){return e.kind==="AddIndexNode"},create(e){return l({kind:"AddIndexNode",name:P.create(e)})},cloneWith(e,o){return l({...e,...o})},cloneWithColumns(e,o){return l({...e,columns:[...e.columns||[],...o]})}})});var NE,od=m(()=>{_();ne();NE=l({is(e){return e.kind==="RenameConstraintNode"},create(e,o){return l({kind:"RenameConstraintNode",oldName:P.create(e),newName:P.create(o)})}})});var td=m(()=>{});var rd=m(()=>{});var nd=m(()=>{});var id=m(()=>{});var ad=m(()=>{});var sd=m(()=>{});var cd=m(()=>{});var ld=m(()=>{});var PE,ud=m(()=>{_();at();PE=l({is(e){return e.kind==="CreateViewNode"},create(e){return l({kind:"CreateViewNode",name:Ve.create(e)})},cloneWith(e,o){return l({...e,...o})}})});var dd=m(()=>{});var DE,pd=m(()=>{_();at();DE=l({is(e){return e.kind==="DropViewNode"},create(e){return l({kind:"DropViewNode",name:Ve.create(e)})},cloneWith(e,o){return l({...e,...o})}})});var md=m(()=>{});var VE,fd=m(()=>{_();$n();Bo();VE=l({is(e){return e.kind==="CreateTypeNode"},create(e){return l({kind:"CreateTypeNode",name:e})},cloneWithEnum(e,o){return l({...e,enum:Nn.create(o.map(Oe.createImmediate))})}})});var hd=m(()=>{});var HE,gd=m(()=>{_();HE=l({is(e){return e.kind==="DropTypeNode"},create(e){return Array.isArray(e)||(e=[e]),l({kind:"DropTypeNode",name:e[0],additionalNames:e.slice(1)})},cloneWith(e,o){return l({...e,...o})}})});var bd=m(()=>{});var eq,wd=m(()=>{_();at();eq=l({is(e){return e.kind==="RefreshMaterializedViewNode"},create(e){return l({kind:"RefreshMaterializedViewNode",name:Ve.create(e)})},cloneWith(e,o){return l({...e,...o})}})});var vd=m(()=>{});var nq,yd=m(()=>{_();nq=l({is(e){return e.kind==="AlterTypeNode"},create(e){return l({kind:"AlterTypeNode",name:e})},cloneWith(e,o){return l({...e,...o})}})});var sq,_d=m(()=>{_();sq=l({is(e){return e.kind==="AddValueNode"},create(e){return l({kind:"AddValueNode",value:e})},cloneWith(e,o){return l({...e,...o})}})});var Nd=m(()=>{});var dq,$d=m(()=>{_();dq=l({is(e){return e.kind==="RenameValueNode"},create(e,o){return l({kind:"RenameValueNode",oldValue:e,newValue:o})}})});var xd=m(()=>{});var Cd=m(()=>{});var jd=m(()=>{});var Od=m(()=>{});var Sd=m(()=>{});var Ad=m(()=>{});var bb,yq,Ed=m(()=>{_();bb=["query","error"],yq=l(bb)});var qd=m(()=>{});var Rd=m(()=>{Symbol.asyncDispose??=Symbol("Symbol.asyncDispose")});function Ao(e){return new Za(e)}var Za,es,os=m(()=>{yo();_();Wn();ne();ze();Za=class e{#e;constructor(o){this.#e=l(o)}get expressionType(){}get isRawBuilder(){return!0}as(o){return new es(this,o)}$castTo(){return new e({...this.#e})}$notNull(){return new e(this.#e)}withPlugin(o){return new e({...this.#e,plugins:this.#e.plugins!==void 0?l([...this.#e.plugins,o]):l([o])})}toOperationNode(){return this.#r(this.#o())}compile(o){return this.#t(this.#o(o))}async execute(o,t){let r=this.#o(o);return r.executeQuery(this.#t(r),t)}#o(o){let t=o!==void 0?o.getExecutor():Fn;return this.#e.plugins!==void 0?t.withPlugins(this.#e.plugins):t}#r(o){return o.transformQuery(this.#e.rawNode,this.#e.queryId)}#t(o){return o.compileQuery(this.#r(o),this.#e.queryId)}};es=class{#e;#o;constructor(o,t){this.#e=o,this.#o=t}get expression(){return this.#e}get alias(){return this.#o}get rawBuilder(){return this.#e}toOperationNode(){return Pe.create(this.#e.toOperationNode(),ie(this.#o)?this.#o.toOperationNode():P.create(this.#o))}}});function kd(e){return ie(e)?e.toOperationNode():G(e)}var S,Pd=m(()=>{ne();ze();ct();Bo();Me();so();$o();Ln();os();S=Object.assign((e,...o)=>Ao({queryId:Ie(),rawNode:le.create(e,o?.map(kd)??[])}),{ref(e){return Ao({queryId:Ie(),rawNode:le.createWithChild(Fe(e))})},val(e){return Ao({queryId:Ie(),rawNode:le.createWithChild(G(e))})},table(e){return Ao({queryId:Ie(),rawNode:le.createWithChild(Ne(e))})},id(...e){let o=new Array(e.length+1).fill(".");return o[0]="",o[o.length-1]="",Ao({queryId:Ie(),rawNode:le.create(o,e.map(P.create))})},lit(e){return Ao({queryId:Ie(),rawNode:le.createWithChild(Oe.createImmediate(e))})},raw(e){return Ao({queryId:Ie(),rawNode:le.createWithSql(e)})},join(e,o=S`, `){let t=new Array(Math.max(2*e.length-1,0)),r=o.toOperationNode();for(let n=0;n<e.length;++n)t[2*n]=kd(e[n]),n!==e.length-1&&(t[2*n+1]=r);return Ao({queryId:Ie(),rawNode:le.createWithChildren(t)})}})});var Td=m(()=>{});var Wq,Bq,Uq,ts=m(()=>{_();Wq=l({ForKeyShare:"for key share",ForNoKeyUpdate:"for no key update",ForUpdate:"for update",ForShare:"for share",NoWait:"nowait",SkipLocked:"skip locked",Distinct:"distinct"}),Bq=l({ForKeyShare:1,ForNoKeyUpdate:1,ForUpdate:1,ForShare:1,NoWait:2,SkipLocked:2,Distinct:0}),Uq=l({InnerJoin:"inner join",LeftJoin:"left join",RightJoin:"right join",FullJoin:"full join",CrossJoin:"cross join",LateralInnerJoin:"inner join lateral",LateralLeftJoin:"left join lateral",LateralCrossJoin:"cross join lateral",OuterApply:"outer apply",CrossApply:"cross apply",Using:"using"})});var wt,Rr=m(()=>{ct();_();Ln();wt=l({raw(e,o=[]){return l({sql:e,query:le.createWithSql(e),parameters:l(o),queryId:Ie()})}})});var Md=m(()=>{});var Id=m(()=>{});var Ld=m(()=>{});var Dd=m(()=>{});var zd=m(()=>{});var Fd=m(()=>{});var Wd=m(()=>{});function Jo(e,o){if(wb(e)&&o.stack){let t=o.stack.split(`
|
|
4
4
|
`).slice(1).join(`
|
|
5
5
|
`);return e.stack+=`
|
|
6
|
-
${t}`,e}return e}function ob(e){return Oe(e)&&W(e.stack)}var Sr=m(()=>{_()});function rb(e){return Oe(e)&&"insertId"in e&&"affectedRows"in e}var tb,Ed,qd=m(()=>{Or();_();Sr();tb=Symbol();Ed=class{#e;#o;#r;#t;constructor(o,t){this.#e=o,this.#o=t}async cancelQuery(o){await this.#i(`kill query ${this.#r}`,o)}async collectSessionInfo(){if(this.#r)return;let{threadId:o}=this.#e;if(o!=null)this.#r=o;else{let[{cid:t}]=await this.#n(pt.raw("select connection_id() as cid"));this.#r=Number(t)}}async executeQuery(o){try{this.#t=o.queryId;let t=await this.#n(o);if(!rb(t))return{rows:Array.isArray(t)?t:[]};let{insertId:n,affectedRows:r,changedRows:a}=t;return{insertId:n!=null&&n.toString()!=="0"?BigInt(n):void 0,numAffectedRows:r!=null?BigInt(r):void 0,numChangedRows:a!=null?BigInt(a):void 0,rows:[]}}catch(t){throw zo(t,new Error)}finally{this.#t=void 0}}async killSession(o){try{this.#e.destroy()}catch{}await this.#i(`kill connection ${this.#r}`,o)}async*streamQuery(o,t){this.#t=o.queryId;let n=this.#e.query(o.sql,o.parameters).stream({objectMode:!0});try{for await(let r of n)yield{rows:[r]}}catch(r){if(Oe(r)&&"code"in r&&r.code==="ERR_STREAM_PREMATURE_CLOSE")return;throw r}finally{this.#t=void 0}}[tb](){this.#e.release()}#n(o){return new Promise((t,n)=>{this.#e.query(o.sql,o.parameters,(r,a)=>{r?n(r):t(a)})})}async#i(o,t){if(!this.#t)return;let{config:n}=this.#e,r=this.#t;if(!this.#o||!n)return await t(async u=>{r.queryId===this.#t?.queryId&&await u.executeQuery(pt.raw(o,[]))});let{clientFlags:a,maxPacketSize:s,...l}=n,d=this.#o(l);try{await new Promise((u,p)=>{d.connect(f=>{if(f)return p(f);if(r.queryId!==this.#t?.queryId)return u();d.query(o,[],h=>{if(h)return p(h);u()})})})}finally{d.destroy()}}}});var kd=m(()=>{});var Rd=m(()=>{});var Pd=m(()=>{});var Td=m(()=>{});var nb,Md,Id=m(()=>{Or();Sr();nb=Symbol(),Md=class{#e;#o;#r;#t;constructor(o,t){this.#e=o,this.#o=t}async cancelQuery(o){return await this.#n(`select pg_cancel_backend(${this.#t})`,o)}async collectSessionInfo(){if(this.#t)return;let{processID:o}=this.#e;if(o)this.#t=o;else{let{rows:[{pid:t}]}=await this.#e.query("select pg_backend_pid() as pid",[]);this.#t=Number(t)}}async executeQuery(o){try{this.#r=o.queryId;let t=await this.#e.query(o.sql,o.parameters),{command:n,rowCount:r,rows:a}=t;return{numAffectedRows:n==="INSERT"||n==="UPDATE"||n==="DELETE"||n==="MERGE"?BigInt(r):void 0,rows:a??[]}}catch(t){throw zo(t,new Error)}finally{this.#r=void 0}}async killSession(o){return await this.#n(`select pg_terminate_backend(${this.#t})`,o)}async*streamQuery(o,t){if(!this.#o.cursor)throw new Error("`cursor` is not present in your postgres dialect config. It's required to make streaming work in postgres.");this.#r=o.queryId;let n=this.#e.query(new this.#o.cursor(o.sql,o.parameters.slice()));try{for(;;){let r=await n.read(t);if(r.length===0)break;yield{rows:r}}}finally{await n.close(),this.#r=void 0}}[nb](){this.#e.release()}async#n(o,t){if(!this.#r)return;let{controlClient:n,poolOptions:r}=this.#o,a=this.#r;if(!n)return await t(async l=>{a.queryId===this.#r?.queryId&&await l.executeQuery(pt.raw(o,[]))});let s=new n({...r,password:"password"in r?r.password:void 0});try{if(await s.connect(),a.queryId!==this.#r.queryId)return;await s.query(o,[])}finally{s.end()}}}});var Dd=m(()=>{});var Ld=m(()=>{});var Mq,Iq,zd=m(()=>{Mq=BigInt("3853314791062309107"),Iq=3600*1e3});var Fd=m(()=>{});var Wd=m(()=>{});var ib,ab,sb,Bd,jr,Ud=m(()=>{_();Or();Sr();ha();xr();ib=Symbol(),ab=Symbol(),sb=Symbol(),Bd=class{#e;#o;#r;#t;constructor(o,t){this.#e=o,this.#o=!1,this.#r=t}async beginTransaction(o){let{isolationLevel:t}=o;await new Promise((n,r)=>this.#e.beginTransaction(a=>{a?r(a):n(void 0)},t?jn(8):void 0,t?this.#n(t):void 0))}async cancelQuery(){if(this.#t)return new Promise(o=>{this.#t?.request.once("requestCompleted",o),this.#e.cancel()||(this.#t?.request.off("requestCompleted",o),o())})}async commitTransaction(){await new Promise((o,t)=>this.#e.commitTransaction(n=>{n?t(n):o(void 0)}))}async connect(){let{promise:o,reject:t,resolve:n}=new je;this.#e.connect(a=>{if(a)return t(a);n()}),this.#e.on("error",a=>{a instanceof Error&&"code"in a&&a.code==="ESOCKET"&&(this.#o=!0),console.error(a),t(a)});function r(){t(new Error("The connection ended without ever completing the connection"))}return this.#e.once("end",r),await o,this.#e.off("end",r),this}async executeQuery(o){try{let t=new je;this.#t=new jr({compiledQuery:o,tedious:this.#r,onDone:t}),this.#e.execSql(this.#t.request);let{rowCount:n,rows:r}=await t.promise;return{numAffectedRows:n!==void 0?BigInt(n):void 0,rows:r}}catch(t){throw zo(t,new Error)}finally{this.#t=void 0}}async rollbackTransaction(o){await new Promise((t,n)=>this.#e.rollbackTransaction(r=>{r?n(r):t(void 0)},o))}async savepoint(o){await new Promise((t,n)=>this.#e.saveTransaction(r=>{r?n(r):t(void 0)},o))}async*streamQuery(o,t){this.#t=new jr({compiledQuery:o,streamChunkSize:t,tedious:this.#r}),this.#e.execSql(this.#t.request);try{for(;;){let n=await this.#t.readChunk();if(n.length===0||(yield{rows:n},n.length<t))break}}finally{await this.cancelQuery(),this.#t=void 0}}#n(o){let{ISOLATION_LEVEL:t}=this.#r,r={"read committed":t.READ_COMMITTED,"read uncommitted":t.READ_UNCOMMITTED,"repeatable read":t.REPEATABLE_READ,serializable:t.SERIALIZABLE,snapshot:t.SNAPSHOT}[o];if(r===void 0)throw new Error(`Unknown isolation level: ${o}`);return r}[ab](){return"closed"in this.#e&&this.#e.closed?Promise.resolve():new Promise(o=>{this.#e.once("end",o),this.#e.close()})}async[ib](){await new Promise((o,t)=>{this.#e.reset(n=>{if(n)return t(n);o()})})}async[sb](){if(this.#o||this.#i())return!1;try{let o=new je,t=new jr({compiledQuery:pt.raw("select 1"),onDone:o,tedious:this.#r});return this.#e.execSql(t.request),await o.promise,!0}catch{return!1}}#i(){return"closed"in this.#e&&!!this.#e.closed}},jr=class{#e;#o;#r;#t;#n;#i;constructor(o){let{compiledQuery:t,onDone:n,streamChunkSize:r,tedious:a}=o;if(this.#o=[],this.#r=r,this.#t={},this.#n=a,n){let s="onDone";this.#t[s]=(l,d)=>{if(l!=="chunkReady"){if(delete this.#t[s],l==="error")return n.reject(d);n.resolve({rowCount:this.#i,rows:this.#o})}}}this.#e=new this.#n.Request(t.sql,(s,l)=>{if(s)return Object.values(this.#t).forEach(d=>d("error",s instanceof AggregateError?s.errors:s));this.#i=l}),this.#a(t.parameters),this.#s()}get request(){return this.#e}readChunk(){let o=this.readChunk.name;return new Promise((t,n)=>{this.#t[o]=(r,a)=>{if(delete this.#t[o],r==="error")return n(a);t(this.#o.splice(0,this.#r))},this.#e.resume()})}#a(o){for(let t=0;t<o.length;t++){let n=o[t];this.#e.addParameter(String(t+1),this.#c(n),n)}}#s(){let o=this.#r?()=>{this.#r<=this.#o.length&&(this.#e.pause(),Object.values(this.#t).forEach(n=>n("chunkReady")))}:()=>{},t=n=>{let r={};for(let a of n)r[a.metadata.colName]=a.value;this.#o.push(r),o()};this.#e.on("row",t),this.#e.once("requestCompleted",()=>{Object.values(this.#t).forEach(n=>n("completed")),this.#e.off("row",t)})}#c(o){return Ko(o)||ho(o)||W(o)?this.#n.TYPES.NVarChar:Zo(o)||oo(o)&&o%1===0?o<-2147483648||o>2147483647?this.#n.TYPES.BigInt:this.#n.TYPES.Int:oo(o)?this.#n.TYPES.Float:Yo(o)?this.#n.TYPES.Bit:Ri(o)?this.#n.TYPES.DateTime:Fc(o)?this.#n.TYPES.VarBinary:this.#n.TYPES.NVarChar}}});var Vd=m(()=>{});var Jd=m(()=>{});var Qd=m(()=>{});var Gd=m(()=>{});var cb,lb,ub,Hd,Xd=m(()=>{xr();Sr();cb=Symbol(),lb=Symbol(),ub=Symbol(),Hd=class{#e;#o;#r;#t;#n;constructor(o){this.#e=o}async executeQuery(o){try{let{affectedRows:t,rows:n}=await(this.#t||this.#e).query(o.sql,o.parameters,{rowMode:"object"});return{numAffectedRows:t!=null?BigInt(t):void 0,rows:n||[]}}catch(t){throw zo(t,new Error)}}async*streamQuery(){throw new Error("Streaming is not supported by PGlite.")}async[cb](){let{promise:o,reject:t,resolve:n}=new je,{promise:r,resolve:a}=new je;this.#o=n,this.#r=t,this.#n=this.#e.transaction(async s=>{this.#t=s,a(),await o}),await r}async[lb](){this.#o?.(),await this.#n,this.#o=void 0,this.#r=void 0,this.#t=void 0,this.#n=void 0}async[ub](){this.#r?.(),await this.#n?.catch(()=>{}),this.#o=void 0,this.#r=void 0,this.#t=void 0,this.#n=void 0}}});var Yd=m(()=>{});var Kd=m(()=>{});var Zd=m(()=>{});var ep=m(()=>{});var op=m(()=>{});var tp=m(()=>{});var rp=m(()=>{});var np=m(()=>{});var ip=m(()=>{});var Fn=m(()=>{vd();Zl();ld();Zr();Ft();Sa();Ml();Dl();Il();Nr();ia();ka();ql();da();ma();Rl();qa();Pa();Da();Kl();Yl();Ii();Qa();_d();fd();Rn();Ga();Or();dd();Qu();td();Xu();nd();Vu();Gu();Ju();Hu();qu();Pu();Uu();Ku();ad();ed();Lu();Bu();pd();sn();Ba();gd();md();hd();$d();xd();Ad();Cd();Od();Sd();jd();Td();qd();kd();Rd();Pd();Id();Fd();Ld();Dd();zd();Wd();Qd();Ud();Vd();Jd();Gd();Xd();Yd();Ga();Kd();Zd();Ul();ep();op();tp();rp();$u();Tu();Fu();Tn();go();Du();Bc();Ro();on();Mn();Wa();Su();Mi();xu();Qe();la();Ll();zl();np();Uc();Vc();Jc();od();Yu();id();Fa();Sl();Eu();yn();Cu();Iu();Qc();Gc();Hc();rd();Zu();oa();Ca();Ru();br();Aa();Au();ya();Ji();Gi();te();Hi();dr();pn();Ma();pr();un();$r();Xi();Vl();ta();ku();va();kl();El();Ti();Le();Bl();Nd();jt();Tl();ot();cn();hr();na();wn();fr();aa();Ui();zu();zi();_o();tt();nn();Ua();Ou();Wu();ea();et();rn();Pi();yr();sa();_a();ip();ur();ua();za();Ra();Mu();vn();Ki();fn();Io();Ol();vr();wr();Fl();sd();cd();ud();wd();bd()});function ap(e){let o=Vt(e,["version","origen","entidades"]);if(o.version!==1)throw i("Perfil relacional inv\xE1lido.");let t=Ar(o.entidades,60).map(r=>{let a=Vt(r,["clave","destino","clave_externa","campos","referencias","procedencia","responsable","tipos","tiposColumna","acl","archivos"]);if(typeof a.destino!="string"||!(["contacts","companies","deals"].includes(a.destino)||/^mod_[a-z][a-z0-9_]{0,40}$/.test(a.destino)))throw i("Perfil relacional inv\xE1lido.");let s=Object.fromEntries(Object.entries(Vt(a.campos)).map(([b,y])=>(Ha(b),[b,Jt(y)])));if(Object.keys(s).length>100)throw i("Perfil relacional inv\xE1lido.");let l=Ar(a.referencias??[],30).map(b=>{let y=Vt(b,["campo","entidad","clave","obligatoria"]);if(y.obligatoria!==void 0&&typeof y.obligatoria!="boolean")throw i("Perfil relacional inv\xE1lido.");return{campo:Ha(y.campo),entidad:Wn(y.entidad),clave:Xa(y.clave),obligatoria:y.obligatoria===!0}}),d=a.archivos===void 0?void 0:Ar(a.archivos,20).map(b=>{let y=Vt(b,["campo","columna","obligatorio"]);if(y.obligatorio!==void 0&&typeof y.obligatorio!="boolean")throw i("Perfil relacional inv\xE1lido.");return{campo:Ha(y.campo),columna:Jt(y.columna),obligatorio:y.obligatorio===!0}});if(d?.length&&!a.destino.startsWith("mod_"))throw i("Perfil relacional inv\xE1lido.");let u=[...(d??[]).map(b=>b.campo),...Object.keys(s),...l.map(b=>b.campo)];if(new Set(u).size!==u.length)throw i("Perfil relacional inv\xE1lido.");let p=a.procedencia===void 0?void 0:Object.fromEntries(Object.entries(Vt(a.procedencia,["autor","creado","actualizado"])).map(([b,y])=>[b,Jt(y)])),f=a.responsable===void 0?void 0:Xa(a.responsable),h=a.tipos===void 0?void 0:Ar(a.tipos,20).map(b=>{if(typeof b!="string"||!/^[a-z0-9][a-z0-9-]{0,59}$/.test(b))throw i("Perfil relacional inv\xE1lido.");return b});if(h&&!["contacts","companies"].includes(a.destino))throw i("Perfil relacional inv\xE1lido.");if(a.tiposColumna!==void 0&&(!h?.length||new Set(h).size!==h.length))throw i("Perfil relacional inv\xE1lido.");return{clave:Wn(a.clave),...a.acl!==void 0?{acl:Jt(a.acl)}:{},...d?{archivos:d}:{},destino:a.destino,...p?{procedencia:p}:{},...f?{responsable:f}:{},...h?{tipos:h}:{},...a.tiposColumna!==void 0?{tiposColumna:Jt(a.tiposColumna)}:{},clave_externa:Xa(a.clave_externa),campos:s,referencias:l}}),n=new Map(t.map(r=>[r.clave,r]));if(!t.length||n.size!==t.length||t.some(r=>r.referencias.some(a=>!n.has(a.entidad)||n.get(a.entidad).clave_externa.length!==a.clave.length)))throw i("Perfil relacional inv\xE1lido.");return{version:1,origen:Wn(o.origen),entidades:t}}var Wn,Ha,Jt,Vt,Ar,Xa,sp=m(()=>{q();Wn=e=>{if(typeof e!="string"||!/^[a-z][a-z0-9_]{0,60}$/.test(e))throw i("Perfil relacional inv\xE1lido.");return e},Ha=e=>{let o=typeof e=="string"&&/^datos\.[a-z][a-z0-9_]{0,60}$/.test(e)?e:Wn(e);if(["id","sales_id","espacio_id","modulo_id","creado_por","actualizado_por","responsable_id"].includes(o))throw i("Perfil relacional inv\xE1lido.");return o},Jt=e=>{if(typeof e!="string"||!/^[a-zA-Z][a-zA-Z0-9_]{0,79}$/.test(e)||/password|passwd|token|(^|_)pin($|_)|secret/i.test(e)||["constructor","prototype","__proto__"].includes(e))throw i("Perfil relacional inv\xE1lido.");return e},Vt=(e,o)=>{if(!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).some(t=>["__proto__","constructor","prototype"].includes(t)||o&&!o.includes(t)))throw i("Perfil relacional inv\xE1lido.");return e},Ar=(e,o)=>{if(!Array.isArray(e)||e.length>o)throw i("Perfil relacional inv\xE1lido.");return e},Xa=e=>{let o=Ar(e,3).map(Jt);if(!o.length||new Set(o).size!==o.length)throw i("Perfil relacional inv\xE1lido.");return o}});function cp(e){if(e===void 0)return[];if(!Array.isArray(e)||e.length>30)throw i("Perfiles de importaci\xF3n inv\xE1lidos.");let o=new Set;return e.map(t=>{if(!t||typeof t!="object"||Array.isArray(t)||Object.keys(t).some(r=>!["clave","perfil"].includes(r)))throw i("Perfiles de importaci\xF3n inv\xE1lidos.");let n=t;if(typeof n.clave!="string"||!/^[a-z][a-z0-9_]{0,60}$/.test(n.clave)||o.has(n.clave))throw i("Perfiles de importaci\xF3n inv\xE1lidos.");return o.add(n.clave),{clave:n.clave,perfil:ap(n.perfil)}})}var lp=m(()=>{q();sp()});function Ya(e){return/^funciones\.([a-z0-9][a-z0-9-]{0,59})\.[a-z][a-z0-9_]{0,40}$/.exec(e)?.[1]}function pb(e,o){return e==="contacts"&&/^(correo|telefono)(_(trabajo|personal))?$/.test(o)?o.startsWith("correo")?"email_jsonb":"phone_jsonb":db[e].includes(o)||/^datos\.[a-z][a-z0-9_]{0,40}$/.test(o)||Ya(o)?o:null}function up(e){if(e===void 0)return[];if(!Array.isArray(e)||e.length>100)throw i("Identidades: hasta 100 restricciones por tipo.");let o=new Set;return e.map(t=>{if(!t||typeof t!="object"||Array.isArray(t))throw i("Restricci\xF3n de identidad no v\xE1lida.");let n=t;if(Object.keys(n).some(l=>!["objeto","tipo","nivel","campos"].includes(l))||!["contacts","companies"].includes(String(n.objeto))||typeof n.tipo!="string"||!/^[a-z0-9][a-z0-9-]{0,59}$/.test(n.tipo)||n.nivel!==void 0&&!["normal","no","lectura"].includes(String(n.nivel)))throw i("Restricci\xF3n de identidad no v\xE1lida.");let r=n.objeto,a=`${r}:${n.tipo}`;if(o.has(a))throw i("Restricci\xF3n de identidad repetida.");o.add(a);let s={};if(n.campos!==void 0){if(!n.campos||typeof n.campos!="object"||Array.isArray(n.campos)||Object.keys(n.campos).length>100)throw i("M\xE1scaras de identidad no v\xE1lidas.");for(let[l,d]of Object.entries(n.campos)){let u=pb(r,l);if(!u||Ya(u)&&Ya(u)!==n.tipo||!["normal","lectura","oculto"].includes(String(d))||Object.hasOwn(s,u))throw i("Campo o nivel de identidad no v\xE1lido.");s[u]=d}}return{objeto:r,tipo:n.tipo,...n.nivel!==void 0?{nivel:n.nivel}:{},...Object.keys(s).length?{campos:s}:{}}})}var db,dp=m(()=>{q();db={contacts:["nif","iban","birthday","gender","address","zipcode","city","province","country","email_jsonb","phone_jsonb"],companies:["tax_identifier","iban","phone_number","correo_facturacion","address","zipcode","city","state_abbr","country"]}});function pp(e){if(e==null)return;let o=Bn(e,["destino","anterior","ciclo","copiar","fechas","estado","precios"]);if(!o.copiar||typeof o.copiar!="object"||Array.isArray(o.copiar)||Object.keys(o.copiar).length>50||!Array.isArray(o.fechas)||!o.fechas.length||o.fechas.length>10)throw i("Sucesi\xF3n: configuraci\xF3n inv\xE1lida.");let t={anterior:Me(o.anterior),ciclo:Me(o.ciclo),copiar:Object.fromEntries(Object.entries(o.copiar).map(([n,r])=>[Me(n),Me(r)])),fechas:o.fechas.map(n=>{let r=Bn(n,["campo","desde","meses"]);if(typeof r.meses!="number"||!Number.isInteger(r.meses)||r.meses<1||r.meses>120)throw i("Sucesi\xF3n: configuraci\xF3n inv\xE1lida.");return{campo:Me(r.campo),desde:Me(r.desde),meses:r.meses}})};if(o.destino!==void 0&&(t.destino=Me(o.destino)),o.estado){let n=Bn(o.estado,["campo","valor"]);if(typeof n.valor!="string"||n.valor.length>100)throw i("Sucesi\xF3n: configuraci\xF3n inv\xE1lida.");t.estado={campo:Me(n.campo),valor:n.valor}}if(o.precios){let n=Bn(o.precios,["tabla","fecha","claves","valor","destino"]);if(!Array.isArray(n.claves)||n.claves.length<1||n.claves.length>3)throw i("Sucesi\xF3n: configuraci\xF3n inv\xE1lida.");t.precios={tabla:Me(n.tabla),fecha:Me(n.fecha),claves:n.claves.map(Me),valor:Me(n.valor),destino:Me(n.destino)}}if(new Set(t.fechas.map(n=>n.campo)).size!==t.fechas.length)throw i("Sucesi\xF3n: configuraci\xF3n inv\xE1lida.");return t}var Me,Bn,mp=m(()=>{q();Me=e=>{if(typeof e!="string"||!/^[a-z][a-z0-9_]{0,40}$/.test(e))throw i("Sucesi\xF3n: configuraci\xF3n inv\xE1lida.");return e},Bn=(e,o)=>{if(!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).some(t=>!o.includes(t)))throw i("Sucesi\xF3n: configuraci\xF3n inv\xE1lida.");return e}});var Er,GT,mb,fp=m(()=>{Er=class e{n;d;constructor(o,t=1n){if(t===0n)throw new Error("decimal_division_cero");t<0n&&(o=-o,t=-t);let n=(a,s)=>s===0n?a<0n?-a:a:n(s,a%s),r=n(o,t);this.n=o/r,this.d=t/r}static leer(o){if(typeof o!="string"||!/^-?\d{1,18}(\.\d{1,6})?$/.test(o))throw new Error("decimal_invalido");let[t,n=""]=o.split(".");return new e(BigInt(t+n),10n**BigInt(n.length))}sumar(o){return new e(this.n*o.d+o.n*this.d,this.d*o.d)}restar(o){return this.sumar(new e(-o.n,o.d))}por(o){return new e(this.n*o.n,this.d*o.d)}entre(o){return new e(this.n*o.d,this.d*o.n)}comparar(o){let t=this.n*o.d-o.n*this.d;return t<0n?-1:t>0n?1:0}centimos(){let t=((this.n<0n?-this.n:this.n)*100n*2n+this.d)/(this.d*2n);return this.n<0n?-t:t}texto(){return mb(this.centimos())}},GT=new Er(0n),mb=e=>`${e<0n?"-":""}${(e<0n?-e:e)/100n}.${String((e<0n?-e:e)%100n).padStart(2,"0")}`});function gp(e,o){if(e==null)return;let t=he(e,["version","beneficiariosPeriodo","origen","fecha","importe","moneda","unidad","grupo","mantenimiento","ciclo","recuperacion","beneficiarios","motor","documento","cuentan","precios","unidad_recuento","componentes"]),n=he(t.motor,["reglas","combinar","margenNegativo","equipoPropio","principal","minimo","objetivo","fijoPeriodo"]),r=he(t.documento,["periodo","estado","total","beneficiario","lineas"]);if(t.version!==2||typeof t.origen!="string"||!/^mod_[a-z][a-z0-9_]{0,40}$/.test(t.origen))throw i("Liquidaci\xF3n v2: versi\xF3n u origen inv\xE1lido.");let a=(w,g)=>{let N=Z(w);if(!o.some(C=>C.clave===N&&!C.archivado&&C.tipo===g))throw i("Liquidaci\xF3n v2: campo de documento inv\xE1lido.");return N},s=Object.fromEntries(Object.entries(he(t.beneficiarios)).map(([w,g])=>{let N=he(g,["tipo","campo"]);return[Z(w),{tipo:ft(N.tipo,["miembro","contacts","companies","registro"]),campo:N.campo==="_dueno"?"_dueno":Z(N.campo)}]}));if(!Object.keys(s).length||Object.keys(s).length>20)throw i("Liquidaci\xF3n v2: beneficiarios inv\xE1lidos.");let l=w=>{let g=he(w,["clave","beneficiario","fijo","porcentaje","resto","equipo","minimo"]),N=Z(g.beneficiario);if(!s[N])throw i("Liquidaci\xF3n v2: beneficiario desconocido.");return{clave:Z(g.clave),beneficiario:N,...g.fijo!==void 0?{fijo:mt(g.fijo)}:{},...g.porcentaje!==void 0?{porcentaje:Ka(g.porcentaje)}:{},...g.resto===!0?{resto:!0}:{},...g.equipo===!0?{equipo:!0}:{},...typeof g.minimo=="boolean"?{minimo:g.minimo}:{}}},d=Fo(n.reglas).map(w=>{let g=he(w,["clave","prioridad","modo","desde","hasta","moneda","unidad","si","bolsa","retencion","receptores"]);if(!hp(g.desde)||g.hasta!==void 0&&(!hp(g.hasta)||g.hasta<=g.desde))throw i("Liquidaci\xF3n v2: vigencia inv\xE1lida.");if(typeof g.moneda!="string"||!/^[A-Z]{3}$/.test(g.moneda)||typeof g.unidad!="string"||!g.unidad||g.unidad.length>60)throw i("Liquidaci\xF3n v2: moneda o unidad inv\xE1lida.");let N=g.si===void 0?void 0:he(g.si,["campo","valores"]);return{clave:Z(g.clave),prioridad:Un(g.prioridad),modo:ft(g.modo,["exclusiva","acumulable"]),desde:g.desde,...g.hasta?{hasta:g.hasta}:{},moneda:g.moneda,unidad:g.unidad,receptores:Fo(g.receptores).map(l),...g.bolsa!==void 0?{bolsa:mt(g.bolsa)}:{},...g.retencion!==void 0?{retencion:mt(g.retencion)}:{},...N?{si:{campo:Z(N.campo),valores:Fo(N.valores).map(C=>String(C).slice(0,100))}}:{}}});if(new Set(d.map(w=>w.clave)).size!==d.length)throw i("Liquidaci\xF3n v2: regla duplicada.");let u;if(n.objetivo){let w=he(n.objetivo,["beneficiario","medida","modo","tramos","consumirBolsa"]),g=Fo(w.tramos).map(N=>{let C=he(N,["desde","tasa","garantia","bonus"]);return{desde:Un(C.desde),tasa:w.medida==="recuento"?mt(C.tasa):Ka(C.tasa),...C.garantia!==void 0?{garantia:mt(C.garantia)}:{},...C.bonus!==void 0?{bonus:mt(C.bonus)}:{}}});if(!g.length||g[0].desde!==0||g.some((N,C)=>C>0&&N.desde<=g[C-1].desde))throw i("Liquidaci\xF3n v2: umbrales inv\xE1lidos.");u={beneficiario:Z(w.beneficiario),medida:ft(w.medida,["recuento","importe"]),modo:ft(w.modo,["alcanzado","marginal"]),tramos:g,consumirBolsa:w.consumirBolsa===!0}}let p=n.minimo?he(n.minimo,["cantidad","modo"]):void 0,f=n.fijoPeriodo?Fo(n.fijoPeriodo).map(w=>{let g=he(w,["beneficiario","importe"]);return{beneficiario:Z(g.beneficiario),importe:mt(g.importe)}}):void 0;if(f&&new Set(f.map(w=>w.beneficiario)).size!==f.length)throw i("Liquidaci\xF3n v2: fijo de periodo duplicado.");let h={version:2,origen:t.origen,fecha:Z(t.fecha),importe:Z(t.importe),moneda:Z(t.moneda),unidad:Z(t.unidad),grupo:t.grupo==="_dueno"?"_dueno":Z(t.grupo),beneficiarios:s,motor:{reglas:d,combinar:n.combinar===!0,margenNegativo:n.margenNegativo===!0,equipoPropio:n.equipoPropio===!0,...n.principal?{principal:Z(n.principal)}:{},...p?{minimo:{cantidad:Un(p.cantidad),modo:ft(p.modo,["umbral","franquicia"])}}:{},...u?{objetivo:u}:{},...f?{fijoPeriodo:f}:{}},documento:{periodo:a(r.periodo,"texto"),estado:a(r.estado,"seleccion"),total:a(r.total,"texto"),beneficiario:a(r.beneficiario,"texto"),lineas:a(r.lineas,"subtabla")},...t.mantenimiento?{mantenimiento:Z(t.mantenimiento)}:{}};if(t.beneficiariosPeriodo!==void 0&&(h.beneficiariosPeriodo=Fo(t.beneficiariosPeriodo,1e4).map(w=>{let g=he(w,["grupo","beneficiarios"]);if(typeof g.grupo!="string"||!g.grupo||g.grupo.length>100)throw i("Liquidaci\xF3n v2: grupo de periodo inv\xE1lido.");let N=Object.fromEntries(Object.entries(he(g.beneficiarios)).map(([C,S])=>{if(!s[C]||typeof S!="number"||!Number.isSafeInteger(S)||S<1)throw i("Liquidaci\xF3n v2: beneficiario de periodo inv\xE1lido.");return[C,S]}));return{grupo:g.grupo,beneficiarios:N}}),new Set(h.beneficiariosPeriodo.map(w=>w.grupo)).size!==h.beneficiariosPeriodo.length))throw i("Liquidaci\xF3n v2: grupo de periodo duplicado.");if(t.cuentan){let w=he(t.cuentan,["campo","valores"]);h.cuentan={campo:Z(w.campo),valores:Fo(w.valores).map(String)}}if(t.unidad_recuento&&(h.unidad_recuento=Z(t.unidad_recuento)),t.componentes){let w=he(t.componentes,["modo","campo"]);h.componentes={modo:ft(w.modo,["todos","principal"]),campo:Z(w.campo)}}if(t.precios){let w=he(t.precios,["tabla","fecha","claves","valor"]);if(h.precios={tabla:Z(w.tabla),fecha:Z(w.fecha),claves:Fo(w.claves,3).map(Z),valor:Z(w.valor)},!h.precios.claves.length)throw i("Liquidaci\xF3n v2: claves de precio ausentes.")}if(t.ciclo&&(h.ciclo=Z(t.ciclo)),t.recuperacion){let w=he(t.recuperacion,["modo","plazo"]);if(h.recuperacion={modo:ft(w.modo,["total","proporcional_dias"]),plazo:Un(w.plazo)},h.recuperacion.plazo===0)throw i("Liquidaci\xF3n v2: plazo inv\xE1lido.")}if([h.motor.principal,h.motor.objetivo?.beneficiario,...(h.motor.fijoPeriodo??[]).map(w=>w.beneficiario)].some(w=>w&&!s[w]))throw i("Liquidaci\xF3n v2: beneficiario desconocido.");let b=o.find(w=>w.clave===h.documento.lineas);if(["fuente","concepto","importe"].some(w=>!b.columnas?.some(g=>g.clave===w&&g.tipo==="texto"&&!g.archivado)))throw i("Liquidaci\xF3n v2: columnas de resumen inv\xE1lidas.");let y=o.find(w=>w.clave===h.documento.estado);if(["borrador","aprobada","cerrada","pagada"].some(w=>!y.opciones?.some(g=>g.valor===w)))throw i("Liquidaci\xF3n v2: estados inv\xE1lidos.");return h}var he,hp,Z,Ka,mt,Fo,ft,Un,bp=m(()=>{q();fp();he=(e,o)=>{if(!e||typeof e!="object"||Array.isArray(e))throw i("Liquidaci\xF3n v2: objeto inv\xE1lido.");if(o&&Object.keys(e).some(t=>!o.includes(t)))throw i("Liquidaci\xF3n v2: propiedad desconocida.");return e},hp=e=>typeof e=="string"&&/^\d{4}-\d{2}-\d{2}$/.test(e)&&Number.isFinite(Date.parse(e+"T00:00:00Z"))&&new Date(e+"T00:00:00Z").toISOString().slice(0,10)===e,Z=e=>{if(typeof e!="string"||!/^[a-z][a-z0-9_]{0,40}$/.test(e))throw i("Liquidaci\xF3n v2: clave inv\xE1lida.");return e},Ka=e=>{if(typeof e!="string")throw i("Liquidaci\xF3n v2: decimal como cadena.");try{if(Er.leer(e).n<0n)throw new Error("negativo")}catch{throw i("Liquidaci\xF3n v2: decimal inv\xE1lido.")}return e},mt=e=>{let o=Ka(e);if(!/^\d{1,18}(?:\.\d{1,2})?$/.test(o))throw i("Liquidaci\xF3n v2: el importe manual admite como m\xE1ximo dos decimales.");return o},Fo=(e,o=20)=>{if(!Array.isArray(e)||e.length>o)throw i("Liquidaci\xF3n v2: lista inv\xE1lida.");return e},ft=(e,o)=>{if(!o.includes(e))throw i("Liquidaci\xF3n v2: opci\xF3n inv\xE1lida.");return e},Un=e=>{if(typeof e!="number"||!Number.isSafeInteger(e)||e<0)throw i("Liquidaci\xF3n v2: entero inv\xE1lido.");return e}});function wp(e,o){if(e==null)return;if(typeof e!="object"||Array.isArray(e))throw i("precios: un objeto.");let t=e,n=["claves","desde","hasta","prioridad","moneda","unidad","valores","solape","falta"];if(Object.keys(t).some(s=>!n.includes(s)))throw i("precios: propiedad desconocida.");let r=(s,l)=>{let d=o.find(u=>u.clave===s&&!u.archivado);if(!d||!l.includes(d.tipo)||d.multiple)throw i("precios: campo inv\xE1lido.");return d.clave},a=(s,l,d)=>{if(!Array.isArray(s)||!s.length||s.length>d||new Set(s).size!==s.length)throw i("precios: lista vac\xEDa, duplicada o demasiado larga.");return s.map(u=>r(u,l))};if(!["bloquear","prioridad"].includes(String(t.solape))||!["bloquear","pendiente"].includes(String(t.falta)))throw i("precios: pol\xEDtica inv\xE1lida.");return{claves:a(t.claves,["texto","seleccion","relacion","numero"],3),desde:r(t.desde,["fecha"]),...t.hasta?{hasta:r(t.hasta,["fecha"])}:{},prioridad:r(t.prioridad,["numero"]),moneda:r(t.moneda,["texto","seleccion"]),unidad:r(t.unidad,["texto","seleccion"]),valores:a(t.valores,["importe","numero","porcentaje"],20),solape:t.solape,falta:t.falta}}var vp=m(()=>{q()});function qr(e,o){if(!Array.isArray(o)||o.length<1||o.length>100)throw i("Una lista lleva entre 1 y 100 elementos.");let t=new Set,n=o.map((r,a)=>{let s=r&&typeof r=="object"?r:{},l=typeof s.value=="string"?s.value.trim():"",d=typeof s.label=="string"?s.label.trim():"";if(!l||l.length>80||!Za(l))throw i(`El elemento ${a+1} no tiene una clave v\xE1lida.`);if(!d||d.length>80||!Za(d))throw i(`El elemento ${a+1} necesita un nombre (hasta 80 caracteres).`);if(t.has(l))throw i(`La clave \xAB${l}\xBB est\xE1 repetida.`);t.add(l);let u={value:l,label:d};if(s.color!==void 0&&s.color!==null&&s.color!==""){if(typeof s.color!="string"||!gb.test(s.color))throw i(`El color de \xAB${d}\xBB no es v\xE1lido.`);u.color=s.color}return s.archivado===!0&&(u.archivado=!0),e==="contactTypes"&&Object.assign(u,bb(s,d)),u});if(!n.some(r=>!r.archivado))throw i("Una lista necesita al menos un elemento sin archivar.");if(e==="dealStages")for(let r of fb){let a=n.find(s=>s.value===r);if(!a)throw new z(400,"etapa_fija","Las etapas \xABGanada\xBB y \xABPerdida\xBB no se pueden quitar; se pueden renombrar.");if(a.archivado)throw new z(400,"etapa_fija","Las etapas \xABGanada\xBB y \xABPerdida\xBB no se pueden archivar; se pueden renombrar.")}if(e==="contactTypes"){for(let s of yp){let l=n.find(d=>d.value===s);if(!l)throw new z(400,"tipo_fijo","Los tipos \xABCliente\xBB y \xABProveedor\xBB no se pueden quitar; se pueden renombrar.");if(l.archivado)throw new z(400,"tipo_fijo","Los tipos \xABCliente\xBB y \xABProveedor\xBB no se pueden archivar; se pueden renombrar.")}let r=n.find(s=>!/^[a-z0-9][a-z0-9-]{0,59}$/.test(s.value));if(r)throw i(`La clave \xAB${r.value}\xBB de un tipo: min\xFAsculas, n\xFAmeros y guiones.`);let a=n.find(s=>s.de&&yp.includes(s.value));if(a)throw i(`\xAB${a.label}\xBB no puede ser un tipo de otro.`)}if(e==="legalForms"){let r=n.find(a=>!/^[a-z0-9][a-z0-9-]{0,59}$/.test(a.value));if(r)throw i(`La clave \xAB${r.value}\xBB de una forma jur\xEDdica: min\xFAsculas, n\xFAmeros y guiones.`)}return n}function bb(e,o){let t=typeof e.plural=="string"&&e.plural.trim()?e.plural.trim():o;if(t.length>80||!Za(t))throw i(`El plural de \xAB${o}\xBB: hasta 80 caracteres.`);let n={plural:t,objeto:e.objeto==="companies"?"companies":"contacts",menu:e.menu===!0};if(e.objetos!==void 0){if(!Array.isArray(e.objetos)||e.objetos.length<1||e.objetos.length>2||new Set(e.objetos).size!==e.objetos.length||!e.objetos.includes(n.objeto)||e.objetos.some(r=>r!=="contacts"&&r!=="companies"))throw i("Las listas del tipo deben incluir su objeto principal y solo Personas o Empresas, sin repetir.");n.objetos=e.objetos}if(e.de!==void 0&&e.de!==null&&e.de!==""){if(e.de!=="cliente"&&e.de!=="proveedor")throw i(`\xAB${o}\xBB: solo puede ser un tipo de Cliente o de Proveedor.`);n.de=e.de}if(e.icono!==void 0&&e.icono!==null&&e.icono!==""){if(typeof e.icono!="string"||!hb.test(e.icono))throw i(`El icono de \xAB${o}\xBB no es v\xE1lido.`);n.icono=e.icono}return n}var fb,yp,hb,Za,gb,os=m(()=>{q();fb=["won","lost"],yp=["cliente","proveedor"],hb=/^[a-z0-9-]{1,40}$/,Za=e=>!/[\u0000-\u001f\u007f]/.test(e),gb=/^#[0-9a-fA-F]{3,8}$|^[a-z]{3,20}$/});function _p(e,o,t){if(e.propiedad!==void 0){if(!Ee(e.propiedad)||o.tipo!=="seleccion"||!o.obligatorio||e.formas!==void 0||e.etiquetas!==void 0||e.vacio!==void 0)throw i("La clasificaci\xF3n propia necesita una selecci\xF3n obligatoria, sin alternativas fiscales, etiquetas ni valor vac\xEDo.");return{propiedad:e.propiedad}}if(e.formas!==void 0&&!wb(e.formas))throw i("Las formas de clasificaci\xF3n necesitan opciones de Empresa y claves fiscales v\xE1lidas.");let n={};for(let[a,s]of Object.entries(e.formas??{})){if(!Object.hasOwn(t,a)||t[a]!=="companies"||typeof s!="string"||s!==s.trim())throw i("Las formas de clasificaci\xF3n necesitan opciones de Empresa y claves fiscales v\xE1lidas.");qr("legalForms",[{value:s,label:ts(o,a)}]),n[a]=s}if(e.etiquetas!==void 0&&(!Array.isArray(e.etiquetas)||new Set(e.etiquetas).size!==e.etiquetas.length||e.etiquetas.some(a=>typeof a!="string"||!Object.hasOwn(t,a)||t[a]!=="contacts")))throw i("Las etiquetas de clasificaci\xF3n necesitan opciones distintas de Persona.");let r=e.etiquetas??[];for(let a of r){let s=o.opciones?.find(l=>l.valor===a);if(ts(o,a).length>60||s?.color&&!/^#[0-9a-fA-F]{6}$/.test(s.color))throw i("La etiqueta de clasificaci\xF3n necesita nombre de hasta 60 caracteres y color #rrggbb.")}for(let a of["contacts","companies"])if(Object.entries(t).filter(([l,d])=>d===a&&!Object.hasOwn(n,l)&&!r.includes(l)).length>1)throw i("Las opciones que comparten objeto necesitan forma jur\xEDdica o etiqueta para conservar su significado.");return{...e.formas!==void 0?{formas:n}:{},...e.etiquetas!==void 0?{etiquetas:r}:{}}}function Np(e,o){if(!o?.formas)return[];let t=e.find(a=>a.clave===o.campo),n=Object.entries(o.formas).map(([a,s])=>({value:s,label:ts(t,a),...t.opciones?.find(l=>l.valor===a)?.color?{color:t.opciones.find(l=>l.valor===a).color}:{}})),r=new Map;for(let a of n){let s=r.get(a.value);if(s&&(s.label!==a.label||s.color!==a.color))throw i("Una forma jur\xEDdica de clasificaci\xF3n tiene etiquetas contradictorias.");r.set(a.value,a)}return qr("legalForms",[...r.values()])}function $p(e,o,t){return o?.propiedad?e.map(n=>n.clave===o.campo?{...n,opciones:n.opciones?.filter(r=>o.valores[r.valor]===t)}:n):e}var wb,ts,xp=m(()=>{q();os();kr();wb=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);ts=(e,o)=>e.opciones?.find(t=>t.valor===o)?.etiqueta??e.etiqueta});var O,Cp,Op=m(()=>{O=(e,o,t={})=>({clave:e,tipo:o,enTabla:!1,ordenable:o!=="texto_largo",filtrable:!1,editable:!["contador","fecha_hora","correos","telefonos","etiquetas"].includes(o),...t}),Cp=[{clave:"companies",icono:"building-2",campoTitulo:"name",campos:[O("name","texto",{enTabla:!0,ancho:240}),O("website","url",{enTabla:!0,ancho:200}),O("sector","seleccion",{enTabla:!0,filtrable:!0,opciones:"config:companySectors"}),O("tags","etiquetas",{enTabla:!0,ordenable:!1,editable:!0,filtrable:!0,relacion:"tags",objetoEtiquetas:"companies",ancho:160,migracion:"0466_etiquetas_por_objeto.sql"}),O("size","seleccion",{enTabla:!0,filtrable:!0,opciones:[{valor:"1",etiqueta:"1"},{valor:"10",etiqueta:"2-9"},{valor:"50",etiqueta:"10-49"},{valor:"250",etiqueta:"50-249"},{valor:"500",etiqueta:"250+"}],ancho:110}),O("city","texto",{enTabla:!0,ancho:140}),O("sales_id","relacion",{enTabla:!0,filtrable:!0,relacion:"sales",ancho:170}),O("nb_contacts","contador",{enTabla:!0,ancho:110}),O("nb_deals","contador",{enTabla:!0,ancho:130}),O("created_at","fecha_hora",{enTabla:!0,ancho:140}),O("proveedor","booleano",{filtrable:!0,ancho:110}),O("has_newsletter","booleano",{etiqueta:"Comunicaciones",filtrable:!0,migracion:"0490_comunicaciones_empresa.sql"}),O("tipos","seleccion_multiple",{enTabla:!0,ordenable:!1,editable:!1,opciones:"config:contactTypes",ancho:170,migracion:"0439_tipos_contactos.sql"}),O("ubicacion","ubicacion",{etiqueta:"Ubicaci\xF3n",editable:!1,ordenable:!1,migracion:"0452_ubicacion_nativa.sql"}),O("phone_number","telefono",{ancho:150}),O("country","texto",{ancho:130}),O("address","texto"),O("state_abbr","texto",{soloFicha:!0,etiqueta:"Provincia"}),O("zipcode","texto",{ancho:110}),O("linkedin_url","url"),O("revenue","texto",{ancho:130}),O("tax_identifier","texto",{ancho:140}),O("razon_social","texto",{ancho:220,migracion:"0440_datos_fiscales.sql"}),O("forma_juridica","seleccion",{filtrable:!0,opciones:"config:legalForms",ancho:160,migracion:"0440_datos_fiscales.sql"}),O("correo_facturacion","correo",{ancho:220,migracion:"0440_datos_fiscales.sql"}),O("pais_fiscal","texto",{filtrable:!0,editable:!1,ancho:90,migracion:"0440_datos_fiscales.sql"}),O("description","texto_largo",{ancho:260})]},{clave:"contacts",icono:"users",campoTitulo:"first_name",camposTitulo:["first_name","last_name"],campos:[O("ubicacion","ubicacion",{etiqueta:"Ubicaci\xF3n",editable:!1,ordenable:!1,migracion:"0452_ubicacion_nativa.sql"}),O("first_name","texto",{enTabla:!0,ancho:220}),O("last_name","texto",{ancho:150}),O("title","texto",{enTabla:!0,ancho:150}),O("company_id","relacion",{enTabla:!0,relacion:"companies",ancho:180}),O("email_jsonb","correos",{enTabla:!0,ordenable:!1,editable:!0,ancho:220}),O("phone_jsonb","telefonos",{enTabla:!0,ordenable:!1,editable:!0,ancho:150}),O("status","seleccion",{enTabla:!0,filtrable:!0,opciones:"config:noteStatuses",ancho:130}),O("tags","etiquetas",{enTabla:!0,ordenable:!1,editable:!0,filtrable:!0,relacion:"tags",objetoEtiquetas:"contacts",ancho:160}),O("tipos","seleccion_multiple",{enTabla:!0,ordenable:!1,editable:!1,opciones:"config:contactTypes",ancho:170,migracion:"0439_tipos_contactos.sql"}),O("sales_id","relacion",{enTabla:!0,filtrable:!0,relacion:"sales",ancho:170}),O("last_seen","fecha_hora",{enTabla:!0,ancho:140}),O("nb_tasks","contador",{ancho:110}),O("first_seen","fecha_hora",{ancho:140}),O("linkedin_url","url"),O("background","texto_largo",{ancho:260}),O("nif","texto",{soloFicha:!0,sensible:!0,etiqueta:"Identificador fiscal",migracion:"0005_datos_es.sql"}),O("iban","texto",{soloFicha:!0,sensible:!0,etiqueta:"IBAN",migracion:"0005_datos_es.sql"}),O("birthday","fecha",{soloFicha:!0,etiqueta:"Fecha de nacimiento",migracion:"0005_datos_es.sql"}),O("address","texto",{soloFicha:!0,etiqueta:"Direcci\xF3n",migracion:"0005_datos_es.sql"}),O("zipcode","texto",{soloFicha:!0,etiqueta:"C\xF3digo postal",migracion:"0005_datos_es.sql"}),O("city","texto",{soloFicha:!0,etiqueta:"Ciudad",migracion:"0005_datos_es.sql"}),O("province","texto",{soloFicha:!0,etiqueta:"Provincia",migracion:"0005_datos_es.sql"}),O("country","texto",{soloFicha:!0,etiqueta:"Pa\xEDs",migracion:"0005_datos_es.sql"}),O("has_newsletter","booleano",{soloFicha:!0,migracion:"0005_datos_es.sql"}),O("pais_fiscal","texto",{filtrable:!0,editable:!1,ancho:90,migracion:"0440_datos_fiscales.sql"})]},{clave:"deals",icono:"handshake",campoTitulo:"name",campos:[O("name","texto",{enTabla:!0,ancho:240}),O("company_id","relacion",{enTabla:!0,relacion:"companies",ancho:180}),O("stage","seleccion",{enTabla:!0,filtrable:!0,opciones:"config:dealStages",ancho:160}),O("amount","importe",{enTabla:!0,ancho:120}),O("expected_closing_date","fecha",{enTabla:!0,ancho:140}),O("category","seleccion",{enTabla:!0,filtrable:!0,opciones:"config:dealCategories",ancho:150}),O("tags","etiquetas",{enTabla:!0,ordenable:!1,editable:!0,filtrable:!0,relacion:"tags",objetoEtiquetas:"deals",ancho:160,migracion:"0466_etiquetas_por_objeto.sql"}),O("sales_id","relacion",{enTabla:!0,filtrable:!0,relacion:"sales",ancho:170}),O("origen_lead","texto",{etiqueta:"Origen",filtrable:!0,editable:!1,ancho:170,migracion:"0467_oportunidades_origen_actividad.sql"}),O("ultima_actividad","fecha_hora",{etiqueta:"\xDAltima actividad",editable:!1,ancho:150,migracion:"0467_oportunidades_origen_actividad.sql"}),O("created_at","fecha_hora",{ancho:140}),O("updated_at","fecha_hora",{ancho:140}),O("description","texto_largo",{ancho:260})]},{clave:"proyectos",icono:"folder-kanban",campoTitulo:"nombre",campos:[O("nombre","texto",{enTabla:!0,ancho:220}),O("clave","texto",{enTabla:!0,ancho:110,editable:!1}),O("estado","seleccion",{enTabla:!0,filtrable:!0,opciones:[{valor:"activo",etiqueta:"Activo"},{valor:"en_pausa",etiqueta:"En pausa"},{valor:"archivado",etiqueta:"Archivado"}],ancho:120}),O("sales_id","relacion",{enTabla:!0,filtrable:!0,relacion:"sales",ancho:170}),O("fecha_inicio","fecha",{enTabla:!0,ancho:130}),O("fecha_fin","fecha",{enTabla:!0,ancho:130}),O("requiere_aceptacion","booleano",{ancho:120}),O("color","texto",{ancho:100}),O("icono","texto",{ancho:100}),O("descripcion","texto_largo",{ancho:260}),O("creado","fecha_hora",{ancho:140}),O("actualizado","fecha_hora",{ancho:140})]},{clave:"tareas",icono:"check-square",campoTitulo:"titulo",campos:[O("titulo","texto",{enTabla:!0,ancho:240}),O("codigo_corto","texto",{enTabla:!0,ancho:110,editable:!1}),O("proyecto_id","relacion",{enTabla:!0,filtrable:!0,relacion:"proyectos",ancho:170,editable:!1}),O("columna_id","texto",{enTabla:!0,filtrable:!0,ancho:130}),O("prioridad","seleccion",{enTabla:!0,filtrable:!0,opciones:[{valor:"baja",etiqueta:"Baja"},{valor:"media",etiqueta:"Media"},{valor:"alta",etiqueta:"Alta"},{valor:"urgente",etiqueta:"Urgente"}],ancho:110}),O("sales_id","relacion",{enTabla:!0,filtrable:!0,relacion:"sales",ancho:170}),O("fecha_entrega","fecha",{enTabla:!0,ancho:130}),O("fecha_inicio","fecha",{ancho:130}),O("estimacion_minutos","numero",{ancho:110}),O("hecho","fecha_hora",{enTabla:!0,editable:!0,marca:!0,ancho:120}),O("contact_id","relacion",{filtrable:!0,relacion:"contacts",ancho:160}),O("descripcion","texto_largo",{ancho:260}),O("creado","fecha_hora",{ancho:140}),O("actualizado","fecha_hora",{ancho:140})]}]});var Sp,vb,cM,jp,Ap=m(()=>{Sp=new Set(["texto","texto_largo","numero","importe","porcentaje","fecha","fecha_hora","hora","duracion","booleano","seleccion","seleccion_multiple","url","correo","telefono","color","codigo","valoracion","autonumero"]),vb=new Set([...Sp,"relacion"]),cM=new Set([...Sp,"relacion"]),jp=new Set([...vb,"busqueda"])});function Ep(e){let o=Eo(),t=(e==="contacts"?yb:_b).map(([n,r])=>({clave:n,etiqueta:eo(o,r),tipo:["correo","correo_facturacion"].includes(n)?"correo":["telefono","phone_number"].includes(n)?"telefono":["background","description"].includes(n)?"texto_largo":n==="website"?"url":"texto",obligatorio:n==="first_name"||n==="name",...Nb(e).has(n)?{}:{permisos:{administrador:"lectura",miembro:"lectura",lectura:"lectura"}}}));return{id:0,clave:`@${e}`,nombre:eo(o,e==="contacts"?"Persona":"Empresa"),nombre_plural:eo(o,e==="contacts"?"Personas":"Empresas"),descripcion:"",icono:e==="contacts"?"users":"building-2",estado:"publicado",campos:t}}var Vn,yb,_b,Nb,qp=m(()=>{Br();Vn=[["address","Direcci\xF3n"],["zipcode","C\xF3digo postal"],["city","Ciudad"],["country","Pa\xEDs"]],yb=[["first_name","Nombre"],["last_name","Apellidos"],["title","Cargo"],["correo","Correo"],["telefono","Tel\xE9fono"],...Vn,["background","Contexto"],["nif","Identificador fiscal"],["pais_fiscal","Pa\xEDs fiscal"]],_b=[["name","Nombre"],["phone_number","Tel\xE9fono"],["website","Web"],...Vn,["description","Descripci\xF3n"],["persona_first_name","Nombre de la persona"],["correo_facturacion","Correo de facturaci\xF3n"],["tax_identifier","Identificador fiscal"],["razon_social","Raz\xF3n social"],["pais_fiscal","Pa\xEDs fiscal"]],Nb=e=>new Set(e==="contacts"?["first_name","last_name","title","telefono",...Vn.map(([o])=>o),"background"]:["name","phone_number","website",...Vn.map(([o])=>o),"description","persona_first_name"])});function kp(e){let o=new Map(e.filter(s=>!s.archivado&&s.completarDesde).map(s=>[s.clave,s])),t=new Map,n=new Set,r=[],a=s=>{if(n.has(s.clave))throw i("El autocompletado necesita dependencias sin ciclos y hasta seis pasos.");if(t.has(s.clave))return t.get(s.clave);n.add(s.clave);let l=0;for(let d of rs(s)){let u=o.get(d.relacion);u&&(l=Math.max(l,a(u)+1))}if(l>6)throw i("El autocompletado necesita dependencias sin ciclos y hasta seis pasos.");return n.delete(s.clave),t.set(s.clave,l),r.push(s),l};for(let s of o.values())a(s);return r}var rs,Rp=m(()=>{q();rs=e=>e.completarDesde?[e.completarDesde,...e.completarDesde.alternativa?[e.completarDesde.alternativa]:[]]:[]});function xb(e){let o=[],t=0;for(;t<e.length;){let n=e[t];if(/\s/.test(n)){t++;continue}if(o.length>=Pp)throw i(`F\xF3rmula demasiado larga: como mucho ${Pp} piezas.`);if(/[0-9]/.test(n)||n==="."&&/[0-9]/.test(e[t+1]??"")){let s=/^[0-9]*\.?[0-9]+|^[0-9]+/.exec(e.slice(t));if(s[0].length>20)throw i("F\xF3rmula: n\xFAmero demasiado largo.");o.push({t:"num",v:s[0]}),t+=s[0].length;continue}if(n==='"'||n==="'"){let s="",l=t+1;for(;;){if(l>=e.length)throw i("F\xF3rmula: falta cerrar unas comillas.");if(e[l]===n){if(e[l+1]===n){s+=n,l+=2;continue}break}s+=e[l],l++}if(s.length>500)throw i("F\xF3rmula: un texto de como mucho 500 caracteres.");o.push({t:"txt",v:s}),t=l+1;continue}if(n==="{"){let s=e.indexOf("}",t);if(s<0)throw i("F\xF3rmula: falta cerrar una llave \xAB}\xBB.");let l=e.slice(t+1,s).trim();if(!l||l.length>80)throw i("F\xF3rmula: un campo entre llaves no v\xE1lido.");o.push({t:"campo",v:l}),t=s+1;continue}let r=/^[A-Za-zÁÉÍÓÚÜÑáéíóúüñ_][A-Za-z0-9ÁÉÍÓÚÜÑáéíóúüñ_.]*/.exec(e.slice(t));if(r){if(r[0].length>40)throw i("F\xF3rmula: nombre demasiado largo.");o.push({t:"id",v:r[0]}),t+=r[0].length;continue}let a=$b.find(s=>e.startsWith(s,t));if(!a)throw i(`F\xF3rmula: no se entiende \xAB${n}\xBB.`);o.push({t:"op",v:a==="!="?"<>":a===";"?",":a}),t+=a.length}return o.push({t:"fin"}),o}function Ob(e){let o=xb(e),t=0,n=0,r=()=>o[t],a=g=>r().t==="op"&&r().v===g,s=g=>{if(!a(g))throw i(`F\xF3rmula: se esperaba \xAB${g}\xBB.`);t++},l=g=>{if(++n>Tp)throw i(`F\xF3rmula: como mucho ${Tp} niveles de anidaci\xF3n.`);try{return g()}finally{n--}},d=(g,N,C=!1)=>()=>{let S=N();for(;r().t==="op"&&g.includes(r().v)&&(S={k:"bin",op:o[t++].v,a:S,b:N()},!C););return S},u=()=>l(()=>{let g=r();if(g.t==="num")return t++,{k:"num",v:g.v};if(g.t==="txt")return t++,{k:"txt",v:g.v};if(g.t==="campo")return t++,{k:"campo",v:g.v};if(g.t==="op"&&g.v==="-")return t++,{k:"neg",a:u()};if(g.t==="op"&&g.v==="("){t++;let N=y();return s(")"),N}if(g.t==="id"){t++;let N=Cb(g.v);if(!a("(")){if(N==="VERDADERO"||N==="TRUE")return{k:"bool",v:!0};if(N==="FALSO"||N==="FALSE")return{k:"bool",v:!1};throw i(`F\xF3rmula: \xAB${g.v}\xBB no es una funci\xF3n (los campos van entre llaves: {${g.v}}).`)}t++;let C=[];if(!a(")"))for(;;){if(C.push(y()),C.length>Ip)throw i(`F\xF3rmula: como mucho ${Ip} argumentos.`);if(a(",")){t++;continue}break}return s(")"),{k:"fn",f:N,args:C}}throw i(g.t==="fin"?"F\xF3rmula incompleta.":"F\xF3rmula: algo sobra o falta.")}),p=d(["*","/"],u),f=d(["+","-"],p),h=d(["&"],f),b=d(["=","<>","<","<=",">",">="],h,!0),y=()=>l(b),w=y();if(r().t!=="fin")throw i("F\xF3rmula: algo sobra al final.");return w}function ns(e){if(!Xe(e,0))throw i("F\xF3rmula: A\xD1O, MES y DIA necesitan una fecha.");return"numero"}function Lp(e){let o=e[0];for(let t of e.slice(1))o=Gt(o,t);if(o!=="numero"&&o!=="fecha"&&o!=="fecha_hora")throw i("F\xF3rmula: MIN y MAX, con n\xFAmeros o fechas.");return o}function Gt(e,o){if(e===o)return e;if(Xe([e,o],0)&&Xe([e,o],1))return"fecha_hora";throw i(`F\xF3rmula: no se mezclan ${gt[e]} y ${gt[o]}.`)}function Jn(e){if(!e)return 0;if(e.k!=="num"||!/^\d+$/.test(e.v)||Number(e.v)>10)throw i("F\xF3rmula: REDONDEAR, con 0 a 10 decimales.");return Number(e.v)}function is(e,o){let t=us(e),n=t.find(r=>r.clave===o)??t.find(r=>r.etiqueta.trim().toLowerCase()===o.trim().toLowerCase());if(!n)throw i(`F\xF3rmula: no hay un campo \xAB${o}\xBB.`);return n}function as(e,o,t){if(!o.includes("."))return null;let n=o.trim().toLowerCase();if(us(e).some(a=>a.clave===o||a.etiqueta.trim().toLowerCase()===n))return null;let r=t?.[o];if(!r)throw i(`F\xF3rmula: no hay un campo \xAB${o}\xBB.`);return r}function Ab(e){let o=e.saltos.at(-1).modulo;if(Wp[o]){let t=Ee(e.campo)?e.campos.find(r=>r.clave===e.campo&&!r.archivado):void 0,n=t?ls[t.tipo]:zp[Pr(o).find(r=>r.clave===e.campo)?.tipo??""];if(!n)throw i(`F\xF3rmula: \xAB${e.campo}\xBB no se puede usar en una f\xF3rmula.`);return n}return Fp({campos:e.campos},jb(e),[])}function Fp(e,o,t){if(o.tipo==="formula")return Bp(e,o,t).tipo;let n=o.tipo==="busqueda"||o.tipo==="resumen"?o.origen?.tipo??"":o.tipo,r=ls[n];if(!r)throw i(`F\xF3rmula: el campo \xAB${o.etiqueta}\xBB no se puede usar en una f\xF3rmula.`);return o.tipo==="busqueda"&&Eb(e,o),r}function Eb(e,o){let t=us(e).find(n=>n.clave===o.desde);if(!t?.relacion||t.multiple)throw i(`F\xF3rmula: la b\xFAsqueda \xAB${o.etiqueta}\xBB trae varios valores y no se usa en una f\xF3rmula.`);if(o.origen?.encadenada)throw i(`F\xF3rmula: la b\xFAsqueda \xAB${o.etiqueta}\xBB ya va encadenada y no se usa en una f\xF3rmula.`);if(t.relacion.startsWith("mod_")){if(!/^[a-z][a-z0-9_]{0,40}$/.test(o.campo??"")||qb.has(o.origen?.tipo??""))throw i(`F\xF3rmula: la b\xFAsqueda \xAB${o.etiqueta}\xBB no es v\xE1lida.`)}else{let n=Pr(t.relacion).find(r=>r.clave===o.campo)??(Ee(o.campo)&&o.origen?{tipo:o.origen.tipo}:void 0);if(!n||!(Ee(o.campo)?ls[n.tipo]:zp[n.tipo])||!Wp[t.relacion])throw i(`F\xF3rmula: la b\xFAsqueda \xAB${o.etiqueta}\xBB no se puede usar en una f\xF3rmula.`)}return{rel:t}}function Bp(e,o,t){if(t.includes(o.clave))throw i(`F\xF3rmula: \xAB${o.etiqueta}\xBB se usa a s\xED misma (en cadena).`);if(t.length>=Mp)throw i(`F\xF3rmula: como mucho ${Mp} f\xF3rmulas encadenadas.`);return kb(e,o.formula??"",[...t,o.clave],o.origen?.rutas)}function kb(e,o,t,n){if(typeof o!="string"||!o.trim())throw i("F\xF3rmula vac\xEDa.");if(o.length>Ye)throw i(`F\xF3rmula de como mucho ${Ye} caracteres.`);let r=Ob(o),a=new Map,s=u=>{let p=d(u);return a.set(u,p),p},l=(u,p,f)=>{let h=s(u);if(h!==p){if(u.k==="campo"){let y=as(e,u.v,n)?u.v:is(e,u.v).etiqueta;throw i(`F\xF3rmula: \xAB${y}\xBB no es ${gt[p]}, es ${gt[h]} (${f} necesita ${gt[p]}).`)}throw i(`F\xF3rmula: ${f} necesita ${gt[p]} y hay ${gt[h]}.`)}},d=u=>{switch(u.k){case"num":return"numero";case"txt":return"texto";case"bool":return"booleano";case"campo":{let p=as(e,u.v,n);return p?Ab(p):Fp(e,is(e,u.v),t)}case"neg":return l(u.a,"numero","\xAB-\xBB"),"numero";case"bin":return u.op==="&"?(s(u.a),s(u.b),"texto"):["+","-","*","/"].includes(u.op)?(l(u.a,"numero",`\xAB${u.op}\xBB`),l(u.b,"numero",`\xAB${u.op}\xBB`),"numero"):(Gt(s(u.a),s(u.b)),"booleano");case"fn":{let p=Sb[u.f]??u.f,f=cs[p];if(!f)throw i(`F\xF3rmula: la funci\xF3n \xAB${u.f}\xBB no existe.`);if(p==="REDONDEAR"&&Jn(u.args[1]),p==="PRECIO_VIGENTE"&&(u.args.length<4||u.args.length>6||u.args[0]?.k!=="txt"||u.args[2]?.k!=="txt"))throw i("PRECIO_VIGENTE: tabla y valor literales, fecha y de una a tres claves.");let h=f.args.length-(f.opcionales??0);if(u.args.length<Math.max(h,f.resto?1:0)||!f.resto&&u.args.length>f.args.length)throw i(`F\xF3rmula: ${p} no lleva ${u.args.length} argumentos.`);let b=u.args.map((y,w)=>{let g=f.args[w]??f.resto;return g==="cualquiera"?s(y):(l(y,g,p),g)});return f.tipo(b)}}};return{tipo:s(r),arbol:r,tipos:a,...n?{rutas:n}:{}}}function Qn(e){let o={campos:e};return e.map(t=>{if(t.tipo!=="formula"||t.archivado)return t;let n=Bp(o,t,[]),r=t.origen?.rutas&&Object.keys(t.origen.rutas).length?t.origen.rutas:void 0;return{...t,formula:Rb(o,t.formula,r),origen:{tipo:n.tipo,...r?{rutas:r}:{}}}})}function Rb(e,o,t){let n="",r=0;for(;r<o.length;){let a=o[r];if(a==='"'||a==="'"){let s=r+1;for(;s<o.length;)if(o[s]===a&&o[s+1]===a)s+=2;else{if(o[s]===a)break;s++}n+=o.slice(r,s+1),r=s+1;continue}if(a==="{"){let s=o.indexOf("}",r),l=o.slice(r+1,s).trim();n+=`{${as(e,l,t)?l:is(e,l).clave}}`,r=s+1;continue}n+=a,r++}return n}var Ye,Pp,Tp,Mp,Ip,ss,$b,Cb,Xe,ht,Dp,Qt,cs,Sb,wM,gt,ls,zp,vM,us,jb,qb,Wp,Gn=m(()=>{kr();Fn();q();Hn();Ye=1e3,Pp=300,Tp=20,Mp=5,Ip=20,ss="Europe/Madrid",$b=["<>","!=","<=",">=","=","<",">","+","-","*","/","&","(",")",",",";"];Cb=e=>e.normalize("NFD").replace(/[̀-ͯ]/g,"").toUpperCase();Xe=(e,o)=>e[o]==="fecha"||e[o]==="fecha_hora",ht=(e,o)=>o==="fecha_hora"?j`(${e} at time zone ${ss})::date`:e,Dp=e=>j`(${e})::text`,Qt=(e,o)=>j`(least(greatest(${e}, ${-o}::numeric), ${o}::numeric))::int`,cs={PRECIO_VIGENTE:{args:["texto","fecha","texto","cualquiera"],resto:"cualquiera",tipo:()=>"numero",sql:e=>j`((crm_precio_formula(${e[0]}, ${e[1]}::date, jsonb_build_array(${j.join(e.slice(3).map(o=>j`(${o})::text`),j`, `)}))->'valores'->>${e[2]})::numeric)`},SI:{args:["booleano","cualquiera","cualquiera"],opcionales:1,tipo:e=>Gt(e[1],e[2]??e[1]),sql:e=>e[2]?j`(case when ${e[0]} then ${e[1]} else ${e[2]} end)`:j`(case when ${e[0]} then ${e[1]} end)`},Y:{args:[],resto:"booleano",tipo:()=>"booleano",sql:e=>j`(${j.join(e,j` and `)})`},O:{args:[],resto:"booleano",tipo:()=>"booleano",sql:e=>j`(${j.join(e,j` or `)})`},NO:{args:["booleano"],tipo:()=>"booleano",sql:e=>j`(not ${e[0]})`},VACIO:{args:["cualquiera"],tipo:()=>"booleano",sql:(e,o)=>o[0]==="texto"?j`(${e[0]} is null or ${e[0]} = '')`:j`(${e[0]} is null)`},REDONDEAR:{args:["numero","numero"],opcionales:1,tipo:()=>"numero",sql:(e,o,t)=>j`round(${e[0]}, ${Jn(t[1])}::int)`},ABS:{args:["numero"],tipo:()=>"numero",sql:e=>j`abs(${e[0]})`},MIN:{args:["cualquiera"],resto:"cualquiera",tipo:e=>Lp(e),sql:e=>j`least(${j.join(e)})`},MAX:{args:["cualquiera"],resto:"cualquiera",tipo:e=>Lp(e),sql:e=>j`greatest(${j.join(e)})`},CONCAT:{args:[],resto:"cualquiera",tipo:()=>"texto",sql:e=>j`concat(${j.join(e.map(Dp))})`},MAYUSCULAS:{args:["texto"],tipo:()=>"texto",sql:e=>j`upper(${e[0]})`},MINUSCULAS:{args:["texto"],tipo:()=>"texto",sql:e=>j`lower(${e[0]})`},IZQUIERDA:{args:["texto","numero"],tipo:()=>"texto",sql:e=>j`left(${e[0]}, ${Qt(e[1],1e4)})`},DERECHA:{args:["texto","numero"],tipo:()=>"texto",sql:e=>j`right(${e[0]}, ${Qt(e[1],1e4)})`},LARGO:{args:["texto"],tipo:()=>"numero",sql:e=>j`(length(${e[0]}))::numeric`},RECORTAR:{args:["texto"],tipo:()=>"texto",sql:e=>j`btrim(${e[0]})`},TEXTO:{args:["cualquiera"],tipo:()=>"texto",sql:e=>Dp(e[0])},HOY:{args:[],tipo:()=>"fecha",sql:()=>j`(now() at time zone ${ss})::date`},AHORA:{args:[],tipo:()=>"fecha_hora",sql:()=>j`now()`},DIAS_ENTRE:{args:["cualquiera","cualquiera"],tipo:e=>{if(!Xe(e,0)||!Xe(e,1))throw i("F\xF3rmula: DIAS_ENTRE necesita dos fechas.");return"numero"},sql:(e,o)=>j`((${ht(e[1],o[1])}) - (${ht(e[0],o[0])}))::numeric`},ANADIR_DIAS:{args:["cualquiera","numero"],tipo:e=>{if(!Xe(e,0))throw i("F\xF3rmula: A\xD1ADIR_DIAS necesita una fecha.");return e[0]},sql:(e,o)=>o[0]==="fecha"?j`(${e[0]} + ${Qt(e[1],1e5)})`:j`(${e[0]} + make_interval(days => ${Qt(e[1],1e5)}))`},ANO:{args:["cualquiera"],tipo:e=>ns(e),sql:(e,o)=>j`(extract(year from ${ht(e[0],o[0])}))::numeric`},MES:{args:["cualquiera"],tipo:e=>ns(e),sql:(e,o)=>j`(extract(month from ${ht(e[0],o[0])}))::numeric`},DIA:{args:["cualquiera"],tipo:e=>ns(e),sql:(e,o)=>j`(extract(day from ${ht(e[0],o[0])}))::numeric`},POTENCIA:{args:["numero","numero"],tipo:()=>"numero",sql:e=>j`(case when ${e[0]} is null or ${e[1]} is null then null
|
|
6
|
+
${t}`,e}return e}function wb(e){return je(e)&&B(e.stack)}var kr=m(()=>{_()});function yb(e){return je(e)&&"insertId"in e&&"affectedRows"in e}var vb,Bd,Ud=m(()=>{Rr();_();kr();vb=Symbol();Bd=class{#e;#o;#r;#t;constructor(o,t){this.#e=o,this.#o=t}async cancelQuery(o){await this.#i(`kill query ${this.#r}`,o)}async collectSessionInfo(){if(this.#r)return;let{threadId:o}=this.#e;if(o!=null)this.#r=o;else{let[{cid:t}]=await this.#n(wt.raw("select connection_id() as cid"));this.#r=Number(t)}}async executeQuery(o){try{this.#t=o.queryId;let t=await this.#n(o);if(!yb(t))return{rows:Array.isArray(t)?t:[]};let{insertId:r,affectedRows:n,changedRows:a}=t;return{insertId:r!=null&&r.toString()!=="0"?BigInt(r):void 0,numAffectedRows:n!=null?BigInt(n):void 0,numChangedRows:a!=null?BigInt(a):void 0,rows:[]}}catch(t){throw Jo(t,new Error)}finally{this.#t=void 0}}async killSession(o){try{this.#e.destroy()}catch{}await this.#i(`kill connection ${this.#r}`,o)}async*streamQuery(o,t){this.#t=o.queryId;let r=this.#e.query(o.sql,o.parameters).stream({objectMode:!0});try{for await(let n of r)yield{rows:[n]}}catch(n){if(je(n)&&"code"in n&&n.code==="ERR_STREAM_PREMATURE_CLOSE")return;throw n}finally{this.#t=void 0}}[vb](){this.#e.release()}#n(o){return new Promise((t,r)=>{this.#e.query(o.sql,o.parameters,(n,a)=>{n?r(n):t(a)})})}async#i(o,t){if(!this.#t)return;let{config:r}=this.#e,n=this.#t;if(!this.#o||!r)return await t(async u=>{n.queryId===this.#t?.queryId&&await u.executeQuery(wt.raw(o,[]))});let{clientFlags:a,maxPacketSize:s,...c}=r,d=this.#o(c);try{await new Promise((u,p)=>{d.connect(f=>{if(f)return p(f);if(n.queryId!==this.#t?.queryId)return u();d.query(o,[],h=>{if(h)return p(h);u()})})})}finally{d.destroy()}}}});var Vd=m(()=>{});var Jd=m(()=>{});var Qd=m(()=>{});var Gd=m(()=>{});var _b,Hd,Xd=m(()=>{Rr();kr();_b=Symbol(),Hd=class{#e;#o;#r;#t;constructor(o,t){this.#e=o,this.#o=t}async cancelQuery(o){return await this.#n(`select pg_cancel_backend(${this.#t})`,o)}async collectSessionInfo(){if(this.#t)return;let{processID:o}=this.#e;if(o)this.#t=o;else{let{rows:[{pid:t}]}=await this.#e.query("select pg_backend_pid() as pid",[]);this.#t=Number(t)}}async executeQuery(o){try{this.#r=o.queryId;let t=await this.#e.query(o.sql,o.parameters),{command:r,rowCount:n,rows:a}=t;return{numAffectedRows:r==="INSERT"||r==="UPDATE"||r==="DELETE"||r==="MERGE"?BigInt(n):void 0,rows:a??[]}}catch(t){throw Jo(t,new Error)}finally{this.#r=void 0}}async killSession(o){return await this.#n(`select pg_terminate_backend(${this.#t})`,o)}async*streamQuery(o,t){if(!this.#o.cursor)throw new Error("`cursor` is not present in your postgres dialect config. It's required to make streaming work in postgres.");this.#r=o.queryId;let r=this.#e.query(new this.#o.cursor(o.sql,o.parameters.slice()));try{for(;;){let n=await r.read(t);if(n.length===0)break;yield{rows:n}}}finally{await r.close(),this.#r=void 0}}[_b](){this.#e.release()}async#n(o,t){if(!this.#r)return;let{controlClient:r,poolOptions:n}=this.#o,a=this.#r;if(!r)return await t(async c=>{a.queryId===this.#r?.queryId&&await c.executeQuery(wt.raw(o,[]))});let s=new r({...n,password:"password"in n?n.password:void 0});try{if(await s.connect(),a.queryId!==this.#r.queryId)return;await s.query(o,[])}finally{s.end()}}}});var Yd=m(()=>{});var Kd=m(()=>{});var wR,vR,Zd=m(()=>{wR=BigInt("3853314791062309107"),vR=3600*1e3});var ep=m(()=>{});var op=m(()=>{});var Nb,$b,xb,tp,Pr,rp=m(()=>{_();Rr();kr();$a();Er();Nb=Symbol(),$b=Symbol(),xb=Symbol(),tp=class{#e;#o;#r;#t;constructor(o,t){this.#e=o,this.#o=!1,this.#r=t}async beginTransaction(o){let{isolationLevel:t}=o;await new Promise((r,n)=>this.#e.beginTransaction(a=>{a?n(a):r(void 0)},t?In(8):void 0,t?this.#n(t):void 0))}async cancelQuery(){if(this.#t)return new Promise(o=>{this.#t?.request.once("requestCompleted",o),this.#e.cancel()||(this.#t?.request.off("requestCompleted",o),o())})}async commitTransaction(){await new Promise((o,t)=>this.#e.commitTransaction(r=>{r?t(r):o(void 0)}))}async connect(){let{promise:o,reject:t,resolve:r}=new Se;this.#e.connect(a=>{if(a)return t(a);r()}),this.#e.on("error",a=>{a instanceof Error&&"code"in a&&a.code==="ESOCKET"&&(this.#o=!0),console.error(a),t(a)});function n(){t(new Error("The connection ended without ever completing the connection"))}return this.#e.once("end",n),await o,this.#e.off("end",n),this}async executeQuery(o){try{let t=new Se;this.#t=new Pr({compiledQuery:o,tedious:this.#r,onDone:t}),this.#e.execSql(this.#t.request);let{rowCount:r,rows:n}=await t.promise;return{numAffectedRows:r!==void 0?BigInt(r):void 0,rows:n}}catch(t){throw Jo(t,new Error)}finally{this.#t=void 0}}async rollbackTransaction(o){await new Promise((t,r)=>this.#e.rollbackTransaction(n=>{n?r(n):t(void 0)},o))}async savepoint(o){await new Promise((t,r)=>this.#e.saveTransaction(n=>{n?r(n):t(void 0)},o))}async*streamQuery(o,t){this.#t=new Pr({compiledQuery:o,streamChunkSize:t,tedious:this.#r}),this.#e.execSql(this.#t.request);try{for(;;){let r=await this.#t.readChunk();if(r.length===0||(yield{rows:r},r.length<t))break}}finally{await this.cancelQuery(),this.#t=void 0}}#n(o){let{ISOLATION_LEVEL:t}=this.#r,n={"read committed":t.READ_COMMITTED,"read uncommitted":t.READ_UNCOMMITTED,"repeatable read":t.REPEATABLE_READ,serializable:t.SERIALIZABLE,snapshot:t.SNAPSHOT}[o];if(n===void 0)throw new Error(`Unknown isolation level: ${o}`);return n}[$b](){return"closed"in this.#e&&this.#e.closed?Promise.resolve():new Promise(o=>{this.#e.once("end",o),this.#e.close()})}async[Nb](){await new Promise((o,t)=>{this.#e.reset(r=>{if(r)return t(r);o()})})}async[xb](){if(this.#o||this.#i())return!1;try{let o=new Se,t=new Pr({compiledQuery:wt.raw("select 1"),onDone:o,tedious:this.#r});return this.#e.execSql(t.request),await o.promise,!0}catch{return!1}}#i(){return"closed"in this.#e&&!!this.#e.closed}},Pr=class{#e;#o;#r;#t;#n;#i;constructor(o){let{compiledQuery:t,onDone:r,streamChunkSize:n,tedious:a}=o;if(this.#o=[],this.#r=n,this.#t={},this.#n=a,r){let s="onDone";this.#t[s]=(c,d)=>{if(c!=="chunkReady"){if(delete this.#t[s],c==="error")return r.reject(d);r.resolve({rowCount:this.#i,rows:this.#o})}}}this.#e=new this.#n.Request(t.sql,(s,c)=>{if(s)return Object.values(this.#t).forEach(d=>d("error",s instanceof AggregateError?s.errors:s));this.#i=c}),this.#a(t.parameters),this.#s()}get request(){return this.#e}readChunk(){let o=this.readChunk.name;return new Promise((t,r)=>{this.#t[o]=(n,a)=>{if(delete this.#t[o],n==="error")return r(a);t(this.#o.splice(0,this.#r))},this.#e.resume()})}#a(o){for(let t=0;t<o.length;t++){let r=o[t];this.#e.addParameter(String(t+1),this.#c(r),r)}}#s(){let o=this.#r?()=>{this.#r<=this.#o.length&&(this.#e.pause(),Object.values(this.#t).forEach(r=>r("chunkReady")))}:()=>{},t=r=>{let n={};for(let a of r)n[a.metadata.colName]=a.value;this.#o.push(n),o()};this.#e.on("row",t),this.#e.once("requestCompleted",()=>{Object.values(this.#t).forEach(r=>r("completed")),this.#e.off("row",t)})}#c(o){return nt(o)||vo(o)||B(o)?this.#n.TYPES.NVarChar:it(o)||ro(o)&&o%1===0?o<-2147483648||o>2147483647?this.#n.TYPES.BigInt:this.#n.TYPES.Int:ro(o)?this.#n.TYPES.Float:rt(o)?this.#n.TYPES.Bit:Fi(o)?this.#n.TYPES.DateTime:el(o)?this.#n.TYPES.VarBinary:this.#n.TYPES.NVarChar}}});var np=m(()=>{});var ip=m(()=>{});var ap=m(()=>{});var sp=m(()=>{});var Cb,jb,Ob,cp,lp=m(()=>{Er();kr();Cb=Symbol(),jb=Symbol(),Ob=Symbol(),cp=class{#e;#o;#r;#t;#n;constructor(o){this.#e=o}async executeQuery(o){try{let{affectedRows:t,rows:r}=await(this.#t||this.#e).query(o.sql,o.parameters,{rowMode:"object"});return{numAffectedRows:t!=null?BigInt(t):void 0,rows:r||[]}}catch(t){throw Jo(t,new Error)}}async*streamQuery(){throw new Error("Streaming is not supported by PGlite.")}async[Cb](){let{promise:o,reject:t,resolve:r}=new Se,{promise:n,resolve:a}=new Se;this.#o=r,this.#r=t,this.#n=this.#e.transaction(async s=>{this.#t=s,a(),await o}),await n}async[jb](){this.#o?.(),await this.#n,this.#o=void 0,this.#r=void 0,this.#t=void 0,this.#n=void 0}async[Ob](){this.#r?.(),await this.#n?.catch(()=>{}),this.#o=void 0,this.#r=void 0,this.#t=void 0,this.#n=void 0}}});var up=m(()=>{});var dp=m(()=>{});var pp=m(()=>{});var mp=m(()=>{});var fp=m(()=>{});var hp=m(()=>{});var gp=m(()=>{});var bp=m(()=>{});var wp=m(()=>{});var Xn=m(()=>{Rd();pu();Nd();ln();Qt();Ta();Hl();Yl();Xl();Sr();ma();za();Ul();va();_a();Jl();Da();Wa();Ja();du();uu();Vi();os();Pd();Od();Wn();ts();Rr();xd();ad();hd();ld();bd();nd();sd();id();cd();Uu();Qu();rd();dd();vd();md();Ku();td();Cd();gn();Ya();Ad();jd();Sd();Md();Id();Wd();Ld();Dd();zd();Fd();Gd();Ud();Vd();Jd();Qd();Xd();ep();Kd();Yd();Zd();op();ap();rp();np();ip();sp();lp();up();ts();dp();pp();ru();mp();fp();hp();gp();Mu();Gu();ed();Un();yo();Yu();tl();Do();dn();Vn();Xa();zu();Ui();Iu();Ge();ba();Kl();Zl();bp();rl();nl();il();fd();ud();wd();Ha();zl();Bu();An();Lu();Xu();al();sl();cl();gd();pd();la();ka();Ju();$r();Ia();Wu();Sa();ea();ta();ne();ra();br();_n();Ua();wr();vn();Ar();na();nu();ua();Vu();Oa();Vl();Bl();Bi();ze();tu();Td();Pt();Gl();st();bn();_r();pa();On();yr();fa();Ki();Zu();Gi();Co();ct();fn();Ka();Du();od();ca();at();mn();Wi();jr();ha();Aa();wp();gr();wa();Ga();Fa();Hu();Sn();aa();$n();Bo();Dl();Cr();xr();eu();yd();_d();$d();qd();Ed()});function vp(e){let o=Yt(e,["version","origen","entidades"]);if(o.version!==1)throw i("Perfil relacional inv\xE1lido.");let t=Tr(o.entidades,60).map(n=>{let a=Yt(n,["clave","destino","clave_externa","campos","referencias","procedencia","responsable","tipos","tiposColumna","acl","archivos"]);if(typeof a.destino!="string"||!(["contacts","companies","deals"].includes(a.destino)||/^mod_[a-z][a-z0-9_]{0,40}$/.test(a.destino)))throw i("Perfil relacional inv\xE1lido.");let s=Object.fromEntries(Object.entries(Yt(a.campos)).map(([b,v])=>(rs(b),[b,Kt(v)])));if(Object.keys(s).length>100)throw i("Perfil relacional inv\xE1lido.");let c=Tr(a.referencias??[],30).map(b=>{let v=Yt(b,["campo","entidad","clave","obligatoria"]);if(v.obligatoria!==void 0&&typeof v.obligatoria!="boolean")throw i("Perfil relacional inv\xE1lido.");return{campo:rs(v.campo),entidad:Yn(v.entidad),clave:ns(v.clave),obligatoria:v.obligatoria===!0}}),d=a.archivos===void 0?void 0:Tr(a.archivos,20).map(b=>{let v=Yt(b,["campo","columna","obligatorio"]);if(v.obligatorio!==void 0&&typeof v.obligatorio!="boolean")throw i("Perfil relacional inv\xE1lido.");return{campo:rs(v.campo),columna:Kt(v.columna),obligatorio:v.obligatorio===!0}});if(d?.length&&!a.destino.startsWith("mod_"))throw i("Perfil relacional inv\xE1lido.");let u=[...(d??[]).map(b=>b.campo),...Object.keys(s),...c.map(b=>b.campo)];if(new Set(u).size!==u.length)throw i("Perfil relacional inv\xE1lido.");let p=a.procedencia===void 0?void 0:Object.fromEntries(Object.entries(Yt(a.procedencia,["autor","creado","actualizado"])).map(([b,v])=>[b,Kt(v)])),f=a.responsable===void 0?void 0:ns(a.responsable),h=a.tipos===void 0?void 0:Tr(a.tipos,20).map(b=>{if(typeof b!="string"||!/^[a-z0-9][a-z0-9-]{0,59}$/.test(b))throw i("Perfil relacional inv\xE1lido.");return b});if(h&&!["contacts","companies"].includes(a.destino))throw i("Perfil relacional inv\xE1lido.");if(a.tiposColumna!==void 0&&(!h?.length||new Set(h).size!==h.length))throw i("Perfil relacional inv\xE1lido.");return{clave:Yn(a.clave),...a.acl!==void 0?{acl:Kt(a.acl)}:{},...d?{archivos:d}:{},destino:a.destino,...p?{procedencia:p}:{},...f?{responsable:f}:{},...h?{tipos:h}:{},...a.tiposColumna!==void 0?{tiposColumna:Kt(a.tiposColumna)}:{},clave_externa:ns(a.clave_externa),campos:s,referencias:c}}),r=new Map(t.map(n=>[n.clave,n]));if(!t.length||r.size!==t.length||t.some(n=>n.referencias.some(a=>!r.has(a.entidad)||r.get(a.entidad).clave_externa.length!==a.clave.length)))throw i("Perfil relacional inv\xE1lido.");return{version:1,origen:Yn(o.origen),entidades:t}}var Yn,rs,Kt,Yt,Tr,ns,yp=m(()=>{R();Yn=e=>{if(typeof e!="string"||!/^[a-z][a-z0-9_]{0,60}$/.test(e))throw i("Perfil relacional inv\xE1lido.");return e},rs=e=>{let o=typeof e=="string"&&/^datos\.[a-z][a-z0-9_]{0,60}$/.test(e)?e:Yn(e);if(["id","sales_id","espacio_id","modulo_id","creado_por","actualizado_por","responsable_id"].includes(o))throw i("Perfil relacional inv\xE1lido.");return o},Kt=e=>{if(typeof e!="string"||!/^[a-zA-Z][a-zA-Z0-9_]{0,79}$/.test(e)||/password|passwd|token|(^|_)pin($|_)|secret/i.test(e)||["constructor","prototype","__proto__"].includes(e))throw i("Perfil relacional inv\xE1lido.");return e},Yt=(e,o)=>{if(!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).some(t=>["__proto__","constructor","prototype"].includes(t)||o&&!o.includes(t)))throw i("Perfil relacional inv\xE1lido.");return e},Tr=(e,o)=>{if(!Array.isArray(e)||e.length>o)throw i("Perfil relacional inv\xE1lido.");return e},ns=e=>{let o=Tr(e,3).map(Kt);if(!o.length||new Set(o).size!==o.length)throw i("Perfil relacional inv\xE1lido.");return o}});function _p(e){if(e===void 0)return[];if(!Array.isArray(e)||e.length>30)throw i("Perfiles de importaci\xF3n inv\xE1lidos.");let o=new Set;return e.map(t=>{if(!t||typeof t!="object"||Array.isArray(t)||Object.keys(t).some(n=>!["clave","perfil"].includes(n)))throw i("Perfiles de importaci\xF3n inv\xE1lidos.");let r=t;if(typeof r.clave!="string"||!/^[a-z][a-z0-9_]{0,60}$/.test(r.clave)||o.has(r.clave))throw i("Perfiles de importaci\xF3n inv\xE1lidos.");return o.add(r.clave),{clave:r.clave,perfil:vp(r.perfil)}})}var Np=m(()=>{R();yp()});function is(e){return/^funciones\.([a-z0-9][a-z0-9-]{0,59})\.[a-z][a-z0-9_]{0,40}$/.exec(e)?.[1]}function Ab(e,o){return e==="contacts"&&/^(correo|telefono)(_(trabajo|personal))?$/.test(o)?o.startsWith("correo")?"email_jsonb":"phone_jsonb":Sb[e].includes(o)||/^datos\.[a-z][a-z0-9_]{0,40}$/.test(o)||is(o)?o:null}function $p(e){if(e===void 0)return[];if(!Array.isArray(e)||e.length>100)throw i("Identidades: hasta 100 restricciones por tipo.");let o=new Set;return e.map(t=>{if(!t||typeof t!="object"||Array.isArray(t))throw i("Restricci\xF3n de identidad no v\xE1lida.");let r=t;if(Object.keys(r).some(c=>!["objeto","tipo","nivel","campos"].includes(c))||!["contacts","companies"].includes(String(r.objeto))||typeof r.tipo!="string"||!/^[a-z0-9][a-z0-9-]{0,59}$/.test(r.tipo)||r.nivel!==void 0&&!["normal","no","lectura"].includes(String(r.nivel)))throw i("Restricci\xF3n de identidad no v\xE1lida.");let n=r.objeto,a=`${n}:${r.tipo}`;if(o.has(a))throw i("Restricci\xF3n de identidad repetida.");o.add(a);let s={};if(r.campos!==void 0){if(!r.campos||typeof r.campos!="object"||Array.isArray(r.campos)||Object.keys(r.campos).length>100)throw i("M\xE1scaras de identidad no v\xE1lidas.");for(let[c,d]of Object.entries(r.campos)){let u=Ab(n,c);if(!u||is(u)&&is(u)!==r.tipo||!["normal","lectura","oculto"].includes(String(d))||Object.hasOwn(s,u))throw i("Campo o nivel de identidad no v\xE1lido.");s[u]=d}}return{objeto:n,tipo:r.tipo,...r.nivel!==void 0?{nivel:r.nivel}:{},...Object.keys(s).length?{campos:s}:{}}})}var Sb,xp=m(()=>{R();Sb={contacts:["nif","iban","birthday","gender","address","zipcode","city","province","country","email_jsonb","phone_jsonb"],companies:["tax_identifier","iban","phone_number","correo_facturacion","address","zipcode","city","state_abbr","country"]}});function Cp(e){if(e==null)return;let o=Kn(e,["destino","anterior","ciclo","copiar","fechas","estado","precios"]);if(!o.copiar||typeof o.copiar!="object"||Array.isArray(o.copiar)||Object.keys(o.copiar).length>50||!Array.isArray(o.fechas)||!o.fechas.length||o.fechas.length>10)throw i("Sucesi\xF3n: configuraci\xF3n inv\xE1lida.");let t={anterior:Le(o.anterior),ciclo:Le(o.ciclo),copiar:Object.fromEntries(Object.entries(o.copiar).map(([r,n])=>[Le(r),Le(n)])),fechas:o.fechas.map(r=>{let n=Kn(r,["campo","desde","meses"]);if(typeof n.meses!="number"||!Number.isInteger(n.meses)||n.meses<1||n.meses>120)throw i("Sucesi\xF3n: configuraci\xF3n inv\xE1lida.");return{campo:Le(n.campo),desde:Le(n.desde),meses:n.meses}})};if(o.destino!==void 0&&(t.destino=Le(o.destino)),o.estado){let r=Kn(o.estado,["campo","valor"]);if(typeof r.valor!="string"||r.valor.length>100)throw i("Sucesi\xF3n: configuraci\xF3n inv\xE1lida.");t.estado={campo:Le(r.campo),valor:r.valor}}if(o.precios){let r=Kn(o.precios,["tabla","fecha","claves","valor","destino"]);if(!Array.isArray(r.claves)||r.claves.length<1||r.claves.length>3)throw i("Sucesi\xF3n: configuraci\xF3n inv\xE1lida.");t.precios={tabla:Le(r.tabla),fecha:Le(r.fecha),claves:r.claves.map(Le),valor:Le(r.valor),destino:Le(r.destino)}}if(new Set(t.fechas.map(r=>r.campo)).size!==t.fechas.length)throw i("Sucesi\xF3n: configuraci\xF3n inv\xE1lida.");return t}var Le,Kn,jp=m(()=>{R();Le=e=>{if(typeof e!="string"||!/^[a-z][a-z0-9_]{0,40}$/.test(e))throw i("Sucesi\xF3n: configuraci\xF3n inv\xE1lida.");return e},Kn=(e,o)=>{if(!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).some(t=>!o.includes(t)))throw i("Sucesi\xF3n: configuraci\xF3n inv\xE1lida.");return e}});var Mr,EM,Eb,Op=m(()=>{Mr=class e{n;d;constructor(o,t=1n){if(t===0n)throw new Error("decimal_division_cero");t<0n&&(o=-o,t=-t);let r=(a,s)=>s===0n?a<0n?-a:a:r(s,a%s),n=r(o,t);this.n=o/n,this.d=t/n}static leer(o){if(typeof o!="string"||!/^-?\d{1,18}(\.\d{1,6})?$/.test(o))throw new Error("decimal_invalido");let[t,r=""]=o.split(".");return new e(BigInt(t+r),10n**BigInt(r.length))}sumar(o){return new e(this.n*o.d+o.n*this.d,this.d*o.d)}restar(o){return this.sumar(new e(-o.n,o.d))}por(o){return new e(this.n*o.n,this.d*o.d)}entre(o){return new e(this.n*o.d,this.d*o.n)}comparar(o){let t=this.n*o.d-o.n*this.d;return t<0n?-1:t>0n?1:0}centimos(){let t=((this.n<0n?-this.n:this.n)*100n*2n+this.d)/(this.d*2n);return this.n<0n?-t:t}texto(){return Eb(this.centimos())}},EM=new Mr(0n),Eb=e=>`${e<0n?"-":""}${(e<0n?-e:e)/100n}.${String((e<0n?-e:e)%100n).padStart(2,"0")}`});function Ap(e,o){if(e==null)return;let t=be(e,["version","beneficiariosPeriodo","origen","fecha","importe","moneda","unidad","grupo","mantenimiento","ciclo","recuperacion","beneficiarios","motor","documento","cuentan","precios","unidad_recuento","componentes"]),r=be(t.motor,["reglas","combinar","margenNegativo","equipoPropio","principal","minimo","objetivo","fijoPeriodo"]),n=be(t.documento,["periodo","estado","total","beneficiario","lineas"]);if(t.version!==2||typeof t.origen!="string"||!/^mod_[a-z][a-z0-9_]{0,40}$/.test(t.origen))throw i("Liquidaci\xF3n v2: versi\xF3n u origen inv\xE1lido.");let a=(w,g)=>{let y=te(w);if(!o.some(C=>C.clave===y&&!C.archivado&&C.tipo===g))throw i("Liquidaci\xF3n v2: campo de documento inv\xE1lido.");return y},s=Object.fromEntries(Object.entries(be(t.beneficiarios)).map(([w,g])=>{let y=be(g,["tipo","campo"]);return[te(w),{tipo:yt(y.tipo,["miembro","contacts","companies","registro"]),campo:y.campo==="_dueno"?"_dueno":te(y.campo)}]}));if(!Object.keys(s).length||Object.keys(s).length>20)throw i("Liquidaci\xF3n v2: beneficiarios inv\xE1lidos.");let c=w=>{let g=be(w,["clave","beneficiario","fijo","porcentaje","resto","equipo","minimo"]),y=te(g.beneficiario);if(!s[y])throw i("Liquidaci\xF3n v2: beneficiario desconocido.");return{clave:te(g.clave),beneficiario:y,...g.fijo!==void 0?{fijo:vt(g.fijo)}:{},...g.porcentaje!==void 0?{porcentaje:as(g.porcentaje)}:{},...g.resto===!0?{resto:!0}:{},...g.equipo===!0?{equipo:!0}:{},...typeof g.minimo=="boolean"?{minimo:g.minimo}:{}}},d=Qo(r.reglas).map(w=>{let g=be(w,["clave","prioridad","modo","desde","hasta","moneda","unidad","si","bolsa","retencion","receptores"]);if(!Sp(g.desde)||g.hasta!==void 0&&(!Sp(g.hasta)||g.hasta<=g.desde))throw i("Liquidaci\xF3n v2: vigencia inv\xE1lida.");if(typeof g.moneda!="string"||!/^[A-Z]{3}$/.test(g.moneda)||typeof g.unidad!="string"||!g.unidad||g.unidad.length>60)throw i("Liquidaci\xF3n v2: moneda o unidad inv\xE1lida.");let y=g.si===void 0?void 0:be(g.si,["campo","valores"]);return{clave:te(g.clave),prioridad:Zn(g.prioridad),modo:yt(g.modo,["exclusiva","acumulable"]),desde:g.desde,...g.hasta?{hasta:g.hasta}:{},moneda:g.moneda,unidad:g.unidad,receptores:Qo(g.receptores).map(c),...g.bolsa!==void 0?{bolsa:vt(g.bolsa)}:{},...g.retencion!==void 0?{retencion:vt(g.retencion)}:{},...y?{si:{campo:te(y.campo),valores:Qo(y.valores).map(C=>String(C).slice(0,100))}}:{}}});if(new Set(d.map(w=>w.clave)).size!==d.length)throw i("Liquidaci\xF3n v2: regla duplicada.");let u;if(r.objetivo){let w=be(r.objetivo,["beneficiario","medida","modo","tramos","consumirBolsa"]),g=Qo(w.tramos).map(y=>{let C=be(y,["desde","tasa","garantia","bonus"]);return{desde:Zn(C.desde),tasa:w.medida==="recuento"?vt(C.tasa):as(C.tasa),...C.garantia!==void 0?{garantia:vt(C.garantia)}:{},...C.bonus!==void 0?{bonus:vt(C.bonus)}:{}}});if(!g.length||g[0].desde!==0||g.some((y,C)=>C>0&&y.desde<=g[C-1].desde))throw i("Liquidaci\xF3n v2: umbrales inv\xE1lidos.");u={beneficiario:te(w.beneficiario),medida:yt(w.medida,["recuento","importe"]),modo:yt(w.modo,["alcanzado","marginal"]),tramos:g,consumirBolsa:w.consumirBolsa===!0}}let p=r.minimo?be(r.minimo,["cantidad","modo"]):void 0,f=r.fijoPeriodo?Qo(r.fijoPeriodo).map(w=>{let g=be(w,["beneficiario","importe"]);return{beneficiario:te(g.beneficiario),importe:vt(g.importe)}}):void 0;if(f&&new Set(f.map(w=>w.beneficiario)).size!==f.length)throw i("Liquidaci\xF3n v2: fijo de periodo duplicado.");let h={version:2,origen:t.origen,fecha:te(t.fecha),importe:te(t.importe),moneda:te(t.moneda),unidad:te(t.unidad),grupo:t.grupo==="_dueno"?"_dueno":te(t.grupo),beneficiarios:s,motor:{reglas:d,combinar:r.combinar===!0,margenNegativo:r.margenNegativo===!0,equipoPropio:r.equipoPropio===!0,...r.principal?{principal:te(r.principal)}:{},...p?{minimo:{cantidad:Zn(p.cantidad),modo:yt(p.modo,["umbral","franquicia"])}}:{},...u?{objetivo:u}:{},...f?{fijoPeriodo:f}:{}},documento:{periodo:a(n.periodo,"texto"),estado:a(n.estado,"seleccion"),total:a(n.total,"texto"),beneficiario:a(n.beneficiario,"texto"),lineas:a(n.lineas,"subtabla")},...t.mantenimiento?{mantenimiento:te(t.mantenimiento)}:{}};if(t.beneficiariosPeriodo!==void 0&&(h.beneficiariosPeriodo=Qo(t.beneficiariosPeriodo,1e4).map(w=>{let g=be(w,["grupo","beneficiarios"]);if(typeof g.grupo!="string"||!g.grupo||g.grupo.length>100)throw i("Liquidaci\xF3n v2: grupo de periodo inv\xE1lido.");let y=Object.fromEntries(Object.entries(be(g.beneficiarios)).map(([C,O])=>{if(!s[C]||typeof O!="number"||!Number.isSafeInteger(O)||O<1)throw i("Liquidaci\xF3n v2: beneficiario de periodo inv\xE1lido.");return[C,O]}));return{grupo:g.grupo,beneficiarios:y}}),new Set(h.beneficiariosPeriodo.map(w=>w.grupo)).size!==h.beneficiariosPeriodo.length))throw i("Liquidaci\xF3n v2: grupo de periodo duplicado.");if(t.cuentan){let w=be(t.cuentan,["campo","valores"]);h.cuentan={campo:te(w.campo),valores:Qo(w.valores).map(String)}}if(t.unidad_recuento&&(h.unidad_recuento=te(t.unidad_recuento)),t.componentes){let w=be(t.componentes,["modo","campo"]);h.componentes={modo:yt(w.modo,["todos","principal"]),campo:te(w.campo)}}if(t.precios){let w=be(t.precios,["tabla","fecha","claves","valor"]);if(h.precios={tabla:te(w.tabla),fecha:te(w.fecha),claves:Qo(w.claves,3).map(te),valor:te(w.valor)},!h.precios.claves.length)throw i("Liquidaci\xF3n v2: claves de precio ausentes.")}if(t.ciclo&&(h.ciclo=te(t.ciclo)),t.recuperacion){let w=be(t.recuperacion,["modo","plazo"]);if(h.recuperacion={modo:yt(w.modo,["total","proporcional_dias"]),plazo:Zn(w.plazo)},h.recuperacion.plazo===0)throw i("Liquidaci\xF3n v2: plazo inv\xE1lido.")}if([h.motor.principal,h.motor.objetivo?.beneficiario,...(h.motor.fijoPeriodo??[]).map(w=>w.beneficiario)].some(w=>w&&!s[w]))throw i("Liquidaci\xF3n v2: beneficiario desconocido.");let b=o.find(w=>w.clave===h.documento.lineas);if(["fuente","concepto","importe"].some(w=>!b.columnas?.some(g=>g.clave===w&&g.tipo==="texto"&&!g.archivado)))throw i("Liquidaci\xF3n v2: columnas de resumen inv\xE1lidas.");let v=o.find(w=>w.clave===h.documento.estado);if(["borrador","aprobada","cerrada","pagada"].some(w=>!v.opciones?.some(g=>g.valor===w)))throw i("Liquidaci\xF3n v2: estados inv\xE1lidos.");return h}var be,Sp,te,as,vt,Qo,yt,Zn,Ep=m(()=>{R();Op();be=(e,o)=>{if(!e||typeof e!="object"||Array.isArray(e))throw i("Liquidaci\xF3n v2: objeto inv\xE1lido.");if(o&&Object.keys(e).some(t=>!o.includes(t)))throw i("Liquidaci\xF3n v2: propiedad desconocida.");return e},Sp=e=>typeof e=="string"&&/^\d{4}-\d{2}-\d{2}$/.test(e)&&Number.isFinite(Date.parse(e+"T00:00:00Z"))&&new Date(e+"T00:00:00Z").toISOString().slice(0,10)===e,te=e=>{if(typeof e!="string"||!/^[a-z][a-z0-9_]{0,40}$/.test(e))throw i("Liquidaci\xF3n v2: clave inv\xE1lida.");return e},as=e=>{if(typeof e!="string")throw i("Liquidaci\xF3n v2: decimal como cadena.");try{if(Mr.leer(e).n<0n)throw new Error("negativo")}catch{throw i("Liquidaci\xF3n v2: decimal inv\xE1lido.")}return e},vt=e=>{let o=as(e);if(!/^\d{1,18}(?:\.\d{1,2})?$/.test(o))throw i("Liquidaci\xF3n v2: el importe manual admite como m\xE1ximo dos decimales.");return o},Qo=(e,o=20)=>{if(!Array.isArray(e)||e.length>o)throw i("Liquidaci\xF3n v2: lista inv\xE1lida.");return e},yt=(e,o)=>{if(!o.includes(e))throw i("Liquidaci\xF3n v2: opci\xF3n inv\xE1lida.");return e},Zn=e=>{if(typeof e!="number"||!Number.isSafeInteger(e)||e<0)throw i("Liquidaci\xF3n v2: entero inv\xE1lido.");return e}});function qp(e,o){if(e==null)return;if(typeof e!="object"||Array.isArray(e))throw i("precios: un objeto.");let t=e,r=["claves","desde","hasta","prioridad","moneda","unidad","valores","solape","falta"];if(Object.keys(t).some(s=>!r.includes(s)))throw i("precios: propiedad desconocida.");let n=(s,c)=>{let d=o.find(u=>u.clave===s&&!u.archivado);if(!d||!c.includes(d.tipo)||d.multiple)throw i("precios: campo inv\xE1lido.");return d.clave},a=(s,c,d)=>{if(!Array.isArray(s)||!s.length||s.length>d||new Set(s).size!==s.length)throw i("precios: lista vac\xEDa, duplicada o demasiado larga.");return s.map(u=>n(u,c))};if(!["bloquear","prioridad"].includes(String(t.solape))||!["bloquear","pendiente"].includes(String(t.falta)))throw i("precios: pol\xEDtica inv\xE1lida.");return{claves:a(t.claves,["texto","seleccion","relacion","numero"],3),desde:n(t.desde,["fecha"]),...t.hasta?{hasta:n(t.hasta,["fecha"])}:{},prioridad:n(t.prioridad,["numero"]),moneda:n(t.moneda,["texto","seleccion"]),unidad:n(t.unidad,["texto","seleccion"]),valores:a(t.valores,["importe","numero","porcentaje"],20),solape:t.solape,falta:t.falta}}var Rp=m(()=>{R()});function Ir(e,o){if(!Array.isArray(o)||o.length<1||o.length>100)throw i("Una lista lleva entre 1 y 100 elementos.");let t=new Set,r=o.map((n,a)=>{let s=n&&typeof n=="object"?n:{},c=typeof s.value=="string"?s.value.trim():"",d=typeof s.label=="string"?s.label.trim():"";if(!c||c.length>80||!ss(c))throw i(`El elemento ${a+1} no tiene una clave v\xE1lida.`);if(!d||d.length>80||!ss(d))throw i(`El elemento ${a+1} necesita un nombre (hasta 80 caracteres).`);if(t.has(c))throw i(`La clave \xAB${c}\xBB est\xE1 repetida.`);t.add(c);let u={value:c,label:d};if(s.color!==void 0&&s.color!==null&&s.color!==""){if(typeof s.color!="string"||!kb.test(s.color))throw i(`El color de \xAB${d}\xBB no es v\xE1lido.`);u.color=s.color}return s.archivado===!0&&(u.archivado=!0),e==="contactTypes"&&Object.assign(u,Pb(s,d)),u});if(!r.some(n=>!n.archivado))throw i("Una lista necesita al menos un elemento sin archivar.");if(e==="dealStages")for(let n of qb){let a=r.find(s=>s.value===n);if(!a)throw new F(400,"etapa_fija","Las etapas \xABGanada\xBB y \xABPerdida\xBB no se pueden quitar; se pueden renombrar.");if(a.archivado)throw new F(400,"etapa_fija","Las etapas \xABGanada\xBB y \xABPerdida\xBB no se pueden archivar; se pueden renombrar.")}if(e==="contactTypes"){for(let s of kp){let c=r.find(d=>d.value===s);if(!c)throw new F(400,"tipo_fijo","Los tipos \xABCliente\xBB y \xABProveedor\xBB no se pueden quitar; se pueden renombrar.");if(c.archivado)throw new F(400,"tipo_fijo","Los tipos \xABCliente\xBB y \xABProveedor\xBB no se pueden archivar; se pueden renombrar.")}let n=r.find(s=>!/^[a-z0-9][a-z0-9-]{0,59}$/.test(s.value));if(n)throw i(`La clave \xAB${n.value}\xBB de un tipo: min\xFAsculas, n\xFAmeros y guiones.`);let a=r.find(s=>s.de&&kp.includes(s.value));if(a)throw i(`\xAB${a.label}\xBB no puede ser un tipo de otro.`)}if(e==="legalForms"){let n=r.find(a=>!/^[a-z0-9][a-z0-9-]{0,59}$/.test(a.value));if(n)throw i(`La clave \xAB${n.value}\xBB de una forma jur\xEDdica: min\xFAsculas, n\xFAmeros y guiones.`)}return r}function Pb(e,o){let t=typeof e.plural=="string"&&e.plural.trim()?e.plural.trim():o;if(t.length>80||!ss(t))throw i(`El plural de \xAB${o}\xBB: hasta 80 caracteres.`);let r={plural:t,objeto:e.objeto==="companies"?"companies":"contacts",menu:e.menu===!0};if(e.objetos!==void 0){if(!Array.isArray(e.objetos)||e.objetos.length<1||e.objetos.length>2||new Set(e.objetos).size!==e.objetos.length||!e.objetos.includes(r.objeto)||e.objetos.some(n=>n!=="contacts"&&n!=="companies"))throw i("Las listas del tipo deben incluir su objeto principal y solo Personas o Empresas, sin repetir.");r.objetos=e.objetos}if(e.de!==void 0&&e.de!==null&&e.de!==""){if(e.de!=="cliente"&&e.de!=="proveedor")throw i(`\xAB${o}\xBB: solo puede ser un tipo de Cliente o de Proveedor.`);r.de=e.de}if(e.icono!==void 0&&e.icono!==null&&e.icono!==""){if(typeof e.icono!="string"||!Rb.test(e.icono))throw i(`El icono de \xAB${o}\xBB no es v\xE1lido.`);r.icono=e.icono}return r}var qb,kp,Rb,ss,kb,ls=m(()=>{R();qb=["won","lost"],kp=["cliente","proveedor"],Rb=/^[a-z0-9-]{1,40}$/,ss=e=>!/[\u0000-\u001f\u007f]/.test(e),kb=/^#[0-9a-fA-F]{3,8}$|^[a-z]{3,20}$/});function Pp(e,o,t){if(e.propiedad!==void 0){if(!Ee(e.propiedad)||o.tipo!=="seleccion"||!o.obligatorio||e.formas!==void 0||e.etiquetas!==void 0||e.vacio!==void 0)throw i("La clasificaci\xF3n propia necesita una selecci\xF3n obligatoria, sin alternativas fiscales, etiquetas ni valor vac\xEDo.");return{propiedad:e.propiedad}}if(e.formas!==void 0&&!Tb(e.formas))throw i("Las formas de clasificaci\xF3n necesitan opciones de Empresa y claves fiscales v\xE1lidas.");let r={};for(let[a,s]of Object.entries(e.formas??{})){if(!Object.hasOwn(t,a)||t[a]!=="companies"||typeof s!="string"||s!==s.trim())throw i("Las formas de clasificaci\xF3n necesitan opciones de Empresa y claves fiscales v\xE1lidas.");Ir("legalForms",[{value:s,label:us(o,a)}]),r[a]=s}if(e.etiquetas!==void 0&&(!Array.isArray(e.etiquetas)||new Set(e.etiquetas).size!==e.etiquetas.length||e.etiquetas.some(a=>typeof a!="string"||!Object.hasOwn(t,a)||t[a]!=="contacts")))throw i("Las etiquetas de clasificaci\xF3n necesitan opciones distintas de Persona.");let n=e.etiquetas??[];for(let a of n){let s=o.opciones?.find(c=>c.valor===a);if(us(o,a).length>60||s?.color&&!/^#[0-9a-fA-F]{6}$/.test(s.color))throw i("La etiqueta de clasificaci\xF3n necesita nombre de hasta 60 caracteres y color #rrggbb.")}for(let a of["contacts","companies"])if(Object.entries(t).filter(([c,d])=>d===a&&!Object.hasOwn(r,c)&&!n.includes(c)).length>1)throw i("Las opciones que comparten objeto necesitan forma jur\xEDdica o etiqueta para conservar su significado.");return{...e.formas!==void 0?{formas:r}:{},...e.etiquetas!==void 0?{etiquetas:n}:{}}}function Tp(e,o){if(!o?.formas)return[];let t=e.find(a=>a.clave===o.campo),r=Object.entries(o.formas).map(([a,s])=>({value:s,label:us(t,a),...t.opciones?.find(c=>c.valor===a)?.color?{color:t.opciones.find(c=>c.valor===a).color}:{}})),n=new Map;for(let a of r){let s=n.get(a.value);if(s&&(s.label!==a.label||s.color!==a.color))throw i("Una forma jur\xEDdica de clasificaci\xF3n tiene etiquetas contradictorias.");n.set(a.value,a)}return Ir("legalForms",[...n.values()])}function Mp(e,o,t){return o?.propiedad?e.map(r=>r.clave===o.campo?{...r,opciones:r.opciones?.filter(n=>o.valores[n.valor]===t)}:r):e}var Tb,us,Ip=m(()=>{R();ls();Lr();Tb=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);us=(e,o)=>e.opciones?.find(t=>t.valor===o)?.etiqueta??e.etiqueta});var j,Lp,Dp=m(()=>{j=(e,o,t={})=>({clave:e,tipo:o,enTabla:!1,ordenable:o!=="texto_largo",filtrable:!1,editable:!["contador","fecha_hora","correos","telefonos","etiquetas"].includes(o),...t}),Lp=[{clave:"companies",icono:"building-2",campoTitulo:"name",campos:[j("name","texto",{enTabla:!0,ancho:240}),j("website","url",{enTabla:!0,ancho:200}),j("sector","seleccion",{enTabla:!0,filtrable:!0,opciones:"config:companySectors"}),j("tags","etiquetas",{enTabla:!0,ordenable:!1,editable:!0,filtrable:!0,relacion:"tags",objetoEtiquetas:"companies",ancho:160,migracion:"0466_etiquetas_por_objeto.sql"}),j("size","seleccion",{enTabla:!0,filtrable:!0,opciones:[{valor:"1",etiqueta:"1"},{valor:"10",etiqueta:"2-9"},{valor:"50",etiqueta:"10-49"},{valor:"250",etiqueta:"50-249"},{valor:"500",etiqueta:"250+"}],ancho:110}),j("city","texto",{enTabla:!0,ancho:140}),j("sales_id","relacion",{enTabla:!0,filtrable:!0,relacion:"sales",ancho:170}),j("nb_contacts","contador",{enTabla:!0,ancho:110}),j("nb_deals","contador",{enTabla:!0,ancho:130}),j("created_at","fecha_hora",{enTabla:!0,ancho:140}),j("proveedor","booleano",{filtrable:!0,ancho:110}),j("has_newsletter","booleano",{etiqueta:"Comunicaciones",filtrable:!0,migracion:"0490_comunicaciones_empresa.sql"}),j("tipos","seleccion_multiple",{enTabla:!0,ordenable:!1,editable:!1,opciones:"config:contactTypes",ancho:170,migracion:"0439_tipos_contactos.sql"}),j("ubicacion","ubicacion",{etiqueta:"Ubicaci\xF3n",editable:!1,ordenable:!1,migracion:"0452_ubicacion_nativa.sql"}),j("phone_number","telefono",{ancho:150}),j("country","texto",{ancho:130}),j("address","texto"),j("state_abbr","texto",{soloFicha:!0,etiqueta:"Provincia"}),j("zipcode","texto",{ancho:110}),j("linkedin_url","url"),j("revenue","texto",{ancho:130}),j("tax_identifier","texto",{ancho:140}),j("razon_social","texto",{ancho:220,migracion:"0440_datos_fiscales.sql"}),j("forma_juridica","seleccion",{filtrable:!0,opciones:"config:legalForms",ancho:160,migracion:"0440_datos_fiscales.sql"}),j("correo_facturacion","correo",{ancho:220,migracion:"0440_datos_fiscales.sql"}),j("pais_fiscal","texto",{filtrable:!0,editable:!1,ancho:90,migracion:"0440_datos_fiscales.sql"}),j("description","texto_largo",{ancho:260})]},{clave:"contacts",icono:"users",campoTitulo:"first_name",camposTitulo:["first_name","last_name"],campos:[j("ubicacion","ubicacion",{etiqueta:"Ubicaci\xF3n",editable:!1,ordenable:!1,migracion:"0452_ubicacion_nativa.sql"}),j("first_name","texto",{enTabla:!0,ancho:220}),j("last_name","texto",{ancho:150}),j("title","texto",{enTabla:!0,ancho:150}),j("company_id","relacion",{enTabla:!0,relacion:"companies",ancho:180}),j("email_jsonb","correos",{enTabla:!0,ordenable:!1,editable:!0,ancho:220}),j("phone_jsonb","telefonos",{enTabla:!0,ordenable:!1,editable:!0,ancho:150}),j("status","seleccion",{enTabla:!0,filtrable:!0,opciones:"config:noteStatuses",ancho:130}),j("tags","etiquetas",{enTabla:!0,ordenable:!1,editable:!0,filtrable:!0,relacion:"tags",objetoEtiquetas:"contacts",ancho:160}),j("tipos","seleccion_multiple",{enTabla:!0,ordenable:!1,editable:!1,opciones:"config:contactTypes",ancho:170,migracion:"0439_tipos_contactos.sql"}),j("sales_id","relacion",{enTabla:!0,filtrable:!0,relacion:"sales",ancho:170}),j("last_seen","fecha_hora",{enTabla:!0,ancho:140}),j("nb_tasks","contador",{ancho:110}),j("first_seen","fecha_hora",{ancho:140}),j("linkedin_url","url"),j("background","texto_largo",{ancho:260}),j("nif","texto",{soloFicha:!0,sensible:!0,etiqueta:"Identificador fiscal",migracion:"0005_datos_es.sql"}),j("iban","texto",{soloFicha:!0,sensible:!0,etiqueta:"IBAN",migracion:"0005_datos_es.sql"}),j("birthday","fecha",{soloFicha:!0,etiqueta:"Fecha de nacimiento",migracion:"0005_datos_es.sql"}),j("address","texto",{soloFicha:!0,etiqueta:"Direcci\xF3n",migracion:"0005_datos_es.sql"}),j("zipcode","texto",{soloFicha:!0,etiqueta:"C\xF3digo postal",migracion:"0005_datos_es.sql"}),j("city","texto",{soloFicha:!0,etiqueta:"Ciudad",migracion:"0005_datos_es.sql"}),j("province","texto",{soloFicha:!0,etiqueta:"Provincia",migracion:"0005_datos_es.sql"}),j("country","texto",{soloFicha:!0,etiqueta:"Pa\xEDs",migracion:"0005_datos_es.sql"}),j("has_newsletter","booleano",{soloFicha:!0,migracion:"0005_datos_es.sql"}),j("pais_fiscal","texto",{filtrable:!0,editable:!1,ancho:90,migracion:"0440_datos_fiscales.sql"})]},{clave:"deals",icono:"handshake",campoTitulo:"name",campos:[j("name","texto",{enTabla:!0,ancho:240}),j("company_id","relacion",{enTabla:!0,relacion:"companies",ancho:180}),j("stage","seleccion",{enTabla:!0,filtrable:!0,opciones:"config:dealStages",ancho:160}),j("amount","importe",{enTabla:!0,ancho:120}),j("expected_closing_date","fecha",{enTabla:!0,ancho:140}),j("category","seleccion",{enTabla:!0,filtrable:!0,opciones:"config:dealCategories",ancho:150}),j("tags","etiquetas",{enTabla:!0,ordenable:!1,editable:!0,filtrable:!0,relacion:"tags",objetoEtiquetas:"deals",ancho:160,migracion:"0466_etiquetas_por_objeto.sql"}),j("sales_id","relacion",{enTabla:!0,filtrable:!0,relacion:"sales",ancho:170}),j("origen_lead","texto",{etiqueta:"Origen",filtrable:!0,editable:!1,ancho:170,migracion:"0467_oportunidades_origen_actividad.sql"}),j("ultima_actividad","fecha_hora",{etiqueta:"\xDAltima actividad",editable:!1,ancho:150,migracion:"0467_oportunidades_origen_actividad.sql"}),j("created_at","fecha_hora",{ancho:140}),j("updated_at","fecha_hora",{ancho:140}),j("description","texto_largo",{ancho:260})]},{clave:"proyectos",icono:"folder-kanban",campoTitulo:"nombre",campos:[j("nombre","texto",{enTabla:!0,ancho:220}),j("clave","texto",{enTabla:!0,ancho:110,editable:!1}),j("estado","seleccion",{enTabla:!0,filtrable:!0,opciones:[{valor:"activo",etiqueta:"Activo"},{valor:"en_pausa",etiqueta:"En pausa"},{valor:"archivado",etiqueta:"Archivado"}],ancho:120}),j("sales_id","relacion",{enTabla:!0,filtrable:!0,relacion:"sales",ancho:170}),j("fecha_inicio","fecha",{enTabla:!0,ancho:130}),j("fecha_fin","fecha",{enTabla:!0,ancho:130}),j("requiere_aceptacion","booleano",{ancho:120}),j("color","texto",{ancho:100}),j("icono","texto",{ancho:100}),j("descripcion","texto_largo",{ancho:260}),j("creado","fecha_hora",{ancho:140}),j("actualizado","fecha_hora",{ancho:140})]},{clave:"tareas",icono:"check-square",campoTitulo:"titulo",campos:[j("titulo","texto",{enTabla:!0,ancho:240}),j("codigo_corto","texto",{enTabla:!0,ancho:110,editable:!1}),j("proyecto_id","relacion",{enTabla:!0,filtrable:!0,relacion:"proyectos",ancho:170,editable:!1}),j("columna_id","texto",{enTabla:!0,filtrable:!0,ancho:130}),j("prioridad","seleccion",{enTabla:!0,filtrable:!0,opciones:[{valor:"baja",etiqueta:"Baja"},{valor:"media",etiqueta:"Media"},{valor:"alta",etiqueta:"Alta"},{valor:"urgente",etiqueta:"Urgente"}],ancho:110}),j("sales_id","relacion",{enTabla:!0,filtrable:!0,relacion:"sales",ancho:170}),j("fecha_entrega","fecha",{enTabla:!0,ancho:130}),j("fecha_inicio","fecha",{ancho:130}),j("estimacion_minutos","numero",{ancho:110}),j("hecho","fecha_hora",{enTabla:!0,editable:!0,marca:!0,ancho:120}),j("contact_id","relacion",{filtrable:!0,relacion:"contacts",ancho:160}),j("descripcion","texto_largo",{ancho:260}),j("creado","fecha_hora",{ancho:140}),j("actualizado","fecha_hora",{ancho:140})]}]});var zp,Mb,UM,Fp,Wp=m(()=>{zp=new Set(["texto","texto_largo","numero","importe","porcentaje","fecha","fecha_hora","hora","duracion","booleano","seleccion","seleccion_multiple","url","correo","telefono","color","codigo","valoracion","autonumero"]),Mb=new Set([...zp,"relacion"]),UM=new Set([...zp,"relacion"]),Fp=new Set([...Mb,"busqueda"])});function Bp(e){let o=To(),t=(e==="contacts"?Ib:Lb).map(([r,n])=>({clave:r,etiqueta:to(o,n),tipo:["correo","correo_facturacion"].includes(r)?"correo":["telefono","phone_number"].includes(r)?"telefono":["background","description"].includes(r)?"texto_largo":r==="website"?"url":"texto",obligatorio:r==="first_name"||r==="name",...Db(e).has(r)?{}:{permisos:{administrador:"lectura",miembro:"lectura",lectura:"lectura"}}}));return{id:0,clave:`@${e}`,nombre:to(o,e==="contacts"?"Persona":"Empresa"),nombre_plural:to(o,e==="contacts"?"Personas":"Empresas"),descripcion:"",icono:e==="contacts"?"users":"building-2",estado:"publicado",campos:t}}var ei,Ib,Lb,Db,Up=m(()=>{on();ei=[["address","Direcci\xF3n"],["zipcode","C\xF3digo postal"],["city","Ciudad"],["country","Pa\xEDs"]],Ib=[["first_name","Nombre"],["last_name","Apellidos"],["title","Cargo"],["correo","Correo"],["telefono","Tel\xE9fono"],...ei,["background","Contexto"],["nif","Identificador fiscal"],["pais_fiscal","Pa\xEDs fiscal"]],Lb=[["name","Nombre"],["phone_number","Tel\xE9fono"],["website","Web"],...ei,["description","Descripci\xF3n"],["persona_first_name","Nombre de la persona"],["correo_facturacion","Correo de facturaci\xF3n"],["tax_identifier","Identificador fiscal"],["razon_social","Raz\xF3n social"],["pais_fiscal","Pa\xEDs fiscal"]],Db=e=>new Set(e==="contacts"?["first_name","last_name","title","telefono",...ei.map(([o])=>o),"background"]:["name","phone_number","website",...ei.map(([o])=>o),"description","persona_first_name"])});function Vp(e){let o=new Map(e.filter(s=>!s.archivado&&s.completarDesde).map(s=>[s.clave,s])),t=new Map,r=new Set,n=[],a=s=>{if(r.has(s.clave))throw i("El autocompletado necesita dependencias sin ciclos y hasta seis pasos.");if(t.has(s.clave))return t.get(s.clave);r.add(s.clave);let c=0;for(let d of ds(s)){let u=o.get(d.relacion);u&&(c=Math.max(c,a(u)+1))}if(c>6)throw i("El autocompletado necesita dependencias sin ciclos y hasta seis pasos.");return r.delete(s.clave),t.set(s.clave,c),n.push(s),c};for(let s of o.values())a(s);return n}var ds,Jp=m(()=>{R();ds=e=>e.completarDesde?[e.completarDesde,...e.completarDesde.alternativa?[e.completarDesde.alternativa]:[]]:[]});function Fb(e){let o=[],t=0;for(;t<e.length;){let r=e[t];if(/\s/.test(r)){t++;continue}if(o.length>=Qp)throw i(`F\xF3rmula demasiado larga: como mucho ${Qp} piezas.`);if(/[0-9]/.test(r)||r==="."&&/[0-9]/.test(e[t+1]??"")){let s=/^[0-9]*\.?[0-9]+|^[0-9]+/.exec(e.slice(t));if(s[0].length>20)throw i("F\xF3rmula: n\xFAmero demasiado largo.");o.push({t:"num",v:s[0]}),t+=s[0].length;continue}if(r==='"'||r==="'"){let s="",c=t+1;for(;;){if(c>=e.length)throw i("F\xF3rmula: falta cerrar unas comillas.");if(e[c]===r){if(e[c+1]===r){s+=r,c+=2;continue}break}s+=e[c],c++}if(s.length>500)throw i("F\xF3rmula: un texto de como mucho 500 caracteres.");o.push({t:"txt",v:s}),t=c+1;continue}if(r==="{"){let s=e.indexOf("}",t);if(s<0)throw i("F\xF3rmula: falta cerrar una llave \xAB}\xBB.");let c=e.slice(t+1,s).trim();if(!c||c.length>80)throw i("F\xF3rmula: un campo entre llaves no v\xE1lido.");o.push({t:"campo",v:c}),t=s+1;continue}let n=/^[A-Za-zÁÉÍÓÚÜÑáéíóúüñ_][A-Za-z0-9ÁÉÍÓÚÜÑáéíóúüñ_.]*/.exec(e.slice(t));if(n){if(n[0].length>40)throw i("F\xF3rmula: nombre demasiado largo.");o.push({t:"id",v:n[0]}),t+=n[0].length;continue}let a=zb.find(s=>e.startsWith(s,t));if(!a)throw i(`F\xF3rmula: no se entiende \xAB${r}\xBB.`);o.push({t:"op",v:a==="!="?"<>":a===";"?",":a}),t+=a.length}return o.push({t:"fin"}),o}function Bb(e){let o=Fb(e),t=0,r=0,n=()=>o[t],a=g=>n().t==="op"&&n().v===g,s=g=>{if(!a(g))throw i(`F\xF3rmula: se esperaba \xAB${g}\xBB.`);t++},c=g=>{if(++r>Gp)throw i(`F\xF3rmula: como mucho ${Gp} niveles de anidaci\xF3n.`);try{return g()}finally{r--}},d=(g,y,C=!1)=>()=>{let O=y();for(;n().t==="op"&&g.includes(n().v)&&(O={k:"bin",op:o[t++].v,a:O,b:y()},!C););return O},u=()=>c(()=>{let g=n();if(g.t==="num")return t++,{k:"num",v:g.v};if(g.t==="txt")return t++,{k:"txt",v:g.v};if(g.t==="campo")return t++,{k:"campo",v:g.v};if(g.t==="op"&&g.v==="-")return t++,{k:"neg",a:u()};if(g.t==="op"&&g.v==="("){t++;let y=v();return s(")"),y}if(g.t==="id"){t++;let y=Wb(g.v);if(!a("(")){if(y==="VERDADERO"||y==="TRUE")return{k:"bool",v:!0};if(y==="FALSO"||y==="FALSE")return{k:"bool",v:!1};throw i(`F\xF3rmula: \xAB${g.v}\xBB no es una funci\xF3n (los campos van entre llaves: {${g.v}}).`)}t++;let C=[];if(!a(")"))for(;;){if(C.push(v()),C.length>Xp)throw i(`F\xF3rmula: como mucho ${Xp} argumentos.`);if(a(",")){t++;continue}break}return s(")"),{k:"fn",f:y,args:C}}throw i(g.t==="fin"?"F\xF3rmula incompleta.":"F\xF3rmula: algo sobra o falta.")}),p=d(["*","/"],u),f=d(["+","-"],p),h=d(["&"],f),b=d(["=","<>","<","<=",">",">="],h,!0),v=()=>c(b),w=v();if(n().t!=="fin")throw i("F\xF3rmula: algo sobra al final.");return w}function ps(e){if(!Ye(e,0))throw i("F\xF3rmula: A\xD1O, MES y DIA necesitan una fecha.");return"numero"}function Kp(e){let o=e[0];for(let t of e.slice(1))o=er(o,t);if(o!=="numero"&&o!=="fecha"&&o!=="fecha_hora")throw i("F\xF3rmula: MIN y MAX, con n\xFAmeros o fechas.");return o}function er(e,o){if(e===o)return e;if(Ye([e,o],0)&&Ye([e,o],1))return"fecha_hora";throw i(`F\xF3rmula: no se mezclan ${Nt[e]} y ${Nt[o]}.`)}function oi(e){if(!e)return 0;if(e.k!=="num"||!/^\d+$/.test(e.v)||Number(e.v)>10)throw i("F\xF3rmula: REDONDEAR, con 0 a 10 decimales.");return Number(e.v)}function ms(e,o){let t=ws(e),r=t.find(n=>n.clave===o)??t.find(n=>n.etiqueta.trim().toLowerCase()===o.trim().toLowerCase());if(!r)throw i(`F\xF3rmula: no hay un campo \xAB${o}\xBB.`);return r}function fs(e,o,t){if(!o.includes("."))return null;let r=o.trim().toLowerCase();if(ws(e).some(a=>a.clave===o||a.etiqueta.trim().toLowerCase()===r))return null;let n=t?.[o];if(!n)throw i(`F\xF3rmula: no hay un campo \xAB${o}\xBB.`);return n}function Jb(e){let o=e.saltos.at(-1).modulo;if(om[o]){let t=Ee(e.campo)?e.campos.find(n=>n.clave===e.campo&&!n.archivado):void 0,r=t?bs[t.tipo]:Zp[zr(o).find(n=>n.clave===e.campo)?.tipo??""];if(!r)throw i(`F\xF3rmula: \xAB${e.campo}\xBB no se puede usar en una f\xF3rmula.`);return r}return em({campos:e.campos},Vb(e),[])}function em(e,o,t){if(o.tipo==="formula")return tm(e,o,t).tipo;let r=o.tipo==="busqueda"||o.tipo==="resumen"?o.origen?.tipo??"":o.tipo,n=bs[r];if(!n)throw i(`F\xF3rmula: el campo \xAB${o.etiqueta}\xBB no se puede usar en una f\xF3rmula.`);return o.tipo==="busqueda"&&Qb(e,o),n}function Qb(e,o){let t=ws(e).find(r=>r.clave===o.desde);if(!t?.relacion||t.multiple)throw i(`F\xF3rmula: la b\xFAsqueda \xAB${o.etiqueta}\xBB trae varios valores y no se usa en una f\xF3rmula.`);if(o.origen?.encadenada)throw i(`F\xF3rmula: la b\xFAsqueda \xAB${o.etiqueta}\xBB ya va encadenada y no se usa en una f\xF3rmula.`);if(t.relacion.startsWith("mod_")){if(!/^[a-z][a-z0-9_]{0,40}$/.test(o.campo??"")||Gb.has(o.origen?.tipo??""))throw i(`F\xF3rmula: la b\xFAsqueda \xAB${o.etiqueta}\xBB no es v\xE1lida.`)}else{let r=zr(t.relacion).find(n=>n.clave===o.campo)??(Ee(o.campo)&&o.origen?{tipo:o.origen.tipo}:void 0);if(!r||!(Ee(o.campo)?bs[r.tipo]:Zp[r.tipo])||!om[t.relacion])throw i(`F\xF3rmula: la b\xFAsqueda \xAB${o.etiqueta}\xBB no se puede usar en una f\xF3rmula.`)}return{rel:t}}function tm(e,o,t){if(t.includes(o.clave))throw i(`F\xF3rmula: \xAB${o.etiqueta}\xBB se usa a s\xED misma (en cadena).`);if(t.length>=Hp)throw i(`F\xF3rmula: como mucho ${Hp} f\xF3rmulas encadenadas.`);return Hb(e,o.formula??"",[...t,o.clave],o.origen?.rutas)}function Hb(e,o,t,r){if(typeof o!="string"||!o.trim())throw i("F\xF3rmula vac\xEDa.");if(o.length>Ke)throw i(`F\xF3rmula de como mucho ${Ke} caracteres.`);let n=Bb(o),a=new Map,s=u=>{let p=d(u);return a.set(u,p),p},c=(u,p,f)=>{let h=s(u);if(h!==p){if(u.k==="campo"){let v=fs(e,u.v,r)?u.v:ms(e,u.v).etiqueta;throw i(`F\xF3rmula: \xAB${v}\xBB no es ${Nt[p]}, es ${Nt[h]} (${f} necesita ${Nt[p]}).`)}throw i(`F\xF3rmula: ${f} necesita ${Nt[p]} y hay ${Nt[h]}.`)}},d=u=>{switch(u.k){case"num":return"numero";case"txt":return"texto";case"bool":return"booleano";case"campo":{let p=fs(e,u.v,r);return p?Jb(p):em(e,ms(e,u.v),t)}case"neg":return c(u.a,"numero","\xAB-\xBB"),"numero";case"bin":return u.op==="&"?(s(u.a),s(u.b),"texto"):["+","-","*","/"].includes(u.op)?(c(u.a,"numero",`\xAB${u.op}\xBB`),c(u.b,"numero",`\xAB${u.op}\xBB`),"numero"):(er(s(u.a),s(u.b)),"booleano");case"fn":{let p=Ub[u.f]??u.f,f=gs[p];if(!f)throw i(`F\xF3rmula: la funci\xF3n \xAB${u.f}\xBB no existe.`);if(p==="REDONDEAR"&&oi(u.args[1]),p==="PRECIO_VIGENTE"&&(u.args.length<4||u.args.length>6||u.args[0]?.k!=="txt"||u.args[2]?.k!=="txt"))throw i("PRECIO_VIGENTE: tabla y valor literales, fecha y de una a tres claves.");let h=f.args.length-(f.opcionales??0);if(u.args.length<Math.max(h,f.resto?1:0)||!f.resto&&u.args.length>f.args.length)throw i(`F\xF3rmula: ${p} no lleva ${u.args.length} argumentos.`);let b=u.args.map((v,w)=>{let g=f.args[w]??f.resto;return g==="cualquiera"?s(v):(c(v,g,p),g)});return f.tipo(b)}}};return{tipo:s(n),arbol:n,tipos:a,...r?{rutas:r}:{}}}function ti(e){let o={campos:e};return e.map(t=>{if(t.tipo!=="formula"||t.archivado)return t;let r=tm(o,t,[]),n=t.origen?.rutas&&Object.keys(t.origen.rutas).length?t.origen.rutas:void 0;return{...t,formula:Xb(o,t.formula,n),origen:{tipo:r.tipo,...n?{rutas:n}:{}}}})}function Xb(e,o,t){let r="",n=0;for(;n<o.length;){let a=o[n];if(a==='"'||a==="'"){let s=n+1;for(;s<o.length;)if(o[s]===a&&o[s+1]===a)s+=2;else{if(o[s]===a)break;s++}r+=o.slice(n,s+1),n=s+1;continue}if(a==="{"){let s=o.indexOf("}",n),c=o.slice(n+1,s).trim();r+=`{${fs(e,c,t)?c:ms(e,c).clave}}`,n=s+1;continue}r+=a,n++}return r}var Ke,Qp,Gp,Hp,Xp,hs,zb,Wb,Ye,_t,Yp,Zt,gs,Ub,eI,Nt,bs,Zp,oI,ws,Vb,Gb,om,ri=m(()=>{Lr();Xn();R();ni();Ke=1e3,Qp=300,Gp=20,Hp=5,Xp=20,hs="Europe/Madrid",zb=["<>","!=","<=",">=","=","<",">","+","-","*","/","&","(",")",",",";"];Wb=e=>e.normalize("NFD").replace(/[̀-ͯ]/g,"").toUpperCase();Ye=(e,o)=>e[o]==="fecha"||e[o]==="fecha_hora",_t=(e,o)=>o==="fecha_hora"?S`(${e} at time zone ${hs})::date`:e,Yp=e=>S`(${e})::text`,Zt=(e,o)=>S`(least(greatest(${e}, ${-o}::numeric), ${o}::numeric))::int`,gs={PRECIO_VIGENTE:{args:["texto","fecha","texto","cualquiera"],resto:"cualquiera",tipo:()=>"numero",sql:e=>S`((crm_precio_formula(${e[0]}, ${e[1]}::date, jsonb_build_array(${S.join(e.slice(3).map(o=>S`(${o})::text`),S`, `)}))->'valores'->>${e[2]})::numeric)`},SI:{args:["booleano","cualquiera","cualquiera"],opcionales:1,tipo:e=>er(e[1],e[2]??e[1]),sql:e=>e[2]?S`(case when ${e[0]} then ${e[1]} else ${e[2]} end)`:S`(case when ${e[0]} then ${e[1]} end)`},Y:{args:[],resto:"booleano",tipo:()=>"booleano",sql:e=>S`(${S.join(e,S` and `)})`},O:{args:[],resto:"booleano",tipo:()=>"booleano",sql:e=>S`(${S.join(e,S` or `)})`},NO:{args:["booleano"],tipo:()=>"booleano",sql:e=>S`(not ${e[0]})`},VACIO:{args:["cualquiera"],tipo:()=>"booleano",sql:(e,o)=>o[0]==="texto"?S`(${e[0]} is null or ${e[0]} = '')`:S`(${e[0]} is null)`},REDONDEAR:{args:["numero","numero"],opcionales:1,tipo:()=>"numero",sql:(e,o,t)=>S`round(${e[0]}, ${oi(t[1])}::int)`},ABS:{args:["numero"],tipo:()=>"numero",sql:e=>S`abs(${e[0]})`},MIN:{args:["cualquiera"],resto:"cualquiera",tipo:e=>Kp(e),sql:e=>S`least(${S.join(e)})`},MAX:{args:["cualquiera"],resto:"cualquiera",tipo:e=>Kp(e),sql:e=>S`greatest(${S.join(e)})`},CONCAT:{args:[],resto:"cualquiera",tipo:()=>"texto",sql:e=>S`concat(${S.join(e.map(Yp))})`},MAYUSCULAS:{args:["texto"],tipo:()=>"texto",sql:e=>S`upper(${e[0]})`},MINUSCULAS:{args:["texto"],tipo:()=>"texto",sql:e=>S`lower(${e[0]})`},IZQUIERDA:{args:["texto","numero"],tipo:()=>"texto",sql:e=>S`left(${e[0]}, ${Zt(e[1],1e4)})`},DERECHA:{args:["texto","numero"],tipo:()=>"texto",sql:e=>S`right(${e[0]}, ${Zt(e[1],1e4)})`},LARGO:{args:["texto"],tipo:()=>"numero",sql:e=>S`(length(${e[0]}))::numeric`},RECORTAR:{args:["texto"],tipo:()=>"texto",sql:e=>S`btrim(${e[0]})`},TEXTO:{args:["cualquiera"],tipo:()=>"texto",sql:e=>Yp(e[0])},HOY:{args:[],tipo:()=>"fecha",sql:()=>S`(now() at time zone ${hs})::date`},AHORA:{args:[],tipo:()=>"fecha_hora",sql:()=>S`now()`},DIAS_ENTRE:{args:["cualquiera","cualquiera"],tipo:e=>{if(!Ye(e,0)||!Ye(e,1))throw i("F\xF3rmula: DIAS_ENTRE necesita dos fechas.");return"numero"},sql:(e,o)=>S`((${_t(e[1],o[1])}) - (${_t(e[0],o[0])}))::numeric`},ANADIR_DIAS:{args:["cualquiera","numero"],tipo:e=>{if(!Ye(e,0))throw i("F\xF3rmula: A\xD1ADIR_DIAS necesita una fecha.");return e[0]},sql:(e,o)=>o[0]==="fecha"?S`(${e[0]} + ${Zt(e[1],1e5)})`:S`(${e[0]} + make_interval(days => ${Zt(e[1],1e5)}))`},ANO:{args:["cualquiera"],tipo:e=>ps(e),sql:(e,o)=>S`(extract(year from ${_t(e[0],o[0])}))::numeric`},MES:{args:["cualquiera"],tipo:e=>ps(e),sql:(e,o)=>S`(extract(month from ${_t(e[0],o[0])}))::numeric`},DIA:{args:["cualquiera"],tipo:e=>ps(e),sql:(e,o)=>S`(extract(day from ${_t(e[0],o[0])}))::numeric`},POTENCIA:{args:["numero","numero"],tipo:()=>"numero",sql:e=>S`(case when ${e[0]} is null or ${e[1]} is null then null
|
|
7
7
|
when abs(${e[1]}) > 64 or abs(${e[0]}) > 1000000000 then null
|
|
8
8
|
when ${e[0]} = 0 and ${e[1]} < 0 then null
|
|
9
9
|
when ${e[0]} < 0 and ${e[1]} <> trunc(${e[1]}) then null
|
|
10
|
-
else power((${e[0]})::numeric, (${e[1]})::numeric) end)`},PAGO:{args:["numero","numero","numero"],tipo:()=>"numero",sql:e=>
|
|
10
|
+
else power((${e[0]})::numeric, (${e[1]})::numeric) end)`},PAGO:{args:["numero","numero","numero"],tipo:()=>"numero",sql:e=>S`(case when ${e[0]} is null or ${e[1]} is null or ${e[2]} is null then null
|
|
11
11
|
when ${e[1]} < 1 or ${e[1]} > 1200 or ${e[0]} <= -1 or ${e[0]} > 10 then null
|
|
12
12
|
when ${e[0]} = 0 then (${e[2]})::numeric / trunc(${e[1]})
|
|
13
|
-
else (${e[2]})::numeric * (${e[0]})::numeric / (1 - power(1 + (${e[0]})::numeric, -trunc(${e[1]})::numeric)) end)`},REDONDEAR_ARRIBA:{args:["numero","numero"],opcionales:1,tipo:()=>"numero",sql:(e,o,t)=>{let
|
|
14
|
-
when abs((${
|
|
15
|
-
else (case when (${
|
|
16
|
-
select count(*) from generate_series(least((${t})::date, (${
|
|
13
|
+
else (${e[2]})::numeric * (${e[0]})::numeric / (1 - power(1 + (${e[0]})::numeric, -trunc(${e[1]})::numeric)) end)`},REDONDEAR_ARRIBA:{args:["numero","numero"],opcionales:1,tipo:()=>"numero",sql:(e,o,t)=>{let r=oi(t[1]);return r?S`(ceil((${e[0]})::numeric * ${10**r}::numeric) / ${10**r}::numeric)`:S`ceil((${e[0]})::numeric)`}},REDONDEAR_ABAJO:{args:["numero","numero"],opcionales:1,tipo:()=>"numero",sql:(e,o,t)=>{let r=oi(t[1]);return r?S`(floor((${e[0]})::numeric * ${10**r}::numeric) / ${10**r}::numeric)`:S`floor((${e[0]})::numeric)`}},DIAS_HABILES:{args:["cualquiera","cualquiera"],tipo:e=>{if(!Ye(e,0)||!Ye(e,1))throw i("F\xF3rmula: DIAS_HABILES necesita dos fechas.");return"numero"},sql:(e,o)=>{let t=_t(e[0],o[0]),r=_t(e[1],o[1]);return S`(case when ${t} is null or ${r} is null then null
|
|
14
|
+
when abs((${r})::date - (${t})::date) > 3660 then null
|
|
15
|
+
else (case when (${r})::date < (${t})::date then -1 else 1 end) * (
|
|
16
|
+
select count(*) from generate_series(least((${t})::date, (${r})::date)::timestamp, greatest((${t})::date, (${r})::date)::timestamp, interval '1 day') as g(d)
|
|
17
17
|
where extract(isodow from g.d) < 6
|
|
18
|
-
and not exists (select 1 from festivos f where f.espacio_id = crm_espacio() and f.fecha = g.d::date))::numeric end)`}}};Object.assign(cs,{RESTO:{args:["numero","numero"],tipo:()=>"numero",sql:e=>j`mod((${e[0]})::numeric, nullif((${e[1]})::numeric, 0))`},CAMBIAR:{args:["cualquiera"],resto:"cualquiera",tipo:e=>{if(e.length<3)throw i("F\xF3rmula: CAMBIAR lleva el valor y, al menos, un caso y su resultado.");let o=null;for(let t=1;t<e.length;t+=2)t+1<e.length?(Gt(e[0],e[t]),o=o?Gt(o,e[t+1]):e[t+1]):o=o?Gt(o,e[t]):e[t];return o},sql:e=>{let o=[];for(let n=1;n+1<e.length;n+=2)o.push(j`when ${e[0]} = ${e[n]} then ${e[n+1]}`);let t=(e.length-1)%2===1?j`else ${e[e.length-1]}`:j``;return j`(case ${j.join(o,j` `)} ${t} end)`}},CONTIENE:{args:["texto","texto"],tipo:()=>"booleano",sql:e=>j`(strpos(lower(${e[0]}), lower(${e[1]})) > 0)`},SUSTITUIR:{args:["texto","texto","texto"],tipo:()=>"texto",sql:e=>j`replace(${e[0]}, ${e[1]}, coalesce(${e[2]}, ''))`},ANADIR_MESES:{args:["cualquiera","numero"],tipo:e=>{if(!Xe(e,0))throw i("F\xF3rmula: A\xD1ADIR_MESES necesita una fecha.");return e[0]},sql:(e,o)=>o[0]==="fecha"?j`((${e[0]} + make_interval(months => ${Qt(e[1],12e3)}))::date)`:j`(${e[0]} + make_interval(months => ${Qt(e[1],12e3)}))`},HORAS_ENTRE:{args:["cualquiera","cualquiera"],tipo:e=>{if(!Xe(e,0)||!Xe(e,1))throw i("F\xF3rmula: HORAS_ENTRE necesita dos fechas (o fechas y horas).");return"numero"},sql:(e,o)=>{let t=(n,r)=>r==="fecha"?j`((${n})::timestamp at time zone ${ss})`:n;return j`round((extract(epoch from (${t(e[1],o[1])} - ${t(e[0],o[0])})) / 3600)::numeric, 6)`}}});Sb={IF:"SI",AND:"Y",OR:"O",NOT:"NO",ISBLANK:"VACIO",ESBLANCO:"VACIO",ROUND:"REDONDEAR",CONCATENAR:"CONCAT",UPPER:"MAYUSCULAS",LOWER:"MINUSCULAS",LEFT:"IZQUIERDA",RIGHT:"DERECHA",LEN:"LARGO",TRIM:"RECORTAR",TEXT:"TEXTO",TODAY:"HOY",NOW:"AHORA",DATETIME_DIFF:"DIAS_ENTRE",DAYS:"DIAS_ENTRE",DATEADD:"ANADIR_DIAS",YEAR:"ANO",MONTH:"MES",DAY:"DIA",POWER:"POTENCIA",PMT:"PAGO",CEIL:"REDONDEAR_ARRIBA",CEILING:"REDONDEAR_ARRIBA",FLOOR:"REDONDEAR_ABAJO",NETWORKDAYS:"DIAS_HABILES",DIAS_LAB:"DIAS_HABILES",MOD:"RESTO",SWITCH:"CAMBIAR",SUBSTITUTE:"SUSTITUIR",EDATE:"ANADIR_MESES",ADDMONTHS:"ANADIR_MESES"},wM=Object.keys(cs);gt={numero:"un n\xFAmero",texto:"un texto",fecha:"una fecha",fecha_hora:"una fecha y hora",booleano:"un s\xED/no"};ls={numero:"numero",importe:"numero",duracion:"numero",porcentaje:"numero",valoracion:"numero",contador:"numero",cronometro:"numero",texto:"texto",texto_largo:"texto",correo:"texto",telefono:"texto",url:"texto",color:"texto",codigo:"texto",seleccion:"texto",autonumero:"texto",fecha:"fecha",fecha_hora:"fecha_hora",hecho:"fecha_hora",creado_el:"fecha_hora",modificado_el:"fecha_hora",booleano:"booleano"},zp={texto:"texto",texto_largo:"texto",correo:"texto",telefono:"texto",url:"texto",seleccion:"texto",numero:"numero",importe:"numero",fecha:"fecha",fecha_hora:"fecha_hora",booleano:"booleano"},vM={numero:j`numeric`,texto:j`text`,fecha:j`date`,fecha_hora:j`timestamptz`,booleano:j`boolean`},us=e=>e.campos.filter(o=>!o.archivado);jb=e=>{let o=e.campos.find(t=>t.clave===e.campo&&!t.archivado);if(!o)throw i(`F\xF3rmula: \xAB${e.campo}\xBB ya no est\xE1 en el otro m\xF3dulo.`);return o};qb=new Set(["creado_el","creado_por","modificado_el","modificado_por","autonumero"]),Wp={companies:"companies_summary",contacts:"contacts_summary",deals:"deals"}});function Up(e,o){if(e==null)return;if(typeof e!="object"||Array.isArray(e))throw new z(400,"peticion_invalida",`\xAB${o}\xBB: permisos no v\xE1lidos.`);let t={};for(let[n,r]of Object.entries(e))if(!(r==null||r==="normal")){if(!Mb(n))throw new z(400,"peticion_invalida",`\xAB${o}\xBB: el papel \xAB${n.slice(0,30)}\xBB no se puede restringir.`);if(!Pb.includes(r))throw new z(400,"peticion_invalida",`\xAB${o}\xBB: nivel de permiso no v\xE1lido.`);t[n]=r}return Object.keys(t).length?t:void 0}var Pb,Tb,Mb,xM,ds,CM,Vp=m(()=>{Fn();q();Pb=["oculto","lectura"],Tb=["administrador","miembro","lectura"],Mb=e=>Tb.includes(e)||/^p_[a-z]{1,12}$/.test(e),xM=j`coalesce(current_setting('app.extension', true), '') <> ''`,ds=class extends Map{get(){return"no"}},CM=new ds});function Jp(e){if(!e||typeof e!="object"||Array.isArray(e))throw i("Fuente operativa no v\xE1lida.");let o=e;if(Object.keys(o).some(t=>!["objeto","tipo"].includes(t)))throw i("Fuente operativa no v\xE1lida.");if(typeof o.objeto=="string"&&Ib.test(o.objeto)&&!Object.hasOwn(o,"tipo"))return{objeto:o.objeto};if((o.objeto==="contacts"||o.objeto==="companies")&&(o.tipo===null||typeof o.tipo=="string"&&Db.test(o.tipo)))return{objeto:o.objeto,tipo:o.tipo};if(o.objeto==="deals"&&o.tipo===null)return{objeto:"deals",tipo:null};throw i("Fuente operativa no v\xE1lida.")}var Ib,Db,Qp=m(()=>{q();Ib=/^mod_[a-z][a-z0-9_]{0,40}$/,Db=/^[a-z0-9][a-z0-9-]{0,59}$/});function Xn(e,o){if(e==null)return;if(!ps(e))throw i("\xABrecurso\xBB: un objeto.");Gp(e,["capacidad","capacidad_campo","persona"],"recurso");let t={};if(e.capacidad_campo!==void 0&&e.capacidad_campo!==null&&e.capacidad_campo!==""){let n=o.find(r=>r.clave===e.capacidad_campo&&!r.archivado);if(n?.tipo!=="numero")throw i("\xABrecurso.capacidad_campo\xBB: un n\xFAmero de este m\xF3dulo.");t.capacidad_campo=n.clave}if(e.capacidad!==void 0&&e.capacidad!==null){let n=Number(e.capacidad);if(!Number.isInteger(n)||n<1||n>1e4)throw i("\xABrecurso.capacidad\xBB: de 1 a 10 000.");t.capacidad=n}if(e.persona!==void 0&&e.persona!==null){if(e.persona!=="responsable")throw i("\xABrecurso.persona\xBB: \xABresponsable\xBB.");t.persona="responsable"}return t}function Yn(e,o){if(e==null)return;if(!ps(e))throw i("\xABreserva\xBB: un objeto.");Gp(e,["fuente_recurso","recurso","modo","inicio","fin","duracion","duracion_fija","plazas","no_ocupan","fuera_de_horario","margen","cupo","dia","hora_inicio","hora_fin","vigencia_desde","vigencia_hasta"],"reserva");let t=p=>o.find(f=>f.clave===p&&!f.archivado),n=(p,f,h)=>{let b=t(p);if(!b||!f.includes(b.tipo))throw i(`\xABreserva.${h}\xBB: ${f.join(" o ")} de este m\xF3dulo.`);return b},r=n(e.recurso,["relacion"],"recurso"),a=e.fuente_recurso===void 0?void 0:Jp(e.fuente_recurso);if(a&&(a.objeto!==r.relacion||!("tipo"in a)||r.tipoContacto&&a.tipo!==r.tipoContacto))throw i("La fuente del recurso no coincide con la relaci\xF3n.");if(!a&&!r.relacion?.startsWith("mod_"))throw i("Una relaci\xF3n nativa requiere su fuente de recurso expl\xEDcita.");let s=e.modo??"puntual";if(s!=="puntual"&&s!=="semanal")throw i("\xABreserva.modo\xBB: \xABpuntual\xBB o \xABsemanal\xBB.");let l={...a?{fuente_recurso:a}:{},recurso:r.clave,modo:s,fuera_de_horario:e.fuera_de_horario==="permitir"?"permitir":"impedir"};if(s==="puntual")l.inicio=n(e.inicio,["fecha_hora","fecha"],"inicio").clave;else{let p=n(e.dia,["seleccion"],"dia");if(!(p.opciones??[]).length||(p.opciones??[]).some(f=>Lb(f.valor)===null))throw i("\xABreserva.dia\xBB: una selecci\xF3n con los d\xEDas de la semana (1\u20137, \xABlunes\xBB\u2026 o L M X J V S D).");l.dia=p.clave,l.hora_inicio=n(e.hora_inicio,["hora"],"hora_inicio").clave,e.vigencia_desde&&(l.vigencia_desde=n(e.vigencia_desde,["fecha"],"vigencia_desde").clave),e.vigencia_hasta&&(l.vigencia_hasta=n(e.vigencia_hasta,["fecha"],"vigencia_hasta").clave)}if(e.fuera_de_horario!==void 0&&e.fuera_de_horario!=="impedir"&&e.fuera_de_horario!=="permitir")throw i("\xABreserva.fuera_de_horario\xBB: \xABimpedir\xBB o \xABpermitir\xBB.");if([s==="semanal"?e.hora_fin:e.fin,e.duracion,e.duracion_fija].filter(p=>p!=null&&p!=="").length!==1)throw i(`\xABreserva\xBB: ${s==="semanal"?"una hora de fin":"un fin"}, una duraci\xF3n o una duraci\xF3n fija (solo una).`);if(s==="semanal"&&e.fin)throw i("\xABreserva.fin\xBB: en una semanal, \xABhora_fin\xBB.");if(s==="puntual"&&e.hora_fin)throw i("\xABreserva.hora_fin\xBB: en una puntual, \xABfin\xBB.");if(e.hora_fin)l.hora_fin=n(e.hora_fin,["hora"],"hora_fin").clave;else if(e.fin)l.fin=n(e.fin,["fecha_hora","fecha"],"fin").clave;else if(e.duracion)l.duracion=n(e.duracion,["duracion","numero"],"duracion").clave;else{let p=Number(e.duracion_fija);if(!Number.isInteger(p)||p<1||p>1440)throw i("\xABreserva.duracion_fija\xBB: de 1 a 1440 minutos.");l.duracion_fija=p}let u=p=>t(p)?.tipo==="fecha";if(s==="puntual"&&u(l.inicio)!==(l.fin?u(l.fin):!1))throw i("\xABreserva\xBB: por d\xEDas, la entrada y la salida son dos fechas (sin hora); con hora, las dos con hora (o una duraci\xF3n).");if(e.plazas&&(l.plazas=n(e.plazas,["numero"],"plazas").clave),e.cupo&&(l.cupo=n(e.cupo,["numero"],"cupo").clave),e.margen!==void 0&&e.margen!==null){let p=Number(e.margen);if(!Number.isInteger(p)||p<0||p>240)throw i("\xABreserva.margen\xBB: de 0 a 240 minutos.");p&&(l.margen=p)}if(e.no_ocupan!==void 0&&e.no_ocupan!==null){let p=e.no_ocupan,f=ps(p)?n(p.campo,["seleccion"],"no_ocupan.campo"):void 0,h=Array.isArray(p.valores)?p.valores:[];if(!f||!h.length||h.some(b=>!f.opciones?.some(y=>y.valor===b)))throw i("\xABreserva.no_ocupan\xBB: una selecci\xF3n y algunas de sus opciones.");l.no_ocupan={campo:f.clave,valores:[...new Set(h)]}}return l}function Lb(e){let o=String(e??"").trim().toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"");return{1:1,lunes:1,l:1,lun:1,monday:1,2:2,martes:2,m:2,mar:2,tuesday:2,3:3,miercoles:3,x:3,mie:3,wednesday:3,4:4,jueves:4,j:4,jue:4,thursday:4,5:5,viernes:5,v:5,vie:5,friday:5,6:6,sabado:6,s:6,sab:6,saturday:6,7:7,domingo:7,d:7,dom:7,sunday:7}[o]??null}var ps,Gp,ms=m(()=>{q();Qp();ps=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Gp=(e,o,t)=>{for(let n of Object.keys(e))if(!o.includes(n))throw i(`\xAB${t}\xBB: clave no admitida \xAB${n.slice(0,40)}\xBB.`)}});function Xp(e,o){if(e==null)return;if(!Array.isArray(e)||e.length>Hp)throw i(`\xABvalidaciones\xBB: hasta ${Hp}.`);let t=[];for(let[n,r]of e.entries()){if(!Fb(r))throw i(`Validaci\xF3n ${n+1}: un objeto.`);for(let s of Object.keys(r))if(s!=="formula"&&s!=="mensaje")throw i(`Validaci\xF3n ${n+1}: clave no admitida \xAB${s.slice(0,40)}\xBB.`);if(typeof r.formula!="string"||!r.formula.trim()||r.formula.length>Ye)throw i(`Validaci\xF3n ${n+1}: la f\xF3rmula, de 1 a ${Ye} caracteres.`);if(typeof r.mensaje!="string"||!r.mensaje.trim()||r.mensaje.length>200)throw i(`Validaci\xF3n ${n+1}: el mensaje, de 1 a 200 caracteres.`);let a;try{a=Qn([...o,Wb(n,r.formula)]).at(-1)}catch(s){throw i(`Validaci\xF3n ${n+1}: ${s instanceof Error?s.message:"la f\xF3rmula no vale"}`)}if(a.origen?.tipo!=="booleano")throw i(`Validaci\xF3n ${n+1}: la f\xF3rmula tiene que dar s\xED o no (una comparaci\xF3n, Y(), O()\u2026).`);t.push({formula:a.formula,mensaje:r.mensaje.trim()})}return t.length?t:void 0}var Hp,Fb,Wb,Yp=m(()=>{q();Gn();Hp=20,Fb=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Wb=(e,o)=>({clave:`validacion_${e}`,etiqueta:`Validaci\xF3n ${e+1}`,tipo:"formula",formula:o})});function em(e,o){if(e==null)return;let t=`\xAB${o.etiqueta}\xBB`;if(o.tipo!=="seleccion"&&o.tipo!=="relacion")throw i(`${t}: solo una selecci\xF3n o una relaci\xF3n pueden depender de otro campo.`);if(!Zp(e))throw i(`${t}: \xABdepende\xBB, un objeto.`);for(let n of Object.keys(e))if(!["campo","opciones","via"].includes(n))throw i(`${t}: clave no admitida \xAB${n.slice(0,40)}\xBB.`);if(typeof e.campo!="string"||!Kp.test(e.campo))throw i(`${t}: \xBFde qu\xE9 campo depende?`);if(o.tipo==="seleccion"){if(!Zp(e.opciones)||Object.keys(e.opciones).length>200)throw i(`${t}: qu\xE9 opciones valen para cada valor del otro campo (hasta 200).`);let n={};for(let[r,a]of Object.entries(e.opciones)){if(r.length>100||!Array.isArray(a)||a.length>200||!a.every(s=>typeof s=="string"&&s.length<=100))throw i(`${t}: las opciones de \xAB${r.slice(0,40)}\xBB, una lista de valores.`);n[r]=[...new Set(a)]}return{campo:e.campo,opciones:n}}if(typeof e.via!="string"||!Kp.test(e.via))throw i(`${t}: por qu\xE9 campo del otro m\xF3dulo se filtra (\xABvia\xBB).`);return{campo:e.campo,via:e.via}}function om(e){let o=e.filter(t=>!t.archivado);for(let t of o.filter(n=>n.depende)){let n=t.depende,r=o.find(a=>a.clave===n.campo);if(!r||r.clave===t.clave)throw i(`\xAB${t.etiqueta}\xBB: depende de un campo que no existe.`);if(t.tipo==="seleccion"){if(r.tipo!=="seleccion")throw i(`\xAB${t.etiqueta}\xBB: una selecci\xF3n depende de otra selecci\xF3n.`);let a=new Set((r.opciones??[]).map(l=>l.valor)),s=new Set((t.opciones??[]).map(l=>l.valor));for(let[l,d]of Object.entries(n.opciones??{})){if(!a.has(l))throw i(`\xAB${t.etiqueta}\xBB: \xAB${l.slice(0,40)}\xBB no es una opci\xF3n de \xAB${r.etiqueta}\xBB.`);let u=d.find(p=>!s.has(p));if(u!==void 0)throw i(`\xAB${t.etiqueta}\xBB: \xAB${u.slice(0,40)}\xBB no es una de sus opciones.`)}}else if(r.tipo!=="relacion"||r.multiple||t.multiple)throw i(`\xAB${t.etiqueta}\xBB: una relaci\xF3n (de uno) depende de otra relaci\xF3n de uno de este m\xF3dulo.`)}for(let t of o.filter(n=>n.depende)){let n=new Set([t.clave]);for(let r=o.find(a=>a.clave===t.depende.campo);r?.depende;r=o.find(a=>a.clave===r.depende.campo)){if(n.has(r.clave))throw i(`\xAB${t.etiqueta}\xBB: las dependencias forman un c\xEDrculo.`);n.add(r.clave)}}}var Kp,Zp,tm=m(()=>{q();Kp=/^[a-z][a-z0-9_]{0,39}$/,Zp=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)});import{createContext as Bb,Script as Ub}from"node:vm";function Kn(e,o){if(e!=null){if(!Array.isArray(e)||e.length>rm)throw i(`\xAB${o}\xBB: como mucho ${rm} condiciones.`);if(e.length)return e.map(t=>{let n=t;if(typeof n!="object"||n===null||typeof n.campo!="string"||!/^[a-z][a-z0-9_]{0,40}$/.test(n.campo))throw i(`\xAB${o}\xBB: una condici\xF3n no es v\xE1lida.`);let r=n.op;if(!Vb.includes(r))throw i(`\xAB${o}\xBB: condici\xF3n no v\xE1lida (${String(n.op).slice(0,20)}).`);let a={campo:n.campo,op:r};if(r==="igual"||r==="distinto"){if(!Jb(n.valor))throw i(`\xAB${o}\xBB: la condici\xF3n necesita un valor.`);a.valor=n.valor}if(r==="uno_de"){if(!Array.isArray(n.valor)||!n.valor.length||n.valor.length>50||!n.valor.every(s=>typeof s=="string"||typeof s=="number"))throw i(`\xAB${o}\xBB: \xABuno de\xBB necesita una lista de valores.`);a.valor=n.valor}return a})}}function cm(e,o){if(!(e==null||e==="")){if(typeof e!="string"||e.length>nm)throw i(`\xAB${o}\xBB: el patr\xF3n, hasta ${nm} caracteres.`);if(/\\[1-9]|\\k<|\(\?<[=!]/.test(e))throw i(`\xAB${o}\xBB: el patr\xF3n no admite retroreferencias ni lookbehind.`);if(Qb(e))throw i(`\xAB${o}\xBB: el patr\xF3n tiene un grupo repetido que se puede disparar (p. ej. \xAB(a+)+\xBB); simplif\xEDcalo.`);try{new RegExp(e,"u")}catch{throw i(`\xAB${o}\xBB: el patr\xF3n no es una expresi\xF3n regular v\xE1lida.`)}return e}}function Qb(e){let o=[],t=!1;for(let n=0;n<e.length;n++){let r=e[n];if(r==="\\"){n++;continue}if(t){r==="]"&&(t=!1);continue}if(r==="["){t=!0;continue}if(r==="("){o.push(!1);continue}if(r===")"){let a=o.pop()??!1,s=e.slice(n+1),l=/^(?:[+*]|\{\d*,)/.test(s)||/^\{(\d+)\}/.test(s)&&Number(/^\{(\d+)\}/.exec(s)[1])>1;if(a&&l)return!0;o.length&&(a||l)&&(o[o.length-1]=!0);continue}(r==="+"||r==="*"||r==="?"||r==="{"||r==="|")&&o.length&&(o[o.length-1]=!0)}return!1}function lm(e,o){if(e==null)return;let t=e,n=t?.tipo;if(typeof t!="object"||!im[n])throw i(`\xAB${o.etiqueta}\xBB: valor por defecto no v\xE1lido.`);if(!im[n].includes(o.tipo))throw i(`\xAB${o.etiqueta}\xBB: ese valor por defecto no vale para este tipo.`);if(n==="fijo")return{tipo:n,valor:t.valor};if(n==="formula"){if(typeof t.formula!="string"||!t.formula.trim()||t.formula.length>1e3)throw i(`\xAB${o.etiqueta}\xBB: escribe la f\xF3rmula por defecto.`);return{tipo:n,formula:t.formula.trim()}}return{tipo:n}}var Vb,rm,nm,am,sm,im,Jb,LM,zM,um=m(()=>{q();Vb=["igual","distinto","vacio","lleno","uno_de"],rm=10,nm=200,am=["texto","correo","telefono","url","codigo"],sm=["texto","correo","telefono","url","codigo","numero","importe"],im={fijo:["texto","texto_largo","numero","importe","fecha","fecha_hora","booleano","seleccion","seleccion_multiple","url","correo","telefono","duracion","porcentaje","valoracion","contador","cronometro","color","codigo","hora"],hoy:["fecha","fecha_hora"],ahora:["fecha_hora"],yo:["texto","correo"],formula:["texto","texto_largo","numero","importe","fecha","fecha_hora","booleano","porcentaje","duracion"]},Jb=e=>typeof e=="string"&&e.length<=200||typeof e=="number"&&Number.isFinite(e)||typeof e=="boolean";LM=Bb({p:"",v:""}),zM=new Ub("new RegExp(p, 'u').test(v)")});function dm(e,o,t){if(e.aprobacion===void 0||e.aprobacion===null)return;let n=e.aprobacion;if(typeof n!="object"||Array.isArray(n))throw i(`\xAB${t}\xBB, \xAB${o.etiqueta}\xBB: la aprobaci\xF3n, un objeto.`);let r=n.papel===void 0||n.papel===null||n.papel===""?void 0:n.papel;if(r!==void 0&&(typeof r!="string"||!/^[a-z_]{1,40}$/.test(r)))throw i(`\xAB${t}\xBB, \xAB${o.etiqueta}\xBB: el papel que aprueba no es v\xE1lido.`);let a=n.personas===void 0||n.personas===null?1:n.personas;if(!Number.isInteger(a)||a<1||a>10)throw i(`\xAB${t}\xBB, \xAB${o.etiqueta}\xBB: de 1 a 10 personas.`);o.aprobacion={...r?{papel:r}:{},personas:a}}var UM,pm=m(()=>{Fn();q();UM=j`select a.*, m.clave,
|
|
18
|
+
and not exists (select 1 from festivos f where f.espacio_id = crm_espacio() and f.fecha = g.d::date))::numeric end)`}}};Object.assign(gs,{RESTO:{args:["numero","numero"],tipo:()=>"numero",sql:e=>S`mod((${e[0]})::numeric, nullif((${e[1]})::numeric, 0))`},CAMBIAR:{args:["cualquiera"],resto:"cualquiera",tipo:e=>{if(e.length<3)throw i("F\xF3rmula: CAMBIAR lleva el valor y, al menos, un caso y su resultado.");let o=null;for(let t=1;t<e.length;t+=2)t+1<e.length?(er(e[0],e[t]),o=o?er(o,e[t+1]):e[t+1]):o=o?er(o,e[t]):e[t];return o},sql:e=>{let o=[];for(let r=1;r+1<e.length;r+=2)o.push(S`when ${e[0]} = ${e[r]} then ${e[r+1]}`);let t=(e.length-1)%2===1?S`else ${e[e.length-1]}`:S``;return S`(case ${S.join(o,S` `)} ${t} end)`}},CONTIENE:{args:["texto","texto"],tipo:()=>"booleano",sql:e=>S`(strpos(lower(${e[0]}), lower(${e[1]})) > 0)`},SUSTITUIR:{args:["texto","texto","texto"],tipo:()=>"texto",sql:e=>S`replace(${e[0]}, ${e[1]}, coalesce(${e[2]}, ''))`},ANADIR_MESES:{args:["cualquiera","numero"],tipo:e=>{if(!Ye(e,0))throw i("F\xF3rmula: A\xD1ADIR_MESES necesita una fecha.");return e[0]},sql:(e,o)=>o[0]==="fecha"?S`((${e[0]} + make_interval(months => ${Zt(e[1],12e3)}))::date)`:S`(${e[0]} + make_interval(months => ${Zt(e[1],12e3)}))`},HORAS_ENTRE:{args:["cualquiera","cualquiera"],tipo:e=>{if(!Ye(e,0)||!Ye(e,1))throw i("F\xF3rmula: HORAS_ENTRE necesita dos fechas (o fechas y horas).");return"numero"},sql:(e,o)=>{let t=(r,n)=>n==="fecha"?S`((${r})::timestamp at time zone ${hs})`:r;return S`round((extract(epoch from (${t(e[1],o[1])} - ${t(e[0],o[0])})) / 3600)::numeric, 6)`}}});Ub={IF:"SI",AND:"Y",OR:"O",NOT:"NO",ISBLANK:"VACIO",ESBLANCO:"VACIO",ROUND:"REDONDEAR",CONCATENAR:"CONCAT",UPPER:"MAYUSCULAS",LOWER:"MINUSCULAS",LEFT:"IZQUIERDA",RIGHT:"DERECHA",LEN:"LARGO",TRIM:"RECORTAR",TEXT:"TEXTO",TODAY:"HOY",NOW:"AHORA",DATETIME_DIFF:"DIAS_ENTRE",DAYS:"DIAS_ENTRE",DATEADD:"ANADIR_DIAS",YEAR:"ANO",MONTH:"MES",DAY:"DIA",POWER:"POTENCIA",PMT:"PAGO",CEIL:"REDONDEAR_ARRIBA",CEILING:"REDONDEAR_ARRIBA",FLOOR:"REDONDEAR_ABAJO",NETWORKDAYS:"DIAS_HABILES",DIAS_LAB:"DIAS_HABILES",MOD:"RESTO",SWITCH:"CAMBIAR",SUBSTITUTE:"SUSTITUIR",EDATE:"ANADIR_MESES",ADDMONTHS:"ANADIR_MESES"},eI=Object.keys(gs);Nt={numero:"un n\xFAmero",texto:"un texto",fecha:"una fecha",fecha_hora:"una fecha y hora",booleano:"un s\xED/no"};bs={numero:"numero",importe:"numero",duracion:"numero",porcentaje:"numero",valoracion:"numero",contador:"numero",cronometro:"numero",texto:"texto",texto_largo:"texto",correo:"texto",telefono:"texto",url:"texto",color:"texto",codigo:"texto",seleccion:"texto",autonumero:"texto",fecha:"fecha",fecha_hora:"fecha_hora",hecho:"fecha_hora",creado_el:"fecha_hora",modificado_el:"fecha_hora",booleano:"booleano"},Zp={texto:"texto",texto_largo:"texto",correo:"texto",telefono:"texto",url:"texto",seleccion:"texto",numero:"numero",importe:"numero",fecha:"fecha",fecha_hora:"fecha_hora",booleano:"booleano"},oI={numero:S`numeric`,texto:S`text`,fecha:S`date`,fecha_hora:S`timestamptz`,booleano:S`boolean`},ws=e=>e.campos.filter(o=>!o.archivado);Vb=e=>{let o=e.campos.find(t=>t.clave===e.campo&&!t.archivado);if(!o)throw i(`F\xF3rmula: \xAB${e.campo}\xBB ya no est\xE1 en el otro m\xF3dulo.`);return o};Gb=new Set(["creado_el","creado_por","modificado_el","modificado_por","autonumero"]),om={companies:"companies_summary",contacts:"contacts_summary",deals:"deals"}});function rm(e,o){if(e==null)return;if(typeof e!="object"||Array.isArray(e))throw new F(400,"peticion_invalida",`\xAB${o}\xBB: permisos no v\xE1lidos.`);let t={};for(let[r,n]of Object.entries(e))if(!(n==null||n==="normal")){if(!Zb(r))throw new F(400,"peticion_invalida",`\xAB${o}\xBB: el papel \xAB${r.slice(0,30)}\xBB no se puede restringir.`);if(!Yb.includes(n))throw new F(400,"peticion_invalida",`\xAB${o}\xBB: nivel de permiso no v\xE1lido.`);t[r]=n}return Object.keys(t).length?t:void 0}var Yb,Kb,Zb,aI,vs,sI,nm=m(()=>{Xn();R();Yb=["oculto","lectura"],Kb=["administrador","miembro","lectura"],Zb=e=>Kb.includes(e)||/^p_[a-z]{1,12}$/.test(e),aI=S`coalesce(current_setting('app.extension', true), '') <> ''`,vs=class extends Map{get(){return"no"}},sI=new vs});function im(e){if(!e||typeof e!="object"||Array.isArray(e))throw i("Fuente operativa no v\xE1lida.");let o=e;if(Object.keys(o).some(t=>!["objeto","tipo"].includes(t)))throw i("Fuente operativa no v\xE1lida.");if(typeof o.objeto=="string"&&ew.test(o.objeto)&&!Object.hasOwn(o,"tipo"))return{objeto:o.objeto};if((o.objeto==="contacts"||o.objeto==="companies")&&(o.tipo===null||typeof o.tipo=="string"&&ow.test(o.tipo)))return{objeto:o.objeto,tipo:o.tipo};if(o.objeto==="deals"&&o.tipo===null)return{objeto:"deals",tipo:null};throw i("Fuente operativa no v\xE1lida.")}var ew,ow,am=m(()=>{R();ew=/^mod_[a-z][a-z0-9_]{0,40}$/,ow=/^[a-z0-9][a-z0-9-]{0,59}$/});function ii(e,o){if(e==null)return;if(!ys(e))throw i("\xABrecurso\xBB: un objeto.");sm(e,["capacidad","capacidad_campo","persona"],"recurso");let t={};if(e.capacidad_campo!==void 0&&e.capacidad_campo!==null&&e.capacidad_campo!==""){let r=o.find(n=>n.clave===e.capacidad_campo&&!n.archivado);if(r?.tipo!=="numero")throw i("\xABrecurso.capacidad_campo\xBB: un n\xFAmero de este m\xF3dulo.");t.capacidad_campo=r.clave}if(e.capacidad!==void 0&&e.capacidad!==null){let r=Number(e.capacidad);if(!Number.isInteger(r)||r<1||r>1e4)throw i("\xABrecurso.capacidad\xBB: de 1 a 10 000.");t.capacidad=r}if(e.persona!==void 0&&e.persona!==null){if(e.persona!=="responsable")throw i("\xABrecurso.persona\xBB: \xABresponsable\xBB.");t.persona="responsable"}return t}function ai(e,o){if(e==null)return;if(!ys(e))throw i("\xABreserva\xBB: un objeto.");sm(e,["fuente_recurso","recurso","modo","inicio","fin","duracion","duracion_fija","plazas","no_ocupan","fuera_de_horario","margen","cupo","dia","hora_inicio","hora_fin","vigencia_desde","vigencia_hasta"],"reserva");let t=p=>o.find(f=>f.clave===p&&!f.archivado),r=(p,f,h)=>{let b=t(p);if(!b||!f.includes(b.tipo))throw i(`\xABreserva.${h}\xBB: ${f.join(" o ")} de este m\xF3dulo.`);return b},n=r(e.recurso,["relacion"],"recurso"),a=e.fuente_recurso===void 0?void 0:im(e.fuente_recurso);if(a&&(a.objeto!==n.relacion||!("tipo"in a)||n.tipoContacto&&a.tipo!==n.tipoContacto))throw i("La fuente del recurso no coincide con la relaci\xF3n.");if(!a&&!n.relacion?.startsWith("mod_"))throw i("Una relaci\xF3n nativa requiere su fuente de recurso expl\xEDcita.");let s=e.modo??"puntual";if(s!=="puntual"&&s!=="semanal")throw i("\xABreserva.modo\xBB: \xABpuntual\xBB o \xABsemanal\xBB.");let c={...a?{fuente_recurso:a}:{},recurso:n.clave,modo:s,fuera_de_horario:e.fuera_de_horario==="permitir"?"permitir":"impedir"};if(s==="puntual")c.inicio=r(e.inicio,["fecha_hora","fecha"],"inicio").clave;else{let p=r(e.dia,["seleccion"],"dia");if(!(p.opciones??[]).length||(p.opciones??[]).some(f=>tw(f.valor)===null))throw i("\xABreserva.dia\xBB: una selecci\xF3n con los d\xEDas de la semana (1\u20137, \xABlunes\xBB\u2026 o L M X J V S D).");c.dia=p.clave,c.hora_inicio=r(e.hora_inicio,["hora"],"hora_inicio").clave,e.vigencia_desde&&(c.vigencia_desde=r(e.vigencia_desde,["fecha"],"vigencia_desde").clave),e.vigencia_hasta&&(c.vigencia_hasta=r(e.vigencia_hasta,["fecha"],"vigencia_hasta").clave)}if(e.fuera_de_horario!==void 0&&e.fuera_de_horario!=="impedir"&&e.fuera_de_horario!=="permitir")throw i("\xABreserva.fuera_de_horario\xBB: \xABimpedir\xBB o \xABpermitir\xBB.");if([s==="semanal"?e.hora_fin:e.fin,e.duracion,e.duracion_fija].filter(p=>p!=null&&p!=="").length!==1)throw i(`\xABreserva\xBB: ${s==="semanal"?"una hora de fin":"un fin"}, una duraci\xF3n o una duraci\xF3n fija (solo una).`);if(s==="semanal"&&e.fin)throw i("\xABreserva.fin\xBB: en una semanal, \xABhora_fin\xBB.");if(s==="puntual"&&e.hora_fin)throw i("\xABreserva.hora_fin\xBB: en una puntual, \xABfin\xBB.");if(e.hora_fin)c.hora_fin=r(e.hora_fin,["hora"],"hora_fin").clave;else if(e.fin)c.fin=r(e.fin,["fecha_hora","fecha"],"fin").clave;else if(e.duracion)c.duracion=r(e.duracion,["duracion","numero"],"duracion").clave;else{let p=Number(e.duracion_fija);if(!Number.isInteger(p)||p<1||p>1440)throw i("\xABreserva.duracion_fija\xBB: de 1 a 1440 minutos.");c.duracion_fija=p}let u=p=>t(p)?.tipo==="fecha";if(s==="puntual"&&u(c.inicio)!==(c.fin?u(c.fin):!1))throw i("\xABreserva\xBB: por d\xEDas, la entrada y la salida son dos fechas (sin hora); con hora, las dos con hora (o una duraci\xF3n).");if(e.plazas&&(c.plazas=r(e.plazas,["numero"],"plazas").clave),e.cupo&&(c.cupo=r(e.cupo,["numero"],"cupo").clave),e.margen!==void 0&&e.margen!==null){let p=Number(e.margen);if(!Number.isInteger(p)||p<0||p>240)throw i("\xABreserva.margen\xBB: de 0 a 240 minutos.");p&&(c.margen=p)}if(e.no_ocupan!==void 0&&e.no_ocupan!==null){let p=e.no_ocupan,f=ys(p)?r(p.campo,["seleccion"],"no_ocupan.campo"):void 0,h=Array.isArray(p.valores)?p.valores:[];if(!f||!h.length||h.some(b=>!f.opciones?.some(v=>v.valor===b)))throw i("\xABreserva.no_ocupan\xBB: una selecci\xF3n y algunas de sus opciones.");c.no_ocupan={campo:f.clave,valores:[...new Set(h)]}}return c}function tw(e){let o=String(e??"").trim().toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"");return{1:1,lunes:1,l:1,lun:1,monday:1,2:2,martes:2,m:2,mar:2,tuesday:2,3:3,miercoles:3,x:3,mie:3,wednesday:3,4:4,jueves:4,j:4,jue:4,thursday:4,5:5,viernes:5,v:5,vie:5,friday:5,6:6,sabado:6,s:6,sab:6,saturday:6,7:7,domingo:7,d:7,dom:7,sunday:7}[o]??null}var ys,sm,_s=m(()=>{R();am();ys=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),sm=(e,o,t)=>{for(let r of Object.keys(e))if(!o.includes(r))throw i(`\xAB${t}\xBB: clave no admitida \xAB${r.slice(0,40)}\xBB.`)}});function lm(e,o){if(e==null)return;if(!Array.isArray(e)||e.length>cm)throw i(`\xABvalidaciones\xBB: hasta ${cm}.`);let t=[];for(let[r,n]of e.entries()){if(!nw(n))throw i(`Validaci\xF3n ${r+1}: un objeto.`);for(let s of Object.keys(n))if(s!=="formula"&&s!=="mensaje")throw i(`Validaci\xF3n ${r+1}: clave no admitida \xAB${s.slice(0,40)}\xBB.`);if(typeof n.formula!="string"||!n.formula.trim()||n.formula.length>Ke)throw i(`Validaci\xF3n ${r+1}: la f\xF3rmula, de 1 a ${Ke} caracteres.`);if(typeof n.mensaje!="string"||!n.mensaje.trim()||n.mensaje.length>200)throw i(`Validaci\xF3n ${r+1}: el mensaje, de 1 a 200 caracteres.`);let a;try{a=ti([...o,iw(r,n.formula)]).at(-1)}catch(s){throw i(`Validaci\xF3n ${r+1}: ${s instanceof Error?s.message:"la f\xF3rmula no vale"}`)}if(a.origen?.tipo!=="booleano")throw i(`Validaci\xF3n ${r+1}: la f\xF3rmula tiene que dar s\xED o no (una comparaci\xF3n, Y(), O()\u2026).`);t.push({formula:a.formula,mensaje:n.mensaje.trim()})}return t.length?t:void 0}var cm,nw,iw,um=m(()=>{R();ri();cm=20,nw=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),iw=(e,o)=>({clave:`validacion_${e}`,etiqueta:`Validaci\xF3n ${e+1}`,tipo:"formula",formula:o})});function mm(e,o){if(e==null)return;let t=`\xAB${o.etiqueta}\xBB`;if(o.tipo!=="seleccion"&&o.tipo!=="relacion")throw i(`${t}: solo una selecci\xF3n o una relaci\xF3n pueden depender de otro campo.`);if(!pm(e))throw i(`${t}: \xABdepende\xBB, un objeto.`);for(let r of Object.keys(e))if(!["campo","opciones","via"].includes(r))throw i(`${t}: clave no admitida \xAB${r.slice(0,40)}\xBB.`);if(typeof e.campo!="string"||!dm.test(e.campo))throw i(`${t}: \xBFde qu\xE9 campo depende?`);if(o.tipo==="seleccion"){if(!pm(e.opciones)||Object.keys(e.opciones).length>200)throw i(`${t}: qu\xE9 opciones valen para cada valor del otro campo (hasta 200).`);let r={};for(let[n,a]of Object.entries(e.opciones)){if(n.length>100||!Array.isArray(a)||a.length>200||!a.every(s=>typeof s=="string"&&s.length<=100))throw i(`${t}: las opciones de \xAB${n.slice(0,40)}\xBB, una lista de valores.`);r[n]=[...new Set(a)]}return{campo:e.campo,opciones:r}}if(typeof e.via!="string"||!dm.test(e.via))throw i(`${t}: por qu\xE9 campo del otro m\xF3dulo se filtra (\xABvia\xBB).`);return{campo:e.campo,via:e.via}}function fm(e){let o=e.filter(t=>!t.archivado);for(let t of o.filter(r=>r.depende)){let r=t.depende,n=o.find(a=>a.clave===r.campo);if(!n||n.clave===t.clave)throw i(`\xAB${t.etiqueta}\xBB: depende de un campo que no existe.`);if(t.tipo==="seleccion"){if(n.tipo!=="seleccion")throw i(`\xAB${t.etiqueta}\xBB: una selecci\xF3n depende de otra selecci\xF3n.`);let a=new Set((n.opciones??[]).map(c=>c.valor)),s=new Set((t.opciones??[]).map(c=>c.valor));for(let[c,d]of Object.entries(r.opciones??{})){if(!a.has(c))throw i(`\xAB${t.etiqueta}\xBB: \xAB${c.slice(0,40)}\xBB no es una opci\xF3n de \xAB${n.etiqueta}\xBB.`);let u=d.find(p=>!s.has(p));if(u!==void 0)throw i(`\xAB${t.etiqueta}\xBB: \xAB${u.slice(0,40)}\xBB no es una de sus opciones.`)}}else if(n.tipo!=="relacion"||n.multiple||t.multiple)throw i(`\xAB${t.etiqueta}\xBB: una relaci\xF3n (de uno) depende de otra relaci\xF3n de uno de este m\xF3dulo.`)}for(let t of o.filter(r=>r.depende)){let r=new Set([t.clave]);for(let n=o.find(a=>a.clave===t.depende.campo);n?.depende;n=o.find(a=>a.clave===n.depende.campo)){if(r.has(n.clave))throw i(`\xAB${t.etiqueta}\xBB: las dependencias forman un c\xEDrculo.`);r.add(n.clave)}}}var dm,pm,hm=m(()=>{R();dm=/^[a-z][a-z0-9_]{0,39}$/,pm=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)});import{createContext as aw,Script as sw}from"node:vm";function si(e,o){if(e!=null){if(!Array.isArray(e)||e.length>gm)throw i(`\xAB${o}\xBB: como mucho ${gm} condiciones.`);if(e.length)return e.map(t=>{let r=t;if(typeof r!="object"||r===null||typeof r.campo!="string"||!/^[a-z][a-z0-9_]{0,40}$/.test(r.campo))throw i(`\xAB${o}\xBB: una condici\xF3n no es v\xE1lida.`);let n=r.op;if(!cw.includes(n))throw i(`\xAB${o}\xBB: condici\xF3n no v\xE1lida (${String(r.op).slice(0,20)}).`);let a={campo:r.campo,op:n};if(n==="igual"||n==="distinto"){if(!lw(r.valor))throw i(`\xAB${o}\xBB: la condici\xF3n necesita un valor.`);a.valor=r.valor}if(n==="uno_de"){if(!Array.isArray(r.valor)||!r.valor.length||r.valor.length>50||!r.valor.every(s=>typeof s=="string"||typeof s=="number"))throw i(`\xAB${o}\xBB: \xABuno de\xBB necesita una lista de valores.`);a.valor=r.valor}return a})}}function _m(e,o){if(!(e==null||e==="")){if(typeof e!="string"||e.length>bm)throw i(`\xAB${o}\xBB: el patr\xF3n, hasta ${bm} caracteres.`);if(/\\[1-9]|\\k<|\(\?<[=!]/.test(e))throw i(`\xAB${o}\xBB: el patr\xF3n no admite retroreferencias ni lookbehind.`);if(uw(e))throw i(`\xAB${o}\xBB: el patr\xF3n tiene un grupo repetido que se puede disparar (p. ej. \xAB(a+)+\xBB); simplif\xEDcalo.`);try{new RegExp(e,"u")}catch{throw i(`\xAB${o}\xBB: el patr\xF3n no es una expresi\xF3n regular v\xE1lida.`)}return e}}function uw(e){let o=[],t=!1;for(let r=0;r<e.length;r++){let n=e[r];if(n==="\\"){r++;continue}if(t){n==="]"&&(t=!1);continue}if(n==="["){t=!0;continue}if(n==="("){o.push(!1);continue}if(n===")"){let a=o.pop()??!1,s=e.slice(r+1),c=/^(?:[+*]|\{\d*,)/.test(s)||/^\{(\d+)\}/.test(s)&&Number(/^\{(\d+)\}/.exec(s)[1])>1;if(a&&c)return!0;o.length&&(a||c)&&(o[o.length-1]=!0);continue}(n==="+"||n==="*"||n==="?"||n==="{"||n==="|")&&o.length&&(o[o.length-1]=!0)}return!1}function Nm(e,o){if(e==null)return;let t=e,r=t?.tipo;if(typeof t!="object"||!wm[r])throw i(`\xAB${o.etiqueta}\xBB: valor por defecto no v\xE1lido.`);if(!wm[r].includes(o.tipo))throw i(`\xAB${o.etiqueta}\xBB: ese valor por defecto no vale para este tipo.`);if(r==="fijo")return{tipo:r,valor:t.valor};if(r==="formula"){if(typeof t.formula!="string"||!t.formula.trim()||t.formula.length>1e3)throw i(`\xAB${o.etiqueta}\xBB: escribe la f\xF3rmula por defecto.`);return{tipo:r,formula:t.formula.trim()}}return{tipo:r}}var cw,gm,bm,vm,ym,wm,lw,_I,NI,$m=m(()=>{R();cw=["igual","distinto","vacio","lleno","uno_de"],gm=10,bm=200,vm=["texto","correo","telefono","url","codigo"],ym=["texto","correo","telefono","url","codigo","numero","importe"],wm={fijo:["texto","texto_largo","numero","importe","fecha","fecha_hora","booleano","seleccion","seleccion_multiple","url","correo","telefono","duracion","porcentaje","valoracion","contador","cronometro","color","codigo","hora"],hoy:["fecha","fecha_hora"],ahora:["fecha_hora"],yo:["texto","correo"],formula:["texto","texto_largo","numero","importe","fecha","fecha_hora","booleano","porcentaje","duracion"]},lw=e=>typeof e=="string"&&e.length<=200||typeof e=="number"&&Number.isFinite(e)||typeof e=="boolean";_I=aw({p:"",v:""}),NI=new sw("new RegExp(p, 'u').test(v)")});function xm(e,o,t){if(e.aprobacion===void 0||e.aprobacion===null)return;let r=e.aprobacion;if(typeof r!="object"||Array.isArray(r))throw i(`\xAB${t}\xBB, \xAB${o.etiqueta}\xBB: la aprobaci\xF3n, un objeto.`);let n=r.papel===void 0||r.papel===null||r.papel===""?void 0:r.papel;if(n!==void 0&&(typeof n!="string"||!/^[a-z_]{1,40}$/.test(n)))throw i(`\xAB${t}\xBB, \xAB${o.etiqueta}\xBB: el papel que aprueba no es v\xE1lido.`);let a=r.personas===void 0||r.personas===null?1:r.personas;if(!Number.isInteger(a)||a<1||a>10)throw i(`\xAB${t}\xBB, \xAB${o.etiqueta}\xBB: de 1 a 10 personas.`);o.aprobacion={...n?{papel:n}:{},personas:a}}var jI,Cm=m(()=>{Xn();R();jI=S`select a.*, m.clave,
|
|
19
19
|
(a.estado = 'pendiente' and crm_aprobacion_puede(a.papel, a.pedida_por, a.espacio_id, crm_yo())
|
|
20
20
|
and not exists (select 1 from jsonb_array_elements(a.votos) v where (v->>'sales_id')::bigint = crm_yo())) as puedo
|
|
21
|
-
from aprobaciones a join modulos m on m.id = a.modulo_id`});function fm(e,o,t){if(e.requisito!==void 0&&e.requisito!==null){let n=e.requisito;if(!Gb(n)||typeof n.formula!="string"||!n.formula.trim()||n.formula.length>Ye||typeof n.mensaje!="string"||!n.mensaje.trim()||n.mensaje.length>200)throw i(`\xAB${t}\xBB, \xAB${o.etiqueta}\xBB: el requisito lleva una f\xF3rmula y un mensaje (hasta 200 caracteres).`);o.requisito={formula:n.formula.trim(),mensaje:n.mensaje.trim()}}if(e.pide!==void 0&&e.pide!==null){if(!Array.isArray(e.pide)||e.pide.length>mm||e.pide.some(n=>typeof n!="string"||!/^[a-z][a-z0-9_]{0,40}$/.test(n)))throw i(`\xAB${t}\xBB, \xAB${o.etiqueta}\xBB: \xABpide\xBB, hasta ${mm} campos.`);e.pide.length&&(o.pide=[...new Set(e.pide)])}if(dm(e,o,t),e.limiteDias!==void 0&&e.limiteDias!==null){if(!Number.isInteger(e.limiteDias)||e.limiteDias<1||e.limiteDias>3650)throw i(`\xAB${t}\xBB, \xAB${o.etiqueta}\xBB: el l\xEDmite de d\xEDas, de 1 a 3650.`);o.limiteDias=e.limiteDias}}function hm(e){let o=e.filter(t=>!t.archivado);return e.map(t=>{if(t.tipo!=="seleccion"||!t.opciones?.some(r=>r.requisito||r.pide||r.limiteDias))return t;let n=t.opciones.map((r,a)=>{for(let l of r.pide??[]){let d=o.find(u=>u.clave===l);if(!d||["formula","resumen","busqueda","subtabla","boton","autonumero","creado_el","creado_por","modificado_el","modificado_por"].includes(d.tipo))throw i(`\xAB${t.etiqueta}\xBB, \xAB${r.etiqueta}\xBB: pide \xAB${l}\xBB, que no es un campo que se rellene.`)}if(!r.requisito)return r;let s;try{s=Qn([...o,Hb(t.clave,a,r.requisito.formula)]).at(-1)}catch(l){throw i(`\xAB${t.etiqueta}\xBB, \xAB${r.etiqueta}\xBB: ${l instanceof Error?l.message:"la f\xF3rmula no vale"}`)}if(s.origen?.tipo!=="booleano")throw i(`\xAB${t.etiqueta}\xBB, \xAB${r.etiqueta}\xBB: el requisito tiene que dar s\xED o no.`);return{...r,requisito:{...r.requisito,formula:s.formula}}});return{...t,opciones:n}})}var mm,Gb,Hb,gm=m(()=>{q();Gn();pm();mm=5,Gb=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Hb=(e,o,t)=>({clave:`etapa_${e}_${o}`,etiqueta:`Requisito ${o+1}`,tipo:"formula",formula:t})});function vm(e){if(e==null)return;if(!Array.isArray(e)||e.length>bm)throw i(`\xABplantillas_hijos\xBB: hasta ${bm}.`);let o=new Set,t=e.map((n,r)=>{let a=`Plantilla de hijos ${r+1}`;if(!fs(n))throw i(`${a}: un objeto.`);for(let d of Object.keys(n))if(!["clave","nombre","cuando","subtabla","modulo","via","registros"].includes(d))throw i(`${a}: clave no admitida \xAB${d.slice(0,40)}\xBB.`);if(typeof n.clave!="string"||!Zn.test(n.clave)||o.has(n.clave))throw i(`${a}: \xABclave\xBB (min\xFAsculas y _), sin repetir.`);if(o.add(n.clave),typeof n.nombre!="string"||!n.nombre.trim()||n.nombre.length>60)throw i(`${a}: el nombre (1\u201360).`);let s=n.cuando===void 0?[]:n.cuando;if(!Array.isArray(s)||s.length>3)throw i(`${a}: \xABcuando\xBB, hasta 3 condiciones.`);let l={clave:n.clave,nombre:n.nombre.trim(),cuando:s.map(d=>{if(!fs(d)||typeof d.campo!="string"||!Zn.test(d.campo)||!(typeof d.valor=="string"||typeof d.valor=="boolean"))throw i(`${a}: cada condici\xF3n, {campo, valor}.`);return{campo:d.campo,valor:d.valor}}),registros:[]};if(typeof n.subtabla=="string"&&n.subtabla){if(!Zn.test(n.subtabla))throw i(`${a}: \xABsubtabla\xBB no v\xE1lida.`);l.subtabla=n.subtabla}else{if(typeof n.modulo!="string"||!/^mod_(?!sub_)[a-z][a-z0-9_]{0,40}$/.test(n.modulo)||typeof n.via!="string"||!Zn.test(n.via))throw i(`${a}: una \xABsubtabla\xBB de este m\xF3dulo, o un \xABmodulo\xBB (mod_<clave>) y su relaci\xF3n \xABvia\xBB con este.`);l.modulo=n.modulo,l.via=n.via}if(!Array.isArray(n.registros)||!n.registros.length||n.registros.length>wm)throw i(`${a}: \xABregistros\xBB, de 1 a ${wm}.`);return l.registros=n.registros.map(d=>{if(!fs(d)||JSON.stringify(d).length>4e3)throw i(`${a}: cada registro, un objeto (de hasta 4000 caracteres).`);return d}),l});return t.length?t:void 0}var bm,wm,Zn,fs,ym=m(()=>{q();bm=10,wm=50,Zn=/^[a-z][a-z0-9_]{0,40}$/,fs=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)});function Pr(e){let o=new Map(Rr(e)?Ep(e).campos.map(a=>[a.clave,a.etiqueta]):[]),t={ubicacion:"Ubicaci\xF3n",nif:"Identificador fiscal",birthday:"Fecha de nacimiento",iban:"IBAN",province:"Provincia",state_abbr:"Provincia",has_newsletter:"Comunicaciones"},n=(Cp.find(a=>a.clave===e)?.campos??[]).map(a=>({...a,...o.has(a.clave)?{etiqueta:o.get(a.clave)}:Object.hasOwn(t,a.clave)?{etiqueta:eo(Eo(),t[a.clave])}:{}})),r=Rr(e)?Zb(e).map(a=>({...a,etiqueta:eo(Eo(),a.etiqueta),editable:!1,ordenable:!1,filtrable:!1,enTabla:!1})):[];return[...n,...r,...e==="companies"?Yb.map(a=>({...a,etiqueta:eo(Eo(),a.etiqueta),editable:!1,ordenable:!1,filtrable:!1,enTabla:!1})):[]]}var Rr,Xb,Yb,Kb,Zb,Hn=m(()=>{Op();qp();Br();Rr=e=>e==="contacts"||e==="companies",Xb=[{clave:"nombre",tipo:"texto",etiqueta:"Nombre completo"},{clave:"direccion",tipo:"texto",etiqueta:"Direcci\xF3n completa"},{clave:"correo",tipo:"correo",etiqueta:"Primer correo"},{clave:"correo_trabajo",tipo:"correo",etiqueta:"Correo del trabajo"},{clave:"correo_personal",tipo:"correo",etiqueta:"Correo personal"},{clave:"telefono",tipo:"telefono",etiqueta:"Primer tel\xE9fono"},{clave:"telefono_trabajo",tipo:"telefono",etiqueta:"Tel\xE9fono del trabajo"},{clave:"telefono_personal",tipo:"telefono",etiqueta:"Tel\xE9fono personal"}],Yb=[{clave:"persona.first_name",tipo:"texto",etiqueta:"Nombre"},{clave:"persona.last_name",tipo:"texto",etiqueta:"Apellidos"},{clave:"persona.correo",tipo:"correo",etiqueta:"Correo"},{clave:"persona.telefono",tipo:"telefono",etiqueta:"Tel\xE9fono"}],Kb=[{clave:"persona_referencia_id",tipo:"relacion",etiqueta:"Persona de referencia",relacion:"contacts"},{clave:"persona_first_name",tipo:"texto",etiqueta:"Nombre de la persona"},{clave:"persona_last_name",tipo:"texto",etiqueta:"Apellidos de la persona"},{clave:"persona_correo",tipo:"correo",etiqueta:"Correo de la persona"},{clave:"persona_telefono",tipo:"telefono",etiqueta:"Tel\xE9fono de la persona"}],Zb=e=>[...Xb.filter(o=>e==="contacts"||["nombre","direccion"].includes(o.clave)),...e==="companies"?Kb:[]]});function _m(e,o,t){let n=(a,s,l,d)=>{if(a.tipo!=="busqueda"||a.archivado)return a;let u=`${l}.${a.clave}`;if(d.length>=2||d.includes(u))throw i(`\xAB${a.etiqueta}\xBB: solo se encadena una b\xFAsqueda a un nivel.`);let p=s.find(b=>b.clave===a.desde&&!b.archivado&&b.tipo==="relacion");if(!p?.relacion)return a;let f=p.relacion,h;if(f.startsWith("mod_")){let b=f.slice(4),y=b===o?e:t?.get(b);if(!y)return a;if(h=y.find(w=>w.clave===a.campo&&!w.archivado),!h)throw i(`\xAB${a.etiqueta}\xBB: el campo que trae ya no existe al otro lado.`);h=n(h,y,b,[...d,u])}else{let b=Pr(f).find(y=>y.clave===a.campo)??t?.get(`@${f}`)?.find(y=>y.clave===a.campo&&!y.archivado);if(!b&&Ee(a.campo)&&!t?.has(`@${f}`))return a;if(!b)throw i(`\xAB${a.etiqueta}\xBB: ese campo no existe en ${f}.`);h={clave:a.campo,etiqueta:a.etiqueta,tipo:b.tipo,...Array.isArray(b.opciones)?{opciones:b.opciones}:{},...b.relacion?{relacion:b.relacion}:{},..."origen"in b&&b.origen?{origen:b.origen}:{}}}if(h.tipo==="archivos")throw i(`\xAB${a.etiqueta}\xBB: los ficheros no se traen en una b\xFAsqueda.`);if(h.tipo==="secreto")throw i(`\xAB${a.etiqueta}\xBB: un secreto no se trae en una b\xFAsqueda.`);if(h.tipo==="formula")throw i(`\xAB${a.etiqueta}\xBB: una f\xF3rmula no se trae en una b\xFAsqueda.`);if(h.tipo==="busqueda"){let b=h.origen;if(!b)throw i(`\xAB${a.etiqueta}\xBB: el campo que trae no est\xE1 listo.`);if(b.encadenada)throw i(`\xAB${a.etiqueta}\xBB: solo se encadena una b\xFAsqueda a un nivel.`);return{...a,origen:{...b,encadenada:!0}}}return{...a,origen:{tipo:h.tipo,...h.opciones?{opciones:h.opciones}:{},...h.relacion?{relacion:h.relacion}:{}}}},r=e.map(a=>n(a,e,o,[]));return ew(r),r}function ew(e){let o=new Set(["texto","texto_largo","correo","telefono","url","codigo","numero","importe","porcentaje","fecha","fecha_hora","booleano"]);for(let t of e.filter(n=>!n.archivado&&n.tipo==="busqueda"&&n.siVacio)){let n=e.find(a=>a.clave===t.siVacio&&!a.archivado),r=a=>!e.find(s=>s.clave===a.desde)?.multiple;if(!n||n===t||n.tipo!=="busqueda"||n.siVacio||!r(t)||!r(n)||!t.origen||!n.origen||!o.has(t.origen.tipo)||t.origen.tipo!==n.origen.tipo||t.origen.encadenada||n.origen.encadenada)throw i("La alternativa necesita otra b\xFAsqueda escalar del mismo tipo, sin cadenas.")}}var Nm=m(()=>{kr();q();Hn()});function Ee(e){if(typeof e!="string"||!/^datos\.[a-z][a-z0-9_]{0,40}$/.test(e))return null;let o=e.slice(6);return o==="tipos"?null:o}function $m(e,o,t){let n=r=>{let a=Object.hasOwn(o,r.campo)?Ee(o[r.campo]):null;if(!a)throw i("La condici\xF3n del campo propio necesita otro campo propio de la misma ra\xEDz.");return{...r,campo:a}};return e.filter(r=>!r.archivado&&Object.hasOwn(o,r.clave)&&Ee(o[r.clave])).map(r=>{if(r.tipo==="relacion"&&(Object.keys(r.copiar??{}).length||r.mostrarTareasEnFichaRelacionada||r.alBorrar&&r.alBorrar!=="avisar")||r.porDefecto||r.depende||r.completarDesde||r.alMarcar||r.embudo||r.opciones?.some(u=>u.requisito||u.pide?.length||u.limiteDias!==void 0||u.aprobacion))throw i("El campo propio necesita conservar sus reglas antes de convertir la ra\xEDz.");let s=[{campo:"tipos",op:"igual",valor:t},...(r.visibleSi??[]).map(n)];if(s.length>10)throw i("El campo propio supera las diez condiciones al a\xF1adir su tipo.");let l=r.tipo==="busqueda"?Ee(o[r.desde??""]):null,d=r.siVacio?Ee(o[r.siVacio]):null;if(r.tipo==="busqueda"&&(!l||r.siVacio&&!d))throw i("La b\xFAsqueda propia necesita relaciones y alternativas propias de la misma ra\xEDz.");return{...structuredClone(r),...l?{desde:l}:{},...d?{siVacio:d}:{},clave:Ee(o[r.clave]),visibleSi:s,...r.obligatorioSi?{obligatorioSi:r.obligatorioSi.map(n)}:{}}})}var kr=m(()=>{q()});function xm(e,o){if(e==null)return;if(!Tr(e))throw i("\xABerp\xBB: un objeto.");let t=(r,a,s=!1)=>{if(!(r===void 0&&s)){if(typeof r!="string"||!o.some(l=>l.clave===r&&l.tipo!=="subtabla"))throw i(`ERP: \xAB${a}\xBB no es un campo del m\xF3dulo.`);return r}},n={};if(e.presupuesto!==void 0){let r=e.presupuesto;if(!Tr(r)||!Tr(r.lineas))throw i("ERP: \xABpresupuesto\xBB con \xABcliente\xBB y \xABlineas\xBB.");let a=o.find(d=>d.clave===r.lineas.subtabla&&d.tipo==="subtabla");if(!a)throw i("ERP: \xABlineas.subtabla\xBB no es una subtabla del m\xF3dulo.");let s=r.lineas,l=(d,u,p=!1)=>{if(!(d===void 0&&p)){if(typeof d!="string"||!(a.columnas??[]).some(f=>f.clave===d))throw i(`ERP: \xAB${u}\xBB no es una columna de la subtabla.`);return d}};if(s.articulo!==void 0&&!(a.columnas??[]).some(d=>d.clave===s.articulo&&d.tipo==="articulo"))throw i("ERP: \xABarticulo\xBB, una columna de art\xEDculo de la subtabla.");if(r.tipo!==void 0&&r.tipo!=="presupuesto"&&r.tipo!=="factura")throw i("ERP: \xABtipo\xBB, presupuesto o factura.");if(r.clienteAlternativo!==void 0&&r.clienteAlternativo===r.cliente)throw i("ERP: las relaciones de cliente deben ser distintas.");n.presupuesto={...r.tipo?{tipo:r.tipo}:{},cliente:t(r.cliente,"cliente"),...r.clienteAlternativo!==void 0?{clienteAlternativo:t(r.clienteAlternativo,"clienteAlternativo")}:{},lineas:{subtabla:a.clave,descripcion:l(s.descripcion,"descripcion"),precio:l(s.precio,"precio"),...s.cantidad!==void 0?{cantidad:l(s.cantidad,"cantidad")}:{},...s.iva!==void 0?{iva:l(s.iva,"iva")}:{},...s.articulo!==void 0?{articulo:s.articulo}:{}}}}if(e.gasto!==void 0){let r=e.gasto;if(!Tr(r))throw i("ERP: \xABgasto\xBB, un objeto.");if(r.tipo!==void 0&&r.tipo!=="factura"&&r.tipo!=="ticket")throw i("ERP: el gasto es factura o ticket.");n.gasto={...r.tipo?{tipo:r.tipo}:{},proveedor:t(r.proveedor,"proveedor"),fecha:t(r.fecha,"fecha"),base:t(r.base,"base"),...r.nif!==void 0?{nif:t(r.nif,"nif")}:{},...r.numero!==void 0?{numero:t(r.numero,"numero")}:{},...r.iva!==void 0?{iva:t(r.iva,"iva")}:{}}}if(e.horas!==void 0){let r=e.horas;if(!Tr(r))throw i("ERP: \xABhoras\xBB, un objeto.");let a=t(r.guardarEn,"guardarEn",!0);if(a&&!o.some(s=>s.clave===a&&["numero","duracion"].includes(s.tipo)))throw i("ERP: \xABguardarEn\xBB, un campo num\xE9rico.");n.horas={desde:t(r.desde,"desde"),hasta:t(r.hasta,"hasta"),...r.persona!==void 0?{persona:t(r.persona,"persona")}:{},...a?{guardarEn:a}:{}}}return Object.keys(n).length?n:void 0}var Tr,Cm=m(()=>{q();Tr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)});function Sm(e,o){if(e==null)return;if(!wt(e))throw i("\xABimpresion\xBB: un objeto.");let{ejemplares:t,cuerpo:n,...r}=e;if(r.subtabla!==void 0)throw i("Impresi\xF3n: clave no admitida \xABsubtabla\xBB.");let a=Mr(r,o)??{},s=Xt(n,"El texto del documento",jm);if(s){for(let l of s.matchAll(/\{\{\s*([^}]*?)\s*\}\}/g)){let d=l[1];if(d!=="hoy"&&!/^padre\.[a-z][a-z0-9_]{0,40}$/.test(d)&&!o.some(u=>u.clave===d&&!u.archivado))throw i(`El texto del documento: \xAB{{${d.slice(0,40)}}}\xBB no es una columna de la l\xEDnea ni \xABpadre.<campo>\xBB.`)}a.cuerpo=s}if(t!=null){if(!Array.isArray(t)||t.length>3||t.some(l=>typeof l!="string"||!l.trim()||l.length>60))throw i("\xABejemplares\xBB: hasta 3, cada uno con su r\xF3tulo (hasta 60).");t.length&&(a.ejemplares=t.map(l=>l.trim()))}return Object.keys(a).length?a:void 0}function ei(e,o,t){for(let n of Object.keys(e))if(!o.includes(n))throw i(`${t}: clave no admitida \xAB${n.slice(0,40)}\xBB.`)}function Xt(e,o,t){if(!(e==null||e==="")){if(typeof e!="string"||e.length>t)throw i(`${o}: texto de hasta ${t} caracteres.`);return e.trim()||void 0}}function bt(e,o,t,n,r=()=>!0){if(e==null)return;if(!Array.isArray(e)||e.length>t||!e.every(s=>typeof s=="string"))throw i(`${n}: hasta ${t} claves de campo.`);let a=new Set(o.filter(s=>!s.archivado&&r(s)).map(s=>s.clave));return[...new Set(e)].filter(s=>a.has(s))}function oi(e,o){if(e==null)return;if(!wt(e))throw i("\xABficha\xBB: un objeto.");ei(e,["cabecera","columnas","pestanas","relacionadas","erp","sin_conexion","rapido","duplicados","tarjeta","en_crear","filtros","principal","plegar_vacios"],"Ficha");let t={},n=bt(e.cabecera,o,4,"La cabecera",p=>!["subtabla","boton","archivos","texto_largo"].includes(p.tipo));if(n?.length&&(t.cabecera=n),e.columnas!==void 0){if(e.columnas!==1&&e.columnas!==2&&e.columnas!==3)throw i("\xABcolumnas\xBB: 1, 2 o 3.");e.columnas>1&&(t.columnas=e.columnas)}if(e.pestanas!==void 0){if(!Array.isArray(e.pestanas)||e.pestanas.length>6)throw i("Hasta 6 pesta\xF1as.");let p=e.pestanas.map((f,h)=>{if(!wt(f))throw i(`Pesta\xF1a ${h+1}: un objeto.`);ei(f,["titulo","secciones","artefacto"],`Pesta\xF1a ${h+1}`);let b=Xt(f.titulo,`Pesta\xF1a ${h+1}`,40);if(!b)throw i(`Pesta\xF1a ${h+1}: falta el t\xEDtulo.`);if(f.artefacto!==void 0){let y=Number(f.artefacto);if(!Number.isSafeInteger(y)||y<1)throw i(`Pesta\xF1a ${h+1}: el artefacto no es v\xE1lido.`);return{titulo:b,secciones:[],artefacto:y}}if(!Array.isArray(f.secciones)||f.secciones.length>20||!f.secciones.every(y=>typeof y=="string"&&y.length<=60))throw i(`Pesta\xF1a ${h+1}: sus secciones, hasta 20.`);return{titulo:b,secciones:[...new Set(f.secciones)]}});p.length&&(t.pestanas=p)}if(e.relacionadas!==void 0){if(e.relacionadas!=="abajo"&&e.relacionadas!=="pestana")throw i("\xABrelacionadas\xBB: abajo o pestana.");e.relacionadas==="pestana"&&(t.relacionadas="pestana")}let r=xm(e.erp,o);if(r&&(t.erp=r),e.sin_conexion!==void 0){if(typeof e.sin_conexion!="boolean")throw i("\xABsin_conexion\xBB: s\xED o no.");e.sin_conexion&&(t.sin_conexion=!0)}let a=bt(e.rapido,o,3,"El registro r\xE1pido",p=>!["subtabla","boton","archivos","firma","busqueda","resumen","formula","autonumero","creado_el","creado_por","modificado_el","modificado_por"].includes(p.tipo));a?.length&&(t.rapido=a);let s=bt(e.duplicados,o,3,"Los campos de duplicados",p=>ow.includes(p.tipo));s?.length&&(t.duplicados=s);let l=bt(e.tarjeta,o,3,"La tarjeta",p=>!["subtabla","boton","archivos","texto_largo","firma"].includes(p.tipo));if(l?.length&&(t.tarjeta=l),e.en_crear!==void 0){if(typeof e.en_crear!="boolean")throw i("\xABen_crear\xBB: s\xED o no.");e.en_crear&&(t.en_crear=!0)}let d=bt(e.filtros,o,4,"Los filtros de arriba",p=>tw.includes(p.tipo));d?.length&&(t.filtros=d);let u=bt(e.principal,o,8,"El contenido principal",p=>p.tipo!=="boton");if(u?.length&&(t.principal=u),e.plegar_vacios!==void 0){if(typeof e.plegar_vacios!="boolean")throw i("\xABplegar_vacios\xBB: s\xED o no.");e.plegar_vacios||(t.plegar_vacios=!1)}return Object.keys(t).length?t:void 0}function Mr(e,o){if(e==null)return;if(!wt(e))throw i("\xABimpresion\xBB: un objeto.");ei(e,["titulo","campos","subtabla","pie","logo","orientacion","cuerpo","color","firmas"],"Impresi\xF3n");let t={},n=Xt(e.titulo,"El t\xEDtulo de la impresi\xF3n",80);n&&(t.titulo=n);let r=bt(e.campos,o,40,"Los campos de la impresi\xF3n",l=>!["subtabla","boton"].includes(l.tipo));if(r?.length&&(t.campos=r),e.subtabla!==void 0&&e.subtabla!==null&&e.subtabla!==""){if(typeof e.subtabla!="string")throw i("\xABsubtabla\xBB: la clave de una subtabla.");o.some(l=>l.clave===e.subtabla&&l.tipo==="subtabla"&&!l.archivado)&&(t.subtabla=e.subtabla)}let a=Xt(e.pie,"El pie de la impresi\xF3n",500);if(a&&(t.pie=a),e.logo!==void 0){if(typeof e.logo!="boolean")throw i("\xABlogo\xBB: s\xED o no.");e.logo&&(t.logo=!0)}if(e.orientacion!==void 0){if(e.orientacion!=="vertical"&&e.orientacion!=="horizontal")throw i("\xABorientacion\xBB: vertical u horizontal.");e.orientacion==="horizontal"&&(t.orientacion="horizontal")}let s=Xt(e.cuerpo,"El texto del documento",jm);if(s){for(let l of s.matchAll(/\{\{\s*([^}]*?)\s*\}\}/g)){let d=l[1];if(d!=="hoy"&&!o.some(u=>u.clave===d&&!u.archivado))throw i(`El texto del documento: \xAB{{${d.slice(0,40)}}}\xBB no es un campo del m\xF3dulo.`)}t.cuerpo=s}if(e.color!==void 0&&e.color!==null&&e.color!==""){if(typeof e.color!="string"||!/^#[0-9a-fA-F]{6}$/.test(e.color))throw i("\xABcolor\xBB: #rrggbb.");t.color=e.color.toLowerCase()}if(e.firmas!==void 0&&e.firmas!==null){if(!Array.isArray(e.firmas)||e.firmas.length>4||e.firmas.some(l=>typeof l!="string"||!l.trim()||l.length>60))throw i("\xABfirmas\xBB: hasta 4 casillas, cada una con su texto (hasta 60).");e.firmas.length&&(t.firmas=e.firmas.map(l=>l.trim()))}return Object.keys(t).length?t:void 0}function hs(e,o=0){return o>10?!1:Array.isArray(e)?e.every(t=>hs(t,o+1)):wt(e)?Object.keys(e).every(t=>!rw.has(t)&&hs(e[t],o+1)):!0}function Am(e){if(e==null)return;if(!Array.isArray(e)||e.length>10)throw i("\xABvistas\xBB: hasta 10.");let o=e.map((t,n)=>{if(!wt(t))throw i(`Vista ${n+1}: un objeto.`);ei(t,["nombre","tipo","config"],`Vista ${n+1}`);let r=Xt(t.nombre,`Vista ${n+1}`,60);if(!r)throw i(`Vista ${n+1}: falta el nombre.`);if(typeof t.tipo!="string"||!Om.includes(t.tipo))throw i(`Vista ${n+1}: tipo ${Om.join(", ")}.`);if(t.config!==void 0&&(!wt(t.config)||!hs(t.config)||JSON.stringify(t.config).length>4e3))throw i(`Vista ${n+1}: \xABconfig\xBB, un objeto de hasta 4 KB.`);return{nombre:r,tipo:t.tipo,...t.config?{config:t.config}:{}}});return o.length?o:void 0}var wt,ow,tw,jm,Om,rw,gs=m(()=>{q();Cm();wt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);ow=["texto","correo","telefono","codigo","url"],tw=["seleccion","seleccion_multiple","etiquetas","booleano","hecho","creado_por","modificado_por","relacion","texto","texto_largo","correo","telefono","url","codigo","autonumero","ubicacion","numero","importe","porcentaje","fecha","fecha_hora","duracion","valoracion"];jm=12e3;Om=["kanban","calendario","linea","mapa","galeria","tablero","cuadrante","dia"],rw=new Set(["__proto__","constructor","prototype"])});var Ir,Em=m(()=>{Ir=e=>e==="@contacts"||e==="@companies"});function ni(e,o){if(e==null)return;if(!Array.isArray(e)||e.length>ti)throw i(`\xABrelacionadas\xBB: hasta ${ti} columnas.`);if(!e.length)return;let t=new Set;return e.map((n,r)=>{let a=`Columna relacionada ${r+1}`;if(!ws(n))throw i(`${a}: un objeto.`);km(n,["clave","etiqueta","via","campo","de","calculo","filtro","siVacio"],a);let s=vt(n.clave,`${a}.clave`);if(t.has(s)||o.some(u=>u.clave===s))throw i(`${a}: la clave \xAB${s}\xBB ya la usa otra columna o un campo.`);if(t.add(s),typeof n.etiqueta!="string"||!n.etiqueta.trim()||n.etiqueta.length>80)throw i(`${a}: \xABetiqueta\xBB, de 1 a 80 caracteres.`);let l=Ir(String(n.de))&&typeof n.via=="string"&&/^datos\.[a-z][a-z0-9_]{0,40}$/.test(n.via)?n.via:vt(n.via,`${a}.via`);if(n.de!==void 0){if(n.siVacio!==void 0)throw i("\xABsiVacio\xBB solo se admite al traer un valor escalar.");let u=typeof n.de=="string"&&Ir(n.de)?n.de:vt(n.de,`${a}.de`);if(typeof n.calculo!="string"||!qm.includes(n.calculo))throw i(`${a}: \xABcalculo\xBB, uno de ${qm.join(", ")}.`);let p=n.calculo,f=p==="recuento"?void 0:Ir(u)&&typeof n.campo=="string"&&/^datos\.[a-z][a-z0-9_]{0,40}$/.test(n.campo)?n.campo:vt(n.campo,`${a}.campo`),h=Dr(n.filtro,a,Ir(u));return{clave:s,etiqueta:n.etiqueta.trim(),via:l,de:u,calculo:p,...f?{campo:f}:{},...h?{filtro:h}:{}}}if(n.calculo!==void 0||n.filtro!==void 0)throw i(`${a}: \xABcalculo\xBB y \xABfiltro\xBB solo con \xABde\xBB (los hijos).`);let d=o.find(u=>u.clave===l&&!u.archivado);if(!d||d.tipo!=="relacion")throw i(`${a}: \xAB${l}\xBB no es una relaci\xF3n de este m\xF3dulo.`);if(d.multiple&&n.siVacio!==void 0)throw i("Una colecci\xF3n no tiene alternativa escalar.");if(typeof n.campo!="string"||!/^[a-z][a-z0-9_.]{0,80}$/.test(n.campo))throw i(`${a}: campo no v\xE1lido.`);return{clave:s,etiqueta:n.etiqueta.trim(),via:l,campo:n.campo,...n.siVacio!==void 0?{siVacio:vt(n.siVacio,`${a}.siVacio`)}:{}}})}function ii(e){if(e==null)return;if(!Array.isArray(e)||e.length>ri)throw i(`\xABsiguientes\xBB: hasta ${ri} pasos.`);if(!e.length)return;let o=new Set;return e.map((t,n)=>{let r=`Siguiente paso ${n+1}`;if(!ws(t))throw i(`${r}: un objeto.`);km(t,["clave","nombre","destino","enlace","campos"],r);let a=vt(t.clave,`${r}.clave`);if(o.has(a))throw i(`${r}: \xABclave\xBB repetida.`);if(o.add(a),typeof t.nombre!="string"||!t.nombre.trim()||t.nombre.length>60)throw i(`${r}: el nombre del bot\xF3n (1\u201360).`);if(typeof t.destino!="string"||!/^mod_(?!sub_)[a-z][a-z0-9_]{0,40}$/.test(t.destino))throw i(`${r}: \xABdestino\xBB, mod_<clave>.`);let s=vt(t.enlace,`${r}.enlace`),l;if(t.campos!==void 0&&t.campos!==null){if(!ws(t.campos)||Object.keys(t.campos).length>40)throw i(`${r}: \xABcampos\xBB, un objeto destino \u2192 origen (hasta 40).`);for(let[d,u]of Object.entries(t.campos))if(!bs.test(d)||typeof u!="string"||!bs.test(u))throw i(`${r}: \xABcampos.${d.slice(0,40)}\xBB no es v\xE1lido.`);l=t.campos}return{clave:a,nombre:t.nombre.trim(),destino:t.destino,enlace:s,...l&&Object.keys(l).length?{campos:l}:{}}})}var qm,ti,ri,bs,ws,km,vt,ai=m(()=>{Em();q();Lr();qm=["recuento","suma","minimo","maximo","ultimo","media"],ti=20,ri=5,bs=/^[a-z][a-z0-9_]{0,40}$/,ws=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),km=(e,o,t)=>{for(let n of Object.keys(e))if(!o.includes(n))throw i(`${t}: clave no admitida \xAB${n.slice(0,40)}\xBB.`)},vt=(e,o)=>{if(typeof e!="string"||!bs.test(e))throw i(`${o}: falta o no es v\xE1lido.`);return e}});function vs(e,o){if(e===void 0)return;if(!e||typeof e!="object"||Array.isArray(e))throw i("La configuraci\xF3n de ra\xEDces necesita objetos expl\xEDcitos.");let t={};for(let[n,r]of Object.entries(e)){if(!["contacts","companies"].includes(n)||!r||typeof r!="object"||Array.isArray(r))throw i("La configuraci\xF3n de ra\xEDces necesita contacts o companies.");let a={};for(let[s,l]of Object.entries(r)){if(!["ficha","impresion","relacionadas","siguientes","recurso","reserva"].includes(s))throw i("Configura ficha, impresi\xF3n, relacionadas, siguientes, recurso o reserva.");Object.assign(a,{[s]:(s==="ficha"?oi(l,o):s==="impresion"?Mr(l,o):s==="relacionadas"?ni(l,o):s==="recurso"?Xn(l,o):s==="reserva"?Yn(l,o):ii(l))??null})}t[n]=a}return t}var Pm=m(()=>{ms();q();gs();ai()});function Tm(e){if(e!==void 0){if(!e||typeof e!="object"||Array.isArray(e))throw i("Los ajustes nativos necesitan objetos expl\xEDcitos.");for(let[o,t]of Object.entries(e))if(!["contacts","companies"].includes(o)||!t||typeof t!="object"||Array.isArray(t)||Object.keys(t).some(n=>!ys.includes(n)))throw i("Un ajuste nativo no cambia la identidad de la relaci\xF3n.");return structuredClone(e)}}var ys,_s=m(()=>{q();ys=["etiqueta","ayuda","enTabla","obligatorio","visibleSi","obligatorioSi","permisos","siVacio","completarDesde"]});function Mm(e,o,t={}){for(let[r,a]of Object.entries(t)){let s=e.find(u=>u.clave===r&&!u.archivado),l=o[r],d=s?.opciones??[];if(s?.tipo!=="seleccion"||!l||!Object.hasOwn(Ns,l)||Object.keys(a).length!==d.length||!d.length||d.some(u=>!Object.hasOwn(a,u.valor))||Object.values(a).some(u=>typeof u!="string"||!u||u!==u.trim())||new Set(Object.values(a)).size!==d.length)throw i("Las conversiones nativas necesitan un mapa de selecciones completo.")}let n=new Map;for(let r of e){let a=o[r.clave];if(r.archivado||r.tipo!=="seleccion"||!a||!Object.hasOwn(Ns,a))continue;let s=Ns[a];if(r.opciones?.some(l=>l.hecho||l.requisito||l.pide?.length||l.limiteDias!==void 0||l.aprobacion))throw i("Las opciones de Personas/Empresas no pueden perder reglas de etapas.");n.set(s,qr(s,(r.opciones??[]).map(l=>({value:Object.hasOwn(t,r.clave)?t[r.clave][l.valor]:l.valor,label:l.etiqueta,...l.color?{color:l.color}:{}}))))}return n}var Ns,Im=m(()=>{q();os();Ns={sector:"companySectors",forma_juridica:"legalForms"}});function xs(e,o){if(e===void 0)return;if(!Oo(e))throw i("\xABpersonas\xBB: un objeto.");if($s(e,["objeto","tipo","de","etiqueta","plural","icono","campos","conversiones","alternativa","clasificacion","configuracion"],"\xABpersonas\xBB"),e.alternativa!==void 0||e.clasificacion!==void 0)return iw(e,o);if(e.objeto==="deals"&&o.some(p=>p.tipo==="autonumero"))throw i("Los auton\xFAmeros propios no est\xE1n disponibles en Oportunidades.");if(e.objeto==="deals"&&o.some(p=>p.unico))throw i("Los campos propios \xFAnicos no est\xE1n disponibles en Oportunidades.");if(e.objeto!=="contacts"&&e.objeto!=="companies")throw i("\xABpersonas.objeto\xBB: contacts o companies.");let t=si(e.tipo,"tipo",60);if(!nw.test(t))throw i("\xABpersonas.tipo\xBB: una clave de tipo.");if(e.de!==void 0&&e.de!=="cliente"&&e.de!=="proveedor")throw i("\xABpersonas.de\xBB: cliente o proveedor.");if(e.de===t||(t==="cliente"||t==="proveedor")&&e.de!==void 0)throw i("\xABpersonas.de\xBB: un tipo base no puede ser un subtipo.");let n=si(e.icono,"icono",40);if(!/^[a-z0-9-]+$/.test(n))throw i("\xABpersonas.icono\xBB: una clave de icono.");if(!Oo(e.campos))throw i("\xABpersonas.campos\xBB: un mapa expl\xEDcito de campos nativos.");let r={},a=new Map;for(let[p,f]of Object.entries(e.campos)){let h=o.find(w=>w.clave===p&&!w.archivado),b=typeof f=="string"&&Object.hasOwn(Lm[e.objeto],f)?Lm[e.objeto][f]:void 0,y=Ee(f);if(!h||!(y?jp.has(h.tipo):b?.includes(h.tipo)))throw i(`\xABpersonas.campos.${p.slice(0,40)}\xBB: campo nativo o tipo incompatible.`);if(h.unico&&typeof f=="string"&&f.startsWith("persona."))throw i("El campo propio necesita conservar sus reglas antes de convertir la ra\xEDz.");if(a.has(f)&&f!=="nif"&&f!=="tax_identifier")throw i(`\xABpersonas.campos\xBB: dos campos apuntan a \xAB${f}\xBB.`);a.set(f,p),r[p]=f}let s=e.objeto==="contacts"?"first_name":"name";if(!a.has(s))throw i(`\xABpersonas.campos\xBB: falta el nombre nativo \xAB${s}\xBB.`);let l=o.filter(p=>!p.archivado);for(let p of l)if(!Object.hasOwn(r,p.clave)&&p.tipo!=="resumen"&&p.tipo!=="formula")throw i(`\xABpersonas.campos\xBB: falta destino para \xAB${p.clave}\xBB; no se puede perder un campo.`);if(e.conversiones!==void 0&&!Oo(e.conversiones))throw i("Las conversiones nativas necesitan un mapa de selecciones completo.");let d={};for(let[p,f]of Object.entries(e.conversiones??{})){if(!Oo(f)||Object.values(f).some(h=>typeof h!="string"))throw i("Las conversiones nativas necesitan un mapa de selecciones completo.");Object.defineProperty(d,p,{value:{...f},enumerable:!0})}$m(o,r,t),Mm(o,r,d);let u=vs(e.configuracion,o);if(u&&Object.keys(u).some(p=>p!==e.objeto))throw i("La configuraci\xF3n cita un objeto que esta ra\xEDz no declara.");return{objeto:e.objeto,tipo:t,...e.de?{de:e.de}:{},...u?{configuracion:u}:{},etiqueta:si(e.etiqueta,"etiqueta",60),plural:si(e.plural,"plural",60),icono:n,campos:r,...e.conversiones!==void 0?{conversiones:d}:{}}}function iw(e,o){let t=e.alternativa,n=e.clasificacion;if(e.objeto!=="contacts"||!Oo(t)||t.objeto!=="companies"||!Oo(t.campos)||!Oo(n))throw i("Los destinos dobles necesitan Persona, Empresa y clasificaci\xF3n expl\xEDcita.");$s(t,["objeto","campos","conversiones"],"\xABpersonas.alternativa\xBB"),$s(n,["campo","valores","vacio","formas","etiquetas","propiedad"],"\xABpersonas.clasificacion\xBB");let r=o.find(w=>w.clave===n.campo&&!w.archivado);if(!r||!["seleccion","booleano"].includes(r.tipo)||!Oo(n.valores)||n.vacio!==void 0&&n.vacio!=="contacts"&&n.vacio!=="companies")throw i("La clasificaci\xF3n necesita todas las opciones de una selecci\xF3n o booleano.");if(r.opciones?.some(w=>w.hecho||w.requisito||w.pide?.length||w.limiteDias!==void 0||w.aprobacion))throw i("La clasificaci\xF3n no puede perder permisos ni reglas de etapas.");let a=r.tipo==="booleano"?["true","false"]:(r.opciones??[]).map(w=>w.valor);if(!a.length||Object.keys(n.valores).length!==a.length||a.some(w=>!Object.hasOwn(n.valores,w))||Object.values(n.valores).some(w=>w!=="contacts"&&w!=="companies")||!Object.values(n.valores).includes("contacts")||!Object.values(n.valores).includes("companies"))throw i("La clasificaci\xF3n necesita todas las opciones de una selecci\xF3n o booleano.");let s=_p(n,r,n.valores),l={campo:r.clave,valores:{...n.valores},...n.vacio?{vacio:n.vacio}:{},...s},{alternativa:d,clasificacion:u,configuracion:p,...f}=e,h=w=>xs(w,$p(o,l,w.objeto).filter(g=>Oo(w.campos)&&Object.hasOwn(w.campos,g.clave)||g.tipo==="resumen"||g.tipo==="formula")),b=h(f),y=h({...f,objeto:"companies",campos:t.campos,conversiones:t.conversiones});if(l.propiedad){if(b.campos[r.clave]!==l.propiedad||y.campos[r.clave]!==l.propiedad||b.conversiones?.[r.clave]||y.conversiones?.[r.clave])throw i("La clasificaci\xF3n propia necesita el mismo destino tipado en ambas ramas, sin conversiones.")}else if(Object.hasOwn(b.campos,r.clave)||Object.hasOwn(y.campos,r.clave))throw i("El discriminante de identidad no es un campo nativo.");for(let w of o.filter(g=>!g.archivado&&g.clave!==r.clave&&g.tipo!=="resumen"&&g.tipo!=="formula"))if(!Object.hasOwn(b.campos,w.clave)&&!Object.hasOwn(y.campos,w.clave))throw i("Los destinos deben conservar todos los campos del origen salvo el discriminante.");return Np(o,l),{...b,alternativa:{objeto:"companies",campos:y.campos,...y.conversiones?{conversiones:y.conversiones}:{}},clasificacion:l,...e.configuracion!==void 0?{configuracion:vs(e.configuracion,o)}:{}}}var Dm,Lm,Oo,nw,si,$s,zm=m(()=>{kr();Ap();Pm();q();xp();Im();Dm={ubicacion:["ubicacion"],address:["texto","texto_largo"],zipcode:["texto","codigo"],city:["texto"],country:["texto"],pais_fiscal:["texto","seleccion"],iban:["texto"]},Lm={contacts:{...Dm,province:["texto"],first_name:["texto"],last_name:["texto"],title:["texto"],correo:["correo"],telefono:["telefono"],background:["texto_largo","texto"],nif:["texto"],birthday:["fecha"],first_seen:["fecha","fecha_hora"],has_newsletter:["booleano"]},companies:{...Dm,state_abbr:["texto"],name:["texto"],razon_social:["texto"],tax_identifier:["texto"],phone_number:["telefono"],website:["url"],description:["texto_largo","texto"],sector:["seleccion","texto"],forma_juridica:["seleccion","texto"],correo_facturacion:["correo"],has_newsletter:["booleano"],"persona.first_name":["texto"],"persona.last_name":["texto"],"persona.correo":["correo"],"persona.telefono":["telefono"]}},Oo=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),nw=/^[a-z0-9][a-z0-9-]{0,59}$/,si=(e,o,t)=>{if(typeof e!="string"||!e.trim()||e.trim().length>t)throw i(`\xABpersonas.${o}\xBB: texto de 1 a ${t} caracteres.`);return e.trim()},$s=(e,o,t)=>{for(let n of Object.keys(e))if(!o.includes(n))throw i(`${t}: clave no admitida \xAB${n.slice(0,40)}\xBB.`)}});function Bm(e){if(e==null)return;if(!Array.isArray(e)||e.length>Fm)throw i(`\xABconversiones\xBB: hasta ${Fm}.`);let o=new Set,t=e.map((n,r)=>{let a=`Conversi\xF3n ${r+1}`;if(!ci(n))throw i(`${a}: un objeto.`);for(let l of Object.keys(n))if(!["clave","nombre","destino","campos","enlaceDestino","enlaceOrigen","lineas","etapa"].includes(l))throw i(`${a}: clave no admitida \xAB${l.slice(0,40)}\xBB.`);if(typeof n.clave!="string"||!yt.test(n.clave)||o.has(n.clave))throw i(`${a}: \xABclave\xBB (min\xFAsculas y _), sin repetir.`);if(o.add(n.clave),typeof n.nombre!="string"||!n.nombre.trim()||n.nombre.length>60)throw i(`${a}: el nombre del bot\xF3n (1\u201360).`);if(typeof n.destino!="string"||!(aw.includes(n.destino)||/^mod_(?!sub_)[a-z][a-z0-9_]{0,40}$/.test(n.destino)))throw i(`${a}: \xABdestino\xBB, contacts, companies, deals o mod_<clave>.`);let s={clave:n.clave,nombre:n.nombre.trim(),destino:n.destino,campos:Wm(n.campos,a)};for(let l of["enlaceDestino","enlaceOrigen"])if(!(n[l]===void 0||n[l]===null||n[l]==="")){if(typeof n[l]!="string"||!yt.test(n[l]))throw i(`${a}: \xAB${l}\xBB no es un campo v\xE1lido.`);s[l]=n[l]}if(n.lineas!==void 0){if(!Array.isArray(n.lineas)||n.lineas.length>5)throw i(`${a}: \xABlineas\xBB, hasta 5.`);s.lineas=n.lineas.map(l=>{if(!ci(l)||typeof l.desde!="string"||!yt.test(l.desde)||typeof l.a!="string"||!yt.test(l.a))throw i(`${a}: cada \xABlineas\xBB, {desde, a, campos}.`);return{desde:l.desde,a:l.a,campos:Wm(l.campos,a)}})}if(n.etapa!==void 0&&n.etapa!==null){if(!ci(n.etapa)||typeof n.etapa.campo!="string"||!yt.test(n.etapa.campo)||typeof n.etapa.valor!="string")throw i(`${a}: \xABetapa\xBB, {campo, valor}.`);s.etapa={campo:n.etapa.campo,valor:n.etapa.valor}}return s});return t.length?t:void 0}var Fm,yt,aw,ci,Wm,Um=m(()=>{q();Fm=5,yt=/^[a-z][a-z0-9_]{0,40}$/,aw=["contacts","companies","deals"],ci=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Wm=(e,o)=>{if(e===void 0)return{};if(!ci(e)||Object.keys(e).length>100)throw i(`${o}: \xABcampos\xBB, un objeto destino \u2192 origen.`);for(let[t,n]of Object.entries(e))if(!yt.test(t)||typeof n!="string"||!yt.test(n))throw i(`${o}: el campo \xAB${t.slice(0,40)}\xBB no es v\xE1lido.`);return e}});function Qm(e,o){if(e==null)return;if(!Array.isArray(e)||e.length>Vm)throw i(`\xABencadenar\xBB: hasta ${Vm}.`);let t=new Set,n=e.map((r,a)=>{let s=`\xABencadenar\xBB ${a+1}`;if(!_t(r))throw i(`${s}: un objeto.`);for(let g of Object.keys(r))if(!["clave","nombre","destino","enlace","campos","lineas","estado","no_cuentan","permitir_exceso","juntar"].includes(g))throw i(`${s}: clave no admitida \xAB${g.slice(0,40)}\xBB.`);let l=Wo(r.clave,`${s}.clave`);if(t.has(l))throw i(`${s}: \xABclave\xBB repetida.`);if(l==="juntar")throw i(`${s}: \xABjuntar\xBB no vale como clave.`);if(t.add(l),typeof r.nombre!="string"||!r.nombre.trim()||r.nombre.length>60)throw i(`${s}: el nombre del bot\xF3n (1\u201360).`);if(typeof r.destino!="string"||!/^mod_(?!sub_)[a-z][a-z0-9_]{0,40}$/.test(r.destino))throw i(`${s}: \xABdestino\xBB, mod_<clave>.`);if(!_t(r.lineas))throw i(`${s}: \xABlineas\xBB {desde, a, cantidad: {origen, destino}}.`);let d=r.lineas,u=Wo(d.desde,`${s}.lineas.desde`),p=cw(o,u);if(!p)throw i(`${s}: \xAB${u}\xBB no es una subtabla de este m\xF3dulo.`);if(!_t(d.cantidad))throw i(`${s}: \xABlineas.cantidad\xBB {origen, destino}.`);let f=Wo(d.cantidad.origen,`${s}.lineas.cantidad.origen`),h=(p.columnas??[]).find(g=>g.clave===f&&!g.archivado);if(!h||!(sw.includes(h.tipo)||h.tipo==="formula"&&h.origen?.tipo==="numero"))throw i(`${s}: la cantidad \xAB${f}\xBB tiene que ser una columna num\xE9rica de \xAB${u}\xBB.`);let b={clave:l,nombre:r.nombre.trim(),destino:r.destino,enlace:Wo(r.enlace,`${s}.enlace`),lineas:{desde:u,a:Wo(d.a,`${s}.lineas.a`),cantidad:{origen:f,destino:Wo(d.cantidad.destino,`${s}.lineas.cantidad.destino`)}}},y=Jm(d.campos,`${s}.lineas.campos`);if(y){for(let g of Object.values(y))if(!(p.columnas??[]).some(N=>N.clave===g&&!N.archivado))throw i(`${s}: \xAB${g}\xBB no es una columna de \xAB${u}\xBB.`);b.lineas.campos=y}let w=Jm(r.campos,`${s}.campos`);if(w){for(let g of Object.values(w))if(!o.some(N=>N.clave===g&&!N.archivado))throw i(`${s}: \xAB${g}\xBB no es un campo de este m\xF3dulo.`);b.campos=w}if(r.estado!==void 0&&r.estado!==null){let g=r.estado;if(!_t(g))throw i(`${s}: \xABestado\xBB {campo, parcial, completo, pendiente?}.`);let N=o.find(S=>S.clave===g.campo&&S.tipo==="seleccion"&&!S.archivado);if(!N)throw i(`${s}: \xABestado.campo\xBB tiene que ser una selecci\xF3n de este m\xF3dulo.`);let C=new Set((N.opciones??[]).map(S=>S.valor));for(let S of["parcial","completo","pendiente"]){let T=g[S];if(!(T===void 0&&S==="pendiente")&&(typeof T!="string"||!C.has(T)))throw i(`${s}: \xABestado.${S}\xBB tiene que ser una opci\xF3n de \xAB${N.etiqueta}\xBB.`)}b.estado={campo:N.clave,parcial:g.parcial,completo:g.completo,...typeof g.pendiente=="string"?{pendiente:g.pendiente}:{}}}if(r.no_cuentan!==void 0&&r.no_cuentan!==null){let g=r.no_cuentan;if(!_t(g)||!Array.isArray(g.valores)||g.valores.length>20||!g.valores.every(N=>typeof N=="string"&&N.length<=60))throw i(`${s}: \xABno_cuentan\xBB {campo, valores}.`);b.no_cuentan={campo:Wo(g.campo,`${s}.no_cuentan.campo`),valores:g.valores}}if(r.permitir_exceso===!0&&(b.permitir_exceso=!0),r.juntar!==void 0&&r.juntar!==null&&r.juntar!==!1){let g=r.juntar===!0?{}:r.juntar;if(!_t(g))throw i(`${s}: \xABjuntar\xBB {iguales?, enlace_varios?}.`);for(let C of Object.keys(g))if(!["iguales","enlace_varios"].includes(C))throw i(`${s}: \xABjuntar\xBB: clave no admitida \xAB${C.slice(0,40)}\xBB.`);let N=g.iguales===void 0?[]:g.iguales;if(!Array.isArray(N)||N.length>10||!N.every(C=>typeof C=="string"&&o.some(S=>S.clave===C&&!S.archivado)))throw i(`${s}: \xABjuntar.iguales\xBB, campos de este m\xF3dulo (hasta 10).`);b.juntar={...N.length?{iguales:N}:{},...g.enlace_varios?{enlace_varios:Wo(g.enlace_varios,`${s}.juntar.enlace_varios`)}:{}}}return b});return n.length?n:void 0}var Vm,Cs,sw,_t,Jm,Wo,cw,Gm=m(()=>{q();Vm=5,Cs=/^[a-z][a-z0-9_]{0,40}$/,sw=["numero","importe","duracion","porcentaje"],_t=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Jm=(e,o)=>{if(e!=null){if(!_t(e)||Object.keys(e).length>60)throw i(`${o}: un objeto destino \u2192 origen.`);for(let[t,n]of Object.entries(e))if(!Cs.test(t)||typeof n!="string"||!Cs.test(n))throw i(`${o}: \xAB${t.slice(0,40)}\xBB no es v\xE1lido.`);return e}},Wo=(e,o)=>{if(typeof e!="string"||!Cs.test(e))throw i(`${o}: falta o no es v\xE1lido.`);return e},cw=(e,o)=>e.find(t=>t.clave===o&&t.tipo==="subtabla"&&!t.archivado)});function Xm(e,o){if(e==null)return;if(!co(e))throw i("\xABpertenencia\xBB: un objeto.");let t=(n,r,a,s=!1)=>{let l=o.find(d=>d.clave===n&&!d.archivado);if(!l||!r.includes(l.tipo)||s&&l.multiple)throw i(`\xABpertenencia.${a}\xBB: ${r.join(" o ")}${s?" simple":""} de este m\xF3dulo.`);return l.clave};return{demanda:t(e.demanda,["relacion"],"demanda",!0),oferta:t(e.oferta,["relacion"],"oferta",!0),desde:t(e.desde,["fecha"],"desde"),...e.hasta?{hasta:t(e.hasta,["fecha"],"hasta")}:{},...e.correccion_dias!==void 0&&e.correccion_dias!==null?{correccion_dias:lw(e.correccion_dias)}:{}}}function Ym(e,o){if(e==null)return;if(!co(e))throw i("\xABasignacion\xBB: un objeto.");if(typeof e.oferta!="string"||!ui.test(e.oferta))throw i("\xABasignacion.oferta\xBB: la clave del m\xF3dulo de la oferta.");let t=e.destino,n;if(co(t)&&t.forma==="pertenencia"&&typeof t.modulo=="string"&&ui.test(t.modulo))n={forma:"pertenencia",modulo:t.modulo};else if(co(t)&&t.forma==="relacion"){let r=o.find(a=>a.clave===t.campo&&!a.archivado);if(r?.tipo!=="relacion"||r.multiple||r.relacion!==`mod_${e.oferta}`)throw i("\xABasignacion.destino.campo\xBB: una relaci\xF3n simple de este m\xF3dulo a la oferta.");n={forma:"relacion",campo:r.clave}}else throw i("\xABasignacion.destino\xBB: {forma: \xABpertenencia\xBB, modulo} o {forma: \xABrelacion\xBB, campo}.");if(typeof e.cupo!="string"||!ui.test(e.cupo))throw i("\xABasignacion.cupo\xBB: un campo num\xE9rico de la oferta.");return{oferta:e.oferta,destino:n,...dw({...e,cupo_fijo:void 0},o),cupo:e.cupo}}function dw(e,o,t=!1){let n=(p,f,h)=>{let b=o.find(y=>y.clave===p&&!y.archivado);if(!b||h&&!h.includes(b.tipo))throw i(`\xABasignacion\xBB: ${f}, ${h?h.join(" o "):"un campo"} de este m\xF3dulo.`);return b.clave},r=(p,f)=>{if(t){if(typeof p!="string"||!/^[a-z][a-z0-9_]{0,40}(\.[a-z][a-z0-9_]{0,40}){0,3}$/.test(p))throw i(`${f}: campo de oferta no v\xE1lido.`);return p}return uw(p,f)},a=t?Hm:ui,s=t&&e.cupo_fijo!==void 0;if(s?e.cupo!==void 0||!Number.isInteger(e.cupo_fijo)||Number(e.cupo_fijo)<1||Number(e.cupo_fijo)>1e4:typeof e.cupo!="string"||!a.test(e.cupo))throw i("\xABasignacion.cupo\xBB: un n\xFAmero de la oferta o un cupo fijo de 1 a 10000.");let l={...s?{cupo_fijo:Number(e.cupo_fijo)}:{cupo:e.cupo},filtros:[],puntos:[]};if(e.orden!==void 0&&e.orden!==null){let p=e.orden;if(!co(p))throw i("\xABasignacion.orden\xBB: {campo, sentido}.");l.orden={campo:p.campo==="numero"?"numero":n(p.campo,"\xABorden.campo\xBB"),...p.sentido==="desc"?{sentido:"desc"}:{}}}if(e.plazas_por!==void 0&&e.plazas_por!==null){let p=e.plazas_por;if(!co(p)||typeof p.oferta!="string"||!a.test(p.oferta))throw i("\xABasignacion.plazas_por\xBB: {demanda (selecci\xF3n m\xFAltiple), oferta (su campo)}.");l.plazas_por={demanda:n(p.demanda,"\xABplazas_por.demanda\xBB",["seleccion_multiple","seleccion"]),oferta:p.oferta}}e.inicio&&(l.inicio=n(e.inicio,"\xABinicio\xBB",["fecha"]));let d=Array.isArray(e.filtros)?e.filtros:[],u=Array.isArray(e.puntos)?e.puntos:[];if(d.length>li||u.length>li)throw i(`\xABasignacion\xBB: hasta ${li} filtros y ${li} puntos.`);if(l.filtros=d.map((p,f)=>{let h=`Filtro ${f+1}`;if(!co(p))throw i(`${h}: un objeto.`);if(p.tipo==="igual"||p.tipo==="contiene")return{tipo:p.tipo,demanda:n(p.demanda,`${h}, \xABdemanda\xBB`),oferta:r(p.oferta,h)};if(p.tipo==="entre")return{tipo:"entre",demanda:n(p.demanda,`${h}, \xABdemanda\xBB`,["numero","importe","porcentaje","fecha","hora"]),min:r(p.min,h),max:r(p.max,h)};throw i(`${h}: \xABtipo\xBB igual, contiene o entre.`)}),l.puntos=u.map((p,f)=>{let h=`Punto ${f+1}`;if(!co(p))throw i(`${h}: un objeto.`);switch(p.tipo){case"base":case"carga":return{tipo:p.tipo,peso:Nt(p.peso,h)};case"dentro":return{tipo:"dentro",demanda:n(p.demanda,`${h}, \xABdemanda\xBB`,["hora","numero","fecha","fecha_hora"]),desde:r(p.desde,h),hasta:r(p.hasta,h),peso:Nt(p.peso,h)};case"igual":case"contiene":return{tipo:p.tipo,demanda:n(p.demanda,`${h}, \xABdemanda\xBB`),oferta:r(p.oferta,h),peso:Nt(p.peso,h)};case"junto":{let b=o.find(w=>w.clave===p.relacion&&!w.archivado);if(b?.tipo!=="relacion")throw i(`${h}: \xABrelacion\xBB, una relaci\xF3n de este m\xF3dulo con otras demandas (los hermanos).`);let y=p.mismo_campo;return{tipo:"junto",relacion:b.clave,misma:Nt(p.misma,h),...co(y)?{mismo_campo:{oferta:r(y.oferta,h),peso:Nt(y.peso,h)}}:{},...p.mismo_valor!==void 0?{mismo_valor:Nt(p.mismo_valor,h)}:{}}}case"si_no":if(typeof p.contiene!="string"||!p.contiene||p.contiene.length>100)throw i(`${h}: \xABcontiene\xBB, el valor que la oferta deber\xEDa tener.`);return{tipo:"si_no",demanda:n(p.demanda,`${h}, \xABdemanda\xBB`,["booleano"]),oferta:r(p.oferta,h),contiene:p.contiene,peso:Nt(p.peso,h)};default:throw i(`${h}: \xABtipo\xBB base, carga, dentro, igual, contiene, junto o si_no.`)}}),e.cercania!==void 0&&e.cercania!==null){let p=e.cercania;if(!co(p))throw i("\xABasignacion.cercania\xBB: {demanda, oferta}.");l.cercania={demanda:n(p.demanda,"\xABcercania.demanda\xBB",["hora","numero","fecha","fecha_hora"]),oferta:r(p.oferta,"\xABcercania\xBB")}}return l}var co,ui,Hm,li,lw,Nt,uw,Km=m(()=>{q();co=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ui=/^[a-z][a-z0-9_]{0,40}$/,Hm=/^[a-z][a-z0-9_]{0,40}(\.[a-z][a-z0-9_]{0,40})?$/,li=20,lw=e=>{let o=Number(e);if(!Number.isInteger(o)||o<0||o>60)throw i("\xABpertenencia.correccion_dias\xBB: un entero de 0 a 60.");return o};Nt=(e,o)=>{let t=Number(e);if(!Number.isFinite(t)||Math.abs(t)>1e4)throw i(`${o}: \xABpeso\xBB, un n\xFAmero (\xB110 000).`);return t},uw=(e,o)=>{if(typeof e!="string"||!Hm.test(e))throw i(`${o}: un campo de la oferta (\xABcampo\xBB o \xABrelacion.campo\xBB).`);return e}});var Os,Zm=m(()=>{Os=["nada","recientes","vistas"]});function tf(e,o){if(de(e))return;if(!lo(e))throw i("\xABstock\xBB: un objeto {articulo?, ubicacion?, movimiento?}.");Bo(e,["articulo","ubicacion","movimiento","reponer"],"stock");let t=s=>o.find(l=>l.clave===s&&!l.archivado),n=(s,l,d,u)=>{let p=t(s);if(!p||!d(p))throw i(`\xABstock.${l}\xBB: ${u} de este m\xF3dulo.`);return p.clave},r=s=>s.tipo==="relacion"&&!s.multiple&&!!s.relacion?.startsWith("mod_"),a={};if(!de(e.articulo)){let s=e.articulo;if(!lo(s))throw i("\xABstock.articulo\xBB: un objeto.");Bo(s,["minimo","reponer","proveedor","permitir_negativo","lotes"],"stock.articulo");let l={};if(de(s.minimo)||(l.minimo=n(s.minimo,"articulo.minimo",d=>d.tipo==="numero","un n\xFAmero")),de(s.reponer)||(l.reponer=n(s.reponer,"articulo.reponer",d=>d.tipo==="numero","un n\xFAmero")),de(s.proveedor)||(l.proveedor=n(s.proveedor,"articulo.proveedor",d=>r(d)||d.tipo==="relacion"&&!d.multiple&&["contacts","companies"].includes(d.relacion??""),"una relaci\xF3n simple a un proveedor")),s.permitir_negativo===!0)l.permitir_negativo=!0;else if(typeof s.permitir_negativo=="string"&&s.permitir_negativo)l.permitir_negativo=n(s.permitir_negativo,"articulo.permitir_negativo",d=>d.tipo==="booleano","un s\xED/no");else if(!de(s.permitir_negativo)&&s.permitir_negativo!==!1)throw i("\xABstock.articulo.permitir_negativo\xBB: true o un s\xED/no del art\xEDculo.");if(!de(s.lotes)){if(s.lotes!=="lote"&&s.lotes!=="serie")throw i("\xABstock.articulo.lotes\xBB: lote o serie.");if(l.permitir_negativo)throw i("\xABstock.articulo\xBB: con lotes o series no se admiten negativos.");l.lotes=s.lotes}a.articulo=l}if(!de(e.ubicacion)){let s=e.ubicacion;if(!lo(s))throw i("\xABstock.ubicacion\xBB: un objeto.");Bo(s,["almacen"],"stock.ubicacion"),a.ubicacion=de(s.almacen)?{}:{almacen:n(s.almacen,"ubicacion.almacen",r,"una relaci\xF3n simple a otro m\xF3dulo")}}if(!de(e.movimiento)){let s=e.movimiento;if(!lo(s))throw i("\xABstock.movimiento\xBB: un objeto.");if(Bo(s,["tipo","lineas","ubicacion","ubicacion_destino","cuando"],"stock.movimiento"),!ef.includes(s.tipo))throw i(`\xABstock.movimiento.tipo\xBB: ${ef.join(", ")}.`);if(!lo(s.lineas))throw i("\xABstock.movimiento.lineas\xBB: {subtabla, articulo, cantidad, ubicacion?, coste?}.");let l=s.lineas;Bo(l,["subtabla","articulo","cantidad","ubicacion","ubicacion_destino","coste","lote","caducidad"],"stock.movimiento.lineas");let d=t(l.subtabla);if(d?.tipo!=="subtabla")throw i("\xABstock.movimiento.lineas.subtabla\xBB: una subtabla de este m\xF3dulo.");let u=(d.columnas??[]).filter(w=>!w.archivado),p=(w,g,N,C)=>{let S=u.find(T=>T.clave===w);if(!S||!N(S))throw i(`\xABstock.movimiento.lineas.${g}\xBB: ${C} de \xAB${d.etiqueta}\xBB.`);return S.clave},f={tipo:s.tipo,lineas:{subtabla:d.clave,articulo:p(l.articulo,"articulo",r,"la columna de producto (una relaci\xF3n simple)"),cantidad:p(l.cantidad,"cantidad",w=>of.includes(w.tipo),"una columna num\xE9rica")},cuando:{campo:"",valores:[]}};if(de(l.ubicacion)||(f.lineas.ubicacion=p(l.ubicacion,"ubicacion",r,"una relaci\xF3n simple")),de(l.coste)||(f.lineas.coste=p(l.coste,"coste",w=>of.includes(w.tipo),"una columna num\xE9rica")),de(l.lote)||(f.lineas.lote=p(l.lote,"lote",w=>w.tipo==="texto"||w.tipo==="codigo","una columna de texto")),de(l.caducidad)||(f.lineas.caducidad=p(l.caducidad,"caducidad",w=>w.tipo==="fecha","una columna de fecha")),de(s.ubicacion)||(f.ubicacion=n(s.ubicacion,"movimiento.ubicacion",r,"una relaci\xF3n simple")),!f.lineas.ubicacion&&!f.ubicacion)throw i("\xABstock.movimiento\xBB: la ubicaci\xF3n, en la l\xEDnea (\xABlineas.ubicacion\xBB) o en el documento (\xABubicacion\xBB).");if(de(l.ubicacion_destino)||(f.lineas.ubicacion_destino=p(l.ubicacion_destino,"ubicacion_destino",r,"una relaci\xF3n simple")),de(s.ubicacion_destino)||(f.ubicacion_destino=n(s.ubicacion_destino,"movimiento.ubicacion_destino",r,"una relaci\xF3n simple")),f.tipo==="traspaso"&&!f.lineas.ubicacion_destino&&!f.ubicacion_destino)throw i("\xABstock.movimiento\xBB: un traspaso necesita la ubicaci\xF3n de destino, en la l\xEDnea (\xABlineas.ubicacion_destino\xBB) o en el documento (\xABubicacion_destino\xBB).");if(f.tipo!=="traspaso"&&(f.lineas.ubicacion_destino||f.ubicacion_destino))throw i("\xABstock.movimiento\xBB: la ubicaci\xF3n de destino es solo de un traspaso.");if(!lo(s.cuando))throw i("\xABstock.movimiento.cuando\xBB: {campo, valor} o {campo, valores}.");Bo(s.cuando,["campo","valor","valores"],"stock.movimiento.cuando");let h=t(s.cuando.campo);if(h?.tipo!=="seleccion")throw i("\xABstock.movimiento.cuando.campo\xBB: una selecci\xF3n de este m\xF3dulo.");let b=Array.isArray(s.cuando.valores)?s.cuando.valores:[s.cuando.valor],y=new Set((h.opciones??[]).map(w=>w.valor));if(!b.length||b.length>20||!b.every(w=>typeof w=="string"&&y.has(w)))throw i(`\xABstock.movimiento.cuando\xBB: opciones de \xAB${h.etiqueta}\xBB.`);f.cuando={campo:h.clave,valores:[...new Set(b)]},a.movimiento=f}if(!de(e.reponer)){let s=e.reponer;if(!lo(s))throw i("\xABstock.reponer\xBB: {destino, proveedor, lineas: {subtabla, articulo, cantidad}, estado?}.");if(Bo(s,["destino","proveedor","lineas","estado","en_camino"],"stock.reponer"),!a.articulo?.minimo||!a.articulo.reponer||!a.articulo.proveedor)throw i("\xABstock.reponer\xBB: el art\xEDculo necesita su m\xEDnimo, su \xABreponer hasta\xBB y su proveedor.");if(typeof s.destino!="string"||!/^mod_(?!sub_)[a-z][a-z_]{1,30}$/.test(s.destino))throw i("\xABstock.reponer.destino\xBB: mod_<clave> del m\xF3dulo de compras.");if(typeof s.proveedor!="string"||!Ss.test(s.proveedor))throw i("\xABstock.reponer.proveedor\xBB: la relaci\xF3n de las compras al proveedor.");if(!lo(s.lineas))throw i("\xABstock.reponer.lineas\xBB: {subtabla, articulo, cantidad}.");Bo(s.lineas,["subtabla","articulo","cantidad"],"stock.reponer.lineas");for(let d of["subtabla","articulo","cantidad"])if(typeof s.lineas[d]!="string"||!Ss.test(s.lineas[d]))throw i(`\xABstock.reponer.lineas.${d}\xBB: falta o no es v\xE1lida.`);let l={destino:s.destino,proveedor:s.proveedor,lineas:{subtabla:s.lineas.subtabla,articulo:s.lineas.articulo,cantidad:s.lineas.cantidad}};if(!de(s.estado)){if(!lo(s.estado)||typeof s.estado.campo!="string"||typeof s.estado.valor!="string")throw i("\xABstock.reponer.estado\xBB: {campo, valor}.");l.estado={campo:s.estado.campo,valor:s.estado.valor}}if(!de(s.en_camino)){let d=s.en_camino;if(!lo(d)||typeof d.campo!="string"||!Ss.test(d.campo)||!Array.isArray(d.valores)||!d.valores.length||d.valores.length>20||!d.valores.every(u=>typeof u=="string"&&u.length<=80))throw i("\xABstock.reponer.en_camino\xBB: {campo, valores} (los estados de la compra pedida y a\xFAn no recibida).");l.en_camino={campo:d.campo,valores:[...new Set(d.valores)]}}a.reponer=l}return Object.keys(a).length?a:void 0}var ef,lo,Bo,of,de,Ss,rf=m(()=>{q();ef=["entrada","salida","ajuste","traspaso","recuento","reserva"],lo=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Bo=(e,o,t)=>{for(let n of Object.keys(e))if(!o.includes(n))throw i(`\xAB${t}\xBB: clave no admitida \xAB${n.slice(0,40)}\xBB.`)},of=["numero","importe","duracion","porcentaje"],de=e=>e==null||e==="";Ss=/^[a-z][a-z0-9_]{0,40}$/});function mw(e,o){let t=`liquidacion.reglas[${o}]`;if(!Uo(e))throw i(`\xAB${t}\xBB: un objeto.`);if(Vo(e,["nombre","si","calculo","valor","tramos"],t),typeof e.nombre!="string"||!e.nombre.trim()||e.nombre.length>60)throw i(`\xAB${t}.nombre\xBB: de 1 a 60 caracteres.`);if(e.calculo!=="porcentaje"&&e.calculo!=="fijo")throw i(`\xAB${t}.calculo\xBB: porcentaje o fijo.`);let n={nombre:e.nombre.trim(),calculo:e.calculo};if($t(e.si)||(n.si=sf(e.si,`${t}.si`)),$t(e.tramos))n.valor=Es(e.valor,`${t}.valor`);else{let r=e.tramos;if(!Uo(r))throw i(`\xAB${t}.tramos\xBB: {por, lista}.`);if(Vo(r,["por","modo","lista"],`${t}.tramos`),r.por!=="acumulado"&&r.por!=="importe")throw i(`\xAB${t}.tramos.por\xBB: acumulado o importe.`);if(r.modo!==void 0&&r.modo!==null&&r.modo!=="marginal"&&r.modo!=="alcanzado")throw i(`\xAB${t}.tramos.modo\xBB: marginal o alcanzado.`);if(!Array.isArray(r.lista)||!r.lista.length||r.lista.length>af)throw i(`\xAB${t}.tramos.lista\xBB: de 1 a ${af} tramos {desde, valor}.`);let a=r.lista.map((s,l)=>{if(!Uo(s))throw i(`\xAB${t}.tramos.lista[${l}]\xBB: {desde, valor}.`);return Vo(s,["desde","valor"],`${t}.tramos.lista[${l}]`),{desde:Es(s.desde,`${t}.tramos.lista[${l}].desde`,0),valor:Es(s.valor,`${t}.tramos.lista[${l}].valor`)}}).sort((s,l)=>s.desde-l.desde);if(a[0].desde!==0)throw i(`\xAB${t}.tramos\xBB: el primer tramo empieza en 0.`);if(new Set(a.map(s=>s.desde)).size!==a.length)throw i(`\xAB${t}.tramos\xBB: dos tramos con el mismo \xABdesde\xBB.`);if(n.tramos={por:r.por,modo:r.modo==="alcanzado"?"alcanzado":"marginal",lista:a},!$t(e.valor))throw i(`\xAB${t}\xBB: con tramos, el valor va en cada tramo.`)}return n}function cf(e,o){if($t(e))return;if(!Uo(e))throw i("\xABliquidacion\xBB: un objeto {origen, importe, fecha, agente, campos, estados, lineas, reglas}.");if(Vo(e,["origen","importe","fecha","agente","cuentan","campos","estados","lineas","reglas"],"liquidacion"),typeof e.origen!="string"||!/^mod_(?!sub_)[a-z][a-z0-9_]{0,40}$/.test(e.origen))throw i("\xABliquidacion.origen\xBB: mod_<clave> del m\xF3dulo de origen.");let t=e.agente==="_dueno"?"_dueno":di(e.agente,"liquidacion.agente"),n=N=>o.find(C=>C.clave===N&&!C.archivado),r=(N,C,S,T)=>{let Y=n(N);if(!Y||!S(Y))throw i(`\xABliquidacion.${C}\xBB: ${T} de este m\xF3dulo.`);return Y.clave},a=N=>N.tipo==="relacion"&&!N.multiple&&!!N.relacion?.startsWith("mod_"),s=N=>a(N)||N.tipo==="relacion"&&!N.multiple&&["contacts","companies"].includes(N.relacion??"");if(!Uo(e.campos))throw i("\xABliquidacion.campos\xBB: {agente?, periodo, estado, total}.");Vo(e.campos,["agente","periodo","estado","total"],"liquidacion.campos");let l={periodo:r(e.campos.periodo,"campos.periodo",N=>N.tipo==="texto","un texto"),estado:r(e.campos.estado,"campos.estado",N=>N.tipo==="seleccion","una selecci\xF3n"),total:r(e.campos.total,"campos.total",N=>As.includes(N.tipo),"un n\xFAmero o importe")};if($t(e.campos.agente)||(l.agente=r(e.campos.agente,"campos.agente",s,"una relaci\xF3n simple")),t!=="_dueno"&&!l.agente)throw i("\xABliquidacion.campos.agente\xBB: con el agente en una relaci\xF3n del origen, la relaci\xF3n de aqu\xED al mismo m\xF3dulo.");let d=n(l.estado),u=new Set((d.opciones??[]).map(N=>N.valor));if(!Uo(e.estados))throw i("\xABliquidacion.estados\xBB: {borrador, aprobada, cerrada, pagada} con opciones de su selecci\xF3n.");Vo(e.estados,[...js],"liquidacion.estados");let p={};for(let N of js){let C=e.estados[N];if(typeof C!="string"||!u.has(C))throw i(`\xABliquidacion.estados.${N}\xBB: una opci\xF3n de \xAB${d.etiqueta}\xBB.`);p[N]=C}if(new Set(Object.values(p)).size!==js.length)throw i("\xABliquidacion.estados\xBB: una opci\xF3n distinta para cada estado.");if(!Uo(e.lineas))throw i("\xABliquidacion.lineas\xBB: {subtabla, origen, base, comision, regla?}.");Vo(e.lineas,["subtabla","origen","base","comision","regla"],"liquidacion.lineas");let f=n(e.lineas.subtabla);if(f?.tipo!=="subtabla")throw i("\xABliquidacion.lineas.subtabla\xBB: una subtabla de este m\xF3dulo.");let h=(f.columnas??[]).filter(N=>!N.archivado),b=(N,C,S,T)=>{let Y=h.find($=>$.clave===N);if(!Y||!S(Y))throw i(`\xABliquidacion.lineas.${C}\xBB: ${T} de \xAB${f.etiqueta}\xBB.`);return Y.clave},y={subtabla:f.clave,origen:b(e.lineas.origen,"origen",N=>a(N)&&N.relacion===e.origen,`la relaci\xF3n simple a ${String(e.origen)}`),base:b(e.lineas.base,"base",N=>As.includes(N.tipo),"una columna num\xE9rica"),comision:b(e.lineas.comision,"comision",N=>As.includes(N.tipo),"una columna num\xE9rica")};if($t(e.lineas.regla)||(y.regla=b(e.lineas.regla,"regla",N=>N.tipo==="texto","una columna de texto")),!Array.isArray(e.reglas)||!e.reglas.length||e.reglas.length>nf)throw i(`\xABliquidacion.reglas\xBB: de 1 a ${nf}.`);let w=e.reglas.map(mw),g={origen:e.origen,importe:di(e.importe,"liquidacion.importe"),fecha:di(e.fecha,"liquidacion.fecha"),agente:t,campos:l,estados:p,lineas:y,reglas:w};return $t(e.cuentan)||(g.cuentan=sf(e.cuentan,"liquidacion.cuentan")),g}var js,nf,af,As,pw,Uo,$t,Vo,di,sf,Es,lf=m(()=>{q();js=["borrador","aprobada","cerrada","pagada"],nf=20,af=20,As=["numero","importe","porcentaje"],pw=/^[a-z][a-z0-9_]{0,40}$/,Uo=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),$t=e=>e==null||e==="",Vo=(e,o,t)=>{for(let n of Object.keys(e))if(!o.includes(n))throw i(`\xAB${t}\xBB: clave no admitida \xAB${n.slice(0,40)}\xBB.`)},di=(e,o)=>{if(typeof e!="string"||!pw.test(e))throw i(`\xAB${o}\xBB: falta o no es v\xE1lido.`);return e},sf=(e,o)=>{if(!Uo(e))throw i(`\xAB${o}\xBB: {campo, valores}.`);if(Vo(e,["campo","valores"],o),!Array.isArray(e.valores)||!e.valores.length||e.valores.length>20||!e.valores.every(t=>typeof t=="string"&&t.length<=60))throw i(`\xAB${o}.valores\xBB: de 1 a 20 opciones.`);return{campo:di(e.campo,`${o}.campo`),valores:[...new Set(e.valores)]}},Es=(e,o,t=-1e12)=>{if(typeof e!="number"||!Number.isFinite(e)||e<t||e>1e12)throw i(`\xAB${o}\xBB: un n\xFAmero.`);return e}});function uf(e,o){if(e==null)return;if(!pi(e))throw i("\xABpublico\xBB: un objeto.");for(let r of Object.keys(e))if(!["campos","titulo","acciones","caducaDias"].includes(r))throw i(`\xABpublico\xBB: clave no admitida \xAB${r.slice(0,40)}\xBB.`);let t=r=>o.find(a=>a.clave===r&&!a.archivado);if(!Array.isArray(e.campos)||!e.campos.length||e.campos.length>20)throw i("\xABpublico.campos\xBB: de 1 a 20 campos.");for(let r of e.campos){let a=t(r);if(!a)throw i(`\xABpublico\xBB: \xAB${String(r).slice(0,40)}\xBB no es un campo del m\xF3dulo.`);if(hw.includes(a.tipo))throw i(`\xABpublico\xBB: \xAB${a.etiqueta}\xBB no se ense\xF1a en una p\xE1gina p\xFAblica.`)}let n={campos:[...new Set(e.campos)]};if(e.titulo!==void 0&&e.titulo!==null&&e.titulo!==""){let r=t(e.titulo);if(r?.tipo!=="texto"&&r?.tipo!=="autonumero")throw i("\xABpublico.titulo\xBB: un texto del m\xF3dulo.");n.titulo=r.clave}if(e.caducaDias!==void 0){let r=Number(e.caducaDias);if(!Number.isInteger(r)||r<1||r>180)throw i("\xABpublico.caducaDias\xBB: de 1 a 180.");n.caducaDias=r}if(e.acciones!==void 0){if(!Array.isArray(e.acciones)||e.acciones.length>3)throw i("\xABpublico.acciones\xBB: hasta 3.");let r=new Set;if(n.acciones=e.acciones.map((a,s)=>{let l=`Acci\xF3n p\xFAblica ${s+1}`;if(!pi(a)||typeof a.clave!="string"||!fw.test(a.clave)||r.has(a.clave))throw i(`${l}: \xABclave\xBB (min\xFAsculas y _), sin repetir.`);if(r.add(a.clave),typeof a.etiqueta!="string"||!a.etiqueta.trim()||a.etiqueta.length>60)throw i(`${l}: el texto del bot\xF3n (1\u201360).`);let d={clave:a.clave,etiqueta:a.etiqueta.trim(),...a.una_vez===!0?{una_vez:!0}:{}};if(a.campo!==void 0&&a.campo!==null&&a.campo!==""){let u=t(a.campo);if(u?.tipo==="seleccion"){let p=u.opciones?.find(f=>f.valor===a.valor);if(!p)throw i(`${l}: el valor tiene que ser una opci\xF3n de \xAB${u.etiqueta}\xBB.`);if(u.embudo&&(p.requisito||p.pide?.length||p.aprobacion))throw i(`${l}: \xAB${p.etiqueta}\xBB tiene requisito o aprobaci\xF3n: no se puede poner desde fuera.`)}else if(u?.tipo==="booleano"){if(typeof a.valor!="boolean")throw i(`${l}: el valor, s\xED o no.`)}else if(u?.tipo==="hecho"){if(a.valor!==!0)throw i(`${l}: un \xABhecho\xBB se marca (true).`)}else throw i(`${l}: el campo, una selecci\xF3n, un s\xED/no o un \xABhecho\xBB.`);d.campo=u.clave,d.valor=a.valor}if(a.lineas!==void 0&&a.lineas!==null){let u=a.lineas,p=pi(u)?t(u.subtabla):void 0,f=p?.tipo==="subtabla"?(p.columnas??[]).find(h=>h.clave===u.columna&&!h.archivado):void 0;if(f?.tipo!=="booleano")throw i(`${l}: \xABlineas\xBB, una subtabla del m\xF3dulo y una columna s\xED/no suya.`);if(!n.campos.includes(p.clave))throw i(`${l}: la subtabla de \xABlineas\xBB tiene que ense\xF1arse en la p\xE1gina.`);d.lineas={subtabla:p.clave,columna:f.clave}}if(a.firma!==void 0&&a.firma!==null&&a.firma!==!1){let u=a.firma===!0?{}:a.firma;if(!pi(u))throw i(`${l}: \xABfirma\xBB, {archivos}.`);for(let p of Object.keys(u))if(p!=="archivos")throw i(`${l}: \xABfirma\xBB, clave no admitida \xAB${p.slice(0,40)}\xBB.`);if(u.archivos!==void 0&&u.archivos!==null&&u.archivos!==""){if(t(u.archivos)?.tipo!=="archivos")throw i(`${l}: \xABfirma.archivos\xBB, un campo de archivos del m\xF3dulo (donde queda el firmado).`);d.firma={archivos:u.archivos}}else d.firma={}}if(!d.campo&&!d.lineas&&!d.firma)throw i(`${l}: un campo, unas l\xEDneas o la firma.`);return d}),n.acciones.filter(a=>a.firma).length>1)throw i("\xABpublico.acciones\xBB: solo una firma el documento.")}return n}var fw,pi,hw,df=m(()=>{q();fw=/^[a-z][a-z0-9_]{0,40}$/,pi=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),hw=["secreto","boton","firma"]});function mf(e,o){if(pf(e))return;if(!qs(e))throw i("\xABcuota\xBB: un objeto {proxima, periodicidad, hasta?}.");for(let a of Object.keys(e))if(!["proxima","periodicidad","hasta"].includes(a))throw i(`\xABcuota\xBB: clave no admitida \xAB${a.slice(0,40)}\xBB.`);let t=a=>o.find(s=>s.clave===a&&!s.archivado),n=(a,s)=>{let l=t(a);if(l?.tipo!=="fecha")throw i(`\xABcuota.${s}\xBB: una fecha de este m\xF3dulo.`);return l.clave},r={proxima:n(e.proxima,"proxima"),periodicidad:"mensual"};if(typeof e.periodicidad=="string"){if(!zr.includes(e.periodicidad))throw i(`\xABcuota.periodicidad\xBB: ${zr.join(", ")} (o {campo, valores}).`);r.periodicidad=e.periodicidad}else if(qs(e.periodicidad)){let a=e.periodicidad,s=t(a.campo);if(s?.tipo!=="seleccion")throw i("\xABcuota.periodicidad.campo\xBB: una selecci\xF3n de este m\xF3dulo.");if(!qs(a.valores)||!Object.keys(a.valores).length)throw i("\xABcuota.periodicidad.valores\xBB: {opci\xF3n: periodo}.");let l=new Set((s.opciones??[]).map(d=>d.valor));for(let[d,u]of Object.entries(a.valores)){if(!l.has(d))throw i(`\xABcuota.periodicidad.valores\xBB: \xAB${d.slice(0,40)}\xBB no es una opci\xF3n de \xAB${s.etiqueta}\xBB.`);if(!zr.includes(u))throw i(`\xABcuota.periodicidad.valores.${d.slice(0,40)}\xBB: ${zr.join(", ")}.`)}r.periodicidad={campo:s.clave,valores:a.valores}}else throw i(`\xABcuota.periodicidad\xBB: ${zr.join(", ")} o {campo, valores}.`);if(!pf(e.hasta)&&(r.hasta=n(e.hasta,"hasta"),r.hasta===r.proxima))throw i("\xABcuota.hasta\xBB: otra fecha que la pr\xF3xima.");return r}var zr,qs,pf,ff=m(()=>{q();zr=["semanal","quincenal","mensual","bimestral","trimestral","semestral","anual"],qs=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),pf=e=>e==null||e===""});function bf(e,o){if(e==null)return;if(!gf(e))throw i("\xABpapel\xBB: {tipo, campos} o null.");let t=Object.keys(e).find(l=>l!=="tipo"&&l!=="campos"&&l!=="atributos");if(t)throw i(`\xABpapel\xBB: \xAB${t}\xBB no se reconoce.`);let n=typeof e.tipo=="string"?ks[e.tipo]:void 0;if(!n||!Object.hasOwn(ks,e.tipo))throw i(`\xABpapel.tipo\xBB: uno de ${Object.keys(ks).join(", ")}.`);let r=e.campos??{};if(!gf(r))throw i("\xABpapel.campos\xBB: {campo est\xE1ndar: clave del campo}.");let a={};for(let[l,d]of Object.entries(r)){let u=Object.hasOwn(n.campos,l)?n.campos[l]:void 0;if(!u)throw i(`\xABpapel.campos\xBB: \xAB${l}\xBB no es un campo de \xAB${n.etiqueta}\xBB (${Object.keys(n.campos).join(", ")}).`);if(d==null||d==="")continue;let p=o.find(f=>f.clave===d&&!f.archivado);if(!p)throw i(`\xABpapel\xBB: ${u.etiqueta} apunta a \xAB${String(d)}\xBB, que no es un campo vivo de este m\xF3dulo.`);if(!u.tipos.includes(p.tipo))throw i(`\xABpapel\xBB: ${u.etiqueta} tiene que ser un campo de tipo ${u.tipos.join(" o ")} (\xAB${p.etiqueta}\xBB es ${p.tipo}).`);a[l]=p.clave}for(let[l,d]of Object.entries(n.campos))if(d.obligatorio&&!a[l])throw i(`\xABpapel\xBB: falta el campo de ${d.etiqueta}.`);let s=bw(n,e.atributos,o);return s?{tipo:e.tipo,campos:a,atributos:s}:{tipo:e.tipo,campos:a}}function bw(e,o,t){if(o==null)return;let n=e.atributos;if(!n)throw i(`\xABpapel.atributos\xBB: \xAB${e.etiqueta}\xBB no tiene atributos.`);if(!Array.isArray(o))throw i("\xABpapel.atributos\xBB: una lista de claves de campo.");if(o.length>n.max)throw i(`\xABpapel.atributos\xBB: como mucho ${n.max}.`);let r=[];for(let a of o){let s=typeof a=="string"?t.find(l=>l.clave===a&&!l.archivado):void 0;if(!s)throw i(`\xABpapel.atributos\xBB: \xAB${String(a)}\xBB no es un campo vivo de este m\xF3dulo.`);if(!n.tipos.includes(s.tipo))throw i(`\xABpapel.atributos\xBB: \xAB${s.etiqueta}\xBB es ${s.tipo}; vale ${n.tipos.join(", ")}.`);r.includes(s.clave)||r.push(s.clave)}return r.length?r:void 0}var hf,gw,ks,gf,wf=m(()=>{q();hf={nombre:{etiqueta:"Nombre",tipos:["texto"],obligatorio:!0},correo:{etiqueta:"Correo",tipos:["correo"]},telefono:{etiqueta:"Tel\xE9fono",tipos:["telefono"]},nif:{etiqueta:"NIF",tipos:["texto"]},direccion:{etiqueta:"Direcci\xF3n",tipos:["texto","texto_largo"]}},gw={nombre:{etiqueta:"Nombre",tipos:["texto"],obligatorio:!0},precio:{etiqueta:"Precio",tipos:["importe","numero"]},foto:{etiqueta:"Foto",tipos:["url"]},enlace:{etiqueta:"Enlace",tipos:["url"]},stock:{etiqueta:"Stock",tipos:["numero","contador"]},descripcion:{etiqueta:"Descripci\xF3n",tipos:["texto","texto_largo"]},categoria:{etiqueta:"Categor\xEDa",tipos:["seleccion","seleccion_multiple","texto"]},varianteId:{etiqueta:"Id de variante",tipos:["texto","numero"]}},ks={cerradura:{etiqueta:"Cerradura",campos:{nombre:{etiqueta:"Nombre",tipos:["texto"],obligatorio:!0},identificador:{etiqueta:"Identificador",tipos:["texto","codigo","numero"]},ubicacion:{etiqueta:"Ubicaci\xF3n",tipos:["texto"]}}},dispositivo:{etiqueta:"Dispositivo",campos:{nombre:{etiqueta:"Nombre",tipos:["texto"],obligatorio:!0},identificador:{etiqueta:"Identificador",tipos:["texto","codigo"]},canal:{etiqueta:"Canal",tipos:["numero"]}}},clientes:{etiqueta:"Clientes",campos:hf},proveedores:{etiqueta:"Proveedores",campos:hf},catalogo:{etiqueta:"Cat\xE1logo",campos:gw,atributos:{etiqueta:"Atributos",tipos:["texto","seleccion","seleccion_multiple","numero","importe","porcentaje","booleano"],max:16}},producto:{etiqueta:"Producto",campos:{nombre:{etiqueta:"Nombre",tipos:["texto"],obligatorio:!0},sku:{etiqueta:"SKU",tipos:["texto","codigo"]},precio:{etiqueta:"Precio",tipos:["numero","importe"]},existencias:{etiqueta:"Existencias",tipos:["numero","contador"]}}},pedido:{etiqueta:"Pedido",campos:{numero:{etiqueta:"N\xFAmero",tipos:["texto","codigo"]},estado:{etiqueta:"Estado",tipos:["texto","seleccion"]},total:{etiqueta:"Total",tipos:["numero","importe"]}}}},gf=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)});function Dr(e,o,t=!1){if(e!=null){if(!Array.isArray(e)||e.length>yf)throw i(`${o}: el filtro, una lista de hasta ${yf} condiciones.`);if(e.length)return e.map((n,r)=>{let a=`${o}, condici\xF3n ${r+1}`;if(typeof n!="object"||n===null||Array.isArray(n))throw i(`${a}: {campo, op, valor}.`);let s=n;for(let u of Object.keys(s))if(!["campo","op","valor"].includes(u))throw i(`${a}: clave no admitida \xAB${u.slice(0,40)}\xBB.`);if(typeof s.campo!="string"||!(Fe.test(s.campo)||t&&/^datos\.[a-z][a-z0-9_]{0,40}$/.test(s.campo)))throw i(`${a}: \xABcampo\xBB, la clave de un campo del m\xF3dulo que resume.`);if(typeof s.op!="string"||!vf.includes(s.op))throw i(`${a}: \xABop\xBB, una de ${vf.join(", ")}.`);let l=s.op;if(l==="vacio"||l==="no_vacio")return{campo:s.campo,op:l};let d=u=>typeof u=="string"&&u.length<=200||typeof u=="number"&&Number.isFinite(u)||typeof u=="boolean";if(l==="en"||l==="no_en"){if(!Array.isArray(s.valor)||!s.valor.length||s.valor.length>50||!s.valor.every(u=>d(u)&&typeof u!="boolean"))throw i(`${a}: \xAB${l}\xBB lleva una lista de valores (hasta 50).`);return{campo:s.campo,op:l,valor:s.valor}}if(!d(s.valor))throw i(`${a}: \xAB${l}\xBB lleva un valor (texto, n\xFAmero o s\xED/no).`);return{campo:s.campo,op:l,valor:s.valor}})}}function Sf(e,o=!1){if(typeof e=="string"&&(Cf.has(e)||_w.has(e)))throw i(`La clave del m\xF3dulo \xAB${e.slice(0,40)}\xBB es una palabra reservada: usa otra (p. ej. \xAB${e.slice(0,30)}_crm\xBB o un sin\xF3nimo).`);if(typeof e!="string"||!Of.test(e))throw i(`La clave del m\xF3dulo${typeof e=="string"?` \xAB${e.slice(0,40)}\xBB`:""}: min\xFAsculas y \xAB_\xBB, de 2 a 31, sin palabras reservadas.`);if(e.startsWith("sub_")!==o)throw i(o?"Clave interna no v\xE1lida.":"La clave del m\xF3dulo no puede empezar por \xABsub_\xBB.");return e}function Ms(e,o,t=!1){if(typeof e!="object"||e===null||Array.isArray(e))throw i("Definici\xF3n no v\xE1lida.");let n=e,r=Sf(n.clave,t);if(!Array.isArray(n.campos))throw i("Faltan los campos.");let a=n.campos.map((s,l)=>mi(s,l,o,r));if(a.filter(s=>s.esCodigo&&!s.archivado).length>1)throw i("Solo un campo puede ser el c\xF3digo de la ficha.");return a}function jf(e,o){if(typeof e!="object"||e===null||Array.isArray(e))throw i("Definici\xF3n no v\xE1lida.");let t=e,n=Sf(t.clave,o.interno===!0),r=Jo(t.nombre,"el nombre",60),a=Jo(t.nombre_plural??t.nombre,"el nombre en plural",60),s=Jo(t.descripcion??"","la descripci\xF3n",500,!0),l=typeof t.icono=="string"&&Ts.includes(t.icono)?t.icono:"box",d;if(t.color===null||t.color==="")d=null;else if(t.color!==void 0){if(typeof t.color!="string"||!/^#[0-9a-f]{6}$/i.test(t.color))throw i("\xABcolor\xBB: un color #rrggbb.");d=t.color.toLowerCase()}let u=_m(Ms(t,o.modulosDelEspacio,o.interno),n,o.camposRelacion);if(u.filter(k=>!k.archivado&&k.opciones?.some(D=>D.hecho)).length>1)throw i("Solo una selecci\xF3n puede marcar estados como \xABhechos\xBB.");if(u.filter(k=>!k.archivado&&k.proximaAccion).length>1)throw i("Solo una fecha puede ser la de la pr\xF3xima acci\xF3n.");let p=new Set;for(let k of u){if(p.has(k.clave))throw i(`El campo \xAB${k.clave}\xBB est\xE1 repetido.`);p.add(k.clave)}let f=u.filter(k=>!k.archivado);for(let k of f)for(let D of rs(k)){let K=f.find(Ct=>Ct.clave===D.relacion);if(!K||K.clave===k.clave||K.tipo!=="relacion"||K.multiple&&!k.multiple)throw i(`\xAB${k.etiqueta}\xBB: un origen m\xFAltiple necesita tambi\xE9n un destino m\xFAltiple.`)}if(kp(f),f.length===0)throw i("El m\xF3dulo necesita al menos un campo.");for(let k of f.filter(D=>D.tipo==="busqueda")){let D=f.find(K=>K.clave===k.desde);if(!D||D.tipo!=="relacion")throw i(`\xAB${k.etiqueta}\xBB: tiene que salir de un campo de relaci\xF3n de este m\xF3dulo.`)}for(let k of f.filter(D=>D.tipo==="qr"&&D.destino==="campo"&&D.campo))if(!f.find(K=>K.clave===k.campo))throw i(`\xAB${k.etiqueta}\xBB: el campo \xAB${k.campo}\xBB no existe en este m\xF3dulo.`);if(f.length>o.topeCampos)throw i(`Como mucho ${o.topeCampos} campos por m\xF3dulo en tu plan.`);for(let k of o.anterior??[]){let D=u.find(K=>K.clave===k.clave);if(!D)throw i(`El campo \xAB${k.etiqueta}\xBB no se quita: se archiva.`);if(D.tipo!==k.tipo&&!Aw(k.tipo,D.tipo))throw i(`\xAB${k.etiqueta}\xBB no puede pasar de ${k.tipo} a ${D.tipo}.`)}let h=t.articulo==="un"||t.articulo==="una"?t.articulo:null,b=oi(t.ficha,u),y=Mr(t.impresion,u),w=Xp(t.validaciones,u.filter(k=>!k.archivado));om(u);for(let k of u){if(k.tipo!=="contador"||!k.alMarcar)continue;let D=u.find(K=>K.clave===k.alMarcar&&!K.archivado);if(D?.tipo!=="booleano"&&D?.tipo!=="hecho")throw i(`\xAB${k.etiqueta}\xBB: \xABal marcar\xBB tiene que ser un s\xED/no o un \xABhecho\xBB de este m\xF3dulo.`)}let g=Am(t.vistas),N=Bm(t.conversiones),C=Qm(t.encadenar,u),S=vm(t.plantillas_hijos),T=Sw(t.campo_ambito,u),Y=uf(t.publico,u),$=Xn(t.recurso,u),v=Yn(t.reserva,u),A=Ym(t.asignacion,u),x=Xm(t.pertenencia,u),M=tf(t.stock,u),B=cf(t.liquidacion,u),I=pp(t.sucesion),ae=gp(t.liquidacion_v2,u);if(B&&ae)throw i("Elige una versi\xF3n de liquidaci\xF3n por m\xF3dulo.");let J=mf(t.cuota,u),ge=wp(t.precios,u),Be=ni(t.relacionadas,u),Go=ii(t.siguientes),Ho=bf(t.papel,u),G=xs(t.personas,u);if(t.portal!==void 0&&t.portal!==null&&!["suyos_ver","suyos_anadir","suyos_editar","todos_ver"].includes(t.portal))throw i("\xABportal\xBB: suyos_ver, suyos_anadir, suyos_editar o todos_ver.");let fo=t.portal??void 0,$e;if(t.portal_campos!==void 0&&t.portal_campos!==null){let k=t.portal_campos;if(!fo)throw i("\xABportal_campos\xBB va con \xABportal\xBB.");if(typeof k!="object"||Array.isArray(k)||Object.keys(k).length>u.length)throw i("\xABportal_campos\xBB: clave del campo \u2192 rellenar, ver o no.");for(let[D,K]of Object.entries(k)){if(!u.some(Ct=>Ct.clave===D))throw i(`\xABportal_campos\xBB: el m\xF3dulo no tiene el campo \xAB${D.slice(0,40)}\xBB.`);if(K!=="rellenar"&&K!=="ver"&&K!=="no")throw i(`\xABportal_campos.${D.slice(0,40)}\xBB: rellenar, ver o no.`)}$e={...k}}let De;if(t.funcionesNativas!==void 0){if(!t.funcionesNativas||typeof t.funcionesNativas!="object"||Array.isArray(t.funcionesNativas)||Object.entries(t.funcionesNativas).some(([k,D])=>!["relacionadas","siguientes"].includes(k)||!Array.isArray(D)||D.length>(k==="relacionadas"?20:5)))throw i("Las funciones nativas necesitan relacionadas o siguientes declarados.");De=structuredClone(t.funcionesNativas)}return{clave:n,nombre:r,nombre_plural:a,articulo:h,descripcion:s,icono:l,...d!==void 0?{color:d}:{},campos:hm(u).map(k=>{if(k.tipo!=="busqueda")return k;let{origen:D,...K}=k;return K}),paginas:t.paginas===!0,...b?{ficha:b}:{},...y?{impresion:y}:{},...w?{validaciones:w}:{},...g?{vistas:g}:{},...N?{conversiones:N}:{},...C?{encadenar:C}:{},...S?{plantillas_hijos:S}:{},...T?{campo_ambito:T}:{},...Y?{publico:Y}:{},...$?{recurso:$}:{},...v?{reserva:v}:{},...A?{asignacion:A}:{},...x?{pertenencia:x}:{},...M?{stock:M}:{},...B?{liquidacion:B}:{},...I?{sucesion:I}:{},...ae?{liquidacion_v2:ae}:{},...J?{cuota:J}:{},...ge?{precios:ge}:{},...Be?{relacionadas:Be}:{},...Go?{siguientes:Go}:{},...Ho?{papel:Ho}:{},...G?{personas:G}:{},...fo?{portal:fo}:{},...$e&&Object.keys($e).length?{portal_campos:$e}:{},...De?{funcionesNativas:De}:{}}}function Sw(e,o){if(e==null||e==="")return;let t=o.find(n=>n.clave===e&&!n.archivado);if(!t||!(t.tipo==="seleccion"||t.tipo==="relacion"&&!t.multiple))throw i("\xABcampo_ambito\xBB: una selecci\xF3n o una relaci\xF3n simple de este m\xF3dulo.");return t.clave}function mi(e,o,t,n){if(typeof e!="object"||e===null||Array.isArray(e))throw i(`Campo ${o+1} no v\xE1lido.`);let r=e;if(typeof r.clave=="string"&&Cf.has(r.clave))throw i(`La clave \xAB${r.clave.slice(0,40)}\xBB del campo ${o+1}${n?` de \xAB${n}\xBB`:""} es una palabra reservada: usa otra (p. ej. \xAB${r.clave.slice(0,30)}_campo\xBB o un sin\xF3nimo).`);if(typeof r.clave!="string"||!Fe.test(r.clave))throw i(`La clave del campo ${o+1}${n?` de \xAB${n}\xBB`:""}${typeof r.clave=="string"?` (\xAB${r.clave.slice(0,40)}\xBB)`:""}: min\xFAsculas, n\xFAmeros y \xAB_\xBB, sin palabras reservadas.`);let a=r.tipo;if(!Rs.includes(a))throw i(`Tipo de campo no v\xE1lido: ${String(r.tipo)}.`);let s={clave:r.clave,etiqueta:Jo(r.etiqueta,`la etiqueta del campo ${o+1}`,80),tipo:a};if(r.ajustesNativos!==void 0){if(a!=="relacion"&&a!=="busqueda")throw i("Solo las relaciones y b\xFAsquedas declaradas tienen ajustes nativos.");s.ajustesNativos=Tm(r.ajustesNativos);for(let u of Object.values(s.ajustesNativos??{})){let p={...r,...u,ajustesNativos:void 0};for(let[f,h]of Object.entries(u))h===null&&delete p[f];mi(p,o,t,n)}}for(let u of["formulaNativa","defectoNativo"])if(r[u]!==void 0){if(typeof r[u]!="string"||!r[u].trim()||r[u].length>Ye||u==="formulaNativa"&&a!=="formula")throw i("La variante nativa necesita una f\xF3rmula v\xE1lida y acotada.");s[u]=r[u]}if(r.obligatorio===!0&&(s.obligatorio=!0),s.enTabla=r.enTabla!==!1,r.sensible!==void 0&&typeof r.sensible!="boolean")throw i("\xABsensible\xBB debe ser s\xED o no.");if(r.sensible===!0&&(s.sensible=!0),r.semantica!==void 0){if(!["dato","firma","consentimiento","credencial","auditoria","financiero"].includes(String(r.semantica)))throw i("Sucesi\xF3n: configuraci\xF3n inv\xE1lida.");s.semantica=r.semantica}r.archivado===!0&&(s.archivado=!0),r.seccion!==void 0&&r.seccion!==""&&(s.seccion=Jo(r.seccion,"la secci\xF3n",60)),r.ayuda!==void 0&&r.ayuda!==""&&(s.ayuda=Jo(r.ayuda,"la ayuda",200)),(a==="fecha"||a==="fecha_hora")&&r.proximaAccion===!0&&(s.proximaAccion=!0),a==="numero"&&r.sinMiles===!0&&(s.sinMiles=!0);for(let u of["minimo","maximo"])if(r[u]!==void 0&&r[u]!==null){if(typeof r[u]!="number"||!Number.isFinite(r[u]))throw i(`\xAB${u}\xBB tiene que ser un n\xFAmero.`);s[u]=r[u]}if(a==="seleccion"||a==="seleccion_multiple"){if(!Array.isArray(r.opciones)||r.opciones.length===0||r.opciones.length>100)throw i(`\xAB${s.etiqueta}\xBB: entre 1 y 100 opciones.`);let u=new Set;s.opciones=r.opciones.map(p=>{let f=typeof p=="string"?{valor:p,etiqueta:p}:p,h=Jo(f.valor??f.etiqueta,"el valor de una opci\xF3n",80);if(u.has(h))throw i(`\xAB${s.etiqueta}\xBB: la opci\xF3n \xAB${h}\xBB est\xE1 repetida.`);u.add(h);let b={valor:h,etiqueta:Jo(f.etiqueta??h,"una opci\xF3n",80)};return typeof f.color=="string"&&Nw.test(f.color)&&(b.color=f.color),a==="seleccion"&&f.hecho===!0&&(b.hecho=!0),a==="seleccion"&&r.embudo===!0&&fm(f,b,s.etiqueta),b}),a==="seleccion"&&r.embudo===!0&&(s.embudo=!0)}if(a==="relacion"){let u=r.relacion;if(!(typeof u=="string"&&(vw.includes(u)||u.startsWith("mod_")&&(t.includes(u.slice(4))||u.slice(4)===n))))throw i(`\xAB${s.etiqueta}\xBB: relaci\xF3n con algo que no existe.`);if(s.relacion=u,r.tipoContacto!==void 0&&r.tipoContacto!==null&&r.tipoContacto!==""){if(u!=="contacts"&&u!=="companies")throw i(`\xAB${s.etiqueta}\xBB: el tipo solo vale en una relaci\xF3n con Personas o Empresas.`);if(typeof r.tipoContacto!="string"||!Ew.test(r.tipoContacto))throw i(`\xAB${s.etiqueta}\xBB: el tipo no es una clave v\xE1lida.`);s.tipoContacto=r.tipoContacto}if(r.mostrarTareasEnFichaRelacionada===!0){if(r.multiple===!0)throw i(`\xAB${s.etiqueta}\xBB: mostrar tareas relacionadas requiere una relaci\xF3n simple.`);s.mostrarTareasEnFichaRelacionada=!0}}else if(r.mostrarTareasEnFichaRelacionada===!0)throw i(`\xAB${s.etiqueta}\xBB: la opci\xF3n de tareas relacionadas solo sirve en campos de relaci\xF3n.`);if(r.completarDesde!==void 0&&r.completarDesde!==null){if(!["relacion","texto","texto_largo","numero","importe","porcentaje","correo","telefono","url","codigo","fecha","fecha_hora","booleano","seleccion","ubicacion"].includes(a))throw i("Ese tipo de campo no admite autocompletado.");let u=r.completarDesde;if(typeof u!="object"||Array.isArray(u)||Object.keys(u).some(f=>!["relacion","campo","alternativa"].includes(f))||typeof u.relacion!="string"||!Fe.test(u.relacion)||typeof u.campo!="string"||!/^[a-z][a-z0-9_.]{0,80}$/.test(u.campo))throw i(`\xAB${s.etiqueta}\xBB: completarDesde requiere relacion y campo.`);let p;if(u.alternativa!==void 0){let f=u.alternativa;if(!f||typeof f!="object"||Array.isArray(f)||Object.keys(f).some(h=>h!=="relacion"&&h!=="campo")||typeof f.relacion!="string"||!Fe.test(f.relacion)||typeof f.campo!="string"||!/^[a-z][a-z0-9_.]{0,80}$/.test(f.campo))throw i("La alternativa de autocompletado necesita relacion y campo.");p={relacion:f.relacion,campo:f.campo}}s.completarDesde={relacion:u.relacion,campo:u.campo,...p?{alternativa:p}:{}}}if(r.completarNativo!==void 0){if(a==="relacion")throw i("La relaci\xF3n conserva su autocompletado en ajustesNativos.");if(r.completarNativo===null)s.completarNativo=null;else{let u=mi({...r,completarDesde:r.completarNativo,completarNativo:void 0},o,t,n).completarDesde;if(!u)throw i("La variante de autocompletado no es v\xE1lida.");s.completarNativo=u}}if((a==="relacion"||a==="archivos")&&r.multiple===!0&&(s.multiple=!0),a==="archivos"&&r.soloImagenes===!0&&(s.soloImagenes=!0),a==="texto_largo"&&r.sinFormato===!0&&(s.sinFormato=!0),(a==="formula"||a==="resumen")&&r.formato!==void 0&&r.formato!==null&&r.formato!=="automatico"){if(r.formato!=="numero"&&r.formato!=="importe"&&r.formato!=="porcentaje")throw i(`\xAB${s.etiqueta}\xBB: el formato es autom\xE1tico, n\xFAmero, importe o porcentaje.`);s.formato=r.formato}if(a==="archivos"&&r.versiones===!0&&(s.versiones=!0),a==="secreto"&&delete s.obligatorio,a==="contador"&&typeof r.alMarcar=="string"&&r.alMarcar){if(!Fe.test(r.alMarcar))throw i(`\xAB${s.etiqueta}\xBB: \xABal marcar\xBB no es un campo v\xE1lido.`);s.alMarcar=r.alMarcar}if(a==="busqueda"){if(typeof r.desde!="string"||!Fe.test(r.desde)||typeof r.campo!="string"||!/^[a-z][a-z0-9_.]{0,80}$/.test(r.campo))throw i(`\xAB${s.etiqueta}\xBB: elige la relaci\xF3n y el campo que trae.`);if(r.siVacio!==void 0){if(typeof r.siVacio!="string"||!Fe.test(r.siVacio))throw i("La alternativa necesita otra b\xFAsqueda escalar del mismo tipo, sin cadenas.");s.siVacio=r.siVacio}s.desde=r.desde,s.campo=r.campo,delete s.obligatorio}if(a==="relacion"&&r.alBorrar!==void 0&&r.alBorrar!=="avisar"){if(!ww.includes(r.alBorrar))throw i(`\xAB${s.etiqueta}\xBB: \xABal borrar\xBB no v\xE1lido.`);s.alBorrar=r.alBorrar}if(a==="valoracion"){let u=r.maximo===void 0||r.maximo===null?5:r.maximo;if(typeof u!="number"||!Number.isInteger(u)||u<3||u>10)throw i(`\xAB${s.etiqueta}\xBB: entre 3 y 10 estrellas.`);s.maximo=u,delete s.minimo}if(a==="autonumero"){let u=typeof r.prefijo=="string"?r.prefijo.trim():"";if(!/^[A-Za-z0-9_-]{0,10}$/.test(u))throw i(`\xAB${s.etiqueta}\xBB: el prefijo, hasta 10 letras, n\xFAmeros, \xAB-\xBB o \xAB_\xBB.`);let p=r.digitos===void 0||r.digitos===null?4:r.digitos;if(typeof p!="number"||!Number.isInteger(p)||p<1||p>10)throw i(`\xAB${s.etiqueta}\xBB: de 1 a 10 d\xEDgitos.`);u&&(s.prefijo=u),s.digitos=p,r.anual===!0?s.anual=!0:delete s.anual}if(xf.includes(a)&&delete s.obligatorio,a==="subtabla"){if(!Array.isArray(r.columnas)||r.columnas.length===0||r.columnas.length>$f)throw i(`\xAB${s.etiqueta}\xBB: entre 1 y ${$f} columnas.`);let u=new Set(["padre"]);s.columnas=r.columnas.map((h,b)=>{let y=mi(h,b,t,n);if(!Ow.includes(y.tipo))throw i(`\xAB${s.etiqueta}\xBB: una columna no puede ser de tipo ${y.tipo}.`);if(u.has(y.clave))throw i(`\xAB${s.etiqueta}\xBB: la columna \xAB${y.clave}\xBB est\xE1 repetida o es reservada.`);if(u.add(y.clave),y.tipo==="subtabla"&&(y.columnas??[]).some(w=>w.tipo==="subtabla"))throw i(`\xAB${s.etiqueta}\xBB: como mucho dos niveles de subtablas (cap\xEDtulo \u2192 partidas).`);if(y.tipo==="relacion"){if(y.multiple)throw i(`\xAB${s.etiqueta}\xBB: una columna de relaci\xF3n es de un solo registro.`);if(!y.relacion?.startsWith("mod_")&&y.relacion!=="contacts"&&y.relacion!=="companies")throw i(`\xAB${s.etiqueta}\xBB: una columna de relaci\xF3n apunta a un m\xF3dulo, Persona o Empresa.`)}return y});for(let h of s.columnas)if(h.tipo==="resumen"&&!s.columnas.some(b=>b.tipo==="subtabla"&&(b.clave===h.de||!!b.hijo&&b.hijo===h.de)))throw i(`\xAB${s.etiqueta}\xBB: el total \xAB${h.etiqueta}\xBB tiene que ser de una subtabla de la l\xEDnea.`);let p=r.columnas;s.columnas=s.columnas.map((h,b)=>{let y=p[b]?.copiar;if(y==null)return h;let w=`\xAB${s.etiqueta}\xBB, columna \xAB${h.etiqueta}\xBB`;if(h.tipo!=="relacion")throw i(`${w}: \xABcopiar\xBB va en una columna de relaci\xF3n.`);if(typeof y!="object"||Array.isArray(y)||Object.keys(y).length>_f)throw i(`${w}: \xABcopiar\xBB, un objeto columna \u2192 campo (hasta ${_f}).`);for(let[g,N]of Object.entries(y)){let C=s.columnas.find(S=>S.clave===g);if(!C||C.tipo==="relacion"||C.tipo==="formula")throw i(`${w}: \xAB${g.slice(0,40)}\xBB no es una columna que se pueda rellenar.`);if(typeof N!="string"||!Fe.test(N))throw i(`${w}: el campo de \xAB${g}\xBB no es v\xE1lido.`)}return Object.keys(y).length?{...h,copiar:{...y}}:h}),s.columnas=s.columnas.map((h,b)=>{let y=p[b]?.rellenar;if(y==null)return h;let w=`\xAB${s.etiqueta}\xBB, columna \xAB${h.etiqueta}\xBB`;if(h.tipo!=="articulo")throw i(`${w}: \xABrellenar\xBB va en una columna de art\xEDculo.`);if(typeof y!="object"||Array.isArray(y)||Object.keys(y).length>Nf.length*2)throw i(`${w}: \xABrellenar\xBB, un objeto columna \u2192 dato del art\xEDculo.`);for(let[g,N]of Object.entries(y)){let C=s.columnas.find(S=>S.clave===g);if(!C||["relacion","articulo","formula","subtabla","resumen"].includes(C.tipo))throw i(`${w}: \xAB${g.slice(0,40)}\xBB no es una columna que se pueda rellenar.`);if(!Nf.includes(N))throw i(`${w}: \xAB${g.slice(0,40)}\xBB se rellena con nombre, referencia, codigo, precio o iva_pct.`)}return Object.keys(y).length?{...h,rellenar:{...y}}:h}),typeof r.hijo=="string"&&Cw.test(r.hijo)&&(s.hijo=r.hijo);let f=Sm(r.impresion,s.columnas);f&&(s.impresion=f),delete s.obligatorio}if(a==="autonumero"){let u=Kn(r.visibleSi,s.etiqueta);u&&(s.visibleSi=u)}if(!Rm({tipo:a})){let u=Kn(r.visibleSi,s.etiqueta);u&&(s.visibleSi=u);let p=Kn(r.obligatorioSi,s.etiqueta);if(p&&(s.obligatorioSi=p),r.patron!==void 0&&r.patron!==null&&r.patron!==""){if(!am.includes(a))throw i(`\xAB${s.etiqueta}\xBB: un patr\xF3n solo vale para textos, correos, tel\xE9fonos, webs y c\xF3digos.`);let h=cm(r.patron,s.etiqueta);h&&(s.patron=h)}if(r.unico===!0){if(!sm.includes(a))throw i(`\xAB${s.etiqueta}\xBB: \xAB\xFAnico\xBB solo vale para textos, correos, tel\xE9fonos, webs, c\xF3digos y n\xFAmeros.`);s.unico=!0}if(r.esCodigo===!0){if(!s.unico)throw i(`\xAB${s.etiqueta}\xBB: el c\xF3digo de la ficha tiene que ser \xFAnico.`);s.esCodigo=!0}let f=lm(r.porDefecto,s);f&&(s.porDefecto=f)}let l=Up(r.permisos,s.etiqueta);if(l&&(s.permisos=l),r.grupo!==void 0&&r.grupo!==null&&r.grupo!==""){if(typeof r.grupo!="string"||!$w.test(r.grupo))throw i(`\xAB${s.etiqueta}\xBB: el grupo, en min\xFAsculas y sin espacios (p. ej. \xABfinanzas\xBB).`);s.grupo=r.grupo}if(r.enmascarado===!0){if(!xw.includes(a))throw i(`\xAB${s.etiqueta}\xBB: solo se enmascaran textos, correos, tel\xE9fonos y c\xF3digos.`);s.enmascarado=!0}let d=em(r.depende,s);if(d&&(s.depende=d),a==="boton"){let u=r.automatizacion;if(typeof u!="number"||!Number.isSafeInteger(u)||u<=0)throw i(`\xAB${s.etiqueta}\xBB: elige la automatizaci\xF3n del bot\xF3n.`);s.automatizacion=u,s.enTabla=!1,delete s.obligatorio}if(a==="formula"){if(typeof r.formula!="string"||!r.formula.trim()||r.formula.length>Ye)throw i(`\xAB${s.etiqueta}\xBB: escribe la f\xF3rmula (hasta ${Ye} caracteres).`);s.formula=r.formula.trim(),delete s.obligatorio}if(a==="resumen"){let u=r.calculo;if(typeof r.de!="string"||!Of.test(r.de)||typeof r.via!="string"||!Fe.test(r.via)||!Ps.includes(u))throw i(`\xAB${s.etiqueta}\xBB: elige de qu\xE9 m\xF3dulo, por qu\xE9 relaci\xF3n y qu\xE9 c\xE1lculo.`);if(s.de=r.de,s.via=r.via,s.calculo=u,u!=="recuento"){if(typeof r.campo!="string"||!Fe.test(r.campo))throw i(`\xAB${s.etiqueta}\xBB: elige el campo que resume.`);s.campo=r.campo}if(u==="media_ponderada"){if(typeof r.peso!="string"||!Fe.test(r.peso))throw i(`\xAB${s.etiqueta}\xBB: elige el campo que pondera la media.`);s.peso=r.peso}else delete s.peso;let p=Dr(r.filtro,`\xAB${s.etiqueta}\xBB`);p?s.filtro=p:delete s.filtro,delete s.obligatorio}if(a==="qr"){let u=r.destino==="campo"||typeof r.campo=="string"&&r.campo&&r.destino!=="ficha"?"campo":"ficha";if(s.destino=u,u==="campo"){if(typeof r.campo!="string"||!Fe.test(r.campo))throw i(`\xAB${s.etiqueta}\xBB: elige el campo que resalta al escanear.`);s.campo=r.campo}else delete s.campo;delete s.obligatorio}return s}var Rs,xf,Ps,vf,yf,ww,vw,yw,Cf,_w,Ts,Fe,Of,Nw,$w,xw,Jo,Cw,Ow,_f,Nf,$f,jw,Aw,Ew,Rm,Lr=m(()=>{mp();bp();vp();zm();_s();Rp();q();Gn();um();Vp();gs();Yp();tm();gm();Um();Gm();ym();df();ms();Km();rf();lf();ff();ai();wf();Nm();Rs=["texto","texto_largo","numero","importe","fecha","fecha_hora","booleano","seleccion","seleccion_multiple","etiquetas","url","correo","telefono","relacion","archivos","busqueda","resumen","duracion","hecho","porcentaje","valoracion","contador","cronometro","secreto","color","ubicacion","checklist","codigo","firma","hora","articulo","creado_el","creado_por","modificado_el","modificado_por","autonumero","formula","subtabla","boton","qr"],xf=["creado_el","creado_por","modificado_el","modificado_por","autonumero"],Ps=["recuento","suma","minimo","maximo","ultimo","media","media_ponderada"],vf=["igual","distinto","en","no_en","vacio","no_vacio","mayor","menor"],yf=5;ww=["avisar","desvincular","impedir"],vw=["companies","contacts","deals"],yw=["id","numero","sales_id","creado","actualizado","espacio_id","modulo_id","datos"],Cf=new Set([...yw,"q","filter","sort","order","page","perpage","limit","offset","select","from","where","insert","update","delete","drop","table","union","join","and","or","not","null","true","false","order","group","having","into","values","create","alter","grant","revoke","truncate","exec","execute","function","user","listar","ver","crear","actualizar","borrar","enlazar","buscar","exportar","importar","confirmar","idempotencia","operacion","tools","list","call","resources","prompts","__proto__","constructor","prototype"]),_w=new Set(["companies","contacts","deals","sales","tasks","tags","notas","tareas","empresas","contactos","oportunidades","formularios","ajustes","miembros","configuracion","modulos","registros","objetos","adjuntos","api","rpc","v1","mcp"]),Ts=["box","boxes","package","folder","folder-open","file-text","clipboard-list","list-checks","calendar","calendar-days","clock","map-pin","truck","car","wrench","hammer","hard-hat","building","home","store","warehouse","factory","briefcase","shopping-cart","receipt","wallet","credit-card","piggy-bank","tag","tags","star","heart","flag","bookmark","user","users","graduation-cap","stethoscope","pill","utensils","coffee","shirt","camera","image","monitor","smartphone","server","database","key","shield","leaf","paw-print","dumbbell","ticket","gift","megaphone","mail","phone","message-square"],Fe=/^[a-z][a-z0-9_]{0,40}$/,Of=/^[a-z][a-z_]{1,30}$/,Nw=/^#[0-9a-fA-F]{6}$/,$w=/^[a-z][a-z_]{0,29}$/,xw=["texto","correo","telefono","codigo"],Jo=(e,o,t,n=!1)=>{if(typeof e!="string")throw i(`Falta ${o}.`);let r=e.trim();if(!n&&!r||r.length>t)throw i(`${o}: entre ${n?0:1} y ${t} caracteres.`);return r};Cw=/^sub_[a-z]{8}$/,Ow=["texto","texto_largo","numero","importe","fecha","fecha_hora","booleano","seleccion","url","correo","telefono","duracion","porcentaje","valoracion","color","codigo","formula","hora","relacion","articulo","subtabla","resumen"],_f=20,Nf=["nombre","referencia","codigo","precio","iva_pct"],$f=30;jw=[["texto","texto_largo"],["texto_largo","texto"],["texto","seleccion"],["seleccion","texto"],["numero","importe"],["importe","numero"],["texto","correo"],["texto","telefono"],["texto","url"],["correo","texto"],["telefono","texto"],["url","texto"],["fecha","fecha_hora"]],Aw=(e,o)=>jw.some(([t,n])=>t===e&&n===o),Ew=/^[a-z0-9][a-z0-9-]{0,59}$/;Rm=e=>e.tipo==="busqueda"||e.tipo==="resumen"||e.tipo==="formula"||e.tipo==="subtabla"||e.tipo==="boton"||e.tipo==="qr"||xf.includes(e.tipo)});function Af(e){if(!e||typeof e!="object"||Array.isArray(e))throw i("F\xF3rmula proyectada no v\xE1lida.");let o=e;if(Object.keys(o).some(a=>!["expresion","campos"].includes(a))||typeof o.expresion!="string"||o.expresion.length>2e3||!Array.isArray(o.campos)||o.campos.length>40)throw i("F\xF3rmula proyectada no v\xE1lida.");let t=["texto","texto_largo","correo","telefono","url","codigo","color","numero","importe","duracion","porcentaje","valoracion","fecha","fecha_hora","booleano","seleccion","ubicacion","formula"],n=new Set,r=o.campos.map(a=>{if(!a||typeof a!="object"||typeof a.clave!="string"||!/^[a-z][a-z0-9_]{0,40}$/.test(a.clave)||n.has(a.clave)||typeof a.etiqueta!="string"||a.etiqueta.length>80||!t.includes(a.tipo)||a.tipo==="formula"&&(typeof a.formula!="string"||a.formula.length>2e3))throw i("F\xF3rmula proyectada no v\xE1lida.");return n.add(a.clave),{clave:a.clave,etiqueta:a.etiqueta,tipo:a.tipo,...a.tipo==="formula"?{formula:a.formula}:{}}});return{expresion:o.expresion,campos:r}}var Ef=m(()=>{q()});function qf(e){if(!e||typeof e!="object"||Array.isArray(e))throw i("Resumen proyectado no v\xE1lido.");let o=e;if(Object.keys(o).some(t=>!["fuente","tipo","via","calculo","campo","peso","filtro"].includes(t))||o.tipo!==void 0&&(!["contacts","companies"].includes(o.fuente)||typeof o.tipo!="string"||!/^[a-z0-9][a-z0-9-]{0,59}$/.test(o.tipo))||typeof o.fuente!="string"||!/^(contacts|companies|deals|mod_(?!sub_)[a-z][a-z0-9_]{0,40})$/.test(o.fuente)||!Ps.includes(o.calculo)||[o.via,...o.calculo!=="recuento"?[o.campo]:[],...o.calculo==="media_ponderada"?[o.peso]:[]].some(t=>typeof t!="string"||!(/^[a-z][a-z0-9_]{0,40}$/.test(t)||["contacts","companies"].includes(o.fuente)&&/^datos\.[a-z][a-z0-9_]{0,40}$/.test(t))))throw i("Resumen proyectado no v\xE1lido.");Dr(o.filtro,"Resumen")}var kf=m(()=>{q();Lr()});function Rf(e,o){if(!Array.isArray(e)||!e.length||e.length>100||e.some(t=>!t||typeof t!="object"||Array.isArray(t)||Object.keys(t).some(n=>!["campo","es","etiqueta","valor"].includes(n))||typeof t.valor!="string"||t.valor.length>100||(t.etiqueta!==void 0?typeof t.etiqueta!="string"||!t.etiqueta||t.etiqueta.length>60||t.campo!==void 0||t.es!==void 0:typeof t.campo!="string"||!/^[a-z][a-z0-9_]{0,40}$/.test(t.campo)||typeof t.es!="string"||t.es.length>100))||o!==void 0&&(typeof o!="string"||o.length>100))throw i("Casos de proyecci\xF3n no v\xE1lidos.")}var Pf=m(()=>{q()});var Tf,Mf=m(()=>{Tf=/^funciones\.[a-z0-9][a-z0-9-]{0,59}\.[a-z][a-z0-9_]{0,40}$/});function Yt(e){if(e===void 0)return;if(JSON.stringify(e).length>6e4)throw i("La fuente combinada es demasiado grande.");if(!Array.isArray(e)||e.length<1||e.length>4)throw i("Una fuente combinada necesita de uno a cuatro or\xEDgenes.");let o=new Set;return e.map(t=>{if(!So(t)||Object.keys(t).some(r=>!["fuente","filtro","campos"].includes(r))||typeof t.fuente!="string"||!kw.test(t.fuente)||o.has(t.fuente))throw i("Origen combinado no v\xE1lido o repetido.");if(o.add(t.fuente),t.filtro!==void 0&&(!So(t.filtro)||JSON.stringify(t.filtro).length>4e3))throw i("Filtro de origen no v\xE1lido.");if(!So(t.campos)||Object.keys(t.campos).length>40)throw i("Proyecci\xF3n de origen no v\xE1lida.");let n=Object.fromEntries(Object.entries(t.campos).map(([r,a])=>{if(!qw.test(r)||["id","objeto"].includes(r)||!So(a)||Object.keys(a).some(l=>!["resumen","formula","permiso","casos","defecto","campo","soloFiltro","valor","alternativas","conversiones","condicion","equivalencias","etiqueta","opciones"].includes(l))||["campo","valor","alternativas","condicion","casos","resumen","formula"].filter(l=>Object.hasOwn(a,l)).length!==1||a.campo!==void 0&&(typeof a.campo!="string"||a.campo.length>125)||Object.hasOwn(a,"valor")&&a.valor!==null&&!["string","number","boolean"].includes(typeof a.valor)||a.alternativas!==void 0&&(!Array.isArray(a.alternativas)||a.alternativas.length!==2||a.alternativas.some(l=>typeof l!="string"||l.length>125))||a.condicion!==void 0&&(!So(a.condicion)||JSON.stringify(a.condicion).length>4e3)||a.conversiones!==void 0&&(!So(a.conversiones)||!Array.isArray(a.alternativas)||Object.entries(a.conversiones).some(([l,d])=>!a.alternativas.includes(l)||!So(d)||Object.keys(d).length>100||Object.values(d).some(u=>typeof u!="string")))||a.permiso!==void 0&&(typeof a.permiso!="string"||!Tf.test(a.permiso)||!["contacts","companies"].includes(t.fuente)||!a.formula&&!a.resumen)||a.soloFiltro!==void 0&&typeof a.soloFiltro!="boolean"||a.etiqueta!==void 0&&(typeof a.etiqueta!="string"||a.etiqueta.length>80)||a.opciones!==void 0&&(!So(a.opciones)||Object.keys(a.opciones).length>100||Object.values(a.opciones).some(l=>typeof l!="string"))||a.equivalencias!==void 0&&(!So(a.equivalencias)||!a.campo||Object.keys(a.equivalencias).length>100||Object.values(a.equivalencias).some(l=>typeof l!="string")))throw i("Campo de proyecci\xF3n no v\xE1lido.");a.resumen!==void 0&&qf(a.resumen);let s=a.formula===void 0?void 0:Af(a.formula);if(a.casos!==void 0)Rf(a.casos,a.defecto);else if(a.defecto!==void 0)throw i("El defecto necesita casos de proyecci\xF3n.");return[r,{...structuredClone(a),...s?{formula:s}:{}}]}));return{fuente:t.fuente,campos:n,...t.filtro?{filtro:structuredClone(t.filtro)}:{}}})}var So,qw,kw,fi=m(()=>{Ef();kf();Pf();q();Mf();So=e=>!!e&&typeof e=="object"&&!Array.isArray(e),qw=/^[a-z][a-z0-9_]{0,40}$/,kw=/^(contacts|companies|deals|mod_(?!sub_)[a-z][a-z0-9_]{0,40})$/});function If(e,o){if(o==null||o==="")return null;if(!["contacts","companies"].includes(e)||typeof o!="string"||!/^[a-z0-9][a-z0-9-]{0,59}$/.test(o))throw i("El \xE1mbito de tipo necesita Personas o Empresas y una clave v\xE1lida.");return o}var Df=m(()=>{q()});function zf(e){let o=Ne(e,"definici\xF3n");We(o,["titulo","fuente","origenes","metrica","agrupar","dividir","filtro","periodo","grafico","top","comparar","meta"],"definici\xF3n");let t=Ie(o.fuente,"fuente",60),n=Yt(o.origenes);if(t==="combinada"!=!!n)throw i("La fuente combinada necesita sus or\xEDgenes.");if(t!=="combinada"&&!Ds.includes(t)&&!/^mod_(?!sub_)[a-z][a-z0-9_]{0,40}$/.test(t))throw i("\xABfuente\xBB no v\xE1lida.");let r=Ne(o.metrica,"metrica");We(r,["tipo","campo","por","filtro_a","filtro_b"],"metrica");let a=Ke(r.tipo,Is,"metrica.tipo"),s={tipo:a,...r.campo!==void 0?{campo:Ie(r.campo,"metrica.campo",60)}:{},...r.por!==void 0?{por:Ie(r.por,"metrica.por",60)}:{},...r.filtro_a!==void 0&&r.filtro_a!==null?{filtro_a:Ne(r.filtro_a,"metrica.filtro_a")}:{},...r.filtro_b!==void 0&&r.filtro_b!==null?{filtro_b:Ne(r.filtro_b,"metrica.filtro_b")}:{}};if(["suma","media","min","max","minimo","maximo","mediana"].includes(a)&&!s.campo)throw i("Esa m\xE9trica necesita un campo.");if(a==="tasa_conversion"&&(r.filtro_a===void 0||r.filtro_b===void 0))throw i("\xABtasa_conversion\xBB necesita \xABfiltro_a\xBB y \xABfiltro_b\xBB.");if((a==="media_por"||a==="valor_medio_por")&&!s.por)throw i("\xABmedia_por\xBB necesita indicar el campo \xABpor\xBB para dividir.");let l;if(o.agrupar!==void 0&&o.agrupar!==null){let g=Ne(o.agrupar,"agrupar");We(g,["campo","paso"],"agrupar"),l={campo:Ie(g.campo,"agrupar.campo",60),...g.paso!==void 0?{paso:Ke(g.paso,Kt,"agrupar.paso")}:{}}}let d;if(o.dividir!==void 0&&o.dividir!==null){let g=Ne(o.dividir,"dividir");We(g,["campo","paso"],"dividir"),d={campo:Ie(g.campo,"dividir.campo",60),...g.paso!==void 0?{paso:Ke(g.paso,Kt,"dividir.paso")}:{}}}if(d&&!l)throw i("\xABDividir por\xBB solo se puede usar si se agrupa.");if(l&&d&&l.campo===d.campo)throw i("No se puede agrupar y dividir por el mismo campo.");let u;if(o.meta!==void 0&&o.meta!==null){if(typeof o.meta!="number"||Number.isNaN(o.meta)||o.meta<=0)throw i("\xABmeta\xBB: n\xFAmero mayor que 0.");u=o.meta}let p=o.periodo!==void 0&&o.periodo!==null?Ls(o.periodo):void 0,f=Ke(o.grafico,Rw,"grafico"),h=["numero","medidor","numero_tendencia"],b=["barras","barras_horizontales","lineas","area","dona","tabla","embudo"],y=["barras_apiladas","barras_agrupadas","varias_lineas","tabla_dinamica","mapa_calor"];if(h.includes(f)){if(l)throw i("Un n\xFAmero no se agrupa.");if(d)throw i("Un n\xFAmero no se divide.");if(f==="medidor"&&u===void 0)throw i("El medidor necesita una \xABmeta\xBB num\xE9rica.");if(f==="numero_tendencia"&&(!p||!o.comparar))throw i("\xABnumero_tendencia\xBB necesita un periodo con comparaci\xF3n.")}else if(b.includes(f)){if(!l)throw i("Ese gr\xE1fico necesita \xABagrupar\xBB.");if(d)throw i("Ese gr\xE1fico no admite \xABdividir por\xBB.")}else if(y.includes(f)){if(!l)throw i("Ese gr\xE1fico necesita \xABagrupar\xBB.");if(!d)throw i("Ese gr\xE1fico necesita \xABdividir por\xBB un segundo campo.")}if(o.top!==void 0&&(!Number.isSafeInteger(o.top)||o.top<1||o.top>Lf))throw i(`\xABtop\xBB: de 1 a ${Lf}.`);if(o.comparar!==void 0&&typeof o.comparar!="boolean")throw i("\xABcomparar\xBB: s\xED o no.");if(o.comparar&&!p)throw i("Para comparar hace falta un periodo.");if(o.comparar&&p?.proximos)throw i("\xABproximos\xBB no se compara (no hay periodo anterior).");if(o.comparar&&p?.preset)throw i("\xABpreset\xBB no se compara (todav\xEDa no se ha acabado).");let w=o.filtro===void 0||o.filtro===null?void 0:Ne(o.filtro,"filtro");if(w&&JSON.stringify(w).length>4e3)throw i("\xABfiltro\xBB demasiado grande.");return{titulo:Ie(o.titulo??"","titulo"),fuente:t,...n?{origenes:n}:{},metrica:s,...l?{agrupar:l}:{},...d?{dividir:d}:{},...u!==void 0?{meta:u}:{},...w?{filtro:w}:{},...p?{periodo:p}:{},grafico:f,...o.top!==void 0?{top:o.top}:{},...o.comparar?{comparar:!0}:{}}}function Ls(e){let o=Ne(e,"periodo");We(o,["campo","ultimos","proximos","preset","desde","hasta"],"periodo");let t={campo:Ie(o.campo,"periodo.campo",60)};if(o.preset!==void 0&&(t.preset=Ke(o.preset,Pw,"periodo.preset")),o.ultimos!==void 0){let r=Ne(o.ultimos,"periodo.ultimos");if(We(r,["n","unidad"],"periodo.ultimos"),!Number.isSafeInteger(r.n)||r.n<1||r.n>3660)throw i("\xABperiodo.ultimos.n\xBB no v\xE1lido.");t.ultimos={n:r.n,unidad:Ke(r.unidad,Kt,"periodo.ultimos.unidad")}}for(let r of["desde","hasta"])if(o[r]!==void 0){if(typeof o[r]!="string"||!Tw.test(o[r])||Number.isNaN(Date.parse(o[r])))throw i(`\xABperiodo.${r}\xBB: AAAA-MM-DD.`);t[r]=o[r]}if(o.proximos!==void 0){let r=Ne(o.proximos,"periodo.proximos");if(We(r,["n","unidad"],"periodo.proximos"),!Number.isSafeInteger(r.n)||r.n<1||r.n>3660)throw i("\xABperiodo.proximos.n\xBB no v\xE1lido.");t.proximos={n:r.n,unidad:Ke(r.unidad,Kt,"periodo.proximos.unidad")}}let n=[!!t.ultimos,!!t.proximos,!!t.preset,!!(t.desde||t.hasta)].filter(Boolean).length;if(!n)throw i("\xABperiodo\xBB: di \xABultimos\xBB, \xABproximos\xBB, \xABpreset\xBB o \xABdesde\xBB/\xABhasta\xBB.");if(n>1)throw i("\xABperiodo\xBB: solo una de \xABultimos\xBB, \xABproximos\xBB, \xABpreset\xBB o \xABdesde\xBB/\xABhasta\xBB.");return t}var Is,Rw,Kt,Ds,Pw,Lf,Tw,Ne,We,Ke,Ie,zs=m(()=>{fi();q();Is=["recuento","suma","media","min","max","minimo","maximo","mediana","porcentaje_total","acumulado","tasa_conversion","media_por","valor_medio_por"],Rw=["numero","barras","lineas","dona","tabla","barras_horizontales","barras_apiladas","barras_agrupadas","area","varias_lineas","embudo","medidor","numero_tendencia","tabla_dinamica","mapa_calor"],Kt=["dia","semana","mes","anio"],Ds=["companies","contacts","deals"],Pw=["hoy","semana","mes","trimestre","anio"],Lf=50,Tw=/^\d{4}-\d{2}-\d{2}$/,Ne=(e,o)=>{if(typeof e!="object"||e===null||Array.isArray(e))throw i(`\xAB${o}\xBB tiene que ser un objeto.`);return e},We=(e,o,t)=>{for(let n of Object.keys(e))if(!o.includes(n))throw i(`\xAB${t}\xBB: clave no admitida \xAB${n.slice(0,40)}\xBB.`)},Ke=(e,o,t)=>{if(typeof e!="string"||!o.includes(e))throw i(`\xAB${t}\xBB no v\xE1lido.`);return e},Ie=(e,o,t=80)=>{if(typeof e!="string"||e.length>t)throw i(`\xAB${o}\xBB no v\xE1lido.`);return e}});function Vf(e,o){if(e===null)return null;if(!jo(e))throw i("La disposici\xF3n no es v\xE1lida.");if(!Lw.test(o))throw i("Esta tabla no admite widgets.");for(let d of Object.keys(e))if(d!=="zonas"&&d!=="widgets")throw i("La disposici\xF3n no es v\xE1lida.");if(!jo(e.zonas))throw Uf();let t=e.zonas,n=jo(e.widgets)?e.widgets:{};for(let d of Object.keys(t))if(!Ff.includes(d))throw i("Zona no v\xE1lida.");let r={},a=new Set;for(let d of Ff){let u=t[d]??[];if(!Array.isArray(u))throw i("Zona no v\xE1lida.");r[d]=u.map(p=>{if(typeof p!="string"||p!==Fs&&!Dw.test(p))throw i("Bloque no v\xE1lido.");if(a.has(p))throw i("Un bloque solo puede estar en un sitio.");return a.add(p),p})}if(!a.has(Fs))throw Uf();if(r.arriba.length>Bf)throw i(`Arriba caben como mucho ${Bf} bloques.`);let s={};for(let[d,u]of Object.entries(n)){if(!a.has(d))continue;if(!jo(u))throw i("Widget no v\xE1lido.");let p=zf(u.definicion);if(u.via!==void 0&&(typeof u.via!="string"||!zw.test(u.via)))throw i("\xABvia\xBB no v\xE1lida.");if(u.via===void 0&&p.fuente!==o)throw i("Un widget de esta tabla solo mide esta tabla o sus relaciones.");s[d]={definicion:p,seguir_filtros:u.seguir_filtros!==!1,...u.via!==void 0?{via:u.via}:{}}}for(let d of a)if(d!==Fs&&!s[d])throw i("Falta la definici\xF3n de un widget.");if(Object.keys(s).length>Wf)throw i(`Como mucho ${Wf} widgets por vista.`);let l={zonas:r,widgets:s};if(JSON.stringify(l).length>6e4)throw i("La disposici\xF3n es demasiado grande.");return l}function Fw(e){if(!(e==null||e==="")){if(typeof e!="string"||!/^[a-z0-9][a-z0-9_:.-]{0,79}$/.test(e))throw i("El \xE1mbito de la vista no es v\xE1lido.");return e}}function Jf(e){if(!jo(e))throw i("La vista no es v\xE1lida.");let o=jo(e.pref)?Object.fromEntries(Object.entries(e.pref).filter(([d])=>Mw.has(d))):{};if(o.vistaOrigen!==void 0&&(typeof o.vistaOrigen!="string"||o.vistaOrigen.length>160))throw i("La vista de origen no es v\xE1lida.");if(o.vista!==void 0&&!Iw.has(String(o.vista)))throw i("El tipo de vista no es v\xE1lido.");let t=jo(e.filtros)?e.filtros:{};if(Object.keys(t).length>40||Object.keys(t).some(d=>!/^[a-zA-Z0-9_@.:-]{1,80}$/.test(d)))throw i("Los filtros de la vista no son v\xE1lidos.");let n=null;if(jo(e.orden)){let{field:d,order:u}=e.orden;if(typeof d!="string"||!/^[a-zA-Z0-9_.]{1,80}(,[a-zA-Z0-9_.]{1,80}){0,2}$/.test(d)||typeof u!="string"||!/^(ASC|DESC)(,(ASC|DESC)){0,2}$/.test(u))throw i("El orden de la vista no es v\xE1lido.");n={field:d,order:u}}let r=e.origenes===void 0?void 0:Yt(e.origenes),a;if(r||e.columnasCalculadas!==void 0){if(!r||r.length!==1||!["contacts","companies"].includes(r[0].fuente)||!jo(e.columnasCalculadas)||Object.keys(e.columnasCalculadas).length>40||Object.entries(e.columnasCalculadas).some(([d,u])=>!/^calc_[a-f0-9]{24}$/.test(d)||typeof u!="string"||!Object.hasOwn(r[0].campos,u)))throw i("Columnas calculadas de vista no v\xE1lidas.");a=e.columnasCalculadas}let s=Fw(e.ambito),l={pref:o,filtros:t,orden:n,...s?{ambito:s}:{},...r?{origenes:r,columnasCalculadas:a}:{}};if(JSON.stringify(l).length>3e4)throw i("La vista es demasiado grande.");return l}var Mw,Iw,Ff,Fs,Dw,Wf,Bf,Lw,zw,Uf,jo,Qf=m(()=>{fi();q();zs();Mw=new Set(["vistaOrigen","vista","visibles","orden","anchos","fijadas","calculos","agrupar","grupo","vistas","separar"]),Iw=new Set(["tabla","lista","kanban","calendario","galeria","linea","mapa"]),Ff=["arriba","izquierda","centro","derecha","abajo"],Fs="tabla",Dw=/^w_[a-z0-9]{1,24}$/,Wf=24,Bf=6,Lw=/^(contacts|companies|deals|mod_(?!sub_)[a-z][a-z0-9_]{1,40})$/,zw=/^[a-z][a-z0-9_]{0,59}$/,Uf=()=>new z(400,"tabla_obligatoria","La tabla no se puede quitar de la vista: mu\xE9vela, pero d\xE9jala.");jo=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)});function Gf(e){let o=new Set,t=n=>{typeof n=="string"&&n.startsWith("mod_")&&o.add(n.slice(4))};if(Ws(e.personas)&&t(e.personas.modulo),Array.isArray(e.secciones)){for(let n of e.secciones)if(Ws(n)&&(t(n.modulo),Array.isArray(n.camino)))for(let r of n.camino)Ws(r)&&t(r.modulo)}return o}var Ws,Hf=m(()=>{Ws=e=>!!e&&typeof e=="object"&&!Array.isArray(e)});function Uw(e){if(typeof e!="string"||!Bw.test(e))throw i("\xABrecurso\xBB: contacts, companies, deals o mod_<clave>.");return e}function Vw(e){if(!Ww.includes(e))throw i("\xABcanal\xBB: whatsapp o correo.");return e}function Yf(e,o="Plantilla"){if(!e||typeof e!="object"||Array.isArray(e))throw i(`${o}: un objeto.`);let t=e;for(let s of Object.keys(t))if(!["recurso","tipoContacto","canal","nombre","asunto","texto"].includes(s))throw i(`${o}: clave no admitida \xAB${s.slice(0,40)}\xBB.`);let n=Uw(t.recurso);if(t.tipoContacto!==void 0&&t.tipoContacto!==null&&(!Rr(n)||typeof t.tipoContacto!="string"||!/^[a-z0-9][a-z0-9-]{0,59}$/.test(t.tipoContacto)))throw i("El tipo de una plantilla necesita Personas o Empresas y una clave de tipo v\xE1lida.");let r=Vw(t.canal),a=r==="correo"?Bs(t.asunto,`${o}, asunto`,300,!1):void 0;return{recurso:n,...t.tipoContacto?{tipoContacto:t.tipoContacto}:{},canal:r,nombre:Bs(t.nombre,`${o}, nombre`,80),...a?{asunto:a}:{},texto:Bs(t.texto,`${o}, texto`,5e3)}}var Ww,hi,Bw,Xf,sD,Bs,Us=m(()=>{Hn();q();Ww=["whatsapp","correo"],hi=50,Bw=/^(contacts|companies|deals|mod_(?!sub_)[a-z][a-z0-9_]{0,40})$/,Xf="(?:datos\\.)?[a-z][a-z0-9_]{0,40}",sD=new RegExp(`\\{\\{\\s*(${Xf}(?:\\|${Xf})?)\\s*\\}\\}`,"g"),Bs=(e,o,t,n=!0)=>{if(e==null||e===""){if(n)throw i(`${o}: obligatorio.`);return}if(typeof e!="string"||e.trim().length>t)throw i(`${o}: un texto de hasta ${t} caracteres.`);return e.trim()}});import{BlockList as Kf,isIP as Jw}from"node:net";var Zf,eh,oh,th=m(()=>{Zf=new Kf,eh=new Kf;for(let[e,o]of[["0.0.0.0",8],["10.0.0.0",8],["100.64.0.0",10],["127.0.0.0",8],["169.254.0.0",16],["172.16.0.0",12],["192.0.0.0",24],["192.0.2.0",24],["192.88.99.0",24],["192.168.0.0",16],["198.18.0.0",15],["198.51.100.0",24],["203.0.113.0",24],["224.0.0.0",4],["240.0.0.0",4]])Zf.addSubnet(e,o,"ipv4");for(let[e,o]of[["::",128],["::1",128],["::ffff:0:0",96],["::",96],["64:ff9b::",96],["64:ff9b:1::",48],["100::",64],["2001::",32],["2001:db8::",32],["2002::",16],["fc00::",7],["fe80::",10],["fec0::",10],["ff00::",8]])eh.addSubnet(e,o,"ipv6");oh=e=>{let o=Jw(e);return o===4?Zf.check(e,"ipv4"):o===6?eh.check(e,"ipv6"):!0}});function ih(e){let o=Ne(e,"informe");We(o,["fuente","origenes","filtro","periodo","columnas","agrupar","agregados","orden"],"informe");let t=Ie(o.fuente,"fuente",60),n=Yt(o.origenes);if(t==="combinada"!=!!n)throw i("La fuente combinada necesita sus or\xEDgenes.");if(t!=="combinada"&&!Ds.includes(t)&&!/^mod_(?!sub_)[a-z][a-z0-9_]{0,40}$/.test(t))throw i("\xABfuente\xBB no v\xE1lida.");let r={fuente:t,...n?{origenes:n}:{}};if(o.filtro!==void 0&&o.filtro!==null&&(r.filtro=Ne(o.filtro,"filtro"),JSON.stringify(r.filtro).length>4e3))throw i("\xABfiltro\xBB demasiado grande.");if(o.periodo!==void 0&&o.periodo!==null&&(r.periodo=Ls(o.periodo)),o.columnas!==void 0&&o.columnas!==null){if(!Array.isArray(o.columnas)||o.columnas.length>rh)throw i(`\xABcolumnas\xBB: una lista de hasta ${rh}.`);r.columnas=[...new Set(o.columnas.map((a,s)=>Ie(a,`columnas[${s}]`,60)))]}if(o.agrupar!==void 0&&o.agrupar!==null){let a=Ne(o.agrupar,"agrupar");We(a,["campo","paso"],"agrupar"),r.agrupar={campo:Ie(a.campo,"agrupar.campo",60),...a.paso!==void 0?{paso:Ke(a.paso,Kt,"agrupar.paso")}:{}}}if(o.agregados!==void 0&&o.agregados!==null){if(!Array.isArray(o.agregados)||o.agregados.length>nh)throw i(`\xABagregados\xBB: una lista de hasta ${nh}.`);r.agregados=o.agregados.map((a,s)=>{let l=Ne(a,`agregados[${s}]`);We(l,["tipo","campo"],`agregados[${s}]`);let d=Ke(l.tipo,Is,`agregados[${s}].tipo`);if(d!=="recuento"&&l.campo===void 0)throw i(`\xABagregados[${s}]\xBB: esa operaci\xF3n necesita un campo.`);return{tipo:d,...d!=="recuento"?{campo:Ie(l.campo,`agregados[${s}].campo`,60)}:{}}})}if(r.agrupar&&!r.agregados?.length&&(r.agregados=[{tipo:"recuento"}]),o.orden!==void 0&&o.orden!==null){let a=Ne(o.orden,"orden");We(a,["por","sentido"],"orden"),r.orden={por:Ie(a.por,"orden.por",60),sentido:Ke(a.sentido??"asc",["asc","desc"],"orden.sentido")}}return r}var rh,nh,ah=m(()=>{fi();q();zs();rh=30,nh=6});var Vs,Qw,sh,ch=m(()=>{Vs=[{clave:"leo",nombre:"Leo",puesto:"Marketing"},{clave:"marina",nombre:"Marina",puesto:"Administrativa"},{clave:"dario",nombre:"Dar\xEDo",puesto:"Comercial"},{clave:"nora",nombre:"Nora",puesto:"Finanzas"},{clave:"irene",nombre:"Irene",puesto:"Consultora de procesos"}],Qw=e=>`pix.agente_${e}`,sh=e=>Vs.some(o=>Qw(o.clave)===e)});var lh,uh=m(()=>{lh=["contacts","companies","deals","tareas","proyectos"]});function dh(e,o,t){if(typeof e!="string"||!e.trim())throw i(`Falta \xAB${o}\xBB.`);let n=e.trim();if(n.length>t)throw i(`\xAB${o}\xBB: como mucho ${t} caracteres.`);return n}function ph(e){if(e===void 0)return;if(!e||typeof e!="object"||Array.isArray(e))throw i("\xABpix\xBB: un objeto.");let o=e;for(let r of Object.keys(o))if(r!=="personalidad")throw i(`\xABpix\xBB: no admite \xAB${r.slice(0,40)}\xBB.`);let t=o.personalidad;if(!t||typeof t!="object"||Array.isArray(t))throw i("\xABpix.personalidad\xBB: un objeto con nombre e instrucciones.");let n=t;for(let r of Object.keys(n))if(r!=="nombre"&&r!=="instrucciones")throw i(`\xABpix.personalidad\xBB: no admite \xAB${r.slice(0,40)}\xBB.`);return{personalidad:{nombre:dh(n.nombre,"pix.personalidad.nombre",Hw),instrucciones:dh(n.instrucciones,"pix.personalidad.instrucciones",Gw)}}}var Gw,Hw,mh=m(()=>{q();Gw=2e3,Hw=60});function fh(e,o){if(e===void 0)return[];if(!Array.isArray(e)||e.length>Fr)throw i(`\xABinformes\xBB: una lista de hasta ${Fr}.`);let t=new Set;return e.map((n,r)=>{if(!Xw(n))throw i(`Informe ${r+1}: un objeto.`);for(let l of Object.keys(n))if(!["nombre","descripcion","definicion"].includes(l))throw i(`Informe ${r+1}: clave no admitida \xAB${l.slice(0,40)}\xBB.`);if(typeof n.nombre!="string"||!n.nombre.trim()||n.nombre.length>80)throw i(`Informe ${r+1}: un nombre de hasta 80 caracteres.`);if(n.descripcion!==void 0&&(typeof n.descripcion!="string"||n.descripcion.length>500))throw i(`Informe ${r+1}: la descripci\xF3n, hasta 500 caracteres.`);let a=n.nombre.trim();if(t.has(a))throw i(`Dos informes se llaman \xAB${a}\xBB.`);t.add(a);let s=ih(n.definicion);if([s.fuente,...s.origenes?.map(l=>l.fuente)??[]].some(l=>l.startsWith("mod_")&&!o.includes(l.slice(4))))throw i(`Informe \xAB${a}\xBB: su fuente no es un m\xF3dulo de la soluci\xF3n.`);return{nombre:a,...n.descripcion?{descripcion:n.descripcion}:{},definicion:s}})}var Fr,Xw,Js=m(()=>{q();ah();Fr=30,Xw=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)});var hh,uo,Zt,er,X,Qs,or,RD,Yw,gi,Kw,Zw,PD,TD,gh=m(()=>{ch();hh={ver:["si","no","suyos","equipo","ambito","jerarquia"],editar:["si","no","suyos","equipo","ambito","jerarquia"],borrar:["si","no","suyos","equipo","ambito","jerarquia"],exportar:["si","no","suyos"],importar:["si","no"],crear:["si","no","suyos","equipo","ambito","jerarquia"],reasignar:["si","no","suyos","jerarquia"],estado:["si","no","suyos","equipo","ambito","jerarquia"],descargar:["si","no"],revelar:["si","no"]},uo=["si","no","suyos"],Zt=["si","no","suyos","equipo","jerarquia"],er=["si","no","suyos","jerarquia"],X=["si","no"],Qs=(e,o,t=!0)=>[{clave:`${e}.ver`,descripcion:`Ver ${o}`,valores:er},{clave:`${e}.crear`,descripcion:`Dar de alta ${o}`,valores:er},{clave:`${e}.editar`,descripcion:`Editar ${o}`,valores:er},{clave:`${e}.reasignar`,descripcion:`Cambiar el responsable de ${o}`,valores:er},...t?[{clave:`${e}.estado`,descripcion:`Cambiar el estado de ${o}`,valores:er}]:[],{clave:`${e}.descargar`,descripcion:`Bajar los ficheros de ${o}`,valores:X},{clave:`${e}.borrar`,descripcion:`Borrar ${o}`,valores:er},{clave:`${e}.exportar`,descripcion:`Exportar ${o}`,valores:uo},{clave:`${e}.importar`,descripcion:`Importar ${o} desde una hoja`,valores:X}],or=[...Qs("contactos","contactos"),...Qs("empresas","empresas",!1),...Qs("oportunidades","oportunidades"),{clave:"proyectos.ver",descripcion:"Ver proyectos",valores:Zt},{clave:"proyectos.editar",descripcion:"Editar los datos del proyecto",valores:Zt},{clave:"proyectos.borrar",descripcion:"Borrar proyectos",valores:Zt},{clave:"proyectos.exportar",descripcion:"Exportar proyectos",valores:uo},{clave:"proyectos.crear",descripcion:"Crear proyectos",valores:X},{clave:"proyectos.gestionar",descripcion:"Cambiar el estado, el responsable, los participantes, las columnas y los ajustes de los proyectos, y gestionar plantillas",valores:X},{clave:"tareas.ver",descripcion:"Ver tareas",valores:Zt},{clave:"tareas.crear",descripcion:"Crear tareas",valores:X},{clave:"tareas.editar",descripcion:"Editar y completar tareas",valores:Zt},{clave:"tareas.borrar",descripcion:"Borrar tareas",valores:Zt},{clave:"tareas.exportar",descripcion:"Exportar tareas visibles",valores:uo},{clave:"notas.ver",descripcion:"Ver notas",valores:uo},{clave:"notas.editar",descripcion:"Escribir, editar y borrar notas",valores:uo},{clave:"adjuntos.ver",descripcion:"Ver y descargar adjuntos",valores:uo},{clave:"adjuntos.subir",descripcion:"Subir adjuntos",valores:uo},{clave:"miembros.gestionar",descripcion:"Invitar, cambiar el papel y desactivar miembros",valores:X},{clave:"conectores.accionar",descripcion:"Ejecutar acciones f\xEDsicas de conectores",valores:X},{clave:"configuracion.gestionar",descripcion:"Cambiar la configuraci\xF3n del espacio y los permisos",valores:X},{clave:"formularios.gestionar",descripcion:"Crear, editar y borrar formularios (y sus respuestas)",valores:X},{clave:"formularios.ver_respuestas",descripcion:"Ver las respuestas de los formularios",valores:uo},{clave:"modulos.configurar",descripcion:"Dise\xF1ar, publicar y archivar m\xF3dulos",valores:X},{clave:"paneles.ver",descripcion:"Ver los paneles de m\xE9tricas",valores:X},{clave:"paneles.editar",descripcion:"Crear, cambiar y borrar paneles de m\xE9tricas",valores:X},{clave:"paneles.compartir",descripcion:"Compartir paneles con el equipo y cambiar o borrar los de equipo",valores:X},{clave:"automatizaciones.gestionar",descripcion:"Crear y cambiar automatizaciones, y ver sus ejecuciones",valores:X},{clave:"campanas.gestionar",descripcion:"Crear y enviar campa\xF1as de correo, y gestionar consentimientos y supresiones",valores:X},{clave:"agenda.ver",descripcion:"Ver las citas de la agenda",valores:uo},{clave:"agenda.editar",descripcion:"Crear, mover y cancelar citas",valores:uo},{clave:"agenda.configurar",descripcion:"Configurar la agenda: tipos de cita, d\xEDas cerrados, horarios, reserva p\xFAblica y los recursos (horarios y aprobar ausencias)",valores:X},{clave:"analisis.ver",descripcion:"Usar An\xE1lisis: informes de lo que ya puede ver",valores:X},{clave:"analisis.compartir",descripcion:"Compartir informes con el equipo y cambiar o borrar los de equipo",valores:X},{clave:"secretos.ver",descripcion:"Ver los campos secretos (cada vez queda registrado qui\xE9n lo vio)",valores:X},{clave:"liquidaciones.gestionar",descripcion:"Generar, aprobar, cerrar, pagar y reabrir liquidaciones de comisiones",valores:X},{clave:"portales.gestionar",descripcion:"Configurar los portales, invitar a ellos y revocar el acceso",valores:X},{clave:"auditoria.ver",descripcion:"Ver la auditor\xEDa del espacio (qui\xE9n hizo qu\xE9 y cu\xE1ndo)",valores:X},{clave:"publico.compartir",descripcion:"Compartir la p\xE1gina p\xFAblica de un registro (un enlace que caduca)",valores:X},{clave:"pix.memoria_espacio",descripcion:"Escribir lo que Pix recuerda para todo el espacio",valores:X},...Vs.map(e=>({clave:`pix.agente_${e.clave}`,descripcion:`Usar a ${e.nombre} (${e.puesto}) del Equipo IA`,valores:X}))],RD=new Set(or.map(e=>e.clave)),Yw=e=>/\.(exportar|importar)$/.test(e),gi=e=>Object.fromEntries(or.map(o=>[o.clave,e(o)])),Kw=e=>e.clave.startsWith("miembros.")||e.clave.startsWith("configuracion.")||e.clave==="formularios.gestionar"||e.clave.startsWith("proyectos.")&&e.clave!=="proyectos.ver"&&e.clave!=="proyectos.exportar"||e.clave==="modulos.configurar"||e.clave==="agenda.configurar"||e.clave==="paneles.compartir"||e.clave==="automatizaciones.gestionar"||e.clave==="campanas.gestionar"||e.clave==="analisis.compartir"||e.clave==="liquidaciones.gestionar"||e.clave==="portales.gestionar"||e.clave==="auditoria.ver"||e.clave==="pix.memoria_espacio"||sh(e.clave),Zw={titular:gi(()=>"si"),administrador:gi(e=>e.clave==="conectores.accionar"?"no":"si"),miembro:gi(e=>Kw(e)||e.clave==="conectores.accionar"||e.clave==="secretos.ver"||Yw(e.clave)?"no":"si"),lectura:gi(e=>e.clave.endsWith(".ver")&&e.clave!=="secretos.ver"&&e.clave!=="auditoria.ver"||e.clave.endsWith(".descargar")?"si":e.clave.endsWith(".reasignar")?"suyos":"no")},PD=or.filter(e=>/^((contactos|empresas|oportunidades|proyectos|tareas|notas|adjuntos)\.|agenda\.(ver|editar)$)/.test(e.clave)&&e.valores.includes("suyos")&&Zw.miembro[e.clave]!=="no").map(e=>e.clave),TD=or.filter(e=>/^((contactos|empresas|oportunidades|proyectos|tareas|notas|adjuntos)\.|agenda\.(ver|editar)$)/.test(e.clave)&&e.valores.includes("suyos")).map(e=>e.clave)});function vh(e){if(!Array.isArray(e))throw i("Los sin\xF3nimos van en una lista de palabras.");let o=[],t=new Set;for(let n of e){if(typeof n!="string")throw i("Cada sin\xF3nimo es un texto.");let r=n.replace(/\s+/g," ").trim();if(r){if(r.length>bh)throw i(`\xAB${r.slice(0,20)}\u2026\xBB: como mucho ${bh} caracteres.`);if(!Gs(r))throw i(`\xAB${r}\xBB no es una palabra.`);t.has(Gs(r))||(t.add(Gs(r)),o.push(r))}}if(o.length>Hs)throw i(`Como mucho ${Hs} sin\xF3nimos por m\xF3dulo.`);return o}var wh,Hs,bh,Gs,yh=m(()=>{q();wh=["contacts","companies","deals","tasks"],Hs=20,bh=40,Gs=e=>e.normalize("NFD").replace(/[̀-ͯ]/g,"").toLowerCase().replace(/[^a-z0-9ñ\s-]/g," ").replace(/\s+/g," ").trim()});function tv(e,o){return mo(e,Ks,"vistasTabla").map((t,n)=>{let r=`Vista de tabla ${n+1}`;if(!pe(t))throw i(`${r}: un objeto.`);po(t,["objeto","tipoContacto","nombre","config","disposicion"],r);let a=typeof t.objeto=="string"?t.objeto:"";if(!["contacts","companies"].includes(a)&&(!a.startsWith("mod_")||!o.includes(a.slice(4))))throw i(`${r}: de un m\xF3dulo de la soluci\xF3n (mod_<clave>).`);let s=Vf(t.disposicion??null,a),l=If(a,t.tipoContacto);return{objeto:a,...l?{tipoContacto:l}:{},nombre:Qo(t.nombre,`nombre de la ${r.toLowerCase()}`,60),...t.config!==void 0?{config:Jf(t.config)}:{},disposicion:s}})}function av(e,o,t=[]){let n=new Set;return mo(e,ec,"papeles").map((r,a)=>{let s=`Papel ${a+1}`;if(!pe(r))throw i(`${s}: un objeto.`);po(r,["nombre","base","permisos","ocultos","lectura","identidades"],s);let l=Qo(r.nombre,`nombre del ${s.toLowerCase()}`,40);if(n.has(l.toLowerCase()))throw i(`${s}: nombre repetido.`);if(n.add(l.toLowerCase()),typeof r.base!="string"||!nv.includes(r.base))throw i(`${s}: \xABbase\xBB, administrador, miembro o lectura.`);let d={};if(r.permisos!==void 0){if(!pe(r.permisos))throw i(`${s}: \xABpermisos\xBB, un objeto.`);for(let[b,y]of Object.entries(r.permisos)){if(b==="miembros.gestionar"||b==="configuracion.gestionar")throw i(`${s}: \xAB${b}\xBB no se da en un papel personalizado.`);let w=iv.exec(b),g=or.find(C=>C.clave===b);if(w?!o.includes(w[1]):!g)throw i(`${s}: permiso desconocido \xAB${b.slice(0,60)}\xBB.`);let N=g?g.valores:hh[w[2]];if(typeof y!="string"||!N.includes(y))throw i(`${s}: valor no v\xE1lido para \xAB${b.slice(0,60)}\xBB.`);d[b]=y}}let u=(b,y)=>{if(b===void 0)return[];if(!Array.isArray(b)||b.length>100)throw i(`${s}: \xAB${y}\xBB, una lista (hasta 100) de \xABmod_<clave>.<campo>\xBB.`);return b.map(w=>{let g=typeof w=="string"?rv.exec(w):null,N=g?t.find(C=>C.clave===g[1]):void 0;if(!g||!N||!N.campos.some(C=>C.clave===g[2]))throw i(`${s}: \xAB${String(w).slice(0,60)}\xBB no es un campo de un m\xF3dulo de la soluci\xF3n.`);return w})},p=u(r.ocultos,"ocultos"),f=u(r.lectura,"lectura"),h=up(r.identidades);return{nombre:l,base:r.base,...Object.keys(d).length?{permisos:d}:{},...p.length?{ocultos:p}:{},...f.length?{lectura:f}:{},...h.length?{identidades:h}:{}}})}function Xs(e,o=0){if(o>30)throw i("La soluci\xF3n anida demasiado.");if(Array.isArray(e))return e.forEach(t=>Xs(t,o+1));if(pe(e))for(let t of Object.keys(e)){if(ov.has(t))throw i(`Clave no admitida \xAB${t}\xBB.`);Xs(e[t],o+1)}}function po(e,o,t){for(let n of Object.keys(e))if(!o.includes(n))throw i(`${t}: clave no admitida \xAB${n.slice(0,40)}\xBB.`)}function Qo(e,o,t,n=!0){if(e==null||e===""){if(n)throw i(`Falta \xAB${o}\xBB.`);return""}if(typeof e!="string"||e.length>t)throw i(`\xAB${o}\xBB: texto de hasta ${t} caracteres.`);return e.trim()}function yi(e,o){if(typeof e=="string"){if(e.length>wi)throw i("La soluci\xF3n pasa de 1 MB.");try{e=JSON.parse(e)}catch{throw i("La soluci\xF3n no es un JSON v\xE1lido.")}}else if(JSON.stringify(e??null).length>wi)throw i("La soluci\xF3n pasa de 1 MB.");if(!pe(e))throw i("La soluci\xF3n tiene que ser un objeto.");Xs(e),po(e,["formato","version","plantilla","nombre","descripcion","icono","modulos","paneles","automatizaciones","ejemplos","informes","principal","mensajes","papeles","portales","vistasTabla","separadores","menu","sinonimos","perfilesImportacion","senales","pix"],"Soluci\xF3n");let t;if(e.plantilla!==void 0){let $=e.plantilla;if(!pe($))throw i("\xABplantilla\xBB: un objeto.");if(po($,["id","version","sector","nivel"],"Plantilla"),typeof $.id!="string"||!/^[a-z][a-z0-9_]{0,59}$/.test($.id))throw i("\xABplantilla.id\xBB: min\xFAsculas, n\xFAmeros y _.");if(!Number.isInteger($.version)||$.version<1)throw i("\xABplantilla.version\xBB: un entero.");if(typeof $.sector!="string"||!/^[a-z][a-z0-9_]{0,39}$/.test($.sector))throw i("\xABplantilla.sector\xBB: min\xFAsculas y _.");if($.nivel!==void 0&&$.nivel!=="completa"&&$.nivel!=="basica")throw i("\xABplantilla.nivel\xBB: completa o basica.");t={id:$.id,version:$.version,sector:$.sector,...$.nivel==="basica"?{nivel:"basica"}:{}}}if(e.formato!==xt)throw i(`No es una soluci\xF3n (formato \xAB${xt}\xBB).`);if(!Number.isInteger(e.version)||e.version<1)throw i("\xABversion\xBB: un entero.");if(e.version>tr)throw i("La soluci\xF3n es de una versi\xF3n m\xE1s nueva del CRM.");let n=Qo(e.icono,"icono",40,!1)||"boxes";if(!_h.test(n))throw i("\xABicono\xBB: un icono de lucide.");if(!Array.isArray(e.modulos)||e.modulos.length<1||e.modulos.length>bi)throw i(`Una soluci\xF3n lleva de 1 a ${bi} m\xF3dulos.`);let r=e.modulos.map($=>pe($)&&typeof $.clave=="string"?$.clave:"");if(new Set(r).size!==r.length)throw i("Dos m\xF3dulos de la soluci\xF3n con la misma clave.");let a=new Map([...o.externos??[]].filter(([$])=>!r.includes($))),s=[...r,...a.keys()],l=new Map([...a,...e.modulos.map(($,v)=>[r[v],Ms($,s)])]),d=e.modulos.map($=>{let v=jf($,{topeCampos:o.topeCampos,modulosDelEspacio:s,camposRelacion:l}),A=pe($)?$.sin_coste:void 0;if(A!==void 0&&A!==!0)throw i(`\xAB${v.nombre_plural}\xBB: \xABsin_coste\xBB solo puede ser true.`);return A===!0?{...v,sin_coste:!0}:v}),u=mo(e.paneles,Ys,"paneles").map(($,v)=>{if(!pe($))throw i(`Panel ${v+1}: un objeto.`);if(po($,["nombre","icono","widgets"],`Panel ${v+1}`),!Array.isArray($.widgets)||$.widgets.length>20)throw i(`Panel ${v+1}: hasta 20 widgets.`);let A=Qo($.icono,"icono",40,!1);if(A&&!_h.test(A))throw i(`Panel ${v+1}: icono no v\xE1lido.`);return{nombre:Qo($.nombre,"nombre del panel",60),...A?{icono:A}:{},widgets:$.widgets}}),p=mo(e.automatizaciones,Zs,"automatizaciones").map(($,v)=>{if(!pe($))throw i(`Automatizaci\xF3n ${v+1}: un objeto.`);if(po($,["nombre","definicion"],`Automatizaci\xF3n ${v+1}`),!pe($.definicion))throw i(`Automatizaci\xF3n ${v+1}: falta su definici\xF3n.`);return{nombre:Qo($.nombre,"nombre de la automatizaci\xF3n",80),definicion:$.definicion}}),f=mo(e.senales,20,"senales").map(($,v)=>{if(!pe($))throw i(`Se\xF1al ${v+1}: un objeto.`);po($,["fuente","regla"],`Se\xF1al ${v+1}`);let A=typeof $.fuente=="string"?$.fuente:"";if(!(A.startsWith("mod_")?r.includes(A.slice(4)):lh.includes(A)))throw i(`Se\xF1al ${v+1}: \xABfuente\xBB, un m\xF3dulo de la soluci\xF3n (mod_<clave>) o un nativo.`);if(!pe($.regla))throw i(`Se\xF1al ${v+1}: falta su regla.`);return{fuente:A,regla:$.regla}}),h=ph(e.pix),b=fh(e.informes,r);if(e.principal!==void 0&&(typeof e.principal!="string"||!r.includes(e.principal)))throw i("\xABprincipal\xBB: la clave de uno de sus m\xF3dulos.");let y=mo(e.mensajes,hi,"mensajes").map(($,v)=>{let A=Yf($,`Mensaje ${v+1}`);if(A.recurso.startsWith("mod_")&&!r.includes(A.recurso.slice(4)))throw i(`Mensaje ${v+1}: de un m\xF3dulo que no est\xE1 en la soluci\xF3n.`);return A}),w=av(e.papeles,r,d),g=cv(e.portales,r),N=tv(e.vistasTabla,r),C=mo(e.separadores??[],oc,"separadores").map(($,v)=>{if(!pe($))throw i(`Separador ${v+1}: un objeto.`);if(po($,["antes","titulo"],`Separador ${v+1}`),$.antes!==null&&(typeof $.antes!="string"||!r.includes($.antes)))throw i(`Separador ${v+1}: \xABantes\xBB, la clave de uno de sus m\xF3dulos.`);if($.titulo!==void 0&&$.titulo!==null&&(typeof $.titulo!="string"||!$.titulo.trim()||$.titulo.trim().length>40))throw i(`Separador ${v+1}: \xABtitulo\xBB, de 1 a 40 caracteres (o null: solo la l\xEDnea).`);return{antes:$.antes,titulo:typeof $.titulo=="string"?$.titulo.trim():null}}),S=mo(e.menu??[],100,"menu").map(($,v)=>{if(!pe($))throw i(`Men\xFA ${v+1}: un objeto.`);if(po($,["entrada","padre","recientes","despliega"],`Men\xFA ${v+1}`),typeof $.entrada!="string"||!r.includes($.entrada))throw i(`Men\xFA ${v+1}: \xABentrada\xBB, la clave de uno de sus m\xF3dulos.`);if($.padre!==void 0&&$.padre!==null&&(typeof $.padre!="string"||!r.includes($.padre)||$.padre===$.entrada))throw i(`Men\xFA ${v+1}: \xABpadre\xBB, otro de sus m\xF3dulos (o null).`);if($.recientes!==void 0&&(!Number.isSafeInteger($.recientes)||$.recientes<0||$.recientes>10))throw i(`Men\xFA ${v+1}: \xABrecientes\xBB, de 0 a 10.`);if($.despliega!==void 0&&(typeof $.despliega!="string"||!Os.includes($.despliega)))throw i(`Men\xFA ${v+1}: \xABdespliega\xBB, ${Os.join(", ")}.`);return{entrada:$.entrada,...$.padre!==void 0?{padre:$.padre}:{},...$.recientes!==void 0?{recientes:$.recientes}:{},...$.despliega!==void 0?{despliega:$.despliega}:{}}});for(let $ of S)if($.padre&&(S.some(v=>v.entrada===$.padre&&v.padre)||S.some(v=>v.padre===$.entrada)))throw i(`Men\xFA: \xAB${$.entrada}\xBB, un solo nivel (ni su padre va dentro de otro ni tiene otros dentro).`);if(new Set(S.map($=>$.entrada)).size!==S.length)throw i("Men\xFA: cada m\xF3dulo, una vez.");let T={};if(e.ejemplos!==void 0){if(!pe(e.ejemplos))throw i("\xABejemplos\xBB: un objeto por m\xF3dulo.");for(let[$,v]of Object.entries(e.ejemplos)){if(!r.includes($))throw i(`Ejemplos de un m\xF3dulo que no est\xE1 en la soluci\xF3n (\xAB${$.slice(0,40)}\xBB).`);let A=new Set;T[$]=mo(v,vi,`ejemplos de ${$}`).map((x,M)=>{if(!pe(x))throw i(`Ejemplo ${M+1} de ${$}: un objeto.`);if(x._ref!==void 0&&!Number.isSafeInteger(x._ref))throw i(`Ejemplo ${M+1} de ${$}: \xAB_ref\xBB es un entero.`);if(typeof x._ref=="number"){if(A.has(x._ref))throw i(`\xAB${$}\xBB: referencia de ejemplo repetida.`);A.add(x._ref)}if((d.find(I=>I.clave===$)?.campos??[]).filter(I=>I.tipo==="secreto").map(I=>I.clave).some(I=>I in x))throw i(`Ejemplo ${M+1} de ${$}: un ejemplo no lleva el valor de un campo secreto.`);return x})}}let Y=cp(e.perfilesImportacion);if(Y.some($=>$.perfil.entidades.some(v=>v.destino.startsWith("mod_")&&!d.some(A=>`mod_${A.clave}`===v.destino))))throw i("El perfil apunta fuera de la soluci\xF3n.");return{formato:xt,...Y.length?{perfilesImportacion:Y}:{},version:e.version,...t?{plantilla:t}:{},nombre:Qo(e.nombre,"nombre",80),descripcion:Qo(e.descripcion,"descripcion",500,!1),icono:n,modulos:d,paneles:u,automatizaciones:p,ejemplos:T,...f.length?{senales:f}:{},...h?{pix:h}:{},...b.length?{informes:b}:{},...typeof e.principal=="string"?{principal:e.principal}:{},...y.length?{mensajes:y}:{},...w.length?{papeles:w}:{},...g.length?{portales:g}:{},...N.length?{vistasTabla:N}:{},...C.length?{separadores:C}:{},...S.length?{menu:S}:{},...sv(e.sinonimos,d.map($=>$.clave))}}function sv(e,o){if(e===void 0)return{};if(!pe(e))throw i("\xABsinonimos\xBB: un objeto (clave del m\xF3dulo \u2192 lista de palabras).");let t={};for(let[n,r]of Object.entries(e)){if(!o.includes(n)&&!wh.includes(n))throw i(`\xABsinonimos\xBB: \xAB${n.slice(0,40)}\xBB no es un m\xF3dulo de la soluci\xF3n ni uno nativo.`);let a=vh(r);a.length&&(t[n]=a)}return Object.keys(t).length?{sinonimos:t}:{}}function cv(e,o){return mo(e,tc,"portales").map((t,n)=>{let r=`Portal ${n+1}`;if(!pe(t))throw i(`${r}: un objeto.`);po(t,["clave","nombre","activo","personas","secciones","textos","marca"],r);let a=[...Gf(t)].filter(p=>!o.includes(p));if(a.length)throw i(`${r}: usa un m\xF3dulo que no est\xE1 en la soluci\xF3n (\xABmod_${a[0].slice(0,40)}\xBB).`);if(!Array.isArray(t.secciones)||!t.secciones.length)throw i(`${r}: al menos una secci\xF3n.`);let{activo:s,marca:l,...d}=t,u=pe(l)&&typeof l.color=="string"?l.color:void 0;return{...d,...u?{marca:{color:u}}:{}}})}function mo(e,o,t){if(e===void 0)return[];if(!Array.isArray(e)||e.length>o)throw i(`\xAB${t}\xBB: una lista de hasta ${o}.`);return e}var xt,tr,bi,Ys,Ks,Zs,vi,wi,_h,ov,ec,rv,nv,iv,pe,oc,tc,rc=m(()=>{lp();dp();Hf();Df();Us();q();uh();mh();Js();Lr();Zm();gh();Qf();yh();xt="forgenex.solucion",tr=2,bi=30,Ys=10,Ks=20,Zs=40,vi=50,wi=1e6,_h=/^[a-z0-9-]{1,40}$/,ov=new Set(["__proto__","constructor","prototype"]);ec=10,rv=/^mod_([a-z][a-z0-9_]{0,40})\.([a-z][a-z0-9_]{0,40})$/,nv=["administrador","miembro","lectura"],iv=/^mod_([a-z][a-z0-9_]{0,40})\.(ver|editar|borrar|exportar|importar|crear|reasignar|estado|descargar|revelar)$/;pe=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);oc=20,tc=10});import{inflateRawSync as lv}from"node:zlib";function dv(e){let o=Buffer.from(e.buffer,e.byteOffset,e.byteLength);if(o.length>uv)throw i("El paquete pasa de 5 MB.");if(o.length<22||o.readUInt32LE(0)!==67324752)throw i("El paquete no es un .zip.");let t=-1;for(let d=o.length-22;d>=Math.max(0,o.length-22-65535);d--)if(o.readUInt32LE(d)===101010256&&d+22+o.readUInt16LE(d+20)===o.length){t=d;break}if(t<0)throw i("El .zip est\xE1 da\xF1ado (sin directorio).");let n=o.readUInt16LE(t+10),r=o.readUInt32LE(t+16),a=o.readUInt32LE(t+12);if(o.readUInt16LE(t+4)!==0||o.readUInt16LE(t+6)!==0||o.readUInt16LE(t+8)!==n||t+22+o.readUInt16LE(t+20)!==o.length||r+a!==t)throw i("El .zip est\xE1 da\xF1ado (directorio inv\xE1lido).");if(n>$h)throw i(`El paquete trae m\xE1s de ${$h} ficheros.`);let s=new Map,l=r;for(let d=0;d<n;d++){if(l+46>t||o.readUInt32LE(l)!==33639248)throw i("El .zip est\xE1 da\xF1ado.");let u=o.readUInt16LE(l+8),p=o.readUInt16LE(l+10),f=o.readUInt32LE(l+20),h=o.readUInt32LE(l+24),b=o.readUInt16LE(l+28),y=o.readUInt16LE(l+30),w=o.readUInt16LE(l+32),g=o.readUInt32LE(l+42);if(l+46+b+y+w>t)throw i("El .zip est\xE1 da\xF1ado.");let N=o.subarray(l+46,l+46+b),C=N.toString("utf8");if(l+=46+b+y+w,!C.endsWith("/")){if(!C||C.includes("\\")||C.startsWith("/")||C.split("/").some(S=>S===".."||S==="."||S==="")||/[\x00-\x1f]/.test(C))throw i(`El paquete trae un nombre de fichero no admitido (\xAB${C.slice(0,80)}\xBB).`);if(s.has(C))throw i(`El paquete trae \xAB${C.slice(0,80)}\xBB dos veces.`);if(u&1)throw i("El paquete no puede ir cifrado.");s.set(C,()=>{if(h>Nh)throw i(`\xAB${C}\xBB pasa de 2 MB.`);if(g+30>o.length||o.readUInt32LE(g)!==67324752)throw i("El .zip est\xE1 da\xF1ado.");let S=o.readUInt16LE(g+26),T=g+30+S+o.readUInt16LE(g+28);if(T>r||T+f>r||o.readUInt16LE(g+6)!==u||o.readUInt16LE(g+8)!==p||!o.subarray(g+30,g+30+S).equals(N))throw i("El .zip est\xE1 da\xF1ado.");let Y=o.subarray(T,T+f);if(Y.length!==f)throw i("El .zip est\xE1 da\xF1ado.");let $;if(p===0)$=Y;else if(p===8)try{$=lv(Y,{maxOutputLength:Nh})}catch{throw i(`\xAB${C}\xBB no se puede descomprimir (o pasa de 2 MB).`)}else throw i(`\xAB${C}\xBB va comprimido de una forma no admitida (solo \xABstore\xBB y \xABdeflate\xBB).`);if($.length!==h)throw i("El .zip est\xE1 da\xF1ado.");return $})}}if(l!==t)throw i("El .zip est\xE1 da\xF1ado (directorio inv\xE1lido).");return s}function nc(e){let o=new Map,t=0;for(let[n,r]of dv(e)){let a=r();if(t+=a.length,t>pv)throw i("Los ficheros del paquete pasan de 10 MB al descomprimirlos.");o.set(n,a)}return o}var uv,Nh,$h,pv,xh=m(()=>{q();uv=5*1024*1024,Nh=2*1024*1024,$h=500;pv=10*1024*1024});import{createHash as Ch,createPublicKey as mv,sign as fv,verify as fL}from"node:crypto";function hv(e){let o=mv(e);if(o.asymmetricKeyType!=="ed25519")throw i("La clave p\xFAblica tiene que ser ed25519.");let t=o.export({type:"spki",format:"der"});return{pem:o.export({type:"spki",format:"pem"}).toString(),id:Ch("sha256").update(t).digest("hex")}}function gv(e){return Buffer.from(JSON.stringify(["forgenex.fgx.v1",[...e].filter(([o])=>o!==ic).sort(([o],[t])=>o<t?-1:o>t?1:0).map(([o,t])=>[o,Ch("sha256").update(t).digest("hex")])]))}function Oh(e,o,t){let{id:n}=hv(t);return Buffer.from(JSON.stringify({formato:"forgenex.firma",version:1,clave:n,firma:fv(null,gv(e),o).toString("base64")}))}var ic,Sh=m(()=>{q();ic="firma.json"});function ac(e){let o=Array.from({length:256},(l,d)=>{let u=d;for(let p=0;p<8;p++)u=u&1?3988292384^u>>>1:u>>>1;return u>>>0}),t=[],n=[],r=0;for(let[l,d]of e){let u=Buffer.from(l),p=4294967295;for(let b of d)p=o[(p^b)&255]^p>>>8;p=(p^4294967295)>>>0;let f=Buffer.alloc(30),h=Buffer.alloc(46);f.writeUInt32LE(67324752),f.writeUInt16LE(20,4),f.writeUInt16LE(2048,6),f.writeUInt32LE(p,14),f.writeUInt32LE(d.length,18),f.writeUInt32LE(d.length,22),f.writeUInt16LE(u.length,26),h.writeUInt32LE(33639248),h.writeUInt16LE(20,4),h.writeUInt16LE(20,6),h.writeUInt16LE(2048,8),h.writeUInt32LE(p,16),h.writeUInt32LE(d.length,20),h.writeUInt32LE(d.length,24),h.writeUInt16LE(u.length,28),h.writeUInt32LE(r,42),t.push(f,u,d),n.push(h,u),r+=f.length+u.length+d.length}let a=Buffer.concat(n),s=Buffer.alloc(22);return s.writeUInt32LE(101010256),s.writeUInt16LE(e.size,8),s.writeUInt16LE(e.size,10),s.writeUInt32LE(a.length,12),s.writeUInt32LE(r,16),Buffer.concat([...t,a,s])}var jh=m(()=>{});import{copyFileSync as sc,mkdirSync as cc,readFileSync as _i,readdirSync as Wr,realpathSync as Ah,writeFileSync as qh}from"node:fs";import{dirname as bv,join as ee,resolve as wv,sep as vv}from"node:path";import{fileURLToPath as yv}from"node:url";import{createRequire as Eh}from"node:module";function kh(e,o="html",t=process.cwd()){if(!/^[a-z][a-z0-9-]{1,59}$/.test(e))throw new Error("El nombre debe tener de 2 a 60 letras min\xFAsculas, n\xFAmeros o guiones y empezar por letra.");if(!["html","react"].includes(o))throw new Error("Plantilla: html o react.");let n=ee(t,e);cc(n);for(let l of["interfaz","funciones"])cc(ee(n,l));let r=(l,d)=>qh(ee(n,l),typeof d=="string"?d:JSON.stringify(d,null,2)+`
|
|
22
|
-
`),a=`ext_${e.replace(/[^a-z]/g,"_").slice(0,27)}`;
|
|
21
|
+
from aprobaciones a join modulos m on m.id = a.modulo_id`});function Om(e,o,t){if(e.requisito!==void 0&&e.requisito!==null){let r=e.requisito;if(!dw(r)||typeof r.formula!="string"||!r.formula.trim()||r.formula.length>Ke||typeof r.mensaje!="string"||!r.mensaje.trim()||r.mensaje.length>200)throw i(`\xAB${t}\xBB, \xAB${o.etiqueta}\xBB: el requisito lleva una f\xF3rmula y un mensaje (hasta 200 caracteres).`);o.requisito={formula:r.formula.trim(),mensaje:r.mensaje.trim()}}if(e.pide!==void 0&&e.pide!==null){if(!Array.isArray(e.pide)||e.pide.length>jm||e.pide.some(r=>typeof r!="string"||!/^[a-z][a-z0-9_]{0,40}$/.test(r)))throw i(`\xAB${t}\xBB, \xAB${o.etiqueta}\xBB: \xABpide\xBB, hasta ${jm} campos.`);e.pide.length&&(o.pide=[...new Set(e.pide)])}if(xm(e,o,t),e.limiteDias!==void 0&&e.limiteDias!==null){if(!Number.isInteger(e.limiteDias)||e.limiteDias<1||e.limiteDias>3650)throw i(`\xAB${t}\xBB, \xAB${o.etiqueta}\xBB: el l\xEDmite de d\xEDas, de 1 a 3650.`);o.limiteDias=e.limiteDias}}function Sm(e){let o=e.filter(t=>!t.archivado);return e.map(t=>{if(t.tipo!=="seleccion"||!t.opciones?.some(n=>n.requisito||n.pide||n.limiteDias))return t;let r=t.opciones.map((n,a)=>{for(let c of n.pide??[]){let d=o.find(u=>u.clave===c);if(!d||["formula","resumen","busqueda","subtabla","boton","autonumero","creado_el","creado_por","modificado_el","modificado_por"].includes(d.tipo))throw i(`\xAB${t.etiqueta}\xBB, \xAB${n.etiqueta}\xBB: pide \xAB${c}\xBB, que no es un campo que se rellene.`)}if(!n.requisito)return n;let s;try{s=ti([...o,pw(t.clave,a,n.requisito.formula)]).at(-1)}catch(c){throw i(`\xAB${t.etiqueta}\xBB, \xAB${n.etiqueta}\xBB: ${c instanceof Error?c.message:"la f\xF3rmula no vale"}`)}if(s.origen?.tipo!=="booleano")throw i(`\xAB${t.etiqueta}\xBB, \xAB${n.etiqueta}\xBB: el requisito tiene que dar s\xED o no.`);return{...n,requisito:{...n.requisito,formula:s.formula}}});return{...t,opciones:r}})}var jm,dw,pw,Am=m(()=>{R();ri();Cm();jm=5,dw=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),pw=(e,o,t)=>({clave:`etapa_${e}_${o}`,etiqueta:`Requisito ${o+1}`,tipo:"formula",formula:t})});function Rm(e){if(e==null)return;if(!Array.isArray(e)||e.length>Em)throw i(`\xABplantillas_hijos\xBB: hasta ${Em}.`);let o=new Set,t=e.map((r,n)=>{let a=`Plantilla de hijos ${n+1}`;if(!Ns(r))throw i(`${a}: un objeto.`);for(let d of Object.keys(r))if(!["clave","nombre","cuando","subtabla","modulo","via","registros"].includes(d))throw i(`${a}: clave no admitida \xAB${d.slice(0,40)}\xBB.`);if(typeof r.clave!="string"||!ci.test(r.clave)||o.has(r.clave))throw i(`${a}: \xABclave\xBB (min\xFAsculas y _), sin repetir.`);if(o.add(r.clave),typeof r.nombre!="string"||!r.nombre.trim()||r.nombre.length>60)throw i(`${a}: el nombre (1\u201360).`);let s=r.cuando===void 0?[]:r.cuando;if(!Array.isArray(s)||s.length>3)throw i(`${a}: \xABcuando\xBB, hasta 3 condiciones.`);let c={clave:r.clave,nombre:r.nombre.trim(),cuando:s.map(d=>{if(!Ns(d)||typeof d.campo!="string"||!ci.test(d.campo)||!(typeof d.valor=="string"||typeof d.valor=="boolean"))throw i(`${a}: cada condici\xF3n, {campo, valor}.`);return{campo:d.campo,valor:d.valor}}),registros:[]};if(typeof r.subtabla=="string"&&r.subtabla){if(!ci.test(r.subtabla))throw i(`${a}: \xABsubtabla\xBB no v\xE1lida.`);c.subtabla=r.subtabla}else{if(typeof r.modulo!="string"||!/^mod_(?!sub_)[a-z][a-z0-9_]{0,40}$/.test(r.modulo)||typeof r.via!="string"||!ci.test(r.via))throw i(`${a}: una \xABsubtabla\xBB de este m\xF3dulo, o un \xABmodulo\xBB (mod_<clave>) y su relaci\xF3n \xABvia\xBB con este.`);c.modulo=r.modulo,c.via=r.via}if(!Array.isArray(r.registros)||!r.registros.length||r.registros.length>qm)throw i(`${a}: \xABregistros\xBB, de 1 a ${qm}.`);return c.registros=r.registros.map(d=>{if(!Ns(d)||JSON.stringify(d).length>4e3)throw i(`${a}: cada registro, un objeto (de hasta 4000 caracteres).`);return d}),c});return t.length?t:void 0}var Em,qm,ci,Ns,km=m(()=>{R();Em=10,qm=50,ci=/^[a-z][a-z0-9_]{0,40}$/,Ns=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)});function zr(e){let o=new Map(Dr(e)?Bp(e).campos.map(a=>[a.clave,a.etiqueta]):[]),t={ubicacion:"Ubicaci\xF3n",nif:"Identificador fiscal",birthday:"Fecha de nacimiento",iban:"IBAN",province:"Provincia",state_abbr:"Provincia",has_newsletter:"Comunicaciones"},r=(Lp.find(a=>a.clave===e)?.campos??[]).map(a=>({...a,...o.has(a.clave)?{etiqueta:o.get(a.clave)}:Object.hasOwn(t,a.clave)?{etiqueta:to(To(),t[a.clave])}:{}})),n=Dr(e)?gw(e).map(a=>({...a,etiqueta:to(To(),a.etiqueta),editable:!1,ordenable:!1,filtrable:!1,enTabla:!1})):[];return[...r,...n,...e==="companies"?fw.map(a=>({...a,etiqueta:to(To(),a.etiqueta),editable:!1,ordenable:!1,filtrable:!1,enTabla:!1})):[]]}var Dr,mw,fw,hw,gw,ni=m(()=>{Dp();Up();on();Dr=e=>e==="contacts"||e==="companies",mw=[{clave:"nombre",tipo:"texto",etiqueta:"Nombre completo"},{clave:"direccion",tipo:"texto",etiqueta:"Direcci\xF3n completa"},{clave:"correo",tipo:"correo",etiqueta:"Primer correo"},{clave:"correo_trabajo",tipo:"correo",etiqueta:"Correo del trabajo"},{clave:"correo_personal",tipo:"correo",etiqueta:"Correo personal"},{clave:"telefono",tipo:"telefono",etiqueta:"Primer tel\xE9fono"},{clave:"telefono_trabajo",tipo:"telefono",etiqueta:"Tel\xE9fono del trabajo"},{clave:"telefono_personal",tipo:"telefono",etiqueta:"Tel\xE9fono personal"}],fw=[{clave:"persona.first_name",tipo:"texto",etiqueta:"Nombre"},{clave:"persona.last_name",tipo:"texto",etiqueta:"Apellidos"},{clave:"persona.correo",tipo:"correo",etiqueta:"Correo"},{clave:"persona.telefono",tipo:"telefono",etiqueta:"Tel\xE9fono"}],hw=[{clave:"persona_referencia_id",tipo:"relacion",etiqueta:"Persona de referencia",relacion:"contacts"},{clave:"persona_first_name",tipo:"texto",etiqueta:"Nombre de la persona"},{clave:"persona_last_name",tipo:"texto",etiqueta:"Apellidos de la persona"},{clave:"persona_correo",tipo:"correo",etiqueta:"Correo de la persona"},{clave:"persona_telefono",tipo:"telefono",etiqueta:"Tel\xE9fono de la persona"}],gw=e=>[...mw.filter(o=>e==="contacts"||["nombre","direccion"].includes(o.clave)),...e==="companies"?hw:[]]});function Pm(e,o,t){let r=(a,s,c,d)=>{if(a.tipo!=="busqueda"||a.archivado)return a;let u=`${c}.${a.clave}`;if(d.length>=2||d.includes(u))throw i(`\xAB${a.etiqueta}\xBB: solo se encadena una b\xFAsqueda a un nivel.`);let p=s.find(b=>b.clave===a.desde&&!b.archivado&&b.tipo==="relacion");if(!p?.relacion)return a;let f=p.relacion,h;if(f.startsWith("mod_")){let b=f.slice(4),v=b===o?e:t?.get(b);if(!v)return a;if(h=v.find(w=>w.clave===a.campo&&!w.archivado),!h)throw i(`\xAB${a.etiqueta}\xBB: el campo que trae ya no existe al otro lado.`);h=r(h,v,b,[...d,u])}else{let b=zr(f).find(v=>v.clave===a.campo)??t?.get(`@${f}`)?.find(v=>v.clave===a.campo&&!v.archivado);if(!b&&Ee(a.campo)&&!t?.has(`@${f}`))return a;if(!b)throw i(`\xAB${a.etiqueta}\xBB: ese campo no existe en ${f}.`);h={clave:a.campo,etiqueta:a.etiqueta,tipo:b.tipo,...Array.isArray(b.opciones)?{opciones:b.opciones}:{},...b.relacion?{relacion:b.relacion}:{},..."origen"in b&&b.origen?{origen:b.origen}:{}}}if(h.tipo==="archivos")throw i(`\xAB${a.etiqueta}\xBB: los ficheros no se traen en una b\xFAsqueda.`);if(h.tipo==="secreto")throw i(`\xAB${a.etiqueta}\xBB: un secreto no se trae en una b\xFAsqueda.`);if(h.tipo==="formula")throw i(`\xAB${a.etiqueta}\xBB: una f\xF3rmula no se trae en una b\xFAsqueda.`);if(h.tipo==="busqueda"){let b=h.origen;if(!b)throw i(`\xAB${a.etiqueta}\xBB: el campo que trae no est\xE1 listo.`);if(b.encadenada)throw i(`\xAB${a.etiqueta}\xBB: solo se encadena una b\xFAsqueda a un nivel.`);return{...a,origen:{...b,encadenada:!0}}}return{...a,origen:{tipo:h.tipo,...h.opciones?{opciones:h.opciones}:{},...h.relacion?{relacion:h.relacion}:{}}}},n=e.map(a=>r(a,e,o,[]));return bw(n),n}function bw(e){let o=new Set(["texto","texto_largo","correo","telefono","url","codigo","numero","importe","porcentaje","fecha","fecha_hora","booleano"]);for(let t of e.filter(r=>!r.archivado&&r.tipo==="busqueda"&&r.siVacio)){let r=e.find(a=>a.clave===t.siVacio&&!a.archivado),n=a=>!e.find(s=>s.clave===a.desde)?.multiple;if(!r||r===t||r.tipo!=="busqueda"||r.siVacio||!n(t)||!n(r)||!t.origen||!r.origen||!o.has(t.origen.tipo)||t.origen.tipo!==r.origen.tipo||t.origen.encadenada||r.origen.encadenada)throw i("La alternativa necesita otra b\xFAsqueda escalar del mismo tipo, sin cadenas.")}}var Tm=m(()=>{Lr();R();ni()});function Ee(e){if(typeof e!="string"||!/^datos\.[a-z][a-z0-9_]{0,40}$/.test(e))return null;let o=e.slice(6);return o==="tipos"?null:o}function Mm(e,o,t){let r=n=>{let a=Object.hasOwn(o,n.campo)?Ee(o[n.campo]):null;if(!a)throw i("La condici\xF3n del campo propio necesita otro campo propio de la misma ra\xEDz.");return{...n,campo:a}};return e.filter(n=>!n.archivado&&Object.hasOwn(o,n.clave)&&Ee(o[n.clave])).map(n=>{if(n.tipo==="relacion"&&(Object.keys(n.copiar??{}).length||n.mostrarTareasEnFichaRelacionada||n.alBorrar&&n.alBorrar!=="avisar")||n.porDefecto||n.depende||n.completarDesde||n.alMarcar||n.embudo||n.opciones?.some(u=>u.requisito||u.pide?.length||u.limiteDias!==void 0||u.aprobacion))throw i("El campo propio necesita conservar sus reglas antes de convertir la ra\xEDz.");let s=[{campo:"tipos",op:"igual",valor:t},...(n.visibleSi??[]).map(r)];if(s.length>10)throw i("El campo propio supera las diez condiciones al a\xF1adir su tipo.");let c=n.tipo==="busqueda"?Ee(o[n.desde??""]):null,d=n.siVacio?Ee(o[n.siVacio]):null;if(n.tipo==="busqueda"&&(!c||n.siVacio&&!d))throw i("La b\xFAsqueda propia necesita relaciones y alternativas propias de la misma ra\xEDz.");return{...structuredClone(n),...c?{desde:c}:{},...d?{siVacio:d}:{},clave:Ee(o[n.clave]),visibleSi:s,...n.obligatorioSi?{obligatorioSi:n.obligatorioSi.map(r)}:{}}})}var Lr=m(()=>{R()});function Im(e,o){if(e==null)return;if(!Fr(e))throw i("\xABerp\xBB: un objeto.");let t=(n,a,s=!1)=>{if(!(n===void 0&&s)){if(typeof n!="string"||!o.some(c=>c.clave===n&&c.tipo!=="subtabla"))throw i(`ERP: \xAB${a}\xBB no es un campo del m\xF3dulo.`);return n}},r={};if(e.presupuesto!==void 0){let n=e.presupuesto;if(!Fr(n)||!Fr(n.lineas))throw i("ERP: \xABpresupuesto\xBB con \xABcliente\xBB y \xABlineas\xBB.");let a=o.find(d=>d.clave===n.lineas.subtabla&&d.tipo==="subtabla");if(!a)throw i("ERP: \xABlineas.subtabla\xBB no es una subtabla del m\xF3dulo.");let s=n.lineas,c=(d,u,p=!1)=>{if(!(d===void 0&&p)){if(typeof d!="string"||!(a.columnas??[]).some(f=>f.clave===d))throw i(`ERP: \xAB${u}\xBB no es una columna de la subtabla.`);return d}};if(s.articulo!==void 0&&!(a.columnas??[]).some(d=>d.clave===s.articulo&&d.tipo==="articulo"))throw i("ERP: \xABarticulo\xBB, una columna de art\xEDculo de la subtabla.");if(n.tipo!==void 0&&n.tipo!=="presupuesto"&&n.tipo!=="factura")throw i("ERP: \xABtipo\xBB, presupuesto o factura.");if(n.clienteAlternativo!==void 0&&n.clienteAlternativo===n.cliente)throw i("ERP: las relaciones de cliente deben ser distintas.");r.presupuesto={...n.tipo?{tipo:n.tipo}:{},cliente:t(n.cliente,"cliente"),...n.clienteAlternativo!==void 0?{clienteAlternativo:t(n.clienteAlternativo,"clienteAlternativo")}:{},lineas:{subtabla:a.clave,descripcion:c(s.descripcion,"descripcion"),precio:c(s.precio,"precio"),...s.cantidad!==void 0?{cantidad:c(s.cantidad,"cantidad")}:{},...s.iva!==void 0?{iva:c(s.iva,"iva")}:{},...s.articulo!==void 0?{articulo:s.articulo}:{}}}}if(e.gasto!==void 0){let n=e.gasto;if(!Fr(n))throw i("ERP: \xABgasto\xBB, un objeto.");if(n.tipo!==void 0&&n.tipo!=="factura"&&n.tipo!=="ticket")throw i("ERP: el gasto es factura o ticket.");r.gasto={...n.tipo?{tipo:n.tipo}:{},proveedor:t(n.proveedor,"proveedor"),fecha:t(n.fecha,"fecha"),base:t(n.base,"base"),...n.nif!==void 0?{nif:t(n.nif,"nif")}:{},...n.numero!==void 0?{numero:t(n.numero,"numero")}:{},...n.iva!==void 0?{iva:t(n.iva,"iva")}:{}}}if(e.horas!==void 0){let n=e.horas;if(!Fr(n))throw i("ERP: \xABhoras\xBB, un objeto.");let a=t(n.guardarEn,"guardarEn",!0);if(a&&!o.some(s=>s.clave===a&&["numero","duracion"].includes(s.tipo)))throw i("ERP: \xABguardarEn\xBB, un campo num\xE9rico.");r.horas={desde:t(n.desde,"desde"),hasta:t(n.hasta,"hasta"),...n.persona!==void 0?{persona:t(n.persona,"persona")}:{},...a?{guardarEn:a}:{}}}return Object.keys(r).length?r:void 0}var Fr,Lm=m(()=>{R();Fr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)});function zm(e,o){if(e==null)return;if(!xt(e))throw i("\xABimpresion\xBB: un objeto.");let{ejemplares:t,cuerpo:r,...n}=e;if(n.subtabla!==void 0)throw i("Impresi\xF3n: clave no admitida \xABsubtabla\xBB.");let a=Wr(n,o)??{},s=tr(r,"El texto del documento",Fm);if(s){for(let c of s.matchAll(/\{\{\s*([^}]*?)\s*\}\}/g)){let d=c[1];if(d!=="hoy"&&!/^padre\.[a-z][a-z0-9_]{0,40}$/.test(d)&&!o.some(u=>u.clave===d&&!u.archivado))throw i(`El texto del documento: \xAB{{${d.slice(0,40)}}}\xBB no es una columna de la l\xEDnea ni \xABpadre.<campo>\xBB.`)}a.cuerpo=s}if(t!=null){if(!Array.isArray(t)||t.length>3||t.some(c=>typeof c!="string"||!c.trim()||c.length>60))throw i("\xABejemplares\xBB: hasta 3, cada uno con su r\xF3tulo (hasta 60).");t.length&&(a.ejemplares=t.map(c=>c.trim()))}return Object.keys(a).length?a:void 0}function li(e,o,t){for(let r of Object.keys(e))if(!o.includes(r))throw i(`${t}: clave no admitida \xAB${r.slice(0,40)}\xBB.`)}function tr(e,o,t){if(!(e==null||e==="")){if(typeof e!="string"||e.length>t)throw i(`${o}: texto de hasta ${t} caracteres.`);return e.trim()||void 0}}function $t(e,o,t,r,n=()=>!0){if(e==null)return;if(!Array.isArray(e)||e.length>t||!e.every(s=>typeof s=="string"))throw i(`${r}: hasta ${t} claves de campo.`);let a=new Set(o.filter(s=>!s.archivado&&n(s)).map(s=>s.clave));return[...new Set(e)].filter(s=>a.has(s))}function ui(e,o){if(e==null)return;if(!xt(e))throw i("\xABficha\xBB: un objeto.");li(e,["cabecera","columnas","pestanas","relacionadas","erp","sin_conexion","rapido","duplicados","tarjeta","en_crear","filtros","principal","plegar_vacios"],"Ficha");let t={},r=$t(e.cabecera,o,4,"La cabecera",p=>!["subtabla","boton","archivos","texto_largo"].includes(p.tipo));if(r?.length&&(t.cabecera=r),e.columnas!==void 0){if(e.columnas!==1&&e.columnas!==2&&e.columnas!==3)throw i("\xABcolumnas\xBB: 1, 2 o 3.");e.columnas>1&&(t.columnas=e.columnas)}if(e.pestanas!==void 0){if(!Array.isArray(e.pestanas)||e.pestanas.length>6)throw i("Hasta 6 pesta\xF1as.");let p=e.pestanas.map((f,h)=>{if(!xt(f))throw i(`Pesta\xF1a ${h+1}: un objeto.`);li(f,["titulo","secciones","artefacto"],`Pesta\xF1a ${h+1}`);let b=tr(f.titulo,`Pesta\xF1a ${h+1}`,40);if(!b)throw i(`Pesta\xF1a ${h+1}: falta el t\xEDtulo.`);if(f.artefacto!==void 0){let v=Number(f.artefacto);if(!Number.isSafeInteger(v)||v<1)throw i(`Pesta\xF1a ${h+1}: el artefacto no es v\xE1lido.`);return{titulo:b,secciones:[],artefacto:v}}if(!Array.isArray(f.secciones)||f.secciones.length>20||!f.secciones.every(v=>typeof v=="string"&&v.length<=60))throw i(`Pesta\xF1a ${h+1}: sus secciones, hasta 20.`);return{titulo:b,secciones:[...new Set(f.secciones)]}});p.length&&(t.pestanas=p)}if(e.relacionadas!==void 0){if(e.relacionadas!=="abajo"&&e.relacionadas!=="pestana")throw i("\xABrelacionadas\xBB: abajo o pestana.");e.relacionadas==="pestana"&&(t.relacionadas="pestana")}let n=Im(e.erp,o);if(n&&(t.erp=n),e.sin_conexion!==void 0){if(typeof e.sin_conexion!="boolean")throw i("\xABsin_conexion\xBB: s\xED o no.");e.sin_conexion&&(t.sin_conexion=!0)}let a=$t(e.rapido,o,3,"El registro r\xE1pido",p=>!["subtabla","boton","archivos","firma","busqueda","resumen","formula","autonumero","creado_el","creado_por","modificado_el","modificado_por"].includes(p.tipo));a?.length&&(t.rapido=a);let s=$t(e.duplicados,o,3,"Los campos de duplicados",p=>ww.includes(p.tipo));s?.length&&(t.duplicados=s);let c=$t(e.tarjeta,o,3,"La tarjeta",p=>!["subtabla","boton","archivos","texto_largo","firma"].includes(p.tipo));if(c?.length&&(t.tarjeta=c),e.en_crear!==void 0){if(typeof e.en_crear!="boolean")throw i("\xABen_crear\xBB: s\xED o no.");e.en_crear&&(t.en_crear=!0)}let d=$t(e.filtros,o,4,"Los filtros de arriba",p=>vw.includes(p.tipo));d?.length&&(t.filtros=d);let u=$t(e.principal,o,8,"El contenido principal",p=>p.tipo!=="boton");if(u?.length&&(t.principal=u),e.plegar_vacios!==void 0){if(typeof e.plegar_vacios!="boolean")throw i("\xABplegar_vacios\xBB: s\xED o no.");e.plegar_vacios||(t.plegar_vacios=!1)}return Object.keys(t).length?t:void 0}function Wr(e,o){if(e==null)return;if(!xt(e))throw i("\xABimpresion\xBB: un objeto.");li(e,["titulo","campos","subtabla","pie","logo","orientacion","cuerpo","color","firmas"],"Impresi\xF3n");let t={},r=tr(e.titulo,"El t\xEDtulo de la impresi\xF3n",80);r&&(t.titulo=r);let n=$t(e.campos,o,40,"Los campos de la impresi\xF3n",c=>!["subtabla","boton"].includes(c.tipo));if(n?.length&&(t.campos=n),e.subtabla!==void 0&&e.subtabla!==null&&e.subtabla!==""){if(typeof e.subtabla!="string")throw i("\xABsubtabla\xBB: la clave de una subtabla.");o.some(c=>c.clave===e.subtabla&&c.tipo==="subtabla"&&!c.archivado)&&(t.subtabla=e.subtabla)}let a=tr(e.pie,"El pie de la impresi\xF3n",500);if(a&&(t.pie=a),e.logo!==void 0){if(typeof e.logo!="boolean")throw i("\xABlogo\xBB: s\xED o no.");e.logo&&(t.logo=!0)}if(e.orientacion!==void 0){if(e.orientacion!=="vertical"&&e.orientacion!=="horizontal")throw i("\xABorientacion\xBB: vertical u horizontal.");e.orientacion==="horizontal"&&(t.orientacion="horizontal")}let s=tr(e.cuerpo,"El texto del documento",Fm);if(s){for(let c of s.matchAll(/\{\{\s*([^}]*?)\s*\}\}/g)){let d=c[1];if(d!=="hoy"&&!o.some(u=>u.clave===d&&!u.archivado))throw i(`El texto del documento: \xAB{{${d.slice(0,40)}}}\xBB no es un campo del m\xF3dulo.`)}t.cuerpo=s}if(e.color!==void 0&&e.color!==null&&e.color!==""){if(typeof e.color!="string"||!/^#[0-9a-fA-F]{6}$/.test(e.color))throw i("\xABcolor\xBB: #rrggbb.");t.color=e.color.toLowerCase()}if(e.firmas!==void 0&&e.firmas!==null){if(!Array.isArray(e.firmas)||e.firmas.length>4||e.firmas.some(c=>typeof c!="string"||!c.trim()||c.length>60))throw i("\xABfirmas\xBB: hasta 4 casillas, cada una con su texto (hasta 60).");e.firmas.length&&(t.firmas=e.firmas.map(c=>c.trim()))}return Object.keys(t).length?t:void 0}function $s(e,o=0){return o>10?!1:Array.isArray(e)?e.every(t=>$s(t,o+1)):xt(e)?Object.keys(e).every(t=>!yw.has(t)&&$s(e[t],o+1)):!0}function Wm(e){if(e==null)return;if(!Array.isArray(e)||e.length>10)throw i("\xABvistas\xBB: hasta 10.");let o=e.map((t,r)=>{if(!xt(t))throw i(`Vista ${r+1}: un objeto.`);li(t,["nombre","tipo","config"],`Vista ${r+1}`);let n=tr(t.nombre,`Vista ${r+1}`,60);if(!n)throw i(`Vista ${r+1}: falta el nombre.`);if(typeof t.tipo!="string"||!Dm.includes(t.tipo))throw i(`Vista ${r+1}: tipo ${Dm.join(", ")}.`);if(t.config!==void 0&&(!xt(t.config)||!$s(t.config)||JSON.stringify(t.config).length>4e3))throw i(`Vista ${r+1}: \xABconfig\xBB, un objeto de hasta 4 KB.`);return{nombre:n,tipo:t.tipo,...t.config?{config:t.config}:{}}});return o.length?o:void 0}var xt,ww,vw,Fm,Dm,yw,xs=m(()=>{R();Lm();xt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);ww=["texto","correo","telefono","codigo","url"],vw=["seleccion","seleccion_multiple","etiquetas","booleano","hecho","creado_por","modificado_por","relacion","texto","texto_largo","correo","telefono","url","codigo","autonumero","ubicacion","numero","importe","porcentaje","fecha","fecha_hora","duracion","valoracion"];Fm=12e3;Dm=["kanban","calendario","linea","mapa","galeria","tablero","cuadrante","dia"],yw=new Set(["__proto__","constructor","prototype"])});var Br,Bm=m(()=>{Br=e=>e==="@contacts"||e==="@companies"});function mi(e,o){if(e==null)return;if(!Array.isArray(e)||e.length>di)throw i(`\xABrelacionadas\xBB: hasta ${di} columnas.`);if(!e.length)return;let t=new Set;return e.map((r,n)=>{let a=`Columna relacionada ${n+1}`;if(!js(r))throw i(`${a}: un objeto.`);Vm(r,["clave","etiqueta","via","campo","de","calculo","filtro","siVacio"],a);let s=Ct(r.clave,`${a}.clave`);if(t.has(s)||o.some(u=>u.clave===s))throw i(`${a}: la clave \xAB${s}\xBB ya la usa otra columna o un campo.`);if(t.add(s),typeof r.etiqueta!="string"||!r.etiqueta.trim()||r.etiqueta.length>80)throw i(`${a}: \xABetiqueta\xBB, de 1 a 80 caracteres.`);let c=Br(String(r.de))&&typeof r.via=="string"&&/^datos\.[a-z][a-z0-9_]{0,40}$/.test(r.via)?r.via:Ct(r.via,`${a}.via`);if(r.de!==void 0){if(r.siVacio!==void 0)throw i("\xABsiVacio\xBB solo se admite al traer un valor escalar.");let u=typeof r.de=="string"&&Br(r.de)?r.de:Ct(r.de,`${a}.de`);if(typeof r.calculo!="string"||!Um.includes(r.calculo))throw i(`${a}: \xABcalculo\xBB, uno de ${Um.join(", ")}.`);let p=r.calculo,f=p==="recuento"?void 0:Br(u)&&typeof r.campo=="string"&&/^datos\.[a-z][a-z0-9_]{0,40}$/.test(r.campo)?r.campo:Ct(r.campo,`${a}.campo`),h=Ur(r.filtro,a,Br(u));return{clave:s,etiqueta:r.etiqueta.trim(),via:c,de:u,calculo:p,...f?{campo:f}:{},...h?{filtro:h}:{}}}if(r.calculo!==void 0||r.filtro!==void 0)throw i(`${a}: \xABcalculo\xBB y \xABfiltro\xBB solo con \xABde\xBB (los hijos).`);let d=o.find(u=>u.clave===c&&!u.archivado);if(!d||d.tipo!=="relacion")throw i(`${a}: \xAB${c}\xBB no es una relaci\xF3n de este m\xF3dulo.`);if(d.multiple&&r.siVacio!==void 0)throw i("Una colecci\xF3n no tiene alternativa escalar.");if(typeof r.campo!="string"||!/^[a-z][a-z0-9_.]{0,80}$/.test(r.campo))throw i(`${a}: campo no v\xE1lido.`);return{clave:s,etiqueta:r.etiqueta.trim(),via:c,campo:r.campo,...r.siVacio!==void 0?{siVacio:Ct(r.siVacio,`${a}.siVacio`)}:{}}})}function fi(e){if(e==null)return;if(!Array.isArray(e)||e.length>pi)throw i(`\xABsiguientes\xBB: hasta ${pi} pasos.`);if(!e.length)return;let o=new Set;return e.map((t,r)=>{let n=`Siguiente paso ${r+1}`;if(!js(t))throw i(`${n}: un objeto.`);Vm(t,["clave","nombre","destino","enlace","campos"],n);let a=Ct(t.clave,`${n}.clave`);if(o.has(a))throw i(`${n}: \xABclave\xBB repetida.`);if(o.add(a),typeof t.nombre!="string"||!t.nombre.trim()||t.nombre.length>60)throw i(`${n}: el nombre del bot\xF3n (1\u201360).`);if(typeof t.destino!="string"||!/^mod_(?!sub_)[a-z][a-z0-9_]{0,40}$/.test(t.destino))throw i(`${n}: \xABdestino\xBB, mod_<clave>.`);let s=Ct(t.enlace,`${n}.enlace`),c;if(t.campos!==void 0&&t.campos!==null){if(!js(t.campos)||Object.keys(t.campos).length>40)throw i(`${n}: \xABcampos\xBB, un objeto destino \u2192 origen (hasta 40).`);for(let[d,u]of Object.entries(t.campos))if(!Cs.test(d)||typeof u!="string"||!Cs.test(u))throw i(`${n}: \xABcampos.${d.slice(0,40)}\xBB no es v\xE1lido.`);c=t.campos}return{clave:a,nombre:t.nombre.trim(),destino:t.destino,enlace:s,...c&&Object.keys(c).length?{campos:c}:{}}})}var Um,di,pi,Cs,js,Vm,Ct,hi=m(()=>{Bm();R();Vr();Um=["recuento","suma","minimo","maximo","ultimo","media"],di=20,pi=5,Cs=/^[a-z][a-z0-9_]{0,40}$/,js=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Vm=(e,o,t)=>{for(let r of Object.keys(e))if(!o.includes(r))throw i(`${t}: clave no admitida \xAB${r.slice(0,40)}\xBB.`)},Ct=(e,o)=>{if(typeof e!="string"||!Cs.test(e))throw i(`${o}: falta o no es v\xE1lido.`);return e}});function Os(e,o){if(e===void 0)return;if(!e||typeof e!="object"||Array.isArray(e))throw i("La configuraci\xF3n de ra\xEDces necesita objetos expl\xEDcitos.");let t={};for(let[r,n]of Object.entries(e)){if(!["contacts","companies"].includes(r)||!n||typeof n!="object"||Array.isArray(n))throw i("La configuraci\xF3n de ra\xEDces necesita contacts o companies.");let a={};for(let[s,c]of Object.entries(n)){if(!["ficha","impresion","relacionadas","siguientes","recurso","reserva"].includes(s))throw i("Configura ficha, impresi\xF3n, relacionadas, siguientes, recurso o reserva.");Object.assign(a,{[s]:(s==="ficha"?ui(c,o):s==="impresion"?Wr(c,o):s==="relacionadas"?mi(c,o):s==="recurso"?ii(c,o):s==="reserva"?ai(c,o):fi(c))??null})}t[r]=a}return t}var Qm=m(()=>{_s();R();xs();hi()});function Gm(e){if(e!==void 0){if(!e||typeof e!="object"||Array.isArray(e))throw i("Los ajustes nativos necesitan objetos expl\xEDcitos.");for(let[o,t]of Object.entries(e))if(!["contacts","companies"].includes(o)||!t||typeof t!="object"||Array.isArray(t)||Object.keys(t).some(r=>!Ss.includes(r)))throw i("Un ajuste nativo no cambia la identidad de la relaci\xF3n.");return structuredClone(e)}}var Ss,As=m(()=>{R();Ss=["etiqueta","ayuda","enTabla","obligatorio","visibleSi","obligatorioSi","permisos","siVacio","completarDesde"]});function Hm(e,o,t={}){for(let[n,a]of Object.entries(t)){let s=e.find(u=>u.clave===n&&!u.archivado),c=o[n],d=s?.opciones??[];if(s?.tipo!=="seleccion"||!c||!Object.hasOwn(Es,c)||Object.keys(a).length!==d.length||!d.length||d.some(u=>!Object.hasOwn(a,u.valor))||Object.values(a).some(u=>typeof u!="string"||!u||u!==u.trim())||new Set(Object.values(a)).size!==d.length)throw i("Las conversiones nativas necesitan un mapa de selecciones completo.")}let r=new Map;for(let n of e){let a=o[n.clave];if(n.archivado||n.tipo!=="seleccion"||!a||!Object.hasOwn(Es,a))continue;let s=Es[a];if(n.opciones?.some(c=>c.hecho||c.requisito||c.pide?.length||c.limiteDias!==void 0||c.aprobacion))throw i("Las opciones de Personas/Empresas no pueden perder reglas de etapas.");r.set(s,Ir(s,(n.opciones??[]).map(c=>({value:Object.hasOwn(t,n.clave)?t[n.clave][c.valor]:c.valor,label:c.etiqueta,...c.color?{color:c.color}:{}}))))}return r}var Es,Xm=m(()=>{R();ls();Es={sector:"companySectors",forma_juridica:"legalForms"}});function Rs(e,o){if(e===void 0)return;if(!Eo(e))throw i("\xABpersonas\xBB: un objeto.");if(qs(e,["objeto","tipo","de","etiqueta","plural","icono","campos","conversiones","alternativa","clasificacion","configuracion"],"\xABpersonas\xBB"),e.alternativa!==void 0||e.clasificacion!==void 0)return Nw(e,o);if(e.objeto==="deals"&&o.some(p=>p.tipo==="autonumero"))throw i("Los auton\xFAmeros propios no est\xE1n disponibles en Oportunidades.");if(e.objeto==="deals"&&o.some(p=>p.unico))throw i("Los campos propios \xFAnicos no est\xE1n disponibles en Oportunidades.");if(e.objeto!=="contacts"&&e.objeto!=="companies")throw i("\xABpersonas.objeto\xBB: contacts o companies.");let t=gi(e.tipo,"tipo",60);if(!_w.test(t))throw i("\xABpersonas.tipo\xBB: una clave de tipo.");if(e.de!==void 0&&e.de!=="cliente"&&e.de!=="proveedor")throw i("\xABpersonas.de\xBB: cliente o proveedor.");if(e.de===t||(t==="cliente"||t==="proveedor")&&e.de!==void 0)throw i("\xABpersonas.de\xBB: un tipo base no puede ser un subtipo.");let r=gi(e.icono,"icono",40);if(!/^[a-z0-9-]+$/.test(r))throw i("\xABpersonas.icono\xBB: una clave de icono.");if(!Eo(e.campos))throw i("\xABpersonas.campos\xBB: un mapa expl\xEDcito de campos nativos.");let n={},a=new Map;for(let[p,f]of Object.entries(e.campos)){let h=o.find(w=>w.clave===p&&!w.archivado),b=typeof f=="string"&&Object.hasOwn(Km[e.objeto],f)?Km[e.objeto][f]:void 0,v=Ee(f);if(!h||!(v?Fp.has(h.tipo):b?.includes(h.tipo)))throw i(`\xABpersonas.campos.${p.slice(0,40)}\xBB: campo nativo o tipo incompatible.`);if(h.unico&&typeof f=="string"&&f.startsWith("persona."))throw i("El campo propio necesita conservar sus reglas antes de convertir la ra\xEDz.");if(a.has(f)&&f!=="nif"&&f!=="tax_identifier")throw i(`\xABpersonas.campos\xBB: dos campos apuntan a \xAB${f}\xBB.`);a.set(f,p),n[p]=f}let s=e.objeto==="contacts"?"first_name":"name";if(!a.has(s))throw i(`\xABpersonas.campos\xBB: falta el nombre nativo \xAB${s}\xBB.`);let c=o.filter(p=>!p.archivado);for(let p of c)if(!Object.hasOwn(n,p.clave)&&p.tipo!=="resumen"&&p.tipo!=="formula")throw i(`\xABpersonas.campos\xBB: falta destino para \xAB${p.clave}\xBB; no se puede perder un campo.`);if(e.conversiones!==void 0&&!Eo(e.conversiones))throw i("Las conversiones nativas necesitan un mapa de selecciones completo.");let d={};for(let[p,f]of Object.entries(e.conversiones??{})){if(!Eo(f)||Object.values(f).some(h=>typeof h!="string"))throw i("Las conversiones nativas necesitan un mapa de selecciones completo.");Object.defineProperty(d,p,{value:{...f},enumerable:!0})}Mm(o,n,t),Hm(o,n,d);let u=Os(e.configuracion,o);if(u&&Object.keys(u).some(p=>p!==e.objeto))throw i("La configuraci\xF3n cita un objeto que esta ra\xEDz no declara.");return{objeto:e.objeto,tipo:t,...e.de?{de:e.de}:{},...u?{configuracion:u}:{},etiqueta:gi(e.etiqueta,"etiqueta",60),plural:gi(e.plural,"plural",60),icono:r,campos:n,...e.conversiones!==void 0?{conversiones:d}:{}}}function Nw(e,o){let t=e.alternativa,r=e.clasificacion;if(e.objeto!=="contacts"||!Eo(t)||t.objeto!=="companies"||!Eo(t.campos)||!Eo(r))throw i("Los destinos dobles necesitan Persona, Empresa y clasificaci\xF3n expl\xEDcita.");qs(t,["objeto","campos","conversiones"],"\xABpersonas.alternativa\xBB"),qs(r,["campo","valores","vacio","formas","etiquetas","propiedad"],"\xABpersonas.clasificacion\xBB");let n=o.find(w=>w.clave===r.campo&&!w.archivado);if(!n||!["seleccion","booleano"].includes(n.tipo)||!Eo(r.valores)||r.vacio!==void 0&&r.vacio!=="contacts"&&r.vacio!=="companies")throw i("La clasificaci\xF3n necesita todas las opciones de una selecci\xF3n o booleano.");if(n.opciones?.some(w=>w.hecho||w.requisito||w.pide?.length||w.limiteDias!==void 0||w.aprobacion))throw i("La clasificaci\xF3n no puede perder permisos ni reglas de etapas.");let a=n.tipo==="booleano"?["true","false"]:(n.opciones??[]).map(w=>w.valor);if(!a.length||Object.keys(r.valores).length!==a.length||a.some(w=>!Object.hasOwn(r.valores,w))||Object.values(r.valores).some(w=>w!=="contacts"&&w!=="companies")||!Object.values(r.valores).includes("contacts")||!Object.values(r.valores).includes("companies"))throw i("La clasificaci\xF3n necesita todas las opciones de una selecci\xF3n o booleano.");let s=Pp(r,n,r.valores),c={campo:n.clave,valores:{...r.valores},...r.vacio?{vacio:r.vacio}:{},...s},{alternativa:d,clasificacion:u,configuracion:p,...f}=e,h=w=>Rs(w,Mp(o,c,w.objeto).filter(g=>Eo(w.campos)&&Object.hasOwn(w.campos,g.clave)||g.tipo==="resumen"||g.tipo==="formula")),b=h(f),v=h({...f,objeto:"companies",campos:t.campos,conversiones:t.conversiones});if(c.propiedad){if(b.campos[n.clave]!==c.propiedad||v.campos[n.clave]!==c.propiedad||b.conversiones?.[n.clave]||v.conversiones?.[n.clave])throw i("La clasificaci\xF3n propia necesita el mismo destino tipado en ambas ramas, sin conversiones.")}else if(Object.hasOwn(b.campos,n.clave)||Object.hasOwn(v.campos,n.clave))throw i("El discriminante de identidad no es un campo nativo.");for(let w of o.filter(g=>!g.archivado&&g.clave!==n.clave&&g.tipo!=="resumen"&&g.tipo!=="formula"))if(!Object.hasOwn(b.campos,w.clave)&&!Object.hasOwn(v.campos,w.clave))throw i("Los destinos deben conservar todos los campos del origen salvo el discriminante.");return Tp(o,c),{...b,alternativa:{objeto:"companies",campos:v.campos,...v.conversiones?{conversiones:v.conversiones}:{}},clasificacion:c,...e.configuracion!==void 0?{configuracion:Os(e.configuracion,o)}:{}}}var Ym,Km,Eo,_w,gi,qs,Zm=m(()=>{Lr();Wp();Qm();R();Ip();Xm();Ym={ubicacion:["ubicacion"],address:["texto","texto_largo"],zipcode:["texto","codigo"],city:["texto"],country:["texto"],pais_fiscal:["texto","seleccion"],iban:["texto"]},Km={contacts:{...Ym,province:["texto"],first_name:["texto"],last_name:["texto"],title:["texto"],correo:["correo"],telefono:["telefono"],background:["texto_largo","texto"],nif:["texto"],birthday:["fecha"],first_seen:["fecha","fecha_hora"],has_newsletter:["booleano"]},companies:{...Ym,state_abbr:["texto"],name:["texto"],razon_social:["texto"],tax_identifier:["texto"],phone_number:["telefono"],website:["url"],description:["texto_largo","texto"],sector:["seleccion","texto"],forma_juridica:["seleccion","texto"],correo_facturacion:["correo"],has_newsletter:["booleano"],"persona.first_name":["texto"],"persona.last_name":["texto"],"persona.correo":["correo"],"persona.telefono":["telefono"]}},Eo=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),_w=/^[a-z0-9][a-z0-9-]{0,59}$/,gi=(e,o,t)=>{if(typeof e!="string"||!e.trim()||e.trim().length>t)throw i(`\xABpersonas.${o}\xBB: texto de 1 a ${t} caracteres.`);return e.trim()},qs=(e,o,t)=>{for(let r of Object.keys(e))if(!o.includes(r))throw i(`${t}: clave no admitida \xAB${r.slice(0,40)}\xBB.`)}});function tf(e){if(e==null)return;if(!Array.isArray(e)||e.length>ef)throw i(`\xABconversiones\xBB: hasta ${ef}.`);let o=new Set,t=e.map((r,n)=>{let a=`Conversi\xF3n ${n+1}`;if(!bi(r))throw i(`${a}: un objeto.`);for(let c of Object.keys(r))if(!["clave","nombre","destino","campos","enlaceDestino","enlaceOrigen","lineas","etapa"].includes(c))throw i(`${a}: clave no admitida \xAB${c.slice(0,40)}\xBB.`);if(typeof r.clave!="string"||!jt.test(r.clave)||o.has(r.clave))throw i(`${a}: \xABclave\xBB (min\xFAsculas y _), sin repetir.`);if(o.add(r.clave),typeof r.nombre!="string"||!r.nombre.trim()||r.nombre.length>60)throw i(`${a}: el nombre del bot\xF3n (1\u201360).`);if(typeof r.destino!="string"||!($w.includes(r.destino)||/^mod_(?!sub_)[a-z][a-z0-9_]{0,40}$/.test(r.destino)))throw i(`${a}: \xABdestino\xBB, contacts, companies, deals o mod_<clave>.`);let s={clave:r.clave,nombre:r.nombre.trim(),destino:r.destino,campos:of(r.campos,a)};for(let c of["enlaceDestino","enlaceOrigen"])if(!(r[c]===void 0||r[c]===null||r[c]==="")){if(typeof r[c]!="string"||!jt.test(r[c]))throw i(`${a}: \xAB${c}\xBB no es un campo v\xE1lido.`);s[c]=r[c]}if(r.lineas!==void 0){if(!Array.isArray(r.lineas)||r.lineas.length>5)throw i(`${a}: \xABlineas\xBB, hasta 5.`);s.lineas=r.lineas.map(c=>{if(!bi(c)||typeof c.desde!="string"||!jt.test(c.desde)||typeof c.a!="string"||!jt.test(c.a))throw i(`${a}: cada \xABlineas\xBB, {desde, a, campos}.`);return{desde:c.desde,a:c.a,campos:of(c.campos,a)}})}if(r.etapa!==void 0&&r.etapa!==null){if(!bi(r.etapa)||typeof r.etapa.campo!="string"||!jt.test(r.etapa.campo)||typeof r.etapa.valor!="string")throw i(`${a}: \xABetapa\xBB, {campo, valor}.`);s.etapa={campo:r.etapa.campo,valor:r.etapa.valor}}return s});return t.length?t:void 0}var ef,jt,$w,bi,of,rf=m(()=>{R();ef=5,jt=/^[a-z][a-z0-9_]{0,40}$/,$w=["contacts","companies","deals"],bi=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),of=(e,o)=>{if(e===void 0)return{};if(!bi(e)||Object.keys(e).length>100)throw i(`${o}: \xABcampos\xBB, un objeto destino \u2192 origen.`);for(let[t,r]of Object.entries(e))if(!jt.test(t)||typeof r!="string"||!jt.test(r))throw i(`${o}: el campo \xAB${t.slice(0,40)}\xBB no es v\xE1lido.`);return e}});function sf(e,o){if(e==null)return;if(!Array.isArray(e)||e.length>nf)throw i(`\xABencadenar\xBB: hasta ${nf}.`);let t=new Set,r=e.map((n,a)=>{let s=`\xABencadenar\xBB ${a+1}`;if(!Ot(n))throw i(`${s}: un objeto.`);for(let g of Object.keys(n))if(!["clave","nombre","destino","enlace","campos","lineas","estado","no_cuentan","permitir_exceso","juntar"].includes(g))throw i(`${s}: clave no admitida \xAB${g.slice(0,40)}\xBB.`);let c=Go(n.clave,`${s}.clave`);if(t.has(c))throw i(`${s}: \xABclave\xBB repetida.`);if(c==="juntar")throw i(`${s}: \xABjuntar\xBB no vale como clave.`);if(t.add(c),typeof n.nombre!="string"||!n.nombre.trim()||n.nombre.length>60)throw i(`${s}: el nombre del bot\xF3n (1\u201360).`);if(typeof n.destino!="string"||!/^mod_(?!sub_)[a-z][a-z0-9_]{0,40}$/.test(n.destino))throw i(`${s}: \xABdestino\xBB, mod_<clave>.`);if(!Ot(n.lineas))throw i(`${s}: \xABlineas\xBB {desde, a, cantidad: {origen, destino}}.`);let d=n.lineas,u=Go(d.desde,`${s}.lineas.desde`),p=Cw(o,u);if(!p)throw i(`${s}: \xAB${u}\xBB no es una subtabla de este m\xF3dulo.`);if(!Ot(d.cantidad))throw i(`${s}: \xABlineas.cantidad\xBB {origen, destino}.`);let f=Go(d.cantidad.origen,`${s}.lineas.cantidad.origen`),h=(p.columnas??[]).find(g=>g.clave===f&&!g.archivado);if(!h||!(xw.includes(h.tipo)||h.tipo==="formula"&&h.origen?.tipo==="numero"))throw i(`${s}: la cantidad \xAB${f}\xBB tiene que ser una columna num\xE9rica de \xAB${u}\xBB.`);let b={clave:c,nombre:n.nombre.trim(),destino:n.destino,enlace:Go(n.enlace,`${s}.enlace`),lineas:{desde:u,a:Go(d.a,`${s}.lineas.a`),cantidad:{origen:f,destino:Go(d.cantidad.destino,`${s}.lineas.cantidad.destino`)}}},v=af(d.campos,`${s}.lineas.campos`);if(v){for(let g of Object.values(v))if(!(p.columnas??[]).some(y=>y.clave===g&&!y.archivado))throw i(`${s}: \xAB${g}\xBB no es una columna de \xAB${u}\xBB.`);b.lineas.campos=v}let w=af(n.campos,`${s}.campos`);if(w){for(let g of Object.values(w))if(!o.some(y=>y.clave===g&&!y.archivado))throw i(`${s}: \xAB${g}\xBB no es un campo de este m\xF3dulo.`);b.campos=w}if(n.estado!==void 0&&n.estado!==null){let g=n.estado;if(!Ot(g))throw i(`${s}: \xABestado\xBB {campo, parcial, completo, pendiente?}.`);let y=o.find(O=>O.clave===g.campo&&O.tipo==="seleccion"&&!O.archivado);if(!y)throw i(`${s}: \xABestado.campo\xBB tiene que ser una selecci\xF3n de este m\xF3dulo.`);let C=new Set((y.opciones??[]).map(O=>O.valor));for(let O of["parcial","completo","pendiente"]){let M=g[O];if(!(M===void 0&&O==="pendiente")&&(typeof M!="string"||!C.has(M)))throw i(`${s}: \xABestado.${O}\xBB tiene que ser una opci\xF3n de \xAB${y.etiqueta}\xBB.`)}b.estado={campo:y.clave,parcial:g.parcial,completo:g.completo,...typeof g.pendiente=="string"?{pendiente:g.pendiente}:{}}}if(n.no_cuentan!==void 0&&n.no_cuentan!==null){let g=n.no_cuentan;if(!Ot(g)||!Array.isArray(g.valores)||g.valores.length>20||!g.valores.every(y=>typeof y=="string"&&y.length<=60))throw i(`${s}: \xABno_cuentan\xBB {campo, valores}.`);b.no_cuentan={campo:Go(g.campo,`${s}.no_cuentan.campo`),valores:g.valores}}if(n.permitir_exceso===!0&&(b.permitir_exceso=!0),n.juntar!==void 0&&n.juntar!==null&&n.juntar!==!1){let g=n.juntar===!0?{}:n.juntar;if(!Ot(g))throw i(`${s}: \xABjuntar\xBB {iguales?, enlace_varios?}.`);for(let C of Object.keys(g))if(!["iguales","enlace_varios"].includes(C))throw i(`${s}: \xABjuntar\xBB: clave no admitida \xAB${C.slice(0,40)}\xBB.`);let y=g.iguales===void 0?[]:g.iguales;if(!Array.isArray(y)||y.length>10||!y.every(C=>typeof C=="string"&&o.some(O=>O.clave===C&&!O.archivado)))throw i(`${s}: \xABjuntar.iguales\xBB, campos de este m\xF3dulo (hasta 10).`);b.juntar={...y.length?{iguales:y}:{},...g.enlace_varios?{enlace_varios:Go(g.enlace_varios,`${s}.juntar.enlace_varios`)}:{}}}return b});return r.length?r:void 0}var nf,ks,xw,Ot,af,Go,Cw,cf=m(()=>{R();nf=5,ks=/^[a-z][a-z0-9_]{0,40}$/,xw=["numero","importe","duracion","porcentaje"],Ot=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),af=(e,o)=>{if(e!=null){if(!Ot(e)||Object.keys(e).length>60)throw i(`${o}: un objeto destino \u2192 origen.`);for(let[t,r]of Object.entries(e))if(!ks.test(t)||typeof r!="string"||!ks.test(r))throw i(`${o}: \xAB${t.slice(0,40)}\xBB no es v\xE1lido.`);return e}},Go=(e,o)=>{if(typeof e!="string"||!ks.test(e))throw i(`${o}: falta o no es v\xE1lido.`);return e},Cw=(e,o)=>e.find(t=>t.clave===o&&t.tipo==="subtabla"&&!t.archivado)});function uf(e,o){if(e==null)return;if(!uo(e))throw i("\xABpertenencia\xBB: un objeto.");let t=(r,n,a,s=!1)=>{let c=o.find(d=>d.clave===r&&!d.archivado);if(!c||!n.includes(c.tipo)||s&&c.multiple)throw i(`\xABpertenencia.${a}\xBB: ${n.join(" o ")}${s?" simple":""} de este m\xF3dulo.`);return c.clave};return{demanda:t(e.demanda,["relacion"],"demanda",!0),oferta:t(e.oferta,["relacion"],"oferta",!0),desde:t(e.desde,["fecha"],"desde"),...e.hasta?{hasta:t(e.hasta,["fecha"],"hasta")}:{},...e.correccion_dias!==void 0&&e.correccion_dias!==null?{correccion_dias:jw(e.correccion_dias)}:{}}}function df(e,o){if(e==null)return;if(!uo(e))throw i("\xABasignacion\xBB: un objeto.");if(typeof e.oferta!="string"||!vi.test(e.oferta))throw i("\xABasignacion.oferta\xBB: la clave del m\xF3dulo de la oferta.");let t=e.destino,r;if(uo(t)&&t.forma==="pertenencia"&&typeof t.modulo=="string"&&vi.test(t.modulo))r={forma:"pertenencia",modulo:t.modulo};else if(uo(t)&&t.forma==="relacion"){let n=o.find(a=>a.clave===t.campo&&!a.archivado);if(n?.tipo!=="relacion"||n.multiple||n.relacion!==`mod_${e.oferta}`)throw i("\xABasignacion.destino.campo\xBB: una relaci\xF3n simple de este m\xF3dulo a la oferta.");r={forma:"relacion",campo:n.clave}}else throw i("\xABasignacion.destino\xBB: {forma: \xABpertenencia\xBB, modulo} o {forma: \xABrelacion\xBB, campo}.");if(typeof e.cupo!="string"||!vi.test(e.cupo))throw i("\xABasignacion.cupo\xBB: un campo num\xE9rico de la oferta.");return{oferta:e.oferta,destino:r,...Sw({...e,cupo_fijo:void 0},o),cupo:e.cupo}}function Sw(e,o,t=!1){let r=(p,f,h)=>{let b=o.find(v=>v.clave===p&&!v.archivado);if(!b||h&&!h.includes(b.tipo))throw i(`\xABasignacion\xBB: ${f}, ${h?h.join(" o "):"un campo"} de este m\xF3dulo.`);return b.clave},n=(p,f)=>{if(t){if(typeof p!="string"||!/^[a-z][a-z0-9_]{0,40}(\.[a-z][a-z0-9_]{0,40}){0,3}$/.test(p))throw i(`${f}: campo de oferta no v\xE1lido.`);return p}return Ow(p,f)},a=t?lf:vi,s=t&&e.cupo_fijo!==void 0;if(s?e.cupo!==void 0||!Number.isInteger(e.cupo_fijo)||Number(e.cupo_fijo)<1||Number(e.cupo_fijo)>1e4:typeof e.cupo!="string"||!a.test(e.cupo))throw i("\xABasignacion.cupo\xBB: un n\xFAmero de la oferta o un cupo fijo de 1 a 10000.");let c={...s?{cupo_fijo:Number(e.cupo_fijo)}:{cupo:e.cupo},filtros:[],puntos:[]};if(e.orden!==void 0&&e.orden!==null){let p=e.orden;if(!uo(p))throw i("\xABasignacion.orden\xBB: {campo, sentido}.");c.orden={campo:p.campo==="numero"?"numero":r(p.campo,"\xABorden.campo\xBB"),...p.sentido==="desc"?{sentido:"desc"}:{}}}if(e.plazas_por!==void 0&&e.plazas_por!==null){let p=e.plazas_por;if(!uo(p)||typeof p.oferta!="string"||!a.test(p.oferta))throw i("\xABasignacion.plazas_por\xBB: {demanda (selecci\xF3n m\xFAltiple), oferta (su campo)}.");c.plazas_por={demanda:r(p.demanda,"\xABplazas_por.demanda\xBB",["seleccion_multiple","seleccion"]),oferta:p.oferta}}e.inicio&&(c.inicio=r(e.inicio,"\xABinicio\xBB",["fecha"]));let d=Array.isArray(e.filtros)?e.filtros:[],u=Array.isArray(e.puntos)?e.puntos:[];if(d.length>wi||u.length>wi)throw i(`\xABasignacion\xBB: hasta ${wi} filtros y ${wi} puntos.`);if(c.filtros=d.map((p,f)=>{let h=`Filtro ${f+1}`;if(!uo(p))throw i(`${h}: un objeto.`);if(p.tipo==="igual"||p.tipo==="contiene")return{tipo:p.tipo,demanda:r(p.demanda,`${h}, \xABdemanda\xBB`),oferta:n(p.oferta,h)};if(p.tipo==="entre")return{tipo:"entre",demanda:r(p.demanda,`${h}, \xABdemanda\xBB`,["numero","importe","porcentaje","fecha","hora"]),min:n(p.min,h),max:n(p.max,h)};throw i(`${h}: \xABtipo\xBB igual, contiene o entre.`)}),c.puntos=u.map((p,f)=>{let h=`Punto ${f+1}`;if(!uo(p))throw i(`${h}: un objeto.`);switch(p.tipo){case"base":case"carga":return{tipo:p.tipo,peso:St(p.peso,h)};case"dentro":return{tipo:"dentro",demanda:r(p.demanda,`${h}, \xABdemanda\xBB`,["hora","numero","fecha","fecha_hora"]),desde:n(p.desde,h),hasta:n(p.hasta,h),peso:St(p.peso,h)};case"igual":case"contiene":return{tipo:p.tipo,demanda:r(p.demanda,`${h}, \xABdemanda\xBB`),oferta:n(p.oferta,h),peso:St(p.peso,h)};case"junto":{let b=o.find(w=>w.clave===p.relacion&&!w.archivado);if(b?.tipo!=="relacion")throw i(`${h}: \xABrelacion\xBB, una relaci\xF3n de este m\xF3dulo con otras demandas (los hermanos).`);let v=p.mismo_campo;return{tipo:"junto",relacion:b.clave,misma:St(p.misma,h),...uo(v)?{mismo_campo:{oferta:n(v.oferta,h),peso:St(v.peso,h)}}:{},...p.mismo_valor!==void 0?{mismo_valor:St(p.mismo_valor,h)}:{}}}case"si_no":if(typeof p.contiene!="string"||!p.contiene||p.contiene.length>100)throw i(`${h}: \xABcontiene\xBB, el valor que la oferta deber\xEDa tener.`);return{tipo:"si_no",demanda:r(p.demanda,`${h}, \xABdemanda\xBB`,["booleano"]),oferta:n(p.oferta,h),contiene:p.contiene,peso:St(p.peso,h)};default:throw i(`${h}: \xABtipo\xBB base, carga, dentro, igual, contiene, junto o si_no.`)}}),e.cercania!==void 0&&e.cercania!==null){let p=e.cercania;if(!uo(p))throw i("\xABasignacion.cercania\xBB: {demanda, oferta}.");c.cercania={demanda:r(p.demanda,"\xABcercania.demanda\xBB",["hora","numero","fecha","fecha_hora"]),oferta:n(p.oferta,"\xABcercania\xBB")}}return c}var uo,vi,lf,wi,jw,St,Ow,pf=m(()=>{R();uo=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),vi=/^[a-z][a-z0-9_]{0,40}$/,lf=/^[a-z][a-z0-9_]{0,40}(\.[a-z][a-z0-9_]{0,40})?$/,wi=20,jw=e=>{let o=Number(e);if(!Number.isInteger(o)||o<0||o>60)throw i("\xABpertenencia.correccion_dias\xBB: un entero de 0 a 60.");return o};St=(e,o)=>{let t=Number(e);if(!Number.isFinite(t)||Math.abs(t)>1e4)throw i(`${o}: \xABpeso\xBB, un n\xFAmero (\xB110 000).`);return t},Ow=(e,o)=>{if(typeof e!="string"||!lf.test(e))throw i(`${o}: un campo de la oferta (\xABcampo\xBB o \xABrelacion.campo\xBB).`);return e}});var Ps,mf=m(()=>{Ps=["nada","recientes","vistas"]});function gf(e,o){if(pe(e))return;if(!po(e))throw i("\xABstock\xBB: un objeto {articulo?, ubicacion?, movimiento?}.");Ho(e,["articulo","ubicacion","movimiento","reponer"],"stock");let t=s=>o.find(c=>c.clave===s&&!c.archivado),r=(s,c,d,u)=>{let p=t(s);if(!p||!d(p))throw i(`\xABstock.${c}\xBB: ${u} de este m\xF3dulo.`);return p.clave},n=s=>s.tipo==="relacion"&&!s.multiple&&!!s.relacion?.startsWith("mod_"),a={};if(!pe(e.articulo)){let s=e.articulo;if(!po(s))throw i("\xABstock.articulo\xBB: un objeto.");Ho(s,["minimo","reponer","proveedor","permitir_negativo","lotes"],"stock.articulo");let c={};if(pe(s.minimo)||(c.minimo=r(s.minimo,"articulo.minimo",d=>d.tipo==="numero","un n\xFAmero")),pe(s.reponer)||(c.reponer=r(s.reponer,"articulo.reponer",d=>d.tipo==="numero","un n\xFAmero")),pe(s.proveedor)||(c.proveedor=r(s.proveedor,"articulo.proveedor",d=>n(d)||d.tipo==="relacion"&&!d.multiple&&["contacts","companies"].includes(d.relacion??""),"una relaci\xF3n simple a un proveedor")),s.permitir_negativo===!0)c.permitir_negativo=!0;else if(typeof s.permitir_negativo=="string"&&s.permitir_negativo)c.permitir_negativo=r(s.permitir_negativo,"articulo.permitir_negativo",d=>d.tipo==="booleano","un s\xED/no");else if(!pe(s.permitir_negativo)&&s.permitir_negativo!==!1)throw i("\xABstock.articulo.permitir_negativo\xBB: true o un s\xED/no del art\xEDculo.");if(!pe(s.lotes)){if(s.lotes!=="lote"&&s.lotes!=="serie")throw i("\xABstock.articulo.lotes\xBB: lote o serie.");if(c.permitir_negativo)throw i("\xABstock.articulo\xBB: con lotes o series no se admiten negativos.");c.lotes=s.lotes}a.articulo=c}if(!pe(e.ubicacion)){let s=e.ubicacion;if(!po(s))throw i("\xABstock.ubicacion\xBB: un objeto.");Ho(s,["almacen"],"stock.ubicacion"),a.ubicacion=pe(s.almacen)?{}:{almacen:r(s.almacen,"ubicacion.almacen",n,"una relaci\xF3n simple a otro m\xF3dulo")}}if(!pe(e.movimiento)){let s=e.movimiento;if(!po(s))throw i("\xABstock.movimiento\xBB: un objeto.");if(Ho(s,["tipo","lineas","ubicacion","ubicacion_destino","cuando"],"stock.movimiento"),!ff.includes(s.tipo))throw i(`\xABstock.movimiento.tipo\xBB: ${ff.join(", ")}.`);if(!po(s.lineas))throw i("\xABstock.movimiento.lineas\xBB: {subtabla, articulo, cantidad, ubicacion?, coste?}.");let c=s.lineas;Ho(c,["subtabla","articulo","cantidad","ubicacion","ubicacion_destino","coste","lote","caducidad"],"stock.movimiento.lineas");let d=t(c.subtabla);if(d?.tipo!=="subtabla")throw i("\xABstock.movimiento.lineas.subtabla\xBB: una subtabla de este m\xF3dulo.");let u=(d.columnas??[]).filter(w=>!w.archivado),p=(w,g,y,C)=>{let O=u.find(M=>M.clave===w);if(!O||!y(O))throw i(`\xABstock.movimiento.lineas.${g}\xBB: ${C} de \xAB${d.etiqueta}\xBB.`);return O.clave},f={tipo:s.tipo,lineas:{subtabla:d.clave,articulo:p(c.articulo,"articulo",n,"la columna de producto (una relaci\xF3n simple)"),cantidad:p(c.cantidad,"cantidad",w=>hf.includes(w.tipo),"una columna num\xE9rica")},cuando:{campo:"",valores:[]}};if(pe(c.ubicacion)||(f.lineas.ubicacion=p(c.ubicacion,"ubicacion",n,"una relaci\xF3n simple")),pe(c.coste)||(f.lineas.coste=p(c.coste,"coste",w=>hf.includes(w.tipo),"una columna num\xE9rica")),pe(c.lote)||(f.lineas.lote=p(c.lote,"lote",w=>w.tipo==="texto"||w.tipo==="codigo","una columna de texto")),pe(c.caducidad)||(f.lineas.caducidad=p(c.caducidad,"caducidad",w=>w.tipo==="fecha","una columna de fecha")),pe(s.ubicacion)||(f.ubicacion=r(s.ubicacion,"movimiento.ubicacion",n,"una relaci\xF3n simple")),!f.lineas.ubicacion&&!f.ubicacion)throw i("\xABstock.movimiento\xBB: la ubicaci\xF3n, en la l\xEDnea (\xABlineas.ubicacion\xBB) o en el documento (\xABubicacion\xBB).");if(pe(c.ubicacion_destino)||(f.lineas.ubicacion_destino=p(c.ubicacion_destino,"ubicacion_destino",n,"una relaci\xF3n simple")),pe(s.ubicacion_destino)||(f.ubicacion_destino=r(s.ubicacion_destino,"movimiento.ubicacion_destino",n,"una relaci\xF3n simple")),f.tipo==="traspaso"&&!f.lineas.ubicacion_destino&&!f.ubicacion_destino)throw i("\xABstock.movimiento\xBB: un traspaso necesita la ubicaci\xF3n de destino, en la l\xEDnea (\xABlineas.ubicacion_destino\xBB) o en el documento (\xABubicacion_destino\xBB).");if(f.tipo!=="traspaso"&&(f.lineas.ubicacion_destino||f.ubicacion_destino))throw i("\xABstock.movimiento\xBB: la ubicaci\xF3n de destino es solo de un traspaso.");if(!po(s.cuando))throw i("\xABstock.movimiento.cuando\xBB: {campo, valor} o {campo, valores}.");Ho(s.cuando,["campo","valor","valores"],"stock.movimiento.cuando");let h=t(s.cuando.campo);if(h?.tipo!=="seleccion")throw i("\xABstock.movimiento.cuando.campo\xBB: una selecci\xF3n de este m\xF3dulo.");let b=Array.isArray(s.cuando.valores)?s.cuando.valores:[s.cuando.valor],v=new Set((h.opciones??[]).map(w=>w.valor));if(!b.length||b.length>20||!b.every(w=>typeof w=="string"&&v.has(w)))throw i(`\xABstock.movimiento.cuando\xBB: opciones de \xAB${h.etiqueta}\xBB.`);f.cuando={campo:h.clave,valores:[...new Set(b)]},a.movimiento=f}if(!pe(e.reponer)){let s=e.reponer;if(!po(s))throw i("\xABstock.reponer\xBB: {destino, proveedor, lineas: {subtabla, articulo, cantidad}, estado?}.");if(Ho(s,["destino","proveedor","lineas","estado","en_camino"],"stock.reponer"),!a.articulo?.minimo||!a.articulo.reponer||!a.articulo.proveedor)throw i("\xABstock.reponer\xBB: el art\xEDculo necesita su m\xEDnimo, su \xABreponer hasta\xBB y su proveedor.");if(typeof s.destino!="string"||!/^mod_(?!sub_)[a-z][a-z_]{1,30}$/.test(s.destino))throw i("\xABstock.reponer.destino\xBB: mod_<clave> del m\xF3dulo de compras.");if(typeof s.proveedor!="string"||!Ts.test(s.proveedor))throw i("\xABstock.reponer.proveedor\xBB: la relaci\xF3n de las compras al proveedor.");if(!po(s.lineas))throw i("\xABstock.reponer.lineas\xBB: {subtabla, articulo, cantidad}.");Ho(s.lineas,["subtabla","articulo","cantidad"],"stock.reponer.lineas");for(let d of["subtabla","articulo","cantidad"])if(typeof s.lineas[d]!="string"||!Ts.test(s.lineas[d]))throw i(`\xABstock.reponer.lineas.${d}\xBB: falta o no es v\xE1lida.`);let c={destino:s.destino,proveedor:s.proveedor,lineas:{subtabla:s.lineas.subtabla,articulo:s.lineas.articulo,cantidad:s.lineas.cantidad}};if(!pe(s.estado)){if(!po(s.estado)||typeof s.estado.campo!="string"||typeof s.estado.valor!="string")throw i("\xABstock.reponer.estado\xBB: {campo, valor}.");c.estado={campo:s.estado.campo,valor:s.estado.valor}}if(!pe(s.en_camino)){let d=s.en_camino;if(!po(d)||typeof d.campo!="string"||!Ts.test(d.campo)||!Array.isArray(d.valores)||!d.valores.length||d.valores.length>20||!d.valores.every(u=>typeof u=="string"&&u.length<=80))throw i("\xABstock.reponer.en_camino\xBB: {campo, valores} (los estados de la compra pedida y a\xFAn no recibida).");c.en_camino={campo:d.campo,valores:[...new Set(d.valores)]}}a.reponer=c}return Object.keys(a).length?a:void 0}var ff,po,Ho,hf,pe,Ts,bf=m(()=>{R();ff=["entrada","salida","ajuste","traspaso","recuento","reserva"],po=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Ho=(e,o,t)=>{for(let r of Object.keys(e))if(!o.includes(r))throw i(`\xAB${t}\xBB: clave no admitida \xAB${r.slice(0,40)}\xBB.`)},hf=["numero","importe","duracion","porcentaje"],pe=e=>e==null||e==="";Ts=/^[a-z][a-z0-9_]{0,40}$/});function Ew(e,o){let t=`liquidacion.reglas[${o}]`;if(!Xo(e))throw i(`\xAB${t}\xBB: un objeto.`);if(Yo(e,["nombre","si","calculo","valor","tramos"],t),typeof e.nombre!="string"||!e.nombre.trim()||e.nombre.length>60)throw i(`\xAB${t}.nombre\xBB: de 1 a 60 caracteres.`);if(e.calculo!=="porcentaje"&&e.calculo!=="fijo")throw i(`\xAB${t}.calculo\xBB: porcentaje o fijo.`);let r={nombre:e.nombre.trim(),calculo:e.calculo};if(At(e.si)||(r.si=yf(e.si,`${t}.si`)),At(e.tramos))r.valor=Ls(e.valor,`${t}.valor`);else{let n=e.tramos;if(!Xo(n))throw i(`\xAB${t}.tramos\xBB: {por, lista}.`);if(Yo(n,["por","modo","lista"],`${t}.tramos`),n.por!=="acumulado"&&n.por!=="importe")throw i(`\xAB${t}.tramos.por\xBB: acumulado o importe.`);if(n.modo!==void 0&&n.modo!==null&&n.modo!=="marginal"&&n.modo!=="alcanzado")throw i(`\xAB${t}.tramos.modo\xBB: marginal o alcanzado.`);if(!Array.isArray(n.lista)||!n.lista.length||n.lista.length>vf)throw i(`\xAB${t}.tramos.lista\xBB: de 1 a ${vf} tramos {desde, valor}.`);let a=n.lista.map((s,c)=>{if(!Xo(s))throw i(`\xAB${t}.tramos.lista[${c}]\xBB: {desde, valor}.`);return Yo(s,["desde","valor"],`${t}.tramos.lista[${c}]`),{desde:Ls(s.desde,`${t}.tramos.lista[${c}].desde`,0),valor:Ls(s.valor,`${t}.tramos.lista[${c}].valor`)}}).sort((s,c)=>s.desde-c.desde);if(a[0].desde!==0)throw i(`\xAB${t}.tramos\xBB: el primer tramo empieza en 0.`);if(new Set(a.map(s=>s.desde)).size!==a.length)throw i(`\xAB${t}.tramos\xBB: dos tramos con el mismo \xABdesde\xBB.`);if(r.tramos={por:n.por,modo:n.modo==="alcanzado"?"alcanzado":"marginal",lista:a},!At(e.valor))throw i(`\xAB${t}\xBB: con tramos, el valor va en cada tramo.`)}return r}function _f(e,o){if(At(e))return;if(!Xo(e))throw i("\xABliquidacion\xBB: un objeto {origen, importe, fecha, agente, campos, estados, lineas, reglas}.");if(Yo(e,["origen","importe","fecha","agente","cuentan","campos","estados","lineas","reglas"],"liquidacion"),typeof e.origen!="string"||!/^mod_(?!sub_)[a-z][a-z0-9_]{0,40}$/.test(e.origen))throw i("\xABliquidacion.origen\xBB: mod_<clave> del m\xF3dulo de origen.");let t=e.agente==="_dueno"?"_dueno":yi(e.agente,"liquidacion.agente"),r=y=>o.find(C=>C.clave===y&&!C.archivado),n=(y,C,O,M)=>{let Z=r(y);if(!Z||!O(Z))throw i(`\xABliquidacion.${C}\xBB: ${M} de este m\xF3dulo.`);return Z.clave},a=y=>y.tipo==="relacion"&&!y.multiple&&!!y.relacion?.startsWith("mod_"),s=y=>a(y)||y.tipo==="relacion"&&!y.multiple&&["contacts","companies"].includes(y.relacion??"");if(!Xo(e.campos))throw i("\xABliquidacion.campos\xBB: {agente?, periodo, estado, total}.");Yo(e.campos,["agente","periodo","estado","total"],"liquidacion.campos");let c={periodo:n(e.campos.periodo,"campos.periodo",y=>y.tipo==="texto","un texto"),estado:n(e.campos.estado,"campos.estado",y=>y.tipo==="seleccion","una selecci\xF3n"),total:n(e.campos.total,"campos.total",y=>Is.includes(y.tipo),"un n\xFAmero o importe")};if(At(e.campos.agente)||(c.agente=n(e.campos.agente,"campos.agente",s,"una relaci\xF3n simple")),t!=="_dueno"&&!c.agente)throw i("\xABliquidacion.campos.agente\xBB: con el agente en una relaci\xF3n del origen, la relaci\xF3n de aqu\xED al mismo m\xF3dulo.");let d=r(c.estado),u=new Set((d.opciones??[]).map(y=>y.valor));if(!Xo(e.estados))throw i("\xABliquidacion.estados\xBB: {borrador, aprobada, cerrada, pagada} con opciones de su selecci\xF3n.");Yo(e.estados,[...Ms],"liquidacion.estados");let p={};for(let y of Ms){let C=e.estados[y];if(typeof C!="string"||!u.has(C))throw i(`\xABliquidacion.estados.${y}\xBB: una opci\xF3n de \xAB${d.etiqueta}\xBB.`);p[y]=C}if(new Set(Object.values(p)).size!==Ms.length)throw i("\xABliquidacion.estados\xBB: una opci\xF3n distinta para cada estado.");if(!Xo(e.lineas))throw i("\xABliquidacion.lineas\xBB: {subtabla, origen, base, comision, regla?}.");Yo(e.lineas,["subtabla","origen","base","comision","regla"],"liquidacion.lineas");let f=r(e.lineas.subtabla);if(f?.tipo!=="subtabla")throw i("\xABliquidacion.lineas.subtabla\xBB: una subtabla de este m\xF3dulo.");let h=(f.columnas??[]).filter(y=>!y.archivado),b=(y,C,O,M)=>{let Z=h.find($=>$.clave===y);if(!Z||!O(Z))throw i(`\xABliquidacion.lineas.${C}\xBB: ${M} de \xAB${f.etiqueta}\xBB.`);return Z.clave},v={subtabla:f.clave,origen:b(e.lineas.origen,"origen",y=>a(y)&&y.relacion===e.origen,`la relaci\xF3n simple a ${String(e.origen)}`),base:b(e.lineas.base,"base",y=>Is.includes(y.tipo),"una columna num\xE9rica"),comision:b(e.lineas.comision,"comision",y=>Is.includes(y.tipo),"una columna num\xE9rica")};if(At(e.lineas.regla)||(v.regla=b(e.lineas.regla,"regla",y=>y.tipo==="texto","una columna de texto")),!Array.isArray(e.reglas)||!e.reglas.length||e.reglas.length>wf)throw i(`\xABliquidacion.reglas\xBB: de 1 a ${wf}.`);let w=e.reglas.map(Ew),g={origen:e.origen,importe:yi(e.importe,"liquidacion.importe"),fecha:yi(e.fecha,"liquidacion.fecha"),agente:t,campos:c,estados:p,lineas:v,reglas:w};return At(e.cuentan)||(g.cuentan=yf(e.cuentan,"liquidacion.cuentan")),g}var Ms,wf,vf,Is,Aw,Xo,At,Yo,yi,yf,Ls,Nf=m(()=>{R();Ms=["borrador","aprobada","cerrada","pagada"],wf=20,vf=20,Is=["numero","importe","porcentaje"],Aw=/^[a-z][a-z0-9_]{0,40}$/,Xo=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),At=e=>e==null||e==="",Yo=(e,o,t)=>{for(let r of Object.keys(e))if(!o.includes(r))throw i(`\xAB${t}\xBB: clave no admitida \xAB${r.slice(0,40)}\xBB.`)},yi=(e,o)=>{if(typeof e!="string"||!Aw.test(e))throw i(`\xAB${o}\xBB: falta o no es v\xE1lido.`);return e},yf=(e,o)=>{if(!Xo(e))throw i(`\xAB${o}\xBB: {campo, valores}.`);if(Yo(e,["campo","valores"],o),!Array.isArray(e.valores)||!e.valores.length||e.valores.length>20||!e.valores.every(t=>typeof t=="string"&&t.length<=60))throw i(`\xAB${o}.valores\xBB: de 1 a 20 opciones.`);return{campo:yi(e.campo,`${o}.campo`),valores:[...new Set(e.valores)]}},Ls=(e,o,t=-1e12)=>{if(typeof e!="number"||!Number.isFinite(e)||e<t||e>1e12)throw i(`\xAB${o}\xBB: un n\xFAmero.`);return e}});function $f(e,o){if(e==null)return;if(!_i(e))throw i("\xABpublico\xBB: un objeto.");for(let n of Object.keys(e))if(!["campos","titulo","acciones","caducaDias"].includes(n))throw i(`\xABpublico\xBB: clave no admitida \xAB${n.slice(0,40)}\xBB.`);let t=n=>o.find(a=>a.clave===n&&!a.archivado);if(!Array.isArray(e.campos)||!e.campos.length||e.campos.length>20)throw i("\xABpublico.campos\xBB: de 1 a 20 campos.");for(let n of e.campos){let a=t(n);if(!a)throw i(`\xABpublico\xBB: \xAB${String(n).slice(0,40)}\xBB no es un campo del m\xF3dulo.`);if(Rw.includes(a.tipo))throw i(`\xABpublico\xBB: \xAB${a.etiqueta}\xBB no se ense\xF1a en una p\xE1gina p\xFAblica.`)}let r={campos:[...new Set(e.campos)]};if(e.titulo!==void 0&&e.titulo!==null&&e.titulo!==""){let n=t(e.titulo);if(n?.tipo!=="texto"&&n?.tipo!=="autonumero")throw i("\xABpublico.titulo\xBB: un texto del m\xF3dulo.");r.titulo=n.clave}if(e.caducaDias!==void 0){let n=Number(e.caducaDias);if(!Number.isInteger(n)||n<1||n>180)throw i("\xABpublico.caducaDias\xBB: de 1 a 180.");r.caducaDias=n}if(e.acciones!==void 0){if(!Array.isArray(e.acciones)||e.acciones.length>3)throw i("\xABpublico.acciones\xBB: hasta 3.");let n=new Set;if(r.acciones=e.acciones.map((a,s)=>{let c=`Acci\xF3n p\xFAblica ${s+1}`;if(!_i(a)||typeof a.clave!="string"||!qw.test(a.clave)||n.has(a.clave))throw i(`${c}: \xABclave\xBB (min\xFAsculas y _), sin repetir.`);if(n.add(a.clave),typeof a.etiqueta!="string"||!a.etiqueta.trim()||a.etiqueta.length>60)throw i(`${c}: el texto del bot\xF3n (1\u201360).`);let d={clave:a.clave,etiqueta:a.etiqueta.trim(),...a.una_vez===!0?{una_vez:!0}:{}};if(a.campo!==void 0&&a.campo!==null&&a.campo!==""){let u=t(a.campo);if(u?.tipo==="seleccion"){let p=u.opciones?.find(f=>f.valor===a.valor);if(!p)throw i(`${c}: el valor tiene que ser una opci\xF3n de \xAB${u.etiqueta}\xBB.`);if(u.embudo&&(p.requisito||p.pide?.length||p.aprobacion))throw i(`${c}: \xAB${p.etiqueta}\xBB tiene requisito o aprobaci\xF3n: no se puede poner desde fuera.`)}else if(u?.tipo==="booleano"){if(typeof a.valor!="boolean")throw i(`${c}: el valor, s\xED o no.`)}else if(u?.tipo==="hecho"){if(a.valor!==!0)throw i(`${c}: un \xABhecho\xBB se marca (true).`)}else throw i(`${c}: el campo, una selecci\xF3n, un s\xED/no o un \xABhecho\xBB.`);d.campo=u.clave,d.valor=a.valor}if(a.lineas!==void 0&&a.lineas!==null){let u=a.lineas,p=_i(u)?t(u.subtabla):void 0,f=p?.tipo==="subtabla"?(p.columnas??[]).find(h=>h.clave===u.columna&&!h.archivado):void 0;if(f?.tipo!=="booleano")throw i(`${c}: \xABlineas\xBB, una subtabla del m\xF3dulo y una columna s\xED/no suya.`);if(!r.campos.includes(p.clave))throw i(`${c}: la subtabla de \xABlineas\xBB tiene que ense\xF1arse en la p\xE1gina.`);d.lineas={subtabla:p.clave,columna:f.clave}}if(a.firma!==void 0&&a.firma!==null&&a.firma!==!1){let u=a.firma===!0?{}:a.firma;if(!_i(u))throw i(`${c}: \xABfirma\xBB, {archivos}.`);for(let p of Object.keys(u))if(p!=="archivos")throw i(`${c}: \xABfirma\xBB, clave no admitida \xAB${p.slice(0,40)}\xBB.`);if(u.archivos!==void 0&&u.archivos!==null&&u.archivos!==""){if(t(u.archivos)?.tipo!=="archivos")throw i(`${c}: \xABfirma.archivos\xBB, un campo de archivos del m\xF3dulo (donde queda el firmado).`);d.firma={archivos:u.archivos}}else d.firma={}}if(!d.campo&&!d.lineas&&!d.firma)throw i(`${c}: un campo, unas l\xEDneas o la firma.`);return d}),r.acciones.filter(a=>a.firma).length>1)throw i("\xABpublico.acciones\xBB: solo una firma el documento.")}return r}var qw,_i,Rw,xf=m(()=>{R();qw=/^[a-z][a-z0-9_]{0,40}$/,_i=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Rw=["secreto","boton","firma"]});function jf(e,o){if(Cf(e))return;if(!Ds(e))throw i("\xABcuota\xBB: un objeto {proxima, periodicidad, hasta?}.");for(let a of Object.keys(e))if(!["proxima","periodicidad","hasta"].includes(a))throw i(`\xABcuota\xBB: clave no admitida \xAB${a.slice(0,40)}\xBB.`);let t=a=>o.find(s=>s.clave===a&&!s.archivado),r=(a,s)=>{let c=t(a);if(c?.tipo!=="fecha")throw i(`\xABcuota.${s}\xBB: una fecha de este m\xF3dulo.`);return c.clave},n={proxima:r(e.proxima,"proxima"),periodicidad:"mensual"};if(typeof e.periodicidad=="string"){if(!Jr.includes(e.periodicidad))throw i(`\xABcuota.periodicidad\xBB: ${Jr.join(", ")} (o {campo, valores}).`);n.periodicidad=e.periodicidad}else if(Ds(e.periodicidad)){let a=e.periodicidad,s=t(a.campo);if(s?.tipo!=="seleccion")throw i("\xABcuota.periodicidad.campo\xBB: una selecci\xF3n de este m\xF3dulo.");if(!Ds(a.valores)||!Object.keys(a.valores).length)throw i("\xABcuota.periodicidad.valores\xBB: {opci\xF3n: periodo}.");let c=new Set((s.opciones??[]).map(d=>d.valor));for(let[d,u]of Object.entries(a.valores)){if(!c.has(d))throw i(`\xABcuota.periodicidad.valores\xBB: \xAB${d.slice(0,40)}\xBB no es una opci\xF3n de \xAB${s.etiqueta}\xBB.`);if(!Jr.includes(u))throw i(`\xABcuota.periodicidad.valores.${d.slice(0,40)}\xBB: ${Jr.join(", ")}.`)}n.periodicidad={campo:s.clave,valores:a.valores}}else throw i(`\xABcuota.periodicidad\xBB: ${Jr.join(", ")} o {campo, valores}.`);if(!Cf(e.hasta)&&(n.hasta=r(e.hasta,"hasta"),n.hasta===n.proxima))throw i("\xABcuota.hasta\xBB: otra fecha que la pr\xF3xima.");return n}var Jr,Ds,Cf,Of=m(()=>{R();Jr=["semanal","quincenal","mensual","bimestral","trimestral","semestral","anual"],Ds=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Cf=e=>e==null||e===""});function Ef(e,o){if(e==null)return;if(!Af(e))throw i("\xABpapel\xBB: {tipo, campos} o null.");let t=Object.keys(e).find(c=>c!=="tipo"&&c!=="campos"&&c!=="atributos");if(t)throw i(`\xABpapel\xBB: \xAB${t}\xBB no se reconoce.`);let r=typeof e.tipo=="string"?zs[e.tipo]:void 0;if(!r||!Object.hasOwn(zs,e.tipo))throw i(`\xABpapel.tipo\xBB: uno de ${Object.keys(zs).join(", ")}.`);let n=e.campos??{};if(!Af(n))throw i("\xABpapel.campos\xBB: {campo est\xE1ndar: clave del campo}.");let a={};for(let[c,d]of Object.entries(n)){let u=Object.hasOwn(r.campos,c)?r.campos[c]:void 0;if(!u)throw i(`\xABpapel.campos\xBB: \xAB${c}\xBB no es un campo de \xAB${r.etiqueta}\xBB (${Object.keys(r.campos).join(", ")}).`);if(d==null||d==="")continue;let p=o.find(f=>f.clave===d&&!f.archivado);if(!p)throw i(`\xABpapel\xBB: ${u.etiqueta} apunta a \xAB${String(d)}\xBB, que no es un campo vivo de este m\xF3dulo.`);if(!u.tipos.includes(p.tipo))throw i(`\xABpapel\xBB: ${u.etiqueta} tiene que ser un campo de tipo ${u.tipos.join(" o ")} (\xAB${p.etiqueta}\xBB es ${p.tipo}).`);a[c]=p.clave}for(let[c,d]of Object.entries(r.campos))if(d.obligatorio&&!a[c])throw i(`\xABpapel\xBB: falta el campo de ${d.etiqueta}.`);let s=Pw(r,e.atributos,o);return s?{tipo:e.tipo,campos:a,atributos:s}:{tipo:e.tipo,campos:a}}function Pw(e,o,t){if(o==null)return;let r=e.atributos;if(!r)throw i(`\xABpapel.atributos\xBB: \xAB${e.etiqueta}\xBB no tiene atributos.`);if(!Array.isArray(o))throw i("\xABpapel.atributos\xBB: una lista de claves de campo.");if(o.length>r.max)throw i(`\xABpapel.atributos\xBB: como mucho ${r.max}.`);let n=[];for(let a of o){let s=typeof a=="string"?t.find(c=>c.clave===a&&!c.archivado):void 0;if(!s)throw i(`\xABpapel.atributos\xBB: \xAB${String(a)}\xBB no es un campo vivo de este m\xF3dulo.`);if(!r.tipos.includes(s.tipo))throw i(`\xABpapel.atributos\xBB: \xAB${s.etiqueta}\xBB es ${s.tipo}; vale ${r.tipos.join(", ")}.`);n.includes(s.clave)||n.push(s.clave)}return n.length?n:void 0}var Sf,kw,zs,Af,qf=m(()=>{R();Sf={nombre:{etiqueta:"Nombre",tipos:["texto"],obligatorio:!0},correo:{etiqueta:"Correo",tipos:["correo"]},telefono:{etiqueta:"Tel\xE9fono",tipos:["telefono"]},nif:{etiqueta:"NIF",tipos:["texto"]},direccion:{etiqueta:"Direcci\xF3n",tipos:["texto","texto_largo"]}},kw={nombre:{etiqueta:"Nombre",tipos:["texto"],obligatorio:!0},precio:{etiqueta:"Precio",tipos:["importe","numero"]},foto:{etiqueta:"Foto",tipos:["url"]},enlace:{etiqueta:"Enlace",tipos:["url"]},stock:{etiqueta:"Stock",tipos:["numero","contador"]},descripcion:{etiqueta:"Descripci\xF3n",tipos:["texto","texto_largo"]},categoria:{etiqueta:"Categor\xEDa",tipos:["seleccion","seleccion_multiple","texto"]},varianteId:{etiqueta:"Id de variante",tipos:["texto","numero"]}},zs={cerradura:{etiqueta:"Cerradura",campos:{nombre:{etiqueta:"Nombre",tipos:["texto"],obligatorio:!0},identificador:{etiqueta:"Identificador",tipos:["texto","codigo","numero"]},ubicacion:{etiqueta:"Ubicaci\xF3n",tipos:["texto"]}}},dispositivo:{etiqueta:"Dispositivo",campos:{nombre:{etiqueta:"Nombre",tipos:["texto"],obligatorio:!0},identificador:{etiqueta:"Identificador",tipos:["texto","codigo"]},canal:{etiqueta:"Canal",tipos:["numero"]}}},clientes:{etiqueta:"Clientes",campos:Sf},proveedores:{etiqueta:"Proveedores",campos:Sf},catalogo:{etiqueta:"Cat\xE1logo",campos:kw,atributos:{etiqueta:"Atributos",tipos:["texto","seleccion","seleccion_multiple","numero","importe","porcentaje","booleano"],max:16}},producto:{etiqueta:"Producto",campos:{nombre:{etiqueta:"Nombre",tipos:["texto"],obligatorio:!0},sku:{etiqueta:"SKU",tipos:["texto","codigo"]},precio:{etiqueta:"Precio",tipos:["numero","importe"]},existencias:{etiqueta:"Existencias",tipos:["numero","contador"]}}},pedido:{etiqueta:"Pedido",campos:{numero:{etiqueta:"N\xFAmero",tipos:["texto","codigo"]},estado:{etiqueta:"Estado",tipos:["texto","seleccion"]},total:{etiqueta:"Total",tipos:["numero","importe"]}}}},Af=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)});function Ur(e,o,t=!1){if(e!=null){if(!Array.isArray(e)||e.length>kf)throw i(`${o}: el filtro, una lista de hasta ${kf} condiciones.`);if(e.length)return e.map((r,n)=>{let a=`${o}, condici\xF3n ${n+1}`;if(typeof r!="object"||r===null||Array.isArray(r))throw i(`${a}: {campo, op, valor}.`);let s=r;for(let u of Object.keys(s))if(!["campo","op","valor"].includes(u))throw i(`${a}: clave no admitida \xAB${u.slice(0,40)}\xBB.`);if(typeof s.campo!="string"||!(We.test(s.campo)||t&&/^datos\.[a-z][a-z0-9_]{0,40}$/.test(s.campo)))throw i(`${a}: \xABcampo\xBB, la clave de un campo del m\xF3dulo que resume.`);if(typeof s.op!="string"||!Rf.includes(s.op))throw i(`${a}: \xABop\xBB, una de ${Rf.join(", ")}.`);let c=s.op;if(c==="vacio"||c==="no_vacio")return{campo:s.campo,op:c};let d=u=>typeof u=="string"&&u.length<=200||typeof u=="number"&&Number.isFinite(u)||typeof u=="boolean";if(c==="en"||c==="no_en"){if(!Array.isArray(s.valor)||!s.valor.length||s.valor.length>50||!s.valor.every(u=>d(u)&&typeof u!="boolean"))throw i(`${a}: \xAB${c}\xBB lleva una lista de valores (hasta 50).`);return{campo:s.campo,op:c,valor:s.valor}}if(!d(s.valor))throw i(`${a}: \xAB${c}\xBB lleva un valor (texto, n\xFAmero o s\xED/no).`);return{campo:s.campo,op:c,valor:s.valor}})}}function zf(e,o=!1){if(typeof e=="string"&&(Lf.has(e)||Lw.has(e)))throw i(`La clave del m\xF3dulo \xAB${e.slice(0,40)}\xBB es una palabra reservada: usa otra (p. ej. \xAB${e.slice(0,30)}_crm\xBB o un sin\xF3nimo).`);if(typeof e!="string"||!Df.test(e))throw i(`La clave del m\xF3dulo${typeof e=="string"?` \xAB${e.slice(0,40)}\xBB`:""}: min\xFAsculas y \xAB_\xBB, de 2 a 31, sin palabras reservadas.`);if(e.startsWith("sub_")!==o)throw i(o?"Clave interna no v\xE1lida.":"La clave del m\xF3dulo no puede empezar por \xABsub_\xBB.");return e}function Us(e,o,t=!1){if(typeof e!="object"||e===null||Array.isArray(e))throw i("Definici\xF3n no v\xE1lida.");let r=e,n=zf(r.clave,t);if(!Array.isArray(r.campos))throw i("Faltan los campos.");let a=r.campos.map((s,c)=>Ni(s,c,o,n));if(a.filter(s=>s.esCodigo&&!s.archivado).length>1)throw i("Solo un campo puede ser el c\xF3digo de la ficha.");return a}function Ff(e,o){if(typeof e!="object"||e===null||Array.isArray(e))throw i("Definici\xF3n no v\xE1lida.");let t=e,r=zf(t.clave,o.interno===!0),n=Ko(t.nombre,"el nombre",60),a=Ko(t.nombre_plural??t.nombre,"el nombre en plural",60),s=Ko(t.descripcion??"","la descripci\xF3n",500,!0),c=typeof t.icono=="string"&&Bs.includes(t.icono)?t.icono:"box",d;if(t.color===null||t.color==="")d=null;else if(t.color!==void 0){if(typeof t.color!="string"||!/^#[0-9a-f]{6}$/i.test(t.color))throw i("\xABcolor\xBB: un color #rrggbb.");d=t.color.toLowerCase()}let u=Pm(Us(t,o.modulosDelEspacio,o.interno),r,o.camposRelacion);if(u.filter(q=>!q.archivado&&q.opciones?.some(L=>L.hecho)).length>1)throw i("Solo una selecci\xF3n puede marcar estados como \xABhechos\xBB.");if(u.filter(q=>!q.archivado&&q.proximaAccion).length>1)throw i("Solo una fecha puede ser la de la pr\xF3xima acci\xF3n.");let p=new Set;for(let q of u){if(p.has(q.clave))throw i(`El campo \xAB${q.clave}\xBB est\xE1 repetido.`);p.add(q.clave)}let f=u.filter(q=>!q.archivado);for(let q of f)for(let L of ds(q)){let oe=f.find(qt=>qt.clave===L.relacion);if(!oe||oe.clave===q.clave||oe.tipo!=="relacion"||oe.multiple&&!q.multiple)throw i(`\xAB${q.etiqueta}\xBB: un origen m\xFAltiple necesita tambi\xE9n un destino m\xFAltiple.`)}if(Vp(f),f.length===0)throw i("El m\xF3dulo necesita al menos un campo.");for(let q of f.filter(L=>L.tipo==="busqueda")){let L=f.find(oe=>oe.clave===q.desde);if(!L||L.tipo!=="relacion")throw i(`\xAB${q.etiqueta}\xBB: tiene que salir de un campo de relaci\xF3n de este m\xF3dulo.`)}for(let q of f.filter(L=>L.tipo==="qr"&&L.destino==="campo"&&L.campo))if(!f.find(oe=>oe.clave===q.campo))throw i(`\xAB${q.etiqueta}\xBB: el campo \xAB${q.campo}\xBB no existe en este m\xF3dulo.`);if(f.length>o.topeCampos)throw i(`Como mucho ${o.topeCampos} campos por m\xF3dulo en tu plan.`);for(let q of o.anterior??[]){let L=u.find(oe=>oe.clave===q.clave);if(!L)throw i(`El campo \xAB${q.etiqueta}\xBB no se quita: se archiva.`);if(L.tipo!==q.tipo&&!Jw(q.tipo,L.tipo))throw i(`\xAB${q.etiqueta}\xBB no puede pasar de ${q.tipo} a ${L.tipo}.`)}let h=t.articulo==="un"||t.articulo==="una"?t.articulo:null,b=ui(t.ficha,u),v=Wr(t.impresion,u),w=lm(t.validaciones,u.filter(q=>!q.archivado));fm(u);for(let q of u){if(q.tipo!=="contador"||!q.alMarcar)continue;let L=u.find(oe=>oe.clave===q.alMarcar&&!oe.archivado);if(L?.tipo!=="booleano"&&L?.tipo!=="hecho")throw i(`\xAB${q.etiqueta}\xBB: \xABal marcar\xBB tiene que ser un s\xED/no o un \xABhecho\xBB de este m\xF3dulo.`)}let g=Wm(t.vistas),y=tf(t.conversiones),C=sf(t.encadenar,u),O=Rm(t.plantillas_hijos),M=Uw(t.campo_ambito,u),Z=$f(t.publico,u),$=ii(t.recurso,u),A=ai(t.reserva,u),N=df(t.asignacion,u),k=uf(t.pertenencia,u),x=gf(t.stock,u),I=_f(t.liquidacion,u),z=Cp(t.sucesion),U=Ap(t.liquidacion_v2,u);if(I&&U)throw i("Elige una versi\xF3n de liquidaci\xF3n por m\xF3dulo.");let ee=jf(t.cuota,u),H=qp(t.precios,u),we=mi(t.relacionadas,u),oo=fi(t.siguientes),Po=Ef(t.papel,u),et=Rs(t.personas,u);if(t.portal!==void 0&&t.portal!==null&&!["suyos_ver","suyos_anadir","suyos_editar","todos_ver"].includes(t.portal))throw i("\xABportal\xBB: suyos_ver, suyos_anadir, suyos_editar o todos_ver.");let X=t.portal??void 0,qe;if(t.portal_campos!==void 0&&t.portal_campos!==null){let q=t.portal_campos;if(!X)throw i("\xABportal_campos\xBB va con \xABportal\xBB.");if(typeof q!="object"||Array.isArray(q)||Object.keys(q).length>u.length)throw i("\xABportal_campos\xBB: clave del campo \u2192 rellenar, ver o no.");for(let[L,oe]of Object.entries(q)){if(!u.some(qt=>qt.clave===L))throw i(`\xABportal_campos\xBB: el m\xF3dulo no tiene el campo \xAB${L.slice(0,40)}\xBB.`);if(oe!=="rellenar"&&oe!=="ver"&&oe!=="no")throw i(`\xABportal_campos.${L.slice(0,40)}\xBB: rellenar, ver o no.`)}qe={...q}}let Re;if(t.funcionesNativas!==void 0){if(!t.funcionesNativas||typeof t.funcionesNativas!="object"||Array.isArray(t.funcionesNativas)||Object.entries(t.funcionesNativas).some(([q,L])=>!["relacionadas","siguientes"].includes(q)||!Array.isArray(L)||L.length>(q==="relacionadas"?20:5)))throw i("Las funciones nativas necesitan relacionadas o siguientes declarados.");Re=structuredClone(t.funcionesNativas)}return{clave:r,nombre:n,nombre_plural:a,articulo:h,descripcion:s,icono:c,...d!==void 0?{color:d}:{},campos:Sm(u).map(q=>{if(q.tipo!=="busqueda")return q;let{origen:L,...oe}=q;return oe}),paginas:t.paginas===!0,...b?{ficha:b}:{},...v?{impresion:v}:{},...w?{validaciones:w}:{},...g?{vistas:g}:{},...y?{conversiones:y}:{},...C?{encadenar:C}:{},...O?{plantillas_hijos:O}:{},...M?{campo_ambito:M}:{},...Z?{publico:Z}:{},...$?{recurso:$}:{},...A?{reserva:A}:{},...N?{asignacion:N}:{},...k?{pertenencia:k}:{},...x?{stock:x}:{},...I?{liquidacion:I}:{},...z?{sucesion:z}:{},...U?{liquidacion_v2:U}:{},...ee?{cuota:ee}:{},...H?{precios:H}:{},...we?{relacionadas:we}:{},...oo?{siguientes:oo}:{},...Po?{papel:Po}:{},...et?{personas:et}:{},...X?{portal:X}:{},...qe&&Object.keys(qe).length?{portal_campos:qe}:{},...Re?{funcionesNativas:Re}:{}}}function Uw(e,o){if(e==null||e==="")return;let t=o.find(r=>r.clave===e&&!r.archivado);if(!t||!(t.tipo==="seleccion"||t.tipo==="relacion"&&!t.multiple))throw i("\xABcampo_ambito\xBB: una selecci\xF3n o una relaci\xF3n simple de este m\xF3dulo.");return t.clave}function Ni(e,o,t,r){if(typeof e!="object"||e===null||Array.isArray(e))throw i(`Campo ${o+1} no v\xE1lido.`);let n=e;if(typeof n.clave=="string"&&Lf.has(n.clave))throw i(`La clave \xAB${n.clave.slice(0,40)}\xBB del campo ${o+1}${r?` de \xAB${r}\xBB`:""} es una palabra reservada: usa otra (p. ej. \xAB${n.clave.slice(0,30)}_campo\xBB o un sin\xF3nimo).`);if(typeof n.clave!="string"||!We.test(n.clave))throw i(`La clave del campo ${o+1}${r?` de \xAB${r}\xBB`:""}${typeof n.clave=="string"?` (\xAB${n.clave.slice(0,40)}\xBB)`:""}: min\xFAsculas, n\xFAmeros y \xAB_\xBB, sin palabras reservadas.`);let a=n.tipo;if(!Fs.includes(a))throw i(`Tipo de campo no v\xE1lido: ${String(n.tipo)}.`);let s={clave:n.clave,etiqueta:Ko(n.etiqueta,`la etiqueta del campo ${o+1}`,80),tipo:a};if(n.ajustesNativos!==void 0){if(a!=="relacion"&&a!=="busqueda")throw i("Solo las relaciones y b\xFAsquedas declaradas tienen ajustes nativos.");s.ajustesNativos=Gm(n.ajustesNativos);for(let u of Object.values(s.ajustesNativos??{})){let p={...n,...u,ajustesNativos:void 0};for(let[f,h]of Object.entries(u))h===null&&delete p[f];Ni(p,o,t,r)}}for(let u of["formulaNativa","defectoNativo"])if(n[u]!==void 0){if(typeof n[u]!="string"||!n[u].trim()||n[u].length>Ke||u==="formulaNativa"&&a!=="formula")throw i("La variante nativa necesita una f\xF3rmula v\xE1lida y acotada.");s[u]=n[u]}if(n.obligatorio===!0&&(s.obligatorio=!0),s.enTabla=n.enTabla!==!1,n.sensible!==void 0&&typeof n.sensible!="boolean")throw i("\xABsensible\xBB debe ser s\xED o no.");if(n.sensible===!0&&(s.sensible=!0),n.semantica!==void 0){if(!["dato","firma","consentimiento","credencial","auditoria","financiero"].includes(String(n.semantica)))throw i("Sucesi\xF3n: configuraci\xF3n inv\xE1lida.");s.semantica=n.semantica}n.archivado===!0&&(s.archivado=!0),n.seccion!==void 0&&n.seccion!==""&&(s.seccion=Ko(n.seccion,"la secci\xF3n",60)),n.ayuda!==void 0&&n.ayuda!==""&&(s.ayuda=Ko(n.ayuda,"la ayuda",200)),(a==="fecha"||a==="fecha_hora")&&n.proximaAccion===!0&&(s.proximaAccion=!0),a==="numero"&&n.sinMiles===!0&&(s.sinMiles=!0);for(let u of["minimo","maximo"])if(n[u]!==void 0&&n[u]!==null){if(typeof n[u]!="number"||!Number.isFinite(n[u]))throw i(`\xAB${u}\xBB tiene que ser un n\xFAmero.`);s[u]=n[u]}if(a==="seleccion"||a==="seleccion_multiple"){if(!Array.isArray(n.opciones)||n.opciones.length===0||n.opciones.length>100)throw i(`\xAB${s.etiqueta}\xBB: entre 1 y 100 opciones.`);let u=new Set;s.opciones=n.opciones.map(p=>{let f=typeof p=="string"?{valor:p,etiqueta:p}:p,h=Ko(f.valor??f.etiqueta,"el valor de una opci\xF3n",80);if(u.has(h))throw i(`\xAB${s.etiqueta}\xBB: la opci\xF3n \xAB${h}\xBB est\xE1 repetida.`);u.add(h);let b={valor:h,etiqueta:Ko(f.etiqueta??h,"una opci\xF3n",80)};return typeof f.color=="string"&&Dw.test(f.color)&&(b.color=f.color),a==="seleccion"&&f.hecho===!0&&(b.hecho=!0),a==="seleccion"&&n.embudo===!0&&Om(f,b,s.etiqueta),b}),a==="seleccion"&&n.embudo===!0&&(s.embudo=!0)}if(a==="relacion"){let u=n.relacion;if(!(typeof u=="string"&&(Mw.includes(u)||u.startsWith("mod_")&&(t.includes(u.slice(4))||u.slice(4)===r))))throw i(`\xAB${s.etiqueta}\xBB: relaci\xF3n con algo que no existe.`);if(s.relacion=u,n.tipoContacto!==void 0&&n.tipoContacto!==null&&n.tipoContacto!==""){if(u!=="contacts"&&u!=="companies")throw i(`\xAB${s.etiqueta}\xBB: el tipo solo vale en una relaci\xF3n con Personas o Empresas.`);if(typeof n.tipoContacto!="string"||!Qw.test(n.tipoContacto))throw i(`\xAB${s.etiqueta}\xBB: el tipo no es una clave v\xE1lida.`);s.tipoContacto=n.tipoContacto}if(n.mostrarTareasEnFichaRelacionada===!0){if(n.multiple===!0)throw i(`\xAB${s.etiqueta}\xBB: mostrar tareas relacionadas requiere una relaci\xF3n simple.`);s.mostrarTareasEnFichaRelacionada=!0}}else if(n.mostrarTareasEnFichaRelacionada===!0)throw i(`\xAB${s.etiqueta}\xBB: la opci\xF3n de tareas relacionadas solo sirve en campos de relaci\xF3n.`);if(n.completarDesde!==void 0&&n.completarDesde!==null){if(!["relacion","texto","texto_largo","numero","importe","porcentaje","correo","telefono","url","codigo","fecha","fecha_hora","booleano","seleccion","ubicacion"].includes(a))throw i("Ese tipo de campo no admite autocompletado.");let u=n.completarDesde;if(typeof u!="object"||Array.isArray(u)||Object.keys(u).some(f=>!["relacion","campo","alternativa"].includes(f))||typeof u.relacion!="string"||!We.test(u.relacion)||typeof u.campo!="string"||!/^[a-z][a-z0-9_.]{0,80}$/.test(u.campo))throw i(`\xAB${s.etiqueta}\xBB: completarDesde requiere relacion y campo.`);let p;if(u.alternativa!==void 0){let f=u.alternativa;if(!f||typeof f!="object"||Array.isArray(f)||Object.keys(f).some(h=>h!=="relacion"&&h!=="campo")||typeof f.relacion!="string"||!We.test(f.relacion)||typeof f.campo!="string"||!/^[a-z][a-z0-9_.]{0,80}$/.test(f.campo))throw i("La alternativa de autocompletado necesita relacion y campo.");p={relacion:f.relacion,campo:f.campo}}s.completarDesde={relacion:u.relacion,campo:u.campo,...p?{alternativa:p}:{}}}if(n.completarNativo!==void 0){if(a==="relacion")throw i("La relaci\xF3n conserva su autocompletado en ajustesNativos.");if(n.completarNativo===null)s.completarNativo=null;else{let u=Ni({...n,completarDesde:n.completarNativo,completarNativo:void 0},o,t,r).completarDesde;if(!u)throw i("La variante de autocompletado no es v\xE1lida.");s.completarNativo=u}}if((a==="relacion"||a==="archivos")&&n.multiple===!0&&(s.multiple=!0),a==="archivos"&&n.soloImagenes===!0&&(s.soloImagenes=!0),a==="texto_largo"&&n.sinFormato===!0&&(s.sinFormato=!0),(a==="formula"||a==="resumen")&&n.formato!==void 0&&n.formato!==null&&n.formato!=="automatico"){if(n.formato!=="numero"&&n.formato!=="importe"&&n.formato!=="porcentaje")throw i(`\xAB${s.etiqueta}\xBB: el formato es autom\xE1tico, n\xFAmero, importe o porcentaje.`);s.formato=n.formato}if(a==="archivos"&&n.versiones===!0&&(s.versiones=!0),a==="secreto"&&delete s.obligatorio,a==="contador"&&typeof n.alMarcar=="string"&&n.alMarcar){if(!We.test(n.alMarcar))throw i(`\xAB${s.etiqueta}\xBB: \xABal marcar\xBB no es un campo v\xE1lido.`);s.alMarcar=n.alMarcar}if(a==="busqueda"){if(typeof n.desde!="string"||!We.test(n.desde)||typeof n.campo!="string"||!/^[a-z][a-z0-9_.]{0,80}$/.test(n.campo))throw i(`\xAB${s.etiqueta}\xBB: elige la relaci\xF3n y el campo que trae.`);if(n.siVacio!==void 0){if(typeof n.siVacio!="string"||!We.test(n.siVacio))throw i("La alternativa necesita otra b\xFAsqueda escalar del mismo tipo, sin cadenas.");s.siVacio=n.siVacio}s.desde=n.desde,s.campo=n.campo,delete s.obligatorio}if(a==="relacion"&&n.alBorrar!==void 0&&n.alBorrar!=="avisar"){if(!Tw.includes(n.alBorrar))throw i(`\xAB${s.etiqueta}\xBB: \xABal borrar\xBB no v\xE1lido.`);s.alBorrar=n.alBorrar}if(a==="valoracion"){let u=n.maximo===void 0||n.maximo===null?5:n.maximo;if(typeof u!="number"||!Number.isInteger(u)||u<3||u>10)throw i(`\xAB${s.etiqueta}\xBB: entre 3 y 10 estrellas.`);s.maximo=u,delete s.minimo}if(a==="autonumero"){let u=typeof n.prefijo=="string"?n.prefijo.trim():"";if(!/^[A-Za-z0-9_-]{0,10}$/.test(u))throw i(`\xAB${s.etiqueta}\xBB: el prefijo, hasta 10 letras, n\xFAmeros, \xAB-\xBB o \xAB_\xBB.`);let p=n.digitos===void 0||n.digitos===null?4:n.digitos;if(typeof p!="number"||!Number.isInteger(p)||p<1||p>10)throw i(`\xAB${s.etiqueta}\xBB: de 1 a 10 d\xEDgitos.`);u&&(s.prefijo=u),s.digitos=p,n.anual===!0?s.anual=!0:delete s.anual}if(If.includes(a)&&delete s.obligatorio,a==="subtabla"){if(!Array.isArray(n.columnas)||n.columnas.length===0||n.columnas.length>Mf)throw i(`\xAB${s.etiqueta}\xBB: entre 1 y ${Mf} columnas.`);let u=new Set(["padre"]);s.columnas=n.columnas.map((h,b)=>{let v=Ni(h,b,t,r);if(!Bw.includes(v.tipo))throw i(`\xAB${s.etiqueta}\xBB: una columna no puede ser de tipo ${v.tipo}.`);if(u.has(v.clave))throw i(`\xAB${s.etiqueta}\xBB: la columna \xAB${v.clave}\xBB est\xE1 repetida o es reservada.`);if(u.add(v.clave),v.tipo==="subtabla"&&(v.columnas??[]).some(w=>w.tipo==="subtabla"))throw i(`\xAB${s.etiqueta}\xBB: como mucho dos niveles de subtablas (cap\xEDtulo \u2192 partidas).`);if(v.tipo==="relacion"){if(v.multiple)throw i(`\xAB${s.etiqueta}\xBB: una columna de relaci\xF3n es de un solo registro.`);if(!v.relacion?.startsWith("mod_")&&v.relacion!=="contacts"&&v.relacion!=="companies")throw i(`\xAB${s.etiqueta}\xBB: una columna de relaci\xF3n apunta a un m\xF3dulo, Persona o Empresa.`)}return v});for(let h of s.columnas)if(h.tipo==="resumen"&&!s.columnas.some(b=>b.tipo==="subtabla"&&(b.clave===h.de||!!b.hijo&&b.hijo===h.de)))throw i(`\xAB${s.etiqueta}\xBB: el total \xAB${h.etiqueta}\xBB tiene que ser de una subtabla de la l\xEDnea.`);let p=n.columnas;s.columnas=s.columnas.map((h,b)=>{let v=p[b]?.copiar;if(v==null)return h;let w=`\xAB${s.etiqueta}\xBB, columna \xAB${h.etiqueta}\xBB`;if(h.tipo!=="relacion")throw i(`${w}: \xABcopiar\xBB va en una columna de relaci\xF3n.`);if(typeof v!="object"||Array.isArray(v)||Object.keys(v).length>Pf)throw i(`${w}: \xABcopiar\xBB, un objeto columna \u2192 campo (hasta ${Pf}).`);for(let[g,y]of Object.entries(v)){let C=s.columnas.find(O=>O.clave===g);if(!C||C.tipo==="relacion"||C.tipo==="formula")throw i(`${w}: \xAB${g.slice(0,40)}\xBB no es una columna que se pueda rellenar.`);if(typeof y!="string"||!We.test(y))throw i(`${w}: el campo de \xAB${g}\xBB no es v\xE1lido.`)}return Object.keys(v).length?{...h,copiar:{...v}}:h}),s.columnas=s.columnas.map((h,b)=>{let v=p[b]?.rellenar;if(v==null)return h;let w=`\xAB${s.etiqueta}\xBB, columna \xAB${h.etiqueta}\xBB`;if(h.tipo!=="articulo")throw i(`${w}: \xABrellenar\xBB va en una columna de art\xEDculo.`);if(typeof v!="object"||Array.isArray(v)||Object.keys(v).length>Tf.length*2)throw i(`${w}: \xABrellenar\xBB, un objeto columna \u2192 dato del art\xEDculo.`);for(let[g,y]of Object.entries(v)){let C=s.columnas.find(O=>O.clave===g);if(!C||["relacion","articulo","formula","subtabla","resumen"].includes(C.tipo))throw i(`${w}: \xAB${g.slice(0,40)}\xBB no es una columna que se pueda rellenar.`);if(!Tf.includes(y))throw i(`${w}: \xAB${g.slice(0,40)}\xBB se rellena con nombre, referencia, codigo, precio o iva_pct.`)}return Object.keys(v).length?{...h,rellenar:{...v}}:h}),typeof n.hijo=="string"&&Ww.test(n.hijo)&&(s.hijo=n.hijo);let f=zm(n.impresion,s.columnas);f&&(s.impresion=f),delete s.obligatorio}if(a==="autonumero"){let u=si(n.visibleSi,s.etiqueta);u&&(s.visibleSi=u)}if(!Jm({tipo:a})){let u=si(n.visibleSi,s.etiqueta);u&&(s.visibleSi=u);let p=si(n.obligatorioSi,s.etiqueta);if(p&&(s.obligatorioSi=p),n.patron!==void 0&&n.patron!==null&&n.patron!==""){if(!vm.includes(a))throw i(`\xAB${s.etiqueta}\xBB: un patr\xF3n solo vale para textos, correos, tel\xE9fonos, webs y c\xF3digos.`);let h=_m(n.patron,s.etiqueta);h&&(s.patron=h)}if(n.unico===!0){if(!ym.includes(a))throw i(`\xAB${s.etiqueta}\xBB: \xAB\xFAnico\xBB solo vale para textos, correos, tel\xE9fonos, webs, c\xF3digos y n\xFAmeros.`);s.unico=!0}if(n.esCodigo===!0){if(!s.unico)throw i(`\xAB${s.etiqueta}\xBB: el c\xF3digo de la ficha tiene que ser \xFAnico.`);s.esCodigo=!0}let f=Nm(n.porDefecto,s);f&&(s.porDefecto=f)}let c=rm(n.permisos,s.etiqueta);if(c&&(s.permisos=c),n.grupo!==void 0&&n.grupo!==null&&n.grupo!==""){if(typeof n.grupo!="string"||!zw.test(n.grupo))throw i(`\xAB${s.etiqueta}\xBB: el grupo, en min\xFAsculas y sin espacios (p. ej. \xABfinanzas\xBB).`);s.grupo=n.grupo}if(n.enmascarado===!0){if(!Fw.includes(a))throw i(`\xAB${s.etiqueta}\xBB: solo se enmascaran textos, correos, tel\xE9fonos y c\xF3digos.`);s.enmascarado=!0}let d=mm(n.depende,s);if(d&&(s.depende=d),a==="archivo"&&(s.enTabla=!1,delete s.obligatorio),a==="boton"){let u=n.automatizacion;if(typeof u!="number"||!Number.isSafeInteger(u)||u<=0)throw i(`\xAB${s.etiqueta}\xBB: elige la automatizaci\xF3n del bot\xF3n.`);s.automatizacion=u,s.enTabla=!1,delete s.obligatorio}if(a==="formula"){if(typeof n.formula!="string"||!n.formula.trim()||n.formula.length>Ke)throw i(`\xAB${s.etiqueta}\xBB: escribe la f\xF3rmula (hasta ${Ke} caracteres).`);s.formula=n.formula.trim(),delete s.obligatorio}if(a==="resumen"){let u=n.calculo;if(typeof n.de!="string"||!Df.test(n.de)||typeof n.via!="string"||!We.test(n.via)||!Ws.includes(u))throw i(`\xAB${s.etiqueta}\xBB: elige de qu\xE9 m\xF3dulo, por qu\xE9 relaci\xF3n y qu\xE9 c\xE1lculo.`);if(s.de=n.de,s.via=n.via,s.calculo=u,u!=="recuento"){if(typeof n.campo!="string"||!We.test(n.campo))throw i(`\xAB${s.etiqueta}\xBB: elige el campo que resume.`);s.campo=n.campo}if(u==="media_ponderada"){if(typeof n.peso!="string"||!We.test(n.peso))throw i(`\xAB${s.etiqueta}\xBB: elige el campo que pondera la media.`);s.peso=n.peso}else delete s.peso;let p=Ur(n.filtro,`\xAB${s.etiqueta}\xBB`);p?s.filtro=p:delete s.filtro,delete s.obligatorio}if(a==="qr"){let u=n.destino==="campo"||typeof n.campo=="string"&&n.campo&&n.destino!=="ficha"?"campo":"ficha";if(s.destino=u,u==="campo"){if(typeof n.campo!="string"||!We.test(n.campo))throw i(`\xAB${s.etiqueta}\xBB: elige el campo que resalta al escanear.`);s.campo=n.campo}else delete s.campo;delete s.obligatorio}return s}var Fs,If,Ws,Rf,kf,Tw,Mw,Iw,Lf,Lw,Bs,We,Df,Dw,zw,Fw,Ko,Ww,Bw,Pf,Tf,Mf,Vw,Jw,Qw,Jm,Vr=m(()=>{jp();Ep();Rp();Zm();As();Jp();R();ri();$m();nm();xs();um();hm();Am();rf();cf();km();xf();_s();pf();bf();Nf();Of();hi();qf();Tm();Fs=["texto","texto_largo","numero","importe","fecha","fecha_hora","booleano","seleccion","seleccion_multiple","etiquetas","url","correo","telefono","relacion","archivos","archivo","busqueda","resumen","duracion","hecho","porcentaje","valoracion","contador","cronometro","secreto","color","ubicacion","checklist","codigo","firma","hora","articulo","creado_el","creado_por","modificado_el","modificado_por","autonumero","formula","subtabla","boton","qr"],If=["creado_el","creado_por","modificado_el","modificado_por","autonumero"],Ws=["recuento","suma","minimo","maximo","ultimo","media","media_ponderada"],Rf=["igual","distinto","en","no_en","vacio","no_vacio","mayor","menor"],kf=5;Tw=["avisar","desvincular","impedir"],Mw=["companies","contacts","deals"],Iw=["id","numero","sales_id","creado","actualizado","espacio_id","modulo_id","datos"],Lf=new Set([...Iw,"q","filter","sort","order","page","perpage","limit","offset","select","from","where","insert","update","delete","drop","table","union","join","and","or","not","null","true","false","order","group","having","into","values","create","alter","grant","revoke","truncate","exec","execute","function","user","listar","ver","crear","actualizar","borrar","enlazar","buscar","exportar","importar","confirmar","idempotencia","operacion","tools","list","call","resources","prompts","__proto__","constructor","prototype"]),Lw=new Set(["companies","contacts","deals","sales","tasks","tags","notas","tareas","empresas","contactos","oportunidades","formularios","ajustes","miembros","configuracion","modulos","registros","objetos","adjuntos","api","rpc","v1","mcp"]),Bs=["box","boxes","package","folder","folder-open","file-text","clipboard-list","list-checks","calendar","calendar-days","clock","map-pin","truck","car","wrench","hammer","hard-hat","building","home","store","warehouse","factory","briefcase","shopping-cart","receipt","wallet","credit-card","piggy-bank","tag","tags","star","heart","flag","bookmark","user","users","graduation-cap","stethoscope","pill","utensils","coffee","shirt","camera","image","monitor","smartphone","server","database","key","shield","leaf","paw-print","dumbbell","ticket","gift","megaphone","mail","phone","message-square"],We=/^[a-z][a-z0-9_]{0,40}$/,Df=/^[a-z][a-z_]{1,30}$/,Dw=/^#[0-9a-fA-F]{6}$/,zw=/^[a-z][a-z_]{0,29}$/,Fw=["texto","correo","telefono","codigo"],Ko=(e,o,t,r=!1)=>{if(typeof e!="string")throw i(`Falta ${o}.`);let n=e.trim();if(!r&&!n||n.length>t)throw i(`${o}: entre ${r?0:1} y ${t} caracteres.`);return n};Ww=/^sub_[a-z]{8}$/,Bw=["texto","texto_largo","numero","importe","fecha","fecha_hora","booleano","seleccion","url","correo","telefono","duracion","porcentaje","valoracion","color","codigo","formula","hora","relacion","articulo","subtabla","resumen"],Pf=20,Tf=["nombre","referencia","codigo","precio","iva_pct"],Mf=30;Vw=[["texto","texto_largo"],["texto_largo","texto"],["texto","seleccion"],["seleccion","texto"],["numero","importe"],["importe","numero"],["texto","correo"],["texto","telefono"],["texto","url"],["correo","texto"],["telefono","texto"],["url","texto"],["fecha","fecha_hora"]],Jw=(e,o)=>Vw.some(([t,r])=>t===e&&r===o),Qw=/^[a-z0-9][a-z0-9-]{0,59}$/;Jm=e=>e.tipo==="busqueda"||e.tipo==="resumen"||e.tipo==="formula"||e.tipo==="subtabla"||e.tipo==="boton"||e.tipo==="qr"||e.tipo==="archivo"||If.includes(e.tipo)});function Wf(e){if(!e||typeof e!="object"||Array.isArray(e))throw i("F\xF3rmula proyectada no v\xE1lida.");let o=e;if(Object.keys(o).some(a=>!["expresion","campos"].includes(a))||typeof o.expresion!="string"||o.expresion.length>2e3||!Array.isArray(o.campos)||o.campos.length>40)throw i("F\xF3rmula proyectada no v\xE1lida.");let t=["texto","texto_largo","correo","telefono","url","codigo","color","numero","importe","duracion","porcentaje","valoracion","fecha","fecha_hora","booleano","seleccion","ubicacion","formula"],r=new Set,n=o.campos.map(a=>{if(!a||typeof a!="object"||typeof a.clave!="string"||!/^[a-z][a-z0-9_]{0,40}$/.test(a.clave)||r.has(a.clave)||typeof a.etiqueta!="string"||a.etiqueta.length>80||!t.includes(a.tipo)||a.tipo==="formula"&&(typeof a.formula!="string"||a.formula.length>2e3))throw i("F\xF3rmula proyectada no v\xE1lida.");return r.add(a.clave),{clave:a.clave,etiqueta:a.etiqueta,tipo:a.tipo,...a.tipo==="formula"?{formula:a.formula}:{}}});return{expresion:o.expresion,campos:n}}var Bf=m(()=>{R()});function Uf(e){if(!e||typeof e!="object"||Array.isArray(e))throw i("Resumen proyectado no v\xE1lido.");let o=e;if(Object.keys(o).some(t=>!["fuente","tipo","via","calculo","campo","peso","filtro"].includes(t))||o.tipo!==void 0&&(!["contacts","companies"].includes(o.fuente)||typeof o.tipo!="string"||!/^[a-z0-9][a-z0-9-]{0,59}$/.test(o.tipo))||typeof o.fuente!="string"||!/^(contacts|companies|deals|mod_(?!sub_)[a-z][a-z0-9_]{0,40})$/.test(o.fuente)||!Ws.includes(o.calculo)||[o.via,...o.calculo!=="recuento"?[o.campo]:[],...o.calculo==="media_ponderada"?[o.peso]:[]].some(t=>typeof t!="string"||!(/^[a-z][a-z0-9_]{0,40}$/.test(t)||["contacts","companies"].includes(o.fuente)&&/^datos\.[a-z][a-z0-9_]{0,40}$/.test(t))))throw i("Resumen proyectado no v\xE1lido.");Ur(o.filtro,"Resumen")}var Vf=m(()=>{R();Vr()});function Jf(e,o){if(!Array.isArray(e)||!e.length||e.length>100||e.some(t=>!t||typeof t!="object"||Array.isArray(t)||Object.keys(t).some(r=>!["campo","es","etiqueta","valor"].includes(r))||typeof t.valor!="string"||t.valor.length>100||(t.etiqueta!==void 0?typeof t.etiqueta!="string"||!t.etiqueta||t.etiqueta.length>60||t.campo!==void 0||t.es!==void 0:typeof t.campo!="string"||!/^[a-z][a-z0-9_]{0,40}$/.test(t.campo)||typeof t.es!="string"||t.es.length>100))||o!==void 0&&(typeof o!="string"||o.length>100))throw i("Casos de proyecci\xF3n no v\xE1lidos.")}var Qf=m(()=>{R()});var Gf,Hf=m(()=>{Gf=/^funciones\.[a-z0-9][a-z0-9-]{0,59}\.[a-z][a-z0-9_]{0,40}$/});function rr(e){if(e===void 0)return;if(JSON.stringify(e).length>6e4)throw i("La fuente combinada es demasiado grande.");if(!Array.isArray(e)||e.length<1||e.length>4)throw i("Una fuente combinada necesita de uno a cuatro or\xEDgenes.");let o=new Set;return e.map(t=>{if(!qo(t)||Object.keys(t).some(n=>!["fuente","filtro","campos"].includes(n))||typeof t.fuente!="string"||!Hw.test(t.fuente)||o.has(t.fuente))throw i("Origen combinado no v\xE1lido o repetido.");if(o.add(t.fuente),t.filtro!==void 0&&(!qo(t.filtro)||JSON.stringify(t.filtro).length>4e3))throw i("Filtro de origen no v\xE1lido.");if(!qo(t.campos)||Object.keys(t.campos).length>40)throw i("Proyecci\xF3n de origen no v\xE1lida.");let r=Object.fromEntries(Object.entries(t.campos).map(([n,a])=>{if(!Gw.test(n)||["id","objeto"].includes(n)||!qo(a)||Object.keys(a).some(c=>!["resumen","formula","permiso","casos","defecto","campo","soloFiltro","valor","alternativas","conversiones","condicion","equivalencias","etiqueta","opciones"].includes(c))||["campo","valor","alternativas","condicion","casos","resumen","formula"].filter(c=>Object.hasOwn(a,c)).length!==1||a.campo!==void 0&&(typeof a.campo!="string"||a.campo.length>125)||Object.hasOwn(a,"valor")&&a.valor!==null&&!["string","number","boolean"].includes(typeof a.valor)||a.alternativas!==void 0&&(!Array.isArray(a.alternativas)||a.alternativas.length!==2||a.alternativas.some(c=>typeof c!="string"||c.length>125))||a.condicion!==void 0&&(!qo(a.condicion)||JSON.stringify(a.condicion).length>4e3)||a.conversiones!==void 0&&(!qo(a.conversiones)||!Array.isArray(a.alternativas)||Object.entries(a.conversiones).some(([c,d])=>!a.alternativas.includes(c)||!qo(d)||Object.keys(d).length>100||Object.values(d).some(u=>typeof u!="string")))||a.permiso!==void 0&&(typeof a.permiso!="string"||!Gf.test(a.permiso)||!["contacts","companies"].includes(t.fuente)||!a.formula&&!a.resumen)||a.soloFiltro!==void 0&&typeof a.soloFiltro!="boolean"||a.etiqueta!==void 0&&(typeof a.etiqueta!="string"||a.etiqueta.length>80)||a.opciones!==void 0&&(!qo(a.opciones)||Object.keys(a.opciones).length>100||Object.values(a.opciones).some(c=>typeof c!="string"))||a.equivalencias!==void 0&&(!qo(a.equivalencias)||!a.campo||Object.keys(a.equivalencias).length>100||Object.values(a.equivalencias).some(c=>typeof c!="string")))throw i("Campo de proyecci\xF3n no v\xE1lido.");a.resumen!==void 0&&Uf(a.resumen);let s=a.formula===void 0?void 0:Wf(a.formula);if(a.casos!==void 0)Jf(a.casos,a.defecto);else if(a.defecto!==void 0)throw i("El defecto necesita casos de proyecci\xF3n.");return[n,{...structuredClone(a),...s?{formula:s}:{}}]}));return{fuente:t.fuente,campos:r,...t.filtro?{filtro:structuredClone(t.filtro)}:{}}})}var qo,Gw,Hw,$i=m(()=>{Bf();Vf();Qf();R();Hf();qo=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Gw=/^[a-z][a-z0-9_]{0,40}$/,Hw=/^(contacts|companies|deals|mod_(?!sub_)[a-z][a-z0-9_]{0,40})$/});function Xf(e,o){if(o==null||o==="")return null;if(!["contacts","companies"].includes(e)||typeof o!="string"||!/^[a-z0-9][a-z0-9-]{0,59}$/.test(o))throw i("El \xE1mbito de tipo necesita Personas o Empresas y una clave v\xE1lida.");return o}var Yf=m(()=>{R()});function Zf(e){let o=$e(e,"definici\xF3n");Be(o,["titulo","fuente","origenes","metrica","agrupar","dividir","filtro","periodo","grafico","top","comparar","meta"],"definici\xF3n");let t=De(o.fuente,"fuente",60),r=rr(o.origenes);if(t==="combinada"!=!!r)throw i("La fuente combinada necesita sus or\xEDgenes.");if(t!=="combinada"&&!Js.includes(t)&&!/^mod_(?!sub_)[a-z][a-z0-9_]{0,40}$/.test(t))throw i("\xABfuente\xBB no v\xE1lida.");let n=$e(o.metrica,"metrica");Be(n,["tipo","campo","por","filtro_a","filtro_b"],"metrica");let a=Ze(n.tipo,Vs,"metrica.tipo"),s={tipo:a,...n.campo!==void 0?{campo:De(n.campo,"metrica.campo",60)}:{},...n.por!==void 0?{por:De(n.por,"metrica.por",60)}:{},...n.filtro_a!==void 0&&n.filtro_a!==null?{filtro_a:$e(n.filtro_a,"metrica.filtro_a")}:{},...n.filtro_b!==void 0&&n.filtro_b!==null?{filtro_b:$e(n.filtro_b,"metrica.filtro_b")}:{}};if(["suma","media","min","max","minimo","maximo","mediana"].includes(a)&&!s.campo)throw i("Esa m\xE9trica necesita un campo.");if(a==="tasa_conversion"&&(n.filtro_a===void 0||n.filtro_b===void 0))throw i("\xABtasa_conversion\xBB necesita \xABfiltro_a\xBB y \xABfiltro_b\xBB.");if((a==="media_por"||a==="valor_medio_por")&&!s.por)throw i("\xABmedia_por\xBB necesita indicar el campo \xABpor\xBB para dividir.");let c;if(o.agrupar!==void 0&&o.agrupar!==null){let g=$e(o.agrupar,"agrupar");Be(g,["campo","paso"],"agrupar"),c={campo:De(g.campo,"agrupar.campo",60),...g.paso!==void 0?{paso:Ze(g.paso,nr,"agrupar.paso")}:{}}}let d;if(o.dividir!==void 0&&o.dividir!==null){let g=$e(o.dividir,"dividir");Be(g,["campo","paso"],"dividir"),d={campo:De(g.campo,"dividir.campo",60),...g.paso!==void 0?{paso:Ze(g.paso,nr,"dividir.paso")}:{}}}if(d&&!c)throw i("\xABDividir por\xBB solo se puede usar si se agrupa.");if(c&&d&&c.campo===d.campo)throw i("No se puede agrupar y dividir por el mismo campo.");let u;if(o.meta!==void 0&&o.meta!==null){if(typeof o.meta!="number"||Number.isNaN(o.meta)||o.meta<=0)throw i("\xABmeta\xBB: n\xFAmero mayor que 0.");u=o.meta}let p=o.periodo!==void 0&&o.periodo!==null?Qs(o.periodo):void 0,f=Ze(o.grafico,Xw,"grafico"),h=["numero","medidor","numero_tendencia"],b=["barras","barras_horizontales","lineas","area","dona","tabla","embudo"],v=["barras_apiladas","barras_agrupadas","varias_lineas","tabla_dinamica","mapa_calor"];if(h.includes(f)){if(c)throw i("Un n\xFAmero no se agrupa.");if(d)throw i("Un n\xFAmero no se divide.");if(f==="medidor"&&u===void 0)throw i("El medidor necesita una \xABmeta\xBB num\xE9rica.");if(f==="numero_tendencia"&&(!p||!o.comparar))throw i("\xABnumero_tendencia\xBB necesita un periodo con comparaci\xF3n.")}else if(b.includes(f)){if(!c)throw i("Ese gr\xE1fico necesita \xABagrupar\xBB.");if(d)throw i("Ese gr\xE1fico no admite \xABdividir por\xBB.")}else if(v.includes(f)){if(!c)throw i("Ese gr\xE1fico necesita \xABagrupar\xBB.");if(!d)throw i("Ese gr\xE1fico necesita \xABdividir por\xBB un segundo campo.")}if(o.top!==void 0&&(!Number.isSafeInteger(o.top)||o.top<1||o.top>Kf))throw i(`\xABtop\xBB: de 1 a ${Kf}.`);if(o.comparar!==void 0&&typeof o.comparar!="boolean")throw i("\xABcomparar\xBB: s\xED o no.");if(o.comparar&&!p)throw i("Para comparar hace falta un periodo.");if(o.comparar&&p?.proximos)throw i("\xABproximos\xBB no se compara (no hay periodo anterior).");if(o.comparar&&p?.preset)throw i("\xABpreset\xBB no se compara (todav\xEDa no se ha acabado).");let w=o.filtro===void 0||o.filtro===null?void 0:$e(o.filtro,"filtro");if(w&&JSON.stringify(w).length>4e3)throw i("\xABfiltro\xBB demasiado grande.");return{titulo:De(o.titulo??"","titulo"),fuente:t,...r?{origenes:r}:{},metrica:s,...c?{agrupar:c}:{},...d?{dividir:d}:{},...u!==void 0?{meta:u}:{},...w?{filtro:w}:{},...p?{periodo:p}:{},grafico:f,...o.top!==void 0?{top:o.top}:{},...o.comparar?{comparar:!0}:{}}}function Qs(e){let o=$e(e,"periodo");Be(o,["campo","ultimos","proximos","preset","desde","hasta"],"periodo");let t={campo:De(o.campo,"periodo.campo",60)};if(o.preset!==void 0&&(t.preset=Ze(o.preset,Yw,"periodo.preset")),o.ultimos!==void 0){let n=$e(o.ultimos,"periodo.ultimos");if(Be(n,["n","unidad"],"periodo.ultimos"),!Number.isSafeInteger(n.n)||n.n<1||n.n>3660)throw i("\xABperiodo.ultimos.n\xBB no v\xE1lido.");t.ultimos={n:n.n,unidad:Ze(n.unidad,nr,"periodo.ultimos.unidad")}}for(let n of["desde","hasta"])if(o[n]!==void 0){if(typeof o[n]!="string"||!Kw.test(o[n])||Number.isNaN(Date.parse(o[n])))throw i(`\xABperiodo.${n}\xBB: AAAA-MM-DD.`);t[n]=o[n]}if(o.proximos!==void 0){let n=$e(o.proximos,"periodo.proximos");if(Be(n,["n","unidad"],"periodo.proximos"),!Number.isSafeInteger(n.n)||n.n<1||n.n>3660)throw i("\xABperiodo.proximos.n\xBB no v\xE1lido.");t.proximos={n:n.n,unidad:Ze(n.unidad,nr,"periodo.proximos.unidad")}}let r=[!!t.ultimos,!!t.proximos,!!t.preset,!!(t.desde||t.hasta)].filter(Boolean).length;if(!r)throw i("\xABperiodo\xBB: di \xABultimos\xBB, \xABproximos\xBB, \xABpreset\xBB o \xABdesde\xBB/\xABhasta\xBB.");if(r>1)throw i("\xABperiodo\xBB: solo una de \xABultimos\xBB, \xABproximos\xBB, \xABpreset\xBB o \xABdesde\xBB/\xABhasta\xBB.");return t}var Vs,Xw,nr,Js,Yw,Kf,Kw,$e,Be,Ze,De,Gs=m(()=>{$i();R();Vs=["recuento","suma","media","min","max","minimo","maximo","mediana","porcentaje_total","acumulado","tasa_conversion","media_por","valor_medio_por"],Xw=["numero","barras","lineas","dona","tabla","barras_horizontales","barras_apiladas","barras_agrupadas","area","varias_lineas","embudo","medidor","numero_tendencia","tabla_dinamica","mapa_calor"],nr=["dia","semana","mes","anio"],Js=["companies","contacts","deals"],Yw=["hoy","semana","mes","trimestre","anio"],Kf=50,Kw=/^\d{4}-\d{2}-\d{2}$/,$e=(e,o)=>{if(typeof e!="object"||e===null||Array.isArray(e))throw i(`\xAB${o}\xBB tiene que ser un objeto.`);return e},Be=(e,o,t)=>{for(let r of Object.keys(e))if(!o.includes(r))throw i(`\xAB${t}\xBB: clave no admitida \xAB${r.slice(0,40)}\xBB.`)},Ze=(e,o,t)=>{if(typeof e!="string"||!o.includes(e))throw i(`\xAB${t}\xBB no v\xE1lido.`);return e},De=(e,o,t=80)=>{if(typeof e!="string"||e.length>t)throw i(`\xAB${o}\xBB no v\xE1lido.`);return e}});function nh(e,o){if(e===null)return null;if(!Ro(e))throw i("La disposici\xF3n no es v\xE1lida.");if(!tv.test(o))throw i("Esta tabla no admite widgets.");for(let d of Object.keys(e))if(d!=="zonas"&&d!=="widgets")throw i("La disposici\xF3n no es v\xE1lida.");if(!Ro(e.zonas))throw rh();let t=e.zonas,r=Ro(e.widgets)?e.widgets:{};for(let d of Object.keys(t))if(!eh.includes(d))throw i("Zona no v\xE1lida.");let n={},a=new Set;for(let d of eh){let u=t[d]??[];if(!Array.isArray(u))throw i("Zona no v\xE1lida.");n[d]=u.map(p=>{if(typeof p!="string"||p!==Hs&&!ov.test(p))throw i("Bloque no v\xE1lido.");if(a.has(p))throw i("Un bloque solo puede estar en un sitio.");return a.add(p),p})}if(!a.has(Hs))throw rh();if(n.arriba.length>th)throw i(`Arriba caben como mucho ${th} bloques.`);let s={};for(let[d,u]of Object.entries(r)){if(!a.has(d))continue;if(!Ro(u))throw i("Widget no v\xE1lido.");let p=Zf(u.definicion);if(u.via!==void 0&&(typeof u.via!="string"||!rv.test(u.via)))throw i("\xABvia\xBB no v\xE1lida.");if(u.via===void 0&&p.fuente!==o)throw i("Un widget de esta tabla solo mide esta tabla o sus relaciones.");s[d]={definicion:p,seguir_filtros:u.seguir_filtros!==!1,...u.via!==void 0?{via:u.via}:{}}}for(let d of a)if(d!==Hs&&!s[d])throw i("Falta la definici\xF3n de un widget.");if(Object.keys(s).length>oh)throw i(`Como mucho ${oh} widgets por vista.`);let c={zonas:n,widgets:s};if(JSON.stringify(c).length>6e4)throw i("La disposici\xF3n es demasiado grande.");return c}function nv(e){if(!(e==null||e==="")){if(typeof e!="string"||!/^[a-z0-9][a-z0-9_:.-]{0,79}$/.test(e))throw i("El \xE1mbito de la vista no es v\xE1lido.");return e}}function ih(e){if(!Ro(e))throw i("La vista no es v\xE1lida.");let o=Ro(e.pref)?Object.fromEntries(Object.entries(e.pref).filter(([d])=>Zw.has(d))):{};if(o.vistaOrigen!==void 0&&(typeof o.vistaOrigen!="string"||o.vistaOrigen.length>160))throw i("La vista de origen no es v\xE1lida.");if(o.vista!==void 0&&!ev.has(String(o.vista)))throw i("El tipo de vista no es v\xE1lido.");let t=Ro(e.filtros)?e.filtros:{};if(Object.keys(t).length>40||Object.keys(t).some(d=>!/^[a-zA-Z0-9_@.:-]{1,80}$/.test(d)))throw i("Los filtros de la vista no son v\xE1lidos.");let r=null;if(Ro(e.orden)){let{field:d,order:u}=e.orden;if(typeof d!="string"||!/^[a-zA-Z0-9_.]{1,80}(,[a-zA-Z0-9_.]{1,80}){0,2}$/.test(d)||typeof u!="string"||!/^(ASC|DESC)(,(ASC|DESC)){0,2}$/.test(u))throw i("El orden de la vista no es v\xE1lido.");r={field:d,order:u}}let n=e.origenes===void 0?void 0:rr(e.origenes),a;if(n||e.columnasCalculadas!==void 0){if(!n||n.length!==1||!["contacts","companies"].includes(n[0].fuente)||!Ro(e.columnasCalculadas)||Object.keys(e.columnasCalculadas).length>40||Object.entries(e.columnasCalculadas).some(([d,u])=>!/^calc_[a-f0-9]{24}$/.test(d)||typeof u!="string"||!Object.hasOwn(n[0].campos,u)))throw i("Columnas calculadas de vista no v\xE1lidas.");a=e.columnasCalculadas}let s=nv(e.ambito),c={pref:o,filtros:t,orden:r,...s?{ambito:s}:{},...n?{origenes:n,columnasCalculadas:a}:{}};if(JSON.stringify(c).length>3e4)throw i("La vista es demasiado grande.");return c}var Zw,ev,eh,Hs,ov,oh,th,tv,rv,rh,Ro,ah=m(()=>{$i();R();Gs();Zw=new Set(["vistaOrigen","vista","visibles","orden","anchos","fijadas","calculos","agrupar","grupo","vistas","separar"]),ev=new Set(["tabla","lista","kanban","calendario","galeria","linea","mapa"]),eh=["arriba","izquierda","centro","derecha","abajo"],Hs="tabla",ov=/^w_[a-z0-9]{1,24}$/,oh=24,th=6,tv=/^(contacts|companies|deals|mod_(?!sub_)[a-z][a-z0-9_]{1,40})$/,rv=/^[a-z][a-z0-9_]{0,59}$/,rh=()=>new F(400,"tabla_obligatoria","La tabla no se puede quitar de la vista: mu\xE9vela, pero d\xE9jala.");Ro=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)});function sh(e){let o=new Set,t=r=>{typeof r=="string"&&r.startsWith("mod_")&&o.add(r.slice(4))};if(Xs(e.personas)&&t(e.personas.modulo),Array.isArray(e.secciones)){for(let r of e.secciones)if(Xs(r)&&(t(r.modulo),Array.isArray(r.camino)))for(let n of r.camino)Xs(n)&&t(n.modulo)}return o}var Xs,ch=m(()=>{Xs=e=>!!e&&typeof e=="object"&&!Array.isArray(e)});function sv(e){if(typeof e!="string"||!av.test(e))throw i("\xABrecurso\xBB: contacts, companies, deals o mod_<clave>.");return e}function cv(e){if(!iv.includes(e))throw i("\xABcanal\xBB: whatsapp o correo.");return e}function uh(e,o="Plantilla"){if(!e||typeof e!="object"||Array.isArray(e))throw i(`${o}: un objeto.`);let t=e;for(let s of Object.keys(t))if(!["recurso","tipoContacto","canal","nombre","asunto","texto"].includes(s))throw i(`${o}: clave no admitida \xAB${s.slice(0,40)}\xBB.`);let r=sv(t.recurso);if(t.tipoContacto!==void 0&&t.tipoContacto!==null&&(!Dr(r)||typeof t.tipoContacto!="string"||!/^[a-z0-9][a-z0-9-]{0,59}$/.test(t.tipoContacto)))throw i("El tipo de una plantilla necesita Personas o Empresas y una clave de tipo v\xE1lida.");let n=cv(t.canal),a=n==="correo"?Ys(t.asunto,`${o}, asunto`,300,!1):void 0;return{recurso:r,...t.tipoContacto?{tipoContacto:t.tipoContacto}:{},canal:n,nombre:Ys(t.nombre,`${o}, nombre`,80),...a?{asunto:a}:{},texto:Ys(t.texto,`${o}, texto`,5e3)}}var iv,xi,av,lh,BL,Ys,Ks=m(()=>{ni();R();iv=["whatsapp","correo"],xi=50,av=/^(contacts|companies|deals|mod_(?!sub_)[a-z][a-z0-9_]{0,40})$/,lh="(?:datos\\.)?[a-z][a-z0-9_]{0,40}",BL=new RegExp(`\\{\\{\\s*(${lh}(?:\\|${lh})?)\\s*\\}\\}`,"g"),Ys=(e,o,t,r=!0)=>{if(e==null||e===""){if(r)throw i(`${o}: obligatorio.`);return}if(typeof e!="string"||e.trim().length>t)throw i(`${o}: un texto de hasta ${t} caracteres.`);return e.trim()}});import{BlockList as dh,isIP as lv}from"node:net";var ph,mh,fh,hh=m(()=>{ph=new dh,mh=new dh;for(let[e,o]of[["0.0.0.0",8],["10.0.0.0",8],["100.64.0.0",10],["127.0.0.0",8],["169.254.0.0",16],["172.16.0.0",12],["192.0.0.0",24],["192.0.2.0",24],["192.88.99.0",24],["192.168.0.0",16],["198.18.0.0",15],["198.51.100.0",24],["203.0.113.0",24],["224.0.0.0",4],["240.0.0.0",4]])ph.addSubnet(e,o,"ipv4");for(let[e,o]of[["::",128],["::1",128],["::ffff:0:0",96],["::",96],["64:ff9b::",96],["64:ff9b:1::",48],["100::",64],["2001::",32],["2001:db8::",32],["2002::",16],["fc00::",7],["fe80::",10],["fec0::",10],["ff00::",8]])mh.addSubnet(e,o,"ipv6");fh=e=>{let o=lv(e);return o===4?ph.check(e,"ipv4"):o===6?mh.check(e,"ipv6"):!0}});function wh(e){let o=$e(e,"informe");Be(o,["fuente","origenes","filtro","periodo","columnas","agrupar","agregados","orden"],"informe");let t=De(o.fuente,"fuente",60),r=rr(o.origenes);if(t==="combinada"!=!!r)throw i("La fuente combinada necesita sus or\xEDgenes.");if(t!=="combinada"&&!Js.includes(t)&&!/^mod_(?!sub_)[a-z][a-z0-9_]{0,40}$/.test(t))throw i("\xABfuente\xBB no v\xE1lida.");let n={fuente:t,...r?{origenes:r}:{}};if(o.filtro!==void 0&&o.filtro!==null&&(n.filtro=$e(o.filtro,"filtro"),JSON.stringify(n.filtro).length>4e3))throw i("\xABfiltro\xBB demasiado grande.");if(o.periodo!==void 0&&o.periodo!==null&&(n.periodo=Qs(o.periodo)),o.columnas!==void 0&&o.columnas!==null){if(!Array.isArray(o.columnas)||o.columnas.length>gh)throw i(`\xABcolumnas\xBB: una lista de hasta ${gh}.`);n.columnas=[...new Set(o.columnas.map((a,s)=>De(a,`columnas[${s}]`,60)))]}if(o.agrupar!==void 0&&o.agrupar!==null){let a=$e(o.agrupar,"agrupar");Be(a,["campo","paso"],"agrupar"),n.agrupar={campo:De(a.campo,"agrupar.campo",60),...a.paso!==void 0?{paso:Ze(a.paso,nr,"agrupar.paso")}:{}}}if(o.agregados!==void 0&&o.agregados!==null){if(!Array.isArray(o.agregados)||o.agregados.length>bh)throw i(`\xABagregados\xBB: una lista de hasta ${bh}.`);n.agregados=o.agregados.map((a,s)=>{let c=$e(a,`agregados[${s}]`);Be(c,["tipo","campo"],`agregados[${s}]`);let d=Ze(c.tipo,Vs,`agregados[${s}].tipo`);if(d!=="recuento"&&c.campo===void 0)throw i(`\xABagregados[${s}]\xBB: esa operaci\xF3n necesita un campo.`);return{tipo:d,...d!=="recuento"?{campo:De(c.campo,`agregados[${s}].campo`,60)}:{}}})}if(n.agrupar&&!n.agregados?.length&&(n.agregados=[{tipo:"recuento"}]),o.orden!==void 0&&o.orden!==null){let a=$e(o.orden,"orden");Be(a,["por","sentido"],"orden"),n.orden={por:De(a.por,"orden.por",60),sentido:Ze(a.sentido??"asc",["asc","desc"],"orden.sentido")}}return n}var gh,bh,vh=m(()=>{$i();R();Gs();gh=30,bh=6});var Zs,uv,yh,_h=m(()=>{Zs=[{clave:"leo",nombre:"Leo",puesto:"Marketing"},{clave:"marina",nombre:"Marina",puesto:"Administrativa"},{clave:"dario",nombre:"Dar\xEDo",puesto:"Comercial"},{clave:"nora",nombre:"Nora",puesto:"Finanzas"},{clave:"irene",nombre:"Irene",puesto:"Consultora de procesos"}],uv=e=>`pix.agente_${e}`,yh=e=>Zs.some(o=>uv(o.clave)===e)});var Nh,$h=m(()=>{Nh=["contacts","companies","deals","tareas","proyectos"]});function xh(e,o,t){if(typeof e!="string"||!e.trim())throw i(`Falta \xAB${o}\xBB.`);let r=e.trim();if(r.length>t)throw i(`\xAB${o}\xBB: como mucho ${t} caracteres.`);return r}function Ch(e){if(e===void 0)return;if(!e||typeof e!="object"||Array.isArray(e))throw i("\xABpix\xBB: un objeto.");let o=e;for(let n of Object.keys(o))if(n!=="personalidad")throw i(`\xABpix\xBB: no admite \xAB${n.slice(0,40)}\xBB.`);let t=o.personalidad;if(!t||typeof t!="object"||Array.isArray(t))throw i("\xABpix.personalidad\xBB: un objeto con nombre e instrucciones.");let r=t;for(let n of Object.keys(r))if(n!=="nombre"&&n!=="instrucciones")throw i(`\xABpix.personalidad\xBB: no admite \xAB${n.slice(0,40)}\xBB.`);return{personalidad:{nombre:xh(r.nombre,"pix.personalidad.nombre",pv),instrucciones:xh(r.instrucciones,"pix.personalidad.instrucciones",dv)}}}var dv,pv,jh=m(()=>{R();dv=2e3,pv=60});function Oh(e,o){if(e===void 0)return[];if(!Array.isArray(e)||e.length>Qr)throw i(`\xABinformes\xBB: una lista de hasta ${Qr}.`);let t=new Set;return e.map((r,n)=>{if(!mv(r))throw i(`Informe ${n+1}: un objeto.`);for(let c of Object.keys(r))if(!["nombre","descripcion","definicion"].includes(c))throw i(`Informe ${n+1}: clave no admitida \xAB${c.slice(0,40)}\xBB.`);if(typeof r.nombre!="string"||!r.nombre.trim()||r.nombre.length>80)throw i(`Informe ${n+1}: un nombre de hasta 80 caracteres.`);if(r.descripcion!==void 0&&(typeof r.descripcion!="string"||r.descripcion.length>500))throw i(`Informe ${n+1}: la descripci\xF3n, hasta 500 caracteres.`);let a=r.nombre.trim();if(t.has(a))throw i(`Dos informes se llaman \xAB${a}\xBB.`);t.add(a);let s=wh(r.definicion);if([s.fuente,...s.origenes?.map(c=>c.fuente)??[]].some(c=>c.startsWith("mod_")&&!o.includes(c.slice(4))))throw i(`Informe \xAB${a}\xBB: su fuente no es un m\xF3dulo de la soluci\xF3n.`);return{nombre:a,...r.descripcion?{descripcion:r.descripcion}:{},definicion:s}})}var Qr,mv,ec=m(()=>{R();vh();Qr=30,mv=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)});var Sh,mo,ir,ar,K,oc,sr,hD,fv,Ci,hv,gv,gD,bD,Ah=m(()=>{_h();Sh={ver:["si","no","suyos","equipo","ambito","jerarquia"],editar:["si","no","suyos","equipo","ambito","jerarquia"],borrar:["si","no","suyos","equipo","ambito","jerarquia"],exportar:["si","no","suyos"],importar:["si","no"],crear:["si","no","suyos","equipo","ambito","jerarquia"],reasignar:["si","no","suyos","jerarquia"],estado:["si","no","suyos","equipo","ambito","jerarquia"],descargar:["si","no"],revelar:["si","no"]},mo=["si","no","suyos"],ir=["si","no","suyos","equipo","jerarquia"],ar=["si","no","suyos","jerarquia"],K=["si","no"],oc=(e,o,t=!0)=>[{clave:`${e}.ver`,descripcion:`Ver ${o}`,valores:ar},{clave:`${e}.crear`,descripcion:`Dar de alta ${o}`,valores:ar},{clave:`${e}.editar`,descripcion:`Editar ${o}`,valores:ar},{clave:`${e}.reasignar`,descripcion:`Cambiar el responsable de ${o}`,valores:ar},...t?[{clave:`${e}.estado`,descripcion:`Cambiar el estado de ${o}`,valores:ar}]:[],{clave:`${e}.descargar`,descripcion:`Bajar los ficheros de ${o}`,valores:K},{clave:`${e}.borrar`,descripcion:`Borrar ${o}`,valores:ar},{clave:`${e}.exportar`,descripcion:`Exportar ${o}`,valores:mo},{clave:`${e}.importar`,descripcion:`Importar ${o} desde una hoja`,valores:K}],sr=[...oc("contactos","contactos"),...oc("empresas","empresas",!1),...oc("oportunidades","oportunidades"),{clave:"proyectos.ver",descripcion:"Ver proyectos",valores:ir},{clave:"proyectos.editar",descripcion:"Editar los datos del proyecto",valores:ir},{clave:"proyectos.borrar",descripcion:"Borrar proyectos",valores:ir},{clave:"proyectos.exportar",descripcion:"Exportar proyectos",valores:mo},{clave:"proyectos.crear",descripcion:"Crear proyectos",valores:K},{clave:"proyectos.gestionar",descripcion:"Cambiar el estado, el responsable, los participantes, las columnas y los ajustes de los proyectos, y gestionar plantillas",valores:K},{clave:"tareas.ver",descripcion:"Ver tareas",valores:ir},{clave:"tareas.crear",descripcion:"Crear tareas",valores:K},{clave:"tareas.editar",descripcion:"Editar y completar tareas",valores:ir},{clave:"tareas.borrar",descripcion:"Borrar tareas",valores:ir},{clave:"tareas.exportar",descripcion:"Exportar tareas visibles",valores:mo},{clave:"notas.ver",descripcion:"Ver notas",valores:mo},{clave:"notas.editar",descripcion:"Escribir, editar y borrar notas",valores:mo},{clave:"adjuntos.ver",descripcion:"Ver y descargar adjuntos",valores:mo},{clave:"adjuntos.subir",descripcion:"Subir adjuntos",valores:mo},{clave:"miembros.gestionar",descripcion:"Invitar, cambiar el papel y desactivar miembros",valores:K},{clave:"conectores.accionar",descripcion:"Ejecutar acciones f\xEDsicas de conectores",valores:K},{clave:"configuracion.gestionar",descripcion:"Cambiar la configuraci\xF3n del espacio y los permisos",valores:K},{clave:"formularios.gestionar",descripcion:"Crear, editar y borrar formularios (y sus respuestas)",valores:K},{clave:"formularios.ver_respuestas",descripcion:"Ver las respuestas de los formularios",valores:mo},{clave:"modulos.configurar",descripcion:"Dise\xF1ar, publicar y archivar m\xF3dulos",valores:K},{clave:"paneles.ver",descripcion:"Ver los paneles de m\xE9tricas",valores:K},{clave:"paneles.editar",descripcion:"Crear, cambiar y borrar paneles de m\xE9tricas",valores:K},{clave:"paneles.compartir",descripcion:"Compartir paneles con el equipo y cambiar o borrar los de equipo",valores:K},{clave:"automatizaciones.gestionar",descripcion:"Crear y cambiar automatizaciones, y ver sus ejecuciones",valores:K},{clave:"campanas.gestionar",descripcion:"Crear y enviar campa\xF1as de correo, y gestionar consentimientos y supresiones",valores:K},{clave:"agenda.ver",descripcion:"Ver las citas de la agenda",valores:mo},{clave:"agenda.editar",descripcion:"Crear, mover y cancelar citas",valores:mo},{clave:"agenda.configurar",descripcion:"Configurar la agenda: tipos de cita, d\xEDas cerrados, horarios, reserva p\xFAblica y los recursos (horarios y aprobar ausencias)",valores:K},{clave:"analisis.ver",descripcion:"Usar An\xE1lisis: informes de lo que ya puede ver",valores:K},{clave:"analisis.compartir",descripcion:"Compartir informes con el equipo y cambiar o borrar los de equipo",valores:K},{clave:"secretos.ver",descripcion:"Ver los campos secretos (cada vez queda registrado qui\xE9n lo vio)",valores:K},{clave:"liquidaciones.gestionar",descripcion:"Generar, aprobar, cerrar, pagar y reabrir liquidaciones de comisiones",valores:K},{clave:"portales.gestionar",descripcion:"Configurar los portales, invitar a ellos y revocar el acceso",valores:K},{clave:"auditoria.ver",descripcion:"Ver la auditor\xEDa del espacio (qui\xE9n hizo qu\xE9 y cu\xE1ndo)",valores:K},{clave:"publico.compartir",descripcion:"Compartir la p\xE1gina p\xFAblica de un registro (un enlace que caduca)",valores:K},{clave:"pix.memoria_espacio",descripcion:"Escribir lo que Pix recuerda para todo el espacio",valores:K},...Zs.map(e=>({clave:`pix.agente_${e.clave}`,descripcion:`Usar a ${e.nombre} (${e.puesto}) del Equipo IA`,valores:K}))],hD=new Set(sr.map(e=>e.clave)),fv=e=>/\.(exportar|importar)$/.test(e),Ci=e=>Object.fromEntries(sr.map(o=>[o.clave,e(o)])),hv=e=>e.clave.startsWith("miembros.")||e.clave.startsWith("configuracion.")||e.clave==="formularios.gestionar"||e.clave.startsWith("proyectos.")&&e.clave!=="proyectos.ver"&&e.clave!=="proyectos.exportar"||e.clave==="modulos.configurar"||e.clave==="agenda.configurar"||e.clave==="paneles.compartir"||e.clave==="automatizaciones.gestionar"||e.clave==="campanas.gestionar"||e.clave==="analisis.compartir"||e.clave==="liquidaciones.gestionar"||e.clave==="portales.gestionar"||e.clave==="auditoria.ver"||e.clave==="pix.memoria_espacio"||yh(e.clave),gv={titular:Ci(()=>"si"),administrador:Ci(e=>e.clave==="conectores.accionar"?"no":"si"),miembro:Ci(e=>hv(e)||e.clave==="conectores.accionar"||e.clave==="secretos.ver"||fv(e.clave)?"no":"si"),lectura:Ci(e=>e.clave.endsWith(".ver")&&e.clave!=="secretos.ver"&&e.clave!=="auditoria.ver"||e.clave.endsWith(".descargar")?"si":e.clave.endsWith(".reasignar")?"suyos":"no")},gD=sr.filter(e=>/^((contactos|empresas|oportunidades|proyectos|tareas|notas|adjuntos)\.|agenda\.(ver|editar)$)/.test(e.clave)&&e.valores.includes("suyos")&&gv.miembro[e.clave]!=="no").map(e=>e.clave),bD=sr.filter(e=>/^((contactos|empresas|oportunidades|proyectos|tareas|notas|adjuntos)\.|agenda\.(ver|editar)$)/.test(e.clave)&&e.valores.includes("suyos")).map(e=>e.clave)});function Rh(e){if(!Array.isArray(e))throw i("Los sin\xF3nimos van en una lista de palabras.");let o=[],t=new Set;for(let r of e){if(typeof r!="string")throw i("Cada sin\xF3nimo es un texto.");let n=r.replace(/\s+/g," ").trim();if(n){if(n.length>Eh)throw i(`\xAB${n.slice(0,20)}\u2026\xBB: como mucho ${Eh} caracteres.`);if(!tc(n))throw i(`\xAB${n}\xBB no es una palabra.`);t.has(tc(n))||(t.add(tc(n)),o.push(n))}}if(o.length>rc)throw i(`Como mucho ${rc} sin\xF3nimos por m\xF3dulo.`);return o}var qh,rc,Eh,tc,kh=m(()=>{R();qh=["contacts","companies","deals","tasks"],rc=20,Eh=40,tc=e=>e.normalize("NFD").replace(/[̀-ͯ]/g,"").toLowerCase().replace(/[^a-z0-9ñ\s-]/g," ").replace(/\s+/g," ").trim()});function vv(e,o){return ho(e,ac,"vistasTabla").map((t,r)=>{let n=`Vista de tabla ${r+1}`;if(!me(t))throw i(`${n}: un objeto.`);fo(t,["objeto","tipoContacto","nombre","config","disposicion"],n);let a=typeof t.objeto=="string"?t.objeto:"";if(!["contacts","companies"].includes(a)&&(!a.startsWith("mod_")||!o.includes(a.slice(4))))throw i(`${n}: de un m\xF3dulo de la soluci\xF3n (mod_<clave>).`);let s=nh(t.disposicion??null,a),c=Xf(a,t.tipoContacto);return{objeto:a,...c?{tipoContacto:c}:{},nombre:Zo(t.nombre,`nombre de la ${n.toLowerCase()}`,60),...t.config!==void 0?{config:ih(t.config)}:{},disposicion:s}})}function $v(e,o,t=[]){let r=new Set;return ho(e,cc,"papeles").map((n,a)=>{let s=`Papel ${a+1}`;if(!me(n))throw i(`${s}: un objeto.`);fo(n,["nombre","base","permisos","ocultos","lectura","identidades"],s);let c=Zo(n.nombre,`nombre del ${s.toLowerCase()}`,40);if(r.has(c.toLowerCase()))throw i(`${s}: nombre repetido.`);if(r.add(c.toLowerCase()),typeof n.base!="string"||!_v.includes(n.base))throw i(`${s}: \xABbase\xBB, administrador, miembro o lectura.`);let d={};if(n.permisos!==void 0){if(!me(n.permisos))throw i(`${s}: \xABpermisos\xBB, un objeto.`);for(let[b,v]of Object.entries(n.permisos)){if(b==="miembros.gestionar"||b==="configuracion.gestionar")throw i(`${s}: \xAB${b}\xBB no se da en un papel personalizado.`);let w=Nv.exec(b),g=sr.find(C=>C.clave===b);if(w?!o.includes(w[1]):!g)throw i(`${s}: permiso desconocido \xAB${b.slice(0,60)}\xBB.`);let y=g?g.valores:Sh[w[2]];if(typeof v!="string"||!y.includes(v))throw i(`${s}: valor no v\xE1lido para \xAB${b.slice(0,60)}\xBB.`);d[b]=v}}let u=(b,v)=>{if(b===void 0)return[];if(!Array.isArray(b)||b.length>100)throw i(`${s}: \xAB${v}\xBB, una lista (hasta 100) de \xABmod_<clave>.<campo>\xBB.`);return b.map(w=>{let g=typeof w=="string"?yv.exec(w):null,y=g?t.find(C=>C.clave===g[1]):void 0;if(!g||!y||!y.campos.some(C=>C.clave===g[2]))throw i(`${s}: \xAB${String(w).slice(0,60)}\xBB no es un campo de un m\xF3dulo de la soluci\xF3n.`);return w})},p=u(n.ocultos,"ocultos"),f=u(n.lectura,"lectura"),h=$p(n.identidades);return{nombre:c,base:n.base,...Object.keys(d).length?{permisos:d}:{},...p.length?{ocultos:p}:{},...f.length?{lectura:f}:{},...h.length?{identidades:h}:{}}})}function nc(e,o=0){if(o>30)throw i("La soluci\xF3n anida demasiado.");if(Array.isArray(e))return e.forEach(t=>nc(t,o+1));if(me(e))for(let t of Object.keys(e)){if(wv.has(t))throw i(`Clave no admitida \xAB${t}\xBB.`);nc(e[t],o+1)}}function fo(e,o,t){for(let r of Object.keys(e))if(!o.includes(r))throw i(`${t}: clave no admitida \xAB${r.slice(0,40)}\xBB.`)}function Zo(e,o,t,r=!0){if(e==null||e===""){if(r)throw i(`Falta \xAB${o}\xBB.`);return""}if(typeof e!="string"||e.length>t)throw i(`\xAB${o}\xBB: texto de hasta ${t} caracteres.`);return e.trim()}function Ai(e,o){if(typeof e=="string"){if(e.length>Oi)throw i("La soluci\xF3n pasa de 1 MB.");try{e=JSON.parse(e)}catch{throw i("La soluci\xF3n no es un JSON v\xE1lido.")}}else if(JSON.stringify(e??null).length>Oi)throw i("La soluci\xF3n pasa de 1 MB.");if(!me(e))throw i("La soluci\xF3n tiene que ser un objeto.");nc(e),fo(e,["formato","version","plantilla","nombre","descripcion","icono","modulos","paneles","automatizaciones","ejemplos","informes","principal","mensajes","papeles","portales","vistasTabla","separadores","menu","sinonimos","perfilesImportacion","senales","pix"],"Soluci\xF3n");let t;if(e.plantilla!==void 0){let $=e.plantilla;if(!me($))throw i("\xABplantilla\xBB: un objeto.");if(fo($,["id","version","sector","nivel"],"Plantilla"),typeof $.id!="string"||!/^[a-z][a-z0-9_]{0,59}$/.test($.id))throw i("\xABplantilla.id\xBB: min\xFAsculas, n\xFAmeros y _.");if(!Number.isInteger($.version)||$.version<1)throw i("\xABplantilla.version\xBB: un entero.");if(typeof $.sector!="string"||!/^[a-z][a-z0-9_]{0,39}$/.test($.sector))throw i("\xABplantilla.sector\xBB: min\xFAsculas y _.");if($.nivel!==void 0&&$.nivel!=="completa"&&$.nivel!=="basica")throw i("\xABplantilla.nivel\xBB: completa o basica.");t={id:$.id,version:$.version,sector:$.sector,...$.nivel==="basica"?{nivel:"basica"}:{}}}if(e.formato!==Et)throw i(`No es una soluci\xF3n (formato \xAB${Et}\xBB).`);if(!Number.isInteger(e.version)||e.version<1)throw i("\xABversion\xBB: un entero.");if(e.version>cr)throw i("La soluci\xF3n es de una versi\xF3n m\xE1s nueva del CRM.");let r=Zo(e.icono,"icono",40,!1)||"boxes";if(!Ph.test(r))throw i("\xABicono\xBB: un icono de lucide.");if(!Array.isArray(e.modulos)||e.modulos.length<1||e.modulos.length>ji)throw i(`Una soluci\xF3n lleva de 1 a ${ji} m\xF3dulos.`);let n=e.modulos.map($=>me($)&&typeof $.clave=="string"?$.clave:"");if(new Set(n).size!==n.length)throw i("Dos m\xF3dulos de la soluci\xF3n con la misma clave.");let a=new Map([...o.externos??[]].filter(([$])=>!n.includes($))),s=[...n,...a.keys()],c=new Map([...a,...e.modulos.map(($,A)=>[n[A],Us($,s)])]),d=e.modulos.map($=>{let A=Ff($,{topeCampos:o.topeCampos,modulosDelEspacio:s,camposRelacion:c}),N=me($)?$.sin_coste:void 0;if(N!==void 0&&N!==!0)throw i(`\xAB${A.nombre_plural}\xBB: \xABsin_coste\xBB solo puede ser true.`);return N===!0?{...A,sin_coste:!0}:A}),u=ho(e.paneles,ic,"paneles").map(($,A)=>{if(!me($))throw i(`Panel ${A+1}: un objeto.`);if(fo($,["nombre","icono","widgets"],`Panel ${A+1}`),!Array.isArray($.widgets)||$.widgets.length>20)throw i(`Panel ${A+1}: hasta 20 widgets.`);let N=Zo($.icono,"icono",40,!1);if(N&&!Ph.test(N))throw i(`Panel ${A+1}: icono no v\xE1lido.`);return{nombre:Zo($.nombre,"nombre del panel",60),...N?{icono:N}:{},widgets:$.widgets}}),p=ho(e.automatizaciones,sc,"automatizaciones").map(($,A)=>{if(!me($))throw i(`Automatizaci\xF3n ${A+1}: un objeto.`);if(fo($,["nombre","definicion"],`Automatizaci\xF3n ${A+1}`),!me($.definicion))throw i(`Automatizaci\xF3n ${A+1}: falta su definici\xF3n.`);return{nombre:Zo($.nombre,"nombre de la automatizaci\xF3n",80),definicion:$.definicion}}),f=ho(e.senales,20,"senales").map(($,A)=>{if(!me($))throw i(`Se\xF1al ${A+1}: un objeto.`);fo($,["fuente","regla"],`Se\xF1al ${A+1}`);let N=typeof $.fuente=="string"?$.fuente:"";if(!(N.startsWith("mod_")?n.includes(N.slice(4)):Nh.includes(N)))throw i(`Se\xF1al ${A+1}: \xABfuente\xBB, un m\xF3dulo de la soluci\xF3n (mod_<clave>) o un nativo.`);if(!me($.regla))throw i(`Se\xF1al ${A+1}: falta su regla.`);return{fuente:N,regla:$.regla}}),h=Ch(e.pix),b=Oh(e.informes,n);if(e.principal!==void 0&&(typeof e.principal!="string"||!n.includes(e.principal)))throw i("\xABprincipal\xBB: la clave de uno de sus m\xF3dulos.");let v=ho(e.mensajes,xi,"mensajes").map(($,A)=>{let N=uh($,`Mensaje ${A+1}`);if(N.recurso.startsWith("mod_")&&!n.includes(N.recurso.slice(4)))throw i(`Mensaje ${A+1}: de un m\xF3dulo que no est\xE1 en la soluci\xF3n.`);return N}),w=$v(e.papeles,n,d),g=Cv(e.portales,n),y=vv(e.vistasTabla,n),C=ho(e.separadores??[],lc,"separadores").map(($,A)=>{if(!me($))throw i(`Separador ${A+1}: un objeto.`);if(fo($,["antes","titulo"],`Separador ${A+1}`),$.antes!==null&&(typeof $.antes!="string"||!n.includes($.antes)))throw i(`Separador ${A+1}: \xABantes\xBB, la clave de uno de sus m\xF3dulos.`);if($.titulo!==void 0&&$.titulo!==null&&(typeof $.titulo!="string"||!$.titulo.trim()||$.titulo.trim().length>40))throw i(`Separador ${A+1}: \xABtitulo\xBB, de 1 a 40 caracteres (o null: solo la l\xEDnea).`);return{antes:$.antes,titulo:typeof $.titulo=="string"?$.titulo.trim():null}}),O=ho(e.menu??[],100,"menu").map(($,A)=>{if(!me($))throw i(`Men\xFA ${A+1}: un objeto.`);if(fo($,["entrada","padre","recientes","despliega"],`Men\xFA ${A+1}`),typeof $.entrada!="string"||!n.includes($.entrada))throw i(`Men\xFA ${A+1}: \xABentrada\xBB, la clave de uno de sus m\xF3dulos.`);if($.padre!==void 0&&$.padre!==null&&(typeof $.padre!="string"||!n.includes($.padre)||$.padre===$.entrada))throw i(`Men\xFA ${A+1}: \xABpadre\xBB, otro de sus m\xF3dulos (o null).`);if($.recientes!==void 0&&(!Number.isSafeInteger($.recientes)||$.recientes<0||$.recientes>10))throw i(`Men\xFA ${A+1}: \xABrecientes\xBB, de 0 a 10.`);if($.despliega!==void 0&&(typeof $.despliega!="string"||!Ps.includes($.despliega)))throw i(`Men\xFA ${A+1}: \xABdespliega\xBB, ${Ps.join(", ")}.`);return{entrada:$.entrada,...$.padre!==void 0?{padre:$.padre}:{},...$.recientes!==void 0?{recientes:$.recientes}:{},...$.despliega!==void 0?{despliega:$.despliega}:{}}});for(let $ of O)if($.padre&&(O.some(A=>A.entrada===$.padre&&A.padre)||O.some(A=>A.padre===$.entrada)))throw i(`Men\xFA: \xAB${$.entrada}\xBB, un solo nivel (ni su padre va dentro de otro ni tiene otros dentro).`);if(new Set(O.map($=>$.entrada)).size!==O.length)throw i("Men\xFA: cada m\xF3dulo, una vez.");let M={};if(e.ejemplos!==void 0){if(!me(e.ejemplos))throw i("\xABejemplos\xBB: un objeto por m\xF3dulo.");for(let[$,A]of Object.entries(e.ejemplos)){if(!n.includes($))throw i(`Ejemplos de un m\xF3dulo que no est\xE1 en la soluci\xF3n (\xAB${$.slice(0,40)}\xBB).`);let N=new Set;M[$]=ho(A,Si,`ejemplos de ${$}`).map((k,x)=>{if(!me(k))throw i(`Ejemplo ${x+1} de ${$}: un objeto.`);if(k._ref!==void 0&&!Number.isSafeInteger(k._ref))throw i(`Ejemplo ${x+1} de ${$}: \xAB_ref\xBB es un entero.`);if(typeof k._ref=="number"){if(N.has(k._ref))throw i(`\xAB${$}\xBB: referencia de ejemplo repetida.`);N.add(k._ref)}if((d.find(z=>z.clave===$)?.campos??[]).filter(z=>z.tipo==="secreto").map(z=>z.clave).some(z=>z in k))throw i(`Ejemplo ${x+1} de ${$}: un ejemplo no lleva el valor de un campo secreto.`);return k})}}let Z=_p(e.perfilesImportacion);if(Z.some($=>$.perfil.entidades.some(A=>A.destino.startsWith("mod_")&&!d.some(N=>`mod_${N.clave}`===A.destino))))throw i("El perfil apunta fuera de la soluci\xF3n.");return{formato:Et,...Z.length?{perfilesImportacion:Z}:{},version:e.version,...t?{plantilla:t}:{},nombre:Zo(e.nombre,"nombre",80),descripcion:Zo(e.descripcion,"descripcion",500,!1),icono:r,modulos:d,paneles:u,automatizaciones:p,ejemplos:M,...f.length?{senales:f}:{},...h?{pix:h}:{},...b.length?{informes:b}:{},...typeof e.principal=="string"?{principal:e.principal}:{},...v.length?{mensajes:v}:{},...w.length?{papeles:w}:{},...g.length?{portales:g}:{},...y.length?{vistasTabla:y}:{},...C.length?{separadores:C}:{},...O.length?{menu:O}:{},...xv(e.sinonimos,d.map($=>$.clave))}}function xv(e,o){if(e===void 0)return{};if(!me(e))throw i("\xABsinonimos\xBB: un objeto (clave del m\xF3dulo \u2192 lista de palabras).");let t={};for(let[r,n]of Object.entries(e)){if(!o.includes(r)&&!qh.includes(r))throw i(`\xABsinonimos\xBB: \xAB${r.slice(0,40)}\xBB no es un m\xF3dulo de la soluci\xF3n ni uno nativo.`);let a=Rh(n);a.length&&(t[r]=a)}return Object.keys(t).length?{sinonimos:t}:{}}function Cv(e,o){return ho(e,uc,"portales").map((t,r)=>{let n=`Portal ${r+1}`;if(!me(t))throw i(`${n}: un objeto.`);fo(t,["clave","nombre","activo","personas","secciones","textos","marca"],n);let a=[...sh(t)].filter(p=>!o.includes(p));if(a.length)throw i(`${n}: usa un m\xF3dulo que no est\xE1 en la soluci\xF3n (\xABmod_${a[0].slice(0,40)}\xBB).`);if(!Array.isArray(t.secciones)||!t.secciones.length)throw i(`${n}: al menos una secci\xF3n.`);let{activo:s,marca:c,...d}=t,u=me(c)&&typeof c.color=="string"?c.color:void 0;return{...d,...u?{marca:{color:u}}:{}}})}function ho(e,o,t){if(e===void 0)return[];if(!Array.isArray(e)||e.length>o)throw i(`\xAB${t}\xBB: una lista de hasta ${o}.`);return e}var Et,cr,ji,ic,ac,sc,Si,Oi,Ph,wv,cc,yv,_v,Nv,me,lc,uc,dc=m(()=>{Np();xp();ch();Yf();Ks();R();$h();jh();ec();Vr();mf();Ah();ah();kh();Et="forgenex.solucion",cr=2,ji=30,ic=10,ac=20,sc=40,Si=50,Oi=1e6,Ph=/^[a-z0-9-]{1,40}$/,wv=new Set(["__proto__","constructor","prototype"]);cc=10,yv=/^mod_([a-z][a-z0-9_]{0,40})\.([a-z][a-z0-9_]{0,40})$/,_v=["administrador","miembro","lectura"],Nv=/^mod_([a-z][a-z0-9_]{0,40})\.(ver|editar|borrar|exportar|importar|crear|reasignar|estado|descargar|revelar)$/;me=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);lc=20,uc=10});import{inflateRawSync as jv}from"node:zlib";function Ov(e){let o=Buffer.from(e.buffer,e.byteOffset,e.byteLength);if(o.length>pc)throw i("El paquete pasa de 5 MB.");if(o.length<22||o.readUInt32LE(0)!==67324752)throw i("El paquete no es un .zip.");let t=-1;for(let d=o.length-22;d>=Math.max(0,o.length-22-65535);d--)if(o.readUInt32LE(d)===101010256&&d+22+o.readUInt16LE(d+20)===o.length){t=d;break}if(t<0)throw i("El .zip est\xE1 da\xF1ado (sin directorio).");let r=o.readUInt16LE(t+10),n=o.readUInt32LE(t+16),a=o.readUInt32LE(t+12);if(o.readUInt16LE(t+4)!==0||o.readUInt16LE(t+6)!==0||o.readUInt16LE(t+8)!==r||t+22+o.readUInt16LE(t+20)!==o.length||n+a!==t)throw i("El .zip est\xE1 da\xF1ado (directorio inv\xE1lido).");if(r>Mh)throw i(`El paquete trae m\xE1s de ${Mh} ficheros.`);let s=new Map,c=n;for(let d=0;d<r;d++){if(c+46>t||o.readUInt32LE(c)!==33639248)throw i("El .zip est\xE1 da\xF1ado.");let u=o.readUInt16LE(c+8),p=o.readUInt16LE(c+10),f=o.readUInt32LE(c+20),h=o.readUInt32LE(c+24),b=o.readUInt16LE(c+28),v=o.readUInt16LE(c+30),w=o.readUInt16LE(c+32),g=o.readUInt32LE(c+42);if(c+46+b+v+w>t)throw i("El .zip est\xE1 da\xF1ado.");let y=o.subarray(c+46,c+46+b),C=y.toString("utf8");if(c+=46+b+v+w,!C.endsWith("/")){if(!C||C.includes("\\")||C.startsWith("/")||C.split("/").some(O=>O===".."||O==="."||O==="")||/[\x00-\x1f]/.test(C))throw i(`El paquete trae un nombre de fichero no admitido (\xAB${C.slice(0,80)}\xBB).`);if(s.has(C))throw i(`El paquete trae \xAB${C.slice(0,80)}\xBB dos veces.`);if(u&1)throw i("El paquete no puede ir cifrado.");s.set(C,()=>{if(h>Th)throw i(`\xAB${C}\xBB pasa de 2 MB.`);if(g+30>o.length||o.readUInt32LE(g)!==67324752)throw i("El .zip est\xE1 da\xF1ado.");let O=o.readUInt16LE(g+26),M=g+30+O+o.readUInt16LE(g+28);if(M>n||M+f>n||o.readUInt16LE(g+6)!==u||o.readUInt16LE(g+8)!==p||!o.subarray(g+30,g+30+O).equals(y))throw i("El .zip est\xE1 da\xF1ado.");let Z=o.subarray(M,M+f);if(Z.length!==f)throw i("El .zip est\xE1 da\xF1ado.");let $;if(p===0)$=Z;else if(p===8)try{$=jv(Z,{maxOutputLength:Th})}catch{throw i(`\xAB${C}\xBB no se puede descomprimir (o pasa de 2 MB).`)}else throw i(`\xAB${C}\xBB va comprimido de una forma no admitida (solo \xABstore\xBB y \xABdeflate\xBB).`);if($.length!==h)throw i("El .zip est\xE1 da\xF1ado.");return $})}}if(c!==t)throw i("El .zip est\xE1 da\xF1ado (directorio inv\xE1lido).");return s}function Gr(e){let o=new Map,t=0;for(let[r,n]of Ov(e)){let a=n();if(t+=a.length,t>Sv)throw i("Los ficheros del paquete pasan de 10 MB al descomprimirlos.");o.set(r,a)}return o}var pc,Th,Mh,Sv,Ei=m(()=>{R();pc=5*1024*1024,Th=2*1024*1024,Mh=500;Sv=10*1024*1024});import{createHash as Ih,createPublicKey as Av,sign as Ev,verify as XD}from"node:crypto";function qv(e){let o=Av(e);if(o.asymmetricKeyType!=="ed25519")throw i("La clave p\xFAblica tiene que ser ed25519.");let t=o.export({type:"spki",format:"der"});return{pem:o.export({type:"spki",format:"pem"}).toString(),id:Ih("sha256").update(t).digest("hex")}}function Rv(e){return Buffer.from(JSON.stringify(["forgenex.fgx.v1",[...e].filter(([o])=>o!==Hr).sort(([o],[t])=>o<t?-1:o>t?1:0).map(([o,t])=>[o,Ih("sha256").update(t).digest("hex")])]))}function Lh(e,o,t){let{id:r}=qv(t);return Buffer.from(JSON.stringify({formato:"forgenex.firma",version:1,clave:r,firma:Ev(null,Rv(e),o).toString("base64")}))}var Hr,mc=m(()=>{R();Hr="firma.json"});function fc(e){let o=Array.from({length:256},(c,d)=>{let u=d;for(let p=0;p<8;p++)u=u&1?3988292384^u>>>1:u>>>1;return u>>>0}),t=[],r=[],n=0;for(let[c,d]of e){let u=Buffer.from(c),p=4294967295;for(let b of d)p=o[(p^b)&255]^p>>>8;p=(p^4294967295)>>>0;let f=Buffer.alloc(30),h=Buffer.alloc(46);f.writeUInt32LE(67324752),f.writeUInt16LE(20,4),f.writeUInt16LE(2048,6),f.writeUInt32LE(p,14),f.writeUInt32LE(d.length,18),f.writeUInt32LE(d.length,22),f.writeUInt16LE(u.length,26),h.writeUInt32LE(33639248),h.writeUInt16LE(20,4),h.writeUInt16LE(20,6),h.writeUInt16LE(2048,8),h.writeUInt32LE(p,16),h.writeUInt32LE(d.length,20),h.writeUInt32LE(d.length,24),h.writeUInt16LE(u.length,28),h.writeUInt32LE(n,42),t.push(f,u,d),r.push(h,u),n+=f.length+u.length+d.length}let a=Buffer.concat(r),s=Buffer.alloc(22);return s.writeUInt32LE(101010256),s.writeUInt16LE(e.size,8),s.writeUInt16LE(e.size,10),s.writeUInt32LE(a.length,12),s.writeUInt32LE(n,16),Buffer.concat([...t,a,s])}var Dh=m(()=>{});import{copyFileSync as Xr,mkdirSync as hc,readFileSync as Yr,readdirSync as Kr,realpathSync as zh,writeFileSync as Wh}from"node:fs";import{dirname as kv,join as Q,resolve as Pv,sep as Tv}from"node:path";import{fileURLToPath as Mv}from"node:url";import{createRequire as Fh}from"node:module";function Bh(e,o="html",t=process.cwd()){if(!/^[a-z][a-z0-9-]{1,59}$/.test(e))throw new Error("El nombre debe tener de 2 a 60 letras min\xFAsculas, n\xFAmeros o guiones y empezar por letra.");if(!["html","react","archivos"].includes(o))throw new Error("Plantilla: html, react o archivos.");let r=Q(t,e);hc(r);for(let c of["interfaz","funciones"])hc(Q(r,c));let n=(c,d)=>Wh(Q(r,c),typeof d=="string"?d:JSON.stringify(d,null,2)+`
|
|
22
|
+
`),a=`ext_${e.replace(/[^a-z]/g,"_").slice(0,27)}`;if(o==="archivos"){let c=JSON.parse(Yr(Q(ko,"ejemplos/archivos-ficha/extension.json"),"utf8"));n("extension.json",{...c,id:`com.ejemplo.${e}`,nombre:e,autor:{nombre:"Mi empresa"}}),Xr(Q(ko,"ejemplos/archivos-ficha/interfaz/index.html"),Q(r,"interfaz/index.html"));for(let d of["GUIA-IA.md","extension.schema.json","solucion.schema.json","puente-extension.d.ts","puente-extension.mjs"])Xr(Q(ko,d),Q(r,d));return n("AGENTS.md",`Lee GUIA-IA.md (secci\xF3n \xABArchivos\xBB). La app solo recibe lo que la persona elige con crm.archivos.elegir(): nunca pidas tokens del almacenamiento. Pide permisos m\xEDnimos. Valida antes de empaquetar.
|
|
23
|
+
`),n(".gitignore",`node_modules/
|
|
24
|
+
*.fgx
|
|
25
|
+
*.pem
|
|
26
|
+
.keys/
|
|
27
|
+
`),go(r),r}n("extension.json",{formato:"forgenex.extension",formato_version:1,id:`com.ejemplo.${e}`,nombre:e,version:"1.0.0",autor:{nombre:"Mi empresa"},solucion:"solucion.json",permisos:{modulos:{[a]:["ver","crear","editar"],contactos:["ver"],empresas:["ver"]},almacen:!0},montajes:[{id:"pagina",punto:"pagina",entrada:"interfaz/index.html",titulo:e}],funciones:[{nombre:"resumir",entrada:"funciones/resumir.js",disparador:{tipo:"webhook"}}]}),n("solucion.json",{formato:"forgenex.solucion",version:2,nombre:e,plantilla:{id:a,version:1,sector:"general"},modulos:[{clave:a,nombre:"Encargo",nombre_plural:"Encargos",icono:"clipboard-list",campos:[{clave:"titulo",etiqueta:"T\xEDtulo",tipo:"texto",obligatorio:!0,enTabla:!0},{clave:"persona",etiqueta:"Persona",tipo:"relacion",relacion:"contacts",enTabla:!0},{clave:"empresa",etiqueta:"Empresa",tipo:"relacion",relacion:"companies",enTabla:!0}]}]}),n("funciones/resumir.js",`export default async function (entrada) {
|
|
23
28
|
const resumen = { mensaje: String(entrada.cuerpo?.mensaje ?? "Hola"), total: 1 };
|
|
24
29
|
await crm.almacen.guardar("ultimo_resumen", resumen);
|
|
25
30
|
return resumen;
|
|
26
31
|
}
|
|
27
|
-
`);for(let
|
|
28
|
-
`);let s=o==="html"?"hola-alpine":"hola-react";for(let
|
|
32
|
+
`);for(let c of["GUIA-IA.md","extension.schema.json","solucion.schema.json","puente-extension.d.ts","puente-extension.mjs"])Xr(Q(ko,c),Q(r,c));n("AGENTS.md",`Lee GUIA-IA.md. Usa el puente del CRM y los m\xF3dulos enlazados a Personas y Empresas. Pide permisos m\xEDnimos. Valida antes de empaquetar. Nunca incluyas claves ni datos reales.
|
|
33
|
+
`);let s=o==="html"?"hola-alpine":"hola-react";for(let c of Kr(Q(ko,"ejemplos",s,"interfaz")))Xr(Q(ko,"ejemplos",s,"interfaz",c),Q(r,"interfaz",c));return o==="react"&&(hc(Q(r,"src")),Xr(Q(ko,"ejemplos/hola-react/src/main.jsx"),Q(r,"src/main.jsx")),n("package.json",{private:!0,type:"module",scripts:{build:"vite build"},dependencies:{react:"19.1.0","react-dom":"19.1.0"},devDependencies:{vite:"7.3.2"}}),n("vite.config.js",`import { defineConfig } from "vite";
|
|
29
34
|
export default defineConfig({ build: { outDir: "interfaz", emptyOutDir: false, rollupOptions: { input: "src/main.jsx", external: ["@forgenex/crm-sdk"], output: { entryFileNames: "app.js", inlineDynamicImports: true } } } });
|
|
30
|
-
`)),
|
|
35
|
+
`)),n(".gitignore",`node_modules/
|
|
31
36
|
*.fgx
|
|
32
37
|
*.pem
|
|
33
38
|
.keys/
|
|
34
|
-
`),Ao(n),n}function Ao(e){let o=Xr(_i(ee(e,"extension.json"),"utf8"));o.solucion&&yi(_i(ee(e,o.solucion),"utf8"),{topeCampos:200});for(let t of[...o.montajes,...o.funciones])_i(ee(e,t.entrada));return o}async function Ni(e){if(!Wr(e).includes("src")||!Wr(ee(e,"src")).includes("main.jsx"))return;let o=Eh(ee(e,"package.json")),t;try{t=o("esbuild")}catch{try{t=Eh(ee(rr,"../src/package.json"))("esbuild")}catch{throw new Error("La plantilla react necesita sus dependencias: ejecuta antes \xABnpm install\xBB en la carpeta de la app.")}}await t.build({entryPoints:[ee(e,"src/main.jsx")],outfile:ee(e,"interfaz/app.js"),bundle:!0,format:"esm",minify:!0,jsx:"automatic",target:"es2020",external:["@forgenex/crm-sdk"],nodePaths:[ee(rr,"../src/node_modules")],define:{"process.env.NODE_ENV":'"production"'},legalComments:"none"})}function _v(e){let o=Ao(e),t=new Map,n=Ah(e),r=s=>{let l=ee(e,s);if(!Ah(l).startsWith(n+vv))throw new Error("El paquete no admite enlaces fuera del proyecto.");t.set(s,_i(l))},a=s=>{for(let l of Wr(ee(e,s),{withFileTypes:!0})){if(l.isSymbolicLink())throw new Error("El paquete no admite enlaces simb\xF3licos.");l.isDirectory()?a(`${s}/${l.name}`):r(`${s}/${l.name}`)}};r("extension.json"),o.solucion&&r(o.solucion);for(let s of["interfaz","funciones"])Wr(e).includes(s)&&a(s);return nc(ac(t)),t}async function Rh(e,o,t){await Ni(e);let n=_v(e);if(o&&t)n.set(ic,Oh(n,o,t));else throw new Error("Falta la clave de firma: ejecuta forgenex claves crear y registrar-clave.");let r=ac(n);nc(r);let a=Ao(e),s=`${a.id.split(".").at(-1)}-${a.version}.fgx`;return qh(ee(e,s),r),ee(e,s)}var rr,$i=m(()=>{Yr();rc();xh();Sh();jh();rr=wv(bv(yv(import.meta.url)),"..")});import{Worker as Nv}from"node:worker_threads";var $v,lc,xi,Ph=m(()=>{ar();$v=new URL(import.meta.url.endsWith(".ts")?"./caja.ts":"./caja.js",import.meta.url),lc=class{w=null;ocupada=!1;worker(){return this.w?this.w:(this.w=new Nv($v,{resourceLimits:{maxOldGenerationSizeMb:96,maxYoungGenerationSizeMb:16,stackSizeMb:4},env:{},stdout:!0,stderr:!0}),this.w.stdout.resume(),this.w.stderr.resume(),this.w.unref(),this.w)}matar(){let o=this.w;this.w=null,o&&o.terminate().catch(()=>{})}correr(o){this.ocupada=!0;let t=Date.now(),n=this.worker();return new Promise(r=>{let a=!1,s=0,l=(b,y)=>{a||(a=!0,clearTimeout(f),n.off("message",d),n.off("error",u),n.off("exit",p),y&&this.matar(),this.ocupada=!1,r(b))},d=b=>{if(b.tipo==="llamar"){if(a)return;if(typeof b.datos!="string"||b.datos.length>L.llamadaCaracteres||s>=L.llamadasEnVuelo){n.postMessage({tipo:"respuesta",n:b.n,ok:!1,valor:typeof b.datos=="string"&&b.datos.length<=L.llamadaCaracteres?"demasiadas llamadas a la vez":"lo que se manda al CRM es demasiado grande"});return}let w=null;try{w=JSON.parse(b.datos)}catch{}s++,o.manejar(b.que,w).finally(()=>{s--}).then(g=>!a&&n.postMessage({tipo:"respuesta",n:b.n,ok:!0,valor:JSON.stringify(g??null)}),g=>!a&&n.postMessage({tipo:"respuesta",n:b.n,ok:!1,valor:g instanceof Error?g.message:String(g)}));return}let y=Date.now()-t;b.ok?l({ok:!0,salida:b.salida,ms:y},!1):l({ok:!1,corte:b.corte,clase:b.clase,mensaje:b.mensaje,ms:y},b.corte!==null)},u=b=>l({ok:!1,corte:/memory|heap/i.test(b.message)?"memoria":null,clase:"Error",mensaje:"la caja se ha cerrado",ms:Date.now()-t},!0),p=()=>l({ok:!1,corte:null,clase:"Error",mensaje:"la caja se ha cerrado",ms:Date.now()-t},!0),f=setTimeout(()=>l({ok:!1,corte:"tiempo",clase:"InternalError",mensaje:"interrupted",ms:Date.now()-t},!0),o.ms+L.margenMs);n.on("message",d),n.on("error",u),n.on("exit",p);let h={tipo:"correr",codigo:o.codigo,fichero:o.fichero,entrada:o.entrada,contexto:o.contexto,ms:o.ms,memoriaMb:o.memoriaMb,pilaBytes:L.pilaBytes,salidaBytes:L.salidaBytes,llamadaCaracteres:L.llamadaCaracteres,enVuelo:L.llamadasEnVuelo};n.postMessage(h)})}cerrar(){this.matar()}},xi=class{ranuras;cola=[];constructor(o=L.simultaneas){this.ranuras=Array.from({length:Math.max(1,o)},()=>new lc)}get libres(){return this.ranuras.filter(o=>!o.ocupada).length}async correr(o){let t=this.ranuras.find(n=>!n.ocupada);for(;!t;)await new Promise(n=>this.cola.push(n)),t=this.ranuras.find(n=>!n.ocupada);t.ocupada=!0;try{return await t.correr(o)}finally{this.cola.shift()?.()}}intentar(o){return this.ranuras.some(t=>!t.ocupada)?this.correr(o):null}cerrarSiLibre(){!this.cola.length&&this.ranuras.every(o=>!o.ocupada)&&this.cerrar()}cerrar(){for(let o of this.ranuras)o.cerrar()}}});import{lookup as xv}from"node:dns/promises";import{request as Cv}from"node:https";import{isIP as Ov}from"node:net";async function dc(e,o,t={}){let n;try{n=new URL(e.url)}catch{throw new me("direcci\xF3n no v\xE1lida")}if(n.protocol!=="https:")throw new me("solo https");if(n.username||n.password)throw new me("sin usuario ni clave en la direcci\xF3n");if(n.port&&n.port!=="443")throw new me("solo al puerto 443");let r=n.hostname.toLowerCase().replace(/\.$/,"");if(Ov(r.replace(/^\[|\]$/g,""))||!uc(o,r))throw new me("el dominio no est\xE1 entre los dominios aceptados");let a=String(e.metodo||"GET").toUpperCase();if(!Th.has(a))throw new me("m\xE9todo no admitido");let s={};if(e.cabeceras&&typeof e.cabeceras=="object")for(let[f,h]of Object.entries(e.cabeceras).slice(0,30)){let b=f.toLowerCase();if(!jv.test(f)||Sv.has(b)||b.startsWith("x-crm-")||b.startsWith("x-forgenex"))continue;let y=String(h);/[\r\n\0]/.test(y)||y.length>4096||(s[b]=y)}s["user-agent"]="ForgeNEX-CRM-Extension/1";let l=e.cuerpo===null||e.cuerpo===void 0?null:String(e.cuerpo);if(l!==null&&Buffer.byteLength(l)>L.red.cuerpoBytes)throw new me(`el cuerpo pasa de ${L.red.cuerpoBytes/1024} KB`);if(l!==null&&(a==="GET"||a==="HEAD"))throw new me("GET y HEAD no llevan cuerpo");let d=await(t.resolver??(f=>xv(f,{all:!0,verbatim:!0})))(r).catch(()=>[]);if(!d.length)throw new me(`${r.slice(0,80)} no resuelve`);if(d.some(f=>oh(f.address)))throw new me(`${r.slice(0,80)} apunta a una red interna`);let u={url:n,ip:d[0].address,familia:d[0].family===6?6:4},p=await(t.transporte??Ev)(u,{metodo:a,cabeceras:s,cuerpo:l});return{host:r,respuesta:p}}function Ev(e,o){return new Promise((t,n)=>{let r={...o.cabeceras,...o.cuerpo!==null?{"content-length":String(Buffer.byteLength(o.cuerpo))}:{}},a=Cv({protocol:"https:",hostname:e.url.hostname,servername:e.url.hostname,port:443,path:`${e.url.pathname}${e.url.search}`,method:o.metodo,headers:r,lookup:((l,d,u)=>d?.all?u(null,[{address:e.ip,family:e.familia}]):u(null,e.ip,e.familia)),timeout:L.red.plazoMs,agent:!1},l=>{let d=[],u=0;l.on("data",p=>{if(u+=p.length,u>L.red.respuestaBytes){l.destroy(),n(new me(`la respuesta pasa de ${L.red.respuestaBytes/1024/1024} MB`));return}d.push(p)}),l.on("end",()=>{clearTimeout(s);let p={};for(let f of Av){let h=l.headers[f];typeof h=="string"&&(p[f]=h.slice(0,2e3))}t({status:l.statusCode??0,headers:p,cuerpo:Buffer.concat(d).toString("utf8")})}),l.on("error",()=>n(new me("la respuesta se cort\xF3")))}),s=setTimeout(()=>a.destroy(new me("sin respuesta a tiempo")),L.red.plazoMs);a.on("timeout",()=>a.destroy(new me("sin respuesta a tiempo"))),a.on("error",l=>{clearTimeout(s),n(l instanceof me?l:new me("no se ha podido conectar"))}),a.end(o.cuerpo??void 0)})}var me,Th,Sv,jv,Av,uc,pc=m(()=>{th();ar();me=class extends Error{constructor(t){super(`fetch: ${t}`);this.motivo=t}motivo},Th=new Set(["GET","POST","PUT","PATCH","DELETE","HEAD"]),Sv=new Set(["host","connection","content-length","transfer-encoding","upgrade","te","trailer","keep-alive","proxy-authorization","proxy-connection","expect","cookie","x-forwarded-for","x-real-ip","forwarded"]),jv=/^[A-Za-z0-9!#$%&'*+.^_`|~-]{1,64}$/,Av=["content-type","location","retry-after","etag","last-modified"],uc=(e,o)=>e.some(t=>t===o||t.startsWith("*.")&&o.endsWith(t.slice(1))&&o.length>t.length-1)});function Ih(e,o){if(typeof o!="string"||typeof e!="string")return null;let n=(Object.hasOwn(Mh,o)?Mh[o]:null)??St(o);if(!n)return null;let r=n.startsWith("mod_");switch(e){case"ver":return r?`${n}.ver`:qv[n]??`${n}.ver`;case"buscar":return r?`${n}.listar`:kv[n]??`${n}.buscar`;case"crear":return`${n}.crear`;case"actualizar":return`${n}.actualizar`;default:return null}}function Dh(e,o){return e.filter(t=>uc(o,t.startsWith("*.")?`x${t.slice(1)}`:t)&&(!t.startsWith("*.")||o.includes(t)))}var Mh,qv,kv,Lh=m(()=>{Yr();pc();Mh={contactos:"contactos",contacts:"contactos",empresas:"empresas",companies:"empresas",oportunidades:"oportunidades",deals:"oportunidades",tareas:"tareas",tasks:"tareas",notas:"notas"},qv={tareas:"tareas.obtener"},kv={tareas:"tareas.listar",notas:"notas.listar"}});var Wh={};eg(Wh,{iniciarDev:()=>Dv});import{createServer as Rv}from"node:http";import{randomBytes as zh}from"node:crypto";import{readFileSync as Pv,realpathSync as Fh,watch as Tv}from"node:fs";import{join as Mv,sep as Iv}from"node:path";async function Dv(e){let o=ir(e),t=Number(Ze(e,"puerto")??5173),n=Fh(process.cwd());if(!Number.isInteger(t)||t<1||t>65535)throw new Error("Puerto no v\xE1lido.");let r=Ao(n),a=(N,C)=>nr(o.api,o.clave,"/api/desarrollador/desarrollo",{espacio:o.espacio,ext_id:r.id,pase:N,funcion:C}),s=await a();await Ni(n);let l=new xi(1),d=zh(24).toString("hex"),u=1,p=null,f,h=Tv(n,{recursive:!0},(N,C)=>{let S=String(C??"");/node_modules|\.fgx$|\.pem|^\.git[\/\\]/.test(S)||S==="interfaz/app.js"||(clearTimeout(f),f=setTimeout(()=>{p=Ni(n).then(()=>{Ao(n),u++,console.log("App actualizada.")}).catch(T=>console.error("Error de desarrollo:",T.message)).finally(()=>{p=null})},100))}),b=Rv(async(N,C)=>{let S=(T,Y)=>{C.writeHead(T,{"content-type":"application/json","cache-control":"no-store"}),C.end(JSON.stringify(Y))};try{if(![`127.0.0.1:${t}`,`localhost:${t}`].includes(N.headers.host??""))return S(403,{error:"host_no_permitido"});let T=N.headers.origin;if(T&&T!==o.api)return S(403,{error:"origen_no_permitido"});if(T===o.api&&(C.setHeader("access-control-allow-origin",o.api),C.setHeader("vary","origin")),C.setHeader("access-control-allow-methods","GET, POST, OPTIONS"),C.setHeader("access-control-allow-headers","content-type, authorization"),N.method==="OPTIONS"){C.writeHead(204),C.end();return}let Y=new URL(N.url??"/",`http://127.0.0.1:${t}`),$=decodeURIComponent(Y.pathname);if(!$.startsWith(`/${d}/`))return S(404,{error:"no_encontrado"});let v=$.slice(d.length+2);if(v==="__forgenex/version"&&N.method==="GET")return S(200,{version:u});if(v.startsWith("__forgenex/funcion/")&&N.method==="POST"){if(T!==o.api)return S(403,{error:"origen_no_permitido"});let M=(N.headers.authorization??"").replace(/^Bearer /,"");if(!M.startsWith("crmui_"))return S(401,{error:"falta_pase"});if(!l.libres)return S(429,{error:"funcion_ocupada"});let B=v.slice(19),I=await a(M,B),J=Ao(n).funciones.find(De=>De.nombre===B),ge=I.manifiesto.funciones.find(De=>De.nombre===B);if(!J||!ge)return S(403,{error:"funcion_no_instalada"});let Be=await fetch(`${o.api}/api/v1/capabilities`,{redirect:"error",headers:{authorization:`Bearer ${M}`,"x-espacio":String(o.espacio)}});if(!Be.ok)return S(Be.status,{error:"pase_revocado"});let Go=await Lv(N),Ho=zh(12).toString("hex"),G=0,fo=0,$e=await l.correr({codigo:y(J.entrada).toString("utf8"),fichero:J.entrada,entrada:Go,contexto:{extension:r.id,version:r.version,funcion:B,disparo:"desarrollo",ejecucion:Ho},...jc(J),manejar:async(De,k)=>{if(De==="red"){if(++fo>L.llamadasRed)throw new Error("Demasiadas peticiones de red.");return(await dc(k,Dh(ge.red,I.aceptados.red_hacia))).respuesta}if(++G>L.llamadasApi)throw new Error("Demasiadas llamadas al CRM.");let D=k,K=D.op??Ih(D.accion,D.modulo);if(!K||!/^[a-z][a-z0-9_]*\.[a-z][a-z0-9_]*$/.test(K))throw new Error("Operaci\xF3n no v\xE1lida.");let Ct=await fetch(`${o.api}/api/v1/capabilities`,{redirect:"error",headers:{authorization:`Bearer ${M}`,"x-espacio":String(o.espacio)}});if(!Ct.ok)throw new Error("Pase caducado o revocado.");let bc=await Ct.json(),wc=(bc.data?.operaciones??bc.operaciones??[]).find(Si=>Si.id===K);if(!wc)throw new Error("Operaci\xF3n no aceptada por el administrador.");let Oi=wc.metodo,vc=D.args??{},Yh=Oi==="GET"?`?${new URLSearchParams(Object.entries(vc).map(([Si,Kh])=>[Si,String(Kh)]))}`:"",yc=await fetch(`${o.api}/api/v1/op/${K}${Yh}`,{method:Oi,redirect:"error",headers:{authorization:`Bearer ${M}`,"x-espacio":String(o.espacio),"content-type":"application/json","idempotency-key":`dev-${Ho}-${G}`},...Oi==="POST"?{body:JSON.stringify(vc)}:{}}),_c=await yc.json();if(!yc.ok)throw new Error(_c.error?.mensaje??"El CRM rechaz\xF3 la operaci\xF3n.");return _c.data}});return $e.ok||console.error(`Funci\xF3n ${B}: ${$e.clase}: ${$e.mensaje}`),S($e.ok?200:422,$e)}if(N.method!=="GET")return S(405,{error:"metodo_no_permitido"});if(await p,!v.startsWith("interfaz/"))return S(404,{error:"no_encontrado"});let A=y(v),x=v.endsWith(".html")?"text/html":v.endsWith(".js")?"text/javascript":v.endsWith(".css")?"text/css":"application/octet-stream";C.writeHead(200,{"content-type":x,"cache-control":"no-store"}),C.end(A)}catch(T){console.error("Error de desarrollo:",T.message),S(400,{error:"desarrollo_error",mensaje:T.message})}});function y(N){if(N.includes("\\")||N.split("/").some(T=>T===".."||T==="."||!T))throw new Error("Ruta no admitida.");let C=Fh(Mv(n,N));if(!C.startsWith(n+Iv))throw new Error("Ruta fuera del proyecto.");let S=Pv(C);if(S.length>2*1024*1024)throw new Error("Recurso demasiado grande.");return S}let w=()=>{clearTimeout(f),h.close(),l.cerrar(),b.closeAllConnections(),b.close()};b.on("error",N=>{console.error(N.message),w(),process.exitCode=1}),process.once("SIGINT",w),process.once("SIGTERM",w),await new Promise((N,C)=>{b.once("error",C),b.listen(t,"127.0.0.1",N)});let g=`http://127.0.0.1:${t}/${d}`;console.log(`Desarrollo: ${g}
|
|
39
|
+
`),go(r),r}function go(e){let o=tt(Yr(Q(e,"extension.json"),"utf8"));o.solucion&&Ai(Yr(Q(e,o.solucion),"utf8"),{topeCampos:200});for(let t of[...o.montajes,...o.funciones])Yr(Q(e,t.entrada));return o}async function lr(e){if(!Kr(e).includes("src")||!Kr(Q(e,"src")).includes("main.jsx"))return;let o=Fh(Q(e,"package.json")),t;try{t=o("esbuild")}catch{try{t=Fh(Q(ko,"../src/package.json"))("esbuild")}catch{throw new Error("La plantilla react necesita sus dependencias: ejecuta antes \xABnpm install\xBB en la carpeta de la app.")}}await t.build({entryPoints:[Q(e,"src/main.jsx")],outfile:Q(e,"interfaz/app.js"),bundle:!0,format:"esm",minify:!0,jsx:"automatic",target:"es2020",external:["@forgenex/crm-sdk"],nodePaths:[Q(ko,"../src/node_modules")],define:{"process.env.NODE_ENV":'"production"'},legalComments:"none"})}function gc(e){let o=go(e),t=new Map,r=zh(e),n=s=>{let c=Q(e,s);if(!zh(c).startsWith(r+Tv))throw new Error("El paquete no admite enlaces fuera del proyecto.");t.set(s,Yr(c))},a=s=>{for(let c of Kr(Q(e,s),{withFileTypes:!0})){if(c.isSymbolicLink())throw new Error("El paquete no admite enlaces simb\xF3licos.");c.isDirectory()?a(`${s}/${c.name}`):n(`${s}/${c.name}`)}};n("extension.json"),o.solucion&&n(o.solucion);for(let s of["interfaz","funciones"])Kr(e).includes(s)&&a(s);return Gr(fc(t)),t}async function Uh(e,o,t){await lr(e);let r=gc(e);if(o&&t)r.set(Hr,Lh(r,o,t));else throw new Error("Falta la clave de firma: ejecuta forgenex claves crear y registrar-clave.");let n=fc(r);Gr(n);let a=go(e),s=`${a.id.split(".").at(-1)}-${a.version}.fgx`;return Wh(Q(e,s),n),Q(e,s)}var ko,qi=m(()=>{kt();dc();Ei();mc();Dh();ko=Pv(kv(Mv(import.meta.url)),"..")});function zv(e,o){let t=[],r=[],n=s=>{if(Lv.has(s)||Dv.has(s))return;let[c,d]=s.split(".");if(c==="almacen")return t.push({prefijo:"almacen",op:"almacen",donde:o});if(c==="archivos")return d==="leer"||d==="elegir"?t.push({prefijo:"archivos",op:"leer",donde:o}):d==="vincular_elegido"?t.push({prefijo:"archivos",op:"escribir",donde:o}):r.push(s);let u=Object.hasOwn(Io,c)?c:c.startsWith("mod_")?wo(c):null,p=Object.hasOwn(wc,d)?wc[d]:null;if(!u||!p)return r.push(s);t.push({prefijo:u,op:u==="notas"&&p!=="ver"?"editar":p,donde:o})};for(let s of e.matchAll(/\.(?:pedir|llamar)\(\s*["'`]([a-z][a-z0-9_]*\.[a-z_]+)["'`]/g))n(s[1]);for(let s of e.matchAll(/\bcrm\.(ver|buscar|crear|actualizar)\(\s*["'`]([a-z][a-z0-9_]*)["'`]/g)){let c=wo(s[2]);c&&t.push({prefijo:c,op:wc[s[1]],donde:o})}/\bcrm\.almacen\.(leer|listar|guardar|borrar)\(/.test(e)&&t.push({prefijo:"almacen",op:"almacen",donde:o}),/\.archivos\.(elegir|leer)\(/.test(e)&&t.push({prefijo:"archivos",op:"leer",donde:o}),/\.archivos\.vincular\(/.test(e)&&t.push({prefijo:"archivos",op:"escribir",donde:o});let a=/\.(?:pedir|llamar)\(\s*[A-Za-z_$]/.test(e)||/\bcrm\.(ver|buscar|crear|actualizar)\(\s*[A-Za-z_$]/.test(e);return{usos:t,desconocidas:r,dinamicas:a}}function Fv(e,o){let t=[],r=[],n=new Set,a=!1;for(let[s,c]of o){let d=zv(c,s);a||=d.dinamicas;for(let u of d.desconocidas)r.push(`${s} llama a \xAB${u}\xBB, que una app no puede usar: el CRM le contestar\xE1 que no tiene permiso.`);for(let u of d.usos)n.add(`${u.prefijo}:${u.op}`),u.prefijo==="almacen"?e.permisos.almacen||t.push(`${u.donde} guarda datos de la app y no pide \xABalmacen\xBB.`):u.prefijo==="archivos"?(e.permisos.archivos??[]).includes(u.op)||t.push(`${u.donde} usa archivos (\xAB${u.op}\xBB) y no lo pide en \xABpermisos.archivos\xBB.`):(e.permisos.modulos[u.prefijo]??[]).includes(u.op)||t.push(`${u.donde} necesita ${Jh[u.op]} ${Qh(u.prefijo)} y no lo pide en \xABpermisos.modulos\xBB.`)}if(a)r.push("El c\xF3digo construye algunas llamadas al CRM en tiempo de ejecuci\xF3n: no se puede comprobar que solo use lo que pide.");else{for(let[s,c]of Object.entries(e.permisos.modulos))for(let d of c)d==="ver"&&c.some(u=>n.has(`${s}:${u}`))||n.has(`${s}:${d}`)||r.push(`Pide ${Jh[d]} ${Qh(s)} y el c\xF3digo no parece usarlo: pide solo lo que usa.`);e.permisos.almacen&&!n.has("almacen:almacen")&&r.push("Pide guardar datos (\xABalmacen\xBB) y el c\xF3digo no parece usarlo.")}return bo("permisos","Permisos coherentes con lo que el c\xF3digo usa",t,r,"Usa solo lo que pide.")}function Vv(e,o){let t=[],r=[],n=e.permisos.red_hacia,a=new Map(e.funciones.map(c=>[c.entrada,c])),s=n.length>0;for(let[c,d]of o){for(let u of d.matchAll(/(?:\b(?:https?|wss?):)?\/\/([a-z0-9](?:[a-z0-9-]{0,62}\.)+[a-z]{2,63})(?=[:/"'`)\s?#]|$)/gi)){let p=u[1].toLowerCase();if(Bv.has(p))continue;let f=u[0].includes(":"),h=d.slice(Math.max(0,u.index-40),u.index),b=Wv.test(h);if(!(!f&&!/(?:src|href)\s*=\s*["']?$/i.test(h)))if(b){s=!0;let v=a.get(c);vc(n,p)?v&&!vc(v.red,p)&&t.push(`La funci\xF3n \xAB${v.nombre}\xBB llama a ${p} y no lo tiene en su \xABred\xBB.`):t.push(`${c} llama a ${p} y no est\xE1 en \xABpermisos.red_hacia\xBB.`)}else!vc(n,p)&&!Uv.test(c)&&r.push(`${c} nombra ${p} (no se ve que llame): si la app se conecta ah\xED, decl\xE1ralo.`)}/\b(?:fetch|new\s+WebSocket|new\s+EventSource|sendBeacon)\s*\(\s*[A-Za-z_$]/.test(d)&&(s=!0,r.push(`${c} se conecta a una direcci\xF3n que construye en tiempo de ejecuci\xF3n: solo podr\xE1 ir a lo declarado en \xABpermisos.red_hacia\xBB.`))}return{red:bo("red","Red declarada",t,r,n.length?`Solo se conecta a lo declarado (${n.join(", ")}).`:"No se conecta fuera del CRM."),usaRed:s}}function Zr(e){let o=e.trim().toLowerCase(),t=/^#([0-9a-f]{3,8})$/.exec(o);if(t){let n=t[1];return n.length===3||n.length===4?[0,1,2].map(a=>parseInt(n[a]+n[a],16)):n.length===6||n.length===8?[0,2,4].map(a=>parseInt(n.slice(a,a+2),16)):null}let r=/^rgba?\(\s*(\d{1,3})[\s,]+(\d{1,3})[\s,]+(\d{1,3})/.exec(o);return r?[Number(r[1]),Number(r[2]),Number(r[3])]:Object.hasOwn(Gh,o)?Gh[o]:null}function Gv(e){let o=e.replace(/!important/i,"").trim();if(Jv.test(o))return{tema:!1,color:null,neutro:!0};let t=/^var\(\s*--[\w-]+\s*(?:,\s*(.+))?\)$/i.exec(o);if(t)return{tema:!0,color:t[1]?Zr(t[1]):null,neutro:!1};let r=o.split(/\s+/).find(n=>Zr(n)!==null);return{tema:/var\(--/.test(o),color:Zr(r||o),neutro:!r&&!Zr(o)&&!/var\(--/.test(o)}}function Hv(e){let o="";for(let t=0;;){let r=e.indexOf("/*",t);if(r<0)return o+e.slice(t);o+=e.slice(t,r);let n=e.indexOf("*/",r+2);if(n<0)return o;t=n+2}}function Xv(e){let o=[],t=0,r=-1,n=0;for(let a=0;a<e.length;a++){let s=e.charCodeAt(a);s===123?(r=a,n=t,t=a+1):s===125&&(r>=0&&r>n&&o.push([e.slice(n,r),e.slice(r+1,a)]),r=-1,t=a+1)}return o}function Yv(e){let o=[],t=/<style/gi,r=/<\/style>/gi;for(;;){let n=t.exec(e);if(!n)return o;let a=e.indexOf(">",n.index+6);if(a<0)return o;r.lastIndex=a+1;let s=r.exec(e);if(!s)return o;o.push(e.slice(a+1,s.index)),t.lastIndex=s.index+s[0].length}}function Kv(e,o){let t=[],r=[],n=[],a=!1,s=!1;for(let[d,u]of o){if(!/\.(css|html?)$/i.test(d)){let f=[...u.matchAll(/\b(?:color|background(?:Color)?)\s*:\s*["'](#[0-9a-f]{3,8}|rgba?\([^)]{0,80}\))["']/gi)].length;f&&r.push(`${d} pone ${f} color(es) fijos en estilos del c\xF3digo: con el tema oscuro pueden no verse.`),/var\(--[\w-]+/.test(u)&&(a=!0);continue}let p=/\.css$/i.test(d)?u:Yv(u).join(`
|
|
40
|
+
`)+[...u.matchAll(/\sstyle\s*=\s*"([^"]*)"/gi)].map(f=>`x{${f[1]}}`).join(`
|
|
41
|
+
`);if(p.trim()){s=!0;for(let[f,h]of Xv(Hv(p))){let b=f.trim().replace(/\s+/g," "),v=null,w=null;for(let g of h.matchAll(/(?:^|;)\s*(color|background-color|background)\s*:\s*([^;]+)/gi)){let y=Gv(g[2]);y.tema&&(a=!0),g[1].toLowerCase()==="color"?v=y:w=y,!y.tema&&!y.neutro&&y.color&&(/(^|,)\s*(html|body|:root)\s*(,|$)/i.test(b)?t.push(`${d}: \xAB${b}\xBB fija ${g[1]} (${g[2].trim()}): la p\xE1gina no seguir\xE1 el tema claro y oscuro del CRM. Usa var(--background) y var(--foreground).`):r.push(`${d}: \xAB${b}\xBB usa un color fijo en ${g[1]} (${g[2].trim()}).`))}if(v?.color&&w?.color){let g=Qv(v.color,w.color);g<4.5&&n.push(`${d}: \xAB${b}\xBB tiene un contraste de ${g.toFixed(2)}:1 entre el texto y el fondo (hace falta 4,5:1).`)}}}}let c=e.montajes.length>0;return c&&s&&!a&&t.push("La interfaz no usa ninguna variable del tema (var(--background), var(--foreground), var(--primary)\u2026): no parecer\xE1 del CRM ni seguir\xE1 el modo oscuro."),[bo("forja","Forja: colores del tema",t,r,c?"Toma los colores del tema del CRM.":"No trae interfaz."),bo("contraste","Contraste del texto (\u2265 4,5:1)",n,[],"Los colores fijos que se pueden medir tienen contraste suficiente.")]}function eo(e,o){for(let t=0;t<3;t++)if((e[t]??0)!==o[t])return(e[t]??0)<o[t];return!1}function oy(e,o,t){let r=[],n=new Set,a=(c,d,u)=>{let p=c.toLowerCase().replace(/\.js$/,"");n.add(`${p} ${d}`);let f=d.split(".").map(Number);for(let h of Zv)h.nombre.test(p)&&h.malas(f)&&r.push(`${u} trae ${h.etiqueta} ${d}, con un fallo de seguridad conocido: usa la ${h.arreglo} o posterior.`)};for(let c of o){let d=/(?:^|\/)([a-z][a-z.]*?)[-.@]v?(\d{1,3}\.\d{1,3}\.\d{1,3})(?:\.min)?\.m?js$/i.exec(c);d&&a(d[1],d[2],c)}for(let[c,d]of t)for(let u of d.matchAll(/\/\*[!*][\s\S]{0,600}?\*\//g))for(let p of u[0].matchAll(ey))a(p[1],p[2],c);let s=e.depende_de.map(c=>`Necesita la app \xAB${c.id}\xBB${c.version?` (${c.version})`:""} instalada antes.`);return bo("dependencias","Dependencias sin fallos conocidos",r,s,n.size?`Librer\xEDas vistas: ${[...n].join(", ")}.`:"No se ven librer\xEDas de terceros con versi\xF3n.")}function ty(e){let o=[];for(let[t,r]of e)/\.(m?js|cjs|jsx|html?)$/i.test(t)&&(/\beval\s*\(|\bnew\s+Function\s*\(/.test(r)&&o.push(`${t} ejecuta c\xF3digo construido en tiempo de ejecuci\xF3n (eval o new Function).`),/\b(?:window\.)?(?:top|parent)\.location\b|\bdocument\.cookie\b/.test(r)&&o.push(`${t} toca la ventana de arriba o las cookies (el CRM lo impide; se mira en la revisi\xF3n).`));return bo("codigo","C\xF3digo para la revisi\xF3n humana",[],o,"Nada que marcar.")}function yc(e){let o=[...e.recursos.keys()].sort(),t=o.filter(d=>Iv.test(d)).map(d=>[d,e.recursos.get(d).toString("utf8")]),{red:r,usaRed:n}=Vv(e.ext,t),a=n||e.ext.servidor!==null,s=[bo("esquema","Manifiesto y soluci\xF3n v\xE1lidos",[],[],"El manifiesto y su soluci\xF3n pasan el validador del CRM."),bo("firma","Firmada por su desarrollador",e.firmada?[]:["El paquete no va firmado: `forgenex empaquetar` con tu clave registrada."],[],e.enLocal?"Se firma al empaquetar con tu clave (la tienda exige firma).":"Firma v\xE1lida de una clave registrada."),bo("tamano","Tama\xF1o",e.bytes>pc?["El paquete pasa de 5 MB."]:[],[],`${(e.bytes/1024).toFixed(0)} KB de 5 MB.`),Fv(e.ext,t),...Kv(e.ext,t),r,bo("politica","Pol\xEDtica de datos",a&&!e.ext.politica_datos?["La app se conecta fuera del CRM: a\xF1ade \xABpolitica_datos\xBB (una direcci\xF3n https con tu pol\xEDtica de datos) al manifiesto."]:[],[],e.ext.politica_datos?`Pol\xEDtica de datos: ${e.ext.politica_datos}`:"No hace falta: no se conecta fuera."),oy(e.ext,o,t),ty(t)],c=s.filter(d=>d.estado==="falla").length;return{ok:c===0,version:1,puntos:s,fallas:c,avisos:s.filter(d=>d.estado==="aviso").length}}var Iv,bc,Vh,bo,wc,Lv,Dv,Jh,Qh,Wv,Bv,Uv,vc,Gh,Jv,Hh,Qv,Zv,ey,Xh=m(()=>{kt();Ei();Iv=/\.(m?js|cjs|jsx|html?|css|svg)$/i,bc=12,Vh=e=>{let o=[...new Set(e)];return o.length>bc?[...o.slice(0,bc),`\u2026 y ${o.length-bc} m\xE1s`]:o},bo=(e,o,t,r=[],n="")=>({clave:e,titulo:o,estado:t.length?"falla":r.length?"aviso":"ok",detalles:t.length?Vh(t):r.length?Vh(r):n?[n]:[]}),wc={buscar:"ver",ver:"ver",listar:"ver",obtener:"ver",pdf:"ver",crear:"crear",actualizar:"editar",mover:"editar",completar:"editar",borrar:"borrar"},Lv=new Set(["contexto.actual","publica.llamar","app.ajustes","extensiones.calcular"]),Dv=new Set(["registros.relacionadas","registros.historial","registros.opciones","registros.adjuntar","mensajes.proponer"]);Jh={ver:"ver",crear:"crear",editar:"cambiar",borrar:"borrar",almacen:"guardar datos",leer:"leer",escribir:"vincular"},Qh=e=>Object.hasOwn(Io,e)?Io[e].nombre:`\xAB${e.replace(/^mod_/,"")}\xBB`;Wv=/(fetch|WebSocket|EventSource|sendBeacon|\.open|import|axios(?:\.[a-z]+)?|\$\.(?:get|post|ajax|getJSON))\s*\(\s*["'`]?$|(?:src|href|action|srcset|poster|data)\s*=\s*["']?$|url\(\s*["']?$|@import\s+(?:url\()?["']?$/i,Bv=new Set(["www.w3.org","w3.org"]),Uv=/(?:\.min\.(?:m?js|css)$)|(?:^|\/)(?:jquery|lodash|alpine|react|vue|preact|chart|d3|moment|axios|dompurify|underscore|bootstrap|handlebars)[^/]*\.m?js$/i,vc=(e,o)=>e.some(t=>t===o||t.startsWith("*.")&&o.endsWith(t.slice(1)));Gh={white:[255,255,255],black:[0,0,0],red:[255,0,0],green:[0,128,0],blue:[0,0,255],gray:[128,128,128],grey:[128,128,128],silver:[192,192,192],yellow:[255,255,0],orange:[255,165,0],navy:[0,0,128],purple:[128,0,128],lightgray:[211,211,211],lightgrey:[211,211,211],darkgray:[169,169,169],darkgrey:[169,169,169],whitesmoke:[245,245,245],gainsboro:[220,220,220]},Jv=/^(transparent|inherit|initial|unset|revert|currentcolor|none)$/i;Hh=([e,o,t])=>{let r=n=>{let a=n/255;return a<=.03928?a/12.92:((a+.055)/1.055)**2.4};return .2126*r(e)+.7152*r(o)+.0722*r(t)},Qv=(e,o)=>{let[t,r]=[Hh(e),Hh(o)].sort((n,a)=>a-n);return(t+.05)/(r+.05)};Zv=[{nombre:/^jquery$/i,etiqueta:"jQuery",malas:e=>eo(e,[3,5,0]),arreglo:"3.5.0 (CVE-2020-11022)"},{nombre:/^lodash$/i,etiqueta:"Lodash",malas:e=>eo(e,[4,17,21]),arreglo:"4.17.21 (CVE-2021-23337)"},{nombre:/^moment$/i,etiqueta:"Moment.js",malas:e=>eo(e,[2,29,4]),arreglo:"2.29.4 (CVE-2022-31129)"},{nombre:/^handlebars$/i,etiqueta:"Handlebars",malas:e=>eo(e,[4,7,7]),arreglo:"4.7.7 (CVE-2021-23369)"},{nombre:/^bootstrap$/i,etiqueta:"Bootstrap",malas:e=>eo(e,[3,4,1])||e[0]===4&&eo(e,[4,3,1]),arreglo:"3.4.1 o 4.3.1 (CVE-2019-8331)"},{nombre:/^angular(js)?$/i,etiqueta:"AngularJS",malas:e=>e[0]===1,arreglo:"ninguna: AngularJS 1.x ya no recibe arreglos"},{nombre:/^dompurify$/i,etiqueta:"DOMPurify",malas:e=>e[0]===2?eo(e,[2,5,4]):eo(e,[3,1,3]),arreglo:"2.5.4 o 3.1.3 (CVE-2024-45801)"},{nombre:/^axios$/i,etiqueta:"Axios",malas:e=>e[0]===0?eo(e,[0,28,0]):eo(e,[1,6,0]),arreglo:"0.28.0 o 1.6.0 (CVE-2023-45857)"},{nombre:/^underscore$/i,etiqueta:"Underscore",malas:e=>eo(e,[1,12,1]),arreglo:"1.12.1 (CVE-2021-23358)"}];ey=/\b(jquery|lodash|moment|handlebars|bootstrap|angularjs|angular|dompurify|axios|underscore|alpine(?:js)?|react|vue|preact|chart\.js|d3)(?:\.js)?(?:\s+javascript\s+library)?[\s@:,-]*v?(\d{1,3}\.\d{1,3}\.\d{1,3})\b/gi});import{Worker as ry}from"node:worker_threads";var ny,_c,Ri,Yh=m(()=>{pr();ny=new URL(import.meta.url.endsWith(".ts")?"./caja.ts":"./caja.js",import.meta.url),_c=class{w=null;ocupada=!1;worker(){return this.w?this.w:(this.w=new ry(ny,{resourceLimits:{maxOldGenerationSizeMb:96,maxYoungGenerationSizeMb:16,stackSizeMb:4},env:{},stdout:!0,stderr:!0}),this.w.stdout.resume(),this.w.stderr.resume(),this.w.unref(),this.w)}matar(){let o=this.w;this.w=null,o&&o.terminate().catch(()=>{})}correr(o){this.ocupada=!0;let t=Date.now(),r=this.worker();return new Promise(n=>{let a=!1,s=0,c=(b,v)=>{a||(a=!0,clearTimeout(f),r.off("message",d),r.off("error",u),r.off("exit",p),v&&this.matar(),this.ocupada=!1,n(b))},d=b=>{if(b.tipo==="llamar"){if(a)return;if(typeof b.datos!="string"||b.datos.length>D.llamadaCaracteres||s>=D.llamadasEnVuelo){r.postMessage({tipo:"respuesta",n:b.n,ok:!1,valor:typeof b.datos=="string"&&b.datos.length<=D.llamadaCaracteres?"demasiadas llamadas a la vez":"lo que se manda al CRM es demasiado grande"});return}let w=null;try{w=JSON.parse(b.datos)}catch{}s++,o.manejar(b.que,w).finally(()=>{s--}).then(g=>!a&&r.postMessage({tipo:"respuesta",n:b.n,ok:!0,valor:JSON.stringify(g??null)}),g=>!a&&r.postMessage({tipo:"respuesta",n:b.n,ok:!1,valor:g instanceof Error?g.message:String(g)}));return}let v=Date.now()-t;b.ok?c({ok:!0,salida:b.salida,ms:v},!1):c({ok:!1,corte:b.corte,clase:b.clase,mensaje:b.mensaje,ms:v},b.corte!==null)},u=b=>c({ok:!1,corte:/memory|heap/i.test(b.message)?"memoria":null,clase:"Error",mensaje:"la caja se ha cerrado",ms:Date.now()-t},!0),p=()=>c({ok:!1,corte:null,clase:"Error",mensaje:"la caja se ha cerrado",ms:Date.now()-t},!0),f=setTimeout(()=>c({ok:!1,corte:"tiempo",clase:"InternalError",mensaje:"interrupted",ms:Date.now()-t},!0),o.ms+D.margenMs);r.on("message",d),r.on("error",u),r.on("exit",p);let h={tipo:"correr",codigo:o.codigo,fichero:o.fichero,entrada:o.entrada,contexto:o.contexto,ms:o.ms,memoriaMb:o.memoriaMb,pilaBytes:D.pilaBytes,salidaBytes:D.salidaBytes,llamadaCaracteres:D.llamadaCaracteres,enVuelo:D.llamadasEnVuelo};r.postMessage(h)})}cerrar(){this.matar()}},Ri=class{ranuras;cola=[];constructor(o=D.simultaneas){this.ranuras=Array.from({length:Math.max(1,o)},()=>new _c)}get libres(){return this.ranuras.filter(o=>!o.ocupada).length}async correr(o){let t=this.ranuras.find(r=>!r.ocupada);for(;!t;)await new Promise(r=>this.cola.push(r)),t=this.ranuras.find(r=>!r.ocupada);t.ocupada=!0;try{return await t.correr(o)}finally{this.cola.shift()?.()}}intentar(o){return this.ranuras.some(t=>!t.ocupada)?this.correr(o):null}cerrarSiLibre(){!this.cola.length&&this.ranuras.every(o=>!o.ocupada)&&this.cerrar()}cerrar(){for(let o of this.ranuras)o.cerrar()}}});import{lookup as iy}from"node:dns/promises";import{request as ay}from"node:https";import{isIP as sy}from"node:net";async function $c(e,o,t={}){let r;try{r=new URL(e.url)}catch{throw new fe("direcci\xF3n no v\xE1lida")}if(r.protocol!=="https:")throw new fe("solo https");if(r.username||r.password)throw new fe("sin usuario ni clave en la direcci\xF3n");if(r.port&&r.port!=="443")throw new fe("solo al puerto 443");let n=r.hostname.toLowerCase().replace(/\.$/,"");if(sy(n.replace(/^\[|\]$/g,""))||!Nc(o,n))throw new fe("el dominio no est\xE1 entre los dominios aceptados");let a=String(e.metodo||"GET").toUpperCase();if(!Kh.has(a))throw new fe("m\xE9todo no admitido");let s={};if(e.cabeceras&&typeof e.cabeceras=="object")for(let[f,h]of Object.entries(e.cabeceras).slice(0,30)){let b=f.toLowerCase();if(!ly.test(f)||cy.has(b)||b.startsWith("x-crm-")||b.startsWith("x-forgenex"))continue;let v=String(h);/[\r\n\0]/.test(v)||v.length>4096||(s[b]=v)}s["user-agent"]="ForgeNEX-CRM-Extension/1";let c=e.cuerpo===null||e.cuerpo===void 0?null:String(e.cuerpo);if(c!==null&&Buffer.byteLength(c)>D.red.cuerpoBytes)throw new fe(`el cuerpo pasa de ${D.red.cuerpoBytes/1024} KB`);if(c!==null&&(a==="GET"||a==="HEAD"))throw new fe("GET y HEAD no llevan cuerpo");let d=await(t.resolver??(f=>iy(f,{all:!0,verbatim:!0})))(n).catch(()=>[]);if(!d.length)throw new fe(`${n.slice(0,80)} no resuelve`);if(d.some(f=>fh(f.address)))throw new fe(`${n.slice(0,80)} apunta a una red interna`);let u={url:r,ip:d[0].address,familia:d[0].family===6?6:4},p=await(t.transporte??dy)(u,{metodo:a,cabeceras:s,cuerpo:c});return{host:n,respuesta:p}}function dy(e,o){return new Promise((t,r)=>{let n={...o.cabeceras,...o.cuerpo!==null?{"content-length":String(Buffer.byteLength(o.cuerpo))}:{}},a=ay({protocol:"https:",hostname:e.url.hostname,servername:e.url.hostname,port:443,path:`${e.url.pathname}${e.url.search}`,method:o.metodo,headers:n,lookup:((c,d,u)=>d?.all?u(null,[{address:e.ip,family:e.familia}]):u(null,e.ip,e.familia)),timeout:D.red.plazoMs,agent:!1},c=>{let d=[],u=0;c.on("data",p=>{if(u+=p.length,u>D.red.respuestaBytes){c.destroy(),r(new fe(`la respuesta pasa de ${D.red.respuestaBytes/1024/1024} MB`));return}d.push(p)}),c.on("end",()=>{clearTimeout(s);let p={};for(let f of uy){let h=c.headers[f];typeof h=="string"&&(p[f]=h.slice(0,2e3))}t({status:c.statusCode??0,headers:p,cuerpo:Buffer.concat(d).toString("utf8")})}),c.on("error",()=>r(new fe("la respuesta se cort\xF3")))}),s=setTimeout(()=>a.destroy(new fe("sin respuesta a tiempo")),D.red.plazoMs);a.on("timeout",()=>a.destroy(new fe("sin respuesta a tiempo"))),a.on("error",c=>{clearTimeout(s),r(c instanceof fe?c:new fe("no se ha podido conectar"))}),a.end(o.cuerpo??void 0)})}var fe,Kh,cy,ly,uy,Nc,xc=m(()=>{hh();pr();fe=class extends Error{constructor(t){super(`fetch: ${t}`);this.motivo=t}motivo},Kh=new Set(["GET","POST","PUT","PATCH","DELETE","HEAD"]),cy=new Set(["host","connection","content-length","transfer-encoding","upgrade","te","trailer","keep-alive","proxy-authorization","proxy-connection","expect","cookie","x-forwarded-for","x-real-ip","forwarded"]),ly=/^[A-Za-z0-9!#$%&'*+.^_`|~-]{1,64}$/,uy=["content-type","location","retry-after","etag","last-modified"],Nc=(e,o)=>e.some(t=>t===o||t.startsWith("*.")&&o.endsWith(t.slice(1))&&o.length>t.length-1)});function eg(e,o){if(typeof o!="string"||typeof e!="string")return null;let r=(Object.hasOwn(Zh,o)?Zh[o]:null)??wo(o);if(!r)return null;let n=r.startsWith("mod_");switch(e){case"ver":return n?`${r}.ver`:py[r]??`${r}.ver`;case"buscar":return n?`${r}.listar`:my[r]??`${r}.buscar`;case"crear":return`${r}.crear`;case"actualizar":return`${r}.actualizar`;default:return null}}function og(e,o){return e.filter(t=>Nc(o,t.startsWith("*.")?`x${t.slice(1)}`:t)&&(!t.startsWith("*.")||o.includes(t)))}var Zh,py,my,tg=m(()=>{kt();xc();Zh={contactos:"contactos",contacts:"contactos",empresas:"empresas",companies:"empresas",oportunidades:"oportunidades",deals:"oportunidades",tareas:"tareas",tasks:"tareas",notas:"notas"},py={tareas:"tareas.obtener"},my={tareas:"tareas.listar",notas:"notas.listar"}});var ig={};bg(ig,{iniciarDev:()=>vy});import{createServer as fy}from"node:http";import{randomBytes as rg}from"node:crypto";import{readFileSync as hy,realpathSync as ng,watch as gy}from"node:fs";import{join as by,sep as wy}from"node:path";async function vy(e){let o=dr(e),t=Number(Ue(e,"puerto")??5173),r=ng(process.cwd());if(!Number.isInteger(t)||t<1||t>65535)throw new Error("Puerto no v\xE1lido.");let n=go(r),a=(y,C)=>ur(o.api,o.clave,"/api/desarrollador/desarrollo",{espacio:o.espacio,ext_id:n.id,pase:y,funcion:C}),s=await a();await lr(r);let c=new Ri(1),d=rg(24).toString("hex"),u=1,p=null,f,h=gy(r,{recursive:!0},(y,C)=>{let O=String(C??"");/node_modules|\.fgx$|\.pem|^\.git[\/\\]/.test(O)||O==="interfaz/app.js"||(clearTimeout(f),f=setTimeout(()=>{p=lr(r).then(()=>{go(r),u++,console.log("App actualizada.")}).catch(M=>console.error("Error de desarrollo:",M.message)).finally(()=>{p=null})},100))}),b=fy(async(y,C)=>{let O=(M,Z)=>{C.writeHead(M,{"content-type":"application/json","cache-control":"no-store"}),C.end(JSON.stringify(Z))};try{if(![`127.0.0.1:${t}`,`localhost:${t}`].includes(y.headers.host??""))return O(403,{error:"host_no_permitido"});let M=y.headers.origin;if(M&&M!==o.api)return O(403,{error:"origen_no_permitido"});if(M===o.api&&(C.setHeader("access-control-allow-origin",o.api),C.setHeader("vary","origin")),C.setHeader("access-control-allow-methods","GET, POST, OPTIONS"),C.setHeader("access-control-allow-headers","content-type, authorization"),y.method==="OPTIONS"){C.writeHead(204),C.end();return}let Z=new URL(y.url??"/",`http://127.0.0.1:${t}`),$=decodeURIComponent(Z.pathname);if(!$.startsWith(`/${d}/`))return O(404,{error:"no_encontrado"});let A=$.slice(d.length+2);if(A==="__forgenex/version"&&y.method==="GET")return O(200,{version:u});if(A.startsWith("__forgenex/funcion/")&&y.method==="POST"){if(M!==o.api)return O(403,{error:"origen_no_permitido"});let x=(y.headers.authorization??"").replace(/^Bearer /,"");if(!x.startsWith("crmui_"))return O(401,{error:"falta_pase"});if(!c.libres)return O(429,{error:"funcion_ocupada"});let I=A.slice(19),z=await a(x,I),ee=go(r).funciones.find(Re=>Re.nombre===I),H=z.manifiesto.funciones.find(Re=>Re.nombre===I);if(!ee||!H)return O(403,{error:"funcion_no_instalada"});let we=await fetch(`${o.api}/api/v1/capabilities`,{redirect:"error",headers:{authorization:`Bearer ${x}`,"x-espacio":String(o.espacio)}});if(!we.ok)return O(we.status,{error:"pase_revocado"});let oo=await yy(y),Po=rg(12).toString("hex"),et=0,X=0,qe=await c.correr({codigo:v(ee.entrada).toString("utf8"),fichero:ee.entrada,entrada:oo,contexto:{extension:n.id,version:n.version,funcion:I,disparo:"desarrollo",ejecucion:Po},...Fc(ee),manejar:async(Re,q)=>{if(Re==="red"){if(++X>D.llamadasRed)throw new Error("Demasiadas peticiones de red.");return(await $c(q,og(H.red,z.aceptados.red_hacia))).respuesta}if(++et>D.llamadasApi)throw new Error("Demasiadas llamadas al CRM.");let L=q,oe=L.op??eg(L.accion,L.modulo);if(!oe||!/^[a-z][a-z0-9_]*\.[a-z][a-z0-9_]*$/.test(oe))throw new Error("Operaci\xF3n no v\xE1lida.");let qt=await fetch(`${o.api}/api/v1/capabilities`,{redirect:"error",headers:{authorization:`Bearer ${x}`,"x-espacio":String(o.espacio)}});if(!qt.ok)throw new Error("Pase caducado o revocado.");let Ec=await qt.json(),qc=(Ec.data?.operaciones??Ec.operaciones??[]).find(Pi=>Pi.id===oe);if(!qc)throw new Error("Operaci\xF3n no aceptada por el administrador.");let ki=qc.metodo,Rc=L.args??{},fg=ki==="GET"?`?${new URLSearchParams(Object.entries(Rc).map(([Pi,hg])=>[Pi,String(hg)]))}`:"",kc=await fetch(`${o.api}/api/v1/op/${oe}${fg}`,{method:ki,redirect:"error",headers:{authorization:`Bearer ${x}`,"x-espacio":String(o.espacio),"content-type":"application/json","idempotency-key":`dev-${Po}-${et}`},...ki==="POST"?{body:JSON.stringify(Rc)}:{}}),Pc=await kc.json();if(!kc.ok)throw new Error(Pc.error?.mensaje??"El CRM rechaz\xF3 la operaci\xF3n.");return Pc.data}});return qe.ok||console.error(`Funci\xF3n ${I}: ${qe.clase}: ${qe.mensaje}`),O(qe.ok?200:422,qe)}if(y.method!=="GET")return O(405,{error:"metodo_no_permitido"});if(await p,!A.startsWith("interfaz/"))return O(404,{error:"no_encontrado"});let N=v(A),k=A.endsWith(".html")?"text/html":A.endsWith(".js")?"text/javascript":A.endsWith(".css")?"text/css":"application/octet-stream";C.writeHead(200,{"content-type":k,"cache-control":"no-store"}),C.end(N)}catch(M){console.error("Error de desarrollo:",M.message),O(400,{error:"desarrollo_error",mensaje:M.message})}});function v(y){if(y.includes("\\")||y.split("/").some(M=>M===".."||M==="."||!M))throw new Error("Ruta no admitida.");let C=ng(by(r,y));if(!C.startsWith(r+wy))throw new Error("Ruta fuera del proyecto.");let O=hy(C);if(O.length>2*1024*1024)throw new Error("Recurso demasiado grande.");return O}let w=()=>{clearTimeout(f),h.close(),c.cerrar(),b.closeAllConnections(),b.close()};b.on("error",y=>{console.error(y.message),w(),process.exitCode=1}),process.once("SIGINT",w),process.once("SIGTERM",w),await new Promise((y,C)=>{b.once("error",C),b.listen(t,"127.0.0.1",y)});let g=`http://127.0.0.1:${t}/${d}`;console.log(`Desarrollo: ${g}
|
|
35
42
|
Abrir CRM: ${o.api}/#/ajustes/extensiones?desarrollo=${s.id}&local=${encodeURIComponent(g)}
|
|
36
|
-
Recarga al guardar. Funciones: crm.pedir("desarrollo.funcion", { nombre, entrada }, { metodo: "POST", idempotencia: crypto.randomUUID() }).`)}async function
|
|
37
|
-
P\xFAblica: ${t}.pub`),0}if(e==="registrar-clave"){let t=ir(o),n=Ci(fc(o),"utf8");return console.log(JSON.stringify(await nr(t.api,t.clave,"/api/desarrollador/claves",{espacio:t.espacio,publica:Uh(n).export({type:"spki",format:"pem"}).toString()}))),0}if(e==="revocar-clave"){let t=ir(o),n=Ze(o,"huella");if(!n||!/^[a-f0-9]{64}$/.test(n))throw new Error("Falta --huella <id de clave p\xFAblica>.");return console.log(JSON.stringify(await nr(t.api,t.clave,"/api/desarrollador/revocar-clave",{espacio:t.espacio,id:n}))),0}if(e==="empaquetar"){let t=Ci(fc(o),"utf8");return console.log(await Rh(process.cwd(),t,Uh(t).export({type:"spki",format:"pem"}).toString())),0}if(e==="instalar"){let t=ir(o),n=Ze(o,"paquete"),r=Ze(o,"app"),a=Ze(o,"version");if(!n&&!r)throw new Error("Falta --app <id de la app publicada> o --paquete <archivo.fgx>.");let s=r?{espacio:t.espacio,app:r,version:a}:{espacio:t.espacio,paquete:Ci(n).toString("base64")},l=await nr(t.api,t.clave,"/api/desarrollador/instalar",s);return console.log(JSON.stringify(l)),l?.pendiente_permisos!==!1&&console.log("El administrador debe aceptar los permisos en Ajustes \u203A Apps."),0}if(e==="publicar"){let t=ir(o),n=Ze(o,"paquete");if(!n)throw new Error("Falta --paquete <archivo.fgx> (lo hace `forgenex empaquetar`).");let r=await nr(t.api,t.clave,"/api/desarrollador/publicar",{espacio:t.espacio,paquete:Ci(n).toString("base64")});console.log(JSON.stringify(r));let a=s=>r.espacios.filter(l=>l.resultado===s).length;return console.log(`Publicada ${r.ext_id} ${r.version} en tus apps.`),a("activa")&&console.log(`\xB7 Actualizada sola en ${a("activa")} espacio(s): no pide m\xE1s permisos.`),a("pendiente_permisos")&&console.log(`\xB7 En ${a("pendiente_permisos")} espacio(s) pide m\xE1s permisos: su administrador los acepta en Ajustes \u203A Apps.`),a("a_mano")&&console.log(`\xB7 En ${a("a_mano")} espacio(s) no se aplica sola (cambian sus m\xF3dulos, o lo instalado all\xED no sali\xF3 de \xABMis apps\xBB): actual\xEDzala con \`forgenex instalar --app ${r.ext_id} --espacio <id>\`.`),a("modo_desarrollador")&&console.log(`\xB7 En ${a("modo_desarrollador")} espacio(s) el modo desarrollador est\xE1 apagado: no se ha tocado.`),a("error")&&console.log(`\xB7 En ${a("error")} espacio(s) no se ha podido actualizar: prueba con \`forgenex instalar --app\`.`),a("cliente_ajeno")&&console.log(`\xB7 En ${a("cliente_ajeno")} espacio(s) no se ha tocado: en ForgeNEX ya no son tuyos ni de un cliente tuyo.`),a("panel_no_disponible")&&console.log(`\xB7 En ${a("panel_no_disponible")} espacio(s) no se ha tocado porque no se ha podido comprobar con ForgeNEX: vuelve a publicar en un momento o usa \`forgenex instalar --app\`.`),0}if(e==="dev"){let{iniciarDev:t}=await Promise.resolve().then(()=>(Bh(),Wh));return await t(o),0}return null}var mc=m(()=>{$i()});mc();$i();Lr();_s();rc();Js();ai();Us();Yr();import{readFileSync as Hh,statSync as Uv}from"node:fs";import{join as Vv}from"node:path";var hc=200;function Jv(e,o){try{return{archivo:e,ok:!0,solucion:yi(o,{topeCampos:hc})}}catch(t){return{archivo:e,ok:!1,error:t instanceof Error?t.message:String(t)}}}function Qv(e){try{let o=JSON.parse(e);return typeof o=="object"&&o!==null&&o.formato===Xo}catch{return!1}}function Gv(e,o){try{return{archivo:e,ok:!0,extension:Xr(o)}}catch(t){return{archivo:e,ok:!1,error:t instanceof Error?t.message:String(t)}}}function Hv(){let e=n=>n.length>1?`${n.slice(0,-1).join(", ")} y ${n.at(-1)}`:n[0]??"",o=Ot.filter(n=>Hr.has(n)).map(n=>`\xAB${n}\xBB`),t=Ot.filter(n=>!Hr.has(n)).map(n=>`\xAB${n}\xBB`);return`D\xF3nde se cuelga su interfaz, en una caja aislada (iframe sin origen). Se pintan ${e(o)}${t.length?`; ${e(t)} se validan, pero todav\xEDa no se pintan`:""}. \xABpublica\xBB es la p\xE1gina sin sesi\xF3n (/app/<enlace>), con sus \xABfunciones\xBB.`}function Xv(){let e=a=>({type:"string",maxLength:a}),o={type:"string",pattern:"^(\\*\\.)?([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\\.)+[a-z]{2,63}$"},t={type:"string",maxLength:200,pattern:"^[A-Za-z0-9_./-]{1,200}$",description:"Un fichero del paquete (relativo, sin \xAB..\xBB)."},n={type:"string",pattern:"^[a-z][a-z0-9_]{0,40}$"},r="Se valida, pero todav\xEDa no se ejecuta (llega en una fase siguiente de las apps).";return{$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://forgenex.com/sdk/extension-v1.schema.json",title:"App del CRM ForgeNEX",description:`Formato \xAB${Xo}\xBB, versi\xF3n ${Qr}. Valida la forma; \xABforgenex-sdk validar\xBB valida todo (el mismo validador que el CRM).`,type:"object",additionalProperties:!1,required:["formato","formato_version","id","nombre","version","autor"],properties:{$schema:{type:"string"},formato:{const:Xo},formato_version:{type:"integer",minimum:1,maximum:Qr,description:"Versi\xF3n del FORMATO (no de la app)."},id:{type:"string",maxLength:200,pattern:"^[a-z][a-z0-9-]{0,62}(\\.[a-z0-9][a-z0-9-]{0,62}){1,6}$",description:"Dominio inverso: com.tuempresa.mi-extension. No cambia nunca."},nombre:e(80),descripcion:e(500),version:{type:"string",pattern:"^(0|[1-9][0-9]{0,5})\\.(0|[1-9][0-9]{0,5})\\.(0|[1-9][0-9]{0,5})(-[0-9a-z.-]{1,30})?$",description:"La versi\xF3n de la app (semver)."},autor:{oneOf:[e(120),{type:"object",additionalProperties:!1,required:["nombre"],properties:{nombre:e(120),web:{type:"string",format:"uri",description:"https"}}}]},icono:{type:"string",pattern:"^[a-z0-9-]{1,40}$",description:"Un icono de lucide."},idiomas:{type:"array",maxItems:30,items:{type:"string",pattern:"^[a-z]{2,3}(-[A-Z]{2})?$"}},compatible_crm:{type:"string",maxLength:80,description:"Rango de versiones del CRM: \xAB>=1.6.0-284\xBB o \xAB>=1.6.0-284 <2.0.0\xBB."},licencia:e(40),depende_de:{type:"array",maxItems:20,description:"Otras apps que tienen que estar instaladas.",items:{oneOf:[{type:"string"},{type:"object",additionalProperties:!1,required:["id"],properties:{id:{type:"string"},version:{type:"string"}}}]}},ofrece:{type:"array",maxItems:20,items:{type:"string",pattern:"^[a-z][a-z0-9_.-]{0,79}$"},description:`Contratos con nombre que ofrece a otras apps. ${r}`},usa:{type:"array",maxItems:20,items:{type:"string",pattern:"^[a-z][a-z0-9_.-]{0,79}$"},description:`Contratos que usa de otras. ${r}`},solucion:{...t,description:"El fichero de la soluci\xF3n del paquete (\xABsolucion.json\xBB, formato forgenex.solucion): sus m\xF3dulos se instalan como copia."},montajes:{type:"array",maxItems:20,description:Hv(),items:{type:"object",additionalProperties:!1,required:["id","punto","entrada","titulo"],properties:{id:{type:"string",pattern:"^[a-z][a-z0-9_-]{0,40}$"},punto:{enum:[...Ot]},entrada:t,titulo:e(60),icono:{type:"string"},modulo:{type:"string",description:`Solo en ${[...cr].join(", ")}: el m\xF3dulo donde se cuelga (permisos.modulos tiene que pedir verlo).`},permiso:{type:"string",description:"<m\xF3dulo>.<operaci\xF3n>, dentro de \xABpermisos\xBB. No en \xABpublica\xBB."},funciones:{type:"array",maxItems:10,uniqueItems:!0,items:n,description:"Solo en \xABpublica\xBB: las funciones (de disparador \xABpublica\xBB) que su p\xE1gina puede llamar."}},allOf:[{if:{properties:{punto:{const:"publica"}},required:["punto"]},then:{not:{required:["permiso"]}},else:{not:{required:["funciones"]}}},{if:{properties:{punto:{enum:[...cr]}},required:["punto"]},then:{required:["modulo"]},else:{not:{required:["modulo"]}}}]}},funciones:{type:"array",maxItems:20,description:"Funciones JS que corren aisladas en el servidor del CRM (QuickJS), con `crm` (la API v1 recortada a lo aceptado) y `fetch` (solo a su \xABred\xBB aceptada). Las de \xABcalculo\xBB se llaman desde su interfaz por extensiones.calcular, solo con lecturas del CRM y sin red.",items:{type:"object",additionalProperties:!1,required:["nombre","entrada","disparador"],properties:{nombre:n,titulo:e(80),descripcion:e(300),entrada:{...t,description:"Su fichero .js del paquete: `export default async function (entrada, contexto) { \u2026 }`."},disparador:{type:"object",additionalProperties:!1,required:["tipo"],description:"evento (con \xABevento\xBB, que est\xE9 en permisos.eventos), programada (con \xABcron\xBB de 5 campos, como poco cada 15 min, hora de Madrid), webhook, automatizacion (un paso del dise\xF1ador) o calculo.",properties:{tipo:{enum:[...Vr]},evento:{type:"string"},cron:{type:"string"}}},tope:{type:"object",additionalProperties:!1,description:"Por llamada. Por defecto, 5000 ms y 64 MB.",properties:{ms:{type:"integer",minimum:100,maximum:3e4},memoria_mb:{type:"integer",minimum:16,maximum:256}}},red:{type:"array",maxItems:10,items:o,description:"Los dominios a los que llama (dentro de permisos.red_hacia). Solo https y sin seguir redirecciones."},parametros:{type:"object",maxProperties:20,description:"Solo en las de \xABautomatizacion\xBB: su entrada en el paso del dise\xF1ador.",additionalProperties:{type:"object",additionalProperties:!1,required:["tipo","desc"],properties:{tipo:{enum:["texto","numero","si_no","fecha"]},desc:e(200),requerido:{type:"boolean"}}}},salida:{type:"array",maxItems:30,description:"Las claves que devuelve (el paso deja guardar cada una en un campo). Con { clave, titulo }, el dise\xF1ador ense\xF1a el t\xEDtulo (\xABD\xEDas h\xE1biles\xBB).",items:{anyOf:[n,{type:"object",additionalProperties:!1,required:["clave"],properties:{clave:n,titulo:e(60)}}]}}}}},servidor:{type:"object",additionalProperties:!1,required:["url"],description:`El servidor propio del desarrollador. ${r}`,properties:{url:{type:"string",format:"uri"},webhooks:{type:"array",items:{type:"string"}}}},herramientas_ia:{type:"array",maxItems:20,description:"Herramientas para Pix (1.9.0). Cada una apunta a una funci\xF3n de disparador \xABherramienta\xBB, que recibe su \xABentrada\xBB y devuelve solo las claves de su \xABsalida\xBB. Corre como la app recortada a la persona que habla con Pix. \xABescribe\xBB: la persona confirma antes; sin \xE9l, si intenta escribir, tambi\xE9n. \xABpermiso\xBB (\xABvehiculos.ver\xBB, dentro de permisos.modulos): quien no lo tiene en su papel no la ve; sin \xE9l, solo la ve quien puede ver todos los m\xF3dulos que la app tiene aceptados.",items:{type:"object",additionalProperties:!1,required:["nombre","descripcion","riesgo","funcion"],properties:{nombre:{type:"string",pattern:"^[a-z][a-z0-9_]{2,40}$"},descripcion:e(500),entrada:{type:"object",maxProperties:20,description:"Lo que Pix (o el MCP) le pasa: { campo: { tipo, desc, requerido? } }, como los \xABparametros\xBB de una funci\xF3n. Tipos: texto, numero, si_no o fecha (en el MCP salen como string, number, boolean y string con fecha). No es un JSON Schema.",additionalProperties:{type:"object",additionalProperties:!1,required:["tipo","desc"],properties:{tipo:{enum:["texto","numero","si_no","fecha"]},desc:e(200),requerido:{type:"boolean"}}}},salida:{type:"array",items:n},riesgo:{enum:["bajo","medio","alto"]},funcion:n,escribe:{type:"boolean"},permiso:{type:"string",maxLength:80}}}},ajustes:{type:"array",maxItems:40,description:"Ajustes (1.13.0): un formulario en Ajustes \u203A Apps \u203A la app, con valores POR ESPACIO (cada instalaci\xF3n los suyos; al instalar, vac\xEDos). La app los lee con la operaci\xF3n v1 `app.ajustes` y sus funciones en `contexto.ajustes`. \xABrequerido\xBB marca el campo en el formulario, pero la app se activa igual sin \xE9l: compru\xE9balo en la funci\xF3n. \xABopcion\xBB lleva \xABopciones\xBB: [{ valor, etiqueta }]; el valor de \xABmodulo\xBB es la clave de un m\xF3dulo del espacio y el de \xABcampo\xBB, \xABmodulo.campo\xBB.",items:{type:"object",additionalProperties:!1,required:["clave","etiqueta","tipo"],properties:{clave:n,etiqueta:e(80),tipo:{enum:[...Jr]},opciones:{type:"array",items:{type:"object",additionalProperties:!1,required:["valor","etiqueta"],properties:{valor:e(60),etiqueta:e(80)}}},requerido:{type:"boolean"}}}},secretos:{type:"array",maxItems:10,description:"Secretos (1.13.0): claves de terceros que pone el administrador de CADA espacio en Ajustes \u203A Apps \u203A la app; van cifradas y SOLO las recibe una funci\xF3n de servidor mientras corre (`contexto.secretos`). Nunca la interfaz, la v1, el MCP ni una exportaci\xF3n.",items:{type:"object",additionalProperties:!1,required:["clave","etiqueta"],properties:{clave:n,etiqueta:e(80),descripcion:e(300)}}},permisos:{type:"object",additionalProperties:!1,description:"Lo que pide. El administrador lo ve y lo acepta al instalar; la clave de la app nunca puede m\xE1s (ni m\xE1s que el papel de su responsable).",properties:{modulos:{type:"object",maxProperties:40,description:`M\xF3dulo \u2192 operaciones. De serie: ${Object.entries(Gr).map(([a,s])=>`${a} (${s.ops.join(", ")})`).join("; ")}. Los de su soluci\xF3n o del espacio, por su clave: ${sr.join(", ")}.`,additionalProperties:{type:"array",minItems:1,maxItems:4,uniqueItems:!0,items:{enum:[...sr]}}},almacen:{type:"boolean",description:"Guardar sus datos internos (clave-valor JSON) en el almac\xE9n de la app."},red_hacia:{type:"array",maxItems:20,items:o,description:"Los dominios a los que pueden conectarse sus funciones (\xAB*.ejemplo.com\xBB cubre sus subdominios). El administrador acepta cada uno."},eventos:{type:"array",maxItems:40,items:{type:"string"},description:"Los eventos del CRM de los que se entera (registro.creado, registro.actualizado\u2026). El administrador acepta cada uno."}}}},"x-forgenex":{tamanoMaximoBytes:Ur}}}function Xh(e){return{nombre:e.nombre,plantilla:e.plantilla??null,modulos:e.modulos.map(o=>({clave:o.clave,nombre:o.nombre_plural,campos:o.campos.length,relaciones:o.campos.filter(t=>t.tipo==="relacion").map(t=>t.relacion??"").filter(Boolean),vistas:o.vistas?.length??0})),paneles:e.paneles?.length??0,automatizaciones:e.automatizaciones?.length??0,informes:e.informes?.length??0,mensajes:e.mensajes?.length??0,papeles:(e.papeles??[]).map(o=>`${o.nombre} (${o.base})`),portales:(e.portales??[]).map(o=>String(o.nombre??o.clave??"")),principal:e.principal??null,ejemplos:Object.fromEntries(Object.entries(e.ejemplos??{}).map(([o,t])=>[o,t.length]))}}function Yv(){let e=o=>({type:"string",maxLength:o});return{$schema:"https://json-schema.org/draft/2020-12/schema",$id:`https://forgenex.com/sdk/solucion-v${tr}.schema.json`,title:"Soluci\xF3n del CRM ForgeNEX",description:`Formato \xAB${xt}\xBB, versi\xF3n ${tr}. Valida la forma; \xABforgenex-sdk validar\xBB valida todo (el mismo validador que el CRM).`,type:"object",additionalProperties:!1,required:["formato","version","nombre","modulos"],properties:{formato:{const:xt},version:{type:"integer",minimum:1,maximum:tr,description:"Versi\xF3n del FORMATO (el CRM lee esta y las anteriores)."},plantilla:{type:"object",additionalProperties:!1,required:["id","version","sector"],properties:{id:{type:"string",pattern:"^[a-z][a-z0-9_]{0,59}$"},version:{type:"integer",minimum:1},sector:{type:"string",pattern:"^[a-z][a-z0-9_]{0,39}$"},nivel:{enum:["completa","basica"]}}},nombre:e(80),descripcion:e(500),icono:{type:"string",pattern:"^[a-z0-9-]{1,40}$"},modulos:{type:"array",minItems:1,maxItems:bi,items:{type:"object",required:["clave","nombre","nombre_plural","campos"],properties:{clave:{type:"string",pattern:"^[a-z][a-z_]{1,40}$"},nombre:e(60),nombre_plural:e(60),articulo:{enum:["un","una",null]},descripcion:e(500),icono:{enum:[...Ts]},campos:{type:"array",maxItems:hc,items:{type:"object",required:["clave","etiqueta","tipo"],properties:{clave:{type:"string"},etiqueta:e(80),tipo:{enum:[...Rs]},formulaNativa:e(4e3),defectoNativo:e(4e3),completarNativo:{type:["object","null"],description:"Variante compilada de una copia nativa personalizada, sin alterar el autocompletado hist\xF3rico."},ajustesNativos:{type:"object",additionalProperties:!1,properties:Object.fromEntries(["contacts","companies"].map(o=>[o,{type:"object",additionalProperties:!1,properties:Object.fromEntries(ys.map(t=>[t,{}]))}]))},siVacio:{type:"string",pattern:"^[a-z][a-z0-9_]{0,40}$",description:"B\xFAsqueda escalar alternativa del mismo tipo, sin cadenas, si el valor es nulo o texto vac\xEDo. Conserva RLS y m\xE1scaras de ambos caminos."},completarDesde:{type:"object",additionalProperties:!1,required:["relacion","campo"],properties:{relacion:{type:"string",pattern:"^[a-z][a-z0-9_]{0,40}$"},campo:{type:"string",pattern:"^[a-z][a-z0-9_.]{0,80}$"},alternativa:{type:"object",additionalProperties:!1,required:["relacion","campo"],properties:{relacion:{type:"string",pattern:"^[a-z][a-z0-9_]{0,40}$"},campo:{type:"string",pattern:"^[a-z][a-z0-9_.]{0,80}$"}}}},description:"Copia al destino vac\xEDo un campo del mismo tipo desde una relaci\xF3n, con permisos de fila y campo. Un origen m\xFAltiple exige relaci\xF3n destino m\xFAltiple; el portal solo copia campos de sus secciones visibles."}}}},paginas:{type:"boolean"},ficha:{type:"object"},impresion:{type:"object"},validaciones:{type:"array"},vistas:{type:"array"},funcionesNativas:{type:"object",additionalProperties:!1,properties:{relacionadas:{type:"array",maxItems:20},siguientes:{type:"array",maxItems:5}}},recurso:{type:"object",description:"Sus registros son recursos (capacidad, persona): ver la gu\xEDa, \xABRecursos y reservas\xBB."},reserva:{type:"object",description:"Cada registro ocupa un recurso (puntual o semanal): ver la gu\xEDa, \xABRecursos y reservas\xBB."},asignacion:{type:"object",description:"\xABAsignar al mejor con hueco\xBB (en la demanda): ver la gu\xEDa, \xABAsignar con cupo y puntos\xBB."},pertenencia:{type:"object",description:"Un m\xF3dulo de pertenencias (demanda, oferta, desde, hasta, correccion_dias): ver la gu\xEDa."},stock:{type:"object",description:"El stock: art\xEDculo (con lotes o series), ubicaci\xF3n, documento que lo mueve (entrada, salida, ajuste, traspaso, recuento, reserva) y punto de pedido (con lo que est\xE1 en camino): ver la gu\xEDa, \xABStock\xBB."},liquidacion:{type:"object",description:"Liquidaciones de comisiones (en el m\xF3dulo de liquidaciones): origen, importe, fecha, agente, reglas con tramos y d\xF3nde va cada cosa: ver la gu\xEDa, \xABLiquidaciones\xBB."},cuota:{type:"object",description:"Cuotas peri\xF3dicas por registro: {proxima: fecha, periodicidad: semanal|quincenal|mensual|bimestral|trimestral|semestral|anual o {campo, valores}, hasta?: fecha}: ver la gu\xEDa, \xABCuotas\xBB."},relacionadas:{type:"array",maxItems:ti,description:"Columnas de OTROS m\xF3dulos en la tabla (se calculan al leer, con lo que ve quien mira): {clave, etiqueta, via, campo} trae un campo del relacionado (editable desde la tabla); {clave, etiqueta, de, via, calculo: recuento|suma|media|minimo|maximo|ultimo, campo?, filtro?} calcula sobre los que citan a este.",items:{type:"object",additionalProperties:!1,required:["clave","etiqueta","via"],properties:{clave:{type:"string",pattern:"^[a-z][a-z0-9_]{0,40}$"},etiqueta:e(80),via:{type:"string"},siVacio:{type:"string",description:"Otra columna de traer escalar del mismo tipo, sin cadenas. Conserva el origen de edici\xF3n por fila."},campo:{type:"string"},de:{type:"string"},calculo:{enum:["recuento","suma","minimo","maximo","ultimo","media"]},filtro:{type:"array",maxItems:5}}}},siguientes:{type:"array",maxItems:ri,description:"Siguientes pasos del proceso: un bot\xF3n que crea el registro siguiente en \xABdestino\xBB (mod_<clave>), enlazado por \xABenlace\xBB (la relaci\xF3n del destino a este) y con \xABcampos\xBB copiados {campo del destino: campo de aqu\xED}.",items:{type:"object",additionalProperties:!1,required:["clave","nombre","destino","enlace"],properties:{clave:{type:"string",pattern:"^[a-z][a-z0-9_]{0,40}$"},nombre:e(60),destino:{type:"string",pattern:"^mod_[a-z][a-z0-9_]{0,40}$"},enlace:{type:"string"},campos:{type:"object",additionalProperties:{type:"string"}}}}},personas:{type:"object",additionalProperties:!1,required:["objeto","tipo","etiqueta","plural","icono","campos"],properties:{objeto:{enum:["contacts","companies"]},tipo:{type:"string",pattern:"^[a-z0-9][a-z0-9-]{0,59}$"},de:{enum:["cliente","proveedor"]},etiqueta:{type:"string",minLength:1,maxLength:60},plural:{type:"string",minLength:1,maxLength:60},icono:{type:"string",pattern:"^[a-z0-9-]{1,40}$"},campos:{type:"object",minProperties:1,additionalProperties:{type:"string"}},configuracion:{type:"object",additionalProperties:!1,description:"Ficha, impresi\xF3n, columnas relacionadas y siguientes por objeto. Claves de origen de la soluci\xF3n, sin ids del espacio.",properties:Object.fromEntries(["contacts","companies"].map(o=>[o,{type:"object",additionalProperties:!1,properties:Object.fromEntries(["ficha","impresion","relacionadas","siguientes"].map(t=>[t,{type:t==="relacionadas"||t==="siguientes"?["array","null"]:["object","null"]}]))}]))},alternativa:{type:"object",additionalProperties:!1,required:["objeto","campos"],description:"Segundo destino separado. El principal es contacts; cada relaci\xF3n se expande en su clave de Persona y <clave>_empresa. No es una relaci\xF3n polim\xF3rfica.",properties:{objeto:{const:"companies"},campos:{type:"object",minProperties:1,additionalProperties:{type:"string"}},conversiones:{type:"object",additionalProperties:{type:"object",additionalProperties:{type:"string"}}}}},clasificacion:{type:"object",additionalProperties:!1,required:["campo","valores"],description:"Todas las opciones de una selecci\xF3n, o true/false de un booleano, a contacts/companies. vacio decide expl\xEDcitamente el valor ausente. Nunca se adivina por nombre o identificador.",properties:{campo:{type:"string"},valores:{type:"object",minProperties:2,additionalProperties:{enum:["contacts","companies"]}},vacio:{enum:["contacts","companies"]},formas:{type:"object",description:"Opciones de Empresa a claves de legalForms. Conserva etiqueta y color de la opci\xF3n hist\xF3rica, sin pisar listas existentes.",additionalProperties:{type:"string",pattern:"^[a-z0-9][a-z0-9-]{0,59}$"}},etiquetas:{type:"array",uniqueItems:!0,description:"Opciones de Persona que conservan su significado como etiqueta, con nombre y color de la opci\xF3n hist\xF3rica.",items:{type:"string"}}}},conversiones:{type:"object",description:"Mapa completo e inyectivo de opciones hist\xF3ricas a claves nativas de sector o forma jur\xEDdica. Conserva etiquetas/colores del campo. No clasifica objetos.",additionalProperties:{type:"object",minProperties:1,maxProperties:100,additionalProperties:{type:"string",minLength:1,maxLength:80}}}}}}}},vistasTabla:{type:"array",maxItems:Ks,items:{type:"object",additionalProperties:!1,required:["objeto","nombre","disposicion"],properties:{objeto:{type:"string",pattern:"^(contacts|companies|mod_[a-z][a-z0-9_]{0,40})$"},tipoContacto:{type:"string",pattern:"^[a-z0-9][a-z0-9-]{0,59}$"},nombre:e(60),config:{type:"object"},disposicion:{type:["object","null"]}}},description:"Vistas por objeto/tipo con preferencias y widgets. Un m\xF3dulo omitido con dos destinos crea una vista por objeto. Actualizaci\xF3n aditiva sin reponer bajas ni pisar personalizaciones."},separadores:{type:"array",maxItems:oc,items:{type:"object",additionalProperties:!1,required:["antes"],properties:{antes:{type:["string","null"],description:"Clave de m\xF3dulo de la soluci\xF3n, o null al final. Si se omite el m\xF3dulo, se conserva delante del siguiente m\xF3dulo real."},titulo:{type:["string","null"],maxLength:40}}}},paneles:{type:"array",maxItems:Ys,description:"Paneles de m\xE9tricas (n\xFAmero, barras, barras horizontales/apiladas/agrupadas, l\xEDneas, \xE1rea, varias l\xEDneas, dona, embudo, medidor con meta, tendencia, tabla, tabla din\xE1mica, mapa de calor; c\xE1lculos de recuento, suma, media, min, max, mediana, % del total, acumulado, tasa de conversi\xF3n, media por)."},automatizaciones:{type:"array",maxItems:Zs,description:"Se instalan APAGADAS: una persona las revisa y las enciende."},ejemplos:{type:"object",description:`Datos de ejemplo por clave de m\xF3dulo (hasta ${vi} cada uno).`,additionalProperties:{type:"array",maxItems:vi}},informes:{type:"array",maxItems:Fr,description:"Informes de An\xE1lisis que se crean al publicar (de equipo).",items:{type:"object",additionalProperties:!1,required:["nombre","definicion"],properties:{nombre:e(80),descripcion:e(500),definicion:{type:"object"}}}},principal:{type:"string",description:"La clave de su m\xF3dulo PRINCIPAL (ah\xED se abre el importador al acabar la bienvenida)."},mensajes:{type:"array",maxItems:hi,description:"Plantillas de mensaje (WhatsApp o correo) de sus m\xF3dulos (mod_<clave>) o de contacts, companies y deals.",items:{type:"object",additionalProperties:!1,required:["recurso","canal","nombre","texto"],properties:{recurso:{type:"string"},tipoContacto:{type:"string",pattern:"^[a-z0-9][a-z0-9-]{0,59}$",description:"\xC1mbito opcional de una plantilla de Personas o Empresas."},canal:{enum:["whatsapp","correo"]},nombre:e(80),asunto:e(300),texto:e(5e3)}}},papeles:{type:"array",maxItems:ec,description:"Papeles personalizados que se crean al publicar: a partir de uno de serie, con permisos de la matriz o de sus m\xF3dulos (mod_<clave>.ver|editar|borrar|exportar). Nunca gestionar miembros ni la configuraci\xF3n.",items:{type:"object",additionalProperties:!1,required:["nombre","base"],properties:{nombre:e(40),base:{enum:["administrador","miembro","lectura"]},permisos:{type:"object",additionalProperties:{enum:["si","no","suyos"]}}}}},portales:{type:"array",maxItems:tc,description:"PORTALES (P15): personas de fuera (clientes, propietarios, hu\xE9spedes, familias, trabajadores) que entran con su usuario y ven SOLO lo alcanzable desde su ficha. Se crean al publicar, DESACTIVADOS (los activa una persona). Ver la gu\xEDa, \xABPortal\xBB.",items:{type:"object",additionalProperties:!1,required:["clave","nombre","personas","secciones"],properties:{clave:{type:"string",pattern:"^[a-z][a-z0-9_]{0,30}$"},nombre:e(80),personas:{oneOf:[{type:"object",additionalProperties:!1,required:["modulo","correo"],properties:{modulo:{type:"string",description:"mod_<clave> del m\xF3dulo de personas."},correo:{type:"string",description:"Su campo de correo (tipo correo)."}}},{type:"object",additionalProperties:!1,required:["objeto"],properties:{objeto:{enum:["contacts","companies"]},tipo:{type:"string",pattern:"^[a-z0-9][a-z0-9-]{0,59}$"}}}]},secciones:{type:"array",minItems:1,maxItems:10,items:{type:"object",additionalProperties:!1,required:["clave","titulo","campos"],properties:{clave:{type:"string",pattern:"^[a-z][a-z0-9_]{0,30}$"},titulo:e(60),modulo:{type:"string",description:"mod_<clave> (opcional: lo dice el camino)."},camino:{type:"array",maxItems:2,description:"Desde la ficha de la persona, cada paso por una relaci\xF3n: {modulo: el que TIENE el campo, campo}. Vac\xEDo: su propia ficha.",items:{type:"object",additionalProperties:!1,required:["modulo","campo"],properties:{modulo:{type:"string"},campo:{type:"string"}}}},campos:{type:"array",items:{type:"string"},maxItems:40,description:"La LISTA BLANCA de lo que se ve (nunca un secreto, un bot\xF3n ni una b\xFAsqueda)."},subtablas:{type:"object",additionalProperties:{type:"array",items:{type:"string"}}},crear:{type:"object",additionalProperties:!1,required:["campos"],properties:{campos:{type:"array",items:{type:"string"}}}},editar:{type:"object",additionalProperties:!1,required:["campos"],properties:{campos:{type:"array",items:{type:"string"}},estado:{type:"object",additionalProperties:!1,required:["campo","valores"],properties:{campo:{type:"string"},valores:{type:"array",items:{type:"string"}}}}}},adjuntar:{type:"object",additionalProperties:!1,required:["campo"],properties:{campo:{type:"string"},tipos:{type:"array",items:{enum:["image/png","image/jpeg","image/webp","image/gif","application/pdf"]}},max_mb:{type:"integer",minimum:1,maximum:25}}},comentar:{type:"boolean"}}}},textos:{type:"object",additionalProperties:!1,properties:{titulo:e(80),bienvenida:e(2e3),pie:e(500)}},marca:{type:"object",additionalProperties:!1,properties:{color:{type:"string",pattern:"^#[0-9a-fA-F]{6}$"}}}}}},proyectos:{type:"array",items:{type:"object",required:["clave","nombre"],properties:{clave:{type:"string",pattern:"^[A-Z0-9]{2,10}$"},nombre:e(100),descripcion:e(500),color:{type:"string"},icono:{type:"string"},columnas:{type:"array"}}}},plantillas_proyecto:{type:"array",items:{type:"object",required:["nombre"],properties:{nombre:e(200),clave_sugerida:{type:"string",pattern:"^[A-Z0-9]{2,10}$"},descripcion:e(500),categoria:e(50),color:{type:"string"},icono:{type:"string"},columnas:{type:"array"},tareas:{type:"array"}}}}},"x-forgenex":{tamanoMaximoBytes:wi,topeCampos:hc}}}async function gc(e){let[o,...t]=e,n=await Gh(o,t);if(n!==null)return n;let r=t.includes("--json"),a=t.filter(s=>s!=="--json");if(o==="validar"&&a.length===0&&a.push("."),o==="version")return console.log(`${xt} v${tr}`),0;if(o==="esquema")return console.log(JSON.stringify(Yv(),null,2)),0;if(o==="esquema-extension")return console.log(JSON.stringify(Xv(),null,2)),0;if((o==="validar"||o==="previsualizar")&&a.length){let s=a.map(l=>{let d;try{Uv(l).isDirectory()?(Ao(l),d=Hh(Vv(l,"extension.json"),"utf8")):d=Hh(l,"utf8")}catch(u){return{archivo:l,ok:!1,error:u instanceof Error?u.message:String(u)}}return Qv(d)?Gv(l,d):Jv(l,d)});if(r)console.log(JSON.stringify(s.map(l=>l.ok?"extension"in l?{archivo:l.archivo,ok:!0,extension:l.extension}:{archivo:l.archivo,ok:!0,resumen:Xh(l.solucion)}:l)));else for(let l of s){if(!l.ok){console.log(`\u2717 ${l.archivo}: ${l.error}`);continue}if("extension"in l){let d=l.extension;console.log(`\u2713 ${l.archivo}: app \xAB${d.nombre}\xBB ${d.version} (${d.id})`);for(let[f,h]of Object.entries(d.permisos.modulos))console.log(` \xB7 pide ${f}: ${h.join(", ")}`);d.permisos.almacen&&console.log(" \xB7 pide su almac\xE9n");let u=[...new Set(d.montajes.filter(f=>!Hr.has(f.punto)).map(f=>`montajes.${f.punto}`))];for(let f of d.funciones)console.log(` \xB7 funci\xF3n ${f.nombre} (${f.disparador.tipo}${f.disparador.evento?`: ${f.disparador.evento}`:f.disparador.cron?`: ${f.disparador.cron}`:""})`);for(let f of d.permisos.red_hacia)console.log(` \xB7 se conecta a ${f}`);let p=[...u,d.servidor&&"servidor"].filter(Boolean);p.length&&console.log(` (v\xE1lidos, pero a\xFAn no se ejecutan: ${p.join(", ")})`);continue}if(console.log(`\u2713 ${l.archivo}: \xAB${l.solucion.nombre}\xBB, ${l.solucion.modulos.length} m\xF3dulos`),o==="previsualizar"){let d=Xh(l.solucion);for(let u of d.modulos)console.log(` \xB7 ${u.nombre} (${u.clave}): ${u.campos} campos${u.relaciones.length?`, \u2192 ${u.relaciones.join(", ")}`:""}${u.vistas?`, ${u.vistas} vistas`:""}`);console.log(` paneles: ${d.paneles} \xB7 automatizaciones: ${d.automatizaciones} (se instalan apagadas)`)}}return s.every(l=>l.ok)?0:1}return console.log("Uso: forgenex crear-app <nombre> [--plantilla html|react] \xB7 validar [directorio|archivo.json \u2026] [--json] \xB7 dev --espacio <id> \xB7 empaquetar \xB7 instalar --espacio <id> (--app <id> | --paquete <archivo.fgx>) \xB7 publicar --espacio <id> --paquete <archivo.fgx> \xB7 claves crear \xB7 registrar-clave \xB7 revocar-clave \xB7 previsualizar \xB7 esquema \xB7 esquema-extension \xB7 version"),2}process.argv[1]?.endsWith("cli.ts")&&gc(process.argv.slice(2)).then(e=>{process.exitCode=e}).catch(e=>{console.error(e instanceof Error?e.message:String(e)),process.exitCode=1});gc(process.argv.slice(2)).then(e=>{process.exitCode=e}).catch(e=>{console.error(e instanceof Error?e.message:String(e)),process.exitCode=1});
|
|
43
|
+
Recarga al guardar. Funciones: crm.pedir("desarrollo.funcion", { nombre, entrada }, { metodo: "POST", idempotencia: crypto.randomUUID() }).`)}async function yy(e){let o=[],t=0;for await(let r of e){if(t+=r.length,t>D.webhookBytes)throw new Error("Entrada demasiado grande.");o.push(r)}return JSON.parse(Buffer.concat(o).toString("utf8")||"null")}var ag=m(()=>{Yh();pr();tg();xc();Cc();qi()});import{generateKeyPairSync as _y,createPublicKey as sg}from"node:crypto";import{mkdirSync as Ny,readFileSync as en,writeFileSync as cg}from"node:fs";import{homedir as $y}from"node:os";import{join as xy,resolve as lg}from"node:path";function Ue(e,o){let t=e.indexOf(`--${o}`);if(t<0)return;let r=e[t+1];if(!r||r.startsWith("--"))throw new Error(`Falta --${o}.`);return r}function ug(e){let o=new URL(e);if(o.username||o.password||o.protocol!=="https:"&&!(o.protocol==="http:"&&["localhost","127.0.0.1"].includes(o.hostname)))throw new Error("La API debe ser https (o http en loopback para pruebas).");return o.origin}async function ur(e,o,t,r){let n=await fetch(`${ug(e)}${t}`,{method:"POST",redirect:"error",headers:{authorization:`Bearer ${o}`,"content-type":"application/json"},body:JSON.stringify(r)}),a=await n.json();if(!n.ok)throw a.error?.datos?.informe&&console.log(Oc(a.error.datos.informe)),new Error(`${n.status}: ${a.error?.mensaje??"El CRM rechaz\xF3 la petici\xF3n."}`);return a.data}function Oc(e){let o=[e.ok?`Revisi\xF3n autom\xE1tica: PASA (${e.avisos} aviso(s)).`:`Revisi\xF3n autom\xE1tica: NO PASA (${e.fallas} punto(s) que corregir).`];for(let t of e.puntos){o.push(`${Cy[t.estado]} ${t.titulo}`);for(let r of t.detalles)o.push(` ${r}`)}return o.join(`
|
|
44
|
+
`)}function jc(e){return lg(Ue(e,"clave-firma")??process.env.FORGENEX_CLAVE_FIRMA??xy($y(),".forgenex/desarrollador.pem"))}function dr(e){let o=Ue(e,"api")??process.env.FORGENEX_API,t=process.env.FORGENEX_CLAVE_DESARROLLADOR,r=Number(Ue(e,"espacio"));if(!o||!t||!Number.isSafeInteger(r)||r<1)throw new Error("Configura FORGENEX_API, FORGENEX_CLAVE_DESARROLLADOR y --espacio <id>.");return{api:ug(o),clave:t,espacio:r}}async function dg(e,o){if(e==="crear-app"||e==="crear-extension")return console.log(Bh(o[0]??"",Ue(o,"plantilla"))),0;if(e==="claves"&&o[0]==="crear"){let t=jc(o);Ny(lg(t,".."),{recursive:!0,mode:448});let r=_y("ed25519");return cg(t,r.privateKey.export({type:"pkcs8",format:"pem"}),{flag:"wx",mode:384}),cg(`${t}.pub`,r.publicKey.export({type:"spki",format:"pem"}),{flag:"wx",mode:420}),console.log(`Clave privada: ${t}
|
|
45
|
+
P\xFAblica: ${t}.pub`),0}if(e==="registrar-clave"){let t=dr(o),r=en(jc(o),"utf8");return console.log(JSON.stringify(await ur(t.api,t.clave,"/api/desarrollador/claves",{espacio:t.espacio,publica:sg(r).export({type:"spki",format:"pem"}).toString()}))),0}if(e==="revocar-clave"){let t=dr(o),r=Ue(o,"huella");if(!r||!/^[a-f0-9]{64}$/.test(r))throw new Error("Falta --huella <id de clave p\xFAblica>.");return console.log(JSON.stringify(await ur(t.api,t.clave,"/api/desarrollador/revocar-clave",{espacio:t.espacio,id:r}))),0}if(e==="empaquetar"){let t=en(jc(o),"utf8");return console.log(await Uh(process.cwd(),t,sg(t).export({type:"spki",format:"pem"}).toString())),0}if(e==="instalar"){let t=dr(o),r=Ue(o,"paquete"),n=Ue(o,"app"),a=Ue(o,"version");if(!r&&!n)throw new Error("Falta --app <id de la app publicada> o --paquete <archivo.fgx>.");let s=n?{espacio:t.espacio,app:n,version:a}:{espacio:t.espacio,paquete:en(r).toString("base64")},c=await ur(t.api,t.clave,"/api/desarrollador/instalar",s);return console.log(JSON.stringify(c)),c?.pendiente_permisos!==!1&&console.log("El administrador debe aceptar los permisos en Ajustes \u203A Apps."),0}if(e==="revisar"){let t=Ue(o,"paquete"),r;if(t){let n=en(t),a=Gr(n),s=a.get("extension.json");if(!s)throw new Error("Al paquete le falta \xABextension.json\xBB.");r=yc({ext:tt(s.toString("utf8")),recursos:a,firmada:a.has(Hr),bytes:n.length,enLocal:!0})}else{let n=process.cwd();await lr(n);let a=gc(n),s=tt(a.get("extension.json").toString("utf8"));r=yc({ext:s,recursos:a,firmada:!0,bytes:[...a.values()].reduce((c,d)=>c+d.length,0),enLocal:!0})}return console.log(o.includes("--json")?JSON.stringify(r,null,2):Oc(r)),r.ok?0:1}if(e==="publicar"){let t=dr(o),r=Ue(o,"paquete"),n=o.includes("--tienda");if(!r)throw new Error("Falta --paquete <archivo.fgx> (lo hace `forgenex empaquetar`).");let a=await ur(t.api,t.clave,"/api/desarrollador/publicar",{espacio:t.espacio,paquete:en(r).toString("base64"),...n?{tienda:!0}:{}});console.log(JSON.stringify({...a,tienda:a.tienda?{estado:a.tienda.estado,humana:a.tienda.humana,porcentaje:a.tienda.porcentaje}:void 0}));let s=c=>a.espacios.filter(d=>d.resultado===c).length;return console.log(`Publicada ${a.ext_id} ${a.version} en tus apps.`),a.tienda&&(console.log(Oc(a.tienda.informe)),console.log(a.tienda.estado==="aprobada"?`\xB7 En la tienda: publicada sola (no pide m\xE1s que la versi\xF3n anterior), al ${a.tienda.porcentaje} % de los espacios; sube al 100 % en 24 h si no da errores.`:`\xB7 En la tienda: en revisi\xF3n (${a.tienda.humana.map(c=>({primera:"es la primera versi\xF3n",permisos:"pide permisos nuevos",red:"se conecta a un dominio nuevo",publica:"trae una p\xE1gina p\xFAblica nueva",todas:"por ahora se revisa cada versi\xF3n"})[c]??c).join(", ")}). Te avisamos al decidir; el estado sale en el panel, Perfil \u203A Desarrollador.`)),s("activa")&&console.log(`\xB7 Actualizada sola en ${s("activa")} espacio(s): no pide m\xE1s permisos.`),s("pendiente_permisos")&&console.log(`\xB7 En ${s("pendiente_permisos")} espacio(s) pide m\xE1s permisos: su administrador los acepta en Ajustes \u203A Apps.`),s("a_mano")&&console.log(`\xB7 En ${s("a_mano")} espacio(s) no se aplica sola (cambian sus m\xF3dulos, o lo instalado all\xED no sali\xF3 de \xABMis apps\xBB): actual\xEDzala con \`forgenex instalar --app ${a.ext_id} --espacio <id>\`.`),s("modo_desarrollador")&&console.log(`\xB7 En ${s("modo_desarrollador")} espacio(s) el modo desarrollador est\xE1 apagado: no se ha tocado.`),s("error")&&console.log(`\xB7 En ${s("error")} espacio(s) no se ha podido actualizar: prueba con \`forgenex instalar --app\`.`),s("cliente_ajeno")&&console.log(`\xB7 En ${s("cliente_ajeno")} espacio(s) no se ha tocado: en ForgeNEX ya no son tuyos ni de un cliente tuyo.`),s("panel_no_disponible")&&console.log(`\xB7 En ${s("panel_no_disponible")} espacio(s) no se ha tocado porque no se ha podido comprobar con ForgeNEX: vuelve a publicar en un momento o usa \`forgenex instalar --app\`.`),0}if(e==="dev"){let{iniciarDev:t}=await Promise.resolve().then(()=>(ag(),ig));return await t(o),0}return null}var Cy,Cc=m(()=>{qi();kt();Ei();mc();Xh();Cy={ok:"\u2713",aviso:"!",falla:"\u2717"}});Cc();qi();Vr();As();dc();ec();hi();Ks();kt();import{readFileSync as pg,statSync as jy}from"node:fs";import{join as Oy}from"node:path";var Sc=200;function Sy(e,o){try{return{archivo:e,ok:!0,solucion:Ai(o,{topeCampos:Sc})}}catch(t){return{archivo:e,ok:!1,error:t instanceof Error?t.message:String(t)}}}function Ay(e){try{let o=JSON.parse(e);return typeof o=="object"&&o!==null&&o.formato===ot}catch{return!1}}function Ey(e,o){try{return{archivo:e,ok:!0,extension:tt(o)}}catch(t){return{archivo:e,ok:!1,error:t instanceof Error?t.message:String(t)}}}function qy(){let e=r=>r.length>1?`${r.slice(0,-1).join(", ")} y ${r.at(-1)}`:r[0]??"",o=Rt.filter(r=>sn.has(r)).map(r=>`\xAB${r}\xBB`),t=Rt.filter(r=>!sn.has(r)).map(r=>`\xAB${r}\xBB`);return`D\xF3nde se cuelga su interfaz, en una caja aislada (iframe sin origen). Se pintan ${e(o)}${t.length?`; ${e(t)} se validan, pero todav\xEDa no se pintan`:""}. \xABpublica\xBB es la p\xE1gina sin sesi\xF3n (/app/<enlace>), con sus \xABfunciones\xBB.`}function Ry(){let e=a=>({type:"string",maxLength:a}),o={type:"string",pattern:"^(\\*\\.)?([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\\.)+[a-z]{2,63}$"},t={type:"string",maxLength:200,pattern:"^[A-Za-z0-9_./-]{1,200}$",description:"Un fichero del paquete (relativo, sin \xAB..\xBB)."},r={type:"string",pattern:"^[a-z][a-z0-9_]{0,40}$"},n="Se valida, pero todav\xEDa no se ejecuta (llega en una fase siguiente de las apps).";return{$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://forgenex.com/sdk/extension-v1.schema.json",title:"App del CRM ForgeNEX",description:`Formato \xAB${ot}\xBB, versi\xF3n ${an}. Valida la forma; \xABforgenex-sdk validar\xBB valida todo (el mismo validador que el CRM).`,type:"object",additionalProperties:!1,required:["formato","formato_version","id","nombre","version","autor"],properties:{$schema:{type:"string"},formato:{const:ot},formato_version:{type:"integer",minimum:1,maximum:an,description:"Versi\xF3n del FORMATO (no de la app)."},id:{type:"string",maxLength:200,pattern:"^[a-z][a-z0-9-]{0,62}(\\.[a-z0-9][a-z0-9-]{0,62}){1,6}$",description:"Dominio inverso: com.tuempresa.mi-extension. No cambia nunca."},nombre:e(80),descripcion:e(500),version:{type:"string",pattern:"^(0|[1-9][0-9]{0,5})\\.(0|[1-9][0-9]{0,5})\\.(0|[1-9][0-9]{0,5})(-[0-9a-z.-]{1,30})?$",description:"La versi\xF3n de la app (semver)."},autor:{oneOf:[e(120),{type:"object",additionalProperties:!1,required:["nombre"],properties:{nombre:e(120),web:{type:"string",format:"uri",description:"https"}}}]},icono:{type:"string",pattern:"^[a-z0-9-]{1,40}$",description:"Un icono de lucide."},idiomas:{type:"array",maxItems:30,items:{type:"string",pattern:"^[a-z]{2,3}(-[A-Z]{2})?$"}},compatible_crm:{type:"string",maxLength:80,description:"Rango de versiones del CRM: \xAB>=1.6.0-284\xBB o \xAB>=1.6.0-284 <2.0.0\xBB."},licencia:e(40),politica_datos:{type:"string",format:"uri",description:"https: tu pol\xEDtica de datos. Obligatoria para entrar en la tienda si la app usa red (permisos.red_hacia)."},depende_de:{type:"array",maxItems:20,description:"Otras apps que tienen que estar instaladas.",items:{oneOf:[{type:"string"},{type:"object",additionalProperties:!1,required:["id"],properties:{id:{type:"string"},version:{type:"string"}}}]}},ofrece:{type:"array",maxItems:20,items:{type:"string",pattern:"^[a-z][a-z0-9_.-]{0,79}$"},description:`Contratos con nombre que ofrece a otras apps. ${n}`},usa:{type:"array",maxItems:20,items:{type:"string",pattern:"^[a-z][a-z0-9_.-]{0,79}$"},description:`Contratos que usa de otras. ${n}`},solucion:{...t,description:"El fichero de la soluci\xF3n del paquete (\xABsolucion.json\xBB, formato forgenex.solucion): sus m\xF3dulos se instalan como copia."},montajes:{type:"array",maxItems:20,description:qy(),items:{type:"object",additionalProperties:!1,required:["id","punto","entrada","titulo"],properties:{id:{type:"string",pattern:"^[a-z][a-z0-9_-]{0,40}$"},punto:{enum:[...Rt]},entrada:t,titulo:e(60),icono:{type:"string"},modulo:{type:"string",description:`Solo en ${[...fr].join(", ")}: el m\xF3dulo donde se cuelga (permisos.modulos tiene que pedir verlo).`},permiso:{type:"string",description:"<m\xF3dulo>.<operaci\xF3n>, dentro de \xABpermisos\xBB. No en \xABpublica\xBB."},funciones:{type:"array",maxItems:10,uniqueItems:!0,items:r,description:"Solo en \xABpublica\xBB: las funciones (de disparador \xABpublica\xBB) que su p\xE1gina puede llamar."}},allOf:[{if:{properties:{punto:{const:"publica"}},required:["punto"]},then:{not:{required:["permiso"]}},else:{not:{required:["funciones"]}}},{if:{properties:{punto:{enum:[...fr]}},required:["punto"]},then:{required:["modulo"]},else:{not:{required:["modulo"]}}}]}},funciones:{type:"array",maxItems:20,description:"Funciones JS que corren aisladas en el servidor del CRM (QuickJS), con `crm` (la API v1 recortada a lo aceptado) y `fetch` (solo a su \xABred\xBB aceptada). Las de \xABcalculo\xBB se llaman desde su interfaz por extensiones.calcular, solo con lecturas del CRM y sin red.",items:{type:"object",additionalProperties:!1,required:["nombre","entrada","disparador"],properties:{nombre:r,titulo:e(80),descripcion:e(300),entrada:{...t,description:"Su fichero .js del paquete: `export default async function (entrada, contexto) { \u2026 }`."},disparador:{type:"object",additionalProperties:!1,required:["tipo"],description:"evento (con \xABevento\xBB, que est\xE9 en permisos.eventos), programada (con \xABcron\xBB de 5 campos, como poco cada 15 min, hora de Madrid), webhook, automatizacion (un paso del dise\xF1ador) o calculo.",properties:{tipo:{enum:[...rn]},evento:{type:"string"},cron:{type:"string"}}},tope:{type:"object",additionalProperties:!1,description:"Por llamada. Por defecto, 5000 ms y 64 MB.",properties:{ms:{type:"integer",minimum:100,maximum:3e4},memoria_mb:{type:"integer",minimum:16,maximum:256}}},red:{type:"array",maxItems:10,items:o,description:"Los dominios a los que llama (dentro de permisos.red_hacia). Solo https y sin seguir redirecciones."},parametros:{type:"object",maxProperties:20,description:"Solo en las de \xABautomatizacion\xBB: su entrada en el paso del dise\xF1ador.",additionalProperties:{type:"object",additionalProperties:!1,required:["tipo","desc"],properties:{tipo:{enum:["texto","numero","si_no","fecha"]},desc:e(200),requerido:{type:"boolean"}}}},salida:{type:"array",maxItems:30,description:"Las claves que devuelve (el paso deja guardar cada una en un campo). Con { clave, titulo }, el dise\xF1ador ense\xF1a el t\xEDtulo (\xABD\xEDas h\xE1biles\xBB).",items:{anyOf:[r,{type:"object",additionalProperties:!1,required:["clave"],properties:{clave:r,titulo:e(60)}}]}}}}},servidor:{type:"object",additionalProperties:!1,required:["url"],description:`El servidor propio del desarrollador. ${n}`,properties:{url:{type:"string",format:"uri"},webhooks:{type:"array",items:{type:"string"}}}},herramientas_ia:{type:"array",maxItems:20,description:"Herramientas para Pix (1.9.0). Cada una apunta a una funci\xF3n de disparador \xABherramienta\xBB, que recibe su \xABentrada\xBB y devuelve solo las claves de su \xABsalida\xBB. Corre como la app recortada a la persona que habla con Pix. \xABescribe\xBB: la persona confirma antes; sin \xE9l, si intenta escribir, tambi\xE9n. \xABpermiso\xBB (\xABvehiculos.ver\xBB, dentro de permisos.modulos): quien no lo tiene en su papel no la ve; sin \xE9l, solo la ve quien puede ver todos los m\xF3dulos que la app tiene aceptados.",items:{type:"object",additionalProperties:!1,required:["nombre","descripcion","riesgo","funcion"],properties:{nombre:{type:"string",pattern:"^[a-z][a-z0-9_]{2,40}$"},descripcion:e(500),entrada:{type:"object",maxProperties:20,description:"Lo que Pix (o el MCP) le pasa: { campo: { tipo, desc, requerido? } }, como los \xABparametros\xBB de una funci\xF3n. Tipos: texto, numero, si_no o fecha (en el MCP salen como string, number, boolean y string con fecha). No es un JSON Schema.",additionalProperties:{type:"object",additionalProperties:!1,required:["tipo","desc"],properties:{tipo:{enum:["texto","numero","si_no","fecha"]},desc:e(200),requerido:{type:"boolean"}}}},salida:{type:"array",items:r},riesgo:{enum:["bajo","medio","alto"]},funcion:r,escribe:{type:"boolean"},permiso:{type:"string",maxLength:80}}}},ajustes:{type:"array",maxItems:40,description:"Ajustes (1.13.0): un formulario en Ajustes \u203A Apps \u203A la app, con valores POR ESPACIO (cada instalaci\xF3n los suyos; al instalar, vac\xEDos). La app los lee con la operaci\xF3n v1 `app.ajustes` y sus funciones en `contexto.ajustes`. \xABrequerido\xBB marca el campo en el formulario, pero la app se activa igual sin \xE9l: compru\xE9balo en la funci\xF3n. \xABopcion\xBB lleva \xABopciones\xBB: [{ valor, etiqueta }]; el valor de \xABmodulo\xBB es la clave de un m\xF3dulo del espacio y el de \xABcampo\xBB, \xABmodulo.campo\xBB.",items:{type:"object",additionalProperties:!1,required:["clave","etiqueta","tipo"],properties:{clave:r,etiqueta:e(80),tipo:{enum:[...nn]},opciones:{type:"array",items:{type:"object",additionalProperties:!1,required:["valor","etiqueta"],properties:{valor:e(60),etiqueta:e(80)}}},requerido:{type:"boolean"}}}},secretos:{type:"array",maxItems:10,description:"Secretos (1.13.0): claves de terceros que pone el administrador de CADA espacio en Ajustes \u203A Apps \u203A la app; van cifradas y SOLO las recibe una funci\xF3n de servidor mientras corre (`contexto.secretos`). Nunca la interfaz, la v1, el MCP ni una exportaci\xF3n.",items:{type:"object",additionalProperties:!1,required:["clave","etiqueta"],properties:{clave:r,etiqueta:e(80),descripcion:e(300)}}},permisos:{type:"object",additionalProperties:!1,description:"Lo que pide. El administrador lo ve y lo acepta al instalar; la clave de la app nunca puede m\xE1s (ni m\xE1s que el papel de su responsable).",properties:{modulos:{type:"object",maxProperties:40,description:`M\xF3dulo \u2192 operaciones. De serie: ${Object.entries(Io).map(([a,s])=>`${a} (${s.ops.join(", ")})`).join("; ")}. Los de su soluci\xF3n o del espacio, por su clave: ${mr.join(", ")}.`,additionalProperties:{type:"array",minItems:1,maxItems:4,uniqueItems:!0,items:{enum:[...mr]}}},almacen:{type:"boolean",description:"Guardar sus datos internos (clave-valor JSON) en el almac\xE9n de la app."},red_hacia:{type:"array",maxItems:20,items:o,description:"Los dominios a los que pueden conectarse sus funciones (\xAB*.ejemplo.com\xBB cubre sus subdominios). El administrador acepta cada uno."},eventos:{type:"array",maxItems:40,items:{type:"string"},description:"Los eventos del CRM de los que se entera (registro.creado, registro.actualizado\u2026). El administrador acepta cada uno."},archivos:{type:"array",maxItems:2,uniqueItems:!0,items:{enum:["leer","escribir"]},description:"1.17.0: los archivos del almacenamiento del espacio que la persona ELIGE con archivos.elegir() (el explorador del CRM). \xABleer\xBB: verlos (archivos.leer); \xABescribir\xBB (pide tambi\xE9n \xABleer\xBB): vincularlos a una ficha (archivos.vincular). Nunca ve el \xE1rbol ni recibe tokens de OneDrive o Google."}}}},"x-forgenex":{tamanoMaximoBytes:tn}}}function mg(e){return{nombre:e.nombre,plantilla:e.plantilla??null,modulos:e.modulos.map(o=>({clave:o.clave,nombre:o.nombre_plural,campos:o.campos.length,relaciones:o.campos.filter(t=>t.tipo==="relacion").map(t=>t.relacion??"").filter(Boolean),vistas:o.vistas?.length??0})),paneles:e.paneles?.length??0,automatizaciones:e.automatizaciones?.length??0,informes:e.informes?.length??0,mensajes:e.mensajes?.length??0,papeles:(e.papeles??[]).map(o=>`${o.nombre} (${o.base})`),portales:(e.portales??[]).map(o=>String(o.nombre??o.clave??"")),principal:e.principal??null,ejemplos:Object.fromEntries(Object.entries(e.ejemplos??{}).map(([o,t])=>[o,t.length]))}}function ky(){let e=o=>({type:"string",maxLength:o});return{$schema:"https://json-schema.org/draft/2020-12/schema",$id:`https://forgenex.com/sdk/solucion-v${cr}.schema.json`,title:"Soluci\xF3n del CRM ForgeNEX",description:`Formato \xAB${Et}\xBB, versi\xF3n ${cr}. Valida la forma; \xABforgenex-sdk validar\xBB valida todo (el mismo validador que el CRM).`,type:"object",additionalProperties:!1,required:["formato","version","nombre","modulos"],properties:{formato:{const:Et},version:{type:"integer",minimum:1,maximum:cr,description:"Versi\xF3n del FORMATO (el CRM lee esta y las anteriores)."},plantilla:{type:"object",additionalProperties:!1,required:["id","version","sector"],properties:{id:{type:"string",pattern:"^[a-z][a-z0-9_]{0,59}$"},version:{type:"integer",minimum:1},sector:{type:"string",pattern:"^[a-z][a-z0-9_]{0,39}$"},nivel:{enum:["completa","basica"]}}},nombre:e(80),descripcion:e(500),icono:{type:"string",pattern:"^[a-z0-9-]{1,40}$"},modulos:{type:"array",minItems:1,maxItems:ji,items:{type:"object",required:["clave","nombre","nombre_plural","campos"],properties:{clave:{type:"string",pattern:"^[a-z][a-z_]{1,40}$"},nombre:e(60),nombre_plural:e(60),articulo:{enum:["un","una",null]},descripcion:e(500),icono:{enum:[...Bs]},campos:{type:"array",maxItems:Sc,items:{type:"object",required:["clave","etiqueta","tipo"],properties:{clave:{type:"string"},etiqueta:e(80),tipo:{enum:[...Fs]},formulaNativa:e(4e3),defectoNativo:e(4e3),completarNativo:{type:["object","null"],description:"Variante compilada de una copia nativa personalizada, sin alterar el autocompletado hist\xF3rico."},ajustesNativos:{type:"object",additionalProperties:!1,properties:Object.fromEntries(["contacts","companies"].map(o=>[o,{type:"object",additionalProperties:!1,properties:Object.fromEntries(Ss.map(t=>[t,{}]))}]))},siVacio:{type:"string",pattern:"^[a-z][a-z0-9_]{0,40}$",description:"B\xFAsqueda escalar alternativa del mismo tipo, sin cadenas, si el valor es nulo o texto vac\xEDo. Conserva RLS y m\xE1scaras de ambos caminos."},completarDesde:{type:"object",additionalProperties:!1,required:["relacion","campo"],properties:{relacion:{type:"string",pattern:"^[a-z][a-z0-9_]{0,40}$"},campo:{type:"string",pattern:"^[a-z][a-z0-9_.]{0,80}$"},alternativa:{type:"object",additionalProperties:!1,required:["relacion","campo"],properties:{relacion:{type:"string",pattern:"^[a-z][a-z0-9_]{0,40}$"},campo:{type:"string",pattern:"^[a-z][a-z0-9_.]{0,80}$"}}}},description:"Copia al destino vac\xEDo un campo del mismo tipo desde una relaci\xF3n, con permisos de fila y campo. Un origen m\xFAltiple exige relaci\xF3n destino m\xFAltiple; el portal solo copia campos de sus secciones visibles."}}}},paginas:{type:"boolean"},ficha:{type:"object"},impresion:{type:"object"},validaciones:{type:"array"},vistas:{type:"array"},funcionesNativas:{type:"object",additionalProperties:!1,properties:{relacionadas:{type:"array",maxItems:20},siguientes:{type:"array",maxItems:5}}},recurso:{type:"object",description:"Sus registros son recursos (capacidad, persona): ver la gu\xEDa, \xABRecursos y reservas\xBB."},reserva:{type:"object",description:"Cada registro ocupa un recurso (puntual o semanal): ver la gu\xEDa, \xABRecursos y reservas\xBB."},asignacion:{type:"object",description:"\xABAsignar al mejor con hueco\xBB (en la demanda): ver la gu\xEDa, \xABAsignar con cupo y puntos\xBB."},pertenencia:{type:"object",description:"Un m\xF3dulo de pertenencias (demanda, oferta, desde, hasta, correccion_dias): ver la gu\xEDa."},stock:{type:"object",description:"El stock: art\xEDculo (con lotes o series), ubicaci\xF3n, documento que lo mueve (entrada, salida, ajuste, traspaso, recuento, reserva) y punto de pedido (con lo que est\xE1 en camino): ver la gu\xEDa, \xABStock\xBB."},liquidacion:{type:"object",description:"Liquidaciones de comisiones (en el m\xF3dulo de liquidaciones): origen, importe, fecha, agente, reglas con tramos y d\xF3nde va cada cosa: ver la gu\xEDa, \xABLiquidaciones\xBB."},cuota:{type:"object",description:"Cuotas peri\xF3dicas por registro: {proxima: fecha, periodicidad: semanal|quincenal|mensual|bimestral|trimestral|semestral|anual o {campo, valores}, hasta?: fecha}: ver la gu\xEDa, \xABCuotas\xBB."},relacionadas:{type:"array",maxItems:di,description:"Columnas de OTROS m\xF3dulos en la tabla (se calculan al leer, con lo que ve quien mira): {clave, etiqueta, via, campo} trae un campo del relacionado (editable desde la tabla); {clave, etiqueta, de, via, calculo: recuento|suma|media|minimo|maximo|ultimo, campo?, filtro?} calcula sobre los que citan a este.",items:{type:"object",additionalProperties:!1,required:["clave","etiqueta","via"],properties:{clave:{type:"string",pattern:"^[a-z][a-z0-9_]{0,40}$"},etiqueta:e(80),via:{type:"string"},siVacio:{type:"string",description:"Otra columna de traer escalar del mismo tipo, sin cadenas. Conserva el origen de edici\xF3n por fila."},campo:{type:"string"},de:{type:"string"},calculo:{enum:["recuento","suma","minimo","maximo","ultimo","media"]},filtro:{type:"array",maxItems:5}}}},siguientes:{type:"array",maxItems:pi,description:"Siguientes pasos del proceso: un bot\xF3n que crea el registro siguiente en \xABdestino\xBB (mod_<clave>), enlazado por \xABenlace\xBB (la relaci\xF3n del destino a este) y con \xABcampos\xBB copiados {campo del destino: campo de aqu\xED}.",items:{type:"object",additionalProperties:!1,required:["clave","nombre","destino","enlace"],properties:{clave:{type:"string",pattern:"^[a-z][a-z0-9_]{0,40}$"},nombre:e(60),destino:{type:"string",pattern:"^mod_[a-z][a-z0-9_]{0,40}$"},enlace:{type:"string"},campos:{type:"object",additionalProperties:{type:"string"}}}}},personas:{type:"object",additionalProperties:!1,required:["objeto","tipo","etiqueta","plural","icono","campos"],properties:{objeto:{enum:["contacts","companies"]},tipo:{type:"string",pattern:"^[a-z0-9][a-z0-9-]{0,59}$"},de:{enum:["cliente","proveedor"]},etiqueta:{type:"string",minLength:1,maxLength:60},plural:{type:"string",minLength:1,maxLength:60},icono:{type:"string",pattern:"^[a-z0-9-]{1,40}$"},campos:{type:"object",minProperties:1,additionalProperties:{type:"string"}},configuracion:{type:"object",additionalProperties:!1,description:"Ficha, impresi\xF3n, columnas relacionadas y siguientes por objeto. Claves de origen de la soluci\xF3n, sin ids del espacio.",properties:Object.fromEntries(["contacts","companies"].map(o=>[o,{type:"object",additionalProperties:!1,properties:Object.fromEntries(["ficha","impresion","relacionadas","siguientes"].map(t=>[t,{type:t==="relacionadas"||t==="siguientes"?["array","null"]:["object","null"]}]))}]))},alternativa:{type:"object",additionalProperties:!1,required:["objeto","campos"],description:"Segundo destino separado. El principal es contacts; cada relaci\xF3n se expande en su clave de Persona y <clave>_empresa. No es una relaci\xF3n polim\xF3rfica.",properties:{objeto:{const:"companies"},campos:{type:"object",minProperties:1,additionalProperties:{type:"string"}},conversiones:{type:"object",additionalProperties:{type:"object",additionalProperties:{type:"string"}}}}},clasificacion:{type:"object",additionalProperties:!1,required:["campo","valores"],description:"Todas las opciones de una selecci\xF3n, o true/false de un booleano, a contacts/companies. vacio decide expl\xEDcitamente el valor ausente. Nunca se adivina por nombre o identificador.",properties:{campo:{type:"string"},valores:{type:"object",minProperties:2,additionalProperties:{enum:["contacts","companies"]}},vacio:{enum:["contacts","companies"]},formas:{type:"object",description:"Opciones de Empresa a claves de legalForms. Conserva etiqueta y color de la opci\xF3n hist\xF3rica, sin pisar listas existentes.",additionalProperties:{type:"string",pattern:"^[a-z0-9][a-z0-9-]{0,59}$"}},etiquetas:{type:"array",uniqueItems:!0,description:"Opciones de Persona que conservan su significado como etiqueta, con nombre y color de la opci\xF3n hist\xF3rica.",items:{type:"string"}}}},conversiones:{type:"object",description:"Mapa completo e inyectivo de opciones hist\xF3ricas a claves nativas de sector o forma jur\xEDdica. Conserva etiquetas/colores del campo. No clasifica objetos.",additionalProperties:{type:"object",minProperties:1,maxProperties:100,additionalProperties:{type:"string",minLength:1,maxLength:80}}}}}}}},vistasTabla:{type:"array",maxItems:ac,items:{type:"object",additionalProperties:!1,required:["objeto","nombre","disposicion"],properties:{objeto:{type:"string",pattern:"^(contacts|companies|mod_[a-z][a-z0-9_]{0,40})$"},tipoContacto:{type:"string",pattern:"^[a-z0-9][a-z0-9-]{0,59}$"},nombre:e(60),config:{type:"object"},disposicion:{type:["object","null"]}}},description:"Vistas por objeto/tipo con preferencias y widgets. Un m\xF3dulo omitido con dos destinos crea una vista por objeto. Actualizaci\xF3n aditiva sin reponer bajas ni pisar personalizaciones."},separadores:{type:"array",maxItems:lc,items:{type:"object",additionalProperties:!1,required:["antes"],properties:{antes:{type:["string","null"],description:"Clave de m\xF3dulo de la soluci\xF3n, o null al final. Si se omite el m\xF3dulo, se conserva delante del siguiente m\xF3dulo real."},titulo:{type:["string","null"],maxLength:40}}}},paneles:{type:"array",maxItems:ic,description:"Paneles de m\xE9tricas (n\xFAmero, barras, barras horizontales/apiladas/agrupadas, l\xEDneas, \xE1rea, varias l\xEDneas, dona, embudo, medidor con meta, tendencia, tabla, tabla din\xE1mica, mapa de calor; c\xE1lculos de recuento, suma, media, min, max, mediana, % del total, acumulado, tasa de conversi\xF3n, media por)."},automatizaciones:{type:"array",maxItems:sc,description:"Se instalan APAGADAS: una persona las revisa y las enciende."},ejemplos:{type:"object",description:`Datos de ejemplo por clave de m\xF3dulo (hasta ${Si} cada uno).`,additionalProperties:{type:"array",maxItems:Si}},informes:{type:"array",maxItems:Qr,description:"Informes de An\xE1lisis que se crean al publicar (de equipo).",items:{type:"object",additionalProperties:!1,required:["nombre","definicion"],properties:{nombre:e(80),descripcion:e(500),definicion:{type:"object"}}}},principal:{type:"string",description:"La clave de su m\xF3dulo PRINCIPAL (ah\xED se abre el importador al acabar la bienvenida)."},mensajes:{type:"array",maxItems:xi,description:"Plantillas de mensaje (WhatsApp o correo) de sus m\xF3dulos (mod_<clave>) o de contacts, companies y deals.",items:{type:"object",additionalProperties:!1,required:["recurso","canal","nombre","texto"],properties:{recurso:{type:"string"},tipoContacto:{type:"string",pattern:"^[a-z0-9][a-z0-9-]{0,59}$",description:"\xC1mbito opcional de una plantilla de Personas o Empresas."},canal:{enum:["whatsapp","correo"]},nombre:e(80),asunto:e(300),texto:e(5e3)}}},papeles:{type:"array",maxItems:cc,description:"Papeles personalizados que se crean al publicar: a partir de uno de serie, con permisos de la matriz o de sus m\xF3dulos (mod_<clave>.ver|editar|borrar|exportar). Nunca gestionar miembros ni la configuraci\xF3n.",items:{type:"object",additionalProperties:!1,required:["nombre","base"],properties:{nombre:e(40),base:{enum:["administrador","miembro","lectura"]},permisos:{type:"object",additionalProperties:{enum:["si","no","suyos"]}}}}},portales:{type:"array",maxItems:uc,description:"PORTALES (P15): personas de fuera (clientes, propietarios, hu\xE9spedes, familias, trabajadores) que entran con su usuario y ven SOLO lo alcanzable desde su ficha. Se crean al publicar, DESACTIVADOS (los activa una persona). Ver la gu\xEDa, \xABPortal\xBB.",items:{type:"object",additionalProperties:!1,required:["clave","nombre","personas","secciones"],properties:{clave:{type:"string",pattern:"^[a-z][a-z0-9_]{0,30}$"},nombre:e(80),personas:{oneOf:[{type:"object",additionalProperties:!1,required:["modulo","correo"],properties:{modulo:{type:"string",description:"mod_<clave> del m\xF3dulo de personas."},correo:{type:"string",description:"Su campo de correo (tipo correo)."}}},{type:"object",additionalProperties:!1,required:["objeto"],properties:{objeto:{enum:["contacts","companies"]},tipo:{type:"string",pattern:"^[a-z0-9][a-z0-9-]{0,59}$"}}}]},secciones:{type:"array",minItems:1,maxItems:10,items:{type:"object",additionalProperties:!1,required:["clave","titulo","campos"],properties:{clave:{type:"string",pattern:"^[a-z][a-z0-9_]{0,30}$"},titulo:e(60),modulo:{type:"string",description:"mod_<clave> (opcional: lo dice el camino)."},camino:{type:"array",maxItems:2,description:"Desde la ficha de la persona, cada paso por una relaci\xF3n: {modulo: el que TIENE el campo, campo}. Vac\xEDo: su propia ficha.",items:{type:"object",additionalProperties:!1,required:["modulo","campo"],properties:{modulo:{type:"string"},campo:{type:"string"}}}},campos:{type:"array",items:{type:"string"},maxItems:40,description:"La LISTA BLANCA de lo que se ve (nunca un secreto, un bot\xF3n ni una b\xFAsqueda)."},subtablas:{type:"object",additionalProperties:{type:"array",items:{type:"string"}}},crear:{type:"object",additionalProperties:!1,required:["campos"],properties:{campos:{type:"array",items:{type:"string"}}}},editar:{type:"object",additionalProperties:!1,required:["campos"],properties:{campos:{type:"array",items:{type:"string"}},estado:{type:"object",additionalProperties:!1,required:["campo","valores"],properties:{campo:{type:"string"},valores:{type:"array",items:{type:"string"}}}}}},adjuntar:{type:"object",additionalProperties:!1,required:["campo"],properties:{campo:{type:"string"},tipos:{type:"array",items:{enum:["image/png","image/jpeg","image/webp","image/gif","application/pdf"]}},max_mb:{type:"integer",minimum:1,maximum:25}}},comentar:{type:"boolean"}}}},textos:{type:"object",additionalProperties:!1,properties:{titulo:e(80),bienvenida:e(2e3),pie:e(500)}},marca:{type:"object",additionalProperties:!1,properties:{color:{type:"string",pattern:"^#[0-9a-fA-F]{6}$"}}}}}},proyectos:{type:"array",items:{type:"object",required:["clave","nombre"],properties:{clave:{type:"string",pattern:"^[A-Z0-9]{2,10}$"},nombre:e(100),descripcion:e(500),color:{type:"string"},icono:{type:"string"},columnas:{type:"array"}}}},plantillas_proyecto:{type:"array",items:{type:"object",required:["nombre"],properties:{nombre:e(200),clave_sugerida:{type:"string",pattern:"^[A-Z0-9]{2,10}$"},descripcion:e(500),categoria:e(50),color:{type:"string"},icono:{type:"string"},columnas:{type:"array"},tareas:{type:"array"}}}}},"x-forgenex":{tamanoMaximoBytes:Oi,topeCampos:Sc}}}async function Ac(e){let[o,...t]=e,r=await dg(o,t);if(r!==null)return r;let n=t.includes("--json"),a=t.filter(s=>s!=="--json");if(o==="validar"&&a.length===0&&a.push("."),o==="version")return console.log(`${Et} v${cr}`),0;if(o==="esquema")return console.log(JSON.stringify(ky(),null,2)),0;if(o==="esquema-extension")return console.log(JSON.stringify(Ry(),null,2)),0;if((o==="validar"||o==="previsualizar")&&a.length){let s=a.map(c=>{let d;try{jy(c).isDirectory()?(go(c),d=pg(Oy(c,"extension.json"),"utf8")):d=pg(c,"utf8")}catch(u){return{archivo:c,ok:!1,error:u instanceof Error?u.message:String(u)}}return Ay(d)?Ey(c,d):Sy(c,d)});if(n)console.log(JSON.stringify(s.map(c=>c.ok?"extension"in c?{archivo:c.archivo,ok:!0,extension:c.extension}:{archivo:c.archivo,ok:!0,resumen:mg(c.solucion)}:c)));else for(let c of s){if(!c.ok){console.log(`\u2717 ${c.archivo}: ${c.error}`);continue}if("extension"in c){let d=c.extension;console.log(`\u2713 ${c.archivo}: app \xAB${d.nombre}\xBB ${d.version} (${d.id})`);for(let[f,h]of Object.entries(d.permisos.modulos))console.log(` \xB7 pide ${f}: ${h.join(", ")}`);d.permisos.almacen&&console.log(" \xB7 pide su almac\xE9n"),d.permisos.archivos?.length&&console.log(` \xB7 pide archivos (lo que la persona elija): ${d.permisos.archivos.join(", ")}`);let u=[...new Set(d.montajes.filter(f=>!sn.has(f.punto)).map(f=>`montajes.${f.punto}`))];for(let f of d.funciones)console.log(` \xB7 funci\xF3n ${f.nombre} (${f.disparador.tipo}${f.disparador.evento?`: ${f.disparador.evento}`:f.disparador.cron?`: ${f.disparador.cron}`:""})`);for(let f of d.permisos.red_hacia)console.log(` \xB7 se conecta a ${f}`);let p=[...u,d.servidor&&"servidor"].filter(Boolean);p.length&&console.log(` (v\xE1lidos, pero a\xFAn no se ejecutan: ${p.join(", ")})`);continue}if(console.log(`\u2713 ${c.archivo}: \xAB${c.solucion.nombre}\xBB, ${c.solucion.modulos.length} m\xF3dulos`),o==="previsualizar"){let d=mg(c.solucion);for(let u of d.modulos)console.log(` \xB7 ${u.nombre} (${u.clave}): ${u.campos} campos${u.relaciones.length?`, \u2192 ${u.relaciones.join(", ")}`:""}${u.vistas?`, ${u.vistas} vistas`:""}`);console.log(` paneles: ${d.paneles} \xB7 automatizaciones: ${d.automatizaciones} (se instalan apagadas)`)}}return s.every(c=>c.ok)?0:1}return console.log("Uso: forgenex crear-app <nombre> [--plantilla html|react|archivos] \xB7 validar [directorio|archivo.json \u2026] [--json] \xB7 dev --espacio <id> \xB7 empaquetar \xB7 instalar --espacio <id> (--app <id> | --paquete <archivo.fgx>) \xB7 publicar --espacio <id> --paquete <archivo.fgx> [--tienda] \xB7 revisar [--paquete <archivo.fgx>] [--json] \xB7 claves crear \xB7 registrar-clave \xB7 revocar-clave \xB7 previsualizar \xB7 esquema \xB7 esquema-extension \xB7 version"),2}process.argv[1]?.endsWith("cli.ts")&&Ac(process.argv.slice(2)).then(e=>{process.exitCode=e}).catch(e=>{console.error(e instanceof Error?e.message:String(e)),process.exitCode=1});Ac(process.argv.slice(2)).then(e=>{process.exitCode=e}).catch(e=>{console.error(e instanceof Error?e.message:String(e)),process.exitCode=1});
|