-
Notifications
You must be signed in to change notification settings - Fork 3
Compile Time Instrumentation
The main challenge for a runtime auditor is the Identity Problem: in a standard React app, a hook like useState(0) is anonymous. The runtime has no idea what variable it belongs to. But for the engine to produce a useful audit, it needs to know that a specific signal in isLogged or the subspace ThemeContext.
We don't want developers to manually label their hooks. That would add noise to the codebase and defeat the purpose. Instead, we use Babel to extract variable names automatically at build time.
Before your code runs, the Babel plugin parses it into an Abstract Syntax Tree (AST). Basis walks this tree using the Visitor Pattern, looking for nodes that represent stateful hooks or context definitions.
The plugin traverses the AST to capture variable names directly from your source code:
-
Identify the Call: Find
CallExpressionnodes where the callee is an audited hook (e.g.,useState,useReducer,createContext). -
Locate the Pattern: Check the parent
VariableDeclarator. -
Capture the Name:
-
For Hooks: The
idis anArrayPattern. The plugin extracts the first element (e.g.,countfromconst [count, setCount]). -
For Context: The
idis a plainIdentifier(e.g.,AuthContextfromconst AuthContext = createContext()).
-
For Hooks: The
Once the label is captured, the plugin rewrites the code to inject metadata into the Basis engine.
Your code:
// AuthContext.tsx
export const AuthContext = createContext(null);
// Component.tsx
const [user, setUser] = useState(null);What the plugin turns it into:
// The plugin injects the filename and variable name as a hidden label
export const AuthContext = createContext(null, "AuthContext.tsx -> AuthContext");
const [user, setUser] = useState(null, "Component.tsx -> user");Because the react-state-basis hooks accept an optional label argument, this transformation is non-breaking. You keep writing normal React code. The auditor gets the identity information it needs for the HUD and logs.
The instrumentation isn't limited to state hooks:
-
useEffect / useLayoutEffect: The plugin assigns labels based on line number (e.g.,
effect_L42). This is how the engine tracks which effect triggered which state change in the causal graph. - useMemo / useCallback: These get labeled as "Projections" in the vector space. The engine can then check their stability and distinguish them from primary Basis vectors.
All of this happens at compile-time:
- Zero Runtime Cost: The name extraction work is done once during the build. Nothing happens at runtime.
- Production Mode: In production, the Babel plugin stays idle and the library exports pure zero-op React hooks. No analysis, no overhead.
-
Safe Shims: The production hooks are designed to safely ignore these injected labels. For example, the
useReducershim makes sure a label string never gets passed to React as aninitfunction, which would crash at runtime.