- Merge client and server dependencies into root package.json - Remove separate client/package.json and server/package.json - Update server/index.js to serve built client static files - Simplify Dockerfile to single build + production stage - Update dev scripts for unified development workflow - SPA routing serves index.html for non-API routes Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
271 lines
8.3 KiB
JavaScript
271 lines
8.3 KiB
JavaScript
import express from 'express';
|
|
import cors from 'cors';
|
|
import multer from 'multer';
|
|
import { v4 as uuidv4 } from 'uuid';
|
|
import sharp from 'sharp';
|
|
import { createCanvas, loadImage } from 'canvas';
|
|
import { fileURLToPath } from 'module';
|
|
import { dirname, join } from 'path';
|
|
import { mkdirSync, existsSync, writeFileSync } from 'fs';
|
|
|
|
const __filename = fileURLToPath(import.meta.url);
|
|
const __dirname = dirname(__filename);
|
|
|
|
const app = express();
|
|
const PORT = process.env.PORT || 3001;
|
|
|
|
// Ensure upload and export directories exist
|
|
const uploadsDir = join(__dirname, 'uploads');
|
|
const exportsDir = join(__dirname, 'exports');
|
|
[uploadsDir, exportsDir].forEach((dir) => {
|
|
if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
|
|
});
|
|
|
|
// Middleware
|
|
app.use(cors());
|
|
app.use(express.json({ limit: '50mb' }));
|
|
app.use(express.urlencoded({ extended: true, limit: '50mb' }));
|
|
|
|
// Serve static files for uploads and exports
|
|
app.use('/uploads', express.static(uploadsDir));
|
|
app.use('/exports', express.static(exportsDir));
|
|
|
|
// Serve built client static files
|
|
const clientDistDir = join(__dirname, 'dist');
|
|
if (existsSync(clientDistDir)) {
|
|
app.use(express.static(clientDistDir));
|
|
|
|
// Serve index.html for all non-API routes (SPA routing)
|
|
app.get('*', (req, res, next) => {
|
|
if (!req.path.startsWith('/api') && !req.path.startsWith('/uploads') && !req.path.startsWith('/exports')) {
|
|
res.sendFile(join(clientDistDir, 'index.html'));
|
|
} else {
|
|
next();
|
|
}
|
|
});
|
|
}
|
|
|
|
// Configure multer for image uploads
|
|
const storage = multer.diskStorage({
|
|
destination: (req, file, cb) => {
|
|
cb(null, uploadsDir);
|
|
},
|
|
filename: (req, file, cb) => {
|
|
const ext = file.originalname.split('.').pop();
|
|
const filename = `${uuidv4()}.${ext}`;
|
|
cb(null, filename);
|
|
},
|
|
});
|
|
|
|
const fileFilter = (req, file, cb) => {
|
|
const allowedTypes = ['image/jpeg', 'image/png', 'image/webp'];
|
|
if (allowedTypes.includes(file.mimetype)) {
|
|
cb(null, true);
|
|
} else {
|
|
cb(new Error('Invalid file type. Only JPEG, PNG, and WebP are allowed.'), false);
|
|
}
|
|
};
|
|
|
|
const upload = multer({
|
|
storage,
|
|
fileFilter,
|
|
limits: {
|
|
fileSize: 20 * 1024 * 1024, // 20MB
|
|
},
|
|
});
|
|
|
|
// Health check endpoint
|
|
app.get('/api/health', (req, res) => {
|
|
res.json({ status: 'ok', timestamp: new Date().toISOString() });
|
|
});
|
|
|
|
// Upload endpoint
|
|
app.post('/api/upload', upload.single('image'), async (req, res) => {
|
|
try {
|
|
if (!req.file) {
|
|
return res.status(400).json({ error: 'No file uploaded' });
|
|
}
|
|
|
|
const originalPath = req.file.path;
|
|
const originalUrl = `/uploads/${req.file.filename}`;
|
|
|
|
// Create preview by resizing to max 1000px
|
|
const previewFilename = req.file.filename.replace(/\.[^.]+$/, '.png');
|
|
const previewPath = join(uploadsDir, 'preview', previewFilename);
|
|
|
|
// Ensure preview directory exists
|
|
const previewDir = join(uploadsDir, 'preview');
|
|
if (!existsSync(previewDir)) mkdirSync(previewDir, { recursive: true });
|
|
|
|
await sharp(originalPath)
|
|
.resize({ width: 1000, height: 1000, fit: 'inside' })
|
|
.png()
|
|
.toFile(previewPath);
|
|
|
|
const previewUrl = `/uploads/preview/${previewFilename}`;
|
|
|
|
res.json({
|
|
success: true,
|
|
original: {
|
|
path: originalPath,
|
|
url: originalUrl,
|
|
filename: req.file.filename,
|
|
size: req.file.size,
|
|
mimetype: req.file.mimetype,
|
|
},
|
|
preview: {
|
|
path: previewPath,
|
|
url: previewUrl,
|
|
filename: previewFilename,
|
|
},
|
|
});
|
|
} catch (error) {
|
|
console.error('Upload error:', error);
|
|
res.status(500).json({ error: 'Failed to process upload', details: error.message });
|
|
}
|
|
});
|
|
|
|
// Error handling for multer
|
|
app.use((err, req, res, next) => {
|
|
if (err instanceof multer.MulterError) {
|
|
if (err.code === 'LIMIT_FILE_SIZE') {
|
|
return res.status(400).json({ error: 'File too large. Maximum size is 20MB.' });
|
|
}
|
|
return res.status(400).json({ error: err.message });
|
|
}
|
|
next(err);
|
|
});
|
|
|
|
// High-resolution export endpoint (300x300px -> 4500x4500px @ 300 DPI)
|
|
const EXPORT_SCALE = 15;
|
|
const EXPORT_SIZE = 4500;
|
|
|
|
app.post('/api/export', async (req, res) => {
|
|
try {
|
|
const { elements, designName = 'design', template } = req.body;
|
|
|
|
if (!elements || !Array.isArray(elements)) {
|
|
return res.status(400).json({ error: 'Elements array is required' });
|
|
}
|
|
|
|
const canvas = createCanvas(EXPORT_SIZE, EXPORT_SIZE);
|
|
const ctx = canvas.getContext('2d');
|
|
|
|
// Render template background layer first (if template active)
|
|
if (template && template.background) {
|
|
const bg = template.background;
|
|
if (bg.type === 'color') {
|
|
ctx.fillStyle = bg.color;
|
|
ctx.fillRect(0, 0, EXPORT_SIZE, EXPORT_SIZE);
|
|
} else if (bg.type === 'image' && bg.src) {
|
|
try {
|
|
const imgUrl = bg.src.startsWith('/')
|
|
? join(__dirname, bg.src.replace('/uploads', 'uploads'))
|
|
: bg.src;
|
|
const img = await loadImage(imgUrl);
|
|
ctx.drawImage(img, 0, 0, EXPORT_SIZE, EXPORT_SIZE);
|
|
} catch (imgError) {
|
|
console.error('Failed to load template background:', imgError);
|
|
ctx.fillStyle = '#ffffff';
|
|
ctx.fillRect(0, 0, EXPORT_SIZE, EXPORT_SIZE);
|
|
}
|
|
}
|
|
} else {
|
|
// Default white background
|
|
ctx.fillStyle = '#ffffff';
|
|
ctx.fillRect(0, 0, EXPORT_SIZE, EXPORT_SIZE);
|
|
}
|
|
|
|
// Helper function to render a single element
|
|
const renderElement = async (el) => {
|
|
ctx.save();
|
|
|
|
const x = (el.x || 0) * EXPORT_SCALE;
|
|
const y = (el.y || 0) * EXPORT_SCALE;
|
|
const centerX = x + ((el.width || el.fontSize || 100) * EXPORT_SCALE) / 2;
|
|
const centerY = y + ((el.height || el.fontSize || 100) * EXPORT_SCALE) / 2;
|
|
|
|
ctx.translate(centerX, centerY);
|
|
ctx.rotate((el.rotation || 0) * Math.PI / 180);
|
|
ctx.translate(-centerX, -centerY);
|
|
|
|
if (el.type === 'image' && el.src) {
|
|
try {
|
|
const imgUrl = el.src.startsWith('/')
|
|
? join(__dirname, el.src.replace('/uploads', 'uploads'))
|
|
: el.src;
|
|
const img = await loadImage(imgUrl);
|
|
const width = (el.width || 100) * EXPORT_SCALE;
|
|
const height = (el.height || 100) * EXPORT_SCALE;
|
|
|
|
// Apply crop if slot crop region specified
|
|
if (el.crop) {
|
|
const { sx, sy, sWidth, sHeight } = el.crop;
|
|
ctx.drawImage(
|
|
img,
|
|
sx, sy, sWidth, sHeight, // source crop
|
|
x, y, width, height // destination
|
|
);
|
|
} else {
|
|
ctx.drawImage(img, x, y, width, height);
|
|
}
|
|
} catch (imgError) {
|
|
console.error('Failed to load image for export:', imgError);
|
|
}
|
|
} else if (el.type === 'text') {
|
|
const fontSize = (el.fontSize || 32) * EXPORT_SCALE / 32;
|
|
ctx.font = `${fontSize}px "${el.fontFamily || 'Arial'}"`;
|
|
ctx.fillStyle = el.fill || '#000000';
|
|
ctx.textAlign = 'center';
|
|
ctx.textBaseline = 'middle';
|
|
ctx.fillText(el.text || '', centerX, centerY);
|
|
}
|
|
|
|
ctx.restore();
|
|
};
|
|
|
|
// Render user elements
|
|
for (const el of elements) {
|
|
// Skip non-printable elements (guides, watermarks, template-only layers)
|
|
if (el.nonPrintable) continue;
|
|
await renderElement(el);
|
|
}
|
|
|
|
// Render template overlay layer last (if template active)
|
|
if (template && template.overlay) {
|
|
for (const overlayEl of template.overlay) {
|
|
if (overlayEl.nonPrintable) continue;
|
|
await renderElement(overlayEl);
|
|
}
|
|
}
|
|
|
|
// Save to file
|
|
const exportFilename = `${designName.replace(/[^a-z0-9]/gi, '_')}_${uuidv4()}.png`;
|
|
const exportPath = join(exportsDir, exportFilename);
|
|
const buffer = canvas.toBuffer('image/png');
|
|
writeFileSync(exportPath, buffer);
|
|
|
|
res.json({
|
|
success: true,
|
|
export: {
|
|
url: `/exports/${exportFilename}`,
|
|
path: exportPath,
|
|
filename: exportFilename,
|
|
width: EXPORT_SIZE,
|
|
height: EXPORT_SIZE,
|
|
dpi: 300,
|
|
sizeInches: '15x15',
|
|
},
|
|
});
|
|
} catch (error) {
|
|
console.error('Export error:', error);
|
|
res.status(500).json({ error: 'Failed to export design', details: error.message });
|
|
}
|
|
});
|
|
|
|
app.listen(PORT, () => {
|
|
console.log(`Server running on http://localhost:${PORT}`);
|
|
console.log(`Health check: http://localhost:${PORT}/api/health`);
|
|
console.log(`Upload endpoint: POST http://localhost:${PORT}/api/upload`);
|
|
});
|