@forgenex/cli 0.4.1 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/GUIA-IA.md +84 -5
- package/README.md +20 -0
- package/REFERENCIA.md +196 -0
- package/dist/forgenex.js +23 -18
- package/dist/locales/ca.js +1 -1
- package/dist/locales/en.js +1 -1
- package/dist/locales/es.js +1 -1
- package/ejemplos/escuela-natacion/README.md +26 -0
- package/ejemplos/escuela-natacion/extension.json +83 -0
- package/ejemplos/escuela-natacion/funciones/opciones.js +3 -0
- package/ejemplos/escuela-natacion/interfaz/agenda.html +5 -0
- package/ejemplos/escuela-natacion/interfaz/alta.html +2 -0
- package/ejemplos/escuela-natacion/interfaz/alta.js +31 -0
- package/ejemplos/escuela-natacion/interfaz/horario.js +64 -0
- package/ejemplos/escuela-natacion/interfaz/inscripcion.html +4 -0
- package/ejemplos/escuela-natacion/interfaz/inscripcion.js +29 -0
- package/ejemplos/escuela-natacion/interfaz/panel.html +7 -0
- package/ejemplos/escuela-natacion/interfaz/panel.js +103 -0
- package/ejemplos/escuela-natacion/interfaz/piscina.html +5 -0
- package/ejemplos/escuela-natacion/solucion.json +399 -0
- package/ejemplos/kit-visual/extension.json +13 -0
- package/ejemplos/kit-visual/interfaz/galeria.js +71 -0
- package/ejemplos/kit-visual/interfaz/index.html +9 -0
- package/kit/pantalla.mjs +980 -0
- package/licencias.txt +1 -1
- package/package.json +2 -1
package/dist/forgenex.js
CHANGED
|
@@ -1,45 +1,50 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __fgxRequire } from "node:module"; const require = __fgxRequire(import.meta.url);
|
|
3
|
-
var Qg=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 Gg=(e,o)=>{for(var t in o)Qg(e,t,{get:o[t],enumerable:!0})};import{AsyncLocalStorage as Hg}from"node:async_hooks";import{readdirSync as Xg}from"node:fs";import{createRequire as Yg}from"node:module";import{fileURLToPath as Kg}from"node:url";function io(e,o){let n=Gc[e]?.[o];if(n!==void 0)return n;for(let r of ob[e]??[]){let a=r.regex.exec(o);if(a)return r.traduccion.replace(/%\{([\w]+)\}/g,(s,c)=>{let d=r.nombres.indexOf(c);return d<0?s:a[d+1]})}return o}var Zg,eb,Gc,ob,tb,Mo,an=m(()=>{Zg=Xg(new URL("./locales/",import.meta.url)).filter(e=>/\.(?:ts|js)$/.test(e)&&!e.endsWith(".d.ts")),eb=Yg(import.meta.url),Gc=Object.fromEntries(Zg.map(e=>[e.replace(/\.(?:ts|js)$/,""),eb(Kg(new URL(`./locales/${e}`,import.meta.url))).default])),ob=Object.fromEntries(Object.entries(Gc).map(([e,o])=>[e,Object.entries(o).filter(([t])=>t.includes("%{")).map(([t,n])=>{let r=[],a=0,s="";for(let c of t.matchAll(/%\{([\w]+)\}/g)){let d=c.index;s+=t.slice(a,d).replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"([\\s\\S]*?)",r.push(c[1]),a=d+c[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)])),tb=new Hg,Mo=()=>tb.getStore()?.idioma??"es"});var L,i,E=m(()=>{an();L=class extends Error{constructor(t,n,r,a=!0,s){super(a?io(Mo(),r):r);this.estado=t;this.codigo=n;this.datos=s}estado;codigo;datos},i=(e,o=!0)=>new L(400,"peticion_invalida",e,o)});function Hc(e){if(e===void 0)return[];if(!Array.isArray(e)||e.length>20)throw i("La app admite hasta 20 conexiones.");let o=new Set;return e.map(t=>{if(!t||typeof t!="object"||Array.isArray(t)||typeof t.clave!="string"||!/^[a-z][a-z0-9_]{0,40}$/.test(t.clave)||o.has(t.clave)||typeof t.base!="string"||t.base.length>1e3||typeof t.operacion!="string"||!/^[a-zA-Z][a-zA-Z0-9_.-]{0,79}$/.test(t.operacion))throw i("Declaraci\xF3n de conexi\xF3n de app no v\xE1lida.");let n=["clave","base","operacion","tipo",...t.tipo==="api_key"?["lugar","nombre"]:[]];if(Object.keys(t).some(c=>!n.includes(c)))throw i("La declaraci\xF3n de conexi\xF3n no admite campos adicionales.");let r;try{r=new URL(t.base)}catch{throw i("La conexi\xF3n necesita una base HTTPS.")}if(!(process.env.NODE_ENV==="test"&&process.env.CRM_CONEXIONES_PRUEBA_LOCAL==="1"&&r.protocol==="http:"&&r.hostname==="127.0.0.1")&&(r.protocol!=="https:"||r.port)||r.username||r.password||r.search||r.hash)throw i("La conexi\xF3n necesita una base HTTPS sin credenciales, query ni fragmento.");o.add(t.clave);let s={clave:t.clave,base:r.href,operacion:t.operacion};if(t.tipo==="api_key"&&(t.lugar==="cabecera"||t.lugar==="query")&&typeof t.nombre=="string"&&/^[a-zA-Z][a-zA-Z0-9_.-]{0,79}$/.test(t.nombre))return{...s,tipo:t.tipo,lugar:t.lugar,nombre:t.nombre};if(t.tipo==="bearer"||t.tipo==="basic"||t.tipo==="oauth2")return{...s,tipo:t.tipo};throw i("Autenticaci\xF3n de conexi\xF3n de app no v\xE1lida.")})}var Xc=m(()=>{E()});var Q,rb,Yc,Kc=m(()=>{Q={id:"Id del registro."},rb=[{nombre:"contacto.creado",descripcion:"Se ha creado un contacto.",datos:Q},{nombre:"contacto.actualizado",descripcion:"Han cambiado datos de un contacto.",datos:{...Q,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:{...Q,fusionado_en:"Si se fusion\xF3: en cu\xE1l."}},{nombre:"empresa.creada",descripcion:"Se ha creado una empresa.",datos:Q},{nombre:"empresa.actualizada",descripcion:"Han cambiado datos de una empresa.",datos:{...Q,campos:"Qu\xE9 columnas (si se sabe)."}},{nombre:"empresa.borrada",descripcion:"Se ha borrado una empresa.",datos:Q},{nombre:"contacto.fusionado",descripcion:"Un contacto se ha fusionado en otro: quien guarde su id, que lo cambie por el que queda.",datos:{...Q,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:{...Q,se_va:"La que se fue.",queda:"La que queda (= id)."}},{nombre:"oportunidad.creada",descripcion:"Se ha creado una oportunidad.",datos:Q},{nombre:"oportunidad.actualizada",descripcion:"Han cambiado datos de una oportunidad (no la etapa).",datos:{...Q,campos:"Qu\xE9 columnas (si se sabe)."}},{nombre:"oportunidad.etapa_cambiada",descripcion:"Una oportunidad ha cambiado de etapa.",datos:{...Q,de:"Etapa anterior.",a:"Etapa nueva."}},{nombre:"oportunidad.ganada",descripcion:"Una oportunidad ha pasado a ganada (adem\xE1s de etapa_cambiada).",datos:{...Q,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:{...Q,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:Q},{nombre:"oportunidad.borrada",descripcion:"Se ha borrado una oportunidad.",datos:Q},{nombre:"nota.creada",descripcion:"Nueva nota en el hilo de un contacto o de una oportunidad.",datos:{...Q,contacto_id:"Si es de un contacto.",oportunidad_id:"Si es de una oportunidad."}},{nombre:"nota.actualizada",descripcion:"Se ha editado una nota.",datos:Q},{nombre:"nota.borrada",descripcion:"Se ha borrado una nota.",datos:Q},{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:{...Q,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:{...Q,contacto_id:"Su contacto."}},{nombre:"tarea.actualizada",descripcion:"Ha cambiado una tarea (o se ha reabierto).",datos:{...Q,campos:"Qu\xE9 columnas (si se sabe)."}},{nombre:"tarea.completada",descripcion:"Se ha completado una tarea.",datos:Q},{nombre:"tarea.borrada",descripcion:"Se ha borrado una tarea.",datos:Q},{nombre:"contacto.etiquetado",descripcion:"Una Persona ha recibido una etiqueta (una vez por etiqueta a\xF1adida, venga de donde venga).",datos:{...Q,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:{...Q,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:{...Q,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:{...Q,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:{...Q,modulo:"La clave del m\xF3dulo.",campos:"Qu\xE9 campos."}},{nombre:"registro.borrado",descripcion:"Se ha borrado un registro de un m\xF3dulo.",datos:{...Q,modulo:"La clave del m\xF3dulo."}}],Yc=rb.map(e=>e.nombre)});function ib(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]),c=a[1]==="*"?t:a[3]!==void 0?Number(a[3]):a[4]!==void 0?t:s,d=a[4]!==void 0?Number(a[4]):1;if(s<o||c>t||s>c||d<1)return null;for(let u=s;u<=c;u+=d)n.add(u)}return n}function Zc(e){let o=e.trim().split(/\s+/);if(o.length!==5)return null;let t=o.map((r,a)=>ib(r,nb[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 el(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 nb,R_,ol=m(()=>{nb=[[0,59],[0,23],[1,31],[1,12],[0,7]];R_=new Intl.DateTimeFormat("en-GB",{timeZone:"Europe/Madrid",hourCycle:"h23",minute:"numeric",hour:"numeric",day:"numeric",month:"numeric",weekday:"short"})});function tl(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,z.ms),memoriaMb:o(e?.tope?.memoria_mb,z.memoriaMb)}}var z,gr=m(()=>{z={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 rl(e){if(!e.startsWith("*."))return!1;let o=e.slice(2).toLowerCase();if(sb.has(o)||cb.test(o))return!0;let t=o.split(".");return t.length===2&&t[1].length===2&&ab.has(t[0])}var ab,sb,cb,nl=m(()=>{ab=new Set(["co","com","net","org","gov","gob","edu","ac","nom","mil","ltd","plc","me","or","ne","go","info","biz","int"]),sb=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"]),cb=/^(s3([.-][a-z0-9-]+)?\.amazonaws\.com|blogspot\.[a-z]{2,3}(\.[a-z]{2})?)$/});function Vi(e,o=0){if(o>20)throw i("El manifiesto anida demasiado.");if(Array.isArray(e))return e.forEach(t=>Vi(t,o+1));if(pe(e))for(let t of Object.keys(e)){if(lb.has(t))throw i(`Clave no admitida \xAB${t}\xBB.`);Vi(e[t],o+1)}}function ye(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 gb(e,o,t={}){return fb.test(e.replace(hb,""))?`\xAB${o}\xBB: lleva caracteres de control, invisibles o de direcci\xF3n del texto.`:t.reservar&&!t.firmada&&Ji(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=gb(r,o);if(a)throw i(a);return r}function vb(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(Ui).filter(Boolean)}function bl(e,o,t){let n=X(e,o,ml,t);if(rl(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 X(e,o,t,n){if(typeof e!="string"||!t.test(e))throw i(`\xAB${o}\xBB: ${n}.`);return e}function ce(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 ge(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 Wi(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||!ml.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 yb(e){let[o,t]=e.split(".");return Ui(o??"")==="forgenex"||Ui(t??"")==="forgenex"}function ao(e){if(Object.hasOwn(Do,e))return e;let o=e.startsWith("mod_")?e.slice(4):e;return pb.test(o)?`mod_${o}`:null}function ul(e,o,t){if(!pe(e))throw i(`\xAB${o}\xBB: un nombre de contrato, o { contrato, modulos, eventos, herramientas }.`);ye(e,["contrato","titulo","modulos","eventos","herramientas",...t],o);let n=X(e.contrato,`${o}.contrato`,Bi,"un nombre de contrato (\xABtaller.vehiculos\xBB)"),r=e.titulo===void 0?null:V(e.titulo,`${o}.titulo`,80),a={};if(e.modulos!==void 0){if(!pe(e.modulos))throw i(`\xAB${o}.modulos\xBB: un objeto { m\xF3dulo: [operaciones] }.`);let d=Object.entries(e.modulos);if(d.length>20)throw i(`\xAB${o}.modulos\xBB: como mucho 20 m\xF3dulos.`);for(let[u,p]of d){let f=ao(u);if(!f)throw i(`\xAB${o}.modulos\xBB: \xAB${u.slice(0,60)}\xBB no es un m\xF3dulo (min\xFAsculas, n\xFAmeros y _).`);if(a[f])throw i(`\xAB${o}.modulos\xBB: \xAB${u}\xBB est\xE1 repetido.`);let h=ce(p,`${o}.modulos.${u}`,4);if(!h.length||h.some(y=>typeof y!="string"||!Lo.includes(y)))throw i(`\xAB${o}.modulos.${u}\xBB: operaciones ${Lo.join(", ")}.`);let b=new Set(h);if((b.has("editar")||b.has("borrar"))&&!b.has("ver"))throw i(`\xAB${o}.modulos.${u}\xBB: para \xABeditar\xBB o \xABborrar\xBB hace falta \xABver\xBB.`);a[f]=Lo.filter(y=>b.has(y))}}let s=ge(ce(e.eventos,`${o}.eventos`,3).map((d,u)=>{if(typeof d!="string"||!il.includes(d))throw i(`\xAB${o}.eventos[${u}]\xBB: ${il.join(", ")} (los de los registros de sus m\xF3dulos).`);return d}),d=>d,`${o}.eventos`).sort();if(s.length&&!Object.values(a).some(d=>d.includes("ver")))throw i(`\xAB${o}.eventos\xBB: los eventos son de sus m\xF3dulos; hace falta \xABver\xBB de alguno en \xAB${o}.modulos\xBB.`);let c=ge(ce(e.herramientas,`${o}.herramientas`,20).map((d,u)=>X(d,`${o}.herramientas[${u}]`,/^[a-z][a-z0-9_]{2,40}$/,"el nombre de una herramienta")),d=>d,`${o}.herramientas`);if(!Object.keys(a).length&&!s.length&&!c.length)throw i(`\xAB${o}\xBB: di qu\xE9 lleva el contrato (m\xF3dulos, eventos o herramientas).`);return{contrato:n,titulo:r,modulos:a,eventos:s,herramientas:c}}function _b(e){if(e===void 0)return{modulos:{},almacen:!1,red_hacia:[],eventos:[],archivos:[]};if(!pe(e))throw i("\xABpermisos\xBB: un objeto.");ye(e,["modulos","almacen","red_hacia","eventos","archivos"],"Permisos");let o={};if(e.modulos!==void 0){if(!pe(e.modulos))throw i("\xABpermisos.modulos\xBB: un objeto { m\xF3dulo: [operaciones] }.");let a=Object.entries(e.modulos);if(a.length>40)throw i("\xABpermisos.modulos\xBB: como mucho 40 m\xF3dulos.");for(let[s,c]of a){let d=ao(s);if(!d)throw i(`\xABpermisos.modulos\xBB: \xAB${s.slice(0,60)}\xBB no es un m\xF3dulo (min\xFAsculas, n\xFAmeros y _).`);if(o[d])throw i(`\xABpermisos.modulos\xBB: \xAB${s}\xBB est\xE1 repetido.`);let u=Do[d]?.ops??Lo,p=ce(c,`permisos.modulos.${s}`,4);if(!p.length)throw i(`\xABpermisos.modulos.${s}\xBB: di qu\xE9 operaciones (${u.join(", ")}).`);for(let h of p)if(typeof h!="string"||!u.includes(h))throw i(`\xABpermisos.modulos.${s}\xBB: operaciones ${u.join(", ")}.`);let f=new Set(p);if((f.has("editar")||f.has("borrar"))&&!f.has("ver"))throw i(`\xABpermisos.modulos.${s}\xBB: para \xABeditar\xBB o \xABborrar\xBB hace falta \xABver\xBB.`);o[d]=Lo.filter(h=>f.has(h))}}if(e.almacen!==void 0&&typeof e.almacen!="boolean")throw i("\xABpermisos.almacen\xBB: s\xED o no (true/false).");let t=ge(ce(e.red_hacia,"permisos.red_hacia",20).map((a,s)=>bl(a,`permisos.red_hacia[${s}]`,"un dominio (\xABapi.ejemplo.com\xBB o \xAB*.ejemplo.com\xBB; ni IP ni localhost)")),a=>a,"permisos.red_hacia").sort(),n=ge(ce(e.eventos,"permisos.eventos",40).map((a,s)=>{if(typeof a!="string"||!Yc.includes(a))throw i(`\xABpermisos.eventos[${s}]\xBB: un evento del cat\xE1logo (GET /api/v1/eventos).`);return a}),a=>a,"permisos.eventos").sort(),r=ce(e.archivos,"permisos.archivos",2);for(let a of r)if(typeof a!="string"||!al.includes(a))throw i('\xABpermisos.archivos\xBB: ["leer"] o ["leer", "escribir"].');if(r.includes("escribir")&&!r.includes("leer"))throw i("\xABpermisos.archivos\xBB: para \xABescribir\xBB hace falta \xABleer\xBB.");return{modulos:Object.fromEntries(Object.entries(o).sort(([a],[s])=>a.localeCompare(s))),almacen:e.almacen===!0,red_hacia:t,eventos:n,archivos:al.filter(a=>r.includes(a))}}function dl(e,o){let t=o.lastIndexOf(".");if(t<1)return!1;let n=ao(o.slice(0,t));return!!n&&(e.modulos[n]??[]).includes(o.slice(t+1))}function pl(e,o){let t={};if(e===void 0)return t;if(!pe(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(X(n,o,Io,"nombres de campo en min\xFAsculas y _"),!pe(r))throw i(`\xAB${o}.${n}\xBB: { tipo, desc }.`);ye(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 zo(e,o={}){if(typeof e=="string"){if(e.length>cn)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>cn)throw i("El manifiesto pasa de 256 KB.");if(!pe(e))throw i("El manifiesto tiene que ser un objeto.");if(Vi(e),e.formato!==nt)throw i(`No es una app (formato \xAB${nt}\xBB).`);if(ye(e,["$schema","formato","formato_version","id","nombre","descripcion","version","autor","icono","idiomas","compatible_crm","licencia","politica_datos","depende_de","ofrece","usa","solucion","montajes","funciones","servidor","herramientas_ia","ajustes","secretos","conexiones","permisos"],"App"),!Number.isInteger(e.formato_version)||e.formato_version<1)throw i("\xABformato_version\xBB: un entero (1).");if(e.formato_version>dn)throw i("La app es de una versi\xF3n del formato m\xE1s nueva que este CRM.");let t=X(e.id,"id",sn,"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&&yb(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=X(e.version,"version",ub,"versi\xF3n semver (\xAB1.0.0\xBB)"),a;if(typeof e.autor=="string")a={nombre:V(e.autor,"autor",120)};else if(pe(e.autor))ye(e.autor,["nombre","web"],"Autor"),a={nombre:V(e.autor.nombre,"autor.nombre",120),...e.autor.web!==void 0?{web:Wi(e.autor.web,"autor.web")}:{}};else throw i("Falta \xABautor\xBB (un nombre, o { nombre, web }).");if(!o.firmada){if(Ji(n))throw i("\xABnombre\xBB: \xABForgeNEX\xBB est\xE1 reservado a lo que publica ForgeNEX.");if(Ji(a.nombre))throw i("\xABautor\xBB: \xABForgeNEX\xBB est\xE1 reservado a lo que publica ForgeNEX.")}let s=e.icono===void 0?"puzzle":X(e.icono,"icono",cl,"un icono de lucide (\xABpuzzle\xBB)"),c=ge(ce(e.idiomas,"idiomas",30).map(($,M)=>X($,`idiomas[${M}]`,db,"un c\xF3digo de idioma (\xABes\xBB, \xABen\xBB, \xABpt-BR\xBB)")),$=>$,"idiomas"),d=null;if(e.compatible_crm!==void 0){let M=V(e.compatible_crm,"compatible_crm",80).split(/\s+/);if(M.length>2||!M.every(g=>sl.test(g)))throw i("\xABcompatible_crm\xBB: un rango (\xAB>=1.6.0-284\xBB, \xAB>=1.6.0-284 <2.0.0\xBB).");d=M.join(" ")}let u=e.licencia===void 0?null:V(e.licencia,"licencia",40),p=e.politica_datos===void 0?{}:{politica_datos:Wi(e.politica_datos,"politica_datos")},f=ge(ce(e.depende_de,"depende_de",20).map(($,M)=>{if(typeof $=="string")return{id:X($,`depende_de[${M}]`,sn,"el id de otra app"),version:null};if(!pe($))throw i(`\xABdepende_de[${M}]\xBB: el id de otra app, o { id, version }.`);ye($,["id","version"],`depende_de[${M}]`);let g=$.version===void 0?null:V($.version,`depende_de[${M}].version`,80);if(g!==null&&!g.split(/\s+/).every(x=>sl.test(x)))throw i(`\xABdepende_de[${M}].version\xBB: un rango (\xAB>=1.0.0\xBB).`);return{id:X($.id,`depende_de[${M}].id`,sn,"el id de otra app"),version:g}}),$=>$.id,"depende_de");if(f.some($=>$.id===t))throw i("\xABdepende_de\xBB: una app no depende de s\xED misma.");let h=_b(e.permisos),b=ge(ce(e.usa,"usa",20).map(($,M)=>{let g=`usa[${M}]`;if(typeof $=="string")return{...ll(X($,g,Bi,"un nombre de contrato (\xABtaller.citas\xBB)")),de:null};let x=ul($,g,["de"]),A=X($.de,`${g}.de`,sn,"el id de la app que lo ofrece (\xABcom.taller.vehiculos\xBB)");if(A===t)throw i(`\xAB${g}.de\xBB: una app no se usa a s\xED misma.`);return{...x,de:A}}),$=>`${$.de??""}/${$.contrato}`,"usa"),y=e.solucion===void 0||e.solucion===null?null:X(e.solucion,"solucion",Fi,"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 v=ge(ce(e.montajes,"montajes",20).map(($,M)=>{let g=`montajes[${M}]`;if(!pe($))throw i(`\xAB${g}\xBB: un objeto.`);ye($,["id","punto","entrada","titulo","icono","modulo","permiso","funciones"],g);let x=V($.punto,`${g}.punto`,20);if(!kt.includes(x))throw i(`\xAB${g}.punto\xBB: ${kt.join(", ")}.`);let A=null;if(br.has(x)){if(A=ao(V($.modulo,`${g}.modulo`,64)),!A)throw i(`\xAB${g}.modulo\xBB: el m\xF3dulo donde se cuelga.`);if(!(h.modulos[A]??[]).includes("ver"))throw i(`\xAB${g}\xBB: se cuelga de \xAB${$.modulo}\xBB, as\xED que \xABpermisos.modulos\xBB tiene que pedir verlo.`)}else if($.modulo!==void 0)throw i(`\xAB${g}.modulo\xBB: solo en ${[...br].join(", ")}.`);let k=$.permiso===void 0?null:V($.permiso,`${g}.permiso`,80);if(k!==null&&!dl(h,k))throw i(`\xAB${g}.permiso\xBB: \xAB${k}\xBB no est\xE1 en \xABpermisos.modulos\xBB.`);if(x==="publica"&&k!==null)throw i(`\xAB${g}.permiso\xBB: la p\xE1gina p\xFAblica no lleva permiso (la ve cualquiera con el enlace).`);let J;if(x==="publica")J=ge(ce($.funciones,`${g}.funciones`,10).map((F,G)=>X(F,`${g}.funciones[${G}]`,Io,"el nombre de una funci\xF3n")),F=>F,`${g}.funciones`);else if($.funciones!==void 0)throw i(`\xAB${g}.funciones\xBB: solo en el montaje \xABpublica\xBB.`);return{id:X($.id,`${g}.id`,/^[a-z][a-z0-9_-]{0,40}$/,"min\xFAsculas, n\xFAmeros, _ y -"),punto:x,entrada:X($.entrada,`${g}.entrada`,Fi,"un fichero del paquete (\xABinterfaz/index.html\xBB)"),titulo:V($.titulo,`${g}.titulo`,60),icono:$.icono===void 0?null:X($.icono,`${g}.icono`,cl,"un icono de lucide"),modulo:A,permiso:k,...J?{funciones:J}:{}}}),$=>$.id,"montajes");if(v.filter($=>$.punto==="publica").length>1)throw i("\xABmontajes\xBB: una app tiene como mucho una p\xE1gina p\xFAblica.");let w=ge(ce(e.funciones,"funciones",20).map(($,M)=>{let g=`funciones[${M}]`;if(!pe($))throw i(`\xAB${g}\xBB: un objeto.`);if(ye($,["nombre","titulo","descripcion","entrada","disparador","tope","red","parametros","salida"],g),!pe($.disparador))throw i(`\xAB${g}.disparador\xBB: { tipo, \u2026 }.`);ye($.disparador,["tipo","evento","cron"],`${g}.disparador`);let x=V($.disparador.tipo,`${g}.disparador.tipo`,20);if(!ln.includes(x))throw i(`\xAB${g}.disparador.tipo\xBB: ${ln.join(", ")}.`);let A={tipo:x};if(x==="evento"){let H=V($.disparador.evento,`${g}.disparador.evento`,80);if(!h.eventos.includes(H)&&!b.some(Qe=>Qe.eventos.includes(H)))throw i(`\xAB${g}.disparador.evento\xBB: \xAB${H}\xBB tiene que estar en \xABpermisos.eventos\xBB (o en los \xABeventos\xBB de un contrato de \xABusa\xBB).`);A.evento=H}if(x==="programada"){A.cron=X($.disparador.cron,`${g}.disparador.cron`,mb,"un cron de 5 campos (\xAB0 7 * * 1-5\xBB)");let H=Zc(A.cron);if(!H)throw i(`\xAB${g}.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(el(H)<z.cronMinutos)throw i(`\xAB${g}.disparador.cron\xBB: como mucho una vez cada ${z.cronMinutos} minutos.`)}let k=pe($.tope)?$.tope:{};$.tope!==void 0&&ye(k,["ms","memoria_mb"],`${g}.tope`);let J=k.ms===void 0?5e3:Number(k.ms),F=k.memoria_mb===void 0?64:Number(k.memoria_mb);if(!Number.isInteger(J)||J<z.ms.min||J>z.ms.max)throw i(`\xAB${g}.tope.ms\xBB: de ${z.ms.min} a ${z.ms.max}.`);if(!Number.isInteger(F)||F<z.memoriaMb.min||F>z.memoriaMb.max)throw i(`\xAB${g}.tope.memoria_mb\xBB: de ${z.memoriaMb.min} a ${z.memoriaMb.max}.`);let G=ce($.red,`${g}.red`,10).map((H,Qe)=>bl(H,`${g}.red[${Qe}]`,"un dominio"));for(let H of G)if(!Nb(h.red_hacia,H))throw i(`\xAB${g}.red\xBB: \xAB${H}\xBB tiene que estar en \xABpermisos.red_hacia\xBB.`);let Je=pl($.parametros,`${g}.parametros`),tt={},rt=ge(ce($.salida,`${g}.salida`,30).map((H,Qe)=>{let Ce=`${g}.salida[${Qe}]`;if(!pe(H))return X(H,Ce,Io,"nombres en min\xFAsculas y _ (o { clave, titulo })");ye(H,["clave","titulo"],Ce);let De=X(H.clave,`${Ce}.clave`,Io,"nombres en min\xFAsculas y _");return H.titulo!==void 0&&(tt[De]=V(H.titulo,`${Ce}.titulo`,60)),De}),H=>H,`${g}.salida`);if(x==="publica"&&G.length)throw i(`\xAB${g}.red\xBB: una funci\xF3n \xABpublica\xBB no sale a la red (solo lee el CRM).`);if(Object.keys(Je).length&&x!=="automatizacion")throw i(`\xAB${g}.parametros\xBB: solo en las de disparador \xABautomatizacion\xBB (las dem\xE1s reciben su evento, su minuto o su webhook).`);return{nombre:X($.nombre,`${g}.nombre`,Io,"min\xFAsculas, n\xFAmeros y _"),titulo:$.titulo===void 0?null:V($.titulo,`${g}.titulo`,80),descripcion:$.descripcion===void 0?null:V($.descripcion,`${g}.descripcion`,300,!1),entrada:X($.entrada,`${g}.entrada`,Fi,"un fichero del paquete (\xABfunciones/calcular.js\xBB)"),disparador:A,tope:{ms:J,memoria_mb:F},red:G,parametros:Je,salida:rt,titulos_salida:tt}}),$=>$.nombre,"funciones"),_=null;if(e.servidor!==void 0&&e.servidor!==null){if(!pe(e.servidor))throw i("\xABservidor\xBB: { url, webhooks }.");ye(e.servidor,["url","webhooks"],"Servidor");let $=ge(ce(e.servidor.webhooks,"servidor.webhooks",40).map((M,g)=>{if(typeof M!="string"||!h.eventos.includes(M))throw i(`\xABservidor.webhooks[${g}]\xBB: un evento que est\xE9 en \xABpermisos.eventos\xBB.`);return M}),M=>M,"servidor.webhooks");_={url:Wi(e.servidor.url,"servidor.url"),webhooks:$}}let C=new Set(w.map($=>$.nombre));for(let $ of v)for(let[M,g]of($.funciones??[]).entries()){let x=w.find(A=>A.nombre===g);if(!x)throw i(`\xABmontajes\xBB.\xAB${$.id}\xBB.funciones[${M}]: \xAB${g}\xBB tiene que estar en \xABfunciones\xBB.`);if(x.disparador.tipo!=="publica")throw i(`\xABmontajes\xBB.\xAB${$.id}\xBB.funciones[${M}]: \xAB${g}\xBB tiene que ser de disparador \xABpublica\xBB.`)}let S=ge(ce(e.herramientas_ia,"herramientas_ia",20).map(($,M)=>{let g=`herramientas_ia[${M}]`;if(!pe($))throw i(`\xAB${g}\xBB: un objeto.`);ye($,["nombre","descripcion","entrada","salida","riesgo","funcion","escribe","permiso"],g);let x=pl($.entrada,`${g}.entrada`),A=V($.riesgo,`${g}.riesgo`,10);if(!["bajo","medio","alto"].includes(A))throw i(`\xAB${g}.riesgo\xBB: bajo, medio o alto.`);let k=V($.funcion,`${g}.funcion`,41);if(!C.has(k))throw i(`\xAB${g}.funcion\xBB: \xAB${k}\xBB tiene que estar en \xABfunciones\xBB.`);if(!["herramienta","calculo"].includes(w.find(F=>F.nombre===k)?.disparador.tipo??""))throw i(`\xAB${g}.funcion\xBB: \xAB${k}\xBB tiene que ser de disparador \xABherramienta\xBB (o \xABcalculo\xBB).`);if($.escribe!==void 0&&typeof $.escribe!="boolean")throw i(`\xAB${g}.escribe\xBB: true o false.`);let J=null;if($.permiso!==void 0){let F=V($.permiso,`${g}.permiso`,80),G=F.lastIndexOf("."),Je=G>0?ao(F.slice(0,G)):null;if(!Je||!dl(h,F))throw i(`\xAB${g}.permiso\xBB: \xAB${F}\xBB no est\xE1 en \xABpermisos.modulos\xBB.`);J=`${Je}.${F.slice(G+1)}`}return{nombre:X($.nombre,`${g}.nombre`,/^[a-z][a-z0-9_]{2,40}$/,"min\xFAsculas, n\xFAmeros y _ (3 a 41)"),descripcion:V($.descripcion,`${g}.descripcion`,500),entrada:x,salida:ge(ce($.salida,`${g}.salida`,30).map((F,G)=>X(F,`${g}.salida[${G}]`,Io,"nombres de campo")),F=>F,`${g}.salida`),riesgo:A,funcion:k,escribe:$.escribe===!0,permiso:J}}),$=>$.nombre,"herramientas_ia"),P=ge(ce(e.ofrece,"ofrece",20).map(($,M)=>{let g=`ofrece[${M}]`;if(typeof $=="string")return ll(X($,g,Bi,"un nombre de contrato (\xABtaller.citas\xBB)"));let x=ul($,g,[]);for(let[A,k]of Object.entries(x.modulos)){if(!A.startsWith("mod_"))throw i(`\xAB${g}.modulos\xBB: \xAB${A}\xBB es de serie; un contrato solo comparte m\xF3dulos de la soluci\xF3n de la app.`);let J=h.modulos[A]??[],F=k.find(G=>!J.includes(G));if(F)throw i(`\xAB${g}.modulos.${A.slice(4)}\xBB: ofrece \xAB${F}\xBB y \xABpermisos.modulos\xBB no lo pide (nadie da lo que no tiene).`)}for(let A of x.eventos)if(!h.eventos.includes(A))throw i(`\xAB${g}.eventos\xBB: \xAB${A}\xBB tiene que estar en \xABpermisos.eventos\xBB.`);for(let A of x.herramientas){let k=S.find(J=>J.nombre===A);if(!k)throw i(`\xAB${g}.herramientas\xBB: \xAB${A}\xBB tiene que estar en \xABherramientas_ia\xBB.`);if(k.escribe)throw i(`\xAB${g}.herramientas\xBB: \xAB${A}\xBB escribe; un contrato solo comparte herramientas que consultan.`)}return x}),$=>$.contrato,"ofrece"),Z=ge(ce(e.ajustes,"ajustes",40).map(($,M)=>{let g=`ajustes[${M}]`;if(!pe($))throw i(`\xAB${g}\xBB: un objeto.`);ye($,["clave","etiqueta","tipo","opciones","requerido"],g);let x=V($.tipo,`${g}.tipo`,10);if(!un.includes(x))throw i(`\xAB${g}.tipo\xBB: ${un.join(", ")}.`);let A=ce($.opciones,`${g}.opciones`,50).map((k,J)=>{if(!pe(k))throw i(`\xAB${g}.opciones[${J}]\xBB: { valor, etiqueta }.`);return ye(k,["valor","etiqueta"],`${g}.opciones[${J}]`),{valor:V(k.valor,`${g}.opciones[${J}].valor`,60),etiqueta:V(k.etiqueta,`${g}.opciones[${J}].etiqueta`,80)}});if(x==="opcion"&&!A.length)throw i(`\xAB${g}.opciones\xBB: un ajuste de tipo opci\xF3n necesita sus opciones.`);if(x!=="opcion"&&A.length)throw i(`\xAB${g}.opciones\xBB: solo en los de tipo opci\xF3n.`);return{clave:X($.clave,`${g}.clave`,Io,"min\xFAsculas, n\xFAmeros y _"),etiqueta:V($.etiqueta,`${g}.etiqueta`,80),tipo:x,opciones:ge(A,k=>k.valor,`${g}.opciones`),requerido:$.requerido===!0}}),$=>$.clave,"ajustes"),we=ge(ce(e.secretos,"secretos",10).map(($,M)=>{let g=`secretos[${M}]`;if(!pe($))throw i(`\xAB${g}\xBB: un objeto.`);return ye($,["clave","etiqueta","descripcion"],g),{clave:X($.clave,`${g}.clave`,Io,"min\xFAsculas, n\xFAmeros y _"),etiqueta:V($.etiqueta,`${g}.etiqueta`,80),descripcion:V($.descripcion,`${g}.descripcion`,300,!1)}}),$=>$.clave,"secretos");return{formato:nt,formato_version:e.formato_version,id:t,nombre:n,descripcion:V(e.descripcion,"descripcion",500,!1),version:r,autor:a,icono:s,idiomas:c,compatible_crm:d,licencia:u,...p,depende_de:f,ofrece:P,usa:b,solucion:y,montajes:v,funciones:w,servidor:_,herramientas_ia:S,ajustes:Z,secretos:we,...e.conexiones!==void 0?{conexiones:Hc(e.conexiones)}:{},permisos:h}}var nt,dn,cn,Do,Lo,kt,pn,br,ln,un,il,al,lb,sn,ub,sl,cl,db,Bi,Io,pb,Fi,ml,mb,pe,fl,fb,W_,hb,hl,gl,bb,wb,Ui,Ji,ll,Nb,Pt=m(()=>{Xc();E();Kc();ol();gr();nl();nt="forgenex.extension",dn=1,cn=256e3,Do={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"]}},Lo=["ver","crear","editar","borrar"],kt=["pagina","ficha_pestana","ficha_bloque","inicio_bloque","accion_ficha","accion_tabla","vista","ajustes","publica"],pn=new Set(["pagina","ficha_pestana","ficha_bloque","inicio_bloque","accion_ficha","accion_tabla","vista","ajustes","publica"]),br=new Set(["ficha_pestana","ficha_bloque","accion_ficha","accion_tabla","vista"]),ln=["evento","programada","webhook","automatizacion","calculo","herramienta","publica"],un=["texto","numero","si_no","opcion","modulo","campo"],il=["registro.creado","registro.actualizado","registro.borrado"],al=["leer","escribir"],lb=new Set(["__proto__","constructor","prototype"]),sn=/^[a-z][a-z0-9-]{0,62}(\.[a-z0-9][a-z0-9-]{0,62}){1,6}$/,ub=/^(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})?$/,sl=/^(>=|<=|>|<|=|\^|~)?(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})?$/,cl=/^[a-z0-9-]{1,40}$/,db=/^[a-z]{2,3}(-[A-Z]{2})?$/,Bi=/^[a-z][a-z0-9_.-]{0,79}$/,Io=/^[a-z][a-z0-9_]{0,40}$/,pb=/^[a-z][a-z0-9_]{0,59}$/,Fi=/^(?!\/)(?!.*\/\/)(?!.*(^|\/)\.\.?(\/|$))[A-Za-z0-9_.\/-]{1,200}$/,ml=/^(\*\.)?([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/,mb=/^[0-9*,\/-]+( [0-9*,\/-]+){4}$/,pe=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);fl=String.raw`[\p{Cc}\p{Cf}\u2028\u2029\u034F\u115F\u1160\u2800\u3164\uFFA0]|(?<!\p{Emoji})[\uFE00-\uFE0F]|(?<=[0-9#*])[\uFE00-\uFE0F](?!\u20E3)`,fb=new RegExp(fl,"u"),W_=new RegExp(fl,"gu"),hb=new RegExp("(?<=\\p{Extended_Pictographic}[\\uFE0F\\p{Emoji_Modifier}]?)\\u200D(?=\\p{Extended_Pictographic})","gu");hl={\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"},gl={\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"},bb=new RegExp(`[${Object.keys(hl).join("")}]`,"gu"),wb=new RegExp(`[${Object.keys(gl).join("")}]`,"gu"),Ui=e=>e.normalize("NFKC").replace(bb,o=>hl[o]).toLowerCase().normalize("NFD").replace(new RegExp("\\p{M}","gu"),"").replace(wb,o=>gl[o]).replace(/[^\p{L}\p{N}]/gu,"");Ji=e=>{let o=vb(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};ll=e=>({contrato:e,titulo:null,modulos:{},eventos:[],herramientas:[]});Nb=(e,o)=>e.some(t=>t===o||t.startsWith("*.")&&o.endsWith(t.slice(1)))});function _o(e){return typeof e>"u"||e===void 0}function U(e){return typeof e=="string"}function so(e){return typeof e=="number"}function it(e){return typeof e=="boolean"}function at(e){return e===null}function Qi(e){return e instanceof Date}function st(e){return typeof e=="bigint"}function wl(e){return typeof Buffer<"u"&&Buffer.isBuffer(e)}function _e(e){return typeof e=="function"}function je(e){return typeof e=="object"&&e!==null}function l(e){return Object.freeze(e)}function wr(e){return qe(e)?e:[e]}function qe(e){return Array.isArray(e)}function vl(e){return e instanceof Error?e.message:String(e)}var N=m(()=>{});var J_,yl=m(()=>{N();J_=l({is(e){return e.kind==="AlterTableNode"},create(e){return l({kind:"AlterTableNode",table:e})},cloneWithTableProps(e,o){return l({...e,...o})},cloneWithColumnAlteration(e,o){return l({...e,columnAlterations:e.columnAlterations?[...e.columnAlterations,o]:[o]})}})});var T,ne=m(()=>{N();T=l({is(e){return e.kind==="IdentifierNode"},create(e){return l({kind:"IdentifierNode",name:e})}})});var K_,_l=m(()=>{N();ne();K_=l({is(e){return e.kind==="CreateIndexNode"},create(e){return l({kind:"CreateIndexNode",name:T.create(e)})},cloneWith(e,o){return l({...e,...o})},cloneWithColumns(e,o){return l({...e,columns:[...e.columns||[],...o]})}})});var t0,Nl=m(()=>{N();ne();t0=l({is(e){return e.kind==="CreateSchemaNode"},create(e,o){return l({kind:"CreateSchemaNode",schema:T.create(e),...o})},cloneWith(e,o){return l({...e,...o})}})});var i0,$l=m(()=>{N();i0=l({is(e){return e.kind==="CreateTableNode"},create(e){return l({kind:"CreateTableNode",table:e,columns:l([])})},cloneWithColumn(e,o){return l({...e,columns:l([...e.columns,o])})},cloneWithConstraint(e,o){return l({...e,constraints:e.constraints?l([...e.constraints,o]):l([o])})},cloneWithIndex(e,o){return l({...e,indexes:e.indexes?l([...e.indexes,o]):l([o])})},cloneWithFrontModifier(e,o){return l({...e,frontModifiers:e.frontModifiers?l([...e.frontModifiers,o]):l([o])})},cloneWithEndModifier(e,o){return l({...e,endModifiers:e.endModifiers?l([...e.endModifiers,o]):l([o])})},cloneWith(e,o){return l({...e,...o})}})});var Ge,ct=m(()=>{N();ne();Ge=l({is(e){return e.kind==="SchemableIdentifierNode"},create(e){return l({kind:"SchemableIdentifierNode",identifier:T.create(e)})},createWithSchema(e,o){return l({kind:"SchemableIdentifierNode",schema:T.create(e),identifier:T.create(o)})}})});var p0,xl=m(()=>{N();ct();p0=l({is(e){return e.kind==="DropIndexNode"},create(e,o){return l({kind:"DropIndexNode",name:Ge.create(e),...o})},cloneWith(e,o){return l({...e,...o})}})});var g0,Cl=m(()=>{N();ne();g0=l({is(e){return e.kind==="DropSchemaNode"},create(e,o){return l({kind:"DropSchemaNode",schema:T.create(e),...o})},cloneWith(e,o){return l({...e,...o})}})});var v0,jl=m(()=>{N();v0=l({is(e){return e.kind==="DropTableNode"},create(e,o){return l({kind:"DropTableNode",table:e,...o})},cloneWith(e,o){return l({...e,...o})}})});var Re,No=m(()=>{N();Re=l({is(e){return e.kind==="AliasNode"},create(e,o){return l({kind:"AliasNode",node:e,alias:o})}})});var Fo,vr=m(()=>{N();ct();Fo=l({is(e){return e.kind==="TableNode"},create(e){return l({kind:"TableNode",table:Ge.create(e)})},createWithSchema(e,o){return l({kind:"TableNode",table:Ge.createWithSchema(e,o)})}})});function ie(e){return je(e)&&_e(e.toOperationNode)}var ze=m(()=>{N()});function mn(e){return je(e)&&"expressionType"in e&&ie(e)}function Sl(e){return je(e)&&"expression"in e&&U(e.alias)&&ie(e)}var fn=m(()=>{ze();N()});var co,Gi=m(()=>{N();co=l({is(e){return e.kind==="SelectModifierNode"},create(e,o){return l({kind:"SelectModifierNode",modifier:e,of:o})},createWithExpression(e){return l({kind:"SelectModifierNode",rawModifier:e})}})});var ke,Wo=m(()=>{N();ke=l({is(e){return e.kind==="AndNode"},create(e,o){return l({kind:"AndNode",left:e,right:o})}})});var He,lt=m(()=>{N();He=l({is(e){return e.kind==="OrNode"},create(e,o){return l({kind:"OrNode",left:e,right:o})}})});var hn,Hi=m(()=>{N();Wo();lt();hn=l({is(e){return e.kind==="OnNode"},create(e){return l({kind:"OnNode",on:e})},cloneWithOperation(e,o,t){return l({...e,on:o==="And"?ke.create(e.on,t):He.create(e.on,t)})}})});var $o,yr=m(()=>{N();Hi();$o=l({is(e){return e.kind==="JoinNode"},create(e,o){return l({kind:"JoinNode",joinType:e,table:o,on:void 0})},createWithOn(e,o,t){return l({kind:"JoinNode",joinType:e,table:o,on:hn.create(t)})},cloneWithOn(e,o){return l({...e,on:e.on?hn.cloneWithOperation(e.on,"And",o):hn.create(o)})}})});var Bo,gn=m(()=>{N();Bo=l({is(e){return e.kind==="BinaryOperationNode"},create(e,o,t){return l({kind:"BinaryOperationNode",leftOperand:e,operator:o,rightOperand:t})}})});function Pl(e){return U(e)&&ql[e]}function Tl(e){return U(e)&&El[e]}function Ml(e){return U(e)&&kl[e]}var Ol,Q0,Al,G0,El,$b,ql,xb,Rl,H0,kl,Cb,X0,Xe,Tt=m(()=>{N();Ol=l({"=":!0,"==":!0,"!=":!0,"<>":!0,">":!0,">=":!0,"<":!0,"<=":!0,in:!0,"not in":!0,is:!0,"is not":!0,like:!0,"not like":!0,match:!0,ilike:!0,"not ilike":!0,"@>":!0,"<@":!0,"^@":!0,"&&":!0,"?":!0,"?&":!0,"?|":!0,"!<":!0,"!>":!0,"<=>":!0,"!~":!0,"~":!0,"~*":!0,"!~*":!0,"@@":!0,"@@@":!0,"!!":!0,"<->":!0,regexp:!0,"is distinct from":!0,"is not distinct from":!0}),Q0=Object.keys(Ol),Al=l({"+":!0,"-":!0,"*":!0,"/":!0,"%":!0,"^":!0,"&":!0,"|":!0,"#":!0,"<<":!0,">>":!0}),G0=Object.keys(Al),El=l({"->":!0,"->>":!0}),$b=Object.keys(El),ql=l({...Ol,...Al,"||":!0}),xb=Object.keys(ql),Rl=l({exists:!0,"not exists":!0}),H0=Object.keys(Rl),kl=l({...Rl,"-":!0,not:!0}),Cb=Object.keys(kl),X0=[...xb,...$b,...Cb,"between","between symmetric"],Xe=l({is(e){return e.kind==="OperatorNode"},create(e){return l({kind:"OperatorNode",operator:e})}})});var le,Ye=m(()=>{N();ne();le=l({is(e){return e.kind==="ColumnNode"},create(e){return l({kind:"ColumnNode",column:T.create(e)})}})});var bn,wn=m(()=>{N();bn=l({is(e){return e.kind==="SelectAllNode"},create(){return l({kind:"SelectAllNode"})}})});var Mt,vn=m(()=>{wn();N();Mt=l({is(e){return e.kind==="ReferenceNode"},create(e,o){return l({kind:"ReferenceNode",table:o,column:e})},createSelectAll(e){return l({kind:"ReferenceNode",table:e,column:bn.create()})}})});function yn(e){return je(e)&&ie(e)&&U(e.dynamicReference)}var _n=m(()=>{ze();N()});var Ke,Nn=m(()=>{N();Ke=l({is(e){return e.kind==="OrderByItemNode"},create(e,o){return l({kind:"OrderByItemNode",orderBy:e,direction:o})},cloneWith(e,o){return l({...e,...o})}})});var ue,ut=m(()=>{N();ue=l({is(e){return e.kind==="RawNode"},create(e,o){return l({kind:"RawNode",sqlFragments:l(e),parameters:l(o)})},createWithSql(e){return ue.create([e],[])},createWithChild(e){return ue.create(["",""],[e])},createWithChildren(e){return ue.create(new Array(e.length+1).fill(""),e)}})});var Il,Xi=m(()=>{N();ne();Il=l({is(e){return e.kind==="CollateNode"},create(e){return l({kind:"CollateNode",collation:T.create(e)})}})});var $n,Yi=m(()=>{Xi();Nn();ut();N();$n=class e{#e;constructor(o){this.#e=l(o)}desc(){return new e({node:Ke.cloneWith(this.#e.node,{direction:ue.createWithSql("desc")})})}asc(){return new e({node:Ke.cloneWith(this.#e.node,{direction:ue.createWithSql("asc")})})}nullsLast(){return new e({node:Ke.cloneWith(this.#e.node,{nulls:"last"})})}nullsFirst(){return new e({node:Ke.cloneWith(this.#e.node,{nulls:"first"})})}collate(o){return new e({node:Ke.cloneWith(this.#e.node,{collation:Il.create(o)})})}toOperationNode(){return this.#e.node}}});function It(e){Ll.has(e)||(Ll.add(e),console.log(e))}var Ll,Ki=m(()=>{Ll=new Set});function jb(e){return e==="asc"||e==="desc"}function Ze(e){if(e.length===2)return[Zi(e[0],e[1])];if(e.length===1){let[o]=e;return Array.isArray(o)?(It("orderBy(array) is deprecated, use multiple orderBy calls instead."),o.map(t=>Zi(t))):[Zi(o)]}throw new Error(`Invalid number of arguments at order by! expected 1-2, received ${e.length}`)}function Zi(e,o){let t=Sb(e);if(Ke.is(t)){if(o)throw new Error("Cannot specify direction twice!");return t}return Dl(t,o)}function Sb(e){if(dt(e))return Vo(e);if(yn(e))return e.toOperationNode();let[o,t]=e.split(" ");return t?(It("`orderBy('column asc')` is deprecated. Use `orderBy('column', 'asc')` instead."),Dl(Fe(o),t)):Fe(e)}function Dl(e,o){if(typeof o=="string"){if(!jb(o))throw new Error(`Invalid order by direction: ${o}`);return Ke.create(e,ue.createWithSql(o))}if(mn(o))return It("`orderBy(..., expr)` is deprecated. Use `orderBy(..., 'asc')` or `orderBy(..., (ob) => ...)` instead."),Ke.create(e,o.toOperationNode());let t=Ke.create(e);return o?o(new $n({node:t})).toOperationNode():t}var Lt=m(()=>{_n();fn();Nn();ut();Yi();Ki();pt();Pe()});var Dt,xn=m(()=>{N();Dt=l({is(e){return e.kind==="JSONReferenceNode"},create(e,o){return l({kind:"JSONReferenceNode",reference:e,traversal:o})},cloneWithTraversal(e,o){return l({...e,traversal:o})}})});var Cn,jn=m(()=>{N();Cn=l({is(e){return e.kind==="JSONOperatorChainNode"},create(e){return l({kind:"JSONOperatorChainNode",operator:e,values:l([])})},cloneWithValue(e,o){return l({...e,values:l([...e.values,o])})}})});var Uo,_r=m(()=>{N();Uo=l({is(e){return e.kind==="JSONPathNode"},create(e){return l({kind:"JSONPathNode",inOperator:e,pathLegs:l([])})},cloneWithLeg(e,o){return l({...e,pathLegs:l([...e.pathLegs,o])})}})});function Ob(e){return U(e)?Fe(e):e.toOperationNode()}function xo(e){return qe(e)?e.map(o=>me(o)):[me(e)]}function me(e){return dt(e)?Vo(e):Ob(e)}function zl(e,o){if(Tl(o))return Dt.create(Fe(e),Cn.create(Xe.create(o)));if(o==="->$"||o==="->>$")return Dt.create(Fe(e),Uo.create(Xe.create(o.slice(0,-1))));throw new Error(`Invalid JSON operator: ${o}`)}function Fe(e){if(!e.includes("."))return Mt.create(le.create(e));let t=e.split(".").map(Wl);if(t.length===3)return Ab(t);if(t.length===2)return Eb(t);throw new Error(`invalid column reference ${e}`)}function Fl(e){let o=" as ";if(e.includes(o)){let[t,n]=e.split(o).map(Wl);return Re.create(Fe(t),T.create(n))}else return Fe(e)}function Ab(e){let[o,t,n]=e;return Mt.create(le.create(n),Fo.createWithSchema(o,t))}function Eb(e){let[o,t]=e;return Mt.create(le.create(t),Fo.create(o))}function Wl(e){return e.trim()}var Pe=m(()=>{No();Ye();vn();vr();N();pt();ne();Tt();xn();jn();_r()});var Bl,ea=m(()=>{N();Bl=l({is(e){return e.kind==="PrimitiveValueListNode"},create(e){return l({kind:"PrimitiveValueListNode",values:l([...e])})}})});var Sn,On=m(()=>{N();Sn=l({is(e){return e.kind==="ValueListNode"},create(e){return l({kind:"ValueListNode",values:l(e)})}})});var Se,Jo=m(()=>{N();Se=l({is(e){return e.kind==="ValueNode"},create(e){return l({kind:"ValueNode",value:e})},createImmediate(e){return l({kind:"ValueNode",value:e,immediate:!0})}})});function Vl(e){return qe(e)?qb(e):Y(e)}function Y(e){return dt(e)?Vo(e):Se.create(e)}function An(e){return so(e)||it(e)||at(e)}function Nr(e){if(!An(e))throw new Error(`unsafe immediate value ${JSON.stringify(e)}`);return Se.createImmediate(e)}function qb(e){return e.some(dt)?Sn.create(e.map(o=>Y(o))):Bl.create(e)}var Co=m(()=>{ea();On();Jo();N();pt()});var Qo,$r=m(()=>{N();Qo=l({is(e){return e.kind==="ParensNode"},create(e){return l({kind:"ParensNode",node:e})}})});function de(e){if(e.length===3)return En(e[0],e[1],e[2]);if(e.length===1)return Y(e[0]);throw new Error(`invalid arguments: ${JSON.stringify(e)}`)}function En(e,o,t){return Rb(o)&&Jl(t)?Bo.create(me(e),oa(o),Se.createImmediate(t)):Bo.create(me(e),oa(o),Vl(t))}function Ne(e,o,t){return Bo.create(me(e),oa(o),me(t))}function ta(e,o){return qn(Object.entries(e).filter(([,t])=>!_o(t)).map(([t,n])=>En(t,Jl(n)?"is":"=",n)),o)}function qn(e,o,t=!0){let n=o==="and"?ke.create:He.create;if(e.length===0)return Bo.create(Se.createImmediate(1),Xe.create("="),Se.createImmediate(o==="and"?1:0));let r=Ul(e[0]);for(let a=1;a<e.length;++a)r=n(r,Ul(e[a]));return e.length>1&&t?Qo.create(r):r}function Rb(e){return e==="is"||e==="is not"}function Jl(e){return at(e)||it(e)}function oa(e){if(Pl(e))return Xe.create(e);if(ie(e))return e.toOperationNode();throw new Error(`invalid operator ${JSON.stringify(e)}`)}function Ul(e){return ie(e)?e.toOperationNode():e}var lo=m(()=>{gn();N();ze();Tt();Pe();Co();Jo();Wo();$r();lt()});var jo,xr=m(()=>{N();jo=l({is(e){return e.kind==="OrderByNode"},create(e){return l({kind:"OrderByNode",items:l([...e])})},cloneWithItems(e,o){return l({...e,items:l([...e.items,...o])})}})});var ra,na=m(()=>{N();ra=l({is(e){return e.kind==="PartitionByNode"},create(e){return l({kind:"PartitionByNode",items:l(e)})},cloneWithItems(e,o){return l({...e,items:l([...e.items,...o])})}})});var Cr,Rn=m(()=>{N();xr();na();Cr=l({is(e){return e.kind==="OverNode"},create(){return l({kind:"OverNode"})},cloneWithOrderByItems(e,o){return l({...e,orderBy:e.orderBy?jo.cloneWithItems(e.orderBy,o):jo.create(o)})},cloneWithPartitionByItems(e,o){return l({...e,partitionBy:e.partitionBy?ra.cloneWithItems(e.partitionBy,o):ra.create(o)})}})});var mt,jr=m(()=>{N();mt=l({is(e){return e.kind==="FromNode"},create(e){return l({kind:"FromNode",froms:l(e)})},cloneWithFroms(e,o){return l({...e,froms:l([...e.froms,...o])})}})});var ia,aa=m(()=>{N();ia=l({is(e){return e.kind==="GroupByNode"},create(e){return l({kind:"GroupByNode",items:l(e)})},cloneWithItems(e,o){return l({...e,items:l([...e.items,...o])})}})});var sa,ca=m(()=>{N();Wo();lt();sa=l({is(e){return e.kind==="HavingNode"},create(e){return l({kind:"HavingNode",having:e})},cloneWithOperation(e,o,t){return l({...e,having:o==="And"?ke.create(e.having,t):He.create(e.having,t)})}})});var Ql,la=m(()=>{N();Ql=l({is(e){return e.kind==="InsertQueryNode"},create(e,o,t){return l({kind:"InsertQueryNode",into:e,...o&&{with:o},replace:t})},createWithoutInto(){return l({kind:"InsertQueryNode"})},cloneWith(e,o){return l({...e,...o})}})});var Gl,ua=m(()=>{N();Gl=l({is(e){return e.kind==="ListNode"},create(e){return l({kind:"ListNode",items:l(e)})}})});var zt,kn=m(()=>{N();jr();ua();zt=l({is(e){return e.kind==="UpdateQueryNode"},create(e,o){return l({kind:"UpdateQueryNode",table:e.length===1?e[0]:Gl.create(e),...o&&{with:o}})},createWithoutTable(){return l({kind:"UpdateQueryNode"})},cloneWithFromItems(e,o){return l({...e,from:e.from?mt.cloneWithFroms(e.from,o):mt.create(o)})},cloneWithUpdates(e,o){return l({...e,updates:e.updates?l([...e.updates,...o]):o})},cloneWithLimit(e,o){return l({...e,limit:o})}})});var da,pa=m(()=>{N();da=l({is(e){return e.kind==="UsingNode"},create(e){return l({kind:"UsingNode",tables:l(e)})},cloneWithTables(e,o){return l({...e,tables:l([...e.tables,...o])})}})});var Ft,Pn=m(()=>{N();jr();pa();So();Ft=l({is(e){return e.kind==="DeleteQueryNode"},create(e,o){return l({kind:"DeleteQueryNode",from:mt.create(e),...o&&{with:o}})},cloneWithOrderByItems:(e,o)=>q.cloneWithOrderByItems(e,o),cloneWithoutOrderBy:e=>q.cloneWithoutOrderBy(e),cloneWithLimit(e,o){return l({...e,limit:o})},cloneWithoutLimit(e){return l({...e,limit:void 0})},cloneWithUsing(e,o){return l({...e,using:e.using!==void 0?da.cloneWithTables(e.using,o):da.create(o)})}})});var ve,Sr=m(()=>{N();Wo();lt();ve=l({is(e){return e.kind==="WhereNode"},create(e){return l({kind:"WhereNode",where:e})},cloneWithOperation(e,o,t){return l({...e,where:o==="And"?ke.create(e.where,t):He.create(e.where,t)})}})});var ma,fa=m(()=>{N();ma=l({is(e){return e.kind==="ReturningNode"},create(e){return l({kind:"ReturningNode",selections:l(e)})},cloneWithSelections(e,o){return l({...e,selections:e.selections?l([...e.selections,...o]):l(o)})}})});var Hl,ha=m(()=>{N();Hl=l({is(e){return e.kind==="ExplainNode"},create(e,o){return l({kind:"ExplainNode",format:e,options:o})}})});var Oo,Or=m(()=>{N();Oo=l({is(e){return e.kind==="WhenNode"},create(e){return l({kind:"WhenNode",condition:e})},cloneWithResult(e,o){return l({...e,result:o})}})});var Xl,ga=m(()=>{N();Or();Xl=l({is(e){return e.kind==="MergeQueryNode"},create(e,o){return l({kind:"MergeQueryNode",into:e,...o&&{with:o}})},cloneWithUsing(e,o){return l({...e,using:o})},cloneWithWhen(e,o){return l({...e,whens:e.whens?l([...e.whens,o]):l([o])})},cloneWithThen(e,o){return l({...e,whens:e.whens?l([...e.whens.slice(0,-1),Oo.cloneWithResult(e.whens[e.whens.length-1],o)]):void 0})}})});var ba,wa=m(()=>{N();ba=l({is(e){return e.kind==="OutputNode"},create(e){return l({kind:"OutputNode",selections:l(e)})},cloneWithSelections(e,o){return l({...e,selections:e.selections?l([...e.selections,...o]):l(o)})}})});var q,So=m(()=>{la();Ar();kn();Pn();Sr();N();fa();ha();ga();wa();xr();q=l({is(e){return K.is(e)||Ql.is(e)||zt.is(e)||Ft.is(e)||Xl.is(e)},cloneWithEndModifier(e,o){return l({...e,endModifiers:e.endModifiers?l([...e.endModifiers,o]):l([o])})},cloneWithWhere(e,o){return l({...e,where:e.where?ve.cloneWithOperation(e.where,"And",o):ve.create(o)})},cloneWithJoin(e,o){return l({...e,joins:e.joins?l([...e.joins,o]):l([o])})},cloneWithReturning(e,o){return l({...e,returning:e.returning?ma.cloneWithSelections(e.returning,o):ma.create(o)})},cloneWithoutReturning(e){return l({...e,returning:void 0})},cloneWithoutWhere(e){return l({...e,where:void 0})},cloneWithExplain(e,o,t){return l({...e,explain:Hl.create(o,t?.toOperationNode())})},cloneWithTop(e,o){return l({...e,top:o})},cloneWithOutput(e,o){return l({...e,output:e.output?ba.cloneWithSelections(e.output,o):ba.create(o)})},cloneWithOrderByItems(e,o){return l({...e,orderBy:e.orderBy?jo.cloneWithItems(e.orderBy,o):jo.create(o)})},cloneWithoutOrderBy(e){return l({...e,orderBy:void 0})}})});var K,Ar=m(()=>{N();jr();aa();ca();So();K=l({is(e){return e.kind==="SelectQueryNode"},create(e){return l({kind:"SelectQueryNode",...e&&{with:e}})},createFrom(e,o){return l({kind:"SelectQueryNode",from:mt.create(e),...o&&{with:o}})},cloneWithSelections(e,o){return l({...e,selections:e.selections?l([...e.selections,...o]):l(o)})},cloneWithDistinctOn(e,o){return l({...e,distinctOn:e.distinctOn?l([...e.distinctOn,...o]):l(o)})},cloneWithFrontModifier(e,o){return l({...e,frontModifiers:e.frontModifiers?l([...e.frontModifiers,o]):l([o])})},cloneWithOrderByItems:(e,o)=>q.cloneWithOrderByItems(e,o),cloneWithGroupByItems(e,o){return l({...e,groupBy:e.groupBy?ia.cloneWithItems(e.groupBy,o):ia.create(o)})},cloneWithLimit(e,o){return l({...e,limit:o})},cloneWithOffset(e,o){return l({...e,offset:o})},cloneWithFetch(e,o){return l({...e,fetch:o})},cloneWithHaving(e,o){return l({...e,having:e.having?sa.cloneWithOperation(e.having,"And",o):sa.create(o)})},cloneWithSetOperations(e,o){return l({...e,setOperations:e.setOperations?l([...e.setOperations,...o]):l([...o])})},cloneWithoutSelections(e){return l({...e,selections:[]})},cloneWithoutLimit(e){return l({...e,limit:void 0})},cloneWithoutOffset(e){return l({...e,offset:void 0})},cloneWithoutOrderBy:e=>q.cloneWithoutOrderBy(e),cloneWithoutGroupBy(e){return l({...e,groupBy:void 0})}})});var Tn,va=m(()=>{yr();ut();lo();N();Tn=class e{#e;constructor(o){this.#e=l(o)}on(...o){return new e({...this.#e,joinNode:$o.cloneWithOn(this.#e.joinNode,de(o))})}onRef(o,t,n){return new e({...this.#e,joinNode:$o.cloneWithOn(this.#e.joinNode,Ne(o,t,n))})}onTrue(){return new e({...this.#e,joinNode:$o.cloneWithOn(this.#e.joinNode,ue.createWithSql("true"))})}$call(o){return o(this)}toOperationNode(){return this.#e.joinNode}}});var Yl,ya=m(()=>{N();Yl=l({is(e){return e.kind==="PartitionByItemNode"},create(e){return l({kind:"PartitionByItemNode",partitionBy:e})}})});function Kl(e){return xo(e).map(Yl.create)}var Zl=m(()=>{ya();Pe()});var Mn,eu=m(()=>{Rn();So();Lt();Zl();N();Mn=class e{#e;constructor(o){this.#e=l(o)}orderBy(...o){return new e({overNode:Cr.cloneWithOrderByItems(this.#e.overNode,Ze(o))})}clearOrderBy(){return new e({overNode:q.cloneWithoutOrderBy(this.#e.overNode)})}partitionBy(o){return new e({overNode:Cr.cloneWithPartitionByItems(this.#e.overNode,Kl(o))})}$call(o){return o(this)}toOperationNode(){return this.#e.overNode}}});var Wt,_a=m(()=>{N();vn();wn();Wt=l({is(e){return e.kind==="SelectionNode"},create(e){return l({kind:"SelectionNode",selection:e})},createSelectAll(){return l({kind:"SelectionNode",selection:bn.create()})},createSelectAllFromTable(e){return l({kind:"SelectionNode",selection:Mt.createSelectAll(e)})}})});function Ao(e){return _e(e)?Ao(e(Eo())):qe(e)?e.map(o=>ou(o)):[ou(e)]}function ou(e){return U(e)?Wt.create(Fl(e)):yn(e)?Wt.create(e.toOperationNode()):Wt.create(In(e))}function uo(e){return e?Array.isArray(e)?e.map(tu):[tu(e)]:[Wt.createSelectAll()]}function tu(e){if(U(e))return Wt.createSelectAllFromTable($e(e));throw new Error(`invalid value selectAll expression: ${JSON.stringify(e)}`)}var Er=m(()=>{N();_a();Pe();_n();pt();po();Bt()});var iC,ru=m(()=>{N();iC=l({is(e){return e.kind==="ValuesNode"},create(e){return l({kind:"ValuesNode",values:l(e)})}})});var cC,nu=m(()=>{N();cC=l({is(e){return e.kind==="DefaultInsertValueNode"},create(){return l({kind:"DefaultInsertValueNode"})}})});var Na,$a=m(()=>{N();Na=l({is(e){return e.kind==="ColumnUpdateNode"},create(e,o){return l({kind:"ColumnUpdateNode",column:e,value:o})}})});function iu(...e){return e.length===2?[Na.create(me(e[0]),Y(e[1]))]:kb(e[0])}function kb(e){let o=_e(e)?e(Eo()):e;return Object.entries(o).filter(([t,n])=>n!==void 0).map(([t,n])=>Na.create(le.create(t),Y(n)))}var au=m(()=>{Ye();$a();Bt();N();Co();Pe()});var yC,su=m(()=>{N();yC=l({is(e){return e.kind==="OnDuplicateKeyNode"},create(e){return l({kind:"OnDuplicateKeyNode",updates:e})}})});var cu=m(()=>{});function Vt(e){return Object.prototype.hasOwnProperty.call(e,"prototype")}var Go,qr=m(()=>{Go=class extends Error{node;constructor(o){super("no result"),this.node=o}}});var jC,lu=m(()=>{N();Sr();jC=l({is(e){return e.kind==="OnConflictNode"},create(){return l({kind:"OnConflictNode"})},cloneWith(e,o){return l({...e,...o})},cloneWithIndexWhere(e,o){return l({...e,indexWhere:e.indexWhere?ve.cloneWithOperation(e.indexWhere,"And",o):ve.create(o)})},cloneWithIndexOrWhere(e,o){return l({...e,indexWhere:e.indexWhere?ve.cloneWithOperation(e.indexWhere,"Or",o):ve.create(o)})},cloneWithUpdateWhere(e,o){return l({...e,updateWhere:e.updateWhere?ve.cloneWithOperation(e.updateWhere,"And",o):ve.create(o)})},cloneWithUpdateOrWhere(e,o){return l({...e,updateWhere:e.updateWhere?ve.cloneWithOperation(e.updateWhere,"Or",o):ve.create(o)})},cloneWithoutIndexWhere(e){return l({...e,indexWhere:void 0})},cloneWithoutUpdateWhere(e){return l({...e,updateWhere:void 0})}})});var uu=m(()=>{});var du,xa=m(()=>{N();du=l({is(e){return e.kind==="TopNode"},create(e,o){return l({kind:"TopNode",expression:e,modifiers:o})}})});function Ut(e,o){if(!so(e)&&!st(e))throw new Error(`Invalid top expression: ${e}`);if(!_o(o)&&!Pb(o))throw new Error(`Invalid top modifiers: ${o}`);return du.create(e,o)}function Pb(e){return e==="percent"||e==="with ties"||e==="percent with ties"}var Ln=m(()=>{xa();N()});var TC,pu=m(()=>{N();TC=l({is(e){return e.kind==="OrActionNode"},create(e){return l({kind:"OrActionNode",action:e})}})});var mu=m(()=>{});var Dn,Ca=m(()=>{Dn=class{numDeletedRows;constructor(o){this.numDeletedRows=o}}});var Jt,Rr=m(()=>{N();Jt=l({is(e){return e.kind==="LimitNode"},create(e){return l({kind:"LimitNode",limit:e})}})});var ae,ja,fu=m(()=>{zn();po();Er();So();N();qr();Ca();Pn();Rr();Lt();lo();Co();Ln();ja=class{#e;constructor(o){this.#e=l(o)}where(...o){return new ae({...this.#e,queryNode:q.cloneWithWhere(this.#e.queryNode,de(o))})}whereRef(o,t,n){return new ae({...this.#e,queryNode:q.cloneWithWhere(this.#e.queryNode,Ne(o,t,n))})}clearWhere(){return new ae({...this.#e,queryNode:q.cloneWithoutWhere(this.#e.queryNode)})}top(o,t){return new ae({...this.#e,queryNode:q.cloneWithTop(this.#e.queryNode,Ut(o,t))})}using(o){return new ae({...this.#e,queryNode:Ft.cloneWithUsing(this.#e.queryNode,ft(o))})}innerJoin(...o){return this.#o("InnerJoin",o)}leftJoin(...o){return this.#o("LeftJoin",o)}rightJoin(...o){return this.#o("RightJoin",o)}fullJoin(...o){return this.#o("FullJoin",o)}#o(o,t){return new ae({...this.#e,queryNode:q.cloneWithJoin(this.#e.queryNode,Qt(o,t))})}returning(o){return new ae({...this.#e,queryNode:q.cloneWithReturning(this.#e.queryNode,Ao(o))})}returningAll(o){return new ae({...this.#e,queryNode:q.cloneWithReturning(this.#e.queryNode,uo(o))})}output(o){return new ae({...this.#e,queryNode:q.cloneWithOutput(this.#e.queryNode,Ao(o))})}outputAll(o){return new ae({...this.#e,queryNode:q.cloneWithOutput(this.#e.queryNode,uo(o))})}clearReturning(){return new ae({...this.#e,queryNode:q.cloneWithoutReturning(this.#e.queryNode)})}clearLimit(){return new ae({...this.#e,queryNode:Ft.cloneWithoutLimit(this.#e.queryNode)})}orderBy(...o){return new ae({...this.#e,queryNode:q.cloneWithOrderByItems(this.#e.queryNode,Ze(o))})}clearOrderBy(){return new ae({...this.#e,queryNode:q.cloneWithoutOrderBy(this.#e.queryNode)})}limit(o){return new ae({...this.#e,queryNode:Ft.cloneWithLimit(this.#e.queryNode,Jt.create(Y(o)))})}modifyEnd(o){return new ae({...this.#e,queryNode:q.cloneWithEndModifier(this.#e.queryNode,o.toOperationNode())})}$call(o){return o(this)}$if(o,t){return o?t(this):new ae({...this.#e})}$castTo(){return new ae(this.#e)}$narrowType(){return new ae(this.#e)}$assertType(){return new ae(this.#e)}withPlugin(o){return new ae({...this.#e,executor:this.#e.executor.withPlugin(o)})}toOperationNode(){return this.#e.executor.transformQuery(this.#e.queryNode,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(o){let t=this.compile(),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 Dn(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??Go;throw Vt(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 ae({...this.#e,queryNode:q.cloneWithExplain(this.#e.queryNode,o,t)}).execute()}};ae=ja});var Fn,Sa=m(()=>{Fn=class{numUpdatedRows;numChangedRows;constructor(o,t){this.numUpdatedRows=o,this.numChangedRows=t}}});var se,Oa,hu=m(()=>{zn();po();Er();So();kn();au();N();Sa();qr();lo();Co();Rr();Ln();Lt();Oa=class{#e;constructor(o){this.#e=l(o)}where(...o){return new se({...this.#e,queryNode:q.cloneWithWhere(this.#e.queryNode,de(o))})}whereRef(o,t,n){return new se({...this.#e,queryNode:q.cloneWithWhere(this.#e.queryNode,Ne(o,t,n))})}clearWhere(){return new se({...this.#e,queryNode:q.cloneWithoutWhere(this.#e.queryNode)})}top(o,t){return new se({...this.#e,queryNode:q.cloneWithTop(this.#e.queryNode,Ut(o,t))})}from(o){return new se({...this.#e,queryNode:zt.cloneWithFromItems(this.#e.queryNode,ft(o))})}innerJoin(...o){return this.#o("InnerJoin",o)}leftJoin(...o){return this.#o("LeftJoin",o)}rightJoin(...o){return this.#o("RightJoin",o)}fullJoin(...o){return this.#o("FullJoin",o)}#o(o,t){return new se({...this.#e,queryNode:q.cloneWithJoin(this.#e.queryNode,Qt(o,t))})}orderBy(...o){return new se({...this.#e,queryNode:q.cloneWithOrderByItems(this.#e.queryNode,Ze(o))})}clearOrderBy(){return new se({...this.#e,queryNode:q.cloneWithoutOrderBy(this.#e.queryNode)})}limit(o){return new se({...this.#e,queryNode:zt.cloneWithLimit(this.#e.queryNode,Jt.create(Y(o)))})}set(...o){return new se({...this.#e,queryNode:zt.cloneWithUpdates(this.#e.queryNode,iu(...o))})}returning(o){return new se({...this.#e,queryNode:q.cloneWithReturning(this.#e.queryNode,Ao(o))})}returningAll(o){return new se({...this.#e,queryNode:q.cloneWithReturning(this.#e.queryNode,uo(o))})}output(o){return new se({...this.#e,queryNode:q.cloneWithOutput(this.#e.queryNode,Ao(o))})}outputAll(o){return new se({...this.#e,queryNode:q.cloneWithOutput(this.#e.queryNode,uo(o))})}modifyEnd(o){return new se({...this.#e,queryNode:q.cloneWithEndModifier(this.#e.queryNode,o.toOperationNode())})}clearReturning(){return new se({...this.#e,queryNode:q.cloneWithoutReturning(this.#e.queryNode)})}$call(o){return o(this)}$if(o,t){return o?t(this):new se({...this.#e})}$castTo(){return new se(this.#e)}$narrowType(){return new se(this.#e)}$assertType(){return new se(this.#e)}withPlugin(o){return new se({...this.#e,executor:this.#e.executor.withPlugin(o)})}toOperationNode(){return this.#e.executor.transformQuery(this.#e.queryNode,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(o){let t=this.compile(),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 Fn(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??Go;throw Vt(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 se({...this.#e,queryNode:q.cloneWithExplain(this.#e.queryNode,o,t)}).execute()}};se=Oa});var yj,gu=m(()=>{N();Ye();vr();yj=l({is(e){return e.kind==="CommonTableExpressionNameNode"},create(e,o){return l({kind:"CommonTableExpressionNameNode",table:Fo.create(e),columns:o?l(o.map(le.create)):void 0})}})});var $j,bu=m(()=>{N();$j=l({is(e){return e.kind==="CommonTableExpressionNode"},create(e,o){return l({kind:"CommonTableExpressionNode",name:e,expression:o})},cloneWith(e,o){return l({...e,...o})}})});var jj,wu=m(()=>{N();jj=l({is(e){return e.kind==="WithNode"},create(e,o){return l({kind:"WithNode",expressions:l([e]),...o})},cloneWithExpression(e,o){return l({...e,expressions:l([...e.expressions,o])})}})});function Wn(e){let o="";for(let t=0;t<e;++t)o+=Tb();return o}function Tb(){return vu[~~(Math.random()*vu.length)]}var vu,Aa=m(()=>{vu=["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 Ea}var Ea,Bn=m(()=>{Aa();Ea=class{#e;get queryId(){return this.#e===void 0&&(this.#e=Wn(8)),this.#e}}});var yu=m(()=>{});var _u=m(()=>{});var Pj,Nu=m(()=>{N();Pj=l({is(e){return e.kind==="MatchedNode"},create(e,o=!1){return l({kind:"MatchedNode",not:e,bySource:o})}})});var Oe,kr=m(()=>{Oe=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 Vn(e,o){let t=new Oe,n=new Oe;return e.provideConnection(async r=>(t.resolve(r),await n.promise),o).catch(r=>t.reject(r)),l({connection:await t.promise,release:n.resolve})}var $u=m(()=>{kr();N()});function Cu(e="ignore query",o,t){if(e!=="ignore query"){if(e==="cancel query"){let n=o.cancelQuery;return n||(t(),xu(e,o.killSession?"kill session":void 0)),n.bind(o)}if(e==="kill session"){let n=o.killSession;return n||(t(),xu(e,o.cancelQuery?"cancel query":void 0)),n.bind(o)}throw t(),new Error(`Unexpected \`inflightQueryAbortStrategy\`: "${e}"`)}}function xu(e,o){throw new Error(`This dialect doesn't support \`inflightQueryAbortStrategy\` "${e}". Use "ignore query"${o?` or "${o}"`:""} instead.`)}function ht(e,o,t){e?.aborted&&(t?.(),gt(e.reason,o))}function gt(e,o){throw Mb(e,o),e}function bt(e){return o=>console.error(`\`${e}\` failed in the background after abortion: ${vl(o)}`)}function Mb(e,o){e!==null&&typeof e=="object"&&!Object.isFrozen(e)&&Object.defineProperty(e,"__kysely_timing__",{configurable:!0,enumerable:!1,value:o,writable:!1})}var mo,ju=m(()=>{N();mo={}});var Ib,Un,Su=m(()=>{N();$u();ju();kr();Ib=l([]),Un=class{#e;constructor(o=Ib){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)}ht(r,"before query execution"),t=l({signal:r});let{connection:a,release:s}=await Vn(this,t),c=this.provideConnection.bind(this),{promise:d,resolve:u}=new Oe,p=()=>u(mo);r.addEventListener("abort",p,{once:!0});try{ht(r,"before query execution",s);let f=Cu(n,a,s);if(f&&a.collectSessionInfo){ht(r,"before query execution",s);let w=a.collectSessionInfo();await Promise.race([d,w]).catch(C=>{throw s(),C})===mo&&(w.catch(bt("collectSessionInfo")).finally(s),gt(r.reason,"before query execution"))}let h=a.executeQuery(o,t),b=await Promise.race([d,h]).catch(w=>{throw s(),w});b===mo?(Promise.allSettled([h.catch(bt("query")),f?.(c).catch(bt("inflightQueryAbortHandler"))]).finally(s),gt(r.reason,"during query execution")):s();let y=this.#o(b,o.queryId,t),v=await Promise.race([d,y]);return v===mo&&(y.catch(bt("plugins.transformResult")),gt(r.reason,"during result transformation")),v}finally{u(mo),r.removeEventListener("abort",p)}}async*stream(o,t,n){let{signal:r}=n||{};if(!r){let{connection:b,release:y}=await Vn(this);try{for await(let v of b.streamQuery(o,t))yield await this.#o(v,o.queryId,n)}finally{y()}return}n=l({signal:r}),ht(r,"before connection acquisition");let{connection:a,release:s}=await Vn(this,n),{promise:c,resolve:d}=new Oe,u=()=>d(mo);r.addEventListener("abort",u,{once:!0});let p,f;ht(r,"before query streaming",s);let{queryId:h}=o;try{for(p=a.streamQuery(o,t,n);;){ht(r,"during query streaming");let b=p.next(),y=await Promise.race([c,b]);if(y===mo&&(f=b.catch(bt("iterator.next")),gt(r.reason,"during query streaming")),y.done)break;let v=this.#o(y.value,h,n),w=await Promise.race([c,v]);w===mo&&(f=v.catch(bt("plugins.transformResult")),gt(r.reason,"during result transformation")),yield w}}finally{d(mo),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(l({queryId:t,result:o,signal:r}));return o}}});var qa,Jn,Qn=m(()=>{Su();qa=class e extends Un{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([])}},Jn=new qa});var Ou=m(()=>{});var Au=m(()=>{});var Eu=m(()=>{});function qu(e,o){return new Tn({joinNode:$o.create(e,wt(o))})}function Ru(){return new Mn({overNode:Cr.create()})}var Ra=m(()=>{yr();Rn();va();eu();po()});function Qt(e,o){if(o.length===3)return Db(e,o[0],o[1],o[2]);if(o.length===2)return Lb(e,o[0],o[1]);if(o.length===1)return zb(e,o[0]);throw new Error("not implemented")}function Lb(e,o,t){return t(qu(e,o)).toOperationNode()}function Db(e,o,t,n){return $o.createWithOn(e,wt(o),Ne(t,"=",n))}function zb(e,o){return $o.create(e,wt(o))}var zn=m(()=>{yr();lo();Ra();po()});var ku,ka=m(()=>{N();ku=l({is(e){return e.kind==="OffsetNode"},create(e){return l({kind:"OffsetNode",offset:e})}})});var Pu,Pa=m(()=>{N();Pu=l({is(e){return e.kind==="GroupByItemNode"},create(e){return l({kind:"GroupByItemNode",groupBy:e})}})});function Tu(e){return e=_e(e)?e(Eo()):e,xo(e).map(Pu.create)}var Mu=m(()=>{Pa();Bt();N();Pe()});var Iu,Ta=m(()=>{N();Iu=l({is(e){return e.kind==="SetOperationNode"},create(e,o,t){return l({kind:"SetOperationNode",operator:e,expression:o,all:t})}})});function vt(e,o,t){return _e(o)&&(o=o(Ma())),qe(o)||(o=[o]),o.map(n=>Iu.create(e,Vo(n),t))}var Lu=m(()=>{Bt();Ta();N();pt()});var B,Pr,Ia,La,Gt=m(()=>{No();Wo();ne();ze();lt();$r();lo();B=class e{#e;constructor(o){this.#e=o}get expressionType(){}as(o){return new Pr(this,o)}or(...o){return new Ia(He.create(this.#e,de(o)))}and(...o){return new La(ke.create(this.#e,de(o)))}$castTo(){return new e(this.#e)}$notNull(){return new e(this.#e)}toOperationNode(){return this.#e}},Pr=class{#e;#o;constructor(o,t){this.#e=o,this.#o=t}get expression(){return this.#e}get alias(){return this.#o}toOperationNode(){return Re.create(this.#e.toOperationNode(),ie(this.#o)?this.#o.toOperationNode():T.create(this.#o))}},Ia=class e{#e;constructor(o){this.#e=o}get expressionType(){}as(o){return new Pr(this,o)}or(...o){return new e(He.create(this.#e,de(o)))}$castTo(){return new e(this.#e)}toOperationNode(){return Qo.create(this.#e)}},La=class e{#e;constructor(o){this.#e=o}get expressionType(){}as(o){return new Pr(this,o)}and(...o){return new e(ke.create(this.#e,de(o)))}$castTo(){return new e(this.#e)}toOperationNode(){return Qo.create(this.#e)}}});var Du,Da=m(()=>{N();Jo();Du=l({is(e){return e.kind==="FetchNode"},create(e,o){return{kind:"FetchNode",rowCount:Se.create(e),modifier:o}}})});function zu(e,o){if(!so(e)&&!st(e))throw new Error(`Invalid fetch row count: ${e}`);if(!Fb(o))throw new Error(`Invalid fetch modifier: ${o}`);return Du.create(e,o)}function Fb(e){return e==="only"||e==="with ties"}var Fu=m(()=>{Da();N()});function Wu(e){return new Gn(e)}var I,Gn,za,Fa=m(()=>{No();Gi();zn();po();Er();Pe();Ar();So();Lt();Rr();ka();N();Mu();qr();ne();Lu();lo();Gt();Co();Fu();Ln();Gn=class{#e;constructor(o){this.#e=l(o)}get expressionType(){}get isSelectQueryBuilder(){return!0}where(...o){return new I({...this.#e,queryNode:q.cloneWithWhere(this.#e.queryNode,de(o))})}whereRef(o,t,n){return new I({...this.#e,queryNode:q.cloneWithWhere(this.#e.queryNode,Ne(o,t,n))})}having(...o){return new I({...this.#e,queryNode:K.cloneWithHaving(this.#e.queryNode,de(o))})}havingRef(o,t,n){return new I({...this.#e,queryNode:K.cloneWithHaving(this.#e.queryNode,Ne(o,t,n))})}select(o){return new I({...this.#e,queryNode:K.cloneWithSelections(this.#e.queryNode,Ao(o))})}distinctOn(o){return new I({...this.#e,queryNode:K.cloneWithDistinctOn(this.#e.queryNode,xo(o))})}modifyFront(o){return new I({...this.#e,queryNode:K.cloneWithFrontModifier(this.#e.queryNode,co.createWithExpression(o.toOperationNode()))})}modifyEnd(o){return new I({...this.#e,queryNode:q.cloneWithEndModifier(this.#e.queryNode,co.createWithExpression(o.toOperationNode()))})}distinct(){return new I({...this.#e,queryNode:K.cloneWithFrontModifier(this.#e.queryNode,co.create("Distinct"))})}forUpdate(o){return new I({...this.#e,queryNode:q.cloneWithEndModifier(this.#e.queryNode,co.create("ForUpdate",o?wr(o).map($e):void 0))})}forShare(o){return new I({...this.#e,queryNode:q.cloneWithEndModifier(this.#e.queryNode,co.create("ForShare",o?wr(o).map($e):void 0))})}forKeyShare(o){return new I({...this.#e,queryNode:q.cloneWithEndModifier(this.#e.queryNode,co.create("ForKeyShare",o?wr(o).map($e):void 0))})}forNoKeyUpdate(o){return new I({...this.#e,queryNode:q.cloneWithEndModifier(this.#e.queryNode,co.create("ForNoKeyUpdate",o?wr(o).map($e):void 0))})}skipLocked(){return new I({...this.#e,queryNode:q.cloneWithEndModifier(this.#e.queryNode,co.create("SkipLocked"))})}noWait(){return new I({...this.#e,queryNode:q.cloneWithEndModifier(this.#e.queryNode,co.create("NoWait"))})}selectAll(o){return new I({...this.#e,queryNode:K.cloneWithSelections(this.#e.queryNode,uo(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 I({...this.#e,queryNode:q.cloneWithJoin(this.#e.queryNode,Qt(o,t))})}orderBy(...o){return new I({...this.#e,queryNode:q.cloneWithOrderByItems(this.#e.queryNode,Ze(o))})}groupBy(o){return new I({...this.#e,queryNode:K.cloneWithGroupByItems(this.#e.queryNode,Tu(o))})}limit(o){return new I({...this.#e,queryNode:K.cloneWithLimit(this.#e.queryNode,Jt.create(Y(o)))})}offset(o){return new I({...this.#e,queryNode:K.cloneWithOffset(this.#e.queryNode,ku.create(Y(o)))})}fetch(o,t="only"){return new I({...this.#e,queryNode:K.cloneWithFetch(this.#e.queryNode,zu(o,t))})}top(o,t){return new I({...this.#e,queryNode:q.cloneWithTop(this.#e.queryNode,Ut(o,t))})}union(o){return new I({...this.#e,queryNode:K.cloneWithSetOperations(this.#e.queryNode,vt("union",o,!1))})}unionAll(o){return new I({...this.#e,queryNode:K.cloneWithSetOperations(this.#e.queryNode,vt("union",o,!0))})}intersect(o){return new I({...this.#e,queryNode:K.cloneWithSetOperations(this.#e.queryNode,vt("intersect",o,!1))})}intersectAll(o){return new I({...this.#e,queryNode:K.cloneWithSetOperations(this.#e.queryNode,vt("intersect",o,!0))})}except(o){return new I({...this.#e,queryNode:K.cloneWithSetOperations(this.#e.queryNode,vt("except",o,!1))})}exceptAll(o){return new I({...this.#e,queryNode:K.cloneWithSetOperations(this.#e.queryNode,vt("except",o,!0))})}as(o){return new za(this,o)}clearSelect(){return new I({...this.#e,queryNode:K.cloneWithoutSelections(this.#e.queryNode)})}clearWhere(){return new I({...this.#e,queryNode:q.cloneWithoutWhere(this.#e.queryNode)})}clearLimit(){return new I({...this.#e,queryNode:K.cloneWithoutLimit(this.#e.queryNode)})}clearOffset(){return new I({...this.#e,queryNode:K.cloneWithoutOffset(this.#e.queryNode)})}clearOrderBy(){return new I({...this.#e,queryNode:q.cloneWithoutOrderBy(this.#e.queryNode)})}clearGroupBy(){return new I({...this.#e,queryNode:K.cloneWithoutGroupBy(this.#e.queryNode)})}$call(o){return o(this)}$if(o,t){return o?t(this):new I({...this.#e})}$castTo(){return new I(this.#e)}$narrowType(){return new I(this.#e)}$assertType(){return new I(this.#e)}$asTuple(){return new B(this.toOperationNode())}$asScalar(){return new B(this.toOperationNode())}withPlugin(o){return new I({...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??Go;throw Vt(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 I({...this.#e,queryNode:q.cloneWithExplain(this.#e.queryNode,o,t)}).execute()}};I=Gn;za=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 Re.create(this.#e.toOperationNode(),T.create(this.#o))}}});var fo,Hn=m(()=>{N();Sr();xr();fo=l({is(e){return e.kind==="AggregateFunctionNode"},create(e,o=[]){return l({kind:"AggregateFunctionNode",func:e,aggregated:o})},cloneWithDistinct(e){return l({...e,distinct:!0})},cloneWithOrderBy(e,o,t=!1){let n=t?"withinGroup":"orderBy";return l({...e,[n]:e[n]?jo.cloneWithItems(e[n],o):jo.create(o)})},cloneWithFilter(e,o){return l({...e,filter:e.filter?ve.cloneWithOperation(e.filter,"And",o):ve.create(o)})},cloneWithOrFilter(e,o){return l({...e,filter:e.filter?ve.cloneWithOperation(e.filter,"Or",o):ve.create(o)})},cloneWithOver(e,o){return l({...e,over:o})}})});var Wa,Ba=m(()=>{N();Wa=l({is(e){return e.kind==="FunctionNode"},create(e,o){return l({kind:"FunctionNode",func:e,arguments:o})}})});var Ht,Va,Ua=m(()=>{N();Hn();No();ne();Ra();lo();Lt();So();Ht=class e{#e;constructor(o){this.#e=l(o)}get expressionType(){}as(o){return new Va(this,o)}distinct(){return new e({...this.#e,aggregateFunctionNode:fo.cloneWithDistinct(this.#e.aggregateFunctionNode)})}orderBy(...o){return new e({...this.#e,aggregateFunctionNode:q.cloneWithOrderByItems(this.#e.aggregateFunctionNode,Ze(o))})}clearOrderBy(){return new e({...this.#e,aggregateFunctionNode:q.cloneWithoutOrderBy(this.#e.aggregateFunctionNode)})}withinGroupOrderBy(...o){return new e({...this.#e,aggregateFunctionNode:fo.cloneWithOrderBy(this.#e.aggregateFunctionNode,Ze(o),!0)})}filterWhere(...o){return new e({...this.#e,aggregateFunctionNode:fo.cloneWithFilter(this.#e.aggregateFunctionNode,de(o))})}filterWhereRef(o,t,n){return new e({...this.#e,aggregateFunctionNode:fo.cloneWithFilter(this.#e.aggregateFunctionNode,Ne(o,t,n))})}over(o){let t=Ru();return new e({...this.#e,aggregateFunctionNode:fo.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}},Va=class{#e;#o;constructor(o,t){this.#e=o,this.#o=t}get expression(){return this.#e}get alias(){return this.#o}toOperationNode(){return Re.create(this.#e.toOperationNode(),T.create(this.#o))}}});function Bu(){let e=(t,n)=>new B(Wa.create(t,xo(n??[]))),o=(t,n)=>new Ht({aggregateFunctionNode:fo.create(t,n?xo(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 Ht({aggregateFunctionNode:fo.create("count",uo(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 Ht({aggregateFunctionNode:fo.create("json_agg",[U(t)?$e(t):t.toOperationNode()])})},toJson(t){return new B(Wa.create("to_json",[U(t)?$e(t):t.toOperationNode()]))}})}var Ja=m(()=>{Gt();Hn();Ba();Pe();Er();Ua();N();po()});var Vu,Qa=m(()=>{N();Vu=l({is(e){return e.kind==="UnaryOperationNode"},create(e,o){return l({kind:"UnaryOperationNode",operator:e,operand:o})}})});function Uu(e,o){if(Ml(e))return Vu.create(Xe.create(e),me(o));throw new Error(`invalid unary operator ${JSON.stringify(e)}`)}var Ju=m(()=>{Tt();Qa();Pe()});var Ae,Xn=m(()=>{N();Or();Ae=l({is(e){return e.kind==="CaseNode"},create(e){return l({kind:"CaseNode",value:e})},cloneWithWhen(e,o){return l({...e,when:l(e.when?[...e.when,o]:[o])})},cloneWithThen(e,o){return l({...e,when:e.when?l([...e.when.slice(0,-1),Oo.cloneWithResult(e.when[e.when.length-1],o)]):void 0})},cloneWith(e,o){return l({...e,...o})}})});var Yn,Xt,Kn,Zn,Ga=m(()=>{Gt();N();Pe();Xn();Or();lo();Co();Yn=class{#e;constructor(o){this.#e=l(o)}when(...o){return new Xt({...this.#e,node:Ae.cloneWithWhen(this.#e.node,Oo.create(de(o)))})}whenRef(o,t,n){return new Xt({...this.#e,node:Ae.cloneWithWhen(this.#e.node,Oo.create(Ne(o,t,n)))})}},Xt=class{#e;constructor(o){this.#e=l(o)}then(o){return new Kn({...this.#e,node:Ae.cloneWithThen(this.#e.node,An(o)?Nr(o):Y(o))})}thenRef(o){return new Kn({...this.#e,node:Ae.cloneWithThen(this.#e.node,me(o))})}},Kn=class{#e;constructor(o){this.#e=l(o)}when(...o){return new Xt({...this.#e,node:Ae.cloneWithWhen(this.#e.node,Oo.create(de(o)))})}whenRef(o,t,n){return new Xt({...this.#e,node:Ae.cloneWithWhen(this.#e.node,Oo.create(Ne(o,t,n)))})}else(o){return new Zn({...this.#e,node:Ae.cloneWith(this.#e.node,{else:An(o)?Nr(o):Y(o)})})}elseRef(o){return new Zn({...this.#e,node:Ae.cloneWith(this.#e.node,{else:me(o)})})}end(){return new B(Ae.cloneWith(this.#e.node,{isStatement:!1}))}endCase(){return new B(Ae.cloneWith(this.#e.node,{isStatement:!0}))}},Zn=class{#e;constructor(o){this.#e=l(o)}end(){return new B(Ae.cloneWith(this.#e.node,{isStatement:!1}))}endCase(){return new B(Ae.cloneWith(this.#e.node,{isStatement:!0}))}}});var Ha,Xa=m(()=>{N();Ha=l({is(e){return e.kind==="JSONPathLegNode"},create(e,o){return l({kind:"JSONPathLegNode",type:e,value:o})}})});var Wb,Yt,ei,Ya,Ka=m(()=>{No();ne();jn();Xa();_r();xn();ze();Jo();Wb=/^#-\d+$/,Yt=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"&&!Wb.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 Dt.is(this.#e)?new ei(Dt.cloneWithTraversal(this.#e,Uo.is(this.#e.traversal)?Uo.cloneWithLeg(this.#e.traversal,Ha.create(o,t)):Cn.cloneWithValue(this.#e.traversal,Se.createImmediate(t)))):new ei(Uo.cloneWithLeg(this.#e,Ha.create(o,t)))}},ei=class e extends Yt{#e;constructor(o){super(o),this.#e=o}get expressionType(){}as(o){return new Ya(this,o)}$castTo(){return new e(this.#e)}$notNull(){return new e(this.#e)}toOperationNode(){return this.#e}},Ya=class{#e;#o;constructor(o,t){this.#e=o,this.#o=t}get expression(){return this.#e}get alias(){return this.#o}toOperationNode(){return Re.create(this.#e.toOperationNode(),ie(this.#o)?this.#o.toOperationNode():T.create(this.#o))}}});var Za,es=m(()=>{N();Za=l({is(e){return e.kind==="TupleNode"},create(e){return l({kind:"TupleNode",values:l(e)})}})});function Gu(e){return Bb[e]||Vb.some(o=>o.test(e))}var Bb,Vb,Qu,os=m(()=>{N();Bb=l({bigint:!0,bigserial:!0,binary:!0,blob:!0,boolean:!0,bytea:!0,char:!0,date:!0,datemultirange:!0,daterange:!0,datetime:!0,datetime2:!0,decimal:!0,"double precision":!0,float4:!0,float8:!0,int2:!0,int4:!0,int4multirange:!0,int4range:!0,int8:!0,int8multirange:!0,int8range:!0,integer:!0,json:!0,jsonb:!0,numeric:!0,nummultirange:!0,numrange:!0,real:!0,serial:!0,smallint:!0,text:!0,time:!0,timestamp:!0,timestamptz:!0,timetz:!0,tsmultirange:!0,tsrange:!0,tstzmultirange:!0,tstzrange:!0,uuid:!0,varbinary:!0,varchar:!0}),Vb=l([/^varchar\(\d+\)$/,/^char\(\d+\)$/,/^decimal\(\d+, \d+\)$/,/^numeric\(\d+, \d+\)$/,/^binary\(\d+\)$/,/^datetime\(\d+\)$/,/^time\(\d+\)$/,/^timetz\(\d+\)$/,/^timestamp\(\d+\)$/,/^timestamptz\(\d+\)$/,/^datetime2\(\d+\)$/,/^varbinary\(\d+\)$/]),Qu=l({is(e){return e.kind==="DataTypeNode"},create(e){return l({kind:"DataTypeNode",dataType:e})}})});function Hu(e){if(ie(e))return e.toOperationNode();if(Gu(e))return Qu.create(e);throw new Error(`invalid column data type ${JSON.stringify(e)}`)}var Xu=m(()=>{os();ze()});var Yu,ts=m(()=>{N();Yu=l({is(e){return e.kind==="CastNode"},create(e,o){return l({kind:"CastNode",expression:e,dataType:o})}})});function Ma(e=Jn){function o(r,a,s){return new B(En(r,a,s))}function t(r,a){return new B(Uu(r,a))}let n=Object.assign(o,{fn:void 0,eb:void 0,selectFrom(r){return Wu({queryId:Te(),executor:e,queryNode:K.createFrom(ft(r))})},case(r){return new Yn({node:Ae.create(_o(r)?void 0:me(r))})},ref(r,a){return _o(a)?new B(Fe(r)):new Yt(zl(r,a))},jsonPath(){return new Yt(Uo.create())},table(r){return new B($e(r))},val(r){return new B(Y(r))},refTuple(...r){return new B(Za.create(r.map(me)))},tuple(...r){return new B(Za.create(r.map(Y)))},lit(r){return new B(Nr(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 B(Bo.create(me(r),Xe.create("between"),ke.create(Y(a),Y(s))))},betweenSymmetric(r,a,s){return new B(Bo.create(me(r),Xe.create("between symmetric"),ke.create(Y(a),Y(s))))},and(r){return qe(r)?new B(qn(r,"and")):new B(ta(r,"and"))},or(r){return qe(r)?new B(qn(r,"or")):new B(ta(r,"or"))},parens(...r){let a=de(r);return Qo.is(a)?new B(a):new B(Qo.create(a))},cast(r,a){return new B(Yu.create(me(r),Hu(a)))}});return n.fn=Bu(),n.eb=n,n}function Eo(e){return Ma()}var Bt=m(()=>{Fa();Ar();po();Bn();Ja();Pe();lo();$r();Gt();Tt();Ju();Co();Qn();Ga();Xn();N();Ka();gn();Wo();es();_r();Xu();ts()});function Vo(e){if(ie(e))return e.toOperationNode();if(_e(e))return e(Eo()).toOperationNode();throw new Error(`invalid expression: ${JSON.stringify(e)}`)}function In(e){if(ie(e))return e.toOperationNode();if(_e(e))return e(Eo()).toOperationNode();throw new Error(`invalid aliased expression: ${JSON.stringify(e)}`)}function dt(e){return mn(e)||Sl(e)||_e(e)}var pt=m(()=>{fn();ze();Bt();N()});function Ku(e){return je(e)&&ie(e)&&U(e.table)&&U(e.alias)}var rs=m(()=>{ze();N()});function ft(e){return qe(e)?e.map(o=>wt(o)):[wt(e)]}function wt(e){return U(e)?Ub(e):Ku(e)?e.toOperationNode():In(e)}function Ub(e){let o=" as ";if(e.includes(o)){let[t,n]=e.split(o).map(Zu);return Re.create($e(t),T.create(n))}else return $e(e)}function $e(e){if(e.includes(".")){let[t,n]=e.split(".").map(Zu);return Fo.createWithSchema(t,n)}else return Fo.create(e)}function Zu(e){return e.trim()}var po=m(()=>{N();No();vr();pt();ne();rs()});var eE,ed=m(()=>{N();eE=l({is(e){return e.kind==="AddColumnNode"},create(e){return l({kind:"AddColumnNode",column:e})}})});var nE,od=m(()=>{N();Ye();nE=l({is(e){return e.kind==="ColumnDefinitionNode"},create(e,o){return l({kind:"ColumnDefinitionNode",column:le.create(e),dataType:o})},cloneWithFrontModifier(e,o){return l({...e,frontModifiers:e.frontModifiers?l([...e.frontModifiers,o]):[o]})},cloneWithEndModifier(e,o){return l({...e,endModifiers:e.endModifiers?l([...e.endModifiers,o]):[o]})},cloneWith(e,o){return l({...e,...o})}})});var cE,td=m(()=>{N();Ye();cE=l({is(e){return e.kind==="DropColumnNode"},create(e){return l({kind:"DropColumnNode",column:le.create(e)})},cloneWith(e,o){return l({...e,...o})}})});var pE,rd=m(()=>{N();Ye();pE=l({is(e){return e.kind==="RenameColumnNode"},create(e,o){return l({kind:"RenameColumnNode",column:le.create(e),renameTo:le.create(o)})}})});var gE,nd=m(()=>{N();ne();gE=l({is(e){return e.kind==="CheckConstraintNode"},create(e,o){return l({kind:"CheckConstraintNode",expression:e,name:o?T.create(o):void 0})}})});var Jb,vE,id,ns=m(()=>{N();Jb=l({cascade:!0,"no action":!0,restrict:!0,"set default":!0,"set null":!0}),vE=Object.keys(Jb),id=l({is(e){return e.kind==="ReferencesNode"},create(e,o){return l({kind:"ReferencesNode",table:e,columns:l([...o])})},cloneWithOnDelete(e,o){return l({...e,onDelete:o})},cloneWithOnUpdate(e,o){return l({...e,onUpdate:o})}})});var NE,ad=m(()=>{N();NE=l({is(e){return e.kind==="GeneratedNode"},create(e){return l({kind:"GeneratedNode",...e})},createWithExpression(e){return l({kind:"GeneratedNode",always:!0,expression:e})},cloneWith(e,o){return l({...e,...o})}})});var CE,sd=m(()=>{N();CE=l({is(e){return e.kind==="DefaultValueNode"},create(e){return l({kind:"DefaultValueNode",defaultValue:e})}})});var cd=m(()=>{});var AE,ld=m(()=>{N();AE=l({is(e){return e.kind==="ModifyColumnNode"},create(e){return l({kind:"ModifyColumnNode",column:e})}})});var PE,ud=m(()=>{N();ne();ns();PE=l({is(e){return e.kind==="ForeignKeyConstraintNode"},create(e,o,t,n){return l({kind:"ForeignKeyConstraintNode",columns:e,references:id.create(o,t),name:n?T.create(n):void 0})},cloneWith(e,o){return l({...e,...o})}})});var dd=m(()=>{});var LE,pd=m(()=>{N();LE=l({is(e){return e.kind==="AddConstraintNode"},create(e){return l({kind:"AddConstraintNode",constraint:e})}})});var VE,md=m(()=>{Ki();N();Ye();ne();VE=l({is(e){return e.kind==="UniqueConstraintNode"},create(e,o,t){return U(e.at(0))&&(It("`UniqueConstraintNode.create(columns: string[], ...)` is deprecated - pass `ColumnNode[]` instead."),e=e.map(le.create)),l({kind:"UniqueConstraintNode",columns:l(e),name:o?T.create(o):void 0,nullsNotDistinct:t})},cloneWith(e,o){return l({...e,...o})}})});var GE,fd=m(()=>{N();ne();GE=l({is(e){return e.kind==="DropConstraintNode"},create(e){return l({kind:"DropConstraintNode",constraintName:T.create(e)})},cloneWith(e,o){return l({...e,...o})}})});var KE,hd=m(()=>{N();Ye();KE=l({is(e){return e.kind==="AlterColumnNode"},create(e,o,t){return l({kind:"AlterColumnNode",column:le.create(e),[o]:t})}})});var gd=m(()=>{});var nq,bd=m(()=>{N();Ye();ne();nq=l({is(e){return e.kind==="PrimaryKeyConstraintNode"},create(e,o){return l({kind:"PrimaryKeyConstraintNode",columns:l(e.map(le.create)),name:o?T.create(o):void 0})},cloneWith(e,o){return l({...e,...o})}})});var cq,wd=m(()=>{N();ne();cq=l({is(e){return e.kind==="AddIndexNode"},create(e){return l({kind:"AddIndexNode",name:T.create(e)})},cloneWith(e,o){return l({...e,...o})},cloneWithColumns(e,o){return l({...e,columns:[...e.columns||[],...o]})}})});var pq,vd=m(()=>{N();ne();pq=l({is(e){return e.kind==="RenameConstraintNode"},create(e,o){return l({kind:"RenameConstraintNode",oldName:T.create(e),newName:T.create(o)})}})});var yd=m(()=>{});var _d=m(()=>{});var Nd=m(()=>{});var $d=m(()=>{});var xd=m(()=>{});var Cd=m(()=>{});var jd=m(()=>{});var Sd=m(()=>{});var xq,Od=m(()=>{N();ct();xq=l({is(e){return e.kind==="CreateViewNode"},create(e){return l({kind:"CreateViewNode",name:Ge.create(e)})},cloneWith(e,o){return l({...e,...o})}})});var Ad=m(()=>{});var Aq,Ed=m(()=>{N();ct();Aq=l({is(e){return e.kind==="DropViewNode"},create(e){return l({kind:"DropViewNode",name:Ge.create(e)})},cloneWith(e,o){return l({...e,...o})}})});var qd=m(()=>{});var Tq,Rd=m(()=>{N();On();Jo();Tq=l({is(e){return e.kind==="CreateTypeNode"},create(e){return l({kind:"CreateTypeNode",name:e})},cloneWithEnum(e,o){return l({...e,enum:Sn.create(o.map(Se.createImmediate))})}})});var kd=m(()=>{});var Dq,Pd=m(()=>{N();Dq=l({is(e){return e.kind==="DropTypeNode"},create(e){return Array.isArray(e)||(e=[e]),l({kind:"DropTypeNode",name:e[0],additionalNames:e.slice(1)})},cloneWith(e,o){return l({...e,...o})}})});var Td=m(()=>{});var Vq,Md=m(()=>{N();ct();Vq=l({is(e){return e.kind==="RefreshMaterializedViewNode"},create(e){return l({kind:"RefreshMaterializedViewNode",name:Ge.create(e)})},cloneWith(e,o){return l({...e,...o})}})});var Id=m(()=>{});var Gq,Ld=m(()=>{N();Gq=l({is(e){return e.kind==="AlterTypeNode"},create(e){return l({kind:"AlterTypeNode",name:e})},cloneWith(e,o){return l({...e,...o})}})});var Yq,Dd=m(()=>{N();Yq=l({is(e){return e.kind==="AddValueNode"},create(e){return l({kind:"AddValueNode",value:e})},cloneWith(e,o){return l({...e,...o})}})});var zd=m(()=>{});var oR,Fd=m(()=>{N();oR=l({is(e){return e.kind==="RenameValueNode"},create(e,o){return l({kind:"RenameValueNode",oldValue:e,newValue:o})}})});var Wd=m(()=>{});var Bd=m(()=>{});var Vd=m(()=>{});var Ud=m(()=>{});var Jd=m(()=>{});var Qd=m(()=>{});var Qb,uR,Gd=m(()=>{N();Qb=["query","error"],uR=l(Qb)});var Hd=m(()=>{});var Xd=m(()=>{Symbol.asyncDispose??=Symbol("Symbol.asyncDispose")});function qo(e){return new is(e)}var is,as,ss=m(()=>{No();N();Qn();ne();ze();is=class e{#e;constructor(o){this.#e=l(o)}get expressionType(){}get isRawBuilder(){return!0}as(o){return new as(this,o)}$castTo(){return new e({...this.#e})}$notNull(){return new e(this.#e)}withPlugin(o){return new e({...this.#e,plugins:this.#e.plugins!==void 0?l([...this.#e.plugins,o]):l([o])})}toOperationNode(){return this.#r(this.#o())}compile(o){return this.#t(this.#o(o))}async execute(o,t){let n=this.#o(o);return n.executeQuery(this.#t(n),t)}#o(o){let t=o!==void 0?o.getExecutor():Jn;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)}};as=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 Re.create(this.#e.toOperationNode(),ie(this.#o)?this.#o.toOperationNode():T.create(this.#o))}}});function Yd(e){return ie(e)?e.toOperationNode():Y(e)}var O,Kd=m(()=>{ne();ze();ut();Jo();Pe();po();Co();Bn();ss();O=Object.assign((e,...o)=>qo({queryId:Te(),rawNode:ue.create(e,o?.map(Yd)??[])}),{ref(e){return qo({queryId:Te(),rawNode:ue.createWithChild(Fe(e))})},val(e){return qo({queryId:Te(),rawNode:ue.createWithChild(Y(e))})},table(e){return qo({queryId:Te(),rawNode:ue.createWithChild($e(e))})},id(...e){let o=new Array(e.length+1).fill(".");return o[0]="",o[o.length-1]="",qo({queryId:Te(),rawNode:ue.create(o,e.map(T.create))})},lit(e){return qo({queryId:Te(),rawNode:ue.createWithChild(Se.createImmediate(e))})},raw(e){return qo({queryId:Te(),rawNode:ue.createWithSql(e)})},join(e,o=O`, `){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 qo({queryId:Te(),rawNode:ue.createWithChildren(t)})}})});var Zd=m(()=>{});var RR,kR,PR,cs=m(()=>{N();RR=l({ForKeyShare:"for key share",ForNoKeyUpdate:"for no key update",ForUpdate:"for update",ForShare:"for share",NoWait:"nowait",SkipLocked:"skip locked",Distinct:"distinct"}),kR=l({ForKeyShare:1,ForNoKeyUpdate:1,ForUpdate:1,ForShare:1,NoWait:2,SkipLocked:2,Distinct:0}),PR=l({InnerJoin:"inner join",LeftJoin:"left join",RightJoin:"right join",FullJoin:"full join",CrossJoin:"cross join",LateralInnerJoin:"inner join lateral",LateralLeftJoin:"left join lateral",LateralCrossJoin:"cross join lateral",OuterApply:"outer apply",CrossApply:"cross apply",Using:"using"})});var yt,Tr=m(()=>{ut();N();Bn();yt=l({raw(e,o=[]){return l({sql:e,query:ue.createWithSql(e),parameters:l(o),queryId:Te()})}})});var ep=m(()=>{});var op=m(()=>{});var tp=m(()=>{});var rp=m(()=>{});var np=m(()=>{});var ip=m(()=>{});var ap=m(()=>{});function Ho(e,o){if(Gb(e)&&o.stack){let t=o.stack.split(`
|
|
3
|
+
var bb=Object.defineProperty;var f=(e,o,t)=>()=>{if(t)throw t[0];try{return e&&(o=e(e=0)),o}catch(n){throw t=[n],n}};var ll=(e,o)=>{for(var t in o)bb(e,t,{get:o[t],enumerable:!0})};import{AsyncLocalStorage as _b}from"node:async_hooks";import{readdirSync as Nb}from"node:fs";import{createRequire as $b}from"node:module";import{fileURLToPath as xb}from"node:url";function co(e,o){let n=dl[e]?.[o];if(n!==void 0)return n;for(let r of Sb[e]??[]){let a=r.regex.exec(o);if(a)return r.traduccion.replace(/%\{([\w]+)\}/g,(s,c)=>{let d=r.nombres.indexOf(c);return d<0?s:a[d+1]})}return o}var Cb,jb,dl,Sb,Ob,Lo,mn=f(()=>{Cb=Nb(new URL("./locales/",import.meta.url)).filter(e=>/\.(?:ts|js)$/.test(e)&&!e.endsWith(".d.ts")),jb=$b(import.meta.url),dl=Object.fromEntries(Cb.map(e=>[e.replace(/\.(?:ts|js)$/,""),jb(xb(new URL(`./locales/${e}`,import.meta.url))).default])),Sb=Object.fromEntries(Object.entries(dl).map(([e,o])=>[e,Object.entries(o).filter(([t])=>t.includes("%{")).map(([t,n])=>{let r=[],a=0,s="";for(let c of t.matchAll(/%\{([\w]+)\}/g)){let d=c.index;s+=t.slice(a,d).replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"([\\s\\S]*?)",r.push(c[1]),a=d+c[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)])),Ob=new _b,Lo=()=>Ob.getStore()?.idioma??"es"});var z,i,q=f(()=>{mn();z=class extends Error{constructor(t,n,r,a=!0,s){super(a?co(Lo(),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)});import{inflateRawSync as Ab}from"node:zlib";function Eb(e){let o=Buffer.from(e.buffer,e.byteOffset,e.byteLength);if(o.length>ea)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>ml)throw i(`El paquete trae m\xE1s de ${ml} ficheros.`);let s=new Map,c=r;for(let d=0;d<n;d++){if(c+46>t||o.readUInt32LE(c)!==33639248)throw i("El .zip est\xE1 da\xF1ado.");let u=o.readUInt16LE(c+8),p=o.readUInt16LE(c+10),m=o.readUInt32LE(c+20),h=o.readUInt32LE(c+24),b=o.readUInt16LE(c+28),y=o.readUInt16LE(c+30),v=o.readUInt16LE(c+32);if((o.readUInt32LE(c+38)>>>16&61440)===40960)throw i("El paquete no admite enlaces simb\xF3licos.");let N=o.readUInt32LE(c+42);if(c+46+b+y+v>t)throw i("El .zip est\xE1 da\xF1ado.");let j=o.subarray(c+46,c+46+b),S=j.toString("utf8");if(c+=46+b+y+v,!S.endsWith("/")){if(!S||S.includes("\\")||S.startsWith("/")||S.split("/").some(R=>R===".."||R==="."||R==="")||/[\x00-\x1f]/.test(S))throw i(`El paquete trae un nombre de fichero no admitido (\xAB${S.slice(0,80)}\xBB).`);if(s.has(S))throw i(`El paquete trae \xAB${S.slice(0,80)}\xBB dos veces.`);if(u&1)throw i("El paquete no puede ir cifrado.");s.set(S,()=>{if(h>pl)throw i(`\xAB${S}\xBB pasa de 2 MB.`);if(N+30>o.length||o.readUInt32LE(N)!==67324752)throw i("El .zip est\xE1 da\xF1ado.");let R=o.readUInt16LE(N+26),F=N+30+R+o.readUInt16LE(N+28);if(F>r||F+m>r||o.readUInt16LE(N+6)!==u||o.readUInt16LE(N+8)!==p||!o.subarray(N+30,N+30+R).equals(j))throw i("El .zip est\xE1 da\xF1ado.");let I=o.subarray(F,F+m);if(I.length!==m)throw i("El .zip est\xE1 da\xF1ado.");let _;if(p===0)_=I;else if(p===8)try{_=Ab(I,{maxOutputLength:pl})}catch{throw i(`\xAB${S}\xBB no se puede descomprimir (o pasa de 2 MB).`)}else throw i(`\xAB${S}\xBB va comprimido de una forma no admitida (solo \xABstore\xBB y \xABdeflate\xBB).`);if(_.length!==h)throw i("El .zip est\xE1 da\xF1ado.");return _})}}if(c!==t)throw i("El .zip est\xE1 da\xF1ado (directorio inv\xE1lido).");return s}function zo(e){let o=new Map,t=0;for(let[n,r]of Eb(e)){let a=r();if(t+=a.length,t>qb)throw i("Los ficheros del paquete pasan de 10 MB al descomprimirlos.");o.set(n,a)}return o}var ea,pl,ml,qb,vr=f(()=>{q();ea=5*1024*1024,pl=2*1024*1024,ml=500;qb=10*1024*1024});function fl(e){if(e===void 0)return[];if(!Array.isArray(e)||e.length>20)throw i("La app admite hasta 20 conexiones.");let o=new Set;return e.map(t=>{if(!t||typeof t!="object"||Array.isArray(t)||typeof t.clave!="string"||!/^[a-z][a-z0-9_]{0,40}$/.test(t.clave)||o.has(t.clave)||typeof t.base!="string"||t.base.length>1e3||typeof t.operacion!="string"||!/^[a-zA-Z][a-zA-Z0-9_.-]{0,79}$/.test(t.operacion))throw i("Declaraci\xF3n de conexi\xF3n de app no v\xE1lida.");let n=["clave","base","operacion","tipo",...t.tipo==="api_key"?["lugar","nombre"]:[]];if(Object.keys(t).some(c=>!n.includes(c)))throw i("La declaraci\xF3n de conexi\xF3n no admite campos adicionales.");let r;try{r=new URL(t.base)}catch{throw i("La conexi\xF3n necesita una base HTTPS.")}if(!(process.env.NODE_ENV==="test"&&process.env.CRM_CONEXIONES_PRUEBA_LOCAL==="1"&&r.protocol==="http:"&&r.hostname==="127.0.0.1")&&(r.protocol!=="https:"||r.port)||r.username||r.password||r.search||r.hash)throw i("La conexi\xF3n necesita una base HTTPS sin credenciales, query ni fragmento.");o.add(t.clave);let s={clave:t.clave,base:r.href,operacion:t.operacion};if(t.tipo==="api_key"&&(t.lugar==="cabecera"||t.lugar==="query")&&typeof t.nombre=="string"&&/^[a-zA-Z][a-zA-Z0-9_.-]{0,79}$/.test(t.nombre))return{...s,tipo:t.tipo,lugar:t.lugar,nombre:t.nombre};if(t.tipo==="bearer"||t.tipo==="basic"||t.tipo==="oauth2")return{...s,tipo:t.tipo};throw i("Autenticaci\xF3n de conexi\xF3n de app no v\xE1lida.")})}var hl=f(()=>{q()});var Y,Rb,gl,bl=f(()=>{Y={id:"Id del registro."},Rb=[{nombre:"contacto.creado",descripcion:"Se ha creado un contacto.",datos:Y},{nombre:"contacto.actualizado",descripcion:"Han cambiado datos de un contacto.",datos:{...Y,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:{...Y,fusionado_en:"Si se fusion\xF3: en cu\xE1l."}},{nombre:"empresa.creada",descripcion:"Se ha creado una empresa.",datos:Y},{nombre:"empresa.actualizada",descripcion:"Han cambiado datos de una empresa.",datos:{...Y,campos:"Qu\xE9 columnas (si se sabe)."}},{nombre:"empresa.borrada",descripcion:"Se ha borrado una empresa.",datos:Y},{nombre:"contacto.fusionado",descripcion:"Un contacto se ha fusionado en otro: quien guarde su id, que lo cambie por el que queda.",datos:{...Y,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:{...Y,se_va:"La que se fue.",queda:"La que queda (= id)."}},{nombre:"oportunidad.creada",descripcion:"Se ha creado una oportunidad.",datos:Y},{nombre:"oportunidad.actualizada",descripcion:"Han cambiado datos de una oportunidad (no la etapa).",datos:{...Y,campos:"Qu\xE9 columnas (si se sabe)."}},{nombre:"oportunidad.etapa_cambiada",descripcion:"Una oportunidad ha cambiado de etapa.",datos:{...Y,de:"Etapa anterior.",a:"Etapa nueva."}},{nombre:"oportunidad.ganada",descripcion:"Una oportunidad ha pasado a ganada (adem\xE1s de etapa_cambiada).",datos:{...Y,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:{...Y,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:Y},{nombre:"oportunidad.borrada",descripcion:"Se ha borrado una oportunidad.",datos:Y},{nombre:"nota.creada",descripcion:"Nueva nota en el hilo de un contacto o de una oportunidad.",datos:{...Y,contacto_id:"Si es de un contacto.",oportunidad_id:"Si es de una oportunidad."}},{nombre:"nota.actualizada",descripcion:"Se ha editado una nota.",datos:Y},{nombre:"nota.borrada",descripcion:"Se ha borrado una nota.",datos:Y},{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:{...Y,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:{...Y,contacto_id:"Su contacto."}},{nombre:"tarea.actualizada",descripcion:"Ha cambiado una tarea (o se ha reabierto).",datos:{...Y,campos:"Qu\xE9 columnas (si se sabe)."}},{nombre:"tarea.completada",descripcion:"Se ha completado una tarea.",datos:Y},{nombre:"tarea.borrada",descripcion:"Se ha borrado una tarea.",datos:Y},{nombre:"contacto.etiquetado",descripcion:"Una Persona ha recibido una etiqueta (una vez por etiqueta a\xF1adida, venga de donde venga).",datos:{...Y,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:{...Y,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:{...Y,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:{...Y,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:{...Y,modulo:"La clave del m\xF3dulo.",campos:"Qu\xE9 campos."}},{nombre:"registro.borrado",descripcion:"Se ha borrado un registro de un m\xF3dulo.",datos:{...Y,modulo:"La clave del m\xF3dulo."}}],gl=Rb.map(e=>e.nombre)});function Pb(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]),c=a[1]==="*"?t:a[3]!==void 0?Number(a[3]):a[4]!==void 0?t:s,d=a[4]!==void 0?Number(a[4]):1;if(s<o||c>t||s>c||d<1)return null;for(let u=s;u<=c;u+=d)n.add(u)}return n}function wl(e){let o=e.trim().split(/\s+/);if(o.length!==5)return null;let t=o.map((r,a)=>Pb(r,kb[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 vl(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 kb,v0,yl=f(()=>{kb=[[0,59],[0,23],[1,31],[1,12],[0,7]];v0=new Intl.DateTimeFormat("en-GB",{timeZone:"Europe/Madrid",hourCycle:"h23",minute:"numeric",hour:"numeric",day:"numeric",month:"numeric",weekday:"short"})});function _l(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,W.ms),memoriaMb:o(e?.tope?.memoria_mb,W.memoriaMb)}}var W,yr=f(()=>{W={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 Nl(e){if(!e.startsWith("*."))return!1;let o=e.slice(2).toLowerCase();if(Mb.has(o)||Ib.test(o))return!0;let t=o.split(".");return t.length===2&&t[1].length===2&&Tb.has(t[0])}var Tb,Mb,Ib,$l=f(()=>{Tb=new Set(["co","com","net","org","gov","gob","edu","ac","nom","mil","ltd","plc","me","or","ne","go","info","biz","int"]),Mb=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"]),Ib=/^(s3([.-][a-z0-9-]+)?\.amazonaws\.com|blogspot\.[a-z]{2,3}(\.[a-z]{2})?)$/});function na(e,o=0){if(o>20)throw i("El manifiesto anida demasiado.");if(Array.isArray(e))return e.forEach(t=>na(t,o+1));if(me(e))for(let t of Object.keys(e)){if(Db.has(t))throw i(`Clave no admitida \xAB${t}\xBB.`);na(e[t],o+1)}}function Ne(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 Ub(e,o,t={}){return Bb.test(e.replace(Vb,""))?`\xAB${o}\xBB: lleva caracteres de control, invisibles o de direcci\xF3n del texto.`:t.reservar&&!t.firmada&&aa(e)?`\xAB${o}\xBB: \xABForgeNEX\xBB est\xE1 reservado a lo que publica ForgeNEX.`:null}function G(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=Ub(r,o);if(a)throw i(a);return r}function Gb(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(ia).filter(Boolean)}function Ml(e,o,t){let n=K(e,o,Rl,t);if(Nl(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 K(e,o,t,n){if(typeof e!="string"||!t.test(e))throw i(`\xAB${o}\xBB: ${n}.`);return e}function ce(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 we(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 ta(e,o){let t=G(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||!Rl.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 Hb(e){let[o,t]=e.split(".");return ia(o??"")==="forgenex"||ia(t??"")==="forgenex"}function lo(e){if(Object.hasOwn(Bo,e))return e;let o=e.startsWith("mod_")?e.slice(4):e;return Fb.test(o)?`mod_${o}`:null}function Al(e,o,t){if(!me(e))throw i(`\xAB${o}\xBB: un nombre de contrato, o { contrato, modulos, eventos, herramientas }.`);Ne(e,["contrato","titulo","modulos","eventos","herramientas",...t],o);let n=K(e.contrato,`${o}.contrato`,ra,"un nombre de contrato (\xABtaller.vehiculos\xBB)"),r=e.titulo===void 0?null:G(e.titulo,`${o}.titulo`,80),a={};if(e.modulos!==void 0){if(!me(e.modulos))throw i(`\xAB${o}.modulos\xBB: un objeto { m\xF3dulo: [operaciones] }.`);let d=Object.entries(e.modulos);if(d.length>20)throw i(`\xAB${o}.modulos\xBB: como mucho 20 m\xF3dulos.`);for(let[u,p]of d){let m=lo(u);if(!m)throw i(`\xAB${o}.modulos\xBB: \xAB${u.slice(0,60)}\xBB no es un m\xF3dulo (min\xFAsculas, n\xFAmeros y _).`);if(a[m])throw i(`\xAB${o}.modulos\xBB: \xAB${u}\xBB est\xE1 repetido.`);let h=ce(p,`${o}.modulos.${u}`,4);if(!h.length||h.some(y=>typeof y!="string"||!Wo.includes(y)))throw i(`\xAB${o}.modulos.${u}\xBB: operaciones ${Wo.join(", ")}.`);let b=new Set(h);if((b.has("editar")||b.has("borrar"))&&!b.has("ver"))throw i(`\xAB${o}.modulos.${u}\xBB: para \xABeditar\xBB o \xABborrar\xBB hace falta \xABver\xBB.`);a[m]=Wo.filter(y=>b.has(y))}}let s=we(ce(e.eventos,`${o}.eventos`,3).map((d,u)=>{if(typeof d!="string"||!xl.includes(d))throw i(`\xAB${o}.eventos[${u}]\xBB: ${xl.join(", ")} (los de los registros de sus m\xF3dulos).`);return d}),d=>d,`${o}.eventos`).sort();if(s.length&&!Object.values(a).some(d=>d.includes("ver")))throw i(`\xAB${o}.eventos\xBB: los eventos son de sus m\xF3dulos; hace falta \xABver\xBB de alguno en \xAB${o}.modulos\xBB.`);let c=we(ce(e.herramientas,`${o}.herramientas`,20).map((d,u)=>K(d,`${o}.herramientas[${u}]`,/^[a-z][a-z0-9_]{2,40}$/,"el nombre de una herramienta")),d=>d,`${o}.herramientas`);if(!Object.keys(a).length&&!s.length&&!c.length)throw i(`\xAB${o}\xBB: di qu\xE9 lleva el contrato (m\xF3dulos, eventos o herramientas).`);return{contrato:n,titulo:r,modulos:a,eventos:s,herramientas:c}}function Xb(e){if(e===void 0)return{modulos:{},almacen:!1,red_hacia:[],eventos:[],archivos:[]};if(!me(e))throw i("\xABpermisos\xBB: un objeto.");Ne(e,["modulos","almacen","red_hacia","eventos","archivos"],"Permisos");let o={};if(e.modulos!==void 0){if(!me(e.modulos))throw i("\xABpermisos.modulos\xBB: un objeto { m\xF3dulo: [operaciones] }.");let a=Object.entries(e.modulos);if(a.length>40)throw i("\xABpermisos.modulos\xBB: como mucho 40 m\xF3dulos.");for(let[s,c]of a){let d=lo(s);if(!d)throw i(`\xABpermisos.modulos\xBB: \xAB${s.slice(0,60)}\xBB no es un m\xF3dulo (min\xFAsculas, n\xFAmeros y _).`);if(o[d])throw i(`\xABpermisos.modulos\xBB: \xAB${s}\xBB est\xE1 repetido.`);let u=Bo[d]?.ops??Wo,p=ce(c,`permisos.modulos.${s}`,4);if(!p.length)throw i(`\xABpermisos.modulos.${s}\xBB: di qu\xE9 operaciones (${u.join(", ")}).`);for(let h of p)if(typeof h!="string"||!u.includes(h))throw i(`\xABpermisos.modulos.${s}\xBB: operaciones ${u.join(", ")}.`);let m=new Set(p);if((m.has("editar")||m.has("borrar"))&&!m.has("ver"))throw i(`\xABpermisos.modulos.${s}\xBB: para \xABeditar\xBB o \xABborrar\xBB hace falta \xABver\xBB.`);o[d]=Wo.filter(h=>m.has(h))}}if(e.almacen!==void 0&&typeof e.almacen!="boolean")throw i("\xABpermisos.almacen\xBB: s\xED o no (true/false).");let t=we(ce(e.red_hacia,"permisos.red_hacia",20).map((a,s)=>Ml(a,`permisos.red_hacia[${s}]`,"un dominio (\xABapi.ejemplo.com\xBB o \xAB*.ejemplo.com\xBB; ni IP ni localhost)")),a=>a,"permisos.red_hacia").sort(),n=we(ce(e.eventos,"permisos.eventos",40).map((a,s)=>{if(typeof a!="string"||!gl.includes(a))throw i(`\xABpermisos.eventos[${s}]\xBB: un evento del cat\xE1logo (GET /api/v1/eventos).`);return a}),a=>a,"permisos.eventos").sort(),r=ce(e.archivos,"permisos.archivos",2);for(let a of r)if(typeof a!="string"||!Cl.includes(a))throw i('\xABpermisos.archivos\xBB: ["leer"] o ["leer", "escribir"].');if(r.includes("escribir")&&!r.includes("leer"))throw i("\xABpermisos.archivos\xBB: para \xABescribir\xBB hace falta \xABleer\xBB.");return{modulos:Object.fromEntries(Object.entries(o).sort(([a],[s])=>a.localeCompare(s))),almacen:e.almacen===!0,red_hacia:t,eventos:n,archivos:Cl.filter(a=>r.includes(a))}}function El(e,o){let t=o.lastIndexOf(".");if(t<1)return!1;let n=lo(o.slice(0,t));return!!n&&(e.modulos[n]??[]).includes(o.slice(t+1))}function ql(e,o){let t={};if(e===void 0)return t;if(!me(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(K(n,o,Fo,"nombres de campo en min\xFAsculas y _"),!me(r))throw i(`\xAB${o}.${n}\xBB: { tipo, desc }.`);Ne(r,["tipo","desc","requerido"],`${o}.${n}`);let a=G(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:G(r.desc,`${o}.${n}.desc`,200),requerido:r.requerido===!0}}return t}function Vo(e,o={}){if(typeof e=="string"){if(e.length>hn)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>hn)throw i("El manifiesto pasa de 256 KB.");if(!me(e))throw i("El manifiesto tiene que ser un objeto.");if(na(e),e.formato!==at)throw i(`No es una app (formato \xAB${at}\xBB).`);if(Ne(e,["$schema","formato","formato_version","id","nombre","descripcion","version","autor","icono","idiomas","compatible_crm","licencia","politica_datos","depende_de","ofrece","usa","solucion","montajes","funciones","servidor","herramientas_ia","ajustes","secretos","conexiones","permisos"],"App"),!Number.isInteger(e.formato_version)||e.formato_version<1)throw i("\xABformato_version\xBB: un entero (1).");if(e.formato_version>wn)throw i("La app es de una versi\xF3n del formato m\xE1s nueva que este CRM.");let t=K(e.id,"id",fn,"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&&Hb(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=G(e.nombre,"nombre",80),r=K(e.version,"version",Lb,"versi\xF3n semver (\xAB1.0.0\xBB)"),a;if(typeof e.autor=="string")a={nombre:G(e.autor,"autor",120)};else if(me(e.autor))Ne(e.autor,["nombre","web"],"Autor"),a={nombre:G(e.autor.nombre,"autor.nombre",120),...e.autor.web!==void 0?{web:ta(e.autor.web,"autor.web")}:{}};else throw i("Falta \xABautor\xBB (un nombre, o { nombre, web }).");if(!o.firmada){if(aa(n))throw i("\xABnombre\xBB: \xABForgeNEX\xBB est\xE1 reservado a lo que publica ForgeNEX.");if(aa(a.nombre))throw i("\xABautor\xBB: \xABForgeNEX\xBB est\xE1 reservado a lo que publica ForgeNEX.")}let s=e.icono===void 0?"puzzle":K(e.icono,"icono",Sl,"un icono de lucide (\xABpuzzle\xBB)"),c=we(ce(e.idiomas,"idiomas",30).map((_,E)=>K(_,`idiomas[${E}]`,zb,"un c\xF3digo de idioma (\xABes\xBB, \xABen\xBB, \xABpt-BR\xBB)")),_=>_,"idiomas"),d=null;if(e.compatible_crm!==void 0){let E=G(e.compatible_crm,"compatible_crm",80).split(/\s+/);if(E.length>2||!E.every(g=>jl.test(g)))throw i("\xABcompatible_crm\xBB: un rango (\xAB>=1.6.0-284\xBB, \xAB>=1.6.0-284 <2.0.0\xBB).");d=E.join(" ")}let u=e.licencia===void 0?null:G(e.licencia,"licencia",40),p=e.politica_datos===void 0?{}:{politica_datos:ta(e.politica_datos,"politica_datos")},m=we(ce(e.depende_de,"depende_de",20).map((_,E)=>{if(typeof _=="string")return{id:K(_,`depende_de[${E}]`,fn,"el id de otra app"),version:null};if(!me(_))throw i(`\xABdepende_de[${E}]\xBB: el id de otra app, o { id, version }.`);Ne(_,["id","version"],`depende_de[${E}]`);let g=_.version===void 0?null:G(_.version,`depende_de[${E}].version`,80);if(g!==null&&!g.split(/\s+/).every(x=>jl.test(x)))throw i(`\xABdepende_de[${E}].version\xBB: un rango (\xAB>=1.0.0\xBB).`);return{id:K(_.id,`depende_de[${E}].id`,fn,"el id de otra app"),version:g}}),_=>_.id,"depende_de");if(m.some(_=>_.id===t))throw i("\xABdepende_de\xBB: una app no depende de s\xED misma.");let h=Xb(e.permisos),b=we(ce(e.usa,"usa",20).map((_,E)=>{let g=`usa[${E}]`;if(typeof _=="string")return{...Ol(K(_,g,ra,"un nombre de contrato (\xABtaller.citas\xBB)")),de:null};let x=Al(_,g,["de"]),O=K(_.de,`${g}.de`,fn,"el id de la app que lo ofrece (\xABcom.taller.vehiculos\xBB)");if(O===t)throw i(`\xAB${g}.de\xBB: una app no se usa a s\xED misma.`);return{...x,de:O}}),_=>`${_.de??""}/${_.contrato}`,"usa"),y=e.solucion===void 0||e.solucion===null?null:K(e.solucion,"solucion",oa,"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 v=we(ce(e.montajes,"montajes",20).map((_,E)=>{let g=`montajes[${E}]`;if(!me(_))throw i(`\xAB${g}\xBB: un objeto.`);Ne(_,["id","punto","entrada","titulo","icono","modulo","permiso","funciones"],g);let x=G(_.punto,`${g}.punto`,20);if(!Pt.includes(x))throw i(`\xAB${g}.punto\xBB: ${Pt.join(", ")}.`);let O=null;if(_r.has(x)){if(O=lo(G(_.modulo,`${g}.modulo`,64)),!O)throw i(`\xAB${g}.modulo\xBB: el m\xF3dulo donde se cuelga.`);if(!(h.modulos[O]??[]).includes("ver"))throw i(`\xAB${g}\xBB: se cuelga de \xAB${_.modulo}\xBB, as\xED que \xABpermisos.modulos\xBB tiene que pedir verlo.`)}else if(_.modulo!==void 0)throw i(`\xAB${g}.modulo\xBB: solo en ${[..._r].join(", ")}.`);let k=_.permiso===void 0?null:G(_.permiso,`${g}.permiso`,80);if(k!==null&&!El(h,k))throw i(`\xAB${g}.permiso\xBB: \xAB${k}\xBB no est\xE1 en \xABpermisos.modulos\xBB.`);if(x==="publica"&&k!==null)throw i(`\xAB${g}.permiso\xBB: la p\xE1gina p\xFAblica no lleva permiso (la ve cualquiera con el enlace).`);let L;if(x==="publica")L=we(ce(_.funciones,`${g}.funciones`,10).map((V,U)=>K(V,`${g}.funciones[${U}]`,Fo,"el nombre de una funci\xF3n")),V=>V,`${g}.funciones`);else if(_.funciones!==void 0)throw i(`\xAB${g}.funciones\xBB: solo en el montaje \xABpublica\xBB.`);return{id:K(_.id,`${g}.id`,/^[a-z][a-z0-9_-]{0,40}$/,"min\xFAsculas, n\xFAmeros, _ y -"),punto:x,entrada:K(_.entrada,`${g}.entrada`,oa,"un fichero del paquete (\xABinterfaz/index.html\xBB)"),titulo:G(_.titulo,`${g}.titulo`,60),icono:_.icono===void 0?null:K(_.icono,`${g}.icono`,Sl,"un icono de lucide"),modulo:O,permiso:k,...L?{funciones:L}:{}}}),_=>_.id,"montajes");if(v.filter(_=>_.punto==="publica").length>1)throw i("\xABmontajes\xBB: una app tiene como mucho una p\xE1gina p\xFAblica.");let w=we(ce(e.funciones,"funciones",20).map((_,E)=>{let g=`funciones[${E}]`;if(!me(_))throw i(`\xAB${g}\xBB: un objeto.`);if(Ne(_,["nombre","titulo","descripcion","entrada","disparador","tope","red","parametros","salida"],g),!me(_.disparador))throw i(`\xAB${g}.disparador\xBB: { tipo, \u2026 }.`);Ne(_.disparador,["tipo","evento","cron"],`${g}.disparador`);let x=G(_.disparador.tipo,`${g}.disparador.tipo`,20);if(!gn.includes(x))throw i(`\xAB${g}.disparador.tipo\xBB: ${gn.join(", ")}.`);let O={tipo:x};if(x==="evento"){let X=G(_.disparador.evento,`${g}.disparador.evento`,80);if(!h.eventos.includes(X)&&!b.some(Ve=>Ve.eventos.includes(X)))throw i(`\xAB${g}.disparador.evento\xBB: \xAB${X}\xBB tiene que estar en \xABpermisos.eventos\xBB (o en los \xABeventos\xBB de un contrato de \xABusa\xBB).`);O.evento=X}if(x==="programada"){O.cron=K(_.disparador.cron,`${g}.disparador.cron`,Wb,"un cron de 5 campos (\xAB0 7 * * 1-5\xBB)");let X=wl(O.cron);if(!X)throw i(`\xAB${g}.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(vl(X)<W.cronMinutos)throw i(`\xAB${g}.disparador.cron\xBB: como mucho una vez cada ${W.cronMinutos} minutos.`)}let k=me(_.tope)?_.tope:{};_.tope!==void 0&&Ne(k,["ms","memoria_mb"],`${g}.tope`);let L=k.ms===void 0?5e3:Number(k.ms),V=k.memoria_mb===void 0?64:Number(k.memoria_mb);if(!Number.isInteger(L)||L<W.ms.min||L>W.ms.max)throw i(`\xAB${g}.tope.ms\xBB: de ${W.ms.min} a ${W.ms.max}.`);if(!Number.isInteger(V)||V<W.memoriaMb.min||V>W.memoriaMb.max)throw i(`\xAB${g}.tope.memoria_mb\xBB: de ${W.memoriaMb.min} a ${W.memoriaMb.max}.`);let U=ce(_.red,`${g}.red`,10).map((X,Ve)=>Ml(X,`${g}.red[${Ve}]`,"un dominio"));for(let X of U)if(!Yb(h.red_hacia,X))throw i(`\xAB${g}.red\xBB: \xAB${X}\xBB tiene que estar en \xABpermisos.red_hacia\xBB.`);let be=ql(_.parametros,`${g}.parametros`),Be={},br=we(ce(_.salida,`${g}.salida`,30).map((X,Ve)=>{let Ue=`${g}.salida[${Ve}]`;if(!me(X))return K(X,Ue,Fo,"nombres en min\xFAsculas y _ (o { clave, titulo })");Ne(X,["clave","titulo"],Ue);let Do=K(X.clave,`${Ue}.clave`,Fo,"nombres en min\xFAsculas y _");return X.titulo!==void 0&&(Be[Do]=G(X.titulo,`${Ue}.titulo`,60)),Do}),X=>X,`${g}.salida`);if(x==="publica"&&U.length)throw i(`\xAB${g}.red\xBB: una funci\xF3n \xABpublica\xBB no sale a la red (solo lee el CRM).`);if(Object.keys(be).length&&x!=="automatizacion")throw i(`\xAB${g}.parametros\xBB: solo en las de disparador \xABautomatizacion\xBB (las dem\xE1s reciben su evento, su minuto o su webhook).`);return{nombre:K(_.nombre,`${g}.nombre`,Fo,"min\xFAsculas, n\xFAmeros y _"),titulo:_.titulo===void 0?null:G(_.titulo,`${g}.titulo`,80),descripcion:_.descripcion===void 0?null:G(_.descripcion,`${g}.descripcion`,300,!1),entrada:K(_.entrada,`${g}.entrada`,oa,"un fichero del paquete (\xABfunciones/calcular.js\xBB)"),disparador:O,tope:{ms:L,memoria_mb:V},red:U,parametros:be,salida:br,titulos_salida:Be}}),_=>_.nombre,"funciones"),N=null;if(e.servidor!==void 0&&e.servidor!==null){if(!me(e.servidor))throw i("\xABservidor\xBB: { url, webhooks }.");Ne(e.servidor,["url","webhooks"],"Servidor");let _=we(ce(e.servidor.webhooks,"servidor.webhooks",40).map((E,g)=>{if(typeof E!="string"||!h.eventos.includes(E))throw i(`\xABservidor.webhooks[${g}]\xBB: un evento que est\xE9 en \xABpermisos.eventos\xBB.`);return E}),E=>E,"servidor.webhooks");N={url:ta(e.servidor.url,"servidor.url"),webhooks:_}}let j=new Set(w.map(_=>_.nombre));for(let _ of v)for(let[E,g]of(_.funciones??[]).entries()){let x=w.find(O=>O.nombre===g);if(!x)throw i(`\xABmontajes\xBB.\xAB${_.id}\xBB.funciones[${E}]: \xAB${g}\xBB tiene que estar en \xABfunciones\xBB.`);if(x.disparador.tipo!=="publica")throw i(`\xABmontajes\xBB.\xAB${_.id}\xBB.funciones[${E}]: \xAB${g}\xBB tiene que ser de disparador \xABpublica\xBB.`)}let S=we(ce(e.herramientas_ia,"herramientas_ia",20).map((_,E)=>{let g=`herramientas_ia[${E}]`;if(!me(_))throw i(`\xAB${g}\xBB: un objeto.`);Ne(_,["nombre","descripcion","entrada","salida","riesgo","funcion","escribe","permiso"],g);let x=ql(_.entrada,`${g}.entrada`),O=G(_.riesgo,`${g}.riesgo`,10);if(!["bajo","medio","alto"].includes(O))throw i(`\xAB${g}.riesgo\xBB: bajo, medio o alto.`);let k=G(_.funcion,`${g}.funcion`,41);if(!j.has(k))throw i(`\xAB${g}.funcion\xBB: \xAB${k}\xBB tiene que estar en \xABfunciones\xBB.`);if(!["herramienta","calculo"].includes(w.find(V=>V.nombre===k)?.disparador.tipo??""))throw i(`\xAB${g}.funcion\xBB: \xAB${k}\xBB tiene que ser de disparador \xABherramienta\xBB (o \xABcalculo\xBB).`);if(_.escribe!==void 0&&typeof _.escribe!="boolean")throw i(`\xAB${g}.escribe\xBB: true o false.`);let L=null;if(_.permiso!==void 0){let V=G(_.permiso,`${g}.permiso`,80),U=V.lastIndexOf("."),be=U>0?lo(V.slice(0,U)):null;if(!be||!El(h,V))throw i(`\xAB${g}.permiso\xBB: \xAB${V}\xBB no est\xE1 en \xABpermisos.modulos\xBB.`);L=`${be}.${V.slice(U+1)}`}return{nombre:K(_.nombre,`${g}.nombre`,/^[a-z][a-z0-9_]{2,40}$/,"min\xFAsculas, n\xFAmeros y _ (3 a 41)"),descripcion:G(_.descripcion,`${g}.descripcion`,500),entrada:x,salida:we(ce(_.salida,`${g}.salida`,30).map((V,U)=>K(V,`${g}.salida[${U}]`,Fo,"nombres de campo")),V=>V,`${g}.salida`),riesgo:O,funcion:k,escribe:_.escribe===!0,permiso:L}}),_=>_.nombre,"herramientas_ia"),R=we(ce(e.ofrece,"ofrece",20).map((_,E)=>{let g=`ofrece[${E}]`;if(typeof _=="string")return Ol(K(_,g,ra,"un nombre de contrato (\xABtaller.citas\xBB)"));let x=Al(_,g,[]);for(let[O,k]of Object.entries(x.modulos)){if(!O.startsWith("mod_"))throw i(`\xAB${g}.modulos\xBB: \xAB${O}\xBB es de serie; un contrato solo comparte m\xF3dulos de la soluci\xF3n de la app.`);let L=h.modulos[O]??[],V=k.find(U=>!L.includes(U));if(V)throw i(`\xAB${g}.modulos.${O.slice(4)}\xBB: ofrece \xAB${V}\xBB y \xABpermisos.modulos\xBB no lo pide (nadie da lo que no tiene).`)}for(let O of x.eventos)if(!h.eventos.includes(O))throw i(`\xAB${g}.eventos\xBB: \xAB${O}\xBB tiene que estar en \xABpermisos.eventos\xBB.`);for(let O of x.herramientas){let k=S.find(L=>L.nombre===O);if(!k)throw i(`\xAB${g}.herramientas\xBB: \xAB${O}\xBB tiene que estar en \xABherramientas_ia\xBB.`);if(k.escribe)throw i(`\xAB${g}.herramientas\xBB: \xAB${O}\xBB escribe; un contrato solo comparte herramientas que consultan.`)}return x}),_=>_.contrato,"ofrece"),F=we(ce(e.ajustes,"ajustes",40).map((_,E)=>{let g=`ajustes[${E}]`;if(!me(_))throw i(`\xAB${g}\xBB: un objeto.`);Ne(_,["clave","etiqueta","tipo","opciones","requerido"],g);let x=G(_.tipo,`${g}.tipo`,10);if(!bn.includes(x))throw i(`\xAB${g}.tipo\xBB: ${bn.join(", ")}.`);let O=ce(_.opciones,`${g}.opciones`,50).map((k,L)=>{if(!me(k))throw i(`\xAB${g}.opciones[${L}]\xBB: { valor, etiqueta }.`);return Ne(k,["valor","etiqueta"],`${g}.opciones[${L}]`),{valor:G(k.valor,`${g}.opciones[${L}].valor`,60),etiqueta:G(k.etiqueta,`${g}.opciones[${L}].etiqueta`,80)}});if(x==="opcion"&&!O.length)throw i(`\xAB${g}.opciones\xBB: un ajuste de tipo opci\xF3n necesita sus opciones.`);if(x!=="opcion"&&O.length)throw i(`\xAB${g}.opciones\xBB: solo en los de tipo opci\xF3n.`);return{clave:K(_.clave,`${g}.clave`,Fo,"min\xFAsculas, n\xFAmeros y _"),etiqueta:G(_.etiqueta,`${g}.etiqueta`,80),tipo:x,opciones:we(O,k=>k.valor,`${g}.opciones`),requerido:_.requerido===!0}}),_=>_.clave,"ajustes"),I=we(ce(e.secretos,"secretos",10).map((_,E)=>{let g=`secretos[${E}]`;if(!me(_))throw i(`\xAB${g}\xBB: un objeto.`);return Ne(_,["clave","etiqueta","descripcion"],g),{clave:K(_.clave,`${g}.clave`,Fo,"min\xFAsculas, n\xFAmeros y _"),etiqueta:G(_.etiqueta,`${g}.etiqueta`,80),descripcion:G(_.descripcion,`${g}.descripcion`,300,!1)}}),_=>_.clave,"secretos");return{formato:at,formato_version:e.formato_version,id:t,nombre:n,descripcion:G(e.descripcion,"descripcion",500,!1),version:r,autor:a,icono:s,idiomas:c,compatible_crm:d,licencia:u,...p,depende_de:m,ofrece:R,usa:b,solucion:y,montajes:v,funciones:w,servidor:N,herramientas_ia:S,ajustes:F,secretos:I,...e.conexiones!==void 0?{conexiones:fl(e.conexiones)}:{},permisos:h}}var at,wn,hn,Bo,Wo,Pt,vn,_r,gn,bn,xl,Cl,Db,fn,Lb,jl,Sl,zb,ra,Fo,Fb,oa,Rl,Wb,me,kl,Bb,A0,Vb,Pl,Tl,Jb,Qb,ia,aa,Ol,Yb,Tt=f(()=>{hl();q();bl();yl();yr();$l();at="forgenex.extension",wn=1,hn=256e3,Bo={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"]}},Wo=["ver","crear","editar","borrar"],Pt=["pagina","ficha_pestana","ficha_bloque","inicio_bloque","accion_ficha","accion_tabla","vista","ajustes","publica"],vn=new Set(["pagina","ficha_pestana","ficha_bloque","inicio_bloque","accion_ficha","accion_tabla","vista","ajustes","publica"]),_r=new Set(["ficha_pestana","ficha_bloque","accion_ficha","accion_tabla","vista"]),gn=["evento","programada","webhook","automatizacion","calculo","herramienta","publica"],bn=["texto","numero","si_no","opcion","modulo","campo"],xl=["registro.creado","registro.actualizado","registro.borrado"],Cl=["leer","escribir"],Db=new Set(["__proto__","constructor","prototype"]),fn=/^[a-z][a-z0-9-]{0,62}(\.[a-z0-9][a-z0-9-]{0,62}){1,6}$/,Lb=/^(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})?$/,jl=/^(>=|<=|>|<|=|\^|~)?(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})?$/,Sl=/^[a-z0-9-]{1,40}$/,zb=/^[a-z]{2,3}(-[A-Z]{2})?$/,ra=/^[a-z][a-z0-9_.-]{0,79}$/,Fo=/^[a-z][a-z0-9_]{0,40}$/,Fb=/^[a-z][a-z0-9_]{0,59}$/,oa=/^(?!\/)(?!.*\/\/)(?!.*(^|\/)\.\.?(\/|$))[A-Za-z0-9_.\/-]{1,200}$/,Rl=/^(\*\.)?([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/,Wb=/^[0-9*,\/-]+( [0-9*,\/-]+){4}$/,me=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);kl=String.raw`[\p{Cc}\p{Cf}\u2028\u2029\u034F\u115F\u1160\u2800\u3164\uFFA0]|(?<!\p{Emoji})[\uFE00-\uFE0F]|(?<=[0-9#*])[\uFE00-\uFE0F](?!\u20E3)`,Bb=new RegExp(kl,"u"),A0=new RegExp(kl,"gu"),Vb=new RegExp("(?<=\\p{Extended_Pictographic}[\\uFE0F\\p{Emoji_Modifier}]?)\\u200D(?=\\p{Extended_Pictographic})","gu");Pl={\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"},Tl={\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"},Jb=new RegExp(`[${Object.keys(Pl).join("")}]`,"gu"),Qb=new RegExp(`[${Object.keys(Tl).join("")}]`,"gu"),ia=e=>e.normalize("NFKC").replace(Jb,o=>Pl[o]).toLowerCase().normalize("NFD").replace(new RegExp("\\p{M}","gu"),"").replace(Qb,o=>Tl[o]).replace(/[^\p{L}\p{N}]/gu,"");aa=e=>{let o=Gb(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};Ol=e=>({contrato:e,titulo:null,modulos:{},eventos:[],herramientas:[]});Yb=(e,o)=>e.some(t=>t===o||t.startsWith("*.")&&o.endsWith(t.slice(1)))});function $o(e){return typeof e>"u"||e===void 0}function H(e){return typeof e=="string"}function uo(e){return typeof e=="number"}function st(e){return typeof e=="boolean"}function ct(e){return e===null}function sa(e){return e instanceof Date}function lt(e){return typeof e=="bigint"}function Il(e){return typeof Buffer<"u"&&Buffer.isBuffer(e)}function $e(e){return typeof e=="function"}function je(e){return typeof e=="object"&&e!==null}function l(e){return Object.freeze(e)}function Nr(e){return ke(e)?e:[e]}function ke(e){return Array.isArray(e)}function Dl(e){return e instanceof Error?e.message:String(e)}var $=f(()=>{});var k0,Ll=f(()=>{$();k0=l({is(e){return e.kind==="AlterTableNode"},create(e){return l({kind:"AlterTableNode",table:e})},cloneWithTableProps(e,o){return l({...e,...o})},cloneWithColumnAlteration(e,o){return l({...e,columnAlterations:e.columnAlterations?[...e.columnAlterations,o]:[o]})}})});var M,ne=f(()=>{$();M=l({is(e){return e.kind==="IdentifierNode"},create(e){return l({kind:"IdentifierNode",name:e})}})});var L0,zl=f(()=>{$();ne();L0=l({is(e){return e.kind==="CreateIndexNode"},create(e){return l({kind:"CreateIndexNode",name:M.create(e)})},cloneWith(e,o){return l({...e,...o})},cloneWithColumns(e,o){return l({...e,columns:[...e.columns||[],...o]})}})});var B0,Fl=f(()=>{$();ne();B0=l({is(e){return e.kind==="CreateSchemaNode"},create(e,o){return l({kind:"CreateSchemaNode",schema:M.create(e),...o})},cloneWith(e,o){return l({...e,...o})}})});var J0,Wl=f(()=>{$();J0=l({is(e){return e.kind==="CreateTableNode"},create(e){return l({kind:"CreateTableNode",table:e,columns:l([])})},cloneWithColumn(e,o){return l({...e,columns:l([...e.columns,o])})},cloneWithConstraint(e,o){return l({...e,constraints:e.constraints?l([...e.constraints,o]):l([o])})},cloneWithIndex(e,o){return l({...e,indexes:e.indexes?l([...e.indexes,o]):l([o])})},cloneWithFrontModifier(e,o){return l({...e,frontModifiers:e.frontModifiers?l([...e.frontModifiers,o]):l([o])})},cloneWithEndModifier(e,o){return l({...e,endModifiers:e.endModifiers?l([...e.endModifiers,o]):l([o])})},cloneWith(e,o){return l({...e,...o})}})});var Ye,ut=f(()=>{$();ne();Ye=l({is(e){return e.kind==="SchemableIdentifierNode"},create(e){return l({kind:"SchemableIdentifierNode",identifier:M.create(e)})},createWithSchema(e,o){return l({kind:"SchemableIdentifierNode",schema:M.create(e),identifier:M.create(o)})}})});var Z0,Bl=f(()=>{$();ut();Z0=l({is(e){return e.kind==="DropIndexNode"},create(e,o){return l({kind:"DropIndexNode",name:Ye.create(e),...o})},cloneWith(e,o){return l({...e,...o})}})});var rN,Vl=f(()=>{$();ne();rN=l({is(e){return e.kind==="DropSchemaNode"},create(e,o){return l({kind:"DropSchemaNode",schema:M.create(e),...o})},cloneWith(e,o){return l({...e,...o})}})});var aN,Ul=f(()=>{$();aN=l({is(e){return e.kind==="DropTableNode"},create(e,o){return l({kind:"DropTableNode",table:e,...o})},cloneWith(e,o){return l({...e,...o})}})});var Pe,xo=f(()=>{$();Pe=l({is(e){return e.kind==="AliasNode"},create(e,o){return l({kind:"AliasNode",node:e,alias:o})}})});var Uo,$r=f(()=>{$();ut();Uo=l({is(e){return e.kind==="TableNode"},create(e){return l({kind:"TableNode",table:Ye.create(e)})},createWithSchema(e,o){return l({kind:"TableNode",table:Ye.createWithSchema(e,o)})}})});function ie(e){return je(e)&&$e(e.toOperationNode)}var Je=f(()=>{$()});function yn(e){return je(e)&&"expressionType"in e&&ie(e)}function Jl(e){return je(e)&&"expression"in e&&H(e.alias)&&ie(e)}var _n=f(()=>{Je();$()});var po,ca=f(()=>{$();po=l({is(e){return e.kind==="SelectModifierNode"},create(e,o){return l({kind:"SelectModifierNode",modifier:e,of:o})},createWithExpression(e){return l({kind:"SelectModifierNode",rawModifier:e})}})});var Te,Jo=f(()=>{$();Te=l({is(e){return e.kind==="AndNode"},create(e,o){return l({kind:"AndNode",left:e,right:o})}})});var Ke,dt=f(()=>{$();Ke=l({is(e){return e.kind==="OrNode"},create(e,o){return l({kind:"OrNode",left:e,right:o})}})});var Nn,la=f(()=>{$();Jo();dt();Nn=l({is(e){return e.kind==="OnNode"},create(e){return l({kind:"OnNode",on:e})},cloneWithOperation(e,o,t){return l({...e,on:o==="And"?Te.create(e.on,t):Ke.create(e.on,t)})}})});var Co,xr=f(()=>{$();la();Co=l({is(e){return e.kind==="JoinNode"},create(e,o){return l({kind:"JoinNode",joinType:e,table:o,on:void 0})},createWithOn(e,o,t){return l({kind:"JoinNode",joinType:e,table:o,on:Nn.create(t)})},cloneWithOn(e,o){return l({...e,on:e.on?Nn.cloneWithOperation(e.on,"And",o):Nn.create(o)})}})});var Qo,$n=f(()=>{$();Qo=l({is(e){return e.kind==="BinaryOperationNode"},create(e,o,t){return l({kind:"BinaryOperationNode",leftOperand:e,operator:o,rightOperand:t})}})});function Zl(e){return H(e)&&Xl[e]}function eu(e){return H(e)&&Hl[e]}function ou(e){return H(e)&&Kl[e]}var Ql,PN,Gl,TN,Hl,Kb,Xl,Zb,Yl,MN,Kl,ew,IN,Ze,Mt=f(()=>{$();Ql=l({"=":!0,"==":!0,"!=":!0,"<>":!0,">":!0,">=":!0,"<":!0,"<=":!0,in:!0,"not in":!0,is:!0,"is not":!0,like:!0,"not like":!0,match:!0,ilike:!0,"not ilike":!0,"@>":!0,"<@":!0,"^@":!0,"&&":!0,"?":!0,"?&":!0,"?|":!0,"!<":!0,"!>":!0,"<=>":!0,"!~":!0,"~":!0,"~*":!0,"!~*":!0,"@@":!0,"@@@":!0,"!!":!0,"<->":!0,regexp:!0,"is distinct from":!0,"is not distinct from":!0}),PN=Object.keys(Ql),Gl=l({"+":!0,"-":!0,"*":!0,"/":!0,"%":!0,"^":!0,"&":!0,"|":!0,"#":!0,"<<":!0,">>":!0}),TN=Object.keys(Gl),Hl=l({"->":!0,"->>":!0}),Kb=Object.keys(Hl),Xl=l({...Ql,...Gl,"||":!0}),Zb=Object.keys(Xl),Yl=l({exists:!0,"not exists":!0}),MN=Object.keys(Yl),Kl=l({...Yl,"-":!0,not:!0}),ew=Object.keys(Kl),IN=[...Zb,...Kb,...ew,"between","between symmetric"],Ze=l({is(e){return e.kind==="OperatorNode"},create(e){return l({kind:"OperatorNode",operator:e})}})});var ue,eo=f(()=>{$();ne();ue=l({is(e){return e.kind==="ColumnNode"},create(e){return l({kind:"ColumnNode",column:M.create(e)})}})});var xn,Cn=f(()=>{$();xn=l({is(e){return e.kind==="SelectAllNode"},create(){return l({kind:"SelectAllNode"})}})});var It,jn=f(()=>{Cn();$();It=l({is(e){return e.kind==="ReferenceNode"},create(e,o){return l({kind:"ReferenceNode",table:o,column:e})},createSelectAll(e){return l({kind:"ReferenceNode",table:e,column:xn.create()})}})});function Sn(e){return je(e)&&ie(e)&&H(e.dynamicReference)}var On=f(()=>{Je();$()});var oo,An=f(()=>{$();oo=l({is(e){return e.kind==="OrderByItemNode"},create(e,o){return l({kind:"OrderByItemNode",orderBy:e,direction:o})},cloneWith(e,o){return l({...e,...o})}})});var de,pt=f(()=>{$();de=l({is(e){return e.kind==="RawNode"},create(e,o){return l({kind:"RawNode",sqlFragments:l(e),parameters:l(o)})},createWithSql(e){return de.create([e],[])},createWithChild(e){return de.create(["",""],[e])},createWithChildren(e){return de.create(new Array(e.length+1).fill(""),e)}})});var tu,ua=f(()=>{$();ne();tu=l({is(e){return e.kind==="CollateNode"},create(e){return l({kind:"CollateNode",collation:M.create(e)})}})});var En,da=f(()=>{ua();An();pt();$();En=class e{#e;constructor(o){this.#e=l(o)}desc(){return new e({node:oo.cloneWith(this.#e.node,{direction:de.createWithSql("desc")})})}asc(){return new e({node:oo.cloneWith(this.#e.node,{direction:de.createWithSql("asc")})})}nullsLast(){return new e({node:oo.cloneWith(this.#e.node,{nulls:"last"})})}nullsFirst(){return new e({node:oo.cloneWith(this.#e.node,{nulls:"first"})})}collate(o){return new e({node:oo.cloneWith(this.#e.node,{collation:tu.create(o)})})}toOperationNode(){return this.#e.node}}});function Dt(e){ru.has(e)||(ru.add(e),console.log(e))}var ru,pa=f(()=>{ru=new Set});function ow(e){return e==="asc"||e==="desc"}function to(e){if(e.length===2)return[ma(e[0],e[1])];if(e.length===1){let[o]=e;return Array.isArray(o)?(Dt("orderBy(array) is deprecated, use multiple orderBy calls instead."),o.map(t=>ma(t))):[ma(o)]}throw new Error(`Invalid number of arguments at order by! expected 1-2, received ${e.length}`)}function ma(e,o){let t=tw(e);if(oo.is(t)){if(o)throw new Error("Cannot specify direction twice!");return t}return nu(t,o)}function tw(e){if(mt(e))return Go(e);if(Sn(e))return e.toOperationNode();let[o,t]=e.split(" ");return t?(Dt("`orderBy('column asc')` is deprecated. Use `orderBy('column', 'asc')` instead."),nu(Qe(o),t)):Qe(e)}function nu(e,o){if(typeof o=="string"){if(!ow(o))throw new Error(`Invalid order by direction: ${o}`);return oo.create(e,de.createWithSql(o))}if(yn(o))return Dt("`orderBy(..., expr)` is deprecated. Use `orderBy(..., 'asc')` or `orderBy(..., (ob) => ...)` instead."),oo.create(e,o.toOperationNode());let t=oo.create(e);return o?o(new En({node:t})).toOperationNode():t}var Lt=f(()=>{On();_n();An();pt();da();pa();ft();Ie()});var zt,qn=f(()=>{$();zt=l({is(e){return e.kind==="JSONReferenceNode"},create(e,o){return l({kind:"JSONReferenceNode",reference:e,traversal:o})},cloneWithTraversal(e,o){return l({...e,traversal:o})}})});var Rn,kn=f(()=>{$();Rn=l({is(e){return e.kind==="JSONOperatorChainNode"},create(e){return l({kind:"JSONOperatorChainNode",operator:e,values:l([])})},cloneWithValue(e,o){return l({...e,values:l([...e.values,o])})}})});var Ho,Cr=f(()=>{$();Ho=l({is(e){return e.kind==="JSONPathNode"},create(e){return l({kind:"JSONPathNode",inOperator:e,pathLegs:l([])})},cloneWithLeg(e,o){return l({...e,pathLegs:l([...e.pathLegs,o])})}})});function rw(e){return H(e)?Qe(e):e.toOperationNode()}function jo(e){return ke(e)?e.map(o=>fe(o)):[fe(e)]}function fe(e){return mt(e)?Go(e):rw(e)}function iu(e,o){if(eu(o))return zt.create(Qe(e),Rn.create(Ze.create(o)));if(o==="->$"||o==="->>$")return zt.create(Qe(e),Ho.create(Ze.create(o.slice(0,-1))));throw new Error(`Invalid JSON operator: ${o}`)}function Qe(e){if(!e.includes("."))return It.create(ue.create(e));let t=e.split(".").map(su);if(t.length===3)return nw(t);if(t.length===2)return iw(t);throw new Error(`invalid column reference ${e}`)}function au(e){let o=" as ";if(e.includes(o)){let[t,n]=e.split(o).map(su);return Pe.create(Qe(t),M.create(n))}else return Qe(e)}function nw(e){let[o,t,n]=e;return It.create(ue.create(n),Uo.createWithSchema(o,t))}function iw(e){let[o,t]=e;return It.create(ue.create(t),Uo.create(o))}function su(e){return e.trim()}var Ie=f(()=>{xo();eo();jn();$r();$();ft();ne();Mt();qn();kn();Cr()});var cu,fa=f(()=>{$();cu=l({is(e){return e.kind==="PrimitiveValueListNode"},create(e){return l({kind:"PrimitiveValueListNode",values:l([...e])})}})});var Pn,Tn=f(()=>{$();Pn=l({is(e){return e.kind==="ValueListNode"},create(e){return l({kind:"ValueListNode",values:l(e)})}})});var Se,Xo=f(()=>{$();Se=l({is(e){return e.kind==="ValueNode"},create(e){return l({kind:"ValueNode",value:e})},createImmediate(e){return l({kind:"ValueNode",value:e,immediate:!0})}})});function lu(e){return ke(e)?aw(e):Z(e)}function Z(e){return mt(e)?Go(e):Se.create(e)}function Mn(e){return uo(e)||st(e)||ct(e)}function jr(e){if(!Mn(e))throw new Error(`unsafe immediate value ${JSON.stringify(e)}`);return Se.createImmediate(e)}function aw(e){return e.some(mt)?Pn.create(e.map(o=>Z(o))):cu.create(e)}var So=f(()=>{fa();Tn();Xo();$();ft()});var Yo,Sr=f(()=>{$();Yo=l({is(e){return e.kind==="ParensNode"},create(e){return l({kind:"ParensNode",node:e})}})});function pe(e){if(e.length===3)return In(e[0],e[1],e[2]);if(e.length===1)return Z(e[0]);throw new Error(`invalid arguments: ${JSON.stringify(e)}`)}function In(e,o,t){return sw(o)&&du(t)?Qo.create(fe(e),ha(o),Se.createImmediate(t)):Qo.create(fe(e),ha(o),lu(t))}function xe(e,o,t){return Qo.create(fe(e),ha(o),fe(t))}function ga(e,o){return Dn(Object.entries(e).filter(([,t])=>!$o(t)).map(([t,n])=>In(t,du(n)?"is":"=",n)),o)}function Dn(e,o,t=!0){let n=o==="and"?Te.create:Ke.create;if(e.length===0)return Qo.create(Se.createImmediate(1),Ze.create("="),Se.createImmediate(o==="and"?1:0));let r=uu(e[0]);for(let a=1;a<e.length;++a)r=n(r,uu(e[a]));return e.length>1&&t?Yo.create(r):r}function sw(e){return e==="is"||e==="is not"}function du(e){return ct(e)||st(e)}function ha(e){if(Zl(e))return Ze.create(e);if(ie(e))return e.toOperationNode();throw new Error(`invalid operator ${JSON.stringify(e)}`)}function uu(e){return ie(e)?e.toOperationNode():e}var mo=f(()=>{$n();$();Je();Mt();Ie();So();Xo();Jo();Sr();dt()});var Oo,Or=f(()=>{$();Oo=l({is(e){return e.kind==="OrderByNode"},create(e){return l({kind:"OrderByNode",items:l([...e])})},cloneWithItems(e,o){return l({...e,items:l([...e.items,...o])})}})});var ba,wa=f(()=>{$();ba=l({is(e){return e.kind==="PartitionByNode"},create(e){return l({kind:"PartitionByNode",items:l(e)})},cloneWithItems(e,o){return l({...e,items:l([...e.items,...o])})}})});var Ar,Ln=f(()=>{$();Or();wa();Ar=l({is(e){return e.kind==="OverNode"},create(){return l({kind:"OverNode"})},cloneWithOrderByItems(e,o){return l({...e,orderBy:e.orderBy?Oo.cloneWithItems(e.orderBy,o):Oo.create(o)})},cloneWithPartitionByItems(e,o){return l({...e,partitionBy:e.partitionBy?ba.cloneWithItems(e.partitionBy,o):ba.create(o)})}})});var ht,Er=f(()=>{$();ht=l({is(e){return e.kind==="FromNode"},create(e){return l({kind:"FromNode",froms:l(e)})},cloneWithFroms(e,o){return l({...e,froms:l([...e.froms,...o])})}})});var va,ya=f(()=>{$();va=l({is(e){return e.kind==="GroupByNode"},create(e){return l({kind:"GroupByNode",items:l(e)})},cloneWithItems(e,o){return l({...e,items:l([...e.items,...o])})}})});var _a,Na=f(()=>{$();Jo();dt();_a=l({is(e){return e.kind==="HavingNode"},create(e){return l({kind:"HavingNode",having:e})},cloneWithOperation(e,o,t){return l({...e,having:o==="And"?Te.create(e.having,t):Ke.create(e.having,t)})}})});var pu,$a=f(()=>{$();pu=l({is(e){return e.kind==="InsertQueryNode"},create(e,o,t){return l({kind:"InsertQueryNode",into:e,...o&&{with:o},replace:t})},createWithoutInto(){return l({kind:"InsertQueryNode"})},cloneWith(e,o){return l({...e,...o})}})});var mu,xa=f(()=>{$();mu=l({is(e){return e.kind==="ListNode"},create(e){return l({kind:"ListNode",items:l(e)})}})});var Ft,zn=f(()=>{$();Er();xa();Ft=l({is(e){return e.kind==="UpdateQueryNode"},create(e,o){return l({kind:"UpdateQueryNode",table:e.length===1?e[0]:mu.create(e),...o&&{with:o}})},createWithoutTable(){return l({kind:"UpdateQueryNode"})},cloneWithFromItems(e,o){return l({...e,from:e.from?ht.cloneWithFroms(e.from,o):ht.create(o)})},cloneWithUpdates(e,o){return l({...e,updates:e.updates?l([...e.updates,...o]):o})},cloneWithLimit(e,o){return l({...e,limit:o})}})});var Ca,ja=f(()=>{$();Ca=l({is(e){return e.kind==="UsingNode"},create(e){return l({kind:"UsingNode",tables:l(e)})},cloneWithTables(e,o){return l({...e,tables:l([...e.tables,...o])})}})});var Wt,Fn=f(()=>{$();Er();ja();Ao();Wt=l({is(e){return e.kind==="DeleteQueryNode"},create(e,o){return l({kind:"DeleteQueryNode",from:ht.create(e),...o&&{with:o}})},cloneWithOrderByItems:(e,o)=>P.cloneWithOrderByItems(e,o),cloneWithoutOrderBy:e=>P.cloneWithoutOrderBy(e),cloneWithLimit(e,o){return l({...e,limit:o})},cloneWithoutLimit(e){return l({...e,limit:void 0})},cloneWithUsing(e,o){return l({...e,using:e.using!==void 0?Ca.cloneWithTables(e.using,o):Ca.create(o)})}})});var ye,qr=f(()=>{$();Jo();dt();ye=l({is(e){return e.kind==="WhereNode"},create(e){return l({kind:"WhereNode",where:e})},cloneWithOperation(e,o,t){return l({...e,where:o==="And"?Te.create(e.where,t):Ke.create(e.where,t)})}})});var Sa,Oa=f(()=>{$();Sa=l({is(e){return e.kind==="ReturningNode"},create(e){return l({kind:"ReturningNode",selections:l(e)})},cloneWithSelections(e,o){return l({...e,selections:e.selections?l([...e.selections,...o]):l(o)})}})});var fu,Aa=f(()=>{$();fu=l({is(e){return e.kind==="ExplainNode"},create(e,o){return l({kind:"ExplainNode",format:e,options:o})}})});var Eo,Rr=f(()=>{$();Eo=l({is(e){return e.kind==="WhenNode"},create(e){return l({kind:"WhenNode",condition:e})},cloneWithResult(e,o){return l({...e,result:o})}})});var hu,Ea=f(()=>{$();Rr();hu=l({is(e){return e.kind==="MergeQueryNode"},create(e,o){return l({kind:"MergeQueryNode",into:e,...o&&{with:o}})},cloneWithUsing(e,o){return l({...e,using:o})},cloneWithWhen(e,o){return l({...e,whens:e.whens?l([...e.whens,o]):l([o])})},cloneWithThen(e,o){return l({...e,whens:e.whens?l([...e.whens.slice(0,-1),Eo.cloneWithResult(e.whens[e.whens.length-1],o)]):void 0})}})});var qa,Ra=f(()=>{$();qa=l({is(e){return e.kind==="OutputNode"},create(e){return l({kind:"OutputNode",selections:l(e)})},cloneWithSelections(e,o){return l({...e,selections:e.selections?l([...e.selections,...o]):l(o)})}})});var P,Ao=f(()=>{$a();kr();zn();Fn();qr();$();Oa();Aa();Ea();Ra();Or();P=l({is(e){return ee.is(e)||pu.is(e)||Ft.is(e)||Wt.is(e)||hu.is(e)},cloneWithEndModifier(e,o){return l({...e,endModifiers:e.endModifiers?l([...e.endModifiers,o]):l([o])})},cloneWithWhere(e,o){return l({...e,where:e.where?ye.cloneWithOperation(e.where,"And",o):ye.create(o)})},cloneWithJoin(e,o){return l({...e,joins:e.joins?l([...e.joins,o]):l([o])})},cloneWithReturning(e,o){return l({...e,returning:e.returning?Sa.cloneWithSelections(e.returning,o):Sa.create(o)})},cloneWithoutReturning(e){return l({...e,returning:void 0})},cloneWithoutWhere(e){return l({...e,where:void 0})},cloneWithExplain(e,o,t){return l({...e,explain:fu.create(o,t?.toOperationNode())})},cloneWithTop(e,o){return l({...e,top:o})},cloneWithOutput(e,o){return l({...e,output:e.output?qa.cloneWithSelections(e.output,o):qa.create(o)})},cloneWithOrderByItems(e,o){return l({...e,orderBy:e.orderBy?Oo.cloneWithItems(e.orderBy,o):Oo.create(o)})},cloneWithoutOrderBy(e){return l({...e,orderBy:void 0})}})});var ee,kr=f(()=>{$();Er();ya();Na();Ao();ee=l({is(e){return e.kind==="SelectQueryNode"},create(e){return l({kind:"SelectQueryNode",...e&&{with:e}})},createFrom(e,o){return l({kind:"SelectQueryNode",from:ht.create(e),...o&&{with:o}})},cloneWithSelections(e,o){return l({...e,selections:e.selections?l([...e.selections,...o]):l(o)})},cloneWithDistinctOn(e,o){return l({...e,distinctOn:e.distinctOn?l([...e.distinctOn,...o]):l(o)})},cloneWithFrontModifier(e,o){return l({...e,frontModifiers:e.frontModifiers?l([...e.frontModifiers,o]):l([o])})},cloneWithOrderByItems:(e,o)=>P.cloneWithOrderByItems(e,o),cloneWithGroupByItems(e,o){return l({...e,groupBy:e.groupBy?va.cloneWithItems(e.groupBy,o):va.create(o)})},cloneWithLimit(e,o){return l({...e,limit:o})},cloneWithOffset(e,o){return l({...e,offset:o})},cloneWithFetch(e,o){return l({...e,fetch:o})},cloneWithHaving(e,o){return l({...e,having:e.having?_a.cloneWithOperation(e.having,"And",o):_a.create(o)})},cloneWithSetOperations(e,o){return l({...e,setOperations:e.setOperations?l([...e.setOperations,...o]):l([...o])})},cloneWithoutSelections(e){return l({...e,selections:[]})},cloneWithoutLimit(e){return l({...e,limit:void 0})},cloneWithoutOffset(e){return l({...e,offset:void 0})},cloneWithoutOrderBy:e=>P.cloneWithoutOrderBy(e),cloneWithoutGroupBy(e){return l({...e,groupBy:void 0})}})});var Wn,ka=f(()=>{xr();pt();mo();$();Wn=class e{#e;constructor(o){this.#e=l(o)}on(...o){return new e({...this.#e,joinNode:Co.cloneWithOn(this.#e.joinNode,pe(o))})}onRef(o,t,n){return new e({...this.#e,joinNode:Co.cloneWithOn(this.#e.joinNode,xe(o,t,n))})}onTrue(){return new e({...this.#e,joinNode:Co.cloneWithOn(this.#e.joinNode,de.createWithSql("true"))})}$call(o){return o(this)}toOperationNode(){return this.#e.joinNode}}});var gu,Pa=f(()=>{$();gu=l({is(e){return e.kind==="PartitionByItemNode"},create(e){return l({kind:"PartitionByItemNode",partitionBy:e})}})});function bu(e){return jo(e).map(gu.create)}var wu=f(()=>{Pa();Ie()});var Bn,vu=f(()=>{Ln();Ao();Lt();wu();$();Bn=class e{#e;constructor(o){this.#e=l(o)}orderBy(...o){return new e({overNode:Ar.cloneWithOrderByItems(this.#e.overNode,to(o))})}clearOrderBy(){return new e({overNode:P.cloneWithoutOrderBy(this.#e.overNode)})}partitionBy(o){return new e({overNode:Ar.cloneWithPartitionByItems(this.#e.overNode,bu(o))})}$call(o){return o(this)}toOperationNode(){return this.#e.overNode}}});var Bt,Ta=f(()=>{$();jn();Cn();Bt=l({is(e){return e.kind==="SelectionNode"},create(e){return l({kind:"SelectionNode",selection:e})},createSelectAll(){return l({kind:"SelectionNode",selection:xn.create()})},createSelectAllFromTable(e){return l({kind:"SelectionNode",selection:It.createSelectAll(e)})}})});function qo(e){return $e(e)?qo(e(Ro())):ke(e)?e.map(o=>yu(o)):[yu(e)]}function yu(e){return H(e)?Bt.create(au(e)):Sn(e)?Bt.create(e.toOperationNode()):Bt.create(Vn(e))}function fo(e){return e?Array.isArray(e)?e.map(_u):[_u(e)]:[Bt.createSelectAll()]}function _u(e){if(H(e))return Bt.createSelectAllFromTable(Ce(e));throw new Error(`invalid value selectAll expression: ${JSON.stringify(e)}`)}var Pr=f(()=>{$();Ta();Ie();On();ft();ho();Vt()});var JC,Nu=f(()=>{$();JC=l({is(e){return e.kind==="ValuesNode"},create(e){return l({kind:"ValuesNode",values:l(e)})}})});var HC,$u=f(()=>{$();HC=l({is(e){return e.kind==="DefaultInsertValueNode"},create(){return l({kind:"DefaultInsertValueNode"})}})});var Ma,Ia=f(()=>{$();Ma=l({is(e){return e.kind==="ColumnUpdateNode"},create(e,o){return l({kind:"ColumnUpdateNode",column:e,value:o})}})});function xu(...e){return e.length===2?[Ma.create(fe(e[0]),Z(e[1]))]:cw(e[0])}function cw(e){let o=$e(e)?e(Ro()):e;return Object.entries(o).filter(([t,n])=>n!==void 0).map(([t,n])=>Ma.create(ue.create(t),Z(n)))}var Cu=f(()=>{eo();Ia();Vt();$();So();Ie()});var sj,ju=f(()=>{$();sj=l({is(e){return e.kind==="OnDuplicateKeyNode"},create(e){return l({kind:"OnDuplicateKeyNode",updates:e})}})});var Su=f(()=>{});function Ut(e){return Object.prototype.hasOwnProperty.call(e,"prototype")}var Ko,Tr=f(()=>{Ko=class extends Error{node;constructor(o){super("no result"),this.node=o}}});var mj,Ou=f(()=>{$();qr();mj=l({is(e){return e.kind==="OnConflictNode"},create(){return l({kind:"OnConflictNode"})},cloneWith(e,o){return l({...e,...o})},cloneWithIndexWhere(e,o){return l({...e,indexWhere:e.indexWhere?ye.cloneWithOperation(e.indexWhere,"And",o):ye.create(o)})},cloneWithIndexOrWhere(e,o){return l({...e,indexWhere:e.indexWhere?ye.cloneWithOperation(e.indexWhere,"Or",o):ye.create(o)})},cloneWithUpdateWhere(e,o){return l({...e,updateWhere:e.updateWhere?ye.cloneWithOperation(e.updateWhere,"And",o):ye.create(o)})},cloneWithUpdateOrWhere(e,o){return l({...e,updateWhere:e.updateWhere?ye.cloneWithOperation(e.updateWhere,"Or",o):ye.create(o)})},cloneWithoutIndexWhere(e){return l({...e,indexWhere:void 0})},cloneWithoutUpdateWhere(e){return l({...e,updateWhere:void 0})}})});var Au=f(()=>{});var Eu,Da=f(()=>{$();Eu=l({is(e){return e.kind==="TopNode"},create(e,o){return l({kind:"TopNode",expression:e,modifiers:o})}})});function Jt(e,o){if(!uo(e)&&!lt(e))throw new Error(`Invalid top expression: ${e}`);if(!$o(o)&&!lw(o))throw new Error(`Invalid top modifiers: ${o}`);return Eu.create(e,o)}function lw(e){return e==="percent"||e==="with ties"||e==="percent with ties"}var Un=f(()=>{Da();$()});var Nj,qu=f(()=>{$();Nj=l({is(e){return e.kind==="OrActionNode"},create(e){return l({kind:"OrActionNode",action:e})}})});var Ru=f(()=>{});var Jn,La=f(()=>{Jn=class{numDeletedRows;constructor(o){this.numDeletedRows=o}}});var Qt,Mr=f(()=>{$();Qt=l({is(e){return e.kind==="LimitNode"},create(e){return l({kind:"LimitNode",limit:e})}})});var ae,za,ku=f(()=>{Qn();ho();Pr();Ao();$();Tr();La();Fn();Mr();Lt();mo();So();Un();za=class{#e;constructor(o){this.#e=l(o)}where(...o){return new ae({...this.#e,queryNode:P.cloneWithWhere(this.#e.queryNode,pe(o))})}whereRef(o,t,n){return new ae({...this.#e,queryNode:P.cloneWithWhere(this.#e.queryNode,xe(o,t,n))})}clearWhere(){return new ae({...this.#e,queryNode:P.cloneWithoutWhere(this.#e.queryNode)})}top(o,t){return new ae({...this.#e,queryNode:P.cloneWithTop(this.#e.queryNode,Jt(o,t))})}using(o){return new ae({...this.#e,queryNode:Wt.cloneWithUsing(this.#e.queryNode,gt(o))})}innerJoin(...o){return this.#o("InnerJoin",o)}leftJoin(...o){return this.#o("LeftJoin",o)}rightJoin(...o){return this.#o("RightJoin",o)}fullJoin(...o){return this.#o("FullJoin",o)}#o(o,t){return new ae({...this.#e,queryNode:P.cloneWithJoin(this.#e.queryNode,Gt(o,t))})}returning(o){return new ae({...this.#e,queryNode:P.cloneWithReturning(this.#e.queryNode,qo(o))})}returningAll(o){return new ae({...this.#e,queryNode:P.cloneWithReturning(this.#e.queryNode,fo(o))})}output(o){return new ae({...this.#e,queryNode:P.cloneWithOutput(this.#e.queryNode,qo(o))})}outputAll(o){return new ae({...this.#e,queryNode:P.cloneWithOutput(this.#e.queryNode,fo(o))})}clearReturning(){return new ae({...this.#e,queryNode:P.cloneWithoutReturning(this.#e.queryNode)})}clearLimit(){return new ae({...this.#e,queryNode:Wt.cloneWithoutLimit(this.#e.queryNode)})}orderBy(...o){return new ae({...this.#e,queryNode:P.cloneWithOrderByItems(this.#e.queryNode,to(o))})}clearOrderBy(){return new ae({...this.#e,queryNode:P.cloneWithoutOrderBy(this.#e.queryNode)})}limit(o){return new ae({...this.#e,queryNode:Wt.cloneWithLimit(this.#e.queryNode,Qt.create(Z(o)))})}modifyEnd(o){return new ae({...this.#e,queryNode:P.cloneWithEndModifier(this.#e.queryNode,o.toOperationNode())})}$call(o){return o(this)}$if(o,t){return o?t(this):new ae({...this.#e})}$castTo(){return new ae(this.#e)}$narrowType(){return new ae(this.#e)}$assertType(){return new ae(this.#e)}withPlugin(o){return new ae({...this.#e,executor:this.#e.executor.withPlugin(o)})}toOperationNode(){return this.#e.executor.transformQuery(this.#e.queryNode,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(o){let t=this.compile(),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 Jn(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??Ko;throw Ut(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 ae({...this.#e,queryNode:P.cloneWithExplain(this.#e.queryNode,o,t)}).execute()}};ae=za});var Gn,Fa=f(()=>{Gn=class{numUpdatedRows;numChangedRows;constructor(o,t){this.numUpdatedRows=o,this.numChangedRows=t}}});var se,Wa,Pu=f(()=>{Qn();ho();Pr();Ao();zn();Cu();$();Fa();Tr();mo();So();Mr();Un();Lt();Wa=class{#e;constructor(o){this.#e=l(o)}where(...o){return new se({...this.#e,queryNode:P.cloneWithWhere(this.#e.queryNode,pe(o))})}whereRef(o,t,n){return new se({...this.#e,queryNode:P.cloneWithWhere(this.#e.queryNode,xe(o,t,n))})}clearWhere(){return new se({...this.#e,queryNode:P.cloneWithoutWhere(this.#e.queryNode)})}top(o,t){return new se({...this.#e,queryNode:P.cloneWithTop(this.#e.queryNode,Jt(o,t))})}from(o){return new se({...this.#e,queryNode:Ft.cloneWithFromItems(this.#e.queryNode,gt(o))})}innerJoin(...o){return this.#o("InnerJoin",o)}leftJoin(...o){return this.#o("LeftJoin",o)}rightJoin(...o){return this.#o("RightJoin",o)}fullJoin(...o){return this.#o("FullJoin",o)}#o(o,t){return new se({...this.#e,queryNode:P.cloneWithJoin(this.#e.queryNode,Gt(o,t))})}orderBy(...o){return new se({...this.#e,queryNode:P.cloneWithOrderByItems(this.#e.queryNode,to(o))})}clearOrderBy(){return new se({...this.#e,queryNode:P.cloneWithoutOrderBy(this.#e.queryNode)})}limit(o){return new se({...this.#e,queryNode:Ft.cloneWithLimit(this.#e.queryNode,Qt.create(Z(o)))})}set(...o){return new se({...this.#e,queryNode:Ft.cloneWithUpdates(this.#e.queryNode,xu(...o))})}returning(o){return new se({...this.#e,queryNode:P.cloneWithReturning(this.#e.queryNode,qo(o))})}returningAll(o){return new se({...this.#e,queryNode:P.cloneWithReturning(this.#e.queryNode,fo(o))})}output(o){return new se({...this.#e,queryNode:P.cloneWithOutput(this.#e.queryNode,qo(o))})}outputAll(o){return new se({...this.#e,queryNode:P.cloneWithOutput(this.#e.queryNode,fo(o))})}modifyEnd(o){return new se({...this.#e,queryNode:P.cloneWithEndModifier(this.#e.queryNode,o.toOperationNode())})}clearReturning(){return new se({...this.#e,queryNode:P.cloneWithoutReturning(this.#e.queryNode)})}$call(o){return o(this)}$if(o,t){return o?t(this):new se({...this.#e})}$castTo(){return new se(this.#e)}$narrowType(){return new se(this.#e)}$assertType(){return new se(this.#e)}withPlugin(o){return new se({...this.#e,executor:this.#e.executor.withPlugin(o)})}toOperationNode(){return this.#e.executor.transformQuery(this.#e.queryNode,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(o){let t=this.compile(),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 Gn(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??Ko;throw Ut(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 se({...this.#e,queryNode:P.cloneWithExplain(this.#e.queryNode,o,t)}).execute()}};se=Wa});var sS,Tu=f(()=>{$();eo();$r();sS=l({is(e){return e.kind==="CommonTableExpressionNameNode"},create(e,o){return l({kind:"CommonTableExpressionNameNode",table:Uo.create(e),columns:o?l(o.map(ue.create)):void 0})}})});var uS,Mu=f(()=>{$();uS=l({is(e){return e.kind==="CommonTableExpressionNode"},create(e,o){return l({kind:"CommonTableExpressionNode",name:e,expression:o})},cloneWith(e,o){return l({...e,...o})}})});var mS,Iu=f(()=>{$();mS=l({is(e){return e.kind==="WithNode"},create(e,o){return l({kind:"WithNode",expressions:l([e]),...o})},cloneWithExpression(e,o){return l({...e,expressions:l([...e.expressions,o])})}})});function Hn(e){let o="";for(let t=0;t<e;++t)o+=uw();return o}function uw(){return Du[~~(Math.random()*Du.length)]}var Du,Ba=f(()=>{Du=["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 De(){return new Va}var Va,Xn=f(()=>{Ba();Va=class{#e;get queryId(){return this.#e===void 0&&(this.#e=Hn(8)),this.#e}}});var Lu=f(()=>{});var zu=f(()=>{});var _S,Fu=f(()=>{$();_S=l({is(e){return e.kind==="MatchedNode"},create(e,o=!1){return l({kind:"MatchedNode",not:e,bySource:o})}})});var Oe,Ir=f(()=>{Oe=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 Yn(e,o){let t=new Oe,n=new Oe;return e.provideConnection(async r=>(t.resolve(r),await n.promise),o).catch(r=>t.reject(r)),l({connection:await t.promise,release:n.resolve})}var Wu=f(()=>{Ir();$()});function Vu(e="ignore query",o,t){if(e!=="ignore query"){if(e==="cancel query"){let n=o.cancelQuery;return n||(t(),Bu(e,o.killSession?"kill session":void 0)),n.bind(o)}if(e==="kill session"){let n=o.killSession;return n||(t(),Bu(e,o.cancelQuery?"cancel query":void 0)),n.bind(o)}throw t(),new Error(`Unexpected \`inflightQueryAbortStrategy\`: "${e}"`)}}function Bu(e,o){throw new Error(`This dialect doesn't support \`inflightQueryAbortStrategy\` "${e}". Use "ignore query"${o?` or "${o}"`:""} instead.`)}function bt(e,o,t){e?.aborted&&(t?.(),wt(e.reason,o))}function wt(e,o){throw dw(e,o),e}function vt(e){return o=>console.error(`\`${e}\` failed in the background after abortion: ${Dl(o)}`)}function dw(e,o){e!==null&&typeof e=="object"&&!Object.isFrozen(e)&&Object.defineProperty(e,"__kysely_timing__",{configurable:!0,enumerable:!1,value:o,writable:!1})}var go,Uu=f(()=>{$();go={}});var pw,Kn,Ju=f(()=>{$();Wu();Uu();Ir();pw=l([]),Kn=class{#e;constructor(o=pw){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 m=await this.provideConnection(async h=>await h.executeQuery(o),t);return await this.#o(m,o.queryId)}bt(r,"before query execution"),t=l({signal:r});let{connection:a,release:s}=await Yn(this,t),c=this.provideConnection.bind(this),{promise:d,resolve:u}=new Oe,p=()=>u(go);r.addEventListener("abort",p,{once:!0});try{bt(r,"before query execution",s);let m=Vu(n,a,s);if(m&&a.collectSessionInfo){bt(r,"before query execution",s);let w=a.collectSessionInfo();await Promise.race([d,w]).catch(j=>{throw s(),j})===go&&(w.catch(vt("collectSessionInfo")).finally(s),wt(r.reason,"before query execution"))}let h=a.executeQuery(o,t),b=await Promise.race([d,h]).catch(w=>{throw s(),w});b===go?(Promise.allSettled([h.catch(vt("query")),m?.(c).catch(vt("inflightQueryAbortHandler"))]).finally(s),wt(r.reason,"during query execution")):s();let y=this.#o(b,o.queryId,t),v=await Promise.race([d,y]);return v===go&&(y.catch(vt("plugins.transformResult")),wt(r.reason,"during result transformation")),v}finally{u(go),r.removeEventListener("abort",p)}}async*stream(o,t,n){let{signal:r}=n||{};if(!r){let{connection:b,release:y}=await Yn(this);try{for await(let v of b.streamQuery(o,t))yield await this.#o(v,o.queryId,n)}finally{y()}return}n=l({signal:r}),bt(r,"before connection acquisition");let{connection:a,release:s}=await Yn(this,n),{promise:c,resolve:d}=new Oe,u=()=>d(go);r.addEventListener("abort",u,{once:!0});let p,m;bt(r,"before query streaming",s);let{queryId:h}=o;try{for(p=a.streamQuery(o,t,n);;){bt(r,"during query streaming");let b=p.next(),y=await Promise.race([c,b]);if(y===go&&(m=b.catch(vt("iterator.next")),wt(r.reason,"during query streaming")),y.done)break;let v=this.#o(y.value,h,n),w=await Promise.race([c,v]);w===go&&(m=v.catch(vt("plugins.transformResult")),wt(r.reason,"during result transformation")),yield w}}finally{d(go),r.removeEventListener("abort",u);let b=(p?.return?.()||Promise.resolve()).finally(()=>m).finally(s);m||await b}}async#o(o,t,n){let{signal:r}=n||{};for(let a of this.#e)o=await a.transformResult(l({queryId:t,result:o,signal:r}));return o}}});var Ua,Zn,ei=f(()=>{Ju();Ua=class e extends Kn{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([])}},Zn=new Ua});var Qu=f(()=>{});var Gu=f(()=>{});var Hu=f(()=>{});function Xu(e,o){return new Wn({joinNode:Co.create(e,yt(o))})}function Yu(){return new Bn({overNode:Ar.create()})}var Ja=f(()=>{xr();Ln();ka();vu();ho()});function Gt(e,o){if(o.length===3)return fw(e,o[0],o[1],o[2]);if(o.length===2)return mw(e,o[0],o[1]);if(o.length===1)return hw(e,o[0]);throw new Error("not implemented")}function mw(e,o,t){return t(Xu(e,o)).toOperationNode()}function fw(e,o,t,n){return Co.createWithOn(e,yt(o),xe(t,"=",n))}function hw(e,o){return Co.create(e,yt(o))}var Qn=f(()=>{xr();mo();Ja();ho()});var Ku,Qa=f(()=>{$();Ku=l({is(e){return e.kind==="OffsetNode"},create(e){return l({kind:"OffsetNode",offset:e})}})});var Zu,Ga=f(()=>{$();Zu=l({is(e){return e.kind==="GroupByItemNode"},create(e){return l({kind:"GroupByItemNode",groupBy:e})}})});function ed(e){return e=$e(e)?e(Ro()):e,jo(e).map(Zu.create)}var od=f(()=>{Ga();Vt();$();Ie()});var td,Ha=f(()=>{$();td=l({is(e){return e.kind==="SetOperationNode"},create(e,o,t){return l({kind:"SetOperationNode",operator:e,expression:o,all:t})}})});function _t(e,o,t){return $e(o)&&(o=o(Xa())),ke(o)||(o=[o]),o.map(n=>td.create(e,Go(n),t))}var rd=f(()=>{Vt();Ha();$();ft()});var Q,Dr,Ya,Ka,Ht=f(()=>{xo();Jo();ne();Je();dt();Sr();mo();Q=class e{#e;constructor(o){this.#e=o}get expressionType(){}as(o){return new Dr(this,o)}or(...o){return new Ya(Ke.create(this.#e,pe(o)))}and(...o){return new Ka(Te.create(this.#e,pe(o)))}$castTo(){return new e(this.#e)}$notNull(){return new e(this.#e)}toOperationNode(){return this.#e}},Dr=class{#e;#o;constructor(o,t){this.#e=o,this.#o=t}get expression(){return this.#e}get alias(){return this.#o}toOperationNode(){return Pe.create(this.#e.toOperationNode(),ie(this.#o)?this.#o.toOperationNode():M.create(this.#o))}},Ya=class e{#e;constructor(o){this.#e=o}get expressionType(){}as(o){return new Dr(this,o)}or(...o){return new e(Ke.create(this.#e,pe(o)))}$castTo(){return new e(this.#e)}toOperationNode(){return Yo.create(this.#e)}},Ka=class e{#e;constructor(o){this.#e=o}get expressionType(){}as(o){return new Dr(this,o)}and(...o){return new e(Te.create(this.#e,pe(o)))}$castTo(){return new e(this.#e)}toOperationNode(){return Yo.create(this.#e)}}});var nd,Za=f(()=>{$();Xo();nd=l({is(e){return e.kind==="FetchNode"},create(e,o){return{kind:"FetchNode",rowCount:Se.create(e),modifier:o}}})});function id(e,o){if(!uo(e)&&!lt(e))throw new Error(`Invalid fetch row count: ${e}`);if(!gw(o))throw new Error(`Invalid fetch modifier: ${o}`);return nd.create(e,o)}function gw(e){return e==="only"||e==="with ties"}var ad=f(()=>{Za();$()});function sd(e){return new oi(e)}var D,oi,es,os=f(()=>{xo();ca();Qn();ho();Pr();Ie();kr();Ao();Lt();Mr();Qa();$();od();Tr();ne();rd();mo();Ht();So();ad();Un();oi=class{#e;constructor(o){this.#e=l(o)}get expressionType(){}get isSelectQueryBuilder(){return!0}where(...o){return new D({...this.#e,queryNode:P.cloneWithWhere(this.#e.queryNode,pe(o))})}whereRef(o,t,n){return new D({...this.#e,queryNode:P.cloneWithWhere(this.#e.queryNode,xe(o,t,n))})}having(...o){return new D({...this.#e,queryNode:ee.cloneWithHaving(this.#e.queryNode,pe(o))})}havingRef(o,t,n){return new D({...this.#e,queryNode:ee.cloneWithHaving(this.#e.queryNode,xe(o,t,n))})}select(o){return new D({...this.#e,queryNode:ee.cloneWithSelections(this.#e.queryNode,qo(o))})}distinctOn(o){return new D({...this.#e,queryNode:ee.cloneWithDistinctOn(this.#e.queryNode,jo(o))})}modifyFront(o){return new D({...this.#e,queryNode:ee.cloneWithFrontModifier(this.#e.queryNode,po.createWithExpression(o.toOperationNode()))})}modifyEnd(o){return new D({...this.#e,queryNode:P.cloneWithEndModifier(this.#e.queryNode,po.createWithExpression(o.toOperationNode()))})}distinct(){return new D({...this.#e,queryNode:ee.cloneWithFrontModifier(this.#e.queryNode,po.create("Distinct"))})}forUpdate(o){return new D({...this.#e,queryNode:P.cloneWithEndModifier(this.#e.queryNode,po.create("ForUpdate",o?Nr(o).map(Ce):void 0))})}forShare(o){return new D({...this.#e,queryNode:P.cloneWithEndModifier(this.#e.queryNode,po.create("ForShare",o?Nr(o).map(Ce):void 0))})}forKeyShare(o){return new D({...this.#e,queryNode:P.cloneWithEndModifier(this.#e.queryNode,po.create("ForKeyShare",o?Nr(o).map(Ce):void 0))})}forNoKeyUpdate(o){return new D({...this.#e,queryNode:P.cloneWithEndModifier(this.#e.queryNode,po.create("ForNoKeyUpdate",o?Nr(o).map(Ce):void 0))})}skipLocked(){return new D({...this.#e,queryNode:P.cloneWithEndModifier(this.#e.queryNode,po.create("SkipLocked"))})}noWait(){return new D({...this.#e,queryNode:P.cloneWithEndModifier(this.#e.queryNode,po.create("NoWait"))})}selectAll(o){return new D({...this.#e,queryNode:ee.cloneWithSelections(this.#e.queryNode,fo(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 D({...this.#e,queryNode:P.cloneWithJoin(this.#e.queryNode,Gt(o,t))})}orderBy(...o){return new D({...this.#e,queryNode:P.cloneWithOrderByItems(this.#e.queryNode,to(o))})}groupBy(o){return new D({...this.#e,queryNode:ee.cloneWithGroupByItems(this.#e.queryNode,ed(o))})}limit(o){return new D({...this.#e,queryNode:ee.cloneWithLimit(this.#e.queryNode,Qt.create(Z(o)))})}offset(o){return new D({...this.#e,queryNode:ee.cloneWithOffset(this.#e.queryNode,Ku.create(Z(o)))})}fetch(o,t="only"){return new D({...this.#e,queryNode:ee.cloneWithFetch(this.#e.queryNode,id(o,t))})}top(o,t){return new D({...this.#e,queryNode:P.cloneWithTop(this.#e.queryNode,Jt(o,t))})}union(o){return new D({...this.#e,queryNode:ee.cloneWithSetOperations(this.#e.queryNode,_t("union",o,!1))})}unionAll(o){return new D({...this.#e,queryNode:ee.cloneWithSetOperations(this.#e.queryNode,_t("union",o,!0))})}intersect(o){return new D({...this.#e,queryNode:ee.cloneWithSetOperations(this.#e.queryNode,_t("intersect",o,!1))})}intersectAll(o){return new D({...this.#e,queryNode:ee.cloneWithSetOperations(this.#e.queryNode,_t("intersect",o,!0))})}except(o){return new D({...this.#e,queryNode:ee.cloneWithSetOperations(this.#e.queryNode,_t("except",o,!1))})}exceptAll(o){return new D({...this.#e,queryNode:ee.cloneWithSetOperations(this.#e.queryNode,_t("except",o,!0))})}as(o){return new es(this,o)}clearSelect(){return new D({...this.#e,queryNode:ee.cloneWithoutSelections(this.#e.queryNode)})}clearWhere(){return new D({...this.#e,queryNode:P.cloneWithoutWhere(this.#e.queryNode)})}clearLimit(){return new D({...this.#e,queryNode:ee.cloneWithoutLimit(this.#e.queryNode)})}clearOffset(){return new D({...this.#e,queryNode:ee.cloneWithoutOffset(this.#e.queryNode)})}clearOrderBy(){return new D({...this.#e,queryNode:P.cloneWithoutOrderBy(this.#e.queryNode)})}clearGroupBy(){return new D({...this.#e,queryNode:ee.cloneWithoutGroupBy(this.#e.queryNode)})}$call(o){return o(this)}$if(o,t){return o?t(this):new D({...this.#e})}$castTo(){return new D(this.#e)}$narrowType(){return new D(this.#e)}$assertType(){return new D(this.#e)}$asTuple(){return new Q(this.toOperationNode())}$asScalar(){return new Q(this.toOperationNode())}withPlugin(o){return new D({...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??Ko;throw Ut(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 D({...this.#e,queryNode:P.cloneWithExplain(this.#e.queryNode,o,t)}).execute()}};D=oi;es=class{#e;#o;constructor(o,t){this.#e=o,this.#o=t}get expression(){return this.#e}get alias(){return this.#o}get isAliasedSelectQueryBuilder(){return!0}toOperationNode(){return Pe.create(this.#e.toOperationNode(),M.create(this.#o))}}});var bo,ti=f(()=>{$();qr();Or();bo=l({is(e){return e.kind==="AggregateFunctionNode"},create(e,o=[]){return l({kind:"AggregateFunctionNode",func:e,aggregated:o})},cloneWithDistinct(e){return l({...e,distinct:!0})},cloneWithOrderBy(e,o,t=!1){let n=t?"withinGroup":"orderBy";return l({...e,[n]:e[n]?Oo.cloneWithItems(e[n],o):Oo.create(o)})},cloneWithFilter(e,o){return l({...e,filter:e.filter?ye.cloneWithOperation(e.filter,"And",o):ye.create(o)})},cloneWithOrFilter(e,o){return l({...e,filter:e.filter?ye.cloneWithOperation(e.filter,"Or",o):ye.create(o)})},cloneWithOver(e,o){return l({...e,over:o})}})});var ts,rs=f(()=>{$();ts=l({is(e){return e.kind==="FunctionNode"},create(e,o){return l({kind:"FunctionNode",func:e,arguments:o})}})});var Xt,ns,is=f(()=>{$();ti();xo();ne();Ja();mo();Lt();Ao();Xt=class e{#e;constructor(o){this.#e=l(o)}get expressionType(){}as(o){return new ns(this,o)}distinct(){return new e({...this.#e,aggregateFunctionNode:bo.cloneWithDistinct(this.#e.aggregateFunctionNode)})}orderBy(...o){return new e({...this.#e,aggregateFunctionNode:P.cloneWithOrderByItems(this.#e.aggregateFunctionNode,to(o))})}clearOrderBy(){return new e({...this.#e,aggregateFunctionNode:P.cloneWithoutOrderBy(this.#e.aggregateFunctionNode)})}withinGroupOrderBy(...o){return new e({...this.#e,aggregateFunctionNode:bo.cloneWithOrderBy(this.#e.aggregateFunctionNode,to(o),!0)})}filterWhere(...o){return new e({...this.#e,aggregateFunctionNode:bo.cloneWithFilter(this.#e.aggregateFunctionNode,pe(o))})}filterWhereRef(o,t,n){return new e({...this.#e,aggregateFunctionNode:bo.cloneWithFilter(this.#e.aggregateFunctionNode,xe(o,t,n))})}over(o){let t=Yu();return new e({...this.#e,aggregateFunctionNode:bo.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}},ns=class{#e;#o;constructor(o,t){this.#e=o,this.#o=t}get expression(){return this.#e}get alias(){return this.#o}toOperationNode(){return Pe.create(this.#e.toOperationNode(),M.create(this.#o))}}});function cd(){let e=(t,n)=>new Q(ts.create(t,jo(n??[]))),o=(t,n)=>new Xt({aggregateFunctionNode:bo.create(t,n?jo(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 Xt({aggregateFunctionNode:bo.create("count",fo(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 Xt({aggregateFunctionNode:bo.create("json_agg",[H(t)?Ce(t):t.toOperationNode()])})},toJson(t){return new Q(ts.create("to_json",[H(t)?Ce(t):t.toOperationNode()]))}})}var as=f(()=>{Ht();ti();rs();Ie();Pr();is();$();ho()});var ld,ss=f(()=>{$();ld=l({is(e){return e.kind==="UnaryOperationNode"},create(e,o){return l({kind:"UnaryOperationNode",operator:e,operand:o})}})});function ud(e,o){if(ou(e))return ld.create(Ze.create(e),fe(o));throw new Error(`invalid unary operator ${JSON.stringify(e)}`)}var dd=f(()=>{Mt();ss();Ie()});var Ae,ri=f(()=>{$();Rr();Ae=l({is(e){return e.kind==="CaseNode"},create(e){return l({kind:"CaseNode",value:e})},cloneWithWhen(e,o){return l({...e,when:l(e.when?[...e.when,o]:[o])})},cloneWithThen(e,o){return l({...e,when:e.when?l([...e.when.slice(0,-1),Eo.cloneWithResult(e.when[e.when.length-1],o)]):void 0})},cloneWith(e,o){return l({...e,...o})}})});var ni,Yt,ii,ai,cs=f(()=>{Ht();$();Ie();ri();Rr();mo();So();ni=class{#e;constructor(o){this.#e=l(o)}when(...o){return new Yt({...this.#e,node:Ae.cloneWithWhen(this.#e.node,Eo.create(pe(o)))})}whenRef(o,t,n){return new Yt({...this.#e,node:Ae.cloneWithWhen(this.#e.node,Eo.create(xe(o,t,n)))})}},Yt=class{#e;constructor(o){this.#e=l(o)}then(o){return new ii({...this.#e,node:Ae.cloneWithThen(this.#e.node,Mn(o)?jr(o):Z(o))})}thenRef(o){return new ii({...this.#e,node:Ae.cloneWithThen(this.#e.node,fe(o))})}},ii=class{#e;constructor(o){this.#e=l(o)}when(...o){return new Yt({...this.#e,node:Ae.cloneWithWhen(this.#e.node,Eo.create(pe(o)))})}whenRef(o,t,n){return new Yt({...this.#e,node:Ae.cloneWithWhen(this.#e.node,Eo.create(xe(o,t,n)))})}else(o){return new ai({...this.#e,node:Ae.cloneWith(this.#e.node,{else:Mn(o)?jr(o):Z(o)})})}elseRef(o){return new ai({...this.#e,node:Ae.cloneWith(this.#e.node,{else:fe(o)})})}end(){return new Q(Ae.cloneWith(this.#e.node,{isStatement:!1}))}endCase(){return new Q(Ae.cloneWith(this.#e.node,{isStatement:!0}))}},ai=class{#e;constructor(o){this.#e=l(o)}end(){return new Q(Ae.cloneWith(this.#e.node,{isStatement:!1}))}endCase(){return new Q(Ae.cloneWith(this.#e.node,{isStatement:!0}))}}});var ls,us=f(()=>{$();ls=l({is(e){return e.kind==="JSONPathLegNode"},create(e,o){return l({kind:"JSONPathLegNode",type:e,value:o})}})});var bw,Kt,si,ds,ps=f(()=>{xo();ne();kn();us();Cr();qn();Je();Xo();bw=/^#-\d+$/,Kt=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"&&!bw.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 zt.is(this.#e)?new si(zt.cloneWithTraversal(this.#e,Ho.is(this.#e.traversal)?Ho.cloneWithLeg(this.#e.traversal,ls.create(o,t)):Rn.cloneWithValue(this.#e.traversal,Se.createImmediate(t)))):new si(Ho.cloneWithLeg(this.#e,ls.create(o,t)))}},si=class e extends Kt{#e;constructor(o){super(o),this.#e=o}get expressionType(){}as(o){return new ds(this,o)}$castTo(){return new e(this.#e)}$notNull(){return new e(this.#e)}toOperationNode(){return this.#e}},ds=class{#e;#o;constructor(o,t){this.#e=o,this.#o=t}get expression(){return this.#e}get alias(){return this.#o}toOperationNode(){return Pe.create(this.#e.toOperationNode(),ie(this.#o)?this.#o.toOperationNode():M.create(this.#o))}}});var ms,fs=f(()=>{$();ms=l({is(e){return e.kind==="TupleNode"},create(e){return l({kind:"TupleNode",values:l(e)})}})});function md(e){return ww[e]||vw.some(o=>o.test(e))}var ww,vw,pd,hs=f(()=>{$();ww=l({bigint:!0,bigserial:!0,binary:!0,blob:!0,boolean:!0,bytea:!0,char:!0,date:!0,datemultirange:!0,daterange:!0,datetime:!0,datetime2:!0,decimal:!0,"double precision":!0,float4:!0,float8:!0,int2:!0,int4:!0,int4multirange:!0,int4range:!0,int8:!0,int8multirange:!0,int8range:!0,integer:!0,json:!0,jsonb:!0,numeric:!0,nummultirange:!0,numrange:!0,real:!0,serial:!0,smallint:!0,text:!0,time:!0,timestamp:!0,timestamptz:!0,timetz:!0,tsmultirange:!0,tsrange:!0,tstzmultirange:!0,tstzrange:!0,uuid:!0,varbinary:!0,varchar:!0}),vw=l([/^varchar\(\d+\)$/,/^char\(\d+\)$/,/^decimal\(\d+, \d+\)$/,/^numeric\(\d+, \d+\)$/,/^binary\(\d+\)$/,/^datetime\(\d+\)$/,/^time\(\d+\)$/,/^timetz\(\d+\)$/,/^timestamp\(\d+\)$/,/^timestamptz\(\d+\)$/,/^datetime2\(\d+\)$/,/^varbinary\(\d+\)$/]),pd=l({is(e){return e.kind==="DataTypeNode"},create(e){return l({kind:"DataTypeNode",dataType:e})}})});function fd(e){if(ie(e))return e.toOperationNode();if(md(e))return pd.create(e);throw new Error(`invalid column data type ${JSON.stringify(e)}`)}var hd=f(()=>{hs();Je()});var gd,gs=f(()=>{$();gd=l({is(e){return e.kind==="CastNode"},create(e,o){return l({kind:"CastNode",expression:e,dataType:o})}})});function Xa(e=Zn){function o(r,a,s){return new Q(In(r,a,s))}function t(r,a){return new Q(ud(r,a))}let n=Object.assign(o,{fn:void 0,eb:void 0,selectFrom(r){return sd({queryId:De(),executor:e,queryNode:ee.createFrom(gt(r))})},case(r){return new ni({node:Ae.create($o(r)?void 0:fe(r))})},ref(r,a){return $o(a)?new Q(Qe(r)):new Kt(iu(r,a))},jsonPath(){return new Kt(Ho.create())},table(r){return new Q(Ce(r))},val(r){return new Q(Z(r))},refTuple(...r){return new Q(ms.create(r.map(fe)))},tuple(...r){return new Q(ms.create(r.map(Z)))},lit(r){return new Q(jr(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 Q(Qo.create(fe(r),Ze.create("between"),Te.create(Z(a),Z(s))))},betweenSymmetric(r,a,s){return new Q(Qo.create(fe(r),Ze.create("between symmetric"),Te.create(Z(a),Z(s))))},and(r){return ke(r)?new Q(Dn(r,"and")):new Q(ga(r,"and"))},or(r){return ke(r)?new Q(Dn(r,"or")):new Q(ga(r,"or"))},parens(...r){let a=pe(r);return Yo.is(a)?new Q(a):new Q(Yo.create(a))},cast(r,a){return new Q(gd.create(fe(r),fd(a)))}});return n.fn=cd(),n.eb=n,n}function Ro(e){return Xa()}var Vt=f(()=>{os();kr();ho();Xn();as();Ie();mo();Sr();Ht();Mt();dd();So();ei();cs();ri();$();ps();$n();Jo();fs();Cr();hd();gs()});function Go(e){if(ie(e))return e.toOperationNode();if($e(e))return e(Ro()).toOperationNode();throw new Error(`invalid expression: ${JSON.stringify(e)}`)}function Vn(e){if(ie(e))return e.toOperationNode();if($e(e))return e(Ro()).toOperationNode();throw new Error(`invalid aliased expression: ${JSON.stringify(e)}`)}function mt(e){return yn(e)||Jl(e)||$e(e)}var ft=f(()=>{_n();Je();Vt();$()});function bd(e){return je(e)&&ie(e)&&H(e.table)&&H(e.alias)}var bs=f(()=>{Je();$()});function gt(e){return ke(e)?e.map(o=>yt(o)):[yt(e)]}function yt(e){return H(e)?yw(e):bd(e)?e.toOperationNode():Vn(e)}function yw(e){let o=" as ";if(e.includes(o)){let[t,n]=e.split(o).map(wd);return Pe.create(Ce(t),M.create(n))}else return Ce(e)}function Ce(e){if(e.includes(".")){let[t,n]=e.split(".").map(wd);return Uo.createWithSchema(t,n)}else return Uo.create(e)}function wd(e){return e.trim()}var ho=f(()=>{$();xo();$r();ft();ne();bs()});var FE,vd=f(()=>{$();FE=l({is(e){return e.kind==="AddColumnNode"},create(e){return l({kind:"AddColumnNode",column:e})}})});var UE,yd=f(()=>{$();eo();UE=l({is(e){return e.kind==="ColumnDefinitionNode"},create(e,o){return l({kind:"ColumnDefinitionNode",column:ue.create(e),dataType:o})},cloneWithFrontModifier(e,o){return l({...e,frontModifiers:e.frontModifiers?l([...e.frontModifiers,o]):[o]})},cloneWithEndModifier(e,o){return l({...e,endModifiers:e.endModifiers?l([...e.endModifiers,o]):[o]})},cloneWith(e,o){return l({...e,...o})}})});var HE,_d=f(()=>{$();eo();HE=l({is(e){return e.kind==="DropColumnNode"},create(e){return l({kind:"DropColumnNode",column:ue.create(e)})},cloneWith(e,o){return l({...e,...o})}})});var ZE,Nd=f(()=>{$();eo();ZE=l({is(e){return e.kind==="RenameColumnNode"},create(e,o){return l({kind:"RenameColumnNode",column:ue.create(e),renameTo:ue.create(o)})}})});var rq,$d=f(()=>{$();ne();rq=l({is(e){return e.kind==="CheckConstraintNode"},create(e,o){return l({kind:"CheckConstraintNode",expression:e,name:o?M.create(o):void 0})}})});var _w,aq,xd,ws=f(()=>{$();_w=l({cascade:!0,"no action":!0,restrict:!0,"set default":!0,"set null":!0}),aq=Object.keys(_w),xd=l({is(e){return e.kind==="ReferencesNode"},create(e,o){return l({kind:"ReferencesNode",table:e,columns:l([...o])})},cloneWithOnDelete(e,o){return l({...e,onDelete:o})},cloneWithOnUpdate(e,o){return l({...e,onUpdate:o})}})});var lq,Cd=f(()=>{$();lq=l({is(e){return e.kind==="GeneratedNode"},create(e){return l({kind:"GeneratedNode",...e})},createWithExpression(e){return l({kind:"GeneratedNode",always:!0,expression:e})},cloneWith(e,o){return l({...e,...o})}})});var pq,jd=f(()=>{$();pq=l({is(e){return e.kind==="DefaultValueNode"},create(e){return l({kind:"DefaultValueNode",defaultValue:e})}})});var Sd=f(()=>{});var gq,Od=f(()=>{$();gq=l({is(e){return e.kind==="ModifyColumnNode"},create(e){return l({kind:"ModifyColumnNode",column:e})}})});var _q,Ad=f(()=>{$();ne();ws();_q=l({is(e){return e.kind==="ForeignKeyConstraintNode"},create(e,o,t,n){return l({kind:"ForeignKeyConstraintNode",columns:e,references:xd.create(o,t),name:n?M.create(n):void 0})},cloneWith(e,o){return l({...e,...o})}})});var Ed=f(()=>{});var Cq,qd=f(()=>{$();Cq=l({is(e){return e.kind==="AddConstraintNode"},create(e){return l({kind:"AddConstraintNode",constraint:e})}})});var qq,Rd=f(()=>{pa();$();eo();ne();qq=l({is(e){return e.kind==="UniqueConstraintNode"},create(e,o,t){return H(e.at(0))&&(Dt("`UniqueConstraintNode.create(columns: string[], ...)` is deprecated - pass `ColumnNode[]` instead."),e=e.map(ue.create)),l({kind:"UniqueConstraintNode",columns:l(e),name:o?M.create(o):void 0,nullsNotDistinct:t})},cloneWith(e,o){return l({...e,...o})}})});var Tq,kd=f(()=>{$();ne();Tq=l({is(e){return e.kind==="DropConstraintNode"},create(e){return l({kind:"DropConstraintNode",constraintName:M.create(e)})},cloneWith(e,o){return l({...e,...o})}})});var Lq,Pd=f(()=>{$();eo();Lq=l({is(e){return e.kind==="AlterColumnNode"},create(e,o,t){return l({kind:"AlterColumnNode",column:ue.create(e),[o]:t})}})});var Td=f(()=>{});var Uq,Md=f(()=>{$();eo();ne();Uq=l({is(e){return e.kind==="PrimaryKeyConstraintNode"},create(e,o){return l({kind:"PrimaryKeyConstraintNode",columns:l(e.map(ue.create)),name:o?M.create(o):void 0})},cloneWith(e,o){return l({...e,...o})}})});var Hq,Id=f(()=>{$();ne();Hq=l({is(e){return e.kind==="AddIndexNode"},create(e){return l({kind:"AddIndexNode",name:M.create(e)})},cloneWith(e,o){return l({...e,...o})},cloneWithColumns(e,o){return l({...e,columns:[...e.columns||[],...o]})}})});var Zq,Dd=f(()=>{$();ne();Zq=l({is(e){return e.kind==="RenameConstraintNode"},create(e,o){return l({kind:"RenameConstraintNode",oldName:M.create(e),newName:M.create(o)})}})});var Ld=f(()=>{});var zd=f(()=>{});var Fd=f(()=>{});var Wd=f(()=>{});var Bd=f(()=>{});var Vd=f(()=>{});var Ud=f(()=>{});var Jd=f(()=>{});var dR,Qd=f(()=>{$();ut();dR=l({is(e){return e.kind==="CreateViewNode"},create(e){return l({kind:"CreateViewNode",name:Ye.create(e)})},cloneWith(e,o){return l({...e,...o})}})});var Gd=f(()=>{});var gR,Hd=f(()=>{$();ut();gR=l({is(e){return e.kind==="DropViewNode"},create(e){return l({kind:"DropViewNode",name:Ye.create(e)})},cloneWith(e,o){return l({...e,...o})}})});var Xd=f(()=>{});var NR,Yd=f(()=>{$();Tn();Xo();NR=l({is(e){return e.kind==="CreateTypeNode"},create(e){return l({kind:"CreateTypeNode",name:e})},cloneWithEnum(e,o){return l({...e,enum:Pn.create(o.map(Se.createImmediate))})}})});var Kd=f(()=>{});var jR,Zd=f(()=>{$();jR=l({is(e){return e.kind==="DropTypeNode"},create(e){return Array.isArray(e)||(e=[e]),l({kind:"DropTypeNode",name:e[0],additionalNames:e.slice(1)})},cloneWith(e,o){return l({...e,...o})}})});var ep=f(()=>{});var qR,op=f(()=>{$();ut();qR=l({is(e){return e.kind==="RefreshMaterializedViewNode"},create(e){return l({kind:"RefreshMaterializedViewNode",name:Ye.create(e)})},cloneWith(e,o){return l({...e,...o})}})});var tp=f(()=>{});var TR,rp=f(()=>{$();TR=l({is(e){return e.kind==="AlterTypeNode"},create(e){return l({kind:"AlterTypeNode",name:e})},cloneWith(e,o){return l({...e,...o})}})});var DR,np=f(()=>{$();DR=l({is(e){return e.kind==="AddValueNode"},create(e){return l({kind:"AddValueNode",value:e})},cloneWith(e,o){return l({...e,...o})}})});var ip=f(()=>{});var WR,ap=f(()=>{$();WR=l({is(e){return e.kind==="RenameValueNode"},create(e,o){return l({kind:"RenameValueNode",oldValue:e,newValue:o})}})});var sp=f(()=>{});var cp=f(()=>{});var lp=f(()=>{});var up=f(()=>{});var dp=f(()=>{});var pp=f(()=>{});var Nw,YR,mp=f(()=>{$();Nw=["query","error"],YR=l(Nw)});var fp=f(()=>{});var hp=f(()=>{Symbol.asyncDispose??=Symbol("Symbol.asyncDispose")});function ko(e){return new vs(e)}var vs,ys,_s=f(()=>{xo();$();ei();ne();Je();vs=class e{#e;constructor(o){this.#e=l(o)}get expressionType(){}get isRawBuilder(){return!0}as(o){return new ys(this,o)}$castTo(){return new e({...this.#e})}$notNull(){return new e(this.#e)}withPlugin(o){return new e({...this.#e,plugins:this.#e.plugins!==void 0?l([...this.#e.plugins,o]):l([o])})}toOperationNode(){return this.#r(this.#o())}compile(o){return this.#t(this.#o(o))}async execute(o,t){let n=this.#o(o);return n.executeQuery(this.#t(n),t)}#o(o){let t=o!==void 0?o.getExecutor():Zn;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)}};ys=class{#e;#o;constructor(o,t){this.#e=o,this.#o=t}get expression(){return this.#e}get alias(){return this.#o}get rawBuilder(){return this.#e}toOperationNode(){return Pe.create(this.#e.toOperationNode(),ie(this.#o)?this.#o.toOperationNode():M.create(this.#o))}}});function gp(e){return ie(e)?e.toOperationNode():Z(e)}var A,bp=f(()=>{ne();Je();pt();Xo();Ie();ho();So();Xn();_s();A=Object.assign((e,...o)=>ko({queryId:De(),rawNode:de.create(e,o?.map(gp)??[])}),{ref(e){return ko({queryId:De(),rawNode:de.createWithChild(Qe(e))})},val(e){return ko({queryId:De(),rawNode:de.createWithChild(Z(e))})},table(e){return ko({queryId:De(),rawNode:de.createWithChild(Ce(e))})},id(...e){let o=new Array(e.length+1).fill(".");return o[0]="",o[o.length-1]="",ko({queryId:De(),rawNode:de.create(o,e.map(M.create))})},lit(e){return ko({queryId:De(),rawNode:de.createWithChild(Se.createImmediate(e))})},raw(e){return ko({queryId:De(),rawNode:de.createWithSql(e)})},join(e,o=A`, `){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]=gp(e[r]),r!==e.length-1&&(t[2*r+1]=n);return ko({queryId:De(),rawNode:de.createWithChildren(t)})}})});var wp=f(()=>{});var vk,yk,_k,Ns=f(()=>{$();vk=l({ForKeyShare:"for key share",ForNoKeyUpdate:"for no key update",ForUpdate:"for update",ForShare:"for share",NoWait:"nowait",SkipLocked:"skip locked",Distinct:"distinct"}),yk=l({ForKeyShare:1,ForNoKeyUpdate:1,ForUpdate:1,ForShare:1,NoWait:2,SkipLocked:2,Distinct:0}),_k=l({InnerJoin:"inner join",LeftJoin:"left join",RightJoin:"right join",FullJoin:"full join",CrossJoin:"cross join",LateralInnerJoin:"inner join lateral",LateralLeftJoin:"left join lateral",LateralCrossJoin:"cross join lateral",OuterApply:"outer apply",CrossApply:"cross apply",Using:"using"})});var Nt,Lr=f(()=>{pt();$();Xn();Nt=l({raw(e,o=[]){return l({sql:e,query:de.createWithSql(e),parameters:l(o),queryId:De()})}})});var vp=f(()=>{});var yp=f(()=>{});var _p=f(()=>{});var Np=f(()=>{});var $p=f(()=>{});var xp=f(()=>{});var Cp=f(()=>{});function Zo(e,o){if($w(e)&&o.stack){let t=o.stack.split(`
|
|
4
4
|
`).slice(1).join(`
|
|
5
5
|
`);return e.stack+=`
|
|
6
|
-
${t}`,e}return e}function Gb(e){return je(e)&&U(e.stack)}var Mr=m(()=>{N()});function Xb(e){return je(e)&&"insertId"in e&&"affectedRows"in e}var Hb,sp,cp=m(()=>{Tr();N();Mr();Hb=Symbol();sp=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(yt.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(!Xb(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 Ho(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(je(r)&&"code"in r&&r.code==="ERR_STREAM_PREMATURE_CLOSE")return;throw r}finally{this.#t=void 0}}[Hb](){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(yt.raw(o,[]))});let{clientFlags:a,maxPacketSize:s,...c}=n,d=this.#o(c);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 lp=m(()=>{});var up=m(()=>{});var dp=m(()=>{});var pp=m(()=>{});var Yb,mp,fp=m(()=>{Tr();Mr();Yb=Symbol(),mp=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 Ho(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}}[Yb](){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 c=>{a.queryId===this.#r?.queryId&&await c.executeQuery(yt.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 hp=m(()=>{});var gp=m(()=>{});var ck,lk,bp=m(()=>{ck=BigInt("3853314791062309107"),lk=3600*1e3});var wp=m(()=>{});var vp=m(()=>{});var Kb,Zb,ew,yp,Ir,_p=m(()=>{N();Tr();Mr();Aa();kr();Kb=Symbol(),Zb=Symbol(),ew=Symbol(),yp=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?Wn(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 Oe;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 Oe;this.#t=new Ir({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 Ho(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 Ir({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}[Zb](){return"closed"in this.#e&&this.#e.closed?Promise.resolve():new Promise(o=>{this.#e.once("end",o),this.#e.close()})}async[Kb](){await new Promise((o,t)=>{this.#e.reset(n=>{if(n)return t(n);o()})})}async[ew](){if(this.#o||this.#i())return!1;try{let o=new Oe,t=new Ir({compiledQuery:yt.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}},Ir=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]=(c,d)=>{if(c!=="chunkReady"){if(delete this.#t[s],c==="error")return n.reject(d);n.resolve({rowCount:this.#i,rows:this.#o})}}}this.#e=new this.#n.Request(t.sql,(s,c)=>{if(s)return Object.values(this.#t).forEach(d=>d("error",s instanceof AggregateError?s.errors:s));this.#i=c}),this.#a(t.parameters),this.#s()}get request(){return this.#e}readChunk(){let o=this.readChunk.name;return new Promise((t,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 at(o)||_o(o)||U(o)?this.#n.TYPES.NVarChar:st(o)||so(o)&&o%1===0?o<-2147483648||o>2147483647?this.#n.TYPES.BigInt:this.#n.TYPES.Int:so(o)?this.#n.TYPES.Float:it(o)?this.#n.TYPES.Bit:Qi(o)?this.#n.TYPES.DateTime:wl(o)?this.#n.TYPES.VarBinary:this.#n.TYPES.NVarChar}}});var Np=m(()=>{});var $p=m(()=>{});var xp=m(()=>{});var Cp=m(()=>{});var ow,tw,rw,jp,Sp=m(()=>{kr();Mr();ow=Symbol(),tw=Symbol(),rw=Symbol(),jp=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 Ho(t,new Error)}}async*streamQuery(){throw new Error("Streaming is not supported by PGlite.")}async[ow](){let{promise:o,reject:t,resolve:n}=new Oe,{promise:r,resolve:a}=new Oe;this.#o=n,this.#r=t,this.#n=this.#e.transaction(async s=>{this.#t=s,a(),await o}),await r}async[tw](){this.#o?.(),await this.#n,this.#o=void 0,this.#r=void 0,this.#t=void 0,this.#n=void 0}async[rw](){this.#r?.(),await this.#n?.catch(()=>{}),this.#o=void 0,this.#r=void 0,this.#t=void 0,this.#n=void 0}}});var Op=m(()=>{});var Ap=m(()=>{});var Ep=m(()=>{});var qp=m(()=>{});var Rp=m(()=>{});var kp=m(()=>{});var Pp=m(()=>{});var Tp=m(()=>{});var Mp=m(()=>{});var oi=m(()=>{Xd();Eu();zd();fn();Gt();Fa();mu();hu();fu();qr();va();Ja();cu();Ca();Sa();uu();Ua();Ga();Ka();Au();Ou();Yi();ss();Kd();Ud();Qn();cs();Tr();Wd();xd();kd();Sd();Td();Nd();Cd();$d();jd();cd();dd();_d();Ad();Id();qd();gd();yd();Bd();_n();rs();Qd();Vd();Jd();ep();op();ap();tp();rp();np();ip();pp();cp();lp();up();dp();fp();wp();gp();hp();bp();vp();xp();_p();Np();$p();Cp();Sp();Op();cs();Ap();Ep();_u();qp();Rp();kp();Pp();ed();pd();wd();Hn();No();hd();yl();Wo();gn();Xn();ts();nd();Xi();od();Ye();$a();gu();bu();Tp();_l();Nl();$l();Rd();Od();Md();os();nu();sd();Pn();td();fd();xl();Cl();jl();Pd();Ed();ha();Da();ud();jr();Ba();ad();Pa();aa();ca();ne();la();yr();jn();Xa();_r();xn();Rr();ua();Nu();ga();ld();ka();lu();su();Hi();ze();yu();Zd();Tt();pu();lt();Nn();xr();wa();Rn();$r();ya();na();bd();ea();So();ut();vn();ns();rd();vd();fa();ct();wn();Gi();Ar();_a();Ta();Mp();vr();xa();es();Qa();md();kn();pa();On();Jo();ru();Or();Sr();wu();Ld();Dd();Fd();Hd();Gd()});import{BlockList as Ip,isIP as nw}from"node:net";var Lp,Dp,zp,Fp=m(()=>{Lp=new Ip,Dp=new Ip;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]])Lp.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]])Dp.addSubnet(e,o,"ipv6");zp=e=>{let o=nw(e);return o===4?Lp.check(e,"ipv4"):o===6?Dp.check(e,"ipv6"):!0}});function Lr(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:{},c=typeof s.value=="string"?s.value.trim():"",d=typeof s.label=="string"?s.label.trim():"";if(!c||c.length>80||!ls(c))throw i(`El elemento ${a+1} no tiene una clave v\xE1lida.`);if(!d||d.length>80||!ls(d))throw i(`El elemento ${a+1} necesita un nombre (hasta 80 caracteres).`);if(t.has(c))throw i(`La clave \xAB${c}\xBB est\xE1 repetida.`);t.add(c);let u={value:c,label:d};if(s.color!==void 0&&s.color!==null&&s.color!==""){if(typeof s.color!="string"||!sw.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,cw(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 iw){let a=n.find(s=>s.value===r);if(!a)throw new L(400,"etapa_fija","Las etapas \xABGanada\xBB y \xABPerdida\xBB no se pueden quitar; se pueden renombrar.");if(a.archivado)throw new L(400,"etapa_fija","Las etapas \xABGanada\xBB y \xABPerdida\xBB no se pueden archivar; se pueden renombrar.")}if(e==="contactTypes"){for(let s of Wp){let c=n.find(d=>d.value===s);if(!c)throw new L(400,"tipo_fijo","Los tipos \xABCliente\xBB y \xABProveedor\xBB no se pueden quitar; se pueden renombrar.");if(c.archivado)throw new L(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&&Wp.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 cw(e,o){let t=typeof e.plural=="string"&&e.plural.trim()?e.plural.trim():o;if(t.length>80||!ls(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.campoNif!==void 0){if(typeof e.campoNif!="string"||!/^[a-z][a-z0-9_]*$/.test(e.campoNif))throw i("El campo del NIF debe ser una clave de campo propio.");n.campoNif=e.campoNif}if(e.icono!==void 0&&e.icono!==null&&e.icono!==""){if(typeof e.icono!="string"||!aw.test(e.icono))throw i(`El icono de \xAB${o}\xBB no es v\xE1lido.`);n.icono=e.icono}return n}var iw,Wp,aw,ls,sw,ds=m(()=>{E();iw=["won","lost"],Wp=["cliente","proveedor"],aw=/^[a-z0-9-]{1,40}$/,ls=e=>!/[\u0000-\u001f\u007f]/.test(e),sw=/^#[0-9a-fA-F]{3,8}$|^[a-z]{3,20}$/});function Bp(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 c=0;for(let d of ps(s)){let u=o.get(d.relacion);u&&(c=Math.max(c,a(u)+1))}if(c>6)throw i("El autocompletado necesita dependencias sin ciclos y hasta seis pasos.");return n.delete(s.clave),t.set(s.clave,c),r.push(s),c};for(let s of o.values())a(s);return r}var ps,Vp=m(()=>{E();ps=e=>e.completarDesde?[e.completarDesde,...e.completarDesde.alternativa?[e.completarDesde.alternativa]:[]]:[]});function Up(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&&!lw(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.");Lr("legalForms",[{value:s,label:ms(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(c=>c.valor===a);if(ms(o,a).length>60||s?.color&&!/^#[0-9a-fA-F]{6}$/.test(s.color))throw i("La etiqueta de clasificaci\xF3n necesita nombre de hasta 60 caracteres y color #rrggbb.")}for(let a of["contacts","companies"])if(Object.entries(t).filter(([c,d])=>d===a&&!Object.hasOwn(n,c)&&!r.includes(c)).length>1)throw i("Las opciones que comparten objeto necesitan forma jur\xEDdica o etiqueta para conservar su significado.");return{...e.formas!==void 0?{formas:n}:{},...e.etiquetas!==void 0?{etiquetas:r}:{}}}function Jp(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:ms(t,a),...t.opciones?.find(c=>c.valor===a)?.color?{color:t.opciones.find(c=>c.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 Lr("legalForms",[...r.values()])}function Qp(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 lw,ms,Gp=m(()=>{E();ds();Dr();lw=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);ms=(e,o)=>e.opciones?.find(t=>t.valor===o)?.etiqueta??e.etiqueta});var j,Hp,Xp=m(()=>{j=(e,o,t={})=>({clave:e,tipo:o,enTabla:!1,ordenable:o!=="texto_largo",filtrable:!1,editable:!["contador","fecha_hora","correos","telefonos","etiquetas"].includes(o),...t}),Hp=[{clave:"companies",icono:"building-2",campoTitulo:"name",campos:[j("name","texto",{enTabla:!0,ancho:240}),j("website","url",{enTabla:!0,ancho:200}),j("sector","seleccion",{enTabla:!0,filtrable:!0,opciones:"config:companySectors"}),j("tags","etiquetas",{enTabla:!0,ordenable:!1,editable:!0,filtrable:!0,relacion:"tags",objetoEtiquetas:"companies",ancho:160,migracion:"0466_etiquetas_por_objeto.sql"}),j("size","seleccion",{enTabla:!0,filtrable:!0,opciones:[{valor:"1",etiqueta:"1"},{valor:"10",etiqueta:"2-9"},{valor:"50",etiqueta:"10-49"},{valor:"250",etiqueta:"50-249"},{valor:"500",etiqueta:"250+"}],ancho:110}),j("city","texto",{enTabla:!0,ancho:140}),j("sales_id","relacion",{enTabla:!0,filtrable:!0,relacion:"sales",ancho:170}),j("nb_contacts","contador",{enTabla:!0,ancho:110}),j("nb_deals","contador",{enTabla:!0,ancho:130}),j("created_at","fecha_hora",{enTabla:!0,ancho:140}),j("proveedor","booleano",{filtrable:!0,ancho:110}),j("has_newsletter","booleano",{etiqueta:"Comunicaciones",filtrable:!0,migracion:"0490_comunicaciones_empresa.sql"}),j("tipos","seleccion_multiple",{enTabla:!0,ordenable:!1,editable:!1,opciones:"config:contactTypes",ancho:170,migracion:"0439_tipos_contactos.sql"}),j("ubicacion","ubicacion",{etiqueta:"Ubicaci\xF3n",editable:!1,ordenable:!1,migracion:"0452_ubicacion_nativa.sql"}),j("phone_number","telefono",{ancho:150}),j("country","texto",{ancho:130}),j("address","texto"),j("state_abbr","texto",{soloFicha:!0,etiqueta:"Provincia"}),j("zipcode","texto",{ancho:110}),j("linkedin_url","url"),j("revenue","texto",{ancho:130}),j("tax_identifier","texto",{ancho:140}),j("razon_social","texto",{ancho:220,migracion:"0440_datos_fiscales.sql"}),j("forma_juridica","seleccion",{filtrable:!0,opciones:"config:legalForms",ancho:160,migracion:"0440_datos_fiscales.sql"}),j("correo_facturacion","correo",{ancho:220,migracion:"0440_datos_fiscales.sql"}),j("pais_fiscal","texto",{filtrable:!0,editable:!1,ancho:90,migracion:"0440_datos_fiscales.sql"}),j("description","texto_largo",{ancho:260})]},{clave:"contacts",icono:"users",campoTitulo:"first_name",camposTitulo:["first_name","last_name"],campos:[j("ubicacion","ubicacion",{etiqueta:"Ubicaci\xF3n",editable:!1,ordenable:!1,migracion:"0452_ubicacion_nativa.sql"}),j("first_name","texto",{enTabla:!0,ancho:220}),j("last_name","texto",{ancho:150}),j("title","texto",{enTabla:!0,ancho:150}),j("company_id","relacion",{enTabla:!0,relacion:"companies",ancho:180}),j("email_jsonb","correos",{enTabla:!0,ordenable:!1,editable:!0,ancho:220}),j("phone_jsonb","telefonos",{enTabla:!0,ordenable:!1,editable:!0,ancho:150}),j("status","seleccion",{enTabla:!0,filtrable:!0,opciones:"config:noteStatuses",ancho:130}),j("tags","etiquetas",{enTabla:!0,ordenable:!1,editable:!0,filtrable:!0,relacion:"tags",objetoEtiquetas:"contacts",ancho:160}),j("tipos","seleccion_multiple",{enTabla:!0,ordenable:!1,editable:!1,opciones:"config:contactTypes",ancho:170,migracion:"0439_tipos_contactos.sql"}),j("sales_id","relacion",{enTabla:!0,filtrable:!0,relacion:"sales",ancho:170}),j("last_seen","fecha_hora",{enTabla:!0,ancho:140}),j("nb_tasks","contador",{ancho:110}),j("first_seen","fecha_hora",{ancho:140}),j("linkedin_url","url"),j("background","texto_largo",{ancho:260}),j("nif","texto",{soloFicha:!0,sensible:!0,etiqueta:"Identificador fiscal",migracion:"0005_datos_es.sql"}),j("iban","texto",{soloFicha:!0,sensible:!0,etiqueta:"IBAN",migracion:"0005_datos_es.sql"}),j("birthday","fecha",{soloFicha:!0,etiqueta:"Fecha de nacimiento",migracion:"0005_datos_es.sql"}),j("address","texto",{soloFicha:!0,etiqueta:"Direcci\xF3n",migracion:"0005_datos_es.sql"}),j("zipcode","texto",{soloFicha:!0,etiqueta:"C\xF3digo postal",migracion:"0005_datos_es.sql"}),j("city","texto",{soloFicha:!0,etiqueta:"Ciudad",migracion:"0005_datos_es.sql"}),j("province","texto",{soloFicha:!0,etiqueta:"Provincia",migracion:"0005_datos_es.sql"}),j("country","texto",{soloFicha:!0,etiqueta:"Pa\xEDs",migracion:"0005_datos_es.sql"}),j("has_newsletter","booleano",{soloFicha:!0,migracion:"0005_datos_es.sql"}),j("pais_fiscal","texto",{filtrable:!0,editable:!1,ancho:90,migracion:"0440_datos_fiscales.sql"})]},{clave:"deals",icono:"handshake",campoTitulo:"name",campos:[j("name","texto",{enTabla:!0,ancho:240}),j("company_id","relacion",{enTabla:!0,relacion:"companies",ancho:180}),j("stage","seleccion",{enTabla:!0,filtrable:!0,opciones:"config:dealStages",ancho:160}),j("amount","importe",{enTabla:!0,ancho:120}),j("expected_closing_date","fecha",{enTabla:!0,ancho:140}),j("category","seleccion",{enTabla:!0,filtrable:!0,opciones:"config:dealCategories",ancho:150}),j("tags","etiquetas",{enTabla:!0,ordenable:!1,editable:!0,filtrable:!0,relacion:"tags",objetoEtiquetas:"deals",ancho:160,migracion:"0466_etiquetas_por_objeto.sql"}),j("sales_id","relacion",{enTabla:!0,filtrable:!0,relacion:"sales",ancho:170}),j("origen_lead","texto",{etiqueta:"Origen",filtrable:!0,editable:!1,ancho:170,migracion:"0467_oportunidades_origen_actividad.sql"}),j("ultima_actividad","fecha_hora",{etiqueta:"\xDAltima actividad",editable:!1,ancho:150,migracion:"0467_oportunidades_origen_actividad.sql"}),j("created_at","fecha_hora",{ancho:140}),j("updated_at","fecha_hora",{ancho:140}),j("description","texto_largo",{ancho:260})]},{clave:"proyectos",icono:"folder-kanban",campoTitulo:"nombre",campos:[j("nombre","texto",{enTabla:!0,ancho:220}),j("clave","texto",{enTabla:!0,ancho:110,editable:!1}),j("estado","seleccion",{enTabla:!0,filtrable:!0,opciones:[{valor:"activo",etiqueta:"Activo"},{valor:"en_pausa",etiqueta:"En pausa"},{valor:"archivado",etiqueta:"Archivado"}],ancho:120}),j("sales_id","relacion",{enTabla:!0,filtrable:!0,relacion:"sales",ancho:170}),j("fecha_inicio","fecha",{enTabla:!0,ancho:130}),j("fecha_fin","fecha",{enTabla:!0,ancho:130}),j("requiere_aceptacion","booleano",{ancho:120}),j("color","texto",{ancho:100}),j("icono","texto",{ancho:100}),j("descripcion","texto_largo",{ancho:260}),j("creado","fecha_hora",{ancho:140}),j("actualizado","fecha_hora",{ancho:140})]},{clave:"tareas",icono:"check-square",campoTitulo:"titulo",campos:[j("titulo","texto",{enTabla:!0,ancho:240}),j("codigo_corto","texto",{enTabla:!0,ancho:110,editable:!1}),j("proyecto_id","relacion",{enTabla:!0,filtrable:!0,relacion:"proyectos",ancho:170,editable:!1}),j("columna_id","texto",{enTabla:!0,filtrable:!0,ancho:130}),j("prioridad","seleccion",{enTabla:!0,filtrable:!0,opciones:[{valor:"baja",etiqueta:"Baja"},{valor:"media",etiqueta:"Media"},{valor:"alta",etiqueta:"Alta"},{valor:"urgente",etiqueta:"Urgente"}],ancho:110}),j("sales_id","relacion",{enTabla:!0,filtrable:!0,relacion:"sales",ancho:170}),j("fecha_entrega","fecha",{enTabla:!0,ancho:130}),j("fecha_inicio","fecha",{ancho:130}),j("estimacion_minutos","numero",{ancho:110}),j("hecho","fecha_hora",{enTabla:!0,editable:!0,marca:!0,ancho:120}),j("contact_id","relacion",{filtrable:!0,relacion:"contacts",ancho:160}),j("descripcion","texto_largo",{ancho:260}),j("creado","fecha_hora",{ancho:140}),j("actualizado","fecha_hora",{ancho:140})]}]});function fs(e){return/^funciones\.([a-z0-9][a-z0-9-]{0,59})\.[a-z][a-z0-9_]{0,40}$/.exec(e)?.[1]}function dw(e,o){return e==="contacts"&&/^(correo|telefono)(_(trabajo|personal))?$/.test(o)?o.startsWith("correo")?"email_jsonb":"phone_jsonb":uw[e].includes(o)||/^datos\.[a-z][a-z0-9_]{0,40}$/.test(o)||fs(o)?o:null}function Yp(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(c=>!["objeto","tipo","nivel","campos"].includes(c))||!["contacts","companies"].includes(String(n.objeto))||typeof n.tipo!="string"||n.tipo!=="*"&&!/^[a-z0-9][a-z0-9-]{0,59}$/.test(n.tipo)||n.tipo==="*"&&n.nivel!==void 0||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[c,d]of Object.entries(n.campos)){let u=dw(r,c);if(!u||fs(u)&&fs(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 uw,Kp=m(()=>{E();uw={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 Zp(e){if(e==null)return;let o=ti(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=ti(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=ti(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=ti(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,ti,em=m(()=>{E();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},ti=(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 zr,CI,pw,om=m(()=>{zr=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 pw(this.centimos())}},CI=new zr(0n),pw=e=>`${e<0n?"-":""}${(e<0n?-e:e)/100n}.${String((e<0n?-e:e)%100n).padStart(2,"0")}`});function rm(e,o){if(e==null)return;let t=be(e,["version","beneficiariosPeriodo","origen","fecha","importe","moneda","unidad","grupo","mantenimiento","ciclo","recuperacion","beneficiarios","motor","documento","cuentan","precios","unidad_recuento","componentes"]),n=be(t.motor,["reglas","combinar","margenNegativo","equipoPropio","principal","minimo","objetivo","fijoPeriodo"]),r=be(t.documento,["periodo","estado","total","beneficiario","lineas"]);if(t.version!==2||typeof t.origen!="string"||!/^mod_[a-z][a-z0-9_]{0,40}$/.test(t.origen))throw i("Liquidaci\xF3n v2: versi\xF3n u origen inv\xE1lido.");let a=(v,w)=>{let _=te(v);if(!o.some(C=>C.clave===_&&!C.archivado&&C.tipo===w))throw i("Liquidaci\xF3n v2: campo de documento inv\xE1lido.");return _},s=Object.fromEntries(Object.entries(be(t.beneficiarios)).map(([v,w])=>{let _=be(w,["tipo","campo"]);return[te(v),{tipo:Nt(_.tipo,["miembro","contacts","companies","registro"]),campo:_.campo==="_dueno"?"_dueno":te(_.campo)}]}));if(!Object.keys(s).length||Object.keys(s).length>20)throw i("Liquidaci\xF3n v2: beneficiarios inv\xE1lidos.");let c=v=>{let w=be(v,["clave","beneficiario","fijo","porcentaje","resto","equipo","minimo"]),_=te(w.beneficiario);if(!s[_])throw i("Liquidaci\xF3n v2: beneficiario desconocido.");return{clave:te(w.clave),beneficiario:_,...w.fijo!==void 0?{fijo:_t(w.fijo)}:{},...w.porcentaje!==void 0?{porcentaje:hs(w.porcentaje)}:{},...w.resto===!0?{resto:!0}:{},...w.equipo===!0?{equipo:!0}:{},...typeof w.minimo=="boolean"?{minimo:w.minimo}:{}}},d=Xo(n.reglas).map(v=>{let w=be(v,["clave","prioridad","modo","desde","hasta","moneda","unidad","si","bolsa","retencion","receptores"]);if(!tm(w.desde)||w.hasta!==void 0&&(!tm(w.hasta)||w.hasta<=w.desde))throw i("Liquidaci\xF3n v2: vigencia inv\xE1lida.");if(typeof w.moneda!="string"||!/^[A-Z]{3}$/.test(w.moneda)||typeof w.unidad!="string"||!w.unidad||w.unidad.length>60)throw i("Liquidaci\xF3n v2: moneda o unidad inv\xE1lida.");let _=w.si===void 0?void 0:be(w.si,["campo","valores"]);return{clave:te(w.clave),prioridad:ri(w.prioridad),modo:Nt(w.modo,["exclusiva","acumulable"]),desde:w.desde,...w.hasta?{hasta:w.hasta}:{},moneda:w.moneda,unidad:w.unidad,receptores:Xo(w.receptores).map(c),...w.bolsa!==void 0?{bolsa:_t(w.bolsa)}:{},...w.retencion!==void 0?{retencion:_t(w.retencion)}:{},..._?{si:{campo:te(_.campo),valores:Xo(_.valores).map(C=>String(C).slice(0,100))}}:{}}});if(new Set(d.map(v=>v.clave)).size!==d.length)throw i("Liquidaci\xF3n v2: regla duplicada.");let u;if(n.objetivo){let v=be(n.objetivo,["beneficiario","medida","modo","tramos","consumirBolsa"]),w=Xo(v.tramos).map(_=>{let C=be(_,["desde","tasa","garantia","bonus"]);return{desde:ri(C.desde),tasa:v.medida==="recuento"?_t(C.tasa):hs(C.tasa),...C.garantia!==void 0?{garantia:_t(C.garantia)}:{},...C.bonus!==void 0?{bonus:_t(C.bonus)}:{}}});if(!w.length||w[0].desde!==0||w.some((_,C)=>C>0&&_.desde<=w[C-1].desde))throw i("Liquidaci\xF3n v2: umbrales inv\xE1lidos.");u={beneficiario:te(v.beneficiario),medida:Nt(v.medida,["recuento","importe"]),modo:Nt(v.modo,["alcanzado","marginal"]),tramos:w,consumirBolsa:v.consumirBolsa===!0}}let p=n.minimo?be(n.minimo,["cantidad","modo"]):void 0,f=n.fijoPeriodo?Xo(n.fijoPeriodo).map(v=>{let w=be(v,["beneficiario","importe"]);return{beneficiario:te(w.beneficiario),importe:_t(w.importe)}}):void 0;if(f&&new Set(f.map(v=>v.beneficiario)).size!==f.length)throw i("Liquidaci\xF3n v2: fijo de periodo duplicado.");let h={version:2,origen:t.origen,fecha:te(t.fecha),importe:te(t.importe),moneda:te(t.moneda),unidad:te(t.unidad),grupo:t.grupo==="_dueno"?"_dueno":te(t.grupo),beneficiarios:s,motor:{reglas:d,combinar:n.combinar===!0,margenNegativo:n.margenNegativo===!0,equipoPropio:n.equipoPropio===!0,...n.principal?{principal:te(n.principal)}:{},...p?{minimo:{cantidad:ri(p.cantidad),modo:Nt(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:te(t.mantenimiento)}:{}};if(t.beneficiariosPeriodo!==void 0&&(h.beneficiariosPeriodo=Xo(t.beneficiariosPeriodo,1e4).map(v=>{let w=be(v,["grupo","beneficiarios"]);if(typeof w.grupo!="string"||!w.grupo||w.grupo.length>100)throw i("Liquidaci\xF3n v2: grupo de periodo inv\xE1lido.");let _=Object.fromEntries(Object.entries(be(w.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:w.grupo,beneficiarios:_}}),new Set(h.beneficiariosPeriodo.map(v=>v.grupo)).size!==h.beneficiariosPeriodo.length))throw i("Liquidaci\xF3n v2: grupo de periodo duplicado.");if(t.cuentan){let v=be(t.cuentan,["campo","valores"]);h.cuentan={campo:te(v.campo),valores:Xo(v.valores).map(String)}}if(t.unidad_recuento&&(h.unidad_recuento=te(t.unidad_recuento)),t.componentes){let v=be(t.componentes,["modo","campo"]);h.componentes={modo:Nt(v.modo,["todos","principal"]),campo:te(v.campo)}}if(t.precios){let v=be(t.precios,["tabla","fecha","claves","valor"]);if(h.precios={tabla:te(v.tabla),fecha:te(v.fecha),claves:Xo(v.claves,3).map(te),valor:te(v.valor)},!h.precios.claves.length)throw i("Liquidaci\xF3n v2: claves de precio ausentes.")}if(t.ciclo&&(h.ciclo=te(t.ciclo)),t.recuperacion){let v=be(t.recuperacion,["modo","plazo"]);if(h.recuperacion={modo:Nt(v.modo,["total","proporcional_dias"]),plazo:ri(v.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(v=>v.beneficiario)].some(v=>v&&!s[v]))throw i("Liquidaci\xF3n v2: beneficiario desconocido.");let b=o.find(v=>v.clave===h.documento.lineas);if(["fuente","concepto","importe"].some(v=>!b.columnas?.some(w=>w.clave===v&&w.tipo==="texto"&&!w.archivado)))throw i("Liquidaci\xF3n v2: columnas de resumen inv\xE1lidas.");let y=o.find(v=>v.clave===h.documento.estado);if(["borrador","aprobada","cerrada","pagada"].some(v=>!y.opciones?.some(w=>w.valor===v)))throw i("Liquidaci\xF3n v2: estados inv\xE1lidos.");return h}var be,tm,te,hs,_t,Xo,Nt,ri,nm=m(()=>{E();om();be=(e,o)=>{if(!e||typeof e!="object"||Array.isArray(e))throw i("Liquidaci\xF3n v2: objeto inv\xE1lido.");if(o&&Object.keys(e).some(t=>!o.includes(t)))throw i("Liquidaci\xF3n v2: propiedad desconocida.");return e},tm=e=>typeof e=="string"&&/^\d{4}-\d{2}-\d{2}$/.test(e)&&Number.isFinite(Date.parse(e+"T00:00:00Z"))&&new Date(e+"T00:00:00Z").toISOString().slice(0,10)===e,te=e=>{if(typeof e!="string"||!/^[a-z][a-z0-9_]{0,40}$/.test(e))throw i("Liquidaci\xF3n v2: clave inv\xE1lida.");return e},hs=e=>{if(typeof e!="string")throw i("Liquidaci\xF3n v2: decimal como cadena.");try{if(zr.leer(e).n<0n)throw new Error("negativo")}catch{throw i("Liquidaci\xF3n v2: decimal inv\xE1lido.")}return e},_t=e=>{let o=hs(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},Xo=(e,o=20)=>{if(!Array.isArray(e)||e.length>o)throw i("Liquidaci\xF3n v2: lista inv\xE1lida.");return e},Nt=(e,o)=>{if(!o.includes(e))throw i("Liquidaci\xF3n v2: opci\xF3n inv\xE1lida.");return e},ri=e=>{if(typeof e!="number"||!Number.isSafeInteger(e)||e<0)throw i("Liquidaci\xF3n v2: entero inv\xE1lido.");return e}});function im(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,c)=>{let d=o.find(u=>u.clave===s&&!u.archivado);if(!d||!c.includes(d.tipo)||d.multiple)throw i("precios: campo inv\xE1lido.");return d.clave},a=(s,c,d)=>{if(!Array.isArray(s)||!s.length||s.length>d||new Set(s).size!==s.length)throw i("precios: lista vac\xEDa, duplicada o demasiado larga.");return s.map(u=>r(u,c))};if(!["bloquear","prioridad"].includes(String(t.solape))||!["bloquear","pendiente"].includes(String(t.falta)))throw i("precios: pol\xEDtica inv\xE1lida.");return{claves:a(t.claves,["texto","seleccion","relacion","numero"],3),desde: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 am=m(()=>{E()});var sm,mw,RI,cm,lm=m(()=>{sm=new Set(["texto","texto_largo","numero","importe","porcentaje","fecha","fecha_hora","hora","duracion","booleano","seleccion","seleccion_multiple","url","correo","telefono","color","codigo","valoracion","autonumero"]),mw=new Set([...sm,"relacion"]),RI=new Set([...sm,"relacion"]),cm=new Set([...mw,"busqueda"])});function ii(e,o){if(e==null)return;if(!Fr(e))throw i("\xABrecurso\xBB: un objeto.");ni(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 ai(e,o){if(e==null)return;if(!Fr(e))throw i("\xABreserva\xBB: un objeto.");ni(e,["fuente_recurso","recurso","modo","inicio","fin","duracion","duracion_fija","plazas","no_ocupan","fuera_de_horario","margen","cupo","acceso","dia","hora_inicio","hora_fin","vigencia_desde","vigencia_hasta"],"reserva");let t=f=>o.find(h=>h.clave===f&&!h.archivado),n=(f,h,b)=>{let y=t(f);if(!y||!h.includes(y.tipo))throw i(`\xABreserva.${b}\xBB: ${h.join(" o ")} de este m\xF3dulo.`);return y},r=n(e.recurso,["relacion"],"recurso"),a=e.fuente_recurso===void 0?void 0:um(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 c={...a?{fuente_recurso:a}:{},recurso:r.clave,modo:s,fuera_de_horario:e.fuera_de_horario==="permitir"?"permitir":"impedir"};if(s==="puntual")c.inicio=n(e.inicio,["fecha_hora","fecha"],"inicio").clave;else{let f=n(e.dia,["seleccion"],"dia");if(!(f.opciones??[]).length||(f.opciones??[]).some(h=>fw(h.valor)===null))throw i("\xABreserva.dia\xBB: una selecci\xF3n con los d\xEDas de la semana (1\u20137, \xABlunes\xBB\u2026 o L M X J V S D).");c.dia=f.clave,c.hora_inicio=n(e.hora_inicio,["hora"],"hora_inicio").clave,e.vigencia_desde&&(c.vigencia_desde=n(e.vigencia_desde,["fecha"],"vigencia_desde").clave),e.vigencia_hasta&&(c.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(f=>f!=null&&f!=="").length!==1)throw i(`\xABreserva\xBB: ${s==="semanal"?"una hora de fin":"un fin"}, una duraci\xF3n o una duraci\xF3n fija (solo una).`);if(s==="semanal"&&e.fin)throw i("\xABreserva.fin\xBB: en una semanal, \xABhora_fin\xBB.");if(s==="puntual"&&e.hora_fin)throw i("\xABreserva.hora_fin\xBB: en una puntual, \xABfin\xBB.");if(e.hora_fin)c.hora_fin=n(e.hora_fin,["hora"],"hora_fin").clave;else if(e.fin)c.fin=n(e.fin,["fecha_hora","fecha"],"fin").clave;else if(e.duracion)c.duracion=n(e.duracion,["duracion","numero"],"duracion").clave;else{let f=Number(e.duracion_fija);if(!Number.isInteger(f)||f<1||f>1440)throw i("\xABreserva.duracion_fija\xBB: de 1 a 1440 minutos.");c.duracion_fija=f}let u=f=>t(f)?.tipo==="fecha";if(s==="puntual"&&u(c.inicio)!==(c.fin?u(c.fin):!1))throw i("\xABreserva\xBB: por d\xEDas, la entrada y la salida son dos fechas (sin hora); con hora, las dos con hora (o una duraci\xF3n).");if(e.plazas&&(c.plazas=n(e.plazas,["numero"],"plazas").clave),e.cupo&&(c.cupo=n(e.cupo,["numero"],"cupo").clave),e.margen!==void 0&&e.margen!==null){let f=Number(e.margen);if(!Number.isInteger(f)||f<0||f>240)throw i("\xABreserva.margen\xBB: de 0 a 240 minutos.");f&&(c.margen=f)}function p(f,h){let b=Fr(f)?f:{},y=n(b.campo,["seleccion"],`${h}.campo`),v=Array.isArray(b.valores)?b.valores:[];if(!y||!v.length||v.some(w=>!y.opciones?.some(_=>_.valor===w)))throw i(`\xABreserva.${h}\xBB: una selecci\xF3n y algunas de sus opciones.`);return{campo:y.clave,valores:[...new Set(v)]}}if(e.acceso!==void 0&&e.acceso!==null){if(!Fr(e.acceso))throw i("\xABreserva.acceso\xBB: un objeto.");ni(e.acceso,["antes","despues","bloqueado","puerta_extra_obligatoria"],"reserva.acceso");let f=y=>{let v=y===void 0?0:Number(y);if(!Number.isInteger(v)||v<0||v>240)throw i("\xABreserva.acceso\xBB: de 0 a 240 minutos.");return v},h={antes:f(e.acceso.antes),despues:f(e.acceso.despues)};e.acceso.bloqueado!==void 0&&(h.bloqueado=p(e.acceso.bloqueado,"acceso.bloqueado"));let b=e.acceso.puerta_extra_obligatoria;if(b!==void 0){if(!Fr(b)||typeof b.campo!="string"||!/^[a-z][a-z0-9_]{0,39}$/.test(b.campo))throw i("\xABreserva.acceso.puerta_extra_obligatoria\xBB: clave de un campo TTLock del recurso.");if(ni(b,["campo","mismo_codigo"],"reserva.acceso.puerta_extra_obligatoria"),b.mismo_codigo!==void 0&&typeof b.mismo_codigo!="boolean")throw i("\xABreserva.acceso.puerta_extra_obligatoria.mismo_codigo\xBB: un booleano.");h.puerta_extra_obligatoria={campo:b.campo,...b.mismo_codigo?{mismo_codigo:!0}:{}}}(h.antes||h.despues||h.bloqueado||h.puerta_extra_obligatoria)&&(c.acceso=h)}return e.no_ocupan!==void 0&&e.no_ocupan!==null&&(c.no_ocupan=p(e.no_ocupan,"no_ocupan")),c}function fw(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 Fr,ni,gs=m(()=>{E();dm();Fr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ni=(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 gw(e){let o=[],t=0;for(;t<e.length;){let n=e[t];if(/\s/.test(n)){t++;continue}if(o.length>=pm)throw i(`F\xF3rmula demasiado larga: como mucho ${pm} 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="",c=t+1;for(;;){if(c>=e.length)throw i("F\xF3rmula: falta cerrar unas comillas.");if(e[c]===n){if(e[c+1]===n){s+=n,c+=2;continue}break}s+=e[c],c++}if(s.length>500)throw i("F\xF3rmula: un texto de como mucho 500 caracteres.");o.push({t:"txt",v:s}),t=c+1;continue}if(n==="{"){let s=e.indexOf("}",t);if(s<0)throw i("F\xF3rmula: falta cerrar una llave \xAB}\xBB.");let c=e.slice(t+1,s).trim();if(!c||c.length>80)throw i("F\xF3rmula: un campo entre llaves no v\xE1lido.");o.push({t:"campo",v:c}),t=s+1;continue}let 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=hw.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 ww(e){let o=gw(e),t=0,n=0,r=()=>o[t],a=w=>r().t==="op"&&r().v===w,s=w=>{if(!a(w))throw i(`F\xF3rmula: se esperaba \xAB${w}\xBB.`);t++},c=w=>{if(++n>mm)throw i(`F\xF3rmula: como mucho ${mm} niveles de anidaci\xF3n.`);try{return w()}finally{n--}},d=(w,_,C=!1)=>()=>{let S=_();for(;r().t==="op"&&w.includes(r().v)&&(S={k:"bin",op:o[t++].v,a:S,b:_()},!C););return S},u=()=>c(()=>{let w=r();if(w.t==="num")return t++,{k:"num",v:w.v};if(w.t==="txt")return t++,{k:"txt",v:w.v};if(w.t==="campo")return t++,{k:"campo",v:w.v};if(w.t==="op"&&w.v==="-")return t++,{k:"neg",a:u()};if(w.t==="op"&&w.v==="("){t++;let _=y();return s(")"),_}if(w.t==="id"){t++;let _=bw(w.v);if(!a("(")){if(_==="VERDADERO"||_==="TRUE")return{k:"bool",v:!0};if(_==="FALSO"||_==="FALSE")return{k:"bool",v:!1};throw i(`F\xF3rmula: \xAB${w.v}\xBB no es una funci\xF3n (los campos van entre llaves: {${w.v}}).`)}t++;let C=[];if(!a(")"))for(;;){if(C.push(y()),C.length>hm)throw i(`F\xF3rmula: como mucho ${hm} argumentos.`);if(a(",")){t++;continue}break}return s(")"),{k:"fn",f:_,args:C}}throw i(w.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=()=>c(b),v=y();if(r().t!=="fin")throw i("F\xF3rmula: algo sobra al final.");return v}function bs(e){if(!eo(e,0))throw i("F\xF3rmula: A\xD1O, MES y DIA necesitan una fecha.");return"numero"}function bm(e){let o=e[0];for(let t of e.slice(1))o=Zt(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 Zt(e,o){if(e===o)return e;if(eo([e,o],0)&&eo([e,o],1))return"fecha_hora";throw i(`F\xF3rmula: no se mezclan ${xt[e]} y ${xt[o]}.`)}function si(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 ws(e,o){let t=$s(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 vs(e,o,t){if(!o.includes("."))return null;let n=o.trim().toLowerCase();if($s(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 _w(e){let o=e.saltos.at(-1).modulo;if(ym[o]){let t=Ee(e.campo)?e.campos.find(r=>r.clave===e.campo&&!r.archivado):void 0,n=t?Ns[t.tipo]:wm[Br(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 vm({campos:e.campos},yw(e),[])}function vm(e,o,t){if(o.tipo==="formula")return _m(e,o,t).tipo;let n=o.tipo==="busqueda"||o.tipo==="resumen"?o.origen?.tipo??"":o.tipo,r=Ns[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"&&Nw(e,o),r}function Nw(e,o){let t=$s(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??"")||$w.has(o.origen?.tipo??""))throw i(`F\xF3rmula: la b\xFAsqueda \xAB${o.etiqueta}\xBB no es v\xE1lida.`)}else{let n=Br(t.relacion).find(r=>r.clave===o.campo)??(Ee(o.campo)&&o.origen?{tipo:o.origen.tipo}:void 0);if(!n||!(Ee(o.campo)?Ns[n.tipo]:wm[n.tipo])||!ym[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 _m(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>=fm)throw i(`F\xF3rmula: como mucho ${fm} f\xF3rmulas encadenadas.`);return xw(e,o.formula??"",[...t,o.clave],o.origen?.rutas)}function xw(e,o,t,n){if(typeof o!="string"||!o.trim())throw i("F\xF3rmula vac\xEDa.");if(o.length>oo)throw i(`F\xF3rmula de como mucho ${oo} caracteres.`);let r=ww(o),a=new Map,s=u=>{let p=d(u);return a.set(u,p),p},c=(u,p,f)=>{let h=s(u);if(h!==p){if(u.k==="campo"){let y=vs(e,u.v,n)?u.v:ws(e,u.v).etiqueta;throw i(`F\xF3rmula: \xAB${y}\xBB no es ${xt[p]}, es ${xt[h]} (${f} necesita ${xt[p]}).`)}throw i(`F\xF3rmula: ${f} necesita ${xt[p]} y hay ${xt[h]}.`)}},d=u=>{switch(u.k){case"num":return"numero";case"txt":return"texto";case"bool":return"booleano";case"campo":{let p=vs(e,u.v,n);return p?_w(p):vm(e,ws(e,u.v),t)}case"neg":return c(u.a,"numero","\xAB-\xBB"),"numero";case"bin":return u.op==="&"?(s(u.a),s(u.b),"texto"):["+","-","*","/"].includes(u.op)?(c(u.a,"numero",`\xAB${u.op}\xBB`),c(u.b,"numero",`\xAB${u.op}\xBB`),"numero"):(Zt(s(u.a),s(u.b)),"booleano");case"fn":{let p=vw[u.f]??u.f,f=_s[p];if(!f)throw i(`F\xF3rmula: la funci\xF3n \xAB${u.f}\xBB no existe.`);if(p==="REDONDEAR"&&si(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,v)=>{let w=f.args[v]??f.resto;return w==="cualquiera"?s(y):(c(y,w,p),w)});return f.tipo(b)}}};return{tipo:s(r),arbol:r,tipos:a,...n?{rutas:n}:{}}}function ci(e){let o={campos:e};return e.map(t=>{if(t.tipo!=="formula"||t.archivado)return t;let n=_m(o,t,[]),r=t.origen?.rutas&&Object.keys(t.origen.rutas).length?t.origen.rutas:void 0;return{...t,formula:Cw(o,t.formula,r),origen:{tipo:n.tipo,...r?{rutas:r}:{}}}})}function Cw(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),c=o.slice(r+1,s).trim();n+=`{${vs(e,c,t)?c:ws(e,c).clave}}`,r=s+1;continue}n+=a,r++}return n}var oo,pm,mm,fm,hm,ys,hw,bw,eo,$t,gm,Kt,_s,vw,FI,xt,Ns,wm,WI,$s,yw,$w,ym,li=m(()=>{Dr();oi();E();ui();oo=1e3,pm=300,mm=20,fm=5,hm=20,ys="Europe/Madrid",hw=["<>","!=","<=",">=","=","<",">","+","-","*","/","&","(",")",",",";"];bw=e=>e.normalize("NFD").replace(/[̀-ͯ]/g,"").toUpperCase();eo=(e,o)=>e[o]==="fecha"||e[o]==="fecha_hora",$t=(e,o)=>o==="fecha_hora"?O`(${e} at time zone ${ys})::date`:e,gm=e=>O`(${e})::text`,Kt=(e,o)=>O`(least(greatest(${e}, ${-o}::numeric), ${o}::numeric))::int`,_s={PRECIO_VIGENTE:{args:["texto","fecha","texto","cualquiera"],resto:"cualquiera",tipo:()=>"numero",sql:e=>O`((crm_precio_formula(${e[0]}, ${e[1]}::date, jsonb_build_array(${O.join(e.slice(3).map(o=>O`(${o})::text`),O`, `)}))->'valores'->>${e[2]})::numeric)`},SI:{args:["booleano","cualquiera","cualquiera"],opcionales:1,tipo:e=>Zt(e[1],e[2]??e[1]),sql:e=>e[2]?O`(case when ${e[0]} then ${e[1]} else ${e[2]} end)`:O`(case when ${e[0]} then ${e[1]} end)`},Y:{args:[],resto:"booleano",tipo:()=>"booleano",sql:e=>O`(${O.join(e,O` and `)})`},O:{args:[],resto:"booleano",tipo:()=>"booleano",sql:e=>O`(${O.join(e,O` or `)})`},NO:{args:["booleano"],tipo:()=>"booleano",sql:e=>O`(not ${e[0]})`},VACIO:{args:["cualquiera"],tipo:()=>"booleano",sql:(e,o)=>o[0]==="texto"?O`(${e[0]} is null or ${e[0]} = '')`:O`(${e[0]} is null)`},REDONDEAR:{args:["numero","numero"],opcionales:1,tipo:()=>"numero",sql:(e,o,t)=>O`round(${e[0]}, ${si(t[1])}::int)`},ABS:{args:["numero"],tipo:()=>"numero",sql:e=>O`abs(${e[0]})`},MIN:{args:["cualquiera"],resto:"cualquiera",tipo:e=>bm(e),sql:e=>O`least(${O.join(e)})`},MAX:{args:["cualquiera"],resto:"cualquiera",tipo:e=>bm(e),sql:e=>O`greatest(${O.join(e)})`},CONCAT:{args:[],resto:"cualquiera",tipo:()=>"texto",sql:e=>O`concat(${O.join(e.map(gm))})`},MAYUSCULAS:{args:["texto"],tipo:()=>"texto",sql:e=>O`upper(${e[0]})`},MINUSCULAS:{args:["texto"],tipo:()=>"texto",sql:e=>O`lower(${e[0]})`},IZQUIERDA:{args:["texto","numero"],tipo:()=>"texto",sql:e=>O`left(${e[0]}, ${Kt(e[1],1e4)})`},DERECHA:{args:["texto","numero"],tipo:()=>"texto",sql:e=>O`right(${e[0]}, ${Kt(e[1],1e4)})`},LARGO:{args:["texto"],tipo:()=>"numero",sql:e=>O`(length(${e[0]}))::numeric`},RECORTAR:{args:["texto"],tipo:()=>"texto",sql:e=>O`btrim(${e[0]})`},TEXTO:{args:["cualquiera"],tipo:()=>"texto",sql:e=>gm(e[0])},HOY:{args:[],tipo:()=>"fecha",sql:()=>O`(now() at time zone ${ys})::date`},AHORA:{args:[],tipo:()=>"fecha_hora",sql:()=>O`now()`},DIAS_ENTRE:{args:["cualquiera","cualquiera"],tipo:e=>{if(!eo(e,0)||!eo(e,1))throw i("F\xF3rmula: DIAS_ENTRE necesita dos fechas.");return"numero"},sql:(e,o)=>O`((${$t(e[1],o[1])}) - (${$t(e[0],o[0])}))::numeric`},ANADIR_DIAS:{args:["cualquiera","numero"],tipo:e=>{if(!eo(e,0))throw i("F\xF3rmula: A\xD1ADIR_DIAS necesita una fecha.");return e[0]},sql:(e,o)=>o[0]==="fecha"?O`(${e[0]} + ${Kt(e[1],1e5)})`:O`(${e[0]} + make_interval(days => ${Kt(e[1],1e5)}))`},ANO:{args:["cualquiera"],tipo:e=>bs(e),sql:(e,o)=>O`(extract(year from ${$t(e[0],o[0])}))::numeric`},MES:{args:["cualquiera"],tipo:e=>bs(e),sql:(e,o)=>O`(extract(month from ${$t(e[0],o[0])}))::numeric`},DIA:{args:["cualquiera"],tipo:e=>bs(e),sql:(e,o)=>O`(extract(day from ${$t(e[0],o[0])}))::numeric`},POTENCIA:{args:["numero","numero"],tipo:()=>"numero",sql:e=>O`(case when ${e[0]} is null or ${e[1]} is null then null
|
|
6
|
+
${t}`,e}return e}function $w(e){return je(e)&&H(e.stack)}var zr=f(()=>{$()});function Cw(e){return je(e)&&"insertId"in e&&"affectedRows"in e}var xw,jp,Sp=f(()=>{Lr();$();zr();xw=Symbol();jp=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(Nt.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(!Cw(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(je(r)&&"code"in r&&r.code==="ERR_STREAM_PREMATURE_CLOSE")return;throw r}finally{this.#t=void 0}}[xw](){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(Nt.raw(o,[]))});let{clientFlags:a,maxPacketSize:s,...c}=n,d=this.#o(c);try{await new Promise((u,p)=>{d.connect(m=>{if(m)return p(m);if(r.queryId!==this.#t?.queryId)return u();d.query(o,[],h=>{if(h)return p(h);u()})})})}finally{d.destroy()}}}});var Op=f(()=>{});var Ap=f(()=>{});var Ep=f(()=>{});var qp=f(()=>{});var jw,Rp,kp=f(()=>{Lr();zr();jw=Symbol(),Rp=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}}[jw](){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 c=>{a.queryId===this.#r?.queryId&&await c.executeQuery(Nt.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 Pp=f(()=>{});var Tp=f(()=>{});var Hk,Xk,Mp=f(()=>{Hk=BigInt("3853314791062309107"),Xk=3600*1e3});var Ip=f(()=>{});var Dp=f(()=>{});var Sw,Ow,Aw,Lp,Fr,zp=f(()=>{$();Lr();zr();Ba();Ir();Sw=Symbol(),Ow=Symbol(),Aw=Symbol(),Lp=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?Hn(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 Oe;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 Oe;this.#t=new Fr({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 Fr({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}[Ow](){return"closed"in this.#e&&this.#e.closed?Promise.resolve():new Promise(o=>{this.#e.once("end",o),this.#e.close()})}async[Sw](){await new Promise((o,t)=>{this.#e.reset(n=>{if(n)return t(n);o()})})}async[Aw](){if(this.#o||this.#i())return!1;try{let o=new Oe,t=new Fr({compiledQuery:Nt.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}},Fr=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]=(c,d)=>{if(c!=="chunkReady"){if(delete this.#t[s],c==="error")return n.reject(d);n.resolve({rowCount:this.#i,rows:this.#o})}}}this.#e=new this.#n.Request(t.sql,(s,c)=>{if(s)return Object.values(this.#t).forEach(d=>d("error",s instanceof AggregateError?s.errors:s));this.#i=c}),this.#a(t.parameters),this.#s()}get request(){return this.#e}readChunk(){let o=this.readChunk.name;return new Promise((t,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 ct(o)||$o(o)||H(o)?this.#n.TYPES.NVarChar:lt(o)||uo(o)&&o%1===0?o<-2147483648||o>2147483647?this.#n.TYPES.BigInt:this.#n.TYPES.Int:uo(o)?this.#n.TYPES.Float:st(o)?this.#n.TYPES.Bit:sa(o)?this.#n.TYPES.DateTime:Il(o)?this.#n.TYPES.VarBinary:this.#n.TYPES.NVarChar}}});var Fp=f(()=>{});var Wp=f(()=>{});var Bp=f(()=>{});var Vp=f(()=>{});var Ew,qw,Rw,Up,Jp=f(()=>{Ir();zr();Ew=Symbol(),qw=Symbol(),Rw=Symbol(),Up=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[Ew](){let{promise:o,reject:t,resolve:n}=new Oe,{promise:r,resolve:a}=new Oe;this.#o=n,this.#r=t,this.#n=this.#e.transaction(async s=>{this.#t=s,a(),await o}),await r}async[qw](){this.#o?.(),await this.#n,this.#o=void 0,this.#r=void 0,this.#t=void 0,this.#n=void 0}async[Rw](){this.#r?.(),await this.#n?.catch(()=>{}),this.#o=void 0,this.#r=void 0,this.#t=void 0,this.#n=void 0}}});var Qp=f(()=>{});var Gp=f(()=>{});var Hp=f(()=>{});var Xp=f(()=>{});var Yp=f(()=>{});var Kp=f(()=>{});var Zp=f(()=>{});var em=f(()=>{});var om=f(()=>{});var ci=f(()=>{hp();Hu();ip();_n();Ht();os();Ru();Pu();ku();Tr();ka();as();Su();La();Fa();Au();is();cs();ps();Gu();Qu();da();_s();bp();up();ei();Ns();Lr();sp();Bd();Kd();Jd();ep();Fd();Vd();Wd();Ud();Sd();Ed();zd();Gd();tp();Xd();Td();Ld();cp();On();bs();pp();lp();dp();vp();yp();Cp();_p();Np();$p();xp();qp();Sp();Op();Ap();Ep();kp();Ip();Tp();Pp();Mp();Dp();Bp();zp();Fp();Wp();Vp();Jp();Qp();Ns();Gp();Hp();zu();Xp();Yp();Kp();Zp();vd();qd();Id();ti();xo();Pd();Ll();Jo();$n();ri();gs();$d();ua();yd();eo();Ia();Tu();Mu();em();zl();Fl();Wl();Yd();Qd();op();hs();$u();jd();Fn();_d();kd();Bl();Vl();Ul();Zd();Hd();Aa();Za();Ad();Er();rs();Cd();Ga();ya();Na();ne();$a();xr();kn();us();Cr();qn();Mr();xa();Fu();Ea();Od();Qa();Ou();ju();la();Je();Lu();wp();Mt();qu();dt();An();Or();Ra();Ln();Sr();Pa();wa();Md();fa();Ao();pt();jn();ws();Nd();Dd();Oa();ut();Cn();ca();kr();Ta();Ha();om();$r();Da();fs();ss();Rd();zn();ja();Tn();Xo();Nu();Rr();qr();Iu();rp();np();ap();fp();mp()});import{BlockList as tm,isIP as kw}from"node:net";var rm,nm,im,am=f(()=>{rm=new tm,nm=new tm;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]])rm.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]])nm.addSubnet(e,o,"ipv6");im=e=>{let o=kw(e);return o===4?rm.check(e,"ipv4"):o===6?nm.check(e,"ipv6"):!0}});function Wr(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:{},c=typeof s.value=="string"?s.value.trim():"",d=typeof s.label=="string"?s.label.trim():"";if(!c||c.length>80||!$s(c))throw i(`El elemento ${a+1} no tiene una clave v\xE1lida.`);if(!d||d.length>80||!$s(d))throw i(`El elemento ${a+1} necesita un nombre (hasta 80 caracteres).`);if(t.has(c))throw i(`La clave \xAB${c}\xBB est\xE1 repetida.`);t.add(c);let u={value:c,label:d};if(s.color!==void 0&&s.color!==null&&s.color!==""){if(typeof s.color!="string"||!Mw.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,Iw(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 Pw){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 sm){let c=n.find(d=>d.value===s);if(!c)throw new z(400,"tipo_fijo","Los tipos \xABCliente\xBB y \xABProveedor\xBB no se pueden quitar; se pueden renombrar.");if(c.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&&sm.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 Iw(e,o){let t=typeof e.plural=="string"&&e.plural.trim()?e.plural.trim():o;if(t.length>80||!$s(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.campoNif!==void 0){if(typeof e.campoNif!="string"||!/^[a-z][a-z0-9_]*$/.test(e.campoNif))throw i("El campo del NIF debe ser una clave de campo propio.");n.campoNif=e.campoNif}if(e.icono!==void 0&&e.icono!==null&&e.icono!==""){if(typeof e.icono!="string"||!Tw.test(e.icono))throw i(`El icono de \xAB${o}\xBB no es v\xE1lido.`);n.icono=e.icono}return n}var Pw,sm,Tw,$s,Mw,xs=f(()=>{q();Pw=["won","lost"],sm=["cliente","proveedor"],Tw=/^[a-z0-9-]{1,40}$/,$s=e=>!/[\u0000-\u001f\u007f]/.test(e),Mw=/^#[0-9a-fA-F]{3,8}$|^[a-z]{3,20}$/});function cm(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 c=0;for(let d of Cs(s)){let u=o.get(d.relacion);u&&(c=Math.max(c,a(u)+1))}if(c>6)throw i("El autocompletado necesita dependencias sin ciclos y hasta seis pasos.");return n.delete(s.clave),t.set(s.clave,c),r.push(s),c};for(let s of o.values())a(s);return r}var Cs,lm=f(()=>{q();Cs=e=>e.completarDesde?[e.completarDesde,...e.completarDesde.alternativa?[e.completarDesde.alternativa]:[]]:[]});function um(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&&!Dw(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.");Wr("legalForms",[{value:s,label:js(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(c=>c.valor===a);if(js(o,a).length>60||s?.color&&!/^#[0-9a-fA-F]{6}$/.test(s.color))throw i("La etiqueta de clasificaci\xF3n necesita nombre de hasta 60 caracteres y color #rrggbb.")}for(let a of["contacts","companies"])if(Object.entries(t).filter(([c,d])=>d===a&&!Object.hasOwn(n,c)&&!r.includes(c)).length>1)throw i("Las opciones que comparten objeto necesitan forma jur\xEDdica o etiqueta para conservar su significado.");return{...e.formas!==void 0?{formas:n}:{},...e.etiquetas!==void 0?{etiquetas:r}:{}}}function dm(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:js(t,a),...t.opciones?.find(c=>c.valor===a)?.color?{color:t.opciones.find(c=>c.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 Wr("legalForms",[...r.values()])}function pm(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 Dw,js,mm=f(()=>{q();xs();Br();Dw=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);js=(e,o)=>e.opciones?.find(t=>t.valor===o)?.etiqueta??e.etiqueta});var C,fm,hm=f(()=>{C=(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}),fm=[{clave:"companies",icono:"building-2",campoTitulo:"name",campos:[C("name","texto",{enTabla:!0,ancho:240}),C("website","url",{enTabla:!0,ancho:200}),C("sector","seleccion",{enTabla:!0,filtrable:!0,opciones:"config:companySectors"}),C("tags","etiquetas",{enTabla:!0,ordenable:!1,editable:!0,filtrable:!0,relacion:"tags",objetoEtiquetas:"companies",ancho:160,migracion:"0466_etiquetas_por_objeto.sql"}),C("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}),C("city","texto",{enTabla:!0,ancho:140}),C("sales_id","relacion",{enTabla:!0,filtrable:!0,relacion:"sales",ancho:170}),C("nb_contacts","contador",{enTabla:!0,ancho:110}),C("nb_deals","contador",{enTabla:!0,ancho:130}),C("created_at","fecha_hora",{enTabla:!0,ancho:140}),C("proveedor","booleano",{filtrable:!0,ancho:110}),C("has_newsletter","booleano",{etiqueta:"Comunicaciones",filtrable:!0,migracion:"0490_comunicaciones_empresa.sql"}),C("tipos","seleccion_multiple",{enTabla:!0,ordenable:!1,editable:!1,opciones:"config:contactTypes",ancho:170,migracion:"0439_tipos_contactos.sql"}),C("ubicacion","ubicacion",{etiqueta:"Ubicaci\xF3n",editable:!1,ordenable:!1,migracion:"0452_ubicacion_nativa.sql"}),C("phone_number","telefono",{ancho:150}),C("country","texto",{ancho:130}),C("address","texto"),C("state_abbr","texto",{soloFicha:!0,etiqueta:"Provincia"}),C("zipcode","texto",{ancho:110}),C("linkedin_url","url"),C("revenue","texto",{ancho:130}),C("tax_identifier","texto",{ancho:140}),C("razon_social","texto",{ancho:220,migracion:"0440_datos_fiscales.sql"}),C("forma_juridica","seleccion",{filtrable:!0,opciones:"config:legalForms",ancho:160,migracion:"0440_datos_fiscales.sql"}),C("correo_facturacion","correo",{ancho:220,migracion:"0440_datos_fiscales.sql"}),C("pais_fiscal","texto",{filtrable:!0,editable:!1,ancho:90,migracion:"0440_datos_fiscales.sql"}),C("description","texto_largo",{ancho:260})]},{clave:"contacts",icono:"users",campoTitulo:"first_name",camposTitulo:["first_name","last_name"],campos:[C("ubicacion","ubicacion",{etiqueta:"Ubicaci\xF3n",editable:!1,ordenable:!1,migracion:"0452_ubicacion_nativa.sql"}),C("first_name","texto",{enTabla:!0,ancho:220}),C("last_name","texto",{ancho:150}),C("title","texto",{enTabla:!0,ancho:150}),C("company_id","relacion",{enTabla:!0,relacion:"companies",ancho:180}),C("email_jsonb","correos",{enTabla:!0,ordenable:!1,editable:!0,ancho:220}),C("phone_jsonb","telefonos",{enTabla:!0,ordenable:!1,editable:!0,ancho:150}),C("status","seleccion",{enTabla:!0,filtrable:!0,opciones:"config:noteStatuses",ancho:130}),C("tags","etiquetas",{enTabla:!0,ordenable:!1,editable:!0,filtrable:!0,relacion:"tags",objetoEtiquetas:"contacts",ancho:160}),C("tipos","seleccion_multiple",{enTabla:!0,ordenable:!1,editable:!1,opciones:"config:contactTypes",ancho:170,migracion:"0439_tipos_contactos.sql"}),C("sales_id","relacion",{enTabla:!0,filtrable:!0,relacion:"sales",ancho:170}),C("last_seen","fecha_hora",{enTabla:!0,ancho:140}),C("nb_tasks","contador",{ancho:110}),C("first_seen","fecha_hora",{ancho:140}),C("linkedin_url","url"),C("background","texto_largo",{ancho:260}),C("nif","texto",{soloFicha:!0,sensible:!0,etiqueta:"Identificador fiscal",migracion:"0005_datos_es.sql"}),C("iban","texto",{soloFicha:!0,sensible:!0,etiqueta:"IBAN",migracion:"0005_datos_es.sql"}),C("birthday","fecha",{soloFicha:!0,etiqueta:"Fecha de nacimiento",migracion:"0005_datos_es.sql"}),C("address","texto",{soloFicha:!0,etiqueta:"Direcci\xF3n",migracion:"0005_datos_es.sql"}),C("zipcode","texto",{soloFicha:!0,etiqueta:"C\xF3digo postal",migracion:"0005_datos_es.sql"}),C("city","texto",{soloFicha:!0,etiqueta:"Ciudad",migracion:"0005_datos_es.sql"}),C("province","texto",{soloFicha:!0,etiqueta:"Provincia",migracion:"0005_datos_es.sql"}),C("country","texto",{soloFicha:!0,etiqueta:"Pa\xEDs",migracion:"0005_datos_es.sql"}),C("has_newsletter","booleano",{soloFicha:!0,migracion:"0005_datos_es.sql"}),C("pais_fiscal","texto",{filtrable:!0,editable:!1,ancho:90,migracion:"0440_datos_fiscales.sql"})]},{clave:"deals",icono:"handshake",campoTitulo:"name",campos:[C("name","texto",{enTabla:!0,ancho:240}),C("company_id","relacion",{enTabla:!0,relacion:"companies",ancho:180}),C("stage","seleccion",{enTabla:!0,filtrable:!0,opciones:"config:dealStages",ancho:160}),C("amount","importe",{enTabla:!0,ancho:120}),C("expected_closing_date","fecha",{enTabla:!0,ancho:140}),C("category","seleccion",{enTabla:!0,filtrable:!0,opciones:"config:dealCategories",ancho:150}),C("tags","etiquetas",{enTabla:!0,ordenable:!1,editable:!0,filtrable:!0,relacion:"tags",objetoEtiquetas:"deals",ancho:160,migracion:"0466_etiquetas_por_objeto.sql"}),C("sales_id","relacion",{enTabla:!0,filtrable:!0,relacion:"sales",ancho:170}),C("origen_lead","texto",{etiqueta:"Origen",filtrable:!0,editable:!1,ancho:170,migracion:"0467_oportunidades_origen_actividad.sql"}),C("ultima_actividad","fecha_hora",{etiqueta:"\xDAltima actividad",editable:!1,ancho:150,migracion:"0467_oportunidades_origen_actividad.sql"}),C("created_at","fecha_hora",{ancho:140}),C("updated_at","fecha_hora",{ancho:140}),C("description","texto_largo",{ancho:260})]},{clave:"proyectos",icono:"folder-kanban",campoTitulo:"nombre",campos:[C("nombre","texto",{enTabla:!0,ancho:220}),C("clave","texto",{enTabla:!0,ancho:110,editable:!1}),C("estado","seleccion",{etiqueta:"Estado",enTabla:!0,filtrable:!0,opciones:[{valor:"activo",etiqueta:"Activo",color:"#16a34a"},{valor:"completado",etiqueta:"Completado",color:"#2563eb"},{valor:"archivado",etiqueta:"Archivado",color:"#64748b"}],ancho:120}),C("sales_id","relacion",{enTabla:!0,filtrable:!0,relacion:"sales",ancho:170}),C("fecha_inicio","fecha",{enTabla:!0,ancho:130}),C("fecha_fin","fecha",{enTabla:!0,ancho:130}),C("requiere_aceptacion","booleano",{ancho:120}),C("color","texto",{ancho:100}),C("icono","texto",{ancho:100}),C("descripcion","texto_largo",{ancho:260}),C("creado","fecha_hora",{ancho:140}),C("actualizado","fecha_hora",{ancho:140})]},{clave:"tareas",campoEstado:"columna_id",icono:"check-square",campoTitulo:"titulo",campos:[C("titulo","texto",{enTabla:!0,ancho:240}),C("codigo_corto","texto",{enTabla:!0,ancho:110,editable:!1}),C("proyecto_id","relacion",{enTabla:!0,filtrable:!0,relacion:"proyectos",ancho:170,editable:!1}),C("columna_id","texto",{etiqueta:"Estado",enTabla:!0,filtrable:!0,ancho:130}),C("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}),C("sales_id","relacion",{enTabla:!0,filtrable:!0,relacion:"sales",ancho:170}),C("fecha_entrega","fecha",{enTabla:!0,ancho:130}),C("fecha_inicio","fecha",{ancho:130}),C("estimacion_minutos","numero",{ancho:110}),C("hecho","fecha_hora",{enTabla:!0,editable:!0,marca:!0,ancho:120}),C("contact_id","relacion",{filtrable:!0,relacion:"contacts",ancho:160}),C("descripcion","texto_largo",{ancho:260}),C("creado","fecha_hora",{ancho:140}),C("actualizado","fecha_hora",{ancho:140})]}]});function Ss(e){return/^funciones\.([a-z0-9][a-z0-9-]{0,59})\.[a-z][a-z0-9_]{0,40}$/.exec(e)?.[1]}function zw(e,o){return e==="contacts"&&/^(correo|telefono)(_(trabajo|personal))?$/.test(o)?o.startsWith("correo")?"email_jsonb":"phone_jsonb":Lw[e].includes(o)||/^datos\.[a-z][a-z0-9_]{0,40}$/.test(o)||Ss(o)?o:null}function gm(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(c=>!["objeto","tipo","nivel","campos"].includes(c))||!["contacts","companies"].includes(String(n.objeto))||typeof n.tipo!="string"||n.tipo!=="*"&&!/^[a-z0-9][a-z0-9-]{0,59}$/.test(n.tipo)||n.tipo==="*"&&n.nivel!==void 0||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[c,d]of Object.entries(n.campos)){let u=zw(r,c);if(!u||Ss(u)&&Ss(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 Lw,bm=f(()=>{q();Lw={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 wm(e){if(e==null)return;let o=ui(e,["destino","anterior","ciclo","copiar","fechas","estado","precios"]);if(!o.copiar||typeof o.copiar!="object"||Array.isArray(o.copiar)||Object.keys(o.copiar).length>50||!Array.isArray(o.fechas)||!o.fechas.length||o.fechas.length>10)throw i("Sucesi\xF3n: configuraci\xF3n inv\xE1lida.");let t={anterior:Le(o.anterior),ciclo:Le(o.ciclo),copiar:Object.fromEntries(Object.entries(o.copiar).map(([n,r])=>[Le(n),Le(r)])),fechas:o.fechas.map(n=>{let r=ui(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:Le(r.campo),desde:Le(r.desde),meses:r.meses}})};if(o.destino!==void 0&&(t.destino=Le(o.destino)),o.estado){let n=ui(o.estado,["campo","valor"]);if(typeof n.valor!="string"||n.valor.length>100)throw i("Sucesi\xF3n: configuraci\xF3n inv\xE1lida.");t.estado={campo:Le(n.campo),valor:n.valor}}if(o.precios){let n=ui(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:Le(n.tabla),fecha:Le(n.fecha),claves:n.claves.map(Le),valor:Le(n.valor),destino:Le(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 Le,ui,vm=f(()=>{q();Le=e=>{if(typeof e!="string"||!/^[a-z][a-z0-9_]{0,40}$/.test(e))throw i("Sucesi\xF3n: configuraci\xF3n inv\xE1lida.");return e},ui=(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 Vr,p1,Fw,ym=f(()=>{Vr=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 Fw(this.centimos())}},p1=new Vr(0n),Fw=e=>`${e<0n?"-":""}${(e<0n?-e:e)/100n}.${String((e<0n?-e:e)%100n).padStart(2,"0")}`});function Nm(e,o){if(e==null)return;let t=ve(e,["version","beneficiariosPeriodo","origen","fecha","importe","moneda","unidad","grupo","mantenimiento","ciclo","recuperacion","beneficiarios","motor","documento","cuentan","precios","unidad_recuento","componentes"]),n=ve(t.motor,["reglas","combinar","margenNegativo","equipoPropio","principal","minimo","objetivo","fijoPeriodo"]),r=ve(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=(v,w)=>{let N=te(v);if(!o.some(j=>j.clave===N&&!j.archivado&&j.tipo===w))throw i("Liquidaci\xF3n v2: campo de documento inv\xE1lido.");return N},s=Object.fromEntries(Object.entries(ve(t.beneficiarios)).map(([v,w])=>{let N=ve(w,["tipo","campo"]);return[te(v),{tipo:xt(N.tipo,["miembro","contacts","companies","registro"]),campo:N.campo==="_dueno"?"_dueno":te(N.campo)}]}));if(!Object.keys(s).length||Object.keys(s).length>20)throw i("Liquidaci\xF3n v2: beneficiarios inv\xE1lidos.");let c=v=>{let w=ve(v,["clave","beneficiario","fijo","porcentaje","resto","equipo","minimo"]),N=te(w.beneficiario);if(!s[N])throw i("Liquidaci\xF3n v2: beneficiario desconocido.");return{clave:te(w.clave),beneficiario:N,...w.fijo!==void 0?{fijo:$t(w.fijo)}:{},...w.porcentaje!==void 0?{porcentaje:Os(w.porcentaje)}:{},...w.resto===!0?{resto:!0}:{},...w.equipo===!0?{equipo:!0}:{},...typeof w.minimo=="boolean"?{minimo:w.minimo}:{}}},d=et(n.reglas).map(v=>{let w=ve(v,["clave","prioridad","modo","desde","hasta","moneda","unidad","si","bolsa","retencion","receptores"]);if(!_m(w.desde)||w.hasta!==void 0&&(!_m(w.hasta)||w.hasta<=w.desde))throw i("Liquidaci\xF3n v2: vigencia inv\xE1lida.");if(typeof w.moneda!="string"||!/^[A-Z]{3}$/.test(w.moneda)||typeof w.unidad!="string"||!w.unidad||w.unidad.length>60)throw i("Liquidaci\xF3n v2: moneda o unidad inv\xE1lida.");let N=w.si===void 0?void 0:ve(w.si,["campo","valores"]);return{clave:te(w.clave),prioridad:di(w.prioridad),modo:xt(w.modo,["exclusiva","acumulable"]),desde:w.desde,...w.hasta?{hasta:w.hasta}:{},moneda:w.moneda,unidad:w.unidad,receptores:et(w.receptores).map(c),...w.bolsa!==void 0?{bolsa:$t(w.bolsa)}:{},...w.retencion!==void 0?{retencion:$t(w.retencion)}:{},...N?{si:{campo:te(N.campo),valores:et(N.valores).map(j=>String(j).slice(0,100))}}:{}}});if(new Set(d.map(v=>v.clave)).size!==d.length)throw i("Liquidaci\xF3n v2: regla duplicada.");let u;if(n.objetivo){let v=ve(n.objetivo,["beneficiario","medida","modo","tramos","consumirBolsa"]),w=et(v.tramos).map(N=>{let j=ve(N,["desde","tasa","garantia","bonus"]);return{desde:di(j.desde),tasa:v.medida==="recuento"?$t(j.tasa):Os(j.tasa),...j.garantia!==void 0?{garantia:$t(j.garantia)}:{},...j.bonus!==void 0?{bonus:$t(j.bonus)}:{}}});if(!w.length||w[0].desde!==0||w.some((N,j)=>j>0&&N.desde<=w[j-1].desde))throw i("Liquidaci\xF3n v2: umbrales inv\xE1lidos.");u={beneficiario:te(v.beneficiario),medida:xt(v.medida,["recuento","importe"]),modo:xt(v.modo,["alcanzado","marginal"]),tramos:w,consumirBolsa:v.consumirBolsa===!0}}let p=n.minimo?ve(n.minimo,["cantidad","modo"]):void 0,m=n.fijoPeriodo?et(n.fijoPeriodo).map(v=>{let w=ve(v,["beneficiario","importe"]);return{beneficiario:te(w.beneficiario),importe:$t(w.importe)}}):void 0;if(m&&new Set(m.map(v=>v.beneficiario)).size!==m.length)throw i("Liquidaci\xF3n v2: fijo de periodo duplicado.");let h={version:2,origen:t.origen,fecha:te(t.fecha),importe:te(t.importe),moneda:te(t.moneda),unidad:te(t.unidad),grupo:t.grupo==="_dueno"?"_dueno":te(t.grupo),beneficiarios:s,motor:{reglas:d,combinar:n.combinar===!0,margenNegativo:n.margenNegativo===!0,equipoPropio:n.equipoPropio===!0,...n.principal?{principal:te(n.principal)}:{},...p?{minimo:{cantidad:di(p.cantidad),modo:xt(p.modo,["umbral","franquicia"])}}:{},...u?{objetivo:u}:{},...m?{fijoPeriodo:m}:{}},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:te(t.mantenimiento)}:{}};if(t.beneficiariosPeriodo!==void 0&&(h.beneficiariosPeriodo=et(t.beneficiariosPeriodo,1e4).map(v=>{let w=ve(v,["grupo","beneficiarios"]);if(typeof w.grupo!="string"||!w.grupo||w.grupo.length>100)throw i("Liquidaci\xF3n v2: grupo de periodo inv\xE1lido.");let N=Object.fromEntries(Object.entries(ve(w.beneficiarios)).map(([j,S])=>{if(!s[j]||typeof S!="number"||!Number.isSafeInteger(S)||S<1)throw i("Liquidaci\xF3n v2: beneficiario de periodo inv\xE1lido.");return[j,S]}));return{grupo:w.grupo,beneficiarios:N}}),new Set(h.beneficiariosPeriodo.map(v=>v.grupo)).size!==h.beneficiariosPeriodo.length))throw i("Liquidaci\xF3n v2: grupo de periodo duplicado.");if(t.cuentan){let v=ve(t.cuentan,["campo","valores"]);h.cuentan={campo:te(v.campo),valores:et(v.valores).map(String)}}if(t.unidad_recuento&&(h.unidad_recuento=te(t.unidad_recuento)),t.componentes){let v=ve(t.componentes,["modo","campo"]);h.componentes={modo:xt(v.modo,["todos","principal"]),campo:te(v.campo)}}if(t.precios){let v=ve(t.precios,["tabla","fecha","claves","valor"]);if(h.precios={tabla:te(v.tabla),fecha:te(v.fecha),claves:et(v.claves,3).map(te),valor:te(v.valor)},!h.precios.claves.length)throw i("Liquidaci\xF3n v2: claves de precio ausentes.")}if(t.ciclo&&(h.ciclo=te(t.ciclo)),t.recuperacion){let v=ve(t.recuperacion,["modo","plazo"]);if(h.recuperacion={modo:xt(v.modo,["total","proporcional_dias"]),plazo:di(v.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(v=>v.beneficiario)].some(v=>v&&!s[v]))throw i("Liquidaci\xF3n v2: beneficiario desconocido.");let b=o.find(v=>v.clave===h.documento.lineas);if(["fuente","concepto","importe"].some(v=>!b.columnas?.some(w=>w.clave===v&&w.tipo==="texto"&&!w.archivado)))throw i("Liquidaci\xF3n v2: columnas de resumen inv\xE1lidas.");let y=o.find(v=>v.clave===h.documento.estado);if(["borrador","aprobada","cerrada","pagada"].some(v=>!y.opciones?.some(w=>w.valor===v)))throw i("Liquidaci\xF3n v2: estados inv\xE1lidos.");return h}var ve,_m,te,Os,$t,et,xt,di,$m=f(()=>{q();ym();ve=(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},_m=e=>typeof e=="string"&&/^\d{4}-\d{2}-\d{2}$/.test(e)&&Number.isFinite(Date.parse(e+"T00:00:00Z"))&&new Date(e+"T00:00:00Z").toISOString().slice(0,10)===e,te=e=>{if(typeof e!="string"||!/^[a-z][a-z0-9_]{0,40}$/.test(e))throw i("Liquidaci\xF3n v2: clave inv\xE1lida.");return e},Os=e=>{if(typeof e!="string")throw i("Liquidaci\xF3n v2: decimal como cadena.");try{if(Vr.leer(e).n<0n)throw new Error("negativo")}catch{throw i("Liquidaci\xF3n v2: decimal inv\xE1lido.")}return e},$t=e=>{let o=Os(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},et=(e,o=20)=>{if(!Array.isArray(e)||e.length>o)throw i("Liquidaci\xF3n v2: lista inv\xE1lida.");return e},xt=(e,o)=>{if(!o.includes(e))throw i("Liquidaci\xF3n v2: opci\xF3n inv\xE1lida.");return e},di=e=>{if(typeof e!="number"||!Number.isSafeInteger(e)||e<0)throw i("Liquidaci\xF3n v2: entero inv\xE1lido.");return e}});function xm(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,c)=>{let d=o.find(u=>u.clave===s&&!u.archivado);if(!d||!c.includes(d.tipo)||d.multiple)throw i("precios: campo inv\xE1lido.");return d.clave},a=(s,c,d)=>{if(!Array.isArray(s)||!s.length||s.length>d||new Set(s).size!==s.length)throw i("precios: lista vac\xEDa, duplicada o demasiado larga.");return s.map(u=>r(u,c))};if(!["bloquear","prioridad"].includes(String(t.solape))||!["bloquear","pendiente"].includes(String(t.falta)))throw i("precios: pol\xEDtica inv\xE1lida.");return{claves:a(t.claves,["texto","seleccion","relacion","numero"],3),desde: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 Cm=f(()=>{q()});var jm,Ww,v1,Sm,Om=f(()=>{jm=new Set(["texto","texto_largo","numero","importe","porcentaje","fecha","fecha_hora","hora","duracion","booleano","seleccion","seleccion_multiple","url","correo","telefono","color","codigo","valoracion","autonumero"]),Ww=new Set([...jm,"relacion"]),v1=new Set([...jm,"relacion"]),Sm=new Set([...Ww,"busqueda"])});function Am(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"&&Bw.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"&&Vw.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 Bw,Vw,Em=f(()=>{q();Bw=/^mod_[a-z][a-z0-9_]{0,40}$/,Vw=/^[a-z0-9][a-z0-9-]{0,59}$/});function mi(e,o){if(e==null)return;if(!Ur(e))throw i("\xABrecurso\xBB: un objeto.");pi(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 fi(e,o){if(e==null)return;if(!Ur(e))throw i("\xABreserva\xBB: un objeto.");pi(e,["fuente_recurso","recurso","modo","inicio","fin","duracion","duracion_fija","plazas","no_ocupan","fuera_de_horario","margen","cupo","acceso","dia","hora_inicio","hora_fin","vigencia_desde","vigencia_hasta"],"reserva");let t=m=>o.find(h=>h.clave===m&&!h.archivado),n=(m,h,b)=>{let y=t(m);if(!y||!h.includes(y.tipo))throw i(`\xABreserva.${b}\xBB: ${h.join(" o ")} de este m\xF3dulo.`);return y},r=n(e.recurso,["relacion"],"recurso"),a=e.fuente_recurso===void 0?void 0:Am(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 c={...a?{fuente_recurso:a}:{},recurso:r.clave,modo:s,fuera_de_horario:e.fuera_de_horario==="permitir"?"permitir":"impedir"};if(s==="puntual")c.inicio=n(e.inicio,["fecha_hora","fecha"],"inicio").clave;else{let m=n(e.dia,["seleccion"],"dia");if(!(m.opciones??[]).length||(m.opciones??[]).some(h=>Uw(h.valor)===null))throw i("\xABreserva.dia\xBB: una selecci\xF3n con los d\xEDas de la semana (1\u20137, \xABlunes\xBB\u2026 o L M X J V S D).");c.dia=m.clave,c.hora_inicio=n(e.hora_inicio,["hora"],"hora_inicio").clave,e.vigencia_desde&&(c.vigencia_desde=n(e.vigencia_desde,["fecha"],"vigencia_desde").clave),e.vigencia_hasta&&(c.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(m=>m!=null&&m!=="").length!==1)throw i(`\xABreserva\xBB: ${s==="semanal"?"una hora de fin":"un fin"}, una duraci\xF3n o una duraci\xF3n fija (solo una).`);if(s==="semanal"&&e.fin)throw i("\xABreserva.fin\xBB: en una semanal, \xABhora_fin\xBB.");if(s==="puntual"&&e.hora_fin)throw i("\xABreserva.hora_fin\xBB: en una puntual, \xABfin\xBB.");if(e.hora_fin)c.hora_fin=n(e.hora_fin,["hora"],"hora_fin").clave;else if(e.fin)c.fin=n(e.fin,["fecha_hora","fecha"],"fin").clave;else if(e.duracion)c.duracion=n(e.duracion,["duracion","numero"],"duracion").clave;else{let m=Number(e.duracion_fija);if(!Number.isInteger(m)||m<1||m>1440)throw i("\xABreserva.duracion_fija\xBB: de 1 a 1440 minutos.");c.duracion_fija=m}let u=m=>t(m)?.tipo==="fecha";if(s==="puntual"&&u(c.inicio)!==(c.fin?u(c.fin):!1))throw i("\xABreserva\xBB: por d\xEDas, la entrada y la salida son dos fechas (sin hora); con hora, las dos con hora (o una duraci\xF3n).");if(e.plazas&&(c.plazas=n(e.plazas,["numero"],"plazas").clave),e.cupo&&(c.cupo=n(e.cupo,["numero"],"cupo").clave),e.margen!==void 0&&e.margen!==null){let m=Number(e.margen);if(!Number.isInteger(m)||m<0||m>240)throw i("\xABreserva.margen\xBB: de 0 a 240 minutos.");m&&(c.margen=m)}function p(m,h){let b=Ur(m)?m:{},y=n(b.campo,["seleccion"],`${h}.campo`),v=Array.isArray(b.valores)?b.valores:[];if(!y||!v.length||v.some(w=>!y.opciones?.some(N=>N.valor===w)))throw i(`\xABreserva.${h}\xBB: una selecci\xF3n y algunas de sus opciones.`);return{campo:y.clave,valores:[...new Set(v)]}}if(e.acceso!==void 0&&e.acceso!==null){if(!Ur(e.acceso))throw i("\xABreserva.acceso\xBB: un objeto.");pi(e.acceso,["antes","despues","bloqueado","puerta_extra_obligatoria"],"reserva.acceso");let m=y=>{let v=y===void 0?0:Number(y);if(!Number.isInteger(v)||v<0||v>240)throw i("\xABreserva.acceso\xBB: de 0 a 240 minutos.");return v},h={antes:m(e.acceso.antes),despues:m(e.acceso.despues)};e.acceso.bloqueado!==void 0&&(h.bloqueado=p(e.acceso.bloqueado,"acceso.bloqueado"));let b=e.acceso.puerta_extra_obligatoria;if(b!==void 0){if(!Ur(b)||typeof b.campo!="string"||!/^[a-z][a-z0-9_]{0,39}$/.test(b.campo))throw i("\xABreserva.acceso.puerta_extra_obligatoria\xBB: clave de un campo TTLock del recurso.");if(pi(b,["campo","mismo_codigo"],"reserva.acceso.puerta_extra_obligatoria"),b.mismo_codigo!==void 0&&typeof b.mismo_codigo!="boolean")throw i("\xABreserva.acceso.puerta_extra_obligatoria.mismo_codigo\xBB: un booleano.");h.puerta_extra_obligatoria={campo:b.campo,...b.mismo_codigo?{mismo_codigo:!0}:{}}}(h.antes||h.despues||h.bloqueado||h.puerta_extra_obligatoria)&&(c.acceso=h)}return e.no_ocupan!==void 0&&e.no_ocupan!==null&&(c.no_ocupan=p(e.no_ocupan,"no_ocupan")),c}function Uw(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 Ur,pi,As=f(()=>{q();Em();Ur=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),pi=(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 Qw(e){let o=[],t=0;for(;t<e.length;){let n=e[t];if(/\s/.test(n)){t++;continue}if(o.length>=qm)throw i(`F\xF3rmula demasiado larga: como mucho ${qm} 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="",c=t+1;for(;;){if(c>=e.length)throw i("F\xF3rmula: falta cerrar unas comillas.");if(e[c]===n){if(e[c+1]===n){s+=n,c+=2;continue}break}s+=e[c],c++}if(s.length>500)throw i("F\xF3rmula: un texto de como mucho 500 caracteres.");o.push({t:"txt",v:s}),t=c+1;continue}if(n==="{"){let s=e.indexOf("}",t);if(s<0)throw i("F\xF3rmula: falta cerrar una llave \xAB}\xBB.");let c=e.slice(t+1,s).trim();if(!c||c.length>80)throw i("F\xF3rmula: un campo entre llaves no v\xE1lido.");o.push({t:"campo",v:c}),t=s+1;continue}let 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=Jw.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 Hw(e){let o=Qw(e),t=0,n=0,r=()=>o[t],a=w=>r().t==="op"&&r().v===w,s=w=>{if(!a(w))throw i(`F\xF3rmula: se esperaba \xAB${w}\xBB.`);t++},c=w=>{if(++n>Rm)throw i(`F\xF3rmula: como mucho ${Rm} niveles de anidaci\xF3n.`);try{return w()}finally{n--}},d=(w,N,j=!1)=>()=>{let S=N();for(;r().t==="op"&&w.includes(r().v)&&(S={k:"bin",op:o[t++].v,a:S,b:N()},!j););return S},u=()=>c(()=>{let w=r();if(w.t==="num")return t++,{k:"num",v:w.v};if(w.t==="txt")return t++,{k:"txt",v:w.v};if(w.t==="campo")return t++,{k:"campo",v:w.v};if(w.t==="op"&&w.v==="-")return t++,{k:"neg",a:u()};if(w.t==="op"&&w.v==="("){t++;let N=y();return s(")"),N}if(w.t==="id"){t++;let N=Gw(w.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${w.v}\xBB no es una funci\xF3n (los campos van entre llaves: {${w.v}}).`)}t++;let j=[];if(!a(")"))for(;;){if(j.push(y()),j.length>Pm)throw i(`F\xF3rmula: como mucho ${Pm} argumentos.`);if(a(",")){t++;continue}break}return s(")"),{k:"fn",f:N,args:j}}throw i(w.t==="fin"?"F\xF3rmula incompleta.":"F\xF3rmula: algo sobra o falta.")}),p=d(["*","/"],u),m=d(["+","-"],p),h=d(["&"],m),b=d(["=","<>","<","<=",">",">="],h,!0),y=()=>c(b),v=y();if(r().t!=="fin")throw i("F\xF3rmula: algo sobra al final.");return v}function Es(e){if(!ro(e,0))throw i("F\xF3rmula: A\xD1O, MES y DIA necesitan una fecha.");return"numero"}function Mm(e){let o=e[0];for(let t of e.slice(1))o=or(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 or(e,o){if(e===o)return e;if(ro([e,o],0)&&ro([e,o],1))return"fecha_hora";throw i(`F\xF3rmula: no se mezclan ${jt[e]} y ${jt[o]}.`)}function hi(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 qs(e,o){let t=Ms(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 Rs(e,o,t){if(!o.includes("."))return null;let n=o.trim().toLowerCase();if(Ms(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 Kw(e){let o=e.saltos.at(-1).modulo;if(Lm[o]){let t=Ee(e.campo)?e.campos.find(r=>r.clave===e.campo&&!r.archivado):void 0,n=t?Ts[t.tipo]:Im[Qr(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 Dm({campos:e.campos},Yw(e),[])}function Dm(e,o,t){if(o.tipo==="formula")return zm(e,o,t).tipo;let n=o.tipo==="busqueda"||o.tipo==="resumen"?o.origen?.tipo??"":o.tipo,r=Ts[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"&&Zw(e,o),r}function Zw(e,o){let t=Ms(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??"")||ev.has(o.origen?.tipo??""))throw i(`F\xF3rmula: la b\xFAsqueda \xAB${o.etiqueta}\xBB no es v\xE1lida.`)}else{let n=Qr(t.relacion).find(r=>r.clave===o.campo)??(Ee(o.campo)&&o.origen?{tipo:o.origen.tipo}:void 0);if(!n||!(Ee(o.campo)?Ts[n.tipo]:Im[n.tipo])||!Lm[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 zm(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>=km)throw i(`F\xF3rmula: como mucho ${km} f\xF3rmulas encadenadas.`);return ov(e,o.formula??"",[...t,o.clave],o.origen?.rutas)}function ov(e,o,t,n){if(typeof o!="string"||!o.trim())throw i("F\xF3rmula vac\xEDa.");if(o.length>no)throw i(`F\xF3rmula de como mucho ${no} caracteres.`);let r=Hw(o),a=new Map,s=u=>{let p=d(u);return a.set(u,p),p},c=(u,p,m)=>{let h=s(u);if(h!==p){if(u.k==="campo"){let y=Rs(e,u.v,n)?u.v:qs(e,u.v).etiqueta;throw i(`F\xF3rmula: \xAB${y}\xBB no es ${jt[p]}, es ${jt[h]} (${m} necesita ${jt[p]}).`)}throw i(`F\xF3rmula: ${m} necesita ${jt[p]} y hay ${jt[h]}.`)}},d=u=>{switch(u.k){case"num":return"numero";case"txt":return"texto";case"bool":return"booleano";case"campo":{let p=Rs(e,u.v,n);return p?Kw(p):Dm(e,qs(e,u.v),t)}case"neg":return c(u.a,"numero","\xAB-\xBB"),"numero";case"bin":return u.op==="&"?(s(u.a),s(u.b),"texto"):["+","-","*","/"].includes(u.op)?(c(u.a,"numero",`\xAB${u.op}\xBB`),c(u.b,"numero",`\xAB${u.op}\xBB`),"numero"):(or(s(u.a),s(u.b)),"booleano");case"fn":{let p=Xw[u.f]??u.f,m=Ps[p];if(!m)throw i(`F\xF3rmula: la funci\xF3n \xAB${u.f}\xBB no existe.`);if(p==="REDONDEAR"&&hi(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=m.args.length-(m.opcionales??0);if(u.args.length<Math.max(h,m.resto?1:0)||!m.resto&&u.args.length>m.args.length)throw i(`F\xF3rmula: ${p} no lleva ${u.args.length} argumentos.`);let b=u.args.map((y,v)=>{let w=m.args[v]??m.resto;return w==="cualquiera"?s(y):(c(y,w,p),w)});return m.tipo(b)}}};return{tipo:s(r),arbol:r,tipos:a,...n?{rutas:n}:{}}}function gi(e){let o={campos:e};return e.map(t=>{if(t.tipo!=="formula"||t.archivado)return t;let n=zm(o,t,[]),r=t.origen?.rutas&&Object.keys(t.origen.rutas).length?t.origen.rutas:void 0;return{...t,formula:tv(o,t.formula,r),origen:{tipo:n.tipo,...r?{rutas:r}:{}}}})}function tv(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),c=o.slice(r+1,s).trim();n+=`{${Rs(e,c,t)?c:qs(e,c).clave}}`,r=s+1;continue}n+=a,r++}return n}var no,qm,Rm,km,Pm,ks,Jw,Gw,ro,Ct,Tm,er,Ps,Xw,E1,jt,Ts,Im,q1,Ms,Yw,ev,Lm,bi=f(()=>{Br();ci();q();wi();no=1e3,qm=300,Rm=20,km=5,Pm=20,ks="Europe/Madrid",Jw=["<>","!=","<=",">=","=","<",">","+","-","*","/","&","(",")",",",";"];Gw=e=>e.normalize("NFD").replace(/[̀-ͯ]/g,"").toUpperCase();ro=(e,o)=>e[o]==="fecha"||e[o]==="fecha_hora",Ct=(e,o)=>o==="fecha_hora"?A`(${e} at time zone ${ks})::date`:e,Tm=e=>A`(${e})::text`,er=(e,o)=>A`(least(greatest(${e}, ${-o}::numeric), ${o}::numeric))::int`,Ps={PRECIO_VIGENTE:{args:["texto","fecha","texto","cualquiera"],resto:"cualquiera",tipo:()=>"numero",sql:e=>A`((crm_precio_formula(${e[0]}, ${e[1]}::date, jsonb_build_array(${A.join(e.slice(3).map(o=>A`(${o})::text`),A`, `)}))->'valores'->>${e[2]})::numeric)`},SI:{args:["booleano","cualquiera","cualquiera"],opcionales:1,tipo:e=>or(e[1],e[2]??e[1]),sql:e=>e[2]?A`(case when ${e[0]} then ${e[1]} else ${e[2]} end)`:A`(case when ${e[0]} then ${e[1]} end)`},Y:{args:[],resto:"booleano",tipo:()=>"booleano",sql:e=>A`(${A.join(e,A` and `)})`},O:{args:[],resto:"booleano",tipo:()=>"booleano",sql:e=>A`(${A.join(e,A` or `)})`},NO:{args:["booleano"],tipo:()=>"booleano",sql:e=>A`(not ${e[0]})`},VACIO:{args:["cualquiera"],tipo:()=>"booleano",sql:(e,o)=>o[0]==="texto"?A`(${e[0]} is null or ${e[0]} = '')`:A`(${e[0]} is null)`},REDONDEAR:{args:["numero","numero"],opcionales:1,tipo:()=>"numero",sql:(e,o,t)=>A`round(${e[0]}, ${hi(t[1])}::int)`},ABS:{args:["numero"],tipo:()=>"numero",sql:e=>A`abs(${e[0]})`},MIN:{args:["cualquiera"],resto:"cualquiera",tipo:e=>Mm(e),sql:e=>A`least(${A.join(e)})`},MAX:{args:["cualquiera"],resto:"cualquiera",tipo:e=>Mm(e),sql:e=>A`greatest(${A.join(e)})`},CONCAT:{args:[],resto:"cualquiera",tipo:()=>"texto",sql:e=>A`concat(${A.join(e.map(Tm))})`},MAYUSCULAS:{args:["texto"],tipo:()=>"texto",sql:e=>A`upper(${e[0]})`},MINUSCULAS:{args:["texto"],tipo:()=>"texto",sql:e=>A`lower(${e[0]})`},IZQUIERDA:{args:["texto","numero"],tipo:()=>"texto",sql:e=>A`left(${e[0]}, ${er(e[1],1e4)})`},DERECHA:{args:["texto","numero"],tipo:()=>"texto",sql:e=>A`right(${e[0]}, ${er(e[1],1e4)})`},LARGO:{args:["texto"],tipo:()=>"numero",sql:e=>A`(length(${e[0]}))::numeric`},RECORTAR:{args:["texto"],tipo:()=>"texto",sql:e=>A`btrim(${e[0]})`},TEXTO:{args:["cualquiera"],tipo:()=>"texto",sql:e=>Tm(e[0])},HOY:{args:[],tipo:()=>"fecha",sql:()=>A`(now() at time zone ${ks})::date`},AHORA:{args:[],tipo:()=>"fecha_hora",sql:()=>A`now()`},DIAS_ENTRE:{args:["cualquiera","cualquiera"],tipo:e=>{if(!ro(e,0)||!ro(e,1))throw i("F\xF3rmula: DIAS_ENTRE necesita dos fechas.");return"numero"},sql:(e,o)=>A`((${Ct(e[1],o[1])}) - (${Ct(e[0],o[0])}))::numeric`},ANADIR_DIAS:{args:["cualquiera","numero"],tipo:e=>{if(!ro(e,0))throw i("F\xF3rmula: A\xD1ADIR_DIAS necesita una fecha.");return e[0]},sql:(e,o)=>o[0]==="fecha"?A`(${e[0]} + ${er(e[1],1e5)})`:A`(${e[0]} + make_interval(days => ${er(e[1],1e5)}))`},ANO:{args:["cualquiera"],tipo:e=>Es(e),sql:(e,o)=>A`(extract(year from ${Ct(e[0],o[0])}))::numeric`},MES:{args:["cualquiera"],tipo:e=>Es(e),sql:(e,o)=>A`(extract(month from ${Ct(e[0],o[0])}))::numeric`},DIA:{args:["cualquiera"],tipo:e=>Es(e),sql:(e,o)=>A`(extract(day from ${Ct(e[0],o[0])}))::numeric`},POTENCIA:{args:["numero","numero"],tipo:()=>"numero",sql:e=>A`(case when ${e[0]} is null or ${e[1]} is null then null
|
|
7
7
|
when abs(${e[1]}) > 64 or abs(${e[0]}) > 1000000000 then null
|
|
8
8
|
when ${e[0]} = 0 and ${e[1]} < 0 then null
|
|
9
9
|
when ${e[0]} < 0 and ${e[1]} <> trunc(${e[1]}) then null
|
|
10
|
-
else power((${e[0]})::numeric, (${e[1]})::numeric) end)`},PAGO:{args:["numero","numero","numero"],tipo:()=>"numero",sql:e=>
|
|
10
|
+
else power((${e[0]})::numeric, (${e[1]})::numeric) end)`},PAGO:{args:["numero","numero","numero"],tipo:()=>"numero",sql:e=>A`(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=
|
|
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=hi(t[1]);return n?A`(ceil((${e[0]})::numeric * ${10**n}::numeric) / ${10**n}::numeric)`:A`ceil((${e[0]})::numeric)`}},REDONDEAR_ABAJO:{args:["numero","numero"],opcionales:1,tipo:()=>"numero",sql:(e,o,t)=>{let n=hi(t[1]);return n?A`(floor((${e[0]})::numeric * ${10**n}::numeric) / ${10**n}::numeric)`:A`floor((${e[0]})::numeric)`}},DIAS_HABILES:{args:["cualquiera","cualquiera"],tipo:e=>{if(!ro(e,0)||!ro(e,1))throw i("F\xF3rmula: DIAS_HABILES necesita dos fechas.");return"numero"},sql:(e,o)=>{let t=Ct(e[0],o[0]),n=Ct(e[1],o[1]);return A`(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(_s,{RESTO:{args:["numero","numero"],tipo:()=>"numero",sql:e=>O`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?(Zt(e[0],e[t]),o=o?Zt(o,e[t+1]):e[t+1]):o=o?Zt(o,e[t]):e[t];return o},sql:e=>{let o=[];for(let n=1;n+1<e.length;n+=2)o.push(O`when ${e[0]} = ${e[n]} then ${e[n+1]}`);let t=(e.length-1)%2===1?O`else ${e[e.length-1]}`:O``;return O`(case ${O.join(o,O` `)} ${t} end)`}},CONTIENE:{args:["texto","texto"],tipo:()=>"booleano",sql:e=>O`(strpos(lower(${e[0]}), lower(${e[1]})) > 0)`},SUSTITUIR:{args:["texto","texto","texto"],tipo:()=>"texto",sql:e=>O`replace(${e[0]}, ${e[1]}, coalesce(${e[2]}, ''))`},ANADIR_MESES:{args:["cualquiera","numero"],tipo:e=>{if(!eo(e,0))throw i("F\xF3rmula: A\xD1ADIR_MESES necesita una fecha.");return e[0]},sql:(e,o)=>o[0]==="fecha"?O`((${e[0]} + make_interval(months => ${Kt(e[1],12e3)}))::date)`:O`(${e[0]} + make_interval(months => ${Kt(e[1],12e3)}))`},HORAS_ENTRE:{args:["cualquiera","cualquiera"],tipo:e=>{if(!eo(e,0)||!eo(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"?O`((${n})::timestamp at time zone ${ys})`:n;return O`round((extract(epoch from (${t(e[1],o[1])} - ${t(e[0],o[0])})) / 3600)::numeric, 6)`}}});vw={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"},FI=Object.keys(_s);xt={numero:"un n\xFAmero",texto:"un texto",fecha:"una fecha",fecha_hora:"una fecha y hora",booleano:"un s\xED/no"};Ns={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"},wm={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"},WI={numero:O`numeric`,texto:O`text`,fecha:O`date`,fecha_hora:O`timestamptz`,booleano:O`boolean`},$s=e=>e.campos.filter(o=>!o.archivado);yw=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};$w=new Set(["creado_el","creado_por","modificado_el","modificado_por","autonumero"]),ym={companies:"companies_summary",contacts:"contacts_summary",deals:"deals"}});function Nm(e,o){if(e==null)return;if(!Vr(e))throw i("\xABerp\xBB: un objeto.");let t=(r,a,s=!1)=>{if(!(r===void 0&&s)){if(typeof r!="string"||!o.some(c=>c.clave===r&&c.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(!Vr(r)||!Vr(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,c=(d,u,p=!1)=>{if(!(d===void 0&&p)){if(typeof d!="string"||!(a.columnas??[]).some(f=>f.clave===d))throw i(`ERP: \xAB${u}\xBB no es una columna de la subtabla.`);return d}};if(s.articulo!==void 0&&!(a.columnas??[]).some(d=>d.clave===s.articulo&&d.tipo==="articulo"))throw i("ERP: \xABarticulo\xBB, una columna de art\xEDculo de la subtabla.");if(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:c(s.descripcion,"descripcion"),precio:c(s.precio,"precio"),...s.cantidad!==void 0?{cantidad:c(s.cantidad,"cantidad")}:{},...s.iva!==void 0?{iva:c(s.iva,"iva")}:{},...s.articulo!==void 0?{articulo:s.articulo}:{}}}}if(e.gasto!==void 0){let r=e.gasto;if(!Vr(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(!Vr(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 Vr,$m=m(()=>{E();Vr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)});function jm(e,o){if(e==null)return;if(!Ro(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=Ur(r,o)??{},s=or(n,"El texto del documento",Sm);if(s){for(let c of s.matchAll(/\{\{\s*([^}]*?)\s*\}\}/g)){let d=c[1].split("|")[0].trim();if(d!=="hoy"&&d!=="espacio.nombre"&&!/^padre\.[a-z][a-z0-9_]{0,40}$/.test(d)&&!o.some(u=>u.clave===d&&!u.archivado))throw i(`El texto del documento: \xAB{{${d.slice(0,40)}}}\xBB no es una columna de la l\xEDnea ni \xABpadre.<campo>\xBB.`)}a.cuerpo=s}if(t!=null){if(!Array.isArray(t)||t.length>3||t.some(c=>typeof c!="string"||!c.trim()||c.length>60))throw i("\xABejemplares\xBB: hasta 3, cada uno con su r\xF3tulo (hasta 60).");t.length&&(a.ejemplares=t.map(c=>c.trim()))}return Object.keys(a).length?a:void 0}function er(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 or(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 Ct(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 xm(e,o){if(e===void 0)return;if(!Ro(e))throw i("La condici\xF3n de ficha necesita un campo y un valor.");er(e,["campo","valor"],"Condici\xF3n de ficha");let t=o.find(n=>n.clave===e.campo&&!n.archivado);if(t?.tipo==="seleccion"&&typeof e.valor=="string"&&t.opciones?.some(n=>n.valor===e.valor))return{campo:t.clave,valor:e.valor};if(t?.tipo==="booleano"&&typeof e.valor=="boolean")return{campo:t.clave,valor:e.valor};throw i("La condici\xF3n de ficha necesita una opci\xF3n del campo o un valor de s\xED/no.")}function di(e,o){if(e==null)return;if(!Ro(e))throw i("\xABficha\xBB: un objeto.");er(e,["cabecera","columnas","pestanas","grupos","relacionadas","erp","sin_conexion","rapido","duplicados","tarjeta","en_crear","filtros","principal","plegar_vacios"],"Ficha");let t={},n=Ct(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(!Ro(f))throw i(`Pesta\xF1a ${h+1}: un objeto.`);er(f,["titulo","secciones","artefacto","cuando"],`Pesta\xF1a ${h+1}`);let b=or(f.titulo,`Pesta\xF1a ${h+1}`,40);if(!b)throw i(`Pesta\xF1a ${h+1}: falta el t\xEDtulo.`);let y=xm(f.cuando,o);if(f.artefacto!==void 0){let v=Number(f.artefacto);if(!Number.isSafeInteger(v)||v<1)throw i(`Pesta\xF1a ${h+1}: el artefacto no es v\xE1lido.`);return{titulo:b,secciones:[],artefacto:v,...y?{cuando:y}:{}}}if(!Array.isArray(f.secciones)||f.secciones.length>20||!f.secciones.every(v=>typeof v=="string"&&v.length<=60))throw i(`Pesta\xF1a ${h+1}: sus secciones, hasta 20.`);return{titulo:b,secciones:[...new Set(f.secciones)],...y?{cuando:y}:{}}});p.length&&(t.pestanas=p)}if(e.grupos!==void 0){if(!Array.isArray(e.grupos)||e.grupos.length>40)throw i("Hasta 40 grupos de ficha.");let p=new Set(o.filter(b=>!b.archivado).map(b=>b.seccion??"")),f=new Set,h=e.grupos.map(b=>{if(!Ro(b))throw i("Grupo de ficha: un objeto.");if(er(b,["seccion","cuando","plegado"],"Grupo de ficha"),typeof b.seccion!="string"||!p.has(b.seccion)||f.has(b.seccion))throw i("El grupo debe corresponder a una secci\xF3n distinta de la ficha.");if(b.plegado!==void 0&&typeof b.plegado!="boolean")throw i("Grupo plegado: s\xED o no.");f.add(b.seccion);let y=xm(b.cuando,o);return{seccion:b.seccion,...y?{cuando:y}:{},...b.plegado!==void 0?{plegado:b.plegado}:{}}});h.length&&(t.grupos=h)}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=Nm(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=Ct(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=Ct(e.duplicados,o,3,"Los campos de duplicados",p=>jw.includes(p.tipo));s?.length&&(t.duplicados=s);let c=Ct(e.tarjeta,o,3,"La tarjeta",p=>!["subtabla","boton","archivos","texto_largo","firma"].includes(p.tipo));if(c?.length&&(t.tarjeta=c),e.en_crear!==void 0){if(typeof e.en_crear!="boolean")throw i("\xABen_crear\xBB: s\xED o no.");e.en_crear&&(t.en_crear=!0)}let d=Ct(e.filtros,o,4,"Los filtros de arriba",p=>Sw.includes(p.tipo));d?.length&&(t.filtros=d);let u=Ct(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 Ur(e,o){if(e==null)return;if(!Ro(e))throw i("\xABimpresion\xBB: un objeto.");er(e,["titulo","campos","subtabla","subtablaVacia","pie","logo","orientacion","cuerpo","color","firmas"],"Impresi\xF3n");let t={},n=or(e.titulo,"El t\xEDtulo de la impresi\xF3n",80);n&&(t.titulo=n);let r=Ct(e.campos,o,40,"Los campos de la impresi\xF3n",c=>!["subtabla","boton"].includes(c.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(c=>c.clave===e.subtabla&&c.tipo==="subtabla"&&!c.archivado)&&(t.subtabla=e.subtabla)}if(t.subtabla&&e.subtablaVacia!=null&&e.subtablaVacia!==""){if(typeof e.subtablaVacia!="string"||e.subtablaVacia.length>120)throw i("El texto de la subtabla vac\xEDa admite hasta 120 caracteres.");e.subtablaVacia.trim()&&(t.subtablaVacia=e.subtablaVacia.trim())}let a=or(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=or(e.cuerpo,"El texto del documento",Sm);if(s){for(let c of s.matchAll(/\{\{\s*([^}]*?)\s*\}\}/g)){let d=c[1].split("|")[0].trim();if(d!=="hoy"&&d!=="espacio.nombre"&&!o.some(u=>u.clave===d&&!u.archivado))throw i(`El texto del documento: \xAB{{${d.slice(0,40)}}}\xBB no es un campo del m\xF3dulo.`)}t.cuerpo=s}if(e.color!==void 0&&e.color!==null&&e.color!==""){if(typeof e.color!="string"||!/^#[0-9a-fA-F]{6}$/.test(e.color))throw i("\xABcolor\xBB: #rrggbb.");t.color=e.color.toLowerCase()}if(e.firmas!==void 0&&e.firmas!==null){if(!Array.isArray(e.firmas)||e.firmas.length>4||e.firmas.some(c=>typeof c!="string"||!c.trim()||c.length>60))throw i("\xABfirmas\xBB: hasta 4 casillas, cada una con su texto (hasta 60).");e.firmas.length&&(t.firmas=e.firmas.map(c=>c.trim()))}return Object.keys(t).length?t:void 0}function xs(e,o=0){return o>10?!1:Array.isArray(e)?e.every(t=>xs(t,o+1)):Ro(e)?Object.keys(e).every(t=>!Ow.has(t)&&xs(e[t],o+1)):!0}function Om(e,o){if(e==null)return;if(!Array.isArray(e)||e.length>10)throw i("\xABvistas\xBB: hasta 10.");let t=e.map((n,r)=>{if(!Ro(n))throw i(`Vista ${r+1}: un objeto.`);er(n,["nombre","tipo","config"],`Vista ${r+1}`);let a=or(n.nombre,`Vista ${r+1}`,60);if(!a)throw i(`Vista ${r+1}: falta el nombre.`);if(typeof n.tipo!="string"||!Cm.includes(n.tipo))throw i(`Vista ${r+1}: tipo ${Cm.join(", ")}.`);if(n.config!==void 0&&(!Ro(n.config)||!xs(n.config)||JSON.stringify(n.config).length>4e3))throw i(`Vista ${r+1}: \xABconfig\xBB, un objeto de hasta 4 KB.`);let s=n.config;if(n.tipo==="kanban"&&s?.segundo!==void 0){let c=o.find(d=>d.clave===s.segundo&&!d.archivado);if(!c||c.clave===s.agrupar||!(c.tipo==="seleccion"&&c.opciones?.length||c.tipo==="relacion"&&!c.multiple))throw i("El segundo campo del kanban debe ser una selecci\xF3n o una relaci\xF3n simple distinta de la primera.")}return{nombre:a,tipo:n.tipo,...n.config?{config:n.config}:{}}});return t.length?t:void 0}var Ro,jw,Sw,Sm,Cm,Ow,Cs=m(()=>{E();$m();Ro=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);jw=["texto","correo","telefono","codigo","url"],Sw=["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"];Sm=12e3;Cm=["kanban","calendario","linea","mapa","galeria","tablero","cuadrante","dia"],Ow=new Set(["__proto__","constructor","prototype"])});var Jr,Am=m(()=>{Jr=e=>e==="@contacts"||e==="@companies"});function fi(e,o){if(e==null)return;if(!Array.isArray(e)||e.length>pi)throw i(`\xABrelacionadas\xBB: hasta ${pi} columnas.`);if(!e.length)return;let t=new Set;return e.map((n,r)=>{let a=`Columna relacionada ${r+1}`;if(!Ss(n))throw i(`${a}: un objeto.`);qm(n,["clave","etiqueta","via","campo","de","calculo","filtro","siVacio"],a);let s=jt(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 c=Jr(String(n.de))&&typeof n.via=="string"&&/^datos\.[a-z][a-z0-9_]{0,40}$/.test(n.via)?n.via:jt(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"&&Jr(n.de)?n.de:jt(n.de,`${a}.de`);if(typeof n.calculo!="string"||!Em.includes(n.calculo))throw i(`${a}: \xABcalculo\xBB, uno de ${Em.join(", ")}.`);let p=n.calculo,f=p==="recuento"?void 0:Jr(u)&&typeof n.campo=="string"&&/^datos\.[a-z][a-z0-9_]{0,40}$/.test(n.campo)?n.campo:jt(n.campo,`${a}.campo`),h=Qr(n.filtro,a,Jr(u));return{clave:s,etiqueta:n.etiqueta.trim(),via:c,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===c&&!u.archivado);if(!d||d.tipo!=="relacion")throw i(`${a}: \xAB${c}\xBB no es una relaci\xF3n de este m\xF3dulo.`);if(d.multiple&&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:c,campo:n.campo,...n.siVacio!==void 0?{siVacio:jt(n.siVacio,`${a}.siVacio`)}:{}}})}function hi(e){if(e==null)return;if(!Array.isArray(e)||e.length>mi)throw i(`\xABsiguientes\xBB: hasta ${mi} pasos.`);if(!e.length)return;let o=new Set;return e.map((t,n)=>{let r=`Siguiente paso ${n+1}`;if(!Ss(t))throw i(`${r}: un objeto.`);qm(t,["clave","nombre","destino","enlace","campos"],r);let a=jt(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=jt(t.enlace,`${r}.enlace`),c;if(t.campos!==void 0&&t.campos!==null){if(!Ss(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(!js.test(d)||typeof u!="string"||!js.test(u))throw i(`${r}: \xABcampos.${d.slice(0,40)}\xBB no es v\xE1lido.`);c=t.campos}return{clave:a,nombre:t.nombre.trim(),destino:t.destino,enlace:s,...c&&Object.keys(c).length?{campos:c}:{}}})}var Em,pi,mi,js,Ss,qm,jt,gi=m(()=>{Am();E();Gr();Em=["recuento","suma","minimo","maximo","ultimo","media"],pi=20,mi=5,js=/^[a-z][a-z0-9_]{0,40}$/,Ss=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),qm=(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.`)},jt=(e,o)=>{if(typeof e!="string"||!js.test(e))throw i(`${o}: falta o no es v\xE1lido.`);return e}});function Os(e,o){if(e===void 0)return;if(!e||typeof e!="object"||Array.isArray(e))throw i("La configuraci\xF3n de ra\xEDces necesita objetos expl\xEDcitos.");let t={};for(let[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,c]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"?di(c,o):s==="impresion"?Ur(c,o):s==="relacionadas"?fi(c,o):s==="recurso"?ii(c,o):s==="reserva"?ai(c,o):hi(c))??null})}t[n]=a}return t}var km=m(()=>{gs();E();Cs();gi()});function Pm(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=>!As.includes(n)))throw i("Un ajuste nativo no cambia la identidad de la relaci\xF3n.");return structuredClone(e)}}var As,Es=m(()=>{E();As=["etiqueta","ayuda","enTabla","obligatorio","visibleSi","obligatorioSi","permisos","siVacio","completarDesde"]});function Tm(e,o,t={}){for(let[r,a]of Object.entries(t)){let s=e.find(u=>u.clave===r&&!u.archivado),c=o[r],d=s?.opciones??[];if(s?.tipo!=="seleccion"||!c||!Object.hasOwn(qs,c)||Object.keys(a).length!==d.length||!d.length||d.some(u=>!Object.hasOwn(a,u.valor))||Object.values(a).some(u=>typeof u!="string"||!u||u!==u.trim())||new Set(Object.values(a)).size!==d.length)throw i("Las conversiones nativas necesitan un mapa de selecciones completo.")}let n=new Map;for(let r of e){let a=o[r.clave];if(r.archivado||r.tipo!=="seleccion"||!a||!Object.hasOwn(qs,a))continue;let s=qs[a];if(r.opciones?.some(c=>c.hecho||c.requisito||c.pide?.length||c.limiteDias!==void 0||c.aprobacion))throw i("Las opciones de Personas/Empresas no pueden perder reglas de etapas.");n.set(s,Lr(s,(r.opciones??[]).map(c=>({value:Object.hasOwn(t,r.clave)?t[r.clave][c.valor]:c.valor,label:c.etiqueta,...c.color?{color:c.color}:{}}))))}return n}var qs,Mm=m(()=>{E();ds();qs={sector:"companySectors",forma_juridica:"legalForms"}});function ks(e,o){if(e===void 0)return;if(!ko(e))throw i("\xABpersonas\xBB: un objeto.");if(Rs(e,["objeto","tipo","de","campoNif","etiqueta","plural","icono","campos","conversiones","alternativa","clasificacion","configuracion"],"\xABpersonas\xBB"),e.alternativa!==void 0||e.clasificacion!==void 0)return Ew(e,o);if(e.objeto==="deals"&&o.some(f=>f.tipo==="autonumero"))throw i("Los auton\xFAmeros propios no est\xE1n disponibles en Oportunidades.");if(e.objeto==="deals"&&o.some(f=>f.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=bi(e.tipo,"tipo",60);if(!Aw.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=bi(e.icono,"icono",40);if(!/^[a-z0-9-]+$/.test(n))throw i("\xABpersonas.icono\xBB: una clave de icono.");if(!ko(e.campos))throw i("\xABpersonas.campos\xBB: un mapa expl\xEDcito de campos nativos.");let r={},a=new Map;for(let[f,h]of Object.entries(e.campos)){let b=o.find(w=>w.clave===f&&!w.archivado),y=typeof h=="string"&&Object.hasOwn(Lm[e.objeto],h)?Lm[e.objeto][h]:void 0,v=Ee(h);if(!b||!(v?cm.has(b.tipo):y?.includes(b.tipo)))throw i(`\xABpersonas.campos.${f.slice(0,40)}\xBB: campo nativo o tipo incompatible.`);if(b.unico&&typeof h=="string"&&h.startsWith("persona."))throw i("El campo propio necesita conservar sus reglas antes de convertir la ra\xEDz.");if(a.has(h)&&h!=="nif"&&h!=="tax_identifier")throw i(`\xABpersonas.campos\xBB: dos campos apuntan a \xAB${h}\xBB.`);a.set(h,f),r[f]=h}let s=e.objeto==="contacts"?"first_name":"name";if(!a.has(s))throw i(`\xABpersonas.campos\xBB: falta el nombre nativo \xAB${s}\xBB.`);let c=o.filter(f=>!f.archivado);for(let f of c)if(!Object.hasOwn(r,f.clave)&&f.tipo!=="resumen"&&f.tipo!=="formula")throw i(`\xABpersonas.campos\xBB: falta destino para \xAB${f.clave}\xBB; no se puede perder un campo.`);if(e.conversiones!==void 0&&!ko(e.conversiones))throw i("Las conversiones nativas necesitan un mapa de selecciones completo.");let d={};for(let[f,h]of Object.entries(e.conversiones??{})){if(!ko(h)||Object.values(h).some(b=>typeof b!="string"))throw i("Las conversiones nativas necesitan un mapa de selecciones completo.");Object.defineProperty(d,f,{value:{...h},enumerable:!0})}let u=e.campoNif;if(u!==void 0&&(e.objeto!=="contacts"||typeof u!="string"||!Object.hasOwn(r,u)||!r[u]?.startsWith("datos.")||!o.some(f=>f.clave===u&&["texto","codigo"].includes(f.tipo))))throw i("\xABpersonas.campoNif\xBB: elige un campo propio de texto de Personas.");zm(o,r,t),Tm(o,r,d);let p=Os(e.configuracion,o);if(p&&Object.keys(p).some(f=>f!==e.objeto))throw i("La configuraci\xF3n cita un objeto que esta ra\xEDz no declara.");return{objeto:e.objeto,tipo:t,...typeof u=="string"?{campoNif:u}:{},...e.de?{de:e.de}:{},...p?{configuracion:p}:{},etiqueta:bi(e.etiqueta,"etiqueta",60),plural:bi(e.plural,"plural",60),icono:n,campos:r,...e.conversiones!==void 0?{conversiones:d}:{}}}function Ew(e,o){let t=e.alternativa,n=e.clasificacion;if(e.objeto!=="contacts"||!ko(t)||t.objeto!=="companies"||!ko(t.campos)||!ko(n))throw i("Los destinos dobles necesitan Persona, Empresa y clasificaci\xF3n expl\xEDcita.");Rs(t,["objeto","campos","conversiones"],"\xABpersonas.alternativa\xBB"),Rs(n,["campo","valores","vacio","formas","etiquetas","propiedad"],"\xABpersonas.clasificacion\xBB");let r=o.find(v=>v.clave===n.campo&&!v.archivado);if(!r||!["seleccion","booleano"].includes(r.tipo)||!ko(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(v=>v.hecho||v.requisito||v.pide?.length||v.limiteDias!==void 0||v.aprobacion))throw i("La clasificaci\xF3n no puede perder permisos ni reglas de etapas.");let a=r.tipo==="booleano"?["true","false"]:(r.opciones??[]).map(v=>v.valor);if(!a.length||Object.keys(n.valores).length!==a.length||a.some(v=>!Object.hasOwn(n.valores,v))||Object.values(n.valores).some(v=>v!=="contacts"&&v!=="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=Up(n,r,n.valores),c={campo:r.clave,valores:{...n.valores},...n.vacio?{vacio:n.vacio}:{},...s},{alternativa:d,clasificacion:u,configuracion:p,...f}=e,h=v=>ks(v,Qp(o,c,v.objeto).filter(w=>ko(v.campos)&&Object.hasOwn(v.campos,w.clave)||w.tipo==="resumen"||w.tipo==="formula")),b=h(f),y=h({...f,objeto:"companies",campoNif:void 0,campos:t.campos,conversiones:t.conversiones});if(c.propiedad){if(b.campos[r.clave]!==c.propiedad||y.campos[r.clave]!==c.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 v of o.filter(w=>!w.archivado&&w.clave!==r.clave&&w.tipo!=="resumen"&&w.tipo!=="formula"))if(!Object.hasOwn(b.campos,v.clave)&&!Object.hasOwn(y.campos,v.clave))throw i("Los destinos deben conservar todos los campos del origen salvo el discriminante.");return Jp(o,c),{...b,alternativa:{objeto:"companies",campos:y.campos,...y.conversiones?{conversiones:y.conversiones}:{}},clasificacion:c,...e.configuracion!==void 0?{configuracion:Os(e.configuracion,o)}:{}}}var Im,Lm,ko,Aw,bi,Rs,Dm=m(()=>{Dr();lm();km();E();Gp();Mm();Im={ubicacion:["ubicacion"],address:["texto","texto_largo"],zipcode:["texto","codigo"],city:["texto"],country:["texto"],pais_fiscal:["texto","seleccion"],iban:["texto"]},Lm={contacts:{...Im,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:{...Im,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"]}},ko=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Aw=/^[a-z0-9][a-z0-9-]{0,59}$/,bi=(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()},Rs=(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.`)}});import{createContext as qw,Script as Rw}from"node:vm";function wi(e,o){if(e!=null){if(!Array.isArray(e)||e.length>Fm)throw i(`\xAB${o}\xBB: como mucho ${Fm} 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(!kw.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(!Pw(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 Jm(e,o){if(!(e==null||e==="")){if(typeof e!="string"||e.length>Wm)throw i(`\xAB${o}\xBB: el patr\xF3n, hasta ${Wm} caracteres.`);if(/\\[1-9]|\\k<|\(\?<[=!]/.test(e))throw i(`\xAB${o}\xBB: el patr\xF3n no admite retroreferencias ni lookbehind.`);if(Tw(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 Tw(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),c=/^(?:[+*]|\{\d*,)/.test(s)||/^\{(\d+)\}/.test(s)&&Number(/^\{(\d+)\}/.exec(s)[1])>1;if(a&&c)return!0;o.length&&(a||c)&&(o[o.length-1]=!0);continue}(r==="+"||r==="*"||r==="?"||r==="{"||r==="|")&&o.length&&(o[o.length-1]=!0)}return!1}function Qm(e,o){if(e==null)return;let t=e,n=t?.tipo;if(typeof t!="object"||!Bm[n])throw i(`\xAB${o.etiqueta}\xBB: valor por defecto no v\xE1lido.`);if(!Bm[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 kw,Fm,Wm,Vm,Um,Bm,Pw,_1,N1,Gm=m(()=>{E();kw=["igual","distinto","vacio","lleno","uno_de"],Fm=10,Wm=200,Vm=["texto","correo","telefono","url","codigo"],Um=["texto","correo","telefono","url","codigo","numero","importe"],Bm={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"]},Pw=e=>typeof e=="string"&&e.length<=200||typeof e=="number"&&Number.isFinite(e)||typeof e=="boolean";_1=qw({p:"",v:""}),N1=new Rw("new RegExp(p, 'u').test(v)")});function Xm(e,o){if(e==null)return;if(!Array.isArray(e)||e.length>Hm)throw i(`\xABvalidaciones\xBB: hasta ${Hm}.`);let t=[];for(let[n,r]of e.entries()){if(!Iw(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>oo)throw i(`Validaci\xF3n ${n+1}: la f\xF3rmula, de 1 a ${oo} 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=ci([...o,Lw(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 Hm,Iw,Lw,Ym=m(()=>{E();li();Hm=20,Iw=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Lw=(e,o)=>({clave:`validacion_${e}`,etiqueta:`Validaci\xF3n ${e+1}`,tipo:"formula",formula:o})});function ef(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(!Zm(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"||!Km.test(e.campo))throw i(`${t}: \xBFde qu\xE9 campo depende?`);if(o.tipo==="seleccion"){if(!Zm(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"||!Km.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 of(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(c=>c.valor)),s=new Set((t.opciones??[]).map(c=>c.valor));for(let[c,d]of Object.entries(n.opciones??{})){if(!a.has(c))throw i(`\xAB${t.etiqueta}\xBB: \xAB${c.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 Km,Zm,tf=m(()=>{E();Km=/^[a-z][a-z0-9_]{0,39}$/,Zm=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)});function nf(e,o){if(!Array.isArray(e)||e.length>300)throw i("Hasta 300 transiciones por campo.");let t=new Set(o.opciones?.map(r=>r.valor)),n=new Set;return e.map(r=>{if(!rf(r)||r.desde!==null&&!t.has(r.desde)||!t.has(r.hasta)||r.desde===r.hasta)throw i("El origen y el destino deben ser estados diferentes del campo; el origen vac\xEDo representa el alta.");let a=JSON.stringify([r.desde,r.hasta]);if(n.has(a))throw i("Transici\xF3n repetida.");n.add(a);let s={desde:r.desde,hasta:r.hasta};if(s.papeles=Ps(r.papeles,30,/^(titular|administrador|miembro|lectura|p_[a-z]{1,12})$/),s.pide=Ps(r.pide,30,/^[a-z][a-z0-9_]{0,40}$/),s.acciones=Ps(r.acciones,10),r.aprobacion!==void 0){let c=r.aprobacion;if(!rf(c)||c.papel!==void 0&&(typeof c.papel!="string"||!/^[a-z_]{1,40}$/.test(c.papel))||c.personas!==void 0&&(!Number.isInteger(c.personas)||Number(c.personas)<1||Number(c.personas)>10))throw i("Aprobaci\xF3n de transici\xF3n no v\xE1lida.");s.aprobacion={papel:c.papel,personas:c.personas}}return s})}function af(e){for(let o of e)for(let t of o.transiciones??[])for(let n of t.pide??[]){let r=e.find(a=>a.clave===n&&!a.archivado);if(!r||["formula","resumen","busqueda","subtabla","boton","autonumero","creado_el","creado_por","modificado_el","modificado_por"].includes(r.tipo))throw i("La guarda debe referirse a un campo editable del m\xF3dulo.")}return e}var rf,Ps,sf=m(()=>{E();rf=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Ps=(e,o,t)=>{if(e!==void 0){if(!Array.isArray(e)||e.length>o||e.some(n=>typeof n!="string"||!n.trim()||n.length>80||t&&!t.test(n)))throw i("Lista de transici\xF3n no v\xE1lida.");if(new Set(e).size!==e.length)throw i("La transici\xF3n contiene valores repetidos.");return e}}});function cf(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 k1,lf=m(()=>{oi();E();k1=O`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(Ps,{RESTO:{args:["numero","numero"],tipo:()=>"numero",sql:e=>A`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?(or(e[0],e[t]),o=o?or(o,e[t+1]):e[t+1]):o=o?or(o,e[t]):e[t];return o},sql:e=>{let o=[];for(let n=1;n+1<e.length;n+=2)o.push(A`when ${e[0]} = ${e[n]} then ${e[n+1]}`);let t=(e.length-1)%2===1?A`else ${e[e.length-1]}`:A``;return A`(case ${A.join(o,A` `)} ${t} end)`}},CONTIENE:{args:["texto","texto"],tipo:()=>"booleano",sql:e=>A`(strpos(lower(${e[0]}), lower(${e[1]})) > 0)`},SUSTITUIR:{args:["texto","texto","texto"],tipo:()=>"texto",sql:e=>A`replace(${e[0]}, ${e[1]}, coalesce(${e[2]}, ''))`},ANADIR_MESES:{args:["cualquiera","numero"],tipo:e=>{if(!ro(e,0))throw i("F\xF3rmula: A\xD1ADIR_MESES necesita una fecha.");return e[0]},sql:(e,o)=>o[0]==="fecha"?A`((${e[0]} + make_interval(months => ${er(e[1],12e3)}))::date)`:A`(${e[0]} + make_interval(months => ${er(e[1],12e3)}))`},HORAS_ENTRE:{args:["cualquiera","cualquiera"],tipo:e=>{if(!ro(e,0)||!ro(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"?A`((${n})::timestamp at time zone ${ks})`:n;return A`round((extract(epoch from (${t(e[1],o[1])} - ${t(e[0],o[0])})) / 3600)::numeric, 6)`}}});Xw={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"},E1=Object.keys(Ps);jt={numero:"un n\xFAmero",texto:"un texto",fecha:"una fecha",fecha_hora:"una fecha y hora",booleano:"un s\xED/no"};Ts={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"},Im={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"},q1={numero:A`numeric`,texto:A`text`,fecha:A`date`,fecha_hora:A`timestamptz`,booleano:A`boolean`},Ms=e=>e.campos.filter(o=>!o.archivado);Yw=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};ev=new Set(["creado_el","creado_por","modificado_el","modificado_por","autonumero"]),Lm={companies:"companies_summary",contacts:"contacts_summary",deals:"deals"}});function Fm(e,o){if(e==null)return;if(!Gr(e))throw i("\xABerp\xBB: un objeto.");let t=(r,a,s=!1)=>{if(!(r===void 0&&s)){if(typeof r!="string"||!o.some(c=>c.clave===r&&c.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(!Gr(r)||!Gr(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,c=(d,u,p=!1)=>{if(!(d===void 0&&p)){if(typeof d!="string"||!(a.columnas??[]).some(m=>m.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:c(s.descripcion,"descripcion"),precio:c(s.precio,"precio"),...s.cantidad!==void 0?{cantidad:c(s.cantidad,"cantidad")}:{},...s.iva!==void 0?{iva:c(s.iva,"iva")}:{},...s.articulo!==void 0?{articulo:s.articulo}:{}}}}if(e.gasto!==void 0){let r=e.gasto;if(!Gr(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(!Gr(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 Gr,Wm=f(()=>{q();Gr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)});function Um(e,o){if(e==null)return;if(!Po(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=Hr(r,o)??{},s=rr(n,"El texto del documento",Jm);if(s){for(let c of s.matchAll(/\{\{\s*([^}]*?)\s*\}\}/g)){let d=c[1].split("|")[0].trim();if(d!=="hoy"&&d!=="espacio.nombre"&&!/^padre\.[a-z][a-z0-9_]{0,40}$/.test(d)&&!o.some(u=>u.clave===d&&!u.archivado))throw i(`El texto del documento: \xAB{{${d.slice(0,40)}}}\xBB no es una columna de la l\xEDnea ni \xABpadre.<campo>\xBB.`)}a.cuerpo=s}if(t!=null){if(!Array.isArray(t)||t.length>3||t.some(c=>typeof c!="string"||!c.trim()||c.length>60))throw i("\xABejemplares\xBB: hasta 3, cada uno con su r\xF3tulo (hasta 60).");t.length&&(a.ejemplares=t.map(c=>c.trim()))}return Object.keys(a).length?a:void 0}function tr(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 rr(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 St(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 Bm(e,o){if(e===void 0)return;if(!Po(e))throw i("La condici\xF3n de ficha necesita un campo y un valor.");tr(e,["campo","valor"],"Condici\xF3n de ficha");let t=o.find(n=>n.clave===e.campo&&!n.archivado);if(t?.tipo==="seleccion"&&typeof e.valor=="string"&&t.opciones?.some(n=>n.valor===e.valor))return{campo:t.clave,valor:e.valor};if(t?.tipo==="booleano"&&typeof e.valor=="boolean")return{campo:t.clave,valor:e.valor};throw i("La condici\xF3n de ficha necesita una opci\xF3n del campo o un valor de s\xED/no.")}function vi(e,o){if(e==null)return;if(!Po(e))throw i("\xABficha\xBB: un objeto.");tr(e,["cabecera","columnas","pestanas","grupos","relacionadas","erp","sin_conexion","rapido","duplicados","tarjeta","en_crear","filtros","principal","plegar_vacios"],"Ficha");let t={},n=St(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((m,h)=>{if(!Po(m))throw i(`Pesta\xF1a ${h+1}: un objeto.`);tr(m,["titulo","secciones","artefacto","cuando"],`Pesta\xF1a ${h+1}`);let b=rr(m.titulo,`Pesta\xF1a ${h+1}`,40);if(!b)throw i(`Pesta\xF1a ${h+1}: falta el t\xEDtulo.`);let y=Bm(m.cuando,o);if(m.artefacto!==void 0){let v=Number(m.artefacto);if(!Number.isSafeInteger(v)||v<1)throw i(`Pesta\xF1a ${h+1}: el artefacto no es v\xE1lido.`);return{titulo:b,secciones:[],artefacto:v,...y?{cuando:y}:{}}}if(!Array.isArray(m.secciones)||m.secciones.length>20||!m.secciones.every(v=>typeof v=="string"&&v.length<=60))throw i(`Pesta\xF1a ${h+1}: sus secciones, hasta 20.`);return{titulo:b,secciones:[...new Set(m.secciones)],...y?{cuando:y}:{}}});p.length&&(t.pestanas=p)}if(e.grupos!==void 0){if(!Array.isArray(e.grupos)||e.grupos.length>40)throw i("Hasta 40 grupos de ficha.");let p=new Set(o.filter(b=>!b.archivado).map(b=>b.seccion??"")),m=new Set,h=e.grupos.map(b=>{if(!Po(b))throw i("Grupo de ficha: un objeto.");if(tr(b,["seccion","cuando","plegado"],"Grupo de ficha"),typeof b.seccion!="string"||!p.has(b.seccion)||m.has(b.seccion))throw i("El grupo debe corresponder a una secci\xF3n distinta de la ficha.");if(b.plegado!==void 0&&typeof b.plegado!="boolean")throw i("Grupo plegado: s\xED o no.");m.add(b.seccion);let y=Bm(b.cuando,o);return{seccion:b.seccion,...y?{cuando:y}:{},...b.plegado!==void 0?{plegado:b.plegado}:{}}});h.length&&(t.grupos=h)}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=Fm(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=St(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=St(e.duplicados,o,3,"Los campos de duplicados",p=>rv.includes(p.tipo));s?.length&&(t.duplicados=s);let c=St(e.tarjeta,o,3,"La tarjeta",p=>!["subtabla","boton","archivos","texto_largo","firma"].includes(p.tipo));if(c?.length&&(t.tarjeta=c),e.en_crear!==void 0){if(typeof e.en_crear!="boolean")throw i("\xABen_crear\xBB: s\xED o no.");e.en_crear&&(t.en_crear=!0)}let d=St(e.filtros,o,4,"Los filtros de arriba",p=>nv.includes(p.tipo));d?.length&&(t.filtros=d);let u=St(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 Hr(e,o){if(e==null)return;if(!Po(e))throw i("\xABimpresion\xBB: un objeto.");tr(e,["titulo","campos","subtabla","subtablaVacia","pie","logo","orientacion","cuerpo","color","firmas"],"Impresi\xF3n");let t={},n=rr(e.titulo,"El t\xEDtulo de la impresi\xF3n",80);n&&(t.titulo=n);let r=St(e.campos,o,40,"Los campos de la impresi\xF3n",c=>!["subtabla","boton"].includes(c.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(c=>c.clave===e.subtabla&&c.tipo==="subtabla"&&!c.archivado)&&(t.subtabla=e.subtabla)}if(t.subtabla&&e.subtablaVacia!=null&&e.subtablaVacia!==""){if(typeof e.subtablaVacia!="string"||e.subtablaVacia.length>120)throw i("El texto de la subtabla vac\xEDa admite hasta 120 caracteres.");e.subtablaVacia.trim()&&(t.subtablaVacia=e.subtablaVacia.trim())}let a=rr(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=rr(e.cuerpo,"El texto del documento",Jm);if(s){for(let c of s.matchAll(/\{\{\s*([^}]*?)\s*\}\}/g)){let d=c[1].split("|")[0].trim();if(d!=="hoy"&&d!=="espacio.nombre"&&!o.some(u=>u.clave===d&&!u.archivado))throw i(`El texto del documento: \xAB{{${d.slice(0,40)}}}\xBB no es un campo del m\xF3dulo.`)}t.cuerpo=s}if(e.color!==void 0&&e.color!==null&&e.color!==""){if(typeof e.color!="string"||!/^#[0-9a-fA-F]{6}$/.test(e.color))throw i("\xABcolor\xBB: #rrggbb.");t.color=e.color.toLowerCase()}if(e.firmas!==void 0&&e.firmas!==null){if(!Array.isArray(e.firmas)||e.firmas.length>4||e.firmas.some(c=>typeof c!="string"||!c.trim()||c.length>60))throw i("\xABfirmas\xBB: hasta 4 casillas, cada una con su texto (hasta 60).");e.firmas.length&&(t.firmas=e.firmas.map(c=>c.trim()))}return Object.keys(t).length?t:void 0}function Is(e,o=0){return o>10?!1:Array.isArray(e)?e.every(t=>Is(t,o+1)):Po(e)?Object.keys(e).every(t=>!iv.has(t)&&Is(e[t],o+1)):!0}function Qm(e,o){if(e==null)return;if(!Array.isArray(e)||e.length>10)throw i("\xABvistas\xBB: hasta 10.");let t=e.map((n,r)=>{if(!Po(n))throw i(`Vista ${r+1}: un objeto.`);tr(n,["nombre","tipo","config"],`Vista ${r+1}`);let a=rr(n.nombre,`Vista ${r+1}`,60);if(!a)throw i(`Vista ${r+1}: falta el nombre.`);if(typeof n.tipo!="string"||!Vm.includes(n.tipo))throw i(`Vista ${r+1}: tipo ${Vm.join(", ")}.`);if(n.config!==void 0&&(!Po(n.config)||!Is(n.config)||JSON.stringify(n.config).length>4e3))throw i(`Vista ${r+1}: \xABconfig\xBB, un objeto de hasta 4 KB.`);let s=n.config;if(n.tipo==="kanban"&&s?.segundo!==void 0){let c=o.find(d=>d.clave===s.segundo&&!d.archivado);if(!c||c.clave===s.agrupar||!(c.tipo==="seleccion"&&c.opciones?.length||c.tipo==="relacion"&&!c.multiple))throw i("El segundo campo del kanban debe ser una selecci\xF3n o una relaci\xF3n simple distinta de la primera.")}return{nombre:a,tipo:n.tipo,...n.config?{config:n.config}:{}}});return t.length?t:void 0}var Po,rv,nv,Jm,Vm,iv,Ds=f(()=>{q();Wm();Po=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);rv=["texto","correo","telefono","codigo","url"],nv=["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;Vm=["kanban","calendario","linea","mapa","galeria","tablero","cuadrante","dia"],iv=new Set(["__proto__","constructor","prototype"])});var Xr,Gm=f(()=>{Xr=e=>e==="@contacts"||e==="@companies"});function Ni(e,o){if(e==null)return;if(!Array.isArray(e)||e.length>yi)throw i(`\xABrelacionadas\xBB: hasta ${yi} columnas.`);if(!e.length)return;let t=new Set;return e.map((n,r)=>{let a=`Columna relacionada ${r+1}`;if(!zs(n))throw i(`${a}: un objeto.`);Xm(n,["clave","etiqueta","via","campo","de","calculo","filtro","siVacio"],a);let s=Ot(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 c=Xr(String(n.de))&&typeof n.via=="string"&&/^datos\.[a-z][a-z0-9_]{0,40}$/.test(n.via)?n.via:Ot(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"&&Xr(n.de)?n.de:Ot(n.de,`${a}.de`);if(typeof n.calculo!="string"||!Hm.includes(n.calculo))throw i(`${a}: \xABcalculo\xBB, uno de ${Hm.join(", ")}.`);let p=n.calculo,m=p==="recuento"?void 0:Xr(u)&&typeof n.campo=="string"&&/^datos\.[a-z][a-z0-9_]{0,40}$/.test(n.campo)?n.campo:Ot(n.campo,`${a}.campo`),h=Yr(n.filtro,a,Xr(u));return{clave:s,etiqueta:n.etiqueta.trim(),via:c,de:u,calculo:p,...m?{campo:m}:{},...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===c&&!u.archivado);if(!d||d.tipo!=="relacion")throw i(`${a}: \xAB${c}\xBB no es una relaci\xF3n de este m\xF3dulo.`);if(d.multiple&&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:c,campo:n.campo,...n.siVacio!==void 0?{siVacio:Ot(n.siVacio,`${a}.siVacio`)}:{}}})}function $i(e){if(e==null)return;if(!Array.isArray(e)||e.length>_i)throw i(`\xABsiguientes\xBB: hasta ${_i} pasos.`);if(!e.length)return;let o=new Set;return e.map((t,n)=>{let r=`Siguiente paso ${n+1}`;if(!zs(t))throw i(`${r}: un objeto.`);Xm(t,["clave","nombre","destino","enlace","campos"],r);let a=Ot(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=Ot(t.enlace,`${r}.enlace`),c;if(t.campos!==void 0&&t.campos!==null){if(!zs(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(!Ls.test(d)||typeof u!="string"||!Ls.test(u))throw i(`${r}: \xABcampos.${d.slice(0,40)}\xBB no es v\xE1lido.`);c=t.campos}return{clave:a,nombre:t.nombre.trim(),destino:t.destino,enlace:s,...c&&Object.keys(c).length?{campos:c}:{}}})}var Hm,yi,_i,Ls,zs,Xm,Ot,xi=f(()=>{Gm();q();Kr();Hm=["recuento","suma","minimo","maximo","ultimo","media"],yi=20,_i=5,Ls=/^[a-z][a-z0-9_]{0,40}$/,zs=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Xm=(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.`)},Ot=(e,o)=>{if(typeof e!="string"||!Ls.test(e))throw i(`${o}: falta o no es v\xE1lido.`);return e}});function Fs(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,c]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"?vi(c,o):s==="impresion"?Hr(c,o):s==="relacionadas"?Ni(c,o):s==="recurso"?mi(c,o):s==="reserva"?fi(c,o):$i(c))??null})}t[n]=a}return t}var Km=f(()=>{As();q();Ds();xi()});function Zm(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,Bs=f(()=>{q();Ws=["etiqueta","ayuda","enTabla","obligatorio","visibleSi","obligatorioSi","permisos","siVacio","completarDesde"]});function ef(e,o,t={}){for(let[r,a]of Object.entries(t)){let s=e.find(u=>u.clave===r&&!u.archivado),c=o[r],d=s?.opciones??[];if(s?.tipo!=="seleccion"||!c||!Object.hasOwn(Vs,c)||Object.keys(a).length!==d.length||!d.length||d.some(u=>!Object.hasOwn(a,u.valor))||Object.values(a).some(u=>typeof u!="string"||!u||u!==u.trim())||new Set(Object.values(a)).size!==d.length)throw i("Las conversiones nativas necesitan un mapa de selecciones completo.")}let n=new Map;for(let r of e){let a=o[r.clave];if(r.archivado||r.tipo!=="seleccion"||!a||!Object.hasOwn(Vs,a))continue;let s=Vs[a];if(r.opciones?.some(c=>c.hecho||c.requisito||c.pide?.length||c.limiteDias!==void 0||c.aprobacion))throw i("Las opciones de Personas/Empresas no pueden perder reglas de etapas.");n.set(s,Wr(s,(r.opciones??[]).map(c=>({value:Object.hasOwn(t,r.clave)?t[r.clave][c.valor]:c.valor,label:c.etiqueta,...c.color?{color:c.color}:{}}))))}return n}var Vs,of=f(()=>{q();xs();Vs={sector:"companySectors",forma_juridica:"legalForms"}});function Js(e,o){if(e===void 0)return;if(!To(e))throw i("\xABpersonas\xBB: un objeto.");if(Us(e,["objeto","tipo","de","campoNif","etiqueta","plural","icono","campos","conversiones","alternativa","clasificacion","configuracion"],"\xABpersonas\xBB"),e.alternativa!==void 0||e.clasificacion!==void 0)return sv(e,o);if(e.objeto==="deals"&&o.some(m=>m.tipo==="autonumero"))throw i("Los auton\xFAmeros propios no est\xE1n disponibles en Oportunidades.");if(e.objeto==="deals"&&o.some(m=>m.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=Ci(e.tipo,"tipo",60);if(!av.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=Ci(e.icono,"icono",40);if(!/^[a-z0-9-]+$/.test(n))throw i("\xABpersonas.icono\xBB: una clave de icono.");if(!To(e.campos))throw i("\xABpersonas.campos\xBB: un mapa expl\xEDcito de campos nativos.");let r={},a=new Map;for(let[m,h]of Object.entries(e.campos)){let b=o.find(w=>w.clave===m&&!w.archivado),y=typeof h=="string"&&Object.hasOwn(rf[e.objeto],h)?rf[e.objeto][h]:void 0,v=Ee(h);if(!b||!(v?Sm.has(b.tipo):y?.includes(b.tipo)))throw i(`\xABpersonas.campos.${m.slice(0,40)}\xBB: campo nativo o tipo incompatible.`);if(b.unico&&typeof h=="string"&&h.startsWith("persona."))throw i("El campo propio necesita conservar sus reglas antes de convertir la ra\xEDz.");if(a.has(h)&&h!=="nif"&&h!=="tax_identifier")throw i(`\xABpersonas.campos\xBB: dos campos apuntan a \xAB${h}\xBB.`);a.set(h,m),r[m]=h}let s=e.objeto==="contacts"?"first_name":"name";if(!a.has(s))throw i(`\xABpersonas.campos\xBB: falta el nombre nativo \xAB${s}\xBB.`);let c=o.filter(m=>!m.archivado);for(let m of c)if(!Object.hasOwn(r,m.clave)&&m.tipo!=="resumen"&&m.tipo!=="formula")throw i(`\xABpersonas.campos\xBB: falta destino para \xAB${m.clave}\xBB; no se puede perder un campo.`);if(e.conversiones!==void 0&&!To(e.conversiones))throw i("Las conversiones nativas necesitan un mapa de selecciones completo.");let d={};for(let[m,h]of Object.entries(e.conversiones??{})){if(!To(h)||Object.values(h).some(b=>typeof b!="string"))throw i("Las conversiones nativas necesitan un mapa de selecciones completo.");Object.defineProperty(d,m,{value:{...h},enumerable:!0})}let u=e.campoNif;if(u!==void 0&&(e.objeto!=="contacts"||typeof u!="string"||!Object.hasOwn(r,u)||!r[u]?.startsWith("datos.")||!o.some(m=>m.clave===u&&["texto","codigo"].includes(m.tipo))))throw i("\xABpersonas.campoNif\xBB: elige un campo propio de texto de Personas.");af(o,r,t),ef(o,r,d);let p=Fs(e.configuracion,o);if(p&&Object.keys(p).some(m=>m!==e.objeto))throw i("La configuraci\xF3n cita un objeto que esta ra\xEDz no declara.");return{objeto:e.objeto,tipo:t,...typeof u=="string"?{campoNif:u}:{},...e.de?{de:e.de}:{},...p?{configuracion:p}:{},etiqueta:Ci(e.etiqueta,"etiqueta",60),plural:Ci(e.plural,"plural",60),icono:n,campos:r,...e.conversiones!==void 0?{conversiones:d}:{}}}function sv(e,o){let t=e.alternativa,n=e.clasificacion;if(e.objeto!=="contacts"||!To(t)||t.objeto!=="companies"||!To(t.campos)||!To(n))throw i("Los destinos dobles necesitan Persona, Empresa y clasificaci\xF3n expl\xEDcita.");Us(t,["objeto","campos","conversiones"],"\xABpersonas.alternativa\xBB"),Us(n,["campo","valores","vacio","formas","etiquetas","propiedad"],"\xABpersonas.clasificacion\xBB");let r=o.find(v=>v.clave===n.campo&&!v.archivado);if(!r||!["seleccion","booleano"].includes(r.tipo)||!To(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(v=>v.hecho||v.requisito||v.pide?.length||v.limiteDias!==void 0||v.aprobacion))throw i("La clasificaci\xF3n no puede perder permisos ni reglas de etapas.");let a=r.tipo==="booleano"?["true","false"]:(r.opciones??[]).map(v=>v.valor);if(!a.length||Object.keys(n.valores).length!==a.length||a.some(v=>!Object.hasOwn(n.valores,v))||Object.values(n.valores).some(v=>v!=="contacts"&&v!=="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=um(n,r,n.valores),c={campo:r.clave,valores:{...n.valores},...n.vacio?{vacio:n.vacio}:{},...s},{alternativa:d,clasificacion:u,configuracion:p,...m}=e,h=v=>Js(v,pm(o,c,v.objeto).filter(w=>To(v.campos)&&Object.hasOwn(v.campos,w.clave)||w.tipo==="resumen"||w.tipo==="formula")),b=h(m),y=h({...m,objeto:"companies",campoNif:void 0,campos:t.campos,conversiones:t.conversiones});if(c.propiedad){if(b.campos[r.clave]!==c.propiedad||y.campos[r.clave]!==c.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 v of o.filter(w=>!w.archivado&&w.clave!==r.clave&&w.tipo!=="resumen"&&w.tipo!=="formula"))if(!Object.hasOwn(b.campos,v.clave)&&!Object.hasOwn(y.campos,v.clave))throw i("Los destinos deben conservar todos los campos del origen salvo el discriminante.");return dm(o,c),{...b,alternativa:{objeto:"companies",campos:y.campos,...y.conversiones?{conversiones:y.conversiones}:{}},clasificacion:c,...e.configuracion!==void 0?{configuracion:Fs(e.configuracion,o)}:{}}}var tf,rf,To,av,Ci,Us,nf=f(()=>{Br();Om();Km();q();mm();of();tf={ubicacion:["ubicacion"],address:["texto","texto_largo"],zipcode:["texto","codigo"],city:["texto"],country:["texto"],pais_fiscal:["texto","seleccion"],iban:["texto"]},rf={contacts:{...tf,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:{...tf,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"]}},To=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),av=/^[a-z0-9][a-z0-9-]{0,59}$/,Ci=(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()},Us=(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.`)}});import{createContext as cv,Script as lv}from"node:vm";function ji(e,o){if(e!=null){if(!Array.isArray(e)||e.length>sf)throw i(`\xAB${o}\xBB: como mucho ${sf} 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(!uv.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(!dv(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 pf(e,o){if(!(e==null||e==="")){if(typeof e!="string"||e.length>cf)throw i(`\xAB${o}\xBB: el patr\xF3n, hasta ${cf} caracteres.`);if(/\\[1-9]|\\k<|\(\?<[=!]/.test(e))throw i(`\xAB${o}\xBB: el patr\xF3n no admite retroreferencias ni lookbehind.`);if(pv(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 pv(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),c=/^(?:[+*]|\{\d*,)/.test(s)||/^\{(\d+)\}/.test(s)&&Number(/^\{(\d+)\}/.exec(s)[1])>1;if(a&&c)return!0;o.length&&(a||c)&&(o[o.length-1]=!0);continue}(r==="+"||r==="*"||r==="?"||r==="{"||r==="|")&&o.length&&(o[o.length-1]=!0)}return!1}function mf(e,o){if(e==null)return;let t=e,n=t?.tipo;if(typeof t!="object"||!lf[n])throw i(`\xAB${o.etiqueta}\xBB: valor por defecto no v\xE1lido.`);if(!lf[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 uv,sf,cf,uf,df,lf,dv,uD,dD,ff=f(()=>{q();uv=["igual","distinto","vacio","lleno","uno_de"],sf=10,cf=200,uf=["texto","correo","telefono","url","codigo"],df=["texto","correo","telefono","url","codigo","numero","importe"],lf={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"]},dv=e=>typeof e=="string"&&e.length<=200||typeof e=="number"&&Number.isFinite(e)||typeof e=="boolean";uD=cv({p:"",v:""}),dD=new lv("new RegExp(p, 'u').test(v)")});function gf(e,o){if(e==null)return;if(!Array.isArray(e)||e.length>hf)throw i(`\xABvalidaciones\xBB: hasta ${hf}.`);let t=[];for(let[n,r]of e.entries()){if(!fv(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>no)throw i(`Validaci\xF3n ${n+1}: la f\xF3rmula, de 1 a ${no} 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=gi([...o,hv(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 hf,fv,hv,bf=f(()=>{q();bi();hf=20,fv=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),hv=(e,o)=>({clave:`validacion_${e}`,etiqueta:`Validaci\xF3n ${e+1}`,tipo:"formula",formula:o})});function yf(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(!vf(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"||!wf.test(e.campo))throw i(`${t}: \xBFde qu\xE9 campo depende?`);if(o.tipo==="seleccion"){if(!vf(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"||!wf.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 _f(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(c=>c.valor)),s=new Set((t.opciones??[]).map(c=>c.valor));for(let[c,d]of Object.entries(n.opciones??{})){if(!a.has(c))throw i(`\xAB${t.etiqueta}\xBB: \xAB${c.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 wf,vf,Nf=f(()=>{q();wf=/^[a-z][a-z0-9_]{0,39}$/,vf=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)});function xf(e,o){if(!Array.isArray(e)||e.length>300)throw i("Hasta 300 transiciones por campo.");let t=new Set(o.opciones?.map(r=>r.valor)),n=new Set;return e.map(r=>{if(!$f(r)||r.desde!==null&&!t.has(r.desde)||!t.has(r.hasta)||r.desde===r.hasta)throw i("El origen y el destino deben ser estados diferentes del campo; el origen vac\xEDo representa el alta.");let a=JSON.stringify([r.desde,r.hasta]);if(n.has(a))throw i("Transici\xF3n repetida.");n.add(a);let s={desde:r.desde,hasta:r.hasta};if(s.papeles=Qs(r.papeles,30,/^(titular|administrador|miembro|lectura|p_[a-z]{1,12})$/),s.pide=Qs(r.pide,30,/^[a-z][a-z0-9_]{0,40}$/),s.acciones=Qs(r.acciones,10),r.aprobacion!==void 0){let c=r.aprobacion;if(!$f(c)||c.papel!==void 0&&(typeof c.papel!="string"||!/^[a-z_]{1,40}$/.test(c.papel))||c.personas!==void 0&&(!Number.isInteger(c.personas)||Number(c.personas)<1||Number(c.personas)>10))throw i("Aprobaci\xF3n de transici\xF3n no v\xE1lida.");s.aprobacion={papel:c.papel,personas:c.personas}}return s})}function Cf(e){for(let o of e)for(let t of o.transiciones??[])for(let n of t.pide??[]){let r=e.find(a=>a.clave===n&&!a.archivado);if(!r||["formula","resumen","busqueda","subtabla","boton","autonumero","creado_el","creado_por","modificado_el","modificado_por"].includes(r.tipo))throw i("La guarda debe referirse a un campo editable del m\xF3dulo.")}return e}var $f,Qs,jf=f(()=>{q();$f=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Qs=(e,o,t)=>{if(e!==void 0){if(!Array.isArray(e)||e.length>o||e.some(n=>typeof n!="string"||!n.trim()||n.length>80||t&&!t.test(n)))throw i("Lista de transici\xF3n no v\xE1lida.");if(new Set(e).size!==e.length)throw i("La transici\xF3n contiene valores repetidos.");return e}}});function Sf(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 ND,Of=f(()=>{ci();q();ND=A`select a.*, m.clave,
|
|
19
19
|
(a.estado = 'pendiente' and crm_aprobacion_puede(a.papel, a.pedida_por, a.espacio_id, crm_yo(), a.autor)
|
|
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 df(e,o,t){if(e.requisito!==void 0&&e.requisito!==null){let n=e.requisito;if(!Dw(n)||typeof n.formula!="string"||!n.formula.trim()||n.formula.length>oo||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>uf||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 ${uf} campos.`);e.pide.length&&(o.pide=[...new Set(e.pide)])}if(cf(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 pf(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 c of r.pide??[]){let d=o.find(u=>u.clave===c);if(!d||["formula","resumen","busqueda","subtabla","boton","autonumero","creado_el","creado_por","modificado_el","modificado_por"].includes(d.tipo))throw i(`\xAB${t.etiqueta}\xBB, \xAB${r.etiqueta}\xBB: pide \xAB${c}\xBB, que no es un campo que se rellene.`)}if(!r.requisito)return r;let s;try{s=ci([...o,zw(t.clave,a,r.requisito.formula)]).at(-1)}catch(c){throw i(`\xAB${t.etiqueta}\xBB, \xAB${r.etiqueta}\xBB: ${c instanceof Error?c.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 uf,Dw,zw,mf=m(()=>{E();li();lf();uf=5,Dw=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),zw=(e,o,t)=>({clave:`etapa_${e}_${o}`,etiqueta:`Requisito ${o+1}`,tipo:"formula",formula:t})});function gf(e){if(e==null)return;if(!Array.isArray(e)||e.length>ff)throw i(`\xABconversiones\xBB: hasta ${ff}.`);let o=new Set,t=e.map((n,r)=>{let a=`Conversi\xF3n ${r+1}`;if(!vi(n))throw i(`${a}: un objeto.`);for(let c of Object.keys(n))if(!["clave","nombre","destino","campos","enlaceDestino","enlaceOrigen","lineas","etapa"].includes(c))throw i(`${a}: clave no admitida \xAB${c.slice(0,40)}\xBB.`);if(typeof n.clave!="string"||!St.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"||!(Fw.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:hf(n.campos,a)};for(let c of["enlaceDestino","enlaceOrigen"])if(!(n[c]===void 0||n[c]===null||n[c]==="")){if(typeof n[c]!="string"||!St.test(n[c]))throw i(`${a}: \xAB${c}\xBB no es un campo v\xE1lido.`);s[c]=n[c]}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(c=>{if(!vi(c)||typeof c.desde!="string"||!St.test(c.desde)||typeof c.a!="string"||!St.test(c.a))throw i(`${a}: cada \xABlineas\xBB, {desde, a, campos}.`);return{desde:c.desde,a:c.a,campos:hf(c.campos,a)}})}if(n.etapa!==void 0&&n.etapa!==null){if(!vi(n.etapa)||typeof n.etapa.campo!="string"||!St.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 ff,St,Fw,vi,hf,bf=m(()=>{E();ff=5,St=/^[a-z][a-z0-9_]{0,40}$/,Fw=["contacts","companies","deals"],vi=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),hf=(e,o)=>{if(e===void 0)return{};if(!vi(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(!St.test(t)||typeof n!="string"||!St.test(n))throw i(`${o}: el campo \xAB${t.slice(0,40)}\xBB no es v\xE1lido.`);return e}});function yf(e,o){if(e==null)return;if(!Array.isArray(e)||e.length>wf)throw i(`\xABencadenar\xBB: hasta ${wf}.`);let t=new Set,n=e.map((r,a)=>{let s=`\xABencadenar\xBB ${a+1}`;if(!Ot(r))throw i(`${s}: un objeto.`);for(let w of Object.keys(r))if(!["clave","nombre","destino","enlace","campos","lineas","estado","no_cuentan","permitir_exceso","juntar"].includes(w))throw i(`${s}: clave no admitida \xAB${w.slice(0,40)}\xBB.`);let c=Yo(r.clave,`${s}.clave`);if(t.has(c))throw i(`${s}: \xABclave\xBB repetida.`);if(c==="juntar")throw i(`${s}: \xABjuntar\xBB no vale como clave.`);if(t.add(c),typeof 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(!Ot(r.lineas))throw i(`${s}: \xABlineas\xBB {desde, a, cantidad: {origen, destino}}.`);let d=r.lineas,u=Yo(d.desde,`${s}.lineas.desde`),p=Bw(o,u);if(!p)throw i(`${s}: \xAB${u}\xBB no es una subtabla de este m\xF3dulo.`);if(!Ot(d.cantidad))throw i(`${s}: \xABlineas.cantidad\xBB {origen, destino}.`);let f=Yo(d.cantidad.origen,`${s}.lineas.cantidad.origen`),h=(p.columnas??[]).find(w=>w.clave===f&&!w.archivado);if(!h||!(Ww.includes(h.tipo)||h.tipo==="formula"&&h.origen?.tipo==="numero"))throw i(`${s}: la cantidad \xAB${f}\xBB tiene que ser una columna num\xE9rica de \xAB${u}\xBB.`);let b={clave:c,nombre:r.nombre.trim(),destino:r.destino,enlace:Yo(r.enlace,`${s}.enlace`),lineas:{desde:u,a:Yo(d.a,`${s}.lineas.a`),cantidad:{origen:f,destino:Yo(d.cantidad.destino,`${s}.lineas.cantidad.destino`)}}},y=vf(d.campos,`${s}.lineas.campos`);if(y){for(let w of Object.values(y))if(!(p.columnas??[]).some(_=>_.clave===w&&!_.archivado))throw i(`${s}: \xAB${w}\xBB no es una columna de \xAB${u}\xBB.`);b.lineas.campos=y}let v=vf(r.campos,`${s}.campos`);if(v){for(let w of Object.values(v))if(!o.some(_=>_.clave===w&&!_.archivado))throw i(`${s}: \xAB${w}\xBB no es un campo de este m\xF3dulo.`);b.campos=v}if(r.estado!==void 0&&r.estado!==null){let w=r.estado;if(!Ot(w))throw i(`${s}: \xABestado\xBB {campo, parcial, completo, pendiente?}.`);let _=o.find(S=>S.clave===w.campo&&S.tipo==="seleccion"&&!S.archivado);if(!_)throw i(`${s}: \xABestado.campo\xBB tiene que ser una selecci\xF3n de este m\xF3dulo.`);let C=new Set((_.opciones??[]).map(S=>S.valor));for(let S of["parcial","completo","pendiente"]){let P=w[S];if(!(P===void 0&&S==="pendiente")&&(typeof P!="string"||!C.has(P)))throw i(`${s}: \xABestado.${S}\xBB tiene que ser una opci\xF3n de \xAB${_.etiqueta}\xBB.`)}b.estado={campo:_.clave,parcial:w.parcial,completo:w.completo,...typeof w.pendiente=="string"?{pendiente:w.pendiente}:{}}}if(r.no_cuentan!==void 0&&r.no_cuentan!==null){let w=r.no_cuentan;if(!Ot(w)||!Array.isArray(w.valores)||w.valores.length>20||!w.valores.every(_=>typeof _=="string"&&_.length<=60))throw i(`${s}: \xABno_cuentan\xBB {campo, valores}.`);b.no_cuentan={campo:Yo(w.campo,`${s}.no_cuentan.campo`),valores:w.valores}}if(r.permitir_exceso===!0&&(b.permitir_exceso=!0),r.juntar!==void 0&&r.juntar!==null&&r.juntar!==!1){let w=r.juntar===!0?{}:r.juntar;if(!Ot(w))throw i(`${s}: \xABjuntar\xBB {iguales?, enlace_varios?}.`);for(let C of Object.keys(w))if(!["iguales","enlace_varios"].includes(C))throw i(`${s}: \xABjuntar\xBB: clave no admitida \xAB${C.slice(0,40)}\xBB.`);let _=w.iguales===void 0?[]:w.iguales;if(!Array.isArray(_)||_.length>10||!_.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={..._.length?{iguales:_}:{},...w.enlace_varios?{enlace_varios:Yo(w.enlace_varios,`${s}.juntar.enlace_varios`)}:{}}}return b});return n.length?n:void 0}var wf,Ts,Ww,Ot,vf,Yo,Bw,_f=m(()=>{E();wf=5,Ts=/^[a-z][a-z0-9_]{0,40}$/,Ww=["numero","importe","duracion","porcentaje"],Ot=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),vf=(e,o)=>{if(e!=null){if(!Ot(e)||Object.keys(e).length>60)throw i(`${o}: un objeto destino \u2192 origen.`);for(let[t,n]of Object.entries(e))if(!Ts.test(t)||typeof n!="string"||!Ts.test(n))throw i(`${o}: \xAB${t.slice(0,40)}\xBB no es v\xE1lido.`);return e}},Yo=(e,o)=>{if(typeof e!="string"||!Ts.test(e))throw i(`${o}: falta o no es v\xE1lido.`);return e},Bw=(e,o)=>e.find(t=>t.clave===o&&t.tipo==="subtabla"&&!t.archivado)});function xf(e){if(e==null)return;if(!Array.isArray(e)||e.length>Nf)throw i(`\xABplantillas_hijos\xBB: hasta ${Nf}.`);let o=new Set,t=e.map((n,r)=>{let a=`Plantilla de hijos ${r+1}`;if(!Ms(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"||!yi.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 c={clave:n.clave,nombre:n.nombre.trim(),cuando:s.map(d=>{if(!Ms(d)||typeof d.campo!="string"||!yi.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(!yi.test(n.subtabla))throw i(`${a}: \xABsubtabla\xBB no v\xE1lida.`);c.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"||!yi.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.`);c.modulo=n.modulo,c.via=n.via}if(!Array.isArray(n.registros)||!n.registros.length||n.registros.length>$f)throw i(`${a}: \xABregistros\xBB, de 1 a ${$f}.`);return c.registros=n.registros.map(d=>{if(!Ms(d)||JSON.stringify(d).length>4e3)throw i(`${a}: cada registro, un objeto (de hasta 4000 caracteres).`);return d}),c});return t.length?t:void 0}var Nf,$f,yi,Ms,Cf=m(()=>{E();Nf=10,$f=50,yi=/^[a-z][a-z0-9_]{0,40}$/,Ms=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)});function Sf(e,o){if(e==null)return;if(!ho(e))throw i("\xABpertenencia\xBB: un objeto.");let t=(n,r,a,s=!1)=>{let c=o.find(d=>d.clave===n&&!d.archivado);if(!c||!r.includes(c.tipo)||s&&c.multiple)throw i(`\xABpertenencia.${a}\xBB: ${r.join(" o ")}${s?" simple":""} de este m\xF3dulo.`);return c.clave};return{demanda:t(e.demanda,["relacion"],"demanda",!0),oferta:t(e.oferta,["relacion"],"oferta",!0),desde:t(e.desde,["fecha"],"desde"),...e.hasta?{hasta:t(e.hasta,["fecha"],"hasta")}:{},...e.correccion_dias!==void 0&&e.correccion_dias!==null?{correccion_dias:Vw(e.correccion_dias)}:{}}}function Of(e,o){if(e==null)return;if(!ho(e))throw i("\xABasignacion\xBB: un objeto.");if(typeof e.oferta!="string"||!Ni.test(e.oferta))throw i("\xABasignacion.oferta\xBB: la clave del m\xF3dulo de la oferta.");let t=e.destino,n;if(ho(t)&&t.forma==="pertenencia"&&typeof t.modulo=="string"&&Ni.test(t.modulo))n={forma:"pertenencia",modulo:t.modulo};else if(ho(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"||!Ni.test(e.cupo))throw i("\xABasignacion.cupo\xBB: un campo num\xE9rico de la oferta.");return{oferta:e.oferta,destino:n,...Jw({...e,cupo_fijo:void 0},o),cupo:e.cupo}}function Jw(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?jf:Ni,s=t&&e.cupo_fijo!==void 0;if(s?e.cupo!==void 0||!Number.isInteger(e.cupo_fijo)||Number(e.cupo_fijo)<1||Number(e.cupo_fijo)>1e4:typeof e.cupo!="string"||!a.test(e.cupo))throw i("\xABasignacion.cupo\xBB: un n\xFAmero de la oferta o un cupo fijo de 1 a 10000.");let c={...s?{cupo_fijo:Number(e.cupo_fijo)}:{cupo:e.cupo},filtros:[],puntos:[]};if(e.orden!==void 0&&e.orden!==null){let p=e.orden;if(!ho(p))throw i("\xABasignacion.orden\xBB: {campo, sentido}.");c.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(!ho(p)||typeof p.oferta!="string"||!a.test(p.oferta))throw i("\xABasignacion.plazas_por\xBB: {demanda (selecci\xF3n m\xFAltiple), oferta (su campo)}.");c.plazas_por={demanda:n(p.demanda,"\xABplazas_por.demanda\xBB",["seleccion_multiple","seleccion"]),oferta:p.oferta}}e.inicio&&(c.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>_i||u.length>_i)throw i(`\xABasignacion\xBB: hasta ${_i} filtros y ${_i} puntos.`);if(c.filtros=d.map((p,f)=>{let h=`Filtro ${f+1}`;if(!ho(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.`)}),c.puntos=u.map((p,f)=>{let h=`Punto ${f+1}`;if(!ho(p))throw i(`${h}: un objeto.`);switch(p.tipo){case"base":case"carga":return{tipo:p.tipo,peso:At(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:At(p.peso,h)};case"igual":case"contiene":return{tipo:p.tipo,demanda:n(p.demanda,`${h}, \xABdemanda\xBB`),oferta:r(p.oferta,h),peso:At(p.peso,h)};case"junto":{let b=o.find(v=>v.clave===p.relacion&&!v.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:At(p.misma,h),...ho(y)?{mismo_campo:{oferta:r(y.oferta,h),peso:At(y.peso,h)}}:{},...p.mismo_valor!==void 0?{mismo_valor:At(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:At(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(!ho(p))throw i("\xABasignacion.cercania\xBB: {demanda, oferta}.");c.cercania={demanda:n(p.demanda,"\xABcercania.demanda\xBB",["hora","numero","fecha","fecha_hora"]),oferta:r(p.oferta,"\xABcercania\xBB")}}return c}var ho,Ni,jf,_i,Vw,At,Uw,Af=m(()=>{E();ho=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Ni=/^[a-z][a-z0-9_]{0,40}$/,jf=/^[a-z][a-z0-9_]{0,40}(\.[a-z][a-z0-9_]{0,40})?$/,_i=20,Vw=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};At=(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"||!jf.test(e))throw i(`${o}: un campo de la oferta (\xABcampo\xBB o \xABrelacion.campo\xBB).`);return e}});function Ef(e,o){if(e==null)return;if(!$i(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(Gw.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 c=`Acci\xF3n p\xFAblica ${s+1}`;if(!$i(a)||typeof a.clave!="string"||!Qw.test(a.clave)||r.has(a.clave))throw i(`${c}: \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(`${c}: el texto del bot\xF3n (1\u201360).`);let d={clave:a.clave,etiqueta:a.etiqueta.trim(),...a.una_vez===!0?{una_vez:!0}:{}};if(a.campo!==void 0&&a.campo!==null&&a.campo!==""){let u=t(a.campo);if(u?.tipo==="seleccion"){let p=u.opciones?.find(f=>f.valor===a.valor);if(!p)throw i(`${c}: el valor tiene que ser una opci\xF3n de \xAB${u.etiqueta}\xBB.`);if(u.embudo&&(p.requisito||p.pide?.length||p.aprobacion))throw i(`${c}: \xAB${p.etiqueta}\xBB tiene requisito o aprobaci\xF3n: no se puede poner desde fuera.`)}else if(u?.tipo==="booleano"){if(typeof a.valor!="boolean")throw i(`${c}: el valor, s\xED o no.`)}else if(u?.tipo==="hecho"){if(a.valor!==!0)throw i(`${c}: un \xABhecho\xBB se marca (true).`)}else throw i(`${c}: el campo, una selecci\xF3n, un s\xED/no o un \xABhecho\xBB.`);d.campo=u.clave,d.valor=a.valor}if(a.lineas!==void 0&&a.lineas!==null){let u=a.lineas,p=$i(u)?t(u.subtabla):void 0,f=p?.tipo==="subtabla"?(p.columnas??[]).find(h=>h.clave===u.columna&&!h.archivado):void 0;if(f?.tipo!=="booleano")throw i(`${c}: \xABlineas\xBB, una subtabla del m\xF3dulo y una columna s\xED/no suya.`);if(!n.campos.includes(p.clave))throw i(`${c}: la subtabla de \xABlineas\xBB tiene que ense\xF1arse en la p\xE1gina.`);d.lineas={subtabla:p.clave,columna:f.clave}}if(a.firma!==void 0&&a.firma!==null&&a.firma!==!1){let u=a.firma===!0?{}:a.firma;if(!$i(u))throw i(`${c}: \xABfirma\xBB, {archivos}.`);for(let p of Object.keys(u))if(p!=="archivos")throw i(`${c}: \xABfirma\xBB, clave no admitida \xAB${p.slice(0,40)}\xBB.`);if(u.archivos!==void 0&&u.archivos!==null&&u.archivos!==""){if(t(u.archivos)?.tipo!=="archivos")throw i(`${c}: \xABfirma.archivos\xBB, un campo de archivos del m\xF3dulo (donde queda el firmado).`);d.firma={archivos:u.archivos}}else d.firma={}}if(!d.campo&&!d.lineas&&!d.firma)throw i(`${c}: un campo, unas l\xEDneas o la firma.`);return d}),n.acciones.filter(a=>a.firma).length>1)throw i("\xABpublico.acciones\xBB: solo una firma el documento.")}return n}var Qw,$i,Gw,qf=m(()=>{E();Qw=/^[a-z][a-z0-9_]{0,40}$/,$i=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Gw=["secreto","boton","firma"]});function Pf(e,o){if(fe(e))return;if(!go(e))throw i("\xABstock\xBB: un objeto {articulo?, ubicacion?, movimiento?}.");Ko(e,["articulo","ubicacion","movimiento","reponer"],"stock");let t=s=>o.find(c=>c.clave===s&&!c.archivado),n=(s,c,d,u)=>{let p=t(s);if(!p||!d(p))throw i(`\xABstock.${c}\xBB: ${u} de este m\xF3dulo.`);return p.clave},r=s=>s.tipo==="relacion"&&!s.multiple&&!!s.relacion?.startsWith("mod_"),a={};if(!fe(e.articulo)){let s=e.articulo;if(!go(s))throw i("\xABstock.articulo\xBB: un objeto.");Ko(s,["minimo","reponer","proveedor","permitir_negativo","lotes"],"stock.articulo");let c={};if(fe(s.minimo)||(c.minimo=n(s.minimo,"articulo.minimo",d=>d.tipo==="numero","un n\xFAmero")),fe(s.reponer)||(c.reponer=n(s.reponer,"articulo.reponer",d=>d.tipo==="numero","un n\xFAmero")),fe(s.proveedor)||(c.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)c.permitir_negativo=!0;else if(typeof s.permitir_negativo=="string"&&s.permitir_negativo)c.permitir_negativo=n(s.permitir_negativo,"articulo.permitir_negativo",d=>d.tipo==="booleano","un s\xED/no");else if(!fe(s.permitir_negativo)&&s.permitir_negativo!==!1)throw i("\xABstock.articulo.permitir_negativo\xBB: true o un s\xED/no del art\xEDculo.");if(!fe(s.lotes)){if(s.lotes!=="lote"&&s.lotes!=="serie")throw i("\xABstock.articulo.lotes\xBB: lote o serie.");if(c.permitir_negativo)throw i("\xABstock.articulo\xBB: con lotes o series no se admiten negativos.");c.lotes=s.lotes}a.articulo=c}if(!fe(e.ubicacion)){let s=e.ubicacion;if(!go(s))throw i("\xABstock.ubicacion\xBB: un objeto.");Ko(s,["almacen"],"stock.ubicacion"),a.ubicacion=fe(s.almacen)?{}:{almacen:n(s.almacen,"ubicacion.almacen",r,"una relaci\xF3n simple a otro m\xF3dulo")}}if(!fe(e.movimiento)){let s=e.movimiento;if(!go(s))throw i("\xABstock.movimiento\xBB: un objeto.");if(Ko(s,["tipo","lineas","ubicacion","ubicacion_destino","cuando"],"stock.movimiento"),!Rf.includes(s.tipo))throw i(`\xABstock.movimiento.tipo\xBB: ${Rf.join(", ")}.`);if(!go(s.lineas))throw i("\xABstock.movimiento.lineas\xBB: {subtabla, articulo, cantidad, ubicacion?, coste?}.");let c=s.lineas;Ko(c,["subtabla","articulo","cantidad","ubicacion","ubicacion_destino","coste","lote","caducidad"],"stock.movimiento.lineas");let d=t(c.subtabla);if(d?.tipo!=="subtabla")throw i("\xABstock.movimiento.lineas.subtabla\xBB: una subtabla de este m\xF3dulo.");let u=(d.columnas??[]).filter(v=>!v.archivado),p=(v,w,_,C)=>{let S=u.find(P=>P.clave===v);if(!S||!_(S))throw i(`\xABstock.movimiento.lineas.${w}\xBB: ${C} de \xAB${d.etiqueta}\xBB.`);return S.clave},f={tipo:s.tipo,lineas:{subtabla:d.clave,articulo:p(c.articulo,"articulo",r,"la columna de producto (una relaci\xF3n simple)"),cantidad:p(c.cantidad,"cantidad",v=>kf.includes(v.tipo),"una columna num\xE9rica")},cuando:{campo:"",valores:[]}};if(fe(c.ubicacion)||(f.lineas.ubicacion=p(c.ubicacion,"ubicacion",r,"una relaci\xF3n simple")),fe(c.coste)||(f.lineas.coste=p(c.coste,"coste",v=>kf.includes(v.tipo),"una columna num\xE9rica")),fe(c.lote)||(f.lineas.lote=p(c.lote,"lote",v=>v.tipo==="texto"||v.tipo==="codigo","una columna de texto")),fe(c.caducidad)||(f.lineas.caducidad=p(c.caducidad,"caducidad",v=>v.tipo==="fecha","una columna de fecha")),fe(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(fe(c.ubicacion_destino)||(f.lineas.ubicacion_destino=p(c.ubicacion_destino,"ubicacion_destino",r,"una relaci\xF3n simple")),fe(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(!go(s.cuando))throw i("\xABstock.movimiento.cuando\xBB: {campo, valor} o {campo, valores}.");Ko(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(v=>v.valor));if(!b.length||b.length>20||!b.every(v=>typeof v=="string"&&y.has(v)))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(!fe(e.reponer)){let s=e.reponer;if(!go(s))throw i("\xABstock.reponer\xBB: {destino, proveedor, lineas: {subtabla, articulo, cantidad}, estado?}.");if(Ko(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"||!Is.test(s.proveedor))throw i("\xABstock.reponer.proveedor\xBB: la relaci\xF3n de las compras al proveedor.");if(!go(s.lineas))throw i("\xABstock.reponer.lineas\xBB: {subtabla, articulo, cantidad}.");Ko(s.lineas,["subtabla","articulo","cantidad"],"stock.reponer.lineas");for(let d of["subtabla","articulo","cantidad"])if(typeof s.lineas[d]!="string"||!Is.test(s.lineas[d]))throw i(`\xABstock.reponer.lineas.${d}\xBB: falta o no es v\xE1lida.`);let c={destino:s.destino,proveedor:s.proveedor,lineas:{subtabla:s.lineas.subtabla,articulo:s.lineas.articulo,cantidad:s.lineas.cantidad}};if(!fe(s.estado)){if(!go(s.estado)||typeof s.estado.campo!="string"||typeof s.estado.valor!="string")throw i("\xABstock.reponer.estado\xBB: {campo, valor}.");c.estado={campo:s.estado.campo,valor:s.estado.valor}}if(!fe(s.en_camino)){let d=s.en_camino;if(!go(d)||typeof d.campo!="string"||!Is.test(d.campo)||!Array.isArray(d.valores)||!d.valores.length||d.valores.length>20||!d.valores.every(u=>typeof u=="string"&&u.length<=80))throw i("\xABstock.reponer.en_camino\xBB: {campo, valores} (los estados de la compra pedida y a\xFAn no recibida).");c.en_camino={campo:d.campo,valores:[...new Set(d.valores)]}}a.reponer=c}return Object.keys(a).length?a:void 0}var Rf,go,Ko,kf,fe,Is,Tf=m(()=>{E();Rf=["entrada","salida","ajuste","traspaso","recuento","reserva"],go=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Ko=(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.`)},kf=["numero","importe","duracion","porcentaje"],fe=e=>e==null||e==="";Is=/^[a-z][a-z0-9_]{0,40}$/});function Xw(e,o){let t=`liquidacion.reglas[${o}]`;if(!Zo(e))throw i(`\xAB${t}\xBB: un objeto.`);if(et(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(Et(e.si)||(n.si=Lf(e.si,`${t}.si`)),Et(e.tramos))n.valor=zs(e.valor,`${t}.valor`);else{let r=e.tramos;if(!Zo(r))throw i(`\xAB${t}.tramos\xBB: {por, lista}.`);if(et(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>If)throw i(`\xAB${t}.tramos.lista\xBB: de 1 a ${If} tramos {desde, valor}.`);let a=r.lista.map((s,c)=>{if(!Zo(s))throw i(`\xAB${t}.tramos.lista[${c}]\xBB: {desde, valor}.`);return et(s,["desde","valor"],`${t}.tramos.lista[${c}]`),{desde:zs(s.desde,`${t}.tramos.lista[${c}].desde`,0),valor:zs(s.valor,`${t}.tramos.lista[${c}].valor`)}}).sort((s,c)=>s.desde-c.desde);if(a[0].desde!==0)throw i(`\xAB${t}.tramos\xBB: el primer tramo empieza en 0.`);if(new Set(a.map(s=>s.desde)).size!==a.length)throw i(`\xAB${t}.tramos\xBB: dos tramos con el mismo \xABdesde\xBB.`);if(n.tramos={por:r.por,modo:r.modo==="alcanzado"?"alcanzado":"marginal",lista:a},!Et(e.valor))throw i(`\xAB${t}\xBB: con tramos, el valor va en cada tramo.`)}return n}function Df(e,o){if(Et(e))return;if(!Zo(e))throw i("\xABliquidacion\xBB: un objeto {origen, importe, fecha, agente, campos, estados, lineas, reglas}.");if(et(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":xi(e.agente,"liquidacion.agente"),n=_=>o.find(C=>C.clave===_&&!C.archivado),r=(_,C,S,P)=>{let Z=n(_);if(!Z||!S(Z))throw i(`\xABliquidacion.${C}\xBB: ${P} de este m\xF3dulo.`);return Z.clave},a=_=>_.tipo==="relacion"&&!_.multiple&&!!_.relacion?.startsWith("mod_"),s=_=>a(_)||_.tipo==="relacion"&&!_.multiple&&["contacts","companies"].includes(_.relacion??"");if(!Zo(e.campos))throw i("\xABliquidacion.campos\xBB: {agente?, periodo, estado, total}.");et(e.campos,["agente","periodo","estado","total"],"liquidacion.campos");let c={periodo:r(e.campos.periodo,"campos.periodo",_=>_.tipo==="texto","un texto"),estado:r(e.campos.estado,"campos.estado",_=>_.tipo==="seleccion","una selecci\xF3n"),total:r(e.campos.total,"campos.total",_=>Ds.includes(_.tipo),"un n\xFAmero o importe")};if(Et(e.campos.agente)||(c.agente=r(e.campos.agente,"campos.agente",s,"una relaci\xF3n simple")),t!=="_dueno"&&!c.agente)throw i("\xABliquidacion.campos.agente\xBB: con el agente en una relaci\xF3n del origen, la relaci\xF3n de aqu\xED al mismo m\xF3dulo.");let d=n(c.estado),u=new Set((d.opciones??[]).map(_=>_.valor));if(!Zo(e.estados))throw i("\xABliquidacion.estados\xBB: {borrador, aprobada, cerrada, pagada} con opciones de su selecci\xF3n.");et(e.estados,[...Ls],"liquidacion.estados");let p={};for(let _ of Ls){let C=e.estados[_];if(typeof C!="string"||!u.has(C))throw i(`\xABliquidacion.estados.${_}\xBB: una opci\xF3n de \xAB${d.etiqueta}\xBB.`);p[_]=C}if(new Set(Object.values(p)).size!==Ls.length)throw i("\xABliquidacion.estados\xBB: una opci\xF3n distinta para cada estado.");if(!Zo(e.lineas))throw i("\xABliquidacion.lineas\xBB: {subtabla, origen, base, comision, regla?}.");et(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(_=>!_.archivado),b=(_,C,S,P)=>{let Z=h.find(we=>we.clave===_);if(!Z||!S(Z))throw i(`\xABliquidacion.lineas.${C}\xBB: ${P} de \xAB${f.etiqueta}\xBB.`);return Z.clave},y={subtabla:f.clave,origen:b(e.lineas.origen,"origen",_=>a(_)&&_.relacion===e.origen,`la relaci\xF3n simple a ${String(e.origen)}`),base:b(e.lineas.base,"base",_=>Ds.includes(_.tipo),"una columna num\xE9rica"),comision:b(e.lineas.comision,"comision",_=>Ds.includes(_.tipo),"una columna num\xE9rica")};if(Et(e.lineas.regla)||(y.regla=b(e.lineas.regla,"regla",_=>_.tipo==="texto","una columna de texto")),!Array.isArray(e.reglas)||!e.reglas.length||e.reglas.length>Mf)throw i(`\xABliquidacion.reglas\xBB: de 1 a ${Mf}.`);let v=e.reglas.map(Xw),w={origen:e.origen,importe:xi(e.importe,"liquidacion.importe"),fecha:xi(e.fecha,"liquidacion.fecha"),agente:t,campos:c,estados:p,lineas:y,reglas:v};return Et(e.cuentan)||(w.cuentan=Lf(e.cuentan,"liquidacion.cuentan")),w}var Ls,Mf,If,Ds,Hw,Zo,Et,et,xi,Lf,zs,zf=m(()=>{E();Ls=["borrador","aprobada","cerrada","pagada"],Mf=20,If=20,Ds=["numero","importe","porcentaje"],Hw=/^[a-z][a-z0-9_]{0,40}$/,Zo=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Et=e=>e==null||e==="",et=(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.`)},xi=(e,o)=>{if(typeof e!="string"||!Hw.test(e))throw i(`\xAB${o}\xBB: falta o no es v\xE1lido.`);return e},Lf=(e,o)=>{if(!Zo(e))throw i(`\xAB${o}\xBB: {campo, valores}.`);if(et(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:xi(e.campo,`${o}.campo`),valores:[...new Set(e.valores)]}},zs=(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 Wf(e,o){if(Ff(e))return;if(!Fs(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 c=t(a);if(c?.tipo!=="fecha")throw i(`\xABcuota.${s}\xBB: una fecha de este m\xF3dulo.`);return c.clave},r={proxima:n(e.proxima,"proxima"),periodicidad:"mensual"};if(typeof e.periodicidad=="string"){if(!Hr.includes(e.periodicidad))throw i(`\xABcuota.periodicidad\xBB: ${Hr.join(", ")} (o {campo, valores}).`);r.periodicidad=e.periodicidad}else if(Fs(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(!Fs(a.valores)||!Object.keys(a.valores).length)throw i("\xABcuota.periodicidad.valores\xBB: {opci\xF3n: periodo}.");let c=new Set((s.opciones??[]).map(d=>d.valor));for(let[d,u]of Object.entries(a.valores)){if(!c.has(d))throw i(`\xABcuota.periodicidad.valores\xBB: \xAB${d.slice(0,40)}\xBB no es una opci\xF3n de \xAB${s.etiqueta}\xBB.`);if(!Hr.includes(u))throw i(`\xABcuota.periodicidad.valores.${d.slice(0,40)}\xBB: ${Hr.join(", ")}.`)}r.periodicidad={campo:s.clave,valores:a.valores}}else throw i(`\xABcuota.periodicidad\xBB: ${Hr.join(", ")} o {campo, valores}.`);if(!Ff(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 Hr,Fs,Ff,Bf=m(()=>{E();Hr=["semanal","quincenal","mensual","bimestral","trimestral","semestral","anual"],Fs=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Ff=e=>e==null||e===""});function Jf(e,o){if(e==null)return;if(!Uf(e))throw i("\xABpapel\xBB: {tipo, campos} o null.");let t=Object.keys(e).find(c=>c!=="tipo"&&c!=="campos"&&c!=="atributos");if(t)throw i(`\xABpapel\xBB: \xAB${t}\xBB no se reconoce.`);let n=typeof e.tipo=="string"?Ws[e.tipo]:void 0;if(!n||!Object.hasOwn(Ws,e.tipo))throw i(`\xABpapel.tipo\xBB: uno de ${Object.keys(Ws).join(", ")}.`);let r=e.campos??{};if(!Uf(r))throw i("\xABpapel.campos\xBB: {campo est\xE1ndar: clave del campo}.");let a={};for(let[c,d]of Object.entries(r)){let u=Object.hasOwn(n.campos,c)?n.campos[c]:void 0;if(!u)throw i(`\xABpapel.campos\xBB: \xAB${c}\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[c]=p.clave}for(let[c,d]of Object.entries(n.campos))if(d.obligatorio&&!a[c])throw i(`\xABpapel\xBB: falta el campo de ${d.etiqueta}.`);let s=Kw(n,e.atributos,o);return s?{tipo:e.tipo,campos:a,atributos:s}:{tipo:e.tipo,campos:a}}function Kw(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(c=>c.clave===a&&!c.archivado):void 0;if(!s)throw i(`\xABpapel.atributos\xBB: \xAB${String(a)}\xBB no es un campo vivo de este m\xF3dulo.`);if(!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 Vf,Yw,Ws,Uf,Qf=m(()=>{E();Vf={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"]}},Yw={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"]}},Ws={cerradura:{etiqueta:"Cerradura",campos:{nombre:{etiqueta:"Nombre",tipos:["texto"],obligatorio:!0},identificador:{etiqueta:"Identificador",tipos:["texto","codigo","numero","dispositivo"]},ubicacion:{etiqueta:"Ubicaci\xF3n",tipos:["texto"]}}},dispositivo:{etiqueta:"Dispositivo",campos:{nombre:{etiqueta:"Nombre",tipos:["texto"],obligatorio:!0},identificador:{etiqueta:"Identificador",tipos:["texto","codigo","dispositivo"]},canal:{etiqueta:"Canal",tipos:["numero"]}}},clientes:{etiqueta:"Clientes",campos:Vf},proveedores:{etiqueta:"Proveedores",campos:Vf},catalogo:{etiqueta:"Cat\xE1logo",campos:Yw,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"]}}}},Uf=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)});function Qr(e,o,t=!1){if(e!=null){if(!Array.isArray(e)||e.length>Hf)throw i(`${o}: el filtro, una lista de hasta ${Hf} 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"||!(We.test(s.campo)||t&&/^datos\.[a-z][a-z0-9_]{0,40}$/.test(s.campo)))throw i(`${a}: \xABcampo\xBB, la clave de un campo del m\xF3dulo que resume.`);if(typeof s.op!="string"||!Gf.includes(s.op))throw i(`${a}: \xABop\xBB, una de ${Gf.join(", ")}.`);let c=s.op;if(c==="vacio"||c==="no_vacio")return{campo:s.campo,op:c};let d=u=>typeof u=="string"&&u.length<=200||typeof u=="number"&&Number.isFinite(u)||typeof u=="boolean";if(c==="en"||c==="no_en"){if(!Array.isArray(s.valor)||!s.valor.length||s.valor.length>50||!s.valor.every(u=>d(u)&&typeof u!="boolean"))throw i(`${a}: \xAB${c}\xBB lleva una lista de valores (hasta 50).`);return{campo:s.campo,op:c,valor:s.valor}}if(!d(s.valor))throw i(`${a}: \xAB${c}\xBB lleva un valor (texto, n\xFAmero o s\xED/no).`);return{campo:s.campo,op:c,valor:s.valor}})}}function th(e,o=!1){if(typeof e=="string"&&(eh.has(e)||rv.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"||!oh.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 Qs(e,o,t=!1){if(typeof e!="object"||e===null||Array.isArray(e))throw i("Definici\xF3n no v\xE1lida.");let n=e,r=th(n.clave,t);if(!Array.isArray(n.campos))throw i("Faltan los campos.");let a=n.campos.map((s,c)=>rr(s,c,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 nh(e,o){if(typeof e!="object"||e===null||Array.isArray(e))throw i("Definici\xF3n no v\xE1lida.");let t=e,n=th(t.clave,o.interno===!0),r=ot(t.nombre,"el nombre",60),a=ot(t.nombre_plural??t.nombre,"el nombre en plural",60),s=ot(t.descripcion??"","la descripci\xF3n",500,!0),c=typeof t.icono=="string"&&Js.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=ih(Qs(t,o.modulosDelEspacio,o.interno),n,o.camposRelacion);if(u.filter(R=>!R.archivado&&R.opciones?.some(D=>D.hecho)).length>1)throw i("Solo una selecci\xF3n puede marcar estados como \xABhechos\xBB.");if(u.filter(R=>!R.archivado&&R.proximaAccion).length>1)throw i("Solo una fecha puede ser la de la pr\xF3xima acci\xF3n.");let p=new Set;for(let R of u){if(p.has(R.clave))throw i(`El campo \xAB${R.clave}\xBB est\xE1 repetido.`);p.add(R.clave)}let f=u.filter(R=>!R.archivado);for(let R of f)for(let D of ps(R)){let oe=f.find(Rt=>Rt.clave===D.relacion);if(!oe||oe.clave===R.clave||oe.tipo!=="relacion"||oe.multiple&&!R.multiple)throw i(`\xAB${R.etiqueta}\xBB: un origen m\xFAltiple necesita tambi\xE9n un destino m\xFAltiple.`)}if(Bp(f),f.length===0)throw i("El m\xF3dulo necesita al menos un campo.");for(let R of f.filter(D=>D.tipo==="busqueda")){let D=f.find(oe=>oe.clave===R.desde);if(!D||D.tipo!=="relacion")throw i(`\xAB${R.etiqueta}\xBB: tiene que salir de un campo de relaci\xF3n de este m\xF3dulo.`)}for(let R of f.filter(D=>D.tipo==="qr"&&D.destino==="campo"&&D.campo))if(!f.find(oe=>oe.clave===R.campo))throw i(`\xAB${R.etiqueta}\xBB: el campo \xAB${R.campo}\xBB no existe en este m\xF3dulo.`);if(f.length>o.topeCampos)throw new L(400,"tope_campos",`Como mucho ${o.topeCampos} campos por m\xF3dulo en tu plan.`,!0,{topePlan:{clave:"campos",tope:o.topeCampos,solicitado:f.length}});for(let R of o.anterior??[]){let D=u.find(oe=>oe.clave===R.clave);if(!D)throw i(`El campo \xAB${R.etiqueta}\xBB no se quita: se archiva.`);if(D.tipo!==R.tipo&&!dv(R.tipo,D.tipo))throw i(`\xAB${R.etiqueta}\xBB no puede pasar de ${R.tipo} a ${D.tipo}.`)}let h=t.articulo==="un"||t.articulo==="una"?t.articulo:null,b=di(t.ficha,u),y=Ur(t.impresion,u),v=Xm(t.validaciones,u.filter(R=>!R.archivado));of(u);for(let R of u){if(R.tipo!=="contador"||!R.alMarcar)continue;let D=u.find(oe=>oe.clave===R.alMarcar&&!oe.archivado);if(D?.tipo!=="booleano"&&D?.tipo!=="hecho")throw i(`\xAB${R.etiqueta}\xBB: \xABal marcar\xBB tiene que ser un s\xED/no o un \xABhecho\xBB de este m\xF3dulo.`)}let w=Om(t.vistas,u),_=gf(t.conversiones),C=yf(t.encadenar,u),S=xf(t.plantillas_hijos),P=lv(t.campo_ambito,u),Z=Ef(t.publico,u),we=ii(t.recurso,u),$=ai(t.reserva,u),M=Of(t.asignacion,u),g=Sf(t.pertenencia,u),x=Pf(t.stock,u),A=Df(t.liquidacion,u),k=Zp(t.sucesion),J=rm(t.liquidacion_v2,u);if(A&&J)throw i("Elige una versi\xF3n de liquidaci\xF3n por m\xF3dulo.");let F=Wf(t.cuota,u),G=im(t.precios,u),Je=fi(t.relacionadas,u),tt=hi(t.siguientes),rt=Jf(t.papel,u),H=ks(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 Qe=t.portal??void 0,Ce;if(t.portal_campos!==void 0&&t.portal_campos!==null){let R=t.portal_campos;if(!Qe)throw i("\xABportal_campos\xBB va con \xABportal\xBB.");if(typeof R!="object"||Array.isArray(R)||Object.keys(R).length>u.length)throw i("\xABportal_campos\xBB: clave del campo \u2192 rellenar, ver o no.");for(let[D,oe]of Object.entries(R)){if(!u.some(Rt=>Rt.clave===D))throw i(`\xABportal_campos\xBB: el m\xF3dulo no tiene el campo \xAB${D.slice(0,40)}\xBB.`);if(oe!=="rellenar"&&oe!=="ver"&&oe!=="no")throw i(`\xABportal_campos.${D.slice(0,40)}\xBB: rellenar, ver o no.`)}Ce={...R}}let De;if(t.funcionesNativas!==void 0){if(!t.funcionesNativas||typeof t.funcionesNativas!="object"||Array.isArray(t.funcionesNativas)||Object.entries(t.funcionesNativas).some(([R,D])=>!["relacionadas","siguientes"].includes(R)||!Array.isArray(D)||D.length>(R==="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:c,...d!==void 0?{color:d}:{},campos:af(pf(u)).map(R=>{if(R.tipo!=="busqueda")return R;let{origen:D,...oe}=R;return oe}),paginas:t.paginas===!0,...b?{ficha:b}:{},...y?{impresion:y}:{},...v?{validaciones:v}:{},...w?{vistas:w}:{},..._?{conversiones:_}:{},...C?{encadenar:C}:{},...S?{plantillas_hijos:S}:{},...P?{campo_ambito:P}:{},...Z?{publico:Z}:{},...we?{recurso:we}:{},...$?{reserva:$}:{},...M?{asignacion:M}:{},...g?{pertenencia:g}:{},...x?{stock:x}:{},...A?{liquidacion:A}:{},...k?{sucesion:k}:{},...J?{liquidacion_v2:J}:{},...F?{cuota:F}:{},...G?{precios:G}:{},...Je?{relacionadas:Je}:{},...tt?{siguientes:tt}:{},...rt?{papel:rt}:{},...H?{personas:H}:{},...Qe?{portal:Qe}:{},...Ce&&Object.keys(Ce).length?{portal_campos:Ce}:{},...De?{funcionesNativas:De}:{}}}function lv(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 rr(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(r.destinos!==void 0){if(r.tipo!=="relacion"||r.multiple===!0||r.camposVinculo!==void 0||!Array.isArray(r.destinos)||!r.destinos.length||r.destinos.length>8||r.destinos.some(y=>typeof y!="string")||new Set(r.destinos).size!==r.destinos.length)throw i("La relaci\xF3n polim\xF3rfica necesita entre 1 y 8 destinos distintos y un solo registro.");let{destinos:u,relacion:p,multiple:f,alBorrar:h,...b}=r;return rr({...b,tipo:"subtabla",polimorfica:!0,columnas:u.map(y=>({clave:`a_${y}`,etiqueta:y,tipo:"relacion",relacion:y,alBorrar:h}))},o,t,n)}if(r.camposVinculo!==void 0){if(r.tipo!=="relacion"||r.multiple!==!0||!Array.isArray(r.camposVinculo)||!r.camposVinculo.length||r.camposVinculo.length>=Bs)throw i("Los datos del v\xEDnculo necesitan una relaci\xF3n m\xFAltiple y entre 1 y 29 campos.");let{camposVinculo:u,relacion:p,tipoContacto:f,alBorrar:h,multiple:b,...y}=r;return rr({...y,tipo:"subtabla",vinculo:!0,columnas:[{clave:"destino",etiqueta:r.etiqueta,tipo:"relacion",relacion:p,tipoContacto:f,alBorrar:h,obligatorio:!0},...u]},o,t,n)}if(typeof r.clave=="string"&&eh.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"||!We.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(!Vs.includes(a))throw i(`Tipo de campo no v\xE1lido: ${String(r.tipo)}.`);let s={clave:r.clave,etiqueta:ot(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=Pm(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];rr(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>oo||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}if(r.archivado===!0&&(s.archivado=!0),r.seccion!==void 0&&r.seccion!==""&&(s.seccion=ot(r.seccion,"la secci\xF3n",60)),r.ayuda!==void 0&&r.ayuda!==""&&(s.ayuda=ot(r.ayuda,"la ayuda",200)),(a==="fecha"||a==="fecha_hora")&&r.proximaAccion===!0&&(s.proximaAccion=!0),a==="numero"&&r.sinMiles===!0&&(s.sinMiles=!0),r.pasoMinutos!==void 0&&r.pasoMinutos!==null){let u=r.pasoMinutos;if(a!=="hora"||typeof u!="number"||!Number.isInteger(u)||u<1||u>60||60%u!==0)throw i(`\xAB${s.etiqueta}\xBB: el paso de la hora, en minutos que dividan la hora (1, 5, 10, 15, 30 o 60).`);u>1&&(s.pasoMinutos=u)}if(r.puertaExtra!==void 0&&typeof r.puertaExtra!="boolean")throw i("\xABpuertaExtra\xBB debe ser s\xED o no.");a==="dispositivo"&&r.conector==="ttlock"&&r.puertaExtra===!0&&(s.puertaExtra=!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(r.transiciones!==void 0&&a!=="seleccion")throw i("Las transiciones requieren una selecci\xF3n.");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;if(s.opciones=r.opciones.map(p=>{let f=typeof p=="string"?{valor:p,etiqueta:p}:p,h=ot(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:ot(f.etiqueta??h,"una opci\xF3n",80)};return typeof f.color=="string"&&nv.test(f.color)&&(b.color=f.color),a==="seleccion"&&f.hecho===!0&&(b.hecho=!0),a==="seleccion"&&r.embudo===!0&&df(f,b,s.etiqueta),b}),a==="seleccion"&&r.embudo===!0&&(s.embudo=!0),r.transiciones!==void 0){if(a!=="seleccion")throw i("Las transiciones requieren una selecci\xF3n.");s.transiciones=nf(r.transiciones,s)}}if(a==="relacion"){let u=r.relacion;if(!(typeof u=="string"&&(ev.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"||!pv.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"||!We.test(u.relacion)||typeof u.campo!="string"||!/^[a-z][a-z0-9_.]{0,80}$/.test(u.campo))throw i(`\xAB${s.etiqueta}\xBB: completarDesde requiere relacion y campo.`);let p;if(u.alternativa!==void 0){let f=u.alternativa;if(!f||typeof f!="object"||Array.isArray(f)||Object.keys(f).some(h=>h!=="relacion"&&h!=="campo")||typeof f.relacion!="string"||!We.test(f.relacion)||typeof f.campo!="string"||!/^[a-z][a-z0-9_.]{0,80}$/.test(f.campo))throw i("La alternativa de autocompletado necesita relacion y campo.");p={relacion:f.relacion,campo:f.campo}}s.completarDesde={relacion:u.relacion,campo:u.campo,...p?{alternativa:p}:{}}}if(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=rr({...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(!We.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"||!We.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"||!We.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(!Zw.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(Zf.includes(a)&&delete s.obligatorio,a==="subtabla"){if(!Array.isArray(r.columnas)||r.columnas.length===0||r.columnas.length>Bs)throw i(`\xAB${s.etiqueta}\xBB: entre 1 y ${Bs} columnas.`);let u=new Set(["padre"]);if(s.columnas=r.columnas.map((h,b)=>{let y=rr(h,b,t,n);if(!cv.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"&&1+rh(y)>Yf)throw i(`\xAB${s.etiqueta}\xBB: como mucho ${Yf} niveles de subtablas (cap\xEDtulo \u2192 subcap\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}),r.vinculo!==void 0){if(r.vinculo!==!0)throw i("\xABvinculo\xBB debe ser true.");let h=s.columnas[0];if(h?.clave!=="destino"||h.tipo!=="relacion"||h.multiple||h.archivado||!h.obligatorio||s.columnas.slice(1).some(b=>["relacion","subtabla","resumen","formula"].includes(b.tipo)))throw i("El v\xEDnculo necesita primero una relaci\xF3n obligatoria \xABdestino\xBB y despu\xE9s sus campos de datos.");s.vinculo=!0}if(r.polimorfica!==void 0){if(r.polimorfica!==!0||r.vinculo||s.columnas.length>8||s.columnas.some(h=>h.tipo!=="relacion"||h.multiple||h.obligatorio||h.archivado)||new Set(s.columnas.map(h=>h.relacion)).size!==s.columnas.length)throw i("La relaci\xF3n polim\xF3rfica lleva hasta ocho columnas de relaci\xF3n simple opcionales y distintas.");s.polimorfica=!0}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 v=`\xAB${s.etiqueta}\xBB, columna \xAB${h.etiqueta}\xBB`;if(h.tipo!=="relacion")throw i(`${v}: \xABcopiar\xBB va en una columna de relaci\xF3n.`);if(typeof y!="object"||Array.isArray(y)||Object.keys(y).length>Xf)throw i(`${v}: \xABcopiar\xBB, un objeto columna \u2192 campo (hasta ${Xf}).`);for(let[w,_]of Object.entries(y)){let C=s.columnas.find(S=>S.clave===w);if(!C||C.tipo==="relacion"||C.tipo==="formula")throw i(`${v}: \xAB${w.slice(0,40)}\xBB no es una columna que se pueda rellenar.`);if(typeof _!="string"||!We.test(_))throw i(`${v}: el campo de \xAB${w}\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 v=`\xAB${s.etiqueta}\xBB, columna \xAB${h.etiqueta}\xBB`;if(h.tipo!=="articulo")throw i(`${v}: \xABrellenar\xBB va en una columna de art\xEDculo.`);if(typeof y!="object"||Array.isArray(y)||Object.keys(y).length>Kf.length*2)throw i(`${v}: \xABrellenar\xBB, un objeto columna \u2192 dato del art\xEDculo.`);for(let[w,_]of Object.entries(y)){let C=s.columnas.find(S=>S.clave===w);if(!C||["relacion","articulo","formula","subtabla","resumen"].includes(C.tipo))throw i(`${v}: \xAB${w.slice(0,40)}\xBB no es una columna que se pueda rellenar.`);if(!Kf.includes(_))throw i(`${v}: \xAB${w.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"&&sv.test(r.hijo)&&(s.hijo=r.hijo);let f=jm(r.impresion,s.columnas);f&&(s.impresion=f),delete s.obligatorio}if(a==="autonumero"){let u=wi(r.visibleSi,s.etiqueta);u&&(s.visibleSi=u)}if(!Rm({tipo:a})){let u=wi(r.visibleSi,s.etiqueta);u&&(s.visibleSi=u);let p=wi(r.obligatorioSi,s.etiqueta);if(p&&(s.obligatorioSi=p),r.patron!==void 0&&r.patron!==null&&r.patron!==""){if(!Vm.includes(a))throw i(`\xAB${s.etiqueta}\xBB: un patr\xF3n solo vale para textos, correos, tel\xE9fonos, webs y c\xF3digos.`);let h=Jm(r.patron,s.etiqueta);h&&(s.patron=h)}if(r.unico===!0){if(!Um.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=Qm(r.porDefecto,s);f&&(s.porDefecto=f)}let c=sh(r.permisos,s.etiqueta);if(c&&(s.permisos=c),r.grupo!==void 0&&r.grupo!==null&&r.grupo!==""){if(typeof r.grupo!="string"||!iv.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(!av.includes(a))throw i(`\xAB${s.etiqueta}\xBB: solo se enmascaran textos, correos, tel\xE9fonos y c\xF3digos.`);s.enmascarado=!0}let d=ef(r.depende,s);if(d&&(s.depende=d),a==="archivo"&&(s.enTabla=!1,delete s.obligatorio),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>oo)throw i(`\xAB${s.etiqueta}\xBB: escribe la f\xF3rmula (hasta ${oo} caracteres).`);s.formula=r.formula.trim(),delete s.obligatorio}if(a==="resumen"){let u=r.calculo;if(typeof r.de!="string"||!oh.test(r.de)||typeof r.via!="string"||!We.test(r.via)||!Us.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"||!We.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"||!We.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=Qr(r.filtro,`\xAB${s.etiqueta}\xBB`);p?s.filtro=p:delete s.filtro,delete s.obligatorio}if(a==="dispositivo"){if(!ov.includes(r.conector))throw i(`\xAB${s.etiqueta}\xBB: elige de qu\xE9 conexi\xF3n es el aparato (TTLock o Shelly).`);s.conector=r.conector}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"||!We.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 Vs,Zf,Us,Gf,Hf,Zw,ev,ov,tv,eh,rv,Js,We,oh,nv,iv,av,ot,sv,cv,Xf,Yf,rh,Kf,Bs,uv,dv,pv,Rm,Gr=m(()=>{em();nm();am();Dm();Es();Vp();E();li();Gm();ch();Cs();Ym();tf();sf();mf();bf();_f();Cf();qf();gs();Af();Tf();zf();Bf();gi();Qf();ah();Vs=["texto","texto_largo","numero","importe","fecha","fecha_hora","booleano","seleccion","seleccion_multiple","etiquetas","url","correo","telefono","relacion","archivos","archivo","busqueda","resumen","duracion","hecho","porcentaje","valoracion","contador","cronometro","secreto","color","ubicacion","checklist","codigo","firma","hora","articulo","dispositivo","creado_el","creado_por","modificado_el","modificado_por","autonumero","formula","subtabla","boton","qr"],Zf=["creado_el","creado_por","modificado_el","modificado_por","autonumero"],Us=["recuento","suma","minimo","maximo","ultimo","media","media_ponderada"],Gf=["igual","distinto","en","no_en","vacio","no_vacio","mayor","menor"],Hf=5;Zw=["avisar","desvincular","impedir"],ev=["companies","contacts","deals"],ov=["ttlock","shelly"],tv=["id","numero","sales_id","creado","actualizado","espacio_id","modulo_id","datos"],eh=new Set([...tv,"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"]),rv=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"]),Js=["box","boxes","package","folder","folder-open","file-text","clipboard-list","list-checks","calendar","calendar-days","clock","map-pin","truck","car","wrench","hammer","hard-hat","building","home","store","warehouse","factory","briefcase","shopping-cart","receipt","wallet","credit-card","piggy-bank","tag","tags","star","heart","flag","bookmark","user","users","graduation-cap","stethoscope","pill","utensils","coffee","shirt","camera","image","monitor","smartphone","server","database","key","shield","leaf","paw-print","dumbbell","ticket","gift","megaphone","mail","phone","message-square"],We=/^[a-z][a-z0-9_]{0,40}$/,oh=/^[a-z][a-z_]{1,30}$/,nv=/^#[0-9a-fA-F]{6}$/,iv=/^[a-z][a-z_]{0,29}$/,av=["texto","correo","telefono","codigo"],ot=(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};sv=/^sub_[a-z]{8}$/,cv=["texto","texto_largo","numero","importe","fecha","fecha_hora","booleano","seleccion","url","correo","telefono","duracion","porcentaje","valoracion","color","codigo","formula","hora","relacion","articulo","subtabla","resumen"],Xf=20,Yf=3,rh=e=>e.tipo!=="subtabla"?0:1+Math.max(0,...(e.columnas??[]).map(o=>rh(o))),Kf=["nombre","referencia","codigo","precio","iva_pct"],Bs=30;uv=[["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"],["texto","dispositivo"],["dispositivo","texto"]],dv=(e,o)=>uv.some(([t,n])=>t===e&&n===o),pv=/^[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"||e.tipo==="archivo"||Zf.includes(e.tipo)});function lh(e){let o=Mo(),t=(e==="contacts"?mv:fv).map(([n,r])=>({clave:n,etiqueta:io(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",...hv(e).has(n)?{}:{permisos:{administrador:"lectura",miembro:"lectura",lectura:"lectura"}}}));return{id:0,clave:`@${e}`,nombre:io(o,e==="contacts"?"Persona":"Empresa"),nombre_plural:io(o,e==="contacts"?"Personas":"Empresas"),descripcion:"",icono:e==="contacts"?"users":"building-2",estado:"publicado",campos:t}}var Ci,mv,fv,hv,uh=m(()=>{an();Ci=[["address","Direcci\xF3n"],["zipcode","C\xF3digo postal"],["city","Ciudad"],["country","Pa\xEDs"]],mv=[["first_name","Nombre"],["last_name","Apellidos"],["title","Cargo"],["correo","Correo"],["telefono","Tel\xE9fono"],...Ci,["background","Contexto"],["nif","Identificador fiscal"],["pais_fiscal","Pa\xEDs fiscal"]],fv=[["name","Nombre"],["phone_number","Tel\xE9fono"],["website","Web"],...Ci,["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"]],hv=e=>new Set(e==="contacts"?["first_name","last_name","title","telefono",...Ci.map(([o])=>o),"background"]:["name","phone_number","website",...Ci.map(([o])=>o),"description","persona_first_name"])});function Br(e){let o=new Map(Wr(e)?lh(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=(Hp.find(a=>a.clave===e)?.campos??[]).map(a=>({...a,...o.has(a.clave)?{etiqueta:o.get(a.clave)}:Object.hasOwn(t,a.clave)?{etiqueta:io(Mo(),t[a.clave])}:{}})),r=Wr(e)?vv(e).map(a=>({...a,etiqueta:io(Mo(),a.etiqueta),editable:!1,ordenable:!1,filtrable:!1,enTabla:!1})):[];return[...n,...r,...e==="companies"?bv.map(a=>({...a,etiqueta:io(Mo(),a.etiqueta),editable:!1,ordenable:!1,filtrable:!1,enTabla:!1})):[]]}var Wr,gv,bv,wv,vv,ui=m(()=>{Xp();uh();an();Wr=e=>e==="contacts"||e==="companies",gv=[{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"}],bv=[{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"}],wv=[{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"}],vv=e=>[...gv.filter(o=>e==="contacts"||["nombre","direccion"].includes(o.clave)),...e==="companies"?wv:[]]});function ih(e,o,t){let n=(a,s,c,d)=>{if(a.tipo!=="busqueda"||a.archivado)return a;let u=`${c}.${a.clave}`;if(d.length>=2||d.includes(u))throw i(`\xAB${a.etiqueta}\xBB: solo se encadena una b\xFAsqueda a un nivel.`);let p=s.find(b=>b.clave===a.desde&&!b.archivado&&b.tipo==="relacion");if(!p?.relacion)return a;let f=p.relacion,h;if(f.startsWith("mod_")){let b=f.slice(4),y=b===o?e:t?.get(b);if(!y)return a;if(h=y.find(v=>v.clave===a.campo&&!v.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=Br(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 yv(r),r}function yv(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 ah=m(()=>{Dr();E();ui()});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 zm(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.transiciones||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 c=r.tipo==="busqueda"?Ee(o[r.desde??""]):null,d=r.siVacio?Ee(o[r.siVacio]):null;if(r.tipo==="busqueda"&&(!c||r.siVacio&&!d))throw i("La b\xFAsqueda propia necesita relaciones y alternativas propias de la misma ra\xEDz.");return{...structuredClone(r),...c?{desde:c}:{},...d?{siVacio:d}:{},clave:Ee(o[r.clave]),visibleSi:s,...r.obligatorioSi?{obligatorioSi:r.obligatorioSi.map(n)}:{}}})}var Dr=m(()=>{E()});function sh(e,o){if(e==null)return;if(typeof e!="object"||Array.isArray(e))throw new L(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(!$v(n))throw new L(400,"peticion_invalida",`\xAB${o}\xBB: el papel \xAB${n.slice(0,30)}\xBB no se puede restringir.`);if(!_v.includes(r))throw new L(400,"peticion_invalida",`\xAB${o}\xBB: nivel de permiso no v\xE1lido.`);t[n]=r}return Object.keys(t).length?t:void 0}var _v,Nv,$v,UL,Gs,JL,ch=m(()=>{oi();E();_v=["oculto","lectura"],Nv=["administrador","miembro","lectura"],$v=e=>Nv.includes(e)||/^p_[a-z]{1,12}$/.test(e),UL=O`coalesce(current_setting('app.extension', true), '') <> ''`,Gs=class extends Map{get(){return"no"}},JL=new Gs});function um(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"&&xv.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"&&Cv.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 xv,Cv,dm=m(()=>{E();xv=/^mod_[a-z][a-z0-9_]{0,40}$/,Cv=/^[a-z0-9][a-z0-9-]{0,59}$/});var Hs,dh=m(()=>{Hs=["nada","recientes","vistas"]});function ph(e,o,t){if(e===void 0)return[];if(!Array.isArray(e)||e.length>o.length)throw i("Fuentes de m\xF3dulo no v\xE1lidas.");let n=new Set;return e.map(r=>{if(!Xs(r)||typeof r.modulo!="string"||n.has(r.modulo)||typeof r.conexion!="string"||!t.some(d=>d.clave===r.conexion&&d.tipo==="api")||typeof r.operacion!="string"||!/^[a-zA-Z][a-zA-Z0-9_.-]{0,79}$/.test(r.operacion)||r.filas!==""&&!ji(r.filas)||!Xs(r.mapeo))throw i("La fuente necesita un m\xF3dulo, una conexi\xF3n API, una operaci\xF3n y un mapeo.");let a=o.find(d=>d.clave===r.modulo),s=Object.entries(r.mapeo);if(!a||a.personas||!s.length||s.some(([d,u])=>!a.campos.some(p=>p.clave===d&&Sv(p))||!ji(u)))throw i("La fuente debe mapear campos de datos de un m\xF3dulo propio.");n.add(r.modulo);let c={modulo:r.modulo,conexion:r.conexion,operacion:r.operacion,filas:r.filas,mapeo:Object.fromEntries(s)};if(r.modo==="vivo")return{...c,modo:r.modo};if(r.modo!=="espejo"||typeof r.minutos!="number"||!Number.isInteger(r.minutos)||r.minutos<5||r.minutos>10080||!ji(r.id_externo)||!Xs(r.cursor)||!ji(r.cursor.ruta)||typeof r.cursor.parametro!="string"||!/^[a-zA-Z_][a-zA-Z0-9_.-]{0,79}$/.test(r.cursor.parametro))throw i("El espejo necesita una clave externa, un cursor y un intervalo entre 5 minutos y 7 d\xEDas.");return{...c,modo:r.modo,minutos:r.minutos,id_externo:r.id_externo,cursor:{ruta:r.cursor.ruta,parametro:r.cursor.parametro}}})}var jv,ji,Xs,Sv,mh=m(()=>{E();jv=new Set(["texto","texto_largo","correo","telefono","codigo","numero","importe","fecha","fecha_hora","booleano","seleccion"]),ji=e=>typeof e=="string"&&e.length<=160&&/^[a-zA-Z_][a-zA-Z0-9_-]*(\.[a-zA-Z_][a-zA-Z0-9_-]*){0,7}$/.test(e),Xs=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Sv=e=>!e.archivado&&jv.has(e.tipo)});function fh(e){if(e===void 0)return[];if(!Array.isArray(e)||e.length>20)throw i("La soluci\xF3n admite hasta 20 conexiones.");let o=new Set;return e.map(t=>{if(!Ov(t)||typeof t.clave!="string"||!/^[a-z][a-z0-9_]{0,39}$/.test(t.clave)||["constructor","prototype"].includes(t.clave)||o.has(t.clave)||typeof t.nombre!="string"||!t.nombre.trim()||t.nombre.length>120||t.tipo!=="api"&&t.tipo!=="mcp")throw i("Requisito de conexi\xF3n no v\xE1lido.");return o.add(t.clave),{clave:t.clave,nombre:t.nombre.trim(),tipo:t.tipo}})}var Ov,hh=m(()=>{E();Ov=e=>!!e&&typeof e=="object"&&!Array.isArray(e)});function Si(e){return typeof e=="number"?Number.isInteger(e)&&e>=1&&e<=2147483647:typeof e=="string"&&e.length<=120&&gh.test(e)}function bh(e,o){let t=c=>gh.exec(typeof c=="number"?`${c}.0.0`:c),n=t(e),r=t(o);for(let c=1;c<=3;c++){let d=BigInt(n[c])-BigInt(r[c]);if(d)return d>0?1:-1}if(!n[4]||!r[4])return+!n[4]-+!r[4];let a=n[4].split("."),s=r[4].split(".");for(let c=0;c<Math.min(a.length,s.length);c++){let d=a[c],u=s[c];if(d===u)continue;let p=/^\d+$/.test(d),f=/^\d+$/.test(u);return p&&f?BigInt(d)>BigInt(u)?1:-1:p!==f?p?-1:1:d>u?1:-1}return a.length-s.length}var gh,Ys=m(()=>{gh=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][\da-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][\da-zA-Z-]*))*))?(?:\+([\da-zA-Z-]+(?:\.[\da-zA-Z-]+)*))?$/});function wh(e,o){if(e===void 0)return;if(!Ks(e)||Object.keys(e).some(r=>r!=="desde"&&r!=="pasos")||!Si(e.desde)||bh(e.desde,o)>=0||!Array.isArray(e.pasos)||!e.pasos.length||e.pasos.length>50)throw i("La migraci\xF3n necesita una versi\xF3n anterior y entre 1 y 50 pasos.");let t=new Set,n=e.pasos.map(r=>{if(!Ks(r)||Object.keys(r).some(f=>!["tipo","modulo","origen","destino","conversion","equivalencias"].includes(f))||r.tipo!=="renombrar"&&r.tipo!=="convertir"&&r.tipo!=="mover"||!Zs(r.modulo)||!Zs(r.origen)||!Zs(r.destino))throw i("Paso de migraci\xF3n inv\xE1lido.");let{tipo:a,modulo:s,origen:c,destino:d,conversion:u,equivalencias:p}=r;if(a==="convertir"&&(typeof u!="string"||!Av.has(u)))throw i("Conversi\xF3n de migraci\xF3n desconocida.");if(a!=="convertir"&&(u!==void 0||c===d))throw i("El paso necesita dos campos distintos.");if(u==="seleccion"?!Ks(p)||!Object.keys(p).length||Object.values(p).some(f=>typeof f!="string"||!f):p!==void 0)throw i("La conversi\xF3n a selecci\xF3n necesita una tabla de equivalencias.");for(let f of new Set([c,d])){let h=`${s}:${f}`;if(t.has(h))throw i("Cada campo puede participar en un solo paso por versi\xF3n.");t.add(h)}return{tipo:a,modulo:s,origen:c,destino:d,...u?{conversion:u}:{},...p?{equivalencias:p}:{}}});return{desde:e.desde,pasos:n}}var Ks,Zs,Av,vh=m(()=>{E();Ys();Ks=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Zs=e=>typeof e=="string"&&/^[a-z][a-z0-9_]{0,59}$/.test(e),Av=new Set(["numero","seleccion","fecha"])});function yh(e){let o=nr(e,["version","origen","entidades"]);if(o.version!==1)throw i("Perfil relacional inv\xE1lido.");let t=Xr(o.entidades,60).map(r=>{let a=nr(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(nr(a.campos)).map(([b,y])=>(ec(b),[b,ir(y)])));if(Object.keys(s).length>100)throw i("Perfil relacional inv\xE1lido.");let c=Xr(a.referencias??[],30).map(b=>{let y=nr(b,["campo","entidad","clave","obligatoria"]);if(y.obligatoria!==void 0&&typeof y.obligatoria!="boolean")throw i("Perfil relacional inv\xE1lido.");return{campo:ec(y.campo),entidad:Oi(y.entidad),clave:oc(y.clave),obligatoria:y.obligatoria===!0}}),d=a.archivos===void 0?void 0:Xr(a.archivos,20).map(b=>{let y=nr(b,["campo","columna","obligatorio"]);if(y.obligatorio!==void 0&&typeof y.obligatorio!="boolean")throw i("Perfil relacional inv\xE1lido.");return{campo:ec(y.campo),columna:ir(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),...c.map(b=>b.campo)];if(new Set(u).size!==u.length)throw i("Perfil relacional inv\xE1lido.");let p=a.procedencia===void 0?void 0:Object.fromEntries(Object.entries(nr(a.procedencia,["autor","creado","actualizado"])).map(([b,y])=>[b,ir(y)])),f=a.responsable===void 0?void 0:oc(a.responsable),h=a.tipos===void 0?void 0:Xr(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:Oi(a.clave),...a.acl!==void 0?{acl:ir(a.acl)}:{},...d?{archivos:d}:{},destino:a.destino,...p?{procedencia:p}:{},...f?{responsable:f}:{},...h?{tipos:h}:{},...a.tiposColumna!==void 0?{tiposColumna:ir(a.tiposColumna)}:{},clave_externa:oc(a.clave_externa),campos:s,referencias:c}}),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:Oi(o.origen),entidades:t}}var Oi,ec,ir,nr,Xr,oc,_h=m(()=>{E();Oi=e=>{if(typeof e!="string"||!/^[a-z][a-z0-9_]{0,60}$/.test(e))throw i("Perfil relacional inv\xE1lido.");return e},ec=e=>{let o=typeof e=="string"&&/^datos\.[a-z][a-z0-9_]{0,60}$/.test(e)?e:Oi(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},ir=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},nr=(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},Xr=(e,o)=>{if(!Array.isArray(e)||e.length>o)throw i("Perfil relacional inv\xE1lido.");return e},oc=e=>{let o=Xr(e,3).map(ir);if(!o.length||new Set(o).size!==o.length)throw i("Perfil relacional inv\xE1lido.");return o}});function Nh(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:yh(n.perfil)}})}var $h=m(()=>{E();_h()});function xh(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 Ch=m(()=>{E()});function jh(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)||!Us.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.");Qr(o.filtro,"Resumen")}var Sh=m(()=>{E();Gr()});function Oh(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 Ah=m(()=>{E()});var Eh,qh=m(()=>{Eh=/^funciones\.[a-z0-9][a-z0-9-]{0,59}\.[a-z][a-z0-9_]{0,40}$/});function ar(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(!Po(t)||Object.keys(t).some(r=>!["fuente","filtro","campos"].includes(r))||typeof t.fuente!="string"||!qv.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&&(!Po(t.filtro)||JSON.stringify(t.filtro).length>4e3))throw i("Filtro de origen no v\xE1lido.");if(!Po(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(!Ev.test(r)||["id","objeto"].includes(r)||!Po(a)||Object.keys(a).some(c=>!["resumen","formula","permiso","casos","defecto","campo","soloFiltro","valor","alternativas","conversiones","condicion","equivalencias","etiqueta","opciones"].includes(c))||["campo","valor","alternativas","condicion","casos","resumen","formula"].filter(c=>Object.hasOwn(a,c)).length!==1||a.campo!==void 0&&(typeof a.campo!="string"||a.campo.length>125)||Object.hasOwn(a,"valor")&&a.valor!==null&&!["string","number","boolean"].includes(typeof a.valor)||a.alternativas!==void 0&&(!Array.isArray(a.alternativas)||a.alternativas.length!==2||a.alternativas.some(c=>typeof c!="string"||c.length>125))||a.condicion!==void 0&&(!Po(a.condicion)||JSON.stringify(a.condicion).length>4e3)||a.conversiones!==void 0&&(!Po(a.conversiones)||!Array.isArray(a.alternativas)||Object.entries(a.conversiones).some(([c,d])=>!a.alternativas.includes(c)||!Po(d)||Object.keys(d).length>100||Object.values(d).some(u=>typeof u!="string")))||a.permiso!==void 0&&(typeof a.permiso!="string"||!Eh.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&&(!Po(a.opciones)||Object.keys(a.opciones).length>100||Object.values(a.opciones).some(c=>typeof c!="string"))||a.equivalencias!==void 0&&(!Po(a.equivalencias)||!a.campo||Object.keys(a.equivalencias).length>100||Object.values(a.equivalencias).some(c=>typeof c!="string")))throw i("Campo de proyecci\xF3n no v\xE1lido.");a.resumen!==void 0&&jh(a.resumen);let s=a.formula===void 0?void 0:xh(a.formula);if(a.casos!==void 0)Oh(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 Po,Ev,qv,Ai=m(()=>{Ch();Sh();Ah();E();qh();Po=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Ev=/^[a-z][a-z0-9_]{0,40}$/,qv=/^(contacts|companies|deals|mod_(?!sub_)[a-z][a-z0-9_]{0,40})$/});function Rh(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 kh=m(()=>{E()});function Th(e){let o=xe(e,"definici\xF3n");Be(o,["titulo","fuente","origenes","metrica","agrupar","dividir","filtro","periodo","grafico","top","comparar","meta"],"definici\xF3n");let t=Ie(o.fuente,"fuente",60),n=ar(o.origenes);if(t==="combinada"!=!!n)throw i("La fuente combinada necesita sus or\xEDgenes.");if(t!=="combinada"&&!rc.includes(t)&&!/^mod_(?!sub_)[a-z][a-z0-9_]{0,40}$/.test(t))throw i("\xABfuente\xBB no v\xE1lida.");let r=xe(o.metrica,"metrica");Be(r,["tipo","campo","por","filtro_a","filtro_b"],"metrica");let a=to(r.tipo,tc,"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:xe(r.filtro_a,"metrica.filtro_a")}:{},...r.filtro_b!==void 0&&r.filtro_b!==null?{filtro_b:xe(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 c;if(o.agrupar!==void 0&&o.agrupar!==null){let w=xe(o.agrupar,"agrupar");Be(w,["campo","paso"],"agrupar"),c={campo:Ie(w.campo,"agrupar.campo",60),...w.paso!==void 0?{paso:to(w.paso,sr,"agrupar.paso")}:{}}}let d;if(o.dividir!==void 0&&o.dividir!==null){let w=xe(o.dividir,"dividir");Be(w,["campo","paso"],"dividir"),d={campo:Ie(w.campo,"dividir.campo",60),...w.paso!==void 0?{paso:to(w.paso,sr,"dividir.paso")}:{}}}if(d&&!c)throw i("\xABDividir por\xBB solo se puede usar si se agrupa.");if(c&&d&&c.campo===d.campo)throw i("No se puede agrupar y dividir por el mismo campo.");let u;if(o.meta!==void 0&&o.meta!==null){if(typeof o.meta!="number"||Number.isNaN(o.meta)||o.meta<=0)throw i("\xABmeta\xBB: n\xFAmero mayor que 0.");u=o.meta}let p=o.periodo!==void 0&&o.periodo!==null?nc(o.periodo):void 0,f=to(o.grafico,Rv,"grafico"),h=["numero","medidor","numero_tendencia"],b=["barras","barras_horizontales","lineas","area","dona","tabla","embudo","tarta","radar","dispersion"],y=["barras_apiladas","barras_agrupadas","varias_lineas","tabla_dinamica","mapa_calor","combinado"];if(h.includes(f)){if(c)throw i("Un n\xFAmero no se agrupa.");if(d)throw i("Un n\xFAmero no se divide.");if(f==="medidor"&&u===void 0)throw i("El medidor necesita una \xABmeta\xBB num\xE9rica.");if(f==="numero_tendencia"&&(!p||!o.comparar))throw i("\xABnumero_tendencia\xBB necesita un periodo con comparaci\xF3n.")}else if(b.includes(f)){if(!c)throw i("Ese gr\xE1fico necesita \xABagrupar\xBB.");if(d)throw i("Ese gr\xE1fico no admite \xABdividir por\xBB.")}else if(y.includes(f)){if(!c)throw i("Ese gr\xE1fico necesita \xABagrupar\xBB.");if(!d)throw i("Ese gr\xE1fico necesita \xABdividir por\xBB un segundo campo.")}if(o.top!==void 0&&(!Number.isSafeInteger(o.top)||o.top<1||o.top>Ph))throw i(`\xABtop\xBB: de 1 a ${Ph}.`);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 v=o.filtro===void 0||o.filtro===null?void 0:xe(o.filtro,"filtro");if(v&&JSON.stringify(v).length>4e3)throw i("\xABfiltro\xBB demasiado grande.");return{titulo:Ie(o.titulo??"","titulo"),fuente:t,...n?{origenes:n}:{},metrica:s,...c?{agrupar:c}:{},...d?{dividir:d}:{},...u!==void 0?{meta:u}:{},...v?{filtro:v}:{},...p?{periodo:p}:{},grafico:f,...o.top!==void 0?{top:o.top}:{},...o.comparar?{comparar:!0}:{}}}function nc(e){let o=xe(e,"periodo");Be(o,["campo","ultimos","proximos","preset","desde","hasta"],"periodo");let t={campo:Ie(o.campo,"periodo.campo",60)};if(o.preset!==void 0&&(t.preset=to(o.preset,kv,"periodo.preset")),o.ultimos!==void 0){let r=xe(o.ultimos,"periodo.ultimos");if(Be(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:to(r.unidad,sr,"periodo.ultimos.unidad")}}for(let r of["desde","hasta"])if(o[r]!==void 0){if(typeof o[r]!="string"||!Pv.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=xe(o.proximos,"periodo.proximos");if(Be(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:to(r.unidad,sr,"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 tc,Rv,sr,rc,kv,Ph,Pv,xe,Be,to,Ie,ic=m(()=>{Ai();E();tc=["recuento","suma","media","min","max","minimo","maximo","mediana","porcentaje_total","acumulado","tasa_conversion","media_por","valor_medio_por"],Rv=["numero","barras","lineas","dona","tabla","barras_horizontales","barras_apiladas","barras_agrupadas","area","varias_lineas","embudo","medidor","numero_tendencia","tabla_dinamica","mapa_calor","tarta","radar","dispersion","combinado"],sr=["dia","semana","mes","anio"],rc=["companies","contacts","deals"],kv=["hoy","semana","mes","trimestre","anio"],Ph=50,Pv=/^\d{4}-\d{2}-\d{2}$/,xe=(e,o)=>{if(typeof e!="object"||e===null||Array.isArray(e))throw i(`\xAB${o}\xBB tiene que ser un objeto.`);return e},Be=(e,o,t)=>{for(let n of Object.keys(e))if(!o.includes(n))throw i(`\xAB${t}\xBB: clave no admitida \xAB${n.slice(0,40)}\xBB.`)},to=(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 zh(e,o){if(e===null)return null;if(!To(e))throw i("La disposici\xF3n no es v\xE1lida.");if(!Lv.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(!To(e.zonas))throw Dh();let t=e.zonas,n=To(e.widgets)?e.widgets:{};for(let d of Object.keys(t))if(!Mh.includes(d))throw i("Zona no v\xE1lida.");let r={},a=new Set;for(let d of Mh){let u=t[d]??[];if(!Array.isArray(u))throw i("Zona no v\xE1lida.");r[d]=u.map(p=>{if(typeof p!="string"||p!==ac&&!Iv.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(ac))throw Dh();if(r.arriba.length>Lh)throw i(`Arriba caben como mucho ${Lh} bloques.`);let s={};for(let[d,u]of Object.entries(n)){if(!a.has(d))continue;if(!To(u))throw i("Widget no v\xE1lido.");let p=Th(u.definicion);if(u.via!==void 0&&(typeof u.via!="string"||!Dv.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!==ac&&!s[d])throw i("Falta la definici\xF3n de un widget.");if(Object.keys(s).length>Ih)throw i(`Como mucho ${Ih} widgets por vista.`);let c={zonas:r,widgets:s};if(JSON.stringify(c).length>6e4)throw i("La disposici\xF3n es demasiado grande.");return c}function zv(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 Fh(e){if(!To(e))throw i("La vista no es v\xE1lida.");let o=To(e.pref)?Object.fromEntries(Object.entries(e.pref).filter(([d])=>Tv.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&&!Mv.has(String(o.vista)))throw i("El tipo de vista no es v\xE1lido.");let t=To(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(To(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:ar(e.origenes),a;if(r||e.columnasCalculadas!==void 0){if(!r||r.length!==1||!["contacts","companies"].includes(r[0].fuente)||!To(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=zv(e.ambito),c={pref:o,filtros:t,orden:n,...s?{ambito:s}:{},...r?{origenes:r,columnasCalculadas:a}:{}};if(JSON.stringify(c).length>3e4)throw i("La vista es demasiado grande.");return c}var Tv,Mv,Mh,ac,Iv,Ih,Lh,Lv,Dv,Dh,To,Wh=m(()=>{Ai();E();ic();Tv=new Set(["vistaOrigen","vista","visibles","orden","anchos","fijadas","calculos","agrupar","grupo","vistas","separar"]),Mv=new Set(["tabla","lista","kanban","calendario","galeria","linea","mapa"]),Mh=["arriba","izquierda","centro","derecha","abajo"],ac="tabla",Iv=/^w_[a-z0-9]{1,24}$/,Ih=24,Lh=6,Lv=/^(contacts|companies|deals|mod_(?!sub_)[a-z][a-z0-9_]{1,40})$/,Dv=/^[a-z][a-z0-9_]{0,59}$/,Dh=()=>new L(400,"tabla_obligatoria","La tabla no se puede quitar de la vista: mu\xE9vela, pero d\xE9jala.");To=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)});function Bh(e){let o=new Set,t=n=>{typeof n=="string"&&n.startsWith("mod_")&&o.add(n.slice(4))};if(sc(e.personas)&&t(e.personas.modulo),Array.isArray(e.secciones)){for(let n of e.secciones)if(sc(n)&&(t(n.modulo),Array.isArray(n.camino)))for(let r of n.camino)sc(r)&&t(r.modulo)}return o}var sc,Vh=m(()=>{sc=e=>!!e&&typeof e=="object"&&!Array.isArray(e)});function Bv(e){if(typeof e!="string"||!Wv.test(e))throw i("\xABrecurso\xBB: contacts, companies, deals o mod_<clave>.");return e}function Vv(e){if(!Fv.includes(e))throw i("\xABcanal\xBB: whatsapp o correo.");return e}function Uh(e,o="Plantilla"){if(!e||typeof e!="object"||Array.isArray(e))throw i(`${o}: un objeto.`);let t=e;for(let s of Object.keys(t))if(!["recurso","tipoContacto","canal","nombre","asunto","texto"].includes(s))throw i(`${o}: clave no admitida \xAB${s.slice(0,40)}\xBB.`);let n=Bv(t.recurso);if(t.tipoContacto!==void 0&&t.tipoContacto!==null&&(!Wr(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=Vv(t.canal),a=r==="correo"?cc(t.asunto,`${o}, asunto`,300,!1):void 0;return{recurso:n,...t.tipoContacto?{tipoContacto:t.tipoContacto}:{},canal:r,nombre:cc(t.nombre,`${o}, nombre`,80),...a?{asunto:a}:{},texto:cc(t.texto,`${o}, texto`,5e3)}}var Fv,Ei,Wv,cc,lc=m(()=>{ui();E();Fv=["whatsapp","correo"],Ei=50,Wv=/^(contacts|companies|deals|mod_(?!sub_)[a-z][a-z0-9_]{0,40})$/,cc=(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()}});function Gh(e){let o=xe(e,"informe");Be(o,["fuente","origenes","filtro","periodo","columnas","agrupar","agregados","orden"],"informe");let t=Ie(o.fuente,"fuente",60),n=ar(o.origenes);if(t==="combinada"!=!!n)throw i("La fuente combinada necesita sus or\xEDgenes.");if(t!=="combinada"&&!rc.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=xe(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=nc(o.periodo)),o.columnas!==void 0&&o.columnas!==null){if(!Array.isArray(o.columnas)||o.columnas.length>Jh)throw i(`\xABcolumnas\xBB: una lista de hasta ${Jh}.`);r.columnas=[...new Set(o.columnas.map((a,s)=>Ie(a,`columnas[${s}]`,60)))]}if(o.agrupar!==void 0&&o.agrupar!==null){let a=xe(o.agrupar,"agrupar");Be(a,["campo","paso"],"agrupar"),r.agrupar={campo:Ie(a.campo,"agrupar.campo",60),...a.paso!==void 0?{paso:to(a.paso,sr,"agrupar.paso")}:{}}}if(o.agregados!==void 0&&o.agregados!==null){if(!Array.isArray(o.agregados)||o.agregados.length>Qh)throw i(`\xABagregados\xBB: una lista de hasta ${Qh}.`);r.agregados=o.agregados.map((a,s)=>{let c=xe(a,`agregados[${s}]`);Be(c,["tipo","campo"],`agregados[${s}]`);let d=to(c.tipo,tc,`agregados[${s}].tipo`);if(d!=="recuento"&&c.campo===void 0)throw i(`\xABagregados[${s}]\xBB: esa operaci\xF3n necesita un campo.`);return{tipo:d,...d!=="recuento"?{campo:Ie(c.campo,`agregados[${s}].campo`,60)}:{}}})}if(r.agrupar&&!r.agregados?.length&&(r.agregados=[{tipo:"recuento"}]),o.orden!==void 0&&o.orden!==null){let a=xe(o.orden,"orden");Be(a,["por","sentido"],"orden"),r.orden={por:Ie(a.por,"orden.por",60),sentido:to(a.sentido??"asc",["asc","desc"],"orden.sentido")}}return r}var Jh,Qh,Hh=m(()=>{Ai();E();ic();Jh=30,Qh=6});var uc,Uv,Xh,Yh=m(()=>{uc=[{clave:"leo",nombre:"Leo",puesto:"Marketing"},{clave:"marina",nombre:"Marina",puesto:"Administrativa"},{clave:"dario",nombre:"Dar\xEDo",puesto:"Comercial"},{clave:"nora",nombre:"Nora",puesto:"Finanzas"},{clave:"irene",nombre:"Irene",puesto:"Consultora de procesos"}],Uv=e=>`pix.agente_${e}`,Xh=e=>uc.some(o=>Uv(o.clave)===e)});var Kh,Zh=m(()=>{Kh=["contacts","companies","deals","tareas","proyectos"]});function eg(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 og(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:eg(n.nombre,"pix.personalidad.nombre",Qv),instrucciones:eg(n.instrucciones,"pix.personalidad.instrucciones",Jv)}}}var Jv,Qv,tg=m(()=>{E();Jv=2e3,Qv=60});function rg(e,o){if(e===void 0)return[];if(!Array.isArray(e)||e.length>Yr)throw i(`\xABinformes\xBB: una lista de hasta ${Yr}.`);let t=new Set;return e.map((n,r)=>{if(!Gv(n))throw i(`Informe ${r+1}: un objeto.`);for(let c of Object.keys(n))if(!["nombre","descripcion","definicion"].includes(c))throw i(`Informe ${r+1}: clave no admitida \xAB${c.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=Gh(n.definicion);if([s.fuente,...s.origenes?.map(c=>c.fuente)??[]].some(c=>c.startsWith("mod_")&&!o.includes(c.slice(4))))throw i(`Informe \xAB${a}\xBB: su fuente no es un m\xF3dulo de la soluci\xF3n.`);return{nombre:a,...n.descripcion?{descripcion:n.descripcion}:{},definicion:s}})}var Yr,Gv,dc=m(()=>{E();Hh();Yr=30,Gv=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)});var ng,bo,cr,lr,ee,pc,ur,hz,Hv,qi,Xv,Yv,gz,bz,ig=m(()=>{Yh();ng={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"]},bo=["si","no","suyos"],cr=["si","no","suyos","equipo","jerarquia"],lr=["si","no","suyos","jerarquia"],ee=["si","no"],pc=(e,o,t=!0)=>[{clave:`${e}.ver`,descripcion:`Ver ${o}`,valores:lr},{clave:`${e}.crear`,descripcion:`Dar de alta ${o}`,valores:lr},{clave:`${e}.editar`,descripcion:`Editar ${o}`,valores:lr},{clave:`${e}.reasignar`,descripcion:`Cambiar el responsable de ${o}`,valores:lr},...t?[{clave:`${e}.estado`,descripcion:`Cambiar el estado de ${o}`,valores:lr}]:[],{clave:`${e}.descargar`,descripcion:`Bajar los ficheros de ${o}`,valores:ee},{clave:`${e}.borrar`,descripcion:`Borrar ${o}`,valores:lr},{clave:`${e}.exportar`,descripcion:`Exportar ${o}`,valores:bo},{clave:`${e}.importar`,descripcion:`Importar ${o} desde una hoja`,valores:ee}],ur=[...pc("contactos","contactos"),...pc("empresas","empresas",!1),...pc("oportunidades","oportunidades"),{clave:"proyectos.ver",descripcion:"Ver proyectos",valores:cr},{clave:"proyectos.editar",descripcion:"Editar los datos del proyecto",valores:cr},{clave:"proyectos.borrar",descripcion:"Borrar proyectos",valores:cr},{clave:"proyectos.exportar",descripcion:"Exportar proyectos",valores:bo},{clave:"proyectos.crear",descripcion:"Crear proyectos",valores:ee},{clave:"proyectos.gestionar",descripcion:"Cambiar el estado, el responsable, los participantes, las columnas y los ajustes de los proyectos, y gestionar plantillas",valores:ee},{clave:"tareas.ver",descripcion:"Ver tareas",valores:cr},{clave:"tareas.crear",descripcion:"Crear tareas",valores:ee},{clave:"tareas.editar",descripcion:"Editar y completar tareas",valores:cr},{clave:"tareas.borrar",descripcion:"Borrar tareas",valores:cr},{clave:"tareas.exportar",descripcion:"Exportar tareas visibles",valores:bo},{clave:"notas.ver",descripcion:"Ver notas",valores:bo},{clave:"notas.editar",descripcion:"Escribir, editar y borrar notas",valores:bo},{clave:"adjuntos.ver",descripcion:"Ver y descargar adjuntos",valores:bo},{clave:"adjuntos.subir",descripcion:"Subir adjuntos",valores:bo},{clave:"miembros.gestionar",descripcion:"Invitar, cambiar el papel y desactivar miembros",valores:ee},{clave:"conectores.accionar",descripcion:"Ejecutar acciones f\xEDsicas de conectores",valores:ee},{clave:"configuracion.gestionar",descripcion:"Cambiar la configuraci\xF3n del espacio y los permisos",valores:ee},{clave:"formularios.gestionar",descripcion:"Crear, editar y borrar formularios (y sus respuestas)",valores:ee},{clave:"formularios.ver_respuestas",descripcion:"Ver las respuestas de los formularios",valores:bo},{clave:"modulos.configurar",descripcion:"Dise\xF1ar, publicar y archivar m\xF3dulos",valores:ee},{clave:"paneles.ver",descripcion:"Ver los paneles de m\xE9tricas",valores:ee},{clave:"paneles.editar",descripcion:"Crear, cambiar y borrar paneles de m\xE9tricas",valores:ee},{clave:"paneles.compartir",descripcion:"Compartir paneles con el equipo y cambiar o borrar los de equipo",valores:ee},{clave:"automatizaciones.gestionar",descripcion:"Crear y cambiar automatizaciones, y ver sus ejecuciones",valores:ee},{clave:"campanas.gestionar",descripcion:"Crear y enviar campa\xF1as de correo, y gestionar consentimientos y supresiones",valores:ee},{clave:"agenda.ver",descripcion:"Ver las citas de la agenda",valores:bo},{clave:"agenda.editar",descripcion:"Crear, mover y cancelar citas",valores:bo},{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:ee},{clave:"analisis.ver",descripcion:"Usar An\xE1lisis: informes de lo que ya puede ver",valores:ee},{clave:"analisis.compartir",descripcion:"Compartir informes con el equipo y cambiar o borrar los de equipo",valores:ee},{clave:"secretos.ver",descripcion:"Ver los campos secretos (cada vez queda registrado qui\xE9n lo vio)",valores:ee},{clave:"liquidaciones.gestionar",descripcion:"Generar, aprobar, cerrar, pagar y reabrir liquidaciones de comisiones",valores:ee},{clave:"portales.gestionar",descripcion:"Configurar los portales, invitar a ellos y revocar el acceso",valores:ee},{clave:"auditoria.ver",descripcion:"Ver la auditor\xEDa del espacio (qui\xE9n hizo qu\xE9 y cu\xE1ndo)",valores:ee},{clave:"publico.compartir",descripcion:"Compartir la p\xE1gina p\xFAblica de un registro (un enlace que caduca)",valores:ee},{clave:"pix.memoria_espacio",descripcion:"Escribir lo que Pix recuerda para todo el espacio",valores:ee},...uc.map(e=>({clave:`pix.agente_${e.clave}`,descripcion:`Usar a ${e.nombre} (${e.puesto}) del Equipo IA`,valores:ee}))],hz=new Set(ur.map(e=>e.clave)),Hv=e=>/\.(exportar|importar)$/.test(e),qi=e=>Object.fromEntries(ur.map(o=>[o.clave,e(o)])),Xv=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"||Xh(e.clave),Yv={titular:qi(()=>"si"),administrador:qi(e=>e.clave==="conectores.accionar"?"no":"si"),miembro:qi(e=>Xv(e)||e.clave==="conectores.accionar"||e.clave==="secretos.ver"||Hv(e.clave)?"no":"si"),lectura:qi(e=>e.clave.endsWith(".ver")&&e.clave!=="secretos.ver"&&e.clave!=="auditoria.ver"||e.clave.endsWith(".descargar")?"si":e.clave.endsWith(".reasignar")?"suyos":"no")},gz=ur.filter(e=>/^((contactos|empresas|oportunidades|proyectos|tareas|notas|adjuntos)\.|agenda\.(ver|editar)$)/.test(e.clave)&&e.valores.includes("suyos")&&Yv.miembro[e.clave]!=="no").map(e=>e.clave),bz=ur.filter(e=>/^((contactos|empresas|oportunidades|proyectos|tareas|notas|adjuntos)\.|agenda\.(ver|editar)$)/.test(e.clave)&&e.valores.includes("suyos")).map(e=>e.clave)});function cg(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>ag)throw i(`\xAB${r.slice(0,20)}\u2026\xBB: como mucho ${ag} caracteres.`);if(!mc(r))throw i(`\xAB${r}\xBB no es una palabra.`);t.has(mc(r))||(t.add(mc(r)),o.push(r))}}if(o.length>fc)throw i(`Como mucho ${fc} sin\xF3nimos por m\xF3dulo.`);return o}var sg,fc,ag,mc,lg=m(()=>{E();sg=["contacts","companies","deals","tasks"],fc=20,ag=40,mc=e=>e.normalize("NFD").replace(/[̀-ͯ]/g,"").toLowerCase().replace(/[^a-z0-9ñ\s-]/g," ").replace(/\s+/g," ").trim()});function ey(e){if(e===void 0)return[];if(!Array.isArray(e)||e.length>5)throw i("Conexiones de la soluci\xF3n no v\xE1lidas.");return e.map(o=>{if(!re(o)||o.tipo!=="conector"||typeof o.conector!="string"||!/^[a-z][a-z0-9_-]{0,39}$/.test(o.conector))throw i("Conexi\xF3n de la soluci\xF3n no v\xE1lida.");let t=wo(o.nombre,"nombre de la conexi\xF3n",80,!1)||o.conector;return{clave:o.conector,nombre:t,tipo:"conector",conector:o.conector}})}function ty(e){if(e===void 0)return[];if(!Array.isArray(e))throw i("Conexiones de la soluci\xF3n no v\xE1lidas.");let o=s=>re(s)&&s.tipo==="conector",t=ey(e.filter(o)),n=fh(e.filter(s=>!o(s))),r=0,a=0;return e.map(s=>o(s)?t[r++]:n[a++])}function ny(e){if(e==null)return null;if(!re(e))throw i("\xABagenda\xBB: un objeto.");Ve(e,["tipos"],"Agenda");let o=new Set,t=ro(e.tipos,ry,"agenda.tipos").map((n,r)=>{let a=`Tipo de cita ${r+1}`;if(!re(n))throw i(`${a}: un objeto.`);Ve(n,["nombre","duracion","color","reserva_publica","quien_atiende","cambio_horas","crear_persona"],a);let s=wo(n.nombre,`nombre del ${a.toLowerCase()}`,80);if(o.has(s.toLowerCase()))throw i(`${a}: nombre repetido.`);if(o.add(s.toLowerCase()),!Number.isInteger(n.duracion)||n.duracion<5||n.duracion>1440)throw i(`${a}: \xABduracion\xBB, de 5 a 1440 minutos.`);if(n.color!==void 0&&(typeof n.color!="string"||!/^#[0-9a-f]{6}$/i.test(n.color)))throw i(`${a}: \xABcolor\xBB, #rrggbb.`);for(let c of["reserva_publica","crear_persona"])if(n[c]!==void 0&&typeof n[c]!="boolean")throw i(`${a}: \xAB${c}\xBB, s\xED o no.`);if(n.quien_atiende!==void 0&&n.quien_atiende!=="cualquiera"&&n.quien_atiende!=="cliente")throw i(`${a}: \xABquien_atiende\xBB, cualquiera o cliente.`);if(n.cambio_horas!==void 0&&(!Number.isInteger(n.cambio_horas)||n.cambio_horas<0||n.cambio_horas>720))throw i(`${a}: \xABcambio_horas\xBB, de 0 a 720.`);return{nombre:s,duracion:n.duracion,...n.color!==void 0?{color:n.color.toLowerCase()}:{},...n.reserva_publica!==void 0?{reserva_publica:n.reserva_publica}:{},...n.quien_atiende!==void 0?{quien_atiende:n.quien_atiende}:{},...n.cambio_horas!==void 0?{cambio_horas:n.cambio_horas}:{},...n.crear_persona!==void 0?{crear_persona:n.crear_persona}:{}}});return t.length?{tipos:t}:null}function iy(e,o){return ro(e,bc,"vistasTabla").map((t,n)=>{let r=`Vista de tabla ${n+1}`;if(!re(t))throw i(`${r}: un objeto.`);Ve(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=zh(t.disposicion??null,a),c=Rh(a,t.tipoContacto);return{objeto:a,...c?{tipoContacto:c}:{},nombre:wo(t.nombre,`nombre de la ${r.toLowerCase()}`,60),...t.config!==void 0?{config:Fh(t.config)}:{},disposicion:s}})}function ly(e,o,t=[]){let n=new Set;return ro(e,vc,"papeles").map((r,a)=>{let s=`Papel ${a+1}`;if(!re(r))throw i(`${s}: un objeto.`);Ve(r,["nombre","base","permisos","ocultos","lectura","identidades"],s);let c=wo(r.nombre,`nombre del ${s.toLowerCase()}`,40);if(n.has(c.toLowerCase()))throw i(`${s}: nombre repetido.`);if(n.add(c.toLowerCase()),typeof r.base!="string"||!sy.includes(r.base))throw i(`${s}: \xABbase\xBB, administrador, miembro o lectura.`);let d={};if(r.permisos!==void 0){if(!re(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 v=cy.exec(b),w=ur.find(C=>C.clave===b);if(v?!o.includes(v[1]):!w)throw i(`${s}: permiso desconocido \xAB${b.slice(0,60)}\xBB.`);let _=w?w.valores:ng[v[2]];if(typeof y!="string"||!_.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(v=>{let w=typeof v=="string"?ay.exec(v):null,_=w?t.find(C=>C.clave===w[1]):void 0;if(!w||!_||!_.campos.some(C=>C.clave===w[2]))throw i(`${s}: \xAB${String(v).slice(0,60)}\xBB no es un campo de un m\xF3dulo de la soluci\xF3n.`);return v})},p=u(r.ocultos,"ocultos"),f=u(r.lectura,"lectura"),h=Yp(r.identidades);return{nombre:c,base:r.base,...Object.keys(d).length?{permisos:d}:{},...p.length?{ocultos:p}:{},...f.length?{lectura:f}:{},...h.length?{identidades:h}:{}}})}function hc(e,o=0){if(o>30)throw i("La soluci\xF3n anida demasiado.");if(Array.isArray(e))return e.forEach(t=>hc(t,o+1));if(re(e))for(let t of Object.keys(e)){if(Zv.has(t))throw i(`Clave no admitida \xAB${t}\xBB.`);hc(e[t],o+1)}}function Ve(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 wo(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 Kr(e,o){if(typeof e=="string"){if(e.length>ki)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>ki)throw i("La soluci\xF3n pasa de 1 MB.");if(!re(e))throw i("La soluci\xF3n tiene que ser un objeto.");hc(e),Ve(e,["formato","version","plantilla","nombre","descripcion","icono","modulos","paneles","automatizaciones","ejemplos","informes","principal","mensajes","papeles","portales","vistasTabla","separadores","menu","sinonimos","perfilesImportacion","conexiones","fuentesExternas","senales","pix","agenda"],"Soluci\xF3n");let t;if(e.plantilla!==void 0){let g=e.plantilla;if(!re(g))throw i("\xABplantilla\xBB: un objeto.");if(Ve(g,["id","version","sector","nivel","dependencias","migracion"],"Plantilla"),typeof g.id!="string"||!/^[a-z][a-z0-9_]{0,59}$/.test(g.id))throw i("\xABplantilla.id\xBB: min\xFAsculas, n\xFAmeros y _.");if(!Si(g.version))throw i("\xABplantilla.version\xBB: usa una versi\xF3n sem\xE1ntica v\xE1lida.");if(typeof g.sector!="string"||!/^[a-z][a-z0-9_]{0,39}$/.test(g.sector))throw i("\xABplantilla.sector\xBB: min\xFAsculas y _.");if(g.nivel!==void 0&&g.nivel!=="completa"&&g.nivel!=="basica")throw i("\xABplantilla.nivel\xBB: completa o basica.");let x=g.dependencias;if(x!==void 0&&(!Array.isArray(x)||x.length>30||x.some(k=>typeof k!="string"||!/^[a-z][a-z0-9_]{0,59}$/.test(k)||k===g.id)||new Set(x).size!==x.length))throw i("\xABplantilla.dependencias\xBB: usa identificadores distintos de otras soluciones.");let A=wh(g.migracion,g.version);t={...A?{migracion:A}:{},id:g.id,version:g.version,sector:g.sector,...x?{dependencias:x}:{},...g.nivel==="basica"?{nivel:"basica"}:{}}}if(e.formato!==qt)throw i(`No es una soluci\xF3n (formato \xAB${qt}\xBB).`);if(!Number.isInteger(e.version)||e.version<1)throw i("\xABversion\xBB: un entero.");if(e.version>dr)throw i("La soluci\xF3n es de una versi\xF3n m\xE1s nueva del CRM.");let n=wo(e.icono,"icono",40,!1)||"boxes";if(!ug.test(n))throw i("\xABicono\xBB: un icono de lucide.");if(!Array.isArray(e.modulos)||e.modulos.length<1||e.modulos.length>Ri)throw i(`Una soluci\xF3n lleva de 1 a ${Ri} m\xF3dulos.`);let r=e.modulos.map(g=>re(g)&&typeof g.clave=="string"?g.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(([g])=>!r.includes(g))),s=[...r,...a.keys()],c=new Map([...a,...e.modulos.map((g,x)=>[r[x],Qs(g,s)])]),d=e.modulos.map(g=>{let x=nh(g,{topeCampos:o.topeCampos,modulosDelEspacio:s,camposRelacion:c}),A=re(g)?g.sin_coste:void 0;if(A!==void 0&&A!==!0)throw i(`\xAB${x.nombre_plural}\xBB: \xABsin_coste\xBB solo puede ser true.`);return A===!0?{...x,sin_coste:!0}:x}),u=ro(e.paneles,gc,"paneles").map((g,x)=>{if(!re(g))throw i(`Panel ${x+1}: un objeto.`);if(Ve(g,["nombre","icono","widgets"],`Panel ${x+1}`),!Array.isArray(g.widgets)||g.widgets.length>20)throw i(`Panel ${x+1}: hasta 20 widgets.`);let A=wo(g.icono,"icono",40,!1);if(A&&!ug.test(A))throw i(`Panel ${x+1}: icono no v\xE1lido.`);return{nombre:wo(g.nombre,"nombre del panel",60),...A?{icono:A}:{},widgets:g.widgets}}),p=ro(e.automatizaciones,wc,"automatizaciones").map((g,x)=>{if(!re(g))throw i(`Automatizaci\xF3n ${x+1}: un objeto.`);if(Ve(g,["nombre","definicion"],`Automatizaci\xF3n ${x+1}`),!re(g.definicion))throw i(`Automatizaci\xF3n ${x+1}: falta su definici\xF3n.`);return{nombre:wo(g.nombre,"nombre de la automatizaci\xF3n",80),definicion:g.definicion}}),f=ro(e.senales,20,"senales").map((g,x)=>{if(!re(g))throw i(`Se\xF1al ${x+1}: un objeto.`);Ve(g,["fuente","regla"],`Se\xF1al ${x+1}`);let A=typeof g.fuente=="string"?g.fuente:"";if(!(A.startsWith("mod_")?r.includes(A.slice(4)):Kh.includes(A)))throw i(`Se\xF1al ${x+1}: \xABfuente\xBB, un m\xF3dulo de la soluci\xF3n (mod_<clave>) o un nativo.`);if(!re(g.regla))throw i(`Se\xF1al ${x+1}: falta su regla.`);return{fuente:A,regla:g.regla}}),h=og(e.pix),b=rg(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=ro(e.mensajes,Ei,"mensajes").map((g,x)=>{let A=Uh(g,`Mensaje ${x+1}`);if(A.recurso.startsWith("mod_")&&!r.includes(A.recurso.slice(4)))throw i(`Mensaje ${x+1}: de un m\xF3dulo que no est\xE1 en la soluci\xF3n.`);return A}),v=ly(e.papeles,r,d),w=dy(e.portales,r),_=ny(e.agenda),C=iy(e.vistasTabla,r),S=ro(e.separadores??[],yc,"separadores").map((g,x)=>{if(!re(g))throw i(`Separador ${x+1}: un objeto.`);if(Ve(g,["antes","titulo"],`Separador ${x+1}`),g.antes!==null&&(typeof g.antes!="string"||!r.includes(g.antes)))throw i(`Separador ${x+1}: \xABantes\xBB, la clave de uno de sus m\xF3dulos.`);if(g.titulo!==void 0&&g.titulo!==null&&(typeof g.titulo!="string"||!g.titulo.trim()||g.titulo.trim().length>40))throw i(`Separador ${x+1}: \xABtitulo\xBB, de 1 a 40 caracteres (o null: solo la l\xEDnea).`);return{antes:g.antes,titulo:typeof g.titulo=="string"?g.titulo.trim():null}}),P=ro(e.menu??[],100,"menu").map((g,x)=>{if(!re(g))throw i(`Men\xFA ${x+1}: un objeto.`);if(Ve(g,["entrada","padre","recientes","despliega"],`Men\xFA ${x+1}`),typeof g.entrada!="string"||!r.includes(g.entrada))throw i(`Men\xFA ${x+1}: \xABentrada\xBB, la clave de uno de sus m\xF3dulos.`);if(g.padre!==void 0&&g.padre!==null&&(typeof g.padre!="string"||!r.includes(g.padre)||g.padre===g.entrada))throw i(`Men\xFA ${x+1}: \xABpadre\xBB, otro de sus m\xF3dulos (o null).`);if(g.recientes!==void 0&&(!Number.isSafeInteger(g.recientes)||g.recientes<0||g.recientes>10))throw i(`Men\xFA ${x+1}: \xABrecientes\xBB, de 0 a 10.`);if(g.despliega!==void 0&&(typeof g.despliega!="string"||!Hs.includes(g.despliega)))throw i(`Men\xFA ${x+1}: \xABdespliega\xBB, ${Hs.join(", ")}.`);return{entrada:g.entrada,...g.padre!==void 0?{padre:g.padre}:{},...g.recientes!==void 0?{recientes:g.recientes}:{},...g.despliega!==void 0?{despliega:g.despliega}:{}}});for(let g of P)if(g.padre&&(P.some(x=>x.entrada===g.padre&&x.padre)||P.some(x=>x.padre===g.entrada)))throw i(`Men\xFA: \xAB${g.entrada}\xBB, un solo nivel (ni su padre va dentro de otro ni tiene otros dentro).`);if(new Set(P.map(g=>g.entrada)).size!==P.length)throw i("Men\xFA: cada m\xF3dulo, una vez.");let Z={};if(e.ejemplos!==void 0){if(!re(e.ejemplos))throw i("\xABejemplos\xBB: un objeto por m\xF3dulo.");for(let[g,x]of Object.entries(e.ejemplos)){if(!r.includes(g))throw i(`Ejemplos de un m\xF3dulo que no est\xE1 en la soluci\xF3n (\xAB${g.slice(0,40)}\xBB).`);let A=new Set;Z[g]=ro(x,Pi,`ejemplos de ${g}`).map((k,J)=>{if(!re(k))throw i(`Ejemplo ${J+1} de ${g}: un objeto.`);if(k._ref!==void 0&&!Number.isSafeInteger(k._ref))throw i(`Ejemplo ${J+1} de ${g}: \xAB_ref\xBB es un entero.`);if(typeof k._ref=="number"){if(A.has(k._ref))throw i(`\xAB${g}\xBB: referencia de ejemplo repetida.`);A.add(k._ref)}if((d.find(G=>G.clave===g)?.campos??[]).filter(G=>G.tipo==="secreto").map(G=>G.clave).some(G=>G in k))throw i(`Ejemplo ${J+1} de ${g}: un ejemplo no lleva el valor de un campo secreto.`);return k})}}let we=ty(e.conexiones),$=ph(e.fuentesExternas,d,we.filter(oy));if($.some(g=>g.modo==="vivo"&&Z[g.modulo]?.length))throw i("Un m\xF3dulo con fuente en vivo no puede tener ejemplos.");let M=Nh(e.perfilesImportacion);if(M.some(g=>g.perfil.entidades.some(x=>x.destino.startsWith("mod_")&&!d.some(A=>`mod_${A.clave}`===x.destino))))throw i("El perfil apunta fuera de la soluci\xF3n.");return{formato:qt,...M.length?{perfilesImportacion:M}:{},...we.length?{conexiones:we}:{},...$.length?{fuentesExternas:$}:{},version:e.version,...t?{plantilla:t}:{},nombre:wo(e.nombre,"nombre",80),descripcion:wo(e.descripcion,"descripcion",500,!1),icono:n,modulos:d,paneles:u,automatizaciones:p,ejemplos:Z,...f.length?{senales:f}:{},...h?{pix:h}:{},...b.length?{informes:b}:{},...typeof e.principal=="string"?{principal:e.principal}:{},...y.length?{mensajes:y}:{},...v.length?{papeles:v}:{},...w.length?{portales:w}:{},..._?{agenda:_}:{},...C.length?{vistasTabla:C}:{},...S.length?{separadores:S}:{},...P.length?{menu:P}:{},...uy(e.sinonimos,d.map(g=>g.clave))}}function uy(e,o){if(e===void 0)return{};if(!re(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)&&!sg.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=cg(r);a.length&&(t[n]=a)}return Object.keys(t).length?{sinonimos:t}:{}}function dy(e,o){return ro(e,_c,"portales").map((t,n)=>{let r=`Portal ${n+1}`;if(!re(t))throw i(`${r}: un objeto.`);Ve(t,["clave","nombre","activo","personas","secciones","textos","marca"],r);let a=[...Bh(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:c,...d}=t,u=re(c)&&typeof c.color=="string"?c.color:void 0;return{...d,...u?{marca:{color:u}}:{}}})}function ro(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 qt,dr,Ri,gc,bc,wc,Pi,ki,ug,Zv,oy,ry,vc,ay,sy,cy,re,yc,_c,Nc=m(()=>{mh();hh();vh();Ys();$h();Kp();Vh();kh();lc();E();Zh();tg();dc();Gr();dh();ig();Wh();lg();qt="forgenex.solucion",dr=2,Ri=30,gc=10,bc=20,wc=40,Pi=50,ki=1e6,ug=/^[a-z0-9-]{1,40}$/,Zv=new Set(["__proto__","constructor","prototype"]);oy=e=>e.tipo!=="conector";ry=10;vc=10,ay=/^mod_([a-z][a-z0-9_]{0,40})\.([a-z][a-z0-9_]{0,40})$/,sy=["administrador","miembro","lectura"],cy=/^mod_([a-z][a-z0-9_]{0,40})\.(ver|editar|borrar|exportar|importar|crear|reasignar|estado|descargar|revelar)$/;re=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);yc=20,_c=10});function pg(e,o){let t=new Map(e);for(let[n,r]of e){if(!/^(interfaz|funciones)\/.+\.ts$/.test(n))continue;let a=n.replace(/\.ts$/,".js");if(e.has(a))throw dg([{ruta:n,linea:null,motivo:`El fichero coincide con la salida \xAB${a}\xBB.`}]);try{let{code:s}=o(r.toString("utf8"),{loader:"ts",sourcefile:n,target:"es2020",format:"esm"});t.set(a,Buffer.from(s)),t.delete(n)}catch(s){let c=s?.errors;throw dg(c?.length?c.slice(0,12).map(({location:d,text:u})=>({ruta:n,linea:d?.line??null,motivo:u})):[{ruta:n,linea:null,motivo:"El compilador no pudo procesar el fichero."}])}}return t}function dg(e){let{ruta:o,linea:t,motivo:n}=e[0];return new L(422,"build_app",`${o}${t?`:${t}`:""}: ${n}`,!1,{errores:e})}var mg=m(()=>{E()});import{inflateRawSync as py}from"node:zlib";function my(e){let o=Buffer.from(e.buffer,e.byteOffset,e.byteLength);if(o.length>$c)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>hg)throw i(`El paquete trae m\xE1s de ${hg} ficheros.`);let s=new Map,c=r;for(let d=0;d<n;d++){if(c+46>t||o.readUInt32LE(c)!==33639248)throw i("El .zip est\xE1 da\xF1ado.");let u=o.readUInt16LE(c+8),p=o.readUInt16LE(c+10),f=o.readUInt32LE(c+20),h=o.readUInt32LE(c+24),b=o.readUInt16LE(c+28),y=o.readUInt16LE(c+30),v=o.readUInt16LE(c+32);if((o.readUInt32LE(c+38)>>>16&61440)===40960)throw i("El paquete no admite enlaces simb\xF3licos.");let _=o.readUInt32LE(c+42);if(c+46+b+y+v>t)throw i("El .zip est\xE1 da\xF1ado.");let C=o.subarray(c+46,c+46+b),S=C.toString("utf8");if(c+=46+b+y+v,!S.endsWith("/")){if(!S||S.includes("\\")||S.startsWith("/")||S.split("/").some(P=>P===".."||P==="."||P==="")||/[\x00-\x1f]/.test(S))throw i(`El paquete trae un nombre de fichero no admitido (\xAB${S.slice(0,80)}\xBB).`);if(s.has(S))throw i(`El paquete trae \xAB${S.slice(0,80)}\xBB dos veces.`);if(u&1)throw i("El paquete no puede ir cifrado.");s.set(S,()=>{if(h>fg)throw i(`\xAB${S}\xBB pasa de 2 MB.`);if(_+30>o.length||o.readUInt32LE(_)!==67324752)throw i("El .zip est\xE1 da\xF1ado.");let P=o.readUInt16LE(_+26),Z=_+30+P+o.readUInt16LE(_+28);if(Z>r||Z+f>r||o.readUInt16LE(_+6)!==u||o.readUInt16LE(_+8)!==p||!o.subarray(_+30,_+30+P).equals(C))throw i("El .zip est\xE1 da\xF1ado.");let we=o.subarray(Z,Z+f);if(we.length!==f)throw i("El .zip est\xE1 da\xF1ado.");let $;if(p===0)$=we;else if(p===8)try{$=py(we,{maxOutputLength:fg})}catch{throw i(`\xAB${S}\xBB no se puede descomprimir (o pasa de 2 MB).`)}else throw i(`\xAB${S}\xBB va comprimido de una forma no admitida (solo \xABstore\xBB y \xABdeflate\xBB).`);if($.length!==h)throw i("El .zip est\xE1 da\xF1ado.");return $})}}if(c!==t)throw i("El .zip est\xE1 da\xF1ado (directorio inv\xE1lido).");return s}function pr(e){let o=new Map,t=0;for(let[n,r]of my(e)){let a=r();if(t+=a.length,t>fy)throw i("Los ficheros del paquete pasan de 10 MB al descomprimirlos.");o.set(n,a)}return o}var $c,fg,hg,fy,Ti=m(()=>{E();$c=5*1024*1024,fg=2*1024*1024,hg=500;fy=10*1024*1024});import{createHash as gg,createPublicKey as hy,sign as gy,verify as rF}from"node:crypto";function by(e){let o=hy(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:gg("sha256").update(t).digest("hex")}}function wy(e){return Buffer.from(JSON.stringify(["forgenex.fgx.v1",[...e].filter(([o])=>o!==Zr).sort(([o],[t])=>o<t?-1:o>t?1:0).map(([o,t])=>[o,gg("sha256").update(t).digest("hex")])]))}function bg(e,o,t){let{id:n}=by(t);return Buffer.from(JSON.stringify({formato:"forgenex.firma",version:1,clave:n,firma:gy(null,wy(e),o).toString("base64")}))}var Zr,xc=m(()=>{E();Zr="firma.json"});function Cc(e){let o=Array.from({length:256},(c,d)=>{let u=d;for(let p=0;p<8;p++)u=u&1?3988292384^u>>>1:u>>>1;return u>>>0}),t=[],n=[],r=0;for(let[c,d]of e){let u=Buffer.from(c),p=4294967295;for(let b of d)p=o[(p^b)&255]^p>>>8;p=(p^4294967295)>>>0;let f=Buffer.alloc(30),h=Buffer.alloc(46);f.writeUInt32LE(67324752),f.writeUInt16LE(20,4),f.writeUInt16LE(2048,6),f.writeUInt32LE(p,14),f.writeUInt32LE(d.length,18),f.writeUInt32LE(d.length,22),f.writeUInt16LE(u.length,26),h.writeUInt32LE(33639248),h.writeUInt16LE(20,4),h.writeUInt16LE(20,6),h.writeUInt16LE(2048,8),h.writeUInt32LE(p,16),h.writeUInt32LE(d.length,20),h.writeUInt32LE(d.length,24),h.writeUInt16LE(u.length,28),h.writeUInt32LE(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 wg=m(()=>{});import{existsSync as vy,copyFileSync as en,mkdirSync as jc,readFileSync as on,readdirSync as tn,realpathSync as vg,writeFileSync as yg}from"node:fs";import{dirname as yy,join as W,resolve as _y,sep as Ny}from"node:path";import{fileURLToPath as $y}from"node:url";import{createRequire as Mi}from"node:module";function _g(e,o="html",t=process.cwd()){if(!/^[a-z][a-z0-9-]{1,59}$/.test(e))throw new Error("El nombre debe tener de 2 a 60 letras min\xFAsculas, n\xFAmeros o guiones y empezar por letra.");if(!["html","react","archivos"].includes(o))throw new Error("Plantilla: html, react o archivos.");let n=W(t,e);jc(n);for(let c of["interfaz","funciones"])jc(W(n,c));let r=(c,d)=>yg(W(n,c),typeof d=="string"?d:JSON.stringify(d,null,2)+`
|
|
22
|
-
`)
|
|
21
|
+
from aprobaciones a join modulos m on m.id = a.modulo_id`});function Ef(e,o,t){if(e.requisito!==void 0&&e.requisito!==null){let n=e.requisito;if(!gv(n)||typeof n.formula!="string"||!n.formula.trim()||n.formula.length>no||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>Af||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 ${Af} campos.`);e.pide.length&&(o.pide=[...new Set(e.pide)])}if(Sf(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 qf(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 c of r.pide??[]){let d=o.find(u=>u.clave===c);if(!d||["formula","resumen","busqueda","subtabla","boton","autonumero","creado_el","creado_por","modificado_el","modificado_por"].includes(d.tipo))throw i(`\xAB${t.etiqueta}\xBB, \xAB${r.etiqueta}\xBB: pide \xAB${c}\xBB, que no es un campo que se rellene.`)}if(!r.requisito)return r;let s;try{s=gi([...o,bv(t.clave,a,r.requisito.formula)]).at(-1)}catch(c){throw i(`\xAB${t.etiqueta}\xBB, \xAB${r.etiqueta}\xBB: ${c instanceof Error?c.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 Af,gv,bv,Rf=f(()=>{q();bi();Of();Af=5,gv=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),bv=(e,o,t)=>({clave:`etapa_${e}_${o}`,etiqueta:`Requisito ${o+1}`,tipo:"formula",formula:t})});function Tf(e){if(e==null)return;if(!Array.isArray(e)||e.length>kf)throw i(`\xABconversiones\xBB: hasta ${kf}.`);let o=new Set,t=e.map((n,r)=>{let a=`Conversi\xF3n ${r+1}`;if(!Si(n))throw i(`${a}: un objeto.`);for(let c of Object.keys(n))if(!["clave","nombre","destino","campos","enlaceDestino","enlaceOrigen","lineas","etapa"].includes(c))throw i(`${a}: clave no admitida \xAB${c.slice(0,40)}\xBB.`);if(typeof n.clave!="string"||!At.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"||!(wv.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:Pf(n.campos,a)};for(let c of["enlaceDestino","enlaceOrigen"])if(!(n[c]===void 0||n[c]===null||n[c]==="")){if(typeof n[c]!="string"||!At.test(n[c]))throw i(`${a}: \xAB${c}\xBB no es un campo v\xE1lido.`);s[c]=n[c]}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(c=>{if(!Si(c)||typeof c.desde!="string"||!At.test(c.desde)||typeof c.a!="string"||!At.test(c.a))throw i(`${a}: cada \xABlineas\xBB, {desde, a, campos}.`);return{desde:c.desde,a:c.a,campos:Pf(c.campos,a)}})}if(n.etapa!==void 0&&n.etapa!==null){if(!Si(n.etapa)||typeof n.etapa.campo!="string"||!At.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 kf,At,wv,Si,Pf,Mf=f(()=>{q();kf=5,At=/^[a-z][a-z0-9_]{0,40}$/,wv=["contacts","companies","deals"],Si=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Pf=(e,o)=>{if(e===void 0)return{};if(!Si(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(!At.test(t)||typeof n!="string"||!At.test(n))throw i(`${o}: el campo \xAB${t.slice(0,40)}\xBB no es v\xE1lido.`);return e}});function Lf(e,o){if(e==null)return;if(!Array.isArray(e)||e.length>If)throw i(`\xABencadenar\xBB: hasta ${If}.`);let t=new Set,n=e.map((r,a)=>{let s=`\xABencadenar\xBB ${a+1}`;if(!Et(r))throw i(`${s}: un objeto.`);for(let w of Object.keys(r))if(!["clave","nombre","destino","enlace","campos","lineas","estado","no_cuentan","permitir_exceso","juntar"].includes(w))throw i(`${s}: clave no admitida \xAB${w.slice(0,40)}\xBB.`);let c=ot(r.clave,`${s}.clave`);if(t.has(c))throw i(`${s}: \xABclave\xBB repetida.`);if(c==="juntar")throw i(`${s}: \xABjuntar\xBB no vale como clave.`);if(t.add(c),typeof 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(!Et(r.lineas))throw i(`${s}: \xABlineas\xBB {desde, a, cantidad: {origen, destino}}.`);let d=r.lineas,u=ot(d.desde,`${s}.lineas.desde`),p=yv(o,u);if(!p)throw i(`${s}: \xAB${u}\xBB no es una subtabla de este m\xF3dulo.`);if(!Et(d.cantidad))throw i(`${s}: \xABlineas.cantidad\xBB {origen, destino}.`);let m=ot(d.cantidad.origen,`${s}.lineas.cantidad.origen`),h=(p.columnas??[]).find(w=>w.clave===m&&!w.archivado);if(!h||!(vv.includes(h.tipo)||h.tipo==="formula"&&h.origen?.tipo==="numero"))throw i(`${s}: la cantidad \xAB${m}\xBB tiene que ser una columna num\xE9rica de \xAB${u}\xBB.`);let b={clave:c,nombre:r.nombre.trim(),destino:r.destino,enlace:ot(r.enlace,`${s}.enlace`),lineas:{desde:u,a:ot(d.a,`${s}.lineas.a`),cantidad:{origen:m,destino:ot(d.cantidad.destino,`${s}.lineas.cantidad.destino`)}}},y=Df(d.campos,`${s}.lineas.campos`);if(y){for(let w of Object.values(y))if(!(p.columnas??[]).some(N=>N.clave===w&&!N.archivado))throw i(`${s}: \xAB${w}\xBB no es una columna de \xAB${u}\xBB.`);b.lineas.campos=y}let v=Df(r.campos,`${s}.campos`);if(v){for(let w of Object.values(v))if(!o.some(N=>N.clave===w&&!N.archivado))throw i(`${s}: \xAB${w}\xBB no es un campo de este m\xF3dulo.`);b.campos=v}if(r.estado!==void 0&&r.estado!==null){let w=r.estado;if(!Et(w))throw i(`${s}: \xABestado\xBB {campo, parcial, completo, pendiente?}.`);let N=o.find(S=>S.clave===w.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 j=new Set((N.opciones??[]).map(S=>S.valor));for(let S of["parcial","completo","pendiente"]){let R=w[S];if(!(R===void 0&&S==="pendiente")&&(typeof R!="string"||!j.has(R)))throw i(`${s}: \xABestado.${S}\xBB tiene que ser una opci\xF3n de \xAB${N.etiqueta}\xBB.`)}b.estado={campo:N.clave,parcial:w.parcial,completo:w.completo,...typeof w.pendiente=="string"?{pendiente:w.pendiente}:{}}}if(r.no_cuentan!==void 0&&r.no_cuentan!==null){let w=r.no_cuentan;if(!Et(w)||!Array.isArray(w.valores)||w.valores.length>20||!w.valores.every(N=>typeof N=="string"&&N.length<=60))throw i(`${s}: \xABno_cuentan\xBB {campo, valores}.`);b.no_cuentan={campo:ot(w.campo,`${s}.no_cuentan.campo`),valores:w.valores}}if(r.permitir_exceso===!0&&(b.permitir_exceso=!0),r.juntar!==void 0&&r.juntar!==null&&r.juntar!==!1){let w=r.juntar===!0?{}:r.juntar;if(!Et(w))throw i(`${s}: \xABjuntar\xBB {iguales?, enlace_varios?}.`);for(let j of Object.keys(w))if(!["iguales","enlace_varios"].includes(j))throw i(`${s}: \xABjuntar\xBB: clave no admitida \xAB${j.slice(0,40)}\xBB.`);let N=w.iguales===void 0?[]:w.iguales;if(!Array.isArray(N)||N.length>10||!N.every(j=>typeof j=="string"&&o.some(S=>S.clave===j&&!S.archivado)))throw i(`${s}: \xABjuntar.iguales\xBB, campos de este m\xF3dulo (hasta 10).`);b.juntar={...N.length?{iguales:N}:{},...w.enlace_varios?{enlace_varios:ot(w.enlace_varios,`${s}.juntar.enlace_varios`)}:{}}}return b});return n.length?n:void 0}var If,Gs,vv,Et,Df,ot,yv,zf=f(()=>{q();If=5,Gs=/^[a-z][a-z0-9_]{0,40}$/,vv=["numero","importe","duracion","porcentaje"],Et=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Df=(e,o)=>{if(e!=null){if(!Et(e)||Object.keys(e).length>60)throw i(`${o}: un objeto destino \u2192 origen.`);for(let[t,n]of Object.entries(e))if(!Gs.test(t)||typeof n!="string"||!Gs.test(n))throw i(`${o}: \xAB${t.slice(0,40)}\xBB no es v\xE1lido.`);return e}},ot=(e,o)=>{if(typeof e!="string"||!Gs.test(e))throw i(`${o}: falta o no es v\xE1lido.`);return e},yv=(e,o)=>e.find(t=>t.clave===o&&t.tipo==="subtabla"&&!t.archivado)});function Bf(e){if(e==null)return;if(!Array.isArray(e)||e.length>Ff)throw i(`\xABplantillas_hijos\xBB: hasta ${Ff}.`);let o=new Set,t=e.map((n,r)=>{let a=`Plantilla de hijos ${r+1}`;if(!Hs(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"||!Oi.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 c={clave:n.clave,nombre:n.nombre.trim(),cuando:s.map(d=>{if(!Hs(d)||typeof d.campo!="string"||!Oi.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(!Oi.test(n.subtabla))throw i(`${a}: \xABsubtabla\xBB no v\xE1lida.`);c.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"||!Oi.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.`);c.modulo=n.modulo,c.via=n.via}if(!Array.isArray(n.registros)||!n.registros.length||n.registros.length>Wf)throw i(`${a}: \xABregistros\xBB, de 1 a ${Wf}.`);return c.registros=n.registros.map(d=>{if(!Hs(d)||JSON.stringify(d).length>4e3)throw i(`${a}: cada registro, un objeto (de hasta 4000 caracteres).`);return d}),c});return t.length?t:void 0}var Ff,Wf,Oi,Hs,Vf=f(()=>{q();Ff=10,Wf=50,Oi=/^[a-z][a-z0-9_]{0,40}$/,Hs=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)});function Jf(e,o){if(e==null)return;if(!wo(e))throw i("\xABpertenencia\xBB: un objeto.");let t=(n,r,a,s=!1)=>{let c=o.find(d=>d.clave===n&&!d.archivado);if(!c||!r.includes(c.tipo)||s&&c.multiple)throw i(`\xABpertenencia.${a}\xBB: ${r.join(" o ")}${s?" simple":""} de este m\xF3dulo.`);return c.clave};return{demanda:t(e.demanda,["relacion"],"demanda",!0),oferta:t(e.oferta,["relacion"],"oferta",!0),desde:t(e.desde,["fecha"],"desde"),...e.hasta?{hasta:t(e.hasta,["fecha"],"hasta")}:{},...e.correccion_dias!==void 0&&e.correccion_dias!==null?{correccion_dias:_v(e.correccion_dias)}:{}}}function Qf(e,o){if(e==null)return;if(!wo(e))throw i("\xABasignacion\xBB: un objeto.");if(typeof e.oferta!="string"||!Ei.test(e.oferta))throw i("\xABasignacion.oferta\xBB: la clave del m\xF3dulo de la oferta.");let t=e.destino,n;if(wo(t)&&t.forma==="pertenencia"&&typeof t.modulo=="string"&&Ei.test(t.modulo))n={forma:"pertenencia",modulo:t.modulo};else if(wo(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"||!Ei.test(e.cupo))throw i("\xABasignacion.cupo\xBB: un campo num\xE9rico de la oferta.");return{oferta:e.oferta,destino:n,...$v({...e,cupo_fijo:void 0},o),cupo:e.cupo}}function $v(e,o,t=!1){let n=(p,m,h)=>{let b=o.find(y=>y.clave===p&&!y.archivado);if(!b||h&&!h.includes(b.tipo))throw i(`\xABasignacion\xBB: ${m}, ${h?h.join(" o "):"un campo"} de este m\xF3dulo.`);return b.clave},r=(p,m)=>{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(`${m}: campo de oferta no v\xE1lido.`);return p}return Nv(p,m)},a=t?Uf:Ei,s=t&&e.cupo_fijo!==void 0;if(s?e.cupo!==void 0||!Number.isInteger(e.cupo_fijo)||Number(e.cupo_fijo)<1||Number(e.cupo_fijo)>1e4:typeof e.cupo!="string"||!a.test(e.cupo))throw i("\xABasignacion.cupo\xBB: un n\xFAmero de la oferta o un cupo fijo de 1 a 10000.");let c={...s?{cupo_fijo:Number(e.cupo_fijo)}:{cupo:e.cupo},filtros:[],puntos:[]};if(e.orden!==void 0&&e.orden!==null){let p=e.orden;if(!wo(p))throw i("\xABasignacion.orden\xBB: {campo, sentido}.");c.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(!wo(p)||typeof p.oferta!="string"||!a.test(p.oferta))throw i("\xABasignacion.plazas_por\xBB: {demanda (selecci\xF3n m\xFAltiple), oferta (su campo)}.");c.plazas_por={demanda:n(p.demanda,"\xABplazas_por.demanda\xBB",["seleccion_multiple","seleccion"]),oferta:p.oferta}}e.inicio&&(c.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>Ai||u.length>Ai)throw i(`\xABasignacion\xBB: hasta ${Ai} filtros y ${Ai} puntos.`);if(c.filtros=d.map((p,m)=>{let h=`Filtro ${m+1}`;if(!wo(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.`)}),c.puntos=u.map((p,m)=>{let h=`Punto ${m+1}`;if(!wo(p))throw i(`${h}: un objeto.`);switch(p.tipo){case"base":case"carga":return{tipo:p.tipo,peso:qt(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:qt(p.peso,h)};case"igual":case"contiene":return{tipo:p.tipo,demanda:n(p.demanda,`${h}, \xABdemanda\xBB`),oferta:r(p.oferta,h),peso:qt(p.peso,h)};case"junto":{let b=o.find(v=>v.clave===p.relacion&&!v.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:qt(p.misma,h),...wo(y)?{mismo_campo:{oferta:r(y.oferta,h),peso:qt(y.peso,h)}}:{},...p.mismo_valor!==void 0?{mismo_valor:qt(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:qt(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(!wo(p))throw i("\xABasignacion.cercania\xBB: {demanda, oferta}.");c.cercania={demanda:n(p.demanda,"\xABcercania.demanda\xBB",["hora","numero","fecha","fecha_hora"]),oferta:r(p.oferta,"\xABcercania\xBB")}}return c}var wo,Ei,Uf,Ai,_v,qt,Nv,Gf=f(()=>{q();wo=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Ei=/^[a-z][a-z0-9_]{0,40}$/,Uf=/^[a-z][a-z0-9_]{0,40}(\.[a-z][a-z0-9_]{0,40})?$/,Ai=20,_v=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};qt=(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},Nv=(e,o)=>{if(typeof e!="string"||!Uf.test(e))throw i(`${o}: un campo de la oferta (\xABcampo\xBB o \xABrelacion.campo\xBB).`);return e}});function Hf(e,o){if(e==null)return;if(!qi(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(Cv.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 c=`Acci\xF3n p\xFAblica ${s+1}`;if(!qi(a)||typeof a.clave!="string"||!xv.test(a.clave)||r.has(a.clave))throw i(`${c}: \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(`${c}: el texto del bot\xF3n (1\u201360).`);let d={clave:a.clave,etiqueta:a.etiqueta.trim(),...a.una_vez===!0?{una_vez:!0}:{}};if(a.campo!==void 0&&a.campo!==null&&a.campo!==""){let u=t(a.campo);if(u?.tipo==="seleccion"){let p=u.opciones?.find(m=>m.valor===a.valor);if(!p)throw i(`${c}: el valor tiene que ser una opci\xF3n de \xAB${u.etiqueta}\xBB.`);if(u.embudo&&(p.requisito||p.pide?.length||p.aprobacion))throw i(`${c}: \xAB${p.etiqueta}\xBB tiene requisito o aprobaci\xF3n: no se puede poner desde fuera.`)}else if(u?.tipo==="booleano"){if(typeof a.valor!="boolean")throw i(`${c}: el valor, s\xED o no.`)}else if(u?.tipo==="hecho"){if(a.valor!==!0)throw i(`${c}: un \xABhecho\xBB se marca (true).`)}else throw i(`${c}: el campo, una selecci\xF3n, un s\xED/no o un \xABhecho\xBB.`);d.campo=u.clave,d.valor=a.valor}if(a.lineas!==void 0&&a.lineas!==null){let u=a.lineas,p=qi(u)?t(u.subtabla):void 0,m=p?.tipo==="subtabla"?(p.columnas??[]).find(h=>h.clave===u.columna&&!h.archivado):void 0;if(m?.tipo!=="booleano")throw i(`${c}: \xABlineas\xBB, una subtabla del m\xF3dulo y una columna s\xED/no suya.`);if(!n.campos.includes(p.clave))throw i(`${c}: la subtabla de \xABlineas\xBB tiene que ense\xF1arse en la p\xE1gina.`);d.lineas={subtabla:p.clave,columna:m.clave}}if(a.firma!==void 0&&a.firma!==null&&a.firma!==!1){let u=a.firma===!0?{}:a.firma;if(!qi(u))throw i(`${c}: \xABfirma\xBB, {archivos}.`);for(let p of Object.keys(u))if(p!=="archivos")throw i(`${c}: \xABfirma\xBB, clave no admitida \xAB${p.slice(0,40)}\xBB.`);if(u.archivos!==void 0&&u.archivos!==null&&u.archivos!==""){if(t(u.archivos)?.tipo!=="archivos")throw i(`${c}: \xABfirma.archivos\xBB, un campo de archivos del m\xF3dulo (donde queda el firmado).`);d.firma={archivos:u.archivos}}else d.firma={}}if(!d.campo&&!d.lineas&&!d.firma)throw i(`${c}: un campo, unas l\xEDneas o la firma.`);return d}),n.acciones.filter(a=>a.firma).length>1)throw i("\xABpublico.acciones\xBB: solo una firma el documento.")}return n}var xv,qi,Cv,Xf=f(()=>{q();xv=/^[a-z][a-z0-9_]{0,40}$/,qi=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Cv=["secreto","boton","firma"]});function Zf(e,o){if(he(e))return;if(!vo(e))throw i("\xABstock\xBB: un objeto {articulo?, ubicacion?, movimiento?}.");tt(e,["articulo","ubicacion","movimiento","reponer"],"stock");let t=s=>o.find(c=>c.clave===s&&!c.archivado),n=(s,c,d,u)=>{let p=t(s);if(!p||!d(p))throw i(`\xABstock.${c}\xBB: ${u} de este m\xF3dulo.`);return p.clave},r=s=>s.tipo==="relacion"&&!s.multiple&&!!s.relacion?.startsWith("mod_"),a={};if(!he(e.articulo)){let s=e.articulo;if(!vo(s))throw i("\xABstock.articulo\xBB: un objeto.");tt(s,["minimo","reponer","proveedor","permitir_negativo","lotes"],"stock.articulo");let c={};if(he(s.minimo)||(c.minimo=n(s.minimo,"articulo.minimo",d=>d.tipo==="numero","un n\xFAmero")),he(s.reponer)||(c.reponer=n(s.reponer,"articulo.reponer",d=>d.tipo==="numero","un n\xFAmero")),he(s.proveedor)||(c.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)c.permitir_negativo=!0;else if(typeof s.permitir_negativo=="string"&&s.permitir_negativo)c.permitir_negativo=n(s.permitir_negativo,"articulo.permitir_negativo",d=>d.tipo==="booleano","un s\xED/no");else if(!he(s.permitir_negativo)&&s.permitir_negativo!==!1)throw i("\xABstock.articulo.permitir_negativo\xBB: true o un s\xED/no del art\xEDculo.");if(!he(s.lotes)){if(s.lotes!=="lote"&&s.lotes!=="serie")throw i("\xABstock.articulo.lotes\xBB: lote o serie.");if(c.permitir_negativo)throw i("\xABstock.articulo\xBB: con lotes o series no se admiten negativos.");c.lotes=s.lotes}a.articulo=c}if(!he(e.ubicacion)){let s=e.ubicacion;if(!vo(s))throw i("\xABstock.ubicacion\xBB: un objeto.");tt(s,["almacen"],"stock.ubicacion"),a.ubicacion=he(s.almacen)?{}:{almacen:n(s.almacen,"ubicacion.almacen",r,"una relaci\xF3n simple a otro m\xF3dulo")}}if(!he(e.movimiento)){let s=e.movimiento;if(!vo(s))throw i("\xABstock.movimiento\xBB: un objeto.");if(tt(s,["tipo","lineas","ubicacion","ubicacion_destino","cuando"],"stock.movimiento"),!Yf.includes(s.tipo))throw i(`\xABstock.movimiento.tipo\xBB: ${Yf.join(", ")}.`);if(!vo(s.lineas))throw i("\xABstock.movimiento.lineas\xBB: {subtabla, articulo, cantidad, ubicacion?, coste?}.");let c=s.lineas;tt(c,["subtabla","articulo","cantidad","ubicacion","ubicacion_destino","coste","lote","caducidad"],"stock.movimiento.lineas");let d=t(c.subtabla);if(d?.tipo!=="subtabla")throw i("\xABstock.movimiento.lineas.subtabla\xBB: una subtabla de este m\xF3dulo.");let u=(d.columnas??[]).filter(v=>!v.archivado),p=(v,w,N,j)=>{let S=u.find(R=>R.clave===v);if(!S||!N(S))throw i(`\xABstock.movimiento.lineas.${w}\xBB: ${j} de \xAB${d.etiqueta}\xBB.`);return S.clave},m={tipo:s.tipo,lineas:{subtabla:d.clave,articulo:p(c.articulo,"articulo",r,"la columna de producto (una relaci\xF3n simple)"),cantidad:p(c.cantidad,"cantidad",v=>Kf.includes(v.tipo),"una columna num\xE9rica")},cuando:{campo:"",valores:[]}};if(he(c.ubicacion)||(m.lineas.ubicacion=p(c.ubicacion,"ubicacion",r,"una relaci\xF3n simple")),he(c.coste)||(m.lineas.coste=p(c.coste,"coste",v=>Kf.includes(v.tipo),"una columna num\xE9rica")),he(c.lote)||(m.lineas.lote=p(c.lote,"lote",v=>v.tipo==="texto"||v.tipo==="codigo","una columna de texto")),he(c.caducidad)||(m.lineas.caducidad=p(c.caducidad,"caducidad",v=>v.tipo==="fecha","una columna de fecha")),he(s.ubicacion)||(m.ubicacion=n(s.ubicacion,"movimiento.ubicacion",r,"una relaci\xF3n simple")),!m.lineas.ubicacion&&!m.ubicacion)throw i("\xABstock.movimiento\xBB: la ubicaci\xF3n, en la l\xEDnea (\xABlineas.ubicacion\xBB) o en el documento (\xABubicacion\xBB).");if(he(c.ubicacion_destino)||(m.lineas.ubicacion_destino=p(c.ubicacion_destino,"ubicacion_destino",r,"una relaci\xF3n simple")),he(s.ubicacion_destino)||(m.ubicacion_destino=n(s.ubicacion_destino,"movimiento.ubicacion_destino",r,"una relaci\xF3n simple")),m.tipo==="traspaso"&&!m.lineas.ubicacion_destino&&!m.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(m.tipo!=="traspaso"&&(m.lineas.ubicacion_destino||m.ubicacion_destino))throw i("\xABstock.movimiento\xBB: la ubicaci\xF3n de destino es solo de un traspaso.");if(!vo(s.cuando))throw i("\xABstock.movimiento.cuando\xBB: {campo, valor} o {campo, valores}.");tt(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(v=>v.valor));if(!b.length||b.length>20||!b.every(v=>typeof v=="string"&&y.has(v)))throw i(`\xABstock.movimiento.cuando\xBB: opciones de \xAB${h.etiqueta}\xBB.`);m.cuando={campo:h.clave,valores:[...new Set(b)]},a.movimiento=m}if(!he(e.reponer)){let s=e.reponer;if(!vo(s))throw i("\xABstock.reponer\xBB: {destino, proveedor, lineas: {subtabla, articulo, cantidad}, estado?}.");if(tt(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"||!Xs.test(s.proveedor))throw i("\xABstock.reponer.proveedor\xBB: la relaci\xF3n de las compras al proveedor.");if(!vo(s.lineas))throw i("\xABstock.reponer.lineas\xBB: {subtabla, articulo, cantidad}.");tt(s.lineas,["subtabla","articulo","cantidad"],"stock.reponer.lineas");for(let d of["subtabla","articulo","cantidad"])if(typeof s.lineas[d]!="string"||!Xs.test(s.lineas[d]))throw i(`\xABstock.reponer.lineas.${d}\xBB: falta o no es v\xE1lida.`);let c={destino:s.destino,proveedor:s.proveedor,lineas:{subtabla:s.lineas.subtabla,articulo:s.lineas.articulo,cantidad:s.lineas.cantidad}};if(!he(s.estado)){if(!vo(s.estado)||typeof s.estado.campo!="string"||typeof s.estado.valor!="string")throw i("\xABstock.reponer.estado\xBB: {campo, valor}.");c.estado={campo:s.estado.campo,valor:s.estado.valor}}if(!he(s.en_camino)){let d=s.en_camino;if(!vo(d)||typeof d.campo!="string"||!Xs.test(d.campo)||!Array.isArray(d.valores)||!d.valores.length||d.valores.length>20||!d.valores.every(u=>typeof u=="string"&&u.length<=80))throw i("\xABstock.reponer.en_camino\xBB: {campo, valores} (los estados de la compra pedida y a\xFAn no recibida).");c.en_camino={campo:d.campo,valores:[...new Set(d.valores)]}}a.reponer=c}return Object.keys(a).length?a:void 0}var Yf,vo,tt,Kf,he,Xs,eh=f(()=>{q();Yf=["entrada","salida","ajuste","traspaso","recuento","reserva"],vo=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),tt=(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.`)},Kf=["numero","importe","duracion","porcentaje"],he=e=>e==null||e==="";Xs=/^[a-z][a-z0-9_]{0,40}$/});function Sv(e,o){let t=`liquidacion.reglas[${o}]`;if(!rt(e))throw i(`\xAB${t}\xBB: un objeto.`);if(nt(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(Rt(e.si)||(n.si=rh(e.si,`${t}.si`)),Rt(e.tramos))n.valor=Zs(e.valor,`${t}.valor`);else{let r=e.tramos;if(!rt(r))throw i(`\xAB${t}.tramos\xBB: {por, lista}.`);if(nt(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>th)throw i(`\xAB${t}.tramos.lista\xBB: de 1 a ${th} tramos {desde, valor}.`);let a=r.lista.map((s,c)=>{if(!rt(s))throw i(`\xAB${t}.tramos.lista[${c}]\xBB: {desde, valor}.`);return nt(s,["desde","valor"],`${t}.tramos.lista[${c}]`),{desde:Zs(s.desde,`${t}.tramos.lista[${c}].desde`,0),valor:Zs(s.valor,`${t}.tramos.lista[${c}].valor`)}}).sort((s,c)=>s.desde-c.desde);if(a[0].desde!==0)throw i(`\xAB${t}.tramos\xBB: el primer tramo empieza en 0.`);if(new Set(a.map(s=>s.desde)).size!==a.length)throw i(`\xAB${t}.tramos\xBB: dos tramos con el mismo \xABdesde\xBB.`);if(n.tramos={por:r.por,modo:r.modo==="alcanzado"?"alcanzado":"marginal",lista:a},!Rt(e.valor))throw i(`\xAB${t}\xBB: con tramos, el valor va en cada tramo.`)}return n}function nh(e,o){if(Rt(e))return;if(!rt(e))throw i("\xABliquidacion\xBB: un objeto {origen, importe, fecha, agente, campos, estados, lineas, reglas}.");if(nt(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":Ri(e.agente,"liquidacion.agente"),n=N=>o.find(j=>j.clave===N&&!j.archivado),r=(N,j,S,R)=>{let F=n(N);if(!F||!S(F))throw i(`\xABliquidacion.${j}\xBB: ${R} de este m\xF3dulo.`);return F.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(!rt(e.campos))throw i("\xABliquidacion.campos\xBB: {agente?, periodo, estado, total}.");nt(e.campos,["agente","periodo","estado","total"],"liquidacion.campos");let c={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=>Ks.includes(N.tipo),"un n\xFAmero o importe")};if(Rt(e.campos.agente)||(c.agente=r(e.campos.agente,"campos.agente",s,"una relaci\xF3n simple")),t!=="_dueno"&&!c.agente)throw i("\xABliquidacion.campos.agente\xBB: con el agente en una relaci\xF3n del origen, la relaci\xF3n de aqu\xED al mismo m\xF3dulo.");let d=n(c.estado),u=new Set((d.opciones??[]).map(N=>N.valor));if(!rt(e.estados))throw i("\xABliquidacion.estados\xBB: {borrador, aprobada, cerrada, pagada} con opciones de su selecci\xF3n.");nt(e.estados,[...Ys],"liquidacion.estados");let p={};for(let N of Ys){let j=e.estados[N];if(typeof j!="string"||!u.has(j))throw i(`\xABliquidacion.estados.${N}\xBB: una opci\xF3n de \xAB${d.etiqueta}\xBB.`);p[N]=j}if(new Set(Object.values(p)).size!==Ys.length)throw i("\xABliquidacion.estados\xBB: una opci\xF3n distinta para cada estado.");if(!rt(e.lineas))throw i("\xABliquidacion.lineas\xBB: {subtabla, origen, base, comision, regla?}.");nt(e.lineas,["subtabla","origen","base","comision","regla"],"liquidacion.lineas");let m=n(e.lineas.subtabla);if(m?.tipo!=="subtabla")throw i("\xABliquidacion.lineas.subtabla\xBB: una subtabla de este m\xF3dulo.");let h=(m.columnas??[]).filter(N=>!N.archivado),b=(N,j,S,R)=>{let F=h.find(I=>I.clave===N);if(!F||!S(F))throw i(`\xABliquidacion.lineas.${j}\xBB: ${R} de \xAB${m.etiqueta}\xBB.`);return F.clave},y={subtabla:m.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=>Ks.includes(N.tipo),"una columna num\xE9rica"),comision:b(e.lineas.comision,"comision",N=>Ks.includes(N.tipo),"una columna num\xE9rica")};if(Rt(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>oh)throw i(`\xABliquidacion.reglas\xBB: de 1 a ${oh}.`);let v=e.reglas.map(Sv),w={origen:e.origen,importe:Ri(e.importe,"liquidacion.importe"),fecha:Ri(e.fecha,"liquidacion.fecha"),agente:t,campos:c,estados:p,lineas:y,reglas:v};return Rt(e.cuentan)||(w.cuentan=rh(e.cuentan,"liquidacion.cuentan")),w}var Ys,oh,th,Ks,jv,rt,Rt,nt,Ri,rh,Zs,ih=f(()=>{q();Ys=["borrador","aprobada","cerrada","pagada"],oh=20,th=20,Ks=["numero","importe","porcentaje"],jv=/^[a-z][a-z0-9_]{0,40}$/,rt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Rt=e=>e==null||e==="",nt=(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.`)},Ri=(e,o)=>{if(typeof e!="string"||!jv.test(e))throw i(`\xAB${o}\xBB: falta o no es v\xE1lido.`);return e},rh=(e,o)=>{if(!rt(e))throw i(`\xAB${o}\xBB: {campo, valores}.`);if(nt(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:Ri(e.campo,`${o}.campo`),valores:[...new Set(e.valores)]}},Zs=(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 sh(e,o){if(ah(e))return;if(!ec(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 c=t(a);if(c?.tipo!=="fecha")throw i(`\xABcuota.${s}\xBB: una fecha de este m\xF3dulo.`);return c.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(ec(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(!ec(a.valores)||!Object.keys(a.valores).length)throw i("\xABcuota.periodicidad.valores\xBB: {opci\xF3n: periodo}.");let c=new Set((s.opciones??[]).map(d=>d.valor));for(let[d,u]of Object.entries(a.valores)){if(!c.has(d))throw i(`\xABcuota.periodicidad.valores\xBB: \xAB${d.slice(0,40)}\xBB no es una opci\xF3n de \xAB${s.etiqueta}\xBB.`);if(!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(!ah(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,ec,ah,ch=f(()=>{q();Zr=["semanal","quincenal","mensual","bimestral","trimestral","semestral","anual"],ec=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ah=e=>e==null||e===""});function dh(e,o){if(e==null)return;if(!uh(e))throw i("\xABpapel\xBB: {tipo, campos} o null.");let t=Object.keys(e).find(c=>c!=="tipo"&&c!=="campos"&&c!=="atributos");if(t)throw i(`\xABpapel\xBB: \xAB${t}\xBB no se reconoce.`);let n=typeof e.tipo=="string"?oc[e.tipo]:void 0;if(!n||!Object.hasOwn(oc,e.tipo))throw i(`\xABpapel.tipo\xBB: uno de ${Object.keys(oc).join(", ")}.`);let r=e.campos??{};if(!uh(r))throw i("\xABpapel.campos\xBB: {campo est\xE1ndar: clave del campo}.");let a={};for(let[c,d]of Object.entries(r)){let u=Object.hasOwn(n.campos,c)?n.campos[c]:void 0;if(!u)throw i(`\xABpapel.campos\xBB: \xAB${c}\xBB no es un campo de \xAB${n.etiqueta}\xBB (${Object.keys(n.campos).join(", ")}).`);if(d==null||d==="")continue;let p=o.find(m=>m.clave===d&&!m.archivado);if(!p)throw i(`\xABpapel\xBB: ${u.etiqueta} apunta a \xAB${String(d)}\xBB, que no es un campo vivo de este m\xF3dulo.`);if(!u.tipos.includes(p.tipo))throw i(`\xABpapel\xBB: ${u.etiqueta} tiene que ser un campo de tipo ${u.tipos.join(" o ")} (\xAB${p.etiqueta}\xBB es ${p.tipo}).`);a[c]=p.clave}for(let[c,d]of Object.entries(n.campos))if(d.obligatorio&&!a[c])throw i(`\xABpapel\xBB: falta el campo de ${d.etiqueta}.`);let s=Av(n,e.atributos,o);return s?{tipo:e.tipo,campos:a,atributos:s}:{tipo:e.tipo,campos:a}}function Av(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(c=>c.clave===a&&!c.archivado):void 0;if(!s)throw i(`\xABpapel.atributos\xBB: \xAB${String(a)}\xBB no es un campo vivo de este m\xF3dulo.`);if(!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 lh,Ov,oc,uh,ph=f(()=>{q();lh={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"]}},Ov={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"]}},oc={cerradura:{etiqueta:"Cerradura",campos:{nombre:{etiqueta:"Nombre",tipos:["texto"],obligatorio:!0},identificador:{etiqueta:"Identificador",tipos:["texto","codigo","numero","dispositivo"]},ubicacion:{etiqueta:"Ubicaci\xF3n",tipos:["texto"]}}},dispositivo:{etiqueta:"Dispositivo",campos:{nombre:{etiqueta:"Nombre",tipos:["texto"],obligatorio:!0},identificador:{etiqueta:"Identificador",tipos:["texto","codigo","dispositivo"]},canal:{etiqueta:"Canal",tipos:["numero"]}}},clientes:{etiqueta:"Clientes",campos:lh},proveedores:{etiqueta:"Proveedores",campos:lh},catalogo:{etiqueta:"Cat\xE1logo",campos:Ov,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"]}}}},uh=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)});function Yr(e,o,t=!1){if(e!=null){if(!Array.isArray(e)||e.length>fh)throw i(`${o}: el filtro, una lista de hasta ${fh} 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"||!(Ge.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"||!mh.includes(s.op))throw i(`${a}: \xABop\xBB, una de ${mh.join(", ")}.`);let c=s.op;if(c==="vacio"||c==="no_vacio")return{campo:s.campo,op:c};let d=u=>typeof u=="string"&&u.length<=200||typeof u=="number"&&Number.isFinite(u)||typeof u=="boolean";if(c==="en"||c==="no_en"){if(!Array.isArray(s.valor)||!s.valor.length||s.valor.length>50||!s.valor.every(u=>d(u)&&typeof u!="boolean"))throw i(`${a}: \xAB${c}\xBB lleva una lista de valores (hasta 50).`);return{campo:s.campo,op:c,valor:s.valor}}if(!d(s.valor))throw i(`${a}: \xAB${c}\xBB lleva un valor (texto, n\xFAmero o s\xED/no).`);return{campo:s.campo,op:c,valor:s.valor}})}}function _h(e,o=!1){if(typeof e=="string"&&(vh.has(e)||Pv.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"||!yh.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 ac(e,o,t=!1){if(typeof e!="object"||e===null||Array.isArray(e))throw i("Definici\xF3n no v\xE1lida.");let n=e,r=_h(n.clave,t);if(!Array.isArray(n.campos))throw i("Faltan los campos.");let a=n.campos.map((s,c)=>nr(s,c,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 $h(e,o){if(typeof e!="object"||e===null||Array.isArray(e))throw i("Definici\xF3n no v\xE1lida.");let t=e,n=_h(t.clave,o.interno===!0),r=it(t.nombre,"el nombre",60),a=it(t.nombre_plural??t.nombre,"el nombre en plural",60),s=it(t.descripcion??"","la descripci\xF3n",500,!0),c=typeof t.icono=="string"&&ic.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=xh(ac(t,o.modulosDelEspacio,o.interno),n,o.camposRelacion);if(u.filter(T=>!T.archivado&&T.opciones?.some(J=>J.hecho)).length>1)throw i("Solo una selecci\xF3n puede marcar estados como \xABhechos\xBB.");if(u.filter(T=>!T.archivado&&T.proximaAccion).length>1)throw i("Solo una fecha puede ser la de la pr\xF3xima acci\xF3n.");let p=new Set;for(let T of u){if(p.has(T.clave))throw i(`El campo \xAB${T.clave}\xBB est\xE1 repetido.`);p.add(T.clave)}let m=u.filter(T=>!T.archivado);for(let T of m)for(let J of Cs(T)){let le=m.find(No=>No.clave===J.relacion);if(!le||le.clave===T.clave||le.tipo!=="relacion"||le.multiple&&!T.multiple)throw i(`\xAB${T.etiqueta}\xBB: un origen m\xFAltiple necesita tambi\xE9n un destino m\xFAltiple.`)}if(cm(m),m.length===0)throw i("El m\xF3dulo necesita al menos un campo.");for(let T of m.filter(J=>J.tipo==="busqueda")){let J=m.find(le=>le.clave===T.desde);if(!J||J.tipo!=="relacion")throw i(`\xAB${T.etiqueta}\xBB: tiene que salir de un campo de relaci\xF3n de este m\xF3dulo.`)}for(let T of m.filter(J=>J.tipo==="qr"&&J.destino==="campo"&&J.campo))if(!m.find(le=>le.clave===T.campo))throw i(`\xAB${T.etiqueta}\xBB: el campo \xAB${T.campo}\xBB no existe en este m\xF3dulo.`);if(m.length>o.topeCampos)throw new z(400,"tope_campos",`Como mucho ${o.topeCampos} campos por m\xF3dulo en tu plan.`,!0,{topePlan:{clave:"campos",tope:o.topeCampos,solicitado:m.length}});for(let T of o.anterior??[]){let J=u.find(le=>le.clave===T.clave);if(!J)throw i(`El campo \xAB${T.etiqueta}\xBB no se quita: se archiva.`);if(J.tipo!==T.tipo&&!Wv(T.tipo,J.tipo))throw i(`\xAB${T.etiqueta}\xBB no puede pasar de ${T.tipo} a ${J.tipo}.`)}let h=t.articulo==="un"||t.articulo==="una"?t.articulo:null,b=vi(t.ficha,u),y=Hr(t.impresion,u),v=gf(t.validaciones,u.filter(T=>!T.archivado));_f(u);for(let T of u){if(T.tipo!=="contador"||!T.alMarcar)continue;let J=u.find(le=>le.clave===T.alMarcar&&!le.archivado);if(J?.tipo!=="booleano"&&J?.tipo!=="hecho")throw i(`\xAB${T.etiqueta}\xBB: \xABal marcar\xBB tiene que ser un s\xED/no o un \xABhecho\xBB de este m\xF3dulo.`)}let w=Qm(t.vistas,u),N=Tf(t.conversiones),j=Lf(t.encadenar,u),S=Bf(t.plantillas_hijos),R=zv(t.campo_ambito,u),F=Hf(t.publico,u),I=mi(t.recurso,u),_=fi(t.reserva,u),E=Qf(t.asignacion,u),g=Jf(t.pertenencia,u),x=Zf(t.stock,u),O=nh(t.liquidacion,u),k=wm(t.sucesion),L=Nm(t.liquidacion_v2,u);if(O&&L)throw i("Elige una versi\xF3n de liquidaci\xF3n por m\xF3dulo.");let V=sh(t.cuota,u),U=xm(t.precios,u),be=Ni(t.relacionadas,u),Be=$i(t.siguientes),br=dh(t.papel,u),X=Js(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 Ve=t.portal??void 0,Ue;if(t.portal_campos!==void 0&&t.portal_campos!==null){let T=t.portal_campos;if(!Ve)throw i("\xABportal_campos\xBB va con \xABportal\xBB.");if(typeof T!="object"||Array.isArray(T)||Object.keys(T).length>u.length)throw i("\xABportal_campos\xBB: clave del campo \u2192 rellenar, ver o no.");for(let[J,le]of Object.entries(T)){if(!u.some(No=>No.clave===J))throw i(`\xABportal_campos\xBB: el m\xF3dulo no tiene el campo \xAB${J.slice(0,40)}\xBB.`);if(le!=="rellenar"&&le!=="ver"&&le!=="no")throw i(`\xABportal_campos.${J.slice(0,40)}\xBB: rellenar, ver o no.`)}Ue={...T}}let Do;if(t.funcionesNativas!==void 0){if(!t.funcionesNativas||typeof t.funcionesNativas!="object"||Array.isArray(t.funcionesNativas)||Object.entries(t.funcionesNativas).some(([T,J])=>!["relacionadas","siguientes"].includes(T)||!Array.isArray(J)||J.length>(T==="relacionadas"?20:5)))throw i("Las funciones nativas necesitan relacionadas o siguientes declarados.");Do=structuredClone(t.funcionesNativas)}return{clave:n,nombre:r,nombre_plural:a,articulo:h,descripcion:s,icono:c,...d!==void 0?{color:d}:{},campos:Cf(qf(u)).map(T=>{if(T.tipo!=="busqueda")return T;let{origen:J,...le}=T;return le}),paginas:t.paginas===!0,...b?{ficha:b}:{},...y?{impresion:y}:{},...v?{validaciones:v}:{},...w?{vistas:w}:{},...N?{conversiones:N}:{},...j?{encadenar:j}:{},...S?{plantillas_hijos:S}:{},...R?{campo_ambito:R}:{},...F?{publico:F}:{},...I?{recurso:I}:{},..._?{reserva:_}:{},...E?{asignacion:E}:{},...g?{pertenencia:g}:{},...x?{stock:x}:{},...O?{liquidacion:O}:{},...k?{sucesion:k}:{},...L?{liquidacion_v2:L}:{},...V?{cuota:V}:{},...U?{precios:U}:{},...be?{relacionadas:be}:{},...Be?{siguientes:Be}:{},...br?{papel:br}:{},...X?{personas:X}:{},...Ve?{portal:Ve}:{},...Ue&&Object.keys(Ue).length?{portal_campos:Ue}:{},...Do?{funcionesNativas:Do}:{}}}function zv(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 nr(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(r.destinos!==void 0){if(r.tipo!=="relacion"||r.multiple===!0||r.camposVinculo!==void 0||!Array.isArray(r.destinos)||!r.destinos.length||r.destinos.length>8||r.destinos.some(y=>typeof y!="string")||new Set(r.destinos).size!==r.destinos.length)throw i("La relaci\xF3n polim\xF3rfica necesita entre 1 y 8 destinos distintos y un solo registro.");let{destinos:u,relacion:p,multiple:m,alBorrar:h,...b}=r;return nr({...b,tipo:"subtabla",polimorfica:!0,columnas:u.map(y=>({clave:`a_${y}`,etiqueta:y,tipo:"relacion",relacion:y,alBorrar:h}))},o,t,n)}if(r.camposVinculo!==void 0){if(r.tipo!=="relacion"||r.multiple!==!0||!Array.isArray(r.camposVinculo)||!r.camposVinculo.length||r.camposVinculo.length>=tc)throw i("Los datos del v\xEDnculo necesitan una relaci\xF3n m\xFAltiple y entre 1 y 29 campos.");let{camposVinculo:u,relacion:p,tipoContacto:m,alBorrar:h,multiple:b,...y}=r;return nr({...y,tipo:"subtabla",vinculo:!0,columnas:[{clave:"destino",etiqueta:r.etiqueta,tipo:"relacion",relacion:p,tipoContacto:m,alBorrar:h,obligatorio:!0},...u]},o,t,n)}if(typeof r.clave=="string"&&vh.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"||!Ge.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(!rc.includes(a))throw i(`Tipo de campo no v\xE1lido: ${String(r.tipo)}.`);let s={clave:r.clave,etiqueta:it(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=Zm(r.ajustesNativos);for(let u of Object.values(s.ajustesNativos??{})){let p={...r,...u,ajustesNativos:void 0};for(let[m,h]of Object.entries(u))h===null&&delete p[m];nr(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>no||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}if(r.archivado===!0&&(s.archivado=!0),r.seccion!==void 0&&r.seccion!==""&&(s.seccion=it(r.seccion,"la secci\xF3n",60)),r.ayuda!==void 0&&r.ayuda!==""&&(s.ayuda=it(r.ayuda,"la ayuda",200)),(a==="fecha"||a==="fecha_hora")&&r.proximaAccion===!0&&(s.proximaAccion=!0),a==="numero"&&r.sinMiles===!0&&(s.sinMiles=!0),r.pasoMinutos!==void 0&&r.pasoMinutos!==null){let u=r.pasoMinutos;if(a!=="hora"||typeof u!="number"||!Number.isInteger(u)||u<1||u>60||60%u!==0)throw i(`\xAB${s.etiqueta}\xBB: el paso de la hora, en minutos que dividan la hora (1, 5, 10, 15, 30 o 60).`);u>1&&(s.pasoMinutos=u)}if(r.puertaExtra!==void 0&&typeof r.puertaExtra!="boolean")throw i("\xABpuertaExtra\xBB debe ser s\xED o no.");a==="dispositivo"&&r.conector==="ttlock"&&r.puertaExtra===!0&&(s.puertaExtra=!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(r.transiciones!==void 0&&a!=="seleccion")throw i("Las transiciones requieren una selecci\xF3n.");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;if(s.opciones=r.opciones.map(p=>{let m=typeof p=="string"?{valor:p,etiqueta:p}:p,h=it(m.valor??m.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:it(m.etiqueta??h,"una opci\xF3n",80)};return typeof m.color=="string"&&Tv.test(m.color)&&(b.color=m.color),a==="seleccion"&&m.hecho===!0&&(b.hecho=!0),a==="seleccion"&&r.embudo===!0&&Ef(m,b,s.etiqueta),b}),a==="seleccion"&&r.embudo===!0&&(s.embudo=!0),r.transiciones!==void 0){if(a!=="seleccion")throw i("Las transiciones requieren una selecci\xF3n.");s.transiciones=xf(r.transiciones,s)}}if(a==="relacion"){let u=r.relacion;if(!(typeof u=="string"&&(qv.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"||!Bv.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(m=>!["relacion","campo","alternativa"].includes(m))||typeof u.relacion!="string"||!Ge.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 m=u.alternativa;if(!m||typeof m!="object"||Array.isArray(m)||Object.keys(m).some(h=>h!=="relacion"&&h!=="campo")||typeof m.relacion!="string"||!Ge.test(m.relacion)||typeof m.campo!="string"||!/^[a-z][a-z0-9_.]{0,80}$/.test(m.campo))throw i("La alternativa de autocompletado necesita relacion y campo.");p={relacion:m.relacion,campo:m.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=nr({...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(!Ge.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"||!Ge.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"||!Ge.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(!Ev.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(wh.includes(a)&&delete s.obligatorio,a==="subtabla"){if(!Array.isArray(r.columnas)||r.columnas.length===0||r.columnas.length>tc)throw i(`\xAB${s.etiqueta}\xBB: entre 1 y ${tc} columnas.`);let u=new Set(["padre"]);if(s.columnas=r.columnas.map((h,b)=>{let y=nr(h,b,t,n);if(!Lv.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"&&1+Nh(y)>gh)throw i(`\xAB${s.etiqueta}\xBB: como mucho ${gh} niveles de subtablas (cap\xEDtulo \u2192 subcap\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}),r.vinculo!==void 0){if(r.vinculo!==!0)throw i("\xABvinculo\xBB debe ser true.");let h=s.columnas[0];if(h?.clave!=="destino"||h.tipo!=="relacion"||h.multiple||h.archivado||!h.obligatorio||s.columnas.slice(1).some(b=>["relacion","subtabla","resumen","formula"].includes(b.tipo)))throw i("El v\xEDnculo necesita primero una relaci\xF3n obligatoria \xABdestino\xBB y despu\xE9s sus campos de datos.");s.vinculo=!0}if(r.polimorfica!==void 0){if(r.polimorfica!==!0||r.vinculo||s.columnas.length>8||s.columnas.some(h=>h.tipo!=="relacion"||h.multiple||h.obligatorio||h.archivado)||new Set(s.columnas.map(h=>h.relacion)).size!==s.columnas.length)throw i("La relaci\xF3n polim\xF3rfica lleva hasta ocho columnas de relaci\xF3n simple opcionales y distintas.");s.polimorfica=!0}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 v=`\xAB${s.etiqueta}\xBB, columna \xAB${h.etiqueta}\xBB`;if(h.tipo!=="relacion")throw i(`${v}: \xABcopiar\xBB va en una columna de relaci\xF3n.`);if(typeof y!="object"||Array.isArray(y)||Object.keys(y).length>hh)throw i(`${v}: \xABcopiar\xBB, un objeto columna \u2192 campo (hasta ${hh}).`);for(let[w,N]of Object.entries(y)){let j=s.columnas.find(S=>S.clave===w);if(!j||j.tipo==="relacion"||j.tipo==="formula")throw i(`${v}: \xAB${w.slice(0,40)}\xBB no es una columna que se pueda rellenar.`);if(typeof N!="string"||!Ge.test(N))throw i(`${v}: el campo de \xAB${w}\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 v=`\xAB${s.etiqueta}\xBB, columna \xAB${h.etiqueta}\xBB`;if(h.tipo!=="articulo")throw i(`${v}: \xABrellenar\xBB va en una columna de art\xEDculo.`);if(typeof y!="object"||Array.isArray(y)||Object.keys(y).length>bh.length*2)throw i(`${v}: \xABrellenar\xBB, un objeto columna \u2192 dato del art\xEDculo.`);for(let[w,N]of Object.entries(y)){let j=s.columnas.find(S=>S.clave===w);if(!j||["relacion","articulo","formula","subtabla","resumen"].includes(j.tipo))throw i(`${v}: \xAB${w.slice(0,40)}\xBB no es una columna que se pueda rellenar.`);if(!bh.includes(N))throw i(`${v}: \xAB${w.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"&&Dv.test(r.hijo)&&(s.hijo=r.hijo);let m=Um(r.impresion,s.columnas);m&&(s.impresion=m),delete s.obligatorio}if(a==="autonumero"){let u=ji(r.visibleSi,s.etiqueta);u&&(s.visibleSi=u)}if(!Ym({tipo:a})){let u=ji(r.visibleSi,s.etiqueta);u&&(s.visibleSi=u);let p=ji(r.obligatorioSi,s.etiqueta);if(p&&(s.obligatorioSi=p),r.patron!==void 0&&r.patron!==null&&r.patron!==""){if(!uf.includes(a))throw i(`\xAB${s.etiqueta}\xBB: un patr\xF3n solo vale para textos, correos, tel\xE9fonos, webs y c\xF3digos.`);let h=pf(r.patron,s.etiqueta);h&&(s.patron=h)}if(r.unico===!0){if(!df.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 m=mf(r.porDefecto,s);m&&(s.porDefecto=m)}let c=jh(r.permisos,s.etiqueta);if(c&&(s.permisos=c),r.grupo!==void 0&&r.grupo!==null&&r.grupo!==""){if(typeof r.grupo!="string"||!Mv.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(!Iv.includes(a))throw i(`\xAB${s.etiqueta}\xBB: solo se enmascaran textos, correos, tel\xE9fonos y c\xF3digos.`);s.enmascarado=!0}let d=yf(r.depende,s);if(d&&(s.depende=d),a==="archivo"&&(s.enTabla=!1,delete s.obligatorio),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>no)throw i(`\xAB${s.etiqueta}\xBB: escribe la f\xF3rmula (hasta ${no} caracteres).`);s.formula=r.formula.trim(),delete s.obligatorio}if(a==="resumen"){let u=r.calculo;if(typeof r.de!="string"||!yh.test(r.de)||typeof r.via!="string"||!Ge.test(r.via)||!nc.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"||!Ge.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"||!Ge.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=Yr(r.filtro,`\xAB${s.etiqueta}\xBB`);p?s.filtro=p:delete s.filtro,delete s.obligatorio}if(a==="dispositivo"){if(!Rv.includes(r.conector))throw i(`\xAB${s.etiqueta}\xBB: elige de qu\xE9 conexi\xF3n es el aparato (TTLock o Shelly).`);s.conector=r.conector}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"||!Ge.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 rc,wh,nc,mh,fh,Ev,qv,Rv,kv,vh,Pv,ic,Ge,yh,Tv,Mv,Iv,it,Dv,Lv,hh,gh,Nh,bh,tc,Fv,Wv,Bv,Ym,Kr=f(()=>{vm();$m();Cm();nf();Bs();lm();q();bi();ff();Sh();Ds();bf();Nf();jf();Rf();Mf();zf();Vf();Xf();As();Gf();eh();ih();ch();xi();ph();Ch();rc=["texto","texto_largo","numero","importe","fecha","fecha_hora","booleano","seleccion","seleccion_multiple","etiquetas","url","correo","telefono","relacion","archivos","archivo","busqueda","resumen","duracion","hecho","porcentaje","valoracion","contador","cronometro","secreto","color","ubicacion","checklist","codigo","firma","hora","articulo","dispositivo","creado_el","creado_por","modificado_el","modificado_por","autonumero","formula","subtabla","boton","qr"],wh=["creado_el","creado_por","modificado_el","modificado_por","autonumero"],nc=["recuento","suma","minimo","maximo","ultimo","media","media_ponderada"],mh=["igual","distinto","en","no_en","vacio","no_vacio","mayor","menor"],fh=5;Ev=["avisar","desvincular","impedir"],qv=["companies","contacts","deals"],Rv=["ttlock","shelly"],kv=["id","numero","sales_id","creado","actualizado","espacio_id","modulo_id","datos","_color_tarjeta"],vh=new Set([...kv,"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","es_plantilla"]),Pv=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"]),ic=["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"],Ge=/^[a-z][a-z0-9_]{0,40}$/,yh=/^[a-z][a-z_]{1,30}$/,Tv=/^#[0-9a-fA-F]{6}$/,Mv=/^[a-z][a-z_]{0,29}$/,Iv=["texto","correo","telefono","codigo"],it=(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};Dv=/^sub_[a-z]{8}$/,Lv=["texto","texto_largo","numero","importe","fecha","fecha_hora","booleano","seleccion","url","correo","telefono","duracion","porcentaje","valoracion","color","codigo","formula","hora","relacion","articulo","subtabla","resumen"],hh=20,gh=3,Nh=e=>e.tipo!=="subtabla"?0:1+Math.max(0,...(e.columnas??[]).map(o=>Nh(o))),bh=["nombre","referencia","codigo","precio","iva_pct"],tc=30;Fv=[["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"],["texto","dispositivo"],["dispositivo","texto"]],Wv=(e,o)=>Fv.some(([t,n])=>t===e&&n===o),Bv=/^[a-z0-9][a-z0-9-]{0,59}$/;Ym=e=>e.tipo==="busqueda"||e.tipo==="resumen"||e.tipo==="formula"||e.tipo==="subtabla"||e.tipo==="boton"||e.tipo==="qr"||e.tipo==="archivo"||wh.includes(e.tipo)});function Oh(e){let o=Lo(),t=(e==="contacts"?Vv:Uv).map(([n,r])=>({clave:n,etiqueta:co(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",...Jv(e).has(n)?{}:{permisos:{administrador:"lectura",miembro:"lectura",lectura:"lectura"}}}));return{id:0,clave:`@${e}`,nombre:co(o,e==="contacts"?"Persona":"Empresa"),nombre_plural:co(o,e==="contacts"?"Personas":"Empresas"),descripcion:"",icono:e==="contacts"?"users":"building-2",estado:"publicado",campos:t}}var ki,Vv,Uv,Jv,Ah=f(()=>{mn();ki=[["address","Direcci\xF3n"],["zipcode","C\xF3digo postal"],["city","Ciudad"],["country","Pa\xEDs"]],Vv=[["first_name","Nombre"],["last_name","Apellidos"],["title","Cargo"],["correo","Correo"],["telefono","Tel\xE9fono"],...ki,["background","Contexto"],["nif","Identificador fiscal"],["pais_fiscal","Pa\xEDs fiscal"]],Uv=[["name","Nombre"],["phone_number","Tel\xE9fono"],["website","Web"],...ki,["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"]],Jv=e=>new Set(e==="contacts"?["first_name","last_name","title","telefono",...ki.map(([o])=>o),"background"]:["name","phone_number","website",...ki.map(([o])=>o),"description","persona_first_name"])});function Qr(e){let o=new Map(Jr(e)?Oh(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=(fm.find(a=>a.clave===e)?.campos??[]).map(a=>({...a,...o.has(a.clave)?{etiqueta:o.get(a.clave)}:Object.hasOwn(t,a.clave)?{etiqueta:co(Lo(),t[a.clave])}:{}})),r=Jr(e)?Xv(e).map(a=>({...a,etiqueta:co(Lo(),a.etiqueta),editable:!1,ordenable:!1,filtrable:!1,enTabla:!1})):[];return[...n,...r,...e==="companies"?Gv.map(a=>({...a,etiqueta:co(Lo(),a.etiqueta),editable:!1,ordenable:!1,filtrable:!1,enTabla:!1})):[]]}var Jr,Qv,Gv,Hv,Xv,wi=f(()=>{hm();Ah();mn();Jr=e=>e==="contacts"||e==="companies",Qv=[{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"}],Gv=[{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"}],Hv=[{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"}],Xv=e=>[...Qv.filter(o=>e==="contacts"||["nombre","direccion"].includes(o.clave)),...e==="companies"?Hv:[]]});function xh(e,o,t){let n=(a,s,c,d)=>{if(a.tipo!=="busqueda"||a.archivado)return a;let u=`${c}.${a.clave}`;if(d.length>=2||d.includes(u))throw i(`\xAB${a.etiqueta}\xBB: solo se encadena una b\xFAsqueda a un nivel.`);let p=s.find(b=>b.clave===a.desde&&!b.archivado&&b.tipo==="relacion");if(!p?.relacion)return a;let m=p.relacion,h;if(m.startsWith("mod_")){let b=m.slice(4),y=b===o?e:t?.get(b);if(!y)return a;if(h=y.find(v=>v.clave===a.campo&&!v.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=Qr(m).find(y=>y.clave===a.campo)??t?.get(`@${m}`)?.find(y=>y.clave===a.campo&&!y.archivado);if(!b&&Ee(a.campo)&&!t?.has(`@${m}`))return a;if(!b)throw i(`\xAB${a.etiqueta}\xBB: ese campo no existe en ${m}.`);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 Yv(r),r}function Yv(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 Ch=f(()=>{Br();q();wi()});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 af(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.transiciones||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 c=r.tipo==="busqueda"?Ee(o[r.desde??""]):null,d=r.siVacio?Ee(o[r.siVacio]):null;if(r.tipo==="busqueda"&&(!c||r.siVacio&&!d))throw i("La b\xFAsqueda propia necesita relaciones y alternativas propias de la misma ra\xEDz.");return{...structuredClone(r),...c?{desde:c}:{},...d?{siVacio:d}:{},clave:Ee(o[r.clave]),visibleSi:s,...r.obligatorioSi?{obligatorioSi:r.obligatorioSi.map(n)}:{}}})}var Br=f(()=>{q()});function jh(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(!ey(n))throw new z(400,"peticion_invalida",`\xAB${o}\xBB: el papel \xAB${n.slice(0,30)}\xBB no se puede restringir.`);if(!Kv.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 Kv,Zv,ey,PL,sc,TL,Sh=f(()=>{ci();q();Kv=["oculto","lectura"],Zv=["administrador","miembro","lectura"],ey=e=>Zv.includes(e)||/^p_[a-z]{1,12}$/.test(e),PL=A`coalesce(current_setting('app.extension', true), '') <> ''`,sc=class extends Map{get(){return"no"}},TL=new sc});function Eh(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 qh=f(()=>{q()});function Rh(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)||!nc.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.");Yr(o.filtro,"Resumen")}var kh=f(()=>{q();Kr()});function Ph(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 Th=f(()=>{q()});var Mh,Ih=f(()=>{Mh=/^funciones\.[a-z0-9][a-z0-9-]{0,59}\.[a-z][a-z0-9_]{0,40}$/});function ir(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(!Mo(t)||Object.keys(t).some(r=>!["fuente","filtro","campos"].includes(r))||typeof t.fuente!="string"||!ty.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&&(!Mo(t.filtro)||JSON.stringify(t.filtro).length>4e3))throw i("Filtro de origen no v\xE1lido.");if(!Mo(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(!oy.test(r)||["id","objeto"].includes(r)||!Mo(a)||Object.keys(a).some(c=>!["resumen","formula","permiso","casos","defecto","campo","soloFiltro","valor","alternativas","conversiones","condicion","equivalencias","etiqueta","opciones"].includes(c))||["campo","valor","alternativas","condicion","casos","resumen","formula"].filter(c=>Object.hasOwn(a,c)).length!==1||a.campo!==void 0&&(typeof a.campo!="string"||a.campo.length>125)||Object.hasOwn(a,"valor")&&a.valor!==null&&!["string","number","boolean"].includes(typeof a.valor)||a.alternativas!==void 0&&(!Array.isArray(a.alternativas)||a.alternativas.length!==2||a.alternativas.some(c=>typeof c!="string"||c.length>125))||a.condicion!==void 0&&(!Mo(a.condicion)||JSON.stringify(a.condicion).length>4e3)||a.conversiones!==void 0&&(!Mo(a.conversiones)||!Array.isArray(a.alternativas)||Object.entries(a.conversiones).some(([c,d])=>!a.alternativas.includes(c)||!Mo(d)||Object.keys(d).length>100||Object.values(d).some(u=>typeof u!="string")))||a.permiso!==void 0&&(typeof a.permiso!="string"||!Mh.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&&(!Mo(a.opciones)||Object.keys(a.opciones).length>100||Object.values(a.opciones).some(c=>typeof c!="string"))||a.equivalencias!==void 0&&(!Mo(a.equivalencias)||!a.campo||Object.keys(a.equivalencias).length>100||Object.values(a.equivalencias).some(c=>typeof c!="string")))throw i("Campo de proyecci\xF3n no v\xE1lido.");a.resumen!==void 0&&Rh(a.resumen);let s=a.formula===void 0?void 0:Eh(a.formula);if(a.casos!==void 0)Ph(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 Mo,oy,ty,Pi=f(()=>{qh();kh();Th();q();Ih();Mo=e=>!!e&&typeof e=="object"&&!Array.isArray(e),oy=/^[a-z][a-z0-9_]{0,40}$/,ty=/^(contacts|companies|deals|mod_(?!sub_)[a-z][a-z0-9_]{0,40})$/});function zh(e){let o=_e(e,"definici\xF3n");ze(o,["titulo","fuente","origenes","metrica","agrupar","dividir","filtro","periodo","grafico","top","comparar","meta","tendencia","ejes_burbujas",...Dh],"definici\xF3n");let t=qe(o.fuente,"fuente",60),n=ir(o.origenes);if(t==="combinada"!=!!n)throw i("La fuente combinada necesita sus or\xEDgenes.");if(t!=="combinada"&&!lc.includes(t)&&!/^mod_(?!sub_)[a-z][a-z0-9_]{0,40}$/.test(t))throw i("\xABfuente\xBB no v\xE1lida.");let r=_e(o.metrica,"metrica");ze(r,["tipo","campo","por","filtro_a","filtro_b"],"metrica");let a=He(r.tipo,cc,"metrica.tipo"),s={tipo:a,...r.campo!==void 0?{campo:qe(r.campo,"metrica.campo",60)}:{},...r.por!==void 0?{por:qe(r.por,"metrica.por",60)}:{},...r.filtro_a!==void 0&&r.filtro_a!==null?{filtro_a:_e(r.filtro_a,"metrica.filtro_a")}:{},...r.filtro_b!==void 0&&r.filtro_b!==null?{filtro_b:_e(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 c;if(o.agrupar!==void 0&&o.agrupar!==null){let R=_e(o.agrupar,"agrupar");ze(R,["campo","paso"],"agrupar"),c={campo:qe(R.campo,"agrupar.campo",60),...R.paso!==void 0?{paso:He(R.paso,ar,"agrupar.paso")}:{}}}let d;if(o.dividir!==void 0&&o.dividir!==null){let R=_e(o.dividir,"dividir");ze(R,["campo","paso"],"dividir"),d={campo:qe(R.campo,"dividir.campo",60),...R.paso!==void 0?{paso:He(R.paso,ar,"dividir.paso")}:{}}}if(d&&!c)throw i("\xABDividir por\xBB solo se puede usar si se agrupa.");if(c&&d&&c.campo===d.campo)throw i("No se puede agrupar y dividir por el mismo campo.");let u;if(o.meta!==void 0&&o.meta!==null){if(typeof o.meta!="number"||Number.isNaN(o.meta)||o.meta<=0)throw i("\xABmeta\xBB: n\xFAmero mayor que 0.");u=o.meta}let p=o.periodo!==void 0&&o.periodo!==null?uc(o.periodo):void 0,m=He(o.grafico,ry,"grafico"),h={},b={doble_eje:m==="combinado",etiquetas:["barras","barras_horizontales","barras_100","barras_apiladas","barras_agrupadas","cascada","dona","tarta","embudo"].includes(m),zoom:!!c?.paso&&["barras","barras_100","barras_apiladas","barras_agrupadas","lineas","area","area_apilada","area_100","varias_lineas","combinado","cascada"].includes(m),escalonada:m==="lineas"||m==="varias_lineas"};for(let R of Dh){let F=o[R];if(F!==void 0){if(typeof F!="boolean")throw i(`\xAB${R}\xBB: s\xED o no.`);if(!b[R])throw i(`\xAB${R}\xBB no se admite en este gr\xE1fico.`);h[R]=F}}let y;if(m==="burbujas"){let R=_e(o.ejes_burbujas,"ejes_burbujas");ze(R,["x","z"],"ejes_burbujas"),y={x:qe(R.x,"ejes_burbujas.x",60),z:qe(R.z,"ejes_burbujas.z",60)}}else if(o.ejes_burbujas!==void 0)throw i("\xABejes_burbujas\xBB solo se usa en burbujas.");let v=["numero","medidor","numero_tendencia"],w=["cascada","treemap","barras_radiales","burbujas","barras","barras_horizontales","lineas","area","dona","tabla","embudo","tarta","radar","dispersion"],N=["sankey","area_apilada","area_100","barras_100","barras_apiladas","barras_agrupadas","varias_lineas","tabla_dinamica","mapa_calor","combinado"];if(v.includes(m)){if(c)throw i("Un n\xFAmero no se agrupa.");if(d)throw i("Un n\xFAmero no se divide.");if(m==="medidor"&&u===void 0)throw i("El medidor necesita una \xABmeta\xBB num\xE9rica.");if(m==="numero_tendencia"&&!p)throw i("\xABnumero_tendencia\xBB necesita un periodo.")}else if(w.includes(m)){if(!c)throw i("Ese gr\xE1fico necesita \xABagrupar\xBB.");if(d)throw i("Ese gr\xE1fico no admite \xABdividir por\xBB.")}else if(N.includes(m)){if(!c)throw i("Ese gr\xE1fico necesita \xABagrupar\xBB.");if(!d)throw i("Ese gr\xE1fico necesita \xABdividir por\xBB un segundo campo.")}if((m==="area_apilada"||m==="area_100")&&!c?.paso)throw i("Las \xE1reas apiladas requieren agrupar por fecha.");if(o.tendencia!==void 0&&typeof o.tendencia!="boolean")throw i("\xABtendencia\xBB: s\xED o no.");if(o.tendencia&&(m!=="tabla"||!c?.paso))throw i("\xABtendencia\xBB requiere una tabla agrupada por fecha.");if(o.top!==void 0&&(!Number.isSafeInteger(o.top)||o.top<1||o.top>Lh))throw i(`\xABtop\xBB: de 1 a ${Lh}.`);let j=o.comparar==null||typeof o.comparar=="boolean"?o.comparar:He(o.comparar,ny,"comparar");if(typeof j=="string"&&m!=="numero"&&m!=="numero_tendencia"&&(!["barras","lineas","area","varias_lineas"].includes(m)||!c?.paso))throw i("\xABcomparar\xBB requiere agrupar por fecha en un gr\xE1fico temporal.");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(typeof j=="string"&&p&&!p.ultimos&&(!p.desde||!p.hasta))throw i("Para comparar hacen falta las dos fechas del periodo.");if(o.comparar&&p?.preset)throw i("\xABpreset\xBB no se compara (todav\xEDa no se ha acabado).");let S=o.filtro===void 0||o.filtro===null?void 0:_e(o.filtro,"filtro");if(S&&JSON.stringify(S).length>4e3)throw i("\xABfiltro\xBB demasiado grande.");return{titulo:qe(o.titulo??"","titulo"),fuente:t,...n?{origenes:n}:{},metrica:s,...y?{ejes_burbujas:y}:{},...c?{agrupar:c}:{},...d?{dividir:d}:{},...u!==void 0?{meta:u}:{},...S?{filtro:S}:{},...p?{periodo:p}:{},grafico:m,...h,...o.top!==void 0?{top:o.top}:{},...j||j===null?{comparar:j}:{},...o.tendencia?{tendencia:!0}:{}}}function uc(e){let o=_e(e,"periodo");ze(o,["campo","ultimos","proximos","preset","desde","hasta"],"periodo");let t={campo:qe(o.campo,"periodo.campo",60)};if(o.preset!==void 0&&(t.preset=He(o.preset,iy,"periodo.preset")),o.ultimos!==void 0){let r=_e(o.ultimos,"periodo.ultimos");if(ze(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:He(r.unidad,ar,"periodo.ultimos.unidad")}}for(let r of["desde","hasta"])if(o[r]!==void 0){if(typeof o[r]!="string"||!ay.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=_e(o.proximos,"periodo.proximos");if(ze(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:He(r.unidad,ar,"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 cc,ry,ar,lc,ny,Dh,iy,Lh,ay,_e,ze,He,qe,dc=f(()=>{Pi();q();cc=["recuento","suma","media","min","max","minimo","maximo","mediana","porcentaje_total","acumulado","tasa_conversion","media_por","valor_medio_por"],ry=["numero","cascada","treemap","sankey","barras_radiales","burbujas","barras","lineas","dona","tabla","barras_horizontales","barras_100","barras_apiladas","barras_agrupadas","area","area_apilada","area_100","varias_lineas","embudo","medidor","numero_tendencia","tabla_dinamica","mapa_calor","tarta","radar","dispersion","combinado"],ar=["dia","semana","mes","anio"],lc=["companies","contacts","deals","tareas","proyectos"],ny=["anterior","anio_anterior"],Dh=["escalonada","zoom","etiquetas","doble_eje"],iy=["hoy","semana","mes","trimestre","anio"],Lh=50,ay=/^\d{4}-\d{2}-\d{2}$/,_e=(e,o)=>{if(typeof e!="object"||e===null||Array.isArray(e))throw i(`\xAB${o}\xBB tiene que ser un objeto.`);return e},ze=(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.`)},He=(e,o,t)=>{if(typeof e!="string"||!o.includes(e))throw i(`\xAB${t}\xBB no v\xE1lido.`);return e},qe=(e,o,t=80)=>{if(typeof e!="string"||e.length>t)throw i(`\xAB${o}\xBB no v\xE1lido.`);return e}});var pc,Fh=f(()=>{pc=["nada","recientes","vistas"]});function Wh(e,o,t){if(e===void 0)return[];if(!Array.isArray(e)||e.length>o.length)throw i("Fuentes de m\xF3dulo no v\xE1lidas.");let n=new Set;return e.map(r=>{if(!mc(r)||typeof r.modulo!="string"||n.has(r.modulo)||typeof r.conexion!="string"||!t.some(d=>d.clave===r.conexion&&d.tipo==="api")||typeof r.operacion!="string"||!/^[a-zA-Z][a-zA-Z0-9_.-]{0,79}$/.test(r.operacion)||r.filas!==""&&!Ti(r.filas)||!mc(r.mapeo))throw i("La fuente necesita un m\xF3dulo, una conexi\xF3n API, una operaci\xF3n y un mapeo.");let a=o.find(d=>d.clave===r.modulo),s=Object.entries(r.mapeo);if(!a||a.personas||!s.length||s.some(([d,u])=>!a.campos.some(p=>p.clave===d&&cy(p))||!Ti(u)))throw i("La fuente debe mapear campos de datos de un m\xF3dulo propio.");n.add(r.modulo);let c={modulo:r.modulo,conexion:r.conexion,operacion:r.operacion,filas:r.filas,mapeo:Object.fromEntries(s)};if(r.modo==="vivo")return{...c,modo:r.modo};if(r.modo!=="espejo"||typeof r.minutos!="number"||!Number.isInteger(r.minutos)||r.minutos<5||r.minutos>10080||!Ti(r.id_externo)||!mc(r.cursor)||!Ti(r.cursor.ruta)||typeof r.cursor.parametro!="string"||!/^[a-zA-Z_][a-zA-Z0-9_.-]{0,79}$/.test(r.cursor.parametro))throw i("El espejo necesita una clave externa, un cursor y un intervalo entre 5 minutos y 7 d\xEDas.");return{...c,modo:r.modo,minutos:r.minutos,id_externo:r.id_externo,cursor:{ruta:r.cursor.ruta,parametro:r.cursor.parametro}}})}var sy,Ti,mc,cy,Bh=f(()=>{q();sy=new Set(["texto","texto_largo","correo","telefono","codigo","numero","importe","fecha","fecha_hora","booleano","seleccion"]),Ti=e=>typeof e=="string"&&e.length<=160&&/^[a-zA-Z_][a-zA-Z0-9_-]*(\.[a-zA-Z_][a-zA-Z0-9_-]*){0,7}$/.test(e),mc=e=>!!e&&typeof e=="object"&&!Array.isArray(e),cy=e=>!e.archivado&&sy.has(e.tipo)});function Vh(e){if(e===void 0)return[];if(!Array.isArray(e)||e.length>20)throw i("La soluci\xF3n admite hasta 20 conexiones.");let o=new Set;return e.map(t=>{if(!ly(t)||typeof t.clave!="string"||!/^[a-z][a-z0-9_]{0,39}$/.test(t.clave)||["constructor","prototype"].includes(t.clave)||o.has(t.clave)||typeof t.nombre!="string"||!t.nombre.trim()||t.nombre.length>120||t.tipo!=="api"&&t.tipo!=="mcp")throw i("Requisito de conexi\xF3n no v\xE1lido.");return o.add(t.clave),{clave:t.clave,nombre:t.nombre.trim(),tipo:t.tipo}})}var ly,Uh=f(()=>{q();ly=e=>!!e&&typeof e=="object"&&!Array.isArray(e)});function Mi(e){return typeof e=="number"?Number.isInteger(e)&&e>=1&&e<=2147483647:typeof e=="string"&&e.length<=120&&Jh.test(e)}function Qh(e,o){let t=c=>Jh.exec(typeof c=="number"?`${c}.0.0`:c),n=t(e),r=t(o);for(let c=1;c<=3;c++){let d=BigInt(n[c])-BigInt(r[c]);if(d)return d>0?1:-1}if(!n[4]||!r[4])return+!n[4]-+!r[4];let a=n[4].split("."),s=r[4].split(".");for(let c=0;c<Math.min(a.length,s.length);c++){let d=a[c],u=s[c];if(d===u)continue;let p=/^\d+$/.test(d),m=/^\d+$/.test(u);return p&&m?BigInt(d)>BigInt(u)?1:-1:p!==m?p?-1:1:d>u?1:-1}return a.length-s.length}var Jh,fc=f(()=>{Jh=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][\da-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][\da-zA-Z-]*))*))?(?:\+([\da-zA-Z-]+(?:\.[\da-zA-Z-]+)*))?$/});function Gh(e,o){if(e===void 0)return;if(!hc(e)||Object.keys(e).some(r=>r!=="desde"&&r!=="pasos")||!Mi(e.desde)||Qh(e.desde,o)>=0||!Array.isArray(e.pasos)||!e.pasos.length||e.pasos.length>50)throw i("La migraci\xF3n necesita una versi\xF3n anterior y entre 1 y 50 pasos.");let t=new Set,n=e.pasos.map(r=>{if(!hc(r)||Object.keys(r).some(m=>!["tipo","modulo","origen","destino","conversion","equivalencias"].includes(m))||r.tipo!=="renombrar"&&r.tipo!=="convertir"&&r.tipo!=="mover"||!gc(r.modulo)||!gc(r.origen)||!gc(r.destino))throw i("Paso de migraci\xF3n inv\xE1lido.");let{tipo:a,modulo:s,origen:c,destino:d,conversion:u,equivalencias:p}=r;if(a==="convertir"&&(typeof u!="string"||!uy.has(u)))throw i("Conversi\xF3n de migraci\xF3n desconocida.");if(a!=="convertir"&&(u!==void 0||c===d))throw i("El paso necesita dos campos distintos.");if(u==="seleccion"?!hc(p)||!Object.keys(p).length||Object.values(p).some(m=>typeof m!="string"||!m):p!==void 0)throw i("La conversi\xF3n a selecci\xF3n necesita una tabla de equivalencias.");for(let m of new Set([c,d])){let h=`${s}:${m}`;if(t.has(h))throw i("Cada campo puede participar en un solo paso por versi\xF3n.");t.add(h)}return{tipo:a,modulo:s,origen:c,destino:d,...u?{conversion:u}:{},...p?{equivalencias:p}:{}}});return{desde:e.desde,pasos:n}}var hc,gc,uy,Hh=f(()=>{q();fc();hc=e=>!!e&&typeof e=="object"&&!Array.isArray(e),gc=e=>typeof e=="string"&&/^[a-z][a-z0-9_]{0,59}$/.test(e),uy=new Set(["numero","seleccion","fecha"])});function Xh(e){let o=sr(e,["version","origen","entidades"]);if(o.version!==1)throw i("Perfil relacional inv\xE1lido.");let t=en(o.entidades,60).map(r=>{let a=sr(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(sr(a.campos)).map(([b,y])=>(bc(b),[b,cr(y)])));if(Object.keys(s).length>100)throw i("Perfil relacional inv\xE1lido.");let c=en(a.referencias??[],30).map(b=>{let y=sr(b,["campo","entidad","clave","obligatoria"]);if(y.obligatoria!==void 0&&typeof y.obligatoria!="boolean")throw i("Perfil relacional inv\xE1lido.");return{campo:bc(y.campo),entidad:Ii(y.entidad),clave:wc(y.clave),obligatoria:y.obligatoria===!0}}),d=a.archivos===void 0?void 0:en(a.archivos,20).map(b=>{let y=sr(b,["campo","columna","obligatorio"]);if(y.obligatorio!==void 0&&typeof y.obligatorio!="boolean")throw i("Perfil relacional inv\xE1lido.");return{campo:bc(y.campo),columna:cr(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),...c.map(b=>b.campo)];if(new Set(u).size!==u.length)throw i("Perfil relacional inv\xE1lido.");let p=a.procedencia===void 0?void 0:Object.fromEntries(Object.entries(sr(a.procedencia,["autor","creado","actualizado"])).map(([b,y])=>[b,cr(y)])),m=a.responsable===void 0?void 0:wc(a.responsable),h=a.tipos===void 0?void 0:en(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:Ii(a.clave),...a.acl!==void 0?{acl:cr(a.acl)}:{},...d?{archivos:d}:{},destino:a.destino,...p?{procedencia:p}:{},...m?{responsable:m}:{},...h?{tipos:h}:{},...a.tiposColumna!==void 0?{tiposColumna:cr(a.tiposColumna)}:{},clave_externa:wc(a.clave_externa),campos:s,referencias:c}}),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:Ii(o.origen),entidades:t}}var Ii,bc,cr,sr,en,wc,Yh=f(()=>{q();Ii=e=>{if(typeof e!="string"||!/^[a-z][a-z0-9_]{0,60}$/.test(e))throw i("Perfil relacional inv\xE1lido.");return e},bc=e=>{let o=typeof e=="string"&&/^datos\.[a-z][a-z0-9_]{0,60}$/.test(e)?e:Ii(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},cr=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},sr=(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},en=(e,o)=>{if(!Array.isArray(e)||e.length>o)throw i("Perfil relacional inv\xE1lido.");return e},wc=e=>{let o=en(e,3).map(cr);if(!o.length||new Set(o).size!==o.length)throw i("Perfil relacional inv\xE1lido.");return o}});function Kh(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:Xh(n.perfil)}})}var Zh=f(()=>{q();Yh()});function eg(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 og=f(()=>{q()});function ag(e,o){if(e===null)return null;if(!Io(e))throw i("La disposici\xF3n no es v\xE1lida.");if(!hy.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(!Io(e.zonas))throw ig();let t=e.zonas,n=Io(e.widgets)?e.widgets:{};for(let d of Object.keys(t))if(!tg.includes(d))throw i("Zona no v\xE1lida.");let r={},a=new Set;for(let d of tg){let u=t[d]??[];if(!Array.isArray(u))throw i("Zona no v\xE1lida.");r[d]=u.map(p=>{if(typeof p!="string"||p!==vc&&!fy.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(vc))throw ig();if(r.arriba.length>ng)throw i(`Arriba caben como mucho ${ng} bloques.`);let s={};for(let[d,u]of Object.entries(n)){if(!a.has(d))continue;if(!Io(u))throw i("Widget no v\xE1lido.");let p=zh(u.definicion);if(u.via!==void 0&&(typeof u.via!="string"||!gy.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!==vc&&!s[d])throw i("Falta la definici\xF3n de un widget.");if(Object.keys(s).length>rg)throw i(`Como mucho ${rg} widgets por vista.`);let c={zonas:r,widgets:s};if(JSON.stringify(c).length>6e4)throw i("La disposici\xF3n es demasiado grande.");return c}function by(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 sg(e){if(!Io(e))throw i("La vista no es v\xE1lida.");let o=Io(e.pref)?Object.fromEntries(Object.entries(e.pref).filter(([d])=>py.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&&!my.has(String(o.vista)))throw i("El tipo de vista no es v\xE1lido.");let t=Io(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(Io(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:ir(e.origenes),a;if(r||e.columnasCalculadas!==void 0){if(!r||r.length!==1||!["contacts","companies"].includes(r[0].fuente)||!Io(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=by(e.ambito),c={pref:o,filtros:t,orden:n,...s?{ambito:s}:{},...r?{origenes:r,columnasCalculadas:a}:{}};if(JSON.stringify(c).length>3e4)throw i("La vista es demasiado grande.");return c}var dy,py,my,tg,vc,fy,rg,ng,hy,gy,ig,Io,cg=f(()=>{Pi();q();dc();dy=/^(contacts|companies|deals|tareas|proyectos|mod_(?!sub_)[a-z][a-z0-9_]{1,40})$/,py=new Set(["vistaOrigen","vista","visibles","orden","anchos","fijadas","calculos","agrupar","grupo","vistas","separar"]),my=new Set(["tabla","lista","kanban","calendario","galeria","linea","mapa"]),tg=["arriba","izquierda","centro","derecha","abajo"],vc="tabla",fy=/^w_[a-z0-9]{1,24}$/,rg=24,ng=6,hy=dy,gy=/^[a-z][a-z0-9_]{0,59}$/,ig=()=>new z(400,"tabla_obligatoria","La tabla no se puede quitar de la vista: mu\xE9vela, pero d\xE9jala.");Io=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)});function lg(e){let o=new Set,t=n=>{typeof n=="string"&&n.startsWith("mod_")&&o.add(n.slice(4))};if(yc(e.personas)&&t(e.personas.modulo),Array.isArray(e.secciones)){for(let n of e.secciones)if(yc(n)&&(t(n.modulo),Array.isArray(n.camino)))for(let r of n.camino)yc(r)&&t(r.modulo)}return o}var yc,ug=f(()=>{yc=e=>!!e&&typeof e=="object"&&!Array.isArray(e)});function yy(e){if(typeof e!="string"||!vy.test(e))throw i("\xABrecurso\xBB: contacts, companies, deals o mod_<clave>.");return e}function _y(e){if(!wy.includes(e))throw i("\xABcanal\xBB: whatsapp o correo.");return e}function dg(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=yy(t.recurso);if(t.tipoContacto!==void 0&&t.tipoContacto!==null&&(!Jr(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=_y(t.canal),a=r==="correo"?_c(t.asunto,`${o}, asunto`,300,!1):void 0;return{recurso:n,...t.tipoContacto?{tipoContacto:t.tipoContacto}:{},canal:r,nombre:_c(t.nombre,`${o}, nombre`,80),...a?{asunto:a}:{},texto:_c(t.texto,`${o}, texto`,5e3)}}var wy,Di,vy,_c,Nc=f(()=>{wi();q();wy=["whatsapp","correo"],Di=50,vy=/^(contacts|companies|deals|mod_(?!sub_)[a-z][a-z0-9_]{0,40})$/,_c=(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()}});function fg(e){let o=_e(e,"informe");ze(o,["fuente","origenes","filtro","periodo","columnas","agrupar","agregados","orden"],"informe");let t=qe(o.fuente,"fuente",60),n=ir(o.origenes);if(t==="combinada"!=!!n)throw i("La fuente combinada necesita sus or\xEDgenes.");if(t!=="combinada"&&!lc.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=_e(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=uc(o.periodo)),o.columnas!==void 0&&o.columnas!==null){if(!Array.isArray(o.columnas)||o.columnas.length>pg)throw i(`\xABcolumnas\xBB: una lista de hasta ${pg}.`);r.columnas=[...new Set(o.columnas.map((a,s)=>qe(a,`columnas[${s}]`,60)))]}if(o.agrupar!==void 0&&o.agrupar!==null){let a=_e(o.agrupar,"agrupar");ze(a,["campo","paso"],"agrupar"),r.agrupar={campo:qe(a.campo,"agrupar.campo",60),...a.paso!==void 0?{paso:He(a.paso,ar,"agrupar.paso")}:{}}}if(o.agregados!==void 0&&o.agregados!==null){if(!Array.isArray(o.agregados)||o.agregados.length>mg)throw i(`\xABagregados\xBB: una lista de hasta ${mg}.`);r.agregados=o.agregados.map((a,s)=>{let c=_e(a,`agregados[${s}]`);ze(c,["tipo","campo"],`agregados[${s}]`);let d=He(c.tipo,cc,`agregados[${s}].tipo`);if(d!=="recuento"&&c.campo===void 0)throw i(`\xABagregados[${s}]\xBB: esa operaci\xF3n necesita un campo.`);return{tipo:d,...d!=="recuento"?{campo:qe(c.campo,`agregados[${s}].campo`,60)}:{}}})}if(r.agrupar&&!r.agregados?.length&&(r.agregados=[{tipo:"recuento"}]),o.orden!==void 0&&o.orden!==null){let a=_e(o.orden,"orden");ze(a,["por","sentido"],"orden"),r.orden={por:qe(a.por,"orden.por",60),sentido:He(a.sentido??"asc",["asc","desc"],"orden.sentido")}}return r}var pg,mg,hg=f(()=>{Pi();q();dc();pg=30,mg=6});var $c,Ny,gg,bg=f(()=>{$c=[{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"}],Ny=e=>`pix.agente_${e}`,gg=e=>$c.some(o=>Ny(o.clave)===e)});var wg,vg=f(()=>{wg=["contacts","companies","deals","tareas","proyectos"]});function yg(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 _g(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:yg(n.nombre,"pix.personalidad.nombre",xy),instrucciones:yg(n.instrucciones,"pix.personalidad.instrucciones",$y)}}}var $y,xy,Ng=f(()=>{q();$y=2e3,xy=60});function $g(e,o){if(e===void 0)return[];if(!Array.isArray(e)||e.length>on)throw i(`\xABinformes\xBB: una lista de hasta ${on}.`);let t=new Set;return e.map((n,r)=>{if(!Cy(n))throw i(`Informe ${r+1}: un objeto.`);for(let c of Object.keys(n))if(!["nombre","descripcion","definicion"].includes(c))throw i(`Informe ${r+1}: clave no admitida \xAB${c.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=fg(n.definicion);if([s.fuente,...s.origenes?.map(c=>c.fuente)??[]].some(c=>c.startsWith("mod_")&&!o.includes(c.slice(4))))throw i(`Informe \xAB${a}\xBB: su fuente no es un m\xF3dulo de la soluci\xF3n.`);return{nombre:a,...n.descripcion?{descripcion:n.descripcion}:{},definicion:s}})}var on,Cy,xc=f(()=>{q();hg();on=30,Cy=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)});var xg,yo,lr,ur,oe,Cc,dr,tF,jy,Li,Sy,Oy,rF,nF,Cg=f(()=>{bg();xg={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"]},yo=["si","no","suyos"],lr=["si","no","suyos","equipo","jerarquia"],ur=["si","no","suyos","jerarquia"],oe=["si","no"],Cc=(e,o,t=!0)=>[{clave:`${e}.ver`,descripcion:`Ver ${o}`,valores:ur},{clave:`${e}.crear`,descripcion:`Dar de alta ${o}`,valores:ur},{clave:`${e}.editar`,descripcion:`Editar ${o}`,valores:ur},{clave:`${e}.reasignar`,descripcion:`Cambiar el responsable de ${o}`,valores:ur},...t?[{clave:`${e}.estado`,descripcion:`Cambiar el estado de ${o}`,valores:ur}]:[],{clave:`${e}.descargar`,descripcion:`Bajar los ficheros de ${o}`,valores:oe},{clave:`${e}.borrar`,descripcion:`Borrar ${o}`,valores:ur},{clave:`${e}.exportar`,descripcion:`Exportar ${o}`,valores:yo},{clave:`${e}.importar`,descripcion:`Importar ${o} desde una hoja`,valores:oe}],dr=[...Cc("contactos","contactos"),...Cc("empresas","empresas",!1),...Cc("oportunidades","oportunidades"),{clave:"proyectos.ver",descripcion:"Ver proyectos",valores:lr},{clave:"proyectos.editar",descripcion:"Editar los datos del proyecto",valores:lr},{clave:"proyectos.borrar",descripcion:"Borrar proyectos",valores:lr},{clave:"proyectos.exportar",descripcion:"Exportar proyectos",valores:yo},{clave:"proyectos.crear",descripcion:"Crear proyectos",valores:oe},{clave:"proyectos.gestionar",descripcion:"Cambiar el estado, el responsable, los participantes, las columnas y los ajustes de los proyectos, y gestionar plantillas",valores:oe},{clave:"tareas.ver",descripcion:"Ver tareas",valores:lr},{clave:"tareas.crear",descripcion:"Crear tareas",valores:oe},{clave:"tareas.editar",descripcion:"Editar y completar tareas",valores:lr},{clave:"tareas.borrar",descripcion:"Borrar tareas",valores:lr},{clave:"tareas.exportar",descripcion:"Exportar tareas visibles",valores:yo},{clave:"notas.ver",descripcion:"Ver notas",valores:yo},{clave:"notas.editar",descripcion:"Escribir, editar y borrar notas",valores:yo},{clave:"adjuntos.ver",descripcion:"Ver y descargar adjuntos",valores:yo},{clave:"adjuntos.subir",descripcion:"Subir adjuntos",valores:yo},{clave:"miembros.gestionar",descripcion:"Invitar, cambiar el papel y desactivar miembros",valores:oe},{clave:"conectores.accionar",descripcion:"Ejecutar acciones f\xEDsicas de conectores",valores:oe},{clave:"configuracion.gestionar",descripcion:"Cambiar la configuraci\xF3n del espacio y los permisos",valores:oe},{clave:"formularios.gestionar",descripcion:"Crear, editar y borrar formularios (y sus respuestas)",valores:oe},{clave:"formularios.ver_respuestas",descripcion:"Ver las respuestas de los formularios",valores:yo},{clave:"modulos.configurar",descripcion:"Dise\xF1ar, publicar y archivar m\xF3dulos",valores:oe},{clave:"paneles.ver",descripcion:"Ver los paneles de m\xE9tricas",valores:oe},{clave:"paneles.editar",descripcion:"Crear, cambiar y borrar paneles de m\xE9tricas",valores:oe},{clave:"paneles.compartir",descripcion:"Compartir paneles con el equipo y cambiar o borrar los de equipo",valores:oe},{clave:"automatizaciones.gestionar",descripcion:"Crear y cambiar automatizaciones, y ver sus ejecuciones",valores:oe},{clave:"campanas.gestionar",descripcion:"Crear y enviar campa\xF1as de correo, y gestionar consentimientos y supresiones",valores:oe},{clave:"agenda.ver",descripcion:"Ver las citas de la agenda",valores:yo},{clave:"agenda.editar",descripcion:"Crear, mover y cancelar citas",valores:yo},{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:oe},{clave:"analisis.ver",descripcion:"Usar An\xE1lisis: informes de lo que ya puede ver",valores:oe},{clave:"analisis.compartir",descripcion:"Compartir informes con el equipo y cambiar o borrar los de equipo",valores:oe},{clave:"secretos.ver",descripcion:"Ver los campos secretos (cada vez queda registrado qui\xE9n lo vio)",valores:oe},{clave:"liquidaciones.gestionar",descripcion:"Generar, aprobar, cerrar, pagar y reabrir liquidaciones de comisiones",valores:oe},{clave:"portales.gestionar",descripcion:"Configurar los portales, invitar a ellos y revocar el acceso",valores:oe},{clave:"auditoria.ver",descripcion:"Ver la auditor\xEDa del espacio (qui\xE9n hizo qu\xE9 y cu\xE1ndo)",valores:oe},{clave:"publico.compartir",descripcion:"Compartir la p\xE1gina p\xFAblica de un registro (un enlace que caduca)",valores:oe},{clave:"pix.memoria_espacio",descripcion:"Escribir lo que Pix recuerda para todo el espacio",valores:oe},...$c.map(e=>({clave:`pix.agente_${e.clave}`,descripcion:`Usar a ${e.nombre} (${e.puesto}) del Equipo IA`,valores:oe}))],tF=new Set(dr.map(e=>e.clave)),jy=e=>/\.(exportar|importar)$/.test(e),Li=e=>Object.fromEntries(dr.map(o=>[o.clave,e(o)])),Sy=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"||gg(e.clave),Oy={titular:Li(()=>"si"),administrador:Li(e=>e.clave==="conectores.accionar"?"no":"si"),miembro:Li(e=>Sy(e)||e.clave==="conectores.accionar"||e.clave==="secretos.ver"||jy(e.clave)?"no":"si"),lectura:Li(e=>e.clave.endsWith(".ver")&&e.clave!=="secretos.ver"&&e.clave!=="auditoria.ver"||e.clave.endsWith(".descargar")?"si":e.clave.endsWith(".reasignar")?"suyos":"no")},rF=dr.filter(e=>/^((contactos|empresas|oportunidades|proyectos|tareas|notas|adjuntos)\.|agenda\.(ver|editar)$)/.test(e.clave)&&e.valores.includes("suyos")&&Oy.miembro[e.clave]!=="no").map(e=>e.clave),nF=dr.filter(e=>/^((contactos|empresas|oportunidades|proyectos|tareas|notas|adjuntos)\.|agenda\.(ver|editar)$)/.test(e.clave)&&e.valores.includes("suyos")).map(e=>e.clave)});function Og(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>jg)throw i(`\xAB${r.slice(0,20)}\u2026\xBB: como mucho ${jg} caracteres.`);if(!jc(r))throw i(`\xAB${r}\xBB no es una palabra.`);t.has(jc(r))||(t.add(jc(r)),o.push(r))}}if(o.length>Sc)throw i(`Como mucho ${Sc} sin\xF3nimos por m\xF3dulo.`);return o}var Sg,Sc,jg,jc,Ag=f(()=>{q();Sg=["contacts","companies","deals","tasks"],Sc=20,jg=40,jc=e=>e.normalize("NFD").replace(/[̀-ͯ]/g,"").toLowerCase().replace(/[^a-z0-9ñ\s-]/g," ").replace(/\s+/g," ").trim()});function qy(e){if(e===void 0)return[];if(!Array.isArray(e)||e.length>5)throw i("Conexiones de la soluci\xF3n no v\xE1lidas.");return e.map(o=>{if(!re(o)||o.tipo!=="conector"||typeof o.conector!="string"||!/^[a-z][a-z0-9_-]{0,39}$/.test(o.conector))throw i("Conexi\xF3n de la soluci\xF3n no v\xE1lida.");let t=_o(o.nombre,"nombre de la conexi\xF3n",80,!1)||o.conector;return{clave:o.conector,nombre:t,tipo:"conector",conector:o.conector}})}function ky(e){if(e===void 0)return[];if(!Array.isArray(e))throw i("Conexiones de la soluci\xF3n no v\xE1lidas.");let o=s=>re(s)&&s.tipo==="conector",t=qy(e.filter(o)),n=Vh(e.filter(s=>!o(s))),r=0,a=0;return e.map(s=>o(s)?t[r++]:n[a++])}function Ty(e){if(e==null)return null;if(!re(e))throw i("\xABagenda\xBB: un objeto.");Xe(e,["tipos"],"Agenda");let o=new Set,t=io(e.tipos,Py,"agenda.tipos").map((n,r)=>{let a=`Tipo de cita ${r+1}`;if(!re(n))throw i(`${a}: un objeto.`);Xe(n,["nombre","duracion","color","reserva_publica","quien_atiende","cambio_horas","crear_persona"],a);let s=_o(n.nombre,`nombre del ${a.toLowerCase()}`,80);if(o.has(s.toLowerCase()))throw i(`${a}: nombre repetido.`);if(o.add(s.toLowerCase()),!Number.isInteger(n.duracion)||n.duracion<5||n.duracion>1440)throw i(`${a}: \xABduracion\xBB, de 5 a 1440 minutos.`);if(n.color!==void 0&&(typeof n.color!="string"||!/^#[0-9a-f]{6}$/i.test(n.color)))throw i(`${a}: \xABcolor\xBB, #rrggbb.`);for(let c of["reserva_publica","crear_persona"])if(n[c]!==void 0&&typeof n[c]!="boolean")throw i(`${a}: \xAB${c}\xBB, s\xED o no.`);if(n.quien_atiende!==void 0&&n.quien_atiende!=="cualquiera"&&n.quien_atiende!=="cliente")throw i(`${a}: \xABquien_atiende\xBB, cualquiera o cliente.`);if(n.cambio_horas!==void 0&&(!Number.isInteger(n.cambio_horas)||n.cambio_horas<0||n.cambio_horas>720))throw i(`${a}: \xABcambio_horas\xBB, de 0 a 720.`);return{nombre:s,duracion:n.duracion,...n.color!==void 0?{color:n.color.toLowerCase()}:{},...n.reserva_publica!==void 0?{reserva_publica:n.reserva_publica}:{},...n.quien_atiende!==void 0?{quien_atiende:n.quien_atiende}:{},...n.cambio_horas!==void 0?{cambio_horas:n.cambio_horas}:{},...n.crear_persona!==void 0?{crear_persona:n.crear_persona}:{}}});return t.length?{tipos:t}:null}function My(e,o){return io(e,Ec,"vistasTabla").map((t,n)=>{let r=`Vista de tabla ${n+1}`;if(!re(t))throw i(`${r}: un objeto.`);Xe(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=ag(t.disposicion??null,a),c=eg(a,t.tipoContacto);return{objeto:a,...c?{tipoContacto:c}:{},nombre:_o(t.nombre,`nombre de la ${r.toLowerCase()}`,60),...t.config!==void 0?{config:sg(t.config)}:{},disposicion:s}})}function zy(e,o,t=[]){let n=new Set;return io(e,Rc,"papeles").map((r,a)=>{let s=`Papel ${a+1}`;if(!re(r))throw i(`${s}: un objeto.`);Xe(r,["nombre","base","permisos","ocultos","lectura","identidades"],s);let c=_o(r.nombre,`nombre del ${s.toLowerCase()}`,40);if(n.has(c.toLowerCase()))throw i(`${s}: nombre repetido.`);if(n.add(c.toLowerCase()),typeof r.base!="string"||!Dy.includes(r.base))throw i(`${s}: \xABbase\xBB, administrador, miembro o lectura.`);let d={};if(r.permisos!==void 0){if(!re(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 v=Ly.exec(b),w=dr.find(j=>j.clave===b);if(v?!o.includes(v[1]):!w)throw i(`${s}: permiso desconocido \xAB${b.slice(0,60)}\xBB.`);let N=w?w.valores:xg[v[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(v=>{let w=typeof v=="string"?Iy.exec(v):null,N=w?t.find(j=>j.clave===w[1]):void 0;if(!w||!N||!N.campos.some(j=>j.clave===w[2]))throw i(`${s}: \xAB${String(v).slice(0,60)}\xBB no es un campo de un m\xF3dulo de la soluci\xF3n.`);return v})},p=u(r.ocultos,"ocultos"),m=u(r.lectura,"lectura"),h=gm(r.identidades);return{nombre:c,base:r.base,...Object.keys(d).length?{permisos:d}:{},...p.length?{ocultos:p}:{},...m.length?{lectura:m}:{},...h.length?{identidades:h}:{}}})}function Oc(e,o=0){if(o>30)throw i("La soluci\xF3n anida demasiado.");if(Array.isArray(e))return e.forEach(t=>Oc(t,o+1));if(re(e))for(let t of Object.keys(e)){if(Ey.has(t))throw i(`Clave no admitida \xAB${t}\xBB.`);Oc(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 _o(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 tn(e,o){if(typeof e=="string"){if(e.length>Fi)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>Fi)throw i("La soluci\xF3n pasa de 1 MB.");if(!re(e))throw i("La soluci\xF3n tiene que ser un objeto.");Oc(e),Xe(e,["formato","version","plantilla","nombre","descripcion","icono","modulos","paneles","automatizaciones","ejemplos","informes","principal","mensajes","papeles","portales","vistasTabla","separadores","menu","sinonimos","perfilesImportacion","conexiones","fuentesExternas","senales","pix","agenda"],"Soluci\xF3n");let t;if(e.plantilla!==void 0){let g=e.plantilla;if(!re(g))throw i("\xABplantilla\xBB: un objeto.");if(Xe(g,["id","version","sector","nivel","dependencias","migracion"],"Plantilla"),typeof g.id!="string"||!/^[a-z][a-z0-9_]{0,59}$/.test(g.id))throw i("\xABplantilla.id\xBB: min\xFAsculas, n\xFAmeros y _.");if(!Mi(g.version))throw i("\xABplantilla.version\xBB: usa una versi\xF3n sem\xE1ntica v\xE1lida.");if(typeof g.sector!="string"||!/^[a-z][a-z0-9_]{0,39}$/.test(g.sector))throw i("\xABplantilla.sector\xBB: min\xFAsculas y _.");if(g.nivel!==void 0&&g.nivel!=="completa"&&g.nivel!=="basica")throw i("\xABplantilla.nivel\xBB: completa o basica.");let x=g.dependencias;if(x!==void 0&&(!Array.isArray(x)||x.length>30||x.some(k=>typeof k!="string"||!/^[a-z][a-z0-9_]{0,59}$/.test(k)||k===g.id)||new Set(x).size!==x.length))throw i("\xABplantilla.dependencias\xBB: usa identificadores distintos de otras soluciones.");let O=Gh(g.migracion,g.version);t={...O?{migracion:O}:{},id:g.id,version:g.version,sector:g.sector,...x?{dependencias:x}:{},...g.nivel==="basica"?{nivel:"basica"}:{}}}if(e.formato!==kt)throw i(`No es una soluci\xF3n (formato \xAB${kt}\xBB).`);if(!Number.isInteger(e.version)||e.version<1)throw i("\xABversion\xBB: un entero.");if(e.version>pr)throw i("La soluci\xF3n es de una versi\xF3n m\xE1s nueva del CRM.");let n=_o(e.icono,"icono",40,!1)||"boxes";if(!Eg.test(n))throw i("\xABicono\xBB: un icono de lucide.");if(!Array.isArray(e.modulos)||e.modulos.length<1||e.modulos.length>zi)throw i(`Una soluci\xF3n lleva de 1 a ${zi} m\xF3dulos.`);let r=e.modulos.map(g=>re(g)&&typeof g.clave=="string"?g.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(([g])=>!r.includes(g))),s=[...r,...a.keys()],c=new Map([...a,...e.modulos.map((g,x)=>[r[x],ac(g,s)])]),d=e.modulos.map(g=>{let x=$h(g,{topeCampos:o.topeCampos,modulosDelEspacio:s,camposRelacion:c}),O=re(g)?g.sin_coste:void 0;if(O!==void 0&&O!==!0)throw i(`\xAB${x.nombre_plural}\xBB: \xABsin_coste\xBB solo puede ser true.`);return O===!0?{...x,sin_coste:!0}:x}),u=io(e.paneles,Ac,"paneles").map((g,x)=>{if(!re(g))throw i(`Panel ${x+1}: un objeto.`);if(Xe(g,["nombre","icono","widgets"],`Panel ${x+1}`),!Array.isArray(g.widgets)||g.widgets.length>20)throw i(`Panel ${x+1}: hasta 20 widgets.`);let O=_o(g.icono,"icono",40,!1);if(O&&!Eg.test(O))throw i(`Panel ${x+1}: icono no v\xE1lido.`);return{nombre:_o(g.nombre,"nombre del panel",60),...O?{icono:O}:{},widgets:g.widgets}}),p=io(e.automatizaciones,qc,"automatizaciones").map((g,x)=>{if(!re(g))throw i(`Automatizaci\xF3n ${x+1}: un objeto.`);if(Xe(g,["nombre","definicion"],`Automatizaci\xF3n ${x+1}`),!re(g.definicion))throw i(`Automatizaci\xF3n ${x+1}: falta su definici\xF3n.`);return{nombre:_o(g.nombre,"nombre de la automatizaci\xF3n",80),definicion:g.definicion}}),m=io(e.senales,20,"senales").map((g,x)=>{if(!re(g))throw i(`Se\xF1al ${x+1}: un objeto.`);Xe(g,["fuente","regla"],`Se\xF1al ${x+1}`);let O=typeof g.fuente=="string"?g.fuente:"";if(!(O.startsWith("mod_")?r.includes(O.slice(4)):wg.includes(O)))throw i(`Se\xF1al ${x+1}: \xABfuente\xBB, un m\xF3dulo de la soluci\xF3n (mod_<clave>) o un nativo.`);if(!re(g.regla))throw i(`Se\xF1al ${x+1}: falta su regla.`);return{fuente:O,regla:g.regla}}),h=_g(e.pix),b=$g(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=io(e.mensajes,Di,"mensajes").map((g,x)=>{let O=dg(g,`Mensaje ${x+1}`);if(O.recurso.startsWith("mod_")&&!r.includes(O.recurso.slice(4)))throw i(`Mensaje ${x+1}: de un m\xF3dulo que no est\xE1 en la soluci\xF3n.`);return O}),v=zy(e.papeles,r,d),w=Wy(e.portales,r),N=Ty(e.agenda),j=My(e.vistasTabla,r),S=io(e.separadores??[],kc,"separadores").map((g,x)=>{if(!re(g))throw i(`Separador ${x+1}: un objeto.`);if(Xe(g,["antes","titulo"],`Separador ${x+1}`),g.antes!==null&&(typeof g.antes!="string"||!r.includes(g.antes)))throw i(`Separador ${x+1}: \xABantes\xBB, la clave de uno de sus m\xF3dulos.`);if(g.titulo!==void 0&&g.titulo!==null&&(typeof g.titulo!="string"||!g.titulo.trim()||g.titulo.trim().length>40))throw i(`Separador ${x+1}: \xABtitulo\xBB, de 1 a 40 caracteres (o null: solo la l\xEDnea).`);return{antes:g.antes,titulo:typeof g.titulo=="string"?g.titulo.trim():null}}),R=io(e.menu??[],100,"menu").map((g,x)=>{if(!re(g))throw i(`Men\xFA ${x+1}: un objeto.`);if(Xe(g,["entrada","padre","recientes","despliega"],`Men\xFA ${x+1}`),typeof g.entrada!="string"||!r.includes(g.entrada))throw i(`Men\xFA ${x+1}: \xABentrada\xBB, la clave de uno de sus m\xF3dulos.`);if(g.padre!==void 0&&g.padre!==null&&(typeof g.padre!="string"||!r.includes(g.padre)||g.padre===g.entrada))throw i(`Men\xFA ${x+1}: \xABpadre\xBB, otro de sus m\xF3dulos (o null).`);if(g.recientes!==void 0&&(!Number.isSafeInteger(g.recientes)||g.recientes<0||g.recientes>10))throw i(`Men\xFA ${x+1}: \xABrecientes\xBB, de 0 a 10.`);if(g.despliega!==void 0&&(typeof g.despliega!="string"||!pc.includes(g.despliega)))throw i(`Men\xFA ${x+1}: \xABdespliega\xBB, ${pc.join(", ")}.`);return{entrada:g.entrada,...g.padre!==void 0?{padre:g.padre}:{},...g.recientes!==void 0?{recientes:g.recientes}:{},...g.despliega!==void 0?{despliega:g.despliega}:{}}});for(let g of R)if(g.padre&&(R.some(x=>x.entrada===g.padre&&x.padre)||R.some(x=>x.padre===g.entrada)))throw i(`Men\xFA: \xAB${g.entrada}\xBB, un solo nivel (ni su padre va dentro de otro ni tiene otros dentro).`);if(new Set(R.map(g=>g.entrada)).size!==R.length)throw i("Men\xFA: cada m\xF3dulo, una vez.");let F={};if(e.ejemplos!==void 0){if(!re(e.ejemplos))throw i("\xABejemplos\xBB: un objeto por m\xF3dulo.");for(let[g,x]of Object.entries(e.ejemplos)){if(!r.includes(g))throw i(`Ejemplos de un m\xF3dulo que no est\xE1 en la soluci\xF3n (\xAB${g.slice(0,40)}\xBB).`);let O=new Set;F[g]=io(x,Wi,`ejemplos de ${g}`).map((k,L)=>{if(!re(k))throw i(`Ejemplo ${L+1} de ${g}: un objeto.`);if(k._ref!==void 0&&!Number.isSafeInteger(k._ref))throw i(`Ejemplo ${L+1} de ${g}: \xAB_ref\xBB es un entero.`);if(typeof k._ref=="number"){if(O.has(k._ref))throw i(`\xAB${g}\xBB: referencia de ejemplo repetida.`);O.add(k._ref)}if((d.find(U=>U.clave===g)?.campos??[]).filter(U=>U.tipo==="secreto").map(U=>U.clave).some(U=>U in k))throw i(`Ejemplo ${L+1} de ${g}: un ejemplo no lleva el valor de un campo secreto.`);return k})}}let I=ky(e.conexiones),_=Wh(e.fuentesExternas,d,I.filter(Ry));if(_.some(g=>g.modo==="vivo"&&F[g.modulo]?.length))throw i("Un m\xF3dulo con fuente en vivo no puede tener ejemplos.");let E=Kh(e.perfilesImportacion);if(E.some(g=>g.perfil.entidades.some(x=>x.destino.startsWith("mod_")&&!d.some(O=>`mod_${O.clave}`===x.destino))))throw i("El perfil apunta fuera de la soluci\xF3n.");return{formato:kt,...E.length?{perfilesImportacion:E}:{},...I.length?{conexiones:I}:{},..._.length?{fuentesExternas:_}:{},version:e.version,...t?{plantilla:t}:{},nombre:_o(e.nombre,"nombre",80),descripcion:_o(e.descripcion,"descripcion",500,!1),icono:n,modulos:d,paneles:u,automatizaciones:p,ejemplos:F,...m.length?{senales:m}:{},...h?{pix:h}:{},...b.length?{informes:b}:{},...typeof e.principal=="string"?{principal:e.principal}:{},...y.length?{mensajes:y}:{},...v.length?{papeles:v}:{},...w.length?{portales:w}:{},...N?{agenda:N}:{},...j.length?{vistasTabla:j}:{},...S.length?{separadores:S}:{},...R.length?{menu:R}:{},...Fy(e.sinonimos,d.map(g=>g.clave))}}function Fy(e,o){if(e===void 0)return{};if(!re(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)&&!Sg.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=Og(r);a.length&&(t[n]=a)}return Object.keys(t).length?{sinonimos:t}:{}}function Wy(e,o){return io(e,Pc,"portales").map((t,n)=>{let r=`Portal ${n+1}`;if(!re(t))throw i(`${r}: un objeto.`);Xe(t,["clave","nombre","activo","personas","secciones","textos","marca"],r);let a=[...lg(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:c,...d}=t,u=re(c)&&typeof c.color=="string"?c.color:void 0;return{...d,...u?{marca:{color:u}}:{}}})}function io(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 kt,pr,zi,Ac,Ec,qc,Wi,Fi,Eg,Ey,Ry,Py,Rc,Iy,Dy,Ly,re,kc,Pc,Tc=f(()=>{Bh();Uh();Hh();fc();Zh();bm();ug();og();Nc();q();vg();Ng();xc();Kr();Fh();Cg();cg();Ag();kt="forgenex.solucion",pr=2,zi=30,Ac=10,Ec=20,qc=40,Wi=50,Fi=1e6,Eg=/^[a-z0-9-]{1,40}$/,Ey=new Set(["__proto__","constructor","prototype"]);Ry=e=>e.tipo!=="conector";Py=10;Rc=10,Iy=/^mod_([a-z][a-z0-9_]{0,40})\.([a-z][a-z0-9_]{0,40})$/,Dy=["administrador","miembro","lectura"],Ly=/^mod_([a-z][a-z0-9_]{0,40})\.(ver|editar|borrar|exportar|importar|crear|reasignar|estado|descargar|revelar)$/;re=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);kc=20,Pc=10});function Rg(e,o){let t=new Map(e);for(let[n,r]of e){if(!/^(interfaz|funciones)\/.+\.ts$/.test(n))continue;let a=n.replace(/\.ts$/,".js");if(e.has(a))throw qg([{ruta:n,linea:null,motivo:`El fichero coincide con la salida \xAB${a}\xBB.`}]);try{let{code:s}=o(r.toString("utf8"),{loader:"ts",sourcefile:n,target:"es2020",format:"esm"});t.set(a,Buffer.from(s)),t.delete(n)}catch(s){let c=s?.errors;throw qg(c?.length?c.slice(0,12).map(({location:d,text:u})=>({ruta:n,linea:d?.line??null,motivo:u})):[{ruta:n,linea:null,motivo:"El compilador no pudo procesar el fichero."}])}}return t}function qg(e){let{ruta:o,linea:t,motivo:n}=e[0];return new z(422,"build_app",`${o}${t?`:${t}`:""}: ${n}`,!1,{errores:e})}var kg=f(()=>{q()});import{createHash as Pg,createPublicKey as By,sign as Vy,verify as FF}from"node:crypto";function Uy(e){let o=By(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:Pg("sha256").update(t).digest("hex")}}function Jy(e){return Buffer.from(JSON.stringify(["forgenex.fgx.v1",[...e].filter(([o])=>o!==rn).sort(([o],[t])=>o<t?-1:o>t?1:0).map(([o,t])=>[o,Pg("sha256").update(t).digest("hex")])]))}function Tg(e,o,t){let{id:n}=Uy(t);return Buffer.from(JSON.stringify({formato:"forgenex.firma",version:1,clave:n,firma:Vy(null,Jy(e),o).toString("base64")}))}var rn,Mc=f(()=>{q();rn="firma.json"});function Ic(e){let o=Array.from({length:256},(c,d)=>{let u=d;for(let p=0;p<8;p++)u=u&1?3988292384^u>>>1:u>>>1;return u>>>0}),t=[],n=[],r=0;for(let[c,d]of e){let u=Buffer.from(c),p=4294967295;for(let b of d)p=o[(p^b)&255]^p>>>8;p=(p^4294967295)>>>0;let m=Buffer.alloc(30),h=Buffer.alloc(46);m.writeUInt32LE(67324752),m.writeUInt16LE(20,4),m.writeUInt16LE(2048,6),m.writeUInt32LE(p,14),m.writeUInt32LE(d.length,18),m.writeUInt32LE(d.length,22),m.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(m,u,d),n.push(h,u),r+=m.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 Mg=f(()=>{});import{existsSync as Qy,cpSync as Gy,copyFileSync as nn,mkdirSync as Dc,readFileSync as mr,readdirSync as an,realpathSync as Ig,writeFileSync as Dg}from"node:fs";import{dirname as Hy,join as B,resolve as Xy,sep as Yy}from"node:path";import{fileURLToPath as Ky}from"node:url";import{createRequire as Bi}from"node:module";function Vi(e,o="html",t=process.cwd()){if(!/^[a-z][a-z0-9-]{1,59}$/.test(e))throw new Error("El nombre debe tener de 2 a 60 letras min\xFAsculas, n\xFAmeros o guiones y empezar por letra.");if(!["html","react","archivos","natacion"].includes(o))throw new Error("Plantilla: html, react, archivos o natacion.");let n=B(t,e);Dc(n);for(let c of["interfaz","funciones"])Dc(B(n,c));let r=(c,d)=>Dg(B(n,c),typeof d=="string"?d:JSON.stringify(d,null,2)+`
|
|
22
|
+
`);if(o==="natacion"){Gy(B(ao,"ejemplos","escuela-natacion"),n,{recursive:!0,filter:d=>!d.endsWith(".fgx")});let c=JSON.parse(mr(B(n,"extension.json"),"utf8"));return r("extension.json",{...c,id:`com.ejemplo.${e}`}),r(".gitignore",`*.fgx
|
|
23
|
+
`),Fe(n),n}let a=`ext_${e.replace(/[^a-z]/g,"_").slice(0,27)}`;if(o==="archivos"){let c=JSON.parse(mr(B(ao,"ejemplos/archivos-ficha/extension.json"),"utf8"));r("extension.json",{...c,id:`com.ejemplo.${e}`,nombre:e,autor:{nombre:"Mi empresa"}}),nn(B(ao,"ejemplos/archivos-ficha/interfaz/index.html"),B(n,"interfaz/index.html"));for(let d of["GUIA-IA.md","extension.schema.json","solucion.schema.json","puente-extension.d.ts","puente-extension.mjs"])nn(B(ao,d),B(n,d));return r("AGENTS.md",`Lee GUIA-IA.md (secci\xF3n \xABArchivos\xBB). La app solo recibe lo que la persona elige con crm.archivos.elegir(): nunca pidas tokens del almacenamiento. Pide permisos m\xEDnimos. Valida antes de empaquetar.
|
|
23
24
|
`),r(".gitignore",`node_modules/
|
|
24
25
|
*.fgx
|
|
25
26
|
*.pem
|
|
26
27
|
.keys/
|
|
27
|
-
`),
|
|
28
|
+
`),Fe(n),n}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) {
|
|
28
29
|
const resumen = { mensaje: String(entrada.cuerpo?.mensaje ?? "Hola"), total: 1 };
|
|
29
30
|
await crm.almacen.guardar("ultimo_resumen", resumen);
|
|
30
31
|
return resumen;
|
|
31
32
|
}
|
|
32
|
-
`);for(let c of["GUIA-IA.md","extension.schema.json","solucion.schema.json","puente-extension.d.ts","puente-extension.mjs"])
|
|
33
|
-
`);let s=o==="html"?"hola-alpine":"hola-react";for(let c of
|
|
34
|
-
export default defineConfig({ build: { outDir: "interfaz", emptyOutDir: false, rollupOptions: { input: "src/main.jsx", external: ["@forgenex/crm-sdk"], output: { entryFileNames: "app.js", inlineDynamicImports: true } } } });
|
|
33
|
+
`);for(let c of["GUIA-IA.md","extension.schema.json","solucion.schema.json","puente-extension.d.ts","puente-extension.mjs"])nn(B(ao,c),B(n,c));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.
|
|
34
|
+
`);let s=o==="html"?"hola-alpine":"hola-react";for(let c of an(B(ao,"ejemplos",s,"interfaz")))nn(B(ao,"ejemplos",s,"interfaz",c),B(n,"interfaz",c));return o==="react"&&(Dc(B(n,"src")),nn(B(ao,"ejemplos/hola-react/src/main.jsx"),B(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";
|
|
35
|
+
export default defineConfig({ build: { outDir: "interfaz", emptyOutDir: false, rollupOptions: { input: "src/main.jsx", external: ["@forgenex/crm-sdk", "@forgenex/forja", "@forgenex/kit"], output: { entryFileNames: "app.js", inlineDynamicImports: true } } } });
|
|
35
36
|
`)),r(".gitignore",`node_modules/
|
|
36
37
|
*.fgx
|
|
37
38
|
*.pem
|
|
38
39
|
.keys/
|
|
39
|
-
`),
|
|
40
|
-
`)+[...u.matchAll(/\sstyle\s*=\s*"([^"]*)"/gi)].map(
|
|
41
|
-
`);if(p.trim()){s=!0;for(let[f,h]of Iy(My(p))){let b=f.trim().replace(/\s+/g," "),y=null,v=null;for(let w of h.matchAll(/(?:^|;)\s*(color|background-color|background)\s*:\s*([^;]+)/gi)){let _=Ty(w[2]);_.tema&&(a=!0),w[1].toLowerCase()==="color"?y=_:v=_,!_.tema&&!_.neutro&&_.color&&(/(^|,)\s*(html|body|:root)\s*(,|$)/i.test(b)?t.push(`${d}: \xAB${b}\xBB fija ${w[1]} (${w[2].trim()}): la p\xE1gina no seguir\xE1 el tema claro y oscuro del CRM. Usa var(--background) y var(--foreground).`):n.push(`${d}: \xAB${b}\xBB usa un color fijo en ${w[1]} (${w[2].trim()}).`))}if(y?.color&&v?.color){let w=Py(y.color,v.color);w<4.5&&r.push(`${d}: \xAB${b}\xBB tiene un contraste de ${w.toFixed(2)}:1 entre el texto y el fondo (hace falta 4,5:1).`)}}}}let c=e.montajes.length>0;return c&&s&&!a&&t.push("La interfaz no usa ninguna variable del tema (var(--background), var(--foreground), var(--primary)\u2026): no parecer\xE1 del CRM ni seguir\xE1 el modo oscuro."),[Le("forja","Forja: colores del tema",t,n,c?"Toma los colores del tema del CRM.":"No trae interfaz."),Le("contraste","Contraste del texto (\u2265 4,5:1)",r,[],"Los colores fijos que se pueden medir tienen contraste suficiente.")]}function no(e,o){for(let t=0;t<3;t++)if((e[t]??0)!==o[t])return(e[t]??0)<o[t];return!1}function Wy(e,o,t){let n=[],r=new Set,a=(c,d,u)=>{let p=c.toLowerCase().replace(/\.js$/,"");r.add(`${p} ${d}`);let f=d.split(".").map(Number);for(let h of zy)h.nombre.test(p)&&h.malas(f)&&n.push(`${u} trae ${h.etiqueta} ${d}, con un fallo de seguridad conocido: usa la ${h.arreglo} o posterior.`)};for(let c of o){let d=/(?:^|\/)([a-z][a-z.]*?)[-.@]v?(\d{1,3}\.\d{1,3}\.\d{1,3})(?:\.min)?\.m?js$/i.exec(c);d&&a(d[1],d[2],c)}for(let[c,d]of t)for(let u of d.matchAll(/\/\*[!*][\s\S]{0,600}?\*\//g))for(let p of u[0].matchAll(Fy))a(p[1],p[2],c);let s=e.depende_de.map(c=>`Necesita la app \xAB${c.id}\xBB${c.version?` (${c.version})`:""} instalada antes.`);return Le("dependencias","Dependencias sin fallos conocidos",n,s,r.size?`Librer\xEDas vistas: ${[...r].join(", ")}.`:"No se ven librer\xEDas de terceros con versi\xF3n.")}function By(e){let o=[];for(let[t,n]of e)/\.(m?js|cjs|jsx|html?)$/i.test(t)&&(/\beval\s*\(|\bnew\s+Function\s*\(/.test(n)&&o.push(`${t} ejecuta c\xF3digo construido en tiempo de ejecuci\xF3n (eval o new Function).`),/\b(?:window\.)?(?:top|parent)\.location\b|\bdocument\.cookie\b/.test(n)&&o.push(`${t} toca la ventana de arriba o las cookies (el CRM lo impide; se mira en la revisi\xF3n).`));return Le("codigo","C\xF3digo para la revisi\xF3n humana",[],o,"Nada que marcar.")}function Rc(e){let o=[...e.recursos.keys()].sort(),t=o.filter(p=>xy.test(p)).map(p=>[p,e.recursos.get(p).toString("utf8")]),{red:n,usaRed:r}=Ry(e.ext,t),a=r||!!e.ext.conexiones?.length||e.ext.servidor!==null,s=By(t),c=e.sinRed?[...a||e.ext.funciones.some(p=>p.red.length)?["La app no puede usar red ni conexiones externas."]:[],...t.flatMap(([p,f])=>/\b(?:fetch|XMLHttpRequest|WebSocket|EventSource|sendBeacon|importScripts)\b|\bimport\s*\(/.test(f)?[`${p} intenta usar una conexi\xF3n fuera del puente del CRM.`]:[]),...n.estado==="aviso"?n.detalles:[]]:[],d=[Le("esquema","Manifiesto y soluci\xF3n v\xE1lidos",[],[],"El manifiesto y su soluci\xF3n pasan el validador del CRM."),e.dePix?Le("firma","Montada por el CRM",[],[],"La ha montado el CRM en este espacio: no viaja a otros ni a la tienda."):Le("firma","Firmada por su desarrollador",e.firmada?[]:["El paquete no va firmado: `forgenex empaquetar` con tu clave registrada."],[],e.enLocal?"Se firma al empaquetar con tu clave (la tienda exige firma).":"Firma v\xE1lida de una clave registrada."),Le("tamano","Tama\xF1o",e.bytes>$c?["El paquete pasa de 5 MB."]:[],[],`${(e.bytes/1024).toFixed(0)} KB de 5 MB.`),Oy(e.ext,t),...Dy(e.ext,t),c.length?Le("red",n.titulo,c):n,Le("politica","Pol\xEDtica de datos",a&&!e.ext.politica_datos?["La app se conecta fuera del CRM: a\xF1ade \xABpolitica_datos\xBB (una direcci\xF3n https con tu pol\xEDtica de datos) al manifiesto."]:[],[],e.ext.politica_datos?`Pol\xEDtica de datos: ${e.ext.politica_datos}`:"No hace falta: no se conecta fuera."),Wy(e.ext,o,t),e.sinRed&&s.estado==="aviso"?Le("codigo",s.titulo,s.detalles):s],u=d.filter(p=>p.estado==="falla").length;return{ok:u===0,version:1,puntos:d,fallas:u,avisos:d.filter(p=>p.estado==="aviso").length}}var xy,Ac,$g,Le,Ec,Cy,jy,xg,Cg,Ay,Ey,qy,qc,jg,ky,Sg,Py,zy,Fy,Og=m(()=>{Pt();Ti();xy=/\.(m?js|cjs|jsx|html?|css|svg)$/i,Ac=12,$g=e=>{let o=[...new Set(e)];return o.length>Ac?[...o.slice(0,Ac),`\u2026 y ${o.length-Ac} m\xE1s`]:o},Le=(e,o,t,n=[],r="")=>({clave:e,titulo:o,estado:t.length?"falla":n.length?"aviso":"ok",detalles:t.length?$g(t):n.length?$g(n):r?[r]:[]}),Ec={buscar:"ver",ver:"ver",listar:"ver",obtener:"ver",pdf:"ver",crear:"crear",actualizar:"editar",mover:"editar",completar:"editar",borrar:"borrar"},Cy=new Set(["contexto.actual","publica.llamar","app.ajustes","extensiones.calcular"]),jy=new Set(["registros.relacionadas","registros.historial","registros.opciones","registros.adjuntar","mensajes.proponer","metricas.calcular"]);xg={ver:"ver",crear:"crear",editar:"cambiar",borrar:"borrar",almacen:"guardar datos",leer:"leer",escribir:"vincular"},Cg=e=>Object.hasOwn(Do,e)?Do[e].nombre:`\xAB${e.replace(/^mod_/,"")}\xBB`;Ay=/(fetch|WebSocket|EventSource|sendBeacon|\.open|import|axios(?:\.[a-z]+)?|\$\.(?:get|post|ajax|getJSON))\s*\(\s*["'`]?$|(?:src|href|action|srcset|poster|data)\s*=\s*["']?$|url\(\s*["']?$|@import\s+(?:url\()?["']?$/i,Ey=new Set(["www.w3.org","w3.org"]),qy=/(?:\.min\.(?:m?js|css)$)|(?:^|\/)(?:jquery|lodash|alpine|react|vue|preact|chart|d3|moment|axios|dompurify|underscore|bootstrap|handlebars)[^/]*\.m?js$/i,qc=(e,o)=>e.some(t=>t===o||t.startsWith("*.")&&o.endsWith(t.slice(1)));jg={white:[255,255,255],black:[0,0,0],red:[255,0,0],green:[0,128,0],blue:[0,0,255],gray:[128,128,128],grey:[128,128,128],silver:[192,192,192],yellow:[255,255,0],orange:[255,165,0],navy:[0,0,128],purple:[128,0,128],lightgray:[211,211,211],lightgrey:[211,211,211],darkgray:[169,169,169],darkgrey:[169,169,169],whitesmoke:[245,245,245],gainsboro:[220,220,220]},ky=/^(transparent|inherit|initial|unset|revert|currentcolor|none)$/i;Sg=([e,o,t])=>{let n=r=>{let a=r/255;return a<=.03928?a/12.92:((a+.055)/1.055)**2.4};return .2126*n(e)+.7152*n(o)+.0722*n(t)},Py=(e,o)=>{let[t,n]=[Sg(e),Sg(o)].sort((r,a)=>a-r);return(t+.05)/(n+.05)};zy=[{nombre:/^jquery$/i,etiqueta:"jQuery",malas:e=>no(e,[3,5,0]),arreglo:"3.5.0 (CVE-2020-11022)"},{nombre:/^lodash$/i,etiqueta:"Lodash",malas:e=>no(e,[4,17,21]),arreglo:"4.17.21 (CVE-2021-23337)"},{nombre:/^moment$/i,etiqueta:"Moment.js",malas:e=>no(e,[2,29,4]),arreglo:"2.29.4 (CVE-2022-31129)"},{nombre:/^handlebars$/i,etiqueta:"Handlebars",malas:e=>no(e,[4,7,7]),arreglo:"4.7.7 (CVE-2021-23369)"},{nombre:/^bootstrap$/i,etiqueta:"Bootstrap",malas:e=>no(e,[3,4,1])||e[0]===4&&no(e,[4,3,1]),arreglo:"3.4.1 o 4.3.1 (CVE-2019-8331)"},{nombre:/^angular(js)?$/i,etiqueta:"AngularJS",malas:e=>e[0]===1,arreglo:"ninguna: AngularJS 1.x ya no recibe arreglos"},{nombre:/^dompurify$/i,etiqueta:"DOMPurify",malas:e=>e[0]===2?no(e,[2,5,4]):no(e,[3,1,3]),arreglo:"2.5.4 o 3.1.3 (CVE-2024-45801)"},{nombre:/^axios$/i,etiqueta:"Axios",malas:e=>e[0]===0?no(e,[0,28,0]):no(e,[1,6,0]),arreglo:"0.28.0 o 1.6.0 (CVE-2023-45857)"},{nombre:/^underscore$/i,etiqueta:"Underscore",malas:e=>no(e,[1,12,1]),arreglo:"1.12.1 (CVE-2021-23358)"}];Fy=/\b(jquery|lodash|moment|handlebars|bootstrap|angularjs|angular|dompurify|axios|underscore|alpine(?:js)?|react|vue|preact|chart\.js|d3)(?:\.js)?(?:\s+javascript\s+library)?[\s@:,-]*v?(\d{1,3}\.\d{1,3}\.\d{1,3})\b/gi});import{Worker as Vy}from"node:worker_threads";var Uy,kc,Li,Ag=m(()=>{gr();Uy=new URL(import.meta.url.endsWith(".ts")?"./caja.ts":"./caja.js",import.meta.url),kc=class{w=null;ocupada=!1;worker(){return this.w?this.w:(this.w=new Vy(Uy,{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,c=(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>z.llamadaCaracteres||s>=z.llamadasEnVuelo){n.postMessage({tipo:"respuesta",n:b.n,ok:!1,valor:typeof b.datos=="string"&&b.datos.length<=z.llamadaCaracteres?"demasiadas llamadas a la vez":"lo que se manda al CRM es demasiado grande"});return}let v=null;try{v=JSON.parse(b.datos)}catch{}s++,o.manejar(b.que,v).finally(()=>{s--}).then(w=>!a&&n.postMessage({tipo:"respuesta",n:b.n,ok:!0,valor:JSON.stringify(w??null)}),w=>!a&&n.postMessage({tipo:"respuesta",n:b.n,ok:!1,valor:w instanceof Error?w.message:String(w)}));return}let y=Date.now()-t;b.ok?c({ok:!0,salida:b.salida,ms:y},!1):c({ok:!1,corte:b.corte,clase:b.clase,mensaje:b.mensaje,ms:y},b.corte!==null)},u=b=>c({ok:!1,corte:/memory|heap/i.test(b.message)?"memoria":null,clase:"Error",mensaje:"la caja se ha cerrado",ms:Date.now()-t},!0),p=()=>c({ok:!1,corte:null,clase:"Error",mensaje:"la caja se ha cerrado",ms:Date.now()-t},!0),f=setTimeout(()=>c({ok:!1,corte:"tiempo",clase:"InternalError",mensaje:"interrupted",ms:Date.now()-t},!0),o.ms+z.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:z.pilaBytes,salidaBytes:z.salidaBytes,llamadaCaracteres:z.llamadaCaracteres,enVuelo:z.llamadasEnVuelo};n.postMessage(h)})}cerrar(){this.matar()}},Li=class{ranuras;cola=[];constructor(o=z.simultaneas){this.ranuras=Array.from({length:Math.max(1,o)},()=>new kc)}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 Jy}from"node:dns/promises";import{request as Qy}from"node:https";import{isIP as Gy}from"node:net";async function Tc(e,o,t={}){let n;try{n=new URL(e.url)}catch{throw new he("direcci\xF3n no v\xE1lida")}if(n.protocol!=="https:")throw new he("solo https");if(n.username||n.password)throw new he("sin usuario ni clave en la direcci\xF3n");if(n.port&&n.port!=="443")throw new he("solo al puerto 443");let r=n.hostname.toLowerCase().replace(/\.$/,"");if(Gy(r.replace(/^\[|\]$/g,""))||!Pc(o,r))throw new he("el dominio no est\xE1 entre los dominios aceptados");let a=String(e.metodo||"GET").toUpperCase();if(!Eg.has(a))throw new he("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(!Xy.test(f)||Hy.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 c=e.cuerpo===null||e.cuerpo===void 0?null:String(e.cuerpo);if(c!==null&&Buffer.byteLength(c)>z.red.cuerpoBytes)throw new he(`el cuerpo pasa de ${z.red.cuerpoBytes/1024} KB`);if(c!==null&&(a==="GET"||a==="HEAD"))throw new he("GET y HEAD no llevan cuerpo");let d=await(t.resolver??(f=>Jy(f,{all:!0,verbatim:!0})))(r).catch(()=>[]);if(!d.length)throw new he(`${r.slice(0,80)} no resuelve`);if(d.some(f=>zp(f.address)))throw new he(`${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??Ky)(u,{metodo:a,cabeceras:s,cuerpo:c});return{host:r,respuesta:p}}function Ky(e,o){return new Promise((t,n)=>{let r={...o.cabeceras,...o.cuerpo!==null?{"content-length":String(Buffer.byteLength(o.cuerpo))}:{}},a=Qy({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:((c,d,u)=>d?.all?u(null,[{address:e.ip,family:e.familia}]):u(null,e.ip,e.familia)),timeout:z.red.plazoMs,agent:!1},c=>{let d=[],u=0;c.on("data",p=>{if(u+=p.length,u>z.red.respuestaBytes){c.destroy(),n(new he(`la respuesta pasa de ${z.red.respuestaBytes/1024/1024} MB`));return}d.push(p)}),c.on("end",()=>{clearTimeout(s);let p={};for(let f of Yy){let h=c.headers[f];typeof h=="string"&&(p[f]=h.slice(0,2e3))}t({status:c.statusCode??0,headers:p,cuerpo:Buffer.concat(d).toString("utf8")})}),c.on("error",()=>n(new he("la respuesta se cort\xF3")))}),s=setTimeout(()=>a.destroy(new he("sin respuesta a tiempo")),z.red.plazoMs);a.on("timeout",()=>a.destroy(new he("sin respuesta a tiempo"))),a.on("error",c=>{clearTimeout(s),n(c instanceof he?c:new he("no se ha podido conectar"))}),a.end(o.cuerpo??void 0)})}var he,Eg,Hy,Xy,Yy,Pc,Mc=m(()=>{Fp();gr();he=class extends Error{constructor(t){super(`fetch: ${t}`);this.motivo=t}motivo},Eg=new Set(["GET","POST","PUT","PATCH","DELETE","HEAD"]),Hy=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"]),Xy=/^[A-Za-z0-9!#$%&'*+.^_`|~-]{1,64}$/,Yy=["content-type","location","retry-after","etag","last-modified"],Pc=(e,o)=>e.some(t=>t===o||t.startsWith("*.")&&o.endsWith(t.slice(1))&&o.length>t.length-1)});function Rg(e,o){if(typeof o!="string"||typeof e!="string")return null;let n=(Object.hasOwn(qg,o)?qg[o]:null)??ao(o);if(!n)return null;let r=n.startsWith("mod_");switch(e){case"ver":return r?`${n}.ver`:Zy[n]??`${n}.ver`;case"buscar":return r?`${n}.listar`:e_[n]??`${n}.buscar`;case"crear":return`${n}.crear`;case"actualizar":return`${n}.actualizar`;default:return null}}function kg(e,o){return e.filter(t=>Pc(o,t.startsWith("*.")?`x${t.slice(1)}`:t)&&(!t.startsWith("*.")||o.includes(t)))}var qg,Zy,e_,Pg=m(()=>{Pt();Mc();qg={contactos:"contactos",contacts:"contactos",empresas:"empresas",companies:"empresas",oportunidades:"oportunidades",deals:"oportunidades",tareas:"tareas",tasks:"tareas",notas:"notas"},Zy={tareas:"tareas.obtener"},e_={tareas:"tareas.listar",notas:"notas.listar"}});var Ig={};Gg(Ig,{iniciarDev:()=>a_});import{createServer as o_}from"node:http";import{randomBytes as Tg}from"node:crypto";import{readFileSync as t_,realpathSync as Mg,watch as r_}from"node:fs";import{join as n_,sep as i_}from"node:path";async function a_(e){let o=hr(e),t=Number(Ue(e,"puerto")??5173),n=Mg(process.cwd());if(!Number.isInteger(t)||t<1||t>65535)throw new Error("Puerto no v\xE1lido.");let r=yo(n),a=(_,C)=>fr(o.api,o.clave,"/api/desarrollador/desarrollo",{espacio:o.espacio,ext_id:r.id,pase:_,funcion:C}),s=await a();await mr(n);let c=new Li(1),d=Tg(24).toString("hex"),u=1,p=null,f,h=r_(n,{recursive:!0},(_,C)=>{let S=String(C??"");/node_modules|\.fgx$|\.pem|^\.git[\/\\]/.test(S)||S==="interfaz/app.js"||(clearTimeout(f),f=setTimeout(()=>{p=mr(n).then(()=>{yo(n),u++,console.log("App actualizada.")}).catch(P=>console.error("Error de desarrollo:",P.message)).finally(()=>{p=null})},100))}),b=o_(async(_,C)=>{let S=(P,Z)=>{C.writeHead(P,{"content-type":"application/json","cache-control":"no-store"}),C.end(JSON.stringify(Z))};try{if(![`127.0.0.1:${t}`,`localhost:${t}`].includes(_.headers.host??""))return S(403,{error:"host_no_permitido"});let P=_.headers.origin;if(P&&P!==o.api)return S(403,{error:"origen_no_permitido"});if(P===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"),_.method==="OPTIONS"){C.writeHead(204),C.end();return}let Z=new URL(_.url??"/",`http://127.0.0.1:${t}`),we=decodeURIComponent(Z.pathname);if(!we.startsWith(`/${d}/`))return S(404,{error:"no_encontrado"});let $=we.slice(d.length+2);if($==="__forgenex/version"&&_.method==="GET")return S(200,{version:u});if($.startsWith("__forgenex/funcion/")&&_.method==="POST"){if(P!==o.api)return S(403,{error:"origen_no_permitido"});let x=(_.headers.authorization??"").replace(/^Bearer /,"");if(!x.startsWith("crmui_"))return S(401,{error:"falta_pase"});if(!c.libres)return S(429,{error:"funcion_ocupada"});let A=$.slice(19),k=await a(x,A),F=yo(n).funciones.find(De=>De.nombre===A),G=k.manifiesto.funciones.find(De=>De.nombre===A);if(!F||!G)return S(403,{error:"funcion_no_instalada"});let Je=await fetch(`${o.api}/api/v1/capabilities`,{redirect:"error",headers:{authorization:`Bearer ${x}`,"x-espacio":String(o.espacio)}});if(!Je.ok)return S(Je.status,{error:"pase_revocado"});let tt=await s_(_),rt=Tg(12).toString("hex"),H=0,Qe=0,Ce=await c.correr({codigo:y(F.entrada).toString("utf8"),fichero:F.entrada,entrada:tt,contexto:{extension:r.id,version:r.version,funcion:A,disparo:"desarrollo",ejecucion:rt},...tl(F),manejar:async(De,R)=>{if(De==="red"){if(++Qe>z.llamadasRed)throw new Error("Demasiadas peticiones de red.");return(await Tc(R,kg(G.red,k.aceptados.red_hacia))).respuesta}if(++H>z.llamadasApi)throw new Error("Demasiadas llamadas al CRM.");let D=R,oe=D.op??Rg(D.accion,D.modulo);if(!oe||!/^[a-z][a-z0-9_]*\.[a-z][a-z0-9_]*$/.test(oe))throw new Error("Operaci\xF3n no v\xE1lida.");let Rt=await fetch(`${o.api}/api/v1/capabilities`,{redirect:"error",headers:{authorization:`Bearer ${x}`,"x-espacio":String(o.espacio)}});if(!Rt.ok)throw new Error("Pase caducado o revocado.");let Bc=await Rt.json(),Vc=(Bc.data?.operaciones??Bc.operaciones??[]).find(zi=>zi.id===oe);if(!Vc)throw new Error("Operaci\xF3n no aceptada por el administrador.");let Di=Vc.metodo,Uc=D.args??{},Ug=Di==="GET"?`?${new URLSearchParams(Object.entries(Uc).map(([zi,Jg])=>[zi,String(Jg)]))}`:"",Jc=await fetch(`${o.api}/api/v1/op/${oe}${Ug}`,{method:Di,redirect:"error",headers:{authorization:`Bearer ${x}`,"x-espacio":String(o.espacio),"content-type":"application/json","idempotency-key":`dev-${rt}-${H}`},...Di==="POST"?{body:JSON.stringify(Uc)}:{}}),Qc=await Jc.json();if(!Jc.ok)throw new Error(Qc.error?.mensaje??"El CRM rechaz\xF3 la operaci\xF3n.");return Qc.data}});return Ce.ok||console.error(`Funci\xF3n ${A}: ${Ce.clase}: ${Ce.mensaje}`),S(Ce.ok?200:422,Ce)}if(_.method!=="GET")return S(405,{error:"metodo_no_permitido"});if(await p,!$.startsWith("interfaz/"))return S(404,{error:"no_encontrado"});let M=y($),g=$.endsWith(".html")?"text/html":$.endsWith(".js")?"text/javascript":$.endsWith(".css")?"text/css":"application/octet-stream";C.writeHead(200,{"content-type":g,"cache-control":"no-store"}),C.end(M)}catch(P){console.error("Error de desarrollo:",P.message),S(400,{error:"desarrollo_error",mensaje:P.message})}});function y(_){if(_.includes("\\")||_.split("/").some(P=>P===".."||P==="."||!P))throw new Error("Ruta no admitida.");let C=Mg(n_(n,_));if(!C.startsWith(n+i_))throw new Error("Ruta fuera del proyecto.");let S=t_(C);if(S.length>2*1024*1024)throw new Error("Recurso demasiado grande.");return S}let v=()=>{clearTimeout(f),h.close(),c.cerrar(),b.closeAllConnections(),b.close()};b.on("error",_=>{console.error(_.message),v(),process.exitCode=1}),process.once("SIGINT",v),process.once("SIGTERM",v),await new Promise((_,C)=>{b.once("error",C),b.listen(t,"127.0.0.1",_)});let w=`http://127.0.0.1:${t}/${d}`;console.log(`Desarrollo: ${w}
|
|
42
|
-
Abrir CRM: ${
|
|
43
|
-
Recarga al guardar. Funciones: crm.pedir("desarrollo.funcion", { nombre, entrada }, { metodo: "POST", idempotencia: crypto.randomUUID() }).`)}async function
|
|
44
|
-
`)}function
|
|
45
|
-
P\xFAblica: ${t}.pub`),0}if(e==="registrar-clave"){let t=hr(o),n=nn(Lc(o),"utf8");return console.log(JSON.stringify(await fr(t.api,t.clave,"/api/desarrollador/claves",{espacio:t.espacio,publica:Dg(n).export({type:"spki",format:"pem"}).toString()}))),0}if(e==="revocar-clave"){let t=hr(o),n=Ue(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 fr(t.api,t.clave,"/api/desarrollador/revocar-clave",{espacio:t.espacio,id:n}))),0}if(e==="empaquetar"){if(o.includes("--sin-firmar")){let n=await Oc(process.cwd());return console.log(`${n} \xB7 Para \xABSubir paquete\xBB con el modo desarrollador encendido.`),0}let t=nn(Lc(o),"utf8");return console.log(await Oc(process.cwd(),t,Dg(t).export({type:"spki",format:"pem"}).toString())),0}if(e==="instalar"){let t=hr(o),n=Ue(o,"paquete"),r=Ue(o,"app"),a=Ue(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:nn(n).toString("base64")},c=await fr(t.api,t.clave,"/api/desarrollador/instalar",s);return console.log(JSON.stringify(c)),c?.pendiente_permisos!==!1&&console.log("El administrador debe aceptar los permisos en Ajustes \u203A Apps."),0}if(e==="revisar"){let t=Ue(o,"paquete"),n;if(t){let r=nn(t),a=pr(r),s=a.get("extension.json");if(!s)throw new Error("Al paquete le falta \xABextension.json\xBB.");n=Rc({ext:zo(s.toString("utf8")),recursos:a,firmada:a.has(Zr),bytes:r.length,enLocal:!0})}else{let r=process.cwd();await mr(r);let a=Sc(r),s=zo(a.get("extension.json").toString("utf8"));n=Rc({ext:s,recursos:a,firmada:!0,bytes:[...a.values()].reduce((c,d)=>c+d.length,0),enLocal:!0})}return console.log(o.includes("--json")?JSON.stringify(n,null,2):Dc(n)),n.ok?0:1}if(e==="publicar"){let t=hr(o),n=Ue(o,"paquete"),r=o.includes("--tienda");if(!n)throw new Error("Falta --paquete <archivo.fgx> (lo hace `forgenex empaquetar`).");let a=await fr(t.api,t.clave,"/api/desarrollador/publicar",{espacio:t.espacio,paquete:nn(n).toString("base64"),...r?{tienda:!0}:{}});console.log(JSON.stringify({...a,tienda:a.tienda?{estado:a.tienda.estado,humana:a.tienda.humana,porcentaje:a.tienda.porcentaje}:void 0}));let s=c=>a.espacios.filter(d=>d.resultado===c).length;return console.log(`Publicada ${a.ext_id} ${a.version} en tus apps.`),a.tienda&&(console.log(Dc(a.tienda.informe)),console.log(a.tienda.estado==="aprobada"?`\xB7 En la tienda: publicada sola (no pide m\xE1s que la versi\xF3n anterior), al ${a.tienda.porcentaje} % de los espacios; sube al 100 % en 24 h si no da errores.`:`\xB7 En la tienda: en revisi\xF3n (${a.tienda.humana.map(c=>({primera:"es la primera versi\xF3n",permisos:"pide permisos nuevos",red:"se conecta a un dominio nuevo",publica:"trae una p\xE1gina p\xFAblica nueva",todas:"por ahora se revisa cada versi\xF3n"})[c]??c).join(", ")}). Te avisamos al decidir; el estado sale en el panel, Perfil \u203A Desarrollador.`)),s("activa")&&console.log(`\xB7 Actualizada sola en ${s("activa")} espacio(s): no pide m\xE1s permisos.`),s("pendiente_permisos")&&console.log(`\xB7 En ${s("pendiente_permisos")} espacio(s) pide m\xE1s permisos: su administrador los acepta en Ajustes \u203A Apps.`),s("a_mano")&&console.log(`\xB7 En ${s("a_mano")} espacio(s) no se aplica sola (cambian sus m\xF3dulos, o lo instalado all\xED no sali\xF3 de \xABMis apps\xBB): actual\xEDzala con \`forgenex instalar --app ${a.ext_id} --espacio <id>\`.`),s("modo_desarrollador")&&console.log(`\xB7 En ${s("modo_desarrollador")} espacio(s) el modo desarrollador est\xE1 apagado: no se ha tocado.`),s("error")&&console.log(`\xB7 En ${s("error")} espacio(s) no se ha podido actualizar: prueba con \`forgenex instalar --app\`.`),s("cliente_ajeno")&&console.log(`\xB7 En ${s("cliente_ajeno")} espacio(s) no se ha tocado: en ForgeNEX ya no son tuyos ni de un cliente tuyo.`),s("panel_no_disponible")&&console.log(`\xB7 En ${s("panel_no_disponible")} espacio(s) no se ha tocado porque no se ha podido comprobar con ForgeNEX: vuelve a publicar en un momento o usa \`forgenex instalar --app\`.`),0}if(e==="dev"){let{iniciarDev:t}=await Promise.resolve().then(()=>(Lg(),Ig));return await t(o),0}return null}var p_,Ic=m(()=>{Ii();Pt();Ti();xc();Og();p_={ok:"\u2713",aviso:"!",falla:"\u2717"}});Ic();Ii();Gr();Es();Nc();dc();gi();lc();Pt();import{readFileSync as zc,statSync as m_}from"node:fs";import{join as f_}from"node:path";var Fc=200;function h_(e,o){try{return{archivo:e,ok:!0,solucion:Kr(o,{topeCampos:Fc})}}catch(t){return{archivo:e,ok:!1,error:t instanceof Error?t.message:String(t)}}}function g_(e){try{let o=JSON.parse(e);return typeof o=="object"&&o!==null&&o.formato===nt}catch{return!1}}function b_(e,o){try{return{archivo:e,ok:!0,extension:zo(o)}}catch(t){return{archivo:e,ok:!1,error:t instanceof Error?t.message:String(t)}}}function w_(){let e=n=>n.length>1?`${n.slice(0,-1).join(", ")} y ${n.at(-1)}`:n[0]??"",o=kt.filter(n=>pn.has(n)).map(n=>`\xAB${n}\xBB`),t=kt.filter(n=>!pn.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 v_(){let e=c=>({type:"string",maxLength:c}),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).",a={type:"string",pattern:"^[a-z][a-z0-9_.-]{0,79}$",description:"Un nombre de contrato suelto (como antes de la R5): no ofrece ni pide nada."},s=c=>({type:"object",additionalProperties:!1,required:c?["contrato","de"]:["contrato"],properties:{contrato:{type:"string",pattern:"^[a-z][a-z0-9_.-]{0,79}$",description:"Su nombre (\xABtaller.vehiculos\xBB)."},...c?{de:{type:"string",description:"El id de la app que lo ofrece (\xABcom.taller.vehiculos\xBB)."}}:{},titulo:{type:"string",maxLength:80,description:"C\xF3mo se llama en la pantalla de permisos (\xABVeh\xEDculos del taller\xBB)."},modulos:{type:"object",maxProperties:20,additionalProperties:{type:"array",minItems:1,maxItems:4,items:{enum:["ver","crear","editar","borrar"]}},description:"M\xF3dulos de la soluci\xF3n de la app que lo ofrece, con su clave del manifiesto (\xABvehiculos\xBB), y sus operaciones."},eventos:{type:"array",maxItems:3,items:{enum:["registro.creado","registro.actualizado","registro.borrado"]},description:"Los de los registros de sus m\xF3dulos (con \xABver\xBB de alguno)."},herramientas:{type:"array",maxItems:20,items:{type:"string",pattern:"^[a-z][a-z0-9_]{2,40}$"},description:"Herramientas (herramientas_ia) que no escriben; se usan con la operaci\xF3n v1 \xABapp.usar_herramienta\xBB."}}});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${nt}\xBB, versi\xF3n ${dn}. 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:nt},formato_version:{type:"integer",minimum:1,maximum:dn,description:"Versi\xF3n del FORMATO (no de la app)."},id:{type:"string",maxLength:200,pattern:"^[a-z][a-z0-9-]{0,62}(\\.[a-z0-9][a-z0-9-]{0,62}){1,6}$",description:"Dominio inverso: com.tuempresa.mi-extension. No cambia nunca."},nombre:e(80),descripcion:e(500),version:{type:"string",pattern:"^(0|[1-9][0-9]{0,5})\\.(0|[1-9][0-9]{0,5})\\.(0|[1-9][0-9]{0,5})(-[0-9a-z.-]{1,30})?$",description:"La versi\xF3n de la app (semver)."},autor:{oneOf:[e(120),{type:"object",additionalProperties:!1,required:["nombre"],properties:{nombre:e(120),web:{type:"string",format:"uri",description:"https"}}}]},icono:{type:"string",pattern:"^[a-z0-9-]{1,40}$",description:"Un icono de lucide."},idiomas:{type:"array",maxItems:30,items:{type:"string",pattern:"^[a-z]{2,3}(-[A-Z]{2})?$"}},compatible_crm:{type:"string",maxLength:80,description:"Rango de versiones del CRM: \xAB>=1.6.0-284\xBB o \xAB>=1.6.0-284 <2.0.0\xBB."},licencia:e(40),politica_datos:{type:"string",format:"uri",description:"https: tu pol\xEDtica de datos. Obligatoria para entrar en la tienda si la app usa red (permisos.red_hacia)."},depende_de:{type:"array",maxItems:20,description:"Otras apps que tienen que estar instaladas.",items:{oneOf:[{type:"string"},{type:"object",additionalProperties:!1,required:["id"],properties:{id:{type:"string"},version:{type:"string"}}}]}},ofrece:{type:"array",maxItems:20,description:"Contratos que publica para otras apps: m\xF3dulos de SU soluci\xF3n (con operaciones que ella misma pide), eventos de registro de esos m\xF3dulos (que ella escucha) y herramientas suyas que no escriben. Otra app los usa con \xABusa\xBB y el permiso del administrador.",items:{oneOf:[a,s(!1)]}},usa:{type:"array",maxItems:20,description:"Contratos de otras apps que usa: \xABde\xBB es el id de la app que lo ofrece; lo que se concede es lo que esa app ofrece \u2229 lo que se pide, si el administrador lo acepta. Sin eso, 403.",items:{oneOf:[a,s(!0)]}},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:w_(),items:{type:"object",additionalProperties:!1,required:["id","punto","entrada","titulo"],properties:{id:{type:"string",pattern:"^[a-z][a-z0-9_-]{0,40}$"},punto:{enum:[...kt]},entrada:t,titulo:e(60),icono:{type:"string"},modulo:{type:"string",description:`Solo en ${[...br].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:[...br]}},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:[...ln]},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:[...un]},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)}}},conexiones:{type:"array",maxItems:20,items:{type:"object",additionalProperties:!1,required:["clave","base","tipo","operacion"],properties:{clave:{type:"string",pattern:"^[a-z][a-z0-9_]{0,40}$"},base:{type:"string",pattern:"^https://",maxLength:1e3},tipo:{enum:["api_key","bearer","basic","oauth2"]},operacion:{type:"string",pattern:"^[a-zA-Z][a-zA-Z0-9_.-]{0,79}$"},lugar:{enum:["cabecera","query"]},nombre:{type:"string",pattern:"^[a-zA-Z][a-zA-Z0-9_.-]{0,79}$"}},if:{properties:{tipo:{const:"api_key"}}},then:{required:["lugar","nombre"]},else:{not:{anyOf:[{required:["lugar"]},{required:["nombre"]}]}}}},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(Do).map(([c,d])=>`${c} (${d.ops.join(", ")})`).join("; ")}. Los de su soluci\xF3n o del espacio, por su clave: ${Lo.join(", ")}.`,additionalProperties:{type:"array",minItems:1,maxItems:4,uniqueItems:!0,items:{enum:[...Lo]}}},almacen:{type:"boolean",description:"Guardar sus datos internos (clave-valor JSON) en el almac\xE9n de la app."},red_hacia:{type:"array",maxItems:20,items:o,description:"Los dominios a los que pueden conectarse sus funciones (\xAB*.ejemplo.com\xBB cubre sus subdominios). El administrador acepta cada uno."},eventos:{type:"array",maxItems:40,items:{type:"string"},description:"Los eventos del CRM de los que se entera (registro.creado, registro.actualizado\u2026). El administrador acepta cada uno."},archivos:{type:"array",maxItems:2,uniqueItems:!0,items:{enum:["leer","escribir"]},description:"1.17.0: los archivos del almacenamiento del espacio que la persona ELIGE con archivos.elegir() (el explorador del CRM). \xABleer\xBB: verlos (archivos.leer); \xABescribir\xBB (pide tambi\xE9n \xABleer\xBB): vincularlos a una ficha (archivos.vincular). Nunca ve el \xE1rbol ni recibe tokens de OneDrive o Google."}}}},"x-forgenex":{tamanoMaximoBytes:cn}}}function Vg(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 y_(){let e=o=>({type:"string",maxLength:o});return{$schema:"https://json-schema.org/draft/2020-12/schema",$id:`https://forgenex.com/sdk/solucion-v${dr}.schema.json`,title:"Soluci\xF3n del CRM ForgeNEX",description:`Formato \xAB${qt}\xBB, versi\xF3n ${dr}. 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:qt},version:{type:"integer",minimum:1,maximum:dr,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}$"},conexiones:{type:"array",maxItems:25,items:{oneOf:[{type:"object",additionalProperties:!1,required:["tipo","conector"],properties:{clave:{type:"string"},nombre:{type:"string",maxLength:80},tipo:{const:"conector"},conector:{type:"string",pattern:"^[a-z][a-z0-9_-]{0,39}$"}}},{type:"object",additionalProperties:!1,required:["clave","nombre","tipo"],properties:{clave:{type:"string",pattern:"^[a-z][a-z0-9_]{0,39}$"},nombre:{type:"string",minLength:1,maxLength:120},tipo:{enum:["api","mcp"]}}}]}},fuentesExternas:{type:"array",maxItems:30,items:{type:"object",additionalProperties:!1,required:["modulo","conexion","operacion","filas","mapeo","modo"],properties:{modulo:{type:"string"},conexion:{type:"string"},operacion:{type:"string"},filas:{type:"string",maxLength:160},mapeo:{type:"object",minProperties:1,additionalProperties:{type:"string",maxLength:160}},modo:{enum:["vivo","espejo"]},minutos:{type:"integer",minimum:5,maximum:10080},id_externo:{type:"string",maxLength:160},cursor:{type:"object",additionalProperties:!1,required:["ruta","parametro"],properties:{ruta:{type:"string",maxLength:160},parametro:{type:"string",maxLength:80}}}},if:{properties:{modo:{const:"espejo"}}},then:{required:["minutos","id_externo","cursor"]}}},modulos:{type:"array",minItems:1,maxItems:Ri,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:[...Js]},campos:{type:"array",maxItems:Fc,items:{type:"object",required:["clave","etiqueta","tipo"],properties:{clave:{type:"string"},etiqueta:e(80),tipo:{enum:[...Vs]},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(As.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:pi,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:mi,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:bc,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:yc,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:gc,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:wc,description:"Se instalan APAGADAS: una persona las revisa y las enciende."},ejemplos:{type:"object",description:`Datos de ejemplo por clave de m\xF3dulo (hasta ${Pi} cada uno).`,additionalProperties:{type:"array",maxItems:Pi}},informes:{type:"array",maxItems:Yr,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:Ei,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:vc,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:_c,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:ki,topeCampos:Fc}}}async function Wc(e){let[o,...t]=e,n=await Bg(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(`${qt} v${dr}`),0;if(o==="esquema")return console.log(JSON.stringify(y_(),null,2)),0;if(o==="esquema-extension")return console.log(JSON.stringify(v_(),null,2)),0;if((o==="validar"||o==="previsualizar")&&a.length){let s=a.map(c=>{let d;try{m_(c).isDirectory()?(yo(c),d=zc(f_(c,"extension.json"),"utf8")):o==="validar"&&c.toLowerCase().endsWith(".fgx")?d=Ng(zc(c)):d=zc(c,"utf8")}catch(u){return{archivo:c,ok:!1,error:u instanceof Error?u.message:String(u)}}return g_(d)?b_(c,d):h_(c,d)});if(r)console.log(JSON.stringify(s.map(c=>c.ok?"extension"in c?{archivo:c.archivo,ok:!0,extension:c.extension}:{archivo:c.archivo,ok:!0,resumen:Vg(c.solucion)}:c)));else for(let c of s){if(!c.ok){console.log(`\u2717 ${c.archivo}: ${c.error}`);continue}if("extension"in c){let d=c.extension;console.log(`\u2713 ${c.archivo}: app \xAB${d.nombre}\xBB ${d.version} (${d.id})`);for(let[f,h]of Object.entries(d.permisos.modulos))console.log(` \xB7 pide ${f}: ${h.join(", ")}`);d.permisos.almacen&&console.log(" \xB7 pide su almac\xE9n"),d.permisos.archivos?.length&&console.log(` \xB7 pide archivos (lo que la persona elija): ${d.permisos.archivos.join(", ")}`);let u=[...new Set(d.montajes.filter(f=>!pn.has(f.punto)).map(f=>`montajes.${f.punto}`))];for(let f of d.funciones)console.log(` \xB7 funci\xF3n ${f.nombre} (${f.disparador.tipo}${f.disparador.evento?`: ${f.disparador.evento}`:f.disparador.cron?`: ${f.disparador.cron}`:""})`);for(let f of d.permisos.red_hacia)console.log(` \xB7 se conecta a ${f}`);let p=[...u,d.servidor&&"servidor"].filter(Boolean);p.length&&console.log(` (v\xE1lidos, pero a\xFAn no se ejecutan: ${p.join(", ")})`);continue}if(console.log(`\u2713 ${c.archivo}: \xAB${c.solucion.nombre}\xBB, ${c.solucion.modulos.length} m\xF3dulos`),o==="previsualizar"){let d=Vg(c.solucion);for(let u of d.modulos)console.log(` \xB7 ${u.nombre} (${u.clave}): ${u.campos} campos${u.relaciones.length?`, \u2192 ${u.relaciones.join(", ")}`:""}${u.vistas?`, ${u.vistas} vistas`:""}`);console.log(` paneles: ${d.paneles} \xB7 automatizaciones: ${d.automatizaciones} (se instalan apagadas)`)}}return s.every(c=>c.ok)?0:1}return console.log("Uso: forgenex crear-app <nombre> [--plantilla html|react|archivos] \xB7 validar [directorio|archivo.json|archivo.fgx \u2026] [--json] \xB7 dev --espacio <id> \xB7 empaquetar [--sin-firmar] \xB7 instalar --espacio <id> (--app <id> | --paquete <archivo.fgx>) \xB7 publicar --espacio <id> --paquete <archivo.fgx> [--tienda] \xB7 revisar [--paquete <archivo.fgx>] [--json] \xB7 claves crear \xB7 registrar-clave \xB7 revocar-clave \xB7 previsualizar \xB7 esquema \xB7 esquema-extension \xB7 version"),2}process.argv[1]?.endsWith("cli.ts")&&Wc(process.argv.slice(2)).then(e=>{process.exitCode=e}).catch(e=>{console.error(e instanceof Error?e.message:String(e)),process.exitCode=1});Wc(process.argv.slice(2)).then(e=>{process.exitCode=e}).catch(e=>{console.error(e instanceof Error?e.message:String(e)),process.exitCode=1});
|
|
40
|
+
`),Fe(n),n}function Fe(e){let o=Vo(mr(B(e,"extension.json"),"utf8"));o.solucion&&tn(mr(B(e,o.solucion),"utf8"),{topeCampos:200});for(let t of[...o.montajes,...o.funciones]){let n=B(e,t.entrada),r=t.entrada.replace(/\.js$/,".ts");mr(r!==t.entrada&&!Qy(n)?B(e,r):n)}return o}function Lg(e){let o=zo(e),t=a=>{let s=o.get(a);if(!s)throw new Error(`Al paquete le falta \xAB${a}\xBB.`);return s.toString("utf8")},n=t("extension.json"),r=Vo(n);r.solucion&&tn(t(r.solucion),{topeCampos:200});for(let a of[...r.montajes,...r.funciones])t(a.entrada);return n}async function fr(e){if(!an(e).includes("src")||!an(B(e,"src")).includes("main.jsx"))return;let o=Bi(B(e,"package.json")),t;try{t=o("esbuild")}catch{try{t=Bi(B(ao,"../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:[B(e,"src/main.jsx")],outfile:B(e,"interfaz/app.js"),bundle:!0,format:"esm",minify:!0,jsx:"automatic",target:"es2020",external:["@forgenex/crm-sdk","@forgenex/forja","@forgenex/kit"],nodePaths:[B(ao,"../src/node_modules")],define:{"process.env.NODE_ENV":'"production"'},legalComments:"none"})}function Lc(e){let o=Fe(e),t=new Map,n=Ig(e),r=u=>{let p=B(e,u);if(!Ig(p).startsWith(n+Yy))throw new Error("El paquete no admite enlaces fuera del proyecto.");t.set(u,mr(p))},a=u=>{for(let p of an(B(e,u),{withFileTypes:!0})){if(p.isSymbolicLink())throw new Error("El paquete no admite enlaces simb\xF3licos.");p.isDirectory()?a(`${u}/${p.name}`):r(`${u}/${p.name}`)}};r("extension.json"),o.solucion&&r(o.solucion);for(let u of["interfaz","funciones"])an(e).includes(u)&&a(u);let s=Bi(B(e,"package.json")),c=Bi(B(ao,"../api/package.json")),d=Rg(t,(u,p)=>{let m;try{m=s("esbuild")}catch{m=c("esbuild")}return m.transformSync(u,p)});return zo(Ic(d)),d}async function sn(e,...o){await fr(e);let t=Lc(e);o.length&&t.set(rn,Tg(t,...o));let n=Ic(t);zo(n);let r=Fe(e),a=`${r.id.split(".").at(-1)}-${r.version}.fgx`;return Dg(B(e,a),n),B(e,a)}var ao,cn=f(()=>{Tt();Tc();kg();vr();Mc();Mg();ao=Xy(Hy(Ky(import.meta.url)),"..")});function t_(e,o){let t=[],n=[],r=s=>{if(e_.has(s)||o_.has(s))return;let[c,d]=s.split(".");if(c==="almacen")return t.push({prefijo:"almacen",op:"almacen",donde:o});if(c==="archivos")return d==="leer"||d==="elegir"?t.push({prefijo:"archivos",op:"leer",donde:o}):d==="vincular_elegido"?t.push({prefijo:"archivos",op:"escribir",donde:o}):n.push(s);let u=Object.hasOwn(Bo,c)?c:c.startsWith("mod_")?lo(c):null,p=Object.hasOwn(Fc,d)?Fc[d]:null;if(!u||!p)return n.push(s);t.push({prefijo:u,op:u==="notas"&&p!=="ver"?"editar":p,donde:o})};for(let s of e.matchAll(/\.(?:pedir|llamar)\(\s*["'`]([a-z][a-z0-9_]*\.[a-z_]+)["'`]/g))r(s[1]);for(let s of e.matchAll(/\bcrm\.(ver|buscar|crear|actualizar)\(\s*["'`]([a-z][a-z0-9_]*)["'`]/g)){let c=lo(s[2]);c&&t.push({prefijo:c,op:Fc[s[1]],donde:o})}/\bcrm\.almacen\.(leer|listar|guardar|borrar)\(/.test(e)&&t.push({prefijo:"almacen",op:"almacen",donde:o}),/\.archivos\.(elegir|leer)\(/.test(e)&&t.push({prefijo:"archivos",op:"leer",donde:o}),/\.archivos\.vincular\(/.test(e)&&t.push({prefijo:"archivos",op:"escribir",donde:o});let a=/\.(?:pedir|llamar)\(\s*[A-Za-z_$]/.test(e)||/\bcrm\.(ver|buscar|crear|actualizar)\(\s*[A-Za-z_$]/.test(e);return{usos:t,desconocidas:n,dinamicas:a}}function r_(e,o){let t=[],n=[],r=new Set,a=!1;for(let[s,c]of o){let d=t_(c,s);a||=d.dinamicas;for(let u of d.desconocidas)n.push(`${s} llama a \xAB${u}\xBB, que una app no puede usar: el CRM le contestar\xE1 que no tiene permiso.`);for(let u of d.usos)r.add(`${u.prefijo}:${u.op}`),u.prefijo==="almacen"?e.permisos.almacen||t.push(`${u.donde} guarda datos de la app y no pide \xABalmacen\xBB.`):u.prefijo==="archivos"?(e.permisos.archivos??[]).includes(u.op)||t.push(`${u.donde} usa archivos (\xAB${u.op}\xBB) y no lo pide en \xABpermisos.archivos\xBB.`):(e.permisos.modulos[u.prefijo]??[]).includes(u.op)||t.push(`${u.donde} necesita ${Fg[u.op]} ${Wg(u.prefijo)} y no lo pide en \xABpermisos.modulos\xBB.`)}if(a)n.push("El c\xF3digo construye algunas llamadas al CRM en tiempo de ejecuci\xF3n: no se puede comprobar que solo use lo que pide.");else{for(let[s,c]of Object.entries(e.permisos.modulos))for(let d of c)d==="ver"&&c.some(u=>r.has(`${s}:${u}`))||r.has(`${s}:${d}`)||n.push(`Pide ${Fg[d]} ${Wg(s)} y el c\xF3digo no parece usarlo: pide solo lo que usa.`);e.permisos.almacen&&!r.has("almacen:almacen")&&n.push("Pide guardar datos (\xABalmacen\xBB) y el c\xF3digo no parece usarlo.")}return We("permisos","Permisos coherentes con lo que el c\xF3digo usa",t,n,"Usa solo lo que pide.")}function s_(e,o){let t=[],n=[],r=e.permisos.red_hacia,a=new Map(e.funciones.map(c=>[c.entrada,c])),s=r.length>0;for(let[c,d]of o){for(let u of d.matchAll(/(?:\b(?:https?|wss?):)?\/\/([a-z0-9](?:[a-z0-9-]{0,62}\.)+[a-z]{2,63})(?=[:/"'`)\s?#]|$)/gi)){let p=u[1].toLowerCase();if(i_.has(p))continue;let m=u[0].includes(":"),h=d.slice(Math.max(0,u.index-40),u.index),b=n_.test(h);if(!(!m&&!/(?:src|href)\s*=\s*["']?$/i.test(h)))if(b){s=!0;let y=a.get(c);Wc(r,p)?y&&!Wc(y.red,p)&&t.push(`La funci\xF3n \xAB${y.nombre}\xBB llama a ${p} y no lo tiene en su \xABred\xBB.`):t.push(`${c} llama a ${p} y no est\xE1 en \xABpermisos.red_hacia\xBB.`)}else!Wc(r,p)&&!a_.test(c)&&n.push(`${c} nombra ${p} (no se ve que llame): si la app se conecta ah\xED, decl\xE1ralo.`)}/\b(?:fetch|new\s+WebSocket|new\s+EventSource|sendBeacon)\s*\(\s*(?:[A-Za-z_$]|["'][^"'\n]*["']\s*\+|`[^`]*\$\{)/.test(d)&&(s=!0,n.push(`${c} se conecta a una direcci\xF3n que construye en tiempo de ejecuci\xF3n: solo podr\xE1 ir a lo declarado en \xABpermisos.red_hacia\xBB.`))}return{red:We("red","Red declarada",t,n,r.length?`Solo se conecta a lo declarado (${r.join(", ")}).`:"No se conecta fuera del CRM."),usaRed:s}}function ln(e){let o=e.trim().toLowerCase(),t=/^#([0-9a-f]{3,8})$/.exec(o);if(t){let r=t[1];return r.length===3||r.length===4?[0,1,2].map(a=>parseInt(r[a]+r[a],16)):r.length===6||r.length===8?[0,2,4].map(a=>parseInt(r.slice(a,a+2),16)):null}let n=/^rgba?\(\s*(\d{1,3})[\s,]+(\d{1,3})[\s,]+(\d{1,3})/.exec(o);return n?[Number(n[1]),Number(n[2]),Number(n[3])]:Object.hasOwn(Bg,o)?Bg[o]:null}function u_(e){let o=e.replace(/!important/i,"").trim();if(c_.test(o))return{tema:!1,color:null,neutro:!0};let t=/^var\(\s*--[\w-]+\s*(?:,\s*(.+))?\)$/i.exec(o);if(t)return{tema:!0,color:t[1]?ln(t[1]):null,neutro:!1};let n=o.split(/\s+/).find(r=>ln(r)!==null);return{tema:/var\(--/.test(o),color:ln(n||o),neutro:!n&&!ln(o)&&!/var\(--/.test(o)}}function d_(e){let o="";for(let t=0;;){let n=e.indexOf("/*",t);if(n<0)return o+e.slice(t);o+=e.slice(t,n);let r=e.indexOf("*/",n+2);if(r<0)return o;t=r+2}}function p_(e){let o=[],t=0,n=-1,r=0;for(let a=0;a<e.length;a++){let s=e.charCodeAt(a);s===123?(n=a,r=t,t=a+1):s===125&&(n>=0&&n>r&&o.push([e.slice(r,n),e.slice(n+1,a)]),n=-1,t=a+1)}return o}function m_(e){let o=[],t=/<style/gi,n=/<\/style>/gi;for(;;){let r=t.exec(e);if(!r)return o;let a=e.indexOf(">",r.index+6);if(a<0)return o;n.lastIndex=a+1;let s=n.exec(e);if(!s)return o;o.push(e.slice(a+1,s.index)),t.lastIndex=s.index+s[0].length}}function f_(e,o){let t=[],n=[],r=[],a=!1,s=!1;for(let[d,u]of o){if(!/\.(css|html?)$/i.test(d)){let m=[...u.matchAll(/\b(?:color|background(?:Color)?)\s*:\s*["'](#[0-9a-f]{3,8}|rgba?\([^)]{0,80}\))["']/gi)].length;m&&n.push(`${d} pone ${m} color(es) fijos en estilos del c\xF3digo: con el tema oscuro pueden no verse.`),/var\(--[\w-]+/.test(u)&&(a=!0);continue}let p=/\.css$/i.test(d)?u:m_(u).join(`
|
|
41
|
+
`)+[...u.matchAll(/\sstyle\s*=\s*"([^"]*)"/gi)].map(m=>`x{${m[1]}}`).join(`
|
|
42
|
+
`);if(p.trim()){s=!0;for(let[m,h]of p_(d_(p))){let b=m.trim().replace(/\s+/g," "),y=null,v=null;for(let w of h.matchAll(/(?:^|;)\s*(color|background-color|background)\s*:\s*([^;]+)/gi)){let N=u_(w[2]);N.tema&&(a=!0),w[1].toLowerCase()==="color"?y=N:v=N,!N.tema&&!N.neutro&&N.color&&(/(^|,)\s*(html|body|:root)\s*(,|$)/i.test(b)?t.push(`${d}: \xAB${b}\xBB fija ${w[1]} (${w[2].trim()}): la p\xE1gina no seguir\xE1 el tema claro y oscuro del CRM. Usa var(--background) y var(--foreground).`):n.push(`${d}: \xAB${b}\xBB usa un color fijo en ${w[1]} (${w[2].trim()}).`))}if(y?.color&&v?.color){let w=l_(y.color,v.color);w<4.5&&r.push(`${d}: \xAB${b}\xBB tiene un contraste de ${w.toFixed(2)}:1 entre el texto y el fondo (hace falta 4,5:1).`)}}}}let c=e.montajes.length>0;return c&&s&&!a&&t.push("La interfaz no usa ninguna variable del tema (var(--background), var(--foreground), var(--primary)\u2026): no parecer\xE1 del CRM ni seguir\xE1 el modo oscuro."),[We("forja","Forja: colores del tema",t,n,c?"Toma los colores del tema del CRM.":"No trae interfaz."),We("contraste","Contraste del texto (\u2265 4,5:1)",r,[],"Los colores fijos que se pueden medir tienen contraste suficiente.")]}function so(e,o){for(let t=0;t<3;t++)if((e[t]??0)!==o[t])return(e[t]??0)<o[t];return!1}function b_(e,o,t){let n=[],r=new Set,a=(c,d,u)=>{let p=c.toLowerCase().replace(/\.js$/,"");r.add(`${p} ${d}`);let m=d.split(".").map(Number);for(let h of h_)h.nombre.test(p)&&h.malas(m)&&n.push(`${u} trae ${h.etiqueta} ${d}, con un fallo de seguridad conocido: usa la ${h.arreglo} o posterior.`)};for(let c of o){let d=/(?:^|\/)([a-z][a-z.]*?)[-.@]v?(\d{1,3}\.\d{1,3}\.\d{1,3})(?:\.min)?\.m?js$/i.exec(c);d&&a(d[1],d[2],c)}for(let[c,d]of t)for(let u of d.matchAll(/\/\*[!*][\s\S]{0,600}?\*\//g))for(let p of u[0].matchAll(g_))a(p[1],p[2],c);let s=e.depende_de.map(c=>`Necesita la app \xAB${c.id}\xBB${c.version?` (${c.version})`:""} instalada antes.`);return We("dependencias","Dependencias sin fallos conocidos",n,s,r.size?`Librer\xEDas vistas: ${[...r].join(", ")}.`:"No se ven librer\xEDas de terceros con versi\xF3n.")}function w_(e){let o=[];for(let[t,n]of e)/\.(m?js|cjs|jsx|html?)$/i.test(t)&&(/\beval\s*\(|\bnew\s+Function\s*\(/.test(n)&&o.push(`${t} ejecuta c\xF3digo construido en tiempo de ejecuci\xF3n (eval o new Function).`),/\b(?:window\.)?(?:top|parent)\.location\b|\bdocument\.cookie\b/.test(n)&&o.push(`${t} toca la ventana de arriba o las cookies (el CRM lo impide; se mira en la revisi\xF3n).`));return We("codigo","C\xF3digo para la revisi\xF3n humana",[],o,"Nada que marcar.")}function Bc(e){let o=[...e.recursos.keys()].sort(),t=o.filter(p=>Zy.test(p)).map(p=>[p,e.recursos.get(p).toString("utf8")]),{red:n,usaRed:r}=s_(e.ext,t),a=r||!!e.ext.conexiones?.length||e.ext.servidor!==null,s=w_(t),c=e.sinRed?[...a||e.ext.funciones.some(p=>p.red.length)?["La app no puede usar red ni conexiones externas."]:[],...t.flatMap(([p,m])=>/\b(?:fetch|XMLHttpRequest|WebSocket|EventSource|sendBeacon|importScripts)\b|\bimport\s*\(/.test(m)?[`${p} intenta usar una conexi\xF3n fuera del puente del CRM.`]:[]),...n.estado==="aviso"?n.detalles:[]]:[],d=[We("esquema","Manifiesto y soluci\xF3n v\xE1lidos",[],[],"El manifiesto y su soluci\xF3n pasan el validador del CRM."),e.dePix?We("firma","Montada por el CRM",[],[],"La ha montado el CRM en este espacio: no viaja a otros ni a la tienda."):We("firma","Firmada por su desarrollador",e.firmada?[]:["El paquete no va firmado: `forgenex empaquetar` con tu clave registrada."],[],e.enLocal?"Se firma al empaquetar con tu clave (la tienda exige firma).":"Firma v\xE1lida de una clave registrada."),We("tamano","Tama\xF1o",e.bytes>ea?["El paquete pasa de 5 MB."]:[],[],`${(e.bytes/1024).toFixed(0)} KB de 5 MB.`),r_(e.ext,t),...f_(e.ext,t),c.length?We("red",n.titulo,c):n,We("politica","Pol\xEDtica de datos",a&&!e.ext.politica_datos?["La app se conecta fuera del CRM: a\xF1ade \xABpolitica_datos\xBB (una direcci\xF3n https con tu pol\xEDtica de datos) al manifiesto."]:[],[],e.ext.politica_datos?`Pol\xEDtica de datos: ${e.ext.politica_datos}`:"No hace falta: no se conecta fuera."),b_(e.ext,o,t),e.sinRed&&s.estado==="aviso"?We("codigo",s.titulo,s.detalles):s],u=d.filter(p=>p.estado==="falla").length;return{ok:u===0,version:1,puntos:d,fallas:u,avisos:d.filter(p=>p.estado==="aviso").length}}var Zy,zc,zg,We,Fc,e_,o_,Fg,Wg,n_,i_,a_,Wc,Bg,c_,Vg,l_,h_,g_,Ug=f(()=>{Tt();vr();Zy=/\.(m?js|cjs|jsx|html?|css|svg)$/i,zc=12,zg=e=>{let o=[...new Set(e)];return o.length>zc?[...o.slice(0,zc),`\u2026 y ${o.length-zc} m\xE1s`]:o},We=(e,o,t,n=[],r="")=>({clave:e,titulo:o,estado:t.length?"falla":n.length?"aviso":"ok",detalles:t.length?zg(t):n.length?zg(n):r?[r]:[]}),Fc={buscar:"ver",ver:"ver",listar:"ver",obtener:"ver",pdf:"ver",crear:"crear",actualizar:"editar",mover:"editar",completar:"editar",borrar:"borrar"},e_=new Set(["contexto.actual","publica.llamar","app.ajustes","extensiones.calcular"]),o_=new Set(["registros.relacionadas","registros.historial","registros.opciones","registros.adjuntar","mensajes.proponer","metricas.calcular"]);Fg={ver:"ver",crear:"crear",editar:"cambiar",borrar:"borrar",almacen:"guardar datos",leer:"leer",escribir:"vincular"},Wg=e=>Object.hasOwn(Bo,e)?Bo[e].nombre:`\xAB${e.replace(/^mod_/,"")}\xBB`;n_=/(fetch|WebSocket|EventSource|sendBeacon|\.open|import|axios(?:\.[a-z]+)?|\$\.(?:get|post|ajax|getJSON))\s*\(\s*["'`]?$|(?:src|href|action|srcset|poster|data)\s*=\s*["']?$|url\(\s*["']?$|@import\s+(?:url\()?["']?$/i,i_=new Set(["www.w3.org","w3.org"]),a_=/(?:\.min\.(?:m?js|css)$)|(?:^|\/)(?:jquery|lodash|alpine|react|vue|preact|chart|d3|moment|axios|dompurify|underscore|bootstrap|handlebars)[^/]*\.m?js$/i,Wc=(e,o)=>e.some(t=>t===o||t.startsWith("*.")&&o.endsWith(t.slice(1)));Bg={white:[255,255,255],black:[0,0,0],red:[255,0,0],green:[0,128,0],blue:[0,0,255],gray:[128,128,128],grey:[128,128,128],silver:[192,192,192],yellow:[255,255,0],orange:[255,165,0],navy:[0,0,128],purple:[128,0,128],lightgray:[211,211,211],lightgrey:[211,211,211],darkgray:[169,169,169],darkgrey:[169,169,169],whitesmoke:[245,245,245],gainsboro:[220,220,220]},c_=/^(transparent|inherit|initial|unset|revert|currentcolor|none)$/i;Vg=([e,o,t])=>{let n=r=>{let a=r/255;return a<=.03928?a/12.92:((a+.055)/1.055)**2.4};return .2126*n(e)+.7152*n(o)+.0722*n(t)},l_=(e,o)=>{let[t,n]=[Vg(e),Vg(o)].sort((r,a)=>a-r);return(t+.05)/(n+.05)};h_=[{nombre:/^jquery$/i,etiqueta:"jQuery",malas:e=>so(e,[3,5,0]),arreglo:"3.5.0 (CVE-2020-11022)"},{nombre:/^lodash$/i,etiqueta:"Lodash",malas:e=>so(e,[4,17,21]),arreglo:"4.17.21 (CVE-2021-23337)"},{nombre:/^moment$/i,etiqueta:"Moment.js",malas:e=>so(e,[2,29,4]),arreglo:"2.29.4 (CVE-2022-31129)"},{nombre:/^handlebars$/i,etiqueta:"Handlebars",malas:e=>so(e,[4,7,7]),arreglo:"4.7.7 (CVE-2021-23369)"},{nombre:/^bootstrap$/i,etiqueta:"Bootstrap",malas:e=>so(e,[3,4,1])||e[0]===4&&so(e,[4,3,1]),arreglo:"3.4.1 o 4.3.1 (CVE-2019-8331)"},{nombre:/^angular(js)?$/i,etiqueta:"AngularJS",malas:e=>e[0]===1,arreglo:"ninguna: AngularJS 1.x ya no recibe arreglos"},{nombre:/^dompurify$/i,etiqueta:"DOMPurify",malas:e=>e[0]===2?so(e,[2,5,4]):so(e,[3,1,3]),arreglo:"2.5.4 o 3.1.3 (CVE-2024-45801)"},{nombre:/^axios$/i,etiqueta:"Axios",malas:e=>e[0]===0?so(e,[0,28,0]):so(e,[1,6,0]),arreglo:"0.28.0 o 1.6.0 (CVE-2023-45857)"},{nombre:/^underscore$/i,etiqueta:"Underscore",malas:e=>so(e,[1,12,1]),arreglo:"1.12.1 (CVE-2021-23358)"}];g_=/\b(jquery|lodash|moment|handlebars|bootstrap|angularjs|angular|dompurify|axios|underscore|alpine(?:js)?|react|vue|preact|chart\.js|d3)(?:\.js)?(?:\s+javascript\s+library)?[\s@:,-]*v?(\d{1,3}\.\d{1,3}\.\d{1,3})\b/gi});import{Worker as v_}from"node:worker_threads";var y_,Vc,Ui,Jg=f(()=>{yr();y_=new URL(import.meta.url.endsWith(".ts")?"./caja.ts":"./caja.js",import.meta.url),Vc=class{w=null;ocupada=!1;worker(){return this.w?this.w:(this.w=new v_(y_,{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,c=(b,y)=>{a||(a=!0,clearTimeout(m),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>W.llamadaCaracteres||s>=W.llamadasEnVuelo){n.postMessage({tipo:"respuesta",n:b.n,ok:!1,valor:typeof b.datos=="string"&&b.datos.length<=W.llamadaCaracteres?"demasiadas llamadas a la vez":"lo que se manda al CRM es demasiado grande"});return}let v=null;try{v=JSON.parse(b.datos)}catch{}s++,o.manejar(b.que,v).finally(()=>{s--}).then(w=>!a&&n.postMessage({tipo:"respuesta",n:b.n,ok:!0,valor:JSON.stringify(w??null)}),w=>!a&&n.postMessage({tipo:"respuesta",n:b.n,ok:!1,valor:w instanceof Error?w.message:String(w)}));return}let y=Date.now()-t;b.ok?c({ok:!0,salida:b.salida,ms:y},!1):c({ok:!1,corte:b.corte,clase:b.clase,mensaje:b.mensaje,ms:y},b.corte!==null)},u=b=>c({ok:!1,corte:/memory|heap/i.test(b.message)?"memoria":null,clase:"Error",mensaje:"la caja se ha cerrado",ms:Date.now()-t},!0),p=()=>c({ok:!1,corte:null,clase:"Error",mensaje:"la caja se ha cerrado",ms:Date.now()-t},!0),m=setTimeout(()=>c({ok:!1,corte:"tiempo",clase:"InternalError",mensaje:"interrupted",ms:Date.now()-t},!0),o.ms+W.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:W.pilaBytes,salidaBytes:W.salidaBytes,llamadaCaracteres:W.llamadaCaracteres,enVuelo:W.llamadasEnVuelo};n.postMessage(h)})}cerrar(){this.matar()}},Ui=class{ranuras;cola=[];constructor(o=W.simultaneas){this.ranuras=Array.from({length:Math.max(1,o)},()=>new Vc)}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 __}from"node:dns/promises";import{request as N_}from"node:https";import{isIP as $_}from"node:net";async function Jc(e,o,t={}){let n;try{n=new URL(e.url)}catch{throw new ge("direcci\xF3n no v\xE1lida")}if(n.protocol!=="https:")throw new ge("solo https");if(n.username||n.password)throw new ge("sin usuario ni clave en la direcci\xF3n");if(n.port&&n.port!=="443")throw new ge("solo al puerto 443");let r=n.hostname.toLowerCase().replace(/\.$/,"");if($_(r.replace(/^\[|\]$/g,""))||!Uc(o,r))throw new ge("el dominio no est\xE1 entre los dominios aceptados");let a=String(e.metodo||"GET").toUpperCase();if(!Qg.has(a))throw new ge("m\xE9todo no admitido");let s={};if(e.cabeceras&&typeof e.cabeceras=="object")for(let[m,h]of Object.entries(e.cabeceras).slice(0,30)){let b=m.toLowerCase();if(!C_.test(m)||x_.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 c=e.cuerpo===null||e.cuerpo===void 0?null:String(e.cuerpo);if(c!==null&&Buffer.byteLength(c)>W.red.cuerpoBytes)throw new ge(`el cuerpo pasa de ${W.red.cuerpoBytes/1024} KB`);if(c!==null&&(a==="GET"||a==="HEAD"))throw new ge("GET y HEAD no llevan cuerpo");let d=await(t.resolver??(m=>__(m,{all:!0,verbatim:!0})))(r).catch(()=>[]);if(!d.length)throw new ge(`${r.slice(0,80)} no resuelve`);if(d.some(m=>im(m.address)))throw new ge(`${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??S_)(u,{metodo:a,cabeceras:s,cuerpo:c});return{host:r,respuesta:p}}function S_(e,o){return new Promise((t,n)=>{let r={...o.cabeceras,...o.cuerpo!==null?{"content-length":String(Buffer.byteLength(o.cuerpo))}:{}},a=N_({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:((c,d,u)=>d?.all?u(null,[{address:e.ip,family:e.familia}]):u(null,e.ip,e.familia)),timeout:W.red.plazoMs,agent:!1},c=>{let d=[],u=0;c.on("data",p=>{if(u+=p.length,u>W.red.respuestaBytes){c.destroy(),n(new ge(`la respuesta pasa de ${W.red.respuestaBytes/1024/1024} MB`));return}d.push(p)}),c.on("end",()=>{clearTimeout(s);let p={};for(let m of j_){let h=c.headers[m];typeof h=="string"&&(p[m]=h.slice(0,2e3))}t({status:c.statusCode??0,headers:p,cuerpo:Buffer.concat(d).toString("utf8")})}),c.on("error",()=>n(new ge("la respuesta se cort\xF3")))}),s=setTimeout(()=>a.destroy(new ge("sin respuesta a tiempo")),W.red.plazoMs);a.on("timeout",()=>a.destroy(new ge("sin respuesta a tiempo"))),a.on("error",c=>{clearTimeout(s),n(c instanceof ge?c:new ge("no se ha podido conectar"))}),a.end(o.cuerpo??void 0)})}var ge,Qg,x_,C_,j_,Uc,Qc=f(()=>{am();yr();ge=class extends Error{constructor(t){super(`fetch: ${t}`);this.motivo=t}motivo},Qg=new Set(["GET","POST","PUT","PATCH","DELETE","HEAD"]),x_=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"]),C_=/^[A-Za-z0-9!#$%&'*+.^_`|~-]{1,64}$/,j_=["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 Hg(e,o){if(typeof o!="string"||typeof e!="string")return null;let n=(Object.hasOwn(Gg,o)?Gg[o]:null)??lo(o);if(!n)return null;let r=n.startsWith("mod_");switch(e){case"ver":return r?`${n}.ver`:O_[n]??`${n}.ver`;case"buscar":return r?`${n}.listar`:A_[n]??`${n}.buscar`;case"crear":return`${n}.crear`;case"actualizar":return`${n}.actualizar`;default:return null}}function Xg(e,o){return e.filter(t=>Uc(o,t.startsWith("*.")?`x${t.slice(1)}`:t)&&(!t.startsWith("*.")||o.includes(t)))}var Gg,O_,A_,Yg=f(()=>{Tt();Qc();Gg={contactos:"contactos",contacts:"contactos",empresas:"empresas",companies:"empresas",oportunidades:"oportunidades",deals:"oportunidades",tareas:"tareas",tasks:"tareas",notas:"notas"},O_={tareas:"tareas.obtener"},A_={tareas:"tareas.listar",notas:"notas.listar"}});var eb={};ll(eb,{iniciarDev:()=>Gc});import{createServer as E_}from"node:http";import{randomBytes as Kg}from"node:crypto";import{readFileSync as q_,realpathSync as Zg,watch as R_}from"node:fs";import{join as k_,sep as P_}from"node:path";async function Gc(e,o){let t=o?.conexion??gr(e),n=Number(Re(e,"puerto")??5173),r=Zg(process.cwd());if(!Number.isInteger(n)||n<1||n>65535)throw new Error("Puerto no v\xE1lido.");let a=Fe(r),s=(I,_)=>hr(t.api,t.clave,"/api/desarrollador/desarrollo",{espacio:t.espacio,ext_id:a.id,pase:I,funcion:_}),c=await s();await fr(r);let d=new Ui(1),u=Kg(24).toString("hex"),p=o?.cookie,m=1,h=null,b,y=R_(r,{recursive:!0},(I,_)=>{let E=String(_??"");/node_modules|\.fgx$|\.pem|^\.git[\/\\]/.test(E)||E==="interfaz/app.js"||(clearTimeout(b),b=setTimeout(()=>{h=fr(r).then(()=>{Fe(r),m++,console.log("App actualizada.")}).catch(g=>console.error("Error de desarrollo:",g.message)).finally(()=>{h=null})},100))}),v=E_(async(I,_)=>{let E=(g,x)=>{_.writeHead(g,{"content-type":"application/json","cache-control":"no-store"}),_.end(JSON.stringify(x))};try{if(![`127.0.0.1:${n}`,`localhost:${n}`].includes(I.headers.host??""))return E(403,{error:"host_no_permitido"});let g=I.headers.origin;if(g&&g!==t.api)return E(403,{error:"origen_no_permitido"});if(g===t.api&&(_.setHeader("access-control-allow-origin",t.api),_.setHeader("vary","origin")),_.setHeader("access-control-allow-methods","GET, POST, OPTIONS"),_.setHeader("access-control-allow-headers","content-type, authorization"),I.method==="OPTIONS"){_.writeHead(204),_.end();return}let x=new URL(I.url??"/",`http://127.0.0.1:${n}`),O=decodeURIComponent(x.pathname);if(!O.startsWith(`/${u}/`))return E(404,{error:"no_encontrado"});let k=O.slice(u.length+2);if(k==="__sandbox/entrar"&&I.method==="GET"&&p){_.writeHead(303,{"set-cookie":p,location:F,"cache-control":"no-store","referrer-policy":"no-referrer"}),p=void 0,_.end();return}if(k==="__forgenex/version"&&I.method==="GET")return E(200,{version:m});if(k.startsWith("__forgenex/funcion/")&&I.method==="POST"){if(g!==t.api)return E(403,{error:"origen_no_permitido"});let U=(I.headers.authorization??"").replace(/^Bearer /,"");if(!U.startsWith("crmui_"))return E(401,{error:"falta_pase"});if(!d.libres)return E(429,{error:"funcion_ocupada"});let be=k.slice(19),Be=await s(U,be),X=Fe(r).funciones.find(wr=>wr.nombre===be),Ve=Be.manifiesto.funciones.find(wr=>wr.nombre===be);if(!X||!Ve)return E(403,{error:"funcion_no_instalada"});let Ue=await fetch(`${t.api}/api/v1/capabilities`,{redirect:"error",headers:{authorization:`Bearer ${U}`,"x-espacio":String(t.espacio)}});if(!Ue.ok)return E(Ue.status,{error:"pase_revocado"});let Do=await T_(I),T=Kg(12).toString("hex"),J=0,le=0,No=await d.correr({codigo:w(X.entrada).toString("utf8"),fichero:X.entrada,entrada:Do,contexto:{extension:a.id,version:a.version,funcion:be,disparo:"desarrollo",ejecucion:T},..._l(X),manejar:async(wr,tl)=>{if(wr==="red"){if(++le>W.llamadasRed)throw new Error("Demasiadas peticiones de red.");return(await Jc(tl,Xg(Ve.red,Be.aceptados.red_hacia))).respuesta}if(++J>W.llamadasApi)throw new Error("Demasiadas llamadas al CRM.");let dn=tl,pn=dn.op??Hg(dn.accion,dn.modulo);if(!pn||!/^[a-z][a-z0-9_]*\.[a-z][a-z0-9_]*$/.test(pn))throw new Error("Operaci\xF3n no v\xE1lida.");let rl=await fetch(`${t.api}/api/v1/capabilities`,{redirect:"error",headers:{authorization:`Bearer ${U}`,"x-espacio":String(t.espacio)}});if(!rl.ok)throw new Error("Pase caducado o revocado.");let nl=await rl.json(),il=(nl.data?.operaciones??nl.operaciones??[]).find(Ki=>Ki.id===pn);if(!il)throw new Error("Operaci\xF3n no aceptada por el administrador.");let Yi=il.metodo,al=dn.args??{},hb=Yi==="GET"?`?${new URLSearchParams(Object.entries(al).map(([Ki,gb])=>[Ki,String(gb)]))}`:"",sl=await fetch(`${t.api}/api/v1/op/${pn}${hb}`,{method:Yi,redirect:"error",headers:{authorization:`Bearer ${U}`,"x-espacio":String(t.espacio),"content-type":"application/json","idempotency-key":`dev-${T}-${J}`},...Yi==="POST"?{body:JSON.stringify(al)}:{}}),cl=await sl.json();if(!sl.ok)throw new Error(cl.error?.mensaje??"El CRM rechaz\xF3 la operaci\xF3n.");return cl.data}});return No.ok||console.error(`Funci\xF3n ${be}: ${No.clase}: ${No.mensaje}`),E(No.ok?200:422,No)}if(I.method!=="GET")return E(405,{error:"metodo_no_permitido"});if(await h,!k.startsWith("interfaz/"))return E(404,{error:"no_encontrado"});let L=w(k),V=k.endsWith(".html")?"text/html":k.endsWith(".js")?"text/javascript":k.endsWith(".css")?"text/css":"application/octet-stream";_.writeHead(200,{"content-type":V,"cache-control":"no-store"}),_.end(L)}catch(g){console.error("Error de desarrollo:",g.message),E(400,{error:"desarrollo_error",mensaje:g.message})}});function w(I){if(I.includes("\\")||I.split("/").some(g=>g===".."||g==="."||!g))throw new Error("Ruta no admitida.");let _=Zg(k_(r,I));if(!_.startsWith(r+P_))throw new Error("Ruta fuera del proyecto.");let E=q_(_);if(E.length>2*1024*1024)throw new Error("Recurso demasiado grande.");return E}let N,j=new Promise(I=>{N=I}),S=()=>{clearTimeout(b),y.close(),d.cerrar(),v.closeAllConnections(),v.close(N)},R=`http://127.0.0.1:${n}/${u}`,F=`${t.api}/#/ajustes/extensiones?desarrollo=${c.id}&local=${encodeURIComponent(R)}`;v.on("error",I=>{console.error(I.message),S(),process.exitCode=1}),process.once("SIGINT",S),process.once("SIGTERM",S),await new Promise((I,_)=>{v.once("error",_),v.listen(n,"127.0.0.1",I)}),console.log(`Desarrollo: ${R}
|
|
43
|
+
Abrir CRM: ${t.api}/#/ajustes/extensiones?desarrollo=${c.id}&local=${encodeURIComponent(R)}
|
|
44
|
+
Recarga al guardar. Funciones: crm.pedir("desarrollo.funcion", { nombre, entrada }, { metodo: "POST", idempotencia: crypto.randomUUID() }).`),o&&(console.log(`Entrar como titular de prueba: ${R}/__sandbox/entrar`),o.signal.aborted?S():o.signal.addEventListener("abort",S,{once:!0}),await j)}async function T_(e){let o=[],t=0;for await(let n of e){if(t+=n.length,t>W.webhookBytes)throw new Error("Entrada demasiado grande.");o.push(n)}return JSON.parse(Buffer.concat(o).toString("utf8")||"null")}var Hc=f(()=>{Jg();yr();Yg();Qc();Ji();cn()});var ab={};ll(ab,{sandbox:()=>B_});import{execFileSync as M_}from"node:child_process";import{randomBytes as ib}from"node:crypto";import{existsSync as ob,readFileSync as I_,readdirSync as D_}from"node:fs";import{createServer as L_}from"node:net";import{fileURLToPath as z_}from"node:url";import{setTimeout as F_}from"node:timers/promises";function Me(e,o=30){try{return M_("docker",e,{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:o*1e3}).trim()}catch(t){let n=t,r=(n.stderr||n.stdout||"").trim().split(`
|
|
45
|
+
`).at(-1);throw new Error(`Docker ${e[0]} fall\xF3${r?`: ${r}`:"."}`)}}function W_(){try{let o=(process.env.DOCKER_CONTEXT?void 0:process.env.DOCKER_HOST)||Me(["context","inspect","--format","{{.Endpoints.docker.Host}}"]);if(!/^(unix|npipe):\/\//.test(o))throw new Error("contexto remoto");Me(["info","--format","{{.ServerVersion}}"])}catch{throw new Error("Hace falta Docker en marcha con un contexto local. Inicia Docker y selecciona su contexto local.")}}function tb(e){let o=Number(e);if(!Number.isInteger(o)||o<1024||o>65535)throw new Error("Usa un puerto entre 1024 y 65535.");return o}async function rb(e){let o=L_();await new Promise((t,n)=>{o.once("error",()=>n(new Error(`El puerto ${e} est\xE1 ocupado. Cierra el proceso que lo usa o elige otro con --puerto y --puerto-dev.`))),o.listen(e,Hi,()=>o.close(()=>t()))})}async function nb(e,o){for(let t of["container","network"]){let n=["--filter",`label=${Xi}=${e}`];o&&n.push("--filter",`label=${Xi}.instancia=${o}`);let r=t==="container",a=Me([t,"ls","-q",...r?["-a"]:[],...n]);for(let s of a.split(`
|
|
46
|
+
`).filter(Boolean))try{Me([t,"rm",...r?["-f","-v"]:[],s])}catch(c){let d=c.message;if(r&&/removal .* already in progress/i.test(d))await Xc(()=>!Me(["container","ls","-aq","--filter",`id=${s}`]),`Docker sigue retirando el contenedor ${s}.`);else if(!/No such (container|network)|network .* not found/i.test(d))throw c}}}async function Xc(e,o){for(let t=0;t<90;t++){try{if(await e())return}catch{}await F_(500)}throw new Error(o)}async function B_(e){let[o=0,t=0]=process.versions.node.split(".").map(Number);if(o<20||o===20&&t<19||o===21||o===22&&t<12)throw new Error("Instala Node 22 LTS (22.12 o superior).");W_();let n=tb(Re(e,"puerto")??process.env.CRM_PUERTO??15504),r=`forgenex-sandbox-${n}`;if(e[0]==="parar"){await nb(r),console.log(`Sandbox ${n} parado.`);return}let a=tb(Re(e,"puerto-dev")??n+1);if(n===a)throw new Error("El CRM y la recarga necesitan puertos distintos.");await Promise.all([rb(n),rb(a)]);try{Me(["image","inspect",Qi])}catch{let F=z_(new URL("../sandbox-local.tar.gz",import.meta.url));if(!ob(F))throw new Error(`Falta la imagen local ${Qi}. Todav\xEDa no es p\xFAblica (ver \xABSandbox\xBB en el README del paquete).`);console.log("Importando las im\xE1genes incluidas en el paquete privado\u2026"),Me(["image","load","--input",F],240)}if(!ob("extension.json")){if(D_(".").length)throw new Error("Ejecuta sandbox en la carpeta de una app o en una carpeta vac\xEDa.");process.chdir(Vi("escuela-natacion","natacion")),console.log("Proyecto creado en escuela-natacion/.")}let s=Fe(process.cwd()),c=I_(await sn(process.cwd())).toString("base64"),d=ib(8).toString("hex"),u=["--label",`${Xi}=${r}`,"--label",`${Xi}.instancia=${d}`],p=`${r}-red`,m=`${r}-pg`,h=`${r}-crm`,b=Gi(),y=Gi(),v=Gi(),w=`http://${Hi}:${n}`,N=(F,I)=>`postgres://${F}:${I}@${m}:5432/postgres`,j=new AbortController,S=()=>j.abort(),R;Me(["network","create",...u,p]),process.once("SIGINT",S),process.once("SIGTERM",S);try{console.log("Preparando Postgres desechable\u2026"),Me(["run","-d","--name",m,"--network",p,...u,"-e",`POSTGRES_PASSWORD=${b}`,"postgres:17"],180),await Xc(()=>Me(["exec",m,"pg_isready","-h",Hi,"-U","postgres"]),"Postgres no est\xE1 listo."),Me(["exec",m,"psql","-U","postgres","-v","ON_ERROR_STOP=1","-c",`create role crm_app login password '${y}'; create role crm_portal nologin noinherit; grant crm_portal to crm_app; create role crm_trabajador nologin;`]),console.log("Aplicando el esquema del CRM\u2026"),Me(["run","--rm","--name",`${r}-migrar`,"--network",p,...u,"-e",`CRM_DB_DUENO_URL=${N("postgres",b)}`,Qi,"node","dist/migrar.js"],180),Me(["run","-d","--name",h,"--network",p,...u,"-p",`${Hi}:${n}:3000`,"-e","NODE_ENV=development","-e","CRM_MODO_PRUEBAS=1","-e","CRM_WEBHOOKS=0","-e",`CRM_ENTRADA_SANDBOX=${v}`,"-e",`CRM_SECRETO=${Gi()}`,"-e",`CRM_URL=${w}`,"-e",`CRM_DB_URL=${N("crm_app",y)}`,Qi]),await Xc(async()=>(await fetch(`${w}/api/salud`,{signal:AbortSignal.timeout(2e3)})).ok,`El CRM no est\xE1 listo. Revisa docker logs ${h} mientras arranca.`);let F={sub:"sandbox-titular",email:"titular@demo.invalid",nombre:"Titular de prueba",apellidos:""},I=await fetch(`${w}/api/pruebas/entrar`,{method:"POST",redirect:"error",headers:{"content-type":"application/json","x-crm-pruebas":v},body:JSON.stringify(F)}),_=I.headers.getSetCookie()[0];if(!I.ok||!_)throw new Error(`El CRM rechaz\xF3 la sesi\xF3n de prueba (${I.status}).`);async function E(L,V,U="POST"){let be=await fetch(w+L,{redirect:"error",headers:{cookie:_.split(";",1)[0],"content-type":"application/json",origin:w},...V===void 0?{}:{method:U,body:JSON.stringify(V)}}),Be=await be.json();if(!be.ok)throw new Error(`${L} (${be.status}): ${Be.error?.mensaje??"CRM rechaz\xF3 la petici\xF3n"}`);return Be.data??Be}let g=await E("/api/yo");await E("/api/aceptaciones",{version:"extensiones-desarrollador-v1"}),await E("/api/preferencias/onboarding",{valor:{bienvenida:"saltada",recorrido:"saltado"}},"PUT"),await E("/api/preferencias/novedades",{valor:{visto:99999}},"PUT");let{clave:x}=await E("/api/extensiones/desarrollador/credencial",{}),O=Number(g.espacio.id);if(!Number.isSafeInteger(O)||O<1)throw new Error("El CRM no cre\xF3 el espacio de prueba.");Me(["exec",m,"psql","-U","postgres","-v","ON_ERROR_STOP=1","-c",`update espacios set tope_modulos = 30, metadatos = jsonb_set(metadatos, '{plan}', '{"estado":"cortesia"}') where id = ${O}`]);let{id:k}=await E("/api/extensiones/instalar",{paquete:c,aceptados:{...s.permisos,red_hacia:[]}});if(s.montajes.some(L=>L.punto==="publica")){let{direccion:L}=await E(`/api/extensiones/${k}/publica/crear`,{});console.log(`P\xE1gina p\xFAblica de prueba: ${L}`)}console.log(`Espacio de prueba: ${O}
|
|
47
|
+
Credencial de desarrollador local: ${x}`),R=setInterval(async()=>{try{await fetch(`${w}/api/salud`,{signal:AbortSignal.timeout(1500)})}catch{S()}},2e3),await Gc(["--puerto",String(a)],{conexion:{api:w,clave:x,espacio:O},cookie:_,signal:j.signal})}finally{clearInterval(R),process.removeListener("SIGINT",S),process.removeListener("SIGTERM",S),await nb(r,d)}}var Qi,Xi,Hi,Gi,sb=f(()=>{Ji();Hc();cn();Qi="forgenex-crm-sandbox:1.78.0",Xi="com.forgenex.cli.sandbox",Hi="127.0.0.1",Gi=()=>ib(32).toString("hex")});import{generateKeyPairSync as V_,createPublicKey as cb}from"node:crypto";import{mkdirSync as U_,readFileSync as un,writeFileSync as lb}from"node:fs";import{homedir as J_}from"node:os";import{join as Q_,resolve as ub}from"node:path";function Re(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 db(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 hr(e,o,t,n){let r=await fetch(`${db(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 a.error?.datos?.informe&&console.log(Kc(a.error.datos.informe)),new Error(`${r.status}: ${a.error?.mensaje??"El CRM rechaz\xF3 la petici\xF3n."}`);return a.data}function Kc(e){let o=[e.ok?`Revisi\xF3n autom\xE1tica: PASA (${e.avisos} aviso(s)).`:`Revisi\xF3n autom\xE1tica: NO PASA (${e.fallas} punto(s) que corregir).`];for(let t of e.puntos){o.push(`${G_[t.estado]} ${t.titulo}`);for(let n of t.detalles)o.push(` ${n}`)}return o.join(`
|
|
48
|
+
`)}function Yc(e){return ub(Re(e,"clave-firma")??process.env.FORGENEX_CLAVE_FIRMA??Q_(J_(),".forgenex/desarrollador.pem"))}function gr(e){let o=Re(e,"api")??process.env.FORGENEX_API,t=process.env.FORGENEX_CLAVE_DESARROLLADOR,n=Number(Re(e,"espacio"));if(!o||!t||!Number.isSafeInteger(n)||n<1)throw new Error("Configura FORGENEX_API, FORGENEX_CLAVE_DESARROLLADOR y --espacio <id>.");return{api:db(o),clave:t,espacio:n}}async function pb(e,o){if(e==="crear-app"||e==="crear-extension")return console.log(Vi(o[0]??"",Re(o,"plantilla"))),0;if(e==="claves"&&o[0]==="crear"){let t=Yc(o);U_(ub(t,".."),{recursive:!0,mode:448});let n=V_("ed25519");return lb(t,n.privateKey.export({type:"pkcs8",format:"pem"}),{flag:"wx",mode:384}),lb(`${t}.pub`,n.publicKey.export({type:"spki",format:"pem"}),{flag:"wx",mode:420}),console.log(`Clave privada: ${t}
|
|
49
|
+
P\xFAblica: ${t}.pub`),0}if(e==="registrar-clave"){let t=gr(o),n=un(Yc(o),"utf8");return console.log(JSON.stringify(await hr(t.api,t.clave,"/api/desarrollador/claves",{espacio:t.espacio,publica:cb(n).export({type:"spki",format:"pem"}).toString()}))),0}if(e==="revocar-clave"){let t=gr(o),n=Re(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 hr(t.api,t.clave,"/api/desarrollador/revocar-clave",{espacio:t.espacio,id:n}))),0}if(e==="empaquetar"){if(o.includes("--sin-firmar")){let n=await sn(process.cwd());return console.log(`${n} \xB7 Para \xABSubir paquete\xBB con el modo desarrollador encendido.`),0}let t=un(Yc(o),"utf8");return console.log(await sn(process.cwd(),t,cb(t).export({type:"spki",format:"pem"}).toString())),0}if(e==="instalar"){let t=gr(o),n=Re(o,"paquete"),r=Re(o,"app"),a=Re(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:un(n).toString("base64")},c=await hr(t.api,t.clave,"/api/desarrollador/instalar",s);return console.log(JSON.stringify(c)),c?.pendiente_permisos!==!1&&console.log("El administrador debe aceptar los permisos en Ajustes \u203A Apps."),0}if(e==="revisar"){let t=Re(o,"paquete"),n;if(t){let r=un(t),a=zo(r),s=a.get("extension.json");if(!s)throw new Error("Al paquete le falta \xABextension.json\xBB.");n=Bc({ext:Vo(s.toString("utf8")),recursos:a,firmada:a.has(rn),bytes:r.length,enLocal:!0})}else{let r=process.cwd();await fr(r);let a=Lc(r),s=Vo(a.get("extension.json").toString("utf8"));n=Bc({ext:s,recursos:a,firmada:!0,bytes:[...a.values()].reduce((c,d)=>c+d.length,0),enLocal:!0})}return console.log(o.includes("--json")?JSON.stringify(n,null,2):Kc(n)),n.ok?0:1}if(e==="publicar"){let t=gr(o),n=Re(o,"paquete"),r=o.includes("--tienda");if(!n)throw new Error("Falta --paquete <archivo.fgx> (lo hace `forgenex empaquetar`).");let a=await hr(t.api,t.clave,"/api/desarrollador/publicar",{espacio:t.espacio,paquete:un(n).toString("base64"),...r?{tienda:!0}:{}});console.log(JSON.stringify({...a,tienda:a.tienda?{estado:a.tienda.estado,humana:a.tienda.humana,porcentaje:a.tienda.porcentaje}:void 0}));let s=c=>a.espacios.filter(d=>d.resultado===c).length;return console.log(`Publicada ${a.ext_id} ${a.version} en tus apps.`),a.tienda&&(console.log(Kc(a.tienda.informe)),console.log(a.tienda.estado==="aprobada"?`\xB7 En la tienda: publicada sola (no pide m\xE1s que la versi\xF3n anterior), al ${a.tienda.porcentaje} % de los espacios; sube al 100 % en 24 h si no da errores.`:`\xB7 En la tienda: en revisi\xF3n (${a.tienda.humana.map(c=>({primera:"es la primera versi\xF3n",permisos:"pide permisos nuevos",red:"se conecta a un dominio nuevo",publica:"trae una p\xE1gina p\xFAblica nueva",todas:"por ahora se revisa cada versi\xF3n"})[c]??c).join(", ")}). Te avisamos al decidir; el estado sale en el panel, Perfil \u203A Desarrollador.`)),s("activa")&&console.log(`\xB7 Actualizada sola en ${s("activa")} espacio(s): no pide m\xE1s permisos.`),s("pendiente_permisos")&&console.log(`\xB7 En ${s("pendiente_permisos")} espacio(s) pide m\xE1s permisos: su administrador los acepta en Ajustes \u203A Apps.`),s("a_mano")&&console.log(`\xB7 En ${s("a_mano")} espacio(s) no se aplica sola (cambian sus m\xF3dulos, o lo instalado all\xED no sali\xF3 de \xABMis apps\xBB): actual\xEDzala con \`forgenex instalar --app ${a.ext_id} --espacio <id>\`.`),s("modo_desarrollador")&&console.log(`\xB7 En ${s("modo_desarrollador")} espacio(s) el modo desarrollador est\xE1 apagado: no se ha tocado.`),s("error")&&console.log(`\xB7 En ${s("error")} espacio(s) no se ha podido actualizar: prueba con \`forgenex instalar --app\`.`),s("cliente_ajeno")&&console.log(`\xB7 En ${s("cliente_ajeno")} espacio(s) no se ha tocado: en ForgeNEX ya no son tuyos ni de un cliente tuyo.`),s("panel_no_disponible")&&console.log(`\xB7 En ${s("panel_no_disponible")} espacio(s) no se ha tocado porque no se ha podido comprobar con ForgeNEX: vuelve a publicar en un momento o usa \`forgenex instalar --app\`.`),0}if(e==="sandbox"){let{sandbox:t}=await Promise.resolve().then(()=>(sb(),ab));return await t(o),0}if(e==="dev"){let{iniciarDev:t}=await Promise.resolve().then(()=>(Hc(),eb));return await t(o),0}return null}var G_,Ji=f(()=>{cn();Tt();vr();Mc();Ug();G_={ok:"\u2713",aviso:"!",falla:"\u2717"}});import{readFileSync as Zc,statSync as H_}from"node:fs";import{dirname as X_,join as mb}from"node:path";import{posix as Zi}from"node:path";var wb=/<(?:html|body)\b[^>]*\s(?:id|class|data-[\w-]+|style|lang|dir|on\w+)\s*=/i,vb=/\b(?:document\s*\.\s*(?:body|documentElement)|(?:querySelector|matches)\s*\(\s*["'`](?:html|body)\b)\s*(?:\?\.|\.)?\s*(?:dataset|classList|className|getAttribute|id\b|style\b|lang\b|dir\b)/,yb=/(?:^|[\s,{])(?:html|body)(?=[.#\[])/m;function ul(e,o){return e.montajes.flatMap(({entrada:t})=>{let n=o(t);if(!n)return[];let a=[...n.matchAll(/<(?:link|script)\b[^>]*\s(?:href|src)\s*=\s*["']([\w./-]+)["']/gi)].map(([,c])=>Zi.normalize(Zi.join(Zi.dirname(t),c??""))),s=[n,...a.filter(c=>c.startsWith("interfaz/")).map(o)].join(`
|
|
50
|
+
`);return wb.test(n)||vb.test(s)||yb.test(s)?[`${t}: el anfitri\xF3n sustituye <html> y <body>. Pon los atributos de la app en un elemento interior.`]:[]})}vr();Ji();cn();Kr();Bs();Tc();xc();xi();Nc();Tt();var el=200;function Y_(e,o){try{return{archivo:e,ok:!0,solucion:tn(o,{topeCampos:el})}}catch(t){return{archivo:e,ok:!1,error:t instanceof Error?t.message:String(t)}}}function K_(e){try{let o=JSON.parse(e);return typeof o=="object"&&o!==null&&o.formato===at}catch{return!1}}function Z_(e,o){try{return{archivo:e,ok:!0,extension:Vo(o)}}catch(t){return{archivo:e,ok:!1,error:t instanceof Error?t.message:String(t)}}}function e0(){let e=n=>n.length>1?`${n.slice(0,-1).join(", ")} y ${n.at(-1)}`:n[0]??"",o=Pt.filter(n=>vn.has(n)).map(n=>`\xAB${n}\xBB`),t=Pt.filter(n=>!vn.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 o0(){let e=c=>({type:"string",maxLength:c}),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).",a={type:"string",pattern:"^[a-z][a-z0-9_.-]{0,79}$",description:"Un nombre de contrato suelto (como antes de la R5): no ofrece ni pide nada."},s=c=>({type:"object",additionalProperties:!1,required:c?["contrato","de"]:["contrato"],properties:{contrato:{type:"string",pattern:"^[a-z][a-z0-9_.-]{0,79}$",description:"Su nombre (\xABtaller.vehiculos\xBB)."},...c?{de:{type:"string",description:"El id de la app que lo ofrece (\xABcom.taller.vehiculos\xBB)."}}:{},titulo:{type:"string",maxLength:80,description:"C\xF3mo se llama en la pantalla de permisos (\xABVeh\xEDculos del taller\xBB)."},modulos:{type:"object",maxProperties:20,additionalProperties:{type:"array",minItems:1,maxItems:4,items:{enum:["ver","crear","editar","borrar"]}},description:"M\xF3dulos de la soluci\xF3n de la app que lo ofrece, con su clave del manifiesto (\xABvehiculos\xBB), y sus operaciones."},eventos:{type:"array",maxItems:3,items:{enum:["registro.creado","registro.actualizado","registro.borrado"]},description:"Los de los registros de sus m\xF3dulos (con \xABver\xBB de alguno)."},herramientas:{type:"array",maxItems:20,items:{type:"string",pattern:"^[a-z][a-z0-9_]{2,40}$"},description:"Herramientas (herramientas_ia) que no escriben; se usan con la operaci\xF3n v1 \xABapp.usar_herramienta\xBB."}}});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${at}\xBB, versi\xF3n ${wn}. 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:at},formato_version:{type:"integer",minimum:1,maximum:wn,description:"Versi\xF3n del FORMATO (no de la app)."},id:{type:"string",maxLength:200,pattern:"^[a-z][a-z0-9-]{0,62}(\\.[a-z0-9][a-z0-9-]{0,62}){1,6}$",description:"Dominio inverso: com.tuempresa.mi-extension. No cambia nunca."},nombre:e(80),descripcion:e(500),version:{type:"string",pattern:"^(0|[1-9][0-9]{0,5})\\.(0|[1-9][0-9]{0,5})\\.(0|[1-9][0-9]{0,5})(-[0-9a-z.-]{1,30})?$",description:"La versi\xF3n de la app (semver)."},autor:{oneOf:[e(120),{type:"object",additionalProperties:!1,required:["nombre"],properties:{nombre:e(120),web:{type:"string",format:"uri",description:"https"}}}]},icono:{type:"string",pattern:"^[a-z0-9-]{1,40}$",description:"Un icono de lucide."},idiomas:{type:"array",maxItems:30,items:{type:"string",pattern:"^[a-z]{2,3}(-[A-Z]{2})?$"}},compatible_crm:{type:"string",maxLength:80,description:"Rango de versiones del CRM: \xAB>=1.6.0-284\xBB o \xAB>=1.6.0-284 <2.0.0\xBB."},licencia:e(40),politica_datos:{type:"string",format:"uri",description:"https: tu pol\xEDtica de datos. Obligatoria para entrar en la tienda si la app usa red (permisos.red_hacia)."},depende_de:{type:"array",maxItems:20,description:"Otras apps que tienen que estar instaladas.",items:{oneOf:[{type:"string"},{type:"object",additionalProperties:!1,required:["id"],properties:{id:{type:"string"},version:{type:"string"}}}]}},ofrece:{type:"array",maxItems:20,description:"Contratos que publica para otras apps: m\xF3dulos de SU soluci\xF3n (con operaciones que ella misma pide), eventos de registro de esos m\xF3dulos (que ella escucha) y herramientas suyas que no escriben. Otra app los usa con \xABusa\xBB y el permiso del administrador.",items:{oneOf:[a,s(!1)]}},usa:{type:"array",maxItems:20,description:"Contratos de otras apps que usa: \xABde\xBB es el id de la app que lo ofrece; lo que se concede es lo que esa app ofrece \u2229 lo que se pide, si el administrador lo acepta. Sin eso, 403.",items:{oneOf:[a,s(!0)]}},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:e0(),items:{type:"object",additionalProperties:!1,required:["id","punto","entrada","titulo"],properties:{id:{type:"string",pattern:"^[a-z][a-z0-9_-]{0,40}$"},punto:{enum:[...Pt]},entrada:t,titulo:e(60),icono:{type:"string"},modulo:{type:"string",description:`Solo en ${[..._r].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:[..._r]}},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:[...gn]},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:[...bn]},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)}}},conexiones:{type:"array",maxItems:20,items:{type:"object",additionalProperties:!1,required:["clave","base","tipo","operacion"],properties:{clave:{type:"string",pattern:"^[a-z][a-z0-9_]{0,40}$"},base:{type:"string",pattern:"^https://",maxLength:1e3},tipo:{enum:["api_key","bearer","basic","oauth2"]},operacion:{type:"string",pattern:"^[a-zA-Z][a-zA-Z0-9_.-]{0,79}$"},lugar:{enum:["cabecera","query"]},nombre:{type:"string",pattern:"^[a-zA-Z][a-zA-Z0-9_.-]{0,79}$"}},if:{properties:{tipo:{const:"api_key"}}},then:{required:["lugar","nombre"]},else:{not:{anyOf:[{required:["lugar"]},{required:["nombre"]}]}}}},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(Bo).map(([c,d])=>`${c} (${d.ops.join(", ")})`).join("; ")}. Los de su soluci\xF3n o del espacio, por su clave: ${Wo.join(", ")}.`,additionalProperties:{type:"array",minItems:1,maxItems:4,uniqueItems:!0,items:{enum:[...Wo]}}},almacen:{type:"boolean",description:"Guardar sus datos internos (clave-valor JSON) en el almac\xE9n de la app."},red_hacia:{type:"array",maxItems:20,items:o,description:"Los dominios a los que pueden conectarse sus funciones (\xAB*.ejemplo.com\xBB cubre sus subdominios). El administrador acepta cada uno."},eventos:{type:"array",maxItems:40,items:{type:"string"},description:"Los eventos del CRM de los que se entera (registro.creado, registro.actualizado\u2026). El administrador acepta cada uno."},archivos:{type:"array",maxItems:2,uniqueItems:!0,items:{enum:["leer","escribir"]},description:"1.17.0: los archivos del almacenamiento del espacio que la persona ELIGE con archivos.elegir() (el explorador del CRM). \xABleer\xBB: verlos (archivos.leer); \xABescribir\xBB (pide tambi\xE9n \xABleer\xBB): vincularlos a una ficha (archivos.vincular). Nunca ve el \xE1rbol ni recibe tokens de OneDrive o Google."}}}},"x-forgenex":{tamanoMaximoBytes:hn}}}function fb(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 t0(){let e=o=>({type:"string",maxLength:o});return{$schema:"https://json-schema.org/draft/2020-12/schema",$id:`https://forgenex.com/sdk/solucion-v${pr}.schema.json`,title:"Soluci\xF3n del CRM ForgeNEX",description:`Formato \xAB${kt}\xBB, versi\xF3n ${pr}. 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:kt},version:{type:"integer",minimum:1,maximum:pr,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}$"},conexiones:{type:"array",maxItems:25,items:{oneOf:[{type:"object",additionalProperties:!1,required:["tipo","conector"],properties:{clave:{type:"string"},nombre:{type:"string",maxLength:80},tipo:{const:"conector"},conector:{type:"string",pattern:"^[a-z][a-z0-9_-]{0,39}$"}}},{type:"object",additionalProperties:!1,required:["clave","nombre","tipo"],properties:{clave:{type:"string",pattern:"^[a-z][a-z0-9_]{0,39}$"},nombre:{type:"string",minLength:1,maxLength:120},tipo:{enum:["api","mcp"]}}}]}},fuentesExternas:{type:"array",maxItems:30,items:{type:"object",additionalProperties:!1,required:["modulo","conexion","operacion","filas","mapeo","modo"],properties:{modulo:{type:"string"},conexion:{type:"string"},operacion:{type:"string"},filas:{type:"string",maxLength:160},mapeo:{type:"object",minProperties:1,additionalProperties:{type:"string",maxLength:160}},modo:{enum:["vivo","espejo"]},minutos:{type:"integer",minimum:5,maximum:10080},id_externo:{type:"string",maxLength:160},cursor:{type:"object",additionalProperties:!1,required:["ruta","parametro"],properties:{ruta:{type:"string",maxLength:160},parametro:{type:"string",maxLength:80}}}},if:{properties:{modo:{const:"espejo"}}},then:{required:["minutos","id_externo","cursor"]}}},modulos:{type:"array",minItems:1,maxItems:zi,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:[...ic]},campos:{type:"array",maxItems:el,items:{type:"object",required:["clave","etiqueta","tipo"],properties:{clave:{type:"string"},etiqueta:e(80),tipo:{enum:[...rc]},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:yi,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:_i,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:Ec,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:kc,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:Ac,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:qc,description:"Se instalan APAGADAS: una persona las revisa y las enciende."},ejemplos:{type:"object",description:`Datos de ejemplo por clave de m\xF3dulo (hasta ${Wi} cada uno).`,additionalProperties:{type:"array",maxItems:Wi}},informes:{type:"array",maxItems:on,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:Di,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:Rc,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:Pc,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:Fi,topeCampos:el}}}async function ol(e){let[o,...t]=e,n=await pb(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(`${kt} v${pr}`),0;if(o==="esquema")return console.log(JSON.stringify(t0(),null,2)),0;if(o==="esquema-extension")return console.log(JSON.stringify(o0(),null,2)),0;if((o==="validar"||o==="previsualizar")&&a.length){let s=a.map(c=>{try{let d=H_(c).isDirectory(),u=o==="validar"&&!d&&c.toLowerCase().endsWith(".fgx")?Zc(c):null;d&&Fe(c);let p=u?Lg(u):Zc(d?mb(c,"extension.json"):c,"utf8");if(!K_(p))return Y_(c,p);let m=Z_(c,p);if(!m.ok||o!=="validar")return m;let h=u?zo(u):null,b=ul(m.extension,y=>{if(h)return h.get(y)?.toString("utf8");try{return Zc(mb(d?c:X_(c),y),"utf8")}catch{return}});return{...m,avisos:b}}catch(d){return{archivo:c,ok:!1,error:d instanceof Error?d.message:String(d)}}});if(r)console.log(JSON.stringify(s.map(c=>c.ok?"extension"in c?{archivo:c.archivo,ok:!0,extension:c.extension,..."avisos"in c&&c.avisos.length?{avisos:c.avisos}:{}}:{archivo:c.archivo,ok:!0,resumen:fb(c.solucion)}:c)));else for(let c of s){if(!c.ok){console.log(`\u2717 ${c.archivo}: ${c.error}`);continue}if("extension"in c){let d=c.extension;if("avisos"in c)for(let m of c.avisos)console.log(` ! ${m}`);console.log(`\u2713 ${c.archivo}: app \xAB${d.nombre}\xBB ${d.version} (${d.id})`);for(let[m,h]of Object.entries(d.permisos.modulos))console.log(` \xB7 pide ${m}: ${h.join(", ")}`);d.permisos.almacen&&console.log(" \xB7 pide su almac\xE9n"),d.permisos.archivos?.length&&console.log(` \xB7 pide archivos (lo que la persona elija): ${d.permisos.archivos.join(", ")}`);let u=[...new Set(d.montajes.filter(m=>!vn.has(m.punto)).map(m=>`montajes.${m.punto}`))];for(let m of d.funciones)console.log(` \xB7 funci\xF3n ${m.nombre} (${m.disparador.tipo}${m.disparador.evento?`: ${m.disparador.evento}`:m.disparador.cron?`: ${m.disparador.cron}`:""})`);for(let m of d.permisos.red_hacia)console.log(` \xB7 se conecta a ${m}`);let p=[...u,d.servidor&&"servidor"].filter(Boolean);p.length&&console.log(` (v\xE1lidos, pero a\xFAn no se ejecutan: ${p.join(", ")})`);continue}if(console.log(`\u2713 ${c.archivo}: \xAB${c.solucion.nombre}\xBB, ${c.solucion.modulos.length} m\xF3dulos`),o==="previsualizar"){let d=fb(c.solucion);for(let u of d.modulos)console.log(` \xB7 ${u.nombre} (${u.clave}): ${u.campos} campos${u.relaciones.length?`, \u2192 ${u.relaciones.join(", ")}`:""}${u.vistas?`, ${u.vistas} vistas`:""}`);console.log(` paneles: ${d.paneles} \xB7 automatizaciones: ${d.automatizaciones} (se instalan apagadas)`)}}return s.every(c=>c.ok)?0:1}return console.log("Uso: forgenex sandbox [parar] [--puerto <n>] \xB7 crear-app <nombre> [--plantilla html|react|archivos|natacion] \xB7 validar [directorio|archivo.json|archivo.fgx \u2026] [--json] \xB7 dev --espacio <id> \xB7 empaquetar [--sin-firmar] \xB7 instalar --espacio <id> (--app <id> | --paquete <archivo.fgx>) \xB7 publicar --espacio <id> --paquete <archivo.fgx> [--tienda] \xB7 revisar [--paquete <archivo.fgx>] [--json] \xB7 claves crear \xB7 registrar-clave \xB7 revocar-clave \xB7 previsualizar \xB7 esquema \xB7 esquema-extension \xB7 version"),2}process.argv[1]?.endsWith("cli.ts")&&ol(process.argv.slice(2)).then(e=>{process.exitCode=e}).catch(e=>{console.error(e instanceof Error?e.message:String(e)),process.exitCode=1});ol(process.argv.slice(2)).then(e=>{process.exitCode=e}).catch(e=>{console.error(e instanceof Error?e.message:String(e)),process.exitCode=1});
|