From 198816b0421b375fba3a5d49c92e8566bea585a7 Mon Sep 17 00:00:00 2001 From: fry69 <142489379+fry69@users.noreply.github.com> Date: Mon, 6 Oct 2025 09:12:07 +0200 Subject: [PATCH] feat(init): template based init script (#3524) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Supersedes earlier attempt -> https://github.com/denoland/fresh/pull/3517 This is now ready for review. The major upside and motivation for this template based approach is that it is now possible to view what gets generated in the repository as actual valid files including syntax highlighting and formatting. Previously those files where just strings inside the old `init` script, which is IMHO a nightmare for maintainability. The approach for this template system is loosely based on Vite's `create-vite`, which also includes (redundant) templates inside the repository, see here -> https://github.com/vitejs/vite/tree/main/packages/create-vite Included in the tests are compatibility checks against the current `@fresh/init@2.0.9`, those can get removed at a later point when the templates start to diverge. They are only included for demonstration purposes, that this new implementation generates 100% identical output. This means that the first PR after this got included, which modifies the templates so the output differs from the old `init` script, also needs to include: ```shell rm packages/init/tests/compatibility_test.ts ``` Since this is a rather large PR, it may be more approachable to view the branch directly -> https://github.com/fry69/fresh/tree/fry69/refactor-init-template-rename/packages/init Generated PR message below: --- Replaces inline string-based project generation with file-based templates for improved maintainability and extensibility. ### Architecture **Template structure:** - `assets/template/` - Complete project templates (vite, vite-tailwind, builder, builder-tailwind) - `assets/variants/` - Additive overlays (docker, vscode, vscode-tailwind) - `assets/base/` - Common files synced across template variants Templates use `__VARIABLE__` syntax for substitution (project name, dependency versions). Files with `__` prefix are renamed to `.` prefix during generation (e.g., `__gitignore` → .gitignore). **Template selection logic:** ``` Base: vite|vite-tailwind|builder|builder-tailwind Variants: +docker, +vscode, +vscode-tailwind ``` ### Maintenance workflow Edit shared files in `assets/base/vite/` or `assets/base/builder/`, then run `deno task sync` to propagate changes to template variants. Template-specific files (deno.json, vite.config.ts, styles.css) are never overwritten. ### Version resolution Matches existing behavior: only Fresh core version is fetched from JSR, all other dependencies use fixed versions updated by release scripts. ### Testing 55 tests covering: - Unit tests for core functionality - Integration tests (project generation, builds, dev servers) - CLI argument parsing - Compatibility tests verifying output matches v2.0.9 (pre-refactor baseline) - Template sync workflow ### Breaking changes None. CLI interface and programmatic API remain identical. Package publishes to same `@fresh/init` scope at JSR. ### Documentation - README.md - User-facing usage documentation - DESIGN.md - Maintainer documentation (architecture, template maintenance, development setup) --- deno.lock | 12 + packages/init/DESIGN.md | 135 ++ packages/init/README.md | 64 +- packages/init/assets/base/builder/README.md | 17 + packages/init/assets/base/builder/__gitignore | 13 + .../assets/base/builder/components/Button.tsx | 17 + .../assets/base/builder/islands/Counter.tsx | 16 + packages/init/assets/base/builder/main.ts | 30 + .../init/assets/base/builder/routes/_app.tsx | 17 + .../assets/base/builder/routes/api/[name].tsx | 10 + .../init/assets/base/builder/routes/index.tsx | 33 + .../init/assets/base/builder/static/logo.svg | 19 + packages/init/assets/base/builder/utils.ts | 9 + packages/init/assets/base/vite/README.md | 17 + packages/init/assets/base/vite/__gitignore | 13 + .../assets/base/vite/components/Button.tsx | 17 + .../init/assets/base/vite/islands/Counter.tsx | 16 + packages/init/assets/base/vite/main.ts | 30 + .../init/assets/base/vite/routes/_app.tsx | 16 + .../assets/base/vite/routes/api/[name].tsx | 10 + .../init/assets/base/vite/routes/index.tsx | 33 + .../init/assets/base/vite/static/logo.svg | 19 + packages/init/assets/base/vite/utils.ts | 9 + .../template/builder-tailwind/README.md | 17 + .../template/builder-tailwind/__gitignore | 13 + .../builder-tailwind/components/Button.tsx | 17 + .../template/builder-tailwind/deno.json | 56 + .../assets/template/builder-tailwind/dev.ts | 12 + .../builder-tailwind/islands/Counter.tsx | 16 + .../assets/template/builder-tailwind/main.ts | 30 + .../template/builder-tailwind/routes/_app.tsx | 17 + .../builder-tailwind/routes/api/[name].tsx | 10 + .../builder-tailwind/routes/index.tsx | 33 + .../template/builder-tailwind/static/logo.svg | 19 + .../builder-tailwind/static/styles.css | 10 + .../assets/template/builder-tailwind/utils.ts | 9 + .../init/assets/template/builder/README.md | 17 + .../init/assets/template/builder/__gitignore | 13 + .../template/builder/components/Button.tsx | 17 + .../init/assets/template/builder/deno.json | 52 + packages/init/assets/template/builder/dev.ts | 11 + .../template/builder/islands/Counter.tsx | 16 + packages/init/assets/template/builder/main.ts | 30 + .../assets/template/builder/routes/_app.tsx | 17 + .../template/builder/routes/api/[name].tsx | 10 + .../assets/template/builder/routes/index.tsx | 33 + .../assets/template/builder/static/logo.svg | 19 + .../assets/template/builder/static/styles.css | 144 +++ .../init/assets/template/builder/utils.ts | 9 + .../assets/template/vite-tailwind/README.md | 17 + .../assets/template/vite-tailwind/__gitignore | 13 + .../template/vite-tailwind/assets/styles.css | 10 + .../assets/template/vite-tailwind/client.ts | 2 + .../vite-tailwind/components/Button.tsx | 17 + .../assets/template/vite-tailwind/deno.json | 59 + .../vite-tailwind/islands/Counter.tsx | 16 + .../assets/template/vite-tailwind/main.ts | 30 + .../template/vite-tailwind/routes/_app.tsx | 16 + .../vite-tailwind/routes/api/[name].tsx | 10 + .../template/vite-tailwind/routes/index.tsx | 33 + .../template/vite-tailwind/static/logo.svg | 19 + .../assets/template/vite-tailwind/utils.ts | 9 + .../template/vite-tailwind/vite.config.ts | 7 + packages/init/assets/template/vite/README.md | 17 + .../init/assets/template/vite/__gitignore | 13 + .../assets/template/vite/assets/styles.css | 144 +++ packages/init/assets/template/vite/client.ts | 2 + .../template/vite/components/Button.tsx | 17 + packages/init/assets/template/vite/deno.json | 57 + .../assets/template/vite/islands/Counter.tsx | 16 + packages/init/assets/template/vite/main.ts | 30 + .../init/assets/template/vite/routes/_app.tsx | 16 + .../template/vite/routes/api/[name].tsx | 10 + .../assets/template/vite/routes/index.tsx | 33 + .../init/assets/template/vite/static/logo.svg | 19 + packages/init/assets/template/vite/utils.ts | 9 + .../init/assets/template/vite/vite.config.ts | 6 + .../init/assets/variants/docker/Dockerfile | 15 + .../vscode-tailwind/__vscode/extensions.json | 6 + .../vscode-tailwind/__vscode/settings.json | 20 + .../vscode-tailwind/__vscode/tailwind.json | 55 + .../variants/vscode/__vscode/extensions.json | 5 + .../variants/vscode/__vscode/settings.json | 17 + packages/init/deno.json | 29 +- packages/init/src/assets/favicon.ico | Bin 22382 -> 0 bytes packages/init/src/init.ts | 1103 ++++------------- packages/init/src/init_test.ts | 363 ------ packages/init/src/mod.ts | 240 +++- packages/init/src/sync.ts | 211 ++++ packages/init/src/types.ts | 82 ++ packages/init/src/utils.ts | 186 +++ packages/init/tests/cli_test.ts | 131 ++ packages/init/tests/compatibility_test.ts | 320 +++++ packages/init/tests/init_test.ts | 249 ++++ packages/init/tests/integration_test.ts | 273 ++++ packages/init/tests/sync_test.ts | 379 ++++++ packages/init/tests/template_test.ts | 219 ++++ packages/init/tests/utils_test.ts | 82 ++ 98 files changed, 4615 insertions(+), 1236 deletions(-) create mode 100644 packages/init/DESIGN.md create mode 100644 packages/init/assets/base/builder/README.md create mode 100644 packages/init/assets/base/builder/__gitignore create mode 100644 packages/init/assets/base/builder/components/Button.tsx create mode 100644 packages/init/assets/base/builder/islands/Counter.tsx create mode 100644 packages/init/assets/base/builder/main.ts create mode 100644 packages/init/assets/base/builder/routes/_app.tsx create mode 100644 packages/init/assets/base/builder/routes/api/[name].tsx create mode 100644 packages/init/assets/base/builder/routes/index.tsx create mode 100644 packages/init/assets/base/builder/static/logo.svg create mode 100644 packages/init/assets/base/builder/utils.ts create mode 100644 packages/init/assets/base/vite/README.md create mode 100644 packages/init/assets/base/vite/__gitignore create mode 100644 packages/init/assets/base/vite/components/Button.tsx create mode 100644 packages/init/assets/base/vite/islands/Counter.tsx create mode 100644 packages/init/assets/base/vite/main.ts create mode 100644 packages/init/assets/base/vite/routes/_app.tsx create mode 100644 packages/init/assets/base/vite/routes/api/[name].tsx create mode 100644 packages/init/assets/base/vite/routes/index.tsx create mode 100644 packages/init/assets/base/vite/static/logo.svg create mode 100644 packages/init/assets/base/vite/utils.ts create mode 100644 packages/init/assets/template/builder-tailwind/README.md create mode 100644 packages/init/assets/template/builder-tailwind/__gitignore create mode 100644 packages/init/assets/template/builder-tailwind/components/Button.tsx create mode 100644 packages/init/assets/template/builder-tailwind/deno.json create mode 100644 packages/init/assets/template/builder-tailwind/dev.ts create mode 100644 packages/init/assets/template/builder-tailwind/islands/Counter.tsx create mode 100644 packages/init/assets/template/builder-tailwind/main.ts create mode 100644 packages/init/assets/template/builder-tailwind/routes/_app.tsx create mode 100644 packages/init/assets/template/builder-tailwind/routes/api/[name].tsx create mode 100644 packages/init/assets/template/builder-tailwind/routes/index.tsx create mode 100644 packages/init/assets/template/builder-tailwind/static/logo.svg create mode 100644 packages/init/assets/template/builder-tailwind/static/styles.css create mode 100644 packages/init/assets/template/builder-tailwind/utils.ts create mode 100644 packages/init/assets/template/builder/README.md create mode 100644 packages/init/assets/template/builder/__gitignore create mode 100644 packages/init/assets/template/builder/components/Button.tsx create mode 100644 packages/init/assets/template/builder/deno.json create mode 100644 packages/init/assets/template/builder/dev.ts create mode 100644 packages/init/assets/template/builder/islands/Counter.tsx create mode 100644 packages/init/assets/template/builder/main.ts create mode 100644 packages/init/assets/template/builder/routes/_app.tsx create mode 100644 packages/init/assets/template/builder/routes/api/[name].tsx create mode 100644 packages/init/assets/template/builder/routes/index.tsx create mode 100644 packages/init/assets/template/builder/static/logo.svg create mode 100644 packages/init/assets/template/builder/static/styles.css create mode 100644 packages/init/assets/template/builder/utils.ts create mode 100644 packages/init/assets/template/vite-tailwind/README.md create mode 100644 packages/init/assets/template/vite-tailwind/__gitignore create mode 100644 packages/init/assets/template/vite-tailwind/assets/styles.css create mode 100644 packages/init/assets/template/vite-tailwind/client.ts create mode 100644 packages/init/assets/template/vite-tailwind/components/Button.tsx create mode 100644 packages/init/assets/template/vite-tailwind/deno.json create mode 100644 packages/init/assets/template/vite-tailwind/islands/Counter.tsx create mode 100644 packages/init/assets/template/vite-tailwind/main.ts create mode 100644 packages/init/assets/template/vite-tailwind/routes/_app.tsx create mode 100644 packages/init/assets/template/vite-tailwind/routes/api/[name].tsx create mode 100644 packages/init/assets/template/vite-tailwind/routes/index.tsx create mode 100644 packages/init/assets/template/vite-tailwind/static/logo.svg create mode 100644 packages/init/assets/template/vite-tailwind/utils.ts create mode 100644 packages/init/assets/template/vite-tailwind/vite.config.ts create mode 100644 packages/init/assets/template/vite/README.md create mode 100644 packages/init/assets/template/vite/__gitignore create mode 100644 packages/init/assets/template/vite/assets/styles.css create mode 100644 packages/init/assets/template/vite/client.ts create mode 100644 packages/init/assets/template/vite/components/Button.tsx create mode 100644 packages/init/assets/template/vite/deno.json create mode 100644 packages/init/assets/template/vite/islands/Counter.tsx create mode 100644 packages/init/assets/template/vite/main.ts create mode 100644 packages/init/assets/template/vite/routes/_app.tsx create mode 100644 packages/init/assets/template/vite/routes/api/[name].tsx create mode 100644 packages/init/assets/template/vite/routes/index.tsx create mode 100644 packages/init/assets/template/vite/static/logo.svg create mode 100644 packages/init/assets/template/vite/utils.ts create mode 100644 packages/init/assets/template/vite/vite.config.ts create mode 100644 packages/init/assets/variants/docker/Dockerfile create mode 100644 packages/init/assets/variants/vscode-tailwind/__vscode/extensions.json create mode 100644 packages/init/assets/variants/vscode-tailwind/__vscode/settings.json create mode 100644 packages/init/assets/variants/vscode-tailwind/__vscode/tailwind.json create mode 100644 packages/init/assets/variants/vscode/__vscode/extensions.json create mode 100644 packages/init/assets/variants/vscode/__vscode/settings.json delete mode 100644 packages/init/src/assets/favicon.ico delete mode 100644 packages/init/src/init_test.ts create mode 100644 packages/init/src/sync.ts create mode 100644 packages/init/src/types.ts create mode 100644 packages/init/src/utils.ts create mode 100644 packages/init/tests/cli_test.ts create mode 100644 packages/init/tests/compatibility_test.ts create mode 100644 packages/init/tests/init_test.ts create mode 100644 packages/init/tests/integration_test.ts create mode 100644 packages/init/tests/sync_test.ts create mode 100644 packages/init/tests/template_test.ts create mode 100644 packages/init/tests/utils_test.ts diff --git a/deno.lock b/deno.lock index 9850a590..e9f2382a 100644 --- a/deno.lock +++ b/deno.lock @@ -19,6 +19,7 @@ "jsr:@std/async@^1.0.13": "1.0.14", "jsr:@std/bytes@^1.0.5": "1.0.6", "jsr:@std/bytes@^1.0.6": "1.0.6", + "jsr:@std/cli@1": "1.0.22", "jsr:@std/cli@^1.0.19": "1.0.22", "jsr:@std/cli@^1.0.21": "1.0.22", "jsr:@std/collections@^1.1.2": "1.1.3", @@ -29,6 +30,7 @@ "jsr:@std/encoding@1": "1.0.10", "jsr:@std/encoding@^1.0.10": "1.0.10", "jsr:@std/expect@^1.0.16": "1.0.17", + "jsr:@std/fmt@1": "1.0.8", "jsr:@std/fmt@1.0.3": "1.0.3", "jsr:@std/fmt@^1.0.3": "1.0.8", "jsr:@std/fmt@^1.0.7": "1.0.8", @@ -3752,6 +3754,16 @@ "npm:@types/node@^24.2.1" ] }, + "packages/init": { + "dependencies": [ + "jsr:@std/cli@1", + "jsr:@std/fmt@1", + "jsr:@std/fs@1", + "jsr:@std/jsonc@1", + "jsr:@std/path@1", + "jsr:@std/semver@1" + ] + }, "packages/plugin-tailwindcss-v3": { "dependencies": [ "npm:autoprefixer@^10.4.21", diff --git a/packages/init/DESIGN.md b/packages/init/DESIGN.md new file mode 100644 index 00000000..b95fe053 --- /dev/null +++ b/packages/init/DESIGN.md @@ -0,0 +1,135 @@ +# Architecture & Maintenance + +Maintainer documentation for `@fresh/init`. + +## Design Philosophy + +Templates are **complete, standalone projects**. The system selects one base +template and optionally applies variant overlays on top. + +## Directory Structure + +``` +packages/init/ +├── src/ +│ ├── mod.ts # CLI entry point (package default export) +│ ├── init.ts # Core initialization logic +│ ├── types.ts # Type definitions +│ ├── utils.ts # File operations, version resolution +│ └── sync.ts # Template synchronization tool +├── assets/ +│ ├── base/ # Common files (edit here!) +│ │ ├── vite/ # Shared between vite templates +│ │ └── builder/ # Shared between builder templates +│ ├── template/ # Complete project templates +│ │ ├── vite/ +│ │ ├── vite-tailwind/ +│ │ ├── builder/ +│ │ └── builder-tailwind/ +│ └── variants/ # Additive overlays +│ ├── docker/ +│ ├── vscode/ +│ └── vscode-tailwind/ +├── tests/ # Test suite +├── deno.json # Package configuration +├── README.md # User documentation +└── DESIGN.md # This file +``` + +## Template Maintenance + +Common files are stored in `assets/base/` and synced to template variants. + +### Editing Common Files + +1. Edit files in `assets/base/vite/` or `assets/base/builder/` +2. Run `deno task sync` to propagate changes +3. Template-specific files are preserved: + - `deno.json` - Different dependencies per variant + - `vite.config.ts` - Tailwind plugin configuration + - `assets/styles.css` / `static/styles.css` - Tailwind imports + +### Sync Commands + +```bash +deno task sync # Apply changes +deno task sync --dry-run # Preview without applying +``` + +The sync script (`src/sync.ts`) copies: + +- `assets/base/vite/` → `vite/` and `vite-tailwind/` +- `assets/base/builder/` → `builder/` and `builder-tailwind/` + +## File Processing + +### Naming Convention + +- `__filename` → `.filename` (e.g., `__gitignore` → `.gitignore`) + +### Variable Substitution + +Template files use `__VARIABLE__` syntax for text replacement: + +**Project Variables:** + +- `__PROJECT_NAME__` - Project name (from directory basename) + +**Version Variables:** + +- `__FRESH_VERSION__` - Fresh core version +- `__FRESH_TAILWIND_VERSION__` - Fresh Tailwind plugin version +- `__FRESH_VITE_PLUGIN_VERSION__` - Fresh Vite plugin version +- `__PREACT_VERSION__` - Preact version +- `__PREACT_SIGNALS_VERSION__` - Preact Signals version +- `__TAILWINDCSS_VERSION__` - Tailwind CSS version +- `__TAILWINDCSS_POSTCSS_VERSION__` - Tailwind CSS PostCSS version +- `__TAILWINDCSS_VITE_VERSION__` - Tailwind CSS Vite plugin version +- `__POSTCSS_VERSION__` - PostCSS version +- `__VITE_VERSION__` - Vite version +- `__DENO_VERSION__` - Deno version (current runtime) + +Text files are processed for variable substitution. Binary files are copied +as-is. + +**Note:** Boolean flags (tailwind, vscode, docker, builder) are used for +**template/variant selection logic**, not as substitutable variables in template +files. + +## Template Selection + +```typescript +// Base template +if (vite && tailwind) → "vite-tailwind" +else if (vite) → "vite" +else if (tailwind) → "builder-tailwind" +else → "builder" + +// Variants (additive) +if (docker) → add "docker" +if (vscode && tailwind) → add "vscode-tailwind" +else if (vscode) → add "vscode" +``` + +## Version Resolution + +Matches `@fresh/init` behavior: + +- Fresh core: Fetched from network +- Other dependencies: Fixed versions (updated by release script) + +## Development + +```bash +deno task test # Run test suite (55 tests) +deno task check # Format, lint, type check +deno task sync # Sync templates +``` + +## Testing + +- **Unit tests** - Core functionality +- **Integration tests** - Full project generation and builds +- **CLI tests** - Command-line interface +- **Compatibility tests** - Verify output matches v2.0.9 (pre-refactor baseline) +- **Sync tests** - Template synchronization diff --git a/packages/init/README.md b/packages/init/README.md index eec288dd..c7d0b936 100644 --- a/packages/init/README.md +++ b/packages/init/README.md @@ -1,10 +1,62 @@ -# Create a new Fresh project. +# @fresh/init -This is a CLI tool to bootstrap a new Fresh project. To do so, run this command: +Template-based initialization system for Fresh projects. -```sh -deno run -Ar jsr:@fresh/init +## Usage + +### CLI + +```bash +# Interactive mode +deno run -Ar jsr:@fresh/init my-project + +# With options +deno run -Ar jsr:@fresh/init my-app --tailwind --vscode --docker ``` -Go to [https://fresh.deno.dev/](https://fresh.deno.dev/) for more information -about Fresh. +**Options:** + +- `--force` - Overwrite existing files +- `--tailwind` - Include Tailwind CSS +- `--vscode` - Add VS Code configuration +- `--docker` - Add Docker support +- `--builder` - Use builder instead of Vite +- `--help` - Show help message + +### Programmatic + +```typescript +import { initProject, resolveVersions } from "jsr:@fresh/init/src/init"; + +const versions = await resolveVersions(); +await initProject(Deno.cwd(), { + directory: "./my-fresh-app", + tailwind: true, + vscode: true, + docker: false, + builder: false, + force: false, +}, versions); +``` + +## Templates + +**Build Systems:** + +- **Vite** (default) - Modern build system with HMR +- **Builder** - Traditional Deno-based build system + +**Styling:** + +- **Plain CSS** (default) +- **Tailwind CSS** (`--tailwind`) + +**Optional Features:** + +- **VS Code** configuration (`--vscode`) +- **Docker** support (`--docker`) + +## Maintainer Documentation + +See [DESIGN.md](./DESIGN.md) for architecture, maintenance workflows, and +development setup. diff --git a/packages/init/assets/base/builder/README.md b/packages/init/assets/base/builder/README.md new file mode 100644 index 00000000..b2e551fd --- /dev/null +++ b/packages/init/assets/base/builder/README.md @@ -0,0 +1,17 @@ +# Fresh project + +Your new Fresh project is ready to go. You can follow the Fresh "Getting +Started" guide here: https://fresh.deno.dev/docs/getting-started + +### Usage + +Make sure to install Deno: +https://docs.deno.com/runtime/getting_started/installation + +Then start the project in development mode: + +``` +deno task dev +``` + +This will watch the project directory and restart as necessary. diff --git a/packages/init/assets/base/builder/__gitignore b/packages/init/assets/base/builder/__gitignore new file mode 100644 index 00000000..0735100f --- /dev/null +++ b/packages/init/assets/base/builder/__gitignore @@ -0,0 +1,13 @@ +# dotenv environment variable files +.env +.env.development.local +.env.test.local +.env.production.local +.env.local + +# Fresh build directory +_fresh/ +# npm + other dependencies +node_modules/ +vendor/ + diff --git a/packages/init/assets/base/builder/components/Button.tsx b/packages/init/assets/base/builder/components/Button.tsx new file mode 100644 index 00000000..71eaf7f4 --- /dev/null +++ b/packages/init/assets/base/builder/components/Button.tsx @@ -0,0 +1,17 @@ +import type { ComponentChildren } from "preact"; + +export interface ButtonProps { + id?: string; + onClick?: () => void; + children?: ComponentChildren; + disabled?: boolean; +} + +export function Button(props: ButtonProps) { + return ( + +

{props.count}

+ + + ); +} diff --git a/packages/init/assets/base/builder/main.ts b/packages/init/assets/base/builder/main.ts new file mode 100644 index 00000000..350d652b --- /dev/null +++ b/packages/init/assets/base/builder/main.ts @@ -0,0 +1,30 @@ +import { App, staticFiles } from "fresh"; +import { define, type State } from "./utils.ts"; + +export const app = new App(); + +app.use(staticFiles()); + +// Pass a shared value from a middleware +app.use(async (ctx) => { + ctx.state.shared = "hello"; + return await ctx.next(); +}); + +// this is the same as the /api/:name route defined via a file. feel free to delete this! +app.get("/api2/:name", (ctx) => { + const name = ctx.params.name; + return new Response( + `Hello, ${name.charAt(0).toUpperCase() + name.slice(1)}!`, + ); +}); + +// this can also be defined via a file. feel free to delete this! +const exampleLoggerMiddleware = define.middleware((ctx) => { + console.log(`${ctx.req.method} ${ctx.req.url}`); + return ctx.next(); +}); +app.use(exampleLoggerMiddleware); + +// Include file-system based routes here +app.fsRoutes(); diff --git a/packages/init/assets/base/builder/routes/_app.tsx b/packages/init/assets/base/builder/routes/_app.tsx new file mode 100644 index 00000000..5c727303 --- /dev/null +++ b/packages/init/assets/base/builder/routes/_app.tsx @@ -0,0 +1,17 @@ +import { define } from "../utils.ts"; + +export default define.page(function App({ Component }) { + return ( + + + + + __PROJECT_NAME__ + + + + + + + ); +}); diff --git a/packages/init/assets/base/builder/routes/api/[name].tsx b/packages/init/assets/base/builder/routes/api/[name].tsx new file mode 100644 index 00000000..0c972482 --- /dev/null +++ b/packages/init/assets/base/builder/routes/api/[name].tsx @@ -0,0 +1,10 @@ +import { define } from "../../utils.ts"; + +export const handler = define.handlers({ + GET(ctx) { + const name = ctx.params.name; + return new Response( + `Hello, ${name.charAt(0).toUpperCase() + name.slice(1)}!`, + ); + }, +}); diff --git a/packages/init/assets/base/builder/routes/index.tsx b/packages/init/assets/base/builder/routes/index.tsx new file mode 100644 index 00000000..74e9ebcc --- /dev/null +++ b/packages/init/assets/base/builder/routes/index.tsx @@ -0,0 +1,33 @@ +import { useSignal } from "@preact/signals"; +import { Head } from "fresh/runtime"; +import { define } from "../utils.ts"; +import Counter from "../islands/Counter.tsx"; + +export default define.page(function Home(ctx) { + const count = useSignal(3); + + console.log("Shared value " + ctx.state.shared); + + return ( +
+ + Fresh counter + +
+ the Fresh logo: a sliced lemon dripping with juice +

