@zapwebp/core 0.0.0-stage → 1.1.1
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/LICENSE +21 -0
- package/README.md +213 -2
- package/package.json +39 -3
- package/src/formats/avif.js +70 -0
- package/src/formats/gif.js +40 -0
- package/src/formats/index.d.ts +40 -0
- package/src/formats/index.js +47 -0
- package/src/formats/jpeg.js +78 -0
- package/src/formats/png.js +64 -0
- package/src/formats/registry.js +154 -0
- package/src/formats/svg.js +87 -0
- package/src/formats/tiff.js +44 -0
- package/src/formats/webp.js +67 -0
- package/src/index.d.ts +123 -0
- package/src/index.js +999 -0
- package/src/metadata/c2pa.js +30 -0
- package/src/metadata/exif.js +45 -0
- package/src/metadata/icc.js +30 -0
- package/src/metadata/index.js +37 -0
- package/src/metadata/png-text.js +32 -0
- package/src/metadata/registry.js +191 -0
- package/src/metadata/xmp.js +43 -0
- package/src/policy.js +254 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Eldrex Delos Reyes Bula
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,214 @@
|
|
|
1
|
-
|
|
1
|
+
<p align="center">
|
|
2
|
+
<img src="../../public/assets/packages-readme-icons/zapwebp-core.svg" width="120" height="120" alt="@zapwebp/core logo" />
|
|
3
|
+
</p>
|
|
2
4
|
|
|
3
|
-
|
|
5
|
+
# @zapwebp/core
|
|
6
|
+
|
|
7
|
+
The shared image conversion, format detection, SVG validation, and metadata cleaning engine behind the entire Zap ecosystem. Provides format-aware, memory-safe conversion across SVG, PNG, JPEG, WebP, AVIF, GIF, and TIFF with strict alpha preservation and zero telemetry.
|
|
8
|
+
|
|
9
|
+
Documentation: [https://zapwebp.vercel.app/formats](https://zapwebp.vercel.app/formats)
|
|
10
|
+
|
|
11
|
+
---
|
|
12
|
+
|
|
13
|
+
## Features
|
|
14
|
+
|
|
15
|
+
- **Format Autodetection:** Sniffs image headers from raw magic bytes and XML patterns, never relying on file extensions alone.
|
|
16
|
+
- **Rust-Powered SVG Engine:** Rasterizes SVG vectors via `@resvg/resvg-js` over transparent canvases with subpixel accuracy.
|
|
17
|
+
- **Libvips Raster Pipeline:** High-throughput streaming image transform pipeline powered by `sharp`.
|
|
18
|
+
- **Alpha Guarantees:** Transparency is preserved across WebP, PNG, and AVIF. Converting transparent inputs to JPEG without an explicit background color throws a structured `alpha_not_representable` error.
|
|
19
|
+
- **Clean Mode & AI Provenance:** Detects AI-generated metadata (C2PA Content Credentials, Midjourney, Adobe Firefly, Stable Diffusion) and generates cryptographically signed Clean Certificates.
|
|
20
|
+
- **Multiplier Tooling:** Utility functions for parsing scale arrays (`@1x`, `@2x`, `@3x`), generating filename suffixes, and building ready-to-paste `<img srcset>` HTML snippets.
|
|
21
|
+
- **Security Sandboxing:** Rejects SVGs containing active scripts (`<script>`, inline handlers), external entity expansions (XXE), or remote network references.
|
|
22
|
+
|
|
23
|
+
---
|
|
24
|
+
|
|
25
|
+
## Installation
|
|
26
|
+
|
|
27
|
+
```bash
|
|
28
|
+
pnpm add @zapwebp/core
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
---
|
|
32
|
+
|
|
33
|
+
## API Reference
|
|
34
|
+
|
|
35
|
+
### 1. `convertImage(input, options)`
|
|
36
|
+
Converts any supported image format to WebP, PNG, JPEG, or AVIF.
|
|
37
|
+
|
|
38
|
+
```typescript
|
|
39
|
+
function convertImage(
|
|
40
|
+
input: Buffer | Uint8Array | string,
|
|
41
|
+
options?: ConvertOptions
|
|
42
|
+
): Promise<Buffer>
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
#### Options (`ConvertOptions`)
|
|
46
|
+
| Property | Type | Default | Description |
|
|
47
|
+
|---|---|---|---|
|
|
48
|
+
| `to` | `'webp' \| 'png' \| 'jpeg' \| 'avif'` | `'webp'` | Target output format |
|
|
49
|
+
| `from` | string | autodetected | Source format override |
|
|
50
|
+
| `width` | number | source | Constrain maximum width (1–4096) |
|
|
51
|
+
| `height` | number | source | Constrain maximum height (1–4096) |
|
|
52
|
+
| `fit` | `'contain' \| 'cover' \| 'fill' \| 'inside' \| 'outside'` | `'contain'` | Resize strategy |
|
|
53
|
+
| `quality` | number | `85` | Compression quality rating (1–100) |
|
|
54
|
+
| `lossless` | boolean | `false` | Lossless encoding where supported |
|
|
55
|
+
| `background` | string | `null` | Hex color (e.g. `'#ffffff'`). Required when alpha input is converted to JPEG. |
|
|
56
|
+
| `stripMetadata` | boolean | `true` | Strip EXIF, XMP, and ICC profiles |
|
|
57
|
+
|
|
58
|
+
#### Example
|
|
59
|
+
```javascript
|
|
60
|
+
const { convertImage } = require('@zapwebp/core');
|
|
61
|
+
|
|
62
|
+
// Convert SVG to WebP with target width
|
|
63
|
+
const webpBuffer = await convertImage(svgString, {
|
|
64
|
+
to: 'webp',
|
|
65
|
+
width: 512,
|
|
66
|
+
quality: 90,
|
|
67
|
+
});
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
---
|
|
71
|
+
|
|
72
|
+
### 2. `inspectImage(input)`
|
|
73
|
+
Analyzes image dimensions, format, color space, alpha transparency, and AI provenance hints.
|
|
74
|
+
|
|
75
|
+
```typescript
|
|
76
|
+
function inspectImage(input: Buffer | Uint8Array | string): Promise<{
|
|
77
|
+
format: string;
|
|
78
|
+
width: number;
|
|
79
|
+
height: number;
|
|
80
|
+
hasAlpha: boolean;
|
|
81
|
+
channels: number;
|
|
82
|
+
space: string;
|
|
83
|
+
bytes: number;
|
|
84
|
+
aiProvenanceHints: string[];
|
|
85
|
+
}>
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
#### Example
|
|
89
|
+
```javascript
|
|
90
|
+
const { inspectImage } = require('@zapwebp/core');
|
|
91
|
+
|
|
92
|
+
const info = await inspectImage(imageBuffer);
|
|
93
|
+
console.log(info.format, info.width, info.hasAlpha, info.aiProvenanceHints);
|
|
94
|
+
// => 'png', 1024, true, ['C2PA Manifest detected']
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
---
|
|
98
|
+
|
|
99
|
+
### 3. `detectFormat(input)`
|
|
100
|
+
Detects image format from magic bytes and XML markers. Throws if unrecognized or unsupported.
|
|
101
|
+
|
|
102
|
+
```javascript
|
|
103
|
+
const { detectFormat } = require('@zapwebp/core');
|
|
104
|
+
|
|
105
|
+
const format = detectFormat(buffer); // 'svg', 'png', 'jpeg', 'webp', 'avif', 'gif', 'tiff'
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
---
|
|
109
|
+
|
|
110
|
+
### 4. Raw Pixel Pipeline: `decodeToRgba` & `encodeFromRgba`
|
|
111
|
+
Provides direct access to raw RGBA pixel buffers for custom transforms.
|
|
112
|
+
|
|
113
|
+
```javascript
|
|
114
|
+
const { decodeToRgba, encodeFromRgba } = require('@zapwebp/core');
|
|
115
|
+
|
|
116
|
+
// Decode image to raw 8-bit RGBA buffer
|
|
117
|
+
const { data, width, height, channels } = await decodeToRgba(inputBuffer);
|
|
118
|
+
|
|
119
|
+
// Process raw pixel buffer...
|
|
120
|
+
|
|
121
|
+
// Encode raw RGBA back to modern format
|
|
122
|
+
const outputBuffer = await encodeFromRgba(data, { width, height }, {
|
|
123
|
+
to: 'webp',
|
|
124
|
+
quality: 85,
|
|
125
|
+
});
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
---
|
|
129
|
+
|
|
130
|
+
### 5. Multipliers & Responsive Helpers
|
|
131
|
+
|
|
132
|
+
#### `parseScales(scales)`
|
|
133
|
+
Parses and validates multiplier scale numbers:
|
|
134
|
+
```javascript
|
|
135
|
+
const { parseScales } = require('@zapwebp/core');
|
|
136
|
+
parseScales([1, 2, 3]); // => [1, 2, 3]
|
|
137
|
+
parseScales('1, 2x, 3'); // => [1, 2, 3]
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
#### `outputName(inputPath, format, scale)`
|
|
141
|
+
Constructs output filename following standard scale conventions:
|
|
142
|
+
```javascript
|
|
143
|
+
const { outputName } = require('@zapwebp/core');
|
|
144
|
+
outputName('logo.svg', 'webp', 2); // => 'logo@2x.webp'
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
#### `generateSrcset(baseFile, scales, format, alt)`
|
|
148
|
+
Generates responsive `<img srcset>` HTML markup:
|
|
149
|
+
```javascript
|
|
150
|
+
const { generateSrcset } = require('@zapwebp/core');
|
|
151
|
+
const html = generateSrcset('hero.png', [1, 2, 3], 'webp', 'Hero Banner');
|
|
152
|
+
// => <img src="hero.webp" srcset="hero.webp 1x, hero@2x.webp 2x, hero@3x.webp 3x" alt="Hero Banner">
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
---
|
|
156
|
+
|
|
157
|
+
### 6. Clean Mode & Certificate Issuance
|
|
158
|
+
|
|
159
|
+
#### `detectMetadata(input)`
|
|
160
|
+
Inspects file for EXIF, XMP, C2PA, and software attribution markers.
|
|
161
|
+
|
|
162
|
+
#### `generateCleanCertificate(input, output)`
|
|
163
|
+
Verifies metadata removal and generates a cryptographically verifiable Clean Certificate:
|
|
164
|
+
```javascript
|
|
165
|
+
const { generateCleanCertificate } = require('@zapwebp/core');
|
|
166
|
+
|
|
167
|
+
const cert = await generateCleanCertificate(sourceBuffer, cleanOutputBuffer);
|
|
168
|
+
console.log(cert.clean, cert.sha256, cert.metadataChunksRemoved);
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
---
|
|
172
|
+
|
|
173
|
+
### 7. Diagnostics & Command Auditing
|
|
174
|
+
|
|
175
|
+
#### `verifyAlpha(input)`
|
|
176
|
+
Checks if an output buffer retains transparent pixels:
|
|
177
|
+
```javascript
|
|
178
|
+
const { verifyAlpha } = require('@zapwebp/core');
|
|
179
|
+
const hasAlpha = await verifyAlpha(webpBuffer);
|
|
180
|
+
```
|
|
181
|
+
|
|
182
|
+
#### `auditConversionCommand(commandString)`
|
|
183
|
+
Lints shell commands (e.g. `magick convert input.svg output.jpg`) for alpha loss and recommends safe Zap equivalents:
|
|
184
|
+
```javascript
|
|
185
|
+
const { auditConversionCommand } = require('@zapwebp/core');
|
|
186
|
+
const audit = auditConversionCommand('magick convert logo.svg logo.jpg');
|
|
187
|
+
// => { safe: false, issues: ['JPEG drops transparency'], recommendedCommand: 'zap logo.svg --to webp' }
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
#### `explainBlackBackground(context)`
|
|
191
|
+
Returns technical root cause and fix for WebP black background defects.
|
|
192
|
+
|
|
193
|
+
---
|
|
194
|
+
|
|
195
|
+
## Constants Reference
|
|
196
|
+
|
|
197
|
+
| Constant | Value | Description |
|
|
198
|
+
|---|---|---|
|
|
199
|
+
| `MAX_WIDTH` | `4096` | Maximum allowable pixel dimension |
|
|
200
|
+
| `INPUT_FORMATS` | `['svg', 'png', 'jpeg', 'webp', 'avif', 'gif', 'tiff']` | Supported input formats |
|
|
201
|
+
| `OUTPUT_FORMATS` | `['webp', 'png', 'jpeg', 'avif']` | Supported output formats |
|
|
202
|
+
| `FIT_MODES` | `['contain', 'cover', 'fill', 'inside', 'outside']` | Supported resize strategies |
|
|
203
|
+
|
|
204
|
+
---
|
|
205
|
+
|
|
206
|
+
## Extensibility & Custom Formats
|
|
207
|
+
|
|
208
|
+
To add support for a new image format to `@zapwebp/core` (e.g. HEIC, JXL), see the [Adding a New Image Format Guide](ADDING_A_FORMAT.md).
|
|
209
|
+
|
|
210
|
+
---
|
|
211
|
+
|
|
212
|
+
## License
|
|
213
|
+
|
|
214
|
+
MIT © [Zapwebp](https://zapwebp.vercel.app/)
|
package/package.json
CHANGED
|
@@ -1,6 +1,42 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zapwebp/core",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "1.1.1",
|
|
4
|
+
"description": "Format-aware image conversion engine with transparency-safe outputs.",
|
|
5
|
+
"main": "src/index.js",
|
|
6
|
+
"types": "src/index.d.ts",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": {
|
|
9
|
+
"types": "./src/index.d.ts",
|
|
10
|
+
"default": "./src/index.js"
|
|
11
|
+
}
|
|
12
|
+
},
|
|
13
|
+
"files": [
|
|
14
|
+
"src",
|
|
15
|
+
"README.md",
|
|
16
|
+
"LICENSE"
|
|
17
|
+
],
|
|
18
|
+
"license": "MIT",
|
|
19
|
+
"engines": {
|
|
20
|
+
"node": ">=22"
|
|
21
|
+
},
|
|
22
|
+
"dependencies": {
|
|
23
|
+
"@resvg/resvg-js": "^2.6.2",
|
|
24
|
+
"sharp": "^0.35.5",
|
|
25
|
+
"@zapwebp/shared": "1.1.2"
|
|
26
|
+
},
|
|
27
|
+
"publishConfig": {
|
|
28
|
+
"access": "public"
|
|
29
|
+
},
|
|
30
|
+
"homepage": "https://zapwebp.vercel.app",
|
|
31
|
+
"repository": {
|
|
32
|
+
"type": "git",
|
|
33
|
+
"url": "https://github.com/Zapwebp/core.git"
|
|
34
|
+
},
|
|
35
|
+
"bugs": {
|
|
36
|
+
"url": "https://github.com/Zapwebp/core/issues"
|
|
37
|
+
},
|
|
38
|
+
"author": "Eldrex Delos Reyes Bula <eldrexdelosreyesbula@gmail.com>",
|
|
39
|
+
"scripts": {
|
|
40
|
+
"test": "node --test"
|
|
41
|
+
}
|
|
6
42
|
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/** @type {import('./registry').FormatHandler} */
|
|
4
|
+
const avifHandler = {
|
|
5
|
+
name: 'avif',
|
|
6
|
+
mimeTypes: Object.freeze(['image/avif']),
|
|
7
|
+
extensions: Object.freeze(['.avif']),
|
|
8
|
+
supportsAlpha: true,
|
|
9
|
+
isInput: true,
|
|
10
|
+
isOutput: true,
|
|
11
|
+
|
|
12
|
+
detect(bytes) {
|
|
13
|
+
if (!bytes || bytes.length < 12) return false;
|
|
14
|
+
const buf = Buffer.isBuffer(bytes) ? bytes : Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
15
|
+
if (buf.subarray(4, 8).toString('ascii') === 'ftyp') {
|
|
16
|
+
const brands = buf.subarray(8, Math.min(buf.length, 4096)).toString('ascii');
|
|
17
|
+
return brands.includes('avif') || brands.includes('avis');
|
|
18
|
+
}
|
|
19
|
+
return false;
|
|
20
|
+
},
|
|
21
|
+
|
|
22
|
+
async decode(bytes) {
|
|
23
|
+
const sharp = require('sharp');
|
|
24
|
+
const { data: raw, info } = await sharp(bytes, { limitInputPixels: 4096 * 4096, pages: 1, animated: false })
|
|
25
|
+
.ensureAlpha()
|
|
26
|
+
.raw()
|
|
27
|
+
.toBuffer({ resolveWithObject: true });
|
|
28
|
+
|
|
29
|
+
return {
|
|
30
|
+
data: new Uint8ClampedArray(raw.buffer, raw.byteOffset, raw.byteLength),
|
|
31
|
+
width: info.width,
|
|
32
|
+
height: info.height,
|
|
33
|
+
};
|
|
34
|
+
},
|
|
35
|
+
|
|
36
|
+
async encode(image, options = {}) {
|
|
37
|
+
const sharp = require('sharp');
|
|
38
|
+
const raw = Buffer.isBuffer(image.data)
|
|
39
|
+
? image.data
|
|
40
|
+
: Buffer.from(image.data.buffer, image.data.byteOffset, image.data.byteLength);
|
|
41
|
+
|
|
42
|
+
let pipeline = sharp(raw, {
|
|
43
|
+
raw: {
|
|
44
|
+
width: image.width,
|
|
45
|
+
height: image.height,
|
|
46
|
+
channels: 4,
|
|
47
|
+
},
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
if (options.background) {
|
|
51
|
+
pipeline = pipeline.flatten({ background: options.background });
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const quality = options.quality !== undefined ? Math.max(1, Math.min(100, Number(options.quality))) : 85;
|
|
55
|
+
const effort = options.effort !== undefined ? Number(options.effort) : 4;
|
|
56
|
+
const lossless = Boolean(options.lossless);
|
|
57
|
+
|
|
58
|
+
return pipeline
|
|
59
|
+
.avif({
|
|
60
|
+
quality,
|
|
61
|
+
lossless,
|
|
62
|
+
effort: Math.max(0, Math.min(9, effort)),
|
|
63
|
+
})
|
|
64
|
+
.toBuffer();
|
|
65
|
+
},
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
module.exports = {
|
|
69
|
+
avifHandler,
|
|
70
|
+
};
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/** @type {import('./registry').FormatHandler} */
|
|
4
|
+
const gifHandler = {
|
|
5
|
+
name: 'gif',
|
|
6
|
+
mimeTypes: Object.freeze(['image/gif']),
|
|
7
|
+
extensions: Object.freeze(['.gif']),
|
|
8
|
+
supportsAlpha: true,
|
|
9
|
+
isInput: true,
|
|
10
|
+
isOutput: false,
|
|
11
|
+
|
|
12
|
+
detect(bytes) {
|
|
13
|
+
if (!bytes || bytes.length < 6) return false;
|
|
14
|
+
const buf = Buffer.isBuffer(bytes) ? bytes : Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
15
|
+
const sig = buf.subarray(0, 6).toString('ascii');
|
|
16
|
+
return sig === 'GIF87a' || sig === 'GIF89a';
|
|
17
|
+
},
|
|
18
|
+
|
|
19
|
+
async decode(bytes) {
|
|
20
|
+
const sharp = require('sharp');
|
|
21
|
+
const { data: raw, info } = await sharp(bytes, { limitInputPixels: 4096 * 4096, pages: 1, animated: false })
|
|
22
|
+
.ensureAlpha()
|
|
23
|
+
.raw()
|
|
24
|
+
.toBuffer({ resolveWithObject: true });
|
|
25
|
+
|
|
26
|
+
return {
|
|
27
|
+
data: new Uint8ClampedArray(raw.buffer, raw.byteOffset, raw.byteLength),
|
|
28
|
+
width: info.width,
|
|
29
|
+
height: info.height,
|
|
30
|
+
};
|
|
31
|
+
},
|
|
32
|
+
|
|
33
|
+
async encode() {
|
|
34
|
+
throw new Error('GIF output encoding is not supported. Zap converts GIF to modern web formats (WebP, PNG, AVIF).');
|
|
35
|
+
},
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
module.exports = {
|
|
39
|
+
gifHandler,
|
|
40
|
+
};
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import type { RawImage, ConvertOptions, InputFormat, OutputFormat } from '../index';
|
|
2
|
+
|
|
3
|
+
export interface FormatHandler<TOptions = ConvertOptions> {
|
|
4
|
+
readonly name: string;
|
|
5
|
+
readonly mimeTypes: readonly string[];
|
|
6
|
+
readonly extensions: readonly string[];
|
|
7
|
+
readonly supportsAlpha: boolean;
|
|
8
|
+
readonly isInput: boolean;
|
|
9
|
+
readonly isOutput: boolean;
|
|
10
|
+
detect(bytes: Uint8Array | Buffer): boolean;
|
|
11
|
+
decode(bytes: Uint8Array | Buffer, options?: object): Promise<RawImage>;
|
|
12
|
+
encode(image: RawImage, options?: TOptions): Promise<Buffer | Uint8Array>;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export class FormatRegistry {
|
|
16
|
+
register(handler: FormatHandler): void;
|
|
17
|
+
getByName(name: string): FormatHandler | undefined;
|
|
18
|
+
getByMime(mime: string): FormatHandler | undefined;
|
|
19
|
+
getByExtension(ext: string): FormatHandler | undefined;
|
|
20
|
+
detect(bytes: Uint8Array | Buffer): FormatHandler | null;
|
|
21
|
+
getAll(): FormatHandler[];
|
|
22
|
+
getSupportedInputs(): string[];
|
|
23
|
+
getSupportedOutputs(): string[];
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export const registry: FormatRegistry;
|
|
27
|
+
export function registerFormat(handler: FormatHandler): void;
|
|
28
|
+
export function getHandlerByName(name: string): FormatHandler | undefined;
|
|
29
|
+
export function getHandlerByMime(mime: string): FormatHandler | undefined;
|
|
30
|
+
export function getHandlerByExtension(ext: string): FormatHandler | undefined;
|
|
31
|
+
export function detectFormatHandler(bytes: Uint8Array | Buffer): FormatHandler | null;
|
|
32
|
+
export function getAllHandlers(): FormatHandler[];
|
|
33
|
+
|
|
34
|
+
export const svgHandler: FormatHandler;
|
|
35
|
+
export const pngHandler: FormatHandler;
|
|
36
|
+
export const jpegHandler: FormatHandler;
|
|
37
|
+
export const webpHandler: FormatHandler;
|
|
38
|
+
export const avifHandler: FormatHandler;
|
|
39
|
+
export const gifHandler: FormatHandler;
|
|
40
|
+
export const tiffHandler: FormatHandler;
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const {
|
|
4
|
+
FormatRegistry,
|
|
5
|
+
registry,
|
|
6
|
+
registerFormat,
|
|
7
|
+
getHandlerByName,
|
|
8
|
+
getHandlerByMime,
|
|
9
|
+
getHandlerByExtension,
|
|
10
|
+
detectFormatHandler,
|
|
11
|
+
getAllHandlers,
|
|
12
|
+
} = require('./registry');
|
|
13
|
+
|
|
14
|
+
const { svgHandler } = require('./svg');
|
|
15
|
+
const { pngHandler } = require('./png');
|
|
16
|
+
const { jpegHandler } = require('./jpeg');
|
|
17
|
+
const { webpHandler } = require('./webp');
|
|
18
|
+
const { avifHandler } = require('./avif');
|
|
19
|
+
const { gifHandler } = require('./gif');
|
|
20
|
+
const { tiffHandler } = require('./tiff');
|
|
21
|
+
|
|
22
|
+
// Register all core built-in format handlers
|
|
23
|
+
registry.register(svgHandler);
|
|
24
|
+
registry.register(pngHandler);
|
|
25
|
+
registry.register(jpegHandler);
|
|
26
|
+
registry.register(webpHandler);
|
|
27
|
+
registry.register(avifHandler);
|
|
28
|
+
registry.register(gifHandler);
|
|
29
|
+
registry.register(tiffHandler);
|
|
30
|
+
|
|
31
|
+
module.exports = {
|
|
32
|
+
FormatRegistry,
|
|
33
|
+
registry,
|
|
34
|
+
registerFormat,
|
|
35
|
+
getHandlerByName,
|
|
36
|
+
getHandlerByMime,
|
|
37
|
+
getHandlerByExtension,
|
|
38
|
+
detectFormatHandler,
|
|
39
|
+
getAllHandlers,
|
|
40
|
+
svgHandler,
|
|
41
|
+
pngHandler,
|
|
42
|
+
jpegHandler,
|
|
43
|
+
webpHandler,
|
|
44
|
+
avifHandler,
|
|
45
|
+
gifHandler,
|
|
46
|
+
tiffHandler,
|
|
47
|
+
};
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/** @type {import('./registry').FormatHandler} */
|
|
4
|
+
const jpegHandler = {
|
|
5
|
+
name: 'jpeg',
|
|
6
|
+
mimeTypes: Object.freeze(['image/jpeg', 'image/jpg']),
|
|
7
|
+
extensions: Object.freeze(['.jpg', '.jpeg']),
|
|
8
|
+
supportsAlpha: false,
|
|
9
|
+
isInput: true,
|
|
10
|
+
isOutput: true,
|
|
11
|
+
|
|
12
|
+
detect(bytes) {
|
|
13
|
+
if (!bytes || bytes.length < 3) return false;
|
|
14
|
+
return bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff;
|
|
15
|
+
},
|
|
16
|
+
|
|
17
|
+
async decode(bytes) {
|
|
18
|
+
const sharp = require('sharp');
|
|
19
|
+
const { data: raw, info } = await sharp(bytes, { limitInputPixels: 4096 * 4096, pages: 1, animated: false })
|
|
20
|
+
.ensureAlpha()
|
|
21
|
+
.raw()
|
|
22
|
+
.toBuffer({ resolveWithObject: true });
|
|
23
|
+
|
|
24
|
+
return {
|
|
25
|
+
data: new Uint8ClampedArray(raw.buffer, raw.byteOffset, raw.byteLength),
|
|
26
|
+
width: info.width,
|
|
27
|
+
height: info.height,
|
|
28
|
+
};
|
|
29
|
+
},
|
|
30
|
+
|
|
31
|
+
async encode(image, options = {}) {
|
|
32
|
+
if (options.lossless) {
|
|
33
|
+
throw new Error('JPEG output does not support lossless encoding.');
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const sharp = require('sharp');
|
|
37
|
+
const raw = Buffer.isBuffer(image.data)
|
|
38
|
+
? image.data
|
|
39
|
+
: Buffer.from(image.data.buffer, image.data.byteOffset, image.data.byteLength);
|
|
40
|
+
|
|
41
|
+
// Check for transparency
|
|
42
|
+
let hasAlpha = false;
|
|
43
|
+
for (let i = 3; i < raw.length; i += 4) {
|
|
44
|
+
if (raw[i] < 255) {
|
|
45
|
+
hasAlpha = true;
|
|
46
|
+
break;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
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.');
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
let pipeline = sharp(raw, {
|
|
55
|
+
raw: {
|
|
56
|
+
width: image.width,
|
|
57
|
+
height: image.height,
|
|
58
|
+
channels: 4,
|
|
59
|
+
},
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
if (options.background && hasAlpha) {
|
|
63
|
+
pipeline = pipeline.flatten({ background: options.background });
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const quality = options.quality !== undefined ? Math.max(1, Math.min(100, Number(options.quality))) : 85;
|
|
67
|
+
return pipeline
|
|
68
|
+
.jpeg({
|
|
69
|
+
quality,
|
|
70
|
+
mozjpeg: true,
|
|
71
|
+
})
|
|
72
|
+
.toBuffer();
|
|
73
|
+
},
|
|
74
|
+
};
|
|
75
|
+
|
|
76
|
+
module.exports = {
|
|
77
|
+
jpegHandler,
|
|
78
|
+
};
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const PNG_HEADER = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
|
|
4
|
+
|
|
5
|
+
/** @type {import('./registry').FormatHandler} */
|
|
6
|
+
const pngHandler = {
|
|
7
|
+
name: 'png',
|
|
8
|
+
mimeTypes: Object.freeze(['image/png']),
|
|
9
|
+
extensions: Object.freeze(['.png']),
|
|
10
|
+
supportsAlpha: true,
|
|
11
|
+
isInput: true,
|
|
12
|
+
isOutput: true,
|
|
13
|
+
|
|
14
|
+
detect(bytes) {
|
|
15
|
+
if (!bytes || bytes.length < 8) return false;
|
|
16
|
+
const buf = Buffer.isBuffer(bytes) ? bytes : Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
17
|
+
return buf.subarray(0, 8).equals(PNG_HEADER);
|
|
18
|
+
},
|
|
19
|
+
|
|
20
|
+
async decode(bytes) {
|
|
21
|
+
const sharp = require('sharp');
|
|
22
|
+
const { data: raw, info } = await sharp(bytes, { limitInputPixels: 4096 * 4096, pages: 1, animated: false })
|
|
23
|
+
.ensureAlpha()
|
|
24
|
+
.raw()
|
|
25
|
+
.toBuffer({ resolveWithObject: true });
|
|
26
|
+
|
|
27
|
+
return {
|
|
28
|
+
data: new Uint8ClampedArray(raw.buffer, raw.byteOffset, raw.byteLength),
|
|
29
|
+
width: info.width,
|
|
30
|
+
height: info.height,
|
|
31
|
+
};
|
|
32
|
+
},
|
|
33
|
+
|
|
34
|
+
async encode(image, options = {}) {
|
|
35
|
+
const sharp = require('sharp');
|
|
36
|
+
const raw = Buffer.isBuffer(image.data)
|
|
37
|
+
? image.data
|
|
38
|
+
: Buffer.from(image.data.buffer, image.data.byteOffset, image.data.byteLength);
|
|
39
|
+
|
|
40
|
+
let pipeline = sharp(raw, {
|
|
41
|
+
raw: {
|
|
42
|
+
width: image.width,
|
|
43
|
+
height: image.height,
|
|
44
|
+
channels: 4,
|
|
45
|
+
},
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
if (options.background) {
|
|
49
|
+
pipeline = pipeline.flatten({ background: options.background });
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const effort = options.effort !== undefined ? Number(options.effort) : 4;
|
|
53
|
+
return pipeline
|
|
54
|
+
.png({
|
|
55
|
+
compressionLevel: Math.max(0, Math.min(9, effort)),
|
|
56
|
+
adaptiveFiltering: true,
|
|
57
|
+
})
|
|
58
|
+
.toBuffer();
|
|
59
|
+
},
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
module.exports = {
|
|
63
|
+
pngHandler,
|
|
64
|
+
};
|