polotno-node 2.10.1 → 2.10.2

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.
Files changed (3) hide show
  1. package/instance.js +33 -1
  2. package/package.json +6 -7
  3. package/video.js +0 -161
package/instance.js CHANGED
@@ -75,6 +75,8 @@ module.exports.jsonToBlob = async (page, json, attrs) => {
75
75
 
76
76
  const busyPages = [];
77
77
 
78
+ const createdInstances = [];
79
+
78
80
  module.exports.createInstance = async ({
79
81
  key,
80
82
  url,
@@ -272,8 +274,9 @@ module.exports.createInstance = async ({
272
274
  return blob;
273
275
  };
274
276
 
275
- return {
277
+ const instance = {
276
278
  close: async () => {
279
+ createdInstances.splice(createdInstances.indexOf(instance), 1);
277
280
  await browser.close();
278
281
  },
279
282
  firstPage,
@@ -288,4 +291,33 @@ module.exports.createInstance = async ({
288
291
  jsonToGIFBase64,
289
292
  createPage: async () => await module.exports.createPage(browser, visitPage),
290
293
  };
294
+
295
+ createdInstances.push(instance);
296
+ return instance;
291
297
  };
298
+
299
+ // Function to close all created instances in parallel
300
+ const closeAllInstances = async () => {
301
+ await Promise.all(createdInstances.map((instance) => instance.close()));
302
+ };
303
+
304
+ // Register the function to be called on process exit
305
+ process.on('beforeExit', () => {
306
+ closeAllInstances().catch((error) => {
307
+ console.error('Error closing instances:', error);
308
+ });
309
+ });
310
+
311
+ // Also handle other termination signals
312
+ ['SIGINT', 'SIGTERM', 'SIGQUIT', 'exit', 'beforeExit'].forEach((signal) => {
313
+ process.on(signal, () => {
314
+ closeAllInstances()
315
+ .then(() => {
316
+ process.exit(0);
317
+ })
318
+ .catch((error) => {
319
+ console.error('Error closing instances:', error);
320
+ process.exit(1);
321
+ });
322
+ });
323
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "polotno-node",
3
- "version": "2.10.1",
3
+ "version": "2.10.2",
4
4
  "description": "Polotno workflow from NodeJS",
5
5
  "main": "index.js",
6
6
  "scripts": {
@@ -12,14 +12,13 @@
12
12
  "dist",
13
13
  "index.js",
14
14
  "instance.js",
15
- "video.js",
16
15
  "video-parallel.js",
17
16
  "README.md"
18
17
  ],
19
18
  "browserslist": "> 0.5%, last 2 versions, not dead",
20
19
  "devDependencies": {
21
20
  "ava": "^6.1.3",
22
- "axios": "^1.7.2",
21
+ "axios": "^1.7.5",
23
22
  "canvas": "^2.11.2",
24
23
  "dotenv": "^16.4.5",
25
24
  "fluent-ffmpeg": "^2.1.3",
@@ -29,14 +28,14 @@
29
28
  "polotno": "^2.12.2",
30
29
  "react": "^18.3.1",
31
30
  "react-dom": "^18.3.1",
32
- "vite": "^5.3.4"
31
+ "vite": "^5.4.2"
33
32
  },
34
33
  "author": "Anton Lavrenov",
35
34
  "license": "MIT",
36
35
  "dependencies": {
37
- "@sparticuz/chromium": "126.0.0",
38
- "puppeteer": "22.13.0",
39
- "puppeteer-core": "22.13.0",
36
+ "@sparticuz/chromium": "127.0.0",
37
+ "puppeteer": "23.1.1",
38
+ "puppeteer-core": "23.1.1",
40
39
  "tmp": "^0.2.3"
41
40
  },
42
41
  "bugs": {
package/video.js DELETED
@@ -1,161 +0,0 @@
1
- const fs = require('fs');
2
- const ffmpeg = require('fluent-ffmpeg');
3
- const axios = require('axios');
4
- const path = require('path');
5
-
6
- const downloadVideo = async (url, destination) => {
7
- const response = await axios({
8
- method: 'GET',
9
- url: url,
10
- responseType: 'stream',
11
- });
12
-
13
- const writer = response.data.pipe(fs.createWriteStream(destination));
14
-
15
- return new Promise((resolve, reject) => {
16
- writer.on('finish', resolve);
17
- writer.on('error', reject);
18
- });
19
- };
20
-
21
- // 2. Convert it into webm format
22
-
23
- const convertToWebM = (input, output) => {
24
- console.log(input, output);
25
- return new Promise((resolve, reject) => {
26
- ffmpeg(input)
27
- .outputOptions(['-c:v libvpx', '-crf 30', '-b:v 1000k'])
28
- .output(output)
29
- .on('start', () => {})
30
- .on('end', () => {
31
- resolve();
32
- })
33
- .on('error', (err) => {
34
- console.log('Error occurred: ' + err.message);
35
- reject(err);
36
- })
37
- .run();
38
- });
39
- };
40
-
41
- // 3. Serialize file into dataurl string
42
- const fileToDataUrl = (filename) => {
43
- return new Promise((resolve, reject) => {
44
- fs.readFile(filename, 'base64', (err, data) => {
45
- if (err) reject(err);
46
- resolve(`data:video/webm;base64,${data}`);
47
- });
48
- });
49
- };
50
-
51
- const videoToDataURL = async (url) => {
52
- console.log('downloading', url);
53
- const filename = Math.random().toString(36).substring(7);
54
- const destination = path.join('./tmp', filename + '.mp4');
55
- await downloadVideo(url, destination);
56
- const webmFile = destination.replace('.mp4', '.webm');
57
- console.log('converting to webm', url);
58
- await convertToWebM(destination, webmFile);
59
- const dataUrl = await fileToDataUrl(webmFile);
60
- return dataUrl;
61
- };
62
-
63
- function printProgress(progress) {
64
- process.stdout.clearLine(0);
65
- process.stdout.cursorTo(0);
66
- process.stdout.write('Rendering frames: ' + progress + '%');
67
- }
68
-
69
- module.exports.jsonToVideo = async function jsonToGifFile(page, json, attrs) {
70
- try {
71
- fs.rmSync('./tmp', { recursive: true });
72
- } catch (e) {}
73
-
74
- fs.mkdirSync('./tmp', { recursive: true });
75
-
76
- for (const page of json.pages) {
77
- for (const el of page.children) {
78
- if (el.type === 'video') {
79
- el.src = await videoToDataURL(el.src);
80
- }
81
- }
82
- }
83
- // first load json
84
- await page.evaluate(
85
- async (json, attrs) => {
86
- store.loadJSON(json);
87
- await store.waitLoading();
88
- // TODO: we need to active all pages first
89
- // disable text fit, as it is already should be processed
90
- if (window.config.unstable_setTextOverflow) {
91
- window.config.unstable_setTextOverflow('resize');
92
- } else {
93
- console.error('Can not set text overflow mode');
94
- }
95
- },
96
- json,
97
- attrs || {}
98
- );
99
-
100
- const duration = await page.evaluate(async () => {
101
- return store.duration;
102
- });
103
-
104
- const fps = 15;
105
- const timePerFrame = 1000 / fps;
106
-
107
- // loop through the images and add each to the animation
108
- const frames = Math.floor((duration / 1000) * fps);
109
- for (let i = 0; i < frames; i++) {
110
- let currentTime = i * timePerFrame;
111
- if (i === 0) {
112
- // offset the very first frame to enable animation start
113
- currentTime = 1;
114
- }
115
- if (i === frames - 1) {
116
- // offset the very last frame to enable animation end
117
- currentTime = duration - 1;
118
- }
119
-
120
- const dataURL = await page.evaluate(
121
- async (json, attrs, currentTime) => {
122
- store.setCurrentTime(currentTime);
123
- const currentPage = store.pages.find((p) => {
124
- return (
125
- store.currentTime >= p.startTime &&
126
- store.currentTime < p.startTime + p.duration
127
- );
128
- });
129
- const url = await store.toDataURL({
130
- pixelRatio: 0.5,
131
- ...attrs,
132
- pageId: currentPage?.id,
133
- });
134
- return url;
135
- },
136
- json,
137
- attrs || {},
138
- currentTime
139
- );
140
- const progress = ((i / (frames - 1)) * 100).toFixed(1);
141
- printProgress(progress);
142
- fs.mkdirSync('./tmp', { recursive: true });
143
- fs.writeFileSync(`./tmp/${i}.png`, dataURL.split(',')[1], 'base64');
144
- }
145
-
146
- console.log('\nRendering video');
147
-
148
- await new Promise((resolve, reject) => {
149
- ffmpeg()
150
- .input(`./tmp/%d.png`) // Make sure your images are named with numbers, e.g. 1.jpg, 2.jpg, etc.
151
- .inputFPS(fps)
152
- .videoCodec('libx264')
153
- .outputOptions('-pix_fmt yuv420p')
154
- .format('mp4')
155
- .on('end', () => resolve())
156
- .on('error', (err) => reject(err))
157
- .save(attrs.out);
158
- });
159
-
160
- fs.rmSync('./tmp', { recursive: true });
161
- };