Welcome to Fresh

+

+ Try updating this message in the + ./routes/index.tsx file, and refresh. +

+ +
+
+ ); +}); diff --git a/packages/init/assets/base/builder/static/logo.svg b/packages/init/assets/base/builder/static/logo.svg new file mode 100644 index 00000000..5b99e0b1 --- /dev/null +++ b/packages/init/assets/base/builder/static/logo.svg @@ -0,0 +1,19 @@ + + + + + + diff --git a/packages/init/assets/base/builder/utils.ts b/packages/init/assets/base/builder/utils.ts new file mode 100644 index 00000000..f404216e --- /dev/null +++ b/packages/init/assets/base/builder/utils.ts @@ -0,0 +1,9 @@ +import { createDefine } from "fresh"; + +// This specifies the type of "ctx.state" which is used to share +// data among middlewares, layouts and routes. +export interface State { + shared: string; +} + +export const define = createDefine(); diff --git a/packages/init/assets/base/vite/README.md b/packages/init/assets/base/vite/README.md new file mode 100644 index 00000000..b2e551fd --- /dev/null +++ b/packages/init/assets/base/vite/README.md @@ -0,0 +1,17 @@ +# Fresh project + +Your new Fresh project is ready to go. You can follow the Fresh "Getting +Started" guide here: https://fresh.deno.dev/docs/getting-started + +### Usage + +Make sure to install Deno: +https://docs.deno.com/runtime/getting_started/installation + +Then start the project in development mode: + +``` +deno task dev +``` + +This will watch the project directory and restart as necessary. diff --git a/packages/init/assets/base/vite/__gitignore b/packages/init/assets/base/vite/__gitignore new file mode 100644 index 00000000..0735100f --- /dev/null +++ b/packages/init/assets/base/vite/__gitignore @@ -0,0 +1,13 @@ +# dotenv environment variable files +.env +.env.development.local +.env.test.local +.env.production.local +.env.local + +# Fresh build directory +_fresh/ +# npm + other dependencies +node_modules/ +vendor/ + diff --git a/packages/init/assets/base/vite/components/Button.tsx b/packages/init/assets/base/vite/components/Button.tsx new file mode 100644 index 00000000..71eaf7f4 --- /dev/null +++ b/packages/init/assets/base/vite/components/Button.tsx @@ -0,0 +1,17 @@ +import type { ComponentChildren } from "preact"; + +export interface ButtonProps { + id?: string; + onClick?: () => void; + children?: ComponentChildren; + disabled?: boolean; +} + +export function Button(props: ButtonProps) { + return ( + +

{props.count}

+ + + ); +} diff --git a/packages/init/assets/base/vite/main.ts b/packages/init/assets/base/vite/main.ts new file mode 100644 index 00000000..350d652b --- /dev/null +++ b/packages/init/assets/base/vite/main.ts @@ -0,0 +1,30 @@ +import { App, staticFiles } from "fresh"; +import { define, type State } from "./utils.ts"; + +export const app = new App(); + +app.use(staticFiles()); + +// Pass a shared value from a middleware +app.use(async (ctx) => { + ctx.state.shared = "hello"; + return await ctx.next(); +}); + +// this is the same as the /api/:name route defined via a file. feel free to delete this! +app.get("/api2/:name", (ctx) => { + const name = ctx.params.name; + return new Response( + `Hello, ${name.charAt(0).toUpperCase() + name.slice(1)}!`, + ); +}); + +// this can also be defined via a file. feel free to delete this! +const exampleLoggerMiddleware = define.middleware((ctx) => { + console.log(`${ctx.req.method} ${ctx.req.url}`); + return ctx.next(); +}); +app.use(exampleLoggerMiddleware); + +// Include file-system based routes here +app.fsRoutes(); diff --git a/packages/init/assets/base/vite/routes/_app.tsx b/packages/init/assets/base/vite/routes/_app.tsx new file mode 100644 index 00000000..e527fa36 --- /dev/null +++ b/packages/init/assets/base/vite/routes/_app.tsx @@ -0,0 +1,16 @@ +import { define } from "../utils.ts"; + +export default define.page(function App({ Component }) { + return ( + + + + + __PROJECT_NAME__ + + + + + + ); +}); diff --git a/packages/init/assets/base/vite/routes/api/[name].tsx b/packages/init/assets/base/vite/routes/api/[name].tsx new file mode 100644 index 00000000..0c972482 --- /dev/null +++ b/packages/init/assets/base/vite/routes/api/[name].tsx @@ -0,0 +1,10 @@ +import { define } from "../../utils.ts"; + +export const handler = define.handlers({ + GET(ctx) { + const name = ctx.params.name; + return new Response( + `Hello, ${name.charAt(0).toUpperCase() + name.slice(1)}!`, + ); + }, +}); diff --git a/packages/init/assets/base/vite/routes/index.tsx b/packages/init/assets/base/vite/routes/index.tsx new file mode 100644 index 00000000..74e9ebcc --- /dev/null +++ b/packages/init/assets/base/vite/routes/index.tsx @@ -0,0 +1,33 @@ +import { useSignal } from "@preact/signals"; +import { Head } from "fresh/runtime"; +import { define } from "../utils.ts"; +import Counter from "../islands/Counter.tsx"; + +export default define.page(function Home(ctx) { + const count = useSignal(3); + + console.log("Shared value " + ctx.state.shared); + + return ( +
+ + Fresh counter + +
+ the Fresh logo: a sliced lemon dripping with juice +

Welcome to Fresh

+

+ Try updating this message in the + ./routes/index.tsx file, and refresh. +

+ +
+
+ ); +}); diff --git a/packages/init/assets/base/vite/static/logo.svg b/packages/init/assets/base/vite/static/logo.svg new file mode 100644 index 00000000..5b99e0b1 --- /dev/null +++ b/packages/init/assets/base/vite/static/logo.svg @@ -0,0 +1,19 @@ + + + + + + diff --git a/packages/init/assets/base/vite/utils.ts b/packages/init/assets/base/vite/utils.ts new file mode 100644 index 00000000..f404216e --- /dev/null +++ b/packages/init/assets/base/vite/utils.ts @@ -0,0 +1,9 @@ +import { createDefine } from "fresh"; + +// This specifies the type of "ctx.state" which is used to share +// data among middlewares, layouts and routes. +export interface State { + shared: string; +} + +export const define = createDefine(); diff --git a/packages/init/assets/template/builder-tailwind/README.md b/packages/init/assets/template/builder-tailwind/README.md new file mode 100644 index 00000000..b2e551fd --- /dev/null +++ b/packages/init/assets/template/builder-tailwind/README.md @@ -0,0 +1,17 @@ +# Fresh project + +Your new Fresh project is ready to go. You can follow the Fresh "Getting +Started" guide here: https://fresh.deno.dev/docs/getting-started + +### Usage + +Make sure to install Deno: +https://docs.deno.com/runtime/getting_started/installation + +Then start the project in development mode: + +``` +deno task dev +``` + +This will watch the project directory and restart as necessary. diff --git a/packages/init/assets/template/builder-tailwind/__gitignore b/packages/init/assets/template/builder-tailwind/__gitignore new file mode 100644 index 00000000..0735100f --- /dev/null +++ b/packages/init/assets/template/builder-tailwind/__gitignore @@ -0,0 +1,13 @@ +# dotenv environment variable files +.env +.env.development.local +.env.test.local +.env.production.local +.env.local + +# Fresh build directory +_fresh/ +# npm + other dependencies +node_modules/ +vendor/ + diff --git a/packages/init/assets/template/builder-tailwind/components/Button.tsx b/packages/init/assets/template/builder-tailwind/components/Button.tsx new file mode 100644 index 00000000..71eaf7f4 --- /dev/null +++ b/packages/init/assets/template/builder-tailwind/components/Button.tsx @@ -0,0 +1,17 @@ +import type { ComponentChildren } from "preact"; + +export interface ButtonProps { + id?: string; + onClick?: () => void; + children?: ComponentChildren; + disabled?: boolean; +} + +export function Button(props: ButtonProps) { + return ( + +

{props.count}

+ + + ); +} diff --git a/packages/init/assets/template/builder-tailwind/main.ts b/packages/init/assets/template/builder-tailwind/main.ts new file mode 100644 index 00000000..350d652b --- /dev/null +++ b/packages/init/assets/template/builder-tailwind/main.ts @@ -0,0 +1,30 @@ +import { App, staticFiles } from "fresh"; +import { define, type State } from "./utils.ts"; + +export const app = new App(); + +app.use(staticFiles()); + +// Pass a shared value from a middleware +app.use(async (ctx) => { + ctx.state.shared = "hello"; + return await ctx.next(); +}); + +// this is the same as the /api/:name route defined via a file. feel free to delete this! +app.get("/api2/:name", (ctx) => { + const name = ctx.params.name; + return new Response( + `Hello, ${name.charAt(0).toUpperCase() + name.slice(1)}!`, + ); +}); + +// this can also be defined via a file. feel free to delete this! +const exampleLoggerMiddleware = define.middleware((ctx) => { + console.log(`${ctx.req.method} ${ctx.req.url}`); + return ctx.next(); +}); +app.use(exampleLoggerMiddleware); + +// Include file-system based routes here +app.fsRoutes(); diff --git a/packages/init/assets/template/builder-tailwind/routes/_app.tsx b/packages/init/assets/template/builder-tailwind/routes/_app.tsx new file mode 100644 index 00000000..5c727303 --- /dev/null +++ b/packages/init/assets/template/builder-tailwind/routes/_app.tsx @@ -0,0 +1,17 @@ +import { define } from "../utils.ts"; + +export default define.page(function App({ Component }) { + return ( + + + + + __PROJECT_NAME__ + + + + + + + ); +}); diff --git a/packages/init/assets/template/builder-tailwind/routes/api/[name].tsx b/packages/init/assets/template/builder-tailwind/routes/api/[name].tsx new file mode 100644 index 00000000..0c972482 --- /dev/null +++ b/packages/init/assets/template/builder-tailwind/routes/api/[name].tsx @@ -0,0 +1,10 @@ +import { define } from "../../utils.ts"; + +export const handler = define.handlers({ + GET(ctx) { + const name = ctx.params.name; + return new Response( + `Hello, ${name.charAt(0).toUpperCase() + name.slice(1)}!`, + ); + }, +}); diff --git a/packages/init/assets/template/builder-tailwind/routes/index.tsx b/packages/init/assets/template/builder-tailwind/routes/index.tsx new file mode 100644 index 00000000..74e9ebcc --- /dev/null +++ b/packages/init/assets/template/builder-tailwind/routes/index.tsx @@ -0,0 +1,33 @@ +import { useSignal } from "@preact/signals"; +import { Head } from "fresh/runtime"; +import { define } from "../utils.ts"; +import Counter from "../islands/Counter.tsx"; + +export default define.page(function Home(ctx) { + const count = useSignal(3); + + console.log("Shared value " + ctx.state.shared); + + return ( +
+ + Fresh counter + +
+ the Fresh logo: a sliced lemon dripping with juice +

Welcome to Fresh

+

+ Try updating this message in the + ./routes/index.tsx file, and refresh. +

+ +
+
+ ); +}); diff --git a/packages/init/assets/template/builder-tailwind/static/logo.svg b/packages/init/assets/template/builder-tailwind/static/logo.svg new file mode 100644 index 00000000..5b99e0b1 --- /dev/null +++ b/packages/init/assets/template/builder-tailwind/static/logo.svg @@ -0,0 +1,19 @@ + + + + + + diff --git a/packages/init/assets/template/builder-tailwind/static/styles.css b/packages/init/assets/template/builder-tailwind/static/styles.css new file mode 100644 index 00000000..5d8109d8 --- /dev/null +++ b/packages/init/assets/template/builder-tailwind/static/styles.css @@ -0,0 +1,10 @@ +@import "tailwindcss"; +.fresh-gradient { + background-color: rgb(134, 239, 172); + background-image: linear-gradient( + to right bottom, + rgb(219, 234, 254), + rgb(187, 247, 208), + rgb(254, 249, 195) + ); +} diff --git a/packages/init/assets/template/builder-tailwind/utils.ts b/packages/init/assets/template/builder-tailwind/utils.ts new file mode 100644 index 00000000..f404216e --- /dev/null +++ b/packages/init/assets/template/builder-tailwind/utils.ts @@ -0,0 +1,9 @@ +import { createDefine } from "fresh"; + +// This specifies the type of "ctx.state" which is used to share +// data among middlewares, layouts and routes. +export interface State { + shared: string; +} + +export const define = createDefine(); diff --git a/packages/init/assets/template/builder/README.md b/packages/init/assets/template/builder/README.md new file mode 100644 index 00000000..b2e551fd --- /dev/null +++ b/packages/init/assets/template/builder/README.md @@ -0,0 +1,17 @@ +# Fresh project + +Your new Fresh project is ready to go. You can follow the Fresh "Getting +Started" guide here: https://fresh.deno.dev/docs/getting-started + +### Usage + +Make sure to install Deno: +https://docs.deno.com/runtime/getting_started/installation + +Then start the project in development mode: + +``` +deno task dev +``` + +This will watch the project directory and restart as necessary. diff --git a/packages/init/assets/template/builder/__gitignore b/packages/init/assets/template/builder/__gitignore new file mode 100644 index 00000000..0735100f --- /dev/null +++ b/packages/init/assets/template/builder/__gitignore @@ -0,0 +1,13 @@ +# dotenv environment variable files +.env +.env.development.local +.env.test.local +.env.production.local +.env.local + +# Fresh build directory +_fresh/ +# npm + other dependencies +node_modules/ +vendor/ + diff --git a/packages/init/assets/template/builder/components/Button.tsx b/packages/init/assets/template/builder/components/Button.tsx new file mode 100644 index 00000000..71eaf7f4 --- /dev/null +++ b/packages/init/assets/template/builder/components/Button.tsx @@ -0,0 +1,17 @@ +import type { ComponentChildren } from "preact"; + +export interface ButtonProps { + id?: string; + onClick?: () => void; + children?: ComponentChildren; + disabled?: boolean; +} + +export function Button(props: ButtonProps) { + return ( + +

{props.count}

+ + + ); +} diff --git a/packages/init/assets/template/builder/main.ts b/packages/init/assets/template/builder/main.ts new file mode 100644 index 00000000..350d652b --- /dev/null +++ b/packages/init/assets/template/builder/main.ts @@ -0,0 +1,30 @@ +import { App, staticFiles } from "fresh"; +import { define, type State } from "./utils.ts"; + +export const app = new App(); + +app.use(staticFiles()); + +// Pass a shared value from a middleware +app.use(async (ctx) => { + ctx.state.shared = "hello"; + return await ctx.next(); +}); + +// this is the same as the /api/:name route defined via a file. feel free to delete this! +app.get("/api2/:name", (ctx) => { + const name = ctx.params.name; + return new Response( + `Hello, ${name.charAt(0).toUpperCase() + name.slice(1)}!`, + ); +}); + +// this can also be defined via a file. feel free to delete this! +const exampleLoggerMiddleware = define.middleware((ctx) => { + console.log(`${ctx.req.method} ${ctx.req.url}`); + return ctx.next(); +}); +app.use(exampleLoggerMiddleware); + +// Include file-system based routes here +app.fsRoutes(); diff --git a/packages/init/assets/template/builder/routes/_app.tsx b/packages/init/assets/template/builder/routes/_app.tsx new file mode 100644 index 00000000..5c727303 --- /dev/null +++ b/packages/init/assets/template/builder/routes/_app.tsx @@ -0,0 +1,17 @@ +import { define } from "../utils.ts"; + +export default define.page(function App({ Component }) { + return ( + + + + + __PROJECT_NAME__ + + + + + + + ); +}); diff --git a/packages/init/assets/template/builder/routes/api/[name].tsx b/packages/init/assets/template/builder/routes/api/[name].tsx new file mode 100644 index 00000000..0c972482 --- /dev/null +++ b/packages/init/assets/template/builder/routes/api/[name].tsx @@ -0,0 +1,10 @@ +import { define } from "../../utils.ts"; + +export const handler = define.handlers({ + GET(ctx) { + const name = ctx.params.name; + return new Response( + `Hello, ${name.charAt(0).toUpperCase() + name.slice(1)}!`, + ); + }, +}); diff --git a/packages/init/assets/template/builder/routes/index.tsx b/packages/init/assets/template/builder/routes/index.tsx new file mode 100644 index 00000000..74e9ebcc --- /dev/null +++ b/packages/init/assets/template/builder/routes/index.tsx @@ -0,0 +1,33 @@ +import { useSignal } from "@preact/signals"; +import { Head } from "fresh/runtime"; +import { define } from "../utils.ts"; +import Counter from "../islands/Counter.tsx"; + +export default define.page(function Home(ctx) { + const count = useSignal(3); + + console.log("Shared value " + ctx.state.shared); + + return ( +
+ + Fresh counter + +
+ the Fresh logo: a sliced lemon dripping with juice +

Welcome to Fresh

+

+ Try updating this message in the + ./routes/index.tsx file, and refresh. +

