/** * Dragon Ball & Toriyama Universal Scraper & Live News Ingestion Engine * Handles: * - dragon-ball-official.com (Official portal articles, news, ranking) * - lineup.toei-anim.co.jp (DBS, DBZ Kai, DBZ, DB anime episode synopses & lineups) * - jajanken.net (Weekly Shonen Jump DB rankings, chapter stats & history) * - inlifeweb.com & caramel.co.jp (Akira Toriyama historical biographies & publishing data) * - ja.wikipedia.org/wiki/鳥山明 (Complete Akira Toriyama encyclopedia) */ import { Browser } from "../api/browser.ts"; import { type CommonOptions, logger } from "./shared.ts"; import { mkdir } from "node:fs/promises"; import { cpus } from "node:os"; import { join } from "node:path"; import { DRAGONBALL_SOURCES, DRAGONBALL_URLS, SHENRON_CONSOLIDATED } from "../sources/dragonball.ts"; import { DRAGONBALL_EXHAUSTIVE_ROOTS } from "../sources/dragonball.ts"; import { AutonomousCrawler } from "../crawler/AutonomousCrawler.ts"; import { GoogleClient } from "../google/client.ts"; import { KeylessGoogleClient } from "../google/keyless.ts"; import { googleNewsSearch, googleScholarSearch, googleVideoSearch, } from "../google/verticals.ts"; import { AssetSearch } from "../assets/providers.ts"; import { archive } from "../archive/index.ts"; import { toShenronManifest } from "../archive/shenron.ts"; import { exportDragonBallJsonl } from "../archive/dragonball-export.ts"; import { detectFrameworks } from "../detect.ts"; import { construireDossier } from "../crawler/wiki-service.ts"; export interface DbArticle { id: string; title: string; url: string; category: string; date: string; imageUrl?: string; summary?: string; contentMarkdown?: string; source: string; tags?: string[]; galleryUrls?: string[]; } export interface DbEpisodeSynopsis { series: "dragon_ball" | "dragon_ball_z" | "dragon_gt" | "dragon_ball_kai" | "dragon_ball_super" | "dragonball_daima" | "dr_slump"; episodeNumber: number; title: string; synopsis: string; broadcastDate?: string; imageUrl?: string; sourceUrl: string; } export interface DbJumpStat { issue: string; year: number; rank: number; title: string; cover: boolean; colorPages: boolean; } export interface ShenronCatalogue { episodes: unknown[]; movies: unknown[]; assets: string[]; } export interface DragonBallCrawlOptions { /** Route every BXC page and direct source request through this proxy. */ proxy?: string; /** Maximum detail pages concurrently requested from the shared Toei origin. */ toeiDetailConcurrency?: number; /** Maximum detail pages collected for each Toei series. */ toeiDetailLimit?: number; /** Internal shared gate used when several Toei series crawl together. */ toeiDetailGate?: AsyncSemaphore; } export interface ShenronCrawlManifest { schema: "bxc-dragonball-crawl/v1"; generatedAt: string; source: "bxc"; datasets: Record; modules?: string[]; } export function shenronAssetUrl(value: string): string | null { try { if (/^https?:\/\//i.test(value)) return new URL(value).href; return new URL(value.replace(/^\.\//, "/"), DRAGONBALL_SOURCES.shenronCdn.origin).href; } catch { return null; } } /** Bun fetch supports HTTP(S) proxies; SOCKS remains handled by BXC browser profiles. */ function directFetchProxy(proxy?: string): { proxy: string } | undefined { return proxy && /^https?:\/\//i.test(proxy) ? { proxy } : undefined; } function shenronRecordAssets(value: unknown, output: Set): void { if (Array.isArray(value)) { for (const item of value) shenronRecordAssets(item, output); return; } if (!value || typeof value !== "object") return; for (const [key, child] of Object.entries(value as Record)) { if (typeof child === "string" && /(?:^image$|imagePath|scene_preview|thumbnail|poster)/i.test(key)) { const asset = shenronAssetUrl(child); if (asset) output.add(asset); } else if (key === "frames" && typeof child === "string") { try { shenronRecordAssets(JSON.parse(child), output); } catch {} } else { shenronRecordAssets(child, output); } } } async function fetchShenronPage(kind: "episodes" | "movies", offset: number, proxy?: string): Promise<{ items: unknown[]; total: number }> { const url = kind === "episodes" ? DRAGONBALL_URLS.shenronEpisodes(100, offset) : DRAGONBALL_URLS.shenronMovies(100, offset); const response = await fetch(url, directFetchProxy(proxy)); if (!response.ok) throw new Error(`Shenron ${kind} request failed with status ${response.status}`); const body = await response.json() as Record; const items = Array.isArray(body[kind]) ? body[kind] : []; return { items, total: typeof body.total === "number" ? body.total : items.length }; } /** Fetch every public Shenron catalogue page and normalize all image/frame assets. */ export async function scrapeShenronCatalogue(options: Pick = {}): Promise { const collect = async (kind: "episodes" | "movies"): Promise => { const first = await fetchShenronPage(kind, 0, options.proxy); const offsets = Array.from({ length: Math.max(0, Math.ceil(first.total / 100) - 1) }, (_, index) => (index + 1) * 100); const rest = await mapConcurrent(offsets, 4, (offset) => fetchShenronPage(kind, offset, options.proxy)); return [first, ...rest].flatMap((page) => page.items); }; const [episodes, movies] = await Promise.all([collect("episodes"), collect("movies")]); const assets = new Set(); shenronRecordAssets(episodes, assets); shenronRecordAssets(movies, assets); return { episodes, movies, assets: [...assets].sort() }; } interface DragonBallGoogleDiscovery { queries: readonly string[]; books: unknown; suggestions: string[]; news: unknown; videos: unknown; scholar: unknown; dns: Record; errors: Record; } /** * Collect the public Google surfaces that are useful for source discovery. * Results are persisted as evidence; only registry-owned domains are allowed * to become crawler seeds. */ async function collectDragonBallGoogleDiscovery( keylessGoogle: KeylessGoogleClient, allowedDomains: readonly string[], ): Promise<{ discovery: DragonBallGoogleDiscovery; urls: string[] }> { const queries = [ "Dragon Ball Akira Toriyama", "ドラゴンボール 鳥山明", "Dragon Ball officiel Toei", ] as const; const errors: Record = {}; const recover = async (name: string, operation: () => Promise, fallback: T): Promise => { try { return await operation(); } catch (error) { errors[name] = error instanceof Error ? error.message : String(error); return fallback; } }; const [books, suggestions, news, videos, scholar, dnsResults] = await Promise.all([ recover("books", () => keylessGoogle.searchBooks(queries[0], 40), {}), recover("suggestions", () => Promise.all(queries.map((query) => keylessGoogle.autocomplete(query))).then((items) => items.flat()), [] as string[]), recover("news", () => googleNewsSearch(queries[0], { hl: "en", num: 50 }), []), recover("videos", () => googleVideoSearch(queries[1], { hl: "ja", num: 50 }), []), recover("scholar", () => googleScholarSearch(queries[0], { hl: "en", num: 50 }), []), Promise.all(allowedDomains.map(async (domain) => [ domain, await recover(`dns:${domain}`, () => keylessGoogle.resolveDns(domain), {}), ] as const)), ]); const urls = [ ...news.map((item) => item.url), ...videos.map((item) => item.url), ...scholar.map((item) => item.url), ].filter((url) => { try { return allowedDomains.includes(new URL(url).hostname); } catch { return false; } }); return { discovery: { queries, books, suggestions: [...new Set(suggestions)], news, videos, scholar, dns: Object.fromEntries(dnsResults), errors, }, urls: [...new Set(urls)], }; } export async function runDragonBallUnifiedPipeline( outDir: string, options: { dryRun?: boolean; proxy?: string } = {}, ): Promise { await mkdir(outDir, { recursive: true }); const storageDir = Bun.env.BXC_DRAGONBALL_STORAGE_DIR ?? join(outDir, "storage"); const databasePath = Bun.env.BXC_DRAGONBALL_DB_PATH ?? join(outDir, "bxc.sqlite"); process.env.BXC_STORAGE_DIR = storageDir; process.env.BXC_DB_PATH = databasePath; await mkdir(storageDir, { recursive: true }); const allowedDomains = [...new Set(Object.values(DRAGONBALL_SOURCES).map((source) => new URL(source.origin).hostname))]; const google = new GoogleClient({ profile: "static" }); const discovered = (await Promise.all([ google.search("site:dragon-ball-official.com Dragon Ball").catch(() => []), google.search("site:lineup.toei-anim.co.jp ドラゴンボール").catch(() => []), google.search("site:kanzenshuu.com Toriyama interview").catch(() => []), ])).flatMap((results) => results.map((result) => result.url)); const googleUrls = [...new Set(discovered.filter((url) => { try { return allowedDomains.includes(new URL(url).hostname); } catch { return false; } }))]; const keylessGoogle = new KeylessGoogleClient(); const googleDiscovery = await collectDragonBallGoogleDiscovery(keylessGoogle, allowedDomains); googleUrls.push(...googleDiscovery.urls); const uniqueGoogleUrls = [...new Set(googleUrls)]; const modules = await Promise.allSettled([ Promise.resolve(googleDiscovery.discovery.books), Promise.resolve(googleDiscovery.discovery.suggestions), Promise.resolve(googleDiscovery.discovery), new AssetSearch().search("Dragon Ball Akira Toriyama", { kind: "image", limit: 50 }), archive.getItem("drslump").then((item) => toShenronManifest(item, "dr_slump")), construireDossier(DRAGONBALL_URLS.wikipediaJaAkiraToriyamaPage(), { avecImages: true, avecContenu: true }), Promise.all(DRAGONBALL_EXHAUSTIVE_ROOTS.map(async (url) => { try { return { url, status: "ok", technologies: await detectFrameworks(url) }; } catch (error) { return { url, status: "error", error: error instanceof Error ? error.message : String(error) }; } })), ]); const moduleArtifacts = ["google-books.json", "google-suggest.json", "google-discovery.json", "assets.json", "archive-drslump.json", "wiki-toriyama.json", "frameworks.json"]; await Promise.all(modules.map(async (result, index) => { const payload = result.status === "fulfilled" ? { status: "ok", data: result.value } : { status: "error", error: result.reason instanceof Error ? result.reason.message : String(result.reason) }; await Bun.write(join(outDir, moduleArtifacts[index]!), JSON.stringify(payload, null, 2)); })); const plan = { schema: "bxc-dragonball-unified-pipeline/v1", generatedAt: new Date().toISOString(), roots: DRAGONBALL_EXHAUSTIVE_ROOTS, googleUrls: uniqueGoogleUrls, allowedDomains, modules: moduleArtifacts, storage: outDir, storageDir, databasePath, }; await Bun.write(join(outDir, "pipeline-plan.json"), JSON.stringify(plan, null, 2)); if (options.dryRun) return; const crawler = new AutonomousCrawler({ requestQueueName: "dragonball-unified-pipeline", allowedDomains, maxDepth: 100, minConcurrency: Math.max(2, cpus().length), maxConcurrency: Math.max(4, cpus().length * 2), profile: "static", daemon: false, proxyPool: options.proxy ? [options.proxy] : undefined, }); await crawler.run([...DRAGONBALL_EXHAUSTIVE_ROOTS, ...uniqueGoogleUrls]); await runFullDragonBallCrawl(outDir, { proxy: options.proxy }); const jsonlPath = join(outDir, "shenron-documents.jsonl"); const exportedDocuments = await exportDragonBallJsonl(databasePath, jsonlPath); const manifestPath = join(outDir, "shenron-ingest-manifest.json"); const manifest = await Bun.file(manifestPath).json() as ShenronCrawlManifest; manifest.modules = [...moduleArtifacts, "shenron-documents.jsonl"]; await Bun.write(manifestPath, JSON.stringify(manifest, null, 2)); await Bun.write(join(outDir, "pipeline-result.json"), JSON.stringify({ schema: "bxc-dragonball-unified-pipeline-result/v1", generatedAt: new Date().toISOString(), databasePath, jsonlPath, exportedDocuments, }, null, 2)); } export class AsyncSemaphore { #available: number; #waiting: Array<() => void> = []; constructor(concurrency: number) { this.#available = Math.max(1, Math.floor(concurrency)); } async run(task: () => Promise): Promise { if (this.#available === 0) { await new Promise((resolve) => this.#waiting.push(resolve)); } this.#available--; try { return await task(); } finally { this.#available++; this.#waiting.shift()?.(); } } } /** * A small async pool for I/O-bound work. Unlike Promise.all(), it keeps one * origin from receiving an unbounded burst while keeping Bun's fetch pool busy. */ export async function mapConcurrent( values: readonly T[], concurrency: number, mapper: (value: T) => Promise, ): Promise { const result = Array.from({ length: values.length }) as R[]; let cursor = 0; const workerCount = Math.min(values.length, Math.max(1, Math.floor(concurrency))); await Promise.all(Array.from({ length: workerCount }, async () => { while (true) { const index = cursor++; if (index >= values.length) return; result[index] = await mapper(values[index]!); } })); return result; } export async function scrapeDragonBallOfficialNews( limit = 15, options: Pick = {}, ): Promise { logger.log("Scraping dragon-ball-official.com/news/..."); const page = await Browser.newPage({ profile: "fast", headless: true, proxy: options.proxy }); const articles: DbArticle[] = []; try { await page.goto(DRAGONBALL_URLS.officialNews()); await new Promise((r) => setTimeout(r, 4000)); // allow SPA hydration const html = await page.content(); // Match article list entries const itemRegex = /]*href=["']([^"']*\/news\/[^"']*\.html)["'][^>]*>([\s\S]*?)<\/a>/gi; let match; while ((match = itemRegex.exec(html)) !== null) { const link = match[1]; const inner = match[2]; const fullUrl = new URL(link, DRAGONBALL_SOURCES.official.origin).href; const imgMatch = inner.match(/]*src=["']([^"']+)["']/i); const titleMatch = inner.match(/]*class=["'][^"']*title[^"']*["'][^>]*>([\s\S]*?)<\/p>/i) || inner.match(/]*>([\s\S]*?)<\/h\d>/i); const dateMatch = inner.match(/\b(20\d{2}\.\d{2}\.\d{2})\b/); const catMatch = inner.match(/]*class=["'][^"']*cat[^"']*["'][^>]*>([\s\S]*?)<\/span>/i); const rawTitle = titleMatch ? titleMatch[1].replace(/<[^>]*>/g, "").trim() : inner.replace(/<[^>]*>/g, " ").trim().slice(0, 80); const cleanTitle = rawTitle.replace(/\s+/g, " "); if (cleanTitle && !articles.some(a => a.url === fullUrl)) { articles.push({ id: link.replace(/[^\w-]/g, "_"), title: cleanTitle, url: fullUrl, category: catMatch ? catMatch[1].replace(/<[^>]*>/g, "").trim() : "NEWS", date: dateMatch ? dateMatch[1] : new Date().toISOString().slice(0, 10), imageUrl: imgMatch ? new URL(imgMatch[1], DRAGONBALL_SOURCES.official.origin).href : undefined, source: "dragon-ball-official.com" }); } if (articles.length >= limit) break; } // Fetch individual article pages to extract full article text, publish dates, category tags, and high-res gallery URLs for (const article of articles) { try { const res = await fetch(article.url, { headers: { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36" }, ...directFetchProxy(options.proxy), }); if (!res.ok) continue; const artHtml = await res.text(); // Extract exact title if available const titleMatch = artHtml.match(/]*class=["'][^"']*news-post__title[^"']*["'][^>]*>([\s\S]*?)<\/h3>/i) || artHtml.match(/]*property=["']og:title["'][^>]*content=["']([^"']+)["']/i); if (titleMatch) { const clean = titleMatch[1].replace(/<[^>]*>/g, "").replace(/\s*\|\s*DRAGON BALL OFFICIAL SITE.*/i, "").trim(); if (clean) article.title = clean; } // Extract publish date const timeMatch = artHtml.match(/]*datetime=["']([^"']+)["']/i) || artHtml.match(/]*>([\s\S]*?)<\/time>/i); if (timeMatch) { article.date = timeMatch[1].trim(); } // Extract category and tags const catDetailMatch = artHtml.match(/]*class=["'][^"']*category[^"']*["'][^>]*>([\s\S]*?)<\/span>/i); if (catDetailMatch) { article.category = catDetailMatch[1].replace(/<[^>]*>/g, "").trim(); } const tagMatches = [...artHtml.matchAll(/]*class=["'][^"']*tags__item[^"']*["'][^>]*>[\s\S]*?]*>([\s\S]*?)<\/a>/gi)]; if (tagMatches.length > 0) { article.tags = tagMatches.map(m => m[1].replace(/<[^>]*>/g, "").trim()).filter(Boolean); } // Extract high-res image gallery URLs const galleryUrls = new Set(); const galleryImgMatches = [ ...artHtml.matchAll(/]*class=["'][^"']*(?:c-gallery|photo-panel|entry-article)[^"']*["'][^>]*>[\s\S]*?]*src=["']([^"']+)["']/gi), ...artHtml.matchAll(/]*src=["']([^"']*\/news\/\d{4}\/\d{2}\/[^"']+)["']/gi), ]; for (const m of galleryImgMatches) { const src = m[1]; if (src && !src.startsWith("data:") && !src.includes("assets/img")) { try { galleryUrls.add(new URL(src, article.url).href); } catch {} } } if (galleryUrls.size > 0) { article.galleryUrls = [...galleryUrls]; if (!article.imageUrl && article.galleryUrls[0]) { article.imageUrl = article.galleryUrls[0]; } } // Extract full article text / body markdown const bodyMatch = artHtml.match(/]*class=["'][^"']*entry-article[^"']*["'][^>]*>([\s\S]*?)<\/div>\s*<\/section>/i) || artHtml.match(/]*class=["'][^"']*news-post__body[^"']*["'][^>]*>([\s\S]*?)<\/div>\s*(?:]*>[\s\S]*?<\/\1>/gi, "") .replace(//gi, "\n") .replace(/<\/p>/gi, "\n\n") .replace(/<[^>]*>/g, " ") .replace(/[ \t]+/g, " ") .replace(/\n\s+\n/g, "\n\n") .trim(); article.contentMarkdown = cleanText; article.summary = cleanText.slice(0, 300); } } catch (err) { logger.warn(`Failed to fetch full article details for ${article.url}: ${err}`); } } } finally { await page.close(); } return articles; } export async function scrapeToeiSeriesEpisodes( seriesSlug: "dragon" | "dragonz" | "dragon_gt" | "dragon_kai" | "dragon_super" | "dragonball_super" | "dragonball_daima", seriesKey: DbEpisodeSynopsis["series"], options: DragonBallCrawlOptions = {}, ): Promise { const slug = seriesSlug === "dragonball_super" ? "dragon_super" : seriesSlug; const url = DRAGONBALL_URLS.toeiEpisodes(slug); logger.log(`Scraping Toei animation synopses for ${seriesKey} from ${url}...`); let html = ""; try { const res = await fetch(url, { headers: { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36" }, ...directFetchProxy(options.proxy), }); if (res.ok) { html = await res.text(); } else { logger.warn(`Toei lineup request for ${seriesKey} returned status ${res.status}`); } } catch (err) { logger.warn(`Toei lineup request failed for ${seriesKey}: ${err}`); } const episodes: DbEpisodeSynopsis[] = []; if (!html) return episodes; // 1. Check direct listing for dt/dd format const epBlockRegex = /]*>([\s\S]*?)<\/dt>\s*]*>([\s\S]*?)<\/dd>/gi; let match; while ((match = epBlockRegex.exec(html)) !== null) { const dt = match[1].replace(/<[^>]*>/g, " ").trim(); const dd = match[2].replace(/<[^>]*>/g, " ").trim(); const numMatch = dt.match(/第?\s*(\d+)\s*話/); const num = numMatch ? parseInt(numMatch[1], 10) : episodes.length + 1; episodes.push({ series: seriesKey, episodeNumber: num, title: dt, synopsis: dd, sourceUrl: url }); } // 2. Check epOne card listing with thumbnails (/upload/save_image/episode/...) const epOneRegex = /]*class=["'][^"']*epOne[^"']*["'][^>]*>([\s\S]*?)<\/div>\s*<\/div>\s*<\/a>\s*<\/div>/gi; let epOneMatch; while ((epOneMatch = epOneRegex.exec(html)) !== null) { const block = epOneMatch[1]; const numMatch = block.match(/]*class=["']num["'][^>]*>第?\s*(\d+)\s*話/i) || block.match(/第?\s*(\d+)\s*話/i); const titleMatch = block.match(/]*class=["']title["'][^>]*>([\s\S]*?)<\/h\d>/i) || block.match(/]*>([\s\S]*?)<\/h\d>/i); const imgMatch = block.match(/]*src=["']([^"']*\/upload\/save_image\/episode\/[^"']+)["']/i) || block.match(/]*src=["']([^"']+)["']/i); const linkMatch = block.match(/]*href=["']([^"']+)["']/i); if (numMatch) { const num = parseInt(numMatch[1], 10); const title = titleMatch ? titleMatch[1].replace(/<[^>]*>/g, "").trim() : `第 ${num} 話`; const imageUrl = imgMatch ? new URL(imgMatch[1], DRAGONBALL_SOURCES.toei.origin).href : undefined; const epUrl = linkMatch ? new URL(linkMatch[1], url).href : DRAGONBALL_URLS.toeiEpisode(slug, num); const existing = episodes.find(e => e.episodeNumber === num); if (existing) { if (imageUrl && !existing.imageUrl) existing.imageUrl = imageUrl; if (!existing.title || existing.title.startsWith("第")) existing.title = title; } else { episodes.push({ series: seriesKey, episodeNumber: num, title, synopsis: "", imageUrl, sourceUrl: epUrl }); } } } // Detail requests across every series share this fixed limit. This avoids // the previous 4 × Promise.all burst against the same Toei host. const linkRegex = /href=["'](?:(?:\.\.\/)?episode\/(\d+)\/?)["']/gi; const epNums = new Set(); let lMatch; while ((lMatch = linkRegex.exec(html)) !== null) { epNums.add(parseInt(lMatch[1], 10)); } if (epNums.size > 0 && episodes.filter(e => e.synopsis).length < 10) { const detailLimit = Math.max(1, options.toeiDetailLimit ?? 25); const targetNums = Array.from(epNums).sort((a, b) => b - a).slice(0, detailLimit); const detailConcurrency = Math.max(1, options.toeiDetailConcurrency ?? 8); const gate = options.toeiDetailGate ?? new AsyncSemaphore(detailConcurrency); const detailResults = await mapConcurrent(targetNums, detailConcurrency, (num) => gate.run(async () => { const epUrl = DRAGONBALL_URLS.toeiEpisode(slug, num); try { const epRes = await fetch(epUrl, { headers: { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)" }, ...directFetchProxy(options.proxy), }); if (!epRes.ok) return null; const epText = await epRes.text(); const titleMatch = epText.match(/]*class=["'][^"']*story_caption_title[^"']*["'][^>]*>([\s\S]*?)<\/h1>/i) || epText.match(/([\s\S]*?)<\/title>/i); const cleanTitle = titleMatch ? titleMatch[1].replace(/<[^>]*>/g, " ").replace(/ - 東映アニメーション.*/, "").trim() : `第 ${num} 話`; const synMatch = epText.match(/<div[^>]*class=["']text_details_inner["'][^>]*>([\s\S]*?)<\/div>/i) || epText.match(/<p[^>]*class=["'][^"']*text[^"']*["'][^>]*>([\s\S]*?)<\/p>/i); const cleanSynopsis = synMatch ? synMatch[1].replace(/<[^>]*>/g, " ").trim() : ""; const dateMatch = epText.match(/(\d{4}\/\d{2}\/\d{2})<span[^>]*>放送<\/span>/); const imgMatch = epText.match(/<img[^>]*src=["']([^"']*\/upload\/save_image\/episode\/[^"']+)["']/i) || epText.match(/<div[^>]*class=["']thumb["'][^>]*>[\s\S]*?<img[^>]*src=["']([^"']+)["']/i); const imageUrl = imgMatch ? new URL(imgMatch[1], DRAGONBALL_SOURCES.toei.origin).href : undefined; return { series: seriesKey, episodeNumber: num, title: cleanTitle.replace(/\s+/g, " "), synopsis: cleanSynopsis.replace(/\s+/g, " "), broadcastDate: dateMatch ? dateMatch[1] : undefined, imageUrl, sourceUrl: epUrl } as DbEpisodeSynopsis; } catch { return null; } })); for (const ep of detailResults) { if (ep) { const existing = episodes.find(e => e.episodeNumber === ep.episodeNumber); if (existing) { if (ep.synopsis) existing.synopsis = ep.synopsis; if (ep.broadcastDate) existing.broadcastDate = ep.broadcastDate; if (ep.imageUrl) existing.imageUrl = ep.imageUrl; if (ep.title && !ep.title.startsWith("第")) existing.title = ep.title; } else { episodes.push(ep); } } } } return episodes; } export async function scrapeJajankenStats( options: Pick<DragonBallCrawlOptions, "proxy"> = {}, ): Promise<DbJumpStat[]> { const url = DRAGONBALL_URLS.jajankenStats(); logger.log("Scraping Weekly Shonen Jump DB rankings from Jajanken.net..."); const res = await fetch(url, { headers: { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36" }, ...directFetchProxy(options.proxy), }); if (!res.ok) throw new Error(`Jajanken request failed: ${res.status}`); const html = await res.text(); const stats: DbJumpStat[] = []; // Jajanken lists 519 chapters with class="sequence", "issue", "title", "order" const rowRegex = /<tr[^>]*>([\s\S]*?)<\/tr>/gi; let rMatch; while ((rMatch = rowRegex.exec(html)) !== null) { const row = rMatch[1]; if (!row.includes('class="issue"') || !row.includes('class="title"')) continue; const issueMatch = row.match(/<td[^>]*class=["'][^"']*issue[^"']*["'][^>]*>([\s\S]*?)<\/td>/i); const titleMatch = row.match(/<td[^>]*class=["'][^"']*title[^"']*["'][^>]*>([\s\S]*?)<\/td>/i); const orderMatch = row.match(/<td[^>]*class=["'][^"']*order[^"']*["'][^>]*>([\s\S]*?)<\/td>/i); if (issueMatch && titleMatch) { const issueStr = issueMatch[1].replace(/<[^>]*>/g, "").trim(); const rawTitle = titleMatch[1].replace(/<[^>]*>/g, " ").trim(); const cleanTitle = rawTitle.replace(/\s+/g, " "); const orderStr = orderMatch ? orderMatch[1].replace(/<[^>]*>/g, "").trim() : "1"; const yearMatch = issueStr.match(/(19\d{2}|20\d{2})/); const rankNum = parseInt(orderStr, 10); stats.push({ issue: issueStr, year: yearMatch ? parseInt(yearMatch[1], 10) : 1984, rank: isNaN(rankNum) ? 1 : rankNum, title: cleanTitle, cover: row.includes("表紙"), colorPages: row.includes("巻頭") || row.includes("カラー") }); } } return stats; } export async function scrapeToriyamaBiographies( options: Pick<DragonBallCrawlOptions, "proxy"> = {}, ): Promise<{ inlifeBio: string; caramelData: string; wikiJaSummary: string; }> { logger.log("Scraping Toriyama Akira biography documents..."); // 1. InLife archive let inlifeBio = ""; try { const res = await fetch(DRAGONBALL_URLS.inlifeBiography(), directFetchProxy(options.proxy)); if (res.ok) { const text = await res.text(); inlifeBio = text.replace(/<(script|style)\b[^>]*>[\s\S]*?<\/\1>/gi, "").replace(/<[^>]*>/g, " ").trim().slice(0, 15000); } } catch (e) { logger.warn(`InLife archive fetch warning: ${e}`); } // 2. Caramel Mama let caramelData = ""; try { const res = await fetch(DRAGONBALL_URLS.caramelBiography(), directFetchProxy(options.proxy)); if (res.ok) { const text = await res.text(); caramelData = text.replace(/<(script|style)\b[^>]*>[\s\S]*?<\/\1>/gi, "").replace(/<[^>]*>/g, " ").trim().slice(0, 15000); } } catch (e) { logger.warn(`Caramel Mama fetch warning: ${e}`); } // 3. Ja Wikipedia via direct API for clean content let wikiJaSummary = ""; try { const apiUrl = DRAGONBALL_URLS.wikipediaJaAkiraToriyama(); const res = await fetch(apiUrl, directFetchProxy(options.proxy)); if (res.ok) { const json = await res.json() as any; const pages = json.query?.pages; if (pages) { const firstKey = Object.keys(pages)[0]; wikiJaSummary = pages[firstKey]?.extract || ""; } } } catch (e) { logger.warn(`Wikipedia JA fetch warning: ${e}`); } return { inlifeBio, caramelData, wikiJaSummary }; } export async function runFullDragonBallCrawl( outDir: string, options: DragonBallCrawlOptions = {}, ): Promise<void> { await mkdir(outDir, { recursive: true }); const toeiDetailConcurrency = Math.max( 1, options.toeiDetailConcurrency ?? Math.min(12, Math.max(4, cpus().length)), ); const toeiDetailGate = new AsyncSemaphore(toeiDetailConcurrency); logger.log(`Starting concurrent Dragon Ball crawl pipeline -> ${outDir} (Toei detail workers: ${toeiDetailConcurrency})`); const [news, dbzEps, dbsEps, dbKaiEps, dbClassicEps, dbGtEps, dbDaimaEps, jumpStats, toriyamaBios, shenronCatalogue] = await Promise.all([ scrapeDragonBallOfficialNews(20, options).catch(err => { logger.error(`News error: ${err}`); return []; }), scrapeToeiSeriesEpisodes("dragonz", "dragon_ball_z", { ...options, toeiDetailConcurrency, toeiDetailGate }).catch(err => { logger.error(`DBZ error: ${err}`); return []; }), scrapeToeiSeriesEpisodes("dragon_super", "dragon_ball_super", { ...options, toeiDetailConcurrency, toeiDetailGate }).catch(err => { logger.error(`DBS error: ${err}`); return []; }), scrapeToeiSeriesEpisodes("dragon_kai", "dragon_ball_kai", { ...options, toeiDetailConcurrency, toeiDetailGate }).catch(err => { logger.error(`DB Kai error: ${err}`); return []; }), scrapeToeiSeriesEpisodes("dragon", "dragon_ball", { ...options, toeiDetailConcurrency, toeiDetailGate }).catch(err => { logger.error(`DB Classic error: ${err}`); return []; }), scrapeToeiSeriesEpisodes("dragon_gt", "dragon_gt", { ...options, toeiDetailConcurrency, toeiDetailGate }).catch(err => { logger.error(`DB GT error: ${err}`); return []; }), scrapeToeiSeriesEpisodes("dragonball_daima", "dragonball_daima", { ...options, toeiDetailConcurrency, toeiDetailGate }).catch(err => { logger.error(`DB Daima error: ${err}`); return []; }), scrapeJajankenStats(options).catch(err => { logger.error(`Jajanken error: ${err}`); return []; }), scrapeToriyamaBiographies(options).catch(err => { logger.error(`Toriyama bios error: ${err}`); return { inlifeBio: "", caramelData: "", wikiJaSummary: "" }; }), scrapeShenronCatalogue(options).catch(err => { logger.error(`Shenron catalogue error: ${err}`); return { episodes: [], movies: [], assets: [] }; }), ]); // Generate ready-to-publish French news feed articles from db_official_news const frenchArticles = news.map(item => { return { slug: item.id, sourceUrl: item.url, title_ja: item.title, title_fr: `[Officiel] ${item.title}`, date: item.date, category: item.category, imageUrl: item.imageUrl, body_markdown: `*Source officielle: [dragon-ball-official.com](${item.url}) — Date: ${item.date}*\n\n` + `**Titre original**: ${item.title}\n\n` + `Cet article provient du portail officiel Dragon Ball au Japon.\n\n` + (item.imageUrl ? `![Illustration](${item.imageUrl})\n\n` : "") + `Retrouvez toutes les informations détaillées sur l'annonce dans la section ${item.category}.` }; }); const datasets = { news: "db_official_news.json", episodesDbz: "toei_episodes_dbz.json", episodesDbs: "toei_episodes_dbs.json", episodesKai: "toei_episodes_kai.json", episodesClassic: "toei_episodes_classic.json", episodesGt: "toei_episodes_gt.json", episodesDaima: "toei_episodes_daima.json", jumpStats: "jajanken_jump_stats.json", toriyamaArchives: "toriyama_archives.json", shenronNewsFeed: "shenron_feed_actu.json", shenronCatalogue: "shenron_catalogue.json", shenronAssets: "shenron_assets.json", shenronCanon: "shenron_canon_consolidated.json", }; const manifest: ShenronCrawlManifest = { schema: "bxc-dragonball-crawl/v1", generatedAt: new Date().toISOString(), source: "bxc", datasets, }; // Bun writes independent files in parallel; the manifest is written last so // a private Shenron importer never observes a half-produced crawl batch. await Promise.all([ Bun.write(join(outDir, datasets.news), JSON.stringify(news, null, 2)), Bun.write(join(outDir, datasets.episodesDbz), JSON.stringify(dbzEps, null, 2)), Bun.write(join(outDir, datasets.episodesDbs), JSON.stringify(dbsEps, null, 2)), Bun.write(join(outDir, datasets.episodesKai), JSON.stringify(dbKaiEps, null, 2)), Bun.write(join(outDir, datasets.episodesClassic), JSON.stringify(dbClassicEps, null, 2)), Bun.write(join(outDir, datasets.episodesGt), JSON.stringify(dbGtEps, null, 2)), Bun.write(join(outDir, datasets.episodesDaima), JSON.stringify(dbDaimaEps, null, 2)), Bun.write(join(outDir, datasets.jumpStats), JSON.stringify(jumpStats, null, 2)), Bun.write(join(outDir, datasets.toriyamaArchives), JSON.stringify(toriyamaBios, null, 2)), Bun.write(join(outDir, datasets.shenronNewsFeed), JSON.stringify(frenchArticles, null, 2)), Bun.write(join(outDir, datasets.shenronCatalogue), JSON.stringify(shenronCatalogue, null, 2)), Bun.write(join(outDir, datasets.shenronAssets), JSON.stringify(shenronCatalogue.assets, null, 2)), Bun.write(join(outDir, datasets.shenronCanon), JSON.stringify(SHENRON_CONSOLIDATED, null, 2)), ]); await Bun.write(join(outDir, "shenron-ingest-manifest.json"), JSON.stringify(manifest, null, 2)); logger.log(`Crawl completed successfully! Produced ${news.length} news, ${dbzEps.length + dbsEps.length + dbKaiEps.length + dbClassicEps.length + dbGtEps.length + dbDaimaEps.length} Toei episodes, ${jumpStats.length} Jump stats, ${shenronCatalogue.episodes.length} Shenron episodes, ${shenronCatalogue.assets.length} Shenron assets, and canonical Shenron dossier.`); } export async function main(argv: readonly string[], opts: CommonOptions): Promise<void> { let outDir = join(process.cwd(), "data", "dragonball"); let toeiDetailConcurrency: number | undefined; let toeiDetailLimit: number | undefined; let pipeline = false; let dryRun = false; let shenron = false; let json = Boolean(opts.json); for (let index = 0; index < argv.length; index++) { const arg = argv[index]; if (arg === "shenron" || arg === "--shenron") shenron = true; else if (arg === "--json") json = true; else if (arg === "--toei-concurrency") toeiDetailConcurrency = Number(argv[++index]); else if (arg === "--toei-detail-limit") toeiDetailLimit = Number(argv[++index]); else if (arg === "--pipeline") pipeline = true; else if (arg === "--dry-run") dryRun = true; else if (!arg.startsWith("-")) outDir = arg; else throw new Error(`Unknown dragonball option: ${arg}`); } if (shenron) { if (json) { console.log(JSON.stringify(SHENRON_CONSOLIDATED, null, 2)); return; } console.log(`================================================================`); console.log(` SHENRON (神龍) — Canonical Dragon Ball Dossier (ID: ${SHENRON_CONSOLIDATED.character_id})`); console.log(`================================================================`); console.log(`Nom: ${SHENRON_CONSOLIDATED.name} (${SHENRON_CONSOLIDATED.name_ja} / ${SHENRON_CONSOLIDATED.name_romaji})`); console.log(`Titre: ${SHENRON_CONSOLIDATED.title_canon}`); console.log(`Race: ${SHENRON_CONSOLIDATED.race_name} (ID: ${SHENRON_CONSOLIDATED.race_id}, slug: ${SHENRON_CONSOLIDATED.race_slug})`); console.log(`Planète: ${SHENRON_CONSOLIDATED.origin_planet_name} (ID: ${SHENRON_CONSOLIDATED.origin_planet_id})`); console.log(`Résidence: ${SHENRON_CONSOLIDATED.location}`); console.log(`Affiliation: ${SHENRON_CONSOLIDATED.affiliation}`); console.log(`\n--- CRÉATEURS ET GARDIENS (${SHENRON_CONSOLIDATED.creators.length}) ---`); for (const c of SHENRON_CONSOLIDATED.creators) { console.log(` • ${c.name} [${c.title}] - ${c.role}`); } console.log(`\n--- RÈGLES CANONIQUES DES SOUHAITS ---`); console.log(` • Ère Kami-sama: ${SHENRON_CONSOLIDATED.rules.wishes_count_kami_sama} souhait.`); console.log(` • Ère Dendé: ${SHENRON_CONSOLIDATED.rules.wishes_count_dende} souhaits (coût résurrection de masse: ${SHENRON_CONSOLIDATED.rules.mass_resurrection_cost_dende} souhaits).`); console.log(` • Rechargement: ${SHENRON_CONSOLIDATED.rules.cooldown_full_year} an (ou ${SHENRON_CONSOLIDATED.rules.cooldown_partial_months_per_wish} mois par souhait consommé).`); console.log(` • Mort naturelle: ${SHENRON_CONSOLIDATED.rules.natural_death_restriction}`); console.log(` • Limite résurrection: ${SHENRON_CONSOLIDATED.rules.one_time_resurrection_limit}`); console.log(` • Plafond de puissance: ${SHENRON_CONSOLIDATED.rules.creator_power_ceiling}`); console.log(` • Neutralité morale: ${SHENRON_CONSOLIDATED.rules.moral_neutrality}`); console.log(`\n--- ÉVÉNEMENTS CHRONOLOGIQUES MORTS / RÉSURRECTIONS (${SHENRON_CONSOLIDATED.deaths_and_rebirths.length}) ---`); for (const d of SHENRON_CONSOLIDATED.deaths_and_rebirths) { console.log(` [${d.year_dragon_world > 0 ? `An ${d.year_dragon_world}` : "Origine"}] (${d.type.toUpperCase()}) ${d.cause}`); console.log(` Réf: ${d.manga_reference} | Acteurs: ${d.actors.join(", ")}`); } console.log(`\n--- INVOCATIONS CANONIQUES DU MANGA (${SHENRON_CONSOLIDATED.manga_canon_wishes.length}) ---`); for (const w of SHENRON_CONSOLIDATED.manga_canon_wishes) { console.log(` #${w.invocation_number} [Ère ${w.era}] Chapitre ${w.chapter} (Tome ${w.volume}): Invoqué par ${w.summoner}`); console.log(` Souhait: "${w.wish_text}" -> ${w.consequence}`); } console.log(`\n--- SOURCES PRIMAIRES ---`); for (const s of SHENRON_CONSOLIDATED.primary_sources) { console.log(` • ${s.work} (${s.nature}, autorité: ${s.authority})`); } console.log(`================================================================\n`); return; } if (toeiDetailConcurrency !== undefined && (!Number.isInteger(toeiDetailConcurrency) || toeiDetailConcurrency < 1)) { throw new Error("--toei-concurrency must be a positive integer"); } if (toeiDetailLimit !== undefined && (!Number.isInteger(toeiDetailLimit) || toeiDetailLimit < 1)) { throw new Error("--toei-detail-limit must be a positive integer"); } if (pipeline) await runDragonBallUnifiedPipeline(outDir, { dryRun, proxy: opts.proxy }); else await runFullDragonBallCrawl(outDir, { toeiDetailConcurrency, toeiDetailLimit, proxy: opts.proxy }); }