@printmadehq/mockup-generator
v1.0.5
Published
Serverless-optimized TypeScript SDK for generating high-quality product mockups from PSD templates
Downloads
37
Maintainers
Readme
Mockup Generator SDK
A powerful, serverless-optimized TypeScript SDK for generating high-quality product mockups from PSD templates. Built on ag-psd and Photopea, designed for modern cloud environments.
🚀 Features
- 🌩️ Serverless Ready: Optimized for AWS Lambda, Vercel, Cloudflare Workers
- 🎨 Smart Object Replacement: Replace any smart object with images from URLs or Buffers
- 📸 Multi-format Export: Export to PNG, JPG, WebP via HeadlessPhotopea with parallel processing
- ☁️ Cloud Storage: Built-in R2/S3 integration for asset management
- 🔧 TypeScript: Full type safety and IntelliSense support
- 🎯 Simple API: Clean, developer-friendly interface
- ⚡ Performance: ~11s for 49MB PSD + 3 exports (53% faster with parallel exports)
- 🛡️ Error Handling: Comprehensive error types and retry mechanisms
📦 Installation
NPM (Recommended for production)
# Install from NPM registry
npm install @printmadehq/mockup-generator
# For TypeScript projects, types are included automaticallyDevelopment with Bun
# For development with Bun
bun add @printmadehq/mockup-generatorPrerequisites
This package requires Node.js 18+ and has native dependencies.
Important: You must install canvas separately:
# Install the package
npm install @printmadehq/mockup-generator
# Install canvas peer dependency
npm install canvasSystem Requirements for Canvas:
- macOS:
brew install pkg-config cairo pango libpng jpeg giflib librsvg pixman - Ubuntu/Debian:
sudo apt-get install build-essential libcairo2-dev libpango1.0-dev libjpeg-dev libgif-dev librsvg2-dev - CentOS/RHEL:
sudo yum install gcc-c++ cairo-devel pango-devel libjpeg-turbo-devel giflib-devel
Most cloud platforms (AWS Lambda, Vercel, etc.) handle canvas automatically.
🏃♂️ Quick Start
Basic Usage
import { MockupSDK } from '@printmadehq/mockup-generator';
// Create SDK instance with serverless optimizations
const sdk = new MockupSDK({
mode: 'serverless', // Automatic serverless optimizations
storage: {
endpoint: 'https://your-r2-endpoint.com',
accessKeyId: 'your-access-key',
secretAccessKey: 'your-secret-key',
bucket: 'your-bucket'
}
});
// Generate mockup
const result = await sdk.generate({
psd: 'https://your-bucket.com/templates/shirt.psd', // or Buffer
replacements: [
{
name: 'Design: front',
image: 'https://your-bucket.com/designs/logo.png', // or Buffer
fillMode: 'fit'
}
],
exports: [
{ format: 'png', quality: 90 },
{ format: 'jpg', quality: 85 }
]
});
console.log(`Generated PSD: ${result.psd.length} bytes`);
console.log(`Exports: ${result.exports.length} files`);
// Cleanup
await sdk.cleanup();Environment Variables
Set these environment variables for automatic configuration:
R2_ENDPOINT=https://your-account.r2.cloudflarestorage.com
R2_ACCESS_KEY_ID=your-access-key
R2_SECRET_ACCESS_KEY=your-secret-key
R2_BUCKET=your-bucket
R2_REGION=autoThen use the factory method:
import { MockupSDK } from '@printmadehq/mockup-generator';
// Auto mode detects environment and loads storage from env vars
const sdk = new MockupSDK({ mode: 'auto' });
// Or use convenience helper
import { createServerlessSDK } from 'mockup-generator-sdk';
const sdk2 = createServerlessSDK(); // Same as { mode: 'serverless' }⚡ Performance
Benchmark Results
The SDK leverages HeadlessPhotopea for blazing-fast parallel exports:
| Export Type | Original SDK | Optimized SDK | Improvement | |-------------|-------------|---------------|-------------| | Single Format | ~8s | ~8s | - | | 3 Formats | ~24s | ~11s | 53% faster | | 5 Formats | ~40s | ~15s | 63% faster |
Performance Breakdown (49MB PSD, 3 exports)
- PSD Generation: ~5s (ag-psd processing)
- Photopea Init: ~2s (one-time setup)
- Parallel Export: ~4s (PNG + JPG + WebP simultaneously)
- Total: ~11s
Key Optimizations
- Parallel Processing: All formats export simultaneously using Promise.all()
- Single Document: PSD loaded once, all exports from same document
- Direct API: HeadlessPhotopea provides direct Photopea API access
- Efficient Transfer: Optimized buffer handling without conversions
🏗️ API Reference
Operation Modes
The SDK uses operation modes for easy configuration:
// Serverless optimized (headless, fast timeout, minimal logging)
const sdk = new MockupSDK({ mode: 'serverless' });
// Development mode (visible browser, verbose logging, longer timeout)
const sdk = new MockupSDK({ mode: 'development' });
// Production mode (balanced settings for production servers)
const sdk = new MockupSDK({ mode: 'production' });
// Auto mode (detects environment, loads storage from env vars)
const sdk = new MockupSDK({ mode: 'auto' });
// Custom mode (override any preset settings)
const sdk = new MockupSDK({
mode: 'serverless',
timeout: 30000, // Override preset
verbose: true // Override preset
});Core Methods
generate(config)- Single mockup generation with config objectgenerateBatch(config)- Batch processing for multiple variationsupload(result, options)- Upload results to storage (separate from generation)analyze(psd)- Inspect PSD structure without generation
Configuration Types
interface MockupGenerationConfig {
psd: string | Buffer; // URL or Buffer
replacements: SmartObjectReplacement[];
exports?: ExportOptions[];
}
interface SmartObjectReplacement {
name: string; // Smart object name
image: string | Buffer; // Image URL or Buffer
fillMode?: 'fit' | 'fill' | 'stretch';
printArea?: { // Custom placement area
x: number; y: number;
width: number; height: number;
};
}🚀 Serverless Examples
AWS Lambda
import { MockupSDK } from '@printmadehq/mockup-generator';
export async function handler(event) {
// Mode automatically optimizes for serverless
const sdk = new MockupSDK({ mode: 'serverless' });
try {
const result = await sdk.generate({
psd: event.psdUrl,
replacements: event.replacements,
exports: event.exports
});
return {
statusCode: 200,
body: JSON.stringify({
success: true,
psdSize: result.psd.length,
exportsCount: result.exports.length
})
};
} finally {
await sdk.cleanup();
}
}Batch Processing
const batchResult = await sdk.generateBatch({
template: 'https://your-bucket.com/templates/shirt.psd',
variations: [
{
id: 'customer-1',
replacements: [
{ name: 'Design: front', image: 'https://example.com/logo1.png' }
],
exports: [{ format: 'png' }],
metadata: { customerId: 'cust_123' }
},
{
id: 'customer-2',
replacements: [
{ name: 'Design: front', image: 'https://example.com/logo2.png' }
],
exports: [{ format: 'png' }, { format: 'jpg' }]
}
]
});
console.log(`Processed ${batchResult.results.length} variations`);📚 Documentation
- Full SDK Documentation - Complete API reference and examples
- Examples - Working code examples for different scenarios
- Serverless Integration - AWS Lambda, Vercel, Cloudflare Workers
🛠️ Development
# Install dependencies
bun install
# Build SDK
bun run build
# Run examples
bun examples/new-api-demo.ts
# Legacy CLI (still available)
bun src/cli.ts --help📦 Publishing to NPM
This package is configured for public NPM publishing:
# Build the package
bun run build
# Login to NPM (one time setup)
npm login
# Publish as public scoped package
npm publish
# Note: Scoped packages default to private, but this package is configured for public accessPackage Structure
dist/index.js- Main entry point (Node.js compatible)dist/index.d.ts- TypeScript definitionssrc/sdk/index.ts- Development entry point- Uses ESM module system with Node.js 18+ compatibility
🔧 Troubleshooting
Canvas Installation Issues
Error: Library not loaded: libpixman-1.0.dylib
This error occurs when canvas native dependencies aren't properly installed.
Solution:
- Install system dependencies first (see Prerequisites section)
- Reinstall canvas:
npm uninstall canvas npm install canvas - For macOS with Homebrew issues:
# Ensure Homebrew packages are linked brew install pixman cairo pango brew link --force pixman
Error: canvas.node related errors
- Ensure canvas is installed in your project's node_modules (not bundled)
- The package now uses canvas as a peer dependency to avoid bundling issues
- Make sure you're running
npm install canvasin your consumer project
Serverless Deployment Issues:
- Most platforms provide canvas pre-compiled
- For custom environments, ensure build tools are available during deployment
- Consider using platform-specific canvas binaries
📄 License
MIT License - see LICENSE file for details.
