import fs from "fs"; import path from "path"; import { execSync } from "child_process"; // 1. Read config to get token and space target const CONFIG_PATH = path.join(process.cwd(), "data", "config.json"); if (!fs.existsSync(CONFIG_PATH)) { console.error("Config file not found at", CONFIG_PATH); process.exit(1); } const config = JSON.parse(fs.readFileSync(CONFIG_PATH, "utf-8")); const token = config.hfToken; const space = config.hfSpace; if (!token || !space) { console.error("Hugging Face space path or token is missing from config.json!"); console.error("Current settings: Space:", space, "Token:", token ? "FOUND" : "MISSING"); process.exit(1); } const tempDir = path.join(process.cwd(), "data", `hf_project_push_${Date.now()}`); console.log(`[Hugging Face Setup] Space path: ${space}`); console.log(`[Hugging Face Setup] Creating temporary workspace at: ${tempDir}`); // Ensure tempDir is clean if (fs.existsSync(tempDir)) { fs.rmSync(tempDir, { recursive: true, force: true }); } fs.mkdirSync(tempDir, { recursive: true }); try { // Cloning space console.log("[Hugging Face Setup] Cloning Space repository..."); const gitUrl = `https://user:${token}@huggingface.co/spaces/${space}`; execSync(`git clone ${gitUrl} ${tempDir} --depth 1`, { env: { ...process.env, GIT_TERMINAL_PROMPT: "0" }, stdio: "inherit" }); console.log("[Hugging Face Setup] Cloned successfully. Moving files..."); // Write .dockerignore and Dockerfile and README.md const readmeContent = `--- title: Streamapi emoji: 📺 colorFrom: blue colorTo: indigo sdk: docker pinned: false --- # Live Stream M3U8 Extractor This application is hosted on Hugging Face Spaces! It automatically crawls live channels to retrieve M3U8 streaming sources and compiles them into a cached playlist. `; const dockerfileContent = `FROM node:20-slim WORKDIR /app # Install git RUN apt-get update && apt-get install -y git && rm -rf /var/lib/apt/lists/* # Copy package config files COPY package*.json ./ # Install all dependencies (production & development for compilation) RUN npm install # Copy full source COPY . . # Build application (generates /dist and /dist/server.cjs) RUN npm run build # Configure default directory permissions RUN mkdir -p /app/data && chmod -R 777 /app/data # Expose Space port EXPOSE 7860 ENV PORT=7860 ENV NODE_ENV=production # Start container CMD ["npm", "run", "start"] `; const dockerignoreContent = `node_modules dist .git .github *.log data/hf_project_push_* data/hf_push_* `; // Custom function to copy directory recursively while ignoring certain folders function copyRecursiveSync(src: string, dest: string, ignorePatterns: RegExp[]) { const stats = fs.statSync(src); const isDir = stats.isDirectory(); const isIgnored = ignorePatterns.some(pat => pat.test(src) || pat.test(path.basename(src))); if (isIgnored) return; if (isDir) { if (!fs.existsSync(dest)) { fs.mkdirSync(dest, { recursive: true }); } fs.readdirSync(src).forEach((child) => { copyRecursiveSync(path.join(src, child), path.join(dest, child), ignorePatterns); }); } else { fs.copyFileSync(src, dest); } } // Clear everything in clone directory except .git fs.readdirSync(tempDir).forEach(file => { if (file !== ".git") { const fullPath = path.join(tempDir, file); fs.rmSync(fullPath, { recursive: true, force: true }); } }); const rootFilesToCopy = fs.readdirSync(process.cwd()); const ignoreList = [ /node_modules/, /dist/, /\.git$/, /\.github/, /hf_project_push_/, /hf_push_/, /\.env/, /package-lock\.json/ ]; console.log("[Hugging Face Setup] Copying project files..."); rootFilesToCopy.forEach((file) => { if (file !== "data" && file !== "node_modules" && file !== "dist" && file !== ".git") { copyRecursiveSync(path.join(process.cwd(), file), path.join(tempDir, file), ignoreList); } }); // Make sure we copy the critical parts of data folder (channels/configs) but NOT other temp stuff if (fs.existsSync(path.join(process.cwd(), "data"))) { fs.mkdirSync(path.join(tempDir, "data"), { recursive: true }); fs.readdirSync(path.join(process.cwd(), "data")).forEach(dataFile => { if (dataFile === "config.json") { const fullLocalPath = path.join(process.cwd(), "data", dataFile); const configData = JSON.parse(fs.readFileSync(fullLocalPath, "utf-8")); // Strip out the hfToken to comply with HF security checks, but leave the other parts intact configData.hfToken = ""; fs.writeFileSync(path.join(tempDir, "data", dataFile), JSON.stringify(configData, null, 2), "utf-8"); } }); } // Write HF config files directly console.log("[Hugging Face Setup] Injecting Dockerfile, dockerignore & README.md metadata..."); fs.writeFileSync(path.join(tempDir, "README.md"), readmeContent, "utf-8"); fs.writeFileSync(path.join(tempDir, "Dockerfile"), dockerfileContent, "utf-8"); fs.writeFileSync(path.join(tempDir, ".dockerignore"), dockerignoreContent, "utf-8"); // Git configure, commit, and push const gitCmd = (cmd: string) => { console.log(`[Git] Executing: ${cmd}`); return execSync(cmd, { cwd: tempDir, encoding: "utf8", env: { ...process.env, GIT_TERMINAL_PROMPT: "0" } }); }; gitCmd("git config user.name 'M3U8 Auto Stream Deployer'"); gitCmd("git config user.email 'deployer@streamapi.com'"); gitCmd("git add ."); const status = gitCmd("git status --porcelain").trim(); if (status.length === 0) { console.log("[Hugging Face Setup] No file changes to push. Project is fully up-to-date inside Hugging Face Space repo!"); } else { gitCmd("git commit -m 'Deploy full project code with Docker runtime'"); console.log("[Hugging Face Setup] Pushing files directly to main branch on Hugging Face..."); gitCmd("git push origin main"); console.log("[Hugging Face Setup] Push succeeded! App will build and launch on your Hugging Face space."); } } catch (error: any) { console.error("[Hugging Face Setup] An error occurred during setup & push:", error.message || error); } finally { // Always clean up temp directory if (fs.existsSync(tempDir)) { console.log("[Hugging Face Setup] Cleaning up temporary workspace..."); fs.rmSync(tempDir, { recursive: true, force: true }); } }