diff --git a/.babelrc b/.babelrc
deleted file mode 100644
index ed723b35..00000000
--- a/.babelrc
+++ /dev/null
@@ -1,9 +0,0 @@
-{
- "presets": [
- "@babel/preset-env",
- "@babel/preset-typescript"
- ],
- "plugins" : [
- "babel-plugin-replace-ts-export-assignment"
- ]
-}
\ No newline at end of file
diff --git a/.fernignore b/.fernignore
new file mode 100644
index 00000000..084a8ebb
--- /dev/null
+++ b/.fernignore
@@ -0,0 +1 @@
+# Specify files that shouldn't be modified by Fern
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
new file mode 100644
index 00000000..7f884eea
--- /dev/null
+++ b/.github/workflows/ci.yml
@@ -0,0 +1,30 @@
+name: ci
+
+on: [push]
+
+jobs:
+ compile:
+ runs-on: ubuntu-latest
+
+ steps:
+ - name: Checkout repo
+ uses: actions/checkout@v4
+
+ - name: Set up node
+ uses: actions/setup-node@v3
+
+ - name: Compile
+ run: yarn && yarn build
+
+ test:
+ runs-on: ubuntu-latest
+
+ steps:
+ - name: Checkout repo
+ uses: actions/checkout@v4
+
+ - name: Set up node
+ uses: actions/setup-node@v3
+
+ - name: Compile
+ run: yarn && yarn test
diff --git a/.github/workflows/nodejs.yml b/.github/workflows/nodejs.yml
deleted file mode 100644
index 7263c90c..00000000
--- a/.github/workflows/nodejs.yml
+++ /dev/null
@@ -1,28 +0,0 @@
-name: Node CI
-
-on: [push]
-
-jobs:
- build:
-
- runs-on: ubuntu-latest
-
- strategy:
- matrix:
- node-version: [12.x, 14.x, 16.x, 18.x]
-
- steps:
- - uses: actions/checkout@v1
- - name: Use Node.js ${{ matrix.node-version }}
- uses: actions/setup-node@v1
- with:
- node-version: ${{ matrix.node-version }}
- - name: Test and report coverage
- run: |
- npm i -g yarn
- yarn install
- yarn test
- yarn test-e2e
- # yarn report-coverage
- env:
- CI: true
diff --git a/.github/workflows/npmpublish.yml b/.github/workflows/npmpublish.yml
deleted file mode 100644
index e1b73f85..00000000
--- a/.github/workflows/npmpublish.yml
+++ /dev/null
@@ -1,49 +0,0 @@
-name: Publish
-
-on:
- release:
- types: [published]
-
-
-jobs:
- build:
-
- runs-on: ubuntu-latest
-
- strategy:
- matrix:
- node-version: [12.x, 14.x]
-
- steps:
- - uses: actions/checkout@v1
- - name: Use Node.js ${{ matrix.node-version }}
- uses: actions/setup-node@v1
- with:
- node-version: ${{ matrix.node-version }}
- - name: npm install, build, and test
- run: |
- npm i -g yarn
- yarn install
- yarn test
- yarn test-e2e
- env:
- CI: true
-
- publish:
- needs: build
- runs-on: ubuntu-latest
- steps:
- - uses: actions/checkout@v1
- - uses: actions/setup-node@v1
- with:
- node-version: 12
- registry-url: https://registry.npmjs.org/
- - name: yarn publish
- run: |
- npm i -g yarn
- yarn config set //registry.npmjs.org/:_authToken=$NODE_AUTH_TOKEN
- yarn install
- yarn publish
- env:
- NODE_AUTH_TOKEN: ${{secrets.npm_token}}
- CI: true
diff --git a/.gitignore b/.gitignore
index 919ac523..72271e04 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,15 +1,3 @@
node_modules
-.vscode
-.nyc_output
-coverage.lcov
-coverage
-.DS_Store
-dist*
-tests/e2e/node-js/package.json
-tests/e2e/node-js/yarn.lock
-tests/e2e/typescript/package.json
-tests/e2e/typescript/yarn.lock
-tests/e2e/typescript/index.js
-.cache
-yarn-error.log
-*.tgz
\ No newline at end of file
+.DS_Store
+/dist
\ No newline at end of file
diff --git a/.mocharc.json b/.mocharc.json
deleted file mode 100644
index fe5128ba..00000000
--- a/.mocharc.json
+++ /dev/null
@@ -1,5 +0,0 @@
-{
- "extension": ["ts"],
- "spec": "tests/*.js",
- "require": "babel-register.js"
-}
\ No newline at end of file
diff --git a/.npmignore b/.npmignore
index eaa22bd7..383dd369 100644
--- a/.npmignore
+++ b/.npmignore
@@ -1,19 +1,10 @@
-.github
+node_modules
+src
tests
-sample
-.npmignore
-.babelrc
-coverage
-babel-register.js
-.nyc_output
-.vscode
-.DS_Store
-.mocharc.json
-.nycrc
-libs/*
-utils/*
-tsconfig*
-fixup.sh
-index.ts
-*.tgz
-test-e2e.sh
\ No newline at end of file
+.gitignore
+.github
+.fernignore
+.prettierrc.yml
+tsconfig.json
+yarn.lock
+pnpm-lock.yaml
\ No newline at end of file
diff --git a/.nycrc b/.nycrc
deleted file mode 100644
index be4975e7..00000000
--- a/.nycrc
+++ /dev/null
@@ -1,4 +0,0 @@
-{
- "check-coverage": true,
- "lines": 95
-}
\ No newline at end of file
diff --git a/.prettierrc.yml b/.prettierrc.yml
new file mode 100644
index 00000000..0c06786b
--- /dev/null
+++ b/.prettierrc.yml
@@ -0,0 +1,2 @@
+tabWidth: 4
+printWidth: 120
diff --git a/CHANGELOG.md b/CHANGELOG.md
deleted file mode 100644
index 7ec52687..00000000
--- a/CHANGELOG.md
+++ /dev/null
@@ -1,38 +0,0 @@
-## Changelog
-
-### SDK Version 6.0.0
-
-### Breaking changes
-
-**1. `listFiles` API response type**
-* The `listFiles` method now returns a unified response type, ListFileResponse, which is an array of both `FileObject` and `FolderObject`. Previously, the response contained only `FileObject`. The `type` property in the response object indicates whether the object is a file or a folder. Even though this change has been made to just the type of the return object, it can be considered a breaking change so it may require require any code relying on the `listFiles` response to be updated.
-
-```
-const result = await imagekit.listFiles({ skip: 0, limit: 10 });
-
-# Before (Pre-version 5.3.0)
-result.forEach((item) => {
- console.log(item);
-});
-
-# After (Version 5.3.0 and above)
-result.forEach((item) => {
- if (item.type === "folder") {
- console.log(item) // item is of type FolderObject
- } else {
- console.log(item) // item is of type FileObject
- }
-});
-```
-
-
-### SDK Version 5.0.0
-
-#### Breaking changes
-
-**1. Overlay syntax update**
-* In version 5.0.0, we've removed the old overlay syntax parameters for transformations, such as `oi`, `ot`, `obg`, and [more](https://docs.imagekit.io/features/image-transformations/overlay). These parameters are deprecated and will start returning errors when used in URLs. Please migrate to the new layers syntax that supports overlay nesting, provides better positional control, and allows more transformations at the layer level. You can start with [examples](https://docs.imagekit.io/features/image-transformations/overlay-using-layers#examples) to learn quickly.
-* You can migrate to the new layers syntax using the `raw` transformation parameter.
-
-**2. Remove Node.js 10.x support**
-* In version 5.0.0, we've removed support for Node.js version 10.x.
diff --git a/LICENSE.txt b/LICENSE.txt
deleted file mode 100644
index 37a4832f..00000000
--- a/LICENSE.txt
+++ /dev/null
@@ -1 +0,0 @@
-Released under the MIT license.
\ No newline at end of file
diff --git a/README.md b/README.md
index dbbf7a59..7674b024 100644
--- a/README.md
+++ b/README.md
@@ -1,42 +1,14 @@
-[
](https://imagekit.io)
+# ImagekitDeveloper TypeScript Library
-# ImageKit.io Node.js SDK
+[](https://buildwithfern.com?utm_source=github&utm_medium=github&utm_campaign=readme&utm_source=https%3A%2F%2Fgithub.com%2Fimagekit-developer%2Fimagekit-nodejs)
+[](https://www.npmjs.com/package/imagekit)
-[](https://github.com/imagekit-developer/imagekit-nodejs/)
-[](https://www.npmjs.com/package/imagekit)
-[](https://codecov.io/gh/imagekit-developer/imagekit-nodejs)
-[](https://npm.runkit.com/imagekit)
-[](https://opensource.org/licenses/MIT)
-[](https://twitter.com/ImagekitIo)
-
-Node.js SDK for [ImageKit](https://imagekit.io/) implements the new APIs and interface for different file operations.
-
-ImageKit is complete media storage, optimization, and transformation solution that comes with an [image and video CDN](https://imagekit.io/features/imagekit-infrastructure). It can be integrated with your existing infrastructure - storage like AWS S3, web servers, your CDN, and custom domain names, allowing you to deliver optimized images in minutes with minimal code changes.
-
-##### Table of contents
-* [Changelog](#changelog)
-* [Installation](#installation)
-* [Initialization](#initialization)
-* [URL generation](#url-generation)
-* [File upload](#file-upload)
-* [File management](#file-management)
-* [Utility functions](#utility-functions)
-* [Rate limits](#rate-limits)
-* [Support](#support)
-* [Links](#links)
+The ImagekitDeveloper TypeScript library provides convenient access to the ImagekitDeveloper API from TypeScript.
## Installation
-Use the following command to download this module. Use the optional `--save` parameter if you wish to save the dependency in your `package.json` file.
-
-```
-npm install imagekit --save
-# or
-pnpm install imagekit --save
-# or
-bun install imagekit // if you are using [Bun](https://bun.sh/) compiler
-# or
-yarn add imagekit
+```sh
+npm i -s imagekit
```
## Initialization
@@ -49,18 +21,27 @@ import ImageKit from "imagekit";
var ImageKit = require("imagekit");
var imagekit = new ImageKit({
- publicKey : "your_public_api_key",
- privateKey : "your_private_api_key",
- urlEndpoint : "https://ik.imagekit.io/your_imagekit_id/"
+ publicKey: "your_public_api_key",
+ privateKey: "your_private_api_key",
+ urlEndpoint: "https://ik.imagekit.io/your_imagekit_id/",
});
```
## Usage
-You can use this Node.js SDK for three different methods - URL generation, file upload, and media management operations. The usage of the SDK has been explained below.
-* `URL Generation`
-* `File Upload`
-* `File Management`
+Instantiate and use the client with the following:
+
+```typescript
+import { createReadStream } from "fs";
+import { ImageKitClient } from "imagekit";
+import * as fs from "fs";
+
+const client = new ImageKitClient({ username: "YOUR_USERNAME", password: "YOUR_PASSWORD" });
+await client.files.upload({
+ file: fs.createReadStream("/path/to/your/file"),
+ fileName: "fileName",
+});
+```
## URL Generation
@@ -71,12 +52,14 @@ This method allows you to create an URL to access a file using the relative file
```js
// For URL Generation, works for both images and videos
var imageURL = imagekit.url({
- path : "/default-image.jpg",
- urlEndpoint : "https://ik.imagekit.io/your_imagekit_id/endpoint/",
- transformation : [{
- "height" : "300",
- "width" : "400"
- }]
+ path: "/default-image.jpg",
+ urlEndpoint: "https://ik.imagekit.io/your_imagekit_id/endpoint/",
+ transformation: [
+ {
+ height: "300",
+ width: "400",
+ },
+ ],
});
```
@@ -90,14 +73,15 @@ https://ik.imagekit.io/your_imagekit_id/endpoint/tr:h-300,w-400/default-image.jp
This method allows you to add transformation parameters to an absolute URL. For example, if you have configured a custom CNAME and have absolute asset URLs in your database or CMS, you will often need this.
-
```js
var imageURL = imagekit.url({
- src : "https://ik.imagekit.io/your_imagekit_id/endpoint/default-image.jpg",
- transformation : [{
- "height" : "300",
- "width" : "400"
- }]
+ src: "https://ik.imagekit.io/your_imagekit_id/endpoint/default-image.jpg",
+ transformation: [
+ {
+ height: "300",
+ width: "400",
+ },
+ ],
});
```
@@ -107,36 +91,40 @@ This results in a URL like
https://ik.imagekit.io/your_imagekit_id/endpoint/default-image.jpg?tr=h-300%2Cw-400
```
-
The `.url()` method accepts the following parameters
-| Option | Description |
-| :----------------| :----------------------------- |
-| urlEndpoint | Optional. The base URL to be appended before the path of the image. If not specified, the URL Endpoint specified at the time of SDK initialization is used. For example, https://ik.imagekit.io/your_imagekit_id/endpoint/ |
-| path | Conditional. This is the path at which the image exists. For example, `/path/to/image.jpg`. Either the `path` or `src` parameter needs to be specified for URL generation. |
-| src | Conditional. This is the complete URL of an image already mapped to ImageKit. For example, `https://ik.imagekit.io/your_imagekit_id/endpoint/path/to/image.jpg`. Either the `path` or `src` parameter needs to be specified for URL generation. |
-| transformation | Optional. An array of objects specifying the transformation to be applied in the URL. The transformation name and the value should be specified as a key-value pair in the object. Different steps of a [chained transformation](https://docs.imagekit.io/features/image-transformations/chained-transformations) can be specified as different objects of the array. The complete list of supported transformations in the SDK and some examples of using them are given later. If you use a transformation name that is not specified in the SDK, it gets applied as it is in the URL. |
-| transformationPosition | Optional. The default value is `path` that places the transformation string as a path parameter in the URL. It can also be specified as `query`, which adds the transformation string as the URL's query parameter `tr`. If you use the `src` parameter to create the URL, then the transformation string is always added as a query parameter. |
-| queryParameters | Optional. These are the other query parameters that you want to add to the final URL. These can be any query parameters and not necessarily related to ImageKit. Especially useful if you want to add some versioning parameter to your URLs. |
-| signed | Optional. Boolean. Default is `false`. If set to `true`, the SDK generates a signed image URL adding the image signature to the image URL. If you create a URL using the `src` parameter instead of `path`, then do correct `urlEndpoint` for this to work. Otherwise returned URL will have the wrong signature |
-| expireSeconds | Optional. Integer. Meant to be used along with the `signed` parameter to specify the time in seconds from now when the URL should expire. If specified, the URL contains the expiry timestamp in the URL, and the image signature is modified accordingly. |
+| Option | Description |
+| :--------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| urlEndpoint | Optional. The base URL to be appended before the path of the image. If not specified, the URL Endpoint specified at the time of SDK initialization is used. For example, https://ik.imagekit.io/your_imagekit_id/endpoint/ |
+| path | Conditional. This is the path at which the image exists. For example, `/path/to/image.jpg`. Either the `path` or `src` parameter needs to be specified for URL generation. |
+| src | Conditional. This is the complete URL of an image already mapped to ImageKit. For example, `https://ik.imagekit.io/your_imagekit_id/endpoint/path/to/image.jpg`. Either the `path` or `src` parameter needs to be specified for URL generation. |
+| transformation | Optional. An array of objects specifying the transformation to be applied in the URL. The transformation name and the value should be specified as a key-value pair in the object. Different steps of a [chained transformation](https://docs.imagekit.io/features/image-transformations/chained-transformations) can be specified as different objects of the array. The complete list of supported transformations in the SDK and some examples of using them are given later. If you use a transformation name that is not specified in the SDK, it gets applied as it is in the URL. |
+| transformationPosition | Optional. The default value is `path` that places the transformation string as a path parameter in the URL. It can also be specified as `query`, which adds the transformation string as the URL's query parameter `tr`. If you use the `src` parameter to create the URL, then the transformation string is always added as a query parameter. |
+| queryParameters | Optional. These are the other query parameters that you want to add to the final URL. These can be any query parameters and not necessarily related to ImageKit. Especially useful if you want to add some versioning parameter to your URLs. |
+| signed | Optional. Boolean. Default is `false`. If set to `true`, the SDK generates a signed image URL adding the image signature to the image URL. If you create a URL using the `src` parameter instead of `path`, then do correct `urlEndpoint` for this to work. Otherwise returned URL will have the wrong signature |
+| expireSeconds | Optional. Integer. Meant to be used along with the `signed` parameter to specify the time in seconds from now when the URL should expire. If specified, the URL contains the expiry timestamp in the URL, and the image signature is modified accordingly. |
#### Examples of generating URLs
**1. Chained Transformations as a query parameter**
+
```js
var imageURL = imagekit.url({
- path : "/default-image.jpg",
- urlEndpoint : "https://ik.imagekit.io/your_imagekit_id/endpoint/",
- transformation : [{
- "height" : "300",
- "width" : "400"
- }, {
- "rotation" : 90
- }],
- transformationPosition : "query"
+ path: "/default-image.jpg",
+ urlEndpoint: "https://ik.imagekit.io/your_imagekit_id/endpoint/",
+ transformation: [
+ {
+ height: "300",
+ width: "400",
+ },
+ {
+ rotation: 90,
+ },
+ ],
+ transformationPosition: "query",
});
```
+
```
https://ik.imagekit.io/your_imagekit_id/endpoint/default-image.jpg?tr=h-300%2Cw-400%3Art-90
```
@@ -147,35 +135,42 @@ There are some transforms like [Sharpening](https://docs.imagekit.io/features/im
```js
var imageURL = imagekit.url({
- src : "https://ik.imagekit.io/your_imagekit_id/endpoint/default-image.jpg",
- transformation : [{
- "format" : "jpg",
- "progressive" : "true",
- "effectSharpen" : "-",
- "effectContrast" : "1"
- }]
+ src: "https://ik.imagekit.io/your_imagekit_id/endpoint/default-image.jpg",
+ transformation: [
+ {
+ format: "jpg",
+ progressive: "true",
+ effectSharpen: "-",
+ effectContrast: "1",
+ },
+ ],
});
```
+
```
//Note that because the `src` parameter was used, the transformation string gets added as a query parameter `tr`
https://ik.imagekit.io/your_imagekit_id/endpoint/default-image.jpg?tr=f-jpg%2Cpr-true%2Ce-sharpen%2Ce-contrast-1
```
**3. Signed URL that expires in 300 seconds with the default URL endpoint and other query parameters**
+
```js
var imageURL = imagekit.url({
- path : "/default-image.jpg",
- queryParameters : {
- "v" : "123"
+ path: "/default-image.jpg",
+ queryParameters: {
+ v: "123",
},
- transformation : [{
- "height" : "300",
- "width" : "400"
- }],
- signed : true,
- expireSeconds : 300
+ transformation: [
+ {
+ height: "300",
+ width: "400",
+ },
+ ],
+ signed: true,
+ expireSeconds: 300,
});
```
+
```
https://ik.imagekit.io/your_imagekit_id/tr:h-300,w-400/default-image.jpg?v=123&ik-t=1567358667&ik-s=f2c7cdacbe7707b71a83d49cf1c6110e3d701054
```
@@ -200,7 +195,9 @@ var imageURL = imagekit.url({
}]
});
```
+
**Sample Result URL**
+
```
https://ik.imagekit.io/your_imagekit_id/tr:h-300,w-400,l-text,i-Imagekit,fs-50,l-end/default-image.jpg
```
@@ -221,7 +218,9 @@ var imageURL = imagekit.url({
}]
});
```
+
**Sample Result URL**
+
```
https://ik.imagekit.io/your_imagekit_id/tr:h-300,w-400,l-image,i-default-image.jpg,w-100,b-10_CDDC39,l-end/default-image.jpg
```
@@ -242,7 +241,9 @@ var imageURL = imagekit.url({
}]
});
```
+
**Sample Result URL**
+
```
https://ik.imagekit.io/your_imagekit_id/tr:h-300,w-400,l-image,i-ik_canvas,bg-FF0000,w-300,h-100,l-end/img/sample-video.mp4
```
@@ -256,62 +257,61 @@ For example:
```js
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"
- }]
+ transformation: [
+ {
+ width: "iw_div_4",
+ height: "ih_div_2",
+ border: "cw_mul_0.05_yellow",
+ },
+ ],
});
```
**Sample Result URL**
+
```
https://ik.imagekit.io/your_imagekit_id/tr:w-iw_div_4,h-ih_div_2,b-cw_mul_0.05_yellow/default-image.jpg
```
-
#### List of supported transformations
See the complete list of transformations supported in ImageKit [here](https://docs.imagekit.io/features/image-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.
If you want to generate transformations in your application and add them to the URL as it is, use the `raw` parameter.
-
-| Supported Transformation Name | Translates to parameter |
-|-------------------------------|-------------------------|
-| height | h |
-| width | w |
-| aspectRatio | ar |
-| quality | q |
-| crop | c |
-| cropMode | cm |
-| x | x |
-| y | y |
-| focus | fo |
-| format | f |
-| radius | r |
-| background | bg |
-| border | b |
-| rotation | rt |
-| blur | bl |
-| named | n |
-| progressive | pr |
-| lossless | lo |
-| trim | t |
-| metadata | md |
-| colorProfile | cp |
-| defaultImage | di |
-| dpr | dpr |
-| effectSharpen | e-sharpen |
-| effectUSM | e-usm |
-| effectContrast | e-contrast |
-| effectGray | e-grayscale |
-| effectShadow | e-shadow |
-| effectGradient | e-gradient |
-| original | orig |
-| raw | `replaced by the parameter value` |
-
-
+| Supported Transformation Name | Translates to parameter |
+| ----------------------------- | --------------------------------- |
+| height | h |
+| width | w |
+| aspectRatio | ar |
+| quality | q |
+| crop | c |
+| cropMode | cm |
+| x | x |
+| y | y |
+| focus | fo |
+| format | f |
+| radius | r |
+| background | bg |
+| border | b |
+| rotation | rt |
+| blur | bl |
+| named | n |
+| progressive | pr |
+| lossless | lo |
+| trim | t |
+| metadata | md |
+| colorProfile | cp |
+| defaultImage | di |
+| dpr | dpr |
+| effectSharpen | e-sharpen |
+| effectUSM | e-usm |
+| effectContrast | e-contrast |
+| effectGray | e-grayscale |
+| effectShadow | e-shadow |
+| effectGradient | e-gradient |
+| original | orig |
+| raw | `replaced by the parameter value` |
## File Upload
@@ -320,6 +320,7 @@ The SDK provides a simple interface using the `.upload()` method to upload files
The `upload()` method requires at least the `file` and the `fileName` parameter to upload a file and returns a callback with the `error` and `result` as arguments. You can pass other parameters supported by the ImageKit upload API using the same parameter name as specified in the upload API documentation. For example, to set tags for a file at the upload time, use the `tags` parameter as defined in the [documentation here](https://docs.imagekit.io/api-reference/upload-file-api/server-side-file-upload).
Sample usage
+
```js
// Using Callback Function
@@ -381,8 +382,6 @@ imagekit.upload({
If the upload succeeds, `error` will be `null,` and the `result` will be the same as what is received from ImageKit's servers.
If the upload fails, the `error` will be the same as what is received from ImageKit's servers, and the `result` will be null.
-
-
## File Management
The SDK provides a simple interface for all the [media APIs mentioned here](https://docs.imagekit.io/api-reference/media-api) to manage your files. You can use a callback function with all API interfaces. The first argument of the callback function is the error, and the second is the result of the API call. The error will be `null` if the API succeeds.
@@ -394,25 +393,30 @@ Accepts an object specifying the parameters used to list and search files. All p
```js
// Using Callback Function
-imagekit.listFiles({
- skip : 10,
- limit : 10
-}, function(error, result) {
- if(error) console.log(error);
- else console.log(result);
-});
-
+imagekit.listFiles(
+ {
+ skip: 10,
+ limit: 10,
+ },
+ function (error, result) {
+ if (error) console.log(error);
+ else console.log(result);
+ },
+);
// Using Promises
-imagekit.listFiles({
- skip : 10,
- limit : 10
-}).then(response => {
- console.log(response);
-}).catch(error => {
- console.log(error);
-});
+imagekit
+ .listFiles({
+ skip: 10,
+ limit: 10,
+ })
+ .then((response) => {
+ console.log(response);
+ })
+ .catch((error) => {
+ console.log(error);
+ });
```
**Get File Details**
@@ -499,34 +503,40 @@ Note: If `publish` is included in the update options, no other parameters are al
```js
// Using Callback Function
-imagekit.updateFileDetails("file_id", {
- tags : ['image_tag'],
- customCoordinates : "10,10,100,100",
- extensions: [
- {
- name: "google-auto-tagging",
- maxTags: 5,
- minConfidence: 95
- }
- ]
-}, function(error, result) {
- if(error) console.log(error);
- else console.log(result);
-});
-
+imagekit.updateFileDetails(
+ "file_id",
+ {
+ tags: ["image_tag"],
+ customCoordinates: "10,10,100,100",
+ extensions: [
+ {
+ name: "google-auto-tagging",
+ maxTags: 5,
+ minConfidence: 95,
+ },
+ ],
+ },
+ function (error, result) {
+ if (error) console.log(error);
+ else console.log(result);
+ },
+);
// Using Promises
-imagekit.updateFileDetails("file_id", {
- publish: {
- isPublished: true,
- includeFileVersions: true
- }
-}).then(response => {
- console.log(response);
-}).catch(error => {
- console.log(error);
-});
+imagekit
+ .updateFileDetails("file_id", {
+ publish: {
+ isPublished: true,
+ includeFileVersions: true,
+ },
+ })
+ .then((response) => {
+ console.log(response);
+ })
+ .catch((error) => {
+ console.log(error);
+ });
```
**Bulk Add tags**
@@ -536,18 +546,21 @@ Add tags to multiple files in a single request as per [API documentation here](h
```js
// Using Callback Function
-imagekit.bulkAddTags(["file_id_1", "file_id_2"], ["tag1", "tag2"], function(error, result) {
- if(error) console.log(error);
+imagekit.bulkAddTags(["file_id_1", "file_id_2"], ["tag1", "tag2"], function (error, result) {
+ if (error) console.log(error);
else console.log(result);
});
// Using Promises
-imagekit.bulkAddTags(["file_id_1", "file_id_2"], ["tag1", "tag2"]).then(response => {
- console.log(response);
-}).catch(error => {
- console.log(error);
-});
+imagekit
+ .bulkAddTags(["file_id_1", "file_id_2"], ["tag1", "tag2"])
+ .then((response) => {
+ console.log(response);
+ })
+ .catch((error) => {
+ console.log(error);
+ });
```
**Bulk Remove tags**
@@ -557,18 +570,21 @@ Remove tags from multiple files in a single request as per [API documentation he
```js
// Using Callback Function
-imagekit.bulkRemoveTags(["file_id_1", "file_id_2"], ["tags"], function(error, result) {
- if(error) console.log(error);
+imagekit.bulkRemoveTags(["file_id_1", "file_id_2"], ["tags"], function (error, result) {
+ if (error) console.log(error);
else console.log(result);
});
// Using Promises
-imagekit.bulkRemoveTags(["file_id_1", "file_id_2"], ["tags"]).then(response => {
- console.log(response);
-}).catch(error => {
- console.log(error);
-});
+imagekit
+ .bulkRemoveTags(["file_id_1", "file_id_2"], ["tags"])
+ .then((response) => {
+ console.log(response);
+ })
+ .catch((error) => {
+ console.log(error);
+ });
```
**Bulk Remove AI Tags**
@@ -578,18 +594,21 @@ Remove AI tags from multiple files in a single request as per [API documentation
```js
// Using Callback Function
-imagekit.bulkRemoveAITags(["file_id_1", "file_id_2"], ["ai-tag1", "ai-tag2"], function(error, result) {
- if(error) console.log(error);
+imagekit.bulkRemoveAITags(["file_id_1", "file_id_2"], ["ai-tag1", "ai-tag2"], function (error, result) {
+ if (error) console.log(error);
else console.log(result);
});
// Using Promises
-imagekit.bulkRemoveAITags(["file_id_1", "file_id_2"], ["ai-tag1", "ai-tag2"]).then(response => {
- console.log(response);
-}).catch(error => {
- console.log(error);
-});
+imagekit
+ .bulkRemoveAITags(["file_id_1", "file_id_2"], ["ai-tag1", "ai-tag2"])
+ .then((response) => {
+ console.log(response);
+ })
+ .catch((error) => {
+ console.log(error);
+ });
```
**Delete File**
@@ -599,19 +618,21 @@ Delete a file as per the [API documentation here](https://docs.imagekit.io/api-r
```js
// Using Callback Function
-imagekit.deleteFile("file_id", function(error, result) {
- if(error) console.log(error);
+imagekit.deleteFile("file_id", function (error, result) {
+ if (error) console.log(error);
else console.log(result);
});
-
// Using Promises
-imagekit.deleteFile("file_id").then(response => {
- console.log(response);
-}).catch(error => {
- console.log(error);
-});
+imagekit
+ .deleteFile("file_id")
+ .then((response) => {
+ console.log(response);
+ })
+ .catch((error) => {
+ console.log(error);
+ });
```
**Delete File Version**
@@ -621,25 +642,30 @@ Delete any non-current version of a file as per the [API documentation here](htt
```js
// Using Callback Function
-imagekit.deleteFileVersion({
- fileId: "file_id",
- versionId: "version_id",
-}, function(error, result) {
- if(error) console.log(error);
- else console.log(result);
-});
-
+imagekit.deleteFileVersion(
+ {
+ fileId: "file_id",
+ versionId: "version_id",
+ },
+ function (error, result) {
+ if (error) console.log(error);
+ else console.log(result);
+ },
+);
// Using Promises
-imagekit.deleteFile({
- fileId: "file_id",
- versionId: "version_id",
-}).then(response => {
- console.log(response);
-}).catch(error => {
- console.log(error);
-});
+imagekit
+ .deleteFile({
+ fileId: "file_id",
+ versionId: "version_id",
+ })
+ .then((response) => {
+ console.log(response);
+ })
+ .catch((error) => {
+ console.log(error);
+ });
```
**Bulk Delete Files**
@@ -649,19 +675,21 @@ Delete multiple files as per the [API documentation here](https://docs.imagekit.
```js
// Using Callback Function
-imagekit.bulkDeleteFiles(["file_id_1", "file_id_2"], function(error, result) {
- if(error) console.log(error);
+imagekit.bulkDeleteFiles(["file_id_1", "file_id_2"], function (error, result) {
+ if (error) console.log(error);
else console.log(result);
});
-
// Using Promises
-imagekit.bulkDeleteFiles(["file_id_1", "file_id_2"]).then(response => {
- console.log(response);
-}).catch(error => {
- console.log(error);
-});
+imagekit
+ .bulkDeleteFiles(["file_id_1", "file_id_2"])
+ .then((response) => {
+ console.log(response);
+ })
+ .catch((error) => {
+ console.log(error);
+ });
```
**Copy File**
@@ -700,24 +728,30 @@ This will move a file from one location to another as per [API documentation her
```js
// Using Callback Function
-imagekit.moveFile({
- sourceFilePath: "/path/to/file.jpg",
- destinationPath: "/folder/to/copy/into/",
-}, function(error, result) {
- if(error) console.log(error);
- else console.log(result);
-});
+imagekit.moveFile(
+ {
+ sourceFilePath: "/path/to/file.jpg",
+ destinationPath: "/folder/to/copy/into/",
+ },
+ function (error, result) {
+ if (error) console.log(error);
+ else console.log(result);
+ },
+);
// Using Promises
-imagekit.moveFile({
- sourceFilePath: "/path/to/file.jpg",
- destinationPath: "/folder/to/copy/into/",
-}).then(response => {
- console.log(response);
-}).catch(error => {
- console.log(error);
-});
+imagekit
+ .moveFile({
+ sourceFilePath: "/path/to/file.jpg",
+ destinationPath: "/folder/to/copy/into/",
+ })
+ .then((response) => {
+ console.log(response);
+ })
+ .catch((error) => {
+ console.log(error);
+ });
```
**Rename File**
@@ -727,26 +761,32 @@ Rename the file as per [API documentation here](https://docs.imagekit.io/api-ref
```js
// Using Callback Function
-imagekit.renameFile({
- filePath: "/path/to/old-file-name.jpg",
- newFileName: "new-file-name.jpg",
- purgeCache: false // optional
-}, function(error, result) {
- if(error) console.log(error);
- else console.log(result);
-});
+imagekit.renameFile(
+ {
+ filePath: "/path/to/old-file-name.jpg",
+ newFileName: "new-file-name.jpg",
+ purgeCache: false, // optional
+ },
+ function (error, result) {
+ if (error) console.log(error);
+ else console.log(result);
+ },
+);
// Using Promises
-imagekit.renameFile({
- filePath: "/path/to/old-file-name.jpg",
- newFileName: "new-file-name.jpg",
- purgeCache: false // optional
-}).then(response => {
- console.log(response);
-}).catch(error => {
- console.log(error);
-});
+imagekit
+ .renameFile({
+ filePath: "/path/to/old-file-name.jpg",
+ newFileName: "new-file-name.jpg",
+ purgeCache: false, // optional
+ })
+ .then((response) => {
+ console.log(response);
+ })
+ .catch((error) => {
+ console.log(error);
+ });
```
**Restore File Version**
@@ -756,24 +796,30 @@ Restore the file version as per [API documentation here](https://docs.imagekit.i
```js
// Using Callback Function
-imagekit.restoreFileVersion({
- fileId: "file_id",
- versionId: "version_id"
-}, function(error, result) {
- if(error) console.log(error);
- else console.log(result);
-});
+imagekit.restoreFileVersion(
+ {
+ fileId: "file_id",
+ versionId: "version_id",
+ },
+ function (error, result) {
+ if (error) console.log(error);
+ else console.log(result);
+ },
+);
// Using Promises
-imagekit.restoreFileVersion({
- fileId: "file_id",
- versionId: "version_id"
-}).then(response => {
- console.log(response);
-}).catch(error => {
- console.log(error);
-});
+imagekit
+ .restoreFileVersion({
+ fileId: "file_id",
+ versionId: "version_id",
+ })
+ .then((response) => {
+ console.log(response);
+ })
+ .catch((error) => {
+ console.log(error);
+ });
```
**Create Folder**
@@ -783,24 +829,30 @@ This will create a new folder as per [API documentation here](https://docs.image
```js
// Using Callback Function
-imagekit.createFolder({
- folderName: "new_folder",
- parentFolderPath: "source/folder/path"
-}, function(error, result) {
- if(error) console.log(error);
- else console.log(result);
-});
+imagekit.createFolder(
+ {
+ folderName: "new_folder",
+ parentFolderPath: "source/folder/path",
+ },
+ function (error, result) {
+ if (error) console.log(error);
+ else console.log(result);
+ },
+);
// Using Promises
-imagekit.createFolder({
- folderName: "new_folder",
- parentFolderPath: "source/folder/path"
-}).then(response => {
- console.log(response);
-}).catch(error => {
- console.log(error);
-});
+imagekit
+ .createFolder({
+ folderName: "new_folder",
+ parentFolderPath: "source/folder/path",
+ })
+ .then((response) => {
+ console.log(response);
+ })
+ .catch((error) => {
+ console.log(error);
+ });
```
**Delete Folder**
@@ -810,18 +862,21 @@ This will delete the specified Folder and all nested files & folders as per [API
```js
// Using Callback Function
-imagekit.deleteFolder("folderPath", function(error, result) {
- if(error) console.log(error);
+imagekit.deleteFolder("folderPath", function (error, result) {
+ if (error) console.log(error);
else console.log(result);
});
// Using Promises
-imagekit.deleteFolder("folderPath").then(response => {
- console.log(response);
-}).catch(error => {
- console.log(error);
-});
+imagekit
+ .deleteFolder("folderPath")
+ .then((response) => {
+ console.log(response);
+ })
+ .catch((error) => {
+ console.log(error);
+ });
```
**Copy Folder**
@@ -831,26 +886,32 @@ This will copy one Folder into another as per [API documentation here](https://d
```js
// Using Callback Function
-imagekit.copyFolder({
- sourceFolderPath: "/folder/to/copy",
- destinationPath: "/folder/to/copy/into/",
- includeFileVersions: false // optional
-}, function(error, result) {
- if(error) console.log(error);
- else console.log(result);
-});
+imagekit.copyFolder(
+ {
+ sourceFolderPath: "/folder/to/copy",
+ destinationPath: "/folder/to/copy/into/",
+ includeFileVersions: false, // optional
+ },
+ function (error, result) {
+ if (error) console.log(error);
+ else console.log(result);
+ },
+);
// Using Promises
-imagekit.copyFolder({
- sourceFolderPath: "/folder/to/copy",
- destinationPath: "/folder/to/copy/into/",
- includeFileVersions: false // optional
-}).then(response => {
- console.log(response);
-}).catch(error => {
- console.log(error);
-});
+imagekit
+ .copyFolder({
+ sourceFolderPath: "/folder/to/copy",
+ destinationPath: "/folder/to/copy/into/",
+ includeFileVersions: false, // optional
+ })
+ .then((response) => {
+ console.log(response);
+ })
+ .catch((error) => {
+ console.log(error);
+ });
```
**Move Folder**
@@ -860,24 +921,30 @@ This will move one Folder into another as per [API documentation here](https://d
```js
// Using Callback Function
-imagekit.moveFolder({
- sourceFolderPath: "/folder/to/move",
- destinationPath: "/folder/to/move/into/"
-}, function(error, result) {
- if(error) console.log(error);
- else console.log(result);
-});
+imagekit.moveFolder(
+ {
+ sourceFolderPath: "/folder/to/move",
+ destinationPath: "/folder/to/move/into/",
+ },
+ function (error, result) {
+ if (error) console.log(error);
+ else console.log(result);
+ },
+);
// Using Promises
-imagekit.moveFolder({
- sourceFolderPath: "/folder/to/move",
- destinationPath: "/folder/to/move/into/"
-}).then(response => {
- console.log(response);
-}).catch(error => {
- console.log(error);
-});
+imagekit
+ .moveFolder({
+ sourceFolderPath: "/folder/to/move",
+ destinationPath: "/folder/to/move/into/",
+ })
+ .then((response) => {
+ console.log(response);
+ })
+ .catch((error) => {
+ console.log(error);
+ });
```
**Get bulk job status**
@@ -887,18 +954,21 @@ This allows us to get a bulk operation status e.g. copy or move Folder as per [A
```js
// Using Callback Function
-imagekit.getBulkJobStatus("jobId", function(error, result) {
- if(error) console.log(error);
+imagekit.getBulkJobStatus("jobId", function (error, result) {
+ if (error) console.log(error);
else console.log(result);
});
// Using Promises
-imagekit.getBulkJobStatus("jobId").then(response => {
- console.log(response);
-}).catch(error => {
- console.log(error);
-});
+imagekit
+ .getBulkJobStatus("jobId")
+ .then((response) => {
+ console.log(response);
+ })
+ .catch((error) => {
+ console.log(error);
+ });
```
**Purge Cache**
@@ -908,19 +978,21 @@ Programmatically issue a clear cache request as per the [API documentation here]
```js
// Using Callback Function
-imagekit.purgeCache("full_url", function(error, result) {
- if(error) console.log(error);
+imagekit.purgeCache("full_url", function (error, result) {
+ if (error) console.log(error);
else console.log(result);
});
-
// Using Promises
-imagekit.purgeCache("full_url").then(response => {
- console.log(response);
-}).catch(error => {
- console.log(error);
-});
+imagekit
+ .purgeCache("full_url")
+ .then((response) => {
+ console.log(response);
+ })
+ .catch((error) => {
+ console.log(error);
+ });
```
**Purge Cache Status**
@@ -930,19 +1002,21 @@ Get the purge cache request status using the request ID returned when a purge ca
```js
// Using Callback Function
-imagekit.getPurgeCacheStatus("cache_request_id", function(error, result) {
- if(error) console.log(error);
+imagekit.getPurgeCacheStatus("cache_request_id", function (error, result) {
+ if (error) console.log(error);
else console.log(result);
});
-
// Using Promises
-imagekit.getPurgeCacheStatus("cache_request_id").then(response => {
- console.log(response);
-}).catch(error => {
- console.log(error);
-});
+imagekit
+ .getPurgeCacheStatus("cache_request_id")
+ .then((response) => {
+ console.log(response);
+ })
+ .catch((error) => {
+ console.log(error);
+ });
```
**Get File Metadata**
@@ -999,33 +1073,33 @@ imagekit.createCustomMetadataField(
schema: {
type: "Number",
minValue: 1000,
- maxValue: 3000
- }
+ maxValue: 3000,
+ },
},
- function(error, result) {
- if(error) console.log(error);
+ function (error, result) {
+ if (error) console.log(error);
else console.log(result);
- }
+ },
);
-
// Using Promises
-imagekit.createCustomMetadataField(
- {
+imagekit
+ .createCustomMetadataField({
name: "price",
label: "price",
schema: {
type: "Number",
minValue: 1000,
- maxValue: 3000
- }
- }
-).then(response => {
- console.log(response);
-}).catch(error => {
- console.log(error);
-});
+ maxValue: 3000,
+ },
+ })
+ .then((response) => {
+ console.log(response);
+ })
+ .catch((error) => {
+ console.log(error);
+ });
```
**Get all custom metadata fields**
@@ -1037,26 +1111,26 @@ Get the list of all custom metadata fields as per the [API documentation here](h
imagekit.getCustomMetadataFields(
{
- includeDeleted: false // optional
+ includeDeleted: false, // optional
},
- function(error, result) {
- if(error) console.log(error);
+ function (error, result) {
+ if (error) console.log(error);
else console.log(result);
- }
+ },
);
-
// Using Promises
-imagekit.getCustomMetadataFields(
- {
- includeDeleted: false // optional
- }
-).then(response => {
- console.log(response);
-}).catch(error => {
- console.log(error);
-});
+imagekit
+ .getCustomMetadataFields({
+ includeDeleted: false, // optional
+ })
+ .then((response) => {
+ console.log(response);
+ })
+ .catch((error) => {
+ console.log(error);
+ });
```
**Update a custom metadata field**
@@ -1071,31 +1145,30 @@ imagekit.updateCustomMetadataField(
{
schema: {
minValue: 500,
- maxValue: 2500
- }
+ maxValue: 2500,
+ },
},
- function(error, result) {
- if(error) console.log(error);
+ function (error, result) {
+ if (error) console.log(error);
else console.log(result);
- }
+ },
);
-
// Using Promises
-imagekit.updateCustomMetadataField(
- "field_id",
- {
+imagekit
+ .updateCustomMetadataField("field_id", {
schema: {
minValue: 500,
- maxValue: 2500
- }
- },
-).then(response => {
- console.log(response);
-}).catch(error => {
- console.log(error);
-});
+ maxValue: 2500,
+ },
+ })
+ .then((response) => {
+ console.log(response);
+ })
+ .catch((error) => {
+ console.log(error);
+ });
```
**Delete a custom metadata field**
@@ -1105,24 +1178,21 @@ delete a custom metadata field as per the [API documentation here](https://docs.
```js
// Using Callback Function
-imagekit.deleteCustomMetadataField(
- "field_id",
- function(error, result) {
- if(error) console.log(error);
- else console.log(result);
- }
-);
-
+imagekit.deleteCustomMetadataField("field_id", function (error, result) {
+ if (error) console.log(error);
+ else console.log(result);
+});
// Using Promises
-imagekit.deleteCustomMetadataField(
- "field_id"
-).then(response => {
- console.log(response);
-}).catch(error => {
- console.log(error);
-});
+imagekit
+ .deleteCustomMetadataField("field_id")
+ .then((response) => {
+ console.log(response);
+ })
+ .catch((error) => {
+ console.log(error);
+ });
```
## Utility functions
@@ -1133,13 +1203,14 @@ We have included the following commonly used utility functions in this package.
If you want to implement client-side file upload, you will need a token, expiry timestamp, and a valid signature for that upload. The SDK provides a simple method you can use in your backend code to generate these authentication parameters.
-*Note: The Private API Key should never be exposed in any client-side code. You must always generate these authentication parameters on the server-side*
+_Note: The Private API Key should never be exposed in any client-side code. You must always generate these authentication parameters on the server-side_
```js
var authenticationParameters = imagekit.getAuthenticationParameters(token, expire);
```
Returns
+
```js
{
token : "unique_token",
@@ -1165,21 +1236,24 @@ const calculateDistance = () => {
// Calculate the distance between them:
const distance = imagekit.pHashDistance(firstHash, secondHash);
return distance;
-}
+};
```
+
#### Distance calculation examples
```js
-imagekit.pHashDistance('f06830ca9f1e3e90', 'f06830ca9f1e3e90');
+imagekit.pHashDistance("f06830ca9f1e3e90", "f06830ca9f1e3e90");
// output: 0 (same image)
-imagekit.pHashDistance('2d5ad3936d2e015b', '2d6ed293db36a4fb');
+imagekit.pHashDistance("2d5ad3936d2e015b", "2d6ed293db36a4fb");
// output: 17 (similar images)
-imagekit.pHashDistance('a4a65595ac94518b', '7838873e791f8400');
+imagekit.pHashDistance("a4a65595ac94518b", "7838873e791f8400");
// output: 37 (dissimilar images)
```
+
## Access request-id, other response headers and HTTP status code
+
You can access `$ResponseMetadata` on success or error object to access the HTTP status code and response headers.
```javascript
@@ -1202,15 +1276,16 @@ try {
```
## Rate limits
+
Except for upload API, all [ImageKit APIs are rate limited](https://docs.imagekit.io/api-reference/api-introduction/rate-limits) to protect the infrastructure from excessive requests rates and to keep ImageKit.io fast and stable for everyone.
When you exceed the rate limits for an endpoint, you will receive a `429` status code. The Node.js library reads the [rate limiting response headers](https://docs.imagekit.io/api-reference/api-introduction/rate-limits#response-headers-to-understand-rate-limits) provided in the API response and adds these in the error argument of the callback or `.catch` when using promises. Please sleep/pause for the number of milliseconds specified by the value of the `X-RateLimit-Reset` property before making additional requests to that endpoint.
-| Property | Description |
-|----------|-------------|
-| `X-RateLimit-Limit` | The maximum number of requests that can be made to this endpoint in the interval specified by the `X-RateLimit-Interval` response header. |
-| `X-RateLimit-Reset` | The amount of time in milliseconds before you can make another request to this endpoint. Pause/sleep your workflow for this duration. |
-| `X-RateLimit-Interval` | The duration of interval in milliseconds for which this rate limit was exceeded. |
+| Property | Description |
+| ---------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- |
+| `X-RateLimit-Limit` | The maximum number of requests that can be made to this endpoint in the interval specified by the `X-RateLimit-Interval` response header. |
+| `X-RateLimit-Reset` | The amount of time in milliseconds before you can make another request to this endpoint. Pause/sleep your workflow for this duration. |
+| `X-RateLimit-Interval` | The duration of interval in milliseconds for which this rate limit was exceeded. |
## Verify webhook events
@@ -1221,22 +1296,22 @@ Verifying webhook signature is easy with imagekit SDK. All you need is the value
Here is an example using the express.js server.
```js
-const express = require('express');
-const Imagekit = require('imagekit');
+const express = require("express");
+const Imagekit = require("imagekit");
// Webhook configs
-const WEBHOOK_SECRET = 'whsec_...'; // Copy from Imagekit dashboard
+const WEBHOOK_SECRET = "whsec_..."; // Copy from Imagekit dashboard
const WEBHOOK_EXPIRY_DURATION = 300 * 1000; // 300 seconds for example
const imagekit = new Imagekit({
- publicKey: 'public_...',
- urlEndpoint: 'https://ik.imagekit.io/imagekit_id',
- privateKey: 'private_...',
-})
+ publicKey: "public_...",
+ urlEndpoint: "https://ik.imagekit.io/imagekit_id",
+ privateKey: "private_...",
+});
const app = express();
-app.post('/webhook', express.raw({ type: 'application/json' }), (req, res) => {
+app.post("/webhook", express.raw({ type: "application/json" }), (req, res) => {
const signature = req.headers["x-ik-signature"];
const requestBody = req.body;
let webhookResult;
@@ -1257,13 +1332,13 @@ app.post('/webhook', express.raw({ type: 'application/json' }), (req, res) => {
// Handle webhook
switch (event.type) {
- case 'video.transformation.accepted':
+ case "video.transformation.accepted":
// It is triggered when a new video transformation request is accepted for processing. You can use this for debugging purposes.
break;
- case 'video.transformation.ready':
+ case "video.transformation.ready":
// It is triggered when a video encoding is finished, and the transformed resource is ready to be served. You should listen to this webhook and update any flag in your database or CMS against that particular asset so your application can start showing it to users.
break;
- case 'video.transformation.error':
+ case "video.transformation.error":
// It is triggered if an error occurs during encoding. Listen to this webhook to log the reason. You should check your origin and URL-endpoint settings if the reason is related to download failure. If the reason seems like an error on the ImageKit side, then raise a support ticket at support@imagekit.io.
break;
default:
@@ -1273,11 +1348,11 @@ app.post('/webhook', express.raw({ type: 'application/json' }), (req, res) => {
// Return a response to acknowledge receipt of the event
res.send();
-})
+});
app.listen(3000, () => {
- console.log(`Example app listening on port 3000`)
-})
+ console.log(`Example app listening on port 3000`);
+});
```
## Support
@@ -1285,9 +1360,162 @@ app.listen(3000, () => {
For any feedback or to report any issues or general implementation support, please reach out to [support@imagekit.io](mailto:support@imagekit.io)
## Links
-* [Documentation](https://docs.imagekit.io)
-* [Main website](https://imagekit.io)
+
+- [Documentation](https://docs.imagekit.io)
+- [Main website](https://imagekit.io)
## License
Released under the MIT license.
+
+## Reference
+
+A full reference for this library is available [here](https://github.com/imagekit-developer/imagekit-nodejs/blob/HEAD/./reference.md).
+
+## Request And Response Types
+
+The SDK exports all request and response types as TypeScript interfaces. Simply import them with the
+following namespace:
+
+```typescript
+import { ImageKit } from "imagekit";
+
+const request: ImageKit.FileUploadV1 = {
+ ...
+};
+```
+
+## Exception Handling
+
+When the API returns a non-success status code (4xx or 5xx response), a subclass of the following error
+will be thrown.
+
+```typescript
+import { ImageKitError } from "imagekit";
+
+try {
+ await client.files.upload(...);
+} catch (err) {
+ if (err instanceof ImageKitError) {
+ console.log(err.statusCode);
+ console.log(err.message);
+ console.log(err.body);
+ console.log(err.rawResponse);
+ }
+}
+```
+
+## Advanced
+
+### Additional Headers
+
+If you would like to send additional headers as part of the request, use the `headers` request option.
+
+```typescript
+const response = await client.files.upload(..., {
+ headers: {
+ 'X-Custom-Header': 'custom value'
+ }
+});
+```
+
+### Additional Query String Parameters
+
+If you would like to send additional query string parameters as part of the request, use the `queryParams` request option.
+
+```typescript
+const response = await client.files.upload(..., {
+ queryParams: {
+ 'customQueryParamKey': 'custom query param value'
+ }
+});
+```
+
+### Retries
+
+The SDK is instrumented with automatic retries with exponential backoff. A request will be retried as long
+as the request is deemed retryable and the number of retry attempts has not grown larger than the configured
+retry limit (default: 2).
+
+A request is deemed retryable when any of the following HTTP status codes is returned:
+
+- [408](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/408) (Timeout)
+- [429](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/429) (Too Many Requests)
+- [5XX](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/500) (Internal Server Errors)
+
+Use the `maxRetries` request option to configure this behavior.
+
+```typescript
+const response = await client.files.upload(..., {
+ maxRetries: 0 // override maxRetries at the request level
+});
+```
+
+### Timeouts
+
+The SDK defaults to a 60 second timeout. Use the `timeoutInSeconds` option to configure this behavior.
+
+```typescript
+const response = await client.files.upload(..., {
+ timeoutInSeconds: 30 // override timeout to 30s
+});
+```
+
+### Aborting Requests
+
+The SDK allows users to abort requests at any point by passing in an abort signal.
+
+```typescript
+const controller = new AbortController();
+const response = await client.files.upload(..., {
+ abortSignal: controller.signal
+});
+controller.abort(); // aborts the request
+```
+
+### Access Raw Response Data
+
+The SDK provides access to raw response data, including headers, through the `.withRawResponse()` method.
+The `.withRawResponse()` method returns a promise that results to an object with a `data` and a `rawResponse` property.
+
+```typescript
+const { data, rawResponse } = await client.files.upload(...).withRawResponse();
+
+console.log(data);
+console.log(rawResponse.headers['X-My-Header']);
+```
+
+### Runtime Compatibility
+
+The SDK works in the following runtimes:
+
+- Node.js 18+
+- Vercel
+- Cloudflare Workers
+- Deno v1.25+
+- Bun 1.0+
+- React Native
+
+### Customizing Fetch Client
+
+The SDK provides a way for you to customize the underlying HTTP client / Fetch function. If you're running in an
+unsupported environment, this provides a way for you to break glass and ensure the SDK works.
+
+```typescript
+import { ImageKitClient } from "imagekit";
+
+const client = new ImageKitClient({
+ ...
+ fetcher: // provide your implementation here
+});
+```
+
+## Contributing
+
+While we value open-source contributions to this SDK, this library is generated programmatically.
+Additions made directly to this library would have to be moved over to our generation code,
+otherwise they would be overwritten upon the next generated release. Feel free to open a PR as
+a proof of concept, but know that we will not be able to merge it as-is. We suggest opening
+an issue first to discuss with us!
+
+On the other hand, contributions to the README are always very welcome!
diff --git a/babel-register.js b/babel-register.js
deleted file mode 100644
index a24dfd20..00000000
--- a/babel-register.js
+++ /dev/null
@@ -1,3 +0,0 @@
-const register = require("@babel/register").default;
-
-register({ extensions: [".ts", ".tsx", ".js", ".jsx"] });
diff --git a/index.ts b/index.ts
deleted file mode 100644
index 59d984fc..00000000
--- a/index.ts
+++ /dev/null
@@ -1,681 +0,0 @@
-/*
- Helper Modules
-*/
-import _ from "lodash";
-import errorMessages from "./libs/constants/errorMessages";
-import {
- BulkDeleteFilesError,
- BulkDeleteFilesResponse,
- CopyFolderError,
- CopyFolderResponse,
- FileDetailsOptions,
- FileObject,
- FolderObject,
- FileMetadataResponse,
- ImageKitOptions,
- ListFileOptions,
- ListFileResponse,
- MoveFolderError,
- MoveFolderResponse,
- PurgeCacheResponse,
- PurgeCacheStatusResponse,
- UploadOptions,
- UploadResponse,
- UrlOptions,
- CopyFileOptions,
- MoveFileOptions,
- CreateFolderOptions,
- CopyFolderOptions,
- MoveFolderOptions,
- FileVersionDetailsOptions,
- DeleteFileVersionOptions,
- RestoreFileVersionOptions,
- CreateCustomMetadataFieldOptions,
- GetCustomMetadataFieldsOptions,
- CustomMetadataField,
- UpdateCustomMetadataFieldOptions,
- RenameFileOptions,
- RenameFileResponse,
-} from "./libs/interfaces";
-import { IKCallback } from "./libs/interfaces/IKCallback";
-import manage from "./libs/manage";
-import signature from "./libs/signature";
-import upload from "./libs/upload";
-import { verify as verifyWebhookEvent } from "./utils/webhook-signature";
-import customMetadataField from "./libs/manage/custom-metadata-field";
-/*
- Implementations
-*/
-import url from "./libs/url";
-/*
- Utils
-*/
-import pHashUtils from "./utils/phash";
-import transformationUtils from "./utils/transformation";
-import IKResponse from "./libs/interfaces/IKResponse";
-
-const promisify = function (thisContext: ImageKit, fn: Function) {
- return function (...args: any[]): Promise | void {
- if (args.length === fn.length && typeof args[args.length - 1] !== "undefined") {
- if (typeof args[args.length - 1] !== "function") {
- throw new Error("Callback must be a function.");
- }
- fn.call(thisContext, ...args);
- } else {
- return new Promise((resolve, reject) => {
- const callback = function (err: Error, ...results: any[]) {
- if (err) {
- return reject(err);
- } else {
- resolve(results.length > 1 ? results : results[0]);
- }
- };
- args.pop()
- args.push(callback);
- fn.call(thisContext, ...args);
- });
- }
- };
-};
-class ImageKit {
- options: ImageKitOptions = {
- uploadEndpoint: "https://upload.imagekit.io/api/v1/files/upload",
- publicKey: "",
- privateKey: "",
- urlEndpoint: "",
- transformationPosition: transformationUtils.getDefault(),
- };
-
- constructor(opts: ImageKitOptions = {} as ImageKitOptions) {
- this.options = _.extend(this.options, opts);
- if (!this.options.publicKey) {
- throw new Error(errorMessages.MANDATORY_PUBLIC_KEY_MISSING.message);
- }
- if (!this.options.privateKey) {
- throw new Error(errorMessages.MANDATORY_PRIVATE_KEY_MISSING.message);
- }
- if (!this.options.urlEndpoint) {
- throw new Error(errorMessages.MANDATORY_URL_ENDPOINT_KEY_MISSING.message);
- }
- }
-
- /**
- * This method allows you to create an URL to access a file using the relative or absolute path and the ImageKit URL endpoint (urlEndpoint). The file can be an image, video or any other static file supported by ImageKit.
- *
- * @see {@link https://github.com/imagekit-developer/imagekit-nodejs#url-generation}
- * @see {@link https://docs.imagekit.io/integration/url-endpoints}
- *
- * @param urlOptions
- */
-
- url(urlOptions: UrlOptions): string {
- return url(urlOptions, this.options);
- }
-
- /**
- * You can upload file to ImageKit.io media library from your server-side using private API key authentication.
- *
- * @see {@link https://docs.imagekit.io/api-reference/upload-file-api/server-side-file-upload}
- *
- * @param uploadOptions
- */
- upload(uploadOptions: UploadOptions): Promise>;
- upload(uploadOptions: UploadOptions, callback: IKCallback>): void;
- upload(
- uploadOptions: UploadOptions,
- callback?: IKCallback>,
- ): void | Promise> {
- return promisify>(this, upload)(uploadOptions, this.options, callback);
- }
-
- /**
- * This API can list all the uploaded files in your ImageKit.io media library.
- * For searching and filtering, you can use query parameters as described in docs.
- *
- * @see {@link https://docs.imagekit.io/api-reference/media-api/list-and-search-files}
- *
- * @param listFilesOptions
- */
- listFiles(listOptions: ListFileOptions): Promise>;
- listFiles(listOptions: ListFileOptions, callback: IKCallback>): void;
- listFiles(
- listOptions: ListFileOptions,
- callback?: IKCallback>,
- ): void | Promise> {
- return promisify>(this, manage.listFiles)(listOptions, this.options, callback);
- }
-
- /**
- * Get the file details such as tags, customCoordinates, and isPrivate properties using get file detail API.
- *
- * @see {@link https://docs.imagekit.io/api-reference/media-api/get-file-details}
- *
- * @param fileId
- */
- getFileDetails(fileId: string): Promise>;
- getFileDetails(fileId: string, callback: IKCallback>): void;
- getFileDetails(
- fileId: string,
- callback?: IKCallback>,
- ): void | Promise> {
- return promisify>(this, manage.getFileDetails)(fileId, this.options, callback);
- }
-
- /**
- * Get all versions of an assset.
- *
- * @see {@link https://docs.imagekit.io/api-reference/media-api/get-file-versions}
- *
- * @param fileId
- */
- getFileVersions(fileId: string): Promise>;
- getFileVersions(fileId: string, callback: IKCallback>): void;
- getFileVersions(
- fileId: string,
- callback?: IKCallback>,
- ): void | Promise> {
- return promisify>(this, manage.getFileVersions)(fileId, this.options, callback);
- }
-
- /**
- * Get file details of a specific version.
- *
- * @see {@link https://docs.imagekit.io/api-reference/media-api/get-file-version-details}
- *
- * @param fileVersionDetailsOptions
- */
- getFileVersionDetails(fileVersionDetailsOptions: FileVersionDetailsOptions): Promise>;
- getFileVersionDetails(
- fileVersionDetailsOptions: FileVersionDetailsOptions,
- callback: IKCallback>,
- ): void;
- getFileVersionDetails(
- fileVersionDetailsOptions: FileVersionDetailsOptions,
- callback?: IKCallback>,
- ): void | Promise> {
- return promisify>(this, manage.getFileVersionDetails)(
- fileVersionDetailsOptions,
- this.options,
- callback,
- );
- }
-
- /**
- * Get image exif, pHash and other metadata for uploaded files in ImageKit.io media library using this API.
- *
- * @see {@link https://docs.imagekit.io/api-reference/metadata-api/get-image-metadata-for-uploaded-media-files}
- *
- * @param fileIdOrURL The unique fileId of the uploaded file or absolute URL.
- */
- getFileMetadata(fileIdOrURL: string): Promise>;
- getFileMetadata(fileIdOrURL: string, callback: IKCallback>): void;
- getFileMetadata(
- fileIdOrURL: string,
- callback?: IKCallback>,
- ): void | Promise> {
- return promisify>(this, manage.getFileMetadata)(
- fileIdOrURL,
- this.options,
- callback,
- );
- }
-
- /**
- * Update file details such as tags and customCoordinates attribute using update file detail API.
- *
- * @see {@link https://docs.imagekit.io/api-reference/media-api/update-file-details}
- *
- * @param fileId The unique fileId of the uploaded file. fileId is returned in list files API and upload API.
- * @param updateData
- */
- updateFileDetails(fileId: string, updateData: FileDetailsOptions): Promise>;
- updateFileDetails(fileId: string, updateData: FileDetailsOptions, callback: IKCallback>): void;
- updateFileDetails(
- fileId: string,
- updateData: FileDetailsOptions,
- callback?: IKCallback>,
- ): void | Promise> {
- return promisify>(this, manage.updateFileDetails)(
- fileId,
- updateData,
- this.options,
- callback,
- );
- }
-
- /**
- * Add tags to multiple files in a single request. The method accepts an array of fileIDs of the files and an array of tags that have to be added to those files.
- *
- * @see {@link https://docs.imagekit.io/api-reference/media-api/add-tags-bulk}
- *
- * @param fileIds
- * @param tags
- */
- bulkAddTags(fileIds: string[], tags: string[]): Promise>;
- bulkAddTags(fileIds: string[], tags: string[], callback: IKCallback>): void;
- bulkAddTags(
- fileIds: string[],
- tags: string[],
- callback?: IKCallback>,
- ): void | Promise> {
- return promisify>(this, manage.bulkAddTags)(fileIds, tags, this.options, callback);
- }
-
- /**
- * Remove tags to multiple files in a single request. The method accepts an array of fileIDs of the files and an array of tags that have to be removed to those files.
- *
- * @see {@link https://docs.imagekit.io/api-reference/media-api/remove-tags-bulk}
- *
- * @param fileIds
- * @param tags
- */
- bulkRemoveTags(fileIds: string[], tags: string[]): Promise>;
- bulkRemoveTags(fileIds: string[], tags: string[], callback: IKCallback>): void;
- bulkRemoveTags(
- fileIds: string[],
- tags: string[],
- callback?: IKCallback>,
- ): void | Promise> {
- return promisify>(this, manage.bulkRemoveTags)(fileIds, tags, this.options, callback);
- }
-
- /**
- * Remove AITags from multiple files in a single request.
- *
- * @see {@link https://docs.imagekit.io/api-reference/media-api/remove-aitags-bulk}
- *
- * @param fileIds
- * @param tags
- */
- bulkRemoveAITags(fileIds: string[], tags: string[]): Promise>;
- bulkRemoveAITags(fileIds: string[], tags: string[], callback: IKCallback>): void;
- bulkRemoveAITags(
- fileIds: string[],
- tags: string[],
- callback?: IKCallback>,
- ): void | Promise> {
- return promisify>(this, manage.bulkRemoveAITags)(fileIds, tags, this.options, callback);
- }
-
- /**
- * You can programmatically delete uploaded files in media library using delete file API.
- *
- * @see {@link https://docs.imagekit.io/api-reference/media-api/delete-file}
- *
- * @param fileId The unique fileId of the uploaded file. fileId is returned in list files API and upload API
- */
- deleteFile(fileId: string): Promise>;
- deleteFile(fileId: string, callback: IKCallback>): void;
- deleteFile(fileId: string, callback?: IKCallback>): void | Promise> {
- return promisify>(this, manage.deleteFile)(fileId, this.options, callback);
- }
-
- /**
- * Delete any non-current version of a file.
- *
- * @see {@link https://docs.imagekit.io/api-reference/media-api/delete-file-version}
- *
- * @param deleteFileVersionOptions
- */
- deleteFileVersion(deleteFileVersionOptions: DeleteFileVersionOptions): Promise>;
- deleteFileVersion(deleteFileVersionOptions: DeleteFileVersionOptions, callback: IKCallback>): void;
- deleteFileVersion(
- deleteFileVersionOptions: DeleteFileVersionOptions,
- callback?: IKCallback>,
- ): void | Promise> {
- return promisify>(this, manage.deleteFileVersion)(
- deleteFileVersionOptions,
- this.options,
- callback,
- );
- }
-
- /**
- * Restore file version to a different version of a file.
- *
- * @see {@link https://docs.imagekit.io/api-reference/media-api/restore-file-version}
- *
- * @param restoreFileVersionOptions
- */
- restoreFileVersion(restoreFileVersionOptions: RestoreFileVersionOptions): Promise>;
- restoreFileVersion(
- restoreFileVersionOptions: RestoreFileVersionOptions,
- callback: IKCallback>,
- ): void;
- restoreFileVersion(
- restoreFileVersionOptions: RestoreFileVersionOptions,
- callback?: IKCallback>,
- ): void | Promise> {
- return promisify>(this, manage.restoreFileVersion)(
- restoreFileVersionOptions,
- this.options,
- callback,
- );
- }
-
- /**
- * This will purge CDN and ImageKit.io internal cache.
- *
- * @see {@link https://docs.imagekit.io/api-reference/media-api/purge-cache}
- *
- * @param url The exact URL of the file to be purged. For example - https://ik.imageki.io/your_imagekit_id/rest-of-the-file-path.jpg
- */
- purgeCache(url: string): Promise>;
- purgeCache(url: string, callback: IKCallback>): void;
- purgeCache(
- url: string,
- callback?: IKCallback>,
- ): void | Promise> {
- return promisify>(this, manage.purgeCache)(url, this.options, callback);
- }
-
- /**
- * Get the status of submitted purge request.
- *
- * @see {@link https://docs.imagekit.io/api-reference/media-api/purge-cache-status}
- *
- * @param requestId The requestId returned in response of purge cache API.
- */
- getPurgeCacheStatus(requestId: string, callback: IKCallback>): void;
- getPurgeCacheStatus(requestId: string): Promise>;
- getPurgeCacheStatus(
- requestId: string,
- callback?: IKCallback>,
- ): void | Promise> {
- return promisify>(this, manage.getPurgeCacheStatus)(
- requestId,
- this.options,
- callback,
- );
- }
-
- /**
- * Delete multiple files. The method accepts an array of file IDs of the files that have to be deleted.
- *
- * @see {@link https://docs.imagekit.io/api-reference/media-api/delete-files-bulk}
- *
- * @param fileIdArray The requestId returned in response of purge cache API.
- */
- bulkDeleteFiles(
- fileIdArray: string[],
- callback?: IKCallback, IKResponse>,
- ): void | Promise>;
- bulkDeleteFiles(
- fileIdArray: string[],
- callback?: IKCallback, IKResponse>,
- ): void | Promise> {
- return promisify>(this, manage.bulkDeleteFiles)(
- fileIdArray,
- this.options,
- callback,
- );
- }
-
- /**
- * This will copy a file from one location to another. This method accepts the source file's path and destination folder path.
- *
- * @see {@link https://docs.imagekit.io/api-reference/media-api/copy-file}
- *
- * @param copyFileOptions
- */
- copyFile(copyFileOptions: CopyFileOptions): Promise>;
- copyFile(copyFileOptions: CopyFileOptions, callback: IKCallback>): void;
- copyFile(
- copyFileOptions: CopyFileOptions,
- callback?: IKCallback>,
- ): void | Promise> {
- return promisify>(this, manage.copyFile)(copyFileOptions, this.options, callback);
- }
-
- /**
- * This will move a file from one location to another. This method accepts the source file's path and destination folder path.
- *
- * @see {@link https://docs.imagekit.io/api-reference/media-api/move-file}
- *
- * @param moveFileOptions
- */
- moveFile(moveFileOptions: MoveFileOptions): Promise>;
- moveFile(moveFileOptions: MoveFileOptions, callback: IKCallback>): void;
- moveFile(
- moveFileOptions: MoveFileOptions,
- callback?: IKCallback>,
- ): void | Promise> {
- return promisify>(this, manage.moveFile)(moveFileOptions, this.options, callback);
- }
-
- /**
- * You can programmatically rename an already existing file in the media library using rename file API. This operation would rename all file versions of the file. Note: The old URLs will stop working. The file/file version URLs cached on CDN will continue to work unless a purge is requested.
- *
- * @see {@link https://docs.imagekit.io/api-reference/media-api/rename-file}
- *
- * @param renameFileOptions
- */
- renameFile(renameFileOptions: RenameFileOptions): Promise>;
- renameFile(renameFileOptions: RenameFileOptions, callback: IKCallback>): void;
- renameFile(
- renameFileOptions: RenameFileOptions,
- callback?: IKCallback>,
- ): void | Promise> {
- return promisify>(this, manage.renameFile)(
- renameFileOptions,
- this.options,
- callback,
- );
- }
-
- /**
- * This will create a new folder. This method accepts folder name and parent folder path.
- *
- * @see {@link https://docs.imagekit.io/api-reference/media-api/create-folder}
- *
- * @param createFolderOptions
- */
- createFolder(createFolderOptions: CreateFolderOptions): Promise>;
- createFolder(createFolderOptions: CreateFolderOptions, callback: IKCallback>): void;
- createFolder(
- createFolderOptions: CreateFolderOptions,
- callback?: IKCallback>,
- ): void | Promise> {
- return promisify>(this, manage.createFolder)(createFolderOptions, this.options, callback);
- }
-
- /**
- * This will delete the specified folder and all nested files & folders. This method accepts the full path of the folder that is to be deleted.
- *
- * @see {@link https://docs.imagekit.io/api-reference/media-api/delete-folder}
- *
- * @param foldePath
- */
- deleteFolder(folderPath: string): Promise>;
- deleteFolder(folderPath: string, callback: IKCallback>): void;
- deleteFolder(folderPath: string, callback?: IKCallback>): void | Promise> {
- return promisify>(this, manage.deleteFolder)(folderPath, this.options, callback);
- }
-
- /**
- * This will copy a folder from one location to another. This method accepts the source folder's path and destination folder path.
- *
- * @see {@link https://docs.imagekit.io/api-reference/media-api/copy-folder}
- *
- * @param copyFolderOptions
- */
- copyFolder(copyFolderOptions: CopyFolderOptions): Promise>;
- copyFolder(
- copyFolderOptions: CopyFolderOptions,
- callback: IKCallback, IKResponse>,
- ): void;
- copyFolder(
- copyFolderOptions: CopyFolderOptions,
- callback?: IKCallback, IKResponse>,
- ): void | Promise> {
- return promisify>(this, manage.copyFolder)(
- copyFolderOptions,
- this.options,
- callback,
- );
- }
-
- /**
- * This will move a folder from one location to another. This method accepts the source folder's path and destination folder path.
- *
- * @see {@link https://docs.imagekit.io/api-reference/media-api/move-folder}
- *
- * @param moveFolderOptions
- */
- moveFolder(moveFolderOptions: MoveFolderOptions): Promise>;
- moveFolder(
- moveFolderOptions: MoveFolderOptions,
- callback: IKCallback, IKResponse>,
- ): void;
- moveFolder(
- moveFolderOptions: MoveFolderOptions,
- callback?: IKCallback, MoveFolderError>,
- ): void | Promise> {
- return promisify>(this, manage.moveFolder)(
- moveFolderOptions,
- this.options,
- callback,
- );
- }
-
- /**
- * In case you are looking to implement client-side file upload, you are going to need a token, expiry timestamp, and a valid signature for that upload. The SDK provides a simple method that you can use in your code to generate these authentication parameters for you.
- *
- * @see {@link https://github.com/imagekit-developer/imagekit-nodejs#authentication-parameter-generation}
- *
- * @param token
- * @param expire
- */
- getAuthenticationParameters(token?: string, expire?: number): { token: string; expire: number; signature: string } {
- return signature.getAuthenticationParameters(token, expire, this.options);
- }
-
- /**
- * This allows us to get a bulk operation status e.g. copy or move folder. This method accepts jobId that is returned by copy and move folder operations.
- *
- * @see {@link https://docs.imagekit.io/api-reference/media-api/move-folder}
- *
- * @param jobId
- */
- getBulkJobStatus(jobId: string): Promise>;
- getBulkJobStatus(jobId: string, callback: IKCallback>): Promise>;
- getBulkJobStatus(jobId: string, callback?: IKCallback>): void | Promise> {
- return promisify>(this, manage.getBulkJobStatus)(jobId, this.options, callback);
- }
-
- /**
- * Create custom metadata field
- *
- * @see {@link https://docs.imagekit.io/api-reference/custom-metadata-fields-api/create-custom-metadata-field}
- *
- * @param createCustomMetadataFieldOptions
- */
- createCustomMetadataField(
- createCustomMetadataFieldOptions: CreateCustomMetadataFieldOptions,
- ): Promise>;
- createCustomMetadataField(
- createCustomMetadataFieldOptions: CreateCustomMetadataFieldOptions,
- callback: IKCallback>,
- ): Promise>;
- createCustomMetadataField(
- createCustomMetadataFieldOptions: CreateCustomMetadataFieldOptions,
- callback?: IKCallback>,
- ): void | Promise> {
- return promisify>(this, customMetadataField.create)(
- createCustomMetadataFieldOptions,
- this.options,
- callback,
- );
- }
-
- /**
- *Get a list of all the custom metadata fields.
- *
- * @see {@link https://docs.imagekit.io/api-reference/custom-metadata-fields-api/get-custom-metadata-field}
- *
- */
- getCustomMetadataFields(
- getCustomMetadataFieldsOptions: GetCustomMetadataFieldsOptions,
- ): Promise>;
- getCustomMetadataFields(
- getCustomMetadataFieldsOptions: GetCustomMetadataFieldsOptions,
- callback: IKCallback>,
- ): Promise>;
- getCustomMetadataFields(
- getCustomMetadataFieldsOptions: GetCustomMetadataFieldsOptions,
- callback?: IKCallback>,
- ): void | Promise> {
- return promisify>(this, customMetadataField.list)(
- getCustomMetadataFieldsOptions,
- this.options,
- callback,
- );
- }
-
- /**
- * Update custom metadata field
- *
- * @see {@link https://docs.imagekit.io/api-reference/custom-metadata-fields-api/update-custom-metadata-field}
- *
- * @param fieldId
- * @param updateCustomMetadataFieldOptions
- */
- updateCustomMetadataField(
- fieldId: string,
- updateCustomMetadataFieldOptions: UpdateCustomMetadataFieldOptions,
- ): Promise>;
- updateCustomMetadataField(
- fieldId: string,
- updateCustomMetadataFieldOptions: UpdateCustomMetadataFieldOptions,
- callback: IKCallback>,
- ): Promise>;
- updateCustomMetadataField(
- fieldId: string,
- updateCustomMetadataFieldOptions: UpdateCustomMetadataFieldOptions,
- callback?: IKCallback>,
- ): void | Promise> {
- return promisify>(this, customMetadataField.update)(
- fieldId,
- updateCustomMetadataFieldOptions,
- this.options,
- callback,
- );
- }
-
- /**
- * Delete a custom metadata field
- *
- * @see {@link https://docs.imagekit.io/api-reference/custom-metadata-fields-api/delete-custom-metadata-field}
- *
- * @param fieldId
- */
- deleteCustomMetadataField(fieldId: string): Promise>;
- deleteCustomMetadataField(fieldId: string, callback: IKCallback>): void;
- deleteCustomMetadataField(fieldId: string, callback?: IKCallback>): void | Promise> {
- return promisify>(this, customMetadataField.deleteField)(fieldId, this.options, callback);
- }
-
- /**
- * Perceptual hashing allows you to construct a hash value that uniquely identifies an input image based on an image's contents. ImageKit.io metadata API returns the pHash value of an image in the response. You can use this value to find a duplicate (or similar) image by calculating the distance between the two images' pHash value.
- *
- * This SDK exposes pHashDistance function to calculate the distance between two pHash values. It accepts two pHash hexadecimal strings and returns a numeric value indicative of the level of difference between the two images.
- *
- * @see {@link https://docs.imagekit.io/api-reference/metadata-api#perceptual-hash-phash}
- *
- * @param firstPHash
- * @param secondPHash
- */
- pHashDistance(firstPHash: string, secondPHash: string): number | Error {
- return pHashUtils.pHashDistance(firstPHash, secondPHash);
- }
-
- /**
- * @param payload - Raw webhook request body (Encoded as UTF8 string or Buffer)
- * @param signature - Webhook signature as UTF8 encoded strings (Stored in `x-ik-signature` header of the request)
- * @param secret - Webhook secret as UTF8 encoded string [Copy from ImageKit dashboard](https://imagekit.io/dashboard/developer/webhooks)
- * @returns \{ `timestamp`: Verified UNIX epoch timestamp if signature, `event`: Parsed webhook event payload \}
- */
- verifyWebhookEvent = verifyWebhookEvent;
-}
-
-export = ImageKit;
diff --git a/jest.config.mjs b/jest.config.mjs
new file mode 100644
index 00000000..b6927007
--- /dev/null
+++ b/jest.config.mjs
@@ -0,0 +1,42 @@
+/** @type {import('jest').Config} */
+export default {
+ preset: "ts-jest",
+ testEnvironment: "node",
+ projects: [
+ {
+ displayName: "unit",
+ preset: "ts-jest",
+ testEnvironment: "node",
+ moduleNameMapper: {
+ "^(\.{1,2}/.*)\.js$": "$1",
+ },
+ roots: ["/tests"],
+ testPathIgnorePatterns: ["\.browser\.(spec|test)\.[jt]sx?$", "/tests/wire/"],
+ setupFilesAfterEnv: [],
+ },
+ {
+ displayName: "browser",
+ preset: "ts-jest",
+ testEnvironment: "/tests/BrowserTestEnvironment.ts",
+ moduleNameMapper: {
+ "^(\.{1,2}/.*)\.js$": "$1",
+ },
+ roots: ["/tests"],
+ testMatch: ["/tests/unit/**/?(*.)+(browser).(spec|test).[jt]s?(x)"],
+ setupFilesAfterEnv: [],
+ },
+ ,
+ {
+ displayName: "wire",
+ preset: "ts-jest",
+ testEnvironment: "node",
+ moduleNameMapper: {
+ "^(\.{1,2}/.*)\.js$": "$1",
+ },
+ roots: ["/tests/wire"],
+ setupFilesAfterEnv: ["/tests/mock-server/setup.ts"],
+ },
+ ],
+ workerThreads: false,
+ passWithNoTests: true,
+};
diff --git a/libs/constants/errorMessages.ts b/libs/constants/errorMessages.ts
deleted file mode 100644
index ba10e6cd..00000000
--- a/libs/constants/errorMessages.ts
+++ /dev/null
@@ -1,53 +0,0 @@
-export default {
- "MANDATORY_INITIALIZATION_MISSING": { message: "Missing publicKey or privateKey or urlEndpoint during ImageKit initialization", help: "" },
- "MANDATORY_PUBLIC_KEY_MISSING": { message: "Missing publicKey during ImageKit initialization", help: "" },
- "MANDATORY_PRIVATE_KEY_MISSING": { message: "Missing privateKey during ImageKit initialization", help: "" },
- "MANDATORY_URL_ENDPOINT_KEY_MISSING": { message: "Missing urlEndpoint during ImageKit initialization", help: "" },
- "INVALID_TRANSFORMATION_POSITION": { message: "Invalid transformationPosition parameter", help: "" },
- "CACHE_PURGE_URL_MISSING": { message: "Missing URL parameter for this request", help: "" },
- "CACHE_PURGE_STATUS_ID_MISSING": { message: "Missing Request ID parameter for this request", help: "" },
- "FILE_ID_MISSING": { message: "Missing fileId parameter for this request", help: "" },
- "FILE_VERSION_ID_MISSING": { message: "Missing versionId parameter for this request", help: "" },
- "FILE_ID_OR_URL_MISSING": { message: "Pass either fileId or remote URL of the image as first parameter", help: "" },
- "INVALID_LIST_OPTIONS": { message: "Pass a valid JSON list options e.g. {skip: 10, limit: 100}.", help: "" },
- "UPDATE_DATA_MISSING": { message: "Missing file update data for this request", help: "" },
- "UPDATE_DATA_TAGS_INVALID": { message: "Invalid tags parameter for this request", help: "tags should be passed as null or an array like ['tag1', 'tag2']" },
- "UPDATE_DATA_COORDS_INVALID": { message: "Invalid customCoordinates parameter for this request", help: "customCoordinates should be passed as null or a string like 'x,y,width,height'" },
- "LIST_FILES_INPUT_MISSING": { message: "Missing options for list files", help: "If you do not want to pass any parameter for listing, pass an empty object" },
- "MISSING_UPLOAD_DATA": { message: "Missing data for upload", help: "" },
- "MISSING_UPLOAD_FILE_PARAMETER": { message: "Missing file parameter for upload", help: "" },
- "MISSING_UPLOAD_FILENAME_PARAMETER": { message: "Missing fileName parameter for upload", help: "" },
- "JOB_ID_MISSING": { message: "Missing jobId parameter", help: "" },
- "INVALID_DESTINATION_FOLDER_PATH": { message: "Invalid destinationPath value", help: "It should be a string like '/path/to/folder'" },
- "INVALID_INCLUDE_VERSION": { message: "Invalid includeFileVersions value", help: "It should be a boolean" },
- "INVALID_SOURCE_FILE_PATH": { message: "Invalid sourceFilePath value", help: "It should be a string like /path/to/file.jpg'" },
- "INVALID_SOURCE_FOLDER_PATH": { message: "Invalid sourceFolderPath value", help: "It should be a string like '/path/to/folder'" },
- "INVALID_FOLDER_NAME": { message: "Invalid folderName value", help: "" },
- "INVALID_PARENT_FOLDER_PATH": { message: "Invalid parentFolderPath value", help: "It should be a string like '/path/to/folder'" },
- "INVALID_FOLDER_PATH": { message: "Invalid folderPath value", help: "It should be a string like '/path/to/folder'" },
- // pHash errors
- "INVALID_PHASH_VALUE": { message: "Invalid pHash value", help: "Both pHash strings must be valid hexadecimal numbers" },
- "MISSING_PHASH_VALUE": { message: "Missing pHash value", help: "Please pass two pHash values" },
- "UNEQUAL_STRING_LENGTH": { message: "Unequal pHash string length", help: "For distance calucation, the two pHash strings must have equal length" },
- //bulk delete errors
- "INVALID_FILEIDS_VALUE": { message: "Invalid value for fileIds", help: "fileIds should be an array of fileId of the files. The array should have atleast one fileId." },
- "BULK_ADD_TAGS_INVALID": { message: "Invalid value for tags", help: "tags should be a non empty array of string like ['tag1', 'tag2']." },
- "BULK_AI_TAGS_INVALID": { message: "Invalid value for AITags", help: "AITags should be a non empty array of string like ['tag1', 'tag2']." },
- "CMF_NAME_MISSING": { message: "Missing name parameter for this request", help: "" },
- "CMF_LABEL_MISSING": { message: "Missing label parameter for this request", help: "" },
- "CMF_SCHEMA_MISSING": { message: "Missing schema parameter for this request", help: "" },
- "CMF_SCHEMA_INVALID": { message: "Invalid value for schema", help: "schema should have a mandatory type field." },
- "CMF_LABEL_SCHEMA_MISSING": { message: "Both label and schema is missing", help: "" },
- "CMF_FIELD_ID_MISSING": { message: "Missing fieldId parameter for this request", help: "" },
- "INVALID_FILE_PATH": { message: "Invalid value for filePath", help: "Pass the full path of the file. For example - /path/to/file.jpg" },
- "INVALID_NEW_FILE_NAME": { message: "Invalid value for newFileName. It should be a string.", help: "" },
- "INVALID_PURGE_CACHE": { message: "Invalid value for purgeCache. It should be boolean.", help: "" },
- // Webhook signature
- "VERIFY_WEBHOOK_EVENT_SIGNATURE_INCORRECT": { message: "Incorrect signature", help: "Please pass x-ik-signature header as utf8 string" },
- "VERIFY_WEBHOOK_EVENT_SIGNATURE_MISSING": { message: "Signature missing", help: "Please pass x-ik-signature header as utf8 string" },
- "VERIFY_WEBHOOK_EVENT_TIMESTAMP_MISSING": { message: "Timestamp missing", help: "Please pass x-ik-signature header as utf8 string" },
- "VERIFY_WEBHOOK_EVENT_TIMESTAMP_INVALID": { message: "Timestamp invalid", help: "Please pass x-ik-signature header as utf8 string" },
- "INVALID_TRANSFORMATION": { message: "Invalid transformation parameter. Please include at least pre, post, or both.", help: ""},
- "INVALID_PRE_TRANSFORMATION": { message: "Invalid pre transformation parameter.", help: ""},
- "INVALID_POST_TRANSFORMATION": { message: "Invalid post transformation parameter.", help: ""},
-};
\ No newline at end of file
diff --git a/libs/constants/supportedTransforms.ts b/libs/constants/supportedTransforms.ts
deleted file mode 100644
index fb0e6498..00000000
--- a/libs/constants/supportedTransforms.ts
+++ /dev/null
@@ -1,162 +0,0 @@
-/**
- * @see {@link https://docs.imagekit.io/features/image-transformations}
- */
-const supportedTransforms = {
- /**
- * @see {@link https://docs.imagekit.io/features/image-transformations/resize-crop-and-other-transformations#width-w}
- */
- width: "w",
-
- /**
- * @see {@link https://docs.imagekit.io/features/image-transformations/resize-crop-and-other-transformations#height-h}
- */
- height: "h",
-
- /**
- * @see {@link https://docs.imagekit.io/features/image-transformations/resize-crop-and-other-transformations#aspect-ratio-ar}
- */
- aspectRatio: "ar",
-
- /**
- * @see {@link https://docs.imagekit.io/features/image-transformations/resize-crop-and-other-transformations#quality-q}
- */
- quality: "q",
-
- /**
- * @see {@link https://docs.imagekit.io/features/image-transformations/resize-crop-and-other-transformations#crop-crop-modes-and-focus}
- */
- crop: "c",
-
- /**
- * @see {@link https://docs.imagekit.io/features/image-transformations/resize-crop-and-other-transformations#crop-crop-modes-and-focus}
- */
- cropMode: "cm",
-
- /**
- * @see {@link https://docs.imagekit.io/features/image-transformations/resize-crop-and-other-transformations#focus-fo}
- */
- focus: "fo",
-
- /**
- * @see {@link https://docs.imagekit.io/features/image-transformations/resize-crop-and-other-transformations#examples-focus-using-cropped-image-coordinates}
- */
- x: "x",
-
- /**
- * @see {@link https://docs.imagekit.io/features/image-transformations/resize-crop-and-other-transformations#examples-focus-using-cropped-image-coordinates}
- */
- y: "y",
-
- /**
- * @see {@link https://docs.imagekit.io/features/image-transformations/resize-crop-and-other-transformations#format-f}
- */
- format: "f",
-
- /**
- * @see {@link https://docs.imagekit.io/features/image-transformations/resize-crop-and-other-transformations#radius-r}
- */
- radius: "r",
-
- /**
- * @see {@link https://docs.imagekit.io/features/image-transformations/resize-crop-and-other-transformations#background-color-bg}
- */
- background: "bg",
-
- /**
- * @see {@link https://docs.imagekit.io/features/image-transformations/resize-crop-and-other-transformations#border-b}
- */
- border: "b",
-
- /**
- * @see {@link https://docs.imagekit.io/features/image-transformations/resize-crop-and-other-transformations#rotate-rt}
- */
- rotation: "rt",
-
- /**
- * @see {@link https://docs.imagekit.io/features/image-transformations/resize-crop-and-other-transformations#rotate-rt}
- */
- rotate: "rt",
-
- /**
- * @see {@link https://docs.imagekit.io/features/image-transformations/resize-crop-and-other-transformations#blur-bl}
- */
- blur: "bl",
-
- /**
- * @see {@link https://docs.imagekit.io/features/image-transformations/resize-crop-and-other-transformations#named-transformation-n}
- */
- named: "n",
-
- /**
- * @see {@link https://docs.imagekit.io/features/image-transformations/resize-crop-and-other-transformations#progressive-image-pr}
- */
- progressive: "pr",
-
- /**
- * @see {@link https://docs.imagekit.io/features/image-transformations/resize-crop-and-other-transformations#lossless-webp-and-png-lo}
- */
- lossless: "lo",
-
- /**
- * @see {@link https://docs.imagekit.io/features/image-transformations/resize-crop-and-other-transformations#trim-edges-t}
- */
- trim: "t",
-
- /**
- * @see {@link https://docs.imagekit.io/features/image-transformations/resize-crop-and-other-transformations#image-metadata-md}
- */
- metadata: "md",
-
- /**
- * @see {@link https://docs.imagekit.io/features/image-transformations/resize-crop-and-other-transformations#color-profile-cp}
- */
- colorProfile: "cp",
-
- /**
- * @see {@link https://docs.imagekit.io/features/image-transformations/resize-crop-and-other-transformations#default-image-di}
- */
- defaultImage: "di",
-
- /**
- * @see {@link https://docs.imagekit.io/features/image-transformations/resize-crop-and-other-transformations#dpr-dpr}
- */
- dpr: "dpr",
-
- /**
- * @see {@link https://docs.imagekit.io/features/image-transformations/image-enhancement-and-color-manipulation#sharpen-e-sharpen}
- */
- effectSharpen: "e-sharpen",
-
- /**
- * @see {@link https://docs.imagekit.io/features/image-transformations/image-enhancement-and-color-manipulation#unsharp-mask-e-usm}
- */
- effectUSM: "e-usm",
-
- /**
- * @see {@link https://docs.imagekit.io/features/image-transformations/image-enhancement-and-color-manipulation#contrast-stretch-e-contrast}
- */
- effectContrast: "e-contrast",
-
- /**
- * @see {@link https://docs.imagekit.io/features/image-transformations/resize-crop-and-other-transformations#grayscale-e-grayscale}
- */
- effectGray: "e-grayscale",
-
- /**
- * @link https://docs.imagekit.io/features/image-transformations/image-enhancement-and-color-manipulation#shadow-e-shadow
- */
- effectShadow: "e-shadow",
-
- /**
- * @link https://docs.imagekit.io/features/image-transformations/image-enhancement-and-color-manipulation#gradient-e-gradient
- */
- effectGradient: "e-gradient",
-
- /**
- * @see {@link https://docs.imagekit.io/features/image-transformations/resize-crop-and-other-transformations#original-image-orig}
- */
- original: "orig",
-};
-
-export default supportedTransforms as { [key: string]: string };
-export type SupportedTransformsParam = keyof typeof supportedTransforms;
diff --git a/libs/interfaces/BulkDeleteFiles.ts b/libs/interfaces/BulkDeleteFiles.ts
deleted file mode 100644
index 9329db3f..00000000
--- a/libs/interfaces/BulkDeleteFiles.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-/**
- * Response when deleting multiple files from the media library.
- *
- * @see {@link https://docs.imagekit.io/api-reference/media-api/delete-files-bulk}
- */
-export interface BulkDeleteFilesResponse {
- /**
- * List of file ids of successfully deleted files
- */
- successfullyDeletedFileIds: string[];
-}
-
-export interface BulkDeleteFilesError extends Error {
- help: string;
- missingFileIds: string[];
-}
diff --git a/libs/interfaces/CopyFile.ts b/libs/interfaces/CopyFile.ts
deleted file mode 100644
index eef7cab3..00000000
--- a/libs/interfaces/CopyFile.ts
+++ /dev/null
@@ -1,15 +0,0 @@
-export interface CopyFileOptions {
- /**
- * The full path of the file you want to copy. For example - /path/to/file.jpg
- */
- sourceFilePath: string;
- /**
- * Full path to the folder you want to copy the above file into. For example - /folder/to/copy/into/
- */
- destinationPath: string;
- /**
- * Option to copy all versions of a file. By default, only the current version of the file is copied. When set to true, all versions of the file will be copied.
- * Default value is false
- */
- includeFileVersions?: boolean;
-}
\ No newline at end of file
diff --git a/libs/interfaces/CopyFolder.ts b/libs/interfaces/CopyFolder.ts
deleted file mode 100644
index c29d1a0f..00000000
--- a/libs/interfaces/CopyFolder.ts
+++ /dev/null
@@ -1,44 +0,0 @@
-/**
- * Response when copying folder in media library.
- *
- * @see {@link https://docs.imagekit.io/api-reference/media-api/copy-folder}
- *
- * On success, you will receive a jobId which can be used to get the copy operation's status.
- */
-export interface CopyFolderResponse {
- jobId: string;
-}
-
-/**
- * Error when copying folder in media library.
- *
- * @see {@link https://docs.imagekit.io/api-reference/media-api/copy-folder}
- *
- * If no files or folders are found at the specified sourceFolderPath then a error is returned.
- */
-export interface CopyFolderError extends Error {
- help: string;
- message: string;
- reason: string;
-}
-
-/**
- * Copy folder API options
- *
- * @see {@link https://docs.imagekit.io/api-reference/media-api/copy-folder}
- */
-export interface CopyFolderOptions {
- /**
- * The full path to the source folder you want to copy. For example - /path/of/source/folder.
- */
- sourceFolderPath: string;
- /**
- * Full path to the destination folder where you want to copy the source folder into. For example - /path/of/destination/folder.
- */
- destinationPath: string;
- /**
- * Option to copy all versions of files that are nested inside the selected folder. By default, only the current version of each file will be copied. When set to true, all versions of each file will be copied.
- * Default value - false
- */
- includeFileVersions?: boolean;
-}
\ No newline at end of file
diff --git a/libs/interfaces/CreateFolder.ts b/libs/interfaces/CreateFolder.ts
deleted file mode 100644
index 6f7c0025..00000000
--- a/libs/interfaces/CreateFolder.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-export interface CreateFolderOptions {
- /**
- * The folder will be created with this name. All characters except alphabets and numbers (inclusive of unicode letters, marks, and numerals in other languages) will be replaced by an underscore i.e. _.
- */
- folderName: string;
- /**
- * The folder where the new folder should be created, for root use / else the path e.g. containing/folder/.
- * Note: If any folder(s) is not present in the parentFolderPath parameter, it will be automatically created. For example, if you pass /product/images/summer, then product, images, and summer folders will be created if they don't already exist.
- */
- parentFolderPath: string;
-}
\ No newline at end of file
diff --git a/libs/interfaces/CustomMetatadaField.ts b/libs/interfaces/CustomMetatadaField.ts
deleted file mode 100644
index 7efcee06..00000000
--- a/libs/interfaces/CustomMetatadaField.ts
+++ /dev/null
@@ -1,123 +0,0 @@
-type RequiredSchema = {
- isValueRequired: true;
- defaultValue: T;
-} | {
- isValueRequired?: false;
- defaultValue?: T;
-};
-
-type CustomMetadataTextField = RequiredSchema & {
- type: "Text";
- minLength?: number;
- maxLength?: number;
-};
-
-type CustomMetadataTextareaField = RequiredSchema & {
- type: "Textarea";
- minLength?: number;
- maxLength?: number;
-};
-
-type CustomMetadataNumberField = RequiredSchema & {
- type: "Number";
- minValue?: string | number;
- maxValue?: string | number;
-};
-
-type CustomMetadataDateField = RequiredSchema & {
- type: "Date";
- minValue?: string | number;
- maxValue?: string | number;
-};
-
-type CustomMetadataBooleanField = RequiredSchema & {
- type: "Boolean";
-};
-
-type CustomMetadataSingleSelectField = RequiredSchema> & {
- type: "SingleSelect";
- selectOptions: Array;
-};
-
-type CustomMetadataMultiSelectField = RequiredSchema> & {
- type: "MultiSelect";
- selectOptions: Array;
-};
-
-export type CustomMetadataFieldSchema =
- | CustomMetadataTextField
- | CustomMetadataTextareaField
- | CustomMetadataNumberField
- | CustomMetadataDateField
- | CustomMetadataBooleanField
- | CustomMetadataSingleSelectField
- | CustomMetadataMultiSelectField;
-
-export type CustomMetadataFieldSchemaMinusType =
- | Omit
- | Omit
- | Omit
- | Omit
- | Omit
- | Omit
- | Omit;
-
-/**
- * Create a new custom metadata field
- *
- * @see {@link https://docs.imagekit.io/api-reference/custom-metadata-fields-api/create-custom-metadata-field}
- */
-export interface CreateCustomMetadataFieldOptions {
- /**
- * Name of the metadata field, unique across all (deleted or not deleted) custom metadata fields.
- */
- name: string;
- /**
- * Label of the metadata field, unique across all non deleted custom metadata fields
- */
- label: string;
- /**
- * An object that describes the rules for the custom metadata key.
- */
- schema: CustomMetadataFieldSchema
-}
-
-export interface CustomMetadataField {
- id: string;
- /**
- * Name of the metadata field, unique across all (deleted or not deleted) custom metadata fields.
- */
- name: string;
- /**
- * Label of the metadata field, unique across all non deleted custom metadata fields
- */
- label: string;
- /**
- * An object that describes the rules for the custom metadata key.
- */
- schema: CustomMetadataFieldSchema
-}
-
-/**
- * Update the label or schema of an existing custom metadata field.
- *
- * @see {@link https://docs.imagekit.io/api-reference/custom-metadata-fields-api/update-custom-metadata-field}
- */
-export interface UpdateCustomMetadataFieldOptions {
- /**
- * Label of the metadata field, unique across all non deleted custom metadata fields. This parameter is required if schema is not provided.
- */
- label?: string;
- /**
- * An object that describes the rules for the custom metadata key. This parameter is required if label is not provided.
- * Note: type cannot be updated and will be ignored if sent with the schema. The schema will be validated as per the existing type.
- */
- schema?: CustomMetadataFieldSchemaMinusType
-}
-
-export interface GetCustomMetadataFieldsOptions {
- /**
- * Set it to true if you want to receive deleted fields as well in the API response.
- */
- includeDeleted?: boolean;
-}
\ No newline at end of file
diff --git a/libs/interfaces/FileDetails.ts b/libs/interfaces/FileDetails.ts
deleted file mode 100644
index 358ac538..00000000
--- a/libs/interfaces/FileDetails.ts
+++ /dev/null
@@ -1,224 +0,0 @@
-import { FileType } from "./FileType";
-
-export interface EmbeddedMetadataValues {
- [key: string]:
- | string
- | number
- | boolean
- | Date
- | Array
-}
-
-export interface AITagItem {
- name: string
- confidence: number
- source: 'google-auto-tagging' | 'aws-auto-tagging'
-}
-
-export interface CMValues {
- [key: string]: | string
- | number
- | boolean
- | Array
-}
-
-interface BgRemoval {
- name: string
- options: {
- bg_color?: string
- bg_image_url?: string
- add_shadow: boolean
- semitransparency: boolean
- }
-}
-
-interface AutoTag {
- name: string
- maxTags: number
- minConfidence: number
-}
-
-export type Extension = (BgRemoval | AutoTag)[];
-
-/**
- * Options when updating file details such as tags and customCoordinates attribute using update file detail API.
- *
- * @see {@link https://docs.imagekit.io/api-reference/media-api/update-file-details}
- */
-export interface FileDetailsOptions {
- /**
- * Array of tags associated with the file.
- */
- tags?: string[];
- /**
- * Define an important area in the image.
- * Example - 50,50,500,500
- */
- customCoordinates?: string;
- /*
- * Object with array of extensions to be processed on the image.
- */
- extensions?: Extension;
- /*
- * Final status of pending extensions will be sent to this URL.
- */
- webhookUrl?: string
- /*
- * Array of AI tags to remove from the asset.
- */
- removeAITags?: string[];
- /*
- * A key-value data to be associated with the asset. To unset a key, send null value for that key. Before setting any custom metadata on an asset you have to create the field using custom metadata fields API.
- */
- customMetadata?: CMValues;
- /**
- * Configure the publication status of a file and its versions.
- */
- publish?: {
- isPublished: boolean;
- includeFileVersions?: boolean;
- };
-}
-
-/**
- *
- * File object.
- *
- * @see {@link https://docs.imagekit.io/api-reference/media-api#file-object-structure}
- */
-export interface FileObject {
- /**
- * The unique fileId of the uploaded file.
- */
- fileId: string;
- /**
- * Type of item. It can be either file, file-version or folder.
- */
- type: "file" | "file-version";
- /**
- * Name of the file or folder.
- */
- name: string;
- /**
- * The relative path of the file. In case of image, you can use this
- * path to construct different transformations.
- */
- filePath: string;
- /**
- * Array of tags associated with the image. If no tags are set, it will be null.
- */
- tags?: string[] | null;
- /**
- * Is the file marked as private. It can be either true or false.
- */
- isPrivateFile: boolean;
- /**
- * Value of custom coordinates associated with the image in format x,y,width,height.
- * If customCoordinates are not defined then it is null.
- */
- customCoordinates: string | null;
- /**
- * A publicly accessible URL of the file.
- */
- url: string;
- /**
- * In case of an image, a small thumbnail URL.
- */
- thumbnail: string;
- /**
- * The type of file, it could be either image or non-image.
- */
- fileType: FileType;
- /*
- * AITags field is populated only because the google-auto-tagging extension was executed synchronously and it received a successresponse.
- */
- AITags?: AITagItem[];
- /*
- * Field object which will contain the status of each extension at the time of completion of the update/upload request.
- */
- extensionStatus?: { [key: string]: string }
- /*
- * Consolidated embedded metadata associated with the file. It includes exif, iptc, and xmp data.
- */
- embeddedMetadata?: EmbeddedMetadataValues | null;
- /*
- * A key-value data associated with the asset. Before setting any custom metadata on an asset, you have to create the field using custom metadata fields API.
- */
- customMetadata?: CMValues;
- /*
- * Size of the file in bytes
- */
- size: number;
- /*
- * The date and time when the file was first uploaded. The format is YYYY-MM-DDTHH:mm:ss.sssZ
- */
- createdAt: string;
- /*
- * The date and time when the file was last updated. The format is YYYY-MM-DDTHH:mm:ss.sssZ
- */
- updatedAt: string;
- /*
- * Height of the image in pixels (Only for images)
- */
- height: number;
- /*
- * Width of the image in pixels (Only for Images)
- */
- width: number;
- /*
- * A boolean indicating if the image has an alpha layer or not.
- */
- hasAlpha: boolean;
- /*
- * MIME Type of the file. For example - image/jpeg
- */
- mime?: string;
- /**
- * An object containing the file or file version's id (versionId) and name.
- */
- versionInfo?: { name: string; id: string };
-}
-
-/**
- *
- * Folder object.
- *
- * @see {@link https://docs.imagekit.io/api-reference/media-api#file-object-structure}
- */
-export interface FolderObject {
- /**
- * The unique fileId of the folder.
- */
- folderId: string;
- /**
- * Type of item. It can be either file, file-version or folder.
- */
- type: "folder";
- /**
- * Name of the file or folder.
- */
- name: string;
- /**
- * The relative path of the folder.
- */
- folderPath: string;
- /*
- * The date and time when the folder was first created. The format is YYYY-MM-DDTHH:mm:ss.sssZ
- */
- createdAt: string;
- /*
- * The date and time when the folder was last updated. The format is YYYY-MM-DDTHH:mm:ss.sssZ
- */
- updatedAt: string;
-}
-
-export interface FileVersionDetailsOptions {
- /**
- * The unique fileId of the uploaded file. fileId is returned in list files API and upload API.
- */
- fileId: string;
- /**
- * The unique versionId of the uploaded file's version. This is returned in list files API and upload API as id within the versionInfo parameter.
- */
- versionId: string;
-}
diff --git a/libs/interfaces/FileFormat.ts b/libs/interfaces/FileFormat.ts
deleted file mode 100644
index aaa9bc90..00000000
--- a/libs/interfaces/FileFormat.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-/**
- * @see {@link https://help.imagekit.io/en/articles/2434102-image-format-support-in-imagekit-for-resizing-compression-and-static-file-delivery}
- */
-export type FileFormat =
- | "jpg"
- | "png"
- | "gif"
- | "svg"
- | "webp"
- | "pdf"
- | "js"
- | "css"
- | "txt"
- | "mp4"
- | "webm"
- | "mov"
- | "swf"
- | "ts"
- | "m3u8"
- | string;
diff --git a/libs/interfaces/FileMetadata.ts b/libs/interfaces/FileMetadata.ts
deleted file mode 100644
index 642310fe..00000000
--- a/libs/interfaces/FileMetadata.ts
+++ /dev/null
@@ -1,85 +0,0 @@
-import { FileFormat } from "./FileFormat";
-
-/**
- * Response when getting image exif, pHash and other metadata for uploaded files in ImageKit.io media library using this API.
- *
- * @see {@link https://docs.imagekit.io/api-reference/metadata-api/get-image-metadata-for-uploaded-media-files}
- */
-export interface FileMetadataResponse {
- height: number;
- width: number;
- size: number;
- format: FileFormat;
- hasColorProfile: boolean;
- quality: number;
- density: number;
- hasTransparency: boolean;
- /**
- * @see {@link https://docs.imagekit.io/api-reference/metadata-api#perceptual-hash-phash}
- */
- pHash: string;
- /**
- * @see {@link https://docs.imagekit.io/api-reference/metadata-api#exif}
- */
- exif: {
- image: {
- Make: string;
- Model: string;
- Orientation: number;
- XResolution: number;
- YResolution: number;
- ResolutionUnit: number;
- Software: string;
- ModifyDate: string;
- YCbCrPositioning: number;
- ExifOffset: number;
- GPSInfo: number;
- };
- thumbnail: {
- Compression: number;
- XResolution: number;
- YResolution: number;
- ResolutionUnit: number;
- ThumbnailOffset: number;
- ThumbnailLength: number;
- };
- exif: {
- ExposureTime: number;
- FNumber: number;
- ExposureProgram: number;
- ISO: number;
- ExifVersion: string;
- DateTimeOriginal: string;
- CreateDate: string;
- ShutterSpeedValue: number;
- ApertureValue: number;
- ExposureCompensation: number;
- MeteringMode: number;
- Flash: number;
- FocalLength: number;
- SubSecTime: string;
- SubSecTimeOriginal: string;
- SubSecTimeDigitized: string;
- FlashpixVersion: string;
- ColorSpace: number;
- ExifImageWidth: number;
- ExifImageHeight: number;
- InteropOffset: number;
- FocalPlaneXResolution: number;
- FocalPlaneYResolution: number;
- FocalPlaneResolutionUnit: number;
- CustomRendered: number;
- ExposureMode: number;
- WhiteBalance: number;
- SceneCaptureType: number;
- };
- gps: {
- GPSVersionID: number[];
- };
- interoperability: {
- InteropIndex: string;
- InteropVersion: string;
- };
- makernote: { [key: string]: string };
- };
-}
diff --git a/libs/interfaces/FileType.ts b/libs/interfaces/FileType.ts
deleted file mode 100644
index f6b6cb70..00000000
--- a/libs/interfaces/FileType.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-/**
- * Type of files to include in result set. Accepts three values:
- * all - include all types of files in result set
- * image - only search in image type files
- * non-image - only search in files which are not image, e.g., JS or CSS or video files.
- *
- * @see {@link https://docs.imagekit.io/api-reference/media-api/list-and-search-files}
- */
-export type FileType = "all" | "image" | "non-image";
diff --git a/libs/interfaces/FileVersion.ts b/libs/interfaces/FileVersion.ts
deleted file mode 100644
index b2c489e1..00000000
--- a/libs/interfaces/FileVersion.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-export interface DeleteFileVersionOptions {
- /**
- * The unique fileId of the uploaded file. fileId is returned in list files API and upload API.
- */
- fileId: string;
- /**
- * The unique versionId of the uploaded file's version. This is returned in list files API and upload API as id within the versionInfo parameter.
- */
- versionId: string;
-}
-
-export interface RestoreFileVersionOptions {
- /**
- * The unique fileId of the uploaded file. fileId is returned in list files API and upload API.
- */
- fileId: string;
- /**
- * The unique versionId of the uploaded file's version. This is returned in list files API and upload API as id within the versionInfo parameter.
- */
- versionId: string;
-}
\ No newline at end of file
diff --git a/libs/interfaces/IKCallback.ts b/libs/interfaces/IKCallback.ts
deleted file mode 100644
index b33ae426..00000000
--- a/libs/interfaces/IKCallback.ts
+++ /dev/null
@@ -1,4 +0,0 @@
-export interface IKCallback {
- (err: E | null, response: T): void;
- (err: E, response: T | null): void;
-}
diff --git a/libs/interfaces/IKResponse.ts b/libs/interfaces/IKResponse.ts
deleted file mode 100644
index a53ca4fb..00000000
--- a/libs/interfaces/IKResponse.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-interface ResponseMetadata {
- statusCode: number;
- headers: Record;
-}
-
-type IKResponse = T extends Error
- ? T & { $ResponseMetadata?: ResponseMetadata }
- : T & { $ResponseMetadata: ResponseMetadata };
-
-export default IKResponse;
diff --git a/libs/interfaces/ImageKitOptions.ts b/libs/interfaces/ImageKitOptions.ts
deleted file mode 100644
index 122a4de2..00000000
--- a/libs/interfaces/ImageKitOptions.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-import { TransformationPosition } from ".";
-
-export interface ImageKitOptions {
- uploadEndpoint?: string,
- publicKey: string;
- privateKey: string;
- urlEndpoint: string;
- transformationPosition?: TransformationPosition;
-}
diff --git a/libs/interfaces/ListFile.ts b/libs/interfaces/ListFile.ts
deleted file mode 100644
index bba9321d..00000000
--- a/libs/interfaces/ListFile.ts
+++ /dev/null
@@ -1,79 +0,0 @@
-import { FileObject, FolderObject } from "./FileDetails";
-import { FileType } from "./FileType";
-
-/**
- * List and search files options
- *
- * @see {@link https://docs.imagekit.io/api-reference/media-api/list-and-search-files}
- */
-
-export interface ListFileOptions {
- /**
- * Folder path if you want to limit the search within a specific folder. For example, /sales-banner/ will only search in folder sales-banner.
- */
- path?: string;
- /**
- * Type of files to include in result set. Accepts three values:
- * all - include all types of files in result set
- * image - only search in image type files
- * non-image - only search in files which are not image, e.g., JS or CSS or video files.
- */
- fileType?: FileType;
- /**
- * Comma-separated list of tags. Files matching any of the tags are included in result response. If no tag is matched, the file is not included in result set.
- */
- tags?: string | string[];
- /**
- * Whether to include folders in search results or not. By default only files are searched.
- * Accepts true and false. If this is set to true then tags and fileType parameters are ignored.
- */
- includeFolder?: boolean;
- /**
- * The name of the file or folder.
- */
- name?: string;
- /**
- * The maximum number of results to return in response:
- * Minimum value - 1
- * Maximum value - 1000
- * Default value - 1000
- */
- limit?: number;
- /**
- * The number of results to skip before returning results.
- * Minimum value - 0
- * Default value - 0
- */
- skip?: number;
- /**
- * You can sort based on the following fields:
- * - name - ASC_NAME or DESC_NAME
- * - createdAt - ASC_CREATED or DESC_CREATED
- * - updatedAt - ASC_UPDATED or DESC_UPDATED
- * - height - ASC_HEIGHT or DESC_HEIGHT
- * - width - ASC_WIDTH or DESC_WIDTH
- * - size - ASC_SIZE or DESC_SIZE
- */
- sort?: string;
- /**
- * Limit search to either file or folder. Pass all to include both files and folders in search results.
- * Default value - `file`
- */
- type?: string;
- /**
- * Query string in a Lucene-like query language. Learn more about the query expression later in this section.
- * Note: When the searchQuery parameter is present, the following query parameters will have no effect on the result:
- * 1. tags
- * 2. type
- * 3. name
- */
- searchQuery?: string;
-}
-
-/**
- *
- * List and search response
- *
- * @see {@link https://docs.imagekit.io/api-reference/media-api/list-and-search-files#response-structure-and-status-code-application-json}
- */
-export type ListFileResponse = Array;
diff --git a/libs/interfaces/MoveFile.ts b/libs/interfaces/MoveFile.ts
deleted file mode 100644
index 1a26a162..00000000
--- a/libs/interfaces/MoveFile.ts
+++ /dev/null
@@ -1,15 +0,0 @@
-/**
- * Move file API options
- *
- * @see {@link https://docs.imagekit.io/api-reference/media-api/move-file}
- */
-export interface MoveFileOptions {
- /**
- * The full path of the file you want to move. For example - /path/to/file.jpg
- */
- sourceFilePath: string;
- /**
- * Full path to the folder you want to move the above file into. For example - /folder/to/move/into/
- */
- destinationPath: string;
-}
\ No newline at end of file
diff --git a/libs/interfaces/MoveFolder.ts b/libs/interfaces/MoveFolder.ts
deleted file mode 100644
index 2361a6ed..00000000
--- a/libs/interfaces/MoveFolder.ts
+++ /dev/null
@@ -1,40 +0,0 @@
-/**
- * Response when moving folder in media library.
- *
- * @see {@link https://docs.imagekit.io/api-reference/media-api/move-folder}
- *
- * On success, you will receive a jobId which can be used to get the move operation's status.
- */
-export interface MoveFolderResponse {
- jobId: string;
-}
-
-/**
- * Error when moving folder in media library.
- *
- * @see {@link https://docs.imagekit.io/api-reference/media-api/move-folder}
- *
- * If no files or folders are found at specified sourceFolderPath then a error is returned.
- */
-export interface MoveFolderError extends Error {
- help: string;
- message: string;
- reason: string;
-}
-
-
-/**
- * Move folder API options
- *
- * @see {@link https://docs.imagekit.io/api-reference/media-api/move-folder}
- */
-export interface MoveFolderOptions {
- /**
- * The full path to the source folder you want to move. For example - /path/of/source/folder.
- */
- sourceFolderPath: string;
- /**
- * Full path to the destination folder where you want to move the source folder into. For example - /path/of/destination/folder.
- */
- destinationPath: string;
-}
\ No newline at end of file
diff --git a/libs/interfaces/PurgeCache.ts b/libs/interfaces/PurgeCache.ts
deleted file mode 100644
index c7b0e386..00000000
--- a/libs/interfaces/PurgeCache.ts
+++ /dev/null
@@ -1,27 +0,0 @@
-/**
- * Response when purging CDN and ImageKit.io internal cache
- *
- * @see {@link https://docs.imagekit.io/api-reference/media-api/purge-cache#response-structure-and-status-code}
- */
-
-export interface PurgeCacheResponse {
- /**
- * requestId can be used to fetch the status of submitted purge request.
- */
- requestId: string;
-}
-
-/**
- * Response when getting the status of submitted purge request.
- *
- * @see {@link https://docs.imagekit.io/api-reference/media-api/purge-cache-status#understanding-response}
- */
-
-export interface PurgeCacheStatusResponse {
- /**
- * Pending - The request has been successfully submitted, and purging is in progress.
- * Complete - The purge request has been successfully completed. And now you should get a fresh object.
- * Check the Age header in response to confirm this.
- */
- status: "Pending" | "Completed";
-}
diff --git a/libs/interfaces/Rename.ts b/libs/interfaces/Rename.ts
deleted file mode 100644
index 98b338df..00000000
--- a/libs/interfaces/Rename.ts
+++ /dev/null
@@ -1,33 +0,0 @@
-/**
- * Response when rename file
- *
- * @see {@link https://docs.imagekit.io/api-reference/media-api/rename-file}
- */
-export interface RenameFileResponse {
- /**
- * When purgeCache is set to true
- */
- purgeRequestId?: string;
-}
-
-/**
- * Response when rename file
- *
- * @see {@link https://docs.imagekit.io/api-reference/media-api/rename-file}
- */
-export interface RenameFileOptions {
- /**
- * The full path of the file you want to rename. For example - /path/to/file.jpg
- */
- filePath: string;
- /**
- * The new name of the file. A filename can contain:
- - Alphanumeric Characters: a-z, A-Z, 0-9 (including Unicode letters, marks, and numerals in other languages).
- - Special Characters: ., _, and -. Any other character, including space, will be replaced by _.
- */
- newFileName: string
- /**
- * Option to purge cache for the old file URL. When set to true, it will internally issue a purge cache request on CDN to remove cached content on the old URL.
- */
- purgeCache: boolean
-}
diff --git a/libs/interfaces/Transformation.ts b/libs/interfaces/Transformation.ts
deleted file mode 100644
index a2990f66..00000000
--- a/libs/interfaces/Transformation.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-import { SupportedTransformsParam } from "../constants/supportedTransforms";
-
-export type TransformationPosition = "path" | "query";
-
-export type Transformation = Partial<
- | {
- [key in SupportedTransformsParam]: string | boolean | number;
- }
- | { [key: string]: string | boolean | number }
->;
\ No newline at end of file
diff --git a/libs/interfaces/UploadOptions.ts b/libs/interfaces/UploadOptions.ts
deleted file mode 100644
index 47389b21..00000000
--- a/libs/interfaces/UploadOptions.ts
+++ /dev/null
@@ -1,121 +0,0 @@
-import { ReadStream } from "fs";
-import { Extension } from "./FileDetails";
-
-interface TransformationObject {
- type: "transformation";
- value: string;
-}
-interface GifToVideoOrThumbnailObject {
- type: "gif-to-video" | "thumbnail";
- value?: string;
-}
-
-interface AbsObject {
- type: "abs";
- value: string;
- protocol: "hls" | "dash";
-}
-
-type PostTransformation = TransformationObject | GifToVideoOrThumbnailObject | AbsObject;
-
-interface Transformation{
- pre?: string
- post?: PostTransformation[]
-}
-
-/**
- * Options used when uploading a file
- *
- * @see {@link https://docs.imagekit.io/api-reference/upload-file-api/server-side-file-upload#request-structure-multipart-form-data}
- */
-export interface UploadOptions {
- /**
- * This field accepts three kinds of values:
- * - binary - You can send the content of the file as binary. This is used when a file is being uploaded from the browser.
- * - base64 - Base64 encoded string of file content.
- * - url - URL of the file from where to download the content before uploading.
- * Downloading file from URL might take longer, so it is recommended that you pass the binary or base64 content of the file.
- * Pass the full URL, for example - https://www.example.com/rest-of-the-image-path.jpg.
- */
- file: string | Buffer | ReadStream;
- /**
- * The name with which the file has to be uploaded.
- * The file name can contain:
- * - Alphanumeric Characters: a-z , A-Z , 0-9
- * - Special Characters: . _ and -
- * Any other character including space will be replaced by _
- */
- fileName: string;
- /**
- * Whether to use a unique filename for this file or not.
- * - Accepts true or false.
- * - If set true, ImageKit.io will add a unique suffix to the filename parameter to get a unique filename.
- * - If set false, then the image is uploaded with the provided filename parameter and any existing file with the same name is replaced.
- * Default value - true
- */
- useUniqueFileName?: boolean;
- /**
- * Set the tags while uploading the file.
- * - Comma-separated value of tags in format tag1,tag2,tag3. For example - t-shirt,round-neck,men
- * - The maximum length of all characters should not exceed 500.
- * - % is not allowed.
- * - If this field is not specified and the file is overwritten then the tags will be removed.
- */
- tags?: string | string[];
- /**
- * The folder path (e.g. /images/folder/) in which the image has to be uploaded. If the folder(s) didn't exist before, a new folder(s) is created.
- * The folder name can contain:
- * - Alphanumeric Characters: a-z , A-Z , 0-9
- * - Special Characters: / _ and -
- * - Using multiple / creates a nested folder.
- * Default value - /
- */
- folder?: string;
- /**
- * Whether to mark the file as private or not. This is only relevant for image type files.
- * - Accepts true or false.
- * - If set true, the file is marked as private which restricts access to the original image URL and unnamed image transformations without signed URLs.
- * Without the signed URL, only named transformations work on private images
- * Default value - false
- */
- isPrivateFile?: boolean;
- /**
- * Define an important area in the image. This is only relevant for image type files.
- * To be passed as a string with the x and y coordinates of the top-left corner, and width and height of the area of interest in format x,y,width,height. For example - 10,10,100,100
- * Can be used with fo-customtransformation.
- * If this field is not specified and the file is overwritten, then customCoordinates will be removed.
- */
- customCoordinates?: string;
- /**
- * Comma-separated values of the fields that you want ImageKit.io to return in response.
- *
- * For example, set the value of this field to tags,customCoordinates,isPrivateFile,metadata to get value of tags, customCoordinates, isPrivateFile , and metadata in the response.
- */
- responseFields?: string | string[];
- /*
- * Object with array of extensions to be processed on the image.
- */
- extensions?: Extension;
- /*
- * Final status of pending extensions will be sent to this URL.
- */
- webhookUrl?: string;
- overwriteFile?: boolean;
- overwriteAITags?: boolean;
- overwriteTags?: boolean;
- overwriteCustomMetadata?: boolean;
- customMetadata?: {
- [key: string]: string | number | boolean | Array;
- },
- transformation?: Transformation
- /**
- * Optional `checks` parameters can be used to run server-side checks before files are uploaded to the Media Library.
- */
- checks?: string
- /**
- * Optional. Determines whether the file should be uploaded as published.
- * If set to false, the file will be marked as unpublished, restricting access to the file through the media library only.
- * Files in draft or unpublished states can only be publicly accessed after they are published.
- */
- isPublished?: boolean
-}
diff --git a/libs/interfaces/UploadResponse.ts b/libs/interfaces/UploadResponse.ts
deleted file mode 100644
index 9ca44376..00000000
--- a/libs/interfaces/UploadResponse.ts
+++ /dev/null
@@ -1,83 +0,0 @@
-import { AITagItem, CMValues, EmbeddedMetadataValues } from "./FileDetails";
-import { FileMetadataResponse } from "./FileMetadata";
-import { FileType } from "./FileType";
-
-/**
- * Response from uploading a file
- *
- * @see {@link https://docs.imagekit.io/api-reference/upload-file-api/server-side-file-upload#response-code-and-structure-json}
- */
-export interface UploadResponse {
- /**
- * Unique fileId. Store this fileld in your database, as this will be used to perform update action on this file.
- */
- fileId: string;
- /**
- * The name of the uploaded file.
- */
- name: string;
- /**
- * The URL of the file.
- */
- url: string;
- /**
- * In case of an image, a small thumbnail URL.
- */
- thumbnailUrl: string;
- /**
- * Height of the uploaded image file. Only applicable when file type is image.
- */
- height: number;
- /**
- * Width of the uploaded image file. Only applicable when file type is image.
- */
- width: number;
- /**
- * Size of the uploaded file in bytes.
- */
- size: number;
- /**
- * Type of file. It can either be image or non-image.
- */
- fileType: FileType;
- /**
- * The path of the file uploaded. It includes any folder that you specified while uploading.
- */
- filePath: string;
- /**
- * Array of tags associated with the image.
- */
- tags?: string[];
- /**
- * Is the file marked as private. It can be either true or false.
- */
- isPrivateFile: boolean;
- /**
- * Value of custom coordinates associated with the image in format x,y,width,height.
- */
- customCoordinates: string | null;
- /**
- * The metadata of the upload file. Use responseFields property in request to get the metadata returned in response of upload API.
- */
- metadata?: FileMetadataResponse;
- /*
- * AITags field is populated only because the google-auto-tagging extension was executed synchronously and it received a successresponse.
- */
- AITags?: AITagItem[];
- /*
- * Field object which will contain the status of each extension at the time of completion of the update/upload request.
- */
- extensionStatus?: { [key: string]: string }
- /*
- * Consolidated embedded metadata associated with the file. It includes exif, iptc, and xmp data.
- */
- embeddedMetadata?: EmbeddedMetadataValues | null;
- /*
- * A key-value data associated with the asset. Before setting any custom metadata on an asset, you have to create the field using custom metadata fields API.
- */
- customMetadata?: CMValues;
- /**
- * Is the file published or in draft state. It can be either true or false.
- */
- isPublished?: boolean
-}
diff --git a/libs/interfaces/UrlOptions.ts b/libs/interfaces/UrlOptions.ts
deleted file mode 100644
index d3dc6ac7..00000000
--- a/libs/interfaces/UrlOptions.ts
+++ /dev/null
@@ -1,65 +0,0 @@
-import { TransformationPosition } from ".";
-import { Transformation } from "./Transformation";
-
-export interface UrlOptionsBase {
- /**
- * An array of objects specifying the transformations to be applied in the URL.
- * The transformation name and the value should be specified as a key-value pair in each object.
- * @see {@link https://docs.imagekit.io/features/image-transformations/chained-transformations}
- */
- transformation?: Array;
- /**
- * Default value is path that places the transformation string as a path parameter in the URL.
- * Can also be specified as query which adds the transformation string as the query parameter tr in the URL.
- * If you use src parameter to create the URL, then the transformation string is always added as a query parameter.
- */
- transformationPosition?: TransformationPosition;
- /**
- * These are the other query parameters that you want to add to the final URL.
- * These can be any query parameters and not necessarily related to ImageKit.
- * Especially useful, if you want to add some versioning parameter to your URLs.
- */
- queryParameters?: { [key: string]: string };
- /**
- * The base URL to be appended before the path of the image.
- * If not specified, the URL Endpoint specified at the time of SDK initialization is used.
- */
- urlEndpoint?: string;
- /**
- * Default is false. If set to true, the SDK generates a signed image URL adding the image signature to the image URL.
- * If you are creating URL using src parameter instead of path then do correct urlEndpoint for this to work.
- * Otherwise returned URL will have wrong signature.
- */
- signed?: boolean;
- /**
- * Meant to be used along with the signed parameter to specify the time in seconds from now when the URL should expire.
- * If specified, the URL contains the expiry timestamp in the URL and the image signature is modified accordingly.
- */
- expireSeconds?: number;
-}
-
-export interface UrlOptionsSrc extends UrlOptionsBase {
- /**
- * Conditional. This is the complete URL of an image already mapped to ImageKit.
- * For example, https://ik.imagekit.io/your_imagekit_id/endpoint/path/to/image.jpg.
- * Either the path or src parameter need to be specified for URL generation.
- */
- src: string;
- path?: never;
-}
-
-export interface UrlOptionsPath extends UrlOptionsBase {
- /**
- * Conditional. This is the path at which the image exists.
- * For example, /path/to/image.jpg. Either the path or src parameter need to be specified for URL generation.
- */
- path: string;
- src?: never;
-}
-
-/**
- * Options for generating an URL
- *
- * @see {@link https://github.com/imagekit-developer/imagekit-nodejs#url-generation}
- */
-export type UrlOptions = UrlOptionsSrc | UrlOptionsPath;
diff --git a/libs/interfaces/index.ts b/libs/interfaces/index.ts
deleted file mode 100644
index 538a897d..00000000
--- a/libs/interfaces/index.ts
+++ /dev/null
@@ -1,79 +0,0 @@
-import { ImageKitOptions } from "./ImageKitOptions";
-import { Transformation, TransformationPosition } from "./Transformation";
-import { UploadOptions } from "./UploadOptions";
-import { UploadResponse } from "./UploadResponse";
-import { FileType } from "./FileType";
-import { UrlOptions } from "./UrlOptions";
-import { ListFileOptions, ListFileResponse } from "./ListFile";
-import { CopyFileOptions } from "./CopyFile";
-import { MoveFileOptions } from "./MoveFile";
-import { CreateFolderOptions } from "./CreateFolder";
-import { FileDetailsOptions, FileVersionDetailsOptions, FileObject, FolderObject } from "./FileDetails";
-import { FileMetadataResponse } from "./FileMetadata";
-import { PurgeCacheResponse, PurgeCacheStatusResponse } from "./PurgeCache";
-import { BulkDeleteFilesResponse, BulkDeleteFilesError } from "./BulkDeleteFiles";
-import { CopyFolderOptions, CopyFolderResponse, CopyFolderError } from "./CopyFolder";
-import { MoveFolderOptions, MoveFolderResponse, MoveFolderError } from "./MoveFolder";
-import { DeleteFileVersionOptions, RestoreFileVersionOptions } from "./FileVersion"
-import { CreateCustomMetadataFieldOptions, CustomMetadataField, UpdateCustomMetadataFieldOptions, GetCustomMetadataFieldsOptions } from "./CustomMetatadaField"
-import { RenameFileOptions, RenameFileResponse } from "./Rename"
-import {
- WebhookEvent,
- WebhookEventVideoTransformationAccepted,
- WebhookEventVideoTransformationReady,
- WebhookEventVideoTransformationError,
- WebhookEventUploadPreTransformationSuccess,
- WebhookEventUploadPreTransformationError,
- WebhookEventUploadPostTransformationSuccess,
- WebhookEventUploadPostTransformationError
-} from "./webhookEvent";
-
-type FinalUrlOptions = ImageKitOptions & UrlOptions; // actual options used to construct url
-
-export type {
- ImageKitOptions,
- Transformation,
- TransformationPosition,
- UploadOptions,
- UploadResponse,
- FileType,
- UrlOptions,
- FinalUrlOptions,
- ListFileOptions,
- ListFileResponse,
- FileDetailsOptions,
- FileVersionDetailsOptions,
- FileObject,
- FolderObject,
- FileMetadataResponse,
- PurgeCacheResponse,
- PurgeCacheStatusResponse,
- BulkDeleteFilesResponse,
- BulkDeleteFilesError,
- CopyFolderResponse,
- CopyFolderError,
- MoveFolderResponse,
- MoveFolderError,
- CopyFileOptions,
- MoveFileOptions,
- CreateFolderOptions,
- CopyFolderOptions,
- MoveFolderOptions,
- DeleteFileVersionOptions,
- RestoreFileVersionOptions,
- CreateCustomMetadataFieldOptions,
- GetCustomMetadataFieldsOptions,
- CustomMetadataField,
- UpdateCustomMetadataFieldOptions,
- RenameFileOptions,
- RenameFileResponse,
- WebhookEvent,
- WebhookEventVideoTransformationAccepted,
- WebhookEventVideoTransformationReady,
- WebhookEventVideoTransformationError,
- WebhookEventUploadPostTransformationSuccess,
- WebhookEventUploadPostTransformationError,
- WebhookEventUploadPreTransformationSuccess,
- WebhookEventUploadPreTransformationError
-};
-export type { IKCallback } from "./IKCallback";
diff --git a/libs/interfaces/webhookEvent.ts b/libs/interfaces/webhookEvent.ts
deleted file mode 100644
index 194afdcd..00000000
--- a/libs/interfaces/webhookEvent.ts
+++ /dev/null
@@ -1,153 +0,0 @@
-import { UploadResponse } from "./UploadResponse";
-
-type Asset = {
- url: string;
-};
-
-type TransformationOptions = {
- video_codec: string;
- audio_codec: string;
- auto_rotate: boolean;
- quality: number;
- format: string;
-};
-
-interface WebhookEventBase {
- type: string;
- id: string;
- created_at: string; // Date
-}
-
-/** WebhookEvent for "video.transformation.*" type */
-interface WebhookEventVideoTransformationBase extends WebhookEventBase {
- request: {
- x_request_id: string;
- url: string;
- user_agent: string;
- };
-}
-
-export interface WebhookEventVideoTransformationAccepted extends WebhookEventVideoTransformationBase {
- type: "video.transformation.accepted";
- data: {
- asset: Asset;
- transformation: {
- type: string;
- options: TransformationOptions;
- };
- };
-}
-
-export interface WebhookEventVideoTransformationReady extends WebhookEventVideoTransformationBase {
- type: "video.transformation.ready";
- timings: {
- donwload_duration: number;
- encoding_duration: number;
- };
- data: {
- asset: Asset;
- transformation: {
- type: string;
- options: TransformationOptions;
- output: {
- url: string;
- video_metadata: {
- duration: number;
- width: number;
- height: number;
- bitrate: number;
- };
- };
- };
- };
-}
-
-export interface WebhookEventVideoTransformationError extends WebhookEventVideoTransformationBase {
- type: "video.transformation.error";
- data: {
- asset: Asset;
- transformation: {
- type: string;
- options: TransformationOptions;
- error: {
- reason: string;
- };
- };
- };
-}
-
-type TransformationType = "transformation" | "abs" | "gif-to-video" | "thumbnail";
-
-interface PreTransformationBase {
- id: string;
- created_at: string;
- request: {
- x_request_id: string;
- transformation: string;
- };
-}
-
-interface PostTransformationBase {
- id: string;
- created_at: string;
- request: {
- x_request_id: string;
- transformation: {
- type: TransformationType;
- value?: string;
- protocol?: 'hls' | 'dash';
- };
- };
-}
-
-export interface WebhookEventUploadPreTransformationSuccess extends PreTransformationBase {
- type: "upload.pre-transform.success";
- data: UploadResponse;
-}
-
-export interface WebhookEventUploadPreTransformationError extends PostTransformationBase {
- type: "upload.pre-transform.error";
- data: {
- name: string;
- path: string;
- transformation: {
- error: {
- reason: string;
- };
- };
- };
-}
-
-export interface WebhookEventUploadPostTransformationSuccess extends PostTransformationBase {
- type: "upload.post-transform.success";
- data: {
- fileId: string;
- url: string;
- name: string;
- };
-}
-
-export interface WebhookEventUploadPostTransformationError extends PostTransformationBase {
- type: "upload.post-transform.error";
- data: {
- fileId: string;
- url: string;
- name: string;
- path: string;
- transformation: {
- error: {
- reason: string;
- };
- };
- };
-}
-
-export type WebhookEvent =
- | WebhookEventVideoTransformationAccepted
- | WebhookEventVideoTransformationReady
- | WebhookEventVideoTransformationError
- | WebhookEventUploadPreTransformationSuccess
- | WebhookEventUploadPreTransformationError
- | WebhookEventUploadPostTransformationSuccess
- | WebhookEventUploadPostTransformationError
- | Object;
diff --git a/libs/manage/cache.ts b/libs/manage/cache.ts
deleted file mode 100644
index a3bb4ef7..00000000
--- a/libs/manage/cache.ts
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- Constants
-*/
-import errorMessages from "../constants/errorMessages";
-
-/*
- Utils
-*/
-import respond from "../../utils/respond";
-import request from "../../utils/request";
-
-/*
- Interfaces
-*/
-import { IKCallback } from "../interfaces/IKCallback";
-import { ImageKitOptions, PurgeCacheResponse, PurgeCacheStatusResponse } from "../interfaces";
-
-const purgeCache = function (url: string, defaultOptions: ImageKitOptions, callback?: IKCallback) {
- if (!url && !url.length) {
- respond(true, errorMessages.CACHE_PURGE_URL_MISSING, callback);
- return;
- }
-
- var requestOptions = {
- url: "https://api.imagekit.io/v1/files/purge",
- method: "POST",
- json: {
- url: url,
- },
- };
-
- request(requestOptions, defaultOptions, callback);
-};
-
-const getPurgeCacheStatus = function (
- requestId: string,
- defaultOptions: ImageKitOptions,
- callback?: IKCallback,
-) {
- if (!requestId && !requestId.length) {
- respond(true, errorMessages.CACHE_PURGE_STATUS_ID_MISSING, callback);
- return;
- }
-
- var requestOptions = {
- url: "https://api.imagekit.io/v1/files/purge/" + requestId,
- method: "GET",
- };
-
- request(requestOptions, defaultOptions, callback);
-};
-
-export default { purgeCache, getPurgeCacheStatus };
diff --git a/libs/manage/custom-metadata-field.ts b/libs/manage/custom-metadata-field.ts
deleted file mode 100644
index 752ab080..00000000
--- a/libs/manage/custom-metadata-field.ts
+++ /dev/null
@@ -1,116 +0,0 @@
-/*
- Constants
-*/
-import errorMessages from "../constants/errorMessages";
-
-/*
- Utils
-*/
-import respond from "../../utils/respond";
-import request from "../../utils/request";
-
-/*
- Interfaces
-*/
-import { IKCallback } from "../interfaces/IKCallback";
-import {
- ImageKitOptions,
- CreateCustomMetadataFieldOptions,
- CustomMetadataField,
- UpdateCustomMetadataFieldOptions,
- GetCustomMetadataFieldsOptions,
-} from "../interfaces";
-
-const create = function (createCustomMetadataFieldOptions: CreateCustomMetadataFieldOptions, defaultOptions: ImageKitOptions, callback?: IKCallback) {
- const { name, label, schema } = createCustomMetadataFieldOptions;
- if (!name || !name.length) {
- respond(true, errorMessages.CMF_NAME_MISSING, callback);
- return;
- }
-
- if (!label || !label.length) {
- respond(true, errorMessages.CMF_LABEL_MISSING, callback);
- return;
- }
-
- if (!schema) {
- respond(true, errorMessages.CMF_SCHEMA_MISSING, callback);
- return;
- }
-
- if (!schema.type) {
- respond(true, errorMessages.CMF_SCHEMA_INVALID, callback);
- return;
- }
-
- var requestOptions = {
- url: "https://api.imagekit.io/v1/customMetadataFields",
- method: "POST",
- json: {
- name,
- label,
- schema
- },
- };
-
- request(requestOptions, defaultOptions, callback);
-};
-
-const list = function (
- getCustomMetadataFieldsOptions: GetCustomMetadataFieldsOptions,
- defaultOptions: ImageKitOptions,
- callback?: IKCallback,
-) {
- const { includeDeleted = false } = getCustomMetadataFieldsOptions || {};
- var requestOptions = {
- url: "https://api.imagekit.io/v1/customMetadataFields",
- method: "GET",
- qs: { includeDeleted }
- };
-
- request(requestOptions, defaultOptions, callback);
-};
-
-const update = function (fieldId: string, updateCustomMetadataFieldOptions: UpdateCustomMetadataFieldOptions, defaultOptions: ImageKitOptions, callback?: IKCallback) {
- if (!fieldId || typeof fieldId !== "string" || !fieldId.length) {
- respond(true, errorMessages.CMF_FIELD_ID_MISSING, callback);
- return;
- }
-
- const { label, schema } = updateCustomMetadataFieldOptions;
- if (!label && !schema) {
- respond(true, errorMessages.CMF_LABEL_SCHEMA_MISSING, callback);
- return;
- }
-
- var requestBody: UpdateCustomMetadataFieldOptions = {};
- if (label) requestBody.label = label;
- if (schema) requestBody.schema = schema;
-
- var requestOptions = {
- url: `https://api.imagekit.io/v1/customMetadataFields/${fieldId}`,
- method: "PATCH",
- json: requestBody
- };
-
- request(requestOptions, defaultOptions, callback);
-};
-
-const deleteField = function (
- fieldId: string,
- defaultOptions: ImageKitOptions,
- callback?: IKCallback,
-) {
- if (!fieldId || typeof fieldId !== "string" || !fieldId.length) {
- respond(true, errorMessages.CMF_FIELD_ID_MISSING, callback);
- return;
- }
- var requestOptions = {
- url: `https://api.imagekit.io/v1/customMetadataFields/${fieldId}`,
- method: "DELETE",
- };
-
- request(requestOptions, defaultOptions, callback);
-};
-
-export default { create, list, update, deleteField };
diff --git a/libs/manage/file.ts b/libs/manage/file.ts
deleted file mode 100644
index 5ee18da7..00000000
--- a/libs/manage/file.ts
+++ /dev/null
@@ -1,699 +0,0 @@
-import { isObject } from 'lodash';
-
-/*
- Constants
-*/
-import errorMessages from "../constants/errorMessages";
-
-/*
- Utils
-*/
-import respond from "../../utils/respond";
-import request from "../../utils/request";
-
-/*
- Interfaces
-*/
-import { IKCallback } from "../interfaces/IKCallback";
-import {
- ImageKitOptions,
- ListFileOptions,
- ListFileResponse,
- FileDetailsOptions,
- FileVersionDetailsOptions,
- FileObject,
- FileMetadataResponse,
- BulkDeleteFilesResponse,
- BulkDeleteFilesError,
- CopyFileOptions,
- CopyFolderResponse,
- MoveFileOptions,
- CreateFolderOptions,
- CopyFolderOptions,
- MoveFolderOptions,
- DeleteFileVersionOptions,
- RestoreFileVersionOptions,
- RenameFileOptions,
- RenameFileResponse,
-} from "../interfaces";
-import ImageKit from "../..";
-
-/*
- Delete a file
-*/
-const deleteFile = function (fileId: string, defaultOptions: ImageKitOptions, callback?: IKCallback) {
- if (!fileId) {
- respond(true, errorMessages.FILE_ID_MISSING, callback);
- return;
- }
-
- var requestOptions = {
- url: "https://api.imagekit.io/v1/files/" + fileId,
- method: "DELETE"
- };
-
- request(requestOptions, defaultOptions, callback);
-};
-
-
-/*
- Delete a file version
-*/
-const deleteFileVersion = function (deleteFileVersionOptions: DeleteFileVersionOptions, defaultOptions: ImageKitOptions, callback?: IKCallback) {
- const { fileId, versionId } = deleteFileVersionOptions || {};
- if (!fileId) {
- respond(true, errorMessages.FILE_ID_MISSING, callback);
- return;
- }
-
- if (!versionId) {
- respond(true, errorMessages.FILE_VERSION_ID_MISSING, callback);
- return;
- }
-
- var requestOptions = {
- url: `https://api.imagekit.io/v1/files/${fileId}/versions/${versionId}`,
- method: "DELETE"
- };
-
- request(requestOptions, defaultOptions, callback);
-};
-
-
-/*
- Restore a file version as the current version
-*/
-const restoreFileVersion = function (
- restoreFileVersionOptions: RestoreFileVersionOptions,
- defaultOptions: ImageKitOptions,
- callback?: IKCallback) {
- const { fileId, versionId } = restoreFileVersionOptions || {};
- if (!fileId) {
- respond(true, errorMessages.FILE_ID_MISSING, callback);
- return;
- }
-
- if (!versionId) {
- respond(true, errorMessages.FILE_VERSION_ID_MISSING, callback);
- return;
- }
-
- var requestOptions = {
- url: `https://api.imagekit.io/v1/files/${fileId}/versions/${versionId}/restore`,
- method: "PUT"
- };
-
- request(requestOptions, defaultOptions, callback);
-};
-
-/*
- Get Metadata of a file
-*/
-const getMetadata = function (
- fileIdOrURL: string,
- defaultOptions: ImageKitOptions,
- callback?: IKCallback,
-) {
- if (!fileIdOrURL || fileIdOrURL.trim() == "") {
- respond(true, errorMessages.FILE_ID_OR_URL_MISSING, callback);
- return;
- }
-
- var requestOptions = {
- url: "https://api.imagekit.io/v1/files/" + fileIdOrURL + "/metadata",
- method: "GET"
- };
-
- // In case of URL change the endopint
- if (fileIdOrURL.indexOf("http") === 0) {
- requestOptions = {
- url: `https://api.imagekit.io/v1/metadata?url=${fileIdOrURL}`,
- method: "GET"
- };
- }
-
- request(requestOptions, defaultOptions, callback);
-};
-
-/*
- Get Details of a file
-*/
-const getDetails = function (
- fileId: string,
- defaultOptions: ImageKitOptions,
- callback?: IKCallback,
-) {
- if (!fileId) {
- respond(true, errorMessages.FILE_ID_MISSING, callback);
- return;
- }
-
- var requestOptions = {
- url: "https://api.imagekit.io/v1/files/" + fileId + "/details",
- method: "GET"
- };
-
- request(requestOptions, defaultOptions, callback);
-};
-
-
-/*
- Get Details of a file version
-*/
-const getFileVersionDetails = function (
- fileDetailsOptions: FileVersionDetailsOptions,
- defaultOptions: ImageKitOptions,
- callback?: IKCallback,
-) {
- const { fileId, versionId } = fileDetailsOptions || {};
- if (!fileId) {
- respond(true, errorMessages.FILE_ID_MISSING, callback);
- return;
- }
-
- if (!versionId) {
- respond(true, errorMessages.FILE_VERSION_ID_MISSING, callback);
- return;
- }
-
- var requestOptions = {
- url: `https://api.imagekit.io/v1/files/${fileId}/versions/${versionId}`,
- method: "GET"
- };
-
- request(requestOptions, defaultOptions, callback);
-};
-
-/*
- Update file details
-*/
-const updateDetails = function (
- fileId: string,
- updateData: FileDetailsOptions,
- defaultOptions: ImageKitOptions,
- callback?: IKCallback,
-) {
- if (!fileId) {
- respond(true, errorMessages.FILE_ID_MISSING, callback);
- return;
- }
-
- if (!isObject(updateData)) {
- respond(true, errorMessages.UPDATE_DATA_MISSING, callback);
- return;
- }
-
- var data = {};
- data = {
- tags: updateData.tags,
- customCoordinates: updateData.customCoordinates,
- extensions: updateData.extensions,
- webhookUrl: updateData.webhookUrl,
- customMetadata: updateData.customMetadata,
- };
-
- if (updateData.publish)
- data = {
- ...data,
- publish: updateData.publish,
- };
-
- var requestOptions = {
- url: "https://api.imagekit.io/v1/files/" + fileId + "/details",
- method: "PATCH",
- json: data,
- };
-
- request(requestOptions, defaultOptions, callback);
-};
-
-/*
- List files
-*/
-const listFiles = function (
- listOptions: ListFileOptions,
- defaultOptions: ImageKitOptions,
- callback?: IKCallback,
-) {
- if (listOptions && !isObject(listOptions)) {
- respond(true, errorMessages.INVALID_LIST_OPTIONS, callback);
- return;
- }
-
- if (listOptions && listOptions.tags && Array.isArray(listOptions.tags) && listOptions.tags.length) {
- listOptions.tags = listOptions.tags.join(",");
- }
-
- var requestOptions = {
- url: `https://api.imagekit.io/v1/files/`,
- method: "GET",
- qs: listOptions || {}
- };
-
- request(requestOptions, defaultOptions, callback);
-};
-
-
-/*
- Get all versions of an asset
-*/
-const getFilesVersions = function (
- fileId: string,
- defaultOptions: ImageKitOptions,
- callback?: IKCallback,
-) {
- if (!fileId) {
- respond(true, errorMessages.FILE_ID_MISSING, callback);
- return;
- }
-
- var requestOptions = {
- url: `https://api.imagekit.io/v1/files/${fileId}/versions`,
- method: "GET"
- };
-
- request(requestOptions, defaultOptions, callback);
-};
-
-/*
- Bulk Delete By FileIds
-*/
-const bulkDeleteFiles = function (
- fileIdArray: string[],
- defaultOptions: ImageKitOptions,
- callback?: IKCallback,
-) {
- if (
- !Array.isArray(fileIdArray) ||
- fileIdArray.length === 0 ||
- fileIdArray.filter((fileId) => typeof fileId !== "string").length > 0
- ) {
- respond(true, errorMessages.INVALID_FILEIDS_VALUE, callback);
- return;
- }
-
- const data = {
- fileIds: fileIdArray,
- };
-
- const requestOptions = {
- url: "https://api.imagekit.io/v1/files/batch/deleteByFileIds",
- method: "POST",
- json: data,
- };
-
- request(requestOptions, defaultOptions, callback);
-};
-
-/*
- Add tags in bulk
-*/
-const bulkAddTags = function (
- fileIdArray: string[],
- tags: string[],
- defaultOptions: ImageKitOptions,
- callback?: IKCallback,
-) {
- if (
- !Array.isArray(fileIdArray) ||
- fileIdArray.length === 0 ||
- fileIdArray.filter((fileId) => typeof fileId !== "string").length > 0
- ) {
- respond(true, errorMessages.INVALID_FILEIDS_VALUE, callback);
- return;
- }
-
- if (!Array.isArray(tags) || tags.length === 0 || tags.filter((tag) => typeof tag !== "string").length > 0) {
- respond(true, errorMessages.BULK_ADD_TAGS_INVALID, callback);
- return;
- }
-
- const data = {
- fileIds: fileIdArray,
- tags: tags,
- };
-
- const requestOptions = {
- url: "https://api.imagekit.io/v1/files/addTags",
- method: "POST",
- json: data,
- };
-
- request(requestOptions, defaultOptions, callback);
-};
-
-/*
- Remove tags in bulk
-*/
-const bulkRemoveTags = function (
- fileIdArray: string[],
- tags: string[],
- defaultOptions: ImageKitOptions,
- callback?: IKCallback,
-) {
- if (
- !Array.isArray(fileIdArray) ||
- fileIdArray.length === 0 ||
- fileIdArray.filter((fileId) => typeof fileId !== "string").length > 0
- ) {
- respond(true, errorMessages.INVALID_FILEIDS_VALUE, callback);
- return;
- }
-
- if (!Array.isArray(tags) || tags.length === 0 || tags.filter((tag) => typeof tag !== "string").length > 0) {
- respond(true, errorMessages.BULK_ADD_TAGS_INVALID, callback);
- return;
- }
-
- const data = {
- fileIds: fileIdArray,
- tags: tags,
- };
-
- const requestOptions = {
- url: "https://api.imagekit.io/v1/files/removeTags",
- method: "POST",
- json: data,
- };
-
- request(requestOptions, defaultOptions, callback);
-};
-
-
-/*
- Remove AI tags in bulk
-*/
-const bulkRemoveAITags = function (
- fileIdArray: string[],
- tags: string[],
- defaultOptions: ImageKitOptions,
- callback?: IKCallback,
-) {
- if (
- !Array.isArray(fileIdArray) ||
- fileIdArray.length === 0 ||
- fileIdArray.filter((fileId) => typeof fileId !== "string").length > 0
- ) {
- respond(true, errorMessages.INVALID_FILEIDS_VALUE, callback);
- return;
- }
-
- if (!Array.isArray(tags) || tags.length === 0 || tags.filter((tag) => typeof tag !== "string").length > 0) {
- respond(true, errorMessages.BULK_ADD_TAGS_INVALID, callback);
- return;
- }
-
- const data = {
- fileIds: fileIdArray,
- AITags: tags,
- };
-
- const requestOptions = {
- url: "https://api.imagekit.io/v1/files/removeAITags",
- method: "POST",
- json: data,
- };
-
- request(requestOptions, defaultOptions, callback);
-};
-
-/*
- Copy file
-*/
-const copyFile = function (
- copyFileOptions: CopyFileOptions,
- defaultOptions: ImageKitOptions,
- callback?: IKCallback,
-) {
- const { sourceFilePath, destinationPath, includeFileVersions = false } = copyFileOptions;
-
- if (typeof sourceFilePath !== "string" || sourceFilePath.length === 0) {
- respond(true, errorMessages.INVALID_SOURCE_FILE_PATH, callback);
- return;
- }
-
- if (typeof destinationPath !== "string" || destinationPath.length === 0) {
- respond(true, errorMessages.INVALID_DESTINATION_FOLDER_PATH, callback);
- return;
- }
-
- if (typeof includeFileVersions !== "boolean") {
- respond(true, errorMessages.INVALID_INCLUDE_VERSION, callback);
- return;
- }
-
- const data = {
- sourceFilePath,
- destinationPath,
- includeFileVersions
- };
-
- const requestOptions = {
- url: "https://api.imagekit.io/v1/files/copy",
- method: "POST",
- json: data,
- };
-
- request(requestOptions, defaultOptions, callback);
-};
-
-/*
- Move file
-*/
-const moveFile = function (
- moveFileOptions: MoveFileOptions,
- defaultOptions: ImageKitOptions,
- callback?: IKCallback,
-) {
- const { sourceFilePath, destinationPath } = moveFileOptions;
- if (typeof sourceFilePath !== "string" || sourceFilePath.length === 0) {
- respond(true, errorMessages.INVALID_SOURCE_FILE_PATH, callback);
- return;
- }
-
- if (typeof destinationPath !== "string" || destinationPath.length === 0) {
- respond(true, errorMessages.INVALID_DESTINATION_FOLDER_PATH, callback);
- return;
- }
-
- const data = {
- sourceFilePath,
- destinationPath
- };
-
- const requestOptions = {
- url: "https://api.imagekit.io/v1/files/move",
- method: "POST",
- json: data,
- };
-
- request(requestOptions, defaultOptions, callback);
-};
-
-/*
- Rename file
-*/
-const renameFile = function (
- renameFileOptions: RenameFileOptions,
- defaultOptions: ImageKitOptions,
- callback?: IKCallback,
-) {
- const { filePath, newFileName, purgeCache = false } = renameFileOptions;
- if (typeof filePath !== "string" || filePath.length === 0) {
- respond(true, errorMessages.INVALID_FILE_PATH, callback);
- return;
- }
-
- if (typeof newFileName !== "string" || newFileName.length === 0) {
- respond(true, errorMessages.INVALID_NEW_FILE_NAME, callback);
- return;
- }
-
- if (typeof purgeCache !== "boolean") {
- respond(true, errorMessages.INVALID_PURGE_CACHE, callback);
- return;
- }
-
- const data = {
- filePath,
- newFileName,
- purgeCache
- };
-
- const requestOptions = {
- url: "https://api.imagekit.io/v1/files/rename",
- method: "PUT",
- json: data,
- };
-
- request(requestOptions, defaultOptions, callback);
-};
-
-/*
- Copy Folder
-*/
-const copyFolder = function (
- copyFolderOptions: CopyFolderOptions,
- defaultOptions: ImageKitOptions,
- callback?: IKCallback,
-) {
- const { sourceFolderPath, destinationPath, includeFileVersions = false } = copyFolderOptions;
- if (typeof sourceFolderPath !== "string" || sourceFolderPath.length === 0) {
- respond(true, errorMessages.INVALID_SOURCE_FOLDER_PATH, callback);
- return;
- }
-
- if (typeof destinationPath !== "string" || destinationPath.length === 0) {
- respond(true, errorMessages.INVALID_DESTINATION_FOLDER_PATH, callback);
- return;
- }
-
- if (typeof includeFileVersions !== "boolean") {
- respond(true, errorMessages.INVALID_INCLUDE_VERSION, callback);
- return;
- }
-
- const data = {
- sourceFolderPath,
- destinationPath,
- includeFileVersions
- };
-
- const requestOptions = {
- url: "https://api.imagekit.io/v1/bulkJobs/copyFolder",
- method: "POST",
- json: data,
- };
-
- request(requestOptions, defaultOptions, callback);
-};
-
-/*
- Move Folder
-*/
-const moveFolder = function (
- moveFolderOptions: MoveFolderOptions,
- defaultOptions: ImageKitOptions,
- callback?: IKCallback,
-) {
- const { sourceFolderPath, destinationPath } = moveFolderOptions;
-
- if (typeof sourceFolderPath !== "string" || sourceFolderPath.length === 0) {
- respond(true, errorMessages.INVALID_SOURCE_FOLDER_PATH, callback);
- return;
- }
-
- if (typeof destinationPath !== "string" || destinationPath.length === 0) {
- respond(true, errorMessages.INVALID_DESTINATION_FOLDER_PATH, callback);
- return;
- }
-
- const data = {
- sourceFolderPath,
- destinationPath,
- };
-
- const requestOptions = {
- url: "https://api.imagekit.io/v1/bulkJobs/moveFolder",
- method: "POST",
- json: data,
- };
-
- request(requestOptions, defaultOptions, callback);
-};
-
-/*
- Create folder
-*/
-const createFolder = function (
- createFolderOptions: CreateFolderOptions,
- defaultOptions: ImageKitOptions,
- callback?: IKCallback,
-) {
- const { folderName, parentFolderPath } = createFolderOptions;
- if (typeof folderName !== "string" || folderName.length === 0) {
- respond(true, errorMessages.INVALID_FOLDER_NAME, callback);
- return;
- }
-
- if (typeof parentFolderPath !== "string" || parentFolderPath.length === 0) {
- respond(true, errorMessages.INVALID_PARENT_FOLDER_PATH, callback);
- return;
- }
-
- const data = {
- folderName: folderName,
- parentFolderPath: parentFolderPath,
- };
-
- const requestOptions = {
- url: "https://api.imagekit.io/v1/folder",
- method: "POST",
- json: data,
- };
-
- request(requestOptions, defaultOptions, callback);
-};
-
-/*
- Delete folder
-*/
-const deleteFolder = function (folderPath: string, defaultOptions: ImageKitOptions, callback?: IKCallback) {
- if (typeof folderPath !== "string" || folderPath.length === 0) {
- respond(true, errorMessages.INVALID_FOLDER_PATH, callback);
- return;
- }
-
- const data = {
- folderPath: folderPath,
- };
-
- const requestOptions = {
- url: "https://api.imagekit.io/v1/folder",
- method: "DELETE",
- json: data,
- };
-
- request(requestOptions, defaultOptions, callback);
-};
-
-/*
- Bulk job status
-*/
-const getBulkJobStatus = function (jobId: string, defaultOptions: ImageKitOptions, callback?: IKCallback) {
- if (!jobId) {
- respond(true, errorMessages.JOB_ID_MISSING, callback);
- return;
- }
-
- const requestOptions = {
- url: "https://api.imagekit.io/v1/bulkJobs/" + jobId,
- method: "GET"
- };
-
- request(requestOptions, defaultOptions, callback);
-};
-
-export default {
- deleteFile,
- getMetadata,
- getDetails,
- getFileVersionDetails,
- updateDetails,
- listFiles,
- getFilesVersions,
- bulkDeleteFiles,
- deleteFileVersion,
- restoreFileVersion,
- bulkAddTags,
- bulkRemoveTags,
- bulkRemoveAITags,
- copyFile,
- moveFile,
- renameFile,
- copyFolder,
- moveFolder,
- createFolder,
- deleteFolder,
- getBulkJobStatus,
-};
diff --git a/libs/manage/index.ts b/libs/manage/index.ts
deleted file mode 100644
index 72f4ac34..00000000
--- a/libs/manage/index.ts
+++ /dev/null
@@ -1,33 +0,0 @@
-import cache from "./cache";
-import file from "./file";
-import customMetadataField from "./custom-metadata-field";
-
-export default {
- listFiles: file.listFiles,
- getFileDetails: file.getDetails,
- getFileVersions: file.getFilesVersions,
- getFileVersionDetails: file.getFileVersionDetails,
- updateFileDetails: file.updateDetails,
- getFileMetadata: file.getMetadata,
- deleteFile: file.deleteFile,
- bulkDeleteFiles: file.bulkDeleteFiles,
- deleteFileVersion: file.deleteFileVersion,
- restoreFileVersion: file.restoreFileVersion,
- bulkAddTags: file.bulkAddTags,
- bulkRemoveTags: file.bulkRemoveTags,
- bulkRemoveAITags: file.bulkRemoveAITags,
- copyFile: file.copyFile,
- moveFile: file.moveFile,
- renameFile: file.renameFile,
- copyFolder: file.copyFolder,
- moveFolder: file.moveFolder,
- createFolder: file.createFolder,
- deleteFolder: file.deleteFolder,
- getBulkJobStatus: file.getBulkJobStatus,
- purgeCache: cache.purgeCache,
- getPurgeCacheStatus: cache.getPurgeCacheStatus,
- createCustomMetadataField: customMetadataField.create,
- getCustomMetadataFields: customMetadataField.list,
- updateCustomMetadataField: customMetadataField.update,
- deleteCustomMetadataField: customMetadataField.deleteField,
-};
diff --git a/libs/signature/index.ts b/libs/signature/index.ts
deleted file mode 100644
index 8d17acec..00000000
--- a/libs/signature/index.ts
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- Helper Modules
-*/
-import { v4 as uuid } from "uuid";
-import crypto from "crypto";
-import { ImageKitOptions } from "../interfaces";
-var DEFAULT_TIME_DIFF = 60 * 30;
-
-const getAuthenticationParameters = function (token?: string, expire?: number, defaultOptions?: ImageKitOptions) {
- var defaultExpire = parseInt(String(new Date().getTime() / 1000), 10) + DEFAULT_TIME_DIFF;
- var authParameters = {
- token: token || "",
- expire: expire || 0,
- signature: "",
- };
-
- if (!defaultOptions || !defaultOptions.privateKey) return authParameters;
-
- token = token || uuid();
- expire = expire || defaultExpire;
- var signature = crypto
- .createHmac("sha1", defaultOptions.privateKey)
- .update(token + expire)
- .digest("hex");
-
- authParameters.token = token;
- authParameters.expire = expire;
- authParameters.signature = signature;
-
- return authParameters;
-};
-
-export default { getAuthenticationParameters };
diff --git a/libs/upload/index.ts b/libs/upload/index.ts
deleted file mode 100644
index 7d1a8577..00000000
--- a/libs/upload/index.ts
+++ /dev/null
@@ -1,110 +0,0 @@
-import _ from "lodash";
-import errorMessages from "../constants/errorMessages";
-import respond from "../../utils/respond";
-import request from "../../utils/request";
-import { IKCallback } from "../interfaces/IKCallback";
-import { ImageKitOptions, UploadOptions, UploadResponse } from "../interfaces";
-import FormData from "form-data";
-
-type Modify = Omit & R;
-type FormDataOptions = Modify<
- UploadOptions,
- {
- file: string | Buffer | object;
- useUniqueFileName: string;
- isPrivateFile: string;
- extensions?: string;
- webhookUrl?: string;
- overwriteFile?: string;
- overwriteAITags?: string;
- overwriteTags?: string;
- overwriteCustomMetadata?: string;
- customMetadata?: string;
- }
->;
-
-export default function (
- uploadOptions: UploadOptions,
- defaultOptions: ImageKitOptions,
- callback?: IKCallback,
-): void | Promise {
- if (!_.isObject(uploadOptions)) {
- respond(true, errorMessages.MISSING_UPLOAD_DATA, callback);
- return;
- }
-
- if (!uploadOptions.file) {
- respond(true, errorMessages.MISSING_UPLOAD_FILE_PARAMETER, callback);
- return;
- }
-
- if (!uploadOptions.fileName) {
- respond(true, errorMessages.MISSING_UPLOAD_FILENAME_PARAMETER, callback);
- return;
- }
-
- if (uploadOptions.transformation) {
- if (!(Object.keys(uploadOptions.transformation).includes("pre") || Object.keys(uploadOptions.transformation).includes("post"))) {
- respond(true, errorMessages.INVALID_TRANSFORMATION, callback);
- return;
- }
- if (Object.keys(uploadOptions.transformation).includes("pre") && !uploadOptions.transformation.pre) {
- respond(true, errorMessages.INVALID_PRE_TRANSFORMATION, callback);
- return;
- }
- if (Object.keys(uploadOptions.transformation).includes("post")) {
- if (Array.isArray(uploadOptions.transformation.post)) {
- for (let transformation of uploadOptions.transformation.post) {
- if (transformation.type === "abs" && !(transformation.protocol || transformation.value)) {
- respond(true, errorMessages.INVALID_POST_TRANSFORMATION, callback);
- return;
- } else if (transformation.type === "transformation" && !transformation.value) {
- respond(true, errorMessages.INVALID_POST_TRANSFORMATION, callback);
- return;
- }
- }
- } else {
- respond(true, errorMessages.INVALID_POST_TRANSFORMATION, callback);
- return;
- }
- }
- }
-
- var formData = {} as FormDataOptions;
-
- const form = new FormData();
-
- let key: keyof typeof uploadOptions;
- for (key in uploadOptions) {
- if (key) {
- if (key == "file" && typeof uploadOptions.file != "string") {
- // form.append('file', uploadOptions.file);
- form.append('file', uploadOptions.file, String(uploadOptions.fileName));
- } else if (key == "tags" && Array.isArray(uploadOptions.tags)) {
- form.append('tags', uploadOptions.tags.join(","));
- } else if (key == "responseFields" && Array.isArray(uploadOptions.responseFields)) {
- form.append('responseFields', uploadOptions.responseFields.join(","));
- } else if (key == "extensions" && Array.isArray(uploadOptions.extensions)) {
- form.append('extensions', JSON.stringify(uploadOptions.extensions));
- } else if (key === "customMetadata" && typeof uploadOptions.customMetadata === "object" &&
- !Array.isArray(uploadOptions.customMetadata) && uploadOptions.customMetadata !== null) {
- form.append('customMetadata', JSON.stringify(uploadOptions.customMetadata));
- } else if (key === "transformation" && typeof uploadOptions.transformation === "object" &&
- uploadOptions.transformation !== null) {
- form.append(key, JSON.stringify(uploadOptions.transformation));
- } else if (key === "checks" && uploadOptions.checks) {
- form.append(key, uploadOptions.checks);
- } else {
- form.append(key, String(uploadOptions[key]));
- }
- }
- }
-
- var requestOptions = {
- url: defaultOptions.uploadEndpoint || "https://upload.imagekit.io/api/v1/files/upload",
- method: "POST",
- formData: form
- };
-
- request(requestOptions, defaultOptions, callback);
-}
diff --git a/libs/url/builder.ts b/libs/url/builder.ts
deleted file mode 100644
index 87319978..00000000
--- a/libs/url/builder.ts
+++ /dev/null
@@ -1,179 +0,0 @@
-/*
- Helper Modules
-*/
-import { URLSearchParams, URL } from "url";
-import path from "path";
-import crypto from "crypto";
-
-/*
- Utils
-*/
-import transformationUtils from "../../utils/transformation";
-import urlFormatter from "../../utils/urlFormatter";
-
-/*
- Interfaces
-*/
-import { FinalUrlOptions, Transformation } from "../interfaces";
-
-/*
- Variables
-*/
-const TRANSFORMATION_PARAMETER: string = "tr";
-const SIGNATURE_PARAMETER: string = "ik-s";
-const TIMESTAMP_PARAMETER: string = "ik-t";
-const DEFAULT_TIMESTAMP: string = "9999999999";
-
-//used to check if special char is present in string (you'll need to encode it to utf-8 if it does)
-const hasMoreThanAscii = (str: string) => {
- return str.split('').some((char) => char.charCodeAt(0) > 127);
-}
-
-const customEncodeURI = (str: string) => {
- return str.includes("?") ? `${encodeURI(str.split("?")[0])}?${str.split("?")[1]}` : encodeURI(str);
-};
-
-export const encodeStringIfRequired = (str: string) => {
- return hasMoreThanAscii(str) ? customEncodeURI(str) : str;
-}
-
-const buildURL = function (opts: FinalUrlOptions): string {
- var isSrcParameterUsedForURL: boolean = false;
-
- var urlObject: URL;
-
- if (opts.path) {
- urlObject = new URL(opts.urlEndpoint)
- } else if (opts.src) {
- isSrcParameterUsedForURL = true;
- urlObject = new URL(opts.src)
- } else {
- return "";
- }
-
-
- var queryParameters = new URLSearchParams(urlObject.search || "");
- for (var i in opts.queryParameters) {
- queryParameters.set(i, opts.queryParameters[i]);
- }
-
- //Create Transformation String
- var transformationString = constructTransformationString(opts.transformation);
- if (transformationString) {
- //force that if src parameter is being used for URL construction then the transformation
- //string should be added only as a query parameter
- if (transformationUtils.addAsQueryParameter(opts) || isSrcParameterUsedForURL) {
- queryParameters.set(TRANSFORMATION_PARAMETER, transformationString);
- urlObject.pathname= `${urlObject.pathname}${opts.path||''}`;
- } else {
- urlObject.pathname = path.posix.join(
- urlObject.pathname,
- [TRANSFORMATION_PARAMETER, transformationString].join(transformationUtils.getChainTransformDelimiter()),
- opts.path || '',
- );
- }
- }
- else{
- urlObject.pathname= `${urlObject.pathname}${opts.path||''}`;
- }
-
- urlObject.host = urlFormatter.removeTrailingSlash(urlObject.host);
- urlObject.pathname = urlFormatter.addLeadingSlash(urlObject.pathname);
- urlObject.search = queryParameters.toString();
-
- /*
- Signature String and Timestamp
- If the url is constructed using src parameter instead of path then we still replace the urlEndpoint we have
- But the user is responsible for passing correct urlEndpoint value
-
- Signature generation logic, let's assume:
- urlEndpoint value = https://ik.imagekit.io/your_imagekit_id
- expiryTimestamp 9999999999
- 1. Let the final URL construct e.g. https://ik.imagekit.io/your_imagekit_id/tr:w-400:rotate-91/sample/testing-file.jpg?param1=123
- 2. Now remove urlEndpoint from it i.e tr:w-400:rotate-91/sample/testing-file.jpg?param1=123
- 3. Append expiryTimestamp to above string and calcualte signature of this string i.e "tr:w-400:rotate-91/sample/testing-file.jpg?param1=1239999999999"
- */
- var expiryTimestamp;
- if (opts.signed === true) {
- if (opts.expireSeconds) {
- expiryTimestamp = getSignatureTimestamp(opts.expireSeconds);
- } else {
- expiryTimestamp = DEFAULT_TIMESTAMP;
- }
-
- var intermediateURL = urlObject.href;
-
- var urlSignature = getSignature({
- privateKey: opts.privateKey,
- url: intermediateURL,
- urlEndpoint: opts.urlEndpoint,
- expiryTimestamp: expiryTimestamp,
- });
-
- if (expiryTimestamp && expiryTimestamp != DEFAULT_TIMESTAMP) {
- queryParameters.set(TIMESTAMP_PARAMETER, expiryTimestamp);
- }
- queryParameters.set(SIGNATURE_PARAMETER, urlSignature);
- urlObject.search = queryParameters.toString();
- }
- return urlObject.href;
-};
-
-function constructTransformationString(inputTransformation: Array | undefined) {
-
- const transformation = inputTransformation as Array<{ [key: string]: string | boolean | number }> | undefined;
- if (!Array.isArray(transformation)) {
- return "";
- }
-
- var parsedTransforms = [];
- for (var i = 0, l = transformation.length; i < l; i++) {
- var parsedTransformStep = [];
- for (var key in transformation[i]) {
- if(transformation[i][key] === undefined || transformation[i][key] === null )
- continue;
- let transformKey = transformationUtils.getTransformKey(key);
- if (!transformKey) {
- transformKey = key;
- }
-
- if (transformation[i][key] === "-") {
- parsedTransformStep.push(transformKey);
- } else if (key === "raw") {
- parsedTransformStep.push(transformation[i][key]);
- } else {
- var value = String(transformation[i][key]);
- if (transformKey === "di") {
- value = urlFormatter.removeTrailingSlash(urlFormatter.removeLeadingSlash(value));
- if (value) value = value.replace(/\//g, "@@");
- }
- parsedTransformStep.push([transformKey, value].join(transformationUtils.getTransformKeyValueDelimiter()));
- }
- }
- parsedTransforms.push(parsedTransformStep.join(transformationUtils.getTransformDelimiter()));
- }
-
- return parsedTransforms.join(transformationUtils.getChainTransformDelimiter());
-}
-
-function getSignatureTimestamp(seconds: number): string {
- if (!seconds) return DEFAULT_TIMESTAMP;
-
- var sec = parseInt(String(seconds), 10);
- if (!sec) return DEFAULT_TIMESTAMP;
-
- var currentTimestamp = parseInt(String(new Date().getTime() / 1000), 10);
- return String(currentTimestamp + sec);
-}
-
-export function getSignature(opts: any) {
- if (!opts.privateKey || !opts.url || !opts.urlEndpoint) return "";
- var stringToSign = opts.url.replace(urlFormatter.addTrailingSlash(opts.urlEndpoint), "") + opts.expiryTimestamp;
- stringToSign = encodeStringIfRequired(stringToSign);
- return crypto.createHmac("sha1", opts.privateKey).update(stringToSign).digest("hex");
-}
-
-export default {
- buildURL,
- getSignature,
-};
diff --git a/libs/url/index.ts b/libs/url/index.ts
deleted file mode 100644
index 35cd2d50..00000000
--- a/libs/url/index.ts
+++ /dev/null
@@ -1,18 +0,0 @@
-/*
- Helper Modules
-*/
-import _ from "lodash";
-/*
- Interfaces
-*/
-import { UrlOptions, ImageKitOptions, FinalUrlOptions } from "../interfaces";
-/*
- URL builder
-*/
-import builder from "./builder";
-
-export default function (urlOpts: UrlOptions, defaultOptions: ImageKitOptions): string {
- var opts: FinalUrlOptions = _.extend({}, defaultOptions, urlOpts);
-
- return builder.buildURL(opts);
-}
diff --git a/package.json b/package.json
index 40f220ed..c2399b07 100644
--- a/package.json
+++ b/package.json
@@ -1,73 +1,65 @@
{
- "name": "imagekit",
- "version": "6.0.0",
- "description": "Offical NodeJS SDK for ImageKit.io integration",
- "main": "./dist/index.js",
- "types": "./dist/index.d.ts",
- "scripts": {
- "compile": "rm -rf dist/ & tsc -p tsconfig.json",
- "test": "export NODE_ENV=test; nyc ./node_modules/mocha/bin/mocha --exit -t 40000 tests/*.js;ex=$?;unset NODE_ENV; exit $ex;",
- "test-e2e": "sh test-e2e.sh; exit $?;",
- "report-coverage": "nyc report --reporter=text-lcov > coverage.lcov && codecov",
- "prepack": "npm run compile"
- },
- "author": "ImageKit Developer ",
- "homepage": "https://imagekit.io",
- "license": "MIT",
- "repository": {
- "type": "git",
- "url": "git+https://github.com/imagekit-developer/imagekit-nodejs.git"
- },
- "bugs": {
- "url": "https://github.com/imagekit-developer/imagekit-nodejs/issues"
- },
- "keywords": [
- "imagekit",
- "nodejs",
- "javascript",
- "sdk",
- "js",
- "sdk",
- "image",
- "optimization",
- "image",
- "transformation",
- "image",
- "resize"
- ],
- "dependencies": {
- "axios": "^1.6.5",
- "form-data": "^4.0.0",
- "hamming-distance": "^1.0.0",
- "lodash": "^4.17.15",
- "tslib": "^2.4.0",
- "uuid": "^8.3.2"
- },
- "engines": {
- "node": ">=12.0.0"
- },
- "devDependencies": {
- "@babel/cli": "^7.14.5",
- "@babel/core": "^7.14.6",
- "@babel/node": "^7.14.5",
- "@babel/preset-env": "^7.14.5",
- "@babel/preset-typescript": "^7.14.5",
- "@babel/register": "^7.14.5",
- "@types/chai": "^4.3.1",
- "@types/lodash": "^4.14.170",
- "@types/mocha": "^9.1.1",
- "@types/node": "^15.12.2",
- "@types/request": "^2.48.5",
- "@types/sinon": "^10.0.12",
- "@types/uuid": "^8.3.4",
- "babel-plugin-replace-ts-export-assignment": "^0.0.2",
- "chai": "^4.2.0",
- "codecov": "^3.8.0",
- "concurrently": "6.5.1",
- "mocha": "^8.1.1",
- "nock": "^13.2.7",
- "nyc": "^15.1.0",
- "sinon": "^9.2.0",
- "typescript": "^4.3.2"
- }
+ "name": "imagekit",
+ "version": "6.0.1",
+ "private": false,
+ "repository": "github:imagekit-developer/imagekit-nodejs",
+ "type": "commonjs",
+ "main": "./dist/cjs/index.js",
+ "module": "./dist/esm/index.mjs",
+ "types": "./dist/cjs/index.d.ts",
+ "exports": {
+ ".": {
+ "types": "./dist/cjs/index.d.ts",
+ "import": {
+ "types": "./dist/esm/index.d.mts",
+ "default": "./dist/esm/index.mjs"
+ },
+ "require": {
+ "types": "./dist/cjs/index.d.ts",
+ "default": "./dist/cjs/index.js"
+ },
+ "default": "./dist/cjs/index.js"
+ },
+ "./package.json": "./package.json"
+ },
+ "files": [
+ "dist",
+ "reference.md",
+ "README.md",
+ "LICENSE"
+ ],
+ "scripts": {
+ "format": "prettier . --write --ignore-unknown",
+ "build": "yarn build:cjs && yarn build:esm",
+ "build:cjs": "tsc --project ./tsconfig.cjs.json",
+ "build:esm": "tsc --project ./tsconfig.esm.json && node scripts/rename-to-esm-files.js dist/esm",
+ "test": "jest --config jest.config.mjs",
+ "test:unit": "jest --selectProjects unit",
+ "test:browser": "jest --selectProjects browser",
+ "test:wire": "jest --selectProjects wire"
+ },
+ "devDependencies": {
+ "webpack": "^5.97.1",
+ "ts-loader": "^9.5.1",
+ "jest": "^29.7.0",
+ "@jest/globals": "^29.7.0",
+ "@types/jest": "^29.5.14",
+ "ts-jest": "^29.3.4",
+ "jest-environment-jsdom": "^29.7.0",
+ "msw": "^2.8.4",
+ "@types/node": "^18.19.70",
+ "prettier": "^3.4.2",
+ "typescript": "~5.7.2"
+ },
+ "browser": {
+ "fs": false,
+ "os": false,
+ "path": false,
+ "stream": false
+ },
+ "packageManager": "yarn@1.22.22",
+ "engines": {
+ "node": ">=18.0.0"
+ },
+ "sideEffects": false
}
diff --git a/reference.md b/reference.md
new file mode 100644
index 00000000..9ca8d53f
--- /dev/null
+++ b/reference.md
@@ -0,0 +1,2874 @@
+# Reference
+
+## Files
+
+client.files.upload({ ...params }) -> ImageKit.Upload
+
+-
+
+#### 📝 Description
+
+
+-
+
+
+-
+
+ImageKit.io allows you to upload files directly from both the server and client sides. For server-side uploads, private API key authentication is used. For client-side uploads, generate a one-time `token`, `signature`, and `expiration` from your secure backend using private API. [Learn more](/docs/api-reference/upload-file/upload-file#how-to-implement-client-side-file-upload) about how to implement client-side file upload.
+
+The [V2 API](/docs/api-reference/upload-file/upload-file-v2) enhances security by verifying the entire payload using JWT.
+
+**File size limit** \
+On the free plan, the maximum upload file sizes are 20MB for images, audio, and raw files and 100MB for videos. On the paid plan, these limits increase to 40MB for images, audio, and raw files and 2GB for videos. These limits can be further increased with higher-tier plans.
+
+**Version limit** \
+A file can have a maximum of 100 versions.
+
+**Demo applications**
+
+- A full-fledged [upload widget using Uppy](https://github.com/imagekit-samples/uppy-uploader), supporting file selections from local storage, URL, Dropbox, Google Drive, Instagram, and more.
+- [Quick start guides](/docs/quick-start-guides) for various frameworks and technologies.
+
+
+
+
+
+#### 🔌 Usage
+
+
+-
+
+
+-
+
+```typescript
+await client.files.upload({
+ file: fs.createReadStream("/path/to/your/file"),
+ fileName: "fileName",
+});
+```
+
+
+
+
+
+
+#### ⚙️ Parameters
+
+
+-
+
+
+-
+
+**request:** `ImageKit.FileUploadV1`
+
+
+
+
+
+-
+
+**requestOptions:** `Files.RequestOptions`
+
+
+
+
+
+
+
+
+
+
+client.files.get(fileId) -> ImageKit.FileDetails
+
+-
+
+#### 📝 Description
+
+
+-
+
+
+-
+
+This API returns an object with details or attributes about the current version of the file.
+
+
+
+
+
+
+#### 🔌 Usage
+
+
+-
+
+
+-
+
+```typescript
+await client.files.get("fileId");
+```
+
+
+
+
+
+
+#### ⚙️ Parameters
+
+
+-
+
+
+-
+
+**fileId:** `string` — The unique `fileId` of the uploaded file. `fileId` is returned in the list and search assets API and upload API.
+
+
+
+
+
+-
+
+**requestOptions:** `Files.RequestOptions`
+
+
+
+
+
+
+
+
+
+
+client.files.update(fileId, { ...params }) -> ImageKit.FilesUpdateResponse
+
+-
+
+#### 📝 Description
+
+
+-
+
+
+-
+
+This API updates the details or attributes of the current version of the file. You can update `tags`, `customCoordinates`, `customMetadata`, publication status, remove existing `AITags` and apply extensions using this API.
+
+
+
+
+
+
+#### 🔌 Usage
+
+
+-
+
+
+-
+
+```typescript
+await client.files.update("fileId", {
+ removeAITags: ["car", "vehicle", "motorsports"],
+ webhookUrl: "https://webhook.site/0d6b6c7a-8e5a-4b3a-8b7c-0d6b6c7a8e5a",
+ extensions: [
+ {
+ name: "remove-bg",
+ options: {
+ add_shadow: true,
+ },
+ },
+ {
+ name: "google-auto-tagging",
+ minConfidence: 80,
+ maxTags: 10,
+ },
+ {
+ name: "aws-auto-tagging",
+ minConfidence: 80,
+ maxTags: 10,
+ },
+ {
+ name: "ai-auto-description",
+ },
+ ],
+ tags: ["tag1", "tag2"],
+ customCoordinates: "10,10,100,100",
+ customMetadata: {
+ brand: "Nike",
+ color: "red",
+ },
+});
+```
+
+
+
+
+
+
+#### ⚙️ Parameters
+
+
+-
+
+
+-
+
+**fileId:** `string` — The unique `fileId` of the uploaded file. `fileId` is returned in list and search assets API and upload API.
+
+
+
+
+
+-
+
+**request:** `ImageKit.FilesUpdateRequest`
+
+
+
+
+
+-
+
+**requestOptions:** `Files.RequestOptions`
+
+
+
+
+
+
+
+
+
+
+client.files.delete(fileId) -> void
+
+-
+
+#### 📝 Description
+
+
+-
+
+
+-
+
+This API deletes the file and all its file versions permanently.
+
+Note: If a file or specific transformation has been requested in the past, then the response is cached. Deleting a file does not purge the cache. You can purge the cache using purge cache API.
+
+
+
+
+
+
+#### 🔌 Usage
+
+
+-
+
+
+-
+
+```typescript
+await client.files.delete("fileId");
+```
+
+
+
+
+
+
+#### ⚙️ Parameters
+
+
+-
+
+
+-
+
+**fileId:** `string` — The unique `fileId` of the uploaded file. `fileId` is returned in list and search assets API and upload API.
+
+
+
+
+
+-
+
+**requestOptions:** `Files.RequestOptions`
+
+
+
+
+
+
+
+
+
+
+client.files.copy({ ...params }) -> Record
+
+-
+
+#### 📝 Description
+
+
+-
+
+
+-
+
+This will copy a file from one folder to another.
+
+Note: If any file at the destination has the same name as the source file, then the source file and its versions (if `includeFileVersions` is set to true) will be appended to the destination file version history.
+
+
+
+
+
+
+#### 🔌 Usage
+
+
+-
+
+
+-
+
+```typescript
+await client.files.copy({
+ sourceFilePath: "/path/to/file.jpg",
+ destinationPath: "/folder/to/copy/into/",
+});
+```
+
+
+
+
+
+
+#### ⚙️ Parameters
+
+
+-
+
+
+-
+
+**request:** `ImageKit.FilesCopyRequest`
+
+
+
+
+
+-
+
+**requestOptions:** `Files.RequestOptions`
+
+
+
+
+
+
+
+
+
+
+client.files.move({ ...params }) -> Record
+
+-
+
+#### 📝 Description
+
+
+-
+
+
+-
+
+This will move a file and all its versions from one folder to another.
+
+Note: If any file at the destination has the same name as the source file, then the source file and its versions will be appended to the destination file.
+
+
+
+
+
+
+#### 🔌 Usage
+
+
+-
+
+
+-
+
+```typescript
+await client.files.move({
+ sourceFilePath: "/path/to/file.jpg",
+ destinationPath: "/folder/to/move/into/",
+});
+```
+
+
+
+
+
+
+#### ⚙️ Parameters
+
+
+-
+
+
+-
+
+**request:** `ImageKit.FilesMoveRequest`
+
+
+
+
+
+-
+
+**requestOptions:** `Files.RequestOptions`
+
+
+
+
+
+
+
+
+
+
+client.files.rename({ ...params }) -> ImageKit.FilesRenameResponse
+
+-
+
+#### 📝 Description
+
+
+-
+
+
+-
+
+You can rename an already existing file in the media library using rename file API. This operation would rename all file versions of the file.
+
+Note: The old URLs will stop working. The file/file version URLs cached on CDN will continue to work unless a purge is requested.
+
+
+
+
+
+
+#### 🔌 Usage
+
+
+-
+
+
+-
+
+```typescript
+await client.files.rename({
+ filePath: "/path/to/file.jpg",
+ newFileName: "newFileName.jpg",
+});
+```
+
+
+
+
+
+
+#### ⚙️ Parameters
+
+
+-
+
+
+-
+
+**request:** `ImageKit.FilesRenameRequest`
+
+
+
+
+
+-
+
+**requestOptions:** `Files.RequestOptions`
+
+
+
+
+
+
+
+
+
+
+## CustomMetadataFields
+
+client.customMetadataFields.list({ ...params }) -> ImageKit.CustomMetadataField[]
+
+-
+
+#### 📝 Description
+
+
+-
+
+
+-
+
+This API returns the array of created custom metadata field objects. By default the API returns only non deleted field objects, but you can include deleted fields in the API response.
+
+
+
+
+
+
+#### 🔌 Usage
+
+
+-
+
+
+-
+
+```typescript
+await client.customMetadataFields.list();
+```
+
+
+
+
+
+
+#### ⚙️ Parameters
+
+
+-
+
+
+-
+
+**request:** `ImageKit.CustomMetadataFieldsListRequest`
+
+
+
+
+
+-
+
+**requestOptions:** `CustomMetadataFields.RequestOptions`
+
+
+
+
+
+
+
+
+
+
+client.customMetadataFields.create({ ...params }) -> ImageKit.CustomMetadataField
+
+-
+
+#### 📝 Description
+
+
+-
+
+
+-
+
+This API creates a new custom metadata field. Once a custom metadata field is created either through this API or using the dashboard UI, its value can be set on the assets. The value of a field for an asset can be set using the media library UI or programmatically through upload or update assets API.
+
+
+
+
+
+
+#### 🔌 Usage
+
+
+-
+
+
+-
+
+```typescript
+await client.customMetadataFields.create({
+ name: "price",
+ label: "price",
+ schema: {
+ type: "Number",
+ minValue: 1000,
+ maxValue: 3000,
+ },
+});
+```
+
+
+
+
+
+
+#### ⚙️ Parameters
+
+
+-
+
+
+-
+
+**request:** `ImageKit.CustomMetadataFieldsCreateRequest`
+
+
+
+
+
+-
+
+**requestOptions:** `CustomMetadataFields.RequestOptions`
+
+
+
+
+
+
+
+
+
+
+client.customMetadataFields.delete(id) -> Record
+
+-
+
+#### 📝 Description
+
+
+-
+
+
+-
+
+This API deletes a custom metadata field. Even after deleting a custom metadata field, you cannot create any new custom metadata field with the same name.
+
+
+
+
+
+
+#### 🔌 Usage
+
+
+-
+
+
+-
+
+```typescript
+await client.customMetadataFields.delete("id");
+```
+
+
+
+
+
+
+#### ⚙️ Parameters
+
+
+-
+
+
+-
+
+**id:** `string` — Should be a valid custom metadata field id.
+
+
+
+
+
+-
+
+**requestOptions:** `CustomMetadataFields.RequestOptions`
+
+
+
+
+
+
+
+
+
+
+client.customMetadataFields.update(id, { ...params }) -> ImageKit.CustomMetadataField
+
+-
+
+#### 📝 Description
+
+
+-
+
+
+-
+
+This API updates the label or schema of an existing custom metadata field.
+
+
+
+
+
+
+#### 🔌 Usage
+
+
+-
+
+
+-
+
+```typescript
+await client.customMetadataFields.update("id", {
+ label: "price",
+ schema: {
+ minValue: 1000,
+ maxValue: 3000,
+ },
+});
+```
+
+
+
+
+
+
+#### ⚙️ Parameters
+
+
+-
+
+
+-
+
+**id:** `string` — Should be a valid custom metadata field id.
+
+
+
+
+
+-
+
+**request:** `ImageKit.CustomMetadataFieldsUpdateRequest`
+
+
+
+
+
+-
+
+**requestOptions:** `CustomMetadataFields.RequestOptions`
+
+
+
+
+
+
+
+
+
+
+## Assets
+
+client.assets.list({ ...params }) -> ImageKit.AssetsListResponseItem[]
+
+-
+
+#### 📝 Description
+
+
+-
+
+
+-
+
+This API can list all the uploaded files and folders in your ImageKit.io media library. In addition, you can fine-tune your query by specifying various filters by generating a query string in a Lucene-like syntax and provide this generated string as the value of the `searchQuery`.
+
+
+
+
+
+
+#### 🔌 Usage
+
+
+-
+
+
+-
+
+```typescript
+await client.assets.list();
+```
+
+
+
+
+
+
+#### ⚙️ Parameters
+
+
+-
+
+
+-
+
+**request:** `ImageKit.AssetsListRequest`
+
+
+
+
+
+-
+
+**requestOptions:** `Assets.RequestOptions`
+
+
+
+
+
+
+
+
+
+
+## Folders
+
+client.folders.create({ ...params }) -> Record
+
+-
+
+#### 📝 Description
+
+
+-
+
+
+-
+
+This will create a new folder. You can specify the folder name and location of the parent folder where this new folder should be created.
+
+
+
+
+
+
+#### 🔌 Usage
+
+
+-
+
+
+-
+
+```typescript
+await client.folders.create({
+ folderName: "summer",
+ parentFolderPath: "/product/images/",
+});
+```
+
+
+
+
+
+
+#### ⚙️ Parameters
+
+
+-
+
+
+-
+
+**request:** `ImageKit.FoldersCreateRequest`
+
+
+
+
+
+-
+
+**requestOptions:** `Folders.RequestOptions`
+
+
+
+
+
+
+
+
+
+
+client.folders.delete({ ...params }) -> Record
+
+-
+
+#### 📝 Description
+
+
+-
+
+
+-
+
+This will delete a folder and all its contents permanently. The API returns an empty response.
+
+
+
+
+
+
+#### 🔌 Usage
+
+
+-
+
+
+-
+
+```typescript
+await client.folders.delete({
+ folderPath: "/folder/to/delete/",
+});
+```
+
+
+
+
+
+
+#### ⚙️ Parameters
+
+
+-
+
+
+-
+
+**request:** `ImageKit.FoldersDeleteRequest`
+
+
+
+
+
+-
+
+**requestOptions:** `Folders.RequestOptions`
+
+
+
+
+
+
+
+
+
+
+client.folders.copy({ ...params }) -> ImageKit.FoldersCopyResponse
+
+-
+
+#### 📝 Description
+
+
+-
+
+
+-
+
+This will copy one folder into another. The selected folder, its nested folders, files, and their versions (in `includeVersions` is set to true) are copied in this operation. Note: If any file at the destination has the same name as the source file, then the source file and its versions will be appended to the destination file version history.
+
+
+
+
+
+
+#### 🔌 Usage
+
+
+-
+
+
+-
+
+```typescript
+await client.folders.copy({
+ sourceFolderPath: "/path/of/source/folder",
+ destinationPath: "/path/of/destination/folder",
+});
+```
+
+
+
+
+
+
+#### ⚙️ Parameters
+
+
+-
+
+
+-
+
+**request:** `ImageKit.FoldersCopyRequest`
+
+
+
+
+
+-
+
+**requestOptions:** `Folders.RequestOptions`
+
+
+
+
+
+
+
+
+
+
+client.folders.move({ ...params }) -> ImageKit.FoldersMoveResponse
+
+-
+
+#### 📝 Description
+
+
+-
+
+
+-
+
+This will move one folder into another. The selected folder, its nested folders, files, and their versions are moved in this operation. Note: If any file at the destination has the same name as the source file, then the source file and its versions will be appended to the destination file version history.
+
+
+
+
+
+
+#### 🔌 Usage
+
+
+-
+
+
+-
+
+```typescript
+await client.folders.move({
+ sourceFolderPath: "/path/of/source/folder",
+ destinationPath: "/path/of/destination/folder",
+});
+```
+
+
+
+
+
+
+#### ⚙️ Parameters
+
+
+-
+
+
+-
+
+**request:** `ImageKit.FoldersMoveRequest`
+
+
+
+
+
+-
+
+**requestOptions:** `Folders.RequestOptions`
+
+
+
+
+
+
+
+
+
+
+client.folders.rename({ ...params }) -> ImageKit.FoldersRenameResponse
+
+-
+
+#### 📝 Description
+
+
+-
+
+
+-
+
+This API allows you to rename an existing folder. The folder and all its nested assets and sub-folders will remain unchanged, but their paths will be updated to reflect the new folder name.
+
+
+
+
+
+
+#### 🔌 Usage
+
+
+-
+
+
+-
+
+```typescript
+await client.folders.rename({
+ folderPath: "/path/of/folder",
+ newFolderName: "new-folder-name",
+});
+```
+
+
+
+
+
+
+#### ⚙️ Parameters
+
+
+-
+
+
+-
+
+**request:** `ImageKit.FoldersRenameRequest`
+
+
+
+
+
+-
+
+**requestOptions:** `Folders.RequestOptions`
+
+
+
+
+
+
+
+
+
+
+## Accounts Usage
+
+client.accounts.usage.get({ ...params }) -> ImageKit.UsageGetResponse
+
+-
+
+#### 📝 Description
+
+
+-
+
+
+-
+
+Get the account usage information between two dates. Note that the API response includes data from the start date while excluding data from the end date. In other words, the data covers the period starting from the specified start date up to, but not including, the end date.
+
+
+
+
+
+
+#### 🔌 Usage
+
+
+-
+
+
+-
+
+```typescript
+await client.accounts.usage.get({
+ startDate: "startDate",
+ endDate: "endDate",
+});
+```
+
+
+
+
+
+
+#### ⚙️ Parameters
+
+
+-
+
+
+-
+
+**request:** `ImageKit.accounts.UsageGetRequest`
+
+
+
+
+
+-
+
+**requestOptions:** `Usage.RequestOptions`
+
+
+
+
+
+
+
+
+
+
+## Accounts Origins
+
+client.accounts.origins.list() -> ImageKit.OriginResponseArray
+
+-
+
+#### 📝 Description
+
+
+-
+
+
+-
+
+**Note:** This API is currently in beta.
+Returns an array of all configured origins for the current account.
+
+
+
+
+
+
+#### 🔌 Usage
+
+
+-
+
+
+-
+
+```typescript
+await client.accounts.origins.list();
+```
+
+
+
+
+
+
+#### ⚙️ Parameters
+
+
+-
+
+
+-
+
+**requestOptions:** `Origins.RequestOptions`
+
+
+
+
+
+
+
+
+
+
+client.accounts.origins.create({ ...params }) -> ImageKit.OriginResponse
+
+-
+
+#### 📝 Description
+
+
+-
+
+
+-
+
+**Note:** This API is currently in beta.
+Creates a new origin and returns the origin object.
+
+
+
+
+
+
+#### 🔌 Usage
+
+
+-
+
+
+-
+
+```typescript
+await client.accounts.origins.create({
+ type: "S3",
+ name: "US S3 Storage",
+ bucket: "product-images",
+ accessKey: "AKIAIOSFODNN7EXAMPLE",
+ secretKey: "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",
+});
+```
+
+
+
+
+
+
+#### ⚙️ Parameters
+
+
+-
+
+
+-
+
+**request:** `ImageKit.OriginSchema`
+
+
+
+
+
+-
+
+**requestOptions:** `Origins.RequestOptions`
+
+
+
+
+
+
+
+
+
+
+client.accounts.origins.get(id) -> ImageKit.OriginResponse
+
+-
+
+#### 📝 Description
+
+
+-
+
+
+-
+
+**Note:** This API is currently in beta.
+Retrieves the origin identified by `id`.
+
+
+
+
+
+
+#### 🔌 Usage
+
+
+-
+
+
+-
+
+```typescript
+await client.accounts.origins.get("id");
+```
+
+
+
+
+
+
+#### ⚙️ Parameters
+
+
+-
+
+
+-
+
+**id:** `string` — Unique identifier for the origin. This is generated by ImageKit when you create a new origin.
+
+
+
+
+
+-
+
+**requestOptions:** `Origins.RequestOptions`
+
+
+
+
+
+
+
+
+
+
+client.accounts.origins.update(id, { ...params }) -> ImageKit.OriginResponse
+
+-
+
+#### 📝 Description
+
+
+-
+
+
+-
+
+**Note:** This API is currently in beta.
+Updates the origin identified by `id` and returns the updated origin object.
+
+
+
+
+
+
+#### 🔌 Usage
+
+
+-
+
+
+-
+
+```typescript
+await client.accounts.origins.update("id", {
+ type: "S3",
+ name: "US S3 Storage",
+ bucket: "product-images",
+ accessKey: "AKIAIOSFODNN7EXAMPLE",
+ secretKey: "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",
+});
+```
+
+
+
+
+
+
+#### ⚙️ Parameters
+
+
+-
+
+
+-
+
+**id:** `string` — Unique identifier for the origin. This is generated by ImageKit when you create a new origin.
+
+
+
+
+
+-
+
+**request:** `ImageKit.OriginSchema`
+
+
+
+
+
+-
+
+**requestOptions:** `Origins.RequestOptions`
+
+
+
+
+
+
+
+
+
+
+client.accounts.origins.delete(id) -> void
+
+-
+
+#### 📝 Description
+
+
+-
+
+
+-
+
+**Note:** This API is currently in beta.
+Permanently removes the origin identified by `id`. If the origin is in use by any URL‑endpoints, the API will return an error.
+
+
+
+
+
+
+#### 🔌 Usage
+
+
+-
+
+
+-
+
+```typescript
+await client.accounts.origins.delete("id");
+```
+
+
+
+
+
+
+#### ⚙️ Parameters
+
+
+-
+
+
+-
+
+**id:** `string` — Unique identifier for the origin. This is generated by ImageKit when you create a new origin.
+
+
+
+
+
+-
+
+**requestOptions:** `Origins.RequestOptions`
+
+
+
+
+
+
+
+
+
+
+## Accounts UrlEndpoints
+
+client.accounts.urlEndpoints.list() -> ImageKit.UrlEndpointResponseArray
+
+-
+
+#### 📝 Description
+
+
+-
+
+
+-
+
+**Note:** This API is currently in beta.
+Returns an array of all URL‑endpoints configured including the default URL-endpoint generated by ImageKit during account creation.
+
+
+
+
+
+
+#### 🔌 Usage
+
+
+-
+
+
+-
+
+```typescript
+await client.accounts.urlEndpoints.list();
+```
+
+
+
+
+
+
+#### ⚙️ Parameters
+
+
+-
+
+
+-
+
+**requestOptions:** `UrlEndpoints.RequestOptions`
+
+
+
+
+
+
+
+
+
+
+client.accounts.urlEndpoints.create({ ...params }) -> ImageKit.UrlEndpointResponse
+
+-
+
+#### 📝 Description
+
+
+-
+
+
+-
+
+**Note:** This API is currently in beta.
+Creates a new URL‑endpoint and returns the resulting object.
+
+
+
+
+
+
+#### 🔌 Usage
+
+
+-
+
+
+-
+
+```typescript
+await client.accounts.urlEndpoints.create({
+ description: "My custom URL endpoint",
+ urlPrefix: "product-images",
+ origins: ["origin-id-1"],
+});
+```
+
+
+
+
+
+
+#### ⚙️ Parameters
+
+
+-
+
+
+-
+
+**request:** `ImageKit.UrlEndpointSchema`
+
+
+
+
+
+-
+
+**requestOptions:** `UrlEndpoints.RequestOptions`
+
+
+
+
+
+
+
+
+
+
+client.accounts.urlEndpoints.get(id) -> ImageKit.UrlEndpointResponse
+
+-
+
+#### 📝 Description
+
+
+-
+
+
+-
+
+**Note:** This API is currently in beta.
+Retrieves the URL‑endpoint identified by `id`.
+
+
+
+
+
+
+#### 🔌 Usage
+
+
+-
+
+
+-
+
+```typescript
+await client.accounts.urlEndpoints.get("id");
+```
+
+
+
+
+
+
+#### ⚙️ Parameters
+
+
+-
+
+
+-
+
+**id:** `string` — Unique identifier for the URL-endpoint. This is generated by ImageKit when you create a new URL-endpoint. For the default URL-endpoint, this is always `default`.
+
+
+
+
+
+-
+
+**requestOptions:** `UrlEndpoints.RequestOptions`
+
+
+
+
+
+
+
+
+
+
+client.accounts.urlEndpoints.update(id, { ...params }) -> ImageKit.UrlEndpointResponse
+
+-
+
+#### 📝 Description
+
+
+-
+
+
+-
+
+**Note:** This API is currently in beta.
+Updates the URL‑endpoint identified by `id` and returns the updated object.
+
+
+
+
+
+
+#### 🔌 Usage
+
+
+-
+
+
+-
+
+```typescript
+await client.accounts.urlEndpoints.update("id", {
+ description: "My custom URL endpoint",
+ urlPrefix: "product-images",
+ origins: ["origin-id-1"],
+});
+```
+
+
+
+
+
+
+#### ⚙️ Parameters
+
+
+-
+
+
+-
+
+**id:** `string` — Unique identifier for the URL-endpoint. This is generated by ImageKit when you create a new URL-endpoint. For the default URL-endpoint, this is always `default`.
+
+
+
+
+
+-
+
+**request:** `ImageKit.UrlEndpointSchema`
+
+
+
+
+
+-
+
+**requestOptions:** `UrlEndpoints.RequestOptions`
+
+
+
+
+
+
+
+
+
+
+client.accounts.urlEndpoints.delete(id) -> void
+
+-
+
+#### 📝 Description
+
+
+-
+
+
+-
+
+**Note:** This API is currently in beta.
+Deletes the URL‑endpoint identified by `id`. You cannot delete the default URL‑endpoint created by ImageKit during account creation.
+
+
+
+
+
+
+#### 🔌 Usage
+
+
+-
+
+
+-
+
+```typescript
+await client.accounts.urlEndpoints.delete("id");
+```
+
+
+
+
+
+
+#### ⚙️ Parameters
+
+
+-
+
+
+-
+
+**id:** `string` — Unique identifier for the URL-endpoint. This is generated by ImageKit when you create a new URL-endpoint. For the default URL-endpoint, this is always `default`.
+
+
+
+
+
+-
+
+**requestOptions:** `UrlEndpoints.RequestOptions`
+
+
+
+
+
+
+
+
+
+
+## Beta V2 Files
+
+client.beta.v2.files.upload({ ...params }) -> ImageKit.Upload
+
+-
+
+#### 📝 Description
+
+
+-
+
+
+-
+
+The V2 API enhances security by verifying the entire payload using JWT. This API is in beta.
+
+ImageKit.io allows you to upload files directly from both the server and client sides. For server-side uploads, private API key authentication is used. For client-side uploads, generate a one-time `token` from your secure backend using private API. [Learn more](/docs/api-reference/upload-file/upload-file-v2#how-to-implement-secure-client-side-file-upload) about how to implement secure client-side file upload.
+
+**File size limit** \
+On the free plan, the maximum upload file sizes are 20MB for images, audio, and raw files, and 100MB for videos. On the paid plan, these limits increase to 40MB for images, audio, and raw files, and 2GB for videos. These limits can be further increased with higher-tier plans.
+
+**Version limit** \
+A file can have a maximum of 100 versions.
+
+**Demo applications**
+
+- A full-fledged [upload widget using Uppy](https://github.com/imagekit-samples/uppy-uploader), supporting file selections from local storage, URL, Dropbox, Google Drive, Instagram, and more.
+- [Quick start guides](/docs/quick-start-guides) for various frameworks and technologies.
+
+
+
+
+
+#### 🔌 Usage
+
+
+-
+
+
+-
+
+```typescript
+await client.beta.v2.files.upload({
+ file: fs.createReadStream("/path/to/your/file"),
+ fileName: "fileName",
+});
+```
+
+
+
+
+
+
+#### ⚙️ Parameters
+
+
+-
+
+
+-
+
+**request:** `ImageKit.beta.v2.FileUploadV2`
+
+
+
+
+
+-
+
+**requestOptions:** `Files.RequestOptions`
+
+
+
+
+
+
+
+
+
+
+## Cache Invalidation
+
+client.cache.invalidation.create({ ...params }) -> ImageKit.InvalidationCreateResponse
+
+-
+
+#### 📝 Description
+
+
+-
+
+
+-
+
+This API will purge CDN cache and ImageKit.io's internal cache for a file. Note: Purge cache is an asynchronous process and it may take some time to reflect the changes.
+
+
+
+
+
+
+#### 🔌 Usage
+
+
+-
+
+
+-
+
+```typescript
+await client.cache.invalidation.create({
+ url: "https://ik.imagekit.io/your_imagekit_id/default-image.jpg",
+});
+```
+
+
+
+
+
+
+#### ⚙️ Parameters
+
+
+-
+
+
+-
+
+**request:** `ImageKit.cache.InvalidationCreateRequest`
+
+
+
+
+
+-
+
+**requestOptions:** `Invalidation.RequestOptions`
+
+
+
+
+
+
+
+
+
+
+client.cache.invalidation.get(requestId) -> ImageKit.InvalidationGetResponse
+
+-
+
+#### 📝 Description
+
+
+-
+
+
+-
+
+This API returns the status of a purge cache request.
+
+
+
+
+
+
+#### 🔌 Usage
+
+
+-
+
+
+-
+
+```typescript
+await client.cache.invalidation.get("requestId");
+```
+
+
+
+
+
+
+#### ⚙️ Parameters
+
+
+-
+
+
+-
+
+**requestId:** `string` — Should be a valid requestId.
+
+
+
+
+
+-
+
+**requestOptions:** `Invalidation.RequestOptions`
+
+
+
+
+
+
+
+
+
+
+## Files Bulk
+
+client.files.bulk.delete({ ...params }) -> ImageKit.BulkDeleteResponse
+
+-
+
+#### 📝 Description
+
+
+-
+
+
+-
+
+This API deletes multiple files and all their file versions permanently.
+
+Note: If a file or specific transformation has been requested in the past, then the response is cached. Deleting a file does not purge the cache. You can purge the cache using purge cache API.
+
+A maximum of 100 files can be deleted at a time.
+
+
+
+
+
+
+#### 🔌 Usage
+
+
+-
+
+
+-
+
+```typescript
+await client.files.bulk.delete({
+ fileIds: ["598821f949c0a938d57563bd", "598821f949c0a938d57563be"],
+});
+```
+
+
+
+
+
+
+#### ⚙️ Parameters
+
+
+-
+
+
+-
+
+**request:** `ImageKit.files.BulkDeleteRequest`
+
+
+
+
+
+-
+
+**requestOptions:** `Bulk.RequestOptions`
+
+
+
+
+
+
+
+
+
+
+client.files.bulk.addTags({ ...params }) -> ImageKit.BulkAddTagsResponse
+
+-
+
+#### 📝 Description
+
+
+-
+
+
+-
+
+This API adds tags to multiple files in bulk. A maximum of 50 files can be specified at a time.
+
+
+
+
+
+
+#### 🔌 Usage
+
+
+-
+
+
+-
+
+```typescript
+await client.files.bulk.addTags({
+ fileIds: ["598821f949c0a938d57563bd", "598821f949c0a938d57563be"],
+ tags: ["t-shirt", "round-neck", "sale2019"],
+});
+```
+
+
+
+
+
+
+#### ⚙️ Parameters
+
+
+-
+
+
+-
+
+**request:** `ImageKit.files.BulkAddTagsRequest`
+
+
+
+
+
+-
+
+**requestOptions:** `Bulk.RequestOptions`
+
+
+
+
+
+
+
+
+
+
+client.files.bulk.removeTags({ ...params }) -> ImageKit.BulkRemoveTagsResponse
+
+-
+
+#### 📝 Description
+
+
+-
+
+
+-
+
+This API removes tags from multiple files in bulk. A maximum of 50 files can be specified at a time.
+
+
+
+
+
+
+#### 🔌 Usage
+
+
+-
+
+
+-
+
+```typescript
+await client.files.bulk.removeTags({
+ fileIds: ["598821f949c0a938d57563bd", "598821f949c0a938d57563be"],
+ tags: ["t-shirt", "round-neck", "sale2019"],
+});
+```
+
+
+
+
+
+
+#### ⚙️ Parameters
+
+
+-
+
+
+-
+
+**request:** `ImageKit.files.BulkRemoveTagsRequest`
+
+
+
+
+
+-
+
+**requestOptions:** `Bulk.RequestOptions`
+
+
+
+
+
+
+
+
+
+
+client.files.bulk.removeAiTags({ ...params }) -> ImageKit.BulkRemoveAiTagsResponse
+
+-
+
+#### 📝 Description
+
+
+-
+
+
+-
+
+This API removes AITags from multiple files in bulk. A maximum of 50 files can be specified at a time.
+
+
+
+
+
+
+#### 🔌 Usage
+
+
+-
+
+
+-
+
+```typescript
+await client.files.bulk.removeAiTags({
+ fileIds: ["598821f949c0a938d57563bd", "598821f949c0a938d57563be"],
+ AITags: ["t-shirt", "round-neck", "sale2019"],
+});
+```
+
+
+
+
+
+
+#### ⚙️ Parameters
+
+
+-
+
+
+-
+
+**request:** `ImageKit.files.BulkRemoveAiTagsRequest`
+
+
+
+
+
+-
+
+**requestOptions:** `Bulk.RequestOptions`
+
+
+
+
+
+
+
+
+
+
+## Files Versions
+
+client.files.versions.list(fileId) -> ImageKit.FileDetails[]
+
+-
+
+#### 📝 Description
+
+
+-
+
+
+-
+
+This API returns details of all versions of a file.
+
+
+
+
+
+
+#### 🔌 Usage
+
+
+-
+
+
+-
+
+```typescript
+await client.files.versions.list("fileId");
+```
+
+
+
+
+
+
+#### ⚙️ Parameters
+
+
+-
+
+
+-
+
+**fileId:** `string` — The unique `fileId` of the uploaded file. `fileId` is returned in list and search assets API and upload API.
+
+
+
+
+
+-
+
+**requestOptions:** `Versions.RequestOptions`
+
+
+
+
+
+
+
+
+
+
+client.files.versions.get(fileId, versionId) -> ImageKit.FileDetails
+
+-
+
+#### 📝 Description
+
+
+-
+
+
+-
+
+This API returns an object with details or attributes of a file version.
+
+
+
+
+
+
+#### 🔌 Usage
+
+
+-
+
+
+-
+
+```typescript
+await client.files.versions.get("fileId", "versionId");
+```
+
+
+
+
+
+
+#### ⚙️ Parameters
+
+
+-
+
+
+-
+
+**fileId:** `string` — The unique `fileId` of the uploaded file. `fileId` is returned in list and search assets API and upload API.
+
+
+
+
+
+-
+
+**versionId:** `string` — The unique `versionId` of the uploaded file. `versionId` is returned in list and search assets API and upload API.
+
+
+
+
+
+-
+
+**requestOptions:** `Versions.RequestOptions`
+
+
+
+
+
+
+
+
+
+
+client.files.versions.delete(fileId, versionId) -> Record
+
+-
+
+#### 📝 Description
+
+
+-
+
+
+-
+
+This API deletes a non-current file version permanently. The API returns an empty response.
+
+Note: If you want to delete all versions of a file, use the delete file API.
+
+
+
+
+
+
+#### 🔌 Usage
+
+
+-
+
+
+-
+
+```typescript
+await client.files.versions.delete("fileId", "versionId");
+```
+
+
+
+
+
+
+#### ⚙️ Parameters
+
+
+-
+
+
+-
+
+**fileId:** `string` — The unique `fileId` of the uploaded file. `fileId` is returned in list and search assets API and upload API.
+
+
+
+
+
+-
+
+**versionId:** `string` — The unique `versionId` of the uploaded file. `versionId` is returned in list and search assets API and upload API.
+
+
+
+
+
+-
+
+**requestOptions:** `Versions.RequestOptions`
+
+
+
+
+
+
+
+
+
+
+client.files.versions.restore(fileId, versionId) -> ImageKit.FileDetails
+
+-
+
+#### 📝 Description
+
+
+-
+
+
+-
+
+This API restores a file version as the current file version.
+
+
+
+
+
+
+#### 🔌 Usage
+
+
+-
+
+
+-
+
+```typescript
+await client.files.versions.restore("fileId", "versionId");
+```
+
+
+
+
+
+
+#### ⚙️ Parameters
+
+
+-
+
+
+-
+
+**fileId:** `string` — The unique `fileId` of the uploaded file. `fileId` is returned in list and search assets API and upload API.
+
+
+
+
+
+-
+
+**versionId:** `string` — The unique `versionId` of the uploaded file. `versionId` is returned in list and search assets API and upload API.
+
+
+
+
+
+-
+
+**requestOptions:** `Versions.RequestOptions`
+
+
+
+
+
+
+
+
+
+
+## Files Metadata
+
+client.files.metadata.get(fileId) -> ImageKit.Metadata
+
+-
+
+#### 📝 Description
+
+
+-
+
+
+-
+
+You can programmatically get image EXIF, pHash, and other metadata for uploaded files in the ImageKit.io media library using this API.
+
+You can also get the metadata in upload API response by passing `metadata` in `responseFields` parameter.
+
+
+
+
+
+
+#### 🔌 Usage
+
+
+-
+
+
+-
+
+```typescript
+await client.files.metadata.get("fileId");
+```
+
+
+
+
+
+
+#### ⚙️ Parameters
+
+
+-
+
+
+-
+
+**fileId:** `string` — The unique `fileId` of the uploaded file. `fileId` is returned in the list and search assets API and upload API.
+
+
+
+
+
+-
+
+**requestOptions:** `Metadata.RequestOptions`
+
+
+
+
+
+
+
+
+
+
+client.files.metadata.getFromUrl({ ...params }) -> ImageKit.Metadata
+
+-
+
+#### 📝 Description
+
+
+-
+
+
+-
+
+Get image EXIF, pHash, and other metadata from ImageKit.io powered remote URL using this API.
+
+
+
+
+
+
+#### 🔌 Usage
+
+
+-
+
+
+-
+
+```typescript
+await client.files.metadata.getFromUrl({
+ url: "url",
+});
+```
+
+
+
+
+
+
+#### ⚙️ Parameters
+
+
+-
+
+
+-
+
+**request:** `ImageKit.files.MetadataGetFromUrlRequest`
+
+
+
+
+
+-
+
+**requestOptions:** `Metadata.RequestOptions`
+
+
+
+
+
+
+
+
+
+
+## Folders Job
+
+client.folders.job.get(jobId) -> ImageKit.JobGetResponse
+
+-
+
+#### 📝 Description
+
+
+-
+
+
+-
+
+This API returns the status of a bulk job like copy and move folder operations.
+
+
+
+
+
+
+#### 🔌 Usage
+
+
+-
+
+
+-
+
+```typescript
+await client.folders.job.get("jobId");
+```
+
+
+
+
+
+
+#### ⚙️ Parameters
+
+
+-
+
+
+-
+
+**jobId:** `string` — The `jobId` is returned in the response of bulk job API e.g. copy folder or move folder API.
+
+
+
+
+
+-
+
+**requestOptions:** `Job.RequestOptions`
+
+
+
+
+
+
+
+
+
diff --git a/sample/README.md b/sample/README.md
deleted file mode 100644
index bb0fdc28..00000000
--- a/sample/README.md
+++ /dev/null
@@ -1,19 +0,0 @@
-# Running the sample application
-
-### Step 1: Install dependencies
-```bash
-npm install
-```
-
-### Step 2: Enter account details
-Open `index.js` and fill the account details:
-```js
-const CONFIG_OPTIONS = {
- publicKey: "your_public_api_key",
- privateKey: "your_private_api_key",
- urlEndpoint: "https://ik.imagekit.io/your_imagekit_id/",
-};
-```
-
-### Step 3:
-Run the `index.js`
\ No newline at end of file
diff --git a/sample/index.js b/sample/index.js
deleted file mode 100644
index 032f2d96..00000000
--- a/sample/index.js
+++ /dev/null
@@ -1,292 +0,0 @@
-const ImageKit = require("imagekit");
-const fs = require("fs");
-const path = require("path");
-
-const CONFIG_OPTIONS = {
- publicKey: "your_public_api_key",
- privateKey: "your_private_api_key",
- urlEndpoint: "https://ik.imagekit.io/your_imagekit_id/",
-};
-
-const FILE_PATH = path.resolve(__dirname, "./test_image.jpg"),
- FILE_NAME = "test_image",
- IMG_URL =
- "https://images.pexels.com/photos/247676/pexels-photo-247676.jpeg?auto=compress&cs=tinysrgb&dpr=3&h=750&w=1260";
-
-const sampleApp = async () => {
- try {
- const imagekit = new ImageKit(CONFIG_OPTIONS);
-
- // Uploading images through binary
- let i = 0;
- while (i < 8) {
- const response = await uploadLocalFile(imagekit, FILE_PATH, `${FILE_NAME}_bin_${i + 1}`);
- console.log(`Binary upload response # ${i + 1}:`, JSON.stringify(response, undefined, 2), "\n");
- i++;
- }
-
- // Uploading images with base64
- const uploadResponse_base64 = await uploadFileBase64(imagekit, FILE_PATH, `${FILE_NAME}_base64`);
- console.log(`Base64 upload response:`, JSON.stringify(uploadResponse_base64, undefined, 2), "\n");
-
- // Uploading images with buffer
- const uploadResponse_buffer = await uploadFileBuffer(imagekit, FILE_PATH, `${FILE_NAME}_buffer`);
- console.log(`Buffer upload response:`, JSON.stringify(uploadResponse_buffer, undefined, 2), "\n");
-
- // Uploading images with URL
- const uploadResponse_url = await uploadFileURL(imagekit, IMG_URL, `${FILE_NAME}_url`);
- console.log(`URL upload response:`, JSON.stringify(uploadResponse_url, undefined, 2), "\n");
-
- // Listing Files
- const filesList = await listFiles(imagekit, 12, 0);
- console.log("List of first 10 files: ", JSON.stringify(filesList, undefined, 2), "\n");
-
- // Generating URLs
- const imageURL = imagekit.url({
- path: filesList[0].filePath,
- transformation: [
- {
- height: 300,
- width: 400,
- },
- ],
- });
- console.log("Url for first image transformed with height: 300, width: 400: ", imageURL, "\n");
-
- var signedUrl = imagekit.url({
- path: filesList[0].filePath,
- signed: true,
- transformation: [
- {
- height: 300,
- width: 400,
- },
- ],
- });
- console.log("Signed Url for first image transformed with height: 300, width: 400: ", signedUrl, "\n");
-
- // Get File Details
- const fileDetails_1 = await getFileDetails(imagekit, filesList[0].fileId);
- console.log("File Details fetched: ", JSON.stringify(fileDetails_1, undefined, 2), "\n");
-
- // Get File Metadata
- const fileMetadata_1 = await getFileMetadata(imagekit, filesList[0].fileId);
- const fileMetadata_2 = await getFileMetadata(imagekit, filesList[1].fileId);
- console.log("File metadata fetched: ", JSON.stringify(fileMetadata_1, undefined, 2), "\n");
-
- // Update File Details
- const fileUpdateResponse = await updateFileDetails(
- imagekit,
- filesList[0].fileId,
- ["buildings", "day"],
- "10,10,100,100",
- //Uncomment to send extensions parameter
- // [
- // {
- // name: "google-auto-tagging",
- // maxTags: 5,
- // minConfidence: 95
- // }
- // ]
- );
- console.log("File Update Response: ", JSON.stringify(fileUpdateResponse, undefined, 2), "\n");
-
- // pHash Distance
- console.log(fileMetadata_1.pHash, fileMetadata_2.pHash);
- const pHashDistance = imagekit.pHashDistance(fileMetadata_1.pHash, fileMetadata_2.pHash);
- console.log(`pHash distance: ${pHashDistance}`, "\n");
-
- // purge Cache and purgeCache status
- const purgeCacheResponse = await purgeCache(imagekit, filesList[0].url);
- console.log("Purge Cache Response: ", JSON.stringify(purgeCacheResponse, undefined, 2), "\n");
-
- const purgeStatus = await getPurgeCacheStatus(imagekit, purgeCacheResponse.requestId);
- console.log("Purge Response: ", JSON.stringify(purgeStatus, undefined, 2), "\n");
-
- // Bulk add tags
- let fileIds = filesList.map((file) => file.fileId);
- fileIds.shift();
- var tags = ["red", "blue"];
- const bulkAddTagsResponse = await bulkAddTags(imagekit, fileIds, tags);
- console.log("Bulk add tags response: ", bulkAddTagsResponse, "\n");
-
- // Bulk remove tags
- const bulkRemoveTagsResponse = await bulkRemoveTags(imagekit, fileIds, tags);
- console.log("Bulk remove tags response: ", bulkRemoveTagsResponse, "\n");
-
- // Create folder
- const createFolderResponse_1 = await createFolder(imagekit, "folder1", "/");
- const createFolderResponse_2 = await createFolder(imagekit, "folder2", "/");
- console.log("Folder creation response: ", createFolderResponse_2, "\n");
-
- // Copy file
- const copyFileResponse = await copyFile(imagekit, fileDetails_1.filePath, "/folder1/");
- console.log("File copy response: ", copyFileResponse, "\n");
-
- // Move file
- const moveFileResponse = await moveFile(imagekit, `/folder1/${fileDetails_1.name}`, "/folder2/");
- console.log("File move response: ", moveFileResponse, "\n");
-
- // Copy folder
- const copyFolderResponse = await copyFolder(imagekit, "/folder2", "/folder1/");
- console.log("Copy folder response: ", JSON.stringify(copyFolderResponse, undefined, 2), "\n");
-
- // Move folder
- const moveFolderResponse = await moveFolder(imagekit, "/folder1", "/folder2/");
- console.log("Move folder response: ", JSON.stringify(moveFolderResponse, undefined, 2), "\n");
-
- // Get bulk job status
- const getBulkJobStatusResponse = await getBulkJobStatus(imagekit, moveFolderResponse.jobId);
- console.log("Bulk job status response: ", JSON.stringify(getBulkJobStatusResponse), "\n");
-
- // Delete folder
- const deleteFolderResponse = await deleteFolder(imagekit, "/folder2/");
- console.log("Delete folder response: ", deleteFolderResponse, "\n");
-
- // Deleting Files
- const deleteResponse = await deleteFile(imagekit, fileDetails_1.fileId);
- console.log("Deletion response: ", deleteResponse, "\n");
-
- // Bulk Delete Files
- const bulkDeleteResponse = await bulkDeleteFiles(imagekit, fileIds);
- console.log("Bulk deletion response: ", bulkDeleteResponse, "\n");
-
- //Authentication token
- const authenticationParameters = imagekit.getAuthenticationParameters("your_token");
- console.log("Authentication Parameters: ", JSON.stringify(authenticationParameters, undefined, 2), "\n");
-
- process.exit(0);
- } catch (err) {
- console.log("Encounterted Error: ", JSON.stringify(err, undefined, 2));
- process.exit(1);
- }
-};
-
-const uploadLocalFile = async (imagekitInstance, filePath, fileName) => {
- const file = fs.createReadStream(filePath);
- const response = await imagekitInstance.upload({ file, fileName });
- return response;
-};
-
-const uploadFileBuffer = async (imagekitInstance, filePath, fileName) => {
- const buffer = fs.readFileSync(filePath);
- const response = await imagekitInstance.upload({ file: buffer, fileName });
- return response;
-};
-
-const uploadFileBase64 = async (imagekitInstance, filePath, fileName) => {
- const file_base64 = fs.readFileSync(filePath, "base64");
- //Uncomment to send extensions parameter
- // var extensions = [
- // {
- // name: "google-auto-tagging",
- // maxTags: 5,
- // minConfidence: 95
- // }
- // ];
- const response = await imagekitInstance.upload({ file: file_base64, fileName/*, extensions*/});
- return response;
-};
-
-const uploadFileURL = async (imagekitInstance, url, fileName) => {
- const response = await imagekitInstance.upload({ file: url, fileName });
- return response;
-};
-
-const listFiles = async (imagekitInstance, limit = 10, skip = 0) => {
- const response = await imagekitInstance.listFiles({
- limit,
- skip,
- });
- return response;
-};
-
-const getFileDetails = async (imagekitInstance, fileId) => {
- const response = await imagekitInstance.getFileDetails(fileId);
- return response;
-};
-
-const getFileMetadata = async (imagekitInstance, fileId) => {
- const response = await imagekitInstance.getFileMetadata(fileId);
- return response;
-};
-
-const updateFileDetails = async (imagekitInstance, fileId, tags = [], customCoordinates = "", extensions = [], webhookUrl = "") => {
- let options = {};
- if (Array.isArray(tags) && tags.length > 0) Object.assign(options, { tags });
- if (typeof customCoordinates === "string" && customCoordinates.length > 0)
- Object.assign(options, { customCoordinates });
- if (Array.isArray(extensions) && extensions.length > 0)
- Object.assign(options,{ extensions });
- if (typeof webhookUrl === "string" && webhookUrl.length > 0)
- Object.assign(options,{ webhookUrl })
- const response = await imagekitInstance.updateFileDetails(fileId, options);
- return response;
-};
-
-const purgeCache = async (imagekitInstance, url) => {
- const response = await imagekitInstance.purgeCache(url);
- return response;
-};
-
-const getPurgeCacheStatus = async (imagekitInstance, requestId) => {
- const response = await imagekitInstance.getPurgeCacheStatus(requestId);
- return response;
-};
-
-const deleteFile = async (imagekitInstance, fileId) => {
- const response = await imagekitInstance.deleteFile(fileId);
- return "success";
-};
-
-const bulkDeleteFiles = async (imagekitInstance, fileIds) => {
- const response = await imagekitInstance.bulkDeleteFiles(fileIds);
- return "success";
-};
-
-const bulkAddTags = async (imagekitInstance, fileIds, tags) => {
- const response = await imagekitInstance.bulkAddTags(fileIds, tags);
- return "success";
-};
-
-const bulkRemoveTags = async (imagekitInstance, fileIds, tags) => {
- const response = await imagekitInstance.bulkRemoveTags(fileIds, tags);
- return "success";
-};
-
-const copyFile = async (imagekitInstance, sourceFilePath, destinationPath) => {
- const response = await imagekitInstance.copyFile(sourceFilePath, destinationPath);
- return "success";
-};
-
-const moveFile = async (imagekitInstance, sourceFilePath, destinationPath) => {
- const response = await imagekitInstance.moveFile(sourceFilePath, destinationPath);
- return "success";
-};
-
-const copyFolder = async (imagekitInstance, sourceFolderPath, destinationPath) => {
- const response = await imagekitInstance.copyFolder(sourceFolderPath, destinationPath);
- return response;
-};
-
-const moveFolder = async (imagekitInstance, sourceFolderPath, destinationPath) => {
- const response = await imagekitInstance.moveFolder(sourceFolderPath, destinationPath);
- return response;
-};
-
-const createFolder = async (imagekitInstance, folderName, parentFolderPath) => {
- const response = await imagekitInstance.createFolder(folderName, parentFolderPath);
- return "success";
-};
-
-const deleteFolder = async (imagekitInstance, folderPath) => {
- const response = await imagekitInstance.deleteFolder(folderPath);
- return "success";
-};
-
-const getBulkJobStatus = async (imagekitInstance, jobId) => {
- const response = await imagekitInstance.getBulkJobStatus(jobId);
- return response;
-};
-
-sampleApp();
diff --git a/sample/package.json b/sample/package.json
deleted file mode 100644
index fb22c514..00000000
--- a/sample/package.json
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "name": "sample",
- "version": "1.0.0",
- "description": "",
- "main": "index.js",
- "scripts": {
- "test": "echo \"Error: no test specified\" && exit 1"
- },
- "dependencies": {
- "imagekit": "*"
- },
- "author": "",
- "license": "ISC"
-}
\ No newline at end of file
diff --git a/sample/test_image.jpg b/sample/test_image.jpg
deleted file mode 100644
index 8102e278..00000000
Binary files a/sample/test_image.jpg and /dev/null differ
diff --git a/scripts/rename-to-esm-files.js b/scripts/rename-to-esm-files.js
new file mode 100644
index 00000000..dc1df1cb
--- /dev/null
+++ b/scripts/rename-to-esm-files.js
@@ -0,0 +1,123 @@
+#!/usr/bin/env node
+
+const fs = require("fs").promises;
+const path = require("path");
+
+const extensionMap = {
+ ".js": ".mjs",
+ ".d.ts": ".d.mts",
+};
+const oldExtensions = Object.keys(extensionMap);
+
+async function findFiles(rootPath) {
+ const files = [];
+
+ async function scan(directory) {
+ const entries = await fs.readdir(directory, { withFileTypes: true });
+
+ for (const entry of entries) {
+ const fullPath = path.join(directory, entry.name);
+
+ if (entry.isDirectory()) {
+ if (entry.name !== "node_modules" && !entry.name.startsWith(".")) {
+ await scan(fullPath);
+ }
+ } else if (entry.isFile()) {
+ if (oldExtensions.some((ext) => entry.name.endsWith(ext))) {
+ files.push(fullPath);
+ }
+ }
+ }
+ }
+
+ await scan(rootPath);
+ return files;
+}
+
+async function updateFiles(files) {
+ const updatedFiles = [];
+ for (const file of files) {
+ const updated = await updateFileContents(file);
+ updatedFiles.push(updated);
+ }
+
+ console.log(`Updated imports in ${updatedFiles.length} files.`);
+}
+
+async function updateFileContents(file) {
+ const content = await fs.readFile(file, "utf8");
+
+ let newContent = content;
+ // Update each extension type defined in the map
+ for (const [oldExt, newExt] of Object.entries(extensionMap)) {
+ // Handle static imports/exports
+ const staticRegex = new RegExp(`(import|export)(.+from\\s+['"])(\\.\\.?\\/[^'"]+)(\\${oldExt})(['"])`, "g");
+ newContent = newContent.replace(staticRegex, `$1$2$3${newExt}$5`);
+
+ // Handle dynamic imports (yield import, await import, regular import())
+ const dynamicRegex = new RegExp(
+ `(yield\\s+import|await\\s+import|import)\\s*\\(\\s*['"](\\.\\.\?\\/[^'"]+)(\\${oldExt})['"]\\s*\\)`,
+ "g",
+ );
+ newContent = newContent.replace(dynamicRegex, `$1("$2${newExt}")`);
+ }
+
+ if (content !== newContent) {
+ await fs.writeFile(file, newContent, "utf8");
+ return true;
+ }
+ return false;
+}
+
+async function renameFiles(files) {
+ let counter = 0;
+ for (const file of files) {
+ const ext = oldExtensions.find((ext) => file.endsWith(ext));
+ const newExt = extensionMap[ext];
+
+ if (newExt) {
+ const newPath = file.slice(0, -ext.length) + newExt;
+ await fs.rename(file, newPath);
+ counter++;
+ }
+ }
+
+ console.log(`Renamed ${counter} files.`);
+}
+
+async function main() {
+ try {
+ const targetDir = process.argv[2];
+ if (!targetDir) {
+ console.error("Please provide a target directory");
+ process.exit(1);
+ }
+
+ const targetPath = path.resolve(targetDir);
+ const targetStats = await fs.stat(targetPath);
+
+ if (!targetStats.isDirectory()) {
+ console.error("The provided path is not a directory");
+ process.exit(1);
+ }
+
+ console.log(`Scanning directory: ${targetDir}`);
+
+ const files = await findFiles(targetDir);
+
+ if (files.length === 0) {
+ console.log("No matching files found.");
+ process.exit(0);
+ }
+
+ console.log(`Found ${files.length} files.`);
+ await updateFiles(files);
+ await renameFiles(files);
+ console.log("\nDone!");
+ } catch (error) {
+ console.error("An error occurred:", error.message);
+ process.exit(1);
+ }
+}
+
+main();
diff --git a/src/Client.ts b/src/Client.ts
new file mode 100644
index 00000000..b74fbcd5
--- /dev/null
+++ b/src/Client.ts
@@ -0,0 +1,95 @@
+/**
+ * This file was auto-generated by Fern from our API Definition.
+ */
+
+import * as environments from "./environments.js";
+import * as core from "./core/index.js";
+import { mergeHeaders } from "./core/headers.js";
+import { Files } from "./api/resources/files/client/Client.js";
+import { CustomMetadataFields } from "./api/resources/customMetadataFields/client/Client.js";
+import { Assets } from "./api/resources/assets/client/Client.js";
+import { Folders } from "./api/resources/folders/client/Client.js";
+import { Accounts } from "./api/resources/accounts/client/Client.js";
+import { Beta } from "./api/resources/beta/client/Client.js";
+import { Cache } from "./api/resources/cache/client/Client.js";
+
+export declare namespace ImageKitClient {
+ export interface Options {
+ environment?: core.Supplier;
+ /** Specify a custom URL to connect the client to. */
+ baseUrl?: core.Supplier;
+ username: core.Supplier;
+ password: core.Supplier;
+ /** Additional headers to include in requests. */
+ headers?: Record | undefined>;
+ }
+
+ export interface RequestOptions {
+ /** The maximum time to wait for a response in seconds. */
+ timeoutInSeconds?: number;
+ /** The number of times to retry the request. Defaults to 2. */
+ maxRetries?: number;
+ /** A hook to abort the request. */
+ abortSignal?: AbortSignal;
+ /** Additional query string parameters to include in the request. */
+ queryParams?: Record;
+ /** Additional headers to include in the request. */
+ headers?: Record | undefined>;
+ }
+}
+
+export class ImageKitClient {
+ protected readonly _options: ImageKitClient.Options;
+ protected _files: Files | undefined;
+ protected _customMetadataFields: CustomMetadataFields | undefined;
+ protected _assets: Assets | undefined;
+ protected _folders: Folders | undefined;
+ protected _accounts: Accounts | undefined;
+ protected _beta: Beta | undefined;
+ protected _cache: Cache | undefined;
+
+ constructor(_options: ImageKitClient.Options) {
+ this._options = {
+ ..._options,
+ headers: mergeHeaders(
+ {
+ "X-Fern-Language": "JavaScript",
+ "X-Fern-SDK-Name": "imagekit",
+ "X-Fern-SDK-Version": "6.0.1",
+ "User-Agent": "imagekit/6.0.1",
+ "X-Fern-Runtime": core.RUNTIME.type,
+ "X-Fern-Runtime-Version": core.RUNTIME.version,
+ },
+ _options?.headers,
+ ),
+ };
+ }
+
+ public get files(): Files {
+ return (this._files ??= new Files(this._options));
+ }
+
+ public get customMetadataFields(): CustomMetadataFields {
+ return (this._customMetadataFields ??= new CustomMetadataFields(this._options));
+ }
+
+ public get assets(): Assets {
+ return (this._assets ??= new Assets(this._options));
+ }
+
+ public get folders(): Folders {
+ return (this._folders ??= new Folders(this._options));
+ }
+
+ public get accounts(): Accounts {
+ return (this._accounts ??= new Accounts(this._options));
+ }
+
+ public get beta(): Beta {
+ return (this._beta ??= new Beta(this._options));
+ }
+
+ public get cache(): Cache {
+ return (this._cache ??= new Cache(this._options));
+ }
+}
diff --git a/src/api/errors/BadRequestError.ts b/src/api/errors/BadRequestError.ts
new file mode 100644
index 00000000..d33b883c
--- /dev/null
+++ b/src/api/errors/BadRequestError.ts
@@ -0,0 +1,18 @@
+/**
+ * This file was auto-generated by Fern from our API Definition.
+ */
+
+import * as errors from "../../errors/index.js";
+import * as core from "../../core/index.js";
+
+export class BadRequestError extends errors.ImageKitError {
+ constructor(body?: unknown, rawResponse?: core.RawResponse) {
+ super({
+ message: "BadRequestError",
+ statusCode: 400,
+ body: body,
+ rawResponse: rawResponse,
+ });
+ Object.setPrototypeOf(this, BadRequestError.prototype);
+ }
+}
diff --git a/src/api/errors/ConflictError.ts b/src/api/errors/ConflictError.ts
new file mode 100644
index 00000000..cbe77d7c
--- /dev/null
+++ b/src/api/errors/ConflictError.ts
@@ -0,0 +1,18 @@
+/**
+ * This file was auto-generated by Fern from our API Definition.
+ */
+
+import * as errors from "../../errors/index.js";
+import * as core from "../../core/index.js";
+
+export class ConflictError extends errors.ImageKitError {
+ constructor(body?: unknown, rawResponse?: core.RawResponse) {
+ super({
+ message: "ConflictError",
+ statusCode: 409,
+ body: body,
+ rawResponse: rawResponse,
+ });
+ Object.setPrototypeOf(this, ConflictError.prototype);
+ }
+}
diff --git a/src/api/errors/ForbiddenError.ts b/src/api/errors/ForbiddenError.ts
new file mode 100644
index 00000000..7534e402
--- /dev/null
+++ b/src/api/errors/ForbiddenError.ts
@@ -0,0 +1,18 @@
+/**
+ * This file was auto-generated by Fern from our API Definition.
+ */
+
+import * as errors from "../../errors/index.js";
+import * as core from "../../core/index.js";
+
+export class ForbiddenError extends errors.ImageKitError {
+ constructor(body?: unknown, rawResponse?: core.RawResponse) {
+ super({
+ message: "ForbiddenError",
+ statusCode: 403,
+ body: body,
+ rawResponse: rawResponse,
+ });
+ Object.setPrototypeOf(this, ForbiddenError.prototype);
+ }
+}
diff --git a/src/api/errors/LockedError.ts b/src/api/errors/LockedError.ts
new file mode 100644
index 00000000..6aea4953
--- /dev/null
+++ b/src/api/errors/LockedError.ts
@@ -0,0 +1,18 @@
+/**
+ * This file was auto-generated by Fern from our API Definition.
+ */
+
+import * as errors from "../../errors/index.js";
+import * as core from "../../core/index.js";
+
+export class LockedError extends errors.ImageKitError {
+ constructor(body?: unknown, rawResponse?: core.RawResponse) {
+ super({
+ message: "LockedError",
+ statusCode: 423,
+ body: body,
+ rawResponse: rawResponse,
+ });
+ Object.setPrototypeOf(this, LockedError.prototype);
+ }
+}
diff --git a/src/api/errors/NotFoundError.ts b/src/api/errors/NotFoundError.ts
new file mode 100644
index 00000000..2a451c05
--- /dev/null
+++ b/src/api/errors/NotFoundError.ts
@@ -0,0 +1,18 @@
+/**
+ * This file was auto-generated by Fern from our API Definition.
+ */
+
+import * as errors from "../../errors/index.js";
+import * as core from "../../core/index.js";
+
+export class NotFoundError extends errors.ImageKitError {
+ constructor(body?: unknown, rawResponse?: core.RawResponse) {
+ super({
+ message: "NotFoundError",
+ statusCode: 404,
+ body: body,
+ rawResponse: rawResponse,
+ });
+ Object.setPrototypeOf(this, NotFoundError.prototype);
+ }
+}
diff --git a/src/api/errors/TooManyRequestsError.ts b/src/api/errors/TooManyRequestsError.ts
new file mode 100644
index 00000000..7aaa7df9
--- /dev/null
+++ b/src/api/errors/TooManyRequestsError.ts
@@ -0,0 +1,18 @@
+/**
+ * This file was auto-generated by Fern from our API Definition.
+ */
+
+import * as errors from "../../errors/index.js";
+import * as core from "../../core/index.js";
+
+export class TooManyRequestsError extends errors.ImageKitError {
+ constructor(body?: unknown, rawResponse?: core.RawResponse) {
+ super({
+ message: "TooManyRequestsError",
+ statusCode: 429,
+ body: body,
+ rawResponse: rawResponse,
+ });
+ Object.setPrototypeOf(this, TooManyRequestsError.prototype);
+ }
+}
diff --git a/src/api/errors/UnauthorizedError.ts b/src/api/errors/UnauthorizedError.ts
new file mode 100644
index 00000000..3a07a93b
--- /dev/null
+++ b/src/api/errors/UnauthorizedError.ts
@@ -0,0 +1,18 @@
+/**
+ * This file was auto-generated by Fern from our API Definition.
+ */
+
+import * as errors from "../../errors/index.js";
+import * as core from "../../core/index.js";
+
+export class UnauthorizedError extends errors.ImageKitError {
+ constructor(body?: unknown, rawResponse?: core.RawResponse) {
+ super({
+ message: "UnauthorizedError",
+ statusCode: 401,
+ body: body,
+ rawResponse: rawResponse,
+ });
+ Object.setPrototypeOf(this, UnauthorizedError.prototype);
+ }
+}
diff --git a/src/api/errors/index.ts b/src/api/errors/index.ts
new file mode 100644
index 00000000..df15b79f
--- /dev/null
+++ b/src/api/errors/index.ts
@@ -0,0 +1,7 @@
+export * from "./BadRequestError.js";
+export * from "./UnauthorizedError.js";
+export * from "./ForbiddenError.js";
+export * from "./TooManyRequestsError.js";
+export * from "./NotFoundError.js";
+export * from "./ConflictError.js";
+export * from "./LockedError.js";
diff --git a/src/api/index.ts b/src/api/index.ts
new file mode 100644
index 00000000..72cddbe7
--- /dev/null
+++ b/src/api/index.ts
@@ -0,0 +1,3 @@
+export * from "./resources/index.js";
+export * from "./types/index.js";
+export * from "./errors/index.js";
diff --git a/src/api/resources/accounts/client/Client.ts b/src/api/resources/accounts/client/Client.ts
new file mode 100644
index 00000000..2509bbc1
--- /dev/null
+++ b/src/api/resources/accounts/client/Client.ts
@@ -0,0 +1,44 @@
+/**
+ * This file was auto-generated by Fern from our API Definition.
+ */
+
+import * as environments from "../../../../environments.js";
+import * as core from "../../../../core/index.js";
+import { Usage } from "../resources/usage/client/Client.js";
+import { Origins } from "../resources/origins/client/Client.js";
+import { UrlEndpoints } from "../resources/urlEndpoints/client/Client.js";
+
+export declare namespace Accounts {
+ export interface Options {
+ environment?: core.Supplier;
+ /** Specify a custom URL to connect the client to. */
+ baseUrl?: core.Supplier;
+ username: core.Supplier;
+ password: core.Supplier;
+ /** Additional headers to include in requests. */
+ headers?: Record | undefined>;
+ }
+}
+
+export class Accounts {
+ protected readonly _options: Accounts.Options;
+ protected _usage: Usage | undefined;
+ protected _origins: Origins | undefined;
+ protected _urlEndpoints: UrlEndpoints | undefined;
+
+ constructor(_options: Accounts.Options) {
+ this._options = _options;
+ }
+
+ public get usage(): Usage {
+ return (this._usage ??= new Usage(this._options));
+ }
+
+ public get origins(): Origins {
+ return (this._origins ??= new Origins(this._options));
+ }
+
+ public get urlEndpoints(): UrlEndpoints {
+ return (this._urlEndpoints ??= new UrlEndpoints(this._options));
+ }
+}
diff --git a/src/api/resources/accounts/client/index.ts b/src/api/resources/accounts/client/index.ts
new file mode 100644
index 00000000..cb0ff5c3
--- /dev/null
+++ b/src/api/resources/accounts/client/index.ts
@@ -0,0 +1 @@
+export {};
diff --git a/src/api/resources/accounts/index.ts b/src/api/resources/accounts/index.ts
new file mode 100644
index 00000000..02bb7065
--- /dev/null
+++ b/src/api/resources/accounts/index.ts
@@ -0,0 +1,2 @@
+export * from "./resources/index.js";
+export * from "./client/index.js";
diff --git a/src/api/resources/accounts/resources/index.ts b/src/api/resources/accounts/resources/index.ts
new file mode 100644
index 00000000..728b4188
--- /dev/null
+++ b/src/api/resources/accounts/resources/index.ts
@@ -0,0 +1,5 @@
+export * as usage from "./usage/index.js";
+export * from "./usage/types/index.js";
+export * as origins from "./origins/index.js";
+export * as urlEndpoints from "./urlEndpoints/index.js";
+export * from "./usage/client/requests/index.js";
diff --git a/src/api/resources/accounts/resources/origins/client/Client.ts b/src/api/resources/accounts/resources/origins/client/Client.ts
new file mode 100644
index 00000000..d47567fd
--- /dev/null
+++ b/src/api/resources/accounts/resources/origins/client/Client.ts
@@ -0,0 +1,483 @@
+/**
+ * This file was auto-generated by Fern from our API Definition.
+ */
+
+import * as environments from "../../../../../../environments.js";
+import * as core from "../../../../../../core/index.js";
+import * as ImageKit from "../../../../../index.js";
+import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../../../core/headers.js";
+import * as errors from "../../../../../../errors/index.js";
+
+export declare namespace Origins {
+ export interface Options {
+ environment?: core.Supplier;
+ /** Specify a custom URL to connect the client to. */
+ baseUrl?: core.Supplier;
+ username: core.Supplier;
+ password: core.Supplier;
+ /** Additional headers to include in requests. */
+ headers?: Record | undefined>;
+ }
+
+ export interface RequestOptions {
+ /** The maximum time to wait for a response in seconds. */
+ timeoutInSeconds?: number;
+ /** The number of times to retry the request. Defaults to 2. */
+ maxRetries?: number;
+ /** A hook to abort the request. */
+ abortSignal?: AbortSignal;
+ /** Additional query string parameters to include in the request. */
+ queryParams?: Record;
+ /** Additional headers to include in the request. */
+ headers?: Record | undefined>;
+ }
+}
+
+export class Origins {
+ protected readonly _options: Origins.Options;
+
+ constructor(_options: Origins.Options) {
+ this._options = _options;
+ }
+
+ /**
+ * **Note:** This API is currently in beta.
+ * Returns an array of all configured origins for the current account.
+ *
+ * @param {Origins.RequestOptions} requestOptions - Request-specific configuration.
+ *
+ * @throws {@link ImageKit.UnauthorizedError}
+ * @throws {@link ImageKit.ForbiddenError}
+ * @throws {@link ImageKit.TooManyRequestsError}
+ *
+ * @example
+ * await client.accounts.origins.list()
+ */
+ public list(requestOptions?: Origins.RequestOptions): core.HttpResponsePromise {
+ return core.HttpResponsePromise.fromPromise(this.__list(requestOptions));
+ }
+
+ private async __list(
+ requestOptions?: Origins.RequestOptions,
+ ): Promise> {
+ var _headers: core.Fetcher.Args["headers"] = mergeHeaders(
+ this._options?.headers,
+ mergeOnlyDefinedHeaders({ Authorization: await this._getAuthorizationHeader() }),
+ requestOptions?.headers,
+ );
+ const _response = await core.fetcher({
+ url: core.url.join(
+ (await core.Supplier.get(this._options.baseUrl)) ??
+ (await core.Supplier.get(this._options.environment)) ??
+ environments.ImageKitEnvironment.Default,
+ "v1/accounts/origins",
+ ),
+ method: "GET",
+ headers: _headers,
+ queryParameters: requestOptions?.queryParams,
+ timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000,
+ maxRetries: requestOptions?.maxRetries,
+ abortSignal: requestOptions?.abortSignal,
+ });
+ if (_response.ok) {
+ return { data: _response.body as ImageKit.OriginResponseArray, rawResponse: _response.rawResponse };
+ }
+
+ if (_response.error.reason === "status-code") {
+ switch (_response.error.statusCode) {
+ case 401:
+ throw new ImageKit.UnauthorizedError(_response.error.body as unknown, _response.rawResponse);
+ case 403:
+ throw new ImageKit.ForbiddenError(_response.error.body as unknown, _response.rawResponse);
+ case 429:
+ throw new ImageKit.TooManyRequestsError(_response.error.body as unknown, _response.rawResponse);
+ default:
+ throw new errors.ImageKitError({
+ statusCode: _response.error.statusCode,
+ body: _response.error.body,
+ rawResponse: _response.rawResponse,
+ });
+ }
+ }
+
+ switch (_response.error.reason) {
+ case "non-json":
+ throw new errors.ImageKitError({
+ statusCode: _response.error.statusCode,
+ body: _response.error.rawBody,
+ rawResponse: _response.rawResponse,
+ });
+ case "timeout":
+ throw new errors.ImageKitTimeoutError("Timeout exceeded when calling GET /v1/accounts/origins.");
+ case "unknown":
+ throw new errors.ImageKitError({
+ message: _response.error.errorMessage,
+ rawResponse: _response.rawResponse,
+ });
+ }
+ }
+
+ /**
+ * **Note:** This API is currently in beta.
+ * Creates a new origin and returns the origin object.
+ *
+ * @param {ImageKit.OriginSchema} request
+ * @param {Origins.RequestOptions} requestOptions - Request-specific configuration.
+ *
+ * @throws {@link ImageKit.BadRequestError}
+ * @throws {@link ImageKit.UnauthorizedError}
+ * @throws {@link ImageKit.ForbiddenError}
+ * @throws {@link ImageKit.TooManyRequestsError}
+ *
+ * @example
+ * await client.accounts.origins.create({
+ * type: "S3",
+ * name: "US S3 Storage",
+ * bucket: "product-images",
+ * accessKey: "AKIAIOSFODNN7EXAMPLE",
+ * secretKey: "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"
+ * })
+ */
+ public create(
+ request: ImageKit.OriginSchema,
+ requestOptions?: Origins.RequestOptions,
+ ): core.HttpResponsePromise {
+ return core.HttpResponsePromise.fromPromise(this.__create(request, requestOptions));
+ }
+
+ private async __create(
+ request: ImageKit.OriginSchema,
+ requestOptions?: Origins.RequestOptions,
+ ): Promise> {
+ var _headers: core.Fetcher.Args["headers"] = mergeHeaders(
+ this._options?.headers,
+ mergeOnlyDefinedHeaders({ Authorization: await this._getAuthorizationHeader() }),
+ requestOptions?.headers,
+ );
+ const _response = await core.fetcher({
+ url: core.url.join(
+ (await core.Supplier.get(this._options.baseUrl)) ??
+ (await core.Supplier.get(this._options.environment)) ??
+ environments.ImageKitEnvironment.Default,
+ "v1/accounts/origins",
+ ),
+ method: "POST",
+ headers: _headers,
+ contentType: "application/json",
+ queryParameters: requestOptions?.queryParams,
+ requestType: "json",
+ body: request,
+ timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000,
+ maxRetries: requestOptions?.maxRetries,
+ abortSignal: requestOptions?.abortSignal,
+ });
+ if (_response.ok) {
+ return { data: _response.body as ImageKit.OriginResponse, rawResponse: _response.rawResponse };
+ }
+
+ if (_response.error.reason === "status-code") {
+ switch (_response.error.statusCode) {
+ case 400:
+ throw new ImageKit.BadRequestError(_response.error.body as unknown, _response.rawResponse);
+ case 401:
+ throw new ImageKit.UnauthorizedError(_response.error.body as unknown, _response.rawResponse);
+ case 403:
+ throw new ImageKit.ForbiddenError(_response.error.body as unknown, _response.rawResponse);
+ case 429:
+ throw new ImageKit.TooManyRequestsError(_response.error.body as unknown, _response.rawResponse);
+ default:
+ throw new errors.ImageKitError({
+ statusCode: _response.error.statusCode,
+ body: _response.error.body,
+ rawResponse: _response.rawResponse,
+ });
+ }
+ }
+
+ switch (_response.error.reason) {
+ case "non-json":
+ throw new errors.ImageKitError({
+ statusCode: _response.error.statusCode,
+ body: _response.error.rawBody,
+ rawResponse: _response.rawResponse,
+ });
+ case "timeout":
+ throw new errors.ImageKitTimeoutError("Timeout exceeded when calling POST /v1/accounts/origins.");
+ case "unknown":
+ throw new errors.ImageKitError({
+ message: _response.error.errorMessage,
+ rawResponse: _response.rawResponse,
+ });
+ }
+ }
+
+ /**
+ * **Note:** This API is currently in beta.
+ * Retrieves the origin identified by `id`.
+ *
+ * @param {string} id - Unique identifier for the origin. This is generated by ImageKit when you create a new origin.
+ * @param {Origins.RequestOptions} requestOptions - Request-specific configuration.
+ *
+ * @throws {@link ImageKit.UnauthorizedError}
+ * @throws {@link ImageKit.ForbiddenError}
+ * @throws {@link ImageKit.NotFoundError}
+ * @throws {@link ImageKit.TooManyRequestsError}
+ *
+ * @example
+ * await client.accounts.origins.get("id")
+ */
+ public get(id: string, requestOptions?: Origins.RequestOptions): core.HttpResponsePromise {
+ return core.HttpResponsePromise.fromPromise(this.__get(id, requestOptions));
+ }
+
+ private async __get(
+ id: string,
+ requestOptions?: Origins.RequestOptions,
+ ): Promise> {
+ var _headers: core.Fetcher.Args["headers"] = mergeHeaders(
+ this._options?.headers,
+ mergeOnlyDefinedHeaders({ Authorization: await this._getAuthorizationHeader() }),
+ requestOptions?.headers,
+ );
+ const _response = await core.fetcher({
+ url: core.url.join(
+ (await core.Supplier.get(this._options.baseUrl)) ??
+ (await core.Supplier.get(this._options.environment)) ??
+ environments.ImageKitEnvironment.Default,
+ `v1/accounts/origins/${encodeURIComponent(id)}`,
+ ),
+ method: "GET",
+ headers: _headers,
+ queryParameters: requestOptions?.queryParams,
+ timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000,
+ maxRetries: requestOptions?.maxRetries,
+ abortSignal: requestOptions?.abortSignal,
+ });
+ if (_response.ok) {
+ return { data: _response.body as ImageKit.OriginResponse, rawResponse: _response.rawResponse };
+ }
+
+ if (_response.error.reason === "status-code") {
+ switch (_response.error.statusCode) {
+ case 401:
+ throw new ImageKit.UnauthorizedError(_response.error.body as unknown, _response.rawResponse);
+ case 403:
+ throw new ImageKit.ForbiddenError(_response.error.body as unknown, _response.rawResponse);
+ case 404:
+ throw new ImageKit.NotFoundError(_response.error.body as unknown, _response.rawResponse);
+ case 429:
+ throw new ImageKit.TooManyRequestsError(_response.error.body as unknown, _response.rawResponse);
+ default:
+ throw new errors.ImageKitError({
+ statusCode: _response.error.statusCode,
+ body: _response.error.body,
+ rawResponse: _response.rawResponse,
+ });
+ }
+ }
+
+ switch (_response.error.reason) {
+ case "non-json":
+ throw new errors.ImageKitError({
+ statusCode: _response.error.statusCode,
+ body: _response.error.rawBody,
+ rawResponse: _response.rawResponse,
+ });
+ case "timeout":
+ throw new errors.ImageKitTimeoutError("Timeout exceeded when calling GET /v1/accounts/origins/{id}.");
+ case "unknown":
+ throw new errors.ImageKitError({
+ message: _response.error.errorMessage,
+ rawResponse: _response.rawResponse,
+ });
+ }
+ }
+
+ /**
+ * **Note:** This API is currently in beta.
+ * Updates the origin identified by `id` and returns the updated origin object.
+ *
+ * @param {string} id - Unique identifier for the origin. This is generated by ImageKit when you create a new origin.
+ * @param {ImageKit.OriginSchema} request
+ * @param {Origins.RequestOptions} requestOptions - Request-specific configuration.
+ *
+ * @throws {@link ImageKit.BadRequestError}
+ * @throws {@link ImageKit.UnauthorizedError}
+ * @throws {@link ImageKit.ForbiddenError}
+ * @throws {@link ImageKit.NotFoundError}
+ * @throws {@link ImageKit.TooManyRequestsError}
+ *
+ * @example
+ * await client.accounts.origins.update("id", {
+ * type: "S3",
+ * name: "US S3 Storage",
+ * bucket: "product-images",
+ * accessKey: "AKIAIOSFODNN7EXAMPLE",
+ * secretKey: "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"
+ * })
+ */
+ public update(
+ id: string,
+ request: ImageKit.OriginSchema,
+ requestOptions?: Origins.RequestOptions,
+ ): core.HttpResponsePromise {
+ return core.HttpResponsePromise.fromPromise(this.__update(id, request, requestOptions));
+ }
+
+ private async __update(
+ id: string,
+ request: ImageKit.OriginSchema,
+ requestOptions?: Origins.RequestOptions,
+ ): Promise> {
+ var _headers: core.Fetcher.Args["headers"] = mergeHeaders(
+ this._options?.headers,
+ mergeOnlyDefinedHeaders({ Authorization: await this._getAuthorizationHeader() }),
+ requestOptions?.headers,
+ );
+ const _response = await core.fetcher({
+ url: core.url.join(
+ (await core.Supplier.get(this._options.baseUrl)) ??
+ (await core.Supplier.get(this._options.environment)) ??
+ environments.ImageKitEnvironment.Default,
+ `v1/accounts/origins/${encodeURIComponent(id)}`,
+ ),
+ method: "PUT",
+ headers: _headers,
+ contentType: "application/json",
+ queryParameters: requestOptions?.queryParams,
+ requestType: "json",
+ body: request,
+ timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000,
+ maxRetries: requestOptions?.maxRetries,
+ abortSignal: requestOptions?.abortSignal,
+ });
+ if (_response.ok) {
+ return { data: _response.body as ImageKit.OriginResponse, rawResponse: _response.rawResponse };
+ }
+
+ if (_response.error.reason === "status-code") {
+ switch (_response.error.statusCode) {
+ case 400:
+ throw new ImageKit.BadRequestError(_response.error.body as unknown, _response.rawResponse);
+ case 401:
+ throw new ImageKit.UnauthorizedError(_response.error.body as unknown, _response.rawResponse);
+ case 403:
+ throw new ImageKit.ForbiddenError(_response.error.body as unknown, _response.rawResponse);
+ case 404:
+ throw new ImageKit.NotFoundError(_response.error.body as unknown, _response.rawResponse);
+ case 429:
+ throw new ImageKit.TooManyRequestsError(_response.error.body as unknown, _response.rawResponse);
+ default:
+ throw new errors.ImageKitError({
+ statusCode: _response.error.statusCode,
+ body: _response.error.body,
+ rawResponse: _response.rawResponse,
+ });
+ }
+ }
+
+ switch (_response.error.reason) {
+ case "non-json":
+ throw new errors.ImageKitError({
+ statusCode: _response.error.statusCode,
+ body: _response.error.rawBody,
+ rawResponse: _response.rawResponse,
+ });
+ case "timeout":
+ throw new errors.ImageKitTimeoutError("Timeout exceeded when calling PUT /v1/accounts/origins/{id}.");
+ case "unknown":
+ throw new errors.ImageKitError({
+ message: _response.error.errorMessage,
+ rawResponse: _response.rawResponse,
+ });
+ }
+ }
+
+ /**
+ * **Note:** This API is currently in beta.
+ * Permanently removes the origin identified by `id`. If the origin is in use by any URL‑endpoints, the API will return an error.
+ *
+ * @param {string} id - Unique identifier for the origin. This is generated by ImageKit when you create a new origin.
+ * @param {Origins.RequestOptions} requestOptions - Request-specific configuration.
+ *
+ * @throws {@link ImageKit.UnauthorizedError}
+ * @throws {@link ImageKit.ForbiddenError}
+ * @throws {@link ImageKit.NotFoundError}
+ * @throws {@link ImageKit.TooManyRequestsError}
+ *
+ * @example
+ * await client.accounts.origins.delete("id")
+ */
+ public delete(id: string, requestOptions?: Origins.RequestOptions): core.HttpResponsePromise {
+ return core.HttpResponsePromise.fromPromise(this.__delete(id, requestOptions));
+ }
+
+ private async __delete(id: string, requestOptions?: Origins.RequestOptions): Promise> {
+ var _headers: core.Fetcher.Args["headers"] = mergeHeaders(
+ this._options?.headers,
+ mergeOnlyDefinedHeaders({ Authorization: await this._getAuthorizationHeader() }),
+ requestOptions?.headers,
+ );
+ const _response = await core.fetcher({
+ url: core.url.join(
+ (await core.Supplier.get(this._options.baseUrl)) ??
+ (await core.Supplier.get(this._options.environment)) ??
+ environments.ImageKitEnvironment.Default,
+ `v1/accounts/origins/${encodeURIComponent(id)}`,
+ ),
+ method: "DELETE",
+ headers: _headers,
+ queryParameters: requestOptions?.queryParams,
+ timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000,
+ maxRetries: requestOptions?.maxRetries,
+ abortSignal: requestOptions?.abortSignal,
+ });
+ if (_response.ok) {
+ return { data: undefined, rawResponse: _response.rawResponse };
+ }
+
+ if (_response.error.reason === "status-code") {
+ switch (_response.error.statusCode) {
+ case 401:
+ throw new ImageKit.UnauthorizedError(_response.error.body as unknown, _response.rawResponse);
+ case 403:
+ throw new ImageKit.ForbiddenError(_response.error.body as unknown, _response.rawResponse);
+ case 404:
+ throw new ImageKit.NotFoundError(_response.error.body as unknown, _response.rawResponse);
+ case 429:
+ throw new ImageKit.TooManyRequestsError(_response.error.body as unknown, _response.rawResponse);
+ default:
+ throw new errors.ImageKitError({
+ statusCode: _response.error.statusCode,
+ body: _response.error.body,
+ rawResponse: _response.rawResponse,
+ });
+ }
+ }
+
+ switch (_response.error.reason) {
+ case "non-json":
+ throw new errors.ImageKitError({
+ statusCode: _response.error.statusCode,
+ body: _response.error.rawBody,
+ rawResponse: _response.rawResponse,
+ });
+ case "timeout":
+ throw new errors.ImageKitTimeoutError(
+ "Timeout exceeded when calling DELETE /v1/accounts/origins/{id}.",
+ );
+ case "unknown":
+ throw new errors.ImageKitError({
+ message: _response.error.errorMessage,
+ rawResponse: _response.rawResponse,
+ });
+ }
+ }
+
+ protected async _getAuthorizationHeader(): Promise {
+ return core.BasicAuth.toAuthorizationHeader({
+ username: await core.Supplier.get(this._options.username),
+ password: await core.Supplier.get(this._options.password),
+ });
+ }
+}
diff --git a/src/api/resources/accounts/resources/origins/client/index.ts b/src/api/resources/accounts/resources/origins/client/index.ts
new file mode 100644
index 00000000..cb0ff5c3
--- /dev/null
+++ b/src/api/resources/accounts/resources/origins/client/index.ts
@@ -0,0 +1 @@
+export {};
diff --git a/src/api/resources/accounts/resources/origins/index.ts b/src/api/resources/accounts/resources/origins/index.ts
new file mode 100644
index 00000000..914b8c3c
--- /dev/null
+++ b/src/api/resources/accounts/resources/origins/index.ts
@@ -0,0 +1 @@
+export * from "./client/index.js";
diff --git a/src/api/resources/accounts/resources/urlEndpoints/client/Client.ts b/src/api/resources/accounts/resources/urlEndpoints/client/Client.ts
new file mode 100644
index 00000000..63c1593e
--- /dev/null
+++ b/src/api/resources/accounts/resources/urlEndpoints/client/Client.ts
@@ -0,0 +1,497 @@
+/**
+ * This file was auto-generated by Fern from our API Definition.
+ */
+
+import * as environments from "../../../../../../environments.js";
+import * as core from "../../../../../../core/index.js";
+import * as ImageKit from "../../../../../index.js";
+import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../../../core/headers.js";
+import * as errors from "../../../../../../errors/index.js";
+
+export declare namespace UrlEndpoints {
+ export interface Options {
+ environment?: core.Supplier;
+ /** Specify a custom URL to connect the client to. */
+ baseUrl?: core.Supplier;
+ username: core.Supplier;
+ password: core.Supplier;
+ /** Additional headers to include in requests. */
+ headers?: Record | undefined>;
+ }
+
+ export interface RequestOptions {
+ /** The maximum time to wait for a response in seconds. */
+ timeoutInSeconds?: number;
+ /** The number of times to retry the request. Defaults to 2. */
+ maxRetries?: number;
+ /** A hook to abort the request. */
+ abortSignal?: AbortSignal;
+ /** Additional query string parameters to include in the request. */
+ queryParams?: Record;
+ /** Additional headers to include in the request. */
+ headers?: Record | undefined>;
+ }
+}
+
+export class UrlEndpoints {
+ protected readonly _options: UrlEndpoints.Options;
+
+ constructor(_options: UrlEndpoints.Options) {
+ this._options = _options;
+ }
+
+ /**
+ * **Note:** This API is currently in beta.
+ * Returns an array of all URL‑endpoints configured including the default URL-endpoint generated by ImageKit during account creation.
+ *
+ * @param {UrlEndpoints.RequestOptions} requestOptions - Request-specific configuration.
+ *
+ * @throws {@link ImageKit.UnauthorizedError}
+ * @throws {@link ImageKit.ForbiddenError}
+ * @throws {@link ImageKit.NotFoundError}
+ * @throws {@link ImageKit.TooManyRequestsError}
+ *
+ * @example
+ * await client.accounts.urlEndpoints.list()
+ */
+ public list(
+ requestOptions?: UrlEndpoints.RequestOptions,
+ ): core.HttpResponsePromise {
+ return core.HttpResponsePromise.fromPromise(this.__list(requestOptions));
+ }
+
+ private async __list(
+ requestOptions?: UrlEndpoints.RequestOptions,
+ ): Promise