diff --git a/plugins/env-checker/README.md b/plugins/env-checker/README.md
new file mode 100644
index 0000000..b557451
--- /dev/null
+++ b/plugins/env-checker/README.md
@@ -0,0 +1,38 @@
+# Env Checker
+
+
+| | |
+|---|---|
+| **Autor** | Pizzy-23 |
+| **Versão** | 0.1.0 |
+| **Licença** | MIT |
+| **Categoria** | Qualidade e testes |
+| **Precisa de** | nada além do BlueScreen |
+| **Código** | [plugins/env-checker](https://github.com/martindevbr/BlueScreen-Plugins/tree/main/plugins/env-checker) |
+
+
+Painel na barra da esquerda para os arquivos `.env*` da raiz do projeto.
+
+## Como usar
+
+- Cada arquivo numa aba (`.env`, `.env.local`, `.env.example`...), com as variáveis e os valores **escondidos**. O olho mostra um de cada vez. Clique no nome para ir à linha no editor.
+- Marca com ● as variáveis que parecem segredo (nome com token, secret, password, api_key... ou valor com cara de chave: `sk-`, `ghp_`, `AKIA`, `xox`, JWT, chave PEM, URL com senha).
+- Avisos:
+ - `.env` **commitado no git** (tire do repositório e troque os segredos);
+ - `.env` fora do `.gitignore`, com o botão **Pôr no .gitignore**;
+ - variáveis que faltam ou sobram em relação ao `.env.example`;
+ - chave repetida;
+ - `.env.example` com segredo de verdade dentro.
+- **Gerar .env.example**: copia o `.env` só com os nomes e os comentários, sem nenhum valor.
+
+Nada sai do PC: ele só lê os arquivos e roda `git check-ignore` e `git ls-files`.
+
+## Autor e licença
+
+Feito por Pizzy-23. Licença MIT (veja o campo `license` do `plugin.json`).
+
+## Histórico de versões
+
+### 0.1.0
+
+- Primeira versão na loja.
diff --git a/plugins/env-checker/icon.svg b/plugins/env-checker/icon.svg
new file mode 100644
index 0000000..88072a4
--- /dev/null
+++ b/plugins/env-checker/icon.svg
@@ -0,0 +1 @@
+
diff --git a/plugins/env-checker/plugin.json b/plugins/env-checker/plugin.json
new file mode 100644
index 0000000..bc75314
--- /dev/null
+++ b/plugins/env-checker/plugin.json
@@ -0,0 +1,18 @@
+{
+ "id": "env-checker",
+ "name": "Env Checker",
+ "description": "Mostra os .env do projeto com os valores escondidos, compara com o .env.example (o que falta, o que sobra), avisa chave repetida, segredo em arquivo de exemplo e .env sem .gitignore ou já commitado no git. Gera o .env.example só com os nomes e acrescenta o .env no .gitignore.",
+ "version": "0.1.0",
+ "author": "Pizzy-23",
+ "license": "MIT",
+ "category": "qualidade",
+ "keywords": [
+ "env",
+ "dotenv",
+ "segredos",
+ "gitignore",
+ "variáveis"
+ ],
+ "icon": "icon.svg",
+ "order": 116
+}
diff --git a/plugins/env-checker/style.css b/plugins/env-checker/style.css
new file mode 100644
index 0000000..437ac48
--- /dev/null
+++ b/plugins/env-checker/style.css
@@ -0,0 +1,20 @@
+.ev-wrap { display: flex; flex-direction: column; height: 100%; min-width: 0; box-sizing: border-box; }
+.ev-top { display: flex; align-items: center; gap: 6px; padding: 8px 10px; border-bottom: 1px solid var(--line); }
+.ev-sp { flex: 1; }
+.ev-body { flex: 1; min-height: 0; overflow: auto; padding: 8px 10px; display: flex; flex-direction: column; gap: 6px; }
+.ev-files { display: flex; gap: 4px; flex-wrap: wrap; }
+.ev-f { background: none; border: 1px solid var(--line-2); border-radius: 12px; color: var(--fg-2); padding: 2px 10px; font: 12px var(--mono); cursor: pointer; display: flex; gap: 6px; }
+.ev-f em { font-style: normal; color: var(--muted); }
+.ev-f.on { background: var(--sel); color: var(--fg); border-color: var(--accent); }
+.ev-n { display: flex; flex-direction: column; gap: 4px; align-items: flex-start; font-size: 12px; line-height: 1.4; padding: 6px 8px; border-radius: 6px; border-left: 3px solid var(--muted); background: var(--panel-2); }
+.ev-n .chip { font-size: 11px; padding: 1px 8px; }
+.ev-bad { border-color: #f85149; } .ev-warn { border-color: #d29922; } .ev-ok { border-color: #3fb950; } .ev-info { border-color: var(--accent-2); }
+.ev-vars { display: flex; flex-direction: column; }
+.ev-v { display: grid; grid-template-columns: minmax(90px, 45%) 1fr auto; gap: 6px; align-items: center; padding: 3px 4px; border-bottom: 1px solid color-mix(in srgb, var(--line) 50%, transparent); font: 12px var(--mono); }
+.ev-v:hover { background: var(--hover); }
+.ev-k { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; cursor: pointer; color: var(--accent-2); }
+.ev-lock { font-style: normal; color: #d29922; margin-left: 4px; font-size: 9px; }
+.ev-val { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--fg-2); }
+.ev-empty { color: var(--muted); }
+.ev-eye { width: 22px; height: 22px; }
+.ev-row { display: flex; gap: 6px; padding-top: 4px; }
diff --git a/plugins/env-checker/ui.js b/plugins/env-checker/ui.js
new file mode 100644
index 0000000..86dcd07
--- /dev/null
+++ b/plugins/env-checker/ui.js
@@ -0,0 +1,141 @@
+// Conferir .env: lê os .env* da raiz do projeto, compara com o .env.example e confere se o git protege os segredos.
+// Os valores ficam mascarados na tela; só um clique no olho mostra um de cada vez.
+const { esc, toast } = bs;
+if (bs.S.remote) return;
+
+const ICON = ' ';
+const EXAMPLES = ['.env.example', '.env.sample', '.env.template', '.env.dist', 'example.env'];
+const SECRET_KEY = /(secret|token|passw|pwd|api[_-]?key|private|credential|auth|dsn|webhook|signing|salt)/i;
+const SECRET_VAL = [/^sk-[\w-]{20,}/, /^gh[pousr]_\w{30,}/, /^github_pat_/, /^AKIA[0-9A-Z]{16}$/, /^xox[abposr]-/, /^AIza[\w-]{30,}/, /-----BEGIN [A-Z ]*PRIVATE KEY/, /^eyJ[\w-]+\.[\w-]+\./, /:\/\/[^:\s/]+:[^@\s]+@/];
+const E = { files: null, sel: null, err: null, shown: new Set(), git: {} };
+
+function parse(text) {
+ const vars = [], dup = new Set(), seen = new Set();
+ text.replace(/\r/g, '').split('\n').forEach((raw, i) => {
+ const m = raw.match(/^\s*(?:export\s+)?([A-Za-z_][\w.-]*)\s*=\s*(.*)$/); if (!m) return;
+ let v = m[2].trim();
+ if (/^(['"`]).*\1$/.test(v)) v = v.slice(1, -1);
+ else v = v.replace(/\s+#.*$/, '');
+ if (seen.has(m[1])) dup.add(m[1]); seen.add(m[1]);
+ vars.push({ key: m[1], value: v, line: i + 1 });
+ });
+ return { vars, dup };
+}
+const looksSecret = (k, v) => !!v && (SECRET_KEY.test(k) || SECRET_VAL.some(r => r.test(v)));
+const mask = (v) => !v ? 'vazio ' : '•'.repeat(Math.min(12, Math.max(4, v.length)));
+
+async function git(args) {
+ const r = await plugin.exec('git', args, { cwd: bs.S.project.path, timeout: 10000 }).catch(() => null);
+ return r ? r.code : -1;
+}
+
+async function load() {
+ E.err = null; E.files = null; draw();
+ if (!bs.S.project) { E.files = []; draw(); return; }
+ try {
+ const r = await plugin.exec('powershell', ['-NoProfile', '-NonInteractive', '-Command',
+ "Get-ChildItem -LiteralPath $env:EV_DIR -Force -File | Where-Object { $_.Name -like '.env*' -or $_.Name -like '*.env' } | ForEach-Object { $_.Name }"],
+ { env: { EV_DIR: bs.S.project.path }, timeout: 10000 });
+ const names = r.out.split(/\r?\n/).map(s => s.trim()).filter(Boolean).sort((a, b) => (a === '.env' ? -1 : b === '.env' ? 1 : a.localeCompare(b)));
+ const files = [];
+ for (const name of names) {
+ const content = (await bs.api('file', { project: bs.S.project.path, file: name }).catch(() => ({ content: '' }))).content || '';
+ files.push({ name, example: EXAMPLES.includes(name.toLowerCase()), ...parse(content) });
+ }
+ E.files = files;
+ E.sel = files.find(f => f.name === E.sel)?.name || files.find(f => !f.example)?.name || files[0]?.name || null;
+ // git: ignorado? já foi commitado? (ls-files sai 0 quando o arquivo está no índice)
+ E.git = {};
+ if (await git(['rev-parse', '--is-inside-work-tree']) === 0) {
+ for (const f of files.filter(f => !f.example)) E.git[f.name] = { ignored: await git(['check-ignore', '-q', f.name]) === 0, tracked: await git(['ls-files', '--error-unmatch', f.name]) === 0 };
+ } else E.git = null;
+ } catch (e) { E.err = e.message; }
+ draw();
+}
+
+function findings(f) {
+ const out = [], ex = E.files.find(x => x.example);
+ if (!f.example && E.git) {
+ const g = E.git[f.name] || {};
+ if (g.tracked) out.push(['bad', `${f.name} está commitado no git. Tire do repositório (git rm --cached ${f.name}) e troque os segredos que estavam nele.`]);
+ else if (!g.ignored) out.push(['warn', `${f.name} não está no .gitignore: um "git add ." leva os segredos junto.`, 'ignore']);
+ else out.push(['ok', `${f.name} está no .gitignore.`]);
+ }
+ if (f.dup.size) out.push(['warn', `Chave repetida: ${[...f.dup].join(', ')} (vale a última).`]);
+ if (!f.example && ex) {
+ const have = new Set(f.vars.map(v => v.key)), want = new Set(ex.vars.map(v => v.key));
+ const miss = [...want].filter(k => !have.has(k)), extra = [...have].filter(k => !want.has(k));
+ if (miss.length) out.push(['warn', `Faltam em ${f.name} (estão no ${ex.name}): ${miss.join(', ')}`]);
+ if (extra.length) out.push(['info', `Não estão no ${ex.name}: ${extra.join(', ')}`, 'example']);
+ }
+ if (!f.example && !ex && f.vars.length) out.push(['info', 'Sem .env.example: quem clonar o projeto não sabe quais variáveis preencher.', 'example']);
+ if (f.example) {
+ const leaked = f.vars.filter(v => v.value && SECRET_VAL.some(r => r.test(v.value)));
+ if (leaked.length) out.push(['bad', `${f.name} parece ter segredos de verdade (${leaked.map(v => v.key).join(', ')}). Ele costuma ir para o git.`]);
+ }
+ return out;
+}
+
+function draw() {
+ const el = bs.$('#toolBody .ev-wrap'); if (!el) return;
+ const body = el.querySelector('.ev-body');
+ if (E.err) { body.innerHTML = `
${esc(E.err)}
`; return; }
+ if (!E.files) { body.innerHTML = '
'; return; }
+ if (!bs.S.project) { body.innerHTML = 'Abra um projeto.
'; return; }
+ if (!E.files.length) { body.innerHTML = 'Nenhum .env na raiz do projeto.
'; return; }
+ const f = E.files.find(x => x.name === E.sel) || E.files[0];
+ const tabs = E.files.map(x => `${esc(x.name)}${x.vars.length} `).join('');
+ const notes = findings(f).map(([lvl, msg, fix]) => `${esc(msg)} ${fix === 'ignore' ? 'Pôr no .gitignore ' : fix === 'example' ? 'Gerar .env.example ' : ''}
`).join('');
+ const rows = f.vars.map(v => {
+ const sec = looksSecret(v.key, v.value), id = f.name + '\n' + v.key, show = E.shown.has(id) || f.example && !sec;
+ return `${esc(v.key)}${sec ? '● ' : ''}
+ ${show ? (v.value ? esc(v.value) : 'vazio ') : mask(v.value)}
+ ${v.value && !(f.example && !sec) ? `${show ? '◉' : '◎'} ` : ''}
`;
+ }).join('');
+ body.innerHTML = `${tabs}
${notes}${rows || '
Sem variáveis.
'}
+ Abrir ${esc(f.name)}
`;
+}
+
+async function fix(kind, btn) {
+ const project = bs.S.project.path;
+ btn.disabled = true;
+ try {
+ if (kind === 'ignore') {
+ let cur = null; try { cur = (await bs.api('file', { project, file: '.gitignore' })).content; } catch {}
+ const add = '\n# segredos locais\n.env\n.env.*\n!' + EXAMPLES.join('\n!') + '\n';
+ if (cur == null) await bs.api('file/new', { project }, { method: 'POST', body: JSON.stringify({ path: '.gitignore', content: add.trimStart() }) });
+ else await bs.api('file', { project, file: '.gitignore' }, { method: 'PUT', body: cur.replace(/\s*$/, '\n') + add });
+ toast('.gitignore atualizado', 'ok');
+ } else {
+ const f = E.files.find(x => x.name === E.sel); const ex = E.files.find(x => x.example);
+ const target = ex?.name || '.env.example';
+ const text = (await bs.api('file', { project, file: f.name })).content.replace(/\r/g, '').split('\n')
+ .map(l => l.replace(/^(\s*(?:export\s+)?[A-Za-z_][\w.-]*\s*=).*$/, '$1')).join('\n');
+ if (ex) {
+ if (!btn.dataset.sure) { btn.dataset.sure = '1'; btn.textContent = `Sobrescrever ${target}?`; btn.disabled = false; return; }
+ await bs.api('file', { project, file: target }, { method: 'PUT', body: text });
+ } else await bs.api('file/new', { project }, { method: 'POST', body: JSON.stringify({ path: target, content: text }) });
+ toast(`${target} gerado só com os nomes, sem os valores`, 'ok');
+ }
+ } catch (e) { toast(e.message); }
+ load();
+}
+
+function panel(el) {
+ el.innerHTML = `Variáveis de ambiente ${bs.I.refresh}
`;
+ const w = el.querySelector('.ev-wrap');
+ w.querySelector('.ev-ref').onclick = load;
+ w.onclick = (e) => {
+ const t = e.target;
+ const f = t.closest('[data-f]'); if (f) { E.sel = f.dataset.f; draw(); return; }
+ const eye = t.closest('.ev-eye'); if (eye) { const id = eye.dataset.id; E.shown.has(id) ? E.shown.delete(id) : E.shown.add(id); draw(); return; }
+ const fx = t.closest('[data-fix]'); if (fx) return fix(fx.dataset.fix, fx);
+ if (t.closest('.ev-open')) return bs.openFile(E.sel, 'editor');
+ const v = t.closest('.ev-v'); if (v && t.closest('.ev-k')) bs.openFile(E.sel, 'editor', +v.dataset.line);
+ };
+ load();
+}
+
+bs.tools.register({ id: 'conferir-env', title: 'Env Checker', icon: ICON, order: 66, render() { panel(bs.$('#toolBody')); } });
+bs.hooks.on('project:select', () => { E.shown.clear(); if (bs.$('#toolBody .ev-wrap')) load(); });
+bs.hooks.on('tab:save', (t) => { if (/(^|\/)\.env|\.env$|\.gitignore$/.test(t?.path || '') && bs.$('#toolBody .ev-wrap')) load(); });
diff --git a/plugins/github-panel/README.md b/plugins/github-panel/README.md
new file mode 100644
index 0000000..8ac99da
--- /dev/null
+++ b/plugins/github-panel/README.md
@@ -0,0 +1,35 @@
+# GitHub Panel
+
+
+| | |
+|---|---|
+| **Autor** | Pizzy-23 |
+| **Versão** | 0.1.0 |
+| **Licença** | MIT |
+| **Categoria** | Integrações |
+| **Precisa de** | nada além do BlueScreen |
+| **Código** | [plugins/github-panel](https://github.com/martindevbr/BlueScreen-Plugins/tree/main/plugins/github-panel) |
+
+
+Painel **GitHub** na barra da esquerda com o repositório do projeto aberto, tudo pelo [GitHub CLI](https://cli.github.com) (`gh`). Ele usa o login que o `gh` já tem: nenhum token fica guardado aqui.
+
+## Como usar
+
+- **PRs** abertos, **Meus** (os seus, inclusive os fechados), **Issues** e **Actions**.
+- Cada PR mostra se é rascunho, a revisão (aprovado, pediu mudanças) e os checks (✓ 5/5, ✕ falhando, ● rodando).
+- Ações ao passar o mouse: **Abrir** no navegador, **Checkout** (pede um segundo clique), **Diff** colorido ali mesmo.
+- Actions que falharam: **Log do erro** (só os passos que falharam) e **Rodar de novo**.
+- Barra de status: o PR do branch atual e o estado dos checks, atualizado a cada 5 minutos. Clique para abrir.
+- Buscar em tudo: abrir o repositório e criar PR do branch atual no navegador.
+
+Precisa do `gh` instalado e com login (`gh auth login`).
+
+## Autor e licença
+
+Feito por Pizzy-23. Licença MIT (veja o campo `license` do `plugin.json`).
+
+## Histórico de versões
+
+### 0.1.0
+
+- Primeira versão na loja.
diff --git a/plugins/github-panel/icon.svg b/plugins/github-panel/icon.svg
new file mode 100644
index 0000000..644c4d1
--- /dev/null
+++ b/plugins/github-panel/icon.svg
@@ -0,0 +1 @@
+
diff --git a/plugins/github-panel/plugin.json b/plugins/github-panel/plugin.json
new file mode 100644
index 0000000..689d5cc
--- /dev/null
+++ b/plugins/github-panel/plugin.json
@@ -0,0 +1,19 @@
+{
+ "id": "github-panel",
+ "name": "GitHub Panel",
+ "description": "PRs, issues e Actions do repositório do projeto aberto, pelo GitHub CLI (gh) que você já usa, sem token novo. Estado dos checks de cada PR, o PR do branch atual na barra de status, abrir no navegador e fazer checkout de um PR.",
+ "version": "0.1.0",
+ "author": "Pizzy-23",
+ "license": "MIT",
+ "category": "integracoes",
+ "keywords": [
+ "github",
+ "gh",
+ "pull request",
+ "issues",
+ "actions",
+ "ci"
+ ],
+ "icon": "icon.svg",
+ "order": 111
+}
diff --git a/plugins/github-panel/style.css b/plugins/github-panel/style.css
new file mode 100644
index 0000000..f51bfdd
--- /dev/null
+++ b/plugins/github-panel/style.css
@@ -0,0 +1,25 @@
+.gh-wrap { display: flex; flex-direction: column; gap: 6px; padding: 8px 10px; height: 100%; box-sizing: border-box; min-width: 0; }
+.gh-top { display: flex; align-items: center; gap: 6px; }
+.gh-repo { font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.gh-sp { flex: 1; }
+.gh-tabs { display: flex; gap: 2px; border-bottom: 1px solid var(--line); }
+.gh-tab { background: none; border: 0; border-bottom: 2px solid transparent; color: var(--fg-2); padding: 4px 8px; cursor: pointer; font: inherit; font-size: 12px; }
+.gh-tab.on { color: var(--fg); border-bottom-color: var(--accent); }
+.gh-q { background: var(--bg); color: var(--fg); border: 1px solid var(--line-2); border-radius: 4px; padding: 4px 8px; font: inherit; }
+.gh-list { flex: 1; min-height: 0; overflow: auto; display: flex; flex-direction: column; gap: 2px; }
+.gh-row { padding: 6px; border-radius: 6px; display: flex; flex-direction: column; gap: 3px; }
+.gh-row:hover { background: var(--hover); }
+.gh-l1 { display: flex; gap: 6px; align-items: baseline; min-width: 0; }
+.gh-num { color: var(--muted); font-size: 12px; flex: none; }
+.gh-title { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.gh-l2 { display: flex; gap: 5px; align-items: center; flex-wrap: wrap; font-size: 11px; }
+.gh-meta { color: var(--muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; min-width: 0; }
+.gh-tag { --gh-c: var(--muted); border: 1px solid color-mix(in srgb, var(--gh-c) 60%, transparent); color: var(--fg-2); background: color-mix(in srgb, var(--gh-c) 18%, transparent); border-radius: 10px; padding: 0 6px; }
+.gh-chk { font-weight: 600; font-size: 11px; flex: none; }
+.gh-good { color: #3fb950; --gh-c: #3fb950; } .gh-bad { color: #f85149; --gh-c: #f85149; } .gh-wait { color: #d29922; --gh-c: #d29922; } .gh-mute { color: var(--muted); }
+.gh-acts { display: none; gap: 4px; }
+.gh-row:hover .gh-acts, .gh-row:has(.gh-detail) .gh-acts { display: flex; }
+.gh-acts .chip { font-size: 11px; padding: 1px 8px; }
+.gh-detail { margin: 4px 0 0; max-height: 360px; overflow: auto; background: var(--bg); border: 1px solid var(--line); border-radius: 4px; padding: 6px; font-size: 11px; white-space: pre; }
+.gh-detail i { font-style: normal; }
+.gh-add { color: #3fb950; } .gh-del { color: #f85149; } .gh-hunk { color: var(--accent-2); }
diff --git a/plugins/github-panel/ui.js b/plugins/github-panel/ui.js
new file mode 100644
index 0000000..5e35059
--- /dev/null
+++ b/plugins/github-panel/ui.js
@@ -0,0 +1,172 @@
+// GitHub do projeto: tudo pelo gh, que já tem o login do usuário (sem token guardado aqui).
+const { esc, toast } = bs;
+if (bs.S.remote) return;
+
+const ICON = ' ';
+const TABS = { prs: 'PRs', mine: 'Meus', issues: 'Issues', runs: 'Actions' };
+const G = { tab: 'prs', repo: null, data: {}, err: null, loading: false, key: null };
+
+async function gh(args, timeout = 30000) {
+ if (!bs.S.project) throw new Error('Abra um projeto');
+ const r = await plugin.exec('gh', args, { cwd: bs.S.project.path, timeout });
+ if (!r.ok) {
+ const e = (r.err || r.out || '').trim();
+ if (/not a git repository|no git remotes|none of the git remotes/i.test(e)) throw new Error('Este projeto não tem um repositório do GitHub como remoto.');
+ if (/auth login|not logged/i.test(e)) throw new Error('O gh está sem login. Rode "gh auth login" no terminal.');
+ throw new Error(e.split(/\r?\n/).slice(-3).join(' ') || `gh saiu com o código ${r.code}`);
+ }
+ return r.out;
+}
+const ghJson = async (args) => JSON.parse(await gh(args) || 'null');
+
+// statusCheckRollup mistura CheckRun (status/conclusion) e StatusContext (state)
+function checks(roll) {
+ const c = { ok: 0, fail: 0, wait: 0 };
+ for (const x of roll || []) {
+ const v = String(x.conclusion || x.state || '').toUpperCase(), st = String(x.status || '').toUpperCase();
+ if (st && st !== 'COMPLETED') c.wait++;
+ else if (['SUCCESS', 'NEUTRAL', 'SKIPPED'].includes(v)) c.ok++;
+ else if (['PENDING', 'EXPECTED', ''].includes(v)) c.wait++;
+ else c.fail++;
+ }
+ return c;
+}
+function checksHtml(roll) {
+ const c = checks(roll); if (!c.ok && !c.fail && !c.wait) return '';
+ const cls = c.fail ? 'gh-bad' : c.wait ? 'gh-wait' : 'gh-good';
+ const sym = c.fail ? '✕' : c.wait ? '●' : '✓';
+ return `${sym} ${c.ok}/${c.ok + c.fail + c.wait} `;
+}
+function ago(iso) {
+ const m = Math.round((Date.now() - new Date(iso)) / 60000);
+ if (m < 1) return 'agora'; if (m < 60) return m + ' min'; if (m < 1440) return Math.round(m / 60) + ' h';
+ const d = Math.round(m / 1440); return d < 45 ? d + ' d' : new Date(iso).toLocaleDateString('pt-BR');
+}
+const REVIEW = { APPROVED: ['aprovado', 'gh-good'], CHANGES_REQUESTED: ['pediu mudanças', 'gh-bad'], REVIEW_REQUIRED: ['falta revisão', 'gh-wait'] };
+const RUN = { success: ['✓', 'gh-good'], failure: ['✕', 'gh-bad'], cancelled: ['⊘', 'gh-mute'], skipped: ['⊘', 'gh-mute'], action_required: ['!', 'gh-wait'] };
+
+const LOAD = {
+ prs: () => ghJson(['pr', 'list', '--limit', '40', '--json', 'number,title,author,headRefName,isDraft,reviewDecision,statusCheckRollup,updatedAt']),
+ mine: () => ghJson(['pr', 'list', '--author', '@me', '--state', 'all', '--limit', '30', '--json', 'number,title,author,headRefName,isDraft,reviewDecision,statusCheckRollup,updatedAt,state']),
+ issues: () => ghJson(['issue', 'list', '--limit', '40', '--json', 'number,title,author,labels,updatedAt,comments']),
+ runs: () => ghJson(['run', 'list', '--limit', '25', '--json', 'databaseId,displayTitle,status,conclusion,workflowName,headBranch,createdAt,event']),
+};
+
+function rowPr(p) {
+ const rv = REVIEW[p.reviewDecision];
+ const state = p.state && p.state !== 'OPEN' ? `${p.state === 'MERGED' ? 'merged' : 'fechado'} ` : '';
+ return `
+
#${p.number} ${esc(p.title)}
+
${p.isDraft ? 'rascunho ' : ''}${state}${rv ? `${rv[0]} ` : ''}${checksHtml(p.statusCheckRollup)}
+ ${esc(p.author?.login || '')} · ${esc(p.headRefName)} · ${esc(ago(p.updatedAt))}
+
Abrir Checkout Diff
+
`;
+}
+function rowIssue(i) {
+ const labels = (i.labels || []).map(l => `${esc(l.name)} `).join('');
+ return `
+
#${i.number} ${esc(i.title)}
+
${labels}${esc(i.author?.login || '')} · ${(i.comments || []).length} coment. · ${esc(ago(i.updatedAt))}
+
Abrir
+
`;
+}
+function rowRun(r) {
+ const s = r.status !== 'completed' ? ['●', 'gh-wait'] : RUN[r.conclusion] || ['?', 'gh-mute'];
+ return `
+
${s[0]} ${esc(r.displayTitle)}
+
${esc(r.workflowName)} · ${esc(r.headBranch)} · ${esc(r.event || '')} · ${esc(ago(r.createdAt))}
+
Abrir ${r.conclusion === 'failure' ? 'Log do erro Rodar de novo ' : ''}
+
`;
+}
+
+async function load(force) {
+ const key = bs.S.project?.path;
+ if (key !== G.key) { G.key = key; G.data = {}; G.repo = null; G.err = null; }
+ if (!force && G.data[G.tab]) return draw();
+ G.loading = true; draw();
+ try {
+ G.repo ||= await ghJson(['repo', 'view', '--json', 'nameWithOwner,url,defaultBranchRef']);
+ G.data[G.tab] = await LOAD[G.tab](); G.err = null;
+ } catch (e) { G.err = e.message; }
+ G.loading = false; draw();
+}
+
+function draw() {
+ const el = bs.$('#toolBody .gh-wrap'); if (!el) return;
+ el.querySelector('.gh-repo').textContent = G.repo ? G.repo.nameWithOwner : bs.S.project ? bs.S.project.name : 'sem projeto';
+ el.querySelectorAll('.gh-tab').forEach(b => b.classList.toggle('on', b.dataset.t === G.tab));
+ const list = el.querySelector('.gh-list'), q = el.querySelector('.gh-q').value.toLowerCase();
+ if (G.loading) { list.innerHTML = ' Buscando…
'; return; }
+ if (G.err) { list.innerHTML = `${esc(G.err)}
`; return; }
+ const rows = (G.data[G.tab] || []).filter(x => !q || JSON.stringify([x.title, x.displayTitle, x.number, x.headRefName, x.author?.login]).toLowerCase().includes(q));
+ const fn = G.tab === 'issues' ? rowIssue : G.tab === 'runs' ? rowRun : rowPr;
+ list.innerHTML = rows.length ? rows.map(fn).join('') : 'Nada por aqui.
';
+}
+
+async function act(row, a, btn) {
+ const n = row.dataset.n, kind = row.dataset.kind;
+ try {
+ if (a === 'web') { await gh([kind === 'run' ? 'run' : kind, 'view', n, '--web']); return; }
+ if (a === 'checkout') {
+ if (!btn.dataset.sure) { btn.dataset.sure = '1'; btn.textContent = 'Confirmar?'; toast(`Clique de novo para trocar para o branch ${row.dataset.branch}`); return; }
+ btn.disabled = true; btn.textContent = '…';
+ await gh(['pr', 'checkout', n], 120000);
+ toast(`No branch do PR #${n}`, 'ok'); statusPr();
+ return;
+ }
+ if (a === 'diff') return detail(row, () => gh(['pr', 'diff', n, '--color', 'never']), 'gh-diff');
+ if (a === 'log') return detail(row, () => gh(['run', 'view', n, '--log-failed'], 60000), 'gh-log');
+ if (a === 'rerun') { btn.disabled = true; await gh(['run', 'rerun', n, '--failed']); toast('Rodando de novo os jobs que falharam', 'ok'); setTimeout(() => load(true), 3000); }
+ } catch (e) { toast(e.message); if (btn) btn.disabled = false; }
+}
+async function detail(row, get, cls) {
+ const open = row.querySelector('.gh-detail');
+ if (open) { open.remove(); return; }
+ row.insertAdjacentHTML('beforeend', `Carregando… `);
+ const pre = row.querySelector('.gh-detail');
+ try {
+ const out = await get();
+ pre.innerHTML = cls === 'gh-diff' ? esc(out.slice(0, 300000)).replace(/^(\+(?!\+\+).*)$/gm, '$1 ').replace(/^(-(?!--).*)$/gm, '$1 ').replace(/^(@@.*)$/gm, '$1 ')
+ : esc(out.split(/\r?\n/).slice(-400).join('\n'));
+ } catch (e) { pre.textContent = e.message; }
+}
+
+function panel(el) {
+ el.innerHTML = `
+
${bs.I.refresh}
+
${Object.entries(TABS).map(([k, v]) => `${v} `).join('')}
+
+
+
`;
+ const w = el.querySelector('.gh-wrap');
+ for (const ev of ['keydown', 'keypress', 'keyup']) w.addEventListener(ev, e => { if (e.target.matches('input') && !(e.ctrlKey && e.altKey)) e.stopPropagation(); });
+ w.querySelector('.gh-ref').onclick = () => load(true);
+ w.querySelector('.gh-q').oninput = draw;
+ w.querySelector('.gh-tabs').onclick = e => { const b = e.target.closest('.gh-tab'); if (b) { G.tab = b.dataset.t; load(); } };
+ w.querySelector('.gh-list').onclick = e => { const b = e.target.closest('[data-a]'), row = e.target.closest('.gh-row'); if (b && row) act(row, b.dataset.a, b); };
+ load();
+}
+
+// o PR do branch atual na barra de status
+const st = bs.status.add({ id: 'stGhPr', title: 'PR do branch atual', onclick: () => gh(['pr', 'view', '--web']).catch(e => toast(e.message)) });
+let stTimer = 0;
+async function statusPr() {
+ if (!bs.S.project) { st.hidden = true; return; }
+ try {
+ const p = await ghJson(['pr', 'view', '--json', 'number,state,statusCheckRollup,reviewDecision']);
+ const c = checks(p.statusCheckRollup);
+ st.textContent = `PR #${p.number} ${c.fail ? '✕' : c.wait ? '●' : c.ok ? '✓' : ''}`.trim();
+ st.title = `PR #${p.number} (${p.state.toLowerCase()}) · checks: ${c.ok} ok, ${c.fail} falhando, ${c.wait} rodando · clique para abrir`;
+ st.hidden = false;
+ } catch { st.hidden = true; }
+}
+bs.hooks.on('project:select', () => { clearTimeout(stTimer); stTimer = setTimeout(statusPr, 1500); G.key = null; if (bs.$('#toolBody .gh-wrap')) load(); });
+const poll = setInterval(() => { if (document.visibilityState === 'visible') statusPr(); }, 5 * 60000);
+plugin.onUnload(() => { clearInterval(poll); clearTimeout(stTimer); });
+setTimeout(statusPr, 3000);
+
+bs.tools.register({ id: 'gh-projeto', title: 'GitHub', icon: ICON, order: 63, render() { panel(bs.$('#toolBody')); } });
+bs.actions.add([
+ { label: 'GitHub: abrir o repositório no navegador', icon: ICON, run: () => gh(['repo', 'view', '--web']).catch(e => toast(e.message)) },
+ { label: 'GitHub: criar PR do branch atual (no navegador)', icon: ICON, run: () => gh(['pr', 'create', '--web']).catch(e => toast(e.message)) },
+]);
diff --git a/plugins/hex-inspector/README.md b/plugins/hex-inspector/README.md
new file mode 100644
index 0000000..84e6d39
--- /dev/null
+++ b/plugins/hex-inspector/README.md
@@ -0,0 +1,35 @@
+# Hex Inspector
+
+
+| | |
+|---|---|
+| **Autor** | Pizzy-23 |
+| **Versão** | 0.1.0 |
+| **Licença** | MIT |
+| **Categoria** | Desenvolvimento |
+| **Precisa de** | nada além do BlueScreen |
+| **Código** | [plugins/hex-inspector](https://github.com/martindevbr/BlueScreen-Plugins/tree/main/plugins/hex-inspector) |
+
+
+Toma o lugar do visualizador hexadecimal da IDE nos binários (`.exe`, `.dll`, `.bin`, `.dat`, `.pak`, arquivos sem extensão conhecida...). Feito para ler formatos de jogos e de programas.
+
+## Como usar
+
+- **O arquivo inteiro**: rola do começo ao fim, mesmo com vários GB. Ele lê só os pedaços que estão na tela.
+- **Seleção**: clique, arraste, Shift+clique ou Shift+setas. `Ctrl+C` (ou **Copiar hex**) copia em hexadecimal. Setas, PageUp/PageDown, Home/End e Ctrl+Home/Ctrl+End navegam.
+- **Inspetor** do byte selecionado: bits, u8/i8, u16, i16, u32, i32, u64, i64, f16, f32, f64, ASCII e UTF-16LE, em little ou big-endian. Clique num valor para copiar.
+- **Ir para**: `0x1A2B`, `1A2Bh` ou decimal, e Enter.
+- **Buscar** texto, bytes em hex (`4D 5A 90 00`) ou texto UTF-16, a partir da seleção e dando a volta no arquivo.
+- **Formato detectado** na barra: PE, ELF, ZIP, PNG, DDS, KTX, glb, FBX, UnityFS, GVAS (save do Unreal), CR2W, Wwise (BKHD/AKPK), FMOD (FSB5), BND4/BHD5, gzip, zstd, LZ4, zlib, SQLite e mais.
+
+Só leitura. Desligar o plugin devolve o hexadecimal original.
+
+## Autor e licença
+
+Feito por Pizzy-23. Licença MIT (veja o campo `license` do `plugin.json`).
+
+## Histórico de versões
+
+### 0.1.0
+
+- Primeira versão na loja.
diff --git a/plugins/hex-inspector/icon.svg b/plugins/hex-inspector/icon.svg
new file mode 100644
index 0000000..2e6d504
--- /dev/null
+++ b/plugins/hex-inspector/icon.svg
@@ -0,0 +1 @@
+4D 5A 90 00
diff --git a/plugins/hex-inspector/plugin.json b/plugins/hex-inspector/plugin.json
new file mode 100644
index 0000000..e9f8089
--- /dev/null
+++ b/plugins/hex-inspector/plugin.json
@@ -0,0 +1,18 @@
+{
+ "id": "hex-inspector",
+ "name": "Hex Inspector",
+ "description": "Hexadecimal feito para engenharia reversa: rola arquivos de vários GB, seleção com mouse e teclado, inspetor de tipos (u8 a u64, f16 a f64, little ou big-endian, ASCII, UTF-16), ir para offset, busca de texto ou bytes e detecção de formato (PE, Unity, Wwise, DDS, GVAS...).",
+ "version": "0.1.0",
+ "author": "Pizzy-23",
+ "license": "MIT",
+ "category": "desenvolvimento",
+ "keywords": [
+ "hex",
+ "binário",
+ "engenharia reversa",
+ "inspetor",
+ "formato"
+ ],
+ "icon": "icon.svg",
+ "order": 112
+}
diff --git a/plugins/hex-inspector/style.css b/plugins/hex-inspector/style.css
new file mode 100644
index 0000000..e3e3a63
--- /dev/null
+++ b/plugins/hex-inspector/style.css
@@ -0,0 +1,23 @@
+.vw-hexi { display: flex; flex-direction: column; height: 100%; min-height: 0; }
+.vw-hexi .vw-bar { flex-wrap: wrap; gap: 4px; }
+.hx-in { background: var(--bg); color: var(--fg); border: 1px solid var(--line-2); border-radius: 4px; padding: 2px 6px; font: inherit; font-size: 12px; }
+.hx-goto { width: 150px; } .hx-find { width: 170px; }
+.hx-main { flex: 1; min-height: 0; display: flex; }
+.hx-view { flex: 1; min-width: 0; position: relative; overflow: auto; outline: none; font-family: var(--mono); font-size: 13px; cursor: text; user-select: none; }
+.hx-rows { position: absolute; top: 0; left: 0; right: 0; padding: 0 12px; will-change: transform; }
+.hx-spacer { width: 1px; }
+.hx-r { height: 18px; line-height: 18px; white-space: pre; display: flex; gap: 18px; }
+.hx-o { color: var(--muted); }
+.hx-h b, .hx-a b { font-weight: normal; }
+.hx-h b { padding: 0 3px; }
+.hx-h b:nth-child(8) { margin-right: 8px; }
+.hx-h b.z { color: var(--muted); }
+.hx-a { color: var(--fg-2); }
+.hx-h b.s, .hx-a b.s { background: var(--sel); color: var(--fg); outline: 1px solid var(--accent); }
+.hx-side { width: 250px; flex: none; border-left: 1px solid var(--line); padding: 8px; overflow: auto; font-size: 12px; display: flex; flex-direction: column; gap: 8px; }
+.hx-endian { display: flex; gap: 4px; } .hx-endian .chip { flex: 1; font-size: 11px; }
+.hx-ins { display: grid; grid-template-columns: auto 1fr; gap: 3px 8px; }
+.hx-k { color: var(--muted); }
+.hx-v { font-family: var(--mono); overflow-wrap: anywhere; cursor: copy; }
+.hx-v:hover { color: var(--accent-2); }
+.hx-help { color: var(--muted); font-size: 11px; line-height: 1.4; }
diff --git a/plugins/hex-inspector/ui.js b/plugins/hex-inspector/ui.js
new file mode 100644
index 0000000..6091627
--- /dev/null
+++ b/plugins/hex-inspector/ui.js
@@ -0,0 +1,259 @@
+// Hex com inspetor: toma o lugar do hexadecimal do visualizador de arquivos (o embutido lê 64 KB por vez e só mostra).
+// O arquivo é lido em pedaços de 64 KB por /api/raw (Range), conforme a rolagem; só as linhas visíveis existem na página,
+// então um arquivo de vários GB abre na hora. Só leitura.
+const FV = bs.fileViewer; if (!FV) return;
+const { esc, toast } = bs;
+const KIND = 'hexi', CH = 65536, RH = 18, MAXPX = 8e6, MAX_CHUNKS = 160;
+
+// o núcleo abre binários com o tipo 'hex' por BS.fileViewer.open: desviar aqui basta, e desligar o plugin devolve o embutido
+const origOpen = FV.open;
+FV.open = (path, kind, line) => origOpen(path, kind === 'hex' ? KIND : kind, line);
+FV.labels[KIND] = 'binário';
+
+const SIGS = [
+ [0, 'MZ', 'Executável Windows (PE/DOS)'], [0, '\x7fELF', 'Executável ELF'], [0, 'PK\x03\x04', 'ZIP (também jar, apk, docx, pak de alguns jogos)'],
+ [0, '\x89PNG', 'Imagem PNG'], [0, '\xff\xd8\xff', 'Imagem JPEG'], [0, 'GIF8', 'Imagem GIF'], [0, 'BM', 'Imagem BMP'], [0, 'DDS ', 'Textura DDS'],
+ [0, '\xabKTX', 'Textura KTX'], [0, 'glTF', 'Modelo glTF binário (.glb)'], [0, 'Kaydara FBX Binary', 'Modelo FBX binário'],
+ [0, 'UnityFS', 'Unity AssetBundle (UnityFS)'], [0, 'UnityWeb', 'Unity AssetBundle (UnityWeb)'], [0, 'UnityRaw', 'Unity AssetBundle (UnityRaw)'],
+ [0, 'GVAS', 'Save do Unreal Engine (GVAS)'], [0, 'CR2W', 'Recurso CR2W (REDengine)'], [0, 'BKHD', 'Soundbank do Wwise (.bnk)'], [0, 'AKPK', 'Pacote do Wwise (.pck)'],
+ [0, 'FSB5', 'Banco de sons FMOD (FSB5)'], [0, 'RIFF', 'Contêiner RIFF (WAV, AVI, WEBP...)'], [0, 'OggS', 'Áudio Ogg'], [0, 'fLaC', 'Áudio FLAC'], [0, 'ID3', 'Áudio MP3 (ID3)'],
+ [0, 'SQLite format 3', 'Banco SQLite'], [0, '\x1f\x8b', 'Compactado gzip'], [0, '(\xb5/\xfd', 'Compactado Zstandard'], [0, '\x04"M\x18', 'Compactado LZ4 (frame)'],
+ [0, '7z\xbc\xaf\x27\x1c', 'Compactado 7-Zip'], [0, 'Rar!', 'Compactado RAR'], [0, '\xca\xfe\xba\xbe', 'Classe Java ou Mach-O universal'],
+ [0, '%PDF', 'Documento PDF'], [0, '\0asm', 'WebAssembly'], [0, 'dex\n', 'Android DEX'], [0, '\xd0\xcf\x11\xe0', 'Documento OLE (doc, xls, msi)'],
+ [0, 'MSCF', 'Gabinete CAB'], [0, '\x78\x9c', 'Compactado zlib'], [0, '\x78\xda', 'Compactado zlib (máximo)'], [0, 'BND4', 'Arquivo BND4 (FromSoftware)'], [0, 'BHD5', 'Cabeçalho BHD5 (FromSoftware)'],
+];
+
+const hex2 = (n) => n.toString(16).toUpperCase().padStart(2, '0');
+const hexOff = (n) => n.toString(16).toUpperCase().padStart(8, '0');
+
+// ----- leitura em pedaços -----
+async function fetchRange(t, off, len) {
+ const r = await fetch(FV.url(t, `&offset=${off}&len=${len}`));
+ if (!r.ok) throw new Error((await r.json().catch(() => ({}))).error || r.statusText);
+ const size = +r.headers.get('x-file-size'); if (size >= 0) t.hx.size = size;
+ return new Uint8Array(await r.arrayBuffer());
+}
+function chunk(t, i) {
+ const h = t.hx, c = h.cache.get(i);
+ if (c) { h.cache.delete(i); h.cache.set(i, c); return c; }
+ if (!h.pending.has(i)) {
+ h.pending.set(i, fetchRange(t, i * CH, CH).then(b => {
+ h.cache.set(i, b); h.pending.delete(i);
+ while (h.cache.size > MAX_CHUNKS) h.cache.delete(h.cache.keys().next().value);
+ schedule(t);
+ }).catch(e => { h.pending.delete(i); h.error = e.message; schedule(t); }));
+ }
+ return null;
+}
+const byteAt = (t, o) => { const c = chunk(t, Math.floor(o / CH)); return c ? c[o % CH] : undefined; };
+function bytes(t, o, n) {
+ n = Math.max(0, Math.min(n, t.hx.size - o));
+ const out = new Uint8Array(n);
+ for (let k = 0; k < n; k++) { const b = byteAt(t, o + k); if (b === undefined) return null; out[k] = b; }
+ return out;
+}
+
+// ----- rolagem virtual (acima de MAXPX a barra é proporcional, não 1:1) -----
+const geo = (t) => {
+ const h = t.hx, view = h.view, rows = Math.ceil(h.size / 16) || 1;
+ const vis = Math.max(1, Math.floor(view.clientHeight / RH));
+ return { rows, vis, total: Math.min(rows * RH, MAXPX), max: Math.max(0, rows - vis) };
+};
+function topRow(t) {
+ const g = geo(t), v = t.hx.view, span = Math.max(1, g.total - v.clientHeight);
+ return g.total < MAXPX ? Math.min(g.max, Math.floor(v.scrollTop / RH)) : Math.round(Math.min(1, v.scrollTop / span) * g.max);
+}
+function scrollToRow(t, row) {
+ const g = geo(t), v = t.hx.view, span = Math.max(1, g.total - v.clientHeight);
+ v.scrollTop = g.total < MAXPX ? row * RH : (g.max ? row / g.max : 0) * span;
+}
+function reveal(t, o) {
+ const g = geo(t), row = Math.floor(o / 16), top = topRow(t);
+ if (row < top) scrollToRow(t, row); else if (row >= top + g.vis) scrollToRow(t, row - g.vis + 1);
+}
+
+function schedule(t) { if (t.hx.raf) return; t.hx.raf = requestAnimationFrame(() => { t.hx.raf = 0; draw(t); }); }
+
+function draw(t) {
+ const h = t.hx; if (!h.view?.isConnected) return;
+ const g = geo(t), top = topRow(t);
+ h.spacer.style.height = g.total + 'px';
+ h.rowsEl.style.transform = `translateY(${h.view.scrollTop}px)`;
+ const [a, b] = h.selEnd == null ? [h.sel, h.sel] : [Math.min(h.sel, h.selEnd), Math.max(h.sel, h.selEnd)];
+ let html = '';
+ for (let r = top; r < Math.min(g.rows, top + g.vis + 1); r++) {
+ const o0 = r * 16; let hx = '', as = '';
+ for (let k = 0; k < 16; k++) {
+ const o = o0 + k;
+ if (o >= h.size) { hx += ' '; continue; }
+ const v = byteAt(t, o), cls = (o >= a && o <= b ? 's' : '') + (v === 0 ? ' z' : '');
+ hx += `${v === undefined ? '··' : hex2(v)} `;
+ as += `${v === undefined ? ' ' : v >= 32 && v < 127 ? esc(String.fromCharCode(v)) : '·'} `;
+ }
+ html += `${hexOff(o0)} ${hx} ${as}
`;
+ }
+ h.rowsEl.innerHTML = html;
+ inspect(t);
+ const meta = t.el.querySelector('[data-meta]'); if (meta) meta.textContent = FV.size(h.size) + (h.magic ? ' · ' + h.magic : '');
+ if (h.error) { toast('Hex: ' + h.error); h.error = null; }
+}
+
+// ----- inspetor -----
+function inspect(t) {
+ const h = t.hx, box = h.side.querySelector('.hx-ins'); if (!box) return;
+ const o = h.sel, b = bytes(t, o, 8), le = h.le;
+ const sel = h.selEnd == null ? 1 : Math.abs(h.selEnd - h.sel) + 1;
+ let rows = [['Offset', `0x${o.toString(16).toUpperCase()} · ${o.toLocaleString('pt-BR')}`], ['Seleção', `${sel.toLocaleString('pt-BR')} byte${sel > 1 ? 's' : ''}`]];
+ if (b && b.length) {
+ const dv = new DataView(b.buffer), n = b.length, f = (w, fn) => n >= w ? fn() : '—';
+ rows.push(
+ ['bits', b[0].toString(2).padStart(8, '0')],
+ ['u8 / i8', `${b[0]} / ${dv.getInt8(0)}`],
+ ['u16', f(2, () => dv.getUint16(0, le))], ['i16', f(2, () => dv.getInt16(0, le))],
+ ['u32', f(4, () => dv.getUint32(0, le))], ['i32', f(4, () => dv.getInt32(0, le))],
+ ['u64', f(8, () => dv.getBigUint64(0, le).toString())], ['i64', f(8, () => dv.getBigInt64(0, le).toString())],
+ ['f16', f(2, () => half(dv.getUint16(0, le)))],
+ ['f32', f(4, () => num(dv.getFloat32(0, le)))], ['f64', f(8, () => num(dv.getFloat64(0, le)))],
+ );
+ const s = bytes(t, o, 64);
+ if (s) {
+ let a = ''; for (const c of s) { if (c === 0) break; a += c >= 32 && c < 127 ? String.fromCharCode(c) : '·'; }
+ let u = ''; for (let k = 0; k + 1 < s.length; k += 2) { const c = s[k] | s[k + 1] << 8; if (!c) break; u += String.fromCharCode(c); }
+ rows.push(['ASCII', a || '—'], ['UTF-16LE', u || '—']);
+ }
+ }
+ box.innerHTML = rows.map(([k, v]) => `${k}
${esc(String(v))}
`).join('');
+}
+const num = (x) => Number.isFinite(x) && Math.abs(x) > 1e-6 && Math.abs(x) < 1e15 ? +x.toPrecision(9) : x;
+function half(u) {
+ const s = u >> 15 ? -1 : 1, e = u >> 10 & 31, m = u & 1023;
+ if (!e) return s * m * 2 ** -24; if (e === 31) return m ? NaN : s * Infinity;
+ return num(s * (1 + m / 1024) * 2 ** (e - 15));
+}
+
+async function detect(t) {
+ try {
+ const b = await fetchRange(t, 0, 64), s = String.fromCharCode(...b);
+ const hit = SIGS.find(([at, sig]) => s.startsWith(sig, at));
+ let m = hit ? hit[2] : '';
+ if (hit && hit[1] === 'RIFF') m = ({ WAVE: 'Áudio WAV', AVI: 'Vídeo AVI', WEBP: 'Imagem WEBP' })[s.slice(8, 12).trim()] || m;
+ t.hx.magic = m; schedule(t);
+ } catch {}
+}
+
+// ----- ir para, buscar, copiar -----
+function parseOff(s) {
+ s = s.trim().replace(/_/g, ''); if (!s) return null;
+ let m;
+ if ((m = s.match(/^0x([0-9a-f]+)$/i)) || (m = s.match(/^([0-9a-f]+)h$/i)) || (/[a-f]/i.test(s) && (m = s.match(/^([0-9a-f]+)$/i)))) return parseInt(m[1], 16);
+ return /^\d+$/.test(s) ? parseInt(s, 10) : null;
+}
+function select(t, o, extend) {
+ const h = t.hx; o = Math.max(0, Math.min(h.size - 1, o));
+ if (extend) h.selEnd = o; else { h.sel = o; h.selEnd = null; }
+ reveal(t, extend ? o : h.sel); schedule(t);
+}
+function pattern(t) {
+ const q = t.el.querySelector('.hx-find').value, mode = t.el.querySelector('.hx-mode').value;
+ if (!q) return null;
+ if (mode === 'hex') {
+ const clean = q.replace(/[\s,]/g, '');
+ if (!/^([0-9a-f]{2})+$/i.test(clean)) { toast('Hex: use pares, ex.: 4D 5A 90 00'); return null; }
+ return Uint8Array.from(clean.match(/../g).map(x => parseInt(x, 16)));
+ }
+ return mode === 'utf16' ? Uint8Array.from([...q].flatMap(c => [c.charCodeAt(0) & 255, c.charCodeAt(0) >> 8])) : new TextEncoder().encode(q);
+}
+function indexOf(hay, pat, from = 0) {
+ for (let i = hay.indexOf(pat[0], from); i >= 0 && i <= hay.length - pat.length; i = hay.indexOf(pat[0], i + 1)) {
+ let k = 1; while (k < pat.length && hay[i + k] === pat[k]) k++;
+ if (k === pat.length) return i;
+ }
+ return -1;
+}
+async function find(t) {
+ const h = t.hx, pat = pattern(t); if (!pat) return;
+ if (h.searching) { h.searching.stop = true; return; }
+ const btn = t.el.querySelector('.hx-go'), job = h.searching = { stop: false }, STEP = 4 << 20;
+ btn.textContent = 'Parar';
+ const scan = async (from, to) => {
+ for (let o = from; o < to && !job.stop; o += STEP - pat.length + 1) {
+ btn.title = `procurando… ${Math.round(o / h.size * 100)}%`;
+ const b = await fetchRange(t, o, Math.min(STEP, to + pat.length - 1 - o)), i = indexOf(b, pat);
+ if (i >= 0) return o + i;
+ }
+ return -1;
+ };
+ try {
+ const start = (h.selEnd ?? h.sel) + 1;
+ let at = await scan(start, h.size);
+ if (at < 0 && !job.stop && start > 0) at = await scan(0, start);
+ if (job.stop) toast('Busca parada');
+ else if (at < 0) toast('Não achei no arquivo');
+ else { select(t, at); select(t, at + pat.length - 1, true); }
+ } catch (e) { toast('Hex: ' + e.message); }
+ h.searching = null; btn.textContent = 'Buscar'; btn.title = '';
+}
+async function copySel(t) {
+ const h = t.hx, a = h.selEnd == null ? h.sel : Math.min(h.sel, h.selEnd), n = h.selEnd == null ? 1 : Math.abs(h.selEnd - h.sel) + 1;
+ if (n > 1 << 20) { toast('Seleção grande demais para copiar (máx. 1 MB)'); return; }
+ try { const b = await fetchRange(t, a, n); await navigator.clipboard.writeText([...b].map(hex2).join(' ')); toast(`${n} bytes copiados em hex`, 'ok'); }
+ catch (e) { toast(e.message); }
+}
+
+// ----- a aba -----
+FV.custom[KIND] = {
+ build(t, el) {
+ el.innerHTML = FV.bar(t, `
+ texto hex UTF-16
+ Buscar
+ Copiar hex `)
+ + ``;
+ const h = t.hx = { size: 0, cache: new Map(), pending: new Map(), sel: 0, selEnd: null, le: true, magic: '', view: el.querySelector('.hx-view'), rowsEl: el.querySelector('.hx-rows'), spacer: el.querySelector('.hx-spacer'), side: el.querySelector('.hx-side') };
+ el.querySelector('[data-a="reveal"]').onclick = () => FV.act(t, 'reveal');
+ h.view.onscroll = () => schedule(t);
+ h.view.onmousedown = (e) => { const b = e.target.closest('[data-o]'); if (!b) return; e.preventDefault(); h.view.focus(); select(t, +b.dataset.o, e.shiftKey); h.drag = true; };
+ h.view.onmousemove = (e) => { if (!h.drag || !(e.buttons & 1)) { h.drag = false; return; } const b = e.target.closest('[data-o]'); if (b && +b.dataset.o !== h.selEnd && +b.dataset.o !== h.sel) select(t, +b.dataset.o, true); };
+ h.view.onmouseup = () => { h.drag = false; };
+ h.view.onkeydown = (e) => {
+ const g = geo(t), cur = h.selEnd ?? h.sel;
+ const mv = { ArrowLeft: -1, ArrowRight: 1, ArrowUp: -16, ArrowDown: 16, PageUp: -16 * g.vis, PageDown: 16 * g.vis }[e.key];
+ if (mv != null) select(t, cur + mv, e.shiftKey);
+ else if (e.key === 'Home') select(t, e.ctrlKey ? 0 : cur - cur % 16, e.shiftKey);
+ else if (e.key === 'End') select(t, e.ctrlKey ? h.size - 1 : cur - cur % 16 + 15, e.shiftKey);
+ else if (e.key === 'c' && e.ctrlKey) copySel(t);
+ else return;
+ e.preventDefault(); e.stopPropagation();
+ };
+ const guard = (inp) => { for (const ev of ['keydown', 'keyup', 'keypress']) inp.addEventListener(ev, (e) => e.stopPropagation()); };
+ el.querySelectorAll('.hx-in').forEach(guard);
+ el.querySelector('.hx-goto').onkeydown = (e) => {
+ if (e.key !== 'Enter') return;
+ const o = parseOff(e.target.value);
+ if (o == null || o >= h.size) { toast(o == null ? 'Offset inválido' : 'Offset depois do fim do arquivo'); return; }
+ select(t, o); h.view.focus();
+ };
+ el.querySelector('.hx-find').onkeydown = (e) => { if (e.key === 'Enter') find(t); };
+ el.querySelector('.hx-go').onclick = () => find(t);
+ el.querySelector('.hx-copy').onclick = () => copySel(t);
+ h.side.onclick = (e) => {
+ const le = e.target.closest('[data-le]'); if (le) { h.le = le.dataset.le === '1'; endian(); inspect(t); return; }
+ const v = e.target.closest('.hx-v'); if (v) navigator.clipboard.writeText(v.textContent).then(() => toast('Copiado', 'ok')).catch(() => {});
+ };
+ const endian = () => h.side.querySelectorAll('[data-le]').forEach(b => b.classList.toggle('primary', (b.dataset.le === '1') === h.le));
+ endian();
+ h.ro = new ResizeObserver(() => schedule(t)); h.ro.observe(h.view);
+ fetchRange(t, 0, 0).then(() => schedule(t)).catch(e => { h.rowsEl.textContent = 'Não deu para ler o arquivo: ' + e.message; });
+ detect(t);
+ },
+ show(t) { schedule(t); },
+ reload(t) { const h = t.hx; if (!h) return; h.cache.clear(); fetchRange(t, 0, 0).then(() => { h.sel = Math.min(h.sel, Math.max(0, h.size - 1)); schedule(t); }).catch(() => {}); detect(t); },
+ close(t) { t.hx?.ro?.disconnect(); if (t.hx?.searching) t.hx.searching.stop = true; },
+};
+
+plugin.onUnload(() => {
+ FV.open = origOpen;
+ delete FV.custom[KIND]; delete FV.labels[KIND];
+ bs.S.tabs.filter(x => x.kind === KIND).forEach(x => { x.hx?.ro?.disconnect(); x.kind = 'hex'; x.el?.remove(); x.el = null; });
+});
diff --git a/plugins/http-client/README.md b/plugins/http-client/README.md
new file mode 100644
index 0000000..1b9836d
--- /dev/null
+++ b/plugins/http-client/README.md
@@ -0,0 +1,34 @@
+# HTTP Client
+
+
+| | |
+|---|---|
+| **Autor** | Pizzy-23 |
+| **Versão** | 0.1.0 |
+| **Licença** | MIT |
+| **Categoria** | Desenvolvimento |
+| **Precisa de** | nada além do BlueScreen |
+| **Código** | [plugins/http-client](https://github.com/martindevbr/BlueScreen-Plugins/tree/main/plugins/http-client) |
+
+
+Painel na barra da esquerda para testar APIs, no estilo do Postman.
+
+## Como usar
+
+- Várias requisições guardadas, cada uma com método, URL, headers (`Nome: valor`, um por linha), token Bearer e body.
+- **Variáveis**: `baseUrl=https://api.exemplo.com`, uma por linha, e `{{baseUrl}}/rota` na requisição.
+- **Segredos**: guarde tokens cifrados (DPAPI, só neste PC) e use `{{secret:nome}}`. O núcleo troca na hora de enviar, e o valor não volta para a página nem fica no histórico. Prefira isso a colar o token direto no campo.
+- Histórico das últimas 30, **Copiar curl** e **Importar do Postman (v2.1)**.
+- O pedido sai pelo núcleo da IDE, então não esbarra em CORS.
+
+`Ctrl+Enter` (ou Enter na URL) envia.
+
+## Autor e licença
+
+Feito por Pizzy-23. Licença MIT (veja o campo `license` do `plugin.json`).
+
+## Histórico de versões
+
+### 0.1.0
+
+- Primeira versão na loja.
diff --git a/plugins/http-client/icon.svg b/plugins/http-client/icon.svg
new file mode 100644
index 0000000..c3f3884
--- /dev/null
+++ b/plugins/http-client/icon.svg
@@ -0,0 +1 @@
+
diff --git a/plugins/http-client/plugin.json b/plugins/http-client/plugin.json
new file mode 100644
index 0000000..da469ab
--- /dev/null
+++ b/plugins/http-client/plugin.json
@@ -0,0 +1,19 @@
+{
+ "id": "http-client",
+ "name": "HTTP Client",
+ "description": "Um Postman na barra da esquerda: várias requisições, método, URL, headers, token Bearer e body, variáveis {{baseUrl}}, segredos cifrados ({{secret:nome}}), histórico, copiar como curl e importar coleção do Postman v2.1. Sem CORS: o pedido sai pelo núcleo.",
+ "version": "0.1.0",
+ "author": "Pizzy-23",
+ "license": "MIT",
+ "category": "desenvolvimento",
+ "keywords": [
+ "http",
+ "api",
+ "rest",
+ "postman",
+ "curl",
+ "requisição"
+ ],
+ "icon": "icon.svg",
+ "order": 103
+}
diff --git a/plugins/http-client/style.css b/plugins/http-client/style.css
new file mode 100644
index 0000000..1b3c27a
--- /dev/null
+++ b/plugins/http-client/style.css
@@ -0,0 +1,28 @@
+.hp-wrap { display: flex; flex-direction: column; gap: 8px; padding: 10px; min-width: 0; box-sizing: border-box; }
+.hp-in { min-width: 0; background: var(--bg); color: var(--fg); border: 1px solid var(--line-2); border-radius: 4px; padding: 5px 8px; font: inherit; box-sizing: border-box; }
+.hp-wrap > .hp-in, .hp-more .hp-ta { width: 100%; }
+.hp-pick, .hp-url { flex: 1; }
+.hp-method { flex: none; font-weight: 600; }
+.hp-ta { min-height: 60px; resize: vertical; font-family: monospace; font-size: 12px; }
+.hp-lbl { color: var(--fg-2); font-size: 12px; margin-bottom: -4px; }
+.hp-lbl span { color: var(--muted); font-size: 11px; }
+.hp-res:empty { display: none; }
+.hp-meta { display: flex; gap: 10px; align-items: center; font-size: 12px; color: var(--fg-2); margin-bottom: 4px; }
+.hp-st { font-weight: 700; font-size: 12px; }
+.hp-ok { color: #3fb950; }
+.hp-err { color: #f85149; }
+.hp-pre { margin: 0; max-height: 320px; overflow: auto; background: var(--panel-2); color: var(--fg); border: 1px solid var(--line); border-radius: 4px; padding: 8px; font-size: 12px; white-space: pre-wrap; word-break: break-word; }
+.hp-more summary { cursor: pointer; color: var(--fg-2); }
+.hp-more[open] { display: flex; flex-direction: column; gap: 6px; }
+.hp-hist { display: flex; flex-direction: column; gap: 1px; }
+.hp-hitem { display: flex; align-items: center; gap: 6px; background: none; border: 0; color: var(--fg); font: inherit; font-size: 12px; padding: 4px 6px; border-radius: 4px; cursor: pointer; text-align: left; min-width: 0; }
+.hp-hitem:hover { background: var(--hover); }
+.hp-hm { color: var(--accent-2); font-weight: 600; }
+.hp-row { display: flex; gap: 6px; align-items: center; }
+.hp-sp { flex: 1; }
+.hp-name { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.hp-kind { color: var(--muted); font-size: 11px; }
+.hp-hint { color: var(--muted); font-size: 12px; padding: 4px 6px; }
+.hp-sec { display: flex; align-items: center; gap: 6px; font-size: 12px; padding: 2px 6px; }
+.hp-sec code { flex: 1; color: var(--accent-2); }
+.hp-secname, .hp-secval { flex: 1; }
diff --git a/plugins/http-client/ui.js b/plugins/http-client/ui.js
new file mode 100644
index 0000000..46b22e9
--- /dev/null
+++ b/plugins/http-client/ui.js
@@ -0,0 +1,201 @@
+// A barra da esquerda tem atalhos de teclado próprios (busca na árvore etc.) que engoliam o que se digitava nos campos.
+function guardKeys(wrap) {
+ for (const ev of ['keydown', 'keypress', 'keyup']) wrap.addEventListener(ev, e => {
+ if (e.target.matches('input, textarea') && !(e.ctrlKey && e.altKey)) e.stopPropagation();
+ });
+}
+
+const HP_ICON = ' ';
+const HP_PLUS = ' ';
+const HP_METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'];
+const HP_NOBODY = ['GET', 'HEAD'];
+let hp = null, hpTimer = 0;
+const hpRes = new Map();
+const hpNew = () => ({ id: 'r' + Date.now().toString(36) + Math.random().toString(36).slice(2, 6), name: 'Nova requisição', method: 'GET', url: '', headers: '', body: '', token: '' });
+
+async function hpLoad() {
+ if (hp) return hp;
+ let d = null;
+ try { d = await plugin.data.get('http', null); } catch (e) { bs.toast('Não deu para ler as requisições: ' + e.message); }
+ hp = d?.reqs?.length ? d : { reqs: [hpNew()], vars: '', history: [] };
+ hp.history ||= []; hp.vars ||= '';
+ if (!hp.reqs.some(r => r.id === hp.cur)) hp.cur = hp.reqs[0].id;
+ return hp;
+}
+const hpFlush = () => { clearTimeout(hpTimer); hpTimer = 0; return plugin.data.set('http', hp).catch(e => bs.toast('Não deu para salvar: ' + e.message)); };
+const hpSave = () => { clearTimeout(hpTimer); hpTimer = setTimeout(hpFlush, 400); };
+plugin.onUnload(() => { if (hpTimer) hpFlush(); });
+
+function hpVars() {
+ const m = {};
+ for (const l of hp.vars.split('\n')) { const i = l.indexOf('='); if (i > 0) m[l.slice(0, i).trim()] = l.slice(i + 1).trim(); }
+ return m;
+}
+// Só troca nomes simples; marcadores de segredo (com ":") passam intactos para o plugin.fetch.
+const hpSub = (s, v) => String(s).replace(/\{\{\s*([\w.-]+)\s*\}\}/g, (all, k) => k in v ? v[k] : all);
+function hpHeaders(r, v) {
+ const h = {};
+ for (const l of r.headers.split('\n')) { const i = l.indexOf(':'); if (i > 0) h[hpSub(l.slice(0, i).trim(), v)] = hpSub(l.slice(i + 1).trim(), v); }
+ if (r.token.trim()) h.Authorization = 'Bearer ' + hpSub(r.token.trim(), v);
+ return h;
+}
+function hpCurl(r) {
+ const v = hpVars(), q = s => "'" + String(s).replace(/'/g, "'\\''") + "'";
+ let c = `curl -X ${r.method} ${q(hpSub(r.url.trim(), v))}`;
+ for (const [k, x] of Object.entries(hpHeaders(r, v))) c += ` \\\n -H ${q(k + ': ' + x)}`;
+ if (r.body && !HP_NOBODY.includes(r.method)) c += ` \\\n --data-raw ${q(hpSub(r.body, v))}`;
+ return c;
+}
+const hpSize = n => n < 1024 ? n + ' B' : n < 1048576 ? (n / 1024).toFixed(1) + ' KB' : (n / 1048576).toFixed(1) + ' MB';
+
+function hpImport(src) {
+ const c = JSON.parse(src), out = [];
+ const walk = (items, prefix) => {
+ for (const it of items || []) {
+ if (it.item) { walk(it.item, prefix + it.name + ' / '); continue; }
+ const rq = it.request; if (!rq) continue;
+ const url = typeof rq === 'string' ? rq : typeof rq.url === 'string' ? rq.url : rq.url?.raw || '';
+ const bearer = rq.auth?.type === 'bearer' ? [].concat(rq.auth.bearer || []).find(b => b.key === 'token')?.value : '';
+ out.push({ ...hpNew(), name: prefix + (it.name || url), method: String(rq.method || 'GET').toUpperCase(), url,
+ headers: (rq.header || []).filter(h => !h.disabled).map(h => h.key + ': ' + h.value).join('\n'),
+ body: rq.body?.raw || '', token: bearer || '' });
+ }
+ };
+ walk(c.item, '');
+ const have = hpVars();
+ for (const v of c.variable || []) if (v.key && !(v.key in have)) hp.vars += (hp.vars && !hp.vars.endsWith('\n') ? '\n' : '') + v.key + '=' + (v.value ?? '');
+ return out;
+}
+
+function hpPanel(el) {
+ el.innerHTML = '';
+ hpLoad().then(() => { if (el.isConnected) hpDraw(el); });
+}
+
+function hpDraw(el) {
+ const r = hp.reqs.find(x => x.id === hp.cur) || hp.reqs[0];
+ hp.cur = r.id;
+ el.innerHTML = `
+
${hp.reqs.map(x => `${bs.esc(x.name)} `).join('')}
+ ${HP_PLUS} ${bs.I.x}
+
+
${HP_METHODS.map(m => `${m} `).join('')}
+
+
Headers Nome: valor, um por linha
+
+
Token Bearer
+
+
Body
+
+
Enviar Copiar curl
+
${hpRes.get(r.id) || ''}
+
Variáveis
+
+
Histórico
+
Segredos
+ Cifrados neste PC. Use {{secret:nome}} na URL, nos headers, no token ou no body: o núcleo põe o valor na hora de enviar, e ele não volta para a página.
+
+ Guardar
+
Importar do Postman (v2.1)
+
+ Importar
+
`;
+ guardKeys(el.querySelector(".hp-wrap"));
+ const wrap = el.querySelector('.hp-wrap'), res = el.querySelector('.hp-res'), sendBtn = el.querySelector('.hp-send');
+
+ function drawHist() {
+ el.querySelector('.hp-hist').innerHTML = hp.history.length ? hp.history.map((h, i) => `
+ ${bs.esc(String(h.status))}
+ ${bs.esc(h.method)} ${bs.esc(h.url)} ${h.ms} ms `).join('')
+ : 'Nada enviado ainda.
';
+ }
+ drawHist();
+
+ async function drawSecrets() {
+ const box = el.querySelector('.hp-seclist');
+ let keys = [];
+ try { keys = await plugin.secrets.keys(); } catch (e) { box.innerHTML = `${bs.esc(e.message)}
`; return; }
+ box.innerHTML = keys.map(k => `{{secret:${bs.esc(k)}}}${bs.I.x}
`).join('');
+ }
+ drawSecrets();
+ el.querySelector('.hp-secadd').onclick = async () => {
+ const n = el.querySelector('.hp-secname'), v = el.querySelector('.hp-secval');
+ const name = n.value.trim();
+ if (!/^[\w.-]+$/.test(name) || !v.value) { bs.toast('Nome (letras, números, . _ -) e valor'); return; }
+ try { await plugin.secrets.set(name, v.value); n.value = v.value = ''; drawSecrets(); bs.toast(`Use {{secret:${name}}}`, 'ok'); }
+ catch (e) { bs.toast('Não deu para guardar: ' + e.message); }
+ };
+ el.querySelector('.hp-seclist').onclick = async e => {
+ const b = e.target.closest('.hp-secdel'); if (!b) return;
+ if (!b.dataset.sure) { b.dataset.sure = '1'; bs.toast('Clique de novo para apagar'); return; }
+ await plugin.secrets.remove(b.dataset.k).catch(err => bs.toast(err.message)); drawSecrets();
+ };
+
+ async function send() {
+ const v = hpVars(), url = hpSub(r.url.trim(), v);
+ if (!url) { bs.toast('Digite a URL.'); return; }
+ res.innerHTML = 'Enviando…
'; sendBtn.disabled = true;
+ const t0 = performance.now();
+ let status = 'Erro', html;
+ try {
+ const opt = { method: r.method, headers: hpHeaders(r, v) };
+ if (r.body && !HP_NOBODY.includes(r.method)) opt.body = hpSub(r.body, v);
+ const x = await plugin.fetch(url, opt);
+ const ms = Math.round(performance.now() - t0), body = String(x.body ?? '');
+ let pretty = body;
+ try { pretty = JSON.stringify(JSON.parse(body), null, 2); } catch {}
+ status = x.status;
+ html = `${bs.esc(String(x.status))} ${ms} ms ${hpSize(new Blob([body]).size)}
${bs.esc(pretty)} `;
+ hp.history.unshift({ id: r.id, method: r.method, url, status, ms });
+ hp.history.length = Math.min(hp.history.length, 30);
+ hpSave();
+ } catch (e) {
+ html = `Erro
${bs.esc(e.message)} `;
+ }
+ hpRes.set(r.id, html);
+ if (res.isConnected) { res.innerHTML = html; sendBtn.disabled = false; drawHist(); }
+ }
+
+ wrap.oninput = e => {
+ const t = e.target;
+ if (t.matches('.hp-f')) {
+ r[t.dataset.k] = t.value;
+ if (t.dataset.k === 'name') el.querySelector(`.hp-pick option[value="${r.id}"]`).textContent = t.value || 'Sem nome';
+ } else if (t.matches('.hp-vars')) hp.vars = t.value;
+ else return;
+ hpSave();
+ };
+ wrap.onchange = e => {
+ if (e.target.matches('.hp-method')) { r.method = e.target.value; hpSave(); }
+ else if (e.target.matches('.hp-pick')) { hp.cur = e.target.value; hpSave(); hpDraw(el); }
+ };
+ wrap.addEventListener('keydown', e => {
+ if (e.key === 'Enter' && (e.ctrlKey || e.target.matches('.hp-url'))) { e.preventDefault(); send(); }
+ });
+ sendBtn.onclick = send;
+ el.querySelector('.hp-add').onclick = () => { const n = hpNew(); hp.reqs.push(n); hp.cur = n.id; hpSave(); hpDraw(el); };
+ el.querySelector('.hp-del').onclick = () => {
+ hp.reqs = hp.reqs.filter(x => x !== r);
+ if (!hp.reqs.length) hp.reqs.push(hpNew());
+ hp.cur = hp.reqs[0].id; hpRes.delete(r.id); hpSave(); hpDraw(el);
+ };
+ el.querySelector('.hp-curl').onclick = async () => {
+ try { await navigator.clipboard.writeText(hpCurl(r)); bs.toast('curl copiado', 'ok'); }
+ catch (e) { bs.toast('Não deu para copiar: ' + e.message); }
+ };
+ el.querySelector('.hp-hist').onclick = e => {
+ const b = e.target.closest('.hp-hitem'); if (!b) return;
+ const h = hp.history[+b.dataset.i];
+ if (hp.reqs.some(x => x.id === h.id)) { hp.cur = h.id; hpDraw(el); }
+ else { const n = { ...hpNew(), name: h.method + ' ' + h.url, method: h.method, url: h.url }; hp.reqs.push(n); hp.cur = n.id; hpSave(); hpDraw(el); }
+ };
+ el.querySelector('.hp-impgo').onclick = () => {
+ try {
+ const got = hpImport(el.querySelector('.hp-imp').value);
+ if (!got.length) { bs.toast('Nenhuma requisição na coleção.'); return; }
+ hp.reqs.push(...got); hp.cur = got[0].id; hpSave(); hpDraw(el);
+ bs.toast(`${got.length} requisiç${got.length === 1 ? 'ão importada' : 'ões importadas'}`, 'ok');
+ } catch (e) { bs.toast('JSON inválido: ' + e.message); }
+ };
+}
+bs.tools.register({ id: 'tv-http', title: 'HTTP Client', icon: HP_ICON, order: 62, render() { hpPanel(bs.$('#toolBody')); } });
diff --git a/plugins/markdown-preview/README.md b/plugins/markdown-preview/README.md
new file mode 100644
index 0000000..3e228b7
--- /dev/null
+++ b/plugins/markdown-preview/README.md
@@ -0,0 +1,32 @@
+# Markdown Preview
+
+
+| | |
+|---|---|
+| **Autor** | Pizzy-23 |
+| **Versão** | 0.1.0 |
+| **Licença** | MIT |
+| **Categoria** | Produtividade |
+| **Precisa de** | nada além do BlueScreen |
+| **Código** | [plugins/markdown-preview](https://github.com/martindevbr/BlueScreen-Plugins/tree/main/plugins/markdown-preview) |
+
+
+Arquivos `.md` e `.markdown` abrem já formatados, com um botão para voltar a editar. Para quem lê e escreve documentação na IDE.
+
+## Como usar
+
+O botão no canto do editor troca entre **Visualizar** e **Editar** (ou `Ctrl+Alt+M`), e a escolha fica por arquivo.
+
+Imagens com caminho relativo ao arquivo aparecem, e um link relativo para outro `.md` abre o arquivo na IDE.
+
+Outros plugins podem pedir para redesenhar: `bs.mdVisual?.sync()` (o Project Tasks usa isso).
+
+## Autor e licença
+
+Feito por Pizzy-23. Licença MIT (veja o campo `license` do `plugin.json`).
+
+## Histórico de versões
+
+### 0.1.0
+
+- Primeira versão na loja.
diff --git a/plugins/markdown-preview/icon.svg b/plugins/markdown-preview/icon.svg
new file mode 100644
index 0000000..a2ae9b4
--- /dev/null
+++ b/plugins/markdown-preview/icon.svg
@@ -0,0 +1 @@
+
diff --git a/plugins/markdown-preview/plugin.json b/plugins/markdown-preview/plugin.json
new file mode 100644
index 0000000..1f8ccd1
--- /dev/null
+++ b/plugins/markdown-preview/plugin.json
@@ -0,0 +1,17 @@
+{
+ "id": "markdown-preview",
+ "name": "Markdown Preview",
+ "description": "Arquivos .md abrem já formatados, com um botão Visualizar/Editar no canto do editor (Ctrl+Alt+M). Imagens e links relativos ao arquivo funcionam: um link para outro .md abre na IDE.",
+ "version": "0.1.0",
+ "author": "Pizzy-23",
+ "license": "MIT",
+ "category": "produtividade",
+ "keywords": [
+ "markdown",
+ "md",
+ "visualizar",
+ "preview"
+ ],
+ "icon": "icon.svg",
+ "order": 101
+}
diff --git a/plugins/markdown-preview/style.css b/plugins/markdown-preview/style.css
new file mode 100644
index 0000000..f500d11
--- /dev/null
+++ b/plugins/markdown-preview/style.css
@@ -0,0 +1,17 @@
+.md-bar { position: absolute; top: 8px; right: 22px; z-index: 20; display: flex; background: var(--panel-2); border: 1px solid var(--line); border-radius: 6px; overflow: hidden; }
+.md-bar[hidden], .md-view[hidden] { display: none; }
+.md-btn { background: none; border: 0; color: var(--fg-2); padding: 4px 10px; font: inherit; font-size: 12px; cursor: pointer; }
+.md-btn:hover { background: var(--hover); }
+.md-btn.md-on { background: var(--accent); color: var(--on-accent); }
+.md-view { position: absolute; inset: 0; z-index: 10; overflow: auto; background: var(--bg); color: var(--fg); }
+.md-body { max-width: 860px; margin: 0 auto; padding: 40px 32px; line-height: 1.6; font-size: 14px; }
+.md-body h1, .md-body h2 { border-bottom: 1px solid var(--line); padding-bottom: .3em; }
+.md-body a { color: var(--accent-2); }
+.md-body code { background: var(--panel-2); padding: .1em .35em; border-radius: 4px; font-family: monospace; font-size: .92em; }
+.md-body pre { background: var(--panel-2); padding: 12px; border-radius: 6px; overflow: auto; }
+.md-body pre code { background: none; padding: 0; }
+.md-body blockquote { margin: 0; padding: 0 1em; border-left: 3px solid var(--line-2); color: var(--fg-2); }
+.md-body table { border-collapse: collapse; }
+.md-body th, .md-body td { border: 1px solid var(--line); padding: 4px 10px; }
+.md-body img { max-width: 100%; }
+.md-body hr { border: 0; border-top: 1px solid var(--line); }
diff --git a/plugins/markdown-preview/ui.js b/plugins/markdown-preview/ui.js
new file mode 100644
index 0000000..2aeadf5
--- /dev/null
+++ b/plugins/markdown-preview/ui.js
@@ -0,0 +1,126 @@
+const isMd = p => /\.(md|markdown)$/i.test(p || '');
+const isRel = u => !/^([a-z][\w+.-]*:|\/\/|#|\/)/i.test(u);
+const dirOf = p => p.includes('/') ? p.slice(0, p.lastIndexOf('/') + 1) : '';
+
+// Junta "docs/" com "../img/a.png" do jeito que o navegador faria, para pedir o arquivo ao núcleo.
+function joinRel(base, rel) {
+ const parts = (base + rel).split('/'), out = [];
+ for (const s of parts) { if (s === '..') out.pop(); else if (s && s !== '.') out.push(s); }
+ return out.join('/');
+}
+
+function mdInline(s, base) {
+ const codes = [];
+ s = bs.esc(s).replace(/`([^`]+)`/g, (_, c) => (codes.push(c), '\u0000' + (codes.length - 1) + '\u0000'));
+ const safe = u => /^\s*javascript:/i.test(u) ? '#' : u;
+ const img = u => {
+ if (!isRel(u) || !bs.S.project) return safe(u);
+ const file = joinRel(base, u.replace(/&/g, '&'));
+ return `/api/raw?project=${encodeURIComponent(bs.S.project.path)}&file=${encodeURIComponent(file)}`;
+ };
+ s = s.replace(/!\[([^\]]*)\]\(([^)\s]+)[^)]*\)/g, (_, a, u) => ` `)
+ .replace(/\[([^\]]+)\]\(([^)\s]+)[^)]*\)/g, (_, t, u) => isRel(u) ? `${t} ` : `${t} `)
+ .replace(/(\*\*|__)(.+?)\1/g, '$2 ')
+ .replace(/(^|[^*\w])[*_]([^*_]+)[*_](?=[^*\w]|$)/g, '$1$2 ')
+ .replace(/~~(.+?)~~/g, '$1');
+ return s.replace(/\u0000(\d+)\u0000/g, (_, i) => `${codes[i]}`);
+}
+
+function mdRender(src, base = '') {
+ const L = src.replace(/\r/g, '').split('\n'), out = [];
+ const inl = s => mdInline(s, base);
+ let i = 0;
+ const cells = r => r.trim().replace(/^\||\|$/g, '').split('|').map(c => c.trim());
+ while (i < L.length) {
+ const l = L[i];
+ let m;
+ if (/^\s*```/.test(l)) {
+ const buf = []; i++;
+ while (i < L.length && !/^\s*```/.test(L[i])) buf.push(L[i++]);
+ i++; out.push(`${bs.esc(buf.join('\n'))} `);
+ } else if ((m = l.match(/^(#{1,6})\s+(.*?)#*\s*$/))) {
+ out.push(`${inl(m[2])} `); i++;
+ } else if (/^\s*([-*_])(\s*\1){2,}\s*$/.test(l)) {
+ out.push(' '); i++;
+ } else if (/^\s*>/.test(l)) {
+ const buf = [];
+ while (i < L.length && /^\s*>/.test(L[i])) buf.push(L[i++].replace(/^\s*>\s?/, ''));
+ out.push(`${mdRender(buf.join('\n'), base)} `);
+ } else if (l.includes('|') && /^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/.test(L[i + 1] || '')) {
+ const head = cells(l); i += 2;
+ let h = '' + head.map(c => `${inl(c)} `).join('') + ' ';
+ while (i < L.length && L[i].includes('|')) h += '' + cells(L[i++]).map(c => `${inl(c)} `).join('') + ' ';
+ out.push(h + '
');
+ } else if (/^\s*([-*+]|\d+[.)])\s+/.test(l)) {
+ const ol = /^\s*\d/.test(l), items = [];
+ while (i < L.length && /^\s*([-*+]|\d+[.)])\s+/.test(L[i])) {
+ let t = L[i++].replace(/^\s*([-*+]|\d+[.)])\s+/, '');
+ const chk = t.match(/^\[([ xX])\]\s+/);
+ if (chk) t = ` ` + inl(t.slice(chk[0].length));
+ else t = inl(t);
+ items.push(`${t} `);
+ }
+ out.push(`<${ol ? 'ol' : 'ul'}>${items.join('')}${ol ? 'ol' : 'ul'}>`);
+ } else if (!l.trim()) {
+ i++;
+ } else {
+ const buf = [];
+ while (i < L.length && L[i].trim() && !/^(#{1,6}\s|\s*```|\s*>|\s*([-*+]|\d+[.)])\s)/.test(L[i])) buf.push(inl(L[i++]));
+ out.push(`${buf.join(' ')}
`);
+ }
+ }
+ return out.join('\n');
+}
+
+const mode = new Map();
+let bar = null, view = null;
+
+function sync() {
+ const path = bs.S.active?.path || '';
+ const host = bs.editor?.getDomNode?.()?.parentElement;
+ if (!host || !isMd(path) || bs.S.active?.mode === 'view') { if (bar) bar.hidden = true; if (view) view.hidden = true; return; }
+ if (!bar || bar.parentElement !== host) {
+ bar?.remove(); view?.remove();
+ if (getComputedStyle(host).position === 'static') host.style.position = 'relative';
+ view = document.createElement('div');
+ view.className = 'md-view';
+ view.onclick = e => {
+ const a = e.target.closest('a[data-rel]'); if (!a) return;
+ e.preventDefault();
+ const [file, hash] = a.dataset.rel.replace(/&/g, '&').split('#');
+ if (file) bs.openFile(joinRel(dirOf(bs.S.active?.path || ''), file), 'editor');
+ else if (hash) view.querySelector(`[id="${CSS.escape(hash)}"]`)?.scrollIntoView();
+ };
+ bar = document.createElement('div');
+ bar.className = 'md-bar';
+ bar.innerHTML = 'Visualizar Editar ';
+ bar.onclick = e => {
+ const b = e.target.closest('.md-btn'); if (!b) return;
+ mode.set(bs.S.active?.path, b.dataset.m); sync();
+ if (b.dataset.m === 'edit') bs.editor.focus();
+ };
+ host.append(view, bar);
+ }
+ const m = mode.get(path) || 'view';
+ bar.hidden = false;
+ bar.querySelectorAll('.md-btn').forEach(b => b.classList.toggle('md-on', b.dataset.m === m));
+ view.hidden = m !== 'view';
+ if (m === 'view') {
+ try {
+ const top = view.scrollTop;
+ view.innerHTML = `${mdRender(bs.editor.getValue(), dirOf(path))}
`;
+ view.querySelectorAll('h1, h2, h3, h4, h5, h6').forEach(h => { h.id = h.textContent.trim().toLowerCase().replace(/[^\p{L}\p{N}\s-]/gu, '').replace(/\s+/g, '-'); });
+ view.scrollTop = top;
+ } catch (e) { bs.toast('Erro ao mostrar o Markdown: ' + e.message); }
+ }
+}
+
+for (const ev of ['tab:open', 'tab:activate', 'tab:close', 'editor:ready', 'refresh', 'files:changed']) bs.hooks.on(ev, () => setTimeout(sync, 0));
+bs.keys.add('Ctrl+Alt+M', () => {
+ const p = bs.S.active?.path;
+ if (!isMd(p)) return false;
+ mode.set(p, (mode.get(p) || 'view') === 'view' ? 'edit' : 'view'); sync();
+});
+bs.mdVisual = { sync, render: mdRender };
+plugin.onUnload(() => { bar?.remove(); view?.remove(); delete bs.mdVisual; });
+setTimeout(sync, 0);
diff --git a/plugins/open-ports/README.md b/plugins/open-ports/README.md
new file mode 100644
index 0000000..ce3fd79
--- /dev/null
+++ b/plugins/open-ports/README.md
@@ -0,0 +1,34 @@
+# Open Ports
+
+
+| | |
+|---|---|
+| **Autor** | Pizzy-23 |
+| **Versão** | 0.1.0 |
+| **Licença** | MIT |
+| **Categoria** | Desenvolvimento |
+| **Precisa de** | nada além do BlueScreen |
+| **Código** | [plugins/open-ports](https://github.com/martindevbr/BlueScreen-Plugins/tree/main/plugins/open-ports) |
+
+
+Painel na barra da esquerda com as portas TCP em que algum programa está ouvindo.
+
+## Como usar
+
+- Porta, programa, PID e o título da janela, quando tem.
+- **local** (só este PC) ou **rede** (0.0.0.0 / ::, outros aparelhos alcançam), em amarelo.
+- Ao passar o mouse: **Abrir** no navegador (`http://127.0.0.1:porta`) e **Encerrar** o processo pelo PID exato. Encerrar pede um segundo clique e não aparece para os processos do Windows.
+- Os processos do sistema ficam escondidos. Marque **sistema** para ver todos.
+- Filtre por porta, nome ou PID. Com o painel aberto, a lista se atualiza a cada 5 segundos.
+
+Bom para achar o servidor de dev esquecido que está segurando a porta 3000.
+
+## Autor e licença
+
+Feito por Pizzy-23. Licença MIT (veja o campo `license` do `plugin.json`).
+
+## Histórico de versões
+
+### 0.1.0
+
+- Primeira versão na loja.
diff --git a/plugins/open-ports/icon.svg b/plugins/open-ports/icon.svg
new file mode 100644
index 0000000..94a65bb
--- /dev/null
+++ b/plugins/open-ports/icon.svg
@@ -0,0 +1 @@
+
diff --git a/plugins/open-ports/plugin.json b/plugins/open-ports/plugin.json
new file mode 100644
index 0000000..4417ed5
--- /dev/null
+++ b/plugins/open-ports/plugin.json
@@ -0,0 +1,18 @@
+{
+ "id": "open-ports",
+ "name": "Open Ports",
+ "description": "Quem está ouvindo em cada porta TCP do PC: o programa, o PID e se a porta está aberta só para este PC ou para a rede. Abrir no navegador e encerrar o processo (pelo PID exato, com confirmação). Atualiza sozinho a cada 5 segundos com o painel aberto.",
+ "version": "0.1.0",
+ "author": "Pizzy-23",
+ "license": "MIT",
+ "category": "desenvolvimento",
+ "keywords": [
+ "portas",
+ "tcp",
+ "processos",
+ "pid",
+ "servidor"
+ ],
+ "icon": "icon.svg",
+ "order": 115
+}
diff --git a/plugins/open-ports/style.css b/plugins/open-ports/style.css
new file mode 100644
index 0000000..c46a11e
--- /dev/null
+++ b/plugins/open-ports/style.css
@@ -0,0 +1,18 @@
+.po-wrap { display: flex; flex-direction: column; gap: 6px; padding: 8px 10px; height: 100%; box-sizing: border-box; min-width: 0; }
+.po-row1 { display: flex; align-items: center; gap: 6px; }
+.po-q { flex: 1; min-width: 0; background: var(--bg); color: var(--fg); border: 1px solid var(--line-2); border-radius: 4px; padding: 5px 8px; font: inherit; }
+.po-count { color: var(--muted); font-size: 11px; }
+.po-sp { flex: 1; }
+.po-chk { display: flex; align-items: center; gap: 4px; font-size: 11px; color: var(--fg-2); }
+.po-list { flex: 1; min-height: 0; overflow: auto; display: flex; flex-direction: column; gap: 1px; }
+.po-row { display: grid; grid-template-columns: 52px 1fr auto; grid-template-areas: "port who scope" "port acts acts"; gap: 2px 8px; align-items: center; padding: 5px 6px; border-radius: 6px; }
+.po-row:hover { background: var(--hover); }
+.po-port { grid-area: port; font: 600 14px var(--mono); color: var(--accent-2); }
+.po-who { grid-area: who; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 12px; }
+.po-who i { color: var(--muted); font-style: normal; font-size: 11px; }
+.po-who small { display: block; color: var(--muted); overflow: hidden; text-overflow: ellipsis; }
+.po-scope { grid-area: scope; font-size: 10px; border-radius: 8px; padding: 0 6px; border: 1px solid var(--line-2); color: var(--fg-2); }
+.po-rede { border-color: #d29922; color: #d29922; }
+.po-acts { grid-area: acts; display: none; gap: 4px; }
+.po-row:hover .po-acts, .po-acts:has([data-sure]) { display: flex; }
+.po-acts .chip { font-size: 11px; padding: 1px 8px; }
diff --git a/plugins/open-ports/ui.js b/plugins/open-ports/ui.js
new file mode 100644
index 0000000..9451861
--- /dev/null
+++ b/plugins/open-ports/ui.js
@@ -0,0 +1,94 @@
+// Portas abertas: quem está ouvindo em cada porta TCP deste PC (Get-NetTCPConnection + Get-Process), com encerrar por PID.
+const { esc, toast } = bs;
+if (bs.S.remote) return;
+
+const ICON = ' ';
+const SYSTEM = /^(system|idle|svchost|services|wininit|lsass|spoolsv|smss|csrss|winlogon|registry|memcompression|searchindexer|msmpeng|nissrv|mdnsresponder|jhi_service)$/i;
+const P = { rows: null, err: null, sys: false, q: '', timer: 0 };
+
+const QUERY = `[Console]::OutputEncoding=[Text.Encoding]::UTF8
+$p = @{}; Get-Process | ForEach-Object { $p[$_.Id] = $_ }
+$r = Get-NetTCPConnection -State Listen -ErrorAction SilentlyContinue | ForEach-Object {
+ $x = $p[[int]$_.OwningProcess]
+ [pscustomobject]@{ port = $_.LocalPort; addr = $_.LocalAddress; pid = $_.OwningProcess; name = $(if ($x) { $x.ProcessName } else { '' }); path = $(if ($x) { $x.Path } else { '' }); title = $(if ($x) { $x.MainWindowTitle } else { '' }) } }
+ConvertTo-Json -Compress -InputObject @($r)`;
+
+async function load() {
+ try {
+ const r = await plugin.exec('powershell', ['-NoProfile', '-NonInteractive', '-Command', QUERY], { timeout: 20000 });
+ if (!r.ok) throw new Error(r.err || 'falha no PowerShell');
+ const seen = new Map();
+ for (const x of JSON.parse(r.out.trim() || '[]')) {
+ const k = x.port + ':' + x.pid, cur = seen.get(k);
+ if (cur) cur.addrs.add(x.addr); else seen.set(k, { ...x, addrs: new Set([x.addr]) });
+ }
+ P.rows = [...seen.values()].sort((a, b) => a.port - b.port); P.err = null;
+ } catch (e) { P.err = e.message; }
+ draw();
+}
+
+// quem ouve em 0.0.0.0/:: também responde no 127.0.0.1; só quem ouve apenas no ::1 precisa do endereço IPv6
+const local = (x) => x.addrs.has('::1') && !x.addrs.has('127.0.0.1') && !x.addrs.has('0.0.0.0') && !x.addrs.has('::') ? `http://[::1]:${x.port}` : `http://127.0.0.1:${x.port}`;
+const isSys = (x) => !x.path || SYSTEM.test(x.name) || x.pid <= 4;
+const scope = (x) => [...x.addrs].some(a => a === '0.0.0.0' || a === '::') ? 'rede' : 'local';
+
+function draw() {
+ const el = bs.$('#toolBody .po-wrap'); if (!el) return;
+ const list = el.querySelector('.po-list');
+ if (P.err) { list.innerHTML = `${esc(P.err)}
`; return; }
+ if (!P.rows) { list.innerHTML = '
'; return; }
+ const q = P.q.toLowerCase();
+ const mine = P.rows.filter(x => P.sys || !isSys(x));
+ const rows = mine.filter(x => !q || String(x.port).includes(q) || x.name.toLowerCase().includes(q) || String(x.pid) === q);
+ const hidden = P.rows.length - mine.length;
+ el.querySelector('.po-count').textContent = `${rows.length} porta${rows.length === 1 ? '' : 's'}${hidden ? ` · ${hidden} do sistema escondidas` : ''}`;
+ list.innerHTML = rows.length ? rows.map(x => `
+ ${x.port}
+ ${esc(x.name || '?')} PID ${x.pid} ${x.title ? `${esc(x.title)} ` : ''}
+ ${scope(x)}
+ Abrir ${isSys(x) ? '' : 'Encerrar '}
+
`).join('') : 'Nada ouvindo.
';
+}
+
+async function kill(pid, btn) {
+ if (!btn.dataset.sure) {
+ btn.dataset.sure = '1'; btn.textContent = 'Confirmar?'; btn.classList.add('danger');
+ setTimeout(() => { if (btn.isConnected) { delete btn.dataset.sure; btn.textContent = 'Encerrar'; btn.classList.remove('danger'); } }, 4000);
+ return;
+ }
+ btn.disabled = true; clearInterval(P.timer);
+ const r = await plugin.exec('powershell', ['-NoProfile', '-NonInteractive', '-Command', `Stop-Process -Id ${+pid} -Force -ErrorAction Stop`], { timeout: 15000 }).catch(e => ({ ok: false, err: e.message }));
+ if (r.ok) toast(`Processo ${pid} encerrado`, 'ok'); else toast('Não deu para encerrar: ' + (r.err || '').trim().split(/\r?\n/)[0]);
+ load(); poll();
+}
+
+// o draw() troca a lista inteira; com o mouse em cima de um "Confirmar?", espera o clique em vez de redesenhar
+function poll() {
+ clearInterval(P.timer);
+ P.timer = setInterval(() => {
+ if (!bs.$('#toolBody .po-wrap')) { clearInterval(P.timer); P.timer = 0; return; }
+ if (document.visibilityState === 'visible' && !bs.$('#toolBody .po-list [data-sure]')) load();
+ }, 5000);
+}
+
+function panel(el) {
+ el.innerHTML = `
+
${bs.I.refresh}
+
sistema
+
`;
+ const w = el.querySelector('.po-wrap');
+ for (const ev of ['keydown', 'keypress', 'keyup']) w.addEventListener(ev, e => { if (e.target.matches('input') && !(e.ctrlKey && e.altKey)) e.stopPropagation(); });
+ w.querySelector('.po-q').oninput = (e) => { P.q = e.target.value; draw(); };
+ w.querySelector('.po-sys').onchange = (e) => { P.sys = e.target.checked; draw(); };
+ w.querySelector('.po-ref').onclick = load;
+ w.querySelector('.po-list').onclick = (e) => {
+ const b = e.target.closest('[data-a]'), row = e.target.closest('.po-row'); if (!b || !row) return;
+ if (b.dataset.a === 'open') plugin.exec('explorer.exe', [b.dataset.url], { timeout: 10000 }).catch(() => {});
+ else kill(row.dataset.pid, b);
+ };
+ draw(); load(); poll();
+}
+
+bs.tools.register({ id: 'portas-abertas', title: 'Open Ports', icon: ICON, order: 65, render() { panel(bs.$('#toolBody')); } });
+bs.actions.add([{ label: 'Open Ports: quem está usando cada porta', icon: ICON, run: () => { const b = bs.$('#strip [data-tool="portas-abertas"]'); if (b && !b.classList.contains('on')) b.click(); } }]);
+plugin.onUnload(() => clearInterval(P.timer));
diff --git a/plugins/project-tasks/README.md b/plugins/project-tasks/README.md
new file mode 100644
index 0000000..0c0a80d
--- /dev/null
+++ b/plugins/project-tasks/README.md
@@ -0,0 +1,38 @@
+# Project Tasks
+
+
+| | |
+|---|---|
+| **Autor** | Pizzy-23 |
+| **Versão** | 0.1.0 |
+| **Licença** | MIT |
+| **Categoria** | Produtividade |
+| **Precisa de** | nada além do BlueScreen |
+| **Código** | [plugins/project-tasks](https://github.com/martindevbr/BlueScreen-Plugins/tree/main/plugins/project-tasks) |
+
+
+Um painel na barra da esquerda (`Ctrl+Alt+T`) com as tarefas do projeto aberto. Elas ficam num `TAREFAS.md` na raiz do projeto, como checkboxes do Markdown (`- [ ] fazer x`), então dá para editar o arquivo à mão, versionar no git e ler em qualquer lugar.
+
+## Como usar
+
+Escreva e aperte Enter para adicionar. Marque, apague ou **Limpar feitas**. O nome do arquivo muda na engrenagem do plugin.
+
+Com o **Markdown Preview** ligado, o `TAREFAS.md` aberto no editor se redesenha a cada mudança.
+
+## Configurações
+
+Aba Plugins › engrenagem do Project Tasks:
+
+| Configuração | O que muda |
+|---|---|
+| **Arquivo das tarefas** | o caminho do arquivo, relativo à raiz do projeto (padrão `TAREFAS.md`) |
+
+## Autor e licença
+
+Feito por Pizzy-23. Licença MIT (veja o campo `license` do `plugin.json`).
+
+## Histórico de versões
+
+### 0.1.0
+
+- Primeira versão na loja.
diff --git a/plugins/project-tasks/icon.svg b/plugins/project-tasks/icon.svg
new file mode 100644
index 0000000..ca03498
--- /dev/null
+++ b/plugins/project-tasks/icon.svg
@@ -0,0 +1 @@
+
diff --git a/plugins/project-tasks/plugin.json b/plugins/project-tasks/plugin.json
new file mode 100644
index 0000000..ebc7fa1
--- /dev/null
+++ b/plugins/project-tasks/plugin.json
@@ -0,0 +1,25 @@
+{
+ "id": "project-tasks",
+ "name": "Project Tasks",
+ "description": "Lista de tarefas de cada projeto, guardada num TAREFAS.md na raiz (checkboxes do Markdown). Painel na barra da esquerda (Ctrl+Alt+T): adicionar, marcar, apagar, limpar as feitas e abrir o arquivo.",
+ "version": "0.1.0",
+ "author": "Pizzy-23",
+ "license": "MIT",
+ "category": "produtividade",
+ "keywords": [
+ "tarefas",
+ "todo",
+ "checklist",
+ "markdown"
+ ],
+ "icon": "icon.svg",
+ "order": 102,
+ "settings": [
+ {
+ "key": "file",
+ "label": "Arquivo das tarefas",
+ "default": "TAREFAS.md",
+ "help": "Caminho relativo à raiz do projeto"
+ }
+ ]
+}
diff --git a/plugins/project-tasks/style.css b/plugins/project-tasks/style.css
new file mode 100644
index 0000000..907b5a4
--- /dev/null
+++ b/plugins/project-tasks/style.css
@@ -0,0 +1,13 @@
+.tk-wrap { display: flex; flex-direction: column; gap: 8px; padding: 10px; min-width: 0; height: 100%; box-sizing: border-box; }
+.tk-row { display: flex; gap: 6px; align-items: center; }
+.tk-sp { flex: 1; }
+.tk-in { flex: 1; min-width: 0; background: var(--bg); color: var(--fg); border: 1px solid var(--line-2); border-radius: 4px; padding: 5px 8px; font: inherit; }
+.tk-list { flex: 1; min-height: 80px; overflow: auto; display: flex; flex-direction: column; gap: 2px; }
+.tk-proj { color: var(--fg-2); font-size: 12px; }
+.tk-item { display: flex; align-items: center; gap: 8px; padding: 4px 6px; border-radius: 4px; color: var(--fg); }
+.tk-item:hover { background: var(--hover); }
+.tk-name { flex: 1; min-width: 0; overflow-wrap: anywhere; }
+.tk-name code { background: var(--panel-2); padding: 0 .3em; border-radius: 3px; font-size: .92em; }
+.tk-done .tk-name { color: var(--muted); text-decoration: line-through; }
+.tk-item .tk-del { opacity: 0; }
+.tk-item:hover .tk-del { opacity: 1; }
diff --git a/plugins/project-tasks/ui.js b/plugins/project-tasks/ui.js
new file mode 100644
index 0000000..bea28e8
--- /dev/null
+++ b/plugins/project-tasks/ui.js
@@ -0,0 +1,98 @@
+const ICON = ' ';
+const TASK = /^(\s*[-*+]\s+\[)([ xX])(\]\s+)(.*)$/;
+let file = 'TAREFAS.md', redraw = null;
+
+plugin.settings.get().then(c => { file = (c.file || '').trim() || file; redraw?.(); }).catch(() => {});
+plugin.settings.onChange(c => { file = (c.file || '').trim() || 'TAREFAS.md'; redraw?.(); });
+
+// A barra da esquerda tem atalhos de teclado próprios (busca na árvore etc.) que engoliam o que se digitava nos campos.
+function guardKeys(wrap) {
+ for (const ev of ['keydown', 'keypress', 'keyup']) wrap.addEventListener(ev, e => {
+ if (e.target.matches('input, textarea') && !(e.ctrlKey && e.altKey)) e.stopPropagation();
+ });
+}
+
+function inline(s) {
+ const codes = [];
+ s = bs.esc(s).replace(/`([^`]+)`/g, (_, c) => (codes.push(c), '\u0000' + (codes.length - 1) + '\u0000'));
+ s = s.replace(/\[([^\]]+)\]\(([^)\s]+)[^)]*\)/g, (_, t, u) => /^\s*javascript:/i.test(u) ? t : `${t} `)
+ .replace(/(\*\*|__)(.+?)\1/g, '$2 ')
+ .replace(/(^|[^*\w])[*_]([^*_]+)[*_](?=[^*\w]|$)/g, '$1$2 ')
+ .replace(/~~(.+?)~~/g, '$1');
+ return s.replace(/\u0000(\d+)\u0000/g, (_, i) => `${codes[i]}`);
+}
+
+async function read() {
+ try { return (await bs.api('file', { project: bs.S.project.path, file })).content || ''; }
+ catch { return null; }
+}
+async function write(text, exists) {
+ const project = bs.S.project.path;
+ if (exists) await bs.api('file', { project, file }, { method: 'PUT', body: text });
+ else await bs.api('file/new', { project }, { method: 'POST', body: JSON.stringify({ path: file, content: text }) });
+}
+
+function panel(el) {
+ el.innerHTML = `
+
+
Adicionar
+
+
Limpar feitas
+
`;
+ guardKeys(el.querySelector('.tk-wrap'));
+ const list = el.querySelector('.tk-list'), inp = el.querySelector('.tk-in'), proj = el.querySelector('.tk-proj'), openBtn = el.querySelector('.tk-open');
+ let lines = [], exists = false;
+
+ async function load() {
+ openBtn.textContent = 'Abrir ' + file;
+ if (!bs.S.project) { proj.textContent = 'Nenhum projeto aberto'; list.innerHTML = 'Abra um projeto para ver as tarefas.
'; return; }
+ const t = await read();
+ exists = t !== null;
+ lines = (t ?? '# Tarefas\n').replace(/\r/g, '').split('\n');
+ draw();
+ }
+ function draw() {
+ const items = lines.map((l, i) => [l.match(TASK), i]).filter(([m]) => m);
+ const open = items.filter(([m]) => m[2] === ' ').length;
+ proj.textContent = `${bs.S.project.name} · ${open} pendente${open === 1 ? '' : 's'}`;
+ list.innerHTML = items.length ? items.map(([m, i]) => `
+ ${inline(m[4])}
+ ${bs.I.x}
`).join('')
+ : 'Nenhuma tarefa ainda.
';
+ }
+ async function save() {
+ try { await write(lines.join('\n'), exists); exists = true; draw(); if (bs.S.active?.path === file) setTimeout(() => bs.mdVisual?.sync(), 0); }
+ catch (e) { bs.toast('Não deu para salvar as tarefas: ' + e.message); }
+ }
+ async function add() {
+ const t = inp.value.trim(); if (!t || !bs.S.project) return;
+ let last = -1; lines.forEach((l, i) => { if (TASK.test(l)) last = i; });
+ if (last < 0) { while (lines.length && !lines[lines.length - 1].trim()) lines.pop(); lines.push('', `- [ ] ${t}`, ''); }
+ else lines.splice(last + 1, 0, `- [ ] ${t}`);
+ inp.value = ''; await save();
+ }
+ inp.onkeydown = e => { if (e.key === 'Enter') add(); };
+ el.querySelector('.tk-add').onclick = add;
+ list.onclick = e => {
+ const row = e.target.closest('.tk-item'); if (!row) return;
+ const i = +row.dataset.i, m = lines[i].match(TASK);
+ if (e.target.closest('.tk-del')) lines.splice(i, 1);
+ else if (e.target.matches('.tk-chk')) lines[i] = m[1] + (m[2] === ' ' ? 'x' : ' ') + m[3] + m[4];
+ else return;
+ save();
+ };
+ el.querySelector('.tk-clean').onclick = () => { lines = lines.filter(l => { const m = l.match(TASK); return !m || m[2] === ' '; }); save(); };
+ openBtn.onclick = async () => {
+ if (!bs.S.project) return;
+ if (!exists) await save();
+ bs.openFile(file, 'editor');
+ };
+ redraw = () => list.isConnected && load();
+ load();
+}
+
+bs.tools.register({ id: 'tv-tarefas', title: 'Project Tasks', icon: ICON, order: 61, render() { panel(bs.$('#toolBody')); } });
+bs.hooks.on('project:select', () => redraw?.());
+bs.hooks.on('tab:save', () => { if (bs.S.active?.path === file) redraw?.(); });
+bs.keys.add('Ctrl+Alt+T', () => { const b = bs.$('#strip [data-tool="tv-tarefas"]'); if (b && !b.classList.contains('on')) b.click(); });
+plugin.onUnload(() => { redraw = null; });
diff --git a/plugins/sqlite-browser/README.md b/plugins/sqlite-browser/README.md
new file mode 100644
index 0000000..b39fb6c
--- /dev/null
+++ b/plugins/sqlite-browser/README.md
@@ -0,0 +1,33 @@
+# SQLite Browser
+
+
+| | |
+|---|---|
+| **Autor** | Pizzy-23 |
+| **Versão** | 0.1.0 |
+| **Licença** | MIT |
+| **Categoria** | Desenvolvimento |
+| **Precisa de** | nada além do BlueScreen |
+| **Código** | [plugins/sqlite-browser](https://github.com/martindevbr/BlueScreen-Plugins/tree/main/plugins/sqlite-browser) |
+
+
+Arquivos `.db`, `.sqlite`, `.sqlite3`, `.db3` e `.s3db` abrem numa aba própria, em vez do hexadecimal.
+
+## Como usar
+
+- À esquerda, as tabelas e views, com quantas linhas cada tabela tem. A estrutura (`CREATE TABLE`) aparece ao passar o mouse e embaixo dos dados.
+- Os dados vêm em páginas de 200 linhas, com **Anterior** e **Próxima**.
+- Um campo de SQL (`Ctrl+Enter` roda). Clique numa célula para copiar o valor, **Copiar CSV** copia o resultado.
+- Abre **só para leitura**. Para `INSERT`, `UPDATE`, `DELETE` ou `CREATE`, marque **Permitir alterar** na barra. A alteração vai direto para o arquivo.
+
+Precisa do Node.js 22.5 ou mais novo (tem o `node:sqlite` embutido). Se não tiver, baixe pela janela **SDKs e runtimes** da IDE.
+
+## Autor e licença
+
+Feito por Pizzy-23. Licença MIT (veja o campo `license` do `plugin.json`).
+
+## Histórico de versões
+
+### 0.1.0
+
+- Primeira versão na loja.
diff --git a/plugins/sqlite-browser/icon.svg b/plugins/sqlite-browser/icon.svg
new file mode 100644
index 0000000..a86745c
--- /dev/null
+++ b/plugins/sqlite-browser/icon.svg
@@ -0,0 +1 @@
+
diff --git a/plugins/sqlite-browser/plugin.json b/plugins/sqlite-browser/plugin.json
new file mode 100644
index 0000000..62f9577
--- /dev/null
+++ b/plugins/sqlite-browser/plugin.json
@@ -0,0 +1,18 @@
+{
+ "id": "sqlite-browser",
+ "name": "SQLite Browser",
+ "description": "Arquivos .db, .sqlite e .sqlite3 abrem numa aba com as tabelas e quantas linhas cada uma tem, os dados em páginas de 200, a estrutura de cada tabela e um campo para rodar SQL. Abre só para leitura, a menos que você marque Permitir alterar. Usa o Node.js 22.5+ (node:sqlite), sem instalar nada.",
+ "version": "0.1.0",
+ "author": "Pizzy-23",
+ "license": "MIT",
+ "category": "desenvolvimento",
+ "keywords": [
+ "sqlite",
+ "banco de dados",
+ "sql",
+ "db",
+ "tabelas"
+ ],
+ "icon": "icon.svg",
+ "order": 113
+}
diff --git a/plugins/sqlite-browser/style.css b/plugins/sqlite-browser/style.css
new file mode 100644
index 0000000..def7c81
--- /dev/null
+++ b/plugins/sqlite-browser/style.css
@@ -0,0 +1,23 @@
+.vw-sqlite { display: flex; flex-direction: column; height: 100%; min-height: 0; }
+.sq-rw { display: flex; align-items: center; gap: 4px; font-size: 12px; color: var(--fg-2); }
+.sq-main { flex: 1; min-height: 0; display: flex; }
+.sq-tables { width: 220px; flex: none; overflow: auto; border-right: 1px solid var(--line); padding: 6px; display: flex; flex-direction: column; gap: 1px; }
+.sq-t { display: flex; gap: 6px; align-items: center; background: none; border: 0; color: var(--fg); font: inherit; font-size: 12px; padding: 4px 6px; border-radius: 4px; cursor: pointer; text-align: left; }
+.sq-t:hover { background: var(--hover); } .sq-t.on { background: var(--sel); }
+.sq-tn { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.sq-tc { color: var(--muted); font-size: 11px; }
+.sq-right { flex: 1; min-width: 0; display: flex; flex-direction: column; }
+.sq-q { display: flex; gap: 6px; padding: 8px; border-bottom: 1px solid var(--line); }
+.sq-sql { flex: 1; min-height: 54px; resize: vertical; background: var(--bg); color: var(--fg); border: 1px solid var(--line-2); border-radius: 4px; padding: 6px; font: 12px/1.5 var(--mono); }
+.sq-out { flex: 1; min-height: 0; overflow: auto; padding: 8px; }
+.sq-meta { display: flex; gap: 8px; align-items: center; font-size: 11px; color: var(--muted); margin-bottom: 6px; }
+.sq-nav { display: flex; gap: 8px; align-items: center; font-size: 12px; margin-bottom: 6px; }
+.sq-msg { color: var(--fg-2); padding: 8px; }
+.sq-grid { border-collapse: collapse; font: 12px var(--mono); }
+.sq-grid th { position: sticky; top: 0; background: var(--panel-2); text-align: left; font-weight: 600; }
+.sq-grid th, .sq-grid td { border: 1px solid var(--line); padding: 3px 8px; white-space: nowrap; max-width: 420px; overflow: hidden; text-overflow: ellipsis; }
+.sq-grid tr:hover td { background: var(--hover); }
+.sq-grid td { cursor: copy; }
+.sq-null { color: var(--muted); } .sq-blob { color: var(--accent-2); }
+.sq-schema { margin-top: 10px; } .sq-schema summary { cursor: pointer; color: var(--fg-2); }
+.sq-schema pre { background: var(--panel-2); padding: 8px; border-radius: 4px; white-space: pre-wrap; font: 12px var(--mono); }
diff --git a/plugins/sqlite-browser/ui.js b/plugins/sqlite-browser/ui.js
new file mode 100644
index 0000000..6260f0c
--- /dev/null
+++ b/plugins/sqlite-browser/ui.js
@@ -0,0 +1,144 @@
+// Navegador de SQLite: .db/.sqlite abrem numa aba com as tabelas, os dados e um campo de SQL.
+// Quem lê o banco é o node:sqlite do Node.js (22.5+), rodado por `node -` com o script pela entrada padrão; nada de
+// biblioteca na página. Só leitura, a menos que a aba libere "Permitir alterar".
+const FV = bs.fileViewer; if (!FV) return;
+const { esc, toast } = bs;
+if (bs.S.remote) return;
+
+const EXT = ['sqlite', 'sqlite3', 'db', 'db3', 's3db', 'sl3'];
+const PAGE = 200;
+const RUNNER = String.raw`
+const { DatabaseSync } = require('node:sqlite');
+const out = (o) => process.stdout.write(JSON.stringify(o, (k, v) => typeof v === 'bigint' ? (Number.isSafeInteger(Number(v)) ? Number(v) : v.toString())
+ : v instanceof Uint8Array ? { blob: v.length, head: Buffer.from(v.subarray(0, 16)).toString('hex') } : v));
+try {
+ const db = new DatabaseSync(process.env.SQ_DB, { readOnly: process.env.SQ_RW !== '1' });
+ const max = +process.env.SQ_MAX || 500, res = [];
+ for (const sql of JSON.parse(process.env.SQ_SQL)) {
+ const st = db.prepare(sql);
+ const cols = st.columns ? st.columns().map(c => c.name) : null;
+ if (cols && cols.length) {
+ st.setReadBigInts?.(true);
+ const rows = []; let more = false;
+ for (const r of st.iterate()) { if (rows.length >= max) { more = true; break; } rows.push(cols.map(c => r[c])); }
+ res.push({ cols, rows, more });
+ } else {
+ const r = st.run();
+ res.push({ changes: Number(r.changes), lastId: r.lastInsertRowid });
+ }
+ }
+ db.close();
+ out({ ok: true, res });
+} catch (e) { out({ ok: false, error: e.message }); }
+`;
+
+const prevHex = FV.kinds.hex;
+FV.kinds.hex = prevHex.filter(e => !EXT.includes(e));
+FV.kinds.sqlite = EXT;
+FV.labels.sqlite = 'SQLite';
+
+const absOf = (t) => t.project.replace(/[\\/]$/, '') + '\\' + t.path.replace(/\//g, '\\');
+const qi = (n) => '"' + String(n).replace(/"/g, '""') + '"';
+
+async function run(t, sqls, rw) {
+ const r = await plugin.exec('node', ['-'], {
+ stdin: RUNNER, timeout: 60000,
+ env: { SQ_DB: absOf(t), SQ_SQL: JSON.stringify(sqls), SQ_RW: rw ? '1' : '0', SQ_MAX: String(PAGE), NODE_NO_WARNINGS: '1' },
+ });
+ let j; try { j = JSON.parse(r.out); } catch {
+ const e = (r.err || r.out || '').trim();
+ throw new Error(/node:sqlite|ERR_UNKNOWN_BUILTIN_MODULE/.test(e) ? 'Precisa do Node.js 22.5 ou mais novo (baixe pela janela SDKs).' : e.split(/\r?\n/).slice(-3).join(' ') || 'o Node.js não respondeu');
+ }
+ if (!j.ok) throw new Error(j.error);
+ return j.res;
+}
+
+function cell(v) {
+ if (v === null) return 'NULL ';
+ if (v && typeof v === 'object' && 'blob' in v) return `blob ${FV.size(v.blob)} `;
+ const s = String(v);
+ return s.length > 160 ? `${esc(s.slice(0, 160))}… ` : esc(s);
+}
+function grid(r) {
+ if (!r.cols) return `${r.changes} linha${r.changes === 1 ? '' : 's'} alterada${r.changes === 1 ? '' : 's'}${r.lastId ? ' · último id ' + esc(String(r.lastId)) : ''}
`;
+ if (!r.rows.length) return 'Nenhuma linha.
';
+ return `${r.cols.map(c => `${esc(c)} `).join('')} ${r.rows.map((row, i) => `${row.map((v, k) => `${cell(v)} `).join('')} `).join('')}
`;
+}
+const csv = (r) => [r.cols, ...r.rows].map(row => row.map(v => v === null ? '' : typeof v === 'object' ? `blob(${v.blob})` : /[",\n;]/.test(String(v)) ? '"' + String(v).replace(/"/g, '""') + '"' : String(v)).join(',')).join('\r\n');
+
+async function loadTables(t) {
+ const q = t.sq, list = t.el.querySelector('.sq-tables');
+ list.innerHTML = '
';
+ try {
+ const [m] = await run(t, ["SELECT name, type, sql FROM sqlite_master WHERE type IN ('table','view') AND name NOT LIKE 'sqlite_%' ORDER BY type, name"]);
+ q.tables = m.rows.map(([name, type, sql]) => ({ name, type, sql }));
+ const counts = q.tables.length <= 300 ? await run(t, q.tables.map(x => `SELECT count(*) FROM ${qi(x.name)}`)).catch(() => []) : [];
+ counts.forEach((c, i) => { q.tables[i].count = c.rows?.[0]?.[0]; });
+ list.innerHTML = q.tables.length ? q.tables.map((x, i) => `
+ ${esc(x.name)} ${x.type === 'view' ? 'view' : x.count != null ? Number(x.count).toLocaleString('pt-BR') : ''} `).join('')
+ : 'Banco vazio.
';
+ if (!q.cur && q.tables[0]) browse(t, q.tables[0].name, 0);
+ } catch (e) { list.innerHTML = `${esc(e.message)}
`; }
+}
+
+async function browse(t, name, off) {
+ const q = t.sq; q.cur = name; q.off = off;
+ t.el.querySelectorAll('.sq-t').forEach(b => b.classList.toggle('on', q.tables[+b.dataset.i]?.name === name));
+ const tb = q.tables.find(x => x.name === name);
+ t.el.querySelector('.sq-sql').value = `SELECT * FROM ${qi(name)} LIMIT ${PAGE} OFFSET ${off}`;
+ await exec(t, { page: true, total: tb?.count, schema: tb?.sql });
+}
+
+async function exec(t, o = {}) {
+ const q = t.sq, sql = t.el.querySelector('.sq-sql').value.trim(), out = t.el.querySelector('.sq-out');
+ if (!sql) return;
+ if (sql.length > 30000) { toast('SQL grande demais (máx. 30 mil caracteres)'); return; }
+ if (!o.page) q.cur = null;
+ out.innerHTML = ' Rodando…
';
+ const t0 = performance.now();
+ try {
+ const res = await run(t, [sql], q.rw);
+ const r = q.last = res[res.length - 1], ms = Math.round(performance.now() - t0);
+ let nav = '';
+ if (o.page && r.cols) {
+ const end = q.off + r.rows.length, total = o.total != null ? Number(o.total) : null;
+ nav = `‹ Anterior
+ ${(q.off + 1).toLocaleString('pt-BR')}–${end.toLocaleString('pt-BR')}${total != null ? ' de ' + total.toLocaleString('pt-BR') : ''}
+ Próxima ›
`;
+ }
+ out.innerHTML = `${ms} ms${r.more && !o.page ? ` · só as primeiras ${PAGE} linhas` : ''}${r.cols ? 'Copiar CSV ' : ''}
${nav}${grid(r)}${o.schema ? `Estrutura ${esc(o.schema)} ` : ''}`;
+ if (!r.cols) loadTables(t);
+ } catch (e) { out.innerHTML = `${esc(e.message)}${/readonly/i.test(e.message) ? ' Marque "Permitir alterar" para gravar no banco.' : ''}
`; }
+}
+
+FV.custom.sqlite = {
+ build(t, el) {
+ t.sq = { tables: [], cur: null, off: 0, rw: false, last: null };
+ el.innerHTML = FV.bar(t, ` Permitir alterar${bs.I.refresh} `)
+ + ``;
+ el.querySelector('[data-a="reveal"]').onclick = () => FV.act(t, 'reveal');
+ const sql = el.querySelector('.sq-sql');
+ for (const ev of ['keydown', 'keyup', 'keypress']) sql.addEventListener(ev, e => e.stopPropagation());
+ sql.addEventListener('keydown', e => { if (e.key === 'Enter' && e.ctrlKey) { e.preventDefault(); exec(t); } });
+ el.querySelector('.sq-run').onclick = () => exec(t);
+ el.querySelector('.sq-ref').onclick = () => loadTables(t);
+ el.querySelector('.sq-rwc').onchange = (e) => { t.sq.rw = e.target.checked; if (t.sq.rw) toast('Alterações vão direto para o arquivo. Faça uma cópia antes se for importante.'); };
+ el.querySelector('.sq-tables').onclick = (e) => { const b = e.target.closest('.sq-t'); if (b) browse(t, t.sq.tables[+b.dataset.i].name, 0); };
+ el.querySelector('.sq-out').onclick = async (e) => {
+ const pg = e.target.closest('[data-pg]'); if (pg && t.sq.cur) return browse(t, t.sq.cur, Math.max(0, t.sq.off + +pg.dataset.pg * PAGE));
+ if (e.target.closest('.sq-csv') && t.sq.last?.cols) { await navigator.clipboard.writeText(csv(t.sq.last)); toast('CSV copiado', 'ok'); return; }
+ const td = e.target.closest('td[data-c]'); const r = t.sq.last;
+ if (td && r?.rows) { const v = r.rows[+td.parentElement.dataset.r][+td.dataset.c]; if (v !== null && typeof v !== 'object') { await navigator.clipboard.writeText(String(v)); toast('Valor copiado', 'ok'); } }
+ };
+ loadTables(t);
+ },
+ reload(t) { if (t.el && t.sq) { loadTables(t); if (t.sq.cur) browse(t, t.sq.cur, t.sq.off); } },
+};
+
+plugin.onUnload(() => {
+ FV.kinds.hex = [...new Set([...FV.kinds.hex, ...prevHex.filter(e => EXT.includes(e))])];
+ delete FV.kinds.sqlite; delete FV.custom.sqlite;
+ bs.S.tabs.filter(x => x.kind === 'sqlite').forEach(x => { x.kind = 'hex'; x.el?.remove(); x.el = null; });
+});
diff --git a/plugins/web-scraper/README.md b/plugins/web-scraper/README.md
new file mode 100644
index 0000000..0eb44de
--- /dev/null
+++ b/plugins/web-scraper/README.md
@@ -0,0 +1,104 @@
+# Web Scraper
+
+
+| | |
+|---|---|
+| **Autor** | Pizzy-23 |
+| **Versão** | 0.3.1 |
+| **Licença** | MIT |
+| **Categoria** | Desenvolvimento |
+| **Precisa de** | nada além do BlueScreen |
+| **Código** | [plugins/web-scraper](https://github.com/martindevbr/BlueScreen-Plugins/tree/main/plugins/web-scraper) |
+
+
+Raspagem de páginas da web sem escrever código. Você clica na página para dizer o que é cada item (um produto, uma linha de tabela, um post) e o que tirar de cada um (texto, link, imagem); o plugin mostra a tabela na hora, segue as próximas páginas e exporta em CSV ou JSON. Páginas montadas por JavaScript abrem num navegador de verdade, sem janela, que também mostra todas as requisições que a página fez: achou a API com os dados, um clique e ela vira a fonte da raspagem.
+
+## Como usar
+
+O ícone **Web Scraper** na barra da esquerda lista as receitas e abre a tela na aba fixa. Também em **Buscar em tudo**: "Web Scraper: abrir".
+
+### Para começar: os exemplos
+
+**Exemplos**, no painel da esquerda, acrescenta três receitas prontas, uma de cada jeito de raspar:
+
+| Receita | O que mostra |
+|---|---|
+| **livros** | HTML comum: item e campos por seletor CSS e o botão de próxima página (books.toscrape.com, um site feito para treinar) |
+| **frases com rolagem infinita** | página montada por JavaScript, aberta no navegador e rolada até o fim (quotes.toscrape.com) |
+| **MangaDex, os mais seguidos** | API pública em JSON, com caminhos (`attributes.title.*`, `attributes.tags.*.attributes.name.en`) e paginação por `{offset:20}` |
+
+Abra uma, clique em **Testar na 1ª página** e depois em **Raspar tudo**.
+
+### O caminho mais fácil
+
+1. Cole a URL e clique em **Escolher clicando na página**. A página aparece dentro da tela.
+2. **Escolher o item** e clique em qualquer parte de um produto: o plugin entende que o produto inteiro é o item e marca todos em azul.
+3. Em seguida, clique no que quer em cada coluna (o título, o preço, a foto, o link). Cada clique vira um campo: link pega o endereço, imagem pega o `src`, o resto pega o texto.
+4. **Testar na 1ª página** e confira a tabela; ajuste o nome das colunas se quiser.
+5. **Raspar tudo** e depois **Copiar CSV**, **Copiar JSON** ou **Salvar no projeto** (o caminho termina em `.csv` ou `.json`; se o arquivo já existe, o botão pede um segundo clique).
+
+### Páginas com JavaScript e as requisições
+
+Se o teste diz que a página está quase vazia (lojas, SPAs, rolagem infinita), marque **Abrir num navegador de verdade**. O plugin abre o Chrome ou o Edge do PC sem janela, espera a página carregar e o item aparecer, rola até o fim quantas vezes você pedir (**Rolar até o fim**) e raspa o HTML já montado.
+
+Nesse modo, **Requisições da página** lista tudo o que a página pediu. **só dados** mostra só as chamadas de API (XHR, fetch, JSON), e o campo de filtro procura também dentro das respostas: digite um preço ou um nome que aparece na tela para achar a API que trouxe. Clicando numa requisição:
+
+- **Usar esta API** cria uma receita nova que chama a API direto (mais rápido e sem navegador), com o mesmo método, corpo e headers, e já sugere o item (a maior lista do JSON) e as colunas;
+- **Copiar como curl** e **Copiar resposta**.
+
+### Em detalhe
+
+- **URLs**: uma por linha. `{pagina}` na URL (ou no corpo do pedido) vira 1, 2, 3..., e `{offset:20}` vira 0, 20, 40..., até vir uma página sem linhas ou chegar ao **Máx. de páginas**.
+- **Item**: seletor CSS (`article.produto`, `table tbody tr`) ou, quando a resposta é JSON, o caminho da lista (`data.items`). Vazio, a página toda vira uma linha.
+- **Campos**: nome da coluna, seletor dentro do item (ou caminho JSON: `preco.valor`, `fotos.0.url`; `*` passa por todos os itens de uma lista ou valores de um objeto, como `tags.*.nome`) e, no HTML, o que pegar: `text`, `html`, `href`, `src` ou outro atributo. Links viram endereço completo. **todos** junta todos os que casarem, separados por `|`.
+- **Paginação e ritmo**: **Próxima página** é o seletor do link para a seguinte (`a[rel=next]`) ou, em JSON, o caminho da URL seguinte (`links.next`). O plugin não repete página e espera a **Espera entre páginas** entre um pedido e outro. Com mais de uma página, a tabela ganha a coluna `_pagina`.
+- **Pedido**: método, headers (um por linha) e corpo, para APIs. Valem quando o navegador está desligado.
+- **Testar um seletor** mostra quantos elementos casam na 1ª página e o HTML dos 5 primeiros (ou o valor do caminho, em JSON).
+
+## Configurações
+
+Aba Plugins › engrenagem do Web Scraper:
+
+| Configuração | O que muda |
+|---|---|
+| **User-Agent** | como o pedido se apresenta ao site (também no navegador sem janela) |
+| **Tempo limite de cada página** | segundos até desistir de uma página |
+| **Navegador (Chrome ou Edge)** | o caminho do `chrome.exe` ou `msedge.exe`, se o plugin não achar sozinho |
+
+## Limites conhecidos
+
+- O navegador sem janela precisa do Chrome ou do Edge instalados (o Edge já vem no Windows). Ele fica aberto 2 minutos depois do último uso, para os testes seguintes serem rápidos, e fecha sozinho.
+- Não faz login nem passa por CAPTCHA. Para uma API que precisa de login, **Usar esta API** copia os headers que a página mandou (inclusive cookies e tokens) para a receita: eles ficam guardados na pasta de dados do plugin.
+- O seletor visual mostra a página sem os scripts dela; num site que monta tudo por JavaScript, use **Abrir num navegador de verdade** antes, para ver a página montada.
+- Alguns sites mandam pedidos com cara de navegador falso para uma verificação anti-robô, que o plugin não tenta passar. Em APIs públicas, como a do MangaDex, um `User-Agent` que diga quem é (em **Pedido**) costuma resolver.
+- Respeite os termos de uso e o `robots.txt` de cada site e use uma espera entre páginas para não sobrecarregar o servidor.
+
+## Segurança e dados
+
+Os pedidos saem do seu PC direto para os sites da lista: pelo núcleo da IDE (`plugin.fetch`) ou pelo navegador sem janela, que usa um perfil próprio na pasta de dados do plugin (não mexe no seu Chrome ou Edge) e só aceita conexão da IDE. As receitas ficam na pasta de dados do plugin; o resultado só sai quando você copia ou salva.
+
+## Autor e licença
+
+Feito por Pizzy-23. Licença MIT (veja o campo `license` do `plugin.json`).
+
+## Histórico de versões
+
+### 0.3.1
+
+- Os botões agora parecem botões (usam o estilo `chip` da IDE, com borda; os principais em destaque).
+
+### 0.3.0
+
+- **Exemplos**: três receitas prontas (HTML com paginação, página com JavaScript, API do MangaDex).
+- `*` nos caminhos JSON e paginação por deslocamento com `{offset:N}`.
+
+### 0.2.0
+
+- Seletor visual: clique na página para escolher o item e os campos.
+- Abrir num navegador de verdade (Chrome ou Edge sem janela): páginas com JavaScript, rolagem infinita e a lista de requisições da página.
+- **Usar esta API**: uma requisição capturada vira receita, com item e colunas sugeridos.
+- Respostas em JSON com caminhos (`data.items`, `preco.valor`), `{pagina}` na URL e no corpo, método, headers e corpo do pedido.
+
+### 0.1.0
+
+- Primeira versão: receitas com item e campos por seletor CSS, teste na 1ª página, paginação, charset da página, CSV/JSON e salvar no projeto.
diff --git a/plugins/web-scraper/icon.svg b/plugins/web-scraper/icon.svg
new file mode 100644
index 0000000..6010f93
--- /dev/null
+++ b/plugins/web-scraper/icon.svg
@@ -0,0 +1 @@
+
diff --git a/plugins/web-scraper/plugin.json b/plugins/web-scraper/plugin.json
new file mode 100644
index 0000000..bf36adb
--- /dev/null
+++ b/plugins/web-scraper/plugin.json
@@ -0,0 +1,44 @@
+{
+ "id": "web-scraper",
+ "name": "Web Scraper",
+ "description": "Raspagem da web sem código: clique na página para escolher itens e campos, abra num navegador de verdade (páginas com JavaScript), veja as requisições que ela faz e transforme uma API em fonte com um clique. Paginação, CSV e JSON.",
+ "version": "0.3.1",
+ "author": "Pizzy-23",
+ "license": "MIT",
+ "category": "desenvolvimento",
+ "keywords": [
+ "scraping",
+ "webscraping",
+ "raspagem",
+ "crawler",
+ "css",
+ "seletor",
+ "csv",
+ "api",
+ "json",
+ "headless",
+ "devtools"
+ ],
+ "icon": "icon.svg",
+ "order": 117,
+ "settings": [
+ {
+ "key": "userAgent",
+ "label": "User-Agent",
+ "default": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0 Safari/537.36",
+ "help": "Como o pedido se apresenta ao site"
+ },
+ {
+ "key": "timeout",
+ "label": "Tempo limite de cada página (segundos)",
+ "type": "number",
+ "default": 20
+ },
+ {
+ "key": "browser",
+ "label": "Navegador (Chrome ou Edge)",
+ "placeholder": "achado sozinho",
+ "help": "Caminho do chrome.exe ou msedge.exe, se o plugin não achar sozinho. Usado em Abrir num navegador de verdade."
+ }
+ ]
+}
diff --git a/plugins/web-scraper/style.css b/plugins/web-scraper/style.css
new file mode 100644
index 0000000..d683bd3
--- /dev/null
+++ b/plugins/web-scraper/style.css
@@ -0,0 +1,68 @@
+.rw-page { overflow: auto; height: 100%; }
+.rw-wrap { display: flex; flex-direction: column; gap: 8px; padding: 12px; max-width: 1100px; box-sizing: border-box; }
+.rw-side { display: flex; flex-direction: column; gap: 6px; padding: 8px; }
+.rw-list { display: flex; flex-direction: column; gap: 1px; }
+.rw-ritem { display: flex; gap: 6px; align-items: center; background: none; border: 0; color: var(--fg); font: inherit; font-size: 12px; padding: 5px 6px; border-radius: 4px; cursor: pointer; text-align: left; min-width: 0; }
+.rw-ritem span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.rw-ritem:hover { background: var(--hover); } .rw-ritem.on { background: var(--sel); }
+.rw-row { display: flex; gap: 6px; align-items: center; flex-wrap: wrap; }
+.rw-sp { flex: 1; }
+.rw-in { min-width: 0; background: var(--bg); color: var(--fg); border: 1px solid var(--line-2); border-radius: 4px; padding: 5px 8px; font: inherit; box-sizing: border-box; }
+.rw-name { flex: 1; font-weight: 600; }
+.rw-ta { min-height: 54px; resize: vertical; }
+.rw-urls, .rw-item, .rw-fsel, .rw-next, .rw-probe, .rw-ta { font-family: var(--mono); font-size: 12px; }
+.rw-lbl { color: var(--fg-2); font-size: 12px; margin-bottom: -4px; }
+.rw-lbl span { color: var(--muted); font-size: 11px; }
+.rw-lbl2 { color: var(--fg-2); font-size: 12px; }
+.rw-fields { display: flex; flex-direction: column; gap: 4px; }
+.rw-field { display: flex; gap: 6px; align-items: center; }
+.rw-fname { width: 130px; } .rw-fsel { flex: 1; } .rw-fattr { width: 100px; }
+.rw-next { flex: 1; } .rw-pages, .rw-delay { width: 90px; }
+.rw-chk { display: flex; gap: 3px; align-items: center; font-size: 12px; color: var(--fg-2); }
+.rw-count { font-size: 11px; color: var(--muted); min-width: 80px; }
+.rw-count.bad { color: #f85149; }
+.rw-del { padding: 2px 8px; }
+.rw-more summary { cursor: pointer; color: var(--fg-2); font-size: 12px; }
+.rw-more[open] { display: flex; flex-direction: column; gap: 6px; }
+.rw-status { font-size: 12px; color: var(--fg-2); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 60%; }
+.rw-out { flex: 1; font-family: var(--mono); font-size: 12px; }
+.rw-pre { margin: 0; max-height: 260px; overflow: auto; background: var(--panel-2); color: var(--fg); border: 1px solid var(--line); border-radius: 4px; padding: 8px; font: 12px var(--mono); white-space: pre-wrap; word-break: break-word; }
+.rw-pre:empty { display: none; }
+.rw-meta { font-size: 12px; color: var(--fg-2); margin-bottom: 6px; }
+.rw-err { color: #f85149; font-size: 12px; margin-bottom: 6px; }
+.rw-msg { color: var(--fg-2); padding: 8px 0; font-size: 12px; }
+.rw-res { overflow: auto; }
+.rw-grid { border-collapse: collapse; font: 12px var(--mono); }
+.rw-grid th { position: sticky; top: 0; background: var(--panel-2); text-align: left; font-weight: 600; }
+.rw-grid th, .rw-grid td { border: 1px solid var(--line); padding: 3px 8px; white-space: nowrap; max-width: 360px; overflow: hidden; text-overflow: ellipsis; }
+.rw-grid tr:hover td { background: var(--hover); }
+.rw-n { color: var(--muted); }
+
+.rw-hint { color: var(--muted); font-size: 11px; }
+.rw-mode { background: var(--panel-2); border: 1px solid var(--line); border-radius: 4px; padding: 6px 8px; }
+.rw-scrolls { width: 60px; }
+.rw-method { width: 100px; }
+.rw-headers, .rw-body { min-height: 60px; }
+.rw-lbl code, .rw-hint code, .rw-msg code { font-family: var(--mono); color: var(--accent-2); }
+.rw-frame { width: 100%; height: 460px; border: 1px solid var(--line-2); border-radius: 4px; background: #fff; margin-top: 6px; }
+.rw-pickbox:empty { display: none; }
+
+.rw-reqlist { display: flex; flex-direction: column; gap: 1px; max-height: 280px; overflow: auto; margin-top: 4px; border: 1px solid var(--line); border-radius: 4px; }
+.rw-req { display: flex; gap: 8px; align-items: center; background: none; border: 0; color: var(--fg); font: 12px var(--mono); padding: 3px 6px; cursor: pointer; text-align: left; min-width: 0; }
+.rw-req:hover { background: var(--hover); } .rw-req.on { background: var(--sel); }
+.rw-rm { width: 44px; flex: none; color: var(--accent-2); font-weight: 600; }
+.rw-rs { width: 34px; flex: none; color: #3fb950; } .rw-rs.bad { color: #f85149; }
+.rw-rt { width: 70px; flex: none; color: var(--muted); }
+.rw-ru { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.rw-rz { flex: none; color: var(--muted); }
+.rw-reqdet:not(:empty) { display: flex; flex-direction: column; gap: 6px; margin-top: 8px; }
+.rw-reqq { flex: 1; }
+.rw-resp { max-height: 360px; }
+.rw-page .chip, .rw-side .chip { border: 1px solid var(--line-2); background: var(--panel-2); color: var(--fg); cursor: pointer; font: inherit; }
+.rw-page .chip:hover:not(:disabled), .rw-side .chip:hover { background: var(--hover); border-color: var(--accent); }
+.rw-page .chip.primary { background: var(--accent); border-color: var(--accent); color: var(--on-accent); }
+.rw-page .chip.primary:hover:not(:disabled) { background: var(--accent-2); }
+.rw-page .chip:disabled { opacity: .45; cursor: default; }
+.rw-page .chip.on { outline: 2px solid var(--accent); outline-offset: 1px; }
+.rw-page .chip.danger { color: #f85149; border-color: #f85149; }
+.rw-del { padding: 0 8px; height: 24px; }
diff --git a/plugins/web-scraper/ui.js b/plugins/web-scraper/ui.js
new file mode 100644
index 0000000..be24b18
--- /dev/null
+++ b/plugins/web-scraper/ui.js
@@ -0,0 +1,779 @@
+const RW_ICON = ' ';
+const RW_ATTRS = ['text', 'html', 'href', 'src', 'content', 'title', 'alt', 'value', 'datetime', 'data-src'];
+const RW_URLATTR = /^(href|src|action|poster|data-src|data-href)$/i;
+const RW_MAXPAGES = 500;
+const RW_PAGEVAR = /\{(pagina|offset:\d+)\}/;
+// {pagina} vira 1, 2, 3...; {offset:20} vira 0, 20, 40... (APIs que paginam por deslocamento)
+const rwPageSub = (s, p) => String(s).replace(/\{(pagina|offset:(\d+))\}/g, (m, k, n) => n ? (p - 1) * n : p);
+
+// A barra da esquerda tem atalhos próprios que engoliam o que se digitava nos campos.
+function rwGuardKeys(wrap) {
+ for (const ev of ['keydown', 'keypress', 'keyup']) wrap.addEventListener(ev, e => {
+ if (e.target.matches('input, textarea') && !(e.ctrlKey && e.altKey)) e.stopPropagation();
+ });
+}
+
+let rw = null, rwTimer = 0, rwPage = null, rwRun = null;
+const rwRes = new Map();
+const rwId = () => 'r' + Date.now().toString(36) + Math.random().toString(36).slice(2, 6);
+const rwNew = (o = {}) => ({ id: rwId(), name: 'Nova receita', urls: '', item: '', fields: [{ name: 'titulo', sel: 'h1', attr: 'text', all: false }],
+ next: '', pages: 1, delay: 1000, out: '', browser: false, scrolls: 0, method: 'GET', headers: '', body: '', ...o });
+const rwCur = () => rw.recipes.find(r => r.id === rw.cur);
+const rwF = (name, sel, attr = 'text', all = false) => ({ name, sel, attr, all });
+// Um exemplo de cada jeito de raspar, para aprender mexendo (botão Exemplos).
+const RW_EXAMPLES = () => [
+ rwNew({ name: 'Exemplo: livros (HTML com paginação)', urls: 'https://books.toscrape.com/', item: 'article.product_pod',
+ fields: [rwF('titulo', 'h3 a', 'title'), rwF('preco', '.price_color'), rwF('estoque', '.availability'), rwF('link', 'h3 a', 'href'), rwF('capa', 'img', 'src')],
+ next: 'li.next a', pages: 3, delay: 500 }),
+ rwNew({ name: 'Exemplo: frases com rolagem infinita (navegador)', urls: 'https://quotes.toscrape.com/scroll', browser: true, scrolls: 2, item: '.quote',
+ fields: [rwF('frase', '.text'), rwF('autor', '.author'), rwF('tags', '.tag', 'text', true)] }),
+ // A API do MangaDex manda User-Agent de navegador falso para uma verificação anti-robô e pede um que diga quem é.
+ rwNew({ name: 'Exemplo: MangaDex, os mais seguidos (API)',
+ urls: 'https://api.mangadex.org/manga?limit=20&offset={offset:20}&order%5BfollowedCount%5D=desc&contentRating%5B%5D=safe',
+ headers: 'User-Agent: web-scraper (BlueScreen plugin)', item: 'data', pages: 3, delay: 1000,
+ fields: [rwF('titulo', 'attributes.title.*'), rwF('ano', 'attributes.year'), rwF('status', 'attributes.status'),
+ rwF('ultimo_capitulo', 'attributes.lastChapter'), rwF('tags', 'attributes.tags.*.attributes.name.en'), rwF('id', 'id')] }),
+];
+
+async function rwLoad() {
+ if (rw) return rw;
+ let d = null;
+ try { d = await plugin.data.get('raspador', null); } catch (e) { bs.toast('Não deu para ler as receitas: ' + e.message); }
+ rw = d?.recipes?.length ? d : { recipes: [rwNew()] };
+ rw.recipes = rw.recipes.map(r => rwNew(r));
+ if (!rw.recipes.some(r => r.id === rw.cur)) rw.cur = rw.recipes[0].id;
+ return rw;
+}
+const rwFlush = () => { clearTimeout(rwTimer); rwTimer = 0; return plugin.data.set('raspador', rw).catch(e => bs.toast('Não deu para salvar: ' + e.message)); };
+const rwSave = () => { clearTimeout(rwTimer); rwTimer = setTimeout(rwFlush, 400); };
+plugin.onUnload(() => { if (rwTimer) rwFlush(); if (rwRun) rwRun.stop = true; rwBClose(); });
+
+const rwSleep = ms => new Promise(ok => setTimeout(ok, ms));
+const rwSettings = () => plugin.settings.get().catch(() => ({}));
+const rwHeader = (h, name) => {
+ if (!h) return '';
+ if (Array.isArray(h)) { const x = h.find(p => String(p[0]).toLowerCase() === name); return x ? x[1] : ''; }
+ const k = Object.keys(h).find(k => k.toLowerCase() === name);
+ return k ? h[k] : '';
+};
+const rwHeaderLines = s => {
+ const h = {};
+ for (const l of String(s || '').split('\n')) { const i = l.indexOf(':', 1); if (i > 0) h[l.slice(0, i).trim()] = l.slice(i + 1).trim(); }
+ return h;
+};
+const rwTryJson = s => { try { return JSON.parse(s); } catch { return undefined; } };
+
+// ---------- busca direta (como o curl) ----------
+// Busca como bytes para respeitar o charset da página (muito site brasileiro ainda é ISO-8859-1).
+async function rwFetch(url, r = {}) {
+ const set = await rwSettings();
+ const method = r.method || 'GET';
+ const opt = {
+ method, as: 'base64', timeout: (+set.timeout || 20) * 1000,
+ headers: { 'User-Agent': set.userAgent || 'Mozilla/5.0', Accept: 'text/html,application/xhtml+xml,application/json,*/*;q=0.8', 'Accept-Language': 'pt-BR,pt;q=0.9,en;q=0.8', ...rwHeaderLines(r.headers) },
+ };
+ if (r.body && !/^(GET|HEAD)$/i.test(method)) opt.body = r.body;
+ const res = await plugin.fetch(url, opt);
+ if (!res.ok) throw new Error(`HTTP ${res.status} em ${url}`);
+ let text = res.body || '';
+ const ct = rwHeader(res.headers, 'content-type');
+ if (res.bodyBase64 != null) {
+ const bytes = Uint8Array.from(atob(res.bodyBase64), c => c.charCodeAt(0));
+ const cs = /charset=["']?([\w-]+)/i.exec(ct)?.[1]
+ || / ]+charset=["']?([\w-]+)/i.exec(new TextDecoder('latin1').decode(bytes.slice(0, 4096)))?.[1] || 'utf-8';
+ try { text = new TextDecoder(cs).decode(bytes); } catch { text = new TextDecoder().decode(bytes); }
+ }
+ if (/json/i.test(ct) || /^\s*[[{]/.test(text)) {
+ const json = rwTryJson(text);
+ if (json !== undefined) return { json, url, base: url, size: text.length };
+ }
+ return rwParse(text, url);
+}
+function rwParse(html, url) {
+ const doc = new DOMParser().parseFromString(html, 'text/html');
+ let base = url;
+ const b = doc.querySelector('base[href]')?.getAttribute('href');
+ if (b) try { base = new URL(b, url).href; } catch {}
+ return { doc, html, base, url, size: html.length };
+}
+
+// ---------- navegador sem janela (Chrome ou Edge pelo DevTools Protocol) ----------
+let rwB = null, rwBIdle = 0;
+async function rwFindBrowser() {
+ const set = await rwSettings();
+ if (set.browser?.trim()) return set.browser.trim();
+ if (/Windows/i.test(navigator.userAgent)) {
+ const ps = '@("$env:ProgramFiles\\Google\\Chrome\\Application\\chrome.exe","${env:ProgramFiles(x86)}\\Google\\Chrome\\Application\\chrome.exe",'
+ + '"$env:LOCALAPPDATA\\Google\\Chrome\\Application\\chrome.exe","${env:ProgramFiles(x86)}\\Microsoft\\Edge\\Application\\msedge.exe",'
+ + '"$env:ProgramFiles\\Microsoft\\Edge\\Application\\msedge.exe") | Where-Object { Test-Path $_ } | Select-Object -First 1';
+ const r = await plugin.exec('powershell', ['-NoProfile', '-NonInteractive', '-Command', ps], { timeout: 15000 }).catch(() => null);
+ if (r?.out?.trim()) return r.out.trim();
+ } else {
+ for (const p of ['/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', '/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge']) {
+ const r = await plugin.exec('test', ['-x', p]).catch(() => null);
+ if (r?.ok) return p;
+ }
+ for (const n of ['google-chrome', 'google-chrome-stable', 'chromium', 'chromium-browser', 'microsoft-edge']) {
+ const r = await plugin.exec('which', [n]).catch(() => null);
+ if (r?.ok && r.out.trim()) return r.out.trim();
+ }
+ }
+ throw new Error('Não achei o Chrome nem o Edge. Indique o caminho nas configurações do plugin.');
+}
+
+function rwCdp(url) {
+ return new Promise((ok, fail) => {
+ const ws = new WebSocket(url), wait = new Map(), subs = new Set();
+ let n = 0;
+ const c = {
+ send(method, params = {}, sessionId) {
+ const id = ++n;
+ ws.send(JSON.stringify({ id, method, params, sessionId }));
+ return new Promise((ok2, fail2) => wait.set(id, { ok: ok2, fail: fail2 }));
+ },
+ on(f) { subs.add(f); return () => subs.delete(f); },
+ close() { try { ws.close(); } catch {} },
+ };
+ ws.onopen = () => ok(c);
+ ws.onerror = () => fail(new Error('Não deu para conectar no navegador'));
+ ws.onclose = () => { for (const w of wait.values()) w.fail(new Error('A conexão com o navegador caiu')); wait.clear(); if (rwB?.cdp === c) rwB = null; };
+ ws.onmessage = e => {
+ const m = JSON.parse(e.data);
+ if (m.id && wait.has(m.id)) { const w = wait.get(m.id); wait.delete(m.id); m.error ? w.fail(new Error(m.error.message)) : w.ok(m.result); }
+ else if (m.method) for (const f of subs) f(m);
+ };
+ });
+}
+
+async function rwLaunch(onStatus) {
+ const exe = await rwFindBrowser();
+ // Processos de uma sessão anterior da IDE seguram a pasta do perfil: sem isso o navegador novo fecharia na hora.
+ for (const p of await plugin.procs.list().catch(() => [])) { try { await plugin.procs.attach(p.id ?? p, {}).kill(); } catch {} }
+ const prof = (await plugin.info()).dataDir.replace(/[\\/]+$/, '') + '/navegador';
+ onStatus('Abrindo o navegador');
+ let got, lost, buf = '';
+ const wsUrl = new Promise((a, b) => { got = a; lost = b; });
+ const proc = await plugin.spawn(exe, ['--headless=new', '--remote-debugging-port=0', '--remote-allow-origins=' + location.origin, '--user-data-dir=' + prof,
+ '--no-first-run', '--no-default-browser-check', '--disable-gpu', '--mute-audio', '--window-size=1366,900', 'about:blank'], {
+ label: 'Web Scraper: navegador',
+ onData(t) { buf += t; const m = /DevTools listening on (ws:\/\/\S+)/.exec(buf); if (m) got(m[1]); },
+ onExit(code) { lost(new Error(`O navegador fechou (código ${code}). ${buf.slice(-300)}`)); if (rwB?.proc === proc) rwB = null; },
+ });
+ const t = setTimeout(() => lost(new Error('O navegador não respondeu em 20 s')), 20000);
+ try { return { proc, cdp: await rwCdp(await wsUrl) }; }
+ catch (e) { proc.kill().catch(() => {}); throw e; }
+ finally { clearTimeout(t); }
+}
+function rwBClose() {
+ clearTimeout(rwBIdle);
+ const b = rwB; rwB = null;
+ if (!b) return;
+ b.cdp.send('Browser.close').catch(() => {}).finally(() => b.cdp.close());
+ setTimeout(() => b.proc.kill().catch(() => {}), 2000);
+}
+
+const rwIsData = q => q.type === 'XHR' || q.type === 'Fetch' || /json|graphql/i.test(q.mime || '');
+
+// Abre a URL numa aba sem janela, espera a rede acalmar (e o item aparecer), rola se pedido e devolve o HTML já montado
+// e todas as requisições que a página fez, com a resposta das de dados.
+async function rwBrowse(url, r, onStatus) {
+ clearTimeout(rwBIdle);
+ rwB ||= await rwLaunch(onStatus);
+ const { cdp } = rwB, set = await rwSettings();
+ const { targetId } = await cdp.send('Target.createTarget', { url: 'about:blank' });
+ const { sessionId } = await cdp.send('Target.attachToTarget', { targetId, flatten: true });
+ const S = (m, p) => cdp.send(m, p, sessionId);
+ const reqs = new Map(), extra = new Map();
+ let inflight = 0, last = Date.now(), loaded = false;
+ const off = cdp.on(m => {
+ if (m.sessionId !== sessionId) return;
+ const p = m.params;
+ if (m.method === 'Network.requestWillBeSent') {
+ const q = reqs.get(p.requestId);
+ if (q) { q.url = p.request.url; q.method = p.request.method; }
+ else { reqs.set(p.requestId, { id: p.requestId, url: p.request.url, method: p.request.method, headers: p.request.headers, postData: p.request.postData, type: p.type, status: 0, mime: '', size: 0 }); inflight++; }
+ last = Date.now();
+ } else if (m.method === 'Network.requestWillBeSentExtraInfo') extra.set(p.requestId, p.headers);
+ else if (m.method === 'Network.responseReceived') {
+ const q = reqs.get(p.requestId); if (q) { q.status = p.response.status; q.mime = p.response.mimeType; q.type = p.type || q.type; }
+ } else if (m.method === 'Network.loadingFinished' || m.method === 'Network.loadingFailed') {
+ const q = reqs.get(p.requestId);
+ if (q && !q.done) { q.done = true; q.size = p.encodedDataLength || 0; q.failed = p.errorText; inflight--; }
+ last = Date.now();
+ } else if (m.method === 'Page.loadEventFired') loaded = true;
+ });
+ const quiet = () => Date.now() - last > (inflight <= 0 ? 700 : 1500);
+ const evalJs = async expr => (await S('Runtime.evaluate', { expression: expr, returnByValue: true })).result?.value;
+ try {
+ await S('Network.enable', { maxPostDataSize: 65536 });
+ await S('Page.enable');
+ if (set.userAgent) await S('Network.setUserAgentOverride', { userAgent: set.userAgent });
+ onStatus('Carregando ' + url);
+ const nav = await S('Page.navigate', { url });
+ if (nav.errorText) throw new Error(`${nav.errorText} em ${url}`);
+ const deadline = Date.now() + (+set.timeout || 20) * 1000;
+ const item = r.item.trim();
+ const hasItem = () => evalJs(`(()=>{try{return !!document.querySelector(${JSON.stringify(item)})}catch(e){return true}})()`);
+ while (Date.now() < deadline && !(loaded && quiet() && (!item || await hasItem()))) await rwSleep(200);
+ for (let i = 0; i < (+r.scrolls || 0); i++) {
+ onStatus(`Rolando a página (${i + 1}/${r.scrolls})`);
+ await evalJs('window.scrollTo(0, document.scrollingElement.scrollHeight)');
+ last = Date.now();
+ const end = Date.now() + 8000;
+ await rwSleep(300);
+ while (Date.now() < end && !quiet()) await rwSleep(200);
+ }
+ const d = JSON.parse(await evalJs('JSON.stringify({ ct: document.contentType, url: location.href, html: document.documentElement.outerHTML, text: document.body ? document.body.innerText : "" })'));
+ const list = [...reqs.values()].map(q => ({ ...q, headers: { ...q.headers, ...(extra.get(q.id) || {}) } }));
+ for (const q of list.filter(q => rwIsData(q) && q.done && !q.failed).slice(0, 80)) {
+ try { const b = await S('Network.getResponseBody', { requestId: q.id }); q.body = b.base64Encoded ? '' : b.body.slice(0, 2e6); } catch {}
+ }
+ const json = /json/i.test(d.ct) ? rwTryJson(d.text) : undefined;
+ const page = json !== undefined ? { json, url: d.url, base: d.url, size: d.text.length } : rwParse(d.html, d.url);
+ page.requests = list;
+ return page;
+ } finally {
+ off();
+ cdp.send('Target.closeTarget', { targetId }).catch(() => {});
+ rwBIdle = setTimeout(rwBClose, 120000);
+ }
+}
+
+const rwGet = (url, r, onStatus = () => {}) => r.browser ? rwBrowse(url, r, onStatus) : rwFetch(url, r);
+
+// ---------- extração ----------
+function rwValue(el, attr, base) {
+ if (!el) return '';
+ if (!attr || attr === 'text') return (el.textContent || '').replace(/\s+/g, ' ').trim();
+ if (attr === 'html') return (el.innerHTML || '').trim();
+ const v = el.getAttribute?.(attr);
+ if (v == null) return '';
+ if (RW_URLATTR.test(attr)) try { return new URL(v.trim(), base).href; } catch {}
+ return v.trim();
+}
+// Caminho JSON: data.items, preco.valor, fotos.0.url (ou fotos[0].url). * passa por todos os itens de uma lista
+// ou valores de um objeto (tags.*.nome, titulo.*). Vazio = o próprio valor.
+function rwPath(o, p) {
+ if (!p.trim()) return o;
+ const keys = p.trim().replace(/\[(\d+)\]/g, '.$1').split('.');
+ const go = (v, i) => {
+ if (i === keys.length) return v;
+ if (v == null) return undefined;
+ if (keys[i] !== '*') return go(v[keys[i]], i + 1);
+ const all = Array.isArray(v) ? v : typeof v === 'object' ? Object.values(v) : [];
+ return all.map(x => go(x, i + 1)).filter(x => x !== undefined).flat();
+ };
+ return go(o, 0);
+}
+const rwJsonVal = v => v == null ? '' : Array.isArray(v) ? v.map(x => x && typeof x === 'object' ? JSON.stringify(x) : x).join(' | ')
+ : typeof v === 'object' ? JSON.stringify(v) : String(v);
+const rwItems = (page, r) => {
+ if (page.json !== undefined) { const v = r.item.trim() ? rwPath(page.json, r.item) : page.json; return Array.isArray(v) ? v : v == null ? [] : [v]; }
+ return r.item.trim() ? [...page.doc.querySelectorAll(r.item)] : [page.doc.documentElement];
+};
+// Sem item, a página inteira vira uma linha. Campo sem seletor pega o próprio item.
+function rwExtract(page, r) {
+ const isJson = page.json !== undefined;
+ return rwItems(page, r).map(s => {
+ const row = {};
+ for (const f of r.fields) {
+ if (!f.name.trim()) continue;
+ const sel = f.sel.trim();
+ if (isJson) row[f.name] = rwJsonVal(rwPath(s, sel));
+ else if (f.all) row[f.name] = (sel ? [...s.querySelectorAll(sel)] : [s]).map(e => rwValue(e, f.attr, page.base)).filter(Boolean).join(' | ');
+ else row[f.name] = rwValue(sel ? s.querySelector(sel) : s, f.attr, page.base);
+ }
+ return row;
+ });
+}
+function rwNext(page, sel) {
+ if (!sel.trim()) return '';
+ if (page.json !== undefined) { const v = rwPath(page.json, sel); try { return typeof v === 'string' && v ? new URL(v, page.url).href : ''; } catch { return ''; } }
+ return rwValue(page.doc.querySelector(sel), 'href', page.base);
+}
+const rwUrls = r => r.urls.split('\n').map(s => s.trim()).filter(s => /^https?:\/\//i.test(s));
+
+// Acha a maior lista de objetos do JSON e sugere as colunas (valores simples e um nível de objeto dentro).
+function rwGuessJson(json) {
+ let best = { path: '', n: -1, arr: null };
+ const isObj = x => x && typeof x === 'object' && !Array.isArray(x);
+ const walk = (o, path, d) => {
+ if (d > 7 || !o || typeof o !== 'object') return;
+ if (Array.isArray(o)) {
+ if (o.length > best.n && o.some(isObj)) best = { path, n: o.length, arr: o };
+ o.slice(0, 2).forEach((x, i) => walk(x, path ? path + '.' + i : String(i), d + 1));
+ return;
+ }
+ for (const k of Object.keys(o)) walk(o[k], path ? path + '.' + k : k, d + 1);
+ };
+ walk(json, '', 0);
+ const sample = (best.arr || [json]).filter(isObj).slice(0, 5), keys = [];
+ const add = k => { if (!keys.includes(k) && keys.length < 15) keys.push(k); };
+ const simple = v => v == null || typeof v !== 'object' || (Array.isArray(v) && v.every(x => x == null || typeof x !== 'object'));
+ for (const it of sample) for (const [k, v] of Object.entries(it)) if (simple(v)) add(k);
+ for (const it of sample) for (const [k, v] of Object.entries(it)) if (isObj(v)) for (const [k2, v2] of Object.entries(v)) if (simple(v2)) add(k + '.' + k2);
+ return { item: best.arr ? best.path : '', fields: keys.map(k => ({ name: k.replace(/\./g, '_'), sel: k, attr: 'text', all: false })) };
+}
+
+function rwCsv(rows) {
+ const cols = [...new Set(rows.flatMap(Object.keys))];
+ const q = v => { const s = String(v ?? ''); return /[",\n\r]/.test(s) ? '"' + s.replace(/"/g, '""') + '"' : s; };
+ return [cols.map(q).join(','), ...rows.map(r => cols.map(c => q(r[c])).join(','))].join('\n') + '\n';
+}
+function rwCurl(q) {
+ const s = v => "'" + String(v).replace(/'/g, "'\\''") + "'";
+ let c = `curl -X ${q.method} ${s(q.url)}`;
+ for (const [k, v] of Object.entries(q.headers || {})) if (!k.startsWith(':')) c += ` \\\n -H ${s(k + ': ' + v)}`;
+ if (q.postData) c += ` \\\n --data-raw ${s(q.postData)}`;
+ return c;
+}
+
+async function rwScrape(r, onProgress) {
+ const urls = rwUrls(r);
+ if (!urls.length) throw new Error('Coloque ao menos uma URL começando com http:// ou https://');
+ const run = rwRun = { stop: false }, rows = [], seen = new Set(), errors = [];
+ const max = Math.min(RW_MAXPAGES, Math.max(1, +r.pages || 1)), wait = Math.max(0, +r.delay || 0);
+ let n = 0;
+ const one = async (u, req) => {
+ if (n) await rwSleep(wait);
+ if (run.stop) return null;
+ n++;
+ onProgress(`Página ${n}: ${u}`);
+ const page = await rwGet(u, req, onProgress);
+ const got = rwExtract(page, req);
+ for (const g of got) g._pagina = u;
+ rows.push(...got);
+ return { page, got };
+ };
+ try {
+ for (const start of urls) {
+ try {
+ if (RW_PAGEVAR.test(start + r.body)) {
+ // {pagina} na URL ou no corpo: 1, 2, 3... até vir uma página sem linhas
+ for (let p = 1; p <= max && !run.stop; p++) {
+ const x = await one(rwPageSub(start, p), { ...r, body: rwPageSub(r.body, p) });
+ if (!x || !x.got.length) break;
+ }
+ continue;
+ }
+ let u = start, k = 0;
+ while (u && k < max && !seen.has(u) && !run.stop) {
+ seen.add(u); k++;
+ const x = await one(u, r);
+ u = x ? rwNext(x.page, r.next) : '';
+ }
+ } catch (e) { errors.push(e.message); }
+ }
+ } finally { if (rwRun === run) rwRun = null; }
+ if (n === 1) for (const g of rows) delete g._pagina;
+ return { rows, pages: n, errors, stopped: run.stop };
+}
+
+// ---------- seletor visual ----------
+const rwStable = c => /^[a-zA-Z_-][\w-]*$/.test(c) && !/\d{3,}|^(css|sc|jsx|svelte|emotion)-|^(active|hover|selected|focus|open|show)$/i.test(c);
+function rwSimpleSel(e) {
+ const cls = [...e.classList].filter(rwStable).slice(0, 2);
+ return e.tagName.toLowerCase() + cls.map(c => '.' + CSS.escape(c)).join('');
+}
+function rwRepeatSel(e) {
+ const s = rwSimpleSel(e);
+ if (s.includes('.') || !e.parentElement || /^(html|body)$/i.test(e.parentElement.tagName)) return s;
+ return rwSimpleSel(e.parentElement) + ' > ' + s;
+}
+// Sobe a partir do clique: a lista repetida mais baixa dá a quantidade; o item é o ancestral mais alto que repete
+// a mesma quantidade (clicar no título de um card escolhe o card, não o título).
+function rwItemSelector(el) {
+ const doc = el.ownerDocument;
+ let want = 0, pick = null;
+ for (let e = el; e && e.parentElement && !/^(body|html)$/i.test(e.tagName); e = e.parentElement) {
+ const s = rwRepeatSel(e);
+ let n = 0; try { n = doc.querySelectorAll(s).length; } catch { continue; }
+ if (!want && n >= 2) { want = n; pick = s; }
+ else if (want && n === want) pick = s;
+ }
+ return pick || rwRepeatSel(el);
+}
+function rwFieldSelector(item, el) {
+ if (item === el) return '';
+ const chain = [];
+ for (let e = el; e && e !== item; e = e.parentElement) chain.unshift(e);
+ for (let i = chain.length - 1; i >= 0; i--) {
+ const s = chain.slice(i).map(rwSimpleSel).join(' ');
+ try { if (item.querySelector(s) === el) return s; } catch {}
+ }
+ const t = el.tagName.toLowerCase(), same = [...el.parentElement.children].filter(x => x.tagName === el.tagName);
+ return chain.slice(0, -1).map(rwSimpleSel).concat(t + (same.length > 1 ? `:nth-of-type(${same.indexOf(el) + 1})` : '')).join(' > ');
+}
+const rwFieldAttr = el => el.tagName === 'IMG' ? 'src' : el.tagName === 'A' ? 'href' : 'text';
+function rwFieldName(el, r) {
+ const tag = el.tagName.toLowerCase(), known = { a: 'link', img: 'imagem', h1: 'titulo', h2: 'titulo', h3: 'titulo', h4: 'titulo', time: 'data', p: 'texto' };
+ const base = (known[tag] || [...el.classList].find(rwStable) || tag).replace(/[^\w]+/g, '_');
+ let n = base, i = 2;
+ while (r.fields.some(f => f.name === n)) n = base + i++;
+ return n;
+}
+
+let rwPick = null;
+function rwShowPicker(page) {
+ const box = rwPage.querySelector('.rw-pickbox');
+ if (page.json !== undefined) { box.innerHTML = 'Esta fonte é JSON: use os caminhos (ex.: data.items) no item e nos campos.
'; return; }
+ box.innerHTML = `Escolher o item Escolher um campo
+ Clique no botão e depois na página. Os itens achados ficam em azul.
`;
+ const fr = box.querySelector('iframe');
+ const html = page.html.replace(/