1
0
mirror of https://github.com/sasjs/server.git synced 2025-12-10 19:34:34 +00:00

chore(merge): Merge branch 'master' into authentication-with-jwt

This commit is contained in:
Saad Jutt
2021-11-09 18:24:35 +05:00
83 changed files with 43080 additions and 10960 deletions

View File

@@ -4,7 +4,7 @@ on:
pull_request:
jobs:
build:
lint:
runs-on: ubuntu-latest
strategy:
@@ -21,10 +21,32 @@ jobs:
- name: Install Dependencies
run: npm ci
- name: Check Code Style
run: npm run lint
- name: Check Api Code Style
run: npm run lint-api
- name: Check Web Code Style
run: npm run lint-web
build-api:
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [12.x]
steps:
- uses: actions/checkout@v2
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v1
with:
node-version: ${{ matrix.node-version }}
- name: Install Dependencies
working-directory: ./api
run: npm ci
- name: Run Unit Tests
working-directory: ./api
run: npm test
env:
CI: true
@@ -33,6 +55,36 @@ jobs:
AUTH_CODE_SECRET: ${{secrets.AUTH_CODE_SECRET}}
- name: Build Package
run: npm run package:lib
working-directory: ./api
run: npm run build
env:
CI: true
build-web:
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [12.x]
steps:
- uses: actions/checkout@v2
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v1
with:
node-version: ${{ matrix.node-version }}
- name: Install Dependencies
working-directory: ./web
run: npm ci
# TODO: Uncomment next step when unit tests provided
# - name: Run Unit Tests
# working-directory: ./web
# run: npm test
- name: Build Package
working-directory: ./web
run: npm run build
env:
CI: true

25065
api/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

65
api/package.json Normal file
View File

@@ -0,0 +1,65 @@
{
"name": "api",
"version": "0.0.1",
"description": "Api of SASjs server",
"main": "./src/server.ts",
"scripts": {
"prestart": "npm run swagger",
"start": "nodemon ./src/server.ts",
"start:prod": "nodemon ./src/prod-server.ts",
"build": "rimraf build && tsc",
"swagger": "tsoa spec",
"semantic-release": "semantic-release -d",
"prepare": "[ -d .git ] && git config core.hooksPath ./.git-hooks || true",
"test": "mkdir -p tmp && mkdir -p ../web/build && jest --coverage",
"lint:fix": "npx prettier --write \"src/**/*.{ts,tsx,js,jsx,html,css,sass,less,yml,md,graphql}\"",
"lint": "npx prettier --check \"src/**/*.{ts,tsx,js,jsx,html,css,sass,less,yml,md,graphql}\"",
"package:lib": "npm run build && cp ./package.json build && cp README.md build && cd build && npm version \"5.0.0\" && npm pack"
},
"release": {
"branches": [
"master"
]
},
"author": "Analytium Ltd",
"dependencies": {
"@sasjs/utils": "^2.23.3",
"bcryptjs": "^2.4.3",
"express": "^4.17.1",
"joi": "^17.4.2",
"jsonwebtoken": "^8.5.1",
"mongoose": "^6.0.12",
"mongoose-sequence": "^5.3.1",
"morgan": "^1.10.0",
"multer": "^1.4.3",
"swagger-ui-express": "^4.1.6",
"tsoa": "^3.14.0"
},
"devDependencies": {
"@types/bcryptjs": "^2.4.2",
"@types/express": "^4.17.12",
"@types/jest": "^26.0.24",
"@types/jsonwebtoken": "^8.5.5",
"@types/mongoose-sequence": "^3.0.6",
"@types/morgan": "^1.9.3",
"@types/multer": "^1.4.7",
"@types/node": "^15.12.2",
"@types/supertest": "^2.0.11",
"@types/swagger-ui-express": "^4.1.3",
"dotenv": "^10.0.0",
"jest": "^27.0.6",
"mongodb-memory-server": "^8.0.0",
"nodemon": "^2.0.7",
"prettier": "^2.3.1",
"rimraf": "^3.0.2",
"semantic-release": "^17.4.3",
"supertest": "^6.1.3",
"ts-jest": "^27.0.3",
"ts-node": "^10.0.0",
"typescript": "^4.3.2"
},
"configuration": {
"sasPath": "/opt/sas/sas9/SASHome/SASFoundation/9.4/sas",
"sasJsPort": 5000
}
}

