### Size Example Source: https://github.com/semanticist21/sinter/blob/main/_autodocs/configuration.md Example of setting a target maximum file size for compression. ```typescript const blob = await sinter() .keepFormat() .size(500, "KB") .compress(file); const blob = await sinter() .toFormat("webp") .size(1, "MB") .compress(file); ``` -------------------------------- ### Timeout Example Source: https://github.com/semanticist21/sinter/blob/main/_autodocs/configuration.md Example of setting a time limit for the compression operation. ```typescript const blob = await sinter() .toFormat("webp") .timeout(30) .compress(file); ``` -------------------------------- ### Quick Compress with Fallback Example Source: https://github.com/semanticist21/sinter/blob/main/_autodocs/configuration.md An example demonstrating a quick compression attempt with a fallback mechanism if the timeout is exceeded. ```typescript async function compressQuick(file) { try { return await sinter() .toFormat("webp") .timeout(5) .maxQuality(80) .compress(file); } catch (err) { if (err.message.includes("timed out")) { console.warn("Compression took too long, using original"); return file; } throw err; } } ``` -------------------------------- ### Installation with bun Source: https://github.com/semanticist21/sinter/blob/main/_autodocs/PACKAGE.md Install the sinter-js package using bun. ```bash bun add sinter-js ``` -------------------------------- ### Install Sinter Source: https://github.com/semanticist21/sinter/blob/main/README.md Install the sinter-js package using npm. ```bash npm install sinter-js ``` -------------------------------- ### Complete Example: All Options Source: https://github.com/semanticist21/sinter/blob/main/_autodocs/configuration.md Demonstrates using all available configuration options in a single compression operation. ```typescript const blob = await sinter() // Format configuration .allowFormats(["avif", "webp"], "jpeg") // Codec configuration .codecOptions({ avif: { speed: 6 }, webp: { lossless: false }, jpeg: { progressive: true } }) // Compression controls .maxQuality(80) .dimensions({ width: 1200, height: 800 }) .size(500, "KB") .timeout(30) // Execute .compress(file); ``` -------------------------------- ### toFormat() Example Source: https://github.com/semanticist21/sinter/blob/main/_autodocs/configuration.md Always convert to the specified format. ```typescript const blob = await sinter().toFormat("webp").compress(file); ``` -------------------------------- ### With Quality Setting Source: https://github.com/semanticist21/sinter/blob/main/_autodocs/QUICK-REFERENCE.md Example demonstrating conversion to WebP with a specified maximum quality. ```typescript const blob = await sinter() .toFormat("webp") .maxQuality(85) .compress(file); ``` -------------------------------- ### Full API Example Source: https://github.com/semanticist21/sinter/blob/main/README.md An example showcasing various API methods for compression. ```javascript await sinter() .allowFormats(["avif", "webp"], "webp") .codecOptions({ webp: { lossless: false } }) .maxQuality(80) .dimensions({ width: 1200 }) .size(1, "MB") .timeout(30) .compress(file); ``` -------------------------------- ### With Resize Source: https://github.com/semanticist21/sinter/blob/main/_autodocs/QUICK-REFERENCE.md Example of keeping the original format and resizing the image dimensions. ```typescript const blob = await sinter() .keepFormat() .dimensions({ width: 1200 }) .compress(file); ``` -------------------------------- ### Example: File Input Source: https://github.com/semanticist21/sinter/blob/main/_autodocs/api-reference/builder.md Provides an example of handling file input from an HTML element and compressing it using Sinter. ```typescript const fileInput = document.querySelector("input[type='file']"); fileInput.addEventListener("change", async (e) => { const file = e.target.files[0]; try { const blob = await sinter() .toFormat("webp") .maxQuality(80) .compress(file); console.log(`Original: ${file.size} bytes, Compressed: ${blob.size} bytes`); } catch (err) { console.error("Compression failed:", err.message); } }); ``` -------------------------------- ### Installation with yarn Source: https://github.com/semanticist21/sinter/blob/main/_autodocs/PACKAGE.md Install the sinter-js package using yarn. ```bash yarn add sinter-js ``` -------------------------------- ### allowFormats() Example Source: https://github.com/semanticist21/sinter/blob/main/_autodocs/configuration.md Prefer specific formats but convert others to a fallback. ```typescript const blob = await sinter() .allowFormats(["avif", "webp"], "jpeg") .compress(file); ``` -------------------------------- ### With Size Target Source: https://github.com/semanticist21/sinter/blob/main/_autodocs/QUICK-REFERENCE.md Example of converting to WebP and targeting a specific file size. ```typescript const blob = await sinter() .toFormat("webp") .size(500, "KB") .compress(file); ``` -------------------------------- ### ImageFormat Examples Source: https://github.com/semanticist21/sinter/blob/main/_autodocs/types.md Examples demonstrating the usage of ImageFormat type. ```typescript // Single format conversion const blob = await sinter().toFormat("webp").compress(file); // Multiple allowed formats const blob = await sinter() .allowFormats(["avif", "webp"], "jpeg") .compress(file); // Type-safe format selection type MyFormats = "webp" | "jpeg"; const codec: CodecMap["webp"] = { lossless: false }; ``` -------------------------------- ### Codec Options Example Source: https://github.com/semanticist21/sinter/blob/main/README.md Example of setting codec-specific options for Avif format. ```javascript sinter() .toFormat("avif") .codecOptions({ avif: { speed: 4 } }) .compress(file); ``` -------------------------------- ### Example Usage of detectFormat() Source: https://github.com/semanticist21/sinter/blob/main/_autodocs/api-reference/format-detection.md Example demonstrating how to use detectFormat() with user file input, converting the file to Uint8Array. ```typescript // From user file input const file = document.querySelector('input[type="file"]').files[0]; const buffer = await file.arrayBuffer(); const bytes = new Uint8Array(buffer); const format = detectFormat(bytes); console.log(`Detected format: ${format}`); ``` -------------------------------- ### CodecMap Examples Source: https://github.com/semanticist21/sinter/blob/main/_autodocs/types.md Examples demonstrating the usage of CodecMap type. ```typescript // WebP lossless const opts: Partial = { webp: { lossless: true } }; // AVIF with speed tuning const avifOpts: CodecMap["avif"] = { speed: 6 }; // Multiple formats const codecOptions: Partial = { avif: { speed: 4 }, webp: { lossless: false }, jpeg: { progressive: true } }; ``` -------------------------------- ### CodecOptions Examples Source: https://github.com/semanticist21/sinter/blob/main/_autodocs/types.md Examples demonstrating the usage of CodecOptions type. ```typescript // Typed to accept any format's options const allOpts: CodecOptions = { webp: { lossless: true }, avif: { speed: 4 } }; // Typed to accept only WebP options const webpPipeline = sinter().toFormat("webp"); const webpOpts: CodecOptions<"webp"> = { webp: { lossless: false } }; // TypeScript error: jpeg is not allowed // const badOpts: CodecOptions<"webp"> = { jpeg: { progressive: true } }; ``` -------------------------------- ### Example Request Source: https://github.com/semanticist21/sinter/blob/main/_autodocs/api-reference/worker-protocol.md A concrete example of a WorkerRequest object. ```typescript const request: WorkerRequest = { buffer: new ArrayBuffer(12345), formatPolicy: { type: "fixed", format: "webp" }, codecOpts: { webp: { lossless: false } }, maxQuality: 80, dims: { width: 1200 }, sizeLimit: 500 * 1024, // 500 KB }; ``` -------------------------------- ### keepFormat() Example Source: https://github.com/semanticist21/sinter/blob/main/_autodocs/configuration.md Use the input image format for output. Most efficient when format conversion is not needed. ```typescript const blob = await sinter().keepFormat().compress(file); ``` -------------------------------- ### Simple Conversion Source: https://github.com/semanticist21/sinter/blob/main/_autodocs/QUICK-REFERENCE.md A basic example of converting an image to WebP format. ```typescript const blob = await sinter() .toFormat("webp") .compress(file); ``` -------------------------------- ### Dimensions Examples Source: https://github.com/semanticist21/sinter/blob/main/_autodocs/configuration.md Illustrates different ways to specify dimensions: width constraint, height constraint, and bounding box. ```typescript // Width constraint .dimensions({ width: 1200 }) // Height constraint .dimensions({ height: 600 }) // Bounding box .dimensions({ width: 1200, height: 800 }) ``` -------------------------------- ### Runtime Detection Example Source: https://github.com/semanticist21/sinter/blob/main/_autodocs/configuration.md Demonstrates how to safely import Sinter on the server and correctly use the compress() function in a browser context, while preventing its server-side execution. ```typescript // Safe to import on server import { sinter } from "sinter-js"; // In server-side route handler export default async function handler(req, res) { // DO NOT call compress() here // Safe: import is allowed if (typeof window === "undefined") { res.status(400).json({ error: "Compression requires browser client" }); } } // In browser client code export default async function ImageUpload() { const file = getFileFromInput(); const blob = await sinter().toFormat("webp").compress(file); // Works! } ``` -------------------------------- ### codecOptions() - PNG Example Source: https://github.com/semanticist21/sinter/blob/main/_autodocs/configuration.md PNG is always lossless and has no encoder options. Example for PNG. ```typescript const blob = await sinter() .toFormat("png") .compress(file); // codecOptions is not needed for PNG ``` -------------------------------- ### Browser and SSR Example Source: https://github.com/semanticist21/sinter/blob/main/_autodocs/api-reference/sinter.md Example showing how to use sinter() in an SSR framework like Next.js. ```typescript // Next.js or other SSR framework import { sinter } from "sinter-js"; // Safe on server export default function Component() { return ( { // Client-side code const blob = await sinter().compress(e.target.files[0]); }} /> ); } ``` -------------------------------- ### codecOptions() - AVIF Example Source: https://github.com/semanticist21/sinter/blob/main/_autodocs/configuration.md Set encoder options for formats that may be produced by this pipeline. Example for AVIF. ```typescript const blob = await sinter() .toFormat("avif") .codecOptions({ avif: { speed: 6 } }) .compress(file); ``` -------------------------------- ### Batch Image Compression Example Source: https://github.com/semanticist21/sinter/blob/main/_autodocs/api-reference/builder.md An example demonstrating how to use the Sinter builder to compress multiple images with specific format, quality, and dimension constraints. ```typescript async function compressImages(files) { const pipeline = sinter() .allowFormats(["avif", "webp"], "webp") .maxQuality(80) .dimensions({ width: 1200 }); const results = await Promise.all( files.map(file => pipeline.compress(file)) ); return results; } ``` -------------------------------- ### With Timeout Source: https://github.com/semanticist21/sinter/blob/main/_autodocs/QUICK-REFERENCE.md Example of setting a timeout for the compression process. ```typescript const blob = await sinter() .toFormat("avif") .timeout(30) .compress(file); ``` -------------------------------- ### codecOptions() - BMP Example Source: https://github.com/semanticist21/sinter/blob/main/_autodocs/configuration.md BMP is always uncompressed and has no encoder options. Example for BMP. ```typescript const blob = await sinter() .toFormat("bmp") .compress(file); // codecOptions is not needed for BMP ``` -------------------------------- ### codecOptions() - JPEG Example Source: https://github.com/semanticist21/sinter/blob/main/_autodocs/configuration.md Set encoder options for formats that may be produced by this pipeline. Example for JPEG. ```typescript const blob = await sinter() .toFormat("jpeg") .codecOptions({ jpeg: { progressive: true } }) .compress(file); ``` -------------------------------- ### Example Usage of maxQuality() Source: https://github.com/semanticist21/sinter/blob/main/_autodocs/api-reference/builder.md Demonstrates setting a maximum quality level for WebP compression. ```typescript const blob = await sinter() .toFormat("webp") .maxQuality(80) // Allow up to quality 80 .compress(file); ``` -------------------------------- ### maxQuality() Example Source: https://github.com/semanticist21/sinter/blob/main/_autodocs/configuration.md Set the highest quality the encoder is allowed to use. ```typescript const blob = await sinter() .keepFormat() .maxQuality(85) .compress(file); ``` -------------------------------- ### With Error Handling Source: https://github.com/semanticist21/sinter/blob/main/_autodocs/QUICK-REFERENCE.md Example showing how to handle potential errors during the compression process using try-catch blocks. ```typescript try { const blob = await sinter() .toFormat("webp") .maxQuality(80) .compress(file); } catch (err) { if (err instanceof SinterValidationError) { // Invalid input or parameters } else if (err instanceof SinterCodecError) { // Compression failed or unsupported runtime } } ``` -------------------------------- ### Example: Both Dimensions for dimensions() Source: https://github.com/semanticist21/sinter/blob/main/_autodocs/api-reference/builder.md Shows setting both width and height constraints for resizing. ```typescript const blob = await sinter() .keepFormat() .dimensions({ width: 800, height: 600 }) .compress(file); // Scales to fit within 800×600 while maintaining aspect ratio ``` -------------------------------- ### Example: Quick Compress with Fallback Source: https://github.com/semanticist21/sinter/blob/main/_autodocs/api-reference/builder.md Shows a quick compression with a short timeout, implying a fast path. ```typescript const blob = await sinter() .toFormat("webp") .timeout(5) // Fast path only .maxQuality(80) .compress(file); ``` -------------------------------- ### Example: AVIF with Speed Tuning Source: https://github.com/semanticist21/sinter/blob/main/_autodocs/api-reference/codec-stage.md Demonstrates tuning the encoding speed for AVIF. ```typescript const blob = await sinter() .toFormat("avif") .codecOptions({ avif: { speed: 6 } }) // Faster encoding .maxQuality(80) .compress(file); ``` -------------------------------- ### Example: Manual Detection Source: https://github.com/semanticist21/sinter/blob/main/_autodocs/api-reference/format-detection.md Examples of manual detection for JPEG and PNG formats using their respective magic bytes. ```typescript import { detectFormat } from "sinter-js"; // Not exported; for internal reference // JPEG detection const jpegBytes = new Uint8Array([0xFF, 0xD8, 0xFF, ...]); const format = detectFormat(jpegBytes); // "jpeg" // PNG detection const pngBytes = new Uint8Array([0x89, 0x50, 0x4E, 0x47, ...]); const format = detectFormat(pngBytes); // "png" ``` -------------------------------- ### Example: Combined Size and Dimension Constraints Source: https://github.com/semanticist21/sinter/blob/main/_autodocs/api-reference/builder.md Illustrates setting both dimension and size constraints, with dimensions applied first. ```typescript const blob = await sinter() .allowFormats(["webp"], "jpeg") .dimensions({ width: 1920 }) .size(200, "KB") .maxQuality(75) .compress(file); // Dimensions limit applies first, then size fitting ``` -------------------------------- ### Example: 1 MB with Format Conversion Source: https://github.com/semanticist21/sinter/blob/main/_autodocs/api-reference/builder.md Shows how to convert an image to WebP format and set a target size of 1 MB. ```typescript const blob = await sinter() .toFormat("webp") .maxQuality(85) .size(1, "MB") .compress(file); ``` -------------------------------- ### Example: Height Constraint for dimensions() Source: https://github.com/semanticist21/sinter/blob/main/_autodocs/api-reference/builder.md Demonstrates setting only the height constraint for resizing. ```typescript const blob = await sinter() .allowFormats(["webp"], "jpeg") .dimensions({ height: 400 }) .compress(file); ``` -------------------------------- ### Example: WebP with Lossless Encoding Source: https://github.com/semanticist21/sinter/blob/main/_autodocs/api-reference/codec-stage.md Demonstrates setting WebP to use lossless encoding. ```typescript const blob = await sinter() .toFormat("webp") .codecOptions({ webp: { lossless: true } }) .compress(file); ``` -------------------------------- ### Example: Width Constraint for dimensions() Source: https://github.com/semanticist21/sinter/blob/main/_autodocs/api-reference/builder.md Demonstrates setting only the width constraint for resizing. ```typescript const blob = await sinter() .toFormat("webp") .dimensions({ width: 1200 }) .maxQuality(80) .compress(file); // If input is 2400×1800, output is 1200×900 ``` -------------------------------- ### Example: Size Fitting with Quality Limit Source: https://github.com/semanticist21/sinter/blob/main/_autodocs/api-reference/builder.md Shows how maxQuality interacts with size() to fit within a target byte limit. ```typescript const blob = await sinter() .keepFormat() .maxQuality(75) .size(500, "KB") // Quality may be reduced further if needed to fit .compress(file); ``` -------------------------------- ### Configuration Reusability Example Source: https://github.com/semanticist21/sinter/blob/main/_autodocs/api-reference/sinter.md Demonstrates reusability of an immutable pipeline configuration. ```typescript const config = sinter() .toFormat("webp") .maxQuality(80); const blob1 = await config.compress(file1); const blob2 = await config.compress(file2); ``` -------------------------------- ### codecOptions() - Multiple Formats Example Source: https://github.com/semanticist21/sinter/blob/main/_autodocs/configuration.md When using `allowFormats()` or `keepFormat()`, specify options for multiple formats. ```typescript const blob = await sinter() .allowFormats(["avif", "webp"], "jpeg") .codecOptions({ avif: { speed: 4 }, webp: { lossless: false }, jpeg: { progressive: true } }) .compress(file); ``` -------------------------------- ### Example: Progressive JPEG Source: https://github.com/semanticist21/sinter/blob/main/_autodocs/api-reference/codec-stage.md Demonstrates enabling progressive encoding for JPEG. ```typescript const blob = await sinter() .toFormat("jpeg") .codecOptions({ jpeg: { progressive: true } }) .maxQuality(85) .compress(file); ``` -------------------------------- ### Reusable Pipeline Source: https://github.com/semanticist21/sinter/blob/main/_autodocs/api-reference/sinter.md Example demonstrating how to configure and reuse a pipeline for multiple files. ```typescript const pipeline = sinter() .allowFormats(["avif", "webp"], "webp") .codecOptions({ webp: { lossless: false } }) .maxQuality(80) .dimensions({ width: 1200 }); const firstBlob = await pipeline.compress(firstFile); const secondBlob = await pipeline.compress(secondFile); ``` -------------------------------- ### Modern Format with Fallback Source: https://github.com/semanticist21/sinter/blob/main/_autodocs/QUICK-REFERENCE.md Example using modern formats like AVIF and WebP with a fallback to JPEG, including codec options and quality settings. ```typescript const blob = await sinter() .allowFormats(["avif", "webp"], "jpeg") .codecOptions({ avif: { speed: 4 }, webp: { lossless: false } }) .maxQuality(80) .compress(file); ``` -------------------------------- ### Basic Usage Source: https://github.com/semanticist21/sinter/blob/main/_autodocs/api-reference/sinter.md Example of basic usage for the sinter() function. ```typescript import { sinter } from "sinter-js"; const blob = await sinter() .toFormat("webp") .maxQuality(80) .compress(file); ``` -------------------------------- ### Format Conversion Source: https://github.com/semanticist21/sinter/blob/main/_autodocs/api-reference/sinter.md Example of converting any format to WebP using sinter(). ```typescript // Convert any format to WebP const webpBlob = await sinter() .toFormat("webp") .compress(jpegFile); ``` -------------------------------- ### With Size Target Source: https://github.com/semanticist21/sinter/blob/main/_autodocs/api-reference/sinter.md Example of compressing a file to fit under a specific size target. ```typescript // Compress to fit under 500 KB const blob = await sinter() .keepFormat() .size(500, "KB") .compress(file); ``` -------------------------------- ### Sending the Request Source: https://github.com/semanticist21/sinter/blob/main/_autodocs/api-reference/worker-protocol.md Example code demonstrating how to construct and send a WorkerRequest from the main thread. ```typescript const buffer = await file.arrayBuffer(); const request: WorkerRequest = { buffer, formatPolicy, codecOpts, maxQuality, dims, sizeLimit, }; // Transfer buffer ownership to worker (buffer becomes unavailable on main thread) worker.postMessage(request, [request.buffer]); ``` -------------------------------- ### SSR Compatibility Example Source: https://github.com/semanticist21/sinter/blob/main/_autodocs/PACKAGE.md Demonstrates safe import and usage patterns for Sinter in SSR applications, highlighting when not to call the compress() function. ```typescript // OK: safe to import on server import { sinter } from "sinter-js"; // OK: safe to use in SSR components export default function ImageCompressor() { // Don't call compress() on the server if (typeof window === "undefined") return null; // Call compress() only in client code return ; } ``` -------------------------------- ### With Size Target Source: https://github.com/semanticist21/sinter/blob/main/_autodocs/INDEX.md Example of compressing an image to a target file size. ```typescript const blob = await sinter() .keepFormat() .dimensions({ width: 1920 }) .size(500, "KB") .compress(file); ``` -------------------------------- ### Example: 30-Second Timeout Source: https://github.com/semanticist21/sinter/blob/main/_autodocs/api-reference/builder.md Demonstrates setting a 30-second timeout for the compression operation and handling potential timeouts. ```typescript try { const blob = await sinter() .toFormat("avif") .maxQuality(80) .timeout(30) .compress(file); } catch (err) { if (err instanceof SinterCodecError && err.message.includes("timed out")) { console.error("Compression took too long"); } } ``` -------------------------------- ### Immutable Pipeline Settings Example Source: https://github.com/semanticist21/sinter/blob/main/_autodocs/api-reference/sinter.md Illustrates the type-level enforcement of immutable pipeline settings in TypeScript. ```typescript // This type-checks fine const blob = await sinter() .maxQuality(80) .maxQuality(90) // Type error: maxQuality not available after first call .compress(file); ``` -------------------------------- ### SinterError Usage Example Source: https://github.com/semanticist21/sinter/blob/main/_autodocs/errors.md Example of catching a SinterError. ```typescript import { SinterError } from "sinter-js"; try { const blob = await sinter().toFormat("webp").compress(file); } catch (err) { if (err instanceof SinterError) { console.error("Sinter error:", err.message); } } ``` -------------------------------- ### Example: Multiple Formats with Mixed Options Source: https://github.com/semanticist21/sinter/blob/main/_autodocs/api-reference/codec-stage.md Demonstrates setting different codec options for multiple formats within the same pipeline. ```typescript const blob = await sinter() .allowFormats(["avif", "webp"], "webp") .codecOptions({ avif: { speed: 4 }, webp: { lossless: false } }) .maxQuality(80) .compress(file); ``` -------------------------------- ### Example Result Source: https://github.com/semanticist21/sinter/blob/main/_autodocs/api-reference/worker-protocol.md A concrete example of a WorkerResultMessage object. ```typescript const result: WorkerResultMessage = { type: "result", buffer: new ArrayBuffer(4567), // Compressed bytes mime: "image/webp", originalByteLength: 12345, }; ``` -------------------------------- ### Error Handling Source: https://github.com/semanticist21/sinter/blob/main/_autodocs/INDEX.md Example demonstrating how to handle different types of errors during compression. ```typescript import { sinter, SinterValidationError, SinterCodecError } from "sinter-js"; try { const blob = await sinter() .toFormat("webp") .maxQuality(80) .timeout(30) .compress(file); } catch (err) { if (err instanceof SinterValidationError) { console.error("Invalid input:", err.message); } else if (err instanceof SinterCodecError) { console.error("Compression failed:", err.message); } else { throw err; } } ``` -------------------------------- ### Reusable Pipeline Source: https://github.com/semanticist21/sinter/blob/main/_autodocs/INDEX.md Example of creating and reusing a compression pipeline with specific format and codec options. ```typescript const pipeline = sinter() .allowFormats(["avif", "webp"], "jpeg") .codecOptions({ avif: { speed: 4 }, webp: { lossless: false } }) .maxQuality(80) .dimensions({ width: 1200 }); const blob1 = await pipeline.compress(file1); const blob2 = await pipeline.compress(file2); ``` -------------------------------- ### Execution Flow Source: https://github.com/semanticist21/sinter/blob/main/_autodocs/QUICK-REFERENCE.md Illustrates the step-by-step process of image compression. ```text compress(file) ↓ validateFile() ↓ file.arrayBuffer() ↓ executePipeline() ├─ detectFormat() ├─ decodeImage() ├─ resizeImageData() (if dimensions set) ├─ encodeImage() (or encodeFitSize() if size set) ├─ inflationGuard() └─ return ArrayBuffer ↓ new Blob([buffer], { type: mime }) ↓ Promise resolves/rejects ``` -------------------------------- ### Basic Usage Source: https://github.com/semanticist21/sinter/blob/main/README.md Example of compressing a file to WebP format with a maximum quality of 80 and a width of 1200 pixels. ```javascript import { sinter } from "sinter-js"; const blob = await sinter() .toFormat("webp") .maxQuality(80) .dimensions({ width: 1200 }) .compress(file); ``` -------------------------------- ### SinterValidationError Usage Example Source: https://github.com/semanticist21/sinter/blob/main/_autodocs/errors.md Example of catching a SinterValidationError when maxQuality is invalid. ```typescript import { SinterValidationError } from "sinter-js"; try { const blob = await sinter() .maxQuality(150) // Invalid: > 100 .compress(file); } catch (err) { if (err instanceof SinterValidationError) { console.error("Invalid input:", err.message); } } ``` -------------------------------- ### Buffer Transfer Example Source: https://github.com/semanticist21/sinter/blob/main/_autodocs/api-reference/worker-protocol.md Illustrates how to transfer an `ArrayBuffer` from the main thread to the worker, and how the worker receives and uses it. This is crucial for performance as it avoids copying large data. ```typescript // Main thread const buffer = await file.arrayBuffer(); worker.postMessage({ buffer, ... }, [buffer]); // buffer is now unusable on main thread; ownership transferred to worker // Worker receives the same buffer and processes it self.onmessage = async (e) => { const { buffer } = e.data; // Worker can read and modify buffer const bytes = new Uint8Array(buffer); // ... }; ``` -------------------------------- ### Pipeline Creation Source: https://github.com/semanticist21/sinter/blob/main/_autodocs/QUICK-REFERENCE.md Initializes a new compression pipeline. ```typescript sinter(): SinterFormatStage ``` -------------------------------- ### Example Worker Error Message Source: https://github.com/semanticist21/sinter/blob/main/_autodocs/api-reference/worker-protocol.md An example of the structure of an error message sent from the worker to the main thread. ```typescript const error: WorkerErrorMessage = { type: "error", message: "Failed to decode JPEG image: native decoder failed.", errorType: "codec", }; ``` -------------------------------- ### Reusable Pipeline Source: https://github.com/semanticist21/sinter/blob/main/_autodocs/QUICK-REFERENCE.md Demonstrates creating a reusable pipeline configuration that can be applied to multiple files. ```typescript const pipeline = sinter() .toFormat("webp") .maxQuality(80) .dimensions({ width: 1200 }); const blob1 = await pipeline.compress(file1); const blob2 = await pipeline.compress(file2); ``` -------------------------------- ### Reusable Pipeline Settings Source: https://github.com/semanticist21/sinter/blob/main/README.md Demonstrates how to create a reusable compression pipeline. ```javascript const pipeline = sinter() .toFormat("webp") .maxQuality(80) .dimensions({ width: 1200 }); const firstBlob = await pipeline.compress(firstFile); const secondBlob = await pipeline.compress(secondFile); ``` -------------------------------- ### SinterValidationError Usage: Dimensions Validation Source: https://github.com/semanticist21/sinter/blob/main/_autodocs/errors.md Example of catching a SinterValidationError for dimensions. ```typescript try { const blob = await sinter() .dimensions({ width: 0 }) // Invalid: must be positive .compress(file); } catch (err) { if (err instanceof SinterValidationError) { console.error("Bad dimensions:", err.message); } } ``` -------------------------------- ### SinterValidationError Usage: File Input Validation Source: https://github.com/semanticist21/sinter/blob/main/_autodocs/errors.md Example of catching a SinterValidationError for file input. ```typescript try { const blob = await sinter() .toFormat("webp") .compress(file); } catch (err) { if (err instanceof SinterValidationError) { // Handle empty file, invalid format, etc. alert("Please select a valid image file."); } } ``` -------------------------------- ### Handling Success Source: https://github.com/semanticist21/sinter/blob/main/_autodocs/api-reference/worker-protocol.md Example code for handling a successful WorkerResultMessage on the main thread. ```typescript worker.onmessage = (e: MessageEvent) => { const msg = e.data; if (msg.type === "result") { const blob = new Blob([msg.buffer], { type: msg.mime }); resolve(blob); worker.terminate(); } }; ``` -------------------------------- ### Main Entry Point Import Source: https://github.com/semanticist21/sinter/blob/main/_autodocs/PACKAGE.md Import the main sinter function from the sinter-js package. ```typescript import { sinter } from "sinter-js"; ``` -------------------------------- ### Import Source: https://github.com/semanticist21/sinter/blob/main/_autodocs/QUICK-REFERENCE.md Imports necessary components from the sinter-js library. ```typescript import { sinter, SinterError, SinterValidationError, SinterCodecError } from "sinter-js"; import type { ImageFormat, CodecOptions, CodecMap } from "sinter-js"; ``` -------------------------------- ### Compress Execution Source: https://github.com/semanticist21/sinter/blob/main/_autodocs/QUICK-REFERENCE.md Executes the compression pipeline. ```typescript async compress(file: File): Promise ``` ```typescript const blob = await sinter().toFormat("webp").compress(file); ``` -------------------------------- ### Graceful Degradation Source: https://github.com/semanticist21/sinter/blob/main/_autodocs/errors.md An example of implementing graceful degradation by falling back to the original file if compression fails. ```typescript async function compressImage(file) { try { return await sinter() .toFormat("webp") .maxQuality(80) .compress(file); } catch (err) { console.warn("Compression failed, using original:", err.message); return file; // or return a Blob of the original } } ``` -------------------------------- ### Combining Dimensions and Size Source: https://github.com/semanticist21/sinter/blob/main/_autodocs/configuration.md Illustrates the order of operations when both dimensions and size constraints are applied. ```typescript const blob = await sinter() .keepFormat() .dimensions({ width: 1920 }) // Resize first .size(500, "KB") // Then fit size .compress(file); ``` -------------------------------- ### Reusable Pipeline Configuration Source: https://github.com/semanticist21/sinter/blob/main/_autodocs/configuration.md Shows how to define a compression pipeline as a constant for reuse across multiple files. ```typescript const imageCompression = sinter() .allowFormats(["avif", "webp"], "jpeg") .codecOptions({ avif: { speed: 4 }, webp: { lossless: false } }) .maxQuality(80) .dimensions({ width: 1200 }); // Use the same pipeline for multiple files const firstBlob = await imageCompression.compress(firstFile); const secondBlob = await imageCompression.compress(secondFile); const thirdBlob = await imageCompression.compress(thirdFile); ``` -------------------------------- ### Fluent Pipeline Configuration Source: https://github.com/semanticist21/sinter/blob/main/_autodocs/INDEX.md Illustrates the method chaining for configuring the Sinter pipeline, showing the progression through format selection, codec options, compression, and execution. ```typescript sinter() → SinterFormatStage → SinterCodecStage → SinterBuilder → Promise ↓ ↓ ↓ ↓ format selection codec opts compression execution ``` -------------------------------- ### Size Target Source: https://github.com/semanticist21/sinter/blob/main/_autodocs/QUICK-REFERENCE.md Targets a specific output file size (best effort). ```typescript size(value: number, unit: "MB" | "KB"): Omit ``` ```typescript .size(500, "KB") ``` ```typescript .size(1, "MB") ``` -------------------------------- ### Configuration Flow Source: https://github.com/semanticist21/sinter/blob/main/_autodocs/configuration.md Sinter uses a fluent API where all configuration is set through chained method calls. There is no constructor with options; instead, use `sinter()` to create a pipeline and then call methods to configure it. ```typescript sinter() // Create pipeline .toFormat("webp") // Format stage .codecOptions({ webp: {...} }) // Codec stage .maxQuality(80) // Builder stage .dimensions({ width: 1200 }) .size(500, "KB") .timeout(30) .compress(file) // Execute ``` -------------------------------- ### Two-Phase Size Fitting Strategy Source: https://github.com/semanticist21/sinter/blob/main/_autodocs/ARCHITECTURE.md Illustrates a two-phase approach for fitting image sizes, involving quality reduction (binary search) and dimension reduction (iterative shrink). A special phase for PNGs includes palette quantization. ```typescript // Phase 1: Quality reduction (binary search) // Phase 2: Dimension reduction (iterative shrink) // For PNG: // Phase 1.5: Palette quantization (binary search) // Phase 2: Dimension reduction ``` -------------------------------- ### Design Pattern: Lazy Module Loading Source: https://github.com/semanticist21/sinter/blob/main/_autodocs/ARCHITECTURE.md Example of lazy module loading for WASM modules, ensuring they are loaded only once per codec. ```typescript // In codecs let wasmPromise: Promise | undefined; export async function decodeJpeg(buffer) { const jpeg = await loadJpegModule(); // ... } async function loadJpegModule() { wasmPromise ??= readJpegWasm(); const wasm = await wasmPromise; // ... } ```