@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
@@ -0,0 +1,106 @@
1
+ 'use strict';
2
+
3
+ const { createError } = require('../errors');
4
+ const { getSharp, normalizeOptions, checkDimensions } = require('../index');
5
+
6
+ /**
7
+ * Encodes a RawImage into target compressed format bytes.
8
+ *
9
+ * @param {import('../types').RawImage} image - Raw RGBA image
10
+ * @param {string} toFormat - Target format ('webp', 'png', 'jpeg', 'avif', etc.)
11
+ * @param {object} [options] - Encoding options
12
+ * @returns {Promise<Uint8Array>}
13
+ */
14
+ async function encode(image, toFormat, options = {}) {
15
+ if (!image || !image.data || !Number.isInteger(image.width) || !Number.isInteger(image.height)) {
16
+ throw createError('E_CORRUPT_HEADER', 'image must be an object with data (RGBA bytes), width, and height.');
17
+ }
18
+
19
+ checkDimensions(image.width, image.height);
20
+ const target = String(toFormat || 'webp').toLowerCase();
21
+ const opts = normalizeOptions({ ...options, to: target });
22
+
23
+ const raw = Buffer.isBuffer(image.data)
24
+ ? image.data
25
+ : Buffer.from(image.data.buffer, image.data.byteOffset, image.data.byteLength);
26
+
27
+ let hasAlpha = Boolean(image.hasAlpha);
28
+ if (!image.hasAlpha) {
29
+ for (let i = 3; i < raw.length; i += 4) {
30
+ if (raw[i] < 255) {
31
+ hasAlpha = true;
32
+ break;
33
+ }
34
+ }
35
+ }
36
+
37
+ if (target === 'jpeg' && hasAlpha && !opts.background) {
38
+ throw createError(
39
+ 'E_ALPHA_NOT_REPRESENTABLE',
40
+ 'JPEG cannot store transparency. Pass a background color to flatten the image, or choose WebP, PNG, or AVIF.'
41
+ );
42
+ }
43
+
44
+ let pipeline = getSharp()(raw, {
45
+ raw: {
46
+ width: image.width,
47
+ height: image.height,
48
+ channels: 4,
49
+ },
50
+ });
51
+
52
+ if (opts.width || opts.height) {
53
+ pipeline = pipeline.resize({
54
+ width: opts.width,
55
+ height: opts.height,
56
+ fit: opts.fit,
57
+ withoutEnlargement: false,
58
+ });
59
+ }
60
+
61
+ if (opts.background && hasAlpha) {
62
+ pipeline = pipeline.flatten({ background: opts.background });
63
+ }
64
+
65
+ if (!opts.stripMetadata) {
66
+ pipeline = pipeline.withMetadata();
67
+ }
68
+
69
+ switch (target) {
70
+ case 'webp':
71
+ pipeline = pipeline.webp({
72
+ quality: opts.quality,
73
+ lossless: opts.lossless,
74
+ effort: 4,
75
+ });
76
+ break;
77
+ case 'avif':
78
+ pipeline = pipeline.avif({
79
+ quality: opts.quality,
80
+ lossless: opts.lossless,
81
+ effort: 4,
82
+ });
83
+ break;
84
+ case 'png':
85
+ pipeline = pipeline.png({
86
+ compressionLevel: 9,
87
+ });
88
+ break;
89
+ case 'jpeg':
90
+ pipeline = pipeline.jpeg({
91
+ quality: opts.quality,
92
+ mozjpeg: true,
93
+ });
94
+ break;
95
+ default:
96
+ throw createError('E_UNSUPPORTED_FORMAT', `Unsupported output encoding target "${target}".`);
97
+ }
98
+
99
+ const encodedBuffer = await pipeline.toBuffer();
100
+ return new Uint8Array(encodedBuffer.buffer, encodedBuffer.byteOffset, encodedBuffer.byteLength);
101
+ }
102
+
103
+ module.exports = {
104
+ encode,
105
+ };
106
+
@@ -0,0 +1,116 @@
1
+ 'use strict';
2
+
3
+ const { createError } = require('../errors');
4
+ const { assertSvgSafety } = require('../safety/svg');
5
+ const { decode } = require('./decode');
6
+ const { applyTransforms } = require('./transform');
7
+ const { encode } = require('./encode');
8
+ const { defaultJournal } = require('../journal');
9
+ const {
10
+ detectFormat,
11
+ validateImageBytes,
12
+ checkDimensions,
13
+ verifyAlpha,
14
+ detectMetadata,
15
+ cleanBytes,
16
+ MAX_DIMENSION,
17
+ } = require('../index');
18
+
19
+ /**
20
+ * Runs the strict 7-step safety chain pipeline from input bytes to output bytes.
21
+ * Enforces Discipline 7: The safety chain cannot be bypassed.
22
+ *
23
+ * @param {Uint8Array|Buffer} input - Source bytes
24
+ * @param {import('../types').ConvertOptions} options - Options
25
+ * @returns {Promise<Uint8Array>}
26
+ */
27
+ async function runPipeline(input, options = {}) {
28
+ const startTime = Date.now();
29
+
30
+ // Step 1: validateBytes
31
+ validateImageBytes(input);
32
+ const data = Buffer.isBuffer(input) ? input : Buffer.from(input.buffer, input.byteOffset, input.byteLength);
33
+
34
+ // Step 2: checkInputSafety
35
+ const format = detectFormat(data);
36
+ if (format === 'svg') {
37
+ assertSvgSafety(data, options);
38
+ }
39
+
40
+ // Step 3: validateSize
41
+ const maxInputBytes = options.maxInputBytes || options.maxBytes;
42
+ if (maxInputBytes && data.length > maxInputBytes) {
43
+ throw createError('E_TOO_LARGE', `Input size of ${data.length} bytes exceeds maximum limit of ${maxInputBytes} bytes.`);
44
+ }
45
+
46
+ // Step 4: decode
47
+ const rawImage = await decode(data, format, options);
48
+ checkDimensions(rawImage.width, rawImage.height);
49
+
50
+ // Step 5: applyTransforms
51
+ const transforms = Array.isArray(options.transforms) ? options.transforms : [];
52
+ const transformedImage = transforms.length > 0
53
+ ? await applyTransforms(rawImage, transforms, options)
54
+ : rawImage;
55
+
56
+ // Step 6: encode
57
+ const toFormat = options.to || options.format || 'webp';
58
+ let outputBytes = await encode(transformedImage, toFormat, options);
59
+
60
+ // Step 7: verifyOutput
61
+ if (options.clean || options.stripMetadata) {
62
+ outputBytes = await cleanBytes(outputBytes);
63
+ }
64
+
65
+ const maxOutputBytes = options.maxOutputBytes;
66
+ if (maxOutputBytes && outputBytes.length > maxOutputBytes) {
67
+ throw createError('E_OUTPUT_TOO_LARGE', `Output size of ${outputBytes.length} bytes exceeds limit of ${maxOutputBytes} bytes.`);
68
+ }
69
+
70
+ // Record in Transaction Journal (Discipline 4 & ISO 27001 A.8.1)
71
+ const durationMs = Date.now() - startTime;
72
+ defaultJournal.record({
73
+ inputBytes: data,
74
+ outputBytes,
75
+ fromFormat: format,
76
+ toFormat,
77
+ durationMs,
78
+ options,
79
+ });
80
+
81
+ return outputBytes;
82
+ }
83
+
84
+ /**
85
+ * Inspects image bytes without converting.
86
+ * @param {Uint8Array|Buffer} input
87
+ * @returns {Promise<import('../types').InspectResult>}
88
+ */
89
+ async function runInspect(input) {
90
+ validateImageBytes(input);
91
+ const data = Buffer.isBuffer(input) ? input : Buffer.from(input.buffer, input.byteOffset, input.byteLength);
92
+ const format = detectFormat(data);
93
+ const raw = await decode(data, format);
94
+ const metadata = detectMetadata(data);
95
+ const alphaResult = await verifyAlpha(data);
96
+
97
+ return {
98
+ format,
99
+ width: raw.width,
100
+ height: raw.height,
101
+ hasAlpha: alphaResult.hasAlpha,
102
+ bytes: data.length,
103
+ metadata: {
104
+ hasExif: metadata.exif,
105
+ hasXmp: metadata.xmp,
106
+ hasC2pa: metadata.c2pa,
107
+ summary: metadata.summary,
108
+ },
109
+ };
110
+ }
111
+
112
+ module.exports = {
113
+ runPipeline,
114
+ runInspect,
115
+ };
116
+
@@ -0,0 +1,37 @@
1
+ 'use strict';
2
+
3
+ const { createError } = require('../errors');
4
+ const { checkDimensions } = require('../index');
5
+
6
+ /**
7
+ * Executes an ordered chain of TransformStep plugins across a RawImage.
8
+ *
9
+ * @param {import('../types').RawImage} image - Input raw RGBA image
10
+ * @param {import('../types').TransformStep[]} transforms - Array of transform steps
11
+ * @param {object} [options]
12
+ * @returns {Promise<import('../types').RawImage>}
13
+ */
14
+ async function applyTransforms(image, transforms = [], options = {}) {
15
+ let current = image;
16
+
17
+ for (const step of transforms) {
18
+ if (!step || typeof step.apply !== 'function') {
19
+ continue;
20
+ }
21
+
22
+ const transformed = await step.apply(current, options);
23
+ if (!transformed || !transformed.data || !transformed.width || !transformed.height) {
24
+ throw createError('E_TRANSFORM_FAILED', `Transform "${step.name || 'unknown'}" returned an invalid RawImage.`);
25
+ }
26
+
27
+ checkDimensions(transformed.width, transformed.height);
28
+ current = transformed;
29
+ }
30
+
31
+ return current;
32
+ }
33
+
34
+ module.exports = {
35
+ applyTransforms,
36
+ };
37
+
@@ -0,0 +1,34 @@
1
+ 'use strict';
2
+
3
+ const { ZapwebpError, ERROR_CATALOG } = require('@zapwebp/shared');
4
+
5
+ /**
6
+ * Creates a standardized ZapwebpError with error code, message, fix, and documentation link.
7
+ * Enforces Discipline 5: No silent failures.
8
+ *
9
+ * @param {string} code - Error code identifier
10
+ * @param {string} [customMessage] - Optional custom context message
11
+ * @param {object} [details] - Additional contextual properties
12
+ * @returns {ZapwebpError}
13
+ */
14
+ function createError(code, customMessage, details = {}) {
15
+ const definition = ERROR_CATALOG[code] || {};
16
+ const message = customMessage || definition.message || `An error occurred with code ${code}`;
17
+ const fix = details.fix || definition.fix || 'Check input parameters or see documentation.';
18
+ const docs = details.docs || definition.docs || `https://zapwebp-docs.vercel.app/errors#${code.toLowerCase()}`;
19
+
20
+ return new ZapwebpError({
21
+ code,
22
+ message,
23
+ fix,
24
+ docs,
25
+ ...details,
26
+ });
27
+ }
28
+
29
+ module.exports = {
30
+ ZapwebpError,
31
+ ERROR_CATALOG,
32
+ createError,
33
+ };
34
+
@@ -1,7 +1,5 @@
1
1
  'use strict';
