@bloque/sdk-core 0.1.13 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/http-client.d.ts +5 -0
- package/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/package.json +1 -1
package/dist/http-client.d.ts
CHANGED
|
@@ -57,6 +57,11 @@ export declare class HttpClient {
|
|
|
57
57
|
* @internal - Called internally when origin is resolved after JWT authentication.
|
|
58
58
|
*/
|
|
59
59
|
setOrigin(origin: string): void;
|
|
60
|
+
/**
|
|
61
|
+
* Create an isolated copy with its own session state (accessToken, urn, origin).
|
|
62
|
+
* Used to encapsulate per-identity sessions without mutating the root client.
|
|
63
|
+
*/
|
|
64
|
+
fork(): HttpClient;
|
|
60
65
|
private validateConfig;
|
|
61
66
|
private isPublicRoute;
|
|
62
67
|
private buildAuthHeaders;
|
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";const __rslib_import_meta_url__="u"<typeof document?new(require("url".replace("",""))).URL("file:"+__filename).href:document.currentScript&&document.currentScript.src||new URL("main.js",document.baseURI).href;var __webpack_require__={};__webpack_require__.d=(e,r)=>{for(var t in r)__webpack_require__.o(r,t)&&!__webpack_require__.o(e,t)&&Object.defineProperty(e,t,{enumerable:!0,get:r[t]})},__webpack_require__.o=(e,r)=>Object.prototype.hasOwnProperty.call(e,r),__webpack_require__.r=e=>{"u">typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var __webpack_exports__={};__webpack_require__.r(__webpack_exports__),__webpack_require__.d(__webpack_exports__,{BloqueInsufficientFundsError:()=>BloqueInsufficientFundsError,API_BASE_URLS:()=>API_BASE_URLS,BloqueNetworkError:()=>BloqueNetworkError,createBloqueError:()=>createBloqueError,BloqueConfigError:()=>BloqueConfigError,BaseClient:()=>BaseClient,BloqueNotFoundError:()=>BloqueNotFoundError,HttpClient:()=>HttpClient,SUPPORTED_ASSETS:()=>SUPPORTED_ASSETS,BloqueAuthenticationError:()=>BloqueAuthenticationError,BloqueRateLimitError:()=>BloqueRateLimitError,DEFAULT_HEADERS:()=>DEFAULT_HEADERS,BloqueAPIError:()=>BloqueAPIError,BloqueValidationError:()=>BloqueValidationError,isSupportedAsset:()=>isSupportedAsset,BloqueTimeoutError:()=>BloqueTimeoutError});class BaseClient{httpClient;constructor(e){this.httpClient=e}}const API_BASE_URLS={sandbox:"https://api.dev-bloque.app",production:"https://api.bloque.app"},DEFAULT_HEADERS={"Content-Type":"application/json"},SUPPORTED_ASSETS=["DUSD/6","COPB/6","COPM/2","KSM/12"];function isSupportedAsset(e){return SUPPORTED_ASSETS.includes(e)}class BloqueAPIError extends Error{status;code;requestId;timestamp;response;cause;constructor(e,r){super(e),this.name="BloqueAPIError",this.status=r?.status,this.code=r?.code,this.requestId=r?.requestId,this.response=r?.response,this.cause=r?.cause,this.timestamp=new Date,Object.setPrototypeOf(this,BloqueAPIError.prototype)}toJSON(){return{name:this.name,message:this.message,status:this.status,code:this.code,requestId:this.requestId,timestamp:this.timestamp.toISOString(),response:this.response,stack:this.stack}}}class BloqueRateLimitError extends BloqueAPIError{retryAfter;constructor(e,r){super(e,{...r,status:429}),this.name="BloqueRateLimitError",this.retryAfter=r?.retryAfter,Object.setPrototypeOf(this,BloqueRateLimitError.prototype)}toJSON(){return{...super.toJSON(),retryAfter:this.retryAfter}}}class BloqueAuthenticationError extends BloqueAPIError{constructor(e,r){super(e,r),this.name="BloqueAuthenticationError",Object.setPrototypeOf(this,BloqueAuthenticationError.prototype)}}class BloqueValidationError extends BloqueAPIError{validationErrors;constructor(e,r){super(e,{...r,status:400}),this.name="BloqueValidationError",this.validationErrors=r?.validationErrors,Object.setPrototypeOf(this,BloqueValidationError.prototype)}toJSON(){return{...super.toJSON(),validationErrors:this.validationErrors}}}class BloqueNotFoundError extends BloqueAPIError{resourceType;resourceId;constructor(e,r){super(e,{...r,status:404}),this.name="BloqueNotFoundError",this.resourceType=r?.resourceType,this.resourceId=r?.resourceId,Object.setPrototypeOf(this,BloqueNotFoundError.prototype)}toJSON(){return{...super.toJSON(),resourceType:this.resourceType,resourceId:this.resourceId}}}class BloqueInsufficientFundsError extends BloqueAPIError{requestedAmount;availableBalance;currency;constructor(e,r){super(e,r),this.name="BloqueInsufficientFundsError",this.requestedAmount=r?.requestedAmount,this.availableBalance=r?.availableBalance,this.currency=r?.currency,Object.setPrototypeOf(this,BloqueInsufficientFundsError.prototype)}toJSON(){return{...super.toJSON(),requestedAmount:this.requestedAmount,availableBalance:this.availableBalance,currency:this.currency}}}class BloqueNetworkError extends BloqueAPIError{constructor(e,r){super(e,{...r,code:r?.code??"NETWORK_ERROR"}),this.name="BloqueNetworkError",Object.setPrototypeOf(this,BloqueNetworkError.prototype)}}class BloqueTimeoutError extends BloqueAPIError{timeoutMs;constructor(e,r){super(e,{...r,code:"TIMEOUT_ERROR"}),this.name="BloqueTimeoutError",this.timeoutMs=r?.timeoutMs??0,Object.setPrototypeOf(this,BloqueTimeoutError.prototype)}toJSON(){return{...super.toJSON(),timeoutMs:this.timeoutMs}}}class BloqueConfigError extends Error{constructor(e){super(e),this.name="BloqueConfigError",Object.setPrototypeOf(this,BloqueConfigError.prototype)}}const ERROR_CODE_MAP={INSUFFICIENT_FUNDS:BloqueInsufficientFundsError,INSUFFICIENT_BALANCE:BloqueInsufficientFundsError};function createBloqueError(e,r){let{status:t,code:o}=r??{};if(o&&ERROR_CODE_MAP[o])return new ERROR_CODE_MAP[o](e,r);switch(t){case 400:return new BloqueValidationError(e,r);case 401:case 403:return new BloqueAuthenticationError(e,r);case 404:return new BloqueNotFoundError(e,r);case 429:return new BloqueRateLimitError(e,r);default:return new BloqueAPIError(e,r)}}const EXCHANGE_REFRESH_BUFFER_MS=6e4,IDEMPOTENCY_HEADER="Idempotency-Key",IDEMPOTENT_METHODS=new Set(["POST","PUT"]),isFrontendPlatform=e=>"browser"===e||"react-native"===e;class HttpClient{_config;baseUrl;_exchangeExpiry=0;_exchangePromise=null;publicRoutes=["/api/aliases","/api/origins/*/assert","/api/origins/*/connect","/api/origins","/api/api-keys/exchange"];constructor(e){const r={...e};this.validateConfig(r),this._config=r,this.baseUrl=r.baseUrl??API_BASE_URLS[r.mode??"production"]}get origin(){return this._config.origin}get auth(){return this._config.auth}get urn(){return this._config.urn}get accessToken(){return this._config.accessToken}setAccessToken(e){this._config.accessToken=e}setJwtToken(e){if("jwt"!==this._config.auth.type)throw new BloqueConfigError("JWT token can only be set for JWT auth");this._config.tokenStorage?.set(e),this._config.accessToken=e}getJwtToken(){if("jwt"!==this._config.auth.type)throw new BloqueConfigError("JWT token is only available for JWT auth");return this._config.tokenStorage?.get()??null}setUrn(e){this._config.urn=e}setOrigin(e){this._config.origin=e}validateConfig(e){if(e.mode??="production",e.platform??="node",e.timeout??=3e4,e.retry??={},e.retry.enabled??=!0,e.retry.maxRetries??=3,e.retry.initialDelay??=1e3,e.retry.maxDelay??=3e4,!["sandbox","production"].includes(e.mode))throw new BloqueConfigError('Mode must be either "sandbox" or "production"');if(void 0!==e.timeout&&e.timeout<0)throw new BloqueConfigError("Timeout must be a non-negative number");if(void 0!==e.retry.maxRetries&&e.retry.maxRetries<0)throw new BloqueConfigError("maxRetries must be a non-negative number");if(void 0!==e.retry.initialDelay&&e.retry.initialDelay<0)throw new BloqueConfigError("initialDelay must be a non-negative number");if(void 0!==e.retry.maxDelay&&e.retry.maxDelay<0)throw new BloqueConfigError("maxDelay must be a non-negative number");if("apiKey"===e.auth.type){if(!e.auth.apiKey?.trim())throw new BloqueConfigError("API key (sk_ secret key) is required for apiKey authentication");if(isFrontendPlatform(e.platform))throw new BloqueConfigError("API key authentication is not allowed in frontend platforms")}if("originKey"===e.auth.type){if(!e.auth.originKey?.trim())throw new BloqueConfigError("Origin key is required for originKey authentication");if(!e.origin?.trim())throw new BloqueConfigError("Origin is required for originKey authentication");if(isFrontendPlatform(e.platform))throw new BloqueConfigError("Origin key authentication is not allowed in frontend platforms")}if("jwt"===e.auth.type&&"browser"!==e.platform&&!e.tokenStorage)throw new BloqueConfigError("tokenStorage must be provided when using JWT authentication outside browser platform")}isPublicRoute(e){let r=e.split("?")[0];return this.publicRoutes.some(e=>{let t=e.replace(/\*/g,"[^/]+");return RegExp(`^${t}$`).test(r)})}buildAuthHeaders(e){if(this.isPublicRoute(e))return{};if("apiKey"===this._config.auth.type)return this._config.accessToken?{Authorization:`Bearer ${this._config.accessToken}`}:{};if("originKey"===this._config.auth.type)return this._config.accessToken?{Authorization:`Bearer ${this._config.accessToken}`}:{Authorization:this._config.auth.originKey};if("jwt"===this._config.auth.type){if("browser"===this._config.platform)return{};let e=this._config.tokenStorage?.get();if(!e)throw new BloqueConfigError("Authentication token is missing");return{Authorization:`Bearer ${e}`}}return{}}isRetryableError(e){return e instanceof BloqueRateLimitError||e instanceof BloqueNetworkError||e instanceof BloqueTimeoutError||e instanceof Error&&"status"in e&&503===e.status}calculateRetryDelay(e,r){let{initialDelay:t=1e3,maxDelay:o=3e4}=this._config.retry??{};if(r){let e=Number.parseInt(r,10);if(!Number.isNaN(e))return Math.min(1e3*e,o);let t=new Date(r);if(!Number.isNaN(t.getTime()))return Math.min(Math.max(t.getTime()-Date.now(),0),o)}let i=t*2**e,s=.25*i*(2*Math.random()-1);return Math.min(i+s,o)}sleep(e){return new Promise(r=>setTimeout(r,e))}generateIdempotencyKey(){return void 0!==globalThis.crypto&&"function"==typeof globalThis.crypto.randomUUID?globalThis.crypto.randomUUID():`idem_${Date.now()}_${Math.random().toString(36).slice(2)}`}isIdempotencyKeyError(e,r){if(409!==e&&400!==e)return!1;let t=`${r.code??""} ${r.message??""}`.toLowerCase().trim();return t.includes("idempotency-key")||t.includes("idempotency key")||t.includes("duplicated idempotency key")}async ensureExchanged(){"apiKey"!==this._config.auth.type||(this._exchangePromise?await this._exchangePromise:this._config.accessToken&&Date.now()<this._exchangeExpiry-6e4||(this._exchangePromise=(async()=>{try{let e=this._config.auth,r=await this.request({method:"POST",path:"/api/api-keys/exchange",body:{key:e.apiKey,scopes:e.scopes},_skipExchange:!0});if(!r.access_token)throw new BloqueAuthenticationError("API key exchange returned an invalid response (missing access_token)",{status:401});this._config.accessToken=r.access_token,this._exchangeExpiry=Date.now()+1e3*r.expires_in}finally{this._exchangePromise=null}})(),await this._exchangePromise))}async request(e){let r;"apiKey"!==this._config.auth.type||e._skipExchange||await this.ensureExchanged();let{method:t,path:o,body:i,headers:s={},timeout:n}=e,a=`${this.baseUrl}${o}`,u={...DEFAULT_HEADERS,...this.buildAuthHeaders(o),...s};IDEMPOTENT_METHODS.has(t.toUpperCase())&&(u[IDEMPOTENCY_HEADER]=u[IDEMPOTENCY_HEADER]||this.generateIdempotencyKey());let c=void 0!==n?n:this._config.timeout??3e4,{enabled:l=!0,maxRetries:_=3}=this._config.retry??{},p=0;for(;p<=(l?_:0);){let e,o=new AbortController;c>0&&(e=setTimeout(()=>{o.abort()},c));try{let s=await fetch(a,{method:t,headers:u,body:i?JSON.stringify(i):void 0,credentials:"jwt"===this._config.auth.type&&"browser"===this._config.platform?"include":void 0,signal:o.signal});void 0!==e&&clearTimeout(e);let n=await s.json().catch(()=>({}));if(!s.ok){let e=s.headers.get("X-Request-ID")??s.headers.get("Request-ID")??void 0,t=s.headers.get("Retry-After"),o=429===s.status?new BloqueRateLimitError(n.message||"Rate limit exceeded",{status:s.status,code:n.code,requestId:e,response:n,retryAfter:t?Number.parseInt(t,10):void 0}):createBloqueError(n.message||`HTTP ${s.status}: ${s.statusText}`,{status:s.status,code:n.code,requestId:e,response:n});if(this.isIdempotencyKeyError(s.status,n))throw o;if(l&&p<_&&this.isRetryableError(o)){r=o;let e=this.calculateRetryDelay(p,t??void 0);await this.sleep(e),p++;continue}throw o}return n}catch(o){let t;if(void 0!==e&&clearTimeout(e),o&&"object"==typeof o&&"name"in o&&"string"==typeof o.name&&o.name.startsWith("Bloque")&&!this.isRetryableError(o))throw o;if(t=o instanceof Error&&"AbortError"===o.name?new BloqueTimeoutError(`Request timeout after ${c}ms`,{timeoutMs:c,cause:o}):o instanceof Error?new BloqueNetworkError(`Request failed: ${o.message}`,{cause:o}):createBloqueError("Unknown error occurred",{code:"UNKNOWN_ERROR"}),l&&p<_&&this.isRetryableError(t)){r=t;let e=this.calculateRetryDelay(p);await this.sleep(e),p++;continue}throw t}}throw r||createBloqueError("Request failed after retries",{code:"MAX_RETRIES_EXCEEDED"})}}for(var __rspack_i in exports.API_BASE_URLS=__webpack_exports__.API_BASE_URLS,exports.BaseClient=__webpack_exports__.BaseClient,exports.BloqueAPIError=__webpack_exports__.BloqueAPIError,exports.BloqueAuthenticationError=__webpack_exports__.BloqueAuthenticationError,exports.BloqueConfigError=__webpack_exports__.BloqueConfigError,exports.BloqueInsufficientFundsError=__webpack_exports__.BloqueInsufficientFundsError,exports.BloqueNetworkError=__webpack_exports__.BloqueNetworkError,exports.BloqueNotFoundError=__webpack_exports__.BloqueNotFoundError,exports.BloqueRateLimitError=__webpack_exports__.BloqueRateLimitError,exports.BloqueTimeoutError=__webpack_exports__.BloqueTimeoutError,exports.BloqueValidationError=__webpack_exports__.BloqueValidationError,exports.DEFAULT_HEADERS=__webpack_exports__.DEFAULT_HEADERS,exports.HttpClient=__webpack_exports__.HttpClient,exports.SUPPORTED_ASSETS=__webpack_exports__.SUPPORTED_ASSETS,exports.createBloqueError=__webpack_exports__.createBloqueError,exports.isSupportedAsset=__webpack_exports__.isSupportedAsset,__webpack_exports__)-1===["API_BASE_URLS","BaseClient","BloqueAPIError","BloqueAuthenticationError","BloqueConfigError","BloqueInsufficientFundsError","BloqueNetworkError","BloqueNotFoundError","BloqueRateLimitError","BloqueTimeoutError","BloqueValidationError","DEFAULT_HEADERS","HttpClient","SUPPORTED_ASSETS","createBloqueError","isSupportedAsset"].indexOf(__rspack_i)&&(exports[__rspack_i]=__webpack_exports__[__rspack_i]);Object.defineProperty(exports,"__esModule",{value:!0});
|
|
1
|
+
"use strict";const __rslib_import_meta_url__="u"<typeof document?new(require("url".replace("",""))).URL("file:"+__filename).href:document.currentScript&&document.currentScript.src||new URL("main.js",document.baseURI).href;var __webpack_require__={};__webpack_require__.d=(e,r)=>{for(var t in r)__webpack_require__.o(r,t)&&!__webpack_require__.o(e,t)&&Object.defineProperty(e,t,{enumerable:!0,get:r[t]})},__webpack_require__.o=(e,r)=>Object.prototype.hasOwnProperty.call(e,r),__webpack_require__.r=e=>{"u">typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var __webpack_exports__={};__webpack_require__.r(__webpack_exports__),__webpack_require__.d(__webpack_exports__,{BloqueInsufficientFundsError:()=>BloqueInsufficientFundsError,API_BASE_URLS:()=>API_BASE_URLS,BloqueNetworkError:()=>BloqueNetworkError,createBloqueError:()=>createBloqueError,BloqueConfigError:()=>BloqueConfigError,BaseClient:()=>BaseClient,BloqueNotFoundError:()=>BloqueNotFoundError,HttpClient:()=>HttpClient,SUPPORTED_ASSETS:()=>SUPPORTED_ASSETS,BloqueAuthenticationError:()=>BloqueAuthenticationError,BloqueRateLimitError:()=>BloqueRateLimitError,DEFAULT_HEADERS:()=>DEFAULT_HEADERS,BloqueAPIError:()=>BloqueAPIError,BloqueValidationError:()=>BloqueValidationError,isSupportedAsset:()=>isSupportedAsset,BloqueTimeoutError:()=>BloqueTimeoutError});class BaseClient{httpClient;constructor(e){this.httpClient=e}}const API_BASE_URLS={sandbox:"https://api.dev-bloque.app",production:"https://api.bloque.app"},DEFAULT_HEADERS={"Content-Type":"application/json"},SUPPORTED_ASSETS=["DUSD/6","COPB/6","COPM/2","KSM/12"];function isSupportedAsset(e){return SUPPORTED_ASSETS.includes(e)}class BloqueAPIError extends Error{status;code;requestId;timestamp;response;cause;constructor(e,r){super(e),this.name="BloqueAPIError",this.status=r?.status,this.code=r?.code,this.requestId=r?.requestId,this.response=r?.response,this.cause=r?.cause,this.timestamp=new Date,Object.setPrototypeOf(this,BloqueAPIError.prototype)}toJSON(){return{name:this.name,message:this.message,status:this.status,code:this.code,requestId:this.requestId,timestamp:this.timestamp.toISOString(),response:this.response,stack:this.stack}}}class BloqueRateLimitError extends BloqueAPIError{retryAfter;constructor(e,r){super(e,{...r,status:429}),this.name="BloqueRateLimitError",this.retryAfter=r?.retryAfter,Object.setPrototypeOf(this,BloqueRateLimitError.prototype)}toJSON(){return{...super.toJSON(),retryAfter:this.retryAfter}}}class BloqueAuthenticationError extends BloqueAPIError{constructor(e,r){super(e,r),this.name="BloqueAuthenticationError",Object.setPrototypeOf(this,BloqueAuthenticationError.prototype)}}class BloqueValidationError extends BloqueAPIError{validationErrors;constructor(e,r){super(e,{...r,status:400}),this.name="BloqueValidationError",this.validationErrors=r?.validationErrors,Object.setPrototypeOf(this,BloqueValidationError.prototype)}toJSON(){return{...super.toJSON(),validationErrors:this.validationErrors}}}class BloqueNotFoundError extends BloqueAPIError{resourceType;resourceId;constructor(e,r){super(e,{...r,status:404}),this.name="BloqueNotFoundError",this.resourceType=r?.resourceType,this.resourceId=r?.resourceId,Object.setPrototypeOf(this,BloqueNotFoundError.prototype)}toJSON(){return{...super.toJSON(),resourceType:this.resourceType,resourceId:this.resourceId}}}class BloqueInsufficientFundsError extends BloqueAPIError{requestedAmount;availableBalance;currency;constructor(e,r){super(e,r),this.name="BloqueInsufficientFundsError",this.requestedAmount=r?.requestedAmount,this.availableBalance=r?.availableBalance,this.currency=r?.currency,Object.setPrototypeOf(this,BloqueInsufficientFundsError.prototype)}toJSON(){return{...super.toJSON(),requestedAmount:this.requestedAmount,availableBalance:this.availableBalance,currency:this.currency}}}class BloqueNetworkError extends BloqueAPIError{constructor(e,r){super(e,{...r,code:r?.code??"NETWORK_ERROR"}),this.name="BloqueNetworkError",Object.setPrototypeOf(this,BloqueNetworkError.prototype)}}class BloqueTimeoutError extends BloqueAPIError{timeoutMs;constructor(e,r){super(e,{...r,code:"TIMEOUT_ERROR"}),this.name="BloqueTimeoutError",this.timeoutMs=r?.timeoutMs??0,Object.setPrototypeOf(this,BloqueTimeoutError.prototype)}toJSON(){return{...super.toJSON(),timeoutMs:this.timeoutMs}}}class BloqueConfigError extends Error{constructor(e){super(e),this.name="BloqueConfigError",Object.setPrototypeOf(this,BloqueConfigError.prototype)}}const ERROR_CODE_MAP={INSUFFICIENT_FUNDS:BloqueInsufficientFundsError,INSUFFICIENT_BALANCE:BloqueInsufficientFundsError};function createBloqueError(e,r){let{status:t,code:o}=r??{};if(o&&ERROR_CODE_MAP[o])return new ERROR_CODE_MAP[o](e,r);switch(t){case 400:return new BloqueValidationError(e,r);case 401:case 403:return new BloqueAuthenticationError(e,r);case 404:return new BloqueNotFoundError(e,r);case 429:return new BloqueRateLimitError(e,r);default:return new BloqueAPIError(e,r)}}const EXCHANGE_REFRESH_BUFFER_MS=6e4,IDEMPOTENCY_HEADER="Idempotency-Key",IDEMPOTENT_METHODS=new Set(["POST","PUT"]),isFrontendPlatform=e=>"browser"===e||"react-native"===e;class HttpClient{_config;baseUrl;_exchangeExpiry=0;_exchangePromise=null;publicRoutes=["/api/aliases","/api/origins/*/assert","/api/origins/*/connect","/api/origins","/api/api-keys/exchange"];constructor(e){const r={...e};this.validateConfig(r),this._config=r,this.baseUrl=r.baseUrl??API_BASE_URLS[r.mode??"production"]}get origin(){return this._config.origin}get auth(){return this._config.auth}get urn(){return this._config.urn}get accessToken(){return this._config.accessToken}setAccessToken(e){this._config.accessToken=e}setJwtToken(e){if("jwt"!==this._config.auth.type)throw new BloqueConfigError("JWT token can only be set for JWT auth");this._config.tokenStorage?.set(e),this._config.accessToken=e}getJwtToken(){if("jwt"!==this._config.auth.type)throw new BloqueConfigError("JWT token is only available for JWT auth");return this._config.tokenStorage?.get()??null}setUrn(e){this._config.urn=e}setOrigin(e){this._config.origin=e}fork(){return new HttpClient({...this._config})}validateConfig(e){if(e.mode??="production",e.platform??="node",e.timeout??=3e4,e.retry??={},e.retry.enabled??=!0,e.retry.maxRetries??=3,e.retry.initialDelay??=1e3,e.retry.maxDelay??=3e4,!["sandbox","production"].includes(e.mode))throw new BloqueConfigError('Mode must be either "sandbox" or "production"');if(void 0!==e.timeout&&e.timeout<0)throw new BloqueConfigError("Timeout must be a non-negative number");if(void 0!==e.retry.maxRetries&&e.retry.maxRetries<0)throw new BloqueConfigError("maxRetries must be a non-negative number");if(void 0!==e.retry.initialDelay&&e.retry.initialDelay<0)throw new BloqueConfigError("initialDelay must be a non-negative number");if(void 0!==e.retry.maxDelay&&e.retry.maxDelay<0)throw new BloqueConfigError("maxDelay must be a non-negative number");if("apiKey"===e.auth.type){if(!e.auth.apiKey?.trim())throw new BloqueConfigError("API key (sk_ secret key) is required for apiKey authentication");if(isFrontendPlatform(e.platform))throw new BloqueConfigError("API key authentication is not allowed in frontend platforms")}if("originKey"===e.auth.type){if(!e.auth.originKey?.trim())throw new BloqueConfigError("Origin key is required for originKey authentication");if(!e.origin?.trim())throw new BloqueConfigError("Origin is required for originKey authentication");if(isFrontendPlatform(e.platform))throw new BloqueConfigError("Origin key authentication is not allowed in frontend platforms")}if("jwt"===e.auth.type&&"browser"!==e.platform&&!e.tokenStorage)throw new BloqueConfigError("tokenStorage must be provided when using JWT authentication outside browser platform")}isPublicRoute(e){let r=e.split("?")[0];return this.publicRoutes.some(e=>{let t=e.replace(/\*/g,"[^/]+");return RegExp(`^${t}$`).test(r)})}buildAuthHeaders(e){if(this.isPublicRoute(e))return{};if("apiKey"===this._config.auth.type)return this._config.accessToken?{Authorization:`Bearer ${this._config.accessToken}`}:{};if("originKey"===this._config.auth.type)return this._config.accessToken?{Authorization:`Bearer ${this._config.accessToken}`}:{Authorization:this._config.auth.originKey};if("jwt"===this._config.auth.type){if("browser"===this._config.platform)return{};let e=this._config.tokenStorage?.get();if(!e)throw new BloqueConfigError("Authentication token is missing");return{Authorization:`Bearer ${e}`}}return{}}isRetryableError(e){return e instanceof BloqueRateLimitError||e instanceof BloqueNetworkError||e instanceof BloqueTimeoutError||e instanceof Error&&"status"in e&&503===e.status}calculateRetryDelay(e,r){let{initialDelay:t=1e3,maxDelay:o=3e4}=this._config.retry??{};if(r){let e=Number.parseInt(r,10);if(!Number.isNaN(e))return Math.min(1e3*e,o);let t=new Date(r);if(!Number.isNaN(t.getTime()))return Math.min(Math.max(t.getTime()-Date.now(),0),o)}let i=t*2**e,s=.25*i*(2*Math.random()-1);return Math.min(i+s,o)}sleep(e){return new Promise(r=>setTimeout(r,e))}generateIdempotencyKey(){return void 0!==globalThis.crypto&&"function"==typeof globalThis.crypto.randomUUID?globalThis.crypto.randomUUID():`idem_${Date.now()}_${Math.random().toString(36).slice(2)}`}isIdempotencyKeyError(e,r){if(409!==e&&400!==e)return!1;let t=`${r.code??""} ${r.message??""}`.toLowerCase().trim();return t.includes("idempotency-key")||t.includes("idempotency key")||t.includes("duplicated idempotency key")}async ensureExchanged(){"apiKey"!==this._config.auth.type||(this._exchangePromise?await this._exchangePromise:this._config.accessToken&&Date.now()<this._exchangeExpiry-6e4||(this._exchangePromise=(async()=>{try{let e=this._config.auth,r=await this.request({method:"POST",path:"/api/api-keys/exchange",body:{key:e.apiKey,scopes:e.scopes},_skipExchange:!0});if(!r.access_token)throw new BloqueAuthenticationError("API key exchange returned an invalid response (missing access_token)",{status:401});this._config.accessToken=r.access_token,this._exchangeExpiry=Date.now()+1e3*r.expires_in}finally{this._exchangePromise=null}})(),await this._exchangePromise))}async request(e){let r;"apiKey"!==this._config.auth.type||e._skipExchange||await this.ensureExchanged();let{method:t,path:o,body:i,headers:s={},timeout:n}=e,a=`${this.baseUrl}${o}`,u={...DEFAULT_HEADERS,...this.buildAuthHeaders(o),...s};IDEMPOTENT_METHODS.has(t.toUpperCase())&&(u[IDEMPOTENCY_HEADER]=u[IDEMPOTENCY_HEADER]||this.generateIdempotencyKey());let c=void 0!==n?n:this._config.timeout??3e4,{enabled:l=!0,maxRetries:_=3}=this._config.retry??{},p=0;for(;p<=(l?_:0);){let e,o=new AbortController;c>0&&(e=setTimeout(()=>{o.abort()},c));try{let s=await fetch(a,{method:t,headers:u,body:i?JSON.stringify(i):void 0,credentials:"jwt"===this._config.auth.type&&"browser"===this._config.platform?"include":void 0,signal:o.signal});void 0!==e&&clearTimeout(e);let n=await s.json().catch(()=>({}));if(!s.ok){let e=s.headers.get("X-Request-ID")??s.headers.get("Request-ID")??void 0,t=s.headers.get("Retry-After"),o=429===s.status?new BloqueRateLimitError(n.message||"Rate limit exceeded",{status:s.status,code:n.code,requestId:e,response:n,retryAfter:t?Number.parseInt(t,10):void 0}):createBloqueError(n.message||`HTTP ${s.status}: ${s.statusText}`,{status:s.status,code:n.code,requestId:e,response:n});if(this.isIdempotencyKeyError(s.status,n))throw o;if(l&&p<_&&this.isRetryableError(o)){r=o;let e=this.calculateRetryDelay(p,t??void 0);await this.sleep(e),p++;continue}throw o}return n}catch(o){let t;if(void 0!==e&&clearTimeout(e),o&&"object"==typeof o&&"name"in o&&"string"==typeof o.name&&o.name.startsWith("Bloque")&&!this.isRetryableError(o))throw o;if(t=o instanceof Error&&"AbortError"===o.name?new BloqueTimeoutError(`Request timeout after ${c}ms`,{timeoutMs:c,cause:o}):o instanceof Error?new BloqueNetworkError(`Request failed: ${o.message}`,{cause:o}):createBloqueError("Unknown error occurred",{code:"UNKNOWN_ERROR"}),l&&p<_&&this.isRetryableError(t)){r=t;let e=this.calculateRetryDelay(p);await this.sleep(e),p++;continue}throw t}}throw r||createBloqueError("Request failed after retries",{code:"MAX_RETRIES_EXCEEDED"})}}for(var __rspack_i in exports.API_BASE_URLS=__webpack_exports__.API_BASE_URLS,exports.BaseClient=__webpack_exports__.BaseClient,exports.BloqueAPIError=__webpack_exports__.BloqueAPIError,exports.BloqueAuthenticationError=__webpack_exports__.BloqueAuthenticationError,exports.BloqueConfigError=__webpack_exports__.BloqueConfigError,exports.BloqueInsufficientFundsError=__webpack_exports__.BloqueInsufficientFundsError,exports.BloqueNetworkError=__webpack_exports__.BloqueNetworkError,exports.BloqueNotFoundError=__webpack_exports__.BloqueNotFoundError,exports.BloqueRateLimitError=__webpack_exports__.BloqueRateLimitError,exports.BloqueTimeoutError=__webpack_exports__.BloqueTimeoutError,exports.BloqueValidationError=__webpack_exports__.BloqueValidationError,exports.DEFAULT_HEADERS=__webpack_exports__.DEFAULT_HEADERS,exports.HttpClient=__webpack_exports__.HttpClient,exports.SUPPORTED_ASSETS=__webpack_exports__.SUPPORTED_ASSETS,exports.createBloqueError=__webpack_exports__.createBloqueError,exports.isSupportedAsset=__webpack_exports__.isSupportedAsset,__webpack_exports__)-1===["API_BASE_URLS","BaseClient","BloqueAPIError","BloqueAuthenticationError","BloqueConfigError","BloqueInsufficientFundsError","BloqueNetworkError","BloqueNotFoundError","BloqueRateLimitError","BloqueTimeoutError","BloqueValidationError","DEFAULT_HEADERS","HttpClient","SUPPORTED_ASSETS","createBloqueError","isSupportedAsset"].indexOf(__rspack_i)&&(exports[__rspack_i]=__webpack_exports__[__rspack_i]);Object.defineProperty(exports,"__esModule",{value:!0});
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
class e{httpClient;constructor(e){this.httpClient=e}}let t={sandbox:"https://api.dev-bloque.app",production:"https://api.bloque.app"},r={"Content-Type":"application/json"},i=["DUSD/6","COPB/6","COPM/2","KSM/12"];function s(e){return i.includes(e)}class o extends Error{status;code;requestId;timestamp;response;cause;constructor(e,t){super(e),this.name="BloqueAPIError",this.status=t?.status,this.code=t?.code,this.requestId=t?.requestId,this.response=t?.response,this.cause=t?.cause,this.timestamp=new Date,Object.setPrototypeOf(this,o.prototype)}toJSON(){return{name:this.name,message:this.message,status:this.status,code:this.code,requestId:this.requestId,timestamp:this.timestamp.toISOString(),response:this.response,stack:this.stack}}}class n extends o{retryAfter;constructor(e,t){super(e,{...t,status:429}),this.name="BloqueRateLimitError",this.retryAfter=t?.retryAfter,Object.setPrototypeOf(this,n.prototype)}toJSON(){return{...super.toJSON(),retryAfter:this.retryAfter}}}class a extends o{constructor(e,t){super(e,t),this.name="BloqueAuthenticationError",Object.setPrototypeOf(this,a.prototype)}}class u extends o{validationErrors;constructor(e,t){super(e,{...t,status:400}),this.name="BloqueValidationError",this.validationErrors=t?.validationErrors,Object.setPrototypeOf(this,u.prototype)}toJSON(){return{...super.toJSON(),validationErrors:this.validationErrors}}}class c extends o{resourceType;resourceId;constructor(e,t){super(e,{...t,status:404}),this.name="BloqueNotFoundError",this.resourceType=t?.resourceType,this.resourceId=t?.resourceId,Object.setPrototypeOf(this,c.prototype)}toJSON(){return{...super.toJSON(),resourceType:this.resourceType,resourceId:this.resourceId}}}class h extends o{requestedAmount;availableBalance;currency;constructor(e,t){super(e,t),this.name="BloqueInsufficientFundsError",this.requestedAmount=t?.requestedAmount,this.availableBalance=t?.availableBalance,this.currency=t?.currency,Object.setPrototypeOf(this,h.prototype)}toJSON(){return{...super.toJSON(),requestedAmount:this.requestedAmount,availableBalance:this.availableBalance,currency:this.currency}}}class l extends o{constructor(e,t){super(e,{...t,code:t?.code??"NETWORK_ERROR"}),this.name="BloqueNetworkError",Object.setPrototypeOf(this,l.prototype)}}class p extends o{timeoutMs;constructor(e,t){super(e,{...t,code:"TIMEOUT_ERROR"}),this.name="BloqueTimeoutError",this.timeoutMs=t?.timeoutMs??0,Object.setPrototypeOf(this,p.prototype)}toJSON(){return{...super.toJSON(),timeoutMs:this.timeoutMs}}}class y extends Error{constructor(e){super(e),this.name="BloqueConfigError",Object.setPrototypeOf(this,y.prototype)}}let d={INSUFFICIENT_FUNDS:h,INSUFFICIENT_BALANCE:h};function f(e,t){let{status:r,code:i}=t??{};if(i&&d[i])return new d[i](e,t);switch(r){case 400:return new u(e,t);case 401:case 403:return new a(e,t);case 404:return new c(e,t);case 429:return new n(e,t);default:return new o(e,t)}}let m="Idempotency-Key",g=new Set(["POST","PUT"]),w=e=>"browser"===e||"react-native"===e;class b{_config;baseUrl;_exchangeExpiry=0;_exchangePromise=null;publicRoutes=["/api/aliases","/api/origins/*/assert","/api/origins/*/connect","/api/origins","/api/api-keys/exchange"];constructor(e){let r={...e};this.validateConfig(r),this._config=r,this.baseUrl=r.baseUrl??t[r.mode??"production"]}get origin(){return this._config.origin}get auth(){return this._config.auth}get urn(){return this._config.urn}get accessToken(){return this._config.accessToken}setAccessToken(e){this._config.accessToken=e}setJwtToken(e){if("jwt"!==this._config.auth.type)throw new y("JWT token can only be set for JWT auth");this._config.tokenStorage?.set(e),this._config.accessToken=e}getJwtToken(){if("jwt"!==this._config.auth.type)throw new y("JWT token is only available for JWT auth");return this._config.tokenStorage?.get()??null}setUrn(e){this._config.urn=e}setOrigin(e){this._config.origin=e}validateConfig(e){if(e.mode??="production",e.platform??="node",e.timeout??=3e4,e.retry??={},e.retry.enabled??=!0,e.retry.maxRetries??=3,e.retry.initialDelay??=1e3,e.retry.maxDelay??=3e4,!["sandbox","production"].includes(e.mode))throw new y('Mode must be either "sandbox" or "production"');if(void 0!==e.timeout&&e.timeout<0)throw new y("Timeout must be a non-negative number");if(void 0!==e.retry.maxRetries&&e.retry.maxRetries<0)throw new y("maxRetries must be a non-negative number");if(void 0!==e.retry.initialDelay&&e.retry.initialDelay<0)throw new y("initialDelay must be a non-negative number");if(void 0!==e.retry.maxDelay&&e.retry.maxDelay<0)throw new y("maxDelay must be a non-negative number");if("apiKey"===e.auth.type){if(!e.auth.apiKey?.trim())throw new y("API key (sk_ secret key) is required for apiKey authentication");if(w(e.platform))throw new y("API key authentication is not allowed in frontend platforms")}if("originKey"===e.auth.type){if(!e.auth.originKey?.trim())throw new y("Origin key is required for originKey authentication");if(!e.origin?.trim())throw new y("Origin is required for originKey authentication");if(w(e.platform))throw new y("Origin key authentication is not allowed in frontend platforms")}if("jwt"===e.auth.type&&"browser"!==e.platform&&!e.tokenStorage)throw new y("tokenStorage must be provided when using JWT authentication outside browser platform")}isPublicRoute(e){let t=e.split("?")[0];return this.publicRoutes.some(e=>{let r=e.replace(/\*/g,"[^/]+");return RegExp(`^${r}$`).test(t)})}buildAuthHeaders(e){if(this.isPublicRoute(e))return{};if("apiKey"===this._config.auth.type)return this._config.accessToken?{Authorization:`Bearer ${this._config.accessToken}`}:{};if("originKey"===this._config.auth.type)return this._config.accessToken?{Authorization:`Bearer ${this._config.accessToken}`}:{Authorization:this._config.auth.originKey};if("jwt"===this._config.auth.type){if("browser"===this._config.platform)return{};let e=this._config.tokenStorage?.get();if(!e)throw new y("Authentication token is missing");return{Authorization:`Bearer ${e}`}}return{}}isRetryableError(e){return e instanceof n||e instanceof l||e instanceof p||e instanceof Error&&"status"in e&&503===e.status}calculateRetryDelay(e,t){let{initialDelay:r=1e3,maxDelay:i=3e4}=this._config.retry??{};if(t){let e=Number.parseInt(t,10);if(!Number.isNaN(e))return Math.min(1e3*e,i);let r=new Date(t);if(!Number.isNaN(r.getTime()))return Math.min(Math.max(r.getTime()-Date.now(),0),i)}let s=r*2**e,o=.25*s*(2*Math.random()-1);return Math.min(s+o,i)}sleep(e){return new Promise(t=>setTimeout(t,e))}generateIdempotencyKey(){return void 0!==globalThis.crypto&&"function"==typeof globalThis.crypto.randomUUID?globalThis.crypto.randomUUID():`idem_${Date.now()}_${Math.random().toString(36).slice(2)}`}isIdempotencyKeyError(e,t){if(409!==e&&400!==e)return!1;let r=`${t.code??""} ${t.message??""}`.toLowerCase().trim();return r.includes("idempotency-key")||r.includes("idempotency key")||r.includes("duplicated idempotency key")}async ensureExchanged(){"apiKey"!==this._config.auth.type||(this._exchangePromise?await this._exchangePromise:this._config.accessToken&&Date.now()<this._exchangeExpiry-6e4||(this._exchangePromise=(async()=>{try{let e=this._config.auth,t=await this.request({method:"POST",path:"/api/api-keys/exchange",body:{key:e.apiKey,scopes:e.scopes},_skipExchange:!0});if(!t.access_token)throw new a("API key exchange returned an invalid response (missing access_token)",{status:401});this._config.accessToken=t.access_token,this._exchangeExpiry=Date.now()+1e3*t.expires_in}finally{this._exchangePromise=null}})(),await this._exchangePromise))}async request(e){let t;"apiKey"!==this._config.auth.type||e._skipExchange||await this.ensureExchanged();let{method:i,path:s,body:o,headers:a={},timeout:u}=e,c=`${this.baseUrl}${s}`,h={...r,...this.buildAuthHeaders(s),...a};g.has(i.toUpperCase())&&(h[m]=h[m]||this.generateIdempotencyKey());let y=void 0!==u?u:this._config.timeout??3e4,{enabled:d=!0,maxRetries:w=3}=this._config.retry??{},b=0;for(;b<=(d?w:0);){let e,r=new AbortController;y>0&&(e=setTimeout(()=>{r.abort()},y));try{let s=await fetch(c,{method:i,headers:h,body:o?JSON.stringify(o):void 0,credentials:"jwt"===this._config.auth.type&&"browser"===this._config.platform?"include":void 0,signal:r.signal});void 0!==e&&clearTimeout(e);let a=await s.json().catch(()=>({}));if(!s.ok){let e=s.headers.get("X-Request-ID")??s.headers.get("Request-ID")??void 0,r=s.headers.get("Retry-After"),i=429===s.status?new n(a.message||"Rate limit exceeded",{status:s.status,code:a.code,requestId:e,response:a,retryAfter:r?Number.parseInt(r,10):void 0}):f(a.message||`HTTP ${s.status}: ${s.statusText}`,{status:s.status,code:a.code,requestId:e,response:a});if(this.isIdempotencyKeyError(s.status,a))throw i;if(d&&b<w&&this.isRetryableError(i)){t=i;let e=this.calculateRetryDelay(b,r??void 0);await this.sleep(e),b++;continue}throw i}return a}catch(i){let r;if(void 0!==e&&clearTimeout(e),i&&"object"==typeof i&&"name"in i&&"string"==typeof i.name&&i.name.startsWith("Bloque")&&!this.isRetryableError(i))throw i;if(r=i instanceof Error&&"AbortError"===i.name?new p(`Request timeout after ${y}ms`,{timeoutMs:y,cause:i}):i instanceof Error?new l(`Request failed: ${i.message}`,{cause:i}):f("Unknown error occurred",{code:"UNKNOWN_ERROR"}),d&&b<w&&this.isRetryableError(r)){t=r;let e=this.calculateRetryDelay(b);await this.sleep(e),b++;continue}throw r}}throw t||f("Request failed after retries",{code:"MAX_RETRIES_EXCEEDED"})}}export{t as API_BASE_URLS,e as BaseClient,o as BloqueAPIError,a as BloqueAuthenticationError,y as BloqueConfigError,h as BloqueInsufficientFundsError,l as BloqueNetworkError,c as BloqueNotFoundError,n as BloqueRateLimitError,p as BloqueTimeoutError,u as BloqueValidationError,r as DEFAULT_HEADERS,b as HttpClient,i as SUPPORTED_ASSETS,f as createBloqueError,s as isSupportedAsset};
|
|
1
|
+
class e{httpClient;constructor(e){this.httpClient=e}}let t={sandbox:"https://api.dev-bloque.app",production:"https://api.bloque.app"},r={"Content-Type":"application/json"},i=["DUSD/6","COPB/6","COPM/2","KSM/12"];function s(e){return i.includes(e)}class o extends Error{status;code;requestId;timestamp;response;cause;constructor(e,t){super(e),this.name="BloqueAPIError",this.status=t?.status,this.code=t?.code,this.requestId=t?.requestId,this.response=t?.response,this.cause=t?.cause,this.timestamp=new Date,Object.setPrototypeOf(this,o.prototype)}toJSON(){return{name:this.name,message:this.message,status:this.status,code:this.code,requestId:this.requestId,timestamp:this.timestamp.toISOString(),response:this.response,stack:this.stack}}}class n extends o{retryAfter;constructor(e,t){super(e,{...t,status:429}),this.name="BloqueRateLimitError",this.retryAfter=t?.retryAfter,Object.setPrototypeOf(this,n.prototype)}toJSON(){return{...super.toJSON(),retryAfter:this.retryAfter}}}class a extends o{constructor(e,t){super(e,t),this.name="BloqueAuthenticationError",Object.setPrototypeOf(this,a.prototype)}}class u extends o{validationErrors;constructor(e,t){super(e,{...t,status:400}),this.name="BloqueValidationError",this.validationErrors=t?.validationErrors,Object.setPrototypeOf(this,u.prototype)}toJSON(){return{...super.toJSON(),validationErrors:this.validationErrors}}}class c extends o{resourceType;resourceId;constructor(e,t){super(e,{...t,status:404}),this.name="BloqueNotFoundError",this.resourceType=t?.resourceType,this.resourceId=t?.resourceId,Object.setPrototypeOf(this,c.prototype)}toJSON(){return{...super.toJSON(),resourceType:this.resourceType,resourceId:this.resourceId}}}class h extends o{requestedAmount;availableBalance;currency;constructor(e,t){super(e,t),this.name="BloqueInsufficientFundsError",this.requestedAmount=t?.requestedAmount,this.availableBalance=t?.availableBalance,this.currency=t?.currency,Object.setPrototypeOf(this,h.prototype)}toJSON(){return{...super.toJSON(),requestedAmount:this.requestedAmount,availableBalance:this.availableBalance,currency:this.currency}}}class l extends o{constructor(e,t){super(e,{...t,code:t?.code??"NETWORK_ERROR"}),this.name="BloqueNetworkError",Object.setPrototypeOf(this,l.prototype)}}class p extends o{timeoutMs;constructor(e,t){super(e,{...t,code:"TIMEOUT_ERROR"}),this.name="BloqueTimeoutError",this.timeoutMs=t?.timeoutMs??0,Object.setPrototypeOf(this,p.prototype)}toJSON(){return{...super.toJSON(),timeoutMs:this.timeoutMs}}}class y extends Error{constructor(e){super(e),this.name="BloqueConfigError",Object.setPrototypeOf(this,y.prototype)}}let d={INSUFFICIENT_FUNDS:h,INSUFFICIENT_BALANCE:h};function f(e,t){let{status:r,code:i}=t??{};if(i&&d[i])return new d[i](e,t);switch(r){case 400:return new u(e,t);case 401:case 403:return new a(e,t);case 404:return new c(e,t);case 429:return new n(e,t);default:return new o(e,t)}}let m="Idempotency-Key",g=new Set(["POST","PUT"]),w=e=>"browser"===e||"react-native"===e;class b{_config;baseUrl;_exchangeExpiry=0;_exchangePromise=null;publicRoutes=["/api/aliases","/api/origins/*/assert","/api/origins/*/connect","/api/origins","/api/api-keys/exchange"];constructor(e){let r={...e};this.validateConfig(r),this._config=r,this.baseUrl=r.baseUrl??t[r.mode??"production"]}get origin(){return this._config.origin}get auth(){return this._config.auth}get urn(){return this._config.urn}get accessToken(){return this._config.accessToken}setAccessToken(e){this._config.accessToken=e}setJwtToken(e){if("jwt"!==this._config.auth.type)throw new y("JWT token can only be set for JWT auth");this._config.tokenStorage?.set(e),this._config.accessToken=e}getJwtToken(){if("jwt"!==this._config.auth.type)throw new y("JWT token is only available for JWT auth");return this._config.tokenStorage?.get()??null}setUrn(e){this._config.urn=e}setOrigin(e){this._config.origin=e}fork(){return new b({...this._config})}validateConfig(e){if(e.mode??="production",e.platform??="node",e.timeout??=3e4,e.retry??={},e.retry.enabled??=!0,e.retry.maxRetries??=3,e.retry.initialDelay??=1e3,e.retry.maxDelay??=3e4,!["sandbox","production"].includes(e.mode))throw new y('Mode must be either "sandbox" or "production"');if(void 0!==e.timeout&&e.timeout<0)throw new y("Timeout must be a non-negative number");if(void 0!==e.retry.maxRetries&&e.retry.maxRetries<0)throw new y("maxRetries must be a non-negative number");if(void 0!==e.retry.initialDelay&&e.retry.initialDelay<0)throw new y("initialDelay must be a non-negative number");if(void 0!==e.retry.maxDelay&&e.retry.maxDelay<0)throw new y("maxDelay must be a non-negative number");if("apiKey"===e.auth.type){if(!e.auth.apiKey?.trim())throw new y("API key (sk_ secret key) is required for apiKey authentication");if(w(e.platform))throw new y("API key authentication is not allowed in frontend platforms")}if("originKey"===e.auth.type){if(!e.auth.originKey?.trim())throw new y("Origin key is required for originKey authentication");if(!e.origin?.trim())throw new y("Origin is required for originKey authentication");if(w(e.platform))throw new y("Origin key authentication is not allowed in frontend platforms")}if("jwt"===e.auth.type&&"browser"!==e.platform&&!e.tokenStorage)throw new y("tokenStorage must be provided when using JWT authentication outside browser platform")}isPublicRoute(e){let t=e.split("?")[0];return this.publicRoutes.some(e=>{let r=e.replace(/\*/g,"[^/]+");return RegExp(`^${r}$`).test(t)})}buildAuthHeaders(e){if(this.isPublicRoute(e))return{};if("apiKey"===this._config.auth.type)return this._config.accessToken?{Authorization:`Bearer ${this._config.accessToken}`}:{};if("originKey"===this._config.auth.type)return this._config.accessToken?{Authorization:`Bearer ${this._config.accessToken}`}:{Authorization:this._config.auth.originKey};if("jwt"===this._config.auth.type){if("browser"===this._config.platform)return{};let e=this._config.tokenStorage?.get();if(!e)throw new y("Authentication token is missing");return{Authorization:`Bearer ${e}`}}return{}}isRetryableError(e){return e instanceof n||e instanceof l||e instanceof p||e instanceof Error&&"status"in e&&503===e.status}calculateRetryDelay(e,t){let{initialDelay:r=1e3,maxDelay:i=3e4}=this._config.retry??{};if(t){let e=Number.parseInt(t,10);if(!Number.isNaN(e))return Math.min(1e3*e,i);let r=new Date(t);if(!Number.isNaN(r.getTime()))return Math.min(Math.max(r.getTime()-Date.now(),0),i)}let s=r*2**e,o=.25*s*(2*Math.random()-1);return Math.min(s+o,i)}sleep(e){return new Promise(t=>setTimeout(t,e))}generateIdempotencyKey(){return void 0!==globalThis.crypto&&"function"==typeof globalThis.crypto.randomUUID?globalThis.crypto.randomUUID():`idem_${Date.now()}_${Math.random().toString(36).slice(2)}`}isIdempotencyKeyError(e,t){if(409!==e&&400!==e)return!1;let r=`${t.code??""} ${t.message??""}`.toLowerCase().trim();return r.includes("idempotency-key")||r.includes("idempotency key")||r.includes("duplicated idempotency key")}async ensureExchanged(){"apiKey"!==this._config.auth.type||(this._exchangePromise?await this._exchangePromise:this._config.accessToken&&Date.now()<this._exchangeExpiry-6e4||(this._exchangePromise=(async()=>{try{let e=this._config.auth,t=await this.request({method:"POST",path:"/api/api-keys/exchange",body:{key:e.apiKey,scopes:e.scopes},_skipExchange:!0});if(!t.access_token)throw new a("API key exchange returned an invalid response (missing access_token)",{status:401});this._config.accessToken=t.access_token,this._exchangeExpiry=Date.now()+1e3*t.expires_in}finally{this._exchangePromise=null}})(),await this._exchangePromise))}async request(e){let t;"apiKey"!==this._config.auth.type||e._skipExchange||await this.ensureExchanged();let{method:i,path:s,body:o,headers:a={},timeout:u}=e,c=`${this.baseUrl}${s}`,h={...r,...this.buildAuthHeaders(s),...a};g.has(i.toUpperCase())&&(h[m]=h[m]||this.generateIdempotencyKey());let y=void 0!==u?u:this._config.timeout??3e4,{enabled:d=!0,maxRetries:w=3}=this._config.retry??{},b=0;for(;b<=(d?w:0);){let e,r=new AbortController;y>0&&(e=setTimeout(()=>{r.abort()},y));try{let s=await fetch(c,{method:i,headers:h,body:o?JSON.stringify(o):void 0,credentials:"jwt"===this._config.auth.type&&"browser"===this._config.platform?"include":void 0,signal:r.signal});void 0!==e&&clearTimeout(e);let a=await s.json().catch(()=>({}));if(!s.ok){let e=s.headers.get("X-Request-ID")??s.headers.get("Request-ID")??void 0,r=s.headers.get("Retry-After"),i=429===s.status?new n(a.message||"Rate limit exceeded",{status:s.status,code:a.code,requestId:e,response:a,retryAfter:r?Number.parseInt(r,10):void 0}):f(a.message||`HTTP ${s.status}: ${s.statusText}`,{status:s.status,code:a.code,requestId:e,response:a});if(this.isIdempotencyKeyError(s.status,a))throw i;if(d&&b<w&&this.isRetryableError(i)){t=i;let e=this.calculateRetryDelay(b,r??void 0);await this.sleep(e),b++;continue}throw i}return a}catch(i){let r;if(void 0!==e&&clearTimeout(e),i&&"object"==typeof i&&"name"in i&&"string"==typeof i.name&&i.name.startsWith("Bloque")&&!this.isRetryableError(i))throw i;if(r=i instanceof Error&&"AbortError"===i.name?new p(`Request timeout after ${y}ms`,{timeoutMs:y,cause:i}):i instanceof Error?new l(`Request failed: ${i.message}`,{cause:i}):f("Unknown error occurred",{code:"UNKNOWN_ERROR"}),d&&b<w&&this.isRetryableError(r)){t=r;let e=this.calculateRetryDelay(b);await this.sleep(e),b++;continue}throw r}}throw t||f("Request failed after retries",{code:"MAX_RETRIES_EXCEEDED"})}}export{t as API_BASE_URLS,e as BaseClient,o as BloqueAPIError,a as BloqueAuthenticationError,y as BloqueConfigError,h as BloqueInsufficientFundsError,l as BloqueNetworkError,c as BloqueNotFoundError,n as BloqueRateLimitError,p as BloqueTimeoutError,u as BloqueValidationError,r as DEFAULT_HEADERS,b as HttpClient,i as SUPPORTED_ASSETS,f as createBloqueError,s as isSupportedAsset};
|