| 1 | // Pruebas en Node (sin navegador) de lo que no necesita Monaco: lectura del |
| 2 | // .vsix, JSONC/plist, colores, mapeo de temas, lenguajes y snippets. |
| 3 | // node tests/ext_unit.mjs |
| 4 | import { spawnSync } from 'node:child_process'; |
| 5 | import { readFileSync } from 'node:fs'; |
| 6 | import { createHash } from 'node:crypto'; |
| 7 | import { parseJsonc, parsePlist, hex6, isHexColor, NOMBRES_PROTO } from '../web/js/ext/formats.js'; |
| 8 | import { openZip, crc32 } from '../web/js/ext/unzip.js'; |
| 9 | import { readVsix, analyzeManifest, resolveNls } from '../web/js/ext/vsix.js'; |
| 10 | import { toMonacoTheme, toTextMateTheme, monarchRules, resolveScope, themeIdFor, chromeCss, builtinTheme, joinPath } from '../web/js/ext/themes.js'; |
| 11 | import { toLanguageConfiguration, matchLanguage, globToRegExp, nestedRepetition, unsafeConfigRegexes, firstLineCandidates, matchFirstLine, FIRST_LINE_MAX } from '../web/js/ext/languages.js'; |
| 12 | import { normalizeSnippets, replaceStart, registerSnippets } from '../web/js/ext/snippets.js'; |
| 13 | import { sanitizeGrammar } from '../web/js/ext/grammars.js'; |
| 14 | import { textoError, textoAviso } from '../web/js/ext/panel.js'; |
| 15 | import { STRINGS } from '../web/js/ext/i18n.js'; |
| 16 | import { describe as veredicto } from '../web/js/ext/verdict.js'; |
| 17 | import tm from '../web/js/ext/vendor/vscode-textmate@9.3.2/main.js'; |
| 18 | import { zip, themeVsix, elfscriptVsix, THEME_DARK, ELFS, EVIL_GRAMMAR, brokenThemeVsix, noPublisherVsix, slowRegexVsix, SLOW } from './ext_fixtures.mjs'; |
| 19 | |
| 20 | let fails = 0; |
| 21 | const ok = (n, c, e = '') => { console.log((c ? '✅' : '❌') + ' ' + n + (e ? ' — ' + e : '')); if (!c) fails++; }; |
| 22 | const throws = async (fn, re) => { try { await fn(); return false; } catch (e) { return re ? re.test(e.message) : true; } }; |
| 23 | const codigo = async fn => { try { await fn(); return null; } catch (e) { return e.code ?? 'sin código: ' + e.message; } }; |
| 24 | // En otro proceso, con tiempo tope: lo que ahí se rompa (el prototipo de todos |
| 25 | // los objetos) no contamina estas pruebas, y una expresión sin fin no las cuelga. |
| 26 | function enOtroProceso(js, timeout = 20000) { |
| 27 | const r = spawnSync(process.execPath, ['--input-type=module', '-e', js], { encoding: 'utf8', timeout }); |
| 28 | return { out: (r.stdout || '').trim(), err: (r.stderr || '').trim().split('\n').slice(-2).join(' '), colgado: r.error?.code === 'ETIMEDOUT' }; |
| 29 | } |
| 30 | const VENDOR = new URL('../web/js/ext/vendor/', import.meta.url); |
| 31 | |
| 32 | // ── JSONC ── |
| 33 | { |
| 34 | const j = parseJsonc('\uFEFF{ // c\n "a": "http://x//y", /* b */ "b": [1, 2, ], "c": {"d": "\\"/*no*/\\"",}, }'); |
| 35 | ok('JSONC: comentarios, comas finales y // dentro de cadenas', j.a === 'http://x//y' && j.b.length === 2 && j.c.d === '"/*no*/"', JSON.stringify(j)); |
| 36 | ok('JSONC: lo inválido sigue fallando', await throws(() => parseJsonc('{"a": 1,, "b": 2}'))); |
| 37 | } |
| 38 | |
| 39 | // ── plist ── |
| 40 | { |
| 41 | const p = parsePlist(`<?xml version="1.0"?><!DOCTYPE plist><plist version="1.0"><dict> |
| 42 | <key>s</key><string>a <b> & AB</string><key>n</key><integer>42</integer><key>r</key><real>1.5</real> |
| 43 | <key>t</key><true/><key>f</key><false/><key>e</key><string/><key>arr</key><array><string>x</string><dict/><array/></array> |
| 44 | <key>cd</key><string><![CDATA[<raw & stuff>]]></string></dict></plist>`); |
| 45 | ok('plist: tipos, entidades y CDATA', p.s === 'a <b> & AB' && p.n === 42 && p.r === 1.5 && p.t === true && p.f === false && p.e === '' && p.arr.length === 3 && p.cd === '<raw & stuff>', JSON.stringify(p)); |
| 46 | ok('plist: roto → error', await throws(() => parsePlist('<plist><dict><key>a</key></dict></plist>'))); |
| 47 | } |
| 48 | |
| 49 | // ── colores ── |
| 50 | ok('hex6: #abc → #AABBCC', hex6('#abc') === '#AABBCC'); |
| 51 | ok('hex6: alfa mezclado sobre el fondo', hex6('#ffffff80', '#000000') === '#808080', hex6('#ffffff80', '#000000')); |
| 52 | ok('hex6: alfa sin fondo se descarta', hex6('#12345678') === '#123456'); |
| 53 | ok('colores no hex rechazados (url(), nombres, rgb())', !isHexColor('url(x)') && !isHexColor('red') && !isHexColor('rgb(1,2,3)') && hex6('#12') === null); |
| 54 | |
| 55 | // ── zip ── |
| 56 | { |
| 57 | const z = zip([['a.txt', 'hola'], ['b/c.json', '{"x":1}', { method: 0 }], ['big.txt', 'x'.repeat(5000)]]); |
| 58 | const r = openZip(z, { maxEntry: 4000 }); |
| 59 | ok('zip: índice del directorio central', r.names.join(',') === 'a.txt,b/c.json,big.txt', r.names.join(',')); |
| 60 | ok('zip: deflate y stored', new TextDecoder().decode(await r.read('a.txt')) === 'hola' && new TextDecoder().decode(await r.read('b/c.json')) === '{"x":1}'); |
| 61 | ok('zip: tope por entrada', await throws(() => r.read('big.txt'), /pesa demasiado/)); |
| 62 | const bomba = zip([['bomb.txt', 'y'.repeat(100000), { declaredSize: 10 }]]); |
| 63 | ok('zip: una entrada que infla más de lo que declara se corta', await throws(() => openZip(bomba).read('bomb.txt'), /demasiado grande/)); |
| 64 | ok('zip: lo que no es zip se rechaza', await throws(() => openZip(new Uint8Array(100)), /no es un zip/)); |
| 65 | ok('crc32 conocido', crc32(new TextEncoder().encode('123456789')) === 0xcbf43926); |
| 66 | } |
| 67 | |
| 68 | // ── .vsix de tema ── |
| 69 | const tema = await readVsix(themeVsix(), { lang: 'es' }); |
| 70 | ok('vsix: id y nombre traducido (package.nls.es.json)', tema.id === 'elffuss-test.elf-theme' && tema.displayName === 'Tema Elfo' && tema.description === 'Synthetic test theme', `${tema.id} · ${tema.displayName} · ${tema.description}`); |
| 71 | ok('vsix: dos temas, etiqueta %clave% resuelta', tema.themes.length === 2 && tema.themes[0].label === 'Elfo Oscuro', tema.themes.map(t => t.label).join(' | ')); |
| 72 | { |
| 73 | const d = tema.themes[0].data; |
| 74 | ok('tema: include encadenado (colores del base + propios)', d.colors['editorCursor.foreground'] === '#FFCC00' && d.colors['editor.background'] === THEME_DARK.bg); |
| 75 | ok('tema: color con url() descartado', !('sideBar.background' in d.colors)); |
| 76 | ok('tema: reglas del base primero y luego las propias', d.tokenColors[0].scope.join() === 'keyword,storage.type' && d.tokenColors.at(-1).scope[0] === 'source.elfs keyword', d.tokenColors.map(r => r.scope?.join('+')).join(' | ')); |
| 77 | const l = tema.themes[1].data; |
| 78 | ok('tema .tmTheme (plist): fondo/primer plano/cursor de la regla global', l.uiTheme === 'vs' && l.colors['editor.background'] === '#FAFAF0' && l.colors['editorCursor.foreground'] === '#FF0000'); |
| 79 | } |
| 80 | ok('vsix: el JS del paquete no se lee nunca (main ignorado, la entrada es ilegible y no falla)', tema.analysis.hasCode === true && !tema.warnings.length, tema.warnings.join('; ')); |
| 81 | ok('vsix: lo que no aplica, con motivo', tema.analysis.ignored.some(i => i.key === 'commands' && i.why === 'code') && tema.analysis.ignored.some(i => i.key === 'iconThemes' && i.why === 'later')); |
| 82 | ok('vsix: licencia leída del paquete', /MIT License/.test(tema.licenseText)); |
| 83 | |
| 84 | // ── mapeo del tema a Monaco ── |
| 85 | { |
| 86 | const d = tema.themes[0].data; |
| 87 | const m = toMonacoTheme(d); |
| 88 | const regla = t => m.rules.find(r => r.token === t); |
| 89 | ok('Monaco: base y herencia', m.base === 'vs-dark' && m.inherit === true); |
| 90 | ok('Monaco: keyword ← keyword/storage.type', regla('keyword')?.foreground === THEME_DARK.keyword.slice(1), JSON.stringify(regla('keyword'))); |
| 91 | ok('Monaco: keyword.flow ← keyword.control (el selector más largo gana)', regla('keyword.flow')?.foreground === THEME_DARK.control.slice(1)); |
| 92 | ok('Monaco: comment con cursiva', regla('comment')?.foreground === THEME_DARK.comment.slice(1) && regla('comment')?.fontStyle === 'italic'); |
| 93 | ok('Monaco: string y number', regla('string')?.foreground === THEME_DARK.string.slice(1) && regla('number')?.foreground === THEME_DARK.number.slice(1)); |
| 94 | ok('Monaco: sin regla en el tema → color por defecto del tema, no el de serie', regla('tag')?.foreground === THEME_DARK.fg.slice(1), JSON.stringify(regla('tag'))); |
| 95 | ok('Monaco: los colores pasan tal cual (y el url() no)', m.colors['editor.background'] === THEME_DARK.bg && m.colors['tab.activeBackground'] === THEME_DARK.tabActive && !m.colors['sideBar.background']); |
| 96 | ok('Monaco: los selectores con contexto no se usan para Monarch', !m.rules.some(r => r.foreground === '123456')); |
| 97 | ok('resolveScope: keyword.control.flow → control; keyword.other → keyword', resolveScope(d.tokenColors, 'keyword.control.flow').foreground === THEME_DARK.control && resolveScope(d.tokenColors, 'keyword.other').foreground === THEME_DARK.keyword); |
| 98 | const tm = toTextMateTheme(d); |
| 99 | ok('TextMate: primera regla = colores por defecto del editor', tm.settings[0].settings.foreground === THEME_DARK.fg && tm.settings[0].settings.background === THEME_DARK.bg); |
| 100 | ok('TextMate: todos los colores en #RRGGBB', tm.settings.every(s => Object.entries(s.settings).every(([k, v]) => k === 'fontStyle' || /^#[0-9A-F]{6}$/.test(v)))); |
| 101 | ok('TextMate: conserva los selectores con contexto (los resuelve vscode-textmate)', tm.settings.some(s => s.scope?.[0] === 'source.elfs keyword')); |
| 102 | const lt = toMonacoTheme(tema.themes[1].data); |
| 103 | ok('Monaco (tmTheme claro): base vs y keyword', lt.base === 'vs' && lt.rules.find(r => r.token === 'keyword')?.foreground === 'AA0000'); |
| 104 | const b = builtinTheme('vs'); |
| 105 | ok('temas de serie con colores TextMate (Light+)', b.uiTheme === 'vs' && toTextMateTheme(b).settings.some(s => s.scope?.includes('comment') && s.settings.foreground === '#008000')); |
| 106 | const css = chromeCss(d); |
| 107 | ok('CSS de pestañas solo con colores hex', css.includes(THEME_DARK.tabActive) && !/url\(|example/.test(css), css.split('\n')[0]); |
| 108 | const usados = new Set(); |
| 109 | const id1 = themeIdFor('Elffuss-Test.Elf Theme', { id: 'Elf Dark (ñ)' }, 0, usados), id2 = themeIdFor('Elffuss-Test.Elf Theme', { id: 'Elf Dark (ñ)' }, 1, usados); |
| 110 | ok('ids de tema válidos para Monaco y únicos', /^[a-z0-9-]+$/.test(id1) && id1 !== id2, `${id1} · ${id2}`); |
| 111 | ok('monarchRules sin tokenColors no rompe', monarchRules({ uiTheme: 'vs', colors: {}, tokenColors: [] }).every(r => /^[0-9A-F]{6}$/.test(r.foreground || '000000'))); |
| 112 | } |
| 113 | |
| 114 | // ── .vsix de lenguaje + gramática + snippets ── |
| 115 | const elfs = await readVsix(elfscriptVsix()); |
| 116 | ok('vsix lenguaje: contribuciones leídas', elfs.languages.length === 1 && elfs.grammars.length === 2 && elfs.snippets.length === 2, `${elfs.languages.length}/${elfs.grammars.length}/${elfs.snippets.length} ${elfs.warnings.join(';')}`); |
| 117 | ok('vsix lenguaje: gramática plist (.tmLanguage)', elfs.grammars[1].scopeName === 'source.elfs.rune' && elfs.grammars[1].data.patterns.length === 1 && !elfs.grammars[1].language); |
| 118 | ok('vsix lenguaje: tokenTypes y licencia «SEE LICENSE IN»', elfs.grammars[0].tokenTypes['string.quoted.single.elfs'] === 'other' && /public domain/.test(elfs.licenseText)); |
| 119 | ok('vsix lenguaje: configurationDefaults no se aplica', elfs.analysis.ignored.some(i => i.key === 'configurationDefaults' && i.why === 'later')); |
| 120 | { |
| 121 | const IA = { None: 0, Indent: 1, IndentOutdent: 2, Outdent: 3 }; |
| 122 | const conf = toLanguageConfiguration(elfs.languages[0].config, { languages: { IndentAction: IA } }); |
| 123 | ok('config: comentarios, corchetes y pares', conf.comments.lineComment === '#' && conf.comments.blockComment[0] === '#[' && conf.brackets.length === 3 && conf.autoClosingPairs.length === 3 && conf.autoClosingPairs[2].notIn[0] === 'string'); |
| 124 | ok('config: expresiones → RegExp', conf.wordPattern instanceof RegExp && conf.wordPattern.test('elf-name') && conf.indentationRules.increaseIndentPattern.test(' spell x')); |
| 125 | ok('config: onEnterRules con IndentAction y la regla con regex inválida fuera', conf.onEnterRules.length === 1 && conf.onEnterRules[0].action.indentAction === IA.Indent); |
| 126 | ok('config: folding markers', conf.folding.markers.start.test('#region a')); |
| 127 | } |
| 128 | { |
| 129 | const c = [{ id: 'a', extensions: ['.mk'], filenames: ['Makefile'] }, ...elfs.languages]; |
| 130 | ok('lenguaje por nombre exacto', matchLanguage(c, 'src/Elffile') === ELFS.lang && matchLanguage(c, 'Makefile') === 'a'); |
| 131 | ok('lenguaje por extensión (sin distinguir mayúsculas)', matchLanguage(c, 'x/Y.ELFS') === ELFS.lang && matchLanguage(c, 'a.mk') === 'a'); |
| 132 | const fl = firstLineCandidates(c); |
| 133 | ok('lenguaje por patrón y por primera línea', matchLanguage(c, 'book/spells/fire.spell') === ELFS.lang && matchFirstLine(fl, '#!/usr/bin/env elfs') === ELFS.lang && matchFirstLine(fl, '#!/bin/sh') === null && matchLanguage(c, 'run') === null); |
| 134 | ok('glob: **, * y {a,b}', globToRegExp('**/*.{js,ts}').test('a/b/c.ts') && !globToRegExp('*.js').test('a/b.js')); |
| 135 | } |
| 136 | { |
| 137 | const s = elfs.snippets[0].data; |
| 138 | ok('snippets: varios prefijos, cuerpo en líneas, grupo anidado, sin prefijo fuera', s.length === 3 && s[0].body === 'spell ${1:name}\n\tcast ${2:fire}\nend' && s.some(x => x.prefix === '#rune'), s.map(x => x.prefix).join(',')); |
| 139 | ok('snippets: rango sobre lo ya escrito (#ru → #rune)', replaceStart(' #ru', '#rune', 4) === 3 && replaceStart('x.elfl', 'elflog', 3) === 3 && replaceStart('foo', 'bar', 1) === 1); |
| 140 | ok('snippets: normalize tolera basura', normalizeSnippets(null).length === 0 && normalizeSnippets({ a: 1, b: { c: 'x' } }).length === 0); |
| 141 | } |
| 142 | |
| 143 | // ── utilidades ── |
| 144 | ok('joinPath no sale de la raíz', joinPath('extension/themes', './a/../b.json') === 'extension/themes/b.json' && await throws(() => joinPath('', '../x'))); |
| 145 | ok('resolveNls: %clave% y {message}', resolveNls({ a: '%k%', b: ['%m%'], c: '%no%' }, { k: 'K', m: { message: 'M' } }).b[0] === 'M'); |
| 146 | ok('analyzeManifest de un paquete solo con código', (() => { const a = analyzeManifest({ main: 'x.js', contributes: { commands: [{}] } }); return a.hasCode && !a.any; })()); |
| 147 | |
| 148 | // ── el motor TextMate va en el repo, sin cambios (y el de jsDelivr no) ── |
| 149 | { |
| 150 | // los valores son los del paquete npm (integridad del registro comprobada) |
| 151 | const esperado = { 'vscode-textmate@9.3.2': [61242, 'sha384-aJzUwh8/jeVrg5exYESASC3qwtfGKKHUgNPuT5uEM0bmJvnwLbJhuy+//+fZ+tPJ'], |
| 152 | 'vscode-oniguruma@2.0.1': [20469, 'sha384-KznAEs+/b3fCQKg6wXrLJQvj0dOjyZQpdCrIpt7hC03S7EovcZMXlHRHRN291Uaj'] }; |
| 153 | for (const [dir, [bytes, sri]] of Object.entries(esperado)) { |
| 154 | const buf = readFileSync(new URL(dir + '/main.js', VENDOR)); |
| 155 | const l1 = buf.indexOf(10), l2 = buf.indexOf(10, l1 + 1); |
| 156 | const cabecera = buf.subarray(0, l1).toString(); |
| 157 | const original = buf.subarray(l2 + 1, l2 + 1 + bytes); |
| 158 | const hash = 'sha384-' + createHash('sha384').update(original).digest('base64'); |
| 159 | ok(`vendor ${dir}: el original intacto dentro del envoltorio`, hash === sri && cabecera.includes(`${bytes} bytes, ${sri}`) |
| 160 | && buf.subarray(l1 + 1, l2).toString() === 'const module = { exports: {} }, exports = module.exports;' |
| 161 | && buf.subarray(l2 + 1 + bytes).toString() === '\nexport default module.exports;\n', hash); |
| 162 | } |
| 163 | ok('vendor: el motor se importa como módulo ES', typeof tm.Registry === 'function' && typeof tm.INITIAL === 'object'); |
| 164 | const src = readFileSync(new URL('../web/js/ext/grammars.js', import.meta.url), 'utf8'); |
| 165 | ok('grammars.js no carga código de +esm ni de otro origen (solo onig.wasm, con SRI)', !/\+esm/.test(src) && !/import\(\s*['"`]https?:/.test(src) && /WASM_SRI = 'sha384-/.test(src)); |
| 166 | } |
| 167 | |
| 168 | // ── gramáticas: nada de salir del repositorio por Object.prototype ── |
| 169 | { |
| 170 | const hostil = JSON.parse(EVIL_GRAMMAR); |
| 171 | const limpia = sanitizeGrammar(hostil); |
| 172 | const includes = [], claves = []; |
| 173 | (function recorre(v) { |
| 174 | if (Array.isArray(v)) return v.forEach(recorre); |
| 175 | if (!v || typeof v !== 'object') return; |
| 176 | for (const k of Object.keys(v)) { claves.push(k); if (k === 'include') includes.push(v[k]); recorre(v[k]); } |
| 177 | })(limpia); |
| 178 | const sinProto = inc => { const i = inc.indexOf('#'); return !NOMBRES_PROTO.has(i < 0 ? inc : inc.slice(i + 1)) && (i <= 0 || !NOMBRES_PROTO.has(inc.slice(0, i))); }; |
| 179 | ok('gramática: ningún include apunta a un nombre de Object.prototype', includes.length > 0 && includes.every(sinProto), includes.join(' ')); |
| 180 | ok('gramática: los include a una gramática llamada como Object.prototype, fuera', !includes.includes('hasOwnProperty') && !includes.some(i => i.startsWith('__proto__#'))); |
| 181 | ok('gramática: «constructor» legítimo renombrado a la vez en repository y en su include', '$elffuss-safe:constructor' in limpia.repository && includes.includes('#$elffuss-safe:constructor') && !Object.hasOwn(limpia.repository, 'constructor')); |
| 182 | ok('gramática: sin claves «__proto__» ni «id» (la marca del motor)', !claves.includes('__proto__') && !claves.includes('id'), claves.filter(k => k === '__proto__' || k === 'id').join()); |
| 183 | const elfs = JSON.parse(new TextDecoder().decode(await openZip(elfscriptVsix()).read('extension/syntaxes/elfs.tmLanguage.json'))); |
| 184 | ok('gramática legítima: sale igual que entra', JSON.stringify(sanitizeGrammar(elfs)) === JSON.stringify(elfs)); |
| 185 | ok('vsix: la gramática se guarda ya saneada', (await readVsix(elfscriptVsix())).grammars.every(g => JSON.stringify(g.data) === JSON.stringify(sanitizeGrammar(g.data)))); |
| 186 | |
| 187 | // con el motor de verdad, en otro proceso (Oniguruma de mentira: la escritura |
| 188 | // en el prototipo ocurre al compilar las reglas, antes de buscar nada) |
| 189 | const prueba = g => ` |
| 190 | const tm = (await import(${JSON.stringify(new URL('vscode-textmate@9.3.2/main.js', VENDOR).href)})).default; |
| 191 | const g0 = ${g}; |
| 192 | const onigLib = Promise.resolve({ createOnigScanner() { throw new Error('stub'); }, createOnigString: s => ({ content: s, dispose() {} }) }); |
| 193 | const reg = new tm.Registry({ onigLib, loadGrammar: async s => (s === g0.scopeName ? g0 : null) }); |
| 194 | const gr = await reg.loadGrammar(g0.scopeName); |
| 195 | try { gr.tokenizeLine('evil ctor (x)', tm.INITIAL); } catch {} |
| 196 | console.log(JSON.stringify({ proto: ({}).id ?? null, object: Object.id ?? null, toStr: Object.prototype.toString.id ?? null, valueOf: Object.prototype.valueOf.id ?? null, propia: Object.prototype.hasOwnProperty('id') }));`; |
| 197 | const antes = enOtroProceso(prueba(EVIL_GRAMMAR)); |
| 198 | ok('motor real SIN sanear: la gramática hostil escribe en Object.prototype (la prueba lo detecta)', /"proto":\d+/.test(antes.out) && /"propia":true/.test(antes.out), antes.out || antes.err); |
| 199 | const despues = enOtroProceso(prueba(JSON.stringify(limpia))); |
| 200 | ok('motor real con la gramática saneada: Object.prototype, Object y sus métodos intactos', despues.out === '{"proto":null,"object":null,"toStr":null,"valueOf":null,"propia":false}', despues.out || despues.err); |
| 201 | } |
| 202 | |
| 203 | // ── temas: un ámbito «hasOwnProperty» tumbaba el árbol de temas del motor ── |
| 204 | { |
| 205 | const tema = { uiTheme: 'vs-dark', colors: {}, tokenColors: [ |
| 206 | { scope: ['hasOwnProperty'], settings: { foreground: '#123123' } }, |
| 207 | { scope: ['__proto__.x', 'keyword.control'], settings: { foreground: '#DD2200' } }, |
| 208 | { scope: ['entity.name.function.constructor'], settings: { foreground: '#22AA44' } }, |
| 209 | ] }; |
| 210 | const reg = new tm.Registry({ onigLib: Promise.resolve({}), loadGrammar: async () => null }); |
| 211 | let crudo = null; |
| 212 | try { reg.setTheme({ settings: [{ settings: { foreground: '#111111', background: '#EEEEEE' } }, ...tema.tokenColors] }); } catch (e) { crudo = e.message; } |
| 213 | ok('motor real: el ámbito «hasOwnProperty» tal cual revienta setTheme (la prueba lo detecta)', /hasOwnProperty is not a function/.test(crudo || ''), crudo); |
| 214 | const tmTema = toTextMateTheme(tema); |
| 215 | let limpio = null; |
| 216 | try { reg.setTheme(tmTema); } catch (e) { limpio = e.message; } |
| 217 | ok('toTextMateTheme: fuera los selectores peligrosos, el resto se queda (constructor incluido)', limpio === null |
| 218 | && tmTema.settings.some(s => s.scope?.join() === 'keyword.control') && tmTema.settings.some(s => s.scope?.[0] === 'entity.name.function.constructor') |
| 219 | && !tmTema.settings.some(s => s.scope?.some(x => /hasOwnProperty|__proto__/.test(x))), limpio); |
| 220 | } |
| 221 | |
| 222 | // ── plist y traducciones no cambian el prototipo de nada ── |
| 223 | { |
| 224 | const p = parsePlist('<plist><dict><key>__proto__</key><dict><key>polluted</key><true/></dict><key>a</key><string>b</string></dict></plist>'); |
| 225 | ok('plist: una clave «__proto__» no cambia el prototipo', Object.getPrototypeOf(p) === Object.prototype && p.polluted === undefined && p.a === 'b'); |
| 226 | const r = resolveNls(JSON.parse('{"__proto__": {"contributes": {"themes": [1]}}, "a": "%k%"}'), { k: 'K' }); |
| 227 | ok('resolveNls: tampoco', Object.getPrototypeOf(r) === Object.prototype && r.contributes === undefined && r.a === 'K'); |
| 228 | ok('analyzeManifest: contribuciones que no son listas no lo rompen', analyzeManifest({ contributes: { snippets: {}, grammars: 'x', languages: null } }).any === false); |
| 229 | } |
| 230 | |
| 231 | // ── snippets: el detalle es texto, nunca Markdown (imágenes = peticiones) ── |
| 232 | { |
| 233 | let proveedor = null; |
| 234 | const monacoFalso = { Range: class { constructor(...a) { this.a = a; } }, languages: { |
| 235 | CompletionItemKind: { Snippet: 27 }, CompletionItemInsertTextRule: { InsertAsSnippet: 4 }, |
| 236 | registerCompletionItemProvider: (l, p) => { proveedor = p; return { dispose() {} }; } } }; |
| 237 | registerSnippets(monacoFalso, 'javascript', async () => [{ prefix: 'zz', name: 'n', description: '', body: 'a\n```\n\n```' }], () => 'Ext'); |
| 238 | const { suggestions: [s] } = await proveedor.provideCompletionItems({ getLineContent: () => 'zz', getWordUntilPosition: () => ({ startColumn: 1 }) }, { lineNumber: 1, column: 3 }); |
| 239 | ok('snippets: detail y documentation son strings (Monaco los pinta como texto, no Markdown)', s.documentation === 'a\n```\n\n```' && s.detail === ' (Ext)', JSON.stringify([s.detail, s.documentation])); |
| 240 | } |
| 241 | |
| 242 | // ── expresiones de los paquetes: nada de repetición anidada ── |
| 243 | { |
| 244 | const malas = ['^(a+)+$', '(a*)*', '(\\w+\\s?)*$', '(x|y+){2,}', '(?:a+){3}', '((a)+)*', '(?<n>b+)+', '(a{1,3})+']; |
| 245 | const buenas = ['^(\\t|[ ])*[ ]\\*[^/]*\\*/\\s*$', '^(\\t|[ ])*[ ]\\*([ ]([^\\*]|\\*(?!/))*)?$', '^\\s*/\\*\\*(?!/)([^\\*]|\\*(?!/))*$', |
| 246 | '^((.*=>\\s*)|((.*[^\\w]+|\\s*)(if|while|for)\\s*\\(.*\\)\\s*))$', '(-?\\d*\\.\\d\\w*)|([^\\`\\~\\!\\@\\#\\%\\^\\&\\*\\(\\)\\-\\=\\+\\[\\{\\]\\}\\\\\\|\\;\\:\\\'\\"\\,\\.\\<\\>\\/\\?\\s]+)', |
| 247 | '[a+]+', '\\(a+\\)+', '(\\d{1,3}\\.)', '^#!.*\\b(bash|zsh|sh)\\b.*|^#\\s*-\\*-[^*]*mode:\\s*shell-script[^*]*-\\*-', '(a+)?b', '(?=a+)']; |
| 248 | ok('repetición anidada: detectada', malas.every(nestedRepetition), malas.filter(x => !nestedRepetition(x)).join(' ')); |
| 249 | ok('repetición anidada: las de VS Code y las simples pasan', !buenas.some(nestedRepetition), buenas.filter(nestedRepetition).join(' ')); |
| 250 | const conf = toLanguageConfiguration({ wordPattern: '(a+)+$', folding: { markers: { start: '^(#+)+region', end: '#end' } }, onEnterRules: [{ beforeText: '(x*)*y', action: { indent: 'indent' } }, { beforeText: '^\\s*x', action: { indent: 'indent' } }] }, { languages: { IndentAction: { None: 0, Indent: 1 } } }); |
| 251 | ok('config: las peligrosas se descartan, las demás se quedan', !conf.wordPattern && !conf.folding.markers && conf.onEnterRules.length === 1, JSON.stringify(Object.keys(conf))); |
| 252 | ok('config: se pueden listar para avisar', unsafeConfigRegexes({ wordPattern: '(a+)+$', onEnterRules: [{ beforeText: { pattern: '(x*)*y' } }] }).join(' ') === '(a+)+$ (x*)*y'); |
| 253 | const fl = firstLineCandidates([{ id: 'a', firstLine: 'elfs' }, { id: 'b', firstLine: '^(a+)+$' }, { id: 'c', firstLine: '(' }]); |
| 254 | ok('firstLine: anclada al principio, sin las anidadas ni las inválidas', fl.length === 1 && fl[0].src === '^elfs' && matchFirstLine(fl, 'x elfs') === null && matchFirstLine(fl, 'elfs x') === 'a'); |
| 255 | ok('firstLine: solo se miran los primeros ' + FIRST_LINE_MAX + ' caracteres', matchFirstLine([{ id: 'z', src: '^a{' + (FIRST_LINE_MAX + 1) + '}' }], 'a'.repeat(FIRST_LINE_MAX + 50)) === null && matchFirstLine([{ id: 'z', src: '^a{' + FIRST_LINE_MAX + '}' }], 'a'.repeat(FIRST_LINE_MAX + 50)) === 'z'); |
| 256 | // el caso de la revisión: antes no terminaba nunca |
| 257 | const lang = JSON.stringify(new URL('../web/js/ext/languages.js', import.meta.url).href); |
| 258 | const r = enOtroProceso(`const L = await import(${lang}); const c = [{ id: 'evil', extensions: ['.evil'], firstLine: '^(a+)+$' }]; |
| 259 | console.log(String(L.matchLanguage(c, 'src/main.js', 'a'.repeat(40) + '!')), String(L.matchFirstLine(L.firstLineCandidates(c), 'a'.repeat(40) + '!')));`, 10000); |
| 260 | ok('firstLine ^(a+)+$ con «aaaa…!»: termina (null null)', !r.colgado && r.out === 'null null', r.colgado ? 'COLGADO' : r.out || r.err); |
| 261 | const v = await readVsix(slowRegexVsix()); |
| 262 | const regex = v.warnings.filter(w => w.kind === 'regex').map(w => w.detail); |
| 263 | ok('vsix: firstLine y wordPattern anidados descartados con aviso; la otra firstLine se queda (la para el Worker)', regex.includes('^(a+)+$') && regex.includes('(a+)+$') && v.languages.find(l => l.id === SLOW.nest).firstLine === undefined && v.languages.find(l => l.id === SLOW.lang).firstLine === SLOW.firstLine, JSON.stringify(regex)); |
| 264 | } |
| 265 | |
| 266 | // ── partes rotas, errores con código y textos en los dos idiomas ── |
| 267 | { |
| 268 | const medio = await readVsix(brokenThemeVsix()); |
| 269 | ok('vsix: el tema roto no tumba el bueno y queda su aviso (tipo, nombre y motivo)', medio.themes.length === 1 && medio.warnings.length === 1 && medio.warnings[0].kind === 'theme' && medio.warnings[0].name === 'Broken One' && medio.warnings[0].code === 'json', JSON.stringify(medio.warnings)); |
| 270 | ok('aviso legible: «Theme “Broken One”: not valid JSON (…)»', /^Theme “Broken One”: not valid JSON \(.+\)$/.test(textoAviso(medio.warnings[0])), textoAviso(medio.warnings[0])); |
| 271 | const roto = await readVsix(brokenThemeVsix({ onlyBroken: true })); |
| 272 | ok('vsix: si todas fallan, ningún tema y un aviso por cada una (JSON roto, fichero que falta)', roto.themes.length === 0 && roto.warnings.map(w => w.code).join() === 'json,missing', JSON.stringify(roto.warnings)); |
| 273 | ok('aviso legible de un fichero que falta', textoAviso(roto.warnings[1]) === 'Theme “Missing One”: the file is not in the package', textoAviso(roto.warnings[1])); |
| 274 | ok('aviso de la versión anterior (texto suelto): se enseña tal cual', textoAviso('tema x: roto') === 'tema x: roto'); |
| 275 | ok('package.json sin publisher → código noname', await codigo(() => readVsix(noPublisherVsix())) === 'noname'); |
| 276 | const malo = zip([['extension/package.json', '{ "name": "x", ']]); |
| 277 | ok('package.json que no es JSON → código badmanifest', await codigo(() => readVsix(malo)) === 'badmanifest'); |
| 278 | const dañado = themeVsix(); |
| 279 | const i = new TextDecoder('latin1').decode(dañado).indexOf('extension/package.json') + 'extension/package.json'.length; |
| 280 | dañado[i + 5] ^= 0xff; // un byte de los datos comprimidos del package.json |
| 281 | ok('zip dañado → código corrupt (con la entrada)', await codigo(() => readVsix(dañado)) === 'corrupt'); |
| 282 | const errores = [{ code: 'noname' }, { code: 'badmanifest', message: 'Unexpected end of JSON input' }, { code: 'notfound' }, { code: 'http', status: 503 }, |
| 283 | { code: 'big', mb: 130 }, { code: 'mismatch', got: 'a.b', want: 'c.d' }, { code: 'corrupt', entry: 'extension/x.json' }, { code: 'missing' }, |
| 284 | { code: 'unreadable', warning: roto.warnings[0] }, { code: 'blocked' }, { name: 'QuotaExceededError' }, { code: 'rate' }, { code: 'sha' }, |
| 285 | { code: 'nothing' }, { code: 'notvsix' }, { code: 'cancel' }]; |
| 286 | const textos = errores.map(textoError); |
| 287 | const español = /\b(sin|respondió|demasiado|paquete|versión|incorrecto|soportad|fichero|está|dice ser)\b/i; |
| 288 | ok('errores: todos con su texto en inglés, ninguno en español ni con «Could not do it»', textos.every(t => t && !español.test(t) && !/Could not do it/.test(t)), textos.filter(t => español.test(t) || /Could not do it/.test(t)).join(' | ')); |
| 289 | ok('errores: el detalle útil se conserva (estado HTTP, entrada, ids)', textos[3].includes('503') && textos[6].includes('extension/x.json') && textos[5].includes('a.b') && textos[5].includes('c.d'), textos.slice(3, 7).join(' | ')); |
| 290 | const faltan = l => Object.keys(STRINGS.en).filter(k => !(k in STRINGS[l])).concat(Object.keys(STRINGS[l]).filter(k => !(k in STRINGS.en))); |
| 291 | ok('textos del panel: ES y EN con las mismas claves', !faltan('es').length, faltan('es').join(' ')); |
| 292 | } |
| 293 | |
| 294 | // ── veredicto en llano (verdict.js) y textos sin jerga ── |
| 295 | { |
| 296 | const JERGA = /contributes|customEditors|extension host|host de extensiones|main\/browser|activationEvents|\bMonaco\b/i; |
| 297 | const malos = Object.entries(STRINGS).flatMap(([l, t]) => Object.entries(t).filter(([, v]) => JERGA.test(v)).map(([k]) => `${l}.${k}`)); |
| 298 | ok('textos del panel: ningún término interno (contributes, customEditors, main/browser, host…)', !malos.length, malos.join(' ')); |
| 299 | // como la extensión real de vista previa: código + editores propios + 2 lenguajes sin colores |
| 300 | const prev = veredicto({ hasCode: true, browserEntry: false, categories: ['Visualization', 'Other'], sizes: { languages: 2, commands: 9, customEditors: 8, menus: 3, configuration: 2 }, |
| 301 | ignored: [{ key: 'commands' }, { key: 'customEditors' }, { key: 'menus' }, { key: 'configuration' }], themes: [], highlight: [], settingsOnly: [], snippets: [] }); |
| 302 | ok('veredicto: solo código → no se ofrece instalar, y sin prometer «la siguiente versión» (editores propios)', prev.kind === 'code' && prev.button.disabled && prev.future === 'never' && !/next version/i.test(prev.verdict + prev.lines.join(' ')), JSON.stringify(prev)); |
| 303 | ok('veredicto: dice lo principal en llano («its own previews»)', /its own previews/.test(prev.verdict) && !JERGA.test(prev.verdict + prev.lines.join(' ')), prev.verdict); |
| 304 | const fmt = veredicto({ hasCode: true, browserEntry: true, categories: ['Formatters'], sizes: { commands: 2, configuration: 3 }, ignored: [{ key: 'commands' }, { key: 'configuration' }, { key: 'jsonValidation' }], themes: [], highlight: [], settingsOnly: [], snippets: [] }); |
| 305 | ok('veredicto: formateador con código para el navegador → «llegará con la siguiente versión»', fmt.kind === 'code' && fmt.future === 'next' && /formatting code/.test(fmt.verdict) && /next version/.test(fmt.lines.join(' ')), JSON.stringify(fmt)); |
| 306 | const toml = veredicto({ hasCode: true, browserEntry: true, categories: ['Programming Languages', 'Linters', 'Formatters'], sizes: { grammars: 3, languages: 1, commands: 5, menus: 1, configuration: 2 }, |
| 307 | ignored: [{ key: 'commands' }, { key: 'menus' }, { key: 'configuration' }, { key: 'semanticTokenTypes' }], themes: [], highlight: [{ id: 'toml', name: 'TOML', exts: ['.toml'] }], settingsOnly: [], snippets: [] }); |
| 308 | ok('veredicto: lenguaje + código → funciona en parte, nombra TOML, botón «solo el resaltado»', toml.kind === 'partial' && /TOML/.test(toml.verdict) && toml.button.key === 'installOnlyHighlight' && !toml.button.disabled, JSON.stringify(toml)); |
| 309 | const tema = veredicto({ hasCode: false, categories: ['Themes'], sizes: { themes: 2 }, ignored: [], themes: ['Dracula', 'Dracula Soft'], highlight: [], settingsOnly: [], snippets: [] }); |
| 310 | ok('veredicto: solo temas → «Works in Code» con los nombres y botón Instalar', tema.kind === 'full' && /Dracula/.test(tema.verdict) && tema.button.key === 'install', JSON.stringify(tema)); |
| 311 | const taller = veredicto({ hasCode: true, browserEntry: false, categories: ['Programming Languages', 'Snippets', 'Linters'], sizes: { commands: 46, views: 1, customEditors: 1, grammars: 16 }, webviews: true, |
| 312 | ignored: [{ key: 'commands' }, { key: 'views' }, { key: 'customEditors' }], themes: [], highlight: [{ id: 'latex', name: 'LaTeX', exts: ['.tex'] }], settingsOnly: [], snippets: [{ id: 'latex', name: 'LaTeX', count: null }] }); |
| 313 | ok('veredicto: sobre todo código → primero lo que no funciona, luego «Only … would apply», botón secundario', taller.kind === 'mostlyCode' && /does not work in Code/.test(taller.verdict) && /^Only/.test(taller.lines[0]) && /LaTeX/.test(taller.lines[0]) && taller.button.style === 'ghost', JSON.stringify(taller)); |
| 314 | const sinTraducir = veredicto({ hasCode: false, categories: ['Themes'], sizes: { themes: 1 }, ignored: [], themes: ['%themeLabel%'], highlight: [], settingsOnly: [], snippets: [] }); |
| 315 | ok('veredicto: un nombre sin traducir (%clave%) no se enseña: se cuenta', !/%/.test(sinTraducir.verdict) && /a colour theme/.test(sinTraducir.verdict), sinTraducir.verdict); |
| 316 | const nombres = veredicto({ hasCode: true, categories: ['Other'], sizes: { foo: 1 }, ignored: [{ key: 'someNewThing' }], themes: [], highlight: [], settingsOnly: [], snippets: [] }); |
| 317 | ok('veredicto: una contribución desconocida sale como «other features», no con su nombre', !/someNewThing/.test(nombres.verdict + nombres.lines.join(' ')), nombres.verdict); |
| 318 | } |
| 319 | |
| 320 | console.log(fails ? `\n❌ ${fails} FALLO(S)` : '\n✅ EXTENSIONES (Node): vsix, formatos, temas, lenguajes y snippets OK'); |
| 321 | process.exit(fails ? 1 : 0); |