| 1 | // Descarga un repo PÚBLICO (GitHub/Bitbucket) en una carpeta real elegida por |
| 2 | // el usuario, para abrirlo como proyecto sin necesitar git instalado. Mismo |
| 3 | // patrón que skills.js: árbol de Git vía API + contenidos por raw CDN (sin |
| 4 | // tope de la API, solo la llamada al árbol cuenta contra el límite 60/h). |
| 5 | // |
| 6 | // RESUMIBLE por diseño: listRepo() (el árbol) y downloadFiles() (los ficheros) |
| 7 | // están separados a propósito — quien llama (main.js) persiste la lista y qué |
| 8 | // rutas ya se descargaron, así una descarga interrumpida (recarga, pestaña |
| 9 | // cerrada) continúa donde se quedó en vez de volver a empezar. |
| 10 | const MAX_FILES = 4000; |
| 11 | const MAX_FILE_BYTES = 4 * 1024 * 1024; // ficheros más grandes se saltan (binarios enormes) |
| 12 | const CONCURRENCY = 10; |
| 13 | |
| 14 | export function parseRepoUrl(raw) { |
| 15 | const url = String(raw || '').trim().replace(/\.git$/, '').replace(/\/+$/, ''); |
| 16 | let m = url.match(/^(?:https?:\/\/)?(?:www\.)?github\.com\/([\w.-]+)\/([\w.-]+)(?:\/tree\/([\w./-]+))?/i); |
| 17 | if (m) return { host: 'github', owner: m[1], repo: m[2], branch: m[3] || null }; |
| 18 | m = url.match(/^(?:https?:\/\/)?(?:www\.)?bitbucket\.org\/([\w.-]+)\/([\w.-]+)(?:\/src\/([\w./-]+))?/i); |
| 19 | if (m) return { host: 'bitbucket', owner: m[1], repo: m[2], branch: m[3] || null }; |
| 20 | throw new Error('URL no reconocida. Usa github.com/usuario/repo o bitbucket.org/usuario/repo'); |
| 21 | } |
| 22 | |
| 23 | // escribe un fichero (texto o binario) en `root`, creando subcarpetas |
| 24 | async function writeInto(root, path, blob) { |
| 25 | const parts = path.split('/'); const name = parts.pop(); |
| 26 | let dir = root; |
| 27 | for (const seg of parts) dir = await dir.getDirectoryHandle(seg, { create: true }); |
| 28 | const fh = await dir.getFileHandle(name, { create: true }); |
| 29 | const w = await fh.createWritable(); |
| 30 | await w.write(blob); |
| 31 | await w.close(); |
| 32 | } |
| 33 | |
| 34 | // pool de concurrencia simple: corre `items` a través de `worker`, máx N a la vez |
| 35 | async function pool(items, n, worker) { |
| 36 | let i = 0; |
| 37 | const runners = Array.from({ length: Math.min(n, items.length) }, async () => { |
| 38 | while (i < items.length) await worker(items[i++]); |
| 39 | }); |
| 40 | await Promise.all(runners); |
| 41 | } |
| 42 | |
| 43 | // ── listar (una sola vez, resultado persistible) ───────────────────────── |
| 44 | async function listGithubFiles({ owner, repo, branch }) { |
| 45 | if (!branch) { |
| 46 | const r = await fetch(`https://api.github.com/repos/${owner}/${repo}`); |
| 47 | if (r.status === 403) throw new Error('GitHub limitó las peticiones (60/h sin login). Reintenta en unos minutos.'); |
| 48 | if (!r.ok) throw new Error(`Repo no encontrado o privado (HTTP ${r.status})`); |
| 49 | branch = (await r.json()).default_branch || 'main'; |
| 50 | } |
| 51 | let tree = null; |
| 52 | for (const b of [branch, 'main', 'master']) { |
| 53 | const r = await fetch(`https://api.github.com/repos/${owner}/${repo}/git/trees/${b}?recursive=1`); |
| 54 | if (r.ok) { tree = (await r.json()).tree || []; branch = b; break; } |
| 55 | if (r.status === 403) throw new Error('GitHub limitó las peticiones (60/h sin login). Reintenta en unos minutos.'); |
| 56 | } |
| 57 | if (!tree) throw new Error('No pude leer el árbol del repo'); |
| 58 | const blobs = tree.filter(n => n.type === 'blob'); |
| 59 | const files = blobs.filter(n => !n.size || n.size <= MAX_FILE_BYTES).slice(0, MAX_FILES).map(n => ({ path: n.path, size: n.size || 0 })); |
| 60 | return { branch, files, skipped: blobs.length - files.length }; |
| 61 | } |
| 62 | // Bitbucket no tiene un único endpoint de árbol recursivo: se camina por directorios. |
| 63 | async function bitbucketWalk(owner, repo, branch, path, files) { |
| 64 | if (files.length >= MAX_FILES) return; |
| 65 | let url = `https://api.bitbucket.org/2.0/repositories/${owner}/${repo}/src/${branch}/${path}?pagelen=100`; |
| 66 | while (url && files.length < MAX_FILES) { |
| 67 | const r = await fetch(url); |
| 68 | if (!r.ok) throw new Error(`Bitbucket: HTTP ${r.status} (¿repo privado o rama incorrecta?)`); |
| 69 | const data = await r.json(); |
| 70 | for (const e of data.values || []) { |
| 71 | if (files.length >= MAX_FILES) break; |
| 72 | if (e.type === 'commit_directory') await bitbucketWalk(owner, repo, branch, e.path, files); |
| 73 | else if (e.type === 'commit_file' && (!e.size || e.size <= MAX_FILE_BYTES)) files.push({ path: e.path, size: e.size || 0 }); |
| 74 | } |
| 75 | url = data.next || null; |
| 76 | } |
| 77 | } |
| 78 | async function listBitbucketFiles({ owner, repo, branch }) { |
| 79 | if (!branch) { |
| 80 | const r = await fetch(`https://api.bitbucket.org/2.0/repositories/${owner}/${repo}`); |
| 81 | if (!r.ok) throw new Error(`Repo no encontrado o privado (HTTP ${r.status})`); |
| 82 | branch = (await r.json()).mainbranch?.name || 'main'; |
| 83 | } |
| 84 | const files = []; |
| 85 | await bitbucketWalk(owner, repo, branch, '', files); |
| 86 | return { branch, files, skipped: 0 }; |
| 87 | } |
| 88 | |
| 89 | // Lista el repo completo UNA vez. Devuelve todo lo necesario para persistir |
| 90 | // el trabajo: { host, owner, repo, branch, files:[{path,size}], skipped }. |
| 91 | export async function listRepo(url) { |
| 92 | const info = parseRepoUrl(url); |
| 93 | const { branch, files, skipped } = info.host === 'github' ? await listGithubFiles(info) : await listBitbucketFiles(info); |
| 94 | if (!files.length) throw new Error('El repo está vacío (o no pude listarlo)'); |
| 95 | return { host: info.host, owner: info.owner, repo: info.repo, branch, files, skipped }; |
| 96 | } |
| 97 | |
| 98 | // Descarga los ficheros de `job.files` que NO estén en `doneSet` (Set de |
| 99 | // rutas). Llama a onFileDone(path) tras cada escritura para que quien invoque |
| 100 | // persista el progreso — así una interrupción se retoma sin re-descargar nada. |
| 101 | export async function downloadFiles(job, targetHandle, doneSet, onProgress, onFileDone) { |
| 102 | const { host, owner, repo, branch, files } = job; |
| 103 | const pending = files.filter(f => !doneSet.has(f.path)); |
| 104 | let done = files.length - pending.length; |
| 105 | onProgress?.({ text: `${done}/${files.length}`, done, total: files.length }); |
| 106 | await pool(pending, CONCURRENCY, async f => { |
| 107 | onProgress?.({ text: `Descargando ${f.path}…`, done, total: files.length }); |
| 108 | const url = host === 'github' |
| 109 | ? `https://raw.githubusercontent.com/${owner}/${repo}/${branch}/${f.path}` |
| 110 | : `https://api.bitbucket.org/2.0/repositories/${owner}/${repo}/src/${branch}/${f.path}`; |
| 111 | const r = await fetch(url); |
| 112 | if (r.ok) await writeInto(targetHandle, f.path, await r.blob()); |
| 113 | done++; |
| 114 | onFileDone?.(f.path); |
| 115 | onProgress?.({ text: `${done}/${files.length}`, done, total: files.length }); |
| 116 | }); |
| 117 | } |
| 118 | |
| 119 | // Conveniencia: listar + descargar todo de una vez (sin resumibilidad; para |
| 120 | // quien no necesite persistir progreso entre sesiones). |
| 121 | export async function cloneToHandle(url, targetHandle, onProgress) { |
| 122 | const job = await listRepo(url); |
| 123 | await downloadFiles(job, targetHandle, new Set(), onProgress); |
| 124 | return { count: job.files.length, skipped: job.skipped }; |
| 125 | } |