@wandelbots/nova-js 4.2.0 → 4.3.0-nova-api-dev.26-6-0-dev-137

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@wandelbots/nova-js",
3
3
  "type": "module",
4
- "version": "4.2.0",
4
+ "version": "4.3.0-nova-api-dev.26-6-0-dev-137",
5
5
  "description": "Official JS client for the Wandelbots API",
6
6
  "sideEffects": false,
7
7
  "packageManager": "pnpm@11.9.0+sha512.bd682d5d03fe525ef7c9fd6780c6884d1e756ac4c9c9fe00c538782824310dcf90e3ddc4f53835f06dfaebd5085e41855e0bcbb3b60de2ac5bbab89e5036f03b",
@@ -20,6 +20,10 @@
20
20
  "./experimental/nats": {
21
21
  "types": "./dist/experimental/nats/index.d.mts",
22
22
  "default": "./dist/experimental/nats/index.mjs"
23
+ },
24
+ "./experimental/math": {
25
+ "types": "./dist/experimental/math/index.d.mts",
26
+ "default": "./dist/experimental/math/index.mjs"
23
27
  }
24
28
  },
25
29
  "main": "./dist/index.mjs",
@@ -57,7 +61,7 @@
57
61
  "@biomejs/biome": "^2.5.6",
58
62
  "@types/node": "^25.9.5",
59
63
  "@types/ws": "^8.18.1",
60
- "@wandelbots/nova-api": "26.5.2",
64
+ "@wandelbots/nova-api": "26.6.0-dev.137",
61
65
  "concurrently": "^10.0.4",
62
66
  "conventional-changelog-conventionalcommits": "^9.3.1",
