@zapwebp/core 1.1.1 → 1.1.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.
- package/README.md +79 -51
- package/agent.json +180 -0
- package/package.json +8 -2
- package/src/cache.js +145 -0
- package/src/engine/decode.js +60 -0
- package/src/engine/encode.js +106 -0
- package/src/engine/pipeline.js +116 -0
- package/src/engine/transform.js +37 -0
- package/src/errors/index.js +34 -0
- package/src/formats/avif.js +1 -1
- package/src/formats/gif.js +8 -2
- package/src/formats/index.js +5 -0
- package/src/formats/jpeg.js +14 -3
- package/src/formats/png.js +1 -1
- package/src/formats/svg.js +76 -14
- package/src/formats/tiff.js +8 -2
- package/src/formats/webp.js +1 -1
- package/src/index.d.ts +286 -9
- package/src/index.js +951 -80
- package/src/journal/index.js +73 -0
- package/src/metadata/c2pa.js +3 -10
- package/src/metadata/chunk-stripper.js +235 -0
- package/src/metadata/exif.js +3 -11
- package/src/metadata/icc.js +3 -10
- package/src/metadata/png-text.js +3 -10
- package/src/metadata/registry.js +25 -2
- package/src/metadata/xmp.js +3 -16
- package/src/parallel.js +134 -0
- package/src/policy.js +95 -6
- package/src/registry/compression.js +84 -0
- package/src/registry/formats.js +30 -0
- package/src/registry/metadata.js +28 -0
- package/src/registry/transforms.js +76 -0
- package/src/report.js +404 -0
- package/src/safety/path.js +52 -0
- package/src/safety/runtime.js +66 -0
- package/src/safety/ssrf.js +9 -0
- package/src/safety/svg.js +66 -0
- package/src/signals.js +683 -0
- package/src/smart.js +351 -0
- package/src/team-policy.js +319 -0
- package/src/testing.d.ts +18 -0
- package/src/testing.js +114 -0
- package/src/tools.js +240 -0
- package/src/types.ts +68 -0
package/src/index.js
CHANGED
|
@@ -17,6 +17,36 @@ const {
|
|
|
17
17
|
checkPolicyInput,
|
|
18
18
|
evaluateQuality,
|
|
19
19
|
} = require('./policy');
|
|
20
|
+
const { listTools, getAgentManifest } = require('./tools');
|
|
21
|
+
const { computeCacheKey, ConversionCache, defaultCache } = require('./cache');
|
|
22
|
+
const { parallelMap, ConversionPool, defaultPool } = require('./parallel');
|
|
23
|
+
const { assertRuntimeIsolation, detectEnvironment } = require('./safety/runtime');
|
|
24
|
+
const {
|
|
25
|
+
computeContentSignals,
|
|
26
|
+
suggest,
|
|
27
|
+
attachCustomMetadata,
|
|
28
|
+
extractCustomMetadata,
|
|
29
|
+
evaluateSourceQuality,
|
|
30
|
+
evaluateSizeImpact,
|
|
31
|
+
verifyLosslessPixels,
|
|
32
|
+
} = require('./signals');
|
|
33
|
+
const {
|
|
34
|
+
computePerformanceReport,
|
|
35
|
+
formatPerformanceReport,
|
|
36
|
+
} = require('./report');
|
|
37
|
+
const {
|
|
38
|
+
analyzeSmart,
|
|
39
|
+
classifyContentType,
|
|
40
|
+
extractSmartSignals,
|
|
41
|
+
RECOMMENDATION_PROFILES,
|
|
42
|
+
} = require('./smart');
|
|
43
|
+
const {
|
|
44
|
+
DEFAULT_TEAM_POLICY_TEMPLATE,
|
|
45
|
+
validateTeamPolicy,
|
|
46
|
+
evaluateFilePolicy,
|
|
47
|
+
checkExceptionsStatus,
|
|
48
|
+
formatPolicyStatus,
|
|
49
|
+
} = require('./team-policy');
|
|
20
50
|
|
|
21
51
|
let _sharpInstance = null;
|
|
22
52
|
function getSharp() {
|
|
@@ -52,7 +82,7 @@ function getResvg() {
|
|
|
52
82
|
const MAX_WIDTH = MAX_DIMENSION;
|
|
53
83
|
const FIT_MODES = Object.freeze(['contain', 'cover', 'fill', 'inside', 'outside']);
|
|
54
84
|
|
|
55
|
-
const SVG_DANGER_RE = /<(?:script|foreignObject)\b|\bon\w+\s
|
|
85
|
+
const SVG_DANGER_RE = /<(?:script|foreignObject)\b|\bon\w+\s*=|javascript:|<\!ENTITY|<\!DOCTYPE|@import/i;
|
|
56
86
|
|
|
57
87
|
/**
|
|
58
88
|
* Validates pre-flight buffer integrity.
|
|
@@ -79,16 +109,44 @@ function validateImageBytes(input) {
|
|
|
79
109
|
}
|
|
80
110
|
}
|
|
81
111
|
|
|
112
|
+
function stripCssComments(text) {
|
|
113
|
+
let result = '';
|
|
114
|
+
let i = 0;
|
|
115
|
+
while (i < text.length) {
|
|
116
|
+
if (text[i] === '/' && text[i + 1] === '*') {
|
|
117
|
+
const end = text.indexOf('*/', i + 2);
|
|
118
|
+
if (end === -1) {
|
|
119
|
+
return result;
|
|
120
|
+
}
|
|
121
|
+
i = end + 2;
|
|
122
|
+
} else {
|
|
123
|
+
result += text[i];
|
|
124
|
+
i++;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
return result;
|
|
128
|
+
}
|
|
129
|
+
|
|
82
130
|
function asBuffer(input) {
|
|
83
131
|
if (Buffer.isBuffer(input)) return input;
|
|
84
132
|
if (input instanceof Uint8Array) return Buffer.from(input.buffer, input.byteOffset, input.byteLength);
|
|
85
133
|
if (typeof input === 'string') return Buffer.from(input, 'utf8');
|
|
86
|
-
throw new
|
|
134
|
+
throw new ZapwebpError({
|
|
135
|
+
code: 'E_INVALID_CONFIG',
|
|
136
|
+
message: 'Image input must be a string, Buffer, or Uint8Array.',
|
|
137
|
+
fix: 'Provide a valid image buffer or file content.',
|
|
138
|
+
});
|
|
87
139
|
}
|
|
88
140
|
|
|
89
141
|
function detectFormat(input) {
|
|
90
142
|
const data = asBuffer(input);
|
|
91
|
-
if (!data.length)
|
|
143
|
+
if (!data.length) {
|
|
144
|
+
throw new ZapwebpError({
|
|
145
|
+
code: 'E_EMPTY_FILE',
|
|
146
|
+
message: 'File is empty (0 bytes).',
|
|
147
|
+
fix: 'Ensure the file has non-zero size before converting.',
|
|
148
|
+
});
|
|
149
|
+
}
|
|
92
150
|
const registered = formats.detectFormatHandler(data);
|
|
93
151
|
if (registered) return registered.name;
|
|
94
152
|
if (data.length >= 8 && data.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))) return 'png';
|
|
@@ -105,21 +163,74 @@ function detectFormat(input) {
|
|
|
105
163
|
|| data.subarray(0, 4).equals(Buffer.from([0x49, 0x49, 0x2b, 0x00]))
|
|
106
164
|
|| data.subarray(0, 4).equals(Buffer.from([0x4d, 0x4d, 0x00, 0x2b]))
|
|
107
165
|
)) return 'tiff';
|
|
108
|
-
if (data.length >= 2 && data.subarray(0, 2).toString('ascii') === 'BM')
|
|
109
|
-
|
|
166
|
+
if (data.length >= 2 && data.subarray(0, 2).toString('ascii') === 'BM') {
|
|
167
|
+
throw new ZapwebpError({
|
|
168
|
+
code: 'E_UNSUPPORTED_FORMAT',
|
|
169
|
+
message: 'BMP input is not supported yet.',
|
|
170
|
+
fix: 'Convert BMP to PNG or JPEG first, or install a BMP format plugin.',
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
if (data.length >= 4 && data[0] === 0 && data[1] === 0 && data[2] === 1 && data[3] === 0) {
|
|
174
|
+
throw new ZapwebpError({
|
|
175
|
+
code: 'E_UNSUPPORTED_FORMAT',
|
|
176
|
+
message: 'ICO input is not supported yet.',
|
|
177
|
+
fix: 'Convert ICO to PNG first, or install an ICO format plugin.',
|
|
178
|
+
});
|
|
179
|
+
}
|
|
110
180
|
const text = data.subarray(0, Math.min(data.length, 4096)).toString('utf8').replace(/^\uFEFF/, '').trimStart();
|
|
111
181
|
if (/<svg(?:\s|\/?>)/i.test(text) || /^<\?xml[\s\S]*?<svg(?:\s|\/?>)/i.test(text)) return 'svg';
|
|
112
|
-
throw new
|
|
182
|
+
throw new ZapwebpError({
|
|
183
|
+
code: 'E_UNSUPPORTED_FORMAT',
|
|
184
|
+
message: 'Unsupported or unrecognized image format. Supported inputs: SVG, PNG, JPEG, WebP, AVIF, GIF, and TIFF.',
|
|
185
|
+
fix: 'Supply an image in a supported format, or register a custom format handler.',
|
|
186
|
+
});
|
|
113
187
|
}
|
|
114
188
|
|
|
115
189
|
function validateSvg(input) {
|
|
116
190
|
const svg = Buffer.isBuffer(input) ? input.toString('utf8') : String(input);
|
|
117
|
-
if (Buffer.byteLength(svg) === 0 || !/<svg(?:\s|\/?>)/i.test(svg))
|
|
191
|
+
if (Buffer.byteLength(svg) === 0 || !/<svg(?:\s|\/?>)/i.test(svg)) {
|
|
192
|
+
throw new ZapwebpError({
|
|
193
|
+
code: 'E_CORRUPT_HEADER',
|
|
194
|
+
message: 'This file does not contain a valid SVG document.',
|
|
195
|
+
fix: 'Verify the file begins with an <svg> tag and is well-formed XML.',
|
|
196
|
+
});
|
|
197
|
+
}
|
|
118
198
|
if (SVG_DANGER_RE.test(svg)) {
|
|
119
|
-
if (/<(?:script|foreignObject)\b/i.test(svg) || /\bon\w+\s*=/i.test(svg))
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
199
|
+
if (/<(?:script|foreignObject)\b/i.test(svg) || /\bon\w+\s*=/i.test(svg)) {
|
|
200
|
+
throw new ZapwebpError({
|
|
201
|
+
code: 'E_UNSAFE_SVG',
|
|
202
|
+
message: 'This SVG contains active content and cannot be converted.',
|
|
203
|
+
fix: 'Remove <script>, inline on* handlers, or foreignObject tags before converting.',
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
if (/javascript:/i.test(svg)) {
|
|
207
|
+
throw new ZapwebpError({
|
|
208
|
+
code: 'E_UNSAFE_SVG',
|
|
209
|
+
message: 'This SVG contains active content and cannot be converted.',
|
|
210
|
+
fix: 'Remove javascript: URI schemes and active content before converting.',
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
if (/<!ENTITY\b/i.test(svg)) {
|
|
214
|
+
throw new ZapwebpError({
|
|
215
|
+
code: 'E_UNSAFE_SVG',
|
|
216
|
+
message: 'Custom XML entities are not supported.',
|
|
217
|
+
fix: 'Remove <!ENTITY> declarations from the SVG markup.',
|
|
218
|
+
});
|
|
219
|
+
}
|
|
220
|
+
if (/<!DOCTYPE\b/i.test(svg)) {
|
|
221
|
+
throw new ZapwebpError({
|
|
222
|
+
code: 'E_UNSAFE_SVG',
|
|
223
|
+
message: 'DOCTYPE declarations are not supported.',
|
|
224
|
+
fix: 'Remove <!DOCTYPE> declarations from the SVG markup.',
|
|
225
|
+
});
|
|
226
|
+
}
|
|
227
|
+
if (/@import\b/i.test(svg)) {
|
|
228
|
+
throw new ZapwebpError({
|
|
229
|
+
code: 'E_UNSAFE_SVG',
|
|
230
|
+
message: 'External stylesheet imports are not supported.',
|
|
231
|
+
fix: 'Embed all styles inline within <style> elements without @import.',
|
|
232
|
+
});
|
|
233
|
+
}
|
|
123
234
|
}
|
|
124
235
|
let decoded;
|
|
125
236
|
try {
|
|
@@ -127,19 +238,53 @@ function validateSvg(input) {
|
|
|
127
238
|
.replace(/&#x([\da-f]+);/gi, (_match, code) => String.fromCodePoint(Number.parseInt(code, 16)))
|
|
128
239
|
.replace(/&#(\d+);/g, (_match, code) => String.fromCodePoint(Number(code)))
|
|
129
240
|
.replace(/&/gi, '&');
|
|
130
|
-
} catch {
|
|
241
|
+
} catch {
|
|
242
|
+
throw new ZapwebpError({
|
|
243
|
+
code: 'E_UNSAFE_SVG',
|
|
244
|
+
message: 'This SVG contains an invalid character reference.',
|
|
245
|
+
fix: 'Fix or remove corrupt character entity references.',
|
|
246
|
+
});
|
|
247
|
+
}
|
|
131
248
|
let normalized;
|
|
132
249
|
try {
|
|
133
|
-
normalized = decoded
|
|
134
|
-
} catch {
|
|
250
|
+
normalized = stripCssComments(decoded).replace(/\\([\da-f]{1,6})\s?/gi, (_match, code) => String.fromCodePoint(Number.parseInt(code, 16)));
|
|
251
|
+
} catch {
|
|
252
|
+
throw new ZapwebpError({
|
|
253
|
+
code: 'E_UNSAFE_SVG',
|
|
254
|
+
message: 'This SVG contains an invalid CSS escape.',
|
|
255
|
+
fix: 'Fix or remove invalid CSS escape sequences.',
|
|
256
|
+
});
|
|
257
|
+
}
|
|
135
258
|
const safeReference = (value) => {
|
|
136
259
|
const ref = value.trim().replace(/^("|')([\s\S]*)\1$/, '$2').trim();
|
|
137
260
|
return ref.startsWith('#') || /^data:image\/(?:png|jpe?g|gif|webp);base64,[a-z\d+/=]+$/i.test(ref) || /^data:font\/(?:woff2?|ttf|otf);base64,[a-z\d+/=]+$/i.test(ref);
|
|
138
261
|
};
|
|
139
262
|
const attributeRefs = /(?:href|src)\s*=\s*(["'])(.*?)\1/gi;
|
|
140
|
-
for (const match of normalized.matchAll(attributeRefs))
|
|
141
|
-
|
|
142
|
-
|
|
263
|
+
for (const match of normalized.matchAll(attributeRefs)) {
|
|
264
|
+
if (!safeReference(match[2])) {
|
|
265
|
+
throw new ZapwebpError({
|
|
266
|
+
code: 'E_UNSAFE_SVG',
|
|
267
|
+
message: 'External references are not supported. Embed raster images and fonts in the SVG first.',
|
|
268
|
+
fix: 'Embed all external image and font references as inline data URIs.',
|
|
269
|
+
});
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
if (/@import\b/i.test(normalized)) {
|
|
273
|
+
throw new ZapwebpError({
|
|
274
|
+
code: 'E_UNSAFE_SVG',
|
|
275
|
+
message: 'External stylesheet imports are not supported.',
|
|
276
|
+
fix: 'Embed all styles inline within <style> elements without @import.',
|
|
277
|
+
});
|
|
278
|
+
}
|
|
279
|
+
for (const match of normalized.matchAll(/url\(\s*([^)]*?)\s*\)/gi)) {
|
|
280
|
+
if (!safeReference(match[1])) {
|
|
281
|
+
throw new ZapwebpError({
|
|
282
|
+
code: 'E_UNSAFE_SVG',
|
|
283
|
+
message: 'External references are not supported. Embed images and fonts in the SVG first.',
|
|
284
|
+
fix: 'Embed all external image and font references as inline data URIs.',
|
|
285
|
+
});
|
|
286
|
+
}
|
|
287
|
+
}
|
|
143
288
|
return svg;
|
|
144
289
|
}
|
|
145
290
|
|
|
@@ -162,16 +307,35 @@ function svgDimensions(svg) {
|
|
|
162
307
|
const root = svg.match(/<svg\b[^>]*>/i)?.[0] || '';
|
|
163
308
|
const attribute = (name) => root.match(new RegExp(`(?:^|\\s)${name}\\s*=\\s*(["'])(.*?)\\1`, 'i'))?.[2];
|
|
164
309
|
const viewBox = attribute('viewBox');
|
|
310
|
+
let width;
|
|
311
|
+
let height;
|
|
165
312
|
if (viewBox) {
|
|
166
313
|
const values = viewBox.trim().split(/[\s,]+/).map(Number);
|
|
167
|
-
if (values.length === 4 && values.every(Number.isFinite) && values[2] > 0 && values[3] > 0)
|
|
314
|
+
if (values.length === 4 && values.every(Number.isFinite) && values[2] > 0 && values[3] > 0) {
|
|
315
|
+
width = values[2];
|
|
316
|
+
height = values[3];
|
|
317
|
+
}
|
|
168
318
|
}
|
|
169
319
|
const dimension = (name) => {
|
|
170
320
|
const value = attribute(name);
|
|
171
321
|
const match = value?.trim().match(/^([+]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?)(?:px)?$/i);
|
|
172
322
|
return match ? Number(match[1]) : undefined;
|
|
173
323
|
};
|
|
174
|
-
|
|
324
|
+
if (width === undefined) width = dimension('width');
|
|
325
|
+
if (height === undefined) height = dimension('height');
|
|
326
|
+
|
|
327
|
+
if (width !== undefined && height !== undefined && width > 0 && height > 0) {
|
|
328
|
+
const aspect = height / width;
|
|
329
|
+
if (aspect < 0.01 || aspect > 100 || width < 0.01 || height < 0.01) {
|
|
330
|
+
throw new ZapwebpError({
|
|
331
|
+
code: 'E_EXTREME_ASPECT_RATIO',
|
|
332
|
+
message: `SVG aspect ratio is extreme (${aspect.toFixed(4)}:1) or dimensions are sub-pixel (${width}x${height}).`,
|
|
333
|
+
fix: 'Check the SVG dimensions. Aspect ratio must be between 0.01:1 and 100:1.',
|
|
334
|
+
});
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
return { width, height };
|
|
175
339
|
}
|
|
176
340
|
|
|
177
341
|
/**
|
|
@@ -341,8 +505,12 @@ async function verifyAlpha(input) {
|
|
|
341
505
|
* @returns {{ safe: boolean, issues: string[], recommendedCommand: string }}
|
|
342
506
|
*/
|
|
343
507
|
function auditConversionCommand(command) {
|
|
344
|
-
if (!command || typeof command !== 'string') {
|
|
345
|
-
throw new
|
|
508
|
+
if (!command || typeof command !== 'string' || !command.trim()) {
|
|
509
|
+
throw new ZapwebpError({
|
|
510
|
+
code: 'E_INVALID_CONFIG',
|
|
511
|
+
message: 'Command must be a non-empty string.',
|
|
512
|
+
fix: 'Pass a CLI command string to audit, e.g. "convert logo.svg logo.webp".',
|
|
513
|
+
});
|
|
346
514
|
}
|
|
347
515
|
|
|
348
516
|
const issues = [];
|
|
@@ -399,7 +567,13 @@ function explainBlackBackground(context = {}) {
|
|
|
399
567
|
}
|
|
400
568
|
|
|
401
569
|
function normalizeOptions(options = {}) {
|
|
402
|
-
if (!options || typeof options !== 'object' || Array.isArray(options))
|
|
570
|
+
if (!options || typeof options !== 'object' || Array.isArray(options)) {
|
|
571
|
+
throw new ZapwebpError({
|
|
572
|
+
code: 'E_INVALID_CONFIG',
|
|
573
|
+
message: 'Conversion options must be an object.',
|
|
574
|
+
fix: 'Pass an options object, e.g. { to: "webp" }.',
|
|
575
|
+
});
|
|
576
|
+
}
|
|
403
577
|
const lockTarget = options.lockTarget || options.lock;
|
|
404
578
|
const overrideLock = Boolean(options.overrideLock);
|
|
405
579
|
const strict = options.strict !== undefined ? Boolean(options.strict) : true;
|
|
@@ -409,24 +583,78 @@ function normalizeOptions(options = {}) {
|
|
|
409
583
|
} else {
|
|
410
584
|
to = String(options.to ?? DEFAULT_OPTIONS.to).toLowerCase();
|
|
411
585
|
}
|
|
412
|
-
|
|
586
|
+
|
|
587
|
+
// Phase 1.1: Dynamically query registry for output formats
|
|
588
|
+
const outputHandlers = formats.getAllHandlers().filter((h) => h.isOutput);
|
|
589
|
+
const validTargets = outputHandlers.map((h) => h.name);
|
|
590
|
+
if (!validTargets.includes(to)) {
|
|
591
|
+
throw new ZapwebpError({
|
|
592
|
+
code: 'E_UNSUPPORTED_FORMAT',
|
|
593
|
+
message: `Unsupported output format: ${to}. Available: ${validTargets.join(', ')}.`,
|
|
594
|
+
fix: `Register a handler with registerFormat() or use one of: ${validTargets.join(', ')}.`,
|
|
595
|
+
target: to,
|
|
596
|
+
});
|
|
597
|
+
}
|
|
598
|
+
|
|
413
599
|
const quality = Number(options.quality ?? DEFAULT_OPTIONS.quality);
|
|
414
|
-
if (!Number.isInteger(quality) || quality < 0 || quality > 100)
|
|
600
|
+
if (!Number.isInteger(quality) || quality < 0 || quality > 100) {
|
|
601
|
+
throw new ZapwebpError({
|
|
602
|
+
code: 'E_INVALID_CONFIG',
|
|
603
|
+
message: 'Quality must be an integer between 0 and 100.',
|
|
604
|
+
fix: 'Specify a quality value between 0 and 100.',
|
|
605
|
+
});
|
|
606
|
+
}
|
|
415
607
|
const effort = Number(options.effort ?? DEFAULT_OPTIONS.effort);
|
|
416
|
-
if (!Number.isInteger(effort) || effort < 0 || effort > 9)
|
|
608
|
+
if (!Number.isInteger(effort) || effort < 0 || effort > 9) {
|
|
609
|
+
throw new ZapwebpError({
|
|
610
|
+
code: 'E_INVALID_CONFIG',
|
|
611
|
+
message: 'Effort must be an integer between 0 and 9.',
|
|
612
|
+
fix: 'Specify an effort value between 0 and 9.',
|
|
613
|
+
});
|
|
614
|
+
}
|
|
417
615
|
const dimension = (key) => {
|
|
418
616
|
if (options[key] === undefined) return undefined;
|
|
419
617
|
const value = Number(options[key]);
|
|
420
|
-
if (!Number.isInteger(value) || value < 1 || value > MAX_WIDTH)
|
|
618
|
+
if (!Number.isInteger(value) || value < 1 || value > MAX_WIDTH) {
|
|
619
|
+
throw new ZapwebpError({
|
|
620
|
+
code: 'E_INVALID_CONFIG',
|
|
621
|
+
message: `${key} must be an integer between 1 and ${MAX_WIDTH}.`,
|
|
622
|
+
fix: `Set ${key} between 1 and ${MAX_WIDTH}.`,
|
|
623
|
+
});
|
|
624
|
+
}
|
|
421
625
|
return value;
|
|
422
626
|
};
|
|
423
627
|
const width = dimension('width');
|
|
424
628
|
const height = dimension('height');
|
|
425
629
|
const fit = String(options.fit ?? DEFAULT_OPTIONS.fit).toLowerCase();
|
|
426
|
-
if (!FIT_MODES.includes(fit))
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
630
|
+
if (!FIT_MODES.includes(fit)) {
|
|
631
|
+
throw new ZapwebpError({
|
|
632
|
+
code: 'E_INVALID_CONFIG',
|
|
633
|
+
message: `Fit must be one of ${FIT_MODES.join(', ')}.`,
|
|
634
|
+
fix: `Specify fit as one of: ${FIT_MODES.join(', ')}.`,
|
|
635
|
+
});
|
|
636
|
+
}
|
|
637
|
+
if (options.lossless !== undefined && typeof options.lossless !== 'boolean') {
|
|
638
|
+
throw new ZapwebpError({
|
|
639
|
+
code: 'E_INVALID_CONFIG',
|
|
640
|
+
message: 'Lossless must be a boolean.',
|
|
641
|
+
fix: 'Set lossless to true or false.',
|
|
642
|
+
});
|
|
643
|
+
}
|
|
644
|
+
if (options.stripMetadata !== undefined && typeof options.stripMetadata !== 'boolean') {
|
|
645
|
+
throw new ZapwebpError({
|
|
646
|
+
code: 'E_INVALID_CONFIG',
|
|
647
|
+
message: 'stripMetadata must be a boolean.',
|
|
648
|
+
fix: 'Set stripMetadata to true or false.',
|
|
649
|
+
});
|
|
650
|
+
}
|
|
651
|
+
if (options.clean !== undefined && typeof options.clean !== 'boolean') {
|
|
652
|
+
throw new ZapwebpError({
|
|
653
|
+
code: 'E_INVALID_CONFIG',
|
|
654
|
+
message: 'clean must be a boolean.',
|
|
655
|
+
fix: 'Set clean to true or false.',
|
|
656
|
+
});
|
|
657
|
+
}
|
|
430
658
|
const clean = options.clean !== undefined ? Boolean(options.clean) : (options.stripMetadata ?? DEFAULT_OPTIONS.clean);
|
|
431
659
|
const stripMetadata = clean;
|
|
432
660
|
const verify = Boolean(options.verify || options.verifyClean);
|
|
@@ -435,7 +663,39 @@ function normalizeOptions(options = {}) {
|
|
|
435
663
|
const transforms = Array.isArray(options.transforms)
|
|
436
664
|
? options.transforms.filter((t) => t && typeof t.apply === 'function')
|
|
437
665
|
: undefined;
|
|
438
|
-
for (const key of ['background', 'svgBackground'])
|
|
666
|
+
for (const key of ['background', 'svgBackground']) {
|
|
667
|
+
if (options[key] !== undefined && (typeof options[key] !== 'string' || !options[key].trim() || options[key].length > 64)) {
|
|
668
|
+
throw new ZapwebpError({
|
|
669
|
+
code: 'E_INVALID_CONFIG',
|
|
670
|
+
message: `${key} must be a non-empty color string of 64 characters or fewer.`,
|
|
671
|
+
fix: 'Supply a valid CSS color string like "#ffffff" or "rgba(0,0,0,0)".',
|
|
672
|
+
});
|
|
673
|
+
}
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
const parseTargetBytesHelper = (val) => {
|
|
677
|
+
if (typeof val === 'number') return val > 0 ? Math.round(val) : undefined;
|
|
678
|
+
if (typeof val === 'string') {
|
|
679
|
+
const match = val.trim().match(/^([0-9]+(?:\.[0-9]+)?)\s*([a-zA-Z]*)$/);
|
|
680
|
+
if (!match) return undefined;
|
|
681
|
+
const num = Number.parseFloat(match[1]);
|
|
682
|
+
const unit = match[2].toLowerCase();
|
|
683
|
+
let mult = 1;
|
|
684
|
+
if (unit === 'k' || unit === 'kb' || unit === 'kib') mult = 1024;
|
|
685
|
+
else if (unit === 'm' || unit === 'mb' || unit === 'mib') mult = 1024 * 1024;
|
|
686
|
+
else if (unit === 'g' || unit === 'gb' || unit === 'gib') mult = 1024 * 1024 * 1024;
|
|
687
|
+
const res = Math.round(num * mult);
|
|
688
|
+
return res > 0 ? res : undefined;
|
|
689
|
+
}
|
|
690
|
+
return undefined;
|
|
691
|
+
};
|
|
692
|
+
|
|
693
|
+
const targetBytes = options.targetBytes !== undefined
|
|
694
|
+
? parseTargetBytesHelper(options.targetBytes)
|
|
695
|
+
: (options.targetOutputBytes !== undefined
|
|
696
|
+
? parseTargetBytesHelper(options.targetOutputBytes)
|
|
697
|
+
: (options.target !== undefined ? parseTargetBytesHelper(options.target) : undefined));
|
|
698
|
+
|
|
439
699
|
return {
|
|
440
700
|
to,
|
|
441
701
|
width,
|
|
@@ -452,20 +712,39 @@ function normalizeOptions(options = {}) {
|
|
|
452
712
|
assertAlpha,
|
|
453
713
|
report,
|
|
454
714
|
transforms,
|
|
715
|
+
targetBytes,
|
|
716
|
+
minQuality: options.minQuality !== undefined ? Number(options.minQuality) : undefined,
|
|
717
|
+
allowDownscale: options.allowDownscale !== undefined ? Boolean(options.allowDownscale) : undefined,
|
|
718
|
+
downscaleStep: options.downscaleStep !== undefined ? Number(options.downscaleStep) : undefined,
|
|
719
|
+
maxDownscaleAttempts: options.maxDownscaleAttempts !== undefined ? Number(options.maxDownscaleAttempts) : undefined,
|
|
720
|
+
compressor: options.compressor,
|
|
455
721
|
lockTarget,
|
|
456
722
|
strict,
|
|
457
723
|
overrideLock,
|
|
458
724
|
policy: options.policy,
|
|
459
|
-
|
|
460
|
-
|
|
725
|
+
sameFormat: options.sameFormat || (options.policy?.formats?.sameFormat) || DEFAULT_OPTIONS.sameFormat || 'passthrough',
|
|
726
|
+
sizeMode: options.sizeMode || (options.policy?.size?.mode) || (options.strict ? 'strict' : undefined) || DEFAULT_OPTIONS.sizeMode || 'compress',
|
|
727
|
+
minInputBytes: options.minInputBytes !== undefined ? Number(options.minInputBytes) : (options.policy?.limits?.minInputBytes),
|
|
728
|
+
minOutputBytes: options.minOutputBytes !== undefined ? Number(options.minOutputBytes) : (options.policy?.limits?.minOutputBytes),
|
|
729
|
+
maxOutputBytes: options.maxOutputBytes !== undefined ? Number(options.maxOutputBytes) : (options.policy?.limits?.maxOutputBytes),
|
|
730
|
+
targetOutputBytes: targetBytes || options.targetOutputBytes,
|
|
461
731
|
accept: options.accept,
|
|
462
732
|
reject: options.reject,
|
|
733
|
+
smart: Boolean(options.smart),
|
|
734
|
+
keepOriginal: options.keepOriginal !== undefined ? Boolean(options.keepOriginal) : (DEFAULT_OPTIONS.keepOriginal ?? true),
|
|
735
|
+
cleanupDelay: ['immediate', 'session', 'manual'].includes(String(options.cleanupDelay).toLowerCase())
|
|
736
|
+
? String(options.cleanupDelay).toLowerCase()
|
|
737
|
+
: (DEFAULT_OPTIONS.cleanupDelay || 'immediate'),
|
|
463
738
|
};
|
|
464
739
|
}
|
|
465
740
|
|
|
466
741
|
function checkDimensions(width, height) {
|
|
467
742
|
if (!Number.isFinite(width) || !Number.isFinite(height) || width < 1 || height < 1 || width > MAX_WIDTH || height > MAX_WIDTH || width * height > MAX_PIXELS) {
|
|
468
|
-
throw new
|
|
743
|
+
throw new ZapwebpError({
|
|
744
|
+
code: 'E_TOO_LARGE',
|
|
745
|
+
message: `Image dimensions (${width}x${height}) exceed the ${MAX_WIDTH} px side or ${MAX_PIXELS} pixel-count limit.`,
|
|
746
|
+
fix: `Downscale image dimensions to within ${MAX_WIDTH}x${MAX_WIDTH}.`,
|
|
747
|
+
});
|
|
469
748
|
}
|
|
470
749
|
}
|
|
471
750
|
|
|
@@ -473,18 +752,69 @@ async function inspectImage(input) {
|
|
|
473
752
|
const data = asBuffer(input);
|
|
474
753
|
const format = detectFormat(data);
|
|
475
754
|
const metadata = detectMetadata(data);
|
|
755
|
+
const custom = extractCustomMetadata(data, format);
|
|
756
|
+
if (custom) {
|
|
757
|
+
metadata.custom = custom;
|
|
758
|
+
metadata.hasMetadata = true;
|
|
759
|
+
if (!metadata.summary.includes('Zapwebp Custom Metadata')) {
|
|
760
|
+
metadata.summary.push('Zapwebp Custom Metadata');
|
|
761
|
+
}
|
|
762
|
+
}
|
|
763
|
+
|
|
764
|
+
let width;
|
|
765
|
+
let height;
|
|
766
|
+
let hasAlpha;
|
|
767
|
+
|
|
476
768
|
if (format === 'svg') {
|
|
477
769
|
const svg = validateSvg(data);
|
|
478
|
-
const
|
|
479
|
-
|
|
480
|
-
|
|
770
|
+
const dims = svgDimensions(svg);
|
|
771
|
+
width = dims.width || undefined;
|
|
772
|
+
height = dims.height || undefined;
|
|
773
|
+
hasAlpha = true;
|
|
774
|
+
if (width && height && (!Number.isFinite(width) || !Number.isFinite(height) || width <= 0 || height <= 0)) {
|
|
775
|
+
throw new ZapwebpError({
|
|
776
|
+
code: 'E_INVALID_CONFIG',
|
|
777
|
+
message: 'The SVG has invalid intrinsic dimensions.',
|
|
778
|
+
fix: 'Verify SVG width, height, or viewBox attributes are positive finite numbers.',
|
|
779
|
+
});
|
|
780
|
+
}
|
|
781
|
+
} else {
|
|
782
|
+
const meta = await getSharp()(data, { limitInputPixels: MAX_PIXELS, pages: 1, animated: false, failOn: 'error' }).metadata();
|
|
783
|
+
checkDimensions(meta.width, meta.height);
|
|
784
|
+
width = meta.width;
|
|
785
|
+
height = meta.height;
|
|
786
|
+
hasAlpha = Boolean(meta.hasAlpha);
|
|
481
787
|
}
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
788
|
+
|
|
789
|
+
const { content, palette } = await computeContentSignals(data, { format, width, height, hasAlpha }, getSharp);
|
|
790
|
+
const smart = await analyzeSmart(data, { format, width, height, hasAlpha }, getSharp);
|
|
791
|
+
const suggestions = suggest({
|
|
792
|
+
format,
|
|
793
|
+
width,
|
|
794
|
+
height,
|
|
795
|
+
bytes: data.length,
|
|
796
|
+
hasAlpha,
|
|
797
|
+
metadata,
|
|
798
|
+
content,
|
|
799
|
+
palette,
|
|
800
|
+
});
|
|
801
|
+
|
|
802
|
+
return {
|
|
803
|
+
format,
|
|
804
|
+
width,
|
|
805
|
+
height,
|
|
806
|
+
hasAlpha,
|
|
807
|
+
bytes: data.length,
|
|
808
|
+
metadata,
|
|
809
|
+
content,
|
|
810
|
+
palette,
|
|
811
|
+
suggestions,
|
|
812
|
+
smart,
|
|
813
|
+
};
|
|
485
814
|
}
|
|
486
815
|
|
|
487
816
|
async function convertImage(input, options = {}) {
|
|
817
|
+
assertRuntimeIsolation();
|
|
488
818
|
const opts = normalizeOptions(options);
|
|
489
819
|
const policy = resolvePolicy(opts.policy, opts);
|
|
490
820
|
const data = asBuffer(input);
|
|
@@ -505,6 +835,38 @@ async function convertImage(input, options = {}) {
|
|
|
505
835
|
}
|
|
506
836
|
|
|
507
837
|
validateImageBytes(data);
|
|
838
|
+
|
|
839
|
+
let smartResult = null;
|
|
840
|
+
if (options.smart) {
|
|
841
|
+
try {
|
|
842
|
+
const detectedFmt = detectFormat(data);
|
|
843
|
+
smartResult = await analyzeSmart(data, { format: detectedFmt }, getSharp);
|
|
844
|
+
if (!options.to && !opts.lockTarget && smartResult.recommendation?.format) {
|
|
845
|
+
opts.to = smartResult.recommendation.format;
|
|
846
|
+
}
|
|
847
|
+
if (options.quality === undefined && smartResult.recommendation?.quality) {
|
|
848
|
+
opts.quality = smartResult.recommendation.quality;
|
|
849
|
+
}
|
|
850
|
+
if (options.lossless === undefined && smartResult.recommendation?.lossless !== undefined) {
|
|
851
|
+
opts.lossless = smartResult.recommendation.lossless;
|
|
852
|
+
}
|
|
853
|
+
} catch {}
|
|
854
|
+
}
|
|
855
|
+
|
|
856
|
+
const useCache = Boolean(opts.cache);
|
|
857
|
+
const cacheKey = useCache ? computeCacheKey(data, opts) : null;
|
|
858
|
+
if (useCache && cacheKey) {
|
|
859
|
+
const cached = defaultCache.get(cacheKey);
|
|
860
|
+
if (cached) return cached;
|
|
861
|
+
}
|
|
862
|
+
|
|
863
|
+
const finish = (result) => {
|
|
864
|
+
if (useCache && cacheKey) {
|
|
865
|
+
defaultCache.set(cacheKey, result);
|
|
866
|
+
}
|
|
867
|
+
return result;
|
|
868
|
+
};
|
|
869
|
+
|
|
508
870
|
let format;
|
|
509
871
|
try {
|
|
510
872
|
format = detectFormat(data);
|
|
@@ -543,16 +905,153 @@ async function convertImage(input, options = {}) {
|
|
|
543
905
|
// Policy check 2: Format allowlist & denylist based on detected bytes
|
|
544
906
|
checkPolicyInput({ policy, data, detectedFormat: format });
|
|
545
907
|
|
|
908
|
+
// Stage 2: Format Lock Decision & Smart Ingestion
|
|
909
|
+
const normalizedFormat = (format || '').toLowerCase() === 'jpg' ? 'jpeg' : (format || '').toLowerCase();
|
|
910
|
+
const normalizedTarget = (opts.to || '').toLowerCase() === 'jpg' ? 'jpeg' : (opts.to || '').toLowerCase();
|
|
911
|
+
const isSameFormat = (normalizedFormat === normalizedTarget);
|
|
912
|
+
const sameFormatAction = opts.sameFormat || policy.formats?.sameFormat || 'passthrough';
|
|
913
|
+
|
|
914
|
+
if (isSameFormat && sameFormatAction === 'reject') {
|
|
915
|
+
throw new ZapwebpError({
|
|
916
|
+
code: 'E_SAME_FORMAT_REJECTED',
|
|
917
|
+
message: `Input format (${format}) matches target lock format (${opts.to}) and same-format uploads are rejected by policy.`,
|
|
918
|
+
fix: 'Change sameFormat policy to "passthrough" or "reencode", or provide a different input format.',
|
|
919
|
+
detectedFormat: format,
|
|
920
|
+
targetFormat: opts.to,
|
|
921
|
+
suggestedFix: {
|
|
922
|
+
sameFormat: 'passthrough',
|
|
923
|
+
reason: 'Allow same-format pass-through without conversion.',
|
|
924
|
+
},
|
|
925
|
+
});
|
|
926
|
+
}
|
|
927
|
+
|
|
928
|
+
const limitMaxOutput = policy.limits?.maxOutputBytes || policy.limits?.targetOutputBytes || opts.targetBytes;
|
|
929
|
+
const limitMinOutput = policy.limits?.minOutputBytes;
|
|
930
|
+
const sizeMode = policy.size?.mode || opts.sizeMode || 'compress';
|
|
931
|
+
const warnings = [];
|
|
932
|
+
|
|
933
|
+
// Fast-Path: Can we pass through without decode & re-encode?
|
|
934
|
+
const canPassthrough = isSameFormat &&
|
|
935
|
+
sameFormatAction === 'passthrough' &&
|
|
936
|
+
!opts.width &&
|
|
937
|
+
!opts.height &&
|
|
938
|
+
(!opts.transforms || opts.transforms.length === 0) &&
|
|
939
|
+
(!opts.background || normalizedTarget !== 'jpeg') &&
|
|
940
|
+
(!limitMaxOutput || data.length <= limitMaxOutput) &&
|
|
941
|
+
(!limitMinOutput || data.length >= limitMinOutput);
|
|
942
|
+
|
|
943
|
+
if (canPassthrough) {
|
|
944
|
+
let meta;
|
|
945
|
+
if (format === 'svg') {
|
|
946
|
+
const svg = validateSvg(data);
|
|
947
|
+
const dims = svgDimensions(svg);
|
|
948
|
+
meta = { width: dims.width, height: dims.height, hasAlpha: true };
|
|
949
|
+
} else {
|
|
950
|
+
meta = await getSharp()(data, { limitInputPixels: MAX_PIXELS, pages: 1, animated: false, failOn: 'error' }).metadata();
|
|
951
|
+
}
|
|
952
|
+
const hasAlpha = Boolean(meta.hasAlpha);
|
|
953
|
+
const alphaPreserved = normalizedTarget !== 'jpeg' && hasAlpha;
|
|
954
|
+
const backgroundStatus = hasAlpha ? 'preserved_alpha' : 'preserved_opaque';
|
|
955
|
+
const transparency = hasAlpha ? 'preserved' : 'preserved_opaque';
|
|
956
|
+
|
|
957
|
+
return finish({
|
|
958
|
+
data,
|
|
959
|
+
format: normalizedTarget,
|
|
960
|
+
width: meta.width,
|
|
961
|
+
height: meta.height,
|
|
962
|
+
size: data.length,
|
|
963
|
+
alphaPreserved,
|
|
964
|
+
alphaVerified: alphaPreserved,
|
|
965
|
+
backgroundStatus,
|
|
966
|
+
transparency,
|
|
967
|
+
flattenColor: opts.background || undefined,
|
|
968
|
+
clean: Boolean(policy.advanced.stripMetadata),
|
|
969
|
+
qualityReducedBy: 0,
|
|
970
|
+
maxOutputHit: false,
|
|
971
|
+
quality: 100,
|
|
972
|
+
passedThrough: true,
|
|
973
|
+
ingestion: {
|
|
974
|
+
stage: 'passthrough',
|
|
975
|
+
action: 'same_format_passthrough',
|
|
976
|
+
detectedFormat: format,
|
|
977
|
+
targetFormat: opts.to,
|
|
978
|
+
sizeMode,
|
|
979
|
+
inputBytes: data.length,
|
|
980
|
+
outputBytes: data.length,
|
|
981
|
+
iterations: 0,
|
|
982
|
+
reason: 'Input matches target format and satisfies all size bounds with zero generational loss.',
|
|
983
|
+
},
|
|
984
|
+
warnings: [],
|
|
985
|
+
removedMetadata: [],
|
|
986
|
+
targetLockEnforced: Boolean(opts.lockTarget && !opts.overrideLock),
|
|
987
|
+
targetLockBypassed: Boolean(opts.lockTarget && opts.overrideLock),
|
|
988
|
+
sourceStatus: opts.keepOriginal ? 'kept' : 'deleted',
|
|
989
|
+
lifecycle: {
|
|
990
|
+
keepOriginal: opts.keepOriginal,
|
|
991
|
+
cleanupDelay: opts.cleanupDelay,
|
|
992
|
+
sourceStatus: opts.keepOriginal ? 'kept' : 'deleted',
|
|
993
|
+
undoEligible: !opts.keepOriginal,
|
|
994
|
+
},
|
|
995
|
+
});
|
|
996
|
+
}
|
|
997
|
+
|
|
546
998
|
let source = data;
|
|
547
999
|
let sourceHasAlpha;
|
|
548
|
-
|
|
1000
|
+
const isCustomInput = !['svg', 'png', 'jpeg', 'webp', 'avif', 'gif', 'tiff'].includes(format);
|
|
1001
|
+
const transformReports = [];
|
|
1002
|
+
let rawBufferInfo = null;
|
|
1003
|
+
|
|
1004
|
+
if (isCustomInput) {
|
|
1005
|
+
const decoder = formats.getHandlerByName(format);
|
|
1006
|
+
if (!decoder || !decoder.isInput) {
|
|
1007
|
+
throw new ZapwebpError({
|
|
1008
|
+
code: 'E_UNSUPPORTED_FORMAT',
|
|
1009
|
+
message: `No decoder registered for input format "${format}".`,
|
|
1010
|
+
fix: 'Install a format plugin or register a handler with registerFormat().',
|
|
1011
|
+
});
|
|
1012
|
+
}
|
|
1013
|
+
const decoded = await decoder.decode(data, opts);
|
|
1014
|
+
if (!decoded || !decoded.data || !Number.isInteger(decoded.width) || !Number.isInteger(decoded.height)) {
|
|
1015
|
+
throw new ZapwebpError({
|
|
1016
|
+
code: 'E_CORRUPT_HEADER',
|
|
1017
|
+
message: `Custom decoder for "${format}" returned an invalid RawImage.`,
|
|
1018
|
+
fix: 'Ensure the custom format decoder returns { data, width, height } with non-empty pixel bytes.',
|
|
1019
|
+
});
|
|
1020
|
+
}
|
|
1021
|
+
checkDimensions(decoded.width, decoded.height);
|
|
1022
|
+
let hasAlpha = Boolean(decoded.hasAlpha);
|
|
1023
|
+
if (decoded.hasAlpha === undefined) {
|
|
1024
|
+
for (let i = 3; i < decoded.data.length; i += 4) {
|
|
1025
|
+
if (decoded.data[i] < 255) {
|
|
1026
|
+
hasAlpha = true;
|
|
1027
|
+
break;
|
|
1028
|
+
}
|
|
1029
|
+
}
|
|
1030
|
+
}
|
|
1031
|
+
sourceHasAlpha = hasAlpha;
|
|
1032
|
+
const rawBuffer = Buffer.isBuffer(decoded.data)
|
|
1033
|
+
? decoded.data
|
|
1034
|
+
: Buffer.from(decoded.data.buffer, decoded.data.byteOffset, decoded.data.byteLength);
|
|
1035
|
+
rawBufferInfo = {
|
|
1036
|
+
buffer: rawBuffer,
|
|
1037
|
+
rawOptions: {
|
|
1038
|
+
width: decoded.width,
|
|
1039
|
+
height: decoded.height,
|
|
1040
|
+
channels: 4,
|
|
1041
|
+
},
|
|
1042
|
+
};
|
|
1043
|
+
} else if (format === 'svg') {
|
|
549
1044
|
const svg = validateSvg(data);
|
|
550
1045
|
const dims = svgDimensions(svg);
|
|
551
1046
|
const aspect = dims.width && dims.height ? dims.height / dims.width : 1;
|
|
552
1047
|
const fitByCover = opts.fit === 'cover' || opts.fit === 'outside';
|
|
553
1048
|
const renderMode = opts.width && opts.height
|
|
554
1049
|
? (fitByCover === (aspect > opts.height / opts.width) ? 'width' : 'height')
|
|
555
|
-
: opts.height && !opts.width
|
|
1050
|
+
: opts.height && !opts.width
|
|
1051
|
+
? 'height'
|
|
1052
|
+
: (!opts.width && !opts.height && aspect > 1)
|
|
1053
|
+
? 'height'
|
|
1054
|
+
: 'width';
|
|
556
1055
|
const renderValue = renderMode === 'height' ? (opts.height ?? opts.width ?? 2048) : (opts.width ?? opts.height ?? 2048);
|
|
557
1056
|
const rasterWidth = renderMode === 'width' ? renderValue : Math.ceil(renderValue / aspect);
|
|
558
1057
|
const rasterHeight = renderMode === 'height' ? renderValue : Math.ceil(renderValue * aspect);
|
|
@@ -569,17 +1068,28 @@ async function convertImage(input, options = {}) {
|
|
|
569
1068
|
sourceHasAlpha = Boolean(meta.hasAlpha);
|
|
570
1069
|
}
|
|
571
1070
|
|
|
572
|
-
const transformReports = [];
|
|
573
|
-
let rawBufferInfo = null;
|
|
574
|
-
|
|
575
1071
|
if (opts.transforms && opts.transforms.length > 0) {
|
|
576
|
-
let raw
|
|
1072
|
+
let raw;
|
|
1073
|
+
if (rawBufferInfo) {
|
|
1074
|
+
raw = {
|
|
1075
|
+
data: rawBufferInfo.buffer,
|
|
1076
|
+
width: rawBufferInfo.rawOptions.width,
|
|
1077
|
+
height: rawBufferInfo.rawOptions.height,
|
|
1078
|
+
};
|
|
1079
|
+
} else {
|
|
1080
|
+
raw = await decodeToRgba(source, format === 'svg' ? 'png' : format);
|
|
1081
|
+
}
|
|
1082
|
+
|
|
577
1083
|
for (const step of opts.transforms) {
|
|
578
1084
|
if (typeof step.apply === 'function') {
|
|
579
1085
|
const inputDims = { width: raw.width, height: raw.height };
|
|
580
1086
|
const transformed = await step.apply(raw, opts);
|
|
581
1087
|
if (!transformed || !transformed.data || !transformed.width || !transformed.height) {
|
|
582
|
-
throw new
|
|
1088
|
+
throw new ZapwebpError({
|
|
1089
|
+
code: 'E_PLUGIN_SANDBOX_VIOLATION',
|
|
1090
|
+
message: `Transform "${step.name || 'unknown'}" returned an invalid RawImage.`,
|
|
1091
|
+
fix: 'Ensure transform plugins return { data, width, height } with non-empty pixel data.',
|
|
1092
|
+
});
|
|
583
1093
|
}
|
|
584
1094
|
checkDimensions(transformed.width, transformed.height);
|
|
585
1095
|
raw = transformed;
|
|
@@ -625,9 +1135,20 @@ async function convertImage(input, options = {}) {
|
|
|
625
1135
|
targetFormat: opts.to,
|
|
626
1136
|
});
|
|
627
1137
|
|
|
628
|
-
const targetQuality = options.quality !== undefined
|
|
629
|
-
|
|
1138
|
+
const targetQuality = (options.quality !== undefined)
|
|
1139
|
+
? Number(options.quality)
|
|
1140
|
+
: (opts.smart && opts.quality !== undefined ? Number(opts.quality) : evalQ.quality);
|
|
1141
|
+
const targetLossless = (options.lossless !== undefined)
|
|
1142
|
+
? Boolean(options.lossless)
|
|
1143
|
+
: (opts.smart && opts.lossless !== undefined ? Boolean(opts.lossless) : evalQ.lossless);
|
|
630
1144
|
|
|
1145
|
+
if (opts.to === 'jpeg' && targetLossless) {
|
|
1146
|
+
throw new ZapwebpError({
|
|
1147
|
+
code: 'E_INVALID_CONFIG',
|
|
1148
|
+
message: 'JPEG output does not support lossless encoding.',
|
|
1149
|
+
fix: 'Choose WebP, PNG, or AVIF for lossless output, or set lossless: false.',
|
|
1150
|
+
});
|
|
1151
|
+
}
|
|
631
1152
|
if (opts.to === 'jpeg' && sourceHasAlpha && !opts.background) {
|
|
632
1153
|
throw new ZapwebpError({
|
|
633
1154
|
code: 'E_ALPHA_NOT_REPRESENTABLE',
|
|
@@ -636,7 +1157,16 @@ async function convertImage(input, options = {}) {
|
|
|
636
1157
|
suggestedFix: { background: '#ffffff' },
|
|
637
1158
|
});
|
|
638
1159
|
}
|
|
639
|
-
|
|
1160
|
+
|
|
1161
|
+
const isCustomOutput = !['webp', 'png', 'jpeg', 'avif'].includes(opts.to);
|
|
1162
|
+
const customEncoder = isCustomOutput ? formats.getHandlerByName(opts.to) : null;
|
|
1163
|
+
if (isCustomOutput && (!customEncoder || !customEncoder.isOutput)) {
|
|
1164
|
+
throw new ZapwebpError({
|
|
1165
|
+
code: 'E_UNSUPPORTED_FORMAT',
|
|
1166
|
+
message: `No encoder registered for output format "${opts.to}".`,
|
|
1167
|
+
fix: 'Install a format plugin or register a handler with registerFormat().',
|
|
1168
|
+
});
|
|
1169
|
+
}
|
|
640
1170
|
|
|
641
1171
|
const createPipeline = () => {
|
|
642
1172
|
const sharpInstance = getSharp();
|
|
@@ -647,6 +1177,32 @@ async function convertImage(input, options = {}) {
|
|
|
647
1177
|
};
|
|
648
1178
|
|
|
649
1179
|
const encodeWithQuality = async (q, isLossless) => {
|
|
1180
|
+
if (isCustomOutput) {
|
|
1181
|
+
let rawImage;
|
|
1182
|
+
if (rawBufferInfo) {
|
|
1183
|
+
rawImage = {
|
|
1184
|
+
data: rawBufferInfo.buffer,
|
|
1185
|
+
width: rawBufferInfo.rawOptions.width,
|
|
1186
|
+
height: rawBufferInfo.rawOptions.height,
|
|
1187
|
+
};
|
|
1188
|
+
} else {
|
|
1189
|
+
rawImage = await decodeToRgba(source, format === 'svg' ? 'png' : format);
|
|
1190
|
+
}
|
|
1191
|
+
const encoded = await customEncoder.encode(rawImage, {
|
|
1192
|
+
...opts,
|
|
1193
|
+
quality: q,
|
|
1194
|
+
lossless: isLossless,
|
|
1195
|
+
});
|
|
1196
|
+
const encodedBuf = Buffer.isBuffer(encoded) ? encoded : Buffer.from(encoded.buffer, encoded.byteOffset, encoded.byteLength);
|
|
1197
|
+
return {
|
|
1198
|
+
data: encodedBuf,
|
|
1199
|
+
info: {
|
|
1200
|
+
width: rawImage.width,
|
|
1201
|
+
height: rawImage.height,
|
|
1202
|
+
size: encodedBuf.length,
|
|
1203
|
+
},
|
|
1204
|
+
};
|
|
1205
|
+
}
|
|
650
1206
|
let p = createPipeline();
|
|
651
1207
|
if (opts.width || opts.height) p = p.resize({ width: opts.width, height: opts.height, fit: opts.fit, withoutEnlargement: false });
|
|
652
1208
|
if (opts.background && sourceHasAlpha) p = p.flatten({ background: opts.background });
|
|
@@ -666,35 +1222,176 @@ async function convertImage(input, options = {}) {
|
|
|
666
1222
|
|
|
667
1223
|
let qualityReducedBy = 0;
|
|
668
1224
|
let maxOutputHit = false;
|
|
669
|
-
|
|
1225
|
+
let compressionIterations = 0;
|
|
1226
|
+
let compressionReport = undefined;
|
|
670
1227
|
|
|
671
|
-
|
|
672
|
-
let currentQ = effectiveQuality;
|
|
673
|
-
while (output.length > limitMaxOutput && currentQ > 10) {
|
|
674
|
-
currentQ -= 5;
|
|
675
|
-
const res = await encodeWithQuality(currentQ, false);
|
|
676
|
-
output = res.data;
|
|
677
|
-
info = res.info;
|
|
678
|
-
}
|
|
1228
|
+
const activeCompressor = opts.compressor || getCompressor('compressor');
|
|
679
1229
|
|
|
680
|
-
|
|
1230
|
+
if (limitMaxOutput && output.length > limitMaxOutput) {
|
|
1231
|
+
if (sizeMode === 'strict') {
|
|
681
1232
|
throw new ZapwebpError({
|
|
682
1233
|
code: 'E_OUTPUT_TOO_LARGE',
|
|
683
|
-
message: `
|
|
684
|
-
fix: 'Increase maxOutputBytes, or
|
|
1234
|
+
message: `Output size (${output.length} bytes) exceeds maximum limit (${limitMaxOutput} bytes) in strict mode.`,
|
|
1235
|
+
fix: 'Increase maxOutputBytes, downscale image, or switch to compress/flexible sizeMode.',
|
|
685
1236
|
actualBytes: output.length,
|
|
686
1237
|
maxBytes: limitMaxOutput,
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
1238
|
+
});
|
|
1239
|
+
}
|
|
1240
|
+
|
|
1241
|
+
if (activeCompressor) {
|
|
1242
|
+
let rawForCompress;
|
|
1243
|
+
if (rawBufferInfo) {
|
|
1244
|
+
rawForCompress = {
|
|
1245
|
+
data: rawBufferInfo.buffer,
|
|
1246
|
+
width: rawBufferInfo.rawOptions.width,
|
|
1247
|
+
height: rawBufferInfo.rawOptions.height,
|
|
1248
|
+
channels: rawBufferInfo.rawOptions.channels || 4,
|
|
1249
|
+
};
|
|
1250
|
+
} else {
|
|
1251
|
+
rawForCompress = await decodeToRgba(source, format === 'svg' ? 'png' : format);
|
|
1252
|
+
}
|
|
1253
|
+
|
|
1254
|
+
const compResult = await activeCompressor.compress(rawForCompress, {
|
|
1255
|
+
targetBytes: limitMaxOutput,
|
|
1256
|
+
minQuality: opts.minQuality ?? 10,
|
|
1257
|
+
maxQuality: effectiveQuality,
|
|
1258
|
+
allowDownscale: opts.allowDownscale,
|
|
1259
|
+
downscaleStep: opts.downscaleStep,
|
|
1260
|
+
maxDownscaleAttempts: opts.maxDownscaleAttempts,
|
|
1261
|
+
format: opts.to,
|
|
1262
|
+
background: opts.background,
|
|
1263
|
+
encodeFn: async (img, o) => {
|
|
1264
|
+
const r = await encodeWithQuality(o.quality, false);
|
|
1265
|
+
return r.data;
|
|
690
1266
|
},
|
|
1267
|
+
throwOnUnreachable: sizeMode !== 'flexible',
|
|
691
1268
|
});
|
|
1269
|
+
|
|
1270
|
+
if (compResult.achieved) {
|
|
1271
|
+
output = Buffer.isBuffer(compResult.output) ? compResult.output : Buffer.from(compResult.output);
|
|
1272
|
+
qualityReducedBy = effectiveQuality - compResult.quality;
|
|
1273
|
+
effectiveQuality = compResult.quality;
|
|
1274
|
+
effectiveLossless = false;
|
|
1275
|
+
maxOutputHit = true;
|
|
1276
|
+
compressionIterations = compResult.iterations;
|
|
1277
|
+
info.width = compResult.width;
|
|
1278
|
+
info.height = compResult.height;
|
|
1279
|
+
info.size = output.length;
|
|
1280
|
+
} else {
|
|
1281
|
+
warnings.push(`Output size (${compResult.bytes} bytes) exceeds target limit (${limitMaxOutput} bytes) despite compression.`);
|
|
1282
|
+
output = Buffer.isBuffer(compResult.output) ? compResult.output : Buffer.from(compResult.output);
|
|
1283
|
+
qualityReducedBy = effectiveQuality - compResult.quality;
|
|
1284
|
+
effectiveQuality = compResult.quality;
|
|
1285
|
+
effectiveLossless = false;
|
|
1286
|
+
maxOutputHit = true;
|
|
1287
|
+
compressionIterations = compResult.iterations;
|
|
1288
|
+
info.width = compResult.width;
|
|
1289
|
+
info.height = compResult.height;
|
|
1290
|
+
info.size = output.length;
|
|
1291
|
+
}
|
|
1292
|
+
|
|
1293
|
+
compressionReport = {
|
|
1294
|
+
target: limitMaxOutput,
|
|
1295
|
+
achieved: compResult.achieved,
|
|
1296
|
+
quality: compResult.quality,
|
|
1297
|
+
iterations: compResult.iterations,
|
|
1298
|
+
downscaled: compResult.downscaled,
|
|
1299
|
+
downscaleCount: compResult.downscaleCount,
|
|
1300
|
+
width: compResult.width,
|
|
1301
|
+
height: compResult.height,
|
|
1302
|
+
reason: compResult.reason,
|
|
1303
|
+
bestAttempt: compResult.bestAttempt,
|
|
1304
|
+
};
|
|
1305
|
+
} else {
|
|
1306
|
+
// Binary search over quality [10, effectiveQuality] with format-specific iteration caps (Finding 4.1)
|
|
1307
|
+
const getMaxIterationsForFormat = (fmt) => {
|
|
1308
|
+
const f = String(fmt || '').toLowerCase();
|
|
1309
|
+
if (f === 'avif') return 3;
|
|
1310
|
+
if (f === 'webp' || f === 'jpeg') return 4;
|
|
1311
|
+
return 3;
|
|
1312
|
+
};
|
|
1313
|
+
const maxIterations = getMaxIterationsForFormat(opts.to);
|
|
1314
|
+
let low = 10;
|
|
1315
|
+
let high = effectiveQuality;
|
|
1316
|
+
let bestResult = null;
|
|
1317
|
+
|
|
1318
|
+
while (low <= high && compressionIterations < maxIterations) {
|
|
1319
|
+
compressionIterations++;
|
|
1320
|
+
const mid = Math.floor((low + high) / 2);
|
|
1321
|
+
const res = await encodeWithQuality(mid, false);
|
|
1322
|
+
if (res.data.length <= limitMaxOutput) {
|
|
1323
|
+
bestResult = { ...res, quality: mid };
|
|
1324
|
+
low = mid + 1; // Try higher quality
|
|
1325
|
+
} else {
|
|
1326
|
+
high = mid - 1; // Needs stronger compression
|
|
1327
|
+
}
|
|
1328
|
+
}
|
|
1329
|
+
|
|
1330
|
+
if (bestResult) {
|
|
1331
|
+
qualityReducedBy = effectiveQuality - bestResult.quality;
|
|
1332
|
+
effectiveQuality = bestResult.quality;
|
|
1333
|
+
effectiveLossless = false;
|
|
1334
|
+
maxOutputHit = true;
|
|
1335
|
+
output = bestResult.data;
|
|
1336
|
+
info = bestResult.info;
|
|
1337
|
+
} else {
|
|
1338
|
+
compressionIterations++;
|
|
1339
|
+
const minRes = await encodeWithQuality(10, false);
|
|
1340
|
+
if (minRes.data.length <= limitMaxOutput) {
|
|
1341
|
+
qualityReducedBy = effectiveQuality - 10;
|
|
1342
|
+
effectiveQuality = 10;
|
|
1343
|
+
effectiveLossless = false;
|
|
1344
|
+
maxOutputHit = true;
|
|
1345
|
+
output = minRes.data;
|
|
1346
|
+
info = minRes.info;
|
|
1347
|
+
} else {
|
|
1348
|
+
if (sizeMode === 'flexible') {
|
|
1349
|
+
warnings.push(`Output size (${minRes.data.length} bytes) exceeds target limit (${limitMaxOutput} bytes) despite compression down to quality 10.`);
|
|
1350
|
+
qualityReducedBy = effectiveQuality - 10;
|
|
1351
|
+
effectiveQuality = 10;
|
|
1352
|
+
effectiveLossless = false;
|
|
1353
|
+
maxOutputHit = true;
|
|
1354
|
+
output = minRes.data;
|
|
1355
|
+
info = minRes.info;
|
|
1356
|
+
} else {
|
|
1357
|
+
throw new ZapwebpError({
|
|
1358
|
+
code: 'E_OUTPUT_TOO_LARGE',
|
|
1359
|
+
message: `Cannot fit output in ${limitMaxOutput} bytes (reached ${minRes.data.length} bytes at quality 10).`,
|
|
1360
|
+
fix: 'Increase maxOutputBytes, downscale the image, or switch to flexible sizeMode.',
|
|
1361
|
+
actualBytes: minRes.data.length,
|
|
1362
|
+
maxBytes: limitMaxOutput,
|
|
1363
|
+
suggestedFix: {
|
|
1364
|
+
quality: 10,
|
|
1365
|
+
reason: 'Image exceeds maxOutputBytes even after reducing quality to 10.',
|
|
1366
|
+
},
|
|
1367
|
+
});
|
|
1368
|
+
}
|
|
1369
|
+
}
|
|
1370
|
+
}
|
|
692
1371
|
}
|
|
1372
|
+
}
|
|
693
1373
|
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
1374
|
+
// Min output size validation
|
|
1375
|
+
if (limitMinOutput && output.length < limitMinOutput) {
|
|
1376
|
+
if (sizeMode === 'strict') {
|
|
1377
|
+
throw new ZapwebpError({
|
|
1378
|
+
code: 'E_OUTPUT_TOO_SMALL',
|
|
1379
|
+
message: `Output size (${output.length} bytes) is below minimum required (${limitMinOutput} bytes) in strict mode.`,
|
|
1380
|
+
fix: 'Increase quality or adjust minOutputBytes.',
|
|
1381
|
+
actualBytes: output.length,
|
|
1382
|
+
minBytes: limitMinOutput,
|
|
1383
|
+
});
|
|
1384
|
+
} else if (sizeMode === 'compress') {
|
|
1385
|
+
throw new ZapwebpError({
|
|
1386
|
+
code: 'E_OUTPUT_BELOW_RANGE',
|
|
1387
|
+
message: `Output size (${output.length} bytes) is below configured minimum (${limitMinOutput} bytes).`,
|
|
1388
|
+
fix: 'Adjust minOutputBytes or switch to flexible sizeMode.',
|
|
1389
|
+
actualBytes: output.length,
|
|
1390
|
+
minBytes: limitMinOutput,
|
|
1391
|
+
});
|
|
1392
|
+
} else {
|
|
1393
|
+
warnings.push(`Output size (${output.length} bytes) is below minimum threshold (${limitMinOutput} bytes).`);
|
|
1394
|
+
}
|
|
698
1395
|
}
|
|
699
1396
|
|
|
700
1397
|
const inputMetadata = detectMetadata(data);
|
|
@@ -707,7 +1404,11 @@ async function convertImage(input, options = {}) {
|
|
|
707
1404
|
if (opts.assertAlpha && sourceHasAlpha) {
|
|
708
1405
|
const check = await verifyAlpha(output);
|
|
709
1406
|
if (!check.hasAlpha) {
|
|
710
|
-
throw new
|
|
1407
|
+
throw new ZapwebpError({
|
|
1408
|
+
code: 'E_ALPHA_NOT_REPRESENTABLE',
|
|
1409
|
+
message: 'Alpha assertion failed: output image does not contain transparent pixels.',
|
|
1410
|
+
fix: 'Ensure the target format supports transparency and no flattening background was applied.',
|
|
1411
|
+
});
|
|
711
1412
|
}
|
|
712
1413
|
}
|
|
713
1414
|
|
|
@@ -719,7 +1420,31 @@ async function convertImage(input, options = {}) {
|
|
|
719
1420
|
? 'flattened'
|
|
720
1421
|
: (sourceHasAlpha ? 'preserved' : 'preserved_opaque');
|
|
721
1422
|
|
|
722
|
-
|
|
1423
|
+
if (options.customMetadata && typeof options.customMetadata === 'object') {
|
|
1424
|
+
output = attachCustomMetadata(output, opts.to, options.customMetadata);
|
|
1425
|
+
}
|
|
1426
|
+
|
|
1427
|
+
const sourceQuality = evaluateSourceQuality(format, data);
|
|
1428
|
+
const sizeImpact = evaluateSizeImpact(output.length, data.length, format, opts.to, effectiveLossless);
|
|
1429
|
+
|
|
1430
|
+
let losslessVerified = false;
|
|
1431
|
+
if (effectiveLossless && !opts.background && ['webp', 'png', 'avif'].includes(opts.to)) {
|
|
1432
|
+
const verified = await verifyLosslessPixels(source, output, format, opts.to, getSharp);
|
|
1433
|
+
if (!verified) {
|
|
1434
|
+
throw new ZapwebpError({
|
|
1435
|
+
code: 'E_LOSSLESS_MISMATCH',
|
|
1436
|
+
message: 'Lossless verification failed: decoded output does not match input pixels.',
|
|
1437
|
+
fix: 'Verify the target format supports full lossless encoding and no color-space shifting was applied.',
|
|
1438
|
+
});
|
|
1439
|
+
}
|
|
1440
|
+
losslessVerified = true;
|
|
1441
|
+
}
|
|
1442
|
+
|
|
1443
|
+
if (effectiveLossless && (format === 'jpeg' || format === 'jpg')) {
|
|
1444
|
+
warnings.push("Lossless conversion of a JPEG source preserves existing compression artifacts and produces a larger file without improving quality.");
|
|
1445
|
+
}
|
|
1446
|
+
|
|
1447
|
+
return finish({
|
|
723
1448
|
data: output,
|
|
724
1449
|
format: opts.to,
|
|
725
1450
|
width: info.width,
|
|
@@ -727,15 +1452,55 @@ async function convertImage(input, options = {}) {
|
|
|
727
1452
|
size: output.length,
|
|
728
1453
|
alphaPreserved,
|
|
729
1454
|
alphaVerified: alphaPreserved,
|
|
1455
|
+
lossless: effectiveLossless,
|
|
1456
|
+
losslessVerified,
|
|
1457
|
+
sourceQuality,
|
|
1458
|
+
sizeImpact,
|
|
730
1459
|
backgroundStatus,
|
|
731
1460
|
transparency,
|
|
732
1461
|
flattenColor: opts.background || undefined,
|
|
733
1462
|
clean: opts.clean,
|
|
1463
|
+
qualityReducedBy,
|
|
1464
|
+
maxOutputHit,
|
|
1465
|
+
quality: effectiveQuality,
|
|
1466
|
+
warnings,
|
|
1467
|
+
ingestion: {
|
|
1468
|
+
stage: 'converted',
|
|
1469
|
+
action: isSameFormat ? 'same_format_reencoded' : 'transcoded',
|
|
1470
|
+
detectedFormat: format,
|
|
1471
|
+
targetFormat: opts.to,
|
|
1472
|
+
sizeMode,
|
|
1473
|
+
inputBytes: data.length,
|
|
1474
|
+
outputBytes: output.length,
|
|
1475
|
+
iterations: compressionIterations,
|
|
1476
|
+
reason: isSameFormat ? 'Same format re-encoded per policy.' : 'Image successfully transcoded to target format.',
|
|
1477
|
+
},
|
|
734
1478
|
removedMetadata: inputMetadata.summary,
|
|
735
1479
|
certificate,
|
|
736
1480
|
transforms: transformReports.length > 0 ? transformReports : undefined,
|
|
1481
|
+
compression: compressionReport || (compressionIterations > 0 ? {
|
|
1482
|
+
target: limitMaxOutput,
|
|
1483
|
+
achieved: output.length <= limitMaxOutput,
|
|
1484
|
+
quality: effectiveQuality,
|
|
1485
|
+
iterations: compressionIterations,
|
|
1486
|
+
downscaled: false,
|
|
1487
|
+
downscaleCount: 0,
|
|
1488
|
+
width: info.width,
|
|
1489
|
+
height: info.height,
|
|
1490
|
+
reason: maxOutputHit ? 'Quality optimized to fit target limit.' : undefined,
|
|
1491
|
+
} : undefined),
|
|
737
1492
|
targetLockEnforced: Boolean(opts.lockTarget && !opts.overrideLock),
|
|
738
1493
|
targetLockBypassed: Boolean(opts.lockTarget && opts.overrideLock),
|
|
1494
|
+
smart: smartResult ? { detectedType: smartResult.detectedType, recommendation: smartResult.recommendation } : undefined,
|
|
1495
|
+
lifecycle: {
|
|
1496
|
+
keepOriginal: opts.keepOriginal,
|
|
1497
|
+
originalPath: options.inputPath || options.filePath || options.originalPath || undefined,
|
|
1498
|
+
originalDeleted: options.originalDeleted !== undefined ? Boolean(options.originalDeleted) : false,
|
|
1499
|
+
action: 'in_memory_only',
|
|
1500
|
+
note: 'convertImage operates on buffers, not files. Use the CLI for file operations.',
|
|
1501
|
+
backupPath: options.backupPath || undefined,
|
|
1502
|
+
cleanupDelay: opts.cleanupDelay,
|
|
1503
|
+
},
|
|
739
1504
|
policy: {
|
|
740
1505
|
quality: {
|
|
741
1506
|
mode: evalQ.mode,
|
|
@@ -745,7 +1510,9 @@ async function convertImage(input, options = {}) {
|
|
|
745
1510
|
reason: qualityReducedBy > 0 ? 'to fit maxOutputBytes' : 'as specified',
|
|
746
1511
|
},
|
|
747
1512
|
limits: {
|
|
1513
|
+
minInputBytes: policy.limits.minInputBytes,
|
|
748
1514
|
maxInputBytes: policy.limits.maxInputBytes,
|
|
1515
|
+
minOutputBytes: limitMinOutput,
|
|
749
1516
|
maxOutputBytes: limitMaxOutput,
|
|
750
1517
|
maxOutputHit,
|
|
751
1518
|
},
|
|
@@ -754,8 +1521,11 @@ async function convertImage(input, options = {}) {
|
|
|
754
1521
|
output: opts.to,
|
|
755
1522
|
accepted: true,
|
|
756
1523
|
},
|
|
1524
|
+
size: {
|
|
1525
|
+
mode: sizeMode,
|
|
1526
|
+
},
|
|
757
1527
|
},
|
|
758
|
-
};
|
|
1528
|
+
});
|
|
759
1529
|
}
|
|
760
1530
|
|
|
761
1531
|
/**
|
|
@@ -778,6 +1548,14 @@ async function convert(input, options = {}) {
|
|
|
778
1548
|
out.passedThrough = Boolean(result.passedThrough);
|
|
779
1549
|
out.data = result.data;
|
|
780
1550
|
out.policy = result.policy;
|
|
1551
|
+
out.lifecycle = result.lifecycle;
|
|
1552
|
+
out.ingestion = result.ingestion;
|
|
1553
|
+
out.warnings = result.warnings;
|
|
1554
|
+
out.quality = result.quality;
|
|
1555
|
+
out.lossless = result.lossless;
|
|
1556
|
+
out.losslessVerified = result.losslessVerified;
|
|
1557
|
+
out.sourceQuality = result.sourceQuality;
|
|
1558
|
+
out.sizeImpact = result.sizeImpact;
|
|
781
1559
|
return out;
|
|
782
1560
|
}
|
|
783
1561
|
|
|
@@ -790,6 +1568,16 @@ async function convert(input, options = {}) {
|
|
|
790
1568
|
async function decodeToRgba(input, format) {
|
|
791
1569
|
const data = asBuffer(input);
|
|
792
1570
|
const fmt = format ? String(format).toLowerCase() : detectFormat(data);
|
|
1571
|
+
const customHandler = formats.getHandlerByName(fmt);
|
|
1572
|
+
if (customHandler && customHandler.isInput && !['svg', 'png', 'jpeg', 'webp', 'avif', 'gif', 'tiff'].includes(fmt)) {
|
|
1573
|
+
const raw = await customHandler.decode(data);
|
|
1574
|
+
checkDimensions(raw.width, raw.height);
|
|
1575
|
+
return {
|
|
1576
|
+
data: raw.data instanceof Uint8ClampedArray ? raw.data : new Uint8ClampedArray(raw.data.buffer, raw.data.byteOffset, raw.data.byteLength),
|
|
1577
|
+
width: raw.width,
|
|
1578
|
+
height: raw.height,
|
|
1579
|
+
};
|
|
1580
|
+
}
|
|
793
1581
|
let source = data;
|
|
794
1582
|
if (fmt === 'svg') {
|
|
795
1583
|
const svg = validateSvg(data);
|
|
@@ -818,10 +1606,19 @@ async function decodeToRgba(input, format) {
|
|
|
818
1606
|
*/
|
|
819
1607
|
async function encodeFromRgba(image, options = {}) {
|
|
820
1608
|
if (!image || !image.data || !Number.isInteger(image.width) || !Number.isInteger(image.height)) {
|
|
821
|
-
throw new
|
|
1609
|
+
throw new ZapwebpError({
|
|
1610
|
+
code: 'E_INVALID_CONFIG',
|
|
1611
|
+
message: 'image must be an object with data (RGBA bytes), width, and height.',
|
|
1612
|
+
fix: 'Pass a valid RawImage object.',
|
|
1613
|
+
});
|
|
822
1614
|
}
|
|
823
1615
|
checkDimensions(image.width, image.height);
|
|
824
1616
|
const opts = normalizeOptions(options);
|
|
1617
|
+
const customHandler = formats.getHandlerByName(opts.to);
|
|
1618
|
+
if (customHandler && customHandler.isOutput && !['webp', 'png', 'jpeg', 'avif'].includes(opts.to)) {
|
|
1619
|
+
const encoded = await customHandler.encode(image, opts);
|
|
1620
|
+
return Buffer.isBuffer(encoded) ? encoded : Buffer.from(encoded.buffer, encoded.byteOffset, encoded.byteLength);
|
|
1621
|
+
}
|
|
825
1622
|
const raw = Buffer.isBuffer(image.data)
|
|
826
1623
|
? image.data
|
|
827
1624
|
: Buffer.from(image.data.buffer, image.data.byteOffset, image.data.byteLength);
|
|
@@ -834,6 +1631,13 @@ async function encodeFromRgba(image, options = {}) {
|
|
|
834
1631
|
}
|
|
835
1632
|
}
|
|
836
1633
|
|
|
1634
|
+
if (opts.to === 'jpeg' && opts.lossless) {
|
|
1635
|
+
throw new ZapwebpError({
|
|
1636
|
+
code: 'E_INVALID_CONFIG',
|
|
1637
|
+
message: 'JPEG output does not support lossless encoding.',
|
|
1638
|
+
fix: 'Choose WebP, PNG, or AVIF for lossless output, or set lossless: false.',
|
|
1639
|
+
});
|
|
1640
|
+
}
|
|
837
1641
|
if (opts.to === 'jpeg' && hasAlpha && !opts.background) {
|
|
838
1642
|
throw new ZapwebpError({
|
|
839
1643
|
code: 'E_ALPHA_NOT_REPRESENTABLE',
|
|
@@ -842,9 +1646,6 @@ async function encodeFromRgba(image, options = {}) {
|
|
|
842
1646
|
suggestedFix: { background: '#ffffff' },
|
|
843
1647
|
});
|
|
844
1648
|
}
|
|
845
|
-
if (opts.to === 'jpeg' && opts.lossless) {
|
|
846
|
-
throw new Error('JPEG output does not support lossless encoding.');
|
|
847
|
-
}
|
|
848
1649
|
|
|
849
1650
|
let pipeline = getSharp()(raw, {
|
|
850
1651
|
raw: {
|
|
@@ -900,9 +1701,14 @@ function parseScales(scaleInput) {
|
|
|
900
1701
|
? scaleInput
|
|
901
1702
|
: String(scaleInput).split(',').map((s) => s.trim()).filter(Boolean);
|
|
902
1703
|
const parsed = list.map((item) => {
|
|
903
|
-
const
|
|
1704
|
+
const cleaned = String(item).trim().replace(/x$/i, '');
|
|
1705
|
+
const num = Number(cleaned);
|
|
904
1706
|
if (!Number.isFinite(num) || num <= 0) {
|
|
905
|
-
throw new
|
|
1707
|
+
throw new ZapwebpError({
|
|
1708
|
+
code: 'E_INVALID_CONFIG',
|
|
1709
|
+
message: `Scale multiplier must be a positive number, received: ${item}`,
|
|
1710
|
+
fix: 'Use positive numbers like "1", "2", or "3".',
|
|
1711
|
+
});
|
|
906
1712
|
}
|
|
907
1713
|
return num;
|
|
908
1714
|
});
|
|
@@ -953,8 +1759,53 @@ function generateSrcset(baseFile, scales = [1], format = 'webp', alt = '') {
|
|
|
953
1759
|
return `<img src="${primaryFile}" srcset="${srcsetString}" alt="${alt}">`;
|
|
954
1760
|
}
|
|
955
1761
|
|
|
1762
|
+
const pkg = require('../package.json');
|
|
1763
|
+
const { registerTransform, getTransforms } = require('./registry/transforms');
|
|
1764
|
+
const { registerCompressor, getCompressor, getCompressors } = require('./registry/compression');
|
|
1765
|
+
|
|
1766
|
+
/**
|
|
1767
|
+
* Returns the frozen engine version.
|
|
1768
|
+
* @returns {string}
|
|
1769
|
+
*/
|
|
1770
|
+
function getVersion() {
|
|
1771
|
+
return pkg.version;
|
|
1772
|
+
}
|
|
1773
|
+
|
|
1774
|
+
/**
|
|
1775
|
+
* Returns all registered format names in the core registry.
|
|
1776
|
+
* @returns {string[]}
|
|
1777
|
+
*/
|
|
1778
|
+
function getFormats() {
|
|
1779
|
+
return formats.getAllHandlers().map((h) => h.name);
|
|
1780
|
+
}
|
|
1781
|
+
|
|
956
1782
|
module.exports = {
|
|
1783
|
+
// Frozen Seven Public Functions (Enterprise Architecture Core API Surface)
|
|
957
1784
|
convert,
|
|
1785
|
+
inspect: inspectImage,
|
|
1786
|
+
registerFormat: formats.registerFormat,
|
|
1787
|
+
registerMetadataHandler: metadata.registerMetadataHandler,
|
|
1788
|
+
registerTransform,
|
|
1789
|
+
registerCompressor,
|
|
1790
|
+
getCompressor,
|
|
1791
|
+
getCompressors,
|
|
1792
|
+
getVersion,
|
|
1793
|
+
getFormats,
|
|
1794
|
+
|
|
1795
|
+
// Agentic & Tool Discovery Surfaces
|
|
1796
|
+
listTools,
|
|
1797
|
+
getAgentManifest,
|
|
1798
|
+
ZapwebpError,
|
|
1799
|
+
|
|
1800
|
+
// Performance Optimization Surfaces (Masterplan)
|
|
1801
|
+
computeCacheKey,
|
|
1802
|
+
ConversionCache,
|
|
1803
|
+
defaultCache,
|
|
1804
|
+
parallelMap,
|
|
1805
|
+
ConversionPool,
|
|
1806
|
+
defaultPool,
|
|
1807
|
+
|
|
1808
|
+
// Backwards-Compatible Surfaces
|
|
958
1809
|
convertImage,
|
|
959
1810
|
convertSvgToWebp,
|
|
960
1811
|
decodeToRgba,
|
|
@@ -979,7 +1830,6 @@ module.exports = {
|
|
|
979
1830
|
evaluateQuality,
|
|
980
1831
|
formats,
|
|
981
1832
|
registry: formats.registry,
|
|
982
|
-
registerFormat: formats.registerFormat,
|
|
983
1833
|
getHandlerByName: formats.getHandlerByName,
|
|
984
1834
|
getHandlerByMime: formats.getHandlerByMime,
|
|
985
1835
|
detectFormatHandler: formats.detectFormatHandler,
|
|
@@ -987,11 +1837,32 @@ module.exports = {
|
|
|
987
1837
|
metadata,
|
|
988
1838
|
MetadataRegistry: metadata.MetadataRegistry,
|
|
989
1839
|
metadataRegistry: metadata.metadataRegistry,
|
|
990
|
-
registerMetadataHandler: metadata.registerMetadataHandler,
|
|
991
1840
|
getMetadataHandlers: metadata.getMetadataHandlers,
|
|
992
1841
|
cleanBytes: metadata.cleanBytes,
|
|
1842
|
+
cleanMetadata: metadata.cleanBytes,
|
|
1843
|
+
suggest,
|
|
1844
|
+
evaluateSourceQuality,
|
|
1845
|
+
evaluateSizeImpact,
|
|
1846
|
+
verifyLosslessPixels,
|
|
1847
|
+
computeContentSignals,
|
|
1848
|
+
attachCustomMetadata,
|
|
1849
|
+
extractCustomMetadata,
|
|
1850
|
+
computePerformanceReport,
|
|
1851
|
+
formatPerformanceReport,
|
|
1852
|
+
analyzeSmart,
|
|
1853
|
+
classifyContentType,
|
|
1854
|
+
extractSmartSignals,
|
|
1855
|
+
RECOMMENDATION_PROFILES,
|
|
1856
|
+
DEFAULT_TEAM_POLICY_TEMPLATE,
|
|
1857
|
+
validateTeamPolicy,
|
|
1858
|
+
evaluateFilePolicy,
|
|
1859
|
+
checkExceptionsStatus,
|
|
1860
|
+
formatPolicyStatus,
|
|
1861
|
+
getTransforms,
|
|
993
1862
|
getSharp,
|
|
994
1863
|
getResvg,
|
|
1864
|
+
assertRuntimeIsolation,
|
|
1865
|
+
detectEnvironment,
|
|
995
1866
|
MAX_WIDTH,
|
|
996
1867
|
INPUT_FORMATS,
|
|
997
1868
|
OUTPUT_FORMATS,
|