@zapwebp/core 1.1.1 โ 1.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +79 -51
- package/agent.json +180 -0
- package/package.json +8 -2
- package/src/cache.js +145 -0
- package/src/engine/decode.js +60 -0
- package/src/engine/encode.js +106 -0
- package/src/engine/pipeline.js +116 -0
- package/src/engine/transform.js +37 -0
- package/src/errors/index.js +34 -0
- package/src/formats/avif.js +1 -1
- package/src/formats/gif.js +8 -2
- package/src/formats/index.js +5 -0
- package/src/formats/jpeg.js +14 -3
- package/src/formats/png.js +1 -1
- package/src/formats/svg.js +76 -14
- package/src/formats/tiff.js +8 -2
- package/src/formats/webp.js +1 -1
- package/src/index.d.ts +286 -9
- package/src/index.js +951 -80
- package/src/journal/index.js +73 -0
- package/src/metadata/c2pa.js +3 -10
- package/src/metadata/chunk-stripper.js +235 -0
- package/src/metadata/exif.js +3 -11
- package/src/metadata/icc.js +3 -10
- package/src/metadata/png-text.js +3 -10
- package/src/metadata/registry.js +25 -2
- package/src/metadata/xmp.js +3 -16
- package/src/parallel.js +134 -0
- package/src/policy.js +95 -6
- package/src/registry/compression.js +84 -0
- package/src/registry/formats.js +30 -0
- package/src/registry/metadata.js +28 -0
- package/src/registry/transforms.js +76 -0
- package/src/report.js +404 -0
- package/src/safety/path.js +52 -0
- package/src/safety/runtime.js +66 -0
- package/src/safety/ssrf.js +9 -0
- package/src/safety/svg.js +66 -0
- package/src/signals.js +683 -0
- package/src/smart.js +351 -0
- package/src/team-policy.js +319 -0
- package/src/testing.d.ts +18 -0
- package/src/testing.js +114 -0
- package/src/tools.js +240 -0
- package/src/types.ts +68 -0
package/src/smart.js
ADDED
|
@@ -0,0 +1,351 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { ZapwebpError } = require('@zapwebp/shared');
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Smart Optimization Recommendation Mapping
|
|
7
|
+
* Aligns strictly with the Zapwebp Three Missing Pillars Masterplan.
|
|
8
|
+
*/
|
|
9
|
+
const RECOMMENDATION_PROFILES = {
|
|
10
|
+
photo: {
|
|
11
|
+
format: 'avif',
|
|
12
|
+
quality: 55,
|
|
13
|
+
lossless: false,
|
|
14
|
+
fallbackFormat: null,
|
|
15
|
+
reason: 'Photos compress best with AVIF\'s lossy algorithm.',
|
|
16
|
+
},
|
|
17
|
+
photo_text: {
|
|
18
|
+
format: 'webp',
|
|
19
|
+
quality: 80,
|
|
20
|
+
lossless: false,
|
|
21
|
+
fallbackFormat: null,
|
|
22
|
+
reason: 'WebP handles mixed photographic content with text better than AVIF.',
|
|
23
|
+
},
|
|
24
|
+
icon: {
|
|
25
|
+
format: 'webp',
|
|
26
|
+
quality: 100,
|
|
27
|
+
lossless: true,
|
|
28
|
+
fallbackFormat: null,
|
|
29
|
+
reason: 'Icons need pixel-perfect fidelity with lossless WebP encoding.',
|
|
30
|
+
},
|
|
31
|
+
logo: {
|
|
32
|
+
format: 'webp',
|
|
33
|
+
quality: 90,
|
|
34
|
+
lossless: false,
|
|
35
|
+
fallbackFormat: 'png',
|
|
36
|
+
reason: 'Small, sharp logos benefit from WebP at 90 with transparent PNG fallback.',
|
|
37
|
+
},
|
|
38
|
+
screenshot: {
|
|
39
|
+
format: 'webp',
|
|
40
|
+
quality: 85,
|
|
41
|
+
lossless: false,
|
|
42
|
+
fallbackFormat: null,
|
|
43
|
+
reason: 'Good balance for UI screenshots preserving crisp text readability.',
|
|
44
|
+
},
|
|
45
|
+
diagram: {
|
|
46
|
+
format: 'png',
|
|
47
|
+
quality: 100,
|
|
48
|
+
lossless: true,
|
|
49
|
+
fallbackFormat: null,
|
|
50
|
+
reason: 'Lossless PNG preserves sharp technical lines and diagram strokes.',
|
|
51
|
+
},
|
|
52
|
+
graphic_alpha: {
|
|
53
|
+
format: 'avif',
|
|
54
|
+
quality: 65,
|
|
55
|
+
lossless: false,
|
|
56
|
+
fallbackFormat: null,
|
|
57
|
+
reason: 'AVIF handles alpha transparency better than WebP at low-to-medium quality.',
|
|
58
|
+
},
|
|
59
|
+
thumbnail: {
|
|
60
|
+
format: 'webp',
|
|
61
|
+
quality: 60,
|
|
62
|
+
lossless: false,
|
|
63
|
+
fallbackFormat: null,
|
|
64
|
+
reason: 'Small dimensions allow aggressive WebP compression for thumbnails.',
|
|
65
|
+
},
|
|
66
|
+
hero: {
|
|
67
|
+
format: 'avif',
|
|
68
|
+
quality: 60,
|
|
69
|
+
lossless: false,
|
|
70
|
+
fallbackFormat: null,
|
|
71
|
+
reason: 'High-quality hero banners achieve maximum compression with AVIF at 60.',
|
|
72
|
+
},
|
|
73
|
+
banner: {
|
|
74
|
+
format: 'avif',
|
|
75
|
+
quality: 70,
|
|
76
|
+
lossless: false,
|
|
77
|
+
fallbackFormat: null,
|
|
78
|
+
reason: 'Large panoramic banners compress efficiently with AVIF at 70.',
|
|
79
|
+
},
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Computes horizontal and vertical Sobel gradient energy for text and edge detection.
|
|
84
|
+
*
|
|
85
|
+
* @param {Float32Array} luminance
|
|
86
|
+
* @param {number} width
|
|
87
|
+
* @param {number} height
|
|
88
|
+
* @returns {{ edgeDensity: number, gradientSmoothness: number, textDetected: boolean }}
|
|
89
|
+
*/
|
|
90
|
+
function computeSobelSignals(luminance, width, height) {
|
|
91
|
+
if (width < 3 || height < 3) {
|
|
92
|
+
return { edgeDensity: 0, gradientSmoothness: 1, textDetected: false };
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
let totalSobel = 0;
|
|
96
|
+
let horizEnergy = 0;
|
|
97
|
+
let vertEnergy = 0;
|
|
98
|
+
let edgePixelCount = 0;
|
|
99
|
+
const innerPixels = (width - 2) * (height - 2);
|
|
100
|
+
|
|
101
|
+
for (let y = 1; y < height - 1; y++) {
|
|
102
|
+
const row = y * width;
|
|
103
|
+
for (let x = 1; x < width - 1; x++) {
|
|
104
|
+
const idx = row + x;
|
|
105
|
+
|
|
106
|
+
// 3x3 Sobel Operator
|
|
107
|
+
// Gx:
|
|
108
|
+
// -1 0 1
|
|
109
|
+
// -2 0 2
|
|
110
|
+
// -1 0 1
|
|
111
|
+
const gx =
|
|
112
|
+
-luminance[idx - width - 1] + luminance[idx - width + 1] +
|
|
113
|
+
-2 * luminance[idx - 1] + 2 * luminance[idx + 1] +
|
|
114
|
+
-luminance[idx + width - 1] + luminance[idx + width + 1];
|
|
115
|
+
|
|
116
|
+
// Gy:
|
|
117
|
+
// -1 -2 -1
|
|
118
|
+
// 0 0 0
|
|
119
|
+
// 1 2 1
|
|
120
|
+
const gy =
|
|
121
|
+
-luminance[idx - width - 1] - 2 * luminance[idx - width] - luminance[idx - width + 1] +
|
|
122
|
+
luminance[idx + width - 1] + 2 * luminance[idx + width] + luminance[idx + width + 1];
|
|
123
|
+
|
|
124
|
+
const mag = Math.sqrt(gx * gx + gy * gy);
|
|
125
|
+
totalSobel += mag;
|
|
126
|
+
horizEnergy += Math.abs(gx);
|
|
127
|
+
vertEnergy += Math.abs(gy);
|
|
128
|
+
|
|
129
|
+
if (mag > 0.25) {
|
|
130
|
+
edgePixelCount++;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
const edgeDensity = Number((edgePixelCount / innerPixels).toFixed(4));
|
|
136
|
+
const avgSobel = totalSobel / innerPixels;
|
|
137
|
+
// Smoothness: inverse of gradient energy scaled to [0, 1]
|
|
138
|
+
const gradientSmoothness = Number(Math.max(0, Math.min(1, 1 - avgSobel * 2)).toFixed(4));
|
|
139
|
+
|
|
140
|
+
// Text detection: high localized edge density with balanced horizontal and vertical stroke energy
|
|
141
|
+
const hvRatio = horizEnergy > 0 && vertEnergy > 0 ? horizEnergy / vertEnergy : 0;
|
|
142
|
+
const textDetected = edgeDensity > 0.08 && edgeDensity < 0.35 && hvRatio > 0.6 && hvRatio < 1.6;
|
|
143
|
+
|
|
144
|
+
return { edgeDensity, gradientSmoothness, textDetected };
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* Extracts deterministic pixel signals from raw RGBA buffer.
|
|
149
|
+
*
|
|
150
|
+
* @param {Buffer|Uint8Array} rawData - 8-bit RGBA pixel stream
|
|
151
|
+
* @param {number} width - Buffer width
|
|
152
|
+
* @param {number} height - Buffer height
|
|
153
|
+
* @param {object} [meta] - Inspected file metadata
|
|
154
|
+
* @returns {object} Signals dictionary
|
|
155
|
+
*/
|
|
156
|
+
function extractSmartSignals(rawData, width, height, meta = {}) {
|
|
157
|
+
const totalPixels = width * height;
|
|
158
|
+
if (!totalPixels || !rawData || rawData.length < totalPixels * 4) {
|
|
159
|
+
return {
|
|
160
|
+
edgeDensity: 0,
|
|
161
|
+
colorCount: 1,
|
|
162
|
+
alphaCoverage: 0,
|
|
163
|
+
gradientSmoothness: 1,
|
|
164
|
+
textDetected: false,
|
|
165
|
+
photoDetected: false,
|
|
166
|
+
iconDetected: false,
|
|
167
|
+
width: meta.width || width,
|
|
168
|
+
height: meta.height || height,
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
const lum = new Float32Array(totalPixels);
|
|
173
|
+
let alphaCount = 0;
|
|
174
|
+
const colorMap = new Map();
|
|
175
|
+
|
|
176
|
+
for (let i = 0; i < totalPixels; i++) {
|
|
177
|
+
const offset = i * 4;
|
|
178
|
+
const r = rawData[offset];
|
|
179
|
+
const g = rawData[offset + 1];
|
|
180
|
+
const b = rawData[offset + 2];
|
|
181
|
+
const a = rawData[offset + 3];
|
|
182
|
+
|
|
183
|
+
if (a < 255) {
|
|
184
|
+
alphaCount++;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
// Rec. 709 Luminance
|
|
188
|
+
lum[i] = (0.2126 * r + 0.7152 * g + 0.0722 * b) / 255;
|
|
189
|
+
|
|
190
|
+
// 15-bit color quantization bucket
|
|
191
|
+
if (a >= 16) {
|
|
192
|
+
const key = ((r >> 3) << 10) | ((g >> 3) << 5) | (b >> 3);
|
|
193
|
+
colorMap.set(key, (colorMap.get(key) || 0) + 1);
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
const alphaCoverage = Number((alphaCount / totalPixels).toFixed(4));
|
|
198
|
+
const colorCount = colorMap.size;
|
|
199
|
+
const { edgeDensity, gradientSmoothness, textDetected } = computeSobelSignals(lum, width, height);
|
|
200
|
+
|
|
201
|
+
const origWidth = meta.width || width;
|
|
202
|
+
const origHeight = meta.height || height;
|
|
203
|
+
|
|
204
|
+
const iconDetected = (origWidth <= 256 && origHeight <= 256) && (colorCount <= 64 || meta.format === 'svg') && edgeDensity > 0.02;
|
|
205
|
+
const photoDetected = colorCount > 400 && gradientSmoothness > 0.55 && alphaCoverage < 0.1;
|
|
206
|
+
|
|
207
|
+
return {
|
|
208
|
+
edgeDensity,
|
|
209
|
+
colorCount,
|
|
210
|
+
alphaCoverage,
|
|
211
|
+
gradientSmoothness,
|
|
212
|
+
textDetected,
|
|
213
|
+
photoDetected,
|
|
214
|
+
iconDetected,
|
|
215
|
+
width: origWidth,
|
|
216
|
+
height: origHeight,
|
|
217
|
+
format: (meta.format || '').toLowerCase(),
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/**
|
|
222
|
+
* Classifies an image into one of the 10 detected content types.
|
|
223
|
+
*
|
|
224
|
+
* @param {object} signals - Computed signals from extractSmartSignals
|
|
225
|
+
* @returns {string} Detected type key
|
|
226
|
+
*/
|
|
227
|
+
function classifyContentType(signals) {
|
|
228
|
+
const {
|
|
229
|
+
width,
|
|
230
|
+
height,
|
|
231
|
+
colorCount,
|
|
232
|
+
alphaCoverage,
|
|
233
|
+
edgeDensity,
|
|
234
|
+
gradientSmoothness,
|
|
235
|
+
textDetected,
|
|
236
|
+
photoDetected,
|
|
237
|
+
iconDetected,
|
|
238
|
+
format,
|
|
239
|
+
} = signals;
|
|
240
|
+
|
|
241
|
+
const aspectRatio = width && height ? width / height : 1;
|
|
242
|
+
|
|
243
|
+
// 1. Panoramic Banner: width >= 800 and aspect ratio >= 2.5:1
|
|
244
|
+
if (width >= 800 && aspectRatio >= 2.5) {
|
|
245
|
+
return 'banner';
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
// 2. High-res Hero image: width >= 1200, height >= 600, photo characteristics
|
|
249
|
+
if (width >= 1200 && height >= 600 && colorCount > 300 && alphaCoverage < 0.05) {
|
|
250
|
+
return 'hero';
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
// 3. Thumbnail: small dimensions with photo color density
|
|
254
|
+
if (width <= 320 && height <= 320 && colorCount > 150 && !iconDetected && alphaCoverage < 0.1) {
|
|
255
|
+
return 'thumbnail';
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
// 4. Icon: small dimensions, few colors, sharp edges, or SVG icons
|
|
259
|
+
if (iconDetected || (width <= 256 && height <= 256 && (format === 'svg' || colorCount <= 64))) {
|
|
260
|
+
return 'icon';
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
// 5. Logo: vector or moderate colors with alpha transparency
|
|
264
|
+
if (format === 'svg' || (alphaCoverage > 0.05 && colorCount <= 128 && edgeDensity > 0.03)) {
|
|
265
|
+
return 'logo';
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
// 6. Photo with Text: mixed photo with prominent text lines
|
|
269
|
+
if (photoDetected && textDetected) {
|
|
270
|
+
return 'photo_text';
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
// 7. Graphic with Alpha: illustration or composite with transparency
|
|
274
|
+
if (alphaCoverage > 0.15) {
|
|
275
|
+
return 'graphic_alpha';
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
// 8. Screenshot: UI elements, high edge density, limited color palette
|
|
279
|
+
if (edgeDensity > 0.12 && colorCount <= 750 && !photoDetected) {
|
|
280
|
+
return 'screenshot';
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
// 9. Diagram: line art, technical plots, low color count without alpha
|
|
284
|
+
if (colorCount <= 200 && alphaCoverage < 0.05 && edgeDensity > 0.04) {
|
|
285
|
+
return 'diagram';
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
// 10. Default: Photo
|
|
289
|
+
return 'photo';
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/**
|
|
293
|
+
* Analyzes an image and generates smart optimization recommendations.
|
|
294
|
+
*
|
|
295
|
+
* @param {Buffer} buffer - Image file bytes
|
|
296
|
+
* @param {object} meta - Basic inspected format and dimensions
|
|
297
|
+
* @param {Function} getSharp - Sharp instance provider
|
|
298
|
+
* @returns {Promise<object>} Smart recommendation result
|
|
299
|
+
*/
|
|
300
|
+
async function analyzeSmart(buffer, meta, getSharp) {
|
|
301
|
+
let signals;
|
|
302
|
+
try {
|
|
303
|
+
const sharp = getSharp();
|
|
304
|
+
const thumbnail = await sharp(buffer, { failOn: 'none', limitInputPixels: 16777216 })
|
|
305
|
+
.resize(128, 128, { fit: 'inside' })
|
|
306
|
+
.ensureAlpha()
|
|
307
|
+
.raw()
|
|
308
|
+
.toBuffer({ resolveWithObject: true });
|
|
309
|
+
|
|
310
|
+
signals = extractSmartSignals(thumbnail.data, thumbnail.info.width, thumbnail.info.height, meta);
|
|
311
|
+
} catch {
|
|
312
|
+
signals = extractSmartSignals(null, 0, 0, meta);
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
const detectedType = classifyContentType(signals);
|
|
316
|
+
const profile = RECOMMENDATION_PROFILES[detectedType] || RECOMMENDATION_PROFILES.photo;
|
|
317
|
+
|
|
318
|
+
const alphaDesc = signals.alphaCoverage > 0.05
|
|
319
|
+
? `transparency ${(signals.alphaCoverage * 100).toFixed(0)}%`
|
|
320
|
+
: 'opaque';
|
|
321
|
+
|
|
322
|
+
const formatTargetDesc = profile.lossless
|
|
323
|
+
? `${profile.format.toUpperCase()} lossless`
|
|
324
|
+
: `${profile.format.toUpperCase()} at ${profile.quality}`;
|
|
325
|
+
|
|
326
|
+
const explanation = [
|
|
327
|
+
`Detected: ${detectedType} (${signals.width}ร${signals.height}, ${signals.colorCount} colors, ${alphaDesc})`,
|
|
328
|
+
`Recommended: ${formatTargetDesc}`,
|
|
329
|
+
`Reason: ${profile.reason}`,
|
|
330
|
+
].join('\n');
|
|
331
|
+
|
|
332
|
+
return {
|
|
333
|
+
detectedType,
|
|
334
|
+
signals,
|
|
335
|
+
recommendation: {
|
|
336
|
+
format: profile.format,
|
|
337
|
+
quality: profile.quality,
|
|
338
|
+
lossless: profile.lossless,
|
|
339
|
+
fallbackFormat: profile.fallbackFormat,
|
|
340
|
+
reason: profile.reason,
|
|
341
|
+
explanation,
|
|
342
|
+
},
|
|
343
|
+
};
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
module.exports = {
|
|
347
|
+
RECOMMENDATION_PROFILES,
|
|
348
|
+
extractSmartSignals,
|
|
349
|
+
classifyContentType,
|
|
350
|
+
analyzeSmart,
|
|
351
|
+
};
|
|
@@ -0,0 +1,319 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const path = require('node:path');
|
|
4
|
+
|
|
5
|
+
const DEFAULT_TEAM_POLICY_TEMPLATE = {
|
|
6
|
+
version: '1.0.0',
|
|
7
|
+
policy: {
|
|
8
|
+
targetFormat: 'webp',
|
|
9
|
+
quality: { min: 75, max: 90 },
|
|
10
|
+
clean: { required: true },
|
|
11
|
+
formats: {
|
|
12
|
+
accept: ['svg', 'png', 'jpg', 'jpeg', 'webp', 'avif'],
|
|
13
|
+
reject: ['gif', 'tiff'],
|
|
14
|
+
},
|
|
15
|
+
limits: {
|
|
16
|
+
maxInputBytes: 10485760, // 10 MB
|
|
17
|
+
maxOutputBytes: 5242880, // 5 MB
|
|
18
|
+
},
|
|
19
|
+
provenance: {
|
|
20
|
+
required: true,
|
|
21
|
+
includeTimestamp: true,
|
|
22
|
+
},
|
|
23
|
+
},
|
|
24
|
+
enforcement: {
|
|
25
|
+
onCi: 'block',
|
|
26
|
+
onLocal: 'warn',
|
|
27
|
+
onPrReview: 'requireApproval',
|
|
28
|
+
},
|
|
29
|
+
exceptions: [
|
|
30
|
+
{
|
|
31
|
+
path: 'public/legacy/*.svg',
|
|
32
|
+
reason: 'Legacy assets, frozen',
|
|
33
|
+
approvedBy: 'team-lead@company.com',
|
|
34
|
+
expiresAt: '2027-06-01',
|
|
35
|
+
},
|
|
36
|
+
],
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Converts a simple glob pattern to a RegExp.
|
|
41
|
+
* Supports `*`, `**`, and file extensions.
|
|
42
|
+
*
|
|
43
|
+
* @param {string} glob
|
|
44
|
+
* @returns {RegExp}
|
|
45
|
+
*/
|
|
46
|
+
function globToRegExp(glob) {
|
|
47
|
+
const norm = String(glob || '').replace(/\\/g, '/').replace(/^\.\//, '');
|
|
48
|
+
const escaped = norm
|
|
49
|
+
.replace(/[.+^${}()|[\]\\]/g, '\\$&')
|
|
50
|
+
.replace(/\*\*/g, '.*')
|
|
51
|
+
.replace(/(?<!\.)\*/g, '[^/]*');
|
|
52
|
+
return new RegExp(`^${escaped}$`, 'i');
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Validates a team policy configuration object.
|
|
57
|
+
*
|
|
58
|
+
* @param {object} policy - Candidate policy object
|
|
59
|
+
* @returns {{ valid: boolean, errors: string[] }}
|
|
60
|
+
*/
|
|
61
|
+
function validateTeamPolicy(policy) {
|
|
62
|
+
const errors = [];
|
|
63
|
+
if (!policy || typeof policy !== 'object') {
|
|
64
|
+
return { valid: false, errors: ['Policy must be a valid JSON object.'] };
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
if (!policy.version || typeof policy.version !== 'string') {
|
|
68
|
+
errors.push('Property "version" is required and must be a string (e.g. "1.0.0").');
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
if (!policy.policy || typeof policy.policy !== 'object') {
|
|
72
|
+
errors.push('Property "policy" is required and must be an object.');
|
|
73
|
+
} else {
|
|
74
|
+
const p = policy.policy;
|
|
75
|
+
|
|
76
|
+
if (p.quality) {
|
|
77
|
+
if (typeof p.quality !== 'object') {
|
|
78
|
+
errors.push('policy.quality must be an object with min and max numbers.');
|
|
79
|
+
} else {
|
|
80
|
+
const { min, max } = p.quality;
|
|
81
|
+
if (min !== undefined && (!Number.isInteger(min) || min < 1 || min > 100)) {
|
|
82
|
+
errors.push('policy.quality.min must be an integer between 1 and 100.');
|
|
83
|
+
}
|
|
84
|
+
if (max !== undefined && (!Number.isInteger(max) || max < 1 || max > 100)) {
|
|
85
|
+
errors.push('policy.quality.max must be an integer between 1 and 100.');
|
|
86
|
+
}
|
|
87
|
+
if (min !== undefined && max !== undefined && min > max) {
|
|
88
|
+
errors.push(`policy.quality.min (${min}) cannot be greater than policy.quality.max (${max}).`);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
if (p.clean && typeof p.clean.required !== 'boolean') {
|
|
94
|
+
errors.push('policy.clean.required must be a boolean.');
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
if (p.formats) {
|
|
98
|
+
if (p.formats.accept && !Array.isArray(p.formats.accept)) {
|
|
99
|
+
errors.push('policy.formats.accept must be an array of format strings.');
|
|
100
|
+
}
|
|
101
|
+
if (p.formats.reject && !Array.isArray(p.formats.reject)) {
|
|
102
|
+
errors.push('policy.formats.reject must be an array of format strings.');
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
if (p.limits) {
|
|
107
|
+
if (p.limits.maxInputBytes !== undefined && (!Number.isFinite(p.limits.maxInputBytes) || p.limits.maxInputBytes <= 0)) {
|
|
108
|
+
errors.push('policy.limits.maxInputBytes must be a positive number.');
|
|
109
|
+
}
|
|
110
|
+
if (p.limits.maxOutputBytes !== undefined && (!Number.isFinite(p.limits.maxOutputBytes) || p.limits.maxOutputBytes <= 0)) {
|
|
111
|
+
errors.push('policy.limits.maxOutputBytes must be a positive number.');
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
if (policy.enforcement) {
|
|
117
|
+
const validCi = ['block', 'warn'];
|
|
118
|
+
const validLocal = ['warn', 'block'];
|
|
119
|
+
if (policy.enforcement.onCi && !validCi.includes(policy.enforcement.onCi)) {
|
|
120
|
+
errors.push(`enforcement.onCi must be one of: ${validCi.join(', ')}.`);
|
|
121
|
+
}
|
|
122
|
+
if (policy.enforcement.onLocal && !validLocal.includes(policy.enforcement.onLocal)) {
|
|
123
|
+
errors.push(`enforcement.onLocal must be one of: ${validLocal.join(', ')}.`);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
if (policy.exceptions) {
|
|
128
|
+
if (!Array.isArray(policy.exceptions)) {
|
|
129
|
+
errors.push('Property "exceptions" must be an array.');
|
|
130
|
+
} else {
|
|
131
|
+
policy.exceptions.forEach((exc, idx) => {
|
|
132
|
+
if (!exc.path || typeof exc.path !== 'string') {
|
|
133
|
+
errors.push(`exceptions[${idx}].path is required.`);
|
|
134
|
+
}
|
|
135
|
+
if (!exc.reason || typeof exc.reason !== 'string') {
|
|
136
|
+
errors.push(`exceptions[${idx}].reason is required.`);
|
|
137
|
+
}
|
|
138
|
+
if (!exc.approvedBy || typeof exc.approvedBy !== 'string') {
|
|
139
|
+
errors.push(`exceptions[${idx}].approvedBy is required.`);
|
|
140
|
+
}
|
|
141
|
+
if (!exc.expiresAt || Number.isNaN(Date.parse(exc.expiresAt))) {
|
|
142
|
+
errors.push(`exceptions[${idx}].expiresAt must be a valid date string (e.g. "2027-06-01").`);
|
|
143
|
+
}
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
return {
|
|
149
|
+
valid: errors.length === 0,
|
|
150
|
+
errors,
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* Evaluates a single file and conversion options against a team policy.
|
|
156
|
+
*
|
|
157
|
+
* @param {object} policyConfig - Validated team policy
|
|
158
|
+
* @param {{ path: string, format: string, size?: number }} fileItem - File to evaluate
|
|
159
|
+
* @param {object} [conversionOptions={}] - Desired conversion options
|
|
160
|
+
* @param {object} [context={}] - Evaluation context (e.g. isCi)
|
|
161
|
+
* @returns {{ allowed: boolean, violations: string[], exceptionApplied?: object }}
|
|
162
|
+
*/
|
|
163
|
+
function evaluateFilePolicy(policyConfig, fileItem, conversionOptions = {}, context = {}) {
|
|
164
|
+
const normPath = String(fileItem.path || '').replace(/\\/g, '/').replace(/^\.\//, '');
|
|
165
|
+
const normFormat = String(fileItem.format || normPath.split('.').pop() || '').toLowerCase();
|
|
166
|
+
const exceptions = Array.isArray(policyConfig.exceptions) ? policyConfig.exceptions : [];
|
|
167
|
+
|
|
168
|
+
// 1. Check for Active Exceptions
|
|
169
|
+
const now = Date.now();
|
|
170
|
+
for (const exc of exceptions) {
|
|
171
|
+
const rx = globToRegExp(exc.path);
|
|
172
|
+
if (rx.test(normPath) || rx.test(normPath.split('/').pop())) {
|
|
173
|
+
const expMs = Date.parse(exc.expiresAt);
|
|
174
|
+
if (!Number.isNaN(expMs) && expMs > now) {
|
|
175
|
+
return {
|
|
176
|
+
allowed: true,
|
|
177
|
+
violations: [],
|
|
178
|
+
exceptionApplied: { ...exc },
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
// 2. Evaluate Policy Rules
|
|
185
|
+
const violations = [];
|
|
186
|
+
const rules = policyConfig.policy || {};
|
|
187
|
+
|
|
188
|
+
// Formats Check
|
|
189
|
+
if (rules.formats) {
|
|
190
|
+
const rejected = (rules.formats.reject || []).map((f) => f.toLowerCase());
|
|
191
|
+
const accepted = (rules.formats.accept || []).map((f) => f.toLowerCase());
|
|
192
|
+
|
|
193
|
+
if (rejected.includes(normFormat)) {
|
|
194
|
+
violations.push(`Format "${normFormat}" is explicitly rejected by team policy.`);
|
|
195
|
+
}
|
|
196
|
+
if (accepted.length > 0 && !accepted.includes(normFormat)) {
|
|
197
|
+
violations.push(`Format "${normFormat}" is not in the approved formats list [${accepted.join(', ')}].`);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
// Target Format Check
|
|
202
|
+
if (rules.targetFormat && conversionOptions.target) {
|
|
203
|
+
const target = String(conversionOptions.target).toLowerCase();
|
|
204
|
+
const allowedTargets = Array.isArray(rules.targetFormat)
|
|
205
|
+
? rules.targetFormat.map((t) => t.toLowerCase())
|
|
206
|
+
: [String(rules.targetFormat).toLowerCase()];
|
|
207
|
+
if (!allowedTargets.includes(target)) {
|
|
208
|
+
violations.push(`Target format "${target}" does not match required team target [${allowedTargets.join(', ')}].`);
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
// Quality Range Check
|
|
213
|
+
if (rules.quality && conversionOptions.quality !== undefined) {
|
|
214
|
+
const q = Number(conversionOptions.quality);
|
|
215
|
+
if (rules.quality.min !== undefined && q < rules.quality.min) {
|
|
216
|
+
violations.push(`Quality ${q} is below team policy minimum of ${rules.quality.min}.`);
|
|
217
|
+
}
|
|
218
|
+
if (rules.quality.max !== undefined && q > rules.quality.max) {
|
|
219
|
+
violations.push(`Quality ${q} exceeds team policy maximum of ${rules.quality.max}.`);
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
// Clean Mode Check
|
|
224
|
+
if (rules.clean && rules.clean.required && conversionOptions.clean === false) {
|
|
225
|
+
violations.push('Clean Mode (metadata stripping) is required by team policy.');
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
// Input File Size Check
|
|
229
|
+
if (rules.limits && rules.limits.maxInputBytes && fileItem.size) {
|
|
230
|
+
if (fileItem.size > rules.limits.maxInputBytes) {
|
|
231
|
+
violations.push(`Input size ${fileItem.size} bytes exceeds maximum allowed ${rules.limits.maxInputBytes} bytes.`);
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
return {
|
|
236
|
+
allowed: violations.length === 0,
|
|
237
|
+
violations,
|
|
238
|
+
};
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/**
|
|
242
|
+
* Checks exception lifecycles and expiration statuses.
|
|
243
|
+
*
|
|
244
|
+
* @param {object} policyConfig
|
|
245
|
+
* @returns {{ active: object[], expired: object[] }}
|
|
246
|
+
*/
|
|
247
|
+
function checkExceptionsStatus(policyConfig) {
|
|
248
|
+
const active = [];
|
|
249
|
+
const expired = [];
|
|
250
|
+
const now = Date.now();
|
|
251
|
+
const exceptions = Array.isArray(policyConfig.exceptions) ? policyConfig.exceptions : [];
|
|
252
|
+
|
|
253
|
+
for (const exc of exceptions) {
|
|
254
|
+
const expMs = Date.parse(exc.expiresAt);
|
|
255
|
+
const msRemaining = expMs - now;
|
|
256
|
+
const days = Math.round(msRemaining / (1000 * 60 * 60 * 24));
|
|
257
|
+
|
|
258
|
+
if (msRemaining > 0) {
|
|
259
|
+
active.push({ ...exc, daysRemaining: days });
|
|
260
|
+
} else {
|
|
261
|
+
expired.push({ ...exc, daysExpired: Math.abs(days) });
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
return { active, expired };
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/**
|
|
269
|
+
* Formats policy status into human-readable terminal output.
|
|
270
|
+
*
|
|
271
|
+
* @param {object} policyConfig
|
|
272
|
+
* @returns {string}
|
|
273
|
+
*/
|
|
274
|
+
function formatPolicyStatus(policyConfig) {
|
|
275
|
+
const p = policyConfig.policy || {};
|
|
276
|
+
const enf = policyConfig.enforcement || {};
|
|
277
|
+
const { active, expired } = checkExceptionsStatus(policyConfig);
|
|
278
|
+
|
|
279
|
+
const lines = [
|
|
280
|
+
'๐ก๏ธ Zapwebp Team Policy Status',
|
|
281
|
+
'โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ',
|
|
282
|
+
`Version: ${policyConfig.version || '1.0.0'}`,
|
|
283
|
+
`Target: ${p.targetFormat || 'webp'}`,
|
|
284
|
+
`Quality: ${p.quality?.min || 75} โ ${p.quality?.max || 90}`,
|
|
285
|
+
`Clean Mode: ${p.clean?.required ? 'Required' : 'Optional'}`,
|
|
286
|
+
`Enforcement: CI=${enf.onCi || 'block'}, Local=${enf.onLocal || 'warn'}`,
|
|
287
|
+
'',
|
|
288
|
+
`Active Exceptions (${active.length}):`,
|
|
289
|
+
];
|
|
290
|
+
|
|
291
|
+
if (!active.length) {
|
|
292
|
+
lines.push(' None');
|
|
293
|
+
} else {
|
|
294
|
+
for (const a of active) {
|
|
295
|
+
lines.push(` โ ${a.path} (${a.reason})`);
|
|
296
|
+
lines.push(` Approved by: ${a.approvedBy} ยท Expires in: ${a.daysRemaining} days (${a.expiresAt})`);
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
if (expired.length > 0) {
|
|
301
|
+
lines.push('');
|
|
302
|
+
lines.push(`โ ๏ธ Expired Exceptions (${expired.length}):`);
|
|
303
|
+
for (const e of expired) {
|
|
304
|
+
lines.push(` โ ${e.path} (${e.reason})`);
|
|
305
|
+
lines.push(` Approved by: ${e.approvedBy} ยท EXPIRED ${e.daysExpired} days ago (${e.expiresAt})`);
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
lines.push('โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ');
|
|
310
|
+
return lines.join('\n');
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
module.exports = {
|
|
314
|
+
DEFAULT_TEAM_POLICY_TEMPLATE,
|
|
315
|
+
validateTeamPolicy,
|
|
316
|
+
evaluateFilePolicy,
|
|
317
|
+
checkExceptionsStatus,
|
|
318
|
+
formatPolicyStatus,
|
|
319
|
+
};
|
package/src/testing.d.ts
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
export interface MockSvgOptions {
|
|
2
|
+
width?: number;
|
|
3
|
+
height?: number;
|
|
4
|
+
transparent?: boolean;
|
|
5
|
+
fill?: string;
|
|
6
|
+
withMetadata?: boolean;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export interface MockImageOptions {
|
|
10
|
+
format?: 'svg' | 'png' | 'webp' | 'jpeg' | 'avif';
|
|
11
|
+
width?: number;
|
|
12
|
+
height?: number;
|
|
13
|
+
transparent?: boolean;
|
|
14
|
+
withMetadata?: boolean;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function createMockSvg(options?: MockSvgOptions): Buffer;
|
|
18
|
+
export function createMockImage(options?: MockImageOptions): Promise<Buffer>;
|