Elffuss BraidHub

utopia-ia/elffuss-code public

main · 8.9 KiBRawPermalink
1// Qué funcionará de una extensión en Elffuss Code, ANTES de instalarla, a
2// partir de su package.json (y del censo en ejecución, tested.json, si la
3// probamos). Lo usa el panel de extensiones para decirlo con honradez:
4//
5// · lo declarativo (nivel 1): temas, gramáticas, snippets, lenguajes, con
6// las mismas reglas que el «Aplica» del panel;
7// · código para el navegador que puede correr en el recinto (nivel 2), y si
8// aquí (navegador, sitio) puede;
9// · «necesita Node»: no está disponible en el navegador;
10// · lo que no aparecerá aquí (vistas, webviews, depurador…);
11// · si la probamos en Code y qué pasó, o que aún no.
12//
13// Es pequeño y no carga nada del recinto: viaja con el panel.
14import { analyzeManifest } from '../ext/vsix.js';
15
16export const VSCODE = '1.138.0';
17
18// Contribuciones que necesitan la interfaz completa de VS Code: aquí no salen.
19export const WORKBENCH = ['views', 'viewsContainers', 'viewsWelcome', 'customEditors', 'notebooks', 'notebookRenderer', 'walkthroughs', 'debuggers',
20 'breakpoints', 'terminal', 'taskDefinitions', 'problemMatchers', 'authentication', 'chatParticipants', 'languageModelTools',
21 'mcpServerDefinitionProviders', 'resourceLabelFormatters', 'statusBarItems', 'remoteHelp', 'typescriptServerPlugins'];
22// Eventos de activación que en Code nunca ocurren
23const NEVER = [/^workspaceContains:/, /^onView:/, /^onWebviewPanel:/, /^onCustomEditor:/, /^onNotebook(Serializer)?:?/, /^onDebug/, /^onTerminalProfile:/,
24 /^onAuthenticationRequest:/, /^onChatParticipant:/, /^onWalkthrough:/, /^onOpenExternalUri:/, /^onFileSystem:/, /^onSearch:/, /^onTaskType:/, /^onRenderer:/];
25
26// ¿satisface 1.138.0 el rango de engines.vscode? (^x.y.z, ~x.y.z, >=x.y.z, x.y.z, *)
27const triple = s => { const m = /^(\d+)\.(\d+|x|\*)(?:\.(\d+|x|\*))?/.exec(s); return m ? [Number(m[1]), m[2] === 'x' || m[2] === '*' ? 0 : Number(m[2]), m[3] === undefined || m[3] === 'x' || m[3] === '*' ? 0 : Number(m[3])] : null; };
28const cmp = (a, b) => a[0] - b[0] || a[1] - b[1] || a[2] - b[2];
29export function engineOk(range, version = VSCODE) {
30 if (typeof range !== 'string' || !range.trim() || range.trim() === '*') return true;
31 const v = triple(version);
32 const r = range.trim().replace(/-[\w.]+$/, '');
33 let m;
34 if ((m = /^\^\s*(.+)$/.exec(r))) { const t = triple(m[1]); return !!t && cmp(v, t) >= 0 && v[0] === t[0]; }
35 if ((m = /^~\s*(.+)$/.exec(r))) { const t = triple(m[1]); return !!t && cmp(v, t) >= 0 && v[0] === t[0] && v[1] === t[1]; }
36 if ((m = /^>=\s*(.+)$/.exec(r))) { const t = triple(m[1]); return !!t && cmp(v, t) >= 0; }
37 const t = triple(r);
38 return t ? cmp(v, t) >= 0 : true; // sin entenderlo, no se bloquea
39}
40
41const arr = v => (Array.isArray(v) ? v : []);
42function settingsCount(conf) {
43 let n = 0;
44 for (const c of [].concat(conf || [])) if (c && typeof c.properties === 'object' && c.properties) n += Object.keys(c.properties).length;
45 return n;
46}
47
48// Opciones: `tested` (el censo en ejecución), `installed` (ids instaladas),
49// `builtinLanguage(id)` y `grammarSkippedFor(lang)` (las mismas reglas que el
50// «Aplica» del panel: el lenguaje de serie de Monaco no se registra otra vez y
51// la gramática de uno de serie sin Monarch no se aplica) y `canRun` (si el
52// nivel 2 puede arrancar en este navegador y sitio).
53export function classify(manifest, { tested = null, installed = new Set(), builtinLanguage = () => false, grammarSkippedFor = () => false, canRun = true } = {}) {
54 const m = manifest && typeof manifest === 'object' ? manifest : {};
55 const c = m.contributes && typeof m.contributes === 'object' ? m.contributes : {};
56 const a = analyzeManifest(m);
57 const id = `${m.publisher}.${m.name}`.toLowerCase();
58 const runtime = typeof m.browser === 'string' ? 'browser' : typeof m.main === 'string' ? 'node' : 'none';
59 const events = arr(m.activationEvents).filter(e => typeof e === 'string');
60 const neverEvents = events.filter(e => NEVER.some(r => r.test(e)));
61 // solo eventos que nunca llegan (y ninguna otra forma de activarse)
62 const startsNever = runtime === 'browser' && events.length > 0 && neverEvents.length === events.length && !arr(c.commands).length && !arr(c.languages).length;
63 const deps = arr(m.extensionDependencies).filter(d => typeof d === 'string').map(d => d.toLowerCase());
64 const unavailable = WORKBENCH.filter(k => c[k] !== undefined && (!Array.isArray(c[k]) || c[k].length) && (typeof c[k] !== 'object' || Object.keys(c[k]).length));
65 // Las APIs propuestas no las enciende Code (ni VS Code fuera de sus
66 // extensiones propias): usarlas falla, pero muchas solo las prueban y
67 // arrancan igual. Es un aviso, no un veto; el censo dice lo que pasó.
68 const apiProposals = arr(m.enabledApiProposals).length;
69 const engine = engineOk(m.engines && m.engines.vscode);
70 const census = tested && tested.results && typeof m.version === 'string' ? tested.results[`${id}@${m.version}`] || null : null;
71 const failed = !!census && ['error', 'install-failed', 'unsupported'].includes(census.state);
72 const started = !!census && census.state === 'active';
73 const reasons = [];
74 if (runtime === 'browser' && !started) {
75 if (!engine) reasons.push('engine');
76 if (startsNever) reasons.push('never');
77 }
78 if (runtime === 'browser' && deps.some(d => !installed.has(d))) reasons.push('deps');
79 if (failed) reasons.push('census');
80 const warnings = runtime === 'browser' && apiProposals ? ['proposals'] : [];
81 // lo declarativo que de verdad se aplicaría aquí (como el «Aplica» del panel)
82 const declarative = {
83 themes: a.applies.themes,
84 grammars: a.grammarLangs.filter(l => !(l && grammarSkippedFor(l))).length,
85 snippets: a.applies.snippets,
86 languages: a.languageList.filter(l => !builtinLanguage(l.id)).length,
87 };
88 const hasDeclarative = Object.values(declarative).some(Boolean);
89 // «puede correr»: entrada de navegador y nada que lo impida de antemano, o
90 // que el censo la vio arrancar. Si faltan dependencias aún puede
91 // instalarse, pero se dice.
92 const eligible = runtime === 'browser' && !failed && (started || (engine && !startsNever));
93 return {
94 id, version: typeof m.version === 'string' ? m.version : '', runtime, engineOk: engine, apiProposals, startsNever, neverEvents,
95 deps: { all: deps, missing: deps.filter(d => !installed.has(d)) }, unavailable, declarative, hasDeclarative, ignored: a.ignored,
96 counts: { commands: arr(c.commands).length, keybindings: arr(c.keybindings).length, settings: settingsCount(c.configuration) },
97 census, eligible, reasons, warnings, canRun: !!canRun,
98 // ¿algo de ella funciona en Code, aquí? (para el filtro)
99 works: hasDeclarative || (eligible && !!canRun),
100 pack: a.pack,
101 };
102}
103
104// Ajustes que escribe el usuario (JSON) contra los que la extensión declara
105// en contributes.configuration: solo claves suyas y del tipo que dice.
106export function contributedSettings(manifest) {
107 const out = Object.create(null); // sin prototipo: «__proto__» no es un ajuste
108 const conf = manifest && manifest.contributes && manifest.contributes.configuration;
109 for (const c of [].concat(conf || [])) {
110 if (!c || typeof c.properties !== 'object' || !c.properties) continue;
111 for (const [k, v] of Object.entries(c.properties)) if (k !== '__proto__' && v && typeof v === 'object') out[k] = v;
112 }
113 return out;
114}
115const typeOf = v => (v === null ? 'null' : Array.isArray(v) ? 'array' : Number.isInteger(v) ? 'integer' : typeof v);
116const fits = (v, t) => t === typeOf(v) || (t === 'number' && typeof v === 'number') || (t === 'integer' && Number.isInteger(v));
117export function validateSettings(manifest, text) {
118 let v;
119 try { v = JSON.parse(String(text ?? '').trim() || '{}'); } catch (e) { return { ok: false, errors: [{ code: 'json', detail: String(e.message || e).slice(0, 200) }] }; }
120 if (!v || typeof v !== 'object' || Array.isArray(v)) return { ok: false, errors: [{ code: 'object' }] };
121 const known = contributedSettings(manifest);
122 const errors = [];
123 for (const [k, x] of Object.entries(v)) {
124 const p = Object.hasOwn(known, k) ? known[k] : null;
125 if (!p) { errors.push({ code: 'unknown', key: k }); continue; }
126 const types = [].concat(p.type || []).filter(t => typeof t === 'string');
127 if (types.length && !types.some(t => fits(x, t))) { errors.push({ code: 'type', key: k, type: types.join(' | ') }); continue; }
128 if (Array.isArray(p.enum) && p.enum.length && !p.enum.some(e => JSON.stringify(e) === JSON.stringify(x))) errors.push({ code: 'enum', key: k, list: p.enum.slice(0, 10).map(e => JSON.stringify(e)).join(', ') });
129 }
130 if (JSON.stringify(v).length > 100000) errors.push({ code: 'big' });
131 return errors.length ? { ok: false, errors } : { ok: true, value: v };
132}
133
134let censo = null;
135export function loadTested() {
136 censo ??= fetch(new URL('./tested.json', import.meta.url), { cache: 'no-cache', credentials: 'same-origin' })
137 .then(r => (r.ok ? r.json() : null)).catch(() => null)
138 .then(j => (j && j.schema === 1 && j.results && typeof j.results === 'object' ? j : null));
139 return censo;
140}