+ +
+
+ ); +}); diff --git a/packages/init/assets/template/builder/static/logo.svg b/packages/init/assets/template/builder/static/logo.svg new file mode 100644 index 00000000..5b99e0b1 --- /dev/null +++ b/packages/init/assets/template/builder/static/logo.svg @@ -0,0 +1,19 @@ + + + + + + diff --git a/packages/init/assets/template/builder/static/styles.css b/packages/init/assets/template/builder/static/styles.css new file mode 100644 index 00000000..21c911c4 --- /dev/null +++ b/packages/init/assets/template/builder/static/styles.css @@ -0,0 +1,144 @@ +*, +*::before, +*::after { + box-sizing: border-box; +} +* { + margin: 0; +} +button { + color: inherit; +} +button, [role="button"] { + cursor: pointer; +} +code { + font-family: + ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", + "Courier New", monospace; + font-size: 1em; +} +img, +svg { + display: block; +} +img, +video { + max-width: 100%; + height: auto; +} + +html { + line-height: 1.5; + -webkit-text-size-adjust: 100%; + font-family: + ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", + Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, + "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", + "Noto Color Emoji"; +} +.transition-colors { + transition-property: background-color, border-color, color, fill, stroke; + transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); + transition-duration: 150ms; +} +.my-6 { + margin-bottom: 1.5rem; + margin-top: 1.5rem; +} +.text-4xl { + font-size: 2.25rem; + line-height: 2.5rem; +} +.mx-2 { + margin-left: 0.5rem; + margin-right: 0.5rem; +} +.my-4 { + margin-bottom: 1rem; + margin-top: 1rem; +} +.mx-auto { + margin-left: auto; + margin-right: auto; +} +.px-4 { + padding-left: 1rem; + padding-right: 1rem; +} +.py-8 { + padding-bottom: 2rem; + padding-top: 2rem; +} +.bg-\[\#86efac\] { + background-color: #86efac; +} +.text-3xl { + font-size: 1.875rem; + line-height: 2.25rem; +} +.py-6 { + padding-bottom: 1.5rem; + padding-top: 1.5rem; +} +.px-2 { + padding-left: 0.5rem; + padding-right: 0.5rem; +} +.py-1 { + padding-bottom: 0.25rem; + padding-top: 0.25rem; +} +.border-gray-500 { + border-color: #6b7280; +} +.bg-white { + background-color: #fff; +} +.flex { + display: flex; +} +.gap-8 { + grid-gap: 2rem; + gap: 2rem; +} +.font-bold { + font-weight: 700; +} +.max-w-screen-md { + max-width: 768px; +} +.flex-col { + flex-direction: column; +} +.items-center { + align-items: center; +} +.justify-center { + justify-content: center; +} +.border-2 { + border-width: 2px; +} +.rounded-sm { + border-radius: 0.25rem; +} +.hover\:bg-gray-200:hover { + background-color: #e5e7eb; +} +.tabular-nums { + font-variant-numeric: tabular-nums; +} +.min-h-screen { + min-height: 100vh; +} + +.fresh-gradient { + background-color: rgb(134, 239, 172); + background-image: linear-gradient( + to right bottom, + rgb(219, 234, 254), + rgb(187, 247, 208), + rgb(254, 249, 195) + ); +} diff --git a/packages/init/assets/template/builder/utils.ts b/packages/init/assets/template/builder/utils.ts new file mode 100644 index 00000000..f404216e --- /dev/null +++ b/packages/init/assets/template/builder/utils.ts @@ -0,0 +1,9 @@ +import { createDefine } from "fresh"; + +// This specifies the type of "ctx.state" which is used to share +// data among middlewares, layouts and routes. +export interface State { + shared: string; +} + +export const define = createDefine(); diff --git a/packages/init/assets/template/vite-tailwind/README.md b/packages/init/assets/template/vite-tailwind/README.md new file mode 100644 index 00000000..b2e551fd --- /dev/null +++ b/packages/init/assets/template/vite-tailwind/README.md @@ -0,0 +1,17 @@ +# Fresh project + +Your new Fresh project is ready to go. You can follow the Fresh "Getting +Started" guide here: https://fresh.deno.dev/docs/getting-started + +### Usage + +Make sure to install Deno: +https://docs.deno.com/runtime/getting_started/installation + +Then start the project in development mode: + +``` +deno task dev +``` + +This will watch the project directory and restart as necessary. diff --git a/packages/init/assets/template/vite-tailwind/__gitignore b/packages/init/assets/template/vite-tailwind/__gitignore new file mode 100644 index 00000000..0735100f --- /dev/null +++ b/packages/init/assets/template/vite-tailwind/__gitignore @@ -0,0 +1,13 @@ +# dotenv environment variable files +.env +.env.development.local +.env.test.local +.env.production.local +.env.local + +# Fresh build directory +_fresh/ +# npm + other dependencies +node_modules/ +vendor/ + diff --git a/packages/init/assets/template/vite-tailwind/assets/styles.css b/packages/init/assets/template/vite-tailwind/assets/styles.css new file mode 100644 index 00000000..5d8109d8 --- /dev/null +++ b/packages/init/assets/template/vite-tailwind/assets/styles.css @@ -0,0 +1,10 @@ +@import "tailwindcss"; +.fresh-gradient { + background-color: rgb(134, 239, 172); + background-image: linear-gradient( + to right bottom, + rgb(219, 234, 254), + rgb(187, 247, 208), + rgb(254, 249, 195) + ); +} diff --git a/packages/init/assets/template/vite-tailwind/client.ts b/packages/init/assets/template/vite-tailwind/client.ts new file mode 100644 index 00000000..016cb078 --- /dev/null +++ b/packages/init/assets/template/vite-tailwind/client.ts @@ -0,0 +1,2 @@ +// Import CSS files here for hot module reloading to work. +import "./assets/styles.css"; diff --git a/packages/init/assets/template/vite-tailwind/components/Button.tsx b/packages/init/assets/template/vite-tailwind/components/Button.tsx new file mode 100644 index 00000000..71eaf7f4 --- /dev/null +++ b/packages/init/assets/template/vite-tailwind/components/Button.tsx @@ -0,0 +1,17 @@ +import type { ComponentChildren } from "preact"; + +export interface ButtonProps { + id?: string; + onClick?: () => void; + children?: ComponentChildren; + disabled?: boolean; +} + +export function Button(props: ButtonProps) { + return ( + +

{props.count}

+ + + ); +} diff --git a/packages/init/assets/template/vite-tailwind/main.ts b/packages/init/assets/template/vite-tailwind/main.ts new file mode 100644 index 00000000..350d652b --- /dev/null +++ b/packages/init/assets/template/vite-tailwind/main.ts @@ -0,0 +1,30 @@ +import { App, staticFiles } from "fresh"; +import { define, type State } from "./utils.ts"; + +export const app = new App(); + +app.use(staticFiles()); + +// Pass a shared value from a middleware +app.use(async (ctx) => { + ctx.state.shared = "hello"; + return await ctx.next(); +}); + +// this is the same as the /api/:name route defined via a file. feel free to delete this! +app.get("/api2/:name", (ctx) => { + const name = ctx.params.name; + return new Response( + `Hello, ${name.charAt(0).toUpperCase() + name.slice(1)}!`, + ); +}); + +// this can also be defined via a file. feel free to delete this! +const exampleLoggerMiddleware = define.middleware((ctx) => { + console.log(`${ctx.req.method} ${ctx.req.url}`); + return ctx.next(); +}); +app.use(exampleLoggerMiddleware); + +// Include file-system based routes here +app.fsRoutes(); diff --git a/packages/init/assets/template/vite-tailwind/routes/_app.tsx b/packages/init/assets/template/vite-tailwind/routes/_app.tsx new file mode 100644 index 00000000..e527fa36 --- /dev/null +++ b/packages/init/assets/template/vite-tailwind/routes/_app.tsx @@ -0,0 +1,16 @@ +import { define } from "../utils.ts"; + +export default define.page(function App({ Component }) { + return ( + + + + + __PROJECT_NAME__ + + + + + + ); +}); diff --git a/packages/init/assets/template/vite-tailwind/routes/api/[name].tsx b/packages/init/assets/template/vite-tailwind/routes/api/[name].tsx new file mode 100644 index 00000000..0c972482 --- /dev/null +++ b/packages/init/assets/template/vite-tailwind/routes/api/[name].tsx @@ -0,0 +1,10 @@ +import { define } from "../../utils.ts"; + +export const handler = define.handlers({ + GET(ctx) { + const name = ctx.params.name; + return new Response( + `Hello, ${name.charAt(0).toUpperCase() + name.slice(1)}!`, + ); + }, +}); diff --git a/packages/init/assets/template/vite-tailwind/routes/index.tsx b/packages/init/assets/template/vite-tailwind/routes/index.tsx new file mode 100644 index 00000000..74e9ebcc --- /dev/null +++ b/packages/init/assets/template/vite-tailwind/routes/index.tsx @@ -0,0 +1,33 @@ +import { useSignal } from "@preact/signals"; +import { Head } from "fresh/runtime"; +import { define } from "../utils.ts"; +import Counter from "../islands/Counter.tsx"; + +export default define.page(function Home(ctx) { + const count = useSignal(3); + + console.log("Shared value " + ctx.state.shared); + + return ( +
+ + Fresh counter + +
+ the Fresh logo: a sliced lemon dripping with juice +

Welcome to Fresh

+

+ Try updating this message in the + ./routes/index.tsx file, and refresh. +

+ +
+
+ ); +}); diff --git a/packages/init/assets/template/vite-tailwind/static/logo.svg b/packages/init/assets/template/vite-tailwind/static/logo.svg new file mode 100644 index 00000000..5b99e0b1 --- /dev/null +++ b/packages/init/assets/template/vite-tailwind/static/logo.svg @@ -0,0 +1,19 @@ + + + + + + diff --git a/packages/init/assets/template/vite-tailwind/utils.ts b/packages/init/assets/template/vite-tailwind/utils.ts new file mode 100644 index 00000000..f404216e --- /dev/null +++ b/packages/init/assets/template/vite-tailwind/utils.ts @@ -0,0 +1,9 @@ +import { createDefine } from "fresh"; + +// This specifies the type of "ctx.state" which is used to share +// data among middlewares, layouts and routes. +export interface State { + shared: string; +} + +export const define = createDefine(); diff --git a/packages/init/assets/template/vite-tailwind/vite.config.ts b/packages/init/assets/template/vite-tailwind/vite.config.ts new file mode 100644 index 00000000..67a37d03 --- /dev/null +++ b/packages/init/assets/template/vite-tailwind/vite.config.ts @@ -0,0 +1,7 @@ +import { defineConfig } from "vite"; +import { fresh } from "@fresh/plugin-vite"; +import tailwindcss from "@tailwindcss/vite"; + +export default defineConfig({ + plugins: [fresh(), tailwindcss()], +}); diff --git a/packages/init/assets/template/vite/README.md b/packages/init/assets/template/vite/README.md new file mode 100644 index 00000000..b2e551fd --- /dev/null +++ b/packages/init/assets/template/vite/README.md @@ -0,0 +1,17 @@ +# Fresh project + +Your new Fresh project is ready to go. You can follow the Fresh "Getting +Started" guide here: https://fresh.deno.dev/docs/getting-started + +### Usage + +Make sure to install Deno: +https://docs.deno.com/runtime/getting_started/installation + +Then start the project in development mode: + +``` +deno task dev +``` + +This will watch the project directory and restart as necessary. diff --git a/packages/init/assets/template/vite/__gitignore b/packages/init/assets/template/vite/__gitignore new file mode 100644 index 00000000..0735100f --- /dev/null +++ b/packages/init/assets/template/vite/__gitignore @@ -0,0 +1,13 @@ +# dotenv environment variable files +.env +.env.development.local +.env.test.local +.env.production.local +.env.local + +# Fresh build directory +_fresh/ +# npm + other dependencies +node_modules/ +vendor/ + diff --git a/packages/init/assets/template/vite/assets/styles.css b/packages/init/assets/template/vite/assets/styles.css new file mode 100644 index 00000000..21c911c4 --- /dev/null +++ b/packages/init/assets/template/vite/assets/styles.css @@ -0,0 +1,144 @@ +*, +*::before, +*::after { + box-sizing: border-box; +} +* { + margin: 0; +} +button { + color: inherit; +} +button, [role="button"] { + cursor: pointer; +} +code { + font-family: + ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", + "Courier New", monospace; + font-size: 1em; +} +img, +svg { + display: block; +} +img, +video { + max-width: 100%; + height: auto; +} + +html { + line-height: 1.5; + -webkit-text-size-adjust: 100%; + font-family: + ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", + Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, + "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", + "Noto Color Emoji"; +} +.transition-colors { + transition-property: background-color, border-color, color, fill, stroke; + transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); + transition-duration: 150ms; +} +.my-6 { + margin-bottom: 1.5rem; + margin-top: 1.5rem; +} +.text-4xl { + font-size: 2.25rem; + line-height: 2.5rem; +} +.mx-2 { + margin-left: 0.5rem; + margin-right: 0.5rem; +} +.my-4 { + margin-bottom: 1rem; + margin-top: 1rem; +} +.mx-auto { + margin-left: auto; + margin-right: auto; +} +.px-4 { + padding-left: 1rem; + padding-right: 1rem; +} +.py-8 { + padding-bottom: 2rem; + padding-top: 2rem; +} +.bg-\[\#86efac\] { + background-color: #86efac; +} +.text-3xl { + font-size: 1.875rem; + line-height: 2.25rem; +} +.py-6 { + padding-bottom: 1.5rem; + padding-top: 1.5rem; +} +.px-2 { + padding-left: 0.5rem; + padding-right: 0.5rem; +} +.py-1 { + padding-bottom: 0.25rem; + padding-top: 0.25rem; +} +.border-gray-500 { + border-color: #6b7280; +} +.bg-white { + background-color: #fff; +} +.flex { + display: flex; +} +.gap-8 { + grid-gap: 2rem; + gap: 2rem; +} +.font-bold { + font-weight: 700; +} +.max-w-screen-md { + max-width: 768px; +} +.flex-col { + flex-direction: column; +} +.items-center { + align-items: center; +} +.justify-center { + justify-content: center; +} +.border-2 { + border-width: 2px; +} +.rounded-sm { + border-radius: 0.25rem; +} +.hover\:bg-gray-200:hover { + background-color: #e5e7eb; +} +.tabular-nums { + font-variant-numeric: tabular-nums; +} +.min-h-screen { + min-height: 100vh; +} + +.fresh-gradient { + background-color: rgb(134, 239, 172); + background-image: linear-gradient( + to right bottom, + rgb(219, 234, 254), + rgb(187, 247, 208), + rgb(254, 249, 195) + ); +} diff --git a/packages/init/assets/template/vite/client.ts b/packages/init/assets/template/vite/client.ts new file mode 100644 index 00000000..016cb078 --- /dev/null +++ b/packages/init/assets/template/vite/client.ts @@ -0,0 +1,2 @@ +// Import CSS files here for hot module reloading to work. +import "./assets/styles.css"; diff --git a/packages/init/assets/template/vite/components/Button.tsx b/packages/init/assets/template/vite/components/Button.tsx new file mode 100644 index 00000000..71eaf7f4 --- /dev/null +++ b/packages/init/assets/template/vite/components/Button.tsx @@ -0,0 +1,17 @@ +import type { ComponentChildren } from "preact"; + +export interface ButtonProps { + id?: string; + onClick?: () => void; + children?: ComponentChildren; + disabled?: boolean; +} + +export function Button(props: ButtonProps) { + return ( + +

{props.count}

+ + + ); +} diff --git a/packages/init/assets/template/vite/main.ts b/packages/init/assets/template/vite/main.ts new file mode 100644 index 00000000..350d652b --- /dev/null +++ b/packages/init/assets/template/vite/main.ts @@ -0,0 +1,30 @@ +import { App, staticFiles } from "fresh"; +import { define, type State } from "./utils.ts"; + +export const app = new App(); + +app.use(staticFiles()); + +// Pass a shared value from a middleware +app.use(async (ctx) => { + ctx.state.shared = "hello"; + return await ctx.next(); +}); + +// this is the same as the /api/:name route defined via a file. feel free to delete this! +app.get("/api2/:name", (ctx) => { + const name = ctx.params.name; + return new Response( + `Hello, ${name.charAt(0).toUpperCase() + name.slice(1)}!`, + ); +}); + +// this can also be defined via a file. feel free to delete this! +const exampleLoggerMiddleware = define.middleware((ctx) => { + console.log(`${ctx.req.method} ${ctx.req.url}`); + return ctx.next(); +}); +app.use(exampleLoggerMiddleware); + +// Include file-system based routes here +app.fsRoutes(); diff --git a/packages/init/assets/template/vite/routes/_app.tsx b/packages/init/assets/template/vite/routes/_app.tsx new file mode 100644 index 00000000..e527fa36 --- /dev/null +++ b/packages/init/assets/template/vite/routes/_app.tsx @@ -0,0 +1,16 @@ +import { define } from "../utils.ts"; + +export default define.page(function App({ Component }) { + return ( + + + + + __PROJECT_NAME__ + + + + + + ); +}); diff --git a/packages/init/assets/template/vite/routes/api/[name].tsx b/packages/init/assets/template/vite/routes/api/[name].tsx new file mode 100644 index 00000000..0c972482 --- /dev/null +++ b/packages/init/assets/template/vite/routes/api/[name].tsx @@ -0,0 +1,10 @@ +import { define } from "../../utils.ts"; + +export const handler = define.handlers({ + GET(ctx) { + const name = ctx.params.name; + return new Response( + `Hello, ${name.charAt(0).toUpperCase() + name.slice(1)}!`, + ); + }, +}); diff --git a/packages/init/assets/template/vite/routes/index.tsx b/packages/init/assets/template/vite/routes/index.tsx new file mode 100644 index 00000000..74e9ebcc --- /dev/null +++ b/packages/init/assets/template/vite/routes/index.tsx @@ -0,0 +1,33 @@ +import { useSignal } from "@preact/signals"; +import { Head } from "fresh/runtime"; +import { define } from "../utils.ts"; +import Counter from "../islands/Counter.tsx"; + +export default define.page(function Home(ctx) { + const count = useSignal(3); + + console.log("Shared value " + ctx.state.shared); + + return ( +
+ + Fresh counter + +
+ the Fresh logo: a sliced lemon dripping with juice +

Welcome to Fresh

+

+ Try updating this message in the + ./routes/index.tsx file, and refresh. +

