-
Notifications
You must be signed in to change notification settings - Fork 2
/
rx-paired.mjs
executable file
·282 lines (255 loc) · 8.33 KB
/
rx-paired.mjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
#!/usr/bin/env node
import path from "path";
import { fileURLToPath } from "url";
import {
DEFAULT_INSPECTOR_PORT,
DEFAULT_DEVICE_PORT,
DEFAULT_HISTORY_SIZE,
DEFAULT_MAX_TOKEN_DURATION,
DEFAULT_MAX_LOG_LENGTH,
DEFAULT_WRONG_PASSWORD_LIMIT,
DEFAULT_DEVICE_CONNECTION_LIMIT,
DEFAULT_INSPECTOR_CONNECTION_LIMIT,
DEFAULT_DEVICE_MESSAGE_LIMIT,
DEFAULT_INSPECTOR_MESSAGE_LIMIT,
DEFAULT_LOG_FILE_PATH,
} from "./server/build/constants.js";
import RxPairedServer from "./server/build/main.js";
import buildClient from "./client/build.mjs";
import buildInspector from "./inspector/build.mjs";
import startStaticHttpServer from "./utils/static_http_server.mjs";
const DEFAULT_STATIC_SERVER_PORT = 8695;
const currentDirName = getCurrentDirectoryName();
const { argv } = process;
if (argv.includes("-h") || argv.includes("--help")) {
displayHelp();
process.exit(0);
}
let password = null;
let noInspector = false;
let inspectorPort;
let httpPort;
let devicePort;
for (let i = 2; i < argv.length; i++) {
const arg = argv[i].trim();
switch (arg) {
case "--device-port":
i++;
devicePort = checkIntArg(arg, argv[i]);
break;
case "--inspector-port":
i++;
inspectorPort = checkIntArg(arg, argv[i]);
break;
case "--http-port":
i++;
httpPort = checkIntArg(arg, argv[i]);
break;
case "--no-inspector":
noInspector = true;
break;
case "--password":
i++;
if (argv[i] === undefined) {
console.error(`Missing password argument for "--password" option.`);
process.exit(1);
} else if (!/^[A-Za-z0-9]+$/.test(argv[i])) {
console.error(
`Invalid password argument for "--password" option. ` +
`Must be only alphanumeric characters, got "${argv[i]}"`,
);
process.exit(1);
}
password = argv[i];
break;
default:
console.error(`Unknown option: "${arg}"`);
process.exit(1);
}
}
startRxPaired({ password, devicePort, inspectorPort, noInspector, httpPort });
export default function startRxPaired({
password,
httpPort,
devicePort,
inspectorPort,
noInspector,
} = {}) {
const noPassword = typeof password !== "string" || password.length === 0;
const serverOpts = {
inspectorPort: noInspector ? -1 : (inspectorPort ?? DEFAULT_INSPECTOR_PORT),
devicePort: devicePort ?? DEFAULT_DEVICE_PORT,
shouldCreateLogFiles: true,
password: noPassword ? null : password,
historySize: DEFAULT_HISTORY_SIZE,
maxTokenDuration: DEFAULT_MAX_TOKEN_DURATION,
maxLogLength: DEFAULT_MAX_LOG_LENGTH,
wrongPasswordLimit: DEFAULT_WRONG_PASSWORD_LIMIT,
inspectorConnectionLimit: DEFAULT_INSPECTOR_CONNECTION_LIMIT,
deviceConnectionLimit: DEFAULT_DEVICE_CONNECTION_LIMIT,
deviceMessageLimit: DEFAULT_DEVICE_MESSAGE_LIMIT,
inspectorMessageLimit: DEFAULT_INSPECTOR_MESSAGE_LIMIT,
persistentTokensFile: null,
logFile: DEFAULT_LOG_FILE_PATH,
disableNoToken: false,
};
const staticServerPort = httpPort ?? DEFAULT_STATIC_SERVER_PORT;
const deviceDebuggerUrl = `ws://127.0.0.1:${serverOpts.devicePort}`;
const deviceScriptUrl = `http://127.0.0.1:${staticServerPort}/client.js`;
const inspectorDebuggerUrl = `ws://127.0.0.1:${serverOpts.inspectorPort}`;
let tokenValue = null;
if (noInspector) {
if (password !== null) {
tokenValue = `!notoken/${password}`;
} else {
tokenValue = "!notoken";
}
}
console.log("Starting RxPaired...");
Promise.race([
RxPairedServer(serverOpts).catch((err) => {
console.error(
`\x1b[31m[${getHumanReadableHours()}]\x1b[0m Server build failed:`,
err,
);
process.exit(1);
}),
noInspector
? Promise.resolve()
: buildInspector({
minify: true,
watch: false,
plugins: [],
deviceScriptUrl,
inspectorDebuggerUrl,
noPassword,
}).catch((err) => {
console.error(
`\x1b[31m[${getHumanReadableHours()}]\x1b[0m Inspector build failed:`,
err,
);
process.exit(1);
}),
buildClient({
minify: true,
watch: false,
plugins: [],
deviceDebuggerUrl,
tokenValue,
}).catch((err) => {
console.error(
`\x1b[31m[${getHumanReadableHours()}]\x1b[0m Client build failed:`,
err,
);
process.exit(1);
}),
])
.then(() => {
if (staticServerPort <= 0) {
return;
}
const servedFiles = {
"index.html": {
path: path.join(currentDirName, "inspector", "index.html"),
contentType: "text/html; charset=UTF-8",
},
// Yes, an empty string is actually a valid key!
"": {
path: path.join(currentDirName, "inspector", "index.html"),
contentType: "text/html; charset=UTF-8",
},
"inspector.js": {
path: path.join(currentDirName, "inspector", "inspector.js"),
contentType: "application/javascript; charset=UTF-8",
},
"client.js": {
path: path.join(currentDirName, "client", "client.js"),
contentType: "application/javascript; charset=UTF-8",
},
};
return startStaticHttpServer(servedFiles, staticServerPort, true);
})
.then(() => {
console.log("");
console.log("RxPaired started with success!");
const clientPath = path.join(currentDirName, "client/client.js");
if (staticServerPort > 0) {
if (noInspector) {
console.log(
`You may load the client script at http://127.0.0.1:${staticServerPort}/client.js or find it in \`${clientPath}\`.`,
);
} else {
console.log(
`To start the inspector, go to http://127.0.0.1:${staticServerPort}/`,
);
}
} else {
if (!noInspector) {
const inspectorPath = path.join(
currentDirName,
"inspector/index.html",
);
console.log(
`An inspector build has been generated in \`${inspectorPath}\` and a client script in \`${clientPath}\``,
);
} else {
console.log(
`A client script has been generated in \`${clientPath}\`, you can now run that script in your device.`,
);
}
}
});
}
/**
* Returns the path to the directory where the current script is found.
* @returns {String}
*/
function getCurrentDirectoryName() {
return path.dirname(fileURLToPath(import.meta.url));
}
/**
* Display through `console.log` an helping message relative to how to run this
* script.
*/
function displayHelp() {
console.log(
/* eslint-disable indent */
`Usage: rx-paired [options]
Options:
-h, --help Display this help
--password <alphanumeric> Optional password used by the server.
Ignore for no password.
--http-port <port> Port used to deliver the inspector HTTP page and the
device's script.
Defaults to ${DEFAULT_STATIC_SERVER_PORT}.
You may set it to "-1" to disable the static server.
--device-port <port> Port used for device-to-server communication.
Defaults to ${DEFAULT_DEVICE_PORT}.
--inspector-port <port> Port used for inspector-to-server communication.
Defaults to ${DEFAULT_INSPECTOR_PORT}.
--no-inspector If this option is present, we won't build and serve the
inspector page nor rely on it for "token" creation.
In effect, RxPaired will mostly act as a log server and
create local files as new clients connect to it.`,
/* eslint-enable indent */
);
}
function checkIntArg(arg, val) {
const toInt = val === undefined ? NaN : Number(val);
if (isNaN(toInt)) {
if (val === undefined || val.startsWith("-")) {
console.error(`Missing argument for "${arg}" option.`);
} else {
console.error(
`Invalid "${arg}" argument. Expected a number, ` + `ot "${val}".`,
);
}
process.exit(1);
} else if (toInt % 1 !== 0) {
console.error(
`Invalid "${arg}" argument. Expected an integer, ` + `got "${val}".`,
);
process.exit(1);
}
return toInt;
}