@zapwebp/core 1.1.0 → 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.
Files changed (45) hide show
  1. package/README.md +79 -51
  2. package/agent.json +180 -0
  3. package/package.json +9 -3
  4. package/src/cache.js +145 -0
  5. package/src/engine/decode.js +60 -0
  6. package/src/engine/encode.js +106 -0
  7. package/src/engine/pipeline.js +116 -0
  8. package/src/engine/transform.js +37 -0
  9. package/src/errors/index.js +34 -0
  10. package/src/formats/avif.js +3 -3
  11. package/src/formats/gif.js +8 -3
  12. package/src/formats/index.js +5 -0
  13. package/src/formats/jpeg.js +15 -4
  14. package/src/formats/png.js +3 -3
  15. package/src/formats/svg.js +75 -14
  16. package/src/formats/tiff.js +8 -3
  17. package/src/formats/webp.js +3 -3
  18. package/src/index.d.ts +286 -9
  19. package/src/index.js +998 -91
  20. package/src/journal/index.js +73 -0
  21. package/src/metadata/c2pa.js +3 -11
  22. package/src/metadata/chunk-stripper.js +235 -0
  23. package/src/metadata/exif.js +3 -12
  24. package/src/metadata/icc.js +3 -11
  25. package/src/metadata/png-text.js +3 -11
  26. package/src/metadata/registry.js +26 -3
  27. package/src/metadata/xmp.js +3 -17
  28. package/src/parallel.js +134 -0
  29. package/src/policy.js +95 -6
  30. package/src/registry/compression.js +84 -0
  31. package/src/registry/formats.js +30 -0
  32. package/src/registry/metadata.js +28 -0
  33. package/src/registry/transforms.js +76 -0
  34. package/src/report.js +404 -0
  35. package/src/safety/path.js +52 -0
  36. package/src/safety/runtime.js +66 -0
  37. package/src/safety/ssrf.js +9 -0
  38. package/src/safety/svg.js +66 -0
  39. package/src/signals.js +683 -0
  40. package/src/smart.js +351 -0
  41. package/src/team-policy.js +319 -0
  42. package/src/testing.d.ts +18 -0
  43. package/src/testing.js +114 -0
  44. package/src/tools.js +240 -0
  45. package/src/types.ts +68 -0
package/src/index.js CHANGED
@@ -2,8 +2,6 @@
2
2
 
3
3
  const path = require('node:path');
4
4
  const crypto = require('node:crypto');
5
- const { Resvg } = require('@resvg/resvg-js');
6
- const sharp = require('sharp');
7
5
  const formats = require('./formats');
8
6
  const metadata = require('./metadata');
