Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 54 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
# AGENTS.md

## Project Overview

`create-rescript-app` is the official CLI tool for scaffolding new ReScript applications. It supports creating projects from templates and adding ReScript to existing JavaScript projects. The tool is written in ReScript and distributed as a bundled Node.js CLI.

## Coding Style & Naming Conventions

- Make sure to use modern ReScript and not Reason syntax! Read https://rescript-lang.org/llms/manual/llm-small.txt to learn the language syntax.
- Formatting is enforced by `rescript format`; keep 2-space indentation and prefer pattern matching over chained conditionals.
- Module files are PascalCase (`Templates.res`), values/functions camelCase, types/variants PascalCase, and records snake_case fields only when matching external JSON.
- Keep `.resi` signatures accurate and minimal; avoid exposing helpers that are template-specific.
- When touching templates, mirror upstream defaults and keep package scripts consistent with the chosen toolchain.

## Package Manager Support

- Detects and supports npm, yarn, pnpm, and bun
- Handles existing project detection based on presence of `package.json`
- Adapts installation commands based on detected package manager

## Directory Structure

- **`src/`**: ReScript source files
- **`lib/`**: Generated build artifacts from ReScript compiler (do not edit)
- **`out/`**: Production bundle (`create-rescript-app.cjs`) for distribution
- **`templates/`**: Project starter templates (keep self-contained)
- **`bindings/`**: External library bindings (ClackPrompts, CompareVersions)

## Development Commands

- **`npm start`** - Run CLI directly from source (`src/Main.res.mjs`) for interactive testing and development
- **`npm run dev`** - Watch ReScript sources and rebuild automatically to `lib/` directory
- **`npm run prepack`** - Compile ReScript and bundle with Rollup into `out/create-rescript-app.cjs` (production build)
- **`npm run format`** - Apply ReScript formatter across all source files

## Testing and Validation

- **Manual Testing**: No automated test suite - perform smoke tests by running the CLI into a temp directory
- **Template Validation**: After changes, test each template type (basic/Next.js/Vite) to ensure templates bootstrap cleanly
- **Build Verification**: Run `npm run prepack` to ensure the production bundle builds correctly

## Build System

- **ReScript Compiler**: Outputs ES modules in-source (`src/*.res.mjs`) with configuration in `rescript.json`
- **Rollup Bundler**: Creates `out/create-rescript-app.cjs` CommonJS bundle for distribution

## Template Modification Guidelines

When modifying templates:

1. Maintain consistency with upstream toolchain defaults
2. Ensure package scripts match the chosen build tool (Vite, Next.js, etc.)
3. Keep templates self-contained with their own dependencies
4. Test template bootstrapping after modifications
57 changes: 45 additions & 12 deletions src/PackageManagers.res
Original file line number Diff line number Diff line change
@@ -1,21 +1,54 @@
open Node

type packageManager =
| Npm
| Yarn1
| YarnBerry
| Pnpm
| Bun

type packageManagerInfo = {
packageManager: packageManager,
command: string,
}

let defaultPackagerInfo = {packageManager: Npm, command: "npm"}

@scope(("process", "env"))
external npm_execpath: option<string> = "npm_execpath"

