@forgenex/cli 0.2.0 → 0.2.1

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/dist/forgenex.js CHANGED
@@ -1,37 +1,37 @@
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=yc[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,yc,sg,cg,Eo,Fr=m(()=>{ig=tg(new URL("./locales/",import.meta.url)).filter(e=>/\.(?:ts|js)$/.test(e)&&!e.endsWith(".d.ts")),ag=rg(import.meta.url),yc=Object.fromEntries(ig.map(e=>[e.replace(/\.(?:ts|js)$/,""),ag(ng(new URL(`./locales/${e}`,import.meta.url))).default])),sg=Object.fromEntries(Object.entries(yc).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(()=>{Fr();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,Nc=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 $c(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 xc(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,ay,Cc=m(()=>{ug=[[0,59],[0,23],[1,31],[1,12],[0,7]];ay=new Intl.DateTimeFormat("en-GB",{timeZone:"Europe/Madrid",hourCycle:"h23",minute:"numeric",hour:"numeric",day:"numeric",month:"numeric",weekday:"short"})});function Oc(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,ir=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 Sc(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,jc=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 ji(e,o=0){if(o>20)throw i("El manifiesto anida demasiado.");if(Array.isArray(e))return e.forEach(t=>ji(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.`);ji(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&&Ei(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(Ai).filter(Boolean)}function zc(e,o,t){let n=oe(e,o,Mc,t);if(Sc(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 kc(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 Ai(o??"")==="forgenex"||Ai(t??"")==="forgenex"}function Ot(e){if(Object.hasOwn(Qr,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=Ot(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=Qr[l]?.ops??ar,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]=ar.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 Rc(e,o){let t=o.lastIndexOf(".");if(t<1)return!1;let n=Ot(o.slice(0,t));return!!n&&(e.modulos[n]??[]).includes(o.slice(t+1))}function Pc(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 Gr(e,o={}){if(typeof e=="string"){if(e.length>Wr)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>Wr)throw i("El manifiesto pasa de 256 KB.");if(!fe(e))throw i("El manifiesto tiene que ser un objeto.");if(ji(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>Jr)throw i("La app es de una versi\xF3n del formato m\xE1s nueva que este CRM.");let t=oe(e.id,"id",Oi,"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:kc(e.autor.web,"autor.web")}:{}};else throw i("Falta \xABautor\xBB (un nombre, o { nombre, web }).");if(!o.firmada){if(Ei(n))throw i("\xABnombre\xBB: \xABForgeNEX\xBB est\xE1 reservado a lo que publica ForgeNEX.");if(Ei(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",qc,"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=>Ec.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}]`,Oi,"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=>Ec.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`,Oi,"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",Si,"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(!Br.includes(M))throw i(`\xAB${x}.punto\xBB: ${Br.join(", ")}.`);let B=null;if(Ac.has(M)){if(B=Ot(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 ${[...Ac].join(", ")}.`);let I=v.permiso===void 0?null:V(v.permiso,`${x}.permiso`,80);if(I!==null&&!Rc(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`,Si,"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`,qc,"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(!Ur.includes(M))throw i(`\xAB${x}.disparador.tipo\xBB: ${Ur.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=$c(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(xc(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=Pc(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`,Si,"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:kc(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=Pc(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?Ot(J.slice(0,ge)):null;if(!Be||!Rc(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(!Vr.includes(M))throw i(`\xAB${x}.tipo\xBB: ${Vr.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,Jr,Wr,Qr,ar,Br,Tc,Ac,Ur,Vr,hg,Oi,gg,Ec,qc,bg,wg,qo,vg,Si,Mc,yg,fe,Ic,_g,hy,Ng,Dc,Lc,xg,Cg,Ai,Ei,Ag,Hr=m(()=>{q();Nc();Cc();ir();jc();Xo="forgenex.extension",Jr=1,Wr=256e3,Qr={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"]}},ar=["ver","crear","editar","borrar"],Br=["pagina","ficha_pestana","ficha_bloque","inicio_bloque","accion_ficha","accion_tabla","vista","ajustes","publica"],Tc=new Set(["pagina","ficha_pestana","ficha_bloque","inicio_bloque","accion_ficha","accion_tabla","vista","ajustes","publica"]),Ac=new Set(["ficha_pestana","ficha_bloque","accion_ficha","accion_tabla","vista"]),Ur=["evento","programada","webhook","automatizacion","calculo","herramienta","publica"],Vr=["texto","numero","si_no","opcion","modulo","campo"],hg=new Set(["__proto__","constructor","prototype"]),Oi=/^[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})?$/,Ec=/^(>=|<=|>|<|=|\^|~)?(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=/^[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}$/,Si=/^(?!\/)(?!.*\/\/)(?!.*(^|\/)\.\.?(\/|$))[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"),hy=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"),Ai=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,"");Ei=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 qi(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 sr(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 vy,Bc=m(()=>{_();vy=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 Cy,Uc=m(()=>{_();te();Cy=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 Ay,Vc=m(()=>{_();te();Ay=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 ky,Jc=m(()=>{_();ky=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 Ly,Qc=m(()=>{_();et();Ly=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 By,Gc=m(()=>{_();te();By=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 Jy,Hc=m(()=>{_();Jy=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,cr=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 Xr(e){return Oe(e)&&"expressionType"in e&&re(e)}function Xc(e){return Oe(e)&&"expression"in e&&W(e.alias)&&re(e)}var Yr=m(()=>{Le();_()});var to,ki=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 Kr,Ri=m(()=>{_();Ro();ot();Kr=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,lr=m(()=>{_();Ri();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:Kr.create(t)})},cloneWithOn(e,o){return c({...e,on:e.on?Kr.cloneWithOperation(e.on,"And",o):Kr.create(o)})}})});var Po,Zr=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,y_,Kc,__,Zc,Eg,el,qg,ol,N_,tl,kg,$_,Je,St=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}),y_=Object.keys(Yc),Kc=c({"+":!0,"-":!0,"*":!0,"/":!0,"%":!0,"^":!0,"&":!0,"|":!0,"#":!0,"<<":!0,">>":!0}),__=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}),N_=Object.keys(ol),tl=c({...ol,"-":!0,not:!0}),kg=Object.keys(tl),$_=[...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 en,on=m(()=>{_();en=c({is(e){return e.kind==="SelectAllNode"},create(){return c({kind:"SelectAllNode"})}})});var jt,tn=m(()=>{on();_();jt=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:en.create()})}})});function rn(e){return Oe(e)&&re(e)&&W(e.dynamicReference)}var nn=m(()=>{Le();_()});var Ge,an=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,Pi=m(()=>{_();te();al=c({is(e){return e.kind==="CollateNode"},create(e){return c({kind:"CollateNode",collation:R.create(e)})}})});var sn,Ti=m(()=>{Pi();an();tt();_();sn=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 At(e){sl.has(e)||(sl.add(e),console.log(e))}var sl,Mi=m(()=>{sl=new Set});function Rg(e){return e==="asc"||e==="desc"}function He(e){if(e.length===2)return[Ii(e[0],e[1])];if(e.length===1){let[o]=e;return Array.isArray(o)?(At("orderBy(array) is deprecated, use multiple orderBy calls instead."),o.map(t=>Ii(t))):[Ii(o)]}throw new Error(`Invalid number of arguments at order by! expected 1-2, received ${e.length}`)}function Ii(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(rn(e))return e.toOperationNode();let[o,t]=e.split(" ");return t?(At("`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(Xr(o))return At("`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 sn({node:t})).toOperationNode():t}var Et=m(()=>{nn();Yr();an();tt();Ti();Mi();nt();Pe()});var qt,cn=m(()=>{_();qt=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 ln,un=m(()=>{_();ln=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,ur=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 qt.create(ze(e),ln.create(Je.create(o)));if(o==="->$"||o==="->>$")return qt.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 jt.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 jt.create(se.create(n),ko.createWithSchema(o,t))}function Ig(e){let[o,t]=e;return jt.create(se.create(t),ko.create(o))}function dl(e){return e.trim()}var Pe=m(()=>{go();Qe();tn();cr();_();nt();te();St();cn();un();ur()});var pl,Di=m(()=>{_();pl=c({is(e){return e.kind==="PrimitiveValueListNode"},create(e){return c({kind:"PrimitiveValueListNode",values:c([...e])})}})});var dn,pn=m(()=>{_();dn=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 mn(e){return oo(e)||Yo(e)||Ko(e)}function dr(e){if(!mn(e))throw new Error(`unsafe immediate value ${JSON.stringify(e)}`);return Se.createImmediate(e)}function Dg(e){return e.some(rt)?dn.create(e.map(o=>Q(o))):pl.create(e)}var vo=m(()=>{Di();pn();Io();_();nt()});var Do,pr=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 fn(e[0],e[1],e[2]);if(e.length===1)return Q(e[0]);throw new Error(`invalid arguments: ${JSON.stringify(e)}`)}function fn(e,o,t){return Lg(o)&&hl(t)?Po.create(ue(e),Li(o),Se.createImmediate(t)):Po.create(ue(e),Li(o),ml(t))}function ye(e,o,t){return Po.create(ue(e),Li(o),ue(t))}function zi(e,o){return hn(Object.entries(e).filter(([,t])=>!ho(t)).map(([t,n])=>fn(t,hl(n)?"is":"=",n)),o)}function hn(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 Li(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(()=>{Zr();_();Le();St();Pe();vo();Io();Ro();pr();ot()});var yo,mr=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 Fi,Wi=m(()=>{_();Fi=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 fr,gn=m(()=>{_();mr();Wi();fr=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?Fi.cloneWithItems(e.partitionBy,o):Fi.create(o)})}})});var it,hr=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 Bi,Ui=m(()=>{_();Bi=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 Vi,Ji=m(()=>{_();Ro();ot();Vi=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,Qi=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,Gi=m(()=>{_();bl=c({is(e){return e.kind==="ListNode"},create(e){return c({kind:"ListNode",items:c(e)})}})});var kt,bn=m(()=>{_();hr();Gi();kt=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 Hi,Xi=m(()=>{_();Hi=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 Rt,wn=m(()=>{_();hr();Xi();_o();Rt=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?Hi.cloneWithTables(e.using,o):Hi.create(o)})}})});var we,gr=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 Yi,Ki=m(()=>{_();Yi=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,Zi=m(()=>{_();wl=c({is(e){return e.kind==="ExplainNode"},create(e,o){return c({kind:"ExplainNode",format:e,options:o})}})});var No,br=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,ea=m(()=>{_();br();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 oa,ta=m(()=>{_();oa=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(()=>{Qi();wr();bn();wn();gr();_();Ki();Zi();ea();ta();mr();E=c({is(e){return H.is(e)||gl.is(e)||kt.is(e)||Rt.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?Yi.cloneWithSelections(e.returning,o):Yi.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?oa.cloneWithSelections(e.output,o):oa.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,wr=m(()=>{_();hr();Ui();Ji();_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?Bi.cloneWithItems(e.groupBy,o):Bi.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?Vi.cloneWithOperation(e.having,"And",o):Vi.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 vn,ra=m(()=>{lr();tt();ro();_();vn=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,na=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(()=>{na();Pe()});var yn,$l=m(()=>{gn();_o();Et();Nl();_();yn=class e{#e;constructor(o){this.#e=c(o)}orderBy(...o){return new e({overNode:fr.cloneWithOrderByItems(this.#e.overNode,He(o))})}clearOrderBy(){return new e({overNode:E.cloneWithoutOrderBy(this.#e.overNode)})}partitionBy(o){return new e({overNode:fr.cloneWithPartitionByItems(this.#e.overNode,_l(o))})}$call(o){return o(this)}toOperationNode(){return this.#e.overNode}}});var Pt,ia=m(()=>{_();tn();on();Pt=c({is(e){return e.kind==="SelectionNode"},create(e){return c({kind:"SelectionNode",selection:e})},createSelectAll(){return c({kind:"SelectionNode",selection:en.create()})},createSelectAllFromTable(e){return c({kind:"SelectionNode",selection:jt.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)?Pt.create(ul(e)):rn(e)?Pt.create(e.toOperationNode()):Pt.create(_n(e))}function no(e){return e?Array.isArray(e)?e.map(Cl):[Cl(e)]:[Pt.createSelectAll()]}function Cl(e){if(W(e))return Pt.createSelectAllFromTable(_e(e));throw new Error(`invalid value selectAll expression: ${JSON.stringify(e)}`)}var vr=m(()=>{_();ia();Pe();nn();nt();io();Tt()});var k$,Ol=m(()=>{_();k$=c({is(e){return e.kind==="ValuesNode"},create(e){return c({kind:"ValuesNode",values:c(e)})}})});var T$,Sl=m(()=>{_();T$=c({is(e){return e.kind==="DefaultInsertValueNode"},create(){return c({kind:"DefaultInsertValueNode"})}})});var aa,sa=m(()=>{_();aa=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?[aa.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])=>aa.create(se.create(t),Q(n)))}var Al=m(()=>{Qe();sa();Tt();_();vo();Pe()});var Q$,El=m(()=>{_();Q$=c({is(e){return e.kind==="OnDuplicateKeyNode"},create(e){return c({kind:"OnDuplicateKeyNode",updates:e})}})});var ql=m(()=>{});function Mt(e){return Object.prototype.hasOwnProperty.call(e,"prototype")}var Lo,yr=m(()=>{Lo=class extends Error{node;constructor(o){super("no result"),this.node=o}}});var Z$,kl=m(()=>{_();gr();Z$=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,ca=m(()=>{_();Pl=c({is(e){return e.kind==="TopNode"},create(e,o){return c({kind:"TopNode",expression:e,modifiers:o})}})});function It(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 Nn=m(()=>{ca();_()});var cx,Tl=m(()=>{_();cx=c({is(e){return e.kind==="OrActionNode"},create(e){return c({kind:"OrActionNode",action:e})}})});var Ml=m(()=>{});var $n,la=m(()=>{$n=class{numDeletedRows;constructor(o){this.numDeletedRows=o}}});var Dt,_r=m(()=>{_();Dt=c({is(e){return e.kind==="LimitNode"},create(e){return c({kind:"LimitNode",limit:e})}})});var ne,ua,Il=m(()=>{xn();io();vr();_o();_();yr();la();wn();_r();Et();ro();vo();Nn();ua=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,It(o,t))})}using(o){return new ne({...this.#e,queryNode:Rt.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,Lt(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:Rt.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:Rt.cloneWithLimit(this.#e.queryNode,Dt.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 $n(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 Mt(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=ua});var Cn,da=m(()=>{Cn=class{numUpdatedRows;numChangedRows;constructor(o,t){this.numUpdatedRows=o,this.numChangedRows=t}}});var ie,pa,Dl=m(()=>{xn();io();vr();_o();bn();Al();_();da();yr();ro();vo();_r();Nn();Et();pa=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,It(o,t))})}from(o){return new ie({...this.#e,queryNode:kt.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,Lt(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:kt.cloneWithLimit(this.#e.queryNode,Dt.create(Q(o)))})}set(...o){return new ie({...this.#e,queryNode:kt.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 Cn(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 Mt(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=pa});var Qx,Ll=m(()=>{_();Qe();cr();Qx=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 Xx,zl=m(()=>{_();Xx=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 Zx,Fl=m(()=>{_();Zx=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 On(e){let o="";for(let t=0;t<e;++t)o+=Wg();return o}function Wg(){return Wl[~~(Math.random()*Wl.length)]}var Wl,ma=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 fa}var fa,Sn=m(()=>{ma();fa=class{#e;get queryId(){return this.#e===void 0&&(this.#e=On(8)),this.#e}}});var Bl=m(()=>{});var Ul=m(()=>{});var sC,Vl=m(()=>{_();sC=c({is(e){return e.kind==="MatchedNode"},create(e,o=!1){return c({kind:"MatchedNode",not:e,bySource:o})}})});var je,Nr=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 jn(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(()=>{Nr();_()});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,An,Xl=m(()=>{_();Jl();Hl();Nr();Ug=c([]),An=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 jn(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 jn(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 jn(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 ha,En,qn=m(()=>{Xl();ha=class e extends An{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([])}},En=new ha});var Yl=m(()=>{});var Kl=m(()=>{});var Zl=m(()=>{});function eu(e,o){return new vn({joinNode:bo.create(e,ut(o))})}function ou(){return new yn({overNode:fr.create()})}var ga=m(()=>{lr();gn();ra();$l();io()});function Lt(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 xn=m(()=>{lr();ro();ga();io()});var tu,ba=m(()=>{_();tu=c({is(e){return e.kind==="OffsetNode"},create(e){return c({kind:"OffsetNode",offset:e})}})});var ru,wa=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(()=>{wa();Tt();_();Pe()});var au,va=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(ya())),qe(o)||(o=[o]),o.map(n=>au.create(e,To(n),t))}var su=m(()=>{Tt();va();_();nt()});var F,$r,_a,Na,zt=m(()=>{go();Ro();te();Le();ot();pr();ro();F=class e{#e;constructor(o){this.#e=o}get expressionType(){}as(o){return new $r(this,o)}or(...o){return new _a(Ve.create(this.#e,le(o)))}and(...o){return new Na(Re.create(this.#e,le(o)))}$castTo(){return new e(this.#e)}$notNull(){return new e(this.#e)}toOperationNode(){return this.#e}},$r=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 $r(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)}},Na=class e{#e;constructor(o){this.#e=o}get expressionType(){}as(o){return new $r(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,$a=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(()=>{$a();_()});function du(e){return new kn(e)}var P,kn,xa,Ca=m(()=>{go();ki();xn();io();vr();Pe();wr();_o();Et();_r();ba();_();iu();yr();te();su();ro();zt();vo();uu();Nn();kn=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?sr(o).map(_e):void 0))})}forShare(o){return new P({...this.#e,queryNode:E.cloneWithEndModifier(this.#e.queryNode,to.create("ForShare",o?sr(o).map(_e):void 0))})}forKeyShare(o){return new P({...this.#e,queryNode:E.cloneWithEndModifier(this.#e.queryNode,to.create("ForKeyShare",o?sr(o).map(_e):void 0))})}forNoKeyUpdate(o){return new P({...this.#e,queryNode:E.cloneWithEndModifier(this.#e.queryNode,to.create("ForNoKeyUpdate",o?sr(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,Lt(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,Dt.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,It(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 xa(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 Mt(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=kn;xa=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,Rn=m(()=>{_();gr();mr();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 Oa,Sa=m(()=>{_();Oa=c({is(e){return e.kind==="FunctionNode"},create(e,o){return c({kind:"FunctionNode",func:e,arguments:o})}})});var Ft,ja,Aa=m(()=>{_();Rn();go();te();ga();ro();Et();_o();Ft=class e{#e;constructor(o){this.#e=c(o)}get expressionType(){}as(o){return new ja(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}},ja=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(Oa.create(t,wo(n??[]))),o=(t,n)=>new Ft({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 Ft({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 Ft({aggregateFunctionNode:so.create("json_agg",[W(t)?_e(t):t.toOperationNode()])})},toJson(t){return new F(Oa.create("to_json",[W(t)?_e(t):t.toOperationNode()]))}})}var Ea=m(()=>{zt();Rn();Sa();Pe();vr();Aa();_();io()});var mu,qa=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(()=>{St();qa();Pe()});var Ae,Pn=m(()=>{_();br();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 Tn,Wt,Mn,In,ka=m(()=>{zt();_();Pe();Pn();br();ro();vo();Tn=class{#e;constructor(o){this.#e=c(o)}when(...o){return new Wt({...this.#e,node:Ae.cloneWithWhen(this.#e.node,No.create(le(o)))})}whenRef(o,t,n){return new Wt({...this.#e,node:Ae.cloneWithWhen(this.#e.node,No.create(ye(o,t,n)))})}},Wt=class{#e;constructor(o){this.#e=c(o)}then(o){return new Mn({...this.#e,node:Ae.cloneWithThen(this.#e.node,mn(o)?dr(o):Q(o))})}thenRef(o){return new Mn({...this.#e,node:Ae.cloneWithThen(this.#e.node,ue(o))})}},Mn=class{#e;constructor(o){this.#e=c(o)}when(...o){return new Wt({...this.#e,node:Ae.cloneWithWhen(this.#e.node,No.create(le(o)))})}whenRef(o,t,n){return new Wt({...this.#e,node:Ae.cloneWithWhen(this.#e.node,No.create(ye(o,t,n)))})}else(o){return new In({...this.#e,node:Ae.cloneWith(this.#e.node,{else:mn(o)?dr(o):Q(o)})})}elseRef(o){return new In({...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}))}},In=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 Ra,Pa=m(()=>{_();Ra=c({is(e){return e.kind==="JSONPathLegNode"},create(e,o){return c({kind:"JSONPathLegNode",type:e,value:o})}})});var Hg,Bt,Dn,Ta,Ma=m(()=>{go();te();un();Pa();ur();cn();Le();Io();Hg=/^#-\d+$/,Bt=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 qt.is(this.#e)?new Dn(qt.cloneWithTraversal(this.#e,Mo.is(this.#e.traversal)?Mo.cloneWithLeg(this.#e.traversal,Ra.create(o,t)):ln.cloneWithValue(this.#e.traversal,Se.createImmediate(t)))):new Dn(Mo.cloneWithLeg(this.#e,Ra.create(o,t)))}},Dn=class e extends Bt{#e;constructor(o){super(o),this.#e=o}get expressionType(){}as(o){return new Ta(this,o)}$castTo(){return new e(this.#e)}$notNull(){return new e(this.#e)}toOperationNode(){return this.#e}},Ta=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 Ia,Da=m(()=>{_();Ia=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,La=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(()=>{La();Le()});var yu,za=m(()=>{_();yu=c({is(e){return e.kind==="CastNode"},create(e,o){return c({kind:"CastNode",expression:e,dataType:o})}})});function ya(e=En){function o(r,a,s){return new F(fn(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 Tn({node:Ae.create(ho(r)?void 0:ue(r))})},ref(r,a){return ho(a)?new F(ze(r)):new Bt(ll(r,a))},jsonPath(){return new Bt(Mo.create())},table(r){return new F(_e(r))},val(r){return new F(Q(r))},refTuple(...r){return new F(Ia.create(r.map(ue)))},tuple(...r){return new F(Ia.create(r.map(Q)))},lit(r){return new F(dr(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(hn(r,"and")):new F(zi(r,"and"))},or(r){return qe(r)?new F(hn(r,"or")):new F(zi(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 ya()}var Tt=m(()=>{Ca();wr();io();Sn();Ea();Pe();ro();pr();zt();St();hu();vo();qn();ka();Pn();_();Ma();Zr();Ro();Da();ur();vu();za()});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 Xr(e)||Xc(e)||ve(e)}var nt=m(()=>{Yr();Le();Tt();_()});function _u(e){return Oe(e)&&re(e)&&W(e.table)&&W(e.alias)}var Fa=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();cr();nt();te();Fa()});var Sj,$u=m(()=>{_();Sj=c({is(e){return e.kind==="AddColumnNode"},create(e){return c({kind:"AddColumnNode",column:e})}})});var qj,xu=m(()=>{_();Qe();qj=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 Tj,Cu=m(()=>{_();Qe();Tj=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 Lj,Ou=m(()=>{_();Qe();Lj=c({is(e){return e.kind==="RenameColumnNode"},create(e,o){return c({kind:"RenameColumnNode",column:se.create(e),renameTo:se.create(o)})}})});var Bj,Su=m(()=>{_();te();Bj=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,Jj,ju,Wa=m(()=>{_();Zg=c({cascade:!0,"no action":!0,restrict:!0,"set default":!0,"set null":!0}),Jj=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 Hj,Au=m(()=>{_();Hj=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 Kj,Eu=m(()=>{_();Kj=c({is(e){return e.kind==="DefaultValueNode"},create(e){return c({kind:"DefaultValueNode",defaultValue:e})}})});var qu=m(()=>{});var tA,ku=m(()=>{_();tA=c({is(e){return e.kind==="ModifyColumnNode"},create(e){return c({kind:"ModifyColumnNode",column:e})}})});var sA,Ru=m(()=>{_();te();Wa();sA=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 dA,Tu=m(()=>{_();dA=c({is(e){return e.kind==="AddConstraintNode"},create(e){return c({kind:"AddConstraintNode",constraint:e})}})});var bA,Mu=m(()=>{Mi();_();Qe();te();bA=c({is(e){return e.kind==="UniqueConstraintNode"},create(e,o,t){return W(e.at(0))&&(At("`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 _A,Iu=m(()=>{_();te();_A=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 CA,Du=m(()=>{_();Qe();CA=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 qA,zu=m(()=>{_();Qe();te();qA=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 TA,Fu=m(()=>{_();te();TA=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 LA,Wu=m(()=>{_();te();LA=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 YA,Yu=m(()=>{_();et();YA=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 tE,Zu=m(()=>{_();et();tE=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 cE,od=m(()=>{_();pn();Io();cE=c({is(e){return e.kind==="CreateTypeNode"},create(e){return c({kind:"CreateTypeNode",name:e})},cloneWithEnum(e,o){return c({...e,enum:dn.create(o.map(Se.createImmediate))})}})});var td=m(()=>{});var pE,rd=m(()=>{_();pE=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 bE,id=m(()=>{_();et();bE=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 _E,sd=m(()=>{_();_E=c({is(e){return e.kind==="AlterTypeNode"},create(e){return c({kind:"AlterTypeNode",name:e})},cloneWith(e,o){return c({...e,...o})}})});var xE,cd=m(()=>{_();xE=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 jE,ud=m(()=>{_();jE=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,IE,bd=m(()=>{_();eb=["query","error"],IE=c(eb)});var wd=m(()=>{});var vd=m(()=>{Symbol.asyncDispose??=Symbol("Symbol.asyncDispose")});function Co(e){return new Ba(e)}var Ba,Ua,Va=m(()=>{go();_();qn();te();Le();Ba=class e{#e;constructor(o){this.#e=c(o)}get expressionType(){}get isRawBuilder(){return!0}as(o){return new Ua(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():En;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)}};Ua=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();Sn();Va();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 iq,aq,sq,Ja=m(()=>{_();iq=c({ForKeyShare:"for key share",ForNoKeyUpdate:"for no key update",ForUpdate:"for update",ForShare:"for share",NoWait:"nowait",SkipLocked:"skip locked",Distinct:"distinct"}),aq=c({ForKeyShare:1,ForNoKeyUpdate:1,ForUpdate:1,ForShare:1,NoWait:2,SkipLocked:2,Distinct:0}),sq=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,xr=m(()=>{tt();_();Sn();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 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(`
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 Cr=m(()=>{_()});function rb(e){return Oe(e)&&"insertId"in e&&"affectedRows"in e}var tb,Ed,qd=m(()=>{xr();_();Cr();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(()=>{xr();Cr();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 Tq,Mq,zd=m(()=>{Tq=BigInt("3853314791062309107"),Mq=3600*1e3});var Fd=m(()=>{});var Wd=m(()=>{});var ib,ab,sb,Bd,Or,Ud=m(()=>{_();xr();Cr();ma();Nr();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?On(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 Or({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 Or({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 Or({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}},Or=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:qi(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(()=>{Nr();Cr();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 Ln=m(()=>{vd();Zl();ld();Yr();zt();Ca();Ml();Dl();Il();yr();ra();Ea();ql();la();da();Rl();Aa();ka();Ma();Kl();Yl();Ti();Va();_d();fd();qn();Ja();xr();dd();Qu();td();Xu();nd();Vu();Gu();Ju();Hu();qu();Pu();Uu();Ku();ad();ed();Lu();Bu();pd();nn();Fa();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();Ja();Kd();Zd();Ul();ep();op();tp();rp();$u();Tu();Fu();Rn();go();Du();Bc();Ro();Zr();Pn();za();Su();Pi();xu();Qe();sa();Ll();zl();np();Uc();Vc();Jc();od();Yu();id();La();Sl();Eu();wn();Cu();Iu();Qc();Gc();Hc();rd();Zu();Zi();$a();Ru();hr();Sa();Au();wa();Ui();Ji();te();Qi();lr();un();Pa();ur();cn();_r();Gi();Vl();ea();ku();ba();kl();El();Ri();Le();Bl();Nd();St();Tl();ot();an();mr();ta();gn();pr();na();Wi();zu();Di();_o();tt();tn();Wa();Ou();Wu();Ki();et();on();ki();wr();ia();va();ip();cr();ca();Da();qa();Mu();bn();Xi();pn();Io();Ol();br();gr();Fl();sd();cd();ud();wd();bd()});function ap(e){let o=Ut(e,["version","origen","entidades"]);if(o.version!==1)throw i("Perfil relacional inv\xE1lido.");let t=Sr(o.entidades,60).map(r=>{let a=Ut(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(Ut(a.campos)).map(([b,y])=>(Qa(b),[b,Vt(y)])));if(Object.keys(s).length>100)throw i("Perfil relacional inv\xE1lido.");let l=Sr(a.referencias??[],30).map(b=>{let y=Ut(b,["campo","entidad","clave","obligatoria"]);if(y.obligatoria!==void 0&&typeof y.obligatoria!="boolean")throw i("Perfil relacional inv\xE1lido.");return{campo:Qa(y.campo),entidad:zn(y.entidad),clave:Ga(y.clave),obligatoria:y.obligatoria===!0}}),d=a.archivos===void 0?void 0:Sr(a.archivos,20).map(b=>{let y=Ut(b,["campo","columna","obligatorio"]);if(y.obligatorio!==void 0&&typeof y.obligatorio!="boolean")throw i("Perfil relacional inv\xE1lido.");return{campo:Qa(y.campo),columna:Vt(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(Ut(a.procedencia,["autor","creado","actualizado"])).map(([b,y])=>[b,Vt(y)])),f=a.responsable===void 0?void 0:Ga(a.responsable),h=a.tipos===void 0?void 0:Sr(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:zn(a.clave),...a.acl!==void 0?{acl:Vt(a.acl)}:{},...d?{archivos:d}:{},destino:a.destino,...p?{procedencia:p}:{},...f?{responsable:f}:{},...h?{tipos:h}:{},...a.tiposColumna!==void 0?{tiposColumna:Vt(a.tiposColumna)}:{},clave_externa:Ga(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:zn(o.origen),entidades:t}}var zn,Qa,Vt,Ut,Sr,Ga,sp=m(()=>{q();zn=e=>{if(typeof e!="string"||!/^[a-z][a-z0-9_]{0,60}$/.test(e))throw i("Perfil relacional inv\xE1lido.");return e},Qa=e=>{let o=typeof e=="string"&&/^datos\.[a-z][a-z0-9_]{0,60}$/.test(e)?e:zn(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},Vt=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},Ut=(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},Sr=(e,o)=>{if(!Array.isArray(e)||e.length>o)throw i("Perfil relacional inv\xE1lido.");return e},Ga=e=>{let o=Sr(e,3).map(Vt);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 Ha(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)||Ha(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||Ha(u)&&Ha(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=Fn(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=Fn(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=Fn(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=Fn(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,Fn,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},Fn=(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 jr,QT,mb,fp=m(()=>{jr=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())}},QT=new jr(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:Xa(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:Wn(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:Wn(C.desde),tasa:w.medida==="recuento"?mt(C.tasa):Xa(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:Wn(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:Wn(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,Xa,mt,Fo,ft,Wn,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},Xa=e=>{if(typeof e!="string")throw i("Liquidaci\xF3n v2: decimal como cadena.");try{if(jr.leer(e).n<0n)throw new Error("negativo")}catch{throw i("Liquidaci\xF3n v2: decimal inv\xE1lido.")}return e},mt=e=>{let o=Xa(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},Wn=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 Ar(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||!Ya(l))throw i(`El elemento ${a+1} no tiene una clave v\xE1lida.`);if(!d||d.length>80||!Ya(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||!Ya(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,Ya,gb,Za=m(()=>{q();fb=["won","lost"],yp=["cliente","proveedor"],hb=/^[a-z0-9-]{1,40}$/,Ya=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.");Ar("legalForms",[{value:s,label:es(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(es(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:es(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 Ar("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,es,xp=m(()=>{q();Za();Er();wb=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);es=(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,sM,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"]),sM=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 Bn,yb,_b,Nb,qp=m(()=>{Fr();Bn=[["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"],...Bn,["background","Contexto"],["nif","Identificador fiscal"],["pais_fiscal","Pa\xEDs fiscal"]],_b=[["name","Nombre"],["phone_number","Tel\xE9fono"],["website","Web"],...Bn,["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",...Bn.map(([o])=>o),"background"]:["name","phone_number","website",...Bn.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 os(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 os,Rp=m(()=>{q();os=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 ts(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=Qt(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 Qt(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 Un(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 rs(e,o){let t=cs(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 ns(e,o,t){if(!o.includes("."))return null;let n=o.trim().toLowerCase();if(cs(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?ss[t.tipo]:zp[kr(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=ss[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=cs(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=kr(t.relacion).find(r=>r.clave===o.campo)??(Ee(o.campo)&&o.origen?{tipo:o.origen.tipo}:void 0);if(!n||!(Ee(o.campo)?ss[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=ns(e,u.v,n)?u.v:rs(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=ns(e,u.v,n);return p?Ab(p):Fp(e,rs(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"):(Qt(s(u.a),s(u.b)),"booleano");case"fn":{let p=Sb[u.f]??u.f,f=as[p];if(!f)throw i(`F\xF3rmula: la funci\xF3n \xAB${u.f}\xBB no existe.`);if(p==="REDONDEAR"&&Un(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 Vn(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+=`{${ns(e,l,t)?l:rs(e,l).clave}}`,r=s+1;continue}n+=a,r++}return n}var Ye,Pp,Tp,Mp,Ip,is,$b,Cb,Xe,ht,Dp,Jt,as,Sb,bM,gt,ss,zp,wM,cs,jb,qb,Wp,Jn=m(()=>{Er();Ln();q();Qn();Ye=1e3,Pp=300,Tp=20,Mp=5,Ip=20,is="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 ${is})::date`:e,Dp=e=>j`(${e})::text`,Jt=(e,o)=>j`(least(greatest(${e}, ${-o}::numeric), ${o}::numeric))::int`,as={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=>Qt(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]}, ${Un(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]}, ${Jt(e[1],1e4)})`},DERECHA:{args:["texto","numero"],tipo:()=>"texto",sql:e=>j`right(${e[0]}, ${Jt(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 ${is})::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]} + ${Jt(e[1],1e5)})`:j`(${e[0]} + make_interval(days => ${Jt(e[1],1e5)}))`},ANO:{args:["cualquiera"],tipo:e=>ts(e),sql:(e,o)=>j`(extract(year from ${ht(e[0],o[0])}))::numeric`},MES:{args:["cualquiera"],tipo:e=>ts(e),sql:(e,o)=>j`(extract(month from ${ht(e[0],o[0])}))::numeric`},DIA:{args:["cualquiera"],tipo:e=>ts(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 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
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
10
  else power((${e[0]})::numeric, (${e[1]})::numeric) end)`},PAGO:{args:["numero","numero","numero"],tipo:()=>"numero",sql:e=>j`(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 n=Un(t[1]);return n?j`(ceil((${e[0]})::numeric * ${10**n}::numeric) / ${10**n}::numeric)`:j`ceil((${e[0]})::numeric)`}},REDONDEAR_ABAJO:{args:["numero","numero"],opcionales:1,tipo:()=>"numero",sql:(e,o,t)=>{let n=Un(t[1]);return n?j`(floor((${e[0]})::numeric * ${10**n}::numeric) / ${10**n}::numeric)`:j`floor((${e[0]})::numeric)`}},DIAS_HABILES:{args:["cualquiera","cualquiera"],tipo:e=>{if(!Xe(e,0)||!Xe(e,1))throw i("F\xF3rmula: DIAS_HABILES necesita dos fechas.");return"numero"},sql:(e,o)=>{let t=ht(e[0],o[0]),n=ht(e[1],o[1]);return j`(case when ${t} is null or ${n} is null then null
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 n=Jn(t[1]);return n?j`(ceil((${e[0]})::numeric * ${10**n}::numeric) / ${10**n}::numeric)`:j`ceil((${e[0]})::numeric)`}},REDONDEAR_ABAJO:{args:["numero","numero"],opcionales:1,tipo:()=>"numero",sql:(e,o,t)=>{let n=Jn(t[1]);return n?j`(floor((${e[0]})::numeric * ${10**n}::numeric) / ${10**n}::numeric)`:j`floor((${e[0]})::numeric)`}},DIAS_HABILES:{args:["cualquiera","cualquiera"],tipo:e=>{if(!Xe(e,0)||!Xe(e,1))throw i("F\xF3rmula: DIAS_HABILES necesita dos fechas.");return"numero"},sql:(e,o)=>{let t=ht(e[0],o[0]),n=ht(e[1],o[1]);return j`(case when ${t} is null or ${n} is null then null
14
14
  when abs((${n})::date - (${t})::date) > 3660 then null
15
15
  else (case when (${n})::date < (${t})::date then -1 else 1 end) * (
16
16
  select count(*) from generate_series(least((${t})::date, (${n})::date)::timestamp, greatest((${t})::date, (${n})::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(as,{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?(Qt(e[0],e[t]),o=o?Qt(o,e[t+1]):e[t+1]):o=o?Qt(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 => ${Jt(e[1],12e3)}))::date)`:j`(${e[0]} + make_interval(months => ${Jt(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 ${is})`: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"},bM=Object.keys(as);gt={numero:"un n\xFAmero",texto:"un texto",fecha:"una fecha",fecha_hora:"una fecha y hora",booleano:"un s\xED/no"};ss={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"},wM={numero:j`numeric`,texto:j`text`,fecha:j`date`,fecha_hora:j`timestamptz`,booleano:j`boolean`},cs=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,$M,ls,xM,Vp=m(()=>{Ln();q();Pb=["oculto","lectura"],Tb=["administrador","miembro","lectura"],Mb=e=>Tb.includes(e)||/^p_[a-z]{1,12}$/.test(e),$M=j`coalesce(current_setting('app.extension', true), '') <> ''`,ls=class extends Map{get(){return"no"}},xM=new ls});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 Gn(e,o){if(e==null)return;if(!us(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 Hn(e,o){if(e==null)return;if(!us(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=us(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 us,Gp,ds=m(()=>{q();Qp();us=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=Vn([...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();Jn();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 Xn(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,DM,LM,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";DM=Bb({p:"",v:""}),LM=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 BM,pm=m(()=>{Ln();q();BM=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(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,
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=Vn([...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();Jn();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(!ps(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"||!Yn.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(!ps(d)||typeof d.campo!="string"||!Yn.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(!Yn.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"||!Yn.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(!ps(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,Yn,ps,ym=m(()=>{q();bm=10,wm=50,Yn=/^[a-z][a-z0-9_]{0,40}$/,ps=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)});function kr(e){let o=new Map(qr(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=qr(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 qr,Xb,Yb,Kb,Zb,Qn=m(()=>{Op();qp();Fr();qr=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=kr(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(()=>{Er();q();Qn()});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 Er=m(()=>{q()});function xm(e,o){if(e==null)return;if(!Rr(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(!Rr(r)||!Rr(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(!Rr(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(!Rr(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 Rr,Cm=m(()=>{q();Rr=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=Pr(r,o)??{},s=Ht(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 Kn(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 Ht(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 Zn(e,o){if(e==null)return;if(!wt(e))throw i("\xABficha\xBB: un objeto.");Kn(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.`);Kn(f,["titulo","secciones","artefacto"],`Pesta\xF1a ${h+1}`);let b=Ht(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 Pr(e,o){if(e==null)return;if(!wt(e))throw i("\xABimpresion\xBB: un objeto.");Kn(e,["titulo","campos","subtabla","pie","logo","orientacion","cuerpo","color","firmas"],"Impresi\xF3n");let t={},n=Ht(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=Ht(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=Ht(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 ms(e,o=0){return o>10?!1:Array.isArray(e)?e.every(t=>ms(t,o+1)):wt(e)?Object.keys(e).every(t=>!rw.has(t)&&ms(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.`);Kn(t,["nombre","tipo","config"],`Vista ${n+1}`);let r=Ht(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)||!ms(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,fs=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 Tr,Em=m(()=>{Tr=e=>e==="@contacts"||e==="@companies"});function ti(e,o){if(e==null)return;if(!Array.isArray(e)||e.length>ei)throw i(`\xABrelacionadas\xBB: hasta ${ei} columnas.`);if(!e.length)return;let t=new Set;return e.map((n,r)=>{let a=`Columna relacionada ${r+1}`;if(!gs(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=Tr(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"&&Tr(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:Tr(u)&&typeof n.campo=="string"&&/^datos\.[a-z][a-z0-9_]{0,40}$/.test(n.campo)?n.campo:vt(n.campo,`${a}.campo`),h=Mr(n.filtro,a,Tr(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 ri(e){if(e==null)return;if(!Array.isArray(e)||e.length>oi)throw i(`\xABsiguientes\xBB: hasta ${oi} pasos.`);if(!e.length)return;let o=new Set;return e.map((t,n)=>{let r=`Siguiente paso ${n+1}`;if(!gs(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(!gs(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(!hs.test(d)||typeof u!="string"||!hs.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,ei,oi,hs,gs,km,vt,ni=m(()=>{Em();q();Ir();qm=["recuento","suma","minimo","maximo","ultimo","media"],ei=20,oi=5,hs=/^[a-z][a-z0-9_]{0,40}$/,gs=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"||!hs.test(e))throw i(`${o}: falta o no es v\xE1lido.`);return e}});function bs(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"?Zn(l,o):s==="impresion"?Pr(l,o):s==="relacionadas"?ti(l,o):s==="recurso"?Gn(l,o):s==="reserva"?Hn(l,o):ri(l))??null})}t[n]=a}return t}var Pm=m(()=>{ds();q();fs();ni()});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=>!ws.includes(n)))throw i("Un ajuste nativo no cambia la identidad de la relaci\xF3n.");return structuredClone(e)}}var ws,vs=m(()=>{q();ws=["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(ys,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(ys,a))continue;let s=ys[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,Ar(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 ys,Im=m(()=>{q();Za();ys={sector:"companySectors",forma_juridica:"legalForms"}});function Ns(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=ii(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=ii(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=bs(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:ii(e.etiqueta,"etiqueta",60),plural:ii(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=>Ns(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:bs(e.configuracion,o)}:{}}}var Dm,Lm,Oo,nw,ii,_s,zm=m(()=>{Er();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}$/,ii=(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(!ai(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(!ai(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(!ai(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,ai,Wm,Um=m(()=>{q();Fm=5,yt=/^[a-z][a-z0-9_]{0,40}$/,aw=["contacts","companies","deals"],ai=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Wm=(e,o)=>{if(e===void 0)return{};if(!ai(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,$s,sw,_t,Jm,Wo,cw,Gm=m(()=>{q();Vm=5,$s=/^[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(!$s.test(t)||typeof n!="string"||!$s.test(n))throw i(`${o}: \xAB${t.slice(0,40)}\xBB no es v\xE1lido.`);return e}},Wo=(e,o)=>{if(typeof e!="string"||!$s.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"||!ci.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"&&ci.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"||!ci.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:ci,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>si||u.length>si)throw i(`\xABasignacion\xBB: hasta ${si} filtros y ${si} 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,ci,Hm,si,lw,Nt,uw,Km=m(()=>{q();co=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ci=/^[a-z][a-z0-9_]{0,40}$/,Hm=/^[a-z][a-z0-9_]{0,40}(\.[a-z][a-z0-9_]{0,40})?$/,si=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 xs,Zm=m(()=>{xs=["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"||!Cs.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"||!Cs.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"||!Cs.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,Cs,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==="";Cs=/^[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=js(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:js(s.desde,`${t}.tramos.lista[${l}].desde`,0),valor:js(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":li(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=>Ss.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,[...Os],"liquidacion.estados");let p={};for(let N of Os){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!==Os.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=>Ss.includes(N.tipo),"una columna num\xE9rica"),comision:b(e.lineas.comision,"comision",N=>Ss.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:li(e.importe,"liquidacion.importe"),fecha:li(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 Os,nf,af,Ss,pw,Uo,$t,Vo,li,sf,js,lf=m(()=>{q();Os=["borrador","aprobada","cerrada","pagada"],nf=20,af=20,Ss=["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.`)},li=(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:li(e.campo,`${o}.campo`),valores:[...new Set(e.valores)]}},js=(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(!ui(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(!ui(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=ui(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(!ui(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,ui,hw,df=m(()=>{q();fw=/^[a-z][a-z0-9_]{0,40}$/,ui=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),hw=["secreto","boton","firma"]});function mf(e,o){if(pf(e))return;if(!As(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(!Dr.includes(e.periodicidad))throw i(`\xABcuota.periodicidad\xBB: ${Dr.join(", ")} (o {campo, valores}).`);r.periodicidad=e.periodicidad}else if(As(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(!As(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(!Dr.includes(u))throw i(`\xABcuota.periodicidad.valores.${d.slice(0,40)}\xBB: ${Dr.join(", ")}.`)}r.periodicidad={campo:s.clave,valores:a.valores}}else throw i(`\xABcuota.periodicidad\xBB: ${Dr.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 Dr,As,pf,ff=m(()=>{q();Dr=["semanal","quincenal","mensual","bimestral","trimestral","semestral","anual"],As=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"?Es[e.tipo]:void 0;if(!n||!Object.hasOwn(Es,e.tipo))throw i(`\xABpapel.tipo\xBB: uno de ${Object.keys(Es).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,Es,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"]}},Es={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 Mr(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 Ps(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)=>di(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"&&Rs.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(Ps(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 os(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=Zn(t.ficha,u),y=Pr(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),$=Gn(t.recurso,u),v=Hn(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=ti(t.relacionadas,u),Go=ri(t.siguientes),Ho=bf(t.papel,u),G=Ns(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 di(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(!qs.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];di(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=di({...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=di(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=Xn(r.visibleSi,s.etiqueta);u&&(s.visibleSi=u)}if(!Rm({tipo:a})){let u=Xn(r.visibleSi,s.etiqueta);u&&(s.visibleSi=u);let p=Xn(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)||!ks.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=Mr(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 qs,xf,ks,vf,yf,ww,vw,yw,Cf,_w,Rs,Fe,Of,Nw,$w,xw,Jo,Cw,Ow,_f,Nf,$f,jw,Aw,Ew,Rm,Ir=m(()=>{mp();bp();vp();zm();vs();Rp();q();Jn();um();Vp();fs();Yp();tm();gm();Um();Gm();ym();df();ds();Km();rf();lf();ff();ni();wf();Nm();qs=["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"],ks=["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"]),Rs=["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)||!ks.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.");Mr(o.filtro,"Resumen")}var kf=m(()=>{q();Ir()});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 Xt(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,pi=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=Xt(o.origenes);if(t==="combinada"!=!!n)throw i("La fuente combinada necesita sus or\xEDgenes.");if(t!=="combinada"&&!Ms.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,Ts,"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,Yt,"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,Yt,"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?Is(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 Is(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,Yt,"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,Yt,"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 Ts,Rw,Yt,Ms,Pw,Lf,Tw,Ne,We,Ke,Ie,Ds=m(()=>{pi();q();Ts=["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"],Yt=["dia","semana","mes","anio"],Ms=["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!==Ls&&!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(Ls))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!==Ls&&!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:Xt(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,Ls,Dw,Wf,Bf,Lw,zw,Uf,jo,Qf=m(()=>{pi();q();Ds();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"],Ls="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(zs(e.personas)&&t(e.personas.modulo),Array.isArray(e.secciones)){for(let n of e.secciones)if(zs(n)&&(t(n.modulo),Array.isArray(n.camino)))for(let r of n.camino)zs(r)&&t(r.modulo)}return o}var zs,Hf=m(()=>{zs=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&&(!qr(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"?Fs(t.asunto,`${o}, asunto`,300,!1):void 0;return{recurso:n,...t.tipoContacto?{tipoContacto:t.tipoContacto}:{},canal:r,nombre:Fs(t.nombre,`${o}, nombre`,80),...a?{asunto:a}:{},texto:Fs(t.texto,`${o}, texto`,5e3)}}var Ww,mi,Bw,Xf,aD,Fs,Ws=m(()=>{Qn();q();Ww=["whatsapp","correo"],mi=50,Bw=/^(contacts|companies|deals|mod_(?!sub_)[a-z][a-z0-9_]{0,40})$/,Xf="(?:datos\\.)?[a-z][a-z0-9_]{0,40}",aD=new RegExp(`\\{\\{\\s*(${Xf}(?:\\|${Xf})?)\\s*\\}\\}`,"g"),Fs=(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=Xt(o.origenes);if(t==="combinada"!=!!n)throw i("La fuente combinada necesita sus or\xEDgenes.");if(t!=="combinada"&&!Ms.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=Is(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,Yt,"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,Ts,`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(()=>{pi();q();Ds();rh=30,nh=6});var Bs,Qw,sh,ch=m(()=>{Bs=[{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=>Bs.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>Lr)throw i(`\xABinformes\xBB: una lista de hasta ${Lr}.`);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 Lr,Xw,Us=m(()=>{q();ah();Lr=30,Xw=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)});var hh,uo,Kt,Zt,X,Vs,er,kD,Yw,fi,Kw,Zw,RD,PD,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"],Kt=["si","no","suyos","equipo","jerarquia"],Zt=["si","no","suyos","jerarquia"],X=["si","no"],Vs=(e,o,t=!0)=>[{clave:`${e}.ver`,descripcion:`Ver ${o}`,valores:Zt},{clave:`${e}.crear`,descripcion:`Dar de alta ${o}`,valores:Zt},{clave:`${e}.editar`,descripcion:`Editar ${o}`,valores:Zt},{clave:`${e}.reasignar`,descripcion:`Cambiar el responsable de ${o}`,valores:Zt},...t?[{clave:`${e}.estado`,descripcion:`Cambiar el estado de ${o}`,valores:Zt}]:[],{clave:`${e}.descargar`,descripcion:`Bajar los ficheros de ${o}`,valores:X},{clave:`${e}.borrar`,descripcion:`Borrar ${o}`,valores:Zt},{clave:`${e}.exportar`,descripcion:`Exportar ${o}`,valores:uo},{clave:`${e}.importar`,descripcion:`Importar ${o} desde una hoja`,valores:X}],er=[...Vs("contactos","contactos"),...Vs("empresas","empresas",!1),...Vs("oportunidades","oportunidades"),{clave:"proyectos.ver",descripcion:"Ver proyectos",valores:Kt},{clave:"proyectos.editar",descripcion:"Editar los datos del proyecto",valores:Kt},{clave:"proyectos.borrar",descripcion:"Borrar proyectos",valores:Kt},{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:Kt},{clave:"tareas.crear",descripcion:"Crear tareas",valores:X},{clave:"tareas.editar",descripcion:"Editar y completar tareas",valores:Kt},{clave:"tareas.borrar",descripcion:"Borrar tareas",valores:Kt},{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},...Bs.map(e=>({clave:`pix.agente_${e.clave}`,descripcion:`Usar a ${e.nombre} (${e.puesto}) del Equipo IA`,valores:X}))],kD=new Set(er.map(e=>e.clave)),Yw=e=>/\.(exportar|importar)$/.test(e),fi=e=>Object.fromEntries(er.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:fi(()=>"si"),administrador:fi(e=>e.clave==="conectores.accionar"?"no":"si"),miembro:fi(e=>Kw(e)||e.clave==="conectores.accionar"||e.clave==="secretos.ver"||Yw(e.clave)?"no":"si"),lectura:fi(e=>e.clave.endsWith(".ver")&&e.clave!=="secretos.ver"&&e.clave!=="auditoria.ver"||e.clave.endsWith(".descargar")?"si":e.clave.endsWith(".reasignar")?"suyos":"no")},RD=er.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),PD=er.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(!Js(r))throw i(`\xAB${r}\xBB no es una palabra.`);t.has(Js(r))||(t.add(Js(r)),o.push(r))}}if(o.length>Qs)throw i(`Como mucho ${Qs} sin\xF3nimos por m\xF3dulo.`);return o}var wh,Qs,bh,Js,yh=m(()=>{q();wh=["contacts","companies","deals","tasks"],Qs=20,bh=40,Js=e=>e.normalize("NFD").replace(/[̀-ͯ]/g,"").toLowerCase().replace(/[^a-z0-9ñ\s-]/g," ").replace(/\s+/g," ").trim()});function tv(e,o){return mo(e,Xs,"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,Ks,"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=er.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 Gs(e,o=0){if(o>30)throw i("La soluci\xF3n anida demasiado.");if(Array.isArray(e))return e.forEach(t=>Gs(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.`);Gs(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 wi(e,o){if(typeof e=="string"){if(e.length>gi)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>gi)throw i("La soluci\xF3n pasa de 1 MB.");if(!pe(e))throw i("La soluci\xF3n tiene que ser un objeto.");Gs(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>or)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>hi)throw i(`Una soluci\xF3n lleva de 1 a ${hi} 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],Ps($,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,Hs,"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,Ys,"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,mi,"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??[],Zs,"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"||!xs.includes($.despliega)))throw i(`Men\xFA ${v+1}: \xABdespliega\xBB, ${xs.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,bi,`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,ec,"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,or,hi,Hs,Xs,Ys,bi,gi,_h,ov,Ks,rv,nv,iv,pe,Zs,ec,oc=m(()=>{lp();dp();Hf();Df();Ws();q();uh();mh();Us();Ir();Zm();gh();Qf();yh();xt="forgenex.solucion",or=2,hi=30,Hs=10,Xs=20,Ys=40,bi=50,gi=1e6,_h=/^[a-z0-9-]{1,40}$/,ov=new Set(["__proto__","constructor","prototype"]);Ks=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);Zs=20,ec=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 tc(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 mL}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!==rc).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 rc,Sh=m(()=>{q();rc="firma.json"});function nc(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 ic,mkdirSync as ac,readFileSync as vi,readdirSync as zr,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);ac(n);for(let l of["interfaz","funciones"])ac(ee(n,l));let r=(l,d)=>qh(ee(n,l),typeof d=="string"?d:JSON.stringify(d,null,2)+`
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
22
  `),a=`ext_${e.replace(/[^a-z]/g,"_").slice(0,27)}`;r("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"}}]}),r("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}]}]}),r("funciones/resumir.js",`export default async function (entrada) {
23
23
  const resumen = { mensaje: String(entrada.cuerpo?.mensaje ?? "Hola"), total: 1 };
24
24
  await crm.almacen.guardar("ultimo_resumen", resumen);
25
25
  return resumen;
26
26
  }
27
- `);for(let l of["GUIA-IA.md","extension.schema.json","solucion.schema.json","puente-extension.d.ts","puente-extension.mjs"])ic(ee(tr,l),ee(n,l));r("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.
28
- `);let s=o==="html"?"hola-alpine":"hola-react";for(let l of zr(ee(tr,"ejemplos",s,"interfaz")))ic(ee(tr,"ejemplos",s,"interfaz",l),ee(n,"interfaz",l));return o==="react"&&(ac(ee(n,"src")),ic(ee(tr,"ejemplos/hola-react/src/main.jsx"),ee(n,"src/main.jsx")),r("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"}}),r("vite.config.js",`import { defineConfig } from "vite";
27
+ `);for(let l of["GUIA-IA.md","extension.schema.json","solucion.schema.json","puente-extension.d.ts","puente-extension.mjs"])sc(ee(rr,l),ee(n,l));r("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.
28
+ `);let s=o==="html"?"hola-alpine":"hola-react";for(let l of Wr(ee(rr,"ejemplos",s,"interfaz")))sc(ee(rr,"ejemplos",s,"interfaz",l),ee(n,"interfaz",l));return o==="react"&&(cc(ee(n,"src")),sc(ee(rr,"ejemplos/hola-react/src/main.jsx"),ee(n,"src/main.jsx")),r("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"}}),r("vite.config.js",`import { defineConfig } from "vite";
29
29
  export default defineConfig({ build: { outDir: "interfaz", emptyOutDir: false, rollupOptions: { input: "src/main.jsx", external: ["@forgenex/crm-sdk"], output: { entryFileNames: "app.js", inlineDynamicImports: true } } } });
30
30
  `)),r(".gitignore",`node_modules/
31
31
  *.fgx
32
32
  *.pem
33
33
  .keys/
34
- `),Ao(n),n}function Ao(e){let o=Gr(vi(ee(e,"extension.json"),"utf8"));o.solucion&&wi(vi(ee(e,o.solucion),"utf8"),{topeCampos:200});for(let t of[...o.montajes,...o.funciones])vi(ee(e,t.entrada));return o}async function yi(e){if(!zr(e).includes("src")||!zr(ee(e,"src")).includes("main.jsx"))return;let o=Eh(ee(e,"package.json")),t;try{t=o("esbuild")}catch{try{t=Eh(ee(tr,"../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(tr,"../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,vi(l))},a=s=>{for(let l of zr(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"])zr(e).includes(s)&&a(s);return tc(nc(t)),t}async function Rh(e,o,t){await yi(e);let n=_v(e);if(o&&t)n.set(rc,Oh(n,o,t));else throw new Error("Falta la clave de firma: ejecuta forgenex claves crear y registrar-clave.");let r=nc(n);tc(r);let a=Ao(e),s=`${a.id.split(".").at(-1)}-${a.version}.fgx`;return qh(ee(e,s),r),ee(e,s)}var tr,_i=m(()=>{Hr();oc();xh();Sh();jh();tr=wv(bv(yv(import.meta.url)),"..")});import{Worker as Nv}from"node:worker_threads";var $v,sc,Ni,Ph=m(()=>{ir();$v=new URL(import.meta.url.endsWith(".ts")?"./caja.ts":"./caja.js",import.meta.url),sc=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()}},Ni=class{ranuras;cola=[];constructor(o=L.simultaneas){this.ranuras=Array.from({length:Math.max(1,o)},()=>new sc)}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 lc(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,""))||!cc(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,cc,uc=m(()=>{th();ir();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"],cc=(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)??Ot(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=>cc(o,t.startsWith("*.")?`x${t.slice(1)}`:t)&&(!t.startsWith("*.")||o.includes(t)))}var Mh,qv,kv,Lh=m(()=>{Hr();uc();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=nr(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)=>rr(o.api,o.clave,"/api/desarrollador/desarrollo",{espacio:o.espacio,ext_id:r.id,pase:N,funcion:C}),s=await a();await yi(n);let l=new Ni(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=yi(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},...Oc(J),manejar:async(De,k)=>{if(De==="red"){if(++fo>L.llamadasRed)throw new Error("Demasiadas peticiones de red.");return(await lc(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 hc=await Ct.json(),gc=(hc.data?.operaciones??hc.operaciones??[]).find(Ci=>Ci.id===K);if(!gc)throw new Error("Operaci\xF3n no aceptada por el administrador.");let xi=gc.metodo,bc=D.args??{},Yh=xi==="GET"?`?${new URLSearchParams(Object.entries(bc).map(([Ci,Kh])=>[Ci,String(Kh)]))}`:"",wc=await fetch(`${o.api}/api/v1/op/${K}${Yh}`,{method:xi,redirect:"error",headers:{authorization:`Bearer ${M}`,"x-espacio":String(o.espacio),"content-type":"application/json","idempotency-key":`dev-${Ho}-${G}`},...xi==="POST"?{body:JSON.stringify(bc)}:{}}),vc=await wc.json();if(!wc.ok)throw new Error(vc.error?.mensaje??"El CRM rechaz\xF3 la operaci\xF3n.");return vc.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}
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}
35
35
  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 Lv(e){let o=[],t=0;for await(let n of e){if(t+=n.length,t>L.webhookBytes)throw new Error("Entrada demasiado grande.");o.push(n)}return JSON.parse(Buffer.concat(o).toString("utf8")||"null")}var Bh=m(()=>{Ph();ir();Lh();uc();dc();_i()});import{generateKeyPairSync as zv,createPublicKey as Uh}from"node:crypto";import{mkdirSync as Fv,readFileSync as $i,writeFileSync as Vh}from"node:fs";import{homedir as Wv}from"node:os";import{join as Bv,resolve as Jh}from"node:path";function Ze(e,o){let t=e.indexOf(`--${o}`);if(t<0)return;let n=e[t+1];if(!n||n.startsWith("--"))throw new Error(`Falta --${o}.`);return n}function Qh(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 rr(e,o,t,n){let r=await fetch(`${Qh(e)}${t}`,{method:"POST",redirect:"error",headers:{authorization:`Bearer ${o}`,"content-type":"application/json"},body:JSON.stringify(n)}),a=await r.json();if(!r.ok)throw new Error(`${r.status}: ${a.error?.mensaje??"El CRM rechaz\xF3 la petici\xF3n."}`);return a.data}function pc(e){return Jh(Ze(e,"clave-firma")??process.env.FORGENEX_CLAVE_FIRMA??Bv(Wv(),".forgenex/desarrollador.pem"))}function nr(e){let o=Ze(e,"api")??process.env.FORGENEX_API,t=process.env.FORGENEX_CLAVE_DESARROLLADOR,n=Number(Ze(e,"espacio"));if(!o||!t||!Number.isSafeInteger(n)||n<1)throw new Error("Configura FORGENEX_API, FORGENEX_CLAVE_DESARROLLADOR y --espacio <id>.");return{api:Qh(o),clave:t,espacio:n}}async function Gh(e,o){if(e==="crear-app"||e==="crear-extension")return console.log(kh(o[0]??"",Ze(o,"plantilla"))),0;if(e==="claves"&&o[0]==="crear"){let t=pc(o);Fv(Jh(t,".."),{recursive:!0,mode:448});let n=zv("ed25519");return Vh(t,n.privateKey.export({type:"pkcs8",format:"pem"}),{flag:"wx",mode:384}),Vh(`${t}.pub`,n.publicKey.export({type:"spki",format:"pem"}),{flag:"wx",mode:420}),console.log(`Clave privada: ${t}
37
- P\xFAblica: ${t}.pub`),0}if(e==="registrar-clave"){let t=nr(o),n=$i(pc(o),"utf8");return console.log(JSON.stringify(await rr(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=nr(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 rr(t.api,t.clave,"/api/desarrollador/revocar-clave",{espacio:t.espacio,id:n}))),0}if(e==="empaquetar"){let t=$i(pc(o),"utf8");return console.log(await Rh(process.cwd(),t,Uh(t).export({type:"spki",format:"pem"}).toString())),0}if(e==="instalar"){let t=nr(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:$i(n).toString("base64")},l=await rr(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=nr(o),n=Ze(o,"paquete");if(!n)throw new Error("Falta --paquete <archivo.fgx> (lo hace `forgenex empaquetar`).");let r=await rr(t.api,t.clave,"/api/desarrollador/publicar",{espacio:t.espacio,paquete:$i(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 dc=m(()=>{_i()});dc();_i();Ir();vs();oc();Us();ni();Ws();Hr();import{readFileSync as Hh,statSync as Uv}from"node:fs";import{join as Vv}from"node:path";var mc=200;function Jv(e,o){try{return{archivo:e,ok:!0,solucion:wi(o,{topeCampos:mc})}}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:Gr(o)}}catch(t){return{archivo:e,ok:!1,error:t instanceof Error?t.message:String(t)}}}function Hv(){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 ${Jr}. 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:Jr,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:"D\xF3nde se cuelga su interfaz, en una caja aislada (iframe sin origen). Se pintan \xABpagina\xBB, \xABficha_pestana\xBB, \xABficha_bloque\xBB, \xABinicio_bloque\xBB y \xABaccion_ficha\xBB; \xABaccion_tabla\xBB, \xABvista\xBB, \xABajustes\xBB y \xABpublica\xBB se validan, pero todav\xEDa no se pintan.",items:{type:"object",additionalProperties:!1,required:["id","punto","entrada","titulo"],properties:{id:{type:"string",pattern:"^[a-z][a-z0-9_-]{0,40}$"},punto:{enum:[...Br]},entrada:t,titulo:e(60),icono:{type:"string"},modulo:{type:"string"},permiso:{type:"string",description:"<m\xF3dulo>.<operaci\xF3n>, dentro de \xABpermisos\xBB."}}}},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:[...Ur]},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:[...Vr]},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(Qr).map(([a,s])=>`${a} (${s.ops.join(", ")})`).join("; ")}. Los de su soluci\xF3n o del espacio, por su clave: ${ar.join(", ")}.`,additionalProperties:{type:"array",minItems:1,maxItems:4,uniqueItems:!0,items:{enum:[...ar]}}},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:Wr}}}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 Xv(){let e=o=>({type:"string",maxLength:o});return{$schema:"https://json-schema.org/draft/2020-12/schema",$id:`https://forgenex.com/sdk/solucion-v${or}.schema.json`,title:"Soluci\xF3n del CRM ForgeNEX",description:`Formato \xAB${xt}\xBB, versi\xF3n ${or}. 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:or,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:hi,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:[...Rs]},campos:{type:"array",maxItems:mc,items:{type:"object",required:["clave","etiqueta","tipo"],properties:{clave:{type:"string"},etiqueta:e(80),tipo:{enum:[...qs]},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(ws.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:ei,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:oi,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:Xs,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:Zs,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:Hs,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:Ys,description:"Se instalan APAGADAS: una persona las revisa y las enciende."},ejemplos:{type:"object",description:`Datos de ejemplo por clave de m\xF3dulo (hasta ${bi} cada uno).`,additionalProperties:{type:"array",maxItems:bi}},informes:{type:"array",maxItems:Lr,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:mi,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:Ks,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:ec,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:gi,topeCampos:mc}}}async function fc(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${or}`),0;if(o==="esquema")return console.log(JSON.stringify(Xv(),null,2)),0;if(o==="esquema-extension")return console.log(JSON.stringify(Hv(),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=>!Tc.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")&&fc(process.argv.slice(2)).then(e=>{process.exitCode=e}).catch(e=>{console.error(e instanceof Error?e.message:String(e)),process.exitCode=1});fc(process.argv.slice(2)).then(e=>{process.exitCode=e}).catch(e=>{console.error(e instanceof Error?e.message:String(e)),process.exitCode=1});
36
+ Recarga al guardar. Funciones: crm.pedir("desarrollo.funcion", { nombre, entrada }, { metodo: "POST", idempotencia: crypto.randomUUID() }).`)}async function Lv(e){let o=[],t=0;for await(let n of e){if(t+=n.length,t>L.webhookBytes)throw new Error("Entrada demasiado grande.");o.push(n)}return JSON.parse(Buffer.concat(o).toString("utf8")||"null")}var Bh=m(()=>{Ph();ar();Lh();pc();mc();$i()});import{generateKeyPairSync as zv,createPublicKey as Uh}from"node:crypto";import{mkdirSync as Fv,readFileSync as Ci,writeFileSync as Vh}from"node:fs";import{homedir as Wv}from"node:os";import{join as Bv,resolve as Jh}from"node:path";function Ze(e,o){let t=e.indexOf(`--${o}`);if(t<0)return;let n=e[t+1];if(!n||n.startsWith("--"))throw new Error(`Falta --${o}.`);return n}function Qh(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 nr(e,o,t,n){let r=await fetch(`${Qh(e)}${t}`,{method:"POST",redirect:"error",headers:{authorization:`Bearer ${o}`,"content-type":"application/json"},body:JSON.stringify(n)}),a=await r.json();if(!r.ok)throw new Error(`${r.status}: ${a.error?.mensaje??"El CRM rechaz\xF3 la petici\xF3n."}`);return a.data}function fc(e){return Jh(Ze(e,"clave-firma")??process.env.FORGENEX_CLAVE_FIRMA??Bv(Wv(),".forgenex/desarrollador.pem"))}function ir(e){let o=Ze(e,"api")??process.env.FORGENEX_API,t=process.env.FORGENEX_CLAVE_DESARROLLADOR,n=Number(Ze(e,"espacio"));if(!o||!t||!Number.isSafeInteger(n)||n<1)throw new Error("Configura FORGENEX_API, FORGENEX_CLAVE_DESARROLLADOR y --espacio <id>.");return{api:Qh(o),clave:t,espacio:n}}async function Gh(e,o){if(e==="crear-app"||e==="crear-extension")return console.log(kh(o[0]??"",Ze(o,"plantilla"))),0;if(e==="claves"&&o[0]==="crear"){let t=fc(o);Fv(Jh(t,".."),{recursive:!0,mode:448});let n=zv("ed25519");return Vh(t,n.privateKey.export({type:"pkcs8",format:"pem"}),{flag:"wx",mode:384}),Vh(`${t}.pub`,n.publicKey.export({type:"spki",format:"pem"}),{flag:"wx",mode:420}),console.log(`Clave privada: ${t}
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});