imagekit-javascript
Version:
Javascript SDK for using ImageKit.io in the browser
2 lines (1 loc) • 11.7 kB
JavaScript
!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 n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function n(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function r(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function o(e){for(var t=1;t<arguments.length;t++){var o=null!=arguments[t]?arguments[t]:{};t%2?r(Object(o),!0).forEach((function(t){n(e,t,o[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(o)):r(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 n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}function i(e,t){var n;if("undefined"==typeof Symbol||null==e[Symbol.iterator]){if(Array.isArray(e)||(n=function(e,t){if(e){if("string"==typeof e)return a(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?a(e,t):void 0}}(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var r=0,o=function(){};return{s:o,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},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(){n=e[Symbol.iterator]()},n:function(){var e=n.next();return s=e.done,e},e:function(e){u=!0,i=e},f:function(){try{s||null==n.return||n.return()}finally{if(u)throw i}}}}var s={message:"Missing urlEndpoint during SDK initialization",help:""},u={message:"Invalid transformationPosition parameter",help:""},c={message:"Missing file parameter for upload",help:""},p={message:"Missing fileName parameter for upload",help:""},f={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,n){"function"==typeof n&&(e?n(t,null):n(null,t))}function O(e){var t={},n=e.getAllResponseHeaders();return Object.keys(n).length&&n.trim().split(/[\r\n]+/).map((function(e){return e.split(/: /)})).forEach((function(e){t[e[0].trim()]=e[1].trim()})),t}var x=function(e,t){var n=o({},e),r={statusCode:t.status,headers:O(t)};return Object.defineProperty(n,"$ResponseMetadata",{value:r,enumerable:!1,writable:!1}),n},j=function(e,t){return new Promise((function(n,r){e.open("POST","https://upload.imagekit.io/api/v1/files/upload"),e.onerror=function(e){return r(l)},e.onload=function(){if(200===e.status)try{var t=JSON.parse(e.responseText),o=x(t,e);return n(o)}catch(e){return r(e)}else try{t=JSON.parse(e.responseText);var a=x(t,e);return r(a)}catch(e){return r(e)}},e.send(t)}))},k=function(t,n,r,o){if(n.file)if(n.fileName)if(r.publicKey)if(n.token)if(n.signature)if(n.expire){if(n.transformation){if(!Object.keys(n.transformation).includes("pre")&&!Object.keys(n.transformation).includes("post"))return void w(!0,y,o);if(Object.keys(n.transformation).includes("pre")&&!n.transformation.pre)return void w(!0,v,o);if(Object.keys(n.transformation).includes("post")){if(!Array.isArray(n.transformation.post))return void w(!0,b,o);var a,s=i(n.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 n)l&&("file"===l&&"string"!=typeof n.file?d.append("file",n.file,String(n.fileName)):"tags"===l&&Array.isArray(n.tags)?d.append("tags",n.tags.join(",")):"signature"===l?d.append("signature",n.signature):"expire"===l?d.append("expire",String(n.expire)):"token"===l?d.append("token",n.token):"responseFields"===l&&Array.isArray(n.responseFields)?d.append("responseFields",n.responseFields.join(",")):"extensions"===l&&Array.isArray(n.extensions)?d.append("extensions",JSON.stringify(n.extensions)):"customMetadata"!==l||"object"!==e(n.customMetadata)||Array.isArray(n.customMetadata)||null===n.customMetadata?"transformation"===l&&"object"===e(n.transformation)&&null!==n.transformation?d.append(l,JSON.stringify(n.transformation)):"checks"===l&&n.checks?d.append("checks",n.checks):void 0!==n[l]&&d.append(l,String(n[l])):d.append("customMetadata",JSON.stringify(n.customMetadata)));d.append("publicKey",r.publicKey),function(e,t,n){j(e,t).then((function(e){return w(!1,e,n)}),(function(e){return w(!0,e,n)}))}(t,d,o)}else w(!0,g,o);else w(!0,h,o);else w(!0,m,o);else w(!0,f,o);else w(!0,p,o);else w(!0,c,o)},S={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",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",fontSize:"fs",fontFamily:"ff",fontColor:"co",innerAlignment:"ia",padding:"pa",alpha:"al",typography:"tg",lineHeight:"lh",fontOutline:"fol",fontShadow:"fsh",raw:"raw"},A=["path","query"],P=function(){return"query"},R=function(e){return"query"===e.transformationPosition},C=function(e){return void 0!==e.transformationPosition&&-1!=A.indexOf(e.transformationPosition)},M=function(e){return e&&(S[e]||S[e.toLowerCase()])||""},I=function(){return":"},E=function(){return","},U=function(){return"-"},q=function(e){return"undefined"!=typeof window?btoa(e):Buffer.from(e,"utf8").toString("base64")},D=new RegExp("^[a-zA-Z0-9-._/ ]*$"),K=new RegExp("^[a-zA-Z0-9-._ ]*$");function T(e){return"string"==typeof e&&"/"==e[e.length-1]&&(e=e.substring(0,e.length-1)),e}function N(e){return"string"==typeof e&&"/"==e[0]&&(e=e.slice(1)),e}function z(e,t){var n=t||"/",r=new RegExp(n+"{1,}","g");return e.join(n).replace(r,n)}function F(e,t){return e=T(N(e)),"plain"===t?"i-".concat(e.replace(/\//g,"@@")):"base64"===t?"ie-".concat(encodeURIComponent(q(e))):D.test(e)?"i-".concat(e.replace(/\//g,"@@")):"ie-".concat(encodeURIComponent(q(e)))}function J(e){var t=[];if(e){var n=e.type,r=e.position,o=void 0===r?{}:r,a=e.timing,i=void 0===a?{}:a,s=e.transformation,u=void 0===s?[]:s;if(!n)throw new Error("Overlay type is required");switch(n){case"text":var c=e;if(!c.text)return;var p=c.encoding||"auto";t.push("l-text"),t.push(function(e,t){return"plain"===t?"i-".concat(encodeURIComponent(e)):"base64"===t?"ie-".concat(encodeURIComponent(q(e))):K.test(e)?"i-".concat(encodeURIComponent(e)):"ie-".concat(encodeURIComponent(q(e)))}(c.text,p));break;case"image":t.push("l-image");var f=e,l=f.encoding||"auto";if(!f.input)return;t.push(F(f.input,l));break;case"video":t.push("l-video");var d=e,h=d.encoding||"auto";if(!d.input)return;t.push(F(d.input,h));break;case"subtitle":t.push("l-subtitle");var m=e,g=m.encoding||"auto";if(!m.input)return;t.push(F(m.input,g));break;case"solidColor":t.push("l-image"),t.push("i-ik_canvas");var y=e;if(!y.color)return;t.push("bg-".concat(y.color))}var v=o.x,b=o.y,w=o.focus;v&&t.push("lx-".concat(v)),b&&t.push("ly-".concat(b)),w&&t.push("lfo-".concat(w));var O=i.start,x=i.end,j=i.duration;O&&t.push("lso-".concat(O)),x&&t.push("leo-".concat(x)),j&&t.push("ldu-".concat(j));var k=L(u);return k&&""!==k.trim()&&t.push(k),t.push("l-end"),t.join(E())}}function L(t){if(!Array.isArray(t))return"";for(var n=[],r=0,o=t.length;r<o;r++){var a=[];for(var i in t[r]){var s=t[r][i];if(null!=s)if("overlay"!==i||"object"!==e(s)){var u=M(i);if(u||(u=i),""!==u)if(["e-grayscale","e-contrast","e-removedotbg","e-bgremove","e-upscale","e-retouch","e-genvar"].includes(u)){if(!0!==s&&"-"!==s&&"true"!==s)continue;a.push(u)}else!["e-sharpen","e-shadow","e-gradient","e-usm","e-dropshadow"].includes(u)||""!==s.toString().trim()&&!0!==s&&"true"!==s?"raw"===i?a.push(t[r][i]):("di"===u&&(s=(s=T(N(s||""))).replace(/\//g,"@@")),"sr"===u&&Array.isArray(s)&&(s=s.join("_")),"t"===u&&""===s.toString().trim()&&(s="true"),a.push([u,s].join(U()))):a.push(u)}else{var c=J(s);c&&""!==c.trim()&&a.push(c)}}a.length&&n.push(a.join(E()))}return n.join(I())}var B=function(e,t){return function(e){if(!e.path&&!e.src)return"";var t,n,r;try{e.path?(r=new URL(e.urlEndpoint).pathname,t=new URL(z([e.urlEndpoint.replace(r,""),e.path]))):(t=new URL(e.src),n=!0)}catch(e){return console.error(e),""}for(var o in e.queryParameters)t.searchParams.append(o,String(e.queryParameters[o]));var a=L(e.transformation);return a&&a.length&&(R(e)||n||(t.pathname=z(["tr"+I()+a,t.pathname]))),t.pathname=z(r?[r,t.pathname]:[t.pathname]),a&&a.length&&(R(e)||n)?""!==t.searchParams.toString()?"".concat(t.href,"&").concat("tr","=").concat(a):"".concat(t.href,"?").concat("tr","=").concat(a):t.href}(o(o({},t),e))};return function(){function r(e){if(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,r),n(this,"options",{publicKey:"",urlEndpoint:"",transformationPosition:P()}),this.options=o(o({},this.options),e||{}),!this.options.urlEndpoint)throw s;if(!C(this.options))throw u}var a,i,c;return a=r,(i=[{key:"url",value:function(e){return B(e,this.options)}},{key:"upload",value:function(t,n,r){var a;if("function"==typeof n?a=n:r=n||{},!t||"object"!==e(t))return w(!0,d,a);var i=o(o({},this.options),r),s=(t||{}).xhr;delete t.xhr;var u,c,p=s||new XMLHttpRequest;return(u=this,c=k,function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];if(t.length!==c.length||void 0===t[t.length-1])return new Promise((function(e,n){t.pop(),t.push((function(t){if(t)return n(t);for(var r=arguments.length,o=new Array(r>1?r-1:0),a=1;a<r;a++)o[a-1]=arguments[a];e(o.length>1?o:o[0])})),c.call.apply(c,[u].concat(t))}));if("function"!=typeof t[t.length-1])throw new Error("Callback must be a function.");c.call.apply(c,[u].concat(t))})(p,t,i,a)}}])&&t(a.prototype,i),c&&t(a,c),r}()}));