diff --git a/README.md b/README.md index 7f91306f..bc4bb6ca 100644 --- a/README.md +++ b/README.md @@ -247,7 +247,7 @@ The `options` argument is optional; [`makeCreator()`](#makecreator) sets default - `enableAutoFreeze` - `boolean`, the default is `false`. - Freeze the next state deeply, also the parts that it shares with the base state, and, in development builds, throw for an object that holds itself. + Freeze the next state deeply, also the parts that it shares with the base state, and, in development builds, throw for an object that holds itself. Typed arrays, Node.js Buffers and DataViews are left unfrozen; see [What is frozen](https://mutative.js.org/docs/advanced-guides/auto-freeze#what-is-frozen). - `mark` - `Mark | Mark[]`, where `Mark` is `(target, { mutable, immutable }) => 'mutable' | 'immutable' | (() => copy) | undefined`. @@ -800,6 +800,10 @@ Mutative v2 keeps the v1 API. The changes below, made since v1.3.0, can affect e - `current()` of a changed array copies the current array instead of reading every element through the draft. Base elements that a native method moved and that hold drafts of an outer `create()` call are left as they are, as unmoved elements always were. - To search a large array without drafting each element it visits, search `current(draft.list)` and change the match through the draft; see [`current()`](#current). +### Auto-freeze + +Auto-freeze now leaves typed arrays, Node.js Buffers and DataViews unfrozen, including empty views. Earlier versions threw `TypeError: Cannot freeze array buffer views with elements` for a non-empty typed array. Their bytes and custom properties remain mutable, so copy the bytes before changing them. Other values retain the 2.0.x freeze behavior; see [What is frozen](https://mutative.js.org/docs/advanced-guides/auto-freeze#what-is-frozen). + ### Returned values - With `enableAutoFreeze`, production builds no longer search frozen objects in a value returned from a recipe, the returned value included, or the values they hold, for drafts, and leave a draft there unresolved. Development builds still search them and throw when they find one, also in an unfrozen object that a frozen one holds, where v1 replaced it. Never put a draft in a frozen object or in a value it holds. Without auto-freeze, returned values are searched as in v1. diff --git a/docs/interfaces/Options.md b/docs/interfaces/Options.md index 0898216a..ae27f1c9 100644 --- a/docs/interfaces/Options.md +++ b/docs/interfaces/Options.md @@ -23,7 +23,8 @@ > `optional` **enableAutoFreeze**: `F` Freeze the next state deeply, also the parts that it shares with the base -state. Development builds also throw for an object that holds itself. +state. ArrayBuffer views are left unfrozen. Development builds also +throw for an object that holds itself. *** diff --git a/scripts/build-size-baseline.json b/scripts/build-size-baseline.json index f02b9ae5..96034d62 100644 --- a/scripts/build-size-baseline.json +++ b/scripts/build-size-baseline.json @@ -1,8 +1,8 @@ { "reference": { - "revision": "c6ce7aa2d550c27a14bcdbe7f38fa6d8397dade5", - "description": "Security update to esbuild 0.28.2: unchanged library artifacts; CJS consumer wrappers add 154 raw bytes, at most 55 gzip bytes and 53 Brotli bytes", - "node": "v24.16.0", + "revision": "1a363492eca37ee283477d5357d3d3dd6257efb5", + "description": "Reference auto-freeze implementation before restoring the 2.0.x freeze policy: includes the ArrayBuffer view exception, draftable-only freezing and the class-instance migration warning.", + "node": "v24.22.0", "commands": [ "pnpm install --frozen-lockfile", "pnpm build" @@ -15,69 +15,69 @@ "esbuild": "0.28.2", "measurements": { "artifact/mutative.cjs.production.min.js": { - "raw": 28489, - "gzip": 9621, - "brotli": 8816 + "raw": 28838, + "gzip": 9714, + "brotli": 8912 }, "artifact/mutative.umd.production.min.js": { - "raw": 28644, - "gzip": 9696, - "brotli": 8863 + "raw": 28995, + "gzip": 9771, + "brotli": 8950 }, "artifact/mutative.esm.production.min.mjs": { - "raw": 28461, - "gzip": 9644, - "brotli": 8838 + "raw": 28810, + "gzip": 9733, + "brotli": 8941 }, "artifact/mutative.cjs.development.js": { - "raw": 75852, - "gzip": 18457, - "brotli": 15984 + "raw": 78995, + "gzip": 19396, + "brotli": 16765 }, "artifact/mutative.umd.development.js": { - "raw": 78214, - "gzip": 18668, - "brotli": 16166 + "raw": 81404, + "gzip": 19630, + "brotli": 16950 }, "artifact/mutative.esm.js": { - "raw": 76687, - "gzip": 18552, - "brotli": 16050 + "raw": 79842, + "gzip": 19512, + "brotli": 16858 }, "artifact/mutative.esm.mjs": { - "raw": 76688, - "gzip": 18554, - "brotli": 16052 + "raw": 79843, + "gzip": 19513, + "brotli": 16850 }, "consumer/import/create": { - "raw": 25647, - "gzip": 9022, - "brotli": 8305 + "raw": 25999, + "gzip": 9142, + "brotli": 8413 }, "consumer/import/patches": { - "raw": 27711, - "gzip": 9711, - "brotli": 8948 + "raw": 28063, + "gzip": 9824, + "brotli": 9021 }, "consumer/import/all": { - "raw": 28497, - "gzip": 9972, - "brotli": 9177 + "raw": 28849, + "gzip": 10078, + "brotli": 9250 }, "consumer/require/create": { - "raw": 28131, - "gzip": 10046, - "brotli": 9235 + "raw": 28476, + "gzip": 10140, + "brotli": 9327 }, "consumer/require/patches": { - "raw": 28199, - "gzip": 10083, - "brotli": 9263 + "raw": 28544, + "gzip": 10178, + "brotli": 9376 }, "consumer/require/all": { - "raw": 28096, - "gzip": 10028, - "brotli": 9212 + "raw": 28441, + "gzip": 10119, + "brotli": 9302 } } } diff --git a/src/current.ts b/src/current.ts index eaa45a85..0494de19 100644 --- a/src/current.ts +++ b/src/current.ts @@ -31,13 +31,24 @@ export function handleReturnValue( useRawReturn?: boolean ) { let containsDraft = false; + const options = rootDraft?.options; // With auto-freeze, the state is frozen, so production builds do not search // frozen objects, the returned value included, or the values they hold, - // which spares searching state built from earlier states. Without it, - // values are rarely frozen and checking would cost more than it saves. - const skipsFrozen = !!rootDraft?.options.enableAutoFreeze; - // `frozen` tells development builds that a skipped object holds `target`. - const replaceDrafts = (target: object, frozen?: boolean) => + // which spares searching state built from earlier states. An unfrozen + // container may hold drafts regardless of whether it will be frozen. + // Without auto-freeze, values are rarely frozen and checking would cost + // more than it saves. + const isSkipped = (target: object) => + !!options?.enableAutoFreeze && Object.isFrozen(target); + // Development builds search the skipped objects too, to report the drafts + // that production builds would leave there, and each of them once, as a + // frozen object may hold itself. + const searched = __DEV__ ? new WeakSet() : undefined; + // `skipped` tells development builds that a skipped object holds `target`. + // The elements of an ArrayBuffer view are numbers, and listing them as keys + // costs time in proportion to its bytes, so views are not searched. + const replaceDrafts = (target: object, skipped?: boolean) => + !ArrayBuffer.isView(target) && forEach(target, (key, item, source) => { const proxyDraft = getProxyDraft(item); // just handle the draft which is created by the same rootDraft @@ -46,7 +57,7 @@ export function handleReturnValue( rootDraft && proxyDraft.finalities === rootDraft.finalities ) { - if (__DEV__ && frozen) { + if (__DEV__ && skipped) { throw new Error( `The return value holds a draft in a frozen object or in a value it holds. With auto-freeze, production builds do not search frozen objects for drafts, so do not put drafts there.` ); @@ -64,19 +75,19 @@ export function handleReturnValue( set(source, key, currentValue); } } else if (typeof item === 'object' && item !== null) { - // Development builds search skipped objects too, to report the drafts - // that production builds would leave there. - if (!skipsFrozen || !Object.isFrozen(item)) { - replaceDrafts(item, frozen); - } else if (__DEV__) { + if (!skipped && !isSkipped(item)) { + replaceDrafts(item); + } else if (__DEV__ && !searched!.has(item)) { + searched!.add(item); replaceDrafts(item, true); } } }); // The returned value follows the same rule as the values it holds. - if (!skipsFrozen || !Object.isFrozen(value)) { + if (!isSkipped(value)) { replaceDrafts(value); } else if (__DEV__) { + searched!.add(value); replaceDrafts(value, true); } if (__DEV__) { diff --git a/src/interface.ts b/src/interface.ts index 0d05ed0d..66d78d99 100644 --- a/src/interface.ts +++ b/src/interface.ts @@ -181,7 +181,8 @@ export interface Options { enablePatches?: O; /** * Freeze the next state deeply, also the parts that it shares with the base - * state. Development builds also throw for an object that holds itself. + * state. ArrayBuffer views are left unfrozen. Development builds also + * throw for an object that holds itself. */ enableAutoFreeze?: F; /** @@ -211,7 +212,8 @@ export interface ExternalOptions { enablePatches?: O; /** * Freeze the next state deeply, also the parts that it shares with the base - * state. Development builds also throw for an object that holds itself. + * state. ArrayBuffer views are left unfrozen. Development builds also + * throw for an object that holds itself. */ enableAutoFreeze?: F; /** diff --git a/src/utils/deepFreeze.ts b/src/utils/deepFreeze.ts index bdefb9c9..62882afa 100644 --- a/src/utils/deepFreeze.ts +++ b/src/utils/deepFreeze.ts @@ -53,7 +53,13 @@ export function deepFreeze( stack.push(target); } } - if (Object.isFrozen(target) || isDraft(target)) { + // Views cannot make their bytes read-only, and freezing a non-empty typed + // array throws. Keep the 2.x freeze policy for every other value. + if ( + Object.isFrozen(target) || + isDraft(target) || + ArrayBuffer.isView(target) + ) { if (__DEV__) { stack!.pop(); keys!.pop(); diff --git a/test/auto-freeze.test.ts b/test/auto-freeze.test.ts new file mode 100644 index 00000000..67db0144 --- /dev/null +++ b/test/auto-freeze.test.ts @@ -0,0 +1,316 @@ +/* eslint-disable @typescript-eslint/no-explicit-any */ +// Which values auto-freeze freezes, in development and production builds. +import { vi } from 'vitest'; +import { runInNewContext } from 'node:vm'; + +class Point { + x = 0; + nested = { y: 0 }; +} + +const mutables = new WeakSet(); +const markedMutable = (value: T) => { + mutables.add(value); + return value; +}; +const marks = { + immutable: (value: any, types: any) => + value instanceof Point ? types.immutable : undefined, + copy: (value: any) => + value instanceof Point + ? () => Object.assign(new Point(), value) + : undefined, + mutable: (value: any, types: any) => + typeof value === 'object' && value !== null && mutables.has(value) + ? types.mutable + : undefined, +}; + +type Case = [ + description: string, + make: () => any, + frozen: { development: boolean; production: boolean }, + options?: { + mark?: (value: any, types: any) => any; + at?: (value: any) => any; + }, +]; + +const both = (frozen: boolean) => ({ development: frozen, production: frozen }); + +const cases: Case[] = [ + ['a plain object', () => ({ a: 1 }), both(true)], + ['an array', () => [1], both(true)], + ['a Map', () => new Map([[1, 1]]), both(true)], + ['a Set', () => new Set([1]), both(true)], + ['a class instance', () => new Point(), both(true)], + [ + 'a plain object that a class instance holds', + () => new Point(), + both(true), + { at: (point) => point.nested }, + ], + ['a null-prototype object', () => Object.create(null), both(true)], + [ + 'a plain object of another realm', + () => runInNewContext('({ n: 1 })'), + both(true), + ], + ['a date', () => new Date(0), both(true)], + ['a regular expression', () => /a/g, both(true)], + ['a function', () => () => 1, { development: true, production: false }], + [ + 'a plain object that a function holds', + () => Object.assign(() => 1, { nested: { n: 0 } }), + { development: true, production: false }, + { at: (value) => value.nested }, + ], + ['a typed array', () => new Uint8Array(1), both(false)], + [ + 'a class instance marked immutable', + () => new Point(), + both(true), + { mark: marks.immutable }, + ], + [ + 'a plain object that a class instance marked immutable holds', + () => new Point(), + both(true), + { mark: marks.immutable, at: (point) => point.nested }, + ], + [ + 'a class instance marked with a shallow copy', + () => new Point(), + both(true), + { mark: marks.copy }, + ], + [ + 'a plain object marked mutable', + () => markedMutable({ a: 1 }), + both(true), + { mark: marks.mutable }, + ], + [ + 'a class instance marked mutable', + () => markedMutable(new Point()), + both(true), + { mark: marks.mutable }, + ], +]; + +test('freezing an unmarked instance does not read its constructor or warn', async () => { + vi.resetModules(); + globalThis.__DEV__ = true; + const { create } = await import('../src'); + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + try { + const prototype = Object.create(null, { + constructor: { + get() { + throw new Error('The constructor must not be read'); + }, + }, + }); + const value = Object.assign(Object.create(prototype), { nested: { n: 0 } }); + const state = create( + { value, n: 0 }, + (draft) => { + draft.n += 1; + }, + { enableAutoFreeze: true } + ); + expect(Object.isFrozen(state.value)).toBe(true); + expect(Object.isFrozen(state.value.nested)).toBe(true); + expect(warn).not.toHaveBeenCalled(); + } finally { + warn.mockRestore(); + } +}); + +for (const dev of [true, false]) { + const build = dev ? 'development' : 'production'; + describe(`auto-freeze, ${build}`, () => { + let mutative: typeof import('../src'); + beforeAll(async () => { + vi.resetModules(); + globalThis.__DEV__ = dev; + mutative = await import('../src'); + }); + afterAll(() => { + globalThis.__DEV__ = true; + }); + + test.each(cases)( + '%s, in the base state or assigned by the recipe', + (_, make, frozen, { mark, at = (value: any) => value } = {}) => { + const { create } = mutative; + const options = { enableAutoFreeze: true as const, mark }; + const state: any = create( + { value: make(), n: 0 }, + (draft) => { + draft.n += 1; + }, + options + ); + expect(Object.isFrozen(at(state.value))).toBe(frozen[build]); + const assigned = make(); + const next: any = create( + { n: 0 } as any, + (draft) => { + draft.value = assigned; + }, + options + ); + expect(next.value).toBe(assigned); + expect(Object.isFrozen(at(next.value))).toBe(frozen[build]); + } + ); + + test.each([ + ['a plain object', () => ({ a: 1 }), true], + ['a class instance', () => new Point(), true], + ])('%s used as a Map key', (_, make, frozen) => { + const { create } = mutative; + const key = make(); + const state = create( + { map: new Map([[key, 1]]), n: 0 }, + (draft) => { + draft.n += 1; + }, + { enableAutoFreeze: true } + ); + expect([...state.map.keys()][0]).toBe(key); + expect(Object.isFrozen(key)).toBe(frozen); + }); + + test('a class instance that holds itself', () => { + const { create } = mutative; + class Node { + self = this; + } + const base = { node: new Node(), item: { k: 1 }, n: 0 }; + const update = () => + create( + base, + (draft) => { + draft.n += 1; + }, + { enableAutoFreeze: true } + ); + if (dev) { + expect(update).toThrow('Forbids circular reference'); + } else { + const state = update(); + expect(state.node.self).toBe(state.node); + expect(Object.isFrozen(state.node)).toBe(true); + } + }); + + test('a mutable mark does not exempt a value from the 2.x freeze policy', () => { + const { create } = mutative; + const options = { enableAutoFreeze: true as const, mark: marks.mutable }; + const counter = markedMutable({ count: 0 }); + const state = create( + { counter, n: 0 }, + (draft) => { + draft.counter.count += 1; + }, + options + ); + expect(state.counter).toBe(counter); + expect(counter.count).toBe(1); + expect(Object.isFrozen(counter)).toBe(true); + expect(Object.isFrozen(state)).toBe(true); + expect(() => + create( + state, + (draft) => { + draft.counter.count += 1; + }, + options + ) + ).toThrow(TypeError); + }); + + test('a regular expression retains the 2.x freeze policy', () => { + const { create } = mutative; + const state = create( + { pattern: /a/g, n: 0 }, + (draft) => { + draft.n += 1; + }, + { enableAutoFreeze: true } + ); + expect(Object.isFrozen(state.pattern)).toBe(true); + expect(() => state.pattern.test('a')).toThrow(TypeError); + }); + + test('auto-freeze does not call marks for unread objects', () => { + const { create } = mutative; + const seen = new Set(); + const base = { unread: { a: 1 }, n: 0 }; + create( + base, + (draft) => { + draft.n += 1; + }, + { + enableAutoFreeze: true, + mark: (value: unknown) => { + seen.add(value); + return undefined; + }, + } + ); + expect(seen.has(base.unread)).toBe(false); + expect(Object.isFrozen(base.unread)).toBe(true); + }); + + test('a shared class instance cannot be used to change earlier states', () => { + const { create } = mutative; + const base = { point: new Point(), n: 0 }; + const state = create( + base, + (draft) => { + draft.n += 1; + }, + { enableAutoFreeze: true } + ); + expect(state.point).toBe(base.point); + expect(() => { + (state.point as Point).nested.y = 42; + }).toThrow(TypeError); + expect(base.point.nested.y).toBe(0); + }); + + test('a no-op recipe freezes a class instance and its children', () => { + const { create } = mutative; + const base = { point: new Point() }; + const state = create(base, () => {}, { enableAutoFreeze: true }); + expect(state).toBe(base); + expect(Object.isFrozen(state.point)).toBe(true); + expect(Object.isFrozen(state.point.nested)).toBe(true); + }); + + test('an identity mark does not leave the changed class copy unfrozen', () => { + const { create } = mutative; + const point = new Point(); + const state = create( + { point }, + (draft) => { + draft.point.x = 1; + }, + { + enableAutoFreeze: true, + mark: (value, { immutable }) => + value === point ? immutable : undefined, + } + ); + expect(state.point).not.toBe(point); + expect(state.point.x).toBe(1); + expect(point.x).toBe(0); + expect(Object.isFrozen(state.point)).toBe(true); + expect(Object.isFrozen(state.point.nested)).toBe(true); + }); + }); +} diff --git a/test/returned-class-drafts.test.ts b/test/returned-class-drafts.test.ts new file mode 100644 index 00000000..f7d4b237 --- /dev/null +++ b/test/returned-class-drafts.test.ts @@ -0,0 +1,108 @@ +import { vi } from 'vitest'; + +class Holder { + constructor(public item: any) {} +} + +const containers: [string, (item: any) => any, (value: any) => any][] = [ + [ + 'a returned class instance', + (item) => new Holder(item), + (value) => value.item, + ], + [ + 'a nested class instance', + (item) => ({ holder: new Holder(item) }), + (value) => value.holder.item, + ], + [ + 'a Map and Set inside a class instance', + (item) => new Holder(new Map([['items', new Set([item])]])), + (value) => [...value.item.get('items')][0], + ], + [ + 'a non-enumerable class property', + (item) => + Object.defineProperty(new Holder(undefined), 'item', { + value: item, + writable: true, + configurable: true, + enumerable: false, + }), + (value) => value.item, + ], + [ + 'an object without a prototype', + (item) => Object.assign(Object.create(null), { item }), + (value) => value.item, + ], +]; + +for (const dev of [true, false]) { + describe(`returned class drafts, ${dev ? 'development' : 'production'}`, () => { + let mutative: typeof import('../src'); + beforeAll(async () => { + vi.resetModules(); + globalThis.__DEV__ = dev; + mutative = await import('../src'); + }); + afterAll(() => { + globalThis.__DEV__ = true; + }); + + describe.each([false, true])('auto-freeze=%s', (enableAutoFreeze) => { + describe.each([false, true])('strict rawReturn=%s', (useRawReturn) => { + test.each(containers)( + `%s resolves its draft, freeze=${enableAutoFreeze}, strict rawReturn=${useRawReturn}`, + async (_, wrap, read) => { + const { create, rawReturn } = mutative; + const base = { item: { n: 1 } }; + let escaped: any; + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + try { + const [state, patches, inverse] = await create( + base as any, + (draft: any) => { + escaped = draft.item; + const value = wrap(draft.item); + return useRawReturn ? rawReturn(value) : value; + }, + { + enableAutoFreeze, + enablePatches: true, + strict: useRawReturn, + } + ); + expect(read(state)).toBe(base.item); + expect(read(state).n).toBe(1); + expect(patches).toEqual([ + { op: 'replace', path: [], value: state }, + ]); + expect(inverse).toEqual([ + { op: 'replace', path: [], value: base }, + ]); + expect(() => escaped.n).toThrow(/revoked/); + } finally { + warn.mockRestore(); + } + } + ); + }); + }); + + test('an async recipe resolves a draft held by its returned class', async () => { + const { create } = mutative; + const base = { item: { n: 1 } }; + const state = await create( + base as any, + async (draft: any) => { + await Promise.resolve(); + return new Holder(draft.item); + }, + { enableAutoFreeze: true } + ); + expect(state.item).toBe(base.item); + expect(state.item.n).toBe(1); + }); + }); +} diff --git a/test/typed-array-freeze.test.ts b/test/typed-array-freeze.test.ts new file mode 100644 index 00000000..b5b4bb28 --- /dev/null +++ b/test/typed-array-freeze.test.ts @@ -0,0 +1,188 @@ +/* eslint-disable @typescript-eslint/no-explicit-any */ +// https://github.com/unadlib/mutative/issues/219 +import { vi } from 'vitest'; + +const views = () => [ + new Uint8Array([1, 2, 3]), + new Float64Array([1.5]), + new BigInt64Array([BigInt(1)]), + new Uint8Array(0), + Buffer.from([1, 2, 3]), + new DataView(new ArrayBuffer(4)), + new Uint8Array(new ArrayBuffer(2, { maxByteLength: 8 })), +]; + +for (const dev of [true, false]) { + describe(`ArrayBuffer views under auto-freeze, ${dev ? 'development' : 'production'}`, () => { + let mutative: typeof import('../src'); + beforeAll(async () => { + vi.resetModules(); + globalThis.__DEV__ = dev; + mutative = await import('../src'); + }); + afterAll(() => { + globalThis.__DEV__ = true; + }); + + test('a view next to a changed value is shared and left unfrozen', () => { + const { create } = mutative; + for (const view of views()) { + const base = { view, list: [{ n: 0 }], other: { n: 0 } }; + const state = create( + base, + (draft) => { + draft.list[0].n = 1; + }, + { enableAutoFreeze: true } + ); + expect(state.view).toBe(view); + expect(Object.isFrozen(state.view)).toBe(false); + expect(Object.isFrozen(state)).toBe(true); + expect(Object.isFrozen(state.list[0])).toBe(true); + expect(Object.isFrozen(state.other)).toBe(true); + // A later update still works and freezes its copies. + const next = create( + state, + (draft) => { + draft.other.n = 2; + }, + { enableAutoFreeze: true } + ); + expect(next.view).toBe(view); + expect(Object.isFrozen(next.other)).toBe(true); + } + }); + + test('views in arrays, Map values, Map keys and Set items, assigned or unchanged', () => { + const { create } = mutative; + for (const view of views()) { + const make = () => ({ + list: [view], + map: new Map([ + ['k', view], + [view, 'v'], + ]), + set: new Set([view]), + n: 0, + }); + // Unchanged parts of the base state, a no-op recipe included. + const base = make(); + expect(create(base, () => {}, { enableAutoFreeze: true })).toBe(base); + expect(Object.isFrozen(base.map)).toBe(true); + expect(Object.isFrozen(view)).toBe(false); + // Values that the recipe assigns. + const state = create( + { n: 0 } as any, + (draft) => { + Object.assign(draft, make()); + draft.direct = view; + }, + { enableAutoFreeze: true } + ); + expect(state.direct).toBe(view); + expect(state.map.get('k')).toBe(view); + expect(state.set.has(view)).toBe(true); + expect(Object.isFrozen(state.set)).toBe(true); + expect(Object.isFrozen(view)).toBe(false); + } + }); + + test('returned values that hold views, or are views', () => { + const { create } = mutative; + const view = new Uint8Array([1]); + const base = { view, item: { n: 0 } }; + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + try { + const state: any = create( + base as any, + (draft: any) => ({ + view: draft.view, + item: draft.item, + extra: [draft.item], + }), + { enableAutoFreeze: true } + ); + // Drafts next to the view are still replaced. + expect(state.item).toBe(base.item); + expect(state.extra[0]).toBe(base.item); + expect(state.view).toBe(view); + expect(Object.isFrozen(state)).toBe(true); + const returned = create(base, () => view as any, { + enableAutoFreeze: true, + }); + expect(returned).toBe(view); + } finally { + warn.mockRestore(); + } + }); + + test('a returned value is searched without listing the elements of views', () => { + const { create } = mutative; + const view = new Uint8Array(1000); + const base = { view, n: 0 }; + const ownKeys = vi.spyOn(Reflect, 'ownKeys'); + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + try { + create(base, (draft) => ({ view: draft.view, n: draft.n + 1 })); + expect(ownKeys.mock.calls.some(([target]) => target === view)).toBe( + false + ); + } finally { + ownKeys.mockRestore(); + warn.mockRestore(); + } + }); + + test('apply() with auto-freeze and a patch whose value is a view', () => { + const { create, apply } = mutative; + const view = new Uint8Array([7]); + const [, patches] = create( + { n: 0 } as any, + (draft) => { + draft.view = view; + }, + { enablePatches: true } + ); + const state = apply({ n: 0 } as any, patches, { enableAutoFreeze: true }); + expect(state.view).toBe(view); + expect(Object.isFrozen(state)).toBe(true); + expect(Object.isFrozen(view)).toBe(false); + }); + + test('a view that the application froze stays frozen and is skipped', () => { + const { create } = mutative; + const view = Object.freeze(new Uint8Array(0)); + const state = create( + { view, n: 0 }, + (draft) => { + draft.n = 1; + }, + { enableAutoFreeze: true } + ); + expect(state.view).toBe(view); + expect(Object.isFrozen(state.view)).toBe(true); + }); + + test('a view that a mark makes draftable is left unfrozen too', () => { + const { create } = mutative; + const marks = [ + (value: any, types: any) => + ArrayBuffer.isView(value) ? types.immutable : undefined, + (value: any) => + value instanceof Uint8Array ? () => value.slice() : undefined, + ]; + for (const mark of marks) { + const view = new Uint8Array([1, 2]); + const state = create( + { view, n: 0 }, + (draft) => { + draft.n = 1; + }, + { enableAutoFreeze: true, mark } + ); + expect(state.view).toBe(view); + expect(Object.isFrozen(view)).toBe(false); + } + }); + }); +} diff --git a/website/content/docs/advanced-guides/auto-freeze.mdx b/website/content/docs/advanced-guides/auto-freeze.mdx index af333915..e31c7107 100644 --- a/website/content/docs/advanced-guides/auto-freeze.mdx +++ b/website/content/docs/advanced-guides/auto-freeze.mdx @@ -40,9 +40,13 @@ Set it for a whole application with [`makeCreator()`](/docs/api-reference/makecr ## What is frozen - Every object of the next state that its enumerable keys reach: the copies of the objects that the recipe changed, the values that it assigned, and the objects that the next state shares with the base state, which are frozen in the base state as well. A recipe that changes nothing returns the base state itself, frozen. -- Class instances, dates and functions, which `Object.freeze()` freezes like any object. A `Date` keeps its setters, such as `setFullYear()`, since its value is not a property. +- Class instances, objects without a prototype, dates and regular expressions. Development builds also freeze functions and their own enumerable properties. A `Date` keeps its setters, such as `setFullYear()`, since its value is not a property. - Maps and Sets, whose `set()`, `add()`, `delete()` and `clear()` methods then throw, and the objects that a Map uses as keys. +Typed arrays, Node.js Buffers and DataViews are skipped together with the values they hold, even when empty or marked `immutable`. Freezing a non-empty typed array throws, and `Object.freeze()` cannot make any view's bytes read-only. Views are shared with the base state; copy the bytes before changing them. Other values retain the 2.0.x freeze behavior: unmarked class instances and the plain objects they hold are still frozen. + +A [mark](/docs/advanced-guides/mark) controls drafting, does not exempt an object from freezing, and is not called again by freezing. Objects marked `mutable` are still frozen; turn off auto-freeze if later updates need to change them in place. + Objects that are already frozen are skipped together with the values they hold, so after the first update freezes the state, each later update freezes only the objects that it copied or added. A base state may be frozen already: Mutative copies frozen objects when a recipe changes them, as it copies any other object. Writing to a frozen object throws a `TypeError` in strict mode code, which includes ES modules and classes, and does nothing elsewhere. A frozen Map or Set throws in either case. diff --git a/website/content/docs/advanced-guides/auto-freeze.zh.mdx b/website/content/docs/advanced-guides/auto-freeze.zh.mdx index a8100ec5..0734318a 100644 --- a/website/content/docs/advanced-guides/auto-freeze.zh.mdx +++ b/website/content/docs/advanced-guides/auto-freeze.zh.mdx @@ -40,9 +40,13 @@ expect(() => { ## 冻结范围 [#what-is-frozen] - 下一个状态中沿可枚举键可达的所有对象:包括已修改对象的副本、更新函数赋入的值,以及与基础状态共享的对象。共享对象在基础状态中也会被冻结。如果更新函数没有修改任何内容,则返回被冻结的基础状态本身。 -- 类实例、日期和函数也像普通对象一样由 `Object.freeze()` 冻结。但 `Date` 仍可调用 `setFullYear()` 等修改方法,因为日期值并非对象属性。 +- 类实例、无原型对象、日期和正则表达式也由 `Object.freeze()` 冻结。开发构建还会冻结函数及其自有可枚举属性。`Date` 仍可调用 `setFullYear()` 等修改方法,因为日期值并非对象属性。 - Map 和 Set 的 `set()`、`add()`、`delete()`、`clear()` 方法会抛错;Map 用作键的对象也会被冻结。 +typed array、Node.js Buffer 和 DataView 及其内部值会被跳过,即使视图为空或被标记为 `immutable`。冻结非空 typed array 会抛错,任何视图的字节也都无法通过 `Object.freeze()` 变为只读。视图会与基础状态共享,修改字节前请先复制。其他值保留 2.0.x 的冻结行为:未标记的类实例及其内部普通对象仍会被冻结。 + +[标记](/zh/docs/advanced-guides/mark)只决定草稿行为,不会让对象免于冻结,也不会由冻结过程额外调用。标记为 `mutable` 的对象仍会被冻结;如果后续需要原地修改它,请关闭自动冻结。 + 已冻结的对象及其内部值会被跳过,因此首次更新冻结状态后,后续更新只需冻结新复制或新增的对象。基础状态也可以预先冻结:修改时,Mutative 像处理其他对象一样复制冻结对象。 在 JavaScript 严格模式代码(包括 ES 模块和类)中,写入冻结对象会抛出 `TypeError`,其他情况下则不生效。冻结的 Map 和 Set 在两种情况下都会抛错。 diff --git a/website/content/docs/advanced-guides/mark.mdx b/website/content/docs/advanced-guides/mark.mdx index dd8c4817..56d6337d 100644 --- a/website/content/docs/advanced-guides/mark.mdx +++ b/website/content/docs/advanced-guides/mark.mdx @@ -64,6 +64,7 @@ Use the same marks for every call on the same state: [`makeCreator({ mark })`](/ ## Patches, auto-freeze and strict mode +- Auto-freeze retains the 2.0.x behavior and also freezes objects marked `mutable` and the values they hold. A mark controls drafting, not exemption from freezing; turn off auto-freeze when later updates must change these values in place. Freezing does not call the marks again. - Values marked `immutable` work with patches and auto-freeze like plain objects, and so does a mark that makes every object immutable, as `() => 'immutable'` does. - A mark that returns a copy function cannot be combined with patches or auto-freeze, which development builds report with an error, and some patches might not apply to such values. - In [strict mode](/docs/advanced-guides/strict-mode), reading a value marked `mutable` from a draft throws outside [`unsafe()`](/docs/api-reference/unsafe), as reading any value that is not drafted does. diff --git a/website/content/docs/advanced-guides/mark.zh.mdx b/website/content/docs/advanced-guides/mark.zh.mdx index a3b66f68..fbd8cc25 100644 --- a/website/content/docs/advanced-guides/mark.zh.mdx +++ b/website/content/docs/advanced-guides/mark.zh.mdx @@ -64,6 +64,7 @@ expect(cache.hits).toBe(1); ## 补丁、自动冻结与严格模式 [#patches-auto-freeze-and-strict-mode] +- 自动冻结保留 2.0.x 的行为,也会冻结标为 `mutable` 的对象及其内部值。标记只控制草稿,不会让对象免于冻结;后续需要原地修改时请关闭自动冻结。冻结过程不会额外调用标记函数。 - 标为 `immutable` 的值像普通对象一样支持补丁和自动冻结。对所有对象都返回 `'immutable'` 的标记(如 `() => 'immutable'`)也同样支持。 - 返回拷贝函数的标记不能与补丁或自动冻结组合,开发构建会报错;部分补丁也可能无法应用到这类值。 - [严格模式](/zh/docs/advanced-guides/strict-mode)下,从草稿读取标为 `mutable` 的值必须位于 [`unsafe()`](/zh/docs/api-reference/unsafe) 内,否则会像读取其他不可创建草稿的对象一样抛错。 diff --git a/website/content/docs/advanced-guides/migration-v2.mdx b/website/content/docs/advanced-guides/migration-v2.mdx index fa126cee..f4445382 100644 --- a/website/content/docs/advanced-guides/migration-v2.mdx +++ b/website/content/docs/advanced-guides/migration-v2.mdx @@ -27,6 +27,10 @@ Mutative v2 keeps the v1 API. The changes below, made since v1.3.0, can affect e - `current()` of a changed array copies the current array instead of reading every element through the draft. Base elements that a native method moved and that hold drafts of an outer `create()` call are left as they are, as unmoved elements always were. - To search a large array without drafting each element it visits, search `current(draft.list)` and change the match through the draft; see [`current()`](/docs/api-reference/current). +## Auto-freeze + +Auto-freeze now leaves typed arrays, Node.js Buffers and DataViews unfrozen, including empty views. Earlier versions threw `TypeError: Cannot freeze array buffer views with elements` for a non-empty typed array. Their bytes and custom properties remain mutable, so copy the bytes before changing them. Other values retain the 2.0.x freeze behavior; see [What is frozen](/docs/advanced-guides/auto-freeze#what-is-frozen). + ## Returned values - With `enableAutoFreeze`, production builds no longer search frozen objects in a value returned from a recipe, the returned value included, or the values they hold, for drafts, and leave a draft there unresolved. Development builds still search them and throw when they find one, also in an unfrozen object that a frozen one holds, where v1 replaced it. Never put a draft in a frozen object or in a value it holds. Without auto-freeze, returned values are searched as in v1. diff --git a/website/content/docs/advanced-guides/migration-v2.zh.mdx b/website/content/docs/advanced-guides/migration-v2.zh.mdx index 99d24731..e31e5584 100644 --- a/website/content/docs/advanced-guides/migration-v2.zh.mdx +++ b/website/content/docs/advanced-guides/migration-v2.zh.mdx @@ -27,6 +27,10 @@ Mutative v2 保留 v1 API。以下列出自 v1.3.0 以来可能影响现有代 - 已修改数组的 `current()` 复制当前数组,不再逐元素通过草稿读取。原生方法移动的基础元素若含外层 `create()` 的草稿,会保持原样,与未移动元素原有行为一致。 - 大数组搜索可用 `current(draft.list)`,避免为每个访问元素创建草稿,再通过草稿修改匹配项,详见 [`current()`](/zh/docs/api-reference/current)。 +## 自动冻结 [#auto-freeze] + +自动冻结现在会跳过 typed array、Node.js Buffer 和 DataView,包括空视图。此前版本对非空 typed array 会抛出 `TypeError: Cannot freeze array buffer views with elements`。视图的字节和自定义属性仍可修改,修改字节前请先复制。其他值保留 2.0.x 的冻结行为,详见[冻结范围](/zh/docs/advanced-guides/auto-freeze#what-is-frozen)。 + ## 返回值 [#returned-values] - 开启 `enableAutoFreeze` 时,生产构建不再搜索返回值中的冻结对象(包括返回值本身)及其内部值,内部草稿会保持未解析。开发构建仍会搜索并在发现草稿时抛错,包括冻结对象内部尚未冻结的对象,v1 会替换其中草稿。不要将草稿放入冻结对象或其内部值。关闭自动冻结时,返回值搜索与 v1 一致。 diff --git a/website/content/docs/api-reference/create.mdx b/website/content/docs/api-reference/create.mdx index 7cf63a00..8d3112f1 100644 --- a/website/content/docs/api-reference/create.mdx +++ b/website/content/docs/api-reference/create.mdx @@ -73,6 +73,8 @@ TypeScript types the result from the type of `enablePatches` in the options pass Freeze the next state deeply, also the parts that it shares with the base state, and, in development builds, throw for an object that holds itself; see [Auto Freeze](/docs/advanced-guides/auto-freeze). +Typed arrays, Node.js Buffers and DataViews are left unfrozen, including empty views. Other values retain the 2.0.x freeze behavior, including class instances and their contents. + ### mark A mark decides how a value is drafted; see [Marking data structure](/docs/advanced-guides/mark). It receives each value that the recipe reads and `{ mutable: 'mutable', immutable: 'immutable' }`, and returns: diff --git a/website/content/docs/api-reference/create.zh.mdx b/website/content/docs/api-reference/create.zh.mdx index 62b606d1..819f3f23 100644 --- a/website/content/docs/api-reference/create.zh.mdx +++ b/website/content/docs/api-reference/create.zh.mdx @@ -73,6 +73,8 @@ TypeScript 根据传给 `create()` 或 `makeCreator()` 的 `enablePatches` 类 深度冻结下一个状态,包括与基础状态共享的部分。开发构建还会拒绝持有自身的对象,详见[自动冻结](/zh/docs/advanced-guides/auto-freeze)。 +typed array、Node.js Buffer 和 DataView 会保持未冻结,即使为空。其他值保留 2.0.x 的冻结行为,包括类实例及其内部值。 + ### mark [#mark] 标记决定如何为值创建草稿,详见[标记数据结构](/zh/docs/advanced-guides/mark)。它接收更新函数读取的每个值和 `{ mutable: 'mutable', immutable: 'immutable' }`,返回: diff --git a/website/content/docs/extra-topics/comparison-with-immer.mdx b/website/content/docs/extra-topics/comparison-with-immer.mdx index 12afff45..06958aec 100644 --- a/website/content/docs/extra-topics/comparison-with-immer.mdx +++ b/website/content/docs/extra-topics/comparison-with-immer.mdx @@ -44,7 +44,7 @@ Mutative and Immer work the same way: a recipe changes a draft, and the library ## Defaults and configuration -- **Auto-freeze.** Mutative leaves results unfrozen unless `enableAutoFreeze` is set, while Immer freezes them by default. With freezing on, both freeze the whole result deeply, unchanged parts included, and freeze Map and Set instances so that their mutators throw. Mutative also freezes the objects that a Map uses as keys, which Immer leaves unfrozen. +- **Auto-freeze.** Mutative leaves results unfrozen unless `enableAutoFreeze` is set, while Immer freezes them by default. Mutative retains its 2.0.x freezing of unmarked class instances and their contents; Immer skips values it does not draft. Both leave typed arrays, Node.js Buffers and DataViews unfrozen. Both guard frozen Map and Set mutators, while Mutative also freezes Map keys. See [Auto Freeze](/docs/advanced-guides/auto-freeze). - **Options per call.** Each `create()` and `apply()` call takes its own options, and `makeCreator()` sets defaults, where Immer's `setAutoFreeze()` and its plugins change the module for every caller. Maps, Sets and patches work without the `enableMapSet()` and `enablePatches()` calls that Immer requires and throws without. - **Marking.** A `mark` function decides how values are drafted: it can make class instances draftable without changing their class, where Immer requires an `[immerable]` property on it, keep values mutable so that the recipe changes them in place, or return a function that copies a value. Mutative copies a class instance that a mark makes draftable with all its own properties, non-enumerable ones included, as Immer does with `setUseStrictShallowCopy('class_only')`, but assigns those that are enumerable, writable and configurable, as Immer's default copy does, so an own property that shadows a setter of the class runs it; see [Copying marked instances](/docs/advanced-guides/mark#copying-marked-instances). Both copy only the enumerable properties of plain objects and read their getters as values. See [mark](/docs/advanced-guides/mark). - **Strict mode.** With `strict: true`, reading a value that the recipe could change without a draft, such as a class instance that is not marked, throws unless the read happens inside `unsafe()`. Immer has no such mode. See [strict mode](/docs/advanced-guides/strict-mode). diff --git a/website/content/docs/extra-topics/comparison-with-immer.zh.mdx b/website/content/docs/extra-topics/comparison-with-immer.zh.mdx index 8501bbff..8120aa39 100644 --- a/website/content/docs/extra-topics/comparison-with-immer.zh.mdx +++ b/website/content/docs/extra-topics/comparison-with-immer.zh.mdx @@ -44,7 +44,7 @@ Mutative 与 Immer 采用相同模型:更新函数修改草稿,库生成下 ## 默认值与配置 [#defaults-and-configuration] -- **自动冻结**:Mutative 默认不冻结结果,需开启 `enableAutoFreeze`;Immer 默认冻结。开启后,两者均深度冻结整个结果及未修改部分,并冻结 Map/Set 实例使修改方法抛错。Mutative 还冻结 Map 的对象键,Immer 不会。 +- **自动冻结。** Mutative 默认不冻结结果,需开启 `enableAutoFreeze`;Immer 默认冻结。Mutative 保留 2.0.x 对未标记类实例及其内部值的冻结行为,Immer 则跳过不创建草稿的值。两者都不冻结 typed array、Node.js Buffer 和 DataView,都会限制被冻结的 Map 和 Set 的修改方法;Mutative 还会冻结 Map 的键。详见[自动冻结](/zh/docs/advanced-guides/auto-freeze)。 - **每次调用独立选项**:`create()` 和 `apply()` 接收独立选项,`makeCreator()` 设置默认值;Immer 的 `setAutoFreeze()` 和插件影响模块的所有调用方。Mutative 内置 Map、Set 和补丁支持,无需 Immer 要求的 `enableMapSet()`、`enablePatches()`。 - **标记**:`mark` 决定如何创建草稿:无需修改类定义即可支持实例,而 Immer 要求 `[immerable]`;也可保持值可变以原地修改,或返回自定义复制函数。Mutative 对已标记实例复制全部自有属性,包括不可枚举属性,类似 Immer 的 `setUseStrictShallowCopy('class_only')`;但对可枚举、可写、可配置属性使用赋值,类似 Immer 默认复制。因此遮蔽类 setter 的自有属性会触发它,详见[复制已标记的实例](/zh/docs/advanced-guides/mark#copying-marked-instances)。两者对普通对象都只复制可枚举属性,并将 getter 读取为值。另见[标记](/zh/docs/advanced-guides/mark)。 - **严格模式**:`strict: true` 时,读取可能绕过草稿被修改的值(如未标记类实例)必须放在 `unsafe()` 内,否则抛错。Immer 没有对应模式,详见[严格模式](/zh/docs/advanced-guides/strict-mode)。