-
Notifications
You must be signed in to change notification settings - Fork 627
Expand file tree
/
Copy pathserver.ts
More file actions
1391 lines (1262 loc) · 51.7 KB
/
server.ts
File metadata and controls
1391 lines (1262 loc) · 51.7 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
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import * as fs from 'fs';
import * as path from 'path';
import * as http from 'http';
import * as https from 'https';
import * as url from 'url';
import * as querystring from 'querystring';
import * as nodeutil from './nodeutil';
import * as hid from './hid';
import * as net from 'net';
import * as storage from './storage';
import { SUB_WEBAPPS } from './subwebapp';
import { promisify } from "util";
import U = pxt.Util;
import Cloud = pxt.Cloud;
import { SecureContextOptions } from 'tls';
const userProjectsDirName = "projects";
let root = ""
let dirs = [""]
let docfilesdirs = [""]
let userProjectsDir = path.join(process.cwd(), userProjectsDirName);
let docsDir = ""
let packagedDir = ""
let localHexCacheDir = path.join("built", "hexcache");
let serveOptions: ServeOptions;
function setupDocfilesdirs() {
docfilesdirs = [
"docfiles",
path.join(nodeutil.pxtCoreDir, "docfiles")
]
}
function setupRootDir() {
root = nodeutil.targetDir
console.log("Starting server in", root)
console.log(`With pxt core at ${nodeutil.pxtCoreDir}`)
dirs = [
"built/web",
path.join(nodeutil.targetDir, "docs"),
path.join(nodeutil.targetDir, "built"),
path.join(nodeutil.targetDir, "sim/public"),
path.join(nodeutil.targetDir, "node_modules", `pxt-${pxt.appTarget.id}-sim`, "public"),
path.join(nodeutil.pxtCoreDir, "built/web"),
path.join(nodeutil.pxtCoreDir, "webapp/public"),
path.join(nodeutil.pxtCoreDir, "common-docs"),
path.join(nodeutil.pxtCoreDir, "docs"),
]
docsDir = path.join(root, "docs")
packagedDir = path.join(root, "built/packaged")
setupDocfilesdirs()
setupProjectsDir()
pxt.debug(`docs dir:\r\n ${docsDir}`)
pxt.debug(`doc files dir: \r\n ${docfilesdirs.join("\r\n ")}`)
pxt.debug(`dirs:\r\n ${dirs.join('\r\n ')}`)
pxt.debug(`projects dir: ${userProjectsDir}`);
}
function setupProjectsDir() {
nodeutil.mkdirP(userProjectsDir);
}
const statAsync = promisify(fs.stat)
const readdirAsync = promisify(fs.readdir)
const readFileAsync = promisify(fs.readFile)
const writeFileAsync: any = promisify(fs.writeFile)
const unlinkAsync: any = promisify(fs.unlink)
function existsAsync(fn: string): Promise<boolean> {
return new Promise<boolean>((resolve, reject) => {
fs.exists(fn, resolve)
})
}
function statOptAsync(fn: string): Promise<fs.Stats> {// or null
return statAsync(fn)
.then(st => st, err => null)
}
function throwError(code: number, msg: string = null) {
let err = new Error(msg || "Error " + code);
(err as any).statusCode = code
throw err
}
type FsFile = pxt.FsFile;
type FsPkg = pxt.FsPkg;
function readAssetsAsync(logicalDirname: string): Promise<any> {
let dirname = path.join(userProjectsDir, logicalDirname, "assets")
let pref = "http://" + serveOptions.hostname + ":" + serveOptions.port + "/assets/" + logicalDirname + "/"
return readdirAsync(dirname)
.catch(err => [])
.then(res => U.promiseMapAll(res, fn => statAsync(path.join(dirname, fn)).then(res => ({
name: fn,
size: res.size,
url: pref + fn
}))))
.then(res => ({
files: res
}))
}
const HEADER_JSON = ".header.json"
async function readPkgAsync(logicalDirname: string, fileContents = false): Promise<FsPkg> {
let dirname = path.join(userProjectsDir, logicalDirname)
let buf = await readFileAsync(path.join(dirname, pxt.CONFIG_NAME))
let cfg: pxt.PackageConfig = JSON.parse(buf.toString("utf8"))
let r: FsPkg = {
path: logicalDirname,
config: cfg,
header: null,
files: []
};
for (let fn of pxt.allPkgFiles(cfg).concat([pxt.github.GIT_JSON, pxt.SIMSTATE_JSON])) {
let st = await statOptAsync(path.join(dirname, fn))
let ff: FsFile = {
name: fn,
mtime: st ? st.mtime.getTime() : null
}
let thisFileContents = st && fileContents
if (!st && fn == pxt.SIMSTATE_JSON)
continue
if (fn == pxt.github.GIT_JSON) {
// skip .git.json altogether if missing
if (!st) continue
thisFileContents = true
}
if (thisFileContents) {
let buf = await readFileAsync(path.join(dirname, fn))
ff.content = buf.toString("utf8")
}
r.files.push(ff)
}
if (await existsAsync(path.join(dirname, "icon.jpeg"))) {
r.icon = "/icon/" + logicalDirname
}
// now try reading the header
buf = await readFileAsync(path.join(dirname, HEADER_JSON))
.then(b => b, err => null)
if (buf && buf.length)
r.header = JSON.parse(buf.toString("utf8"))
return r
}
function writeScreenshotAsync(logicalDirname: string, screenshotUri: string, iconUri: string) {
console.log('writing screenshot...');
const dirname = path.join(userProjectsDir, logicalDirname)
nodeutil.mkdirP(dirname)
function writeUriAsync(name: string, uri: string) {
if (!uri) return Promise.resolve();
const m = uri.match(/^data:image\/(png|jpeg);base64,(.*)$/);
if (!m) return Promise.resolve();
const ext = m[1];
const data = m[2];
const fn = path.join(dirname, name + "." + ext);
console.log(`writing ${fn}`)
return writeFileAsync(fn, Buffer.from(data, 'base64'));
}
return Promise.all([
writeUriAsync("screenshot", screenshotUri),
writeUriAsync("icon", iconUri)
]).then(() => { });
}
function writePkgAssetAsync(logicalDirname: string, data: any) {
const dirname = path.join(userProjectsDir, logicalDirname, "assets")
nodeutil.mkdirP(dirname)
return writeFileAsync(dirname + "/" + data.name, Buffer.from(data.data, data.encoding || "base64"))
.then(() => ({
name: data.name
}))
}
function writePkgAsync(logicalDirname: string, data: FsPkg) {
const dirname = path.join(userProjectsDir, logicalDirname)
nodeutil.mkdirP(dirname)
return U.promiseMapAll(data.files, f =>
readFileAsync(path.join(dirname, f.name))
.then(buf => {
if (f.name == pxt.CONFIG_NAME) {
try {
if (!pxt.Package.parseAndValidConfig(f.content)) {
pxt.log("Trying to save invalid JSON config")
pxt.debug(f.content);
throwError(410)
}
} catch (e) {
pxt.log("Trying to save invalid format JSON config")
pxt.log(e)
pxt.debug(f.content);
throwError(410)
}
}
if (buf.toString("utf8") !== f.prevContent) {
pxt.log(`merge error for ${f.name}: previous content changed...`);
throwError(409)
}
}, err => { }))
// no conflict, proceed with writing
.then(() => U.promiseMapAll(data.files, f => {
let d = f.name.replace(/\/[^\/]*$/, "")
if (d != f.name)
nodeutil.mkdirP(path.join(dirname, d))
const fn = path.join(dirname, f.name)
return f.content == null ? unlinkAsync(fn) : writeFileAsync(fn, f.content)
}))
.then(() => {
if (data.header)
return writeFileAsync(path.join(dirname, HEADER_JSON), JSON.stringify(data.header, null, 4))
})
.then(() => readPkgAsync(logicalDirname, false))
}
function returnDirAsync(logicalDirname: string, depth: number): Promise<FsPkg[]> {
logicalDirname = logicalDirname.replace(/^\//, "")
const dirname = path.join(userProjectsDir, logicalDirname)
// load packages under /projects, 3 level deep
return existsAsync(path.join(dirname, pxt.CONFIG_NAME))
// read package if pxt.json exists
.then(ispkg => Promise.all<FsPkg[]>([
// current folder
ispkg ? readPkgAsync(logicalDirname).then<FsPkg[]>(r => [r], err => undefined) : Promise.resolve<FsPkg[]>(undefined),
// nested packets
depth <= 1 ? Promise.resolve<FsPkg[]>(undefined)
: readdirAsync(dirname).then(files => U.promiseMapAll(files, fn =>
statAsync(path.join(dirname, fn)).then<FsPkg[]>(st => {
if (fn[0] != "." && st.isDirectory())
return returnDirAsync(logicalDirname + "/" + fn, depth - 1)
else return undefined
})).then(U.concat)
)
]))
// drop empty arrays
.then(rs => rs.filter(r => !!r))
.then(U.concat);
}
function isAuthorizedLocalRequest(req: http.IncomingMessage): boolean {
// validate token
return req.headers["authorization"]
&& req.headers["authorization"] == serveOptions.localToken;
}
function getCachedHexAsync(sha: string): Promise<any> {
if (!sha) {
return Promise.resolve();
}
let hexFile = path.resolve(localHexCacheDir, sha + ".hex");
return existsAsync(hexFile)
.then((results) => {
if (!results) {
console.log(`offline HEX not found: ${hexFile}`);
return Promise.resolve(null);
}
console.log(`serving HEX from offline cache: ${hexFile}`);
return readFileAsync(hexFile)
.then((fileContent) => {
return {
enums: [],
functions: [],
hex: fileContent.toString()
};
});
});
}
async function handleApiStoreRequestAsync(req: http.IncomingMessage, res: http.ServerResponse, elts: string[]): Promise<void> {
const meth = req.method.toUpperCase();
const container = decodeURIComponent(elts[0]);
const key = decodeURIComponent(elts[1]);
if (!container || !key) { throw throwError(400, "malformed api/store request: " + req.url); }
const origin = req.headers['origin'] || '*';
res.setHeader('Access-Control-Allow-Origin', origin);
if (meth === "GET") {
const val = await storage.getAsync(container, key);
if (val) {
if (typeof val === "object") {
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf8' });
res.end(JSON.stringify(val));
} else {
res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf8' });
res.end(val.toString());
}
} else {
res.writeHead(204);
res.end();
}
} else if (meth === "POST") {
const srec = (await nodeutil.readResAsync(req)).toString("utf8");
const rec = JSON.parse(srec) as storage.Record;
await storage.setAsync(container, key, rec);
res.writeHead(200);
res.end();
} else if (meth === "DELETE") {
await storage.delAsync(container, key);
res.writeHead(200);
res.end();
} else if (meth === "OPTIONS") {
const allowedHeaders = req.headers['access-control-request-headers'] || 'Content-Type';
const allowedMethods = req.headers['access-control-request-method'] || 'GET, POST, DELETE';
res.setHeader('Access-Control-Allow-Headers', allowedHeaders);
res.setHeader('Access-Control-Allow-Methods', allowedMethods);
res.writeHead(200);
res.end();
} else {
throw res.writeHead(400, "Unsupported HTTP method: " + meth);
}
}
function handleApiAsync(req: http.IncomingMessage, res: http.ServerResponse, elts: string[]): Promise<any> {
const opts: pxt.Map<string | string[]> = querystring.parse(url.parse(req.url).query)
const innerPath = elts.slice(2).join("/").replace(/^\//, "")
const filename = path.resolve(path.join(userProjectsDir, innerPath))
const meth = req.method.toUpperCase()
const cmd = meth + " " + elts[1]
const readJsonAsync = () =>
nodeutil.readResAsync(req)
.then(buf => JSON.parse(buf.toString("utf8")))
if (cmd == "GET list")
return returnDirAsync(innerPath, 3)
.then<pxt.FsPkgs>(lst => {
return {
pkgs: lst
}
})
else if (cmd == "GET stat")
return statOptAsync(filename)
.then(st => {
if (!st) return {}
else return {
mtime: st.mtime.getTime()
}
})
else if (cmd == "GET pkg")
return readPkgAsync(innerPath, true)
else if (cmd == "POST pkg")
return readJsonAsync()
.then(d => writePkgAsync(innerPath, d))
else if (cmd == "POST pkgasset")
return readJsonAsync()
.then(d => writePkgAssetAsync(innerPath, d))
else if (cmd == "GET pkgasset")
return readAssetsAsync(innerPath)
else if (cmd == "POST deploy" && pxt.commands.hasDeployFn())
return readJsonAsync()
.then(pxt.commands.deployAsync)
.then((boardCount) => {
return {
boardCount: boardCount
};
});
else if (cmd == "POST screenshot")
return readJsonAsync()
.then(d => writeScreenshotAsync(innerPath, d.screenshot, d.icon));
else if (cmd == "GET compile")
return getCachedHexAsync(innerPath)
.then((res) => {
if (!res) {
return {
notInOfflineCache: true
};
}
return res;
});
else if (cmd == "GET md" && pxt.appTarget.id + "/" == innerPath.slice(0, pxt.appTarget.id.length + 1)) {
// innerpath start with targetid
return readMdAsync(
innerPath.slice(pxt.appTarget.id.length + 1),
opts["lang"] as string);
}
else if (cmd == "GET config" && new RegExp(`${pxt.appTarget.id}\/targetconfig(\/v[0-9.]+)?$`).test(innerPath)) {
// target config
return readFileAsync("targetconfig.json").then(buf => JSON.parse(buf.toString("utf8")));
}
else throw throwError(400, `unknown command ${cmd.slice(0, 140)}`)
}
export function lookupDocFile(name: string) {
if (docfilesdirs.length <= 1)
setupDocfilesdirs()
for (let d of docfilesdirs) {
let foundAt = path.join(d, name)
if (fs.existsSync(foundAt)) return foundAt
}
return null
}
export function expandHtml(html: string, params?: pxt.Map<string>, appTheme?: pxt.AppTheme) {
let theme = U.flatClone(appTheme || pxt.appTarget.appTheme)
html = expandDocTemplateCore(html)
params = params || {};
params["name"] = params["name"] || pxt.appTarget.appTheme.title;
params["description"] = params["description"] || pxt.appTarget.appTheme.description;
params["locale"] = params["locale"] || pxt.appTarget.appTheme.defaultLocale || "en"
// page overrides
let m = /<title>([^<>@]*)<\/title>/.exec(html)
if (m) params["name"] = m[1]
m = /<meta name="Description" content="([^"@]*)"/i.exec(html)
if (m) params["description"] = m[1]
let d: pxt.docs.RenderData = {
html: html,
params: params,
theme: theme,
// Note that breadcrumb and filepath expansion are not supported in the cloud
// so we don't do them here either.
}
pxt.docs.prepTemplate(d)
return d.finish().replace(/@-(\w+)-@/g, (f, w) => "@" + w + "@")
}
export function expandDocTemplateCore(template: string) {
template = template
.replace(/<!--\s*@include\s+(\S+)\s*-->/g,
(full, fn) => {
return `
<!-- include ${fn} -->
${expandDocFileTemplate(fn)}
<!-- end include ${fn} -->
`
})
return template
}
export function expandDocFileTemplate(name: string) {
let fn = lookupDocFile(name)
let template = fn ? fs.readFileSync(fn, "utf8") : ""
return expandDocTemplateCore(template)
}
let wsSerialClients: WebSocket[] = [];
let webappReady = false;
function initSocketServer(wsPort: number, hostname: string) {
console.log(`starting local ws server at ${wsPort}...`)
const WebSocket = require('faye-websocket');
function startSerial(request: any, socket: any, body: any) {
let ws = new WebSocket(request, socket, body);
wsSerialClients.push(ws);
ws.on('message', function (event: any) {
// ignore
});
ws.on('close', function (event: any) {
console.log('ws connection closed')
wsSerialClients.splice(wsSerialClients.indexOf(ws), 1)
ws = null;
});
ws.on('error', function () {
console.log('ws connection closed')
wsSerialClients.splice(wsSerialClients.indexOf(ws), 1)
ws = null;
})
}
function objToString(obj: any) {
if (obj == null)
return "null"
let r = "{\n"
for (let k of Object.keys(obj)) {
r += " " + k + ": "
let s = JSON.stringify(obj[k])
if (!s) s = "(null)"
if (s.length > 60) s = s.slice(0, 60) + "..."
r += s + "\n"
}
r += "}"
return r
}
let hios: pxt.Map<Promise<pxt.HF2.Wrapper>> = {};
function startHID(request: http.IncomingMessage, socket: WebSocket, body: any) {
let ws = new WebSocket(request, socket, body);
ws.on('open', () => {
ws.send(JSON.stringify({ id: "ready" }))
})
ws.on('message', function (event: any) {
try {
let msg = JSON.parse(event.data);
pxt.debug(`hid: msg ${msg.op}`) // , objToString(msg.arg))
// check that HID is installed
if (!hid.isInstalled(true)) {
if (!ws) return;
ws.send(JSON.stringify({
result: {
errorMessage: "node-hid not installed",
},
op: msg.op,
id: msg.id
}))
return;
}
Promise.resolve()
.then(() => {
let hio = hios[msg.arg.path]
if (!hio && msg.arg.path)
hios[msg.arg.path] = hio = hid.hf2ConnectAsync(msg.arg.path, !!msg.arg.raw)
return hio
})
.then(hio => {
switch (msg.op) {
case "disconnect":
return hio.disconnectAsync()
.then(() => ({}))
case "init":
return hio.reconnectAsync()
.then(() => {
hio.io.onEvent = v => {
if (!ws) return
ws.send(JSON.stringify({
op: "event",
result: {
path: msg.arg.path,
data: U.toHex(v),
}
}))
}
if (hio.rawMode)
hio.io.onData = hio.io.onEvent
hio.onSerial = (v, isErr) => {
if (!ws) return
ws.send(JSON.stringify({
op: "serial",
result: {
isError: isErr,
path: msg.arg.path,
data: U.toHex(v),
}
}))
}
return {}
})
case "send":
if (!hio.rawMode)
return null
return hio.io.sendPacketAsync(U.fromHex(msg.arg.data))
.then(() => ({}))
case "talk":
return U.promiseMapAllSeries(msg.arg.cmds, (obj: any) => {
pxt.debug(`hid talk ${obj.cmd}`)
return hio.talkAsync(obj.cmd, U.fromHex(obj.data))
.then(res => ({ data: U.toHex(res) }))
});
case "sendserial":
return hio.sendSerialAsync(U.fromHex(msg.arg.data), msg.arg.isError);
case "list":
return hid.getHF2DevicesAsync()
.then(devices => { return { devices } as any; });
default: // unknown message
pxt.log(`unknown hid message ${msg.op}`)
return null;
}
})
.then(resp => {
if (!ws) return;
pxt.debug(`hid: resp ${objToString(resp)}`)
ws.send(JSON.stringify({
op: msg.op,
id: msg.id,
result: resp
}))
}, error => {
pxt.log(`hid: error ${error.message}`)
if (!ws) return;
ws.send(JSON.stringify({
result: {
errorMessage: error.message || "Error",
errorStackTrace: error.stack,
},
op: msg.op,
id: msg.id
}))
})
} catch (e) {
console.log("ws hid error", e.stack)
}
});
ws.on('close', function (event: any) {
console.log('ws hid connection closed')
ws = null;
});
ws.on('error', function () {
console.log('ws hid connection closed')
ws = null;
})
}
let openSockets: pxt.Map<net.Socket> = {};
function startTCP(request: http.IncomingMessage, socket: WebSocket, body: any) {
let ws = new WebSocket(request, socket, body);
let netSockets: net.Socket[] = []
ws.on('open', () => {
ws.send(JSON.stringify({ id: "ready" }))
})
ws.on('message', function (event: any) {
try {
let msg = JSON.parse(event.data);
pxt.debug(`tcp: msg ${msg.op}`) // , objToString(msg.arg))
Promise.resolve()
.then(() => {
let sock = openSockets[msg.arg.socket]
switch (msg.op) {
case "close":
sock.end();
let idx = netSockets.indexOf(sock)
if (idx >= 0)
netSockets.splice(idx, 1)
return {}
case "open":
return new Promise((resolve, reject) => {
const newSock = new net.Socket()
netSockets.push(newSock)
const id = pxt.U.guidGen()
newSock.on('error', err => {
if (ws)
ws.send(JSON.stringify({ op: "error", result: { socket: id, error: err.message } }))
})
newSock.connect(msg.arg.port, msg.arg.host, () => {
openSockets[id] = newSock
resolve({ socket: id })
})
newSock.on('data', d => {
if (ws)
ws.send(JSON.stringify({ op: "data", result: { socket: id, data: d.toString("base64"), encoding: "base64" } }))
})
newSock.on('close', () => {
if (ws)
ws.send(JSON.stringify({ op: "close", result: { socket: id } }))
})
})
case "send":
sock.write(Buffer.from(msg.arg.data, msg.arg.encoding || "utf8"))
return {}
default: // unknown message
pxt.log(`unknown tcp message ${msg.op}`)
return null;
}
})
.then(resp => {
if (!ws) return;
pxt.debug(`hid: resp ${objToString(resp)}`)
ws.send(JSON.stringify({
op: msg.op,
id: msg.id,
result: resp
}))
}, error => {
pxt.log(`hid: error ${error.message}`)
if (!ws) return;
ws.send(JSON.stringify({
result: {
errorMessage: error.message || "Error",
errorStackTrace: error.stack,
},
op: msg.op,
id: msg.id
}))
})
} catch (e) {
console.log("ws tcp error", e.stack)
}
});
function closeAll() {
console.log('ws tcp connection closed')
ws = null;
for (let s of netSockets) {
try {
s.end()
} catch (e) { }
}
}
ws.on('close', closeAll);
ws.on('error', closeAll);
}
function startDebug(request: http.IncomingMessage, socket: WebSocket, body: any) {
let ws = new WebSocket(request, socket, body);
let dapjs: any
ws.on('open', () => {
ws.send(JSON.stringify({ id: "ready" }))
})
ws.on('message', function (event: any) {
try {
let msg = JSON.parse(event.data);
if (!dapjs) dapjs = require("dapjs")
let toHandle = msg.arg
toHandle.op = msg.op
console.log("DEBUGMSG", objToString(toHandle))
Promise.resolve()
.then(() => dapjs.handleMessageAsync(toHandle))
.then(resp => {
if (resp == null || typeof resp != "object")
resp = { response: resp }
console.log("DEBUGRESP", objToString(resp))
ws.send(JSON.stringify({
op: msg.op,
id: msg.id,
result: resp
}))
}, error => {
console.log("DEBUGERR", error.stack)
ws.send(JSON.stringify({
result: {
errorMessage: error.message || "Error",
errorStackTrace: error.stack,
},
op: msg.op,
id: msg.id
}))
})
} catch (e) {
console.log("ws debug error", e.stack)
}
});
ws.on('close', function (event: any) {
console.log('ws debug connection closed')
ws = null;
});
ws.on('error', function () {
console.log('ws debug connection closed')
ws = null;
})
}
let wsserver = http.createServer();
wsserver.on('upgrade', function (request: http.IncomingMessage, socket: WebSocket, body: any) {
try {
if (WebSocket.isWebSocket(request)) {
console.log('ws connection at ' + request.url);
if (request.url == "/" + serveOptions.localToken + "/serial")
startSerial(request, socket, body);
else if (request.url == "/" + serveOptions.localToken + "/debug")
startDebug(request, socket, body);
else if (request.url == "/" + serveOptions.localToken + "/hid")
startHID(request, socket, body);
else if (request.url == "/" + serveOptions.localToken + "/tcp")
startTCP(request, socket, body);
else {
console.log('refused connection at ' + request.url);
socket.close(403);
}
}
} catch (e) {
console.log('upgrade failed...')
}
});
return new Promise<void>((resolve, reject) => {
wsserver.on("Error", reject);
wsserver.listen(wsPort, hostname, () => resolve());
});
}
function sendSerialMsg(msg: string) {
//console.log('sending ' + msg);
wsSerialClients.forEach(function (client: any) {
client.send(msg);
})
}
function initSerialMonitor() {
// TODO HID
}
export interface ServeOptions {
localToken: string;
autoStart: boolean;
packaged?: boolean;
browser?: string;
port?: number;
hostname?: string;
wsPort?: number;
serial?: boolean;
noauth?: boolean;
backport?: number;
https?: boolean;
}
// can use http://localhost:3232/streams/nnngzlzxslfu for testing
function streamPageTestAsync(id: string) {
return Cloud.privateGetAsync(id)
.then((info: pxt.streams.JsonStream) => {
let html = pxt.docs.renderMarkdown({
template: expandDocFileTemplate("stream.html"),
markdown: "",
theme: pxt.appTarget.appTheme,
pubinfo: info as any,
filepath: "/" + id
})
return html
})
}
function certificateTestAsync(): Promise<string> {
return Promise.resolve(expandDocFileTemplate("certificates.html"));
}
// use http://localhost:3232/45912-50568-62072-42379 for testing
function scriptPageTestAsync(id: string) {
return Cloud.privateGetAsync(pxt.Cloud.parseScriptId(id))
.then((info: Cloud.JsonScript) => {
// if running against old cloud, infer 'thumb' field
// can be removed after new cloud deployment
if (info.thumb !== undefined)
return info
return Cloud.privateGetTextAsync(id + "/thumb")
.then(_ => {
info.thumb = true
return info
}, _ => {
info.thumb = false
return info
})
})
.then((info: Cloud.JsonScript) => {
let infoA = info as any
infoA.cardLogo = info.thumb
? Cloud.apiRoot + id + "/thumb"
: pxt.appTarget.appTheme.thumbLogo || pxt.appTarget.appTheme.cardLogo
let html = pxt.docs.renderMarkdown({
template: expandDocFileTemplate(pxt.appTarget.appTheme.leanShare
? "leanscript.html" : "script.html"),
markdown: "",
theme: pxt.appTarget.appTheme,
pubinfo: info as any,
filepath: "/" + id
})
return html
});
}
// use http://localhost:3232/pkg/microsoft/pxt-neopixel for testing
function pkgPageTestAsync(id: string) {
return pxt.packagesConfigAsync()
.then(config => pxt.github.repoAsync(id, config))
.then(repo => {
if (!repo)
return "Not found"
return Cloud.privateGetAsync("gh/" + id + "/text")
.then((files: pxt.Map<string>) => {
let info = JSON.parse(files["pxt.json"])
info["slug"] = id
info["id"] = "gh/" + id
if (repo.status == pxt.github.GitRepoStatus.Approved)
info["official"] = "yes"
else
info["official"] = ""
const html = pxt.docs.renderMarkdown({
template: expandDocFileTemplate("package.html"),
markdown: files["README.md"] || "No `README.md`",
theme: pxt.appTarget.appTheme,
pubinfo: info,
filepath: "/pkg/" + id,
repo: { name: repo.name, fullName: repo.fullName, tag: "v" + info.version }
})
return html
})
})
}
function readMdAsync(pathname: string, lang: string): Promise<string> {
if (!lang || lang == "en") {
const content = nodeutil.resolveMd(root, pathname);
if (content) return Promise.resolve(content);
return Promise.resolve(`# Not found ${pathname}\nChecked:\n` + [docsDir].concat(dirs).concat(nodeutil.lastResolveMdDirs).map(s => "* ``" + s + "``\n").join(""));
} else {
// ask makecode cloud for translations
const mdpath = pathname.replace(/^\//, '');
return pxt.Cloud.markdownAsync(mdpath, lang);
}
}
function resolveTOC(pathname: string): pxt.TOCMenuEntry[] {
// find summary.md
let summarydir = pathname.replace(/^\//, '');
let presummarydir = "";
while (summarydir !== presummarydir) {
const summaryf = path.join(summarydir, "SUMMARY");
// find "closest summary"
const summaryMd = nodeutil.resolveMd(root, summaryf)
if (summaryMd) {
try {
return pxt.docs.buildTOC(summaryMd);
} catch (e) {
pxt.log(`invalid ${summaryf} format - ${e.message}`)
pxt.log(e.stack);
}
break;
}
presummarydir = summarydir;
summarydir = path.dirname(summarydir);
}
// not found
pxt.log(`SUMMARY.md not found`)
return undefined;
}
const compiledCache: pxt.Map<string> = {}
export async function compileScriptAsync(id: string) {
if (compiledCache[id])
return compiledCache[id]
const scrText = await Cloud.privateGetAsync(id + "/text")
const res = await pxt.simpleCompileAsync(scrText, {})
let r = ""
if (res.errors)
r = `throw new Error(${JSON.stringify(res.errors)})`
else
r = res.outfiles["binary.js"]
compiledCache[id] = r
return r
}
export function serveAsync(options: ServeOptions) {
serveOptions = options;
if (!serveOptions.port) serveOptions.port = 3232;
if (!serveOptions.wsPort) serveOptions.wsPort = 3233;
if (!serveOptions.hostname) serveOptions.hostname = "localhost";
setupRootDir();
const wsServerPromise = initSocketServer(serveOptions.wsPort, serveOptions.hostname);
if (serveOptions.serial)
initSerialMonitor();
const reqListener: http.RequestListener = async (req, res) => {
const error = (code: number, msg: string = null) => {
res.writeHead(code, { "Content-Type": "text/plain" })
res.end(msg || "Error " + code)
}
const sendJson = (v: any) => {
if (typeof v == "string") {
res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf8' })
res.end(v)
} else {
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf8' })
res.end(JSON.stringify(v))
}
}
const sendHtml = (s: string, code = 200) => {
res.writeHead(code, { 'Content-Type': 'text/html; charset=utf8' })
res.end(s.replace(
/(<img [^>]* src=")(?:\/docs|\.)\/static\/([^">]+)"/g,
function (f, pref, addr) { return pref + '/static/' + addr + '"'; }
))
}
const sendFile = (filename: string) => {
try {
let stat = fs.statSync(filename);
res.writeHead(200, {
'Content-Type': U.getMime(filename),
'Content-Length': stat.size
});
fs.createReadStream(filename).pipe(res);
} catch (e) {
error(404, "File missing: " + filename)
}
}
// Strip /app/hash-sig from URL.
// This can happen when the locally running backend is serving an uploaded target,
// but has been configured to route simulator urls to port 3232.
req.url = req.url.replace(/^\/app\/[0-9a-f]{40}(?:-[0-9a-f]{10})?(.*)$/i, "$1");
let uri = url.parse(req.url);
let pathname = decodeURI(uri.pathname);