scaffold.ts 5.35 KB
import fs from 'node:fs';
import path from 'node:path';

/**
 * Deterministic React + Vite + TS + TailwindCSS V4 + Less scaffold.
 *
 * Why this exists: the original INITIAL node drove an LLM agent (evoltagent) to
 * generate these files. That agent has an unbounded `while(true)` loop and is
 * fragile against some OpenAI-compatible endpoints (e.g. Aliyun MAAS Qwen),
 * which caused runs to hang indefinitely at "Initializing project...".
 *
 * The scaffold is identical on every run (the only variable is the app name /
 * page title), so generating it directly is faster, deterministic, and removes
 * the model from the critical path. The generated structure matches exactly
 * what the downstream CODE node expects (src/components, src/App.tsx, etc.).
 */

function renderPackageJson(appName: string): string {
    return JSON.stringify(
        {
            name: appName || 'my-app',
            private: true,
            version: '0.0.0',
            type: 'module',
            scripts: {
                dev: 'pnpm exec vite',
                build: 'pnpm exec tsc && pnpm exec vite build',
                preview: 'pnpm exec vite preview',
            },
            dependencies: {
                react: '^18.3.1',
                'react-dom': '^18.3.1',
            },
            devDependencies: {
                '@tailwindcss/vite': '^4.1.4',
                '@types/node': '^20.17.30',
                '@types/react': '^18.3.20',
                '@types/react-dom': '^18.3.6',
                '@vitejs/plugin-react': '^4.4.1',
                less: '^4.3.0',
                tailwindcss: '^4.1.4',
                typescript: '~5.8.3',
                vite: '^6.3.5',
            },
        },
        null,
        2
    );
}

function renderViteConfig(): string {
    return `import path from "node:path";
import { fileURLToPath } from "node:url";
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import tailwindcss from "@tailwindcss/vite";

const __dirname = path.dirname(fileURLToPath(import.meta.url));

export default defineConfig({
  plugins: [react(), tailwindcss()],
  resolve: {
    alias: {
      "@": path.resolve(__dirname, "./src"),
    },
  },
});
`;
}

function renderTsConfig(): string {
    return `{
  "compilerOptions": {
    "target": "ES2020",
    "useDefineForClassFields": true,
    "lib": ["ES2020", "DOM", "DOM.Iterable"],
    "module": "ESNext",
    "moduleResolution": "bundler",
    "allowImportingTsExtensions": true,
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx",
    "strict": true,
    "skipLibCheck": true,
    "baseUrl": ".",
    "paths": {
      "@/*": ["src/*"]
    }
  },
  "include": ["src"]
}
`;
}

function renderIndexHtml(title: string): string {
    return `<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>${title}</title>
  </head>
  <body>
    <div id="root"></div>
    <script type="module" src="/src/main.tsx"></script>
  </body>
</html>
`;
}

function renderMainTsx(): string {
    return `import React from "react";
import ReactDOM from "react-dom/client";
import App from "@/App";
import "@/globals.css";
import "@/App.less";

ReactDOM.createRoot(document.getElementById("root")!).render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);
`;
}

function renderAppTsx(): string {
    return `import ReviewDetailPage from '@/components';

export default function App() {
  return <div><ReviewDetailPage /></div>;
}
`;
}

function renderGlobalsCss(): string {
    return `@import "tailwindcss";
`;
}

function renderAppLess(): string {
    return ``;
}

function renderViteEnvDts(): string {
    return `/// <reference types="vite/client" />
`;
}

function renderGitignore(): string {
    return `# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*

# Dependencies
node_modules/

# Build output
dist/
build/
dist-ssr/
*.local

# Environment files
.env
.env.*

# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea/
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

# Cache
.cache/
.eslintcache
.stylelintcache
*.tsbuildinfo

# Lock files
package-lock.json
yarn.lock
pnpm-lock.yaml
`;
}

/**
 * Write the full scaffold into `appPath`.
 * @param appPath absolute path to the generated app folder
 * @param appName project name (used in package.json and page title)
 */
export function writeScaffold(appPath: string, appName: string): void {
    const files: Record<string, string> = {
        'package.json': renderPackageJson(appName),
        'vite.config.ts': renderViteConfig(),
        'tsconfig.json': renderTsConfig(),
        'index.html': renderIndexHtml(appName || 'my-app'),
        'src/main.tsx': renderMainTsx(),
        'src/App.tsx': renderAppTsx(),
        'src/globals.css': renderGlobalsCss(),
        'src/App.less': renderAppLess(),
        'src/vite-env.d.ts': renderViteEnvDts(),
        '.gitignore': renderGitignore(),
    };

    for (const [rel, content] of Object.entries(files)) {
        const full = path.join(appPath, rel);
        fs.mkdirSync(path.dirname(full), { recursive: true });
        fs.writeFileSync(full, content, 'utf8');
    }

    // Ensure the components directory exists (App.tsx imports from '@/components').
    fs.mkdirSync(path.join(appPath, 'src', 'components'), { recursive: true });
}