@twick/render-server 0.15.21 โ†’ 0.15.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@twick/render-server",
3
- "version": "0.15.21",
3
+ "version": "0.15.22",
4
4
  "license": "https://github.com/ncounterspecialist/twick/blob/main/LICENSE.md",
5
5
  "main": "./dist/index.cjs",
6
6
  "module": "./dist/index.js",
@@ -26,12 +26,12 @@
26
26
  "access": "public"
27
27
  },
28
28
  "dependencies": {
29
- "@twick/2d": "^0.15.21",
30
- "@twick/core": "^0.15.21",
31
- "@twick/ffmpeg": "^0.15.21",
32
- "@twick/renderer": "^0.15.21",
33
- "@twick/ui": "^0.15.21",
34
- "@twick/visualizer": "0.15.21",
29
+ "@twick/2d": "^0.15.22",
30
+ "@twick/core": "^0.15.22",
31
+ "@twick/ffmpeg": "^0.15.22",
32
+ "@twick/renderer": "^0.15.22",
33
+ "@twick/ui": "^0.15.22",
34
+ "@twick/visualizer": "0.15.22",
35
35
  "cors": "^2.8.5",
36
36
  "express": "^4.18.2",
37
37
  "express-rate-limit": "^8.0.1",
@@ -49,5 +49,8 @@
49
49
  },
50
50
  "engines": {
51
51
  "node": ">=20.0.0"
52
- }
52
+ },
53
+ "files": [
54
+ "dist"
55
+ ]
53
56
  }
