unpic

repository·main·Indexed 19 days ago

https://github.com/ascorbic/unpic

A universal image CDN URL translator (v4.2.2) that provides a consistent interface for detecting and transforming image URLs across various CDN providers. It includes functions like transformUrl() for applying standard operations (width, height, quality, format) and parseUrl() for extracting metadata. The library supports a wide range of providers including Cloudflare Images, Cloudinary, Cloudimage, Contentstack, Supabase, and others, with support for provider-specific operations and direct imports to optimize bundle size.

Tokens
14.1K
Snippets
36
Records
46
Agent score
64%

What's inside unpic

  1. Replace URL delegation with the Fallback system

    main

    Version 4 removes the recursive URL delegation system (the recursive option). Instead, use the fallback property to explicitly define which provider should handle a URL if it is not recognized as a known CDN URL.

    This is useful for handling user-provided URLs or ensuring framework-specific optimizers (like nextjs) are used when a source URL is unrecognized.

    // Use a fallback provider when a URL isn't recognized
    transformUrl(
      {
        url: "https://example.com/image.jpg",
        width: 1200,
        fallback: "nextjs",
      },
      {},
      {
        // optional configuration for the fallback provider
      }
    );
  2. Use provider-specific operations and configurations

    main

    While transformUrl supports standard operations (width, height, quality, format), you can pass provider-specific operations as a third argument. This allows you to use features unique to a specific CDN (like crop for Shopify or position for Imgix).

    These options are type-safe. You can also pass provider-specific configuration objects (like cloudName for Cloudinary) as a fourth argument.

    import { transformUrl } from "unpic";
    
    // Using provider-specific operations
    const url = transformUrl(
    	"https://cdn.shopify.com/static/sample-images/bath.jpeg",
    	{
    		width: 800,
    		height: 600,
    	},
    	{
    		shopify: {
    			crop: "center",
    		},
    	},
    );
    
    // Using provider-specific configurations (e.g., Cloudinary cloudName)
    const urlWithConfig = transformUrl(
    	src,
    	{
    		width: 800,
    		height: 600,
    		fallback: "cloudinary",
    	},
    	{
    		shopify: {
    			crop: "left",
    		},
    	},
    	{
    		cloudinary: {
    			cloudName: "demo",
    		},
    	},
    );
  3. Migrate transformUrl from Version 3 to Version 4

    main

    In Version 4, the transformUrl function signature has changed to improve type safety and separate concerns. Instead of a single object containing everything, it now uses three distinct arguments:

    1. Primary Options: An object containing the url, dimensions (width, height), and the provider (use provider instead of the deprecated cdn).
    2. Operations: An object containing provider-specific operations (e.g., crop, gravity).
    3. Provider Configuration: An object containing provider-specific configuration (e.g., cloudName, baseUrl).

    Migration Summary:

    • Replace cdn with provider (though cdn is still supported but deprecated).
    • Move provider-specific operations from cdnOptions to the second argument.
    • Move provider configuration (like API keys or project names) to the third argument.
    // Version 4 signature
    transformUrl(
      {
        url: "https://example.com/image.jpg",
        width: 800,
        provider: "shopify",
      },
      {
        shopify: {
          crop: "center",
        },
      },
      {
        shopify: {
          // configuration options here
        },
      }
    );
  4. Use direct provider imports for better tree-shaking

    main

    To reduce bundle size, you can import specific provider transformation functions directly instead of using the main transformUrl entry point. This allows for better tree-shaking of unused provider logic.

    import { transform } from "unpic/providers/shopify";
    
    const url = transform(
      "https://cdn.shopify.com/image.jpg",
      {
        width: 800,
        crop: "center",
      },
    );
  5. Migrate to v3.0.0: Breaking Changes

    main

    When upgrading from v2.x to v3.0.0, be aware of the following breaking change:

    • Transformer Return Types: Transformers may now return URLs as plain strings instead of other object types. Ensure your implementation handles string return values from transformers correctly.
  6. Optimize bundle size with direct provider imports

    main

    If you know exactly which CDN provider you are using, you can import a specific transform function from that provider's subpath. This allows tree-shaking to remove unused provider logic, reducing your application's bundle size.

    import { transform } from "unpic/providers/shopify";
    
    const url = transform(
    	"https://cdn.shopify.com/static/sample-images/bath.jpeg",
    	{
    		width: 800,
    		height: 600,
    		crop: "center",
    	},
    );
  7. Use type-safe provider operations in TypeScript

    main

    In Version 4, transformUrl supports generics to provide type safety for provider-specific operations. By passing the provider name as a type argument, TypeScript will validate that only valid options for that specific provider are used.

    // Type-safe: only valid Shopify options are allowed in the second argument
    transformUrl<"shopify">({
      url: url,
      width: 800,
      provider: "shopify",
    }, {
      shopify: {
        crop: "center",
      },
    });
  8. Understand changes to parseUrl and URL extractors

    main

    The parseUrl function has been updated in Version 4. It now returns a different object structure and supports generic types.

    Old Structure (v3):

    • cdn: provider name
    • width/height: dimensions
    • base: the base URL
    • params: URL parameters

    New Structure (v4):

    • provider: provider name (or cdn)
    • src: the base URL
    • operations: an object containing width, height, and other transformation parameters.

    New in v4: URL Extractors You can now use getExtractorForUrl(url) to obtain an extractor function that can parse specific URL formats.

  9. Parse image URLs with parseUrl()

    main

    The parseUrl function analyzes an existing image URL to extract information about its origin and current transformations. It returns an object containing the detected provider, the original src (without existing transforms), and the operations currently applied to the URL.

    import { parseUrl } from "unpic";
    
    const parsed = parseUrl(
    	"https://cdn.shopify.com/static/sample-images/bath_800x600_crop_center.jpeg",
    );
    
    // Result:
    // {
    //   provider: "shopify",
    //   src: "https://cdn.shopify.com/static/sample-images/bath.jpeg",
    //   operations: {
    //     width: 800,
    //     height: 600,
    //     crop: "center"
    //   }
    // }
  10. Transform image URLs with transformUrl()

    main

    The transformUrl function takes an image URL and an options object to generate a new URL with transformations applied.

    By default, it supports the following standard operations:

    • width
    • height
    • quality
    • format

    If the source URL is not recognized as a known CDN, you can specify a fallback provider. You can also bypass auto-detection by explicitly providing a provider.

    import { transformUrl } from "unpic";
    
    const url = transformUrl(
    	"https://cdn.shopify.com/static/sample-images/bath_grande_crop_center.jpeg",
    	{
    		width: 800,
    		height: 600,
    	},
    );
    // Output: https://cdn.shopify.com/static/sample-images/bath.jpeg?width=800&height=600&crop=center
  11. Configure Cloudflare provider options

    main

    When using the Cloudflare provider, you can specify the domain in the CloudflareOptions object. This is used during URL generation to construct the base URL for the Cloudflare Image service.

    const options: CloudflareOptions = {
      domain: 'your-cloudflare-domain.com'
    };