@djodjonx/x32-simulator 0.0.6 → 0.0.8

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/dist/server.cjs CHANGED
@@ -1,13 +1,190 @@
1
1
  #!/usr/bin/env node
2
- const require_SchemaRegistry = require('./SchemaRegistry-DE6iObDv.cjs');
2
+ const require_SchemaRegistry = require('./SchemaRegistry-aSJvYTM7.cjs');
3
3
  let node_readline = require("node:readline");
4
4
  node_readline = require_SchemaRegistry.__toESM(node_readline);
5
5
  let node_fs = require("node:fs");
6
6
  node_fs = require_SchemaRegistry.__toESM(node_fs);
7
7
  let node_path = require("node:path");
8
8
  node_path = require_SchemaRegistry.__toESM(node_path);
9
+ let node_crypto = require("node:crypto");
10
+ let node_fs_promises = require("node:fs/promises");
9
11
 
12
+ //#region src/infrastructure/repositories/JsonFileStateRepository.ts
13
+ /**
14
+ * JSON file-based state repository.
15
+ * Persists state to a JSON file on disk.
16
+ * Supports auto-save and manual flush.
17
+ */
18
+ var JsonFileStateRepository = class {
19
+ state = /* @__PURE__ */ new Map();
20
+ dirty = false;
21
+ autoSaveTimer = null;
22
+ saving = false;
23
+ /**
24
+ * Creates a new JSON file repository.
25
+ * @param filePath - Path to the JSON file.
26
+ * @param autoSaveInterval - Auto-save interval in ms (0 = disabled).
27
+ */
28
+ constructor(filePath, autoSaveInterval = 5e3) {
29
+ this.filePath = filePath;
30
+ this.autoSaveInterval = autoSaveInterval;
31
+ if (this.autoSaveInterval > 0) this.startAutoSave();
32
+ }
33
+ /**
34
+ * Starts the auto-save timer.
35
+ */
36
+ startAutoSave() {
37
+ this.autoSaveTimer = setInterval(async () => {
38
+ if (this.dirty && !this.saving) await this.flush();
39
+ }, this.autoSaveInterval);
40
+ this.autoSaveTimer.unref();
41
+ }
42
+ /**
43
+ * Stops the auto-save timer.
44
+ */
45
+ stopAutoSave() {
46
+ if (this.autoSaveTimer) {
47
+ clearInterval(this.autoSaveTimer);
48
+ this.autoSaveTimer = null;
49
+ }
50
+ }
51
+ /**
52
+ * Checks if the file exists.
53
+ */
54
+ async fileExists() {
55
+ try {
56
+ await (0, node_fs_promises.access)(this.filePath, node_fs.constants.F_OK);
57
+ return true;
58
+ } catch {
59
+ return false;
60
+ }
61
+ }
62
+ /**
63
+ * Loads state from JSON file.
64
+ */
65
+ async load() {
66
+ if (await this.fileExists()) try {
67
+ const content = await (0, node_fs_promises.readFile)(this.filePath, "utf-8");
68
+ const data = JSON.parse(content);
69
+ this.state.clear();
70
+ for (const [key, value] of Object.entries(data)) this.state.set(key, value);
71
+ this.dirty = false;
72
+ return data;
73
+ } catch (error) {
74
+ console.error(`[JsonFileStateRepository] Failed to load state from ${this.filePath}:`, error);
75
+ return {};
76
+ }
77
+ return {};
78
+ }
79
+ /**
80
+ * Saves complete state to JSON file.
81
+ */
82
+ async save(state) {
83
+ this.state.clear();
84
+ for (const [key, value] of Object.entries(state)) this.state.set(key, value);
85
+ this.dirty = true;
86
+ await this.flush();
87
+ }
88
+ /**
89
+ * Gets a single value.
90
+ */
91
+ get(address) {
92
+ return this.state.get(address);
93
+ }
94
+ /**
95
+ * Sets a single value and marks as dirty.
96
+ */
97
+ set(address, value) {
98
+ this.state.set(address, value);
99
+ this.dirty = true;
100
+ }
101
+ /**
102
+ * Gets all entries.
103
+ */
104
+ getAll() {
105
+ const result = {};
106
+ this.state.forEach((value, key) => {
107
+ result[key] = value;
108
+ });
109
+ return result;
110
+ }
111
+ /**
112
+ * Resets state to defaults and marks as dirty.
113
+ */
114
+ reset(defaults) {
115
+ this.state.clear();
116
+ for (const [key, value] of Object.entries(defaults)) this.state.set(key, value);
117
+ this.dirty = true;
118
+ }
119
+ /**
120
+ * Writes state to JSON file if dirty.
121
+ */
122
+ async flush() {
123
+ if (!this.dirty || this.saving) return;
124
+ this.saving = true;
125
+ const tmpPath = `${this.filePath}.${process.pid}.${(0, node_crypto.randomBytes)(4).toString("hex")}.tmp`;
126
+ try {
127
+ const data = this.getAll();
128
+ await (0, node_fs_promises.writeFile)(tmpPath, JSON.stringify(data, null, 2), "utf-8");
129
+ await (0, node_fs_promises.rename)(tmpPath, this.filePath);
130
+ this.dirty = false;
131
+ } catch (error) {
132
+ await (0, node_fs_promises.rm)(tmpPath, { force: true });
133
+ console.error(`[JsonFileStateRepository] Failed to save state to ${this.filePath}:`, error);
134
+ } finally {
135
+ this.saving = false;
136
+ }
137
+ }
138
+ /**
139
+ * Cleanup: stop auto-save and flush pending changes.
140
+ */
141
+ async dispose() {
142
+ this.stopAutoSave();
143
+ await this.flush();
144
+ }
145
+ };
146
+
147
+ //#endregion
148
+ //#region src/infrastructure/repositories/StateRepositoryFactory.ts
149
+ /**
150
+ * Creates a state repository based on configuration.
151
+ * @param config - Repository configuration.
152
+ * @returns The configured state repository.
153
+ */
154
+ function createStateRepository(config) {
155
+ switch (config.type) {
156
+ case "json":
157
+ if (!config.filePath) throw new Error("JSON repository requires a filePath");
158
+ return new JsonFileStateRepository(config.filePath, config.autoSaveInterval ?? 5e3);
159
+ case "memory":
160
+ default: return new require_SchemaRegistry.InMemoryStateRepository();
161
+ }
162
+ }
163
+
164
+ //#endregion
10
165
  //#region src/presentation/cli/server.ts
