perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
BREAKING CHANGE: enable loose iteration by default * Simplify some iteration checks * Allow passing type to get/set utils to skip archetype lookup * Convert assigned_ to Map * Enable loose iteration * Replace recursive tree finalization with targeted callbacks Ported Mutative's "finalization callback" approach as a more targeted and performant implementation for finalization compared to the existing recursive tree traversal approach: - Added cleanup callbacks for each draft that's created - Added callbacks to handle root drafts, assigned values, and recursing inside of plain values - Updated state creation to return [draft, state] to avoid a lookup - Rewrote patch generation system to work with callbacks instead of during tree traversal * Update self-reference test with new behavior * Apply code review suggestions * Byte-shave scopes and patch plugin usage * Inline finalizeAssigned * Move fixPotentialSetContents to plugin * Byte-shave typeof utils * Byte-shave Object references * Byte-shave field names and arrow functions
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
14 files+715 added−351 removed
- tests:+35 added−32 removed
- other:+680 added−319 removed
Provenance
- Commit
d6c1202- Tree
f9fabe0- Author
Mark Erikson <mark@isquaredsoftware.com>- Committer
GitHub <noreply@github.com>- Parent
521d5ed
14 files changed+715 added−351 removed
modified:__tests__/__snapshots__/base.js.snap-16 removed
8 unmodified lines9 exports[`base functionality - auto-freeze=false:shallow-copy=false:use-listener=false > map drafts > revokes map proxies 2`] = `[Error: [Immer] Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? {}]`;10 11 exports[`base functionality - auto-freeze=false:shallow-copy=false:use-listener=false > recipe functions > cannot return a modified child draft 1`] = `[Error: [Immer] An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.]`;12 13-exports[`base functionality - auto-freeze=false:shallow-copy=false:use-listener=false > recipe functions > cannot return an object that references itself 1`] = `[Error: [Immer] Immer forbids circular references]`;14-13 exports[`base functionality - auto-freeze=false:shallow-copy=false:use-listener=false > revokes the draft once produce returns 1`] = `[TypeError: Cannot perform 'get' on a proxy that has been revoked]`;14 15 exports[`base functionality - auto-freeze=false:shallow-copy=false:use-listener=false > revokes the draft once produce returns 2`] = `[TypeError: Cannot perform 'set' on a proxy that has been revoked]`;16 28 unmodified lines45 exports[`base functionality - auto-freeze=false:shallow-copy=false:use-listener=true > map drafts > revokes map proxies 2`] = `[Error: [Immer] Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? {}]`;46 47 exports[`base functionality - auto-freeze=false:shallow-copy=false:use-listener=true > recipe functions > cannot return a modified child draft 1`] = `[Error: [Immer] An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.]`;48 51-exports[`base functionality - auto-freeze=false:shallow-copy=false:use-listener=true > recipe functions > cannot return an object that references itself 1`] = `[Error: [Immer] Immer forbids circular references]`;52-49 exports[`base functionality - auto-freeze=false:shallow-copy=false:use-listener=true > revokes the draft once produce returns 1`] = `[TypeError: Cannot perform 'get' on a proxy that has been revoked]`;50 51 exports[`base functionality - auto-freeze=false:shallow-copy=false:use-listener=true > revokes the draft once produce returns 2`] = `[TypeError: Cannot perform 'set' on a proxy that has been revoked]`;52 28 unmodified lines81 exports[`base functionality - auto-freeze=false:shallow-copy=true:use-listener=false > map drafts > revokes map proxies 2`] = `[Error: [Immer] Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? {}]`;82 83 exports[`base functionality - auto-freeze=false:shallow-copy=true:use-listener=false > recipe functions > cannot return a modified child draft 1`] = `[Error: [Immer] An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.]`;84 89-exports[`base functionality - auto-freeze=false:shallow-copy=true:use-listener=false > recipe functions > cannot return an object that references itself 1`] = `[Error: [Immer] Immer forbids circular references]`;90-85 exports[`base functionality - auto-freeze=false:shallow-copy=true:use-listener=false > revokes the draft once produce returns 1`] = `[TypeError: Cannot perform 'get' on a proxy that has been revoked]`;86 87 exports[`base functionality - auto-freeze=false:shallow-copy=true:use-listener=false > revokes the draft once produce returns 2`] = `[TypeError: Cannot perform 'set' on a proxy that has been revoked]`;88 28 unmodified lines117 exports[`base functionality - auto-freeze=false:shallow-copy=true:use-listener=true > map drafts > revokes map proxies 2`] = `[Error: [Immer] Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? {}]`;118 119 exports[`base functionality - auto-freeze=false:shallow-copy=true:use-listener=true > recipe functions > cannot return a modified child draft 1`] = `[Error: [Immer] An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.]`;120 127-exports[`base functionality - auto-freeze=false:shallow-copy=true:use-listener=true > recipe functions > cannot return an object that references itself 1`] = `[Error: [Immer] Immer forbids circular references]`;128-121 exports[`base functionality - auto-freeze=false:shallow-copy=true:use-listener=true > revokes the draft once produce returns 1`] = `[TypeError: Cannot perform 'get' on a proxy that has been revoked]`;122 123 exports[`base functionality - auto-freeze=false:shallow-copy=true:use-listener=true > revokes the draft once produce returns 2`] = `[TypeError: Cannot perform 'set' on a proxy that has been revoked]`;124 28 unmodified lines153 exports[`base functionality - auto-freeze=true:shallow-copy=false:use-listener=false > map drafts > revokes map proxies 2`] = `[Error: [Immer] Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? {}]`;154 155 exports[`base functionality - auto-freeze=true:shallow-copy=false:use-listener=false > recipe functions > cannot return a modified child draft 1`] = `[Error: [Immer] An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.]`;156 165-exports[`base functionality - auto-freeze=true:shallow-copy=false:use-listener=false > recipe functions > cannot return an object that references itself 1`] = `[Error: [Immer] Immer forbids circular references]`;166-157 exports[`base functionality - auto-freeze=true:shallow-copy=false:use-listener=false > revokes the draft once produce returns 1`] = `[TypeError: Cannot perform 'get' on a proxy that has been revoked]`;158 159 exports[`base functionality - auto-freeze=true:shallow-copy=false:use-listener=false > revokes the draft once produce returns 2`] = `[TypeError: Cannot perform 'set' on a proxy that has been revoked]`;160 28 unmodified lines189 exports[`base functionality - auto-freeze=true:shallow-copy=false:use-listener=true > map drafts > revokes map proxies 2`] = `[Error: [Immer] Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? {}]`;190 191 exports[`base functionality - auto-freeze=true:shallow-copy=false:use-listener=true > recipe functions > cannot return a modified child draft 1`] = `[Error: [Immer] An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.]`;192 203-exports[`base functionality - auto-freeze=true:shallow-copy=false:use-listener=true > recipe functions > cannot return an object that references itself 1`] = `[Error: [Immer] Immer forbids circular references]`;204-193 exports[`base functionality - auto-freeze=true:shallow-copy=false:use-listener=true > revokes the draft once produce returns 1`] = `[TypeError: Cannot perform 'get' on a proxy that has been revoked]`;194 195 exports[`base functionality - auto-freeze=true:shallow-copy=false:use-listener=true > revokes the draft once produce returns 2`] = `[TypeError: Cannot perform 'set' on a proxy that has been revoked]`;196 28 unmodified lines225 exports[`base functionality - auto-freeze=true:shallow-copy=true:use-listener=false > map drafts > revokes map proxies 2`] = `[Error: [Immer] Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? {}]`;226 227 exports[`base functionality - auto-freeze=true:shallow-copy=true:use-listener=false > recipe functions > cannot return a modified child draft 1`] = `[Error: [Immer] An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.]`;228 241-exports[`base functionality - auto-freeze=true:shallow-copy=true:use-listener=false > recipe functions > cannot return an object that references itself 1`] = `[Error: [Immer] Immer forbids circular references]`;242-229 exports[`base functionality - auto-freeze=true:shallow-copy=true:use-listener=false > revokes the draft once produce returns 1`] = `[TypeError: Cannot perform 'get' on a proxy that has been revoked]`;230 231 exports[`base functionality - auto-freeze=true:shallow-copy=true:use-listener=false > revokes the draft once produce returns 2`] = `[TypeError: Cannot perform 'set' on a proxy that has been revoked]`;232 28 unmodified lines261 exports[`base functionality - auto-freeze=true:shallow-copy=true:use-listener=true > map drafts > revokes map proxies 2`] = `[Error: [Immer] Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? {}]`;262 263 exports[`base functionality - auto-freeze=true:shallow-copy=true:use-listener=true > recipe functions > cannot return a modified child draft 1`] = `[Error: [Immer] An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.]`;264 279-exports[`base functionality - auto-freeze=true:shallow-copy=true:use-listener=true > recipe functions > cannot return an object that references itself 1`] = `[Error: [Immer] Immer forbids circular references]`;280-265 exports[`base functionality - auto-freeze=true:shallow-copy=true:use-listener=true > revokes the draft once produce returns 1`] = `[TypeError: Cannot perform 'get' on a proxy that has been revoked]`;266 267 exports[`base functionality - auto-freeze=true:shallow-copy=true:use-listener=true > revokes the draft once produce returns 2`] = `[TypeError: Cannot perform 'set' on a proxy that has been revoked]`;268 397 unmodified linesmodified:__tests__/base.js+26 added-8 removed
2365 unmodified lines2366 draft.x = "s2"2367 draft.y = 12368 draft.z = NaN2369 if (!isProd) {2370- expect(draft[DRAFT_STATE].assigned_.x).toBe(true)2371- expect(draft[DRAFT_STATE].assigned_.y).toBe(undefined)2372- expect(draft[DRAFT_STATE].assigned_.z).toBe(undefined)2370+ expect(draft[DRAFT_STATE].assigned_.get("x")).toBe(true)2371+ expect(draft[DRAFT_STATE].assigned_.get("y")).toBe(undefined)2372+ expect(draft[DRAFT_STATE].assigned_.get("z")).toBe(undefined)2373 }2374 })2375 expect(nextState.x).toBe("s2")2376 })378 unmodified lines2755 expect(next[0]).toBe(base.a)2756 expect(next[0]).toBe(next[1])2757 })2758 2759- // This actually seems to pass now!2760- it("cannot return an object that references itself", () => {2759+ // As of the finalization callback rewrite, the2760+ // the original `() => res.self` check passes without throwing,2761+ // but we still will not have self-references2762+ // when returning updated values2763+ it("can return self-references, but not for modified values", () => {2764 const res = {}2765 res.self = res2763- expect(() => {2764- produce(res, () => res.self)2765- }).toThrowErrorMatchingSnapshot()2766+2767+ // the call will pass2768+ const next = produce(res, draft => {2769+ draft.a = 422770+ draft.self.b = 992771+ })2772+2773+ // Root object and first child were both copied2774+ expect(next).not.toBe(next.self)2775+ // Second child is the first circular reference2776+ expect(next.self.self).not.toBe(next.self)2777+ // And it's turtles all the way down2778+ expect(next.self.self.self).toBe(next.self.self.self.self)2779+ expect(next.a).toBe(42)2780+ expect(next.self.b).toBe(99)2781+ // The child copy did not receive the update2782+ // to the root object2783+ expect(next.self.a).toBe(undefined)2784 })2785 })2786 2787 it("throws when the draft is modified and another object is returned", () => {738 unmodified linesmodified:__tests__/map-set.js+9 added-8 removed
122 unmodified lines123 },124 [125 {126 op: "remove",127- path: ["map", "b", "a"]127+ path: ["map", "d", "a"]128 },129 {130 op: "remove",131 path: ["map", "c", "a"]132 },133 {134 op: "remove",135- path: ["map", "d", "a"]135+ path: ["map", "b", "a"]136 }137 ],138 [139 {140 op: "add",141- path: ["map", "b", "a"],141+ path: ["map", "d", "a"],142 value: true143 },144 {145 op: "add",1 unmodified line147 value: true148 },149 {150 op: "add",151- path: ["map", "d", "a"],151+ path: ["map", "b", "a"],152 value: true153 }154 ]155 ])40 unmodified lines196 })197 expect(p).toEqual([198 {199 op: "remove",200- path: ["map", "b", "a"]200+ path: ["map", "d", "a"]201 },202 {203 op: "remove",204 path: ["map", "c", "a"]205 },206 {207 op: "remove",208- path: ["map", "d", "a"]208+ path: ["map", "b", "a"]209 }210 ])211 expect(ip).toEqual([212 {213 op: "add",214- path: ["map", "b", "a"],214+ path: ["map", "d", "a"],215 value: true216 },217+218 {219 op: "add",220 path: ["map", "c", "a"],221 value: true222 },223 {224 op: "add",224- path: ["map", "d", "a"],225+ path: ["map", "b", "a"],226 value: true227 }228 ])229 })140 unmodified linesmodified:src/core/finalize.ts+231 added-128 removed
3 unmodified lines4 isDraftable,5 NOTHING,6 PatchPath,7 each,8- has,8 freeze,9 ImmerState,10 isDraft,11 SetState,2 unmodified lines14 getPlugin,15 die,16 revokeScope,17 isFrozen,19- isMap18+ get,19+ Patch,20+ latest,21+ prepareCopy,22+ getFinalValue,23+ getValue24 } from "../internal"25 26 export function processResult(result: any, scope: ImmerScope) {27 scope.unfinalizedDrafts_ = scope.drafts_.length28 const baseDraft = scope.drafts_![0]29 const isReplaced = result !== undefined && result !== baseDraft30+31 if (isReplaced) {32 if (baseDraft[DRAFT_STATE].modified_) {33 revokeScope(scope)34 die(4)35 }36 if (isDraftable(result)) {37 // Finalize the result in case it contains (or is) a subset of the draft.38 result = finalize(scope, result)34- if (!scope.parent_) maybeFreeze(scope, result)39 }36- if (scope.patches_) {37- getPlugin("Patches").generateReplacementPatches_(40+ const {patchPlugin_} = scope41+ if (patchPlugin_) {42+ patchPlugin_.generateReplacementPatches_(43 baseDraft[DRAFT_STATE].base_,44 result,40- scope.patches_,41- scope.inversePatches_!45+ scope46 )47 }48 } else {49 // Finalize the base draft.46- result = finalize(scope, baseDraft, [])50+ result = finalize(scope, baseDraft)51 }52+53+ maybeFreeze(scope, result, true)54+55 revokeScope(scope)56 if (scope.patches_) {57 scope.patchListener_!(scope.patches_, scope.inversePatches_!)58 }59 return result !== NOTHING ? result : undefined60 }61 55-function finalize(rootScope: ImmerScope, value: any, path?: PatchPath) {62+function finalize(rootScope: ImmerScope, value: any) {63 // Don't recurse in tho recursive data structures64 if (isFrozen(value)) return value65 59- const useStrictIteration = rootScope.immer_.shouldUseStrictIteration()60-66 const state: ImmerState = value[DRAFT_STATE]62- // A plain object, might need freezing, might contain drafts67 if (!state) {64- each(65- value,66- (key, childValue) =>67- finalizeProperty(rootScope, state, value, key, childValue, path),68- useStrictIteration69- )68+ const finalValue = handleValue(value, rootScope.handledSet_, rootScope)69+ return finalValue70+ }71+72+ // Never finalize drafts owned by another scope73+ if (!isSameScope(state, rootScope)) {74 return value75 }72- // Never finalize drafts owned by another scope.73- if (state.scope_ !== rootScope) return value76+77 // Unmodified draft, return the (frozen) original78 if (!state.modified_) {76- maybeFreeze(rootScope, state.base_, true)79 return state.base_80 }79- // Not finalized yet, let's do that now81+82 if (!state.finalized_) {81- state.finalized_ = true82- state.scope_.unfinalizedDrafts_--83- const result = state.copy_84- // Finalize all children of the copy85- // For sets we clone before iterating, otherwise we can get in endless loop due to modifying during iteration, see #62886- // To preserve insertion order in all cases we then clear the set87- // And we let finalizeProperty know it needs to re-add non-draft children back to the target88- let resultEach = result89- let isSet = false90- if (state.type_ === ArchType.Set) {91- resultEach = new Set(result)92- result.clear()93- isSet = true83+ // Execute all registered draft finalization callbacks84+ const {callbacks_} = state85+ if (callbacks_) {86+ while (callbacks_.length > 0) {87+ const callback = callbacks_.pop()!88+ callback(rootScope)89+ }90 }95- each(96- resultEach,97- (key, childValue) =>98- finalizeProperty(99- rootScope,100- state,101- result,102- key,103- childValue,104- path,105- isSet106- ),107- useStrictIteration108- )109- // everything inside is frozen, we can freeze here110- maybeFreeze(rootScope, result, false)111- // first time finalizing, let's create those patches112- if (path && rootScope.patches_) {113- getPlugin("Patches").generatePatches_(114- state,115- path,116- rootScope.patches_,117- rootScope.inversePatches_!118- )119- }91+92+ generatePatchesAndFinalize(state, rootScope)93 }94+95+ // By now the root copy has been fully updated throughout its tree96 return state.copy_97 }98 124-function finalizeProperty(125- rootScope: ImmerScope,126- parentState: undefined | ImmerState,127- targetObject: any,128- prop: string | number,129- childValue: any,130- rootPath?: PatchPath,131- targetIsSet?: boolean132-) {133- if (childValue == null) {134- return99+function maybeFreeze(scope: ImmerScope, value: any, deep = false) {100+ // we never freeze for a non-root scope; as it would prevent pruning for drafts inside wrapping objects101+ if (!scope.parent_ && scope.immer_.autoFreeze_ && scope.canAutoFreeze_) {102+ freeze(value, deep)103 }104+}105 137- if (typeof childValue !== "object" && !targetIsSet) {138- return106+function markStateFinalized(state: ImmerState) {107+ state.finalized_ = true108+ state.scope_.unfinalizedDrafts_--109+}110+111+let isSameScope = (state: ImmerState, rootScope: ImmerScope) =>112+ state.scope_ === rootScope113+114+// A reusable empty array to avoid allocations115+const EMPTY_LOCATIONS_RESULT: (string | symbol | number)[] = []116+117+// Updates all references to a draft in its parent to the finalized value.118+// This handles cases where the same draft appears multiple times in the parent, or has been moved around.119+export function updateDraftInParent(120+ parent: ImmerState,121+ draftValue: any,122+ finalizedValue: any,123+ originalKey?: string | number | symbol124+): void {125+ const parentCopy = latest(parent)126+ const parentType = parent.type_127+128+ // Fast path: Check if draft is still at original key129+ if (originalKey !== undefined) {130+ const currentValue = get(parentCopy, originalKey, parentType)131+ if (currentValue === draftValue) {132+ // Still at original location, just update it133+ set(parentCopy, originalKey, finalizedValue, parentType)134+ return135+ }136 }140- const childIsFrozen = isFrozen(childValue)141- if (childIsFrozen && !targetIsSet) {142- return137+138+ // Slow path: Build reverse mapping of all children139+ // to their indices in the parent, so that we can140+ // replace all locations where this draft appears.141+ // We only have to build this once per parent.142+ if (!parent.draftLocations_) {143+ const draftLocations = (parent.draftLocations_ = new Map())144+145+ // Use `each` which works on Arrays, Maps, and Objects146+ each(parentCopy, (key, value) => {147+ if (isDraft(value)) {148+ const keys = draftLocations.get(value) || []149+ keys.push(key)150+ draftLocations.set(value, keys)151+ }152+ })153 }154 145- if (process.env.NODE_ENV !== "production" && childValue === targetObject)146- die(5)147- if (isDraft(childValue)) {148- const path =149- rootPath &&150- parentState &&151- parentState!.type_ !== ArchType.Set && // Set objects are atomic since they have no keys.152- !has((parentState as Exclude<ImmerState, SetState>).assigned_!, prop) // Skip deep patches for assigned keys.153- ? rootPath!.concat(prop)154- : undefined155- // Drafts owned by `scope` are finalized here.156- const res = finalize(rootScope, childValue, path)157- set(targetObject, prop, res)158- // Drafts from another scope must prevented to be frozen159- // if we got a draft back from finalize, we're in a nested produce and shouldn't freeze160- if (isDraft(res)) {161- rootScope.canAutoFreeze_ = false162- } else return163- } else if (targetIsSet) {164- targetObject.add(childValue)155+ // Look up all locations where this draft appears156+ const locations =157+ parent.draftLocations_.get(draftValue) ?? EMPTY_LOCATIONS_RESULT158+159+ // Update all locations160+ for (const location of locations) {161+ set(parentCopy, location, finalizedValue, parentType)162 }166- // Search new objects for unfinalized drafts. Frozen objects should never contain drafts.167- if (isDraftable(childValue) && !childIsFrozen) {168- if (!rootScope.immer_.autoFreeze_ && rootScope.unfinalizedDrafts_ < 1) {169- // optimization: if an object is not a draft, and we don't have to170- // deepfreeze everything, and we are sure that no drafts are left in the remaining object171- // cause we saw and finalized all drafts already; we can stop visiting the rest of the tree.172- // This benefits especially adding large data tree's without further processing.173- // See add-data.js perf test163+}164+165+// Register a callback to finalize a child draft when the parent draft is finalized.166+// This assumes there is a parent -> child relationship between the two drafts,167+// and we have a key to locate the child in the parent.168+export function registerChildFinalizationCallback(169+ parent: ImmerState,170+ child: ImmerState,171+ key: string | number | symbol172+) {173+ parent.callbacks_.push(function childCleanup(rootScope) {174+ const state: ImmerState = child175+176+ // Can only continue if this is a draft owned by this scope177+ if (!state || !isSameScope(state, rootScope)) {178 return179 }176- if (177- parentState &&178- parentState.base_ &&179- parentState.base_[prop] === childValue &&180- childIsFrozen181- ) {182- // Object is unchanged from base - no need to process further183- return180+181+ // Handle potential set value finalization first182+ rootScope.mapSetPlugin_?.fixSetContents(state)183+184+ const finalizedValue = getFinalValue(state)185+186+ // Update all locations in the parent that referenced this draft187+ updateDraftInParent(parent, state.draft_ ?? state, finalizedValue, key)188+189+ generatePatchesAndFinalize(state, rootScope)190+ })191+}192+193+function generatePatchesAndFinalize(state: ImmerState, rootScope: ImmerScope) {194+ const shouldFinalize =195+ state.modified_ &&196+ !state.finalized_ &&197+ (state.type_ === ArchType.Set || (state.assigned_?.size ?? 0) > 0)198+199+ if (shouldFinalize) {200+ const {patchPlugin_} = rootScope201+ if (patchPlugin_) {202+ const basePath = patchPlugin_!.getPath(state)203+204+ if (basePath) {205+ patchPlugin_!.generatePatches_(state, basePath, rootScope)206+ }207 }185- finalize(rootScope, childValue)186- // Immer deep freezes plain objects, so if there is no parent state, we freeze as well187- // Per #590, we never freeze symbolic properties. Just to make sure don't accidentally interfere188- // with other frameworks.189- if (190- (!parentState || !parentState.scope_.parent_) &&191- typeof prop !== "symbol" &&192- (isMap(targetObject)193- ? targetObject.has(prop)194- : Object.prototype.propertyIsEnumerable.call(targetObject, prop))195- )196- maybeFreeze(rootScope, childValue)208+209+ markStateFinalized(state)210 }211 }212 200-function maybeFreeze(scope: ImmerScope, value: any, deep = false) {201- // we never freeze for a non-root scope; as it would prevent pruning for drafts inside wrapping objects202- if (!scope.parent_ && scope.immer_.autoFreeze_ && scope.canAutoFreeze_) {203- freeze(value, deep)213+export function handleCrossReference(214+ target: ImmerState,215+ key: string | number | symbol,216+ value: any217+) {218+ const {scope_} = target219+ // Check if value is a draft from this scope220+ if (isDraft(value)) {221+ const state: ImmerState = value[DRAFT_STATE]222+ if (isSameScope(state, scope_)) {223+ // Register callback to update this location when the draft finalizes224+225+ state.callbacks_.push(function crossReferenceCleanup() {226+ // Update the target location with finalized value227+ prepareCopy(target)228+229+ const finalizedValue = getFinalValue(state)230+231+ updateDraftInParent(target, value, finalizedValue, key)232+ })233+ }234+ } else if (isDraftable(value)) {235+ // Handle non-draft objects that might contain drafts236+ target.callbacks_.push(function nestedDraftCleanup() {237+ const targetCopy = latest(target)238+239+ if (get(targetCopy, key, target.type_) === value) {240+ // Process the value to replace any nested drafts241+ // finalizeAssigned(target, key, target.scope_)242+243+ if (244+ scope_.drafts_.length > 1 &&245+ ((target as Exclude<ImmerState, SetState>).assigned_!.get(key) ??246+ false) === true &&247+ target.copy_248+ ) {249+ // This might be a non-draft value that has drafts250+ // inside. We do need to recurse here to handle those.251+ handleValue(252+ get(target.copy_, key, target.type_),253+ scope_.handledSet_,254+ scope_255+ )256+ }257+ }258+ })259 }260 }261+262+export function handleValue(263+ target: any,264+ handledSet: Set<any>,265+ rootScope: ImmerScope266+) {267+ if (!rootScope.immer_.autoFreeze_ && rootScope.unfinalizedDrafts_ < 1) {268+ // optimization: if an object is not a draft, and we don't have to269+ // deepfreeze everything, and we are sure that no drafts are left in the remaining object270+ // cause we saw and finalized all drafts already; we can stop visiting the rest of the tree.271+ // This benefits especially adding large data tree's without further processing.272+ // See add-data.js perf test273+ return target274+ }275+276+ // Skip if already handled, frozen, or not draftable277+ if (278+ isDraft(target) ||279+ handledSet.has(target) ||280+ !isDraftable(target) ||281+ isFrozen(target)282+ ) {283+ return target284+ }285+286+ handledSet.add(target)287+288+ // Process ALL properties/entries289+ each(target, (key, value) => {290+ if (isDraft(value)) {291+ const state: ImmerState = value[DRAFT_STATE]292+ if (isSameScope(state, rootScope)) {293+ // Replace draft with finalized value294+295+ const updatedValue = getFinalValue(state)296+297+ set(target, key, updatedValue, target.type_)298+299+ markStateFinalized(state)300+ }301+ } else if (isDraftable(value)) {302+ // Recursively handle nested values303+ handleValue(value, handledSet, rootScope)304+ }305+ })306+307+ return target308+}modified:src/core/immerClass.ts+59 added-22 removed
21 unmodified lines22 usePatchesInScope,23 getCurrentScope,24 NOTHING,25 freeze,26- current26+ current,27+ ImmerScope,28+ registerChildFinalizationCallback,29+ ArchType,30+ MapSetPlugin,31+ AnyMap,32+ AnySet,33+ isObjectish,34+ isFunction,35+ isBoolean,36+ PluginMapSet,37+ PluginPatches38 } from "../internal"39 40 interface ProducersFns {41 produce: IProduce4 unmodified lines46 47 export class Immer implements ProducersFns {48 autoFreeze_: boolean = true49 useStrictShallowCopy_: StrictMode = false39- useStrictIteration_: boolean = true50+ useStrictIteration_: boolean = false51 52 constructor(config?: {53 autoFreeze?: boolean54 useStrictShallowCopy?: StrictMode55 useStrictIteration?: boolean56 }) {46- if (typeof config?.autoFreeze === "boolean")47- this.setAutoFreeze(config!.autoFreeze)48- if (typeof config?.useStrictShallowCopy === "boolean")57+ if (isBoolean(config?.autoFreeze)) this.setAutoFreeze(config!.autoFreeze)58+ if (isBoolean(config?.useStrictShallowCopy))59 this.setUseStrictShallowCopy(config!.useStrictShallowCopy)50- if (typeof config?.useStrictIteration === "boolean")60+ if (isBoolean(config?.useStrictIteration))61 this.setUseStrictIteration(config!.useStrictIteration)62 }63 64 /**16 unmodified lines81 * @returns {any} a new state, or the initial state if nothing was modified82 */83 produce: IProduce = (base: any, recipe?: any, patchListener?: any) => {84 // curried invocation75- if (typeof base === "function" && typeof recipe !== "function") {85+ if (isFunction(base) && !isFunction(recipe)) {86 const defaultBase = recipe87 recipe = base88 89 const self = this5 unmodified lines95 return self.produce(base, (draft: Drafted) => recipe.call(this, draft, ...args)) // prettier-ignore96 }97 }98 89- if (typeof recipe !== "function") die(6)90- if (patchListener !== undefined && typeof patchListener !== "function")91- die(7)99+ if (!isFunction(recipe)) die(6)100+ if (patchListener !== undefined && !isFunction(patchListener)) die(7)101 102 let result103 104 // Only plain objects, arrays, and "immerable classes" are drafted.105 if (isDraftable(base)) {106 const scope = enterScope(this)98- const proxy = createProxy(base, undefined)107+ const proxy = createProxy(scope, base, undefined)108 let hasError = true109 try {110 result = recipe(proxy)111 hasError = false3 unmodified lines115 else leaveScope(scope)116 }117 usePatchesInScope(scope, patchListener)118 return processResult(result, scope)110- } else if (!base || typeof base !== "object") {119+ } else if (!base || !isObjectish(base)) {120 result = recipe(base)121 if (result === undefined) result = base122 if (result === NOTHING) result = undefined123 if (this.autoFreeze_) freeze(result, true)124 if (patchListener) {125 const p: Patch[] = []126 const ip: Patch[] = []118- getPlugin("Patches").generateReplacementPatches_(base, result, p, ip)127+ getPlugin(PluginPatches).generateReplacementPatches_(base, result, {128+ patches_: p,129+ inversePatches_: ip130+ } as ImmerScope) // dummy scope131 patchListener(p, ip)132 }133 return result134 } else die(1, base)135 }136 137 produceWithPatches: IProduceWithPatches = (base: any, recipe?: any): any => {138 // curried invocation127- if (typeof base === "function") {139+ if (isFunction(base)) {140 return (state: any, ...args: any[]) =>141 this.produceWithPatches(state, (draft: any) => base(draft, ...args))142 }143 8 unmodified lines152 createDraft<T extends Objectish>(base: T): Draft<T> {153 if (!isDraftable(base)) die(8)154 if (isDraft(base)) base = current(base)155 const scope = enterScope(this)144- const proxy = createProxy(base, undefined)156+ const proxy = createProxy(scope, base, undefined)157 proxy[DRAFT_STATE].isManual_ = true158 leaveScope(scope)159 return proxy as any160 }57 unmodified lines218 if (i > -1) {219 patches = patches.slice(i + 1)220 }221 210- const applyPatchesImpl = getPlugin("Patches").applyPatches_222+ const applyPatchesImpl = getPlugin(PluginPatches).applyPatches_223 if (isDraft(base)) {224 // N.B: never hits if some patch a replacement, patches are never drafts225 return applyPatchesImpl(base, patches)226 }4 unmodified lines231 }232 }233 234 export function createProxy<T extends Objectish>(235+ rootScope: ImmerScope,236 value: T,224- parent?: ImmerState237+ parent?: ImmerState,238+ key?: string | number | symbol239 ): Drafted<T, ImmerState> {240 // precondition: createProxy should be guarded by isDraftable, so we know we can safely draft241+ // returning a tuple here lets us skip a proxy access242+ // to DRAFT_STATE later227- const draft: Drafted = isMap(value)228- ? getPlugin("MapSet").proxyMap_(value, parent)243+ const [draft, state] = isMap(value)244+ ? getPlugin(PluginMapSet).proxyMap_(value, parent)245 : isSet(value)230- ? getPlugin("MapSet").proxySet_(value, parent)246+ ? getPlugin(PluginMapSet).proxySet_(value, parent)247 : createProxyProxy(value, parent)248 233- const scope = parent ? parent.scope_ : getCurrentScope()249+ const scope = parent?.scope_ ?? getCurrentScope()250 scope.drafts_.push(draft)251+252+ // Ensure the parent callbacks are passed down so we actually253+ // track all callbacks added throughout the tree254+ state.callbacks_ = parent?.callbacks_ ?? []255+ state.key_ = key256+257+ if (parent && key !== undefined) {258+ registerChildFinalizationCallback(parent, state, key)259+ } else {260+ // It's a root draft, register it with the scope261+ state.callbacks_.push(function rootDraftCleanup(rootScope) {262+ rootScope.mapSetPlugin_?.fixSetContents(state)263+264+ const {patchPlugin_} = rootScope265+266+ if (state.modified_ && patchPlugin_) {267+ patchPlugin_.generatePatches_(state, [], rootScope)268+ }269+ })270+ }271+235- return draft272+ return draft as any273 }modified:src/core/proxy.ts+47 added-32 removed
15 unmodified lines16 DRAFT_STATE,17 die,18 createProxy,19 ArchType,20- ImmerScope20+ ImmerScope,21+ handleCrossReference,22+ WRITABLE,23+ CONFIGURABLE,24+ ENUMERABLE,25+ VALUE,26+ isArray27 } from "../internal"28 29 interface ProxyBaseState extends ImmerBaseState {24- assigned_: {25- [property: string]: boolean26- }30 parent_?: ImmerState31 revoke_(): void32 }33 20 unmodified lines54 */55 export function createProxyProxy<T extends Objectish>(56 base: T,57 parent?: ImmerState55-): Drafted<T, ProxyState> {56- const isArray = Array.isArray(base)58+): [Drafted<T, ProxyState>, ProxyState] {59+ const baseIsArray = isArray(base)60 const state: ProxyState = {58- type_: isArray ? ArchType.Array : (ArchType.Object as any),61+ type_: baseIsArray ? ArchType.Array : (ArchType.Object as any),62 // Track which produce call this is associated with.63 scope_: parent ? parent.scope_ : getCurrentScope()!,64 // True for both shallow and deep changes.65 modified_: false,66 // Used during finalization.67 finalized_: false,68 // Track which properties have been assigned (true) or deleted (false).69+ // actually instantiated in `prepareCopy()`66- assigned_: {},70+ assigned_: undefined,71 // The parent draft state.72 parent_: parent,73 // The base state.74 base_: base,2 unmodified lines77 // The base copy with any updated values.78 copy_: null,79 // Called by the `produce` function.80 revoke_: null as any,77- isManual_: false81+ isManual_: false,82+ // `callbacks` actually gets assigned in `createProxy`83+ callbacks_: undefined as any84 }85 86 // the traps must target something, a bit like the 'real' base.87 // but also, we need to be able to determine from the target what the relevant state is2 unmodified lines90 // So the trick is to use 'state' as the actual 'target'! (and make sure we intercept everything)91 // Note that in the case of an array, we put the state in an array to have better Reflect defaults ootb92 let target: T = state as any93 let traps: ProxyHandler<object | Array<any>> = objectTraps88- if (isArray) {94+ if (baseIsArray) {95 target = [state] as any96 traps = arrayTraps97 }98 99 const {revoke, proxy} = Proxy.revocable(target, traps)100 state.draft_ = proxy as any101 state.revoke_ = revoke96- return proxy as any102+ return [proxy as any, state]103 }104 105 /**106 * Object drafts2 unmodified lines109 get(state, prop) {110 if (prop === DRAFT_STATE) return state111 112 const source = latest(state)107- if (!has(source, prop)) {113+ if (!has(source, prop, state.type_)) {114 // non-existing or non-own property...115 return readPropFromProto(state, source, prop)116 }117 const value = source[prop]3 unmodified lines121 // Check for existing draft in modified state.122 // Assigned values are never drafted. This catches any drafts we created, too.123 if (value === peek(state.base_, prop)) {124 prepareCopy(state)119- return (state.copy_![prop as any] = createProxy(value, state))125+ // Ensure array keys are always numbers126+ const childKey = state.type_ === ArchType.Array ? +(prop as string) : prop127+ const childDraft = createProxy(state.scope_, value, state, childKey)128+129+ return (state.copy_![childKey] = childDraft)130 }131 return value132 },133 has(state, prop) {21 unmodified lines155 // special case, if we assigning the original value to a draft, we can ignore the assignment156 const currentState: ProxyObjectState = current?.[DRAFT_STATE]157 if (currentState && currentState.base_ === value) {158 state.copy_![prop] = value149- state.assigned_[prop] = false159+ state.assigned_!.set(prop, false)160 return true161 }152- if (is(value, current) && (value !== undefined || has(state.base_, prop)))162+ if (163+ is(value, current) &&164+ (value !== undefined || has(state.base_, prop, state.type_))165+ )166 return true167 prepareCopy(state)168 markChanged(state)169 }8 unmodified lines178 return true179 180 // @ts-ignore181 state.copy_![prop] = value169- state.assigned_[prop] = true182+ state.assigned_!.set(prop, true)183+184+ handleCrossReference(state, prop, value)185 return true186 },187 deleteProperty(state, prop: string) {188+ prepareCopy(state)189 // The `undefined` check is a fast path for pre-existing keys.190 if (peek(state.base_, prop) !== undefined || prop in state.base_) {175- state.assigned_[prop] = false176- prepareCopy(state)191+ state.assigned_!.set(prop, false)192 markChanged(state)193 } else {194 // if an originally not assigned property was deleted180- delete state.assigned_[prop]195+ state.assigned_!.delete(prop)196 }197 if (state.copy_) {198 delete state.copy_[prop]199 }5 unmodified lines205 const owner = latest(state)206 const desc = Reflect.getOwnPropertyDescriptor(owner, prop)207 if (!desc) return desc208 return {194- writable: true,195- configurable: state.type_ !== ArchType.Array || prop !== "length",196- enumerable: desc.enumerable,197- value: owner[prop]209+ [WRITABLE]: true,210+ [CONFIGURABLE]: state.type_ !== ArchType.Array || prop !== "length",211+ [ENUMERABLE]: desc[ENUMERABLE],212+ [VALUE]: owner[prop]213 }214 },215 defineProperty() {216 die(11)13 unmodified lines230 const arrayTraps: ProxyHandler<[ProxyArrayState]> = {}231 each(objectTraps, (key, fn) => {232 // @ts-ignore233 arrayTraps[key] = function() {234+ const args = arguments219- arguments[0] = arguments[0][0]220- return fn.apply(this, arguments)235+ args[0] = args[0][0]236+ return fn.apply(this, args)237 }238 })239 arrayTraps.deleteProperty = function(state, prop) {240 if (process.env.NODE_ENV !== "production" && isNaN(parseInt(prop as any)))20 unmodified lines261 262 function readPropFromProto(state: ImmerState, source: any, prop: PropertyKey) {263 const desc = getDescriptorFromProto(source, prop)264 return desc249- ? `value` in desc250- ? desc.value265+ ? VALUE in desc266+ ? desc[VALUE]267 : // This is a very special case, if the prop is a getter defined by the268 // prototype, we should invoke it with the draft as context!269 desc.get?.call(state.draft_)270 : undefined22 unmodified lines293 }294 }295 }296 281-export function prepareCopy(state: {282- base_: any283- copy_: any284- scope_: ImmerScope285-}) {297+export function prepareCopy(state: ImmerState) {298 if (!state.copy_) {299+ // Actually create the `assigned_` map now that we300+ // know this is a modified draft.301+ state.assigned_ = new Map()302 state.copy_ = shallowCopy(303 state.base_,304 state.scope_.immer_.useStrictShallowCopy_305 )2 unmodified linesmodified:src/core/scope.ts+29 added-20 removed
4 unmodified lines56789910111213141516171819202122232425262728293031323334352728293637313839403435363738394041424344414243444546474849505152535455565758596051616263646511 unmodified lines777879807172738182838485863 unmodified lines4 unmodified lines Immer, DRAFT_STATE, ImmerState, ArchType, getPlugin getPlugin, PatchesPlugin, MapSetPlugin, isPluginLoaded, PluginMapSet, PluginPatches} from "../internal"
/** Each scope represents a `produce` call. */
export interface ImmerScope { patches_?: Patch[] inversePatches_?: Patch[] patchPlugin_?: PatchesPlugin mapSetPlugin_?: MapSetPlugin canAutoFreeze_: boolean drafts_: any[] parent_?: ImmerScope patchListener_?: PatchListener immer_: Immer unfinalizedDrafts_: number handledSet_: Set<any> processedForPatches_: Set<any>}
let currentScope: ImmerScope | undefined
export function getCurrentScope() { return currentScope!}export let getCurrentScope = () => currentScope!
function createScope(let createScope = ( parent_: ImmerScope | undefined, immer_: Immer): ImmerScope { return { drafts_: [], parent_, immer_, // Whenever the modified draft contains a draft from another scope, we // need to prevent auto-freezing so the unowned draft can be finalized. canAutoFreeze_: true, unfinalizedDrafts_: 0 }}): ImmerScope => ({ drafts_: [], parent_, immer_, // Whenever the modified draft contains a draft from another scope, we // need to prevent auto-freezing so the unowned draft can be finalized. canAutoFreeze_: true, unfinalizedDrafts_: 0, handledSet_: new Set(), processedForPatches_: new Set(), mapSetPlugin_: isPluginLoaded(PluginMapSet) ? getPlugin(PluginMapSet) : undefined})
export function usePatchesInScope( scope: ImmerScope, patchListener?: PatchListener) { if (patchListener) { getPlugin("Patches") // assert we have the plugin scope.patchPlugin_ = getPlugin(PluginPatches) // assert we have the plugin scope.patches_ = [] scope.inversePatches_ = [] scope.patchListener_ = patchListener }11 unmodified lines currentScope = scope.parent_ }}
export function enterScope(immer: Immer) { return (currentScope = createScope(currentScope, immer))}export let enterScope = (immer: Immer) => (currentScope = createScope(currentScope, immer))
function revokeDraft(draft: Drafted) { const state: ImmerState = draft[DRAFT_STATE] if (state.type_ === ArchType.Object || state.type_ === ArchType.Array)3 unmodified linesmodified:src/plugins/mapset.ts+35 added-10 removed
12 unmodified lines13 loadPlugin,14 markChanged,15 die,16 ArchType,17- each17+ each,18+ getValue,19+ PluginMapSet20 } from "../internal"21 22 export function enableMapSet() {23 class DraftMap extends Map {11 unmodified lines35 assigned_: undefined,36 base_: target,37 draft_: this as any,38 isManual_: false,37- revoked_: false39+ revoked_: false,40+ callbacks_: []41 }42 }43 44 get size(): number {66 unmodified lines111 if (value !== state.base_.get(key)) {112 return value // either already drafted or reassigned113 }114 // despite what it looks, this creates a draft only once, see above condition112- const draft = createProxy(value, state)115+ const draft = createProxy(state.scope_, value, state, key)116 prepareMapCopy(state)117 state.copy_!.set(key, draft)118 return draft119 }40 unmodified lines160 return this.entries()161 }162 }163 161- function proxyMap_<T extends AnyMap>(target: T, parent?: ImmerState): T {164+ function proxyMap_<T extends AnyMap>(165+ target: T,166+ parent?: ImmerState167+ ): [T, MapState] {168 // @ts-ignore163- return new DraftMap(target, parent)169+ const map = new DraftMap(target, parent)170+ return [map as any, map[DRAFT_STATE]]171 }172 173 function prepareMapCopy(state: MapState) {174 if (!state.copy_) {16 unmodified lines191 base_: target,192 draft_: this,193 drafts_: new Map(),194 revoked_: false,188- isManual_: false195+ isManual_: false,196+ assigned_: undefined,197+ callbacks_: []198 }199 }200 201 get size(): number {81 unmodified lines283 result = iterator.next()284 }285 }286 }278- function proxySet_<T extends AnySet>(target: T, parent?: ImmerState): T {287+ function proxySet_<T extends AnySet>(288+ target: T,289+ parent?: ImmerState290+ ): [T, SetState] {291 // @ts-ignore280- return new DraftSet(target, parent)292+ const set = new DraftSet(target, parent)293+ return [set as any, set[DRAFT_STATE]]294 }295 296 function prepareSetCopy(state: SetState) {297 if (!state.copy_) {298 // create drafts for all entries to preserve insertion order299 state.copy_ = new Set()300 state.base_.forEach(value => {301 if (isDraftable(value)) {289- const draft = createProxy(value, state)302+ const draft = createProxy(state.scope_, value, state, value)303 state.drafts_.set(value, draft)304 state.copy_!.add(draft)305 } else {306 state.copy_!.add(value)5 unmodified lines312 function assertUnrevoked(state: any /*ES5State | MapState | SetState*/) {313 if (state.revoked_) die(3, JSON.stringify(latest(state)))314 }315 303- loadPlugin("MapSet", {proxyMap_, proxySet_})316+ function fixSetContents(target: ImmerState) {317+ // For sets we clone before iterating, otherwise we can get in endless loop due to modifying during iteration, see #628318+ // To preserve insertion order in all cases we then clear the set319+ if (target.type_ === ArchType.Set && target.copy_) {320+ const copy = new Set(target.copy_)321+ target.copy_.clear()322+ copy.forEach(value => {323+ target.copy_!.add(getValue(value))324+ })325+ }326+ }327+328+ loadPlugin(PluginMapSet, {proxyMap_, proxySet_, fixSetContents})329 }modified:src/plugins/patches.ts+136 added-26 removed
18 unmodified lines19 die,20 isDraft,21 isDraftable,22 NOTHING,23- errors23+ errors,24+ DRAFT_STATE,25+ getProxyDraft,26+ ImmerScope,27+ isObjectish,28+ isFunction,29+ CONSTRUCTOR,30+ PluginPatches,31+ isArray,32+ PROTOTYPE33 } from "../internal"34 35 export function enablePatches() {36 const errorOffset = 169 unmodified lines46 "Patching reserved attributes like __proto__, prototype and constructor is not allowed"47 )48 }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) {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_!))57+ const valueAtKey = get(parentCopy, state.key_!)58+59+ if (valueAtKey === undefined) {60+ return null61+ }62+63+ // Check if the value at the key is still related to this draft64+ // It should be either the draft itself, the base, or the copy65+ if (66+ valueAtKey !== state.draft_ &&67+ valueAtKey !== state.base_ &&68+ valueAtKey !== state.copy_69+ ) {70+ return null // Value was replaced with something else71+ }72+ if (proxyDraft != null && proxyDraft.base_ !== state.base_) {73+ return null // Different draft74+ }75+76+ // Step 3: Handle Set case specially77+ const isSet = state.parent_!.type_ === ArchType.Set78+ let key: string | number79+80+ if (isSet) {81+ // For Sets, find the index in the drafts_ map82+ const setParent = state.parent_ as SetState83+ key = Array.from(setParent.drafts_.keys()).indexOf(state.key_)84+ } else {85+ key = state.key_ as string | number86+ }87+88+ // Step 4: Validate key still exists in parent89+ if (!((isSet && parentCopy.size > key) || has(parentCopy, key))) {90+ return null // Key deleted91+ }92+93+ // Step 5: Add key to path94+ path.push(key)95+ }96+97+ // Step 6: Recurse to parent if exists98+ if (state.parent_) {99+ return getPath(state.parent_, path)100+ }101+102+ // Step 7: At root - reverse path and validate103+ path.reverse()104+105+ try {106+ // Validate path can be resolved from ROOT107+ resolvePath(state.copy_, path)108+ } catch (e) {109+ return null // Path invalid110+ }111+112+ return path113+ }114+115+ // NEW: Add resolvePath helper function116+ function resolvePath(base: any, path: PatchPath): any {117+ let current = base118+ for (let i = 0; i < path.length - 1; i++) {119+ const key = path[i]120+ current = get(current, key)121+ if (!isObjectish(current) || current === null) {122+ throw new Error(`Cannot resolve path at '${path.join("/")}'`)123+ }124+ }125+ return current126+ }127+128 const REPLACE = "replace"129 const ADD = "add"130 const REMOVE = "remove"131 132 function generatePatches_(133 state: ImmerState,134 basePath: PatchPath,48- patches: Patch[],49- inversePatches: Patch[]135+ scope: ImmerScope136 ): void {137+ if (state.scope_.processedForPatches_.has(state)) {138+ return139+ }140+141+ state.scope_.processedForPatches_.add(state)142+143+ const {patches_, inversePatches_} = scope144+145 switch (state.type_) {146 case ArchType.Object:147 case ArchType.Map:148 return generatePatchesFromAssigned(149 state,150 basePath,57- patches,58- inversePatches151+ patches_!,152+ inversePatches_!153 )154 case ArchType.Array:61- return generateArrayPatches(state, basePath, patches, inversePatches)155+ return generateArrayPatches(156+ state,157+ basePath,158+ patches_!,159+ inversePatches_!160+ )161 case ArchType.Set:162 return generateSetPatches(163 (state as any) as SetState,164 basePath,66- patches,67- inversePatches165+ patches_!,166+ inversePatches_!167 )168 }169 }170 14 unmodified lines185 }186 187 // Process replaced indices.188 for (let i = 0; i < base_.length; i++) {90- if (assigned_[i] && copy_[i] !== base_[i]) {189+ const copiedItem = copy_[i]190+ const baseItem = base_[i]191+ if (assigned_?.get(i.toString()) && copiedItem !== baseItem) {192+ const childState = copiedItem?.[DRAFT_STATE]193+ if (childState && childState.modified_) {194+ // Skip - let the child generate its own patches195+ continue196+ }197 const path = basePath.concat([i])198 patches.push({199 op: REPLACE,200 path,201 // Need to maybe clone it, as it can in fact be the original value202 // due to the base/copy inversion at the start of this function97- value: clonePatchValueIfNeeded(copy_[i])203+ value: clonePatchValueIfNeeded(copiedItem)204 })205 inversePatches.push({206 op: REPLACE,207 path,102- value: clonePatchValueIfNeeded(base_[i])208+ value: clonePatchValueIfNeeded(baseItem)209 })210 }211 }212 23 unmodified lines236 basePath: PatchPath,237 patches: Patch[],238 inversePatches: Patch[]239 ) {134- const {base_, copy_} = state240+ const {base_, copy_, type_} = state241 each(state.assigned_!, (key, assignedValue) => {136- const origValue = get(base_, key)137- const value = get(copy_!, key)242+ const origValue = get(base_, key, type_)243+ const value = get(copy_!, key, type_)244 const op = !assignedValue ? REMOVE : has(base_, key) ? REPLACE : ADD245 if (origValue === value && op === REPLACE) return246 const path = basePath.concat(key as any)141- patches.push(op === REMOVE ? {op, path} : {op, path, value})247+ patches.push(248+ op === REMOVE249+ ? {op, path}250+ : {op, path, value: clonePatchValueIfNeeded(value)}251+ )252 inversePatches.push(253 op === ADD254 ? {op: REMOVE, path}255 : op === REMOVE49 unmodified lines305 306 function generateReplacementPatches_(307 baseValue: any,308 replacement: any,199- patches: Patch[],200- inversePatches: Patch[]309+ scope: ImmerScope310 ): void {311+ const {patches_, inversePatches_} = scope202- patches.push({312+ patches_!.push({313 op: REPLACE,314 path: [],315 value: replacement === NOTHING ? undefined : replacement316 })207- inversePatches.push({317+ inversePatches_!.push({318 op: REPLACE,319 path: [],320 value: baseValue321 })13 unmodified lines335 336 // See #738, avoid prototype pollution337 if (338 (parentType === ArchType.Object || parentType === ArchType.Array) &&229- (p === "__proto__" || p === "constructor")339+ (p === "__proto__" || p === CONSTRUCTOR)340 )341 die(errorOffset + 3)232- if (typeof base === "function" && p === "prototype")233- die(errorOffset + 3)342+ if (isFunction(base) && p === PROTOTYPE) die(errorOffset + 3)343 base = get(base, p)235- if (typeof base !== "object") die(errorOffset + 2, path.join("/"))344+ if (!isObjectish(base)) die(errorOffset + 2, path.join("/"))345 }346 347 const type = getArchtype(base)348 const value = deepClonePatchValue(patch.value) // used to clone patch to ensure original patch is not modified, see #41150 unmodified lines399 // (See failing test when deepClone just returns obj)400 function deepClonePatchValue<T>(obj: T): T401 function deepClonePatchValue(obj: any) {402 if (!isDraftable(obj)) return obj294- if (Array.isArray(obj)) return obj.map(deepClonePatchValue)403+ if (isArray(obj)) return obj.map(deepClonePatchValue)404 if (isMap(obj))405 return new Map(406 Array.from(obj.entries()).map(([k, v]) => [k, deepClonePatchValue(v)])407 )9 unmodified lines417 return deepClonePatchValue(obj)418 } else return obj419 }420 312- loadPlugin("Patches", {421+ loadPlugin(PluginPatches, {422 applyPatches_,423 generatePatches_,315- generateReplacementPatches_424+ generateReplacementPatches_,425+ getPath426 })427 }modified:src/types/types-internal.ts+14 added-1 removed
2 unmodified lines3 ImmerScope,4 ProxyObjectState,5 ProxyArrayState,6 MapState,7- DRAFT_STATE7+ DRAFT_STATE,8+ Patch,9+ PatchPath10 } from "../internal"11 12 export type Objectish = AnyObject | AnyArray | AnyMap | AnySet13 export type ObjectishNoSet = AnyObject | AnyArray | AnyMap15 unmodified lines29 scope_: ImmerScope30 modified_: boolean31 finalized_: boolean32 isManual_: boolean33+ assigned_: Map<any, boolean> | undefined34+ key_?: string | number | symbol35+ callbacks_: ((scope: ImmerScope) => void)[]36+ draftLocations_?: Map<any, (string | number | symbol)[]>37 }38 39 export type ImmerState =40 | ProxyObjectState4 unmodified lines45 // The _internal_ type used for drafts (not to be confused with Draft, which is public facing)46 export type Drafted<Base = any, T extends ImmerState = ImmerState> = {47 [DRAFT_STATE]: T48 } & Base49+50+export type GeneratePatches = (51+ state: ImmerState,52+ basePath: PatchPath,53+ patches: Patch[],54+ inversePatches: Patch[]55+) => voidmodified:src/utils/common.ts+93 added-52 removed
10 unmodified lines11 die,12 StrictMode13 } from "../internal"14 15-export const getPrototypeOf = Object.getPrototypeOf15+const O = Object16 17+export const getPrototypeOf = O.getPrototypeOf18+19+export const CONSTRUCTOR = "constructor"20+export const PROTOTYPE = "prototype"21+22+export const CONFIGURABLE = "configurable"23+export const ENUMERABLE = "enumerable"24+export const WRITABLE = "writable"25+export const VALUE = "value"26+27 /** Returns true if the given value is an Immer draft */28 /*#__PURE__*/19-export function isDraft(value: any): boolean {20- return !!value && !!value[DRAFT_STATE]21-}29+export let isDraft = (value: any): boolean => !!value && !!value[DRAFT_STATE]30 31 /** Returns true if the given value can be drafted by Immer */32 /*#__PURE__*/33 export function isDraftable(value: any): boolean {34 if (!value) return false35 return (36 isPlainObject(value) ||29- Array.isArray(value) ||37+ isArray(value) ||38 !!value[DRAFTABLE] ||31- !!value.constructor?.[DRAFTABLE] ||39+ !!value[CONSTRUCTOR]?.[DRAFTABLE] ||40 isMap(value) ||41 isSet(value)42 )43 }44 37-const objectCtorString = Object.prototype.constructor.toString()45+const objectCtorString = O[PROTOTYPE][CONSTRUCTOR].toString()46 const cachedCtorStrings = new WeakMap()47 /*#__PURE__*/48 export function isPlainObject(value: any): boolean {41- if (!value || typeof value !== "object") return false42- const proto = Object.getPrototypeOf(value)43- if (proto === null || proto === Object.prototype) return true49+ if (!value || !isObjectish(value)) return false50+ const proto = getPrototypeOf(value)51+ if (proto === null || proto === O[PROTOTYPE]) return true52 45- const Ctor =46- Object.hasOwnProperty.call(proto, "constructor") && proto.constructor53+ const Ctor = O.hasOwnProperty.call(proto, CONSTRUCTOR) && proto[CONSTRUCTOR]54 if (Ctor === Object) return true55 49- if (typeof Ctor !== "function") return false56+ if (!isFunction(Ctor)) return false57 58 let ctorString = cachedCtorStrings.get(Ctor)59 if (ctorString === undefined) {60 ctorString = Function.toString.call(Ctor)28 unmodified lines89 export function each(obj: any, iter: any, strict: boolean = true) {90 if (getArchtype(obj) === ArchType.Object) {91 // If strict, we do a full iteration including symbols and non-enumerable properties92 // Otherwise, we only iterate enumerable string properties for performance86- const keys = strict ? Reflect.ownKeys(obj) : Object.keys(obj)93+ const keys = strict ? Reflect.ownKeys(obj) : O.keys(obj)94 keys.forEach(key => {95 iter(key, obj[key], obj)96 })97 } else {5 unmodified lines103 export function getArchtype(thing: any): ArchType {104 const state: undefined | ImmerState = thing[DRAFT_STATE]105 return state106 ? state.type_100- : Array.isArray(thing)107+ : isArray(thing)108 ? ArchType.Array109 : isMap(thing)110 ? ArchType.Map111 : isSet(thing)1 unmodified line113 : ArchType.Object114 }115 116 /*#__PURE__*/110-export function has(thing: any, prop: PropertyKey): boolean {111- return getArchtype(thing) === ArchType.Map117+export let has = (118+ thing: any,119+ prop: PropertyKey,120+ type = getArchtype(thing)121+): boolean =>122+ type === ArchType.Map123 ? thing.has(prop)113- : Object.prototype.hasOwnProperty.call(thing, prop)114-}124+ : O[PROTOTYPE].hasOwnProperty.call(thing, prop)125 126 /*#__PURE__*/117-export function get(thing: AnyMap | AnyObject, prop: PropertyKey): any {127+export let get = (128+ thing: AnyMap | AnyObject,129+ prop: PropertyKey,130+ type = getArchtype(thing)131+): any =>132 // @ts-ignore119- return getArchtype(thing) === ArchType.Map ? thing.get(prop) : thing[prop]120-}133+ type === ArchType.Map ? thing.get(prop) : thing[prop]134 135 /*#__PURE__*/123-export function set(thing: any, propOrOldValue: PropertyKey, value: any) {124- const t = getArchtype(thing)125- if (t === ArchType.Map) thing.set(propOrOldValue, value)126- else if (t === ArchType.Set) {136+export let set = (137+ thing: any,138+ propOrOldValue: PropertyKey,139+ value: any,140+ type = getArchtype(thing)141+) => {142+ if (type === ArchType.Map) thing.set(propOrOldValue, value)143+ else if (type === ArchType.Set) {144 thing.add(value)145 } else thing[propOrOldValue] = value146 }147 6 unmodified lines154 return x !== x && y !== y155 }156 }157 158+export let isArray = Array.isArray159+160 /*#__PURE__*/142-export function isMap(target: any): target is AnyMap {143- return target instanceof Map144-}161+export let isMap = (target: any): target is AnyMap => target instanceof Map162 163 /*#__PURE__*/147-export function isSet(target: any): target is AnySet {148- return target instanceof Set164+export let isSet = (target: any): target is AnySet => target instanceof Set165+166+export let isObjectish = (target: any) => typeof target === "object"167+168+export let isFunction = (target: any): target is Function =>169+ typeof target === "function"170+171+export let isBoolean = (target: any): target is boolean =>172+ typeof target === "boolean"173+174+export let getProxyDraft = <T extends any>(value: T): ImmerState | null => {175+ if (!isObjectish(value)) return null176+ return (value as {[DRAFT_STATE]: any})?.[DRAFT_STATE]177 }178+179 /*#__PURE__*/151-export function latest(state: ImmerState): any {152- return state.copy_ || state.base_180+export let latest = (state: ImmerState): any => state.copy_ || state.base_181+182+export let getValue = <T extends object>(value: T): T => {183+ const proxyDraft = getProxyDraft(value)184+ return proxyDraft ? proxyDraft.copy_ ?? proxyDraft.base_ : value185 }186 187+export let getFinalValue = (state: ImmerState): any =>188+ state.modified_ ? state.copy_ : state.base_189+190 /*#__PURE__*/191 export function shallowCopy(base: any, strict: StrictMode) {192 if (isMap(base)) {193 return new Map(base)194 }195 if (isSet(base)) {196 return new Set(base)197 }163- if (Array.isArray(base)) return Array.prototype.slice.call(base)198+ if (isArray(base)) return Array[PROTOTYPE].slice.call(base)199 200 const isPlain = isPlainObject(base)201 202 if (strict === true || (strict === "class_only" && !isPlain)) {203 // Perform a strict copy169- const descriptors = Object.getOwnPropertyDescriptors(base)204+ const descriptors = O.getOwnPropertyDescriptors(base)205 delete descriptors[DRAFT_STATE as any]206 let keys = Reflect.ownKeys(descriptors)207 for (let i = 0; i < keys.length; i++) {208 const key: any = keys[i]209 const desc = descriptors[key]175- if (desc.writable === false) {176- desc.writable = true177- desc.configurable = true210+ if (desc[WRITABLE] === false) {211+ desc[WRITABLE] = true212+ desc[CONFIGURABLE] = true213 }214 // like object.assign, we will read any _own_, get/set accessors. This helps in dealing215 // with libraries that trap values, like mobx or vue216 // unlike object.assign, non-enumerables will be copied as well217 if (desc.get || desc.set)218 descriptors[key] = {184- configurable: true,185- writable: true, // could live with !!desc.set as well here...186- enumerable: desc.enumerable,187- value: base[key]219+ [CONFIGURABLE]: true,220+ [WRITABLE]: true, // could live with !!desc.set as well here...221+ [ENUMERABLE]: desc[ENUMERABLE],222+ [VALUE]: base[key]223 }224 }190- return Object.create(getPrototypeOf(base), descriptors)225+ return O.create(getPrototypeOf(base), descriptors)226 } else {227 // perform a sloppy copy228 const proto = getPrototypeOf(base)229 if (proto !== null && isPlain) {230 return {...base} // assumption: better inner class optimization than the assign below231 }197- const obj = Object.create(proto)198- return Object.assign(obj, base)232+ const obj = O.create(proto)233+ return O.assign(obj, base)234 }235 }236 237 /**4 unmodified lines242 * @param deep243 */244 export function freeze<T>(obj: T, deep?: boolean): T245 export function freeze<T>(obj: any, deep: boolean = false): T {211- if (isFrozen(obj) || isDraft(obj) || !isDraftable(obj)) return obj246+ if (isFrozen(obj) || isDraft(obj)) return obj247 if (getArchtype(obj) > 1 /* Map or Set */) {213- Object.defineProperties(obj, {248+ O.defineProperties(obj, {249 set: dontMutateMethodOverride,250 add: dontMutateMethodOverride,251 clear: dontMutateMethodOverride,252 delete: dontMutateMethodOverride253 })254 }220- Object.freeze(obj)255+ O.freeze(obj)256 if (deep)257 // See #590, don't recurse into non-enumerable / Symbol properties when freezing258 // So use Object.values (only string-like, enumerables) instead of each()224- Object.values(obj).forEach(value => freeze(value, true))259+ each(260+ obj,261+ (_key, value) => {262+ freeze(value, true)263+ },264+ false265+ )266 return obj267 }268 269 function dontMutateFrozenCollections() {270 die(2)271 }272 273 const dontMutateMethodOverride = {233- value: dontMutateFrozenCollections274+ [VALUE]: dontMutateFrozenCollections275 }276 277 export function isFrozen(obj: any): boolean {278 // Fast path: primitives and null/undefined are always "frozen"238- if (obj === null || typeof obj !== "object") return true239- return Object.isFrozen(obj)279+ if (obj === null || !isObjectish(obj)) return true280+ return O.isFrozen(obj)281 }modified:src/utils/errors.ts+3 added-1 removed
1+import {isFunction} from "../internal"2+3 export const errors =4 process.env.NODE_ENV !== "production"5 ? [6 // All error codes, starting by 0:33 unmodified lines40 41 export function die(error: number, ...args: any[]): never {42 if (process.env.NODE_ENV !== "production") {43 const e = errors[error]42- const msg = typeof e === "function" ? e.apply(null, args as any) : e44+ const msg = isFunction(e) ? e.apply(null, args as any) : e45 throw new Error(`[Immer] ${msg}`)46 }47 throw new Error(48 `[Immer] minified error nr: ${error}. Full error at: https://bit.ly/3cXEKWf`2 unmodified linesmodified:src/utils/plugins.ts+31 added-21 removed
4 unmodified lines5 ImmerBaseState,6 AnyMap,7 AnySet,8 ArchType,9- die9+ die,10+ ImmerScope11 } from "../internal"12 13+export const PluginMapSet = "MapSet"14+export const PluginPatches = "Patches"15+16+export type PatchesPlugin = {17+ generatePatches_(18+ state: ImmerState,19+ basePath: PatchPath,20+ rootScope: ImmerScope21+ ): void22+ generateReplacementPatches_(23+ base: any,24+ replacement: any,25+ rootScope: ImmerScope26+ ): void27+ applyPatches_<T>(draft: T, patches: readonly Patch[]): T28+ getPath: (state: ImmerState) => PatchPath | null29+}30+31+export type MapSetPlugin = {32+ proxyMap_<T extends AnyMap>(target: T, parent?: ImmerState): [T, ImmerState]33+ proxySet_<T extends AnySet>(target: T, parent?: ImmerState): [T, ImmerState]34+ fixSetContents: (state: ImmerState) => void35+}36+37 /** Plugin utilities */38 const plugins: {14- Patches?: {15- generatePatches_(16- state: ImmerState,17- basePath: PatchPath,18- patches: Patch[],19- inversePatches: Patch[]20- ): void21- generateReplacementPatches_(22- base: any,23- replacement: any,24- patches: Patch[],25- inversePatches: Patch[]26- ): void27- applyPatches_<T>(draft: T, patches: readonly Patch[]): T28- }29- MapSet?: {30- proxyMap_<T extends AnyMap>(target: T, parent?: ImmerState): T31- proxySet_<T extends AnySet>(target: T, parent?: ImmerState): T32- }39+ Patches?: PatchesPlugin40+ MapSet?: MapSetPlugin41 } = {}42 43 type Plugins = typeof plugins44 7 unmodified lines52 // @ts-ignore53 return plugin54 }55 56+export let isPluginLoaded = <K extends keyof Plugins>(pluginKey: K): boolean =>57+ !!plugins[pluginKey]58+59 export function loadPlugin<K extends keyof Plugins>(60 pluginKey: K,61 implementation: Plugins[K]62 ): void {3 unmodified lines66 67 export interface MapState extends ImmerBaseState {68 type_: ArchType.Map69 copy_: AnyMap | undefined59- assigned_: Map<any, boolean> | undefined70 base_: AnyMap71 revoked_: boolean72 draft_: Drafted<AnyMap, MapState>73 }13 unmodified linesmodified:src/immer.ts+2 added-6 removed
108 unmodified lines109 * to an draft type and make TypeScript happy110 *111 * @param value112 */113-export function castDraft<T>(value: T): Draft<T> {114- return value as any115-}113+export let castDraft = <T>(value: T): Draft<T> => value as any114 115 /**116 * This function is actually a no-op, but can be used to cast a mutable type117 * to an immutable type and make TypeScript happy118 * @param value119 */122-export function castImmutable<T>(value: T): Immutable<T> {123- return value as any124-}120+export let castImmutable = <T>(value: T): Immutable<T> => value as any121 122 export {Immer}123 124 export {enablePatches} from "./plugins/patches"1 unmodified line