let compatiblePackageManagers = ["pnpm", "npm", "yarn", "bun"]
let getPackageManagerInfo = async () =>
switch npm_execpath {
| None => defaultPackagerInfo
| Some(execPath) =>
// #58: Windows: packageManager may be something like
// "C:\Program Files\nodejs\node_modules\npm\bin\npm-cli.js".
//
// Therefore, packageManager needs to be in quotes, and we need to prepend "node "
// if packageManager points to a JS file, otherwise the invocation will hang.
let maybeNode = execPath->String.endsWith("js") ? "node " : ""
let command = `${maybeNode}"${execPath}"`

let isCompatiblePackageManager = execPath => {
let filename = Path.parse(execPath).name
// Note: exec path may be something like
// /usr/local/lib/node_modules/npm/bin/npm-cli.js
// So we have to check for substrings here.
let filename = Path.parse(execPath).name->String.toLowerCase

// Note: exec path may be something like
// /usr/local/lib/node_modules/npm/bin/npm-cli.js
// So we have to check for substrings here.
compatiblePackageManagers->Array.some(pm => filename->String.includes(pm))
}
let packageManager = switch () {
| _ if filename->String.includes("npm") => Some(Npm)
| _ if filename->String.includes("yarn") =>
let versionResult = await Promisified.ChildProcess.exec(`${command} --version`)
let version = versionResult.stdout->String.trim
let isYarn1 = CompareVersions.compareVersions(version, "2.0.0")->Ordering.isLess

let getActivePackageManager = () =>
switch npm_execpath {
| Some(execPath) if isCompatiblePackageManager(execPath) => execPath
| _ => "npm"
Some(isYarn1 ? Yarn1 : YarnBerry)
| _ if filename->String.includes("pnpm") => Some(Pnpm)
| _ if filename->String.includes("bun") => Some(Bun)
| _ => None
}

switch packageManager {
| Some(packageManager) => {packageManager, command}
| None => defaultPackagerInfo
}
}
14 changes: 13 additions & 1 deletion src/PackageManagers.resi
Original file line number Diff line number Diff line change
@@ -1 +1,13 @@
let getActivePackageManager: unit => string
type packageManager =
| Npm
| Yarn1
| YarnBerry
| Pnpm
| Bun

type packageManagerInfo = {
packageManager: packageManager,
command: string,
}

let getPackageManagerInfo: unit => promise<packageManagerInfo>
43 changes: 34 additions & 9 deletions src/RescriptVersions.res
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
open Node

module P = ClackPrompts

let rescriptVersionRange = `11.x.x || 12.x.x`
Expand Down Expand Up @@ -73,8 +75,29 @@ let promptVersions = async () => {
{rescriptVersion, rescriptCoreVersion}
}

let ensureYarnNodeModulesLinker = async () => {
let yarnRcPath = Path.join2(Process.cwd(), ".yarnrc.yml")

if !Fs.existsSync(yarnRcPath) {
let nodeLinkerLine = "nodeLinker: node-modules"
let eol = Os.eol

await Fs.Promises.writeFile(yarnRcPath, `${nodeLinkerLine}${eol}`)
}
}

let removeNpmPackageLock = async () => {
let packageLockPath = Path.join2(Process.cwd(), "package-lock.json")

if Fs.existsSync(packageLockPath) {
await Fs.Promises.unlink(packageLockPath)
}
}

let installVersions = async ({rescriptVersion, rescriptCoreVersion}) => {
let packageManager = PackageManagers.getActivePackageManager()
let packageManagerInfo = await PackageManagers.getPackageManagerInfo()
let {command: packageManagerCommand, packageManager} = packageManagerInfo

let packages = switch rescriptCoreVersion {
| Some(rescriptCoreVersion) => [
`rescript@${rescriptVersion}`,
Expand All @@ -83,15 +106,17 @@ let installVersions = async ({rescriptVersion, rescriptCoreVersion}) => {
| None => [`rescript@${rescriptVersion}`]
}

// #58: Windows: packageManager may be something like
// "C:\Program Files\nodejs\node_modules\npm\bin\npm-cli.js".
//
// Therefore, packageManager needs to be in quotes, and we need to prepend "node "
// if packageManager points to a JS file, otherwise the invocation will hang.
let maybeNode = packageManager->String.endsWith("js") ? "node " : ""
let command = `${maybeNode}"${packageManager}" add ${packages->Array.join(" ")}`
if packageManager === YarnBerry {
await ensureYarnNodeModulesLinker()
}

let _ = await Node.Promisified.ChildProcess.exec(command)
let command = `${packageManagerCommand} add ${packages->Array.join(" ")}`

let _ = await Promisified.ChildProcess.exec(command)

if packageManager !== Npm {
await removeNpmPackageLock()
}
}

let esmModuleSystemName = ({rescriptVersion}) =>
Expand Down
3 changes: 3 additions & 0 deletions src/bindings/Node.res
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@ module Fs = {

@module("node:fs") @scope("promises")
external mkdir: string => promise<unit> = "mkdir"

@module("node:fs") @scope("promises")
external unlink: string => promise<unit> = "unlink"
}
}

Expand Down