2
2
 
3
- const sharp = require('sharp');
4
-
5
3
  /** @type {import('./registry').FormatHandler} */
6
4
  const avifHandler = {
7
5
  name: 'avif',
@@ -22,7 +20,8 @@ const avifHandler = {
22
20
  },
23
21
 
24
22
  async decode(bytes) {
25
- const { data: raw, info } = await sharp(bytes, { limitInputPixels: 4096 * 4096, pages: 1, animated: false })
23
+ const sharp = require('sharp');
24
+ const { data: raw, info } = await sharp(bytes, { limitInputPixels: 4096 * 4096, pages: 1, animated: false, failOn: 'error' })
26
25
  .ensureAlpha()
27
26
  .raw()
28
27
  .toBuffer({ resolveWithObject: true });
@@ -35,6 +34,7 @@ const avifHandler = {
35
34
  },
36
35
 
37
36
  async encode(image, options = {}) {
37
+ const sharp = require('sharp');
38
38
  const raw = Buffer.isBuffer(image.data)
39
39
  ? image.data
40
40
  : Buffer.from(image.data.buffer, image.data.byteOffset, image.data.byteLength);
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- const sharp = require('sharp');
3
+ const { ZapwebpError } = require('@zapwebp/shared');
4
4
 
5
5
  /** @type {import('./registry').FormatHandler} */
6
6
  const gifHandler = {
@@ -19,7 +19,8 @@ const gifHandler = {
19
19
  },
20
20
 
21
21
  async decode(bytes) {
22
- const { data: raw, info } = await sharp(bytes, { limitInputPixels: 4096 * 4096, pages: 1, animated: false })
22
+ const sharp = require('sharp');
23
+ const { data: raw, info } = await sharp(bytes, { limitInputPixels: 4096 * 4096, pages: 1, animated: false, failOn: 'error' })
23
24
  .ensureAlpha()
24
25
  .raw()
25
26
  .toBuffer({ resolveWithObject: true });
@@ -32,7 +33,11 @@ const gifHandler = {
32
33
  },
33
34
 
34
35
  async encode() {
35
- throw new Error('GIF output encoding is not supported. Zap converts GIF to modern web formats (WebP, PNG, AVIF).');
36
+ throw new ZapwebpError({
37
+ code: 'E_UNSUPPORTED_FORMAT',
38
+ message: 'GIF output encoding is not supported. Zapwebp converts GIF to modern web formats (WebP, PNG, AVIF).',
39
+ fix: 'Choose one of: webp, png, avif, or jpeg.',
40
+ });
36
41
  },
37
42
  };
38
43
 
@@ -28,6 +28,11 @@ registry.register(avifHandler);
28
28
  registry.register(gifHandler);
29
29
  registry.register(tiffHandler);
30
30
 
31
+ try {
32
+ const { icoHandler } = require('@zapwebp/format-ico');
33
+ if (icoHandler) registry.register(icoHandler);
34
+ } catch {}
35
+
31
36
  module.exports = {
32
37
  FormatRegistry,
33
38
  registry,
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- const sharp = require('sharp');
3
+ const { ZapwebpError } = require('@zapwebp/shared');
4
4
 
5
5
  /** @type {import('./registry').FormatHandler} */
6
6
  const jpegHandler = {
@@ -17,7 +17,8 @@ const jpegHandler = {
17
17
  },
18
18
 
19
19
  async decode(bytes) {
20
- const { data: raw, info } = await sharp(bytes, { limitInputPixels: 4096 * 4096, pages: 1, animated: false })
20
+ const sharp = require('sharp');
21
+ const { data: raw, info } = await sharp(bytes, { limitInputPixels: 4096 * 4096, pages: 1, animated: false, failOn: 'error' })
21
22
  .ensureAlpha()
22
23
  .raw()
23
24
  .toBuffer({ resolveWithObject: true });
@@ -31,9 +32,14 @@ const jpegHandler = {
31
32
 
32
33
  async encode(image, options = {}) {
33
34
  if (options.lossless) {
34
- throw new Error('JPEG output does not support lossless encoding.');
35
+ throw new ZapwebpError({
36
+ code: 'E_INVALID_CONFIG',
37
+ message: 'JPEG output does not support lossless encoding.',
38
+ fix: 'Choose WebP, PNG, or AVIF for lossless output, or set lossless: false.',
39
+ });
35
40
  }
36
41
 
42
+ const sharp = require('sharp');
37
43
  const raw = Buffer.isBuffer(image.data)
38
44
  ? image.data
39
45
  : Buffer.from(image.data.buffer, image.data.byteOffset, image.data.byteLength);
@@ -48,7 +54,12 @@ const jpegHandler = {
48
54
  }
49
55
 
50
56
  if (hasAlpha && !options.background) {
51
- throw new Error('JPEG cannot store transparency. Pass a background color to flatten the image, or choose WebP, PNG, or AVIF.');
57
+ throw new ZapwebpError({
58
+ code: 'E_ALPHA_NOT_REPRESENTABLE',
59
+ message: 'JPEG cannot store transparency. Pass a background color to flatten the image, or choose WebP, PNG, or AVIF.',
60
+ fix: 'Pass background: "#ffffff" or choose WebP/PNG/AVIF.',
61
+ suggestedFix: { background: '#ffffff' },
62
+ });
52
63
  }
53
64
 
54
65
  let pipeline = sharp(raw, {
@@ -1,7 +1,5 @@
1
1
  'use strict';
2
2
 
3
- const sharp = require('sharp');
4
-
5
3
  const PNG_HEADER = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
6
4
 
7
5
  /** @type {import('./registry').FormatHandler} */
@@ -20,7 +18,8 @@ const pngHandler = {
20
18
  },
21
19
 
22
20
  async decode(bytes) {
23
- const { data: raw, info } = await sharp(bytes, { limitInputPixels: 4096 * 4096, pages: 1, animated: false })
21
+ const sharp = require('sharp');
22
+ const { data: raw, info } = await sharp(bytes, { limitInputPixels: 4096 * 4096, pages: 1, animated: false, failOn: 'error' })
24
23
  .ensureAlpha()
25
24
  .raw()
26
25
  .toBuffer({ resolveWithObject: true });
@@ -33,6 +32,7 @@ const pngHandler = {
33
32
  },
34
33
 
35
34
  async encode(image, options = {}) {
35
+ const sharp = require('sharp');
36
36
  const raw = Buffer.isBuffer(image.data)
37
37
  ? image.data
38
38
  : Buffer.from(image.data.buffer, image.data.byteOffset, image.data.byteLength);
@@ -1,7 +1,6 @@
1
1
  'use strict';
2
2
 
3
- const { Resvg } = require('@resvg/resvg-js');
4
- const sharp = require('sharp');
3
+ const { ZapwebpError } = require('@zapwebp/shared');
5
4
 
6
5
  /**
7
6
  * Validates an SVG input buffer or string.
@@ -11,16 +10,32 @@ const sharp = require('sharp');
11
10
  function validateSvgString(input) {
12
11
  const svg = Buffer.isBuffer(input) ? input.toString('utf8') : String(input);
13
12
  if (Buffer.byteLength(svg) === 0 || !/<svg(?:\s|\/?>)/i.test(svg)) {
14
- throw new Error('This file does not contain a valid SVG document.');
13
+ throw new ZapwebpError({
14
+ code: 'E_CORRUPT_HEADER',
15
+ message: 'This file does not contain a valid SVG document.',
16
+ fix: 'Verify the file begins with an <svg> tag and is well-formed XML.',
17
+ });
15
18
  }
16
- if (/<(?:script|foreignObject)\b/i.test(svg) || /\bon\w+\s*=/i.test(svg)) {
17
- throw new Error('This SVG contains active content and cannot be converted.');
19
+ if (/<(?:script|foreignObject)\b/i.test(svg) || /\bon\w+\s*=/i.test(svg) || /javascript:/i.test(svg)) {
20
+ throw new ZapwebpError({
21
+ code: 'E_UNSAFE_SVG',
22
+ message: 'This SVG contains active content and cannot be converted.',
23
+ fix: 'Remove <script>, inline on* handlers, or javascript: URI schemes before converting.',
24
+ });
18
25
  }
19
26
  if (/<!ENTITY\b/i.test(svg)) {
20
- throw new Error('Custom XML entities are not supported.');
27
+ throw new ZapwebpError({
28
+ code: 'E_UNSAFE_SVG',
29
+ message: 'Custom XML entities are not supported.',
30
+ fix: 'Remove <!ENTITY> declarations from the SVG markup.',
31
+ });
21
32
  }
22
33
  if (/<!DOCTYPE\b/i.test(svg)) {
23
- throw new Error('DOCTYPE declarations are not supported.');
34
+ throw new ZapwebpError({
35
+ code: 'E_UNSAFE_SVG',
36
+ message: 'DOCTYPE declarations are not supported.',
37
+ fix: 'Remove <!DOCTYPE> declarations from the SVG markup.',
38
+ });
24
39
  }
25
40
  return svg;
26
41
  }
@@ -39,6 +54,37 @@ function getSvgDimensions(svg) {
39
54
  return { width, height };
40
55
  }
41
56
 
57
+ let _cachedResvg = null;
58
+ function getResvg() {
59
+ if (_cachedResvg) return _cachedResvg;
60
+ try {
61
+ const mod = require('@resvg/resvg-js');
62
+ _cachedResvg = mod.Resvg || mod;
63
+ return _cachedResvg;
64
+ } catch (err) {
65
+ throw new ZapwebpError({
66
+ code: 'E_ENGINE_UNAVAILABLE',
67
+ message: 'Native resvg engine is not available: ' + (err && err.message ? err.message : String(err)),
68
+ fix: 'Install @resvg/resvg-js or ensure native prebuilts are compiled for this architecture.',
69
+ });
70
+ }
71
+ }
72
+
73
+ let _cachedSharp = null;
74
+ function getSharp() {
75
+ if (_cachedSharp) return _cachedSharp;
76
+ try {
77
+ _cachedSharp = require('sharp');
78
+ return _cachedSharp;
79
+ } catch (err) {
80
+ throw new ZapwebpError({
81
+ code: 'E_ENGINE_UNAVAILABLE',
82
+ message: 'Native sharp engine is not available: ' + (err && err.message ? err.message : String(err)),
83
+ fix: 'Install sharp via "npm install sharp" or ensure native prebuilts are compiled for this architecture.',
84
+ });
85
+ }
86
+ }
87
+
42
88
  /** @type {import('./registry').FormatHandler} */
43
89
  const svgHandler = {
44
90
  name: 'svg',
@@ -54,17 +100,28 @@ const svgHandler = {
54
100
  return /<svg(?:\s|\/?>)/i.test(sample) || /^<\?xml[\s\S]*?<svg(?:\s|\/?>)/i.test(sample);
55
101
  },
56
102
 
57
- async decode(bytes) {
103
+ async decode(bytes, options = {}) {
104
+ const Resvg = getResvg();
105
+ const sharp = getSharp();
58
106
  const svg = validateSvgString(bytes);
59
107
  const dims = getSvgDimensions(svg);
60
- const width = dims.width || 2048;
61
- const height = dims.height || 2048;
108
+
109
+ // Target-width direct rasterization (Optimization 3)
110
+ let fitTo = { mode: 'original' };
111
+ if (options.width && options.height) {
112
+ fitTo = { mode: 'width', value: options.width };
113
+ } else if (options.width) {
114
+ fitTo = { mode: 'width', value: options.width };
115
+ } else if (options.height) {
116
+ fitTo = { mode: 'height', value: options.height };
117
+ }
118
+
62
119
  const resvg = new Resvg(svg, {
63
- fitTo: { mode: 'original' },
64
- background: 'rgba(0, 0, 0, 0)',
120
+ fitTo,
121
+ background: options.background || 'rgba(0, 0, 0, 0)',
65
122
  });
66
123
  const pngBuffer = resvg.render().asPng();
67
- const { data: raw, info } = await sharp(pngBuffer, { limitInputPixels: 4096 * 4096 })
124
+ const { data: raw, info } = await sharp(pngBuffer, { limitInputPixels: 4096 * 4096, failOn: 'error' })
68
125
  .ensureAlpha()
69
126
  .raw()
70
127
  .toBuffer({ resolveWithObject: true });
@@ -77,7 +134,11 @@ const svgHandler = {
77
134
  },
78
135
 
79
136
  async encode() {
80
- throw new Error('SVG output encoding from raster is not supported. Zap converts SVG to modern raster formats (WebP, PNG, AVIF).');
137
+ throw new ZapwebpError({
138
+ code: 'E_UNSUPPORTED_FORMAT',
139
+ message: 'SVG output encoding from raster is not supported. Zapwebp converts SVG to modern raster formats (WebP, PNG, AVIF).',
140
+ fix: 'Choose webp, png, avif, or jpeg as output target.',
141
+ });
81
142
  },
82
143
  };
83
144
 
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- const sharp = require('sharp');
3
+ const { ZapwebpError } = require('@zapwebp/shared');
4
4
 
5
5
  /** @type {import('./registry').FormatHandler} */
6
6
  const tiffHandler = {
@@ -23,7 +23,8 @@ const tiffHandler = {
23
23
  },
24
24
 
25
25
  async decode(bytes) {
26
- const { data: raw, info } = await sharp(bytes, { limitInputPixels: 4096 * 4096, pages: 1, animated: false })
26
+ const sharp = require('sharp');
27
+ const { data: raw, info } = await sharp(bytes, { limitInputPixels: 4096 * 4096, pages: 1, animated: false, failOn: 'error' })
27
28
  .ensureAlpha()
28
29
  .raw()
29
30
  .toBuffer({ resolveWithObject: true });
@@ -36,7 +37,11 @@ const tiffHandler = {
36
37
  },
37
38
 
38
39
  async encode() {
39
- throw new Error('TIFF output encoding is not supported. Zap converts TIFF to modern web formats (WebP, PNG, AVIF).');
40
+ throw new ZapwebpError({
41
+ code: 'E_UNSUPPORTED_FORMAT',
42
+ message: 'TIFF output encoding is not supported. Zapwebp converts TIFF to modern web formats (WebP, PNG, AVIF).',
43
+ fix: 'Choose one of: webp, png, avif, or jpeg.',
44
+ });
40
45
  },
41
46
  };
42
47
 
@@ -1,7 +1,5 @@
1
1
  'use strict';
2
2
 
3
- const sharp = require('sharp');
4
-
5
3
  /** @type {import('./registry').FormatHandler} */
6
4
  const webpHandler = {
7
5
  name: 'webp',
@@ -18,7 +16,8 @@ const webpHandler = {
18
16
  },
19
17
 
20
18
  async decode(bytes) {
21
- const { data: raw, info } = await sharp(bytes, { limitInputPixels: 4096 * 4096, pages: 1, animated: false })
19
+ const sharp = require('sharp');
20
+ const { data: raw, info } = await sharp(bytes, { limitInputPixels: 4096 * 4096, pages: 1, animated: false, failOn: 'error' })
22
21
  .ensureAlpha()
23
22
  .raw()
24
23
  .toBuffer({ resolveWithObject: true });
@@ -31,6 +30,7 @@ const webpHandler = {
31
30
  },
32
31
 
33
32
  async encode(image, options = {}) {
33
+ const sharp = require('sharp');
34
34
  const raw = Buffer.isBuffer(image.data)
35
35
  ? image.data
36
36
  : Buffer.from(image.data.buffer, image.data.byteOffset, image.data.byteLength);