-
-
Notifications
You must be signed in to change notification settings - Fork 58
/
Copy pathserver.node.ts
495 lines (386 loc) · 12.6 KB
/
server.node.ts
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
namespace $ {
export class $mol_build_server extends $mol_server {
static trace = false
sync_middleware(
mdl: (
req : typeof $node.express.request ,
res : typeof $node.express.response ,
) => void | boolean
) {
const wrapped = $mol_wire_async(mdl)
return $mol_func_name_from(async (
req : typeof $node.express.request ,
res : typeof $node.express.response ,
next : (err?: unknown) => any
) => {
// const wrapped = $mol_wire_async(mdl)
try {
const stopped = await wrapped(req, res)
if (! stopped) Promise.resolve().then(next)
} catch (error: any) {
if (! this.$.$mol_build_server.trace) {
error.message += '\n' + 'Set $mol_build_server.trace = true for stacktraces'
}
res.status(500).send( error.toString() ).end()
this.$.$mol_log3_fail({
place: `${this}.${mdl.name}()`,
uri: req.path,
stack: this.$.$mol_build_server.trace ? error.stack : undefined,
message: error.message,
})
}
}, mdl)
}
expressGenerator() { return this.sync_middleware(this.handleRequest.bind(this)) }
handleRequest(
req : typeof $node.express.request ,
res : typeof $node.express.response,
) {
try {
// if( req.query._escaped_fragment_ ) {
// const fragment = decodeURIComponent( String( req.query._escaped_fragment_ ) )
// const url = req.protocol + '://' + req.get( 'host' ) + req.path + '#!' + fragment
// const html = $mol_browser.html( url )
// res.send( html ).end()
// return
// }
if (! this.generate( req.url ) ) return false
res.set( 'Cache-Control', 'no-cache, public' )
} catch( error: any ) {
if ($mol_promise_like(error)) $mol_fail_hidden(error)
if (! req.url.match( /\.js$/ ) ) $mol_fail_hidden(error)
this.$.$mol_log3_fail({
place: `${this}.handleRequest()`,
uri: req.path,
message: error.message,
stack: error.stack,
})
const script = ( error as Error ).message.split( '\n\n' ).map( msg => {
return `console.error( ${ JSON.stringify( msg ) } )`
} ).join( '\n' )
res.send( script ).end()
return true
}
}
build() : $mol_build {
return $mol_fail( new Error( 'Not implemented' ) )
}
@ $mol_mem_key
generate( url : string ) {
$mol_wire_solid()
/*
Если использовать динамически подгружаемые через $mol_script модули
То урл тут может быть вида /demo/app/-/node_modules/stockfish/-/stockfish.js
В path должна попасть часть до первого /-/
Динамически подгружаться могут обособленные, редко используемые скрипты.
Например шахматы, встроенные в основное приложение.
У которых здоровый двиг stockfish.js динамически загружается в воркер
только при открытии шахмат.
*/
const matched = url.match( /^(.*?)\/-\/((?:(?:\w+(?:.\w+)+)(?:\/-\/)?)+)$/ )
if( !matched ) return null
const build = this.build()
const [ , rawpath , bundle ] = matched
const mod = build.root().resolve( rawpath )
if( bundle === 'web.css' ) {
this.$.$mol_log3_warn({
place: `${this}.generate()`,
message: 'CSS compiles into JS bundle now',
hint: 'Remove link to web.css',
})
}
const path = mod.path()
this.path_add(path, bundle)
return build.bundle( [ path , bundle ] )
}
override expressIndex() { return this.sync_middleware(this.expressIndexRequest.bind(this)) }
@ $mol_mem_key
protected ensure(path: string) {
$mol_wire_solid()
this.build().modEnsure( path )
}
expressIndexRequest(
req : typeof $node.express.request ,
res : typeof $node.express.response ,
) {
const root = this.$.$mol_file.absolute( this.rootPublic() )
const dir = root.resolve( req.path )
const path = dir.path()
// ensure загружает сорцы, делает git pull, это не стоит делать на build-папках
// Поэтому регулярка выше отсеивает build-папки
this.ensure( path )
// a/b/?c#d, a/b/-/
const match = req.url.match( /(\/|.*[^\-]\/)([\?#].*)?$/ )
if( !match) return
const file = root.resolve( `${req.path}index.html` )
if( file.exists() ) {
res.redirect( 301, `${match[1]}-/test.html${match[2] ?? ''}` )
return true
}
if( dir.type() !== 'dir' ) return
const files = [ {name: '-', type: 'dir'} ]
for( const file of dir.sub() ) {
if (!files.find(( {name} ) => name === file.name())) {
files.push( {name: file.name(), type: file.type()} )
}
if( /\.meta\.tree$/.test( file.name() ) ) {
const meta = this.$.$mol_tree2_from_string( file.text() )
for( const pack of meta.select( 'pack', null ).kids ) {
if ( files.find(( {name} ) => name === pack.type) ) continue
files.push( {name: pack.type, type: 'dir'} )
}
}
}
const html = `
<style>
body {
display: flex;
flex-direction: column;
flex-wrap: wrap;
font: 1rem/1.5rem sans-serif;
height: 100%;
margin: 0;
padding: 0.75rem;
box-sizing: border-box;
}
a {
text-decoration: none;
color: rgb(57, 115, 172);
font-weight: bolder;
}
a:hover {
background: hsl( 0deg, 0%, 0%, .05 )
}
a[href^="."], a[href^="-"], a[href="node_modules"] {
opacity: 0.5;
}
a[href=".."], a[href="-"] {
opacity: 1;
}
</style>
<link href="/_logo.png" rel="icon" />
<a href="..">📁 ..</a>
` + files
.sort($mol_compare_text((item) => item.type))
.map( file => `<a href="${file.name}">${file.type === 'dir' ? '📁' : '📄'} ${file.name}</a>` )
.join( '\n' )
res.writeHead( 200, {
'Content-Type': 'text/html',
'Access-Control-Allow-Origin': '*',
} )
res.end( html )
return true
}
port() {
return 9080
}
@ $mol_mem
lines( next = new Map< InstanceType<$node['ws']['WebSocket']>, string >() ) {
return next
}
@ $mol_mem
socket() {
const build = this.build()
const root = build.root()
return super.socket().on( 'connection' , ( line , req )=> {
const path_relative = req.url!.replace( /\/-.*/ , '' ).substring( 1 )
const path = root.resolve( path_relative ).path()
this.$.$mol_log3_rise({
place: this ,
message: `Connect` ,
path ,
})
this.lines( new Map( [ ... this.lines(), [ line, path ] ] ) )
this.path_add(path, '')
line.on( 'close' , ()=> {
this.path_doubt(path)
const lines = new Map( this.lines() )
lines.delete( line )
this.lines( lines )
} )
} )
}
@ $mol_mem
start() {
this.slave_servers()
this.repl()
const socket = this.socket()
for( const [ line, path ] of this.lines() ) {
this.notify([ line, path ])
}
// this.bundles_keep()
return socket
}
@ $mol_mem
protected bundles_count(reset?: null): number {
return 1 + ( $mol_wire_probe(() => this.bundles_count()) ?? 0 )
}
/**
* Держать в памяти собранные бандлы плохо, т.к. gc их может долго не утилизировать и node сожрет память и упадет.
* Логичнее удалять отложенно, после того как reload-сокет отписался от пути и повторно не подписался.
*/
@ $mol_mem
protected bundles_keep() {
const build = this.build()
this.bundles_count()
for (const [path, bundles] of Object.entries(this.path_bundles)) {
const sources = build.sourcesAll([ path , [ 'node' ] ])
for (const source of sources ) source.version()
for (const bundle of bundles) {
const files = build.bundle([ path, bundle ])
for ( const file of files ) {
file.version()
}
}
}
}
protected path_bundles = {} as Record<string, Set<string>>
protected path_doubted = new Set<string>()
path_add(path: string, bundle: string) {
return
this.path_doubted.delete(path)
if (! this.path_bundles[path]) this.path_bundles[path] = new Set()
this.path_bundles[path].add(bundle)
this.bundles_count(null)
}
protected path_doubt_timeout = null as null | $mol_after_timeout
path_doubt(path: string) {
this.path_doubted.add(path)
if ( this.path_doubt_timeout) return
this.path_doubt_timeout = new this.$.$mol_after_timeout(
15000,
() => $mol_wire_async(this).path_doubted_remove()
)
}
path_doubted_remove() {
for (const path of this.path_doubted) {
delete this.path_bundles[path]
}
this.path_doubt_timeout = null
this.path_doubted.clear()
this.bundles_count(null)
}
@ $mol_mem_key
bundle_changed_at( path: string ) {
const build = this.build()
try {
const sources = build.sourcesAll([ path , [ 'node' ] ])
/**
Бывает надо какой-то внешней программой в watch-режиме компилить js-ки или wasm
и класть как артефакт в - (например, игровой движок на unity)
При изменении этих файлов, надо перезапускать страницу.
Если их класть не в -, а рядом с сорцами, то билдер mol будет пытаться их анализировать и упадет.
*/
const resources = build.bundleFiles([ path , [ 'node' ] ])
for( const src of [...sources, ...resources] ) src.version()
} catch (error) {
if ($mol_fail_catch(error)) {
this.$.$mol_log3_fail({
place: `${this}.notify`,
message: (error as Error)?.message,
path,
})
}
}
return new Date()
}
@ $mol_mem_key
notify( [ line, path ]: [ InstanceType<$node['ws']['WebSocket']>, string ] ) {
this.bundle_changed_at(path)
// ignore initial
if( !$mol_mem_cached( ()=> this.notify([ line, path ]) ) ) return true
this.$.$mol_log3_rise({
place: `${this}`,
message: `$mol_build_obsolete`,
path
})
line.send( '$mol_build_obsolete' )
return true
}
@ $mol_mem
slave_commands( next = [] as string[] ) {
return next
}
@ $mol_mem
slave_servers() {
return this.slave_commands().map( cmd => this.slave_server( cmd ) )
}
@ $mol_mem_key
slave_server( cmd: string ) {
const [ path, ... args ] = cmd.split( ' ' )
const command = `node ./${path}/-/node.js ${args.join(' ')}`
const prev = $mol_wire_probe( ()=> this.slave_server( cmd ) )
if( prev ) prev.destructor()
const build = this.build()
try {
for( const file of build.bundle([ path, 'node.js' ]) ) file.version()
for( const file of build.bundle([ path, 'node.audit.js' ]) ) file.version()
for( const file of build.bundle([ path, 'node.test.js' ]) ) file.version()
} catch( error: any ) {
if ($mol_fail_catch(error)) {
this.$.$mol_log3_fail({
place: `${this}.slave_server`,
stack: error.stack,
message: error.message ?? error,
})
}
return null
}
this.$.$mol_log3_come({
place: this,
message: 'Start',
command ,
})
const server = $node['child_process'].spawn(
'node',
[ '--enable-source-maps', '--trace-uncaught', `./${path}/-/node.js`, ... args ],
{
stdio: [ 'pipe', 'inherit', 'inherit' ],
}
)
return Object.assign( server, {
destructor: ()=> {
if( server.killed ) return
server.kill()
this.$.$mol_log3_done({
place: this,
message: 'Stopped',
command ,
})
}
} )
}
@ $mol_mem
repl() {
const terminal = $node.readline.createInterface({
input: process.stdin,
output: process.stdout,
history: [],
tabSize: 4,
prompt: '',
})
terminal.prompt()
const hint = 'start: + path/to/module args\nstop: - path/to/module args'
terminal
.on( 'line', line => {
if( !line.trim() ) return
const [ action, ... params ] = line.split( ' ' )
const command = params.join(' ')
switch( action ) {
case '+': return this.slave_commands([ ... this.slave_commands(), command ])
case '-': return this.slave_commands( this.slave_commands().filter( cmd => cmd !== command ) )
case '?':
default: return console.log( hint )
}
})
.on( 'SIGINT', () => process.exit(0) )
.on( 'close', () => process.exit(0) )
// this.$.$mol_log3_done({
// place: this,
// message: 'Watch dog started',
// hint,
// })
return terminal
}
}
}