+ +
+
+ ); +}); diff --git a/packages/init/assets/template/vite/static/logo.svg b/packages/init/assets/template/vite/static/logo.svg new file mode 100644 index 00000000..5b99e0b1 --- /dev/null +++ b/packages/init/assets/template/vite/static/logo.svg @@ -0,0 +1,19 @@ + + + + + + diff --git a/packages/init/assets/template/vite/utils.ts b/packages/init/assets/template/vite/utils.ts new file mode 100644 index 00000000..f404216e --- /dev/null +++ b/packages/init/assets/template/vite/utils.ts @@ -0,0 +1,9 @@ +import { createDefine } from "fresh"; + +// This specifies the type of "ctx.state" which is used to share +// data among middlewares, layouts and routes. +export interface State { + shared: string; +} + +export const define = createDefine(); diff --git a/packages/init/assets/template/vite/vite.config.ts b/packages/init/assets/template/vite/vite.config.ts new file mode 100644 index 00000000..727d49a2 --- /dev/null +++ b/packages/init/assets/template/vite/vite.config.ts @@ -0,0 +1,6 @@ +import { defineConfig } from "vite"; +import { fresh } from "@fresh/plugin-vite"; + +export default defineConfig({ + plugins: [fresh()], +}); diff --git a/packages/init/assets/variants/docker/Dockerfile b/packages/init/assets/variants/docker/Dockerfile new file mode 100644 index 00000000..f034f630 --- /dev/null +++ b/packages/init/assets/variants/docker/Dockerfile @@ -0,0 +1,15 @@ + +FROM denoland/deno:__DENO_VERSION__ + +ARG GIT_REVISION +ENV DENO_DEPLOYMENT_ID=${GIT_REVISION} + +WORKDIR /app + +COPY . . +RUN deno cache _fresh/server.js + +EXPOSE 8000 + +CMD ["serve", "-A", "_fresh/server.js"] + diff --git a/packages/init/assets/variants/vscode-tailwind/__vscode/extensions.json b/packages/init/assets/variants/vscode-tailwind/__vscode/extensions.json new file mode 100644 index 00000000..455f9fcd --- /dev/null +++ b/packages/init/assets/variants/vscode-tailwind/__vscode/extensions.json @@ -0,0 +1,6 @@ +{ + "recommendations": [ + "denoland.vscode-deno", + "bradlc.vscode-tailwindcss" + ] +} diff --git a/packages/init/assets/variants/vscode-tailwind/__vscode/settings.json b/packages/init/assets/variants/vscode-tailwind/__vscode/settings.json new file mode 100644 index 00000000..bedf1ce5 --- /dev/null +++ b/packages/init/assets/variants/vscode-tailwind/__vscode/settings.json @@ -0,0 +1,20 @@ +{ + "deno.enable": true, + "deno.lint": true, + "editor.defaultFormatter": "denoland.vscode-deno", + "[typescriptreact]": { + "editor.defaultFormatter": "denoland.vscode-deno" + }, + "[typescript]": { + "editor.defaultFormatter": "denoland.vscode-deno" + }, + "[javascriptreact]": { + "editor.defaultFormatter": "denoland.vscode-deno" + }, + "[javascript]": { + "editor.defaultFormatter": "denoland.vscode-deno" + }, + "css.customData": [ + ".vscode/tailwind.json" + ] +} diff --git a/packages/init/assets/variants/vscode-tailwind/__vscode/tailwind.json b/packages/init/assets/variants/vscode-tailwind/__vscode/tailwind.json new file mode 100644 index 00000000..96a1f579 --- /dev/null +++ b/packages/init/assets/variants/vscode-tailwind/__vscode/tailwind.json @@ -0,0 +1,55 @@ +{ + "version": 1.1, + "atDirectives": [ + { + "name": "@tailwind", + "description": "Use the `@tailwind` directive to insert Tailwind's `base`, `components`, `utilities` and `screens` styles into your CSS.", + "references": [ + { + "name": "Tailwind Documentation", + "url": "https://tailwindcss.com/docs/functions-and-directives#tailwind" + } + ] + }, + { + "name": "@apply", + "description": "Use the `@apply` directive to inline any existing utility classes into your own custom CSS. This is useful when you find a common utility pattern in your HTML that you’d like to extract to a new component.", + "references": [ + { + "name": "Tailwind Documentation", + "url": "https://tailwindcss.com/docs/functions-and-directives#apply" + } + ] + }, + { + "name": "@responsive", + "description": "You can generate responsive variants of your own classes by wrapping their definitions in the `@responsive` directive:\n```css\n@responsive {\n .alert {\n background-color: #E53E3E;\n }\n}\n```\n", + "references": [ + { + "name": "Tailwind Documentation", + "url": "https://tailwindcss.com/docs/functions-and-directives#responsive" + } + ] + }, + { + "name": "@screen", + "description": "The `@screen` directive allows you to create media queries that reference your breakpoints by **name** instead of duplicating their values in your own CSS:\n```css\n@screen sm {\n /* ... */\n}\n```\n…gets transformed into this:\n```css\n@media (min-width: 640px) {\n /* ... */\n}\n```\n", + "references": [ + { + "name": "Tailwind Documentation", + "url": "https://tailwindcss.com/docs/functions-and-directives#screen" + } + ] + }, + { + "name": "@variants", + "description": "Generate `hover`, `focus`, `active` and other **variants** of your own utilities by wrapping their definitions in the `@variants` directive:\n```css\n@variants hover, focus {\n .btn-brand {\n background-color: #3182CE;\n }\n}\n```\n", + "references": [ + { + "name": "Tailwind Documentation", + "url": "https://tailwindcss.com/docs/functions-and-directives#variants" + } + ] + } + ] +} diff --git a/packages/init/assets/variants/vscode/__vscode/extensions.json b/packages/init/assets/variants/vscode/__vscode/extensions.json new file mode 100644 index 00000000..09cf720d --- /dev/null +++ b/packages/init/assets/variants/vscode/__vscode/extensions.json @@ -0,0 +1,5 @@ +{ + "recommendations": [ + "denoland.vscode-deno" + ] +} diff --git a/packages/init/assets/variants/vscode/__vscode/settings.json b/packages/init/assets/variants/vscode/__vscode/settings.json new file mode 100644 index 00000000..a5f0701f --- /dev/null +++ b/packages/init/assets/variants/vscode/__vscode/settings.json @@ -0,0 +1,17 @@ +{ + "deno.enable": true, + "deno.lint": true, + "editor.defaultFormatter": "denoland.vscode-deno", + "[typescriptreact]": { + "editor.defaultFormatter": "denoland.vscode-deno" + }, + "[typescript]": { + "editor.defaultFormatter": "denoland.vscode-deno" + }, + "[javascriptreact]": { + "editor.defaultFormatter": "denoland.vscode-deno" + }, + "[javascript]": { + "editor.defaultFormatter": "denoland.vscode-deno" + } +} diff --git a/packages/init/deno.json b/packages/init/deno.json index 8fdc90bc..b1aa1828 100644 --- a/packages/init/deno.json +++ b/packages/init/deno.json @@ -1,15 +1,40 @@ { "name": "@fresh/init", - "version": "2.0.9", + "version": "2.1.0", "license": "MIT", "exports": "./src/mod.ts", "exclude": ["**/tmp/*"], + "lint": { + "rules": { + "exclude": ["no-console"] + } + }, + "tasks": { + "check": "deno fmt --check . && deno lint . && deno check **/*.ts", + "test": "deno test -A", + "sync": "deno run -A src/sync.ts" + }, + "imports": { + "@std/cli": "jsr:@std/cli@^1", + "@std/fmt": "jsr:@std/fmt@^1", + "@std/fs": "jsr:@std/fs@^1", + "@std/path": "jsr:@std/path@^1", + "@std/semver": "jsr:@std/semver@^1", + "@std/jsonc": "jsr:@std/jsonc@^1" + }, "publish": { "include": [ "src/**/*.ts", + "assets/**/*", "deno.json", "README.md" ], - "exclude": ["**/*_test.*", "*.todo"] + "exclude": [ + "**/*_test.*", + "*.todo", + "tests/", + "DESIGN.md", + "src/sync.ts" + ] } } diff --git a/packages/init/src/assets/favicon.ico b/packages/init/src/assets/favicon.ico deleted file mode 100644 index 1cfaaa2193b0f210107a559f7421569f57a25388..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 22382 zcmeI4dw7?{mB%N97z7oqA|OH{6p11r>cU#lM7K(nW`t#!NG z`qUAy{#t>9K|!BwH6TqGo5?%XehL;`0&-}m=Ue0llhcL@pl$8VmT z%zK+TmpOCh%*>geb9pY`9euPTFLpO|c5Z}ouDCdHKbPk-c~(}IxG%ZDxr=%@SHd^E zqD103nR9%XEERoVu3rrLu0HUY|1MgG%1x{{_pcwC`)FSxKQUHUyl&n5r0WaUnLDS_ zO1@EJ-yc$bGez?bM z=RUI!pyBE&vtsb~Nlt_6nbdbp$ix3y;iH@E#h>mpJEOtu-!_}g;rgj-#Y+6IA}J3UgmtZ|>|08$6-G-YTPxu6$cc zJ}Rv5v(Pi0IwV{0`8sY^c>!W~<7>=~Tx&xf*kG?*vC-^u@LmTG`5`^sYZLs?&Z47< zau=(tlCR@3bgovaC9=>IxZ5Az`p`7QbsLpKRZnMv?v+|=>T0dXj*Kq-QIJBHP z|7e}QxX#YKtKQ~J++@|)ZM40&Ldy@fo4v5p8sT>e-{eKhtBxXMsXo$eWkM!yf#sjQ z)=I9cwrlAl)9$Ue??K~b`75l;@nQc`xp-2&f?j+x6#e{Gt+~pN%r!Kd8&_?vC(rv! ze}Ht!_gP;j?HADK%gukuxzat@j{@hWVjre<;!Qq~$8`v0%_HeUVb!WU|dRvpYNRdVE0va2Ds}tG@I?%%a~DZ z+u;ANyx$6VJD+L3fikD4Zsd}Z1bxF8E4%;Tv)D7AWShaCDZco3qWL`4-3NQ6JX!L# z2>aLL3+wIesy!aN+3%o*_wjnOxnB(4A;K+4CI|nHcE0+djrP&U*v&M4mmWAyW`kef zz77<7JW(0QR;%5+uC(JAkN>i~F^WBL{Ul@l$&8Ol#`|pOm;?U(d?e8!{3VQSyu0lu zn+#9If`7ZYLIqor{0{UZprMU)G=k$RaT(~I@y`t|x9P9#O8825gX?_8`YRdhr_uf| zB9mJBLOCrXzvZHJ37u#I9gD!%T{vaS0{+PdAp>-5;#}}91;>&2De{-Re^AK%5d4cb z@ZpryH)k^L{|j`;?-5XECh!lwyHNNA9>1=ST4lrWb?V;-zx*PPyCsL7Teh100YBwG z@ZZ)$Lk+t5U&!f4(UXUhWX$L#^pGEF9(hHouNT}5kqHs3>k-OExcn zdoS&PAEWv6LU13Ej`wK01hhhfWN|U`NqoW~rpIwLUuUYkFY^z*&!tbF1QH%q;{WbhR$6z5Te#G@DZsd`&W)Mv z+#sN5nRDG1C7^)3fcrx7{Mo>B0N>}=0XupA5%2d-bp`ttxk5YLb+?tSo7K9W)>L^T z-u$d6POXPhmzxS`9W_X0i7fX&CxM&fK@;>uo2i2g4Xk^fcJq# zz%1Y{pcLo>+zc!Ob^yD98ej&XcL9A-n%na_(w5i5>n`n4|A9I2>&(wtx3EFw!TQ6G z!!{Dnqkw6E_|RU7_MRoHwt)Cu4T$Gt<$uldjP_yLA`|KkWJ_L5yRTp$IM_Gv^9TH7d(H+5m#AY8&`~LM()|s}j?h{Y1vNjajf>d;N)H~_g2=U+EGVpbhkEVThJ<6I} zvb2_cjen{*U@f?#_>I>qyKp<>qxOc|RR*drT;FA^klo=-fGVuB7z1b#gg zyLT)59Q%Hs#O_69@djfd>$LIxkYsdr{{BkkIF`|1nLK$0vXJOkFMe+8yyIFFQDK5g4hWoMl`F$P!Pm% z27A??tUZ)pbe;G)rY>_G2>Cx1`&V}-`)qqs*!)z2S&Tg-)+vbn)VP2=y>1@LT(Ml5 zYi6tiA^#UbZ=?1gqp2Lo^Vm0pM-G6fZEPY;aC7WsZxTv&0`~u%-en6~Q;2#`f zIqZX<+r?9V;!`t8A^&C2xob9j`cwn&=Q75}_kk6w;P=dLz)sG>7gn4?)K_RkFtUxr z9JIu696~uLM(kMerSTwL3i&@7pQl>%`lS8-Wbp`bc_>yx`_yBZ7r%=fqDlIp7_dpy z>*IP3fgBW@H74XM9sAz)A5NcLpja&Jb1TiGKgZ)z;=J#7&l-W^I%E&yNpe_*9PTED zf!MG^;Wy9dpW!~S_kC!W37YRdAKL#n>Ep)`gRmcuv~{Zc6VZc}p$@!5`9Hz4{3M@b zTVJEUd=2{`Tpc)O{+;&kAstAUyq=Kvm*2104$W^AlT$`KRw{nu@6;FOz~3rlFch8d z2A`MHFJ49th@&N`{-?30oCyhJ&;flybL6wdn|!-;$;$vbCaYb1%Qu zPLeUe^O|kmhyI}$P{r~1q)V-*5OWgn-j2HPP|&U!w7&$@`<)g)_-gv)?(d+#>bn2U zI1t2;rs@0H$YLZi{XO+Y)j@VwYpX-b+s!`C#t#nG)YB>e9|W>OS6KfmqzxWdjPgAC zsAQlR-fZ~G8}T>Rpl3b_*CKR5>u$1*2dN9s!&8Cy$~3jefVF-4!IF^`i5O7% zdKbs~bS6Az@{Qv9o@T6#h#}~E#8De()(&QjSism;sPQe+R20VbhjKU%8B|@uS^(#g z0-K&m9B(E($G?#-+=ebx(Fc5zKRJhI8N>j$W;0)g_b%D+FF6IgD>e_i!SyxBU>mV_ z)<6R-K@KIfOPv1px<4Dc@CsvPG%1dLG;IJKt?}8~^B1B2F!7UZ@_PWtPWIzY*+b&l zZ4>RIc-=v*$Ux)2Y-JG7+D3b+c;BB87aR4Pbl&o-)R(0_cpBP+HR5df*Y}c}fc@Cc z;GG0C>3pQl3oJ$tPG@{b*6zKaUuPN>Uwk1pLq611tfN1G4eibNm#j?undB$iSQi;5 z>%pryaA?X@4v%>r+QNTS2GnyH{7*&?8a2n)nI8Fg;w#pRi1(QBO-UW_b#lJ9&UGKZE_p#9e?1KKn6e_G=|st3qG z{pkj5QG?D={fU06q%%G8aietWjKNfVy=77YlEzS7-%md{Joat0T(WD~T-hC;6a&t= zj#Oi#V&l&g|Lv6mSyEqkX8sanu#$7T_H%T4JM?H>=(Hp@LG67HJdfa=)=hNgLv}J5 zpQ)bdEQZD(pLAa6^49mDGM@isBOfn=Fds@^n9qJ$V3*cG+d6F21ngF}^X621N8kN3 z<6|W_d|HCcTUmd90vg+F`%}pzh|iIKfGz+%u!}#GP0;zVKeBe9wJ+JeOY!A()+|bY zdt7T=Q4E4lkAMd{;&6-TqrawNrOodogOGpWP>jzN^oMsfXW$IHtwk4P`{vO;I{T-y zM(x47>X4oJbHqnl4=(-o0d3%AptzbKK7zJsGmq&C7FT>MgHRR&z&9N^?9katonPCE zu4)}+EnJ_h&_oW%@wrf4jlr;qXhdP>3C?5_u?H|624MmKl)3^;8pZu zug>WxZfF`C3u^mmFjRkh$8v4p59;&>nF*JNiCq7eX5P z(I@U_U2z4!Wnqe?(s-%)q|$bTq4|!^s7e;maYJh)W6_nf7&ql(>KyG?xPLX`2dEBy zFC#b)7WV%+;0j9FTVn&qx%oiClr@+E;3V$3T2m5Zafg2!6iTF zIGBzUQb1p*pOI_LtBQe3(2Gg*k!O&{n?NPk8+o=J*a_&jGwOi9!}nZdC%#XN)RWO# ze@F6{P2KX%qO?b@U%1Iz6ft&<#639s)CxM&8D($iiPS z`4rnXm5kiNe6McZI7{TiY+rES)A(%zQnxTa()hgt(qXnS$U7Oofk4We!fz);a7v(y&DRt~7zy75O|tmn&+X8hls8Z!IVlSy`CR4)Ri4 z8s>?LhlK=}8ow<`Dm8wnA;=RIjN=zlbx%G+IRXhdGgifPzmOU3B69BS4)IC8#<@<) bck@HGWY%2idMme??%p8ZW3z(%VE+9-Ofn0d diff --git a/packages/init/src/init.ts b/packages/init/src/init.ts index a0160dde..6d5df6d2 100644 --- a/packages/init/src/init.ts +++ b/packages/init/src/init.ts @@ -1,880 +1,299 @@ -// deno-lint-ignore-file no-console -import * as colors from "@std/fmt/colors"; import * as path from "@std/path"; -import * as semver from "@std/semver"; -import initConfig from "../deno.json" with { type: "json" }; +import * as fs from "@std/fs"; +import type { + InitOptions, + TemplateVariables, + VersionOverrides, +} from "./types.ts"; +import { + getLatestVersion, + getTemplateDir, + getVariantsDir, + processFilename, + substituteVariables, +} from "./utils.ts"; -// Keep these as is, as we replace these version in our release script +/** + * Default version constants for dependencies. + * These are updated automatically by the release script (tools/release.ts). + */ const FRESH_VERSION = "2.1.1"; const FRESH_TAILWIND_VERSION = "1.0.0"; -const FRESH_VITE_PLUGIN = "1.0.0"; const PREACT_VERSION = "10.27.2"; const PREACT_SIGNALS_VERSION = "2.3.1"; + +/** + * Other dependency versions (not automatically updated). + * Update these manually when needed. + */ +const FRESH_VITE_PLUGIN_VERSION = "1.0.0"; const TAILWINDCSS_VERSION = "4.1.10"; const TAILWINDCSS_POSTCSS_VERSION = "4.1.10"; +const TAILWINDCSS_VITE_VERSION = "4.1.12"; const POSTCSS_VERSION = "8.5.6"; +const VITE_VERSION = "7.1.3"; -function css(strs: TemplateStringsArray, ...exprs: string[]): string { - let out = ""; - - for (let i = 0; i < exprs.length; i++) { - out += strs[i]; - out += String(exprs[i]); - } - out += strs.at(-1) ?? ""; - - return out; -} - -export class InitError extends Error {} - -function error(message: string): never { - console.error(`%cerror%c: ${message}`, "color: red; font-weight: bold", ""); - throw new InitError(); -} - -export const HELP_TEXT = ` -${ - colors.bgRgb8( - colors.rgb8( - ` 🍋 @fresh/init${colors.rgb8(`@${initConfig.version}`, 248)} `, - 0, - ), - 121, - ) -} - -Initialize a new Fresh project. This will create all the necessary files -for a new project. - -To generate a project in the './foobar' subdirectory: - ${colors.rgb8("deno run -Ar jsr:@fresh/init ./foobar", 245)} - -To generate a project in the current directory: - ${colors.rgb8("deno run -Ar jsr:@fresh/init .", 245)} - -${colors.rgb8("USAGE:", 3)} - ${colors.rgb8("deno run -Ar jsr:@fresh/init [DIRECTORY]", 245)} - -${colors.rgb8("OPTIONS:", 3)} - ${colors.rgb8("--force", 2)} Overwrite existing files - ${colors.rgb8("--tailwind", 2)} Use Tailwind for styling - ${colors.rgb8("--vscode", 2)} Setup project for VS Code - ${colors.rgb8("--docker", 2)} Setup Project to use Docker - ${colors.rgb8("--builder", 2)} Setup with builder instead of vite - ${colors.rgb8("--help, -h", 2)} Show this help message -`; - -export const CONFIRM_EMPTY_MESSAGE = - "The target directory is not empty (files could get overwritten). Do you want to continue anyway?"; -export const CONFIRM_TAILWIND_MESSAGE = `Set up ${ - colors.cyan("Tailwind CSS") -} for styling?`; -export const CONFIRM_VSCODE_MESSAGE = `Do you use ${colors.cyan("VS Code")}?`; -export const CONFIRM_VITE_MESSAGE = `Set up ${ - colors.cyan("Vite") -} for build tooling?`; - +/** + * Initialize a new Fresh project using templates. + * This is a pure template processor - all validation, prompts, and output + * should be handled by the caller (typically CLI). + * + * @example + * ```ts + * import { initProject, resolveVersions } from "./init.ts"; + * + * const options: InitOptions = { + * directory: "./my-app", + * tailwind: true, + * vscode: false, + * docker: false, + * builder: false, + * force: false, + * }; + * + * const versions = await resolveVersions(); + * await initProject(Deno.cwd(), options, versions); + * ``` + * + * @param cwd - Current working directory + * @param options - Initialization options (optional fields will use defaults) + * @param versions - Pre-resolved version strings (without PROJECT_NAME) + */ export async function initProject( - cwd = Deno.cwd(), - input: (string | number)[], - flags: { - docker?: boolean | null; - force?: boolean | null; - tailwind?: boolean | null; - vscode?: boolean | null; - builder?: boolean | null; - help?: boolean | null; - h?: boolean | null; - } = {}, + cwd: string, + options: Required, + versions: Omit, ): Promise { - const freshVersion = await getLatestVersion("@fresh/core", FRESH_VERSION); + const projectDir = path.resolve(cwd, options.directory); + const projectName = path.basename(projectDir); - if (flags.help || flags.h) { - console.log(HELP_TEXT); - return; - } + // Boolean flags for template/variant selection (not template variables) + const useVite = !options.builder; + const useTailwind = options.tailwind; + const useVSCode = options.vscode; + const useDocker = options.docker; - console.log(); - console.log( - colors.bgRgb8( - colors.rgb8(" 🍋 Fresh: The next-gen web framework. ", 0), - 121, - ), - ); - console.log(` version ${colors.rgb8(freshVersion, 4)}`); - console.log(); - - let unresolvedDirectory; - if (input.length !== 1) { - const userInput = prompt( - "Project Name:", - "fresh-project", - ); - if (!userInput) { - error(HELP_TEXT); - } - - unresolvedDirectory = userInput; - } else { - unresolvedDirectory = String(input[0]); - } - - const projectDir = path.resolve(cwd, unresolvedDirectory); - - try { - const dir = [...Deno.readDirSync(projectDir)]; - const isEmpty = dir.length === 0 || - dir.length === 1 && dir[0].name === ".git"; - if ( - !isEmpty && - !(flags.force === null ? confirm(CONFIRM_EMPTY_MESSAGE) : flags.force) - ) { - error("Directory is not empty."); - } - } catch (err) { - if (!(err instanceof Deno.errors.NotFound)) { - throw err; - } - } - - const useVite = !flags.builder; - - const useDocker = flags.docker; - let useTailwind = flags.tailwind || false; - if (flags.tailwind == null) { - if ( - confirm(CONFIRM_TAILWIND_MESSAGE) - ) { - useTailwind = true; - } - } - - const useVSCode = flags.vscode == null - ? confirm(CONFIRM_VSCODE_MESSAGE) - : flags.vscode; - - const writeFile = async ( - pathname: string, - content: - | string - | Uint8Array - | ReadableStream - | Record, - ) => await writeProjectFile(projectDir, pathname, content); - - const GITIGNORE = `# dotenv environment variable files -.env -.env.development.local -.env.test.local -.env.production.local -.env.local - -# Fresh build directory -_fresh/ -# npm + other dependencies -node_modules/ -vendor/ -`; - - await writeFile(".gitignore", GITIGNORE); - - if (useDocker) { - const DENO_VERSION = Deno.version.deno; - const DOCKERFILE_TEXT = ` -FROM denoland/deno:${DENO_VERSION} - -ARG GIT_REVISION -ENV DENO_DEPLOYMENT_ID=\${GIT_REVISION} - -WORKDIR /app - -COPY . . -RUN deno cache _fresh/server.js - -EXPOSE 8000 - -CMD ["serve", "-A", "_fresh/server.js"] - -`; - await writeFile("Dockerfile", DOCKERFILE_TEXT); - } - - // deno-fmt-ignore - const GRADIENT_CSS = css`.fresh-gradient { - background-color: rgb(134, 239, 172); - background-image: linear-gradient( - to right bottom, - rgb(219, 234, 254), - rgb(187, 247, 208), - rgb(254, 249, 195) - ); -}`; - // deno-fmt-ignore - const NO_TAILWIND_STYLES = css`*, -*::before, -*::after { - box-sizing: border-box; -} -* { - margin: 0; -} -button { - color: inherit; -} -button, [role="button"] { - cursor: pointer; -} -code { - font-family: - ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", - "Courier New", monospace; - font-size: 1em; -} -img, -svg { - display: block; -} -img, -video { - max-width: 100%; - height: auto; -} - -html { - line-height: 1.5; - -webkit-text-size-adjust: 100%; - font-family: - ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", - Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, - "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", - "Noto Color Emoji"; -} -.transition-colors { - transition-property: background-color, border-color, color, fill, stroke; - transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); - transition-duration: 150ms; -} -.my-6 { - margin-bottom: 1.5rem; - margin-top: 1.5rem; -} -.text-4xl { - font-size: 2.25rem; - line-height: 2.5rem; -} -.mx-2 { - margin-left: 0.5rem; - margin-right: 0.5rem; -} -.my-4 { - margin-bottom: 1rem; - margin-top: 1rem; -} -.mx-auto { - margin-left: auto; - margin-right: auto; -} -.px-4 { - padding-left: 1rem; - padding-right: 1rem; -} -.py-8 { - padding-bottom: 2rem; - padding-top: 2rem; -} -.bg-\\[\\#86efac\\] { - background-color: #86efac; -} -.text-3xl { - font-size: 1.875rem; - line-height: 2.25rem; -} -.py-6 { - padding-bottom: 1.5rem; - padding-top: 1.5rem; -} -.px-2 { - padding-left: 0.5rem; - padding-right: 0.5rem; -} -.py-1 { - padding-bottom: 0.25rem; - padding-top: 0.25rem; -} -.border-gray-500 { - border-color: #6b7280; -} -.bg-white { - background-color: #fff; -} -.flex { - display: flex; -} -.gap-8 { - grid-gap: 2rem; - gap: 2rem; -} -.font-bold { - font-weight: 700; -} -.max-w-screen-md { - max-width: 768px; -} -.flex-col { - flex-direction: column; -} -.items-center { - align-items: center; -} -.justify-center { - justify-content: center; -} -.border-2 { - border-width: 2px; -} -.rounded-sm { - border-radius: 0.25rem; -} -.hover\\:bg-gray-200:hover { - background-color: #e5e7eb; -} -.tabular-nums { - font-variant-numeric: tabular-nums; -} -.min-h-screen { - min-height: 100vh; -} - -${GRADIENT_CSS}`; - // deno-fmt-ignore - const TAILWIND_CSS = css`@import "tailwindcss"; -${GRADIENT_CSS}`; - - const cssStyles = useTailwind ? TAILWIND_CSS : NO_TAILWIND_STYLES; - - if (useVite) { - await writeFile("assets/styles.css", cssStyles); - await writeFile( - "client.ts", - `// Import CSS files here for hot module reloading to work. -import "./assets/styles.css";`, - ); - } else { - await writeFile("static/styles.css", cssStyles); - } - // deno-fmt-ignore - const STATIC_LOGO = - ` - - - - -`; - await writeFile("static/logo.svg", STATIC_LOGO); - - try { - const res = await fetch("https://fresh.deno.dev/favicon.ico"); - const buf = await res.arrayBuffer(); - await writeFile("static/favicon.ico", new Uint8Array(buf)); - } catch { - // Skip this and be silent if there is a network issue. - } - - const MAIN_TS = `import { App, staticFiles } from "fresh"; -import { define, type State } from "./utils.ts"; - -export const app = new App(); - -app.use(staticFiles()); - -// Pass a shared value from a middleware -app.use(async (ctx) => { - ctx.state.shared = "hello"; - return await ctx.next(); -}); - -// this is the same as the /api/:name route defined via a file. feel free to delete this! -app.get("/api2/:name", (ctx) => { - const name = ctx.params.name; - return new Response( - \`Hello, \${name.charAt(0).toUpperCase() + name.slice(1)}!\`, - ); -}); - -// this can also be defined via a file. feel free to delete this! -const exampleLoggerMiddleware = define.middleware((ctx) => { - console.log(\`\${ctx.req.method} \${ctx.req.url}\`); - return ctx.next(); -}); -app.use(exampleLoggerMiddleware); - -// Include file-system based routes here -app.fsRoutes();`; - await writeFile("main.ts", MAIN_TS); - - const COMPONENTS_BUTTON_TSX = - `import type { ComponentChildren } from "preact"; - -export interface ButtonProps { - id?: string; - onClick?: () => void; - children?: ComponentChildren; - disabled?: boolean; -} - -export function Button(props: ButtonProps) { - return ( - -

{props.count}

