This commit is contained in:
Eugene Pankov
2021-06-15 23:43:23 +02:00
parent e1425c6c80
commit 15d1fe4a46
17 changed files with 276 additions and 1031 deletions

View File

@@ -3,6 +3,7 @@ import { NgbDropdownModule } from '@ng-bootstrap/ng-bootstrap'
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { HttpClientModule, HttpClientXsrfModule } from '@angular/common/http'
import { FontAwesomeModule } from '@fortawesome/angular-fontawesome'
import { AppComponent } from './components/app.component'
@NgModule({
@@ -12,6 +13,7 @@ import { AppComponent } from './components/app.component'
HttpClientModule,
HttpClientXsrfModule,
NgbDropdownModule,
FontAwesomeModule,
],
declarations: [
AppComponent,

View File

@@ -1,15 +1,55 @@
.sidebar
img.logo(src='{{_logo}}')
div(ngbDropdown)
button.btn.btn-secondary(ngbDropdownToggle) Cfg
//) !{require('../icons/download-solid.svg')}
div(ngbDropdownMenu)
a(
*ngFor='let config of configs',
ngbDropdownItem,
(click)='selectConfig(config)'
) Config modified at {{config.modified_at}}
div(ngbDropdown, placement='bottom-right')
button.btn.btn-secondary(ngbDropdownToggle)
fa-icon([icon]='_cogIcon', [fixedWidth]='true')
.terminal([hidden]='!showApp')
.config-menu(ngbDropdownMenu)
.header(*ngIf='getActiveConfig()')
.dropdown-header Active config
.title {{getActiveConfig().modified_at}}
div(*ngIf='activeVersion')
div App version:
div(ngbDropdown)
button.btn.btn-secondary(ngbDropdownToggle) {{activeVersion.version}}
div(ngbDropdownMenu)
a(
*ngFor='let version of versions',
ngbDropdownItem,
[class.active]='version == activeVersion',
(click)='selectVersion(version)'
) {{version.version}}
.btn-toolbar
button.btn.btn-light.w-50((click)='duplicateConfig()')
fa-icon([icon]='_copyIcon', [fixedWidth]='true')
span Duplicate
button.btn.btn-light.w-50((click)='deleteConfig()')
fa-icon([icon]='_deleteIcon', [fixedWidth]='true')
span Delete
div(*ngIf='configs.length > 1')
.dropdown-header All configs
ng-container(*ngFor='let config of configs')
a(
*ngIf='config !== getActiveConfig()',
ngbDropdownItem,
(click)='selectConfig(config)'
) Config modified at {{config.modified_at}}
button.btn.btn-light.w-100((click)='createNewConfig()')
fa-icon([icon]='_addIcon', [fixedWidth]='true')
span New config
div(ngbDropdown, placement='bottom-right')
button.btn.btn-secondary(ngbDropdownToggle)
fa-icon([icon]='_userIcon', [fixedWidth]='true')
div(ngbDropdownMenu)
a(ngbDropdownItem, (click)='logout()') Logout
.terminal([hidden]='!activeVersion')
iframe(#iframe)

View File

@@ -32,3 +32,10 @@ iframe {
height: 100%;
border: none;
}
.config-menu {
.header {
border-bottom: 1px solid black;
}
}

View File

@@ -1,7 +1,10 @@
import * as semverGT from 'semver/functions/gt'
import { Component, ElementRef, ViewChild } from '@angular/core'
import { HttpClient } from '@angular/common/http'
import { AppConnectorService } from '../services/appConnector.service'
import { faCog, faUser, faCopy, faTrash, faPlus } from '@fortawesome/free-solid-svg-icons'
@Component({
selector: 'app',
templateUrl: './app.component.pug',
@@ -9,8 +12,15 @@ import { AppConnectorService } from '../services/appConnector.service'
})
export class AppComponent {
_logo = require('../assets/logo.svg')
showApp = false
_cogIcon = faCog
_userIcon = faUser
_copyIcon = faCopy
_addIcon = faPlus
_deleteIcon = faTrash
configs: any[] = []
versions: any[] = []
activeVersion?: any
@ViewChild('iframe') iframe: ElementRef
constructor (
@@ -27,24 +37,69 @@ export class AppComponent {
async ngAfterViewInit () {
this.configs = await this.http.get('/api/1/configs').toPromise()
this.versions = await this.http.get('/api/1/versions').toPromise()
this.versions.sort((a, b) => semverGT(a, b))
if (!this.configs.length) {
await this.createNewConfig()
}
this.selectConfig(this.configs[0])
}
async createNewConfig () {
this.configs.push(await this.http.post('/api/1/configs', {
content: '{}',
last_used_with_version: this.versions[0].version,
}).toPromise())
}
async duplicateConfig () {
const copy = {...this.appConnector.config, pk: undefined}
this.configs.push(await this.http.post('/api/1/configs', copy).toPromise())
}
unloadApp () {
this.showApp = false
delete this.activeVersion
this.iframe.nativeElement.src = 'about:blank'
}
loadApp () {
this.iframe.nativeElement.src = '/terminal'
this.showApp = true
loadApp (version) {
this.iframe.nativeElement.src = `/terminal?${version.version}`
this.activeVersion = version
}
selectConfig (config: any) {
this.appConnector.config = config
getActiveConfig () {
return this.appConnector.config
}
selectVersion (version: any) {
// TODO check config incompatibility
this.unloadApp()
setTimeout(() => {
this.loadApp()
this.loadApp(version)
})
}
async selectConfig (config: any) {
let matchingVersion = this.versions.find(x => x.version === config.last_used_with_version)
if (!matchingVersion) {
// TODO ask to upgrade
matchingVersion = this.versions[0]
}
this.appConnector.config = config
const result = await this.http.patch(`/api/1/configs/${config.id}`, {
last_used_with_version: matchingVersion.version,
}).toPromise()
Object.assign(config, result)
this.selectVersion(matchingVersion)
}
async logout () {
await this.http.post('/api/1/auth/logout', null).toPromise()
}
}

View File

@@ -1,202 +0,0 @@
// Based on http://stackoverflow.com/a/22747272/680742, the browser with
// the lowest limit is Chrome, with 0x10000 args.
// We go 1 magnitude less, for safety
const MAX_ARGUMENTS_LENGTH = 0x1000
const base64 = require('base64-js')
function blitBuffer(src, dst, offset, length) {
let i
for (i = 0; i < length; ++i) {
if ((i + offset >= dst.length) || (i >= src.length)) break
dst[i + offset] = src[i]
}
return i
}
export function utf8Write(string, offset, length) {
return blitBuffer(utf8ToBytes(string, this.length - offset), this, offset, length)
}
export function base64Slice(start, end) {
if (start === 0 && end === this.length) {
return base64.fromByteArray(this)
} else {
return base64.fromByteArray(this.slice(start, end))
}
}
function decodeCodePointsArray(codePoints) {
const len = codePoints.length
if (len <= MAX_ARGUMENTS_LENGTH) {
return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
}
// Decode in chunks to avoid "call stack size exceeded".
let res = ''
let i = 0
while (i < len) {
res += String.fromCharCode.apply(
String,
codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
)
}
return res
}
export function latin1Slice(start, end) {
let ret = ''
end = Math.min(this.length, end)
for (var i = start; i < end; ++i) {
ret += String.fromCharCode(this[i])
}
return ret
}
export function utf8Slice(this, start, end) {
end = Math.min(this.length, end)
const res = []
let i = start
while (i < end) {
const firstByte = this[i]
let codePoint = null
let bytesPerSequence = (firstByte > 0xEF) ? 4 : (firstByte > 0xDF) ? 3 : (firstByte > 0xBF) ? 2 : 1
if (i + bytesPerSequence <= end) {
let secondByte, thirdByte, fourthByte, tempCodePoint
switch (bytesPerSequence) {
case 1:
if (firstByte < 0x80) {
codePoint = firstByte
}
break
case 2:
secondByte = this[i + 1]
if ((secondByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
if (tempCodePoint > 0x7F) {
codePoint = tempCodePoint
}
}
break
case 3:
secondByte = this[i + 1]
thirdByte = this[i + 2]
if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
codePoint = tempCodePoint
}
}
break
case 4:
secondByte = this[i + 1]
thirdByte = this[i + 2]
fourthByte = this[i + 3]
if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
codePoint = tempCodePoint
}
}
}
}
if (codePoint === null) {
// we did not generate a valid codePoint so insert a
// replacement char (U+FFFD) and advance only 1 byte
codePoint = 0xFFFD
bytesPerSequence = 1
} else if (codePoint > 0xFFFF) {
// encode to utf16 (surrogate pair dance)
codePoint -= 0x10000
res.push(codePoint >>> 10 & 0x3FF | 0xD800)
codePoint = 0xDC00 | codePoint & 0x3FF
}
res.push(codePoint)
i += bytesPerSequence
}
return decodeCodePointsArray(res)
}
function utf8ToBytes(string, units) {
units = units || Infinity
let codePoint
const length = string.length
let leadSurrogate = null
const bytes = []
for (let i = 0; i < length; ++i) {
codePoint = string.charCodeAt(i)
// is surrogate component
if (codePoint > 0xD7FF && codePoint < 0xE000) {
// last char was a lead
if (!leadSurrogate) {
// no lead yet
if (codePoint > 0xDBFF) {
// unexpected trail
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
continue
} else if (i + 1 === length) {
// unpaired lead
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
continue
}
// valid lead
leadSurrogate = codePoint
continue
}
// 2 leads in a row
if (codePoint < 0xDC00) {
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
leadSurrogate = codePoint
continue
}
// valid surrogate pair
codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
} else if (leadSurrogate) {
// valid bmp char, but last char was a lead
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
}
leadSurrogate = null
// encode utf8
if (codePoint < 0x80) {
if ((units -= 1) < 0) break
bytes.push(codePoint)
} else if (codePoint < 0x800) {
if ((units -= 2) < 0) break
bytes.push(
codePoint >> 0x6 | 0xC0,
codePoint & 0x3F | 0x80
)
} else if (codePoint < 0x10000) {
if ((units -= 3) < 0) break
bytes.push(
codePoint >> 0xC | 0xE0,
codePoint >> 0x6 & 0x3F | 0x80,
codePoint & 0x3F | 0x80
)
} else if (codePoint < 0x110000) {
if ((units -= 4) < 0) break
bytes.push(
codePoint >> 0x12 | 0xF0,
codePoint >> 0xC & 0x3F | 0x80,
codePoint >> 0x6 & 0x3F | 0x80,
codePoint & 0x3F | 0x80
)
} else {
throw new Error('Invalid code point')
}
}
return bytes
}

View File

@@ -9,8 +9,9 @@ export class AppConnectorService {
private configUpdate = new Subject<string>()
constructor (private http: HttpClient) {
this.configUpdate.pipe(debounceTime(1000)).subscribe(content => {
this.http.patch(`/api/1/configs/${this.config.id}`, { content }).toPromise()
this.configUpdate.pipe(debounceTime(1000)).subscribe(async content => {
const result = await this.http.patch(`/api/1/configs/${this.config.id}`, { content }).toPromise()
Object.assign(this.config, result)
})
}
@@ -20,5 +21,6 @@ export class AppConnectorService {
async saveConfig (content: string): Promise<void> {
this.configUpdate.next(content)
this.config.content = content
}
}

View File

@@ -15,17 +15,7 @@ Object.assign(window, {
})
import * as angularCoreModule from '@angular/core'
import * as angularCompilerModule from '@angular/compiler'
import * as angularCommonModule from '@angular/common'
import * as angularFormsModule from '@angular/forms'
import * as angularPlatformBrowserModule from '@angular/platform-browser'
import * as angularPlatformBrowserAnimationsModule from '@angular/platform-browser/animations'
import * as angularPlatformBrowserDynamicModule from '@angular/platform-browser-dynamic'
import * as angularAnimationsModule from '@angular/animations'
import * as ngBootstrapModule from '@ng-bootstrap/ng-bootstrap'
import * as ngxToastrModule from 'ngx-toastr'
import { Duplex } from 'stream-browserify'
import 'core-js/proposals/reflect-metadata'
import '@fortawesome/fontawesome-free/css/solid.css'
@@ -33,11 +23,8 @@ import '@fortawesome/fontawesome-free/css/brands.css'
import '@fortawesome/fontawesome-free/css/fontawesome.css'
import 'source-code-pro/source-code-pro.css'
import 'source-sans-pro/source-sans-pro.css'
import { Duplex } from 'stream-browserify'
import { Buffer } from 'buffer'
import './terminal-styles.scss'
import { base64Slice, latin1Slice, utf8Slice, utf8Write } from './polyfills'
export class Socket extends Duplex {
webSocket: WebSocket
@@ -90,55 +77,8 @@ export class Socket extends Duplex {
}
async function start () {
class Logger {
constructor () {
for (let x of ['info', 'warn', 'error', 'log', 'debug']) {
this[x] = () => null
}
}
}
const mocks = {
fs: {
realpathSync: path => {
console.warn('mock realPathSync', path)
return path
},
existsSync: path => {
console.warn('mock existsSync', path)
return false
},
readdir: () => null,
stat: () => null,
mkdir: path => {
console.warn('mock mkdir', path)
},
mkdirSync: path => {
console.warn('mock mkdirSync', path)
},
writeFileSync: () => null,
readFileSync: (path) => {
return ''
},
readFile: (path, enc, cb) => {
console.warn('mock readFile', path)
cb('UNKNOWN', null)
},
// readdir: (path, cb) => {
// if (path === 'resources/builtin-plugins') {
// cb(null, [
// 'terminus-core',
// 'terminus-ssh',
// 'terminus-settings',
// 'terminus-terminal',
// ])
// } else {
// console.warn('mock readdir', path)
// cb(null, [])
// }
// },
constants: {},
},
'@electron/remote': {
app: {
getVersion: () => '1.0-web',
@@ -174,7 +114,7 @@ async function start () {
getGlobal: () => window['process'],
},
electron: {
ipcRenderer: {
ipcRenderer: { // TODO remove
on: (e, c) => {
console.log('[ipc listen]', e)
},
@@ -186,125 +126,28 @@ async function start () {
}
},
},
path: {
join: (...x) => x.join('/'),
basename: x => x,
dirname: x => x,
relative: (a, b) => b,
resolve: (a, b) => {
console.warn('mock path.resolve', a, b)
return b
}
},
buffer: {
Buffer,
},
crypto: {
...require('crypto-browserify'),
getHashes () {
return ['sha1', 'sha224', 'sha256', 'sha384', 'sha512', 'md5', 'rmd160']
},
timingSafeEqual (a, b) {
return a.equals(b)
},
},
events: require('events'),
readline: {
cursorTo: () => null,
clearLine: stream => stream.write('\r'),
},
zlib: {
...require('browserify-zlib'),
constants: require('browserify-zlib'),
},
'any-promise': Promise,
net: {
Socket,
},
tls: { },
module: {
globalPaths: [],
},
assert: require('assert'),
url: {
parse: () => null,
},
http: {
Agent: class {},
request: {},
},
https: {
Agent: class {},
request: {},
},
querystring: {},
tty: { isatty: () => false },
child_process: {},
winston: {
Logger,
transports: {
File: Object,
Console: Object,
}
},
'readable-stream': {},
os: {
platform: () => 'web',
homedir: () => '/home',
},
'mz/child_process': {
exec: (...x) => Promise.reject(),
},
'mz/fs': {
readFile: path => mocks.fs.readFileSync(path),
exists: path => mocks.fs.existsSync(path),
existsSync: path => mocks.fs.existsSync(path),
},
constants: require('constants-browserify'),
'hterm-umdjs': {
hterm: {
PreferenceManager: class { set () {} },
VT: {
ESC: {},
CSI: {},
OSC: {},
},
Terminal: class {},
Keyboard: class {},
},
lib: {
wc: {},
Storage: {
Memory: class {},
},
},
},
dns: {},
util: require('util/'),
keytar: {
getPassword: () => null,
},
// winston: {
// Logger,
// transports: {
// File: Object,
// Console: Object,
// }
// },
// 'mz/child_process': {
// exec: (...x) => Promise.reject(),
// },
// 'mz/fs': {
// readFile: path => mocks.fs.readFileSync(path),
// exists: path => mocks.fs.existsSync(path),
// existsSync: path => mocks.fs.existsSync(path),
// },
}
;(mocks.assert as any).assertNotStrictEqual = () => true
;(mocks.assert as any).notStrictEqual = () => true
let builtins = {
'@angular/core': angularCoreModule,
'@angular/compiler': angularCompilerModule,
'@angular/common': angularCommonModule,
'@angular/forms': angularFormsModule,
'@angular/platform-browser': angularPlatformBrowserModule,
'@angular/platform-browser/animations': angularPlatformBrowserAnimationsModule,
'@angular/platform-browser-dynamic': angularPlatformBrowserDynamicModule,
'@angular/animations': angularAnimationsModule,
'@ng-bootstrap/ng-bootstrap': ngBootstrapModule,
'ngx-toastr': ngxToastrModule,
'deepmerge': require('deepmerge'),
'rxjs': require('rxjs'),
'rxjs/operators': require('rxjs/operators'),
'js-yaml': require('js-yaml'),
'zone.js/dist/zone.js': require('zone.js/dist/zone.js'),
}
Object.assign(window, {
@@ -320,31 +163,11 @@ async function start () {
},
})
window['require'].main = {
paths: []
} as any
window['module'] = {
paths: []
} as any
window['require'].resolve = (path => null) as any
window['Buffer'] = mocks.buffer.Buffer
window['__dirname'] = '__dirname'
window['setImmediate'] = setTimeout as any
mocks.module['prototype'] = { require: window['require'] }
Buffer.prototype['latin1Slice'] = latin1Slice
Buffer.prototype['utf8Slice'] = utf8Slice
Buffer.prototype['base64Slice'] = base64Slice
Buffer.prototype['utf8Write'] = utf8Write
builtins['ssh2'] = require('ssh2')
builtins['ssh2/lib/protocol/constants'] = require('ssh2/lib/protocol/constants')
builtins['stream'] = require('stream-browserify')
const appVersion = location.search.substring(1)
async function loadPlugin (name, file = 'index.js') {
const url = `../app-dist/${name}/dist/${file}`
const url = `../app-dist/${appVersion}/${name}/dist/${file}`
console.log(`Loading ${url}`)
const e = document.createElement('script')
window['module'] = { exports: {} } as any
window['exports'] = window['module'].exports
@@ -356,6 +179,9 @@ async function start () {
return window['module'].exports
}
await loadPlugin('web', 'preload.js')
await loadPlugin('web', 'bundle.js')
const pluginModules = []
for (const plugin of [
'terminus-core',
@@ -365,14 +191,11 @@ async function start () {
'terminus-community-color-schemes',
'terminus-web',
]) {
console.log(`Loading ${plugin}`)
const mod = await loadPlugin(plugin)
builtins[`resources/builtin-plugins/${plugin}`] = builtins[plugin] = mod
pluginModules.push(mod)
}
await loadPlugin('app', 'preload.js')
await loadPlugin('app', 'bundle-web.js')
document.querySelector('app-root')['style'].display = 'flex'
await new Promise<void>(resolve => {