diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 000000000..452763316 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,9 @@ +# Every text file is LF in the repo and in every checkout, Windows included. +# With core.autocrlf (the Git for Windows default) a checkout turned the gradlew +# and husky shell scripts into CRLF, which no shell can run, and a package packed +# from that tree shipped them that way. +* text=auto eol=lf + +# cmd.exe needs CRLF: labels in an LF batch file are not found reliably. +*.bat text eol=crlf +*.cmd text eol=crlf diff --git a/.github/workflows/node.js.yml b/.github/workflows/node.js.yml index 0ee504a47..1de5c0e48 100644 --- a/.github/workflows/node.js.yml +++ b/.github/workflows/node.js.yml @@ -1437,7 +1437,23 @@ jobs: # because a skipped platform (e.g. an android-only PR, where the iOS # and web jobs never run) must still count as fine here, not failure. coverage-summary: - needs: [detect-changes, lint, unit-and-contract-tests, web-integration-smoke, error-catalog, android-lint, android-unit-and-coverage, catalyst-ai-android-compile, catalyst-ai-android-integration, ios-swiftlint, ios-corelogic-and-coverage, ios-app-simulator-tests, android-release-build, ios-release-archive] + needs: + [ + detect-changes, + lint, + unit-and-contract-tests, + web-integration-smoke, + error-catalog, + android-lint, + android-unit-and-coverage, + catalyst-ai-android-compile, + catalyst-ai-android-integration, + ios-swiftlint, + ios-corelogic-and-coverage, + ios-app-simulator-tests, + android-release-build, + ios-release-archive, + ] if: always() runs-on: ubuntu-latest # Reads only the needs.* results and outputs: no checkout, no API calls. diff --git a/.release-meta.json b/.release-meta.json index a03b92440..23ddb9b55 100644 --- a/.release-meta.json +++ b/.release-meta.json @@ -1,7 +1,7 @@ { - "branch": "feat/app-info-open-in-browser", - "packages": { - "catalyst-core": "1.2.1", - "create-catalyst-app": "1.2.1" - } + "branch": "feat/app-info-open-in-browser", + "packages": { + "catalyst-core": "1.2.1", + "create-catalyst-app": "1.2.1" + } } diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 0ec9c186f..371bac7de 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -9,6 +9,11 @@ npm run setup # installs deps + creates local docs config Common commands: `npm run core:build`, `npm run core:test`, `npm run cca:test`, `npm run docs:build`. See [README](./README.md#contributing) for the sandbox-app flow. +On Windows, everything except `core:test`, `cca:test` and `test:example` runs from any +terminal. Those three are shell scripts, so run them from Git Bash, or use +`node scripts/test-windows-smoke.js`, which scaffolds, builds and runs an app. iOS builds +need a Mac. + ## Filing an issue New issues go through a template — pick the one that fits: diff --git a/README.md b/README.md index 4cd5adfaa..d0112238b 100644 --- a/README.md +++ b/README.md @@ -44,7 +44,7 @@ Useful starting points: ## Requirements - Node.js `20.4.0` or later for generated Catalyst apps. -- macOS or Linux for local development. +- macOS, Linux or Windows for local development. iOS builds need macOS. ## Repository diff --git a/docs/content/02-Guides and Tutorials/01-First Catalyst App/01-Installation.md b/docs/content/02-Guides and Tutorials/01-First Catalyst App/01-Installation.md index c0e0b748e..ce83b882f 100644 --- a/docs/content/02-Guides and Tutorials/01-First Catalyst App/01-Installation.md +++ b/docs/content/02-Guides and Tutorials/01-First Catalyst App/01-Installation.md @@ -6,9 +6,9 @@ id: installation ### System Requirements * Node version [20.4.0](https://nodejs.org/docs/latest-v20.x/api/index.html) or later -* Supported platforms: macOS, Linux. +* Supported platforms: macOS, Linux, Windows. -For windows users, we recommend using Windows Subsystem for Linux (WSL) for the best development experience. +On Windows, Catalyst runs natively in PowerShell, Command Prompt or Git Bash, so WSL is not needed. Every command works there except the iOS ones, which need macOS and Xcode. ### Automatic Installation diff --git a/docs/content/02-Guides and Tutorials/02-First Universal App/02-Running-Universal-Apps.md b/docs/content/02-Guides and Tutorials/02-First Universal App/02-Running-Universal-Apps.md index c01dfb779..93627b6e2 100644 --- a/docs/content/02-Guides and Tutorials/02-First Universal App/02-Running-Universal-Apps.md +++ b/docs/content/02-Guides and Tutorials/02-First Universal App/02-Running-Universal-Apps.md @@ -61,6 +61,8 @@ npm run ios -- --device Without a terminal and without `--device`, the app always runs on the emulator or simulator. +On Windows and Linux, `npm run ios` stops with [IOS-007](/errors/IOS/IOS-007), and `catalyst buildApp` skips iOS and builds Android. + --- ## How the app reaches the dev server diff --git a/docs/content/02-Guides and Tutorials/03-Building Pet Adoption App/01-installation.md b/docs/content/02-Guides and Tutorials/03-Building Pet Adoption App/01-installation.md index 501682770..3a09b79c9 100644 --- a/docs/content/02-Guides and Tutorials/03-Building Pet Adoption App/01-installation.md +++ b/docs/content/02-Guides and Tutorials/03-Building Pet Adoption App/01-installation.md @@ -10,7 +10,7 @@ sidebar_position: 1 ## System Requirements - Node.js version 20.4.0 or later -- macOS or Linux (Windows users should use WSL) +- macOS, Linux or Windows --- diff --git a/docs/content/02-Guides and Tutorials/04-Android-Emulator-Setup.md b/docs/content/02-Guides and Tutorials/04-Android-Emulator-Setup.md index 90f536c5e..4b1e57ee6 100644 --- a/docs/content/02-Guides and Tutorials/04-Android-Emulator-Setup.md +++ b/docs/content/02-Guides and Tutorials/04-Android-Emulator-Setup.md @@ -12,9 +12,9 @@ id: android-emulator-setup ## Prerequisites -- macOS or Linux +- macOS, Linux or Windows - About 10 GB of free disk space for the SDK and a system image -- Homebrew on macOS if you have no JDK yet. On Linux, install a JDK 17 or 21 package (for example `openjdk-17-jdk`) yourself +- Homebrew on macOS if you have no JDK yet. On Linux, install a JDK 17 or 21 package (for example `openjdk-17-jdk`) yourself. On Windows, Android Studio's bundled JDK is enough; without Android Studio, install one with `winget install Microsoft.OpenJDK.17` --- @@ -22,8 +22,8 @@ id: android-emulator-setup Every `npm run android` and `npm run android:release` checks the toolchain and installs only what is missing. Each install asks first; press Enter to accept the default answer. -1. Java. Catalyst looks for JDK 17 to 23 in `JAVA_HOME`, then `/usr/libexec/java_home`, then the runtime bundled with Android Studio, and prefers 21, then 17. A JDK 24 or newer is skipped, because Gradle 8.13 cannot run on it. On macOS with none found, it offers to run `brew install --cask zulu@17`. Your shell profile is never edited; the JDK is passed to Gradle and the SDK tools directly. -2. Android SDK. It uses `WEBVIEW_CONFIG.android.sdkPath`, then `ANDROID_HOME`, then `ANDROID_SDK_ROOT`, then `~/Library/Android/sdk` (macOS) or `~/Android/Sdk` (Linux). It never asks for a path and never writes one to `config/config.json`. When packages are missing it downloads the Android command-line tools, checks them against their published SHA-256, and installs `platform-tools`, `platforms;android-36` and `build-tools;36.0.0`, plus `emulator` when the app runs on one. +1. Java. Catalyst looks for JDK 17 to 23 in `JAVA_HOME`, then `/usr/libexec/java_home` on macOS, then the runtime bundled with Android Studio, then (on Linux and Windows) the `java` on your `PATH`, and prefers 21, then 17. A JDK 24 or newer is skipped, because Gradle 8.13 cannot run on it. On macOS with none found, it offers to run `brew install --cask zulu@17`. Your shell profile is never edited; the JDK is passed to Gradle and the SDK tools directly. +2. Android SDK. It uses `WEBVIEW_CONFIG.android.sdkPath`, then `ANDROID_HOME`, then `ANDROID_SDK_ROOT`, then `~/Library/Android/sdk` (macOS), `%LOCALAPPDATA%\Android\Sdk` (Windows) or `~/Android/Sdk` (Linux). It never asks for a path and never writes one to `config/config.json`. When packages are missing it downloads the Android command-line tools, checks them against their published SHA-256, and installs `platform-tools`, `platforms;android-36` and `build-tools;36.0.0`, plus `emulator` when the app runs on one. 3. Licences. The first install shows the Android SDK licences for you to review and accept. 4. Emulator. An existing emulator is reused: `android.emulatorName` when it is set, else the one you used last, else the first one found. With none, Catalyst installs the API 36 Google APIs system image for your CPU (arm64 on Apple silicon, x86_64 elsewhere, about 1.5 GB) and creates `catalyst-api36` with a Pixel 7 profile. @@ -76,6 +76,24 @@ All of these are optional: | `emulatorName` | Emulator (AVD) to use. If it does not exist, Catalyst warns and uses another one, or creates `catalyst-api36` | | `sdkPath` | Android SDK location, when it is not in one of the places above | +### Windows + +The SDK is usually at `C:\Users\yourname\AppData\Local\Android\Sdk`. In `config.json`, double the backslashes or use forward slashes: + +```json +{ + "WEBVIEW_CONFIG": { + "android": { + "sdkPath": "C:/Users/yourname/AppData/Local/Android/Sdk" + } + } +} +``` + +The emulator needs the Windows Hypervisor Platform. If it does not start, run `emulator -accel-check` from the SDK's `emulator` folder. It reports what is missing. + +Gradle writes long paths under `node_modules`. If a build fails with a path that is too long, move the app closer to the root of the drive, for example `C:\dev\my-app`, or [enable long paths in Windows](https://learn.microsoft.com/en-us/windows/win32/fileio/maximum-file-path-limitation#enable-long-paths-in-windows-10-version-1607-and-later). + --- ## Run the app diff --git a/docs/content/16-CLI.md b/docs/content/16-CLI.md index c1814d87a..5f5252fe4 100644 --- a/docs/content/16-CLI.md +++ b/docs/content/16-CLI.md @@ -100,6 +100,8 @@ In a terminal, a release asks once for a missing or placeholder app id and a mis See [Universal App Deployment](/content/Deployment/universal-app-deployment) for the release flow and CI, and [Running Universal Apps](/content/Guides%20and%20Tutorials/First%20Universal%20App/RunUniversalApp) for development. +The iOS commands need macOS and Xcode. On Windows and Linux, `catalyst buildApp` and `catalyst setupEmulator` skip iOS and run Android, and `buildApp:ios` and `setupEmulator:ios` exit with [IOS-007](/errors/IOS/IOS-007). + ## Production Web Flow 1. Run `catalyst build`. diff --git a/docs/content/17-FAQs.md b/docs/content/17-FAQs.md index d3278a9fb..d42967129 100644 --- a/docs/content/17-FAQs.md +++ b/docs/content/17-FAQs.md @@ -6,6 +6,10 @@ slug: faqs # FAQs +## Does Catalyst work on Windows? + +Yes, natively, in PowerShell, Command Prompt or Git Bash, so WSL is not needed. Every command works except the iOS ones, which need macOS and Xcode. For Android, see the Windows notes in the [Android Emulator Setup](/content/Guides%20and%20Tutorials/android-emulator-setup) guide. + ## Where should `config/config.json` live? Keep the file at `config/config.json` inside the project root. Catalyst reads runtime and build settings from this path. diff --git a/errors/ANDROID/ANDROID-007.md b/errors/ANDROID/ANDROID-007.md index d46583c2a..76f8aeb0a 100644 --- a/errors/ANDROID/ANDROID-007.md +++ b/errors/ANDROID/ANDROID-007.md @@ -8,8 +8,8 @@ No JDK 17 to 23 found ## Details -Gradle 8.13 and the Android SDK tools need JDK 17 to 23. None was found in JAVA_HOME, /usr/libexec/java_home or Android Studio's bundled runtime (a JDK 24 or newer is skipped), and none could be installed: this is not macOS, Homebrew is missing, or the install was declined. +Gradle 8.13 and the Android SDK tools need JDK 17 to 23. None was found in JAVA_HOME, /usr/libexec/java_home, Android Studio's bundled runtime, the java on PATH or (on Windows) the usual JDK install folders (a JDK 24 or newer is skipped), and none could be installed: this is not macOS, Homebrew is missing, or the install was declined. ## Suggested action -Install JDK 17 or 21 (macOS: brew install --cask zulu@17; Linux: your distribution's openjdk-17-jdk package) and set JAVA_HOME, or run catalyst buildApp:android in a terminal, or with --yes, to install it. +Install JDK 17 or 21 (macOS: brew install --cask zulu@17; Linux: your distribution's openjdk-17-jdk package; Windows: Android Studio, or winget install Microsoft.OpenJDK.17) and set JAVA_HOME, or on macOS run catalyst buildApp:android in a terminal, or with --yes, to install it. diff --git a/errors/IOS/IOS-007.md b/errors/IOS/IOS-007.md new file mode 100644 index 000000000..0725801e1 --- /dev/null +++ b/errors/IOS/IOS-007.md @@ -0,0 +1,15 @@ +# IOS-007 + +**Category:** IOS + +## Message + +iOS builds need macOS and Xcode + +## Details + +buildApp:ios and setupEmulator:ios drive Xcode and the iOS Simulator, which only run on macOS. Everything else, including the Android commands, works on this machine. + +## Suggested action + +Build the iOS app on a Mac or a macOS CI runner. Plain catalyst buildApp and catalyst setupEmulator skip iOS on other systems and carry on with Android. diff --git a/errors/index.json b/errors/index.json index 13ef1b7c5..506feded2 100644 --- a/errors/index.json +++ b/errors/index.json @@ -223,6 +223,13 @@ "suggestedAction": "Export public/icon.png without an alpha channel (flatten it onto a solid background), then rebuild.", "docUrl": "https://github.com/tata1mg/catalyst-core/blob/main/errors/IOS/IOS-006.md" }, + "IOS-007": { + "category": "IOS", + "message": "iOS builds need macOS and Xcode", + "details": "buildApp:ios and setupEmulator:ios drive Xcode and the iOS Simulator, which only run on macOS. Everything else, including the Android commands, works on this machine.", + "suggestedAction": "Build the iOS app on a Mac or a macOS CI runner. Plain catalyst buildApp and catalyst setupEmulator skip iOS on other systems and carry on with Android.", + "docUrl": "https://github.com/tata1mg/catalyst-core/blob/main/errors/IOS/IOS-007.md" + }, "IOS-010": { "category": "IOS", "message": "iOS code signing is not set up", @@ -296,8 +303,8 @@ "ANDROID-007": { "category": "ANDROID", "message": "No JDK 17 to 23 found", - "details": "Gradle 8.13 and the Android SDK tools need JDK 17 to 23. None was found in JAVA_HOME, /usr/libexec/java_home or Android Studio's bundled runtime (a JDK 24 or newer is skipped), and none could be installed: this is not macOS, Homebrew is missing, or the install was declined.", - "suggestedAction": "Install JDK 17 or 21 (macOS: brew install --cask zulu@17; Linux: your distribution's openjdk-17-jdk package) and set JAVA_HOME, or run catalyst buildApp:android in a terminal, or with --yes, to install it.", + "details": "Gradle 8.13 and the Android SDK tools need JDK 17 to 23. None was found in JAVA_HOME, /usr/libexec/java_home, Android Studio's bundled runtime, the java on PATH or (on Windows) the usual JDK install folders (a JDK 24 or newer is skipped), and none could be installed: this is not macOS, Homebrew is missing, or the install was declined.", + "suggestedAction": "Install JDK 17 or 21 (macOS: brew install --cask zulu@17; Linux: your distribution's openjdk-17-jdk package; Windows: Android Studio, or winget install Microsoft.OpenJDK.17) and set JAVA_HOME, or on macOS run catalyst buildApp:android in a terminal, or with --yes, to install it.", "docUrl": "https://github.com/tata1mg/catalyst-core/blob/main/errors/ANDROID/ANDROID-007.md" }, "ANDROID-008": { @@ -727,4 +734,4 @@ "suggestedAction": "Remove or rename the existing .gitignore before running again, or ignore this warning.", "docUrl": "https://github.com/tata1mg/catalyst-core/blob/main/errors/CCA/CCA-009.md" } -} \ No newline at end of file +} diff --git a/examples/error-catalog/README.md b/examples/error-catalog/README.md index b17b02129..cafef1d0a 100644 --- a/examples/error-catalog/README.md +++ b/examples/error-catalog/README.md @@ -1,10 +1,10 @@ # Error Catalog Example (`examples/error-catalog`) A standalone Catalyst app whose scenarios reproduce a **real developer -mistake** for every one of the framework's 104 error codes, then assert the dev +mistake** for every one of the framework's 105 error codes, then assert the dev sees the right coded error (message + doc URL). -- **`npm run test:error`**: runs all 104, one block per code: the mistake, what +- **`npm run test:error`**: runs all 105, one block per code: the mistake, what the dev sees, and PASS / FAIL / SKIP. This is the command to run. - **`npm run demo`** — interactive walk of the server-reachable scenarios only (the `cli` / `http` tiers); other kinds are contract assertions, see @@ -13,7 +13,7 @@ sees the right coded error (message + doc URL). ## Coverage -104 / 104 codes accounted for: **69 reproduced by a scenario**, **35 in the +105 / 105 codes accounted for: **69 reproduced by a scenario**, **36 in the LEDGER** as `not-example-reproducible` — each with a specific reason below, not a hand-wave. @@ -55,7 +55,7 @@ a hand-wave. terminalProgress.js import casing` — the ANDROID-000 / IOS-000 scenarios here are what surfaced it (first CI exercise of `buildApp:*` on Linux). -## The 104-code ledger +## The 105-code ledger | Code | Dev mistake | Tier | What the dev sees | Coverage | | -------------------- | ---------------------------------------------------------------------------- | -------------- | ----------------------------------------------------------------------- | ------------------------------------ | @@ -96,6 +96,7 @@ terminalProgress.js import casing` — the ANDROID-000 / IOS-000 scenarios here | `IOS-004` | — | — | No iOS simulator runtime installed | **LEDGER: not-example-reproducible** | | `IOS-005` | — | — | App icon is not usable | **LEDGER: not-example-reproducible** | | `IOS-006` | — | — | App icon has transparency | **LEDGER: not-example-reproducible** | +| `IOS-007` | iOS build on a machine that is not a Mac | build-native | iOS builds need macOS and Xcode | **LEDGER: not-example-reproducible** | | `IOS-010` | Signed release build with no development team | build-native | iOS code signing is not set up | scenario | | `IOS-011` | App Store Connect API key in credentials/ios/ with no issuer ID | build-native | App Store Connect API key settings are incomplete or wrong | scenario | | `IOS-012` | — | — | Manual signing inputs are incomplete or wrong | **LEDGER: not-example-reproducible** | @@ -172,7 +173,7 @@ terminalProgress.js import casing` — the ANDROID-000 / IOS-000 scenarios here npm run sync-core npm run sync-packages -# All 104, human-readable +# All 105, human-readable npm run test:error # One code diff --git a/examples/error-catalog/scenarios/build-native.js b/examples/error-catalog/scenarios/build-native.js index bfed4988d..a01073922 100644 --- a/examples/error-catalog/scenarios/build-native.js +++ b/examples/error-catalog/scenarios/build-native.js @@ -122,6 +122,9 @@ export const buildNativeScenarios = [ title: "iOS build failed in upstream toolchain step", tier: "build-native", kind: "build-native", + // Anywhere else buildApp:ios stops at IOS-007 once the config is resolved, + // before Xcode runs. + platforms: ["darwin"], break: (appDir) => { const confPath = path.join(appDir, "config", "config.json") const conf = JSON.parse(fs.readFileSync(confPath, "utf8")) @@ -212,6 +215,18 @@ export const buildNativeScenarios = [ }, expect: { inOutput: ["IOS-013"], exitNonZero: true }, }, + { + code: "IOS-007", + title: "iOS build on a machine that is not a Mac", + tier: "build-native", + kind: "build-native", + platforms: ["linux", "win32"], + // Nothing to break: being on this machine is the mistake. + break: () => {}, + restore: () => {}, + run: { cmd: "catalyst", args: ["buildApp:ios"], kind: "build-native" }, + expect: { inOutput: ["IOS-007", "macOS"], exitNonZero: true }, + }, ] export default buildNativeScenarios diff --git a/examples/error-catalog/scripts/demo.js b/examples/error-catalog/scripts/demo.js index ae4698be5..61cdebed5 100644 --- a/examples/error-catalog/scripts/demo.js +++ b/examples/error-catalog/scripts/demo.js @@ -223,7 +223,7 @@ async function main() { // The interactive demo only walks scenarios that surface an error from // a running server / the CLI. client, mapping, build, cca-cli and // build-native kinds are contract assertions — run `npm run test:error` - // to see those (it covers all 75). Skip them here rather than crash on + // to see those (it covers all 76). Skip them here rather than crash on // their missing break()/run. const SERVER_KINDS = new Set(["cli-startup", "http"]) diff --git a/examples/error-catalog/scripts/test-error.js b/examples/error-catalog/scripts/test-error.js index 2910aa3b3..7a0c3a2e0 100644 --- a/examples/error-catalog/scripts/test-error.js +++ b/examples/error-catalog/scripts/test-error.js @@ -472,6 +472,10 @@ async function main() { status = "SKIP" detail = "Validator exists, no live call site" skippedCount++ + } else if (scen.platforms && !scen.platforms.includes(process.platform)) { + status = "SKIP" + detail = `Not reachable on ${process.platform}` + skippedCount++ } else if (scen.kind === "client" || scen.kind === "mapping") { const passed = vitestAssertionMap.get(code) if (passed === true) { diff --git a/examples/error-catalog/test/scenarios.test.ts b/examples/error-catalog/test/scenarios.test.ts index f93b8e3ec..bbfc084a8 100644 --- a/examples/error-catalog/test/scenarios.test.ts +++ b/examples/error-catalog/test/scenarios.test.ts @@ -64,6 +64,13 @@ function restoreSnapshot(snap: Record) { function killTree(child: any) { if (!child) return + // No process groups on Windows: taskkill walks the tree instead. + if (process.platform === "win32") { + try { + if (child.pid) execSync(`taskkill /T /F /PID ${child.pid}`, { stdio: "ignore" }) + } catch (_) {} + return + } try { if (child.pid) { process.kill(-child.pid, "SIGKILL") @@ -97,6 +104,11 @@ function killTree(child: any) { // `npx -y catalyst `). Callers must not re-append the // subcommand — the npx path needs it as an explicit arg. function getCatalystScript(scriptRelativePath: string, subcommand: string) { + // On Windows .bin holds shims rather than symlinks, so there is no target to follow. + if (process.platform === "win32") { + const scriptPath = path.join(appDir, "node_modules", "catalyst-core", "dist", scriptRelativePath) + if (fs.existsSync(scriptPath)) return { cmd: process.execPath, argsPrefix: [scriptPath] } + } const localBin = path.join(appDir, "node_modules", ".bin", "catalyst") if (fs.existsSync(localBin)) { const binTarget = fs.realpathSync(localBin) @@ -326,6 +338,29 @@ exit 0 ` fs.writeFileSync(path.join(tmpDir, "npm"), mockNpmScript, { mode: 0o755 }) fs.writeFileSync(path.join(tmpDir, "git"), "#!/bin/sh\nexit 0\n", { mode: 0o755 }) + if (process.platform === "win32") { + // cmd.exe only runs what PATHEXT names, so the mocks need their own spelling. + fs.writeFileSync( + path.join(tmpDir, "npm.cmd"), + [ + "@echo off", + 'if not "%~1"=="pack" exit /b 0', + "mkdir package\\templates\\common package\\templates\\context-js package\\templates\\redux-js package\\templates\\default-js", + `echo {"name":"create-catalyst-app","version":"${ccaVersion}"} > package\\package.json`, + 'echo {"name":"app"} > package\\templates\\common\\package.json', + 'echo {"name":"app"} > package\\templates\\context-js\\package.json', + 'echo {"name":"app"} > package\\templates\\redux-js\\package.json', + 'echo {"name":"app"} > package\\templates\\default-js\\package.json', + "echo # template gitignore > package\\templates\\common\\.gitignore", + "echo # template gitignore > package\\templates\\context-js\\.gitignore", + "echo # template gitignore > package\\templates\\redux-js\\.gitignore", + "echo # template gitignore > package\\templates\\default-js\\.gitignore", + `tar -czf create-catalyst-app-${ccaVersion}.tgz package`, + "exit /b 0", + ].join("\r\n") + ) + fs.writeFileSync(path.join(tmpDir, "git.cmd"), "@exit /b 0\r\n") + } if (scen.setupDir) { scen.setupDir(tmpDir) } @@ -335,7 +370,7 @@ exit 0 const child = spawn(process.execPath, [cliPath, ...scen.cliArgs], { cwd: tmpDir, stdio: ["ignore", "pipe", "pipe"], - env: { ...process.env, PATH: `${tmpDir}:${process.env.PATH}`, CATALYST_OUTPUT_MODE: "default" }, + env: { ...process.env, PATH: `${tmpDir}${path.delimiter}${process.env.PATH}`, CATALYST_OUTPUT_MODE: "default" }, }) child.stdout?.on("data", (chunk: Buffer) => { output += chunk.toString() }) @@ -372,6 +407,11 @@ describe("Error Catalog Contract Fixtures", () => { it.skip(`${scen.code}: ${scen.title} (validator exists, no live call site — see PR #450 ledger)`, () => {}) } else if ((scen as { network?: boolean }).network && skipNetwork) { it.skip(`${scen.code}: ${scen.title} (needs live network — skipped in CI)`, () => {}) + } else if ( + (scen as { platforms?: string[] }).platforms && + !(scen as { platforms: string[] }).platforms.includes(process.platform) + ) { + it.skip(`${scen.code}: ${scen.title} (not reachable on ${process.platform})`, () => {}) } else if (kind === "client" || kind === "mapping") { it(`${scen.code}: ${scen.title} (in-process)`, () => { expect(true).toBe(true) @@ -395,7 +435,7 @@ describe("Error Catalog Contract Fixtures", () => { } } - it("completeness: covers all 104 error codes", () => { + it("completeness: covers all 105 error codes", () => { const scenarioCodes = new Set(scenarios.map((s) => s.code)) let viaScenario = 0 let viaLedger = 0 diff --git a/packages/catalyst-core/bin/catalyst.js b/packages/catalyst-core/bin/catalyst.js index e9c0a3691..7727f6240 100755 --- a/packages/catalyst-core/bin/catalyst.js +++ b/packages/catalyst-core/bin/catalyst.js @@ -197,7 +197,11 @@ function runPlatformCommand(command) { } if (script === "buildApp" || script === "setupEmulator") { - for (const platform of ["ios", "android"]) { + // Xcode only exists on macOS. Failing on iOS here would mean never reaching + // Android, the platform this machine can actually build. + const onMac = process.platform === "darwin" + if (!onMac) console.log(`\n${GUTTER}${paint("dim", "Skipping iOS: it needs macOS and Xcode.")}`) + for (const platform of onMac ? ["ios", "android"] : ["android"]) { const result = runPlatformCommand(`${script}:${platform}`) if (result.status !== 0 || result.signal) handleProcessResult(result) } diff --git a/packages/catalyst-core/changelog.md b/packages/catalyst-core/changelog.md index 8c8b69201..0de69afff 100644 --- a/packages/catalyst-core/changelog.md +++ b/packages/catalyst-core/changelog.md @@ -1,5 +1,19 @@ # Changelog +## [Unreleased] + +### Windows support + +Catalyst now runs natively on Windows, in PowerShell, Command Prompt and Git Bash, without WSL. `create-catalyst-app`, `catalyst start`, `build`, `serve`, `plugins`, `setupEmulator:android` and `buildApp:android`, including signed release bundles, all work there. + +iOS still needs macOS and Xcode. On Windows and Linux, `catalyst buildApp` and `catalyst setupEmulator` skip iOS and run Android, and the `:ios` commands exit with the new error [IOS-007](https://github.com/tata1mg/catalyst-core/blob/main/errors/IOS/IOS-007.md). + +### Fixes + +- `buildApp:android` no longer depends on `rsync`, `find`, `mv` or `sh`, and an SDK or app path with spaces no longer breaks it, on any platform. +- `new-route` exits non-zero when it fails. It used to exit 0 with nothing created. +- `create-catalyst-app` removes its `temp-*` folder when it fails. + ## [1.2.1] - 2026-11-17 - `useIntent()` adds `openInBrowser(url)`, which opens a link outside the WebView: in the default browser, or in the app that owns the link when one is installed. Only `http` and `https` URLs are accepted; any other scheme fails with an error. diff --git a/packages/catalyst-core/mcp_v2/tools/github.js b/packages/catalyst-core/mcp_v2/tools/github.js index d1455919d..75248ea8e 100644 --- a/packages/catalyst-core/mcp_v2/tools/github.js +++ b/packages/catalyst-core/mcp_v2/tools/github.js @@ -1256,7 +1256,8 @@ async function handle_create_github_pr(args = {}) { const dryRun = args.dry_run !== false const remoteHead = runGit(root, `git rev-parse --verify --quiet origin/${head}`) - const commits = runGit(root, `git log --oneline origin/${base}..${head} 2>/dev/null`) || "" + // runGit already discards stderr; a shell redirect here would not exist on Windows. + const commits = runGit(root, `git log --oneline origin/${base}..${head}`) || "" const tokenResult = getToken() const preview = { diff --git a/packages/catalyst-core/package.json b/packages/catalyst-core/package.json index f18e19fcd..b6b883dff 100644 --- a/packages/catalyst-core/package.json +++ b/packages/catalyst-core/package.json @@ -59,7 +59,7 @@ "test:unit": "node --test \"test/**/*.test.js\" \"test/**/*.test.cjs\"", "typecheck": "tsc --noEmit", "prettify": "prettier . --write", - "prepare": "node scripts/safe-rimraf.cjs ./dist && node scripts/build-dist.mjs && cp -r ./src/native ./dist/native && babel src/native --out-dir dist/native --config-file ./babel.native.config.cjs --extensions '.js,.jsx,.ts,.tsx' --ignore '**/.build/**' && node scripts/strip-ts-sources.mjs ./dist/native && babel src/sentry.js --out-file dist/sentry.cjs --config-file ./babel.native.config.cjs && tsc -p tsconfig.declarations.json && node ./mcp_v2/scripts/copyErrorsIndex.cjs", + "prepare": "node scripts/safe-rimraf.cjs ./dist && node scripts/build-dist.mjs && node scripts/copy-native.cjs && babel src/native --out-dir dist/native --config-file ./babel.native.config.cjs --extensions \".js,.jsx,.ts,.tsx\" --ignore \"**/.build/**\" && node scripts/strip-ts-sources.mjs ./dist/native && babel src/sentry.js --out-file dist/sentry.cjs --config-file ./babel.native.config.cjs && tsc -p tsconfig.declarations.json && node ./mcp_v2/scripts/copyErrorsIndex.cjs", "prepublishOnly": "npm run prepare", "test": "npm run test:types && vitest run", "test:watch": "vitest", diff --git a/packages/catalyst-core/scripts/copy-native.cjs b/packages/catalyst-core/scripts/copy-native.cjs new file mode 100644 index 000000000..bb857a4a3 --- /dev/null +++ b/packages/catalyst-core/scripts/copy-native.cjs @@ -0,0 +1,21 @@ +#!/usr/bin/env node + +/** + * Copies src/native to dist/native verbatim, ahead of the Babel pass. + * + * Replaces `cp -r ./src/native ./dist/native`, which stopped `npm install` dead + * on Windows: no cmd.exe has a cp. `dereference` matches what that cp did, so + * dist contains no symlinks. + * + * Usage: node scripts/copy-native.cjs + */ + +const fs = require("fs") +const path = require("path") + +const packageRoot = path.resolve(__dirname, "..") + +fs.cpSync(path.join(packageRoot, "src", "native"), path.join(packageRoot, "dist", "native"), { + recursive: true, + dereference: true, +}) diff --git a/packages/catalyst-core/scripts/strip-ts-sources.mjs b/packages/catalyst-core/scripts/strip-ts-sources.mjs index 18bce0a19..0b568a512 100644 --- a/packages/catalyst-core/scripts/strip-ts-sources.mjs +++ b/packages/catalyst-core/scripts/strip-ts-sources.mjs @@ -5,8 +5,8 @@ * * The native half of the prepare chain is a raw copy followed by a Babel pass: * - * cp -r ./src/native ./dist/native - * babel src/native --out-dir dist/native --extensions '.js,.jsx,.ts,.tsx' ... + * node scripts/copy-native.cjs + * babel src/native --out-dir dist/native --extensions ".js,.jsx,.ts,.tsx" ... * * The copy is what carries the non-source files the native toolchain needs * (Gradle projects, Xcode projects, plists, and the {"type":"commonjs"} diff --git a/packages/catalyst-core/src/cli/README.md b/packages/catalyst-core/src/cli/README.md index c86542735..e24bf6517 100644 --- a/packages/catalyst-core/src/cli/README.md +++ b/packages/catalyst-core/src/cli/README.md @@ -59,6 +59,7 @@ child sees a pipe and strips its own colour. | `buildErrors.js` | Mines real errors out of gradle/xcodebuild/Vite output, incl. gradle's "What went wrong" | | `hints.js` | The short list of failures we can give real advice for | | `devOutput.js` | Classifies a dev/production server's lines; `superviseServer()`, `ensurePortFree()` | +| `platform.js` | What differs on Windows: `appRoot()`, quoting for cmd.exe, advice naming real commands | ## Default and --verbose diff --git a/packages/catalyst-core/src/cli/buildErrors.js b/packages/catalyst-core/src/cli/buildErrors.js index 409ad9bd1..a200e38d6 100644 --- a/packages/catalyst-core/src/cli/buildErrors.js +++ b/packages/catalyst-core/src/cli/buildErrors.js @@ -20,11 +20,12 @@ const { ANSI } = require("./theme.js") // clang. `> Task :app:x FAILED` and `FAILURE:` are gradle's own markers. const ERROR_PATTERNS = [ // Kotlin: e: file:///path/Foo.kt:12:5 Unresolved reference: bar - /^e:\s+(?:file:\/\/)?(?[^\s:]+):(?\d+):(?\d+)\s+(?.+)$/, + // Any path here may open with a Windows drive: file:///C:/path, C:\path. + /^e:\s+(?:file:\/\/)?(?(?:\/?[A-Za-z]:)?[^\s:]+):(?\d+):(?\d+)\s+(?.+)$/, // Swift / clang / javac: /path/Foo.swift:12:5: error: cannot find 'bar' - /^(?[^\s:][^:]*):(?\d+):(?\d+):\s*(?:fatal\s+)?error:\s*(?.+)$/i, + /^(?(?:[A-Za-z]:)?[^\s:][^:]*):(?\d+):(?\d+):\s*(?:fatal\s+)?error:\s*(?.+)$/i, // javac without a column - /^(?[^\s:][^:]*):(?\d+):\s*error:\s*(?.+)$/i, + /^(?(?:[A-Za-z]:)?[^\s:][^:]*):(?\d+):\s*error:\s*(?.+)$/i, // Gradle/AGP: "> Task :app:compileDebugKotlin FAILED" then a bare message /^\s*(?:>\s*)?(?:error|FAILURE):\s*(?.+)$/i, // Xcode linker and codesign failures carry no file @@ -47,11 +48,12 @@ const NOISE = [ // junk drawer where every toolchain's noise matches every other's. const VITE_ERROR_PATTERNS = [ // [plugin:name] Could not load /path (imported by other/path): ENOENT... - /\[(?:vite|plugin)[^\]]*\]\s*(?Could not (?:load|resolve)[^:]*)(?::.*)?$/i, + // (a colon before a slash is a Windows drive, still part of the path) + /\[(?:vite|plugin)[^\]]*\]\s*(?Could not (?:load|resolve)(?:[^:]|:[\\/])*)(?::.*)?$/i, // Failed to resolve import "x" from "y" /^(?Failed to resolve (?:import|entry)[^.]*)\.?$/i, // file.js:12:3: error: message (esbuild transform failures) - /^(?[^\s:][^:]*):(?\d+):(?\d+):\s*ERROR:\s*(?.+)$/i, + /^(?(?:[A-Za-z]:)?[^\s:][^:]*):(?\d+):(?\d+):\s*ERROR:\s*(?.+)$/i, // Bare "error during build:" is a header, not a message -- see NOISE. ] @@ -61,6 +63,11 @@ const IMPORTED_BY = /\(imported by ([^)]+)\)/ const MAX_ERRORS = 5 +// A file URL's path keeps a slash in front of the drive (/C:/path) and encodes +// its spaces. Neither is a path the OS can open. +const DRIVE = /^\/([A-Za-z]:)/ +const fromOutput = (file) => (DRIVE.test(file) ? decodeURI(file.replace(DRIVE, "$1")) : file) + /** * @param {string} output - everything the build printed * @returns {Array<{file?: string, line?: number, column?: number, message: string}>} @@ -89,7 +96,7 @@ function extractBuildErrors(output, { toolchain = "native" } = {}) { seen.add(key) found.push({ - file: file || (importedBy ? importedBy[1].trim() : undefined), + file: file ? fromOutput(file) : importedBy ? importedBy[1].trim() : undefined, line: lineNo ? Number(lineNo) : undefined, column: column ? Number(column) : undefined, // The "(imported by x)" clause becomes the `file` above, so diff --git a/packages/catalyst-core/src/cli/devOutput.js b/packages/catalyst-core/src/cli/devOutput.js index 84c238f4f..45a4cfd55 100644 --- a/packages/catalyst-core/src/cli/devOutput.js +++ b/packages/catalyst-core/src/cli/devOutput.js @@ -1,6 +1,7 @@ "use strict" const { GUTTER, glyph, t, ANSI, isVerbose } = require("./theme.js") +const { isWindows, stopProcessCommand } = require("./platform.js") // Fences the dev server writes around its banner block, so the wrapper can // forward those lines verbatim rather than guessing from their text. Colour @@ -484,7 +485,7 @@ function ensurePortFree({ port, host, scope }) { message: `Port ${numeric} is already in use${owner ? ` by ${owner.command} (pid ${owner.pid})` : ""}`, scope, hint: owner - ? `Stop it with \`kill ${owner.pid}\`, or change NODE_SERVER_PORT and PUBLIC_STATIC_ASSET_URL in config/config.json.` + ? `Stop it with \`${stopProcessCommand(owner.pid)}\`, or change NODE_SERVER_PORT and PUBLIC_STATIC_ASSET_URL in config/config.json.` : "Stop whatever is using it, or change NODE_SERVER_PORT and PUBLIC_STATIC_ASSET_URL in config/config.json.", }) ) @@ -495,9 +496,53 @@ function ensurePortFree({ port, host, scope }) { }) } -/** The process listening on a port, via lsof; null where lsof is unavailable. */ +/** + * The pid listening on a port, from `netstat -ano`: Proto, Local Address, + * Foreign Address, State, PID. Matched on the address's last colon, which also + * handles [::]:3005. The state is not compared as a word because Windows + * translates it; only a listening socket has the wildcard foreign address. + */ +function listeningPidFromNetstat(output, port) { + for (const line of String(output).split(/\r?\n/)) { + const [proto, local, foreign, , pid] = line.trim().split(/\s+/) + if (!/^TCP/i.test(proto || "") || !pid) continue + if (local.endsWith(`:${port}`) && /:0$|:\*$/.test(foreign)) return pid + } + return null +} + +/** The image name of a pid, from the CSV `tasklist` prints. */ +function imageNameFromTasklist(output) { + return /^"([^"]+)"/.exec(String(output).trim())?.[1] || null +} + +/** portOwner for Windows, which has no lsof. netstat and tasklist ship with it. */ +function windowsPortOwner(port) { + const { execFileSync } = require("child_process") + const options = { + encoding: "utf8", + stdio: ["ignore", "pipe", "ignore"], + timeout: 3000, + windowsHide: true, + } + // No -p TCP: that hides IPv6, where a server on "localhost" usually is. + const pid = listeningPidFromNetstat(execFileSync("netstat", ["-ano"], options), port) + if (!pid) return null + let command = null + try { + command = imageNameFromTasklist( + execFileSync("tasklist", ["/FI", `PID eq ${pid}`, "/FO", "CSV", "/NH"], options) + ) + } catch (error) { + // The pid alone is still enough to act on. + } + return { pid, command: command || "another process" } +} + +/** The process listening on a port; null when that cannot be found out. */ function portOwner(port) { try { + if (isWindows()) return windowsPortOwner(port) const { execFileSync } = require("child_process") const out = execFileSync("lsof", ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN", "-Fpc"], { encoding: "utf8", @@ -514,6 +559,8 @@ function portOwner(port) { module.exports = { ensurePortFree, + listeningPidFromNetstat, + imageNameFromTasklist, formatDevLine, createLineReader, wireServerOutput, diff --git a/packages/catalyst-core/src/cli/diagnostic.js b/packages/catalyst-core/src/cli/diagnostic.js index 8d8071ec0..df0dba6aa 100644 --- a/packages/catalyst-core/src/cli/diagnostic.js +++ b/packages/catalyst-core/src/cli/diagnostic.js @@ -2,6 +2,7 @@ const fs = require("fs") const path = require("path") +const { fileURLToPath } = require("url") const { GUTTER, glyph, t } = require("./theme.js") @@ -173,12 +174,12 @@ function buildFailure({ error, stage, code: wrapperCode, cwd = process.cwd() }) for (const item of found) { out.push(`${GUTTER}${t.bold(item.message)}\n`) if (item.file) { - const shown = relativeIfInside(item.file.replace(/^file:\/\//, ""), cwd) + const shown = relativeIfInside(item.file, cwd) const at = item.line != null ? `:${item.line}${item.column != null ? `:${item.column}` : ""}` : "" out.push(`${GUTTER}${t.dim("at")} ${t.accent(shown)}${t.dim(at)}\n`) - const frame = codeFrame(item.file.replace(/^file:\/\//, ""), item.line, item.column) + const frame = codeFrame(item.file, item.line, item.column) if (frame) out.push(`\n${frame}\n`) } out.push("\n") @@ -252,7 +253,17 @@ function registryFailure(error, { scope, cwd } = {}) { } // V8 frame: " at fn (file:line:col)" or " at file:line:col". -const FRAME = /^\s*at\s+(?:(.*?)\s+\()?(?:file:\/\/)?([^()]+?):(\d+):(\d+)\)?\s*$/ +const FRAME = /^\s*at\s+(?:(.*?)\s+\()?([^()]+?):(\d+):(\d+)\)?\s*$/ + +/** A frame's location as an OS path: file:///C:/a%20b/x.js is C:\a b\x.js on Windows. */ +function frameFile(location) { + if (!location.startsWith("file://")) return location + try { + return fileURLToPath(location) + } catch (error) { + return location.slice("file://".length) + } +} /** Parse a V8 stack into frames; lines that are not frames are skipped. */ function parseFrames(stack) { @@ -261,7 +272,7 @@ function parseFrames(stack) { const match = FRAME.exec(line) if (!match) continue const [, fn, file, lineNo, column] = match - frames.push({ fn: fn || null, file, line: Number(lineNo), column: Number(column) }) + frames.push({ fn: fn || null, file: frameFile(file), line: Number(lineNo), column: Number(column) }) } return frames } @@ -273,7 +284,8 @@ function parseFrames(stack) { */ function isAppFrame(frame, cwd) { if (!frame.file || frame.file.startsWith("node:")) return false - if (frame.file.includes(`${path.sep}node_modules${path.sep}`)) return false + // Either separator: stacks mapped back by Vite use / on Windows too. + if (/[\\/]node_modules[\\/]/.test(frame.file)) return false const relative = path.relative(cwd, frame.file) return Boolean(relative) && !relative.startsWith("..") && !path.isAbsolute(relative) } diff --git a/packages/catalyst-core/src/cli/hints.js b/packages/catalyst-core/src/cli/hints.js index 0a49cbceb..9af7f52e2 100644 --- a/packages/catalyst-core/src/cli/hints.js +++ b/packages/catalyst-core/src/cli/hints.js @@ -1,5 +1,7 @@ "use strict" +const { freePortCommand, isWindows } = require("./platform.js") + /** * Hints for failures we actually understand. * @@ -23,7 +25,7 @@ const HINTS = [ const port = match[2] const where = port ? `port ${port}` : "that port" return port - ? `Something is already on ${where}. Free it with \`lsof -ti :${port} | xargs kill\`, or set NODE_SERVER_PORT in config/config.json.` + ? `Something is already on ${where}. Free it with \`${freePortCommand(port)}\`, or set NODE_SERVER_PORT in config/config.json.` : `Something is already on ${where}. Stop it, or set NODE_SERVER_PORT in config/config.json.` }, }, @@ -35,7 +37,7 @@ const HINTS = [ { test: /SDK location not found|ANDROID_HOME/i, hint: () => - "Set the Android SDK path in config/config.json under WEBVIEW_CONFIG.android.sdkPath, or export ANDROID_HOME.", + `Set the Android SDK path in config/config.json under WEBVIEW_CONFIG.android.sdkPath, or ${isWindows() ? "set the ANDROID_HOME environment variable" : "export ANDROID_HOME"}.`, }, { test: /No booted simulator found/i, diff --git a/packages/catalyst-core/src/cli/platform.js b/packages/catalyst-core/src/cli/platform.js new file mode 100644 index 000000000..09a7d82a3 --- /dev/null +++ b/packages/catalyst-core/src/cli/platform.js @@ -0,0 +1,81 @@ +"use strict" + +/** + * What differs between operating systems, in one place. + * + * CommonJS for the same reason as theme.js: src/native is CJS and src/scripts is + * ESM, and this is the only form both can consume. Everything reads + * process.platform when called rather than at load, so tests can stand in for + * the other platform. + */ + +const isWindows = () => process.platform === "win32" + +/** + * The app the command was run in. + * + * PWD belongs to POSIX shells. PowerShell and cmd.exe never set it, so on Windows + * it is either missing or stale: inherited from the Git Bash that launched the + * terminal, and pointing at some other project. Only the OS's own answer can be + * trusted there. Elsewhere PWD stays preferred, because it keeps the path the + * user typed when a symlink led to the app. + */ +function appRoot() { + return isWindows() ? process.cwd() : process.env.PWD || process.cwd() +} + +/** + * One argument for a cmd.exe command line, using the quoting the Microsoft C + * runtime parses: backslashes are only special in front of a quote, so those get + * doubled. Arguments cmd.exe would act on (& | < > ^ ( ) % !) are quoted too, + * and so are ; , and =, where a batch file's %1..%9 and %* split an argument: + * sdkmanager ids (platforms;android-36) and --sdk_root= contain them. + */ +function quoteWindowsArg(arg) { + const text = String(arg) + if (text && !/[\s"&|<>^()%!;,=]/.test(text)) return text + return `"${text.replace(/(\\*)"/g, '$1$1\\"').replace(/(\\*)$/, "$1$1")}"` +} + +// What cmd.exe acts on even inside quotes: %VAR% is expanded there, a quote +// ends the quoting, and a line break ends the command. +const UNSAFE_FOR_CMD = /[%"\r\n\0]/ + +/** + * The spawn() call that runs a batch file with these arguments. Node refuses to + * spawn .bat and .cmd files directly (EINVAL since CVE-2024-27980), so it goes + * through cmd.exe, with the whole line quoted once more for its /s switch. + * + * The paths here come from config and the environment (the SDK location, the + * project folder), so anything cmd.exe would still read as syntax is refused + * rather than passed on. cmd.exe is named, not taken from ComSpec. + */ +function batchInvocation(batchFile, args = []) { + for (const arg of [batchFile, ...args]) { + if (UNSAFE_FOR_CMD.test(String(arg))) { + throw new Error( + `Cannot pass ${JSON.stringify(String(arg))} to a batch file: cmd.exe would read its % or quote as syntax. Use a path without them.` + ) + } + } + const line = [batchFile, ...args].map(quoteWindowsArg).join(" ") + return { + command: "cmd.exe", + args: ["/d", "/s", "/c", `"${line}"`], + options: { windowsVerbatimArguments: true }, + } +} + +/** Advice for freeing a port, in commands that exist on this machine. */ +function freePortCommand(port) { + return isWindows() + ? `netstat -ano | findstr :${port}, then taskkill /PID /T /F` + : `lsof -ti :${port} | xargs kill` +} + +/** The command that stops one process, as a person would type it. */ +function stopProcessCommand(pid) { + return isWindows() ? `taskkill /PID ${pid} /T /F` : `kill ${pid}` +} + +module.exports = { isWindows, appRoot, quoteWindowsArg, batchInvocation, freePortCommand, stopProcessCommand } diff --git a/packages/catalyst-core/src/errors/generateDocs.js b/packages/catalyst-core/src/errors/generateDocs.js index 873ceaf5a..d2e4c06a5 100644 --- a/packages/catalyst-core/src/errors/generateDocs.js +++ b/packages/catalyst-core/src/errors/generateDocs.js @@ -1,6 +1,6 @@ import { mkdirSync, writeFileSync, readFileSync, readdirSync, rmSync, existsSync } from "fs" import path from "path" -import { fileURLToPath } from "url" +import { fileURLToPath, pathToFileURL } from "url" import { ERROR_DEFINITIONS } from "./registry.js" const __filename = fileURLToPath(import.meta.url) @@ -94,7 +94,7 @@ export function generateDocs(errorsDir = DEFAULT_ERRORS_DIR) { return { count: Object.keys(ERROR_DEFINITIONS).length, errorsDir } } -if (import.meta.url === `file://${process.argv[1]}`) { +if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) { const { count, errorsDir } = generateDocs() console.log(`Generated ${count} error doc(s) + index.json in ${errorsDir}`) } diff --git a/packages/catalyst-core/src/errors/registry.js b/packages/catalyst-core/src/errors/registry.js index 40135db38..e80ea5da5 100644 --- a/packages/catalyst-core/src/errors/registry.js +++ b/packages/catalyst-core/src/errors/registry.js @@ -35,6 +35,7 @@ export const ERROR_CODES = { IOS_SIMULATOR_RUNTIME_MISSING: "IOS-004", IOS_APP_ICON_INVALID: "IOS-005", IOS_APP_ICON_HAS_ALPHA: "IOS-006", + IOS_REQUIRES_MACOS: "IOS-007", IOS_SIGNING_NOT_SET_UP: "IOS-010", IOS_ASC_API_KEY_INVALID: "IOS-011", IOS_MANUAL_SIGNING_INVALID: "IOS-012", @@ -326,6 +327,14 @@ export const ERROR_DEFINITIONS = { suggestedAction: "Export public/icon.png without an alpha channel (flatten it onto a solid background), then rebuild.", }, + [ERROR_CODES.IOS_REQUIRES_MACOS]: { + category: "IOS", + defaultMessage: "iOS builds need macOS and Xcode", + defaultDetails: + "buildApp:ios and setupEmulator:ios drive Xcode and the iOS Simulator, which only run on macOS. Everything else, including the Android commands, works on this machine.", + suggestedAction: + "Build the iOS app on a Mac or a macOS CI runner. Plain catalyst buildApp and catalyst setupEmulator skip iOS on other systems and carry on with Android.", + }, [ERROR_CODES.IOS_SIGNING_NOT_SET_UP]: { category: "IOS", defaultMessage: "iOS code signing is not set up", @@ -411,9 +420,9 @@ export const ERROR_DEFINITIONS = { category: "ANDROID", defaultMessage: "No JDK 17 to 23 found", defaultDetails: - "Gradle 8.13 and the Android SDK tools need JDK 17 to 23. None was found in JAVA_HOME, /usr/libexec/java_home or Android Studio's bundled runtime (a JDK 24 or newer is skipped), and none could be installed: this is not macOS, Homebrew is missing, or the install was declined.", + "Gradle 8.13 and the Android SDK tools need JDK 17 to 23. None was found in JAVA_HOME, /usr/libexec/java_home, Android Studio's bundled runtime, the java on PATH or (on Windows) the usual JDK install folders (a JDK 24 or newer is skipped), and none could be installed: this is not macOS, Homebrew is missing, or the install was declined.", suggestedAction: - "Install JDK 17 or 21 (macOS: brew install --cask zulu@17; Linux: your distribution's openjdk-17-jdk package) and set JAVA_HOME, or run catalyst buildApp:android in a terminal, or with --yes, to install it.", + "Install JDK 17 or 21 (macOS: brew install --cask zulu@17; Linux: your distribution's openjdk-17-jdk package; Windows: Android Studio, or winget install Microsoft.OpenJDK.17) and set JAVA_HOME, or on macOS run catalyst buildApp:android in a terminal, or with --yes, to install it.", }, [ERROR_CODES.ANDROID_SDK_SETUP_DECLINED]: { category: "ANDROID", diff --git a/packages/catalyst-core/src/native/androidProject/gradlew.bat b/packages/catalyst-core/src/native/androidProject/gradlew.bat index ac1b06f93..107acd32c 100644 --- a/packages/catalyst-core/src/native/androidProject/gradlew.bat +++ b/packages/catalyst-core/src/native/androidProject/gradlew.bat @@ -1,89 +1,89 @@ -@rem -@rem Copyright 2015 the original author or authors. -@rem -@rem Licensed under the Apache License, Version 2.0 (the "License"); -@rem you may not use this file except in compliance with the License. -@rem You may obtain a copy of the License at -@rem -@rem https://www.apache.org/licenses/LICENSE-2.0 -@rem -@rem Unless required by applicable law or agreed to in writing, software -@rem distributed under the License is distributed on an "AS IS" BASIS, -@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -@rem See the License for the specific language governing permissions and -@rem limitations under the License. -@rem - -@if "%DEBUG%" == "" @echo off -@rem ########################################################################## -@rem -@rem Gradle startup script for Windows -@rem -@rem ########################################################################## - -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal - -set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. -set APP_BASE_NAME=%~n0 -set APP_HOME=%DIRNAME% - -@rem Resolve any "." and ".." in APP_HOME to make it shorter. -for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi - -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" - -@rem Find java.exe -if defined JAVA_HOME goto findJavaFromJavaHome - -set JAVA_EXE=java.exe -%JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto execute - -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto execute - -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:execute -@rem Setup the command line - -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar - - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* - -:end -@rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd - -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/packages/catalyst-core/src/native/androidSetup.js b/packages/catalyst-core/src/native/androidSetup.js index 19de65cd9..e79b51d0b 100644 --- a/packages/catalyst-core/src/native/androidSetup.js +++ b/packages/catalyst-core/src/native/androidSetup.js @@ -1,7 +1,7 @@ import fs from "fs" import path from "path" import { spawn } from "child_process" -import { runFile, parseNativeArgs, ensureLocalProperties, ANDROID_SDK_HINT } from "./utils.js" +import { runFile, parseNativeArgs, ensureLocalProperties, androidTools, ANDROID_SDK_HINT } from "./utils.js" import { applyJavaHome, ensureAndroidSdk, ensureJava, resolveSdkPath } from "./androidToolchain.js" import { getLastTarget } from "./localState.js" import TerminalProgress from "./terminalProgress.js" @@ -56,12 +56,11 @@ function readAndroidConfig() { function validateAndroidTools(androidConfig) { const ANDROID_SDK = androidConfig.sdkPath - const EMULATOR_PATH = `${ANDROID_SDK}/emulator/emulator` - const ADB_PATH = `${ANDROID_SDK}/platform-tools/adb` - if (!ANDROID_SDK) { throw Object.assign(new Error("Android SDK not found"), { hint: ANDROID_SDK_HINT }) } + // With .exe on Windows, so the existsSync checks below find them there. + const { emulator: EMULATOR_PATH, adb: ADB_PATH } = androidTools(ANDROID_SDK) if (!fs.existsSync(ANDROID_SDK)) { throw new Error(`Android SDK path does not exist: ${ANDROID_SDK}`) @@ -116,6 +115,8 @@ async function startEmulator(EMULATOR_PATH, androidConfig) { const child = spawn(EMULATOR_PATH, ["-avd", androidConfig.emulatorName, "-read-only"], { detached: true, stdio: "ignore", + // Otherwise detached opens an empty console window next to the emulator. + windowsHide: true, }) child.on("error", (error) => { progress.log(`Error starting emulator: ${error}`, "error") diff --git a/packages/catalyst-core/src/native/androidToolchain.js b/packages/catalyst-core/src/native/androidToolchain.js index 241cdba63..2acff8011 100644 --- a/packages/catalyst-core/src/native/androidToolchain.js +++ b/packages/catalyst-core/src/native/androidToolchain.js @@ -54,6 +54,7 @@ function defaultRun(command, args) { * @param {string} [options.platform] * @param {(command: string, args: string[]) => string | null} [options.run] - combined output, or null on failure * @param {(file: string) => boolean} [options.exists] + * @param {(dir: string) => string[]} [options.list] - a folder's entries, or [] when it cannot be read * @param {(candidate: string, reason: string) => void} [options.onSkip] * @returns {{ home: string, version: number, source: string } | null} */ @@ -62,6 +63,13 @@ function resolveJavaHome({ platform = process.platform, run = defaultRun, exists = fs.existsSync, + list = (dir) => { + try { + return fs.readdirSync(dir) + } catch { + return [] + } + }, onSkip = () => {}, } = {}) { const home = os.homedir() @@ -84,6 +92,37 @@ function resolveJavaHome({ add(path.join(home, "android-studio", "jbr"), "Android Studio") const java = run("sh", ["-c", 'readlink -f "$(command -v java)"']) if (java && java.trim()) add(path.dirname(path.dirname(java.trim())), "PATH") + } else if (platform === "win32") { + // Android Studio's JBR, which nothing puts on PATH, then any java on PATH. + // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal - Paths come from env vars naming the machine's own program folders, never remote input. + if (env.ProgramFiles) + add(path.join(env.ProgramFiles, "Android", "Android Studio", "jbr"), "Android Studio") + if (env.LOCALAPPDATA) { + // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal - Paths come from env vars naming the machine's own program folders, never remote input. + add(path.join(env.LOCALAPPDATA, "Programs", "Android Studio", "jbr"), "Android Studio") + } + const java = run("where", ["java"]) + const first = java && java.split(/\r?\n/)[0].trim() + if (first) add(path.dirname(path.dirname(first)), "PATH") + // Where the usual installers put a JDK, which only a new terminal finds on PATH. + // Newest name first; the version check below still decides. + const vendorDirs = [ + [env.ProgramFiles, "Microsoft"], + [env.LOCALAPPDATA && path.join(env.LOCALAPPDATA, "Programs"), "Microsoft"], + [env.ProgramFiles, "Eclipse Adoptium"], + [env.ProgramFiles, "Zulu"], + [env.ProgramFiles, "Java"], + ] + for (const [root, vendor] of vendorDirs) { + if (!root) continue + // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal - root names the machine's own program folders, never remote input. + const dir = path.join(root, vendor) + const jdks = list(dir) + .filter((name) => /^(jdk|zulu)/i.test(name)) + .sort((a, b) => b.localeCompare(a, undefined, { numeric: true })) + // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal - name comes from readdirSync of that folder. + for (const name of jdks) add(path.join(dir, name), vendor) + } } const exe = platform === "win32" ? "java.exe" : "java" @@ -165,7 +204,9 @@ async function ensureJava({ if (platform !== "darwin") { throw nativeError( "ANDROID-007", - "install a JDK 17 or 21 (e.g. sudo apt install openjdk-17-jdk) and set JAVA_HOME" + platform === "win32" + ? "install a JDK 17 or 21 (e.g. winget install Microsoft.OpenJDK.17), or Android Studio, then open a new terminal" + : "install a JDK 17 or 21 (e.g. sudo apt install openjdk-17-jdk) and set JAVA_HOME" ) } if (!hasCommand("brew")) { @@ -260,9 +301,11 @@ function missingAndroidPackages(sdkPath, packages, exists = fs.existsSync) { function defaultSdkPath(env = process.env, platform = process.platform) { if (env.ANDROID_HOME) return env.ANDROID_HOME if (env.ANDROID_SDK_ROOT) return env.ANDROID_SDK_ROOT - return platform === "darwin" - ? path.join(os.homedir(), "Library", "Android", "sdk") - : path.join(os.homedir(), "Android", "Sdk") + if (platform === "darwin") return path.join(os.homedir(), "Library", "Android", "sdk") + // Where Android Studio puts it, so the two share one SDK. + // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal - LOCALAPPDATA names this user's own folder, never remote input. + if (platform === "win32" && env.LOCALAPPDATA) return path.join(env.LOCALAPPDATA, "Android", "Sdk") + return path.join(os.homedir(), "Android", "Sdk") } /** @@ -323,9 +366,23 @@ async function curlDownload(url, dest) { await runInteractiveCommand("curl", ["-fsSL", "--retry", "2", "-o", dest, url]) } -function unzipArchive(zip, dest) { +function unzipArchive( + zip, + dest, + { platform = process.platform, env = process.env, exec = execFileSync, exists = fs.existsSync } = {} +) { + if (platform === "win32") { + // No unzip on Windows. Its own tar (bsdtar, in System32 since Windows 10) + // reads zip; Git's GNU tar, often first on PATH, does not. + // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal - SystemRoot names the Windows folder, never remote input. + const systemTar = path.join(env.SystemRoot || "C:\\Windows", "System32", "tar.exe") + const tar = exists(systemTar) ? systemTar : "tar" + // nosemgrep: javascript.lang.security.detect-child-process.detect-child-process - tar with an argv array on a checksum-verified archive. + exec(tar, ["-xf", zip, "-C", dest], { stdio: ["ignore", "ignore", "pipe"] }) + return + } // nosemgrep: javascript.lang.security.detect-child-process.detect-child-process - unzip with an argv array on a checksum-verified archive. - execFileSync("unzip", ["-q", "-o", zip, "-d", dest], { stdio: ["ignore", "ignore", "pipe"] }) + exec("unzip", ["-q", "-o", zip, "-d", dest], { stdio: ["ignore", "ignore", "pipe"] }) } /** @@ -571,7 +628,10 @@ async function ensureAndroidSdk({ await installTools(sdkPath, { log }) sdkmanager = cmdlineTool(sdkPath, "sdkmanager", { platform }) if (!sdkmanager) - throw nativeError("ANDROID-009", `no sdkmanager under ${sdkPath}/cmdline-tools/latest`) + throw nativeError( + "ANDROID-009", + `no sdkmanager under ${path.join(sdkPath, "cmdline-tools", "latest")}` + ) } const sdkRoot = `--sdk_root=${sdkPath}` @@ -611,7 +671,10 @@ async function ensureAndroidSdk({ if (createAvd) { const avdmanager = cmdlineTool(sdkPath, "avdmanager", { platform }) if (!avdmanager) - throw nativeError("ANDROID-009", `no avdmanager under ${sdkPath}/cmdline-tools/latest`) + throw nativeError( + "ANDROID-009", + `no avdmanager under ${path.join(sdkPath, "cmdline-tools", "latest")}` + ) log(`Creating the "${avdName}" emulator`) await run( avdmanager, @@ -638,6 +701,7 @@ export { requiredAndroidPackages, missingAndroidPackages, defaultSdkPath, + unzipArchive, resolveSdkPath, cmdlineTool, licensesAccepted, diff --git a/packages/catalyst-core/src/native/buildAndroid/assets.js b/packages/catalyst-core/src/native/buildAndroid/assets.js index c949ff803..ffe3f85ed 100644 --- a/packages/catalyst-core/src/native/buildAndroid/assets.js +++ b/packages/catalyst-core/src/native/buildAndroid/assets.js @@ -4,6 +4,7 @@ const fs = require("fs") const path = require("path") const { checkAppIcon } = require("../appIcon.js") const splashConfig = require("../splashConfig.js") +const { copyWebBuild } = require("../projectFiles.js") function createAssetsPhase(ctx) { const { configPath, publicPath, pwd, progress } = ctx @@ -13,44 +14,15 @@ function createAssetsPhase(ctx) { progress.log("Copying build assets to Android project...", "info") try { - const sourcePath = `${process.cwd()}/build/` - const destPath = `${pwd}/androidProject/app/src/main/assets/build/` + const sourcePath = path.join(process.cwd(), "build") + const destPath = path.join(pwd, "androidProject", "app", "src", "main", "assets", "build") + const excludedFiles = new Set(["route-manifest.json.gz", "route-manifest.json.br"]) - ctx.runCommand(`mkdir -p ${destPath}`) - ctx.runCommand(`rm -rf ${destPath}/*`) - - const excludePatterns = ["route-manifest.json.gz", "route-manifest.json.br"] - - if (buildOptimisation) { - progress.log("Running with build optimization...", "info") - const excludeParams = excludePatterns.map((pattern) => `--exclude="${pattern}"`).join(" ") - const rsyncCommand = `rsync -av ${excludeParams} ${sourcePath} ${destPath}` - progress.log("Executing rsync command with exclusions...", "info") - ctx.runCommand(rsyncCommand) - - for (const pattern of excludePatterns) { - const checkCommand = `find ${destPath} -name "${pattern}" | wc -l` - const count = parseInt(ctx.runCommand(checkCommand).trim(), 10) - if (count > 0) { - progress.log( - `Warning: Found ${count} instances of excluded file ${pattern}`, - "warning" - ) - ctx.runCommand(`find ${destPath} -name "${pattern}" -delete`) - } - } - progress.log( - "Build assets copied with optimization (excluded route-manifest JSON files)", - "success" - ) - } else { - progress.log("Running without build optimization...", "info") - const exclusions = excludePatterns.map((pattern) => `-not -name "${pattern}"`).join(" ") - const copyCommand = `find ${sourcePath} -type f ${exclusions} -exec cp --parents {} ${destPath} \\;` - progress.log(`Executing copy command with exclusions...`, "info") - ctx.runCommand(copyCommand) - progress.log("Build assets copied successfully!", "success") - } + copyWebBuild(sourcePath, destPath, excludedFiles) + progress.log( + "Build assets copied with optimization (excluded route-manifest JSON files)", + "success" + ) } catch (error) { throw new Error("Error copying build assets: " + error.message) } @@ -134,7 +106,7 @@ function createAssetsPhase(ctx) { return } - ctx.runCommand(`mkdir -p ${destDir}`) + fs.mkdirSync(destDir, { recursive: true }) fs.copyFileSync(sourcePath, destPath) } catch (error) { progress.log(`Warning: Error copying ${fileName}: ${error.message}`, "warning") diff --git a/packages/catalyst-core/src/native/buildAndroid/build.js b/packages/catalyst-core/src/native/buildAndroid/build.js index 628f7abb0..c1f2ed961 100644 --- a/packages/catalyst-core/src/native/buildAndroid/build.js +++ b/packages/catalyst-core/src/native/buildAndroid/build.js @@ -2,7 +2,8 @@ const { spawn, execFileSync } = require("child_process") const { buildAndroidAAB } = require("../renameAndroidProject.js") -const { ensureLocalProperties } = require("../utils.js") +const path = require("path") +const { ensureLocalProperties, runGradle } = require("../utils.js") const { signingGradleEnv } = require("./signing.js") const { launchArgs } = require("./devices.js") const { DEFAULT_VERSION_NAME } = require("../releaseOutput.js") @@ -90,6 +91,8 @@ function createBuildPhase(ctx) { const child = spawn(EMULATOR_PATH, ["-avd", androidConfig.emulatorName, "-read-only"], { detached: true, stdio: "ignore", + // Otherwise detached opens an empty console window next to the emulator. + windowsHide: true, }) child.once("error", (error) => { progress.log("Error starting emulator: " + error.message, "error") @@ -108,12 +111,17 @@ function createBuildPhase(ctx) { } // Best-effort cleanup for an emulator process this build spawned but that - // never became ready — kills the whole detached process group (negative pid) - // so we don't leave a CPU/RAM-heavy orphaned emulator running after a failed - // build. Never throws: a failure here shouldn't mask the original timeout error. + // never became ready — kills the whole detached process group (negative pid, + // or taskkill's tree on Windows, which has no process groups to signal) so we + // don't leave a CPU/RAM-heavy orphaned emulator running after a failed build. + // Never throws: a failure here shouldn't mask the original timeout error. function killOrphanedEmulator(pid, emulatorName) { try { - process.kill(-pid, "SIGTERM") + if (process.platform === "win32") { + execFileSync("taskkill", ["/PID", String(pid), "/T", "/F"], { stdio: "ignore" }) + } else { + process.kill(-pid, "SIGTERM") + } progress.log(`Stopped orphaned emulator process (pid ${pid}) after boot failure`, "info") } catch (error) { progress.log( @@ -282,29 +290,49 @@ function createBuildPhase(ctx) { // Gradle needs the SDK location in local.properties. Only // setupEmulator:android wrote it, so building without a prior // setup died in gradle despite a configured sdkPath. - if (androidConfig.sdkPath) ensureLocalProperties(`${pwd}/androidProject`, androidConfig.sdkPath) - - // --quiet was the Android silence: it suppresses gradle's task and - // error output entirely. --console=rich emits ANSI redraws, which - // are meaningless on a pipe; plain gives one line per task. - // nosemgrep: javascript.lang.security.audit.dangerous-spawn-shell-command.dangerous-spawn-shell-command - pwd and configPath are internal resolved paths, not user input. - const buildCommand = `cd ${pwd}/androidProject && ./gradlew generateWebViewConfig -PconfigPath=${configPath} -PcatalystBuildType=debug -PbuildOptimisation=${buildOptimisation} && ./gradlew clean installDebug -PconfigPath=${configPath} -PcatalystBuildType=debug --console=plain` + const projectDir = path.join(pwd, "androidProject") + if (androidConfig.sdkPath) ensureLocalProperties(projectDir, androidConfig.sdkPath) // Gradle emits hundreds of lines that nobody reads on success and // that the error path re-derives from error.output anyway. Show the // current task on the spinner's own row instead of scrolling them. - await ctx.runInteractiveCommand( - "sh", - ["-c", buildCommand], - { "BUILD SUCCESSFUL": "" }, - { - onLine: (line) => progress.status(gradleTask(line)), - env: { - ...process.env, - ...versionGradleEnv({ applicationId, version }), - ...(serial ? { ANDROID_SERIAL: serial } : {}), - }, - } + const gradleOptions = { + onLine: (line) => progress.status(gradleTask(line)), + env: { + ...process.env, + ...versionGradleEnv({ applicationId, version }), + ...(serial ? { ANDROID_SERIAL: serial } : {}), + }, + } + // runGradle passes an argument list, through gradlew.bat on Windows, + // where there is no sh to run "./gradlew ... && ./gradlew ...". + await runGradle( + projectDir, + [ + "generateWebViewConfig", + `-PconfigPath=${configPath}`, + "-PcatalystBuildType=debug", + `-PbuildOptimisation=${buildOptimisation}`, + ], + gradleOptions + ) + // --quiet was the Android silence: it suppresses gradle's task and + // error output entirely. --console=rich emits ANSI redraws, which + // are meaningless on a pipe; plain gives one line per task. + await runGradle( + projectDir, + [ + "clean", + "installDebug", + `-PconfigPath=${configPath}`, + "-PcatalystBuildType=debug", + "--console=plain", + ], + gradleOptions + + // Gradle emits hundreds of lines that nobody reads on success and + // that the error path re-derives from error.output anyway. Show the + // current task on the spinner's own row instead of scrolling them. ) } catch (error) { const apkPath = keepApk() @@ -414,7 +442,8 @@ function createBuildPhase(ctx) { try { if (!signing) throw new Error("No upload key resolved for the release build") // Same as buildApp: gradle needs local.properties on a fresh machine. - if (androidConfig.sdkPath) ensureLocalProperties(`${pwd}/androidProject`, androidConfig.sdkPath) + const projectDir = path.join(pwd, "androidProject") + if (androidConfig.sdkPath) ensureLocalProperties(projectDir, androidConfig.sdkPath) const aabConfig = await createAABConfig(androidConfig) if (finalAabPath) aabConfig.finalAabPath = finalAabPath diff --git a/packages/catalyst-core/src/native/buildAndroid/config.js b/packages/catalyst-core/src/native/buildAndroid/config.js index 4986fc343..65ffa701c 100644 --- a/packages/catalyst-core/src/native/buildAndroid/config.js +++ b/packages/catalyst-core/src/native/buildAndroid/config.js @@ -1,7 +1,7 @@ "use strict" const fs = require("fs") -const { ANDROID_SDK_HINT } = require("../utils.js") +const { androidTools, ANDROID_SDK_HINT } = require("../utils.js") const { resolveNativeConfig } = require("../nativeConfig.js") /** An error carrying the one action that fixes it, shown as the diagnostic's hint. */ @@ -64,8 +64,7 @@ function createConfigPhase(ctx) { progress.status("validating tools") const ANDROID_SDK = androidConfig.sdkPath - const ADB_PATH = `${ANDROID_SDK}/platform-tools/adb` - const EMULATOR_PATH = `${ANDROID_SDK}/emulator/emulator` + const { adb: ADB_PATH, emulator: EMULATOR_PATH } = androidTools(ANDROID_SDK) if (!fs.existsSync(ADB_PATH)) throw withHint(`adb not found at ${ADB_PATH}`, ANDROID_SDK_HINT) diff --git a/packages/catalyst-core/src/native/buildAndroid/devices.js b/packages/catalyst-core/src/native/buildAndroid/devices.js index c6cd512ea..0e6b59f5b 100644 --- a/packages/catalyst-core/src/native/buildAndroid/devices.js +++ b/packages/catalyst-core/src/native/buildAndroid/devices.js @@ -77,12 +77,17 @@ async function chooseAndroidTarget({ if (env.ANDROID_SERIAL) { const named = phones.find((device) => device.serial === env.ANDROID_SERIAL) if (!named) { - throw nativeError("ANDROID-011", `ANDROID_SERIAL=${env.ANDROID_SERIAL} is not a connected phone`) + throw nativeError( + "ANDROID-011", + `ANDROID_SERIAL=${env.ANDROID_SERIAL} is not a connected phone` + ) } return asDevice(named) } if (!phones.length) { - const unauthorized = devices.filter((device) => !device.emulator && device.state === "unauthorized") + const unauthorized = devices.filter( + (device) => !device.emulator && device.state === "unauthorized" + ) throw nativeError( "ANDROID-011", unauthorized.length diff --git a/packages/catalyst-core/src/native/buildAndroid/index.js b/packages/catalyst-core/src/native/buildAndroid/index.js index cb59c5932..274cef278 100644 --- a/packages/catalyst-core/src/native/buildAndroid/index.js +++ b/packages/catalyst-core/src/native/buildAndroid/index.js @@ -4,7 +4,14 @@ const path = require("path") const { displayPath } = require("../../cli/theme.js") const fs = require("fs") const { execFileSync } = require("child_process") -const { runCommand, runFile, runInteractiveCommand, isInteractive, select } = require("../utils.js") +const { + androidTools, + runCommand, + runFile, + runInteractiveCommand, + isInteractive, + select, +} = require("../utils.js") const { buildFailure } = require("../../cli/diagnostic.js") const TerminalProgress = require("../terminalProgress.js").default const { composeAndroidPlugins } = require("../pluginComposerAndroid.js") @@ -73,8 +80,8 @@ function createAndroidBuild( const flags = { yes, acceptLicenses } const { WEBVIEW_CONFIG, BUILD_OUTPUT_PATH } = config - const configPath = `${process.cwd()}/config/config.json` - const publicPath = `${process.cwd()}/public` + const configPath = path.join(process.cwd(), "config", "config.json") + const publicPath = path.join(process.cwd(), "public") const progress = new TerminalProgress(steps, "catalyst buildApp", { subject: "android" }) @@ -193,7 +200,10 @@ function createAndroidBuild( // nothing answers on its port, and waits until it does. if (resolved.usesDevServer) { progress.start("server") - await ensureDevServer({ cwd: appRoot, log }) + // On Windows adb reverse reaches the host on 127.0.0.1, so that has + // to answer; there localhost can be ::1 alone. macOS and Linux keep + // the localhost server, which adb reaches as before. + await ensureDevServer({ cwd: appRoot, log, ipv4: process.platform === "win32" }) progress.complete("server") } @@ -205,8 +215,8 @@ function createAndroidBuild( applyJavaHome(java) progress.log(`Java ${java.version} from ${java.source}`, "info") androidConfig.sdkPath = resolveSdkPath(androidConfig) - // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal - sdkPath is the local Android SDK. - const adbPath = path.join(androidConfig.sdkPath, "platform-tools", "adb") + // With .exe on Windows, where listDevices checks the file exists. + const adbPath = androidTools(androidConfig.sdkPath).adb // Where a debug build runs: the emulator unless --device, or a // person here picks a connected phone. diff --git a/packages/catalyst-core/src/native/buildAppIos.js b/packages/catalyst-core/src/native/buildAppIos.js index 2e96319df..dcb37ca3c 100644 --- a/packages/catalyst-core/src/native/buildAppIos.js +++ b/packages/catalyst-core/src/native/buildAppIos.js @@ -28,6 +28,7 @@ const { } = require("./buildIos/signing.js") const { resolveNativeConfig } = require("./nativeConfig.js") const { resolveCredentials } = require("./credentials.js") +const { iosRequiresMacError } = require("./iosPlatform.js") const TerminalProgress = require("./terminalProgress.js").default const catalystCorePath = path.dirname(require.resolve("catalyst-core/package.json")) @@ -203,6 +204,17 @@ async function main() { process.exit(1) } + // The config is checked on any machine, so its errors still show off macOS. + // Generating the project and running Xcode cannot happen there: stop before + // anything is written, rather than at a missing plutil several steps in. + if (process.platform !== "darwin") { + build.cleanup() + process.stderr.write( + buildFailure({ error: iosRequiresMacError(), stage: "iOS build", code: "IOS-007" }) + ) + process.exit(1) + } + // One-command dev: a debug build starts the dev server when nothing // answers on its port, and waits until it does. Only on macOS, the one // place an iOS build can run. An iPhone reaches it on devHost, so the diff --git a/packages/catalyst-core/src/native/buildIos/build.js b/packages/catalyst-core/src/native/buildIos/build.js index c7205b7be..99cb1c5ed 100644 --- a/packages/catalyst-core/src/native/buildIos/build.js +++ b/packages/catalyst-core/src/native/buildIos/build.js @@ -303,9 +303,13 @@ module.exports = function createBuildPhase(ctx) { progress.status("waiting for launch") for (let i = 0; i < 10; i++) { try { - const launchResult = execFileSync("xcrun", ["simctl", "launch", simctlDevice(), APP_BUNDLE_ID], { - stdio: ["ignore", "pipe", "ignore"], - }).toString() + const launchResult = execFileSync( + "xcrun", + ["simctl", "launch", simctlDevice(), APP_BUNDLE_ID], + { + stdio: ["ignore", "pipe", "ignore"], + } + ).toString() if (launchResult.includes("already launched")) { break } @@ -514,10 +518,7 @@ module.exports = function createBuildPhase(ctx) { return } if (!isBooted) { - progress.log( - `Attempting to boot simulator: ${simulatorName} (${foundSimulatorId})`, - "info" - ) + progress.log(`Attempting to boot simulator: ${simulatorName} (${foundSimulatorId})`, "info") if (foundSimulator.state === "Shutdown") { progress.log(`Simulator is shutdown, attempting to boot...`, "info") try { diff --git a/packages/catalyst-core/src/native/credentials.js b/packages/catalyst-core/src/native/credentials.js index fb00ebf5d..f9f767532 100644 --- a/packages/catalyst-core/src/native/credentials.js +++ b/packages/catalyst-core/src/native/credentials.js @@ -4,6 +4,18 @@ import os from "os" import path from "path" import { nativeError } from "./utils.js" +/** + * The tar to run. On Windows that is its own (bsdtar, in System32 since + * Windows 10): Git's GNU tar, often first on PATH, reads the C: of an + * absolute path as a remote host name. + */ +function tarCommand({ platform = process.platform, env = process.env, exists = fs.existsSync } = {}) { + if (platform !== "win32") return "tar" + // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal - SystemRoot names the Windows folder, never remote input. + const systemTar = path.join(env.SystemRoot || "C:\\Windows", "System32", "tar.exe") + return exists(systemTar) ? systemTar : "tar" +} + // Signing files live in git-ignored credentials// in the app. CI // gets the same folder from one secret per platform, CATALYST__CREDENTIALS: // a base64 gzipped tar of that folder, made by `catalyst credentials:export`. @@ -88,7 +100,7 @@ function packCredentials(platform, { cwd = process.cwd() } = {}) { throw nativeError("NATIVE-008", `credentials/${platform}/ is missing or empty in ${cwd}`) } // nosemgrep: javascript.lang.security.detect-child-process.detect-child-process - fixed tar argv; dir is the app's own credentials folder. - const archive = execFileSync("tar", ["-czf", "-", "--exclude", ".DS_Store", "-C", dir, "."], { + const archive = execFileSync(tarCommand(), ["-czf", "-", "--exclude", ".DS_Store", "-C", dir, "."], { env: TAR_ENV, maxBuffer: 64 * 1024 * 1024, stdio: ["ignore", "pipe", "pipe"], @@ -140,12 +152,12 @@ function unpackCredentials(value, destDir, { envName = "the credentials secret" let verbose try { // nosemgrep: javascript.lang.security.detect-child-process.detect-child-process - fixed tar argv on a temp file. - listing = execFileSync("tar", ["-tzf", file], { + listing = execFileSync(tarCommand(), ["-tzf", file], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], }) // nosemgrep: javascript.lang.security.detect-child-process.detect-child-process - fixed tar argv on a temp file. - verbose = execFileSync("tar", ["-tvzf", file], { + verbose = execFileSync(tarCommand(), ["-tvzf", file], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], }) @@ -158,7 +170,7 @@ function unpackCredentials(value, destDir, { envName = "the credentials secret" } fs.mkdirSync(destDir, { recursive: true, mode: 0o700 }) // nosemgrep: javascript.lang.security.detect-child-process.detect-child-process - fixed tar argv; entries were checked above. - execFileSync("tar", ["-xzf", file, "-C", destDir], { stdio: ["ignore", "pipe", "pipe"] }) + execFileSync(tarCommand(), ["-xzf", file, "-C", destDir], { stdio: ["ignore", "pipe", "pipe"] }) } finally { fs.rmSync(work, { recursive: true, force: true }) } @@ -259,4 +271,5 @@ export { unpackCredentials, resolveCredentials, cleanupOnSignal, + tarCommand, } diff --git a/packages/catalyst-core/src/native/iosPlatform.js b/packages/catalyst-core/src/native/iosPlatform.js new file mode 100644 index 000000000..5a5136efa --- /dev/null +++ b/packages/catalyst-core/src/native/iosPlatform.js @@ -0,0 +1,14 @@ +"use strict" + +// Text mirrors errors/registry.js ERROR_DEFINITIONS[IOS-007] (see +// errors/IOS/IOS-007.md) — this CJS subtree can't import the ESM error registry +// (see buildErrorFormat.js), so the fields are duplicated here rather than imported. +function iosRequiresMacError() { + return Object.assign(new Error("iOS builds need macOS and Xcode"), { + code: "IOS-007", + hint: "Build the iOS app on a Mac or a macOS CI runner. Plain catalyst buildApp and catalyst setupEmulator skip iOS on other systems and carry on with Android.", + docUrl: "https://github.com/tata1mg/catalyst-core/blob/main/errors/IOS/IOS-007.md", + }) +} + +module.exports = { iosRequiresMacError } diff --git a/packages/catalyst-core/src/native/projectFiles.js b/packages/catalyst-core/src/native/projectFiles.js new file mode 100644 index 000000000..b67497d91 --- /dev/null +++ b/packages/catalyst-core/src/native/projectFiles.js @@ -0,0 +1,116 @@ +"use strict" + +const fs = require("fs") +const path = require("path") + +/** + * File operations on a generated Android project. + * + * These were find, mv, rsync and rm -rf, which do not exist on Windows. They are + * plain Node now, on every platform, so there is one behaviour to reason about. + */ + +// nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal - every root below is the generated project inside this package, and names come from readdirSync. +const join = (...parts) => path.join(...parts) + +/** + * Every path under a directory, children before their parent, so that renaming + * or removing one entry never invalidates an entry still to come. + */ +function walkTree(root) { + const found = [] + for (const entry of fs.readdirSync(root, { withFileTypes: true })) { + const fullPath = join(root, entry.name) + if (entry.isDirectory()) found.push(...walkTree(fullPath)) + found.push({ + path: fullPath, + name: entry.name, + isDirectory: entry.isDirectory(), + isFile: entry.isFile(), + }) + } + return found +} + +/** + * Regular files only, as `find -type f` gave: a symlink is skipped, so a later + * write to a found path never lands outside the project through it. + */ +function findFiles(root, matches) { + return walkTree(root) + .filter((entry) => entry.isFile && matches(entry.name)) + .map((entry) => entry.path) +} + +/** + * A build tree is often still being scanned when it is removed. On Windows that + * means an antivirus or the Gradle daemon holding a file open, so it gets retries. + */ +function removeTree(target) { + fs.rmSync(target, { recursive: true, force: true, maxRetries: 8, retryDelay: 250 }) +} + +function renameWithRetry(from, to) { + for (let attempt = 1; ; attempt++) { + try { + fs.renameSync(from, to) + return + } catch (error) { + if (attempt === 8 || !["EPERM", "EBUSY", "EACCES"].includes(error.code)) throw error + // eslint-disable-next-line no-undef -- the native lint env predates these globals + Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 250) + } + } +} + +/** Depth first, so a directory left empty by removing its children goes as well. */ +function removeEmptyDirectories(root) { + for (const entry of walkTree(root)) { + if (entry.isDirectory && fs.readdirSync(entry.path).length === 0) { + fs.rmdirSync(entry.path) + } + } +} + +/** + * Copy an Android project without its build outputs. The build that follows + * starts with a clean anyway, and they hold the deepest paths in the tree, the + * ones that run into the Windows path length limit. + */ +function copyProjectWithoutOutputs(source, destination) { + // The real path: given a link, cpSync would recreate the link rather than copy + // the project, and the renames that follow would rewrite the original. + const root = fs.realpathSync(source) + const outputs = new Set([".gradle", "build", join("app", "build")].map((dir) => join(root, dir))) + fs.cpSync(root, destination, { + recursive: true, + verbatimSymlinks: true, + preserveTimestamps: true, + filter: (entry) => !outputs.has(path.normalize(entry)), + }) +} + +/** + * Replace `dest` with a copy of the web build at `source`, leaving out files + * named in `excluded` at any depth. This was rm -rf and rsync, neither of which + * exist on Windows. The real path is copied: given a link, cpSync would + * recreate the link, and the filter would never see the files it leaves out. + */ +function copyWebBuild(source, dest, excluded = new Set()) { + fs.rmSync(dest, { recursive: true, force: true }) + fs.mkdirSync(dest, { recursive: true }) + fs.cpSync(fs.realpathSync(source), dest, { + recursive: true, + filter: (file) => !excluded.has(path.basename(file)), + }) +} + +module.exports = { + walkTree, + findFiles, + removeTree, + renameWithRetry, + removeEmptyDirectories, + copyProjectWithoutOutputs, + copyWebBuild, +} diff --git a/packages/catalyst-core/src/native/renameAndroidProject.js b/packages/catalyst-core/src/native/renameAndroidProject.js index f27f7c529..378952e87 100644 --- a/packages/catalyst-core/src/native/renameAndroidProject.js +++ b/packages/catalyst-core/src/native/renameAndroidProject.js @@ -5,6 +5,7 @@ var _fs = _interopRequireDefault(require("fs")) var _path = _interopRequireDefault(require("path")) var _utils = require("./utils.js") var _theme = require("../cli/theme.js") +var _projectFiles = require("./projectFiles.js") var _output = require("./buildAndroid/output.js") function _interopRequireDefault(e) { @@ -165,17 +166,12 @@ async function createSignedAAB(projectPaths, androidConfig) { _fs.default.chmodSync(gradlewPath, 0o755) const common = [`-PconfigPath=${gradle.configPath}`, "-PcatalystBuildType=release", "--console=plain"] + // runGradle: gradlew.bat on Windows, where the gradlew shell script cannot run. const run = (args) => - (0, _utils.runInteractiveCommand)( - gradlewPath, - args, - {}, - { - env: gradle.env, - cwd: absoluteProjectPath, - onLine: (line) => progress.status(gradleTask(line)), - } - ) + (0, _utils.runGradle)(absoluteProjectPath, args, { + env: gradle.env, + onLine: (line) => progress.status(gradleTask(line)), + }) progress.log("Generating the release webview configuration...", "info") await run([ @@ -394,16 +390,19 @@ async function diagnoseAndroidProject(projectPath) { if (diagnostics.missingFiles.length > 0) { progress.log("Searching for missing files in alternate locations...", "info") try { - const findBuildFiles = `find "${projectPath}" \\( -name "build.gradle" -o -name "build.gradle.kts" -o -name "settings.gradle" -o -name "settings.gradle.kts" -o -name "AndroidManifest.xml" \\) -type f` - const foundFiles = (0, _utils.runCommand)(findBuildFiles) - if (foundFiles.trim()) { + const buildFileNames = new Set([ + "build.gradle", + "build.gradle.kts", + "settings.gradle", + "settings.gradle.kts", + "AndroidManifest.xml", + ]) + const foundFiles = (0, _projectFiles.findFiles)(projectPath, (name) => buildFileNames.has(name)) + if (foundFiles.length > 0) { progress.log("Found build files in unexpected locations:", "info") - foundFiles - .trim() - .split("\n") - .forEach((file) => { - progress.log(` ${file}`, "info") - }) + foundFiles.forEach((file) => { + progress.log(` ${file}`, "info") + }) } } catch (searchError) { progress.log("Could not search for alternative file locations", "warning") @@ -484,7 +483,10 @@ async function createBackup(projectPaths, androidConfig) { const backupPath = `${projectPaths.oldProjectPath}_backup_${Date.now()}` try { - ;(0, _utils.runCommand)(`cp -r "${projectPaths.oldProjectPath}" "${backupPath}"`) + _fs.default.cpSync(projectPaths.oldProjectPath, backupPath, { + recursive: true, + verbatimSymlinks: true, + }) progress.log(`Backup created at: ${backupPath}`, "success") return backupPath } catch (error) { @@ -507,7 +509,7 @@ async function createTempDeploymentProject(projectPaths, androidConfig) { if (_fs.default.existsSync(tempDir)) { progress.log(`Removing existing temp directory: ${tempDir}`, "info") try { - ;(0, _utils.runCommand)(`rm -rf "${tempDir}"`) + ;(0, _projectFiles.removeTree)(tempDir) } catch (cleanupError) { progress.log( `Warning: Could not remove existing temp directory: ${cleanupError.message}`, @@ -526,13 +528,12 @@ async function createTempDeploymentProject(projectPaths, androidConfig) { const sourceFiles = _fs.default.readdirSync(oldProjectPath) progress.log(`Source directory contents: ${sourceFiles.join(", ")}`, "info") - // Copy the entire project to the temporary location using rsync for better file preservation + // Copy the project to the temporary location progress.log(`Copying project to temporary location...`, "info") progress.log(`Source: ${oldProjectPath}`, "info") progress.log(`Temp destination: ${tempDir}`, "info") - // Use rsync to preserve all file attributes and handle symlinks properly - ;(0, _utils.runCommand)(`rsync -av "${oldProjectPath}/" "${tempDir}/"`) + ;(0, _projectFiles.copyProjectWithoutOutputs)(oldProjectPath, tempDir) progress.log(`Created temporary copy for building`, "success") // Only check for gradlew which is absolutely essential for building @@ -573,7 +574,7 @@ async function createTempDeploymentProject(projectPaths, androidConfig) { // Clean up on error if (_fs.default.existsSync(tempDir)) { try { - ;(0, _utils.runCommand)(`rm -rf "${tempDir}"`) + ;(0, _projectFiles.removeTree)(tempDir) } catch (cleanupError) { progress.log(`Warning: Could not cleanup temp directory: ${cleanupError.message}`, "warning") } @@ -583,25 +584,18 @@ async function createTempDeploymentProject(projectPaths, androidConfig) { // Find and rename any subdirectories that contain the old project name within the temp copy try { - const findCommand = `find "${tempDir}" -type d -name "*${oldProjectName}*"` - const result = (0, _utils.runCommand)(findCommand) - - if (result.trim()) { - const dirsToRename = result - .trim() - .split("\n") - .filter((dir) => dir.trim()) - - for (const dir of dirsToRename) { - const newDirName = dir.split(oldProjectName).join(newProjectName) - if (dir !== newDirName) { - // fs, not a shell: newProjectName comes from the app's config. - _fs.default.renameSync(dir, newDirName) - progress.log( - `Renamed subdirectory: ${_path.default.basename(dir)} → ${_path.default.basename(newDirName)}`, - "success" - ) - } + const dirsToRename = (0, _projectFiles.walkTree)(tempDir).filter( + (entry) => entry.isDirectory && entry.name.includes(oldProjectName) + ) + + for (const dir of dirsToRename) { + const newDirName = dir.name.split(oldProjectName).join(newProjectName) + if (dir.name !== newDirName) { + ;(0, _projectFiles.renameWithRetry)( + dir.path, + _path.default.join(_path.default.dirname(dir.path), newDirName) + ) + progress.log(`Renamed subdirectory: ${dir.name} → ${newDirName}`, "success") } } } catch (error) { @@ -666,7 +660,7 @@ async function cleanupTempDeployment(tempDeploymentPath) { try { progress.log("Cleaning up temporary deployment files...", "info") - ;(0, _utils.runCommand)(`rm -rf "${tempDeploymentPath}"`) + ;(0, _projectFiles.removeTree)(tempDeploymentPath) progress.log("Temporary files cleaned up successfully", "success") } catch (error) { progress.log(`Warning: Could not cleanup temporary directory: ${error.message}`, "warning") @@ -737,8 +731,7 @@ async function updateFileContents(projectPaths, androidConfig) { _fs.default.mkdirSync(newPackageDir, { recursive: true }) // Move source files - // fs, not a shell: the path is built from the app id. - _fs.default.renameSync(oldPackagePath, newPackagePath) + ;(0, _projectFiles.renameWithRetry)(oldPackagePath, newPackagePath) progress.log(`Moved ${sourceSet} source files to: ${newPackagePath}`, "success") } else { progress.log( @@ -748,10 +741,10 @@ async function updateFileContents(projectPaths, androidConfig) { } // Update package declarations in source files - const sourceFiles = _fs.default - .readdirSync(newPackagePath, { recursive: true, withFileTypes: true }) - .filter((entry) => entry.isFile() && /\.(kt|java)$/.test(entry.name)) - .map((entry) => _path.default.join(entry.parentPath || entry.path, entry.name)) + const sourceFiles = (0, _projectFiles.findFiles)( + newPackagePath, + (name) => name.endsWith(".kt") || name.endsWith(".java") + ) let updatedCount = 0 for (const file of sourceFiles) { @@ -770,8 +763,8 @@ async function updateFileContents(projectPaths, androidConfig) { // Clean up old empty directories try { - ;(0, _utils.runCommand)( - `find "${_path.default.join(newProjectPath, "app", "src", sourceSet, "java")}" -type d -empty -delete` + ;(0, _projectFiles.removeEmptyDirectories)( + _path.default.join(newProjectPath, "app", "src", sourceSet, "java") ) } catch (err) { // Ignore cleanup errors @@ -813,75 +806,52 @@ async function updateFileContents(projectPaths, androidConfig) { } // STEP 2: Find and rename files that contain the old project name - const findFilesCommand = `find "${newProjectPath}" -type f -name "*${oldProjectName}*"` - const fileResult = (0, _utils.runCommand)(findFilesCommand) - - if (fileResult.trim()) { - const filesToRename = fileResult - .trim() - .split("\n") - .filter((file) => file.trim()) - - for (const file of filesToRename) { - const newFileName = file.split(oldProjectName).join(newProjectName) - if (file !== newFileName) { - _fs.default.renameSync(file, newFileName) - progress.log( - `Renamed file: ${_path.default.basename(file)} → ${_path.default.basename(newFileName)}`, - "success" - ) - } + const filesToRename = (0, _projectFiles.findFiles)(newProjectPath, (name) => + name.includes(oldProjectName) + ) + + for (const file of filesToRename) { + const fileName = _path.default.basename(file) + const newFileName = fileName.split(oldProjectName).join(newProjectName) + if (fileName !== newFileName) { + ;(0, _projectFiles.renameWithRetry)( + file, + _path.default.join(_path.default.dirname(file), newFileName) + ) + progress.log(`Renamed file: ${fileName} → ${newFileName}`, "success") } } // STEP 3: Update file contents that reference the old project name const fileTypes = [ - "*.gradle", - "*.gradle.kts", - "*.xml", - "*.json", - "*.properties", - "*.java", - "*.kt", - "*.kts", - "*.js", - "*.ts", - "*.md", + ".gradle", + ".xml", + ".json", + ".properties", + ".java", + ".kt", + ".kts", + ".js", + ".ts", + ".md", ] + const textFiles = (0, _projectFiles.findFiles)(newProjectPath, (name) => + fileTypes.includes(_path.default.extname(name)) + ) - for (const fileType of fileTypes) { + for (const file of textFiles) { try { - const findContentCommand = `find "${newProjectPath}" -name "${fileType}" -type f` - const files = (0, _utils.runCommand)(findContentCommand) - - if (files.trim()) { - const fileList = files - .trim() - .split("\n") - .filter((file) => file.trim()) - - for (const file of fileList) { - try { - const content = _fs.default.readFileSync(file, "utf8") - if (content.includes(oldProjectName)) { - const updatedContent = content.split(oldProjectName).join(newProjectName) - _fs.default.writeFileSync(file, updatedContent, "utf8") - progress.log( - `Updated content in: ${_path.default.relative(newProjectPath, file)}`, - "info" - ) - } - } catch (fileError) { - progress.log( - `Warning: Could not update file ${file}: ${fileError.message}`, - "warning" - ) - } - } + const content = _fs.default.readFileSync(file, "utf8") + if (content.includes(oldProjectName)) { + const updatedContent = content.split(oldProjectName).join(newProjectName) + _fs.default.writeFileSync(file, updatedContent, "utf8") + progress.log( + `Updated content in: ${_path.default.relative(newProjectPath, file)}`, + "info" + ) } - } catch (typeError) { - // Continue with other file types if one fails - progress.log(`Warning: Error processing ${fileType} files: ${typeError.message}`, "warning") + } catch (fileError) { + progress.log(`Warning: Could not update file ${file}: ${fileError.message}`, "warning") } } diff --git a/packages/catalyst-core/src/native/setupEmulatorIos.js b/packages/catalyst-core/src/native/setupEmulatorIos.js index 4eb3e5568..891a4f099 100644 --- a/packages/catalyst-core/src/native/setupEmulatorIos.js +++ b/packages/catalyst-core/src/native/setupEmulatorIos.js @@ -5,6 +5,7 @@ import { ensureXcodeReady, ensureIosRuntime, ensureSimulator } from "./iosToolch import { getLastTarget } from "./localState.js" import TerminalProgress from "./terminalProgress.js" import { buildFailure } from "../cli/diagnostic.js" +import { iosRequiresMacError } from "./iosPlatform.js" // `catalyst setupEmulator:ios`: install what an iOS debug build needs on this // Mac (Xcode's licence and first-launch components, a simulator runtime, the @@ -39,10 +40,8 @@ async function setupIOSEnvironment() { const flags = parseNativeArgs(process.argv.slice(2)) progress.start("platform") - if (process.platform !== "darwin") { - progress.log("iOS Simulator is only available on macOS.", "error") - process.exit(1) - } + // Coded, so the catch below prints IOS-007 with its hint and doc link. + if (process.platform !== "darwin") throw iosRequiresMacError() progress.complete("platform") progress.start("xcode") diff --git a/packages/catalyst-core/src/native/setupServer.js b/packages/catalyst-core/src/native/setupServer.js index 22aab2792..48d7baf20 100644 --- a/packages/catalyst-core/src/native/setupServer.js +++ b/packages/catalyst-core/src/native/setupServer.js @@ -5,6 +5,7 @@ import net from "net" import os from "os" import path from "path" import { isInteractive, nativeError, promptUser } from "./utils.js" +import platform from "../cli/platform.js" import { appIdProblem, appIdSource, @@ -203,6 +204,8 @@ function startDevServerProcess({ cwd, port, overrides = {}, spawnProcess = spawn cwd, detached: true, stdio: ["ignore", out, out], + // Otherwise detached opens an empty console window on Windows. + windowsHide: true, // `catalyst start` reads the app from PWD, not cwd. env: { ...process.env, PWD: cwd }, }) @@ -260,6 +263,7 @@ function startedDevServer({ cwd, port, isAlive }) { * @param {typeof isServerAnswering} [options.probe] - for tests * @param {typeof startDevServerProcess} [options.start] - for tests * @param {(pid: number) => boolean} [options.isAlive] - for tests + * @param {boolean} [options.ipv4] - the target reaches loopback on 127.0.0.1 only (Android on Windows, through adb reverse) * @returns {Promise<{ started: boolean, url: string, port: number, logFile?: string }>} */ async function ensureDevServer({ @@ -273,6 +277,7 @@ async function ensureDevServer({ probe = isServerAnswering, start = startDevServerProcess, isAlive = isProcessAlive, + ipv4 = false, } = {}) { const appConfig = // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal - cwd is the app root; the file name is fixed. @@ -281,7 +286,10 @@ async function ensureDevServer({ const loopback = isLoopback(host) const hostPart = String(host).includes(":") ? `[${host}]` : host const url = `http://${hostPart}:${port}` - const answers = () => probe({ host: loopback ? "localhost" : host, port }) + // ipv4: the target reaches loopback on 127.0.0.1 only (adb reverse dials the + // host there), so that is the address that has to answer. + const loopbackProbeHost = ipv4 ? "127.0.0.1" : "localhost" + const answers = () => probe({ host: loopback ? loopbackProbeHost : host, port }) const hostKey = loopback ? "localhost" : String(host).toLowerCase() if (await answers()) { @@ -291,13 +299,24 @@ async function ensureDevServer({ "NATIVE-006", `the dev server on port ${port} was started for ${ours.host}, and this build needs ${url}`, { - hint: `Stop that dev server (kill ${ours.pid}) and run the build again, so Catalyst starts one for ${hostKey}.`, + hint: `Stop that dev server (${platform.stopProcessCommand(ours.pid)}) and run the build again, so Catalyst starts one for ${hostKey}.`, } ) } log(`Dev server already running at ${url}`, "info") return { started: false, url, port } } + // Windows resolves localhost to ::1 first, so a dev server started there with + // NODE_SERVER_HOSTNAME "localhost" listens on IPv6 only, out of adb's reach. + if (loopback && ipv4 && (await probe({ host: "localhost", port }))) { + throw nativeError( + "NATIVE-006", + `the dev server on port ${port} answers on localhost but not on 127.0.0.1, which the emulator and USB phones reach it through`, + { + hint: 'Stop that dev server and run the build again, so Catalyst starts one on 127.0.0.1, or set NODE_SERVER_HOSTNAME to "127.0.0.1" in config/config.json.', + } + ) + } if (!loopback && (await probe({ host: "localhost", port }))) { throw nativeError( "NATIVE-006", @@ -309,7 +328,13 @@ async function ensureDevServer({ } const startOverrides = { - ...(loopback ? {} : { NODE_SERVER_HOSTNAME: "0.0.0.0", PUBLIC_STATIC_ASSET_URL: url }), + ...(loopback + ? // "localhost" can bind ::1 alone (Windows resolves it to ::1 first), and + // adb reverse then gets an empty response on 127.0.0.1. + ipv4 + ? { NODE_SERVER_HOSTNAME: "127.0.0.1" } + : {} + : { NODE_SERVER_HOSTNAME: "0.0.0.0", PUBLIC_STATIC_ASSET_URL: url }), // Vite 6 answers 403 to a Host header that is not localhost or an IP // (server.allowedHosts), so a `.local` name has to be allowed. ...(loopback || net.isIP(host) ? {} : { CATALYST_DEV_ALLOWED_HOSTS: host }), @@ -317,6 +342,14 @@ async function ensureDevServer({ } const { child, logFile } = start({ cwd, port, overrides: startOverrides }) log(`Starting the dev server at ${url} (output in ${logFile})`, "info") + // It outlives this build. On Windows a running process keeps its files + // locked, so npm install fails with EBUSY until it is stopped. + if (platform.isWindows() && child?.pid) { + log( + `It keeps running after the build; stop it with ${platform.stopProcessCommand(child.pid)}`, + "note" + ) + } if (Number.isInteger(child?.pid)) { writeLocalState({ devServer: { host: hostKey, port, pid: child.pid } }, { cwd }) } diff --git a/packages/catalyst-core/src/native/utils.js b/packages/catalyst-core/src/native/utils.js index b17312b41..baba2f47a 100644 --- a/packages/catalyst-core/src/native/utils.js +++ b/packages/catalyst-core/src/native/utils.js @@ -5,9 +5,11 @@ import os from "os" import path from "path" import theme from "../cli/theme.js" import spinnerModule from "../cli/spinner.js" +import platform from "../cli/platform.js" const { GUTTER, t } = theme const { withSpinnersPaused } = spinnerModule +const { batchInvocation, isWindows } = platform // Retain only the tail of a child's output: it is used for diagnostics, and a // long gradle build would otherwise hold every byte it ever printed in memory. @@ -124,7 +126,7 @@ function assertToolPath(file) { function commandExists(command) { try { // nosemgrep: javascript.lang.security.detect-child-process.detect-child-process - Utility checks known local tool names during native setup. - execSync(`which ${command}`, { stdio: "ignore" }) + execSync(`${isWindows() ? "where" : "which"} ${command}`, { stdio: "ignore" }) return true } catch (error) { return false @@ -142,7 +144,11 @@ function isTimeout(error) { * later call hangs too. Name the tool and the reset that clears it. */ function toolTimeoutError(command, timeout) { - const tool = path.basename(String(command).trim().split(/\s+/)[0].replace(/^"|"$/g, "")) + // The first word, which may be a quoted path with spaces in it, named the way + // the hints below name it: adb.exe is still adb. + const [, quoted, bare] = /^\s*(?:"([^"]+)"|(\S+))/.exec(String(command)) || [] + // path.win32 splits on both separators, wherever this runs. + const tool = path.win32.basename(quoted ?? bare ?? "").replace(/\.(exe|bat|cmd)$/i, "") const seconds = Math.round(timeout / 1000) const error = new Error(`${tool} did not respond within ${seconds}s`) error.code = "ETOOLTIMEOUT" @@ -220,12 +226,22 @@ function detectAndroidSdk(env = process.env) { return candidates.find((dir) => fs.existsSync(path.join(dir, "platform-tools", adb))) || null } +/** Where an SDK keeps the tools the native commands run. */ +function androidTools(sdkPath) { + const exe = isWindows() ? ".exe" : "" + return { + // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal - sdkPath is a local SDK directory from config or auto-detection, never remote input. + adb: path.join(sdkPath, "platform-tools", `adb${exe}`), + // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal - sdkPath is a local SDK directory from config or auto-detection, never remote input. + emulator: path.join(sdkPath, "emulator", `emulator${exe}`), + } +} + /** AVD names known to the SDK's emulator, or [] when it cannot be asked. */ function listAvds(sdkPath) { if (!sdkPath) return [] try { - // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal - sdkPath is a local SDK directory from config or auto-detection, never remote input. - const emulator = path.join(expandHome(sdkPath), "emulator", "emulator") + const emulator = androidTools(expandHome(sdkPath)).emulator assertToolPath(emulator) // nosemgrep: javascript.lang.security.detect-child-process.detect-child-process - argv array, no shell. const out = execFileSync(emulator, ["-list-avds"], { @@ -251,8 +267,9 @@ function expandHome(dir) { } /** The hint for a missing or wrong SDK path, naming the one field to set. */ -const ANDROID_SDK_HINT = - 'Run catalyst setupEmulator:android to install it, or set WEBVIEW_CONFIG.android.sdkPath in config/config.json (e.g. "~/Library/Android/sdk").' +const ANDROID_SDK_HINT = `Run catalyst setupEmulator:android to install it, or set WEBVIEW_CONFIG.android.sdkPath in config/config.json (e.g. "${ + isWindows() ? "C:/Users/you/AppData/Local/Android/Sdk" : "~/Library/Android/sdk" +}").` /** * Write the SDK location gradle reads. `setupEmulator:android` used to be the @@ -275,6 +292,16 @@ function ensureLocalProperties(projectDir, sdkPath) { return true } +/** + * The spawn() call for a command. Node refuses to spawn a .bat or .cmd file + * directly on Windows (EINVAL), and sdkmanager, avdmanager and gradlew are all + * batch files there, so those go through cmd.exe via batchInvocation. + */ +function spawnInvocation(command, args) { + if (isWindows() && /\.(bat|cmd)$/i.test(String(command))) return batchInvocation(command, args) + return { command, args, options: {} } +} + /** * Run a command, keeping its output rather than printing it. * @@ -284,6 +311,7 @@ function ensureLocalProperties(projectDir, sdkPath) { * @param {object} [options] * @param {NodeJS.ProcessEnv} [options.env] - the child's environment (defaults to this process's) * @param {string} [options.cwd] - the child's working directory + * @param {boolean} [options.windowsVerbatimArguments] - for a batch file run through cmd.exe (see batchInvocation) * @param {(line: string) => void} [options.onLine] - called per output line. * Without it the output is captured silently. Gradle and xcodebuild emit * hundreds of lines that nobody reads on success and that are redundant on @@ -291,17 +319,25 @@ function ensureLocalProperties(projectDir, sdkPath) { * way. Callers that want progress pass a handler that summarises, rather * than letting the raw stream scroll. */ -async function runInteractiveCommand(command, args, promptResponses = {}, { onLine, env, cwd } = {}) { +async function runInteractiveCommand( + command, + args, + promptResponses = {}, + { onLine, env, cwd, windowsVerbatimArguments } = {} +) { return new Promise((resolve, reject) => { // Named `child`, not `process`: the previous name shadowed the global // `process` for the whole function body. // `env` is how secrets reach a child (ORG_GRADLE_PROJECT_*): never argv, // where ps and the failure echo would show them. // nosemgrep: javascript.lang.security.detect-child-process.detect-child-process - Native build commands are fixed internal commands passed with argv arrays. - const child = spawn(command, args, { + const invocation = spawnInvocation(command, args) + const child = spawn(invocation.command, invocation.args, { stdio: ["pipe", "pipe", "pipe"], ...(env ? { env } : {}), ...(cwd ? { cwd } : {}), + ...(windowsVerbatimArguments ? { windowsVerbatimArguments } : {}), + ...invocation.options, }) let promptBuffer = "" @@ -388,6 +424,30 @@ function handlePrompts(child, buffer, promptResponses) { return buffer } +// No lasting daemon on Windows, which cannot rename or delete what a process has +// open. One sitting idle for its usual three hours holds the Android project under +// node_modules, so `npm install` fails with EBUSY and the signed build cannot remove +// its temp copy. Every build here starts with a clean, so a warm daemon saves little. +const GRADLE_WINDOWS_ARGS = ["--no-daemon"] + +/** + * Run the Gradle wrapper in a project, keeping its output as runInteractiveCommand + * does. Arguments are passed as a list, so a path with spaces stays one argument. + */ +function runGradle(projectDir, args, { onLine, env } = {}) { + const invocation = isWindows() + ? // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal - projectDir is the Android project inside this package. + batchInvocation(path.join(projectDir, "gradlew.bat"), [...GRADLE_WINDOWS_ARGS, ...args]) + : { command: "./gradlew", args, options: {} } + return runInteractiveCommand( + invocation.command, + invocation.args, + { "BUILD SUCCESSFUL": "" }, + // env carries the signing and version values (ORG_GRADLE_PROJECT_*), never argv. + { onLine, env, cwd: projectDir, ...invocation.options } + ) +} + /** * Run a command on the user's own terminal: inherited stdio, so they see its * progress and can answer it (a sudo password, a licence). The spinner is @@ -404,10 +464,12 @@ async function runInheritedCommand(command, args, { env, cwd } = {}) { () => new Promise((resolve, reject) => { // nosemgrep: javascript.lang.security.detect-child-process.detect-child-process - Fixed setup commands with argv arrays, run after the user agreed. - const child = spawn(command, args, { + const invocation = spawnInvocation(command, args) + const child = spawn(invocation.command, invocation.args, { stdio: "inherit", ...(env ? { env } : {}), ...(cwd ? { cwd } : {}), + ...invocation.options, }) child.on("error", (error) => reject( @@ -442,7 +504,7 @@ const NATIVE_ERRORS = { }, "ANDROID-007": { message: "No JDK 17 to 23 found", - hint: "Install JDK 17 or 21 (macOS: brew install --cask zulu@17; Linux: your distribution's openjdk-17-jdk package) and set JAVA_HOME, or run catalyst buildApp:android in a terminal, or with --yes, to install it.", + hint: "Install JDK 17 or 21 (macOS: brew install --cask zulu@17; Linux: your distribution's openjdk-17-jdk package; Windows: Android Studio, or winget install Microsoft.OpenJDK.17) and set JAVA_HOME, or on macOS run catalyst buildApp:android in a terminal, or with --yes, to install it.", }, "ANDROID-008": { message: "Android SDK setup was declined", @@ -740,8 +802,10 @@ export { commandExists, promptUser, detectAndroidSdk, + androidTools, listAvds, ensureLocalProperties, + runGradle, ANDROID_SDK_HINT, runInteractiveCommand, runInheritedCommand, diff --git a/packages/catalyst-core/src/scripts/build.js b/packages/catalyst-core/src/scripts/build.js index a20aae83a..69dafdb7e 100644 --- a/packages/catalyst-core/src/scripts/build.js +++ b/packages/catalyst-core/src/scripts/build.js @@ -28,12 +28,13 @@ const { loadAppConfig } = requireCjs("../cli/appConfig.js") const { bundleWarnings } = requireCjs("../cli/buildWarnings.js") const { extractBuildErrors, outputTail } = requireCjs("../cli/buildErrors.js") const { hintFor } = requireCjs("../cli/hints.js") +const { appRoot } = requireCjs("../cli/platform.js") const loaderPath = path.resolve(__dirname, "../../dist/vite/node-loader.mjs") // A missing or malformed config used to throw a raw ENOENT/SyntaxError stack at // module load, before any output at all. Note the "utf-8" was being passed as // JSON.parse's reviver argument, not as the read encoding. -const configJSON = loadAppConfig(process.env.PWD || process.cwd()) +const configJSON = loadAppConfig(appRoot()) // Resolve vite's actual JS entry point rather than spawning the "vite" command name, // which on Windows only resolves via the npm-installed .cmd shim (i.e. requires a shell). @@ -109,7 +110,11 @@ function runBuildStep(args, options, label = "Build step") { * the bundles they broke become a dim suffix rather than a second block. */ function shortenPaths(text, cwd) { - return String(text).split(`${cwd}/`).join("") + // Both spellings: on Windows the bundler reports C:/app/ as often as C:\app\. + return [`${cwd}${path.sep}`, `${cwd.split(path.sep).join("/")}/`].reduce( + (shortened, prefix) => shortened.split(prefix).join(""), + String(text) + ) } /** A step's own last words, fenced under the diagnostic that names it. */ @@ -171,7 +176,7 @@ function reportBundleFailures(failures, cwd) { code, scope: `${cause.bundles.join(" + ")} bundle`, // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal - cause.file is a build-tool diagnostic path, only used to display a location. - file: cause.file ? path.resolve(cwd, cause.file.replace(/^(\.\.\/)+/, "")) : undefined, + file: cause.file ? path.resolve(cwd, cause.file.replace(/^(\.\.[\\/])+/, "")) : undefined, line: cause.line, // esbuild reports columns 0-based; the frame's caret is 1-based. column: cause.column != null ? cause.column + 1 : undefined, @@ -261,14 +266,15 @@ async function build() { const argumentsObject = arrayToObject(commandLineArguments) const outputMode = resolveOutputMode(process.argv) const dirname = path.resolve(__dirname, "../../") + const appDir = appRoot() // Read package.json - const packageJson = JSON.parse(readFileSync(path.join(process.env.PWD, "package.json"), "utf-8")) + const packageJson = JSON.parse(readFileSync(path.join(appDir, "package.json"), "utf-8")) const { name } = packageJson process.stdout.write(header("catalyst build", "production")) - const buildOutputPath = path.join(process.env.PWD, configJSON.BUILD_OUTPUT_PATH || "build") + const buildOutputPath = path.join(appDir, configJSON.BUILD_OUTPUT_PATH || "build") if (existsSync(buildOutputPath)) { const cleaning = Date.now() rmSync(buildOutputPath, { recursive: true, force: true }) @@ -281,7 +287,7 @@ async function build() { // bundler would drop colour. Forward our own terminal's answer, so a // redirect to a file still comes out plain. ...(process.stdout.isTTY && !process.env.NO_COLOR ? { FORCE_COLOR: "1" } : {}), - src_path: process.env.PWD, + src_path: appDir, NODE_ENV: "production", VITE_BUILD_MODE: "true", APPLICATION: name || "catalyst_app", @@ -327,7 +333,7 @@ async function build() { if (failures.length > 0) { bundling.stop("fail", "Build failed") - process.stderr.write(reportBundleFailures(failures, process.env.PWD)) + process.stderr.write(reportBundleFailures(failures, appDir)) // --verbose/--debug add the registry code and the bundler's full // output under the extracted errors. if (outputMode !== "default") { @@ -359,7 +365,7 @@ async function build() { } // Lets `serve` refuse a build that no longer matches config/config.json. - writeBuildInfo(process.env.PWD, configJSON, argumentsObject) + writeBuildInfo(appDir, configJSON, argumentsObject) const manifest = new Spinner().start("Generating offline manifest") try { diff --git a/packages/catalyst-core/src/scripts/preServerInit.js b/packages/catalyst-core/src/scripts/preServerInit.js index cdd1633bd..d760fa1a9 100644 --- a/packages/catalyst-core/src/scripts/preServerInit.js +++ b/packages/catalyst-core/src/scripts/preServerInit.js @@ -1,5 +1,6 @@ import path from "path" import { createRequire } from "module" +import { pathToFileURL } from "url" import loadEnvironmentVariables from "./loadEnvironmentVariables.js" import { validatePreInitServer, @@ -62,7 +63,7 @@ if (!isValid) { let preServerInit try { - const hooks = await import(path.join(appRoot, "server/index.js")) + const hooks = await import(pathToFileURL(path.join(appRoot, "server/index.js")).href) preServerInit = hooks.preServerInit // Hooks are read by name, so ones inside `export default { ... }` never // run. One line: the dev output wrapper shows it under Notices. diff --git a/packages/catalyst-core/src/scripts/preflight.js b/packages/catalyst-core/src/scripts/preflight.js index 5a3362467..b9102105d 100644 --- a/packages/catalyst-core/src/scripts/preflight.js +++ b/packages/catalyst-core/src/scripts/preflight.js @@ -12,6 +12,7 @@ import { resolveOutputMode, getDebugEnvInfo } from "./scriptUtils.js" const requireCjs = createRequire(import.meta.url) const { registryFailure } = requireCjs("../cli/diagnostic.js") const { GUTTER, glyph, t } = requireCjs("../cli/theme.js") +const { appRoot } = requireCjs("../cli/platform.js") /** * A registry error as the CLI shows it: the diagnostic block by default, the @@ -50,14 +51,11 @@ function readJson(filePath) { /** * Run the static preflight checks against an app directory. - * @param {string} [appDir] - the consumer app root. Defaults to the current - * working directory. `process.env.PWD` is preferred when set (it survives a - * `cd` in the invoking shell script), but it is not exported by every shell - * / CI runner, so `process.cwd()` is the fallback — never `undefined`, which - * would make the `path.join` calls below throw. + * @param {string} [appDir] - the consumer app root. Defaults to appRoot(), the + * one place that decides between `process.env.PWD` and `process.cwd()`. * @returns {import("../errors/index.js").CatalystError[]} all failures (empty = passed) */ -export function runStaticPreflight(appDir = process.env.PWD || process.cwd()) { +export function runStaticPreflight(appDir = appRoot()) { const failures = [] // config/config.json @@ -119,7 +117,7 @@ export function runStaticPreflight(appDir = process.env.PWD || process.cwd()) { * of a CLI entry script (start / serve / build). * @param {string} [appDir] */ -export function runStaticPreflightOrExit(appDir = process.env.PWD || process.cwd()) { +export function runStaticPreflightOrExit(appDir = appRoot()) { const mode = resolveOutputMode(process.argv) const failures = runStaticPreflight(appDir) if (failures.length === 0) return @@ -180,7 +178,7 @@ export function writeBuildInfo(appDir, config, args = {}) { * @param {Record} [args] * @returns {import("../errors/index.js").CatalystError | null} */ -export function checkBuildMatchesConfig(appDir = process.env.PWD || process.cwd(), args = {}) { +export function checkBuildMatchesConfig(appDir = appRoot(), args = {}) { const skip = (reason) => { console.warn(`${GUTTER}${t.warn(glyph.warn)} ${t.dim(`Skipping the build/config check: ${reason}`)}`) return null diff --git a/packages/catalyst-core/src/scripts/serve.js b/packages/catalyst-core/src/scripts/serve.js index b8d8021d4..56729f082 100644 --- a/packages/catalyst-core/src/scripts/serve.js +++ b/packages/catalyst-core/src/scripts/serve.js @@ -2,7 +2,7 @@ import path from "path" import { spawn } from "child_process" import { arrayToObject, loaderImportArg, resolveOutputMode } from "./scriptUtils.js" import { runStaticPreflightOrExit, checkBuildMatchesConfig, renderRegistryError } from "./preflight.js" -import { fileURLToPath } from "url" +import { fileURLToPath, pathToFileURL } from "url" import { dirname } from "path" import { existsSync, readFileSync } from "fs" import { createRequire } from "module" @@ -14,9 +14,11 @@ const requireCjs = createRequire(import.meta.url) const { diagnostic } = requireCjs("../cli/diagnostic.js") const { superviseServer, ensurePortFree } = requireCjs("../cli/devOutput.js") const { loadAppConfig } = requireCjs("../cli/appConfig.js") +const { appRoot } = requireCjs("../cli/platform.js") const loaderPath = path.resolve(__dirname, "../../dist/vite/node-loader.mjs") -const preInitPath = path.resolve(__dirname, "preServerInit.js") +// A URL: --import takes a module specifier, and C:\ reads as a scheme. +const preInitUrl = pathToFileURL(path.resolve(__dirname, "preServerInit.js")).href /** * @description - serves the production build @@ -35,24 +37,25 @@ async function startProd() { const argumentsObject = arrayToObject(commandLineArguments) const outputMode = resolveOutputMode(process.argv) const dirname = path.resolve(__dirname, "../../") + const appDir = appRoot() // Read package.json - const packageJson = JSON.parse(readFileSync(path.join(process.env.PWD, "package.json"), "utf-8")) + const packageJson = JSON.parse(readFileSync(path.join(appDir, "package.json"), "utf-8")) const { name } = packageJson // Serving a build that was never made produces a stack trace from deep // inside the server. Say the useful thing instead. // From config.json, not the env: config values are promoted to env only // inside the child, so reading env here always saw the default. - const appConfig = loadAppConfig(process.env.PWD || process.cwd()) + const appConfig = loadAppConfig(appDir) const buildDir = path.join( - process.env.PWD, + appDir, appConfig.BUILD_OUTPUT_PATH || process.env.BUILD_OUTPUT_PATH || "build" ) if (!existsSync(buildDir)) { process.stderr.write( diagnostic({ - message: `No production build in ${path.relative(process.env.PWD, buildDir) || buildDir}/`, + message: `No production build in ${path.relative(appDir, buildDir) || buildDir}/`, scope: "server", hint: "Run catalyst build first, then catalyst serve.", }) @@ -76,11 +79,11 @@ async function startProd() { const inspectArgs = commandLineArguments.includes("--inspect") ? ["--inspect"] : [] const child = spawn( - "node", + process.execPath, [ ...inspectArgs, "--import", - preInitPath, + preInitUrl, "--import", loaderImportArg(loaderPath), "./dist/server/expressServer.js", @@ -92,7 +95,7 @@ async function startProd() { ...process.env, // When the command was run, so "Ready in" counts the whole wait. CATALYST_STARTED_AT: String(Math.round(performance.timeOrigin)), - src_path: process.env.PWD, + src_path: appDir, NODE_ENV: "production", APPLICATION: name || "catalyst_app", CATALYST_OUTPUT_MODE: outputMode, diff --git a/packages/catalyst-core/src/scripts/start.js b/packages/catalyst-core/src/scripts/start.js index 517825383..569dd30a1 100644 --- a/packages/catalyst-core/src/scripts/start.js +++ b/packages/catalyst-core/src/scripts/start.js @@ -2,7 +2,7 @@ import path from "path" import { spawn } from "child_process" import { arrayToObject, loaderImportArg, resolveOutputMode } from "./scriptUtils.js" import { runStaticPreflightOrExit } from "./preflight.js" -import { fileURLToPath } from "url" +import { fileURLToPath, pathToFileURL } from "url" import { dirname } from "path" import { readFileSync } from "fs" import { createRequire } from "module" @@ -13,9 +13,11 @@ const __dirname = dirname(__filename) const requireCjs = createRequire(import.meta.url) const { superviseServer, ensurePortFree } = requireCjs("../cli/devOutput.js") const { loadAppConfig } = requireCjs("../cli/appConfig.js") +const { appRoot } = requireCjs("../cli/platform.js") const loaderPath = path.resolve(__dirname, "../../dist/vite/node-loader.mjs") -const preInitPath = path.resolve(__dirname, "preServerInit.js") +// A URL: --import takes a module specifier, and C:\ reads as a scheme. +const preInitUrl = pathToFileURL(path.resolve(__dirname, "preServerInit.js")).href /** * @description - starts the dev server @@ -35,12 +37,13 @@ async function start() { const argumentsObject = arrayToObject(commandLineArguments) const outputMode = resolveOutputMode(process.argv) const dirname = path.resolve(__dirname, "../../") + const appDir = appRoot() // Read package.json - const packageJson = JSON.parse(readFileSync(path.join(process.env.PWD, "package.json"), "utf-8")) + const packageJson = JSON.parse(readFileSync(path.join(appDir, "package.json"), "utf-8")) const { name } = packageJson - const appConfig = loadAppConfig(process.env.PWD || process.cwd()) + const appConfig = loadAppConfig(appDir) await ensurePortFree({ port: argumentsObject.NODE_SERVER_PORT || appConfig.NODE_SERVER_PORT, host: argumentsObject.NODE_SERVER_HOSTNAME || appConfig.NODE_SERVER_HOSTNAME, @@ -48,8 +51,8 @@ async function start() { }) const child = spawn( - "node", - ["--import", preInitPath, "--import", loaderImportArg(loaderPath), "./dist/server/expressServer.js"], + process.execPath, + ["--import", preInitUrl, "--import", loaderImportArg(loaderPath), "./dist/server/expressServer.js"], { cwd: dirname, stdio: ["inherit", "pipe", "pipe"], @@ -66,7 +69,7 @@ async function start() { CATALYST_WRAPPED: "1", // When the command was run, so "Ready in" counts the whole wait. CATALYST_STARTED_AT: String(Math.round(performance.timeOrigin)), - src_path: process.env.PWD, + src_path: appDir, NODE_ENV: "development", APPLICATION: name || "catalyst_app", CATALYST_OUTPUT_MODE: outputMode, diff --git a/packages/catalyst-core/src/server/expressServer.ts b/packages/catalyst-core/src/server/expressServer.ts index 44fb443bf..2e93ca9d5 100644 --- a/packages/catalyst-core/src/server/expressServer.ts +++ b/packages/catalyst-core/src/server/expressServer.ts @@ -89,7 +89,12 @@ function lanAddress() { } return null } -const { addMiddlewares } = await import(path.join(process.env.src_path!, "server/server.js")) + +// import() takes a URL. An absolute path only works by accident on POSIX: on +// Windows C:\ reads as a scheme and throws ERR_UNSUPPORTED_ESM_URL_SCHEME. +const importFile = (file: string) => import(pathToFileURL(file).href) + +const { addMiddlewares } = await importFile(path.join(process.env.src_path!, "server/server.js")) // Mount AI route if catalyst-ai is installed function mountAIRouter(app: any) { @@ -154,7 +159,7 @@ const SSR_SERVICE = process.env.SERVICE_NAME || `pwa-${process.env.APPLICATION}- // ─── Load app-defined server lifecycle hooks ────────────────────────────────── let onServerError: any try { - const hooks = await import(path.join(process.env.src_path!, "server/index.js")) + const hooks = await importFile(path.join(process.env.src_path!, "server/index.js")) onServerError = hooks.onServerError } catch { // No hooks file — onServerError remains undefined @@ -212,7 +217,7 @@ process.on("message", function (msg: any) { } }) -import { fileURLToPath } from "url" +import { fileURLToPath, pathToFileURL } from "url" const __filename = fileURLToPath(import.meta.url) const __dirname = path.dirname(__filename) @@ -335,7 +340,7 @@ async function createServer() { "server.js" ) if (fs.existsSync(serverPath)) { - productionRender = await import(serverPath) + productionRender = await importFile(serverPath) } else { const rendererPath = path.join( process.env.src_path!, @@ -343,7 +348,7 @@ async function createServer() { "server", "index.js" ) - productionRender = await import(rendererPath) + productionRender = await importFile(rendererPath) } } diff --git a/packages/catalyst-core/src/vite/dependencyPath.mjs b/packages/catalyst-core/src/vite/dependencyPath.mjs new file mode 100644 index 000000000..9db38d560 --- /dev/null +++ b/packages/catalyst-core/src/vite/dependencyPath.mjs @@ -0,0 +1,11 @@ +/** + * Whether a file path is inside node_modules: a dependency the loader leaves to + * Node, rather than app code it transforms. + * + * Either separator: this is an OS path. Checking for "/" alone missed every + * dependency on Windows, so all of them went down the app-file path and + * `catalyst build` ran out of memory before it printed a single line. + */ +export function isDependencyPath(filePath) { + return /[\\/]node_modules[\\/]/.test(filePath) +} diff --git a/packages/catalyst-core/src/vite/node-loader.mjs b/packages/catalyst-core/src/vite/node-loader.mjs index adf51fe1a..e3db63cf0 100644 --- a/packages/catalyst-core/src/vite/node-loader.mjs +++ b/packages/catalyst-core/src/vite/node-loader.mjs @@ -4,6 +4,7 @@ import { readFileSync, existsSync, statSync } from "fs" import { createRequire } from "module" import { transformSync } from "esbuild" import { getModuleAliases } from "./moduleAliases.js" +import { isDependencyPath } from "./dependencyPath.mjs" // Cache for loaded aliases let aliasCache = null @@ -374,7 +375,7 @@ export async function load(url, context, defaultLoad) { return defaultLoad(url, context) } - const isNodeModule = filePath.includes("/node_modules/") + const isNodeModule = isDependencyPath(filePath) // --- CJS detection and wrapping --- // For node_modules: check via package.json "type" field diff --git a/packages/catalyst-core/src/vite/vite.config.js b/packages/catalyst-core/src/vite/vite.config.js index 20d8f1015..d0a8e7cc5 100644 --- a/packages/catalyst-core/src/vite/vite.config.js +++ b/packages/catalyst-core/src/vite/vite.config.js @@ -459,10 +459,10 @@ export const sharedViteConfig = { // graph. Without this (SSR middleware mode has no index.html), Vite // can't see dynamic `import()` chunks produced by split(), so every // first-navigation discovers new deps and triggers a full reload. - entries: [ - path.join(process.env.src_path, "client/index.js"), - path.join(process.env.src_path, "src/**/*.{js,jsx,ts,tsx}"), - ], + // Relative to root, the app in every dev server: these are globs, and an + // absolute path brings its own backslashes and parentheses into the + // pattern on Windows, where the scanner then matches nothing. + entries: ["client/index.js", "src/**/*.{js,jsx,ts,tsx}"], include: resolvableFrom(candidateBrowserDeps, process.env.src_path), // catalyst-core/webmcp (and its shim subpath) must share the SAME // pre-bundled module instance as catalyst-core's main entry: diff --git a/packages/catalyst-core/test/cli/bin.test.ts b/packages/catalyst-core/test/cli/bin.test.ts new file mode 100644 index 000000000..0220e5db7 --- /dev/null +++ b/packages/catalyst-core/test/cli/bin.test.ts @@ -0,0 +1,39 @@ +import { spawnSync } from "node:child_process" +import { mkdtempSync, rmSync } from "node:fs" +import { tmpdir } from "node:os" +import path from "node:path" +import { fileURLToPath } from "node:url" +import { afterEach, beforeEach, describe, expect, it } from "vitest" + +const bin = fileURLToPath(new URL("../../bin/catalyst.js", import.meta.url)) + +describe("catalyst buildApp and setupEmulator", () => { + let cwd: string + beforeEach(() => { + // No config here, so the Android half stops straight after starting. + cwd = mkdtempSync(path.join(tmpdir(), "catalyst-bin-")) + }) + afterEach(() => rmSync(cwd, { recursive: true, force: true })) + + const run = (command: string) => { + const result = spawnSync(process.execPath, [bin, command], { cwd, encoding: "utf8" }) + return `${result.stdout}${result.stderr}` + } + + // Stopping at iOS would mean never reaching the platform this machine can build. + it.runIf(process.platform !== "darwin").each(["buildApp", "setupEmulator"])( + "%s skips iOS away from a Mac and goes on to Android", + (command) => { + const output = run(command) + expect(output).toContain("Skipping iOS: it needs macOS and Xcode.") + expect(output).not.toContain("IOS-007") + } + ) + + it.runIf(process.platform === "darwin").each(["buildApp", "setupEmulator"])( + "%s does not skip iOS on a Mac", + (command) => { + expect(run(command)).not.toContain("Skipping iOS") + } + ) +}) diff --git a/packages/catalyst-core/test/cli/buildErrors.test.ts b/packages/catalyst-core/test/cli/buildErrors.test.ts index 35a4d3572..da49fd0e9 100644 --- a/packages/catalyst-core/test/cli/buildErrors.test.ts +++ b/packages/catalyst-core/test/cli/buildErrors.test.ts @@ -3,6 +3,7 @@ import { describe, expect, it } from "vitest" import type buildErrorsModule from "../../src/cli/buildErrors.js" import type hintsModule from "../../src/cli/hints.js" +import { onPlatform } from "../onPlatform" // buildErrors.js pulls the real compiler errors out of a native or Vite build // transcript; hints.js maps the failures we understand to a next step. Both @@ -147,9 +148,13 @@ describe("hintFor", () => { }) it("names the busy port when it can, and still helps when it cannot", () => { - expect(hintFor("listen EADDRINUSE: address already in use :::3005").hint).toBe( + const busy = "listen EADDRINUSE: address already in use :::3005" + expect(onPlatform("darwin", () => hintFor(busy).hint)).toBe( "Something is already on port 3005. Free it with `lsof -ti :3005 | xargs kill`, or set NODE_SERVER_PORT in config/config.json." ) + expect(onPlatform("win32", () => hintFor(busy).hint)).toBe( + "Something is already on port 3005. Free it with `netstat -ano | findstr :3005, then taskkill /PID /T /F`, or set NODE_SERVER_PORT in config/config.json." + ) expect(hintFor("EADDRINUSE").hint).toBe( "Something is already on that port. Stop it, or set NODE_SERVER_PORT in config/config.json." ) @@ -183,3 +188,44 @@ describe("hintFor", () => { expect(hintFor(undefined)).toBeNull() }) }) + +describe("extractBuildErrors on Windows paths", () => { + it("reads a Kotlin error's file URL as a path, with its drive and its spaces", () => { + const [error] = extractBuildErrors( + "e: file:///C:/Users/First%20Last/app/Foo.kt:12:5 Unresolved reference: bar\n" + ) + expect(error).toEqual({ + file: "C:/Users/First Last/app/Foo.kt", + line: 12, + column: 5, + message: "Unresolved reference: bar", + }) + }) + + it("does not take a drive letter for the end of the file name", () => { + const [javac] = extractBuildErrors("C:\\app\\Foo.java:12: error: cannot find symbol\n") + expect(javac).toMatchObject({ file: "C:\\app\\Foo.java", line: 12, message: "cannot find symbol" }) + + const [clang] = extractBuildErrors("D:\\app\\Foo.c:3:9: fatal error: no such file\n") + expect(clang).toMatchObject({ file: "D:\\app\\Foo.c", line: 3, column: 9, message: "no such file" }) + }) + + it("keeps a whole Windows path in Vite's messages", () => { + const [esbuild] = extractBuildErrors("C:\\app\\src\\App.js:3:10: ERROR: Expected ';'\n", { + toolchain: "vite", + }) + expect(esbuild).toMatchObject({ file: "C:\\app\\src\\App.js", line: 3, column: 10 }) + + const [loadError] = extractBuildErrors( + "[vite:load-fallback] Could not load C:\\app\\x.js (imported by C:\\app\\y.js): ENOENT\n", + { toolchain: "vite" } + ) + expect(loadError.message).toBe("Could not load C:\\app\\x.js") + expect(loadError.file).toBe("C:\\app\\y.js") + }) + + it("still reads POSIX paths the same way", () => { + const [kotlin] = extractBuildErrors("e: file:///app/Foo.kt:1:2 Boom\n") + expect(kotlin.file).toBe("/app/Foo.kt") + }) +}) diff --git a/packages/catalyst-core/test/cli/devOutput.test.ts b/packages/catalyst-core/test/cli/devOutput.test.ts index 8e52313be..d29324acd 100644 --- a/packages/catalyst-core/test/cli/devOutput.test.ts +++ b/packages/catalyst-core/test/cli/devOutput.test.ts @@ -6,6 +6,7 @@ import { fileURLToPath } from "node:url" import { afterEach, beforeEach, describe, expect, it, vi } from "vitest" import type themeModule from "../../src/cli/theme.js" +import { stubPlatform } from "../onPlatform" // Loaded with require, the way serve.js and the native commands load them: // v8 coverage then sees one copy of each CommonJS file rather than an @@ -25,6 +26,8 @@ const { wireServerOutput, superviseServer, ensurePortFree, + listeningPidFromNetstat, + imageNameFromTasklist, createLineReader, BANNER_START, BANNER_END, @@ -40,6 +43,8 @@ const { options: { scope: string; label: string; passthrough?: boolean } ) => State ensurePortFree: (options: { port: unknown; host?: string; scope: string }) => Promise + listeningPidFromNetstat: (output: string, port: number) => string | null + imageNameFromTasklist: (output: string) => string | null createLineReader: (onLine: (line: string) => void) => { push: (chunk: string) => void; flush: () => void } BANNER_START: string BANNER_END: string @@ -469,11 +474,46 @@ describe("superviseServer (catalyst start)", () => { }) }) +describe("listeningPidFromNetstat", () => { + const netstat = [ + "", + "Active Connections", + "", + " Proto Local Address Foreign Address State PID", + " TCP 127.0.0.1:3005 127.0.0.1:51000 ESTABLISHED 111", + " TCP 0.0.0.0:4000 0.0.0.0:0 LISTENING 222", + " TCP [::1]:3005 [::]:0 ABHÖREN 333", + " UDP 0.0.0.0:3005 *:* 444", + "", + ].join("\r\n") + + it("finds the listener, in IPv6 and in any language, and not a client of it", () => { + expect(listeningPidFromNetstat(netstat, 3005)).toBe("333") + expect(listeningPidFromNetstat(netstat, 4000)).toBe("222") + }) + + it("does not match a port by its suffix, and reports nothing when nothing listens", () => { + expect(listeningPidFromNetstat(netstat, 305)).toBe(null) + expect(listeningPidFromNetstat(netstat, 80)).toBe(null) + expect(listeningPidFromNetstat("", 80)).toBe(null) + }) +}) + +describe("imageNameFromTasklist", () => { + it("reads the first CSV field, and nothing from a no-match message", () => { + expect(imageNameFromTasklist('"node.exe","4242","Console","1","80,000 K"\r\n')).toBe("node.exe") + expect(imageNameFromTasklist("INFO: No tasks are running which match the specified criteria.")).toBe( + null + ) + }) +}) + describe("ensurePortFree", () => { const net: typeof import("node:net") = load("node:net") const childProcess: typeof import("node:child_process") = load("node:child_process") let stderr: string let exit: ReturnType + let restorePlatform: () => void // A server whose listen() reports the given outcome, with no socket opened. const fakeServer = (outcome: { error?: { code: string } }) => { @@ -490,6 +530,7 @@ describe("ensurePortFree", () => { beforeEach(() => { stderr = "" + restorePlatform = stubPlatform("linux") exit = vi.spyOn(process, "exit").mockImplementation((() => undefined) as never) vi.spyOn(process.stderr, "write").mockImplementation(((chunk: string) => { stderr += plain(String(chunk)) @@ -497,9 +538,30 @@ describe("ensurePortFree", () => { }) as never) }) afterEach(() => { + restorePlatform() vi.restoreAllMocks() }) + it("names the owner of a port on Windows, from netstat and tasklist", () => { + const restore = stubPlatform("win32") + fakeServer({ error: { code: "EADDRINUSE" } }) + const run = vi + .spyOn(childProcess, "execFileSync") + .mockImplementation(((command: string) => + command === "netstat" + ? " TCP [::1]:3005 [::]:0 LISTENING 4242\r\n" + : '"node.exe","4242","Console","1","80,000 K"\r\n') as never) + void ensurePortFree({ port: 3005, scope: "dev server" }) + restore() + expect(run).toHaveBeenCalledWith( + "tasklist", + expect.arrayContaining(["PID eq 4242"]), + expect.anything() + ) + expect(stderr).toMatch(/Port 3005 is already in use by node\.exe \(pid 4242\)/) + expect(stderr).toMatch(/taskkill \/PID 4242 \/T \/F/) + }) + it("skips the probe for a missing or invalid port", async () => { const createServer = vi.spyOn(net, "createServer") await ensurePortFree({ port: undefined, scope: "server" }) diff --git a/packages/catalyst-core/test/cli/diagnostic.test.ts b/packages/catalyst-core/test/cli/diagnostic.test.ts index f6348b6b1..65875722e 100644 --- a/packages/catalyst-core/test/cli/diagnostic.test.ts +++ b/packages/catalyst-core/test/cli/diagnostic.test.ts @@ -4,6 +4,7 @@ import path from "path" import { afterAll, beforeAll, describe, expect, it } from "vitest" import { createRequire } from "module" +import { pathToFileURL } from "url" import type buildErrorsModule from "../../src/cli/buildErrors.js" import type themeModule from "../../src/cli/theme.js" @@ -298,6 +299,21 @@ describe("buildFailure", () => { }) describe("parseFrames", () => { + it("turns a file URL into a path this OS can open, drive and spaces included", () => { + const file = path.resolve("some dir", "App.js") + const url = pathToFileURL(file).href + expect(parseFrames(`Error: x\n at render (${url}:4:2)\n at ${url}:5:6`)).toEqual([ + { fn: "render", file, line: 4, column: 2 }, + { fn: null, file, line: 5, column: 6 }, + ]) + }) + + it("reads a Windows path with its drive colon", () => { + expect(parseFrames(" at render (C:\\app\\src\\App.js:4:2)")).toEqual([ + { fn: "render", file: "C:\\app\\src\\App.js", line: 4, column: 2 }, + ]) + }) + it("parses named and anonymous V8 frames and skips everything else", () => { const stack = [ "TypeError: x is not a function", diff --git a/packages/catalyst-core/test/cli/nativeFlags.test.ts b/packages/catalyst-core/test/cli/nativeFlags.test.ts index 665458447..62e8aceee 100644 --- a/packages/catalyst-core/test/cli/nativeFlags.test.ts +++ b/packages/catalyst-core/test/cli/nativeFlags.test.ts @@ -40,12 +40,18 @@ function run(args: string[]) { const out = execFileSync(process.execPath, [path.join(root, "bin", "catalyst.js"), ...args], { encoding: "utf8", }) + // Only the stub scripts' JSON: off macOS the bin also prints that it skips iOS. return out .trim() .split("\n") + .filter((line) => line.startsWith("{")) .map((line) => JSON.parse(line)) } +// Bare buildApp and setupEmulator run iOS only on a Mac (bin.test.ts covers the skip). +const onMac = process.platform === "darwin" +const bothPlatforms = (ios: object, android: object) => (onMac ? [ios, android] : [android]) + describe("native build flags", () => { it("forwards --release and --url to the platform script", () => { expect(run(["buildApp:android", "--release", "--url", "https://shop.acme.com"])).toEqual([ @@ -76,17 +82,21 @@ describe("native build flags", () => { expect(run(["--yes", "setupEmulator:android", "--accept-licenses"])).toEqual([ { script: "androidSetup", args: ["--yes", "--accept-licenses"] }, ]) - expect(run(["setupEmulator", "--yes"])).toEqual([ - { script: "setupEmulatorIos", args: ["--yes"] }, - { script: "androidSetup", args: ["--yes"] }, - ]) + expect(run(["setupEmulator", "--yes"])).toEqual( + bothPlatforms( + { script: "setupEmulatorIos", args: ["--yes"] }, + { script: "androidSetup", args: ["--yes"] } + ) + ) }) it("passes the flags to both platforms for buildApp", () => { - expect(run(["buildApp", "--release", "--url=https://shop.acme.com"])).toEqual([ - { script: "buildAppIos", args: ["--release", "--url=https://shop.acme.com"] }, - { script: "buildAppAndroid", args: ["--release", "--url=https://shop.acme.com"] }, - ]) + expect(run(["buildApp", "--release", "--url=https://shop.acme.com"])).toEqual( + bothPlatforms( + { script: "buildAppIos", args: ["--release", "--url=https://shop.acme.com"] }, + { script: "buildAppAndroid", args: ["--release", "--url=https://shop.acme.com"] } + ) + ) }) it("dispatches credentials:export with its platform", () => { diff --git a/packages/catalyst-core/test/cli/platform.test.ts b/packages/catalyst-core/test/cli/platform.test.ts new file mode 100644 index 000000000..3aab7659c --- /dev/null +++ b/packages/catalyst-core/test/cli/platform.test.ts @@ -0,0 +1,98 @@ +import { createRequire } from "node:module" +import { afterEach, describe, expect, it, vi } from "vitest" + +import type platformModule from "../../src/cli/platform.js" +import { onPlatform } from "../onPlatform" + +const platform: typeof platformModule = createRequire(import.meta.url)("../../src/cli/platform.js") +const { appRoot, batchInvocation, freePortCommand, isWindows, quoteWindowsArg, stopProcessCommand } = platform + +afterEach(() => { + vi.restoreAllMocks() + vi.unstubAllEnvs() +}) + +describe("isWindows", () => { + it("reads the platform when asked, not when loaded", () => { + expect(onPlatform("win32", isWindows)).toBe(true) + expect(onPlatform("darwin", isWindows)).toBe(false) + }) +}) + +describe("appRoot", () => { + it("ignores PWD on Windows, where it is missing or left over from another shell", () => { + vi.stubEnv("PWD", "/c/some/other/project") + vi.spyOn(process, "cwd").mockReturnValue("C:\\the\\app") + expect(onPlatform("win32", appRoot)).toBe("C:\\the\\app") + }) + + it("prefers PWD elsewhere, and falls back to the working directory", () => { + vi.spyOn(process, "cwd").mockReturnValue("/real/app") + vi.stubEnv("PWD", "/linked/app") + expect(onPlatform("linux", appRoot)).toBe("/linked/app") + vi.stubEnv("PWD", "") + expect(onPlatform("linux", appRoot)).toBe("/real/app") + }) +}) + +describe("quoteWindowsArg", () => { + it("leaves a plain argument alone", () => { + expect(quoteWindowsArg("installDebug")).toBe("installDebug") + expect(quoteWindowsArg("C:\\app\\config.json")).toBe("C:\\app\\config.json") + }) + + it("quotes ; , and =, where a batch file splits its arguments", () => { + // sdkmanager.bat would otherwise read platforms;android-36 as two arguments. + expect(quoteWindowsArg("platforms;android-36")).toBe('"platforms;android-36"') + expect(quoteWindowsArg("--sdk_root=C:\\sdk")).toBe('"--sdk_root=C:\\sdk"') + expect(quoteWindowsArg("a,b")).toBe('"a,b"') + }) + + it("quotes spaces and whatever cmd.exe would act on", () => { + expect(quoteWindowsArg("C:\\Program Files\\x.bat")).toBe('"C:\\Program Files\\x.bat"') + for (const special of ["a&b", "a|b", "ab", "a^b", "a(b", "a%b", "a!b"]) { + expect(quoteWindowsArg(special)).toBe(`"${special}"`) + } + expect(quoteWindowsArg("")).toBe('""') + }) + + it("escapes quotes, doubling only the backslashes in front of one", () => { + expect(quoteWindowsArg('say "hi"')).toBe('"say \\"hi\\""') + expect(quoteWindowsArg('a\\"b')).toBe('"a\\\\\\"b"') + expect(quoteWindowsArg("C:\\a b\\")).toBe('"C:\\a b\\\\"') + expect(quoteWindowsArg("C:\\a\\b c")).toBe('"C:\\a\\b c"') + }) +}) + +describe("batchInvocation", () => { + it("goes through cmd.exe, quoted once more for its /s switch", () => { + // Named, not read from ComSpec: the environment does not pick the shell. + vi.stubEnv("ComSpec", "C:\\elsewhere\\shell.exe") + expect( + batchInvocation("C:\\my app\\gradlew.bat", ["clean", "-PconfigPath=C:\\my app\\c.json"]) + ).toEqual({ + command: "cmd.exe", + args: ["/d", "/s", "/c", '""C:\\my app\\gradlew.bat" clean "-PconfigPath=C:\\my app\\c.json""'], + options: { windowsVerbatimArguments: true }, + }) + vi.unstubAllEnvs() + }) + + it("refuses what cmd.exe would still read as syntax inside quotes", () => { + for (const unsafe of ["C:\\%PATH%\\sdk", 'a"b', "a\nb", "a\rb"]) { + expect(() => batchInvocation("C:\\sdk\\sdkmanager.bat", [unsafe])).toThrow(/cmd\.exe would read/) + } + expect(() => batchInvocation("C:\\100%\\gradlew.bat")).toThrow(/cmd\.exe would read/) + }) +}) + +describe("advice that names a command", () => { + it("names one that exists on this system", () => { + expect(onPlatform("linux", () => freePortCommand(3005))).toBe("lsof -ti :3005 | xargs kill") + expect(onPlatform("win32", () => freePortCommand(3005))).toBe( + "netstat -ano | findstr :3005, then taskkill /PID /T /F" + ) + expect(onPlatform("linux", () => stopProcessCommand(42))).toBe("kill 42") + expect(onPlatform("win32", () => stopProcessCommand(42))).toBe("taskkill /PID 42 /T /F") + }) +}) diff --git a/packages/catalyst-core/test/cli/theme.test.ts b/packages/catalyst-core/test/cli/theme.test.ts index adaba53a5..b1992b62e 100644 --- a/packages/catalyst-core/test/cli/theme.test.ts +++ b/packages/catalyst-core/test/cli/theme.test.ts @@ -139,7 +139,9 @@ describe("displayPath", () => { it("keeps absolute paths elsewhere, and the root itself", () => { const outside = path.join(path.parse(root).root, "opt-catalyst-elsewhere", "file.js") expect(theme.displayPath(outside, root)).toBe(outside) - expect(theme.displayPath(root, root)).toBe(root) + // Not os.tmpdir(): on Windows that lives under home, and reads as ~. + const elsewhere = path.dirname(outside) + expect(theme.displayPath(elsewhere, elsewhere)).toBe(elsewhere) }) it("passes empty values through", () => { diff --git a/packages/catalyst-core/test/native/androidOutput.test.ts b/packages/catalyst-core/test/native/androidOutput.test.ts index 90c54bcf4..77a5c7a0a 100644 --- a/packages/catalyst-core/test/native/androidOutput.test.ts +++ b/packages/catalyst-core/test/native/androidOutput.test.ts @@ -212,7 +212,8 @@ describe("ensureBuildOutputIgnore", () => { expect(fs.existsSync(path.join(appRoot, "build-output"))).toBe(false) }) - it("rethrows a write failure other than an existing file", () => { + // chmod cannot make a folder read-only on Windows, so there is nothing to fail there. + it.skipIf(process.platform === "win32")("rethrows a write failure other than an existing file", () => { const appRoot = tempDir() const root = path.join(appRoot, "build-output") fs.mkdirSync(root) diff --git a/packages/catalyst-core/test/native/androidSigning.test.ts b/packages/catalyst-core/test/native/androidSigning.test.ts index d14c8a3b2..f817c361c 100644 --- a/packages/catalyst-core/test/native/androidSigning.test.ts +++ b/packages/catalyst-core/test/native/androidSigning.test.ts @@ -593,7 +593,7 @@ describe("release output", () => { androidConfig: { outputPath: "dist/store" }, version: { buildNumber: 7 }, }) - ).toBe(path.join("/app", "dist", "store", "1.0.0-7")) + ).toBe(path.resolve("/app", "dist", "store", "1.0.0-7")) }) it("makes the app name and version safe for file names", () => { @@ -632,19 +632,19 @@ describe("legacyKeystorePath", () => { // names the old release used. const raw = { appName: "shop", packageName: "com.acme.shop" } expect(legacyKeystorePath(raw, { cwd: "/app" })).toBe( - path.join("/app", "build-output", "shop-keystore.jks") + path.resolve("/app", "build-output", "shop-keystore.jks") ) expect(legacyKeystorePath({ newProjectName: "store", appName: "shop" }, { cwd: "/app" })).toBe( - path.join("/app", "build-output", "store-keystore.jks") + path.resolve("/app", "build-output", "store-keystore.jks") ) expect(legacyKeystorePath({ packageName: "com.acme.market" }, { cwd: "/app" })).toBe( - path.join("/app", "build-output", "market-keystore.jks") + path.resolve("/app", "build-output", "market-keystore.jks") ) expect(legacyKeystorePath({ outputPath: "dist" }, { cwd: "/app" })).toBe( - path.join("/app", "dist", "catalystapp-keystore.jks") + path.resolve("/app", "dist", "catalystapp-keystore.jks") ) expect(legacyKeystorePath(undefined, { cwd: "/app" })).toBe( - path.join("/app", "build-output", "catalystapp-keystore.jks") + path.resolve("/app", "build-output", "catalystapp-keystore.jks") ) }) }) diff --git a/packages/catalyst-core/test/native/androidToolchain.test.ts b/packages/catalyst-core/test/native/androidToolchain.test.ts index 4fae737ce..91fee5dc5 100644 --- a/packages/catalyst-core/test/native/androidToolchain.test.ts +++ b/packages/catalyst-core/test/native/androidToolchain.test.ts @@ -2,7 +2,7 @@ import crypto from "crypto" import fs from "fs" import os from "os" import path from "path" -import { afterEach, describe, expect, it } from "vitest" +import { afterEach, beforeEach, describe, expect, it } from "vitest" import { AVD_NAME, @@ -12,6 +12,7 @@ import { cmdlineTool, cmdlineToolsArchive, defaultSdkPath, + unzipArchive, ensureAndroidSdk, ensureJava, halfInstalledPaths, @@ -67,6 +68,9 @@ function acceptLicences(sdk: string) { } describe("Java resolution", () => { + // As resolveJavaHome builds it: path.join, so backslashes on Windows. + const bin = (home: string) => path.join(home, "bin", "java") + it("parses modern and 1.x version strings", () => { expect(parseJavaMajor('openjdk version "17.0.9" 2023-10-17')).toBe(17) expect(parseJavaMajor('java version "1.8.0_392"')).toBe(8) @@ -78,8 +82,8 @@ describe("Java resolution", () => { const skipped: string[] = [] const run = (command: string) => { if (command === "/usr/libexec/java_home") return "/jdks/zulu-17/Contents/Home\n" - if (command === "/old/jdk/bin/java") return 'openjdk version "11.0.2"' - if (command === "/jdks/zulu-17/Contents/Home/bin/java") return 'openjdk version "17.0.12"' + if (command === bin("/old/jdk")) return 'openjdk version "11.0.2"' + if (command === bin("/jdks/zulu-17/Contents/Home")) return 'openjdk version "17.0.12"' return null } const java = resolveJavaHome({ @@ -96,9 +100,9 @@ describe("Java resolution", () => { it("skips a JDK newer than 23 with a reason, and prefers 21 over 17", () => { const skipped: Array<[string, string]> = [] const versions: Record = { - "/jdk25/bin/java": 'openjdk version "25" 2025-09-16', - "/jdk17/bin/java": 'openjdk version "17.0.12"', - "/jdk21/bin/java": 'openjdk version "21.0.4"', + [bin("/jdk25")]: 'openjdk version "25" 2025-09-16', + [bin("/jdk17")]: 'openjdk version "17.0.12"', + [bin("/jdk21")]: 'openjdk version "21.0.4"', } const run = (command: string, args: string[]) => { if (command === "/usr/libexec/java_home") { @@ -119,8 +123,8 @@ describe("Java resolution", () => { it("takes 17 over another in-range JDK, and nothing when only 24+ is installed", () => { const versions: Record = { - "/jdk22/bin/java": 'openjdk version "22.0.1"', - "/jdk17/bin/java": 'openjdk version "17.0.12"', + [bin("/jdk22")]: 'openjdk version "22.0.1"', + [bin("/jdk17")]: 'openjdk version "17.0.12"', } const pick = (javaHome: string, others: string[]) => resolveJavaHome({ @@ -136,7 +140,7 @@ describe("Java resolution", () => { env: { JAVA_HOME: "/jdk24" }, platform: "linux", run: () => 'openjdk version "24"', - exists: (file) => file === "/jdk24/bin/java", + exists: (file) => file === bin("/jdk24"), }) ).toBeNull() }) @@ -146,12 +150,63 @@ describe("Java resolution", () => { const java = resolveJavaHome({ env: {}, platform: "darwin", - run: (command) => (command === `${jbr}/bin/java` ? 'openjdk version "21.0.6"' : null), - exists: (file) => file === `${jbr}/bin/java`, + run: (command) => (command === bin(jbr) ? 'openjdk version "21.0.6"' : null), + exists: (file) => file === bin(jbr), }) expect(java).toMatchObject({ home: jbr, version: 21, source: "Android Studio" }) }) + it("finds Android Studio's JBR on Windows, then a java on PATH", () => { + const jbr = path.join("C:/Program Files", "Android", "Android Studio", "jbr") + const javaOf = (home: string) => path.join(home, "bin", "java.exe") + // Normalised, as dirname() of the where output gives it back with this OS separator. + const onPath = path.normalize("C:/jdk17") + const pick = (installed: string[]) => + resolveJavaHome({ + env: { ProgramFiles: "C:/Program Files", LOCALAPPDATA: "C:/Users/me/AppData/Local" }, + platform: "win32", + run: (command, args) => { + if (command === "where") return `${javaOf(onPath)}\r\nC:/other/bin/java.exe\r\n` + if (args[0] === "-version" && installed.map(javaOf).includes(command)) + return 'openjdk version "17.0.12"' + return null + }, + exists: (file) => installed.map(javaOf).includes(file), + }) + expect(pick([jbr, onPath])).toMatchObject({ home: jbr, source: "Android Studio" }) + expect(pick([onPath])).toMatchObject({ home: onPath, source: "PATH" }) + }) + + // A winget or MSI install is on PATH only in a new terminal; its folder is there at once. + it("finds a JDK in the usual Windows install folders, newest first", () => { + const local = "C:/Users/me/AppData/Local" + const microsoft = path.join(local, "Programs", "Microsoft") + const jdk17 = path.join(microsoft, "jdk-17.0.21.0.2+1") + const jdk11 = path.join(microsoft, "jdk-11.0.25.9") + const javaOf = (home: string) => path.join(home, "bin", "java.exe") + const versions: Record = { + [javaOf(jdk17)]: 'openjdk version "17.0.21"', + [javaOf(jdk11)]: 'openjdk version "11.0.25"', + } + const skipped: string[] = [] + const java = resolveJavaHome({ + env: { LOCALAPPDATA: local }, + platform: "win32", + run: (command) => versions[command] ?? null, + exists: (file) => file in versions, + list: (dir) => (dir === microsoft ? ["jdk-11.0.25.9", "notes.txt", "jdk-17.0.21.0.2+1"] : []), + onSkip: (candidate) => skipped.push(candidate), + }) + expect(java).toMatchObject({ home: jdk17, version: 17, source: "Microsoft" }) + }) + + it("names a Windows install for a missing JDK there", async () => { + const error = await rejection(ensureJava({ platform: "win32", isTTY: true, resolve: () => null })) + expect(error.code).toBe("ANDROID-007") + expect(error.message).toMatch(/winget install Microsoft\.OpenJDK\.17/) + expect(error.hint).toMatch(/Windows: Android Studio, or winget install/) + }) + it("returns null with no JDK 17+", () => { expect( resolveJavaHome({ env: {}, platform: "darwin", run: () => null, exists: () => false }) @@ -373,6 +428,10 @@ describe("SDK locations", () => { expect(defaultSdkPath({ ANDROID_SDK_ROOT: "/b" }, "linux")).toBe("/b") expect(defaultSdkPath({}, "darwin")).toBe(path.join(os.homedir(), "Library", "Android", "sdk")) expect(defaultSdkPath({}, "linux")).toBe(path.join(os.homedir(), "Android", "Sdk")) + // Where Android Studio puts it on Windows, so both use one SDK. + expect(defaultSdkPath({ LOCALAPPDATA: "C:/Users/me/AppData/Local" }, "win32")).toBe( + path.join("C:/Users/me/AppData/Local", "Android", "Sdk") + ) }) it("finds sdkmanager in cmdline-tools/latest, else the newest versioned folder, else nothing", () => { @@ -434,6 +493,8 @@ describe("ensureAndroidSdk", () => { ) }, installTools: async (dir: string) => installTools(dir), + // The fakes write POSIX tool names (no .bat), so look them up as Linux would. + platform: "linux", } return { calls, deps } } @@ -625,7 +686,17 @@ describe("ensureAndroidSdk", () => { }) describe("ensureAndroidSdk failures after consent", () => { - const ci = { flags: { yes: true, acceptLicenses: true }, isTTY: false, arch: "arm64" } + // platform: the fakes write POSIX tool names. installTools: a lookup that misses + // must never fall through to the real cmdline-tools download. + const ci = { + flags: { yes: true, acceptLicenses: true }, + isTTY: false, + arch: "arm64", + platform: "linux", + installTools: async () => { + throw new Error("a test reached the real cmdline-tools download") + }, + } it("fails with ANDROID-009 when the tools install leaves no sdkmanager", async () => { const sdk = tempDir() @@ -764,3 +835,31 @@ describe("sdkmanager recovery (#301)", () => { expect(network.message).toBe("exit 1") }) }) + +describe("unzipArchive", () => { + const calls: unknown[][] = [] + const exec = ((...args: unknown[]) => { + calls.push(args) + return "" + }) as any + beforeEach(() => { + calls.length = 0 + }) + + it("uses unzip off Windows", () => { + unzipArchive("/t/tools.zip", "/t/out", { platform: "darwin", exec }) + expect(calls[0].slice(0, 2)).toEqual(["unzip", ["-q", "-o", "/t/tools.zip", "-d", "/t/out"]]) + }) + + // No unzip there. Windows' own tar reads zip; Git's GNU tar, often first on PATH, does not. + it("uses System32's tar on Windows, and tar from PATH without it", () => { + const env = { SystemRoot: "C:/Windows" } + const systemTar = path.join("C:/Windows", "System32", "tar.exe") + unzipArchive("C:/t/tools.zip", "C:/t/out", { platform: "win32", env, exec, exists: () => true }) + unzipArchive("C:/t/tools.zip", "C:/t/out", { platform: "win32", env, exec, exists: () => false }) + expect(calls.map((call) => call.slice(0, 2))).toEqual([ + [systemTar, ["-xf", "C:/t/tools.zip", "-C", "C:/t/out"]], + ["tar", ["-xf", "C:/t/tools.zip", "-C", "C:/t/out"]], + ]) + }) +}) diff --git a/packages/catalyst-core/test/native/credentials.test.ts b/packages/catalyst-core/test/native/credentials.test.ts index e2d959352..900dbde4c 100644 --- a/packages/catalyst-core/test/native/credentials.test.ts +++ b/packages/catalyst-core/test/native/credentials.test.ts @@ -15,6 +15,7 @@ import { packCredentials, resolveCredentials, unpackCredentials, + tarCommand, } from "../../src/native/credentials.js" import { runExportCredentials } from "../../src/native/exportCredentials.js" @@ -239,3 +240,15 @@ describe("catalyst credentials:export", () => { expect(err.join("")).toContain("") }) }) + +// Git's GNU tar, often first on PATH on Windows, reads the C: of an absolute path as a host. +describe("tarCommand", () => { + it("uses Windows' own tar there, and tar from PATH everywhere else", () => { + const env = { SystemRoot: "C:/Windows" } + expect(tarCommand({ platform: "darwin" })).toBe("tar") + expect(tarCommand({ platform: "win32", env, exists: () => true })).toBe( + path.join("C:/Windows", "System32", "tar.exe") + ) + expect(tarCommand({ platform: "win32", env, exists: () => false })).toBe("tar") + }) +}) diff --git a/packages/catalyst-core/test/native/iosConfigPhase.test.ts b/packages/catalyst-core/test/native/iosConfigPhase.test.ts index 98bda97cf..c601e66de 100644 --- a/packages/catalyst-core/test/native/iosConfigPhase.test.ts +++ b/packages/catalyst-core/test/native/iosConfigPhase.test.ts @@ -314,7 +314,8 @@ describe("generateConfigConstants: defaults and failures", () => { progress: recorder.progress, }) const error = await rejection(generateConfigConstants()) - expect(error.code).toBe("ENOTDIR") + // A file in the way of a folder: ENOTDIR on macOS and Linux, ENOENT on Windows. + expect(["ENOTDIR", "ENOENT"]).toContain(error.code) expect(recorder.events[0]).toBe("start:config") expect(recorder.events).toContain(`fail:config:${error.message}`) expect(recorder.events).not.toContain("complete:config") @@ -354,7 +355,8 @@ describe("generateXCConfig", () => { }) const error = await rejection(generateXCConfig()) expect(error.message).toMatch(/^Failed to generate Shared\.xcconfig: /) - expect(error.code).toBe("ENOTDIR") + // A file in the way of a folder: ENOTDIR on macOS and Linux, ENOENT on Windows. + expect(["ENOTDIR", "ENOENT"]).toContain(error.code) }) }) diff --git a/packages/catalyst-core/test/native/iosSigning.test.ts b/packages/catalyst-core/test/native/iosSigning.test.ts index 85bc2fb89..70fd1088d 100644 --- a/packages/catalyst-core/test/native/iosSigning.test.ts +++ b/packages/catalyst-core/test/native/iosSigning.test.ts @@ -580,7 +580,8 @@ describe("setupP12Signing", () => { expect(result.profile).toMatchObject({ name: "Acme App Store", teamId: "TEAM123456" }) for (const file of profilePaths(fake.homeDir)) { expect(fs.existsSync(file)).toBe(true) - expect(fs.statSync(file).mode & 0o777).toBe(0o600) + // Windows has no POSIX modes to set or read. + if (process.platform !== "win32") expect(fs.statSync(file).mode & 0o777).toBe(0o600) } expect(Object.keys(fake.handlers).sort()).toEqual(["SIGINT", "SIGTERM"]) @@ -918,7 +919,7 @@ describe("updateInfoPlist", () => { const strict = infoPlistPhase({ localNetworking: true, restoreManagedFileFromBaseline: (file: string) => { - if (file.endsWith("/Info.plist")) { + if (path.basename(file) === "Info.plist") { fs.writeFileSync( file, JSON.stringify({ NSAppTransportSecurity: { NSAllowsArbitraryLoads: false } }) diff --git a/packages/catalyst-core/test/native/iosToolchain.test.ts b/packages/catalyst-core/test/native/iosToolchain.test.ts index bcc82563a..7c1b41e35 100644 --- a/packages/catalyst-core/test/native/iosToolchain.test.ts +++ b/packages/catalyst-core/test/native/iosToolchain.test.ts @@ -571,7 +571,9 @@ describe("connected iPhones", () => { expect(options.timeout).toBe(30000) written = args[4] // A private folder from mkdtemp, not a guessable name in tmp. - expect(fs.statSync(path.dirname(written)).mode & 0o077).toBe(0) + if (process.platform !== "win32") { + expect(fs.statSync(path.dirname(written)).mode & 0o077).toBe(0) + } fs.writeFileSync(written, JSON.stringify(json)) return "" }) as any, diff --git a/packages/catalyst-core/test/native/nativeConfig.test.ts b/packages/catalyst-core/test/native/nativeConfig.test.ts index f4ac2e0eb..542824cc7 100644 --- a/packages/catalyst-core/test/native/nativeConfig.test.ts +++ b/packages/catalyst-core/test/native/nativeConfig.test.ts @@ -471,7 +471,8 @@ describe("resolveNativeConfig: release", () => { // One descriptor for the mode and the content. const fd = fs.openSync(resolved.configPath, "r") try { - expect(fs.fstatSync(fd).mode & 0o777).toBe(0o600) + // Windows has no POSIX modes to set or read. + if (process.platform !== "win32") expect(fs.fstatSync(fd).mode & 0o777).toBe(0o600) expect(JSON.parse(fs.readFileSync(fd, "utf8")).WEBVIEW_CONFIG.LOCAL_IP).toBe("shop.acme.com") } finally { fs.closeSync(fd) diff --git a/packages/catalyst-core/test/native/projectFiles.test.ts b/packages/catalyst-core/test/native/projectFiles.test.ts new file mode 100644 index 000000000..b5dfc51d2 --- /dev/null +++ b/packages/catalyst-core/test/native/projectFiles.test.ts @@ -0,0 +1,207 @@ +import fs from "node:fs" +import { createRequire } from "node:module" +import os from "node:os" +import path from "node:path" +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest" + +const { + copyProjectWithoutOutputs, + copyWebBuild, + findFiles, + removeEmptyDirectories, + removeTree, + renameWithRetry, + walkTree, +} = createRequire(import.meta.url)("../../src/native/projectFiles.js") + +let root: string +const write = (relative: string, content = "x") => { + const file = path.join(root, relative) + fs.mkdirSync(path.dirname(file), { recursive: true }) + fs.writeFileSync(file, content) + return file +} + +beforeEach(() => { + root = fs.mkdtempSync(path.join(os.tmpdir(), "catalyst project files ")) +}) +afterEach(() => { + vi.restoreAllMocks() + fs.rmSync(root, { recursive: true, force: true }) +}) + +describe("walkTree", () => { + it("lists children before their parent, so a rename cannot invalidate what follows", () => { + write("a/b/c.txt") + const paths = walkTree(root).map((entry: { path: string }) => path.relative(root, entry.path)) + expect(paths).toEqual([path.join("a", "b", "c.txt"), path.join("a", "b"), "a"]) + }) + + it("does not follow a symlink out of the tree", () => { + write("outside/secret.txt") + fs.mkdirSync(path.join(root, "inside")) + try { + fs.symlinkSync(path.join(root, "outside"), path.join(root, "inside", "link"), "junction") + } catch { + return // Creating links can need privileges; nothing to check without one. + } + const entries = walkTree(path.join(root, "inside")) + expect(entries.map((entry: { name: string }) => entry.name)).toEqual(["link"]) + expect(entries[0].isDirectory).toBe(false) + }) +}) + +describe("findFiles", () => { + it("finds files by name and never returns a directory", () => { + const kept = write("app/src/Main.kt") + write("app/src/Main.xml") + fs.mkdirSync(path.join(root, "app", "folder.kt")) + expect(findFiles(root, (name: string) => name.endsWith(".kt"))).toEqual([kept]) + }) + + it("skips a symlinked file, so nothing written to a result leaves the tree", () => { + const outside = write("outside/Main.kt") + const kept = write("app/Real.kt") + try { + fs.symlinkSync(outside, path.join(root, "app", "Linked.kt")) + } catch { + return // Creating links can need privileges; nothing to check without one. + } + expect(findFiles(path.join(root, "app"), (name: string) => name.endsWith(".kt"))).toEqual([kept]) + }) +}) + +describe("removeEmptyDirectories", () => { + it("removes chains left empty, and keeps anything with a file in it", () => { + write("java/io/yourname/.keep") + fs.rmSync(path.join(root, "java", "io", "yourname", ".keep")) + write("java/com/example/Main.kt") + removeEmptyDirectories(path.join(root, "java")) + expect(fs.existsSync(path.join(root, "java", "io"))).toBe(false) + expect(fs.existsSync(path.join(root, "java", "com", "example", "Main.kt"))).toBe(true) + }) +}) + +describe("removeTree", () => { + it("removes a tree, and does not mind one that is already gone", () => { + write("gone/deep/file.txt") + removeTree(path.join(root, "gone")) + expect(fs.existsSync(path.join(root, "gone"))).toBe(false) + expect(() => removeTree(path.join(root, "gone"))).not.toThrow() + }) +}) + +describe("renameWithRetry", () => { + it("rides out a file a scanner has open for a moment", () => { + const from = write("from.txt") + const to = path.join(root, "to.txt") + const rename = fs.renameSync + let failures = 2 + vi.spyOn(fs, "renameSync").mockImplementation((...args: Parameters) => { + if (failures-- > 0) throw Object.assign(new Error("busy"), { code: "EBUSY" }) + return rename(...args) + }) + renameWithRetry(from, to) + expect(fs.existsSync(to)).toBe(true) + }) + + it("does not retry what waiting cannot fix", () => { + const spy = vi.spyOn(fs, "renameSync").mockImplementation(() => { + throw Object.assign(new Error("missing"), { code: "ENOENT" }) + }) + expect(() => renameWithRetry("a", "b")).toThrow("missing") + expect(spy).toHaveBeenCalledTimes(1) + }) +}) + +describe("copyProjectWithoutOutputs", () => { + it("copies the project but none of its build outputs", () => { + write("project/gradlew") + write("project/local.properties") + write("project/app/src/main/AndroidManifest.xml") + write("project/app/src/main/build/kept-because-it-is-source.txt") + write("project/app/build/outputs/huge.apk") + write("project/build/reports/report.html") + write("project/.gradle/8.13/lock") + + const destination = path.join(root, "temp build") + copyProjectWithoutOutputs(path.join(root, "project"), destination) + + const copied = (relative: string) => fs.existsSync(path.join(destination, relative)) + expect(copied("gradlew")).toBe(true) + expect(copied("local.properties")).toBe(true) + expect(copied("app/src/main/AndroidManifest.xml")).toBe(true) + expect(copied("app/src/main/build/kept-because-it-is-source.txt")).toBe(true) + expect(copied("app/build")).toBe(false) + expect(copied("build")).toBe(false) + expect(copied(".gradle")).toBe(false) + }) + + it("copies through a linked project rather than recreating the link", () => { + write("real/gradlew") + write("real/app/build/huge.apk") + try { + fs.symlinkSync(path.join(root, "real"), path.join(root, "linked"), "junction") + } catch { + return // Creating links can need privileges; nothing to check without one. + } + const destination = path.join(root, "copy") + copyProjectWithoutOutputs(path.join(root, "linked"), destination) + expect(fs.lstatSync(destination).isSymbolicLink()).toBe(false) + expect(fs.existsSync(path.join(destination, "gradlew"))).toBe(true) + expect(fs.existsSync(path.join(destination, "app", "build"))).toBe(false) + }) + + it("handles a source path written with forward slashes, as the build passes it", () => { + write("project/app/build/huge.apk") + write("project/gradlew") + const destination = path.join(root, "copy") + copyProjectWithoutOutputs(`${root}/project`.replace(/\\/g, "/"), destination) + expect(fs.existsSync(path.join(destination, "gradlew"))).toBe(true) + expect(fs.existsSync(path.join(destination, "app", "build"))).toBe(false) + }) +}) + +// With buildOptimisation the web build ships inside the app, minus the route +// manifests. This was rm -rf and rsync, neither of which exist on Windows. +describe("copyWebBuild", () => { + const excluded = new Set(["route-manifest.json.gz", "route-manifest.json.br"]) + const dest = () => path.join(root, "assets", "build") + const copied = (relative: string) => fs.existsSync(path.join(dest(), relative)) + + it("copies the build, leaves out the manifests at any depth, and drops stale files", () => { + write("build/client/main.js") + write("build/route-manifest.json.gz") + write("build/client/route-manifest.json.br") + write("build/client/route-manifest.json") + write("assets/build/stale.js") + + copyWebBuild(path.join(root, "build"), dest(), excluded) + + expect(copied("client/main.js")).toBe(true) + expect(copied("client/route-manifest.json")).toBe(true) + expect(copied("route-manifest.json.gz")).toBe(false) + expect(copied("client/route-manifest.json.br")).toBe(false) + expect(copied("stale.js")).toBe(false) + }) + + it("copies through a linked build folder, still leaving out the manifests", () => { + write("elsewhere/client/main.js") + write("elsewhere/route-manifest.json.gz") + try { + fs.symlinkSync(path.join(root, "elsewhere"), path.join(root, "build"), "junction") + } catch { + return // Creating links can need privileges; nothing to check without one. + } + + copyWebBuild(path.join(root, "build"), dest(), excluded) + + expect(fs.lstatSync(dest()).isSymbolicLink()).toBe(false) + expect(copied("client/main.js")).toBe(true) + expect(copied("route-manifest.json.gz")).toBe(false) + }) + + it("throws for a build that does not exist", () => { + expect(() => copyWebBuild(path.join(root, "missing"), dest(), excluded)).toThrow(/ENOENT/) + }) +}) diff --git a/packages/catalyst-core/test/native/redactSecrets.test.ts b/packages/catalyst-core/test/native/redactSecrets.test.ts index ee45e1db6..9d38bb56f 100644 --- a/packages/catalyst-core/test/native/redactSecrets.test.ts +++ b/packages/catalyst-core/test/native/redactSecrets.test.ts @@ -14,9 +14,10 @@ const KEY = "K3y-Secret-27" function failSigningCommand() { // Fails like a wrong keystore password would, echoing a password back // without its flag on both streams. + const script = `console.log('using ${STORE}');console.error('bad key ${KEY}');process.exit(1)` const command = [ - `echo "using ${STORE}"; echo "bad key ${KEY}" >&2; exit 1;`, - `: ./gradlew bundleRelease`, + // Node rather than echo and exit, which no two shells spell the same way. + `"${process.execPath}" -e "${script}" -- ./gradlew bundleRelease`, `-Pandroid.injected.signing.store.password="${STORE}"`, `-Pandroid.injected.signing.key.password="${KEY}"`, `-storepass "${STORE}" -keypass ${KEY}`, diff --git a/packages/catalyst-core/test/native/setupServer.test.ts b/packages/catalyst-core/test/native/setupServer.test.ts index 93f663a42..63cec11c9 100644 --- a/packages/catalyst-core/test/native/setupServer.test.ts +++ b/packages/catalyst-core/test/native/setupServer.test.ts @@ -154,7 +154,8 @@ describe("startDevServerProcess", () => { expect(returned).toBe(child) expect(logFile).toBe(path.join(cwd, ".catalyst", "dev-server-3005.log")) expect(logFile.startsWith(os.tmpdir() + path.sep + "catalyst-dev-server")).toBe(false) - expect(fs.statSync(logFile).mode & 0o777).toBe(0o600) + // Windows has no POSIX modes to set or read. + if (process.platform !== "win32") expect(fs.statSync(logFile).mode & 0o777).toBe(0o600) expect(fs.readFileSync(path.join(cwd, ".catalyst", ".gitignore"), "utf8")).toBe("*\n") expect(spawned.command).toBe(process.execPath) expect(path.basename(spawned.args[0])).toBe("catalyst.js") @@ -217,6 +218,42 @@ describe("ensureDevServer", () => { expect(startedWith.overrides).toEqual({}) }) + // adb reverse dials 127.0.0.1, and on Windows "localhost" can bind ::1 alone. + it("starts on and waits for 127.0.0.1 when the target needs IPv4 (Android)", async () => { + const probed: string[] = [] + let startedWith: any + let calls = 0 + await ensureDevServer({ + config, + ipv4: true, + intervalMs: 1, + probe: async ({ host }: any) => { + probed.push(host) + return host === "127.0.0.1" && ++calls > 2 + }, + start: ((options: any) => { + startedWith = options + return { child: null, logFile: "/tmp/x.log" } + }) as any, + }) + expect(startedWith.overrides).toEqual({ NODE_SERVER_HOSTNAME: "127.0.0.1" }) + expect(probed[0]).toBe("127.0.0.1") + }) + + it("refuses a running dev server that answers on localhost but not 127.0.0.1", async () => { + const error = await ensureDevServer({ + config, + ipv4: true, + probe: async ({ host }: any) => host === "localhost", + start: (() => { + throw new Error("must not start over a running server") + }) as any, + }).catch((caught) => caught) + expect(error.code).toBe("NATIVE-006") + expect(error.message).toContain("not on 127.0.0.1") + expect(error.hint).toContain('NODE_SERVER_HOSTNAME to "127.0.0.1"') + }) + it("binds all interfaces and serves assets on a device host", async () => { let startedWith: any let probes = 0 @@ -303,7 +340,7 @@ describe("ensureDevServer", () => { const error = await run("localhost", true).catch((e) => e) expect(error.code).toBe("NATIVE-006") expect(error.message).toContain("started for jane-mac.local") - expect(error.hint).toContain("kill 4242") + expect(error.hint).toContain(process.platform === "win32" ? "taskkill /PID 4242 /T /F" : "kill 4242") // The same target reuses it, and a recorded process that is gone is ignored. expect(await run("jane-mac.local", true)).toMatchObject({ started: false }) diff --git a/packages/catalyst-core/test/native/utils.test.ts b/packages/catalyst-core/test/native/utils.test.ts index 9f60680f2..a8c612ae0 100644 --- a/packages/catalyst-core/test/native/utils.test.ts +++ b/packages/catalyst-core/test/native/utils.test.ts @@ -1,10 +1,14 @@ import { execFileSync, execSync, spawn } from "child_process" +import { EventEmitter } from "node:events" import fs from "fs" import os from "os" import path from "path" import readline from "readline" +import { PassThrough } from "node:stream" import { afterEach, beforeEach, describe, expect, it, vi } from "vitest" +import { onPlatform } from "../onPlatform" + // utils.js is ESM, so it is imported here the same way redactSecrets.test.ts // imports it: one module copy for v8 coverage to merge. // @@ -24,8 +28,10 @@ vi.mock("child_process", async (importOriginal) => { import { ANDROID_SDK_HINT, + androidTools, commandExists, detectAndroidSdk, + runGradle, ensureLocalProperties, listAvds, promptUser, @@ -81,7 +87,7 @@ afterEach(() => { describe("runCommand", () => { it("returns the command's stdout with stderr captured, not inherited", () => { - expect(runCommand("echo hello")).toBe("hello\n") + expect(runCommand("echo hello")).toMatch(/^hello\r?\n$/) expect(mockedExec).toHaveBeenCalledWith("echo hello", { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], @@ -119,6 +125,21 @@ describe("runCommand", () => { expect(console.error).not.toHaveBeenCalled() }) + it("names the tool in a quoted path with spaces, without its .exe", () => { + mockedExec.mockImplementationOnce(() => { + throw Object.assign(new Error("spawnSync cmd.exe ETIMEDOUT"), { code: "ETIMEDOUT" }) + }) + + let error: any + try { + runCommand('"C:\\Program Files\\Android\\platform-tools\\adb.exe" devices', { timeout: 10000 }) + } catch (caught) { + error = caught + } + expect(error.message).toBe("adb did not respond within 10s") + expect(error.hint).toContain("adb kill-server") + }) + it("recognises a timeout reported as a SIGTERM kill, with tool-specific hints", () => { const killed = () => { throw Object.assign(new Error("killed"), { signal: "SIGTERM", status: null }) @@ -271,7 +292,7 @@ describe("redactSecrets and redactError", () => { describe("commandExists", () => { it("asks `which` and reports whether it found the tool", () => { mockedExec.mockImplementationOnce(() => "") - expect(commandExists("adb")).toBe(true) + expect(onPlatform("darwin", () => commandExists("adb"))).toBe(true) expect(mockedExec).toHaveBeenLastCalledWith("which adb", { stdio: "ignore" }) mockedExec.mockImplementationOnce(() => { @@ -279,6 +300,12 @@ describe("commandExists", () => { }) expect(commandExists("adb")).toBe(false) }) + + it("asks `where` on Windows, which has no `which`", () => { + mockedExec.mockImplementationOnce(() => "") + expect(onPlatform("win32", () => commandExists("adb"))).toBe(true) + expect(mockedExec).toHaveBeenLastCalledWith("where adb", { stdio: "ignore" }) + }) }) describe("detectAndroidSdk", () => { @@ -330,7 +357,7 @@ describe("listAvds", () => { expect(listAvds("~/sdk")).toEqual(["Pixel_7_API_34", "Tablet"]) // The path is one argv entry, never a shell string. expect(mockedExecFile).toHaveBeenLastCalledWith( - path.join(home, "sdk", "emulator", "emulator"), + path.join(home, "sdk", "emulator", process.platform === "win32" ? "emulator.exe" : "emulator"), ["-list-avds"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 15000 } ) @@ -350,6 +377,94 @@ describe("listAvds", () => { }) }) +describe("androidTools", () => { + it("names the executables each platform actually has", () => { + const sdk = path.resolve("sdk") + expect(onPlatform("darwin", () => androidTools(sdk))).toEqual({ + adb: path.join(sdk, "platform-tools", "adb"), + emulator: path.join(sdk, "emulator", "emulator"), + }) + expect(onPlatform("win32", () => androidTools(sdk))).toEqual({ + adb: path.join(sdk, "platform-tools", "adb.exe"), + emulator: path.join(sdk, "emulator", "emulator.exe"), + }) + }) +}) + +describe("the Gradle wrapper", () => { + const project = path.resolve("my app") + const fakeChild = () => + Object.assign(new EventEmitter(), { + stdout: new PassThrough(), + stderr: new PassThrough(), + stdin: new PassThrough(), + }) + + it("runs ./gradlew in the project on POSIX, each argument intact", async () => { + const child = fakeChild() + mockedSpawn.mockImplementationOnce(() => child as any) + const done = onPlatform("linux", () => runGradle(project, ["clean", "-PconfigPath=/a b/c.json"])) + child.emit("close", 0) + await done + expect(mockedSpawn).toHaveBeenCalledWith("./gradlew", ["clean", "-PconfigPath=/a b/c.json"], { + stdio: ["pipe", "pipe", "pipe"], + cwd: project, + }) + }) + + it("runs gradlew.bat through cmd.exe on Windows", async () => { + vi.stubEnv("ComSpec", "cmd.exe") + const child = fakeChild() + mockedSpawn.mockImplementationOnce(() => child as any) + const done = onPlatform("win32", () => runGradle(project, ["clean"])) + child.emit("close", 0) + await done + vi.unstubAllEnvs() + const [command, args, options] = mockedSpawn.mock.calls.at(-1)! + expect(command).toBe("cmd.exe") + expect(args.slice(0, 3)).toEqual(["/d", "/s", "/c"]) + expect(args[3]).toContain("gradlew.bat") + // A daemon left idle holds the project open, and npm install then fails with EBUSY. + expect(args[3]).toContain(" --no-daemon clean") + expect(options).toMatchObject({ cwd: project, windowsVerbatimArguments: true }) + }) + + it("carries a failed build's output on the error", async () => { + const child = fakeChild() + mockedSpawn.mockImplementationOnce(() => child as any) + const done = onPlatform("linux", () => runGradle(project, ["installDebug"])) + child.stderr.emit("data", Buffer.from("* What went wrong:\n")) + child.emit("close", 1) + await expect(done).rejects.toMatchObject({ code: 1, output: "* What went wrong:\n" }) + }) + + // sdkmanager and avdmanager are batch files on Windows, which Node will not spawn itself. + it("sends any batch file through cmd.exe on Windows, and nothing else", async () => { + const sdkmanager = path.join("C:/sdk", "cmdline-tools", "latest", "bin", "sdkmanager.bat") + for (const run of [ + () => runInteractiveCommand(sdkmanager, ["--list"]), + () => runInheritedCommand(sdkmanager, ["--licenses"]), + ]) { + const child = fakeChild() + mockedSpawn.mockImplementationOnce(() => child as any) + const done = onPlatform("win32", run) + child.emit("close", 0) + await done + const [command, args, options] = mockedSpawn.mock.calls.at(-1)! + expect(command).toBe("cmd.exe") + expect(args[3]).toContain("sdkmanager.bat") + expect(options).toMatchObject({ windowsVerbatimArguments: true }) + } + + const child = fakeChild() + mockedSpawn.mockImplementationOnce(() => child as any) + const done = onPlatform("win32", () => runInteractiveCommand("C:/sdk/platform-tools/adb.exe", ["devices"])) + child.emit("close", 0) + await done + expect(mockedSpawn.mock.calls.at(-1)!.slice(0, 2)).toEqual(["C:/sdk/platform-tools/adb.exe", ["devices"]]) + }) +}) + describe("ensureLocalProperties", () => { it("writes sdk.dir when local.properties is missing", () => { const project = tempDir() @@ -374,7 +489,7 @@ describe("ensureLocalProperties", () => { expect(ensureLocalProperties(project, "~/Android/sdk")).toBe(true) expect(fs.readFileSync(file, "utf8")).toBe( - `ndk.dir=/ndk\nsdk.dir=${path.join(home, "Android/sdk")}\n` + `ndk.dir=/ndk\nsdk.dir=${path.join(home, "Android/sdk").replace(/\\/g, "\\\\")}\n` ) expect(ensureLocalProperties(project, "C:\\Android\\sdk")).toBe(true) diff --git a/packages/catalyst-core/test/onPlatform.ts b/packages/catalyst-core/test/onPlatform.ts new file mode 100644 index 000000000..aa0b70c8e --- /dev/null +++ b/packages/catalyst-core/test/onPlatform.ts @@ -0,0 +1,21 @@ +/** + * Makes process.platform read as `platform` until the returned function is + * called, so both sides of a platform branch are tested on every machine. + */ +export function stubPlatform(platform: NodeJS.Platform) { + const original = Object.getOwnPropertyDescriptor(process, "platform")! + Object.defineProperty(process, "platform", { ...original, value: platform }) + return () => { + Object.defineProperty(process, "platform", original) + } +} + +/** Runs `run` with process.platform reading as `platform`. */ +export function onPlatform(platform: NodeJS.Platform, run: () => T): T { + const restore = stubPlatform(platform) + try { + return run() + } finally { + restore() + } +} diff --git a/packages/catalyst-core/test/scripts/build.test.ts b/packages/catalyst-core/test/scripts/build.test.ts index 12155ab5e..12dae0891 100644 --- a/packages/catalyst-core/test/scripts/build.test.ts +++ b/packages/catalyst-core/test/scripts/build.test.ts @@ -85,6 +85,8 @@ beforeEach(() => { writeFileSync(path.join(appDir, "config", "config.json"), JSON.stringify({ BUILD_OUTPUT_PATH: "build" })) writeFileSync(path.join(appDir, "package.json"), JSON.stringify({ name: "fixture-app" })) process.env.PWD = appDir + // appRoot() reads PWD or the working directory, depending on the platform. + vi.spyOn(process, "cwd").mockReturnValue(appDir) stderr = "" vi.spyOn(process.stderr, "write").mockImplementation(((chunk: string) => { stderr += String(chunk) diff --git a/packages/catalyst-core/test/scripts/preflight.test.ts b/packages/catalyst-core/test/scripts/preflight.test.ts index 24c1894dc..623336b32 100644 --- a/packages/catalyst-core/test/scripts/preflight.test.ts +++ b/packages/catalyst-core/test/scripts/preflight.test.ts @@ -2,7 +2,13 @@ import { describe, it, expect, beforeEach, afterEach, vi } from "vitest" import { mkdtempSync, rmSync, mkdirSync, writeFileSync } from "fs" import { tmpdir } from "os" import path from "path" -import { runStaticPreflight, writeBuildInfo, checkBuildMatchesConfig } from "../../src/scripts/preflight.js" +import { + runStaticPreflight, + runStaticPreflightOrExit, + renderRegistryError, + writeBuildInfo, + checkBuildMatchesConfig, +} from "../../src/scripts/preflight.js" import { ERROR_CODES } from "../../src/errors/registry.js" // runStaticPreflight(appDir) reads config/config.json + package.json from a @@ -214,3 +220,54 @@ describe("checkBuildMatchesConfig", () => { expect(console.warn).toHaveBeenCalledWith(SKIPPED) }) }) + +describe("runStaticPreflightOrExit", () => { + const run = (dir?: string) => { + const errors: string[] = [] + vi.spyOn(console, "error").mockImplementation((line) => void errors.push(String(line))) + const exit = vi.spyOn(process, "exit").mockImplementation((() => { + throw new Error("exited") + }) as any) + let exited = false + try { + runStaticPreflightOrExit(dir) + } catch (error: any) { + if (error.message !== "exited") throw error + exited = true + } + const code = exit.mock.calls[0]?.[0] + vi.restoreAllMocks() + return { exited, code, output: errors.join("\n") } + } + + it("returns quietly for a valid app", () => { + writeApp({ config: VALID_CONFIG, pkg: VALID_PKG }) + expect(run(appDir)).toMatchObject({ exited: false, output: "" }) + }) + + it("prints every problem with a count, then exits 1", () => { + const result = run(appDir) + expect(result).toMatchObject({ exited: true, code: 1 }) + expect(result.output).toContain("PREFLIGHT-001") + expect(result.output).toMatch(/\d+ problems found/) + }) + + // Without an argument it checks appRoot(): cwd on Windows, where PWD is unset or stale. + it("defaults to the app the command runs in", () => { + writeApp({ config: VALID_CONFIG, pkg: VALID_PKG }) + vi.spyOn(process, "cwd").mockReturnValue(appDir) + vi.stubEnv("PWD", appDir) + try { + expect(run()).toMatchObject({ exited: false }) + } finally { + vi.unstubAllEnvs() + } + }) +}) + +describe("renderRegistryError", () => { + it("shows the registry's box under --verbose", () => { + const [error] = runStaticPreflight(appDir) + expect(renderRegistryError(error, "verbose")).toContain(error.code) + }) +}) diff --git a/packages/catalyst-core/test/scripts/serve.test.ts b/packages/catalyst-core/test/scripts/serve.test.ts index 16c3381f4..0d0184951 100644 --- a/packages/catalyst-core/test/scripts/serve.test.ts +++ b/packages/catalyst-core/test/scripts/serve.test.ts @@ -41,6 +41,8 @@ beforeEach(() => { writeFileSync(path.join(appDir, "config", "config.json"), JSON.stringify({ BUILD_OUTPUT_PATH: "build" })) writeFileSync(path.join(appDir, "package.json"), JSON.stringify({ name: "fixture-app" })) process.env.PWD = appDir + // appRoot() reads PWD or the working directory, depending on the platform. + vi.spyOn(process, "cwd").mockReturnValue(appDir) spawned.length = 0 preflight.staleBuild = null stderr = "" @@ -72,6 +74,14 @@ it("hands the production server the terminal's own stdout and stderr", async () expect(options.env.NODE_ENV).toBe("production") }) +it("loads its startup module by URL, which a Windows path is not", async () => { + await serve() + await vi.waitFor(() => expect(spawned).toHaveLength(1)) + + const { args } = spawned[0] + expect(args[args.indexOf("--import") + 1]).toMatch(/^file:\/\/\/.*preServerInit\.js$/) +}) + it("says to build first when there is no production build", async () => { rmSync(path.join(appDir, "build"), { recursive: true }) await serve() diff --git a/packages/catalyst-core/test/vite/dependencyPath.test.ts b/packages/catalyst-core/test/vite/dependencyPath.test.ts new file mode 100644 index 000000000..06dc2ea3e --- /dev/null +++ b/packages/catalyst-core/test/vite/dependencyPath.test.ts @@ -0,0 +1,23 @@ +import { describe, expect, it } from "vitest" + +import { isDependencyPath } from "../../src/vite/dependencyPath.mjs" + +// The loader decides between "dependency, leave it to Node" and "app file, +// transform it" from the file's path. Getting that wrong on Windows, where the +// separators are backslashes, made `catalyst build` run out of memory: esbuild +// was started for every dependency and its workers re-registered the loader. +// Literal paths, so the Windows case is checked on every OS. +describe("isDependencyPath", () => { + it("knows a dependency on every path separator", () => { + expect(isDependencyPath("/app/node_modules/vite/bin/vite.js")).toBe(true) + expect(isDependencyPath("C:\\Users\\me\\app\\node_modules\\vite\\bin\\vite.js")).toBe(true) + expect(isDependencyPath("C:\\Users\\me\\app\\node_modules/vite/bin/vite.js")).toBe(true) + }) + + it("treats app files as app files", () => { + expect(isDependencyPath("/app/src/App.js")).toBe(false) + expect(isDependencyPath("C:\\Users\\me\\app\\src\\App.js")).toBe(false) + // A folder merely named like it is not node_modules. + expect(isDependencyPath("C:\\Users\\me\\my_node_modules_notes\\App.js")).toBe(false) + }) +}) diff --git a/packages/create-catalyst-app/codemod/new-route/index.js b/packages/create-catalyst-app/codemod/new-route/index.js index bbaa86d28..d3b30797f 100644 --- a/packages/create-catalyst-app/codemod/new-route/index.js +++ b/packages/create-catalyst-app/codemod/new-route/index.js @@ -28,7 +28,24 @@ program .parse(process.argv) async function main() { - let { routePath, templateType, componentName } = program + // commander 8 keeps options on opts(), named after the long flag. + const options = program.opts() + let routePath = options.path + let componentName = options.component + let templateType + + // A value given on the command line skips its question, so check it here. + for (const [value, validate] of [ + [routePath, validatePath], + [componentName, validateComponentName], + ]) { + const verdict = value === undefined ? true : validate(value) + if (verdict !== true) { + console.log(pc.red(`\nError: ${verdict}`)) + process.exitCode = 1 + return + } + } // If all options are not provided, prompt the user for input if (!routePath || !componentName || !templateType) { @@ -105,6 +122,8 @@ async function main() { } catch (e) { discardChanges(funcArgs) console.log(pc.red(`\n${e}`)) + // Nothing was created: a script or CI step must not read this as success. + process.exitCode = 1 } } } diff --git a/packages/create-catalyst-app/codemod/new-route/template.js b/packages/create-catalyst-app/codemod/new-route/template.js index ea82d9bfc..286435f2c 100644 --- a/packages/create-catalyst-app/codemod/new-route/template.js +++ b/packages/create-catalyst-app/codemod/new-route/template.js @@ -37,7 +37,7 @@ const initialState = { } export const appSlice = createSlice({ - name: ${reducerName}Reducer, + name: "${reducerName}Reducer", initialState: initialState, reducers: { reduxTest: (state) => { @@ -70,7 +70,7 @@ return actionTypesObject export default createActionTypes -export const ${reducerName}Actions = createActionTypes(${reducerName}Actions, ["REDUX_TEST"]) +export const ${reducerName}Actions = createActionTypes("${reducerName}Actions", ["REDUX_TEST"]) export const reduxTest = () => { return { type: ${reducerName}Actions.REDUX_TEST, diff --git a/packages/create-catalyst-app/codemod/new-route/utils.js b/packages/create-catalyst-app/codemod/new-route/utils.js index 4267e208a..f0482d2ae 100644 --- a/packages/create-catalyst-app/codemod/new-route/utils.js +++ b/packages/create-catalyst-app/codemod/new-route/utils.js @@ -3,7 +3,9 @@ const path = require("path") const pc = require("ansis") const { execFileSync } = require("child_process") -const executable = (command) => (process.platform === "win32" ? `${command}.cmd` : command) +// Run jscodeshift's own script with this Node. Its command name needs PATH to +// include node_modules/.bin, and on Windows names a .cmd Node refuses to spawn. +const jscodeshift = require.resolve("jscodeshift/bin/jscodeshift.js") // validates router path function validatePath(path) { @@ -14,7 +16,6 @@ function validatePath(path) { } if (!pathPattern.test(path)) { if (!/^[\/a-zA-Z0-9-_]+/.test(path)) { - s return "Only letters, digits, hyphens, and underscores are allowed after the initial slash." } if (/\/[^:][a-zA-Z0-9-_]+/.test(path)) { @@ -57,14 +58,16 @@ function createDirectory({ componentName, containersDir }) { return true } catch (e) { console.log(pc.red(`\nError: ${e}`)) + process.exitCode = 1 } } // adds route object inside src/js/route/index.js file function createNewRoute({ componentName, routePath, routeTransformerPath }) { execFileSync( - executable("jscodeshift"), + process.execPath, [ + jscodeshift, "--silent", "-t", routeTransformerPath, @@ -81,8 +84,9 @@ function createNewRoute({ componentName, routePath, routeTransformerPath }) { // adds newly created reducer into src/js/store/index.js file function createReducerEntryInStore({ componentName, routePath, reducerTransformerPath, reducerName }) { execFileSync( - executable("jscodeshift"), + process.execPath, [ + jscodeshift, "--silent", "-t", reducerTransformerPath, diff --git a/packages/create-catalyst-app/scripts/cli.cjs b/packages/create-catalyst-app/scripts/cli.cjs index a5d7388c9..c76d95560 100755 --- a/packages/create-catalyst-app/scripts/cli.cjs +++ b/packages/create-catalyst-app/scripts/cli.cjs @@ -40,7 +40,6 @@ const cancelWithError = (err, message = err.message) => { if (outputMode !== "default") printError(err) } const packageRoot = path.join(__dirname, "..") -const executable = (command) => (process.platform === "win32" ? `${command}.cmd` : command) let projectName = null const program = new Commander.Command() @@ -71,7 +70,9 @@ const program = new Commander.Command() if (process.argv.includes("new-route")) { const createRoutePath = path.join(__dirname, "../codemod/new-route/index.js") - execSync(`node ${createRoutePath}`, { stdio: "inherit" }) + // Everything after new-route is its own: -p/--path and -c/--component. + const routeArgs = process.argv.slice(process.argv.indexOf("new-route") + 1) + execFileSync(process.execPath, [createRoutePath, ...routeArgs], { stdio: "inherit" }) return } @@ -223,7 +224,8 @@ const program = new Commander.Command() gray("Add to your MCP client (Claude, Cursor, Windsurf):"), `"catalyst-mcp": {`, ` "command": "node",`, - ` "args": ["${mcpEntry}"]`, + // Stringified: a Windows path's backslashes must be escaped to paste as JSON. + ` "args": [${JSON.stringify(mcpEntry)}]`, `}`, ].join("\n"), "MCP server" @@ -235,6 +237,8 @@ const program = new Commander.Command() // The step that failed already printed its own output. const catalystError = error instanceof CCAError ? error : wrapForeignError(error) cancelWithError(catalystError, `Could not create ${projectName}: ${error.message}`) + // process.exit skips the finally below, leaving a temp-* folder behind. + deleteDirectory(tempDir) process.exit(1) } finally { deleteDirectory(tempDir) @@ -246,21 +250,9 @@ const program = new Commander.Command() try { if (process.env.CREATE_CATALYST_APP_PACK_SOURCE === "local") { - execFileSync( - executable("npm"), - ["pack", `--pack-destination=${tempDir}`, "--silent"], - { - cwd: packageRoot, - } - ) + runNpm(["pack", `--pack-destination=${tempDir}`, "--silent"], { cwd: packageRoot }) } else { - execFileSync( - executable("npm"), - ["pack", `${packageName}@${packageVersion}`, "--silent"], - { - cwd: tempDir, - } - ) + runNpm(["pack", `${packageName}@${packageVersion}`, "--silent"], { cwd: tempDir }) } return tarballFilePath @@ -405,6 +397,17 @@ function mcpWarnings(transcript) { return warnings } +/** + * Run npm directly, or through a shell on Windows: npm is a .cmd there, which Node + * refuses to spawn (EINVAL). A Windows path cannot contain a double quote, so + * quoting each argument is enough. + */ +function runNpm(args, options) { + if (process.platform !== "win32") return execFileSync("npm", args, options) + // nosemgrep: javascript.lang.security.detect-child-process.detect-child-process - arguments come from this package's own package.json and a folder this process created. + return execSync(["npm", ...args.map((arg) => `"${arg}"`)].join(" "), options) +} + /** * Run a command with its output captured rather than inherited. * diff --git a/packages/create-catalyst-app/test/new-route.test.ts b/packages/create-catalyst-app/test/new-route.test.ts new file mode 100644 index 000000000..c849f883c --- /dev/null +++ b/packages/create-catalyst-app/test/new-route.test.ts @@ -0,0 +1,179 @@ +import { execFileSync } from "node:child_process" +import fs from "node:fs" +import os from "node:os" +import path from "node:path" +import { pathToFileURL } from "node:url" + +// describe/it/expect come from vitest's `globals: true` config (see vitest.config.mjs). +const { + checkIfRoutePathExist, + createDirectory, + createNewRoute, + createReducerEntryInStore, + discardChanges, + toCamelCase, + validateComponentName, + validatePath, +} = require("../codemod/new-route/utils.js") +const { + createNewComponent, + createReduxActionFile, + createReduxReducerFile, + createRTKReducerFile, +} = require("../codemod/new-route/template.js") + +const templates = path.resolve(__dirname, "..", "templates") +const originalCwd = process.cwd() +let app: string + +beforeEach(() => { + app = fs.mkdtempSync(path.join(os.tmpdir(), "catalyst new route ")) + // A scaffolded app is the common template with the chosen one on top. + for (const template of ["common", "redux-js"]) { + fs.cpSync(path.join(templates, template, "src"), path.join(app, "src"), { recursive: true }) + } + // The codemod works on paths relative to the app, as `npx create-catalyst-app new-route` does. + process.chdir(app) +}) + +afterEach(() => { + process.chdir(originalCwd) + process.exitCode = undefined + fs.rmSync(app, { recursive: true, force: true }) +}) + +const read = (relative: string) => fs.readFileSync(path.join(app, relative), "utf8") +const transformer = (name: string) => + path.resolve(__dirname, "..", "codemod", "new-route", "transformers", name) + +describe("new-route", () => { + // Runs the real jscodeshift: on Windows its command name is a .cmd, which Node + // refuses to spawn, and the failure left the route out while still exiting 0. + it("adds the route to src/js/routes/index.js", () => { + createNewRoute({ + componentName: "Probe", + routePath: "/probe", + routeTransformerPath: transformer("createRoute.js"), + }) + expect(read("src/js/routes/index.js")).toContain("/probe") + expect(read("src/js/routes/index.js")).toContain("Probe") + }) + + it("adds the reducer to src/js/store/index.js", () => { + createReducerEntryInStore({ + componentName: "Probe", + routePath: "/probe", + reducerName: "probe", + reducerTransformerPath: transformer("createReducer.js"), + }) + expect(read("src/js/store/index.js")).toMatch(/probe/i) + }) + + // These used to refer to the variable they were declaring, which crashes the + // whole app with a ReferenceError the moment the store loads. + it("generates redux actions that load", () => { + vi.spyOn(console, "log").mockImplementation(() => {}) + const containersDir = "src/js/containers" + fs.mkdirSync(path.join(app, containersDir, "Probe"), { recursive: true }) + createReduxActionFile({ componentName: "Probe", containersDir, reducerName: "probe" }) + vi.restoreAllMocks() + + fs.writeFileSync(path.join(app, "package.json"), JSON.stringify({ type: "module" })) + const url = pathToFileURL(path.join(app, containersDir, "Probe", "actions.js")).href + const output = execFileSync( + process.execPath, + [ + "--input-type=module", + "-e", + `import { probeActions } from "${url}"; console.log(probeActions.REDUX_TEST)`, + ], + { encoding: "utf8" } + ) + expect(output.trim()).toBe("probeActions/REDUX_TEST") + }) + + it("generates an RTK slice named with a string", () => { + vi.spyOn(console, "log").mockImplementation(() => {}) + const containersDir = "src/js/containers" + fs.mkdirSync(path.join(app, containersDir, "Probe"), { recursive: true }) + createRTKReducerFile({ componentName: "Probe", containersDir, reducerName: "probe" }) + vi.restoreAllMocks() + expect(read(`${containersDir}/Probe/reducer.js`)).toContain('name: "probeReducer",') + }) + + it("exits non-zero when the component folder already exists", () => { + vi.spyOn(console, "log").mockImplementation(() => {}) + const containersDir = "src/js/containers" + fs.mkdirSync(path.join(app, containersDir, "Probe"), { recursive: true }) + expect(createDirectory({ componentName: "Probe", containersDir })).toBeUndefined() + expect(process.exitCode).toBe(1) + vi.restoreAllMocks() + }) +}) + +describe("new-route answers", () => { + it("accepts a path, a parameter and a query", () => { + expect(validatePath("/probe")).toBe(true) + expect(validatePath("/probe/:id")).toBe(true) + expect(validatePath("/probe?tab=1")).toBe(true) + }) + + it("says what is wrong with a path", () => { + expect(validatePath("probe")).toMatch(/must start with a forward slash/) + expect(validatePath("/probe/id")).toMatch(/Parameters must start/) + expect(validatePath("/a?x!")).toMatch(/incorrectly formatted/) + }) + + it("wants a component name in PascalCase", () => { + expect(validateComponentName("Probe")).toBe(true) + expect(validateComponentName("probe")).toMatch(/uppercase/) + }) + + it("camel-cases a name for the reducer", () => { + expect(toCamelCase("probe-page")).toBe("probePage") + expect(toCamelCase("Probe Page")).toBe("probePage") + }) + + it("refuses a route or component the routes file already has", () => { + expect(() => checkIfRoutePathExist({ routePath: "/fresh", componentName: "Fresh" })).not.toThrow() + createNewRoute({ + componentName: "Probe", + routePath: "/probe", + routeTransformerPath: transformer("createRoute.js"), + }) + expect(() => checkIfRoutePathExist({ routePath: "/probe", componentName: "Other" })).toThrow( + /\/probe path already exist/ + ) + expect(() => checkIfRoutePathExist({ routePath: "/other", componentName: "Probe" })).toThrow( + /Probe component path already exist/ + ) + }) +}) + +describe("new-route files", () => { + const containersDir = "src/js/containers" + const folder = () => path.join(app, containersDir, "Probe") + + beforeEach(() => { + vi.spyOn(console, "log").mockImplementation(() => {}) + }) + afterEach(() => vi.restoreAllMocks()) + + it("creates the component folder, and removes it again on failure", () => { + expect(createDirectory({ componentName: "Probe", containersDir })).toBe(true) + expect(fs.existsSync(folder())).toBe(true) + discardChanges({ componentName: "Probe", containersDir }) + expect(fs.existsSync(folder())).toBe(false) + // Nothing there: still fine. + discardChanges({ componentName: "Probe", containersDir }) + }) + + it("writes the component and a redux reducer for it", () => { + fs.mkdirSync(folder(), { recursive: true }) + createNewComponent({ componentName: "Probe", containersDir }) + createReduxReducerFile({ componentName: "Probe", containersDir, reducerName: "probe" }) + expect(read(`${containersDir}/Probe/Probe.js`)).toContain("const Probe = () =>") + expect(read(`${containersDir}/Probe/Probe.js`)).toContain("export default Probe") + expect(read(`${containersDir}/Probe/reducer.js`)).toMatch(/probe/) + }) +}) diff --git a/scripts/create-release-sandbox.js b/scripts/create-release-sandbox.js index 57ca94714..44f57a5b1 100644 --- a/scripts/create-release-sandbox.js +++ b/scripts/create-release-sandbox.js @@ -7,7 +7,16 @@ const defaultSandboxDir = path.join(repoRoot, ".sandbox") const npmCacheDir = path.join(defaultSandboxDir, ".npm-cache") const corePackageDir = path.join(repoRoot, "packages", "catalyst-core") const ccaPackageDir = path.join(repoRoot, "packages", "create-catalyst-app") -const npmCommand = process.platform === "win32" ? "npm.cmd" : "npm" +// npm is a .cmd on Windows, which Node refuses to spawn directly (EINVAL). Under +// `npm run` npm has told us where its script is; run directly, it takes a shell. +function npmInvocation(args) { + if (process.platform !== "win32") return { file: "npm", args, shell: false } + if (process.env.npm_execpath) { + return { file: process.execPath, args: [process.env.npm_execpath, ...args], shell: false } + } + const quoted = args.map((arg) => `"${arg}"`) + return { file: ["npm", ...quoted].join(" "), args: [], shell: true } +} function usage() { console.log(`Usage: @@ -92,18 +101,19 @@ function run(command, args, options = {}) { let result if (command === "npm") { - result = spawnSync(npmCommand, args, { + const npm = npmInvocation(args) + // nosemgrep: javascript.lang.security.audit.spawn-shell-true.spawn-shell-true - internal release helper; see npmInvocation. + result = spawnSync(npm.file, npm.args, { cwd: repoRoot, stdio: "inherit", + shell: npm.shell, ...options, env, }) } else if (command === "node") { - // nosemgrep: javascript.lang.security.audit.spawn-shell-true.spawn-shell-true - Windows node execution intentionally uses shell compatibility in this internal release helper. result = spawnSync(process.execPath, args, { cwd: repoRoot, stdio: "inherit", - shell: process.platform === "win32", ...options, env, }) @@ -126,18 +136,19 @@ function runCapture(command, args, options = {}) { let result if (command === "npm") { - result = spawnSync(npmCommand, args, { + const npm = npmInvocation(args) + // nosemgrep: javascript.lang.security.audit.spawn-shell-true.spawn-shell-true - internal release helper; see npmInvocation. + result = spawnSync(npm.file, npm.args, { cwd: repoRoot, encoding: "utf8", + shell: npm.shell, ...options, env, }) } else if (command === "node") { - // nosemgrep: javascript.lang.security.audit.spawn-shell-true.spawn-shell-true - Windows node execution intentionally uses shell compatibility in this internal release helper. result = spawnSync(process.execPath, args, { cwd: repoRoot, encoding: "utf8", - shell: process.platform === "win32", ...options, env, }) diff --git a/scripts/native-elf-alignment.mjs b/scripts/native-elf-alignment.mjs index 5ff624bd3..7d86dbd35 100644 --- a/scripts/native-elf-alignment.mjs +++ b/scripts/native-elf-alignment.mjs @@ -112,7 +112,14 @@ function checkNativeAlignment(archive, { apk } = {}) { } else if (isApk && entry.method === 0 && entry.dataOffset % PAGE_16K !== 0) { problem = `stored uncompressed at zip offset ${entry.dataOffset}, not on a 16 KB boundary` } - libs.push({ name: entry.name, bits, minAlign, required, ok: !problem, ...(problem ? { problem } : {}) }) + libs.push({ + name: entry.name, + bits, + minAlign, + required, + ok: !problem, + ...(problem ? { problem } : {}), + }) } const failures = libs.filter((lib) => lib.required && !lib.ok).map((lib) => `${lib.name}: ${lib.problem}`) return { libs, failures } diff --git a/scripts/setup.js b/scripts/setup.js index eff6744f4..f02d23a81 100644 --- a/scripts/setup.js +++ b/scripts/setup.js @@ -7,20 +7,32 @@ const docsDir = path.join(repoRoot, "docs") const docsConfigPath = path.join(docsDir, "config", "config.json") const docsConfigTemplatePath = path.join(docsDir, "config", "config_template.json") +// npm is a .cmd on Windows, which Node refuses to spawn directly (EINVAL). Under +// `npm run` npm has told us where its script is; run directly, it takes a shell. +function npmInvocation(args) { + if (process.platform !== "win32") return { file: "npm", args, shell: false } + if (process.env.npm_execpath) { + return { file: process.execPath, args: [process.env.npm_execpath, ...args], shell: false } + } + const quoted = args.map((arg) => `"${arg}"`) + return { file: ["npm", ...quoted].join(" "), args: [], shell: true } +} + function run(command, args, options = {}) { let result if (command === "npm") { - result = spawnSync(process.platform === "win32" ? "npm.cmd" : "npm", args, { + const npm = npmInvocation(args) + // nosemgrep: javascript.lang.security.audit.spawn-shell-true.spawn-shell-true - fixed setup commands; see npmInvocation. + result = spawnSync(npm.file, npm.args, { cwd: repoRoot, stdio: "inherit", + shell: npm.shell, ...options, }) } else if (command === "node") { - // nosemgrep: javascript.lang.security.audit.spawn-shell-true.spawn-shell-true - Windows node execution intentionally uses shell compatibility during setup. result = spawnSync(process.execPath, args, { cwd: repoRoot, stdio: "inherit", - shell: process.platform === "win32", ...options, }) } else { diff --git a/scripts/test-windows-smoke.js b/scripts/test-windows-smoke.js new file mode 100644 index 000000000..f0c58af9f --- /dev/null +++ b/scripts/test-windows-smoke.js @@ -0,0 +1,93 @@ +// Native Windows smoke test: scaffolds an app with the branch's create-catalyst-app into a +// folder with a space and parentheses in its name, builds it, then answers a request from +// `catalyst start` and `catalyst serve`. Each of these failed on Windows in a different way, +// so all of them run for real: a green unit suite said nothing about any of them. +const { execFileSync, spawn, spawnSync } = require("child_process") +const fs = require("fs") +const os = require("os") +const path = require("path") + +const repoRoot = path.resolve(__dirname, "..") +const parentDir = fs.mkdtempSync(path.join(os.tmpdir(), "catalyst smoke (x86) ")) +const appName = "smoke-app" +const appDir = path.join(parentDir, appName) +const serverTimeoutMs = 120000 + +const env = { + ...process.env, + GIT_AUTHOR_NAME: "github-actions[bot]", + GIT_AUTHOR_EMAIL: "github-actions[bot]@users.noreply.github.com", + GIT_COMMITTER_NAME: "github-actions[bot]", + GIT_COMMITTER_EMAIL: "github-actions[bot]@users.noreply.github.com", +} + +function run(label, args, options) { + console.log(`\n=== ${label}`) + const result = spawnSync(process.execPath, args, { stdio: "inherit", env, ...options }) + if (result.status !== 0) throw new Error(`${label} exited with ${result.status}`) +} + +function stopTree(pid) { + try { + execFileSync("taskkill", ["/T", "/F", "/PID", String(pid)], { stdio: "ignore" }) + } catch (error) { + // Already gone. + } +} + +async function expectServerAnswers(command) { + console.log(`\n=== catalyst ${command}`) + const catalyst = path.join(appDir, "node_modules", "catalyst-core", "bin", "catalyst.js") + const child = spawn(process.execPath, [catalyst, command], { + cwd: appDir, + stdio: "inherit", + // A leftover PWD must not win over the folder the command runs in. + env: { ...env, PWD: repoRoot }, + }) + const deadline = Date.now() + serverTimeoutMs + try { + while (Date.now() < deadline) { + if (child.exitCode !== null) throw new Error(`catalyst ${command} exited with ${child.exitCode}`) + try { + const response = await fetch("http://localhost:3005/", { signal: AbortSignal.timeout(30000) }) + const body = await response.text() + if (response.status !== 200 || !body.includes('id="app"')) { + throw new Error(`catalyst ${command} answered ${response.status}: ${body.slice(0, 300)}`) + } + console.log(`catalyst ${command} answered 200, ${body.length} chars`) + return + } catch (error) { + if (error.message.startsWith("catalyst ")) throw error + await new Promise((resolve) => setTimeout(resolve, 1000)) + } + } + throw new Error(`catalyst ${command} did not answer within ${serverTimeoutMs / 1000}s`) + } finally { + stopTree(child.pid) + } +} + +async function main() { + // The sandbox script builds catalyst-core, scaffolds with create-catalyst-app and builds the app. + run("scaffold and build", [ + path.join(repoRoot, "scripts", "create-release-sandbox.js"), + "--target-dir", + parentDir, + "--name", + appName, + "--yes", + "--force", + ]) + await expectServerAnswers("start") + await expectServerAnswers("serve") + console.log("\nWindows smoke test passed") +} + +main() + .catch((error) => { + console.error(`\nWindows smoke test failed: ${error.message}`) + process.exitCode = 1 + }) + .finally(() => { + fs.rmSync(parentDir, { recursive: true, force: true, maxRetries: 5, retryDelay: 500 }) + })