diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 746fbf2..db42f1d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -28,10 +28,31 @@ jobs: "$RUNNER_TEMP/jpm-install/node_modules/.bin/jpm" --version "$RUNNER_TEMP/jpm-install/node_modules/.bin/jpm" --help + windows: + runs-on: windows-latest + strategy: + matrix: + node-version: [22, 24, 26] + steps: + - uses: actions/checkout@v7.0.1 + - uses: actions/setup-node@v7.1.0 + with: + node-version: ${{ matrix.node-version }} + cache: npm + - run: npm ci + - run: npm run build + - run: node --test test/windows.test.js + - name: Run the installed npm command in PowerShell + run: | + $archive = npm.cmd pack --ignore-scripts --silent + npm.cmd install --prefix "$env:RUNNER_TEMP/jpm-install" --ignore-scripts "./$archive" + if ($LASTEXITCODE) { exit $LASTEXITCODE } + & "$env:RUNNER_TEMP/jpm-install/node_modules/.bin/jpm.cmd" --version + # Branch protection requires these two check names. Both wait for the full matrix. check: if: ${{ always() }} - needs: runtime + needs: [runtime, windows] strategy: matrix: os: [ubuntu-latest, macos-latest] @@ -40,4 +61,5 @@ jobs: - name: Require all runtime checks to pass env: RESULT: ${{ needs.runtime.result }} - run: test "$RESULT" = success + WINDOWS: ${{ needs.windows.result }} + run: test "$RESULT" = success && test "$WINDOWS" = success diff --git a/CHANGELOG.md b/CHANGELOG.md index 7a9f5c5..970b9aa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ # Changelog +## 0.1.0-alpha.2 + +- Run jpm on native Windows with PowerShell, Maven Wrapper and verified Temurin ZIP downloads. [Release notes](docs/releases/0.1.0-alpha.2.md) + ## 0.1.0-alpha.1 (npm prerelease) - Published the first npm alpha as `@seriohhhh/java-npm`, then as the unscoped `java-npm-cli`. Install it with `npm install -g java-npm-cli@alpha` to get the `jpm` command. [Release notes](docs/releases/0.1.0-alpha.1.md) diff --git a/README.md b/README.md index c86d12e..d7bf7cb 100644 --- a/README.md +++ b/README.md @@ -20,13 +20,15 @@ If you already reach for `npm install` and `npm run dev`, jpm gives you a famili -Install the [npm alpha](https://www.npmjs.com/package/java-npm-cli) on macOS or Linux with Node.js 22 or later. +Install the [npm alpha](https://www.npmjs.com/package/java-npm-cli) on Windows, macOS or Linux with Node.js 22 or later. + +In PowerShell, use `npm.cmd` and `jpm.cmd` if script execution is restricted. [Windows quick start](docs/cli.md#windows-powershell) ```sh npm install --global java-npm-cli ``` -Prefer Homebrew? `brew install coderserio/tap/jpm` includes Node. The [tap](https://github.com/CoderSerio/homebrew-tap/blob/main/Formula/jpm.rb) currently ships `0.1.0-alpha.0` and npm ships `0.1.0-alpha.1`. +On macOS or Linux, `brew install coderserio/tap/jpm` installs jpm and Node together. @@ -77,7 +79,7 @@ If you edit the manifest yourself, run `jpm install` to synchronize the POM. jpm ## Working with the alpha -This release targets **new, single-module Spring MVC projects on macOS and Linux**. See the roadmap for existing Maven projects, Gradle, multi-module builds, and Windows. [Roadmap](https://github.com/CoderSerio/java-npm/blob/main/docs/roadmap.md) · [Tested environments](https://github.com/CoderSerio/java-npm/blob/main/VALIDATION.md) +This release targets **new, single-module Spring MVC projects on Windows, macOS and Linux**. See the roadmap for existing Maven projects, Gradle and multi-module builds. [Roadmap](https://github.com/CoderSerio/java-npm/blob/main/docs/roadmap.md) · [Tested environments](https://github.com/CoderSerio/java-npm/blob/main/VALIDATION.md) | When you want to… | Start here | | --- | --- | diff --git a/README.zh-CN.md b/README.zh-CN.md index cd7cee6..c6b6518 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -20,13 +20,15 @@ -在 macOS 或 Linux 上准备好 Node.js 22 或更高版本,然后安装 [npm 上的 alpha 版](https://www.npmjs.com/package/java-npm-cli)。 +在 Windows、macOS 或 Linux 上准备好 Node.js 22 或更高版本,然后安装 [npm 上的 alpha 版](https://www.npmjs.com/package/java-npm-cli)。 + +如果 PowerShell 提示禁止运行脚本,可以直接使用 `npm.cmd` 和 `jpm.cmd`。[Windows 快速开始](docs/cli.md#windows-powershell) ```sh npm install --global java-npm-cli ``` -习惯 Homebrew 的话,`brew install coderserio/tap/jpm` 会一起装好 Node。当前 [Homebrew 配方](https://github.com/CoderSerio/homebrew-tap/blob/main/Formula/jpm.rb)提供 `0.1.0-alpha.0`,npm 提供 `0.1.0-alpha.1`。 +在 macOS 或 Linux 上,`brew install coderserio/tap/jpm` 会一起安装 jpm 和 Node。 @@ -77,7 +79,7 @@ jpm build ## 使用 alpha 版 -当前支持在 **macOS 和 Linux 上新建单模块 Spring MVC 项目**。已有 Maven 项目的导入、Gradle、多模块构建和 Windows 的支持情况可以查阅路线图。[路线图](https://github.com/CoderSerio/java-npm/blob/main/docs/roadmap.md) · [已验证的环境](https://github.com/CoderSerio/java-npm/blob/main/VALIDATION.md) +当前支持在 **Windows、macOS 和 Linux 上新建单模块 Spring MVC 项目**。已有 Maven 项目的导入、Gradle 和多模块构建的支持情况可以查阅路线图。[路线图](https://github.com/CoderSerio/java-npm/blob/main/docs/roadmap.md) · [已验证的环境](https://github.com/CoderSerio/java-npm/blob/main/VALIDATION.md) | 想做什么 | 从这里开始 | | --- | --- | diff --git a/VALIDATION.md b/VALIDATION.md index 2ddb3ac..e65a51b 100644 --- a/VALIDATION.md +++ b/VALIDATION.md @@ -1,3 +1,11 @@ +# Windows 11 x64 原生验收 + +2026-12-05,使用隔离 npm prefix、Node 22.22.0、Temurin 21.0.13.1、Maven Wrapper 3.3.4 / Maven 3.10.2 和 Spring Boot 4.2.0。 + +- 通过 PowerShell 的 `jpm.cmd` 从 Spring Initializr 创建了项目。`jdk use 21` 安装了 Windows x64 JDK 并写入项目选择,`doctor --json` 的所有检查均通过。测试机直连 GitHub 下载中断,安装时通过临时 HTTPS 镜像传输原版 ZIP,并用 Adoptium 官方元数据校验。 +- 从 npm 归档安装后运行 `jpm.cmd dev`,终端能看到 Maven 和 Spring 日志。修改 Controller 后实际 HTTP 响应从 `Hello from jpm!` 变为 `Windows reload OK`。按 Ctrl+C 后监听端口释放。 +- 使用预热的依赖缓存运行 `jpm.cmd test` 和 `jpm.cmd build`,两个 Java 测试均通过,生成可执行的 Spring Boot JAR。 + # TypeScript / Node 26 alpha 验证 ## 文档与发布配套复核 diff --git a/docs/cli.md b/docs/cli.md index 6f7ba62..9fc6a21 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -1,6 +1,6 @@ # CLI reference -The npm package `java-npm-cli` installs the `jpm` command. Use `jpm --help` and `jpm --version` to inspect the installed CLI. Node 22+ and macOS/Linux are required. +The npm package `java-npm-cli` installs the `jpm` command. Use `jpm --help` and `jpm --version` to inspect the installed CLI. Node 22+ is required. Windows support starts with 0.1.0-alpha.2. Unless noted otherwise, project commands run from the directory containing the project's `package.json` and `mvnw`. @@ -89,9 +89,9 @@ eval "$(jpm jdk env)" - `jdk` lists installed JDKs, with the installation selected for jpm first. The current row has a blue accent and a `*` / `(current)` label, followed by the configuration source. This is jpm's selection, which may differ from the shell's `java`. Listing does not change it. - `jdk list` is an alias for `jdk`. Both detect installations and verify `java` and `javac`, without network access. `jdk list ` filters this local list; a current installation outside the filter is not shown. With no configuration, they list installations without marking one current. Invalid configuration or an unavailable selected JDK produces an error after displaying the installed versions. - `jdk list --remote` (or `-r`) queries Temurin releases for the current operating system and CPU. It shows the latest available GA release for each supported major version; `jdk list 21 -r` shows the available Java 21 patch/build history. Only JDKs are listed, not JREs or early-access builds. Installed/current labels require a matching detected Temurin runtime version. Remote listing fetches metadata only: it does not download JDK archives or change the selection. -- `jdk install [major]` (or `jdk i [major]`) installs a Temurin JDK to `~/.jpm/jdks/` and verifies size/checksum. It reuses an existing complete cached installation, without upgrading it or changing the selection. Omitting the version requires an existing selection. Installation supports x64 and arm64 on macOS/Linux. +- `jdk install [major]` (or `jdk i [major]`) installs a Temurin JDK to `~/.jpm/jdks/` and verifies size/checksum. It reuses an existing complete cached installation, without upgrading it or changing the selection. Omitting the version requires an existing selection. Windows uses the matching Adoptium ZIP when a build is available for the selected architecture. - `jdk use [--global]` reuses a usable local JDK of that major version, regardless of distribution. If none is found, it installs Temurin. It checks project target compatibility before downloading and saves the choice in project/user `.jpmrc` only after successful preparation; a failed download leaves the previous choice intact. `--global` saves the user default without imposing the current project's target. Neither form changes the project's compilation target. -- `jdk env [major]` prints quoted bash/zsh-compatible exports. It does not edit shell startup files; review the output before evaluating it. +- `jdk env [major]` prints quoted bash/zsh exports on macOS/Linux or PowerShell assignments on Windows. It does not edit shell startup files; review the output before evaluating it. Version arguments are major versions from 17 to 99. New downloads select the latest available Temurin release for that major. Although remote listing displays full patch/build versions, installing or pinning an exact build and selecting another distribution are not supported yet. There are no `--distribution`, `--all`, or `--versions` flags; use a positional major version and `--remote` to choose the listing scope. @@ -109,3 +109,20 @@ jpm doctor --json In a terminal, doctor shows an environment summary followed by labeled check results and repair suggestions. Warnings and errors remain visible even when colors are disabled. Redirected output keeps the plain checklist, and `doctor --json` always emits only the JSON report. JSON output has `ok` and `checks`; each check includes `name`, `status` (`ok`, `warn`, `error`), `detail`, and an optional `action`. Any error produces exit 1; warnings alone do not. Maven commands propagate failure status; signal exits use conventional codes such as 130 for SIGINT and 143 for SIGTERM. + +## Windows PowerShell + +Install Node.js 22 or newer. Install jpm with `npm.cmd install -g java-npm-cli`. Use `jpm.cmd` if your PowerShell policy blocks the npm-generated .ps1 shim. + +```powershell +jpm.cmd create hello-jpm --java 21 -y +cd hello-jpm +jpm.cmd jdk use 21 +jpm.cmd dev +# After stopping the app with Ctrl+C +jpm.cmd test +jpm.cmd build +``` + +jpm selects the JDK for its Maven children automatically. To select it for this PowerShell session as well, review `jpm.cmd jdk env` and run `(jpm.cmd jdk env) -join [Environment]::NewLine | Invoke-Expression`. +Windows uses the generated `mvnw.cmd`. Spaces in project paths and Maven argument values are supported. Use a project path without quotes, percent or exclamation marks. Arguments containing cmd control characters are rejected. diff --git a/docs/launch/README.md b/docs/launch/README.md index 8325d1c..f10a874 100644 --- a/docs/launch/README.md +++ b/docs/launch/README.md @@ -1,6 +1,6 @@ # Launch kit -Use these materials to introduce jpm or record a short walkthrough. The first npm alpha is available on macOS and Linux with Node.js 22+. +Use these materials to introduce jpm or record a short walkthrough. Use Node.js 22+ on Windows, macOS or Linux. The Windows workflow starts with 0.1.0-alpha.2. ## Public links diff --git a/docs/launch/announcement.md b/docs/launch/announcement.md index e626dea..d1b8554 100644 --- a/docs/launch/announcement.md +++ b/docs/launch/announcement.md @@ -1,6 +1,6 @@ # Announcement drafts -Draft copy for the first npm alpha. [Release notes](../releases/0.1.0-alpha.1.md) +Draft copy for the Windows release. [Release notes](../releases/0.1.0-alpha.2.md) ## 中文 @@ -17,9 +17,9 @@ jpm install jpm dev ``` -在 macOS 或 Linux 上安装 Node.js 22+ 后就可以开始。`jpm jdk use 21` 会优先使用本机已有的 JDK 21,缺少时下载 Temurin。首次创建和下载依赖需要联网。启动后,另开终端执行 `curl http://localhost:8080/` 就能看到 `{"message":"Hello from jpm!"}`。 +在 Windows、macOS 或 Linux 上安装 Node.js 22+ 后就可以开始。`jpm jdk use 21` 会优先使用本机已有的 JDK 21,缺少时下载 Temurin。首次创建和下载依赖需要联网。启动后,另开终端执行 `curl http://localhost:8080/` 就能看到 `{"message":"Hello from jpm!"}`。 -这一版聚焦新建的单模块 Spring MVC 项目,也提供 JDK 选择、依赖查看和 `doctor` 环境检查。Windows、Gradle、多模块以及任意现有 Maven 项目的导入还不在支持范围内。Alpha 阶段的命令和配置可能调整,欢迎带着具体场景来试用和反馈。 +这一版聚焦新建的单模块 Spring MVC 项目,也提供 JDK 选择、依赖查看和 `doctor` 环境检查。Gradle、多模块以及任意现有 Maven 项目的导入还不在支持范围内。Alpha 阶段的命令和配置可能调整,欢迎带着具体场景来试用和反馈。 [项目主页](https://coderserio.github.io/java-npm/) · [源码与文档](https://github.com/CoderSerio/java-npm) · [npm 包](https://www.npmjs.com/package/java-npm-cli) · MIT 许可 @@ -38,8 +38,8 @@ jpm install jpm dev ``` -Start with Node.js 22+ on macOS or Linux. `jpm jdk use 21` reuses a local JDK 21 or downloads Temurin. The initial setup needs network access. In a second terminal, run `curl http://localhost:8080/` to see `{"message":"Hello from jpm!"}`. +Start with Node.js 22+ on Windows, macOS or Linux. `jpm jdk use 21` reuses a local JDK 21 or downloads Temurin. The initial setup needs network access. In a second terminal, run `curl http://localhost:8080/` to see `{"message":"Hello from jpm!"}`. -This alpha focuses on new single-module Spring MVC projects. It also includes JDK selection, dependency inspection, and a `doctor` command. Windows, Gradle, multi-module builds, and arbitrary existing Maven project imports are outside its current scope. Commands and configuration may change during alpha; concrete bug reports and workflow feedback are welcome. +This alpha focuses on new single-module Spring MVC projects. It also includes JDK selection, dependency inspection, and a `doctor` command. Gradle, multi-module builds, and arbitrary existing Maven project imports are outside its current scope. Commands and configuration may change during alpha; concrete bug reports and workflow feedback are welcome. [Product page](https://coderserio.github.io/java-npm/) · [Source and docs](https://github.com/CoderSerio/java-npm) · [npm package](https://www.npmjs.com/package/java-npm-cli) · MIT licensed diff --git a/docs/launch/demo.md b/docs/launch/demo.md index eee9e8b..df89ca6 100644 --- a/docs/launch/demo.md +++ b/docs/launch/demo.md @@ -1,6 +1,6 @@ # Demo recording script -Aim for a 45–60 second edited walkthrough. Install jpm with `npm install -g java-npm-cli` and start in a new disposable directory. Use Node.js 22+ on macOS or Linux. Check network access, the Maven cache and the application port before recording. Label edits that shorten download time. +Aim for a 45–60 second edited walkthrough. Install jpm with `npm install -g java-npm-cli` and start in a new disposable directory. Use Node.js 22+ on Windows, macOS or Linux. Check network access, the Maven cache and the application port before recording. Label edits that shorten download time. | Segment | Action | Explanation | | --- | --- | --- | diff --git a/docs/releases/0.1.0-alpha.2.md b/docs/releases/0.1.0-alpha.2.md new file mode 100644 index 0000000..f39ad67 --- /dev/null +++ b/docs/releases/0.1.0-alpha.2.md @@ -0,0 +1,15 @@ +# jpm 0.1.0-alpha.2 + +Windows developers can create, run, test and package a single-module Spring Boot application with Node.js 22 or later and the generated Maven Wrapper. jpm discovers installed Windows JDKs and can download and verify a Temurin ZIP when needed. + +```powershell +npm.cmd install -g java-npm-cli +jpm.cmd create hello-jpm --java 21 -y +cd hello-jpm +jpm.cmd jdk use 21 +jpm.cmd dev +``` + +Stop the server with Ctrl+C, then use `jpm.cmd test` or `jpm.cmd build`. The [PowerShell guide](../cli.md#windows-powershell) covers selecting Java for the current terminal and supported Maven arguments. + +On macOS and Linux, install with npm or with `brew install coderserio/tap/jpm`. Existing Homebrew users can run `brew update` followed by `brew upgrade jpm`. diff --git a/docs/releasing.md b/docs/releasing.md index ff3de13..f571c8b 100644 --- a/docs/releasing.md +++ b/docs/releasing.md @@ -1,6 +1,6 @@ # Publishing an alpha -Maintainers publish `java-npm-cli` manually. The package installs the `jpm` command. Publish prereleases with `--tag alpha`. `latest` currently points to a `0.0.0-stage` placeholder; see the [first npm release](releases/0.1.0-alpha.1.md). Record the registry's actual tags before and after publishing. +Maintainers publish `java-npm-cli` manually. The package installs the `jpm` command. Publish prereleases with `--tag alpha`. Update `latest` when the release is approved for default installation. Record the registry's actual tags before and after publishing. ## Prepare the release diff --git a/docs/roadmap.md b/docs/roadmap.md index ee651e3..fa5eb06 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -8,17 +8,21 @@ The [first npm alpha](releases/0.1.0-alpha.1.md) is available for feedback on th - JSON-managed Maven dependencies and POM synchronization. - Development compilation/restart, tests, JAR builds, dependency inspection, and diagnostics. - JDK discovery, major-version selection, shell exports, and explicit verified Temurin installation. -- Node 22+, macOS/Linux, and a separately installed CLI. +- Node 22+, Windows/macOS/Linux, and a separately installed CLI. + +## Native Windows + +Version 0.1.0-alpha.2 adds support for native PowerShell, Maven Wrapper projects and verified Temurin ZIP installation. See the [Windows quick start](cli.md#windows-powershell). ## Next priorities -1. Exercise first-time project setup on fresh macOS and Linux machines, including JDK and Maven downloads. +1. Exercise first-time project setup on fresh Windows, macOS and Linux machines, including JDK and Maven downloads. 2. Gather feedback on installation, failure messages, and the create-to-dev workflow. 3. Stabilize the supported configuration and document any migrations between alpha releases. 4. Improve reproducibility and CI coverage where real user reports reveal gaps. ## Proposals requiring design work -Existing Maven project import, Gradle, Windows, multi-module projects, additional templates, exact JDK vendor/build pinning, and Java dependency locking need separate designs and tests. They are not part of the current support promise. +Existing Maven project import, Gradle, multi-module projects, additional templates, exact JDK vendor/build pinning, and Java dependency locking need separate designs and tests. They are not part of the current support promise. Use the feature-request template to explain a concrete workflow, current workaround, and expected benefit. Avoid treating this list as a commitment to implement every item. diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 4ac22e4..1a3924f 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -4,7 +4,7 @@ Start with `jpm --version`, `node --version`, and `jpm doctor --json` from the p | Symptom | What to check | | --- | --- | -| `jpm: command not found` | Run `npm install -g java-npm-cli`. On macOS or Linux, check that the `bin` directory under `npm prefix -g` is on your shell's PATH. | +| `jpm: command not found` | Run `npm install -g java-npm-cli`. On macOS or Linux, check that the `bin` directory under `npm prefix -g` is on your shell's PATH. On Windows, check that the directory printed by `npm.cmd prefix -g` is on PATH. If PowerShell blocks scripts, run `jpm.cmd`. | | npm cannot find `java-npm-cli` | Check the spelling: the package is `java-npm-cli`, not `jpm` or `java-npm`. Run `npm view java-npm-cli version --registry=https://registry.npmjs.org/`. If that succeeds, check your configured registry or mirror. [Published package](https://www.npmjs.com/package/java-npm-cli) | | Node 22 required | Select Node 22+ with your version manager. Check `node --version` in the same shell running jpm. | | No project manifest | Run project commands from the generated application's root, not the jpm source repository or a source subdirectory. | diff --git a/package-lock.json b/package-lock.json index a0a0bd3..0a6d7d5 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,22 +1,24 @@ { "name": "java-npm-cli", - "version": "0.1.0-alpha.1", + "version": "0.1.0-alpha.2", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "java-npm-cli", - "version": "0.1.0-alpha.1", + "version": "0.1.0-alpha.2", "license": "MIT", "dependencies": { "fast-xml-parser": "^5.12.0", - "tar": "^7.5.22" + "tar": "^7.5.22", + "yauzl": "^3.4.0" }, "bin": { "jpm": "bin/jpm.js" }, "devDependencies": { "@types/node": "26.6.6", + "@types/yauzl": "^3.4.0", "typescript": "7.0.2" }, "engines": { @@ -57,6 +59,16 @@ "undici-types": "~8.9.0" } }, + "node_modules/@types/yauzl": { + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/@types/yauzl/-/yauzl-3.4.0.tgz", + "integrity": "sha512-NRPn5w6h8dhcnmx3YIRQcqMywY/+nND/uOkJessedcrowO3C0AssHp3tMJpxKAwOhFOo0OV1y9VtsC5hbKKBAw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, "node_modules/@typescript/typescript-aix-ppc64": { "version": "7.0.2", "resolved": "https://registry.npmjs.org/@typescript/typescript-aix-ppc64/-/typescript-aix-ppc64-7.0.2.tgz", @@ -505,6 +517,12 @@ "node": ">=14.0.0" } }, + "node_modules/pend": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/pend/-/pend-1.2.0.tgz", + "integrity": "sha512-F3asv42UuXchdzt+xXqfW1OGlVBe+mxa2mqI0pg5yAHZPvFmY3Y6drSf/GQ1A86WgWEN9Kzh/WrgKa6iGcHXLg==", + "license": "MIT" + }, "node_modules/strnum": { "version": "2.5.1", "resolved": "https://registry.npmjs.org/strnum/-/strnum-2.5.1.tgz", @@ -601,6 +619,18 @@ "engines": { "node": ">=18" } + }, + "node_modules/yauzl": { + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/yauzl/-/yauzl-3.4.0.tgz", + "integrity": "sha512-jIH9yLR9wqr0wOS0TpBvo/g/2UgZH5qePVbjgRliiF0BYvOZyaBknKsF+x9Iht0O6sqgnB93rCICdOZFecJuDw==", + "license": "MIT", + "dependencies": { + "pend": "~1.2.0" + }, + "engines": { + "node": ">=12" + } } } } diff --git a/package.json b/package.json index a442bc2..c620b66 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "java-npm-cli", - "version": "0.1.0-alpha.1", + "version": "0.1.0-alpha.2", "description": "A familiar command-line workflow for Java and Spring Boot.", "type": "module", "bin": { @@ -33,10 +33,12 @@ ], "dependencies": { "fast-xml-parser": "^5.12.0", - "tar": "^7.5.22" + "tar": "^7.5.22", + "yauzl": "^3.4.0" }, "devDependencies": { "@types/node": "26.6.6", + "@types/yauzl": "^3.4.0", "typescript": "7.0.2" }, "repository": { diff --git a/site/guide/index.html b/site/guide/index.html index 5efad92..4cfe97e 100644 --- a/site/guide/index.html +++ b/site/guide/index.html @@ -39,9 +39,10 @@
  • See a change in your browser
  • Add a dependency and build
  • Your first Spring Boot app

    Start with an empty directory. By the end you’ll have a local HTTP endpoint, a passing test and a JAR you can run with Java.

    -

    Install jpm

    Use macOS or Linux with Node.js 22 or newer. The alpha supports new, single-module Spring MVC applications. Allow network access for the first setup.

    +

    Install jpm

    Use Windows, macOS or Linux with Node.js 22 or newer. The alpha supports new, single-module Spring MVC applications. Allow network access for the first setup.

    npm install -g java-npm-cli
     jpm --version
    +

    In PowerShell, if script execution is restricted, use npm.cmd and jpm.cmd. See the PowerShell commands for selecting Java in your shell.

    On Homebrew, brew install coderserio/tap/jpm installs the CLI and Node together. The formula has its own release version.

    Create the project

    jpm create hello-jpm --java 21 -y
     cd hello-jpm
    diff --git a/site/index.html b/site/index.html
    index 119370c..a298e45 100644
    --- a/site/index.html
    +++ b/site/index.html
    @@ -83,14 +83,14 @@ 

    Spring Boot, from

    If npm’s commands feel like home, jpm brings that workflow to Java. Create a Spring app, add Maven dependencies, and build a runnable JAR.

    - - + +
    npm i -g java-npm-cli
    -

    Node.js 22+ · macOS or Linux

    +

    Node.js 22+ · Windows, macOS or Linux

    @@ -200,7 +200,7 @@

    Before you install.

    Which projects can I use it for? -

    Start a new, single-module Spring MVC app on macOS or Linux. The alpha uses Spring Initializr for the template and Maven for the build. Existing POM imports, Gradle and multi-module projects are outside its current scope.

    +

    Start a new, single-module Spring MVC app on Windows, macOS or Linux. The alpha uses Spring Initializr for the template and Maven for the build. Existing POM imports, Gradle and multi-module projects are outside its current scope.

    Do I need a JDK or Maven already installed? diff --git a/site/zh/guide/index.html b/site/zh/guide/index.html index 2ea2fec..2cb707a 100644 --- a/site/zh/guide/index.html +++ b/site/zh/guide/index.html @@ -39,9 +39,10 @@
  • 看一次改动生效
  • 添加依赖并打包
  • 跑起你的第一个 Spring Boot 应用

    从一个空目录开始。跟着做完,你会得到一个本地 HTTP 接口、一份能通过的测试,以及一个可以用 Java 直接运行的 JAR。

    -

    安装 jpm

    准备好 macOS 或 Linux,以及 Node.js 22 或更高版本。当前 alpha 支持新建单模块 Spring MVC 应用,首次安装和创建项目需要联网。

    +

    安装 jpm

    准备好 Windows、macOS 或 Linux,以及 Node.js 22 或更高版本。当前 alpha 支持新建单模块 Spring MVC 应用,首次安装和创建项目需要联网。

    npm install -g java-npm-cli
     jpm --version
    +

    如果 PowerShell 提示禁止运行脚本,可以使用 npm.cmd 和 jpm.cmd。在当前终端选择 Java 的命令见 PowerShell 说明。

    也可以用 brew install coderserio/tap/jpm 一并安装 CLI 和 Node。Homebrew 的版本见 formula。

    创建项目

    jpm create hello-jpm --java 21 -y
     cd hello-jpm
    diff --git a/site/zh/index.html b/site/zh/index.html
    index 02f8dd7..a63af31 100644
    --- a/site/zh/index.html
    +++ b/site/zh/index.html
    @@ -83,14 +83,14 @@ 

    在终端里,

    习惯了 npm 的命令?用 jpm,你可以沿用这套工作方式,在本机创建 Spring 应用、添加 Maven 依赖,再构建出可运行的 JAR。

    - - + +
    npm i -g java-npm-cli
    -

    Node.js 22+ · macOS 或 Linux

    +

    Node.js 22+ · Windows、macOS 或 Linux

    @@ -200,7 +200,7 @@

    安装前,你可能想知道。

    适合哪些项目? -

    当前 alpha 支持在 macOS 或 Linux 上新建单模块 Spring MVC 应用。项目模板来自 Spring Initializr,构建交给 Maven。导入已有 POM、Gradle 和多模块项目尚不在支持范围内。

    +

    当前 alpha 支持在 Windows、macOS 或 Linux 上新建单模块 Spring MVC 应用。项目模板来自 Spring Initializr,构建交给 Maven。导入已有 POM、Gradle 和多模块项目尚不在支持范围内。

    需要提前安装 JDK 和 Maven 吗? diff --git a/src/cli.ts b/src/cli.ts index 55ee8e2..0d76d66 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -2,7 +2,7 @@ import { errorCode, errorMessage, isJavaMajor, isProjectName, isRecord } from '. import { parseArgs } from 'node:util'; import { lstat, readFile, realpath } from 'node:fs/promises'; import { createProject } from './create.js'; -import { resolveJdk, installJdk, listJdks, listRemoteJdks, majorVersion, shellEnvironment, type Jdk } from './jdk.js'; +import { resolveJdk, installJdk, listJdks, listRemoteJdks, majorVersion, shellSwitchCommand, shellEnvironment, type Jdk } from './jdk.js'; import { readJavaConfig, writeJavaConfig } from './config.js'; import { runMaven, runDev, wrapperPath } from './maven.js'; import { inspectDoctor } from './doctor.js'; @@ -30,11 +30,11 @@ const help = `jpm — a frontend-friendly Java workflow jpm jdk list [major] [-r] List local JDKs, or available Temurin releases with --remote jpm jdk install [major] Install Temurin without selecting it (alias: jdk i) jpm jdk use [--global] Install if missing, then select in .jpmrc (or ~/.jpmrc) - jpm jdk env [major] Print exports for eval "$(jpm jdk env)" + jpm jdk env [major] Print shell settings for the selected JDK Pass Maven arguments after --, for example jpm build -- -DskipTests. .jpmrc selects the JDK; package.json java.version remains the compile target. -Requires Node.js 22+. The first release supports macOS and Linux. +Requires Node.js 22+. Supports Windows, macOS and Linux. `; async function cliVersion(): Promise { @@ -257,7 +257,7 @@ export async function main(args = process.argv.slice(2)) { if (!values.global) requireCompatibleJdk(major, await compileTarget(cwd)); const jdk = await resolveJdk(major, { installIfMissing: true, onInstall: () => console.log(`JDK ${major} is not installed. Downloading Temurin ${major}…`) }); const file = await writeJavaConfig(cwd, jdk.version, { global: values.global }); - console.log(`Saved Java ${jdk.version} in ${file}.\nJDK: ${jdk.home}\nTo switch this terminal too, run: eval "$(jpm jdk env${values.global ? ` ${jdk.version}` : ''})"`); + console.log(`Saved Java ${jdk.version} in ${file}.\nJDK: ${jdk.home}\nTo switch this terminal too, run: ${shellSwitchCommand(values.global ? String(jdk.version) : '')}`); } else if (['env', 'install', 'i'].includes(action) && jdkArgs.length <= 1) { const { version } = await configuredJava(cwd, jdkArgs[0]); if (action === 'env') console.log(shellEnvironment(await resolveJdk(version))); diff --git a/src/create.ts b/src/create.ts index 86ad06e..471b271 100644 --- a/src/create.ts +++ b/src/create.ts @@ -1,3 +1,4 @@ +import { validWindowsPath } from './windows-archive.js'; import { errorCode, httpsBase, isJavaMajor, isProjectName, isRecord, secureFetch } from './validation.js'; import { chmod, lstat, mkdir, mkdtemp, readFile, readdir, rename, rm, writeFile } from 'node:fs/promises'; import path from 'node:path'; @@ -108,6 +109,7 @@ async function extractArchive(archive: Buffer, directory: string) { if (++entries > 256 || entry.size > MAX_EXPANDED || !['File', 'OldFile', 'Directory'].includes(entry.type) || entry.path.includes('\\') || entry.path.includes('\0') || entry.path.split('/').includes('..') || path.posix.isAbsolute(entry.path) || /^[a-zA-Z]:/.test(entry.path) + || (process.platform === 'win32' && normalized !== '.' && !validWindowsPath(normalized)) || normalized === '..' || normalized.startsWith('../') || seen.has(normalized)) { invalid = new Error('Spring Initializr archive contains unsafe or unsupported entries.'); } @@ -176,6 +178,7 @@ export async function createProject(name: string, options: CreateOptions = {}) { const groupId = options.group ?? 'com.example'; const packageName = options.packageName ?? `${groupId}.${name.replaceAll('-', '')}`; if (!javaPackage(groupId) || !javaPackage(packageName)) throw new Error('Group and package names must contain valid Java identifiers separated by dots.'); + if (process.platform === 'win32' && !validWindowsPath(name)) throw new Error('Choose a project name supported by Windows.'); const cwd = path.resolve(options.cwd ?? process.cwd()); const javaVersion = String(options.java ?? (await readJavaConfig(cwd)).version ?? '21'); if (!isJavaMajor(javaVersion)) throw new Error('jpm requires Java 17 or newer.'); diff --git a/src/doctor.ts b/src/doctor.ts index f59172a..91c9361 100644 --- a/src/doctor.ts +++ b/src/doctor.ts @@ -4,7 +4,7 @@ import { access, readFile, realpath, stat } from 'node:fs/promises'; import { homedir } from 'node:os'; import path from 'node:path'; import { readJavaConfig } from './config.js'; -import { resolveJdk } from './jdk.js'; +import { resolveJdk, shellSwitchCommand } from './jdk.js'; import { inspectPom, readProject } from './project.js'; interface DoctorOptions { @@ -22,7 +22,7 @@ export interface DoctorCheck { async function pathJava(env: NodeJS.ProcessEnv, cwd: string) { for (const directory of (env.PATH ?? '').split(path.delimiter)) { - const file = path.resolve(cwd, directory, 'java'); + const file = path.resolve(cwd, directory, process.platform === 'win32' ? 'java.exe' : 'java'); try { if (!(await stat(file)).isFile()) continue; await access(file, constants.X_OK); @@ -44,8 +44,8 @@ export async function inspectDoctor(cwd: string, options: DoctorOptions = {}) { const nodeMajor = Number(String(nodeVersion).replace(/^v/, '').split('.')[0]); add('Node.js', nodeMajor >= 22 ? 'ok' : 'error', String(nodeVersion), nodeMajor >= 22 ? undefined : 'Install Node.js 22 or newer.'); - const supportedPlatform = ['darwin', 'linux'].includes(platform); - add('Platform', supportedPlatform ? 'ok' : 'error', platform, supportedPlatform ? undefined : 'Run jpm on macOS or Linux; Windows is not supported yet.'); + const supportedPlatform = ['darwin', 'linux', 'win32'].includes(platform); + add('Platform', supportedPlatform ? 'ok' : 'error', platform, supportedPlatform ? undefined : 'Run jpm on Windows, macOS or Linux.'); let manifest; try { @@ -82,12 +82,12 @@ export async function inspectDoctor(cwd: string, options: DoctorOptions = {}) { try { const terminalHome = env.JAVA_HOME ? await realpath(env.JAVA_HOME).catch(() => env.JAVA_HOME) : undefined; const executable = await pathJava(env, cwd); - const selectedExecutable = await realpath(path.join(jdk.home, 'bin', 'java')); + const selectedExecutable = await realpath(path.join(jdk.home, 'bin', process.platform === 'win32' ? 'java.exe' : 'java')); const matches = terminalHome === jdk.home && executable === selectedExecutable; add('Shell environment', matches ? 'ok' : 'warn', matches ? 'JAVA_HOME and PATH select the same JDK as jpm.' : `jpm uses ${jdk.home}; JAVA_HOME is ${env.JAVA_HOME ?? 'unset'} and PATH Java is ${executable ?? 'not found'}.`, - matches ? undefined : 'To switch this terminal too, run: eval "$(jpm jdk env)"'); + matches ? undefined : 'To switch this terminal too, run: ' + shellSwitchCommand()); } catch (error) { add('Shell environment', 'warn', `Could not inspect the shell environment: ${errorMessage(error)}`, 'Review JAVA_HOME and PATH, then rerun jpm doctor.'); } @@ -95,12 +95,13 @@ export async function inspectDoctor(cwd: string, options: DoctorOptions = {}) { } const wrapperProblems = []; - const wrapper = path.join(cwd, 'mvnw'); + const wrapperName = platform === 'win32' ? 'mvnw.cmd' : 'mvnw'; + const wrapper = path.join(cwd, wrapperName); try { if (!(await stat(wrapper)).isFile()) throw new Error('not a file'); await access(wrapper, constants.X_OK); } catch (error) { - wrapperProblems.push(errorCode(error) === 'ENOENT' ? 'mvnw is missing' : 'mvnw is not an executable file'); + wrapperProblems.push(errorCode(error) === 'ENOENT' ? `${wrapperName} is missing` : `${wrapperName} is not an executable file`); } const wrapperProperties = path.join(cwd, '.mvn', 'wrapper', 'maven-wrapper.properties'); try { @@ -109,8 +110,8 @@ export async function inspectDoctor(cwd: string, options: DoctorOptions = {}) { } catch (error) { wrapperProblems.push(errorCode(error) === 'ENOENT' ? 'maven-wrapper.properties is missing' : `Cannot read maven-wrapper.properties: ${errorMessage(error)}`); } - add('Maven Wrapper', wrapperProblems.length ? 'error' : 'ok', wrapperProblems.length ? wrapperProblems.join('; ') : 'mvnw and its distribution configuration are present.', - wrapperProblems.length ? 'Restore the project Maven Wrapper files; if mvnw exists, make it executable with chmod +x mvnw.' : undefined); + add('Maven Wrapper', wrapperProblems.length ? 'error' : 'ok', wrapperProblems.length ? wrapperProblems.join('; ') : `${wrapperName} and its distribution configuration are present.`, + wrapperProblems.length ? (platform === 'win32' ? 'Restore mvnw.cmd and .mvn/wrapper/maven-wrapper.properties.' : 'Restore the project Maven Wrapper files; if mvnw exists, make it executable with chmod +x mvnw.') : undefined); if (manifest) { try { diff --git a/src/jdk.ts b/src/jdk.ts index 2465d48..57a1ca6 100644 --- a/src/jdk.ts +++ b/src/jdk.ts @@ -8,6 +8,7 @@ import path from 'node:path'; import { Readable, Transform } from 'node:stream'; import { pipeline } from 'node:stream/promises'; import { promisify } from 'node:util'; +import { extractWindowsJdk } from './windows-archive.js'; import { x as extract } from 'tar'; export interface Jdk { @@ -59,8 +60,8 @@ function adoptiumDownload(options: JdkOptions) { function settings(options: JdkOptions) { const platform = options.platform ?? process.platform; - if (!['darwin', 'linux'].includes(platform)) { - throw new Error('jpm 0.1 supports JDK management on macOS and Linux. Windows support is not available yet.'); + if (!['darwin', 'linux', 'win32'].includes(platform)) { + throw new Error('Unsupported platform for JDK management.'); } const homeDir = options.homeDir ?? homedir(); return { platform, homeDir, env: options.env ?? process.env, cacheRoot: options.cacheRoot ?? path.join(homeDir, '.jpm', 'jdks') }; @@ -74,11 +75,20 @@ async function output(command: string, args: string[], env: NodeJS.ProcessEnv, t function selectedEnvironment(home: string, env: NodeJS.ProcessEnv) { const bin = path.join(home, 'bin'); const previousBin = env.JAVA_HOME && path.join(env.JAVA_HOME, 'bin'); - const remaining = (env.PATH ? env.PATH.split(path.delimiter) : []).filter(entry => { + const childEnv = { ...env }; + // Node passes only one spelling of each environment key to Windows children. + const pathKey = process.platform === 'win32' ? Object.keys(childEnv).find(key => key.toUpperCase() === 'PATH') : 'PATH'; + const originalPath = pathKey && childEnv[pathKey]; + if (process.platform === 'win32') { + for (const key of Object.keys(childEnv)) { + if (['JAVA_HOME', 'PATH'].includes(key.toUpperCase())) delete childEnv[key]; + } + } + const remaining = (originalPath ? originalPath.split(path.delimiter) : []).filter(entry => { const normalized = entry && path.normalize(entry); return normalized !== bin && normalized !== previousBin; }); - return { ...env, JAVA_HOME: home, PATH: [bin, ...remaining].join(path.delimiter) }; + return { ...childEnv, JAVA_HOME: home, PATH: [bin, ...remaining].join(path.delimiter) }; } export function shellEnvironment(jdk: Pick, env = process.env) { @@ -86,19 +96,28 @@ export function shellEnvironment(jdk: Pick, env = process.env) { throw new Error('The JDK home must be an absolute path without a NUL or PATH separator.'); } const selected = selectedEnvironment(jdk.home, env); + if (process.platform === 'win32') { + const literal = (value: string) => "'" + value.replace(/['\u2018-\u201b]/g, "'$&") + "'"; + return `$env:JAVA_HOME = ${literal(selected.JAVA_HOME)}\n$env:Path = ${literal(selected.PATH)}\n`; + } const quote = (value: string) => `'${value.replaceAll("'", "'\\''")}'`; return `export JAVA_HOME=${quote(selected.JAVA_HOME)};\nexport PATH=${quote(selected.PATH)};\n`; } +export function shellSwitchCommand(version = '') { + const command = 'jpm jdk env' + (version ? ' ' + version : ''); + return process.platform === 'win32' ? `(${command}) -join [Environment]::NewLine | Invoke-Expression` : `eval "$(${command})"`; +} + async function inspectHome(candidate: string, version: number | undefined, env: NodeJS.ProcessEnv, timeout = 10_000): Promise { for (const home of [candidate, path.join(candidate, 'Contents', 'Home')]) { try { - const java = await output(path.join(home, 'bin', 'java'), ['-XshowSettings:properties', '-version'], env, timeout); + const java = await output(path.join(home, 'bin', process.platform === 'win32' ? 'java.exe' : 'java'), ['-XshowSettings:properties', '-version'], env, timeout); const javaVersion = java.match(/^\s*java\.specification\.version\s*=\s*(\d+)\s*$/m)?.[1] ?? java.match(/\bversion\s+"(?:1\.)?(\d+)/)?.[1]; const detectedVersion = Number(javaVersion); if (!Number.isSafeInteger(detectedVersion) || detectedVersion < 17 || (version !== undefined && detectedVersion !== version)) continue; - const javac = await output(path.join(home, 'bin', 'javac'), ['-version'], env, timeout); + const javac = await output(path.join(home, 'bin', process.platform === 'win32' ? 'javac.exe' : 'javac'), ['-version'], env, timeout); if (Number(javac.match(/\bjavac\s+(?:1\.)?(\d+)/)?.[1]) !== detectedVersion) continue; const resolvedHome = await realpath(home); const runtime = java.match(/^\s*java\.runtime\.version\s*=\s*(\S+)\s*$/m)?.[1] @@ -123,6 +142,8 @@ async function candidateHomes(options: JdkOptions, major?: number) { const sdkman = path.join(env.SDKMAN_CANDIDATES_DIR ?? path.join(homeDir, '.sdkman', 'candidates'), 'java'); const systemRoots = options.systemRoots ?? (platform === 'darwin' ? ['/Library/Java/JavaVirtualMachines', path.join(homeDir, 'Library', 'Java', 'JavaVirtualMachines'), '/System/Library/Java/JavaVirtualMachines'] + : platform === 'win32' + ? ['Java', 'Eclipse Adoptium', 'Microsoft', 'Amazon Corretto'].map(vendor => path.join(env.ProgramFiles ?? 'C:\\Program Files', vendor)) : ['/usr/lib/jvm']); const directories = [sdkman, ...systemRoots]; if (major === undefined) directories.unshift(cacheRoot); @@ -198,7 +219,7 @@ function downloadTarget(options: JdkOptions) { const arch = options.arch ?? process.arch; const architecture = arch === 'x64' ? 'x64' : arch === 'arm64' ? 'aarch64' : undefined; if (!architecture) throw new Error('JDK downloads support x64 and arm64 processors.'); - return { architecture, os: platform === 'darwin' ? 'mac' : 'linux' } as const; + return { architecture, os: platform === 'darwin' ? 'mac' : platform === 'win32' ? 'windows' : 'linux' } as const; } function archivePackage(archive: unknown, downloadBase: string) { @@ -304,7 +325,7 @@ export async function installJdk(version: string | number, options: JdkOptions = const { archive: { size: expectedSize, checksum, url } } = releasePackage(assets[0], major, target, downloadBase); const download = await secureFetch(request, url, { signal: AbortSignal.timeout(300_000) }); if (!download.ok || !download.body) throw new Error(`JDK download failed: HTTP ${download.status}.`); - const archivePath = path.join(staging, 'jdk.tar.gz'); + const archivePath = path.join(staging, target.os === 'windows' ? 'jdk.zip' : 'jdk.tar.gz'); const hash = createHash('sha256'); let bytes = 0; await pipeline(Readable.fromWeb(download.body), new Transform({ @@ -320,26 +341,8 @@ export async function installJdk(version: string | number, options: JdkOptions = } const unpacked = path.join(staging, 'unpacked'); await mkdir(unpacked); - let extractedBytes = 0; - let unsafeArchive = false; - await extract({ file: archivePath, cwd: unpacked, strict: true, preserveOwner: false, chmod: true, - filter(entryPath, entry) { - if (!('type' in entry)) return false; - extractedBytes += entry.size; - const linkpath = entry.linkpath ?? ''; - const link = entry.type === 'SymbolicLink' ? path.posix.join(path.posix.dirname(entryPath), linkpath) : linkpath; - if (entryPath.includes('\\') || path.posix.isAbsolute(entryPath) || entryPath.split('/').includes('..') - || !['File', 'Directory', 'SymbolicLink', 'Link'].includes(entry.type) - || (link && (path.posix.isAbsolute(linkpath) || link.includes('\\') || path.posix.normalize(link).split('/').includes('..') - || path.posix.normalize(link).split('/')[0] !== path.posix.normalize(entryPath).split('/')[0])) - || extractedBytes > 2 * 1024 * 1024 * 1024) { - unsafeArchive = true; - return false; - } - return true; - }, - }); - if (unsafeArchive) throw new Error('JDK archive contains an unsafe path, entry type, or excessive expanded data.'); + if (target.os === 'windows') await extractWindowsJdk(archivePath, unpacked); + else await extractTarJdk(archivePath, unpacked); const entries = await readdir(unpacked, { withFileTypes: true }); if (entries.length !== 1 || !entries[0].isDirectory()) throw new Error('JDK archive has an unexpected directory structure.'); const extractedRoot = path.join(unpacked, entries[0].name); @@ -355,3 +358,26 @@ export async function installJdk(version: string | number, options: JdkOptions = await rm(lock, { recursive: true, force: true }); } } + +async function extractTarJdk(archivePath: string, unpacked: string) { + let extractedBytes = 0; + let unsafeArchive = false; + await extract({ file: archivePath, cwd: unpacked, strict: true, preserveOwner: false, chmod: true, + filter(entryPath, entry) { + if (!('type' in entry)) return false; + extractedBytes += entry.size; + const linkpath = entry.linkpath ?? ''; + const link = entry.type === 'SymbolicLink' ? path.posix.join(path.posix.dirname(entryPath), linkpath) : linkpath; + if (entryPath.includes('\\') || path.posix.isAbsolute(entryPath) || entryPath.split('/').includes('..') + || !['File', 'Directory', 'SymbolicLink', 'Link'].includes(entry.type) + || (link && (path.posix.isAbsolute(linkpath) || link.includes('\\') || path.posix.normalize(link).split('/').includes('..') + || path.posix.normalize(link).split('/')[0] !== path.posix.normalize(entryPath).split('/')[0])) + || extractedBytes > 2 * 1024 * 1024 * 1024) { + unsafeArchive = true; + return false; + } + return true; + }, + }); + if (unsafeArchive) throw new Error('JDK archive contains an unsafe path, entry type, or excessive expanded data.'); +} diff --git a/src/maven.ts b/src/maven.ts index a4c3f29..d37bcab 100644 --- a/src/maven.ts +++ b/src/maven.ts @@ -1,5 +1,5 @@ import { errorCode } from './validation.js'; -import { spawn, type StdioOptions } from 'node:child_process'; +import { spawnSync, spawn, type StdioOptions } from 'node:child_process'; import { access, cp, mkdir, readdir, rm, stat, writeFile } from 'node:fs/promises'; import { constants } from 'node:fs'; import path from 'node:path'; @@ -16,17 +16,18 @@ interface MavenOptions { const signalCode = (signal: NodeJS.Signals | null) => signal && osConstants.signals[signal] ? 128 + osConstants.signals[signal] : 1; export async function wrapperPath(cwd: string) { - if (process.platform === 'win32') throw new Error('jpm currently supports macOS and Linux. Use WSL on Windows.'); - const wrapper = path.join(cwd, 'mvnw'); + const name = process.platform === 'win32' ? 'mvnw.cmd' : 'mvnw'; + const wrapper = path.join(cwd, name); try { if (!(await stat(wrapper)).isFile()) throw new Error('not a file'); await access(wrapper, constants.X_OK); } - catch { throw new Error('Maven Wrapper is missing or not executable. Run this command in a jpm project containing ./mvnw.'); } + catch { throw new Error(`Maven Wrapper is missing or not executable. Run this command in a jpm project containing ./${name}.`); } return wrapper; } function spawnMaven(wrapper: string, cwd: string, args: string[], options: MavenOptions) { + if (process.platform === 'win32') return spawnWindowsMaven(cwd, args, options); const child = spawn(wrapper, args, { cwd, env: options.env ?? process.env, stdio: options.stdio ?? 'inherit', detached: true, }); @@ -73,6 +74,41 @@ function spawnMaven(wrapper: string, cwd: string, args: string[], options: Maven } }; } +// A batch wrapper needs cmd.exe. Keep the wrapper path relative to cwd (which can +// contain spaces) and keep user arguments out of cmd expansion and control syntax. +function spawnWindowsMaven(cwd: string, args: string[], options: MavenOptions) { + // The generated wrapper interpolates its directory into a PowerShell literal. + if (/['%!"\r\n]/.test(cwd)) throw new Error('The Windows Maven Wrapper needs a project path without quotes, percent or exclamation marks.'); + if (args.some(arg => /[\x00-\x1f"%!&|<>^()]/.test(arg))) { + throw new Error('Maven arguments on Windows cannot contain cmd.exe control characters.'); + } + const system = path.join(process.env.SystemRoot ?? 'C:\\Windows', 'System32'); + const command = ['.\\mvnw.cmd', ...args.map(arg => `"${arg}"`)].join(' '); + // Detaching cmd.exe loses output from its JVM grandchildren on Windows. + // Pipe Maven output through jpm so it works with both a terminal and redirects. + const forwardOutput = options.stdio === undefined || options.stdio === 'inherit'; + const child = spawn(path.join(system, 'cmd.exe'), ['/d', '/v:off', '/s', '/c', `"${command}"`], { + cwd, env: options.env ?? process.env, stdio: forwardOutput ? ['inherit', 'pipe', 'pipe'] : options.stdio, + windowsHide: true, windowsVerbatimArguments: true, + }); + if (forwardOutput) { + child.stdout?.pipe(process.stdout, { end: false }); + child.stderr?.pipe(process.stderr, { end: false }); + } + let requestedSignal: NodeJS.Signals | undefined; + const done = new Promise((resolve, reject) => { + child.once('error', reject); + child.once('close', code => resolve(requestedSignal ? signalCode(requestedSignal) : code ?? 1)); + }); + return { done, stop(signal: NodeJS.Signals = 'SIGTERM') { + if (!child.pid || child.exitCode !== null || child.signalCode || requestedSignal) return; + requestedSignal = signal; + // The wrapper starts Maven, which can start another JVM for Spring Boot. + const result = spawnSync(path.join(system, 'taskkill.exe'), ['/pid', String(child.pid), '/t', '/f'], { windowsHide: true, stdio: 'ignore' }); + if (result.error) throw result.error; + } }; +} + function listenForStop(stop: (signal: NodeJS.Signals) => void, signal?: AbortSignal) { const onInt = () => stop('SIGINT'); const onTerm = () => stop('SIGTERM'); @@ -187,6 +223,7 @@ export async function runDev(cwd: string, options: MavenOptions = {}) { }, 200); }; let previous = await sourceSnapshot(sources); + const app = start(['spring-boot:run', ...(options.args ?? [])]); let polling = false; // Polling is portable and handles atomic editor saves without native watcher limits. poller = setInterval(async () => { @@ -202,7 +239,6 @@ export async function runDev(cwd: string, options: MavenOptions = {}) { } catch (error) { fatalError = error; stop(); } finally { polling = false; } }, 300); - const app = start(['spring-boot:run', ...(options.args ?? [])]); const unlisten = listenForStop(stop, options.signal); try { const code = await app.done; diff --git a/src/windows-archive.ts b/src/windows-archive.ts new file mode 100644 index 0000000..75c12d5 --- /dev/null +++ b/src/windows-archive.ts @@ -0,0 +1,34 @@ +import path from 'node:path'; +import { createWriteStream } from 'node:fs'; +import { mkdir } from 'node:fs/promises'; +import { pipeline } from 'node:stream/promises'; +import { openPromise } from 'yauzl'; + +// Reject NT device names, alternate streams and names Win32 silently normalizes. +export function validWindowsPath(name: string) { + return name.split('/').every(part => part.length > 0 + && !/[<>:"|?*\\\x00-\x1f]/.test(part) && !/[. ]$/.test(part) + && !/^(?:con|prn|aux|nul|conin\$|conout\$|(?:com|lpt)[1-9¹²³])(?: *\.|$)/i.test(part)); +} + +export async function extractWindowsJdk(archive: string, destination: string) { + // Windows ZIP writers may use backslashes. yauzl normalizes them before validating the path. + const zip = await openPromise(archive, { strictFileNames: false, validateEntrySizes: true }); + let expanded = 0; + try { + if (zip.entryCount > 100_000) throw new Error('JDK ZIP has too many entries.'); + for await (const entry of zip.eachEntry()) { + const directory = entry.fileName.endsWith('/'); + const name = entry.fileName.replace(/\/$/, ''); + const kind = entry.externalFileAttributes >>> 28; + if (!validWindowsPath(name) || (kind !== 0 && kind !== (directory ? 4 : 8)) || entry.isEncrypted()) { + throw new Error('Unsafe entry in JDK ZIP.'); + } + expanded += entry.uncompressedSize; + if (expanded > 2 * 1024 ** 3) throw new Error('Expanded JDK exceeds size limit.'); + const target = path.join(destination, name); + await mkdir(directory ? target : path.dirname(target), { recursive: true }); + if (!directory) await pipeline(await zip.openReadStreamPromise(entry), createWriteStream(target, { flags: 'wx' })); + } + } finally { zip.close(); } +} diff --git a/test/jdk.test.js b/test/jdk.test.js index 354b723..3ee1764 100644 --- a/test/jdk.test.js +++ b/test/jdk.test.js @@ -91,7 +91,7 @@ test('a valid JAVA_HOME does not probe fallback Java installations or PATH', asy const env = { JAVA_HOME: home, PATH: probeBin }; assert.equal((await resolveJdk(21, { ...options, env })).home, home); await assert.rejects(readFile(marker), { code: 'ENOENT' }); - await assert.rejects(resolveJdk(21, { ...options, platform: 'win32', env }), /Windows support/); + await assert.rejects(resolveJdk(21, { ...options, platform: 'freebsd', env }), /Unsupported platform/); }); test('optional discovery directories do not block cached JDK resolution or listing', async t => { @@ -194,9 +194,9 @@ test('rejects invalid version paths and unsupported platforms before downloading const options = { installIfMissing: true, onInstall: () => assert.fail('invalid request must not install'), fetch: () => assert.fail('must not download') }; await assert.rejects(resolveJdk('../21', options), /major version/); await assert.rejects(resolveJdk(100, options), /major version/); - await assert.rejects(resolveJdk(21, { ...options, platform: 'win32' }), /Windows support/); + await assert.rejects(resolveJdk(21, { ...options, platform: 'freebsd' }), /Unsupported platform/); await assert.rejects(installJdk('21.0.1'), /major version/); - await assert.rejects(installJdk(21, { platform: 'win32' }), /Windows support/); + await assert.rejects(installJdk(21, { platform: 'freebsd' }), /Unsupported platform/); }); test('checksum failure leaves no installation or staging files', async t => { @@ -340,8 +340,8 @@ test('remote catalog rejects malformed or failed metadata instead of claiming no change(release); await assert.rejects(listRemoteJdks(21, { ...options, fetch: async () => Response.json([release]) }), /invalid|unexpected/); } - for (const configuration of [{ platform: 'win32' }, { arch: 'ia32' }]) { - await assert.rejects(listRemoteJdks(21, { ...options, ...configuration, fetch: () => assert.fail('must not query') }), /Windows support|x64 and arm64/); + for (const configuration of [{ platform: 'freebsd' }, { arch: 'ia32' }]) { + await assert.rejects(listRemoteJdks(21, { ...options, ...configuration, fetch: () => assert.fail('must not query') }), /Unsupported platform|x64 and arm64/); } }); diff --git a/test/windows.test.js b/test/windows.test.js new file mode 100644 index 0000000..92ec1de --- /dev/null +++ b/test/windows.test.js @@ -0,0 +1,81 @@ +import assert from 'node:assert/strict'; +import { execFile } from 'node:child_process'; +import { mkdir, mkdtemp, readFile, writeFile, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import { setTimeout as delay } from 'node:timers/promises'; +import { promisify } from 'node:util'; +import test from 'node:test'; +import { shellEnvironment } from '../dist/jdk.js'; +import { runMaven } from '../dist/maven.js'; +import { extractWindowsJdk, validWindowsPath } from '../dist/windows-archive.js'; + +const execute = promisify(execFile); +const native = { skip: process.platform !== 'win32' }; + +test('archive names must map to ordinary Windows files', () => { + assert.ok(validWindowsPath('jdk-21.0.1/bin/java.exe')); + for (const name of ['..', 'bin/../java', 'NUL.txt', 'CON ', 'LPT1.class', 'foo:bar', 'a/b.', 'D:/tmp', 'one\\two']) { + assert.equal(validWindowsPath(name), false, name); + } +}); + +test('native Maven wrapper preserves spaces and propagates the exit code', native, async t => { + const cwd = await mkdtemp(path.join(tmpdir(), 'jpm wrapper ')); + t.after(() => rm(cwd, { recursive: true, force: true })); + await writeFile(path.join(cwd, 'mvnw.cmd'), '@echo off\r\nif "%~1"=="-Dmessage=hello world" exit /b 19\r\nexit /b 1\r\n'); + assert.equal(await runMaven(cwd, ['-Dmessage=hello world']), 19); +}); + +test('the Windows wrapper forwards Maven output to the calling terminal', native, async t => { + const cwd = await mkdtemp(path.join(tmpdir(), 'jpm output ')); + t.after(() => rm(cwd, { recursive: true, force: true })); + await writeFile(path.join(cwd, 'output.cjs'), "console.log('building'); console.error('diagnostic');"); + await writeFile(path.join(cwd, 'mvnw.cmd'), '@echo off\r\n"%JPM_TEST_NODE%" output.cjs\r\n'); + const maven = new URL('../dist/maven.js', import.meta.url).href; + const script = `import { runMaven } from ${JSON.stringify(maven)}; process.exitCode = await runMaven(process.cwd(), []);`; + const { stdout, stderr } = await execute(process.execPath, ['--input-type=module', '-e', script], { + cwd, env: { ...process.env, JPM_TEST_NODE: process.execPath }, + }); + assert.equal(stdout.trim(), 'building'); + assert.equal(stderr.trim(), 'diagnostic'); +}); + +test('stopping the Windows wrapper stops its long-lived child', native, async t => { + const cwd = await mkdtemp(path.join(tmpdir(), 'jpm stop ')); + t.after(() => rm(cwd, { recursive: true, force: true })); + await writeFile(path.join(cwd, 'app.cjs'), "require('fs').writeFileSync('pid', String(process.pid)); setInterval(() => {}, 60000);"); + await writeFile(path.join(cwd, 'mvnw.cmd'), '@echo off\r\n"%JPM_TEST_NODE%" app.cjs\r\n'); + const stop = new AbortController(); + const job = runMaven(cwd, [], { env: { ...process.env, JPM_TEST_NODE: process.execPath }, signal: stop.signal }); + try { + let pid; + for (let i = 0; i < 100 && !pid; i++) { + pid = Number(await readFile(path.join(cwd, 'pid'), 'utf8').catch(() => '')); + if (!pid) await delay(100); + } + assert.ok(pid, 'child started'); + stop.abort(); + assert.equal(await job, 143); + assert.throws(() => process.kill(pid, 0), { code: 'ESRCH' }); + } finally { stop.abort(); await job; } +}); + +test('PowerShell can apply the selected JDK environment literally', native, async () => { + const home = "C:\\tools\\Bob's JDK"; + const script = shellEnvironment({ home }, { Path: 'C:\\Windows' }); + const encoded = Buffer.from(script + '\nWrite-Output $env:JAVA_HOME\nWrite-Output $env:Path', 'utf16le').toString('base64'); + const { stdout } = await execute('powershell.exe', ['-NoProfile', '-EncodedCommand', encoded]); + assert.deepEqual(stdout.trim().split(/\r?\n/), [home, home + '\\bin;C:\\Windows']); +}); + + +test('native Temurin ZIP layout is preserved when installing on Windows', native, async t => { + const cwd = await mkdtemp(path.join(tmpdir(), 'jpm zip ')); + t.after(() => rm(cwd, { recursive: true, force: true })); + await mkdir(path.join(cwd, 'jdk-21', 'bin'), { recursive: true }); + await writeFile(path.join(cwd, 'jdk-21', 'bin', 'release.txt'), 'sample'); + await execute('powershell.exe', ['-NoProfile', '-Command', 'Compress-Archive -LiteralPath jdk-21 -DestinationPath jdk.zip'], { cwd }); + await extractWindowsJdk(path.join(cwd, 'jdk.zip'), path.join(cwd, 'unpacked')); + assert.equal(await readFile(path.join(cwd, 'unpacked', 'jdk-21', 'bin', 'release.txt'), 'utf8'), 'sample'); +});