@rosepetal/node-red-contrib-image-tools 1.1.3

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 (131) hide show
  1. package/.gitattributes +6 -0
  2. package/.github/workflows/build-prebuild.yml +326 -0
  3. package/LICENSE +13 -0
  4. package/README.md +161 -0
  5. package/artifacts/darwin-arm64/package.json +25 -0
  6. package/artifacts/linux-arm64/package.json +26 -0
  7. package/artifacts/linux-x64/package.json +26 -0
  8. package/artifacts/linuxmusl-x64/package.json +26 -0
  9. package/assets/flow_time_example.gif +0 -0
  10. package/assets/nodes/io/array-in-demo.gif +0 -0
  11. package/assets/nodes/io/array-out-demo.gif +0 -0
  12. package/assets/nodes/io/array-select-demo.gif +0 -0
  13. package/assets/nodes/io/image-in-demo.gif +0 -0
  14. package/assets/nodes/mix/concat-demo.gif +0 -0
  15. package/assets/nodes/mix/mosaic-demo.gif +0 -0
  16. package/assets/nodes/transform/crop-demo.gif +0 -0
  17. package/assets/nodes/transform/filter-demo.gif +0 -0
  18. package/assets/nodes/transform/padding-demo.gif +0 -0
  19. package/assets/nodes/transform/resize-demo.gif +0 -0
  20. package/assets/nodes/transform/rotate-demo.gif +0 -0
  21. package/docs/nodes/blend/add-mask.md +275 -0
  22. package/docs/nodes/blend/add-masks.md +284 -0
  23. package/docs/nodes/blend/blend.md +248 -0
  24. package/docs/nodes/io/array-in.md +119 -0
  25. package/docs/nodes/io/array-out.md +150 -0
  26. package/docs/nodes/io/array-select.md +157 -0
  27. package/docs/nodes/io/image-in.md +131 -0
  28. package/docs/nodes/io/image-out.md +179 -0
  29. package/docs/nodes/io/queue.md +57 -0
  30. package/docs/nodes/io/save-file.md +30 -0
  31. package/docs/nodes/mix/advanced-mosaic.md +108 -0
  32. package/docs/nodes/mix/concat.md +127 -0
  33. package/docs/nodes/mix/mosaic.md +146 -0
  34. package/docs/nodes/specialized/cropBB.md +271 -0
  35. package/docs/nodes/specialized/image-align.md +426 -0
  36. package/docs/nodes/transform/crop.md +132 -0
  37. package/docs/nodes/transform/draw.md +77 -0
  38. package/docs/nodes/transform/filter.md +84 -0
  39. package/docs/nodes/transform/padding.md +133 -0
  40. package/docs/nodes/transform/resize.md +158 -0
  41. package/docs/nodes/transform/rotate.md +121 -0
  42. package/docs/nodes/util/block-detect.md +46 -0
  43. package/install.sh +144 -0
  44. package/node-red-contrib-image-tools/lib/cpp-bridge.js +224 -0
  45. package/node-red-contrib-image-tools/lib/node-utils.js +529 -0
  46. package/node-red-contrib-image-tools/nodes/blend/add-bbs.html +590 -0
  47. package/node-red-contrib-image-tools/nodes/blend/add-bbs.js +241 -0
  48. package/node-red-contrib-image-tools/nodes/blend/add-mask.html +449 -0
  49. package/node-red-contrib-image-tools/nodes/blend/add-mask.js +170 -0
  50. package/node-red-contrib-image-tools/nodes/blend/add-masks.html +703 -0
  51. package/node-red-contrib-image-tools/nodes/blend/add-masks.js +321 -0
  52. package/node-red-contrib-image-tools/nodes/blend/blend.html +552 -0
  53. package/node-red-contrib-image-tools/nodes/blend/blend.js +124 -0
  54. package/node-red-contrib-image-tools/nodes/io/array-in.html +110 -0
  55. package/node-red-contrib-image-tools/nodes/io/array-in.js +113 -0
  56. package/node-red-contrib-image-tools/nodes/io/array-out.html +125 -0
  57. package/node-red-contrib-image-tools/nodes/io/array-out.js +213 -0
  58. package/node-red-contrib-image-tools/nodes/io/array-select.html +156 -0
  59. package/node-red-contrib-image-tools/nodes/io/array-select.js +187 -0
  60. package/node-red-contrib-image-tools/nodes/io/folder-in.html +248 -0
  61. package/node-red-contrib-image-tools/nodes/io/folder-in.js +335 -0
  62. package/node-red-contrib-image-tools/nodes/io/image-in.html +146 -0
  63. package/node-red-contrib-image-tools/nodes/io/image-in.js +143 -0
  64. package/node-red-contrib-image-tools/nodes/io/image-out.html +506 -0
  65. package/node-red-contrib-image-tools/nodes/io/image-out.js +545 -0
  66. package/node-red-contrib-image-tools/nodes/io/queue.html +119 -0
  67. package/node-red-contrib-image-tools/nodes/io/queue.js +191 -0
  68. package/node-red-contrib-image-tools/nodes/io/save-file.html +243 -0
  69. package/node-red-contrib-image-tools/nodes/io/save-file.js +440 -0
  70. package/node-red-contrib-image-tools/nodes/mix/advanced-mosaic.html +2149 -0
  71. package/node-red-contrib-image-tools/nodes/mix/advanced-mosaic.js +195 -0
  72. package/node-red-contrib-image-tools/nodes/mix/concat.html +390 -0
  73. package/node-red-contrib-image-tools/nodes/mix/concat.js +112 -0
  74. package/node-red-contrib-image-tools/nodes/mix/mosaic.html +550 -0
  75. package/node-red-contrib-image-tools/nodes/mix/mosaic.js +151 -0
  76. package/node-red-contrib-image-tools/nodes/specialized/cropBB.html +268 -0
  77. package/node-red-contrib-image-tools/nodes/specialized/cropBB.js +277 -0
  78. package/node-red-contrib-image-tools/nodes/specialized/image-align.html +528 -0
  79. package/node-red-contrib-image-tools/nodes/specialized/image-align.js +306 -0
  80. package/node-red-contrib-image-tools/nodes/transform/crop.html +410 -0
  81. package/node-red-contrib-image-tools/nodes/transform/crop.js +149 -0
  82. package/node-red-contrib-image-tools/nodes/transform/draw.html +719 -0
  83. package/node-red-contrib-image-tools/nodes/transform/draw.js +509 -0
  84. package/node-red-contrib-image-tools/nodes/transform/filter.html +578 -0
  85. package/node-red-contrib-image-tools/nodes/transform/filter.js +177 -0
  86. package/node-red-contrib-image-tools/nodes/transform/padding.html +475 -0
  87. package/node-red-contrib-image-tools/nodes/transform/padding.js +142 -0
  88. package/node-red-contrib-image-tools/nodes/transform/resize.html +429 -0
  89. package/node-red-contrib-image-tools/nodes/transform/resize.js +162 -0
  90. package/node-red-contrib-image-tools/nodes/transform/rotate.html +299 -0
  91. package/node-red-contrib-image-tools/nodes/transform/rotate.js +141 -0
  92. package/node-red-contrib-image-tools/nodes/util/block-detect.html +85 -0
  93. package/node-red-contrib-image-tools/nodes/util/block-detect.js +136 -0
  94. package/node-red-contrib-image-tools/nodes/util/clean-debug.html +201 -0
  95. package/node-red-contrib-image-tools/nodes/util/clean-debug.js +393 -0
  96. package/node-red-contrib-image-tools/package.json +64 -0
  97. package/npm/darwin-arm64/lib/.gitkeep +1 -0
  98. package/npm/darwin-arm64/package.json +25 -0
  99. package/npm/darwin-x64/lib/.gitkeep +1 -0
  100. package/npm/darwin-x64/package.json +25 -0
  101. package/npm/linux-arm64/lib/.gitkeep +1 -0
  102. package/npm/linux-arm64/package.json +26 -0
  103. package/npm/linux-x64/lib/.gitkeep +1 -0
  104. package/npm/linux-x64/package.json +26 -0
  105. package/npm/linuxmusl-x64/lib/.gitkeep +1 -0
  106. package/npm/linuxmusl-x64/package.json +26 -0
  107. package/npm/win32-x64/lib/.gitkeep +1 -0
  108. package/npm/win32-x64/package.json +25 -0
  109. package/package.json +74 -0
  110. package/rosepetal-image-engine/binding.gyp +153 -0
  111. package/rosepetal-image-engine/package.json +19 -0
  112. package/rosepetal-image-engine/src/add-bbs.cpp +433 -0
  113. package/rosepetal-image-engine/src/add-mask.cpp +240 -0
  114. package/rosepetal-image-engine/src/add-masks.cpp +638 -0
  115. package/rosepetal-image-engine/src/advanced-mosaic.cpp +740 -0
  116. package/rosepetal-image-engine/src/blend.cpp +200 -0
  117. package/rosepetal-image-engine/src/concat.cpp +329 -0
  118. package/rosepetal-image-engine/src/crop.cpp +139 -0
  119. package/rosepetal-image-engine/src/draw.cpp +414 -0
  120. package/rosepetal-image-engine/src/filter.cpp +230 -0
  121. package/rosepetal-image-engine/src/filters/kernels.h +171 -0
  122. package/rosepetal-image-engine/src/image-align.cpp +551 -0
  123. package/rosepetal-image-engine/src/main.cpp +36 -0
  124. package/rosepetal-image-engine/src/mosaic.cpp +373 -0
  125. package/rosepetal-image-engine/src/padding.cpp +124 -0
  126. package/rosepetal-image-engine/src/resize.cpp +210 -0
  127. package/rosepetal-image-engine/src/rotate.cpp +177 -0
  128. package/rosepetal-image-engine/src/utils.h +563 -0
  129. package/rosepetal-image-engine/test-formats.js +119 -0
  130. package/scripts/build-opencv-static.ps1 +166 -0
  131. package/scripts/build-opencv-static.sh +147 -0
