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
8 changes: 8 additions & 0 deletions .changepacks/changepack_log_engine_sessions_bindings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"changes": {
"bindings/devup-ui-wasm/package.json": "Patch",
"bindings/devup-ui-binding/package.json": "Patch"
},
"note": "New `createSession()`, `selectSession(id)` and `dropSession(id)` exports on the WASM and native engines: a session is an engine state of its own (numbering, sheet, theme, settings and module resolver), and every call works on the selected one. Session 0 is selected from the start. `selectSession` and `dropSession` throw a `TypeError` for an id that is not an unsigned 32-bit integer, and an `Error` for an unknown session or for dropping session 0",
"date": "2026-11-15T00:00:00.000Z"
}
8 changes: 8 additions & 0 deletions .changepacks/changepack_log_engine_sessions_state.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"changes": {
"bindings/devup-ui-wasm/package.json": "Patch",
"bindings/devup-ui-binding/package.json": "Patch"
},
"note": "The engine keeps its state per engine session: class and file numbering, routes, prefix, debug, atom hoisting, slot reservation, shorthands, theme tokens, Tailwind definitions, the stylesheet, the stylesheet caches and the module resolver move together when a session is switched. Session 0 is the only one until a host creates another, so a single app sees no change",
"date": "2026-11-15T00:00:00.000Z"
}
4 changes: 4 additions & 0 deletions bindings/argument-validation.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ module.exports = function createBoundary() {
const descriptors = {
codeExtract: extraction,
codeExtractWithoutSourceMap: extraction,
dropSession: 'id:u',
getCss: 'file_num:n import_main_css:b',
getThemeInterface:
'package_name:s color_interface_name:s typography_interface_name:s length_interface_name:s shadows_interface_name:s theme_interface_name:s',
Expand All @@ -20,6 +21,7 @@ module.exports = function createBoundary() {
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',
selectSession: 'id:u',
setAtomHoist: 'threshold:n',
setDebug: 'debug:b',
setModuleResolver: 'resolver:f',
Expand All @@ -32,6 +34,7 @@ module.exports = function createBoundary() {
p: 'a string, null or undefined',
f: 'a function, null or undefined',
a: 'an array of strings',
u: 'a session id',
aliases: 'an alias mapping',
canonical: 'a canonical mapping',
class: 'a nested class-index mapping',
Expand All @@ -51,6 +54,7 @@ module.exports = function createBoundary() {
p: (value) => value == null || typeof value === 'string',
f: (value) => value == null || typeof value === 'function',
a: Array.isArray,
u: (value) => Number.isInteger(value) && value >= 0 && value <= 0xffffffff,
}
let frame
const fail = (slot) => {
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
30 compiler names, with identical function/class identities and no default init.
33 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 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.
The shared native/WASM boundary validates ordinary calls at 48 argument positions in 21 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, 288-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.
3 changes: 3 additions & 0 deletions bindings/devup-ui-binding/adapter.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,8 @@ exports.createBinding = function createBinding(raw) {
Output: raw.Output,
codeExtract,
codeExtractWithoutSourceMap,
createSession: () => raw.createSession(),
dropSession: (id) => raw.dropSession(id),
exportCanonicalMap: raw.exportCanonicalMap,
exportClassMap: raw.exportClassMap,
exportFileMap: raw.exportFileMap,
Expand All @@ -108,6 +110,7 @@ exports.createBinding = function createBinding(raw) {
resetBuildState: () => raw.reset(false),
resetStateForTesting: () => raw.reset(true),
seedFileMap,
selectSession: (id) => raw.selectSession(id),
setAtomHoist: (value) => raw.setAtomHoist(index(value)),
setDebug: (value) => raw.setDebug(value),
setModuleResolver,
Expand Down
8 changes: 7 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 30-name compiler ABI.
// Positional signatures intentionally match the existing 33-name compiler ABI.
export function codeExtract(
filename: string,
code: string,
Expand All @@ -32,6 +32,10 @@ export function codeExtractWithoutSourceMap(
importMainCssInCss: boolean,
importAliases: unknown,
): Output
/** Create an engine session with a clean state; select it before each call. */
export function createSession(): number
/** Drop a session and its state; dropping the live one makes session 0 live. */
export function dropSession(id: number): boolean
export function exportCanonicalMap(): string
export function exportClassMap(): string
export function exportFileMap(): string
Expand Down Expand Up @@ -78,6 +82,8 @@ export function reserveClassSlots(
export function resetBuildState(): void
export function resetStateForTesting(): void
export function seedFileMap(files: string[]): void
/** Make a session live: later calls work on its state until another is selected. */
export function selectSession(id: number): void
export function setAtomHoist(threshold?: number | null): void
export function setDebug(debug: boolean): void
export function setModuleResolver(
Expand Down
3 changes: 3 additions & 0 deletions bindings/devup-ui-binding/index.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ export const {
Output,
codeExtract,
codeExtractWithoutSourceMap,
createSession,
dropSession,
exportCanonicalMap,
exportClassMap,
exportFileMap,
Expand All @@ -27,6 +29,7 @@ export const {
resetBuildState,
resetStateForTesting,
seedFileMap,
selectSession,
setAtomHoist,
setDebug,
setModuleResolver,
Expand Down
34 changes: 28 additions & 6 deletions bindings/devup-ui-binding/src/host.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,20 +16,23 @@ pub struct Resolved {
pub code: String,
}
type Resolver = FunctionRef<FnArgs<(String, String)>, Option<Either<String, Resolved>>>;
struct State(Option<Rc<Resolver>>);
/// The resolver each engine session set in this environment
struct State(core::PerSession<Rc<Resolver>>);

/// Initialize environment-local ownership without overwriting existing state.
#[napi]
pub fn init(env: Env) -> Result<()> {
if env.get_instance_data::<State>()?.is_none() {
env.set_instance_data(State(None), (), |context| drop(context.value))?;
env.set_instance_data(State(core::PerSession::new()), (), |context| {
drop(context.value);
})?;
}
Ok(())
}
/// Replace the owned synchronous resolver in the current environment only.
#[napi]
pub fn set_resolver(env: Env, resolver: Option<Resolver>) -> Result<()> {
state(&env)?.0 = resolver.map(Rc::new);
state(&env)?.0.set_live(resolver.map(Rc::new));
Ok(())
}
fn state(env: &Env) -> Result<&'static mut State> {
Expand All @@ -41,13 +44,32 @@ fn state(env: &Env) -> Result<&'static mut State> {
pub fn reset(env: Env, full: bool) -> Result<()> {
let state = state(&env)?;
if full {
core::reset_state_internal(|| state.0 = None);
core::reset_state_internal(|| state.0 = core::PerSession::new());
} else {
core::reset_build_state_internal();
state.0 = None;
state.0.set_live(None);
}
Ok(())
}
/// Create an engine session with a clean state and return its id.
#[napi]
pub fn create_session() -> u32 {
core::create_session()
}
/// Make session `id` live until another is selected.
#[napi]
pub fn select_session(env: Env, id: u32) -> Result<()> {
core::select_session(id)
.map(drop)
.map_err(|error| binding_error(env, error))
}
/// Drop session `id` with its state and this environment's resolver for it.
#[napi]
pub fn drop_session(env: Env, id: u32) -> Result<bool> {
let dropped = core::drop_session(id).map_err(|error| binding_error(env, error))?;
state(&env)?.0.remove(id);
Ok(dropped)
}
fn with_resolver<T>(
env: Env,
diagnostics: core::ResolverState,
Expand All @@ -56,7 +78,7 @@ fn with_resolver<T>(
&dyn Fn() -> std::result::Result<(), String>,
) -> Result<T>,
) -> Result<T> {
let current = state(&env)?.0.clone();
let current = state(&env)?.0.live();
let diagnostics = Rc::new(RefCell::new(diagnostics));
let failure = Rc::new(RefCell::new(None));
let resolver = current.map(|current| {
Expand Down
5 changes: 4 additions & 1 deletion bindings/devup-ui-binding/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@ mod host;
mod output;
mod value;

pub use host::{Resolved, extract, has_devup_ui, init, reserve, reset, set_resolver};
pub use host::{
Resolved, create_session, drop_session, extract, has_devup_ui, init, reserve, reset,
select_session, set_resolver,
};
pub use output::NativeOutput;

use de::Wasm32Index;
Expand Down
10 changes: 10 additions & 0 deletions bindings/devup-ui-wasm/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,16 @@ unwind. Binding tests compose these with sheet/resolver snapshots. Keep a named
guard on its creating thread and retain `#[serial]`: guards clean up but do not
serialize concurrent tests. Cleanup does not run for panic=abort.

## Sessions

`createSession()` returns the id of a new engine session with a clean state, and
`selectSession(id)` makes it live: every later call reads and changes that
session's state, resolver included, until another is selected. Session 0 is
live from the start, so a single app needs neither. Two apps in one process
each select their own session before each call. `dropSession(id)` forgets a
session (dropping the live one makes session 0 live), and the full test reset
forgets every session but 0.

## Errors

A source the build cannot compile makes `codeExtract` throw an `Error`. Its
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 @@ -50,9 +50,9 @@ types = types.replace(hookType, '')
assert.equal(types.includes('install_panic_hook'), false)
writeFileSync('pkg/index.d.ts', types, 'utf8')
const names = [...source.matchAll(/^exports\.(\w+) = \1;/gm)]
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(names.length, 33)
assert.equal(new Set(names.map((match) => match[1])).size, 33)
assert.equal([...source.matchAll(/^exports\./gm)].length, 33)
assert.equal(source.includes('module.exports'), false)
for (const name of ['codeExtract', 'codeExtractWithoutSourceMap']) {
const signatures = [
Expand Down
63 changes: 59 additions & 4 deletions bindings/devup-ui-wasm/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,9 @@ mod css_output_edge_tests;
mod dynamic_as_sibling_props_tests;

thread_local! {
static MODULE_RESOLVER: RefCell<Option<js_sys::Function>> = const { RefCell::new(None) };
/// The resolver `setModuleResolver` set in each engine session
static MODULE_RESOLVER: RefCell<binding_core::PerSession<js_sys::Function>> =
const { RefCell::new(binding_core::PerSession::new()) };
}

#[cfg(not(tarpaulin_include))]
Expand Down Expand Up @@ -297,6 +299,40 @@ pub fn seed_file_map(files: Vec<String>) {
binding_core::seed_file_map(&files);
}

/// Create an engine session with a clean state and return its id.
///
/// Two apps in one process each keep their own session: select it before
/// every call so the call reads and changes only that app's state. Session 0
/// is live until another is selected.
#[wasm_bindgen(js_name = "createSession")]
#[must_use]
pub fn create_session() -> u32 {
binding_core::create_session()
}

/// Make session `id` live: every later call works on its state until
/// another session is selected.
#[wasm_bindgen(js_name = "selectSession")]
#[cfg(not(tarpaulin_include))]
pub fn select_session(id: u32) -> Result<(), JsValue> {
binding_core::select_session(id).map(drop).map_err(js_error)
}

/// Drop session `id` with its state and resolver (testable without `JsValue`)
pub fn drop_session_internal(id: u32) -> Result<bool, String> {
let dropped = binding_core::drop_session(id)?;
MODULE_RESOLVER.with_borrow_mut(|resolvers| resolvers.remove(id));
Ok(dropped)
}

/// Drop session `id` with its state and module resolver, returning whether
/// it existed. Dropping the live session makes session 0 live.
#[wasm_bindgen(js_name = "dropSession")]
#[cfg(not(tarpaulin_include))]
pub fn drop_session(id: u32) -> Result<bool, JsValue> {
drop_session_internal(id).map_err(js_error)
}

/// 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,
Expand All @@ -314,7 +350,7 @@ pub fn remove_file(filename: &str) -> bool {
/// alone. Theme, shorthands and debug mode are set by every build, and stay.
pub fn reset_build_state_internal() {
binding_core::reset_build_state_internal();
MODULE_RESOLVER.with_borrow_mut(|current| *current = None);
MODULE_RESOLVER.with_borrow_mut(|current| current.set_live(None));
}

#[wasm_bindgen(js_name = "resetBuildState")]
Expand Down Expand Up @@ -476,7 +512,7 @@ fn code_extract_internal_impl(
#[wasm_bindgen(js_name = "setModuleResolver")]
#[cfg(not(tarpaulin_include))]
pub fn set_module_resolver(resolver: Option<js_sys::Function>) {
MODULE_RESOLVER.with_borrow_mut(|current| *current = resolver);
MODULE_RESOLVER.with_borrow_mut(|current| current.set_live(resolver));
}

#[cfg(not(tarpaulin_include))]
Expand Down Expand Up @@ -537,7 +573,7 @@ fn call_module_resolver(
/// The resolver set by `setModuleResolver`, if any
#[cfg(not(tarpaulin_include))]
fn resolver_from_js(state: std::rc::Rc<RefCell<ResolverState>>) -> Option<Box<ModuleResolver>> {
let resolver = MODULE_RESOLVER.with_borrow(Clone::clone)?;
let resolver = MODULE_RESOLVER.with_borrow(binding_core::PerSession::live)?;
Some(Box::new(move |specifier: &str, importer: &str| {
let request = state.borrow().request(specifier, importer)?;
call_module_resolver(&resolver, request, &state)
Expand Down Expand Up @@ -1727,6 +1763,25 @@ mod tests {
assert!(json_str.starts_with('{') || json_str.starts_with("[]"));
}

#[test]
#[serial]
fn sessions_keep_their_own_prefix_until_dropped() {
let _state = TestStateGuard::new();
// Given: a second session with its own prefix
let session = create_session();
assert_eq!(binding_core::select_session(session), Ok(0));
set_prefix(Some("app-".into()));
// When / Then: session 0 keeps its own, and the dropped session goes
assert_eq!(binding_core::select_session(0), Ok(session));
assert_eq!(get_prefix(), None);
assert_eq!(
drop_session_internal(0),
Err("engine session 0 cannot be dropped".to_string())
);
assert_eq!(drop_session_internal(session), Ok(true));
assert_eq!(drop_session_internal(session), Ok(false));
}

#[test]
#[serial]
fn remove_file_reports_whether_the_sheet_changed() {
Expand Down
22 changes: 12 additions & 10 deletions bindings/devup-ui-wasm/src/reservation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,16 +37,18 @@ pub fn reserve_class_slots(
import_aliases: import_aliases_from_js(import_aliases, 5)?,
..ExtractOption::default()
};
let resolver = MODULE_RESOLVER.with_borrow(Clone::clone).map(|resolver| {
let state = Rc::new(RefCell::new(ResolverState::default()));
for input in &inputs {
state.borrow_mut().add_source(&input.filename, &input.code);
}
move |specifier: &str, importer: &str| {
let request = state.borrow().request(specifier, importer)?;
call_module_resolver(&resolver, request, &state)
}
});
let resolver = MODULE_RESOLVER
.with_borrow(devup_ui_binding_core::PerSession::live)
.map(|resolver| {
let state = Rc::new(RefCell::new(ResolverState::default()));
for input in &inputs {
state.borrow_mut().add_source(&input.filename, &input.code);
}
move |specifier: &str, importer: &str| {
let request = state.borrow().request(specifier, importer)?;
call_module_resolver(&resolver, request, &state)
}
});
reserve_class_slots_internal(
&inputs,
option,
Expand Down
Loading
Loading