9
7
  const {
@@ -19,11 +17,72 @@ const {
19
17
  checkPolicyInput,
20
18
  evaluateQuality,
21
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');
50
+
51
+ let _sharpInstance = null;
52
+ function getSharp() {
53
+ if (_sharpInstance) return _sharpInstance;
54
+ try {
55
+ _sharpInstance = require('sharp');
56
+ return _sharpInstance;
57
+ } catch (err) {
58
+ throw new ZapwebpError({
59
+ code: 'E_ENGINE_UNAVAILABLE',
60
+ message: 'Native raster engine (sharp) is not available in this environment: ' + (err && err.message ? err.message : String(err)),
61
+ fix: 'Install sharp via "npm install sharp" or ensure native prebuilts are compiled for this architecture.',
62
+ });
63
+ }
64
+ }
65
+
66
+ let _resvgInstance = null;
67
+ function getResvg() {
68
+ if (_resvgInstance) return _resvgInstance;
69
+ try {
70
+ const mod = require('@resvg/resvg-js');
71
+ _resvgInstance = mod.Resvg || mod;
72
+ return _resvgInstance;
73
+ } catch (err) {
74
+ throw new ZapwebpError({
75
+ code: 'E_ENGINE_UNAVAILABLE',
76
+ message: 'Native vector engine (@resvg/resvg-js) is not available in this environment: ' + (err && err.message ? err.message : String(err)),
77
+ fix: 'Install @resvg/resvg-js or ensure native prebuilts are compiled for this architecture.',
78
+ });
79
+ }
80
+ }
22
81
 
23
82
  const MAX_WIDTH = MAX_DIMENSION;
24
83
  const FIT_MODES = Object.freeze(['contain', 'cover', 'fill', 'inside', 'outside']);
25
84
 
26
- const SVG_DANGER_RE = /<(?:script|foreignObject)\b|\bon\w+\s*=|<\!ENTITY|<\!DOCTYPE|@import/i;
85
+ const SVG_DANGER_RE = /<(?:script|foreignObject)\b|\bon\w+\s*=|javascript:|<\!ENTITY|<\!DOCTYPE|@import/i;
27
86
 
28
87
  /**
29
88
  * Validates pre-flight buffer integrity.
@@ -50,16 +109,46 @@ function validateImageBytes(input) {
50
109
  }
51
110
  }
52
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
+
53
130
  function asBuffer(input) {
54
131
  if (Buffer.isBuffer(input)) return input;
55
132
  if (input instanceof Uint8Array) return Buffer.from(input.buffer, input.byteOffset, input.byteLength);
56
133
  if (typeof input === 'string') return Buffer.from(input, 'utf8');
57
- throw new Error('Image input must be a string or byte array.');
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
+ });
58
139
  }
59
140
 
60
141
  function detectFormat(input) {
61
142
  const data = asBuffer(input);
62
- if (!data.length) throw new Error('The input file is empty.');
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
+ }
150
+ const registered = formats.detectFormatHandler(data);
151
+ if (registered) return registered.name;
63
152
  if (data.length >= 8 && data.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))) return 'png';
64
153
  if (data.length >= 3 && data[0] === 0xff && data[1] === 0xd8 && data[2] === 0xff) return 'jpeg';
65
154
  if (data.length >= 6 && (data.subarray(0, 6).toString('ascii') === 'GIF87a' || data.subarray(0, 6).toString('ascii') === 'GIF89a')) return 'gif';
@@ -74,21 +163,74 @@ function detectFormat(input) {
74
163
  || data.subarray(0, 4).equals(Buffer.from([0x49, 0x49, 0x2b, 0x00]))
75
164
  || data.subarray(0, 4).equals(Buffer.from([0x4d, 0x4d, 0x00, 0x2b]))
76
165
  )) return 'tiff';
77
- if (data.length >= 2 && data.subarray(0, 2).toString('ascii') === 'BM') throw new Error('BMP input is not supported yet.');
78
- if (data.length >= 4 && data[0] === 0 && data[1] === 0 && data[2] === 1 && data[3] === 0) throw new Error('ICO input is not supported yet.');
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
+ }
79
180
  const text = data.subarray(0, Math.min(data.length, 4096)).toString('utf8').replace(/^\uFEFF/, '').trimStart();
80
181
  if (/<svg(?:\s|\/?>)/i.test(text) || /^<\?xml[\s\S]*?<svg(?:\s|\/?>)/i.test(text)) return 'svg';
81
- throw new Error('Unsupported or unrecognized image format. Supported inputs: SVG, PNG, JPEG, WebP, AVIF, GIF, and TIFF.');
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
+ });
82
187
  }
83
188
 
84
189
  function validateSvg(input) {
85
190
  const svg = Buffer.isBuffer(input) ? input.toString('utf8') : String(input);
86
- if (Buffer.byteLength(svg) === 0 || !/<svg(?:\s|\/?>)/i.test(svg)) throw new Error('This file does not contain a valid SVG document.');
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
+ }
87
198
  if (SVG_DANGER_RE.test(svg)) {
88
- if (/<(?:script|foreignObject)\b/i.test(svg) || /\bon\w+\s*=/i.test(svg)) throw new Error('This SVG contains active content and cannot be converted.');
89
- if (/<!ENTITY\b/i.test(svg)) throw new Error('Custom XML entities are not supported.');
90
- if (/<!DOCTYPE\b/i.test(svg)) throw new Error('DOCTYPE declarations are not supported.');
91
- if (/@import\b/i.test(svg)) throw new Error('External stylesheet imports are not supported.');
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
+ }
92
234
  }
93
235
  let decoded;
94
236
  try {
@@ -96,19 +238,53 @@ function validateSvg(input) {
96
238
  .replace(/&#x([\da-f]+);/gi, (_match, code) => String.fromCodePoint(Number.parseInt(code, 16)))
97
239
  .replace(/&#(\d+);/g, (_match, code) => String.fromCodePoint(Number(code)))
98
240
  .replace(/&amp;/gi, '&');
99
- } catch { throw new Error('This SVG contains an invalid character reference.'); }
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
+ }
100
248
  let normalized;
101
249
  try {
102
- normalized = decoded.replace(/\/\*[\s\S]*?\*\//g, '').replace(/\\([\da-f]{1,6})\s?/gi, (_match, code) => String.fromCodePoint(Number.parseInt(code, 16)));
103
- } catch { throw new Error('This SVG contains an invalid CSS escape.'); }
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
+ }
104
258
  const safeReference = (value) => {
105
259
  const ref = value.trim().replace(/^("|')([\s\S]*)\1$/, '$2').trim();
106
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);
107
261
  };
108
262
  const attributeRefs = /(?:href|src)\s*=\s*(["'])(.*?)\1/gi;
109
- for (const match of normalized.matchAll(attributeRefs)) if (!safeReference(match[2])) throw new Error('External references are not supported. Embed raster images and fonts in the SVG first.');
110
- if (/@import\b/i.test(normalized)) throw new Error('External stylesheet imports are not supported.');
111
- for (const match of normalized.matchAll(/url\(\s*([^)]*?)\s*\)/gi)) if (!safeReference(match[1])) throw new Error('External references are not supported. Embed images and fonts in the SVG first.');
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
+ }
112
288
  return svg;
113
289
  }
114
290
 
@@ -131,16 +307,35 @@ function svgDimensions(svg) {
131
307
  const root = svg.match(/<svg\b[^>]*>/i)?.[0] || '';
132
308
  const attribute = (name) => root.match(new RegExp(`(?:^|\\s)${name}\\s*=\\s*(["'])(.*?)\\1`, 'i'))?.[2];
133
309
  const viewBox = attribute('viewBox');
310
+ let width;
311
+ let height;
134
312
  if (viewBox) {
135
313
  const values = viewBox.trim().split(/[\s,]+/).map(Number);
136
- if (values.length === 4 && values.every(Number.isFinite) && values[2] > 0 && values[3] > 0) return { width: values[2], height: values[3] };
314
+ if (values.length === 4 && values.every(Number.isFinite) && values[2] > 0 && values[3] > 0) {
315
+ width = values[2];
316
+ height = values[3];
317
+ }
137
318
  }
138
319
  const dimension = (name) => {
139
320
  const value = attribute(name);
140
321
  const match = value?.trim().match(/^([+]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?)(?:px)?$/i);
141
322
  return match ? Number(match[1]) : undefined;
142
323
  };
143
- return { width: dimension('width'), height: dimension('height') };
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 };
144
339
  }
145
340
 
146
341
  /**
@@ -277,7 +472,7 @@ function generateCleanCertificate(output) {
277
472
  */
278
473
  async function verifyAlpha(input) {
279
474
  const data = asBuffer(input);
280
- const { data: raw, info } = await sharp(data, { limitInputPixels: MAX_PIXELS }).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
475
+ const { data: raw, info } = await getSharp()(data, { limitInputPixels: MAX_PIXELS }).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
281
476
  const w = info.width;
282
477
  const h = info.height;
283
478
 
@@ -310,8 +505,12 @@ async function verifyAlpha(input) {
310
505
  * @returns {{ safe: boolean, issues: string[], recommendedCommand: string }}
311
506
  */
312
507
  function auditConversionCommand(command) {
313
- if (!command || typeof command !== 'string') {
314
- throw new Error('Command must be a non-empty string.');
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
+ });
315
514
  }
316
515
 
317
516
  const issues = [];
@@ -368,7 +567,13 @@ function explainBlackBackground(context = {}) {
368
567
  }
369
568
 
370
569
  function normalizeOptions(options = {}) {
371
- if (!options || typeof options !== 'object' || Array.isArray(options)) throw new Error('Conversion options must be an object.');
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
+ }
372
577
  const lockTarget = options.lockTarget || options.lock;
373
578
  const overrideLock = Boolean(options.overrideLock);
374
579
  const strict = options.strict !== undefined ? Boolean(options.strict) : true;
@@ -378,24 +583,78 @@ function normalizeOptions(options = {}) {
378
583
  } else {
379
584
  to = String(options.to ?? DEFAULT_OPTIONS.to).toLowerCase();
380
585
  }
381
- if (!OUTPUT_FORMATS.includes(to)) throw new Error(`Unsupported output format: ${to}. Choose ${OUTPUT_FORMATS.join(', ')}.`);
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
+
382
599
  const quality = Number(options.quality ?? DEFAULT_OPTIONS.quality);
383
- if (!Number.isInteger(quality) || quality < 0 || quality > 100) throw new Error('Quality must be an integer between 0 and 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
+ }
384
607
  const effort = Number(options.effort ?? DEFAULT_OPTIONS.effort);
385
- if (!Number.isInteger(effort) || effort < 0 || effort > 9) throw new Error('Effort must be an integer between 0 and 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
+ }
386
615
  const dimension = (key) => {
387
616
  if (options[key] === undefined) return undefined;
388
617
  const value = Number(options[key]);
389
- if (!Number.isInteger(value) || value < 1 || value > MAX_WIDTH) throw new Error(`${key} must be an integer between 1 and ${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
+ }
390
625
  return value;
391
626
  };
392
627
  const width = dimension('width');
393
628
  const height = dimension('height');
394
629
  const fit = String(options.fit ?? DEFAULT_OPTIONS.fit).toLowerCase();
395
- if (!FIT_MODES.includes(fit)) throw new Error(`Fit must be one of ${FIT_MODES.join(', ')}.`);
396
- if (options.lossless !== undefined && typeof options.lossless !== 'boolean') throw new Error('Lossless must be a boolean.');
397
- if (options.stripMetadata !== undefined && typeof options.stripMetadata !== 'boolean') throw new Error('stripMetadata must be a boolean.');
398
- if (options.clean !== undefined && typeof options.clean !== 'boolean') throw new Error('clean must be a boolean.');
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
+ }
399
658
  const clean = options.clean !== undefined ? Boolean(options.clean) : (options.stripMetadata ?? DEFAULT_OPTIONS.clean);
400
659
  const stripMetadata = clean;
401
660
  const verify = Boolean(options.verify || options.verifyClean);
@@ -404,7 +663,39 @@ function normalizeOptions(options = {}) {
404
663
  const transforms = Array.isArray(options.transforms)
405
664
  ? options.transforms.filter((t) => t && typeof t.apply === 'function')
406
665
  : undefined;
407
- for (const key of ['background', 'svgBackground']) if (options[key] !== undefined && (typeof options[key] !== 'string' || !options[key].trim() || options[key].length > 64)) throw new Error(`${key} must be a non-empty color string of 64 characters or fewer.`);
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
+
408
699
  return {
409
700
  to,
410
701
  width,
@@ -421,20 +712,39 @@ function normalizeOptions(options = {}) {
421
712
  assertAlpha,
422
713
  report,
423
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,
424
721
  lockTarget,
425
722
  strict,
426
723
  overrideLock,
427
724
  policy: options.policy,
428
- maxOutputBytes: options.maxOutputBytes,
429
- targetOutputBytes: options.targetOutputBytes,
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,
430
731
  accept: options.accept,
431
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'),
432
738
  };
433
739
  }
434
740
 
435
741
  function checkDimensions(width, height) {
436
742
  if (!Number.isFinite(width) || !Number.isFinite(height) || width < 1 || height < 1 || width > MAX_WIDTH || height > MAX_WIDTH || width * height > MAX_PIXELS) {
437
- throw new Error(`Image dimensions exceed the ${MAX_WIDTH} px side or pixel-count limit.`);
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
+ });
438
748
  }
439
749
  }
440
750
 
@@ -442,18 +752,69 @@ async function inspectImage(input) {
442
752
  const data = asBuffer(input);
443
753
  const format = detectFormat(data);
444
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
+
445
768
  if (format === 'svg') {
446
769
  const svg = validateSvg(data);
447
- const { width, height } = svgDimensions(svg);
448
- if (width && height && (!Number.isFinite(width) || !Number.isFinite(height) || width <= 0 || height <= 0)) throw new Error('The SVG has invalid intrinsic dimensions.');
449
- return { format, width: width || undefined, height: height || undefined, hasAlpha: true, bytes: data.length, metadata };
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);
450
787
  }
451
- const meta = await sharp(data, { limitInputPixels: MAX_PIXELS, pages: 1, animated: false, failOn: 'error' }).metadata();
452
- checkDimensions(meta.width, meta.height);
453
- return { format, width: meta.width, height: meta.height, hasAlpha: Boolean(meta.hasAlpha), bytes: data.length, metadata };
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
+ };
454
814
  }
455
815
 
456
816
  async function convertImage(input, options = {}) {
817
+ assertRuntimeIsolation();
457
818
  const opts = normalizeOptions(options);
458
819
  const policy = resolvePolicy(opts.policy, opts);
459
820
  const data = asBuffer(input);
@@ -474,6 +835,38 @@ async function convertImage(input, options = {}) {
474
835
  }
475
836
 
476
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
+
477
870
  let format;
478
871
  try {
479
872
  format = detectFormat(data);
@@ -512,42 +905,191 @@ async function convertImage(input, options = {}) {
512
905
  // Policy check 2: Format allowlist & denylist based on detected bytes
513
906
  checkPolicyInput({ policy, data, detectedFormat: format });
514
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
+
515
998
  let source = data;
516
999
  let sourceHasAlpha;
517
- if (format === 'svg') {
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') {
518
1044
  const svg = validateSvg(data);
519
1045
  const dims = svgDimensions(svg);
520
1046
  const aspect = dims.width && dims.height ? dims.height / dims.width : 1;
521
1047
  const fitByCover = opts.fit === 'cover' || opts.fit === 'outside';
522
1048
  const renderMode = opts.width && opts.height
523
1049
  ? (fitByCover === (aspect > opts.height / opts.width) ? 'width' : 'height')
524
- : opts.height && !opts.width ? 'height' : 'width';
1050
+ : opts.height && !opts.width
1051
+ ? 'height'
1052
+ : (!opts.width && !opts.height && aspect > 1)
1053
+ ? 'height'
1054
+ : 'width';
525
1055
  const renderValue = renderMode === 'height' ? (opts.height ?? opts.width ?? 2048) : (opts.width ?? opts.height ?? 2048);
526
1056
  const rasterWidth = renderMode === 'width' ? renderValue : Math.ceil(renderValue / aspect);
527
1057
  const rasterHeight = renderMode === 'height' ? renderValue : Math.ceil(renderValue * aspect);
528
1058
  checkDimensions(rasterWidth, rasterHeight);
529
1059
  const resvgOptions = { background: opts.svgBackground ?? 'rgba(0, 0, 0, 0)' };
530
1060
  resvgOptions.fitTo = { mode: renderMode, value: renderValue };
531
- source = new Resvg(svg, resvgOptions).render().asPng();
532
- const svgMeta = await sharp(source, { limitInputPixels: MAX_PIXELS }).metadata();
1061
+ const ResvgClass = getResvg();
1062
+ source = new ResvgClass(svg, resvgOptions).render().asPng();
1063
+ const svgMeta = await getSharp()(source, { limitInputPixels: MAX_PIXELS }).metadata();
533
1064
  sourceHasAlpha = Boolean(svgMeta.hasAlpha);
534
1065
  } else {
535
- const meta = await sharp(source, { limitInputPixels: MAX_PIXELS, pages: 1, animated: false, failOn: 'error' }).metadata();
1066
+ const meta = await getSharp()(source, { limitInputPixels: MAX_PIXELS, pages: 1, animated: false, failOn: 'error' }).metadata();
536
1067
  checkDimensions(meta.width, meta.height);
537
1068
  sourceHasAlpha = Boolean(meta.hasAlpha);
538
1069
  }
539
1070
 
540
- const transformReports = [];
541
- let rawBufferInfo = null;
542
-
543
1071
  if (opts.transforms && opts.transforms.length > 0) {
544
- let raw = await decodeToRgba(source, format === 'svg' ? 'png' : format);
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
+
545
1083
  for (const step of opts.transforms) {
546
1084
  if (typeof step.apply === 'function') {
547
1085
  const inputDims = { width: raw.width, height: raw.height };
548
1086
  const transformed = await step.apply(raw, opts);
549
1087
  if (!transformed || !transformed.data || !transformed.width || !transformed.height) {
550
- throw new Error(`Transform "${step.name || 'unknown'}" returned an invalid RawImage.`);
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
+ });
551
1093
  }
552
1094
  checkDimensions(transformed.width, transformed.height);
553
1095
  raw = transformed;
@@ -593,9 +1135,20 @@ async function convertImage(input, options = {}) {
593
1135
  targetFormat: opts.to,
594
1136
  });
595
1137
 
596
- const targetQuality = options.quality !== undefined ? Number(options.quality) : evalQ.quality;
597
- const targetLossless = options.lossless !== undefined ? Boolean(options.lossless) : evalQ.lossless;
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);
598
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
+ }
599
1152
  if (opts.to === 'jpeg' && sourceHasAlpha && !opts.background) {
600
1153
  throw new ZapwebpError({
601
1154
  code: 'E_ALPHA_NOT_REPRESENTABLE',
@@ -604,16 +1157,52 @@ async function convertImage(input, options = {}) {
604
1157
  suggestedFix: { background: '#ffffff' },
605
1158
  });
606
1159
  }
607
- if (opts.to === 'jpeg' && targetLossless) throw new Error('JPEG output does not support lossless encoding.');
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
+ }
608
1170
 
609
1171
  const createPipeline = () => {
1172
+ const sharpInstance = getSharp();
610
1173
  if (rawBufferInfo) {
611
- return sharp(rawBufferInfo.buffer, { raw: rawBufferInfo.rawOptions });
1174
+ return sharpInstance(rawBufferInfo.buffer, { raw: rawBufferInfo.rawOptions });
612
1175
  }
613
- return sharp(source, { limitInputPixels: MAX_PIXELS, pages: 1, animated: false, failOn: 'error' });
1176
+ return sharpInstance(source, { limitInputPixels: MAX_PIXELS, pages: 1, animated: false, failOn: 'error' });
614
1177
  };
615
1178
 
616
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
+ }
617
1206
  let p = createPipeline();
618
1207
  if (opts.width || opts.height) p = p.resize({ width: opts.width, height: opts.height, fit: opts.fit, withoutEnlargement: false });
619
1208
  if (opts.background && sourceHasAlpha) p = p.flatten({ background: opts.background });
@@ -633,35 +1222,176 @@ async function convertImage(input, options = {}) {
633
1222
 
634
1223
  let qualityReducedBy = 0;
635
1224
  let maxOutputHit = false;
636
- const limitMaxOutput = policy.limits?.maxOutputBytes || policy.limits?.targetOutputBytes;
1225
+ let compressionIterations = 0;
1226
+ let compressionReport = undefined;
637
1227
 
638
- if (limitMaxOutput && output.length > limitMaxOutput) {
639
- let currentQ = effectiveQuality;
640
- while (output.length > limitMaxOutput && currentQ > 10) {
641
- currentQ -= 5;
642
- const res = await encodeWithQuality(currentQ, false);
643
- output = res.data;
644
- info = res.info;
645
- }
1228
+ const activeCompressor = opts.compressor || getCompressor('compressor');
646
1229
 
647
- if (output.length > limitMaxOutput) {
1230
+ if (limitMaxOutput && output.length > limitMaxOutput) {
1231
+ if (sizeMode === 'strict') {
648
1232
  throw new ZapwebpError({
649
1233
  code: 'E_OUTPUT_TOO_LARGE',
650
- message: `Cannot fit output in ${limitMaxOutput} bytes (reached ${output.length} bytes at quality ${currentQ}).`,
651
- fix: 'Increase maxOutputBytes, or downscale the image.',
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.',
652
1236
  actualBytes: output.length,
653
1237
  maxBytes: limitMaxOutput,
654
- suggestedFix: {
655
- quality: 10,
656
- reason: 'Image exceeds maxOutputBytes even after reducing quality to 10.',
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;
657
1266
  },
1267
+ throwOnUnreachable: sizeMode !== 'flexible',
658
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
+ }
659
1371
  }
1372
+ }
660
1373
 
661
- qualityReducedBy = effectiveQuality - currentQ;
662
- effectiveQuality = currentQ;
663
- effectiveLossless = false;
664
- maxOutputHit = true;
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
+ }
665
1395
  }
666
1396
 
667
1397
  const inputMetadata = detectMetadata(data);
@@ -674,7 +1404,11 @@ async function convertImage(input, options = {}) {
674
1404
  if (opts.assertAlpha && sourceHasAlpha) {
675
1405
  const check = await verifyAlpha(output);
676
1406
  if (!check.hasAlpha) {
677
- throw new Error('Alpha assertion failed: output image does not contain transparent pixels.');
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
+ });
678
1412
  }
679
1413
  }
680
1414
 
@@ -686,7 +1420,31 @@ async function convertImage(input, options = {}) {
686
1420
  ? 'flattened'
687
1421
  : (sourceHasAlpha ? 'preserved' : 'preserved_opaque');
688
1422
 
689
- return {
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({
690
1448
  data: output,
691
1449
  format: opts.to,
692
1450
  width: info.width,
@@ -694,15 +1452,55 @@ async function convertImage(input, options = {}) {
694
1452
  size: output.length,
695
1453
  alphaPreserved,
696
1454
  alphaVerified: alphaPreserved,
1455
+ lossless: effectiveLossless,
1456
+ losslessVerified,
1457
+ sourceQuality,
1458
+ sizeImpact,
697
1459
  backgroundStatus,
698
1460
  transparency,
699
1461
  flattenColor: opts.background || undefined,
700
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
+ },
701
1478
  removedMetadata: inputMetadata.summary,
702
1479
  certificate,
703
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),
704
1492
  targetLockEnforced: Boolean(opts.lockTarget && !opts.overrideLock),
705
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
+ },
706
1504
  policy: {
707
1505
  quality: {
708
1506
  mode: evalQ.mode,
@@ -712,7 +1510,9 @@ async function convertImage(input, options = {}) {
712
1510
  reason: qualityReducedBy > 0 ? 'to fit maxOutputBytes' : 'as specified',
713
1511
  },
714
1512
  limits: {
1513
+ minInputBytes: policy.limits.minInputBytes,
715
1514
  maxInputBytes: policy.limits.maxInputBytes,
1515
+ minOutputBytes: limitMinOutput,
716
1516
  maxOutputBytes: limitMaxOutput,
717
1517
  maxOutputHit,
718
1518
  },
@@ -721,8 +1521,11 @@ async function convertImage(input, options = {}) {
721
1521
  output: opts.to,
722
1522
  accepted: true,
723
1523
  },
1524
+ size: {
1525
+ mode: sizeMode,
1526
+ },
724
1527
  },
725
- };
1528
+ });
726
1529
  }
727
1530
 
728
1531
  /**
@@ -745,6 +1548,14 @@ async function convert(input, options = {}) {
745
1548
  out.passedThrough = Boolean(result.passedThrough);
746
1549
  out.data = result.data;
747
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;
748
1559
  return out;
749
1560
  }
750
1561
 
@@ -757,6 +1568,16 @@ async function convert(input, options = {}) {
757
1568
  async function decodeToRgba(input, format) {
758
1569
  const data = asBuffer(input);
759
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
+ }
760
1581
  let source = data;
761
1582
  if (fmt === 'svg') {
762
1583
  const svg = validateSvg(data);
@@ -764,9 +1585,10 @@ async function decodeToRgba(input, format) {
764
1585
  const width = dims.width || 2048;
765
1586
  const height = dims.height || 2048;
766
1587
  checkDimensions(width, height);
767
- source = new Resvg(svg, { fitTo: { mode: 'original' }, background: 'rgba(0, 0, 0, 0)' }).render().asPng();
1588
+ const ResvgClass = getResvg();
1589
+ source = new ResvgClass(svg, { fitTo: { mode: 'original' }, background: 'rgba(0, 0, 0, 0)' }).render().asPng();
768
1590
  }
769
- const pipeline = sharp(source, { limitInputPixels: MAX_PIXELS, pages: 1, animated: false, failOn: 'error' }).ensureAlpha();
1591
+ const pipeline = getSharp()(source, { limitInputPixels: MAX_PIXELS, pages: 1, animated: false, failOn: 'error' }).ensureAlpha();
770
1592
  const { data: raw, info } = await pipeline.raw().toBuffer({ resolveWithObject: true });
771
1593
  checkDimensions(info.width, info.height);
772
1594
  return {
@@ -784,10 +1606,19 @@ async function decodeToRgba(input, format) {
784
1606
  */
785
1607
  async function encodeFromRgba(image, options = {}) {
786
1608
  if (!image || !image.data || !Number.isInteger(image.width) || !Number.isInteger(image.height)) {
787
- throw new Error('image must be an object with data (RGBA bytes), width, and height.');
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
+ });
788
1614
  }
789
1615
  checkDimensions(image.width, image.height);
790
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
+ }
791
1622
  const raw = Buffer.isBuffer(image.data)
792
1623
  ? image.data
793
1624
  : Buffer.from(image.data.buffer, image.data.byteOffset, image.data.byteLength);
@@ -800,6 +1631,13 @@ async function encodeFromRgba(image, options = {}) {
800
1631
  }
801
1632
  }
802
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
+ }
803
1641
  if (opts.to === 'jpeg' && hasAlpha && !opts.background) {
804
1642
  throw new ZapwebpError({
805
1643
  code: 'E_ALPHA_NOT_REPRESENTABLE',
@@ -808,11 +1646,8 @@ async function encodeFromRgba(image, options = {}) {
808
1646
  suggestedFix: { background: '#ffffff' },
809
1647
  });
810
1648
  }
811
- if (opts.to === 'jpeg' && opts.lossless) {
812
- throw new Error('JPEG output does not support lossless encoding.');
813
- }
814
1649
 
815
- let pipeline = sharp(raw, {
1650
+ let pipeline = getSharp()(raw, {
816
1651
  raw: {
817
1652
  width: image.width,
818
1653
  height: image.height,
@@ -866,9 +1701,14 @@ function parseScales(scaleInput) {
866
1701
  ? scaleInput
867
1702
  : String(scaleInput).split(',').map((s) => s.trim()).filter(Boolean);
868
1703
  const parsed = list.map((item) => {
869
- const num = Number(item);
1704
+ const cleaned = String(item).trim().replace(/x$/i, '');
1705
+ const num = Number(cleaned);
870
1706
  if (!Number.isFinite(num) || num <= 0) {
871
- throw new Error(`Scale multiplier must be a positive number, received: ${item}`);
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
+ });
872
1712
  }
873
1713
  return num;
874
1714
  });
@@ -919,8 +1759,53 @@ function generateSrcset(baseFile, scales = [1], format = 'webp', alt = '') {
919
1759
  return `<img src="${primaryFile}" srcset="${srcsetString}" alt="${alt}">`;
920
1760
  }
921
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
+
922
1782
  module.exports = {
1783
+ // Frozen Seven Public Functions (Enterprise Architecture Core API Surface)
923
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
924
1809
  convertImage,
925
1810
  convertSvgToWebp,
926
1811
  decodeToRgba,
@@ -945,7 +1830,6 @@ module.exports = {
945
1830
  evaluateQuality,
946
1831
  formats,
947
1832
  registry: formats.registry,
948
- registerFormat: formats.registerFormat,
949
1833
  getHandlerByName: formats.getHandlerByName,
950
1834
  getHandlerByMime: formats.getHandlerByMime,
951
1835
  detectFormatHandler: formats.detectFormatHandler,
@@ -953,9 +1837,32 @@ module.exports = {
953
1837
  metadata,
954
1838
  MetadataRegistry: metadata.MetadataRegistry,
955
1839
  metadataRegistry: metadata.metadataRegistry,
956
- registerMetadataHandler: metadata.registerMetadataHandler,
957
1840
  getMetadataHandlers: metadata.getMetadataHandlers,
958
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,
1862
+ getSharp,
1863
+ getResvg,
1864
+ assertRuntimeIsolation,
1865
+ detectEnvironment,
959
1866
  MAX_WIDTH,
960
1867
  INPUT_FORMATS,
961
1868
  OUTPUT_FORMATS,