@nhost/hasura-storage-js
Advanced tools
Comparing version 1.13.2 to 2.0.0
@@ -1,2 +0,2 @@ | ||
import { ApiDeleteParams, ApiDeleteResponse, ApiGetPresignedUrlParams, ApiGetPresignedUrlResponse, ApiUploadParams, ApiUploadResponse } from './utils'; | ||
import { ApiDeleteParams, ApiDeleteResponse, ApiGetPresignedUrlParams, ApiGetPresignedUrlResponse, ApiUploadParams, StorageUploadResponse } from './utils/types'; | ||
/** | ||
@@ -8,3 +8,2 @@ * @internal | ||
private url; | ||
private httpClient; | ||
private accessToken?; | ||
@@ -15,3 +14,3 @@ private adminSecret?; | ||
}); | ||
upload(params: ApiUploadParams): Promise<ApiUploadResponse>; | ||
upload(params: ApiUploadParams): Promise<StorageUploadResponse>; | ||
getPresignedUrl(params: ApiGetPresignedUrlParams): Promise<ApiGetPresignedUrlResponse>; | ||
@@ -33,5 +32,4 @@ delete(params: ApiDeleteParams): Promise<ApiDeleteResponse>; | ||
setAdminSecret(adminSecret?: string): HasuraStorageApi; | ||
private generateUploadHeaders; | ||
private generateAuthHeaders; | ||
} | ||
//# sourceMappingURL=hasura-storage-api.d.ts.map |
@@ -58,6 +58,2 @@ import { StorageDeleteParams, StorageDeleteResponse, StorageGetPresignedUrlParams, StorageGetPresignedUrlResponse, StorageGetUrlParams, StorageUploadFileParams, StorageUploadFormDataParams, StorageUploadResponse } from './utils'; | ||
/** | ||
* @deprecated Use `nhost.storage.getPublicUrl()` instead. | ||
*/ | ||
getUrl(params: StorageGetUrlParams): string; | ||
/** | ||
* Use `nhost.storage.getPublicUrl` to get the public URL of a file. The public URL can be used for un-authenticated users to access files. To access public files the `public` role must have permissions to select the file in the `storage.files` table. | ||
@@ -64,0 +60,0 @@ * |
@@ -1,2 +0,2 @@ | ||
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const y=require("axios"),I=require("form-data"),o=require("xstate"),E=(r,e)=>{const t=Object.entries(e).map(([s,a])=>`${Array.from(s)[0]}=${a}`).join("&");return t?`${r}?${t}`:r},m=r=>{try{return btoa(r),r}catch{return encodeURIComponent(r)}};class O{constructor({url:e}){this.url=e,this.httpClient=y.create({baseURL:this.url})}async upload(e){const{formData:t}=e;try{return{fileMetadata:(await this.httpClient.post("/files",t,{headers:{...this.generateUploadHeaders(e),...this.generateAuthHeaders(),"Content-Type":"multipart/form-data"}})).data,error:null}}catch(s){return{fileMetadata:null,error:s}}}async getPresignedUrl(e){try{const{fileId:t}=e,s=`/files/${t}/presignedurl`;return{presignedUrl:(await this.httpClient.get(s,{headers:{...this.generateAuthHeaders()}})).data,error:null}}catch(t){return{presignedUrl:null,error:t}}}async delete(e){try{const{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){const{bucketId:t,name:s,id:a}=e,n={};return t&&(n["x-nhost-bucket-id"]=t),a&&(n["x-nhost-file-id"]=a),s&&(n["x-nhost-file-name"]=m(s)),n}generateAuthHeaders(){return!this.adminSecret&&!this.accessToken?null:this.adminSecret?{"x-hasura-admin-secret":this.adminSecret}:{Authorization:`Bearer ${this.accessToken}`}}}class S{constructor({url:e,adminSecret:t}){this.url=e,this.api=new O({url:e}),this.setAdminSecret(t)}async upload(e){let t;"file"in e?(t=new I,t.append("file",e.file)):t=e.formData;const{fileMetadata:s,error:a}=await this.api.upload({...e,formData:t});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){const{fileId:t,...s}=e;return E(`${this.url}/files/${t}`,s)}async getPresignedUrl(e){const{presignedUrl:t,error:s}=await this.api.getPresignedUrl(e);return s?{presignedUrl:null,error:s}:t?{presignedUrl:t,error:null}:{presignedUrl:null,error:new Error("Invalid file id")}}async delete(e){const{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}}const h={progress:null,loaded:0,error:null,bucketId:void 0,file:void 0,id:void 0},L=()=>o.createMachine({predictableActionArguments:!0,schema:{context:{},events:{}},tsTypes:{},context:{...h},initial:"idle",on:{DESTROY:{actions:"sendDestroy",target:"stopped"}},states:{idle:{on:{ADD:{actions:"addFile"},UPLOAD:{cond:"hasFile",target:"uploading"}}},uploading:{entry:"resetProgress",on:{UPLOAD_PROGRESS:{actions:["incrementProgress","sendProgress"]},UPLOAD_DONE:"uploaded",UPLOAD_ERROR:"error",CANCEL:"idle"},invoke:{src:"uploadFile"}},uploaded:{entry:["setFileMetadata","sendDone"],on:{ADD:{actions:"addFile",target:"idle"},UPLOAD:{actions:"resetContext",target:"uploading"}}},error:{entry:["setError","sendError"],on:{ADD:{actions:"addFile",target:"idle"},UPLOAD:{actions:"resetContext",target:"uploading"}}},stopped:{type:"final"}}},{guards:{hasFile:(r,e)=>!!r.file||!!e.file},actions:{incrementProgress:o.assign({loaded:(r,{loaded:e})=>e,progress:(r,{progress:e})=>e}),setFileMetadata:o.assign({id:(r,{id:e})=>e,bucketId:(r,{bucketId:e})=>e,progress:r=>100}),setError:o.assign({error:(r,{error:e})=>e}),sendProgress:()=>{},sendError:()=>{},sendDestroy:()=>{},sendDone:()=>{},resetProgress:o.assign({progress:r=>null,loaded:r=>0}),resetContext:o.assign(r=>h),addFile:o.assign({file:(r,{file:e})=>e,bucketId:(r,{bucketId:e})=>e,id:(r,{id:e})=>e})},services:{uploadFile:(r,e)=>t=>{const s={"Content-Type":"multipart/form-data"},a=e.id||r.id;a&&(s["x-nhost-file-id"]=a);const n=e.bucketId||r.bucketId;n&&(s["x-nhost-bucket-id"]=n);const l=e.file||r.file;s["x-nhost-file-name"]=m(e.name||l.name);const c=new FormData;c.append("file",l),e.adminSecret&&(s["x-hasura-admin-secret"]=e.adminSecret),e.accessToken&&(s.Authorization=`Bearer ${e.accessToken}`);let u=0;const A=new AbortController;return y.post(e.url+"/files",c,{headers:s,signal:A.signal,onUploadProgress:i=>{const d=i.total?Math.round(i.loaded*l.size/i.total):0,p=d-u;u=d,t({type:"UPLOAD_PROGRESS",progress:i.total?Math.round(d*100/i.total):0,loaded:d,additions:p})}}).then(({data:{id:i,bucketId:d}})=>{t({type:"UPLOAD_DONE",id:i,bucketId:d})}).catch(({response:i,message:d})=>{var p,P,U,D;t({type:"UPLOAD_ERROR",error:{status:(i==null?void 0:i.status)??0,message:((P=(p=i==null?void 0:i.data)==null?void 0:p.error)==null?void 0:P.message)||d,error:((D=(U=i==null?void 0:i.data)==null?void 0:U.error)==null?void 0:D.message)||d}})}),()=>{A.abort()}}}}),{pure:f,sendParent:g}=o.actions,_=()=>o.createMachine({id:"files-list",schema:{context:{},events:{}},tsTypes:{},predictableActionArguments:!0,context:{progress:null,files:[],loaded:0,total:0},initial:"idle",on:{UPLOAD:{cond:"hasFileToDownload",actions:"addItem",target:"uploading"},ADD:{actions:"addItem"},REMOVE:{actions:"removeItem"}},states:{idle:{entry:["resetProgress","resetLoaded","resetTotal"],on:{CLEAR:{actions:"clearList",target:"idle"}}},uploading:{entry:["upload","startProgress","resetLoaded","resetTotal"],on:{UPLOAD_PROGRESS:{actions:["incrementProgress"]},UPLOAD_DONE:[{cond:"isAllUploaded",target:"uploaded"},{cond:"isAllUploadedOrError",target:"error"}],UPLOAD_ERROR:[{cond:"isAllUploaded",target:"uploaded"},{cond:"isAllUploadedOrError",target:"error"}],CANCEL:{actions:"cancel",target:"idle"}}},uploaded:{entry:"setUploaded",on:{CLEAR:{actions:"clearList",target:"idle"}}},error:{on:{CLEAR:{actions:"clearList",target:"idle"}}}}},{guards:{hasFileToDownload:(r,e)=>r.files.some(t=>t.getSnapshot().matches("idle"))||!!e.files,isAllUploaded:r=>r.files.every(e=>{var t;return(t=e.getSnapshot())==null?void 0:t.matches("uploaded")}),isAllUploadedOrError:r=>r.files.every(e=>{const t=e.getSnapshot();return(t==null?void 0:t.matches("error"))||(t==null?void 0:t.matches("uploaded"))})},actions:{incrementProgress:o.assign((r,e)=>{const t=r.loaded+e.additions,s=Math.round(t*100/r.total);return{...r,loaded:t,progress:s}}),setUploaded:o.assign({progress:r=>100,loaded:({files:r})=>r.map(e=>e.getSnapshot()).filter(e=>e.matches("uploaded")).reduce((e,t)=>{var s;return e+((s=t.context.file)==null?void 0:s.size)},0)}),resetTotal:o.assign({total:({files:r})=>r.map(e=>e.getSnapshot()).filter(e=>!e.matches("uploaded")).reduce((e,t)=>{var s;return e+((s=t.context.file)==null?void 0:s.size)},0)}),resetLoaded:o.assign({loaded:r=>0}),startProgress:o.assign({progress:r=>0}),resetProgress:o.assign({progress:r=>null}),addItem:o.assign((r,{files:e,bucketId:t})=>{const s=e?Array.isArray(e)?e:"length"in e?Array.from(e):[e]:[],a=r.total+s.reduce((l,c)=>l+c.size,0),n=Math.round(r.loaded*100/a);return{files:[...r.files,...s.map(l=>o.spawn(L().withConfig({actions:{sendProgress:g((c,{additions:u})=>({type:"UPLOAD_PROGRESS",additions:u})),sendDone:g("UPLOAD_DONE"),sendError:g("UPLOAD_ERROR"),sendDestroy:g("REMOVE")}}).withContext({...h,file:l,bucketId:t}),{sync:!0}))],total:a,loaded:r.loaded,progress:n}}),removeItem:o.assign({files:r=>r.files.filter(e=>{var s,a;const t=(s=e.getSnapshot())==null?void 0:s.matches("stopped");return t&&((a=e.stop)==null||a.call(e)),!t})}),clearList:f(r=>r.files.map(e=>o.send({type:"DESTROY"},{to:e.id}))),upload:f((r,e)=>r.files.map(t=>o.send(e,{to:t.id}))),cancel:f(r=>r.files.map(e=>o.send({type:"CANCEL"},{to:e.id})))}}),T=async(r,e)=>new Promise(t=>{e.send({type:"UPLOAD",...r}),e.subscribe(s=>{var a;s.matches("error")?t({error:s.context.error,isError:!0,isUploaded:!1}):s.matches("uploaded")&&t({error:null,isError:!1,isUploaded:!0,id:s.context.id,bucketId:s.context.id,name:(a=s.context.file)==null?void 0:a.name})})}),R=async(r,e)=>new Promise(t=>{e.send({type:"UPLOAD",...r,files:r.files}),e.onTransition(s=>{s.matches("error")?t({errors:s.context.files.filter(a=>{var n;return(n=a.getSnapshot())==null?void 0:n.context.error}),isError:!0,files:[]}):s.matches("uploaded")&&t({errors:[],isError:!1,files:s.context.files})})});exports.HasuraStorageApi=O;exports.HasuraStorageClient=S;exports.INITIAL_FILE_CONTEXT=h;exports.appendImageTransformationParameters=E;exports.createFileUploadMachine=L;exports.createMultipleFilesUploadMachine=_;exports.toIso88591=m;exports.uploadFilePromise=T;exports.uploadMultipleFilesPromise=R; | ||
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const C=require("form-data"),h=require("xstate");var K=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Q(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var x={exports:{}};(function(s,t){var o=typeof self<"u"?self:K,n=function(){function c(){this.fetch=!1,this.DOMException=o.DOMException}return c.prototype=o,new c}();(function(c){(function(a){var l={searchParams:"URLSearchParams"in c,iterable:"Symbol"in c&&"iterator"in Symbol,blob:"FileReader"in c&&"Blob"in c&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in c,arrayBuffer:"ArrayBuffer"in c};function g(e){return e&&DataView.prototype.isPrototypeOf(e)}if(l.arrayBuffer)var w=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],b=ArrayBuffer.isView||function(e){return e&&w.indexOf(Object.prototype.toString.call(e))>-1};function f(e){if(typeof e!="string"&&(e=String(e)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(e))throw new TypeError("Invalid character in header field name");return e.toLowerCase()}function O(e){return typeof e!="string"&&(e=String(e)),e}function P(e){var r={next:function(){var i=e.shift();return{done:i===void 0,value:i}}};return l.iterable&&(r[Symbol.iterator]=function(){return r}),r}function p(e){this.map={},e instanceof p?e.forEach(function(r,i){this.append(i,r)},this):Array.isArray(e)?e.forEach(function(r){this.append(r[0],r[1])},this):e&&Object.getOwnPropertyNames(e).forEach(function(r){this.append(r,e[r])},this)}p.prototype.append=function(e,r){e=f(e),r=O(r);var i=this.map[e];this.map[e]=i?i+", "+r:r},p.prototype.delete=function(e){delete this.map[f(e)]},p.prototype.get=function(e){return e=f(e),this.has(e)?this.map[e]:null},p.prototype.has=function(e){return this.map.hasOwnProperty(f(e))},p.prototype.set=function(e,r){this.map[f(e)]=O(r)},p.prototype.forEach=function(e,r){for(var i in this.map)this.map.hasOwnProperty(i)&&e.call(r,this.map[i],i,this)},p.prototype.keys=function(){var e=[];return this.forEach(function(r,i){e.push(i)}),P(e)},p.prototype.values=function(){var e=[];return this.forEach(function(r){e.push(r)}),P(e)},p.prototype.entries=function(){var e=[];return this.forEach(function(r,i){e.push([i,r])}),P(e)},l.iterable&&(p.prototype[Symbol.iterator]=p.prototype.entries);function R(e){if(e.bodyUsed)return Promise.reject(new TypeError("Already read"));e.bodyUsed=!0}function B(e){return new Promise(function(r,i){e.onload=function(){r(e.result)},e.onerror=function(){i(e.error)}})}function N(e){var r=new FileReader,i=B(r);return r.readAsArrayBuffer(e),i}function $(e){var r=new FileReader,i=B(r);return r.readAsText(e),i}function z(e){for(var r=new Uint8Array(e),i=new Array(r.length),m=0;m<r.length;m++)i[m]=String.fromCharCode(r[m]);return i.join("")}function M(e){if(e.slice)return e.slice(0);var r=new Uint8Array(e.byteLength);return r.set(new Uint8Array(e)),r.buffer}function F(){return this.bodyUsed=!1,this._initBody=function(e){this._bodyInit=e,e?typeof e=="string"?this._bodyText=e:l.blob&&Blob.prototype.isPrototypeOf(e)?this._bodyBlob=e:l.formData&&FormData.prototype.isPrototypeOf(e)?this._bodyFormData=e:l.searchParams&&URLSearchParams.prototype.isPrototypeOf(e)?this._bodyText=e.toString():l.arrayBuffer&&l.blob&&g(e)?(this._bodyArrayBuffer=M(e.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):l.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(e)||b(e))?this._bodyArrayBuffer=M(e):this._bodyText=e=Object.prototype.toString.call(e):this._bodyText="",this.headers.get("content-type")||(typeof e=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):l.searchParams&&URLSearchParams.prototype.isPrototypeOf(e)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},l.blob&&(this.blob=function(){var e=R(this);if(e)return e;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?R(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(N)}),this.text=function(){var e=R(this);if(e)return e;if(this._bodyBlob)return $(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(z(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},l.formData&&(this.formData=function(){return this.text().then(X)}),this.json=function(){return this.text().then(JSON.parse)},this}var G=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function V(e){var r=e.toUpperCase();return G.indexOf(r)>-1?r:e}function E(e,r){r=r||{};var i=r.body;if(e instanceof E){if(e.bodyUsed)throw new TypeError("Already read");this.url=e.url,this.credentials=e.credentials,r.headers||(this.headers=new p(e.headers)),this.method=e.method,this.mode=e.mode,this.signal=e.signal,!i&&e._bodyInit!=null&&(i=e._bodyInit,e.bodyUsed=!0)}else this.url=String(e);if(this.credentials=r.credentials||this.credentials||"same-origin",(r.headers||!this.headers)&&(this.headers=new p(r.headers)),this.method=V(r.method||this.method||"GET"),this.mode=r.mode||this.mode||null,this.signal=r.signal||this.signal,this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&i)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(i)}E.prototype.clone=function(){return new E(this,{body:this._bodyInit})};function X(e){var r=new FormData;return e.trim().split("&").forEach(function(i){if(i){var m=i.split("="),y=m.shift().replace(/\+/g," "),d=m.join("=").replace(/\+/g," ");r.append(decodeURIComponent(y),decodeURIComponent(d))}}),r}function Y(e){var r=new p,i=e.replace(/\r?\n[\t ]+/g," ");return i.split(/\r?\n/).forEach(function(m){var y=m.split(":"),d=y.shift().trim();if(d){var T=y.join(":").trim();r.append(d,T)}}),r}F.call(E.prototype);function A(e,r){r||(r={}),this.type="default",this.status=r.status===void 0?200:r.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in r?r.statusText:"OK",this.headers=new p(r.headers),this.url=r.url||"",this._initBody(e)}F.call(A.prototype),A.prototype.clone=function(){return new A(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new p(this.headers),url:this.url})},A.error=function(){var e=new A(null,{status:0,statusText:""});return e.type="error",e};var J=[301,302,303,307,308];A.redirect=function(e,r){if(J.indexOf(r)===-1)throw new RangeError("Invalid status code");return new A(null,{status:r,headers:{location:e}})},a.DOMException=c.DOMException;try{new a.DOMException}catch{a.DOMException=function(r,i){this.message=r,this.name=i;var m=Error(r);this.stack=m.stack},a.DOMException.prototype=Object.create(Error.prototype),a.DOMException.prototype.constructor=a.DOMException}function v(e,r){return new Promise(function(i,m){var y=new E(e,r);if(y.signal&&y.signal.aborted)return m(new a.DOMException("Aborted","AbortError"));var d=new XMLHttpRequest;function T(){d.abort()}d.onload=function(){var _={status:d.status,statusText:d.statusText,headers:Y(d.getAllResponseHeaders()||"")};_.url="responseURL"in d?d.responseURL:_.headers.get("X-Request-URL");var S="response"in d?d.response:d.responseText;i(new A(S,_))},d.onerror=function(){m(new TypeError("Network request failed"))},d.ontimeout=function(){m(new TypeError("Network request failed"))},d.onabort=function(){m(new a.DOMException("Aborted","AbortError"))},d.open(y.method,y.url,!0),y.credentials==="include"?d.withCredentials=!0:y.credentials==="omit"&&(d.withCredentials=!1),"responseType"in d&&l.blob&&(d.responseType="blob"),y.headers.forEach(function(_,S){d.setRequestHeader(S,_)}),y.signal&&(y.signal.addEventListener("abort",T),d.onreadystatechange=function(){d.readyState===4&&y.signal.removeEventListener("abort",T)}),d.send(typeof y._bodyInit>"u"?null:y._bodyInit)})}return v.polyfill=!0,c.fetch||(c.fetch=v,c.Headers=p,c.Request=E,c.Response=A),a.Headers=p,a.Request=E,a.Response=A,a.fetch=v,Object.defineProperty(a,"__esModule",{value:!0}),a})({})})(n),n.fetch.ponyfill=!0,delete n.fetch.polyfill;var u=n;t=u.fetch,t.default=u.fetch,t.fetch=u.fetch,t.Headers=u.Headers,t.Request=u.Request,t.Response=u.Response,s.exports=t})(x,x.exports);const I=Q(x.exports),W=s=>{try{return btoa(s),s}catch{return encodeURIComponent(s)}},k=async(s,t,{accessToken:o,name:n,fileId:u,bucketId:c,adminSecret:a,onUploadProgress:l}={})=>{const g={};u&&(g["x-nhost-file-id"]=u),c&&(g["x-nhost-bucket-id"]=c),n&&(g["x-nhost-file-name"]=W(n)),a&&(g["x-hasura-admin-secret"]=a),o&&(g.Authorization=`Bearer ${o}`);const w=`${s}/files`;if(typeof XMLHttpRequest>"u")try{const b=await I(w,{method:"POST",headers:g,body:t});return b.ok?{fileMetadata:await b.json(),error:null}:{error:{status:b.status,message:await b.text(),error:b.statusText},fileMetadata:null}}catch(b){return{error:{status:0,message:b.message,error:b.message},fileMetadata:null}}return new Promise(b=>{console.log("NOOOOOOO");let f=new XMLHttpRequest;f.responseType="json",f.onload=()=>f.status<200&&f.status>=300?b({fileMetadata:null,error:{error:f.statusText,message:f.statusText,status:f.status}}):b({fileMetadata:f.response,error:null}),f.onerror=()=>b({fileMetadata:null,error:{error:f.statusText,message:f.statusText,status:f.status}}),l&&f.upload.addEventListener("progress",l,!1),f.open("POST",w,!0),Object.entries(g).forEach(([O,P])=>{f.setRequestHeader(O,P)}),f.send(t)})};class j{constructor({url:t}){this.url=t}async upload(t){const{formData:o}=t;return k(this.url,o,{accessToken:this.accessToken,adminSecret:this.accessToken,bucketId:t.bucketId,fileId:t.id,name:t.name})}async getPresignedUrl(t){try{const{fileId:o}=t,n=await I(`${this.url}/files/${o}/presignedurl`,{method:"GET",headers:this.generateAuthHeaders()});if(!n.ok)throw new Error(await n.text());return{presignedUrl:await n.json(),error:null}}catch(o){return{presignedUrl:null,error:o}}}async delete(t){try{const{fileId:o}=t,n=await I(`${this.url}/files/${o}`,{method:"DELETE",headers:this.generateAuthHeaders()});if(!n.ok)throw new Error(await n.text());return{error:null}}catch(o){return{error:o}}}setAccessToken(t){return this.accessToken=t,this}setAdminSecret(t){return this.adminSecret=t,this}generateAuthHeaders(){if(!(!this.adminSecret&&!this.accessToken))return this.adminSecret?{"x-hasura-admin-secret":this.adminSecret}:{Authorization:`Bearer ${this.accessToken}`}}}const H=(s,t)=>{const o=Object.entries(t).map(([n,u])=>`${Array.from(n)[0]}=${u}`).join("&");return o?`${s}?${o}`:s};class Z{constructor({url:t,adminSecret:o}){this.url=t,this.api=new j({url:t}),this.setAdminSecret(o)}async upload(t){let o;return"file"in t?(o=new C,o.append("file",t.file)):o=t.formData,this.api.upload({...t,formData:o})}getPublicUrl(t){const{fileId:o,...n}=t;return H(`${this.url}/files/${o}`,n)}async getPresignedUrl(t){const{presignedUrl:o,error:n}=await this.api.getPresignedUrl(t);return n?{presignedUrl:null,error:n}:o?{presignedUrl:o,error:null}:{presignedUrl:null,error:new Error("Invalid file id")}}async delete(t){const{error:o}=await this.api.delete(t);return o?{error:o}:{error:null}}setAccessToken(t){return this.api.setAccessToken(t),this}setAdminSecret(t){return this.api.setAdminSecret(t),this}}const U={progress:null,loaded:0,error:null,bucketId:void 0,file:void 0,id:void 0},q=()=>h.createMachine({predictableActionArguments:!0,schema:{context:{},events:{}},tsTypes:{},context:{...U},initial:"idle",on:{DESTROY:{actions:"sendDestroy",target:"stopped"}},states:{idle:{on:{ADD:{actions:"addFile"},UPLOAD:{cond:"hasFile",target:"uploading"}}},uploading:{entry:"resetProgress",on:{UPLOAD_PROGRESS:{actions:["incrementProgress","sendProgress"]},UPLOAD_DONE:"uploaded",UPLOAD_ERROR:"error",CANCEL:"idle"},invoke:{src:"uploadFile"}},uploaded:{entry:["setFileMetadata","sendDone"],on:{ADD:{actions:"addFile",target:"idle"},UPLOAD:{actions:"resetContext",target:"uploading"}}},error:{entry:["setError","sendError"],on:{ADD:{actions:"addFile",target:"idle"},UPLOAD:{actions:"resetContext",target:"uploading"}}},stopped:{type:"final"}}},{guards:{hasFile:(s,t)=>!!s.file||!!t.file},actions:{incrementProgress:h.assign({loaded:(s,{loaded:t})=>t,progress:(s,{progress:t})=>t}),setFileMetadata:h.assign({id:(s,{id:t})=>t,bucketId:(s,{bucketId:t})=>t,progress:s=>100}),setError:h.assign({error:(s,{error:t})=>t}),sendProgress:()=>{},sendError:()=>{},sendDestroy:()=>{},sendDone:()=>{},resetProgress:h.assign({progress:s=>null,loaded:s=>0}),resetContext:h.assign(s=>U),addFile:h.assign({file:(s,{file:t})=>t,bucketId:(s,{bucketId:t})=>t,id:(s,{id:t})=>t})},services:{uploadFile:(s,t)=>o=>{const n=t.file||s.file,u=new C;u.append("file",n);let c=0;return k(t.url,u,{fileId:t.id||s.id,bucketId:t.bucketId||s.bucketId,accessToken:t.accessToken,adminSecret:t.adminSecret,name:t.name||n.name,onUploadProgress:a=>{const l=a.total?Math.round(a.loaded*n.size/a.total):0,g=l-c;c=l,o({type:"UPLOAD_PROGRESS",progress:a.total?Math.round(l*100/a.total):0,loaded:l,additions:g})}}).then(({fileMetadata:a,error:l})=>{if(l&&o({type:"UPLOAD_ERROR",error:l}),a){const{id:g,bucketId:w}=a;o({type:"UPLOAD_DONE",id:g,bucketId:w})}}),()=>{}}}}),{pure:L,sendParent:D}=h.actions,ee=()=>h.createMachine({id:"files-list",schema:{context:{},events:{}},tsTypes:{},predictableActionArguments:!0,context:{progress:null,files:[],loaded:0,total:0},initial:"idle",on:{UPLOAD:{cond:"hasFileToDownload",actions:"addItem",target:"uploading"},ADD:{actions:"addItem"},REMOVE:{actions:"removeItem"}},states:{idle:{entry:["resetProgress","resetLoaded","resetTotal"],on:{CLEAR:{actions:"clearList",target:"idle"}}},uploading:{entry:["upload","startProgress","resetLoaded","resetTotal"],on:{UPLOAD_PROGRESS:{actions:["incrementProgress"]},UPLOAD_DONE:[{cond:"isAllUploaded",target:"uploaded"},{cond:"isAllUploadedOrError",target:"error"}],UPLOAD_ERROR:[{cond:"isAllUploaded",target:"uploaded"},{cond:"isAllUploadedOrError",target:"error"}],CANCEL:{actions:"cancel",target:"idle"}}},uploaded:{entry:"setUploaded",on:{CLEAR:{actions:"clearList",target:"idle"}}},error:{on:{CLEAR:{actions:"clearList",target:"idle"}}}}},{guards:{hasFileToDownload:(s,t)=>s.files.some(o=>o.getSnapshot().matches("idle"))||!!t.files,isAllUploaded:s=>s.files.every(t=>{var o;return(o=t.getSnapshot())==null?void 0:o.matches("uploaded")}),isAllUploadedOrError:s=>s.files.every(t=>{const o=t.getSnapshot();return(o==null?void 0:o.matches("error"))||(o==null?void 0:o.matches("uploaded"))})},actions:{incrementProgress:h.assign((s,t)=>{const o=s.loaded+t.additions,n=Math.round(o*100/s.total);return{...s,loaded:o,progress:n}}),setUploaded:h.assign({progress:s=>100,loaded:({files:s})=>s.map(t=>t.getSnapshot()).filter(t=>t.matches("uploaded")).reduce((t,o)=>{var n;return t+((n=o.context.file)==null?void 0:n.size)},0)}),resetTotal:h.assign({total:({files:s})=>s.map(t=>t.getSnapshot()).filter(t=>!t.matches("uploaded")).reduce((t,o)=>{var n;return t+((n=o.context.file)==null?void 0:n.size)},0)}),resetLoaded:h.assign({loaded:s=>0}),startProgress:h.assign({progress:s=>0}),resetProgress:h.assign({progress:s=>null}),addItem:h.assign((s,{files:t,bucketId:o})=>{const n=t?Array.isArray(t)?t:"length"in t?Array.from(t):[t]:[],u=s.total+n.reduce((a,l)=>a+l.size,0),c=Math.round(s.loaded*100/u);return{files:[...s.files,...n.map(a=>h.spawn(q().withConfig({actions:{sendProgress:D((l,{additions:g})=>({type:"UPLOAD_PROGRESS",additions:g})),sendDone:D("UPLOAD_DONE"),sendError:D("UPLOAD_ERROR"),sendDestroy:D("REMOVE")}}).withContext({...U,file:a,bucketId:o}),{sync:!0}))],total:u,loaded:s.loaded,progress:c}}),removeItem:h.assign({files:s=>s.files.filter(t=>{var n,u;const o=(n=t.getSnapshot())==null?void 0:n.matches("stopped");return o&&((u=t.stop)==null||u.call(t)),!o})}),clearList:L(s=>s.files.map(t=>h.send({type:"DESTROY"},{to:t.id}))),upload:L((s,t)=>s.files.map(o=>h.send(t,{to:o.id}))),cancel:L(s=>s.files.map(t=>h.send({type:"CANCEL"},{to:t.id})))}}),te=async(s,t)=>new Promise(o=>{t.send({type:"UPLOAD",...s}),t.subscribe(n=>{var u;n.matches("error")?o({error:n.context.error,isError:!0,isUploaded:!1}):n.matches("uploaded")&&o({error:null,isError:!1,isUploaded:!0,id:n.context.id,bucketId:n.context.id,name:(u=n.context.file)==null?void 0:u.name})})}),re=async(s,t)=>new Promise(o=>{t.send({type:"UPLOAD",...s,files:s.files}),t.onTransition(n=>{n.matches("error")?o({errors:n.context.files.filter(u=>{var c;return(c=u.getSnapshot())==null?void 0:c.context.error}),isError:!0,files:[]}):n.matches("uploaded")&&o({errors:[],isError:!1,files:n.context.files})})});exports.HasuraStorageApi=j;exports.HasuraStorageClient=Z;exports.INITIAL_FILE_CONTEXT=U;exports.appendImageTransformationParameters=H;exports.createFileUploadMachine=q;exports.createMultipleFilesUploadMachine=ee;exports.uploadFilePromise=te;exports.uploadMultipleFilesPromise=re; | ||
//# sourceMappingURL=index.cjs.js.map |
@@ -1,115 +0,422 @@ | ||
import y from "axios"; | ||
import L from "form-data"; | ||
import { createMachine as E, assign as i, spawn as _, send as g, actions as R } from "xstate"; | ||
const S = (r, e) => { | ||
const t = Object.entries(e).map(([s, a]) => `${Array.from(s)[0]}=${a}`).join("&"); | ||
return t ? `${r}?${t}` : r; | ||
}, O = (r) => { | ||
import C from "form-data"; | ||
import { createMachine as j, assign as b, spawn as J, send as L, actions as K } from "xstate"; | ||
var Q = typeof globalThis < "u" ? globalThis : typeof window < "u" ? window : typeof global < "u" ? global : typeof self < "u" ? self : {}; | ||
function W(s) { | ||
return s && s.__esModule && Object.prototype.hasOwnProperty.call(s, "default") ? s.default : s; | ||
} | ||
var x = { exports: {} }; | ||
(function(s, t) { | ||
var o = typeof self < "u" ? self : Q, n = function() { | ||
function c() { | ||
this.fetch = !1, this.DOMException = o.DOMException; | ||
} | ||
return c.prototype = o, new c(); | ||
}(); | ||
(function(c) { | ||
(function(a) { | ||
var d = { | ||
searchParams: "URLSearchParams" in c, | ||
iterable: "Symbol" in c && "iterator" in Symbol, | ||
blob: "FileReader" in c && "Blob" in c && function() { | ||
try { | ||
return new Blob(), !0; | ||
} catch { | ||
return !1; | ||
} | ||
}(), | ||
formData: "FormData" in c, | ||
arrayBuffer: "ArrayBuffer" in c | ||
}; | ||
function m(e) { | ||
return e && DataView.prototype.isPrototypeOf(e); | ||
} | ||
if (d.arrayBuffer) | ||
var w = [ | ||
"[object Int8Array]", | ||
"[object Uint8Array]", | ||
"[object Uint8ClampedArray]", | ||
"[object Int16Array]", | ||
"[object Uint16Array]", | ||
"[object Int32Array]", | ||
"[object Uint32Array]", | ||
"[object Float32Array]", | ||
"[object Float64Array]" | ||
], g = ArrayBuffer.isView || function(e) { | ||
return e && w.indexOf(Object.prototype.toString.call(e)) > -1; | ||
}; | ||
function f(e) { | ||
if (typeof e != "string" && (e = String(e)), /[^a-z0-9\-#$%&'*+.^_`|~]/i.test(e)) | ||
throw new TypeError("Invalid character in header field name"); | ||
return e.toLowerCase(); | ||
} | ||
function O(e) { | ||
return typeof e != "string" && (e = String(e)), e; | ||
} | ||
function P(e) { | ||
var r = { | ||
next: function() { | ||
var i = e.shift(); | ||
return { done: i === void 0, value: i }; | ||
} | ||
}; | ||
return d.iterable && (r[Symbol.iterator] = function() { | ||
return r; | ||
}), r; | ||
} | ||
function h(e) { | ||
this.map = {}, e instanceof h ? e.forEach(function(r, i) { | ||
this.append(i, r); | ||
}, this) : Array.isArray(e) ? e.forEach(function(r) { | ||
this.append(r[0], r[1]); | ||
}, this) : e && Object.getOwnPropertyNames(e).forEach(function(r) { | ||
this.append(r, e[r]); | ||
}, this); | ||
} | ||
h.prototype.append = function(e, r) { | ||
e = f(e), r = O(r); | ||
var i = this.map[e]; | ||
this.map[e] = i ? i + ", " + r : r; | ||
}, h.prototype.delete = function(e) { | ||
delete this.map[f(e)]; | ||
}, h.prototype.get = function(e) { | ||
return e = f(e), this.has(e) ? this.map[e] : null; | ||
}, h.prototype.has = function(e) { | ||
return this.map.hasOwnProperty(f(e)); | ||
}, h.prototype.set = function(e, r) { | ||
this.map[f(e)] = O(r); | ||
}, h.prototype.forEach = function(e, r) { | ||
for (var i in this.map) | ||
this.map.hasOwnProperty(i) && e.call(r, this.map[i], i, this); | ||
}, h.prototype.keys = function() { | ||
var e = []; | ||
return this.forEach(function(r, i) { | ||
e.push(i); | ||
}), P(e); | ||
}, h.prototype.values = function() { | ||
var e = []; | ||
return this.forEach(function(r) { | ||
e.push(r); | ||
}), P(e); | ||
}, h.prototype.entries = function() { | ||
var e = []; | ||
return this.forEach(function(r, i) { | ||
e.push([i, r]); | ||
}), P(e); | ||
}, d.iterable && (h.prototype[Symbol.iterator] = h.prototype.entries); | ||
function U(e) { | ||
if (e.bodyUsed) | ||
return Promise.reject(new TypeError("Already read")); | ||
e.bodyUsed = !0; | ||
} | ||
function F(e) { | ||
return new Promise(function(r, i) { | ||
e.onload = function() { | ||
r(e.result); | ||
}, e.onerror = function() { | ||
i(e.error); | ||
}; | ||
}); | ||
} | ||
function q(e) { | ||
var r = new FileReader(), i = F(r); | ||
return r.readAsArrayBuffer(e), i; | ||
} | ||
function $(e) { | ||
var r = new FileReader(), i = F(r); | ||
return r.readAsText(e), i; | ||
} | ||
function N(e) { | ||
for (var r = new Uint8Array(e), i = new Array(r.length), y = 0; y < r.length; y++) | ||
i[y] = String.fromCharCode(r[y]); | ||
return i.join(""); | ||
} | ||
function M(e) { | ||
if (e.slice) | ||
return e.slice(0); | ||
var r = new Uint8Array(e.byteLength); | ||
return r.set(new Uint8Array(e)), r.buffer; | ||
} | ||
function k() { | ||
return this.bodyUsed = !1, this._initBody = function(e) { | ||
this._bodyInit = e, e ? typeof e == "string" ? this._bodyText = e : d.blob && Blob.prototype.isPrototypeOf(e) ? this._bodyBlob = e : d.formData && FormData.prototype.isPrototypeOf(e) ? this._bodyFormData = e : d.searchParams && URLSearchParams.prototype.isPrototypeOf(e) ? this._bodyText = e.toString() : d.arrayBuffer && d.blob && m(e) ? (this._bodyArrayBuffer = M(e.buffer), this._bodyInit = new Blob([this._bodyArrayBuffer])) : d.arrayBuffer && (ArrayBuffer.prototype.isPrototypeOf(e) || g(e)) ? this._bodyArrayBuffer = M(e) : this._bodyText = e = Object.prototype.toString.call(e) : this._bodyText = "", this.headers.get("content-type") || (typeof e == "string" ? this.headers.set("content-type", "text/plain;charset=UTF-8") : this._bodyBlob && this._bodyBlob.type ? this.headers.set("content-type", this._bodyBlob.type) : d.searchParams && URLSearchParams.prototype.isPrototypeOf(e) && this.headers.set("content-type", "application/x-www-form-urlencoded;charset=UTF-8")); | ||
}, d.blob && (this.blob = function() { | ||
var e = U(this); | ||
if (e) | ||
return e; | ||
if (this._bodyBlob) | ||
return Promise.resolve(this._bodyBlob); | ||
if (this._bodyArrayBuffer) | ||
return Promise.resolve(new Blob([this._bodyArrayBuffer])); | ||
if (this._bodyFormData) | ||
throw new Error("could not read FormData body as blob"); | ||
return Promise.resolve(new Blob([this._bodyText])); | ||
}, this.arrayBuffer = function() { | ||
return this._bodyArrayBuffer ? U(this) || Promise.resolve(this._bodyArrayBuffer) : this.blob().then(q); | ||
}), this.text = function() { | ||
var e = U(this); | ||
if (e) | ||
return e; | ||
if (this._bodyBlob) | ||
return $(this._bodyBlob); | ||
if (this._bodyArrayBuffer) | ||
return Promise.resolve(N(this._bodyArrayBuffer)); | ||
if (this._bodyFormData) | ||
throw new Error("could not read FormData body as text"); | ||
return Promise.resolve(this._bodyText); | ||
}, d.formData && (this.formData = function() { | ||
return this.text().then(V); | ||
}), this.json = function() { | ||
return this.text().then(JSON.parse); | ||
}, this; | ||
} | ||
var z = ["DELETE", "GET", "HEAD", "OPTIONS", "POST", "PUT"]; | ||
function G(e) { | ||
var r = e.toUpperCase(); | ||
return z.indexOf(r) > -1 ? r : e; | ||
} | ||
function E(e, r) { | ||
r = r || {}; | ||
var i = r.body; | ||
if (e instanceof E) { | ||
if (e.bodyUsed) | ||
throw new TypeError("Already read"); | ||
this.url = e.url, this.credentials = e.credentials, r.headers || (this.headers = new h(e.headers)), this.method = e.method, this.mode = e.mode, this.signal = e.signal, !i && e._bodyInit != null && (i = e._bodyInit, e.bodyUsed = !0); | ||
} else | ||
this.url = String(e); | ||
if (this.credentials = r.credentials || this.credentials || "same-origin", (r.headers || !this.headers) && (this.headers = new h(r.headers)), this.method = G(r.method || this.method || "GET"), this.mode = r.mode || this.mode || null, this.signal = r.signal || this.signal, this.referrer = null, (this.method === "GET" || this.method === "HEAD") && i) | ||
throw new TypeError("Body not allowed for GET or HEAD requests"); | ||
this._initBody(i); | ||
} | ||
E.prototype.clone = function() { | ||
return new E(this, { body: this._bodyInit }); | ||
}; | ||
function V(e) { | ||
var r = new FormData(); | ||
return e.trim().split("&").forEach(function(i) { | ||
if (i) { | ||
var y = i.split("="), p = y.shift().replace(/\+/g, " "), l = y.join("=").replace(/\+/g, " "); | ||
r.append(decodeURIComponent(p), decodeURIComponent(l)); | ||
} | ||
}), r; | ||
} | ||
function X(e) { | ||
var r = new h(), i = e.replace(/\r?\n[\t ]+/g, " "); | ||
return i.split(/\r?\n/).forEach(function(y) { | ||
var p = y.split(":"), l = p.shift().trim(); | ||
if (l) { | ||
var D = p.join(":").trim(); | ||
r.append(l, D); | ||
} | ||
}), r; | ||
} | ||
k.call(E.prototype); | ||
function A(e, r) { | ||
r || (r = {}), this.type = "default", this.status = r.status === void 0 ? 200 : r.status, this.ok = this.status >= 200 && this.status < 300, this.statusText = "statusText" in r ? r.statusText : "OK", this.headers = new h(r.headers), this.url = r.url || "", this._initBody(e); | ||
} | ||
k.call(A.prototype), A.prototype.clone = function() { | ||
return new A(this._bodyInit, { | ||
status: this.status, | ||
statusText: this.statusText, | ||
headers: new h(this.headers), | ||
url: this.url | ||
}); | ||
}, A.error = function() { | ||
var e = new A(null, { status: 0, statusText: "" }); | ||
return e.type = "error", e; | ||
}; | ||
var Y = [301, 302, 303, 307, 308]; | ||
A.redirect = function(e, r) { | ||
if (Y.indexOf(r) === -1) | ||
throw new RangeError("Invalid status code"); | ||
return new A(null, { status: r, headers: { location: e } }); | ||
}, a.DOMException = c.DOMException; | ||
try { | ||
new a.DOMException(); | ||
} catch { | ||
a.DOMException = function(r, i) { | ||
this.message = r, this.name = i; | ||
var y = Error(r); | ||
this.stack = y.stack; | ||
}, a.DOMException.prototype = Object.create(Error.prototype), a.DOMException.prototype.constructor = a.DOMException; | ||
} | ||
function R(e, r) { | ||
return new Promise(function(i, y) { | ||
var p = new E(e, r); | ||
if (p.signal && p.signal.aborted) | ||
return y(new a.DOMException("Aborted", "AbortError")); | ||
var l = new XMLHttpRequest(); | ||
function D() { | ||
l.abort(); | ||
} | ||
l.onload = function() { | ||
var _ = { | ||
status: l.status, | ||
statusText: l.statusText, | ||
headers: X(l.getAllResponseHeaders() || "") | ||
}; | ||
_.url = "responseURL" in l ? l.responseURL : _.headers.get("X-Request-URL"); | ||
var v = "response" in l ? l.response : l.responseText; | ||
i(new A(v, _)); | ||
}, l.onerror = function() { | ||
y(new TypeError("Network request failed")); | ||
}, l.ontimeout = function() { | ||
y(new TypeError("Network request failed")); | ||
}, l.onabort = function() { | ||
y(new a.DOMException("Aborted", "AbortError")); | ||
}, l.open(p.method, p.url, !0), p.credentials === "include" ? l.withCredentials = !0 : p.credentials === "omit" && (l.withCredentials = !1), "responseType" in l && d.blob && (l.responseType = "blob"), p.headers.forEach(function(_, v) { | ||
l.setRequestHeader(v, _); | ||
}), p.signal && (p.signal.addEventListener("abort", D), l.onreadystatechange = function() { | ||
l.readyState === 4 && p.signal.removeEventListener("abort", D); | ||
}), l.send(typeof p._bodyInit > "u" ? null : p._bodyInit); | ||
}); | ||
} | ||
return R.polyfill = !0, c.fetch || (c.fetch = R, c.Headers = h, c.Request = E, c.Response = A), a.Headers = h, a.Request = E, a.Response = A, a.fetch = R, Object.defineProperty(a, "__esModule", { value: !0 }), a; | ||
})({}); | ||
})(n), n.fetch.ponyfill = !0, delete n.fetch.polyfill; | ||
var u = n; | ||
t = u.fetch, t.default = u.fetch, t.fetch = u.fetch, t.Headers = u.Headers, t.Request = u.Request, t.Response = u.Response, s.exports = t; | ||
})(x, x.exports); | ||
const B = /* @__PURE__ */ W(x.exports), Z = (s) => { | ||
try { | ||
return btoa(r), r; | ||
return btoa(s), s; | ||
} catch { | ||
return encodeURIComponent(r); | ||
return encodeURIComponent(s); | ||
} | ||
}, H = async (s, t, { | ||
accessToken: o, | ||
name: n, | ||
fileId: u, | ||
bucketId: c, | ||
adminSecret: a, | ||
onUploadProgress: d | ||
} = {}) => { | ||
const m = {}; | ||
u && (m["x-nhost-file-id"] = u), c && (m["x-nhost-bucket-id"] = c), n && (m["x-nhost-file-name"] = Z(n)), a && (m["x-hasura-admin-secret"] = a), o && (m.Authorization = `Bearer ${o}`); | ||
const w = `${s}/files`; | ||
if (typeof XMLHttpRequest > "u") | ||
try { | ||
const g = await B(w, { | ||
method: "POST", | ||
headers: m, | ||
body: t | ||
}); | ||
return g.ok ? { fileMetadata: await g.json(), error: null } : { error: { | ||
status: g.status, | ||
message: await g.text(), | ||
error: g.statusText | ||
}, fileMetadata: null }; | ||
} catch (g) { | ||
return { error: { | ||
status: 0, | ||
message: g.message, | ||
error: g.message | ||
}, fileMetadata: null }; | ||
} | ||
return new Promise((g) => { | ||
console.log("NOOOOOOO"); | ||
let f = new XMLHttpRequest(); | ||
f.responseType = "json", f.onload = () => f.status < 200 && f.status >= 300 ? g({ | ||
fileMetadata: null, | ||
error: { error: f.statusText, message: f.statusText, status: f.status } | ||
}) : g({ fileMetadata: f.response, error: null }), f.onerror = () => g({ | ||
fileMetadata: null, | ||
error: { error: f.statusText, message: f.statusText, status: f.status } | ||
}), d && f.upload.addEventListener("progress", d, !1), f.open("POST", w, !0), Object.entries(m).forEach(([O, P]) => { | ||
f.setRequestHeader(O, P); | ||
}), f.send(t); | ||
}); | ||
}; | ||
class I { | ||
constructor({ url: e }) { | ||
this.url = e, this.httpClient = y.create({ | ||
baseURL: this.url | ||
class ee { | ||
constructor({ url: t }) { | ||
this.url = t; | ||
} | ||
async upload(t) { | ||
const { formData: o } = t; | ||
return H(this.url, o, { | ||
accessToken: this.accessToken, | ||
adminSecret: this.accessToken, | ||
bucketId: t.bucketId, | ||
fileId: t.id, | ||
name: t.name | ||
}); | ||
} | ||
async upload(e) { | ||
const { formData: t } = e; | ||
async getPresignedUrl(t) { | ||
try { | ||
return { fileMetadata: (await this.httpClient.post("/files", t, { | ||
headers: { | ||
...this.generateUploadHeaders(e), | ||
...this.generateAuthHeaders(), | ||
"Content-Type": "multipart/form-data" | ||
} | ||
})).data, error: null }; | ||
} catch (s) { | ||
return { fileMetadata: null, error: s }; | ||
const { fileId: o } = t, n = await B(`${this.url}/files/${o}/presignedurl`, { | ||
method: "GET", | ||
headers: this.generateAuthHeaders() | ||
}); | ||
if (!n.ok) | ||
throw new Error(await n.text()); | ||
return { presignedUrl: await n.json(), error: null }; | ||
} catch (o) { | ||
return { presignedUrl: null, error: o }; | ||
} | ||
} | ||
async getPresignedUrl(e) { | ||
async delete(t) { | ||
try { | ||
const { fileId: t } = e, s = `/files/${t}/presignedurl`; | ||
return { presignedUrl: (await this.httpClient.get(s, { | ||
headers: { | ||
...this.generateAuthHeaders() | ||
} | ||
})).data, error: null }; | ||
} catch (t) { | ||
return { presignedUrl: null, error: t }; | ||
const { fileId: o } = t, n = await B(`${this.url}/files/${o}`, { | ||
method: "DELETE", | ||
headers: this.generateAuthHeaders() | ||
}); | ||
if (!n.ok) | ||
throw new Error(await n.text()); | ||
return { error: null }; | ||
} catch (o) { | ||
return { error: o }; | ||
} | ||
} | ||
async delete(e) { | ||
try { | ||
const { fileId: t } = e; | ||
return await this.httpClient.delete(`/files/${t}`, { | ||
headers: { | ||
...this.generateAuthHeaders() | ||
} | ||
}), { error: null }; | ||
} catch (t) { | ||
return { error: t }; | ||
} | ||
setAccessToken(t) { | ||
return this.accessToken = t, this; | ||
} | ||
setAccessToken(e) { | ||
return this.accessToken = e, this; | ||
setAdminSecret(t) { | ||
return this.adminSecret = t, this; | ||
} | ||
setAdminSecret(e) { | ||
return this.adminSecret = e, this; | ||
} | ||
generateUploadHeaders(e) { | ||
const { bucketId: t, name: s, id: a } = e, n = {}; | ||
return t && (n["x-nhost-bucket-id"] = t), a && (n["x-nhost-file-id"] = a), s && (n["x-nhost-file-name"] = O(s)), n; | ||
} | ||
generateAuthHeaders() { | ||
return !this.adminSecret && !this.accessToken ? null : this.adminSecret ? { | ||
"x-hasura-admin-secret": this.adminSecret | ||
} : { | ||
Authorization: `Bearer ${this.accessToken}` | ||
}; | ||
if (!(!this.adminSecret && !this.accessToken)) | ||
return this.adminSecret ? { | ||
"x-hasura-admin-secret": this.adminSecret | ||
} : { | ||
Authorization: `Bearer ${this.accessToken}` | ||
}; | ||
} | ||
} | ||
class k { | ||
constructor({ url: e, adminSecret: t }) { | ||
this.url = e, this.api = new I({ url: e }), this.setAdminSecret(t); | ||
const te = (s, t) => { | ||
const o = Object.entries(t).map(([n, u]) => `${Array.from(n)[0]}=${u}`).join("&"); | ||
return o ? `${s}?${o}` : s; | ||
}; | ||
class ne { | ||
constructor({ url: t, adminSecret: o }) { | ||
this.url = t, this.api = new ee({ url: t }), this.setAdminSecret(o); | ||
} | ||
async upload(e) { | ||
let t; | ||
"file" in e ? (t = new L(), t.append("file", e.file)) : t = e.formData; | ||
const { fileMetadata: s, error: a } = await this.api.upload({ | ||
...e, | ||
formData: t | ||
async upload(t) { | ||
let o; | ||
return "file" in t ? (o = new C(), o.append("file", t.file)) : o = t.formData, this.api.upload({ | ||
...t, | ||
formData: o | ||
}); | ||
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) { | ||
const { fileId: t, ...s } = e; | ||
return S( | ||
`${this.url}/files/${t}`, | ||
s | ||
getPublicUrl(t) { | ||
const { fileId: o, ...n } = t; | ||
return te( | ||
`${this.url}/files/${o}`, | ||
n | ||
); | ||
} | ||
async getPresignedUrl(e) { | ||
const { presignedUrl: t, error: s } = await this.api.getPresignedUrl(e); | ||
return s ? { presignedUrl: null, error: s } : t ? { presignedUrl: t, error: null } : { presignedUrl: null, error: new Error("Invalid file id") }; | ||
async getPresignedUrl(t) { | ||
const { presignedUrl: o, error: n } = await this.api.getPresignedUrl(t); | ||
return n ? { presignedUrl: null, error: n } : o ? { presignedUrl: o, error: null } : { presignedUrl: null, error: new Error("Invalid file id") }; | ||
} | ||
async delete(e) { | ||
const { error: t } = await this.api.delete(e); | ||
return t ? { error: t } : { error: null }; | ||
async delete(t) { | ||
const { error: o } = await this.api.delete(t); | ||
return o ? { error: o } : { error: null }; | ||
} | ||
setAccessToken(e) { | ||
return this.api.setAccessToken(e), this; | ||
setAccessToken(t) { | ||
return this.api.setAccessToken(t), this; | ||
} | ||
setAdminSecret(e) { | ||
return this.api.setAdminSecret(e), this; | ||
setAdminSecret(t) { | ||
return this.api.setAdminSecret(t), this; | ||
} | ||
} | ||
const m = { | ||
const I = { | ||
progress: null, | ||
@@ -121,3 +428,3 @@ loaded: 0, | ||
id: void 0 | ||
}, T = () => E( | ||
}, re = () => j( | ||
{ | ||
@@ -130,3 +437,3 @@ predictableActionArguments: !0, | ||
tsTypes: {}, | ||
context: { ...m }, | ||
context: { ...I }, | ||
initial: "idle", | ||
@@ -172,15 +479,15 @@ on: { | ||
guards: { | ||
hasFile: (r, e) => !!r.file || !!e.file | ||
hasFile: (s, t) => !!s.file || !!t.file | ||
}, | ||
actions: { | ||
incrementProgress: i({ | ||
loaded: (r, { loaded: e }) => e, | ||
progress: (r, { progress: e }) => e | ||
incrementProgress: b({ | ||
loaded: (s, { loaded: t }) => t, | ||
progress: (s, { progress: t }) => t | ||
}), | ||
setFileMetadata: i({ | ||
id: (r, { id: e }) => e, | ||
bucketId: (r, { bucketId: e }) => e, | ||
progress: (r) => 100 | ||
setFileMetadata: b({ | ||
id: (s, { id: t }) => t, | ||
bucketId: (s, { bucketId: t }) => t, | ||
progress: (s) => 100 | ||
}), | ||
setError: i({ error: (r, { error: e }) => e }), | ||
setError: b({ error: (s, { error: t }) => t }), | ||
sendProgress: () => { | ||
@@ -194,50 +501,36 @@ }, | ||
}, | ||
resetProgress: i({ progress: (r) => null, loaded: (r) => 0 }), | ||
resetContext: i((r) => m), | ||
addFile: i({ | ||
file: (r, { file: e }) => e, | ||
bucketId: (r, { bucketId: e }) => e, | ||
id: (r, { id: e }) => e | ||
resetProgress: b({ progress: (s) => null, loaded: (s) => 0 }), | ||
resetContext: b((s) => I), | ||
addFile: b({ | ||
file: (s, { file: t }) => t, | ||
bucketId: (s, { bucketId: t }) => t, | ||
id: (s, { id: t }) => t | ||
}) | ||
}, | ||
services: { | ||
uploadFile: (r, e) => (t) => { | ||
const s = { | ||
"Content-Type": "multipart/form-data" | ||
}, a = e.id || r.id; | ||
a && (s["x-nhost-file-id"] = a); | ||
const n = e.bucketId || r.bucketId; | ||
n && (s["x-nhost-bucket-id"] = n); | ||
const l = e.file || r.file; | ||
s["x-nhost-file-name"] = O(e.name || l.name); | ||
const c = new FormData(); | ||
c.append("file", l), e.adminSecret && (s["x-hasura-admin-secret"] = e.adminSecret), e.accessToken && (s.Authorization = `Bearer ${e.accessToken}`); | ||
let u = 0; | ||
const A = new AbortController(); | ||
return y.post(e.url + "/files", c, { | ||
headers: s, | ||
signal: A.signal, | ||
onUploadProgress: (o) => { | ||
const d = o.total ? Math.round(o.loaded * l.size / o.total) : 0, p = d - u; | ||
u = d, t({ | ||
uploadFile: (s, t) => (o) => { | ||
const n = t.file || s.file, u = new C(); | ||
u.append("file", n); | ||
let c = 0; | ||
return H(t.url, u, { | ||
fileId: t.id || s.id, | ||
bucketId: t.bucketId || s.bucketId, | ||
accessToken: t.accessToken, | ||
adminSecret: t.adminSecret, | ||
name: t.name || n.name, | ||
onUploadProgress: (a) => { | ||
const d = a.total ? Math.round(a.loaded * n.size / a.total) : 0, m = d - c; | ||
c = d, o({ | ||
type: "UPLOAD_PROGRESS", | ||
progress: o.total ? Math.round(d * 100 / o.total) : 0, | ||
progress: a.total ? Math.round(d * 100 / a.total) : 0, | ||
loaded: d, | ||
additions: p | ||
additions: m | ||
}); | ||
} | ||
}).then(({ data: { id: o, bucketId: d } }) => { | ||
t({ type: "UPLOAD_DONE", id: o, bucketId: d }); | ||
}).catch(({ response: o, message: d }) => { | ||
var p, P, U, D; | ||
t({ | ||
type: "UPLOAD_ERROR", | ||
error: { | ||
status: (o == null ? void 0 : o.status) ?? 0, | ||
message: ((P = (p = o == null ? void 0 : o.data) == null ? void 0 : p.error) == null ? void 0 : P.message) || d, | ||
error: ((D = (U = o == null ? void 0 : o.data) == null ? void 0 : U.error) == null ? void 0 : D.message) || d | ||
} | ||
}); | ||
}).then(({ fileMetadata: a, error: d }) => { | ||
if (d && o({ type: "UPLOAD_ERROR", error: d }), a) { | ||
const { id: m, bucketId: w } = a; | ||
o({ type: "UPLOAD_DONE", id: m, bucketId: w }); | ||
} | ||
}), () => { | ||
A.abort(); | ||
}; | ||
@@ -247,3 +540,3 @@ } | ||
} | ||
), { pure: f, sendParent: h } = R, w = () => E( | ||
), { pure: S, sendParent: T } = K, ie = () => j( | ||
{ | ||
@@ -306,51 +599,51 @@ id: "files-list", | ||
guards: { | ||
hasFileToDownload: (r, e) => r.files.some((t) => t.getSnapshot().matches("idle")) || !!e.files, | ||
isAllUploaded: (r) => r.files.every((e) => { | ||
var t; | ||
return (t = e.getSnapshot()) == null ? void 0 : t.matches("uploaded"); | ||
hasFileToDownload: (s, t) => s.files.some((o) => o.getSnapshot().matches("idle")) || !!t.files, | ||
isAllUploaded: (s) => s.files.every((t) => { | ||
var o; | ||
return (o = t.getSnapshot()) == null ? void 0 : o.matches("uploaded"); | ||
}), | ||
isAllUploadedOrError: (r) => r.files.every((e) => { | ||
const t = e.getSnapshot(); | ||
return (t == null ? void 0 : t.matches("error")) || (t == null ? void 0 : t.matches("uploaded")); | ||
isAllUploadedOrError: (s) => s.files.every((t) => { | ||
const o = t.getSnapshot(); | ||
return (o == null ? void 0 : o.matches("error")) || (o == null ? void 0 : o.matches("uploaded")); | ||
}) | ||
}, | ||
actions: { | ||
incrementProgress: i((r, e) => { | ||
const t = r.loaded + e.additions, s = Math.round(t * 100 / r.total); | ||
return { ...r, loaded: t, progress: s }; | ||
incrementProgress: b((s, t) => { | ||
const o = s.loaded + t.additions, n = Math.round(o * 100 / s.total); | ||
return { ...s, loaded: o, progress: n }; | ||
}), | ||
setUploaded: i({ | ||
progress: (r) => 100, | ||
loaded: ({ files: r }) => r.map((e) => e.getSnapshot()).filter((e) => e.matches("uploaded")).reduce((e, t) => { | ||
var s; | ||
return e + ((s = t.context.file) == null ? void 0 : s.size); | ||
setUploaded: b({ | ||
progress: (s) => 100, | ||
loaded: ({ files: s }) => s.map((t) => t.getSnapshot()).filter((t) => t.matches("uploaded")).reduce((t, o) => { | ||
var n; | ||
return t + ((n = o.context.file) == null ? void 0 : n.size); | ||
}, 0) | ||
}), | ||
resetTotal: i({ | ||
total: ({ files: r }) => r.map((e) => e.getSnapshot()).filter((e) => !e.matches("uploaded")).reduce((e, t) => { | ||
var s; | ||
return e + ((s = t.context.file) == null ? void 0 : s.size); | ||
resetTotal: b({ | ||
total: ({ files: s }) => s.map((t) => t.getSnapshot()).filter((t) => !t.matches("uploaded")).reduce((t, o) => { | ||
var n; | ||
return t + ((n = o.context.file) == null ? void 0 : n.size); | ||
}, 0) | ||
}), | ||
resetLoaded: i({ loaded: (r) => 0 }), | ||
startProgress: i({ progress: (r) => 0 }), | ||
resetProgress: i({ progress: (r) => null }), | ||
addItem: i((r, { files: e, bucketId: t }) => { | ||
const s = e ? Array.isArray(e) ? e : "length" in e ? Array.from(e) : [e] : [], a = r.total + s.reduce((l, c) => l + c.size, 0), n = Math.round(r.loaded * 100 / a); | ||
resetLoaded: b({ loaded: (s) => 0 }), | ||
startProgress: b({ progress: (s) => 0 }), | ||
resetProgress: b({ progress: (s) => null }), | ||
addItem: b((s, { files: t, bucketId: o }) => { | ||
const n = t ? Array.isArray(t) ? t : "length" in t ? Array.from(t) : [t] : [], u = s.total + n.reduce((a, d) => a + d.size, 0), c = Math.round(s.loaded * 100 / u); | ||
return { | ||
files: [ | ||
...r.files, | ||
...s.map( | ||
(l) => _( | ||
T().withConfig({ | ||
...s.files, | ||
...n.map( | ||
(a) => J( | ||
re().withConfig({ | ||
actions: { | ||
sendProgress: h((c, { additions: u }) => ({ | ||
sendProgress: T((d, { additions: m }) => ({ | ||
type: "UPLOAD_PROGRESS", | ||
additions: u | ||
additions: m | ||
})), | ||
sendDone: h("UPLOAD_DONE"), | ||
sendError: h("UPLOAD_ERROR"), | ||
sendDestroy: h("REMOVE") | ||
sendDone: T("UPLOAD_DONE"), | ||
sendError: T("UPLOAD_ERROR"), | ||
sendDestroy: T("REMOVE") | ||
} | ||
}).withContext({ ...m, file: l, bucketId: t }), | ||
}).withContext({ ...I, file: a, bucketId: o }), | ||
{ sync: !0 } | ||
@@ -360,69 +653,68 @@ ) | ||
], | ||
total: a, | ||
loaded: r.loaded, | ||
progress: n | ||
total: u, | ||
loaded: s.loaded, | ||
progress: c | ||
}; | ||
}), | ||
removeItem: i({ | ||
files: (r) => r.files.filter((e) => { | ||
var s, a; | ||
const t = (s = e.getSnapshot()) == null ? void 0 : s.matches("stopped"); | ||
return t && ((a = e.stop) == null || a.call(e)), !t; | ||
removeItem: b({ | ||
files: (s) => s.files.filter((t) => { | ||
var n, u; | ||
const o = (n = t.getSnapshot()) == null ? void 0 : n.matches("stopped"); | ||
return o && ((u = t.stop) == null || u.call(t)), !o; | ||
}) | ||
}), | ||
clearList: f( | ||
(r) => r.files.map((e) => g({ type: "DESTROY" }, { to: e.id })) | ||
clearList: S( | ||
(s) => s.files.map((t) => L({ type: "DESTROY" }, { to: t.id })) | ||
), | ||
upload: f((r, e) => r.files.map((t) => g(e, { to: t.id }))), | ||
cancel: f( | ||
(r) => r.files.map((e) => g({ type: "CANCEL" }, { to: e.id })) | ||
upload: S((s, t) => s.files.map((o) => L(t, { to: o.id }))), | ||
cancel: S( | ||
(s) => s.files.map((t) => L({ type: "CANCEL" }, { to: t.id })) | ||
) | ||
} | ||
} | ||
), F = async (r, e) => new Promise((t) => { | ||
e.send({ | ||
), ae = async (s, t) => new Promise((o) => { | ||
t.send({ | ||
type: "UPLOAD", | ||
...r | ||
}), e.subscribe((s) => { | ||
var a; | ||
s.matches("error") ? t({ | ||
error: s.context.error, | ||
...s | ||
}), t.subscribe((n) => { | ||
var u; | ||
n.matches("error") ? o({ | ||
error: n.context.error, | ||
isError: !0, | ||
isUploaded: !1 | ||
}) : s.matches("uploaded") && t({ | ||
}) : n.matches("uploaded") && o({ | ||
error: null, | ||
isError: !1, | ||
isUploaded: !0, | ||
id: s.context.id, | ||
bucketId: s.context.id, | ||
name: (a = s.context.file) == null ? void 0 : a.name | ||
id: n.context.id, | ||
bucketId: n.context.id, | ||
name: (u = n.context.file) == null ? void 0 : u.name | ||
}); | ||
}); | ||
}), M = async (r, e) => new Promise((t) => { | ||
e.send({ | ||
}), de = async (s, t) => new Promise((o) => { | ||
t.send({ | ||
type: "UPLOAD", | ||
...r, | ||
files: r.files | ||
}), e.onTransition((s) => { | ||
s.matches("error") ? t({ | ||
errors: s.context.files.filter((a) => { | ||
var n; | ||
return (n = a.getSnapshot()) == null ? void 0 : n.context.error; | ||
...s, | ||
files: s.files | ||
}), t.onTransition((n) => { | ||
n.matches("error") ? o({ | ||
errors: n.context.files.filter((u) => { | ||
var c; | ||
return (c = u.getSnapshot()) == null ? void 0 : c.context.error; | ||
}), | ||
isError: !0, | ||
files: [] | ||
}) : s.matches("uploaded") && t({ errors: [], isError: !1, files: s.context.files }); | ||
}) : n.matches("uploaded") && o({ errors: [], isError: !1, files: n.context.files }); | ||
}); | ||
}); | ||
export { | ||
I as HasuraStorageApi, | ||
k as HasuraStorageClient, | ||
m as INITIAL_FILE_CONTEXT, | ||
S as appendImageTransformationParameters, | ||
T as createFileUploadMachine, | ||
w as createMultipleFilesUploadMachine, | ||
O as toIso88591, | ||
F as uploadFilePromise, | ||
M as uploadMultipleFilesPromise | ||
ee as HasuraStorageApi, | ||
ne as HasuraStorageClient, | ||
I as INITIAL_FILE_CONTEXT, | ||
te as appendImageTransformationParameters, | ||
re as createFileUploadMachine, | ||
ie as createMultipleFilesUploadMachine, | ||
ae as uploadFilePromise, | ||
de as uploadMultipleFilesPromise | ||
}; | ||
//# sourceMappingURL=index.esm.js.map |
import { StorageImageTransformationParams } from './types'; | ||
export * from './types'; | ||
export declare const appendImageTransformationParameters: (url: string, params: StorageImageTransformationParams) => string; | ||
/** Convert any string into ISO-8859-1 */ | ||
export declare const toIso88591: (fileName: string) => string; | ||
//# sourceMappingURL=index.d.ts.map |
@@ -39,3 +39,3 @@ import FormData from 'form-data'; | ||
fileMetadata: null; | ||
error: Error; | ||
error: ErrorPayload; | ||
}; | ||
@@ -74,3 +74,3 @@ export interface StorageImageTransformationParams { | ||
} | ||
interface FileResponse { | ||
export interface FileResponse { | ||
id: string; | ||
@@ -83,2 +83,5 @@ name: string; | ||
bucketId: string; | ||
isUploaded: true; | ||
updatedAt: string; | ||
uploadedByUserId: string; | ||
} | ||
@@ -91,9 +94,2 @@ export interface ApiUploadParams { | ||
} | ||
export declare type ApiUploadResponse = { | ||
fileMetadata: FileResponse; | ||
error: null; | ||
} | { | ||
fileMetadata: null; | ||
error: Error; | ||
}; | ||
export interface ApiGetPresignedUrlParams { | ||
@@ -118,8 +114,7 @@ fileId: string; | ||
} | ||
export interface UploadHeaders { | ||
export declare type UploadHeaders = HeadersInit & { | ||
'x-nhost-bucket-id'?: string; | ||
'x-nhost-file-id'?: string; | ||
'x-nhost-file-name'?: string; | ||
} | ||
export {}; | ||
}; | ||
//# sourceMappingURL=types.d.ts.map |
{ | ||
"name": "@nhost/hasura-storage-js", | ||
"version": "1.13.2", | ||
"version": "2.0.0", | ||
"description": "Hasura-storage client", | ||
@@ -43,3 +43,2 @@ "license": "MIT", | ||
"dependencies": { | ||
"axios": "^1.2.0", | ||
"form-data": "^4.0.0", | ||
@@ -46,0 +45,0 @@ "xstate": "^4.33.5" |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is not supported yet
2
37
1647
569203
- Removedaxios@^1.2.0
- Removedaxios@1.7.9(transitive)
- Removedfollow-redirects@1.15.9(transitive)
- Removedproxy-from-env@1.1.0(transitive)