Compare commits
23 Commits
8f0112526f
...
Add-wf
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a0cd68b42b | ||
|
|
0c97c4421c | ||
|
|
529b506612 | ||
|
|
93e3a66252 | ||
|
|
a10d6ecc29 | ||
|
|
0fe61acfe7 | ||
|
|
18193b71c1 | ||
|
|
88984a21b2 | ||
|
|
c4221c9bea | ||
|
|
325699d036 | ||
|
|
5cc15eb87a | ||
|
|
0b347c5c94 | ||
|
|
fb57cf6376 | ||
|
|
5890745ed2 | ||
|
|
15f890abda | ||
|
|
acce21c0e6 | ||
|
|
ddc5311fb9 | ||
|
|
bb4a154a27 | ||
|
|
7b6800de37 | ||
|
|
7ddc8cde84 | ||
|
|
6565223b96 | ||
|
|
f262c785aa | ||
|
|
4b8f5f3739 |
25
.dockerignore
Normal file
25
.dockerignore
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
node_modules
|
||||||
|
npm-debug.log
|
||||||
|
.git
|
||||||
|
.gitignore
|
||||||
|
*.md
|
||||||
|
.vscode
|
||||||
|
.idea
|
||||||
|
*.log
|
||||||
|
dist
|
||||||
|
build
|
||||||
|
coverage
|
||||||
|
.nyc_output
|
||||||
|
playwright-report
|
||||||
|
test-results
|
||||||
|
e2e
|
||||||
|
*.test.ts
|
||||||
|
*.test.tsx
|
||||||
|
*.spec.ts
|
||||||
|
*.spec.tsx
|
||||||
|
vitest.config.ts
|
||||||
|
playwright.config.ts
|
||||||
|
eslint.config.js
|
||||||
|
.qwen
|
||||||
|
*.ico
|
||||||
|
cgg-ico\ copy.png
|
||||||
19
.gitea/workflows/demo.yaml
Normal file
19
.gitea/workflows/demo.yaml
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
name: Gitea Actions Demo
|
||||||
|
run-name: ${{ gitea.actor }} is testing out Gitea Actions 🚀
|
||||||
|
on: [push]
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
Explore-Gitea-Actions:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- run: echo "🎉 The job was automatically triggered by a ${{ gitea.event_name }} event."
|
||||||
|
- run: echo "🐧 This job is now running on a ${{ runner.os }} server hosted by Gitea!"
|
||||||
|
- run: echo "🔎 The name of your branch is ${{ gitea.ref }} and your repository is ${{ gitea.repository }}."
|
||||||
|
- name: Check out repository code
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
- run: echo "💡 The ${{ gitea.repository }} repository has been cloned to the runner."
|
||||||
|
- run: echo "🖥️ The workflow is now ready to test your code on the runner."
|
||||||
|
- name: List files in the repository
|
||||||
|
run: |
|
||||||
|
ls ${{ gitea.workspace }}
|
||||||
|
- run: echo "🍏 This job's status is ${{ job.status }}."
|
||||||
1
.gitignore
vendored
1
.gitignore
vendored
@@ -22,3 +22,4 @@ dist-ssr
|
|||||||
*.njsproj
|
*.njsproj
|
||||||
*.sln
|
*.sln
|
||||||
*.sw?
|
*.sw?
|
||||||
|
playwright-report
|
||||||
317
DEPLOYMENT.md
Normal file
317
DEPLOYMENT.md
Normal file
@@ -0,0 +1,317 @@
|
|||||||
|
# Configucci Docker Deployment Guide
|
||||||
|
|
||||||
|
## Quick Start
|
||||||
|
|
||||||
|
### Local Deployment (Windows/Linux/Mac)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Make script executable (Linux/Mac only)
|
||||||
|
chmod +x deploy-docker.sh
|
||||||
|
|
||||||
|
# Deploy locally
|
||||||
|
./deploy-docker.sh
|
||||||
|
|
||||||
|
# Or on Windows (PowerShell)
|
||||||
|
bash deploy-docker.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
### Remote Deployment (Linux Server)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Deploy to remote server
|
||||||
|
./deploy-docker.sh user@your-server.com
|
||||||
|
|
||||||
|
# Example
|
||||||
|
./deploy-docker.sh root@192.168.1.100
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Manual Deployment
|
||||||
|
|
||||||
|
### 1. Build and Run Locally
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Build image
|
||||||
|
docker-compose build
|
||||||
|
|
||||||
|
# Start container
|
||||||
|
docker-compose up -d
|
||||||
|
|
||||||
|
# View logs
|
||||||
|
docker-compose logs -f
|
||||||
|
|
||||||
|
# Stop
|
||||||
|
docker-compose down
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. Deploy to Linux Server
|
||||||
|
|
||||||
|
#### Option A: Using Deployment Script (Recommended)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# From your local machine
|
||||||
|
./deploy-docker.sh user@your-server.com
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Option B: Manual Steps on Server
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# SSH to server
|
||||||
|
ssh user@your-server.com
|
||||||
|
|
||||||
|
# Install Docker (if not installed)
|
||||||
|
curl -fsSL https://get.docker.com -o get-docker.sh
|
||||||
|
sudo sh get-docker.sh
|
||||||
|
sudo usermod -aG docker $USER
|
||||||
|
exit
|
||||||
|
|
||||||
|
# SSH again (to apply group changes)
|
||||||
|
ssh user@your-server.com
|
||||||
|
|
||||||
|
# Clone repository
|
||||||
|
git clone https://git.six83.ru/ssa/configucci.git
|
||||||
|
cd configucci
|
||||||
|
|
||||||
|
# Build and run
|
||||||
|
docker-compose build
|
||||||
|
docker-compose up -d
|
||||||
|
|
||||||
|
# View logs
|
||||||
|
docker-compose logs -f
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Accessing the Application
|
||||||
|
|
||||||
|
After deployment, access the app at:
|
||||||
|
|
||||||
|
- **Local:** http://localhost:11088
|
||||||
|
- **Server:** http://your-server-ip:11088
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Useful Docker Commands
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# View running containers
|
||||||
|
docker-compose ps
|
||||||
|
|
||||||
|
# View logs
|
||||||
|
docker-compose logs -f
|
||||||
|
|
||||||
|
# Restart application
|
||||||
|
docker-compose restart
|
||||||
|
|
||||||
|
# Stop application
|
||||||
|
docker-compose down
|
||||||
|
|
||||||
|
# Rebuild and restart
|
||||||
|
docker-compose build --no-cache
|
||||||
|
docker-compose up -d
|
||||||
|
|
||||||
|
# View resource usage
|
||||||
|
docker stats configucci-app
|
||||||
|
|
||||||
|
# Execute command in container
|
||||||
|
docker exec -it configucci-app sh
|
||||||
|
|
||||||
|
# Remove everything (container + image)
|
||||||
|
docker-compose down --rmi all
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Production Setup with SSL
|
||||||
|
|
||||||
|
### 1. Install Nginx Proxy Manager (Recommended)
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
# Add to docker-compose.yml
|
||||||
|
version: '3.8'
|
||||||
|
|
||||||
|
services:
|
||||||
|
proxy:
|
||||||
|
image: jc21/nginx-proxy-manager:latest
|
||||||
|
ports:
|
||||||
|
- "80:80"
|
||||||
|
- "81:81"
|
||||||
|
- "443:443"
|
||||||
|
volumes:
|
||||||
|
- ./data:/data
|
||||||
|
- ./letsencrypt:/etc/letsencrypt
|
||||||
|
restart: unless-stopped
|
||||||
|
|
||||||
|
configucci:
|
||||||
|
# ... existing configucci config
|
||||||
|
```
|
||||||
|
|
||||||
|
Then access `http://your-server:81` to configure SSL via web UI.
|
||||||
|
|
||||||
|
### 2. Or Use Certbot Directly
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# On host server (not in Docker)
|
||||||
|
sudo apt install certbot -y
|
||||||
|
|
||||||
|
# Get certificate
|
||||||
|
sudo certbot certonly --standalone -d your-domain.com
|
||||||
|
|
||||||
|
# Mount certificates in docker-compose.yml
|
||||||
|
volumes:
|
||||||
|
- /etc/letsencrypt:/etc/letsencrypt:ro
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Environment Variables
|
||||||
|
|
||||||
|
You can customize the build by setting environment variables:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# In docker-compose.yml or .env file
|
||||||
|
GIT_URL=https://git.six83.ru/ssa/configucci.git
|
||||||
|
GIT_BRANCH=ai
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Troubleshooting
|
||||||
|
|
||||||
|
### Container Won't Start
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Check logs
|
||||||
|
docker-compose logs
|
||||||
|
|
||||||
|
# Check if port 80 is in use
|
||||||
|
sudo netstat -tlnp | grep :80
|
||||||
|
|
||||||
|
# Use different port
|
||||||
|
# Edit docker-compose.yml: ports: - "8080:80"
|
||||||
|
```
|
||||||
|
|
||||||
|
### Build Fails
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Clean build cache
|
||||||
|
docker-compose build --no-cache
|
||||||
|
|
||||||
|
# Remove all Docker resources
|
||||||
|
docker system prune -a
|
||||||
|
```
|
||||||
|
|
||||||
|
### Can't Access Application
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Check firewall
|
||||||
|
sudo ufw status
|
||||||
|
sudo ufw allow 80/tcp
|
||||||
|
|
||||||
|
# Check container is running
|
||||||
|
docker-compose ps
|
||||||
|
|
||||||
|
# Test from server
|
||||||
|
curl http://localhost
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Automated Deployment with CI/CD
|
||||||
|
|
||||||
|
Create `.gitlab-ci.yml` or GitHub Actions workflow:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
# Example: GitHub Actions
|
||||||
|
name: Deploy
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [ai]
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
deploy:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v3
|
||||||
|
|
||||||
|
- name: Deploy to server
|
||||||
|
uses: appleboy/ssh-action@master
|
||||||
|
with:
|
||||||
|
host: ${{ secrets.SERVER_HOST }}
|
||||||
|
username: ${{ secrets.SERVER_USER }}
|
||||||
|
key: ${{ secrets.SSH_PRIVATE_KEY }}
|
||||||
|
script: |
|
||||||
|
cd /opt/configucci
|
||||||
|
git pull
|
||||||
|
docker-compose build --no-cache
|
||||||
|
docker-compose up -d
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Backup and Restore
|
||||||
|
|
||||||
|
### Backup
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Backup configuration
|
||||||
|
tar -czf configucci-backup.tar.gz docker-compose.yml nginx.conf
|
||||||
|
```
|
||||||
|
|
||||||
|
### Restore
|
||||||
|
|
||||||
|
```bash
|
||||||
|
tar -xzf configucci-backup.tar.gz
|
||||||
|
docker-compose up -d
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Monitoring
|
||||||
|
|
||||||
|
### Install Docker Monitoring
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Install cAdvisor for container monitoring
|
||||||
|
docker run \
|
||||||
|
--volume=/:/rootfs:ro \
|
||||||
|
--volume=/var/run:/var/run:ro \
|
||||||
|
--volume=/sys:/sys:ro \
|
||||||
|
--volume=/var/lib/docker/:/var/lib/docker:ro \
|
||||||
|
--volume=/dev/disk/:/dev/disk:ro \
|
||||||
|
--publish=8080:8080 \
|
||||||
|
--name=cadvisor \
|
||||||
|
google/cadvisor:latest
|
||||||
|
```
|
||||||
|
|
||||||
|
Access at: `http://your-server:8080`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Security Recommendations
|
||||||
|
|
||||||
|
1. **Use HTTPS** - Always use SSL in production
|
||||||
|
2. **Firewall** - Only open necessary ports
|
||||||
|
3. **Regular Updates** - Keep Docker and system updated
|
||||||
|
4. **Non-root User** - Run container as non-root
|
||||||
|
5. **Resource Limits** - Set CPU/memory limits in docker-compose.yml
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
# Add resource limits
|
||||||
|
deploy:
|
||||||
|
resources:
|
||||||
|
limits:
|
||||||
|
cpus: '0.5'
|
||||||
|
memory: 512M
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Support
|
||||||
|
|
||||||
|
For issues, check:
|
||||||
|
- Docker logs: `docker-compose logs`
|
||||||
|
- Nginx logs: `docker exec configucci-app cat /var/log/nginx/error.log`
|
||||||
|
- Application health: `docker inspect --format='{{.State.Health.Status}}' configucci-app`
|
||||||
39
Dockerfile
Normal file
39
Dockerfile
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
# Build stage
|
||||||
|
FROM node:20-alpine AS build
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
# Install git
|
||||||
|
RUN apk add --no-cache git
|
||||||
|
|
||||||
|
# Clone repository
|
||||||
|
ARG GIT_URL=https://git.six83.ru/ssa/configucci.git
|
||||||
|
ARG GIT_BRANCH=main
|
||||||
|
RUN git clone --depth 1 --branch ${GIT_BRANCH} ${GIT_URL} .
|
||||||
|
|
||||||
|
# Install dependencies
|
||||||
|
COPY package*.json ./
|
||||||
|
RUN npm ci
|
||||||
|
|
||||||
|
# Copy source and build
|
||||||
|
COPY . .
|
||||||
|
RUN npm run build
|
||||||
|
|
||||||
|
# Production stage
|
||||||
|
FROM nginx:alpine
|
||||||
|
|
||||||
|
# Copy custom nginx config
|
||||||
|
COPY nginx.conf /etc/nginx/conf.d/default.conf
|
||||||
|
|
||||||
|
# Copy built files from build stage
|
||||||
|
COPY --from=build /app/dist /usr/share/nginx/html
|
||||||
|
|
||||||
|
# Expose port 80
|
||||||
|
EXPOSE 80
|
||||||
|
|
||||||
|
# Health check
|
||||||
|
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
|
||||||
|
CMD wget --no-verbose --tries=1 --spider http://localhost/ || exit 1
|
||||||
|
|
||||||
|
# Start nginx
|
||||||
|
CMD ["nginx", "-g", "daemon off;"]
|
||||||
152
deploy-docker.sh
Normal file
152
deploy-docker.sh
Normal file
@@ -0,0 +1,152 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
# Configucci Docker Deployment Script
|
||||||
|
# Usage: ./deploy-docker.sh [server]
|
||||||
|
|
||||||
|
set -e
|
||||||
|
|
||||||
|
# Colors for output
|
||||||
|
RED='\033[0;31m'
|
||||||
|
GREEN='\033[0;32m'
|
||||||
|
YELLOW='\033[1;33m'
|
||||||
|
NC='\033[0m' # No Color
|
||||||
|
|
||||||
|
# Configuration
|
||||||
|
SERVER="${1:-}"
|
||||||
|
APP_NAME="configucci"
|
||||||
|
GIT_BRANCH="main"
|
||||||
|
|
||||||
|
echo -e "${GREEN}==================================${NC}"
|
||||||
|
echo -e "${GREEN} Configucci Docker Deployment ${NC}"
|
||||||
|
echo -e "${GREEN}==================================${NC}"
|
||||||
|
|
||||||
|
# Function to deploy locally
|
||||||
|
deploy_local() {
|
||||||
|
echo -e "${YELLOW}Building Docker image...${NC}"
|
||||||
|
docker-compose build --no-cache
|
||||||
|
|
||||||
|
echo -e "${YELLOW}Stopping existing container (if any)...${NC}"
|
||||||
|
docker-compose down || true
|
||||||
|
|
||||||
|
echo -e "${YELLOW}Starting new container...${NC}"
|
||||||
|
docker-compose up -d
|
||||||
|
|
||||||
|
echo -e "${YELLOW}Waiting for application to start...${NC}"
|
||||||
|
sleep 5
|
||||||
|
|
||||||
|
echo -e "${GREEN}==================================${NC}"
|
||||||
|
echo -e "${GREEN} Deployment Complete! ${NC}"
|
||||||
|
echo -e "${GREEN}==================================${NC}"
|
||||||
|
echo ""
|
||||||
|
echo -e "Application URL: ${GREEN}http://localhost${NC}"
|
||||||
|
echo ""
|
||||||
|
echo -e "Useful commands:"
|
||||||
|
echo -e " View logs: ${YELLOW}docker-compose logs -f${NC}"
|
||||||
|
echo -e " Stop app: ${YELLOW}docker-compose down${NC}"
|
||||||
|
echo -e " Restart app: ${YELLOW}docker-compose restart${NC}"
|
||||||
|
echo -e " Rebuild: ${YELLOW}docker-compose build && docker-compose up -d${NC}"
|
||||||
|
}
|
||||||
|
|
||||||
|
# Function to deploy to remote server
|
||||||
|
deploy_remote() {
|
||||||
|
echo -e "${YELLOW}Deploying to server: ${SERVER}${NC}"
|
||||||
|
|
||||||
|
# Check if server is accessible
|
||||||
|
if ! ping -c 1 "$SERVER" &> /dev/null; then
|
||||||
|
echo -e "${RED}Cannot connect to server: ${SERVER}${NC}"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Create deployment script on server
|
||||||
|
cat << 'EOF' > /tmp/deploy-configucci.sh
|
||||||
|
#!/bin/bash
|
||||||
|
set -e
|
||||||
|
|
||||||
|
APP_DIR="/opt/configucci"
|
||||||
|
GIT_URL="https://git.six83.ru/ssa/configucci.git"
|
||||||
|
GIT_BRANCH="main"
|
||||||
|
|
||||||
|
echo "Creating app directory..."
|
||||||
|
mkdir -p \$APP_DIR
|
||||||
|
cd \$APP_DIR
|
||||||
|
|
||||||
|
echo "Pulling latest code..."
|
||||||
|
if [ -d ".git" ]; then
|
||||||
|
git pull origin \$GIT_BRANCH
|
||||||
|
else
|
||||||
|
git clone --depth 1 --branch \$GIT_BRANCH \$GIT_URL .
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "Building Docker image..."
|
||||||
|
docker-compose build --no-cache
|
||||||
|
|
||||||
|
echo "Stopping existing container..."
|
||||||
|
docker-compose down || true
|
||||||
|
|
||||||
|
echo "Starting new container..."
|
||||||
|
docker-compose up -d
|
||||||
|
|
||||||
|
echo "Cleaning up old images..."
|
||||||
|
docker image prune -f
|
||||||
|
|
||||||
|
echo "Deployment complete!"
|
||||||
|
docker-compose ps
|
||||||
|
EOF
|
||||||
|
|
||||||
|
# Copy docker-compose.yml to server
|
||||||
|
echo -e "${YELLOW}Copying files to server...${NC}"
|
||||||
|
scp docker-compose.yml Dockerfile nginx.conf "$SERVER:/tmp/"
|
||||||
|
|
||||||
|
# Execute deployment on server
|
||||||
|
echo -e "${YELLOW}Executing deployment on server...${NC}"
|
||||||
|
ssh "$SERVER" << 'ENDSSH'
|
||||||
|
#!/bin/bash
|
||||||
|
set -e
|
||||||
|
|
||||||
|
APP_DIR="/opt/configucci"
|
||||||
|
cd $APP_DIR
|
||||||
|
|
||||||
|
# Copy files from /tmp
|
||||||
|
cp /tmp/docker-compose.yml .
|
||||||
|
cp /tmp/Dockerfile .
|
||||||
|
cp /tmp/nginx.conf .
|
||||||
|
|
||||||
|
# Build and deploy
|
||||||
|
docker-compose build --no-cache
|
||||||
|
docker-compose down || true
|
||||||
|
docker-compose up -d
|
||||||
|
|
||||||
|
# Cleanup
|
||||||
|
docker image prune -f
|
||||||
|
docker-compose ps
|
||||||
|
ENDSSH
|
||||||
|
|
||||||
|
echo -e "${GREEN}==================================${NC}"
|
||||||
|
echo -e "${GREEN} Remote Deployment Complete! ${NC}"
|
||||||
|
echo -e "${GREEN}==================================${NC}"
|
||||||
|
echo ""
|
||||||
|
echo -e "Server: ${GREEN}http://${SERVER}${NC}"
|
||||||
|
echo ""
|
||||||
|
echo -e "Useful commands:"
|
||||||
|
echo -e " SSH to server: ${YELLOW}ssh ${SERVER}${NC}"
|
||||||
|
echo -e " View logs: ${YELLOW}ssh ${SERVER} 'docker-compose logs -f'${NC}"
|
||||||
|
echo -e " Stop app: ${YELLOW}ssh ${SERVER} 'docker-compose down'${NC}"
|
||||||
|
}
|
||||||
|
|
||||||
|
# Check if Docker is available
|
||||||
|
if ! command -v docker &> /dev/null; then
|
||||||
|
echo -e "${RED}Docker is not installed or not in PATH${NC}"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
if ! command -v docker-compose &> /dev/null; then
|
||||||
|
echo -e "${RED}docker-compose is not installed or not in PATH${NC}"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Deploy
|
||||||
|
if [ -z "$SERVER" ]; then
|
||||||
|
deploy_local
|
||||||
|
else
|
||||||
|
deploy_remote
|
||||||
|
fi
|
||||||
34
docker-compose.yml
Normal file
34
docker-compose.yml
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
version: '3.8'
|
||||||
|
|
||||||
|
services:
|
||||||
|
configucci:
|
||||||
|
build:
|
||||||
|
context: .
|
||||||
|
dockerfile: Dockerfile
|
||||||
|
args:
|
||||||
|
GIT_URL: https://git.six83.ru/ssa/configucci.git
|
||||||
|
GIT_BRANCH: main
|
||||||
|
container_name: configucci-app
|
||||||
|
ports:
|
||||||
|
- "11088:80"
|
||||||
|
restart: unless-stopped
|
||||||
|
networks:
|
||||||
|
- configucci-network
|
||||||
|
volumes:
|
||||||
|
# Optional: persist nginx logs
|
||||||
|
- nginx-logs:/var/log/nginx
|
||||||
|
environment:
|
||||||
|
- TZ=Europe/Moscow
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost/"]
|
||||||
|
interval: 30s
|
||||||
|
timeout: 10s
|
||||||
|
retries: 3
|
||||||
|
start_period: 10s
|
||||||
|
|
||||||
|
networks:
|
||||||
|
configucci-network:
|
||||||
|
driver: bridge
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
nginx-logs:
|
||||||
190
e2e/environment.spec.ts
Normal file
190
e2e/environment.spec.ts
Normal file
@@ -0,0 +1,190 @@
|
|||||||
|
import { test, expect } from '@playwright/test';
|
||||||
|
import * as fs from 'fs';
|
||||||
|
|
||||||
|
test.describe('Environment Management', () => {
|
||||||
|
test('should not allow removing DEFAULT environment', async ({ page }) => {
|
||||||
|
await page.goto('/');
|
||||||
|
await page.click('button:has-text("Create new")');
|
||||||
|
const removeButton = page.locator('button.btn-danger[title="Remove environment"]');
|
||||||
|
await expect(removeButton).toBeDisabled();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('should remove non-DEFAULT environment', async ({ page }) => {
|
||||||
|
await page.goto('/');
|
||||||
|
await page.click('button:has-text("Create new")');
|
||||||
|
page.once('dialog', async dialog => { await dialog.accept('toRemove'); });
|
||||||
|
await page.click('button.btn-success[title="Add environment"]');
|
||||||
|
await page.waitForTimeout(500);
|
||||||
|
await expect(page.locator('#environments option')).toHaveCount(2);
|
||||||
|
page.once('dialog', async dialog => { await dialog.accept(); });
|
||||||
|
await page.click('button.btn-danger[title="Remove environment"]');
|
||||||
|
await page.waitForTimeout(300);
|
||||||
|
await expect(page.locator('#environments option')).toHaveCount(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('should create new environment and switch without errors', async ({ page }) => {
|
||||||
|
await page.goto('/');
|
||||||
|
await page.click('button:has-text("Create new")');
|
||||||
|
page.once('dialog', async dialog => { await dialog.accept('env1'); });
|
||||||
|
await page.click('button.btn-success[title="Add environment"]');
|
||||||
|
await page.waitForTimeout(500);
|
||||||
|
await expect(page.locator('#environments option')).toHaveCount(2);
|
||||||
|
await page.locator('#environments').selectOption({ index: 0 });
|
||||||
|
await page.waitForTimeout(300);
|
||||||
|
await page.locator('#environments').selectOption('env1');
|
||||||
|
await page.waitForTimeout(300);
|
||||||
|
await expect(page.locator('#environments')).toBeVisible();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('should create multiple environments and switch between them', async ({ page }) => {
|
||||||
|
await page.goto('/');
|
||||||
|
await page.click('button:has-text("Create new")');
|
||||||
|
page.once('dialog', async dialog => { await dialog.accept('env1'); });
|
||||||
|
await page.click('button.btn-success[title="Add environment"]');
|
||||||
|
await page.waitForTimeout(500);
|
||||||
|
page.once('dialog', async dialog => { await dialog.accept('env2'); });
|
||||||
|
await page.click('button.btn-success[title="Add environment"]');
|
||||||
|
await page.waitForTimeout(500);
|
||||||
|
await expect(page.locator('#environments option')).toHaveCount(3);
|
||||||
|
await page.locator('#environments').selectOption({ index: 0 });
|
||||||
|
await page.waitForTimeout(200);
|
||||||
|
await page.locator('#environments').selectOption('env1');
|
||||||
|
await page.waitForTimeout(200);
|
||||||
|
await page.locator('#environments').selectOption('env2');
|
||||||
|
await page.waitForTimeout(200);
|
||||||
|
await expect(page.locator('#environments')).toBeVisible();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('should add params and edit template manually', async ({ page }) => {
|
||||||
|
await page.goto('/');
|
||||||
|
await page.click('button:has-text("Create new")');
|
||||||
|
const nameInput = page.locator('input[placeholder="name"]').first();
|
||||||
|
const valueInput = page.locator('input[placeholder="value"]').first();
|
||||||
|
const addButton = page.locator('button.btn-success').first();
|
||||||
|
await nameInput.fill('host');
|
||||||
|
await valueInput.fill('localhost:8080');
|
||||||
|
await addButton.click();
|
||||||
|
await page.waitForTimeout(500);
|
||||||
|
await nameInput.fill('port');
|
||||||
|
await valueInput.fill('9090');
|
||||||
|
await addButton.click();
|
||||||
|
await page.waitForTimeout(500);
|
||||||
|
await page.click('a:has-text("Content Template")');
|
||||||
|
await page.waitForTimeout(500);
|
||||||
|
await expect(page.locator('button:has-text("Edit")')).toBeVisible();
|
||||||
|
await page.click('button:has-text("Edit")');
|
||||||
|
await page.waitForTimeout(500);
|
||||||
|
const textarea = page.locator('textarea');
|
||||||
|
await expect(textarea).toBeVisible();
|
||||||
|
await textarea.fill('{\n "!!! host": "@host@",\n "!!! port": "@port@",\n "!!! custom": "@custom@"\n}');
|
||||||
|
await page.waitForTimeout(300);
|
||||||
|
await page.click('button:has-text("Save")');
|
||||||
|
await page.waitForTimeout(500);
|
||||||
|
await expect(page.locator('button:has-text("Edit")')).toBeVisible();
|
||||||
|
const pageContent = await page.content();
|
||||||
|
expect(pageContent).toContain('!!! custom');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('should not duplicate params when placeholder already exists', async ({ page }) => {
|
||||||
|
await page.goto('/');
|
||||||
|
await page.click('button:has-text("Create new")');
|
||||||
|
const nameInput = page.locator('input[placeholder="name"]').first();
|
||||||
|
const valueInput = page.locator('input[placeholder="value"]').first();
|
||||||
|
const addButton = page.locator('button.btn-success').first();
|
||||||
|
await nameInput.fill('host');
|
||||||
|
await valueInput.fill('localhost:8080');
|
||||||
|
await addButton.click();
|
||||||
|
await page.waitForTimeout(500);
|
||||||
|
await page.click('a:has-text("Content Template")');
|
||||||
|
await page.waitForTimeout(500);
|
||||||
|
await page.click('button:has-text("Edit")');
|
||||||
|
await page.waitForTimeout(300);
|
||||||
|
const textarea = page.locator('textarea');
|
||||||
|
await textarea.fill('{\n "!!! host": "@host@",\n "apiUrl": "http://@host@/api"\n}');
|
||||||
|
await page.waitForTimeout(300);
|
||||||
|
await page.click('button:has-text("Save")');
|
||||||
|
await page.waitForTimeout(500);
|
||||||
|
await page.click('a:has-text("Env")');
|
||||||
|
await page.waitForTimeout(300);
|
||||||
|
await nameInput.fill('host');
|
||||||
|
await valueInput.fill('updated-host:9090');
|
||||||
|
await addButton.click();
|
||||||
|
await page.waitForTimeout(500);
|
||||||
|
await page.click('a:has-text("Content Template")');
|
||||||
|
await page.waitForTimeout(500);
|
||||||
|
const templateContent = await page.locator('.config-template-editor').textContent();
|
||||||
|
const hostKeyCount = (templateContent.match(/!!! host/g) || []).length;
|
||||||
|
expect(hostKeyCount).toBe(1);
|
||||||
|
const hostPlaceholderCount = (templateContent.match(/@host@/g) || []).length;
|
||||||
|
expect(hostPlaceholderCount).toBe(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('should validate template with unquoted placeholders', async ({ page }) => {
|
||||||
|
await page.goto('/');
|
||||||
|
await page.click('button:has-text("Create new")');
|
||||||
|
await page.waitForTimeout(500);
|
||||||
|
|
||||||
|
// Add a parameter
|
||||||
|
await page.click('button:has-text("✚")');
|
||||||
|
await page.waitForTimeout(300);
|
||||||
|
const nameInput = page.locator('input[placeholder="name"]');
|
||||||
|
const valueInput = page.locator('input[placeholder="value"]');
|
||||||
|
const addButton = page.locator('button:has-text("✓")');
|
||||||
|
await nameInput.fill('port');
|
||||||
|
await valueInput.fill('8080');
|
||||||
|
await addButton.click();
|
||||||
|
await page.waitForTimeout(500);
|
||||||
|
|
||||||
|
// Go to Content Template and edit with unquoted placeholder
|
||||||
|
await page.click('a:has-text("Content Template")');
|
||||||
|
await page.waitForTimeout(300);
|
||||||
|
await page.click('button:has-text("Edit")');
|
||||||
|
await page.waitForTimeout(300);
|
||||||
|
|
||||||
|
// Fill template with unquoted @port@ placeholder
|
||||||
|
const textarea = page.locator('textarea');
|
||||||
|
await textarea.fill('{\n "Host": "@host@",\n "Port": @port@,\n "Url": "http://@host@:@port@/api"\n}');
|
||||||
|
await page.waitForTimeout(300);
|
||||||
|
|
||||||
|
// Check that Save button is enabled (validation passed)
|
||||||
|
const saveButton = page.locator('button:has-text("Save")');
|
||||||
|
await expect(saveButton).toBeEnabled();
|
||||||
|
|
||||||
|
// Check that there's no JSON error
|
||||||
|
const errorAlert = page.locator('.alert-danger');
|
||||||
|
await expect(errorAlert).not.toBeVisible();
|
||||||
|
|
||||||
|
// Save the template
|
||||||
|
await saveButton.click();
|
||||||
|
await page.waitForTimeout(500);
|
||||||
|
|
||||||
|
// Verify it was saved - should be in view mode with Edit button visible
|
||||||
|
const editButton = page.locator('button:has-text("Edit")');
|
||||||
|
await expect(editButton).toBeVisible();
|
||||||
|
|
||||||
|
// Verify the template content is displayed correctly
|
||||||
|
const codeContent = page.locator('code');
|
||||||
|
await expect(codeContent).toBeVisible();
|
||||||
|
const content = await codeContent.textContent();
|
||||||
|
expect(content).toContain('@port@');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('should download config file with correct filename', async ({ page }) => {
|
||||||
|
await page.goto('/');
|
||||||
|
await page.click('button:has-text("Create new")');
|
||||||
|
await page.waitForTimeout(500);
|
||||||
|
const [download] = await Promise.all([
|
||||||
|
page.waitForEvent('download'),
|
||||||
|
page.click('button:has-text("Download")')
|
||||||
|
]);
|
||||||
|
const filename = download.suggestedFilename();
|
||||||
|
expect(filename).toMatch(/^config_\d{2}-\d{2}-\d{2}-\d{4}\.json\.xml$/);
|
||||||
|
// Save and read the file to verify content
|
||||||
|
await download.saveAs('temp-config.xml');
|
||||||
|
const contentStr = fs.readFileSync('temp-config.xml', 'utf8');
|
||||||
|
expect(contentStr).toContain('engine');
|
||||||
|
expect(contentStr).toContain('DEFAULT');
|
||||||
|
expect(contentStr).toContain('template');
|
||||||
|
fs.unlinkSync('temp-config.xml');
|
||||||
|
});
|
||||||
|
});
|
||||||
36
nginx.conf
Normal file
36
nginx.conf
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
server {
|
||||||
|
listen 80;
|
||||||
|
server_name localhost;
|
||||||
|
|
||||||
|
root /usr/share/nginx/html;
|
||||||
|
index index.html;
|
||||||
|
|
||||||
|
# Gzip compression
|
||||||
|
gzip on;
|
||||||
|
gzip_vary on;
|
||||||
|
gzip_min_length 1024;
|
||||||
|
gzip_proxied expired no-cache no-store private auth;
|
||||||
|
gzip_types text/plain text/css text/xml text/javascript application/x-javascript application/xml application/javascript application/json;
|
||||||
|
|
||||||
|
# Security headers
|
||||||
|
add_header X-Frame-Options "SAMEORIGIN" always;
|
||||||
|
add_header X-Content-Type-Options "nosniff" always;
|
||||||
|
add_header X-XSS-Protection "1; mode=block" always;
|
||||||
|
|
||||||
|
# SPA routing - all routes go to index.html
|
||||||
|
location / {
|
||||||
|
try_files $uri $uri/ /index.html;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Cache static assets
|
||||||
|
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ {
|
||||||
|
expires 1y;
|
||||||
|
add_header Cache-Control "public, immutable";
|
||||||
|
access_log off;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Disable cache for index.html
|
||||||
|
location = /index.html {
|
||||||
|
add_header Cache-Control "no-cache, no-store, must-revalidate";
|
||||||
|
}
|
||||||
|
}
|
||||||
64
package-lock.json
generated
64
package-lock.json
generated
@@ -15,6 +15,7 @@
|
|||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@eslint/js": "^9.17.0",
|
"@eslint/js": "^9.17.0",
|
||||||
|
"@playwright/test": "^1.58.2",
|
||||||
"@types/react": "^18.3.18",
|
"@types/react": "^18.3.18",
|
||||||
"@types/react-dom": "^18.3.5",
|
"@types/react-dom": "^18.3.5",
|
||||||
"@types/react-highlight": "^0.12.8",
|
"@types/react-highlight": "^0.12.8",
|
||||||
@@ -1228,6 +1229,22 @@
|
|||||||
"@jridgewell/sourcemap-codec": "^1.4.14"
|
"@jridgewell/sourcemap-codec": "^1.4.14"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@playwright/test": {
|
||||||
|
"version": "1.58.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.58.2.tgz",
|
||||||
|
"integrity": "sha512-akea+6bHYBBfA9uQqSYmlJXn61cTa+jbO87xVLCWbTqbWadRVmhxlXATaOjOgcBaWU4ePo0wB41KMFv3o35IXA==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"dependencies": {
|
||||||
|
"playwright": "1.58.2"
|
||||||
|
},
|
||||||
|
"bin": {
|
||||||
|
"playwright": "cli.js"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/@popperjs/core": {
|
"node_modules/@popperjs/core": {
|
||||||
"version": "2.11.8",
|
"version": "2.11.8",
|
||||||
"resolved": "https://registry.npmjs.org/@popperjs/core/-/core-2.11.8.tgz",
|
"resolved": "https://registry.npmjs.org/@popperjs/core/-/core-2.11.8.tgz",
|
||||||
@@ -3383,6 +3400,53 @@
|
|||||||
"url": "https://github.com/sponsors/jonschlinkert"
|
"url": "https://github.com/sponsors/jonschlinkert"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/playwright": {
|
||||||
|
"version": "1.58.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.58.2.tgz",
|
||||||
|
"integrity": "sha512-vA30H8Nvkq/cPBnNw4Q8TWz1EJyqgpuinBcHET0YVJVFldr8JDNiU9LaWAE1KqSkRYazuaBhTpB5ZzShOezQ6A==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"dependencies": {
|
||||||
|
"playwright-core": "1.58.2"
|
||||||
|
},
|
||||||
|
"bin": {
|
||||||
|
"playwright": "cli.js"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
},
|
||||||
|
"optionalDependencies": {
|
||||||
|
"fsevents": "2.3.2"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/playwright-core": {
|
||||||
|
"version": "1.58.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.58.2.tgz",
|
||||||
|
"integrity": "sha512-yZkEtftgwS8CsfYo7nm0KE8jsvm6i/PTgVtB8DL726wNf6H2IMsDuxCpJj59KDaxCtSnrWan2AeDqM7JBaultg==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"bin": {
|
||||||
|
"playwright-core": "cli.js"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/playwright/node_modules/fsevents": {
|
||||||
|
"version": "2.3.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz",
|
||||||
|
"integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==",
|
||||||
|
"dev": true,
|
||||||
|
"hasInstallScript": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"darwin"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/postcss": {
|
"node_modules/postcss": {
|
||||||
"version": "8.5.6",
|
"version": "8.5.6",
|
||||||
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.6.tgz",
|
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.6.tgz",
|
||||||
|
|||||||
@@ -8,7 +8,8 @@
|
|||||||
"build": "tsc -b && vite build",
|
"build": "tsc -b && vite build",
|
||||||
"lint": "eslint .",
|
"lint": "eslint .",
|
||||||
"preview": "vite preview",
|
"preview": "vite preview",
|
||||||
"test": "vitest"
|
"test": "vitest",
|
||||||
|
"test:e2e": "playwright test"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"bootstrap": "^5.3.3",
|
"bootstrap": "^5.3.3",
|
||||||
@@ -18,6 +19,7 @@
|
|||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@eslint/js": "^9.17.0",
|
"@eslint/js": "^9.17.0",
|
||||||
|
"@playwright/test": "^1.58.2",
|
||||||
"@types/react": "^18.3.18",
|
"@types/react": "^18.3.18",
|
||||||
"@types/react-dom": "^18.3.5",
|
"@types/react-dom": "^18.3.5",
|
||||||
"@types/react-highlight": "^0.12.8",
|
"@types/react-highlight": "^0.12.8",
|
||||||
|
|||||||
14
playwright.config.ts
Normal file
14
playwright.config.ts
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
import { defineConfig } from '@playwright/test';
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
testDir: './e2e',
|
||||||
|
fullyParallel: true,
|
||||||
|
forbidOnly: !!process.env.CI,
|
||||||
|
retries: process.env.CI ? 2 : 0,
|
||||||
|
workers: process.env.CI ? 1 : undefined,
|
||||||
|
reporter: 'html',
|
||||||
|
use: {
|
||||||
|
baseURL: 'http://localhost:5173',
|
||||||
|
trace: 'on-first-retry',
|
||||||
|
},
|
||||||
|
});
|
||||||
96
src/App.tsx
96
src/App.tsx
@@ -11,44 +11,92 @@ import logo from './assets/cgg.png'
|
|||||||
class AppState {
|
class AppState {
|
||||||
private constructor(
|
private constructor(
|
||||||
public config: Config = new Config(),
|
public config: Config = new Config(),
|
||||||
public envs: Env[] = [
|
|
||||||
],
|
|
||||||
) { }
|
) { }
|
||||||
|
|
||||||
static readonly Instance = new AppState();
|
static readonly Instance = new AppState();
|
||||||
|
|
||||||
public loadConfig(cfg: Config) {
|
public loadConfig(cfg: Config) {
|
||||||
this.envs = [...cfg.envs];
|
|
||||||
this.config = cfg;
|
this.config = cfg;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async saveEnv(env: Env): Promise<number> {
|
public async saveEnv(env: Env): Promise<number> {
|
||||||
|
// Simulate async save with 1 second delay
|
||||||
// Create a promise that resolves after 1 second
|
|
||||||
return await new Promise<number>((resolve) => {
|
return await new Promise<number>((resolve) => {
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
let idx = this.envs.findIndex(x => x.id === env.id);
|
console.log("Saved env:", env.name);
|
||||||
if (idx > -1) {
|
resolve(0);
|
||||||
this.envs[idx] = env;
|
|
||||||
console.log("UPDATED envs", this.envs);
|
|
||||||
}
|
|
||||||
resolve(idx); // Resolve the promise after updating
|
|
||||||
}, 1000);
|
}, 1000);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function App() {
|
function App() {
|
||||||
const [envs, setEnvs] = useState(AppState.Instance.envs);
|
const [config, setConfig] = useState(() => AppState.Instance.config);
|
||||||
|
const [envs, setEnvs] = useState(() => AppState.Instance.config.envs);
|
||||||
const [selectedEnv, setSelectedEnv] = useState(0);
|
const [selectedEnv, setSelectedEnv] = useState(0);
|
||||||
const [config, setConfig] = useState(AppState.Instance.config);
|
|
||||||
|
// Ensure selectedEnv is always valid
|
||||||
|
const validSelectedEnv = Math.min(selectedEnv, Math.max(0, envs.length - 1));
|
||||||
|
const currentEnv = envs[validSelectedEnv];
|
||||||
|
|
||||||
async function handleEnvChanged(env: Env) {
|
async function handleEnvChanged(env: Env) {
|
||||||
let idx = await AppState.Instance.saveEnv(env);
|
// Optimistic update - update React state immediately
|
||||||
if (idx > -1) {
|
setEnvs(prevEnvs => {
|
||||||
setEnvs([...AppState.Instance.envs]);
|
const newEnvs = [...prevEnvs];
|
||||||
setSelectedEnv(idx);
|
const idx = newEnvs.findIndex(x => x.id === env.id);
|
||||||
}
|
if (idx > -1) {
|
||||||
|
newEnvs[idx] = env;
|
||||||
|
}
|
||||||
|
return newEnvs;
|
||||||
|
});
|
||||||
|
|
||||||
|
// Also update config.envs and template to keep them in sync
|
||||||
|
setConfig(prevConfig => {
|
||||||
|
const newConfig = new Config();
|
||||||
|
newConfig.envs = prevConfig.envs.map(e => e.id === env.id ? env : e);
|
||||||
|
// Update template JSON with params from this environment
|
||||||
|
newConfig.template = prevConfig.template;
|
||||||
|
newConfig.updateTemplateFromEnv(env);
|
||||||
|
return newConfig;
|
||||||
|
});
|
||||||
|
|
||||||
|
// Fire off async save in background (no need to wait)
|
||||||
|
AppState.Instance.saveEnv(env);
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleEnvSelected(idx: number) {
|
||||||
|
setSelectedEnv(idx);
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleEnvAdded(env: Env): number {
|
||||||
|
const newIdx = envs.length;
|
||||||
|
setEnvs(prevEnvs => [...prevEnvs, env]);
|
||||||
|
setConfig(prevConfig => {
|
||||||
|
const newConfig = new Config();
|
||||||
|
newConfig.envs = [...prevConfig.envs, env];
|
||||||
|
newConfig.template = prevConfig.template;
|
||||||
|
return newConfig;
|
||||||
|
});
|
||||||
|
return newIdx;
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleEnvRemoved(envId: number) {
|
||||||
|
setEnvs(prevEnvs => prevEnvs.filter(e => e.id !== envId));
|
||||||
|
setConfig(prevConfig => {
|
||||||
|
const newConfig = new Config();
|
||||||
|
newConfig.envs = prevConfig.envs.filter(e => e.id !== envId);
|
||||||
|
newConfig.template = prevConfig.template;
|
||||||
|
return newConfig;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleTemplateSaved(newContent: string) {
|
||||||
|
setConfig(prevConfig => {
|
||||||
|
const newConfig = new Config();
|
||||||
|
newConfig.envs = prevConfig.envs;
|
||||||
|
newConfig.addTemplate(newContent);
|
||||||
|
return newConfig;
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -57,9 +105,9 @@ function App() {
|
|||||||
<div className="row mb-2">
|
<div className="row mb-2">
|
||||||
<FileChooser onSelected={x => {
|
<FileChooser onSelected={x => {
|
||||||
AppState.Instance.loadConfig(x);
|
AppState.Instance.loadConfig(x);
|
||||||
setEnvs(AppState.Instance.envs);
|
setEnvs(x.envs);
|
||||||
setConfig(AppState.Instance.config);
|
setConfig(x);
|
||||||
}} />
|
}} config={config} />
|
||||||
</div>
|
</div>
|
||||||
{envs.length > 0 ?
|
{envs.length > 0 ?
|
||||||
(<div className="row">
|
(<div className="row">
|
||||||
@@ -67,10 +115,12 @@ function App() {
|
|||||||
<Environment
|
<Environment
|
||||||
envs={envs}
|
envs={envs}
|
||||||
onChanged={async (e) => await handleEnvChanged(e)}
|
onChanged={async (e) => await handleEnvChanged(e)}
|
||||||
onSelected={x => setSelectedEnv(x)} />
|
onSelected={handleEnvSelected}
|
||||||
|
onAdd={handleEnvAdded}
|
||||||
|
onRemove={handleEnvRemoved} />
|
||||||
</section>
|
</section>
|
||||||
<section id="content" className="col-8 col-xl-7 border-start ms-1">
|
<section id="content" className="col-8 col-xl-7 border-start ms-1">
|
||||||
<Content env={envs[selectedEnv]} config={config} />
|
<Content env={currentEnv} config={config} onTemplateSaved={handleTemplateSaved} />
|
||||||
</section>
|
</section>
|
||||||
</div>)
|
</div>)
|
||||||
:
|
:
|
||||||
|
|||||||
39
src/builders/ConfigBuilder.ts
Normal file
39
src/builders/ConfigBuilder.ts
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
import { Config } from "../models/Config";
|
||||||
|
import { EnvBuilder } from "./EnvBuilder";
|
||||||
|
|
||||||
|
export class ConfigBuilder {
|
||||||
|
/**
|
||||||
|
* Builds a full XML config file with all environments and template.
|
||||||
|
*/
|
||||||
|
public static buildFullXml(config: Config): string {
|
||||||
|
const lines: string[] = [];
|
||||||
|
lines.push("<engine>");
|
||||||
|
|
||||||
|
// Add all environments
|
||||||
|
for (const env of config.envs) {
|
||||||
|
const envXml = new EnvBuilder().buildEnv(env);
|
||||||
|
lines.push(envXml);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add template
|
||||||
|
lines.push(" <template>");
|
||||||
|
lines.push(config.template.content);
|
||||||
|
lines.push(" </template>");
|
||||||
|
|
||||||
|
lines.push("</engine>");
|
||||||
|
return lines.join("\r\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generates filename with timestamp: config_yy-dd-MM-HHmm.json.xml
|
||||||
|
*/
|
||||||
|
public static generateFilename(): string {
|
||||||
|
const now = new Date();
|
||||||
|
const yy = now.getFullYear().toString().slice(-2);
|
||||||
|
const dd = String(now.getDate()).padStart(2, '0');
|
||||||
|
const MM = String(now.getMonth() + 1).padStart(2, '0');
|
||||||
|
const HH = String(now.getHours()).padStart(2, '0');
|
||||||
|
const mm = String(now.getMinutes()).padStart(2, '0');
|
||||||
|
return `config_${yy}-${dd}-${MM}-${HH}${mm}.json.xml`;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -16,6 +16,14 @@ export class EnvBuilder implements IBuilder<Env> {
|
|||||||
this._src = v;
|
this._src = v;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Builds XML for a single environment (static method for direct use)
|
||||||
|
*/
|
||||||
|
public buildEnv(env: Env): string {
|
||||||
|
this.src = env;
|
||||||
|
return this.build();
|
||||||
|
}
|
||||||
|
|
||||||
build(): string {
|
build(): string {
|
||||||
return this
|
return this
|
||||||
.open()
|
.open()
|
||||||
|
|||||||
@@ -1,9 +1,6 @@
|
|||||||
import { Env } from "../models/Env";
|
import { Env } from "../models/Env";
|
||||||
import { EnvBuilder } from "./EnvBuilder";
|
import { EnvBuilder } from "./EnvBuilder";
|
||||||
|
import { ConfigBuilder } from "./ConfigBuilder";
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
export interface IBuilder<T> {
|
export interface IBuilder<T> {
|
||||||
get src(): T;
|
get src(): T;
|
||||||
@@ -20,7 +17,9 @@ export class Builder {
|
|||||||
};
|
};
|
||||||
|
|
||||||
public static getEnvs(envs: Env[]): string {
|
public static getEnvs(envs: Env[]): string {
|
||||||
return envs.map(x => Builder.getEnv(x).build()).join("\r\n");
|
return envs.map(x => Builder.getEnv(x).build()).join("\r\n");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export { ConfigBuilder };
|
||||||
|
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
import { Env } from "../models/Env";
|
import { Env } from "../models/Env";
|
||||||
import { ConfigReader } from "../models/ConfigReader";
|
import { ConfigReader } from "../models/ConfigReader";
|
||||||
import { Config } from "../models/Config";
|
import { Config } from "../models/Config";
|
||||||
|
import { ConfigBuilder } from "../builders/ConfigBuilder";
|
||||||
|
|
||||||
|
export function FileChooser(props: { onSelected: (x: Config) => void, config?: Config }) {
|
||||||
export function FileChooser(props: { onSelected: (x: Config) => void }) {
|
|
||||||
async function handleFile(x: React.ChangeEvent<HTMLInputElement>) {
|
async function handleFile(x: React.ChangeEvent<HTMLInputElement>) {
|
||||||
let file = x.target.files![0];
|
let file = x.target.files![0];
|
||||||
|
|
||||||
@@ -18,15 +18,47 @@ export function FileChooser(props: { onSelected: (x: Config) => void }) {
|
|||||||
|
|
||||||
function handleNew(){
|
function handleNew(){
|
||||||
let cfg = new Config();
|
let cfg = new Config();
|
||||||
cfg.addEnvs([new Env(0,"DEFAULT", [])]);
|
cfg.addEnvs([new Env(0, "DEFAULT", [])]);
|
||||||
|
cfg.addTemplate("{}");
|
||||||
props.onSelected(cfg);
|
props.onSelected(cfg);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function handleDownload() {
|
||||||
|
if (!props.config) {
|
||||||
|
alert("No configuration loaded");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const xmlContent = ConfigBuilder.buildFullXml(props.config);
|
||||||
|
const filename = ConfigBuilder.generateFilename();
|
||||||
|
|
||||||
|
// Create blob and download
|
||||||
|
const blob = new Blob([xmlContent], { type: "text/xml" });
|
||||||
|
const url = URL.createObjectURL(blob);
|
||||||
|
const link = document.createElement("a");
|
||||||
|
link.href = url;
|
||||||
|
link.download = filename;
|
||||||
|
document.body.appendChild(link);
|
||||||
|
link.click();
|
||||||
|
document.body.removeChild(link);
|
||||||
|
URL.revokeObjectURL(url);
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<div className="col-2">
|
<div className="col-2">
|
||||||
<button className="btn btn-primary" onClick={handleNew} >Create new</button>
|
<button className="btn btn-primary" onClick={handleNew} >Create new</button>
|
||||||
</div>
|
</div>
|
||||||
|
<div className="col-auto">
|
||||||
|
<button
|
||||||
|
className="btn btn-success"
|
||||||
|
onClick={handleDownload}
|
||||||
|
disabled={!props.config}
|
||||||
|
title="Download full config template"
|
||||||
|
>
|
||||||
|
⬇ Download
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
<div className="col-1">or</div>
|
<div className="col-1">or</div>
|
||||||
|
|
||||||
<div className="col">
|
<div className="col">
|
||||||
|
|||||||
145
src/componets/content/ConfigTemplate.tsx
Normal file
145
src/componets/content/ConfigTemplate.tsx
Normal file
@@ -0,0 +1,145 @@
|
|||||||
|
import { useState, useEffect } from "react";
|
||||||
|
import Highlight from 'react-highlight';
|
||||||
|
import 'highlight.js/styles/far.css';
|
||||||
|
import { Config } from "../../models/Config";
|
||||||
|
|
||||||
|
interface ConfigTemplateProps {
|
||||||
|
config: Config;
|
||||||
|
onSaved: (newContent: string) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ConfigTemplate(props: ConfigTemplateProps) {
|
||||||
|
const [mode, setMode] = useState<'view' | 'edit'>('view');
|
||||||
|
const [draftContent, setDraftContent] = useState(props.config.template.content);
|
||||||
|
const [originalContent, setOriginalContent] = useState(props.config.template.content);
|
||||||
|
const [jsonError, setJsonError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
// Sync draft when config changes (only in view mode)
|
||||||
|
useEffect(() => {
|
||||||
|
if (mode === 'view') {
|
||||||
|
setDraftContent(props.config.template.content);
|
||||||
|
}
|
||||||
|
}, [props.config.template.content, mode]);
|
||||||
|
|
||||||
|
function handleEdit() {
|
||||||
|
setOriginalContent(props.config.template.content);
|
||||||
|
setDraftContent(props.config.template.content);
|
||||||
|
setJsonError(null);
|
||||||
|
setMode('edit');
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleRevert() {
|
||||||
|
setDraftContent(originalContent);
|
||||||
|
setJsonError(null);
|
||||||
|
setMode('view');
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleSave() {
|
||||||
|
// Validate JSON before saving (with placeholder support)
|
||||||
|
try {
|
||||||
|
const sanitizedValue = draftContent.replace(/@[^@]+@/g, '1');
|
||||||
|
JSON.parse(sanitizedValue);
|
||||||
|
setJsonError(null);
|
||||||
|
props.onSaved(draftContent);
|
||||||
|
setMode('view');
|
||||||
|
} catch (e) {
|
||||||
|
setJsonError((e as Error).message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleDraftChange(value: string) {
|
||||||
|
setDraftContent(value);
|
||||||
|
// Validate JSON on every change
|
||||||
|
try {
|
||||||
|
if (value.trim()) {
|
||||||
|
// Replace @placeholders@ with valid JSON values for validation
|
||||||
|
// Strategy: Replace ALL @...@ patterns with "1" (valid for both string and numeric contexts)
|
||||||
|
const sanitizedValue = value.replace(/@[^@]+@/g, '1');
|
||||||
|
|
||||||
|
JSON.parse(sanitizedValue);
|
||||||
|
setJsonError(null);
|
||||||
|
} else {
|
||||||
|
setJsonError(null);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
setJsonError((e as Error).message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleKeyDown(e: React.KeyboardEvent<HTMLTextAreaElement>) {
|
||||||
|
if (e.key === 'Tab') {
|
||||||
|
e.preventDefault();
|
||||||
|
const textarea = e.currentTarget;
|
||||||
|
const start = textarea.selectionStart;
|
||||||
|
const end = textarea.selectionEnd;
|
||||||
|
const value = textarea.value;
|
||||||
|
|
||||||
|
// Insert 2 spaces at cursor position
|
||||||
|
const newValue = value.substring(0, start) + ' ' + value.substring(end);
|
||||||
|
handleDraftChange(newValue);
|
||||||
|
|
||||||
|
// Move cursor after the inserted spaces
|
||||||
|
setTimeout(() => {
|
||||||
|
textarea.selectionStart = textarea.selectionEnd = start + 2;
|
||||||
|
}, 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const isValidJson = jsonError === null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="config-template-editor">
|
||||||
|
{mode === 'view' ? (
|
||||||
|
<>
|
||||||
|
<div className="mb-2">
|
||||||
|
<button className="btn btn-primary btn-sm" onClick={handleEdit}>
|
||||||
|
✎ Edit
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<Highlight className="language-json">
|
||||||
|
{props.config.template.content || "{}"}
|
||||||
|
</Highlight>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<div className="mb-2 d-flex gap-2 align-items-center">
|
||||||
|
<button
|
||||||
|
className="btn btn-success btn-sm"
|
||||||
|
onClick={handleSave}
|
||||||
|
disabled={!isValidJson}
|
||||||
|
>
|
||||||
|
✓ Save
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
className="btn btn-secondary btn-sm"
|
||||||
|
onClick={handleRevert}
|
||||||
|
>
|
||||||
|
× Revert
|
||||||
|
</button>
|
||||||
|
<span className={`ms-2 ${isValidJson ? 'text-success' : 'text-danger'}`}>
|
||||||
|
{isValidJson ? 'Valid JSON' : 'Invalid JSON'}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
{jsonError && (
|
||||||
|
<div className="alert alert-danger py-1 px-2 mb-2" style={{ fontSize: '0.875rem' }}>
|
||||||
|
{jsonError}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<textarea
|
||||||
|
className={`form-control font-monospace ${isValidJson ? 'border-success' : 'border-danger'}`}
|
||||||
|
value={draftContent}
|
||||||
|
onChange={(e) => handleDraftChange(e.target.value)}
|
||||||
|
onKeyDown={handleKeyDown}
|
||||||
|
rows={20}
|
||||||
|
style={{
|
||||||
|
fontFamily: 'monospace',
|
||||||
|
whiteSpace: 'pre',
|
||||||
|
overflowX: 'auto'
|
||||||
|
}}
|
||||||
|
spellCheck={false}
|
||||||
|
/>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
.highlihgt-scrolled {
|
.highlihgt-scrolled {
|
||||||
overflow-x: auto;
|
overflow-x: auto;
|
||||||
max-width: 90%;
|
/ max-width: 90%;
|
||||||
}
|
}
|
||||||
@@ -4,17 +4,22 @@ import Highlight from 'react-highlight'
|
|||||||
import 'highlight.js/styles/far.css'
|
import 'highlight.js/styles/far.css'
|
||||||
import { Builder } from "../../builders";
|
import { Builder } from "../../builders";
|
||||||
import { Config } from "../../models/Config";
|
import { Config } from "../../models/Config";
|
||||||
|
import { ConfigTemplate } from "./ConfigTemplate";
|
||||||
|
|
||||||
|
|
||||||
export function Content(props: { config: Config, env: Env }) {
|
export function Content(props: { config: Config, env: Env, onTemplateSaved: (newContent: string) => void }) {
|
||||||
const [selectTab, setTab] = useState(ContentType.Env);
|
const [selectTab, setTab] = useState(ContentType.Env);
|
||||||
|
|
||||||
|
// Validate placeholders for warning badge
|
||||||
|
const missingPlaceholders = props.config.validatePlaceholders();
|
||||||
|
const hasValidationWarnings = missingPlaceholders.length > 0;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<ContentTabs onSelected={(id) => setTab(id)} />
|
<ContentTabs onSelected={(id) => setTab(id)} selectedTab={selectTab} hasValidationWarnings={hasValidationWarnings} />
|
||||||
<div className="">
|
<div className="">
|
||||||
{selectTab == ContentType.Env ? (<ContentParams env={props.env} />) : ""}
|
{selectTab == ContentType.Env ? (<ContentParams env={props.env} />) : ""}
|
||||||
{selectTab == ContentType.Json ? (<ContentTemplate env={props.env} config={props.config} />) : ""}
|
{selectTab == ContentType.Json ? (<ConfigTemplate config={props.config} onSaved={props.onTemplateSaved} />) : ""}
|
||||||
{selectTab == ContentType.Raw ? (<ContentRaw config={props.config} env={props.env} />) : ""}
|
{selectTab == ContentType.Raw ? (<ContentRaw config={props.config} env={props.env} />) : ""}
|
||||||
{selectTab == ContentType.Test ? (<ContentTest config={props.config} env={props.env} />) : ""}
|
{selectTab == ContentType.Test ? (<ContentTest config={props.config} env={props.env} />) : ""}
|
||||||
</div>
|
</div>
|
||||||
@@ -29,16 +34,13 @@ enum ContentType {
|
|||||||
Test = 3
|
Test = 3
|
||||||
}
|
}
|
||||||
|
|
||||||
function ContentTabs(props: { onSelected: (id: ContentType) => void }) {
|
function ContentTabs(props: { onSelected: (id: ContentType) => void, selectedTab: ContentType, hasValidationWarnings: boolean }) {
|
||||||
const [selectTab, setSelect] = useState(ContentType.Env);
|
|
||||||
|
|
||||||
function clickHandler(type: ContentType) {
|
function clickHandler(type: ContentType) {
|
||||||
setSelect(type);
|
|
||||||
props.onSelected(type);
|
props.onSelected(type);
|
||||||
}
|
}
|
||||||
|
|
||||||
function isActive(type: ContentType): string {
|
function isActive(type: ContentType): string {
|
||||||
return type == selectTab ? " active" : " ";
|
return type == props.selectedTab ? " active" : " ";
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -47,7 +49,12 @@ function ContentTabs(props: { onSelected: (id: ContentType) => void }) {
|
|||||||
<a className={"nav-link" + isActive(ContentType.Env)} aria-current="page" href="#" onClick={() => clickHandler(ContentType.Env)}>Env</a>
|
<a className={"nav-link" + isActive(ContentType.Env)} aria-current="page" href="#" onClick={() => clickHandler(ContentType.Env)}>Env</a>
|
||||||
</li>
|
</li>
|
||||||
<li className="nav-item">
|
<li className="nav-item">
|
||||||
<a className={"nav-link" + isActive(ContentType.Json)} href="#" onClick={() => clickHandler(ContentType.Json)} >Content Template</a>
|
<a className={"nav-link" + isActive(ContentType.Json)} href="#" onClick={() => clickHandler(ContentType.Json)} >
|
||||||
|
Content Template
|
||||||
|
{props.hasValidationWarnings && (
|
||||||
|
<span className="badge bg-warning text-dark ms-1">!</span>
|
||||||
|
)}
|
||||||
|
</a>
|
||||||
</li>
|
</li>
|
||||||
<li className="nav-item">
|
<li className="nav-item">
|
||||||
<a className={"nav-link" + isActive(ContentType.Raw)} href="#" onClick={() => clickHandler(ContentType.Raw)}>Raw template</a>
|
<a className={"nav-link" + isActive(ContentType.Raw)} href="#" onClick={() => clickHandler(ContentType.Raw)}>Raw template</a>
|
||||||
@@ -129,7 +136,7 @@ function fillTemplate(config: Config, env: Env): string {
|
|||||||
let filledTemplate = config.template.content;
|
let filledTemplate = config.template.content;
|
||||||
const placeholderRegex = /@(\w+)@/g;
|
const placeholderRegex = /@(\w+)@/g;
|
||||||
|
|
||||||
filledTemplate = filledTemplate.replace(placeholderRegex, (match, paramName) => {
|
filledTemplate = filledTemplate.replace(placeholderRegex, (_, paramName) => {
|
||||||
if (paramName === Config.ENV_NAME_PARAM) {
|
if (paramName === Config.ENV_NAME_PARAM) {
|
||||||
return env.name ?? "--NO-VALUE--";
|
return env.name ?? "--NO-VALUE--";
|
||||||
}
|
}
|
||||||
@@ -139,18 +146,6 @@ function fillTemplate(config: Config, env: Env): string {
|
|||||||
return filledTemplate;
|
return filledTemplate;
|
||||||
}
|
}
|
||||||
|
|
||||||
function ContentTemplate(props: { config: Config, env: Env }) {
|
|
||||||
|
|
||||||
let text = props.config.getTemplateAsJson() ?? "{//no content. at all. tottaly empty!!!\n}";
|
|
||||||
return (
|
|
||||||
<>
|
|
||||||
<Highlight className="language-json" >
|
|
||||||
{text ?? ""}
|
|
||||||
</Highlight>
|
|
||||||
</>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
function ContentParams(props: { env: Env }) {
|
function ContentParams(props: { env: Env }) {
|
||||||
const bldr = Builder.getEnv(props.env);
|
const bldr = Builder.getEnv(props.env);
|
||||||
|
|
||||||
|
|||||||
95
src/componets/env/Environment.tsx
vendored
95
src/componets/env/Environment.tsx
vendored
@@ -1,10 +1,19 @@
|
|||||||
import { useState } from "react";
|
import { useState, useEffect } from "react";
|
||||||
import { AddEvent, AppEvent, DelEvent, Env, UpdateEvent } from "../../models/Env";
|
import { AddEvent, AppEvent, DelEvent, Env, UpdateEvent } from "../../models/Env";
|
||||||
import { EnvParam } from "../../models/EnvParam";
|
import { EnvParam } from "../../models/EnvParam";
|
||||||
import { EnvironmentParam } from "./EnvironmentParam";
|
import { EnvironmentParam } from "./EnvironmentParam";
|
||||||
|
|
||||||
export function Environment(props: { envs: Env[], onChanged: (env: Env) => void, onSelected: (envId: number) => void }) {
|
export function Environment(props: { envs: Env[], onChanged: (env: Env) => void, onSelected: (envId: number) => void, onAdd: (env: Env) => number, onRemove: (envId: number) => void }) {
|
||||||
const [currEnv, setCurrEnv] = useState(props.envs[0]);
|
const [currEnvId, setCurrEnvId] = useState(props.envs[0]?.id);
|
||||||
|
|
||||||
|
// Sync currEnvId when props.envs changes
|
||||||
|
useEffect(() => {
|
||||||
|
if (!props.envs.find(e => e.id === currEnvId)) {
|
||||||
|
setCurrEnvId(props.envs[0]?.id);
|
||||||
|
}
|
||||||
|
}, [props.envs, currEnvId]);
|
||||||
|
|
||||||
|
const currEnv = props.envs.find(e => e.id === currEnvId) ?? props.envs[0];
|
||||||
|
|
||||||
function handleParamChanged(e: AppEvent<EnvParam>) {
|
function handleParamChanged(e: AppEvent<EnvParam>) {
|
||||||
let isChanged = false;
|
let isChanged = false;
|
||||||
@@ -26,12 +35,47 @@ export function Environment(props: { envs: Env[], onChanged: (env: Env) => void,
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (isChanged) {
|
if (isChanged) {
|
||||||
let idx = props.envs.findIndex(x => x.id === env.id);
|
props.onChanged(env);
|
||||||
if (idx > -1) {
|
setCurrEnvId(env.id);
|
||||||
props.envs[idx] = env;
|
}
|
||||||
props.onChanged(props.envs[idx]);
|
}
|
||||||
setCurrEnv(env);
|
|
||||||
|
function handleAddEnv() {
|
||||||
|
const name = prompt("Enter new environment name:");
|
||||||
|
if (!name || name.trim() === "") return;
|
||||||
|
|
||||||
|
// Calculate next integer ID based on max existing ID
|
||||||
|
const maxId = props.envs.reduce((max, e) => Math.max(max, e.id ?? 0), -1);
|
||||||
|
const newId = maxId + 1;
|
||||||
|
|
||||||
|
const newEnv = new Env(
|
||||||
|
newId,
|
||||||
|
name.trim(),
|
||||||
|
[...currEnv.params]
|
||||||
|
);
|
||||||
|
// Parent synchronously adds the env and returns the index
|
||||||
|
const newIdx = props.onAdd(newEnv);
|
||||||
|
setCurrEnvId(newEnv.id);
|
||||||
|
props.onSelected(newIdx);
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleRemoveEnv() {
|
||||||
|
if (currEnv.isDefault()) {
|
||||||
|
alert("Cannot remove DEFAULT environment");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!confirm(`Remove environment "${currEnv.name}"?`)) return;
|
||||||
|
|
||||||
|
const idx = props.envs.findIndex(x => x.id === currEnv.id);
|
||||||
|
if (idx > -1 && currEnv.id !== undefined) {
|
||||||
|
// Let parent handle the removal
|
||||||
|
props.onRemove(currEnv.id);
|
||||||
|
const newIdx = Math.max(0, idx - 1);
|
||||||
|
const newEnv = props.envs[newIdx];
|
||||||
|
if (newEnv?.id !== undefined) {
|
||||||
|
setCurrEnvId(newEnv.id);
|
||||||
}
|
}
|
||||||
|
props.onSelected(newIdx);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -44,19 +88,28 @@ export function Environment(props: { envs: Env[], onChanged: (env: Env) => void,
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<div className="row">
|
<div className="row g-0">
|
||||||
<select
|
<div className="col">
|
||||||
id="environments"
|
<select
|
||||||
name="environments"
|
id="environments"
|
||||||
aria-label="Environments"
|
name="environments"
|
||||||
className="form-select"
|
aria-label="Environments"
|
||||||
onChange={x => {
|
className="form-select"
|
||||||
let id = Number.parseInt(x.target.value);
|
value={currEnvId}
|
||||||
setCurrEnv(props.envs[id]);
|
onChange={x => {
|
||||||
props.onSelected(id);
|
let id = Number.parseInt(x.target.value);
|
||||||
}}>
|
setCurrEnvId(id);
|
||||||
{selectOptions}
|
props.onSelected(id);
|
||||||
</select>
|
}}>
|
||||||
|
{selectOptions}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div className="col-auto ms-2">
|
||||||
|
<button className="btn btn-success" onClick={handleAddEnv} title="Add environment">✚</button>
|
||||||
|
</div>
|
||||||
|
<div className="col-auto ms-2">
|
||||||
|
<button className="btn btn-danger" onClick={handleRemoveEnv} title="Remove environment" disabled={currEnv.isDefault()}>−</button>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="row">Params</div>
|
<div className="row">Params</div>
|
||||||
{paramCtrls}
|
{paramCtrls}
|
||||||
|
|||||||
@@ -60,6 +60,45 @@ export class Config {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Updates the template JSON by adding/updating params from the given environment.
|
||||||
|
* Params are added as "!!! paramName": "@paramName@" placeholder pairs.
|
||||||
|
* If a param's @placeholder@ already exists in template, it won't be added.
|
||||||
|
* Existing template content is preserved.
|
||||||
|
*/
|
||||||
|
updateTemplateFromEnv(env: Env) {
|
||||||
|
let templateObj: Record<string, any> = {};
|
||||||
|
|
||||||
|
// Try to parse existing template as JSON
|
||||||
|
try {
|
||||||
|
if (this.template.content.trim()) {
|
||||||
|
templateObj = JSON.parse(this.template.content);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
// If parsing fails, start with empty object
|
||||||
|
console.warn("Template is not valid JSON, starting fresh");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add/update params from the environment as placeholders
|
||||||
|
for (const param of env.params) {
|
||||||
|
if (param.name && param.name.trim() !== "") {
|
||||||
|
const placeholderValue = `@${param.name}@`;
|
||||||
|
|
||||||
|
// Check if this placeholder already exists anywhere in the template
|
||||||
|
const placeholderAlreadyExists = this.template.content.includes(placeholderValue);
|
||||||
|
|
||||||
|
if (!placeholderAlreadyExists) {
|
||||||
|
const placeholderKey = `!!! ${param.name}`;
|
||||||
|
templateObj[placeholderKey] = placeholderValue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Convert back to formatted JSON string
|
||||||
|
const newTemplateContent = JSON.stringify(templateObj, null, 4);
|
||||||
|
this.template = new ConfigTemplate(newTemplateContent);
|
||||||
|
}
|
||||||
|
|
||||||
validateParams(): string[] {
|
validateParams(): string[] {
|
||||||
const envKeys = this.envs.map(env => env.params.map(param => param.name)).flat();
|
const envKeys = this.envs.map(env => env.params.map(param => param.name)).flat();
|
||||||
const missingParams = this.template.Params.filter(param => param != Config.ENV_NAME_PARAM && !envKeys.includes(param));
|
const missingParams = this.template.Params.filter(param => param != Config.ENV_NAME_PARAM && !envKeys.includes(param));
|
||||||
@@ -70,5 +109,50 @@ export class Config {
|
|||||||
|
|
||||||
return missingParams;
|
return missingParams;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Validates that all @placeholders@ in template have corresponding params.
|
||||||
|
* Checks DEFAULT env first, then all custom envs.
|
||||||
|
* Returns array of placeholder names that are not defined.
|
||||||
|
*/
|
||||||
|
validatePlaceholders(): string[] {
|
||||||
|
const defaultEnv = this.envs.find(e => e.name === "DEFAULT");
|
||||||
|
const customEnvs = this.envs.filter(e => e.name !== "DEFAULT");
|
||||||
|
|
||||||
|
// Collect all param names from DEFAULT
|
||||||
|
const defaultParamNames = new Set(
|
||||||
|
defaultEnv?.params.map(p => p.name).filter(n => n && n.trim() !== "") || []
|
||||||
|
);
|
||||||
|
|
||||||
|
// Collect all param names from all custom envs
|
||||||
|
const customParamNames = new Set(
|
||||||
|
customEnvs.flatMap(e => e.params.map(p => p.name).filter(n => n && n.trim() !== ""))
|
||||||
|
);
|
||||||
|
|
||||||
|
// Extract all @placeholders@ from template
|
||||||
|
const placeholderRegex = /@(\w+)@/g;
|
||||||
|
const placeholdersInTemplate = new Set<string>();
|
||||||
|
let match;
|
||||||
|
while ((match = placeholderRegex.exec(this.template.content)) !== null) {
|
||||||
|
placeholdersInTemplate.add(match[1]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Find placeholders that don't have matching params
|
||||||
|
const missingParams: string[] = [];
|
||||||
|
for (const placeholder of placeholdersInTemplate) {
|
||||||
|
if (placeholder === Config.ENV_NAME_PARAM) continue; // Skip built-in
|
||||||
|
|
||||||
|
// Check if exists in DEFAULT or in ANY custom env
|
||||||
|
const inDefault = defaultParamNames.has(placeholder);
|
||||||
|
const inCustom = customParamNames.has(placeholder);
|
||||||
|
|
||||||
|
// Valid if: in DEFAULT, or in at least one custom env
|
||||||
|
if (!inDefault && !inCustom) {
|
||||||
|
missingParams.push(placeholder);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return missingParams;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
11
src/test/ConfigBuilder.test.ts
Normal file
11
src/test/ConfigBuilder.test.ts
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
import { describe, it, expect } from 'vitest';
|
||||||
|
import { ConfigBuilder } from '../builders/ConfigBuilder';
|
||||||
|
|
||||||
|
describe('ConfigBuilder', () => {
|
||||||
|
describe('generateFilename', () => {
|
||||||
|
it('should generate filename with correct format', () => {
|
||||||
|
const filename = ConfigBuilder.generateFilename();
|
||||||
|
expect(filename).toMatch(/^config_\d{2}-\d{2}-\d{2}-\d{4}\.json\.xml$/);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
108
src/test/ConfigTemplate.test.ts
Normal file
108
src/test/ConfigTemplate.test.ts
Normal file
@@ -0,0 +1,108 @@
|
|||||||
|
import { describe, it, expect } from 'vitest';
|
||||||
|
|
||||||
|
describe('JSON Validation with @placeholders@', () => {
|
||||||
|
/**
|
||||||
|
* Helper function that mimics the validation logic in ConfigTemplate.tsx
|
||||||
|
*/
|
||||||
|
function validateJsonWithPlaceholders(value: string): { valid: boolean; error?: string } {
|
||||||
|
try {
|
||||||
|
if (!value.trim()) {
|
||||||
|
return { valid: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
// This is the current implementation from ConfigTemplate.tsx
|
||||||
|
// Replace ALL @...@ patterns with "1" (valid for both string and numeric contexts)
|
||||||
|
const sanitizedValue = value.replace(/@[^@]+@/g, '1');
|
||||||
|
|
||||||
|
JSON.parse(sanitizedValue);
|
||||||
|
return { valid: true };
|
||||||
|
} catch (e) {
|
||||||
|
return { valid: false, error: (e as Error).message };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
it('should validate quoted placeholders', () => {
|
||||||
|
const json = `{
|
||||||
|
"Host": "@host@",
|
||||||
|
"Port": "@port@"
|
||||||
|
}`;
|
||||||
|
|
||||||
|
const result = validateJsonWithPlaceholders(json);
|
||||||
|
expect(result.valid).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should validate unquoted placeholders', () => {
|
||||||
|
const json = `{
|
||||||
|
"Host": "@host@",
|
||||||
|
"Port": @port@
|
||||||
|
}`;
|
||||||
|
|
||||||
|
const result = validateJsonWithPlaceholders(json);
|
||||||
|
expect(result.valid).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should validate mixed quoted and unquoted placeholders', () => {
|
||||||
|
const json = `{
|
||||||
|
"Host": "@host@",
|
||||||
|
"Port": @port@,
|
||||||
|
"ApiPath": "@host@:@port@/v1/data",
|
||||||
|
"MessageBroker": {
|
||||||
|
"hosts": @MessageBrokerHosts@
|
||||||
|
}
|
||||||
|
}`;
|
||||||
|
|
||||||
|
const result = validateJsonWithPlaceholders(json);
|
||||||
|
expect(result.valid).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should validate placeholders inside strings (URLs)', () => {
|
||||||
|
const json = `{
|
||||||
|
"ApiUrl": "http://@host@:@port@/api"
|
||||||
|
}`;
|
||||||
|
|
||||||
|
const result = validateJsonWithPlaceholders(json);
|
||||||
|
expect(result.valid).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should validate complex real-world template', () => {
|
||||||
|
const json = `{
|
||||||
|
"Host": "@host@",
|
||||||
|
"Port": @port@,
|
||||||
|
|
||||||
|
"ApiPath": "@host@:@port@/v1/data",
|
||||||
|
|
||||||
|
"MessageBroker": {
|
||||||
|
"hosts": @MessageBrokerHosts@
|
||||||
|
},
|
||||||
|
|
||||||
|
"basePath": "./@env_name@/in",
|
||||||
|
|
||||||
|
"NoParam": "@no_param@"
|
||||||
|
}`;
|
||||||
|
|
||||||
|
const result = validateJsonWithPlaceholders(json);
|
||||||
|
expect(result.valid).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should reject invalid JSON structure', () => {
|
||||||
|
const json = `{
|
||||||
|
"Host": "@host@",
|
||||||
|
"Port": @port@
|
||||||
|
"Missing": "comma"
|
||||||
|
}`;
|
||||||
|
|
||||||
|
const result = validateJsonWithPlaceholders(json);
|
||||||
|
expect(result.valid).toBe(false);
|
||||||
|
expect(result.error).toContain('Expected');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should handle empty value', () => {
|
||||||
|
const result = validateJsonWithPlaceholders('');
|
||||||
|
expect(result.valid).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should handle whitespace only', () => {
|
||||||
|
const result = validateJsonWithPlaceholders(' \n\t ');
|
||||||
|
expect(result.valid).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
111
src/test/Environment.test.tsx
Normal file
111
src/test/Environment.test.tsx
Normal file
@@ -0,0 +1,111 @@
|
|||||||
|
import { describe, it, expect, beforeEach } from 'vitest';
|
||||||
|
import { Env } from '../models/Env';
|
||||||
|
import { EnvParam } from '../models/EnvParam';
|
||||||
|
|
||||||
|
describe('Environment Management', () => {
|
||||||
|
let envs: Env[];
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
envs = [
|
||||||
|
new Env(0, 'DEFAULT', [
|
||||||
|
new EnvParam(1, 'host', 'http://localhost'),
|
||||||
|
new EnvParam(2, 'port', '8080')
|
||||||
|
]),
|
||||||
|
new Env(1, 'env1', [
|
||||||
|
new EnvParam(3, 'port', '9090')
|
||||||
|
])
|
||||||
|
];
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('add environment', () => {
|
||||||
|
it('should create new environment with copied params from current', () => {
|
||||||
|
const currentEnv = envs[1]; // env1 with port=9090
|
||||||
|
const newEnvName = 'env2';
|
||||||
|
|
||||||
|
// Simulate copying params from current env
|
||||||
|
const newEnv = new Env(
|
||||||
|
Math.random() * 10000,
|
||||||
|
newEnvName,
|
||||||
|
[...currentEnv.params]
|
||||||
|
);
|
||||||
|
envs.push(newEnv);
|
||||||
|
|
||||||
|
expect(envs).toHaveLength(3);
|
||||||
|
expect(envs[2].name).toBe('env2');
|
||||||
|
expect(envs[2].params).toHaveLength(1);
|
||||||
|
expect(envs[2].params[0].name).toBe('port');
|
||||||
|
expect(envs[2].params[0].value).toBe('9090');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should create new environment with empty params from DEFAULT', () => {
|
||||||
|
const currentEnv = envs[0]; // DEFAULT
|
||||||
|
const newEnv = new Env(
|
||||||
|
Math.random() * 10000,
|
||||||
|
'newEnv',
|
||||||
|
[...currentEnv.params]
|
||||||
|
);
|
||||||
|
envs.push(newEnv);
|
||||||
|
|
||||||
|
expect(envs).toHaveLength(3);
|
||||||
|
expect(newEnv.params).toHaveLength(2);
|
||||||
|
expect(newEnv.params.map(p => p.name)).toContain('host');
|
||||||
|
expect(newEnv.params.map(p => p.name)).toContain('port');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('remove environment', () => {
|
||||||
|
it('should not allow removing DEFAULT environment', () => {
|
||||||
|
const defaultEnv = envs.find(e => e.name === 'DEFAULT');
|
||||||
|
expect(defaultEnv?.isDefault()).toBe(true);
|
||||||
|
|
||||||
|
// In the component, this is blocked by check: if (currEnv.isDefault())
|
||||||
|
// Simulating the protection
|
||||||
|
const canRemove = !defaultEnv?.isDefault();
|
||||||
|
expect(canRemove).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should remove non-DEFAULT environment', () => {
|
||||||
|
const envToRemove = envs[1]; // env1
|
||||||
|
const idx = envs.findIndex(x => x.id === envToRemove.id);
|
||||||
|
|
||||||
|
expect(idx).toBe(1);
|
||||||
|
expect(envs).toHaveLength(2);
|
||||||
|
|
||||||
|
// Simulate removal
|
||||||
|
envs.splice(idx, 1);
|
||||||
|
|
||||||
|
expect(envs).toHaveLength(1);
|
||||||
|
expect(envs.find(e => e.id === envToRemove.id)).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should select previous environment after removal', () => {
|
||||||
|
const idxToRemove = 1; // removing env1
|
||||||
|
envs.splice(idxToRemove, 1);
|
||||||
|
|
||||||
|
// After removal, should select max(0, idx-1) = max(0, 0) = 0
|
||||||
|
const newSelectedIdx = Math.max(0, idxToRemove - 1);
|
||||||
|
expect(newSelectedIdx).toBe(0);
|
||||||
|
expect(envs[newSelectedIdx].name).toBe('DEFAULT');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('environment selection', () => {
|
||||||
|
it('should find current env by ID from props', () => {
|
||||||
|
const selectedId = 1;
|
||||||
|
const currEnv = envs.find(e => e.id === selectedId) ?? envs[0];
|
||||||
|
|
||||||
|
expect(currEnv).toBeDefined();
|
||||||
|
expect(currEnv.id).toBe(1);
|
||||||
|
expect(currEnv.name).toBe('env1');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should fallback to first env if ID not found', () => {
|
||||||
|
const selectedId = 999; // non-existent
|
||||||
|
const currEnv = envs.find(e => e.id === selectedId) ?? envs[0];
|
||||||
|
|
||||||
|
expect(currEnv).toBeDefined();
|
||||||
|
expect(currEnv.id).toBe(0);
|
||||||
|
expect(currEnv.name).toBe('DEFAULT');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
4
test-results/.last-run.json
Normal file
4
test-results/.last-run.json
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
{
|
||||||
|
"status": "passed",
|
||||||
|
"failedTests": []
|
||||||
|
}
|
||||||
@@ -7,6 +7,7 @@ export default defineConfig({
|
|||||||
plugins: [react()],
|
plugins: [react()],
|
||||||
test: {
|
test: {
|
||||||
globals: true,
|
globals: true,
|
||||||
environment: "jsdom"
|
environment: "jsdom",
|
||||||
|
exclude: ['**/e2e/**', '**/node_modules/**']
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
Reference in New Issue
Block a user