diff --git a/CHANGELOG.md b/CHANGELOG.md index 03d7092..1033ef1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,26 @@ # Changelog +## Version 4.0.0 + +### Breaking Changes + +1. The default value for `transformationPosition` is now `query` instead of `path`. This change enables wildcard cache purging to remove CDN cache for all generated transformations. + + **Action Required:** + If you're using the `transformationPosition` parameter in the `url` method and want to apply transformations in the path, you must now explicitly set the value to `path`. The default is `query`. + +2. Removed the following deprecated parameters: + `effectSharpen`, `effectUSM`, `effectContrast`, `effectGray`, `effectShadow`, `effectGradient`, and `rotate`. + +### Other Changes + +1. Native support for overlays has been added. See the README for usage examples. +2. New AI-powered transformations are now supported: + `aiRemoveBackground`, `aiUpscale`, `aiVariation`, `aiDropShadow`, `aiChangeBackground`, and more. + *(Introduced in version 3.1.0)* + +--- + ## SDK Version 3.0.0 ### Breaking Changes diff --git a/README.md b/README.md index 2b06eea..c79c405 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) [![Twitter Follow](https://img.shields.io/twitter/follow/imagekitio?label=Follow&style=social)](https://twitter.com/ImagekitIo) -Lightweight JavaScript SDK for generating optimized URLs for images and videos, and for handling file uploads via ImageKit. +A lightweight JavaScript SDK for generating image and video URLs with transformations, and for uploading files directly from the browser to ImageKit. This SDK is intended for use in the browser only. For Node.js, please refer to our official [Node.js SDK](https://github.com/imagekit-developer/imagekit-nodejs). ## Table of Contents - [Installation](#installation) @@ -18,6 +18,10 @@ Lightweight JavaScript SDK for generating optimized URLs for images and videos, - [URL Generation](#url-generation) - [Basic URL Generation](#basic-url-generation) - [Advanced URL Generation Examples](#advanced-url-generation-examples) + - [Chained Transformations](#chained-transformations) + - [Overlays and Effects](#overlays-and-effects) + - [AI and Advanced Transformations](#ai-and-advanced-transformations) + - [Arithmetic Expressions in Transformations](#arithmetic-expressions-in-transformations) - [Supported Transformations](#supported-transformations) - [Handling Unsupported Transformations](#handling-unsupported-transformations) - [File Upload](#file-upload) @@ -50,68 +54,74 @@ Download a specific version: ``` https://unpkg.com/imagekit-javascript@1.3.0/dist/imagekit.min.js ``` -Or for the latest version, remove the version number: +Or for the latest version, remove the version number (don't use in production as it may break your code if a new major version is released): ``` https://unpkg.com/imagekit-javascript/dist/imagekit.min.js ``` + And include it in your HTML: ```html ``` ## Initialization +To use the SDK, initialize it with your ImageKit URL endpoint. You can get the URL endpoint [here](https://imagekit.io/dashboard/url-endpoints) and your public API key from the [developer section](https://imagekit.io/dashboard/developer/api-keys): -Initialize the SDK by specifying your URL endpoint. You can obtain your URL endpoint from [https://imagekit.io/dashboard/url-endpoints](https://imagekit.io/dashboard/url-endpoints) and your public API key from [https://imagekit.io/dashboard/developer/api-keys](https://imagekit.io/dashboard/developer/api-keys). For URL generation: ```js var imagekit = new ImageKit({ - urlEndpoint: "https://ik.imagekit.io/your_imagekit_id" + urlEndpoint: "https://ik.imagekit.io/your_imagekit_id", // Required + transformationPosition: "query", // Optional, defaults to "query" + publicKey: "your_public_api_key", // Optional, required only for client-side file uploads }); ``` -For client-side file uploads, include your public key: -```js -var imagekit = new ImageKit({ - publicKey: "your_public_api_key", - urlEndpoint: "https://ik.imagekit.io/your_imagekit_id", -}); -``` -*Note: Never include your private key in client-side code. If provided, the SDK throws an error.* + +> Note: Never include your private API key in client-side code. The SDK will throw an error if you do. + +### Initialization Options + +| Option | Description | Example | +| ---------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------- | +| urlEndpoint | Required. Your ImageKit URL endpoint or custom domain. | `urlEndpoint: "https://ik.imagekit.io/your_id"` | +| transformationPosition | Optional. Specifies whether transformations are added as URL path segments (`path`) or query parameters (`query`). The default is `query`, which allows you to perform wildcard purges and remove all generated transformations from the CDN cache. | `transformationPosition: "query"` | +| publicKey | Optional. Your public API key for client-side uploads. | `publicKey: "your_public_api_key"` | + ## URL Generation The SDK’s `.url()` method enables you to generate optimized image and video URLs with a variety of transformations. +The method accepts an object with the following parameters: + +| Option | Description | Example | +| --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------- | +| path | The relative path of the image. Either `src` or `path` must be provided. | `"/path/to/image.jpg"` | +| src | The full URL of an image already mapped to ImageKit. Either `src` or `path` must be provided. | `"https://ik.imagekit.io/your_imagekit_id/path/to/image.jpg"` | +| transformation | An array of objects specifying the transformations to be applied in the URL. Each object contains key-value pairs representing transformation parameters. See [supported transformations](#supported-transformations). | `[ { width: 300, height: 400 } ]` | +| queryParameters | Additional query parameters to be appended to the URL. | `{ v: 1 }` | + +Optionally, you can include `transformationPosition` and `urlEndpoint` in the object to override the initialization settings for a specific `.url()` call. + ### Basic URL Generation -1. **Using an Image Path with a URL Endpoint** - ```js - var imageURL = imagekit.url({ - path: "/default-image.jpg", - urlEndpoint: "https://ik.imagekit.io/your_imagekit_id/endpoint/", - transformation: [{ - "height": "300", - "width": "400" - }] - }); - ``` - *Result Example:* - ``` - https://ik.imagekit.io/your_imagekit_id/endpoint/tr:h-300,w-400/default-image.jpg - ``` - -2. **Using a Full Image URL (src)** - ```js - var imageURL = imagekit.url({ - src: "https://ik.imagekit.io/your_imagekit_id/endpoint/default-image.jpg", - transformation: [{ - "height": "300", - "width": "400" - }] - }); - ``` - *Result Example:* - ``` - https://ik.imagekit.io/your_imagekit_id/endpoint/default-image.jpg?tr=h-300%2Cw-400 - ``` +*A simple height and width transformation:* + +```js +var imageURL = imagekit.url({ + path: "/default-image.jpg", + urlEndpoint: "https://ik.imagekit.io/your_imagekit_id/endpoint/", + transformation: [{ + height: 300, + width: 400 + }] +}); +``` + +*Result Example:* +``` +https://ik.imagekit.io/your_imagekit_id/endpoint/default-image.jpg?tr=h-300,w-400 +``` + +SDK automatically generates the URL based on the provided parameters. The generated URL includes the base URL, path, and transformation parameters. ### Advanced URL Generation Examples @@ -121,17 +131,17 @@ Apply multiple transformations by passing an array: var imageURL = imagekit.url({ path: "/default-image.jpg", transformation: [{ - "height": "300", - "width": "400" + height: 300, + width: 400 }, { - "rotation": 90 + rotation: 90 }], - transformationPosition: "query" // Use query parameter for transformations }); ``` + *Result Example:* ``` -https://ik.imagekit.io/your_imagekit_id/default-image.jpg?tr=h-300%2Cw-400%3Art-90 +https://ik.imagekit.io/your_imagekit_id/default-image.jpg?tr=h-300,w-400:rt-90 ``` #### Overlays and Effects @@ -140,24 +150,182 @@ https://ik.imagekit.io/your_imagekit_id/default-image.jpg?tr=h-300%2Cw-400%3Art- var imageURL = imagekit.url({ src: "https://ik.imagekit.io/your_imagekit_id/default-image.jpg", transformation: [{ - "width": 400, - "height": 300, - "raw": "l-text,i-Imagekit,fs-50,l-end" + width: 400, + height: 300, + overlay: { + text: "Imagekit", + fontSize: 50, + color: "red", + position: { + x: 10, + y: 20 + } + } }] }); ``` + *Image Overlay Example:* + ```js var imageURL = imagekit.url({ src: "https://ik.imagekit.io/your_imagekit_id/default-image.jpg", transformation: [{ - "width": 400, - "height": 300, - "raw": "l-image,i-default-image.jpg,w-100,b-10_CDDC39,l-end" + width: 400, + height: 300, + overlay: { + type: "image", + input: "logo.png", + transformation: [{ + width: 100, + border: "10_CDDC39" + }], + position: { + focus: "top_left" + } + } + }] +}); +``` + +*Video Overlay Example:* + +```js +var videoOverlayURL = imagekit.url({ + src: "https://ik.imagekit.io/your_imagekit_id/base-video.mp4", + transformation: [{ + overlay: { + type: "video", + input: "overlay-video.mp4", + position: { + x: "10", + y: "20" + }, + timing: { + start: 5, + duration: 10 + } + } + }] +}); +``` + +*Subtitle Overlay Example:* + +```js +var subtitleOverlayURL = imagekit.url({ + src: "https://ik.imagekit.io/your_imagekit_id/base-video.mp4", + transformation: [{ + overlay: { + type: "subtitle", + input: "subtitle.vtt", + transformation: [{ + fontSize: 16, + fontFamily: "Arial" + }], + position: { + focus: "bottom" + }, + timing: { + start: 0, + duration: 5 + } + } + }] +}); +``` + +*Solid Color Overlay Example:* +```js +var solidColorOverlayURL = imagekit.url({ + src: "https://ik.imagekit.io/your_imagekit_id/base-image.jpg", + transformation: [{ + overlay: { + type: "solidColor", + color: "FF0000", + transformation: [{ + width: 100, + height: 50, + alpha: 5 + }], + position: { x: 20, y: 20 } + } }] }); ``` +##### Overlay Options + +ImageKit supports various overlay types, including text, image, video, subtitle, and solid color overlays. Each overlay type has specific configuration options to customize the overlay appearance and behavior. To learn more about how overlays work, refer to the [ImageKit documentation](https://imagekit.io/docs/transformations#overlay-using-layers). + +The table below outlines the available overlay configuration options: + +| Option | Description | Example | +| -------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------- | +| type | Specifies the type of overlay. Supported values: `text`, `image`, `video`, `subtitle`, `solidColor`. | `type: "text"` | +| text | (For text overlays) The text content to display. | `text: "ImageKit"` | +| input | (For image, video, or subtitle overlays) Relative path to the overlay asset. | `input: "logo.png"` or `input: "overlay-video.mp4"` | +| color | (For solidColor overlays) RGB/RGBA hex code or color name for the overlay color. | `color: "FF0000"` | +| encoding | Accepted values: `auto`, `plain`, `base64`. [Check this](#encoding-options) for more details. | `encoding: "auto"` | +| transformation | An array of transformation objects to style the overlay.
- [Text Overlay Transformations](#text-overlay-transformations)
- [Subtitle Overlay Transformations](#subtitle-overlay-transformations)
- Image and video overlays support most [transformations](#supported-transformations).
See [ImageKit docs](https://imagekit.io/docs/transformations#overlay-using-layers) for more details. | `transformation: [{ fontSize: 50 }]` | +| position | Sets the overlay’s position relative to the base asset. Accepts an object with `x`, `y`, or `focus`. The `focus` value can be one of: `center`, `top`, `left`, `bottom`, `right`, `top_left`, `top_right`, `bottom_left`, or `bottom_right`. | `position: { x: 10, y: 20 }` or `position: { focus: "center" }` | +| timing | (For video base) Specifies when the overlay appears using `start`, `duration`, and `end` (in seconds); if both `duration` and `end` are set, `duration` is ignored. | `timing: { start: 5, duration: 10 }` | + +##### Encoding Options + +Overlay encoding options define how the overlay input is converted for URL construction. When set to `auto`, the SDK automatically determines whether to use plain text or Base64 encoding based on the input content. + +For text overlays: +- If `auto` is used, the SDK checks the text overlay input: if it is URL-safe, it uses the format `i-{input}` (plain text); otherwise, it applies Base64 encoding with the format `ie-{base64_encoded_input}`. +- You can force a specific method by setting encoding to `plain` (always use `i-{input}`) or `base64` (always use `ie-{base64}`). +- Note: In all cases, the text is percent-encoded to ensure URL safety. + +For image, video, and subtitle overlays: +- The input path is processed by removing any leading/trailing slashes and replacing inner slashes with `@@` when `plain` is used. +- Similarly, if `auto` is used, the SDK determines whether to apply plain text or Base64 encoding based on the characters present. +- For explicit behavior, use `plain` or `base64` to enforce the desired encoding. + +Use `auto` for most cases to let the SDK optimize encoding, and use `plain` or `base64` when a specific encoding method is required. + +##### Solid Color Overlay Transformations + +| Option | Description | Example | +| ------ | ---------------------------------------------------------------------------------------------------------------------------------- | --------------- | +| width | Specifies the width of the solid color overlay block (in pixels or as an arithmetic expression). | `width: 100` | +| height | Specifies the height of the solid color overlay block (in pixels or as an arithmetic expression). | `height: 50` | +| radius | Specifies the corner radius of the solid color overlay block or shape. Can be a number or `"max"` for circular/oval shapes. | `radius: "max"` | +| alpha | Specifies the transparency level of the solid color overlay. Supports integers from 1 (most transparent) to 9 (least transparent). | `alpha: 5` | + +##### Text Overlay Transformations + +| Option | Description | Example | +| -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------- | +| width | Specifies the maximum width (in pixels) of the overlaid text. The text wraps automatically, and arithmetic expressions are supported (e.g., `bw_mul_0.2` or `bh_div_2`). | `width: 400` | +| fontSize | Specifies the font size of the overlaid text. Accepts a numeric value or an arithmetic expression. | `fontSize: 50` | +| fontFamily | Specifies the font family of the overlaid text. Choose from the supported fonts or provide a custom font. | `fontFamily: "Arial"` | +| fontColor | Specifies the font color of the overlaid text. Accepts an RGB hex code, an RGBA code, or a standard color name. | `fontColor: "FF0000"` | +| innerAlignment | Specifies the inner alignment of the text when it doesn’t occupy the full width. Supported values: `left`, `right`, `center`. | `innerAlignment: "center"` | +| padding | Specifies the padding around the text overlay. Can be a single integer or multiple values separated by underscores; arithmetic expressions are accepted. | `padding: 10` | +| alpha | Specifies the transparency level of the text overlay. Accepts an integer between `1` and `9`. | `alpha: 5` | +| typography | Specifies the typography style of the text. Supported values: `b` for bold, `i` for italics, and `b_i` for bold with italics. | `typography: "b"` | +| background | Specifies the background color of the text overlay. Accepts an RGB hex code, an RGBA code, or a color name. | `background: "red"` | +| radius | Specifies the corner radius of the text overlay. Accepts a numeric value or `max` for circular/oval shape. | `radius: "max"` | +| rotation | Specifies the rotation angle of the text overlay. Accepts a numeric value for clockwise rotation or a string prefixed with `N` for counterclockwise rotation. | `rotation: 90` | +| flip | Specifies the flip option for the text overlay. Supported values: `h`, `v`, `h_v`, `v_h`. | `flip: "h"` | +| lineHeight | Specifies the line height for multi-line text. Accepts a numeric value or an arithmetic expression. | `lineHeight: 1.5` | + +##### Subtitle Overlay Transformations + +| Option | Description | Example | +| ----------- | --------------------------------------------------------------------------------------------------------- | ----------------------- | +| background | Specifies the subtitle background color using a standard color name, RGB color code, or RGBA color code. | `background: "blue"` | +| fontSize | Sets the font size of subtitle text. | `fontSize: 16` | +| fontFamily | Sets the font family of subtitle text. | `fontFamily: "Arial"` | +| color | Specifies the font color of subtitle text using standard color name, RGB, or RGBA color code. | `color: "FF0000"` | +| typography | Sets the typography style of subtitle text. Supported values: `b`, `i`, `b_i`. | `typography: "b"` | +| fontOutline | Specifies the font outline for subtitles. Requires an outline width and color separated by an underscore. | `fontOutline: "2_blue"` | +| fontShadow | Specifies the font shadow for subtitles. Requires shadow color and indent separated by an underscore. | `fontShadow: "blue_2"` | + #### AI and Advanced Transformations *Background Removal:* ```js @@ -192,73 +360,74 @@ var dropShadowURL = imagekit.url({ var imageURL = imagekit.url({ src: "https://ik.imagekit.io/your_imagekit_id/default-image.jpg", transformation: [{ - "width": "iw_div_4", - "height": "ih_div_2", - "border": "cw_mul_0.05_yellow" + width: "iw_div_4", + height: "ih_div_2", + border: "cw_mul_0.05_yellow" }] }); ``` ### Supported Transformations -The SDK gives a name to each transformation parameter e.g. height for h and width for w parameter. It makes your code more readable. If the property does not match any of the following supported options, it is added as it is. +The SDK gives a name to each transformation parameter (e.g. `height` maps to `h`, `width` maps to `w`). If the property does not match any of the following supported options, it is added as is. -If you want to generate transformations in your application and add them to the URL as it is, use the raw parameter. +If you want to generate transformations without any modifications, use the `raw` parameter. Check ImageKit [transformation documentation](https://imagekit.io/docs/transformations) for more details. -| Transformation Name | URL Parameter | -| -------------------------- | ------------------------------------------------------------- | -| width | w | -| height | h | -| aspectRatio | ar | -| quality | q | -| aiRemoveBackground | e-bgremove (ImageKit powered) | -| aiRemoveBackgroundExternal | e-removedotbg (Using third party) | -| aiUpscale | e-upscale | -| aiRetouch | e-retouch | -| aiVariation | e-genvar | -| aiDropShadow | e-dropshadow | -| aiChangeBackground | e-changebg | -| crop | c | -| cropMode | cm | -| x | x | -| y | y | -| xCenter | xc | -| yCenter | yc | -| focus | fo | -| format | f | -| radius | r | -| background | bg | -| border | b | -| rotation | rt | -| blur | bl | -| named | n | -| dpr | dpr | -| progressive | pr | -| lossless | lo | -| trim | t | -| metadata | md | -| colorProfile | cp | -| defaultImage | di | -| original | orig | -| videoCodec | vc | -| audioCodec | ac | -| grayscale | e-grayscale | -| contrastStretch | e-contrast | -| shadow | e-shadow | -| sharpen | e-sharpen | -| unsharpMask | e-usm | -| gradient | e-gradient | -| flip | fl | -| opacity | o | -| zoom | z | -| page | pg | -| startOffset | so | -| endOffset | eo | -| duration | du | -| streamingResolutions | sr | -| raw | The string provided in raw will be added in the URL as it is. | +| Transformation Name | URL Parameter | +| -------------------------- | ---------------------------------------------------------------------------------------------- | +| width | w | +| height | h | +| aspectRatio | ar | +| quality | q | +| aiRemoveBackground | e-bgremove (ImageKit powered) | +| aiRemoveBackgroundExternal | e-removedotbg (Using third party) | +| aiUpscale | e-upscale | +| aiRetouch | e-retouch | +| aiVariation | e-genvar | +| aiDropShadow | e-dropshadow | +| aiChangeBackground | e-changebg | +| crop | c | +| cropMode | cm | +| x | x | +| y | y | +| xCenter | xc | +| yCenter | yc | +| focus | fo | +| format | f | +| radius | r | +| background | bg | +| border | b | +| rotation | rt | +| blur | bl | +| named | n | +| dpr | dpr | +| progressive | pr | +| lossless | lo | +| trim | t | +| metadata | md | +| colorProfile | cp | +| defaultImage | di | +| original | orig | +| videoCodec | vc | +| audioCodec | ac | +| grayscale | e-grayscale | +| contrastStretch | e-contrast | +| shadow | e-shadow | +| sharpen | e-sharpen | +| unsharpMask | e-usm | +| gradient | e-gradient | +| flip | fl | +| opacity | o | +| zoom | z | +| page | pg | +| startOffset | so | +| endOffset | eo | +| duration | du | +| streamingResolutions | sr | +| overlay | Generates the correct layer syntax for image, video, text, subtitle, and solid color overlays. | +| raw | The string provided in raw will be added in the URL as is. | ### Handling Unsupported Transformations @@ -269,10 +438,10 @@ For example: var imageURL = imagekit.url({ path: "/test_path.jpg", transformation: [{ - "newparam": "cool" + newparam: "cool" }] }); -// Generated URL: https://ik.imagekit.io/test_url_endpoint/tr:newparam-cool/test_path.jpg +// Generated URL: https://ik.imagekit.io/test_url_endpoint/test_path.jpg?tr=newparam-cool ``` ## File Upload @@ -284,6 +453,31 @@ The SDK offers a simple interface via the `.upload()` method to upload files to Before invoking the upload, generate the necessary security parameters as per the [ImageKit Upload API documentation](https://imagekit.io/docs/api-reference/upload-file/upload-file#how-to-implement-client-side-file-upload). +### Upload Options +| Option | Description | Example | +| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------- | +| file | The file content to be uploaded. Accepts binary, base64 string, or URL. | `file: fileInput.files[0]` | +| fileName | The name to assign to the uploaded file. Supports alphanumeric characters, dot, underscore, and dash. | `fileName: "myImage.jpg"` | +| signature | HMAC-SHA1 digest computed using the private API key. Must be calculated on the server side. | `signature: "generated_signature"` | +| token | A unique token to prevent duplicate upload retries. Typically a V4 UUID or similar unique string. | `token: "unique_upload_token"` | +| expire | Unix timestamp (in seconds) indicating the signature expiry time (should be within 1 hour). | `expire: 1616161616` | +| useUniqueFileName | Boolean flag to automatically generate a unique filename if set to true. Defaults to true. | `useUniqueFileName: true` | +| folder | The folder path where the file will be uploaded. Automatically creates nested folders if they don’t exist. | `folder: "/images/uploads"` | +| isPrivateFile | Boolean to mark the file as private, restricting access to the original file URL. Defaults to false. | `isPrivateFile: false` | +| tags | Tags to associate with the file. Can be a comma-separated string or an array of tags. | `tags: "summer,holiday"` or `tags: ["summer","holiday"]` | +| customCoordinates | Specifies an area of interest in the image formatted as `x,y,width,height`. | `customCoordinates: "10,10,100,100"` | +| responseFields | Comma-separated list of fields to include in the upload response. | `responseFields: "tags,customCoordinates"` | +| extensions | Array of extension objects for additional image processing. | `extensions: [{ name: "auto-tagging" }]` | +| webhookUrl | URL to which the final status of extension processing will be sent. | `webhookUrl: "https://example.com/webhook"` | +| overwriteFile | Boolean flag indicating whether to overwrite a file if it exists. Defaults to true. | `overwriteFile: true` | +| overwriteAITags | Boolean flag to remove AITags from a file if overwritten. Defaults to true. | `overwriteAITags: true` | +| overwriteTags | Boolean flag that determines if existing tags should be removed when new tags are not provided. Defaults to true when file is overwritten without tags. | `overwriteTags: true` | +| overwriteCustomMetadata | Boolean flag dictating if existing custom metadata should be removed when not provided. Defaults to true under similar conditions as tags. | `overwriteCustomMetadata: true` | +| customMetadata | Stringified JSON or an object containing custom metadata key-value pairs to associate with the file. | `customMetadata: {author: "John Doe"}` | +| transformation | Optional transformation object to apply during the upload process. It follows the same structure as in URL generation. | `transformation: { pre: "w-200,h-200", post: [...] }` | +| xhr | An optional XMLHttpRequest object provided to monitor upload progress. | `xhr: new XMLHttpRequest()` | +| checks | Optional string value for specifying server-side checks to run before file upload. | `checks: "file.size' < '1MB'"` | + ### Basic Upload Example Below is an HTML form example that uses a callback for handling the upload response: @@ -338,10 +532,10 @@ imagekit.upload({ ## Test Examples -For a quick demonstration of the SDK features, refer to our test examples: -- URL Generation examples can be found in [test/url-generation.js](./test/url-generation.js) -- File Upload examples can be found in [test/upload.js](./test/upload.js) +For a quick demonstration of the SDK features, check the test suite: +- URL generation examples can be found in [basic](./test/url-generation/basic.js) and [overlay](./test/url-generation/overlay.js) +- File upload examples can be found in [test/upload.js](./test/upload.js) ## Changelog -For a detailed history of changes, please refer to [CHANGELOG.md](CHANGELOG.md). +For a detailed history of changes, please refer to [CHANGELOG.md](CHANGELOG.md). \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index b1f0c3f..7f04be8 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,6 +1,6 @@ { "name": "imagekit-javascript", - "version": "3.1.0", + "version": "4.0.0", "lockfileVersion": 1, "requires": true, "dependencies": { diff --git a/package.json b/package.json index 1938f2e..2e5d45f 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "imagekit-javascript", - "version": "3.1.0", + "version": "4.0.0", "description": "Javascript SDK for using ImageKit.io in the browser", "main": "dist/imagekit.cjs.js", "module": "dist/imagekit.esm.js", @@ -43,7 +43,7 @@ "dev": "rollup -c -w", "export-types": "tsc", "build": "rm -rf dist*;rollup -c && yarn export-types", - "test": "NODE_ENV=test nyc ./node_modules/mocha/bin/mocha test/*.js", + "test": "NODE_ENV=test nyc ./node_modules/mocha/bin/mocha \"test/**/*.js\"", "startSampleApp": "yarn build && cd samples/sample-app/ && yarn install && node index.js", "report-coverage": "codecov" }, @@ -56,13 +56,13 @@ "javascript", "sdk", "js", - "sdk", "image", "optimization", - "image", "transformation", - "image", - "resize" + "resize", + "upload", + "video", + "overlay" ], "author": "ImageKit Developer", "license": "MIT", diff --git a/src/constants/supportedTransforms.ts b/src/constants/supportedTransforms.ts index bbc560f..8353ceb 100644 --- a/src/constants/supportedTransforms.ts +++ b/src/constants/supportedTransforms.ts @@ -32,15 +32,6 @@ export const supportedTransforms: { [key: string]: string } = { duration: "du", streamingResolutions: "sr", - // Old deprecated mappings - effectSharpen: "e-sharpen", - effectUSM: "e-usm", - effectContrast: "e-contrast", - effectGray: "e-grayscale", - effectShadow: "e-shadow", - effectGradient: "e-gradient", - rotate: "rt", - // AI & advanced effects grayscale: "e-grayscale", aiUpscale: "e-upscale", @@ -66,6 +57,20 @@ export const supportedTransforms: { [key: string]: string } = { zoom: "z", page: "pg", + // Text overlay transformations which are not defined yet + fontSize: "fs", + fontFamily: "ff", + fontColor: "co", + innerAlignment: "ia", + padding: "pa", + alpha: "al", + typography: "tg", + lineHeight: "lh", + + // Subtitles transformations which are not defined + fontOutline: "fol", + fontShadow: "fsh", + // Raw pass-through raw: "raw", }; diff --git a/src/index.ts b/src/index.ts index 9b88b33..6594fa7 100644 --- a/src/index.ts +++ b/src/index.ts @@ -37,13 +37,12 @@ const promisify = function (thisContext: ImageKit, fn: Function) { class ImageKit { options: ImageKitOptions = { - sdkVersion: `javascript-${version}`, publicKey: "", urlEndpoint: "", transformationPosition: transformationUtils.getDefault(), }; - constructor(opts: Omit) { + constructor(opts: ImageKitOptions) { this.options = { ...this.options, ...(opts || {}) }; if (!mandatoryParametersAvailable(this.options)) { throw errorMessages.MANDATORY_INITIALIZATION_MISSING; diff --git a/src/interfaces/ImageKitOptions.ts b/src/interfaces/ImageKitOptions.ts index d7394f0..6f8b78f 100644 --- a/src/interfaces/ImageKitOptions.ts +++ b/src/interfaces/ImageKitOptions.ts @@ -2,7 +2,6 @@ import { TransformationPosition } from "."; export interface ImageKitOptions { urlEndpoint: string; - sdkVersion?: string; publicKey?: string; transformationPosition?: TransformationPosition; } diff --git a/src/interfaces/Transformation.ts b/src/interfaces/Transformation.ts index a963f8f..adbe8dd 100644 --- a/src/interfaces/Transformation.ts +++ b/src/interfaces/Transformation.ts @@ -1,426 +1,722 @@ export type TransformationPosition = "path" | "query"; -type StreamingResolution = "240" | "360" | "480" | "720" | "1080" | "1440" | "2160"; +export type StreamingResolution = "240" | "360" | "480" | "720" | "1080" | "1440" | "2160"; /** - * The SDK provides easy to use names for transformations. These names are converted to the corresponding transformation string before being added to the URL. + * The SDK provides easy-to-use names for transformations. These names are converted to the corresponding transformation string before being added to the URL. * SDKs are updated regularly to support new transformations. If you want to use a transformation that is not supported by the SDK, you can use the `raw` parameter to pass the transformation string directly. * - * {@link https://imagekit.io/docs/transformations} + * {@link https://imagekit.io/docs/transformations|Transformations Documentation} */ export interface Transformation { /** - * The width of the output. If a value between 0 and 1 is used, it’s treated - * as a percentage (e.g., `0.4` -> 40% of original width). You can also supply - * arithmetic expressions (e.g., `"iw_div_2"`). + * Specifies the width of the output. If a value between 0 and 1 is provided, it is treated as a percentage + * (e.g., `0.4` represents 40% of the original width). You can also supply arithmetic expressions (e.g., `iw_div_2`). * - * {@link https://imagekit.io/docs/image-resize-and-crop#width---w} + * Width transformation - {@link https://imagekit.io/docs/image-resize-and-crop#width---w|Images} | {@link https://imagekit.io/docs/video-resize-and-crop#width---w|Videos} */ width?: number | string; /** - * The height of the output. If a value between 0 and 1 is used, it’s treated - * as a percentage (e.g., `0.5` -> 50% of original height). You can also supply - * arithmetic expressions (e.g., `"ih_mul_0.5"`). + * Specifies the height of the output. If a value between 0 and 1 is provided, it is treated as a percentage + * (e.g., `0.5` represents 50% of the original height). You can also supply arithmetic expressions (e.g., `ih_mul_0.5`). * - * {@link https://imagekit.io/docs/image-resize-and-crop#height---h} + * Height transformation - {@link https://imagekit.io/docs/image-resize-and-crop#height---h|Images} | {@link https://imagekit.io/docs/video-resize-and-crop#height---h|Videos} */ height?: number | string; /** - * Specifies the aspect ratio for the output, e.g., `"ar-4-3"`. - * Typically used with either width or height (not both). - * Example usage: `aspectRatio = "4:3"` or `"4_3"` or an expression like `"iar_div_2"`. + * Specifies the aspect ratio for the output, e.g., "ar-4-3". Typically used with either width or height (but not both). + * For example: aspectRatio = `4:3`, `4_3`, or an expression like `iar_div_2`. * - * {@link https://imagekit.io/docs/image-resize-and-crop#aspect-ratio---ar} + * {@link https://imagekit.io/docs/image-resize-and-crop#aspect-ratio---ar|Image Resize and Crop - Aspect Ratio} */ aspectRatio?: number | string; /** - * Specify the background that can be used along with some cropping strategies while resizing an image: - * - A solid color: `"red"`, `"F3F3F3"`, `"AAFF0010"`. + * Specifies the background to be used in conjunction with certain cropping strategies when resizing an image. + * - A solid color: e.g., `red`, `F3F3F3`, `AAFF0010`. * - * {@link https://imagekit.io/docs/effects-and-enhancements#solid-color-background} + * {@link https://imagekit.io/docs/effects-and-enhancements#solid-color-background|Effects and Enhancements - Solid Color Background} * - * - A blurred background: `"blurred"`, `"blurred_25_N15"`, etc. + * - A blurred background: e.g., `blurred`, `blurred_25_N15`, etc. * - * {@link https://imagekit.io/docs/effects-and-enhancements#blurred-background} + * {@link https://imagekit.io/docs/effects-and-enhancements#blurred-background|Effects and Enhancements - Blurred Background} * - * - Expand the image boundaries using generative fill: `genfill`. Optionally control the background scene by passing text prompt: `genfill[:-prompt-${text}]` or `genfill[:-prompte-${urlencoded_base64_encoded_text}]`. + * - Expand the image boundaries using generative fill: `genfill`. Not supported inside overlay. Optionally, control the background scene by passing a text prompt: + * `genfill[:-prompt-${text}]` or `genfill[:-prompte-${urlencoded_base64_encoded_text}]`. * - * {@link https://imagekit.io/docs/ai-transformations#generative-fill-bg-genfill} + * {@link https://imagekit.io/docs/ai-transformations#generative-fill-bg-genfill|AI Transformations - Generative Fill Background} */ background?: string; /** - * Add a border to the output media. Accepts `_`, - * e.g. `"5_FFF000"` (5px yellow border), or an expression like `"ih_div_20_FF00FF"`. + * Adds a border to the output media. Accepts a string in the format `_` + * (e.g., `5_FFF000` for a 5px yellow border), or an expression like `ih_div_20_FF00FF`. * - * {@link https://imagekit.io/docs/effects-and-enhancements#border---b} + * {@link https://imagekit.io/docs/effects-and-enhancements#border---b|Effects and Enhancements - Border} */ border?: string; /** - * {@link https://imagekit.io/docs/image-resize-and-crop#crop-crop-modes--focus} + * {@link https://imagekit.io/docs/image-resize-and-crop#crop-crop-modes--focus|Image Resize and Crop - Crop Modes} */ crop?: "force" | "at_max" | "at_max_enlarge" | "at_least" | "maintain_ratio"; /** - * {@link https://imagekit.io/docs/image-resize-and-crop#crop-crop-modes--focus} + * {@link https://imagekit.io/docs/image-resize-and-crop#crop-crop-modes--focus|Image Resize and Crop - Crop Modes} */ cropMode?: "pad_resize" | "extract" | "pad_extract"; /** - * Possible values 0.1 to 5 or `auto` for automatic DPR calculation. + * Accepts values between 0.1 and 5, or `auto` for automatic device pixel ratio (DPR) calculation. * - * {@link https://imagekit.io/docs/image-resize-and-crop#dpr---dpr} + * {@link https://imagekit.io/docs/image-resize-and-crop#dpr---dpr|Image Resize and Crop - DPR} */ dpr?: number /** - * This parameter can be used along with pad resize, maintain ratio, or extract crop to change the behavior of padding or cropping + * This parameter can be used with pad resize, maintain ratio, or extract crop to modify the padding or cropping behavior. * - * {@link https://imagekit.io/docs/image-resize-and-crop#focus---fo} + * {@link https://imagekit.io/docs/image-resize-and-crop#focus---fo|Image Resize and Crop - Focus} */ focus?: string; /** - * Used to specify the quality of the output image for lossy formats like JPEG, WebP, and AVIF. A large quality number indicates a larger output image size with high quality. A small quality number indicates a smaller output image size with lower quality. + * Specifies the quality of the output image for lossy formats such as JPEG, WebP, and AVIF. + * A higher quality value results in a larger file size with better quality, while a lower value produces a smaller file size with reduced quality. * - * {@link https://imagekit.io/docs/image-optimization#quality---q} + * {@link https://imagekit.io/docs/image-optimization#quality---q|Image Optimization - Quality} */ quality?: number; /** - * {@link https://imagekit.io/docs/image-resize-and-crop#example---focus-using-cropped-image-coordinates} + * {@link https://imagekit.io/docs/image-resize-and-crop#example---focus-using-cropped-image-coordinates|Image Resize and Crop - Focus Using Cropped Image Coordinates} */ x?: number | string; /** - * {@link https://imagekit.io/docs/image-resize-and-crop#example---focus-using-cropped-image-coordinates} + * {@link https://imagekit.io/docs/image-resize-and-crop#example---focus-using-cropped-image-coordinates|Image Resize and Crop - Focus Using Cropped Image Coordinates} */ xCenter?: number | string; /** - * {@link https://imagekit.io/docs/image-resize-and-crop#example---focus-using-cropped-image-coordinates} + * {@link https://imagekit.io/docs/image-resize-and-crop#example---focus-using-cropped-image-coordinates|Image Resize and Crop - Focus Using Cropped Image Coordinates} */ y?: number | string; /** - * {@link https://imagekit.io/docs/image-resize-and-crop#example---focus-using-cropped-image-coordinates} + * {@link https://imagekit.io/docs/image-resize-and-crop#example---focus-using-cropped-image-coordinates|Image Resize and Crop - Focus Using Cropped Image Coordinates} */ yCenter?: number | string; /** - * Output format for images or videos, e.g., `"jpg"`, `"png"`, `"webp"`, `"mp4"`, `"auto"`. You can also pass `orig` which works only for images and will return the image in the original format. + * Specifies the output format for images or videos, e.g., `jpg`, `png`, `webp`, `mp4`, or `auto`. + * You can also pass `orig` for images to return the original format. + * ImageKit automatically delivers images and videos in the optimal format based on device support unless overridden by the dashboard settings or the format parameter. * - * ImageKit will automatically deliver images and videos in best possible format based on the device support unless you disable it from the dashboard settings or override it using the `format` parameter. - * - * {@link https://imagekit.io/docs/image-optimization#format---f} - * - * {@link https://imagekit.io/docs/video-optimization#format---f}} + * {@link https://imagekit.io/docs/image-optimization#format---f|Image Optimization - Format} & {@link https://imagekit.io/docs/video-optimization#format---f|Video Optimization - Format} */ format?: "auto" | "webp" | "jpg" | "jpeg" | "png" | "gif" | "svg" | "mp4" | "webm" | "avif" | "orig"; /** - * Video codec, e.g., `"h264"`, `"vp9"`, `"av1"` or `"none"`. + * Specifies the video codec, e.g., `h264`, `vp9`, `av1`, or `none`. * - * {@link https://imagekit.io/docs/video-optimization#video-codec---vc} + * {@link https://imagekit.io/docs/video-optimization#video-codec---vc|Video Optimization - Video Codec} */ videoCodec?: "h264" | "vp9" | "av1" | "none"; /** - * Audio codec, e.g., `"aac"`, `"opus"` or `"none"`. + * Specifies the audio codec, e.g., `aac`, `opus`, or `none`. * - * {@link https://imagekit.io/docs/video-optimization#audio-codec---ac} + * {@link https://imagekit.io/docs/video-optimization#audio-codec---ac|Video Optimization - Audio Codec} */ audioCodec?: "aac" | "opus" | "none"; /** - * Corner radius for rounded corners (e.g., `20`) or `"max"` for circular/oval shapes. + * Specifies the corner radius for rounded corners (e.g., 20) or `max` for circular/oval shapes. * - * {@link https://imagekit.io/docs/effects-and-enhancements#radius---r} + * {@link https://imagekit.io/docs/effects-and-enhancements#radius---r|Effects and Enhancements - Radius} */ radius?: number | "max"; /** - * Rotation in degrees. Positive values rotate clockwise; you can - * also use e.g. `"N40"` for counterclockwise or `"auto"` to read EXIF data. - * For videos only 0 , 90 , 180 , 270 and 360 values are supported. + * Specifies the rotation angle in degrees. Positive values rotate the image clockwise; you can also use, for example, `N40` for counterclockwise rotation + * or `auto` to use the orientation specified in the image's EXIF data. + * For videos, only the following values are supported: 0, 90, 180, 270, or 360. * - * {@link https://imagekit.io/docs/effects-and-enhancements#rotate---rt} + * {@link https://imagekit.io/docs/effects-and-enhancements#rotate---rt|Effects and Enhancements - Rotate} */ rotation?: number | string; /** - * Gaussian blur level. Ranges 1–100 or an expression like `"bl-10"`. Possible values include integers between 1 and 100. + * Specifies the Gaussian blur level. Accepts an integer value between 1 and 100, or an expression like `bl-10`. * - * {@link https://imagekit.io/docs/effects-and-enhancements#blur---bl} + * {@link https://imagekit.io/docs/effects-and-enhancements#blur---bl|Effects and Enhancements - Blur} */ blur?: number; /** - * {@link https://imagekit.io/docs/transformations#named-transformations} + * {@link https://imagekit.io/docs/transformations#named-transformations|Transformations - Named Transformations} */ named?: string; /** - * Fallback image if the resource is not found, e.g., a URL or path. + * Specifies a fallback image if the resource is not found, e.g., a URL or file path. * - * {@link https://imagekit.io/docs/image-transformation#default-image---di} + * {@link https://imagekit.io/docs/image-transformation#default-image---di|Image Transformation - Default Image} */ defaultImage?: string; /** - * It is used to flip/mirror an image horizontally, vertically, or in both directions. - * Possible values - h (horizontal), v (vertical), h_v (horizontal and vertical) + * Flips or mirrors an image either horizontally, vertically, or both. + * Acceptable values: `h` (horizontal), `v` (vertical), `h_v` (horizontal and vertical), or `v_h`. * - * {@link https://imagekit.io/docs/effects-and-enhancements#flip---fl} + * {@link https://imagekit.io/docs/effects-and-enhancements#flip---fl|Effects and Enhancements - Flip} */ flip?: "h" | "v" | "h_v" | "v_h"; /** - * Whether to serve the original file without any transformations if `true`. + * If set to true, serves the original file without applying any transformations. * - * {@link https://imagekit.io/docs/core-delivery-features#deliver-original-file-as-is---orig-true} + * {@link https://imagekit.io/docs/core-delivery-features#deliver-original-file-as-is---orig-true|Core Delivery Features - Deliver Original File As Is} */ original?: boolean; /** - * Start offset (in seconds) for trimming videos. e.g., `5` or `"10.5"`. - * Also supports arithmetic expressions. + * Specifies the start offset (in seconds) for trimming videos, e.g., `5` or `10.5`. + * Arithmetic expressions are also supported. * - * {@link https://imagekit.io/docs/trim-videos#start-offset---so} + * {@link https://imagekit.io/docs/trim-videos#start-offset---so|Trim Videos - Start Offset} */ startOffset?: number | string; /** - * End offset (in seconds) for trimming videos. e.g., `5` or `"10.5"`. - * Usually used with `startOffset` to define a time window. - * Also supports arithmetic expressions. + * Specifies the end offset (in seconds) for trimming videos, e.g., `5` or `10.5`. + * Typically used with startOffset to define a time window. Arithmetic expressions are supported. * - * {@link https://imagekit.io/docs/trim-videos#end-offset---eo} + * {@link https://imagekit.io/docs/trim-videos#end-offset---eo|Trim Videos - End Offset} */ endOffset?: number | string; /** - * Duration (in seconds) for trimming videos. e.g., `5` or `"10.5"`. - * Typically used with `startOffset` to specify length from the start point. - * Also supports arithmetic expressions. + * Specifies the duration (in seconds) for trimming videos, e.g., `5` or `10.5`. + * Typically used with startOffset to indicate the length from the start offset. Arithmetic expressions are supported. * - * {@link https://imagekit.io/docs/trim-videos#duration---du} + * {@link https://imagekit.io/docs/trim-videos#duration---du|Trim Videos - Duration} */ duration?: number | string; /** - * Provide an array of resolutions (e.g. `["240", "360", "480", "720", "1080"]`). + * An array of resolutions for adaptive bitrate streaming, e.g., [`240`, `360`, `480`, `720`, `1080`]. * - * {@link https://imagekit.io/docs/adaptive-bitrate-streaming} + * {@link https://imagekit.io/docs/adaptive-bitrate-streaming|Adaptive Bitrate Streaming} */ streamingResolutions?: StreamingResolution[]; /** - * Enable grayscale effect for images. + * Enables a grayscale effect for images. * - * {@link https://imagekit.io/docs/effects-and-enhancements#grayscale---e-grayscale} + * {@link https://imagekit.io/docs/effects-and-enhancements#grayscale---e-grayscale|Effects and Enhancements - Grayscale} */ grayscale?: true; /** - * Upscale images beyond their original dimensions with AI. + * Upscales images beyond their original dimensions using AI. Not supported inside overlay. * - * {@link https://imagekit.io/docs/ai-transformations#upscale-e-upscale} + * {@link https://imagekit.io/docs/ai-transformations#upscale-e-upscale|AI Transformations - Upscale} */ aiUpscale?: true /** - * Retouch (AI-based) for improving faces or product shots. + * Performs AI-based retouching to improve faces or product shots. Not supported inside overlay. * - * {@link https://imagekit.io/docs/ai-transformations#retouch-e-retouch} + * {@link https://imagekit.io/docs/ai-transformations#retouch-e-retouch|AI Transformations - Retouch} */ aiRetouch?: true /** - * Generate variation of an image using AI. This will generate a new image with slight variations from the original image. The variations include changes in color, texture, and other visual elements. However, the model will try to preserve the structure and essence of the original image. + * Generates a variation of an image using AI. This produces a new image with slight variations from the original, + * such as changes in color, texture, and other visual elements, while preserving the structure and essence of the original image. Not supported inside overlay. * - * {@link https://imagekit.io/docs/ai-transformations#generate-variations-of-an-image-e-genvar} + * {@link https://imagekit.io/docs/ai-transformations#generate-variations-of-an-image-e-genvar|AI Transformations - Generate Variations} */ aiVariation?: true /** - * Add an AI-based drop shadow around a foreground object on a transparent or removed background. - * Optionally, you can control the direction, elevation, and saturation of the light source. E.g. change light direction `az-45`. - * - * Pass `true` for default drop shadow or a string for custom drop shadow. + * Adds an AI-based drop shadow around a foreground object on a transparent or removed background. + * Optionally, control the direction, elevation, and saturation of the light source (e.g., `az-45` to change light direction). + * Pass `true` for the default drop shadow, or provide a string for a custom drop shadow. + * Supported inside overlay. * - * {@link https://imagekit.io/docs/ai-transformations#ai-drop-shadow-e-dropshadow} + * {@link https://imagekit.io/docs/ai-transformations#ai-drop-shadow-e-dropshadow|AI Transformations - Drop Shadow} */ aiDropShadow?: true | string /** - * Change background using AI. Provide a prompt or base64-encoded prompt. e.g. `prompt-snow road` or `prompte-[urlencoded_base64_encoded_text]`. + * Uses AI to change the background. Provide a text prompt or a base64-encoded prompt, + * e.g., `prompt-snow road` or `prompte-[urlencoded_base64_encoded_text]`. + * Not supported inside overlay. * - * {@link https://imagekit.io/docs/ai-transformations#change-background-e-changebg} + * {@link https://imagekit.io/docs/ai-transformations#change-background-e-changebg|AI Transformations - Change Background} */ aiChangeBackground?: string; /** - * ImageKit’s in-house background removal. + * Applies ImageKit’s in-house background removal. + * Supported inside overlay. * - * {@link https://imagekit.io/docs/ai-transformations#imagekit-background-removal-e-bgremove} + * {@link https://imagekit.io/docs/ai-transformations#imagekit-background-removal-e-bgremove|AI Transformations - Background Removal} */ aiRemoveBackground?: true /** - * Use third-party background removal. Use `aiRemoveBackground` - ImageKit's in-house background removal which is 90% cheaper. + * Uses third-party background removal. + * Note: It is recommended to use aiRemoveBackground, ImageKit’s in-house solution, which is more cost-effective. + * Supported inside overlay. * - * {@link https://imagekit.io/docs/ai-transformations#background-removal-e-removedotbg} + * {@link https://imagekit.io/docs/ai-transformations#background-removal-e-removedotbg|AI Transformations - External Background Removal} */ aiRemoveBackgroundExternal?: true /** - * Auto-enhance contrast for an image (contrast stretch). + * Automatically enhances the contrast of an image (contrast stretch). * - * {@link https://imagekit.io/docs/effects-and-enhancements#contrast-stretch---e-contrast} + * {@link https://imagekit.io/docs/effects-and-enhancements#contrast-stretch---e-contrast|Effects and Enhancements - Contrast Stretch} */ contrastStretch?: true /** - * This adds a shadow under solid objects in an input image with a transparent background. Check `eDropshadow` for AI-based shadows. + * Adds a shadow beneath solid objects in an image with a transparent background. + * For AI-based drop shadows, refer to aiDropShadow. + * Pass `true` for a default shadow, or provide a string for a custom shadow. * - * Pass `true` for default shadow or a string for custom shadow. - * - * {@link https://imagekit.io/docs/effects-and-enhancements#shadow---e-shadow} + * {@link https://imagekit.io/docs/effects-and-enhancements#shadow---e-shadow|Effects and Enhancements - Shadow} */ shadow?: true | string /** - * It is used to sharpen the input image. It is useful when highlighting the edges and finer details within an image. - * - * Pass `true` for default sharpening or a number for custom sharpening. + * Sharpens the input image, highlighting edges and finer details. + * Pass `true` for default sharpening, or provide a numeric value for custom sharpening. * - * {@link https://imagekit.io/docs/effects-and-enhancements#sharpen---e-sharpen} + * {@link https://imagekit.io/docs/effects-and-enhancements#sharpen---e-sharpen|Effects and Enhancements - Sharpen} */ sharpen?: true | number /** - * Unsharp Masking (USM) is an image sharpening technique. This transform allows you to apply and control unsharp masks on your images. + * Applies Unsharp Masking (USM), an image sharpening technique. + * Pass `true` for a default unsharp mask, or provide a string for a custom unsharp mask. * - * Pass `true` for default unsharp mask or a string for custom unsharp mask. - * - * {@link https://imagekit.io/docs/effects-and-enhancements#unsharp-mask---e-usm} + * {@link https://imagekit.io/docs/effects-and-enhancements#unsharp-mask---e-usm|Effects and Enhancements - Unsharp Mask} */ unsharpMask?: true | string; /** - * The gradient formed is a linear gradient containing two colors, and it can be customized. - * - * Pass `true` for default gradient or a string for custom gradient. + * Creates a linear gradient with two colors. Pass `true` for a default gradient, or provide a string for a custom gradient. * - * {@link https://imagekit.io/docs/effects-and-enhancements#gradient---e-gradient} + * {@link https://imagekit.io/docs/effects-and-enhancements#gradient---e-gradient|Effects and Enhancements - Gradient} */ gradient?: true | string; /** - * Used to specify whether the output JPEG image must be rendered progressively. In progressive loading, the output image renders as a low-quality pixelated full image, which, over time, keeps on adding more pixels and information to the image. This helps you maintain a fast perceived load time. + * Specifies whether the output JPEG image should be rendered progressively. Progressive loading begins with a low-quality, + * pixelated version of the full image, which gradually improves to provide a faster perceived load time. * - * {@link https://imagekit.io/docs/image-optimization#progressive-image---pr} + * {@link https://imagekit.io/docs/image-optimization#progressive-image---pr|Image Optimization - Progressive Image} */ progressive?: boolean; /** - * Used to specify whether the output image (if in JPEG or PNG) must be compressed losslessly. + * Specifies whether the output image (in JPEG or PNG) should be compressed losslessly. * - * {@link https://imagekit.io/docs/image-optimization#lossless-webp-and-png---lo} + * {@link https://imagekit.io/docs/image-optimization#lossless-webp-and-png---lo|Image Optimization - Lossless Compression} */ lossless?: boolean /** - * It specifies whether the output image should contain the color profile initially available with the original image. + * Indicates whether the output image should retain the original color profile. * - * {@link https://imagekit.io/docs/image-optimization#color-profile---cp} + * {@link https://imagekit.io/docs/image-optimization#color-profile---cp|Image Optimization - Color Profile} */ colorProfile?: boolean; /** - * By default, ImageKit removes all metadata as part of automatic image compression. Set this to `true` to preserve metadata. + * By default, ImageKit removes all metadata during automatic image compression. + * Set this to true to preserve metadata. * - * {@link https://imagekit.io/docs/image-optimization#image-metadata---md} + * {@link https://imagekit.io/docs/image-optimization#image-metadata---md|Image Optimization - Image Metadata} */ metadata?: boolean; /** - * It is used to specify the opacity level of the output image. + * Specifies the opacity level of the output image. * - * {@link https://imagekit.io/docs/effects-and-enhancements#opacity---o} + * {@link https://imagekit.io/docs/effects-and-enhancements#opacity---o|Effects and Enhancements - Opacity} */ opacity?: number; /** - * Useful with images that have a solid or nearly solid background with the object in the center. This parameter trims the background from the image, leaving only the central object in the output image. + * Useful for images with a solid or nearly solid background and a central object. This parameter trims the background, + * leaving only the central object in the output image. * - * {@link https://imagekit.io/docs/effects-and-enhancements#trim-edges---t} + * {@link https://imagekit.io/docs/effects-and-enhancements#trim-edges---t|Effects and Enhancements - Trim Edges} */ trim?: true | number; /** - * This parameter accepts a number that determines how much to zoom in or out of the cropped area. - * It must be used along with fo-face or fo- + * Accepts a numeric value that determines how much to zoom in or out of the cropped area. + * It should be used in conjunction with fo-face or fo-. * - * {@link https://imagekit.io/docs/image-resize-and-crop#zoom---z} + * {@link https://imagekit.io/docs/image-resize-and-crop#zoom---z|Image Resize and Crop - Zoom} */ zoom?: number; /** - * Extract specific page/frame from multi-page or layered files (PDF, PSD, AI), - * Pick by number e.g., `2`. Or 2nd and 3rd layers combined using `3-4`. - * Or pick a layer from PSD by name, e.g., `name-layer-4`. + * Extracts a specific page or frame from multi-page or layered files (PDF, PSD, AI). + * For example, specify by number (e.g., `2`), a range (e.g., `3-4` for the 2nd and 3rd layers), + * or by name (e.g., `name-layer-4` for a PSD layer). * - * {@link https://imagekit.io/docs/vector-and-animated-images#get-thumbnail-from-psd-pdf-ai-eps-and-animated-files} + * {@link https://imagekit.io/docs/vector-and-animated-images#get-thumbnail-from-psd-pdf-ai-eps-and-animated-files|Vector and Animated Images - Thumbnail Extraction} */ page?: number | string; /** - * Pass any transformation that is not directly supported by the SDK. This transformation is passed as it is in the URL. + * Pass any transformation not directly supported by the SDK. + * This transformation string is appended to the URL as provided. */ raw?: string; - // old as it is but deprecated /** - * @deprecated Use `rotation` instead. + * Specifies an overlay to be applied on the parent image or video. + * ImageKit supports overlays including images, text, videos, subtitles, and solid colors. + * + * {@link https://imagekit.io/docs/transformations#overlay-using-layers|Transformations - Overlay Using Layers} + */ + overlay?: Overlay; +} + +export type Overlay = + | TextOverlay + | ImageOverlay + | VideoOverlay + | SubtitleOverlay + | SolidColorOverlay + +export interface BaseOverlay { + /** + * Specifies the overlay's position relative to the parent asset. + * Accepts a JSON object with `x` and `y` (or `focus`) properties. + * + * {@link https://imagekit.io/docs/transformations#position-of-layer|Transformations - Position of Layer} + */ + position?: OverlayPosition; + + /** + * Specifies timing information for the overlay (only applicable if the base asset is a video). + * Accepts a JSON object with `start` (`lso`), `end` (`leo`), and `duration` (`ldu`) properties. + * + * {@link https://imagekit.io/docs/transformations#position-of-layer|Transformations - Position of Layer} + */ + timing?: OverlayTiming; +} + +export interface OverlayPosition { + /** + * Specifies the x-coordinate of the top-left corner of the base asset where the overlay's top-left corner will be positioned. + * It also accepts arithmetic expressions such as `bw_mul_0.4` or `bw_sub_cw`. + * Maps to `lx` in the URL. + * + * Learn about [Arithmetic expressions](https://imagekit.io/docs/arithmetic-expressions-in-transformations) + */ + x?: number | string; + + /** + * Specifies the y-coordinate of the top-left corner of the base asset where the overlay's top-left corner will be positioned. + * It also accepts arithmetic expressions such as `bh_mul_0.4` or `bh_sub_ch`. + * Maps to `ly` in the URL. + * + * Learn about [Arithmetic expressions](https://imagekit.io/docs/arithmetic-expressions-in-transformations) + */ + y?: number | string; + + /** + * Specifies the position of the overlay relative to the parent image or video. + * Acceptable values: `center`, `top`, `left`, `bottom`, `right`, `top_left`, `top_right`, `bottom_left`, or `bottom_right`. + * Maps to `lfo` in the URL. + */ + focus?: `center` | `top` | `left` | `bottom` | `right` | `top_left` | `top_right` | `bottom_left` | `bottom_right`; +} + +export interface OverlayTiming { + /** + * Specifies the start time (in seconds) for when the overlay should appear on the base video. + * Accepts a positive number up to two decimal places (e.g., `20` or `20.50`) and arithmetic expressions such as `bdu_mul_0.4` or `bdu_sub_idu`. + * Applies only if the base asset is a video. + * + * Maps to `lso` in the URL. + */ + start?: number | string; + + /** + * Specifies the duration (in seconds) during which the overlay should appear on the base video. + * Accepts a positive number up to two decimal places (e.g., `20` or `20.50`) and arithmetic expressions such as `bdu_mul_0.4` or `bdu_sub_idu`. + * Applies only if the base asset is a video. + * + * Maps to `ldu` in the URL. + */ + duration?: number | string; + + /** + * Specifies the end time (in seconds) for when the overlay should disappear from the base video. + * If both end and duration are provided, duration is ignored. + * Accepts a positive number up to two decimal places (e.g., `20` or `20.50`) and arithmetic expressions such as `bdu_mul_0.4` or `bdu_sub_idu`. + * Applies only if the base asset is a video. + * + * Maps to `leo` in the URL. + */ + end?: number | string; +} + +export interface TextOverlay extends BaseOverlay { + type: "text"; + + /** + * Specifies the text to be displayed in the overlay. The SDK automatically handles special characters and encoding. + */ + text: string; + + /** + * Text can be included in the layer as either `i-{input}` (plain text) or `ie-{base64_encoded_input}` (base64). + * By default, the SDK selects the appropriate format based on the input text. + * To always use base64 (`ie-{base64}`), set this parameter to `base64`. + * To always use plain text (`i-{input}`), set it to `plain`. + * + * Regardless of the encoding method, the input text is always percent-encoded to ensure it is URL-safe. + */ + + encoding: "auto" | "plain" | "base64"; + + /** + * Control styling of the text overlay. + */ + transformation?: TextOverlayTransformation[]; +} + +export interface ImageOverlay extends BaseOverlay { + type: "image"; + + /** + * Specifies the relative path to the image used as an overlay. + */ + input: string; + + /** + * The input path can be included in the layer as either `i-{input}` or `ie-{base64_encoded_input}`. + * By default, the SDK determines the appropriate format automatically. + * To always use base64 encoding (`ie-{base64}`), set this parameter to `base64`. + * To always use plain text (`i-{input}`), set it to `plain`. + * + * Regardless of the encoding method: + * - Leading and trailing slashes are removed. + * - Remaining slashes within the path are replaced with `@@` when using plain text. + */ + encoding: "auto" | "plain" | "base64"; + + /** + * Array of transformations to be applied to the overlay image. Supported transformations depends on the base/parent asset. + * + * {@link https://imagekit.io/docs/add-overlays-on-images#list-of-supported-image-transformations-in-image-layers|Image} | {@link https://imagekit.io/docs/add-overlays-on-videos#list-of-transformations-supported-on-image-overlay|Video} + */ + transformation?: Transformation[]; +} + +export interface VideoOverlay extends BaseOverlay { + type: "video"; + /** + * Specifies the relative path to the video used as an overlay. + */ + input: string; + + /** + * The input path can be included in the layer as either `i-{input}` or `ie-{base64_encoded_input}`. + * By default, the SDK determines the appropriate format automatically. + * To always use base64 encoding (`ie-{base64}`), set this parameter to `base64`. + * To always use plain text (`i-{input}`), set it to `plain`. + * + * Regardless of the encoding method: + * - Leading and trailing slashes are removed. + * - Remaining slashes within the path are replaced with `@@` when using plain text. */ - rotate?: string; + encoding: "auto" | "plain" | "base64"; /** - * @deprecated Use `sharpen` instead. + * Array of transformation to be applied to the overlay video. Except `streamingResolutions`, all other video transformations are supported. + * + * {@link https://imagekit.io/docs/video-transformation|Video Transformations} */ - effectSharpen?: string; + transformation?: Transformation[]; +} +export interface SubtitleOverlay extends BaseOverlay { + type: "subtitle"; /** - * @deprecated Use `unsharpMask` instead. + * Specifies the relative path to the subtitle file used as an overlay. */ - effectUSM?: string; + input: string; /** - * @deprecated Use `contrastStretch` instead. + * The input path can be included in the layer as either `i-{input}` or `ie-{base64_encoded_input}`. + * By default, the SDK determines the appropriate format automatically. + * To always use base64 encoding (`ie-{base64}`), set this parameter to `base64`. + * To always use plain text (`i-{input}`), set it to `plain`. + * + * Regardless of the encoding method: + * - Leading and trailing slashes are removed. + * - Remaining slashes within the path are replaced with `@@` when using plain text. */ - effectContrast?: string; + encoding: "auto" | "plain" | "base64"; /** - * @deprecated Use `grayscale` instead. + * Control styling of the subtitle. + * + * {@link https://imagekit.io/docs/add-overlays-on-videos#styling-controls-for-subtitles-layer|Styling subtitles} */ - effectGray?: string; + transformation?: SubtitleOverlayTransformation[]; +} +export interface SolidColorOverlay extends BaseOverlay { + type: "solidColor"; /** - * @deprecated Use `shadow` instead. + * Specifies the color of the block using an RGB hex code (e.g., `FF0000`), an RGBA code (e.g., `FFAABB50`), or a color name (e.g., `red`). + * If an 8-character value is provided, the last two characters represent the opacity level (from `00` for 0.00 to `99` for 0.99). */ - effectShadow?: string; + color: string; /** - * @deprecated Use `gradient` instead. + * Control width and height of the solid color overlay. Supported transformations depend on the base/parent asset. + * + * {@link https://imagekit.io/docs/add-overlays-on-images#apply-transformation-on-solid-color-overlay|Image} | {@link https://imagekit.io/docs/add-overlays-on-videos#apply-transformations-on-solid-color-block-overlay|Video} */ - effectGradient?: string; + transformation?: SolidColorOverlayTransformation[]; } +export type TextOverlayTransformation = { + /** + * Specifies the maximum width (in pixels) of the overlaid text. The text wraps automatically, and arithmetic expressions (e.g., `bw_mul_0.2` or `bh_div_2`) are supported. Useful when used in conjunction with the `background`. + */ + width?: number | string; + + /** + * Specifies the font size of the overlaid text. Accepts a numeric value or an arithmetic expression. + */ + fontSize?: number | string; + + /** + * Specifies the font family of the overlaid text. Choose from the [supported fonts list](https://imagekit.io/docs/add-overlays-on-images#supported-text-font-list) or use a [custom font](https://imagekit.io/docs/add-overlays-on-images#change-font-family-in-text-overlay). + */ + fontFamily?: string; + + /** + * Specifies the font color of the overlaid text. Accepts an RGB hex code (e.g., `FF0000`), an RGBA code (e.g., `FFAABB50`), or a color name. + */ + fontColor?: string; + + /** + * Specifies the inner alignment of the text when width is more than the text length. + * Supported values: `left`, `right`, and `center` (default). + */ + innerAlignment?: "left" | "right" | "center"; + + /** + * Specifies the padding around the overlaid text. + * Can be provided as a single positive integer or multiple values separated by underscores (following CSS shorthand order). + * Arithmetic expressions are also accepted. + */ + padding?: number | string; + /** + * Specifies the transparency level of the text overlay. Accepts integers from `1` to `9`. + */ + alpha?: number; + + /** + * Specifies the typography style of the text. + * Supported values: `b` for bold, `i` for italics, and `b_i` for bold with italics. + */ + typography?: "b" | "i" | "b_i"; + + /** + * Specifies the background color of the text overlay. + * Accepts an RGB hex code, an RGBA code, or a color name. + */ + background?: string; + + /** + * Specifies the corner radius of the text overlay. + * Set to `max` to achieve a circular or oval shape. + */ + radius?: number | "max"; + + /** + * Specifies the rotation angle of the text overlay. + * Accepts a numeric value for clockwise rotation or a string prefixed with "N" for counter-clockwise rotation. + */ + rotation?: number | string; + + /** + * Flip/mirror the text horizontally, vertically, or in both directions. + * Acceptable values: `h` (horizontal), `v` (vertical), `h_v` (horizontal and vertical), or `v_h`. + */ + flip?: "h" | "v" | "h_v" | "v_h"; + + /** + * Specifies the line height for multi-line text overlays. It will come into effect only if the text wraps over multiple lines. + * Accepts either an integer value or an arithmetic expression. + */ + lineHeight?: number | string; +} + +export type SubtitleOverlayTransformation = { + /** + * Specifies the subtitle background color using a standard color name, an RGB color code (e.g., `FF0000`), or an RGBA color code (e.g., `FFAABB50`). + */ + background?: string; + /** + * Sets the font size of subtitle text. + */ + fontSize?: number | string; + /** + * Sets the font family of subtitle text. + * Refer to the [supported fonts documented](https://imagekit.io/docs/add-overlays-on-images#supported-text-font-list) in the ImageKit transformations guide. + */ + fontFamily?: string; + /** + * Sets the font color of the subtitle text using a standard color name, an RGB color code (e.g., `FF0000`), or an RGBA color code (e.g., `FFAABB50`). + */ + color?: string; + /** + * Sets the typography style of the subtitle text. + * Supported values: `b` for bold, `i` for italics, and `b_i` for bold with italics. + */ + typography?: "b" | "i" | "b_i"; + /** + * Sets the font outline of the subtitle text. + * Requires the outline width (an integer) and the outline color (as an RGB color code, RGBA color code, or standard web color name) separated by an underscore. + * Examples: `2_blue`, `2_A1CCDD`, or `2_A1CCDD50`. + */ + fontOutline?: string; + /** + * Sets the font shadow for the subtitle text. + * Requires the shadow color (as an RGB color code, RGBA color code, or standard web color name) and the shadow indent (an integer) separated by an underscore. + * Examples: `blue_2`, `A1CCDD_3`, or `A1CCDD50_3`. + */ + fontShadow?: string; +} + +export type SolidColorOverlayTransformation = Pick & { + /** + * Specifies the transparency level of the overlaid solid color layer. Supports integers from `1` to `9`. + */ + alpha?: number; +} diff --git a/src/url/builder.ts b/src/url/builder.ts index 29e13f8..ceebc59 100644 --- a/src/url/builder.ts +++ b/src/url/builder.ts @@ -1,7 +1,9 @@ import { ImageKitOptions, UrlOptions } from "../interfaces"; -import { Transformation } from "../interfaces/Transformation"; -import transformationUtils from "../utils/transformation"; +import { ImageOverlay, SolidColorOverlay, SubtitleOverlay, TextOverlay, Transformation, VideoOverlay } from "../interfaces/Transformation"; +import transformationUtils, { safeBtoa } from "../utils/transformation"; const TRANSFORMATION_PARAMETER = "tr"; +const SIMPLE_OVERLAY_PATH_REGEX = new RegExp('^[a-zA-Z0-9-._/ ]*$') +const SIMPLE_OVERLAY_TEXT_REGEX = new RegExp('^[a-zA-Z0-9-._ ]*$') // These characters are selected by testing actual URLs on both path and query parameters. If and when backend starts supporting wide range of characters, this regex should be updated to improve URL readability. function removeTrailingSlash(str: string) { if (typeof str == "string" && str[str.length - 1] == "/") { @@ -43,10 +45,6 @@ export const buildURL = (opts: UrlOptions & ImageKitOptions) => { return ""; } - // if (opts.sdkVersion && opts.sdkVersion.trim() != "") { - // urlObj.searchParams.append("ik-sdk-version", opts.sdkVersion.trim()); - // } - for (var i in opts.queryParameters) { urlObj.searchParams.append(i, String(opts.queryParameters[i])); } @@ -54,14 +52,12 @@ export const buildURL = (opts: UrlOptions & ImageKitOptions) => { var transformationString = constructTransformationString(opts.transformation); if (transformationString && transformationString.length) { - if (transformationUtils.addAsQueryParameter(opts) || isSrcParameterUsedForURL) { - urlObj.searchParams.append(TRANSFORMATION_PARAMETER, transformationString); - } else { + if (!transformationUtils.addAsQueryParameter(opts) && !isSrcParameterUsedForURL) { urlObj.pathname = pathJoin([ TRANSFORMATION_PARAMETER + transformationUtils.getChainTransformDelimiter() + transformationString, urlObj.pathname, ]); - } + } } if (urlEndpointPattern) { @@ -70,23 +66,176 @@ export const buildURL = (opts: UrlOptions & ImageKitOptions) => { urlObj.pathname = pathJoin([urlObj.pathname]); } + if (transformationString && transformationString.length) { + if(transformationUtils.addAsQueryParameter(opts) || isSrcParameterUsedForURL) { + if(urlObj.searchParams.toString() !== "") { // In 12 node.js .size was not there. So, we need to check if it is an object or not. + return `${urlObj.href}&${TRANSFORMATION_PARAMETER}=${transformationString}`; + } + else { + return `${urlObj.href}?${TRANSFORMATION_PARAMETER}=${transformationString}`; + } + } + } + return urlObj.href; }; +function processInputPath(str: string, enccoding: string): string { + // Remove leading and trailing slashes + str = removeTrailingSlash(removeLeadingSlash(str)); + if(enccoding === "plain") { + return `i-${str.replace(/\//g, "@@")}`; + } + if(enccoding === "base64") { + return `ie-${encodeURIComponent(safeBtoa(str))}`; + } + if (SIMPLE_OVERLAY_PATH_REGEX.test(str)) { + return `i-${str.replace(/\//g, "@@")}`; + } else { + return `ie-${encodeURIComponent(safeBtoa(str))}`; + } +} + +function processText(str: string, enccoding: TextOverlay["encoding"]): string { + if (enccoding === "plain") { + return `i-${encodeURIComponent(str)}`; + } + if (enccoding === "base64") { + return `ie-${encodeURIComponent(safeBtoa(str))}`; + } + if (SIMPLE_OVERLAY_TEXT_REGEX.test(str)) { + return `i-${encodeURIComponent(str)}`; + } + return `ie-${encodeURIComponent(safeBtoa(str))}`; +} + +function processOverlay(overlay: Transformation["overlay"]): string | undefined { + const entries = []; + if (!overlay) { + return; + } + const { type, position = {}, timing = {}, transformation = [] } = overlay; + + if (!type) { + throw new Error("Overlay type is required"); + } + + switch (type) { + case "text": { + const textOverlay = overlay as TextOverlay; + if (!textOverlay.text) { + return; + } + const enccoding = textOverlay.encoding || "auto"; + + entries.push("l-text"); + entries.push(processText(textOverlay.text, enccoding)); + } + break; + case "image": + entries.push("l-image"); + { + const imageOverlay = overlay as ImageOverlay; + const enccoding = imageOverlay.encoding || "auto"; + if (imageOverlay.input) { + entries.push(processInputPath(imageOverlay.input, enccoding)); + } else { + return; + } + } + break; + case "video": + entries.push("l-video"); + { + const videoOverlay = overlay as VideoOverlay; + const enccoding = videoOverlay.encoding || "auto"; + if (videoOverlay.input) { + entries.push(processInputPath(videoOverlay.input, enccoding)); + } else { + return; + } + } + break; + case "subtitle": + entries.push("l-subtitle"); + { + const subtitleOverlay = overlay as SubtitleOverlay; + const enccoding = subtitleOverlay.encoding || "auto"; + if (subtitleOverlay.input) { + entries.push(processInputPath(subtitleOverlay.input, enccoding)); + } else { + return; + } + } + break; + case "solidColor": + entries.push("l-image"); + entries.push(`i-ik_canvas`); + { + const solidColorOverlay = overlay as SolidColorOverlay; + if (solidColorOverlay.color) { + entries.push(`bg-${solidColorOverlay.color}`); + } else { + return; + } + } + break; + } + + const { x, y, focus } = position; + if (x) { + entries.push(`lxo-${x}`); + } + if (y) { + entries.push(`lyo-${y}`); + } + if (focus) { + entries.push(`lfo-${focus}`); + } + + const { start, end, duration } = timing; + + if (start) { + entries.push(`lso-${start}`); + } + if (end) { + entries.push(`leo-${end}`); + } + if (duration) { + entries.push(`ldu-${duration}`); + } + + const transformationString = constructTransformationString(transformation); + + if (transformationString && transformationString.trim() !== "") entries.push(transformationString); + + entries.push("l-end"); + + return entries.join(transformationUtils.getTransformDelimiter()); +} + function constructTransformationString(transformation: Transformation[] | undefined) { if (!Array.isArray(transformation)) { return ""; } - var parsedTransforms = []; + var parsedTransforms: string[] = []; for (var i = 0, l = transformation.length; i < l; i++) { - var parsedTransformStep = []; + var parsedTransformStep: string[] = []; for (var key in transformation[i]) { let value = transformation[i][key as keyof Transformation]; if (value === undefined || value === null) { continue; } + if (key === "overlay" && typeof value === "object") { + var rawString = processOverlay(value as Transformation["overlay"]); + if (rawString && rawString.trim() !== "") { + parsedTransformStep.push(rawString); + } + continue; // Always continue as overlay is processed. + } + var transformKey = transformationUtils.getTransformKey(key); if (!transformKey) { transformKey = key; @@ -111,7 +260,7 @@ function constructTransformationString(transformation: Transformation[] | undefi ) { parsedTransformStep.push(transformKey); } else if (key === "raw") { - parsedTransformStep.push(transformation[i][key]); + parsedTransformStep.push(transformation[i][key] as string); } else { if (transformKey === "di") { value = removeTrailingSlash(removeLeadingSlash(value as string || "")); diff --git a/src/utils/transformation.ts b/src/utils/transformation.ts index ef4ec26..5034d0f 100644 --- a/src/utils/transformation.ts +++ b/src/utils/transformation.ts @@ -1,12 +1,13 @@ import supportedTransforms from "../constants/supportedTransforms"; import { ImageKitOptions, TransformationPosition } from "../interfaces"; -const DEFAULT_TRANSFORMATION_POSITION : TransformationPosition = "path"; -const QUERY_TRANSFORMATION_POSITION : TransformationPosition = "query"; -const VALID_TRANSFORMATION_POSITIONS = [DEFAULT_TRANSFORMATION_POSITION, QUERY_TRANSFORMATION_POSITION]; -const CHAIN_TRANSFORM_DELIMITER : string = ":"; -const TRANSFORM_DELIMITER : string = ","; -const TRANSFORM_KEY_VALUE_DELIMITER : string = "-"; +const QUERY_TRANSFORMATION_POSITION: TransformationPosition = "query"; +const PATH_TRANSFORMATION_POSITION: TransformationPosition = "path"; +const DEFAULT_TRANSFORMATION_POSITION: TransformationPosition = QUERY_TRANSFORMATION_POSITION; +const VALID_TRANSFORMATION_POSITIONS = [PATH_TRANSFORMATION_POSITION, QUERY_TRANSFORMATION_POSITION]; +const CHAIN_TRANSFORM_DELIMITER: string = ":"; +const TRANSFORM_DELIMITER: string = ","; +const TRANSFORM_KEY_VALUE_DELIMITER: string = "-"; export default { getDefault: (): TransformationPosition => { @@ -15,8 +16,8 @@ export default { addAsQueryParameter: (options: ImageKitOptions) => { return options.transformationPosition === QUERY_TRANSFORMATION_POSITION; }, - validParameters: (options: ImageKitOptions) => { - if(typeof options.transformationPosition == "undefined") return false; + validParameters: (options: ImageKitOptions) => { + if (typeof options.transformationPosition == "undefined") return false; return VALID_TRANSFORMATION_POSITIONS.indexOf(options.transformationPosition) != -1; }, getTransformKey: function (transform: string) { @@ -33,4 +34,13 @@ export default { getTransformKeyValueDelimiter: function () { return TRANSFORM_KEY_VALUE_DELIMITER; } +} + +export const safeBtoa = function (str: string): string { + if (typeof window !== "undefined") { + return btoa(str); + } else { + // Node fallback + return Buffer.from(str, "utf8").toString("base64"); + } } \ No newline at end of file diff --git a/test/data/index.js b/test/data/index.js index d7676c2..1ec1645 100644 --- a/test/data/index.js +++ b/test/data/index.js @@ -1,4 +1,5 @@ module.exports.initializationParams = { publicKey: "test_public_key", urlEndpoint: "https://ik.imagekit.io/test_url_endpoint", + transformationPosition: "path", } \ No newline at end of file diff --git a/test/url-generation.js b/test/url-generation/basic.js similarity index 96% rename from test/url-generation.js rename to test/url-generation/basic.js index 40c7e38..cb81ef2 100644 --- a/test/url-generation.js +++ b/test/url-generation/basic.js @@ -1,9 +1,9 @@ const chai = require("chai"); -const pkg = require("../package.json"); +const pkg = require("../../package.json"); global.FormData = require('formdata-node'); const expect = chai.expect; -const initializationParams = require("./data").initializationParams -import ImageKit from "../src/index"; +const initializationParams = require("../data").initializationParams +import ImageKit from "../../src/index"; describe("URL generation", function () { @@ -48,8 +48,25 @@ describe("URL generation", function () { expect(url).equal(`https://ik.imagekit.io/test_url_endpoint/test_path_alt.jpg`); }); + it("By default transformationPosition should be query", function () { + var imagekitNew = new ImageKit({ + publicKey: "test_public_key", + urlEndpoint: "https://ik.imagekit.io/test_url_endpoint", + }); + const url = imagekitNew.url({ + path: "/test_path.jpg", + transformation: [{ + "height": "300", + "width": "400" + }, { + rotation: 90 + }] + }); + expect(url).equal("https://ik.imagekit.io/test_url_endpoint/test_path.jpg?tr=h-300,w-400:rt-90"); + }); + it('should generate the URL without sdk version', function () { - const ik = new ImageKit({ ...initializationParams, sdkVersion: "" }) + const ik = new ImageKit(initializationParams) const url = ik.url({ path: "/test_path.jpg", @@ -111,7 +128,7 @@ describe("URL generation", function () { }] }); - expect(url).equal(`https://ik.imagekit.io/test_url_endpoint/test_path.jpg?tr=h-300%2Cw-400`); + expect(url).equal(`https://ik.imagekit.io/test_url_endpoint/test_path.jpg?tr=h-300,w-400`); }); it('should generate the correct URL with a valid src parameter and transformation', function () { @@ -123,7 +140,7 @@ describe("URL generation", function () { }] }); - expect(url).equal(`https://ik.imagekit.io/test_url_endpoint/test_path_alt.jpg?tr=h-300%2Cw-400`); + expect(url).equal(`https://ik.imagekit.io/test_url_endpoint/test_path_alt.jpg?tr=h-300,w-400`); }); it('should generate the correct URL with transformationPosition as query parameter when src is provided', function () { @@ -136,7 +153,7 @@ describe("URL generation", function () { }] }); - expect(url).equal(`https://ik.imagekit.io/test_url_endpoint/test_path_alt.jpg?tr=h-300%2Cw-400`); + expect(url).equal(`https://ik.imagekit.io/test_url_endpoint/test_path_alt.jpg?tr=h-300,w-400`); }); it('should merge query parameters correctly in the generated URL', function () { @@ -149,7 +166,7 @@ describe("URL generation", function () { }] }); - expect(url).equal(`https://ik.imagekit.io/test_url_endpoint/test_path_alt.jpg?t1=v1&t2=v2&t3=v3&tr=h-300%2Cw-400`); + expect(url).equal(`https://ik.imagekit.io/test_url_endpoint/test_path_alt.jpg?t1=v1&t2=v2&t3=v3&tr=h-300,w-400`); }); @@ -261,7 +278,7 @@ describe("URL generation", function () { const url = imagekit.url({ path: "/test_path.jpg", transformation: [{ - effectContrast: "-" + contrastStretch: "-" }] }) @@ -274,7 +291,7 @@ describe("URL generation", function () { transformation: [{ defaultImage: "/test_path.jpg", quality: undefined, - effectContrast: null + contrastStretch: null }] }) @@ -286,7 +303,7 @@ describe("URL generation", function () { path: "/test_path1.jpg", transformation: [{ defaultImage: "/test_path.jpg", - effectContrast: false + contrastStretch: false }] }) @@ -893,12 +910,12 @@ describe("URL generation", function () { colorProfile: true, defaultImage: "/folder/file.jpg/", //trailing and leading slash case dpr: 3, - effectSharpen: 10, - effectUSM: "2-2-0.8-0.024", - effectContrast: true, - effectGray: true, - effectShadow: 'bl-15_st-40_x-10_y-N5', - effectGradient: 'from-red_to-white', + sharpen: 10, + unsharpMask: "2-2-0.8-0.024", + contrastStretch: true, + grayscale: true, + shadow: 'bl-15_st-40_x-10_y-N5', + gradient: 'from-red_to-white', original: true, raw: "h-200,w-300,l-image,i-logo.png,l-end" }] diff --git a/test/url-generation/overlay.js b/test/url-generation/overlay.js new file mode 100644 index 0000000..028a2df --- /dev/null +++ b/test/url-generation/overlay.js @@ -0,0 +1,458 @@ +const chai = require("chai"); +const expect = chai.expect; +const initializationParams = require("../data").initializationParams; +import ImageKit from "../../src/index"; +import { safeBtoa } from "../../src/utils/transformation"; +describe("Overlay Transformation Test Cases", function () { + const imagekit = new ImageKit(initializationParams); + + it('Ignore invalid values if text is missing', function () { + const url = imagekit.url({ + path: "/base-image.jpg", + transformation: [{ + overlay: { + type: "text" + } + }] + }); + expect(url).equal(`https://ik.imagekit.io/test_url_endpoint/base-image.jpg`); + }); + + it('Ignore invalid values if input', function () { + const url = imagekit.url({ + path: "/base-image.jpg", + transformation: [{ + overlay: { + type: "image" + } + }] + }); + expect(url).equal(`https://ik.imagekit.io/test_url_endpoint/base-image.jpg`); + }); + + it('Ignore invalid values if input', function () { + const url = imagekit.url({ + path: "/base-image.jpg", + transformation: [{ + overlay: { + type: "video" + } + }] + }); + expect(url).equal(`https://ik.imagekit.io/test_url_endpoint/base-image.jpg`); + }); + + it('Ignore invalid values if input', function () { + const url = imagekit.url({ + path: "/base-image.jpg", + transformation: [{ + overlay: { + type: "subtitle" + } + }] + }); + expect(url).equal(`https://ik.imagekit.io/test_url_endpoint/base-image.jpg`); + }); + + it('Ignore invalid values if color is missing', function () { + const url = imagekit.url({ + path: "/base-image.jpg", + transformation: [{ + overlay: { + type: "solidColor" + } + }] + }); + expect(url).equal(`https://ik.imagekit.io/test_url_endpoint/base-image.jpg`); + }); + + it('Text overlay generates correct URL with encoded overlay text', function () { + const url = imagekit.url({ + path: "/base-image.jpg", + transformation: [{ + overlay: { + type: "text", + text: "Minimal Text", + } + }] + }); + expect(url).equal(`https://ik.imagekit.io/test_url_endpoint/tr:l-text,i-${encodeURIComponent("Minimal Text")},l-end/base-image.jpg`); + }); + + it('Image overlay generates correct URL with input logo.png', function () { + const url = imagekit.url({ + path: "/base-image.jpg", + transformation: [{ + overlay: { + type: "image", + input: "logo.png", + } + }] + }); + expect(url).equal(`https://ik.imagekit.io/test_url_endpoint/tr:l-image,i-logo.png,l-end/base-image.jpg`); + }); + + it('Video overlay generates correct URL with input play-pause-loop.mp4', function () { + const url = imagekit.url({ + path: "/base-video.mp4", + transformation: [{ + overlay: { + type: "video", + input: "play-pause-loop.mp4", + } + }] + }); + expect(url).equal(`https://ik.imagekit.io/test_url_endpoint/tr:l-video,i-play-pause-loop.mp4,l-end/base-video.mp4`); + }); + + it("Subtitle overlay generates correct URL with input subtitle.srt", function () { + const url = imagekit.url({ + path: "/base-video.mp4", + transformation: [{ + overlay: { + type: "subtitle", + input: "subtitle.srt", + } + }] + }); + expect(url).equal(`https://ik.imagekit.io/test_url_endpoint/tr:l-subtitle,i-subtitle.srt,l-end/base-video.mp4`); + }); + + it("Solid color overlay generates correct URL with background color FF0000", function () { + const url = imagekit.url({ + path: "/base-image.jpg", + transformation: [{ + overlay: { + type: "solidColor", + color: "FF0000", + } + }] + }); + expect(url).equal(`https://ik.imagekit.io/test_url_endpoint/tr:l-image,i-ik_canvas,bg-FF0000,l-end/base-image.jpg`); + }); + + it('Combined overlay transformations generate correct URL including nested overlays', function () { + const url = imagekit.url({ + path: "/base-image.jpg", + transformation: [ + { + // Text overlay + overlay: { + type: "text", + text: "Every thing", + position: { + x: "10", + y: "20", + focus: "center" + }, + timing: { + start: 5, + duration: "10", + end: 15 + }, + transformation: [{ + width: "bw_mul_0.5", + fontSize: 20, + fontFamily: "Arial", + fontColor: "0000ff", + innerAlignment: "left", + padding: 5, + alpha: 7, + typography: "b", + background: "red", + radius: 10, + rotation: "N45", + flip: "h", + lineHeight: 20 + }] + } + }, + { + // Image overlay + overlay: { + type: "image", + input: "logo.png", + position: { + x: "10", + y: "20", + focus: "center" + }, + timing: { + start: 5, + duration: "10", + end: 15 + }, + transformation: [ + { + width: "bw_mul_0.5", + height: "bh_mul_0.5", + rotation: "N45", + flip: "h", + overlay: { + type: "text", + text: "Nested text overlay", + } + } + ] + } + }, + { + // Video overlay. Just for url generation testing, you can't overlay a video on an image. + overlay: { + type: "video", + input: "play-pause-loop.mp4", + position: { + x: "10", + y: "20", + focus: "center" + }, + timing: { + start: 5, + duration: "10", + end: 15 + }, + transformations: [{ + width: "bw_mul_0.5", + height: "bh_mul_0.5", + rotation: "N45", + flip: "h", + }] + } + }, + { + // Subtitle overlay. Just for url generation testing, you can't overlay a subtitle on an image. + overlay: { + type: "subtitle", + input: "subtitle.srt", + position: { + x: "10", + y: "20", + focus: "center" + }, + timing: { + start: 5, + duration: "10", + end: 15 + }, + transformations: [{ + width: "bw_mul_0.5", + height: "bh_mul_0.5", + rotation: "N45", + flip: "h", + }] + } + }, + { + // Solid color overlay + overlay: { + type: "solidColor", + color: "FF0000", + position: { + x: "10", + y: "20", + focus: "center" + }, + timing: { + start: 5, + duration: "10", + end: 15 + }, + transformation: [{ + width: "bw_mul_0.5", + height: "bh_mul_0.5", + rotation: "N45", + flip: "h", + }] + } + } + ] + }); + + expect(url).equal(`https://ik.imagekit.io/test_url_endpoint/tr:l-text,i-${encodeURIComponent("Every thing")},lxo-10,lyo-20,lfo-center,lso-5,leo-15,ldu-10,w-bw_mul_0.5,fs-20,ff-Arial,co-0000ff,ia-left,pa-5,al-7,tg-b,bg-red,r-10,rt-N45,fl-h,lh-20,l-end:l-image,i-logo.png,lxo-10,lyo-20,lfo-center,lso-5,leo-15,ldu-10,w-bw_mul_0.5,h-bh_mul_0.5,rt-N45,fl-h,l-text,i-${encodeURIComponent("Nested text overlay")},l-end,l-end:l-video,i-play-pause-loop.mp4,lxo-10,lyo-20,lfo-center,lso-5,leo-15,ldu-10,l-end:l-subtitle,i-subtitle.srt,lxo-10,lyo-20,lfo-center,lso-5,leo-15,ldu-10,l-end:l-image,i-ik_canvas,bg-FF0000,lxo-10,lyo-20,lfo-center,lso-5,leo-15,ldu-10,w-bw_mul_0.5,h-bh_mul_0.5,rt-N45,fl-h,l-end/base-image.jpg`) + }); +}); + + +describe("Overlay encoding test cases", function () { + const imagekit = new ImageKit({ + ...initializationParams, + urlEndpoint: "https://ik.imagekit.io/demo", // Using real url to test correctness quickly by clicking link + }); + + it('Nested simple path, should use i instead of ie, handle slash properly', function () { + const url = imagekit.url({ + path: "/medium_cafe_B1iTdD0C.jpg", + transformation: [{ + overlay: { + type: "image", + input: "/customer_logo/nykaa.png", + } + }] + }); + expect(url).equal(`https://ik.imagekit.io/demo/tr:l-image,i-customer_logo@@nykaa.png,l-end/medium_cafe_B1iTdD0C.jpg`); + }); + + it('Nested non-simple path, should use ie instead of i', function () { + const url = imagekit.url({ + path: "/medium_cafe_B1iTdD0C.jpg", + transformation: [{ + overlay: { + type: "image", + input: "/customer_logo/Ñykaa.png" + } + }] + }); + expect(url).equal(`https://ik.imagekit.io/demo/tr:l-image,ie-Y3VzdG9tZXJfbG9nby9OzIN5a2FhLnBuZw%3D%3D,l-end/medium_cafe_B1iTdD0C.jpg`); + }); + + it('Simple text overlay, should use i instead of ie', function () { + const url = imagekit.url({ + path: "/medium_cafe_B1iTdD0C.jpg", + transformation: [{ + overlay: { + type: "text", + text: "Manu", + } + }] + }); + expect(url).equal(`https://ik.imagekit.io/demo/tr:l-text,i-Manu,l-end/medium_cafe_B1iTdD0C.jpg`); + }); + + it('Simple text overlay with spaces and other safe characters, should use i instead of ie', function () { + const url = imagekit.url({ + path: "/medium_cafe_B1iTdD0C.jpg", + transformation: [{ + overlay: { + type: "text", + text: "alnum123-._ ", + } + }] + }); + expect(url).equal(`https://ik.imagekit.io/demo/tr:l-text,i-${encodeURIComponent("alnum123-._ ")},l-end/medium_cafe_B1iTdD0C.jpg`); + }); + + it('Non simple text overlay, should use ie instead of i', function () { + const url = imagekit.url({ + path: "/medium_cafe_B1iTdD0C.jpg", + transformation: [{ + overlay: { + type: "text", + text: "Let's use ©, ®, ™, etc", + } + }] + }); + expect(url).equal(`https://ik.imagekit.io/demo/tr:l-text,ie-TGV0J3MgdXNlIMKpLCDCriwg4oSiLCBldGM%3D,l-end/medium_cafe_B1iTdD0C.jpg`); + }); + + it('Text overlay with explicit plain encoding', function () { + const url = imagekit.url({ + path: "/sample.jpg", + transformation: [{ + overlay: { + type: "text", + text: "HelloWorld", + encoding: "plain" + } + }] + }); + expect(url).equal(`https://ik.imagekit.io/demo/tr:l-text,i-HelloWorld,l-end/sample.jpg`); + }); + + it('Text overlay with explicit base64 encoding', function () { + const url = imagekit.url({ + path: "/sample.jpg", + transformation: [{ + overlay: { + type: "text", + text: "HelloWorld", + encoding: "base64" + } + }] + }); + expect(url).equal(`https://ik.imagekit.io/demo/tr:l-text,ie-${encodeURIComponent(safeBtoa("HelloWorld"))},l-end/sample.jpg`); + }); + + it('Image overlay with explicit plain encoding', function () { + const url = imagekit.url({ + path: "/sample.jpg", + transformation: [{ + overlay: { + type: "image", + input: "/customer/logo.png", + encoding: "plain" + } + }] + }); + expect(url).equal(`https://ik.imagekit.io/demo/tr:l-image,i-customer@@logo.png,l-end/sample.jpg`); + }); + + it('Image overlay with explicit base64 encoding', function () { + const url = imagekit.url({ + path: "/sample.jpg", + transformation: [{ + overlay: { + type: "image", + input: "/customer/logo.png", + encoding: "base64" + } + }] + }); + expect(url).equal(`https://ik.imagekit.io/demo/tr:l-image,ie-${encodeURIComponent(safeBtoa("customer/logo.png"))},l-end/sample.jpg`); + }); + + it('Video overlay with explicit base64 encoding', function () { + const url = imagekit.url({ + path: "/sample.mp4", + transformation: [{ + overlay: { + type: "video", + input: "/path/to/video.mp4", + encoding: "base64" + } + }] + }); + expect(url).equal(`https://ik.imagekit.io/demo/tr:l-video,ie-${encodeURIComponent(safeBtoa("path/to/video.mp4"))},l-end/sample.mp4`); + }); + + it('Subtitle overlay with explicit plain encoding', function () { + const url = imagekit.url({ + path: "/sample.mp4", + transformation: [{ + overlay: { + type: "subtitle", + input: "/sub.srt", + encoding: "plain" + } + }] + }); + expect(url).equal(`https://ik.imagekit.io/demo/tr:l-subtitle,i-sub.srt,l-end/sample.mp4`); + }); + + it('Subtitle overlay with explicit base64 encoding', function () { + const url = imagekit.url({ + path: "/sample.mp4", + transformation: [{ + overlay: { + type: "subtitle", + input: "sub.srt", + encoding: "base64" + } + }] + }); + expect(url).equal(`https://ik.imagekit.io/demo/tr:l-subtitle,ie-${encodeURIComponent(safeBtoa("sub.srt"))},l-end/sample.mp4`); + }); + + it("Avoid double encoding when transformation string is in query params", function () { + const url = imagekit.url({ + path: "/sample.jpg", + transformation: [{ + overlay: { + type: "text", + text: "Minimal Text" + } + }], + transformationPosition: "query" + }); + expect(url).equal(`https://ik.imagekit.io/demo/sample.jpg?tr=l-text,i-Minimal%20Text,l-end`); + }); +});