Comparing version 1.2.0 to 1.3.0
/** | ||
* @license magicbell v1.2.0 | ||
* @license magicbell v1.3.0 | ||
* | ||
@@ -4,0 +4,0 @@ * Copyright (c) MagicBell Inc. and its affiliates. |
/** | ||
* @license magicbell v1.2.0 | ||
* @license magicbell v1.3.0 | ||
* | ||
@@ -77,3 +77,3 @@ * Copyright (c) MagicBell Inc. and its affiliates. | ||
binding: "magicbell", | ||
binding_version: "1.2.0", | ||
binding_version: "1.3.0", | ||
publisher: "magicbell" | ||
@@ -486,3 +486,4 @@ }; | ||
debug: isBoolean, | ||
features: isObject | ||
features: isObject, | ||
headers: isObject | ||
}; | ||
@@ -1048,6 +1049,7 @@ function isOptionsHash(object) { | ||
return compact( | ||
normalizeHeaders({ | ||
normalizeHeaders(__spreadProps(__spreadValues({ | ||
"Accept-Version": "v2", | ||
"Idempotency-Key": options.idempotencyKey || __privateMethod(this, _getDefaultIdempotencyKey, getDefaultIdempotencyKey_fn).call(this, method, options.maxRetries) | ||
}, __privateGet(this, _options).headers), { | ||
"User-Agent": isBrowser ? null : __privateGet(this, _userAgent), | ||
"Idempotency-Key": options.idempotencyKey || __privateMethod(this, _getDefaultIdempotencyKey, getDefaultIdempotencyKey_fn).call(this, method, options.maxRetries), | ||
"Accept-Version": "v2", | ||
"X-MAGICBELL-API-KEY": options.apiKey, | ||
@@ -1059,3 +1061,3 @@ "X-MAGICBELL-API-SECRET": options.apiSecret, | ||
"X-MAGICBELL-USER-HMAC": userHmac | ||
}), | ||
})), | ||
true | ||
@@ -1062,0 +1064,0 @@ ); |
/** | ||
* @license magicbell v1.2.0 | ||
* @license magicbell v1.3.0 | ||
* | ||
@@ -10,3 +10,3 @@ * Copyright (c) MagicBell Inc. and its affiliates. | ||
"use strict";var ge=Object.defineProperty,ye=Object.defineProperties;var Ee=Object.getOwnPropertyDescriptors;var ee=Object.getOwnPropertySymbols;var xe=Object.prototype.hasOwnProperty,Te=Object.prototype.propertyIsEnumerable;var D=(e,t,r)=>t in e?ge(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,b=(e,t)=>{for(var r in t||(t={}))xe.call(t,r)&&D(e,r,t[r]);if(ee)for(var r of ee(t))Te.call(t,r)&&D(e,r,t[r]);return e},k=(e,t)=>ye(e,Ee(t));var i=(e,t,r)=>(D(e,typeof t!="symbol"?t+"":t,r),r),F=(e,t,r)=>{if(!t.has(e))throw TypeError("Cannot "+r)};var T=(e,t,r)=>(F(e,t,"read from private field"),r?r.call(e):t.get(e)),x=(e,t,r)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,r)},O=(e,t,r,n)=>(F(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);var v=(e,t,r)=>(F(e,t,"access private method"),r);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const be=require("axios"),Pe=require("crypto"),Se=require("eventsource"),W=e=>e&&typeof e=="object"&&"default"in e?e:{default:e},Z=W(be),X=W(Pe),ve=W(Se);function se(e,t){if(!e||!t)return"";if(!X.default||!X.default.createHmac)throw new Error("This method is not available in the browser. Please provide a userHmac.");return X.default.createHmac("sha256",e).update(t).digest("base64")}function ie(){var t;const e={binding:"magicbell",binding_version:"1.2.0",publisher:"magicbell"};return typeof process>"u"?e:k(b({},e),{runtime:((t=process==null?void 0:process.release)==null?void 0:t.name)||"node",runtime_version:process.version,platform:process.platform,arch:process.arch})}function Ae(e){return e!=null&&e.name?[e==null?void 0:e.name,e.version&&`/${e.version}`,e.url&&` (${e.url})`].filter(Boolean).join(""):""}function _e(e){const t=ie();return[`${t.binding}/${t.binding_version}`,"runtime"in t&&`${t.runtime}/${t.runtime_version}`,Ae(e)].filter(Boolean).join(" ")}function we(e){return JSON.stringify(k(b({},ie()),{application:e}))}function qe(e){for(const t of["code","type","status"])switch(e[t]){case"user_identifier_not_provided":return new te(e);case"invalid_request_error":return new Oe(e);case"api_error":return new $e(e);case"authentication_error":return new te(e);case"rate_limit_error":return new Ie(e);case"idempotency_error":return new Me(e);case 404:return new Be(e);case 422:return new Le(e)}return new Ue(e)}class S extends Error{constructor(r){super(r.message);i(this,"name");i(this,"message");i(this,"type");i(this,"docs_url");i(this,"code");i(this,"status");i(this,"statusText");i(this,"suggestion");this.type=this.constructor.name,this.name="MagicBellError",this.code=r.code,this.status=r.status,this.statusText=r.statusText,this.message=r.message,this.suggestion=r.suggestion,this.docs_url=r.docs_url||r.help_link}}class Oe extends S{}class Le extends S{}class $e extends S{}class te extends S{}class Ie extends S{}class Me extends S{}class Ue extends S{}class Be extends S{}function K(e){if(!e||typeof e!="object")return e;const t={};for(const r of Object.keys(e))t[ke(r)]=e[r];return t}function ke(e){const t={etag:"ETag",magicbell:"MagicBell"};return e.split("-").map(r=>t[r.toLowerCase()]||r.charAt(0).toUpperCase()+r.slice(1).toLowerCase()).join("-")}const _={reset:"\x1B[0m",magenta:"\x1B[35m",red:"\x1B[31m"};class Ne{constructor(){i(this,"active",!1)}debug(t){!this.active||console.log(`${_.reset}${_.magenta}magicbell:${_.reset} ${t}`)}error(t){!this.active||console.error(`${_.reset}${_.red}magicbell:${_.reset} ${t}`)}}function Re(e){return`${e.slice(0,4)}\u2026${e.slice(-4)}`}const je=/secret|token|key|password/i;function He(e){return je.test(e)}function Ce({method:e,baseURL:t,url:r,data:n,headers:s}){return[`curl -X ${e.toUpperCase()}`,`${t}/${r.replace(/^\//,"")}`,Object.entries(s).map(([u,o])=>`-H '${u}: ${He(u)?Re(String(o)):o}'`).join(" "),n&&`-d '${JSON.stringify(n)}'`].join(" ")}const Q=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);function P(e){return typeof e=="string"}function L(e){return typeof e=="boolean"}function oe(e){return Array.isArray(e)}function re(e){return Array.isArray(e)&&e.every(t=>typeof t=="string")}function J(e){return typeof e=="number"}function $(e){return e&&typeof e=="object"}function Ge(e,t=!1){if(typeof e!="object")throw new Error("Argument must be an object");const r={};for(const n of Object.keys(e))e[n]!=null&&(t&&e[n]===""||(r[n]=e[n]));return r}function De(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}async function Fe(e){return new Promise(t=>setTimeout(t,e))}function Xe(...e){if(e.length<=2)return e.join(" and ");const t=e.slice(-1)[0];return[e.slice(0,-1).join(", "),t].join(", and ")}function Ke(...e){return["/",...e].join("/").replace(/\/+/g,"/").replace(/\/$/,"")}const ae=typeof Symbol<"u"&&Symbol.asyncIterator?Symbol.asyncIterator:"@@asyncIterator";function Je(e){return Q(e,"current_page")&&Q(e,"total_pages")&&e.current_page<e.total_pages}function Ye(e,{data:t,params:r}){const n={currentPromise:null},s=typeof r.after<"u";let u=0,o=e({data:t,params:r});const h=c=>{const y=c.current_page+1;return e({data:t,params:k(b({},r),{page:y})})};function m(c){const y=Object.keys(c).find(d=>Array.isArray(c[d])),l=c[y]||c.data;if(!l||typeof l.length!="number")throw Error("Unexpected: MagicBell API response does not have a well-formed response.");if(u<l.length){const d=s?l.length-1-u:u,E=l[d];return u+=1,{value:E,done:!1}}return Je(c)?(u=0,o=h(c),o.then(m)):{value:void 0,done:!0}}function p(){return ze(n,(c,y)=>o.then(m).then(c).catch(y))}const g=ue(p),f=Qe(g),a={forEach:g,toArray:f,next:p,return:()=>({}),[ae]:()=>a};return Object.assign(o,a)}function ze(e,t){return e.currentPromise||(e.currentPromise=new Promise(t).then(r=>(e.currentPromise=void 0,r))),e.currentPromise}function ue(e,t){return function(n){return new Promise((s,u)=>{let o=0;function h(m){if(m.done){s();return}const p=m.value;return new Promise(g=>{g(n(p,o))}).then(g=>g===!1?(t==null||t(),h({done:!0})):(o++,e().then(h)))}e().then(h).catch(u)})}}function Qe(e){return function(r){const n=r==null?void 0:r.limit;if(!n)throw Error("You must pass a `limit` option to toArray, e.g., `toArray({ limit: 1000 });`.");if(n>1e4)throw Error("You cannot specify a limit of more than 10,000 items to fetch in `toArray`; use `forEach` to iterate through longer lists.");return new Promise((s,u)=>{const o=[];e(h=>{if(o.push(h),o.length>=n)return!1}).then(()=>{s(o)}).catch(u)})}}function We(e,t={}){let r,n,s,u;const o=[];let h;const m=f=>{o.push(f),h&&(h(),h=null)};async function p(f){!n&&!u&&(u=e.request({method:"GET",path:"/config"},f).then(d=>n=d.ws.channel));const a=await e.request({method:"POST",path:"/ws/auth"},f),{token:c}=await Z.default.post(`https://rest.ably.io/keys/${a.keyName}/requestToken`,a).then(d=>d.data);await u;const y=t.sseHost||"https://realtime.ably.io",l=new URL("sse",y);l.searchParams.append("v","1.1"),l.searchParams.append("accessToken",c),l.searchParams.append("channels",n),l.searchParams.append("heartbeats","true"),s&&l.searchParams.append("lastEvent",s),r&&r.close(),r=new ve.default(l.toString()),r.onmessage=d=>{if(d.origin!==y||(s=d.lastEventId,!("data"in d)))return;const E=JSON.parse(d.data);if(E.type==="close")return m({value:null,done:!0});E.data=E.encoding==="json"?JSON.parse(E.data):E.data,m({value:E,done:!1})},r.onerror=d=>{const E="data"in d?JSON.parse(d.data):{};E.code>=40140&&E.code<40150?(r.close(),p(f)):/invalid channel id/i.test(E.message)?(r.close(),m({value:null,done:!0})):console.log("err",d)}}function g(f){p(f);const a=async()=>{o.length||await new Promise(E=>h=E);const d=o.pop();return d.done&&r&&r.close(),d},c=()=>(r.close(),m({done:!0,value:void 0}),{done:!0,value:void 0}),l={forEach:ue(a,c),close:c,next:a,return:c,[ae]:()=>l};return l}return g}const Y={host:P,maxRetryDelay:J,timeout:J,apiKey:P,maxRetries:J,userEmail:P,userExternalId:P,userHmac:P,idempotencyKey:P,telemetry:L,apiSecret:P,appInfo:$,debug:L,features:$};function V(e){var t;if(!$(e))return!1;for(const r of Object.keys(e))if(!((t=Y[r])!=null&&t.call(Y,e[r])))return!1;return!0}const z={archived:L,read:L,seen:L,categories:e=>P(e)||re(e),topics:e=>P(e)||re(e)};function Ze(e){var t;if(!$(e))return!1;for(const r of Object.keys(e))if(!((t=z[r])!=null&&t.call(z,e[r])))return!1;return!0}function Ve(e,t,r={encode:!0}){return e.replace(/{([\s\S]+?)}/g,(n,s)=>r.encode?encodeURIComponent(t[s]||""):t[s]||"")}function et(e){return(e.match(/{\w+}/g)||[]||[]).map(r=>r.replace(/[{}]/g,""))}function tt(e){return!oe(e)||!$(e[0])?{}:V(e[0])?{}:e.shift()}function rt(e){if(!oe(e)||e.length===0)return{};const t=e[e.length-1];return V(t)?b({},e.pop()):{}}function nt({path:e,method:t,args:r}){const n=[...r].filter(a=>a!==void 0),u=et(e).reduce((a,c)=>{const y=n.shift();if(typeof y!="string")throw new Error(`MagicBell: Argument "${c}" must be a string, but got ${typeof y}: ${JSON.stringify(y)} (on API request to \`${t} ${e}\`)`);return a[c]=y,a},{}),o=Ve(e,u,{encode:!1}),h=tt(n),m=rt(n);if(n.filter(a=>a!=null).length)throw new Error(`MagicBell: Unknown arguments (${JSON.stringify(n)}). (on API request to \`${t} ${o}\`)`);let p=t==="GET";return t==="POST"&&Ze(h)&&(p=!0),{path:o,data:p?{}:h,params:p?h:{},options:m}}function ne(e){return e?Array.isArray(e)?e.length===0:typeof e=="object"?Object.keys(e).length===0:!1:!0}class q{constructor(t){i(this,"path");i(this,"entity");i(this,"client");this.client=t}request({method:t,paged:r,path:n},...s){const{path:u,data:o,params:h,options:m}=nt({path:Ke(this.path,n),method:t,args:s}),p=({data:g,params:f})=>{const a=this.entity||this.path;return g=ne(g)?void 0:{[a]:g},f=ne(f)?void 0:f,this.client.request({method:t,path:u,data:g,params:f},m).then(c=>c[a]||c)};return r?Ye(p,{data:o,params:h}):p({data:o,params:h})}assertFeatureFlag(t){if(!this.client.hasFlag(t))throw new Error(`This is a beta feature, please enable it by providing the "${t}" feature flag.`)}}class st extends q{constructor(){super(...arguments);i(this,"path","imports");i(this,"entity","import")}create(r,n){return this.request({method:"POST"},r,n)}get(r,n){return this.request({method:"GET",path:"{import_id}"},r,n)}}class it extends q{constructor(){super(...arguments);i(this,"path","notification_preferences");i(this,"entity","notification_preferences")}get(r){return this.request({method:"GET"},r)}update(r,n){return this.request({method:"PUT"},r,n)}}class ot extends q{constructor(){super(...arguments);i(this,"path","notifications");i(this,"entity","notification")}create(r,n){return this.request({method:"POST"},r,n)}list(r,n){return this.request({method:"GET",paged:!0},r,n)}get(r,n){return this.request({method:"GET",path:"{notification_id}"},r,n)}delete(r,n){return this.request({method:"DELETE",path:"{notification_id}"},r,n)}markAsRead(r,n){return this.request({method:"POST",path:"{notification_id}/read"},r,n)}markAsUnread(r,n){return this.request({method:"POST",path:"{notification_id}/unread"},r,n)}archive(r,n){return this.request({method:"POST",path:"{notification_id}/archive"},r,n)}unarchive(r,n){return this.request({method:"DELETE",path:"{notification_id}/archive"},r,n)}markAllRead(r,n){return this.request({method:"POST",path:"read"},r,n)}markAllSeen(r,n){return this.request({method:"POST",path:"seen"},r,n)}}class at extends q{constructor(){super(...arguments);i(this,"path","push_subscriptions");i(this,"entity","push_subscription")}create(r,n){return this.assertFeatureFlag("push-subscriptions-create"),this.request({method:"POST"},r,n)}delete(r,n){return this.assertFeatureFlag("push-subscriptions-delete"),this.request({method:"DELETE",path:"{device_token}"},r,n)}}class ut extends q{constructor(){super(...arguments);i(this,"path","subscriptions");i(this,"entity","subscription")}list(r){return this.request({method:"GET",paged:!0},r)}create(r,n){return this.request({method:"POST"},r,n)}unsubscribe(r,n,s){return this.request({method:"POST",path:"{topic}/unsubscribe"},r,n,s)}get(r,n){return this.request({method:"GET",path:"{topic}"},r,n)}delete(r,n,s){return this.request({method:"DELETE",path:"{topic}"},r,n,s)}}class ct extends q{constructor(){super(...arguments);i(this,"path","users");i(this,"entity","user")}create(r,n){return this.request({method:"POST"},r,n)}update(r,n,s){return this.request({method:"PUT",path:"{user_id}"},r,n,s)}delete(r,n){return this.request({method:"DELETE",path:"{user_id}"},r,n)}updateByEmail(r,n,s){return this.request({method:"PUT",path:"email:{user_email}"},r,n,s)}deleteByEmail(r,n){return this.request({method:"DELETE",path:"email:{user_email}"},r,n)}updateByExternalId(r,n,s){return this.request({method:"PUT",path:"external_id:{external_id}"},r,n,s)}deleteByExternalId(r,n){return this.request({method:"DELETE",path:"external_id:{external_id}"},r,n)}}typeof XMLHttpRequest!="function"&&(Z.default.defaults.adapter=require("axios/lib/adapters/http"));const lt={host:"https://api.magicbell.com",timeout:3e4,maxRetries:3,maxRetryDelay:60,telemetry:!0};var I,M,A,w,U,B,N,le,R,he,j,de,H,fe,C,me,G,pe;class ce{constructor(t){x(this,N);x(this,R);x(this,j);x(this,H);x(this,C);x(this,G);x(this,I,void 0);x(this,M,void 0);x(this,A,void 0);x(this,w,new Ne);x(this,U,{});x(this,B,[]);i(this,"listen",We(this));i(this,"imports",new st(this));i(this,"notificationPreferences",new it(this));i(this,"notifications",new ot(this));i(this,"pushSubscriptions",new at(this));i(this,"subscriptions",new ut(this));i(this,"users",new ct(this));const r=["apiKey"].filter(n=>!Q(t,n));if(r.length)throw new Error(`You haven't provided all required options, please provide ${Xe(...r)} to Client(options)`);if(!V(t))throw new Error("You have provided invalid options. Please check your client options.");O(this,A,Object.assign({},lt,t)),T(this,w).active=Boolean(T(this,A).debug),O(this,M,we(t.appInfo)),O(this,I,_e(t.appInfo)),O(this,U,t.features||{})}hasFlag(t){return T(this,U)[t]||!1}async request({method:t,path:r,data:n,params:s},u){var p,g;const o=b(b({},T(this,A)),u),h=v(this,N,le).call(this,o,t),m=Math.max(0,o.maxRetries);for(let f=1;f<=m;f++){let a,c;const y=Date.now();if(T(this,w).debug(`${t} ${r}`),await Z.default({method:t,url:r,baseURL:o.host,headers:b(b({},h),K({"X-MAGICBELL-CLIENT-TELEMETRY":v(this,j,de).call(this)})),data:n,params:s,timeout:o.timeout}).then(l=>{a=l}).catch(l=>{const d=Ce({method:t,baseURL:o.host,url:r,data:n,params:s,headers:h});T(this,w).error(`${l.message}: ${d}`),c=l,a=l.response}),v(this,R,he).call(this,a,{startTime:y}),v(this,H,fe).call(this,a,f,m)){const l=Number(a.headers["retry-after"]);await Fe(v(this,C,me).call(this,f,l,o.maxRetryDelay));continue}if(c)throw qe(b({name:c.name,message:c.message,type:c.type,status:a.status,statusText:a.statusText},(g=(p=a==null?void 0:a.data)==null?void 0:p.errors)==null?void 0:g[0]));return a.data}}}I=new WeakMap,M=new WeakMap,A=new WeakMap,w=new WeakMap,U=new WeakMap,B=new WeakMap,N=new WeakSet,le=function(t,r){let n=t.userHmac;return!n&&t.apiSecret&&(t.userExternalId||t.userEmail)&&(n=se(t.apiSecret,t.userExternalId||t.userEmail)),Ge(K({"User-Agent":typeof document<"u"?null:T(this,I),"Idempotency-Key":t.idempotencyKey||v(this,G,pe).call(this,r,t.maxRetries),"Accept-Version":"v2","X-MAGICBELL-API-KEY":t.apiKey,"X-MAGICBELL-API-SECRET":t.apiSecret,"X-MAGICBELL-CLIENT-USER-AGENT":T(this,M),"X-MAGICBELL-USER-EMAIL":t.userEmail,"X-MAGICBELL-USER-EXTERNAL-ID":t.userExternalId,"X-MAGICBELL-USER-HMAC":n}),!0)},R=new WeakSet,he=function(t,{startTime:r}){if(!T(this,A).telemetry||!(t!=null&&t.status))return;const n=K(t.headers);T(this,B).push({id:n["X-Request-Id"],runtime:Number(n["X-Runtime"]),duration:Date.now()-r,status:t.status})},j=new WeakSet,de=function(){const t=T(this,B).pop();return t?JSON.stringify(t):null},H=new WeakSet,fe=function(t,r,n){return r>=n?!1:t?t.headers["should-retry"]?t.headers["should-retry"]==="true":t.status===409||t.status===503||t.status>=500&&t.request.method!=="POST":!0},C=new WeakSet,me=function(t,r=null,n){let u=Math.min(.5*Math.pow(t,2),n);return u*=.75*(1+Math.random()),u=Math.min(Math.max(.5,u),n),Number.isInteger(r)&&r<=60&&(u=Math.max(u,r)),u*1e3},G=new WeakSet,pe=function(t,r){if(!(t!=="POST"||r===0))return`magicbell-retry-${De()}`};exports.Client=ce;exports.createHmac=se;exports.default=ce; | ||
"use strict";var ge=Object.defineProperty,ye=Object.defineProperties;var Ee=Object.getOwnPropertyDescriptors;var ee=Object.getOwnPropertySymbols;var xe=Object.prototype.hasOwnProperty,Te=Object.prototype.propertyIsEnumerable;var D=(e,t,r)=>t in e?ge(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,b=(e,t)=>{for(var r in t||(t={}))xe.call(t,r)&&D(e,r,t[r]);if(ee)for(var r of ee(t))Te.call(t,r)&&D(e,r,t[r]);return e},L=(e,t)=>ye(e,Ee(t));var i=(e,t,r)=>(D(e,typeof t!="symbol"?t+"":t,r),r),F=(e,t,r)=>{if(!t.has(e))throw TypeError("Cannot "+r)};var x=(e,t,r)=>(F(e,t,"read from private field"),r?r.call(e):t.get(e)),T=(e,t,r)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,r)},$=(e,t,r,n)=>(F(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);var A=(e,t,r)=>(F(e,t,"access private method"),r);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const be=require("axios"),Pe=require("crypto"),Se=require("eventsource"),W=e=>e&&typeof e=="object"&&"default"in e?e:{default:e},Z=W(be),X=W(Pe),ve=W(Se);function se(e,t){if(!e||!t)return"";if(!X.default||!X.default.createHmac)throw new Error("This method is not available in the browser. Please provide a userHmac.");return X.default.createHmac("sha256",e).update(t).digest("base64")}function ie(){var t;const e={binding:"magicbell",binding_version:"1.3.0",publisher:"magicbell"};return typeof process>"u"?e:L(b({},e),{runtime:((t=process==null?void 0:process.release)==null?void 0:t.name)||"node",runtime_version:process.version,platform:process.platform,arch:process.arch})}function Ae(e){return e!=null&&e.name?[e==null?void 0:e.name,e.version&&`/${e.version}`,e.url&&` (${e.url})`].filter(Boolean).join(""):""}function _e(e){const t=ie();return[`${t.binding}/${t.binding_version}`,"runtime"in t&&`${t.runtime}/${t.runtime_version}`,Ae(e)].filter(Boolean).join(" ")}function qe(e){return JSON.stringify(L(b({},ie()),{application:e}))}function we(e){for(const t of["code","type","status"])switch(e[t]){case"user_identifier_not_provided":return new te(e);case"invalid_request_error":return new Oe(e);case"api_error":return new $e(e);case"authentication_error":return new te(e);case"rate_limit_error":return new Ie(e);case"idempotency_error":return new Me(e);case 404:return new Be(e);case 422:return new Le(e)}return new Ue(e)}class v extends Error{constructor(r){super(r.message);i(this,"name");i(this,"message");i(this,"type");i(this,"docs_url");i(this,"code");i(this,"status");i(this,"statusText");i(this,"suggestion");this.type=this.constructor.name,this.name="MagicBellError",this.code=r.code,this.status=r.status,this.statusText=r.statusText,this.message=r.message,this.suggestion=r.suggestion,this.docs_url=r.docs_url||r.help_link}}class Oe extends v{}class Le extends v{}class $e extends v{}class te extends v{}class Ie extends v{}class Me extends v{}class Ue extends v{}class Be extends v{}function K(e){if(!e||typeof e!="object")return e;const t={};for(const r of Object.keys(e))t[ke(r)]=e[r];return t}function ke(e){const t={etag:"ETag",magicbell:"MagicBell"};return e.split("-").map(r=>t[r.toLowerCase()]||r.charAt(0).toUpperCase()+r.slice(1).toLowerCase()).join("-")}const _={reset:"\x1B[0m",magenta:"\x1B[35m",red:"\x1B[31m"};class Ne{constructor(){i(this,"active",!1)}debug(t){!this.active||console.log(`${_.reset}${_.magenta}magicbell:${_.reset} ${t}`)}error(t){!this.active||console.error(`${_.reset}${_.red}magicbell:${_.reset} ${t}`)}}function Re(e){return`${e.slice(0,4)}\u2026${e.slice(-4)}`}const je=/secret|token|key|password/i;function He(e){return je.test(e)}function Ce({method:e,baseURL:t,url:r,data:n,headers:s}){return[`curl -X ${e.toUpperCase()}`,`${t}/${r.replace(/^\//,"")}`,Object.entries(s).map(([u,o])=>`-H '${u}: ${He(u)?Re(String(o)):o}'`).join(" "),n&&`-d '${JSON.stringify(n)}'`].join(" ")}const Q=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);function P(e){return typeof e=="string"}function I(e){return typeof e=="boolean"}function oe(e){return Array.isArray(e)}function re(e){return Array.isArray(e)&&e.every(t=>typeof t=="string")}function J(e){return typeof e=="number"}function q(e){return e&&typeof e=="object"}function Ge(e,t=!1){if(typeof e!="object")throw new Error("Argument must be an object");const r={};for(const n of Object.keys(e))e[n]!=null&&(t&&e[n]===""||(r[n]=e[n]));return r}function De(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}async function Fe(e){return new Promise(t=>setTimeout(t,e))}function Xe(...e){if(e.length<=2)return e.join(" and ");const t=e.slice(-1)[0];return[e.slice(0,-1).join(", "),t].join(", and ")}function Ke(...e){return["/",...e].join("/").replace(/\/+/g,"/").replace(/\/$/,"")}const ae=typeof Symbol<"u"&&Symbol.asyncIterator?Symbol.asyncIterator:"@@asyncIterator";function Je(e){return Q(e,"current_page")&&Q(e,"total_pages")&&e.current_page<e.total_pages}function Ye(e,{data:t,params:r}){const n={currentPromise:null},s=typeof r.after<"u";let u=0,o=e({data:t,params:r});const h=c=>{const y=c.current_page+1;return e({data:t,params:L(b({},r),{page:y})})};function m(c){const y=Object.keys(c).find(d=>Array.isArray(c[d])),l=c[y]||c.data;if(!l||typeof l.length!="number")throw Error("Unexpected: MagicBell API response does not have a well-formed response.");if(u<l.length){const d=s?l.length-1-u:u,E=l[d];return u+=1,{value:E,done:!1}}return Je(c)?(u=0,o=h(c),o.then(m)):{value:void 0,done:!0}}function p(){return ze(n,(c,y)=>o.then(m).then(c).catch(y))}const g=ue(p),f=Qe(g),a={forEach:g,toArray:f,next:p,return:()=>({}),[ae]:()=>a};return Object.assign(o,a)}function ze(e,t){return e.currentPromise||(e.currentPromise=new Promise(t).then(r=>(e.currentPromise=void 0,r))),e.currentPromise}function ue(e,t){return function(n){return new Promise((s,u)=>{let o=0;function h(m){if(m.done){s();return}const p=m.value;return new Promise(g=>{g(n(p,o))}).then(g=>g===!1?(t==null||t(),h({done:!0})):(o++,e().then(h)))}e().then(h).catch(u)})}}function Qe(e){return function(r){const n=r==null?void 0:r.limit;if(!n)throw Error("You must pass a `limit` option to toArray, e.g., `toArray({ limit: 1000 });`.");if(n>1e4)throw Error("You cannot specify a limit of more than 10,000 items to fetch in `toArray`; use `forEach` to iterate through longer lists.");return new Promise((s,u)=>{const o=[];e(h=>{if(o.push(h),o.length>=n)return!1}).then(()=>{s(o)}).catch(u)})}}function We(e,t={}){let r,n,s,u;const o=[];let h;const m=f=>{o.push(f),h&&(h(),h=null)};async function p(f){!n&&!u&&(u=e.request({method:"GET",path:"/config"},f).then(d=>n=d.ws.channel));const a=await e.request({method:"POST",path:"/ws/auth"},f),{token:c}=await Z.default.post(`https://rest.ably.io/keys/${a.keyName}/requestToken`,a).then(d=>d.data);await u;const y=t.sseHost||"https://realtime.ably.io",l=new URL("sse",y);l.searchParams.append("v","1.1"),l.searchParams.append("accessToken",c),l.searchParams.append("channels",n),l.searchParams.append("heartbeats","true"),s&&l.searchParams.append("lastEvent",s),r&&r.close(),r=new ve.default(l.toString()),r.onmessage=d=>{if(d.origin!==y||(s=d.lastEventId,!("data"in d)))return;const E=JSON.parse(d.data);if(E.type==="close")return m({value:null,done:!0});E.data=E.encoding==="json"?JSON.parse(E.data):E.data,m({value:E,done:!1})},r.onerror=d=>{const E="data"in d?JSON.parse(d.data):{};E.code>=40140&&E.code<40150?(r.close(),p(f)):/invalid channel id/i.test(E.message)?(r.close(),m({value:null,done:!0})):console.log("err",d)}}function g(f){p(f);const a=async()=>{o.length||await new Promise(E=>h=E);const d=o.pop();return d.done&&r&&r.close(),d},c=()=>(r.close(),m({done:!0,value:void 0}),{done:!0,value:void 0}),l={forEach:ue(a,c),close:c,next:a,return:c,[ae]:()=>l};return l}return g}const Y={host:P,maxRetryDelay:J,timeout:J,apiKey:P,maxRetries:J,userEmail:P,userExternalId:P,userHmac:P,idempotencyKey:P,telemetry:I,apiSecret:P,appInfo:q,debug:I,features:q,headers:q};function V(e){var t;if(!q(e))return!1;for(const r of Object.keys(e))if(!((t=Y[r])!=null&&t.call(Y,e[r])))return!1;return!0}const z={archived:I,read:I,seen:I,categories:e=>P(e)||re(e),topics:e=>P(e)||re(e)};function Ze(e){var t;if(!q(e))return!1;for(const r of Object.keys(e))if(!((t=z[r])!=null&&t.call(z,e[r])))return!1;return!0}function Ve(e,t,r={encode:!0}){return e.replace(/{([\s\S]+?)}/g,(n,s)=>r.encode?encodeURIComponent(t[s]||""):t[s]||"")}function et(e){return(e.match(/{\w+}/g)||[]||[]).map(r=>r.replace(/[{}]/g,""))}function tt(e){return!oe(e)||!q(e[0])?{}:V(e[0])?{}:e.shift()}function rt(e){if(!oe(e)||e.length===0)return{};const t=e[e.length-1];return V(t)?b({},e.pop()):{}}function nt({path:e,method:t,args:r}){const n=[...r].filter(a=>a!==void 0),u=et(e).reduce((a,c)=>{const y=n.shift();if(typeof y!="string")throw new Error(`MagicBell: Argument "${c}" must be a string, but got ${typeof y}: ${JSON.stringify(y)} (on API request to \`${t} ${e}\`)`);return a[c]=y,a},{}),o=Ve(e,u,{encode:!1}),h=tt(n),m=rt(n);if(n.filter(a=>a!=null).length)throw new Error(`MagicBell: Unknown arguments (${JSON.stringify(n)}). (on API request to \`${t} ${o}\`)`);let p=t==="GET";return t==="POST"&&Ze(h)&&(p=!0),{path:o,data:p?{}:h,params:p?h:{},options:m}}function ne(e){return e?Array.isArray(e)?e.length===0:typeof e=="object"?Object.keys(e).length===0:!1:!0}class O{constructor(t){i(this,"path");i(this,"entity");i(this,"client");this.client=t}request({method:t,paged:r,path:n},...s){const{path:u,data:o,params:h,options:m}=nt({path:Ke(this.path,n),method:t,args:s}),p=({data:g,params:f})=>{const a=this.entity||this.path;return g=ne(g)?void 0:{[a]:g},f=ne(f)?void 0:f,this.client.request({method:t,path:u,data:g,params:f},m).then(c=>c[a]||c)};return r?Ye(p,{data:o,params:h}):p({data:o,params:h})}assertFeatureFlag(t){if(!this.client.hasFlag(t))throw new Error(`This is a beta feature, please enable it by providing the "${t}" feature flag.`)}}class st extends O{constructor(){super(...arguments);i(this,"path","imports");i(this,"entity","import")}create(r,n){return this.request({method:"POST"},r,n)}get(r,n){return this.request({method:"GET",path:"{import_id}"},r,n)}}class it extends O{constructor(){super(...arguments);i(this,"path","notification_preferences");i(this,"entity","notification_preferences")}get(r){return this.request({method:"GET"},r)}update(r,n){return this.request({method:"PUT"},r,n)}}class ot extends O{constructor(){super(...arguments);i(this,"path","notifications");i(this,"entity","notification")}create(r,n){return this.request({method:"POST"},r,n)}list(r,n){return this.request({method:"GET",paged:!0},r,n)}get(r,n){return this.request({method:"GET",path:"{notification_id}"},r,n)}delete(r,n){return this.request({method:"DELETE",path:"{notification_id}"},r,n)}markAsRead(r,n){return this.request({method:"POST",path:"{notification_id}/read"},r,n)}markAsUnread(r,n){return this.request({method:"POST",path:"{notification_id}/unread"},r,n)}archive(r,n){return this.request({method:"POST",path:"{notification_id}/archive"},r,n)}unarchive(r,n){return this.request({method:"DELETE",path:"{notification_id}/archive"},r,n)}markAllRead(r,n){return this.request({method:"POST",path:"read"},r,n)}markAllSeen(r,n){return this.request({method:"POST",path:"seen"},r,n)}}class at extends O{constructor(){super(...arguments);i(this,"path","push_subscriptions");i(this,"entity","push_subscription")}create(r,n){return this.assertFeatureFlag("push-subscriptions-create"),this.request({method:"POST"},r,n)}delete(r,n){return this.assertFeatureFlag("push-subscriptions-delete"),this.request({method:"DELETE",path:"{device_token}"},r,n)}}class ut extends O{constructor(){super(...arguments);i(this,"path","subscriptions");i(this,"entity","subscription")}list(r){return this.request({method:"GET",paged:!0},r)}create(r,n){return this.request({method:"POST"},r,n)}unsubscribe(r,n,s){return this.request({method:"POST",path:"{topic}/unsubscribe"},r,n,s)}get(r,n){return this.request({method:"GET",path:"{topic}"},r,n)}delete(r,n,s){return this.request({method:"DELETE",path:"{topic}"},r,n,s)}}class ct extends O{constructor(){super(...arguments);i(this,"path","users");i(this,"entity","user")}create(r,n){return this.request({method:"POST"},r,n)}update(r,n,s){return this.request({method:"PUT",path:"{user_id}"},r,n,s)}delete(r,n){return this.request({method:"DELETE",path:"{user_id}"},r,n)}updateByEmail(r,n,s){return this.request({method:"PUT",path:"email:{user_email}"},r,n,s)}deleteByEmail(r,n){return this.request({method:"DELETE",path:"email:{user_email}"},r,n)}updateByExternalId(r,n,s){return this.request({method:"PUT",path:"external_id:{external_id}"},r,n,s)}deleteByExternalId(r,n){return this.request({method:"DELETE",path:"external_id:{external_id}"},r,n)}}typeof XMLHttpRequest!="function"&&(Z.default.defaults.adapter=require("axios/lib/adapters/http"));const lt={host:"https://api.magicbell.com",timeout:3e4,maxRetries:3,maxRetryDelay:60,telemetry:!0};var M,U,S,w,B,k,N,le,R,he,j,de,H,fe,C,me,G,pe;class ce{constructor(t){T(this,N);T(this,R);T(this,j);T(this,H);T(this,C);T(this,G);T(this,M,void 0);T(this,U,void 0);T(this,S,void 0);T(this,w,new Ne);T(this,B,{});T(this,k,[]);i(this,"listen",We(this));i(this,"imports",new st(this));i(this,"notificationPreferences",new it(this));i(this,"notifications",new ot(this));i(this,"pushSubscriptions",new at(this));i(this,"subscriptions",new ut(this));i(this,"users",new ct(this));const r=["apiKey"].filter(n=>!Q(t,n));if(r.length)throw new Error(`You haven't provided all required options, please provide ${Xe(...r)} to Client(options)`);if(!V(t))throw new Error("You have provided invalid options. Please check your client options.");$(this,S,Object.assign({},lt,t)),x(this,w).active=Boolean(x(this,S).debug),$(this,U,qe(t.appInfo)),$(this,M,_e(t.appInfo)),$(this,B,t.features||{})}hasFlag(t){return x(this,B)[t]||!1}async request({method:t,path:r,data:n,params:s},u){var p,g;const o=b(b({},x(this,S)),u),h=A(this,N,le).call(this,o,t),m=Math.max(0,o.maxRetries);for(let f=1;f<=m;f++){let a,c;const y=Date.now();if(x(this,w).debug(`${t} ${r}`),await Z.default({method:t,url:r,baseURL:o.host,headers:b(b({},h),K({"X-MAGICBELL-CLIENT-TELEMETRY":A(this,j,de).call(this)})),data:n,params:s,timeout:o.timeout}).then(l=>{a=l}).catch(l=>{const d=Ce({method:t,baseURL:o.host,url:r,data:n,params:s,headers:h});x(this,w).error(`${l.message}: ${d}`),c=l,a=l.response}),A(this,R,he).call(this,a,{startTime:y}),A(this,H,fe).call(this,a,f,m)){const l=Number(a.headers["retry-after"]);await Fe(A(this,C,me).call(this,f,l,o.maxRetryDelay));continue}if(c)throw we(b({name:c.name,message:c.message,type:c.type,status:a.status,statusText:a.statusText},(g=(p=a==null?void 0:a.data)==null?void 0:p.errors)==null?void 0:g[0]));return a.data}}}M=new WeakMap,U=new WeakMap,S=new WeakMap,w=new WeakMap,B=new WeakMap,k=new WeakMap,N=new WeakSet,le=function(t,r){let n=t.userHmac;!n&&t.apiSecret&&(t.userExternalId||t.userEmail)&&(n=se(t.apiSecret,t.userExternalId||t.userEmail));const s=typeof document<"u";return Ge(K(L(b({"Accept-Version":"v2","Idempotency-Key":t.idempotencyKey||A(this,G,pe).call(this,r,t.maxRetries)},x(this,S).headers),{"User-Agent":s?null:x(this,M),"X-MAGICBELL-API-KEY":t.apiKey,"X-MAGICBELL-API-SECRET":t.apiSecret,"X-MAGICBELL-CLIENT-USER-AGENT":x(this,U),"X-MAGICBELL-USER-EMAIL":t.userEmail,"X-MAGICBELL-USER-EXTERNAL-ID":t.userExternalId,"X-MAGICBELL-USER-HMAC":n})),!0)},R=new WeakSet,he=function(t,{startTime:r}){if(!x(this,S).telemetry||!(t!=null&&t.status))return;const n=K(t.headers);x(this,k).push({id:n["X-Request-Id"],runtime:Number(n["X-Runtime"]),duration:Date.now()-r,status:t.status})},j=new WeakSet,de=function(){const t=x(this,k).pop();return t?JSON.stringify(t):null},H=new WeakSet,fe=function(t,r,n){return r>=n?!1:t?t.headers["should-retry"]?t.headers["should-retry"]==="true":t.status===409||t.status===503||t.status>=500&&t.request.method!=="POST":!0},C=new WeakSet,me=function(t,r=null,n){let u=Math.min(.5*Math.pow(t,2),n);return u*=.75*(1+Math.random()),u=Math.min(Math.max(.5,u),n),Number.isInteger(r)&&r<=60&&(u=Math.max(u,r)),u*1e3},G=new WeakSet,pe=function(t,r){if(!(t!=="POST"||r===0))return`magicbell-retry-${De()}`};exports.Client=ce;exports.createHmac=se;exports.default=ce; | ||
//# sourceMappingURL=magicbell.cjs.min.js.map |
/** | ||
* @license magicbell v1.2.0 | ||
* @license magicbell v1.3.0 | ||
* | ||
@@ -71,3 +71,3 @@ * Copyright (c) MagicBell Inc. and its affiliates. | ||
binding: "magicbell", | ||
binding_version: "1.2.0", | ||
binding_version: "1.3.0", | ||
publisher: "magicbell" | ||
@@ -480,3 +480,4 @@ }; | ||
debug: isBoolean, | ||
features: isObject | ||
features: isObject, | ||
headers: isObject | ||
}; | ||
@@ -1042,6 +1043,7 @@ function isOptionsHash(object) { | ||
return compact( | ||
normalizeHeaders({ | ||
normalizeHeaders(__spreadProps(__spreadValues({ | ||
"Accept-Version": "v2", | ||
"Idempotency-Key": options.idempotencyKey || __privateMethod(this, _getDefaultIdempotencyKey, getDefaultIdempotencyKey_fn).call(this, method, options.maxRetries) | ||
}, __privateGet(this, _options).headers), { | ||
"User-Agent": isBrowser ? null : __privateGet(this, _userAgent), | ||
"Idempotency-Key": options.idempotencyKey || __privateMethod(this, _getDefaultIdempotencyKey, getDefaultIdempotencyKey_fn).call(this, method, options.maxRetries), | ||
"Accept-Version": "v2", | ||
"X-MAGICBELL-API-KEY": options.apiKey, | ||
@@ -1053,3 +1055,3 @@ "X-MAGICBELL-API-SECRET": options.apiSecret, | ||
"X-MAGICBELL-USER-HMAC": userHmac | ||
}), | ||
})), | ||
true | ||
@@ -1056,0 +1058,0 @@ ); |
/** | ||
* @license magicbell v1.2.0 | ||
* @license magicbell v1.3.0 | ||
* | ||
@@ -21,3 +21,3 @@ * Copyright (c) MagicBell Inc. and its affiliates. | ||
return e; | ||
}, k = (e, t) => me(e, pe(t)); | ||
}, $ = (e, t) => me(e, pe(t)); | ||
var i = (e, t, r) => (F(e, typeof t != "symbol" ? t + "" : t, r), r), D = (e, t, r) => { | ||
@@ -27,8 +27,8 @@ if (!t.has(e)) | ||
}; | ||
var T = (e, t, r) => (D(e, t, "read from private field"), r ? r.call(e) : t.get(e)), x = (e, t, r) => { | ||
var x = (e, t, r) => (D(e, t, "read from private field"), r ? r.call(e) : t.get(e)), T = (e, t, r) => { | ||
if (t.has(e)) | ||
throw TypeError("Cannot add the same private member more than once"); | ||
t instanceof WeakSet ? t.add(e) : t.set(e, r); | ||
}, O = (e, t, r, n) => (D(e, t, "write to private field"), n ? n.call(e, r) : t.set(e, r), r); | ||
var S = (e, t, r) => (D(e, t, "access private method"), r); | ||
}, L = (e, t, r, n) => (D(e, t, "write to private field"), n ? n.call(e, r) : t.set(e, r), r); | ||
var v = (e, t, r) => (D(e, t, "access private method"), r); | ||
import W from "axios"; | ||
@@ -48,6 +48,6 @@ import X from "crypto"; | ||
binding: "magicbell", | ||
binding_version: "1.2.0", | ||
binding_version: "1.3.0", | ||
publisher: "magicbell" | ||
}; | ||
return typeof process > "u" ? e : k(b({}, e), { | ||
return typeof process > "u" ? e : $(b({}, e), { | ||
runtime: ((t = process == null ? void 0 : process.release) == null ? void 0 : t.name) || "node", | ||
@@ -71,3 +71,3 @@ runtime_version: process.version, | ||
function Pe(e) { | ||
return JSON.stringify(k(b({}, ne()), { application: e })); | ||
return JSON.stringify($(b({}, ne()), { application: e })); | ||
} | ||
@@ -96,3 +96,3 @@ function Ae(e) { | ||
} | ||
class A extends Error { | ||
class S extends Error { | ||
constructor(r) { | ||
@@ -111,17 +111,17 @@ super(r.message); | ||
} | ||
class Se extends A { | ||
class Se extends S { | ||
} | ||
class ve extends A { | ||
class ve extends S { | ||
} | ||
class we extends A { | ||
class we extends S { | ||
} | ||
class ee extends A { | ||
class ee extends S { | ||
} | ||
class qe extends A { | ||
class qe extends S { | ||
} | ||
class _e extends A { | ||
class _e extends S { | ||
} | ||
class Oe extends A { | ||
class Oe extends S { | ||
} | ||
class $e extends A { | ||
class $e extends S { | ||
} | ||
@@ -178,3 +178,3 @@ function K(e) { | ||
} | ||
function $(e) { | ||
function I(e) { | ||
return typeof e == "boolean"; | ||
@@ -191,3 +191,3 @@ } | ||
} | ||
function L(e) { | ||
function q(e) { | ||
return e && typeof e == "object"; | ||
@@ -230,3 +230,3 @@ } | ||
const y = c.current_page + 1; | ||
return e({ data: t, params: k(b({}, r), { page: y }) }); | ||
return e({ data: t, params: $(b({}, r), { page: y }) }); | ||
}; | ||
@@ -347,11 +347,12 @@ function m(c) { | ||
idempotencyKey: P, | ||
telemetry: $, | ||
telemetry: I, | ||
apiSecret: P, | ||
appInfo: L, | ||
debug: $, | ||
features: L | ||
appInfo: q, | ||
debug: I, | ||
features: q, | ||
headers: q | ||
}; | ||
function Z(e) { | ||
var t; | ||
if (!L(e)) | ||
if (!q(e)) | ||
return !1; | ||
@@ -364,5 +365,5 @@ for (const r of Object.keys(e)) | ||
const z = { | ||
archived: $, | ||
read: $, | ||
seen: $, | ||
archived: I, | ||
read: I, | ||
seen: I, | ||
categories: (e) => P(e) || te(e), | ||
@@ -373,3 +374,3 @@ topics: (e) => P(e) || te(e) | ||
var t; | ||
if (!L(e)) | ||
if (!q(e)) | ||
return !1; | ||
@@ -391,3 +392,3 @@ for (const r of Object.keys(e)) | ||
function Qe(e) { | ||
return !se(e) || !L(e[0]) ? {} : Z(e[0]) ? {} : e.shift(); | ||
return !se(e) || !q(e[0]) ? {} : Z(e[0]) ? {} : e.shift(); | ||
} | ||
@@ -425,3 +426,3 @@ function We(e) { | ||
} | ||
class _ { | ||
class O { | ||
constructor(t) { | ||
@@ -452,3 +453,3 @@ i(this, "path"); | ||
} | ||
class Ve extends _ { | ||
class Ve extends O { | ||
constructor() { | ||
@@ -479,3 +480,3 @@ super(...arguments); | ||
} | ||
class et extends _ { | ||
class et extends O { | ||
constructor() { | ||
@@ -504,3 +505,3 @@ super(...arguments); | ||
} | ||
class tt extends _ { | ||
class tt extends O { | ||
constructor() { | ||
@@ -611,3 +612,3 @@ super(...arguments); | ||
} | ||
class rt extends _ { | ||
class rt extends O { | ||
constructor() { | ||
@@ -638,3 +639,3 @@ super(...arguments); | ||
} | ||
class nt extends _ { | ||
class nt extends O { | ||
constructor() { | ||
@@ -696,3 +697,3 @@ super(...arguments); | ||
} | ||
class st extends _ { | ||
class st extends O { | ||
constructor() { | ||
@@ -784,17 +785,17 @@ super(...arguments); | ||
}; | ||
var I, M, v, q, U, B, N, ae, R, ue, j, ce, H, le, G, he, C, de; | ||
var M, U, A, _, B, k, N, ae, R, ue, j, ce, H, le, G, he, C, de; | ||
class ht { | ||
constructor(t) { | ||
x(this, N); | ||
x(this, R); | ||
x(this, j); | ||
x(this, H); | ||
x(this, G); | ||
x(this, C); | ||
x(this, I, void 0); | ||
x(this, M, void 0); | ||
x(this, v, void 0); | ||
x(this, q, new Ie()); | ||
x(this, U, {}); | ||
x(this, B, []); | ||
T(this, N); | ||
T(this, R); | ||
T(this, j); | ||
T(this, H); | ||
T(this, G); | ||
T(this, C); | ||
T(this, M, void 0); | ||
T(this, U, void 0); | ||
T(this, A, void 0); | ||
T(this, _, new Ie()); | ||
T(this, B, {}); | ||
T(this, k, []); | ||
i(this, "listen", Ke(this)); | ||
@@ -814,14 +815,14 @@ i(this, "imports", new Ve(this)); | ||
throw new Error("You have provided invalid options. Please check your client options."); | ||
O(this, v, Object.assign({}, it, t)), T(this, q).active = Boolean(T(this, v).debug), O(this, M, Pe(t.appInfo)), O(this, I, be(t.appInfo)), O(this, U, t.features || {}); | ||
L(this, A, Object.assign({}, it, t)), x(this, _).active = Boolean(x(this, A).debug), L(this, U, Pe(t.appInfo)), L(this, M, be(t.appInfo)), L(this, B, t.features || {}); | ||
} | ||
hasFlag(t) { | ||
return T(this, U)[t] || !1; | ||
return x(this, B)[t] || !1; | ||
} | ||
async request({ method: t, path: r, data: n, params: s }, u) { | ||
var p, g; | ||
const o = b(b({}, T(this, v)), u), h = S(this, N, ae).call(this, o, t), m = Math.max(0, o.maxRetries); | ||
const o = b(b({}, x(this, A)), u), h = v(this, N, ae).call(this, o, t), m = Math.max(0, o.maxRetries); | ||
for (let f = 1; f <= m; f++) { | ||
let a, c; | ||
const y = Date.now(); | ||
if (T(this, q).debug(`${t} ${r}`), await W({ | ||
if (x(this, _).debug(`${t} ${r}`), await W({ | ||
method: t, | ||
@@ -831,3 +832,3 @@ url: r, | ||
headers: b(b({}, h), K({ | ||
"X-MAGICBELL-CLIENT-TELEMETRY": S(this, j, ce).call(this) | ||
"X-MAGICBELL-CLIENT-TELEMETRY": v(this, j, ce).call(this) | ||
})), | ||
@@ -841,6 +842,6 @@ data: n, | ||
const d = ke({ method: t, baseURL: o.host, url: r, data: n, params: s, headers: h }); | ||
T(this, q).error(`${l.message}: ${d}`), c = l, a = l.response; | ||
}), S(this, R, ue).call(this, a, { startTime: y }), S(this, H, le).call(this, a, f, m)) { | ||
x(this, _).error(`${l.message}: ${d}`), c = l, a = l.response; | ||
}), v(this, R, ue).call(this, a, { startTime: y }), v(this, H, le).call(this, a, f, m)) { | ||
const l = Number(a.headers["retry-after"]); | ||
await je(S(this, G, he).call(this, f, l, o.maxRetryDelay)); | ||
await je(v(this, G, he).call(this, f, l, o.maxRetryDelay)); | ||
continue; | ||
@@ -860,23 +861,26 @@ } | ||
} | ||
I = new WeakMap(), M = new WeakMap(), v = new WeakMap(), q = new WeakMap(), U = new WeakMap(), B = new WeakMap(), N = new WeakSet(), ae = function(t, r) { | ||
M = new WeakMap(), U = new WeakMap(), A = new WeakMap(), _ = new WeakMap(), B = new WeakMap(), k = new WeakMap(), N = new WeakSet(), ae = function(t, r) { | ||
let n = t.userHmac; | ||
return !n && t.apiSecret && (t.userExternalId || t.userEmail) && (n = xe(t.apiSecret, t.userExternalId || t.userEmail)), Ne( | ||
K({ | ||
"User-Agent": typeof document < "u" ? null : T(this, I), | ||
"Idempotency-Key": t.idempotencyKey || S(this, C, de).call(this, r, t.maxRetries), | ||
!n && t.apiSecret && (t.userExternalId || t.userEmail) && (n = xe(t.apiSecret, t.userExternalId || t.userEmail)); | ||
const s = typeof document < "u"; | ||
return Ne( | ||
K($(b({ | ||
"Accept-Version": "v2", | ||
"Idempotency-Key": t.idempotencyKey || v(this, C, de).call(this, r, t.maxRetries) | ||
}, x(this, A).headers), { | ||
"User-Agent": s ? null : x(this, M), | ||
"X-MAGICBELL-API-KEY": t.apiKey, | ||
"X-MAGICBELL-API-SECRET": t.apiSecret, | ||
"X-MAGICBELL-CLIENT-USER-AGENT": T(this, M), | ||
"X-MAGICBELL-CLIENT-USER-AGENT": x(this, U), | ||
"X-MAGICBELL-USER-EMAIL": t.userEmail, | ||
"X-MAGICBELL-USER-EXTERNAL-ID": t.userExternalId, | ||
"X-MAGICBELL-USER-HMAC": n | ||
}), | ||
})), | ||
!0 | ||
); | ||
}, R = new WeakSet(), ue = function(t, { startTime: r }) { | ||
if (!T(this, v).telemetry || !(t != null && t.status)) | ||
if (!x(this, A).telemetry || !(t != null && t.status)) | ||
return; | ||
const n = K(t.headers); | ||
T(this, B).push({ | ||
x(this, k).push({ | ||
id: n["X-Request-Id"], | ||
@@ -888,3 +892,3 @@ runtime: Number(n["X-Runtime"]), | ||
}, j = new WeakSet(), ce = function() { | ||
const t = T(this, B).pop(); | ||
const t = x(this, k).pop(); | ||
return t ? JSON.stringify(t) : null; | ||
@@ -891,0 +895,0 @@ }, H = new WeakSet(), le = function(t, r, n) { |
@@ -20,2 +20,3 @@ export declare type ClientOptions = { | ||
features?: Record<string, boolean>; | ||
headers?: Record<string, string>; | ||
}; | ||
@@ -22,0 +23,0 @@ export declare type RequestOptions = { |
{ | ||
"name": "magicbell", | ||
"version": "1.2.0", | ||
"version": "1.3.0", | ||
"description": "MagicBell API wrapper", | ||
@@ -5,0 +5,0 @@ "author": "MagicBell <bot@magicbell.io> (https://magicbell.com)", |
@@ -213,2 +213,6 @@ # MagicBell Node.js Library | ||
- **headers** _Record<string, string>_ | ||
Custom headers you wish to include on the request, for example to instruct your proxy servers or to decorate your logs. | ||
### Configuring Timeout | ||
@@ -215,0 +219,0 @@ |
@@ -130,1 +130,37 @@ import { basename } from 'path'; | ||
}); | ||
test('client accepts custom headers', async () => { | ||
const status = server.intercept('all', () => ({ id: 1 })); | ||
const client = new Client({ | ||
host: 'https://example.com', | ||
apiKey: 'my-api-key', | ||
maxRetryDelay: 0, | ||
headers: { | ||
'X-Custom-Header': 'foo', | ||
host: 'api.magicbell.com', | ||
}, | ||
}); | ||
// verify that this request is done using 3 identical idempotencyKeys | ||
await client.request({ method: 'POST', path: '/me' }); | ||
expect(status.lastRequest.url.toString()).toEqual('https://example.com/me'); | ||
expect(status.lastRequest.headers.get('x-custom-header')).toEqual('foo'); | ||
expect(status.lastRequest.headers.get('host')).toEqual('api.magicbell.com'); | ||
}); | ||
test("custom headers don't override controlled ones", async () => { | ||
const status = server.intercept('all', () => ({ id: 1 })); | ||
const client = new Client({ | ||
apiKey: 'my-api-key', | ||
maxRetryDelay: 0, | ||
headers: { | ||
'x-magicbell-api-key': 'bar', | ||
}, | ||
}); | ||
// verify that this request is done using 3 identical idempotencyKeys | ||
await client.request({ method: 'POST', path: '/me' }); | ||
expect(status.lastRequest.headers.get('x-magicbell-api-key')).toEqual('my-api-key'); | ||
}); |
@@ -145,6 +145,11 @@ import axios, { AxiosError, AxiosResponse } from 'axios'; | ||
normalizeHeaders({ | ||
// overridable default headers | ||
'Accept-Version': 'v2', | ||
'Idempotency-Key': options.idempotencyKey || this.#getDefaultIdempotencyKey(method, options.maxRetries), | ||
// user-provided headers | ||
...this.#options.headers, | ||
// can't set user-agent in the browser, see https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name | ||
'User-Agent': isBrowser ? null : this.#userAgent, | ||
'Idempotency-Key': options.idempotencyKey || this.#getDefaultIdempotencyKey(method, options.maxRetries), | ||
'Accept-Version': 'v2', | ||
'X-MAGICBELL-API-KEY': options.apiKey, | ||
@@ -151,0 +156,0 @@ 'X-MAGICBELL-API-SECRET': options.apiSecret, |
@@ -19,2 +19,3 @@ import { isBoolean, isNumber, isObject, isString } from './lib/utils'; | ||
features: isObject, | ||
headers: isObject, | ||
}; | ||
@@ -21,0 +22,0 @@ |
@@ -20,2 +20,3 @@ export type ClientOptions = { | ||
features?: Record<string, boolean>; | ||
headers?: Record<string, string>; | ||
}; | ||
@@ -22,0 +23,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
Sorry, the diff of this file is not supported yet
681388
9205
893