node-osc 10.0.0 → 11.0.0

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.
@@ -0,0 +1,324 @@
1
+ // OSC 1.0 Protocol Implementation
2
+ // Based on http://opensoundcontrol.org/spec-1_0
3
+
4
+ // Helper functions for OSC encoding/decoding
5
+
6
+ function padString(str) {
7
+ const nullTerminated = str + '\0';
8
+ const padding = 4 - (nullTerminated.length % 4);
9
+ return nullTerminated + '\0'.repeat(padding === 4 ? 0 : padding);
10
+ }
11
+
12
+ function readString(buffer, offset) {
13
+ let end = offset;
14
+ while (end < buffer.length && buffer[end] !== 0) {
15
+ end++;
16
+ }
17
+ const str = buffer.subarray(offset, end).toString('utf8');
18
+ // Find next 4-byte boundary
19
+ const paddedLength = Math.ceil((end - offset + 1) / 4) * 4;
20
+ return { value: str, offset: offset + paddedLength };
21
+ }
22
+
23
+ function writeInt32(value) {
24
+ const buffer = Buffer.alloc(4);
25
+ buffer.writeInt32BE(value, 0);
26
+ return buffer;
27
+ }
28
+
29
+ function readInt32(buffer, offset) {
30
+ const value = buffer.readInt32BE(offset);
31
+ return { value, offset: offset + 4 };
32
+ }
33
+
34
+ function writeFloat32(value) {
35
+ const buffer = Buffer.alloc(4);
36
+ buffer.writeFloatBE(value, 0);
37
+ return buffer;
38
+ }
39
+
40
+ function readFloat32(buffer, offset) {
41
+ const value = buffer.readFloatBE(offset);
42
+ return { value, offset: offset + 4 };
43
+ }
44
+
45
+ function writeBlob(value) {
46
+ const length = value.length;
47
+ const lengthBuffer = writeInt32(length);
48
+ const padding = 4 - (length % 4);
49
+ const paddingBuffer = Buffer.alloc(padding === 4 ? 0 : padding);
50
+ return Buffer.concat([lengthBuffer, value, paddingBuffer]);
51
+ }
52
+
53
+ function readBlob(buffer, offset) {
54
+ const lengthResult = readInt32(buffer, offset);
55
+ const length = lengthResult.value;
56
+ const data = buffer.subarray(lengthResult.offset, lengthResult.offset + length);
57
+ const padding = 4 - (length % 4);
58
+ const nextOffset = lengthResult.offset + length + (padding === 4 ? 0 : padding);
59
+ return { value: data, offset: nextOffset };
60
+ }
61
+
62
+ function writeTimeTag(value) {
63
+ // For now, treat timetag as a double (8 bytes)
64
+ // OSC timetag is 64-bit: 32-bit seconds since 1900, 32-bit fractional
65
+ const buffer = Buffer.alloc(8);
66
+ if (typeof value === 'number') {
67
+ // Convert to OSC timetag format
68
+ const seconds = Math.floor(value);
69
+ const fraction = Math.floor((value - seconds) * 0x100000000);
70
+ buffer.writeUInt32BE(seconds + 2208988800, 0); // Add epoch offset (1900 vs 1970)
71
+ buffer.writeUInt32BE(fraction, 4);
72
+ } else {
73
+ // If not a number, write zeros (immediate execution)
74
+ buffer.writeUInt32BE(0, 0);
75
+ buffer.writeUInt32BE(1, 4);
76
+ }
77
+ return buffer;
78
+ }
79
+
80
+ function readTimeTag(buffer, offset) {
81
+ const seconds = buffer.readUInt32BE(offset);
82
+ const fraction = buffer.readUInt32BE(offset + 4);
83
+
84
+ let value;
85
+ if (seconds === 0 && fraction === 1) {
86
+ // Immediate execution
87
+ value = 0;
88
+ } else {
89
+ // Convert from OSC epoch (1900) to Unix epoch (1970)
90
+ const unixSeconds = seconds - 2208988800;
91
+ const fractionalSeconds = fraction / 0x100000000;
92
+ value = unixSeconds + fractionalSeconds;
93
+ }
94
+
95
+ return { value, offset: offset + 8 };
96
+ }
97
+
98
+ function writeMidi(value) {
99
+ // MIDI message is 4 bytes: port id, status byte, data1, data2
100
+ const buffer = Buffer.alloc(4);
101
+
102
+ if (Buffer.isBuffer(value)) {
103
+ if (value.length !== 4) {
104
+ throw new Error('MIDI message must be exactly 4 bytes');
105
+ }
106
+ value.copy(buffer);
107
+ } else if (typeof value === 'object' && value !== null) {
108
+ // Allow object format: { port: 0, status: 144, data1: 60, data2: 127 }
109
+ buffer.writeUInt8(value.port || 0, 0);
110
+ buffer.writeUInt8(value.status || 0, 1);
111
+ buffer.writeUInt8(value.data1 || 0, 2);
112
+ buffer.writeUInt8(value.data2 || 0, 3);
113
+ } else {
114
+ throw new Error('MIDI value must be a 4-byte Buffer or object with port, status, data1, data2 properties');
115
+ }
116
+
117
+ return buffer;
118
+ }
119
+
120
+ function readMidi(buffer, offset) {
121
+ if (offset + 4 > buffer.length) {
122
+ throw new Error('Not enough bytes for MIDI message');
123
+ }
124
+
125
+ const value = buffer.subarray(offset, offset + 4);
126
+ return { value, offset: offset + 4 };
127
+ }
128
+
129
+ function encodeArgument(arg) {
130
+ if (typeof arg === 'object' && arg.type && arg.value !== undefined) {
131
+ // Explicit type specification
132
+ switch (arg.type) {
133
+ case 'i':
134
+ case 'integer':
135
+ return { tag: 'i', data: writeInt32(arg.value) };
136
+ case 'f':
137
+ case 'float':
138
+ return { tag: 'f', data: writeFloat32(arg.value) };
139
+ case 's':
140
+ case 'string':
141
+ return { tag: 's', data: Buffer.from(padString(arg.value)) };
142
+ case 'b':
143
+ case 'blob':
144
+ return { tag: 'b', data: writeBlob(arg.value) };
145
+ case 'd':
146
+ case 'double':
147
+ // For doubles, use float for now (OSC 1.0 doesn't have double)
148
+ return { tag: 'f', data: writeFloat32(arg.value) };
149
+ case 'T':
150
+ case 'boolean':
151
+ return arg.value ? { tag: 'T', data: Buffer.alloc(0) } : { tag: 'F', data: Buffer.alloc(0) };
152
+ case 'm':
153
+ case 'midi':
154
+ return { tag: 'm', data: writeMidi(arg.value) };
155
+ default:
156
+ throw new Error(`Unknown argument type: ${arg.type}`);
157
+ }
158
+ }
159
+
160
+ // Infer type from JavaScript type
161
+ switch (typeof arg) {
162
+ case 'number':
163
+ if (Number.isInteger(arg)) {
164
+ return { tag: 'i', data: writeInt32(arg) };
165
+ } else {
166
+ return { tag: 'f', data: writeFloat32(arg) };
167
+ }
168
+ case 'string':
169
+ return { tag: 's', data: Buffer.from(padString(arg)) };
170
+ case 'boolean':
171
+ return arg ? { tag: 'T', data: Buffer.alloc(0) } : { tag: 'F', data: Buffer.alloc(0) };
172
+ default:
173
+ if (Buffer.isBuffer(arg)) {
174
+ return { tag: 'b', data: writeBlob(arg) };
175
+ }
176
+ throw new Error(`Don't know how to encode argument: ${arg}`);
177
+ }
178
+ }
179
+
180
+ function decodeArgument(tag, buffer, offset) {
181
+ switch (tag) {
182
+ case 'i':
183
+ return readInt32(buffer, offset);
184
+ case 'f':
185
+ return readFloat32(buffer, offset);
186
+ case 's':
187
+ return readString(buffer, offset);
188
+ case 'b':
189
+ return readBlob(buffer, offset);
190
+ case 'T':
191
+ return { value: true, offset };
192
+ case 'F':
193
+ return { value: false, offset };
194
+ case 'N':
195
+ return { value: null, offset };
196
+ case 'm':
197
+ return readMidi(buffer, offset);
198
+ default:
199
+ throw new Error(`I don't understand the argument code ${tag}`);
200
+ }
201
+ }
202
+
203
+ export function toBuffer(message) {
204
+ if (message.oscType === 'bundle') {
205
+ return encodeBundleToBuffer(message);
206
+ } else {
207
+ return encodeMessageToBuffer(message);
208
+ }
209
+ }
210
+
211
+ function encodeMessageToBuffer(message) {
212
+ // OSC Message format:
213
+ // Address pattern (padded string)
214
+ // Type tag string (padded string starting with ,)
215
+ // Arguments (encoded according to type tags)
216
+
217
+ const address = padString(message.address);
218
+ const addressBuffer = Buffer.from(address);
219
+
220
+ const encodedArgs = message.args.map(encodeArgument);
221
+ const typeTags = ',' + encodedArgs.map(arg => arg.tag).join('');
222
+ const typeTagsBuffer = Buffer.from(padString(typeTags));
223
+
224
+ const argumentBuffers = encodedArgs.map(arg => arg.data);
225
+
226
+ return Buffer.concat([addressBuffer, typeTagsBuffer, ...argumentBuffers]);
227
+ }
228
+
229
+ function encodeBundleToBuffer(bundle) {
230
+ // OSC Bundle format:
231
+ // "#bundle" (padded string)
232
+ // Timetag (8 bytes)
233
+ // Elements (each prefixed with size)
234
+
235
+ const bundleString = padString('#bundle');
236
+ const bundleStringBuffer = Buffer.from(bundleString);
237
+
238
+ const timetagBuffer = writeTimeTag(bundle.timetag);
239
+
240
+ const elementBuffers = bundle.elements.map(element => {
241
+ let elementBuffer;
242
+ if (element.oscType === 'bundle') {
243
+ elementBuffer = encodeBundleToBuffer(element);
244
+ } else {
245
+ elementBuffer = encodeMessageToBuffer(element);
246
+ }
247
+ const sizeBuffer = writeInt32(elementBuffer.length);
248
+ return Buffer.concat([sizeBuffer, elementBuffer]);
249
+ });
250
+
251
+ return Buffer.concat([bundleStringBuffer, timetagBuffer, ...elementBuffers]);
252
+ }
253
+
254
+ export function fromBuffer(buffer) {
255
+ // Check if it's a bundle or message
256
+ if (buffer.length >= 8 && buffer.subarray(0, 8).toString() === '#bundle\0') {
257
+ return decodeBundleFromBuffer(buffer);
258
+ } else {
259
+ return decodeMessageFromBuffer(buffer);
260
+ }
261
+ }
262
+
263
+ function decodeMessageFromBuffer(buffer) {
264
+ let offset = 0;
265
+
266
+ // Read address pattern
267
+ const addressResult = readString(buffer, offset);
268
+ const address = addressResult.value;
269
+ offset = addressResult.offset;
270
+
271
+ // Read type tag string
272
+ const typeTagsResult = readString(buffer, offset);
273
+ const typeTags = typeTagsResult.value;
274
+ offset = typeTagsResult.offset;
275
+
276
+ if (!typeTags.startsWith(',')) {
277
+ throw new Error('Malformed Packet');
278
+ }
279
+
280
+ const tags = typeTags.slice(1); // Remove leading comma
281
+ const args = [];
282
+
283
+ for (const tag of tags) {
284
+ const argResult = decodeArgument(tag, buffer, offset);
285
+ args.push({ value: argResult.value });
286
+ offset = argResult.offset;
287
+ }
288
+
289
+ return {
290
+ oscType: 'message',
291
+ address,
292
+ args
293
+ };
294
+ }
295
+
296
+ function decodeBundleFromBuffer(buffer) {
297
+ let offset = 8; // Skip "#bundle\0"
298
+
299
+ // Read timetag
300
+ const timetagResult = readTimeTag(buffer, offset);
301
+ const timetag = timetagResult.value;
302
+ offset = timetagResult.offset;
303
+
304
+ const elements = [];
305
+
306
+ while (offset < buffer.length) {
307
+ // Read element size
308
+ const sizeResult = readInt32(buffer, offset);
309
+ const size = sizeResult.value;
310
+ offset = sizeResult.offset;
311
+
312
+ // Read element data
313
+ const elementBuffer = buffer.subarray(offset, offset + size);
314
+ const element = fromBuffer(elementBuffer);
315
+ elements.push(element);
316
+ offset += size;
317
+ }
318
+
319
+ return {
320
+ oscType: 'bundle',
321
+ timetag,
322
+ elements
323
+ };
324
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "node-osc",
3
3
  "description": "pyOSC inspired library for sending and receiving OSC messages",
4
- "version": "10.0.0",
4
+ "version": "11.0.0",
5
5
  "exports": {
6
6
  "require": "./dist/lib/index.js",
7
7
  "default": "./lib/index.mjs"
@@ -10,6 +10,10 @@
10
10
  "#decode": {
11
11
  "require": "./dist/lib/internal/decode.js",
12
12
  "default": "./lib/internal/decode.mjs"
13
+ },
14
+ "#osc": {
15
+ "require": "./dist/lib/internal/osc.js",
16
+ "default": "./lib/internal/osc.mjs"
13
17
  }
14
18
  },
15
19
  "author": {
@@ -42,9 +46,6 @@
42
46
  "type": "git",
43
47
  "url": "git+https://github.com/MylesBorins/node-osc.git"
44
48
  },
45
- "dependencies": {
46
- "osc-min": "^1.1.1"
47
- },
48
49
  "devDependencies": {
49
50
  "@eslint/js": "^9.32.0",
50
51
  "eslint": "^9.32.0",
package/rollup.config.mjs CHANGED
@@ -34,7 +34,6 @@ function walkLib(config) {
34
34
  external: [
35
35
  'node:dgram',
36
36
  'node:events',
37
- 'osc-min',
38
37
  'jspack',
39
38
  '#decode'
40
39
  ]
@@ -59,7 +58,6 @@ function walkTest(config) {
59
58
  'node:dgram',
60
59
  'node:net',
61
60
  'node-osc',
62
- 'osc-min',
63
61
  'tap',
64
62
  '#decode'
65
63
  ]
@@ -29,3 +29,80 @@ test('decode: invalid typetags', (t) => {
29
29
  }, /I don't understand the argument code R/);
30
30
  t.end();
31
31
  });
32
+
33
+ test('decode: malformed OSC structure', (t) => {
34
+ // Try to create a scenario that might trigger the "else" case in decode
35
+ // This tests an edge case where the buffer might be parsed but not create a valid OSC structure
36
+ t.throws(() => {
37
+ // Create a buffer that's too short to be valid
38
+ const buf = Buffer.from('\0\0\0\0');
39
+ decode(buf);
40
+ }, /Malformed Packet/);
41
+ t.end();
42
+ });
43
+
44
+ test('decode: corrupted buffer', (t) => {
45
+ // Test with a buffer that could potentially cause fromBuffer to return unexpected results
46
+ t.throws(() => {
47
+ // Create a malformed buffer that might not parse correctly
48
+ const buf = Buffer.from('invalid');
49
+ decode(buf);
50
+ }, /(Malformed Packet|Cannot read|out of range)/);
51
+ t.end();
52
+ });
53
+
54
+ // This test attempts to exercise edge cases in the decode function
55
+ test('decode: edge case with manually crafted invalid structure', (t) => {
56
+ // Since the decode function has a defensive else clause, let's try to trigger it
57
+ // by creating a buffer that might result in an unexpected object structure
58
+
59
+ // Try with an empty buffer
60
+ t.throws(() => {
61
+ const buf = Buffer.alloc(0);
62
+ decode(buf);
63
+ }, /(Malformed Packet|Cannot read|out of range)/);
64
+
65
+ // Try with a buffer containing only null bytes
66
+ t.throws(() => {
67
+ const buf = Buffer.alloc(16, 0);
68
+ decode(buf);
69
+ }, /(Malformed Packet|Cannot read|out of range)/);
70
+
71
+ t.end();
72
+ });
73
+
74
+ test('decode: malformed structure with unexpected oscType', async (t) => {
75
+ // Test the defensive else clause by providing a custom fromBuffer function
76
+ // that returns an object with an invalid oscType
77
+
78
+ const mockFromBuffer = () => ({
79
+ oscType: 'invalid',
80
+ data: 'test'
81
+ });
82
+
83
+ t.throws(() => {
84
+ decode(Buffer.from('test'), mockFromBuffer);
85
+ }, /Malformed Packet/, 'should throw for invalid oscType');
86
+
87
+ // Test with undefined oscType
88
+ const mockFromBufferUndefined = () => ({
89
+ data: 'test'
90
+ // missing oscType property
91
+ });
92
+
93
+ t.throws(() => {
94
+ decode(Buffer.from('test'), mockFromBufferUndefined);
95
+ }, /Malformed Packet/, 'should throw for undefined oscType');
96
+
97
+ // Test with null oscType
98
+ const mockFromBufferNull = () => ({
99
+ oscType: null,
100
+ data: 'test'
101
+ });
102
+
103
+ t.throws(() => {
104
+ decode(Buffer.from('test'), mockFromBufferNull);
105
+ }, /Malformed Packet/, 'should throw for null oscType');
106
+
107
+ t.end();
108
+ });