-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathdev-server.ts
More file actions
418 lines (365 loc) · 12.1 KB
/
dev-server.ts
File metadata and controls
418 lines (365 loc) · 12.1 KB
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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
/* eslint-disable max-lines */
import type { ViteDevServer, Plugin } from 'vite'
import YAML from 'yaml'
import fs from 'fs'
import path from 'path'
import { WebSocketServer } from 'ws'
type ScreenlyManifestField = {
type: string
default_value?: string
title: string
optional: boolean
is_global?: boolean
help_text: string | Record<string, unknown>
}
type BaseScreenlyMockData = {
metadata: {
coordinates: [number, number]
hostname: string
screen_name: string
hardware: string
location: string
screenly_version: string
tags: string[]
}
settings: Record<string, string>
cors_proxy_url: string
}
const defaultScreenlyConfig: BaseScreenlyMockData = {
metadata: {
coordinates: [37.3861, -122.0839] as [number, number],
hostname: 'dev-hostname',
screen_name: 'Development Server',
hardware: 'x86',
location: 'Development Environment',
screenly_version: 'development-server',
tags: ['Development'],
},
settings: {
enable_analytics: 'true',
tag_manager_id: '',
theme: 'light',
screenly_color_accent: '#972EFF',
screenly_color_light: '#ADAFBE',
screenly_color_dark: '#454BD2',
},
cors_proxy_url: 'http://127.0.0.1:8080',
}
const PERIPHERAL_WS_PORT = 9010
const ETB = '\x17'
type SensorType =
| 'ambient_temperature'
| 'humidity'
| 'air_pressure'
| 'secure_card_id'
const SENSOR_META: Record<
SensorType,
{ channelName: string; unit: string | null }
> = {
ambient_temperature: { channelName: 'my_living_room_temp', unit: '°C' },
humidity: { channelName: 'room_humidity', unit: '%' },
air_pressure: { channelName: 'room_pressure', unit: 'hPa' },
secure_card_id: { channelName: 'room1_access', unit: null },
}
const MOCK_CARD_IDS = {
operator: 'DEADBEEF',
maintenance: 'CAFEBABE',
}
function makeMockSensorValue(sensor: SensorType): number | string {
switch (sensor) {
case 'ambient_temperature':
return parseFloat((20 + Math.random() * 10).toFixed(2))
case 'humidity':
return parseFloat((40 + Math.random() * 40).toFixed(2))
case 'air_pressure':
return parseFloat((1000 + Math.random() * 30).toFixed(2))
case 'secure_card_id':
return Math.random() < 0.5
? MOCK_CARD_IDS.operator
: MOCK_CARD_IDS.maintenance
}
}
function generateUlid(): string {
return (
Date.now().toString(36).toUpperCase() +
Math.random().toString(36).slice(2, 12).toUpperCase()
)
}
function buildStateSnapshot(): Record<string, unknown>[] {
return (
Object.entries(SENSOR_META) as [
SensorType,
{ channelName: string; unit: string | null },
][]
).map(([wireKey, meta]) => {
const reading: Record<string, unknown> = {
name: meta.channelName,
[wireKey]: makeMockSensorValue(wireKey),
timestamp: Date.now(),
}
if (meta.unit) reading.unit = meta.unit
return reading
})
}
// eslint-disable-next-line max-lines-per-function
function startPeripheralMockServer(): void {
const wss = new WebSocketServer({ port: PERIPHERAL_WS_PORT })
// eslint-disable-next-line max-lines-per-function
wss.on('connection', (ws) => {
let identified = false
ws.on('message', (raw: Buffer) => {
const text = raw.toString().replace(ETB, '')
let msg: Record<string, unknown>
try {
msg = JSON.parse(text)
} catch {
return
}
const req = msg.request as Record<string, unknown> | undefined
if (!req) return
const requestId = req.id as string
// Identification handshake
if (req.identification) {
identified = true
const ack =
JSON.stringify({
response: { request_id: requestId, ok: { identification: null } },
}) + ETB
ws.send(ack)
// Push full state snapshot immediately after identification
const initialSnapshot =
JSON.stringify({
request: {
id: generateUlid(),
edge_app_source_state: { states: buildStateSnapshot() },
},
}) + ETB
ws.send(initialSnapshot)
return
}
if (!identified) return
// GetState request
const channelName = req.source_channel_get_state as string | undefined
const sensorEntry = channelName
? (
Object.entries(SENSOR_META) as [
SensorType,
{ channelName: string; unit: string | null },
][]
).find(([, meta]) => meta.channelName === channelName)
: undefined
if (sensorEntry) {
const [wireKey, meta] = sensorEntry
const value = makeMockSensorValue(wireKey)
const reading: Record<string, unknown> = {
name: channelName,
[wireKey]: value,
timestamp: Date.now(),
}
if (meta.unit) reading.unit = meta.unit
const response =
JSON.stringify({
response: {
request_id: requestId,
ok: { source_channel_get_state: reading },
},
}) + ETB
ws.send(response)
}
})
// Push full state snapshot every 5 seconds
const interval = setInterval(() => {
if (!identified || ws.readyState !== ws.OPEN) return
const event =
JSON.stringify({
request: {
id: generateUlid(),
edge_app_source_state: { states: buildStateSnapshot() },
},
}) + ETB
ws.send(event)
}, 5000)
ws.on('close', () => clearInterval(interval))
})
wss.on('error', (err: NodeJS.ErrnoException) => {
if (err.code === 'EADDRINUSE') {
console.warn(
`[screenly-dev-server] Port ${PERIPHERAL_WS_PORT} already in use — peripheral mock not started.`,
)
} else {
console.error('[screenly-dev-server] Peripheral WS error:', err.message)
}
})
console.log(
`[screenly-dev-server] Peripheral mock WS server listening on ws://127.0.0.1:${PERIPHERAL_WS_PORT}`,
)
}
function generateScreenlyObject(config: BaseScreenlyMockData) {
return `
// Generated screenly.js for development mode
window.screenly = {
signalReadyForRendering: () => {},
metadata: ${JSON.stringify(config.metadata, null, 2)},
settings: ${JSON.stringify(config.settings, null, 2)},
cors_proxy_url: ${JSON.stringify(config.cors_proxy_url)},
peripherals: (() => {
const ETB = '\\x17'
const WS_URL = 'ws://127.0.0.1:${PERIPHERAL_WS_PORT}'
let ws = null
let identified = false
const subscribers = []
const readings = {}
function generateUlid() {
return Date.now().toString(36).toUpperCase() + Math.random().toString(36).slice(2, 12).toUpperCase()
}
function send(payload) {
if (ws && ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify(payload) + ETB)
}
}
function notifySubscribers() {
const snapshot = Object.values(readings)
subscribers.forEach(cb => cb(snapshot))
dispatchEvent(new CustomEvent('screenly:peripheral', { detail: snapshot }))
}
function connect() {
ws = new WebSocket(WS_URL)
ws.onopen = () => {
send({ request: { id: generateUlid(), identification: { node_id: generateUlid(), description: 'Edge App Dev' } } })
}
ws.onmessage = (e) => {
const text = e.data.replace(ETB, '')
let msg
try { msg = JSON.parse(text) } catch { return }
if (msg.response?.ok?.identification !== undefined) {
identified = true
return
}
if (msg.request?.edge_app_source_state) {
msg.request.edge_app_source_state.states.forEach(s => { readings[s.name] = s })
notifySubscribers()
send({ response: { request_id: msg.request.id, ok: 'edge_app_source_state' } })
return
}
if (msg.request?.downstream_node_event) {
send({ response: { request_id: msg.request.id, ok: 'downstream_node_event' } })
return
}
}
ws.onerror = () => console.warn('[screenly] Peripheral WS error')
ws.onclose = () => { identified = false; setTimeout(connect, 2000) }
}
return {
watchState(callback) {
if (!ws) connect()
subscribers.push(callback)
}
}
})()
}
`
}
function generateMockData(
rootDir: string,
previousConfig: BaseScreenlyMockData = defaultScreenlyConfig,
): BaseScreenlyMockData {
const manifestPath = path.resolve(rootDir, 'screenly.yml')
const mockDataPath = path.resolve(rootDir, 'mock-data.yml')
let manifest: Record<string, unknown>
try {
if (!fs.existsSync(manifestPath)) {
console.warn(
`screenly.yml not found at ${manifestPath}, using previous config.`,
)
return previousConfig
}
manifest = YAML.parse(fs.readFileSync(manifestPath, 'utf8'))
} catch (error) {
const message = error instanceof Error ? error.message : 'Unknown error'
console.warn(
`Failed to parse screenly.yml: ${message}. Using previous config.`,
)
return previousConfig
}
const screenlyConfig: BaseScreenlyMockData = structuredClone(
defaultScreenlyConfig,
)
// Merge settings from manifest
if (manifest?.settings && typeof manifest.settings === 'object') {
for (const [key, value] of Object.entries(manifest.settings) as [
string,
ScreenlyManifestField,
][]) {
if (value.type === 'string' || value.type === 'secret') {
const manifestField: ScreenlyManifestField = value
const defaultValue = manifestField?.default_value ?? ''
screenlyConfig.settings[key] = defaultValue
}
}
}
// Override with mock-data.yml if it exists
if (fs.existsSync(mockDataPath)) {
let mockData: Record<string, unknown>
try {
mockData = YAML.parse(fs.readFileSync(mockDataPath, 'utf8'))
} catch (error) {
const message = error instanceof Error ? error.message : 'Unknown error'
console.warn(
`Failed to parse mock-data.yml: ${message}. Keeping config without mock-data overrides.`,
)
return screenlyConfig
}
if (mockData && typeof mockData === 'object') {
// Override metadata if present
if (mockData.metadata) {
Object.assign(screenlyConfig.metadata, mockData.metadata)
}
// Override settings if present
if (mockData.settings) {
Object.assign(screenlyConfig.settings, mockData.settings)
}
// Override cors_proxy_url if present
if (mockData.cors_proxy_url) {
screenlyConfig.cors_proxy_url = mockData.cors_proxy_url as string
}
}
}
return screenlyConfig
}
export function screenlyDevServer(): Plugin {
let config: BaseScreenlyMockData
let rootDir: string
return {
name: 'screenly-dev-server',
configureServer(server: ViteDevServer) {
rootDir = server.config.root
// Start peripheral mock WebSocket server
startPeripheralMockServer()
// Generate initial mock data
config = generateMockData(rootDir)
// Watch for changes to screenly.yml and mock-data.yml using Vite's watcher
const manifestPath = path.resolve(rootDir, 'screenly.yml')
const mockDataPath = path.resolve(rootDir, 'mock-data.yml')
const handleConfigFileChange = (file: string) => {
if (file === manifestPath || file === mockDataPath) {
config = generateMockData(rootDir, config)
// Notify connected clients to perform a full reload so they pick up the new mock config
server.ws.send({ type: 'full-reload', path: '*' })
}
}
server.watcher.add([manifestPath, mockDataPath])
server.watcher.on('add', handleConfigFileChange)
server.watcher.on('change', handleConfigFileChange)
server.watcher.on('unlink', handleConfigFileChange)
server.middlewares.use((req, res, next) => {
if (req.url === '/screenly.js?version=1') {
const screenlyJsContent = generateScreenlyObject(config)
res.setHeader('Content-Type', 'application/javascript')
res.end(screenlyJsContent)
return
}
next()
})
},
}
}