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
Provenance
- Commit
124518b- Tree
c68a9f4- Author
Michel Weststrate <mweststrate@fb.com>- Committer
Michel Weststrate <mweststrate@fb.com>- Parent
c7e9de8
13 files changed+1064 added−951 removed
added:src/plugins/es5/es5.ts+286 added
1+"use strict"2+import {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"23+24+type ES5State = ES5ArrayState | ES5ObjectState25+26+export 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+}46+47+export function createES5Proxy<T>(48+ base: T,49+ parent?: ImmerState50+): Drafted<T, ES5ObjectState | ES5ArrayState> {51+ const isArray = Array.isArray(base)52+ const draft = clonePotentialDraft(base)53+54+ each(draft, prop => {55+ proxyProperty(draft, prop, isArray || isEnumerable(base, prop))56+ })57+58+ 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+ }72+73+ createHiddenProperty(draft, DRAFT_STATE, state)74+ return draft75+}76+77+// Access a property without creating an Immer draft.78+function 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+}88+89+function 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+}101+102+function 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+}113+114+export function markChangedES5(state: ImmerState) {115+ if (!state.modified) {116+ state.modified = true117+ if (state.parent) markChangedES5(state.parent)118+ }119+}120+121+function prepareCopy(state: ES5State) {122+ if (!state.copy) state.copy = clonePotentialDraft(state.base)123+}124+125+function 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+}135+136+// property descriptors are recycled to make sure we don't create a get and set closure per property,137+// but share them all instead138+const descriptors: {[prop: string]: PropertyDescriptor} = {}139+140+function 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+}162+163+// This looks expensive, but only proxies are visited, and only objects without known changes are scanned.164+function 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+}183+184+function 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+ }219+220+ 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+ }225+226+ // Minimum count is enough, the other parts has been processed.227+ const min = Math.min(draft.length, base.length)228+229+ for (let i = 0; i < min; i++) {230+ // Only untouched indices trigger recursion.231+ if (assigned[i] === undefined) markChangesRecursively(draft[i])232+ }233+ }234+}235+236+function hasObjectChanges(state: ES5ObjectState) {237+ const {base, draft} = state238+239+ // 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+ }259+260+ // 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+}264+265+function 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+}281+282+loadPlugin("es5", {283+ createES5Proxy,284+ markChangedES5,285+ willFinalizeES5286+})added:src/plugins/mapset/extends.ts+24 added
123456789101112131415161718192021222324/* istanbul ignore next */var extendStatics = function(d: any, b: any): any { extendStatics = Object.setPrototypeOf || ({__proto__: []} instanceof Array && function(d, b) { d.__proto__ = b }) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p] } return extendStatics(d, b)}
// Ugly hack to resolve #502 and inherit built in Map / Setexport function __extends(d: any, b: any): any { extendStatics(d, b) function __(this: any): any { this.constructor = d } d.prototype = // @ts-ignore ((__.prototype = b.prototype), new __())}added:src/plugins/mapset/map.ts+178 added
1+import {__extends} from "./extends"2+import {proxySet} from "./set"3+import {4+ ProxyType,5+ AnyMap,6+ ImmerState,7+ DRAFT_STATE,8+ ImmerScope,9+ latest,10+ assertUnrevoked,11+ isDraftable,12+ iteratorSymbol,13+ MapState14+} from "../../internal"15+import {loadPlugin} from "../../plugins"16+17+const 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.prototype41+42+ // 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+ })50+51+ p.has = function(key: any): boolean {52+ return latest(this[DRAFT_STATE]).has(key)53+ }54+55+ 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+ }67+68+ p.delete = function(key: any): boolean {69+ if (!this.has(key)) {70+ return false71+ }72+73+ 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+ }81+82+ 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+ }90+91+ 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+ }100+101+ 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+ }117+118+ p.keys = function(): IterableIterator<any> {119+ return latest(this[DRAFT_STATE]).keys()120+ }121+122+ 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+ }138+139+ 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+ }155+156+ p[iteratorSymbol] = function() {157+ return this.entries()158+ }159+160+ return DraftMap161+})(Map)162+163+export function proxyMap<T extends AnyMap>(164+ target: T,165+ parent?: ImmerState166+): T & {[DRAFT_STATE]: MapState} {167+ // @ts-ignore168+ return new DraftMap(target, parent)169+}170+171+function prepareCopy(state: MapState) {172+ if (!state.copy) {173+ state.assigned = new Map()174+ state.copy = new Map(state.base)175+ }176+}177+178+loadPlugin("mapset", {proxyMap, proxySet})added:src/plugins/mapset/set.ts+157 added
1+import {__extends} from "./extends"2+import {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"16+17+const 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.prototype41+42+ Object.defineProperty(p, "size", {43+ get: function() {44+ return latest(this[DRAFT_STATE]).size45+ },46+ enumerable: true,47+ configurable: true48+ })49+50+ 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+ }62+63+ 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+ }75+76+ p.delete = function(value: any): any {77+ if (!this.has(value)) {78+ return false79+ }80+81+ 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+ }92+93+ 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+ }100+101+ p.values = function(): IterableIterator<any> {102+ const state = this[DRAFT_STATE]103+ assertUnrevoked(state)104+ prepareCopy(state)105+ return state.copy!.values()106+ }107+108+ 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+ }114+115+ p.keys = function(): IterableIterator<any> {116+ return this.values()117+ }118+119+ p[iteratorSymbol] = function() {120+ return this.values()121+ }122+123+ 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+ }131+132+ return DraftSet133+})(Set)134+135+export function proxySet<T extends AnySet>(136+ target: T,137+ parent?: ImmerState138+): T & {[DRAFT_STATE]: SetState} {139+ // @ts-ignore140+ return new DraftSet(target, parent)141+}142+143+function 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
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+ isMap,18+ isSet,19+ PatchPath,20+ loadPlugin21+} from "../../internal"22+23+export 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+}51+52+function 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()61+62+ // 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+ }68+69+ const delta = copy.length - base.length70+71+ // Find the first replaced index.72+ let start = 073+ while (base[start] === copy[start] && start < base.length) {74+ ++start75+ }76+77+ // 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+ }82+83+ // 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+ }99+100+ const replaceCount = patches.length101+102+ // 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+}116+117+// This is used for both Map objects and normal objects.118+function 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+}141+142+function generateSetPatches(143+ state: SetState,144+ basePath: PatchPath,145+ patches: Patch[],146+ inversePatches: Patch[]147+) {148+ let {base, copy} = state149+150+ 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+}185+186+export function applyPatches<T>(draft: T, patches: Patch[]): T {187+ patches.forEach(patch => {188+ const {path, op} = patch189+190+ /* istanbul ignore next */191+ if (!path.length) die()192+193+ 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+ }199+200+ 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+ })244+245+ return draft246+}247+248+// 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)251+function deepClonePatchValue<T>(obj: T): T252+function 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+}264+265+loadPlugin("patches", {applyPatches, generatePatches})modified:src/common.ts+8 added
208 unmodified lines209 /* istanbul ignore next */210 export function die(): never {211 throw new Error("Illegal state, please file a bug")212 }213+214+export 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"2-import {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"24-25-interface ES5BaseState extends ImmerBaseState {26- finalizing: boolean27- assigned: {[key: string]: any}28- parent?: ImmerState29- revoked: boolean30-}31-32-export interface ES5ObjectState extends ES5BaseState {33- type: ProxyType.ES5Object34- draft: Drafted<AnyObject, ES5ObjectState>35- base: AnyObject36- copy: AnyObject | null37-}38-39-export interface ES5ArrayState extends ES5BaseState {40- type: ProxyType.ES5Array41- draft: Drafted<AnyObject, ES5ArrayState>42- base: AnyArray43- copy: AnyArray | null44-}45-46-type ES5State = ES5ArrayState | ES5ObjectState47-48-export 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-}68-69-export function createES5Proxy<T>(70- base: T,71- parent?: ImmerState72-): Drafted<T, ES5ObjectState | ES5ArrayState> {73- const isArray = Array.isArray(base)74- const draft = clonePotentialDraft(base)75-76- each(draft, prop => {77- proxyProperty(draft, prop, isArray || isEnumerable(base, prop))78- })79-80- 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- }94-95- createHiddenProperty(draft, DRAFT_STATE, state)96- return draft97-}98-99-// Access a property without creating an Immer draft.100-function 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-}110-111-function 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-}123-124-function 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-}135-136-export function markChangedES5(state: ImmerState) {137- if (!state.modified) {138- state.modified = true139- if (state.parent) markChangedES5(state.parent)140- }141-}142-143-function prepareCopy(state: ES5State) {144- if (!state.copy) state.copy = clonePotentialDraft(state.base)145-}146-147-function 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-}157-158-// property descriptors are recycled to make sure we don't create a get and set closure per property,159-// but share them all instead160-const descriptors: {[prop: string]: PropertyDescriptor} = {}161-162-function 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-}184-185-export 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-}192-193-// This looks expensive, but only proxies are visited, and only objects without known changes are scanned.194-function 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-}213-214-function 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- }249-250- 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- }255-256- // Minimum count is enough, the other parts has been processed.257- const min = Math.min(draft.length, base.length)258-259- for (let i = 0; i < min; i++) {260- // Only untouched indices trigger recursion.261- if (assigned[i] === undefined) markChangesRecursively(draft[i])262- }263- }264-}265-266-function hasObjectChanges(state: ES5ObjectState) {267- const {base, draft} = state268-269- // 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- }289-290- // 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-}294-295-function 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
123456789101112131415161718192021222324/* istanbul ignore next */var extendStatics = function(d: any, b: any): any { extendStatics = Object.setPrototypeOf || ({__proto__: []} instanceof Array && function(d, b) { d.__proto__ = b }) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p] } return extendStatics(d, b)}
// Ugly hack to resolve #502 and inherit built in Map / Setexport function __extends(d: any, b: any): any { extendStatics(d, b) function __(this: any): any { this.constructor = d } d.prototype = // @ts-ignore ((__.prototype = b.prototype), new __())}modified:src/internal.ts+1 added-5 removed
12234567910111289export * from "./env"export * from "./extends"export * from "./types-external"export * from "./types-internal"export * from "./common"export * from "./scope"export * from "./finalize"export * from "./proxy"export * from "./es5"export * from "./map"export * from "./set"export * from "./patches"export * from "./immer"export * from "./plugins"deleted:src/map.ts-184 removed
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-16-export 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-}24-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!,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.prototype49-50- // 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- })58-59- p.has = function(key: any): boolean {60- return latest(this[DRAFT_STATE]).has(key)61- }62-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)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- }75-76- p.delete = function(key: any): boolean {77- if (!this.has(key)) {78- return false79- }80-81- 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- }89-90- 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- }98-99- 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- }108-109- 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- }125-126- p.keys = function(): IterableIterator<any> {127- return latest(this[DRAFT_STATE]).keys()128- }129-130- 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- }146-147- 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- }163-164- p[iteratorSymbol] = function() {165- return this.entries()166- }167-168- return DraftMap169-})(Map)170-171-export function proxyMap<T extends AnyMap>(172- target: T,173- parent?: ImmerState174-): T & {[DRAFT_STATE]: MapState} {175- // @ts-ignore176- return new DraftMap(target, parent)177-}178-179-function 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
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- isMap,18- isSet19-} from "./internal"20-21-export type PatchPath = (string | number)[]22-23-export 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-}51-52-function 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()61-62- // 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- }68-69- const delta = copy.length - base.length70-71- // Find the first replaced index.72- let start = 073- while (base[start] === copy[start] && start < base.length) {74- ++start75- }76-77- // 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- }82-83- // 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- }99-100- const replaceCount = patches.length101-102- // 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-}116-117-// This is used for both Map objects and normal objects.118-function 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-}141-142-function generateSetPatches(143- state: SetState,144- basePath: PatchPath,145- patches: Patch[],146- inversePatches: Patch[]147-) {148- let {base, copy} = state149-150- 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-}185-186-export function applyPatches<T>(draft: T, patches: Patch[]): T {187- patches.forEach(patch => {188- const {path, op} = patch189-190- /* istanbul ignore next */191- if (!path.length) die()192-193- 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- }199-200- 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- })244-245- return draft246-}247-248-// 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)251-function deepClonePatchValue<T>(obj: T): T252-function 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
1+import {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"14+15+/** Plugin utilities */16+const 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+} = {}31+32+type Plugins = typeof plugins33+34+export 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+}46+47+export function loadPlugin<K extends keyof Plugins>(48+ pluginKey: K,49+ implementation: Plugins[K]50+) {51+ plugins[pluginKey] = implementation52+}53+54+/** ES5 Plugin */55+56+interface ES5BaseState extends ImmerBaseState {57+ finalizing: boolean58+ assigned: {[key: string]: any}59+ parent?: ImmerState60+ revoked: boolean61+}62+63+export interface ES5ObjectState extends ES5BaseState {64+ type: ProxyType.ES5Object65+ draft: Drafted<AnyObject, ES5ObjectState>66+ base: AnyObject67+ copy: AnyObject | null68+}69+70+export interface ES5ArrayState extends ES5BaseState {71+ type: ProxyType.ES5Array72+ draft: Drafted<AnyObject, ES5ArrayState>73+ base: AnyArray74+ copy: AnyArray | null75+}76+77+export function willFinalizeES5(78+ scope: ImmerScope,79+ result: any,80+ isReplaced: boolean81+) {82+ getPlugin("es5").willFinalizeES5(scope, result, isReplaced)83+}84+85+export function createES5Proxy<T>(86+ base: T,87+ parent?: ImmerState88+): Drafted<T, ES5ObjectState | ES5ArrayState> {89+ return getPlugin("es5").createES5Proxy(base, parent)90+}91+92+export function markChangedES5(state: ImmerState) {93+ getPlugin("es5").markChangedES5(state)94+}95+96+/** Map / Set plugin */97+98+export 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+}106+107+export 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+}115+116+export function proxyMap<T extends AnyMap>(117+ target: T,118+ parent?: ImmerState119+): T & {[DRAFT_STATE]: MapState} {120+ return getPlugin("mapset").proxyMap(target, parent)121+}122+123+export function proxySet<T extends AnySet>(124+ target: T,125+ parent?: ImmerState126+): T & {[DRAFT_STATE]: SetState} {127+ return getPlugin("mapset").proxySet(target, parent)128+}129+130+/** Patches plugin */131+132+export type PatchPath = (string | number)[]133+134+export 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+}142+143+export function applyPatches<T>(draft: T, patches: Patch[]): T {144+ return getPlugin("patches").applyPatches(draft, patches)145+}deleted:src/set.ts-165 removed
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-16-export 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-}24-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!,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.prototype49-50- Object.defineProperty(p, "size", {51- get: function() {52- return latest(this[DRAFT_STATE]).size53- },54- enumerable: true,55- configurable: true56- })57-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) {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- }70-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)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- }83-84- p.delete = function(value: any): any {85- if (!this.has(value)) {86- return false87- }88-89- 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- }100-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-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-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-123- p.keys = function(): IterableIterator<any> {124- return this.values()125- }126-127- p[iteratorSymbol] = function() {128- return this.values()129- }130-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- }139-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) {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-}