-
Notifications
You must be signed in to change notification settings - Fork 81
Add JSON-Safe serialization modes #1308
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
minggangw
merged 2 commits into
RobotWebTools:develop
from
mahmoud-ghalayini:feat-add-json-safe-serialization-modes-1307
Oct 27, 2025
Merged
Changes from 1 commit
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
41 changes: 41 additions & 0 deletions
41
example/topics/subscriber/subscription-json-utilities-example.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,41 @@ | ||
| // Copyright (c) 2024 rclnodejs contributors. All rights reserved. | ||
| // | ||
| // Licensed under the Apache License, Version 2.0 (the "License"); | ||
| // you may not use this file except in compliance with the License. | ||
| // You may obtain a copy of the License at | ||
| // | ||
| // http://www.apache.org/licenses/LICENSE-2.0 | ||
| // | ||
| // Unless required by applicable law or agreed to in writing, software | ||
| // distributed under the License is distributed on an "AS IS" BASIS, | ||
| // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| // See the License for the specific language governing permissions and | ||
| // limitations under the License. | ||
|
|
||
| 'use strict'; | ||
|
|
||
| const rclnodejs = require('../../../index.js'); | ||
|
|
||
| /** | ||
| * This example demonstrates the JSON utility functions for manual message conversion. | ||
| * These utilities are useful when you need to convert messages on-demand | ||
| * rather than using the serializationMode subscription option. | ||
| */ | ||
| async function main() { | ||
| await rclnodejs.init(); | ||
| const node = new rclnodejs.Node('json_utilities_example_node'); | ||
|
|
||
| node.createSubscription('sensor_msgs/msg/LaserScan', '/laser_scan', (msg) => { | ||
| // Convert using utility functions | ||
| const jsonSafe = rclnodejs.toJSONSafe(msg); | ||
| const jsonString = rclnodejs.toJSONString(msg); | ||
|
|
||
| console.log( | ||
| `Original: ${msg.ranges ? msg.ranges.constructor.name : 'undefined'}, JSON-safe: ${jsonSafe.ranges ? jsonSafe.ranges.constructor.name : 'undefined'}, JSON length: ${jsonString.length}` | ||
| ); | ||
| }); | ||
|
|
||
| node.spin(); | ||
| } | ||
|
|
||
| main().catch(console.error); | ||
78 changes: 78 additions & 0 deletions
78
example/topics/subscriber/subscription-serialization-modes-example.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,78 @@ | ||
| // Copyright (c) 2024 rclnodejs contributors. All rights reserved. | ||
| // | ||
| // Licensed under the Apache License, Version 2.0 (the "License"); | ||
| // you may not use this file except in compliance with the License. | ||
| // You may obtain a copy of the License at | ||
| // | ||
| // http://www.apache.org/licenses/LICENSE-2.0 | ||
| // | ||
| // Unless required by applicable law or agreed to in writing, software | ||
| // distributed under the License is distributed on an "AS IS" BASIS, | ||
| // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| // See the License for the specific language governing permissions and | ||
| // limitations under the License. | ||
|
|
||
| 'use strict'; | ||
|
|
||
| const rclnodejs = require('../../../index.js'); | ||
|
|
||
| /** | ||
| * This example demonstrates the use of serialization modes for subscriptions. | ||
| * Serialization modes allow you to control how TypedArrays are handled in messages: | ||
| * - 'typed' (default): Keep TypedArrays for performance | ||
| * - 'plain': Convert TypedArrays to regular arrays | ||
| * - 'json': Fully JSON-safe (converts TypedArrays, BigInt, Infinity, etc.) | ||
| */ | ||
| async function main() { | ||
| await rclnodejs.init(); | ||
| const node = new rclnodejs.Node('serialization_modes_example_node'); | ||
|
|
||
| // Default mode: 'typed' - keeps TypedArrays | ||
| node.createSubscription( | ||
| 'sensor_msgs/msg/LaserScan', | ||
| '/laser_scan', | ||
| { serializationMode: 'typed' }, | ||
| (msg) => { | ||
| console.log( | ||
| `[TYPED] ranges: ${msg.ranges ? msg.ranges.constructor.name : 'undefined'}` | ||
| ); | ||
| } | ||
| ); | ||
|
|
||
| // Plain mode: converts TypedArrays to regular arrays | ||
| node.createSubscription( | ||
| 'sensor_msgs/msg/LaserScan', | ||
| '/laser_scan', | ||
| { serializationMode: 'plain' }, | ||
| (msg) => { | ||
| console.log( | ||
| `[PLAIN] ranges: ${msg.ranges ? msg.ranges.constructor.name : 'undefined'}` | ||
| ); | ||
| } | ||
| ); | ||
|
|
||
| // JSON mode: fully JSON-safe | ||
| node.createSubscription( | ||
| 'sensor_msgs/msg/LaserScan', | ||
| '/laser_scan', | ||
| { serializationMode: 'json' }, | ||
| (msg) => { | ||
| console.log( | ||
| `[JSON] ranges: ${msg.ranges ? msg.ranges.constructor.name : 'undefined'}, JSON-safe: ${canStringifyJSON(msg)}` | ||
| ); | ||
| } | ||
| ); | ||
|
|
||
| node.spin(); | ||
| } | ||
|
|
||
| function canStringifyJSON(obj) { | ||
| try { | ||
| JSON.stringify(obj); | ||
| return true; | ||
| } catch { | ||
| return false; | ||
| } | ||
| } | ||
|
|
||
| main().catch(console.error); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,171 @@ | ||
| // Copyright (c) 2024 rclnodejs contributors. All rights reserved. | ||
| // | ||
| // Licensed under the Apache License, Version 2.0 (the "License"); | ||
| // you may not use this file except in compliance with the License. | ||
| // You may obtain a copy of the License at | ||
| // | ||
| // http://www.apache.org/licenses/LICENSE-2.0 | ||
| // | ||
| // Unless required by applicable law or agreed to in writing, software | ||
| // distributed under the License is distributed on an "AS IS" BASIS, | ||
| // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| // See the License for the specific language governing permissions and | ||
| // limitations under the License. | ||
|
|
||
| 'use strict'; | ||
|
|
||
| /** | ||
| * Check if a value is a TypedArray | ||
| * @param {*} value - The value to check | ||
| * @returns {boolean} True if the value is a TypedArray | ||
| */ | ||
| function isTypedArray(value) { | ||
| return ArrayBuffer.isView(value) && !(value instanceof DataView); | ||
| } | ||
|
|
||
| /** | ||
| * Check if a value needs JSON conversion (BigInt, functions, etc.) | ||
| * @param {*} value - The value to check | ||
| * @returns {boolean} True if the value needs special JSON handling | ||
| */ | ||
| function needsJSONConversion(value) { | ||
| return ( | ||
| typeof value === 'bigint' || | ||
| typeof value === 'function' || | ||
| typeof value === 'undefined' || | ||
| value === Infinity || | ||
| value === -Infinity || | ||
| (typeof value === 'number' && isNaN(value)) | ||
| ); | ||
| } | ||
|
|
||
| /** | ||
| * Convert a message to plain arrays (TypedArray -> regular Array) | ||
| * @param {*} obj - The object to convert | ||
| * @returns {*} The converted object with plain arrays | ||
| */ | ||
| function toPlainArrays(obj) { | ||
| if (obj === null || obj === undefined) { | ||
| return obj; | ||
| } | ||
|
|
||
| if (isTypedArray(obj)) { | ||
| return Array.from(obj); | ||
| } | ||
|
|
||
| if (Array.isArray(obj)) { | ||
| return obj.map((item) => toPlainArrays(item)); | ||
| } | ||
|
|
||
| if (typeof obj === 'object' && obj !== null) { | ||
| const result = {}; | ||
| for (const key in obj) { | ||
| if (Object.prototype.hasOwnProperty.call(obj, key)) { | ||
| result[key] = toPlainArrays(obj[key]); | ||
| } | ||
| } | ||
| return result; | ||
| } | ||
|
|
||
| return obj; | ||
| } | ||
|
|
||
| /** | ||
| * Convert a message to be fully JSON-safe | ||
| * @param {*} obj - The object to convert | ||
| * @returns {*} The JSON-safe converted object | ||
| */ | ||
| function toJSONSafe(obj) { | ||
| if (obj === null || obj === undefined) { | ||
| return obj; | ||
| } | ||
|
|
||
| if (isTypedArray(obj)) { | ||
| return Array.from(obj).map((item) => toJSONSafe(item)); | ||
| } | ||
|
|
||
| if (needsJSONConversion(obj)) { | ||
| if (typeof obj === 'bigint') { | ||
| // Convert BigInt to string with 'n' suffix to indicate it was a BigInt | ||
| return obj.toString() + 'n'; | ||
| } | ||
| if (obj === Infinity) return 'Infinity'; | ||
| if (obj === -Infinity) return '-Infinity'; | ||
| if (typeof obj === 'number' && isNaN(obj)) return 'NaN'; | ||
| if (typeof obj === 'undefined') return null; | ||
| if (typeof obj === 'function') return '[Function]'; | ||
| } | ||
|
|
||
| if (Array.isArray(obj)) { | ||
| return obj.map((item) => toJSONSafe(item)); | ||
| } | ||
|
|
||
| if (typeof obj === 'object' && obj !== null) { | ||
| const result = {}; | ||
| for (const key in obj) { | ||
| if (Object.prototype.hasOwnProperty.call(obj, key)) { | ||
| result[key] = toJSONSafe(obj[key]); | ||
| } | ||
| } | ||
| return result; | ||
| } | ||
|
|
||
| return obj; | ||
| } | ||
|
|
||
| /** | ||
| * Convert a message to a JSON string | ||
| * @param {*} obj - The object to convert | ||
| * @param {number} [space] - Space parameter for JSON.stringify formatting | ||
| * @returns {string} The JSON string representation | ||
| */ | ||
| function toJSONString(obj, space) { | ||
| const jsonSafeObj = toJSONSafe(obj); | ||
| return JSON.stringify(jsonSafeObj, null, space); | ||
| } | ||
|
|
||
| /** | ||
| * Apply serialization mode conversion to a message object | ||
| * @param {*} message - The message object to convert | ||
| * @param {string} serializationMode - The serialization mode ('typed', 'plain', 'json') | ||
| * @returns {*} The converted message | ||
| */ | ||
| function applySerializationMode(message, serializationMode) { | ||
| switch (serializationMode) { | ||
| case 'typed': | ||
| // No conversion needed - keep TypedArrays | ||
| return message; | ||
|
|
||
| case 'plain': | ||
| // Convert TypedArrays to regular arrays | ||
| return toPlainArrays(message); | ||
|
|
||
| case 'json': | ||
| // Convert to fully JSON-safe format | ||
| return toJSONSafe(message); | ||
|
|
||
| default: | ||
| throw new TypeError( | ||
| `Invalid serializationMode: ${serializationMode}. Valid modes are: 'typed', 'plain', 'json'` | ||
| ); | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Validate serialization mode | ||
| * @param {string} mode - The serialization mode to validate | ||
| * @returns {boolean} True if valid | ||
| */ | ||
| function isValidSerializationMode(mode) { | ||
| return ['typed', 'plain', 'json'].includes(mode); | ||
| } | ||
|
|
||
| module.exports = { | ||
| isTypedArray, | ||
| needsJSONConversion, | ||
| toPlainArrays, | ||
| toJSONSafe, | ||
| toJSONString, | ||
| applySerializationMode, | ||
| isValidSerializationMode, | ||
| }; |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I prefer unifying the wording here, you can either:
It's up to you. nit: it's year of 2025 already :)