-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
StudioServerApp.js
executable file
·180 lines (149 loc) · 5.24 KB
/
StudioServerApp.js
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
#! /usr/local/bin/node
const express = require("express")
const bodyParser = require("body-parser")
const glob = require("glob")
const fs = require("fs")
const { jtree } = require("jtree")
const StudioServerAppConstants = {}
StudioServerAppConstants.routeFileGlob = "/*/*.routes.js"
StudioServerAppConstants.ohayoPackagesFolder = "/ohayo/packages/"
class StudioServerApp {
constructor(port = 1111, cwd = process.cwd(), hostname = "localhost", protocol = "http") {
this._cwd = cwd.replace(/\/$/, "") + "/"
this._port = port
this._hostname = hostname
this._protocol = protocol
this._verboseOn = true
}
getCwd() {
return this._cwd
}
get app() {
if (!this._app) this._initApp()
return this._app
}
_addCurrentWorkingDirectory(content, cwd) {
return content.replace(`const DefaultServerCurrentWorkingDirectory = "/"`, `const isConnectedToStudioServerApp = true;\nconst DefaultServerCurrentWorkingDirectory = "${cwd}"`)
}
_getPackageDirectories() {
return [__dirname + StudioServerAppConstants.ohayoPackagesFolder]
}
_getStaticRoutes() {
// this dir and whatever folder someone started it in for plugins
return [__dirname + "/", this.getCwd()]
}
_initApp() {
const app = express()
this._app = app
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
app.cwd = this.getCwd()
this._addHomeRoute()
this._addOtherRoutes()
this._getStaticRoutes().forEach(path => this._initStaticRoute(path))
// Load: standard. node_modules. custom-packages.
this._getPackageDirectories().forEach(dir => this._initPackageFolder(dir))
return app
}
_addOtherRoutes() {}
_initStaticRoute(path) {
this.app.use(
"/",
express.static(path, {
maxAge: 31557600000
})
)
}
_verbose(msg) {
if (this._verboseOn) console.log(msg)
}
_initPackageFolder(folder) {
this._verbose(`Loading folder ${folder}...`)
// todo: don't recurse.
jtree.Utils.flatten(glob.sync(folder + StudioServerAppConstants.routeFileGlob)).forEach(filePath => {
this._verbose(`Loading package ${filePath}...`)
require(filePath)(this.app)
})
}
_getUrlBase() {
return `${this._protocol}://${this._hostname}:${this._port}/`
}
_getHomePage() {
return "index.html"
}
_addHomeRoute() {
this.app.get("/" + this._getHomePage(), (req, res) => {
// Avoid cacheing
res.send(this._addCurrentWorkingDirectory(fs.readFileSync(__dirname + "/" + this._getHomePage(), "utf8"), this.getCwd()))
})
}
start() {
this.app.listen(this._port, () => {
console.log(`Running ${this.constructor.name} in folder '${this.getCwd()}'. cmd+dblclick: ${this._getUrlBase()}${this._getHomePage()}`)
})
}
}
class DevServer extends StudioServerApp {
_onFileChange(event, filename) {
return "todo: restore"
const { Builder } = require("./builder.ts")
// Note: if this ever becomes a load problem we can look for changes
// Note: do we want this? What if it fails? What if its partial?
if (filename.includes("node_modules/") || filename.includes("ignore/")) return true
console.log(`Changes to 'studio/${filename}' detected. Building dev.html...`)
new Builder().produceDevHtml()
}
listenForFileChanges() {
fs.watch("studio/", { recursive: true }, (event, filename) => this._onFileChange(event, filename))
fs.watch("ohayo/", { recursive: true }, (event, filename) => this._onFileChange(event, filename))
return this
}
_getHomePage() {
return "dev.html"
}
_addOtherRoutes() {
const sendDevMessage = (req, res) => res.send(`This is dev server. Visit ${this._getHomePage()} instead.`)
this.app.get("/devWithLocalStorage.html", (req, res) => {
res.send(fs.readFileSync(__dirname + "/" + this._getHomePage(), "utf8"))
})
this.app.get("/index.html", sendDevMessage)
this.app.get("/", sendDevMessage)
const { TypeScriptRewriter } = require("jtree/products/TypeScriptRewriter.js")
// todo; cleanup
const treeFiles = "Studio.drums challenges.tree Templates.stamp".split(" ")
treeFiles.forEach(name => {
this.app.get(new RegExp(`.*/${name}`), (req, res) => {
const filename = __dirname + req.path
fs.readFile(filename, "utf8", (err, file) => {
res.send(TypeScriptRewriter.treeToJs(filename, file))
})
})
})
// todo: cleanup
const serveDevFile = (req, res, next) => {
const filename = __dirname + req.path
fs.readFile(filename, "utf8", (err, file) => {
if (err) {
console.log(err)
return res.status(400).send(err)
} else if (filename.endsWith(".js") && !filename.endsWith("min.js")) {
res.send(
new TypeScriptRewriter(file)
.removeRequires()
.changeNodeExportsToWindowExports()
.changeDefaultExportsToWindowExports()
.removeTsGeneratedCrap()
.removeNodeJsOnly()
.removeImports()
.removeExports()
.addUseStrictIfNotPresent()
.getString()
)
} else res.send(file)
})
}
this.app.get(/.*(studio|ohayo)\/.*\.(js)/, serveDevFile)
return this
}
}
module.exports = { StudioServerApp, DevServer }