fix: Fix broken array patching and ensure all values in draft Maps/Sets are finalized (#1201)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Remove hardcoded key_ field name check * Only build for `test:build` command * Rewrite Vitest prod build config to ensure prod build is used * Add tests for prod patch paths * Ensure plain values in draft maps/sets get finalized * Work around an error with prod tests Somehow was seeing an error with `each` "not existing" on startup when running the prod build tests * Fix test run
authored by Mark Erikson · committed by GitHub · parent d626513 · Browse files · 8 files·+228 added−29 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
8 files+228 added−29 removed
- tests:+154 added−0 removed
- other:+74 added−29 removed
Provenance
- Commit
b208d58- Tree
0ce013f- Author
Mark Erikson <mark@isquaredsoftware.com>- Committer
GitHub <noreply@github.com>- Parent
d626513
8 files changed+228 added−29 removed
modified:__tests__/map-set.js+115 added
365 unmodified lines366 expect(Array.from(newSet)).toEqual([objs[0], objs[1]])367 })368 })369 }370+371+// Bug reproduction: DraftSet leakage when placed in new object and set into Map372+// This bug occurs when a plain object containing a draft Set is set into a DraftMap373+describe("RTK-5159: DraftSet leakage in Map", () => {374+ const {produce} = new Immer({autoFreeze: true})375+376+ test("DraftSet should not leak when placed in new object and set into Map", () => {377+ const baseState = {378+ map: new Map([["key1", {users: new Set()}]])379+ }380+381+ // First produce: add a user382+ const state1 = produce(baseState, draft => {383+ const entry = draft.map.get("key1")384+ entry.users.add({name: "user1"})385+ })386+387+ // Second produce: create new object with existing Set and set into Map388+ const state2 = produce(state1, draft => {389+ const existingUsers = draft.map.get("key1")?.users ?? new Set()390+ const newEntry = {users: existingUsers} // New plain object with existing draft Set391+ draft.map.set("key1", newEntry)392+ newEntry.users.add({name: "user2"})393+ })394+395+ // Should not throw "Cannot use a proxy that has been revoked"396+ const users = state2.map.get("key1").users397+398+ expect(users).toBeInstanceOf(Set)399+ expect([...users].map(u => u.name)).toEqual(["user1", "user2"])400+ })401+402+ test("DraftSet in new object set into Map should finalize correctly", () => {403+ const baseState = {404+ map: new Map([["key1", {items: new Set([1, 2, 3])}]])405+ }406+407+ const result = produce(baseState, draft => {408+ const existingItems = draft.map.get("key1").items409+ // Create a new plain object containing the draft Set410+ const newEntry = {items: existingItems, extra: "data"}411+ draft.map.set("key1", newEntry)412+ newEntry.items.add(4)413+ })414+415+ // Verify the result is properly finalized (not a draft/proxy)416+ const items = result.map.get("key1").items417+ expect(items).toBeInstanceOf(Set)418+ expect([...items]).toEqual([1, 2, 3, 4])419+ expect(result.map.get("key1").extra).toBe("data")420+ })421+422+ // Test for DraftSet.add() with non-draft object containing nested draft423+ // This covers the handleCrossReference() call in DraftSet.add()424+ test("DraftSet.add() should handle non-draft object containing nested draft", () => {425+ const baseState = {426+ items: [{id: 1, name: "item1"}],427+ itemSet: new Set()428+ }429+430+ const result = produce(baseState, draft => {431+ // Get a draft of an existing item432+ const draftItem = draft.items[0]433+ // Create a new plain object that contains the draft434+ const wrapper = {item: draftItem, extra: "wrapper data"}435+ // Add the non-draft wrapper (containing a draft) to the Set436+ draft.itemSet.add(wrapper)437+ // Modify the draft item after adding438+ draftItem.name = "modified"439+ })440+441+ // The wrapper should be finalized correctly442+ const addedItems = [...result.itemSet]443+ expect(addedItems).toHaveLength(1)444+ expect(addedItems[0].item.id).toBe(1)445+ expect(addedItems[0].item.name).toBe("modified")446+ expect(addedItems[0].extra).toBe("wrapper data")447+ // Verify it's not a proxy448+ expect(() => JSON.stringify(result)).not.toThrow()449+ })450+451+ test("DraftSet.add() should handle deeply nested drafts in plain objects", () => {452+ const baseState = {453+ nested: {454+ deep: {455+ value: "original"456+ }457+ },458+ mySet: new Set()459+ }460+461+ const result = produce(baseState, draft => {462+ // Get a draft of a deeply nested object463+ const deepDraft = draft.nested.deep464+ // Create a plain object hierarchy containing the draft465+ const wrapper = {466+ level1: {467+ level2: {468+ draftRef: deepDraft469+ }470+ }471+ }472+ // Add to Set473+ draft.mySet.add(wrapper)474+ // Modify the draft475+ deepDraft.value = "modified"476+ })477+478+ const items = [...result.mySet]479+ expect(items).toHaveLength(1)480+ expect(items[0].level1.level2.draftRef.value).toBe("modified")481+ // Should not throw when accessing482+ expect(() => JSON.stringify(result)).not.toThrow()483+ })484+})modified:__tests__/patch.js+39 added
1492 unmodified lines1493 expect(state3).toEqual({1494 a: [1, 2, 3]1495 })1496 })1497+1498+// Bug reproduction: Patch path truncation in production build1499+// This bug is caused by the "key_" in state check failing after minification1500+// The patch path should include the full path for nested array modifications1501+describe("RTK-5159: Patch path truncation bug", () => {1502+ test("patch paths should include full path for nested array modifications", () => {1503+ const baseState = {1504+ lists: [{items: [{id: 1}]}]1505+ }1506+1507+ const [result, patches] = produceWithPatches(baseState, draft => {1508+ draft.lists[0].items.push({id: 2})1509+ })1510+1511+ // The patch path should be ["lists", 0, "items", 1], not just [1]1512+ expect(patches[0].path).toEqual(["lists", 0, "items", 1])1513+ expect(patches).toEqual([1514+ {op: "add", path: ["lists", 0, "items", 1], value: {id: 2}}1515+ ])1516+ })1517+1518+ test("patch paths correct for deeply nested object in array", () => {1519+ const baseState = {1520+ queries: {1521+ queryKey: {1522+ data: {1523+ items: [{name: "item1"}]1524+ }1525+ }1526+ }1527+ }1528+1529+ const [result, patches] = produceWithPatches(baseState, draft => {1530+ draft.queries.queryKey.data.items.push({name: "item2"})1531+ })1532+1533+ expect(patches[0].path).toEqual(["queries", "queryKey", "data", "items", 1])1534+ })1535+})modified:src/core/finalize.ts+23 added-17 removed
238 unmodified lines239 // Handle non-draft objects that might contain drafts240 target.callbacks_.push(function nestedDraftCleanup() {241 const targetCopy = latest(target)242 243- if (get(targetCopy, key, target.type_) === value) {244- // Process the value to replace any nested drafts245- // finalizeAssigned(target, key, target.scope_)246-247- if (248- scope_.drafts_.length > 1 &&249- ((target as Exclude<ImmerState, SetState>).assigned_!.get(key) ??250- false) === true &&251- target.copy_252- ) {253- // This might be a non-draft value that has drafts254- // inside. We do need to recurse here to handle those.255- handleValue(256- get(target.copy_, key, target.type_),257- scope_.handledSet_,258- scope_259- )243+ // For Sets, check if value is still in the set244+ if (target.type_ === ArchType.Set) {245+ if (targetCopy.has(value)) {246+ // Process the value to replace any nested drafts247+ handleValue(value, scope_.handledSet_, scope_)248 }249+ } else {250+ // Maps/objects251+ if (get(targetCopy, key, target.type_) === value) {252+ if (253+ scope_.drafts_.length > 1 &&254+ ((target as Exclude<ImmerState, SetState>).assigned_!.get(key) ??255+ false) === true &&256+ target.copy_257+ ) {258+ // This might be a non-draft value that has drafts259+ // inside. We do need to recurse here to handle those.260+ handleValue(261+ get(target.copy_, key, target.type_),262+ scope_.handledSet_,263+ scope_264+ )265+ }266+ }267 }268 })269 }270 }48 unmodified linesmodified:src/core/proxy.ts+5 added-4 removed
1 import {2- each,2 has,3 is,4 isDraftable,5 shallowCopy,9 unmodified lines15 DRAFT_STATE,16 die,17 createProxy,18 ArchType,20- ImmerScope,19 handleCrossReference,20 WRITABLE,21 CONFIGURABLE,22 ENUMERABLE,230 unmodified lines253 * Array drafts254 */255 256 const arrayTraps: ProxyHandler<[ProxyArrayState]> = {}259-each(objectTraps, (key, fn) => {257+// Use `for..in` instead of `each` to work around a weird258+// prod test suite issue259+for (let key in objectTraps) {260+ let fn = objectTraps[key as keyof typeof objectTraps] as Function261 // @ts-ignore262 arrayTraps[key] = function() {263 const args = arguments264 args[0] = args[0][0]265 return fn.apply(this, args)266 }266-})267+}268 arrayTraps.deleteProperty = function(state, prop) {269 if (process.env.NODE_ENV !== "production" && isNaN(parseInt(prop as any)))270 die(13)271 // @ts-ignore65 unmodified linesmodified:src/plugins/mapset.ts+4 added-1 removed
14 unmodified lines15 die,16 ArchType,17 each,18 getValue,19- PluginMapSet19+ PluginMapSet,20+ handleCrossReference21 } from "../internal"22 23 export function enableMapSet() {24 class DraftMap extends Map {33 unmodified lines58 markChanged(state)59 state.assigned_!.set(key, true)60 state.copy_!.set(key, value)61 state.assigned_!.set(key, true)62+ handleCrossReference(state, key, value)63 }64 return this65 }66 156 unmodified lines223 if (!this.has(value)) {224 prepareSetCopy(state)225 markChanged(state)226 state.copy_!.add(value)227+ handleCrossReference(state, value, value)228 }229 return this230 }231 101 unmodified linesmodified:src/plugins/patches.ts+1 added-1 removed
47 unmodified lines48 }49 50 function getPath(state: ImmerState, path: PatchPath = []): PatchPath | null {51 // Step 1: Check if state has a stored key52- if ("key_" in state && state.key_ !== undefined) {52+ if (state.key_ !== undefined) {53 // Step 2: Validate the key is still valid in parent54 55 const parentCopy = state.parent_!.copy_ ?? state.parent_!.base_56 const proxyDraft = getProxyDraft(get(parentCopy, state.key_!))375 unmodified linesmodified:package.json+1 added-2 removed
24 unmodified lines252627282929303133323334353660 unmodified lines24 unmodified lines "source": "src/immer.ts", "types": "./dist/immer.d.ts", "sideEffects": false, "scripts": { "pretest": "yarn build", "test": "vitest run && yarn test:build && yarn test:flow", "test:perf": "cd __performance_tests__ && node add-data.mjs && node todo.mjs && node incremental.mjs && node large-obj.mjs", "test:flow": "yarn flow check __tests__/flow", "test:build": "vitest run --config vitest.config.build.ts", "test:build": "yarn build && vitest run --config vitest.config.build.ts", "test:src": "vitest run", "watch": "vitest", "coverage": "vitest run --coverage", "coveralls": "vitest run --coverage && cat ./coverage/lcov.info | ./node_modules/.bin/coveralls && rm -rf ./coverage",60 unmodified linesmodified:vitest.config.build.ts+40 added-4 removed
123456767889101112131415161718192021222324252627282930313233343536373839403 unmodified lines4445464721484950515253545556575859import {defineConfig} from "vitest/config"import path from "path"
const prodCJSPath = path.resolve(__dirname, "dist/cjs/immer.cjs.production.js")
export default defineConfig({ resolve: { alias: { "^src/(.*)": path.resolve(__dirname, "dist/cjs/immer.cjs.production.js") } // // Make all `immer` imports use the production build alias: [ { find: /^src\/(.*)/, replacement: prodCJSPath }, { find: "../src/immer", replacement: prodCJSPath }, { find: "immer", replacement: prodCJSPath } ], // Ensure only one copy of immer is used throughout the dependency tree dedupe: ["immer"] }, // Force Vite to process immer so our alias applies to dependencies too optimizeDeps: { include: ["immer"], // Force re-bundling to pick up our alias force: true }, // SSR settings are needed because Vitest runs in Node environment ssr: { // Don't externalize immer - this makes our alias apply to it noExternal: ["immer"] }, define: { "global.USES_BUILD": true, "process.env.NODE_ENV": '"production"' },3 unmodified lines globals: true, resolveSnapshotPath: (testPath: string, snapExtension: string) => testPath.replace("__tests__", "__tests__/__prod_snapshots__") + snapExtension, reporters: ["default", "./vitest-custom-reporter.ts"] reporters: ["default", "./vitest-custom-reporter.ts"], // Ensure deps are processed through Vite's transform pipeline deps: { optimizer: { // For SSR (Node) environment, include immer so it's transformed ssr: { include: ["immer"] } } } }})