You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Synchronous clone = global.structuredClone(value, transfer = []) API #793
Reacted by Oleg Isonen, Arthur Grotzky, Max G J Panas, Jake Archibald, Matthew Phillips, Philip Walton, Haroen Viaene, Rasmus Hansen, Jarek Radosz, Agrumas and 127 more
I think there's a lot of demand for a structuredClone() function like this. Though it may not be the best practice, realistically it is very common to have a lot of application state in ad-hoc graphs of standard data structures. I've had to implement similar cloning functions to help support that on a few different projects, and I've seen bugs from people using JSON.parse(JSON.stringify(...)) instead without considering cyclic data structures, leading to unexpected crashes later.
A built-in feature or interface for deep cloning standard data structures is common in other dynamic languages, and is something I've seen many novices look for when starting to use JavaScript. It would be nice to have a standard that includes making this fully extensible, but as you discussed on the mailing list that is quite complicated and doesn't seem to be happening soon. Extensibility is somewhat orthogonal to exposing this existing functionality to users.
As an outsider this appears to be relatively low-hanging fruit that many users would benefit from.
Reacted by Dannii Willis, Omar Alshaker, Anthony D'Andrea, Twaha Rahman, Owen Campbell-Moore, Kris Dages, Brian M Hunt, Jinrui Cheng and Underscore
I think there is a use-case for wanting to deep-copy objects, and the structured clone algorithm comes very close to that — it would solve the vast majority of use-cases.
The hack with the History API can be slow as there’s some cross-process communication going on.
I also wrote an asynchronous version using MessageChannel that turned out to be faster than the History API or JSON.parse(), even for big objects:
But sometime a synchronous version is very desirable.
As an outsider this appears to be relatively low-hanging fruit that many users would benefit from.
I agree with this.
Reacted by Rafael Hengles, Dave Landis, Dennis Zoma, Ethan Resnick, atshaas, Ben Blank, Dennis Richter, daipeng7, The web walker, Timo Tijhof and 15 more
The main thing blocking this is getting interest from implementers (judging by that 2015 thread there is interest from Mozilla) and then finding someone who wants to write the specification and someone who wants to write the tests (can be the same someone).
Maybe I'm naïve, but shouldn't specification be rather trivial, considering that the structured clone algorithm is already specified? If that is the case, I'm happy to take this as my opportunity to write my first spec bits and tests :D (Provided we get the interest bit sorted, of course)
Reacted by Anne van Kesteren, Jason Miller, Shawn Biddle, Jeremy Banks, Rasmus Hansen, Wayne Patterson, Max G J Panas, Romain Bessuges-Meusy, Simon Jentsch, Tim van der Lippe and 20 more
I wonder if this structured clone is actually what the developer wants. For instance, structured clone does some replication of the object graph, but makes no attempt to replicate the original prototype chain, so if the author has Point objects and expects to get Point objects out, they will be disappointed. (There's not an obvious reasonable way to do this cross-realm, but perhaps that is what authors want within the realm.)
I guess it's at least as close a match as JSON.parse(JSON.stringify(o)), though.
@jeremyroman Not entirely sure it would be a full/strict clone if you still referenced the old Point constructor in the prototype chain so this would be kind of expected, right?
It depends what the application is trying to do. Naively, I wouldn't blame an author for thinking this is reasonable:
let p = new Point(3, 4);
let p2 = clone(p);
console.assert(p2 instanceof Point);
Structured cloning necessarily clones only the things that you can kinda reasonably do across realms. I'm not sure it's a general-purpose deep clone (though I admit I'm not familiar with the ones apparently present in other dynamic languages), though it's possible that it is suitable for some author use cases.
though it's possible that it is suitable for some author use cases
I’d argue it’s enough for the majority of cases, but we’d have to look into that. Types by the author have never been cloned (unless the author also wrote a custom cloning function), so I think we should expose structured clone first, before thinking about how to handle the prototype chain.
Maybe we want to have two different clone variants, one that just does structural cloning and one that also clones the prototype hierarchy properly as well. Call em structualClone() and cloneWithPrototypeHierarchy() or whatever. In any case the former is basically already done, as surma mentioned, so why not? Let's go already.
If what's wanted is a generic way to deeply clone ECMAScript objects, maybe that's something that belongs in the ECMAScript spec (or maybe just a third-party library) rather than the HTML spec.
On the other hand, if it's useful for authors to have semantics that match postMessage, IndexedDB, etc. (for which it's not really clear what dealing with the prototype chain would even mean), then perhaps HTML should expose the existing primitive as suggested.
Reacted by Ben Blank, Jeremy Banks, Dannii Willis, Steven and Twaha Rahman
This works best as a WHATWG proposal as the WHATWG is the body that specifies structured cloning.
The next steps necessary to have it implemented in browsers are for browsers to determine that it's a high priority on their product roadmap (compared to other things they could spend engineering effort on). That is usually helped by evidence such as web developers advocating for it or showing what they're using instead. However, I think we've already reached a pretty good amount of evidence that this would be useful, so I'm not sure how to make progress on increasing the priority in browser teams' backlogs :(.
Both of these tweets are about cloning JS objects, not structured cloning, and some of the discussions explicitly mention a "proper" way of cloning JS objects.
I'd be curious to know more concrete use cases, and whatever v0 API being proposed here would satisfy any of them.
Yes, I was looking at deep-cloning at the time. Standardizing/exposing structured clone seemed like a low risk and low friction first step. It behaves correct for the majority of use cases (as far as I can tell) and is already specified and implemented in most engines.
The use-cases are mostly related to architectures relying on immutable data structures and chaining-style APIs.
Reacted by Jeremy Banks, Artemii, stefnotch, josephrocca and Horace
The initialValue reference is copied to value, which unfortunately copies the Vue getter/setter functions that exist on initialValue.
This means if a person mutates the local state of value, Vue fires the hidden setter functions on the upstream reference and therefore breaks the component encapsulation. In this way, the data flow is not unidirectional, but it is expected behaviour simply because the reference is copied in a non-immutable fashion. Part of this is Vue's problem in my opinion. I think the framework itself should deep clone props as they enter into a component.
This example means you can pass a reference through 100 dimensions of child components and mutate the root component's state in a way that is extremely difficult to trace by visual code analysis. I suspect countless application developers will experience some form of this issue moving forward.
Currently, shallow cloning is not adequate as a solution because nested Objects do not have their child references broken. So in my opinion, the only viable solution is to use Lodash's cloneDeep function or equivalent.
My described issue would be solved using structuredClone like this:
I think browsers should natively support deep cloning ASAP, so that a third party cloning dependency can be avoided. This will save bandwidth for all parties by reducing bundle size in every library that packages some form of deep cloning in order to operate immutably.
Personally, I like the idea of following the implementation details from node.js because it will make it easier for both node.js and browsers to benefit from continued innovations from either node.js or browsers with respect to deep cloning and immutable paradigms.
Reacted by stefnotch, GrosSacASacs, Gene Armstrong, Cameron Sanchez, Will Stott, gotjoshua, Aaron Anderson, Horace, Julien Barbay, ShiJie and 1 more
Does anyone have any suggestions on how to advocate for something like this to the browser vendors?
What if one was to just implement it in Chromium or Firefox and try to submit it to the project?
Or maybe standing outside headquarters chanting with a protest sign? :)
Activity
banksJeremy commentedon Dec 19, 2016
I think there's a lot of demand for a
structuredClone()function like this. Though it may not be the best practice, realistically it is very common to have a lot of application state in ad-hoc graphs of standard data structures. I've had to implement similar cloning functions to help support that on a few different projects, and I've seen bugs from people usingJSON.parse(JSON.stringify(...))instead without considering cyclic data structures, leading to unexpected crashes later.A built-in feature or interface for deep cloning standard data structures is common in other dynamic languages, and is something I've seen many novices look for when starting to use JavaScript. It would be nice to have a standard that includes making this fully extensible, but as you discussed on the mailing list that is quite complicated and doesn't seem to be happening soon. Extensibility is somewhat orthogonal to exposing this existing functionality to users.
As an outsider this appears to be relatively low-hanging fruit that many users would benefit from.
annevk commentedon Jan 23, 2018
As pointed out in https://twitter.com/DasSurma/status/955484341358022657 by @surma you can already do this synchronously today by (ab)using the history API. Seems like another reason to expose this.
surma commentedon Jan 23, 2018
I think there is a use-case for wanting to deep-copy objects, and the structured clone algorithm comes very close to that — it would solve the vast majority of use-cases.
The hack with the History API can be slow as there’s some cross-process communication going on.
I also wrote an asynchronous version using
MessageChannelthat turned out to be faster than the History API orJSON.parse(), even for big objects:But sometime a synchronous version is very desirable.
I agree with this.
annevk commentedon Jan 23, 2018
The main thing blocking this is getting interest from implementers (judging by that 2015 thread there is interest from Mozilla) and then finding someone who wants to write the specification and someone who wants to write the tests (can be the same someone).
@ajklein @othermaciej @dstorey thoughts?
surma commentedon Jan 23, 2018
Maybe I'm naïve, but shouldn't specification be rather trivial, considering that the structured clone algorithm is already specified? If that is the case, I'm happy to take this as my opportunity to write my first spec bits and tests :D (Provided we get the interest bit sorted, of course)
jeremyroman commentedon Jan 23, 2018
I wonder if this structured clone is actually what the developer wants. For instance, structured clone does some replication of the object graph, but makes no attempt to replicate the original prototype chain, so if the author has Point objects and expects to get Point objects out, they will be disappointed. (There's not an obvious reasonable way to do this cross-realm, but perhaps that is what authors want within the realm.)
I guess it's at least as close a match as
JSON.parse(JSON.stringify(o)), though.RamIdeas commentedon Jan 23, 2018
@jeremyroman Not entirely sure it would be a full/strict clone if you still referenced the old Point constructor in the prototype chain so this would be kind of expected, right?
jeremyroman commentedon Jan 23, 2018
It depends what the application is trying to do. Naively, I wouldn't blame an author for thinking this is reasonable:
Structured cloning necessarily clones only the things that you can kinda reasonably do across realms. I'm not sure it's a general-purpose deep clone (though I admit I'm not familiar with the ones apparently present in other dynamic languages), though it's possible that it is suitable for some author use cases.
surma commentedon Jan 25, 2018
I’d argue it’s enough for the majority of cases, but we’d have to look into that. Types by the author have never been cloned (unless the author also wrote a custom cloning function), so I think we should expose structured clone first, before thinking about how to handle the prototype chain.
othermaciej commentedon Jan 25, 2018
Tagging @cdumez and @rniwa to give WebKit thoughts on this.
samal-rasmussen commentedon Jan 25, 2018
Maybe we want to have two different clone variants, one that just does structural cloning and one that also clones the prototype hierarchy properly as well. Call em structualClone() and cloneWithPrototypeHierarchy() or whatever. In any case the former is basically already done, as surma mentioned, so why not? Let's go already.
jeremyroman commentedon Jan 25, 2018
If what's wanted is a generic way to deeply clone ECMAScript objects, maybe that's something that belongs in the ECMAScript spec (or maybe just a third-party library) rather than the HTML spec.
On the other hand, if it's useful for authors to have semantics that match postMessage, IndexedDB, etc. (for which it's not really clear what dealing with the prototype chain would even mean), then perhaps HTML should expose the existing primitive as suggested.
34 remaining items
GrosSacASac commentedon Aug 20, 2019
I found a tc39 proposal in the stage 0 list. It looks like it is not active anymore, could someone present it ?
Should it be a tc39 proposal or a whatwg one ?
What are the next steps necessary to have it implemented in browsers ?
domenic commentedon Aug 20, 2019
This works best as a WHATWG proposal as the WHATWG is the body that specifies structured cloning.
The next steps necessary to have it implemented in browsers are for browsers to determine that it's a high priority on their product roadmap (compared to other things they could spend engineering effort on). That is usually helped by evidence such as web developers advocating for it or showing what they're using instead. However, I think we've already reached a pretty good amount of evidence that this would be useful, so I'm not sure how to make progress on increasing the priority in browser teams' backlogs :(.
rniwa commentedon Aug 20, 2019
It looks like two use cases being discussed are:
Both of these tweets are about cloning JS objects, not structured cloning, and some of the discussions explicitly mention a "proper" way of cloning JS objects.
I'd be curious to know more concrete use cases, and whatever v0 API being proposed here would satisfy any of them.
surma commentedon Aug 20, 2019
Yes, I was looking at deep-cloning at the time. Standardizing/exposing structured clone seemed like a low risk and low friction first step. It behaves correct for the majority of use cases (as far as I can tell) and is already specified and implemented in most engines.
The use-cases are mostly related to architectures relying on immutable data structures and chaining-style APIs.
agm1984 commentedon Sep 14, 2019
I am encountering an issue currently in Vue JS whereby I pass an Object prop from a parent to child component like this:
Also I apologize for showing framework code, but my intent is to help establish context for a need.
The
initialValuereference is copied tovalue, which unfortunately copies the Vue getter/setter functions that exist oninitialValue.This means if a person mutates the local state of
value, Vue fires the hidden setter functions on the upstream reference and therefore breaks the component encapsulation. In this way, the data flow is not unidirectional, but it is expected behaviour simply because the reference is copied in a non-immutable fashion. Part of this is Vue's problem in my opinion. I think the framework itself should deep clone props as they enter into a component.This example means you can pass a reference through 100 dimensions of child components and mutate the root component's state in a way that is extremely difficult to trace by visual code analysis. I suspect countless application developers will experience some form of this issue moving forward.
Currently, shallow cloning is not adequate as a solution because nested Objects do not have their child references broken. So in my opinion, the only viable solution is to use Lodash's
cloneDeepfunction or equivalent.My described issue would be solved using structuredClone like this:
I think browsers should natively support deep cloning ASAP, so that a third party cloning dependency can be avoided. This will save bandwidth for all parties by reducing bundle size in every library that packages some form of deep cloning in order to operate immutably.
Personally, I like the idea of following the implementation details from node.js because it will make it easier for both node.js and browsers to benefit from continued innovations from either node.js or browsers with respect to deep cloning and immutable paradigms.
krisdages commentedon Dec 9, 2020
Does anyone have any suggestions on how to advocate for something like this to the browser vendors?
What if one was to just implement it in Chromium or Firefox and try to submit it to the project?
Or maybe standing outside headquarters chanting with a protest sign? :)
jeremyroman commentedon Dec 9, 2020
You'd have to follow their respective launch processes to submit it. For Chromium, that's this process.
Define self.structuredClone()
Define self.structuredClone()
Define self.structuredClone()
Define self.structuredClone()