63
67
  "jsdom": "^29.1.1",
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Experimental pose math helpers (`Pose`, `Quaternion`, `withMath`) for
3
+ * working with position + axis-angle orientation values from the NOVA API.
4
+ *
5
+ * This API is experimental and may change without a major version bump.
6
+ */
7
+ export type { Pose as PoseData } from "@wandelbots/nova-api/v2"
8
+ export { Pose } from "../../lib/experimental/math/Pose.ts"
9
+ export { Quaternion } from "../../lib/experimental/math/Quaternion.ts"
10
+ export type { QuaternionData } from "../../lib/experimental/math/Quaternion.ts"
11
+ export {
12
+ augmentPoses,
13
+ withMath,
14
+ } from "../../lib/experimental/math/withMath.ts"
15
+ export type {
16
+ DeepPoseAugmented,
17
+ NovaWithMath,
18
+ } from "../../lib/experimental/math/withMath.ts"
@@ -0,0 +1,162 @@
1
+ import type { Pose as PoseData } from "@wandelbots/nova-api/v2"
2
+ import { Quaternion } from "./Quaternion.ts"
3
+
4
+ const ZERO_VECTOR = [0, 0, 0]
5
+
6
+ // Matches wb-robotix's Constants.h TOLERANCE_MILLI, the default isApprox tolerance.
7
+ const TOLERANCE_MILLI = 1e-3
8
+
9
+ function addVectors(a: number[], b: number[]): number[] {
10
+ return [
11
+ (a[0] ?? 0) + (b[0] ?? 0),
12
+ (a[1] ?? 0) + (b[1] ?? 0),
13
+ (a[2] ?? 0) + (b[2] ?? 0),
14
+ ]
15
+ }
16
+
17
+ function negateVector(a: number[]): number[] {
18
+ return [-(a[0] ?? 0), -(a[1] ?? 0), -(a[2] ?? 0)]
19
+ }
20
+
21
+ function isFiniteVector3(v: number[]): boolean {
22
+ return v.length === 3 && v.every((n) => Number.isFinite(n))
23
+ }
24
+
25
+ /**
26
+ * A `Pose` (position + axis-angle orientation) with methods for composing
27
+ * and inverting transforms. Instances are plain-data compatible with the
28
+ * wire-format `PoseData` type (own `position`/`orientation` properties only,
29
+ * no enumerable methods), so they can be passed directly back into API calls
30
+ * that expect a pose.
31
+ */
32
+ export class Pose implements PoseData {
33
+ readonly position: number[]
34
+ readonly orientation: number[]
35
+
36
+ constructor(
37
+ position: number[] = ZERO_VECTOR,
38
+ orientation: number[] = ZERO_VECTOR,
39
+ ) {
40
+ if (!isFiniteVector3(position)) {
41
+ throw new Error(
42
+ `Pose constructor: position must be an array of 3 finite numbers, got ${JSON.stringify(position)}`,
43
+ )
44
+ }
45
+ if (!isFiniteVector3(orientation)) {
46
+ throw new Error(
47
+ `Pose constructor: orientation must be an array of 3 finite numbers, got ${JSON.stringify(orientation)}`,
48
+ )
49
+ }
50
+ // Copy defensively so mutating the caller's arrays afterward can't
51
+ // change this (supposedly immutable) instance's state.
52
+ this.position = [...position]
53
+ this.orientation = [...orientation]
54
+ }
55
+
56
+ static from(pose: PoseData): Pose {
57
+ if (pose instanceof Pose) {
58
+ return pose
59
+ }
60
+ return new Pose(
61
+ pose.position ?? ZERO_VECTOR,
62
+ pose.orientation ?? ZERO_VECTOR,
63
+ )
64
+ }
65
+
66
+ static identity(): Pose {
67
+ return new Pose()
68
+ }
69
+
70
+ /**
71
+ * Compose this pose with `other`, treating `other` as being expressed in
72
+ * this pose's coordinate frame. Equivalent to the homogeneous transform
73
+ * product `this * other`: applying the result to a point is the same as
74
+ * applying `other` first, then `this`.
75
+ */
76
+ multiply(other: PoseData): Pose {
77
+ const q1 = Quaternion.fromRotationVector(this.orientation)
78
+ const q2 = Quaternion.fromRotationVector(other.orientation ?? ZERO_VECTOR)
79
+
80
+ const position = addVectors(
81
+ this.position,
82
+ q1.rotateVector(other.position ?? ZERO_VECTOR),
83
+ )
84
+ const orientation = q1.multiply(q2).toRotationVector()
85
+
86
+ return new Pose(position, orientation)
87
+ }
88
+
89
+ /** The inverse transform, such that `pose.multiply(pose.inverse())` is the identity pose. */
90
+ inverse(): Pose {
91
+ const qInverse = Quaternion.fromRotationVector(this.orientation).inverse()
92
+
93
+ const position = qInverse.rotateVector(negateVector(this.position))
94
+ // Negating an axis-angle vector gives the inverse rotation directly.
95
+ const orientation = negateVector(this.orientation)
96
+
97
+ return new Pose(position, orientation)
98
+ }
99
+
100
+ /** Apply this pose's transform to a point, returning the transformed point. */
101
+ transformPoint(point: number[]): number[] {
102
+ const q = Quaternion.fromRotationVector(this.orientation)
103
+ return addVectors(this.position, q.rotateVector(point))
104
+ }
105
+
106
+ /**
107
+ * Compare to another pose using separate position/orientation tolerances,
108
+ * matching wb-robotix's `Pose::isApprox()`: Euclidean distance for
109
+ * position, and quaternion angular distance for orientation - not a naive
110
+ * per-component diff, since two rotation vectors can represent nearly
111
+ * identical rotations while differing componentwise near a
112
+ * canonicalization boundary (e.g. close to the +/-pi wraparound).
113
+ */
114
+ isApprox(
115
+ other: PoseData,
116
+ deltaPosition = TOLERANCE_MILLI,
117
+ deltaOrientation = TOLERANCE_MILLI,
118
+ ): boolean {
119
+ const otherPosition = other.position ?? ZERO_VECTOR
120
+ const otherOrientation = other.orientation ?? ZERO_VECTOR
121
+
122
+ const positionDistance = Math.sqrt(
123
+ this.position.reduce(
124
+ (sum, v, i) => sum + (v - (otherPosition[i] ?? 0)) ** 2,
125
+ 0,
126
+ ),
127
+ )
128
+ const orientationDistance = Quaternion.fromRotationVector(
129
+ this.orientation,
130
+ ).angularDistance(Quaternion.fromRotationVector(otherOrientation))
131
+
132
+ return (
133
+ positionDistance <= deltaPosition &&
134
+ orientationDistance <= deltaOrientation
135
+ )
136
+ }
137
+
138
+ /**
139
+ * Position + orientation as a 6-element [x, y, z, roll, pitch, yaw] vector
140
+ * (Euler angles in rad, XYZ Tait-Bryan / Rx*Ry*Rz convention), matching
141
+ * wb-robotix's `Pose::toCartesian()`.
142
+ */
143
+ toCartesian(): number[] {
144
+ const { w, x, y, z } = Quaternion.fromRotationVector(this.orientation)
145
+
146
+ const roll = Math.atan2(2 * (w * x - y * z), 1 - 2 * (x * x + y * y))
147
+ const pitch = Math.asin(Math.min(1, Math.max(-1, 2 * (x * z + w * y))))
148
+ const yaw = Math.atan2(2 * (w * z - x * y), 1 - 2 * (y * y + z * z))
149
+
150
+ return [...this.position, roll, pitch, yaw]
151
+ }
152
+
153
+ /** Human-readable `[x, y, z][rx, ry, rz]` representation, matching wb-robotix's `Pose::string()`. */
154
+ toString(precision = 6): string {
155
+ const fmt = (v: number) => Number(v.toPrecision(precision))
156
+ return `[${this.position.map(fmt).join(", ")}][${this.orientation.map(fmt).join(", ")}]`
157
+ }
158
+
159
+ toJSON(): PoseData {
160
+ return { position: this.position, orientation: this.orientation }
161
+ }
162
+ }
@@ -0,0 +1,147 @@
1
+ /**
2
+ * A unit quaternion representing a 3D rotation. Mirrors the subset of
3
+ * `Eigen::Quaternion`'s API (see wb-robotix's `QuaternionBasePlugin.h`) that
4
+ * `Pose` composition needs: Hamilton product, conjugate/inverse, vector
5
+ * rotation, and axis-angle rotation-vector conversion. Instances are
6
+ * immutable - every method returns a new `Quaternion`.
7
+ */
8
+
9
+ export type QuaternionData = { w: number; x: number; y: number; z: number }
10
+
11
+ const EPSILON = 1e-12
12
+
13
+ export class Quaternion implements QuaternionData {
14
+ readonly w: number
15
+ readonly x: number
16
+ readonly y: number
17
+ readonly z: number
18
+
19
+ constructor(w = 1, x = 0, y = 0, z = 0) {
20
+ this.w = w
21
+ this.x = x
22
+ this.y = y
23
+ this.z = z
24
+ }
25
+
26
+ static identity(): Quaternion {
27
+ return new Quaternion()
28
+ }
29
+
30
+ /**
31
+ * Construct from an axis-angle rotation vector [rx, ry, rz] (magnitude =
32
+ * angle in rad), matching `Eigen::Quaternion::FromRotationVector` (ported
33
+ * from wb-robotix's `QuaternionBasePlugin.h`).
34
+ */
35
+ static fromRotationVector(rotationVector: number[]): Quaternion {
36
+ const rx = rotationVector[0] ?? 0
37
+ const ry = rotationVector[1] ?? 0
38
+ const rz = rotationVector[2] ?? 0
39
+
40
+ const angle = Math.sqrt(rx * rx + ry * ry + rz * rz)
41
+ if (angle < EPSILON) {
42
+ return Quaternion.identity()
43
+ }
44
+ const half = angle / 2
45
+ const s = Math.sin(half) / angle
46
+ return new Quaternion(Math.cos(half), rx * s, ry * s, rz * s)
47
+ }
48
+
49
+ /**
50
+ * Rotation vector [rx, ry, rz] representation (magnitude = angle in rad),
51
+ * matching `Eigen::Quaternion::toRotationVector()` (ported from
52
+ * wb-robotix's `QuaternionBasePlugin.h`): using `atan2` rather than `acos`
53
+ * keeps the angle canonically within [0, pi] regardless of which of the
54
+ * two antipodal unit quaternions (this or its negation) represents the
55
+ * rotation, rather than acos's [0, 2*pi] range - important since composed
56
+ * poses need to match the same canonical rotation vector the robot
57
+ * controller itself would report for a pose.
58
+ */
59
+ toRotationVector(): number[] {
60
+ const vecNorm = Math.sqrt(
61
+ this.x * this.x + this.y * this.y + this.z * this.z,
62
+ )
63
+ if (vecNorm < EPSILON) {
64
+ return [0, 0, 0]
65
+ }
66
+ const angle = 2 * Math.atan2(vecNorm, Math.abs(this.w))
67
+ const scale = (this.w >= 0 ? angle : -angle) / vecNorm
68
+ return [this.x * scale, this.y * scale, this.z * scale]
69
+ }
70
+
71
+ /** Hamilton product: `a.multiply(b)` applied to a vector rotates by `b` first, then by `a`. */
72
+ multiply(other: QuaternionData): Quaternion {
73
+ const { w: aw, x: ax, y: ay, z: az } = this
74
+ const { w: bw, x: bx, y: by, z: bz } = other
75
+ return new Quaternion(
76
+ aw * bw - ax * bx - ay * by - az * bz,
77
+ aw * bx + ax * bw + ay * bz - az * by,
78
+ aw * by - ax * bz + ay * bw + az * bx,
79
+ aw * bz + ax * by - ay * bx + az * bw,
80
+ )
81
+ }
82
+
83
+ /** Conjugate: negates the vector part. Equal to `inverse()` for unit quaternions. */
84
+ conjugate(): Quaternion {
85
+ return new Quaternion(this.w, -this.x, -this.y, -this.z)
86
+ }
87
+
88
+ /** Inverse: `conjugate()` scaled by `1 / squaredNorm()`, matching `Eigen::Quaternion::inverse()`. Equal to `conjugate()` for unit quaternions. */
89
+ inverse(): Quaternion {
90
+ const squaredNorm =
91
+ this.w * this.w + this.x * this.x + this.y * this.y + this.z * this.z
92
+ // Degenerate (zero) quaternion has no inverse - flag it the same way Eigen does.
93
+ if (squaredNorm < EPSILON) {
94
+ return new Quaternion(0, 0, 0, 0)
95
+ }
96
+ const conjugate = this.conjugate()
97
+ return new Quaternion(
98
+ conjugate.w / squaredNorm,
99
+ conjugate.x / squaredNorm,
100
+ conjugate.y / squaredNorm,
101
+ conjugate.z / squaredNorm,
102
+ )
103
+ }
104
+
105
+ /**
106
+ * The angle (in rad, always within [0, pi]) of the rotation that takes
107
+ * `other` to `this`, matching Eigen's built-in `Quaternion::angularDistance()`.
108
+ */
109
+ angularDistance(other: QuaternionData): number {
110
+ const relative = this.multiply({
111
+ w: other.w,
112
+ x: -other.x,
113
+ y: -other.y,
114
+ z: -other.z,
115
+ })
116
+ const vecNorm = Math.sqrt(
117
+ relative.x * relative.x +
118
+ relative.y * relative.y +
119
+ relative.z * relative.z,
120
+ )
121
+ return 2 * Math.atan2(vecNorm, Math.abs(relative.w))
122
+ }
123
+
124
+ /** Rotate a 3D vector by this quaternion. */
125
+ rotateVector(v: number[]): number[] {
126
+ const vx = v[0] ?? 0
127
+ const vy = v[1] ?? 0
128
+ const vz = v[2] ?? 0
129
+ const { w, x, y, z } = this
130
+
131
+ // t = 2 * cross(q.xyz, v)
132
+ const tx = 2 * (y * vz - z * vy)
133
+ const ty = 2 * (z * vx - x * vz)
134
+ const tz = 2 * (x * vy - y * vx)
135
+
136
+ // v' = v + w*t + cross(q.xyz, t)
137
+ return [
138
+ vx + w * tx + (y * tz - z * ty),
139
+ vy + w * ty + (z * tx - x * tz),
140
+ vz + w * tz + (x * ty - y * tx),
141
+ ]
142
+ }
143
+
144
+ toJSON(): QuaternionData {
145
+ return { w: this.w, x: this.x, y: this.y, z: this.z }
146
+ }
147
+ }
@@ -0,0 +1,175 @@
1
+ import type { Pose as PoseData } from "@wandelbots/nova-api/v2"
2
+ import type { Nova } from "../../Nova.ts"
3
+ import { Pose } from "./Pose.ts"
4
+
5
+ type PoseKeys = keyof PoseData
6
+
7
+ type IsExactlyPoseData<T> = [Exclude<keyof T, PoseKeys>] extends [never]
8
+ ? [Exclude<PoseKeys, keyof T>] extends [never]
9
+ ? true
10
+ : false
11
+ : false
12
+
13
+ // Depth cap avoids "type instantiation is excessively deep" on nova-api's
14
+ // large (and possibly cyclic, e.g. compound colliders) generated type graph.
15
+ type MaxDepth = [
16
+ unknown,
17
+ unknown,
18
+ unknown,
19
+ unknown,
20
+ unknown,
21
+ unknown,
22
+ unknown,
23
+ unknown,
24
+ unknown,
25
+ unknown,
26
+ ]
27
+
28
+ type AugmentPosesCore<
29
+ T,
30
+ Depth extends readonly unknown[],
31
+ > = Depth["length"] extends MaxDepth["length"]
32
+ ? T
33
+ : IsExactlyPoseData<T> extends true
34
+ ? Pose
35
+ : T extends readonly (infer U)[]
36
+ ? DeepPoseAugmented<U, [...Depth, unknown]>[]
37
+ : T extends object
38
+ ? { [K in keyof T]: DeepPoseAugmented<T[K], [...Depth, unknown]> }
39
+ : T
40
+
41
+ /**
42
+ * Type-level counterpart to `augmentPoses`: recursively replaces any
43
+ * `PoseData`-shaped field with `Pose` (distributing over unions, e.g. so
44
+ * optional `Pose | undefined` fields keep the `| undefined`), so the static
45
+ * type matches what's actually returned at runtime.
46
+ */
47
+ export type DeepPoseAugmented<
48
+ T,
49
+ Depth extends readonly unknown[] = [],
50
+ > = T extends unknown ? AugmentPosesCore<T, Depth> : never
51
+
52
+ function isPlainObject(value: unknown): value is Record<string, unknown> {
53
+ return (
54
+ typeof value === "object" &&
55
+ value !== null &&
56
+ !Array.isArray(value) &&
57
+ !(value instanceof Pose)
58
+ )
59
+ }
60
+
61
+ function isNumberTriple(value: unknown): value is number[] {
62
+ return (
63
+ Array.isArray(value) &&
64
+ value.length === 3 &&
65
+ value.every((n) => typeof n === "number")
66
+ )
67
+ }
68
+
69
+ /**
70
+ * Structural check for the wire shape of `Pose` (`{ position, orientation }`,
71
+ * each a 3-number array, and nothing else). This API has no other type with
72
+ * this exact shape, so it reliably identifies `Pose` values without needing
73
+ * per-endpoint knowledge of which fields are poses.
74
+ */
75
+ function isPoseShape(value: Record<string, unknown>): boolean {
76
+ return (
77
+ Object.keys(value).length === 2 &&
78
+ isNumberTriple(value.position) &&
79
+ isNumberTriple(value.orientation)
80
+ )
81
+ }
82
+
83
+ function augmentPosesInPlace(value: unknown): void {
84
+ if (Array.isArray(value)) {
85
+ for (const item of value) {
86
+ augmentPosesInPlace(item)
87
+ }
88
+ return
89
+ }
90
+
91
+ if (isPlainObject(value)) {
92
+ if (isPoseShape(value)) {
93
+ Object.setPrototypeOf(value, Pose.prototype)
94
+ } else {
95
+ for (const key of Object.keys(value)) {
96
+ augmentPosesInPlace(value[key])
97
+ }
98
+ }
99
+ }
100
+ }
101
+
102
+ /**
103
+ * Recursively walks a parsed API response/request body, upgrading any
104
+ * `Pose`-shaped objects in place to `Pose` instances so they gain math
105
+ * methods (`multiply`, `inverse`, ...) while remaining JSON/wire-compatible.
106
+ * Used by `withMath` for `nova.api.*` responses; exported so it can also
107
+ * be applied manually to e.g. websocket messages.
108
+ */
109
+ export function augmentPoses<T>(value: T): DeepPoseAugmented<T> {
110
+ augmentPosesInPlace(value)
111
+ return value as DeepPoseAugmented<T>
112
+ }
113
+
114
+ type WithAugmentedPosesCore<
115
+ T,
116
+ Depth extends readonly unknown[],
117
+ > = Depth["length"] extends MaxDepth["length"]
118
+ ? T
119
+ : T extends (...args: infer A) => Promise<infer R>
120
+ ? (...args: A) => Promise<DeepPoseAugmented<R>>
121
+ : T extends object
122
+ ? { [K in keyof T]: WithAugmentedPosesCore<T[K], [...Depth, unknown]> }
123
+ : T
124
+
125
+ /**
126
+ * Recursively maps every method on `Nova["api"]` (and its nested API groups)
127
+ * so calls are typed as returning `DeepPoseAugmented` results, matching what
128
+ * `withMath` does at runtime.
129
+ */
130
+ type WithAugmentedPoses<T> = WithAugmentedPosesCore<T, []>
131
+
132
+ export type NovaWithMath = Omit<Nova, "api"> & {
133
+ readonly api: WithAugmentedPoses<Nova["api"]>
134
+ }
135
+
136
+ function wrapWithPoseAugmentation<T extends object>(target: T): T {
137
+ return new Proxy(target, {
138
+ get(t, prop) {
139
+ const value = Reflect.get(t, prop, t)
140
+ if (typeof value === "function") {
141
+ return (...args: unknown[]) => {
142
+ const result = (value as (...a: unknown[]) => unknown).apply(t, args)
143
+ return result instanceof Promise
144
+ ? result.then((data) => augmentPoses(data))
145
+ : result
146
+ }
147
+ }
148
+ if (value !== null && typeof value === "object") {
149
+ return wrapWithPoseAugmentation(value)
150
+ }
151
+ return value
152
+ },
153
+ }) as T
154
+ }
155
+
156
+ /**
157
+ * Wraps a `Nova` instance so every `nova.api.*` call automatically upgrades
158
+ * `Pose`-shaped fields in its response to `Pose` instances (with math
159
+ * methods like `multiply`/`inverse`). Returns a new proxied view - does not
160
+ * mutate the original `nova` instance.
161
+ */
162
+ export function withMath(nova: Nova): NovaWithMath {
163
+ const proxy = new Proxy(nova, {
164
+ get(target, prop) {
165
+ if (prop === "api") {
166
+ return wrapWithPoseAugmentation(target.api)
167
+ }
168
+ // receiver is `target`, not the proxy, so `this` inside Nova's own
169
+ // methods stays bound to the original (un-proxied) instance.
170
+ return Reflect.get(target, prop, target)
171
+ },
172
+ })
173
+
174
+ return proxy as unknown as NovaWithMath
175
+ }