fix: Map and Set instantions won't work on certain environments, fixes #502
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Michel Weststrate · committed by GitHub · parents 49ff121, 7639c29 · Browse files · 18 files·+307 added−184 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
18 files+307 added−184 removed
- tests:+18 added−3 removed
- other:+289 added−181 removed
Provenance
- Commit
9f4711a- Tree
c9aa7e0- Author
Michel Weststrate <mweststrate@fb.com>- Committer
GitHub <noreply@github.com>- Parent 1
49ff121- Parent 2
7639c29
18 files changed+307 added−184 removed
modified:__tests__/base.js+15 added-1 removed
1 "use strict"2 import {Immer, nothing, original, isDraft, immerable} from "../src/index"3-import {each, shallowCopy, isEnumerable, DRAFT_STATE} from "../src/common"3+import {each, shallowCopy, isEnumerable, DRAFT_STATE} from "../src/internal"4 import deepFreeze from "deep-freeze"5 import cloneDeep from "lodash.clonedeep"6 import * as lodash from "lodash"7 573 unmodified lines581 expect(entries).toEqual([[key, 4]])582 expect(entries[0][0]).toBe(key)583 expect(entries[0][0].a).toBe(2)584 })585+586+ it("does support instanceof Map", () => {587+ const map = new Map()588+ produce(map, d => {589+ expect(d instanceof Map).toBeTruthy()590+ })591+ })592 })593 594 describe("set drafts", () => {595 it("supports iteration", () => {259 unmodified lines855 expect(() => m.add("x")).toThrow(856 "Cannot use a proxy that has been revoked"857 )858 })859+860+ it("does support instanceof Set", () => {861+ const set = new Set()862+ produce(set, d => {863+ expect(d instanceof Set).toBeTruthy()864+ })865+ })866 })867 868 it("supports `immerable` symbol on constructor", () => {869 class One {}1105 unmodified linesmodified:__tests__/empty.ts+2 added-1 removed
12234562 unmodified lines91011121314151617125 unmodified linesExpand allimport {produce, produceWithPatches, setUseProxies} from "../src"import {DRAFT_STATE} from "../src/common"import {DRAFT_STATE} from "../src/internal"
test("empty stub test", () => { expect(true).toBe(true)})2 unmodified lines test("can assign set value", () => { setUseProxies(false)
const baseState = new Map([["x", 1]]) debugger const nextState = produce(baseState, s => { s.set("x", 2) }) expect(baseState.get("x")).toEqual(1)125 unmodified linesExpand allmodified:__tests__/polyfills.js+1 added-1 removed
5 unmodified lines678910101112131434 unmodified lines5 unmodified linesObject.assign = undefinedReflect.ownKeys = undefined
jest.resetModules()const common = require("../src/common")const common = require("../src/internal")
// Reset the globals to avoid unintended effects.Symbol = SymbolConstructorObject.assign = assign34 unmodified linesmodified:src/common.ts+6 added-40 removed
1 import {2+ DRAFT_STATE,3+ DRAFTABLE,4+ hasSet,5 Objectish,6 Drafted,7 AnyObject,8 AnyArray,9 AnyMap,10 AnySet,11 ImmerState,12 ProxyType,10- Archtype11-} from "./types"13+ Archtype,14+ hasMap15+} from "./internal"16 13-/** Use a class type for `nothing` so its type is unique */14-export class Nothing {15- // This lets us do `Exclude<T, Nothing>`16- // @ts-ignore17- private _!: unique symbol18-}19-20-const hasSymbol = typeof Symbol !== "undefined"21-export const hasMap = typeof Map !== "undefined"22-export const hasSet = typeof Set !== "undefined"23-24-/**25- * The sentinel value returned by producers to replace the draft with undefined.26- */27-export const NOTHING: Nothing = hasSymbol28- ? Symbol("immer-nothing")29- : ({["immer-nothing"]: true} as any)30-31-/**32- * To let Immer treat your class instances as plain immutable objects33- * (albeit with a custom prototype), you must define either an instance property34- * or a static property on each of your custom classes.35- *36- * Otherwise, your class instance will never be drafted, which means it won't be37- * safe to mutate in a produce callback.38- */39-export const DRAFTABLE: unique symbol = hasSymbol40- ? Symbol("immer-draftable")41- : ("__$immer_draftable" as any)42-43-export const DRAFT_STATE: unique symbol = hasSymbol44- ? Symbol("immer-state")45- : ("__$immer_state" as any)46-47-export const iteratorSymbol: typeof Symbol.iterator = hasSymbol48- ? Symbol.iterator49- : ("@@iterator" as any)50-17 /** Returns true if the given value is an Immer draft */18 export function isDraft(value: any): boolean {19 return !!value && !!value[DRAFT_STATE]20 }191 unmodified linesadded:src/env.ts+40 added
1+// Should be no imports here!2+3+// SOme things that should be evaluated before all else...4+const hasSymbol = typeof Symbol !== "undefined"5+export const hasMap = typeof Map !== "undefined"6+export const hasSet = typeof Set !== "undefined"7+8+/**9+ * The sentinel value returned by producers to replace the draft with undefined.10+ */11+export const NOTHING: Nothing = hasSymbol12+ ? Symbol("immer-nothing")13+ : ({["immer-nothing"]: true} as any)14+15+/**16+ * To let Immer treat your class instances as plain immutable objects17+ * (albeit with a custom prototype), you must define either an instance property18+ * or a static property on each of your custom classes.19+ *20+ * Otherwise, your class instance will never be drafted, which means it won't be21+ * safe to mutate in a produce callback.22+ */23+export const DRAFTABLE: unique symbol = hasSymbol24+ ? Symbol("immer-draftable")25+ : ("__$immer_draftable" as any)26+27+export const DRAFT_STATE: unique symbol = hasSymbol28+ ? Symbol("immer-state")29+ : ("__$immer_state" as any)30+31+export const iteratorSymbol: typeof Symbol.iterator = hasSymbol32+ ? Symbol.iterator33+ : ("@@iterator" as any)34+35+/** Use a class type for `nothing` so its type is unique */36+export class Nothing {37+ // This lets us do `Exclude<T, Nothing>`38+ // @ts-ignore39+ private _!: unique symbol40+}modified:src/es5.ts+7 added-10 removed
5 unmodified lines6 isDraft,7 isDraftable,8 isEnumerable,9 shallowCopy,10- DRAFT_STATE,10 latest,12- createHiddenProperty13-} from "./common"14-15-import {ImmerScope} from "./scope"16-import {11+ createHiddenProperty,12+ ImmerScope,13 ImmerState,14 Drafted,15 AnyObject,16 Objectish,17 ImmerBaseState,18 AnyArray,23- ProxyType24-} from "./types"25-import {MapState} from "./map"26-import {SetState} from "./set"19+ ProxyType,20+ MapState,21+ SetState,22+ DRAFT_STATE23+} from "./internal"24 25 interface ES5BaseState extends ImmerBaseState {26 finalizing: boolean27 assigned: {[key: string]: any}276 unmodified linesadded:src/extends.ts+23 added
1+var extendStatics = function(d: any, b: any): any {2+ extendStatics =3+ Object.setPrototypeOf ||4+ ({__proto__: []} instanceof Array &&5+ function(d, b) {6+ d.__proto__ = b7+ }) ||8+ function(d, b) {9+ for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]10+ }11+ return extendStatics(d, b)12+}13+14+// Ugly hack to resolve #502 and inherit built in Map / Set15+export function __extends(d: any, b: any): any {16+ extendStatics(d, b)17+ function __(this: any): any {18+ this.constructor = d19+ }20+ d.prototype =21+ // @ts-ignore22+ ((__.prototype = b.prototype), new __())23+}modified:src/finalize.ts+17 added-13 removed
1-import {Immer} from "./immer"2-import {ImmerState, Drafted, ProxyType} from "./types"3-import {ImmerScope} from "./scope"1 import {5- isSet,6- has,7- is,8- get,9- each,2+ Immer,3+ ImmerScope,4 DRAFT_STATE,5+ isDraftable,6 NOTHING,7+ Drafted,8+ PatchPath,9+ ProxyType,10+ each,11+ has,12 freeze,13+ generatePatches,14 shallowCopy,14- set15-} from "./common"16-import {isDraft, isDraftable} from "./index"17-import {SetState} from "./set"18-import {generatePatches, PatchPath} from "./patches"15+ ImmerState,16+ isSet,17+ isDraft,18+ SetState,19+ set,20+ is,21+ get22+} from "./internal"23 24 export function processResult(immer: Immer, result: any, scope: ImmerScope) {25 const baseDraft = scope.drafts![0]26 const isReplaced = result !== undefined && result !== baseDraft181 unmodified linesmodified:src/immer.ts+23 added-22 removed
1-import {createES5Proxy, willFinalizeES5, markChangedES5} from "./es5"2-import {createProxy, markChanged} from "./proxy"3-4-import {applyPatches} from "./patches"1 import {2+ createES5Proxy,3+ willFinalizeES5,4+ markChangedES5,5+ IProduceWithPatches,6+ IProduce,7+ ImmerState,8 each,7- isDraft,8- isSet,9- isMap,9+ Drafted,10 isDraftable,11- DRAFT_STATE,11+ ImmerScope,12+ processResult,13 NOTHING,13- die14-} from "./common"15-import {ImmerScope} from "./scope"16-import {17- ImmerState,18- IProduce,19- IProduceWithPatches,14+ maybeFreeze,15+ die,16+ Patch,17 Objectish,21- PatchListener,18+ DRAFT_STATE,19 Draft,23- Patch,24- Drafted25-} from "./types"26-import {proxyMap} from "./map"27-import {proxySet} from "./set"28-import {processResult, maybeFreeze} from "./finalize"20+ PatchListener,21+ isDraft,22+ applyPatches,23+ isMap,24+ proxyMap,25+ isSet,26+ proxySet,27+ createProxy,28+ markChanged29+} from "./internal"30 31 /* istanbul ignore next */32 function verifyMinified() {}33 244 unmodified linesmodified:src/index.ts+12 added-11 removed
1-import {Immer} from "./immer"2-import {IProduce, IProduceWithPatches} from "./types"1+import {IProduce, IProduceWithPatches, Immer} from "./internal"2 4-export {Draft, Immutable, Patch, PatchListener} from "./types"3+export {4+ Draft,5+ Immutable,6+ Patch,7+ PatchListener,8+ original,9+ isDraft,10+ isDraftable,11+ NOTHING as nothing,12+ DRAFTABLE as immerable13+} from "./internal"14 15 const immer = new Immer()16 17 /**63 unmodified lines81 * changes that were made.82 */83 export const finishDraft = immer.finishDraft.bind(immer)84 76-export {77- original,78- isDraft,79- isDraftable,80- NOTHING as nothing,81- DRAFTABLE as immerable82-} from "./common"83-85 export {Immer}added:src/internal.ts+12 added
1+export * from "./env"2+export * from "./extends"3+export * from "./types"4+export * from "./common"5+export * from "./scope"6+export * from "./finalize"7+export * from "./proxy"8+export * from "./es5"9+export * from "./map"10+export * from "./set"11+export * from "./patches"12+export * from "./immer"modified:src/map.ts+55 added-31 removed
1-import {isDraftable, DRAFT_STATE, latest, iteratorSymbol} from "./common"1+import {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"15 3-import {ImmerScope} from "./scope"4-import {AnyMap, Drafted, ImmerState, ImmerBaseState, ProxyType} from "./types"5-import {assertUnrevoked} from "./es5"6-16 export interface MapState extends ImmerBaseState {17 type: ProxyType.Map18 copy: AnyMap | undefined19 assigned: Map<any, boolean> | undefined1 unmodified line21 revoked: boolean22 draft: Drafted<AnyMap, MapState>23 }24 16-// Make sure DraftMap declarion doesn't die if Map is not avialable...17-/* istanbul ignore next */18-const MapBase: MapConstructor =19- typeof Map !== "undefined" ? Map : (function FakeMap() {} as any)20-21-export class DraftMap<K, V> extends MapBase implements Map<K, V> {22- [DRAFT_STATE]: MapState23- constructor(target: AnyMap, parent?: ImmerState) {24- super()25+const 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!,1 unmodified line38 finalized: false,39 copy: undefined,40 assigned: undefined,41 base: target,34- draft: this,42+ draft: this as any,43 isManual: false,44 revoked: false45 }46+ return this47 }48+ const p = DraftMap.prototype49 50+ // TODO: smaller build size if we create a util for Object.defineProperty51+ Object.defineProperty(p, "size", {40- get size(): number {41- return latest(this[DRAFT_STATE]).size42- }52+ get: function() {53+ return latest(this[DRAFT_STATE]).size54+ },55+ enumerable: true,56+ configurable: true57+ })58 44- has(key: K): boolean {59+ p.has = function(key: any): boolean {60 return latest(this[DRAFT_STATE]).has(key)61 }62 48- set(key: K, value: V): this {63+ 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)4 unmodified lines72 }73 return this74 }75 61- delete(key: K): boolean {76+ p.delete = function(key: any): boolean {77 if (!this.has(key)) {78 return false79 }80 5 unmodified lines86 state.copy!.delete(key)87 return true88 }89 75- clear() {90+ p.clear = function() {91 const state = this[DRAFT_STATE]92 assertUnrevoked(state)93 prepareCopy(state)94 state.scope.immer.markChanged(state)3 unmodified lines98 }99 return state.copy!.clear()100 }101 87- forEach(cb: (value: V, key: K, self: this) => void, thisArg?: any) {102+ p.forEach = function(103+ cb: (value: any, key: any, self: any) => void,104+ thisArg?: any105+ ) {106 const state = this[DRAFT_STATE]89- latest(state).forEach((_value: V, key: K, _map: this) => {107+ latest(state).forEach((_value: any, key: any, _map: any) => {108 cb.call(thisArg, this.get(key), key, this)109 })110 }111 94- get(key: K): V {112+ p.get = function(key: any): any {113 const state = this[DRAFT_STATE]114 assertUnrevoked(state)115 const value = latest(state).get(key)116 if (state.finalized || !isDraftable(value)) {8 unmodified lines125 state.copy!.set(key, draft)126 return draft127 }128 111- keys(): IterableIterator<K> {129+ p.keys = function(): IterableIterator<any> {130 return latest(this[DRAFT_STATE]).keys()131 }132 115- values(): IterableIterator<V> {133+ p.values = function(): IterableIterator<any> {134 const iterator = this.keys()135 return {136 [iteratorSymbol]: () => this.values(),137 next: () => {8 unmodified lines146 }147 } as any148 }149 132- entries(): IterableIterator<[K, V]> {150+ p.entries = function(): IterableIterator<[any, any]> {151 const iterator = this.keys()152 return {153 [iteratorSymbol]: () => this.entries(),154 next: () => {8 unmodified lines163 }164 } as any165 }166 149- [iteratorSymbol]() {167+ p[iteratorSymbol] = function() {168 return this.entries()169 }152-}170 154-export function proxyMap(target: AnyMap, parent?: ImmerState) {171+ return DraftMap172+})(Map)173+174+export function proxyMap<T extends AnyMap>(175+ target: T,176+ parent?: ImmerState177+): T & {[DRAFT_STATE]: MapState} {178+ // @ts-ignore179 return new DraftMap(target, parent)180 }181 182 function prepareCopy(state: MapState) {5 unmodified linesmodified:src/patches.ts+18 added-6 removed
1-import {get, each, isMap, has, die, getArchtype} from "./common"2-import {Patch, ImmerState, ProxyType, Archtype} from "./types"3-import {SetState} from "./set"4-import {ES5ArrayState, ES5ObjectState} from "./es5"5-import {ProxyArrayState, ProxyObjectState} from "./proxy"6-import {MapState} from "./map"1+import {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+ isMap18+} from "./internal"19 20 export type PatchPath = (string | number)[]21 22 export function generatePatches(240 unmodified linesmodified:src/proxy.ts+8 added-10 removed
3 unmodified lines4 has,5 is,6 isDraftable,7 shallowCopy,8- DRAFT_STATE,9- latest10-} from "./common"11-import {ImmerScope} from "./scope"12-import {13- AnyObject,14- Drafted,8+ latest,9+ ImmerBaseState,10 ImmerState,11+ Drafted,12+ ProxyType,13+ AnyObject,14 AnyArray,15 Objectish,18- ImmerBaseState,19- ProxyType20-} from "./types"16+ ImmerScope,17+ DRAFT_STATE18+} from "./internal"19 20 interface ProxyBaseState extends ImmerBaseState {21 assigned: {22 [property: string]: boolean235 unmodified linesmodified:src/scope.ts+8 added-3 removed
1-import {DRAFT_STATE} from "./common"2-import {Patch, PatchListener, Drafted, ProxyType} from "./types"3-import {Immer} from "./immer"1+import {2+ Patch,3+ PatchListener,4+ Drafted,5+ ProxyType,6+ Immer,7+ DRAFT_STATE8+} from "./internal"9 10 /** Each scope represents a `produce` call. */11 export class ImmerScope {12 static current?: ImmerScope56 unmodified linesmodified:src/set.ts+48 added-28 removed
1-import {DRAFT_STATE, latest, isDraftable, iteratorSymbol} from "./common"1+import {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"15 3-import {ImmerScope} from "./scope"4-import {AnySet, Drafted, ImmerState, ImmerBaseState, ProxyType} from "./types"5-import {assertUnrevoked} from "./es5"6-16 export interface SetState extends ImmerBaseState {17 type: ProxyType.Set18 copy: AnySet | undefined19 base: AnySet1 unmodified line21 revoked: boolean22 draft: Drafted<AnySet, SetState>23 }24 16-// Make sure DraftSet declarion doesn't die if Map is not avialable...17-/* istanbul ignore next */18-const SetBase: SetConstructor =19- typeof Set !== "undefined" ? Set : (function FakeSet() {} as any)20-21-export class DraftSet<K, V> extends SetBase implements Set<V> {22- [DRAFT_STATE]: SetState23- constructor(target: AnySet, parent?: ImmerState) {24- super()25+const 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!,5 unmodified lines42 drafts: new Map(),43 revoked: false,44 isManual: false45 }46+ return this47 }48+ const p = DraftSet.prototype49 50+ Object.defineProperty(p, "size", {40- get size(): number {41- return latest(this[DRAFT_STATE]).size42- }51+ get: function() {52+ return latest(this[DRAFT_STATE]).size53+ },54+ enumerable: true,55+ configurable: true56+ })57 44- has(value: V): boolean {58+ 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) {4 unmodified lines67 return true68 return false69 }70 57- add(value: V): this {71+ p.add = function(value: any): any {72 const state = this[DRAFT_STATE]73 assertUnrevoked(state)74 if (state.copy) {75 state.copy.add(value)4 unmodified lines80 }81 return this82 }83 70- delete(value: V): boolean {84+ p.delete = function(value: any): any {85 if (!this.has(value)) {86 return false87 }88 8 unmodified lines97 : /* istanbul ignore next */ false)98 )99 }100 87- clear() {101+ 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 }108 95- values(): IterableIterator<V> {109+ p.values = function(): IterableIterator<any> {110 const state = this[DRAFT_STATE]111 assertUnrevoked(state)112 prepareCopy(state)113 return state.copy!.values()114 }115 102- entries(): IterableIterator<[V, V]> {116+ 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 }122 109- keys(): IterableIterator<V> {123+ p.keys = function(): IterableIterator<any> {124 return this.values()125 }126 113- [iteratorSymbol]() {127+ p[iteratorSymbol] = function() {128 return this.values()129 }130 117- forEach(cb: (value: V, key: V, self: this) => void, thisArg?: any) {131+ 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 }125-}139 127-export function proxySet(target: AnySet, parent?: ImmerState) {140+ return DraftSet141+})(Set)142+143+export function proxySet<T extends AnySet>(144+ target: T,145+ parent?: ImmerState146+): T & {[DRAFT_STATE]: SetState} {147+ // @ts-ignore148 return new DraftSet(target, parent)149 }150 151 function prepareCopy(state: SetState) {14 unmodified linesmodified:src/types.ts+11 added-6 removed
1-import {Nothing, DRAFT_STATE} from "./common"2-import {SetState} from "./set"3-import {MapState} from "./map"4-import {ProxyObjectState, ProxyArrayState} from "./proxy"5-import {ES5ObjectState, ES5ArrayState} from "./es5"6-import {ImmerScope} from "./scope"1+import {2+ SetState,3+ ImmerScope,4+ ProxyObjectState,5+ ProxyArrayState,6+ ES5ObjectState,7+ ES5ArrayState,8+ MapState,9+ DRAFT_STATE,10+ Nothing11+} from "./internal"12 13 export type Objectish = AnyObject | AnyArray | AnyMap | AnySet14 export type ObjectishNoSet = AnyObject | AnyArray | AnyMap15 206 unmodified linesmodified:tsconfig.json+1 added-1 removed
1 {2 "compilerOptions": {3 "lib": ["es2015"],4- "target": "ES6",4+ "target": "ES5",5 "strict": true,6 "declaration": true,7 "importHelpers": false,8 "noImplicitAny": true,9 unmodified lines