overlays-server 0.0.0-stage → 0.1.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.
- package/LICENSE +661 -0
- package/README-tr.md +292 -0
- package/README.md +295 -2
- package/config.example.json +40 -0
- package/dist/app.d.ts +19 -0
- package/dist/app.js +127 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +176 -0
- package/dist/config.d.ts +62 -0
- package/dist/config.js +115 -0
- package/dist/core/driver.d.ts +56 -0
- package/dist/core/driver.js +5 -0
- package/dist/core/hub.d.ts +100 -0
- package/dist/core/hub.js +280 -0
- package/dist/core/last-position.d.ts +23 -0
- package/dist/core/last-position.js +67 -0
- package/dist/core/protocol.d.ts +56 -0
- package/dist/core/protocol.js +27 -0
- package/dist/core/registry.d.ts +9 -0
- package/dist/core/registry.js +29 -0
- package/dist/core/types.d.ts +83 -0
- package/dist/core/types.js +2 -0
- package/dist/drivers/ddpai/http-api.d.ts +30 -0
- package/dist/drivers/ddpai/http-api.js +84 -0
- package/dist/drivers/ddpai/index.d.ts +20 -0
- package/dist/drivers/ddpai/index.js +107 -0
- package/dist/drivers/ddpai/messages.d.ts +29 -0
- package/dist/drivers/ddpai/messages.js +76 -0
- package/dist/drivers/index.d.ts +6 -0
- package/dist/drivers/index.js +8 -0
- package/dist/drivers/simulator.d.ts +13 -0
- package/dist/drivers/simulator.js +64 -0
- package/dist/index.d.ts +26 -0
- package/dist/index.js +26 -0
- package/dist/lib/delimited.d.ts +21 -0
- package/dist/lib/delimited.js +51 -0
- package/dist/lib/log.d.ts +27 -0
- package/dist/lib/log.js +80 -0
- package/dist/lib/nmea.d.ts +57 -0
- package/dist/lib/nmea.js +141 -0
- package/dist/lib/options.d.ts +29 -0
- package/dist/lib/options.js +85 -0
- package/dist/lib/reconnecting-tcp.d.ts +35 -0
- package/dist/lib/reconnecting-tcp.js +91 -0
- package/dist/lib/redact.d.ts +10 -0
- package/dist/lib/redact.js +30 -0
- package/dist/tools/probe.d.ts +37 -0
- package/dist/tools/probe.js +208 -0
- package/dist/transports/diagnostics.d.ts +65 -0
- package/dist/transports/diagnostics.js +49 -0
- package/dist/transports/feed.d.ts +22 -0
- package/dist/transports/feed.js +78 -0
- package/dist/transports/http-server.d.ts +39 -0
- package/dist/transports/http-server.js +196 -0
- package/dist/transports/security.d.ts +15 -0
- package/dist/transports/security.js +78 -0
- package/dist/transports/status-page.d.ts +7 -0
- package/dist/transports/status-page.js +204 -0
- package/dist/version.d.ts +2 -0
- package/dist/version.js +4 -0
- package/docs/architecture.md +85 -0
- package/docs/data.md +87 -0
- package/docs/devices/README.md +29 -0
- package/docs/devices/ddpai.md +99 -0
- package/docs/drivers.md +130 -0
- package/docs/new-device.md +94 -0
- package/docs/protocol.md +160 -0
- package/docs/remote.md +126 -0
- package/docs/testing-locally.md +150 -0
- package/docs/windows-network.md +58 -0
- package/package.json +72 -4
package/dist/app.js
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import { Hub } from './core/hub.js';
|
|
3
|
+
import { LastPositionStore } from './core/last-position.js';
|
|
4
|
+
import { DriverRegistry } from './core/registry.js';
|
|
5
|
+
import { BUILTIN_DRIVERS } from './drivers/index.js';
|
|
6
|
+
import { createLogger, errorMessage, LogBuffer, recordingLogger } from './lib/log.js';
|
|
7
|
+
import { ConfigError, OptionReader } from './lib/options.js';
|
|
8
|
+
import { createHttpServer } from './transports/http-server.js';
|
|
9
|
+
import { isLoopbackHost } from './transports/security.js';
|
|
10
|
+
/** Builds every enabled source, starts the HTTP/WebSocket server, then starts the sources. */
|
|
11
|
+
export async function startServer(options) {
|
|
12
|
+
const { config } = options;
|
|
13
|
+
const logBuffer = new LogBuffer(500);
|
|
14
|
+
const log = recordingLogger(options.log ?? createLogger(config.logLevel), logBuffer);
|
|
15
|
+
const registry = new DriverRegistry(options.drivers ?? BUILTIN_DRIVERS);
|
|
16
|
+
const hub = new Hub({ staleAfterMs: config.staleAfterMs, gpsPriority: config.gpsPriority, log });
|
|
17
|
+
// Validate everything before opening a port.
|
|
18
|
+
const plans = config.sources
|
|
19
|
+
.filter((s) => s.enabled)
|
|
20
|
+
.map((s) => {
|
|
21
|
+
const driver = registry.get(s.driver);
|
|
22
|
+
const reader = new OptionReader(s.options, `sources.${s.id}.options`);
|
|
23
|
+
const parsed = driver.parseOptions(reader);
|
|
24
|
+
for (const key of reader.unknownKeys())
|
|
25
|
+
log.warn(`sources.${s.id}.options: unknown key "${key}" ignored`);
|
|
26
|
+
return { config: s, driver, options: parsed };
|
|
27
|
+
});
|
|
28
|
+
if (plans.length === 0)
|
|
29
|
+
log.warn('no enabled sources in the config');
|
|
30
|
+
const running = plans.map((plan) => {
|
|
31
|
+
const ctx = hub.register({ id: plan.config.id, driver: plan.driver.id, driverName: plan.driver.name, capabilities: plan.driver.capabilities }, log.child(plan.config.id));
|
|
32
|
+
return { id: plan.config.id, ctx, source: plan.driver.create(ctx, plan.options) };
|
|
33
|
+
});
|
|
34
|
+
// Last positions from the previous run, then keep the file current.
|
|
35
|
+
const positions = config.rememberLastPosition ? new LastPositionStore(config.stateFile, log.child('state')) : undefined;
|
|
36
|
+
if (positions) {
|
|
37
|
+
const remembered = positions.load();
|
|
38
|
+
for (const r of running) {
|
|
39
|
+
const p = remembered[r.id];
|
|
40
|
+
if (p)
|
|
41
|
+
hub.seedLastFix(r.id, p.fix, p.savedAt);
|
|
42
|
+
}
|
|
43
|
+
const seeded = running.filter((r) => remembered[r.id]).length;
|
|
44
|
+
if (seeded)
|
|
45
|
+
log.info(`last known position restored for ${seeded} source(s)`);
|
|
46
|
+
hub.subscribe((e) => {
|
|
47
|
+
if (e.kind === 'fix')
|
|
48
|
+
positions.update(e.source, e.fix);
|
|
49
|
+
});
|
|
50
|
+
positions.start();
|
|
51
|
+
}
|
|
52
|
+
let tls;
|
|
53
|
+
if (config.tls) {
|
|
54
|
+
try {
|
|
55
|
+
tls = { cert: fs.readFileSync(config.tls.certFile), key: fs.readFileSync(config.tls.keyFile) };
|
|
56
|
+
}
|
|
57
|
+
catch (err) {
|
|
58
|
+
throw new ConfigError(`cannot read the TLS certificate / key: ${errorMessage(err)}`);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
if (!isLoopbackHost(config.host) && !config.token) {
|
|
62
|
+
log.warn(`listening on ${config.host} without a token: every device that can reach this port can read the live position. ` +
|
|
63
|
+
'Set "token" (and use TLS when reachable from the internet).');
|
|
64
|
+
}
|
|
65
|
+
const { server, closeClients } = createHttpServer({
|
|
66
|
+
hub,
|
|
67
|
+
host: config.host,
|
|
68
|
+
allowedOrigins: config.allowedOrigins,
|
|
69
|
+
allowedHosts: config.allowedHosts,
|
|
70
|
+
...(tls && { tls }),
|
|
71
|
+
...(config.token && { token: config.token }),
|
|
72
|
+
motionMaxHz: config.motionMaxHz,
|
|
73
|
+
log: log.child('http'),
|
|
74
|
+
diagnostics: { config, logBuffer, startedAt: Date.now() },
|
|
75
|
+
});
|
|
76
|
+
await new Promise((resolve, reject) => {
|
|
77
|
+
const onError = (err) => {
|
|
78
|
+
server.off('listening', onListening);
|
|
79
|
+
if (err.code === 'EADDRINUSE') {
|
|
80
|
+
reject(new ConfigError(`port ${config.port} is already in use (is overlays-server already running?)`));
|
|
81
|
+
}
|
|
82
|
+
else if (err.code === 'EACCES') {
|
|
83
|
+
reject(new ConfigError(`no permission to listen on ${config.host}:${config.port}`));
|
|
84
|
+
}
|
|
85
|
+
else {
|
|
86
|
+
reject(err);
|
|
87
|
+
}
|
|
88
|
+
};
|
|
89
|
+
const onListening = () => {
|
|
90
|
+
server.off('error', onError);
|
|
91
|
+
resolve();
|
|
92
|
+
};
|
|
93
|
+
server.once('error', onError);
|
|
94
|
+
server.once('listening', onListening);
|
|
95
|
+
server.listen(config.port, config.host);
|
|
96
|
+
});
|
|
97
|
+
const port = server.address().port;
|
|
98
|
+
const hostForUrl = config.host.includes(':') ? `[${config.host}]` : config.host;
|
|
99
|
+
hub.start();
|
|
100
|
+
for (const r of running) {
|
|
101
|
+
try {
|
|
102
|
+
await r.source.start();
|
|
103
|
+
}
|
|
104
|
+
catch (err) {
|
|
105
|
+
log.error(`${r.id}: failed to start: ${errorMessage(err)}`);
|
|
106
|
+
r.ctx.setLink('offline', `failed to start: ${errorMessage(err)}`);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
let closing;
|
|
110
|
+
const close = () => (closing ??= (async () => {
|
|
111
|
+
for (const r of running) {
|
|
112
|
+
try {
|
|
113
|
+
await r.source.stop();
|
|
114
|
+
}
|
|
115
|
+
catch (err) {
|
|
116
|
+
log.warn(`${r.id}: stop failed: ${errorMessage(err)}`);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
hub.stop();
|
|
120
|
+
positions?.stop();
|
|
121
|
+
closeClients();
|
|
122
|
+
await new Promise((resolve) => server.close(() => resolve()));
|
|
123
|
+
server.closeAllConnections();
|
|
124
|
+
})());
|
|
125
|
+
return { url: `${tls ? 'https' : 'http'}://${hostForUrl}:${port}`, port, hub, close };
|
|
126
|
+
}
|
|
127
|
+
//# sourceMappingURL=app.js.map
|
package/dist/cli.d.ts
ADDED
package/dist/cli.js
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { parseArgs } from 'node:util';
|
|
3
|
+
import { startServer } from './app.js';
|
|
4
|
+
import { findConfigFile, parseConfig, readConfigFile, userConfigPath } from './config.js';
|
|
5
|
+
import { BUILTIN_DRIVERS } from './drivers/index.js';
|
|
6
|
+
import { createLogger, errorMessage, LOG_LEVELS } from './lib/log.js';
|
|
7
|
+
import { ConfigError } from './lib/options.js';
|
|
8
|
+
import { runProbe } from './tools/probe.js';
|
|
9
|
+
import { REPO_URL, VERSION } from './version.js';
|
|
10
|
+
const HELP = `overlays-server ${VERSION}
|
|
11
|
+
Local telemetry bridge for stream overlays (live dashcam GPS -> browser source).
|
|
12
|
+
|
|
13
|
+
Usage: overlays-server [options]
|
|
14
|
+
|
|
15
|
+
Options:
|
|
16
|
+
-c, --config <file> Config file (JSON). Default search: $OVERLAYS_SERVER_CONFIG,
|
|
17
|
+
./overlays-server.config.json, ${userConfigPath()}
|
|
18
|
+
-p, --port <port> Port to listen on (default 3456)
|
|
19
|
+
--host <address> Interface to listen on (default 127.0.0.1)
|
|
20
|
+
--origin <origin> Extra allowed web origin (repeatable), e.g. https://example.com
|
|
21
|
+
--token <secret> Require ?token=<secret> from clients
|
|
22
|
+
--allowed-host <name> Extra Host name behind a reverse proxy (repeatable), e.g. pi.tailnet.ts.net
|
|
23
|
+
--tls-cert <file> Serve HTTPS/WSS with this PEM certificate (needs --tls-key)
|
|
24
|
+
--tls-key <file> PEM private key for --tls-cert
|
|
25
|
+
--ddpai-host <ip> DDPAI camera address (default 193.168.0.1)
|
|
26
|
+
--ddpai-http-port <port> DDPAI HTTP API port (default 80)
|
|
27
|
+
--simulate Use the built-in simulator instead of the configured sources
|
|
28
|
+
--log-level <level> ${LOG_LEVELS.join(' | ')} (default info)
|
|
29
|
+
--print-config Print the effective config and exit
|
|
30
|
+
--list-drivers List available drivers and exit
|
|
31
|
+
--probe <host> Inspect a device (ports, model, data samples) and print a report
|
|
32
|
+
for a GitHub issue, then exit. Personal data is masked.
|
|
33
|
+
--probe-ports <list> Ports for --probe, comma separated (default: common camera ports)
|
|
34
|
+
-v, --version Print the version
|
|
35
|
+
-h, --help Show this help
|
|
36
|
+
|
|
37
|
+
Environment: OVERLAYS_SERVER_PORT, OVERLAYS_SERVER_HOST, OVERLAYS_SERVER_LOG_LEVEL, OVERLAYS_SERVER_CONFIG.
|
|
38
|
+
Docs: ${REPO_URL}
|
|
39
|
+
`;
|
|
40
|
+
function parseCli() {
|
|
41
|
+
// `pnpm start -- --flag` passes the `--` through.
|
|
42
|
+
const args = process.argv.slice(2);
|
|
43
|
+
if (args[0] === '--')
|
|
44
|
+
args.shift();
|
|
45
|
+
return parseArgs({
|
|
46
|
+
args,
|
|
47
|
+
allowPositionals: false,
|
|
48
|
+
options: {
|
|
49
|
+
config: { type: 'string', short: 'c' },
|
|
50
|
+
port: { type: 'string', short: 'p' },
|
|
51
|
+
host: { type: 'string' },
|
|
52
|
+
origin: { type: 'string', multiple: true },
|
|
53
|
+
token: { type: 'string' },
|
|
54
|
+
'allowed-host': { type: 'string', multiple: true },
|
|
55
|
+
'tls-cert': { type: 'string' },
|
|
56
|
+
'tls-key': { type: 'string' },
|
|
57
|
+
'ddpai-host': { type: 'string' },
|
|
58
|
+
'ddpai-http-port': { type: 'string' },
|
|
59
|
+
simulate: { type: 'boolean' },
|
|
60
|
+
'log-level': { type: 'string' },
|
|
61
|
+
'print-config': { type: 'boolean' },
|
|
62
|
+
'list-drivers': { type: 'boolean' },
|
|
63
|
+
probe: { type: 'string' },
|
|
64
|
+
'probe-ports': { type: 'string' },
|
|
65
|
+
version: { type: 'boolean', short: 'v' },
|
|
66
|
+
help: { type: 'boolean', short: 'h' },
|
|
67
|
+
},
|
|
68
|
+
}).values;
|
|
69
|
+
}
|
|
70
|
+
/** Config file, then environment, then command line flags (later wins). */
|
|
71
|
+
function buildConfig(args, warn) {
|
|
72
|
+
const file = findConfigFile(args.config ?? undefined);
|
|
73
|
+
const raw = (file ? readConfigFile(file) : {});
|
|
74
|
+
const env = process.env;
|
|
75
|
+
const overrides = {
|
|
76
|
+
...(env.OVERLAYS_SERVER_PORT && { port: env.OVERLAYS_SERVER_PORT }),
|
|
77
|
+
...(env.OVERLAYS_SERVER_HOST && { host: env.OVERLAYS_SERVER_HOST }),
|
|
78
|
+
...(env.OVERLAYS_SERVER_LOG_LEVEL && { logLevel: env.OVERLAYS_SERVER_LOG_LEVEL }),
|
|
79
|
+
...(args.port && { port: args.port }),
|
|
80
|
+
...(args.host && { host: args.host }),
|
|
81
|
+
...(args.token && { token: args.token }),
|
|
82
|
+
...((args['tls-cert'] || args['tls-key']) && { tls: { certFile: args['tls-cert'], keyFile: args['tls-key'] } }),
|
|
83
|
+
...(args['log-level'] && { logLevel: args['log-level'] }),
|
|
84
|
+
};
|
|
85
|
+
const config = parseConfig({ ...raw, ...overrides }, warn);
|
|
86
|
+
if (args.origin?.length)
|
|
87
|
+
config.allowedOrigins = [...config.allowedOrigins, ...args.origin];
|
|
88
|
+
if (args['allowed-host']?.length)
|
|
89
|
+
config.allowedHosts = [...config.allowedHosts, ...args['allowed-host'].map((h) => h.toLowerCase())];
|
|
90
|
+
if (args.simulate) {
|
|
91
|
+
config.sources = [{ id: 'simulator', driver: 'simulator', enabled: true, options: {} }];
|
|
92
|
+
}
|
|
93
|
+
if (args['ddpai-host'] || args['ddpai-http-port']) {
|
|
94
|
+
const ddpai = config.sources.filter((s) => s.driver === 'ddpai');
|
|
95
|
+
if (ddpai.length === 0)
|
|
96
|
+
throw new ConfigError('--ddpai-host / --ddpai-http-port given but no ddpai source is configured');
|
|
97
|
+
for (const s of ddpai) {
|
|
98
|
+
s.options = {
|
|
99
|
+
...s.options,
|
|
100
|
+
...(args['ddpai-host'] && { host: args['ddpai-host'] }),
|
|
101
|
+
...(args['ddpai-http-port'] && { httpPort: args['ddpai-http-port'] }),
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
return { config, file };
|
|
106
|
+
}
|
|
107
|
+
async function main() {
|
|
108
|
+
let args;
|
|
109
|
+
try {
|
|
110
|
+
args = parseCli();
|
|
111
|
+
}
|
|
112
|
+
catch (err) {
|
|
113
|
+
console.error(`${errorMessage(err)}\n\n${HELP}`);
|
|
114
|
+
return 2;
|
|
115
|
+
}
|
|
116
|
+
if (args.help) {
|
|
117
|
+
console.log(HELP);
|
|
118
|
+
return 0;
|
|
119
|
+
}
|
|
120
|
+
if (args.version) {
|
|
121
|
+
console.log(VERSION);
|
|
122
|
+
return 0;
|
|
123
|
+
}
|
|
124
|
+
if (args.probe) {
|
|
125
|
+
const ports = args['probe-ports']?.split(',').map((p) => Number(p.trim()));
|
|
126
|
+
if (ports && ports.some((p) => !Number.isInteger(p) || p < 1 || p > 65535)) {
|
|
127
|
+
throw new ConfigError('--probe-ports: comma separated port numbers, e.g. 80,554,6100');
|
|
128
|
+
}
|
|
129
|
+
return runProbe(args.probe, ports ? { ports } : {});
|
|
130
|
+
}
|
|
131
|
+
if (args['list-drivers']) {
|
|
132
|
+
for (const d of BUILTIN_DRIVERS)
|
|
133
|
+
console.log(`${d.id.padEnd(12)} ${d.name} — ${d.description}`);
|
|
134
|
+
return 0;
|
|
135
|
+
}
|
|
136
|
+
const warnings = [];
|
|
137
|
+
const { config, file } = buildConfig(args, (m) => warnings.push(m));
|
|
138
|
+
if (args['print-config']) {
|
|
139
|
+
console.log(JSON.stringify({ ...config, ...(config.token && { token: '***' }) }, null, 2));
|
|
140
|
+
return 0;
|
|
141
|
+
}
|
|
142
|
+
const log = createLogger(config.logLevel);
|
|
143
|
+
for (const w of warnings)
|
|
144
|
+
log.warn(w);
|
|
145
|
+
log.info(`overlays-server ${VERSION} (node ${process.version})`);
|
|
146
|
+
log.info(file ? `config: ${file}` : 'config: defaults (no config file found)');
|
|
147
|
+
const server = await startServer({ config, log });
|
|
148
|
+
log.info(`status page: ${server.url}/`);
|
|
149
|
+
log.info(`overlay feed: ${server.url.replace(/^http/, 'ws')}/v1/ws`);
|
|
150
|
+
let stopping = false;
|
|
151
|
+
const shutdown = (signal) => {
|
|
152
|
+
if (stopping)
|
|
153
|
+
process.exit(1);
|
|
154
|
+
stopping = true;
|
|
155
|
+
log.info(`${signal}: shutting down`);
|
|
156
|
+
const force = setTimeout(() => process.exit(1), 3000);
|
|
157
|
+
force.unref();
|
|
158
|
+
void server.close().then(() => process.exit(0));
|
|
159
|
+
};
|
|
160
|
+
process.on('SIGINT', () => shutdown('SIGINT'));
|
|
161
|
+
process.on('SIGTERM', () => shutdown('SIGTERM'));
|
|
162
|
+
return -1; // keep running
|
|
163
|
+
}
|
|
164
|
+
main().then((code) => {
|
|
165
|
+
if (code >= 0)
|
|
166
|
+
process.exitCode = code;
|
|
167
|
+
}, (err) => {
|
|
168
|
+
if (err instanceof ConfigError) {
|
|
169
|
+
console.error(`error: ${err.message}`);
|
|
170
|
+
}
|
|
171
|
+
else {
|
|
172
|
+
console.error(err);
|
|
173
|
+
}
|
|
174
|
+
process.exitCode = 1;
|
|
175
|
+
});
|
|
176
|
+
//# sourceMappingURL=cli.js.map
|
package/dist/config.d.ts
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { type LogLevel } from './lib/log.ts';
|
|
2
|
+
export interface SourceConfig {
|
|
3
|
+
/** Unique name of this source; clients can subscribe to it (`?source=<id>`). */
|
|
4
|
+
id: string;
|
|
5
|
+
/** Driver id (`ddpai`, `simulator`, ...). */
|
|
6
|
+
driver: string;
|
|
7
|
+
enabled: boolean;
|
|
8
|
+
/** Driver specific options, validated by the driver. */
|
|
9
|
+
options: Record<string, unknown>;
|
|
10
|
+
}
|
|
11
|
+
export interface AppConfig {
|
|
12
|
+
/** Interface to listen on. Keep 127.0.0.1 unless the overlay runs on another device. */
|
|
13
|
+
host: string;
|
|
14
|
+
port: number;
|
|
15
|
+
/**
|
|
16
|
+
* Web pages allowed to read the data. `https://site` exact, `http://localhost:*` any port, `*` anyone.
|
|
17
|
+
* Without this any website open in a browser on this PC could read the live location.
|
|
18
|
+
*/
|
|
19
|
+
allowedOrigins: string[];
|
|
20
|
+
/** Optional shared secret: clients must send `?token=` (or `Authorization: Bearer`). */
|
|
21
|
+
token?: string;
|
|
22
|
+
/**
|
|
23
|
+
* Extra Host names accepted while listening on loopback (DNS rebinding guard), for a reverse proxy in front of the
|
|
24
|
+
* server: Tailscale Serve (`pi.tailnet-name.ts.net`), Caddy, Nginx. Not needed when listening on a LAN/VPN address.
|
|
25
|
+
*/
|
|
26
|
+
allowedHosts: string[];
|
|
27
|
+
/** Serve HTTPS / WSS directly (PEM files), e.g. a `tailscale cert` or Let's Encrypt certificate. */
|
|
28
|
+
tls?: {
|
|
29
|
+
certFile: string;
|
|
30
|
+
keyFile: string;
|
|
31
|
+
};
|
|
32
|
+
/** A GPS source that goes quiet this long is reported `stale`. */
|
|
33
|
+
staleAfterMs: number;
|
|
34
|
+
/** Source ids in preference order for the default GPS stream. */
|
|
35
|
+
gpsPriority: string[];
|
|
36
|
+
/** Upper bound for motion messages per client per second. */
|
|
37
|
+
motionMaxHz: number;
|
|
38
|
+
logLevel: LogLevel;
|
|
39
|
+
/**
|
|
40
|
+
* Keep each source's last position on disk so it survives restarts while GPS is lost (tunnels).
|
|
41
|
+
* Stored in `stateFile` (default: next to the per-user config).
|
|
42
|
+
*/
|
|
43
|
+
rememberLastPosition: boolean;
|
|
44
|
+
stateFile: string;
|
|
45
|
+
sources: SourceConfig[];
|
|
46
|
+
}
|
|
47
|
+
export declare const DEFAULT_PORT = 3456;
|
|
48
|
+
export declare const DEFAULT_ALLOWED_ORIGINS: string[];
|
|
49
|
+
export declare const DEFAULT_SOURCES: SourceConfig[];
|
|
50
|
+
/** Validates a parsed config file (any missing key takes its default). */
|
|
51
|
+
export declare function parseConfig(raw: unknown, onWarning?: (message: string) => void): AppConfig;
|
|
52
|
+
/** Per-user config file location (`%APPDATA%\overlays-server\config.json`, `~/.config/overlays-server/config.json`). */
|
|
53
|
+
export declare function userConfigPath(): string;
|
|
54
|
+
/** Per-user file for the remembered last positions. */
|
|
55
|
+
export declare function userStatePath(): string;
|
|
56
|
+
/**
|
|
57
|
+
* Where to read the config from: an explicit path, `$OVERLAYS_SERVER_CONFIG`,
|
|
58
|
+
* `overlays-server.config.json` in the working directory, then the per-user file.
|
|
59
|
+
* Returns `undefined` when none exists (defaults are used).
|
|
60
|
+
*/
|
|
61
|
+
export declare function findConfigFile(explicit?: string): string | undefined;
|
|
62
|
+
export declare function readConfigFile(file: string): unknown;
|
package/dist/config.js
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { LOG_LEVELS } from './lib/log.js';
|
|
5
|
+
import { ConfigError, OptionReader } from './lib/options.js';
|
|
6
|
+
export const DEFAULT_PORT = 3456;
|
|
7
|
+
export const DEFAULT_ALLOWED_ORIGINS = [
|
|
8
|
+
'https://overlays.ramazansancar.com.tr',
|
|
9
|
+
'http://localhost:*',
|
|
10
|
+
'http://127.0.0.1:*',
|
|
11
|
+
];
|
|
12
|
+
export const DEFAULT_SOURCES = [{ id: 'ddpai', driver: 'ddpai', enabled: true, options: {} }];
|
|
13
|
+
const SOURCE_ID = /^[A-Za-z0-9][A-Za-z0-9_-]{0,39}$/;
|
|
14
|
+
/** Validates a parsed config file (any missing key takes its default). */
|
|
15
|
+
export function parseConfig(raw, onWarning = () => { }) {
|
|
16
|
+
const o = new OptionReader(raw, 'config');
|
|
17
|
+
o.raw('$schema');
|
|
18
|
+
const token = o.string('token');
|
|
19
|
+
const config = {
|
|
20
|
+
host: o.string('host', '127.0.0.1'),
|
|
21
|
+
port: o.port('port', DEFAULT_PORT),
|
|
22
|
+
allowedOrigins: o.stringList('allowedOrigins', DEFAULT_ALLOWED_ORIGINS),
|
|
23
|
+
...(token && { token }),
|
|
24
|
+
allowedHosts: o.stringList('allowedHosts', []).map((h) => h.trim().toLowerCase()).filter(Boolean),
|
|
25
|
+
...parseTls(o.raw('tls')),
|
|
26
|
+
staleAfterMs: o.number('staleAfterMs', 5000, { min: 500, integer: true }),
|
|
27
|
+
gpsPriority: o.stringList('gpsPriority', []),
|
|
28
|
+
motionMaxHz: o.number('motionMaxHz', 10, { min: 0, max: 100 }),
|
|
29
|
+
logLevel: o.oneOf('logLevel', LOG_LEVELS, 'info'),
|
|
30
|
+
rememberLastPosition: o.boolean('rememberLastPosition', true),
|
|
31
|
+
stateFile: o.string('stateFile', userStatePath()),
|
|
32
|
+
sources: o.has('sources') ? parseSources(o.raw('sources')) : structuredClone(DEFAULT_SOURCES),
|
|
33
|
+
};
|
|
34
|
+
for (const key of o.unknownKeys())
|
|
35
|
+
onWarning(`config: unknown key "${key}" ignored`);
|
|
36
|
+
return config;
|
|
37
|
+
}
|
|
38
|
+
function parseTls(raw) {
|
|
39
|
+
if (raw === undefined || raw === null)
|
|
40
|
+
return {};
|
|
41
|
+
const o = new OptionReader(raw, 'config.tls');
|
|
42
|
+
const certFile = o.string('certFile');
|
|
43
|
+
const keyFile = o.string('keyFile');
|
|
44
|
+
if (!certFile || !keyFile)
|
|
45
|
+
throw new ConfigError('config.tls: needs both certFile and keyFile');
|
|
46
|
+
return { tls: { certFile, keyFile } };
|
|
47
|
+
}
|
|
48
|
+
function parseSources(raw) {
|
|
49
|
+
if (!Array.isArray(raw))
|
|
50
|
+
throw new ConfigError('config.sources: must be a list');
|
|
51
|
+
const ids = new Set();
|
|
52
|
+
return raw.map((item, i) => {
|
|
53
|
+
const o = new OptionReader(item, `config.sources[${i}]`);
|
|
54
|
+
const driver = o.string('driver');
|
|
55
|
+
if (!driver)
|
|
56
|
+
throw new ConfigError(`config.sources[${i}].driver: required`);
|
|
57
|
+
const id = o.string('id', driver);
|
|
58
|
+
if (!SOURCE_ID.test(id))
|
|
59
|
+
throw new ConfigError(`config.sources[${i}].id: letters, digits, - and _ only`);
|
|
60
|
+
if (ids.has(id))
|
|
61
|
+
throw new ConfigError(`config.sources[${i}].id: "${id}" is used twice`);
|
|
62
|
+
ids.add(id);
|
|
63
|
+
const options = o.raw('options') ?? {};
|
|
64
|
+
if (typeof options !== 'object' || Array.isArray(options)) {
|
|
65
|
+
throw new ConfigError(`config.sources[${i}].options: must be an object`);
|
|
66
|
+
}
|
|
67
|
+
return { id, driver, enabled: o.boolean('enabled', true), options: options };
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
/** Per-user config file location (`%APPDATA%\overlays-server\config.json`, `~/.config/overlays-server/config.json`). */
|
|
71
|
+
export function userConfigPath() {
|
|
72
|
+
const base = process.platform === 'win32'
|
|
73
|
+
? (process.env.APPDATA ?? path.join(os.homedir(), 'AppData', 'Roaming'))
|
|
74
|
+
: (process.env.XDG_CONFIG_HOME ?? path.join(os.homedir(), '.config'));
|
|
75
|
+
return path.join(base, 'overlays-server', 'config.json');
|
|
76
|
+
}
|
|
77
|
+
/** Per-user file for the remembered last positions. */
|
|
78
|
+
export function userStatePath() {
|
|
79
|
+
return path.join(path.dirname(userConfigPath()), 'last-position.json');
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Where to read the config from: an explicit path, `$OVERLAYS_SERVER_CONFIG`,
|
|
83
|
+
* `overlays-server.config.json` in the working directory, then the per-user file.
|
|
84
|
+
* Returns `undefined` when none exists (defaults are used).
|
|
85
|
+
*/
|
|
86
|
+
export function findConfigFile(explicit) {
|
|
87
|
+
if (explicit) {
|
|
88
|
+
if (!fs.existsSync(explicit))
|
|
89
|
+
throw new ConfigError(`config file not found: ${explicit}`);
|
|
90
|
+
return path.resolve(explicit);
|
|
91
|
+
}
|
|
92
|
+
const candidates = [
|
|
93
|
+
process.env.OVERLAYS_SERVER_CONFIG,
|
|
94
|
+
path.resolve('overlays-server.config.json'),
|
|
95
|
+
userConfigPath(),
|
|
96
|
+
].filter((p) => Boolean(p));
|
|
97
|
+
return candidates.find((p) => fs.existsSync(p));
|
|
98
|
+
}
|
|
99
|
+
export function readConfigFile(file) {
|
|
100
|
+
let text;
|
|
101
|
+
try {
|
|
102
|
+
text = fs.readFileSync(file, 'utf8');
|
|
103
|
+
}
|
|
104
|
+
catch (err) {
|
|
105
|
+
throw new ConfigError(`cannot read ${file}: ${err.message}`);
|
|
106
|
+
}
|
|
107
|
+
try {
|
|
108
|
+
// Notepad saves UTF-8 with a BOM.
|
|
109
|
+
return JSON.parse(text.charCodeAt(0) === 0xfeff ? text.slice(1) : text);
|
|
110
|
+
}
|
|
111
|
+
catch (err) {
|
|
112
|
+
throw new ConfigError(`${file} is not valid JSON: ${err.message}`);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
//# sourceMappingURL=config.js.map
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import type { Logger } from '../lib/log.ts';
|
|
2
|
+
import type { OptionReader } from '../lib/options.ts';
|
|
3
|
+
import type { Capability, DeviceEvent, DeviceInfo, GpsFix, LinkState, MotionSample } from './types.ts';
|
|
4
|
+
/**
|
|
5
|
+
* What a running source gets from the server. Drivers only talk to the outside world through this,
|
|
6
|
+
* so the hub can track state, detect stale data and fan out to clients without knowing the device.
|
|
7
|
+
*/
|
|
8
|
+
export interface SourceContext {
|
|
9
|
+
/** Instance id from the config (e.g. `ddpai`, `front-cam`). */
|
|
10
|
+
readonly id: string;
|
|
11
|
+
readonly log: Logger;
|
|
12
|
+
/** Aborted when the source is stopped; pass it to fetch() / timers. */
|
|
13
|
+
readonly signal: AbortSignal;
|
|
14
|
+
setLink(state: LinkState, message?: string): void;
|
|
15
|
+
setDevice(info: DeviceInfo): void;
|
|
16
|
+
/** A valid position. */
|
|
17
|
+
publishFix(fix: GpsFix): void;
|
|
18
|
+
/** The device is talking but has no position (no satellite lock yet). */
|
|
19
|
+
publishNoFix(detail?: {
|
|
20
|
+
satellites?: number;
|
|
21
|
+
hdop?: number;
|
|
22
|
+
}): void;
|
|
23
|
+
publishMotion(sample: MotionSample): void;
|
|
24
|
+
/** Any other device message, passed to clients that asked for events. */
|
|
25
|
+
publishEvent(event: DeviceEvent): void;
|
|
26
|
+
/**
|
|
27
|
+
* Keeps a raw device message (text, as received) in a small ring buffer for the diagnostics download, so a
|
|
28
|
+
* problem can be replayed with the fake device. Cheap; call it for every message.
|
|
29
|
+
*/
|
|
30
|
+
recordRaw(frame: string): void;
|
|
31
|
+
}
|
|
32
|
+
/** A running instance of a driver. */
|
|
33
|
+
export interface Source {
|
|
34
|
+
start(): void | Promise<void>;
|
|
35
|
+
stop(): void | Promise<void>;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* A device type. To support a new camera / GPS, write one of these and add it to `src/drivers/index.ts`.
|
|
39
|
+
*
|
|
40
|
+
* `parseOptions` gets the `options` object of a config entry and turns it into typed options
|
|
41
|
+
* (throw `ConfigError` for bad values). `create` builds the source; it must not connect yet:
|
|
42
|
+
* the server calls `start()` when it is ready.
|
|
43
|
+
*/
|
|
44
|
+
export interface Driver<Options = unknown> {
|
|
45
|
+
/** Value of `driver` in the config. Lowercase, no spaces. */
|
|
46
|
+
readonly id: string;
|
|
47
|
+
readonly name: string;
|
|
48
|
+
readonly description: string;
|
|
49
|
+
readonly capabilities: readonly Capability[];
|
|
50
|
+
parseOptions(options: OptionReader): Options;
|
|
51
|
+
create(ctx: SourceContext, options: Options): Source;
|
|
52
|
+
}
|
|
53
|
+
/** Identity helper that keeps the options type of a driver checked. */
|
|
54
|
+
export declare function defineDriver<Options>(driver: Driver<Options>): Driver<Options>;
|
|
55
|
+
/** Any driver, options type erased (for registries and lists). */
|
|
56
|
+
export type AnyDriver = Driver<any>;
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { type Logger } from '../lib/log.ts';
|
|
2
|
+
import type { SourceContext } from './driver.ts';
|
|
3
|
+
import type { Capability, DeviceEvent, GpsFix, MotionSample, SourceStatus } from './types.ts';
|
|
4
|
+
export interface SourceInfo {
|
|
5
|
+
id: string;
|
|
6
|
+
driver: string;
|
|
7
|
+
driverName: string;
|
|
8
|
+
capabilities: readonly Capability[];
|
|
9
|
+
}
|
|
10
|
+
export interface SourceSnapshot extends SourceInfo {
|
|
11
|
+
status: SourceStatus;
|
|
12
|
+
lastFix?: GpsFix;
|
|
13
|
+
/** Server clock when `lastFix` arrived. */
|
|
14
|
+
lastFixAt?: number;
|
|
15
|
+
lastMotion?: MotionSample;
|
|
16
|
+
/** This source currently feeds the default (`auto`) GPS stream. */
|
|
17
|
+
active: boolean;
|
|
18
|
+
}
|
|
19
|
+
export type HubEvent = {
|
|
20
|
+
kind: 'status';
|
|
21
|
+
snapshot: SourceSnapshot;
|
|
22
|
+
} | {
|
|
23
|
+
kind: 'fix';
|
|
24
|
+
source: string;
|
|
25
|
+
fix: GpsFix;
|
|
26
|
+
active: boolean;
|
|
27
|
+
} | {
|
|
28
|
+
kind: 'motion';
|
|
29
|
+
source: string;
|
|
30
|
+
sample: MotionSample;
|
|
31
|
+
} | {
|
|
32
|
+
kind: 'event';
|
|
33
|
+
source: string;
|
|
34
|
+
event: DeviceEvent;
|
|
35
|
+
};
|
|
36
|
+
export type HubListener = (event: HubEvent) => void;
|
|
37
|
+
/** A raw device message kept for diagnostics. */
|
|
38
|
+
export interface RawFrame {
|
|
39
|
+
/** Epoch ms when it arrived. */
|
|
40
|
+
t: number;
|
|
41
|
+
frame: string;
|
|
42
|
+
}
|
|
43
|
+
export interface HubOptions {
|
|
44
|
+
/** Raw frames kept per source for diagnostics (default 2000, ~2 min of DDPAI data). */
|
|
45
|
+
rawFrameCapacity?: number;
|
|
46
|
+
/** A source that sent fixes and then went quiet for this long is `stale`. */
|
|
47
|
+
staleAfterMs?: number;
|
|
48
|
+
/** Source ids in preference order for the `auto` GPS stream; others follow in registration order. */
|
|
49
|
+
gpsPriority?: string[];
|
|
50
|
+
log?: Logger;
|
|
51
|
+
now?: () => number;
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Central state: one entry per source, the active GPS source, stale detection and fan-out.
|
|
55
|
+
* Sources write through their `SourceContext`, transports read snapshots and subscribe to events.
|
|
56
|
+
*/
|
|
57
|
+
export declare class Hub {
|
|
58
|
+
private readonly entries;
|
|
59
|
+
private readonly listeners;
|
|
60
|
+
private readonly staleAfterMs;
|
|
61
|
+
private readonly rawFrameCapacity;
|
|
62
|
+
private readonly gpsPriority;
|
|
63
|
+
private readonly log;
|
|
64
|
+
private readonly now;
|
|
65
|
+
private activeId;
|
|
66
|
+
private staleTimer;
|
|
67
|
+
constructor(options?: HubOptions);
|
|
68
|
+
/** Adds a source and returns the context its driver writes through. */
|
|
69
|
+
register(info: SourceInfo, log?: Logger): SourceContext;
|
|
70
|
+
/** Aborts the source's signal and marks it stopped. */
|
|
71
|
+
unregister(id: string): void;
|
|
72
|
+
start(): void;
|
|
73
|
+
stop(): void;
|
|
74
|
+
subscribe(listener: HubListener): () => void;
|
|
75
|
+
get activeGpsSource(): string | undefined;
|
|
76
|
+
has(id: string): boolean;
|
|
77
|
+
snapshot(id: string): SourceSnapshot | undefined;
|
|
78
|
+
snapshots(): SourceSnapshot[];
|
|
79
|
+
/**
|
|
80
|
+
* Gives a source a last known position from an earlier run (see LastPositionStore). It is served to clients as
|
|
81
|
+
* `lastKnown` until the device reports a live fix; the GPS state is not changed.
|
|
82
|
+
*/
|
|
83
|
+
seedLastFix(id: string, fix: GpsFix, receivedAt: number): void;
|
|
84
|
+
/** Recent raw device messages of a source, oldest first (for diagnostics). */
|
|
85
|
+
recentFrames(id: string): RawFrame[];
|
|
86
|
+
private setLink;
|
|
87
|
+
private setDevice;
|
|
88
|
+
private publishFix;
|
|
89
|
+
private publishNoFix;
|
|
90
|
+
private publishMotion;
|
|
91
|
+
private publishEvent;
|
|
92
|
+
private updateStatus;
|
|
93
|
+
private recomputeActive;
|
|
94
|
+
private priorityOrder;
|
|
95
|
+
private checkStale;
|
|
96
|
+
private toSnapshot;
|
|
97
|
+
private emit;
|
|
98
|
+
}
|
|
99
|
+
/** Validates a fix and trims it to sensible precision. Returns `undefined` for impossible values. */
|
|
100
|
+
export declare function normalizeFix(fix: GpsFix): GpsFix | undefined;
|