package/.dockerignore DELETED
@@ -1,13 +0,0 @@
1
- node_modules
2
- npm-debug.log
3
- Dockerfile
4
- .dockerignore
5
- *.md
6
- dist
7
- .git
8
- .gitignore
9
- .env*
10
- *.log
11
- coverage
12
- .nyc_output
13
- test.js
package/Dockerfile DELETED
@@ -1,39 +0,0 @@
1
- FROM ghcr.io/puppeteer/puppeteer:latest AS builder
2
- WORKDIR /app
3
-
4
- COPY package*.json ./
5
- RUN npm install
6
-
7
- # Copy only source and config (avoid overwriting node_modules from context)
8
- COPY src ./src
9
- COPY tsup.config.ts tsconfig.json ./
10
- RUN npm run build
11
- # Ensure server entry point exists (tsup outputs ESM as .mjs)
12
- RUN test -f /app/dist/server.mjs || test -f /app/dist/server.js || (echo "Missing dist/server.mjs or server.js. Contents of /app/dist:" && ls -la /app/dist 2>/dev/null || true && exit 1)
13
-
14
- FROM ghcr.io/puppeteer/puppeteer:latest
15
-
16
- WORKDIR /app
17
-
18
- # Switch to root to install system packages (needed for ffmpeg)
19
- USER root
20
-
21
- RUN apt-get update && apt-get install -y ffmpeg && rm -rf /var/lib/apt/lists/*
22
-
23
- # Drop back to the non-root Puppeteer user for runtime
24
- USER pptruser
25
-
26
- # Tell @twick/ffmpeg to use the system binaries
27
- ENV FFMPEG_PATH=/usr/bin/ffmpeg
28
- ENV FFPROBE_PATH=/usr/bin/ffprobe
29
-
30
- COPY package*.json ./
31
- RUN npm install --only=production
32
-
33
- COPY --from=builder /app/dist ./dist
34
-
35
- EXPOSE 5000
36
-
37
- # Start the built-in render server on port 5000
38
- CMD ["node", "dist/server.mjs"]
39
-
@@ -1,22 +0,0 @@
1
- # @twick/render-server โ€” configurable via .env
2
- # Copy .env.example to .env and adjust values.
3
-
4
- services:
5
- render-server:
6
- build:
7
- context: .
8
- dockerfile: Dockerfile
9
- image: twick-render-server:latest
10
- container_name: twick-render-server
11
- restart: unless-stopped
12
-
13
- environment:
14
- PORT: "${PORT:-5000}"
15
- NODE_ENV: "${NODE_ENV:-production}"
16
- # Rate limiting: window in ms, max requests per window, cleanup interval in ms
17
- RATE_LIMIT_WINDOW_MS: "${RATE_LIMIT_WINDOW_MS:-900000}"
18
- RATE_LIMIT_MAX_REQUESTS: "${RATE_LIMIT_MAX_REQUESTS:-100}"
19
- RATE_LIMIT_CLEANUP_INTERVAL_MS: "${RATE_LIMIT_CLEANUP_INTERVAL_MS:-60000}"
20
-
21
- ports:
22
- - "${PORT:-5000}:${PORT:-5000}"
package/package.json.bak DELETED
@@ -1,53 +0,0 @@
1
- {
2
- "name": "@twick/render-server",
3
- "version": "0.15.21",
4
- "license": "https://github.com/ncounterspecialist/twick/blob/main/LICENSE.md",
5
- "main": "./dist/index.cjs",
6
- "module": "./dist/index.js",
7
- "types": "./dist/index.d.ts",
8
- "exports": {
9
- ".": {
10
- "types": "./dist/index.d.ts",
11
- "import": "./dist/index.js",
12
- "require": "./dist/index.cjs"
13
- }
14
- },
15
- "bin": {
16
- "twick-render-server": "./dist/cli.js"
17
- },
18
- "scripts": {
19
- "build": "tsup",
20
- "dev": "tsx watch src/server.ts",
21
- "start": "node dist/server.js",
22
- "test:render": "tsx src/test-render.ts",
23
- "clean": "rimraf dist"
24
- },
25
- "publishConfig": {
26
- "access": "public"
27
- },
28
- "dependencies": {
29
- "@twick/2d": "^0.15.21",
30
- "@twick/core": "^0.15.21",
31
- "@twick/ffmpeg": "^0.15.21",
32
- "@twick/renderer": "^0.15.21",
33
- "@twick/ui": "^0.15.21",
34
- "@twick/visualizer": "0.15.21",
35
- "cors": "^2.8.5",
36
- "express": "^4.18.2",
37
- "express-rate-limit": "^8.0.1",
38
- "node-fetch": "^3.3.2",
39
- "path": "^0.12.7"
40
- },
41
- "devDependencies": {
42
- "@types/cors": "^2.8.17",
43
- "@types/express": "^4.17.21",
44
- "@types/node": "^20.10.0",
45
- "rimraf": "^5.0.5",
46
- "tsup": "^8.0.0",
47
- "tsx": "^4.7.0",
48
- "typescript": "5.4.2"
49
- },
50
- "engines": {
51
- "node": ">=20.0.0"
52
- }
53
- }
package/src/cli.ts DELETED
@@ -1,326 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- import fs from "fs";
4
- import path from "path";
5
- import { fileURLToPath } from "url";
6
-
7
- const __filename = fileURLToPath(import.meta.url);
8
- const __dirname = path.dirname(__filename);
9
-
10
- const SERVER_TEMPLATE = `import express from "express";
11
- import cors from "cors";
12
- import path from "path";
13
- import { fileURLToPath } from "url";
14
- import { renderTwickVideo } from "@twick/render-server";
15
-
16
- const PORT = process.env.PORT || 3001;
17
- const BASE_PATH = \`http://localhost:\${PORT}\`;
18
-
19
- const __filename = fileURLToPath(import.meta.url);
20
- const __dirname = path.dirname(__filename);
21
-
22
- // Rate limiting configuration
23
- const RATE_LIMIT_WINDOW_MS = 15 * 60 * 1000; // 15 minutes
24
- const RATE_LIMIT_MAX_REQUESTS = 100; // Maximum requests per window
25
- const RATE_LIMIT_CLEANUP_INTERVAL_MS = 60 * 1000; // Cleanup every minute
26
-
27
- // In-memory store for rate limiting
28
- interface RateLimitEntry {
29
- count: number;
30
- resetTime: number;
31
- }
32
-
33
- const rateLimitStore = new Map<string, RateLimitEntry>();
34
-
35
- // Cleanup expired entries periodically
36
- setInterval(() => {
37
- const now = Date.now();
38
- for (const [key, entry] of rateLimitStore.entries()) {
39
- if (now > entry.resetTime) {
40
- rateLimitStore.delete(key);
41
- }
42
- }
43
- }, RATE_LIMIT_CLEANUP_INTERVAL_MS);
44
-
45
- /**
46
- * Rate limiting middleware for API endpoints.
47
- * Tracks request counts per IP address and enforces rate limits
48
- * to prevent abuse of the render server.
49
- *
50
- * @param req - Express request object
51
- * @param res - Express response object
52
- * @param next - Express next function
53
- *
54
- * @example
55
- * \`\`\`js
56
- * app.use('/api', rateLimitMiddleware);
57
- * // Applies rate limiting to all /api routes
58
- * \`\`\`
59
- */
60
- const rateLimitMiddleware = (req: express.Request, res: express.Response, next: express.NextFunction) => {
61
- const clientIP = req.ip || req.connection.remoteAddress || 'unknown';
62
- const now = Date.now();
63
-
64
- // Get or create rate limit entry for this IP
65
- let entry = rateLimitStore.get(clientIP);
66
-
67
- if (!entry || now > entry.resetTime) {
68
- // New window or expired entry
69
- entry = {
70
- count: 1,
71
- resetTime: now + RATE_LIMIT_WINDOW_MS
72
- };
73
- rateLimitStore.set(clientIP, entry);
74
- } else {
75
- // Increment count in current window
76
- entry.count++;
77
-
78
- if (entry.count > RATE_LIMIT_MAX_REQUESTS) {
79
- // Rate limit exceeded
80
- const retryAfter = Math.ceil((entry.resetTime - now) / 1000);
81
- res.set('Retry-After', retryAfter.toString());
82
- res.set('X-RateLimit-Limit', RATE_LIMIT_MAX_REQUESTS.toString());
83
- res.set('X-RateLimit-Remaining', '0');
84
- res.set('X-RateLimit-Reset', new Date(entry.resetTime).toISOString());
85
-
86
- return res.status(429).json({
87
- success: false,
88
- error: 'Too many requests',
89
- message: \`Rate limit exceeded. Try again in \${retryAfter} seconds.\`,
90
- retryAfter
91
- });
92
- }
93
- }
94
-
95
- // Add rate limit headers
96
- res.set('X-RateLimit-Limit', RATE_LIMIT_MAX_REQUESTS.toString());
97
- res.set('X-RateLimit-Remaining', (RATE_LIMIT_MAX_REQUESTS - entry.count).toString());
98
- res.set('X-RateLimit-Reset', new Date(entry.resetTime).toISOString());
99
-
100
- next();
101
- };
102
-
103
- const app = express();
104
-
105
- app.use(cors());
106
- app.use(express.json());
107
-
108
- // Serve static files from output directory
109
- app.use("/output", express.static(path.join(__dirname, "output")));
110
-
111
- /**
112
- * POST endpoint for video rendering requests.
113
- * Accepts project variables and settings, renders the video,
114
- * and returns a download URL for the completed video.
115
- *
116
- * @param req - Express request object containing variables and settings
117
- * @param res - Express response object
118
- *
119
- * @example
120
- * \`\`\`js
121
- * POST /api/render-video
122
- * Body: { variables: {...}, settings: {...} }
123
- * Response: { success: true, downloadUrl: "..." }
124
- * \`\`\`
125
- */
126
- app.post("/api/render-video", async (req, res) => {
127
- const { variables, settings } = req.body;
128
-
129
- try {
130
- const outputPath = await renderTwickVideo(variables, settings);
131
- res.json({
132
- success: true,
133
- downloadUrl: \`\${BASE_PATH}/download/\${path.basename(outputPath)}\`,
134
- });
135
- } catch (error) {
136
- console.error("Render error:", error);
137
- res.status(500).json({
138
- success: false,
139
- error: error instanceof Error ? error.message : "Unknown error",
140
- });
141
- }
142
- });
143
-
144
- /**
145
- * GET endpoint for downloading rendered videos.
146
- * Serves video files with rate limiting and security checks
147
- * to prevent path traversal attacks.
148
- *
149
- * @param req - Express request object with filename parameter
150
- * @param res - Express response object
151
- *
152
- * @example
153
- * \`\`\`js
154
- * GET /download/video-123.mp4
155
- * // Downloads the specified video file
156
- * \`\`\`
157
- */
158
- app.get("/download/:filename", rateLimitMiddleware, (req, res) => {
159
- const outputDir = path.resolve(__dirname, "output");
160
- const requestedPath = path.resolve(outputDir, req.params.filename);
161
- if (!requestedPath.startsWith(outputDir + path.sep)) {
162
- // Attempted path traversal or access outside output directory
163
- res.status(403).json({
164
- success: false,
165
- error: "Forbidden",
166
- });
167
- return;
168
- }
169
- res.download(requestedPath, (err) => {
170
- if (err) {
171
- res.status(404).json({
172
- success: false,
173
- error: "File not found",
174
- });
175
- }
176
- });
177
- });
178
-
179
- /**
180
- * Health check endpoint for monitoring server status.
181
- * Returns server status and current timestamp for health monitoring.
182
- *
183
- * @param req - Express request object
184
- * @param res - Express response object
185
- *
186
- * @example
187
- * \`\`\`js
188
- * GET /health
189
- * Response: { status: "ok", timestamp: "2024-01-01T00:00:00.000Z" }
190
- * \`\`\`
191
- */
192
- app.get("/health", (req, res) => {
193
- res.json({
194
- status: "ok",
195
- timestamp: new Date().toISOString(),
196
- });
197
- });
198
-
199
- // Start the server
200
- app.listen(PORT, () => {
201
- console.log(\`Render server running on port \${PORT}\`);
202
- console.log(\`Health check: \${BASE_PATH}/health\`);
203
- console.log(\`API endpoint: \${BASE_PATH}/api/render-video\`);
204
- console.log(\`Download endpoint rate limited: \${RATE_LIMIT_MAX_REQUESTS} requests per \${RATE_LIMIT_WINDOW_MS / 60000} minutes\`);
205
- });
206
- `;
207
-
208
- const PACKAGE_JSON_TEMPLATE = `{
209
- "name": "twick-render-server",
210
- "version": "1.0.0",
211
- "type": "module",
212
- "scripts": {
213
- "dev": "tsx watch server.ts",
214
- "build": "tsc",
215
- "start": "node dist/server.js"
216
- },
217
- "dependencies": {
218
- "@twick/render-server": "^0.14.11",
219
- "cors": "^2.8.5",
220
- "express": "^4.18.2"
221
- },
222
- "devDependencies": {
223
- "@types/cors": "^2.8.17",
224
- "@types/express": "^4.17.21",
225
- "@types/node": "^20.10.0",
226
- "tsx": "^4.7.0",
227
- "typescript": "5.4.2"
228
- }
229
- }
230
- `;
231
-
232
- const TSCONFIG_TEMPLATE = `{
233
- "compilerOptions": {
234
- "target": "ES2022",
235
- "module": "ESNext",
236
- "moduleResolution": "bundler",
237
- "allowSyntheticDefaultImports": true,
238
- "esModuleInterop": true,
239
- "allowJs": true,
240
- "strict": true,
241
- "skipLibCheck": true,
242
- "forceConsistentCasingInFileNames": true,
243
- "outDir": "./dist",
244
- "rootDir": ".",
245
- "declaration": true,
246
- "declarationMap": true,
247
- "sourceMap": true,
248
- "resolveJsonModule": true,
249
- "noEmit": false
250
- },
251
- "include": ["server.ts"],
252
- "exclude": ["node_modules", "dist"]
253
- }
254
- `;
255
-
256
- const GITIGNORE_TEMPLATE = `node_modules/
257
- dist/
258
- output/
259
- .env
260
- *.log
261
- `;
262
-
263
- function scaffoldServer() {
264
- const currentDir = process.cwd();
265
- const serverDir = path.join(currentDir, "twick-render-server");
266
-
267
- // Check if directory already exists
268
- if (fs.existsSync(serverDir)) {
269
- console.error(`Error: Directory "${serverDir}" already exists.`);
270
- console.error("Please remove it or choose a different location.");
271
- process.exit(1);
272
- }
273
-
274
- // Create server directory
275
- fs.mkdirSync(serverDir, { recursive: true });
276
- fs.mkdirSync(path.join(serverDir, "output"), { recursive: true });
277
-
278
- // Write server.ts
279
- fs.writeFileSync(
280
- path.join(serverDir, "server.ts"),
281
- SERVER_TEMPLATE,
282
- "utf-8"
283
- );
284
-
285
- // Write package.json
286
- fs.writeFileSync(
287
- path.join(serverDir, "package.json"),
288
- PACKAGE_JSON_TEMPLATE,
289
- "utf-8"
290
- );
291
-
292
- // Write tsconfig.json
293
- fs.writeFileSync(
294
- path.join(serverDir, "tsconfig.json"),
295
- TSCONFIG_TEMPLATE,
296
- "utf-8"
297
- );
298
-
299
- // Write .gitignore
300
- fs.writeFileSync(
301
- path.join(serverDir, ".gitignore"),
302
- GITIGNORE_TEMPLATE,
303
- "utf-8"
304
- );
305
-
306
- console.log(`โœ… Successfully scaffolded Twick render server!`);
307
- console.log(`\n๐Ÿ“ Server created at: ${serverDir}`);
308
- console.log(`\n๐Ÿ“ Next steps:`);
309
- console.log(` 1. cd ${path.basename(serverDir)}`);
310
- console.log(` 2. npm install`);
311
- console.log(` 3. npm run dev (for development)`);
312
- console.log(` 4. npm run build && npm start (for production)`);
313
- }
314
-
315
- // Parse command line arguments
316
- const args = process.argv.slice(2);
317
- const command = args[0];
318
-
319
- if (command === "init") {
320
- scaffoldServer();
321
- } else {
322
- console.log("Usage: npx twick-render-server init");
323
- console.log("\nThis command scaffolds a new Twick render server in the current directory.");
324
- process.exit(1);
325
- }
326
-
package/src/index.ts DELETED
@@ -1,3 +0,0 @@
1
- // Export the renderer function
2
- export { default as renderTwickVideo } from "./renderer";
3
-
package/src/renderer.ts DELETED
@@ -1,115 +0,0 @@
1
- import { renderVideo } from "@twick/renderer";
2
-
3
- // Simple in-process concurrency control for render jobs.
4
- // This helps avoid overloading a single server instance.
5
- let activeRenders = 0;
6
- const renderQueue: Array<() => void> = [];
7
-
8
- const getMaxConcurrentRenders = () => {
9
- const fromEnv = process.env.TWICK_MAX_CONCURRENT_RENDERS;
10
- const parsed = fromEnv ? parseInt(fromEnv, 10) : NaN;
11
- return Number.isFinite(parsed) && parsed > 0 ? parsed : 2;
12
- };
13
-
14
- async function withRenderSlot<T>(fn: () => Promise<T>): Promise<T> {
15
- const maxConcurrent = getMaxConcurrentRenders();
16
-
17
- if (activeRenders >= maxConcurrent) {
18
- await new Promise<void>((resolve) => {
19
- renderQueue.push(resolve);
20
- });
21
- }
22
-
23
- activeRenders++;
24
- try {
25
- return await fn();
26
- } finally {
27
- activeRenders--;
28
- const next = renderQueue.shift();
29
- if (next) {
30
- next();
31
- }
32
- }
33
- }
34
-
35
- /**
36
- * Renders a Twick video with the provided variables and settings.
37
- * Processes project variables, merges settings with defaults, and
38
- * generates a video file using the Twick renderer.
39
- *
40
- * @param variables - Project variables containing input configuration
41
- * @param settings - Optional render settings to override defaults
42
- * @returns Promise resolving to the path of the rendered video file
43
- *
44
- * @example
45
- * ```js
46
- * const videoPath = await renderTwickVideo(
47
- * { input: { properties: { width: 1920, height: 1080 } } },
48
- * { quality: "high", outFile: "my-video.mp4" }
49
- * );
50
- * // videoPath = "./output/my-video.mp4"
51
- * ```
52
- */
53
- const renderTwickVideo = async (variables: any, settings: any) => {
54
- const start = Date.now();
55
- try {
56
- const { input } = variables;
57
- const { properties } = input;
58
-
59
- // Basic safety limits (can be overridden via env)
60
- const maxWidth =
61
- parseInt(process.env.TWICK_MAX_RENDER_WIDTH ?? "3840", 10) || 3840;
62
- const maxHeight =
63
- parseInt(process.env.TWICK_MAX_RENDER_HEIGHT ?? "2160", 10) || 2160;
64
- const maxFps =
65
- parseInt(process.env.TWICK_MAX_RENDER_FPS ?? "60", 10) || 60;
66
-
67
- const width = Math.min(properties.width, maxWidth);
68
- const height = Math.min(properties.height, maxHeight);
69
- const fps = Math.min(properties.fps ?? 30, maxFps);
70
-
71
- // Merge user settings with defaults
72
- const mergedSettings = {
73
- logProgress: true,
74
- outDir: "./output",
75
- outFile: properties.reqesutId ?? `video-${Date.now()}` + ".mp4",
76
- quality: "medium",
77
- projectSettings: {
78
- exporter: {
79
- name: "@twick/core/wasm-effects",
80
- },
81
- size: {
82
- x: width,
83
- y: height,
84
- },
85
- fps,
86
- },
87
- ...settings, // Allow user settings to override defaults
88
- };
89
-
90
- const result = await withRenderSlot(async () => {
91
- const file = await renderVideo({
92
- projectFile: "@twick/visualizer/dist/project.js",
93
- variables,
94
- settings: mergedSettings,
95
- });
96
- return file;
97
- });
98
-
99
- const elapsedMs = Date.now() - start;
100
- console.log(
101
- `[RenderServer] Render completed in ${elapsedMs}ms (active=${activeRenders}) ->`,
102
- result,
103
- );
104
- return result;
105
- } catch (error) {
106
- const elapsedMs = Date.now() - start;
107
- console.error(
108
- `[RenderServer] Render error after ${elapsedMs}ms (active=${activeRenders}):`,
109
- error,
110
- );
111
- throw error;
112
- }
113
- };
114
-
115
- export default renderTwickVideo;
package/src/server.ts DELETED
@@ -1,202 +0,0 @@
1
- import express from "express";
2
- import cors from "cors";
3
- import path from "path";
4
- import { fileURLToPath } from "url";
5
- import renderTwickVideo from "./renderer";
6
-
7
- const PORT = process.env.PORT || 5000;
8
- const BASE_PATH = `http://localhost:${PORT}`;
9
-
10
- const __filename = fileURLToPath(import.meta.url);
11
- const __dirname = path.dirname(__filename);
12
-
13
- // Rate limiting configuration (all configurable via env)
14
- const RATE_LIMIT_WINDOW_MS =
15
- parseInt(process.env.RATE_LIMIT_WINDOW_MS ?? "900000", 10) || 15 * 60 * 1000; // default 15 min (ms)
16
- const RATE_LIMIT_MAX_REQUESTS =
17
- parseInt(process.env.RATE_LIMIT_MAX_REQUESTS ?? "100", 10) || 100; // max requests per window
18
- const RATE_LIMIT_CLEANUP_INTERVAL_MS =
19
- parseInt(process.env.RATE_LIMIT_CLEANUP_INTERVAL_MS ?? "60000", 10) || 60 * 1000; // default 1 min (ms)
20
-
21
- // In-memory store for rate limiting
22
- interface RateLimitEntry {
23
- count: number;
24
- resetTime: number;
25
- }
26
-
27
- const rateLimitStore = new Map<string, RateLimitEntry>();
28
-
29
- // Cleanup expired entries periodically
30
- setInterval(() => {
31
- const now = Date.now();
32
- for (const [key, entry] of rateLimitStore.entries()) {
33
- if (now > entry.resetTime) {
34
- rateLimitStore.delete(key);
35
- }
36
- }
37
- }, RATE_LIMIT_CLEANUP_INTERVAL_MS);
38
-
39
- /**
40
- * Rate limiting middleware for API endpoints.
41
- * Tracks request counts per IP address and enforces rate limits
42
- * to prevent abuse of the render server.
43
- *
44
- * @param req - Express request object
45
- * @param res - Express response object
46
- * @param next - Express next function
47
- *
48
- * @example
49
- * ```js
50
- * app.use('/api', rateLimitMiddleware);
51
- * // Applies rate limiting to all /api routes
52
- * ```
53
- */
54
- const rateLimitMiddleware = (req: express.Request, res: express.Response, next: express.NextFunction) => {
55
- const clientIP = req.ip || req.connection.remoteAddress || 'unknown';
56
- const now = Date.now();
57
-
58
- // Get or create rate limit entry for this IP
59
- let entry = rateLimitStore.get(clientIP);
60
-
61
- if (!entry || now > entry.resetTime) {
62
- // New window or expired entry
63
- entry = {
64
- count: 1,
65
- resetTime: now + RATE_LIMIT_WINDOW_MS
66
- };
67
- rateLimitStore.set(clientIP, entry);
68
- } else {
69
- // Increment count in current window
70
- entry.count++;
71
-
72
- if (entry.count > RATE_LIMIT_MAX_REQUESTS) {
73
- // Rate limit exceeded
74
- const retryAfter = Math.ceil((entry.resetTime - now) / 1000);
75
- res.set('Retry-After', retryAfter.toString());
76
- res.set('X-RateLimit-Limit', RATE_LIMIT_MAX_REQUESTS.toString());
77
- res.set('X-RateLimit-Remaining', '0');
78
- res.set('X-RateLimit-Reset', new Date(entry.resetTime).toISOString());
79
-
80
- return res.status(429).json({
81
- success: false,
82
- error: 'Too many requests',
83
- message: `Rate limit exceeded. Try again in ${retryAfter} seconds.`,
84
- retryAfter
85
- });
86
- }
87
- }
88
-
89
- // Add rate limit headers
90
- res.set('X-RateLimit-Limit', RATE_LIMIT_MAX_REQUESTS.toString());
91
- res.set('X-RateLimit-Remaining', (RATE_LIMIT_MAX_REQUESTS - entry.count).toString());
92
- res.set('X-RateLimit-Reset', new Date(entry.resetTime).toISOString());
93
-
94
- next();
95
- };
96
-
97
- const nodeApp: import("express").Express = express();
98
-
99
- nodeApp.use(cors());
100
- nodeApp.use(express.json());
101
-
102
- // Serve static files from output directory
103
- nodeApp.use("/output", express.static(path.join(__dirname, "../output")));
104
-
105
- /**
106
- * POST endpoint for video rendering requests.
107
- * Accepts project variables and settings, renders the video,
108
- * and returns a download URL for the completed video.
109
- *
110
- * @param req - Express request object containing variables and settings
111
- * @param res - Express response object
112
- *
113
- * @example
114
- * ```js
115
- * POST /api/render-video
116
- * Body: { variables: {...}, settings: {...} }
117
- * Response: { success: true, downloadUrl: "..." }
118
- * ```
119
- */
120
- nodeApp.post("/api/render-video", async (req, res) => {
121
- const { variables, settings } = req.body;
122
-
123
- try {
124
- const outputPath = await renderTwickVideo(variables, settings);
125
- res.json({
126
- success: true,
127
- downloadUrl: `${BASE_PATH}/download/${path.basename(outputPath)}`,
128
- });
129
- } catch (error) {
130
- console.error("Render error:", error);
131
- res.status(500).json({
132
- success: false,
133
- error: error instanceof Error ? error.message : "Unknown error",
134
- });
135
- }
136
- });
137
-
138
- /**
139
- * GET endpoint for downloading rendered videos.
140
- * Serves video files with rate limiting and security checks
141
- * to prevent path traversal attacks.
142
- *
143
- * @param req - Express request object with filename parameter
144
- * @param res - Express response object
145
- *
146
- * @example
147
- * ```js
148
- * GET /download/video-123.mp4
149
- * // Downloads the specified video file
150
- * ```
151
- */
152
- nodeApp.get("/download/:filename", rateLimitMiddleware, (req, res) => {
153
- const outputDir = path.resolve(__dirname, "../output");
154
- const requestedPath = path.resolve(outputDir, req.params.filename);
155
- if (!requestedPath.startsWith(outputDir + path.sep)) {
156
- // Attempted path traversal or access outside output directory
157
- res.status(403).json({
158
- success: false,
159
- error: "Forbidden",
160
- });
161
- return;
162
- }
163
- res.download(requestedPath, (err) => {
164
- if (err) {
165
- res.status(404).json({
166
- success: false,
167
- error: "File not found",
168
- });
169
- }
170
- });
171
- });
172
-
173
- /**
174
- * Health check endpoint for monitoring server status.
175
- * Returns server status and current timestamp for health monitoring.
176
- *
177
- * @param req - Express request object
178
- * @param res - Express response object
179
- *
180
- * @example
181
- * ```js
182
- * GET /health
183
- * Response: { status: "ok", timestamp: "2024-01-01T00:00:00.000Z" }
184
- * ```
185
- */
186
- nodeApp.get("/health", (req, res) => {
187
- res.json({
188
- status: "ok",
189
- timestamp: new Date().toISOString(),
190
- });
191
- });
192
-
193
- // Export the app for programmatic usage
194
- export default nodeApp;
195
-
196
- // Start the server
197
- nodeApp.listen(PORT, () => {
198
- console.log(`Render server running on port ${PORT}`);
199
- console.log(`Health check: ${BASE_PATH}/health`);
200
- console.log(`API endpoint: ${BASE_PATH}/api/render-video`);
201
- console.log(`Download endpoint rate limited: ${RATE_LIMIT_MAX_REQUESTS} requests per ${RATE_LIMIT_WINDOW_MS / 60000} minutes`);
202
- });
@@ -1,159 +0,0 @@
1
- /**
2
- * Test file for rendering a video with an example project
3
- *
4
- * This script demonstrates how to use the renderTwickVideo function
5
- * to create a video from a Twick project configuration.
6
- *
7
- * Run with: tsx src/test-render.ts
8
- */
9
-
10
- import { renderTwickVideo } from "./index.js";
11
- import { fileURLToPath } from "url";
12
- import { dirname, join } from "path";
13
-
14
- const __filename = fileURLToPath(import.meta.url);
15
- const __dirname = dirname(__filename);
16
-
17
- /**
18
- * Example project configuration
19
- * This creates a simple video with:
20
- * - A colored background rectangle
21
- * - Animated text elements
22
- * - Audio track
23
- */
24
- const exampleProject = {
25
- input: {
26
- properties: {
27
- width: 720,
28
- height: 1280,
29
- fps: 30,
30
- },
31
- "tracks": [
32
- {
33
- "id": "t-sample",
34
- "name": "sample",
35
- "type": "element",
36
- "props": {},
37
- "elements": [
38
- {
39
- "id": "e-sample",
40
- "trackId": "t-sample",
41
- "type": "text",
42
- "name": "sample",
43
- "s": 0,
44
- "e": 5,
45
- "props": {
46
- "text": "Twick SDK",
47
- "fill": "#FFFFFF"
48
- }
49
- }
50
- ]
51
- },
52
- {
53
- "id": "t-948a8e683ebb",
54
- "name": "Track_1772121198607",
55
- "type": "element",
56
- "props": {},
57
- "elements": [
58
- {
59
- "id": "e-cc0401034d3e",
60
- "trackId": "t-948a8e683ebb",
61
- "type": "image",
62
- "s": 0,
63
- "e": 3,
64
- "props": {
65
- "src": "https://images.pexels.com/photos/358457/pexels-photo-358457.jpeg",
66
- "mediaFilter": "none"
67
- },
68
- "frame": {
69
- "size": [
70
- 720,
71
- 1080.2700675168792
72
- ],
73
- "x": 0,
74
- "y": 0
75
- },
76
- "frameEffects": [],
77
- "objectFit": "cover"
78
- }
79
- ]
80
- },
81
- {
82
- "id": "t-85e232b36bd0",
83
- "name": "Track_1772121202675",
84
- "type": "element",
85
- "props": {},
86
- "elements": [
87
- {
88
- "id": "e-b262ef2b4ff1",
89
- "trackId": "t-85e232b36bd0",
90
- "type": "effect",
91
- "s": 0,
92
- "e": 1,
93
- "props": {
94
- "effectKey": "vignette",
95
- "intensity": 1
96
- }
97
- }
98
- ]
99
- }
100
- ],
101
- "version": 6,
102
- "metadata": {}
103
- },
104
- };
105
-
106
- /**
107
- * Render settings
108
- */
109
- const renderSettings = {
110
- outFile: `test-video-${Date.now()}.mp4`,
111
- outDir: join(__dirname, "../output"),
112
- quality: "medium",
113
- logProgress: true,
114
- };
115
-
116
- /**
117
- * Main test function
118
- */
119
- async function testVideoRender() {
120
- console.log("๐ŸŽฌ Starting video render test...\n");
121
- console.log("๐Ÿ“‹ Project Configuration:");
122
- console.log(` Resolution: ${exampleProject.input.properties.width}x${exampleProject.input.properties.height}`);
123
- console.log(` FPS: ${exampleProject.input.properties.fps}`);
124
- console.log(` Tracks: ${exampleProject.input.tracks.length}`);
125
- console.log(` Total Elements: ${exampleProject.input.tracks.reduce((sum, track) => sum + track.elements.length, 0)}\n`);
126
-
127
- try {
128
- console.log("๐Ÿ”„ Rendering video...");
129
- const startTime = Date.now();
130
-
131
- const outputPath = await renderTwickVideo(exampleProject, renderSettings);
132
-
133
- const endTime = Date.now();
134
- const duration = ((endTime - startTime) / 1000).toFixed(2);
135
-
136
- console.log("\nโœ… Video rendered successfully!");
137
- console.log(`๐Ÿ“ Output file: ${outputPath}`);
138
- console.log(`โฑ๏ธ Render time: ${duration}s`);
139
- console.log(`\n๐ŸŽ‰ Test completed successfully!`);
140
-
141
- return outputPath;
142
- } catch (error) {
143
- console.error("\nโŒ Render failed:");
144
- console.error(error);
145
- if (error instanceof Error) {
146
- console.error(` Error: ${error.message}`);
147
- if (error.stack) {
148
- console.error(` Stack: ${error.stack}`);
149
- }
150
- }
151
- process.exit(1);
152
- }
153
- }
154
-
155
- // Run the test
156
- testVideoRender().catch((error) => {
157
- console.error("Fatal error:", error);
158
- process.exit(1);
159
- });
package/test.js DELETED
@@ -1,163 +0,0 @@
1
- // Simple test script for the render server
2
- import fetch from 'node-fetch';
3
-
4
- const API_URL = 'http://localhost:3001';
5
-
6
- const sample = {
7
- "input": {
8
- "properties": {
9
- "width": 720,
10
- "height": 1280
11
- },
12
- "tracks": [
13
- {
14
- "id": "t-track-1",
15
- "type": "element",
16
- "elements": [
17
- {
18
- "id": "e-244f8d5a3baa",
19
- "trackId": "t-track-1",
20
- "type": "rect",
21
- "s": 0,
22
- "e": 5,
23
- "props": {
24
- "width": 720,
25
- "height": 1280,
26
- "fill": "#fff000"
27
- }
28
- }
29
- ],
30
- "name": "element"
31
- },
32
- {
33
- "id": "t-track-2",
34
- "type": "element",
35
- "elements": [
36
- {
37
- "id": "e-244f8d5a3bba",
38
- "trackId": "t-track-2",
39
- "type": "text",
40
- "s": 0,
41
- "e": 1,
42
- "props": {
43
- "text": "Hello Guys!",
44
- "fontSize": 100,
45
- "fill": "#FF0000"
46
- }
47
- },
48
- {
49
- "id": "e-244f8d5a3bbb",
50
- "trackId": "t-track-2",
51
- "type": "text",
52
- "s": 1,
53
- "e": 4,
54
- "props": {
55
- "text": "Welcome to the world of Twick!",
56
- "fontSize": 100,
57
- "fill": "#FF0000",
58
- "maxWidth": 500,
59
- "textAlign": "center",
60
- "textWrap": true
61
- }
62
- },
63
- {
64
- "id": "e-244f8d5a3bbc",
65
- "trackId": "t-track-2",
66
- "type": "text",
67
- "s": 4,
68
- "e": 5,
69
- "props": {
70
- "text": "Thank You !",
71
- "fontSize": 100,
72
- "fill": "#FF0000"
73
- }
74
- }
75
- ],
76
- "name": "element"
77
- },
78
- {
79
- "id": "t-track-3",
80
- "type": "element",
81
- "elements": [
82
- {
83
- "id": "e-244f8d5aabaa",
84
- "trackId": "t-track-3",
85
- "type": "audio",
86
- "s": 0,
87
- "e": 5,
88
- "props": {
89
- "src": "https://cdn.pixabay.com/audio/2024/09/15/audio_e00d39651a.mp3",
90
- "play": true,
91
- "volume": 1
92
- }
93
- }
94
- ],
95
- "name": "audio"
96
- }
97
- ],
98
- "version": 1
99
- }
100
- }
101
-
102
-
103
- async function testHealth() {
104
- try {
105
- const response = await fetch(`${API_URL}/health`);
106
- const result = await response.json();
107
- console.log('Health check passed:', result);
108
- return true;
109
- } catch (error) {
110
- console.error('Health check failed:', error.message);
111
- return false;
112
- }
113
- }
114
-
115
- async function testRender() {
116
- try {
117
- console.log('๐Ÿ”„ Testing video render...');
118
-
119
- const response = await fetch(`${API_URL}/api/render-video`, {
120
- method: 'POST',
121
- headers: {
122
- 'Content-Type': 'application/json',
123
- },
124
- body: JSON.stringify({
125
- variables: sample,
126
- settings: {
127
- outFile: `test-${Date.now()}.mp4`,
128
- }
129
- })
130
- });
131
-
132
- const result = await response.json();
133
-
134
- if (result.success) {
135
- console.log('Render test passed!');
136
- console.log('๐Ÿ“ Output:', result.downloadUrl);
137
- return true;
138
- } else {
139
- console.error('Render test failed:', result.error);
140
- return false;
141
- }
142
- } catch (error) {
143
- console.error('Render test failed:', error.message);
144
- return false;
145
- }
146
- }
147
-
148
- async function runTests() {
149
- console.log('๐Ÿงช Running render server tests...\n');
150
-
151
- const healthPassed = await testHealth();
152
- console.log('');
153
-
154
- if (healthPassed) {
155
- await testRender();
156
- } else {
157
- console.log('Skipping render test due to health check failure');
158
- }
159
-
160
- console.log('\n๐Ÿ Tests completed');
161
- }
162
-
163
- runTests().catch(console.error);
package/tsconfig.json DELETED
@@ -1,22 +0,0 @@
1
- {
2
- "compilerOptions": {
3
- "target": "ES2022",
4
- "module": "Node16",
5
- "moduleResolution": "Node16",
6
- "allowSyntheticDefaultImports": true,
7
- "esModuleInterop": true,
8
- "allowJs": true,
9
- "strict": true,
10
- "skipLibCheck": true,
11
- "forceConsistentCasingInFileNames": true,
12
- "outDir": "./dist",
13
- "rootDir": "./src",
14
- "declaration": true,
15
- "declarationMap": true,
16
- "sourceMap": true,
17
- "resolveJsonModule": true,
18
- "noEmit": false
19
- },
20
- "include": ["src/**/*"],
21
- "exclude": ["node_modules", "dist", "src/**/*.test.ts", "src/test-render.ts"]
22
- }
package/tsup.config.ts DELETED
@@ -1,49 +0,0 @@
1
- import { defineConfig } from 'tsup';
2
-
3
- export default defineConfig([
4
- // Build index.ts in both CJS and ESM for library exports
5
- {
6
- entry: ['src/index.ts'],
7
- format: ['cjs', 'esm'],
8
- dts: true,
9
- splitting: false,
10
- sourcemap: true,
11
- clean: true,
12
- outDir: 'dist',
13
- external: [
14
- '@twick/2d',
15
- '@twick/core',
16
- '@twick/ffmpeg',
17
- '@twick/renderer',
18
- '@twick/ui',
19
- '@twick/visualizer',
20
- 'cors',
21
- 'express',
22
- 'express-rate-limit',
23
- 'node-fetch',
24
- 'path'
25
- ],
26
- },
27
- // Build cli.ts and server.ts only as ESM (they use import.meta)
28
- {
29
- entry: ['src/cli.ts', 'src/server.ts'],
30
- format: ['esm'],
31
- dts: false, // No need for declarations for CLI/server files
32
- splitting: false,
33
- sourcemap: true,
34
- outDir: 'dist',
35
- external: [
36
- '@twick/2d',
37
- '@twick/core',
38
- '@twick/ffmpeg',
39
- '@twick/renderer',
40
- '@twick/ui',
41
- '@twick/visualizer',
42
- 'cors',
43
- 'express',
44
- 'express-rate-limit',
45
- 'node-fetch',
46
- 'path'
47
- ],
48
- },
49
- ]);