forked from microsoft/devicescript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdevtools.ts
More file actions
491 lines (452 loc) · 15.1 KB
/
devtools.ts
File metadata and controls
491 lines (452 loc) · 15.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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
/* eslint-disable @typescript-eslint/no-var-requires */
const WebSocket = require("faye-websocket")
import http from "http"
import url from "url"
import net from "net"
import { error, isInteractive, log, setInteractive } from "./command"
import { watch } from "fs-extra"
import { resolveBuildConfig, SrcFile } from "@devicescript/compiler"
import {
bufferConcat,
debounce,
delay,
DEVICE_ANNOUNCE,
DeviceScriptManagerReg,
ERROR,
Flags,
FRAME_PROCESS,
FRAME_PROCESS_LARGE,
JDBus,
JDDevice,
JDFrameBuffer,
loadServiceSpecifications,
serializeToTrace,
SRV_DEVICE_SCRIPT_MANAGER,
SRV_SETTINGS,
Transport,
TRANSPORT_ERROR,
} from "jacdac-ts"
import { deployToService } from "./deploy"
import { open, readFile } from "fs/promises"
import EventEmitter from "events"
import {
connectTransport,
createTransports,
initTransportCmds,
TransportsOptions,
} from "./transport"
import { fetchDevToolsProxy } from "./devtoolsproxy"
import {
DevToolsClient,
DevToolsIface,
initSideProto,
processSideMessage,
} from "./sidedata"
import { FSWatcher } from "fs"
import { compileFile } from "./build"
import { resolve } from "path"
import {
BuildStatus,
BuildReqArgs,
ConnectReqArgs,
BuildOptions,
} from "./sideprotocol"
import { DsDapSession } from "@devicescript/dap"
import { initVMCmds, overrideConsoleDebug, stopVmWorker } from "./vmworker"
import { enableLogging } from "./logging"
import { cliVersion } from "./version"
import { EXIT_CODE_EADDRINUSE } from "./exitcodes"
import { initAddCmds } from "./init"
export interface DevToolsOptions {
internet?: boolean
localhost?: boolean
trace?: string
vscode?: boolean
diagnostics?: boolean
}
let devtoolsSelf: DevToolsIface
let watcher: FSWatcher
function loadProjectServiceSpecifications() {
const { added, errors } = loadServiceSpecifications(
resolveBuildConfig().services
)
if (added?.length)
console.debug(`services: added ${added.map(a => a.shortId).join(", ")}`)
if (errors?.length)
errors.forEach(err =>
console.error(
`services: error adding ${err.spec.shortId}, ${err.message}`
)
)
}
function transportError(ev: {
transport: Transport
context: string
exception: any
}) {
error(`${ev.transport.type} error: ${ev.exception?.message || ev.context}`)
if (ev.exception && Flags.diagnostics) console.debug(ev.exception)
}
export async function devtools(
fn: string | undefined,
options: DevToolsOptions & BuildOptions & TransportsOptions = {}
) {
const port = 8081
const tcpPort = 8082
const dbgPort = 8083
if (options.vscode) setInteractive(false) // don't prompt for anything
if (options.diagnostics) Flags.diagnostics = true
overrideConsoleDebug()
log(`${cliVersion()} running in ${process.cwd()}`)
loadProjectServiceSpecifications()
const traceFd = options.trace ? await open(options.trace, "w") : null
// passive bus to sniff packets
const transports = await createTransports(options)
const bus = new JDBus(transports, {
client: false,
disableRoleManager: true,
proxy: true,
})
devtoolsSelf = {
clients: [],
bus,
lastOKBuild: null,
mainClient: null,
build: buildCmd,
watch: watchCmd,
connect: connectCmd,
}
initSideProto(devtoolsSelf)
initVMCmds()
initTransportCmds(devtoolsSelf, bus)
initAddCmds()
bus.passive = false
bus.on(ERROR, e => error(e))
bus.on(TRANSPORT_ERROR, transportError)
bus.on(FRAME_PROCESS, (frame: JDFrameBuffer) => {
if (traceFd)
traceFd.write(
serializeToTrace(frame, 0, bus, { showTime: false }) + "\n"
)
devtoolsSelf.clients
.filter(c => c.__devsSender !== frame._jacdac_sender)
.forEach(c => c.send(Buffer.from(frame)))
})
bus.on(FRAME_PROCESS_LARGE, (frame: JDFrameBuffer) => {
devtoolsSelf.clients
.filter(c => c.__devsSender !== frame._jacdac_sender)
.forEach(c => c.send(Buffer.from(frame)))
})
startProxyServers(port, tcpPort, options)
startDbgServer(dbgPort, options)
enableLogging(bus)
if (options.vscode) disableAutoStart(bus)
bus.autoConnect = true
bus.start()
await bus.connect(true)
if (fn) {
const args: BuildReqArgs = {
filename: fn,
deployTo: "*",
buildOptions: options,
}
if (transports.length) {
console.log("waiting for enumeration...")
await delay(1000)
}
console.log(`building ${fn}...`)
logBuildStatus(await buildCmd(args))
console.log(`watching ${fn}...`)
await watchCmd(args, logBuildStatus)
}
function logBuildStatus(st: BuildStatus) {
console.log(`build ${fn} ${st.success ? "OK" : "Failed"}`)
for (const msg of st.diagnostics) console.error(msg.formatted)
if (st.deployStatus) {
console.log(`deploy status: ${st.deployStatus}`)
}
}
}
export const DISABLE_AUTO_START_KEY = "disableAutoStart"
function disableAutoStart(bus: JDBus) {
bus.nodeData[DISABLE_AUTO_START_KEY] = true // settings might fiddle with this flag
bus.on(DEVICE_ANNOUNCE, async (dev: JDDevice) => {
// when a device manager connects, disable auto start
const managers = dev.services({
serviceClass: SRV_DEVICE_SCRIPT_MANAGER,
})
for (const manager of managers) {
console.debug(`disable autostart of ${manager}`)
const autoStart = manager.register(DeviceScriptManagerReg.Autostart)
await autoStart.sendSetBoolAsync(false)
}
})
}
function startProxyServers(
port: number,
tcpPort: number,
options: DevToolsOptions
) {
let clientId = 0
const { vscode } = options
const bus = devtoolsSelf.bus
const listenHost = options.internet ? undefined : "127.0.0.1"
const domain = listenHost || "localhost"
log(` dashboard : http://${domain}:${port}/`)
log(` connection : http://${domain}:${port}/connect`)
log(` websocket : ws://${domain}:${port}`)
const server = http.createServer(function (req, res) {
const parsedUrl = url.parse(req.url)
const pathname = parsedUrl.pathname
let route: "vscode" | "connect" | "dashboard"
if (pathname === "/") route = vscode ? "vscode" : "dashboard"
else if (pathname === "/connect") route = "connect"
if (!route) res.statusCode = 404
else
fetchDevToolsProxy(options.localhost, route)
.then(proxyHtml => {
res.setHeader("Cache-control", "no-cache")
res.setHeader("Content-type", "text/html")
res.end(proxyHtml)
})
.catch(e => {
error(e)
res.statusCode = 3
})
})
server.on("error", handleError)
server.on("upgrade", (request, socket, body) => {
// is this a socket?
if (WebSocket.isWebSocket(request)) {
const client: DevToolsClient = new WebSocket(request, socket, body)
const sender = "ws" + ++clientId
// store sender id to deduped packet
client.__devsSender = sender
devtoolsSelf.clients.push(client)
log(
`webclient: connected (${sender}, ${devtoolsSelf.clients.length} clients)`
)
const ev = client as any as EventEmitter
ev.on("message", (event: any) => {
const { data } = event
if (typeof data === "string")
processSideMessage(devtoolsSelf, data, client)
else processPacket(data, sender)
})
ev.on("close", () => removeClient(client))
ev.on("error", (ev: Error) => error(ev.message))
}
})
server.listen(port, listenHost)
log(` tcpsocket : tcp://${domain}:${tcpPort}`)
const tcpServer = net.createServer(socket => {
const sender = "tcp" + ++clientId
const client: DevToolsClient = socket as any
client.__devsSender = sender
client.send = (pkt0: Buffer | string) => {
if (typeof pkt0 == "string") return
if (socket.readyState !== "open") return
if (pkt0.length >= 0xff) return
const pkt = new Uint8Array(pkt0)
const b = new Uint8Array(1 + pkt.length)
b[0] = pkt.length
b.set(pkt, 1)
try {
socket.write(b)
} catch {
try {
socket.end()
} catch {} // eslint-disable-line no-empty
}
}
devtoolsSelf.clients.push(client)
log(
`tcpclient: connected (${sender} ${devtoolsSelf.clients.length} clients)`
)
let acc: Uint8Array
socket.on("data", (buf: Uint8Array) => {
if (acc) {
buf = bufferConcat(acc, buf)
acc = null
} else {
buf = new Uint8Array(buf)
}
while (buf) {
let endp = buf[0] + 1
let off = 1
if (endp == 0x100 && buf.length > 3) {
endp = 3 + buf[1] + (buf[2] << 8)
off = 3
}
if (buf.length >= endp) {
const pkt = buf.slice(off, endp)
if (buf.length > endp) buf = buf.slice(endp)
else buf = null
processPacket(pkt, sender)
} else {
acc = buf
buf = null
}
}
})
socket.on("end", () => removeClient(client))
socket.on("error", (ev: Error) => error(ev))
})
tcpServer.on("error", handleError)
tcpServer.listen(tcpPort, listenHost)
function handleError(err: Error) {
if (/EADDRINUSE/.test(err.message)) process.exit(EXIT_CODE_EADDRINUSE)
else {
error(err)
process.exit(1)
}
}
function removeClient(client: DevToolsClient) {
const i = devtoolsSelf.clients.indexOf(client)
devtoolsSelf.clients.splice(i, 1)
if (devtoolsSelf.mainClient == client) devtoolsSelf.mainClient = null
log(`client: disconnected (${devtoolsSelf.clients.length} clients)`)
}
function processPacket(message: Buffer | Uint8Array, sender: string) {
const data: JDFrameBuffer = new Uint8Array(message)
data._jacdac_sender = sender
bus.sendFrameAsync(data)
}
}
function startDbgServer(port: number, options: DevToolsOptions) {
let fnResolveMap: Record<string, string> = {}
const resolvePath = (s: SrcFile) => fnResolveMap[s.path]
async function checkFiles() {
fnResolveMap = {}
const folder = process.cwd()
const dbg = devtoolsSelf.lastOKBuild.dbg
for (const f of dbg.sources) {
const fn = resolve(folder, f.path)
try {
const src = await readFile(fn, "utf-8")
if (src == f.text) fnResolveMap[f.path] = fn
else {
console.log(`file ${f.path} different on disk`)
}
} catch {
console.log(`can't find ${f.path}`)
}
}
}
const listenHost = options.internet ? undefined : "127.0.0.1"
const domain = listenHost || "localhost"
console.log(` dbgserver : tcp://${domain}:${port}`)
net.createServer(async socket => {
console.log("dbgserver: connection")
let session: DsDapSession
socket.on("end", async () => {
console.log("dbgserver: connection closed")
await session?.finish()
await stopVmWorker()
})
const dbg = devtoolsSelf.lastOKBuild?.dbg
if (!dbg) {
error("dbgserver: can't find any build to debug")
// TODO compare sha256
socket.end()
return
}
await checkFiles()
session = new DsDapSession(devtoolsSelf.bus, dbg, resolvePath)
session.setRunAsServer(true)
session.start(socket, socket)
}).listen(port, listenHost)
}
async function connectCmd(req: ConnectReqArgs) {
await connectTransport(devtoolsSelf, req)
}
async function buildCmd(args: BuildReqArgs) {
args = { ...args }
return await rebuild(args)
}
async function watchCmd(
args: BuildReqArgs,
watchCb?: (st: BuildStatus) => void
) {
args = { ...args }
watcher?.close()
if (!args.filename) watcher = undefined
else
watcher = watch(
args.filename,
debounce(async () => {
let res: BuildStatus
try {
res = await rebuild(args)
} catch (err) {
res = {
success: false,
dbg: null,
binary: null,
diagnostics: [],
usedFiles: [args.filename],
deployStatus: err.message || "" + err,
}
}
watchCb(res)
}, 500)
)
}
async function rebuild(args: BuildReqArgs) {
const opts = { ...args.buildOptions }
if (!opts.cwd) opts.cwd = process.cwd()
opts.verify = false
opts.quiet = true
const res = await compileFile(args.filename, opts)
let deployStatus = ""
if (args.deployTo && res.success) {
const binary = res.binary
const settings = res.settings
try {
const service = deployService(args)
const settingsService = service?.device?.services({
serviceClass: SRV_SETTINGS,
})?.[0]
await deployToService(service, binary, {
settingsService,
settings,
})
deployStatus = `OK`
} catch (err) {
deployStatus = err.message || "" + err
error("Deploy error: " + deployStatus)
}
}
delete res.binary
res.diagnostics.forEach(d => {
d.filename = resolve(d.filename)
})
const r: BuildStatus = {
...res,
deployStatus,
}
if (res.success) devtoolsSelf.lastOKBuild = r
return r
}
function deployService(args: BuildReqArgs) {
const bus = devtoolsSelf.bus
if (args.deployTo == "*") {
const services = bus.services({
serviceClass: SRV_DEVICE_SCRIPT_MANAGER,
lost: false,
})
if (services.length > 1)
throw new Error(`Multiple DeviceScript device found.`)
else if (services.length == 0)
throw new Error(`No DeviceScript device found.`)
return services[0]
}
const dev = bus.device(args.deployTo, true)
if (!dev) throw new Error(`Device ${args.deployTo} not found`)
const service = dev.services({
serviceClass: SRV_DEVICE_SCRIPT_MANAGER,
})[0]
if (!service)
throw new Error(`Device ${dev} doesn't have a DeviceScript Manager.`)
return service
}