Elffuss BraidHub

utopia-ia/elffuss-code public

main · 16.4 KiBRawPermalink
1// Proveedores de las extensiones, vistos desde la página: por cada
2// «providers.add» del recinto se registra en el Monaco 0.52 de Code un
3// proveedor equivalente que pregunta al recinto (invoke) y reconstruye la
4// respuesta con convert.js. Los modelos de Code son inmemory://, así que el
5// selector de la extensión se traduce: esquemas file/untitled/* valen (se
6// quitan), cualquier otro no se registra, y los patrones se comprueban aquí
7// contra file:///<ruta del proyecto> con un comparador de tiempo lineal.
8import * as convert from './convert.js';
9
10// ── glob en tiempo lineal (sin expresiones regulares que puedan atascarse) ──
11const MAX_BRACES = 64;
12function expandBraces(p) {
13 const out = [];
14 const stack = [p];
15 while (stack.length && out.length < MAX_BRACES) {
16 const x = stack.pop();
17 const i = x.indexOf('{');
18 if (i < 0) { out.push(x); continue; }
19 let depth = 0, j = i;
20 for (; j < x.length; j++) { if (x[j] === '{') depth++; else if (x[j] === '}' && --depth === 0) break; }
21 if (j >= x.length) { out.push(x); continue; }
22 const inner = x.slice(i + 1, j), alts = [];
23 let d = 0, last = 0;
24 for (let k = 0; k < inner.length; k++) {
25 if (inner[k] === '{') d++; else if (inner[k] === '}') d--;
26 else if (inner[k] === ',' && d === 0) { alts.push(inner.slice(last, k)); last = k + 1; }
27 }
28 alts.push(inner.slice(last));
29 for (const a of alts.reverse()) stack.push(x.slice(0, i) + a + x.slice(j + 1));
30 }
31 return out;
32}
33function tokens(p) {
34 const t = [];
35 for (let i = 0; i < p.length; i++) {
36 const c = p[i];
37 if (c === '*') {
38 if (p[i + 1] === '*') { t.push({ k: 'G' }); while (p[i + 1] === '*') i++; }
39 else t.push({ k: 'S' });
40 } else if (c === '?') t.push({ k: 'A' });
41 else if (c === '[') {
42 const j = p.indexOf(']', i + 2);
43 if (j < 0) { t.push({ k: 'L', c }); continue; }
44 let body = p.slice(i + 1, j);
45 const neg = body[0] === '!' || body[0] === '^';
46 if (neg) body = body.slice(1);
47 const ranges = [];
48 for (let k = 0; k < body.length; k++) {
49 if (body[k + 1] === '-' && k + 2 < body.length) { ranges.push([body[k], body[k + 2]]); k += 2; }
50 else ranges.push([body[k], body[k]]);
51 }
52 t.push({ k: 'C', neg, ranges });
53 i = j;
54 } else t.push({ k: 'L', c: c === '\\' ? '/' : c });
55 }
56 return t;
57}
58function run(t, path) {
59 const closure = set => {
60 for (const i of [...set]) for (let k = i; k < t.length && (t[k].k === 'S' || t[k].k === 'G'); k++) set.add(k + 1);
61 return set;
62 };
63 let cur = closure(new Set([0]));
64 for (const ch of path) {
65 const next = new Set();
66 for (const i of cur) {
67 const tok = t[i];
68 if (!tok) continue;
69 if (tok.k === 'G') next.add(i);
70 else if (tok.k === 'S') { if (ch !== '/') next.add(i); }
71 else if (tok.k === 'A') { if (ch !== '/') next.add(i + 1); }
72 else if (tok.k === 'C') { if (ch !== '/' && tok.ranges.some(([a, b]) => ch >= a && ch <= b) !== tok.neg) next.add(i + 1); }
73 else if (tok.c === ch) next.add(i + 1);
74 }
75 if (!next.size) return false;
76 cur = closure(next);
77 }
78 return cur.has(t.length);
79}
80export function globMatch(pattern, path) {
81 if (typeof pattern !== 'string' || pattern.length > 500 || typeof path !== 'string') return false;
82 const p = pattern.replace(/\\/g, '/');
83 return expandBraces(p).some(x => run(tokens(x), path));
84}
85
86// selector del recinto → { languages para Monaco, filtros que se comprueban aquí }
87export function compileSelector(selector) {
88 const filters = [];
89 for (const f of Array.isArray(selector) ? selector : []) {
90 if (!f) continue;
91 if (f.scheme && !['file', 'untitled', '*'].includes(f.scheme)) continue;
92 filters.push({ language: f.language || '*', pattern: f.pattern || null });
93 }
94 const langs = new Set(filters.map(f => f.language));
95 return { filters, monacoSelector: langs.has('*') ? '*' : [...langs], hasLanguage: filters.some(f => f.language !== '*') };
96}
97export function selectorMatches(filters, path, languageId) {
98 const fsPath = '/' + path;
99 return filters.some(f => (f.language === '*' || f.language === languageId) && (!f.pattern || globMatch(f.pattern, fsPath) || globMatch(f.pattern, path)));
100}
101
102export class Features {
103 // call(kind, handle, model, args, token) → valor del recinto, o null si no aplica
104 constructor({ monaco, call, docs, touched = () => {}, release = () => {}, report = () => {} }) {
105 this.monaco = monaco;
106 this.call = call;
107 this.docs = docs;
108 this.touched = touched;
109 this.release = release;
110 this.report = report;
111 this.handles = new Map(); // handle → { kind, dispose }
112 this.specs = new Map(); // handle → lo que mandó el recinto (para volver a registrarlo)
113 this.prefs = new Map(); // id de extensión → { lenguaje: 'builtin' | 'extension' }
114 }
115
116 // Formateador por lenguaje: «de serie» quita el de esa extensión para ese
117 // lenguaje (Monaco elige el más nuevo, así que si no, ganaría la extensión).
118 setPrefs(prefs) {
119 const next = new Map([...prefs].map(([k, v]) => [String(k).toLowerCase(), v || {}]));
120 if (JSON.stringify([...next]) === JSON.stringify([...this.prefs])) return;
121 this.prefs = next;
122 for (const spec of [...this.specs.values()]) if (spec.kind.startsWith('format')) { this.remove(spec.handle); this.add(spec); }
123 }
124 // lenguajes con formateador de cada extensión (para el panel)
125 formatters() {
126 const out = {};
127 for (const s of this.specs.values()) {
128 if (!s.kind.startsWith('format') || typeof s.meta?.extension !== 'string') continue;
129 const id = s.meta.extension.toLowerCase();
130 const langs = (Array.isArray(s.selector) ? s.selector : []).map(f => f && f.language).filter(l => typeof l === 'string' && l !== '*');
131 out[id] = [...new Set([...(out[id] || []), ...langs])].sort();
132 }
133 return out;
134 }
135
136 add(spec) {
137 const { handle, kind, selector, meta = {} } = spec;
138 const { monaco, docs } = this;
139 this.specs.set(handle, spec);
140 const sel = compileSelector(selector);
141 if (!sel.filters.length) { this.report(handle, kind, 'its selector targets documents Code does not have'); return; }
142 if (kind.startsWith('format') && !sel.hasLanguage) { this.report(handle, kind, 'formatters need a language; this one only names file patterns'); return; }
143 if (kind.startsWith('format') && Array.isArray(sel.monacoSelector)) {
144 const pref = this.prefs.get(String(meta.extension || '').toLowerCase()) || {};
145 sel.monacoSelector = sel.monacoSelector.filter(l => pref[l] !== 'builtin');
146 if (!sel.monacoSelector.length) return; // el usuario prefiere el de serie en todos sus lenguajes
147 }
148 const ask = async (k, model, args, token) => {
149 const path = docs.pathOf(model);
150 if (!path || !selectorMatches(sel.filters, path, model.getLanguageId())) return null;
151 return this.call(k, handle, model, args, token);
152 };
153 const pos = p => [p.lineNumber, p.column];
154 const rng = r => [r.startLineNumber, r.startColumn, r.endLineNumber, r.endColumn];
155 const opts = o => ({ tabSize: o?.tabSize, insertSpaces: !!o?.insertSpaces });
156 const L = monaco.languages;
157 const edited = (model, edits) => { if (edits.length) this.touched(model); return edits; };
158 const modelForUri = uri => docs.modelForUri(uri);
159 const uriOf = m => docs.uriOf(m);
160 const strs = (v, n) => (Array.isArray(v) ? v.filter(c => typeof c === 'string' && c.length === 1).slice(0, n) : []);
161 let d;
162 switch (kind) {
163 case 'format':
164 d = L.registerDocumentFormattingEditProvider(sel.monacoSelector, {
165 displayName: typeof meta.displayName === 'string' ? meta.displayName.slice(0, 100) : undefined,
166 provideDocumentFormattingEdits: async (model, o, token) => edited(model, convert.textEdits(monaco, model, (await ask('format', model, { options: opts(o) }, token))?.edits)),
167 });
168 break;
169 case 'formatRange':
170 d = L.registerDocumentRangeFormattingEditProvider(sel.monacoSelector, {
171 displayName: typeof meta.displayName === 'string' ? meta.displayName.slice(0, 100) : undefined,
172 provideDocumentRangeFormattingEdits: async (model, r, o, token) => edited(model, convert.textEdits(monaco, model, (await ask('formatRange', model, { range: rng(r), options: opts(o) }, token))?.edits)),
173 });
174 break;
175 case 'formatOnType': {
176 const chars = strs(meta.triggerCharacters, 20);
177 if (!chars.length) return;
178 d = L.registerOnTypeFormattingEditProvider(sel.monacoSelector, {
179 autoFormatTriggerCharacters: chars,
180 provideOnTypeFormattingEdits: async (model, p, ch, o, token) => edited(model, convert.textEdits(monaco, model, (await ask('formatOnType', model, { position: pos(p), ch, options: opts(o) }, token))?.edits)),
181 });
182 break;
183 }
184 case 'hover':
185 d = L.registerHoverProvider(sel.monacoSelector, {
186 provideHover: async (model, p, token) => convert.hover(monaco, model, await ask('hover', model, { position: pos(p) }, token)),
187 });
188 break;
189 case 'completion': {
190 const resolve = meta.resolve === true;
191 const owners = new WeakMap();
192 d = L.registerCompletionItemProvider(sel.monacoSelector, {
193 triggerCharacters: strs(meta.triggerCharacters, 50),
194 provideCompletionItems: async (model, p, context, token) => {
195 const v = await ask('completion', model, { position: pos(p), triggerKind: context?.triggerKind, triggerCharacter: context?.triggerCharacter }, token);
196 if (!v || !Array.isArray(v.suggestions)) return null;
197 const suggestions = v.suggestions.slice(0, 5000).map(it => convert.completionItem(monaco, model, p, it)).filter(Boolean);
198 for (const s of suggestions) owners.set(s, model);
199 // aceptar una puede meter texto de la extensión en el documento
200 if (suggestions.length) this.touched(model);
201 const hs = suggestions.map(convert.handleOfItem).filter(Number.isSafeInteger);
202 return { suggestions, incomplete: v.incomplete === true, dispose: () => this.release(hs) };
203 },
204 ...(resolve ? {
205 resolveCompletionItem: async (item, token) => {
206 const model = owners.get(item), h = convert.handleOfItem(item);
207 if (!model || model.isDisposed() || !Number.isSafeInteger(h)) return item;
208 const v = await this.call('completion.resolve', handle, model, { item: h }, token);
209 if (!v) return item;
210 const r = convert.completionItem(monaco, model, model.validatePosition({ lineNumber: 1, column: 1 }), { ...v, range: undefined });
211 if (!r) return item;
212 // solo los detalles: lo que se inserta no cambia al resolver
213 return { ...item, detail: r.detail ?? item.detail, documentation: r.documentation ?? item.documentation, additionalTextEdits: r.additionalTextEdits ?? item.additionalTextEdits, command: r.command ?? item.command };
214 },
215 } : {}),
216 });
217 break;
218 }
219 case 'signature':
220 d = L.registerSignatureHelpProvider(sel.monacoSelector, {
221 signatureHelpTriggerCharacters: strs(meta.triggerCharacters, 20),
222 signatureHelpRetriggerCharacters: strs(meta.retriggerCharacters, 20),
223 provideSignatureHelp: async (model, p, token, context) => {
224 const value = convert.signatureHelp(await ask('signature', model, { position: pos(p), triggerKind: context?.triggerKind, triggerCharacter: context?.triggerCharacter, isRetrigger: !!context?.isRetrigger }, token));
225 return value ? { value, dispose() {} } : null;
226 },
227 });
228 break;
229 case 'codeAction': {
230 const resolve = meta.resolve === true;
231 const owners = new WeakMap();
232 d = L.registerCodeActionProvider(sel.monacoSelector, {
233 provideCodeActions: async (model, r, context, token) => {
234 const v = await ask('codeAction', model, { range: rng(r), trigger: context?.trigger, only: context?.only }, token);
235 if (!v || !Array.isArray(v.actions)) return { actions: [], dispose() {} };
236 const actions = v.actions.slice(0, 500).map(a => convert.codeAction(monaco, model, uriOf, a)).filter(Boolean);
237 for (const a of actions) { owners.set(a, model); if (a.edit) this.touched(model); }
238 const hs = actions.map(convert.handleOfItem).filter(Number.isSafeInteger);
239 return { actions, dispose: () => this.release(hs) };
240 },
241 ...(resolve ? {
242 resolveCodeAction: async (action, token) => {
243 const model = owners.get(action), h = convert.handleOfItem(action);
244 if (!model || model.isDisposed() || !Number.isSafeInteger(h)) return action;
245 const v = await this.call('codeAction.resolve', handle, model, { action: h }, token);
246 const r = v && convert.codeAction(monaco, model, uriOf, v);
247 return r ? { ...action, edit: r.edit ?? action.edit, disabled: r.disabled ?? action.disabled, command: r.command ?? action.command } : action;
248 },
249 } : {}),
250 // sin tipos declarados, ninguno: Monaco descartaría el proveedor al pedir «solo arreglos»
251 }, { providedCodeActionKinds: Array.isArray(meta.kinds) && meta.kinds.length ? meta.kinds.filter(k => typeof k === 'string').slice(0, 50) : undefined });
252 break;
253 }
254 case 'symbols':
255 d = L.registerDocumentSymbolProvider(sel.monacoSelector, {
256 displayName: typeof meta.displayName === 'string' ? meta.displayName.slice(0, 100) : undefined,
257 provideDocumentSymbols: async (model, token) => convert.symbols(monaco, model, (await ask('symbols', model, {}, token))?.symbols),
258 });
259 break;
260 case 'definition': case 'declaration': case 'typeDefinition': case 'implementation': {
261 const reg = { definition: 'registerDefinitionProvider', declaration: 'registerDeclarationProvider', typeDefinition: 'registerTypeDefinitionProvider', implementation: 'registerImplementationProvider' }[kind];
262 const method = { definition: 'provideDefinition', declaration: 'provideDeclaration', typeDefinition: 'provideTypeDefinition', implementation: 'provideImplementation' }[kind];
263 d = L[reg](sel.monacoSelector, { [method]: async (model, p, token) => convert.locations(monaco, (await ask(kind, model, { position: pos(p) }, token))?.locations, modelForUri) });
264 break;
265 }
266 case 'references':
267 d = L.registerReferenceProvider(sel.monacoSelector, {
268 provideReferences: async (model, p, context, token) => convert.locations(monaco, (await ask('references', model, { position: pos(p), includeDeclaration: context?.includeDeclaration !== false }, token))?.locations, modelForUri),
269 });
270 break;
271 case 'highlights':
272 d = L.registerDocumentHighlightProvider(sel.monacoSelector, {
273 provideDocumentHighlights: async (model, p, token) => convert.highlights(monaco, model, (await ask('highlights', model, { position: pos(p) }, token))?.highlights),
274 });
275 break;
276 case 'rename':
277 d = L.registerRenameProvider(sel.monacoSelector, {
278 provideRenameEdits: async (model, p, newName, token) => {
279 const w = convert.workspaceEdit(monaco, model, uriOf, await ask('rename', model, { position: pos(p), newName }, token));
280 if (!w.edit) return { edits: [], rejectReason: w.reason || 'nothing to rename' };
281 this.touched(model);
282 return w.edit;
283 },
284 ...(meta.resolve === true ? {
285 resolveRenameLocation: async (model, p, token) => {
286 const v = await ask('rename.resolve', model, { position: pos(p) }, token);
287 if (!v) return null;
288 const r = convert.range(monaco, model, v.range);
289 return r ? { range: r, text: typeof v.text === 'string' ? v.text.slice(0, 1000) : model.getValueInRange(r), rejectReason: typeof v.rejectReason === 'string' ? v.rejectReason.slice(0, 1000) : undefined } : null;
290 },
291 } : {}),
292 });
293 break;
294 default:
295 return;
296 }
297 this.handles.set(handle, { kind, dispose: () => d?.dispose() });
298 }
299
300 remove(handle) {
301 this.specs.delete(handle);
302 const h = this.handles.get(handle);
303 if (!h) return;
304 this.handles.delete(handle);
305 try { h.dispose(); } catch { /* ya fuera */ }
306 }
307
308 kinds() { return [...this.handles.values()].map(h => h.kind); }
309 dispose() { for (const k of [...this.handles.keys()]) this.remove(k); this.specs.clear(); }
310}