From d2ad9b4fb6a6c4d54f14e19e0c74f1285ee5e402 Mon Sep 17 00:00:00 2001 From: Jason Zhang Date: Fri, 4 Oct 2024 16:39:37 +0930 Subject: [PATCH] worker: add `markAsUncloneable` api External modules need a way to decorate their objects so that node can recognize it as a host object for serialization process. Exposing a way for turning off instead of turning on is much safer. PR-URL: https://github.com/nodejs/node/pull/55234 Refs: https://github.com/nodejs/node/pull/55178 Reviewed-By: Chengzhong Wu Reviewed-By: Daeyeon Jeong Reviewed-By: Matthew Aitken --- doc/api/worker_threads.md | 32 +++++++++ lib/internal/worker/io.js | 16 +++++ lib/worker_threads.js | 2 + ...test-worker-message-mark-as-uncloneable.js | 70 +++++++++++++++++++ 4 files changed, 120 insertions(+) create mode 100644 test/parallel/test-worker-message-mark-as-uncloneable.js diff --git a/doc/api/worker_threads.md b/doc/api/worker_threads.md index b718a90f621..ddf7a2cd545 100644 --- a/doc/api/worker_threads.md +++ b/doc/api/worker_threads.md @@ -194,6 +194,38 @@ isMarkedAsUntransferable(pooledBuffer); // Returns true. There is no equivalent to this API in browsers. +## `worker.markAsUncloneable(object)` + + + +* `object` {any} Any arbitrary JavaScript value. + +Mark an object as not cloneable. If `object` is used as [`message`](#event-message) in +a [`port.postMessage()`][] call, an error is thrown. This is a no-op if `object` is a +primitive value. + +This has no effect on `ArrayBuffer`, or any `Buffer` like objects. + +This operation cannot be undone. + +```js +const { markAsUncloneable } = require('node:worker_threads'); + +const anyObject = { foo: 'bar' }; +markAsUncloneable(anyObject); +const { port1 } = new MessageChannel(); +try { + // This will throw an error, because anyObject is not cloneable. + port1.postMessage(anyObject) +} catch (error) { + // error.name === 'DataCloneError' +} +``` + +There is no equivalent to this API in browsers. + ## `worker.moveMessagePortToContext(port, contextifiedSandbox)`