@nhost/hasura-storage-js
Advanced tools
Comparing version 0.2.0 to 0.2.1
import { ApiDeleteParams, ApiDeleteResponse, ApiGetPresignedUrlParams, ApiGetPresignedUrlResponse, ApiUploadParams, ApiUploadResponse } from './utils/types'; | ||
/** | ||
* @internal | ||
* This is an internal class. | ||
*/ | ||
export declare class HasuraStorageApi { | ||
@@ -13,3 +17,15 @@ private url; | ||
delete(params: ApiDeleteParams): Promise<ApiDeleteResponse>; | ||
/** | ||
* Set the access token to use for authentication. | ||
* | ||
* @param accessToken Access token | ||
* @returns Hasura Storage API instance | ||
*/ | ||
setAccessToken(accessToken?: string): HasuraStorageApi; | ||
/** | ||
* Set the admin secret to use for authentication. | ||
* | ||
* @param adminSecret Hasura admin secret | ||
* @returns Hasura Storage API instance | ||
*/ | ||
setAdminSecret(adminSecret?: string): HasuraStorageApi; | ||
@@ -19,1 +35,2 @@ private generateUploadHeaders; | ||
} | ||
//# sourceMappingURL=hasura-storage-api.d.ts.map |
import { StorageDeleteParams, StorageDeleteResponse, StorageGetPresignedUrlParams, StorageGetPresignedUrlResponse, StorageGetUrlParams, StorageUploadParams, StorageUploadResponse } from './utils/types'; | ||
/** | ||
* @alias Storage | ||
*/ | ||
export declare class HasuraStorageClient { | ||
@@ -8,9 +11,57 @@ private url; | ||
}); | ||
/** | ||
* Use `.upload` to upload a file. | ||
* | ||
* @example | ||
* ```ts | ||
* storage.upload({ file }) | ||
* ``` | ||
*/ | ||
upload(params: StorageUploadParams): Promise<StorageUploadResponse>; | ||
/** | ||
* @deprecated use `.getPublicUrl` instead | ||
*/ | ||
getUrl(params: StorageGetUrlParams): string; | ||
/** | ||
* Use `.getPublicUrl` to direct file URL to a file. | ||
* | ||
* @example | ||
* ```ts | ||
* storage.getPublicUrl({ fileId: 'uuid' }) | ||
* ``` | ||
*/ | ||
getPublicUrl(params: StorageGetUrlParams): string; | ||
/** | ||
* Use `.getPresignedUrl` to get a presigned URL to a file. | ||
* | ||
* @example | ||
* ```ts | ||
* storage.getPresignedUrl({ fileId: 'uuid' }) | ||
* ``` | ||
*/ | ||
getPresignedUrl(params: StorageGetPresignedUrlParams): Promise<StorageGetPresignedUrlResponse>; | ||
/** | ||
* Use `.delete` to delete a file. | ||
* | ||
* @example | ||
* ```ts | ||
* storage.delete({ fileId: 'uuid' }) | ||
* ``` | ||
*/ | ||
delete(params: StorageDeleteParams): Promise<StorageDeleteResponse>; | ||
/** | ||
* Set the access token to use for authentication. | ||
* | ||
* @param accessToken Access token | ||
* @returns Hasura Storage Client instance | ||
*/ | ||
setAccessToken(accessToken?: string): HasuraStorageClient; | ||
/** | ||
* Set the admin secret to use for authentication. | ||
* | ||
* @param adminSecret Hasura admin secret | ||
* @returns Hasura Storage Client instance | ||
*/ | ||
setAdminSecret(adminSecret?: string): HasuraStorageClient; | ||
} | ||
//# sourceMappingURL=hasura-storage-client.d.ts.map |
@@ -1,2 +0,2 @@ | ||
var U=Object.create;var n=Object.defineProperty,P=Object.defineProperties,A=Object.getOwnPropertyDescriptor,S=Object.getOwnPropertyDescriptors,H=Object.getOwnPropertyNames,p=Object.getOwnPropertySymbols,R=Object.getPrototypeOf,u=Object.prototype.hasOwnProperty,x=Object.prototype.propertyIsEnumerable;var d=(t,e,r)=>e in t?n(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,i=(t,e)=>{for(var r in e||(e={}))u.call(e,r)&&d(t,r,e[r]);if(p)for(var r of p(e))x.call(e,r)&&d(t,r,e[r]);return t},g=(t,e)=>P(t,S(e)),c=t=>n(t,"__esModule",{value:!0});var G=(t,e)=>{for(var r in e)n(t,r,{get:e[r],enumerable:!0})},h=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of H(e))!u.call(t,a)&&(r||a!=="default")&&n(t,a,{get:()=>e[a],enumerable:!(s=A(e,a))||s.enumerable});return t},v=(t,e)=>h(c(n(t!=null?U(R(t)):{},"default",!e&&t&&t.__esModule?{get:()=>t.default,enumerable:!0}:{value:t,enumerable:!0})),t),w=(t=>(e,r)=>t&&t.get(e)||(r=h(c({}),e,1),t&&t.set(e,r),r))(typeof WeakMap!="undefined"?new WeakMap:0);var k={};G(k,{HasuraStorageApi:()=>l,HasuraStorageClient:()=>f});var m=v(require("axios")),l=class{constructor({url:e}){this.url=e,this.httpClient=m.default.create({baseURL:this.url})}async upload(e){try{return{fileMetadata:(await this.httpClient.post("/files",e.file,{headers:i(i({},this.generateUploadHeaders(e)),this.generateAuthHeaders())})).data,error:null}}catch(r){return{fileMetadata:null,error:r}}}async getPresignedUrl(e){try{let{fileId:r}=e;return{presignedUrl:(await this.httpClient.get(`/files/${r}/presignedurl`,{headers:i({},this.generateAuthHeaders())})).data,error:null}}catch(r){return{presignedUrl:null,error:r}}}async delete(e){try{let{fileId:r}=e;return await this.httpClient.delete(`/files/${r}`,{headers:i({},this.generateAuthHeaders())}),{error:null}}catch(r){return{error:r}}}setAccessToken(e){return this.accessToken=e,this}setAdminSecret(e){return this.adminSecret=e,this}generateUploadHeaders(e){let{bucketId:r,name:s,id:a}=e,o={};return r&&(o["x-nhost-bucket-id"]=r),a&&(o["x-nhost-file-id"]=a),s&&(o["x-nhost-file-name"]=s),o}generateAuthHeaders(){return!this.adminSecret&&!this.accessToken?null:this.adminSecret?{"x-hasura-admin-secret":this.adminSecret}:{Authorization:`Bearer ${this.accessToken}`}}};var f=class{constructor({url:e}){this.url=e,this.api=new l({url:e})}async upload(e){let r=new FormData;r.append("file",e.file);let{fileMetadata:s,error:a}=await this.api.upload(g(i({},e),{file:r}));return a?{fileMetadata:null,error:a}:s?{fileMetadata:s,error:null}:{fileMetadata:null,error:new Error("Invalid file returned")}}getUrl(e){return this.getPublicUrl(e)}getPublicUrl(e){let{fileId:r}=e;return`${this.url}/files/${r}`}async getPresignedUrl(e){let{presignedUrl:r,error:s}=await this.api.getPresignedUrl(e);return s?{presignedUrl:null,error:s}:r?{presignedUrl:r,error:null}:{presignedUrl:null,error:new Error("Invalid file id")}}async delete(e){let{error:r}=await this.api.delete(e);return r?{error:r}:{error:null}}setAccessToken(e){return this.api.setAccessToken(e),this}setAdminSecret(e){return this.api.setAdminSecret(e),this}};module.exports=w(k);0&&(module.exports={HasuraStorageApi,HasuraStorageClient}); | ||
"use strict";var c=Object.defineProperty,h=Object.defineProperties;var f=Object.getOwnPropertyDescriptors;var l=Object.getOwnPropertySymbols;var g=Object.prototype.hasOwnProperty,p=Object.prototype.propertyIsEnumerable;var u=(t,e,r)=>e in t?c(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,s=(t,e)=>{for(var r in e||(e={}))g.call(e,r)&&u(t,r,e[r]);if(l)for(var r of l(e))p.call(e,r)&&u(t,r,e[r]);return t},o=(t,e)=>h(t,f(e));Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});var U=require("axios");function A(t){return t&&typeof t=="object"&&"default"in t?t:{default:t}}var S=A(U);class d{constructor({url:e}){this.url=e,this.httpClient=S.default.create({baseURL:this.url})}async upload(e){try{return{fileMetadata:(await this.httpClient.post("/files",e.file,{headers:s(s({},this.generateUploadHeaders(e)),this.generateAuthHeaders())})).data,error:null}}catch(r){return{fileMetadata:null,error:r}}}async getPresignedUrl(e){try{const{fileId:r}=e;return{presignedUrl:(await this.httpClient.get(`/files/${r}/presignedurl`,{headers:s({},this.generateAuthHeaders())})).data,error:null}}catch(r){return{presignedUrl:null,error:r}}}async delete(e){try{const{fileId:r}=e;return await this.httpClient.delete(`/files/${r}`,{headers:s({},this.generateAuthHeaders())}),{error:null}}catch(r){return{error:r}}}setAccessToken(e){return this.accessToken=e,this}setAdminSecret(e){return this.adminSecret=e,this}generateUploadHeaders(e){const{bucketId:r,name:i,id:a}=e,n={};return r&&(n["x-nhost-bucket-id"]=r),a&&(n["x-nhost-file-id"]=a),i&&(n["x-nhost-file-name"]=i),n}generateAuthHeaders(){return!this.adminSecret&&!this.accessToken?null:this.adminSecret?{"x-hasura-admin-secret":this.adminSecret}:{Authorization:`Bearer ${this.accessToken}`}}}class y{constructor({url:e}){this.url=e,this.api=new d({url:e})}async upload(e){const r=new FormData;r.append("file",e.file);const{fileMetadata:i,error:a}=await this.api.upload(o(s({},e),{file:r}));return a?{fileMetadata:null,error:a}:i?{fileMetadata:i,error:null}:{fileMetadata:null,error:new Error("Invalid file returned")}}getUrl(e){return this.getPublicUrl(e)}getPublicUrl(e){const{fileId:r}=e;return`${this.url}/files/${r}`}async getPresignedUrl(e){const{presignedUrl:r,error:i}=await this.api.getPresignedUrl(e);return i?{presignedUrl:null,error:i}:r?{presignedUrl:r,error:null}:{presignedUrl:null,error:new Error("Invalid file id")}}async delete(e){const{error:r}=await this.api.delete(e);return r?{error:r}:{error:null}}setAccessToken(e){return this.api.setAccessToken(e),this}setAdminSecret(e){return this.api.setAdminSecret(e),this}}exports.HasuraStorageApi=d;exports.HasuraStorageClient=y; | ||
//# sourceMappingURL=index.cjs.js.map |
export * from './hasura-storage-api'; | ||
export * from './hasura-storage-client'; | ||
export * from './utils/types'; | ||
//# sourceMappingURL=index.d.ts.map |
@@ -1,3 +0,149 @@ | ||
var fr=Object.create;var D=Object.defineProperty;var dr=Object.getOwnPropertyDescriptor;var pr=Object.getOwnPropertyNames;var hr=Object.getPrototypeOf,mr=Object.prototype.hasOwnProperty;var vr=r=>D(r,"__esModule",{value:!0});var c=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports);var gr=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of pr(e))!mr.call(r,s)&&(t||s!=="default")&&D(r,s,{get:()=>e[s],enumerable:!(n=dr(e,s))||n.enumerable});return r},yr=(r,e)=>gr(vr(D(r!=null?fr(hr(r)):{},"default",!e&&r&&r.__esModule?{get:()=>r.default,enumerable:!0}:{value:r,enumerable:!0})),r);var B=c((dt,te)=>{"use strict";te.exports=function(e,t){return function(){for(var s=new Array(arguments.length),a=0;a<s.length;a++)s[a]=arguments[a];return e.apply(t,s)}}});var m=c((pt,ie)=>{"use strict";var xr=B(),w=Object.prototype.toString;function I(r){return w.call(r)==="[object Array]"}function H(r){return typeof r=="undefined"}function wr(r){return r!==null&&!H(r)&&r.constructor!==null&&!H(r.constructor)&&typeof r.constructor.isBuffer=="function"&&r.constructor.isBuffer(r)}function br(r){return w.call(r)==="[object ArrayBuffer]"}function Sr(r){return typeof FormData!="undefined"&&r instanceof FormData}function Er(r){var e;return typeof ArrayBuffer!="undefined"&&ArrayBuffer.isView?e=ArrayBuffer.isView(r):e=r&&r.buffer&&r.buffer instanceof ArrayBuffer,e}function Ar(r){return typeof r=="string"}function Pr(r){return typeof r=="number"}function ne(r){return r!==null&&typeof r=="object"}function q(r){if(w.call(r)!=="[object Object]")return!1;var e=Object.getPrototypeOf(r);return e===null||e===Object.prototype}function qr(r){return w.call(r)==="[object Date]"}function Ur(r){return w.call(r)==="[object File]"}function Rr(r){return w.call(r)==="[object Blob]"}function se(r){return w.call(r)==="[object Function]"}function Cr(r){return ne(r)&&se(r.pipe)}function Or(r){return typeof URLSearchParams!="undefined"&&r instanceof URLSearchParams}function Tr(r){return r.trim?r.trim():r.replace(/^\s+|\s+$/g,"")}function Nr(){return typeof navigator!="undefined"&&(navigator.product==="ReactNative"||navigator.product==="NativeScript"||navigator.product==="NS")?!1:typeof window!="undefined"&&typeof document!="undefined"}function M(r,e){if(!(r===null||typeof r=="undefined"))if(typeof r!="object"&&(r=[r]),I(r))for(var t=0,n=r.length;t<n;t++)e.call(null,r[t],t,r);else for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&e.call(null,r[s],s,r)}function L(){var r={};function e(s,a){q(r[a])&&q(s)?r[a]=L(r[a],s):q(s)?r[a]=L({},s):I(s)?r[a]=s.slice():r[a]=s}for(var t=0,n=arguments.length;t<n;t++)M(arguments[t],e);return r}function jr(r,e,t){return M(e,function(s,a){t&&typeof s=="function"?r[a]=xr(s,t):r[a]=s}),r}function kr(r){return r.charCodeAt(0)===65279&&(r=r.slice(1)),r}ie.exports={isArray:I,isArrayBuffer:br,isBuffer:wr,isFormData:Sr,isArrayBufferView:Er,isString:Ar,isNumber:Pr,isObject:ne,isPlainObject:q,isUndefined:H,isDate:qr,isFile:Ur,isBlob:Rr,isFunction:se,isStream:Cr,isURLSearchParams:Or,isStandardBrowserEnv:Nr,forEach:M,merge:L,extend:jr,trim:Tr,stripBOM:kr}});var F=c((ht,oe)=>{"use strict";var S=m();function ae(r){return encodeURIComponent(r).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}oe.exports=function(e,t,n){if(!t)return e;var s;if(n)s=n(t);else if(S.isURLSearchParams(t))s=t.toString();else{var a=[];S.forEach(t,function(i,g){i===null||typeof i=="undefined"||(S.isArray(i)?g=g+"[]":i=[i],S.forEach(i,function(d){S.isDate(d)?d=d.toISOString():S.isObject(d)&&(d=JSON.stringify(d)),a.push(ae(g)+"="+ae(d))}))}),s=a.join("&")}if(s){var o=e.indexOf("#");o!==-1&&(e=e.slice(0,o)),e+=(e.indexOf("?")===-1?"?":"&")+s}return e}});var le=c((mt,ue)=>{"use strict";var Dr=m();function U(){this.handlers=[]}U.prototype.use=function(e,t,n){return this.handlers.push({fulfilled:e,rejected:t,synchronous:n?n.synchronous:!1,runWhen:n?n.runWhen:null}),this.handlers.length-1};U.prototype.eject=function(e){this.handlers[e]&&(this.handlers[e]=null)};U.prototype.forEach=function(e){Dr.forEach(this.handlers,function(n){n!==null&&e(n)})};ue.exports=U});var fe=c((vt,ce)=>{"use strict";var Br=m();ce.exports=function(e,t){Br.forEach(e,function(s,a){a!==t&&a.toUpperCase()===t.toUpperCase()&&(e[t]=s,delete e[a])})}});var J=c((gt,de)=>{"use strict";de.exports=function(e,t,n,s,a){return e.config=t,n&&(e.code=n),e.request=s,e.response=a,e.isAxiosError=!0,e.toJSON=function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:this.config,code:this.code}},e}});var G=c((yt,pe)=>{"use strict";var Hr=J();pe.exports=function(e,t,n,s,a){var o=new Error(e);return Hr(o,t,n,s,a)}});var me=c((xt,he)=>{"use strict";var Lr=G();he.exports=function(e,t,n){var s=n.config.validateStatus;!n.status||!s||s(n.status)?e(n):t(Lr("Request failed with status code "+n.status,n.config,null,n.request,n))}});var ge=c((wt,ve)=>{"use strict";var R=m();ve.exports=R.isStandardBrowserEnv()?function(){return{write:function(t,n,s,a,o,u){var i=[];i.push(t+"="+encodeURIComponent(n)),R.isNumber(s)&&i.push("expires="+new Date(s).toGMTString()),R.isString(a)&&i.push("path="+a),R.isString(o)&&i.push("domain="+o),u===!0&&i.push("secure"),document.cookie=i.join("; ")},read:function(t){var n=document.cookie.match(new RegExp("(^|;\\s*)("+t+")=([^;]*)"));return n?decodeURIComponent(n[3]):null},remove:function(t){this.write(t,"",Date.now()-864e5)}}}():function(){return{write:function(){},read:function(){return null},remove:function(){}}}()});var xe=c((bt,ye)=>{"use strict";ye.exports=function(e){return/^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(e)}});var be=c((St,we)=>{"use strict";we.exports=function(e,t){return t?e.replace(/\/+$/,"")+"/"+t.replace(/^\/+/,""):e}});var Ee=c((Et,Se)=>{"use strict";var Ir=xe(),Mr=be();Se.exports=function(e,t){return e&&!Ir(t)?Mr(e,t):t}});var Pe=c((At,Ae)=>{"use strict";var _=m(),Fr=["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"];Ae.exports=function(e){var t={},n,s,a;return e&&_.forEach(e.split(` | ||
`),function(u){if(a=u.indexOf(":"),n=_.trim(u.substr(0,a)).toLowerCase(),s=_.trim(u.substr(a+1)),n){if(t[n]&&Fr.indexOf(n)>=0)return;n==="set-cookie"?t[n]=(t[n]?t[n]:[]).concat([s]):t[n]=t[n]?t[n]+", "+s:s}}),t}});var Re=c((Pt,Ue)=>{"use strict";var qe=m();Ue.exports=qe.isStandardBrowserEnv()?function(){var e=/(msie|trident)/i.test(navigator.userAgent),t=document.createElement("a"),n;function s(a){var o=a;return e&&(t.setAttribute("href",o),o=t.href),t.setAttribute("href",o),{href:t.href,protocol:t.protocol?t.protocol.replace(/:$/,""):"",host:t.host,search:t.search?t.search.replace(/^\?/,""):"",hash:t.hash?t.hash.replace(/^#/,""):"",hostname:t.hostname,port:t.port,pathname:t.pathname.charAt(0)==="/"?t.pathname:"/"+t.pathname}}return n=s(window.location.href),function(o){var u=qe.isString(o)?s(o):o;return u.protocol===n.protocol&&u.host===n.host}}():function(){return function(){return!0}}()});var V=c((qt,Ce)=>{"use strict";var C=m(),Jr=me(),Gr=ge(),_r=F(),zr=Ee(),Vr=Pe(),Kr=Re(),z=G();Ce.exports=function(e){return new Promise(function(n,s){var a=e.data,o=e.headers,u=e.responseType;C.isFormData(a)&&delete o["Content-Type"];var i=new XMLHttpRequest;if(e.auth){var g=e.auth.username||"",b=e.auth.password?unescape(encodeURIComponent(e.auth.password)):"";o.Authorization="Basic "+btoa(g+":"+b)}var d=zr(e.baseURL,e.url);i.open(e.method.toUpperCase(),_r(d,e.params,e.paramsSerializer),!0),i.timeout=e.timeout;function f(){if(!!i){var x="getAllResponseHeaders"in i?Vr(i.getAllResponseHeaders()):null,y=!u||u==="text"||u==="json"?i.responseText:i.response,A={data:y,status:i.status,statusText:i.statusText,headers:x,config:e,request:i};Jr(n,s,A),i=null}}if("onloadend"in i?i.onloadend=f:i.onreadystatechange=function(){!i||i.readyState!==4||i.status===0&&!(i.responseURL&&i.responseURL.indexOf("file:")===0)||setTimeout(f)},i.onabort=function(){!i||(s(z("Request aborted",e,"ECONNABORTED",i)),i=null)},i.onerror=function(){s(z("Network Error",e,null,i)),i=null},i.ontimeout=function(){var y="timeout of "+e.timeout+"ms exceeded";e.timeoutErrorMessage&&(y=e.timeoutErrorMessage),s(z(y,e,e.transitional&&e.transitional.clarifyTimeoutError?"ETIMEDOUT":"ECONNABORTED",i)),i=null},C.isStandardBrowserEnv()){var l=(e.withCredentials||Kr(d))&&e.xsrfCookieName?Gr.read(e.xsrfCookieName):void 0;l&&(o[e.xsrfHeaderName]=l)}"setRequestHeader"in i&&C.forEach(o,function(y,A){typeof a=="undefined"&&A.toLowerCase()==="content-type"?delete o[A]:i.setRequestHeader(A,y)}),C.isUndefined(e.withCredentials)||(i.withCredentials=!!e.withCredentials),u&&u!=="json"&&(i.responseType=e.responseType),typeof e.onDownloadProgress=="function"&&i.addEventListener("progress",e.onDownloadProgress),typeof e.onUploadProgress=="function"&&i.upload&&i.upload.addEventListener("progress",e.onUploadProgress),e.cancelToken&&e.cancelToken.promise.then(function(y){!i||(i.abort(),s(y),i=null)}),a||(a=null),i.send(a)})}});var T=c((Ut,Ne)=>{"use strict";var p=m(),Oe=fe(),$r=J(),Wr={"Content-Type":"application/x-www-form-urlencoded"};function Te(r,e){!p.isUndefined(r)&&p.isUndefined(r["Content-Type"])&&(r["Content-Type"]=e)}function Xr(){var r;return typeof XMLHttpRequest!="undefined"?r=V():typeof process!="undefined"&&Object.prototype.toString.call(process)==="[object process]"&&(r=V()),r}function Yr(r,e,t){if(p.isString(r))try{return(e||JSON.parse)(r),p.trim(r)}catch(n){if(n.name!=="SyntaxError")throw n}return(t||JSON.stringify)(r)}var O={transitional:{silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},adapter:Xr(),transformRequest:[function(e,t){return Oe(t,"Accept"),Oe(t,"Content-Type"),p.isFormData(e)||p.isArrayBuffer(e)||p.isBuffer(e)||p.isStream(e)||p.isFile(e)||p.isBlob(e)?e:p.isArrayBufferView(e)?e.buffer:p.isURLSearchParams(e)?(Te(t,"application/x-www-form-urlencoded;charset=utf-8"),e.toString()):p.isObject(e)||t&&t["Content-Type"]==="application/json"?(Te(t,"application/json"),Yr(e)):e}],transformResponse:[function(e){var t=this.transitional,n=t&&t.silentJSONParsing,s=t&&t.forcedJSONParsing,a=!n&&this.responseType==="json";if(a||s&&p.isString(e)&&e.length)try{return JSON.parse(e)}catch(o){if(a)throw o.name==="SyntaxError"?$r(o,this,"E_JSON_PARSE"):o}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,validateStatus:function(e){return e>=200&&e<300}};O.headers={common:{Accept:"application/json, text/plain, */*"}};p.forEach(["delete","get","head"],function(e){O.headers[e]={}});p.forEach(["post","put","patch"],function(e){O.headers[e]=p.merge(Wr)});Ne.exports=O});var ke=c((Rt,je)=>{"use strict";var Zr=m(),Qr=T();je.exports=function(e,t,n){var s=this||Qr;return Zr.forEach(n,function(o){e=o.call(s,e,t)}),e}});var K=c((Ct,De)=>{"use strict";De.exports=function(e){return!!(e&&e.__CANCEL__)}});var Le=c((Ot,He)=>{"use strict";var Be=m(),$=ke(),et=K(),rt=T();function W(r){r.cancelToken&&r.cancelToken.throwIfRequested()}He.exports=function(e){W(e),e.headers=e.headers||{},e.data=$.call(e,e.data,e.headers,e.transformRequest),e.headers=Be.merge(e.headers.common||{},e.headers[e.method]||{},e.headers),Be.forEach(["delete","get","head","post","put","patch","common"],function(s){delete e.headers[s]});var t=e.adapter||rt.adapter;return t(e).then(function(s){return W(e),s.data=$.call(e,s.data,s.headers,e.transformResponse),s},function(s){return et(s)||(W(e),s&&s.response&&(s.response.data=$.call(e,s.response.data,s.response.headers,e.transformResponse))),Promise.reject(s)})}});var X=c((Tt,Ie)=>{"use strict";var h=m();Ie.exports=function(e,t){t=t||{};var n={},s=["url","method","data"],a=["headers","auth","proxy","params"],o=["baseURL","transformRequest","transformResponse","paramsSerializer","timeout","timeoutMessage","withCredentials","adapter","responseType","xsrfCookieName","xsrfHeaderName","onUploadProgress","onDownloadProgress","decompress","maxContentLength","maxBodyLength","maxRedirects","transport","httpAgent","httpsAgent","cancelToken","socketPath","responseEncoding"],u=["validateStatus"];function i(f,l){return h.isPlainObject(f)&&h.isPlainObject(l)?h.merge(f,l):h.isPlainObject(l)?h.merge({},l):h.isArray(l)?l.slice():l}function g(f){h.isUndefined(t[f])?h.isUndefined(e[f])||(n[f]=i(void 0,e[f])):n[f]=i(e[f],t[f])}h.forEach(s,function(l){h.isUndefined(t[l])||(n[l]=i(void 0,t[l]))}),h.forEach(a,g),h.forEach(o,function(l){h.isUndefined(t[l])?h.isUndefined(e[l])||(n[l]=i(void 0,e[l])):n[l]=i(void 0,t[l])}),h.forEach(u,function(l){l in t?n[l]=i(e[l],t[l]):l in e&&(n[l]=i(void 0,e[l]))});var b=s.concat(a).concat(o).concat(u),d=Object.keys(e).concat(Object.keys(t)).filter(function(l){return b.indexOf(l)===-1});return h.forEach(d,g),n}});var Me=c((Nt,tt)=>{tt.exports={name:"axios",version:"0.21.4",description:"Promise based HTTP client for the browser and node.js",main:"index.js",scripts:{test:"grunt test",start:"node ./sandbox/server.js",build:"NODE_ENV=production grunt build",preversion:"npm test",version:"npm run build && grunt version && git add -A dist && git add CHANGELOG.md bower.json package.json",postversion:"git push && git push --tags",examples:"node ./examples/server.js",coveralls:"cat coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js",fix:"eslint --fix lib/**/*.js"},repository:{type:"git",url:"https://github.com/axios/axios.git"},keywords:["xhr","http","ajax","promise","node"],author:"Matt Zabriskie",license:"MIT",bugs:{url:"https://github.com/axios/axios/issues"},homepage:"https://axios-http.com",devDependencies:{coveralls:"^3.0.0","es6-promise":"^4.2.4",grunt:"^1.3.0","grunt-banner":"^0.6.0","grunt-cli":"^1.2.0","grunt-contrib-clean":"^1.1.0","grunt-contrib-watch":"^1.0.0","grunt-eslint":"^23.0.0","grunt-karma":"^4.0.0","grunt-mocha-test":"^0.13.3","grunt-ts":"^6.0.0-beta.19","grunt-webpack":"^4.0.2","istanbul-instrumenter-loader":"^1.0.0","jasmine-core":"^2.4.1",karma:"^6.3.2","karma-chrome-launcher":"^3.1.0","karma-firefox-launcher":"^2.1.0","karma-jasmine":"^1.1.1","karma-jasmine-ajax":"^0.1.13","karma-safari-launcher":"^1.0.0","karma-sauce-launcher":"^4.3.6","karma-sinon":"^1.0.5","karma-sourcemap-loader":"^0.3.8","karma-webpack":"^4.0.2","load-grunt-tasks":"^3.5.2",minimist:"^1.2.0",mocha:"^8.2.1",sinon:"^4.5.0","terser-webpack-plugin":"^4.2.3",typescript:"^4.0.5","url-search-params":"^0.10.0",webpack:"^4.44.2","webpack-dev-server":"^3.11.0"},browser:{"./lib/adapters/http.js":"./lib/adapters/xhr.js"},jsdelivr:"dist/axios.min.js",unpkg:"dist/axios.min.js",typings:"./index.d.ts",dependencies:{"follow-redirects":"^1.14.0"},bundlesize:[{path:"./dist/axios.min.js",threshold:"5kB"}]}});var ze=c((jt,_e)=>{"use strict";var Je=Me(),Y={};["object","boolean","number","function","string","symbol"].forEach(function(r,e){Y[r]=function(n){return typeof n===r||"a"+(e<1?"n ":" ")+r}});var Fe={},nt=Je.version.split(".");function Ge(r,e){for(var t=e?e.split("."):nt,n=r.split("."),s=0;s<3;s++){if(t[s]>n[s])return!0;if(t[s]<n[s])return!1}return!1}Y.transitional=function(e,t,n){var s=t&&Ge(t);function a(o,u){return"[Axios v"+Je.version+"] Transitional option '"+o+"'"+u+(n?". "+n:"")}return function(o,u,i){if(e===!1)throw new Error(a(u," has been removed in "+t));return s&&!Fe[u]&&(Fe[u]=!0,console.warn(a(u," has been deprecated since v"+t+" and will be removed in the near future"))),e?e(o,u,i):!0}};function st(r,e,t){if(typeof r!="object")throw new TypeError("options must be an object");for(var n=Object.keys(r),s=n.length;s-- >0;){var a=n[s],o=e[a];if(o){var u=r[a],i=u===void 0||o(u,a,r);if(i!==!0)throw new TypeError("option "+a+" must be "+i);continue}if(t!==!0)throw Error("Unknown option "+a)}}_e.exports={isOlderVersion:Ge,assertOptions:st,validators:Y}});var Ye=c((kt,Xe)=>{"use strict";var $e=m(),it=F(),Ve=le(),Ke=Le(),N=X(),We=ze(),E=We.validators;function P(r){this.defaults=r,this.interceptors={request:new Ve,response:new Ve}}P.prototype.request=function(e){typeof e=="string"?(e=arguments[1]||{},e.url=arguments[0]):e=e||{},e=N(this.defaults,e),e.method?e.method=e.method.toLowerCase():this.defaults.method?e.method=this.defaults.method.toLowerCase():e.method="get";var t=e.transitional;t!==void 0&&We.assertOptions(t,{silentJSONParsing:E.transitional(E.boolean,"1.0.0"),forcedJSONParsing:E.transitional(E.boolean,"1.0.0"),clarifyTimeoutError:E.transitional(E.boolean,"1.0.0")},!1);var n=[],s=!0;this.interceptors.request.forEach(function(f){typeof f.runWhen=="function"&&f.runWhen(e)===!1||(s=s&&f.synchronous,n.unshift(f.fulfilled,f.rejected))});var a=[];this.interceptors.response.forEach(function(f){a.push(f.fulfilled,f.rejected)});var o;if(!s){var u=[Ke,void 0];for(Array.prototype.unshift.apply(u,n),u=u.concat(a),o=Promise.resolve(e);u.length;)o=o.then(u.shift(),u.shift());return o}for(var i=e;n.length;){var g=n.shift(),b=n.shift();try{i=g(i)}catch(d){b(d);break}}try{o=Ke(i)}catch(d){return Promise.reject(d)}for(;a.length;)o=o.then(a.shift(),a.shift());return o};P.prototype.getUri=function(e){return e=N(this.defaults,e),it(e.url,e.params,e.paramsSerializer).replace(/^\?/,"")};$e.forEach(["delete","get","head","options"],function(e){P.prototype[e]=function(t,n){return this.request(N(n||{},{method:e,url:t,data:(n||{}).data}))}});$e.forEach(["post","put","patch"],function(e){P.prototype[e]=function(t,n,s){return this.request(N(s||{},{method:e,url:t,data:n}))}});Xe.exports=P});var Q=c((Dt,Ze)=>{"use strict";function Z(r){this.message=r}Z.prototype.toString=function(){return"Cancel"+(this.message?": "+this.message:"")};Z.prototype.__CANCEL__=!0;Ze.exports=Z});var er=c((Bt,Qe)=>{"use strict";var at=Q();function j(r){if(typeof r!="function")throw new TypeError("executor must be a function.");var e;this.promise=new Promise(function(s){e=s});var t=this;r(function(s){t.reason||(t.reason=new at(s),e(t.reason))})}j.prototype.throwIfRequested=function(){if(this.reason)throw this.reason};j.source=function(){var e,t=new j(function(s){e=s});return{token:t,cancel:e}};Qe.exports=j});var tr=c((Ht,rr)=>{"use strict";rr.exports=function(e){return function(n){return e.apply(null,n)}}});var sr=c((Lt,nr)=>{"use strict";nr.exports=function(e){return typeof e=="object"&&e.isAxiosError===!0}});var or=c((It,ee)=>{"use strict";var ir=m(),ot=B(),k=Ye(),ut=X(),lt=T();function ar(r){var e=new k(r),t=ot(k.prototype.request,e);return ir.extend(t,k.prototype,e),ir.extend(t,e),t}var v=ar(lt);v.Axios=k;v.create=function(e){return ar(ut(v.defaults,e))};v.Cancel=Q();v.CancelToken=er();v.isCancel=K();v.all=function(e){return Promise.all(e)};v.spread=tr();v.isAxiosError=sr();ee.exports=v;ee.exports.default=v});var lr=c((Mt,ur)=>{ur.exports=or()});var cr=yr(lr()),re=class{constructor({url:e}){this.url=e,this.httpClient=cr.default.create({baseURL:this.url})}async upload(e){try{return{fileMetadata:(await this.httpClient.post("/files",e.file,{headers:{...this.generateUploadHeaders(e),...this.generateAuthHeaders()}})).data,error:null}}catch(t){return{fileMetadata:null,error:t}}}async getPresignedUrl(e){try{let{fileId:t}=e;return{presignedUrl:(await this.httpClient.get(`/files/${t}/presignedurl`,{headers:{...this.generateAuthHeaders()}})).data,error:null}}catch(t){return{presignedUrl:null,error:t}}}async delete(e){try{let{fileId:t}=e;return await this.httpClient.delete(`/files/${t}`,{headers:{...this.generateAuthHeaders()}}),{error:null}}catch(t){return{error:t}}}setAccessToken(e){return this.accessToken=e,this}setAdminSecret(e){return this.adminSecret=e,this}generateUploadHeaders(e){let{bucketId:t,name:n,id:s}=e,a={};return t&&(a["x-nhost-bucket-id"]=t),s&&(a["x-nhost-file-id"]=s),n&&(a["x-nhost-file-name"]=n),a}generateAuthHeaders(){return!this.adminSecret&&!this.accessToken?null:this.adminSecret?{"x-hasura-admin-secret":this.adminSecret}:{Authorization:`Bearer ${this.accessToken}`}}};var ct=class{constructor({url:e}){this.url=e,this.api=new re({url:e})}async upload(e){let t=new FormData;t.append("file",e.file);let{fileMetadata:n,error:s}=await this.api.upload({...e,file:t});return s?{fileMetadata:null,error:s}:n?{fileMetadata:n,error:null}:{fileMetadata:null,error:new Error("Invalid file returned")}}getUrl(e){return this.getPublicUrl(e)}getPublicUrl(e){let{fileId:t}=e;return`${this.url}/files/${t}`}async getPresignedUrl(e){let{presignedUrl:t,error:n}=await this.api.getPresignedUrl(e);return n?{presignedUrl:null,error:n}:t?{presignedUrl:t,error:null}:{presignedUrl:null,error:new Error("Invalid file id")}}async delete(e){let{error:t}=await this.api.delete(e);return t?{error:t}:{error:null}}setAccessToken(e){return this.api.setAccessToken(e),this}setAdminSecret(e){return this.api.setAdminSecret(e),this}};export{re as HasuraStorageApi,ct as HasuraStorageClient}; | ||
var __defProp = Object.defineProperty; | ||
var __defProps = Object.defineProperties; | ||
var __getOwnPropDescs = Object.getOwnPropertyDescriptors; | ||
var __getOwnPropSymbols = Object.getOwnPropertySymbols; | ||
var __hasOwnProp = Object.prototype.hasOwnProperty; | ||
var __propIsEnum = Object.prototype.propertyIsEnumerable; | ||
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; | ||
var __spreadValues = (a, b) => { | ||
for (var prop in b || (b = {})) | ||
if (__hasOwnProp.call(b, prop)) | ||
__defNormalProp(a, prop, b[prop]); | ||
if (__getOwnPropSymbols) | ||
for (var prop of __getOwnPropSymbols(b)) { | ||
if (__propIsEnum.call(b, prop)) | ||
__defNormalProp(a, prop, b[prop]); | ||
} | ||
return a; | ||
}; | ||
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b)); | ||
import axios from "axios"; | ||
class HasuraStorageApi { | ||
constructor({ url }) { | ||
this.url = url; | ||
this.httpClient = axios.create({ | ||
baseURL: this.url | ||
}); | ||
} | ||
async upload(params) { | ||
try { | ||
const res = await this.httpClient.post("/files", params.file, { | ||
headers: __spreadValues(__spreadValues({}, this.generateUploadHeaders(params)), this.generateAuthHeaders()) | ||
}); | ||
return { fileMetadata: res.data, error: null }; | ||
} catch (error) { | ||
return { fileMetadata: null, error }; | ||
} | ||
} | ||
async getPresignedUrl(params) { | ||
try { | ||
const { fileId } = params; | ||
const res = await this.httpClient.get(`/files/${fileId}/presignedurl`, { | ||
headers: __spreadValues({}, this.generateAuthHeaders()) | ||
}); | ||
return { presignedUrl: res.data, error: null }; | ||
} catch (error) { | ||
return { presignedUrl: null, error }; | ||
} | ||
} | ||
async delete(params) { | ||
try { | ||
const { fileId } = params; | ||
await this.httpClient.delete(`/files/${fileId}`, { | ||
headers: __spreadValues({}, this.generateAuthHeaders()) | ||
}); | ||
return { error: null }; | ||
} catch (error) { | ||
return { error }; | ||
} | ||
} | ||
setAccessToken(accessToken) { | ||
this.accessToken = accessToken; | ||
return this; | ||
} | ||
setAdminSecret(adminSecret) { | ||
this.adminSecret = adminSecret; | ||
return this; | ||
} | ||
generateUploadHeaders(params) { | ||
const { bucketId, name, id } = params; | ||
const uploadheaders = {}; | ||
if (bucketId) { | ||
uploadheaders["x-nhost-bucket-id"] = bucketId; | ||
} | ||
if (id) { | ||
uploadheaders["x-nhost-file-id"] = id; | ||
} | ||
if (name) { | ||
uploadheaders["x-nhost-file-name"] = name; | ||
} | ||
return uploadheaders; | ||
} | ||
generateAuthHeaders() { | ||
if (!this.adminSecret && !this.accessToken) { | ||
return null; | ||
} | ||
if (this.adminSecret) { | ||
return { | ||
"x-hasura-admin-secret": this.adminSecret | ||
}; | ||
} | ||
return { | ||
Authorization: `Bearer ${this.accessToken}` | ||
}; | ||
} | ||
} | ||
class HasuraStorageClient { | ||
constructor({ url }) { | ||
this.url = url; | ||
this.api = new HasuraStorageApi({ url }); | ||
} | ||
async upload(params) { | ||
const file = new FormData(); | ||
file.append("file", params.file); | ||
const { fileMetadata, error } = await this.api.upload(__spreadProps(__spreadValues({}, params), { | ||
file | ||
})); | ||
if (error) { | ||
return { fileMetadata: null, error }; | ||
} | ||
if (!fileMetadata) { | ||
return { fileMetadata: null, error: new Error("Invalid file returned") }; | ||
} | ||
return { fileMetadata, error: null }; | ||
} | ||
getUrl(params) { | ||
return this.getPublicUrl(params); | ||
} | ||
getPublicUrl(params) { | ||
const { fileId } = params; | ||
return `${this.url}/files/${fileId}`; | ||
} | ||
async getPresignedUrl(params) { | ||
const { presignedUrl, error } = await this.api.getPresignedUrl(params); | ||
if (error) { | ||
return { presignedUrl: null, error }; | ||
} | ||
if (!presignedUrl) { | ||
return { presignedUrl: null, error: new Error("Invalid file id") }; | ||
} | ||
return { presignedUrl, error: null }; | ||
} | ||
async delete(params) { | ||
const { error } = await this.api.delete(params); | ||
if (error) { | ||
return { error }; | ||
} | ||
return { error: null }; | ||
} | ||
setAccessToken(accessToken) { | ||
this.api.setAccessToken(accessToken); | ||
return this; | ||
} | ||
setAdminSecret(adminSecret) { | ||
this.api.setAdminSecret(adminSecret); | ||
return this; | ||
} | ||
} | ||
export { HasuraStorageApi, HasuraStorageClient }; | ||
//# sourceMappingURL=index.es.js.map |
@@ -83,1 +83,2 @@ export interface StorageUploadParams { | ||
export {}; | ||
//# sourceMappingURL=types.d.ts.map |
{ | ||
"name": "@nhost/hasura-storage-js", | ||
"version": "0.2.0", | ||
"version": "0.2.1", | ||
"description": "Hasura-storage client", | ||
@@ -21,17 +21,31 @@ "license": "MIT", | ||
"main": "dist/index.cjs.js", | ||
"module": "dist/index.es.js", | ||
"types": "dist/index.d.ts", | ||
"source": "src/index.ts", | ||
"files": [ | ||
"dist", | ||
"umd", | ||
"README.md" | ||
], | ||
"exports": { | ||
".": { | ||
"import": "./dist/index.es.js", | ||
"require": "./dist/index.cjs.js" | ||
} | ||
}, | ||
"publishConfig": { | ||
"access": "public" | ||
}, | ||
"files": [ | ||
"dist" | ||
], | ||
"dependencies": { | ||
"axios": "^0.21.1" | ||
"axios": "^0.26.0" | ||
}, | ||
"devDependencies": {}, | ||
"devDependencies": { | ||
"@nhost/docgen": "0.1.1" | ||
}, | ||
"scripts": { | ||
"build": "run-s build:esbuild build:types", | ||
"build:esbuild": "node ../../esbuild.lib.js", | ||
"build:types": "tsc --build tsconfig.types.json", | ||
"test": "pnpm jest --runInBand --config ../../jest.config.base.js", | ||
"dev": "vite build --config ../../config/vite.lib.dev.config.js", | ||
"build": "run-p build:lib build:umd", | ||
"build:lib": "vite build --config ../../config/vite.lib.config.js", | ||
"build:umd": "vite build --config ../../config/vite.lib.umd.config.js", | ||
"test": "pnpm jest --runInBand --config ../../config/jest.config.js", | ||
"prettier": "prettier --check src/", | ||
@@ -42,16 +56,7 @@ "prettier:fix": "prettier --write src/", | ||
"verify": "run-p prettier lint", | ||
"verify:fix": "run-p prettier:fix lint:fix" | ||
"verify:fix": "run-p prettier:fix lint:fix", | ||
"typedoc": "typedoc --options ./storage.typedoc.json --tsconfig ./typedoc.tsconfig.json", | ||
"docgen": "pnpm typedoc && docgen --config ./storage.docgen.json" | ||
}, | ||
"exports": { | ||
".": { | ||
"import": { | ||
"node": "./dist/index.cjs.js", | ||
"default": "./dist/index.es.js" | ||
}, | ||
"require": "./dist/index.cjs.js" | ||
} | ||
}, | ||
"module": "dist/index.es.js", | ||
"typings": "./dist/index.d.ts", | ||
"readme": "# Hasura Storage JS SDK\n\nHasura Auth JS SDK to handle **Auth** with [Hasura](https://hasura.io/).\n\n## Install\n\n`$ npm install @nhost/hasura-storage-js`\n\n## Documentation\n\n[https://docs.nhost.io/reference/sdk/authentication](https://docs.nhost.io/reference/sdk/storage)\n" | ||
"readme": "# Hasura Storage JS SDK\n\nHasura Auth JS SDK to handle **Auth** with [Hasura](https://hasura.io/).\n\n## Install\n\n`$ npm install @nhost/hasura-storage-js`\n\n## Documentation\n\n[https://docs.nhost.io/reference/javascript/storage](https://docs.nhost.io/reference/javascript/storage)\n" | ||
} |
@@ -11,2 +11,2 @@ # Hasura Storage JS SDK | ||
[https://docs.nhost.io/reference/sdk/authentication](https://docs.nhost.io/reference/sdk/storage) | ||
[https://docs.nhost.io/reference/javascript/storage](https://docs.nhost.io/reference/javascript/storage) |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
146394
25
600
1
1
+ Addedaxios@0.26.1(transitive)
- Removedaxios@0.21.4(transitive)
Updatedaxios@^0.26.0