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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions .changepacks/changepack_log_remove_deleted_files.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"changes": {
"bindings/devup-ui-binding/package.json": "Patch",
"bindings/devup-ui-wasm/package.json": "Patch",
"packages/vite-plugin/package.json": "Patch",
"packages/webpack-plugin/package.json": "Patch",
"packages/rsbuild-plugin/package.json": "Patch",
"packages/next-plugin/package.json": "Patch"
},
"note": "A source file deleted or renamed in watch mode or the dev server no longer leaves its styles behind: its `globalCss`, its own stylesheet and the class names handed out in it are dropped, and it leaves the bucket it collapsed into. The engine gains `removeFile(filename)` (native and WASM), which Vite calls on a `delete` watch change, webpack and Rsbuild on the removed files of a watch run (webpack watch mode also saves the pruned state), and the Next.js Turbopack coordinator when an edited file is extracted again. Atoms in a stylesheet other files share stay, as nothing records which file added them; they style nothing once no module uses them",
"date": "2026-11-15T00:00:00.000Z"
}
1 change: 1 addition & 0 deletions bindings/argument-validation.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ module.exports = function createBoundary() {
importSheet: 'sheet_object:sheet',
registerShorthands: 'shorthands:shorthands',
registerTheme: 'theme_object:theme',
removeFile: 'filename:s',
reserveClassSlots:
'rows:rows _package:s single_css:b import_main_css_in_code:b _import_main_css_in_css:b import_aliases:aliases',
seedFileMap: 'files:a',
Expand Down
4 changes: 2 additions & 2 deletions bindings/devup-ui-binding/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

Synchronous native build-time compiler for Node.js and Bun. Both
`require('@devup-ui/binding')` and named ESM imports expose exactly the existing
29 compiler names, with identical function/class identities and no default init.
30 compiler names, with identical function/class identities and no default init.
Authored CommonJS/ESM declarations are included; no WASM dependency is required.

The private loader selects one optional platform sibling: Windows MSVC, macOS,
Expand Down Expand Up @@ -96,4 +96,4 @@ The decoder is private and target-bounded: unused Serde hints use trait forwardi

Malformed-enum error paths follow shipped serde-wasm-bindgen 0.6.5: Object.entries result length is read and coerced once for the check, then read and coerced again for the invalid-length diagnostic when the first length is not one, before any index read. The second value supplies the diagnostic; errors thrown by its getter or coercion propagate unchanged. Valid enums retain one length read.

The shared native/WASM boundary validates ordinary calls at 45 argument positions in 18 functions: malformed inputs throw a genuine `TypeError` naming the function, parameter and required type before state mutation. Preflight defaults the entire alias map on schema failure (after diagnostics) or a caught iterator-import failure whose `new Error(String(error))` conversion succeeds. Raw access failures and conversion faults escape unchanged before resolver selection; conversion runs once with the pending failure cleared, so reentry is isolated and resolver changes take effect before the outer core starts. Extraction and reservation remain strict. For example, `setPrefix(false)` throws `setPrefix(): argument prefix must be a string, null or undefined`; string/nullish prefixes remain supported. Extraction wrappers retain the measured metadata, receiver, extra-argument and apply/construct policy; `seedFileMap` validates and copies the caller's array before engine entry without rereading its indices. Same-revision Node/Bun identity, 267-case invalid-input, 73-exception preservation and seed-safety gates cover these contracts, not optimized shipping-native performance or real Node-host Linux Rust/authored-JS 100% coverage, which remain public-delivery gates.
The shared native/WASM boundary validates ordinary calls at 46 argument positions in 19 functions: malformed inputs throw a genuine `TypeError` naming the function, parameter and required type before state mutation. Preflight defaults the entire alias map on schema failure (after diagnostics) or a caught iterator-import failure whose `new Error(String(error))` conversion succeeds. Raw access failures and conversion faults escape unchanged before resolver selection; conversion runs once with the pending failure cleared, so reentry is isolated and resolver changes take effect before the outer core starts. Extraction and reservation remain strict. For example, `setPrefix(false)` throws `setPrefix(): argument prefix must be a string, null or undefined`; string/nullish prefixes remain supported. Extraction wrappers retain the measured metadata, receiver, extra-argument and apply/construct policy; `seedFileMap` validates and copies the caller's array before engine entry without rereading its indices. Same-revision Node/Bun identity, 272-case invalid-input, 73-exception preservation and seed-safety gates cover these contracts, not optimized shipping-native performance or real Node-host Linux Rust/authored-JS 100% coverage, which remain public-delivery gates.
1 change: 1 addition & 0 deletions bindings/devup-ui-binding/adapter.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,7 @@ exports.createBinding = function createBinding(raw) {
isDebug: raw.isDebug,
registerShorthands: (value) => call(raw.registerShorthands, value),
registerTheme: (value) => call(raw.registerTheme, value),
removeFile: (filename) => raw.removeFile(filename),
reserveClassSlots: (rows, pkg, single, code, css, aliases) =>
call(raw.reserve, [rows, pkg, single, code, css, aliases]),
resetBuildState: () => raw.reset(false),
Expand Down
4 changes: 3 additions & 1 deletion bindings/devup-ui-binding/index.d.cts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export class Output {
readonly updatedBaseStyle: boolean
}

// Positional signatures intentionally match the existing 29-name compiler ABI.
// Positional signatures intentionally match the existing 30-name compiler ABI.
export function codeExtract(
filename: string,
code: string,
Expand Down Expand Up @@ -65,6 +65,8 @@ export function importSheet(value: unknown): void
export function isDebug(): boolean
export function registerShorthands(value: unknown): void
export function registerTheme(value: unknown): void
/** Forget a deleted source file's own styles; whether the sheet changed. */
export function removeFile(filename: string): boolean
export function reserveClassSlots(
rows: unknown,
packageName: string,
Expand Down
1 change: 1 addition & 0 deletions bindings/devup-ui-binding/index.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ export const {
isDebug,
registerShorthands,
registerTheme,
removeFile,
reserveClassSlots,
resetBuildState,
resetStateForTesting,
Expand Down
5 changes: 5 additions & 0 deletions bindings/devup-ui-binding/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,11 @@ pub fn set_atom_hoist(value: Option<u32>) {
pub fn get_css(value: Option<u32>, import_main: bool) -> String {
core::get_css(value.map(widen_index), import_main)
}
/// Forget a deleted source file, returning whether the sheet changed.
#[napi]
pub fn remove_file(filename: String) -> bool {
core::remove_file_internal(&filename)
}
/// Seed the array-like wrapper's copied strings, not arbitrary JS iterables.
#[napi]
pub fn seed_file_map(files: Vec<String>) {
Expand Down
1 change: 1 addition & 0 deletions bindings/devup-ui-wasm/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ Everything is exported from `pkg/index.js` (types in `pkg/index.d.ts`).
| `codeExtractWithoutSourceMap(...)` | The same without the source map. |
| `hasDevupUI(filename, code, package)` | Whether the file imports Devup UI, so a plugin can skip the rest. |
| `getCss(fileNum, importMainCss)` | The stylesheet collected so far: the whole sheet for `null`, one file's for its number. |
| `removeFile(filename)` | Forgets a deleted source file: its global CSS, its own stylesheet and the class names handed out in it. Returns whether the sheet changed. |
| `registerTheme(theme)`, `registerShorthands(shorthands)` | Registers the `devup.json` theme and the custom shorthand props before extracting. |
| `getThemeInterface(package, color, typography, length, shadows, theme)` | The `.d.ts` text that types the registered theme. |
| `getDefaultTheme()` | The theme variant that applies without `data-theme`. |
Expand Down
6 changes: 3 additions & 3 deletions bindings/devup-ui-wasm/script.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,9 @@ for (const operation of ['begin', 'end', 'error', 'fail'])
)
assert.equal([...source.matchAll(/__devupBoundary/g)].length, 4)
const names = [...source.matchAll(/^exports\.(\w+) = \1;/gm)]
assert.equal(names.length, 29)
assert.equal(new Set(names.map((match) => match[1])).size, 29)
assert.equal([...source.matchAll(/^exports\./gm)].length, 29)
assert.equal(names.length, 30)
assert.equal(new Set(names.map((match) => match[1])).size, 30)
assert.equal([...source.matchAll(/^exports\./gm)].length, 30)
assert.equal(source.includes('module.exports'), false)
for (const name of ['codeExtract', 'codeExtractWithoutSourceMap']) {
const signatures = [
Expand Down
32 changes: 32 additions & 0 deletions bindings/devup-ui-wasm/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -295,6 +295,16 @@ pub fn seed_file_map(files: Vec<String>) {
binding_core::seed_file_map(&files);
}

/// Forget a source file that was deleted or renamed away.
///
/// Its global CSS, its own bucket and the class names handed out in it go,
/// and it no longer collapses into another bucket. Returns whether the sheet
/// changed, so the caller knows to serve its CSS again.
#[wasm_bindgen(js_name = "removeFile")]
pub fn remove_file(filename: &str) -> bool {
binding_core::remove_file_internal(filename)
}

/// Forget everything one build left in the engine.
///
/// That is names, numbers, styles, buckets, routes, the prefix, atom hoisting
Expand Down Expand Up @@ -1719,6 +1729,28 @@ mod tests {
assert!(json_str.starts_with('{') || json_str.starts_with("[]"));
}

#[test]
#[serial]
fn remove_file_reports_whether_the_sheet_changed() {
let _state = TestStateGuard::new();
// Given: a file with its own bucket.
let output = code_extract_internal(
"removed.tsx",
"import { Box } from '@devup-ui/react'; export const view = <Box bg=\"red\" />;",
"@devup-ui/react",
"df".to_string(),
false,
false,
false,
HashMap::new(),
)
.unwrap();
assert!(output.css.is_some());
// When / Then: the first removal drops it, a second finds nothing.
assert!(remove_file("removed.tsx"));
assert!(!remove_file("removed.tsx"));
}

#[test]
#[serial]
fn test_exported_maps_are_canonical_json() {
Expand Down
9 changes: 9 additions & 0 deletions e2e/binding/corpus/state.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,15 @@ add('reservation-malformed-second-row-arity-nonmutation', (h) => {
h.call('reserveClassSlots', value, pkg, false, false, false, {})
h.call('reserveClassSlots', rows, pkg, false, false, false, { bad: 7 })
})
add('remove-file-drops-its-own-styles', (h) => {
h.call('importCanonicalMap', { 'src/child.tsx': 'src/root.tsx' })
h.extract(source, { single: false })
h.extract(box('color="blue"'), { filename: 'src/root.tsx', single: false })
h.extract(box('color="teal"'), { filename: 'src/child.tsx', single: false })
for (const filename of ['src/root.tsx', file, file, 'src/child.tsx'])
h.call('removeFile', filename)
h.call('removeFile', 'src/root.tsx')
})
add('four-raw-states-explicit-import-roundtrip', (h) => {
h.call('registerTheme', theme)
h.call('importCanonicalMap', { [file]: 'src/root.tsx' })
Expand Down
6 changes: 3 additions & 3 deletions e2e/binding/host.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ save('provenance.json', {
scenarios: corpus.map((c) => c.name),
})
const names =
'Output codeExtract codeExtractWithoutSourceMap exportCanonicalMap exportClassMap exportFileMap exportSheet getCss getDefaultTheme getPrefix getThemeInterface getUnreservedClassSlotCount hasDevupUI importCanonicalMap importClassMap importFileMap importFileRoutes importSheet isDebug registerShorthands registerTheme reserveClassSlots resetBuildState resetStateForTesting seedFileMap setAtomHoist setDebug setModuleResolver setPrefix'.split(
'Output codeExtract codeExtractWithoutSourceMap exportCanonicalMap exportClassMap exportFileMap exportSheet getCss getDefaultTheme getPrefix getThemeInterface getUnreservedClassSlotCount hasDevupUI importCanonicalMap importClassMap importFileMap importFileRoutes importSheet isDebug registerShorthands registerTheme removeFile reserveClassSlots resetBuildState resetStateForTesting seedFileMap setAtomHoist setDebug setModuleResolver setPrefix'.split(
' ',
)
const abi = {
Expand Down Expand Up @@ -199,8 +199,8 @@ const h = {
)
},
}
assert.equal(corpus.length, 25)
assert.equal(new Set(corpus.map((c) => c.name)).size, 25)
assert.equal(corpus.length, 26)
assert.equal(new Set(corpus.map((c) => c.name)).size, 26)
h.note('public-error-inventory', runDiagnostics(w))
for (const test of corpus) {
scenario = test.name
Expand Down
2 changes: 1 addition & 1 deletion e2e/binding/package/consumer.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ export async function consume(options) {
]
.map((match) => match[1])
.sort()
assert.equal(names.length, 29)
assert.equal(names.length, 30)
for (const manager of ['npm', 'bun']) {
for (const omit of [false, true]) {
const startRequest = server.requests.length
Expand Down
5 changes: 3 additions & 2 deletions e2e/binding/validation-cases.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ export const positions = [
['importSheet', 'sheet_object:sheet', () => [{}]],
['registerShorthands', 'shorthands:shorthands', () => [{}]],
['registerTheme', 'theme_object:theme', () => [{}]],
['removeFile', 'filename:s', () => ['src/new.tsx']],
[
'reserveClassSlots',
'rows:rows _package:s single_css:b import_main_css_in_code:b _import_main_css_in_css:b import_aliases:aliases',
Expand Down Expand Up @@ -153,6 +154,6 @@ export const cases = positions.flatMap((position) =>
.map((good, index) => (index === position.index ? value : good)),
})),
)
assert.equal(positions.length, 45)
assert.equal(new Set(positions.map((p) => p.fn)).size, 18)
assert.equal(positions.length, 46)
assert.equal(new Set(positions.map((p) => p.fn)).size, 19)
assert.equal(new Set(cases.map((c) => c.id)).size, cases.length)
13 changes: 13 additions & 0 deletions libs/binding/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,19 @@ pub fn seed_file_map(files: &[String]) {
css::file_map::seed_file_numbers(files);
}

/// Forget a deleted source file: its global CSS, its own bucket with the class
/// names handed out in it, and the bucket it collapsed into.
///
/// File numbers stay, as they are handed out by count and a freed one would be
/// handed out twice. Returns whether the sheet changed.
pub fn remove_file_internal(filename: &str) -> bool {
let (bucket, alone) = css::file_map::remove_bucket_membership(filename);
if alone {
css::class_map::remove_class_scope(&bucket);
}
with_style_sheet_mut(|sheet| sheet.rm_file(filename, &bucket, alone))
}

/// Clear production build state, retaining theme registries, shorthands and debug.
/// The host adapter separately clears its resolver handle.
pub fn reset_build_state_internal() {
Expand Down
76 changes: 76 additions & 0 deletions libs/binding/tests/remove_file.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
use devup_ui_binding_core::{
ExtractionMode, SourceMapMode, code_extract, export_canonical_map_internal,
export_class_map_internal, get_css, import_canonical_map_internal, remove_file_internal,
reset_state_internal,
};
use extractor::ExtractOption;

fn extract(filename: &str, code: &str) -> Result<(), String> {
code_extract(
(filename, code),
ExtractOption {
package: "@devup-ui/react".to_string(),
css_dir: "df".to_string(),
..ExtractOption::default()
},
ExtractionMode {
source_map: SourceMapMode::Skip,
resolver: None,
resolver_check: None,
import_main_css_in_css: false,
},
)
.map(drop)
}

fn file_num(filename: &str) -> usize {
css::file_map::get_file_num_by_filename(filename)
}

#[test]
fn removed_files_leave_no_styles_of_their_own() -> Result<(), String> {
// Given: a file with its own bucket and global CSS, beside another file.
reset_state_internal(|| {});
extract(
"a.tsx",
"import { Box, globalCss } from '@devup-ui/react'; globalCss({ body: { margin: 0 } }); export const view = <Box bg=\"red\" />;",
)?;
extract(
"b.tsx",
"import { Box } from '@devup-ui/react'; export const view = <Box bg=\"blue\" />;",
)?;
assert!(get_css(None, false).contains("margin:0"));
assert!(get_css(Some(file_num("a.tsx")), false).contains("red"));

// When: the first file is deleted.
assert!(remove_file_internal("a.tsx"));

// Then: its global CSS, bucket and class names are gone; the other file stays.
assert!(!get_css(None, false).contains("margin:0"));
assert!(!get_css(Some(file_num("a.tsx")), false).contains("red"));
assert!(get_css(Some(file_num("b.tsx")), false).contains("blue"));
assert!(!export_class_map_internal()?.contains("a.tsx"));
assert!(!remove_file_internal("a.tsx"));

// Given: a file collapsed into the remaining file's bucket.
import_canonical_map_internal([("c.tsx".to_string(), "b.tsx".to_string())].into());
extract(
"c.tsx",
"import { Box } from '@devup-ui/react'; export const view = <Box bg=\"green\" />;",
)?;

// When: the bucket's root goes first, the collapsed file still shares it.
assert!(!remove_file_internal("b.tsx"));
assert!(get_css(Some(file_num("b.tsx")), false).contains("green"));

// When: the collapsed file goes too, it leaves the bucket.
assert!(!remove_file_internal("c.tsx"));
assert_eq!(export_canonical_map_internal()?, "{}");

// Then: the bucket belongs to no other file and goes with its root.
assert!(remove_file_internal("b.tsx"));
assert!(!get_css(Some(file_num("b.tsx")), false).contains("green"));
// Names in the shared scope stay: other files may hand out the same ones.
assert!(!export_class_map_internal()?.contains("b.tsx"));
Ok(())
}
5 changes: 5 additions & 0 deletions libs/css/src/class_map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,11 @@ pub fn get_class_map() -> HashMap<String, HashMap<String, usize>> {
with_class_map(Clone::clone)
}

/// Forget the class names handed out in one bucket.
pub fn remove_class_scope(scope: &str) {
with_class_map_mut(|map| map.remove(scope));
}

#[cfg(test)]
mod tests {
use serial_test::serial;
Expand Down
11 changes: 11 additions & 0 deletions libs/css/src/file_map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,17 @@ pub fn get_canonical_map() -> std::collections::HashMap<String, String> {
with_canonical_map(Clone::clone)
}

/// Forget the bucket `filename` collapses into, returning that bucket and
/// whether it is the file's own one with no other file collapsed into it.
#[must_use]
pub fn remove_bucket_membership(filename: &str) -> (String, bool) {
with_canonical_map_mut(|map| {
let bucket = map.remove(filename).unwrap_or_else(|| filename.to_string());
let alone = bucket == filename && !map.values().any(|root| root == filename);
(bucket, alone)
})
}

/// Resolve a filename to its bucket-root via `CANONICAL_MAP`, or identity when absent.
#[must_use]
pub fn canonical(filename: &str) -> String {
Expand Down
Loading
Loading