- - - ); -}`; - await writeFile("islands/Counter.tsx", ISLANDS_COUNTER_TSX); - - const DEV_TS = `#!/usr/bin/env -S deno run -A --watch=static/,routes/ -${useTailwind ? `import { tailwind } from "@fresh/plugin-tailwind";\n` : ""} -import { Builder } from "fresh/dev"; - -const builder = new Builder(); -${useTailwind ? "tailwind(builder);" : ""} -if (Deno.args.includes("build")) { - await builder.build(); -} else { - await builder.listen(() => import("./main.ts")); -}`; - - if (!useVite) { - await writeFile("dev.ts", DEV_TS); - } - - const denoJson = { - nodeModulesDir: "auto", - tasks: { - check: "deno fmt --check . && deno lint . && deno check", - dev: "deno run -A --watch=static/,routes/ dev.ts", - build: "deno run -A dev.ts build", - start: "deno serve -A _fresh/server.js", - update: "deno run -A -r jsr:@fresh/update .", - }, - lint: { - rules: { - tags: ["fresh", "recommended"], - }, - }, - exclude: ["**/_fresh/*"], - imports: { - "fresh": `jsr:@fresh/core@^${freshVersion}`, - "preact": `npm:preact@^${PREACT_VERSION}`, - "@preact/signals": `npm:@preact/signals@^${PREACT_SIGNALS_VERSION}`, - } as Record, - compilerOptions: { - lib: ["dom", "dom.asynciterable", "dom.iterable", "deno.ns"], - jsx: "precompile", - jsxImportSource: "preact", - jsxPrecompileSkipElements: [ - "a", - "img", - "source", - "body", - "html", - "head", - "title", - "meta", - "script", - "link", - "style", - "base", - "noscript", - "template", - ], - } as Record, + // Template substitution variables (includes PROJECT_NAME + all versions) + const variables: TemplateVariables = { + ...versions, + PROJECT_NAME: projectName, }; - if (useVite) { - denoJson.compilerOptions.types = ["vite/client"]; - denoJson.tasks.dev = "vite"; - denoJson.tasks.build = "vite build"; - - const vitePluginVersion = await getLatestVersion( - "@fresh/plugin-vite", - FRESH_VITE_PLUGIN, - ); - - denoJson.imports["@fresh/plugin-vite"] = - `jsr:@fresh/plugin-vite@^${vitePluginVersion}`; - denoJson.imports["vite"] = "npm:vite@^7.1.3"; - - if (useTailwind) { - denoJson.imports["tailwindcss"] = - `npm:tailwindcss@^${TAILWINDCSS_VERSION}`; - denoJson.imports["@tailwindcss/vite"] = `npm:@tailwindcss/vite@^4.1.12`; - } + // Select complete template based on build system and styling choice + let templateName: string; + if (useVite && useTailwind) { + templateName = "vite-tailwind"; + } else if (useVite) { + templateName = "vite"; } else if (useTailwind) { - denoJson.imports["tailwindcss"] = `npm:tailwindcss@^${TAILWINDCSS_VERSION}`; - denoJson.imports["@fresh/plugin-tailwind"] = - `jsr:@fresh/plugin-tailwind@^${FRESH_TAILWIND_VERSION}`; - denoJson.imports["@tailwindcss/postcss"] = - `npm:@tailwindcss/postcss@^${TAILWINDCSS_POSTCSS_VERSION}`; - denoJson.imports["postcss"] = `npm:postcss@^${POSTCSS_VERSION}`; + templateName = "builder-tailwind"; + } else { + templateName = "builder"; } - await writeFile("deno.json", denoJson); - - if (useVite) { - let viteConfig = `import { defineConfig } from "vite"; -import { fresh } from "@fresh/plugin-vite";\n`; - - if (useTailwind) { - viteConfig += `import tailwindcss from "@tailwindcss/vite";\n`; - } - - viteConfig += `\nexport default defineConfig({ - plugins: [fresh()${useTailwind ? ", tailwindcss()" : ""}], -});`; - - await writeFile("vite.config.ts", viteConfig); - } - - const README_MD = `# Fresh project - -Your new Fresh project is ready to go. You can follow the Fresh "Getting -Started" guide here: https://fresh.deno.dev/docs/getting-started - -### Usage - -Make sure to install Deno: -https://docs.deno.com/runtime/getting_started/installation - -Then start the project in development mode: - -\`\`\` -deno task dev -\`\`\` - -This will watch the project directory and restart as necessary.`; - await writeFile("README.md", README_MD); + const templateDir = path.join(getTemplateDir(), templateName); + // Collect truly additive variants (docker, vscode, vscode-tailwind) + const variants: string[] = []; if (useVSCode) { - const vscodeSettings = { - "deno.enable": true, - "deno.lint": true, - "editor.defaultFormatter": "denoland.vscode-deno", - "[typescriptreact]": { - "editor.defaultFormatter": "denoland.vscode-deno", - }, - "[typescript]": { - "editor.defaultFormatter": "denoland.vscode-deno", - }, - "[javascriptreact]": { - "editor.defaultFormatter": "denoland.vscode-deno", - }, - "[javascript]": { - "editor.defaultFormatter": "denoland.vscode-deno", - }, - "css.customData": useTailwind ? [".vscode/tailwind.json"] : undefined, - }; - - await writeFile(".vscode/settings.json", vscodeSettings); - - const recommendations = ["denoland.vscode-deno"]; - if (useTailwind) recommendations.push("bradlc.vscode-tailwindcss"); - await writeFile(".vscode/extensions.json", { recommendations }); - + variants.push("vscode"); + // Add Tailwind-specific VS Code support if both are enabled if (useTailwind) { - const tailwindCustomData = { - "version": 1.1, - "atDirectives": [ - { - "name": "@tailwind", - "description": - "Use the `@tailwind` directive to insert Tailwind's `base`, `components`, `utilities` and `screens` styles into your CSS.", - "references": [ - { - "name": "Tailwind Documentation", - "url": - "https://tailwindcss.com/docs/functions-and-directives#tailwind", - }, - ], - }, - { - "name": "@apply", - "description": - "Use the `@apply` directive to inline any existing utility classes into your own custom CSS. This is useful when you find a common utility pattern in your HTML that you’d like to extract to a new component.", - "references": [ - { - "name": "Tailwind Documentation", - "url": - "https://tailwindcss.com/docs/functions-and-directives#apply", - }, - ], - }, - { - "name": "@responsive", - "description": - "You can generate responsive variants of your own classes by wrapping their definitions in the `@responsive` directive:\n```css\n@responsive {\n .alert {\n background-color: #E53E3E;\n }\n}\n```\n", - "references": [ - { - "name": "Tailwind Documentation", - "url": - "https://tailwindcss.com/docs/functions-and-directives#responsive", - }, - ], - }, - { - "name": "@screen", - "description": - "The `@screen` directive allows you to create media queries that reference your breakpoints by **name** instead of duplicating their values in your own CSS:\n```css\n@screen sm {\n /* ... */\n}\n```\n…gets transformed into this:\n```css\n@media (min-width: 640px) {\n /* ... */\n}\n```\n", - "references": [ - { - "name": "Tailwind Documentation", - "url": - "https://tailwindcss.com/docs/functions-and-directives#screen", - }, - ], - }, - { - "name": "@variants", - "description": - "Generate `hover`, `focus`, `active` and other **variants** of your own utilities by wrapping their definitions in the `@variants` directive:\n```css\n@variants hover, focus {\n .btn-brand {\n background-color: #3182CE;\n }\n}\n```\n", - "references": [ - { - "name": "Tailwind Documentation", - "url": - "https://tailwindcss.com/docs/functions-and-directives#variants", - }, - ], - }, - ], - }; - - await writeFile(".vscode/tailwind.json", tailwindCustomData); + variants.push("vscode-tailwind"); } } - - // Specifically print unresolvedDirectory, rather than resolvedDirectory in order to - // not leak personal info (e.g. `/Users/MyName`) - console.log( - "\n%cProject initialized!\n", - "color: green; font-weight: bold", - ); - - if (unresolvedDirectory !== ".") { - console.log( - `Enter your project directory using %ccd ${unresolvedDirectory}%c.`, - "color: cyan", - "", - ); + if (useDocker) { + variants.push("docker"); } - console.log( - "Run %cdeno task dev%c to start the project. %cCTRL-C%c to stop.", - "color: cyan", - "", - "color: cyan", - "", - ); - console.log(); - console.log( - "Stuck? Join our Discord %chttps://discord.gg/deno", - "color: cyan", - "", - ); - console.log(); - console.log( - "%cHappy hacking! 🦕", - "color: gray", - ); + + // Process template + await processTemplate(templateDir, variants, projectDir, variables); + + // Fetch and write favicon + await fetchFavicon(projectDir); } -async function writeProjectFile( - projectDir: string, - pathname: string, - content: - | string - | Uint8Array - | ReadableStream - | Record, -) { - const filePath = path.join( - projectDir, - ...pathname.split("/").filter(Boolean), - ); - try { - await Deno.mkdir( - path.dirname(filePath), - { recursive: true }, - ); - if (typeof content === "string") { - let formatted = content; - if (!content.endsWith("\n\n")) { - formatted += "\n"; +/** + * Resolve all version strings for dependencies. + * + * Version resolution strategy: + * - Only Fresh core version is fetched from network (latest from JSR) + * - All other versions use fixed defaults (updated by release script) + * + * @example + * ```ts + * // Resolve with defaults + * const versions = await resolveVersions(); + * console.log(versions.FRESH_VERSION); // "2.1.1" or latest from network + * + * // Override specific versions (useful for testing) + * const testVersions = await resolveVersions({ + * fresh: "2.0.0", + * preact: "10.20.0", + * }); + * ``` + * + * @param overrides - Optional version overrides for testing or pinning + * @returns Template variables (without PROJECT_NAME, which is added later) + */ +export async function resolveVersions( + overrides?: VersionOverrides, +): Promise> { + // Build default versions object + const defaults = { + fresh: FRESH_VERSION, + freshTailwind: FRESH_TAILWIND_VERSION, + freshVitePlugin: FRESH_VITE_PLUGIN_VERSION, + preact: PREACT_VERSION, + preactSignals: PREACT_SIGNALS_VERSION, + tailwindcss: TAILWINDCSS_VERSION, + tailwindcssPostcss: TAILWINDCSS_POSTCSS_VERSION, + tailwindcssVite: TAILWINDCSS_VITE_VERSION, + postcss: POSTCSS_VERSION, + vite: VITE_VERSION, + }; + + const versions = { ...defaults, ...overrides }; + + // Only fetch latest for Fresh core from JSR + const fresh = await getLatestVersion("@fresh/core", versions.fresh); + + return { + FRESH_VERSION: fresh, + FRESH_TAILWIND_VERSION: versions.freshTailwind, + FRESH_VITE_PLUGIN_VERSION: versions.freshVitePlugin, + // Use fixed versions for Preact and Signals (not fetched from network) + PREACT_VERSION: versions.preact, + PREACT_SIGNALS_VERSION: versions.preactSignals, + TAILWINDCSS_VERSION: versions.tailwindcss, + TAILWINDCSS_POSTCSS_VERSION: versions.tailwindcssPostcss, + TAILWINDCSS_VITE_VERSION: versions.tailwindcssVite, + POSTCSS_VERSION: versions.postcss, + VITE_VERSION: versions.vite, + DENO_VERSION: Deno.version.deno, + }; +} + +/** + * Process a template and write to target directory. + */ +async function processTemplate( + templateDir: string, + variants: string[], + targetDir: string, + variables: TemplateVariables, +): Promise { + // Ensure target directory exists + await fs.ensureDir(targetDir); + + // Copy base template + await processDirectory(templateDir, targetDir, variables); + + // Apply variants + const variantsDir = getVariantsDir(); + for (const variant of variants) { + const variantDir = path.join(variantsDir, variant); + try { + await Deno.stat(variantDir); + await applyVariant(variantDir, targetDir, variables); + } catch (err) { + if (!(err instanceof Deno.errors.NotFound)) { + throw err; } - await Deno.writeTextFile(filePath, formatted); - } else if ( - content instanceof Uint8Array || content instanceof ReadableStream - ) { - await Deno.writeFile(filePath, content); + // Variant doesn't exist, skip it + } + } +} + +/** + * Process a directory, copying and transforming files. + */ +async function processDirectory( + srcDir: string, + destDir: string, + variables: TemplateVariables, +): Promise { + for await (const entry of Deno.readDir(srcDir)) { + const srcPath = path.join(srcDir, entry.name); + + if (entry.isDirectory) { + // Process directory name (convert __ to .) + const destName = processFilename(entry.name); + const destPath = path.join(destDir, destName); + await fs.ensureDir(destPath); + await processDirectory(srcPath, destPath, variables); } else { - await Deno.writeTextFile( - filePath, - JSON.stringify(content, null, 2) + "\n", - ); - } - } catch (err) { - if (!(err instanceof Deno.errors.AlreadyExists)) { - throw err; + // For files, don't process filename here - processFile will handle it + await processFile(srcPath, destDir, entry.name, variables); } } } -interface JsrMeta { - scope: string; - name: string; - latest: string | null; - versions: Record; -} - -async function getLatestVersion( - pkg: string, - fallback: string, -): Promise { - // deno-lint-ignore no-explicit-any - if ((globalThis as any).INIT_TEST) { - return fallback; - } +/** + * Process a single file. + */ +async function processFile( + srcPath: string, + destDir: string, + filename: string, + variables: TemplateVariables, +): Promise { + // Process filename: convert __ prefix to . prefix + const finalName = processFilename(filename); + const destPath = path.join(destDir, finalName); + // Try to read as text and perform substitution on ALL files + // If file is binary, the copy will fail gracefully and we'll copy as binary try { - const res = await fetch(`https://jsr.io/${pkg}/meta.json`); - const json = (await res.json()) as JsrMeta; - - if (json.latest !== null) { - return json.latest; - } - - const versions = Object.keys(json.versions); - if (versions.length === 0) throw new Error("No versions"); - - versions.sort((a, b) => { - const s1 = semver.parse(a); - const s2 = semver.parse(b); - return semver.compare(s1, s2); - }); - - return versions.at(-1)!; - } catch { - console.log( - `Could not fetch latest ${pkg} version. Falling back to: ${fallback}`, + const content = await Deno.readTextFile(srcPath); + const transformed = substituteVariables( + content, + variables as unknown as Record, ); - return fallback; + await Deno.writeTextFile(destPath, transformed); + } catch { + // File is binary or unreadable as text, copy as-is + await fs.copy(srcPath, destPath, { overwrite: true }); + } +} + +/** + * Apply a variant overlay to the target directory. + * Variants are truly additive - they only add files, don't modify existing ones. + */ +async function applyVariant( + variantDir: string, + targetDir: string, + variables: TemplateVariables, +): Promise { + for await (const entry of Deno.readDir(variantDir)) { + const srcPath = path.join(variantDir, entry.name); + + if (entry.isDirectory) { + // Process directory name (convert __ to .) + const destName = processFilename(entry.name); + const destPath = path.join(targetDir, destName); + await fs.ensureDir(destPath); + await processDirectory(srcPath, destPath, variables); + } else { + // Regular file - copy/process + await processFile(srcPath, targetDir, entry.name, variables); + } + } +} + +/** + * Fetch and write favicon. + */ +async function fetchFavicon(projectDir: string): Promise { + try { + const res = await fetch("https://fresh.deno.dev/favicon.ico"); + if (!res.ok) return; + + const buf = await res.arrayBuffer(); + const faviconPath = path.join(projectDir, "static", "favicon.ico"); + await Deno.writeFile(faviconPath, new Uint8Array(buf)); + } catch { + // Silent failure - favicon is not critical } } diff --git a/packages/init/src/init_test.ts b/packages/init/src/init_test.ts deleted file mode 100644 index b91a67ae..00000000 --- a/packages/init/src/init_test.ts +++ /dev/null @@ -1,363 +0,0 @@ -import { expect } from "@std/expect"; -import { - CONFIRM_TAILWIND_MESSAGE, - CONFIRM_VITE_MESSAGE, - CONFIRM_VSCODE_MESSAGE, - HELP_TEXT, - initProject, -} from "./init.ts"; -import * as path from "@std/path"; -import { getStdOutput, withBrowser } from "../../fresh/tests/test_utils.tsx"; -import { waitForText } from "../../fresh/tests/test_utils.tsx"; -import { withChildProcessServer } from "../../fresh/tests/test_utils.tsx"; -import { withTmpDir as withTmpDirBase } from "../../fresh/src/test_utils.ts"; -import { stub } from "@std/testing/mock"; - -// deno-lint-ignore no-explicit-any -(globalThis as any).INIT_TEST = true; - -function stubPrompt(result: string) { - return stub(globalThis, "prompt", () => result); -} - -function stubConfirm(steps: Record = {}) { - return stub( - globalThis, - "confirm", - (message) => message ? steps[message] : false, - ); -} - -function stubLogs() { - return stub( - console, - "log", - () => undefined, - ); -} - -function withTmpDir(): Promise<{ dir: string } & AsyncDisposable> { - // Windows need temporary files in the repository root - if (Deno.build.os === "windows") { - const dir = path.join(import.meta.dirname!, "..", "..", "..", ".."); - return withTmpDirBase({ dir, prefix: "tmp_" }); - } - return withTmpDirBase(); -} - -async function patchProject(dir: string): Promise { - const jsonPath = path.join(dir, "deno.json"); - const json = JSON.parse(await Deno.readTextFile(jsonPath)); - - json.workspace = []; - // See https://github.com/denoland/deno/issues/27313 - // json.links = [path.fromFileURL(new URL("../..", import.meta.url))]; - json.links = [new URL("../../fresh", import.meta.url).href]; - - // assert with this stricter rule, before adding it to initialized projects - json.lint.rules.include = ["verbatim-module-syntax"]; - - await Deno.writeTextFile(jsonPath, JSON.stringify(json, null, 2) + "\n"); -} - -async function expectProjectFile(dir: string, pathname: string) { - const filePath = path.join(dir, ...pathname.split("/").filter(Boolean)); - const stat = await Deno.stat(filePath); - if (!stat.isFile) { - throw new Error(`Not a project file: ${filePath}`); - } -} - -async function expectNotProjectFile(dir: string, pathname: string) { - const filePath = path.join(dir, ...pathname.split("/").filter(Boolean)); - try { - const stat = await Deno.stat(filePath); - if (stat.isFile) { - throw new Error(`A project file but expected it not to be: ${filePath}`); - } - } catch (err) { - if (!(err instanceof Deno.errors.NotFound)) { - throw err; - } - } -} - -async function readProjectFile(dir: string, pathname: string): Promise { - const filePath = path.join(dir, ...pathname.split("/").filter(Boolean)); - const content = await Deno.readTextFile(filePath); - return content; -} - -Deno.test("init - show help", async () => { - using logs = stubLogs(); - - await initProject("", [], { help: true }); - const args = logs.calls.flatMap((c) => c.args); - const out = args.join("\n"); - await initProject("", [], { h: true }); - - expect(out).toBe(HELP_TEXT); - expect(args).toEqual(logs.calls.flatMap((c) => c.args).slice(args.length)); -}); - -Deno.test("init - new project", async () => { - await using tmp = await withTmpDir(); - using _promptStub = stubPrompt("fresh-init"); - using _confirmStub = stubConfirm(); - - await initProject(tmp.dir, [], { builder: true }); -}); - -Deno.test("init - create project dir", async () => { - await using tmp = await withTmpDir(); - const dir = tmp.dir; - using _promptStub = stubPrompt("fresh-init"); - using _confirmStub = stubConfirm(); - await initProject(dir, [], { builder: true }); - - const root = path.join(dir, "fresh-init"); - await expectProjectFile(root, "deno.json"); - await expectProjectFile(root, "main.ts"); - await expectProjectFile(root, "dev.ts"); - await expectProjectFile(root, ".gitignore"); - await expectProjectFile(root, "static/styles.css"); -}); - -Deno.test("init - with tailwind", async () => { - await using tmp = await withTmpDir(); - const dir = tmp.dir; - using _promptStub = stubPrompt("."); - using _confirmStub = stubConfirm({ - [CONFIRM_TAILWIND_MESSAGE]: true, - }); - await initProject(dir, [], { builder: true }); - - const css = await readProjectFile(dir, "static/styles.css"); - expect(css).toMatch(/@import "tailwindcss"/); - - const main = await readProjectFile(dir, "main.ts"); - const dev = await readProjectFile(dir, "dev.ts"); - expect(main).not.toMatch(/tailwind/); - expect(dev).toMatch(/tailwind/); -}); - -Deno.test("init - with vscode", async () => { - await using tmp = await withTmpDir(); - const dir = tmp.dir; - using _promptStub = stubPrompt("."); - using _confirmStub = stubConfirm({ - [CONFIRM_VSCODE_MESSAGE]: true, - }); - await initProject(dir, [], { builder: true }); - - await expectProjectFile(dir, ".vscode/settings.json"); - await expectProjectFile(dir, ".vscode/extensions.json"); -}); - -Deno.test({ - name: "init - fmt, lint, and type check project", - // Ignore this test on canary due to different formatting - // behaviours when the formatter changes. - ignore: Deno.version.deno.includes("+"), - fn: async () => { - await using tmp = await withTmpDir(); - const dir = tmp.dir; - using _promptStub = stubPrompt("."); - using _confirmStub = stubConfirm(); - await initProject(dir, [], { builder: true }); - await expectProjectFile(dir, "main.ts"); - await expectProjectFile(dir, "dev.ts"); - - await patchProject(dir); - - const check = await new Deno.Command(Deno.execPath(), { - args: ["task", "check"], - cwd: dir, - stderr: "inherit", - stdout: "inherit", - }).output(); - expect(check.code).toEqual(0); - }, -}); - -Deno.test( - "init with tailwind - fmt, lint, and type check project", - async () => { - await using tmp = await withTmpDir(); - const dir = tmp.dir; - using _promptStub = stubPrompt("."); - using _confirmStub = stubConfirm({ - [CONFIRM_TAILWIND_MESSAGE]: true, - }); - - await initProject(dir, [], { builder: true }); - await expectProjectFile(dir, "main.ts"); - await expectProjectFile(dir, "dev.ts"); - - await patchProject(dir); - - const check = await new Deno.Command(Deno.execPath(), { - args: ["task", "check"], - cwd: dir, - stderr: "inherit", - stdout: "inherit", - }).output(); - expect(check.code).toEqual(0); - }, -); - -Deno.test({ - // TODO: For some reason this test is flaky in GitHub CI. It works when - // testing locally on windows though. Not sure what's going on. - ignore: Deno.build.os === "windows" && Deno.env.get("CI") !== undefined, - name: "init - can start dev server", - fn: async () => { - await using tmp = await withTmpDir(); - const dir = tmp.dir; - using _promptStub = stubPrompt("."); - using _confirmStub = stubConfirm(); - await initProject(dir, [], { builder: true }); - await expectProjectFile(dir, "main.ts"); - await expectProjectFile(dir, "dev.ts"); - - await patchProject(dir); - await withChildProcessServer( - { cwd: dir, args: ["task", "dev"] }, - async (address) => { - await withBrowser(async (page) => { - await page.goto(address); - await page.locator("#decrement").click(); - await waitForText(page, "button + p", "2"); - }); - }, - ); - }, -}); - -Deno.test("init - can start built project", async () => { - await using tmp = await withTmpDir(); - const dir = tmp.dir; - using _promptStub = stubPrompt("."); - using _confirmStub = stubConfirm(); - await initProject(dir, [], { builder: true }); - await expectProjectFile(dir, "main.ts"); - await expectProjectFile(dir, "dev.ts"); - - await patchProject(dir); - - // Build - await new Deno.Command(Deno.execPath(), { - args: ["task", "build"], - stdin: "null", - stdout: "piped", - stderr: "piped", - cwd: dir, - }).output(); - - await withChildProcessServer( - { cwd: dir, env: { PORT: "0" }, args: ["task", "start"] }, - async (address) => { - await withBrowser(async (page) => { - await page.goto(address); - await page.locator("button").click(); - await waitForText(page, "button + p", "2"); - }); - }, - ); -}); - -Deno.test("init - errors on missing build cache in prod", async () => { - await using tmp = await withTmpDir(); - const dir = tmp.dir; - using _promptStub = stubPrompt("."); - using _confirmStub = stubConfirm(); - await initProject(dir, [], { builder: true }); - await expectProjectFile(dir, "main.ts"); - await expectProjectFile(dir, "dev.ts"); - - await patchProject(dir); - - const cp = await new Deno.Command(Deno.execPath(), { - args: ["task", "start"], - stdin: "null", - stdout: "piped", - stderr: "piped", - cwd: dir, - }).output(); - - const { stderr } = getStdOutput(cp); - expect(cp.code).toEqual(1); - - expect(stderr).toMatch(/Module not found/); -}); - -// There is a peerDependency issue with links -Deno.test.ignore("init - vite dev server", async () => { - await using tmp = await withTmpDir(); - const dir = tmp.dir; - using _promptStub = stubPrompt("."); - using _confirmStub = stubConfirm(); - await initProject(dir, [], {}); - - await expectProjectFile(dir, "vite.config.ts"); - await expectNotProjectFile(dir, "dev.ts"); - - await patchProject(dir); - - await withChildProcessServer( - { cwd: dir, args: ["task", "dev"] }, - async (address) => { - await withBrowser(async (page) => { - await page.goto(address); - await page.locator("#decrement").click(); - await waitForText(page, "button + p", "2"); - }); - }, - ); -}); - -// There is a peerDependency issue with links -Deno.test.ignore("init - vite build", async () => { - await using tmp = await withTmpDir(); - const dir = tmp.dir; - using _promptStub = stubPrompt("."); - using _confirmStub = stubConfirm(); - await initProject(dir, [], {}); - - await expectProjectFile(dir, "vite.config.ts"); - - await patchProject(dir); - - // Build - await new Deno.Command(Deno.execPath(), { - args: ["task", "build"], - stdin: "null", - stdout: "piped", - stderr: "piped", - cwd: dir, - }).output(); - - await withChildProcessServer( - { cwd: dir, env: { PORT: "0" }, args: ["task", "start"] }, - async (address) => { - await withBrowser(async (page) => { - await page.goto(address); - await page.locator("button").click(); - await waitForText(page, "button + p", "2"); - }); - }, - ); -}); - -Deno.test("init - with vite", async () => { - await using tmp = await withTmpDir(); - const dir = tmp.dir; - using _promptStub = stubPrompt("."); - using _confirmStub = stubConfirm({ - [CONFIRM_VITE_MESSAGE]: true, - }); - await initProject(dir, [], {}); - - await expectProjectFile(dir, "vite.config.ts"); - await expectNotProjectFile(dir, "dev.ts"); -}); diff --git a/packages/init/src/mod.ts b/packages/init/src/mod.ts index ce6cc9f4..b7451765 100644 --- a/packages/init/src/mod.ts +++ b/packages/init/src/mod.ts @@ -1,26 +1,220 @@ +#!/usr/bin/env -S deno run -A +/** + * CLI entry point for @fresh/init + * + * This module serves two purposes: + * 1. CLI execution: Parses command-line arguments and runs the init script + * 2. Programmatic API: Exports initProject and resolveVersions for library use + * + * When run directly (deno run -Ar jsr:@fresh/init), this serves as + * the CLI entry point, providing interactive and non-interactive modes + * for creating new Fresh projects. + */ + import { parseArgs } from "@std/cli/parse-args"; -import { initProject } from "./init.ts"; -import { InitError } from "./init.ts"; +import * as colors from "@std/fmt/colors"; +import { initProject as initProjectImpl, resolveVersions } from "./init.ts"; +import type { InitOptions } from "./types.ts"; +import initConfig from "../deno.json" with { type: "json" }; -const flags = parseArgs(Deno.args, { - boolean: ["force", "tailwind", "vscode", "docker", "help", "builder"], - default: { - force: null, - tailwind: null, - vscode: null, - docker: null, - builder: null, - }, - alias: { - help: "h", - }, -}); - -try { - await initProject(Deno.cwd(), flags._, flags); -} catch (err) { - if (err instanceof InitError) { - Deno.exit(1); - } - throw err; +const HELP_TEXT = ` +${ + colors.bgRgb8( + colors.rgb8( + ` 🍋 @fresh/init${colors.rgb8(`@${initConfig.version}`, 248)} `, + 0, + ), + 121, + ) +} + +Initialize a new Fresh project. This will create all the necessary files +for a new project. + +To generate a project in the './foobar' subdirectory: + ${colors.rgb8("deno run -Ar jsr:@fresh/init ./foobar", 245)} + +To generate a project in the current directory: + ${colors.rgb8("deno run -Ar jsr:@fresh/init .", 245)} + +${colors.rgb8("USAGE:", 3)} + ${colors.rgb8("deno run -Ar jsr:@fresh/init [DIRECTORY]", 245)} + +${colors.rgb8("OPTIONS:", 3)} + ${colors.rgb8("--force", 2)} Overwrite existing files + ${colors.rgb8("--tailwind", 2)} Use Tailwind for styling + ${colors.rgb8("--vscode", 2)} Setup project for VS Code + ${colors.rgb8("--docker", 2)} Setup project to use Docker + ${colors.rgb8("--builder", 2)} Setup with builder instead of vite + ${colors.rgb8("--help, -h", 2)} Show this help message +`; + +const CONFIRM_EMPTY_MESSAGE = + "The target directory is not empty (files could get overwritten). Do you want to continue anyway?"; +const CONFIRM_TAILWIND_MESSAGE = `Set up ${ + colors.cyan("Tailwind CSS") +} for styling?`; +const CONFIRM_VSCODE_MESSAGE = `Do you use ${colors.cyan("VS Code")}?`; + +export class InitError extends Error {} + +function error(message: string): never { + console.error(`%cerror%c: ${message}`, "color: red; font-weight: bold", ""); + throw new InitError(); +} + +/** + * Initialize a Fresh project. + * + * This is the main CLI entry point that accepts command-line arguments + * and flags to create a new Fresh project. + * + * @param cwd - Current working directory + * @param input - Directory arguments from command line + * @param flags - CLI flags (force, tailwind, vscode, docker, builder, help) + */ +export async function initProject( + cwd: string = Deno.cwd(), + input: (string | number)[], + flags: { + docker?: boolean | null; + force?: boolean | null; + tailwind?: boolean | null; + vscode?: boolean | null; + builder?: boolean | null; + help?: boolean | null; + h?: boolean | null; + } = {}, +): Promise { + // Show help if requested + if (flags.help || flags.h) { + console.log(HELP_TEXT); + return; + } + + // Display banner + console.log(); + console.log( + colors.bgRgb8( + colors.rgb8(" 🍋 Fresh: The next-gen web framework. ", 0), + 121, + ), + ); + console.log(); + + // Get project directory + let directory: string; + if (input.length === 0) { + const userInput = prompt("Project Name:", "fresh-project"); + if (!userInput) { + error(HELP_TEXT); + } + directory = userInput; + } else if (input.length === 1) { + directory = String(input[0]); + } else { + error("Too many arguments. Expected at most one directory argument."); + } + + // Build options from CLI flags (with prompts for missing values) + const tailwind = flags.tailwind ?? confirm(CONFIRM_TAILWIND_MESSAGE); + const vscode = flags.vscode ?? confirm(CONFIRM_VSCODE_MESSAGE); + let force = flags.force ?? false; + + // Check if directory is empty (if not forced) + if (!force) { + try { + const projectDir = new URL(directory, `file://${cwd}/`).pathname; + const entries = [...Deno.readDirSync(projectDir)]; + const isEmpty = entries.length === 0 || + (entries.length === 1 && entries[0].name === ".git"); + + if (!isEmpty) { + const shouldContinue = confirm(CONFIRM_EMPTY_MESSAGE); + if (!shouldContinue) { + error("Directory is not empty. Use --force to overwrite."); + } + force = true; + } + } catch (err) { + if (!(err instanceof Deno.errors.NotFound)) { + throw err; + } + // Directory doesn't exist - that's fine + } + } + + // Build fully resolved options + const options: Required = { + directory, + builder: flags.builder ?? false, + tailwind, + vscode, + docker: flags.docker ?? false, + force, + }; + + // Resolve versions + const versions = await resolveVersions(); + + console.log(` version ${colors.rgb8(versions.FRESH_VERSION, 4)}`); + console.log(); + + // Call the template engine (pure processing, no output) + await initProjectImpl(cwd, options, versions); + + // Display success messages + console.log( + "\n%cProject initialized!\n", + "color: green; font-weight: bold", + ); + + if (directory !== ".") { + console.log( + `Enter your project directory using %ccd ${directory}%c.`, + "color: cyan", + "", + ); + } + console.log( + "Run %cdeno task dev%c to start the project. %cCTRL-C%c to stop.", + "color: cyan", + "", + "color: cyan", + "", + ); + console.log(); + console.log( + "Stuck? Join our Discord %chttps://discord.gg/deno", + "color: cyan", + "", + ); + console.log(); + console.log("%cHappy hacking! 🦕", "color: gray"); +} + +// When run as CLI +if (import.meta.main) { + const flags = parseArgs(Deno.args, { + boolean: ["force", "tailwind", "vscode", "docker", "help", "builder"], + default: { + force: null, + tailwind: null, + vscode: null, + docker: null, + builder: null, + }, + alias: { + help: "h", + }, + }); + + try { + await initProject(Deno.cwd(), flags._, flags); + } catch (err) { + if (err instanceof InitError) { + Deno.exit(1); + } + throw err; + } } diff --git a/packages/init/src/sync.ts b/packages/init/src/sync.ts new file mode 100644 index 00000000..86452c68 --- /dev/null +++ b/packages/init/src/sync.ts @@ -0,0 +1,211 @@ +#!/usr/bin/env -S deno run -A +/** + * Sync script for template maintenance. + * + * This script copies common files from base templates to their corresponding + * template variants, making it easier to maintain shared files across templates. + * + * Structure: + * - assets/base/vite/ -> Copied to assets/template/vite/ and vite-tailwind/ + * - assets/base/builder/ -> Copied to assets/template/builder/ and builder-tailwind/ + * + * Template-specific files (like deno.json.tmpl, styles.css) are never overwritten. + * + * Usage: + * deno run -A sync_templates.ts + * deno run -A sync_templates.ts --dry-run + */ + +import * as path from "@std/path"; +import * as fs from "@std/fs"; +import * as colors from "@std/fmt/colors"; + +/** + * Files that should NOT be copied from base to templates. + * These are template-specific and should be maintained separately. + */ +const TEMPLATE_SPECIFIC_FILES = [ + // Dependency files - different for each template variant + "deno.json.tmpl", + "deno.json", + + // Build config - tailwind variants override these + "vite.config.ts", + + // Styles - different content for tailwind vs regular + "assets/styles.css", + "static/styles.css", +]; + +/** + * Template configurations. + */ +const TEMPLATE_CONFIG = { + vite: { + base: "assets/base/vite", + targets: ["assets/template/vite", "assets/template/vite-tailwind"], + }, + builder: { + base: "assets/base/builder", + targets: ["assets/template/builder", "assets/template/builder-tailwind"], + }, +}; + +interface SyncResult { + copied: string[]; + skipped: string[]; + errors: string[]; +} + +/** + * Check if a file path should be skipped (template-specific). + */ +function isTemplateSpecific(relPath: string): boolean { + return TEMPLATE_SPECIFIC_FILES.some((specific) => + relPath === specific || relPath.endsWith(`/${specific}`) + ); +} + +/** + * Recursively copy files from source to destination, skipping template-specific files. + */ +async function syncDirectory( + srcDir: string, + destDir: string, + baseDir: string, + dryRun: boolean, +): Promise { + const result: SyncResult = { copied: [], skipped: [], errors: [] }; + + try { + for await (const entry of Deno.readDir(srcDir)) { + const srcPath = path.join(srcDir, entry.name); + const destPath = path.join(destDir, entry.name); + const relPath = path.relative(baseDir, srcPath); + + if (entry.isDirectory) { + // Recursively sync directories + if (!dryRun) { + await fs.ensureDir(destPath); + } + const subResult = await syncDirectory( + srcPath, + destPath, + baseDir, + dryRun, + ); + result.copied.push(...subResult.copied); + result.skipped.push(...subResult.skipped); + result.errors.push(...subResult.errors); + } else { + // Check if file is template-specific + if (isTemplateSpecific(relPath)) { + result.skipped.push(relPath); + continue; + } + + // Copy file + try { + if (!dryRun) { + await fs.copy(srcPath, destPath, { overwrite: true }); + } + result.copied.push(relPath); + } catch (err) { + const message = err instanceof Error ? err.message : String(err); + result.errors.push(`${relPath}: ${message}`); + } + } + } + } catch (err) { + const message = err instanceof Error ? err.message : String(err); + result.errors.push(`Error reading ${srcDir}: ${message}`); + } + + return result; +} + +/** + * Sync base template to all its target templates. + */ +async function syncTemplate( + name: string, + config: { base: string; targets: string[] }, + dryRun: boolean, +): Promise { + console.log(colors.bold(colors.cyan(`\n📦 Syncing ${name} templates...`))); + console.log(colors.dim(` Base: ${config.base}`)); + + for (const target of config.targets) { + const targetName = path.basename(target); + console.log(colors.dim(` → ${targetName}`)); + + const result = await syncDirectory( + config.base, + target, + config.base, + dryRun, + ); + + if (result.copied.length > 0) { + console.log( + colors.green( + ` ✓ ${result.copied.length} file(s) ${ + dryRun ? "would be copied" : "copied" + }`, + ), + ); + } + + if (result.skipped.length > 0) { + console.log( + colors.yellow( + ` ⊘ ${result.skipped.length} file(s) skipped (template-specific)`, + ), + ); + } + + if (result.errors.length > 0) { + console.log(colors.red(` ✗ ${result.errors.length} error(s):`)); + for (const error of result.errors) { + console.log(colors.red(` ${error}`)); + } + } + } +} + +/** + * Main sync function. + */ +async function main() { + const args = Deno.args; + const dryRun = args.includes("--dry-run"); + + console.log(colors.bold("\n🔄 Template Sync Tool\n")); + + if (dryRun) { + console.log(colors.yellow("🔍 DRY RUN MODE - No files will be modified\n")); + } + + // Sync all template groups + for (const [name, config] of Object.entries(TEMPLATE_CONFIG)) { + await syncTemplate(name, config, dryRun); + } + + console.log(colors.bold(colors.green("\n✅ Sync complete!"))); + + if (dryRun) { + console.log( + colors.dim("\nRun without --dry-run to actually copy files."), + ); + } else { + console.log( + colors.dim( + "\nReview changes with git diff before committing.", + ), + ); + } +} + +if (import.meta.main) { + await main(); +} diff --git a/packages/init/src/types.ts b/packages/init/src/types.ts new file mode 100644 index 00000000..1cb64f68 --- /dev/null +++ b/packages/init/src/types.ts @@ -0,0 +1,82 @@ +/** + * Options for initializing a Fresh project. + * Optional fields will use defaults or prompt the user. + * + * @example + * ```ts + * const options: InitOptions = { + * directory: "./my-app", + * tailwind: true, + * vscode: false, + * docker: false, + * builder: false, + * force: false, + * }; + * ``` + */ +export interface InitOptions { + /** Target directory for the project */ + directory: string; + + /** Use legacy builder instead of Vite (default: false) */ + builder?: boolean; + + /** Include Tailwind CSS setup (default: prompt user) */ + tailwind?: boolean; + + /** Include VS Code configuration (default: prompt user) */ + vscode?: boolean; + + /** Include Docker setup (default: false) */ + docker?: boolean; + + /** Force overwrite existing files (default: false) */ + force?: boolean; +} + +/** + * Version overrides for testing or pinning specific versions. + * All fields are optional and use camelCase naming. + */ +export type VersionOverrides = Partial<{ + fresh: string; + freshTailwind: string; + freshVitePlugin: string; + preact: string; + preactSignals: string; + tailwindcss: string; + tailwindcssPostcss: string; + tailwindcssVite: string; + postcss: string; + vite: string; +}>; + +/** + * Variables available for template substitution using __VARIABLE__ syntax. + * All fields represent actual template placeholders in template files. + * + * @example + * ```ts + * const variables: TemplateVariables = { + * PROJECT_NAME: "my-app", + * FRESH_VERSION: "2.1.1", + * PREACT_VERSION: "10.27.2", + * // ... other version strings + * }; + * // In templates: __PROJECT_NAME__, __FRESH_VERSION__, etc. + * ``` + */ +export interface TemplateVariables { + PROJECT_NAME: string; + FRESH_VERSION: string; + FRESH_TAILWIND_VERSION: string; + FRESH_VITE_PLUGIN_VERSION: string; + PREACT_VERSION: string; + PREACT_SIGNALS_VERSION: string; + TAILWINDCSS_VERSION: string; + TAILWINDCSS_POSTCSS_VERSION: string; + TAILWINDCSS_VITE_VERSION: string; + POSTCSS_VERSION: string; + VITE_VERSION: string; + DENO_VERSION: string; +} diff --git a/packages/init/src/utils.ts b/packages/init/src/utils.ts new file mode 100644 index 00000000..d54265cb --- /dev/null +++ b/packages/init/src/utils.ts @@ -0,0 +1,186 @@ +import * as path from "@std/path"; +import * as fs from "@std/fs"; +import * as semver from "@std/semver"; + +/** + * Fetch the latest version of a package from JSR or npm. + */ +export async function getLatestVersion( + pkg: string, + fallback: string, +): Promise { + // In test mode, always use fallback to avoid network calls + // deno-lint-ignore no-explicit-any + if ((globalThis as any).INIT_TEST) { + return fallback; + } + + try { + // Check if it's an npm package + if (pkg.startsWith("npm:")) { + const npmPkg = pkg.slice(4); // Remove "npm:" prefix + const res = await fetch(`https://registry.npmjs.org/${npmPkg}/latest`); + if (!res.ok) { + await res.body?.cancel(); + throw new Error(`HTTP ${res.status}`); + } + + const json = await res.json() as { version: string }; + return json.version; + } + + // JSR package + const res = await fetch(`https://jsr.io/${pkg}/meta.json`); + if (!res.ok) { + await res.body?.cancel(); // Consume the body to avoid leaks + throw new Error(`HTTP ${res.status}`); + } + + const json = await res.json() as { + latest: string | null; + versions: Record; + }; + + if (json.latest !== null) { + return json.latest; + } + + const versions = Object.keys(json.versions); + if (versions.length === 0) { + throw new Error("No versions available"); + } + + versions.sort((a, b) => { + const s1 = semver.parse(a); + const s2 = semver.parse(b); + return semver.compare(s1, s2); + }); + + return versions.at(-1)!; + } catch (err) { + // Silent fallback for network or API errors + const message = err instanceof Error ? err.message : String(err); + console.error( + `Could not fetch latest ${pkg} version: ${message}. Using fallback: ${fallback}`, + ); + return fallback; + } +} + +/** + * Check if a directory exists and is empty (or only contains .git). + */ +export async function isDirectoryEmpty(dir: string): Promise { + try { + const entries = []; + for await (const entry of Deno.readDir(dir)) { + entries.push(entry); + } + return entries.length === 0 || + (entries.length === 1 && entries[0].name === ".git"); + } catch (err) { + if (err instanceof Deno.errors.NotFound) { + return true; // Directory doesn't exist, so it's "empty" + } + throw err; + } +} + +/** + * Recursively copy a directory. + */ +export async function copyDir(src: string, dest: string): Promise { + await fs.ensureDir(dest); + + for await (const entry of Deno.readDir(src)) { + const srcPath = path.join(src, entry.name); + const destPath = path.join(dest, entry.name); + + if (entry.isDirectory) { + await copyDir(srcPath, destPath); + } else { + await fs.copy(srcPath, destPath, { overwrite: true }); + } + } +} + +/** + * Substitute variables in a template string. + * Replaces __VAR__ patterns with values. + */ +export function substituteVariables( + content: string, + variables: Record, +): string { + let result = content; + + for (const [key, value] of Object.entries(variables)) { + const regex = new RegExp(`__${key}__`, "g"); + result = result.replace(regex, String(value)); + } + + return result; +} + +/** + * Convert double-underscore-prefixed filename to dot-prefixed. + * Only converts files/dirs that start with double underscore (__). + * Files with single underscore (like _app.tsx) are NOT converted. + * Examples: + * - "__gitignore" -> ".gitignore" + * - "__vscode" -> ".vscode" + * - "_app.tsx" -> "_app.tsx" (unchanged) + */ +export function processFilename(filename: string): string { + if (filename.startsWith("__")) { + return "." + filename.slice(2); + } + return filename; +} + +/** + * Get the template directory path. + */ +export function getTemplateDir(): string { + const moduleDir = path.dirname(path.fromFileUrl(import.meta.url)); + return path.join(moduleDir, "..", "assets", "template"); +} + +/** + * Get the variants directory path. + */ +export function getVariantsDir(): string { + const moduleDir = path.dirname(path.fromFileUrl(import.meta.url)); + return path.join(moduleDir, "..", "assets", "variants"); +} + +/** + * Prompt user for confirmation (or use provided value). + */ +export function confirmOrValue( + message: string, + providedValue: boolean | undefined, +): boolean { + if (providedValue !== undefined) { + return providedValue; + } + return confirm(message); +} + +/** + * Prompt user for input (or use provided value). + */ +export function promptOrValue( + message: string, + defaultValue: string, + providedValue: string | undefined, +): string { + if (providedValue !== undefined) { + return providedValue; + } + const result = prompt(message, defaultValue); + if (!result) { + throw new Error("Input required"); + } + return result; +} diff --git a/packages/init/tests/cli_test.ts b/packages/init/tests/cli_test.ts new file mode 100644 index 00000000..c979ace7 --- /dev/null +++ b/packages/init/tests/cli_test.ts @@ -0,0 +1,131 @@ +import { expect } from "@std/expect"; +import * as path from "@std/path"; + +Deno.test({ + name: "cli - shows help text", + async fn() { + const command = new Deno.Command(Deno.execPath(), { + args: [ + "run", + "-A", + path.join(import.meta.dirname!, "..", "src", "mod.ts"), + "--help", + ], + stdout: "piped", + stderr: "piped", + }); + + const { code, stdout } = await command.output(); + const output = new TextDecoder().decode(stdout); + + expect(code).toBe(0); + expect(output).toContain("@fresh/init"); + expect(output).toContain("USAGE:"); + expect(output).toContain("OPTIONS:"); + expect(output).toContain("--force"); + expect(output).toContain("--tailwind"); + expect(output).toContain("--vscode"); + expect(output).toContain("--docker"); + expect(output).toContain("--builder"); + }, + sanitizeOps: false, + sanitizeResources: false, +}); + +Deno.test({ + name: "cli - creates project with flags", + async fn() { + const tmpDir = await Deno.makeTempDir(); + const projectName = "test-cli-full"; + + try { + const command = new Deno.Command(Deno.execPath(), { + args: [ + "run", + "-A", + path.join(import.meta.dirname!, "..", "src", "mod.ts"), + projectName, + "--force", + "--tailwind", + "--vscode", + ], + cwd: tmpDir, + stdout: "piped", + stderr: "piped", + }); + + const { code, stdout } = await command.output(); + const output = new TextDecoder().decode(stdout); + + expect(code).toBe(0); + expect(output).toContain("Project initialized!"); + + // Verify project structure + const projectDir = path.join(tmpDir, projectName); + const stat = await Deno.stat(projectDir); + expect(stat.isDirectory).toBe(true); + + // Verify key files exist + await Deno.stat(path.join(projectDir, "deno.json")); + await Deno.stat(path.join(projectDir, "vite.config.ts")); + await Deno.stat(path.join(projectDir, "assets", "styles.css")); + await Deno.stat(path.join(projectDir, ".vscode", "settings.json")); + await Deno.stat(path.join(projectDir, ".vscode", "tailwind.json")); + } finally { + await Deno.remove(tmpDir, { recursive: true }); + } + }, + sanitizeOps: false, + sanitizeResources: false, +}); + +Deno.test({ + name: "cli - creates builder project", + async fn() { + const tmpDir = await Deno.makeTempDir(); + const projectName = "test-cli-builder"; + + try { + const command = new Deno.Command(Deno.execPath(), { + args: [ + "run", + "-A", + path.join(import.meta.dirname!, "..", "src", "mod.ts"), + projectName, + "--force", + "--builder", + "--docker", + ], + cwd: tmpDir, + stdout: "piped", + stderr: "piped", + stdin: "null", + env: { + "NO_COLOR": "1", // Disable prompts in test + }, + }); + + const { code } = await command.output(); + expect(code).toBe(0); + + // Verify builder project structure + const projectDir = path.join(tmpDir, projectName); + await Deno.stat(path.join(projectDir, "dev.ts")); + await Deno.stat(path.join(projectDir, "Dockerfile")); + + // Should NOT have vite files + try { + await Deno.stat(path.join(projectDir, "vite.config.ts")); + throw new Error("Should not have vite.config.ts in builder mode"); + } catch (err) { + if (!(err instanceof Deno.errors.NotFound)) { + throw err; + } + } + } finally { + await Deno.remove(tmpDir, { recursive: true }); + } + }, + sanitizeOps: false, + sanitizeResources: false, +}); diff --git a/packages/init/tests/compatibility_test.ts b/packages/init/tests/compatibility_test.ts new file mode 100644 index 00000000..fc059fa6 --- /dev/null +++ b/packages/init/tests/compatibility_test.ts @@ -0,0 +1,320 @@ +/** + * Compatibility tests that compare the output of @fresh/init v2.0.9 + * (last version before template-based refactor) with the current version + * to ensure 100% identical output for various option combinations. + */ +import { expect } from "@std/expect"; +import * as path from "@std/path"; +import * as fs from "@std/fs"; +import { stub } from "@std/testing/mock"; +import { initProject as newInitProject, resolveVersions } from "../src/init.ts"; +import { withTmpDir } from "../../fresh/src/test_utils.ts"; + +/** + * Recursively get all files in a directory with their relative paths + */ +async function getAllFiles(dir: string, baseDir = dir): Promise { + const files: string[] = []; + + for await (const entry of fs.walk(dir, { includeFiles: true })) { + if (entry.isFile) { + const relativePath = path.relative(baseDir, entry.path); + files.push(relativePath); + } + } + + return files.sort(); +} + +/** + * Compare two directories recursively, ensuring all files and contents match + */ +async function compareDirectories( + dir1: string, + dir2: string, + description: string, +): Promise { + const files1 = await getAllFiles(dir1); + const files2 = await getAllFiles(dir2); + + // Compare file lists + expect(files1).toEqual(files2); + + // Compare file contents + for (const file of files1) { + const file1Path = path.join(dir1, file); + const file2Path = path.join(dir2, file); + + let content1 = await Deno.readTextFile(file1Path); + let content2 = await Deno.readTextFile(file2Path); + + // For deno.json, normalize dependency versions to allow minor/patch differences + // The current init fetches latest Fresh version from network, which may differ + // from the version that was current when 2.0.9 was released. This is expected. + if (file === "deno.json") { + content1 = normalizeDependencyVersions(content1); + content2 = normalizeDependencyVersions(content2); + } + + if (content1 !== content2) { + console.error(`\nFile mismatch in ${description}: ${file}`); + console.error(`Version 2.0.9: ${file1Path}`); + console.error(`Current version: ${file2Path}`); + console.error("\n--- Expected (v2.0.9) ---"); + console.error(content1.slice(0, 500)); + console.error("\n--- Actual (current) ---"); + console.error(content2.slice(0, 500)); + } + + expect(content2).toBe(content1); + } +} + +/** + * Normalize dependency versions in deno.json to allow minor/patch differences. + * Replaces specific version numbers with major version only for comparison. + */ +function normalizeDependencyVersions(content: string): string { + return content + // Normalize preact signals version (2.3.x -> 2.x) + .replace( + /"npm:@preact\/signals@\^2\.\d+\.\d+"/g, + '"npm:@preact/signals@^2.x"', + ) + // Normalize preact version (10.x.x -> 10.x) + .replace(/"npm:preact@\^10\.\d+\.\d+"/g, '"npm:preact@^10.x"') + // Normalize fresh/plugin-vite version (1.0.x -> 1.0) + .replace( + /"jsr:@fresh\/plugin-vite@\^1\.0\.\d+"/g, + '"jsr:@fresh/plugin-vite@^1.0"', + ); +} + +/** + * Run the reference init script (v2.0.9) from JSR using the CLI. + * This is the last version before the template-based refactor. + */ +async function runReferenceInit( + dir: string, + projectName: string, + flags: { + docker?: boolean; + tailwind?: boolean; + vscode?: boolean; + builder?: boolean; + }, +): Promise { + const args = [ + "run", + "-A", + "jsr:@fresh/init@2.0.9", + projectName, + "--force", + ]; + + if (flags.builder) args.push("--builder"); + if (flags.tailwind) args.push("--tailwind"); + if (flags.vscode) args.push("--vscode"); + if (flags.docker) args.push("--docker"); + + const command = new Deno.Command("deno", { + args, + cwd: dir, + stdout: "null", + stderr: "null", + }); + + const { success } = await command.output(); + if (!success) { + throw new Error("Reference init script (v2.0.9) failed"); + } +} + +/** + * Test helper that runs both v2.0.9 (reference) and current init with the same + * options and compares the output to ensure backward compatibility. + */ +async function testCompatibility( + testName: string, + flags: { + docker?: boolean; + tailwind?: boolean; + vscode?: boolean; + builder?: boolean; + }, +): Promise { + // Use temporary directories for both tests + await using tmpOld = await withTmpDir(); + await using tmpNew = await withTmpDir(); + + const projectName = "test-project"; + + // Stub console.log to suppress init output + using _logs = stub(console, "log", () => undefined); + + // Stub prompt and confirm to prevent waiting for user input + using _promptStub = stub(globalThis, "prompt", () => projectName); + using _confirmStub = stub(globalThis, "confirm", () => false); + + // Run reference init script (v2.0.9) from JSR using CLI + await runReferenceInit(tmpOld.dir, projectName, flags); + + // Resolve versions to match what v2.0.9 would use (fixed versions) + const versions = await resolveVersions({ + fresh: "2.1.1", + freshTailwind: "1.0.0", + freshVitePlugin: "1.0.0", + preact: "10.27.2", + preactSignals: "2.3.1", + tailwindcss: "4.1.10", + tailwindcssPostcss: "4.1.10", + tailwindcssVite: "4.1.12", + postcss: "8.5.6", + vite: "7.1.3", + }); + + // Run current init script + await newInitProject( + tmpNew.dir, + { + directory: projectName, + builder: flags.builder ?? false, + tailwind: flags.tailwind ?? false, + vscode: flags.vscode ?? false, + docker: flags.docker ?? false, + force: true, + }, + versions, + ); + + // Compare the outputs + const oldProjectDir = path.join(tmpOld.dir, projectName); + const newProjectDir = path.join(tmpNew.dir, projectName); + await compareDirectories(oldProjectDir, newProjectDir, testName); +} + +// Test suite covering major option combinations + +Deno.test({ + name: "compatibility - default (builder, no extras)", + async fn() { + await testCompatibility("default", { + builder: true, + }); + }, + sanitizeResources: false, + sanitizeOps: false, +}); + +Deno.test({ + name: "compatibility - vite only", + async fn() { + await testCompatibility("vite", { + builder: false, + }); + }, + sanitizeResources: false, + sanitizeOps: false, +}); + +Deno.test({ + name: "compatibility - vite + tailwind", + async fn() { + await testCompatibility("vite-tailwind", { + builder: false, + tailwind: true, + }); + }, + sanitizeResources: false, + sanitizeOps: false, +}); + +Deno.test({ + name: "compatibility - builder + tailwind", + async fn() { + await testCompatibility("builder-tailwind", { + builder: true, + tailwind: true, + }); + }, + sanitizeResources: false, + sanitizeOps: false, +}); + +Deno.test({ + name: "compatibility - vite + vscode", + async fn() { + await testCompatibility("vite-vscode", { + builder: false, + vscode: true, + }); + }, + sanitizeResources: false, + sanitizeOps: false, +}); + +Deno.test({ + name: "compatibility - vite + docker", + async fn() { + await testCompatibility("vite-docker", { + builder: false, + docker: true, + }); + }, + sanitizeResources: false, + sanitizeOps: false, +}); + +Deno.test({ + name: "compatibility - vite + tailwind + vscode", + async fn() { + await testCompatibility("vite-tailwind-vscode", { + builder: false, + tailwind: true, + vscode: true, + }); + }, + sanitizeResources: false, + sanitizeOps: false, +}); + +Deno.test({ + name: "compatibility - builder + tailwind + docker", + async fn() { + await testCompatibility("builder-tailwind-docker", { + builder: true, + tailwind: true, + docker: true, + }); + }, + sanitizeResources: false, + sanitizeOps: false, +}); + +Deno.test({ + name: "compatibility - vite + all extras", + async fn() { + await testCompatibility("vite-all", { + builder: false, + tailwind: true, + vscode: true, + docker: true, + }); + }, + sanitizeResources: false, + sanitizeOps: false, +}); + +Deno.test({ + name: "compatibility - builder + all extras", + async fn() { + await testCompatibility("builder-all", { + builder: true, + tailwind: true, + vscode: true, + docker: true, + }); + }, + sanitizeResources: false, + sanitizeOps: false, +}); diff --git a/packages/init/tests/init_test.ts b/packages/init/tests/init_test.ts new file mode 100644 index 00000000..442c50d5 --- /dev/null +++ b/packages/init/tests/init_test.ts @@ -0,0 +1,249 @@ +import { expect } from "@std/expect"; +import * as path from "@std/path"; +import { withTmpDir } from "../../fresh/src/test_utils.ts"; +import { initProject, resolveVersions } from "../src/init.ts"; + +Deno.test("initProject - creates vite project with default options", async () => { + await using tmp = await withTmpDir(); + const projectDir = path.join(tmp.dir, "test-project"); + + const versions = await resolveVersions({ + fresh: "2.1.1", + preact: "10.27.2", + }); + + await initProject(tmp.dir, { + directory: "test-project", + builder: false, + tailwind: false, + vscode: false, + docker: false, + force: true, + }, versions); + + // Check that key files exist + const files = [ + "deno.json", + "vite.config.ts", + "main.ts", + "client.ts", + "utils.ts", + "README.md", + ".gitignore", + "routes/index.tsx", + "routes/_app.tsx", + "routes/api/[name].tsx", + "islands/Counter.tsx", + "components/Button.tsx", + "assets/styles.css", + "static/logo.svg", + // favicon.ico might not exist if network fails, so skip checking it + ]; + + for (const file of files) { + const filePath = path.join(projectDir, file); + const stat = await Deno.stat(filePath); + expect(stat.isFile).toBe(true); + } + + // Check that deno.json contains correct version + const denoJson = JSON.parse( + await Deno.readTextFile(path.join(projectDir, "deno.json")), + ); + expect(denoJson.imports.fresh).toContain("2.1.1"); + expect(denoJson.imports.preact).toContain("10.27.2"); + + // Check that vite.config.ts doesn't include tailwind + const viteConfig = await Deno.readTextFile( + path.join(projectDir, "vite.config.ts"), + ); + expect(viteConfig).not.toContain("tailwindcss"); + + // Check that _app.tsx has project name + const appFile = await Deno.readTextFile( + path.join(projectDir, "routes/_app.tsx"), + ); + expect(appFile).toContain("test-project"); +}); + +Deno.test("initProject - creates vite project with tailwind", async () => { + await using tmp = await withTmpDir(); + const projectDir = path.join(tmp.dir, "test-tailwind"); + + const versions = await resolveVersions({ fresh: "2.1.1" }); + + await initProject(tmp.dir, { + directory: "test-tailwind", + builder: false, + tailwind: true, + vscode: false, + docker: false, + force: true, + }, versions); + + // Check vite.config.ts includes tailwind + const viteConfig = await Deno.readTextFile( + path.join(projectDir, "vite.config.ts"), + ); + expect(viteConfig).toContain("tailwindcss"); + expect(viteConfig).toContain("@tailwindcss/vite"); + + // Check deno.json includes tailwind + const denoJson = JSON.parse( + await Deno.readTextFile(path.join(projectDir, "deno.json")), + ); + expect(denoJson.imports.tailwindcss).toBeTruthy(); + expect(denoJson.imports["@tailwindcss/vite"]).toBeTruthy(); + + // Check styles.css uses @import + const styles = await Deno.readTextFile( + path.join(projectDir, "assets/styles.css"), + ); + expect(styles).toContain("@import"); +}); + +Deno.test("initProject - creates builder project", async () => { + await using tmp = await withTmpDir(); + const projectDir = path.join(tmp.dir, "test-builder"); + + const versions = await resolveVersions({ fresh: "2.1.1" }); + + await initProject(tmp.dir, { + directory: "test-builder", + builder: true, + tailwind: false, + vscode: false, + docker: false, + force: true, + }, versions); + + // Check that dev.ts exists (not vite.config.ts) + const devTsPath = path.join(projectDir, "dev.ts"); + const vitePath = path.join(projectDir, "vite.config.ts"); + + const devStat = await Deno.stat(devTsPath); + expect(devStat.isFile).toBe(true); + + try { + await Deno.stat(vitePath); + throw new Error("vite.config.ts should not exist in builder mode"); + } catch (err) { + expect(err).toBeInstanceOf(Deno.errors.NotFound); + } + + // Check that static/styles.css exists (not assets/) + const stylesPath = path.join(projectDir, "static/styles.css"); + const stylesStat = await Deno.stat(stylesPath); + expect(stylesStat.isFile).toBe(true); + + // Check that _app.tsx has link to styles.css + const appFile = await Deno.readTextFile( + path.join(projectDir, "routes/_app.tsx"), + ); + expect(appFile).toContain('href="/styles.css"'); +}); + +Deno.test("initProject - creates project with vscode settings", async () => { + await using tmp = await withTmpDir(); + const projectDir = path.join(tmp.dir, "test-vscode"); + + const versions = await resolveVersions({ fresh: "2.1.1" }); + + await initProject(tmp.dir, { + directory: "test-vscode", + builder: false, + tailwind: false, + vscode: true, + docker: false, + force: true, + }, versions); + + // Check VS Code files exist + const vscodeFiles = [ + ".vscode/settings.json", + ".vscode/extensions.json", + ]; + + for (const file of vscodeFiles) { + const filePath = path.join(projectDir, file); + const stat = await Deno.stat(filePath); + expect(stat.isFile).toBe(true); + } + + // Check settings.json content + const settings = JSON.parse( + await Deno.readTextFile(path.join(projectDir, ".vscode/settings.json")), + ); + expect(settings["deno.enable"]).toBe(true); + expect(settings["deno.lint"]).toBe(true); + + // Check extensions.json content + const extensions = JSON.parse( + await Deno.readTextFile( + path.join(projectDir, ".vscode/extensions.json"), + ), + ); + expect(extensions.recommendations).toContain("denoland.vscode-deno"); +}); + +Deno.test("initProject - creates project with docker", async () => { + await using tmp = await withTmpDir(); + const projectDir = path.join(tmp.dir, "test-docker"); + + const versions = await resolveVersions({ fresh: "2.1.1" }); + + await initProject(tmp.dir, { + directory: "test-docker", + builder: false, + tailwind: false, + vscode: false, + docker: true, + force: true, + }, versions); + + // Check Dockerfile exists + const dockerfilePath = path.join(projectDir, "Dockerfile"); + const dockerStat = await Deno.stat(dockerfilePath); + expect(dockerStat.isFile).toBe(true); + + // Check Dockerfile content + const dockerfile = await Deno.readTextFile(dockerfilePath); + expect(dockerfile).toContain("FROM denoland/deno"); + expect(dockerfile).toContain("EXPOSE 8000"); +}); + +Deno.test( + "initProject - creates tailwind.json when vscode + tailwind", + async () => { + await using tmp = await withTmpDir(); + const projectDir = path.join(tmp.dir, "test-vscode-tailwind"); + + const versions = await resolveVersions({ fresh: "2.1.1" }); + + await initProject(tmp.dir, { + directory: "test-vscode-tailwind", + builder: false, + tailwind: true, + vscode: true, + docker: false, + force: true, + }, versions); + + // Check .vscode/tailwind.json exists + const tailwindJsonPath = path.join( + projectDir, + ".vscode/tailwind.json", + ); + const tailwindStat = await Deno.stat(tailwindJsonPath); + expect(tailwindStat.isFile).toBe(true); + + // Check tailwind.json content + const tailwindJson = JSON.parse( + await Deno.readTextFile(tailwindJsonPath), + ); + expect(tailwindJson.version).toBe(1.1); + expect(tailwindJson.atDirectives).toBeTruthy(); + expect(tailwindJson.atDirectives.length).toBeGreaterThan(0); + expect(tailwindJson.atDirectives[0].name).toBe("@tailwind"); + }, +); diff --git a/packages/init/tests/integration_test.ts b/packages/init/tests/integration_test.ts new file mode 100644 index 00000000..069d53d7 --- /dev/null +++ b/packages/init/tests/integration_test.ts @@ -0,0 +1,273 @@ +import { expect } from "@std/expect"; +import * as path from "@std/path"; +import { initProject, resolveVersions } from "../src/init.ts"; +import { withTmpDir } from "../../fresh/src/test_utils.ts"; +import { withChildProcessServer } from "../../fresh/tests/test_utils.tsx"; + +/** + * Integration tests for validating generated projects. + * + * These tests generate complete projects and verify they work correctly: + * - Project files are valid and can be checked with `deno task check` + * - Development server starts successfully with `deno task dev` + * - Production build completes with `deno task build` + * + * Note: These tests are more extensive and slower than unit tests. + * They should be run less frequently, perhaps in CI or before releases. + */ + +// Helper to run a command in a directory and check its exit code +async function runCommand( + dir: string, + cmd: string[], +): Promise<{ success: boolean; output: string }> { + const command = new Deno.Command(cmd[0], { + args: cmd.slice(1), + cwd: dir, + stdout: "piped", + stderr: "piped", + }); + + const { code, stdout, stderr } = await command.output(); + const output = new TextDecoder().decode(stdout) + + new TextDecoder().decode(stderr); + + return { success: code === 0, output }; +} + +// Helper to initialize a project with resolved versions (for tests) +async function initTestProject( + cwd: string, + directory: string, + builder: boolean, + tailwind: boolean, +) { + const versions = await resolveVersions({ fresh: "2.1.1" }); + await initProject(cwd, { + directory, + builder, + tailwind, + vscode: false, + docker: false, + force: true, + }, versions); +} + +Deno.test({ + name: "integration - vite project passes check", + ignore: false, + async fn() { + await using tmp = await withTmpDir(); + const projectDir = path.join(tmp.dir, "test-vite-check"); + + await initTestProject(tmp.dir, "test-vite-check", false, false); + + const { success, output } = await runCommand( + projectDir, + ["deno", "task", "check"], + ); + + expect(success, `Check failed: ${output}`).toBe(true); + }, + sanitizeOps: false, + sanitizeResources: false, +}); + +Deno.test({ + name: "integration - builder project passes check", + ignore: false, + async fn() { + await using tmp = await withTmpDir(); + const projectDir = path.join(tmp.dir, "test-builder-check"); + + await initTestProject(tmp.dir, "test-builder-check", true, false); + + const { success, output } = await runCommand( + projectDir, + ["deno", "task", "check"], + ); + + expect(success, `Check failed: ${output}`).toBe(true); + }, + sanitizeOps: false, + sanitizeResources: false, +}); + +Deno.test({ + name: "integration - vite with tailwind passes check", + ignore: false, + async fn() { + await using tmp = await withTmpDir(); + const projectDir = path.join(tmp.dir, "test-vite-tailwind-check"); + + await initTestProject(tmp.dir, "test-vite-tailwind-check", false, true); + + const { success, output } = await runCommand( + projectDir, + ["deno", "task", "check"], + ); + + expect(success, `Check failed: ${output}`).toBe(true); + }, + sanitizeOps: false, + sanitizeResources: false, +}); + +Deno.test({ + name: "integration - vite project can build", + ignore: false, + async fn() { + await using tmp = await withTmpDir(); + const projectDir = path.join(tmp.dir, "test-vite-build"); + + await initTestProject(tmp.dir, "test-vite-build", false, false); + + // Install dependencies first + await runCommand(projectDir, ["deno", "install"]); + + const { success, output } = await runCommand( + projectDir, + ["deno", "task", "build"], + ); + + expect(success, `Build failed: ${output}`).toBe(true); + + // Check that _fresh directory was created + const freshDir = path.join(projectDir, "_fresh"); + const stat = await Deno.stat(freshDir); + expect(stat.isDirectory).toBe(true); + }, + sanitizeOps: false, + sanitizeResources: false, +}); + +Deno.test({ + name: "integration - builder project can build", + ignore: false, + async fn() { + await using tmp = await withTmpDir(); + const projectDir = path.join(tmp.dir, "test-builder-build"); + + await initTestProject(tmp.dir, "test-builder-build", true, false); + + const { success, output } = await runCommand( + projectDir, + ["deno", "task", "build"], + ); + + expect(success, `Build failed: ${output}`).toBe(true); + + // Check that _fresh directory was created + const freshDir = path.join(projectDir, "_fresh"); + const stat = await Deno.stat(freshDir); + expect(stat.isDirectory).toBe(true); + }, + sanitizeOps: false, + sanitizeResources: false, +}); + +Deno.test({ + name: "integration - vite dev server works", + ignore: false, + async fn() { + await using tmp = await withTmpDir(); + const projectDir = path.join(tmp.dir, "test-dev-server"); + + await initTestProject(tmp.dir, "test-dev-server", false, false); + + // Start dev server and verify it works + await withChildProcessServer( + { + cwd: projectDir, + args: ["task", "dev"], + }, + async (address) => { + // Verify the home page responds with correct content + const res = await fetch(address); + expect(res.status).toBe(200); + + const html = await res.text(); + // Check for Fresh welcome message + expect( + html, + "Fresh welcome message should appear", + ).toContain("Welcome to Fresh"); + // Check for counter buttons (verifies island is rendered) + expect( + html, + "Counter buttons should be present", + ).toContain('id="increment"'); + expect( + html, + "Counter buttons should be present", + ).toContain('id="decrement"'); + // Check for logo + expect( + html, + "Fresh logo should be present", + ).toContain("logo.svg"); + + // Test the API route + const apiRes = await fetch(`${address}/api/fresh`); + expect(apiRes.status).toBe(200); + const greeting = await apiRes.text(); + expect(greeting, "API should return greeting").toBe("Hello, Fresh!"); + }, + ); + }, + sanitizeOps: false, + sanitizeResources: false, +}); + +Deno.test({ + name: "integration - builder dev server works", + ignore: false, + async fn() { + await using tmp = await withTmpDir(); + const projectDir = path.join(tmp.dir, "test-builder-dev"); + + await initTestProject(tmp.dir, "test-builder-dev", true, false); + + // Start dev server and verify it works + await withChildProcessServer( + { + cwd: projectDir, + args: ["task", "dev"], + }, + async (address) => { + // Verify the home page responds with correct content + const res = await fetch(address); + expect(res.status).toBe(200); + + const html = await res.text(); + // Check for Fresh welcome message + expect( + html, + "Fresh welcome message should appear", + ).toContain("Welcome to Fresh"); + // Check for counter buttons (verifies island is rendered) + expect( + html, + "Counter buttons should be present", + ).toContain('id="increment"'); + expect( + html, + "Counter buttons should be present", + ).toContain('id="decrement"'); + // Check for logo + expect( + html, + "Fresh logo should be present", + ).toContain("logo.svg"); + + // Test the API route + const apiRes = await fetch(`${address}/api/fresh`); + expect(apiRes.status).toBe(200); + const greeting = await apiRes.text(); + expect(greeting, "API should return greeting").toBe("Hello, Fresh!"); + }, + ); + }, + sanitizeOps: false, + sanitizeResources: false, +}); diff --git a/packages/init/tests/sync_test.ts b/packages/init/tests/sync_test.ts new file mode 100644 index 00000000..da81e0da --- /dev/null +++ b/packages/init/tests/sync_test.ts @@ -0,0 +1,379 @@ +import { expect } from "@std/expect"; +import * as path from "@std/path"; +import * as fs from "@std/fs"; + +/** + * Helper to create a temporary directory structure for testing + */ +async function createTestStructure(baseDir: string): Promise { + // Create base template structure + const baseVite = path.join(baseDir, "assets/base/vite"); + const baseBuilder = path.join(baseDir, "assets/base/builder"); + + await fs.ensureDir(path.join(baseVite, "components")); + await fs.ensureDir(path.join(baseVite, "routes")); + await fs.ensureDir(path.join(baseBuilder, "components")); + await fs.ensureDir(path.join(baseBuilder, "static")); + + // Create common files + await Deno.writeTextFile( + path.join(baseVite, "main.ts"), + "export const app = new App();", + ); + await Deno.writeTextFile( + path.join(baseVite, "components/Button.tsx"), + "export function Button() {}", + ); + await Deno.writeTextFile( + path.join(baseVite, "routes/index.tsx"), + "export default function Home() {}", + ); + + await Deno.writeTextFile( + path.join(baseBuilder, "main.ts"), + "export const app = new App();", + ); + await Deno.writeTextFile( + path.join(baseBuilder, "components/Button.tsx"), + "export function Button() {}", + ); + + // Create template directories + const templateVite = path.join(baseDir, "assets/template/vite"); + const templateViteTailwind = path.join( + baseDir, + "assets/template/vite-tailwind", + ); + const templateBuilder = path.join(baseDir, "assets/template/builder"); + const templateBuilderTailwind = path.join( + baseDir, + "assets/template/builder-tailwind", + ); + + await fs.ensureDir(templateVite); + await fs.ensureDir(templateViteTailwind); + await fs.ensureDir(templateBuilder); + await fs.ensureDir(templateBuilderTailwind); + + // Create template-specific files + await Deno.writeTextFile( + path.join(templateVite, "deno.json.tmpl"), + '{"imports": {"vite": "npm:vite"}}', + ); + await Deno.writeTextFile( + path.join(templateViteTailwind, "deno.json.tmpl"), + '{"imports": {"vite": "npm:vite", "tailwind": "npm:tailwindcss"}}', + ); + await Deno.writeTextFile( + path.join(templateVite, "vite.config.ts"), + "export default { plugins: [] }", + ); + await Deno.writeTextFile( + path.join(templateViteTailwind, "vite.config.ts"), + "export default { plugins: [tailwind()] }", + ); + + await fs.ensureDir(path.join(templateVite, "assets")); + await fs.ensureDir(path.join(templateViteTailwind, "assets")); + await Deno.writeTextFile( + path.join(templateVite, "assets/styles.css"), + ".fresh { color: blue; }", + ); + await Deno.writeTextFile( + path.join(templateViteTailwind, "assets/styles.css"), + "@import 'tailwindcss';", + ); + + await fs.ensureDir(path.join(templateBuilder, "static")); + await fs.ensureDir(path.join(templateBuilderTailwind, "static")); + await Deno.writeTextFile( + path.join(templateBuilder, "static/styles.css"), + ".fresh { color: blue; }", + ); + await Deno.writeTextFile( + path.join(templateBuilderTailwind, "static/styles.css"), + "@import 'tailwindcss';", + ); +} + +/** + * Test that isTemplateSpecific correctly identifies template-specific files + */ +Deno.test("isTemplateSpecific - identifies template-specific files", () => { + // Import the function from the script + const TEMPLATE_SPECIFIC_FILES = [ + "deno.json.tmpl", + "deno.json", + "vite.config.ts", + "assets/styles.css", + "static/styles.css", + ]; + + function isTemplateSpecific(relPath: string): boolean { + return TEMPLATE_SPECIFIC_FILES.some((specific) => + relPath === specific || relPath.endsWith(`/${specific}`) + ); + } + + // Should return true for template-specific files + expect(isTemplateSpecific("deno.json.tmpl")).toBe(true); + expect(isTemplateSpecific("vite.config.ts")).toBe(true); + expect(isTemplateSpecific("assets/styles.css")).toBe(true); + expect(isTemplateSpecific("static/styles.css")).toBe(true); + expect(isTemplateSpecific("path/to/deno.json.tmpl")).toBe(true); + + // Should return false for common files + expect(isTemplateSpecific("main.ts")).toBe(false); + expect(isTemplateSpecific("components/Button.tsx")).toBe(false); + expect(isTemplateSpecific("routes/index.tsx")).toBe(false); + expect(isTemplateSpecific("README.md")).toBe(false); +}); + +/** + * Test sync in dry-run mode + */ +Deno.test("sync_templates - dry run does not modify files", async () => { + const tmpDir = await Deno.makeTempDir(); + + try { + await createTestStructure(tmpDir); + + // Get path to src/sync.ts relative to this test file + const syncScriptPath = path.join( + path.dirname(path.fromFileUrl(import.meta.url)), + "../src/sync.ts", + ); + + // Run sync in dry-run mode + const process = new Deno.Command("deno", { + args: [ + "run", + "-A", + syncScriptPath, + "--dry-run", + ], + cwd: tmpDir, + stdout: "piped", + stderr: "piped", + }); + + const { code, stdout } = await process.output(); + const output = new TextDecoder().decode(stdout); + + expect(code).toBe(0); + expect(output).toContain("DRY RUN MODE"); + expect(output).toContain("would be copied"); + + // Verify templates are still empty (dry run didn't copy) + const viteMain = path.join(tmpDir, "assets/template/vite/main.ts"); + const exists = await fs.exists(viteMain); + expect(exists).toBe(false); + } finally { + await Deno.remove(tmpDir, { recursive: true }); + } +}); + +/** + * Test actual sync operation + */ +Deno.test("sync_templates - syncs common files correctly", async () => { + const tmpDir = await Deno.makeTempDir(); + + try { + await createTestStructure(tmpDir); + + // Get path to src/sync.ts relative to this test file + const syncScriptPath = path.join( + path.dirname(path.fromFileUrl(import.meta.url)), + "../src/sync.ts", + ); + + // Run actual sync + const process = new Deno.Command("deno", { + args: [ + "run", + "-A", + syncScriptPath, + ], + cwd: tmpDir, + stdout: "piped", + stderr: "piped", + }); + + const { code, stdout } = await process.output(); + const output = new TextDecoder().decode(stdout); + + expect(code).toBe(0); + expect(output).toContain("Sync complete"); + + // Verify common files were copied + const viteMain = path.join(tmpDir, "assets/template/vite/main.ts"); + const viteButton = path.join( + tmpDir, + "assets/template/vite/components/Button.tsx", + ); + const viteTailwindMain = path.join( + tmpDir, + "assets/template/vite-tailwind/main.ts", + ); + + expect(await fs.exists(viteMain)).toBe(true); + expect(await fs.exists(viteButton)).toBe(true); + expect(await fs.exists(viteTailwindMain)).toBe(true); + + // Verify content is correct + const mainContent = await Deno.readTextFile(viteMain); + expect(mainContent).toBe("export const app = new App();"); + + // Verify template-specific files were NOT overwritten + const viteDeno = path.join(tmpDir, "assets/template/vite/deno.json.tmpl"); + const viteConfig = path.join(tmpDir, "assets/template/vite/vite.config.ts"); + const viteStyles = path.join( + tmpDir, + "assets/template/vite/assets/styles.css", + ); + + const denoContent = await Deno.readTextFile(viteDeno); + const configContent = await Deno.readTextFile(viteConfig); + const stylesContent = await Deno.readTextFile(viteStyles); + + expect(denoContent).toBe('{"imports": {"vite": "npm:vite"}}'); + expect(configContent).toBe("export default { plugins: [] }"); + expect(stylesContent).toBe(".fresh { color: blue; }"); + + // Verify tailwind variant has different template-specific files + const viteTailwindDeno = path.join( + tmpDir, + "assets/template/vite-tailwind/deno.json.tmpl", + ); + const viteTailwindConfig = path.join( + tmpDir, + "assets/template/vite-tailwind/vite.config.ts", + ); + const viteTailwindStyles = path.join( + tmpDir, + "assets/template/vite-tailwind/assets/styles.css", + ); + + const tailwindDenoContent = await Deno.readTextFile(viteTailwindDeno); + const tailwindConfigContent = await Deno.readTextFile(viteTailwindConfig); + const tailwindStylesContent = await Deno.readTextFile(viteTailwindStyles); + + expect(tailwindDenoContent).toBe( + '{"imports": {"vite": "npm:vite", "tailwind": "npm:tailwindcss"}}', + ); + expect(tailwindConfigContent).toBe( + "export default { plugins: [tailwind()] }", + ); + expect(tailwindStylesContent).toBe("@import 'tailwindcss';"); + } finally { + await Deno.remove(tmpDir, { recursive: true }); + } +}); + +/** + * Test that sync handles builder templates correctly + */ +Deno.test("sync_templates - syncs builder templates", async () => { + const tmpDir = await Deno.makeTempDir(); + + try { + await createTestStructure(tmpDir); + + // Get path to src/sync.ts relative to this test file + const syncScriptPath = path.join( + path.dirname(path.fromFileUrl(import.meta.url)), + "../src/sync.ts", + ); + + // Run sync + const process = new Deno.Command("deno", { + args: [ + "run", + "-A", + syncScriptPath, + ], + cwd: tmpDir, + stdout: "piped", + stderr: "piped", + }); + + const { code } = await process.output(); + expect(code).toBe(0); + + // Verify builder files were copied + const builderMain = path.join(tmpDir, "assets/template/builder/main.ts"); + const builderButton = path.join( + tmpDir, + "assets/template/builder/components/Button.tsx", + ); + const builderTailwindMain = path.join( + tmpDir, + "assets/template/builder-tailwind/main.ts", + ); + + expect(await fs.exists(builderMain)).toBe(true); + expect(await fs.exists(builderButton)).toBe(true); + expect(await fs.exists(builderTailwindMain)).toBe(true); + + // Verify template-specific files were preserved + const builderStyles = path.join( + tmpDir, + "assets/template/builder/static/styles.css", + ); + const builderTailwindStyles = path.join( + tmpDir, + "assets/template/builder-tailwind/static/styles.css", + ); + + const stylesContent = await Deno.readTextFile(builderStyles); + const tailwindStylesContent = await Deno.readTextFile( + builderTailwindStyles, + ); + + expect(stylesContent).toBe(".fresh { color: blue; }"); + expect(tailwindStylesContent).toBe("@import 'tailwindcss';"); + } finally { + await Deno.remove(tmpDir, { recursive: true }); + } +}); + +/** + * Test error handling when base directory doesn't exist + */ +Deno.test("sync_templates - handles missing base directory", async () => { + const tmpDir = await Deno.makeTempDir(); + + try { + // Create only template directories, not base + await fs.ensureDir(path.join(tmpDir, "assets/template/vite")); + await fs.ensureDir(path.join(tmpDir, "assets/template/vite-tailwind")); + + // Get path to src/sync.ts relative to this test file + const syncScriptPath = path.join( + path.dirname(path.fromFileUrl(import.meta.url)), + "../src/sync.ts", + ); + + // Run sync (should handle missing base gracefully) + const process = new Deno.Command("deno", { + args: [ + "run", + "-A", + syncScriptPath, + ], + cwd: tmpDir, + stdout: "piped", + stderr: "piped", + }); + + const { code, stdout } = await process.output(); + const output = new TextDecoder().decode(stdout); + + // Should complete but report errors + expect(code).toBe(0); + expect(output).toContain("error"); + } finally { + await Deno.remove(tmpDir, { recursive: true }); + } +}); diff --git a/packages/init/tests/template_test.ts b/packages/init/tests/template_test.ts new file mode 100644 index 00000000..e6cca3f3 --- /dev/null +++ b/packages/init/tests/template_test.ts @@ -0,0 +1,219 @@ +import { expect } from "@std/expect"; +import * as path from "@std/path"; +import { getTemplateDir, getVariantsDir } from "../src/utils.ts"; + +Deno.test("vite - has all required files", async () => { + const templateDir = path.join(getTemplateDir(), "vite"); + + const requiredFiles = [ + "__gitignore", + "README.md", + "deno.json", + "vite.config.ts", + "main.ts", + "client.ts", + "utils.ts", + "assets/styles.css", + "components/Button.tsx", + "islands/Counter.tsx", + "routes/index.tsx", + "routes/_app.tsx", + "routes/api/[name].tsx", + "static/logo.svg", + ]; + + for (const file of requiredFiles) { + const filePath = path.join(templateDir, file); + const stat = await Deno.stat(filePath); + expect(stat).toBeTruthy(); + expect(stat.isFile).toBe(true); + } +}); + +Deno.test("vite-tailwind - has all required files", async () => { + const templateDir = path.join(getTemplateDir(), "vite-tailwind"); + + const requiredFiles = [ + "__gitignore", + "README.md", + "deno.json", + "vite.config.ts", + "main.ts", + "client.ts", + "utils.ts", + "assets/styles.css", + "components/Button.tsx", + "islands/Counter.tsx", + "routes/index.tsx", + "routes/_app.tsx", + "routes/api/[name].tsx", + "static/logo.svg", + ]; + + for (const file of requiredFiles) { + const filePath = path.join(templateDir, file); + const stat = await Deno.stat(filePath); + expect(stat).toBeTruthy(); + expect(stat.isFile).toBe(true); + } +}); + +Deno.test("builder - has all required files", async () => { + const templateDir = path.join(getTemplateDir(), "builder"); + + const requiredFiles = [ + "__gitignore", + "README.md", + "deno.json", + "dev.ts", + "main.ts", + "utils.ts", + "components/Button.tsx", + "islands/Counter.tsx", + "routes/index.tsx", + "routes/_app.tsx", + "routes/api/[name].tsx", + "static/styles.css", + "static/logo.svg", + ]; + + for (const file of requiredFiles) { + const filePath = path.join(templateDir, file); + const stat = await Deno.stat(filePath); + expect(stat).toBeTruthy(); + expect(stat.isFile).toBe(true); + } +}); + +Deno.test("builder-tailwind - has all required files", async () => { + const templateDir = path.join(getTemplateDir(), "builder-tailwind"); + + const requiredFiles = [ + "__gitignore", + "README.md", + "deno.json", + "dev.ts", + "main.ts", + "utils.ts", + "components/Button.tsx", + "islands/Counter.tsx", + "routes/index.tsx", + "routes/_app.tsx", + "routes/api/[name].tsx", + "static/styles.css", + "static/logo.svg", + ]; + + for (const file of requiredFiles) { + const filePath = path.join(templateDir, file); + const stat = await Deno.stat(filePath); + expect(stat).toBeTruthy(); + expect(stat.isFile).toBe(true); + } +}); + +Deno.test("vite deno.json - contains template variables", async () => { + const templateDir = path.join(getTemplateDir(), "vite"); + const denoJsonPath = path.join(templateDir, "deno.json"); + const content = await Deno.readTextFile(denoJsonPath); + + expect(content).toContain("__FRESH_VERSION__"); + expect(content).toContain("__PREACT_VERSION__"); + expect(content).toContain("__PREACT_SIGNALS_VERSION__"); + expect(content).toContain("__VITE_VERSION__"); +}); + +Deno.test("vite-tailwind deno.json - contains Tailwind dependencies", async () => { + const templateDir = path.join(getTemplateDir(), "vite-tailwind"); + const denoJsonPath = path.join(templateDir, "deno.json"); + const content = await Deno.readTextFile(denoJsonPath); + + expect(content).toContain("__TAILWINDCSS_VERSION__"); + expect(content).toContain("__TAILWINDCSS_VITE_VERSION__"); +}); + +Deno.test("vite-tailwind vite.config.ts - imports Tailwind", async () => { + const templateDir = path.join(getTemplateDir(), "vite-tailwind"); + const configPath = path.join(templateDir, "vite.config.ts"); + const content = await Deno.readTextFile(configPath); + + expect(content).toContain("@tailwindcss/vite"); + expect(content).toContain("tailwindcss()"); +}); + +Deno.test("vite-tailwind assets/styles.css - uses Tailwind", async () => { + const templateDir = path.join(getTemplateDir(), "vite-tailwind"); + const cssPath = path.join(templateDir, "assets/styles.css"); + const content = await Deno.readTextFile(cssPath); + + expect(content).toContain('@import "tailwindcss"'); +}); + +Deno.test("builder-tailwind deno.json - contains Tailwind dependencies", async () => { + const templateDir = path.join(getTemplateDir(), "builder-tailwind"); + const denoJsonPath = path.join(templateDir, "deno.json"); + const content = await Deno.readTextFile(denoJsonPath); + + expect(content).toContain("__TAILWINDCSS_VERSION__"); + expect(content).toContain("__FRESH_TAILWIND_VERSION__"); +}); + +Deno.test("builder-tailwind static/styles.css - uses Tailwind", async () => { + const templateDir = path.join(getTemplateDir(), "builder-tailwind"); + const cssPath = path.join(templateDir, "static/styles.css"); + const content = await Deno.readTextFile(cssPath); + + expect(content).toContain('@import "tailwindcss"'); +}); + +Deno.test("vite _app.tsx - contains PROJECT_NAME variable", async () => { + const templateDir = path.join(getTemplateDir(), "vite"); + const appPath = path.join(templateDir, "routes/_app.tsx"); + const content = await Deno.readTextFile(appPath); + + expect(content).toContain("__PROJECT_NAME__"); +}); + +Deno.test("variants/docker - has Dockerfile", async () => { + const variantDir = path.join(getVariantsDir(), "docker"); + const dockerfilePath = path.join(variantDir, "Dockerfile"); + + const stat = await Deno.stat(dockerfilePath); + expect(stat).toBeTruthy(); + expect(stat.isFile).toBe(true); + + const content = await Deno.readTextFile(dockerfilePath); + expect(content).toContain("__DENO_VERSION__"); +}); + +Deno.test("variants/vscode - has required files", async () => { + const variantDir = path.join(getVariantsDir(), "vscode"); + + const requiredFiles = [ + "__vscode/settings.json", + "__vscode/extensions.json", + ]; + + for (const file of requiredFiles) { + const filePath = path.join(variantDir, file); + const stat = await Deno.stat(filePath); + expect(stat).toBeTruthy(); + expect(stat.isFile).toBe(true); + } +}); + +Deno.test("variants/vscode-tailwind - has tailwind.json", async () => { + const variantDir = path.join(getVariantsDir(), "vscode-tailwind"); + const tailwindJsonPath = path.join(variantDir, "__vscode/tailwind.json"); + + const stat = await Deno.stat(tailwindJsonPath); + expect(stat).toBeTruthy(); + expect(stat.isFile).toBe(true); + + // Check content + const content = JSON.parse(await Deno.readTextFile(tailwindJsonPath)); + expect(content.version).toBe(1.1); + expect(content.atDirectives).toBeTruthy(); + expect(content.atDirectives.length).toBeGreaterThan(0); + expect(content.atDirectives[0].name).toBe("@tailwind"); +}); diff --git a/packages/init/tests/utils_test.ts b/packages/init/tests/utils_test.ts new file mode 100644 index 00000000..2ef43f62 --- /dev/null +++ b/packages/init/tests/utils_test.ts @@ -0,0 +1,82 @@ +import { expect } from "@std/expect"; +import { + getLatestVersion, + isDirectoryEmpty, + processFilename, + substituteVariables, +} from "../src/utils.ts"; + +Deno.test("processFilename - converts double underscore prefix to dot", () => { + expect(processFilename("__gitignore")).toBe(".gitignore"); + expect(processFilename("__vscode")).toBe(".vscode"); + expect(processFilename("_app.tsx")).toBe("_app.tsx"); + expect(processFilename("regular-file.ts")).toBe("regular-file.ts"); +}); + +Deno.test("substituteVariables - replaces template variables", () => { + const template = "Hello __NAME__, version __VERSION__!"; + const variables = { NAME: "Fresh", VERSION: "2.0.0" }; + const result = substituteVariables(template, variables); + expect(result).toBe("Hello Fresh, version 2.0.0!"); +}); + +Deno.test("substituteVariables - handles multiple occurrences", () => { + const template = "__X__ + __X__ = __Y__"; + const variables = { X: "1", Y: "2" }; + const result = substituteVariables(template, variables); + expect(result).toBe("1 + 1 = 2"); +}); + +Deno.test("substituteVariables - handles boolean values", () => { + const template = "Enabled: __ENABLED__"; + const variables = { ENABLED: true }; + const result = substituteVariables(template, variables); + expect(result).toBe("Enabled: true"); +}); + +Deno.test("isDirectoryEmpty - returns true for non-existent directory", async () => { + const isEmpty = await isDirectoryEmpty("/non/existent/path"); + expect(isEmpty).toBe(true); +}); + +Deno.test("isDirectoryEmpty - returns false for directory with files", async () => { + const tempDir = await Deno.makeTempDir(); + await Deno.writeTextFile(`${tempDir}/test.txt`, "test"); + + const isEmpty = await isDirectoryEmpty(tempDir); + expect(isEmpty).toBe(false); + + await Deno.remove(tempDir, { recursive: true }); +}); + +Deno.test("isDirectoryEmpty - returns true for empty directory", async () => { + const tempDir = await Deno.makeTempDir(); + + const isEmpty = await isDirectoryEmpty(tempDir); + expect(isEmpty).toBe(true); + + await Deno.remove(tempDir); +}); + +Deno.test("isDirectoryEmpty - returns true for directory with only .git", async () => { + const tempDir = await Deno.makeTempDir(); + await Deno.mkdir(`${tempDir}/.git`); + + const isEmpty = await isDirectoryEmpty(tempDir); + expect(isEmpty).toBe(true); + + await Deno.remove(tempDir, { recursive: true }); +}); + +Deno.test("getLatestVersion - returns fallback on error", async () => { + const version = await getLatestVersion("@nonexistent/package", "1.0.0"); + expect(version).toBe("1.0.0"); +}); + +Deno.test("getLatestVersion - fetches real version", async () => { + // This test requires network access + const version = await getLatestVersion("@std/assert", "0.0.1"); + expect(version).toBeTruthy(); + // Should return something other than fallback + // (unless there's a network error, in which case it returns fallback) +});