Skip to content
Myr

separating plugins from core

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Michel Weststrate · committed by Michel Weststrate · parent c7e9de8 · Browse files · 13 files+1064 added−951 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

13 files+1064 added−951 removed

  • other:+1064 added−951 removed

13 files+1064 added−951 removed

added:src/plugins/es5/es5.ts+286 added
1"use strict"2import {3 each,4 has,5 is,6 isDraft,7 isDraftable,8 isEnumerable,9 shallowCopy,10 latest,11 createHiddenProperty,12 ImmerScope,13 ImmerState,14 Drafted,15 Objectish,16 ProxyType,17 DRAFT_STATE,18 loadPlugin,19 ES5ArrayState,20 ES5ObjectState,21 assertUnrevoked22} from "../../internal"2324type ES5State = ES5ArrayState | ES5ObjectState2526export function willFinalizeES5(27 scope: ImmerScope,28 result: any,29 isReplaced: boolean30) {31 scope.drafts!.forEach(draft => {32 draft[DRAFT_STATE].finalizing = true33 })34 if (!isReplaced) {35 if (scope.patches) {36 markChangesRecursively(scope.drafts![0])37 }38 // This is faster when we don't care about which attributes changed.39 markChangesSweep(scope.drafts)40 }41 // When a child draft is returned, look for changes.42 else if (isDraft(result) && result[DRAFT_STATE].scope === scope) {43 markChangesSweep(scope.drafts)44 }45}4647export function createES5Proxy<T>(48 base: T,49 parent?: ImmerState50): Drafted<T, ES5ObjectState | ES5ArrayState> {51 const isArray = Array.isArray(base)52 const draft = clonePotentialDraft(base)5354 each(draft, prop => {55 proxyProperty(draft, prop, isArray || isEnumerable(base, prop))56 })5758 const state: ES5ObjectState | ES5ArrayState = {59 type: isArray ? ProxyType.ES5Array : (ProxyType.ES5Object as any),60 scope: parent ? parent.scope : ImmerScope.current!,61 modified: false,62 finalizing: false,63 finalized: false,64 assigned: {},65 parent,66 base,67 draft,68 copy: null,69 revoked: false,70 isManual: false71 }7273 createHiddenProperty(draft, DRAFT_STATE, state)74 return draft75}7677// Access a property without creating an Immer draft.78function peek(draft: Drafted, prop: PropertyKey) {79 const state = draft[DRAFT_STATE]80 if (state && !state.finalizing) {81 state.finalizing = true82 const value = draft[prop]83 state.finalizing = false84 return value85 }86 return draft[prop]87}8889function get(state: ES5State, prop: string | number) {90 assertUnrevoked(state)91 const value = peek(latest(state), prop)92 if (state.finalizing) return value93 // Create a draft if the value is unmodified.94 if (value === peek(state.base, prop) && isDraftable(value)) {95 prepareCopy(state)96 // @ts-ignore97 return (state.copy![prop] = state.scope.immer.createProxy(value, state))98 }99 return value100}101102function set(state: ES5State, prop: string | number, value: any) {103 assertUnrevoked(state)104 state.assigned[prop] = true105 if (!state.modified) {106 if (is(value, peek(latest(state), prop))) return107 markChangedES5(state)108 prepareCopy(state)109 }110 // @ts-ignore111 state.copy![prop] = value112}113114export function markChangedES5(state: ImmerState) {115 if (!state.modified) {116 state.modified = true117 if (state.parent) markChangedES5(state.parent)118 }119}120121function prepareCopy(state: ES5State) {122 if (!state.copy) state.copy = clonePotentialDraft(state.base)123}124125function clonePotentialDraft(base: Objectish) {126 const state = base && (base as any)[DRAFT_STATE]127 if (state) {128 state.finalizing = true129 const draft = shallowCopy(state.draft, true)130 state.finalizing = false131 return draft132 }133 return shallowCopy(base)134}135136// property descriptors are recycled to make sure we don't create a get and set closure per property,137// but share them all instead138const descriptors: {[prop: string]: PropertyDescriptor} = {}139140function proxyProperty(141 draft: Drafted<any, ES5State>,142 prop: string | number,143 enumerable: boolean144) {145 let desc = descriptors[prop]146 if (desc) {147 desc.enumerable = enumerable148 } else {149 descriptors[prop] = desc = {150 configurable: true,151 enumerable,152 get(this: any) {153 return get(this[DRAFT_STATE], prop)154 },155 set(this: any, value) {156 set(this[DRAFT_STATE], prop, value)157 }158 }159 }160 Object.defineProperty(draft, prop, desc)161}162163// This looks expensive, but only proxies are visited, and only objects without known changes are scanned.164function markChangesSweep(drafts: Drafted<any, ImmerState>[]) {165 // The natural order of drafts in the `scope` array is based on when they166 // were accessed. By processing drafts in reverse natural order, we have a167 // better chance of processing leaf nodes first. When a leaf node is known to168 // have changed, we can avoid any traversal of its ancestor nodes.169 for (let i = drafts.length - 1; i >= 0; i--) {170 const state = drafts[i][DRAFT_STATE]171 if (!state.modified) {172 switch (state.type) {173 case ProxyType.ES5Array:174 if (hasArrayChanges(state)) markChangedES5(state)175 break176 case ProxyType.ES5Object:177 if (hasObjectChanges(state)) markChangedES5(state)178 break179 }180 }181 }182}183184function markChangesRecursively(object: any) {185 if (!object || typeof object !== "object") return186 const state = object[DRAFT_STATE]187 if (!state) return188 const {base, draft, assigned, type} = state189 if (type === ProxyType.ES5Object) {190 // Look for added keys.191 // TODO: looks quite duplicate to hasObjectChanges,192 // probably there is a faster way to detect changes, as sweep + recurse seems to do some193 // unnecessary work.194 // also: probably we can store the information we detect here, to speed up tree finalization!195 each(draft, key => {196 if ((key as any) === DRAFT_STATE) return197 // The `undefined` check is a fast path for pre-existing keys.198 if (base[key] === undefined && !has(base, key)) {199 assigned[key] = true200 markChangedES5(state)201 } else if (!assigned[key]) {202 // Only untouched properties trigger recursion.203 markChangesRecursively(draft[key])204 }205 })206 // Look for removed keys.207 each(base, key => {208 // The `undefined` check is a fast path for pre-existing keys.209 if (draft[key] === undefined && !has(draft, key)) {210 assigned[key] = false211 markChangedES5(state)212 }213 })214 } else if (type === ProxyType.ES5Array) {215 if (hasArrayChanges(state)) {216 markChangedES5(state)217 assigned.length = true218 }219220 if (draft.length < base.length) {221 for (let i = draft.length; i < base.length; i++) assigned[i] = false222 } else {223 for (let i = base.length; i < draft.length; i++) assigned[i] = true224 }225226 // Minimum count is enough, the other parts has been processed.227 const min = Math.min(draft.length, base.length)228229 for (let i = 0; i < min; i++) {230 // Only untouched indices trigger recursion.231 if (assigned[i] === undefined) markChangesRecursively(draft[i])232 }233 }234}235236function hasObjectChanges(state: ES5ObjectState) {237 const {base, draft} = state238239 // Search for added keys and changed keys. Start at the back, because240 // non-numeric keys are ordered by time of definition on the object.241 const keys = Object.keys(draft)242 for (let i = keys.length - 1; i >= 0; i--) {243 const key = keys[i]244 const baseValue = base[key]245 // The `undefined` check is a fast path for pre-existing keys.246 if (baseValue === undefined && !has(base, key)) {247 return true248 }249 // Once a base key is deleted, future changes go undetected, because its250 // descriptor is erased. This branch detects any missed changes.251 else {252 const value = draft[key]253 const state = value && value[DRAFT_STATE]254 if (state ? state.base !== baseValue : !is(value, baseValue)) {255 return true256 }257 }258 }259260 // At this point, no keys were added or changed.261 // Compare key count to determine if keys were deleted.262 return keys.length !== Object.keys(base).length263}264265function hasArrayChanges(state: ES5ArrayState) {266 const {draft} = state267 if (draft.length !== state.base.length) return true268 // See #116269 // If we first shorten the length, our array interceptors will be removed.270 // If after that new items are added, result in the same original length,271 // those last items will have no intercepting property.272 // So if there is no own descriptor on the last position, we know that items were removed and added273 // N.B.: splice, unshift, etc only shift values around, but not prop descriptors, so we only have to check274 // the last one275 const descriptor = Object.getOwnPropertyDescriptor(draft, draft.length - 1)276 // descriptor can be null, but only for newly created sparse arrays, eg. new Array(10)277 if (descriptor && !descriptor.get) return true278 // For all other cases, we don't have to compare, as they would have been picked up by the index setters279 return false280}281282loadPlugin("es5", {283 createES5Proxy,284 markChangedES5,285 willFinalizeES5286})
added:src/plugins/mapset/extends.ts+24 added
added:src/plugins/mapset/map.ts+178 added
1import {__extends} from "./extends"2import {proxySet} from "./set"3import {4 ProxyType,5 AnyMap,6 ImmerState,7 DRAFT_STATE,8 ImmerScope,9 latest,10 assertUnrevoked,11 isDraftable,12 iteratorSymbol,13 MapState14} from "../../internal"15import {loadPlugin} from "../../plugins"1617const DraftMap = (function(_super) {18 if (!_super) {19 /* istanbul ignore next */20 throw new Error("Map is not polyfilled")21 }22 __extends(DraftMap, _super)23 // Create class manually, cause #50224 function DraftMap(this: any, target: AnyMap, parent?: ImmerState): any {25 this[DRAFT_STATE] = {26 type: ProxyType.Map,27 parent,28 scope: parent ? parent.scope : ImmerScope.current!,29 modified: false,30 finalized: false,31 copy: undefined,32 assigned: undefined,33 base: target,34 draft: this as any,35 isManual: false,36 revoked: false37 }38 return this39 }40 const p = DraftMap.prototype4142 // TODO: smaller build size if we create a util for Object.defineProperty43 Object.defineProperty(p, "size", {44 get: function() {45 return latest(this[DRAFT_STATE]).size46 },47 enumerable: true,48 configurable: true49 })5051 p.has = function(key: any): boolean {52 return latest(this[DRAFT_STATE]).has(key)53 }5455 p.set = function(key: any, value: any) {56 const state = this[DRAFT_STATE]57 assertUnrevoked(state)58 if (latest(state).get(key) !== value) {59 prepareCopy(state)60 state.scope.immer.markChanged(state)61 state.assigned!.set(key, true)62 state.copy!.set(key, value)63 state.assigned!.set(key, true)64 }65 return this66 }6768 p.delete = function(key: any): boolean {69 if (!this.has(key)) {70 return false71 }7273 const state = this[DRAFT_STATE]74 assertUnrevoked(state)75 prepareCopy(state)76 state.scope.immer.markChanged(state)77 state.assigned!.set(key, false)78 state.copy!.delete(key)79 return true80 }8182 p.clear = function() {83 const state = this[DRAFT_STATE]84 assertUnrevoked(state)85 prepareCopy(state)86 state.scope.immer.markChanged(state)87 state.assigned = new Map()88 return state.copy!.clear()89 }9091 p.forEach = function(92 cb: (value: any, key: any, self: any) => void,93 thisArg?: any94 ) {95 const state = this[DRAFT_STATE]96 latest(state).forEach((_value: any, key: any, _map: any) => {97 cb.call(thisArg, this.get(key), key, this)98 })99 }100101 p.get = function(key: any): any {102 const state = this[DRAFT_STATE]103 assertUnrevoked(state)104 const value = latest(state).get(key)105 if (state.finalized || !isDraftable(value)) {106 return value107 }108 if (value !== state.base.get(key)) {109 return value // either already drafted or reassigned110 }111 // despite what it looks, this creates a draft only once, see above condition112 const draft = state.scope.immer.createProxy(value, state)113 prepareCopy(state)114 state.copy!.set(key, draft)115 return draft116 }117118 p.keys = function(): IterableIterator<any> {119 return latest(this[DRAFT_STATE]).keys()120 }121122 p.values = function(): IterableIterator<any> {123 const iterator = this.keys()124 return {125 [iteratorSymbol]: () => this.values(),126 next: () => {127 const r = iterator.next()128 /* istanbul ignore next */129 if (r.done) return r130 const value = this.get(r.value)131 return {132 done: false,133 value134 }135 }136 } as any137 }138139 p.entries = function(): IterableIterator<[any, any]> {140 const iterator = this.keys()141 return {142 [iteratorSymbol]: () => this.entries(),143 next: () => {144 const r = iterator.next()145 /* istanbul ignore next */146 if (r.done) return r147 const value = this.get(r.value)148 return {149 done: false,150 value: [r.value, value]151 }152 }153 } as any154 }155156 p[iteratorSymbol] = function() {157 return this.entries()158 }159160 return DraftMap161})(Map)162163export function proxyMap<T extends AnyMap>(164 target: T,165 parent?: ImmerState166): T & {[DRAFT_STATE]: MapState} {167 // @ts-ignore168 return new DraftMap(target, parent)169}170171function prepareCopy(state: MapState) {172 if (!state.copy) {173 state.assigned = new Map()174 state.copy = new Map(state.base)175 }176}177178loadPlugin("mapset", {proxyMap, proxySet})
added:src/plugins/mapset/set.ts+157 added
1import {__extends} from "./extends"2import {3 ImmerBaseState,4 ProxyType,5 AnySet,6 Drafted,7 ImmerState,8 DRAFT_STATE,9 ImmerScope,10 latest,11 assertUnrevoked,12 iteratorSymbol,13 isDraftable,14 SetState15} from "../../internal"1617const DraftSet = (function(_super) {18 if (!_super) {19 /* istanbul ignore next */20 throw new Error("Set is not polyfilled")21 }22 __extends(DraftSet, _super)23 // Create class manually, cause #50224 function DraftSet(this: any, target: AnySet, parent?: ImmerState) {25 this[DRAFT_STATE] = {26 type: ProxyType.Set,27 parent,28 scope: parent ? parent.scope : ImmerScope.current!,29 modified: false,30 finalized: false,31 copy: undefined,32 base: target,33 draft: this,34 drafts: new Map(),35 revoked: false,36 isManual: false37 }38 return this39 }40 const p = DraftSet.prototype4142 Object.defineProperty(p, "size", {43 get: function() {44 return latest(this[DRAFT_STATE]).size45 },46 enumerable: true,47 configurable: true48 })4950 p.has = function(value: any): boolean {51 const state = this[DRAFT_STATE]52 assertUnrevoked(state)53 // bit of trickery here, to be able to recognize both the value, and the draft of its value54 if (!state.copy) {55 return state.base.has(value)56 }57 if (state.copy.has(value)) return true58 if (state.drafts.has(value) && state.copy.has(state.drafts.get(value)))59 return true60 return false61 }6263 p.add = function(value: any): any {64 const state = this[DRAFT_STATE]65 assertUnrevoked(state)66 if (state.copy) {67 state.copy.add(value)68 } else if (!state.base.has(value)) {69 prepareCopy(state)70 state.scope.immer.markChanged(state)71 state.copy!.add(value)72 }73 return this74 }7576 p.delete = function(value: any): any {77 if (!this.has(value)) {78 return false79 }8081 const state = this[DRAFT_STATE]82 assertUnrevoked(state)83 prepareCopy(state)84 state.scope.immer.markChanged(state)85 return (86 state.copy!.delete(value) ||87 (state.drafts.has(value)88 ? state.copy!.delete(state.drafts.get(value))89 : /* istanbul ignore next */ false)90 )91 }9293 p.clear = function() {94 const state = this[DRAFT_STATE]95 assertUnrevoked(state)96 prepareCopy(state)97 state.scope.immer.markChanged(state)98 return state.copy!.clear()99 }100101 p.values = function(): IterableIterator<any> {102 const state = this[DRAFT_STATE]103 assertUnrevoked(state)104 prepareCopy(state)105 return state.copy!.values()106 }107108 p.entries = function entries(): IterableIterator<[any, any]> {109 const state = this[DRAFT_STATE]110 assertUnrevoked(state)111 prepareCopy(state)112 return state.copy!.entries()113 }114115 p.keys = function(): IterableIterator<any> {116 return this.values()117 }118119 p[iteratorSymbol] = function() {120 return this.values()121 }122123 p.forEach = function forEach(cb: any, thisArg?: any) {124 const iterator = this.values()125 let result = iterator.next()126 while (!result.done) {127 cb.call(thisArg, result.value, result.value, this)128 result = iterator.next()129 }130 }131132 return DraftSet133})(Set)134135export function proxySet<T extends AnySet>(136 target: T,137 parent?: ImmerState138): T & {[DRAFT_STATE]: SetState} {139 // @ts-ignore140 return new DraftSet(target, parent)141}142143function prepareCopy(state: SetState) {144 if (!state.copy) {145 // create drafts for all entries to preserve insertion order146 state.copy = new Set()147 state.base.forEach(value => {148 if (isDraftable(value)) {149 const draft = state.scope.immer.createProxy(value, state)150 state.drafts.set(value, draft)151 state.copy!.add(draft)152 } else {153 state.copy!.add(value)154 }155 })156 }157}
added:src/plugins/patches/patches.ts+265 added
1import {2 get,3 each,4 has,5 die,6 getArchtype,7 ImmerState,8 Patch,9 ProxyType,10 SetState,11 ES5ArrayState,12 ProxyArrayState,13 MapState,14 ES5ObjectState,15 ProxyObjectState,16 Archtype,17 isMap,18 isSet,19 PatchPath,20 loadPlugin21} from "../../internal"2223export function generatePatches(24 state: ImmerState,25 basePath: PatchPath,26 patches: Patch[],27 inversePatches: Patch[]28): void {29 switch (state.type) {30 case ProxyType.ProxyObject:31 case ProxyType.ES5Object:32 case ProxyType.Map:33 return generatePatchesFromAssigned(34 state,35 basePath,36 patches,37 inversePatches38 )39 case ProxyType.ES5Array:40 case ProxyType.ProxyArray:41 return generateArrayPatches(state, basePath, patches, inversePatches)42 case ProxyType.Set:43 return generateSetPatches(44 (state as any) as SetState,45 basePath,46 patches,47 inversePatches48 )49 }50}5152function generateArrayPatches(53 state: ES5ArrayState | ProxyArrayState,54 basePath: PatchPath,55 patches: Patch[],56 inversePatches: Patch[]57) {58 let {base, assigned, copy} = state59 /* istanbul ignore next */60 if (!copy) die()6162 // Reduce complexity by ensuring `base` is never longer.63 if (copy.length < base.length) {64 // @ts-ignore65 ;[base, copy] = [copy, base]66 ;[patches, inversePatches] = [inversePatches, patches]67 }6869 const delta = copy.length - base.length7071 // Find the first replaced index.72 let start = 073 while (base[start] === copy[start] && start < base.length) {74 ++start75 }7677 // Find the last replaced index. Search from the end to optimize splice patches.78 let end = base.length79 while (end > start && base[end - 1] === copy[end + delta - 1]) {80 --end81 }8283 // Process replaced indices.84 for (let i = start; i < end; ++i) {85 if (assigned[i] && copy[i] !== base[i]) {86 const path = basePath.concat([i])87 patches.push({88 op: "replace",89 path,90 value: copy[i]91 })92 inversePatches.push({93 op: "replace",94 path,95 value: base[i]96 })97 }98 }99100 const replaceCount = patches.length101102 // Process added indices.103 for (let i = end + delta - 1; i >= end; --i) {104 const path = basePath.concat([i])105 patches[replaceCount + i - end] = {106 op: "add",107 path,108 value: copy[i]109 }110 inversePatches.push({111 op: "remove",112 path113 })114 }115}116117// This is used for both Map objects and normal objects.118function generatePatchesFromAssigned(119 state: MapState | ES5ObjectState | ProxyObjectState,120 basePath: PatchPath,121 patches: Patch[],122 inversePatches: Patch[]123) {124 const {base, copy} = state125 each(state.assigned!, (key, assignedValue) => {126 const origValue = get(base, key)127 const value = get(copy!, key)128 const op = !assignedValue ? "remove" : has(base, key) ? "replace" : "add"129 if (origValue === value && op === "replace") return130 const path = basePath.concat(key as any)131 patches.push(op === "remove" ? {op, path} : {op, path, value})132 inversePatches.push(133 op === "add"134 ? {op: "remove", path}135 : op === "remove"136 ? {op: "add", path, value: origValue}137 : {op: "replace", path, value: origValue}138 )139 })140}141142function generateSetPatches(143 state: SetState,144 basePath: PatchPath,145 patches: Patch[],146 inversePatches: Patch[]147) {148 let {base, copy} = state149150 let i = 0151 base.forEach(value => {152 if (!copy!.has(value)) {153 const path = basePath.concat([i])154 patches.push({155 op: "remove",156 path,157 value158 })159 inversePatches.unshift({160 op: "add",161 path,162 value163 })164 }165 i++166 })167 i = 0168 copy!.forEach(value => {169 if (!base.has(value)) {170 const path = basePath.concat([i])171 patches.push({172 op: "add",173 path,174 value175 })176 inversePatches.unshift({177 op: "remove",178 path,179 value180 })181 }182 i++183 })184}185186export function applyPatches<T>(draft: T, patches: Patch[]): T {187 patches.forEach(patch => {188 const {path, op} = patch189190 /* istanbul ignore next */191 if (!path.length) die()192193 let base: any = draft194 for (let i = 0; i < path.length - 1; i++) {195 base = get(base, path[i])196 if (!base || typeof base !== "object")197 throw new Error("Cannot apply patch, path doesn't resolve: " + path.join("/")) // prettier-ignore198 }199200 const type = getArchtype(base)201 const value = deepClonePatchValue(patch.value) // used to clone patch to ensure original patch is not modified, see #411202 const key = path[path.length - 1]203 switch (op) {204 case "replace":205 switch (type) {206 case Archtype.Map:207 return base.set(key, value)208 /* istanbul ignore next */209 case Archtype.Set:210 throw new Error('Sets cannot have "replace" patches.')211 default:212 // if value is an object, then it's assigned by reference213 // in the following add or remove ops, the value field inside the patch will also be modifyed214 // so we use value from the cloned patch215 // @ts-ignore216 return (base[key] = value)217 }218 case "add":219 switch (type) {220 case Archtype.Array:221 return base.splice(key as any, 0, value)222 case Archtype.Map:223 return base.set(key, value)224 case Archtype.Set:225 return base.add(value)226 default:227 return (base[key] = value)228 }229 case "remove":230 switch (type) {231 case Archtype.Array:232 return base.splice(key as any, 1)233 case Archtype.Map:234 return base.delete(key)235 case Archtype.Set:236 return base.delete(patch.value)237 default:238 return delete base[key]239 }240 default:241 throw new Error("Unsupported patch operation: " + op)242 }243 })244245 return draft246}247248// TODO: optimize: this is quite a performance hit, can we detect intelligently when it is needed?249// E.g. auto-draft when new objects from outside are assigned and modified?250// (See failing test when deepClone just returns obj)251function deepClonePatchValue<T>(obj: T): T252function deepClonePatchValue(obj: any) {253 if (!obj || typeof obj !== "object") return obj254 if (Array.isArray(obj)) return obj.map(deepClonePatchValue)255 if (isMap(obj))256 return new Map(257 Array.from(obj.entries()).map(([k, v]) => [k, deepClonePatchValue(v)])258 )259 if (isSet(obj)) return new Set(Array.from(obj).map(deepClonePatchValue))260 const cloned = Object.create(Object.getPrototypeOf(obj))261 for (const key in obj) cloned[key] = deepClonePatchValue(obj[key])262 return cloned263}264265loadPlugin("patches", {applyPatches, generatePatches})
modified:src/common.ts+8 added
208 unmodified lines
209/* istanbul ignore next */210export function die(): never {211 throw new Error("Illegal state, please file a bug")212}213214export function assertUnrevoked(state: any /*ES5State | MapState | SetState*/) {215 if (state.revoked === true)216 throw new Error(217 "Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? " +218 JSON.stringify(latest(state))219 )220}
deleted:src/es5.ts-310 removed
1"use strict"2import {3 each,4 has,5 is,6 isDraft,7 isDraftable,8 isEnumerable,9 shallowCopy,10 latest,11 createHiddenProperty,12 ImmerScope,13 ImmerState,14 Drafted,15 AnyObject,16 Objectish,17 ImmerBaseState,18 AnyArray,19 ProxyType,20 MapState,21 SetState,22 DRAFT_STATE23} from "./internal"2425interface ES5BaseState extends ImmerBaseState {26 finalizing: boolean27 assigned: {[key: string]: any}28 parent?: ImmerState29 revoked: boolean30}3132export interface ES5ObjectState extends ES5BaseState {33 type: ProxyType.ES5Object34 draft: Drafted<AnyObject, ES5ObjectState>35 base: AnyObject36 copy: AnyObject | null37}3839export interface ES5ArrayState extends ES5BaseState {40 type: ProxyType.ES5Array41 draft: Drafted<AnyObject, ES5ArrayState>42 base: AnyArray43 copy: AnyArray | null44}4546type ES5State = ES5ArrayState | ES5ObjectState4748export function willFinalizeES5(49 scope: ImmerScope,50 result: any,51 isReplaced: boolean52) {53 scope.drafts!.forEach(draft => {54 draft[DRAFT_STATE].finalizing = true55 })56 if (!isReplaced) {57 if (scope.patches) {58 markChangesRecursively(scope.drafts![0])59 }60 // This is faster when we don't care about which attributes changed.61 markChangesSweep(scope.drafts)62 }63 // When a child draft is returned, look for changes.64 else if (isDraft(result) && result[DRAFT_STATE].scope === scope) {65 markChangesSweep(scope.drafts)66 }67}6869export function createES5Proxy<T>(70 base: T,71 parent?: ImmerState72): Drafted<T, ES5ObjectState | ES5ArrayState> {73 const isArray = Array.isArray(base)74 const draft = clonePotentialDraft(base)7576 each(draft, prop => {77 proxyProperty(draft, prop, isArray || isEnumerable(base, prop))78 })7980 const state: ES5ObjectState | ES5ArrayState = {81 type: isArray ? ProxyType.ES5Array : (ProxyType.ES5Object as any),82 scope: parent ? parent.scope : ImmerScope.current!,83 modified: false,84 finalizing: false,85 finalized: false,86 assigned: {},87 parent,88 base,89 draft,90 copy: null,91 revoked: false,92 isManual: false93 }9495 createHiddenProperty(draft, DRAFT_STATE, state)96 return draft97}9899// Access a property without creating an Immer draft.100function peek(draft: Drafted, prop: PropertyKey) {101 const state = draft[DRAFT_STATE]102 if (state && !state.finalizing) {103 state.finalizing = true104 const value = draft[prop]105 state.finalizing = false106 return value107 }108 return draft[prop]109}110111function get(state: ES5State, prop: string | number) {112 assertUnrevoked(state)113 const value = peek(latest(state), prop)114 if (state.finalizing) return value115 // Create a draft if the value is unmodified.116 if (value === peek(state.base, prop) && isDraftable(value)) {117 prepareCopy(state)118 // @ts-ignore119 return (state.copy![prop] = state.scope.immer.createProxy(value, state))120 }121 return value122}123124function set(state: ES5State, prop: string | number, value: any) {125 assertUnrevoked(state)126 state.assigned[prop] = true127 if (!state.modified) {128 if (is(value, peek(latest(state), prop))) return129 markChangedES5(state)130 prepareCopy(state)131 }132 // @ts-ignore133 state.copy![prop] = value134}135136export function markChangedES5(state: ImmerState) {137 if (!state.modified) {138 state.modified = true139 if (state.parent) markChangedES5(state.parent)140 }141}142143function prepareCopy(state: ES5State) {144 if (!state.copy) state.copy = clonePotentialDraft(state.base)145}146147function clonePotentialDraft(base: Objectish) {148 const state = base && (base as any)[DRAFT_STATE]149 if (state) {150 state.finalizing = true151 const draft = shallowCopy(state.draft, true)152 state.finalizing = false153 return draft154 }155 return shallowCopy(base)156}157158// property descriptors are recycled to make sure we don't create a get and set closure per property,159// but share them all instead160const descriptors: {[prop: string]: PropertyDescriptor} = {}161162function proxyProperty(163 draft: Drafted<any, ES5State>,164 prop: string | number,165 enumerable: boolean166) {167 let desc = descriptors[prop]168 if (desc) {169 desc.enumerable = enumerable170 } else {171 descriptors[prop] = desc = {172 configurable: true,173 enumerable,174 get(this: any) {175 return get(this[DRAFT_STATE], prop)176 },177 set(this: any, value) {178 set(this[DRAFT_STATE], prop, value)179 }180 }181 }182 Object.defineProperty(draft, prop, desc)183}184185export function assertUnrevoked(state: ES5State | MapState | SetState) {186 if (state.revoked === true)187 throw new Error(188 "Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? " +189 JSON.stringify(latest(state))190 )191}192193// This looks expensive, but only proxies are visited, and only objects without known changes are scanned.194function markChangesSweep(drafts: Drafted<any, ImmerState>[]) {195 // The natural order of drafts in the `scope` array is based on when they196 // were accessed. By processing drafts in reverse natural order, we have a197 // better chance of processing leaf nodes first. When a leaf node is known to198 // have changed, we can avoid any traversal of its ancestor nodes.199 for (let i = drafts.length - 1; i >= 0; i--) {200 const state = drafts[i][DRAFT_STATE]201 if (!state.modified) {202 switch (state.type) {203 case ProxyType.ES5Array:204 if (hasArrayChanges(state)) markChangedES5(state)205 break206 case ProxyType.ES5Object:207 if (hasObjectChanges(state)) markChangedES5(state)208 break209 }210 }211 }212}213214function markChangesRecursively(object: any) {215 if (!object || typeof object !== "object") return216 const state = object[DRAFT_STATE]217 if (!state) return218 const {base, draft, assigned, type} = state219 if (type === ProxyType.ES5Object) {220 // Look for added keys.221 // TODO: looks quite duplicate to hasObjectChanges,222 // probably there is a faster way to detect changes, as sweep + recurse seems to do some223 // unnecessary work.224 // also: probably we can store the information we detect here, to speed up tree finalization!225 each(draft, key => {226 if ((key as any) === DRAFT_STATE) return227 // The `undefined` check is a fast path for pre-existing keys.228 if (base[key] === undefined && !has(base, key)) {229 assigned[key] = true230 markChangedES5(state)231 } else if (!assigned[key]) {232 // Only untouched properties trigger recursion.233 markChangesRecursively(draft[key])234 }235 })236 // Look for removed keys.237 each(base, key => {238 // The `undefined` check is a fast path for pre-existing keys.239 if (draft[key] === undefined && !has(draft, key)) {240 assigned[key] = false241 markChangedES5(state)242 }243 })244 } else if (type === ProxyType.ES5Array) {245 if (hasArrayChanges(state)) {246 markChangedES5(state)247 assigned.length = true248 }249250 if (draft.length < base.length) {251 for (let i = draft.length; i < base.length; i++) assigned[i] = false252 } else {253 for (let i = base.length; i < draft.length; i++) assigned[i] = true254 }255256 // Minimum count is enough, the other parts has been processed.257 const min = Math.min(draft.length, base.length)258259 for (let i = 0; i < min; i++) {260 // Only untouched indices trigger recursion.261 if (assigned[i] === undefined) markChangesRecursively(draft[i])262 }263 }264}265266function hasObjectChanges(state: ES5ObjectState) {267 const {base, draft} = state268269 // Search for added keys and changed keys. Start at the back, because270 // non-numeric keys are ordered by time of definition on the object.271 const keys = Object.keys(draft)272 for (let i = keys.length - 1; i >= 0; i--) {273 const key = keys[i]274 const baseValue = base[key]275 // The `undefined` check is a fast path for pre-existing keys.276 if (baseValue === undefined && !has(base, key)) {277 return true278 }279 // Once a base key is deleted, future changes go undetected, because its280 // descriptor is erased. This branch detects any missed changes.281 else {282 const value = draft[key]283 const state = value && value[DRAFT_STATE]284 if (state ? state.base !== baseValue : !is(value, baseValue)) {285 return true286 }287 }288 }289290 // At this point, no keys were added or changed.291 // Compare key count to determine if keys were deleted.292 return keys.length !== Object.keys(base).length293}294295function hasArrayChanges(state: ES5ArrayState) {296 const {draft} = state297 if (draft.length !== state.base.length) return true298 // See #116299 // If we first shorten the length, our array interceptors will be removed.300 // If after that new items are added, result in the same original length,301 // those last items will have no intercepting property.302 // So if there is no own descriptor on the last position, we know that items were removed and added303 // N.B.: splice, unshift, etc only shift values around, but not prop descriptors, so we only have to check304 // the last one305 const descriptor = Object.getOwnPropertyDescriptor(draft, draft.length - 1)306 // descriptor can be null, but only for newly created sparse arrays, eg. new Array(10)307 if (descriptor && !descriptor.get) return true308 // For all other cases, we don't have to compare, as they would have been picked up by the index setters309 return false310}
deleted:src/extends.ts-24 removed
modified:src/internal.ts+1 added-5 removed
deleted:src/map.ts-184 removed
1import {2 __extends,3 ImmerBaseState,4 ProxyType,5 AnyMap,6 Drafted,7 ImmerState,8 DRAFT_STATE,9 ImmerScope,10 latest,11 assertUnrevoked,12 isDraftable,13 iteratorSymbol14} from "./internal"1516export interface MapState extends ImmerBaseState {17 type: ProxyType.Map18 copy: AnyMap | undefined19 assigned: Map<any, boolean> | undefined20 base: AnyMap21 revoked: boolean22 draft: Drafted<AnyMap, MapState>23}2425const DraftMap = (function(_super) {26 if (!_super) {27 /* istanbul ignore next */28 throw new Error("Map is not polyfilled")29 }30 __extends(DraftMap, _super)31 // Create class manually, cause #50232 function DraftMap(this: any, target: AnyMap, parent?: ImmerState): any {33 this[DRAFT_STATE] = {34 type: ProxyType.Map,35 parent,36 scope: parent ? parent.scope : ImmerScope.current!,37 modified: false,38 finalized: false,39 copy: undefined,40 assigned: undefined,41 base: target,42 draft: this as any,43 isManual: false,44 revoked: false45 }46 return this47 }48 const p = DraftMap.prototype4950 // TODO: smaller build size if we create a util for Object.defineProperty51 Object.defineProperty(p, "size", {52 get: function() {53 return latest(this[DRAFT_STATE]).size54 },55 enumerable: true,56 configurable: true57 })5859 p.has = function(key: any): boolean {60 return latest(this[DRAFT_STATE]).has(key)61 }6263 p.set = function(key: any, value: any) {64 const state = this[DRAFT_STATE]65 assertUnrevoked(state)66 if (latest(state).get(key) !== value) {67 prepareCopy(state)68 state.scope.immer.markChanged(state)69 state.assigned!.set(key, true)70 state.copy!.set(key, value)71 state.assigned!.set(key, true)72 }73 return this74 }7576 p.delete = function(key: any): boolean {77 if (!this.has(key)) {78 return false79 }8081 const state = this[DRAFT_STATE]82 assertUnrevoked(state)83 prepareCopy(state)84 state.scope.immer.markChanged(state)85 state.assigned!.set(key, false)86 state.copy!.delete(key)87 return true88 }8990 p.clear = function() {91 const state = this[DRAFT_STATE]92 assertUnrevoked(state)93 prepareCopy(state)94 state.scope.immer.markChanged(state)95 state.assigned = new Map()96 return state.copy!.clear()97 }9899 p.forEach = function(100 cb: (value: any, key: any, self: any) => void,101 thisArg?: any102 ) {103 const state = this[DRAFT_STATE]104 latest(state).forEach((_value: any, key: any, _map: any) => {105 cb.call(thisArg, this.get(key), key, this)106 })107 }108109 p.get = function(key: any): any {110 const state = this[DRAFT_STATE]111 assertUnrevoked(state)112 const value = latest(state).get(key)113 if (state.finalized || !isDraftable(value)) {114 return value115 }116 if (value !== state.base.get(key)) {117 return value // either already drafted or reassigned118 }119 // despite what it looks, this creates a draft only once, see above condition120 const draft = state.scope.immer.createProxy(value, state)121 prepareCopy(state)122 state.copy!.set(key, draft)123 return draft124 }125126 p.keys = function(): IterableIterator<any> {127 return latest(this[DRAFT_STATE]).keys()128 }129130 p.values = function(): IterableIterator<any> {131 const iterator = this.keys()132 return {133 [iteratorSymbol]: () => this.values(),134 next: () => {135 const r = iterator.next()136 /* istanbul ignore next */137 if (r.done) return r138 const value = this.get(r.value)139 return {140 done: false,141 value142 }143 }144 } as any145 }146147 p.entries = function(): IterableIterator<[any, any]> {148 const iterator = this.keys()149 return {150 [iteratorSymbol]: () => this.entries(),151 next: () => {152 const r = iterator.next()153 /* istanbul ignore next */154 if (r.done) return r155 const value = this.get(r.value)156 return {157 done: false,158 value: [r.value, value]159 }160 }161 } as any162 }163164 p[iteratorSymbol] = function() {165 return this.entries()166 }167168 return DraftMap169})(Map)170171export function proxyMap<T extends AnyMap>(172 target: T,173 parent?: ImmerState174): T & {[DRAFT_STATE]: MapState} {175 // @ts-ignore176 return new DraftMap(target, parent)177}178179function prepareCopy(state: MapState) {180 if (!state.copy) {181 state.assigned = new Map()182 state.copy = new Map(state.base)183 }184}
deleted:src/patches.ts-263 removed
1import {2 get,3 each,4 has,5 die,6 getArchtype,7 ImmerState,8 Patch,9 ProxyType,10 SetState,11 ES5ArrayState,12 ProxyArrayState,13 MapState,14 ES5ObjectState,15 ProxyObjectState,16 Archtype,17 isMap,18 isSet19} from "./internal"2021export type PatchPath = (string | number)[]2223export function generatePatches(24 state: ImmerState,25 basePath: PatchPath,26 patches: Patch[],27 inversePatches: Patch[]28): void {29 switch (state.type) {30 case ProxyType.ProxyObject:31 case ProxyType.ES5Object:32 case ProxyType.Map:33 return generatePatchesFromAssigned(34 state,35 basePath,36 patches,37 inversePatches38 )39 case ProxyType.ES5Array:40 case ProxyType.ProxyArray:41 return generateArrayPatches(state, basePath, patches, inversePatches)42 case ProxyType.Set:43 return generateSetPatches(44 (state as any) as SetState,45 basePath,46 patches,47 inversePatches48 )49 }50}5152function generateArrayPatches(53 state: ES5ArrayState | ProxyArrayState,54 basePath: PatchPath,55 patches: Patch[],56 inversePatches: Patch[]57) {58 let {base, assigned, copy} = state59 /* istanbul ignore next */60 if (!copy) die()6162 // Reduce complexity by ensuring `base` is never longer.63 if (copy.length < base.length) {64 // @ts-ignore65 ;[base, copy] = [copy, base]66 ;[patches, inversePatches] = [inversePatches, patches]67 }6869 const delta = copy.length - base.length7071 // Find the first replaced index.72 let start = 073 while (base[start] === copy[start] && start < base.length) {74 ++start75 }7677 // Find the last replaced index. Search from the end to optimize splice patches.78 let end = base.length79 while (end > start && base[end - 1] === copy[end + delta - 1]) {80 --end81 }8283 // Process replaced indices.84 for (let i = start; i < end; ++i) {85 if (assigned[i] && copy[i] !== base[i]) {86 const path = basePath.concat([i])87 patches.push({88 op: "replace",89 path,90 value: copy[i]91 })92 inversePatches.push({93 op: "replace",94 path,95 value: base[i]96 })97 }98 }99100 const replaceCount = patches.length101102 // Process added indices.103 for (let i = end + delta - 1; i >= end; --i) {104 const path = basePath.concat([i])105 patches[replaceCount + i - end] = {106 op: "add",107 path,108 value: copy[i]109 }110 inversePatches.push({111 op: "remove",112 path113 })114 }115}116117// This is used for both Map objects and normal objects.118function generatePatchesFromAssigned(119 state: MapState | ES5ObjectState | ProxyObjectState,120 basePath: PatchPath,121 patches: Patch[],122 inversePatches: Patch[]123) {124 const {base, copy} = state125 each(state.assigned!, (key, assignedValue) => {126 const origValue = get(base, key)127 const value = get(copy!, key)128 const op = !assignedValue ? "remove" : has(base, key) ? "replace" : "add"129 if (origValue === value && op === "replace") return130 const path = basePath.concat(key as any)131 patches.push(op === "remove" ? {op, path} : {op, path, value})132 inversePatches.push(133 op === "add"134 ? {op: "remove", path}135 : op === "remove"136 ? {op: "add", path, value: origValue}137 : {op: "replace", path, value: origValue}138 )139 })140}141142function generateSetPatches(143 state: SetState,144 basePath: PatchPath,145 patches: Patch[],146 inversePatches: Patch[]147) {148 let {base, copy} = state149150 let i = 0151 base.forEach(value => {152 if (!copy!.has(value)) {153 const path = basePath.concat([i])154 patches.push({155 op: "remove",156 path,157 value158 })159 inversePatches.unshift({160 op: "add",161 path,162 value163 })164 }165 i++166 })167 i = 0168 copy!.forEach(value => {169 if (!base.has(value)) {170 const path = basePath.concat([i])171 patches.push({172 op: "add",173 path,174 value175 })176 inversePatches.unshift({177 op: "remove",178 path,179 value180 })181 }182 i++183 })184}185186export function applyPatches<T>(draft: T, patches: Patch[]): T {187 patches.forEach(patch => {188 const {path, op} = patch189190 /* istanbul ignore next */191 if (!path.length) die()192193 let base: any = draft194 for (let i = 0; i < path.length - 1; i++) {195 base = get(base, path[i])196 if (!base || typeof base !== "object")197 throw new Error("Cannot apply patch, path doesn't resolve: " + path.join("/")) // prettier-ignore198 }199200 const type = getArchtype(base)201 const value = deepClonePatchValue(patch.value) // used to clone patch to ensure original patch is not modified, see #411202 const key = path[path.length - 1]203 switch (op) {204 case "replace":205 switch (type) {206 case Archtype.Map:207 return base.set(key, value)208 /* istanbul ignore next */209 case Archtype.Set:210 throw new Error('Sets cannot have "replace" patches.')211 default:212 // if value is an object, then it's assigned by reference213 // in the following add or remove ops, the value field inside the patch will also be modifyed214 // so we use value from the cloned patch215 // @ts-ignore216 return (base[key] = value)217 }218 case "add":219 switch (type) {220 case Archtype.Array:221 return base.splice(key as any, 0, value)222 case Archtype.Map:223 return base.set(key, value)224 case Archtype.Set:225 return base.add(value)226 default:227 return (base[key] = value)228 }229 case "remove":230 switch (type) {231 case Archtype.Array:232 return base.splice(key as any, 1)233 case Archtype.Map:234 return base.delete(key)235 case Archtype.Set:236 return base.delete(patch.value)237 default:238 return delete base[key]239 }240 default:241 throw new Error("Unsupported patch operation: " + op)242 }243 })244245 return draft246}247248// TODO: optimize: this is quite a performance hit, can we detect intelligently when it is needed?249// E.g. auto-draft when new objects from outside are assigned and modified?250// (See failing test when deepClone just returns obj)251function deepClonePatchValue<T>(obj: T): T252function deepClonePatchValue(obj: any) {253 if (!obj || typeof obj !== "object") return obj254 if (Array.isArray(obj)) return obj.map(deepClonePatchValue)255 if (isMap(obj))256 return new Map(257 Array.from(obj.entries()).map(([k, v]) => [k, deepClonePatchValue(v)])258 )259 if (isSet(obj)) return new Set(Array.from(obj).map(deepClonePatchValue))260 const cloned = Object.create(Object.getPrototypeOf(obj))261 for (const key in obj) cloned[key] = deepClonePatchValue(obj[key])262 return cloned263}
added:src/plugins.ts+145 added
1import {2 ImmerState,3 Patch,4 ImmerScope,5 Drafted,6 AnyObject,7 ImmerBaseState,8 AnyArray,9 ProxyType,10 AnyMap,11 DRAFT_STATE,12 AnySet13} from "./internal"1415/** Plugin utilities */16const plugins: {17 patches?: {18 generatePatches: typeof generatePatches19 applyPatches: typeof applyPatches20 }21 es5?: {22 willFinalizeES5: typeof willFinalizeES523 createES5Proxy: typeof createES5Proxy24 markChangedES5: typeof markChangedES525 }26 mapset?: {27 proxyMap: typeof proxyMap28 proxySet: typeof proxySet29 }30} = {}3132type Plugins = typeof plugins3334export function getPlugin<K extends keyof Plugins>(35 pluginKey: K36): Exclude<Plugins[K], undefined> {37 const plugin = plugins[pluginKey]38 if (!plugin) {39 throw new Error(40 `The plugin ${pluginKey} has not been loaded into Immer. Make sure the require from "immer/${pluginKey}" when initializing your application, just after requiring immer itself.`41 )42 }43 // @ts-ignore44 return plugin45}4647export function loadPlugin<K extends keyof Plugins>(48 pluginKey: K,49 implementation: Plugins[K]50) {51 plugins[pluginKey] = implementation52}5354/** ES5 Plugin */5556interface ES5BaseState extends ImmerBaseState {57 finalizing: boolean58 assigned: {[key: string]: any}59 parent?: ImmerState60 revoked: boolean61}6263export interface ES5ObjectState extends ES5BaseState {64 type: ProxyType.ES5Object65 draft: Drafted<AnyObject, ES5ObjectState>66 base: AnyObject67 copy: AnyObject | null68}6970export interface ES5ArrayState extends ES5BaseState {71 type: ProxyType.ES5Array72 draft: Drafted<AnyObject, ES5ArrayState>73 base: AnyArray74 copy: AnyArray | null75}7677export function willFinalizeES5(78 scope: ImmerScope,79 result: any,80 isReplaced: boolean81) {82 getPlugin("es5").willFinalizeES5(scope, result, isReplaced)83}8485export function createES5Proxy<T>(86 base: T,87 parent?: ImmerState88): Drafted<T, ES5ObjectState | ES5ArrayState> {89 return getPlugin("es5").createES5Proxy(base, parent)90}9192export function markChangedES5(state: ImmerState) {93 getPlugin("es5").markChangedES5(state)94}9596/** Map / Set plugin */9798export interface MapState extends ImmerBaseState {99 type: ProxyType.Map100 copy: AnyMap | undefined101 assigned: Map<any, boolean> | undefined102 base: AnyMap103 revoked: boolean104 draft: Drafted<AnyMap, MapState>105}106107export interface SetState extends ImmerBaseState {108 type: ProxyType.Set109 copy: AnySet | undefined110 base: AnySet111 drafts: Map<any, Drafted> // maps the original value to the draft value in the new set112 revoked: boolean113 draft: Drafted<AnySet, SetState>114}115116export function proxyMap<T extends AnyMap>(117 target: T,118 parent?: ImmerState119): T & {[DRAFT_STATE]: MapState} {120 return getPlugin("mapset").proxyMap(target, parent)121}122123export function proxySet<T extends AnySet>(124 target: T,125 parent?: ImmerState126): T & {[DRAFT_STATE]: SetState} {127 return getPlugin("mapset").proxySet(target, parent)128}129130/** Patches plugin */131132export type PatchPath = (string | number)[]133134export function generatePatches(135 state: ImmerState,136 basePath: PatchPath,137 patches: Patch[],138 inversePatches: Patch[]139): void {140 getPlugin("patches").generatePatches(state, basePath, patches, inversePatches)141}142143export function applyPatches<T>(draft: T, patches: Patch[]): T {144 return getPlugin("patches").applyPatches(draft, patches)145}
deleted:src/set.ts-165 removed
1import {2 __extends,3 ImmerBaseState,4 ProxyType,5 AnySet,6 Drafted,7 ImmerState,8 DRAFT_STATE,9 ImmerScope,10 latest,11 assertUnrevoked,12 iteratorSymbol,13 isDraftable14} from "./internal"1516export interface SetState extends ImmerBaseState {17 type: ProxyType.Set18 copy: AnySet | undefined19 base: AnySet20 drafts: Map<any, Drafted> // maps the original value to the draft value in the new set21 revoked: boolean22 draft: Drafted<AnySet, SetState>23}2425const DraftSet = (function(_super) {26 if (!_super) {27 /* istanbul ignore next */28 throw new Error("Set is not polyfilled")29 }30 __extends(DraftSet, _super)31 // Create class manually, cause #50232 function DraftSet(this: any, target: AnySet, parent?: ImmerState) {33 this[DRAFT_STATE] = {34 type: ProxyType.Set,35 parent,36 scope: parent ? parent.scope : ImmerScope.current!,37 modified: false,38 finalized: false,39 copy: undefined,40 base: target,41 draft: this,42 drafts: new Map(),43 revoked: false,44 isManual: false45 }46 return this47 }48 const p = DraftSet.prototype4950 Object.defineProperty(p, "size", {51 get: function() {52 return latest(this[DRAFT_STATE]).size53 },54 enumerable: true,55 configurable: true56 })5758 p.has = function(value: any): boolean {59 const state = this[DRAFT_STATE]60 assertUnrevoked(state)61 // bit of trickery here, to be able to recognize both the value, and the draft of its value62 if (!state.copy) {63 return state.base.has(value)64 }65 if (state.copy.has(value)) return true66 if (state.drafts.has(value) && state.copy.has(state.drafts.get(value)))67 return true68 return false69 }7071 p.add = function(value: any): any {72 const state = this[DRAFT_STATE]73 assertUnrevoked(state)74 if (state.copy) {75 state.copy.add(value)76 } else if (!state.base.has(value)) {77 prepareCopy(state)78 state.scope.immer.markChanged(state)79 state.copy!.add(value)80 }81 return this82 }8384 p.delete = function(value: any): any {85 if (!this.has(value)) {86 return false87 }8889 const state = this[DRAFT_STATE]90 assertUnrevoked(state)91 prepareCopy(state)92 state.scope.immer.markChanged(state)93 return (94 state.copy!.delete(value) ||95 (state.drafts.has(value)96 ? state.copy!.delete(state.drafts.get(value))97 : /* istanbul ignore next */ false)98 )99 }100101 p.clear = function() {102 const state = this[DRAFT_STATE]103 assertUnrevoked(state)104 prepareCopy(state)105 state.scope.immer.markChanged(state)106 return state.copy!.clear()107 }108109 p.values = function(): IterableIterator<any> {110 const state = this[DRAFT_STATE]111 assertUnrevoked(state)112 prepareCopy(state)113 return state.copy!.values()114 }115116 p.entries = function entries(): IterableIterator<[any, any]> {117 const state = this[DRAFT_STATE]118 assertUnrevoked(state)119 prepareCopy(state)120 return state.copy!.entries()121 }122123 p.keys = function(): IterableIterator<any> {124 return this.values()125 }126127 p[iteratorSymbol] = function() {128 return this.values()129 }130131 p.forEach = function forEach(cb: any, thisArg?: any) {132 const iterator = this.values()133 let result = iterator.next()134 while (!result.done) {135 cb.call(thisArg, result.value, result.value, this)136 result = iterator.next()137 }138 }139140 return DraftSet141})(Set)142143export function proxySet<T extends AnySet>(144 target: T,145 parent?: ImmerState146): T & {[DRAFT_STATE]: SetState} {147 // @ts-ignore148 return new DraftSet(target, parent)149}150151function prepareCopy(state: SetState) {152 if (!state.copy) {153 // create drafts for all entries to preserve insertion order154 state.copy = new Set()155 state.base.forEach(value => {156 if (isDraftable(value)) {157 const draft = state.scope.immer.createProxy(value, state)158 state.drafts.set(value, draft)159 state.copy!.add(draft)160 } else {161 state.copy!.add(value)162 }163 })164 }165}