View File

@@ -2,6 +2,7 @@ import express from 'express'
import morgan from 'morgan'
import webRouter from './routes/web'
import apiRouter from './routes/api'
import { getWebBuildFolderPath } from './utils'
const app = express()
@@ -11,5 +12,8 @@ app.use(express.static('public'))
app.use('/', webRouter)
app.use('/SASjsApi', apiRouter)
app.use(express.json({ limit: '50mb' }))
app.use(express.static(getWebBuildFolderPath()))
export default app

View File

@@ -1,4 +1,5 @@
import { Security, Route, Tags, Example, Post, Body, Response } from 'tsoa'
import { fileExists, readFile, createFile } from '@sasjs/utils'
import { createFileTree, getTreeExample } from '.'
import { FileTree, isFileTree } from '../types'
@@ -33,7 +34,7 @@ const execErrorResponse: DeployResponse = {
@Security('bearerAuth')
@Route('SASjsApi/drive')
@Tags('Drive')
export default class DriveController {
export class DriveController {
/**
* Creates/updates files within SASjs Drive using provided payload.
*
@@ -45,6 +46,22 @@ export default class DriveController {
public async deploy(@Body() body: DeployPayload): Promise<DeployResponse> {
return deploy(body)
}
async readFile(filePath: string) {
await this.validateFilePath(filePath)
return await readFile(filePath)
}
async updateFile(filePath: string, fileContent: string) {
await this.validateFilePath(filePath)
return await createFile(filePath, fileContent)
}
private async validateFilePath(filePath: string) {
if (!(await fileExists(filePath))) {
throw 'DriveController: File does not exists.'
}
}
}
const deploy = async (data: DeployPayload) => {

View File

@@ -1,11 +1,13 @@
import path from 'path'
import fs from 'fs'
import { getSessionController } from './'
import { readFile, fileExists, createFile } from '@sasjs/utils'
import path from 'path'
import { configuration } from '../../package.json'
import { promisify } from 'util'
import { execFile } from 'child_process'
import { Session } from '../types'
import { generateFileUploadSasCode } from '../utils'
import { Session, TreeNode } from '../types'
import { generateFileUploadSasCode, getTmpFilesFolderPath } from '../utils'
const execFilePromise = promisify(execFile)
export class ExecutionController {
@@ -109,4 +111,41 @@ ${webout}
return Promise.resolve(jsonResult || webout)
}
buildDirectorytree() {
const root: TreeNode = {
name: 'files',
relativePath: '',
absolutePath: getTmpFilesFolderPath(),
children: []
}
const stack = [root]
while (stack.length) {
const currentNode = stack.pop()
if (currentNode) {
const children = fs.readdirSync(currentNode.absolutePath)
for (let child of children) {
const absoluteChildPath = `${currentNode.absolutePath}/${child}`
const relativeChildPath = `${currentNode.relativePath}/${child}`
const childNode: TreeNode = {
name: child,
relativePath: relativeChildPath,
absolutePath: absoluteChildPath,
children: []
}
currentNode.children.push(childNode)
if (fs.statSync(childNode.absolutePath).isDirectory()) {
stack.push(childNode)
}
}
}
}
return root
}
}

View File

@@ -1,4 +1,5 @@
export * from './deploy'
export * from './drive'
export * from './Session'
export * from './Execution'
export * from './FileUploadController'

View File

@@ -0,0 +1,74 @@
import express from 'express'
import path from 'path'
import {
DriveController,
ExecutionController
} from '../../controllers'
import { isFileQuery } from '../../types'
import { getTmpFilesFolderPath } from '../../utils'
const driveRouter = express.Router()
driveRouter.post('/deploy', async (req, res) => {
const controller = new DriveController()
try {
const response = await controller.deploy(req.body)
res.send(response)
} catch (err: any) {
const statusCode = err.code
delete err.code
res.status(statusCode).send(err)
}
})
driveRouter.get('/file', async (req, res) => {
if (isFileQuery(req.query)) {
const filePath = path
.join(getTmpFilesFolderPath(), req.query.filePath)
.replace(new RegExp('/', 'g'), path.sep)
await new DriveController()
.readFile(filePath)
.then((fileContent) => {
res.status(200).send({ status: 'success', fileContent: fileContent })
})
.catch((err) => {
res.status(400).send({
status: 'failure',
message: 'File request failed.',
...(typeof err === 'object' ? err : { details: err })
})
})
} else {
res.status(400).send({
status: 'failure',
message: 'Invalid Request: Expected parameter filePath was not provided'
})
}
})
driveRouter.patch('/file', async (req, res) => {
const filePath = path
.join(getTmpFilesFolderPath(), req.body.filePath)
.replace(new RegExp('/', 'g'), path.sep)
await new DriveController()
.updateFile(filePath, req.body.fileContent)
.then(() => {
res.status(200).send({ status: 'success' })
})
.catch((err) => {
res.status(400).send({
status: 'failure',
message: 'File request failed.',
...(typeof err === 'object' ? err : { details: err })
})
})
})
driveRouter.get('/fileTree', async (req, res) => {
const tree = new ExecutionController().buildDirectorytree()
res.status(200).send({ status: 'success', tree })
})
export default driveRouter

View File

@@ -1,5 +1,5 @@
import express from 'express'
import { ExecutionResult, isRequestQuery, isFileTree } from '../../types'
import { isExecutionQuery } from '../../types'
import path from 'path'
import { getTmpFilesFolderPath, makeFilesNamesMap } from '../../utils'
import { ExecutionController, FileUploadController } from '../../controllers'
@@ -8,15 +8,49 @@ const stpRouter = express.Router()
const fileUploadController = new FileUploadController()
stpRouter.get('/execute', async (req, res) => {
if (isExecutionQuery(req.query)) {
let sasCodePath =
path
.join(getTmpFilesFolderPath(), req.query._program)
.replace(new RegExp('/', 'g'), path.sep) + '.sas'
await new ExecutionController()
.execute(sasCodePath, undefined, undefined, { ...req.query })
.then((result: {}) => {
res.status(200).send(result)
})
.catch((err: {} | string) => {
res.status(400).send({
status: 'failure',
message: 'Job execution failed.',
...(typeof err === 'object' ? err : { details: err })
})
})
} else {
res.status(400).send({
status: 'failure',
message: `Please provide the location of SAS code`
})
}
})
stpRouter.post(
'/execute',
fileUploadController.preuploadMiddleware,
fileUploadController.getMulterUploadObject().any(),
async (req: any, res: any) => {
if (isRequestQuery(req.body)) {
let _program
if (isExecutionQuery(req.query)) {
_program = req.query._program
} else if (isExecutionQuery(req.body)) {
_program = req.body._program
}
if (_program) {
let sasCodePath =
path
.join(getTmpFilesFolderPath(), req.body._program)
.join(getTmpFilesFolderPath(), _program)
.replace(new RegExp('/', 'g'), path.sep) + '.sas'
let filesNamesMap = null

13
api/src/routes/web/web.ts Normal file
View File

@@ -0,0 +1,13 @@
import express from 'express'
import { isExecutionQuery } from '../../types'
import path from 'path'
import { getTmpFilesFolderPath, getWebBuildFolderPath } from '../../utils'
import { ExecutionController } from '../../controllers'
const webRouter = express.Router()
webRouter.get('/', async (_, res) => {
res.sendFile(path.join(getWebBuildFolderPath(), 'index.html'))
})
export default webRouter

17
api/src/types/Request.ts Normal file
View File

@@ -0,0 +1,17 @@
import { MacroVars } from '@sasjs/utils'
export interface ExecutionQuery {
_program: string
macroVars?: MacroVars
_debug?: number
}
export interface FileQuery {
filePath: string
}
export const isExecutionQuery = (arg: any): arg is ExecutionQuery =>
arg && !Array.isArray(arg) && typeof arg._program === 'string'
export const isFileQuery = (arg: any): arg is FileQuery =>
arg && !Array.isArray(arg) && typeof arg.filePath === 'string'

View File

@@ -0,0 +1,6 @@
export interface TreeNode {
name: string
relativePath: string
absolutePath: string
children: Array<TreeNode>
}

View File

@@ -4,3 +4,4 @@ export * from './Request'
export * from './FileTree'
export * from './Session'
export * from './InfoJWT'
export * from './TreeNode'

View File

@@ -1,5 +1,8 @@
import path from 'path'
import { getRealPath, generateTimestamp } from '@sasjs/utils'
import { getRealPath } from '@sasjs/utils'
export const getWebBuildFolderPath = () =>
getRealPath(path.join(__dirname, '..', '..', '..', 'web', 'build'))
export const getTmpFolderPath = () =>
getRealPath(path.join(__dirname, '..', '..', 'tmp'))

10808
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,65 +1,16 @@
{
"name": "server",
"version": "0.0.1",
"description": "SASjs server",
"main": "./src/server.ts",
"description": "NodeJS wrapper for calling the SAS binary executable",
"scripts": {
"prestart": "npm run swagger",
"start": "nodemon ./src/server.ts",
"start:prod": "nodemon ./src/prod-server.ts",
"build": "rimraf build && tsc",
"swagger": "tsoa spec",
"semantic-release": "semantic-release -d",
"prepare": "[ -d .git ] && git config core.hooksPath ./.git-hooks || true",
"test": "mkdir -p tmp && jest --coverage",
"lint:fix": "npx prettier --write \"src/**/*.{ts,tsx,js,jsx,html,css,sass,less,yml,md,graphql}\"",
"lint": "npx prettier --check \"src/**/*.{ts,tsx,js,jsx,html,css,sass,less,yml,md,graphql}\"",
"package:lib": "npm run build && cp ./package.json build && cp README.md build && cd build && npm version \"5.0.0\" && npm pack"
},
"release": {
"branches": [
"master"
]
},
"author": "Analytium Ltd",
"dependencies": {
"@sasjs/utils": "^2.23.3",
"bcryptjs": "^2.4.3",
"express": "^4.17.1",
"joi": "^17.4.2",
"jsonwebtoken": "^8.5.1",
"mongoose": "^6.0.12",
"mongoose-sequence": "^5.3.1",
"morgan": "^1.10.0",
"multer": "^1.4.3",
"swagger-ui-express": "^4.1.6",
"tsoa": "^3.14.0"
"lint-api:fix": "npx prettier --write \"api/src/**/*.{ts,tsx,js,jsx,html,css,sass,less,yml,md,graphql}\"",
"lint-api": "npx prettier --check \"api/src/**/*.{ts,tsx,js,jsx,html,css,sass,less,yml,md,graphql}\"",
"lint-web:fix": "npx prettier --write \"web/src/**/*.{ts,tsx,js,jsx,html,css,sass,less,yml,md,graphql}\"",
"lint-web": "npx prettier --check \"web/src/**/*.{ts,tsx,js,jsx,html,css,sass,less,yml,md,graphql}\"",
"lint": "npm run lint-api && npm run lint-web",
"lint:fix": "npm run lint-api:fix && npm run lint-web:fix"
},
"devDependencies": {
"@types/bcryptjs": "^2.4.2",
"@types/express": "^4.17.12",
"@types/jest": "^26.0.24",
"@types/jsonwebtoken": "^8.5.5",
"@types/mongoose-sequence": "^3.0.6",
"@types/morgan": "^1.9.3",
"@types/multer": "^1.4.7",
"@types/node": "^15.12.2",
"@types/supertest": "^2.0.11",
"@types/swagger-ui-express": "^4.1.3",
"dotenv": "^10.0.0",
"jest": "^27.0.6",
"mongodb-memory-server": "^8.0.0",
"nodemon": "^2.0.7",
"prettier": "^2.3.1",
"rimraf": "^3.0.2",
"semantic-release": "^17.4.3",
"supertest": "^6.1.3",
"ts-jest": "^27.0.3",
"ts-node": "^10.0.0",
"typescript": "^4.3.2"
},
"configuration": {
"sasPath": "/opt/sas/sas9/SASHome/SASFoundation/9.4/sas",
"sasJsPort": 5000
"prettier": "^2.3.1"
}
}

View File

@@ -1,20 +0,0 @@
import express from 'express'
import DriveController from '../../controllers/drive'
const driveRouter = express.Router()
driveRouter.post('/deploy', async (req, res) => {
const controller = new DriveController()
try {
const response = await controller.deploy(req.body)
res.send(response)
} catch (err: any) {
const statusCode = err.code
delete err.code
res.status(statusCode).send(err)
}
})
export default driveRouter

View File

@@ -1,55 +0,0 @@
import express from 'express'
import {
createFileTree,
getSessionController,
getTreeExample
} from '../../controllers'
import { ExecutionResult, isRequestQuery, isFileTree } from '../../types'
import path from 'path'
import {
getTmpFilesFolderPath,
getTmpFolderPath,
makeFilesNamesMap
} from '../../utils'
import { ExecutionController, FileUploadController } from '../../controllers'
import { uuidv4 } from '@sasjs/utils'
const webRouter = express.Router()
webRouter.get('/', async (_, res) => {
res.status(200).send('Welcome to @sasjs/server API')
})
// TODO: respond with HTML page including file tree
webRouter.get('/SASjsExecutor', async (req, res) => {
res.status(200).send({ status: 'success', tree: {} })
})
webRouter.get('/SASjsExecutor/do', async (req, res) => {
if (isRequestQuery(req.query)) {
let sasCodePath =
path
.join(getTmpFilesFolderPath(), req.query._program)
.replace(new RegExp('/', 'g'), path.sep) + '.sas'
await new ExecutionController()
.execute(sasCodePath, undefined, undefined, { ...req.query })
.then((result: {}) => {
res.status(200).send(result)
})
.catch((err: {} | string) => {
res.status(400).send({
status: 'failure',
message: 'Job execution failed.',
...(typeof err === 'object' ? err : { details: err })
})
})
} else {
res.status(400).send({
status: 'failure',
message: `Please provide the location of SAS code`
})
}
})
export default webRouter

View File

@@ -1,10 +0,0 @@
import { MacroVars } from '@sasjs/utils'
export interface ExecutionQuery {
_program: string
macroVars?: MacroVars
_debug?: boolean
}
export const isRequestQuery = (arg: any): arg is ExecutionQuery =>
arg && !Array.isArray(arg) && typeof arg._program === 'string'

46
web/README.md Normal file
View File

@@ -0,0 +1,46 @@
# Getting Started with Create React App
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
## Available Scripts
In the project directory, you can run:
### `npm start`
Runs the app in the development mode.\
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
The page will reload if you make edits.\
You will also see any lint errors in the console.
### `npm test`
Launches the test runner in the interactive watch mode.\
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
### `npm run build`
Builds the app for production to the `build` folder.\
It correctly bundles React in production mode and optimizes the build for the best performance.
The build is minified and the filenames include the hashes.\
Your app is ready to be deployed!
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
### `npm run eject`
**Note: this is a one-way operation. Once you `eject`, you cant go back!**
If you arent satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point youre on your own.
You dont have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldnt feel obligated to use this feature. However we understand that this tool wouldnt be useful if you couldnt customize it when you are ready for it.
## Learn More
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
To learn React, check out the [React documentation](https://reactjs.org/).

16956
web/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

56
web/package.json Normal file
View File

@@ -0,0 +1,56 @@
{
"name": "web",
"version": "0.1.0",
"private": true,
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"dependencies": {
"@emotion/react": "^11.4.1",
"@emotion/styled": "^11.3.0",
"@monaco-editor/react": "^4.3.1",
"@mui/icons-material": "^5.0.3",
"@mui/lab": "^5.0.0-alpha.50",
"@mui/material": "^5.0.3",
"@mui/styles": "^5.0.1",
"@testing-library/jest-dom": "^5.14.1",
"@testing-library/react": "^11.2.7",
"@testing-library/user-event": "^12.8.3",
"@types/jest": "^26.0.24",
"@types/node": "^12.20.28",
"@types/react": "^17.0.27",
"@types/react-dom": "^17.0.9",
"axios": "^0.22.0",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-router-dom": "^5.3.0",
"react-scripts": "4.0.3",
"typescript": "^4.4.3"
},
"devDependencies": {
"@types/prismjs": "^1.16.6",
"@types/react-router-dom": "^5.3.1",
"babel-plugin-prismjs": "^2.1.0"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}

BIN
web/public/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 104 KiB

39
web/public/index.html Normal file
View File

@@ -0,0 +1,39 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta name="description" content="SASjs Server Web Interface" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>SASjs Server Web Interface</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>

BIN
web/public/logo-white.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 KiB

BIN
web/public/logo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

15
web/public/manifest.json Normal file
View File

@@ -0,0 +1,15 @@
{
"short_name": "SASjs Server Web",
"name": "SASjs Server Web Interface",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}

3
web/public/robots.txt Normal file
View File

@@ -0,0 +1,3 @@
# https://www.robotstxt.org/robotstxt.html
User-agent: *
Disallow:

31
web/src/App.tsx Normal file
View File

@@ -0,0 +1,31 @@
import React from 'react'
import { Route, HashRouter, Switch } from 'react-router-dom'
import { ThemeProvider } from '@mui/material/styles'
import { theme } from './theme'
import Header from './components/header'
import Home from './components/home'
import Drive from './containers/Drive'
import Studio from './containers/Studio'
function App() {
return (
<ThemeProvider theme={theme}>
<HashRouter>
<Header />
<Switch>
<Route exact path="/">
<Home />
</Route>
<Route exact path="/SASjsDrive">
<Drive />
</Route>
<Route exact path="/SASjsStudio">
<Studio />
</Route>
</Switch>
</HashRouter>
</ThemeProvider>
)
}
export default App

View File

@@ -0,0 +1,60 @@
import React, { useState } from 'react'
import { Link, useHistory, useLocation } from 'react-router-dom'
import AppBar from '@mui/material/AppBar'
import Toolbar from '@mui/material/Toolbar'
import Tabs from '@mui/material/Tabs'
import Tab from '@mui/material/Tab'
const Header = (props: any) => {
const history = useHistory()
const { pathname } = useLocation()
const [tabValue, setTabValue] = useState(pathname)
const handleTabChange = (event: React.SyntheticEvent, value: string) => {
setTabValue(value)
}
return (
<AppBar
position="fixed"
sx={{ zIndex: (theme) => theme.zIndex.drawer + 1 }}
>
<Toolbar variant="dense">
<img
src="logo-white.png"
alt="logo"
style={{
width: '50px',
cursor: 'pointer',
marginRight: '25px'
}}
onClick={() => {
setTabValue('/')
history.push('/')
}}
/>
<Tabs
indicatorColor="secondary"
value={tabValue}
onChange={handleTabChange}
>
<Tab label="Home" value="/" to="/" component={Link} />
<Tab
label="Drive"
value="/SASjsDrive"
to="/SASjsDrive"
component={Link}
/>
<Tab
label="Studio"
value="/SASjsStudio"
to="/SASjsStudio"
component={Link}
/>
</Tabs>
</Toolbar>
</AppBar>
)
}
export default Header

View File

@@ -0,0 +1,41 @@
import React from 'react'
import CssBaseline from '@mui/material/CssBaseline'
import Box from '@mui/material/Box'
const Home = () => {
return (
<Box className="main">
<CssBaseline />
<h2>Welcome to SASjs Server!</h2>
<p>
This portal provides an interface for executing Stored Programs (drive)
and ad hoc code (studio) against a SAS executable. The source code is
available on{' '}
<a
href="https://github.com/sasjs/server"
target="_blank"
rel="noreferrer"
>
{' '}
github
</a>{' '}
and contributions are welcomed.
</p>
<p>
SASjs Server is maintained by the SASjs Apps team -{' '}
<a
href="https://sasapps.io/contact-us"
target="_blank"
rel="noreferrer"
>
{' '}
contact us
</a>{' '}
if you'd like help with SAS DevOps or SAS Application development!{' '}
</p>
</Box>
)
}
export default Home

View File

@@ -0,0 +1,20 @@
import React, { useState } from 'react'
import CssBaseline from '@mui/material/CssBaseline'
import Box from '@mui/material/Box'
import SideBar from './sideBar'
import Main from './main'
const Drive = () => {
const [selectedFilePath, setSelectedFilePath] = useState('')
return (
<Box sx={{ display: 'flex' }}>
<CssBaseline />
<SideBar setSelectedFilePath={setSelectedFilePath} />
<Main selectedFilePath={selectedFilePath} />
</Box>
)
}
export default Drive

View File

@@ -0,0 +1,129 @@
import React, { useState, useEffect } from 'react'
import axios from 'axios'
import Editor from '@monaco-editor/react'
import Box from '@mui/material/Box'
import Paper from '@mui/material/Paper'
import Stack from '@mui/material/Stack'
import Button from '@mui/material/Button'
import Toolbar from '@mui/material/Toolbar'
import CircularProgress from '@mui/material/CircularProgress'
const Main = (props: any) => {
const baseUrl = window.location.origin
const [isLoading, setIsLoading] = useState(false)
const [fileContentBeforeEdit, setFileContentBeforeEdit] = useState('')
const [fileContent, setFileContent] = useState('')
const [editMode, setEditMode] = useState(false)
useEffect(() => {
if (props.selectedFilePath) {
setIsLoading(true)
axios
.get(`/SASjsApi/drive/file?filePath=${props.selectedFilePath}`)
.then((res: any) => {
setFileContent(res.data.fileContent)
})
.catch((err) => {
console.log(err)
})
.finally(() => {
setIsLoading(false)
})
}
}, [props.selectedFilePath])
const handleEditSaveBtnClick = () => {
if (!editMode) {
setFileContentBeforeEdit(fileContent)
setEditMode(true)
} else {
setIsLoading(true)
axios
.patch(`/SASjsApi/drive/file`, {
filePath: props.selectedFilePath,
fileContent: fileContent
})
.then((res) => {
setEditMode(false)
})
.catch((err) => {
console.log(err)
})
.finally(() => {
setIsLoading(false)
})
}
}
const handleCancelExecuteBtnClick = () => {
if (editMode) {
setFileContent(fileContentBeforeEdit)
setEditMode(false)
} else {
window.open(
`${baseUrl}/SASjsApi/stp/execute?_program=${props.selectedFilePath.replace(
/.sas$/,
''
)}`
)
}
}
return (
<Box component="main" sx={{ flexGrow: 1, p: 3 }}>
<Toolbar />
<Paper
sx={{
height: '75vh',
padding: '10px',
overflow: 'auto',
position: 'relative'
}}
elevation={3}
>
{isLoading && (
<CircularProgress
style={{ position: 'absolute', left: '50%', top: '50%' }}
/>
)}
{!isLoading && props?.selectedFilePath !== '' && !editMode && (
<code style={{ whiteSpace: 'break-spaces' }}>{fileContent}</code>
)}
{!isLoading && props?.selectedFilePath !== '' && editMode && (
<Editor
height="95%"
value={fileContent}
onChange={(val) => {
if (val) setFileContent(val)
}}
/>
)}
</Paper>
<Stack
spacing={3}
direction="row"
sx={{ justifyContent: 'center', marginTop: '20px' }}
>
<Button
variant="contained"
onClick={handleEditSaveBtnClick}
disabled={isLoading || props?.selectedFilePath === ''}
>
{!editMode ? 'Edit' : 'Save'}
</Button>
<Button
variant="contained"
onClick={handleCancelExecuteBtnClick}
disabled={isLoading || props?.selectedFilePath === ''}
>
{editMode ? 'Cancel' : 'Execute'}
</Button>
</Stack>
</Box>
)
}
export default Main

View File

@@ -0,0 +1,119 @@
import React, { useState, useEffect, useCallback } from 'react'
import axios from 'axios'
import { useLocation } from 'react-router-dom'
import { makeStyles } from '@mui/styles'
import Box from '@mui/material/Box'
import Drawer from '@mui/material/Drawer'
import Toolbar from '@mui/material/Toolbar'
import ListItem from '@mui/material/ListItem'
import ListItemText from '@mui/material/ListItemText'
import TreeView from '@mui/lab/TreeView'
import TreeItem from '@mui/lab/TreeItem'
import ExpandMoreIcon from '@mui/icons-material/ExpandMore'
import ChevronRightIcon from '@mui/icons-material/ChevronRight'
interface TreeNode {
name: string
relativePath: string
absolutePath: string
children: Array<TreeNode>
}
const useStyles = makeStyles(() => ({
root: {
'& .MuiTreeItem-content': {
width: 'auto'
}
},
listItem: {
padding: 0
}
}))
const drawerWidth = 240
const SideBar = (props: any) => {
const location = useLocation()
const baseUrl = window.location.origin
const classes = useStyles()
const { setSelectedFilePath } = props
const [directoryData, setDirectoryData] = useState<TreeNode | null>(null)
const setFilePathOnMount = useCallback(() => {
const queryParams = new URLSearchParams(location.search)
setSelectedFilePath(queryParams.get('filePath'))
}, [location.search, setSelectedFilePath])
useEffect(() => {
axios
.get(`/SASjsApi/drive/fileTree`)
.then((res: any) => {
if (res.data && res.data?.status === 'success') {
setDirectoryData(res.data.tree)
}
})
.catch((err) => {
console.log(err)
})
setFilePathOnMount()
}, [setFilePathOnMount])
const handleSelect = (node: TreeNode) => {
if (!node.children.length) {
window.history.pushState(
'',
'',
`${baseUrl}/#/SASjsDrive?filePath=${node.relativePath}`
)
setSelectedFilePath(node.relativePath)
}
}
const renderTree = (nodes: TreeNode) => (
<TreeItem
classes={{ root: classes.root }}
key={nodes.relativePath}
nodeId={nodes.relativePath}
label={
<ListItem
className={classes.listItem}
onClick={() => handleSelect(nodes)}
>
<ListItemText primary={nodes.name} />
</ListItem>
}
>
{Array.isArray(nodes.children)
? nodes.children.map((node) => renderTree(node))
: null}
</TreeItem>
)
return (
<Drawer
variant="permanent"
sx={{
width: drawerWidth,
flexShrink: 0,
[`& .MuiDrawer-paper`]: { width: drawerWidth, boxSizing: 'border-box' }
}}
>
<Toolbar />
<Box sx={{ overflow: 'auto' }}>
<TreeView
defaultCollapseIcon={<ExpandMoreIcon />}
defaultExpandIcon={<ChevronRightIcon />}
>
{directoryData && renderTree(directoryData)}
</TreeView>
</Box>
</Drawer>
)
}
export default SideBar

View File

@@ -0,0 +1,15 @@
import React from 'react'
import CssBaseline from '@mui/material/CssBaseline'
import Box from '@mui/material/Box'
const Studio = () => {
return (
<Box className="main">
<CssBaseline />
<h2>This is container for SASjs studio</h2>
</Box>
)
}
export default Studio

20
web/src/index.css Normal file
View File

@@ -0,0 +1,20 @@
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
code {
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
monospace;
}
.main {
margin-top: 50px;
display: flex;
flex-direction: column;
align-items: center;
}

11
web/src/index.tsx Normal file
View File

@@ -0,0 +1,11 @@
import React from 'react'
import ReactDOM from 'react-dom'
import './index.css'
import App from './App'
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
)

1
web/src/react-app-env.d.ts vendored Normal file
View File

@@ -0,0 +1 @@
/// <reference types="react-scripts" />

5
web/src/setupTests.ts Normal file
View File

@@ -0,0 +1,5 @@
// jest-dom adds custom jest matchers for asserting on DOM nodes.
// allows you to do things like:
// expect(element).toHaveTextContent(/react/i)
// learn more: https://github.com/testing-library/jest-dom
import '@testing-library/jest-dom'

19
web/src/theme/index.js Normal file
View File

@@ -0,0 +1,19 @@
import { createTheme } from '@mui/material/styles'
import palette from './palette'
export const theme = createTheme({
palette,
components: {
MuiTab: {
styleOverrides: {
root: {
fontSize: '21px',
color: palette.white,
'&.Mui-selected': {
color: palette.secondary.main
}
}
}
}
}
})

55
web/src/theme/palette.js Normal file
View File

@@ -0,0 +1,55 @@
import { colors } from '@mui/material'
const white = '#FFFFFF'
const black = '#000000'
const yellow = '#F6E30F'
const palette = {
black,
white,
primary: {
contrastText: white,
main: black
},
secondary: {
contrastText: white,
main: yellow
},
success: {
contrastText: white,
dark: colors.green[900],
main: colors.green[600],
light: colors.green[400]
},
info: {
contrastText: white,
dark: colors.blue[900],
main: colors.blue[600],
light: colors.blue[400]
},
warning: {
contrastText: white,
dark: colors.orange[900],
main: colors.orange[600],
light: colors.orange[400]
},
error: {
contrastText: white,
dark: colors.red[900],
main: colors.red[600],
light: colors.red[400]
},
text: {
primary: colors.blueGrey[900],
secondary: colors.blueGrey[600],
link: colors.blue[600]
},
background: {
default: '#F4F6F8',
paper: white
},
icon: colors.blueGrey[600],
divider: colors.grey[200]
}
export default palette

26
web/tsconfig.json Normal file
View File

@@ -0,0 +1,26 @@
{
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx"
},
"include": [
"src"
]
}