@@ -0,0 +1,440 @@
1
+ /**
2
+ * @file Generic filesystem sink that can write JSON, images, text, or binary data.
3
+ * Designed to accept raw image objects, encoded buffers, or plain JS values.
4
+ */
5
+ const fs = require('fs').promises;
6
+ const path = require('path');
7
+ const sharp = require('sharp');
8
+ const JSON_WARN_BYTES = 5 * 1024 * 1024; // warn when JSON output is larger than 5MB
9
+
10
+ module.exports = function (RED) {
11
+ const NodeUtils = require('../../lib/node-utils.js')(RED);
12
+
13
+ function SaveFileNode(config) {
14
+ RED.nodes.createNode(this, config);
15
+ const node = this;
16
+ const diskWarnState = { logged: false };
17
+
18
+ node.on('input', async (msg, send, done) => {
19
+ const started = Date.now();
20
+ node.status({ fill: 'blue', shape: 'dot', text: 'saving...' });
21
+
22
+ try {
23
+ const evaluateProperty = (value, type, fallback = 'str') =>
24
+ new Promise((resolve, reject) => {
25
+ const actualType = type || fallback;
26
+ try {
27
+ RED.util.evaluateNodeProperty(value, actualType, node, msg, (err, res) => {
28
+ if (err) reject(err);
29
+ else resolve(res);
30
+ });
31
+ } catch (err) {
32
+ reject(err);
33
+ }
34
+ });
35
+
36
+ // Resolve paths and inputs
37
+ const folderPathType = config.folderPathType || 'str';
38
+ const folderPathValue = await evaluateProperty(config.folderPath, folderPathType);
39
+ const folderPath = String(folderPathValue ?? '').trim();
40
+ if (!folderPath) {
41
+ throw new Error('Folder path is not configured or resolved.');
42
+ }
43
+ await fs.mkdir(folderPath, { recursive: true });
44
+
45
+ const inputPath = config.inputPath || 'payload';
46
+ const inputPathType = config.inputPathType || 'msg';
47
+ let incoming;
48
+ if (inputPathType === 'msg') {
49
+ incoming = RED.util.getMessageProperty(msg, inputPath);
50
+ } else if (inputPathType === 'flow') {
51
+ incoming = node.context().flow.get(inputPath);
52
+ } else if (inputPathType === 'global') {
53
+ incoming = node.context().global.get(inputPath);
54
+ }
55
+ if (incoming === undefined) {
56
+ throw new Error('No data found at configured input path.');
57
+ }
58
+
59
+ // Resolve file name
60
+ const filenameType = config.filenameType || 'str';
61
+ const filenameValue = await evaluateProperty(config.filename, filenameType);
62
+ const filenameRaw = filenameValue !== undefined && filenameValue !== null
63
+ ? String(filenameValue).trim()
64
+ : '';
65
+ if (/[\\/]/.test(filenameRaw)) {
66
+ throw new Error('Filename must not contain path separators.');
67
+ }
68
+ const parsedName = path.parse(filenameRaw);
69
+ let baseName = parsedName.name || '';
70
+ let extFromName = parsedName.ext ? parsedName.ext.replace(/^\./, '') : '';
71
+
72
+ // Determine file type and format
73
+ const configType = String(config.fileType || 'auto').toLowerCase();
74
+ let imageFormat = String(config.imageFormat || 'jpg').toLowerCase();
75
+ const extInfo = mapExtension(extFromName);
76
+
77
+ let fileType = configType;
78
+ if (fileType === 'auto' && extInfo?.type) {
79
+ fileType = extInfo.type;
80
+ if (extInfo.format) {
81
+ imageFormat = extInfo.format;
82
+ }
83
+ }
84
+
85
+ const inferred = fileType === 'auto'
86
+ ? await inferFileType(incoming, extInfo)
87
+ : { type: fileType, format: imageFormat };
88
+
89
+ fileType = inferred.type;
90
+ if (fileType === 'image' && inferred.format) {
91
+ imageFormat = inferred.format;
92
+ }
93
+ if (fileType === 'image' && extInfo?.format) {
94
+ imageFormat = extInfo.format;
95
+ }
96
+
97
+ if (!['image', 'json', 'text', 'binary'].includes(fileType)) {
98
+ throw new Error(`Unsupported file type: ${fileType}`);
99
+ }
100
+
101
+ // Finalize extension and name
102
+ let extension = extFromName || defaultExtension(fileType, imageFormat);
103
+ if (!extension) {
104
+ throw new Error('Unable to determine file extension.');
105
+ }
106
+ if (!baseName) {
107
+ baseName = defaultBaseName(fileType);
108
+ }
109
+ let filename = `${baseName}.${extension}`;
110
+ const originalFilename = filename;
111
+ let filePath = path.join(folderPath, filename);
112
+
113
+ const overwriteEnabled = String(config.overwriteProtection) !== 'false';
114
+ if (overwriteEnabled) {
115
+ let counter = 2;
116
+ while (await fileExists(filePath)) {
117
+ filename = `${baseName}_${counter}.${extension}`;
118
+ filePath = path.join(folderPath, filename);
119
+ counter += 1;
120
+ if (counter > 1000) {
121
+ throw new Error('Too many file variations exist in target folder.');
122
+ }
123
+ }
124
+ }
125
+
126
+ // Check disk space (skip if 90%+ used)
127
+ const diskInfo = await getDiskUsageInfo(folderPath, node, diskWarnState);
128
+ if (diskInfo && diskInfo.usedRatio >= 0.9) {
129
+ const usedPercent = (diskInfo.usedRatio * 100).toFixed(1);
130
+ node.warn(`Storage at "${folderPath}" is ${usedPercent}% full. Skipping save to avoid exhausting disk space.`);
131
+ node.status({ fill: 'yellow', shape: 'ring', text: `disk ${usedPercent}% full` });
132
+ done && done();
133
+ return;
134
+ }
135
+
136
+ // Prepare data to write
137
+ const quality = parseInt(config.imageQuality, 10) || 90;
138
+ const pngOptimize = config.pngOptimize === true || config.pngOptimize === 'true';
139
+ const jsonIndent = Number.isInteger(parseInt(config.jsonIndent, 10))
140
+ ? parseInt(config.jsonIndent, 10)
141
+ : 2;
142
+
143
+ let payloadToWrite;
144
+ let isText = false;
145
+
146
+ if (fileType === 'image') {
147
+ payloadToWrite = await toImageBuffer(incoming, imageFormat, quality, pngOptimize, NodeUtils, node);
148
+ } else if (fileType === 'json') {
149
+ if (typeof incoming === 'string') {
150
+ try {
151
+ // Keep valid JSON strings as-is
152
+ JSON.parse(incoming);
153
+ payloadToWrite = incoming;
154
+ } catch {
155
+ payloadToWrite = JSON.stringify(incoming, null, jsonIndent);
156
+ }
157
+ } else {
158
+ payloadToWrite = JSON.stringify(incoming, null, jsonIndent);
159
+ }
160
+ isText = true;
161
+ } else if (fileType === 'text') {
162
+ payloadToWrite = incoming === undefined || incoming === null ? '' : String(incoming);
163
+ isText = true;
164
+ } else {
165
+ payloadToWrite = await toBinary(incoming);
166
+ }
167
+
168
+ if (isText) {
169
+ await fs.writeFile(filePath, payloadToWrite, 'utf8');
170
+ } else {
171
+ await fs.writeFile(filePath, payloadToWrite);
172
+ }
173
+
174
+ const sizeBytes = isText
175
+ ? Buffer.byteLength(payloadToWrite, 'utf8')
176
+ : payloadToWrite.length;
177
+
178
+ if (fileType === 'json' && sizeBytes >= JSON_WARN_BYTES) {
179
+ const sizeMB = (sizeBytes / (1024 * 1024)).toFixed(1);
180
+ node.warn(`JSON output is large (${sizeMB} MB); this may impact the event loop and memory usage.`);
181
+ }
182
+
183
+ const resultInfo = {
184
+ path: filePath,
185
+ filename,
186
+ type: fileType,
187
+ extension,
188
+ sizeBytes
189
+ };
190
+ if (fileType === 'image') {
191
+ resultInfo.format = imageFormat;
192
+ }
193
+
194
+ // Optionally attach result info for downstream nodes
195
+ const outputPath = config.outputPath || 'savedFile';
196
+ const outputPathType = config.outputPathType || 'msg';
197
+ try {
198
+ if (outputPathType === 'msg') {
199
+ RED.util.setMessageProperty(msg, outputPath, resultInfo, true);
200
+ } else if (outputPathType === 'flow') {
201
+ node.context().flow.set(outputPath, resultInfo);
202
+ } else if (outputPathType === 'global') {
203
+ node.context().global.set(outputPath, resultInfo);
204
+ }
205
+ } catch (setErr) {
206
+ node.warn(`Unable to store output metadata: ${setErr.message}`);
207
+ }
208
+
209
+ const elapsed = Date.now() - started;
210
+ const renameOccurred = overwriteEnabled && filename !== originalFilename;
211
+ const statusSuffix = renameOccurred ? ' (avoided overwrite)' : '';
212
+ node.status({
213
+ fill: 'green',
214
+ shape: 'dot',
215
+ text: `saved ${filename}${statusSuffix} (${elapsed}ms)`
216
+ });
217
+
218
+ // Record basic performance metric for consistency across nodes
219
+ NodeUtils.recordPerformanceMetrics(node, msg, { taskMs: elapsed }, elapsed);
220
+
221
+ send(msg);
222
+ done && done();
223
+ } catch (err) {
224
+ node.status({ fill: 'red', shape: 'ring', text: 'Error' });
225
+ node.error(err.message, msg);
226
+ done && done(err);
227
+ }
228
+ });
229
+ }
230
+
231
+ RED.nodes.registerType('save-file', SaveFileNode);
232
+ };
233
+
234
+ // Helpers
235
+ function mapExtension(ext) {
236
+ if (!ext) return null;
237
+ const lower = ext.toLowerCase();
238
+ if (lower === 'jpg' || lower === 'jpeg') return { type: 'image', format: 'jpg' };
239
+ if (lower === 'png') return { type: 'image', format: 'png' };
240
+ if (lower === 'webp') return { type: 'image', format: 'webp' };
241
+ if (lower === 'json') return { type: 'json' };
242
+ if (lower === 'txt') return { type: 'text' };
243
+ if (lower === 'bin' || lower === 'dat') return { type: 'binary' };
244
+ return null;
245
+ }
246
+
247
+ function defaultExtension(type, imageFormat) {
248
+ if (type === 'image') return imageFormat || 'jpg';
249
+ if (type === 'json') return 'json';
250
+ if (type === 'text') return 'txt';
251
+ if (type === 'binary') return 'bin';
252
+ return '';
253
+ }
254
+
255
+ function defaultBaseName(type) {
256
+ const timestamp = new Date()
257
+ .toISOString()
258
+ .replace(/[-:]/g, '')
259
+ .replace(/\.\d{3}Z$/, 'Z')
260
+ .replace('T', '_');
261
+ switch (type) {
262
+ case 'image': return `image_${timestamp}`;
263
+ case 'json': return `data_${timestamp}`;
264
+ case 'text': return `text_${timestamp}`;
265
+ default: return `file_${timestamp}`;
266
+ }
267
+ }
268
+
269
+ async function fileExists(p) {
270
+ try {
271
+ await fs.access(p);
272
+ return true;
273
+ } catch {
274
+ return false;
275
+ }
276
+ }
277
+
278
+ async function inferFileType(value, extInfo) {
279
+ if (extInfo?.type) {
280
+ return { type: extInfo.type, format: extInfo.format };
281
+ }
282
+
283
+ if (value && typeof value === 'object') {
284
+ if (Buffer.isBuffer(value)) {
285
+ try {
286
+ const meta = await sharp(value).metadata();
287
+ if (meta?.format) {
288
+ const fmt = normalizeSharpFormat(meta.format);
289
+ if (fmt) return { type: 'image', format: fmt };
290
+ }
291
+ } catch {
292
+ // Not an image buffer
293
+ }
294
+ return { type: 'binary' };
295
+ }
296
+
297
+ if (isRawImageLike(value)) {
298
+ return { type: 'image' };
299
+ }
300
+
301
+ return { type: 'json' };
302
+ }
303
+
304
+ if (typeof value === 'string') {
305
+ const trimmed = value.trim();
306
+ if ((trimmed.startsWith('{') && trimmed.endsWith('}')) ||
307
+ (trimmed.startsWith('[') && trimmed.endsWith(']'))) {
308
+ return { type: 'json' };
309
+ }
310
+ return { type: 'text' };
311
+ }
312
+
313
+ return { type: 'binary' };
314
+ }
315
+
316
+ function normalizeSharpFormat(fmt) {
317
+ if (!fmt) return null;
318
+ if (fmt === 'jpeg' || fmt === 'jpg') return 'jpg';
319
+ if (fmt === 'png') return 'png';
320
+ if (fmt === 'webp') return 'webp';
321
+ return null;
322
+ }
323
+
324
+ function isRawImageLike(obj) {
325
+ return obj &&
326
+ typeof obj === 'object' &&
327
+ !Buffer.isBuffer(obj) &&
328
+ Object.prototype.hasOwnProperty.call(obj, 'data') &&
329
+ Object.prototype.hasOwnProperty.call(obj, 'width') &&
330
+ Object.prototype.hasOwnProperty.call(obj, 'height');
331
+ }
332
+
333
+ async function toBinary(value) {
334
+ if (Buffer.isBuffer(value)) return value;
335
+ if (value && typeof value === 'object' && Buffer.isBuffer(value.data)) {
336
+ return Buffer.from(value.data);
337
+ }
338
+ if (typeof value === 'string') {
339
+ return Buffer.from(value, 'utf8');
340
+ }
341
+ return Buffer.from(JSON.stringify(value ?? ''), 'utf8');
342
+ }
343
+
344
+ async function toImageBuffer(imageValue, format, quality, pngOptimize, NodeUtils, node) {
345
+ // Encoded buffer path
346
+ if (Buffer.isBuffer(imageValue) && !(imageValue.width && imageValue.height)) {
347
+ let inputFormat;
348
+ try {
349
+ const metadata = await sharp(imageValue).metadata();
350
+ inputFormat = metadata.format;
351
+ } catch {
352
+ inputFormat = null;
353
+ }
354
+
355
+ if (inputFormat && (normalizeSharpFormat(inputFormat) === format)) {
356
+ return imageValue;
357
+ }
358
+
359
+ const sharpInstance = sharp(imageValue);
360
+ return encodeSharp(sharpInstance, format, quality, pngOptimize);
361
+ }
362
+
363
+ // Raw image path (uses validator for clear errors)
364
+ const validated = NodeUtils.validateImageStructure(imageValue, node);
365
+ if (!validated) {
366
+ throw new Error('Invalid image structure.');
367
+ }
368
+
369
+ const colorSpace = validated.colorSpace;
370
+ const channels = validated.channels;
371
+ let data = validated.data;
372
+
373
+ if (colorSpace === 'BGR' || colorSpace === 'BGRA') {
374
+ data = Buffer.from(data);
375
+ for (let i = 0; i < data.length; i += channels) {
376
+ const t = data[i];
377
+ data[i] = data[i + 2];
378
+ data[i + 2] = t;
379
+ }
380
+ }
381
+
382
+ let sharpInstance = sharp(data, {
383
+ raw: {
384
+ width: validated.width,
385
+ height: validated.height,
386
+ channels: channels
387
+ }
388
+ });
389
+
390
+ if (colorSpace === 'GRAY') {
391
+ sharpInstance = sharpInstance.toColourspace('b-w');
392
+ }
393
+
394
+ return encodeSharp(sharpInstance, format, quality, pngOptimize);
395
+ }
396
+
397
+ function encodeSharp(sharpInstance, format, quality, pngOptimize) {
398
+ if (format === 'png') {
399
+ const pngOptions = pngOptimize
400
+ ? { compressionLevel: 9, palette: true }
401
+ : { compressionLevel: 6 };
402
+ return sharpInstance.png(pngOptions).toBuffer();
403
+ }
404
+ if (format === 'webp') {
405
+ return sharpInstance.webp({ quality }).toBuffer();
406
+ }
407
+ return sharpInstance.jpeg({ quality }).toBuffer();
408
+ }
409
+
410
+ async function getDiskUsageInfo(targetPath, node, warnState) {
411
+ try {
412
+ const stats = await fs.statfs(targetPath);
413
+ const blockSize = Number(stats.bsize) || 0;
414
+ const totalBlocks = Number(stats.blocks) || 0;
415
+ const availableBlocks = Number(
416
+ stats.bavail !== undefined ? stats.bavail :
417
+ stats.bfree !== undefined ? stats.bfree : 0
418
+ );
419
+
420
+ const totalBytes = totalBlocks * blockSize;
421
+ const availableBytes = availableBlocks * blockSize;
422
+
423
+ if (totalBytes <= 0) {
424
+ return null;
425
+ }
426
+
427
+ const usedRatio = 1 - (availableBytes / totalBytes);
428
+ return {
429
+ totalBytes,
430
+ availableBytes,
431
+ usedRatio
432
+ };
433
+ } catch (err) {
434
+ if (!warnState.logged) {
435
+ node.warn(`Disk usage check failed for "${targetPath}": ${err.message}`);
436
+ warnState.logged = true;
437
+ }
438
+ return null;
439
+ }
440
+ }