imagekit-javascript
Advanced tools
Comparing version
@@ -164,3 +164,3 @@ 'use strict'; | ||
var version = "3.0.2"; | ||
var version = "3.1.0"; | ||
@@ -414,23 +414,27 @@ var errorMessages = { | ||
aspectRatio: "ar", | ||
quality: "q", | ||
background: "bg", | ||
border: "b", | ||
crop: "c", | ||
cropMode: "cm", | ||
dpr: "dpr", | ||
focus: "fo", | ||
quality: "q", | ||
x: "x", | ||
xCenter: "xc", | ||
y: "y", | ||
yCenter: "yc", | ||
format: "f", | ||
videoCodec: "vc", | ||
audioCodec: "ac", | ||
radius: "r", | ||
background: "bg", | ||
border: "b", | ||
rotation: "rt", | ||
rotate: "rt", | ||
blur: "bl", | ||
named: "n", | ||
progressive: "pr", | ||
lossless: "lo", | ||
trim: "t", | ||
metadata: "md", | ||
colorProfile: "cp", | ||
defaultImage: "di", | ||
dpr: "dpr", | ||
flip: "fl", | ||
original: "orig", | ||
startOffset: "so", | ||
endOffset: "eo", | ||
duration: "du", | ||
streamingResolutions: "sr", | ||
effectSharpen: "e-sharpen", | ||
@@ -440,5 +444,26 @@ effectUSM: "e-usm", | ||
effectGray: "e-grayscale", | ||
original: "orig", | ||
effectShadow: "e-shadow", | ||
effectGradient: "e-gradient", | ||
rotate: "rt", | ||
grayscale: "e-grayscale", | ||
aiUpscale: "e-upscale", | ||
aiRetouch: "e-retouch", | ||
aiVariation: "e-genvar", | ||
aiDropShadow: "e-dropshadow", | ||
aiChangeBackground: "e-changebg", | ||
aiRemoveBackground: "e-bgremove", | ||
aiRemoveBackgroundExternal: "e-removedotbg", | ||
contrastStretch: "e-contrast", | ||
shadow: "e-shadow", | ||
sharpen: "e-sharpen", | ||
unsharpMask: "e-usm", | ||
gradient: "e-gradient", | ||
progressive: "pr", | ||
lossless: "lo", | ||
colorProfile: "cp", | ||
metadata: "md", | ||
opacity: "o", | ||
trim: "t", | ||
zoom: "z", | ||
page: "pg", | ||
raw: "raw" | ||
@@ -542,3 +567,6 @@ }; | ||
for (var key in transformation[i]) { | ||
if (transformation[i][key] === undefined || transformation[i][key] === null) continue; | ||
var value = transformation[i][key]; | ||
if (value === undefined || value === null) { | ||
continue; | ||
} | ||
var transformKey = transformationUtils.getTransformKey(key); | ||
@@ -548,3 +576,12 @@ if (!transformKey) { | ||
} | ||
if (transformation[i][key] === "-") { | ||
if (transformKey === "") { | ||
continue; | ||
} | ||
if (["e-grayscale", "e-contrast", "e-removedotbg", "e-bgremove", "e-upscale", "e-retouch", "e-genvar"].includes(transformKey)) { | ||
if (value === true || value === "-" || value === "true") { | ||
parsedTransformStep.push(transformKey); | ||
} else { | ||
continue; | ||
} | ||
} else if (["e-sharpen", "e-shadow", "e-gradient", "e-usm", "e-dropshadow"].includes(transformKey) && (value.toString().trim() === "" || value === true || value === "true")) { | ||
parsedTransformStep.push(transformKey); | ||
@@ -554,3 +591,2 @@ } else if (key === "raw") { | ||
} else { | ||
var value = transformation[i][key]; | ||
if (transformKey === "di") { | ||
@@ -560,6 +596,14 @@ value = removeTrailingSlash(removeLeadingSlash(value || "")); | ||
} | ||
if (transformKey === "sr" && Array.isArray(value)) { | ||
value = value.join("_"); | ||
} | ||
if (transformKey === "t" && value.toString().trim() === "") { | ||
value = "true"; | ||
} | ||
parsedTransformStep.push([transformKey, value].join(transformationUtils.getTransformKeyValueDelimiter())); | ||
} | ||
} | ||
parsedTransforms.push(parsedTransformStep.join(transformationUtils.getTransformDelimiter())); | ||
if (parsedTransformStep.length) { | ||
parsedTransforms.push(parsedTransformStep.join(transformationUtils.getTransformDelimiter())); | ||
} | ||
} | ||
@@ -566,0 +610,0 @@ return parsedTransforms.join(transformationUtils.getChainTransformDelimiter()); |
@@ -162,3 +162,3 @@ function _typeof(obj) { | ||
var version = "3.0.2"; | ||
var version = "3.1.0"; | ||
@@ -412,23 +412,27 @@ var errorMessages = { | ||
aspectRatio: "ar", | ||
quality: "q", | ||
background: "bg", | ||
border: "b", | ||
crop: "c", | ||
cropMode: "cm", | ||
dpr: "dpr", | ||
focus: "fo", | ||
quality: "q", | ||
x: "x", | ||
xCenter: "xc", | ||
y: "y", | ||
yCenter: "yc", | ||
format: "f", | ||
videoCodec: "vc", | ||
audioCodec: "ac", | ||
radius: "r", | ||
background: "bg", | ||
border: "b", | ||
rotation: "rt", | ||
rotate: "rt", | ||
blur: "bl", | ||
named: "n", | ||
progressive: "pr", | ||
lossless: "lo", | ||
trim: "t", | ||
metadata: "md", | ||
colorProfile: "cp", | ||
defaultImage: "di", | ||
dpr: "dpr", | ||
flip: "fl", | ||
original: "orig", | ||
startOffset: "so", | ||
endOffset: "eo", | ||
duration: "du", | ||
streamingResolutions: "sr", | ||
effectSharpen: "e-sharpen", | ||
@@ -438,5 +442,26 @@ effectUSM: "e-usm", | ||
effectGray: "e-grayscale", | ||
original: "orig", | ||
effectShadow: "e-shadow", | ||
effectGradient: "e-gradient", | ||
rotate: "rt", | ||
grayscale: "e-grayscale", | ||
aiUpscale: "e-upscale", | ||
aiRetouch: "e-retouch", | ||
aiVariation: "e-genvar", | ||
aiDropShadow: "e-dropshadow", | ||
aiChangeBackground: "e-changebg", | ||
aiRemoveBackground: "e-bgremove", | ||
aiRemoveBackgroundExternal: "e-removedotbg", | ||
contrastStretch: "e-contrast", | ||
shadow: "e-shadow", | ||
sharpen: "e-sharpen", | ||
unsharpMask: "e-usm", | ||
gradient: "e-gradient", | ||
progressive: "pr", | ||
lossless: "lo", | ||
colorProfile: "cp", | ||
metadata: "md", | ||
opacity: "o", | ||
trim: "t", | ||
zoom: "z", | ||
page: "pg", | ||
raw: "raw" | ||
@@ -540,3 +565,6 @@ }; | ||
for (var key in transformation[i]) { | ||
if (transformation[i][key] === undefined || transformation[i][key] === null) continue; | ||
var value = transformation[i][key]; | ||
if (value === undefined || value === null) { | ||
continue; | ||
} | ||
var transformKey = transformationUtils.getTransformKey(key); | ||
@@ -546,3 +574,12 @@ if (!transformKey) { | ||
} | ||
if (transformation[i][key] === "-") { | ||
if (transformKey === "") { | ||
continue; | ||
} | ||
if (["e-grayscale", "e-contrast", "e-removedotbg", "e-bgremove", "e-upscale", "e-retouch", "e-genvar"].includes(transformKey)) { | ||
if (value === true || value === "-" || value === "true") { | ||
parsedTransformStep.push(transformKey); | ||
} else { | ||
continue; | ||
} | ||
} else if (["e-sharpen", "e-shadow", "e-gradient", "e-usm", "e-dropshadow"].includes(transformKey) && (value.toString().trim() === "" || value === true || value === "true")) { | ||
parsedTransformStep.push(transformKey); | ||
@@ -552,3 +589,2 @@ } else if (key === "raw") { | ||
} else { | ||
var value = transformation[i][key]; | ||
if (transformKey === "di") { | ||
@@ -558,6 +594,14 @@ value = removeTrailingSlash(removeLeadingSlash(value || "")); | ||
} | ||
if (transformKey === "sr" && Array.isArray(value)) { | ||
value = value.join("_"); | ||
} | ||
if (transformKey === "t" && value.toString().trim() === "") { | ||
value = "true"; | ||
} | ||
parsedTransformStep.push([transformKey, value].join(transformationUtils.getTransformKeyValueDelimiter())); | ||
} | ||
} | ||
parsedTransforms.push(parsedTransformStep.join(transformationUtils.getTransformDelimiter())); | ||
if (parsedTransformStep.length) { | ||
parsedTransforms.push(parsedTransformStep.join(transformationUtils.getTransformDelimiter())); | ||
} | ||
} | ||
@@ -564,0 +608,0 @@ return parsedTransforms.join(transformationUtils.getChainTransformDelimiter()); |
@@ -1,1 +0,1 @@ | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).ImageKit=t()}(this,(function(){"use strict";function e(t){return(e="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(t)}function t(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}function r(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function n(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function o(e){for(var t=1;t<arguments.length;t++){var o=null!=arguments[t]?arguments[t]:{};t%2?n(Object(o),!0).forEach((function(t){r(e,t,o[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(o)):n(Object(o)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(o,t))}))}return e}function a(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function i(e,t){var r;if("undefined"==typeof Symbol||null==e[Symbol.iterator]){if(Array.isArray(e)||(r=function(e,t){if(e){if("string"==typeof e)return a(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?a(e,t):void 0}}(e))||t&&e&&"number"==typeof e.length){r&&(e=r);var n=0,o=function(){};return{s:o,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:o}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,s=!0,u=!1;return{s:function(){r=e[Symbol.iterator]()},n:function(){var e=r.next();return s=e.done,e},e:function(e){u=!0,i=e},f:function(){try{s||null==r.return||r.return()}finally{if(u)throw i}}}}var s={message:"Missing urlEndpoint during SDK initialization",help:""},u={message:"Invalid transformationPosition parameter",help:""},f={message:"Missing file parameter for upload",help:""},p={message:"Missing fileName parameter for upload",help:""},l={message:"Missing public key for upload",help:""},c={message:"Request to ImageKit upload endpoint failed due to network error",help:""},d={message:"Invalid uploadOptions parameter",help:""},m={message:"Missing signature for upload. The SDK expects token, signature and expire for authentication.",help:""},y={message:"Missing token for upload. The SDK expects token, signature and expire for authentication.",help:""},h={message:"Missing expire for upload. The SDK expects token, signature and expire for authentication.",help:""},g={message:"Invalid transformation parameter. Please include at least pre, post, or both.",help:""},b={message:"Invalid pre transformation parameter.",help:""},v={message:"Invalid post transformation parameter.",help:""};function w(e,t,r){"function"==typeof r&&(e?r(t,null):r(null,t))}function O(e){var t={},r=e.getAllResponseHeaders();return Object.keys(r).length&&r.trim().split(/[\r\n]+/).map((function(e){return e.split(/: /)})).forEach((function(e){t[e[0].trim()]=e[1].trim()})),t}var j=function(e,t){var r=o({},e),n={statusCode:t.status,headers:O(t)};return Object.defineProperty(r,"$ResponseMetadata",{value:n,enumerable:!1,writable:!1}),r},S=function(e,t){return new Promise((function(r,n){e.open("POST","https://upload.imagekit.io/api/v1/files/upload"),e.onerror=function(e){return n(c)},e.onload=function(){if(200===e.status)try{var t=JSON.parse(e.responseText),o=j(t,e);return r(o)}catch(e){return n(e)}else try{t=JSON.parse(e.responseText);var a=j(t,e);return n(a)}catch(e){return n(e)}},e.send(t)}))},k=function(t,r,n,o){if(r.file)if(r.fileName)if(n.publicKey)if(r.token)if(r.signature)if(r.expire){if(r.transformation){if(!Object.keys(r.transformation).includes("pre")&&!Object.keys(r.transformation).includes("post"))return void w(!0,g,o);if(Object.keys(r.transformation).includes("pre")&&!r.transformation.pre)return void w(!0,b,o);if(Object.keys(r.transformation).includes("post")){if(!Array.isArray(r.transformation.post))return void w(!0,v,o);var a,s=i(r.transformation.post);try{for(s.s();!(a=s.n()).done;){var u=a.value;if("abs"===u.type&&!u.protocol&&!u.value)return void w(!0,v,o);if("transformation"===u.type&&!u.value)return void w(!0,v,o)}}catch(e){s.e(e)}finally{s.f()}}}var c,d=new FormData;for(c in r)c&&("file"===c&&"string"!=typeof r.file?d.append("file",r.file,String(r.fileName)):"tags"===c&&Array.isArray(r.tags)?d.append("tags",r.tags.join(",")):"signature"===c?d.append("signature",r.signature):"expire"===c?d.append("expire",String(r.expire)):"token"===c?d.append("token",r.token):"responseFields"===c&&Array.isArray(r.responseFields)?d.append("responseFields",r.responseFields.join(",")):"extensions"===c&&Array.isArray(r.extensions)?d.append("extensions",JSON.stringify(r.extensions)):"customMetadata"!==c||"object"!==e(r.customMetadata)||Array.isArray(r.customMetadata)||null===r.customMetadata?"transformation"===c&&"object"===e(r.transformation)&&null!==r.transformation?d.append(c,JSON.stringify(r.transformation)):"checks"===c&&r.checks?d.append("checks",r.checks):void 0!==r[c]&&d.append(c,String(r[c])):d.append("customMetadata",JSON.stringify(r.customMetadata)));d.append("publicKey",n.publicKey),function(e,t,r){S(e,t).then((function(e){return w(!1,e,r)}),(function(e){return w(!0,e,r)}))}(t,d,o)}else w(!0,h,o);else w(!0,m,o);else w(!0,y,o);else w(!0,l,o);else w(!0,p,o);else w(!0,f,o)},x={width:"w",height:"h",aspectRatio:"ar",quality:"q",crop:"c",cropMode:"cm",focus:"fo",x:"x",y:"y",format:"f",radius:"r",background:"bg",border:"b",rotation:"rt",rotate:"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",original:"orig",effectShadow:"e-shadow",effectGradient:"e-gradient",raw:"raw"},P=["path","query"],A=function(){return"path"},M=function(e){return"query"===e.transformationPosition},E=function(e){return void 0!==e.transformationPosition&&-1!=P.indexOf(e.transformationPosition)},I=function(e){return e&&(x[e]||x[e.toLowerCase()])||""},K=function(){return":"},T=function(){return","},D=function(){return"-"};function R(e){return"string"==typeof e&&"/"==e[e.length-1]&&(e=e.substring(0,e.length-1)),e}function q(e,t){var r=t||"/",n=new RegExp(r+"{1,}","g");return e.join(r).replace(n,r)}var N=function(e){if(!e.path&&!e.src)return"";var t,r,n;try{e.path?(n=new URL(e.urlEndpoint).pathname,t=new URL(q([e.urlEndpoint.replace(n,""),e.path]))):(t=new URL(e.src),r=!0)}catch(e){return console.error(e),""}for(var o in e.queryParameters)t.searchParams.append(o,String(e.queryParameters[o]));var a=function(e){if(!Array.isArray(e))return"";for(var t=[],r=0,n=e.length;r<n;r++){var o=[];for(var a in e[r])if(void 0!==e[r][a]&&null!==e[r][a]){var i=I(a);if(i||(i=a),"-"===e[r][a])o.push(i);else if("raw"===a)o.push(e[r][a]);else{var s=e[r][a];"di"===i&&(s=(s=R(("string"==typeof(u=s||"")&&"/"==u[0]&&(u=u.slice(1)),u))).replace(/\//g,"@@")),o.push([i,s].join(D()))}}t.push(o.join(T()))}var u;return t.join(K())}(e.transformation);return a&&a.length&&(M(e)||r?t.searchParams.append("tr",a):t.pathname=q(["tr"+K()+a,t.pathname])),t.pathname=q(n?[n,t.pathname]:[t.pathname]),t.href};return function(){function n(e){if(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,n),r(this,"options",{sdkVersion:"javascript-".concat("3.0.2"),publicKey:"",urlEndpoint:"",transformationPosition:A()}),this.options=o(o({},this.options),e||{}),!this.options.urlEndpoint)throw s;if(!E(this.options))throw u}var a,i,f;return a=n,(i=[{key:"url",value:function(e){return t=e,r=this.options,N(o(o({},r),t));var t,r}},{key:"upload",value:function(t,r,n){var a;if("function"==typeof r?a=r:n=r||{},!t||"object"!==e(t))return w(!0,d,a);var i=o(o({},this.options),n),s=(t||{}).xhr;delete t.xhr;var u,f,p=s||new XMLHttpRequest;return(u=this,f=k,function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];if(t.length!==f.length||void 0===t[t.length-1])return new Promise((function(e,r){t.pop(),t.push((function(t){if(t)return r(t);for(var n=arguments.length,o=new Array(n>1?n-1:0),a=1;a<n;a++)o[a-1]=arguments[a];e(o.length>1?o:o[0])})),f.call.apply(f,[u].concat(t))}));if("function"!=typeof t[t.length-1])throw new Error("Callback must be a function.");f.call.apply(f,[u].concat(t))})(p,t,i,a)}}])&&t(a.prototype,i),f&&t(a,f),n}()})); | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).ImageKit=t()}(this,(function(){"use strict";function e(t){return(e="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(t)}function t(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}function r(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function n(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function o(e){for(var t=1;t<arguments.length;t++){var o=null!=arguments[t]?arguments[t]:{};t%2?n(Object(o),!0).forEach((function(t){r(e,t,o[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(o)):n(Object(o)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(o,t))}))}return e}function a(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function i(e,t){var r;if("undefined"==typeof Symbol||null==e[Symbol.iterator]){if(Array.isArray(e)||(r=function(e,t){if(e){if("string"==typeof e)return a(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?a(e,t):void 0}}(e))||t&&e&&"number"==typeof e.length){r&&(e=r);var n=0,o=function(){};return{s:o,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:o}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,s=!0,u=!1;return{s:function(){r=e[Symbol.iterator]()},n:function(){var e=r.next();return s=e.done,e},e:function(e){u=!0,i=e},f:function(){try{s||null==r.return||r.return()}finally{if(u)throw i}}}}var s={message:"Missing urlEndpoint during SDK initialization",help:""},u={message:"Invalid transformationPosition parameter",help:""},p={message:"Missing file parameter for upload",help:""},f={message:"Missing fileName parameter for upload",help:""},c={message:"Missing public key for upload",help:""},l={message:"Request to ImageKit upload endpoint failed due to network error",help:""},d={message:"Invalid uploadOptions parameter",help:""},h={message:"Missing signature for upload. The SDK expects token, signature and expire for authentication.",help:""},m={message:"Missing token for upload. The SDK expects token, signature and expire for authentication.",help:""},g={message:"Missing expire for upload. The SDK expects token, signature and expire for authentication.",help:""},y={message:"Invalid transformation parameter. Please include at least pre, post, or both.",help:""},v={message:"Invalid pre transformation parameter.",help:""},b={message:"Invalid post transformation parameter.",help:""};function w(e,t,r){"function"==typeof r&&(e?r(t,null):r(null,t))}function O(e){var t={},r=e.getAllResponseHeaders();return Object.keys(r).length&&r.trim().split(/[\r\n]+/).map((function(e){return e.split(/: /)})).forEach((function(e){t[e[0].trim()]=e[1].trim()})),t}var j=function(e,t){var r=o({},e),n={statusCode:t.status,headers:O(t)};return Object.defineProperty(r,"$ResponseMetadata",{value:n,enumerable:!1,writable:!1}),r},S=function(e,t){return new Promise((function(r,n){e.open("POST","https://upload.imagekit.io/api/v1/files/upload"),e.onerror=function(e){return n(l)},e.onload=function(){if(200===e.status)try{var t=JSON.parse(e.responseText),o=j(t,e);return r(o)}catch(e){return n(e)}else try{t=JSON.parse(e.responseText);var a=j(t,e);return n(a)}catch(e){return n(e)}},e.send(t)}))},k=function(t,r,n,o){if(r.file)if(r.fileName)if(n.publicKey)if(r.token)if(r.signature)if(r.expire){if(r.transformation){if(!Object.keys(r.transformation).includes("pre")&&!Object.keys(r.transformation).includes("post"))return void w(!0,y,o);if(Object.keys(r.transformation).includes("pre")&&!r.transformation.pre)return void w(!0,v,o);if(Object.keys(r.transformation).includes("post")){if(!Array.isArray(r.transformation.post))return void w(!0,b,o);var a,s=i(r.transformation.post);try{for(s.s();!(a=s.n()).done;){var u=a.value;if("abs"===u.type&&!u.protocol&&!u.value)return void w(!0,b,o);if("transformation"===u.type&&!u.value)return void w(!0,b,o)}}catch(e){s.e(e)}finally{s.f()}}}var l,d=new FormData;for(l in r)l&&("file"===l&&"string"!=typeof r.file?d.append("file",r.file,String(r.fileName)):"tags"===l&&Array.isArray(r.tags)?d.append("tags",r.tags.join(",")):"signature"===l?d.append("signature",r.signature):"expire"===l?d.append("expire",String(r.expire)):"token"===l?d.append("token",r.token):"responseFields"===l&&Array.isArray(r.responseFields)?d.append("responseFields",r.responseFields.join(",")):"extensions"===l&&Array.isArray(r.extensions)?d.append("extensions",JSON.stringify(r.extensions)):"customMetadata"!==l||"object"!==e(r.customMetadata)||Array.isArray(r.customMetadata)||null===r.customMetadata?"transformation"===l&&"object"===e(r.transformation)&&null!==r.transformation?d.append(l,JSON.stringify(r.transformation)):"checks"===l&&r.checks?d.append("checks",r.checks):void 0!==r[l]&&d.append(l,String(r[l])):d.append("customMetadata",JSON.stringify(r.customMetadata)));d.append("publicKey",n.publicKey),function(e,t,r){S(e,t).then((function(e){return w(!1,e,r)}),(function(e){return w(!0,e,r)}))}(t,d,o)}else w(!0,g,o);else w(!0,h,o);else w(!0,m,o);else w(!0,c,o);else w(!0,f,o);else w(!0,p,o)},x={width:"w",height:"h",aspectRatio:"ar",background:"bg",border:"b",crop:"c",cropMode:"cm",dpr:"dpr",focus:"fo",quality:"q",x:"x",xCenter:"xc",y:"y",yCenter:"yc",format:"f",videoCodec:"vc",audioCodec:"ac",radius:"r",rotation:"rt",blur:"bl",named:"n",defaultImage:"di",flip:"fl",original:"orig",startOffset:"so",endOffset:"eo",duration:"du",streamingResolutions:"sr",effectSharpen:"e-sharpen",effectUSM:"e-usm",effectContrast:"e-contrast",effectGray:"e-grayscale",effectShadow:"e-shadow",effectGradient:"e-gradient",rotate:"rt",grayscale:"e-grayscale",aiUpscale:"e-upscale",aiRetouch:"e-retouch",aiVariation:"e-genvar",aiDropShadow:"e-dropshadow",aiChangeBackground:"e-changebg",aiRemoveBackground:"e-bgremove",aiRemoveBackgroundExternal:"e-removedotbg",contrastStretch:"e-contrast",shadow:"e-shadow",sharpen:"e-sharpen",unsharpMask:"e-usm",gradient:"e-gradient",progressive:"pr",lossless:"lo",colorProfile:"cp",metadata:"md",opacity:"o",trim:"t",zoom:"z",page:"pg",raw:"raw"},P=["path","query"],A=function(){return"path"},M=function(e){return"query"===e.transformationPosition},E=function(e){return void 0!==e.transformationPosition&&-1!=P.indexOf(e.transformationPosition)},R=function(e){return e&&(x[e]||x[e.toLowerCase()])||""},C=function(){return":"},I=function(){return","},D=function(){return"-"};function K(e){return"string"==typeof e&&"/"==e[e.length-1]&&(e=e.substring(0,e.length-1)),e}function T(e,t){var r=t||"/",n=new RegExp(r+"{1,}","g");return e.join(r).replace(n,r)}var q=function(e){if(!e.path&&!e.src)return"";var t,r,n;try{e.path?(n=new URL(e.urlEndpoint).pathname,t=new URL(T([e.urlEndpoint.replace(n,""),e.path]))):(t=new URL(e.src),r=!0)}catch(e){return console.error(e),""}for(var o in e.queryParameters)t.searchParams.append(o,String(e.queryParameters[o]));var a=function(e){if(!Array.isArray(e))return"";for(var t=[],r=0,n=e.length;r<n;r++){var o=[];for(var a in e[r]){var i=e[r][a];if(null!=i){var s=R(a);if(s||(s=a),""!==s)if(["e-grayscale","e-contrast","e-removedotbg","e-bgremove","e-upscale","e-retouch","e-genvar"].includes(s)){if(!0!==i&&"-"!==i&&"true"!==i)continue;o.push(s)}else!["e-sharpen","e-shadow","e-gradient","e-usm","e-dropshadow"].includes(s)||""!==i.toString().trim()&&!0!==i&&"true"!==i?"raw"===a?o.push(e[r][a]):("di"===s&&(i=(i=K(("string"==typeof(u=i||"")&&"/"==u[0]&&(u=u.slice(1)),u))).replace(/\//g,"@@")),"sr"===s&&Array.isArray(i)&&(i=i.join("_")),"t"===s&&""===i.toString().trim()&&(i="true"),o.push([s,i].join(D()))):o.push(s)}}o.length&&t.push(o.join(I()))}var u;return t.join(C())}(e.transformation);return a&&a.length&&(M(e)||r?t.searchParams.append("tr",a):t.pathname=T(["tr"+C()+a,t.pathname])),t.pathname=T(n?[n,t.pathname]:[t.pathname]),t.href};return function(){function n(e){if(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,n),r(this,"options",{sdkVersion:"javascript-".concat("3.1.0"),publicKey:"",urlEndpoint:"",transformationPosition:A()}),this.options=o(o({},this.options),e||{}),!this.options.urlEndpoint)throw s;if(!E(this.options))throw u}var a,i,p;return a=n,(i=[{key:"url",value:function(e){return t=e,r=this.options,q(o(o({},r),t));var t,r}},{key:"upload",value:function(t,r,n){var a;if("function"==typeof r?a=r:n=r||{},!t||"object"!==e(t))return w(!0,d,a);var i=o(o({},this.options),n),s=(t||{}).xhr;delete t.xhr;var u,p,f=s||new XMLHttpRequest;return(u=this,p=k,function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];if(t.length!==p.length||void 0===t[t.length-1])return new Promise((function(e,r){t.pop(),t.push((function(t){if(t)return r(t);for(var n=arguments.length,o=new Array(n>1?n-1:0),a=1;a<n;a++)o[a-1]=arguments[a];e(o.length>1?o:o[0])})),p.call.apply(p,[u].concat(t))}));if("function"!=typeof t[t.length-1])throw new Error("Callback must be a function.");p.call.apply(p,[u].concat(t))})(f,t,i,a)}}])&&t(a.prototype,i),p&&t(a,p),n}()})); |
/** | ||
* @link https://docs.imagekit.io/features/image-transformations | ||
* {@link https://imagekit.io/docs/transformations} | ||
*/ | ||
declare const supportedTransforms: { | ||
export declare const supportedTransforms: { | ||
[key: string]: string; | ||
}; | ||
export default supportedTransforms; |
@@ -7,20 +7,9 @@ import { ImageKitOptions, UploadOptions, UploadResponse, UrlOptions } from "./interfaces"; | ||
/** | ||
* You can add multiple origins in the same ImageKit.io account. | ||
* URL endpoints allow you to configure which origins are accessible through your account and set their preference order as well. | ||
* | ||
* @see {@link https://github.com/imagekit-developer/imagekit-nodejs#url-generation} | ||
* @see {@link https://docs.imagekit.io/integration/url-endpoints} | ||
* | ||
* @param urlOptions | ||
* A utility function to generate asset URL. It applies the specified transformations and other parameters to the URL. | ||
*/ | ||
url(urlOptions: UrlOptions): string; | ||
/** | ||
* You can upload files to ImageKit.io media library from your server-side using private API key authentication. | ||
* For uploading files directly from the browser to ImageKit.io. | ||
* | ||
* File size limit | ||
* The maximum upload file size is limited to 25MB. | ||
* | ||
* @see {@link https://docs.imagekit.io/api-reference/upload-file-api/server-side-file-upload} | ||
* | ||
* @param uploadOptions | ||
* {@link https://imagekit.io/docs/api-reference/upload-file/upload-file#how-to-implement-client-side-file-upload} | ||
*/ | ||
@@ -27,0 +16,0 @@ upload(uploadOptions: UploadOptions, options?: Partial<ImageKitOptions>): Promise<IKResponse<UploadResponse>>; |
@@ -1,3 +0,365 @@ | ||
import supportedTransforms from "../constants/supportedTransforms"; | ||
export declare type TransformationPosition = "path" | "query"; | ||
export declare type Transformation = Partial<typeof supportedTransforms>; | ||
declare type StreamingResolution = "240" | "360" | "480" | "720" | "1080" | "1440" | "2160"; | ||
/** | ||
* The SDK provides easy to use names for transformations. These names are converted to the corresponding transformation string before being added to the URL. | ||
* SDKs are updated regularly to support new transformations. If you want to use a transformation that is not supported by the SDK, you can use the `raw` parameter to pass the transformation string directly. | ||
* | ||
* {@link https://imagekit.io/docs/transformations} | ||
*/ | ||
export interface Transformation { | ||
/** | ||
* The width of the output. If a value between 0 and 1 is used, it’s treated | ||
* as a percentage (e.g., `0.4` -> 40% of original width). You can also supply | ||
* arithmetic expressions (e.g., `"iw_div_2"`). | ||
* | ||
* {@link https://imagekit.io/docs/image-resize-and-crop#width---w} | ||
*/ | ||
width?: number | string; | ||
/** | ||
* The height of the output. If a value between 0 and 1 is used, it’s treated | ||
* as a percentage (e.g., `0.5` -> 50% of original height). You can also supply | ||
* arithmetic expressions (e.g., `"ih_mul_0.5"`). | ||
* | ||
* {@link https://imagekit.io/docs/image-resize-and-crop#height---h} | ||
*/ | ||
height?: number | string; | ||
/** | ||
* Specifies the aspect ratio for the output, e.g., `"ar-4-3"`. | ||
* Typically used with either width or height (not both). | ||
* Example usage: `aspectRatio = "4:3"` or `"4_3"` or an expression like `"iar_div_2"`. | ||
* | ||
* {@link https://imagekit.io/docs/image-resize-and-crop#aspect-ratio---ar} | ||
*/ | ||
aspectRatio?: number | string; | ||
/** | ||
* Specify the background that can be used along with some cropping strategies while resizing an image: | ||
* - A solid color: `"red"`, `"F3F3F3"`, `"AAFF0010"`. | ||
* | ||
* {@link https://imagekit.io/docs/effects-and-enhancements#solid-color-background} | ||
* | ||
* - A blurred background: `"blurred"`, `"blurred_25_N15"`, etc. | ||
* | ||
* {@link https://imagekit.io/docs/effects-and-enhancements#blurred-background} | ||
* | ||
* - Expand the image boundaries using generative fill: `genfill`. Optionally control the background scene by passing text prompt: `genfill[:-prompt-${text}]` or `genfill[:-prompte-${urlencoded_base64_encoded_text}]`. | ||
* | ||
* {@link https://imagekit.io/docs/ai-transformations#generative-fill-bg-genfill} | ||
*/ | ||
background?: string; | ||
/** | ||
* Add a border to the output media. Accepts `<border-width>_<hex-code>`, | ||
* e.g. `"5_FFF000"` (5px yellow border), or an expression like `"ih_div_20_FF00FF"`. | ||
* | ||
* {@link https://imagekit.io/docs/effects-and-enhancements#border---b} | ||
*/ | ||
border?: string; | ||
/** | ||
* {@link https://imagekit.io/docs/image-resize-and-crop#crop-crop-modes--focus} | ||
*/ | ||
crop?: "force" | "at_max" | "at_max_enlarge" | "at_least" | "maintain_ratio"; | ||
/** | ||
* {@link https://imagekit.io/docs/image-resize-and-crop#crop-crop-modes--focus} | ||
*/ | ||
cropMode?: "pad_resize" | "extract" | "pad_extract"; | ||
/** | ||
* Possible values 0.1 to 5 or `auto` for automatic DPR calculation. | ||
* | ||
* {@link https://imagekit.io/docs/image-resize-and-crop#dpr---dpr} | ||
*/ | ||
dpr?: number; | ||
/** | ||
* This parameter can be used along with pad resize, maintain ratio, or extract crop to change the behavior of padding or cropping | ||
* | ||
* {@link https://imagekit.io/docs/image-resize-and-crop#focus---fo} | ||
*/ | ||
focus?: string; | ||
/** | ||
* Used to specify the quality of the output image for lossy formats like JPEG, WebP, and AVIF. A large quality number indicates a larger output image size with high quality. A small quality number indicates a smaller output image size with lower quality. | ||
* | ||
* {@link https://imagekit.io/docs/image-optimization#quality---q} | ||
*/ | ||
quality?: number; | ||
/** | ||
* {@link https://imagekit.io/docs/image-resize-and-crop#example---focus-using-cropped-image-coordinates} | ||
*/ | ||
x?: number | string; | ||
/** | ||
* {@link https://imagekit.io/docs/image-resize-and-crop#example---focus-using-cropped-image-coordinates} | ||
*/ | ||
xCenter?: number | string; | ||
/** | ||
* {@link https://imagekit.io/docs/image-resize-and-crop#example---focus-using-cropped-image-coordinates} | ||
*/ | ||
y?: number | string; | ||
/** | ||
* {@link https://imagekit.io/docs/image-resize-and-crop#example---focus-using-cropped-image-coordinates} | ||
*/ | ||
yCenter?: number | string; | ||
/** | ||
* Output format for images or videos, e.g., `"jpg"`, `"png"`, `"webp"`, `"mp4"`, `"auto"`. You can also pass `orig` which works only for images and will return the image in the original format. | ||
* | ||
* ImageKit will automatically deliver images and videos in best possible format based on the device support unless you disable it from the dashboard settings or override it using the `format` parameter. | ||
* | ||
* {@link https://imagekit.io/docs/image-optimization#format---f} | ||
* | ||
* {@link https://imagekit.io/docs/video-optimization#format---f}} | ||
*/ | ||
format?: "auto" | "webp" | "jpg" | "jpeg" | "png" | "gif" | "svg" | "mp4" | "webm" | "avif" | "orig"; | ||
/** | ||
* Video codec, e.g., `"h264"`, `"vp9"`, `"av1"` or `"none"`. | ||
* | ||
* {@link https://imagekit.io/docs/video-optimization#video-codec---vc} | ||
*/ | ||
videoCodec?: "h264" | "vp9" | "av1" | "none"; | ||
/** | ||
* Audio codec, e.g., `"aac"`, `"opus"` or `"none"`. | ||
* | ||
* {@link https://imagekit.io/docs/video-optimization#audio-codec---ac} | ||
*/ | ||
audioCodec?: "aac" | "opus" | "none"; | ||
/** | ||
* Corner radius for rounded corners (e.g., `20`) or `"max"` for circular/oval shapes. | ||
* | ||
* {@link https://imagekit.io/docs/effects-and-enhancements#radius---r} | ||
*/ | ||
radius?: number | "max"; | ||
/** | ||
* Rotation in degrees. Positive values rotate clockwise; you can | ||
* also use e.g. `"N40"` for counterclockwise or `"auto"` to read EXIF data. | ||
* For videos only 0 , 90 , 180 , 270 and 360 values are supported. | ||
* | ||
* {@link https://imagekit.io/docs/effects-and-enhancements#rotate---rt} | ||
*/ | ||
rotation?: number | string; | ||
/** | ||
* Gaussian blur level. Ranges 1–100 or an expression like `"bl-10"`. Possible values include integers between 1 and 100. | ||
* | ||
* {@link https://imagekit.io/docs/effects-and-enhancements#blur---bl} | ||
*/ | ||
blur?: number; | ||
/** | ||
* {@link https://imagekit.io/docs/transformations#named-transformations} | ||
*/ | ||
named?: string; | ||
/** | ||
* Fallback image if the resource is not found, e.g., a URL or path. | ||
* | ||
* {@link https://imagekit.io/docs/image-transformation#default-image---di} | ||
*/ | ||
defaultImage?: string; | ||
/** | ||
* It is used to flip/mirror an image horizontally, vertically, or in both directions. | ||
* Possible values - h (horizontal), v (vertical), h_v (horizontal and vertical) | ||
* | ||
* {@link https://imagekit.io/docs/effects-and-enhancements#flip---fl} | ||
*/ | ||
flip?: "h" | "v" | "h_v" | "v_h"; | ||
/** | ||
* Whether to serve the original file without any transformations if `true`. | ||
* | ||
* {@link https://imagekit.io/docs/core-delivery-features#deliver-original-file-as-is---orig-true} | ||
*/ | ||
original?: boolean; | ||
/** | ||
* Start offset (in seconds) for trimming videos. e.g., `5` or `"10.5"`. | ||
* Also supports arithmetic expressions. | ||
* | ||
* {@link https://imagekit.io/docs/trim-videos#start-offset---so} | ||
*/ | ||
startOffset?: number | string; | ||
/** | ||
* End offset (in seconds) for trimming videos. e.g., `5` or `"10.5"`. | ||
* Usually used with `startOffset` to define a time window. | ||
* Also supports arithmetic expressions. | ||
* | ||
* {@link https://imagekit.io/docs/trim-videos#end-offset---eo} | ||
*/ | ||
endOffset?: number | string; | ||
/** | ||
* Duration (in seconds) for trimming videos. e.g., `5` or `"10.5"`. | ||
* Typically used with `startOffset` to specify length from the start point. | ||
* Also supports arithmetic expressions. | ||
* | ||
* {@link https://imagekit.io/docs/trim-videos#duration---du} | ||
*/ | ||
duration?: number | string; | ||
/** | ||
* Provide an array of resolutions (e.g. `["240", "360", "480", "720", "1080"]`). | ||
* | ||
* {@link https://imagekit.io/docs/adaptive-bitrate-streaming} | ||
*/ | ||
streamingResolutions?: StreamingResolution[]; | ||
/** | ||
* Enable grayscale effect for images. | ||
* | ||
* {@link https://imagekit.io/docs/effects-and-enhancements#grayscale---e-grayscale} | ||
*/ | ||
grayscale?: true; | ||
/** | ||
* Upscale images beyond their original dimensions with AI. | ||
* | ||
* {@link https://imagekit.io/docs/ai-transformations#upscale-e-upscale} | ||
*/ | ||
aiUpscale?: true; | ||
/** | ||
* Retouch (AI-based) for improving faces or product shots. | ||
* | ||
* {@link https://imagekit.io/docs/ai-transformations#retouch-e-retouch} | ||
*/ | ||
aiRetouch?: true; | ||
/** | ||
* Generate variation of an image using AI. This will generate a new image with slight variations from the original image. The variations include changes in color, texture, and other visual elements. However, the model will try to preserve the structure and essence of the original image. | ||
* | ||
* {@link https://imagekit.io/docs/ai-transformations#generate-variations-of-an-image-e-genvar} | ||
*/ | ||
aiVariation?: true; | ||
/** | ||
* Add an AI-based drop shadow around a foreground object on a transparent or removed background. | ||
* Optionally, you can control the direction, elevation, and saturation of the light source. E.g. change light direction `az-45`. | ||
* | ||
* Pass `true` for default drop shadow or a string for custom drop shadow. | ||
* | ||
* {@link https://imagekit.io/docs/ai-transformations#ai-drop-shadow-e-dropshadow} | ||
*/ | ||
aiDropShadow?: true | string; | ||
/** | ||
* Change background using AI. Provide a prompt or base64-encoded prompt. e.g. `prompt-snow road` or `prompte-[urlencoded_base64_encoded_text]`. | ||
* | ||
* {@link https://imagekit.io/docs/ai-transformations#change-background-e-changebg} | ||
*/ | ||
aiChangeBackground?: string; | ||
/** | ||
* ImageKit’s in-house background removal. | ||
* | ||
* {@link https://imagekit.io/docs/ai-transformations#imagekit-background-removal-e-bgremove} | ||
*/ | ||
aiRemoveBackground?: true; | ||
/** | ||
* Use third-party background removal. Use `aiRemoveBackground` - ImageKit's in-house background removal which is 90% cheaper. | ||
* | ||
* {@link https://imagekit.io/docs/ai-transformations#background-removal-e-removedotbg} | ||
*/ | ||
aiRemoveBackgroundExternal?: true; | ||
/** | ||
* Auto-enhance contrast for an image (contrast stretch). | ||
* | ||
* {@link https://imagekit.io/docs/effects-and-enhancements#contrast-stretch---e-contrast} | ||
*/ | ||
contrastStretch?: true; | ||
/** | ||
* This adds a shadow under solid objects in an input image with a transparent background. Check `eDropshadow` for AI-based shadows. | ||
* | ||
* Pass `true` for default shadow or a string for custom shadow. | ||
* | ||
* {@link https://imagekit.io/docs/effects-and-enhancements#shadow---e-shadow} | ||
*/ | ||
shadow?: true | string; | ||
/** | ||
* It is used to sharpen the input image. It is useful when highlighting the edges and finer details within an image. | ||
* | ||
* Pass `true` for default sharpening or a number for custom sharpening. | ||
* | ||
* {@link https://imagekit.io/docs/effects-and-enhancements#sharpen---e-sharpen} | ||
*/ | ||
sharpen?: true | number; | ||
/** | ||
* Unsharp Masking (USM) is an image sharpening technique. This transform allows you to apply and control unsharp masks on your images. | ||
* | ||
* Pass `true` for default unsharp mask or a string for custom unsharp mask. | ||
* | ||
* {@link https://imagekit.io/docs/effects-and-enhancements#unsharp-mask---e-usm} | ||
*/ | ||
unsharpMask?: true | string; | ||
/** | ||
* The gradient formed is a linear gradient containing two colors, and it can be customized. | ||
* | ||
* Pass `true` for default gradient or a string for custom gradient. | ||
* | ||
* {@link https://imagekit.io/docs/effects-and-enhancements#gradient---e-gradient} | ||
*/ | ||
gradient?: true | string; | ||
/** | ||
* Used to specify whether the output JPEG image must be rendered progressively. In progressive loading, the output image renders as a low-quality pixelated full image, which, over time, keeps on adding more pixels and information to the image. This helps you maintain a fast perceived load time. | ||
* | ||
* {@link https://imagekit.io/docs/image-optimization#progressive-image---pr} | ||
*/ | ||
progressive?: boolean; | ||
/** | ||
* Used to specify whether the output image (if in JPEG or PNG) must be compressed losslessly. | ||
* | ||
* {@link https://imagekit.io/docs/image-optimization#lossless-webp-and-png---lo} | ||
*/ | ||
lossless?: boolean; | ||
/** | ||
* It specifies whether the output image should contain the color profile initially available with the original image. | ||
* | ||
* {@link https://imagekit.io/docs/image-optimization#color-profile---cp} | ||
*/ | ||
colorProfile?: boolean; | ||
/** | ||
* By default, ImageKit removes all metadata as part of automatic image compression. Set this to `true` to preserve metadata. | ||
* | ||
* {@link https://imagekit.io/docs/image-optimization#image-metadata---md} | ||
*/ | ||
metadata?: boolean; | ||
/** | ||
* It is used to specify the opacity level of the output image. | ||
* | ||
* {@link https://imagekit.io/docs/effects-and-enhancements#opacity---o} | ||
*/ | ||
opacity?: number; | ||
/** | ||
* Useful with images that have a solid or nearly solid background with the object in the center. This parameter trims the background from the image, leaving only the central object in the output image. | ||
* | ||
* {@link https://imagekit.io/docs/effects-and-enhancements#trim-edges---t} | ||
*/ | ||
trim?: true | number; | ||
/** | ||
* This parameter accepts a number that determines how much to zoom in or out of the cropped area. | ||
* It must be used along with fo-face or fo-<object_name> | ||
* | ||
* {@link https://imagekit.io/docs/image-resize-and-crop#zoom---z} | ||
*/ | ||
zoom?: number; | ||
/** | ||
* Extract specific page/frame from multi-page or layered files (PDF, PSD, AI), | ||
* Pick by number e.g., `2`. Or 2nd and 3rd layers combined using `3-4`. | ||
* Or pick a layer from PSD by name, e.g., `name-layer-4`. | ||
* | ||
* {@link https://imagekit.io/docs/vector-and-animated-images#get-thumbnail-from-psd-pdf-ai-eps-and-animated-files} | ||
*/ | ||
page?: number | string; | ||
/** | ||
* Pass any transformation that is not directly supported by the SDK. This transformation is passed as it is in the URL. | ||
*/ | ||
raw?: string; | ||
/** | ||
* @deprecated Use `rotation` instead. | ||
*/ | ||
rotate?: string; | ||
/** | ||
* @deprecated Use `sharpen` instead. | ||
*/ | ||
effectSharpen?: string; | ||
/** | ||
* @deprecated Use `unsharpMask` instead. | ||
*/ | ||
effectUSM?: string; | ||
/** | ||
* @deprecated Use `contrastStretch` instead. | ||
*/ | ||
effectContrast?: string; | ||
/** | ||
* @deprecated Use `grayscale` instead. | ||
*/ | ||
effectGray?: string; | ||
/** | ||
* @deprecated Use `shadow` instead. | ||
*/ | ||
effectShadow?: string; | ||
/** | ||
* @deprecated Use `gradient` instead. | ||
*/ | ||
effectGradient?: string; | ||
} | ||
export {}; |
@@ -22,3 +22,3 @@ interface TransformationObject { | ||
* | ||
* @link https://docs.imagekit.io/api-reference/upload-file-api/server-side-file-upload#request-structure-multipart-form-data | ||
* {@link https://imagekit.io/docs/api-reference/upload-file/upload-file#Request} | ||
*/ | ||
@@ -25,0 +25,0 @@ export interface UploadOptions { |
@@ -7,3 +7,3 @@ /** | ||
* | ||
* @link https://docs.imagekit.io/api-reference/media-api/list-and-search-files | ||
* {@link https://imagekit.io/docs/api-reference/digital-asset-management-dam/list-and-search-assets} | ||
*/ | ||
@@ -13,4 +13,5 @@ export declare type FileType = "all" | "image" | "non-image"; | ||
* Metadata object structure | ||
* @link https://docs.imagekit.io/api-reference/metadata-api#metadata-object-structure | ||
* | ||
* {@link https://imagekit.io/docs/api-reference/file-metadata/get-uploaded-file-metadata#Responses} | ||
* | ||
* Contents of Object | ||
@@ -101,3 +102,3 @@ * | ||
* | ||
* @link https://docs.imagekit.io/api-reference/upload-file-api/server-side-file-upload#response-code-and-structure-json | ||
* {@link https://imagekit.io/docs/api-reference/upload-file/upload-file#Responses} | ||
*/ | ||
@@ -104,0 +105,0 @@ export interface UploadResponse { |
@@ -7,3 +7,4 @@ import { TransformationPosition } from "."; | ||
* The transformation name and the value should be specified as a key-value pair in each object. | ||
* @link https://docs.imagekit.io/features/image-transformations/chained-transformations | ||
* | ||
* {@link https://imagekit.io/docs/transformations#chained-transformations} | ||
*/ | ||
@@ -51,4 +52,4 @@ transformation?: Array<Transformation>; | ||
* | ||
* @link https://github.com/imagekit-developer/imagekit-javascript#url-generation | ||
* {@link https://github.com/imagekit-developer/imagekit-javascript#url-generation} | ||
*/ | ||
export declare type UrlOptions = UrlOptionsSrc | UrlOptionsPath; |
{ | ||
"name": "imagekit-javascript", | ||
"version": "3.0.2", | ||
"version": "3.1.0", | ||
"description": "Javascript SDK for using ImageKit.io in the browser", | ||
@@ -5,0 +5,0 @@ "main": "dist/imagekit.cjs.js", |
566
README.md
[<img width="250" alt="ImageKit.io" src="https://raw.githubusercontent.com/imagekit-developer/imagekit-javascript/master/assets/imagekit-light-logo.svg"/>](https://imagekit.io) | ||
# ImageKit.io Javascript SDK | ||
# ImageKit.io JavaScript SDK | ||
@@ -13,50 +13,48 @@  | ||
Javascript SDK for [ImageKit](https://imagekit.io/) provides URL generation for image & video resizing and provides an interface for file upload. This SDK is lightweight and has no dependency. You can also use this as an ES module. | ||
Lightweight JavaScript SDK for generating optimized URLs for images and videos, and for handling file uploads via ImageKit. | ||
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 | ||
- [Installation](#installation) | ||
- [Initialization](#initialization) | ||
- [URL Generation](#url-generation) | ||
- [Basic URL Generation](#basic-url-generation) | ||
- [Advanced URL Generation Examples](#advanced-url-generation-examples) | ||
- [Supported Transformations](#supported-transformations) | ||
- [Handling Unsupported Transformations](#handling-unsupported-transformations) | ||
- [File Upload](#file-upload) | ||
- [Basic Upload Example](#basic-upload-example) | ||
- [Promise-based Upload Example](#promise-based-upload-example) | ||
- [Test Examples](#test-examples) | ||
- [Changelog](#changelog) | ||
## Changelog | ||
### SDK Version 3.0.0 | ||
#### Breaking changes | ||
**1. Overlay syntax update** | ||
* In version 3.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. | ||
### SDK Version 2.0.0 | ||
#### Breaking changes | ||
**1. Authentication Process Update:** | ||
* Previously, when using client side file upload, the SDK required the `publicKey` and `authenticationEndpoint` parameters during SDK initialization to fetch security parameters (`signature`, `token`, and `expire`). | ||
* In version 2.0.0, we've updated the authentication process for the SDK. As a user of the SDK, you are now responsible for generating the security parameters (`signature`, `token`, and `expire`) yourself. This means you no longer need to provide the `authenticationEndpoint`. When using the SDK's upload method, make sure to pass these security parameters explicitly along with other [upload options](https://docs.imagekit.io/api-reference/upload-file-api/client-side-file-upload). For guidance on generating these security parameters, please refer to the documentation available [here](https://docs.imagekit.io/api-reference/upload-file-api/client-side-file-upload#signature-generation-for-client-side-file-upload). | ||
## Installation | ||
### Using npm | ||
Install `imagekit-javascript` | ||
``` | ||
Install the SDK via npm: | ||
```bash | ||
npm install imagekit-javascript --save | ||
#or | ||
# or | ||
yarn add imagekit-javascript | ||
``` | ||
Now import ImageKit | ||
Then import ImageKit: | ||
```js | ||
import ImageKit from "imagekit-javascript" | ||
// or | ||
const ImageKit = require("imagekit-javascript") | ||
import ImageKit from "imagekit-javascript"; | ||
// or with CommonJS: | ||
const ImageKit = require("imagekit-javascript"); | ||
``` | ||
### Using CDN | ||
You can download a specific version of this SDK from a global CDN. | ||
You can also use the global CDN: | ||
Download a specific version: | ||
``` | ||
https://unpkg.com/imagekit-javascript@1.3.0/dist/imagekit.min.js | ||
``` | ||
For the latest version, remove the version number i.e. | ||
Or for the latest version, remove the version number: | ||
``` | ||
https://unpkg.com/imagekit-javascript/dist/imagekit.min.js | ||
``` | ||
Now load it using a `<script>` tag. | ||
``` | ||
And include it in your HTML: | ||
```html | ||
<script type="text/javascript" src="https://unpkg.com/imagekit-javascript/dist/imagekit.min.js"></script> | ||
@@ -67,105 +65,61 @@ ``` | ||
`urlEndpoint` is required to use the SDK. You can get URL-endpoint from your ImageKit dashboard - https://imagekit.io/dashboard#url-endpoints | ||
``` | ||
Initialize the SDK by specifying your URL endpoint. You can obtain your URL endpoint from [https://imagekit.io/dashboard/url-endpoints](https://imagekit.io/dashboard/url-endpoints) and your public API key from [https://imagekit.io/dashboard/developer/api-keys](https://imagekit.io/dashboard/developer/api-keys). For URL generation: | ||
```js | ||
var imagekit = new ImageKit({ | ||
urlEndpoint: "https://ik.imagekit.io/your_imagekit_id" | ||
}); | ||
}); | ||
``` | ||
`publicKey` parameter is required if you want to use the SDK for client-side file upload. You can get this parameter from the developer section in your ImageKit dashboard - https://imagekit.io/dashboard#developers | ||
``` | ||
For client-side file uploads, include your public key: | ||
```js | ||
var imagekit = new ImageKit({ | ||
publicKey: "your_public_api_key", | ||
urlEndpoint: "https://ik.imagekit.io/your_imagekit_id", | ||
}); | ||
``` | ||
*Note: Do not include your Private Key in any client-side code, including this SDK or its initialization. If you pass the `privateKey` parameter while initializing this SDK, it throws an error* | ||
## Demo Application | ||
The fastest way to get started is by running the demo application in [samples/sample-app](https://github.com/imagekit-developer/imagekit-javascript/tree/master/samples/sample-app) folder. Follow these steps to run the application locally: | ||
``` | ||
git clone https://github.com/imagekit-developer/imagekit-javascript.git | ||
cd imagekit-javascript | ||
``` | ||
Create a file `.env` using `sample.env` in the directory `samples/sample-app` and fill in your `PRIVATE_KEY`, `PUBLIC_KEY` and `URL_ENDPOINT` from your [imageKit dashboard](https://imagekit.io/dashboard#developers). `SERVER_PORT` must also be included as per the `sample.env` file. | ||
Now start the sample application by running: | ||
``` | ||
// Run it from the project root | ||
yarn startSampleApp | ||
``` | ||
## Usage | ||
You can use this SDK for URL generation and client-side file uploads. | ||
### URL Generation | ||
**1. Using image path and image hostname or endpoint** | ||
This method allows you to create an URL to access a file using the relative file path and the ImageKit URL endpoint (`urlEndpoint`). The file can be an image, video, or any other static file supported by ImageKit. | ||
``` | ||
var imageURL = imagekit.url({ | ||
path: "/default-image.jpg", | ||
urlEndpoint: "https://ik.imagekit.io/your_imagekit_id/endpoint/", | ||
transformation: [{ | ||
"height": "300", | ||
"width": "400" | ||
}] | ||
}); | ||
``` | ||
*Note: Never include your private key in client-side code. If provided, the SDK throws an error.* | ||
This results in a URL like | ||
## URL Generation | ||
``` | ||
https://ik.imagekit.io/your_imagekit_id/endpoint/tr:h-300,w-400/default-image.jpg | ||
``` | ||
The SDK’s `.url()` method enables you to generate optimized image and video URLs with a variety of transformations. | ||
**2. Using full image URL** | ||
### Basic URL Generation | ||
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. | ||
1. **Using an Image Path with a URL Endpoint** | ||
```js | ||
var imageURL = imagekit.url({ | ||
path: "/default-image.jpg", | ||
urlEndpoint: "https://ik.imagekit.io/your_imagekit_id/endpoint/", | ||
transformation: [{ | ||
"height": "300", | ||
"width": "400" | ||
}] | ||
}); | ||
``` | ||
*Result Example:* | ||
``` | ||
https://ik.imagekit.io/your_imagekit_id/endpoint/tr:h-300,w-400/default-image.jpg | ||
``` | ||
2. **Using a Full Image URL (src)** | ||
```js | ||
var imageURL = imagekit.url({ | ||
src: "https://ik.imagekit.io/your_imagekit_id/endpoint/default-image.jpg", | ||
transformation: [{ | ||
"height": "300", | ||
"width": "400" | ||
}] | ||
}); | ||
``` | ||
*Result Example:* | ||
``` | ||
https://ik.imagekit.io/your_imagekit_id/endpoint/default-image.jpg?tr=h-300%2Cw-400 | ||
``` | ||
``` | ||
var imageURL = imagekit.url({ | ||
src: "https://ik.imagekit.io/your_imagekit_id/endpoint/default-image.jpg", | ||
transformation: [{ | ||
"height": "300", | ||
"width": "400" | ||
}] | ||
}); | ||
``` | ||
### Advanced URL Generation Examples | ||
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. | | ||
| transformationPostion | Optional. The default value is `path`, which 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 query parameter `tr` in the URL. 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 are not necessarily related to ImageKit. Especially useful if you want to add some versioning parameters to your URLs. | | ||
#### Examples of generating URLs | ||
**1. Chained Transformations as a query parameter** | ||
``` | ||
#### Chained Transformations | ||
Apply multiple transformations by passing an array: | ||
```js | ||
var imageURL = imagekit.url({ | ||
path: "/default-image.jpg", | ||
urlEndpoint: "https://ik.imagekit.io/your_imagekit_id/endpoint/", | ||
transformation: [{ | ||
@@ -177,39 +131,12 @@ "height": "300", | ||
}], | ||
transformationPosition: "query" | ||
transformationPosition: "query" // Use query parameter for transformations | ||
}); | ||
``` | ||
*Result Example:* | ||
``` | ||
https://ik.imagekit.io/your_imagekit_id/endpoint/default-image.jpg?tr=h-300%2Cw-400%3Art-90 | ||
https://ik.imagekit.io/your_imagekit_id/default-image.jpg?tr=h-300%2Cw-400%3Art-90 | ||
``` | ||
**2. Sharpening and contrast transforms and a progressive JPG image** | ||
There are some transforms like [Sharpening](https://docs.imagekit.io/features/image-transformations/image-enhancement-and-color-manipulation) that can be added to the URL with or without any other value. To use such transforms without specifying a value, specify the value as "-" in the transformation object. Otherwise, specify the value that you want to be added to this transformation. | ||
``` | ||
var imageURL = imagekit.url({ | ||
src: "https://ik.imagekit.io/your_imagekit_id/endpoint/default-image.jpg", | ||
transformation: [{ | ||
"format": "jpg", | ||
"progressive": "true", | ||
"effectSharpen": "-", | ||
"effectContrast": "1" | ||
}] | ||
}); | ||
``` | ||
``` | ||
//Note that because `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. Adding overlays** | ||
ImageKit.io enables you to apply overlays to [images](https://docs.imagekit.io/features/image-transformations/overlay-using-layers) and [videos](https://docs.imagekit.io/features/video-transformation/overlay) using the raw parameter with the concept of [layers](https://docs.imagekit.io/features/image-transformations/overlay-using-layers#layers). The raw parameter facilitates incorporating transformations directly in the URL. A layer is a distinct type of transformation that allows you to define an asset to serve as an overlay, along with its positioning and additional transformations. | ||
**Text as overlays** | ||
You can add any text string over a base video or image using a text layer (l-text). | ||
For example: | ||
#### Overlays and Effects | ||
*Text Overlay Example:* | ||
```js | ||
@@ -220,3 +147,3 @@ var imageURL = imagekit.url({ | ||
"width": 400, | ||
"height": 300 | ||
"height": 300, | ||
"raw": "l-text,i-Imagekit,fs-50,l-end" | ||
@@ -226,13 +153,3 @@ }] | ||
``` | ||
**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 | ||
``` | ||
**Image as overlays** | ||
You can add an image over a base video or image using an image layer (l-image). | ||
For example: | ||
*Image Overlay Example:* | ||
```js | ||
@@ -243,3 +160,3 @@ var imageURL = imagekit.url({ | ||
"width": 400, | ||
"height": 300 | ||
"height": 300, | ||
"raw": "l-image,i-default-image.jpg,w-100,b-10_CDDC39,l-end" | ||
@@ -249,34 +166,33 @@ }] | ||
``` | ||
**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 | ||
``` | ||
**Solid color blocks as overlays** | ||
You can add solid color blocks over a base video or image using an image layer (l-image). | ||
For example: | ||
#### AI and Advanced Transformations | ||
*Background Removal:* | ||
```js | ||
var imageURL = imagekit.url({ | ||
src: "https://ik.imagekit.io/your_imagekit_id/img/sample-video.mp4", | ||
transformation: [{ | ||
"width": 400, | ||
"height": 300 | ||
"raw": "l-image,i-ik_canvas,bg-FF0000,w-300,h-100,l-end" | ||
}] | ||
path: "/sample-image.jpg", | ||
transformation: [{ | ||
aiRemoveBackground: true | ||
}] | ||
}); | ||
``` | ||
**Sample Result URL** | ||
*Upscaling:* | ||
```js | ||
var upscaledURL = imagekit.url({ | ||
path: "/sample-image.jpg", | ||
transformation: [{ | ||
aiUpscale: true | ||
}] | ||
}); | ||
``` | ||
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 | ||
*Drop Shadow:* | ||
```js | ||
var dropShadowURL = imagekit.url({ | ||
path: "/sample-image.jpg", | ||
transformation: [{ | ||
aiDropShadow: "az-45" | ||
}] | ||
}); | ||
``` | ||
**4. Arithmetic expressions in transformations** | ||
ImageKit allows use of [arithmetic expressions](https://docs.imagekit.io/features/arithmetic-expressions-in-transformations) in certain dimension and position-related parameters, making media transformations more flexible and dynamic. | ||
For example: | ||
#### Arithmetic Expressions in Transformations | ||
```js | ||
@@ -293,71 +209,98 @@ var imageURL = imagekit.url({ | ||
**Sample Result URL** | ||
``` | ||
https://ik.imagekit.io/your_imagekit_id/default-image.jpg?tr=w-iw_div_4,h-ih_div_2,b-cw_mul_0.05_yellow | ||
``` | ||
### Supported Transformations | ||
#### List of supported transformations | ||
The SDK gives a name to each transformation parameter e.g. height for h and width for w parameter. It makes your code more readable. If the property does not match any of the following supported options, it is added as it is. | ||
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. | ||
If you want to generate transformations in your application and add them to the URL as it is, use the `raw` parameter. | ||
Check ImageKit [transformation documentation](https://imagekit.io/docs/transformations) for more details. | ||
| 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 | The string provided in raw will be added in the URL as it is. | | ||
| Transformation Name | URL Parameter | | ||
| -------------------------- | ------------------------------------------------------------- | | ||
| width | w | | ||
| height | h | | ||
| aspectRatio | ar | | ||
| quality | q | | ||
| aiRemoveBackground | e-bgremove (ImageKit powered) | | ||
| aiRemoveBackgroundExternal | e-removedotbg (Using third party) | | ||
| aiUpscale | e-upscale | | ||
| aiRetouch | e-retouch | | ||
| aiVariation | e-genvar | | ||
| aiDropShadow | e-dropshadow | | ||
| aiChangeBackground | e-changebg | | ||
| crop | c | | ||
| cropMode | cm | | ||
| x | x | | ||
| y | y | | ||
| xCenter | xc | | ||
| yCenter | yc | | ||
| focus | fo | | ||
| format | f | | ||
| radius | r | | ||
| background | bg | | ||
| border | b | | ||
| rotation | rt | | ||
| blur | bl | | ||
| named | n | | ||
| dpr | dpr | | ||
| progressive | pr | | ||
| lossless | lo | | ||
| trim | t | | ||
| metadata | md | | ||
| colorProfile | cp | | ||
| defaultImage | di | | ||
| original | orig | | ||
| videoCodec | vc | | ||
| audioCodec | ac | | ||
| grayscale | e-grayscale | | ||
| contrastStretch | e-contrast | | ||
| shadow | e-shadow | | ||
| sharpen | e-sharpen | | ||
| unsharpMask | e-usm | | ||
| gradient | e-gradient | | ||
| flip | fl | | ||
| opacity | o | | ||
| zoom | z | | ||
| page | pg | | ||
| startOffset | so | | ||
| endOffset | eo | | ||
| duration | du | | ||
| streamingResolutions | sr | | ||
| raw | The string provided in raw will be added in the URL as it is. | | ||
### Handling Unsupported Transformations | ||
### File Upload | ||
If you specify a transformation parameter that is not explicitly supported by the SDK, it is added “as-is” in the generated URL. This provides flexibility for using new or custom transformations without waiting for an SDK update. | ||
The SDK provides a simple interface using the `.upload()` method to upload files to the ImageKit Media Library. | ||
For example: | ||
```js | ||
var imageURL = imagekit.url({ | ||
path: "/test_path.jpg", | ||
transformation: [{ | ||
"newparam": "cool" | ||
}] | ||
}); | ||
// Generated URL: https://ik.imagekit.io/test_url_endpoint/tr:newparam-cool/test_path.jpg | ||
``` | ||
The `upload()` method requires mandatory `file` and the `fileName` parameter. In addition, it accepts all the parameters supported by the [ImageKit Upload API](https://docs.imagekit.io/api-reference/upload-file-api/client-side-file-upload). | ||
## File Upload | ||
Also, before making an upload request, please ensure you have generated mandatory security parameters: `signature`, `token`, and `expire`. To generate these security parameters, refer to the [documentation here](https://docs.imagekit.io/api-reference/upload-file-api/client-side-file-upload#signature-generation-for-client-side-file-upload). Obtain the parameters using a secure method and pass them, along with the mandatory `file` and `fileName` parameters, to the `upload()` method. | ||
The SDK offers a simple interface via the `.upload()` method to upload files to the ImageKit Media Library. This method requires the following: | ||
- **file** (mandatory) | ||
- **fileName** (mandatory) | ||
- Security parameters: **signature**, **token**, and **expire** | ||
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 specify tags for a file at the time of upload, use the `tags` parameter as specified in the [documentation here](https://docs.imagekit.io/api-reference/upload-file-api/client-side-file-upload). | ||
Before invoking the upload, generate the necessary security parameters as per the [ImageKit Upload API documentation](https://imagekit.io/docs/api-reference/upload-file/upload-file#how-to-implement-client-side-file-upload). | ||
### Basic Upload Example | ||
#### Sample usage | ||
Below is an HTML form example that uses a callback for handling the upload response: | ||
```html | ||
<form action="#" onsubmit="upload()"> | ||
<form action="#" onsubmit="upload(); return false;"> | ||
<input type="file" id="file1" /> | ||
<input type="submit" /> | ||
</form> | ||
<script type="text/javascript" src="../dist/imagekit.js"></script> | ||
<script src="../dist/imagekit.js"></script> | ||
<script> | ||
/* | ||
SDK initialization | ||
*/ | ||
var imagekit = new ImageKit({ | ||
@@ -368,63 +311,17 @@ publicKey: "your_public_api_key", | ||
// Upload function internally uses the ImageKit.io javascript SDK | ||
function upload(data) { | ||
function upload() { | ||
var file = document.getElementById("file1"); | ||
// Using Callback Function | ||
imagekit.upload({ | ||
file: file.files[0], | ||
fileName: "abc1.jpg", | ||
tags: ["tag1"], | ||
token: 'generated_token', | ||
signature: 'generated_signature', | ||
expire: 'generated_expire', | ||
extensions: [ | ||
{ | ||
name: "aws-auto-tagging", | ||
minConfidence: 80, | ||
maxTags: 10 | ||
} | ||
], | ||
transformation: { | ||
pre: 'l-text,i-Imagekit,fs-50,l-end', | ||
post: [ | ||
{ | ||
type: 'transformation', | ||
value: 'w-100' | ||
} | ||
] | ||
} | ||
expire: 'generated_expire' | ||
}, function(err, result) { | ||
console.log(result); | ||
}) | ||
// Using Promises | ||
imagekit.upload({ | ||
file: file.files[0], | ||
fileName: "abc1.jpg", | ||
tags: ["tag1"], | ||
token: 'generated_token', | ||
signature: 'generated_signature', | ||
expire: 'generated_expire', | ||
extensions: [ | ||
{ | ||
name: "aws-auto-tagging", | ||
minConfidence: 80, | ||
maxTags: 10 | ||
} | ||
], | ||
transformation: { | ||
pre: 'l-text,i-Imagekit,fs-50,l-end', | ||
post: [ | ||
{ | ||
type: 'transformation', | ||
value: 'w-100' | ||
} | ||
] | ||
if(err){ | ||
console.error(err); | ||
} else { | ||
console.log(result); | ||
} | ||
}).then(result => { | ||
console.log(result); | ||
}).then(error => { | ||
console.log(error); | ||
}) | ||
}); | ||
} | ||
@@ -434,92 +331,27 @@ </script> | ||
If the upload succeeds, `err` will be `null`, and the `result` will be the same as what is received from ImageKit's servers. | ||
If the upload fails, `err` will be the same as what is received from ImageKit's servers, and the `result` will be null. | ||
### Promise-based Upload Example | ||
## Tracking upload progress using custom XMLHttpRequest | ||
You can use a custom XMLHttpRequest object as the following to bind `progress` or any other events for a customized implementation. | ||
You can also use promises for a cleaner asynchronous approach: | ||
```js | ||
var fileSize = file.files[0].size; | ||
var customXHR = new XMLHttpRequest(); | ||
customXHR.upload.addEventListener('progress', function (e) { | ||
if (e.loaded <= fileSize) { | ||
var percent = Math.round(e.loaded / fileSize * 100); | ||
console.log(`Uploaded ${percent}%`); | ||
} | ||
if(e.loaded == e.total){ | ||
console.log("Upload done"); | ||
} | ||
}); | ||
imagekit.upload({ | ||
xhr: customXHR, | ||
file: file.files[0], | ||
fileName: "abc1.jpg", | ||
tags: ["tag1"], | ||
token: 'generated_token', | ||
signature: 'generated_signature', | ||
expire: 'generated_expire', | ||
extensions: [ | ||
{ | ||
name: "aws-auto-tagging", | ||
minConfidence: 80, | ||
maxTags: 10 | ||
} | ||
] | ||
expire: 'generated_expire' | ||
}).then(result => { | ||
console.log(result); | ||
}).then(error => { | ||
console.log(error); | ||
}) | ||
}).catch(error => { | ||
console.error(error); | ||
}); | ||
``` | ||
## 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. | ||
## Test Examples | ||
```js | ||
// Success | ||
var response = await imagekit.upload({ | ||
file: file.files[0], | ||
fileName: "abc1.jpg", | ||
tags: ["tag1"], | ||
token: 'generated_token', | ||
signature: 'generated_signature', | ||
expire: 'generated_expire', | ||
extensions: [ | ||
{ | ||
name: "aws-auto-tagging", | ||
minConfidence: 80, | ||
maxTags: 10 | ||
} | ||
] | ||
}); | ||
console.log(response.$ResponseMetadata.statusCode); // 200 | ||
For a quick demonstration of the SDK features, refer to our test examples: | ||
- URL Generation examples can be found in [test/url-generation.js](./test/url-generation.js) | ||
- File Upload examples can be found in [test/upload.js](./test/upload.js) | ||
// { 'content-length': "300", 'content-type': 'application/json', 'x-request-id': 'ee560df4-d44f-455e-a48e-29dfda49aec5'} | ||
console.log(response.$ResponseMetadata.headers); | ||
## Changelog | ||
// Error | ||
try { | ||
await imagekit.upload({ | ||
file: file.files[0], | ||
fileName: "abc1.jpg", | ||
tags: ["tag1"], | ||
token: 'generated_token', | ||
signature: 'generated_signature', | ||
expire: 'generated_expire', | ||
extensions: [ | ||
{ | ||
name: "aws-auto-tagging", | ||
minConfidence: 80, | ||
maxTags: 10 | ||
} | ||
] | ||
}); | ||
} catch (ex) { | ||
console.log(response.$ResponseMetadata.statusCode); // 400 | ||
// {'content-type': 'application/json', 'x-request-id': 'ee560df4-d44f-455e-a48e-29dfda49aec5'} | ||
console.log(response.$ResponseMetadata.headers); | ||
} | ||
``` | ||
For a detailed history of changes, please refer to [CHANGELOG.md](CHANGELOG.md). |
/** | ||
* @link https://docs.imagekit.io/features/image-transformations | ||
* {@link https://imagekit.io/docs/transformations} | ||
*/ | ||
const supportedTransforms: { [key: string]: string } = { | ||
/** | ||
* @link https://docs.imagekit.io/features/image-transformations/resize-crop-and-other-transformations#width-w | ||
*/ | ||
export const supportedTransforms: { [key: string]: string } = { | ||
// Basic sizing & layout | ||
width: "w", | ||
/** | ||
* @link https://docs.imagekit.io/features/image-transformations/resize-crop-and-other-transformations#height-h | ||
*/ | ||
height: "h", | ||
/** | ||
* @link https://docs.imagekit.io/features/image-transformations/resize-crop-and-other-transformations#aspect-ratio-ar | ||
*/ | ||
aspectRatio: "ar", | ||
/** | ||
* @link https://docs.imagekit.io/features/image-transformations/resize-crop-and-other-transformations#quality-q | ||
*/ | ||
quality: "q", | ||
/** | ||
* @link https://docs.imagekit.io/features/image-transformations/resize-crop-and-other-transformations#crop-crop-modes-and-focus | ||
*/ | ||
background: "bg", | ||
border: "b", | ||
crop: "c", | ||
/** | ||
* @link https://docs.imagekit.io/features/image-transformations/resize-crop-and-other-transformations#crop-crop-modes-and-focus | ||
*/ | ||
cropMode: "cm", | ||
/** | ||
* @link https://docs.imagekit.io/features/image-transformations/resize-crop-and-other-transformations#focus-fo | ||
*/ | ||
dpr: "dpr", | ||
focus: "fo", | ||
/** | ||
* @link https://docs.imagekit.io/features/image-transformations/resize-crop-and-other-transformations#examples-focus-using-cropped-image-coordinates | ||
*/ | ||
quality: "q", | ||
x: "x", | ||
/** | ||
* @link https://docs.imagekit.io/features/image-transformations/resize-crop-and-other-transformations#examples-focus-using-cropped-image-coordinates | ||
*/ | ||
xCenter: "xc", | ||
y: "y", | ||
/** | ||
* @link https://docs.imagekit.io/features/image-transformations/resize-crop-and-other-transformations#format-f | ||
*/ | ||
yCenter: "yc", | ||
format: "f", | ||
/** | ||
* @link https://docs.imagekit.io/features/image-transformations/resize-crop-and-other-transformations#radius-r | ||
*/ | ||
videoCodec: "vc", | ||
audioCodec: "ac", | ||
radius: "r", | ||
/** | ||
* @link https://docs.imagekit.io/features/image-transformations/resize-crop-and-other-transformations#background-color-bg | ||
*/ | ||
background: "bg", | ||
/** | ||
* @link https://docs.imagekit.io/features/image-transformations/resize-crop-and-other-transformations#border-b | ||
*/ | ||
border: "b", | ||
/** | ||
* @link https://docs.imagekit.io/features/image-transformations/resize-crop-and-other-transformations#rotate-rt | ||
*/ | ||
rotation: "rt", | ||
/** | ||
* @link https://docs.imagekit.io/features/image-transformations/resize-crop-and-other-transformations#rotate-rt | ||
*/ | ||
rotate: "rt", | ||
/** | ||
* @link https://docs.imagekit.io/features/image-transformations/resize-crop-and-other-transformations#blur-bl | ||
*/ | ||
blur: "bl", | ||
/** | ||
* @link https://docs.imagekit.io/features/image-transformations/resize-crop-and-other-transformations#named-transformation-n | ||
*/ | ||
named: "n", | ||
/** | ||
* @link https://docs.imagekit.io/features/image-transformations/resize-crop-and-other-transformations#progressive-image-pr | ||
*/ | ||
progressive: "pr", | ||
/** | ||
* @link https://docs.imagekit.io/features/image-transformations/resize-crop-and-other-transformations#lossless-webp-and-png-lo | ||
*/ | ||
lossless: "lo", | ||
/** | ||
* @link https://docs.imagekit.io/features/image-transformations/resize-crop-and-other-transformations#trim-edges-t | ||
*/ | ||
trim: "t", | ||
/** | ||
* @link https://docs.imagekit.io/features/image-transformations/resize-crop-and-other-transformations#image-metadata-md | ||
*/ | ||
metadata: "md", | ||
/** | ||
* @link https://docs.imagekit.io/features/image-transformations/resize-crop-and-other-transformations#color-profile-cp | ||
*/ | ||
colorProfile: "cp", | ||
/** | ||
* @link https://docs.imagekit.io/features/image-transformations/resize-crop-and-other-transformations#default-image-di | ||
*/ | ||
defaultImage: "di", | ||
flip: "fl", | ||
original: "orig", | ||
startOffset: "so", | ||
endOffset: "eo", | ||
duration: "du", | ||
streamingResolutions: "sr", | ||
/** | ||
* @link https://docs.imagekit.io/features/image-transformations/resize-crop-and-other-transformations#dpr-dpr | ||
*/ | ||
dpr: "dpr", | ||
/** | ||
* @link https://docs.imagekit.io/features/image-transformations/image-enhancement-and-color-manipulation#sharpen-e-sharpen | ||
*/ | ||
// Old deprecated mappings | ||
effectSharpen: "e-sharpen", | ||
/** | ||
* @link https://docs.imagekit.io/features/image-transformations/image-enhancement-and-color-manipulation#unsharp-mask-e-usm | ||
*/ | ||
effectUSM: "e-usm", | ||
/** | ||
* @link https://docs.imagekit.io/features/image-transformations/image-enhancement-and-color-manipulation#contrast-stretch-e-contrast | ||
*/ | ||
effectContrast: "e-contrast", | ||
/** | ||
* @link https://docs.imagekit.io/features/image-transformations/resize-crop-and-other-transformations#grayscale-e-grayscale | ||
*/ | ||
effectGray: "e-grayscale", | ||
effectShadow: "e-shadow", | ||
effectGradient: "e-gradient", | ||
rotate: "rt", | ||
/** | ||
* @link https://docs.imagekit.io/features/image-transformations/resize-crop-and-other-transformations#original-image-orig | ||
*/ | ||
original: "orig", | ||
// AI & advanced effects | ||
grayscale: "e-grayscale", | ||
aiUpscale: "e-upscale", | ||
aiRetouch: "e-retouch", | ||
aiVariation: "e-genvar", | ||
aiDropShadow: "e-dropshadow", | ||
aiChangeBackground: "e-changebg", | ||
aiRemoveBackground: "e-bgremove", | ||
aiRemoveBackgroundExternal: "e-removedotbg", | ||
contrastStretch: "e-contrast", | ||
shadow: "e-shadow", | ||
sharpen: "e-sharpen", | ||
unsharpMask: "e-usm", | ||
gradient: "e-gradient", | ||
/** | ||
* @link https://docs.imagekit.io/features/image-transformations/image-enhancement-and-color-manipulation#shadow-e-shadow | ||
*/ | ||
effectShadow: "e-shadow", | ||
// Other flags & finishing | ||
progressive: "pr", | ||
lossless: "lo", | ||
colorProfile: "cp", | ||
metadata: "md", | ||
opacity: "o", | ||
trim: "t", | ||
zoom: "z", | ||
page: "pg", | ||
/** | ||
* @link https://docs.imagekit.io/features/image-transformations/image-enhancement-and-color-manipulation#gradient-e-gradient | ||
*/ | ||
effectGradient: "e-gradient", | ||
// Raw pass-through | ||
raw: "raw", | ||
}; | ||
/** | ||
* @link https://docs.imagekit.io/features/image-transformations/conditional-transformations | ||
*/ | ||
raw: "raw", | ||
} | ||
export default supportedTransforms |
@@ -58,9 +58,3 @@ import { version } from "../package.json"; | ||
/** | ||
* You can add multiple origins in the same ImageKit.io account. | ||
* URL endpoints allow you to configure which origins are accessible through your account and set their preference order as well. | ||
* | ||
* @see {@link https://github.com/imagekit-developer/imagekit-nodejs#url-generation} | ||
* @see {@link https://docs.imagekit.io/integration/url-endpoints} | ||
* | ||
* @param urlOptions | ||
* A utility function to generate asset URL. It applies the specified transformations and other parameters to the URL. | ||
*/ | ||
@@ -72,10 +66,5 @@ url(urlOptions: UrlOptions): string { | ||
/** | ||
* You can upload files to ImageKit.io media library from your server-side using private API key authentication. | ||
* For uploading files directly from the browser to ImageKit.io. | ||
* | ||
* File size limit | ||
* The maximum upload file size is limited to 25MB. | ||
* | ||
* @see {@link https://docs.imagekit.io/api-reference/upload-file-api/server-side-file-upload} | ||
* | ||
* @param uploadOptions | ||
* {@link https://imagekit.io/docs/api-reference/upload-file/upload-file#how-to-implement-client-side-file-upload} | ||
*/ | ||
@@ -82,0 +71,0 @@ upload(uploadOptions: UploadOptions, options?: Partial<ImageKitOptions>): Promise<IKResponse<UploadResponse>> |
@@ -1,5 +0,426 @@ | ||
import supportedTransforms from "../constants/supportedTransforms"; | ||
export type TransformationPosition = "path" | "query"; | ||
export type Transformation = Partial<typeof supportedTransforms>; | ||
type StreamingResolution = "240" | "360" | "480" | "720" | "1080" | "1440" | "2160"; | ||
/** | ||
* The SDK provides easy to use names for transformations. These names are converted to the corresponding transformation string before being added to the URL. | ||
* SDKs are updated regularly to support new transformations. If you want to use a transformation that is not supported by the SDK, you can use the `raw` parameter to pass the transformation string directly. | ||
* | ||
* {@link https://imagekit.io/docs/transformations} | ||
*/ | ||
export interface Transformation { | ||
/** | ||
* The width of the output. If a value between 0 and 1 is used, it’s treated | ||
* as a percentage (e.g., `0.4` -> 40% of original width). You can also supply | ||
* arithmetic expressions (e.g., `"iw_div_2"`). | ||
* | ||
* {@link https://imagekit.io/docs/image-resize-and-crop#width---w} | ||
*/ | ||
width?: number | string; | ||
/** | ||
* The height of the output. If a value between 0 and 1 is used, it’s treated | ||
* as a percentage (e.g., `0.5` -> 50% of original height). You can also supply | ||
* arithmetic expressions (e.g., `"ih_mul_0.5"`). | ||
* | ||
* {@link https://imagekit.io/docs/image-resize-and-crop#height---h} | ||
*/ | ||
height?: number | string; | ||
/** | ||
* Specifies the aspect ratio for the output, e.g., `"ar-4-3"`. | ||
* Typically used with either width or height (not both). | ||
* Example usage: `aspectRatio = "4:3"` or `"4_3"` or an expression like `"iar_div_2"`. | ||
* | ||
* {@link https://imagekit.io/docs/image-resize-and-crop#aspect-ratio---ar} | ||
*/ | ||
aspectRatio?: number | string; | ||
/** | ||
* Specify the background that can be used along with some cropping strategies while resizing an image: | ||
* - A solid color: `"red"`, `"F3F3F3"`, `"AAFF0010"`. | ||
* | ||
* {@link https://imagekit.io/docs/effects-and-enhancements#solid-color-background} | ||
* | ||
* - A blurred background: `"blurred"`, `"blurred_25_N15"`, etc. | ||
* | ||
* {@link https://imagekit.io/docs/effects-and-enhancements#blurred-background} | ||
* | ||
* - Expand the image boundaries using generative fill: `genfill`. Optionally control the background scene by passing text prompt: `genfill[:-prompt-${text}]` or `genfill[:-prompte-${urlencoded_base64_encoded_text}]`. | ||
* | ||
* {@link https://imagekit.io/docs/ai-transformations#generative-fill-bg-genfill} | ||
*/ | ||
background?: string; | ||
/** | ||
* Add a border to the output media. Accepts `<border-width>_<hex-code>`, | ||
* e.g. `"5_FFF000"` (5px yellow border), or an expression like `"ih_div_20_FF00FF"`. | ||
* | ||
* {@link https://imagekit.io/docs/effects-and-enhancements#border---b} | ||
*/ | ||
border?: string; | ||
/** | ||
* {@link https://imagekit.io/docs/image-resize-and-crop#crop-crop-modes--focus} | ||
*/ | ||
crop?: "force" | "at_max" | "at_max_enlarge" | "at_least" | "maintain_ratio"; | ||
/** | ||
* {@link https://imagekit.io/docs/image-resize-and-crop#crop-crop-modes--focus} | ||
*/ | ||
cropMode?: "pad_resize" | "extract" | "pad_extract"; | ||
/** | ||
* Possible values 0.1 to 5 or `auto` for automatic DPR calculation. | ||
* | ||
* {@link https://imagekit.io/docs/image-resize-and-crop#dpr---dpr} | ||
*/ | ||
dpr?: number | ||
/** | ||
* This parameter can be used along with pad resize, maintain ratio, or extract crop to change the behavior of padding or cropping | ||
* | ||
* {@link https://imagekit.io/docs/image-resize-and-crop#focus---fo} | ||
*/ | ||
focus?: string; | ||
/** | ||
* Used to specify the quality of the output image for lossy formats like JPEG, WebP, and AVIF. A large quality number indicates a larger output image size with high quality. A small quality number indicates a smaller output image size with lower quality. | ||
* | ||
* {@link https://imagekit.io/docs/image-optimization#quality---q} | ||
*/ | ||
quality?: number; | ||
/** | ||
* {@link https://imagekit.io/docs/image-resize-and-crop#example---focus-using-cropped-image-coordinates} | ||
*/ | ||
x?: number | string; | ||
/** | ||
* {@link https://imagekit.io/docs/image-resize-and-crop#example---focus-using-cropped-image-coordinates} | ||
*/ | ||
xCenter?: number | string; | ||
/** | ||
* {@link https://imagekit.io/docs/image-resize-and-crop#example---focus-using-cropped-image-coordinates} | ||
*/ | ||
y?: number | string; | ||
/** | ||
* {@link https://imagekit.io/docs/image-resize-and-crop#example---focus-using-cropped-image-coordinates} | ||
*/ | ||
yCenter?: number | string; | ||
/** | ||
* Output format for images or videos, e.g., `"jpg"`, `"png"`, `"webp"`, `"mp4"`, `"auto"`. You can also pass `orig` which works only for images and will return the image in the original format. | ||
* | ||
* ImageKit will automatically deliver images and videos in best possible format based on the device support unless you disable it from the dashboard settings or override it using the `format` parameter. | ||
* | ||
* {@link https://imagekit.io/docs/image-optimization#format---f} | ||
* | ||
* {@link https://imagekit.io/docs/video-optimization#format---f}} | ||
*/ | ||
format?: "auto" | "webp" | "jpg" | "jpeg" | "png" | "gif" | "svg" | "mp4" | "webm" | "avif" | "orig"; | ||
/** | ||
* Video codec, e.g., `"h264"`, `"vp9"`, `"av1"` or `"none"`. | ||
* | ||
* {@link https://imagekit.io/docs/video-optimization#video-codec---vc} | ||
*/ | ||
videoCodec?: "h264" | "vp9" | "av1" | "none"; | ||
/** | ||
* Audio codec, e.g., `"aac"`, `"opus"` or `"none"`. | ||
* | ||
* {@link https://imagekit.io/docs/video-optimization#audio-codec---ac} | ||
*/ | ||
audioCodec?: "aac" | "opus" | "none"; | ||
/** | ||
* Corner radius for rounded corners (e.g., `20`) or `"max"` for circular/oval shapes. | ||
* | ||
* {@link https://imagekit.io/docs/effects-and-enhancements#radius---r} | ||
*/ | ||
radius?: number | "max"; | ||
/** | ||
* Rotation in degrees. Positive values rotate clockwise; you can | ||
* also use e.g. `"N40"` for counterclockwise or `"auto"` to read EXIF data. | ||
* For videos only 0 , 90 , 180 , 270 and 360 values are supported. | ||
* | ||
* {@link https://imagekit.io/docs/effects-and-enhancements#rotate---rt} | ||
*/ | ||
rotation?: number | string; | ||
/** | ||
* Gaussian blur level. Ranges 1–100 or an expression like `"bl-10"`. Possible values include integers between 1 and 100. | ||
* | ||
* {@link https://imagekit.io/docs/effects-and-enhancements#blur---bl} | ||
*/ | ||
blur?: number; | ||
/** | ||
* {@link https://imagekit.io/docs/transformations#named-transformations} | ||
*/ | ||
named?: string; | ||
/** | ||
* Fallback image if the resource is not found, e.g., a URL or path. | ||
* | ||
* {@link https://imagekit.io/docs/image-transformation#default-image---di} | ||
*/ | ||
defaultImage?: string; | ||
/** | ||
* It is used to flip/mirror an image horizontally, vertically, or in both directions. | ||
* Possible values - h (horizontal), v (vertical), h_v (horizontal and vertical) | ||
* | ||
* {@link https://imagekit.io/docs/effects-and-enhancements#flip---fl} | ||
*/ | ||
flip?: "h" | "v" | "h_v" | "v_h"; | ||
/** | ||
* Whether to serve the original file without any transformations if `true`. | ||
* | ||
* {@link https://imagekit.io/docs/core-delivery-features#deliver-original-file-as-is---orig-true} | ||
*/ | ||
original?: boolean; | ||
/** | ||
* Start offset (in seconds) for trimming videos. e.g., `5` or `"10.5"`. | ||
* Also supports arithmetic expressions. | ||
* | ||
* {@link https://imagekit.io/docs/trim-videos#start-offset---so} | ||
*/ | ||
startOffset?: number | string; | ||
/** | ||
* End offset (in seconds) for trimming videos. e.g., `5` or `"10.5"`. | ||
* Usually used with `startOffset` to define a time window. | ||
* Also supports arithmetic expressions. | ||
* | ||
* {@link https://imagekit.io/docs/trim-videos#end-offset---eo} | ||
*/ | ||
endOffset?: number | string; | ||
/** | ||
* Duration (in seconds) for trimming videos. e.g., `5` or `"10.5"`. | ||
* Typically used with `startOffset` to specify length from the start point. | ||
* Also supports arithmetic expressions. | ||
* | ||
* {@link https://imagekit.io/docs/trim-videos#duration---du} | ||
*/ | ||
duration?: number | string; | ||
/** | ||
* Provide an array of resolutions (e.g. `["240", "360", "480", "720", "1080"]`). | ||
* | ||
* {@link https://imagekit.io/docs/adaptive-bitrate-streaming} | ||
*/ | ||
streamingResolutions?: StreamingResolution[]; | ||
/** | ||
* Enable grayscale effect for images. | ||
* | ||
* {@link https://imagekit.io/docs/effects-and-enhancements#grayscale---e-grayscale} | ||
*/ | ||
grayscale?: true; | ||
/** | ||
* Upscale images beyond their original dimensions with AI. | ||
* | ||
* {@link https://imagekit.io/docs/ai-transformations#upscale-e-upscale} | ||
*/ | ||
aiUpscale?: true | ||
/** | ||
* Retouch (AI-based) for improving faces or product shots. | ||
* | ||
* {@link https://imagekit.io/docs/ai-transformations#retouch-e-retouch} | ||
*/ | ||
aiRetouch?: true | ||
/** | ||
* Generate variation of an image using AI. This will generate a new image with slight variations from the original image. The variations include changes in color, texture, and other visual elements. However, the model will try to preserve the structure and essence of the original image. | ||
* | ||
* {@link https://imagekit.io/docs/ai-transformations#generate-variations-of-an-image-e-genvar} | ||
*/ | ||
aiVariation?: true | ||
/** | ||
* Add an AI-based drop shadow around a foreground object on a transparent or removed background. | ||
* Optionally, you can control the direction, elevation, and saturation of the light source. E.g. change light direction `az-45`. | ||
* | ||
* Pass `true` for default drop shadow or a string for custom drop shadow. | ||
* | ||
* {@link https://imagekit.io/docs/ai-transformations#ai-drop-shadow-e-dropshadow} | ||
*/ | ||
aiDropShadow?: true | string | ||
/** | ||
* Change background using AI. Provide a prompt or base64-encoded prompt. e.g. `prompt-snow road` or `prompte-[urlencoded_base64_encoded_text]`. | ||
* | ||
* {@link https://imagekit.io/docs/ai-transformations#change-background-e-changebg} | ||
*/ | ||
aiChangeBackground?: string; | ||
/** | ||
* ImageKit’s in-house background removal. | ||
* | ||
* {@link https://imagekit.io/docs/ai-transformations#imagekit-background-removal-e-bgremove} | ||
*/ | ||
aiRemoveBackground?: true | ||
/** | ||
* Use third-party background removal. Use `aiRemoveBackground` - ImageKit's in-house background removal which is 90% cheaper. | ||
* | ||
* {@link https://imagekit.io/docs/ai-transformations#background-removal-e-removedotbg} | ||
*/ | ||
aiRemoveBackgroundExternal?: true | ||
/** | ||
* Auto-enhance contrast for an image (contrast stretch). | ||
* | ||
* {@link https://imagekit.io/docs/effects-and-enhancements#contrast-stretch---e-contrast} | ||
*/ | ||
contrastStretch?: true | ||
/** | ||
* This adds a shadow under solid objects in an input image with a transparent background. Check `eDropshadow` for AI-based shadows. | ||
* | ||
* Pass `true` for default shadow or a string for custom shadow. | ||
* | ||
* {@link https://imagekit.io/docs/effects-and-enhancements#shadow---e-shadow} | ||
*/ | ||
shadow?: true | string | ||
/** | ||
* It is used to sharpen the input image. It is useful when highlighting the edges and finer details within an image. | ||
* | ||
* Pass `true` for default sharpening or a number for custom sharpening. | ||
* | ||
* {@link https://imagekit.io/docs/effects-and-enhancements#sharpen---e-sharpen} | ||
*/ | ||
sharpen?: true | number | ||
/** | ||
* Unsharp Masking (USM) is an image sharpening technique. This transform allows you to apply and control unsharp masks on your images. | ||
* | ||
* Pass `true` for default unsharp mask or a string for custom unsharp mask. | ||
* | ||
* {@link https://imagekit.io/docs/effects-and-enhancements#unsharp-mask---e-usm} | ||
*/ | ||
unsharpMask?: true | string; | ||
/** | ||
* The gradient formed is a linear gradient containing two colors, and it can be customized. | ||
* | ||
* Pass `true` for default gradient or a string for custom gradient. | ||
* | ||
* {@link https://imagekit.io/docs/effects-and-enhancements#gradient---e-gradient} | ||
*/ | ||
gradient?: true | string; | ||
/** | ||
* Used to specify whether the output JPEG image must be rendered progressively. In progressive loading, the output image renders as a low-quality pixelated full image, which, over time, keeps on adding more pixels and information to the image. This helps you maintain a fast perceived load time. | ||
* | ||
* {@link https://imagekit.io/docs/image-optimization#progressive-image---pr} | ||
*/ | ||
progressive?: boolean; | ||
/** | ||
* Used to specify whether the output image (if in JPEG or PNG) must be compressed losslessly. | ||
* | ||
* {@link https://imagekit.io/docs/image-optimization#lossless-webp-and-png---lo} | ||
*/ | ||
lossless?: boolean | ||
/** | ||
* It specifies whether the output image should contain the color profile initially available with the original image. | ||
* | ||
* {@link https://imagekit.io/docs/image-optimization#color-profile---cp} | ||
*/ | ||
colorProfile?: boolean; | ||
/** | ||
* By default, ImageKit removes all metadata as part of automatic image compression. Set this to `true` to preserve metadata. | ||
* | ||
* {@link https://imagekit.io/docs/image-optimization#image-metadata---md} | ||
*/ | ||
metadata?: boolean; | ||
/** | ||
* It is used to specify the opacity level of the output image. | ||
* | ||
* {@link https://imagekit.io/docs/effects-and-enhancements#opacity---o} | ||
*/ | ||
opacity?: number; | ||
/** | ||
* Useful with images that have a solid or nearly solid background with the object in the center. This parameter trims the background from the image, leaving only the central object in the output image. | ||
* | ||
* {@link https://imagekit.io/docs/effects-and-enhancements#trim-edges---t} | ||
*/ | ||
trim?: true | number; | ||
/** | ||
* This parameter accepts a number that determines how much to zoom in or out of the cropped area. | ||
* It must be used along with fo-face or fo-<object_name> | ||
* | ||
* {@link https://imagekit.io/docs/image-resize-and-crop#zoom---z} | ||
*/ | ||
zoom?: number; | ||
/** | ||
* Extract specific page/frame from multi-page or layered files (PDF, PSD, AI), | ||
* Pick by number e.g., `2`. Or 2nd and 3rd layers combined using `3-4`. | ||
* Or pick a layer from PSD by name, e.g., `name-layer-4`. | ||
* | ||
* {@link https://imagekit.io/docs/vector-and-animated-images#get-thumbnail-from-psd-pdf-ai-eps-and-animated-files} | ||
*/ | ||
page?: number | string; | ||
/** | ||
* Pass any transformation that is not directly supported by the SDK. This transformation is passed as it is in the URL. | ||
*/ | ||
raw?: string; | ||
// old as it is but deprecated | ||
/** | ||
* @deprecated Use `rotation` instead. | ||
*/ | ||
rotate?: string; | ||
/** | ||
* @deprecated Use `sharpen` instead. | ||
*/ | ||
effectSharpen?: string; | ||
/** | ||
* @deprecated Use `unsharpMask` instead. | ||
*/ | ||
effectUSM?: string; | ||
/** | ||
* @deprecated Use `contrastStretch` instead. | ||
*/ | ||
effectContrast?: string; | ||
/** | ||
* @deprecated Use `grayscale` instead. | ||
*/ | ||
effectGray?: string; | ||
/** | ||
* @deprecated Use `shadow` instead. | ||
*/ | ||
effectShadow?: string; | ||
/** | ||
* @deprecated Use `gradient` instead. | ||
*/ | ||
effectGradient?: string; | ||
} | ||
@@ -26,3 +26,3 @@ interface TransformationObject { | ||
* | ||
* @link https://docs.imagekit.io/api-reference/upload-file-api/server-side-file-upload#request-structure-multipart-form-data | ||
* {@link https://imagekit.io/docs/api-reference/upload-file/upload-file#Request} | ||
*/ | ||
@@ -29,0 +29,0 @@ export interface UploadOptions { |
@@ -7,3 +7,3 @@ /** | ||
* | ||
* @link https://docs.imagekit.io/api-reference/media-api/list-and-search-files | ||
* {@link https://imagekit.io/docs/api-reference/digital-asset-management-dam/list-and-search-assets} | ||
*/ | ||
@@ -14,4 +14,5 @@ export type FileType = "all" | "image" | "non-image"; | ||
* Metadata object structure | ||
* @link https://docs.imagekit.io/api-reference/metadata-api#metadata-object-structure | ||
* | ||
* {@link https://imagekit.io/docs/api-reference/file-metadata/get-uploaded-file-metadata#Responses} | ||
* | ||
* Contents of Object | ||
@@ -101,3 +102,3 @@ * | ||
* | ||
* @link https://docs.imagekit.io/api-reference/upload-file-api/server-side-file-upload#response-code-and-structure-json | ||
* {@link https://imagekit.io/docs/api-reference/upload-file/upload-file#Responses} | ||
*/ | ||
@@ -104,0 +105,0 @@ export interface UploadResponse { |
@@ -8,3 +8,4 @@ import { TransformationPosition } from "."; | ||
* The transformation name and the value should be specified as a key-value pair in each object. | ||
* @link https://docs.imagekit.io/features/image-transformations/chained-transformations | ||
* | ||
* {@link https://imagekit.io/docs/transformations#chained-transformations} | ||
*/ | ||
@@ -53,4 +54,4 @@ transformation?: Array<Transformation>; | ||
* | ||
* @link https://github.com/imagekit-developer/imagekit-javascript#url-generation | ||
* {@link https://github.com/imagekit-developer/imagekit-javascript#url-generation} | ||
*/ | ||
export type UrlOptions = UrlOptionsSrc | UrlOptionsPath; |
@@ -85,4 +85,7 @@ import { ImageKitOptions, UrlOptions } from "../interfaces"; | ||
for (var key in transformation[i]) { | ||
if(transformation[i][key] === undefined || transformation[i][key] === null ) | ||
continue; | ||
let value = transformation[i][key as keyof Transformation]; | ||
if (value === undefined || value === null) { | ||
continue; | ||
} | ||
var transformKey = transformationUtils.getTransformKey(key); | ||
@@ -93,3 +96,19 @@ if (!transformKey) { | ||
if (transformation[i][key] === "-") { | ||
if (transformKey === "") { | ||
continue; | ||
} | ||
if ( | ||
["e-grayscale", "e-contrast", "e-removedotbg", "e-bgremove", "e-upscale", "e-retouch", "e-genvar"].includes(transformKey) | ||
) { | ||
if (value === true || value === "-" || value === "true") { | ||
parsedTransformStep.push(transformKey); | ||
} else { | ||
// Any other value means that the effect should not be applied | ||
continue; | ||
} | ||
} else if ( | ||
["e-sharpen", "e-shadow", "e-gradient", "e-usm", "e-dropshadow"].includes(transformKey) && | ||
(value.toString().trim() === "" || value === true || value === "true") | ||
) { | ||
parsedTransformStep.push(transformKey); | ||
@@ -99,11 +118,19 @@ } else if (key === "raw") { | ||
} else { | ||
var value = transformation[i][key]; | ||
if (transformKey === "di") { | ||
value = removeTrailingSlash(removeLeadingSlash(value || "")); | ||
value = removeTrailingSlash(removeLeadingSlash(value as string || "")); | ||
value = value.replace(/\//g, "@@"); | ||
} | ||
if (transformKey === "sr" && Array.isArray(value)) { | ||
value = value.join("_"); | ||
} | ||
// Special case for trim with empty string - should be treated as true | ||
if (transformKey === "t" && value.toString().trim() === "") { | ||
value = "true"; | ||
} | ||
parsedTransformStep.push([transformKey, value].join(transformationUtils.getTransformKeyValueDelimiter())); | ||
} | ||
} | ||
parsedTransforms.push(parsedTransformStep.join(transformationUtils.getTransformDelimiter())); | ||
if (parsedTransformStep.length) { | ||
parsedTransforms.push(parsedTransformStep.join(transformationUtils.getTransformDelimiter())); | ||
} | ||
} | ||
@@ -110,0 +137,0 @@ |
156694
19.28%38
2.7%3443
28.14%348
-32.43%