166
+ const CONSOLE_MODELS = new Set([
167
+ "X32",
168
+ "X32RACK",
169
+ "X32C",
170
+ "X32P",
171
+ "X32CORE",
172
+ "M32",
173
+ "M32C",
174
+ "M32R"
175
+ ]);
176
+ const MODEL_LIST = "X32, X32RACK, X32C, X32P, X32CORE, M32, M32C, or M32R";
177
+ const FIRMWARE_PATTERN = /^\d+\.\d+$/;
178
+ const IPV4_OCTET = "(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)";
179
+ const IPV4_PATTERN = /* @__PURE__ */ new RegExp(`^${IPV4_OCTET}(?:\\.${IPV4_OCTET}){3}$`);
180
+ const fail = (message) => {
181
+ throw new Error(message);
182
+ };
183
+ const readOption = (args, index, flag) => {
184
+ const next = args[index + 1];
185
+ if (next === void 0 || next.startsWith("-")) fail(`Missing value for ${flag}.`);
186
+ return next;
187
+ };
11
188
  const loadEnv = () => {
12
189
  try {
13
190
  const envPath = node_path.resolve(process.cwd(), ".env");
@@ -28,6 +205,15 @@ const parseArgs = (argv) => {
28
205
  const args = argv.slice(2);
29
206
  let cliPort;
30
207
  let cliHost;
208
+ let storageType = "memory";
209
+ let stateFilePath;
210
+ let cliName;
211
+ let cliModel;
212
+ let cliFirmware;
213
+ let cliAdvertiseIp;
214
+ let cliLogLevel;
215
+ let cliPermissive = false;
216
+ let cliMeterMode;
31
217
  for (let i = 0; i < args.length; i++) {
32
218
  const arg = args[i];
33
219
  if (arg === "--port" || arg === "-p") {
@@ -46,29 +232,199 @@ const parseArgs = (argv) => {
46
232
  continue;
47
233
  }
48
234
  }
49
- if (!cliHost && /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(arg)) {
50
- cliHost = arg;
235
+ if (arg === "--name") {
236
+ cliName = readOption(args, i, arg);
237
+ i++;
238
+ continue;
239
+ }
240
+ if (arg === "--model") {
241
+ const model$1 = readOption(args, i, arg);
242
+ if (!CONSOLE_MODELS.has(model$1)) fail(`Unknown model "${model$1}". Expected ${MODEL_LIST}.`);
243
+ cliModel = model$1;
244
+ i++;
245
+ continue;
246
+ }
247
+ if (arg === "--firmware") {
248
+ const firmware$1 = readOption(args, i, arg);
249
+ if (!FIRMWARE_PATTERN.test(firmware$1)) fail(`Invalid firmware "${firmware$1}". Expected <digits>.<digits>, for example 4.06.`);
250
+ cliFirmware = firmware$1;
251
+ i++;
252
+ continue;
253
+ }
254
+ if (arg === "--log-level") {
255
+ cliLogLevel = require_SchemaRegistry.parseLogLevel(readOption(args, i, arg));
256
+ i++;
257
+ continue;
258
+ }
259
+ if (arg === "--meters") {
260
+ cliMeterMode = require_SchemaRegistry.parseMeterMode(readOption(args, i, arg));
261
+ i++;
262
+ continue;
263
+ }
264
+ if (arg === "--advertise-ip") {
265
+ const advertiseIp = readOption(args, i, arg);
266
+ if (!IPV4_PATTERN.test(advertiseIp)) fail(`Invalid advertise IP "${advertiseIp}". Expected an IPv4 address.`);
267
+ cliAdvertiseIp = advertiseIp;
268
+ i++;
51
269
  continue;
52
270
  }
53
- if (!cliPort && /^\d+$/.test(arg)) {
54
- cliPort = parseInt(arg, 10);
271
+ if (arg === "--storage" || arg === "-s") {
272
+ const next = args[i + 1];
273
+ if (next && (next === "memory" || next === "json")) {
274
+ storageType = next;
275
+ i++;
276
+ }
277
+ }
278
+ if (arg === "--state-file" || arg === "-f") {
279
+ const next = args[i + 1];
280
+ if (next) {
281
+ stateFilePath = next;
282
+ storageType = "json";
283
+ i++;
284
+ }
285
+ }
286
+ if (arg === "--permissive") {
287
+ cliPermissive = true;
55
288
  continue;
56
289
  }
290
+ if (arg === "--help") {
291
+ console.log(`
292
+ X32 Simulator - Usage:
293
+ x32-simulator [options]
294
+
295
+ Options:
296
+ -p, --port <port> UDP port to listen on (default: 10023)
297
+ -h, --host <ip> IP address to bind to (default: 0.0.0.0)
298
+ --name <string> Console name reported by /xinfo (default: osc-server)
299
+ --model <model> ${MODEL_LIST} (default: X32)
300
+ --firmware <d.d> Firmware digits.digits (default: 4.06)
301
+ --advertise-ip <ipv4> IP announced when bound to 0.0.0.0
302
+ --log-level <level> debug, info, warn or error (default: info)
303
+ --meters <mode> silent, fixed, or noise (default: silent)
304
+ --permissive Store a Set sent to an unknown address
305
+ -s, --storage <type> Storage type: 'memory' or 'json' (default: memory)
306
+ -f, --state-file <file> Path to JSON state file (implies --storage json)
307
+ --help Show this help message
308
+
309
+ Terminal:
310
+ reset Reset every parameter to its default and notify clients
311
+ set <address> <text> Set a parameter from scene text, for example set /ch/01/mix/fader -10
312
+ get <address> Print a parameter in scene text
313
+ save Flush the state file
314
+ exit Stop the server
315
+
316
+ Examples:
317
+ x32-simulator --port 10023 --host 192.168.1.100
318
+ x32-simulator --model X32RACK --name TestRack --firmware 4.06
319
+ x32-simulator --storage json --state-file ./x32-state.json
320
+ x32-simulator -p 10023 -f ./my-mixer-state.json
321
+ `);
322
+ process.exit(0);
323
+ }
324
+ if (!cliHost && /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(arg)) cliHost = arg;
325
+ if (!cliPort && /^\d+$/.test(arg)) cliPort = parseInt(arg, 10);
57
326
  }
327
+ const PORT = cliPort || parseInt(process.env.X32_PORT || "10023", 10);
328
+ const HOST = cliHost || process.env.X32_IP || "0.0.0.0";
329
+ const name = cliName ?? require_SchemaRegistry.DEFAULT_CONFIG.DEFAULT_NAME;
330
+ const model = cliModel ?? require_SchemaRegistry.DEFAULT_CONFIG.DEFAULT_MODEL;
331
+ const firmware = cliFirmware ?? require_SchemaRegistry.DEFAULT_FIRMWARE;
332
+ const logLevel = cliLogLevel ?? require_SchemaRegistry.LogLevel.INFO;
58
333
  return {
59
- PORT: cliPort || parseInt(process.env.X32_PORT || "10023", 10),
60
- HOST: cliHost || process.env.X32_IP || "0.0.0.0"
334
+ PORT,
335
+ HOST,
336
+ storageType,
337
+ stateFilePath,
338
+ name,
339
+ model,
340
+ firmware,
341
+ advertiseIp: cliAdvertiseIp,
342
+ logLevel,
343
+ permissive: cliPermissive,
344
+ meterMode: cliMeterMode
61
345
  };
62
346
  };
347
+ /** Keeps `{ PERMISSIVE }` alone when `--meters` is omitted, so the default stays `silent`. */
348
+ const meterConfig = (permissive, meterMode) => {
349
+ const config = { PERMISSIVE: permissive };
350
+ if (meterMode !== void 0) config.METER_MODE = meterMode;
351
+ return config;
352
+ };
353
+ /**
354
+ * `set` converts scene text with {@link textToOsc}. `get` prints scene text.
355
+ * Unknown addresses and bad tokens are reported. They do not change the state.
356
+ */
357
+ const runParamCommand = (word, line, schemaRegistry, service) => {
358
+ const match = /^(?:set|get)\s+(\S+)(?:\s+([\s\S]+))?$/i.exec(line);
359
+ const address = match?.[1];
360
+ if (!address) {
361
+ console.log(`Unknown address ${line}`);
362
+ return;
363
+ }
364
+ const node = schemaRegistry.getNode(address);
365
+ if (!node) {
366
+ console.log(`Unknown address ${address}`);
367
+ return;
368
+ }
369
+ if (word === "get") {
370
+ try {
371
+ const value = service.getParameter(address);
372
+ if (value === void 0) {
373
+ console.log(address);
374
+ return;
375
+ }
376
+ const shown = node.param ? require_SchemaRegistry.oscToText(node.param, value) : String(value);
377
+ console.log(`${address} ${shown}`);
378
+ } catch (err) {
379
+ console.log(err instanceof Error ? err.message : String(err));
380
+ }
381
+ return;
382
+ }
383
+ const text = match?.[2]?.trim();
384
+ if (!text) {
385
+ console.log(`Invalid value for ${address}`);
386
+ return;
387
+ }
388
+ let osc;
389
+ if (node.param) osc = require_SchemaRegistry.textToOsc(node.param, text);
390
+ else if (node.type === "s") osc = text;
391
+ else {
392
+ const numeric = Number(text);
393
+ osc = Number.isFinite(numeric) ? numeric : null;
394
+ }
395
+ if (osc === null) {
396
+ console.log(`Invalid value for ${address}`);
397
+ return;
398
+ }
399
+ try {
400
+ service.setParameter(address, osc);
401
+ } catch (err) {
402
+ console.log(err instanceof Error ? err.message : String(err));
403
+ }
404
+ };
63
405
  const bootstrap = async () => {
64
406
  loadEnv();
65
- const { PORT, HOST } = parseArgs(process.argv);
407
+ let parsed;
408
+ try {
409
+ parsed = parseArgs(process.argv);
410
+ } catch (err) {
411
+ const message = err instanceof Error ? err.message : String(err);
412
+ console.error(message);
413
+ process.exit(1);
414
+ return;
415
+ }
416
+ const { PORT, HOST, storageType, stateFilePath, name, model, firmware, advertiseIp, logLevel, permissive, meterMode } = parsed;
66
417
  const logger = require_SchemaRegistry.ConsoleLogger.getInstance();
67
- logger.setLevel(require_SchemaRegistry.LogLevel.DEBUG);
418
+ logger.setLevel(logLevel);
68
419
  const schemaRegistry = new require_SchemaRegistry.SchemaRegistry(new require_SchemaRegistry.SchemaFactory());
69
- const service = new require_SchemaRegistry.SimulationService(new require_SchemaRegistry.UdpNetworkGateway(logger, new require_SchemaRegistry.OscCodec(schemaRegistry)), logger, new require_SchemaRegistry.InMemoryStateRepository(logger, schemaRegistry), schemaRegistry, PORT, HOST);
420
+ const service = new require_SchemaRegistry.SimulationService(new require_SchemaRegistry.UdpNetworkGateway(logger, new require_SchemaRegistry.OscCodec(schemaRegistry)), logger, createStateRepository({
421
+ type: storageType,
422
+ filePath: stateFilePath,
423
+ autoSaveInterval: 5e3
424
+ }), schemaRegistry, PORT, HOST, name, model, meterConfig(permissive, meterMode), firmware, advertiseIp);
70
425
  try {
71
426
  await service.start();
427
+ const storageInfo = storageType === "json" ? `JSON (${stateFilePath})` : "In-Memory";
72
428
  console.log(`
73
429
  ╔════════════════════════════════════════╗
74
430
  ║ 🚀 X32 SIMULATION SERVER ACTIVE ║
@@ -76,10 +432,20 @@ const bootstrap = async () => {
76
432
  • IP: ${HOST}
77
433
  • Port: ${PORT}
78
434
  • Protocol: UDP (Strict X32 Schema)
79
- • Logging: ENHANCED (DEBUG)
435
+ • Storage: ${storageInfo}
436
+ • Logging: ${[
437
+ "debug",
438
+ "info",
439
+ "warn",
440
+ "error",
441
+ "none"
442
+ ][logLevel]}
80
443
 
81
444
  👉 Type "exit" or "stop" to shut down.
82
445
  👉 Type "reset" to reset faders to default.
446
+ 👉 Type "set <address> <text>" to move a control, for example set /ch/01/mix/fader -10.
447
+ 👉 Type "get <address>" to print a control.
448
+ 👉 Type "save" to force save state (JSON mode).
83
449
  `);
84
450
  } catch (err) {
85
451
  if (err.code === "EADDRNOTAVAIL") {
@@ -108,23 +474,29 @@ const bootstrap = async () => {
108
474
  input: process.stdin,
109
475
  output: process.stdout
110
476
  }).on("line", async (input) => {
111
- const command = input.trim().toLowerCase();
112
- switch (command) {
113
- case "exit":
114
- case "stop":
115
- case "quit":
116
- console.log("Shutting down...");
117
- await service.stop();
118
- process.exit(0);
119
- break;
120
- case "reset":
121
- service.resetState();
122
- console.log("✨ Console state reset to defaults.");
123
- break;
124
- default:
125
- if (command) console.log(`Unknown command: "${command}"`);
126
- break;
477
+ const line = input.trim();
478
+ const word = (line.split(/\s+/, 1)[0] ?? "").toLowerCase();
479
+ if (word === "exit" || word === "stop" || word === "quit") {
480
+ console.log("Shutting down...");
481
+ await service.stop();
482
+ process.exit(0);
483
+ return;
484
+ }
485
+ if (word === "reset") {
486
+ service.resetState();
487
+ console.log("✨ Console state reset to defaults.");
488
+ return;
489
+ }
490
+ if (word === "save") {
491
+ await service.saveState();
492
+ console.log("💾 State saved to storage.");
493
+ return;
494
+ }
495
+ if (word === "set" || word === "get") {
496
+ runParamCommand(word, line, schemaRegistry, service);
497
+ return;
127
498
  }
499
+ if (line) console.log(`Unknown command: "${line}"`);
128
500
  });
129
501
  process.on("SIGINT", async () => {
130
502
  console.log("\n(SIGINT received)");