diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 05ab139..914dd9e 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -15,6 +15,8 @@ updates: update-types: - "version-update:semver-major" - "version-update:semver-minor" + - dependency-name: "@types/node" + update-types: ["version-update:semver-major"] - package-ecosystem: github-actions directory: / diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8497059..418132c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -15,9 +15,17 @@ permissions: jobs: scaffold: - name: Scaffold and check a project + name: Scaffold and check a project (${{ matrix.variant }}) runs-on: ubuntu-latest timeout-minutes: 20 + strategy: + fail-fast: false + matrix: + include: + - variant: web only + desktop: "no" + - variant: with the desktop app + desktop: "yes" steps: - uses: actions/checkout@v7 - uses: actions/setup-node@v7 @@ -32,9 +40,14 @@ jobs: - name: Generate a project the way npx does env: PACKAGE: github:${{ github.repository }}#${{ github.event.pull_request.head.sha || github.sha }} - run: npx --yes "$PACKAGE" "Demo App" --description "A project generated in CI." + run: printf '%s\n' "Demo App" "A project generated in CI." "" "${{ matrix.desktop }}" | npx --yes --allow-git=all "$PACKAGE" - name: Check that no placeholder survived run: "! grep -rIiE 'b7[-_ ]?stack' demo-app --exclude-dir=node_modules --exclude-dir=.git" + - name: Check that no template marker survived + run: "! grep -rIE '(desktop|web-only):(start|end)' demo-app --exclude-dir=node_modules --exclude-dir=.git" + - name: Check that nothing of the desktop app was copied + if: ${{ matrix.desktop == 'no' }} + run: "! grep -rIi 'desktop' demo-app --exclude-dir=node_modules --exclude-dir=.git" - name: Preflight the project run: npm run preflight working-directory: demo-app diff --git a/.gitignore b/.gitignore index 70f5e1c..a5d2fcf 100644 --- a/.gitignore +++ b/.gitignore @@ -4,6 +4,8 @@ node_modules !.env.template .next/ +.vite/ +out/ coverage/ dist/ *.tsbuildinfo diff --git a/.husky/pre-commit b/.husky/pre-commit index 067775c..c27d889 100755 --- a/.husky/pre-commit +++ b/.husky/pre-commit @@ -1,4 +1 @@ -lint-staged || { - printf '\nSkip the hook once with: git commit --no-verify\n' >&2 - exit 1 -} +lint-staged diff --git a/.prettierignore b/.prettierignore index a3d8278..24f34d9 100644 --- a/.prettierignore +++ b/.prettierignore @@ -1,4 +1,5 @@ template/ +template-web-only/ dist/ package-lock.json package.json diff --git a/README.md b/README.md index db65061..c533110 100644 --- a/README.md +++ b/README.md @@ -1,60 +1,160 @@ # b7-stack -A one-command starting point for new projects. Every project gets the same stack, so the only inputs are a name and a description. +A one-command starting point for new projects. Every project gets the same stack, so it only asks for a name, a description, a database port, and whether to add a desktop app. -- **Web**: Next.js (App Router, Cache Components, React Compiler), Tailwind CSS, Testing Library -- **API**: Express 5 on Node.js 26, running TypeScript directly with no build step -- **Data**: PostgreSQL in Docker, Drizzle ORM with SQL migrations -- **Shared**: Zod schemas and types used by both the API and the web app -- **Tooling**: npm workspaces, TypeScript 7, ESLint, Prettier, Vitest, Husky with lint-staged, ShellCheck, Dependabot, GitHub Actions CI +| Part | What you get | +| ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Web | Next.js (App Router, Cache Components, React Compiler), Tailwind CSS, Testing Library | +| API | Express 5 on Node.js 26, running TypeScript directly with no build step | +| Data | PostgreSQL in Docker, Drizzle ORM with SQL migrations | +| Shared | Zod schemas and types, used by the API and the web app | +| Desktop (optional) | Electron with Electron Forge and Vite, calling the API directly. Adding it also adds a UI package, which holds the React components and the Tailwind theme for both apps, and moves the API client and the form logic into the shared package | +| Tooling | npm workspaces, TypeScript 7, ESLint, Prettier, Vitest, Husky with lint-staged, ShellCheck, Dependabot, GitHub Actions CI | -## Usage +A generated project ships a notes CRUD as a worked example of the whole path, from PostgreSQL through Drizzle, Express, Zod, and Next.js server actions to React components. Its own README lists every script. -SunnyRadish is the example project name used throughout this README. Put your own name in its place. +## Quick start + +Requires Node.js 26 or newer, Git, and Docker for the database. SunnyRadish is the example name used throughout; put your own in its place. + +```sh +npx --allow-git=all github:benlambert43/b7-stack +``` + +npm 12 and newer refuse packages fetched from Git with `npm error code EALLOWGIT` unless `--allow-git=all` is given. Older versions of npm do not need the flag. + +npx asks to install the package, and the CLI then asks its questions one by one. When it finishes, the project runs straight away: ```sh -npx github:benlambert43/b7-stack "SunnyRadish" +cd sunnyradish +npm run db:start # PostgreSQL in Docker, migrations applied +npm run dev # web app on http://localhost:3000 +npm run dev:server # API on http://localhost:4000 +npm run dev:desktop # desktop app, if you added one ``` -Starting with npm v12+, you may get this error when trying to run this command: +## Questions + +The command takes no arguments. Everything is asked for, in this order: +| Question | Default | What the answer sets | +| ------------------------------------------------- | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `Project name, or . to use the current directory` | none | The display name of the project. The folder and package names are derived from it | +| `Description` | none | One sentence for the README, `package.json`, and the home page | +| `Database port` | `5432` | The host port for the PostgreSQL container, from 1 to 65535. Give each project its own to run their databases side by side | +| `Add an Electron desktop app?` | `yes` | `yes` or `y` adds `sunnyradish-desktop`, an Electron app that shows the same notes page as the web app, and `sunnyradish-ui`, the components the two share; `no` or `n` leaves both out | + +A default is shown in parentheses after the question and is used when the answer is left blank. A question without a default is asked again until it is answered. + +### Examples + +Take the defaults by pressing Enter at the last two questions, which adds the desktop app: + +```text +Project name, or . to use the current directory: SunnyRadish +Description: Notes for gardeners. +Database port (5432): +Add an Electron desktop app? (yes): ``` -npm error code EALLOWGIT -npm error Fetching packages of type "git" have been disabled + +Leave the desktop app out, and publish PostgreSQL on a port other than 5432: + +```text +Project name, or . to use the current directory: SunnyRadish +Description: Notes for gardeners. +Database port (5432): 5433 +Add an Electron desktop app? (yes): no ``` -You can bypass this with --allow-git=all. +Scaffold into the current directory, such as a freshly cloned empty repository. Answering `.` brings up the name again, with the folder's name as its default: + +```text +Project name, or . to use the current directory: . +Project name (sunnyradish): +Description: Notes for gardeners. +Database port (5432): +Add an Electron desktop app? (yes): +``` + +In a script or in CI, give the answers on standard input, one line each and in the same order. An empty line takes the default, and `--yes` stops npx from asking to install the package. This one keeps port 5432 and leaves the desktop app out: ```sh -npx --allow-git=all github:benlambert43/b7-stack "SunnyRadish" +printf '%s\n' "SunnyRadish" "Notes for gardeners." "" "no" | npx --yes --allow-git=all github:benlambert43/b7-stack ``` -npx asks to install the package (the first run on a machine also installs the tooling that compiles the CLI), then the CLI asks for a one-sentence description. The command then creates `sunnyradish/`, swaps the name and description in, writes `.env` files with local defaults, runs `git init`, installs dependencies, and formats the result with the project's own Prettier. The result runs straight away: +### Rules + +- **Names.** The name is lowercased and each run of characters other than letters and digits becomes a hyphen. `SunnyRadish` gives `sunnyradish`, `@sunnyradish/shared`, `sunnyradish-server`, and `sunnyradish-web`, and with the desktop app `sunnyradish-desktop` and `@sunnyradish/ui` as well; `Demo App` gives `demo-app`. +- **Characters.** The name and the description may not contain `"`, `\`, or control characters, which would break the files they are written into. With the desktop app the name may not contain `* / : < > ? |` either, which Windows does not allow in file names. +- **Target folder.** It must be new, or hold nothing but what GitHub adds to a new repository: `.git`, `.gitignore`, `.gitattributes`, `LICENSE`, and `README.md`. The template's `.gitignore`, `.gitattributes`, and `README.md` replace the ones already there. +- **Invalid answers.** An answer that breaks one of these rules, a port out of range, or anything but `yes`, `y`, `no`, or `n` for the desktop app stops the command before any file is written. So does input that ends before every question has an answer. + +### What the command does + +1. Copies the template into `sunnyradish/` and swaps the name and the description in. +2. Writes a `.env` beside each `.env.template` with local defaults: the slug as the database user and name, a random password, and the database port that was chosen. +3. Runs `git init` with `main` as the branch, unless `.git` already exists. +4. Runs `npm install`, then formats the project with its own Prettier. + +If a step fails, the files stay in the folder and the error says where they are. + +## Working on this repository + +| Path | What it holds | +| --------------------------- | ----------------------------------------------------------------------------------------------------------------------- | +| `bin/create.ts` | The CLI. `npm install` compiles it into `dist/create.js`, which is what npx runs | +| `template/` | A complete, working project named "B7 Stack", which the CLI copies | +| `template/b7-stack-desktop` | The desktop app, always present in the template and left out when declined | +| `template/b7-stack-ui` | The components the web and desktop apps share, left out with the desktop app | +| `template-web-only/` | The files that differ in a project without the desktop app, which keeps its components and API calls inside the web app | +| `.github/workflows/ci.yml` | Scaffolds a project with and without the desktop app and runs each one's preflight | + +### Setup ```sh -cd sunnyradish -npm run db:start -npm run dev # web app on http://localhost:3000 -npm run dev:server # API on http://localhost:4000 +npm install # builds the CLI and installs the git hooks +cd template && npm install # the template works in place; then follow template/README.md +``` + +The repository's `.vscode` settings mirror the template's and point VS Code at the TypeScript copy inside `template/node_modules`, so editing the template from this checkout behaves like editing a generated project. + +### Commands + +| Command | What it does | +| ----------------------- | ------------------------------------------------------------------------------------------------------------ | +| `npm run preflight` | Every check below, in order | +| `npm run format:check` | Checks formatting with Prettier; `npm run format` rewrites the files | +| `npm run typecheck` | Type-checks the CLI and the root config files | +| `npm run lint` | Runs ESLint with the typed rules and the deprecated-API check; `npm run lint:fix` applies fixes | +| `npm run lint:shell` | Runs ShellCheck on the pre-commit hook | +| `npm run lint:editor` | Fails on `.vscode/settings.json` keys that the installed VS Code marks as deprecated | +| `npm run lint:variants` | Fails when a template file has changed and the web-only variant that mirrors it has not been brought in line | + +These cover the root only; ESLint and Prettier ignore `template/` and `template-web-only/` here. Run the template's own checks from `template/`. On commit, Husky runs lint-staged, and staged files inside `template/` go through the template's lint-staged config. + +### Trying the CLI + +The CLI runs from source and asks the same questions as it does through npx. It creates the project in the directory it is run from, so run it from somewhere outside the checkout, with the path to yours in place of `/path/to`: + +```sh +node /path/to/b7-stack/bin/create.ts ``` -- The folder and package names come from the name, lowercased and with each run of characters other than letters and digits replaced by a hyphen: `"SunnyRadish"` gives `sunnyradish`, `@sunnyradish/shared`, `sunnyradish-server`, and `sunnyradish-web`. -- Pass `.` instead of a name to scaffold into the current directory, such as a freshly cloned empty repository. The folder name is offered as the project name, and `git init` is skipped when `.git` already exists. -- Pass `--description "..."` to skip the prompt, for example in scripts. -- Pass `--db-port 5433` (or any free port) to publish the PostgreSQL container on a port other than 5432 -- For example: +Pipe the answers in to skip the typing. This one sets the database port to 5433 and adds the desktop app: ```sh -npx --allow-git=all github:benlambert43/b7-stack "SunnyRadish" --db-port 5487 +printf '%s\n' "Demo App" "Trying things out." "5433" "yes" | node /path/to/b7-stack/bin/create.ts ``` -- Node.js 26 or newer is required. +To see what npx would install, list the package's files: -The generated project ships a notes CRUD as a worked example of the whole path from PostgreSQL through Drizzle, Express, Zod, and Next.js server actions to React. Its README lists every script. +```sh +npm pack --dry-run +``` -## Working on the template +### Editing the template -`template/` is a complete project named "B7 Stack" and works in place: `cd template && npm install`, then follow its README. The repository has its own `.vscode` settings, mirroring those of the template and pointing VS Code at the TypeScript copy inside `template/node_modules`, so editing the template from this checkout behaves like editing a generated project. The CLI copies it file for file and replaces three strings everywhere, in file contents and in folder names: +The CLI copies `template/` file for file and replaces three strings everywhere, in file contents and in folder names: | In the template | In a generated project | | ------------------------- | --------------------------------------- | @@ -62,8 +162,71 @@ The generated project ships a notes CRUD as a worked example of the whole path f | `b7-stack` | the slug derived from it, `sunnyradish` | | `A new B7 Stack project.` | the description | -Keep those three strings exact when editing the template, and do not write `b7-stack` anywhere else in it. `template/_gitignore` and `template/_npmrc` become `.gitignore` and `.npmrc` on copy, because npm drops files with those names when it packages the template for `npx`. `.env` files, `node_modules`, and build output inside `template/` are never copied. The generated project is formatted afterwards because the slug's length moves table columns and line breaks around. Skip `npm run clean` inside `template/`: run from there, its `git clean` exclusions no longer cover `b7-stack-server/.env` and `b7-stack-web/.env`. +- Keep those three strings exact, and do not write `b7-stack` anywhere else in the template. +- `template/_gitignore` and `template/_npmrc` become `.gitignore` and `.npmrc` on copy, because npm drops files with those names when it packages the template for npx. +- `.env` files, `node_modules`, and build output inside `template/` are never copied. The `files` list in the root `package.json` leaves the same paths out of the package, so `npm pack` works in a checkout where the template has been installed or built. +- The dependencies in each `package.json` are sorted again once the names are in, because `@sunnyradish/shared` does not sort where `@b7-stack/shared` did, and npm would otherwise reorder them on its next install. +- A `|` in the name or the description is written as `\|` in a Markdown table row, where it would start a new cell. +- The generated project is formatted afterwards because the slug's length moves table columns and line breaks around. +- Skip `npm run clean` inside `template/`. Run from there, its `git clean` exclusions no longer cover the `.env` files of the workspaces. + +### The desktop app in the template + +The template is the project with the desktop app. In it the web and desktop apps share their components through `b7-stack-ui`, and the API client and the form logic through `b7-stack-shared`. A project without the desktop app has one app, so it keeps all of that inside `b7-stack-web`, as it would if the desktop app did not exist. + +When the desktop app is declined, the CLI leaves out `template/b7-stack-desktop`, `template/b7-stack-ui`, `.vscode/launch.json`, and `apiClient.ts` and `noteActions.ts` in `b7-stack-shared/src`. The `desktopOnlyPaths` list in `bin/create.ts` names them. What a file contains then depends on four things, listed from the one to prefer to the one to avoid. + +**Entries that remove themselves.** The CLI removes each reference to `b7-stack-desktop` or `b7-stack-ui` that is a whole entry on its own: + +- the workspaces and the scripts for them in the root `package.json`; +- a line that is a quoted string in a list with one entry per line, a path in an ignore file, or a Markdown list item or table row; +- a quoted string later in a list written on one line, together with the comma before it. + +**Markers.** Everything between a line containing `desktop:start` and the next line containing `desktop:end` is removed. Everything between `web-only:start` and `web-only:end` is kept instead, and removed when the desktop app is added. Write a web-only block inside a comment, so that it does nothing in the template: + +```md + + +Shown with the desktop app. + + + +``` + +The marker lines themselves never reach a project. `template/README.md` pairs the two kinds of block wherever the projects differ, and `theme.css` in `b7-stack-ui` does the same in a CSS comment. + +**Moved files.** `webOnlyMoves` in `bin/create.ts` lists files of `b7-stack-ui` that the project without the desktop app gets inside its web app: `StatusRow.tsx` goes to `app/_components`, and `theme.css` becomes `app/globals.css`. + +**Variants.** A file in `template-web-only/` takes the place of the template's file at the same path, or is added where the template has none. These are the files that are wired differently, such as the components that import the server actions instead of taking them as props. A JSON file there is merged into the template's file instead, so that the versions in a `package.json` stay in one place: a key set to `null` is removed, an object is merged key by key, and any other value replaces the one in the template. + +A variant is a second copy, so `template-web-only/variants.json` lists the template files that each one mirrors, with a hash of each. `npm run lint:variants` fails when one of those files has changed, and names the variant to look at. Make the same change there where it applies, then record the new hashes: + +```sh +npm run lint:variants -- --update +``` + +A new variant needs an entry in `variants.json` with the template files it mirrors; give each an empty string and run the same command. JSON files are not listed. Prettier and ESLint do not run on `template-web-only/` in this repository, so scaffold a project without the desktop app and run its `npm run preflight` to check a change there, as CI does. + +Any other line that names one of the two workspaces or `@b7-stack/ui`, and any unbalanced marker, makes the CLI stop with an error naming the file. CI also fails if the project without the desktop app contains the word "desktop" at all. + +`package-lock.json` is copied whole, and the `npm install` that follows prunes it. Electron's binary is not part of that install: the `electron` package downloads it the first time the desktop app is started or packaged. + +### Tooling notes + +- Nothing in the repository is JavaScript. Config files are TypeScript that Node.js 26 loads directly, except that ESLint needs `jiti` to read `eslint.config.ts`. +- Node.js refuses to strip types from files under `node_modules`, where npx installs the package. The `prepare` script therefore compiles the CLI into `dist/`, which is gitignored and rebuilt on every install, including the one npx performs. +- The root and the template root keep TypeScript 6 because typescript-eslint cannot use TypeScript 7 yet. + +### CI and Dependabot + +CI runs the root preflight, installs the commit under test with npx exactly as a user would, scaffolds a project with and without the desktop app by piping the answers in, checks that no placeholder or marker survived, and runs each project's `npm run preflight`. The root preflight includes `lint:variants`. A broken template or CLI fails here first. -Nothing in the repository is JavaScript. Config files in the template are TypeScript that Node 26 loads directly, except that ESLint still needs `jiti` to read `eslint.config.ts`, which is why that package is a devDependency. The CLI is `bin/create.ts`. Node refuses to strip types from files under `node_modules`, where npx installs the package, so the `prepare` script compiles it into `dist/create.js`, which is gitignored and rebuilt on every install, including the one npx performs. The root holds itself to the gates a generated project gets: `npm install` builds the CLI and installs the git hooks, `npm run preflight` runs the format check, typecheck, lint with the same typed rules and deprecated-API check, ShellCheck on the hook, and the editor-settings check, and Husky runs lint-staged on commit. Staged files inside `template/` are handled by the template's own lint-staged config, run from `template/`, so a change to the template gets the template's checks. The root keeps TypeScript 6 for the same reason the template root does: typescript-eslint cannot use TypeScript 7 yet. +Dependabot updates the npm packages at the root and in the template, the Postgres image in the template, and the actions in this repository's workflow. Three things are left to do by hand: -Try the CLI from a checkout with `node bin/create.ts "Demo App" --description "Trying things out."`. CI runs the root preflight, installs the commit under test with `npx` exactly as a user would, scaffolds a project, and runs its `npm run preflight`, so a broken template or CLI fails here first. Dependabot updates the npm packages at the root and in the template, the Postgres image in the template, and the actions in this repository's own workflow. It cannot see `template/.github/workflows/ci.yml`, so bump the `uses:` versions there by hand. +- Bump the `uses:` versions in `template/.github/workflows/ci.yml`, which Dependabot cannot see. +- Raise the major version of `@types/node` when its runtime moves: Node.js for most of the repository, and the Node.js inside Electron for the desktop app. Raise TypeScript's major and minor versions by hand as well. +- Run `npm dedupe` in `template/` after updating by hand. npm can otherwise install a second copy of a package that one already present would satisfy, as it does with Rolldown after a fresh resolution. diff --git a/bin/create.ts b/bin/create.ts index 31fb92c..daef2f6 100755 --- a/bin/create.ts +++ b/bin/create.ts @@ -3,10 +3,11 @@ import { execFileSync } from "node:child_process"; import { randomBytes } from "node:crypto"; import fs from "node:fs"; import path from "node:path"; -import readline from "node:readline/promises"; -import { parseArgs, styleText } from "node:util"; +import readline from "node:readline"; +import { styleText } from "node:util"; const templateDir = path.join(import.meta.dirname, "..", "template"); +const webOnlyDir = path.join(import.meta.dirname, "..", "template-web-only"); const placeholders = { description: "A new B7 Stack project.", @@ -14,6 +15,59 @@ const placeholders = { slug: "b7-stack", }; +const desktopWorkspaces = [ + `${placeholders.slug}-desktop`, + `${placeholders.slug}-ui`, +]; +const desktopNames = [...desktopWorkspaces, `@${placeholders.slug}/ui`]; +const desktopOnlyPaths = new Set([ + ...desktopWorkspaces, + path.join(".vscode", "launch.json"), + path.join(`${placeholders.slug}-shared`, "src", "apiClient.ts"), + path.join(`${placeholders.slug}-shared`, "src", "noteActions.ts"), +]); +const webOnlyMoves = new Map([ + [ + path.join(`${placeholders.slug}-ui`, "src", "StatusRow.tsx"), + path.join( + `${placeholders.slug}-web`, + "app", + "_components", + "StatusRow.tsx", + ), + ], + [ + path.join(`${placeholders.slug}-ui`, "src", "theme.css"), + path.join(`${placeholders.slug}-web`, "app", "globals.css"), + ], +]); +const webOnlyMoveTargets = new Set(webOnlyMoves.values()); +const variantManifest = "variants.json"; +const desktopWorkspacePattern = `(?:${desktopWorkspaces.join("|")})`; +const lineEnd = String.raw`(?:\r?\n|(?![\s\S]))`; +const blockOf = (name: string) => + new RegExp( + String.raw`^.*${name}:start.*\r?\n[\s\S]*?^.*${name}:end.*` + lineEnd, + "gm", + ); +const markerOf = (name: string) => + new RegExp(String.raw`^.*${name}:(?:start|end).*` + lineEnd, "gm"); +const desktopBlock = blockOf("desktop"); +const desktopMarker = markerOf("desktop"); +const webOnlyBlock = blockOf("web-only"); +const webOnlyMarker = markerOf("web-only"); +const removableDesktopLine = new RegExp( + String.raw`^(?:[ \t]*["'][^"'\n]*${desktopWorkspacePattern}[^"'\n]*["'],?[ \t]*|[^\s]*${desktopWorkspacePattern}[^\s]*|[ \t]*(?:[-*|]|\d+\.)[ \t].*${desktopWorkspacePattern}.*)` + + lineEnd, + "gm", +); +const removableDesktopEntry = new RegExp( + String.raw`,[ \t]*(["'])[^"'\n]*${desktopWorkspacePattern}[^"'\n]*\1`, + "g", +); +const unsupportedCharacters = /["\\\p{Cc}]/u; +const unsupportedDesktopNameCharacters = /[*/:<>?|]/; + const renamedFiles = new Map([ ["_gitignore", ".gitignore"], ["_npmrc", ".npmrc"], @@ -22,6 +76,8 @@ const renamedFiles = new Map([ const skippedFiles = new Set([ "node_modules", ".next", + ".vite", + "out", "coverage", ".env", ".DS_Store", @@ -38,18 +94,6 @@ const starterFiles = new Set([ "README.md", ]); -const usage = `Usage: npx github:benlambert43/b7-stack [name | .] [--description ] [--db-port ] - - name Display name of the new project. The folder and package names - are derived from it: "SunnyRadish" becomes sunnyradish. - . Scaffold into the current directory instead. It must be empty - apart from .git and the files GitHub adds to a new repository. - --description One sentence for the README, package.json, and the home page. - --db-port Host port for the PostgreSQL container (default 5432). Give - each project its own to run their databases side by side. - -Whatever is not given is asked for.`; - function fail(message: string): never { console.error(styleText("red", message, { stream: process.stderr })); process.exit(1); @@ -62,57 +106,10 @@ function slugify(name: string) { .replace(/^-+|-+$/g, ""); } -async function ask(question: string, defaultValue = "") { - if (!process.stdin.isTTY) { - if (defaultValue) { - return defaultValue; - } - fail( - `${question} is required when there is no terminal to ask in.\n\n${usage}`, - ); - } - const prompt = readline.createInterface({ - input: process.stdin, - output: process.stdout, - }); - try { - let answer = ""; - while (!answer) { - const hint = defaultValue ? ` (${defaultValue})` : ""; - answer = - (await prompt.question(`${question}${hint}: `)).trim() || defaultValue; - } - return answer; - } finally { - prompt.close(); - } -} - -function parseArguments() { - try { - return parseArgs({ - allowPositionals: true, - options: { - description: { type: "string", short: "d" }, - "db-port": { type: "string", default: "5432" }, - help: { type: "boolean", short: "h" }, - }, - }); - } catch (error) { - fail( - `${error instanceof Error ? error.message : String(error)}\n\n${usage}`, - ); - } -} - -const { values, positionals } = parseArguments(); - -if (values.help) { - console.log(usage); - process.exit(0); -} -if (positionals.length > 1) { - fail(`Expected one name, got ${positionals.length}.\n\n${usage}`); +if (process.argv.length > 2) { + fail( + "This command takes no arguments. Run it without any and answer its questions.", + ); } const nodeMajor = Number.parseInt(process.versions.node, 10); @@ -120,21 +117,73 @@ if (nodeMajor < 26) { fail(`Node.js 26 or newer is required; this is ${process.version}.`); } -const dbPort = values["db-port"]; -if (!/^\d+$/.test(dbPort) || Number(dbPort) < 1 || Number(dbPort) > 65535) { - fail(`--db-port must be a port number from 1 to 65535, got "${dbPort}".`); +const terminal = process.stdin.isTTY ? process.stdout.isTTY : false; +const prompt = readline.createInterface({ + input: process.stdin, + output: process.stdout, + terminal, +}); +const answers = prompt[Symbol.asyncIterator](); + +async function ask(question: string, defaultValue = "") { + const hint = defaultValue ? ` (${defaultValue})` : ""; + const text = `${question}${hint}: `; + for (;;) { + if (terminal) { + prompt.setPrompt(text); + prompt.prompt(); + } else { + process.stdout.write(text); + } + const line = await answers.next(); + if (line.done) { + fail(`\nThe input ended before "${question}" was answered.`); + } + const answer = line.value.trim() || defaultValue; + if (!process.stdin.isTTY) { + console.log(answer); + } + if (answer) { + return answer; + } + } } -const inPlace = positionals[0] === "."; +const nameAnswer = await ask("Project name, or . to use the current directory"); +const inPlace = nameAnswer === "."; const name = inPlace ? await ask("Project name", path.basename(process.cwd())) - : (positionals[0] ?? (await ask("Project name"))); + : nameAnswer; +if (unsupportedCharacters.test(name)) { + fail( + `"${name}" contains a character that cannot be used in the project name: " \\ or a control character`, + ); +} const slug = slugify(name); if (!slug) { fail(`"${name}" has no letters or digits to name the packages after.`); } -const description = - (values.description ?? "").trim() || (await ask("Description")); +const description = await ask("Description"); +if (unsupportedCharacters.test(description)) { + fail( + `The description contains a character that cannot be used in it: " \\ or a control character`, + ); +} +const dbPort = await ask("Database port", "5432"); +if (!/^\d+$/.test(dbPort) || Number(dbPort) < 1 || Number(dbPort) > 65535) { + fail(`The database port must be a number from 1 to 65535, got "${dbPort}".`); +} +const desktopAnswer = await ask("Add an Electron desktop app?", "yes"); +if (!/^(?:y|yes|n|no)$/i.test(desktopAnswer)) { + fail(`Answer yes or no to the desktop app, got "${desktopAnswer}".`); +} +const desktop = /^y/i.test(desktopAnswer); +prompt.close(); +if (desktop && unsupportedDesktopNameCharacters.test(name)) { + fail( + `"${name}" contains a character that cannot be used in the name of a project with a desktop app: * / : < > ? |`, + ); +} const targetDir = inPlace ? process.cwd() : path.resolve(slug); if (fs.existsSync(targetDir)) { @@ -160,30 +209,185 @@ const placeholderPattern = new RegExp( [...replacements.keys()].map(escapeRegExp).join("|"), "g", ); -const fill = (text: string) => - text.replace(placeholderPattern, (match) => replacements.get(match) ?? match); +const fill = (text: string, escape = (value: string) => value) => + text.replace(placeholderPattern, (match) => + escape(replacements.get(match) ?? match), + ); +const escapeTableCell = (value: string) => + value.replaceAll("|", String.raw`\|`); + +type Json = null | boolean | number | string | Json[] | { [key: string]: Json }; + +function isJsonObject(value: Json): value is Record { + return value !== null && typeof value === "object" && !Array.isArray(value); +} + +const dependencyFields = [ + "dependencies", + "devDependencies", + "optionalDependencies", + "peerDependencies", +]; -function copyTemplate(sourceDir: string, destinationDir: string) { +function sortDependencies(text: string) { + const manifest = JSON.parse(text) as Record; + for (const field of dependencyFields) { + const dependencies = manifest[field]; + if (dependencies !== undefined && isJsonObject(dependencies)) { + manifest[field] = Object.fromEntries( + Object.entries(dependencies).sort(([a], [b]) => + a.localeCompare(b, "en"), + ), + ); + } + } + return `${JSON.stringify(manifest, null, 2)}\n`; +} + +function render(relative: string, text: string) { + if (path.basename(relative) === "package.json") { + return sortDependencies(fill(text)); + } + if (path.extname(relative) === ".md") { + return text + .split("\n") + .map((line) => + line.startsWith("|") ? fill(line, escapeTableCell) : fill(line), + ) + .join("\n"); + } + return fill(text); +} + +function mergePatch(target: Json, patch: Json): Json { + if (!isJsonObject(patch)) { + return patch; + } + const merged = new Map(Object.entries(isJsonObject(target) ? target : {})); + for (const [key, value] of Object.entries(patch)) { + if (value === null) { + merged.delete(key); + } else { + merged.set(key, mergePatch(merged.get(key) ?? null, value)); + } + } + return Object.fromEntries(merged); +} + +function applyWebOnly(relative: string, text: string) { + const variant = path.join(webOnlyDir, relative); + if (!fs.existsSync(variant)) { + return text; + } + const variantText = fs.readFileSync(variant, "utf8"); + if (path.extname(relative) !== ".json") { + return variantText; + } + const merged = mergePatch( + JSON.parse(text) as Json, + JSON.parse(variantText) as Json, + ); + return `${JSON.stringify(merged, null, 2)}\n`; +} + +function checkMarkers(relative: string, text: string) { + for (const name of ["desktop", "web-only"]) { + const markers = [ + ...text.matchAll(new RegExp(`${name}:(start|end)`, "g")), + ].map(([, kind]) => kind); + if (markers.some((kind, index) => kind !== (index % 2 ? "end" : "start"))) { + fail(`${relative} has unbalanced ${name}:start and ${name}:end markers.`); + } + } +} + +function selectVariant(relative: string, text: string) { + if (path.basename(relative) === "package-lock.json") { + return text; + } + checkMarkers(relative, text); + return desktop + ? text.replace(webOnlyBlock, "").replace(desktopMarker, "") + : removeDesktop(relative, text); +} + +function removeDesktop(relative: string, text: string) { + if (relative === "package.json") { + const manifest = JSON.parse(text) as { + workspaces: string[]; + scripts: Record; + }; + manifest.workspaces = manifest.workspaces.filter( + (workspace) => !desktopWorkspaces.includes(workspace), + ); + manifest.scripts = Object.fromEntries( + Object.entries(manifest.scripts).filter( + ([, command]) => + !desktopWorkspaces.some((workspace) => command.includes(workspace)), + ), + ); + return `${JSON.stringify(manifest, null, 2)}\n`; + } + const stripped = text + .replace(desktopBlock, "") + .replace(webOnlyMarker, "") + .replace(removableDesktopLine, "") + .replace(removableDesktopEntry, ""); + const leftover = stripped + .split("\n") + .find((line) => desktopNames.some((name) => line.includes(name))); + if (leftover !== undefined) { + fail( + `${relative}: "${leftover.trim()}" names a workspace that only a project with the desktop app has, but is not a list entry, an ignore path, or a Markdown list item or table row. Put it between desktop:start and desktop:end markers, or give the file a variant in template-web-only.`, + ); + } + return stripped; +} + +function copyTemplate( + sourceDir: string, + destinationDir: string, + rootDir = sourceDir, +) { fs.mkdirSync(destinationDir, { recursive: true }); for (const entry of fs.readdirSync(sourceDir, { withFileTypes: true })) { - if (skippedFiles.has(entry.name)) { + const source = path.join(sourceDir, entry.name); + const relative = path.relative(rootDir, source); + const fromTemplate = rootDir === templateDir; + if ( + skippedFiles.has(entry.name) || + (!desktop && desktopOnlyPaths.has(relative)) || + (!desktop && fromTemplate && webOnlyMoveTargets.has(relative)) || + (!fromTemplate && relative === variantManifest) + ) { continue; } - const source = path.join(sourceDir, entry.name); const destination = path.join( destinationDir, renamedFiles.get(entry.name) ?? fill(entry.name), ); if (entry.isDirectory()) { - copyTemplate(source, destination); + copyTemplate(source, destination, rootDir); + continue; + } + if (!fromTemplate && fs.existsSync(path.join(templateDir, relative))) { continue; } const content = fs.readFileSync(source); - fs.writeFileSync( - destination, - content.includes(0) ? content : fill(content.toString("utf8")), - { mode: fs.statSync(source).mode }, + if (content.includes(0)) { + fs.writeFileSync(destination, content, { + mode: fs.statSync(source).mode, + }); + continue; + } + const text = content.toString("utf8"); + const selected = selectVariant( + relative, + !desktop && fromTemplate ? applyWebOnly(relative, text) : text, ); + fs.writeFileSync(destination, render(relative, selected), { + mode: fs.statSync(source).mode, + }); } } @@ -228,9 +432,19 @@ function run(command: string, commandArgs: string[]) { console.log(styleText("bold", `\nā–¶ Creating ${name} in ${targetDir}`)); copyTemplate(templateDir, targetDir); +if (!desktop) { + copyTemplate(webOnlyDir, targetDir); + for (const [from, to] of webOnlyMoves) { + const text = fs.readFileSync(path.join(templateDir, from), "utf8"); + fs.writeFileSync( + path.join(targetDir, fill(to)), + render(to, selectVariant(to, text)), + ); + } +} const envCount = writeEnvFiles(targetDir); console.log( - ` copied the template and wrote ${envCount} .env files with local defaults`, + ` copied the template and wrote ${String(envCount)} .env files with local defaults`, ); if (!fs.existsSync(path.join(targetDir, ".git"))) { @@ -239,10 +453,14 @@ if (!fs.existsSync(path.join(targetDir, ".git"))) { run("npm", ["install"]); run("npm", ["run", "format", "--silent", "--", "--log-level", "warn"]); +const desktopStep = desktop + ? "\n npm run dev:desktop desktop app, which calls the API" + : ""; + console.log(` ${styleText("green", "āœ”")} ${styleText("bold", name)} is ready. Next: ${inPlace ? "" : `\n cd ${slug}`} npm run db:start PostgreSQL in Docker on port ${dbPort}, migrations applied npm run dev web app on http://localhost:3000 - npm run dev:server API on http://localhost:4000 + npm run dev:server API on http://localhost:4000${desktopStep} `); diff --git a/eslint.config.ts b/eslint.config.ts index 937352c..7852b3b 100644 --- a/eslint.config.ts +++ b/eslint.config.ts @@ -4,7 +4,7 @@ import globals from "globals"; import tseslint from "typescript-eslint"; export default defineConfig([ - globalIgnores(["dist/", "template/"]), + globalIgnores(["dist/", "template/", "template-web-only/"]), js.configs.recommended, { files: ["**/*.{ts,tsx,mts,cts,js,mjs,cjs}"], @@ -21,10 +21,6 @@ export default defineConfig([ }, rules: { "@typescript-eslint/no-deprecated": "error", - "@typescript-eslint/restrict-template-expressions": [ - "error", - { allowNumber: true }, - ], "@typescript-eslint/no-unused-vars": [ "error", { diff --git a/package-lock.json b/package-lock.json index c433c77..c1dad25 100644 --- a/package-lock.json +++ b/package-lock.json @@ -14,13 +14,13 @@ "@eslint/js": "^10.0.1", "@types/node": "^26.6.6", "eslint": "^10.14.0", - "globals": "^17.13.0", + "globals": "^17.14.0", "husky": "^9.1.7", "jiti": "^2.7.0", "lint-staged": "^17.6.0", - "prettier": "^3.9.10", + "prettier": "^3.10.0", "typescript": "~6.0.3", - "typescript-eslint": "^8.72.1" + "typescript-eslint": "^8.72.2" }, "engines": { "node": ">=26" @@ -83,9 +83,9 @@ } }, "node_modules/@eslint-community/regexpp": { - "version": "4.12.2", - "resolved": "https://registry.npmjs.org/@eslint-community/regexpp/-/regexpp-4.12.2.tgz", - "integrity": "sha512-EriSTlt5OC9/7SXkRSCAhfSxxoSUgBm33OH+IkwbdpgoqsSsUg7y3uh+IICI/Qg4BBWr3U2i39RpmycbxMq4ew==", + "version": "4.12.3", + "resolved": "https://registry.npmjs.org/@eslint-community/regexpp/-/regexpp-4.12.3.tgz", + "integrity": "sha512-R76UKbvsqI68DJJVTVyqFKqU98CN4+B+acxNfEA2IFarSzP0SjtKf/3+fFiXzTyv5Fj3PxLkGHe2wnVWWMxobQ==", "dev": true, "license": "MIT", "engines": { @@ -300,17 +300,17 @@ } }, "node_modules/@typescript-eslint/eslint-plugin": { - "version": "8.72.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.72.1.tgz", - "integrity": "sha512-5CokTWXpmbylfFabsbvHC0CAw3XLaGnoa+nFJX5FR592h/LoZsENUE6p/rg5xvkKrFEXz6pYmgI29AgXc2N3BQ==", + "version": "8.72.2", + "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.72.2.tgz", + "integrity": "sha512-222PKFXKihmFpi/pS5njoBgdAqsPhj2/GBmFbrNw8Tq8gEG9Sv+kSlKFy4u2q+mJv9ZzJgM2Gkv/bUzRZwZw5g==", "dev": true, "license": "MIT", "dependencies": { "@eslint-community/regexpp": "^4.12.2", - "@typescript-eslint/scope-manager": "8.72.1", - "@typescript-eslint/type-utils": "8.72.1", - "@typescript-eslint/utils": "8.72.1", - "@typescript-eslint/visitor-keys": "8.72.1", + "@typescript-eslint/scope-manager": "8.72.2", + "@typescript-eslint/type-utils": "8.72.2", + "@typescript-eslint/utils": "8.72.2", + "@typescript-eslint/visitor-keys": "8.72.2", "ignore": "^7.0.5", "natural-compare": "^1.4.0", "ts-api-utils": "^2.5.0" @@ -323,7 +323,7 @@ "url": "https://opencollective.com/typescript-eslint" }, "peerDependencies": { - "@typescript-eslint/parser": "^8.72.1", + "@typescript-eslint/parser": "^8.72.2", "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", "typescript": ">=4.8.4 <6.1.0" } @@ -339,16 +339,16 @@ } }, "node_modules/@typescript-eslint/parser": { - "version": "8.72.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.72.1.tgz", - "integrity": "sha512-ZGwZP4OCfyA0AQTpEAMWz+rtX01DRhQWW5hB0ucKDEIX5U7jdmPSaMx94rQfaPAQzIYz2BimOgKOJtjfpRFQ9g==", + "version": "8.72.2", + "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.72.2.tgz", + "integrity": "sha512-llP+T1YuJOLlxEciP6OyQGtz5SMxyn+9LA2BvZw5RmToGVa1y4beEDVQL6Gje7T5WFYh19WREjDCN9Ev4gm5AA==", "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/scope-manager": "8.72.1", - "@typescript-eslint/types": "8.72.1", - "@typescript-eslint/typescript-estree": "8.72.1", - "@typescript-eslint/visitor-keys": "8.72.1", + "@typescript-eslint/scope-manager": "8.72.2", + "@typescript-eslint/types": "8.72.2", + "@typescript-eslint/typescript-estree": "8.72.2", + "@typescript-eslint/visitor-keys": "8.72.2", "debug": "^4.4.3" }, "engines": { @@ -364,14 +364,14 @@ } }, "node_modules/@typescript-eslint/project-service": { - "version": "8.72.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/project-service/-/project-service-8.72.1.tgz", - "integrity": "sha512-fAuVMkwdO/huI8nyo/WKnNKf6Gag93S56Rh3Ts5mGcavwSdaN8tRg1gCeIGX8PF+nzp1BjGfO4gHhGzW1J6jTg==", + "version": "8.72.2", + "resolved": "https://registry.npmjs.org/@typescript-eslint/project-service/-/project-service-8.72.2.tgz", + "integrity": "sha512-6y5dLTZdHhI8Eh3yIQ/bfQhRKwn5e+TpJj64o18Cngc0iW/BCrVvrr6zGYqXPnYH31u6YXAYiFh0+qxX5mybJw==", "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/tsconfig-utils": "^8.72.1", - "@typescript-eslint/types": "^8.72.1", + "@typescript-eslint/tsconfig-utils": "^8.72.2", + "@typescript-eslint/types": "^8.72.2", "debug": "^4.4.3" }, "engines": { @@ -386,14 +386,14 @@ } }, "node_modules/@typescript-eslint/scope-manager": { - "version": "8.72.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.72.1.tgz", - "integrity": "sha512-lC/t6eMCZZQAAKZEYGL6RDVSuFehpdmMT6h+nJIjIa6oylN/PwDgDVtEIbB7O9xFfZYtZAYLoLlDNWKJhtF+uQ==", + "version": "8.72.2", + "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.72.2.tgz", + "integrity": "sha512-iIoMJ6/8c1/QpFNyFjU0d1YzPco4MsZjQw0k3V+vfzNWAFmUmvhlyMoYEoYYDQZXc+J6Gi1X5XcxlzW2taIIGQ==", "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/types": "8.72.1", - "@typescript-eslint/visitor-keys": "8.72.1" + "@typescript-eslint/types": "8.72.2", + "@typescript-eslint/visitor-keys": "8.72.2" }, "engines": { "node": "^18.18.0 || ^20.9.0 || >=21.1.0" @@ -404,9 +404,9 @@ } }, "node_modules/@typescript-eslint/tsconfig-utils": { - "version": "8.72.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.72.1.tgz", - "integrity": "sha512-e4D5R5vpeAEPBxT2BAzsFQL3sbwyeeeo5+aczgNSRK1V734jE7pTqaGFU+fXapWEQwnZbpFaTn32+Z8DwS6OTg==", + "version": "8.72.2", + "resolved": "https://registry.npmjs.org/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.72.2.tgz", + "integrity": "sha512-+h3iCgZXuTNtoLXcnnjP12ZUHLMqoUcIHPfQrFEXTUqvb9dF8QK9b5nv5VtSo5fLkdHuks8ehbTzZj3rImAm9w==", "dev": true, "license": "MIT", "engines": { @@ -421,15 +421,15 @@ } }, "node_modules/@typescript-eslint/type-utils": { - "version": "8.72.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.72.1.tgz", - "integrity": "sha512-iY2wlmyrXJmx4yxUGP3aYCFF3cA/6ShddOKmLU2dx7LnEykbAM8WThlxZEfd1NddqceF6eJmZUayxx9oKIYNlg==", + "version": "8.72.2", + "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.72.2.tgz", + "integrity": "sha512-STfkR38qIdhfkLpgtXnUjAzsNy4xouqiBO0lrVc/Wpk9Kem5/aHXUx1J8dGC16zpdYN1+yc2ILQ28er1kXX7ag==", "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/types": "8.72.1", - "@typescript-eslint/typescript-estree": "8.72.1", - "@typescript-eslint/utils": "8.72.1", + "@typescript-eslint/types": "8.72.2", + "@typescript-eslint/typescript-estree": "8.72.2", + "@typescript-eslint/utils": "8.72.2", "debug": "^4.4.3", "ts-api-utils": "^2.5.0" }, @@ -446,9 +446,9 @@ } }, "node_modules/@typescript-eslint/types": { - "version": "8.72.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.72.1.tgz", - "integrity": "sha512-LmE5IhQet1BWOWEXqBrVtBPsMAOQ6Nzk35d+WLh3mk4EUF33sqlfxjio1MdYeSvKSG5skactKKuixBIKXhL4Rw==", + "version": "8.72.2", + "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.72.2.tgz", + "integrity": "sha512-Xfn37OLZx03+PCU7qWx9DTv2FCRh1E6fk2+wONeNY15HXIwtcwuveaSwVpGAUptkNmPQegRxW5JyRel9T7wrog==", "dev": true, "license": "MIT", "engines": { @@ -460,16 +460,16 @@ } }, "node_modules/@typescript-eslint/typescript-estree": { - "version": "8.72.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.72.1.tgz", - "integrity": "sha512-DAlUoUV93hIvrtIQLwCbmZQYVZwOMhiHJrOVUUIWicFZaIYjTRqlY3I/NZevfkLmSqkNHRu2qYDcq9lrn16oOQ==", + "version": "8.72.2", + "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.72.2.tgz", + "integrity": "sha512-pQEGqIK/cqEvKivVWaFLYpe7XYejFxfuAOi4mu1oAWFvIo36aRHI9esRFTUxcIy/z8N482RJyH+LpZB0ZIU7Ow==", "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/project-service": "8.72.1", - "@typescript-eslint/tsconfig-utils": "8.72.1", - "@typescript-eslint/types": "8.72.1", - "@typescript-eslint/visitor-keys": "8.72.1", + "@typescript-eslint/project-service": "8.72.2", + "@typescript-eslint/tsconfig-utils": "8.72.2", + "@typescript-eslint/types": "8.72.2", + "@typescript-eslint/visitor-keys": "8.72.2", "debug": "^4.4.3", "minimatch": "^10.2.2", "semver": "^7.7.3", @@ -488,16 +488,16 @@ } }, "node_modules/@typescript-eslint/utils": { - "version": "8.72.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.72.1.tgz", - "integrity": "sha512-5v5liypurJBFHCBNqh/RjsymAD+VWcE0djuGY/BUqp5fC3Qn+luWDEksjuTtWjPn6i5zQlUtkZCRG/CYG0yCkA==", + "version": "8.72.2", + "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.72.2.tgz", + "integrity": "sha512-hv3eRYbpPbbpezuax1EfGrzpa3C4ySgNZkPUkLOWOAjU8HsOKowEDAr8C7nsNl1C+SBSKDpvno6VKHnlhvp9iA==", "dev": true, "license": "MIT", "dependencies": { "@eslint-community/eslint-utils": "^4.9.1", - "@typescript-eslint/scope-manager": "8.72.1", - "@typescript-eslint/types": "8.72.1", - "@typescript-eslint/typescript-estree": "8.72.1" + "@typescript-eslint/scope-manager": "8.72.2", + "@typescript-eslint/types": "8.72.2", + "@typescript-eslint/typescript-estree": "8.72.2" }, "engines": { "node": "^18.18.0 || ^20.9.0 || >=21.1.0" @@ -512,13 +512,13 @@ } }, "node_modules/@typescript-eslint/visitor-keys": { - "version": "8.72.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.72.1.tgz", - "integrity": "sha512-SB8xqipSzZHUePCCLNeYxqnxq83X61/qzNhjQGbTfjxGZIeOEP7tBgWYX05Tcd6CgE02WdTJnh5b8kMZJ/+bnQ==", + "version": "8.72.2", + "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.72.2.tgz", + "integrity": "sha512-NAGrjn0Pitjqzq/GkgMC4kBYm233PQ8GffyQ9+kTA3AlNQYEzOf25EIM02BAHZv5FRJSpHpJk+OGUxVkOB93GQ==", "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/types": "8.72.1", + "@typescript-eslint/types": "8.72.2", "eslint-visitor-keys": "^5.0.0" }, "engines": { @@ -580,9 +580,9 @@ } }, "node_modules/brace-expansion": { - "version": "5.0.12", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.12.tgz", - "integrity": "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==", + "version": "5.0.13", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.13.tgz", + "integrity": "sha512-Vh3dmFbc4wZeox7M9I/0L9GfFd83Su4+yCck/OF9Gi/P/dAHn0RT7X4K9R7gMNMhDck3DvhR6QXsnQdjjgwNvQ==", "dev": true, "license": "MIT", "dependencies": { @@ -913,9 +913,9 @@ } }, "node_modules/globals": { - "version": "17.13.0", - "resolved": "https://registry.npmjs.org/globals/-/globals-17.13.0.tgz", - "integrity": "sha512-RwMTC61u7hrG3ZJMkZQOK4JLJrKS8QtoTii63EmWvFXHqycY9FObBJQCbsLxSO8kjKhWE5kV1GC+Vb1g3RI0Zg==", + "version": "17.14.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-17.14.0.tgz", + "integrity": "sha512-UtdkTVyAJePQv0J2M9Xe4L0ruNSDV314XiIJsADI2Zf40bcdAonE/D/OhAU8AT99oij9mhLByb+NvA3QWZYgCg==", "dev": true, "license": "MIT", "engines": { @@ -1223,9 +1223,9 @@ } }, "node_modules/prettier": { - "version": "3.9.10", - "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.9.10.tgz", - "integrity": "sha512-skGHTH1Yb9QvaTC4hWnRTzEYtCpApF0UMBPz+t/0ZPzP8ihefo/btKd+QA7pUE0fEwA1SbS/NmhyEcstdXOIdA==", + "version": "3.10.0", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.10.0.tgz", + "integrity": "sha512-mBi4765LgjO1PFjlEs7pUeK0nb1bw71c+N4/ItfeUWNdY5cV2pRKaFpbbFRYmDJMO+5ZwzGxHRqHxFZna7iv5w==", "dev": true, "license": "MIT", "bin": { @@ -1269,9 +1269,9 @@ "license": "MIT" }, "node_modules/semver": { - "version": "7.8.5", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", - "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", + "version": "7.8.6", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.6.tgz", + "integrity": "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==", "dev": true, "license": "ISC", "bin": { @@ -1382,16 +1382,16 @@ } }, "node_modules/typescript-eslint": { - "version": "8.72.1", - "resolved": "https://registry.npmjs.org/typescript-eslint/-/typescript-eslint-8.72.1.tgz", - "integrity": "sha512-3Li9FfPmQp45nxEtFD1ZCrYFI3cYK5kpyNtmm1H7lMagm8u9sy6PTjy3ytwQZs7KNukOyKFHAZ6z6GjYFeaeXw==", + "version": "8.72.2", + "resolved": "https://registry.npmjs.org/typescript-eslint/-/typescript-eslint-8.72.2.tgz", + "integrity": "sha512-c/+AKMW1KB81r28Sp0AAdcyXj5dzNmAsZFcsrxKbZTKmcBK2xIwBR31dcSYSDu3bKmzXe8GKrSxO+eDQ401Uzg==", "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/eslint-plugin": "8.72.1", - "@typescript-eslint/parser": "8.72.1", - "@typescript-eslint/typescript-estree": "8.72.1", - "@typescript-eslint/utils": "8.72.1" + "@typescript-eslint/eslint-plugin": "8.72.2", + "@typescript-eslint/parser": "8.72.2", + "@typescript-eslint/typescript-estree": "8.72.2", + "@typescript-eslint/utils": "8.72.2" }, "engines": { "node": "^18.18.0 || ^20.9.0 || >=21.1.0" diff --git a/package.json b/package.json index b10fe64..2e53091 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "create-b7-stack", "version": "0.1.0", - "description": "Scaffolds a new project from the B7 Stack template: Next.js, Express, Drizzle, and PostgreSQL in one npm workspace.", + "description": "Scaffolds a new project from the B7 Stack template: Next.js, Express, Drizzle, and PostgreSQL in one npm workspace, with an optional Electron desktop app.", "private": true, "type": "module", "bin": { @@ -9,7 +9,17 @@ }, "files": [ "dist", - "template" + "template", + "template-web-only", + "!template-web-only/variants.json", + "!template/**/node_modules", + "!template/**/.next", + "!template/**/.vite", + "!template/**/out", + "!template/**/coverage", + "!template/**/.env", + "!template/**/next-env.d.ts", + "!template/**/*.tsbuildinfo" ], "engines": { "node": ">=26" @@ -22,19 +32,20 @@ "lint:shell": "shellcheck .husky/pre-commit", "format": "prettier --write .", "format:check": "prettier --check .", - "preflight": "npm run format:check && npm run typecheck && npm run lint && npm run lint:shell && npm run lint:editor", - "lint:editor": "node template/scripts/check-editor-settings.ts" + "preflight": "npm run format:check && npm run typecheck && npm run lint && npm run lint:shell && npm run lint:editor && npm run lint:variants", + "lint:editor": "node template/scripts/check-editor-settings.ts", + "lint:variants": "node scripts/check-variants.ts" }, "devDependencies": { "@eslint/js": "^10.0.1", "@types/node": "^26.6.6", "eslint": "^10.14.0", - "globals": "^17.13.0", + "globals": "^17.14.0", "husky": "^9.1.7", "jiti": "^2.7.0", "lint-staged": "^17.6.0", - "prettier": "^3.9.10", + "prettier": "^3.10.0", "typescript": "~6.0.3", - "typescript-eslint": "^8.72.1" + "typescript-eslint": "^8.72.2" } } diff --git a/scripts/check-variants.ts b/scripts/check-variants.ts new file mode 100644 index 0000000..ff0ec16 --- /dev/null +++ b/scripts/check-variants.ts @@ -0,0 +1,85 @@ +import { createHash } from "node:crypto"; +import fs from "node:fs"; +import path from "node:path"; +import { styleText } from "node:util"; + +const root = path.join(import.meta.dirname, ".."); +const templateDir = path.join(root, "template"); +const variantsDir = path.join(root, "template-web-only"); +const manifestFile = path.join(variantsDir, "variants.json"); +const update = process.argv.includes("--update"); + +type Manifest = Record>; + +function hash(source: string) { + const text = fs.readFileSync(path.join(templateDir, source), "utf8"); + return createHash("sha256") + .update(text.replaceAll("\r\n", "\n")) + .digest("hex"); +} + +const manifest = JSON.parse(fs.readFileSync(manifestFile, "utf8")) as Manifest; +const variants = fs + .readdirSync(variantsDir, { encoding: "utf8", recursive: true }) + .filter( + (file) => + path.extname(file) !== ".json" && + fs.statSync(path.join(variantsDir, file)).isFile(), + ) + .map((file) => file.split(path.sep).join("/")); + +const problems: string[] = []; + +for (const variant of variants) { + if (!(variant in manifest)) { + problems.push( + `template-web-only/${variant} is not in variants.json. List it there with the template files it mirrors.`, + ); + } +} + +for (const [variant, sources] of Object.entries(manifest)) { + if (!variants.includes(variant)) { + problems.push( + `variants.json lists ${variant}, which is not in template-web-only.`, + ); + continue; + } + for (const [source, recorded] of Object.entries(sources)) { + if (!fs.existsSync(path.join(templateDir, source))) { + problems.push( + `variants.json says ${variant} mirrors template/${source}, which does not exist.`, + ); + continue; + } + const current = hash(source); + if (update) { + sources[source] = current; + } else if (current !== recorded) { + problems.push( + `template/${source} has changed since template-web-only/${variant} was last brought in line with it.`, + ); + } + } +} + +if (problems.length > 0) { + console.error( + styleText("red", problems.join("\n"), { stream: process.stderr }), + ); + if (!update) { + console.error( + "\nMake the same change in each variant named above where it applies, then record the template files as they are now:\n\n npm run lint:variants -- --update", + ); + } + process.exit(1); +} + +if (update) { + fs.writeFileSync(manifestFile, `${JSON.stringify(manifest, null, 2)}\n`); +} +console.log( + update + ? `Recorded the template files that ${String(variants.length)} web-only variants mirror.` + : `${String(variants.length)} web-only variants are in line with the template files they mirror.`, +); diff --git a/template-web-only/b7-stack-shared/package.json b/template-web-only/b7-stack-shared/package.json new file mode 100644 index 0000000..c83a5fb --- /dev/null +++ b/template-web-only/b7-stack-shared/package.json @@ -0,0 +1,3 @@ +{ + "description": "Types and Zod schemas shared by b7-stack-server and b7-stack-web." +} diff --git a/template-web-only/b7-stack-shared/tsconfig.json b/template-web-only/b7-stack-shared/tsconfig.json new file mode 100644 index 0000000..a3d2aed --- /dev/null +++ b/template-web-only/b7-stack-shared/tsconfig.json @@ -0,0 +1,5 @@ +{ + "compilerOptions": { + "lib": ["esnext"] + } +} diff --git a/template-web-only/b7-stack-web/app/_actions/notes.ts b/template-web-only/b7-stack-web/app/_actions/notes.ts new file mode 100644 index 0000000..c209cce --- /dev/null +++ b/template-web-only/b7-stack-web/app/_actions/notes.ts @@ -0,0 +1,76 @@ +"use server"; + +import { noteIdSchema, noteInputSchema } from "@b7-stack/shared"; +import { refresh } from "next/cache"; + +import * as notesApi from "@/app/_lib/notesApi.ts"; + +export interface NoteFormState { + body: string; + error: string | null; +} + +function readBody(formData: FormData): string { + const body = formData.get("body"); + return typeof body === "string" ? body : ""; +} + +export async function createNote( + _previousState: NoteFormState, + formData: FormData, +): Promise { + const body = readBody(formData); + const input = noteInputSchema.safeParse({ body }); + if (!input.success) { + return { body, error: input.error.issues[0]?.message ?? "Invalid note." }; + } + try { + await notesApi.createNote(input.data); + } catch (error) { + console.error(error); + return { body, error: "Could not save the note. Try again." }; + } + refresh(); + return { body: "", error: null }; +} + +export async function updateNote( + id: string, + _previousState: NoteFormState, + formData: FormData, +): Promise { + const body = readBody(formData); + const noteId = noteIdSchema.safeParse(id); + const input = noteInputSchema.safeParse({ body }); + if (!noteId.success || !input.success) { + return { + body, + error: input.error?.issues[0]?.message ?? "Invalid note.", + }; + } + try { + await notesApi.updateNote(noteId.data, input.data); + } catch (error) { + console.error(error); + return { body, error: "Could not update the note. Try again." }; + } + refresh(); + return { body: input.data.body, error: null }; +} + +export async function deleteNote( + id: string, +): Promise<{ error: string | null }> { + const noteId = noteIdSchema.safeParse(id); + if (!noteId.success) { + return { error: "Invalid note." }; + } + try { + await notesApi.deleteNote(noteId.data); + } catch (error) { + console.error(error); + return { error: "Could not delete the note. Try again." }; + } + refresh(); + return { error: null }; +} diff --git a/template-web-only/b7-stack-web/app/_components/HelloWorld.test.tsx b/template-web-only/b7-stack-web/app/_components/HelloWorld.test.tsx new file mode 100644 index 0000000..fc3a096 --- /dev/null +++ b/template-web-only/b7-stack-web/app/_components/HelloWorld.test.tsx @@ -0,0 +1,9 @@ +import { render, screen } from "@testing-library/react"; +import { expect, it } from "vitest"; + +import { StatusRow } from "@/app/_components/StatusRow.tsx"; + +it("renders Hello World", () => { + render(); + expect(screen.getByText("Hello World")).toBeInTheDocument(); +}); diff --git a/template/b7-stack-web/app/_components/NoteForm.tsx b/template-web-only/b7-stack-web/app/_components/NoteForm.tsx similarity index 100% rename from template/b7-stack-web/app/_components/NoteForm.tsx rename to template-web-only/b7-stack-web/app/_components/NoteForm.tsx diff --git a/template/b7-stack-web/app/_components/NoteItem.tsx b/template-web-only/b7-stack-web/app/_components/NoteItem.tsx similarity index 88% rename from template/b7-stack-web/app/_components/NoteItem.tsx rename to template-web-only/b7-stack-web/app/_components/NoteItem.tsx index d2fff52..739c68d 100644 --- a/template/b7-stack-web/app/_components/NoteItem.tsx +++ b/template-web-only/b7-stack-web/app/_components/NoteItem.tsx @@ -7,7 +7,7 @@ import { TrashIcon, XMarkIcon, } from "@heroicons/react/24/outline"; -import { useActionState, useState } from "react"; +import { useActionState, useEffect, useRef, useState } from "react"; import { deleteNote, @@ -20,6 +20,15 @@ const iconButtonClassName = export function NoteItem({ note }: { note: Note }) { const [editing, setEditing] = useState(false); + const editField = useRef(null); + + useEffect(() => { + const field = editField.current; + if (editing && field) { + field.focus(); + field.setSelectionRange(field.value.length, field.value.length); + } + }, [editing]); const [editState, editAction, editPending] = useActionState( async (previousState: NoteFormState, formData: FormData) => { @@ -47,11 +56,11 @@ export function NoteItem({ note }: { note: Note }) { Edit note