Shrinking an array with `length =` and growing it back loses the patches for the truncated indices
Los mantenedores suelen responder en 4 días
Evaluación
- Dificultad
- 2/5
- Tiempo estimado
- 1-3 horas
- Aptitud para principiantes
- 75/100
- Tipo de issue
- Error
- Claridad
- Bien especificado
- Estado de actividad
- Activo
- Stack tecnológico
- javascript
- Área
- backend
Línea de trabajo
Empieza en src/plugins/patches.ts, especialmente en generateArrayPatches_, y sigue cómo el hecho de reducir un array borrador cambia copy_ y assigned_. Añade la prueba de regresión proporcionada para reducir y volver a aumentar length, y ejecuta las pruebas relacionadas con los patches. El trabajo estará terminado cuando los patches de avance reproduzcan el resultado de la receta y los patches inversos restauren la base.
Escrito por el modelo de indexación a partir del texto del issue.
Descripción
🐛 Bug Report
With enablePatches(), if a recipe shrinks a draft array by assigning .length and then grows it back to at least its original length, no replace patch (and no inverse patch) is produced for the truncated indices. Replaying the patches on the base gives a different state than the recipe, and the inverse patches do not restore the base. The same recipe written with splice(0) produces correct patches.
Link to repro
Not applicable: no CodeSandbox account; the script below and the unit test at the end reproduce it.
To Reproduce
npm i [email protected], save as t.mjs, run node t.mjs:
import { produceWithPatches, applyPatches, enablePatches } from "immer";
enablePatches();
const base = [1];
const [result, patches, inverse] = produceWithPatches(base, d => {
d.length = 0; // truncate index 0
d[1] = 2; // grow again
});
console.log(result);
console.log(patches);
console.log(inverse);
console.log(applyPatches(base, patches));
console.log(applyPatches(result, inverse));
const [r2, p2, i2] = produceWithPatches([1, 2], d => { d.length = 0; d.length = 2; });
console.log(r2, p2, i2);
Observed behavior
[ <1 empty item>, 2 ]
[ { op: 'add', path: [ 1 ], value: 2 } ]
[ { op: 'remove', path: [ 1 ] } ]
[ 1, 2 ]
[ <1 empty item> ]
[ <2 empty items> ] [] []
applyPatches(base, patches) keeps the stale 1 at index 0, and applyPatches(result, inverse) does not bring it back. The second recipe changes both elements but produces no patches at all.
Expected behavior
The same patches as for d.splice(0); d[1] = 2, which immer already gets right:
[
{ op: 'replace', path: [ 0 ], value: undefined },
{ op: 'add', path: [ 1 ], value: 2 }
] [
{ op: 'replace', path: [ 0 ], value: 1 },
{ op: 'remove', path: [ 1 ] }
]
so that applyPatches(base, patches) gives [ undefined, 2 ] and applyPatches(result, inverse) gives [ 1 ].
generateArrayPatches_ in src/plugins/patches.ts only emits a replace for an index below base.length when assigned_.get(i) is set (or allIndicesReassigned_). Assigning a smaller length truncates copy_ without marking the dropped indices as assigned, so they are skipped once the array is long again.
Unit test:
test("length shrink then grow produces replace patches", () => {
const base = [1]
const [result, patches, inverse] = produceWithPatches(base, d => {
d.length = 0
d[1] = 2
})
expect(applyPatches(base, patches)).toEqual(result)
expect(applyPatches(result, inverse)).toEqual(base)
})
Environment
We only accept bug reports against the latest Immer version.
- Immer version: 11.2.9 (also main 75a290e, built from source), Node.js v26.13.0
- I filed this report against the latest version of Immer
- Occurs with
setUseProxies(true) - Occurs with
setUseProxies(false)(ES5 only)
Credit: https://ucsbplse.github.io/
- Lenguaje dominante
- JavaScript
- Estrellas
- 29k
- Forks
- 905
- Merge medio
- 3 d 16 h
- PR fusionados (30 d)
- 22
Preparar el entorno
Este proyecto no incluye contenedor de desarrollo, Dockerfile ni guía de contribución, así que la configuración corre por tu cuenta: empieza por su README y consulta nuestra guía para la primera contribución para los pasos generales.
Primeros pasos
- Lee el issue completo y luego la guía de contribución del proyecto.
- Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
- Haz un fork del repositorio y trabaja en una rama.
- Abre un pull request que haga referencia al número del issue.
Más de immerjs/immer
-
Dificultad 3/5 1-2 días Aptitud para principiantes 35/100
Los mantenedores suelen responder en 4 días
-
Docs: Chinese (zh-CN) website translation is outdated vs English docsQuizá libre de nuevo @lijiayou0728 la tomó hace 91 días y no hay ningún pull request abierto. Abierto
Dificultad 4/5 3-5 días Aptitud para principiantes 55/100
immerjs/immer#1242 · 5 comentarios ·
Los mantenedores suelen responder en 4 días
-
Branding Drafts on Type levelAbiertoquestion
Dificultad 5/5 Más de una semana Aptitud para principiantes 35/100
Los mantenedores suelen responder en 4 días
-
Dificultad 5/5 Más de una semana Aptitud para principiantes 35/100
immerjs/immer#1217 · 1 comentario ·
Los mantenedores suelen responder en 4 días
-
[Feature Request] Support for "Splice" patches in arrays for CRDT/Y.js integration (and others)Abiertoproposal
Dificultad 5/5 Más de una semana Aptitud para principiantes 25/100
immerjs/immer#1202 · 2 comentarios · 1 reacción ·
Los mantenedores suelen responder en 4 días
Todos los issues de immerjs/immer
Issues similares
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 76/100
Automattic/node-canvas#2633 ·
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 78/100
capricorn86/happy-dom#2594 ·
Los mantenedores suelen responder en 1 día
-
Decoding tag 1 (epoch date) with an 8-byte integer throws "Cannot mix BigInt and other types"Abierto
Dificultad 2/5 1-3 horas Aptitud para principiantes 78/100
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 79/100
microsoft/monaco-editor#5575 ·
Los mantenedores suelen responder en 1 día
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 84/100
Los mantenedores suelen responder en 1 día