@stacks/common
Advanced tools
Comparing version 7.0.3-pr.1 to 7.0.3-pr.2
export declare const getFetchOptions: () => RequestInit; | ||
export declare const setFetchOptions: (ops: RequestInit) => RequestInit; | ||
export declare function fetchWrapper(input: RequestInfo, init?: RequestInit): Promise<Response>; | ||
export type FetchFn = (url: string, init?: RequestInit) => Promise<Response>; | ||
export declare function fetchWrapper(input: RequestInfo | URL, init?: RequestInit): Promise<Response>; | ||
export type FetchFn = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>; | ||
export interface ClientOpts { | ||
@@ -15,2 +15,3 @@ baseUrl?: string; | ||
url: string; | ||
input: RequestInfo | URL; | ||
init: RequestInit; | ||
@@ -21,2 +22,3 @@ } | ||
url: string; | ||
input: RequestInfo | URL; | ||
init: RequestInit; | ||
@@ -29,4 +31,8 @@ response: Response; | ||
} | ||
export interface FetchArgs { | ||
input: RequestInfo | URL; | ||
init?: RequestInit; | ||
} | ||
export interface FetchMiddleware { | ||
pre?: (context: RequestContext) => PromiseLike<FetchParams | void> | FetchParams | void; | ||
pre?: (context: RequestContext) => PromiseLike<FetchParams | FetchArgs | void> | FetchParams | FetchArgs | void; | ||
post?: (context: ResponseContext) => Promise<Response | void> | Response | void; | ||
@@ -41,3 +47,3 @@ } | ||
export declare function createApiKeyMiddleware({ apiKey, host, httpHeader, }: ApiKeyMiddlewareOpts): FetchMiddleware; | ||
export declare function createFetchFn(fetchLib: FetchFn, ...middleware: FetchMiddleware[]): FetchFn; | ||
export declare function createFetchFn(fetchFn: FetchFn, ...middleware: FetchMiddleware[]): FetchFn; | ||
export declare function createFetchFn(...middleware: FetchMiddleware[]): FetchFn; |
@@ -38,32 +38,35 @@ const defaultFetchOpts = { | ||
function argsForCreateFetchFn(args) { | ||
let fetchLib = fetchWrapper; | ||
let middlewares = []; | ||
if (args.length > 0 && typeof args[0] === 'function') { | ||
fetchLib = args.shift(); | ||
if (typeof args[0] === 'function') { | ||
return { | ||
fetch: args.shift(), | ||
middlewares: args, | ||
}; | ||
} | ||
if (args.length > 0) { | ||
middlewares = args; | ||
} | ||
return { fetchLib, middlewares }; | ||
return { fetch: fetchWrapper, middlewares: args }; | ||
} | ||
export function createFetchFn(...args) { | ||
const { fetchLib, middlewares } = argsForCreateFetchFn(args); | ||
const fetchFn = async (url, init) => { | ||
let fetchParams = { url, init: init ?? {} }; | ||
const { fetch, middlewares } = argsForCreateFetchFn(args); | ||
const fetchFn = async (input, init) => { | ||
let fetchParams = { input, init: init ?? {} }; | ||
for (const middleware of middlewares) { | ||
if (typeof middleware.pre === 'function') { | ||
const result = await Promise.resolve(middleware.pre({ | ||
fetch: fetchLib, | ||
...fetchParams, | ||
fetch, | ||
url: fetchParams.input, | ||
input: fetchParams.input, | ||
init: fetchParams.init ?? {}, | ||
})); | ||
if (result && 'url' in result) | ||
result.input = result.url; | ||
fetchParams = result ?? fetchParams; | ||
} | ||
} | ||
let response = await fetchLib(fetchParams.url, fetchParams.init); | ||
let response = await fetch(fetchParams.input, fetchParams.init); | ||
for (const middleware of middlewares) { | ||
if (typeof middleware.post === 'function') { | ||
const result = await Promise.resolve(middleware.post({ | ||
fetch: fetchLib, | ||
url: fetchParams.url, | ||
init: fetchParams.init, | ||
fetch, | ||
url: fetchParams.input, | ||
input: fetchParams.input, | ||
init: fetchParams.init ?? {}, | ||
response: response?.clone() ?? response, | ||
@@ -70,0 +73,0 @@ })); |
export declare const getFetchOptions: () => RequestInit; | ||
export declare const setFetchOptions: (ops: RequestInit) => RequestInit; | ||
export declare function fetchWrapper(input: RequestInfo, init?: RequestInit): Promise<Response>; | ||
export type FetchFn = (url: string, init?: RequestInit) => Promise<Response>; | ||
export declare function fetchWrapper(input: RequestInfo | URL, init?: RequestInit): Promise<Response>; | ||
export type FetchFn = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>; | ||
export interface ClientOpts { | ||
@@ -15,2 +15,3 @@ baseUrl?: string; | ||
url: string; | ||
input: RequestInfo | URL; | ||
init: RequestInit; | ||
@@ -21,2 +22,3 @@ } | ||
url: string; | ||
input: RequestInfo | URL; | ||
init: RequestInit; | ||
@@ -29,4 +31,8 @@ response: Response; | ||
} | ||
export interface FetchArgs { | ||
input: RequestInfo | URL; | ||
init?: RequestInit; | ||
} | ||
export interface FetchMiddleware { | ||
pre?: (context: RequestContext) => PromiseLike<FetchParams | void> | FetchParams | void; | ||
pre?: (context: RequestContext) => PromiseLike<FetchParams | FetchArgs | void> | FetchParams | FetchArgs | void; | ||
post?: (context: ResponseContext) => Promise<Response | void> | Response | void; | ||
@@ -41,3 +47,3 @@ } | ||
export declare function createApiKeyMiddleware({ apiKey, host, httpHeader, }: ApiKeyMiddlewareOpts): FetchMiddleware; | ||
export declare function createFetchFn(fetchLib: FetchFn, ...middleware: FetchMiddleware[]): FetchFn; | ||
export declare function createFetchFn(fetchFn: FetchFn, ...middleware: FetchMiddleware[]): FetchFn; | ||
export declare function createFetchFn(...middleware: FetchMiddleware[]): FetchFn; |
@@ -46,32 +46,35 @@ "use strict"; | ||
function argsForCreateFetchFn(args) { | ||
let fetchLib = fetchWrapper; | ||
let middlewares = []; | ||
if (args.length > 0 && typeof args[0] === 'function') { | ||
fetchLib = args.shift(); | ||
if (typeof args[0] === 'function') { | ||
return { | ||
fetch: args.shift(), | ||
middlewares: args, | ||
}; | ||
} | ||
if (args.length > 0) { | ||
middlewares = args; | ||
} | ||
return { fetchLib, middlewares }; | ||
return { fetch: fetchWrapper, middlewares: args }; | ||
} | ||
function createFetchFn(...args) { | ||
const { fetchLib, middlewares } = argsForCreateFetchFn(args); | ||
const fetchFn = async (url, init) => { | ||
let fetchParams = { url, init: init ?? {} }; | ||
const { fetch, middlewares } = argsForCreateFetchFn(args); | ||
const fetchFn = async (input, init) => { | ||
let fetchParams = { input, init: init ?? {} }; | ||
for (const middleware of middlewares) { | ||
if (typeof middleware.pre === 'function') { | ||
const result = await Promise.resolve(middleware.pre({ | ||
fetch: fetchLib, | ||
...fetchParams, | ||
fetch, | ||
url: fetchParams.input, | ||
input: fetchParams.input, | ||
init: fetchParams.init ?? {}, | ||
})); | ||
if (result && 'url' in result) | ||
result.input = result.url; | ||
fetchParams = result ?? fetchParams; | ||
} | ||
} | ||
let response = await fetchLib(fetchParams.url, fetchParams.init); | ||
let response = await fetch(fetchParams.input, fetchParams.init); | ||
for (const middleware of middlewares) { | ||
if (typeof middleware.post === 'function') { | ||
const result = await Promise.resolve(middleware.post({ | ||
fetch: fetchLib, | ||
url: fetchParams.url, | ||
init: fetchParams.init, | ||
fetch, | ||
url: fetchParams.input, | ||
input: fetchParams.input, | ||
init: fetchParams.init ?? {}, | ||
response: response?.clone() ?? response, | ||
@@ -78,0 +81,0 @@ })); |
@@ -1,2 +0,2 @@ | ||
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.StacksCommon=t():e.StacksCommon=t()}(this,(()=>(()=>{"use strict";var e={142:(e,t,r)=>{function n(e,t){if(e.byteLength!==t.byteLength)return!1;for(let r=0;r<e.byteLength;r++)if(e[r]!==t[r])return!1;return!0}function o(e,t){const r=new Uint8Array(e);for(let n=0;n<e;n++)r[n]=t;return r}function s(e,t){return(e[t+0]<<8|e[t+1])>>>0}function i(e,t,r=0){return e[r+0]=t>>>8,e[r+1]=t>>>0,e}function a(e,t){return e[t]}function c(e,t,r=0){return e[r]=t,e}function u(e,t){return e[t+0]<<0>>>0|e[t+1]<<8>>>0}function l(e,t,r=0){return e[r+0]=255&t,t>>>=8,e[r+1]=255&t,e}function g(e,t){return e[t]*2**24+65536*e[t+1]+256*e[t+2]+e[t+3]}function f(e,t,r=0){return e[r+3]=t,t>>>=8,e[r+2]=t,t>>>=8,e[r+1]=t,t>>>=8,e[r]=t,e}function d(e,t){return e[t+0]<<0>>>0|e[t+1]<<8>>>0|e[t+2]<<16>>>0|e[t+3]<<24>>>0}function h(e,t,r=0){return e[r+0]=255&t,t>>>=8,e[r+1]=255&t,t>>>=8,e[r+2]=255&t,t>>>=8,e[r+3]=255&t,e}r.d(t,{Ag:()=>g,Cg:()=>c,Q$:()=>a,T4:()=>f,cQ:()=>i,fS:()=>n,mP:()=>u,n8:()=>s,nm:()=>d,oq:()=>l,un:()=>o,v7:()=>h})},392:(e,t,r)=>{r.d(t,{v:()=>n});const n={network:{layer1:"placeholder"},logLevel:"debug"}},902:(e,t,r)=>{r.d(t,{IE:()=>o,Mh:()=>c,fg:()=>n,it:()=>s,lW:()=>i,sQ:()=>a});const n="https://api.mainnet.hiro.so",o="https://api.testnet.hiro.so",s="http://localhost:3999",i="https://hub.blockstack.org",a=33,c=32},889:(e,t,r)=>{r.d(t,{AI:()=>I,AY:()=>y,Ev:()=>u,Fe:()=>E,Ie:()=>b,JU:()=>m,M4:()=>h,O1:()=>n,Ru:()=>R,Y0:()=>f,hy:()=>a,jO:()=>s,kn:()=>c,oO:()=>p,p8:()=>_,sk:()=>o,ur:()=>T,v0:()=>i,vP:()=>d,xE:()=>l,zd:()=>g});const n={MISSING_PARAMETER:"missing_parameter",REMOTE_SERVICE_ERROR:"remote_service_error",INVALID_STATE:"invalid_state",NO_SESSION_DATA:"no_session_data",DOES_NOT_EXIST:"does_not_exist",FAILED_DECRYPTION_ERROR:"failed_decryption_error",INVALID_DID_ERROR:"invalid_did_error",NOT_ENOUGH_FUNDS_ERROR:"not_enough_error",INVALID_AMOUNT_ERROR:"invalid_amount_error",LOGIN_FAILED_ERROR:"login_failed",SIGNATURE_VERIFICATION_ERROR:"signature_verification_failure",CONFLICT_ERROR:"conflict_error",NOT_ENOUGH_PROOF_ERROR:"not_enough_proof_error",BAD_PATH_ERROR:"bad_path_error",VALIDATION_ERROR:"validation_error",PAYLOAD_TOO_LARGE_ERROR:"payload_too_large_error",PRECONDITION_FAILED_ERROR:"precondition_failed_error",UNKNOWN:"unknown"};Object.freeze(n);class o extends Error{constructor(e){super();let t=e.message,r=`Error Code: ${e.code}`,n=this.stack;if(n)r+=`Stack Trace:\n${n}`;else try{throw new Error}catch(e){n=e.stack}t+=`\nIf you believe this exception is caused by a bug in stacks.js,\n please file a bug report: https://github.com/blockstack/stacks.js/issues\n\n${r}`,this.message=t,this.code=e.code,this.parameter=e.parameter?e.parameter:void 0}toString(){return`${super.toString()}\n code: ${this.code} param: ${this.parameter?this.parameter:"n/a"}`}}class s extends o{constructor(e,t=""){super({code:n.MISSING_PARAMETER,message:t,parameter:e}),this.name="MissingParametersError"}}class i extends o{constructor(e,t=""){super({code:n.MISSING_PARAMETER,message:t,parameter:e}),this.name="MissingParametersError"}}class a extends o{constructor(e,t=""){super({code:n.REMOTE_SERVICE_ERROR,message:t}),this.response=e}}class c extends o{constructor(e=""){super({code:n.INVALID_DID_ERROR,message:e}),this.name="InvalidDIDError"}}class u extends o{constructor(e){const t=`Not enough UTXOs to fund. Left to fund: ${e}`;super({code:n.NOT_ENOUGH_FUNDS_ERROR,message:t}),this.leftToFund=e,this.name="NotEnoughFundsError",this.message=t}}class l extends o{constructor(e,t){const r=`Not enough coin to fund fees transaction fees. Fees would be ${e}, specified spend is ${t}`;super({code:n.INVALID_AMOUNT_ERROR,message:r}),this.specifiedAmount=t,this.fees=e,this.name="InvalidAmountError",this.message=r}}class g extends o{constructor(e){const t=`Failed to login: ${e}`;super({code:n.LOGIN_FAILED_ERROR,message:t}),this.message=t,this.name="LoginFailedError"}}class f extends o{constructor(e){const t=`Failed to verify signature: ${e}`;super({code:n.SIGNATURE_VERIFICATION_ERROR,message:t}),this.message=t,this.name="SignatureVerificationError"}}class d extends o{constructor(e="Unable to decrypt cipher object."){super({code:n.FAILED_DECRYPTION_ERROR,message:e}),this.message=e,this.name="FailedDecryptionError"}}class h extends o{constructor(e){super({code:n.INVALID_STATE,message:e}),this.message=e,this.name="InvalidStateError"}}class E extends o{constructor(e){super({code:n.INVALID_STATE,message:e}),this.message=e,this.name="NoSessionDataError"}}class p extends o{constructor(e,t){super(e),t&&(this.hubError={statusCode:t.status,statusText:t.statusText},"string"==typeof t.body?this.hubError.message=t.body:"object"==typeof t.body&&Object.assign(this.hubError,t.body))}}class I extends p{constructor(e,t){super({message:e,code:n.DOES_NOT_EXIST},t),this.name="DoesNotExist"}}class y extends p{constructor(e,t){super({message:e,code:n.CONFLICT_ERROR},t),this.name="ConflictError"}}class m extends p{constructor(e,t){super({message:e,code:n.NOT_ENOUGH_PROOF_ERROR},t),this.name="NotEnoughProofError"}}class R extends p{constructor(e,t){super({message:e,code:n.BAD_PATH_ERROR},t),this.name="BadPathError"}}class _ extends p{constructor(e,t){super({message:e,code:n.VALIDATION_ERROR},t),this.name="ValidationError"}}class b extends p{constructor(e,t,r){super({message:e,code:n.PAYLOAD_TOO_LARGE_ERROR},t),this.name="PayloadTooLargeError",this.maxUploadByteSize=r}}class T extends p{constructor(e,t){super({message:e,code:n.PRECONDITION_FAILED_ERROR},t),this.name="PreconditionFailedError"}}},436:(e,t,r)=>{r.d(t,{O6:()=>l,eA:()=>E,h$:()=>d,hM:()=>f,i$:()=>g,jX:()=>h});var n=Object.defineProperty,o=Object.getOwnPropertySymbols,s=Object.prototype.hasOwnProperty,i=Object.prototype.propertyIsEnumerable,a=(e,t,r)=>t in e?n(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,c=(e,t)=>{for(var r in t||(t={}))s.call(t,r)&&a(e,r,t[r]);if(o)for(var r of o(t))i.call(t,r)&&a(e,r,t[r]);return e};const u={referrerPolicy:"origin",headers:{"x-hiro-product":"stacksjs"}},l=()=>u,g=e=>Object.assign(u,e);async function f(e,t){const r={};return Object.assign(r,u,t),await fetch(e,r)}function d(e,t){return"string"==typeof t?t===e:t.exec(e)}function h({apiKey:e,host:t=/(.*)api(.*)(\.stacks\.co|\.hiro\.so)$/i,httpHeader:r="x-api-key"}){return{pre:n=>{d(new URL(n.url).host,t)&&(n.init.headers instanceof Headers?n.init.headers:n.init.headers=new Headers(n.init.headers)).set(r,e)}}}function E(...e){const{fetchLib:t,middlewares:r}=function(e){let t=f,r=[];return e.length>0&&"function"==typeof e[0]&&(t=e.shift()),e.length>0&&(r=e),{fetchLib:t,middlewares:r}}(e);return async(e,n)=>{var o;let s={url:e,init:null!=n?n:{}};for(const e of r)if("function"==typeof e.pre){const r=await Promise.resolve(e.pre(c({fetch:t},s)));s=null!=r?r:s}let i=await t(s.url,s.init);for(const e of r)if("function"==typeof e.post){const r=await Promise.resolve(e.post({fetch:t,url:s.url,init:s.init,response:null!=(o=null==i?void 0:i.clone())?o:i}));i=null!=r?r:i}return i}}},631:(e,t,r)=>{r.d(t,{z:()=>o});var n=r(788);function o(e){const t="string"==typeof e?(0,n.nr)(e):e;if(32!=t.length&&33!=t.length)throw new Error(`Improperly formatted private-key. Private-key byte length should be 32 or 33. Length provided: ${t.length}`);if(33==t.length&&1!==t[32])throw new Error("Improperly formatted private-key. 33 bytes indicate compressed key, but the last byte must be == 01");return t}},976:(e,t,r)=>{r.d(t,{Y:()=>a});var n=r(392);const o=["debug","info","warn","error","none"],s={},i={};for(let e=0;e<o.length;e++){const t=o[e];s[t]=e,i[e]=t}class a{static error(e){this.shouldLog("error")&&console.error(this.logMessage("error",e))}static warn(e){this.shouldLog("warn")&&console.warn(this.logMessage("warn",e))}static info(e){this.shouldLog("info")&&console.log(this.logMessage("info",e))}static debug(e){this.shouldLog("debug")&&console.log(this.logMessage("debug",e))}static logMessage(e,t){return`[${e.toUpperCase()}] ${t}`}static shouldLog(e){return s[n.v.logLevel]<=s[e]}}},225:(e,t,r)=>{r.d(t,{U8:()=>a,ph:()=>i,xP:()=>s});var n=r(788);const o=32;function s(e){if(e.length<2*o*2+1)throw new Error("Invalid signature");const t=e.slice(0,2),r=e.slice(2,2+2*o),s=e.slice(2+2*o);return{recoveryId:(0,n.WR)(t),r,s}}function i(e){return e.slice(2)+e.slice(0,2)}function a(e){return e.slice(-2)+e.slice(0,-2)}},59:()=>{},788:(e,t,r)=>{r.d(t,{$O:()=>k,$g:()=>_,$j:()=>A,A5:()=>y,GW:()=>g,HN:()=>R,I4:()=>O,Md:()=>B,NA:()=>F,NJ:()=>s,QD:()=>P,Qs:()=>$,Rf:()=>I,T7:()=>V,WR:()=>w,WT:()=>u,WW:()=>C,Xt:()=>c,_Y:()=>N,at:()=>b,cG:()=>a,ci:()=>L,cn:()=>v,eV:()=>j,gS:()=>d,iY:()=>D,jk:()=>x,ko:()=>h,lW:()=>E,nD:()=>i,nr:()=>U,ru:()=>l,sO:()=>m,se:()=>f,y_:()=>T,ym:()=>o});var n=r(976);const o="blockstack";function s(){return new Date((new Date).setFullYear((new Date).getFullYear()+1))}function i(){return new Date((new Date).setMonth((new Date).getMonth()+1))}function a(){return new Date((new Date).setHours((new Date).getHours()+1))}function c(e){return Number.isFinite(e)?Math.floor(1024*e*1024):0}function u(e){return 16*(Math.floor(e/16)+1)}function l(e){return 4*Math.ceil(e/3)}function g(e,t,r){const n=new RegExp(`([?&])${t}=.*?(&|$)`,"i"),o=-1!==e.indexOf("?")?"&":"?";return e.match(n)?e.replace(n,`$1${t}=${r}$2`):`${e}${o}${t}=${r}`}function f(e,t){void 0!==e&&""!==e||(e="0.0.0"),void 0!==t&&""!==e||(t="0.0.0");const r=e.split(".").map((e=>parseInt(e,10))),n=t.split(".").map((e=>parseInt(e,10)));for(let o=0;o<t.length;o++)if(o>=e.length&&n.push(0),r[o]<n[o])return!1;return!0}function d(){let e=(new Date).getTime();return"undefined"!=typeof performance&&"function"==typeof performance.now&&(e+=performance.now()),"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(t=>{const r=(e+16*Math.random())%16|0;return e=Math.floor(e/16),("x"===t?r:3&r|8).toString(16)}))}function h(e,t){try{const r=new URL(e),n=new URL(t),o=0|parseInt(r.port||"0",10)||("https:"===r.protocol?443:80),s=0|parseInt(n.port||"0",10)||("https:"===n.protocol?443:80),i={scheme:r.protocol===n.protocol,hostname:r.hostname===n.hostname,port:o===s,absolute:(e.includes("http://")||e.includes("https://"))&&(t.includes("http://")||t.includes("https://"))};return i.scheme&&i.hostname&&i.port&&i.absolute}catch(e){return console.log(e),console.log("Parsing error in same URL origin check"),!1}}function E(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if(void 0!==r.g)return r.g;throw new Error("Unexpected runtime environment - no supported global scope (`window`, `self`, `global`) available")}function p(e,t,r){return r?`Use of '${r}' requires \`${t}\` which is unavailable on the '${e}' object within the currently executing environment.`:`\`${t}\` is unavailable on the '${e}' object within the currently executing environment.`}function I(e,{throwIfUnavailable:t,usageDesc:r,returnEmptyObject:o}={}){let s;try{if(s=E(),s){const t=s[e];if(t)return t}}catch(t){n.Y.error(`Error getting object '${e}' from global scope '${s}': ${t}`)}if(t){const t=p(s,e.toString(),r);throw n.Y.error(t),new Error(t)}if(o)return{}}function y(e,{throwIfUnavailable:t,usageDesc:r,returnEmptyObject:o}={}){let s;try{s=E()}catch(i){if(n.Y.error(`Error getting global scope: ${i}`),t){const t=p(s,e[0].toString(),r);throw n.Y.error(t),t}o&&(s={})}const i={};for(let a=0;a<e.length;a++){const c=e[a];try{if(s){const e=s[c];if(e)i[c]=e;else{if(t){const e=p(s,c.toString(),r);throw n.Y.error(e),new Error(e)}o&&(i[c]={})}}}catch(e){if(t){const e=p(s,c.toString(),r);throw n.Y.error(e),new Error(e)}}}return i}function m(e,t){return x(R(e),t)}function R(e){if("bigint"==typeof e)return e;if("string"==typeof e)return BigInt(e);if("number"==typeof e){if(!Number.isInteger(e))throw new RangeError("Invalid value. Values of type 'number' must be an integer.");if(e>Number.MAX_SAFE_INTEGER)throw new RangeError(`Invalid value. Values of type 'number' must be less than or equal to ${Number.MAX_SAFE_INTEGER}. For larger values, try using a BigInt instead.`);return BigInt(e)}if(k(e,Uint8Array))return BigInt(`0x${L(e)}`);throw new TypeError("intToBigInt: Invalid value type. Must be a number, bigint, BigInt-compatible string, or Uint8Array.")}function _(e){return/^0x/i.test(e)?e:`0x${e}`}function b(e){return/^0x/i.test(e)?e.slice(2):e}function T(e){if("string"!=typeof e)throw new TypeError("hexToBigInt: expected string, got "+typeof e);return BigInt(`0x${e}`)}function O(e,t=8){return("bigint"==typeof e?e:R(e)).toString(16).padStart(2*t,"0")}function w(e){return parseInt(e,16)}function x(e,t=16){return U(O(e,t))}function A(e,t){if(e<-(BigInt(1)<<t-BigInt(1))||(BigInt(1)<<t-BigInt(1))-BigInt(1)<e)throw`Unable to represent integer in width: ${t}`;return e>=BigInt(0)?BigInt(e):e+(BigInt(1)<<t)}function v(e){return N(BigInt(`0x${L(e)}`),BigInt(8*e.byteLength))}function N(e,t){return function(e,t){return e&BigInt(1)<<t}(e,t-BigInt(1))?e-(BigInt(1)<<t):e}const S=Array.from({length:256},((e,t)=>t.toString(16).padStart(2,"0")));function L(e){if(!(e instanceof Uint8Array))throw new Error("Uint8Array expected");let t="";for(const r of e)t+=S[r];return t}function U(e){if("string"!=typeof e)throw new TypeError("hexToBytes: expected string, got "+typeof e);e=(e=b(e)).length%2?`0${e}`:e;const t=new Uint8Array(e.length/2);for(let r=0;r<t.length;r++){const n=2*r,o=e.slice(n,n+2),s=Number.parseInt(o,16);if(Number.isNaN(s)||s<0)throw new Error("Invalid byte sequence");t[r]=s}return t}function D(e){return(new TextEncoder).encode(e)}function B(e){return(new TextDecoder).decode(e)}function P(e){const t=[];for(let r=0;r<e.length;r++)t.push(255&e.charCodeAt(r));return new Uint8Array(t)}function $(e){return String.fromCharCode.apply(null,e)}function M(e){return!Number.isInteger(e)||e<0||e>255}function F(e){if(e.some(M))throw new Error("Some values are invalid bytes.");return new Uint8Array(e)}function j(...e){if(!e.every((e=>e instanceof Uint8Array)))throw new Error("Uint8Array list expected");if(1===e.length)return e[0];const t=e.reduce(((e,t)=>e+t.length),0),r=new Uint8Array(t);for(let t=0,n=0;t<e.length;t++){const o=e[t];r.set(o,n),n+=o.length}return r}function C(e){return j(...e.map((e=>"number"==typeof e?F([e]):e instanceof Array?F(e):e)))}function k(e,t){var r,n;return e instanceof t||(null==(n=null==(r=null==e?void 0:e.constructor)?void 0:r.name)?void 0:n.toLowerCase())===t.name}function V(e){return 64===(e=b(e)).length&&/^[0-9a-fA-F]+$/.test(e)}}},t={};function r(n){var o=t[n];if(void 0!==o)return o.exports;var s=t[n]={exports:{}};return e[n](s,s.exports,r),s.exports}r.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return r.d(t,{a:t}),t},r.d=(e,t)=>{for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var n={};return(()=>{r.r(n),r.d(n,{BLOCKSTACK_HANDLER:()=>s.ym,BadPathError:()=>t.Ru,BlockstackError:()=>t.sk,ConflictError:()=>t.AY,DEVNET_URL:()=>i.it,DoesNotExist:()=>t.AI,ERROR_CODES:()=>t.O1,FailedDecryptionError:()=>t.vP,GAIA_URL:()=>i.lW,GaiaHubError:()=>t.oO,HIRO_MAINNET_URL:()=>i.fg,HIRO_TESTNET_URL:()=>i.IE,InvalidAmountError:()=>t.xE,InvalidDIDError:()=>t.kn,InvalidParameterError:()=>t.jO,InvalidStateError:()=>t.M4,Logger:()=>o.Y,LoginFailedError:()=>t.zd,MissingParameterError:()=>t.v0,NoSessionDataError:()=>t.Fe,NotEnoughFundsError:()=>t.Ev,NotEnoughProofError:()=>t.JU,PRIVATE_KEY_BYTES_COMPRESSED:()=>i.sQ,PRIVATE_KEY_BYTES_UNCOMPRESSED:()=>i.Mh,PayloadTooLargeError:()=>t.Ie,PreconditionFailedError:()=>t.ur,RemoteServiceError:()=>t.hy,SignatureVerificationError:()=>t.Y0,ValidationError:()=>t.p8,alloc:()=>u.un,asciiToBytes:()=>s.QD,bigIntToBytes:()=>s.jk,bytesToAscii:()=>s.Qs,bytesToHex:()=>s.ci,bytesToTwosBigInt:()=>s.cn,bytesToUtf8:()=>s.Md,concatArray:()=>s.WW,concatBytes:()=>s.eV,config:()=>e.v,createApiKeyMiddleware:()=>f.jX,createFetchFn:()=>f.eA,equals:()=>u.fS,fetchWrapper:()=>f.hM,fromTwos:()=>s._Y,getAesCbcOutputLength:()=>s.WT,getBase64OutputLength:()=>s.ru,getFetchOptions:()=>f.O6,getGlobalObject:()=>s.Rf,getGlobalObjects:()=>s.A5,getGlobalScope:()=>s.lW,hexToBigInt:()=>s.y_,hexToBytes:()=>s.nr,hexToInt:()=>s.WR,hostMatches:()=>f.h$,intToBigInt:()=>s.HN,intToBytes:()=>s.sO,intToHex:()=>s.I4,isInstance:()=>s.$O,isLaterVersion:()=>s.se,isSameOriginAbsoluteUrl:()=>s.ko,makeUUID4:()=>s.gS,megabytesToBytes:()=>s.Xt,nextHour:()=>s.cG,nextMonth:()=>s.nD,nextYear:()=>s.NJ,octetsToBytes:()=>s.NA,parseRecoverableSignatureVrs:()=>a.xP,privateKeyToBytes:()=>c.z,readUInt16BE:()=>u.n8,readUInt16LE:()=>u.mP,readUInt32BE:()=>u.Ag,readUInt32LE:()=>u.nm,readUInt8:()=>u.Q$,setFetchOptions:()=>f.i$,signatureRsvToVrs:()=>a.U8,signatureVrsToRsv:()=>a.ph,toTwos:()=>s.$j,updateQueryStringParameter:()=>s.GW,utf8ToBytes:()=>s.iY,validateHash256:()=>s.T7,with0x:()=>s.$g,without0x:()=>s.at,writeUInt16BE:()=>u.cQ,writeUInt16LE:()=>u.oq,writeUInt32BE:()=>u.T4,writeUInt32LE:()=>u.v7,writeUInt8:()=>u.Cg});var e=r(392),t=r(889),o=r(976),s=r(788),i=r(902),a=r(225),c=r(631),u=r(142),l=r(59),g={};for(const e in l)["default","config","BadPathError","BlockstackError","ConflictError","DoesNotExist","ERROR_CODES","FailedDecryptionError","GaiaHubError","InvalidAmountError","InvalidDIDError","InvalidParameterError","InvalidStateError","LoginFailedError","MissingParameterError","NoSessionDataError","NotEnoughFundsError","NotEnoughProofError","PayloadTooLargeError","PreconditionFailedError","RemoteServiceError","SignatureVerificationError","ValidationError","Logger","BLOCKSTACK_HANDLER","asciiToBytes","bigIntToBytes","bytesToAscii","bytesToHex","bytesToTwosBigInt","bytesToUtf8","concatArray","concatBytes","fromTwos","getAesCbcOutputLength","getBase64OutputLength","getGlobalObject","getGlobalObjects","getGlobalScope","hexToBigInt","hexToBytes","hexToInt","intToBigInt","intToBytes","intToHex","isInstance","isLaterVersion","isSameOriginAbsoluteUrl","makeUUID4","megabytesToBytes","nextHour","nextMonth","nextYear","octetsToBytes","toTwos","updateQueryStringParameter","utf8ToBytes","validateHash256","with0x","without0x","DEVNET_URL","GAIA_URL","HIRO_MAINNET_URL","HIRO_TESTNET_URL","PRIVATE_KEY_BYTES_COMPRESSED","PRIVATE_KEY_BYTES_UNCOMPRESSED","parseRecoverableSignatureVrs","signatureRsvToVrs","signatureVrsToRsv","privateKeyToBytes","alloc","equals","readUInt16BE","readUInt16LE","readUInt32BE","readUInt32LE","readUInt8","writeUInt16BE","writeUInt16LE","writeUInt32BE","writeUInt32LE","writeUInt8"].indexOf(e)<0&&(g[e]=()=>l[e]);r.d(n,g);var f=r(436)})(),n})())); | ||
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.StacksCommon=t():e.StacksCommon=t()}(this,(()=>(()=>{"use strict";var e={142:(e,t,r)=>{function n(e,t){if(e.byteLength!==t.byteLength)return!1;for(let r=0;r<e.byteLength;r++)if(e[r]!==t[r])return!1;return!0}function o(e,t){const r=new Uint8Array(e);for(let n=0;n<e;n++)r[n]=t;return r}function s(e,t){return(e[t+0]<<8|e[t+1])>>>0}function i(e,t,r=0){return e[r+0]=t>>>8,e[r+1]=t>>>0,e}function a(e,t){return e[t]}function c(e,t,r=0){return e[r]=t,e}function u(e,t){return e[t+0]<<0>>>0|e[t+1]<<8>>>0}function l(e,t,r=0){return e[r+0]=255&t,t>>>=8,e[r+1]=255&t,e}function g(e,t){return e[t]*2**24+65536*e[t+1]+256*e[t+2]+e[t+3]}function d(e,t,r=0){return e[r+3]=t,t>>>=8,e[r+2]=t,t>>>=8,e[r+1]=t,t>>>=8,e[r]=t,e}function f(e,t){return e[t+0]<<0>>>0|e[t+1]<<8>>>0|e[t+2]<<16>>>0|e[t+3]<<24>>>0}function h(e,t,r=0){return e[r+0]=255&t,t>>>=8,e[r+1]=255&t,t>>>=8,e[r+2]=255&t,t>>>=8,e[r+3]=255&t,e}r.d(t,{Ag:()=>g,Cg:()=>c,Q$:()=>a,T4:()=>d,cQ:()=>i,fS:()=>n,mP:()=>u,n8:()=>s,nm:()=>f,oq:()=>l,un:()=>o,v7:()=>h})},392:(e,t,r)=>{r.d(t,{v:()=>n});const n={network:{layer1:"placeholder"},logLevel:"debug"}},902:(e,t,r)=>{r.d(t,{IE:()=>o,Mh:()=>c,fg:()=>n,it:()=>s,lW:()=>i,sQ:()=>a});const n="https://api.mainnet.hiro.so",o="https://api.testnet.hiro.so",s="http://localhost:3999",i="https://hub.blockstack.org",a=33,c=32},889:(e,t,r)=>{r.d(t,{AI:()=>I,AY:()=>m,Ev:()=>u,Fe:()=>E,Ie:()=>T,JU:()=>R,M4:()=>h,O1:()=>n,Ru:()=>y,Y0:()=>d,hy:()=>a,jO:()=>s,kn:()=>c,oO:()=>p,p8:()=>_,sk:()=>o,ur:()=>b,v0:()=>i,vP:()=>f,xE:()=>l,zd:()=>g});const n={MISSING_PARAMETER:"missing_parameter",REMOTE_SERVICE_ERROR:"remote_service_error",INVALID_STATE:"invalid_state",NO_SESSION_DATA:"no_session_data",DOES_NOT_EXIST:"does_not_exist",FAILED_DECRYPTION_ERROR:"failed_decryption_error",INVALID_DID_ERROR:"invalid_did_error",NOT_ENOUGH_FUNDS_ERROR:"not_enough_error",INVALID_AMOUNT_ERROR:"invalid_amount_error",LOGIN_FAILED_ERROR:"login_failed",SIGNATURE_VERIFICATION_ERROR:"signature_verification_failure",CONFLICT_ERROR:"conflict_error",NOT_ENOUGH_PROOF_ERROR:"not_enough_proof_error",BAD_PATH_ERROR:"bad_path_error",VALIDATION_ERROR:"validation_error",PAYLOAD_TOO_LARGE_ERROR:"payload_too_large_error",PRECONDITION_FAILED_ERROR:"precondition_failed_error",UNKNOWN:"unknown"};Object.freeze(n);class o extends Error{constructor(e){super();let t=e.message,r=`Error Code: ${e.code}`,n=this.stack;if(n)r+=`Stack Trace:\n${n}`;else try{throw new Error}catch(e){n=e.stack}t+=`\nIf you believe this exception is caused by a bug in stacks.js,\n please file a bug report: https://github.com/blockstack/stacks.js/issues\n\n${r}`,this.message=t,this.code=e.code,this.parameter=e.parameter?e.parameter:void 0}toString(){return`${super.toString()}\n code: ${this.code} param: ${this.parameter?this.parameter:"n/a"}`}}class s extends o{constructor(e,t=""){super({code:n.MISSING_PARAMETER,message:t,parameter:e}),this.name="MissingParametersError"}}class i extends o{constructor(e,t=""){super({code:n.MISSING_PARAMETER,message:t,parameter:e}),this.name="MissingParametersError"}}class a extends o{constructor(e,t=""){super({code:n.REMOTE_SERVICE_ERROR,message:t}),this.response=e}}class c extends o{constructor(e=""){super({code:n.INVALID_DID_ERROR,message:e}),this.name="InvalidDIDError"}}class u extends o{constructor(e){const t=`Not enough UTXOs to fund. Left to fund: ${e}`;super({code:n.NOT_ENOUGH_FUNDS_ERROR,message:t}),this.leftToFund=e,this.name="NotEnoughFundsError",this.message=t}}class l extends o{constructor(e,t){const r=`Not enough coin to fund fees transaction fees. Fees would be ${e}, specified spend is ${t}`;super({code:n.INVALID_AMOUNT_ERROR,message:r}),this.specifiedAmount=t,this.fees=e,this.name="InvalidAmountError",this.message=r}}class g extends o{constructor(e){const t=`Failed to login: ${e}`;super({code:n.LOGIN_FAILED_ERROR,message:t}),this.message=t,this.name="LoginFailedError"}}class d extends o{constructor(e){const t=`Failed to verify signature: ${e}`;super({code:n.SIGNATURE_VERIFICATION_ERROR,message:t}),this.message=t,this.name="SignatureVerificationError"}}class f extends o{constructor(e="Unable to decrypt cipher object."){super({code:n.FAILED_DECRYPTION_ERROR,message:e}),this.message=e,this.name="FailedDecryptionError"}}class h extends o{constructor(e){super({code:n.INVALID_STATE,message:e}),this.message=e,this.name="InvalidStateError"}}class E extends o{constructor(e){super({code:n.INVALID_STATE,message:e}),this.message=e,this.name="NoSessionDataError"}}class p extends o{constructor(e,t){super(e),t&&(this.hubError={statusCode:t.status,statusText:t.statusText},"string"==typeof t.body?this.hubError.message=t.body:"object"==typeof t.body&&Object.assign(this.hubError,t.body))}}class I extends p{constructor(e,t){super({message:e,code:n.DOES_NOT_EXIST},t),this.name="DoesNotExist"}}class m extends p{constructor(e,t){super({message:e,code:n.CONFLICT_ERROR},t),this.name="ConflictError"}}class R extends p{constructor(e,t){super({message:e,code:n.NOT_ENOUGH_PROOF_ERROR},t),this.name="NotEnoughProofError"}}class y extends p{constructor(e,t){super({message:e,code:n.BAD_PATH_ERROR},t),this.name="BadPathError"}}class _ extends p{constructor(e,t){super({message:e,code:n.VALIDATION_ERROR},t),this.name="ValidationError"}}class T extends p{constructor(e,t,r){super({message:e,code:n.PAYLOAD_TOO_LARGE_ERROR},t),this.name="PayloadTooLargeError",this.maxUploadByteSize=r}}class b extends p{constructor(e,t){super({message:e,code:n.PRECONDITION_FAILED_ERROR},t),this.name="PreconditionFailedError"}}},436:(e,t,r)=>{r.d(t,{O6:()=>o,eA:()=>u,h$:()=>a,hM:()=>i,i$:()=>s,jX:()=>c});const n={referrerPolicy:"origin",headers:{"x-hiro-product":"stacksjs"}},o=()=>n,s=e=>Object.assign(n,e);async function i(e,t){const r={};return Object.assign(r,n,t),await fetch(e,r)}function a(e,t){return"string"==typeof t?t===e:t.exec(e)}function c({apiKey:e,host:t=/(.*)api(.*)(\.stacks\.co|\.hiro\.so)$/i,httpHeader:r="x-api-key"}){return{pre:n=>{a(new URL(n.url).host,t)&&(n.init.headers instanceof Headers?n.init.headers:n.init.headers=new Headers(n.init.headers)).set(r,e)}}}function u(...e){const{fetch:t,middlewares:r}=function(e){return"function"==typeof e[0]?{fetch:e.shift(),middlewares:e}:{fetch:i,middlewares:e}}(e);return async(e,n)=>{var o,s,i;let a={input:e,init:null!=n?n:{}};for(const e of r)if("function"==typeof e.pre){const r=await Promise.resolve(e.pre({fetch:t,url:a.input,input:a.input,init:null!=(o=a.init)?o:{}}));r&&"url"in r&&(r.input=r.url),a=null!=r?r:a}let c=await t(a.input,a.init);for(const e of r)if("function"==typeof e.post){const r=await Promise.resolve(e.post({fetch:t,url:a.input,input:a.input,init:null!=(s=a.init)?s:{},response:null!=(i=null==c?void 0:c.clone())?i:c}));c=null!=r?r:c}return c}}},631:(e,t,r)=>{r.d(t,{z:()=>o});var n=r(788);function o(e){const t="string"==typeof e?(0,n.nr)(e):e;if(32!=t.length&&33!=t.length)throw new Error(`Improperly formatted private-key. Private-key byte length should be 32 or 33. Length provided: ${t.length}`);if(33==t.length&&1!==t[32])throw new Error("Improperly formatted private-key. 33 bytes indicate compressed key, but the last byte must be == 01");return t}},976:(e,t,r)=>{r.d(t,{Y:()=>a});var n=r(392);const o=["debug","info","warn","error","none"],s={},i={};for(let e=0;e<o.length;e++){const t=o[e];s[t]=e,i[e]=t}class a{static error(e){this.shouldLog("error")&&console.error(this.logMessage("error",e))}static warn(e){this.shouldLog("warn")&&console.warn(this.logMessage("warn",e))}static info(e){this.shouldLog("info")&&console.log(this.logMessage("info",e))}static debug(e){this.shouldLog("debug")&&console.log(this.logMessage("debug",e))}static logMessage(e,t){return`[${e.toUpperCase()}] ${t}`}static shouldLog(e){return s[n.v.logLevel]<=s[e]}}},225:(e,t,r)=>{r.d(t,{U8:()=>a,ph:()=>i,xP:()=>s});var n=r(788);const o=32;function s(e){if(e.length<2*o*2+1)throw new Error("Invalid signature");const t=e.slice(0,2),r=e.slice(2,2+2*o),s=e.slice(2+2*o);return{recoveryId:(0,n.WR)(t),r,s}}function i(e){return e.slice(2)+e.slice(0,2)}function a(e){return e.slice(-2)+e.slice(0,-2)}},59:()=>{},788:(e,t,r)=>{r.d(t,{$O:()=>V,$g:()=>_,$j:()=>A,A5:()=>m,GW:()=>g,HN:()=>y,I4:()=>O,Md:()=>B,NA:()=>F,NJ:()=>s,QD:()=>P,Qs:()=>$,Rf:()=>I,T7:()=>j,WR:()=>w,WT:()=>u,WW:()=>k,Xt:()=>c,_Y:()=>N,at:()=>T,cG:()=>a,ci:()=>U,cn:()=>v,eV:()=>C,gS:()=>f,iY:()=>L,jk:()=>x,ko:()=>h,lW:()=>E,nD:()=>i,nr:()=>D,ru:()=>l,sO:()=>R,se:()=>d,y_:()=>b,ym:()=>o});var n=r(976);const o="blockstack";function s(){return new Date((new Date).setFullYear((new Date).getFullYear()+1))}function i(){return new Date((new Date).setMonth((new Date).getMonth()+1))}function a(){return new Date((new Date).setHours((new Date).getHours()+1))}function c(e){return Number.isFinite(e)?Math.floor(1024*e*1024):0}function u(e){return 16*(Math.floor(e/16)+1)}function l(e){return 4*Math.ceil(e/3)}function g(e,t,r){const n=new RegExp(`([?&])${t}=.*?(&|$)`,"i"),o=-1!==e.indexOf("?")?"&":"?";return e.match(n)?e.replace(n,`$1${t}=${r}$2`):`${e}${o}${t}=${r}`}function d(e,t){void 0!==e&&""!==e||(e="0.0.0"),void 0!==t&&""!==e||(t="0.0.0");const r=e.split(".").map((e=>parseInt(e,10))),n=t.split(".").map((e=>parseInt(e,10)));for(let o=0;o<t.length;o++)if(o>=e.length&&n.push(0),r[o]<n[o])return!1;return!0}function f(){let e=(new Date).getTime();return"undefined"!=typeof performance&&"function"==typeof performance.now&&(e+=performance.now()),"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(t=>{const r=(e+16*Math.random())%16|0;return e=Math.floor(e/16),("x"===t?r:3&r|8).toString(16)}))}function h(e,t){try{const r=new URL(e),n=new URL(t),o=0|parseInt(r.port||"0",10)||("https:"===r.protocol?443:80),s=0|parseInt(n.port||"0",10)||("https:"===n.protocol?443:80),i={scheme:r.protocol===n.protocol,hostname:r.hostname===n.hostname,port:o===s,absolute:(e.includes("http://")||e.includes("https://"))&&(t.includes("http://")||t.includes("https://"))};return i.scheme&&i.hostname&&i.port&&i.absolute}catch(e){return console.log(e),console.log("Parsing error in same URL origin check"),!1}}function E(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if(void 0!==r.g)return r.g;throw new Error("Unexpected runtime environment - no supported global scope (`window`, `self`, `global`) available")}function p(e,t,r){return r?`Use of '${r}' requires \`${t}\` which is unavailable on the '${e}' object within the currently executing environment.`:`\`${t}\` is unavailable on the '${e}' object within the currently executing environment.`}function I(e,{throwIfUnavailable:t,usageDesc:r,returnEmptyObject:o}={}){let s;try{if(s=E(),s){const t=s[e];if(t)return t}}catch(t){n.Y.error(`Error getting object '${e}' from global scope '${s}': ${t}`)}if(t){const t=p(s,e.toString(),r);throw n.Y.error(t),new Error(t)}if(o)return{}}function m(e,{throwIfUnavailable:t,usageDesc:r,returnEmptyObject:o}={}){let s;try{s=E()}catch(i){if(n.Y.error(`Error getting global scope: ${i}`),t){const t=p(s,e[0].toString(),r);throw n.Y.error(t),t}o&&(s={})}const i={};for(let a=0;a<e.length;a++){const c=e[a];try{if(s){const e=s[c];if(e)i[c]=e;else{if(t){const e=p(s,c.toString(),r);throw n.Y.error(e),new Error(e)}o&&(i[c]={})}}}catch(e){if(t){const e=p(s,c.toString(),r);throw n.Y.error(e),new Error(e)}}}return i}function R(e,t){return x(y(e),t)}function y(e){if("bigint"==typeof e)return e;if("string"==typeof e)return BigInt(e);if("number"==typeof e){if(!Number.isInteger(e))throw new RangeError("Invalid value. Values of type 'number' must be an integer.");if(e>Number.MAX_SAFE_INTEGER)throw new RangeError(`Invalid value. Values of type 'number' must be less than or equal to ${Number.MAX_SAFE_INTEGER}. For larger values, try using a BigInt instead.`);return BigInt(e)}if(V(e,Uint8Array))return BigInt(`0x${U(e)}`);throw new TypeError("intToBigInt: Invalid value type. Must be a number, bigint, BigInt-compatible string, or Uint8Array.")}function _(e){return/^0x/i.test(e)?e:`0x${e}`}function T(e){return/^0x/i.test(e)?e.slice(2):e}function b(e){if("string"!=typeof e)throw new TypeError("hexToBigInt: expected string, got "+typeof e);return BigInt(`0x${e}`)}function O(e,t=8){return("bigint"==typeof e?e:y(e)).toString(16).padStart(2*t,"0")}function w(e){return parseInt(e,16)}function x(e,t=16){return D(O(e,t))}function A(e,t){if(e<-(BigInt(1)<<t-BigInt(1))||(BigInt(1)<<t-BigInt(1))-BigInt(1)<e)throw`Unable to represent integer in width: ${t}`;return e>=BigInt(0)?BigInt(e):e+(BigInt(1)<<t)}function v(e){return N(BigInt(`0x${U(e)}`),BigInt(8*e.byteLength))}function N(e,t){return function(e,t){return e&BigInt(1)<<t}(e,t-BigInt(1))?e-(BigInt(1)<<t):e}const S=Array.from({length:256},((e,t)=>t.toString(16).padStart(2,"0")));function U(e){if(!(e instanceof Uint8Array))throw new Error("Uint8Array expected");let t="";for(const r of e)t+=S[r];return t}function D(e){if("string"!=typeof e)throw new TypeError("hexToBytes: expected string, got "+typeof e);e=(e=T(e)).length%2?`0${e}`:e;const t=new Uint8Array(e.length/2);for(let r=0;r<t.length;r++){const n=2*r,o=e.slice(n,n+2),s=Number.parseInt(o,16);if(Number.isNaN(s)||s<0)throw new Error("Invalid byte sequence");t[r]=s}return t}function L(e){return(new TextEncoder).encode(e)}function B(e){return(new TextDecoder).decode(e)}function P(e){const t=[];for(let r=0;r<e.length;r++)t.push(255&e.charCodeAt(r));return new Uint8Array(t)}function $(e){return String.fromCharCode.apply(null,e)}function M(e){return!Number.isInteger(e)||e<0||e>255}function F(e){if(e.some(M))throw new Error("Some values are invalid bytes.");return new Uint8Array(e)}function C(...e){if(!e.every((e=>e instanceof Uint8Array)))throw new Error("Uint8Array list expected");if(1===e.length)return e[0];const t=e.reduce(((e,t)=>e+t.length),0),r=new Uint8Array(t);for(let t=0,n=0;t<e.length;t++){const o=e[t];r.set(o,n),n+=o.length}return r}function k(e){return C(...e.map((e=>"number"==typeof e?F([e]):e instanceof Array?F(e):e)))}function V(e,t){var r,n;return e instanceof t||(null==(n=null==(r=null==e?void 0:e.constructor)?void 0:r.name)?void 0:n.toLowerCase())===t.name}function j(e){return 64===(e=T(e)).length&&/^[0-9a-fA-F]+$/.test(e)}}},t={};function r(n){var o=t[n];if(void 0!==o)return o.exports;var s=t[n]={exports:{}};return e[n](s,s.exports,r),s.exports}r.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return r.d(t,{a:t}),t},r.d=(e,t)=>{for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var n={};return(()=>{r.r(n),r.d(n,{BLOCKSTACK_HANDLER:()=>s.ym,BadPathError:()=>t.Ru,BlockstackError:()=>t.sk,ConflictError:()=>t.AY,DEVNET_URL:()=>i.it,DoesNotExist:()=>t.AI,ERROR_CODES:()=>t.O1,FailedDecryptionError:()=>t.vP,GAIA_URL:()=>i.lW,GaiaHubError:()=>t.oO,HIRO_MAINNET_URL:()=>i.fg,HIRO_TESTNET_URL:()=>i.IE,InvalidAmountError:()=>t.xE,InvalidDIDError:()=>t.kn,InvalidParameterError:()=>t.jO,InvalidStateError:()=>t.M4,Logger:()=>o.Y,LoginFailedError:()=>t.zd,MissingParameterError:()=>t.v0,NoSessionDataError:()=>t.Fe,NotEnoughFundsError:()=>t.Ev,NotEnoughProofError:()=>t.JU,PRIVATE_KEY_BYTES_COMPRESSED:()=>i.sQ,PRIVATE_KEY_BYTES_UNCOMPRESSED:()=>i.Mh,PayloadTooLargeError:()=>t.Ie,PreconditionFailedError:()=>t.ur,RemoteServiceError:()=>t.hy,SignatureVerificationError:()=>t.Y0,ValidationError:()=>t.p8,alloc:()=>u.un,asciiToBytes:()=>s.QD,bigIntToBytes:()=>s.jk,bytesToAscii:()=>s.Qs,bytesToHex:()=>s.ci,bytesToTwosBigInt:()=>s.cn,bytesToUtf8:()=>s.Md,concatArray:()=>s.WW,concatBytes:()=>s.eV,config:()=>e.v,createApiKeyMiddleware:()=>d.jX,createFetchFn:()=>d.eA,equals:()=>u.fS,fetchWrapper:()=>d.hM,fromTwos:()=>s._Y,getAesCbcOutputLength:()=>s.WT,getBase64OutputLength:()=>s.ru,getFetchOptions:()=>d.O6,getGlobalObject:()=>s.Rf,getGlobalObjects:()=>s.A5,getGlobalScope:()=>s.lW,hexToBigInt:()=>s.y_,hexToBytes:()=>s.nr,hexToInt:()=>s.WR,hostMatches:()=>d.h$,intToBigInt:()=>s.HN,intToBytes:()=>s.sO,intToHex:()=>s.I4,isInstance:()=>s.$O,isLaterVersion:()=>s.se,isSameOriginAbsoluteUrl:()=>s.ko,makeUUID4:()=>s.gS,megabytesToBytes:()=>s.Xt,nextHour:()=>s.cG,nextMonth:()=>s.nD,nextYear:()=>s.NJ,octetsToBytes:()=>s.NA,parseRecoverableSignatureVrs:()=>a.xP,privateKeyToBytes:()=>c.z,readUInt16BE:()=>u.n8,readUInt16LE:()=>u.mP,readUInt32BE:()=>u.Ag,readUInt32LE:()=>u.nm,readUInt8:()=>u.Q$,setFetchOptions:()=>d.i$,signatureRsvToVrs:()=>a.U8,signatureVrsToRsv:()=>a.ph,toTwos:()=>s.$j,updateQueryStringParameter:()=>s.GW,utf8ToBytes:()=>s.iY,validateHash256:()=>s.T7,with0x:()=>s.$g,without0x:()=>s.at,writeUInt16BE:()=>u.cQ,writeUInt16LE:()=>u.oq,writeUInt32BE:()=>u.T4,writeUInt32LE:()=>u.v7,writeUInt8:()=>u.Cg});var e=r(392),t=r(889),o=r(976),s=r(788),i=r(902),a=r(225),c=r(631),u=r(142),l=r(59),g={};for(const e in l)["default","config","BadPathError","BlockstackError","ConflictError","DoesNotExist","ERROR_CODES","FailedDecryptionError","GaiaHubError","InvalidAmountError","InvalidDIDError","InvalidParameterError","InvalidStateError","LoginFailedError","MissingParameterError","NoSessionDataError","NotEnoughFundsError","NotEnoughProofError","PayloadTooLargeError","PreconditionFailedError","RemoteServiceError","SignatureVerificationError","ValidationError","Logger","BLOCKSTACK_HANDLER","asciiToBytes","bigIntToBytes","bytesToAscii","bytesToHex","bytesToTwosBigInt","bytesToUtf8","concatArray","concatBytes","fromTwos","getAesCbcOutputLength","getBase64OutputLength","getGlobalObject","getGlobalObjects","getGlobalScope","hexToBigInt","hexToBytes","hexToInt","intToBigInt","intToBytes","intToHex","isInstance","isLaterVersion","isSameOriginAbsoluteUrl","makeUUID4","megabytesToBytes","nextHour","nextMonth","nextYear","octetsToBytes","toTwos","updateQueryStringParameter","utf8ToBytes","validateHash256","with0x","without0x","DEVNET_URL","GAIA_URL","HIRO_MAINNET_URL","HIRO_TESTNET_URL","PRIVATE_KEY_BYTES_COMPRESSED","PRIVATE_KEY_BYTES_UNCOMPRESSED","parseRecoverableSignatureVrs","signatureRsvToVrs","signatureVrsToRsv","privateKeyToBytes","alloc","equals","readUInt16BE","readUInt16LE","readUInt32BE","readUInt32LE","readUInt8","writeUInt16BE","writeUInt16LE","writeUInt32BE","writeUInt32LE","writeUInt8"].indexOf(e)<0&&(g[e]=()=>l[e]);r.d(n,g);var d=r(436)})(),n})())); | ||
//# sourceMappingURL=index.js.map |
{ | ||
"name": "@stacks/common", | ||
"version": "7.0.3-pr.1+23115454", | ||
"version": "7.0.3-pr.2+edbd2947", | ||
"description": "Common Stacks utilities", | ||
@@ -47,3 +47,3 @@ "license": "MIT", | ||
}, | ||
"gitHead": "2311545402003b52f3ae07472d6c3dfb4efef4c4" | ||
"gitHead": "edbd29473c18075d3d9dcd0b2a1967ebadcefbc2" | ||
} |
@@ -40,3 +40,6 @@ // Define default request options and allow modification using getters, setters | ||
/** @ignore */ | ||
export async function fetchWrapper(input: RequestInfo, init?: RequestInit): Promise<Response> { | ||
export async function fetchWrapper( | ||
input: RequestInfo | URL, | ||
init?: RequestInit | ||
): Promise<Response> { | ||
const fetchOpts = {}; | ||
@@ -50,7 +53,7 @@ // Use the provided options in request options along with default or user provided values | ||
export type FetchFn = (url: string, init?: RequestInit) => Promise<Response>; | ||
export type FetchFn = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>; | ||
/** | ||
* @ignore Internally used for letting networking functions specify "API" options. | ||
* Should be compatible with the `client`s created by the API and RPC packages. | ||
* Should be compatible with the `client`s created by the API and RPC client packages. | ||
*/ | ||
@@ -70,3 +73,7 @@ export interface ClientOpts { | ||
fetch: FetchFn; | ||
/** @deprecated This may in some cases be a Request/RequestInfo object instead of a string. For safety use `.input` instead. */ | ||
url: string; | ||
input: RequestInfo | URL; | ||
init: RequestInit; | ||
@@ -77,7 +84,13 @@ } | ||
fetch: FetchFn; | ||
/** @deprecated This may in some cases be a Request/RequestInfo object instead of a string. For safety use `.input` instead. */ | ||
url: string; | ||
input: RequestInfo | URL; | ||
init: RequestInit; | ||
response: Response; | ||
} | ||
/** @deprecated Use {@link FetchArgs} instead. The `.url` property is may also be a Request object. */ | ||
export interface FetchParams { | ||
@@ -88,4 +101,11 @@ url: string; | ||
export interface FetchArgs { | ||
input: RequestInfo | URL; | ||
init?: RequestInit; | ||
} | ||
export interface FetchMiddleware { | ||
pre?: (context: RequestContext) => PromiseLike<FetchParams | void> | FetchParams | void; | ||
pre?: ( | ||
context: RequestContext | ||
) => PromiseLike<FetchParams | FetchArgs | void> | FetchParams | FetchArgs | void; | ||
post?: (context: ResponseContext) => Promise<Response | void> | Response | void; | ||
@@ -138,12 +158,12 @@ } | ||
function argsForCreateFetchFn(args: any[]): { fetchLib: FetchFn; middlewares: FetchMiddleware[] } { | ||
let fetchLib: FetchFn = fetchWrapper; | ||
let middlewares: FetchMiddleware[] = []; | ||
if (args.length > 0 && typeof args[0] === 'function') { | ||
fetchLib = args.shift(); | ||
/** @internal */ | ||
function argsForCreateFetchFn(args: any[]): { fetch: FetchFn; middlewares: FetchMiddleware[] } { | ||
if (typeof args[0] === 'function') { | ||
return { | ||
fetch: args.shift(), // first arg is fetch function | ||
middlewares: args, | ||
}; | ||
} | ||
if (args.length > 0) { | ||
middlewares = args; // remaining args | ||
} | ||
return { fetchLib, middlewares }; | ||
return { fetch: fetchWrapper, middlewares: args }; | ||
} | ||
@@ -161,9 +181,9 @@ | ||
*/ | ||
export function createFetchFn(fetchLib: FetchFn, ...middleware: FetchMiddleware[]): FetchFn; | ||
export function createFetchFn(fetchFn: FetchFn, ...middleware: FetchMiddleware[]): FetchFn; | ||
export function createFetchFn(...middleware: FetchMiddleware[]): FetchFn; | ||
export function createFetchFn(...args: any[]): FetchFn { | ||
const { fetchLib, middlewares } = argsForCreateFetchFn(args); | ||
const { fetch, middlewares } = argsForCreateFetchFn(args); | ||
const fetchFn = async (url: string, init?: RequestInit | undefined): Promise<Response> => { | ||
let fetchParams = { url, init: init ?? {} }; | ||
const fetchFn: FetchFn = async (input, init) => { | ||
let fetchParams: FetchArgs = { input, init: init ?? {} }; | ||
@@ -174,11 +194,14 @@ for (const middleware of middlewares) { | ||
middleware.pre({ | ||
fetch: fetchLib, | ||
...fetchParams, | ||
fetch, | ||
url: fetchParams.input as string, // @deprecated (type mismatch, but this is backwards compatible behavior) | ||
input: fetchParams.input, | ||
init: fetchParams.init ?? {}, | ||
}) | ||
); | ||
fetchParams = result ?? fetchParams; | ||
if (result && 'url' in result) (result as unknown as FetchArgs).input = result.url; | ||
fetchParams = (result as FetchArgs | void) ?? fetchParams; | ||
} | ||
} | ||
let response = await fetchLib(fetchParams.url, fetchParams.init); | ||
let response = await fetch(fetchParams.input, fetchParams.init); | ||
@@ -189,5 +212,6 @@ for (const middleware of middlewares) { | ||
middleware.post({ | ||
fetch: fetchLib, | ||
url: fetchParams.url, | ||
init: fetchParams.init, | ||
fetch, | ||
url: fetchParams.input as string, // @deprecated (type mismatch, but this is backwards compatible behavior) | ||
input: fetchParams.input, | ||
init: fetchParams.init ?? {}, | ||
response: response?.clone() ?? response, | ||
@@ -194,0 +218,0 @@ }) |
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
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Manifest confusion
Supply chain riskThis package has inconsistent metadata. This could be malicious or caused by an error when publishing the package.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Manifest confusion
Supply chain riskThis package has inconsistent metadata. This could be malicious or caused by an error when publishing the package.
Found 1 instance in 1 package
266028
3505
10