From 6a83f59c9ec9b14771473016afd95e9cf1741eef Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 21 Oct 2026 01:29:36 +0900 Subject: [PATCH 1/2] fix(native): ignore padding in wide reduction AND A two-state reduction AND of an all-ones vector such as 981 or 2051 bits currently returns zero because unused high bits of the last storage word are included. In both the x86-64 and AArch64 backends, fill that padding with ones before reducing and iterate over the declared source width. Add a shared regression that checks the all-ones value and clears each of the 981 declared bits individually. It passes native, Cranelift, Wasm and parallel variants on x86-64, plus Verilator and Icarus. Run its native and native-parallel variants in the ARM64 CI job as well. Add a direct AArch64 regression for widths 1, 63, 64, 65, 127, 128, 129, 981, 1024 and 2051, including widening the one-bit result. It generates AArch64 code on every host; on AArch64 Linux it executes each all-ones value and every single-cleared-bit value, then verifies restoration. Validation: 611 x86 native unit tests and 47 AArch64 backend tests on x86-64; focused shared SV regression; affected backend Clippy and formatting; AArch64-target test compilation using the installed Rust 1.99.1 toolchain; 16 CI workflow script tests and actionlint (ignoring its outdated runner-label catalogue for the existing ubuntu-26.04-arm label). Related wide-operator, four-state and parameterized-operation consumers also passed. AArch64 machine-code execution requires the ARM CI runner and was not run locally. Change-Id: I57339044d93504b32e95b254505a76153682d1f6 --- .github/workflows/ci.yml | 5 + crates/celox-backend-arm64/src/isel/tests.rs | 1 + .../src/isel/tests/reductions.rs | 120 ++++++++++++++++++ .../src/isel/wide_unary.rs | 22 +++- .../src/backend/native/isel/wide_unary.rs | 22 +++- .../src/sv/cases/operators.vtest | 16 +++ .../frontends/systemverilog/operators.rs | 6 + 7 files changed, 188 insertions(+), 4 deletions(-) create mode 100644 crates/celox-backend-arm64/src/isel/tests/reductions.rs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a7eba619c0d..e2eace94df0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -673,6 +673,11 @@ jobs: - name: Test AArch64 facade integration run: cargo test --locked -p celox --lib --test native_exec + - name: Test partial-word reduction AND on AArch64 + run: >- + cargo test --locked -p celox --features systemverilog + --test systemverilog wide_reduction_and_respects_partial_storage_words::native + - name: Check x86-64 cross-codegen from AArch64 run: >- cargo check --locked -p celox -p celox-bench diff --git a/crates/celox-backend-arm64/src/isel/tests.rs b/crates/celox-backend-arm64/src/isel/tests.rs index a7aa3bd8706..403ea737368 100644 --- a/crates/celox-backend-arm64/src/isel/tests.rs +++ b/crates/celox-backend-arm64/src/isel/tests.rs @@ -1,4 +1,5 @@ mod partial_load; +mod reductions; mod shifts; mod slice; mod strided; diff --git a/crates/celox-backend-arm64/src/isel/tests/reductions.rs b/crates/celox-backend-arm64/src/isel/tests/reductions.rs new file mode 100644 index 00000000000..c5033ee86ad --- /dev/null +++ b/crates/celox-backend-arm64/src/isel/tests/reductions.rs @@ -0,0 +1,120 @@ +//! Compile on every host and execute the emitted code on AArch64. +use super::*; + +#[test] +fn wide_reduction_and_respects_source_width_and_partial_words() { + for width in [1usize, 63, 64, 65, 127, 128, 129, 981, 1024, 2051] { + // Also check that widening the one-bit result keeps the high bits clear. + for result_width in [1, 193] { + let input = AbsoluteAddr { + instance_id: InstanceId(0), + var_id: StateObjectId(0), + }; + let output = AbsoluteAddr { + var_id: StateObjectId(1), + ..input + }; + let address = + |absolute| RegionedAbsoluteAddr::from_absolute_addr(STABLE_REGION, absolute); + let loaded = RegisterId(0); + let reduced = RegisterId(1); + let result = RegisterId(2); + let unit = ExecutionUnit { + entry_block_id: SirBlockId(0), + blocks: [( + SirBlockId(0), + BasicBlock { + id: SirBlockId(0), + params: vec![], + instructions: vec![ + SIRInstruction::Load( + loaded, + address(input), + SIROffset::Static(0), + width, + ), + SIRInstruction::Unary(reduced, UnaryOp::And, loaded), + SIRInstruction::Unary(result, UnaryOp::Ident, reduced), + SIRInstruction::Store( + address(output), + SIROffset::Static(0), + result_width, + result, + vec![], + vec![], + ), + ], + terminator: SIRTerminator::Return, + }, + )] + .into_iter() + .collect(), + register_map: [(loaded, width), (reduced, 1), (result, result_width)] + .into_iter() + .map(|(register, width)| { + ( + register, + RegisterType::Bit { + width, + signed: false, + }, + ) + }) + .collect(), + }; + let output_offset = width.div_ceil(64) * 8; + let size = output_offset + result_width.div_ceil(64) * 8; + let mut layout = layout_for(input, width, false); + layout.offsets.insert(output, output_offset); + layout.widths.insert(output, result_width); + layout.is_4states.insert(output, false); + layout.total_size = size; + layout.working_base_offset = size; + layout.sparse_base_offset = size; + layout.sparse_active_bits_offset = size; + layout.merged_total_size = size; + layout.triggered_bits_offset = size; + layout.scratch_base_offset = size; + let image = crate::scalar::emit_prepared_eu( + &unit, + &layout, + false, + "reduction_and", + false, + None, + || false, + ) + .unwrap(); + assert!(!image.code.is_empty()); + + #[cfg(all(target_arch = "aarch64", target_os = "linux"))] + { + use num_bigint::BigUint; + let jit = crate::jit_mem::JitCode::new(&image.code).unwrap(); + let ones = (BigUint::from(1u8) << width) - 1u8; + let mut state = vec![0u8; size]; + let mut check = |value: &BigUint, expected: u8| { + state.fill(0); + let bytes = value.to_bytes_le(); + state[..bytes.len()].copy_from_slice(&bytes); + // Ensure the entire result, including widened high bits, is written. + state[output_offset..].fill(0xff); + assert_eq!(unsafe { jit.call(&mut state) }, 0); + let end = output_offset + result_width.div_ceil(8); + let actual = BigUint::from_bytes_le(&state[output_offset..end]) + & ((BigUint::from(1u8) << result_width) - 1u8); + assert_eq!( + actual, + BigUint::from(expected), + "width={width} result_width={result_width} input={value:x}" + ); + }; + check(&ones, 1); + for bit in 0..width { + check(&(&ones ^ (BigUint::from(1u8) << bit)), 0); + } + check(&ones, 1); + } + } + } +} diff --git a/crates/celox-backend-arm64/src/isel/wide_unary.rs b/crates/celox-backend-arm64/src/isel/wide_unary.rs index 4909d87454d..91cb349f357 100644 --- a/crates/celox-backend-arm64/src/isel/wide_unary.rs +++ b/crates/celox-backend-arm64/src/isel/wide_unary.rs @@ -170,8 +170,26 @@ pub(super) fn lower_wide_unary( value: u64::MAX, }); let mut acc = all_ones; - for i in 0..n_chunks { - let c = ctx.wide_chunk_or_zero(&src_chunks, i, block); + for i in 0..ISelContext::num_chunks(src_width) { + let mut c = ctx.wide_chunk_or_zero(&src_chunks, i, block); + let valid_bits = (src_width - i * 64).min(64); + if valid_bits < 64 { + // Padding outside the declared source width must not + // make an all-ones packed value reduce to zero. + let padding = u64::MAX << valid_bits; + let mask = ctx.alloc_vreg(SpillDesc::remat(padding)); + block.push(MInst::LoadImm { + dst: mask, + value: padding, + }); + let filled = ctx.alloc_vreg(SpillDesc::transient()); + block.push(MInst::Or { + dst: filled, + lhs: c, + rhs: mask, + }); + c = filled; + } let next = ctx.alloc_vreg(SpillDesc::transient()); block.push(MInst::And { dst: next, diff --git a/crates/celox-backend-x86/src/backend/native/isel/wide_unary.rs b/crates/celox-backend-x86/src/backend/native/isel/wide_unary.rs index 4909d87454d..91cb349f357 100644 --- a/crates/celox-backend-x86/src/backend/native/isel/wide_unary.rs +++ b/crates/celox-backend-x86/src/backend/native/isel/wide_unary.rs @@ -170,8 +170,26 @@ pub(super) fn lower_wide_unary( value: u64::MAX, }); let mut acc = all_ones; - for i in 0..n_chunks { - let c = ctx.wide_chunk_or_zero(&src_chunks, i, block); + for i in 0..ISelContext::num_chunks(src_width) { + let mut c = ctx.wide_chunk_or_zero(&src_chunks, i, block); + let valid_bits = (src_width - i * 64).min(64); + if valid_bits < 64 { + // Padding outside the declared source width must not + // make an all-ones packed value reduce to zero. + let padding = u64::MAX << valid_bits; + let mask = ctx.alloc_vreg(SpillDesc::remat(padding)); + block.push(MInst::LoadImm { + dst: mask, + value: padding, + }); + let filled = ctx.alloc_vreg(SpillDesc::transient()); + block.push(MInst::Or { + dst: filled, + lhs: c, + rhs: mask, + }); + c = filled; + } let next = ctx.alloc_vreg(SpillDesc::transient()); block.push(MInst::And { dst: next, diff --git a/crates/celox-test-suite/src/sv/cases/operators.vtest b/crates/celox-test-suite/src/sv/cases/operators.vtest index be1e0c90737..0cd6abf3297 100644 --- a/crates/celox-test-suite/src/sv/cases/operators.vtest +++ b/crates/celox-test-suite/src/sv/cases/operators.vtest @@ -1500,3 +1500,19 @@ endmodule (modify (set row 5) (set col 3)) (assert_eq selected 0x38) (assert_eq bit_value 1)) + +(case wide_reduction_and_respects_partial_storage_words + (source "partial_reduction.sv" #" + module Top(input logic [980:0] a, output logic all_set); + assign all_set = &a; + endmodule + "#) + (top Top) + (let ones (- (<< 1 981) 1)) + (modify (set a ones)) + (assert_eq all_set 1) + (for bit (range 0 981) + (modify (set a (^ ones (<< 1 bit)))) + (assert_eq all_set 0 "each declared bit contributes, including the partial last word")) + (modify (set a ones)) + (assert_eq all_set 1)) diff --git a/crates/celox/tests/frontends/systemverilog/operators.rs b/crates/celox/tests/frontends/systemverilog/operators.rs index 58533bc3e51..1927a0ffded 100644 --- a/crates/celox/tests/frontends/systemverilog/operators.rs +++ b/crates/celox/tests/frontends/systemverilog/operators.rs @@ -158,3 +158,9 @@ sv_backends! { @case "operators::wide_wildcard_comparisons_normalize_unknown_to_x"; } } + +sv_backends! { + fn wide_reduction_and_respects_partial_storage_words(sim) { + @case "operators::wide_reduction_and_respects_partial_storage_words"; + } +} From 16302329a6105739ae856ea0560ad7cfb139d550 Mon Sep 17 00:00:00 2001 From: tignear Date: Tue, 20 Oct 2026 19:03:16 +0900 Subject: [PATCH 2/2] fix(vite): resolve cached Veryl imports inside and outside the root Vitest's persistent cache replays imports as Vite root-relative URLs or /@fs/ URLs for sources outside the Vite root. Resolve both forms to their canonical source, project and watch IDs so warm runs load generated JavaScript instead of raw Veryl. Prefer the Vite-root candidate for cached URLs outside the project's absolute namespace even if an unrelated host path exists. A matching project prefix only preserves an absolute identity when that file exists; otherwise try the Vite-root candidate too. Preserve canonical absolute project IDs and explicit /@fs/ identities, virtual-module ownership and optional watch-file behavior. Add real-file collision, prefix-shaped URL (including projectRoot=/) and source/query resolution regressions. Run the injected component fixture cold and warm in both internal and external project layouts. Normalize the fixture's absolute test include path to forward slashes so Vitest also discovers the test on Windows. Preserve the canonical watch identity of absent optional configuration when replaying cached root-relative URLs, including the Windows drive letter. Validation: - External /@fs/ and colliding-host regressions reproduce before their fixes. Both prefix-shaped URL regressions also fail on the previous head. - Vite package tests: 132 passed; cold/warm fixtures pass in both layouts (8 assertions). - Dependency, source/client-build, build-watch and component-watch checks pass. - TypeScript build, plugin/playground type checks, plugin Biome and diff checks pass. - NAPI rebuilt from unmodified master Rust sources independently of the struct fix. Windows fixture follow-up validation: - Rebuilt NAPI and JS packages; reran the Vite package tests and fixture end-to-end checks on Linux. - Explicit fixture-config TypeScript check and Biome formatting/lint output check pass. - Reproduced the internal warm-cache failure on Windows with Node 24.12.0, pnpm 12.13.0 and the Windows NAPI artifact from CI run 39440394247. - Windows: CI JS test command passes (422 runtime tests, 130 Vite tests with 2 existing platform skips, cold/warm internal/external fixtures and dependency/source/build/component watch checks). - Added absent-config watch-identity regression: fails before the fix and passes afterward on Linux and Windows. - Linux: Vite package tests (132 passed), fixture checks, playground typecheck and plugin Biome pass. Change-Id: I7613c2a332df5a43a7aac5b09e73207f05bc269d --- packages/playground/package.json | 2 +- .../injected-components/cache-e2e.mjs | 50 ++++++ .../injected-components/vitest.config.ts | 11 +- .../playground/test/vite-plugin-watch.test.ts | 157 +++++++++++++++++- packages/vite-plugin/src/index.ts | 39 ++++- 5 files changed, 244 insertions(+), 15 deletions(-) create mode 100644 packages/playground/test/fixtures/injected-components/cache-e2e.mjs diff --git a/packages/playground/package.json b/packages/playground/package.json index 3f8035c9154..74f2cbca4d3 100644 --- a/packages/playground/package.json +++ b/packages/playground/package.json @@ -9,7 +9,7 @@ "preview": "vite preview", "test": "vitest run", "typecheck": "node test/generate-sidecars.mjs && tsc -p .", - "test:vite-components": "vitest run test/vite-plugin-cache.test.ts test/generated-dts.test.ts test/vite-assertion-bytes.test.ts test/vite-plugin-cache-real.test.ts test/vite-plugin-watch.test.ts test/sidecar-orphans.test.ts test/sidecar-lock.test.ts && vitest run --config test/fixtures/injected-components/vitest.config.ts && node test/fixtures/injected-components/dependency-e2e.mjs && node test/fixtures/source-watch/watch-e2e.mjs && node test/fixtures/source-watch/build-watch-e2e.mjs && node test/fixtures/source-watch/component-watch-e2e.mjs", + "test:vite-components": "vitest run test/vite-plugin-cache.test.ts test/generated-dts.test.ts test/vite-assertion-bytes.test.ts test/vite-plugin-cache-real.test.ts test/vite-plugin-watch.test.ts test/sidecar-orphans.test.ts test/sidecar-lock.test.ts && node test/fixtures/injected-components/cache-e2e.mjs && node test/fixtures/injected-components/dependency-e2e.mjs && node test/fixtures/source-watch/watch-e2e.mjs && node test/fixtures/source-watch/build-watch-e2e.mjs && node test/fixtures/source-watch/component-watch-e2e.mjs", "test:lsp-components": "pnpm run test:vite-components && node test/fixtures/injected-components/lsp-e2e.mjs", "test:e2e": "pnpm run build && playwright test", "test:watch": "vitest", diff --git a/packages/playground/test/fixtures/injected-components/cache-e2e.mjs b/packages/playground/test/fixtures/injected-components/cache-e2e.mjs new file mode 100644 index 00000000000..e842763f1a8 --- /dev/null +++ b/packages/playground/test/fixtures/injected-components/cache-e2e.mjs @@ -0,0 +1,50 @@ +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; + +const vitest = join( + dirname(fileURLToPath(import.meta.resolve("vitest/package.json"))), + "vitest.mjs", +); +for (const layout of ["internal", "external"]) { + const cache = mkdtempSync(join(tmpdir(), "celox-vitest-cache-")); + const client = + layout === "external" + ? mkdtempSync(join(import.meta.dirname, ".cache-client-")) + : undefined; + try { + for (const phase of ["cold", "warm"]) { + const result = spawnSync( + process.execPath, + [ + vitest, + "run", + "--config", + join(import.meta.dirname, "vitest.config.ts"), + "--fsModuleCachePath", + cache, + ], + { + cwd: import.meta.dirname, + env: { ...process.env, CELOX_TEST_EXTERNAL_VITE_ROOT: client ?? "" }, + encoding: "utf8", + timeout: 120_000, + }, + ); + process.stdout.write(result.stdout ?? ""); + process.stderr.write(result.stderr ?? ""); + assert.ifError(result.error); + assert.equal( + result.status, + 0, + `${layout} ${phase} module-cache run failed`, + ); + } + } finally { + rmSync(cache, { recursive: true, force: true }); + if (client) rmSync(client, { recursive: true, force: true }); + } +} diff --git a/packages/playground/test/fixtures/injected-components/vitest.config.ts b/packages/playground/test/fixtures/injected-components/vitest.config.ts index bc89ddd9b39..2fbd5bfe1b5 100644 --- a/packages/playground/test/fixtures/injected-components/vitest.config.ts +++ b/packages/playground/test/fixtures/injected-components/vitest.config.ts @@ -1,6 +1,6 @@ -import celox from "@celox-sim/vite-plugin"; import { resolve } from "node:path"; -import type { Plugin } from "vite"; +import celox from "@celox-sim/vite-plugin"; +import { normalizePath, type Plugin } from "vite"; import { defineConfig } from "vitest/config"; const virtualTbStep: Plugin = { @@ -14,7 +14,7 @@ const virtualTbStep: Plugin = { }; export default defineConfig({ - root: import.meta.dirname, + root: process.env.CELOX_TEST_EXTERNAL_VITE_ROOT || import.meta.dirname, resolve: { alias: { "@fixture/tb-helper": resolve( @@ -26,8 +26,11 @@ export default defineConfig({ plugins: [ virtualTbStep, celox({ + projectRoot: import.meta.dirname, testbenchComponents: "./tb-components.ts", }), ], - test: { include: ["entry.test.ts"] }, + test: { + include: [normalizePath(resolve(import.meta.dirname, "entry.test.ts"))], + }, }); diff --git a/packages/playground/test/vite-plugin-watch.test.ts b/packages/playground/test/vite-plugin-watch.test.ts index e7763c6de41..a42ae2ae090 100644 --- a/packages/playground/test/vite-plugin-watch.test.ts +++ b/packages/playground/test/vite-plugin-watch.test.ts @@ -1,5 +1,11 @@ import { EventEmitter } from "node:events"; -import { mkdtempSync, rmSync, utimesSync, writeFileSync } from "node:fs"; +import { + mkdirSync, + mkdtempSync, + rmSync, + utimesSync, + writeFileSync, +} from "node:fs"; import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; import { normalizePath } from "vite"; @@ -1045,3 +1051,152 @@ test.each([true, false])( expect(watcher.add).not.toHaveBeenCalled(); }, ); + +// Vitest's persistent module cache replays imports as URLs rooted at Vite's +// root, rather than their original paths relative to the importer. +test("cached root-relative imports retain their generated module identity", async () => { + const root = mkdtempSync(join(tmpdir(), "celox-cached-import-")); + roots.push(root); + mkdirSync(join(root, "src")); + writeFileSync(join(root, "src", "Main.veryl"), "module Main {}\n"); + writeFileSync(join(root, "Veryl.toml"), "[project]\nname = 'test'\n"); + const { plugin, context } = await initialize(root); + for (const [url, file] of [ + ["/src/Main.veryl", join(root, "src", "Main.veryl")], + [ + "/src/Main.veryl?dse=preserveAllPorts", + `${join(root, "src", "Main.veryl")}?dse=preserveAllPorts`, + ], + ["/Veryl.toml?celox-project", `${join(root, "Veryl.toml")}?celox-project`], + ["/celox.toml?celox-watch", `${join(root, "celox.toml")}?celox-watch`], + [ + "/src/Main.veryl?celox-watch", + `${join(root, "src", "Main.veryl")}?celox-watch`, + ], + ]) { + const id = (plugin.resolveId as Function)(url, join(root, "index.html")); + expect(id).toBe(normalizePath(file!)); + expect((plugin.load as Function).call(context, id)).toBeTypeOf("string"); + } + expect((plugin.resolveId as Function)("/missing.veryl")).toBeUndefined(); + // Optional configuration is absent, but its canonical watch identity must + // survive both the initial absolute import and the cached root-relative URL. + const optional = `${normalizePath(join(root, "celox.toml"))}?celox-watch`; + expect((plugin.resolveId as Function)(optional)).toBe(optional); + expect((plugin.load as Function).call(context, optional)).toBe("export {};"); + expect(context.addWatchFile).not.toHaveBeenCalledWith( + normalizePath(join(root, "celox.toml")), + ); +}); + +// A project outside Vite's root is replayed through the /@fs/ URL namespace. +test("cached external project imports retain their generated module identity", async () => { + const root = mkdtempSync(join(tmpdir(), "celox-external-cache-")); + const client = mkdtempSync(join(tmpdir(), "celox-external-client-")); + roots.push(root, client); + writeFileSync(join(root, "Main.veryl"), "module Main {}\n"); + writeFileSync(join(root, "Veryl.toml"), "[project]\nname = 'test'\n"); + const plugin = celox({ projectRoot: root }); + const context = { addWatchFile: vi.fn(), warn: vi.fn() }; + await (plugin.configResolved as Function)({ root: client }); + await (plugin.buildStart as Function).call(context); + for (const query of ["", "?dse=preserveAllPorts", "?celox-watch"]) { + const file = normalizePath(join(root, "Main.veryl")) + query; + const id = (plugin.resolveId as Function)( + `/@fs/${file.replace(/^\//, "")}`, + join(client, "index.html"), + ); + expect(id).toBe(file); + expect((plugin.load as Function).call(context, id)).toBeTypeOf("string"); + } + const project = `${normalizePath(join(root, "Veryl.toml"))}?celox-project`; + const id = (plugin.resolveId as Function)( + `/@fs/${project.replace(/^\//, "")}`, + ); + expect(id).toBe(project); + expect((plugin.load as Function).call(context, id)).toBeTypeOf("string"); +}); + +// Both the host-absolute and Vite-root-relative paths exist. Their existence +// alone must not let an unrelated host file take over a cached project URL. +test("cached URLs prefer the project over colliding host paths", async () => { + const client = mkdtempSync(join(tmpdir(), "celox-collision-client-")); + const host = mkdtempSync(join(tmpdir(), "celox-collision-host-")); + roots.push(client, host); + const urlRoot = normalizePath(host).replace(/^[A-Z]:/i, ""); + const project = join(client, urlRoot.replace(/^\//, "")); + mkdirSync(project, { recursive: true }); + for (const dir of [host, project]) { + writeFileSync(join(dir, "Main.veryl"), "module Main {}\n"); + writeFileSync(join(dir, "Veryl.toml"), "[project]\nname = 'test'\n"); + } + const plugin = celox({ projectRoot: project }); + const context = { addWatchFile: vi.fn(), warn: vi.fn() }; + await (plugin.configResolved as Function)({ root: client }); + await (plugin.buildStart as Function).call(context); + for (const [name, query] of [ + ["Main.veryl", ""], + ["Main.veryl", "?dse=preserveAllPorts"], + ["Main.veryl", "?celox-watch"], + ["Veryl.toml", "?celox-project"], + ]) { + const file = normalizePath(join(project, name!)) + query; + const url = `${urlRoot}/${name}${query}`; + const id = (plugin.resolveId as Function)(url, join(client, "index.html")); + expect(id).toBe(file); + expect((plugin.load as Function).call(context, id)).toBeTypeOf("string"); + } + + // Canonical absolute project IDs must stay stable even if their root-relative + // lookalikes also exist. Explicit /@fs/ URLs retain their absolute meaning. + const mirror = join( + client, + normalizePath(project) + .replace(/^[A-Z]:/i, "") + .replace(/^\//, ""), + ); + mkdirSync(mirror, { recursive: true }); + writeFileSync(join(mirror, "Main.veryl"), "module Main {}\n"); + writeFileSync(join(mirror, "Veryl.toml"), "[project]\nname = 'other'\n"); + for (const name of ["Main.veryl", "Veryl.toml?celox-project"]) { + const file = normalizePath(join(project, name)); + expect((plugin.resolveId as Function)(file)).toBe(file); + } + const hostFile = normalizePath(join(host, "Main.veryl")); + expect( + (plugin.resolveId as Function)(`/@fs/${hostFile.replace(/^\//, "")}`), + ).toBe(hostFile); +}); + +test.each([false, true])( + "cached prefix-shaped URLs fall back to the Vite root (filesystem root=%s)", + async (filesystemRoot) => { + const project = mkdtempSync(join(tmpdir(), "celox-prefix-project-")); + roots.push(project); + const client = join(project, "client"); + const url = filesystemRoot + ? `/celox-prefix-${project.split(/[\\/]/).at(-1)}/Main.veryl` + : normalizePath(join(project, "Main.veryl")).replace(/^[A-Z]:/i, ""); + const rooted = join(client, url.replace(/^[A-Z]:/i, "").replace(/^\//, "")); + mkdirSync(dirname(rooted), { recursive: true }); + writeFileSync(rooted, "module Main {}\n"); + const plugin = celox({ projectRoot: filesystemRoot ? "/" : project }); + // Resolution does not need buildStart; do not generate sidecars at '/'. + await (plugin.configResolved as Function)({ root: client }); + for (const query of ["", "?dse=preserveAllPorts", "?celox-watch"]) { + expect((plugin.resolveId as Function)(url + query)).toBe( + normalizePath(rooted) + query, + ); + } + expect( + (plugin.resolveId as Function)(`/@fs/${url.replace(/^\//, "")}`), + ).toBeUndefined(); + if (!filesystemRoot) { + // Once the canonical project file exists, keep that identity even though + // the cached-root lookalike exists too. + writeFileSync(join(project, "Main.veryl"), "module Main {}\n"); + const canonical = normalizePath(join(project, "Main.veryl")); + expect((plugin.resolveId as Function)(canonical)).toBe(canonical); + } + }, +); diff --git a/packages/vite-plugin/src/index.ts b/packages/vite-plugin/src/index.ts index ad26a777148..888fca7ee04 100644 --- a/packages/vite-plugin/src/index.ts +++ b/packages/vite-plugin/src/index.ts @@ -411,16 +411,37 @@ export default function celoxPlugin(options?: CeloxPluginOptions): Plugin { // Split off query string (e.g. "?dse=preserveAllPorts") const [rawPath, queryStr] = source.split("?", 2); if (source.startsWith("\0")) return; - if (queryStr === PROJECT_QUERY || queryStr === WATCH_QUERY) { - const id = normalizePath(source); - resolvedIds.add(id); - return id; - } - if (!rawPath!.endsWith(".veryl")) return; + const generatedQuery = + queryStr === PROJECT_QUERY || queryStr === WATCH_QUERY; + if (!generatedQuery && !rawPath!.endsWith(".veryl")) return; // Resolve to absolute path let absPath: string; - if (isAbsolute(rawPath!)) { + if (rawPath!.startsWith("/@fs/")) { + // Vite uses /@fs/ for files outside its root. Keep POSIX roots + // and Windows drive letters when decoding that URL namespace. + const file = normalizePath(rawPath!.slice("/@fs/".length)); + absPath = + file.startsWith("/") || /^[A-Z]:/i.test(file) ? file : `/${file}`; + } else if ( + rawPath!.startsWith("/") && + (!normalizePath(rawPath!).startsWith(projectPrefix) || + !existsSync(rawPath!)) + ) { + // Keep existing canonical project files, but a matching prefix alone + // does not make a cached URL absolute. Root other URLs at Vite's + // root even when an unrelated host file exists. + const rooted = resolve(viteConfig.root, `.${rawPath}`); + // Optional configuration still has a canonical watch identity when + // absent. Returning its cached URL (e.g. /celox.toml) would lose the + // project directory and, on Windows, the drive letter. + const optionalConfig = + queryStr === WATCH_QUERY && + CONFIG_FILES.some( + (name) => projectFile(name) === normalizePath(rooted), + ); + absPath = existsSync(rooted) || optionalConfig ? rooted : rawPath!; + } else if (isAbsolute(rawPath!)) { absPath = rawPath!; } else if (importer) { absPath = resolve(dirname(importer.split("?", 1)[0]!), rawPath!); @@ -430,8 +451,8 @@ export default function celoxPlugin(options?: CeloxPluginOptions): Plugin { absPath = normalizePath(absPath); - // Only handle .veryl files that exist - if (!existsSync(absPath)) return; + // Generated watch modules may refer to optional configuration files. + if (!generatedQuery && !existsSync(absPath)) return; // Preserve the real file identity so Vite/Vitest can trace changes. const id = absPath + (queryStr ? `?${queryStr}` : "");