Elffuss BraidHub

utopia-ia/elffuss-code public

main · 7.0 KiBRawPermalink
1// Formatos que traen las extensiones de VS Code: JSON con comentarios (JSONC),
2// plist XML (.tmTheme / .tmLanguage) y colores hex. Sin DOM ni dependencias:
3// se prueban en Node igual que en el navegador.
4
5// Nombres que un objeto normal hereda de Object.prototype (más «prototype»).
6// Usados como clave de un objeto de datos, una búsqueda sale del objeto y una
7// escritura toca el prototipo: los datos de una extensión nunca deben llegar
8// con ellos a donde se busca o se escribe por nombre.
9export const NOMBRES_PROTO = new Set([...Object.getOwnPropertyNames(Object.prototype), 'prototype']);
10
11// JSONC como lo lee VS Code: comentarios // y /* */ y comas finales. Recorre
12// el texto respetando las cadenas, así un "http://…" dentro de un string no se
13// toma por comentario.
14export function parseJsonc(text) {
15 const s = String(text ?? '').replace(/^/, '');
16 let out = '';
17 let coma = false; // coma pendiente: se escribe solo si no cierra
18 for (let i = 0; i < s.length;) {
19 const c = s[i];
20 if (c === '"') {
21 if (coma) { out += ','; coma = false; }
22 let j = i + 1;
23 while (j < s.length && s[j] !== '"') j += s[j] === '\\' ? 2 : 1;
24 out += s.slice(i, j + 1);
25 i = j + 1;
26 continue;
27 }
28 if (c === '/' && s[i + 1] === '/') { const e = s.indexOf('\n', i); i = e < 0 ? s.length : e; continue; }
29 if (c === '/' && s[i + 1] === '*') { const e = s.indexOf('*/', i + 2); i = e < 0 ? s.length : e + 2; continue; }
30 if (c === ',') { if (coma) out += ','; coma = true; i++; continue; }
31 if (c === ' ' || c === '\t' || c === '\n' || c === '\r') { out += c; i++; continue; }
32 if (coma) { if (c !== '}' && c !== ']') out += ','; coma = false; }
33 out += c;
34 i++;
35 }
36 if (coma) out += ',';
37 return JSON.parse(out);
38}
39
40// plist XML de Apple (temas .tmTheme y gramáticas .tmLanguage). Analizador
41// propio y mínimo: nunca resuelve entidades externas ni DTD, y funciona sin DOM.
42const ENTIDADES = { lt: '<', gt: '>', amp: '&', quot: '"', apos: "'" };
43function desentidad(t) {
44 return t.replace(/&(#x[0-9a-f]+|#\d+|\w+);/gi, (m, e) => {
45 if (e[0] === '#') {
46 const n = e[1] === 'x' || e[1] === 'X' ? parseInt(e.slice(2), 16) : parseInt(e.slice(1), 10);
47 return Number.isFinite(n) && n >= 0 && n <= 0x10ffff ? String.fromCodePoint(n) : m;
48 }
49 return ENTIDADES[e] ?? m;
50 });
51}
52
53export function parsePlist(text) {
54 const s = String(text ?? '').replace(/^/, '');
55 let i = 0;
56 const fallo = msg => { throw Object.assign(new Error(`plist: ${msg} (posición ${i})`), { code: 'plist' }); };
57
58 // salta espacios, comentarios, <?xml?> y <!DOCTYPE>
59 function saltaRelleno() {
60 for (;;) {
61 while (i < s.length && /\s/.test(s[i])) i++;
62 if (s.startsWith('<!--', i)) { const e = s.indexOf('-->', i + 4); i = e < 0 ? s.length : e + 3; continue; }
63 if (s.startsWith('<?', i)) { const e = s.indexOf('?>', i + 2); i = e < 0 ? s.length : e + 2; continue; }
64 if (s.startsWith('<!DOCTYPE', i) || s.startsWith('<!doctype', i)) { const e = s.indexOf('>', i); i = e < 0 ? s.length : e + 1; continue; }
65 return;
66 }
67 }
68 // lee una etiqueta: { nombre, cierre, vacia }
69 function etiqueta() {
70 saltaRelleno();
71 if (s[i] !== '<') fallo('se esperaba una etiqueta');
72 const e = s.indexOf('>', i);
73 if (e < 0) fallo('etiqueta sin cerrar');
74 let cuerpo = s.slice(i + 1, e).trim();
75 i = e + 1;
76 const cierre = cuerpo.startsWith('/');
77 const vacia = cuerpo.endsWith('/');
78 cuerpo = cuerpo.replace(/^\//, '').replace(/\/$/, '').trim();
79 return { nombre: cuerpo.split(/\s+/)[0], cierre, vacia };
80 }
81 // texto hasta </nombre>, con CDATA y entidades
82 function texto(nombre) {
83 let out = '';
84 for (;;) {
85 if (i >= s.length) fallo(`falta </${nombre}>`);
86 if (s.startsWith('<![CDATA[', i)) {
87 const e = s.indexOf(']]>', i + 9);
88 if (e < 0) fallo('CDATA sin cerrar');
89 out += s.slice(i + 9, e);
90 i = e + 3;
91 } else if (s.startsWith('<!--', i)) {
92 const e = s.indexOf('-->', i + 4);
93 i = e < 0 ? s.length : e + 3;
94 } else if (s[i] === '<') {
95 const t = etiqueta();
96 if (!t.cierre || t.nombre !== nombre) fallo(`se esperaba </${nombre}>`);
97 return out;
98 } else {
99 const e = s.indexOf('<', i);
100 const trozo = e < 0 ? s.slice(i) : s.slice(i, e);
101 out += desentidad(trozo);
102 i = e < 0 ? s.length : e;
103 }
104 }
105 }
106 function valor(t) {
107 switch (t.nombre) {
108 case 'dict': {
109 const o = {};
110 if (t.vacia) return o;
111 for (;;) {
112 const k = etiqueta();
113 if (k.cierre && k.nombre === 'dict') return o;
114 if (k.nombre !== 'key') fallo('se esperaba <key>');
115 const clave = k.vacia ? '' : texto('key');
116 const v = etiqueta();
117 if (v.cierre) fallo('falta el valor de ' + clave);
118 const x = valor(v);
119 if (clave !== '__proto__') o[clave] = x; // asignarla cambiaría el prototipo de `o`
120 }
121 }
122 case 'array': {
123 const a = [];
124 if (t.vacia) return a;
125 for (;;) {
126 const v = etiqueta();
127 if (v.cierre && v.nombre === 'array') return a;
128 if (v.cierre) fallo('cierre inesperado');
129 a.push(valor(v));
130 }
131 }
132 case 'string': case 'date': case 'data': return t.vacia ? '' : texto(t.nombre);
133 case 'integer': return t.vacia ? 0 : parseInt(texto('integer'), 10);
134 case 'real': return t.vacia ? 0 : parseFloat(texto('real'));
135 case 'true': if (!t.vacia) texto('true'); return true;
136 case 'false': if (!t.vacia) texto('false'); return false;
137 default: return fallo('etiqueta desconocida <' + t.nombre + '>');
138 }
139 }
140 const raiz = etiqueta();
141 if (raiz.nombre !== 'plist') return valor(raiz); // plist sin envoltorio
142 if (raiz.vacia) return null;
143 const v = etiqueta();
144 if (v.cierre) return null;
145 return valor(v);
146}
147
148// Colores: solo #rgb, #rgba, #rrggbb o #rrggbbaa. Cualquier otra cosa (un
149// url(), un nombre, una variable) no pasa: llegaría a Monaco o a una variable
150// CSS y podría hacer una petición a un servidor de fuera.
151const HEX = /^#([0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/i;
152export const isHexColor = v => typeof v === 'string' && HEX.test(v);
153
154// → '#RRGGBB' en mayúsculas. El alfa se mezcla sobre `fondo` si se da (un
155// comentario '#ffffff80' sobre fondo oscuro sale gris, como en VS Code) y si
156// no, se descarta. null si el color no es válido.
157export function hex6(v, fondo = null) {
158 if (!isHexColor(v)) return null;
159 let h = v.slice(1);
160 if (h.length <= 4) h = [...h].map(c => c + c).join('');
161 const rgb = [0, 2, 4].map(k => parseInt(h.slice(k, k + 2), 16));
162 const a = h.length === 8 ? parseInt(h.slice(6, 8), 16) / 255 : 1;
163 let final = rgb;
164 if (a < 1 && isHexColor(fondo)) {
165 const f = hex6(fondo).slice(1);
166 const bg = [0, 2, 4].map(k => parseInt(f.slice(k, k + 2), 16));
167 final = rgb.map((c, k) => Math.round(c * a + bg[k] * (1 - a)));
168 }
169 return '#' + final.map(c => c.toString(16).padStart(2, '0')).join('').toUpperCase();
170}