Skip to content

Commit

Permalink
[debugging] add mutation detector proxy class
Browse files Browse the repository at this point in the history
  • Loading branch information
cscheid committed Mar 6, 2025
1 parent 91c665a commit 4ca63a7
Showing 1 changed file with 65 additions and 0 deletions.
65 changes: 65 additions & 0 deletions src/core/debug/mutation-detector-proxy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
/*
* mutation-detector-proxy
*
* Copyright (C) 2025 Posit Software, PBC
*/

export type DeepProxyChange = {
type: "update" | "delete";
path: (string | symbol)[];
oldValue: unknown;
newValue?: unknown;
};

export type OnChangeCallback = (change: DeepProxyChange) => void;

export function mutationDetectorProxy<T extends object>(
obj: T,
onChange: OnChangeCallback,
path: (string | symbol)[] = [],
): T {
return new Proxy(obj, {
get(target: T, property: string | symbol): any {
const value = Reflect.get(target, property);
if (value && typeof value === "object") {
return mutationDetectorProxy(
value,
onChange,
[...path, property],
);
}
return value;
},

set(target: T, property: string | symbol, value: any): boolean {
const oldValue = Reflect.get(target, property);
const result = Reflect.set(target, property, value);

if (result) {
onChange({
type: "update",
path: [...path, property],
oldValue,
newValue: value,
});
}

return result;
},

deleteProperty(target: T, property: string | symbol): boolean {
const oldValue = Reflect.get(target, property);
const result = Reflect.deleteProperty(target, property);

if (result) {
onChange({
type: "delete",
path: [...path, property],
oldValue,
});
}

return result;
},
});
}

0 comments on commit 4ca63a7

Please sign in to comment.