converted everything, 0 errors
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 15f8079 · Browse files · 5 files·+454 added−400 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+454 added−400 removed
- other:+454 added−400 removed
Provenance
- Commit
b4c6e59- Tree
2a2b0d0- Author
Michel Weststrate <mweststrate@fb.com>- Committer
Michel Weststrate <mweststrate@fb.com>- Parent
15f8079
5 files changed+454 added−400 removed
modified:src/common.ts+2 added-2 removed
180 unmodified lines181 export function isSet(target): target is Set<any> {182 return hasSet && target instanceof Set183 }184 185-export function makeIterable(next: Objectish) {185+export function makeIterable(next: () => {done: boolean; value: any}) {186 let self187 return (self = {188 [Symbol.iterator]: () => self,189 next17 unmodified lines207 }208 }209 210 export function makeIterateSetValues(createProxy) {211- function iterateSetValues(state, prop) {211+ function iterateSetValues(state, prop?) {212 const isEntries = prop === "entries"213 return () => {214 const iterator = latest(state)[Symbol.iterator]()215 return makeIterable(() => {58 unmodified linesmodified:src/es5.ts+6 added-5 removed
20 unmodified lines21 interface ES5Draft {22 [DRAFT_STATE]: ES5State23 }24 25+// TODO: merge with ImmerState?26 interface ES5State<T = any> {27 scope: ImmerScope28 modified: boolean29 finalizing: boolean28 unmodified lines58 markChangesSweep(scope.drafts)59 }60 }61 61-export function createProxy(base: any, parent: ES5State) {62+export function createProxy<T>(base: T, parent: ES5State): ES5Draft {63 const isArray = Array.isArray(base)64 const draft = clonePotentialDraft(base)65 66 if (isMap(base)) {7 unmodified lines74 }75 76 // See "proxy.js" for property documentation.77 const scope = parent ? parent.scope : ImmerScope.current!77- const state: ES5State = {78+ const state: ES5State<T> = {79 scope,80 modified: false,81 finalizing: false, // es5 only82 finalized: false,106 unmodified lines189 if (hasSymbol) {190 Object.defineProperty(191 target,192 Symbol.iterator,192- proxyMethod(iterateMapValues)193+ proxyMethod(iterateMapValues, Symbol.iterator)194 )195 }196 }197 58 unmodified lines256 if (hasSymbol) {257 Object.defineProperty(258 target,259 Symbol.iterator,259- proxyMethod(iterateSetValues)260+ proxyMethod(iterateSetValues, Symbol.iterator)261 )262 }263 }264 63 unmodified lines328 329 function proxyMethod(trap, key) {330 return {331 get() {331- return function(...args) {332+ return function(this: ES5Draft, ...args) {333 const state = this[DRAFT_STATE]334 assertUnrevoked(state)335 return trap(state, key, state.draft)(...args)336 }157 unmodified linesmodified:src/immer.ts+33 added-20 removed
16 unmodified lines17 NOTHING,18 freeze19 } from "./common"20 import {ImmerScope} from "./scope"21-import {ImmerState, IProduce, IProduceWithPatches} from "./types"21+import {ImmerState, IProduce, IProduceWithPatches, Objectish, PatchListener, Draft, Patch} from "./types"22 23 function verifyMinified() {}24 25 const configDefaults = {17 unmodified lines43 44 export class Immer implements ProducersFns {45 useProxies: boolean = false46 autoFreeze: boolean = false47+ onAssign?: (48+ state: ImmerState,49+ prop: string | number,50+ value: unknown51+ ) => void52+ onDelete?: (state: ImmerState, prop: string | number) => void53+ onCopy?: (state: ImmerState) => void54+ createProxy!:<T>(value: T) => T;55+ willFinalize!: (scope: ImmerScope, thing: any, isReplaced: boolean) => void;56 57 constructor(config?: {58 useProxies?: boolean59 autoFreeze?: boolean29 unmodified lines89 * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified90 * @param {Function} patchListener - optional function that will be called with all the patches produced here91 * @returns {any} a new state, or the initial state if nothing was modified92 */84- produce(base, recipe, patchListener) {93+ produce(base, recipe?, patchListener?) {94 // curried invocation95 if (typeof base === "function" && typeof recipe !== "function") {96 const defaultBase = recipe97 recipe = base98 99 const self = this91- return function curriedProduce(base = defaultBase, ...args) {100+ return function curriedProduce(this: any, base = defaultBase, ...args) {101 return self.produce(base, draft => recipe.call(this, draft, ...args)) // prettier-ignore102 }103 }104 44 unmodified lines149 return result150 }151 }152 144- produceWithPatches(arg1, arg2, arg3) {153+ produceWithPatches(arg1, arg2?, arg3?): any {154 if (typeof arg1 === "function") {155 const self = this156 return (state, ...args) =>157 this.produceWithPatches(state, draft => arg1(draft, ...args))8 unmodified lines166 })167 return [nextState, patches, inversePatches]168 }169 161- createDraft(base) {170+ createDraft<T extends Objectish>(base: T): Draft<T> {171 if (!isDraftable(base)) {172 throw new Error("First argument to `createDraft` must be a plain object, an array, or an immerable object") // prettier-ignore173 }174 const scope = ImmerScope.enter()175 const proxy = this.createProxy(base)176 proxy[DRAFT_STATE].isManual = true177 scope.leave()169- return proxy178+ return proxy as any179 }180 172- finishDraft(draft, patchListener) {181+ finishDraft<D extends Draft<any>>(draft: D, patchListener: PatchListener): D extends Draft<infer T> ? T : never {182 const state = draft && draft[DRAFT_STATE]183 if (!state || !state.isManual) {184 throw new Error("First argument to `finishDraft` must be a draft returned by `createDraft`") // prettier-ignore185 }9 unmodified lines195 * Pass true to automatically freeze all copies created by Immer.196 *197 * By default, auto-freezing is disabled in production.198 */190- setAutoFreeze(value) {199+ setAutoFreeze(value: boolean) {200 this.autoFreeze = value201 }202 203 /**1 unmodified line205 * always faster than using ES5 proxies.206 *207 * By default, feature detection is used, so calling this is rarely necessary.208 */200- setUseProxies(value) {209+ setUseProxies(value: boolean) {210 this.useProxies = value211 assign(this, value ? modernProxy : legacyProxy)212 }204- applyPatches(base, patches) {213+214+ applyPatches(base: Objectish, patches: Patch[]) {215 // If a patch replaces the entire state, take that replacement as base216 // before applying patches217 let i218 for (i = patches.length - 1; i >= 0; i--) {12 unmodified lines231 return this.produce(base, draft =>232 applyPatches(draft, patches.slice(i + 1))233 )234 }235+236 /** @internal */226- processResult(result, scope) {227- const baseDraft = scope.drafts[0]237+ processResult(result: any, scope: ImmerScope) {238+ const baseDraft = scope.drafts![0]239 const isReplaced = result !== undefined && result !== baseDraft240 this.willFinalize(scope, result, isReplaced)241 if (isReplaced) {242 if (baseDraft[DRAFT_STATE].modified) {10 unmodified lines253 op: "replace",254 path: [],255 value: result256 })246- scope.inversePatches.push({257+ scope.inversePatches!.push({258 op: "replace",259 path: [],260 value: baseDraft[DRAFT_STATE].base261 })3 unmodified lines265 result = this.finalize(baseDraft, [], scope)266 }267 scope.revoke()268 if (scope.patches) {258- scope.patchListener(scope.patches, scope.inversePatches)269+ scope.patchListener!(scope.patches, scope.inversePatches!)270 }271 return result !== NOTHING ? result : undefined272 }273+274 /**275 * @internal276 * Finalize a draft, returning either the unmodified base state or a modified277 * copy of the base state.278 */267- finalize(draft, path, scope) {279+ finalize(draft: any, path: string[] | null, scope: ImmerScope) {280 const state = draft[DRAFT_STATE]281 if (!state) {282 if (Object.isFrozen(draft)) return draft283 return this.finalizeTree(draft, null, scope)15 unmodified lines299 // The `assigned` object is unreliable with ES5 drafts.300 if (this.useProxies) {301 const {assigned} = state302 each(assigned, (prop, exists) => {291- if (!exists) this.onDelete(state, prop)303+ if (!exists) this.onDelete?.(state, prop as any)304 })305 } else {306 // TODO: Figure it out for Maps and Sets if we need to support ES5307 const {base, copy} = state308 each(base, prop => {297- if (!has(copy, prop)) this.onDelete(state, prop)309+ if (!has(copy, prop)) this.onDelete?.(state, prop as any)310 })311 }312 }313 if (this.onCopy) {6 unmodified lines320 freeze(state.copy, false)321 }322 323 if (path && scope.patches) {312- generatePatches(state, path, scope.patches, scope.inversePatches)324+ generatePatches(state, path, scope.patches, scope.inversePatches!)325 }326 }327 return state.copy328 }329+330 /**331 * @internal332 * Finalize all drafts in the given state tree.333 */321- finalizeTree(root, rootPath, scope) {334+ finalizeTree(root: any, rootPath: string[] | null, scope: ImmerScope) {335 const state = root[DRAFT_STATE]336 if (state) {337 if (!this.useProxies) {338 // Create the final copy, with added keys and without deleted keys.17 unmodified lines356 isDraftProp &&357 needPatches &&358 !isSetMember && // Set objects are atomic since they have no keys.359 !has(state.assigned, prop) // Skip deep patches for assigned keys.347- ? rootPath.concat(prop)360+ ? rootPath!.concat(prop)361 : null362 363 // Drafts owned by `scope` are finalized here.364 value = this.finalize(value, path, scope)53 unmodified linesdeleted:src/proxy.js-373 removed
1-"use strict"2-import {3- assign,4- each,5- has,6- is,7- isDraftable,8- isDraft,9- isMap,10- isSet,11- hasSymbol,12- shallowCopy,13- makeIterable,14- DRAFT_STATE,15- assignMap,16- assignSet,17- original,18- iterateMapValues,19- makeIterateSetValues20-} from "./common"21-import {ImmerScope} from "./scope"22-23-// Do nothing before being finalized.24-export function willFinalize() {}25-26-/**27- * Returns a new draft of the `base` object.28- *29- * The second argument is the parent draft-state (used internally).30- */31-export function createProxy(base, parent) {32- const scope = parent ? parent.scope : ImmerScope.current33- const state = {34- // Track which produce call this is associated with.35- scope,36- // True for both shallow and deep changes.37- modified: false,38- // Used during finalization.39- finalized: false,40- // Track which properties have been assigned (true) or deleted (false).41- assigned: {},42- // The parent draft state.43- parent,44- // The base state.45- base,46- // The base proxy.47- draft: null,48- // Any property proxies.49- drafts: {},50- // The base copy with any updated values.51- copy: null,52- // Called by the `produce` function.53- revoke: null54- }55-56- let target = state57- let traps = objectTraps58- if (Array.isArray(base)) {59- target = [state]60- traps = arrayTraps61- }62- // Map drafts must support object keys, so we use Map objects to track changes.63- else if (isMap(base)) {64- traps = mapTraps65- state.drafts = new Map()66- state.assigned = new Map()67- }68- // Set drafts use a Map object to track which of its values are drafted.69- // And we don't need the "assigned" property, because Set objects have no keys.70- else if (isSet(base)) {71- traps = setTraps72- state.drafts = new Map()73- }74-75- const {revoke, proxy} = Proxy.revocable(target, traps)76-77- state.draft = proxy78- state.revoke = revoke79-80- scope.drafts.push(proxy)81- return proxy82-}83-84-/**85- * Object drafts86- */87-88-const objectTraps = {89- get(state, prop) {90- if (prop === DRAFT_STATE) return state91- let {drafts} = state92-93- // Check for existing draft in unmodified state.94- if (!state.modified && has(drafts, prop)) {95- return drafts[prop]96- }97-98- const value = latest(state)[prop]99- if (state.finalized || !isDraftable(value)) {100- return value101- }102-103- // Check for existing draft in modified state.104- if (state.modified) {105- // Assigned values are never drafted. This catches any drafts we created, too.106- if (value !== peek(state.base, prop)) return value107- // Store drafts on the copy (when one exists).108- drafts = state.copy109- }110-111- return (drafts[prop] = createProxy(value, state))112- },113- has(state, prop) {114- return prop in latest(state)115- },116- ownKeys(state) {117- return Reflect.ownKeys(latest(state))118- },119- set(state, prop, value) {120- if (!state.modified) {121- const baseValue = peek(state.base, prop)122- // Optimize based on value's truthiness. Truthy values are guaranteed to123- // never be undefined, so we can avoid the `in` operator. Lastly, truthy124- // values may be drafts, but falsy values are never drafts.125- const isUnchanged = value126- ? is(baseValue, value) || value === state.drafts[prop]127- : is(baseValue, value) && prop in state.base128- if (isUnchanged) return true129- markChanged(state)130- }131- state.assigned[prop] = true132- state.copy[prop] = value133- return true134- },135- deleteProperty(state, prop) {136- // The `undefined` check is a fast path for pre-existing keys.137- if (peek(state.base, prop) !== undefined || prop in state.base) {138- state.assigned[prop] = false139- markChanged(state)140- } else if (state.assigned[prop]) {141- // if an originally not assigned property was deleted142- delete state.assigned[prop]143- }144- if (state.copy) delete state.copy[prop]145- return true146- },147- // Note: We never coerce `desc.value` into an Immer draft, because we can't make148- // the same guarantee in ES5 mode.149- getOwnPropertyDescriptor(state, prop) {150- const owner = latest(state)151- const desc = Reflect.getOwnPropertyDescriptor(owner, prop)152- if (desc) {153- desc.writable = true154- desc.configurable = !Array.isArray(owner) || prop !== "length"155- }156- return desc157- },158- defineProperty() {159- throw new Error("Object.defineProperty() cannot be used on an Immer draft") // prettier-ignore160- },161- getPrototypeOf(state) {162- return Object.getPrototypeOf(state.base)163- },164- setPrototypeOf() {165- throw new Error("Object.setPrototypeOf() cannot be used on an Immer draft") // prettier-ignore166- }167-}168-169-/**170- * Array drafts171- */172-173-const arrayTraps = {}174-each(objectTraps, (key, fn) => {175- arrayTraps[key] = function() {176- arguments[0] = arguments[0][0]177- return fn.apply(this, arguments)178- }179-})180-arrayTraps.deleteProperty = function(state, prop) {181- if (isNaN(parseInt(prop))) {182- throw new Error("Immer only supports deleting array indices") // prettier-ignore183- }184- return objectTraps.deleteProperty.call(this, state[0], prop)185-}186-arrayTraps.set = function(state, prop, value) {187- if (prop !== "length" && isNaN(parseInt(prop))) {188- throw new Error("Immer only supports setting array indices and the 'length' property") // prettier-ignore189- }190- return objectTraps.set.call(this, state[0], prop, value)191-}192-193-// Used by Map and Set drafts194-const reflectTraps = makeReflectTraps([195- "ownKeys",196- "has",197- "set",198- "deleteProperty",199- "defineProperty",200- "getOwnPropertyDescriptor",201- "preventExtensions",202- "isExtensible",203- "getPrototypeOf"204-])205-206-/**207- * Map drafts208- */209-210-const mapTraps = makeTrapsForGetters({211- [DRAFT_STATE]: state => state,212- size: state => latest(state).size,213- has: state => key => latest(state).has(key),214- set: state => (key, value) => {215- const values = latest(state)216- if (!values.has(key) || values.get(key) !== value) {217- markChanged(state)218- state.assigned.set(key, true)219- state.copy.set(key, value)220- }221- return state.draft222- },223- delete: state => key => {224- if (latest(state).has(key)) {225- markChanged(state)226- state.assigned.set(key, false)227- return state.copy.delete(key)228- }229- return false230- },231- clear: state => () => {232- markChanged(state)233- state.assigned = new Map()234- for (const key of latest(state).keys()) {235- state.assigned.set(key, false)236- }237- return state.copy.clear()238- },239- forEach: (state, _, receiver) => (cb, thisArg) =>240- latest(state).forEach((_, key, map) => {241- const value = receiver.get(key)242- cb.call(thisArg, value, key, map)243- }),244- get: state => key => {245- const drafts = state.modified ? state.copy : state.drafts246-247- if (drafts.has(key)) {248- const value = drafts.get(key)249-250- if (isDraft(value) || !isDraftable(value)) return value251-252- const draft = createProxy(value, state)253- drafts.set(key, draft)254- return draft255- }256-257- const value = latest(state).get(key)258- if (state.finalized || !isDraftable(value)) {259- return value260- }261-262- const draft = createProxy(value, state)263- drafts.set(key, draft)264- return draft265- },266- keys: state => () => latest(state).keys(),267- values: iterateMapValues,268- entries: iterateMapValues,269- [hasSymbol ? Symbol.iterator : "@@iterator"]: iterateMapValues270-})271-272-const iterateSetValues = makeIterateSetValues(createProxy)273-/**274- * Set drafts275- */276-277-const setTraps = makeTrapsForGetters({278- [DRAFT_STATE]: state => state,279- size: state => latest(state).size,280- has: state => key => latest(state).has(key),281- add: state => value => {282- if (!latest(state).has(value)) {283- markChanged(state)284- state.copy.add(value)285- }286- return state.draft287- },288- delete: state => value => {289- markChanged(state)290- return state.copy.delete(value)291- },292- clear: state => () => {293- markChanged(state)294- return state.copy.clear()295- },296- forEach: state => (cb, thisArg) => {297- const iterator = iterateSetValues(state)()298- let result = iterator.next()299- while (!result.done) {300- cb.call(thisArg, result.value, result.value, state.draft)301- result = iterator.next()302- }303- },304- keys: iterateSetValues,305- values: iterateSetValues,306- entries: iterateSetValues,307- [hasSymbol ? Symbol.iterator : "@@iterator"]: iterateSetValues308-})309-310-/**311- * Helpers312- */313-314-// Retrieve the latest values of the draft.315-function latest(state) {316- return state.copy || state.base317-}318-319-// Access a property without creating an Immer draft.320-function peek(draft, prop) {321- const state = draft[DRAFT_STATE]322- const desc = Reflect.getOwnPropertyDescriptor(323- state ? latest(state) : draft,324- prop325- )326- return desc && desc.value327-}328-329-function markChanged(state) {330- if (!state.modified) {331- state.modified = true332-333- const {base, drafts, parent} = state334- const copy = shallowCopy(base)335-336- if (isSet(base)) {337- // Note: The `drafts` property is preserved for Set objects, since338- // we need to keep track of which values are drafted.339- assignSet(copy, drafts)340- } else {341- // Merge nested drafts into the copy.342- if (isMap(base)) assignMap(copy, drafts)343- else assign(copy, drafts)344- state.drafts = null345- }346-347- state.copy = copy348- if (parent) {349- markChanged(parent)350- }351- }352-}353-354-/** Create traps that all use the `Reflect` API on the `latest(state)` */355-function makeReflectTraps(names) {356- return names.reduce((traps, name) => {357- traps[name] = (state, ...args) => Reflect[name](latest(state), ...args)358- return traps359- }, {})360-}361-362-function makeTrapsForGetters(getters) {363- return assign({}, reflectTraps, {364- get(state, prop, receiver) {365- return getters.hasOwnProperty(prop)366- ? getters[prop](state, prop, receiver)367- : Reflect.get(state, prop, receiver)368- },369- setPrototypeOf(state) {370- throw new Error("Object.setPrototypeOf() cannot be used on an Immer draft") // prettier-ignore371- }372- })373-}added:src/proxy.ts+413 added
1+"use strict"2+import {3+ assign,4+ each,5+ has,6+ is,7+ isDraftable,8+ isDraft,9+ isMap,10+ isSet,11+ hasSymbol,12+ shallowCopy,13+ makeIterable,14+ DRAFT_STATE,15+ assignMap,16+ assignSet,17+ original,18+ iterateMapValues,19+ makeIterateSetValues20+} from "./common"21+import {ImmerScope} from "./scope"22+23+// Do nothing before being finalized.24+export function willFinalize() {}25+26+interface ES6Draft {27+28+}29+30+interface ES6State<T= any> {31+ scope: ImmerScope,32+ modified: boolean,33+ finalized: boolean,34+ assigned: {35+ [property: string]: boolean;36+ } | Map<string, boolean> // TODO: always use a Map?37+ parent: ES6State,38+ base: T,39+ draft: ES6Draft | null40+ drafts: {41+ [property: string]: ES6Draft42+ } | Map<string, ES6Draft> // TODO: always use a Map?43+ copy: T | null44+ revoke : null | (() => void)45+}46+47+/**48+ * Returns a new draft of the `base` object.49+ *50+ * The second argument is the parent draft-state (used internally).51+ */52+export function createProxy<T extends object>(base: T, parent: ES6State): ES6Draft {53+ const scope = parent ? parent.scope : ImmerScope.current!54+ const state: ES6State<T> = {55+ // Track which produce call this is associated with.56+ scope,57+ // True for both shallow and deep changes.58+ modified: false,59+ // Used during finalization.60+ finalized: false,61+ // Track which properties have been assigned (true) or deleted (false).62+ assigned: {},63+ // The parent draft state.64+ parent,65+ // The base state.66+ base,67+ // The base proxy.68+ draft: null,69+ // Any property proxies.70+ drafts: {},71+ // The base copy with any updated values.72+ copy: null,73+ // Called by the `produce` function.74+ revoke: null75+ }76+77+ // the traps must target something, a bit like the 'real' base.78+ // but also, we need to be able to determine from the target what the relevant state is79+ // (to avoid creating traps per instance to capture the state in closure,80+ // and to avoid creating weird hidden properties as well)81+ // So the trick is to use 'state' as the actual 'target'! (and make sure we intercept everything)82+ // Note that in the case of an array, we put the state in an array to have better Reflect defaults ootb83+ let target: T = state as any84+ let traps: ProxyHandler<object|Array<any>> = objectTraps85+ if (Array.isArray(base)) {86+ target = [state] as any87+ traps = arrayTraps88+ }89+ // Map drafts must support object keys, so we use Map objects to track changes.90+ else if (isMap(base)) {91+ traps = mapTraps92+ state.drafts = new Map()93+ state.assigned = new Map()94+ }95+ // Set drafts use a Map object to track which of its values are drafted.96+ // And we don't need the "assigned" property, because Set objects have no keys.97+ else if (isSet(base)) {98+ traps = setTraps99+ state.drafts = new Map()100+ }101+102+ const {revoke, proxy} = Proxy.revocable(target, traps)103+104+ state.draft = proxy105+ state.revoke = revoke106+107+ scope.drafts!.push(proxy)108+ return proxy109+}110+111+/**112+ * Object drafts113+ */114+const objectTraps: ProxyHandler<ES6State> = {115+ get(state, prop) {116+ if (prop === DRAFT_STATE) return state117+ let {drafts} = state118+119+ // Check for existing draft in unmodified state.120+ if (!state.modified && has(drafts, prop)) {121+ return drafts[prop]122+ }123+124+ const value = latest(state)[prop]125+ if (state.finalized || !isDraftable(value)) {126+ return value127+ }128+129+ // Check for existing draft in modified state.130+ if (state.modified) {131+ // Assigned values are never drafted. This catches any drafts we created, too.132+ if (value !== peek(state.base, prop)) return value133+ // Store drafts on the copy (when one exists).134+ drafts = state.copy135+ }136+137+ return (drafts[prop] = createProxy(value, state))138+ },139+ has(state, prop) {140+ return prop in latest(state)141+ },142+ ownKeys(state) {143+ return Reflect.ownKeys(latest(state))144+ },145+ set(state, prop, value) {146+ if (!state.modified) {147+ const baseValue = peek(state.base, prop)148+ // Optimize based on value's truthiness. Truthy values are guaranteed to149+ // never be undefined, so we can avoid the `in` operator. Lastly, truthy150+ // values may be drafts, but falsy values are never drafts.151+ const isUnchanged = value152+ ? is(baseValue, value) || value === state.drafts[prop]153+ : is(baseValue, value) && prop in state.base154+ if (isUnchanged) return true155+ markChanged(state)156+ }157+ state.assigned[prop] = true158+ state.copy[prop] = value159+ return true160+ },161+ deleteProperty(state, prop) {162+ // The `undefined` check is a fast path for pre-existing keys.163+ if (peek(state.base, prop) !== undefined || prop in state.base) {164+ state.assigned[prop] = false165+ markChanged(state)166+ } else if (state.assigned[prop]) {167+ // if an originally not assigned property was deleted168+ delete state.assigned[prop]169+ }170+ if (state.copy) delete state.copy[prop]171+ return true172+ },173+ // Note: We never coerce `desc.value` into an Immer draft, because we can't make174+ // the same guarantee in ES5 mode.175+ getOwnPropertyDescriptor(state, prop) {176+ const owner = latest(state)177+ const desc = Reflect.getOwnPropertyDescriptor(owner, prop)178+ if (desc) {179+ desc.writable = true180+ desc.configurable = !Array.isArray(owner) || prop !== "length"181+ }182+ return desc183+ },184+ defineProperty() {185+ throw new Error("Object.defineProperty() cannot be used on an Immer draft") // prettier-ignore186+ },187+ getPrototypeOf(state) {188+ return Object.getPrototypeOf(state.base)189+ },190+ setPrototypeOf() {191+ throw new Error("Object.setPrototypeOf() cannot be used on an Immer draft") // prettier-ignore192+ }193+}194+195+/**196+ * Array drafts197+ */198+199+const arrayTraps: ProxyHandler<[ES6State]> = {}200+each(objectTraps, (key, fn) => {201+ arrayTraps[key] = function() {202+ arguments[0] = arguments[0][0]203+ return fn.apply(this, arguments)204+ }205+})206+arrayTraps.deleteProperty = function(state, prop) {207+ if (isNaN(parseInt(prop as any))) {208+ throw new Error("Immer only supports deleting array indices") // prettier-ignore209+ }210+ return objectTraps.deleteProperty!.call(undefined, state[0], prop)211+}212+arrayTraps.set = function(state, prop, value) {213+ if (prop !== "length" && isNaN(parseInt(prop as any))) {214+ throw new Error("Immer only supports setting array indices and the 'length' property") // prettier-ignore215+ }216+ return objectTraps.set!.call(undefined, state[0], prop, value, state[0])217+}218+219+// Used by Map and Set drafts220+const reflectTraps = makeReflectTraps([221+ "ownKeys",222+ "has",223+ "set",224+ "deleteProperty",225+ "defineProperty",226+ "getOwnPropertyDescriptor",227+ "preventExtensions",228+ "isExtensible",229+ "getPrototypeOf"230+])231+232+/**233+ * Map drafts234+ */235+236+const mapTraps = makeTrapsForGetters<Map<any, any>>({237+ [DRAFT_STATE]: state => state,238+ size: state => latest(state).size,239+ has: state => key => latest(state).has(key),240+ set: state => (key, value) => {241+ const values = latest(state)242+ if (!values.has(key) || values.get(key) !== value) {243+ markChanged(state)244+ // @ts-ignore245+ state.assigned.set(key, true)246+ state.copy!.set(key, value)247+ }248+ return state.draft249+ },250+ delete: state => key => {251+ if (latest(state).has(key)) {252+ markChanged(state)253+ // @ts-ignore254+ state.assigned.set(key, false)255+ return state.copy!.delete(key)256+ }257+ return false258+ },259+ clear: state => () => {260+ markChanged(state)261+ state.assigned = new Map()262+ for (const key of latest(state).keys()) {263+ state.assigned.set(key, false)264+ }265+ return state.copy!.clear()266+ },267+ // @ts-ignore268+ forEach: (state, _, receiver) => (cb, thisArg) =>269+ latest(state).forEach((_, key, map) => {270+ const value = receiver.get(key)271+ cb.call(thisArg, value, key, map)272+ }),273+ get: state => key => {274+ const drafts = state.modified ? state.copy : state.drafts275+276+ // @ts-ignore TODO: ...or fix by using different ES6Draft types (but better just unify to maps)277+ if (drafts!.has(key)) {278+ // @ts-ignore279+ const value = drafts.get(key)280+281+ if (isDraft(value) || !isDraftable(value)) return value282+283+ const draft = createProxy(value, state)284+ // @ts-ignore285+ drafts.set(key, draft)286+ return draft287+ }288+289+ const value = latest(state).get(key)290+ if (state.finalized || !isDraftable(value)) {291+ return value292+ }293+294+ const draft = createProxy(value, state)295+ //@ts-ignore296+ drafts.set(key, draft)297+ return draft298+ },299+ keys: state => () => latest(state).keys(),300+ //@ts-ignore301+ values: iterateMapValues,302+ //@ts-ignore303+ entries: iterateMapValues,304+ [hasSymbol ? Symbol.iterator : "@@iterator"]: iterateMapValues305+})306+307+const iterateSetValues = makeIterateSetValues(createProxy)308+/**309+ * Set drafts310+ */311+312+const setTraps = makeTrapsForGetters<Set<any>>({313+ //@ts-ignore314+ [DRAFT_STATE]: state => state,315+ size: state => latest(state).size,316+ has: state => key => latest(state).has(key),317+ add: state => value => {318+ if (!latest(state).has(value)) {319+ markChanged(state)320+ //@ts-ignore321+ state.copy.add(value)322+ }323+ return state.draft324+ },325+ delete: state => value => {326+ markChanged(state)327+ //@ts-ignore328+ return state.copy.delete(value)329+ },330+ clear: state => () => {331+ markChanged(state)332+ //@ts-ignore333+ return state.copy.clear()334+ },335+ forEach: state => (cb, thisArg) => {336+ const iterator = iterateSetValues(state)()337+ let result = iterator.next()338+ while (!result.done) {339+ cb.call(thisArg, result.value, result.value, state.draft)340+ result = iterator.next()341+ }342+ },343+ keys: iterateSetValues,344+ values: iterateSetValues,345+ entries: iterateSetValues,346+ [hasSymbol ? Symbol.iterator : "@@iterator"]: iterateSetValues347+})348+349+/**350+ * Helpers351+ */352+353+// Retrieve the latest values of the draft.354+function latest(state) {355+ return state.copy || state.base356+}357+358+// Access a property without creating an Immer draft.359+function peek(draft, prop) {360+ const state = draft[DRAFT_STATE]361+ const desc = Reflect.getOwnPropertyDescriptor(362+ state ? latest(state) : draft,363+ prop364+ )365+ return desc && desc.value366+}367+368+function markChanged(state) {369+ if (!state.modified) {370+ state.modified = true371+372+ const {base, drafts, parent} = state373+ const copy = shallowCopy(base)374+375+ if (isSet(base)) {376+ // Note: The `drafts` property is preserved for Set objects, since377+ // we need to keep track of which values are drafted.378+ assignSet(copy, drafts)379+ } else {380+ // Merge nested drafts into the copy.381+ if (isMap(base)) assignMap(copy, drafts)382+ else assign(copy, drafts)383+ state.drafts = null384+ }385+386+ state.copy = copy387+ if (parent) {388+ markChanged(parent)389+ }390+ }391+}392+393+/** Create traps that all use the `Reflect` API on the `latest(state)` */394+function makeReflectTraps<T extends object>(names: (keyof typeof Reflect)[]): ProxyHandler<T> {395+ return names.reduce((traps, name) => {396+ // @ts-ignore397+ traps[name] = (state, ...args) => Reflect[name](latest(state), ...args)398+ return traps399+ }, {} as any)400+}401+402+function makeTrapsForGetters<T extends object>(getters: {[K in keyof T]: (state: ES6State<T>) => /* Skip first arg of: ProxyHandler<T>[K] */ any }): ProxyHandler<T> {403+ return assign({}, reflectTraps, {404+ get(state, prop, receiver) {405+ return getters.hasOwnProperty(prop)406+ ? getters[prop](state, prop, receiver)407+ : Reflect.get(state, prop, receiver)408+ },409+ setPrototypeOf(state) {410+ throw new Error("Object.setPrototypeOf() cannot be used on an Immer draft") // prettier-ignore411+ }412+ })413+}