@zapwebp/sdk 0.0.0-stage → 1.1.0
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 +158 -2
- package/package.json +37 -3
- package/src/index.d.ts +83 -0
- package/src/index.js +231 -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,159 @@
|
|
|
1
|
-
|
|
1
|
+
<p align="center">
|
|
2
|
+
<img src="../../public/assets/packages-readme-icons/zapwebp-sdk.svg" width="120" height="120" alt="@zapwebp/sdk logo" />
|
|
3
|
+
</p>
|
|
2
4
|
|
|
3
|
-
|
|
5
|
+
# @zapwebp/sdk
|
|
6
|
+
|
|
7
|
+
Official JavaScript and TypeScript SDK for the Zap image conversion and asset optimization platform. Works offline in-memory by default, or connects to the remote hosted Zap edge service.
|
|
8
|
+
|
|
9
|
+
Documentation: [https://zapwebp.vercel.app/docs](https://zapwebp.vercel.app/docs)
|
|
10
|
+
|
|
11
|
+
---
|
|
12
|
+
|
|
13
|
+
## Features
|
|
14
|
+
|
|
15
|
+
- **Zero-Config In-Memory Execution:** Runs completely offline by default using the `@zapwebp/core` engine. No API keys, no network requests, and zero latency in local development and CI pipelines.
|
|
16
|
+
- **Remote Edge API Support:** Configure `baseUrl: 'https://zapwebp.vercel.app'` to delegate large batch workloads to the hosted serverless API.
|
|
17
|
+
- **Multi-Target Bundling:** Convert an image to multiple formats simultaneously (`to: ['webp', 'avif', 'png']`) in a single call.
|
|
18
|
+
- **Project Asset Optimization:** Automated directory scanning and modern format generation with byte-savings reporting.
|
|
19
|
+
- **Webhook Security:** Built-in cryptographic verification for webhook payloads via HMAC SHA-256.
|
|
20
|
+
|
|
21
|
+
---
|
|
22
|
+
|
|
23
|
+
## Installation
|
|
24
|
+
|
|
25
|
+
```bash
|
|
26
|
+
pnpm add @zapwebp/sdk
|
|
27
|
+
# or
|
|
28
|
+
npm install @zapwebp/sdk
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
---
|
|
32
|
+
|
|
33
|
+
## Quick Starts
|
|
34
|
+
|
|
35
|
+
### 1. Offline Mode (Default)
|
|
36
|
+
|
|
37
|
+
```typescript
|
|
38
|
+
import { Zap } from '@zapwebp/sdk';
|
|
39
|
+
|
|
40
|
+
// Initializes in offline mode (runs via @zapwebp/core in memory)
|
|
41
|
+
const zap = new Zap();
|
|
42
|
+
|
|
43
|
+
// Convert a single image
|
|
44
|
+
const webp = await zap.convert('public/logo.svg', {
|
|
45
|
+
to: 'webp',
|
|
46
|
+
width: 512,
|
|
47
|
+
quality: 85,
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
console.log(`Converted bytes: ${webp.length}, Alpha preserved: ${webp.alphaPreserved}`);
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
### 2. Multi-Target Output
|
|
54
|
+
|
|
55
|
+
```typescript
|
|
56
|
+
// Generates WebP, AVIF, and fallback PNG variants in one pass
|
|
57
|
+
const variants = await zap.convert('assets/banner.png', {
|
|
58
|
+
to: ['webp', 'avif', 'png'],
|
|
59
|
+
width: 1200,
|
|
60
|
+
quality: 80,
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
for (const variant of variants) {
|
|
64
|
+
console.log(`${variant.format}: ${variant.data.length} bytes`);
|
|
65
|
+
}
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
### 3. Inspect Image Properties
|
|
69
|
+
|
|
70
|
+
```typescript
|
|
71
|
+
const info = await zap.inspect('assets/hero.png');
|
|
72
|
+
console.log({
|
|
73
|
+
format: info.format,
|
|
74
|
+
dimensions: `${info.width}x${info.height}`,
|
|
75
|
+
hasAlpha: info.hasAlpha,
|
|
76
|
+
recommendedTargets: info.recommendedTargets,
|
|
77
|
+
});
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
### 4. Optimize Directory Assets
|
|
81
|
+
|
|
82
|
+
```typescript
|
|
83
|
+
const report = await zap.optimize({
|
|
84
|
+
files: ['public/logo.svg', 'public/banner.png'],
|
|
85
|
+
targets: [
|
|
86
|
+
{ to: 'webp', quality: 85 },
|
|
87
|
+
{ to: 'avif', quality: 60 },
|
|
88
|
+
],
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
console.log(`Saved ${report.savedPercent}% of total bytes across ${report.totalFiles} files`);
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
### 5. Remote API Mode
|
|
95
|
+
|
|
96
|
+
```typescript
|
|
97
|
+
// Connects to hosted Zap Edge API
|
|
98
|
+
const remoteZap = new Zap({
|
|
99
|
+
baseUrl: 'https://zapwebp.vercel.app',
|
|
100
|
+
apiKey: process.env.ZAP_API_KEY,
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
const remoteResult = await remoteZap.convert('photo.jpg', { to: 'webp' });
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
### 6. Webhook Signature Verification
|
|
107
|
+
|
|
108
|
+
```typescript
|
|
109
|
+
import { Zap } from '@zapwebp/sdk';
|
|
110
|
+
|
|
111
|
+
const isValid = Zap.verifyWebhookSignature(
|
|
112
|
+
rawBodyBuffer,
|
|
113
|
+
req.headers['x-zap-signature'],
|
|
114
|
+
process.env.ZAP_WEBHOOK_SECRET
|
|
115
|
+
);
|
|
116
|
+
|
|
117
|
+
if (!isValid) {
|
|
118
|
+
return res.status(401).send('Invalid webhook signature');
|
|
119
|
+
}
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
---
|
|
123
|
+
|
|
124
|
+
## TypeScript Types Reference
|
|
125
|
+
|
|
126
|
+
```typescript
|
|
127
|
+
export interface ZapOptions {
|
|
128
|
+
baseUrl?: string;
|
|
129
|
+
apiKey?: string;
|
|
130
|
+
timeoutMs?: number;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export interface ConvertOptions {
|
|
134
|
+
to?: 'webp' | 'png' | 'jpeg' | 'avif' | Array<'webp' | 'png' | 'jpeg' | 'avif'>;
|
|
135
|
+
width?: number;
|
|
136
|
+
height?: number;
|
|
137
|
+
quality?: number;
|
|
138
|
+
lossless?: boolean;
|
|
139
|
+
background?: string;
|
|
140
|
+
clean?: boolean;
|
|
141
|
+
scales?: number[];
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
export interface ConvertResult {
|
|
145
|
+
format: string;
|
|
146
|
+
width: number;
|
|
147
|
+
height: number;
|
|
148
|
+
data: Buffer;
|
|
149
|
+
length: number;
|
|
150
|
+
alphaPreserved: boolean;
|
|
151
|
+
cleanCertificate?: CleanCertificate;
|
|
152
|
+
}
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
---
|
|
156
|
+
|
|
157
|
+
## License
|
|
158
|
+
|
|
159
|
+
MIT © [Zapwebp](https://zapwebp.vercel.app/)
|
package/package.json
CHANGED
|
@@ -1,6 +1,40 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zapwebp/sdk",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "1.1.0",
|
|
4
|
+
"description": "Official TypeScript and JavaScript SDK for Zap / Zapwebp.",
|
|
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
|
+
"@zapwebp/core": "1.1.0"
|
|
24
|
+
},
|
|
25
|
+
"publishConfig": {
|
|
26
|
+
"access": "public"
|
|
27
|
+
},
|
|
28
|
+
"homepage": "https://zapwebp.vercel.app",
|
|
29
|
+
"repository": {
|
|
30
|
+
"type": "git",
|
|
31
|
+
"url": "https://github.com/Zapwebp/sdk.git"
|
|
32
|
+
},
|
|
33
|
+
"bugs": {
|
|
34
|
+
"url": "https://github.com/Zapwebp/sdk/issues"
|
|
35
|
+
},
|
|
36
|
+
"author": "Eldrex Delos Reyes Bula <eldrexdelosreyesbula@gmail.com>",
|
|
37
|
+
"scripts": {
|
|
38
|
+
"test": "node --test"
|
|
39
|
+
}
|
|
6
40
|
}
|
package/src/index.d.ts
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
export type InputFormat = 'svg' | 'png' | 'jpeg' | 'webp' | 'avif' | 'gif' | 'tiff';
|
|
2
|
+
export type OutputFormat = 'webp' | 'png' | 'jpeg' | 'avif';
|
|
3
|
+
export type FitMode = 'contain' | 'cover' | 'fill' | 'inside' | 'outside';
|
|
4
|
+
|
|
5
|
+
export interface ConvertOptions {
|
|
6
|
+
to?: OutputFormat | OutputFormat[];
|
|
7
|
+
width?: number;
|
|
8
|
+
height?: number;
|
|
9
|
+
fit?: FitMode;
|
|
10
|
+
quality?: number;
|
|
11
|
+
lossless?: boolean;
|
|
12
|
+
effort?: number;
|
|
13
|
+
background?: string;
|
|
14
|
+
stripMetadata?: boolean;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export interface ConvertResult {
|
|
18
|
+
data: Buffer;
|
|
19
|
+
format: OutputFormat;
|
|
20
|
+
width: number;
|
|
21
|
+
height: number;
|
|
22
|
+
size: number;
|
|
23
|
+
alphaPreserved: boolean;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export interface ImageInspection {
|
|
27
|
+
format: InputFormat;
|
|
28
|
+
width?: number;
|
|
29
|
+
height?: number;
|
|
30
|
+
hasAlpha: boolean;
|
|
31
|
+
bytes: number;
|
|
32
|
+
recommendedTargets: Array<{ to: OutputFormat; reason: string }>;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface OptimizeTarget {
|
|
36
|
+
to: OutputFormat;
|
|
37
|
+
quality?: number;
|
|
38
|
+
width?: number;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export interface OptimizeResult {
|
|
42
|
+
totalBytesBefore: number;
|
|
43
|
+
totalBytesAfter: number;
|
|
44
|
+
savedPercent: number;
|
|
45
|
+
files: Array<{
|
|
46
|
+
input: string;
|
|
47
|
+
inputBytes: number;
|
|
48
|
+
outputs: Array<{
|
|
49
|
+
format: OutputFormat;
|
|
50
|
+
bytes: number;
|
|
51
|
+
width: number;
|
|
52
|
+
height: number;
|
|
53
|
+
alphaPreserved: boolean;
|
|
54
|
+
}>;
|
|
55
|
+
savedPercent: number;
|
|
56
|
+
}>;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export interface ZapClientOptions {
|
|
60
|
+
apiKey?: string;
|
|
61
|
+
baseUrl?: string;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export class Zap {
|
|
65
|
+
constructor(options?: ZapClientOptions);
|
|
66
|
+
apiKey: string | null;
|
|
67
|
+
baseUrl: string | null;
|
|
68
|
+
isOffline: boolean;
|
|
69
|
+
|
|
70
|
+
convert(input: Buffer | Uint8Array | string, options?: ConvertOptions & { to?: OutputFormat }): Promise<Buffer & ConvertResult>;
|
|
71
|
+
convert(input: Buffer | Uint8Array | string, options: ConvertOptions & { to: OutputFormat[] }): Promise<ConvertResult[]>;
|
|
72
|
+
inspect(input: Buffer | Uint8Array | string): Promise<ImageInspection>;
|
|
73
|
+
batch(inputs: Array<Buffer | Uint8Array | string>, options?: ConvertOptions): Promise<Array<Buffer & ConvertResult>>;
|
|
74
|
+
optimize(options: { files?: Array<string | Buffer>; targets?: OptimizeTarget[] }): Promise<OptimizeResult>;
|
|
75
|
+
|
|
76
|
+
static verifyWebhookSignature(payload: string | Buffer, signature: string, secret: string): boolean;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export function createZapClient(options?: ZapClientOptions): Zap;
|
|
80
|
+
|
|
81
|
+
export const INPUT_FORMATS: readonly InputFormat[];
|
|
82
|
+
export const OUTPUT_FORMATS: readonly OutputFormat[];
|
|
83
|
+
|
package/src/index.js
ADDED
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const fs = require('node:fs/promises');
|
|
4
|
+
const path = require('node:path');
|
|
5
|
+
const crypto = require('node:crypto');
|
|
6
|
+
const core = require('@zapwebp/core');
|
|
7
|
+
|
|
8
|
+
const { convertImage, convert, inspectImage, detectFormat, outputName, INPUT_FORMATS, OUTPUT_FORMATS } = core;
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Normalizes input into a Buffer.
|
|
12
|
+
* @param {Buffer|Uint8Array|string} input - File path, URL, or raw bytes
|
|
13
|
+
* @returns {Promise<{ buffer: Buffer, filename: string }>}
|
|
14
|
+
*/
|
|
15
|
+
async function resolveInput(input) {
|
|
16
|
+
if (Buffer.isBuffer(input)) {
|
|
17
|
+
return { buffer: input, filename: 'input.bin' };
|
|
18
|
+
}
|
|
19
|
+
if (input instanceof Uint8Array) {
|
|
20
|
+
return { buffer: Buffer.from(input.buffer, input.byteOffset, input.byteLength), filename: 'input.bin' };
|
|
21
|
+
}
|
|
22
|
+
if (typeof input === 'string') {
|
|
23
|
+
if (/^https?:\/\//i.test(input)) {
|
|
24
|
+
const res = await fetch(input);
|
|
25
|
+
if (!res.ok) throw new Error(`Failed to fetch image from URL: ${input} (${res.status} ${res.statusText})`);
|
|
26
|
+
const arrayBuf = await res.arrayBuffer();
|
|
27
|
+
const urlPath = new URL(input).pathname;
|
|
28
|
+
return { buffer: Buffer.from(arrayBuf), filename: path.basename(urlPath) || 'image.bin' };
|
|
29
|
+
}
|
|
30
|
+
const resolved = path.resolve(input);
|
|
31
|
+
const data = await fs.readFile(resolved);
|
|
32
|
+
return { buffer: data, filename: path.basename(resolved) };
|
|
33
|
+
}
|
|
34
|
+
throw new Error('Input must be a file path string, URL, Buffer, or Uint8Array.');
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
class Zap {
|
|
38
|
+
/**
|
|
39
|
+
* @param {object} [options]
|
|
40
|
+
* @param {string} [options.apiKey] - Optional API key (defaults to process.env.ZAP_API_KEY)
|
|
41
|
+
* @param {string} [options.baseUrl] - Optional API endpoint (enables remote HTTP execution)
|
|
42
|
+
*/
|
|
43
|
+
constructor(options = {}) {
|
|
44
|
+
this.apiKey = options.apiKey || process.env.ZAP_API_KEY || null;
|
|
45
|
+
this.baseUrl = options.baseUrl ? options.baseUrl.replace(/\/$/, '') : null;
|
|
46
|
+
this.isOffline = !this.baseUrl && !this.apiKey;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Converts an image to one or multiple target formats.
|
|
51
|
+
* @param {Buffer|Uint8Array|string} input
|
|
52
|
+
* @param {object} [options]
|
|
53
|
+
* @returns {Promise<Buffer|Array<{ format: string, data: Buffer, width: number, height: number, size: number, alphaPreserved: boolean }>>}
|
|
54
|
+
*/
|
|
55
|
+
async convert(input, options = {}) {
|
|
56
|
+
const { buffer } = await resolveInput(input);
|
|
57
|
+
const targets = Array.isArray(options.to) ? options.to : null;
|
|
58
|
+
|
|
59
|
+
if (targets && targets.length > 0) {
|
|
60
|
+
const results = await Promise.all(
|
|
61
|
+
targets.map((to) => convertImage(buffer, { ...options, to }))
|
|
62
|
+
);
|
|
63
|
+
return results.map((r) => ({
|
|
64
|
+
format: r.format,
|
|
65
|
+
data: r.data,
|
|
66
|
+
width: r.width,
|
|
67
|
+
height: r.height,
|
|
68
|
+
size: r.size,
|
|
69
|
+
alphaPreserved: r.alphaPreserved,
|
|
70
|
+
}));
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
if (this.isOffline) {
|
|
74
|
+
return convert(buffer, options);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// Remote API mode
|
|
78
|
+
const formData = new FormData();
|
|
79
|
+
formData.append('svg', new Blob([buffer]), 'input.bin');
|
|
80
|
+
if (options.to) formData.append('to', options.to);
|
|
81
|
+
if (options.width) formData.append('width', String(options.width));
|
|
82
|
+
if (options.height) formData.append('height', String(options.height));
|
|
83
|
+
if (options.quality) formData.append('quality', String(options.quality));
|
|
84
|
+
if (options.lossless !== undefined) formData.append('lossless', String(options.lossless));
|
|
85
|
+
if (options.background) formData.append('background', options.background);
|
|
86
|
+
if (options.fit) formData.append('fit', options.fit);
|
|
87
|
+
|
|
88
|
+
const headers = {};
|
|
89
|
+
if (this.apiKey) headers.Authorization = `Bearer ${this.apiKey}`;
|
|
90
|
+
|
|
91
|
+
const res = await fetch(`${this.baseUrl}/api/v1/convert`, {
|
|
92
|
+
method: 'POST',
|
|
93
|
+
body: formData,
|
|
94
|
+
headers,
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
if (!res.ok) {
|
|
98
|
+
const errorJson = await res.json().catch(() => ({}));
|
|
99
|
+
throw new Error(errorJson.error || `Zap API error: ${res.status} ${res.statusText}`);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const outBuf = Buffer.from(await res.arrayBuffer());
|
|
103
|
+
outBuf.format = options.to || 'webp';
|
|
104
|
+
outBuf.width = Number(res.headers.get('x-zapwebp-width')) || 0;
|
|
105
|
+
outBuf.height = Number(res.headers.get('x-zapwebp-height')) || 0;
|
|
106
|
+
outBuf.alphaPreserved = res.headers.get('x-zapwebp-alpha-preserved') === 'true';
|
|
107
|
+
outBuf.size = outBuf.length;
|
|
108
|
+
outBuf.data = outBuf;
|
|
109
|
+
return outBuf;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* Inspects image properties, dimensions, transparency, and returns target suggestions.
|
|
114
|
+
* @param {Buffer|Uint8Array|string} input
|
|
115
|
+
* @returns {Promise<{ format: string, width?: number, height?: number, hasAlpha: boolean, bytes: number, recommendedTargets: Array<{ to: string, reason: string }> }>}
|
|
116
|
+
*/
|
|
117
|
+
async inspect(input) {
|
|
118
|
+
const { buffer } = await resolveInput(input);
|
|
119
|
+
const details = await inspectImage(buffer);
|
|
120
|
+
const recommendedTargets = details.hasAlpha
|
|
121
|
+
? [
|
|
122
|
+
{ to: 'webp', reason: 'preserves transparency with compact output' },
|
|
123
|
+
{ to: 'png', reason: 'lossless transparency fallback' },
|
|
124
|
+
{ to: 'avif', reason: 'modern compact format with alpha support' },
|
|
125
|
+
]
|
|
126
|
+
: [
|
|
127
|
+
{ to: 'avif', reason: 'compact photographic output' },
|
|
128
|
+
{ to: 'webp', reason: 'broad modern web support' },
|
|
129
|
+
{ to: 'jpeg', reason: 'widely compatible photographic output' },
|
|
130
|
+
];
|
|
131
|
+
return {
|
|
132
|
+
...details,
|
|
133
|
+
recommendedTargets,
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Converts a collection of images concurrently.
|
|
139
|
+
* @param {Array<Buffer|Uint8Array|string>} inputs
|
|
140
|
+
* @param {object} [options]
|
|
141
|
+
* @returns {Promise<Array<any>>}
|
|
142
|
+
*/
|
|
143
|
+
async batch(inputs, options = {}) {
|
|
144
|
+
if (!Array.isArray(inputs)) throw new Error('inputs must be an array.');
|
|
145
|
+
return Promise.all(inputs.map((item) => this.convert(item, options)));
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* Project-level asset optimization tool.
|
|
150
|
+
* @param {object} options
|
|
151
|
+
* @param {Array<string|Buffer>} [options.files]
|
|
152
|
+
* @param {Array<{ to: string, quality?: number, width?: number }>} [options.targets]
|
|
153
|
+
* @returns {Promise<{ totalBytesBefore: number, totalBytesAfter: number, savedPercent: number, files: Array<any> }>}
|
|
154
|
+
*/
|
|
155
|
+
async optimize(options = {}) {
|
|
156
|
+
const files = options.files || [];
|
|
157
|
+
const targets = options.targets || [{ to: 'webp', quality: 85 }, { to: 'avif', quality: 55 }];
|
|
158
|
+
let totalBytesBefore = 0;
|
|
159
|
+
let totalBytesAfter = 0;
|
|
160
|
+
const fileReports = [];
|
|
161
|
+
|
|
162
|
+
for (const file of files) {
|
|
163
|
+
const { buffer, filename } = await resolveInput(file);
|
|
164
|
+
totalBytesBefore += buffer.length;
|
|
165
|
+
const outputs = [];
|
|
166
|
+
let fileOutputBytes = 0;
|
|
167
|
+
|
|
168
|
+
for (const target of targets) {
|
|
169
|
+
const converted = await convertImage(buffer, target);
|
|
170
|
+
fileOutputBytes += converted.size;
|
|
171
|
+
outputs.push({
|
|
172
|
+
format: converted.format,
|
|
173
|
+
bytes: converted.size,
|
|
174
|
+
width: converted.width,
|
|
175
|
+
height: converted.height,
|
|
176
|
+
alphaPreserved: converted.alphaPreserved,
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
totalBytesAfter += fileOutputBytes;
|
|
181
|
+
const saved = buffer.length ? Number(((buffer.length - fileOutputBytes) / buffer.length * 100).toFixed(1)) : 0;
|
|
182
|
+
fileReports.push({
|
|
183
|
+
input: filename,
|
|
184
|
+
inputBytes: buffer.length,
|
|
185
|
+
outputs,
|
|
186
|
+
savedPercent: saved,
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
const savedPercent = totalBytesBefore
|
|
191
|
+
? Number(((totalBytesBefore - totalBytesAfter) / totalBytesBefore * 100).toFixed(1))
|
|
192
|
+
: 0;
|
|
193
|
+
|
|
194
|
+
return {
|
|
195
|
+
totalBytesBefore,
|
|
196
|
+
totalBytesAfter,
|
|
197
|
+
savedPercent,
|
|
198
|
+
files: fileReports,
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* Verifies an incoming webhook HMAC-SHA256 signature.
|
|
204
|
+
* @param {string|Buffer} payload - Raw request body
|
|
205
|
+
* @param {string} signature - Header signature (e.g., "sha256=...")
|
|
206
|
+
* @param {string} secret - Webhook secret key
|
|
207
|
+
* @returns {boolean}
|
|
208
|
+
*/
|
|
209
|
+
static verifyWebhookSignature(payload, signature, secret) {
|
|
210
|
+
if (!payload || !signature || !secret) return false;
|
|
211
|
+
const expected = crypto
|
|
212
|
+
.createHmac('sha256', secret)
|
|
213
|
+
.update(typeof payload === 'string' ? payload : Buffer.from(payload))
|
|
214
|
+
.digest('hex');
|
|
215
|
+
const provided = signature.replace(/^sha256=/i, '').trim();
|
|
216
|
+
if (expected.length !== provided.length) return false;
|
|
217
|
+
return crypto.timingSafeEqual(Buffer.from(expected, 'hex'), Buffer.from(provided, 'hex'));
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
function createZapClient(options) {
|
|
222
|
+
return new Zap(options);
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
module.exports = {
|
|
226
|
+
Zap,
|
|
227
|
+
createZapClient,
|
|
228
|
+
INPUT_FORMATS,
|
|
229
|
+
OUTPUT_FORMATS,
|
|
230
|
+
};
|
|
231
|
+
|