@fyno/node 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,37 @@
1
+ # This workflow will run tests using node and then publish a package to GitHub Packages when a release is created
2
+ # For more information see: https://docs.github.com/en/actions/publishing-packages/publishing-nodejs-packages
3
+
4
+ name: Node.js Package
5
+
6
+ on:
7
+ release:
8
+ types: [created]
9
+
10
+ jobs:
11
+ build:
12
+ runs-on: ubuntu-latest
13
+ steps:
14
+ - uses: actions/checkout@v3
15
+ - uses: actions/setup-node@v3
16
+ with:
17
+ node-version: 16
18
+ - run: npm install
19
+ - run: npm test
20
+ env:
21
+ FYNO_WSID: ${{secrets.fyno_wsid}}
22
+ FYNO_API_KEY: ${{secrets.fyno_api_key}}
23
+ FYNO_ENV: ${{secrets.fyno_env}}
24
+
25
+ publish-npm:
26
+ needs: build
27
+ runs-on: ubuntu-latest
28
+ steps:
29
+ - uses: actions/checkout@v3
30
+ - uses: actions/setup-node@v3
31
+ with:
32
+ node-version: 16
33
+ registry-url: https://registry.npmjs.org/
34
+ - run: npm install
35
+ - run: npm publish --access=public
36
+ env:
37
+ NODE_AUTH_TOKEN: ${{secrets.npm_token}}
@@ -0,0 +1,22 @@
1
+ {
2
+ "arrowParens": "always",
3
+ "bracketSpacing": true,
4
+ "endOfLine": "lf",
5
+ "htmlWhitespaceSensitivity": "css",
6
+ "insertPragma": false,
7
+ "singleAttributePerLine": false,
8
+ "bracketSameLine": false,
9
+ "jsxBracketSameLine": false,
10
+ "jsxSingleQuote": false,
11
+ "printWidth": 80,
12
+ "proseWrap": "preserve",
13
+ "quoteProps": "as-needed",
14
+ "requirePragma": false,
15
+ "semi": true,
16
+ "singleQuote": false,
17
+ "tabWidth": 4,
18
+ "trailingComma": "es5",
19
+ "useTabs": false,
20
+ "vueIndentScriptAndStyle": false,
21
+ "parser": "typescript"
22
+ }
@@ -0,0 +1,10 @@
1
+ {
2
+ "editor.defaultFormatter": "esbenp.prettier-vscode",
3
+ "editor.formatOnSave": true,
4
+ "[ignore]": {
5
+ "editor.defaultFormatter": "foxundermoon.shell-format"
6
+ },
7
+ "[properties]": {
8
+ "editor.defaultFormatter": "foxundermoon.shell-format"
9
+ }
10
+ }
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022 Fyno.io
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,57 @@
1
+ This is the official Node.js module for sending notifications through [Fyno.io.](https://fyno.io)
2
+
3
+ You can use this module to send notifications to any channel (SMS, Email, WhatsApp, Push, Discord, Teams, Slack, etc).
4
+
5
+ ![Fyno: Fire your notifications](https://media-exp1.licdn.com/dms/image/D561BAQGlc_gJy29kQA/company-background_10000/0/1660044270257?e=1670940000&v=beta&t=Hxq_mWNsivmJ1j0FZZvvHhwQtXvQSrhEMQ2BPMpPYVU)
6
+
7
+ # Installation
8
+ ``` js
9
+ npm install @fyno/node
10
+ OR
11
+ yarn add @fyno/node
12
+ ```
13
+
14
+ # Prerequisite
15
+ You will need to:
16
+ - Own a [Fyno.io](https://fyno.io) account
17
+ - Create a Fyno API Key
18
+ - Obtain the Workspace ID for your account
19
+ - Create integrations, templates, routing (optional), events as per your requirement
20
+
21
+ # Environment Variables
22
+ We recommend using environment variables for storing your Workspace ID and API Key. To set values for these variables, use the following variable names:
23
+ - **FYNO_WSID:** To store the Workspace ID.
24
+ - **FYNO_API_KEY:** To store the API Key.
25
+ - **FYNO_ENV:** To specify the environment you wish to use for sending notification. Possible values: dev, prod. Default: prod.
26
+
27
+ # Getting Started
28
+ Here's a code snippet that can help you get started:
29
+
30
+ ``` js
31
+ import { Fyno } from "@fyno/node";
32
+
33
+ // If you set the environment variables discussed earlier, use the following code:
34
+ const fyno = new Fyno();
35
+
36
+ // If you wish to provide the environment variables manually, uncomment the lines below and comment the line above.
37
+ // const fyno = new Fyno(
38
+ // "<FYNO_WSID>",
39
+ // "<FYNO_API_KEY>",
40
+ // "<FYNO_ENV>"
41
+ // );
42
+
43
+ fyno.fire("<EventName>", {
44
+ to: {
45
+ sms: "", // Enter number with country code
46
+ whatsapp: "", // Enter WhatsApp number with country code
47
+ email: "", // Enter email address
48
+ slack: "", // Enter slack ID or email address
49
+ discord: "", // Enter discord ID
50
+ teams: "", // Enter channel name
51
+ push: "" // Enter push token
52
+ },
53
+ data: {
54
+ // Enter data here
55
+ },
56
+ })
57
+ ```
package/dist/main.js ADDED
@@ -0,0 +1 @@
1
+ (()=>{var e={138:(e,t,n)=>{const r=n(218);e.exports={Fyno:class{wsid=process.env.FYNO_WSID;api_key=process.env.FYNO_API_KEY;env=process.env.FYNO_ENV||"prod";constructor(e=this.wsid,t=this.api_key,n=this.env){this.wsid=e,this.api_key=t,this.env=n,this.api_url=`https://api.fyno.io/v1/${this.wsid}${this.getENVUrl()}`,this.headers=this.getHeaders(),this.validate()}getENVUrl(){return"dev"===this.env?"/dev":""}getHeaders(){return{headers:{Authorization:`Bearer ${this.api_key}`,"Content-Type":"application/json"}}}validate(){if(!this.wsid||this.wsid.length<10||this.wsid.length>20)throw new Error(`Workspace ID value '${this.wsid}' is invalid`);if(!this.api_key||this.api_key.length<25||this.api_key.length>60)throw new Error(`API Key value '${this.api_key}' is invalid`);if(!["dev","prod"].includes(`${this.env}`))throw new Error(`Environment value '${this.env}' is invalid. It should be either 'prod' or 'dev'.`)}fire=async(e,t)=>new Promise(((n,o)=>{r.post(`${this.api_url}/event`,{event:e,...t},this.headers).then((e=>{n(e.data)})).catch((e=>{o(e.response.data)}))}))}}},218:(e,t,n)=>{"use strict";function r(e,t){return function(){return e.apply(t,arguments)}}const{toString:o}=Object.prototype,{getPrototypeOf:s}=Object,i=(a=Object.create(null),e=>{const t=o.call(e);return a[t]||(a[t]=t.slice(8,-1).toLowerCase())});var a;const c=e=>(e=e.toLowerCase(),t=>i(t)===e),u=e=>t=>typeof t===e,{isArray:l}=Array,f=u("undefined"),h=c("ArrayBuffer"),d=u("string"),p=u("function"),m=u("number"),y=e=>null!==e&&"object"==typeof e,g=e=>{if("object"!==i(e))return!1;const t=s(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||Symbol.toStringTag in e||Symbol.iterator in e)},b=c("Date"),w=c("File"),E=c("Blob"),O=c("FileList"),v=c("URLSearchParams");function S(e,t,{allOwnKeys:n=!1}={}){if(null==e)return;let r,o;if("object"!=typeof e&&(e=[e]),l(e))for(r=0,o=e.length;r<o;r++)t.call(null,e[r],r,e);else{const o=n?Object.getOwnPropertyNames(e):Object.keys(e),s=o.length;let i;for(r=0;r<s;r++)i=o[r],t.call(null,e[i],i,e)}}function R(e,t){t=t.toLowerCase();const n=Object.keys(e);let r,o=n.length;for(;o-- >0;)if(r=n[o],t===r.toLowerCase())return r;return null}const A="undefined"==typeof self?void 0===n.g?void 0:n.g:self,j=e=>!f(e)&&e!==A,T=(x="undefined"!=typeof Uint8Array&&s(Uint8Array),e=>x&&e instanceof x);var x;const N=c("HTMLFormElement"),_=(({hasOwnProperty:e})=>(t,n)=>e.call(t,n))(Object.prototype),C=c("RegExp"),P=(e,t)=>{const n=Object.getOwnPropertyDescriptors(e),r={};S(n,((n,o)=>{!1!==t(n,o,e)&&(r[o]=n)})),Object.defineProperties(e,r)};var B={isArray:l,isArrayBuffer:h,isBuffer:function(e){return null!==e&&!f(e)&&null!==e.constructor&&!f(e.constructor)&&p(e.constructor.isBuffer)&&e.constructor.isBuffer(e)},isFormData:e=>{const t="[object FormData]";return e&&("function"==typeof FormData&&e instanceof FormData||o.call(e)===t||p(e.toString)&&e.toString()===t)},isArrayBufferView:function(e){let t;return t="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&h(e.buffer),t},isString:d,isNumber:m,isBoolean:e=>!0===e||!1===e,isObject:y,isPlainObject:g,isUndefined:f,isDate:b,isFile:w,isBlob:E,isRegExp:C,isFunction:p,isStream:e=>y(e)&&p(e.pipe),isURLSearchParams:v,isTypedArray:T,isFileList:O,forEach:S,merge:function e(){const{caseless:t}=j(this)&&this||{},n={},r=(r,o)=>{const s=t&&R(n,o)||o;g(n[s])&&g(r)?n[s]=e(n[s],r):g(r)?n[s]=e({},r):l(r)?n[s]=r.slice():n[s]=r};for(let e=0,t=arguments.length;e<t;e++)arguments[e]&&S(arguments[e],r);return n},extend:(e,t,n,{allOwnKeys:o}={})=>(S(t,((t,o)=>{n&&p(t)?e[o]=r(t,n):e[o]=t}),{allOwnKeys:o}),e),trim:e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,""),stripBOM:e=>(65279===e.charCodeAt(0)&&(e=e.slice(1)),e),inherits:(e,t,n,r)=>{e.prototype=Object.create(t.prototype,r),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),n&&Object.assign(e.prototype,n)},toFlatObject:(e,t,n,r)=>{let o,i,a;const c={};if(t=t||{},null==e)return t;do{for(o=Object.getOwnPropertyNames(e),i=o.length;i-- >0;)a=o[i],r&&!r(a,e,t)||c[a]||(t[a]=e[a],c[a]=!0);e=!1!==n&&s(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t},kindOf:i,kindOfTest:c,endsWith:(e,t,n)=>{e=String(e),(void 0===n||n>e.length)&&(n=e.length),n-=t.length;const r=e.indexOf(t,n);return-1!==r&&r===n},toArray:e=>{if(!e)return null;if(l(e))return e;let t=e.length;if(!m(t))return null;const n=new Array(t);for(;t-- >0;)n[t]=e[t];return n},forEachEntry:(e,t)=>{const n=(e&&e[Symbol.iterator]).call(e);let r;for(;(r=n.next())&&!r.done;){const n=r.value;t.call(e,n[0],n[1])}},matchAll:(e,t)=>{let n;const r=[];for(;null!==(n=e.exec(t));)r.push(n);return r},isHTMLForm:N,hasOwnProperty:_,hasOwnProp:_,reduceDescriptors:P,freezeMethods:e=>{P(e,((t,n)=>{if(p(e)&&-1!==["arguments","caller","callee"].indexOf(n))return!1;const r=e[n];p(r)&&(t.enumerable=!1,"writable"in t?t.writable=!1:t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")}))}))},toObjectSet:(e,t)=>{const n={},r=e=>{e.forEach((e=>{n[e]=!0}))};return l(e)?r(e):r(String(e).split(t)),n},toCamelCase:e=>e.toLowerCase().replace(/[_-\s]([a-z\d])(\w*)/g,(function(e,t,n){return t.toUpperCase()+n})),noop:()=>{},toFiniteNumber:(e,t)=>(e=+e,Number.isFinite(e)?e:t),findKey:R,global:A,isContextDefined:j,toJSONObject:e=>{const t=new Array(10),n=(e,r)=>{if(y(e)){if(t.indexOf(e)>=0)return;if(!("toJSON"in e)){t[r]=e;const o=l(e)?[]:{};return S(e,((e,t)=>{const s=n(e,r+1);!f(s)&&(o[t]=s)})),t[r]=void 0,o}}return e};return n(e,0)}};function F(e,t,n,r,o){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=(new Error).stack,this.message=e,this.name="AxiosError",t&&(this.code=t),n&&(this.config=n),r&&(this.request=r),o&&(this.response=o)}B.inherits(F,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:B.toJSONObject(this.config),code:this.code,status:this.response&&this.response.status?this.response.status:null}}});const D=F.prototype,U={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach((e=>{U[e]={value:e}})),Object.defineProperties(F,U),Object.defineProperty(D,"isAxiosError",{value:!0}),F.from=(e,t,n,r,o,s)=>{const i=Object.create(D);return B.toFlatObject(e,i,(function(e){return e!==Error.prototype}),(e=>"isAxiosError"!==e)),F.call(i,e.message,t,n,r,o),i.cause=e,i.name=e.name,s&&Object.assign(i,s),i};var k="object"==typeof self?self.FormData:window.FormData;function L(e){return B.isPlainObject(e)||B.isArray(e)}function z(e){return B.endsWith(e,"[]")?e.slice(0,-2):e}function I(e,t,n){return e?e.concat(t).map((function(e,t){return e=z(e),!n&&t?"["+e+"]":e})).join(n?".":""):t}const J=B.toFlatObject(B,{},null,(function(e){return/^is[A-Z]/.test(e)}));function q(e,t,n){if(!B.isObject(e))throw new TypeError("target must be an object");t=t||new(k||FormData);const r=(n=B.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,(function(e,t){return!B.isUndefined(t[e])}))).metaTokens,o=n.visitor||l,s=n.dots,i=n.indexes,a=(n.Blob||"undefined"!=typeof Blob&&Blob)&&(c=t)&&B.isFunction(c.append)&&"FormData"===c[Symbol.toStringTag]&&c[Symbol.iterator];var c;if(!B.isFunction(o))throw new TypeError("visitor must be a function");function u(e){if(null===e)return"";if(B.isDate(e))return e.toISOString();if(!a&&B.isBlob(e))throw new F("Blob is not supported. Use a Buffer instead.");return B.isArrayBuffer(e)||B.isTypedArray(e)?a&&"function"==typeof Blob?new Blob([e]):Buffer.from(e):e}function l(e,n,o){let a=e;if(e&&!o&&"object"==typeof e)if(B.endsWith(n,"{}"))n=r?n:n.slice(0,-2),e=JSON.stringify(e);else if(B.isArray(e)&&function(e){return B.isArray(e)&&!e.some(L)}(e)||B.isFileList(e)||B.endsWith(n,"[]")&&(a=B.toArray(e)))return n=z(n),a.forEach((function(e,r){!B.isUndefined(e)&&null!==e&&t.append(!0===i?I([n],r,s):null===i?n:n+"[]",u(e))})),!1;return!!L(e)||(t.append(I(o,n,s),u(e)),!1)}const f=[],h=Object.assign(J,{defaultVisitor:l,convertValue:u,isVisitable:L});if(!B.isObject(e))throw new TypeError("data must be an object");return function e(n,r){if(!B.isUndefined(n)){if(-1!==f.indexOf(n))throw Error("Circular reference detected in "+r.join("."));f.push(n),B.forEach(n,(function(n,s){!0===(!(B.isUndefined(n)||null===n)&&o.call(t,n,B.isString(s)?s.trim():s,r,h))&&e(n,r?r.concat(s):[s])})),f.pop()}}(e),t}function M(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,(function(e){return t[e]}))}function W(e,t){this._pairs=[],e&&q(e,this,t)}const H=W.prototype;function K(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function V(e,t,n){if(!t)return e;const r=n&&n.encode||K,o=n&&n.serialize;let s;if(s=o?o(t,n):B.isURLSearchParams(t)?t.toString():new W(t,n).toString(r),s){const t=e.indexOf("#");-1!==t&&(e=e.slice(0,t)),e+=(-1===e.indexOf("?")?"?":"&")+s}return e}H.append=function(e,t){this._pairs.push([e,t])},H.toString=function(e){const t=e?function(t){return e.call(this,t,M)}:M;return this._pairs.map((function(e){return t(e[0])+"="+t(e[1])}),"").join("&")};var $=class{constructor(){this.handlers=[]}use(e,t,n){return this.handlers.push({fulfilled:e,rejected:t,synchronous:!!n&&n.synchronous,runWhen:n?n.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){B.forEach(this.handlers,(function(t){null!==t&&e(t)}))}},X={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},Y="undefined"!=typeof URLSearchParams?URLSearchParams:W,G=FormData;const Q=(()=>{let e;return("undefined"==typeof navigator||"ReactNative"!==(e=navigator.product)&&"NativeScript"!==e&&"NS"!==e)&&"undefined"!=typeof window&&"undefined"!=typeof document})(),Z="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts;var ee={isBrowser:!0,classes:{URLSearchParams:Y,FormData:G,Blob},isStandardBrowserEnv:Q,isStandardBrowserWebWorkerEnv:Z,protocols:["http","https","file","blob","url","data"]};function te(e){function t(e,n,r,o){let s=e[o++];const i=Number.isFinite(+s),a=o>=e.length;return s=!s&&B.isArray(r)?r.length:s,a?(B.hasOwnProp(r,s)?r[s]=[r[s],n]:r[s]=n,!i):(r[s]&&B.isObject(r[s])||(r[s]=[]),t(e,n,r[s],o)&&B.isArray(r[s])&&(r[s]=function(e){const t={},n=Object.keys(e);let r;const o=n.length;let s;for(r=0;r<o;r++)s=n[r],t[s]=e[s];return t}(r[s])),!i)}if(B.isFormData(e)&&B.isFunction(e.entries)){const n={};return B.forEachEntry(e,((e,r)=>{t(function(e){return B.matchAll(/\w+|\[(\w*)]/g,e).map((e=>"[]"===e[0]?"":e[1]||e[0]))}(e),r,n,0)})),n}return null}const ne={"Content-Type":void 0},re={transitional:X,adapter:["xhr","http"],transformRequest:[function(e,t){const n=t.getContentType()||"",r=n.indexOf("application/json")>-1,o=B.isObject(e);if(o&&B.isHTMLForm(e)&&(e=new FormData(e)),B.isFormData(e))return r&&r?JSON.stringify(te(e)):e;if(B.isArrayBuffer(e)||B.isBuffer(e)||B.isStream(e)||B.isFile(e)||B.isBlob(e))return e;if(B.isArrayBufferView(e))return e.buffer;if(B.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let s;if(o){if(n.indexOf("application/x-www-form-urlencoded")>-1)return function(e,t){return q(e,new ee.classes.URLSearchParams,Object.assign({visitor:function(e,t,n,r){return ee.isNode&&B.isBuffer(e)?(this.append(t,e.toString("base64")),!1):r.defaultVisitor.apply(this,arguments)}},t))}(e,this.formSerializer).toString();if((s=B.isFileList(e))||n.indexOf("multipart/form-data")>-1){const t=this.env&&this.env.FormData;return q(s?{"files[]":e}:e,t&&new t,this.formSerializer)}}return o||r?(t.setContentType("application/json",!1),function(e,t,n){if(B.isString(e))try{return(0,JSON.parse)(e),B.trim(e)}catch(e){if("SyntaxError"!==e.name)throw e}return(0,JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){const t=this.transitional||re.transitional,n=t&&t.forcedJSONParsing,r="json"===this.responseType;if(e&&B.isString(e)&&(n&&!this.responseType||r)){const n=!(t&&t.silentJSONParsing)&&r;try{return JSON.parse(e)}catch(e){if(n){if("SyntaxError"===e.name)throw F.from(e,F.ERR_BAD_RESPONSE,this,null,this.response);throw e}}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:ee.classes.FormData,Blob:ee.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*"}}};B.forEach(["delete","get","head"],(function(e){re.headers[e]={}})),B.forEach(["post","put","patch"],(function(e){re.headers[e]=B.merge(ne)}));var oe=re;const se=B.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),ie=Symbol("internals");function ae(e){return e&&String(e).trim().toLowerCase()}function ce(e){return!1===e||null==e?e:B.isArray(e)?e.map(ce):String(e)}function ue(e,t,n,r){return B.isFunction(r)?r.call(this,t,n):B.isString(t)?B.isString(r)?-1!==t.indexOf(r):B.isRegExp(r)?r.test(t):void 0:void 0}class le{constructor(e){e&&this.set(e)}set(e,t,n){const r=this;function o(e,t,n){const o=ae(t);if(!o)throw new Error("header name must be a non-empty string");const s=B.findKey(r,o);(!s||void 0===r[s]||!0===n||void 0===n&&!1!==r[s])&&(r[s||t]=ce(e))}const s=(e,t)=>B.forEach(e,((e,n)=>o(e,n,t)));return B.isPlainObject(e)||e instanceof this.constructor?s(e,t):B.isString(e)&&(e=e.trim())&&!/^[-_a-zA-Z]+$/.test(e.trim())?s((e=>{const t={};let n,r,o;return e&&e.split("\n").forEach((function(e){o=e.indexOf(":"),n=e.substring(0,o).trim().toLowerCase(),r=e.substring(o+1).trim(),!n||t[n]&&se[n]||("set-cookie"===n?t[n]?t[n].push(r):t[n]=[r]:t[n]=t[n]?t[n]+", "+r:r)})),t})(e),t):null!=e&&o(t,e,n),this}get(e,t){if(e=ae(e)){const n=B.findKey(this,e);if(n){const e=this[n];if(!t)return e;if(!0===t)return function(e){const t=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let r;for(;r=n.exec(e);)t[r[1]]=r[2];return t}(e);if(B.isFunction(t))return t.call(this,e,n);if(B.isRegExp(t))return t.exec(e);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=ae(e)){const n=B.findKey(this,e);return!(!n||t&&!ue(0,this[n],n,t))}return!1}delete(e,t){const n=this;let r=!1;function o(e){if(e=ae(e)){const o=B.findKey(n,e);!o||t&&!ue(0,n[o],o,t)||(delete n[o],r=!0)}}return B.isArray(e)?e.forEach(o):o(e),r}clear(){return Object.keys(this).forEach(this.delete.bind(this))}normalize(e){const t=this,n={};return B.forEach(this,((r,o)=>{const s=B.findKey(n,o);if(s)return t[s]=ce(r),void delete t[o];const i=e?function(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,((e,t,n)=>t.toUpperCase()+n))}(o):String(o).trim();i!==o&&delete t[o],t[i]=ce(r),n[i]=!0})),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const t=Object.create(null);return B.forEach(this,((n,r)=>{null!=n&&!1!==n&&(t[r]=e&&B.isArray(n)?n.join(", "):n)})),t}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map((([e,t])=>e+": "+t)).join("\n")}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...t){const n=new this(e);return t.forEach((e=>n.set(e))),n}static accessor(e){const t=(this[ie]=this[ie]={accessors:{}}).accessors,n=this.prototype;function r(e){const r=ae(e);t[r]||(function(e,t){const n=B.toCamelCase(" "+t);["get","set","has"].forEach((r=>{Object.defineProperty(e,r+n,{value:function(e,n,o){return this[r].call(this,t,e,n,o)},configurable:!0})}))}(n,e),t[r]=!0)}return B.isArray(e)?e.forEach(r):r(e),this}}le.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent"]),B.freezeMethods(le.prototype),B.freezeMethods(le);var fe=le;function he(e,t){const n=this||oe,r=t||n,o=fe.from(r.headers);let s=r.data;return B.forEach(e,(function(e){s=e.call(n,s,o.normalize(),t?t.status:void 0)})),o.normalize(),s}function de(e){return!(!e||!e.__CANCEL__)}function pe(e,t,n){F.call(this,null==e?"canceled":e,F.ERR_CANCELED,t,n),this.name="CanceledError"}B.inherits(pe,F,{__CANCEL__:!0});var me=ee.isStandardBrowserEnv?{write:function(e,t,n,r,o,s){const i=[];i.push(e+"="+encodeURIComponent(t)),B.isNumber(n)&&i.push("expires="+new Date(n).toGMTString()),B.isString(r)&&i.push("path="+r),B.isString(o)&&i.push("domain="+o),!0===s&&i.push("secure"),document.cookie=i.join("; ")},read:function(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove:function(e){this.write(e,"",Date.now()-864e5)}}:{write:function(){},read:function(){return null},remove:function(){}};function ye(e,t){return e&&!/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t)?function(e,t){return t?e.replace(/\/+$/,"")+"/"+t.replace(/^\/+/,""):e}(e,t):t}var ge=ee.isStandardBrowserEnv?function(){const e=/(msie|trident)/i.test(navigator.userAgent),t=document.createElement("a");let n;function r(n){let r=n;return e&&(t.setAttribute("href",r),r=t.href),t.setAttribute("href",r),{href:t.href,protocol:t.protocol?t.protocol.replace(/:$/,""):"",host:t.host,search:t.search?t.search.replace(/^\?/,""):"",hash:t.hash?t.hash.replace(/^#/,""):"",hostname:t.hostname,port:t.port,pathname:"/"===t.pathname.charAt(0)?t.pathname:"/"+t.pathname}}return n=r(window.location.href),function(e){const t=B.isString(e)?r(e):e;return t.protocol===n.protocol&&t.host===n.host}}():function(){return!0};function be(e,t){let n=0;const r=function(e,t){e=e||10;const n=new Array(e),r=new Array(e);let o,s=0,i=0;return t=void 0!==t?t:1e3,function(a){const c=Date.now(),u=r[i];o||(o=c),n[s]=a,r[s]=c;let l=i,f=0;for(;l!==s;)f+=n[l++],l%=e;if(s=(s+1)%e,s===i&&(i=(i+1)%e),c-o<t)return;const h=u&&c-u;return h?Math.round(1e3*f/h):void 0}}(50,250);return o=>{const s=o.loaded,i=o.lengthComputable?o.total:void 0,a=s-n,c=r(a);n=s;const u={loaded:s,total:i,progress:i?s/i:void 0,bytes:a,rate:c||void 0,estimated:c&&i&&s<=i?(i-s)/c:void 0,event:o};u[t?"download":"upload"]=!0,e(u)}}const we={http:null,xhr:"undefined"!=typeof XMLHttpRequest&&function(e){return new Promise((function(t,n){let r=e.data;const o=fe.from(e.headers).normalize(),s=e.responseType;let i;function a(){e.cancelToken&&e.cancelToken.unsubscribe(i),e.signal&&e.signal.removeEventListener("abort",i)}B.isFormData(r)&&(ee.isStandardBrowserEnv||ee.isStandardBrowserWebWorkerEnv)&&o.setContentType(!1);let c=new XMLHttpRequest;if(e.auth){const t=e.auth.username||"",n=e.auth.password?unescape(encodeURIComponent(e.auth.password)):"";o.set("Authorization","Basic "+btoa(t+":"+n))}const u=ye(e.baseURL,e.url);function l(){if(!c)return;const r=fe.from("getAllResponseHeaders"in c&&c.getAllResponseHeaders());!function(e,t,n){const r=n.config.validateStatus;n.status&&r&&!r(n.status)?t(new F("Request failed with status code "+n.status,[F.ERR_BAD_REQUEST,F.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n)):e(n)}((function(e){t(e),a()}),(function(e){n(e),a()}),{data:s&&"text"!==s&&"json"!==s?c.response:c.responseText,status:c.status,statusText:c.statusText,headers:r,config:e,request:c}),c=null}if(c.open(e.method.toUpperCase(),V(u,e.params,e.paramsSerializer),!0),c.timeout=e.timeout,"onloadend"in c?c.onloadend=l:c.onreadystatechange=function(){c&&4===c.readyState&&(0!==c.status||c.responseURL&&0===c.responseURL.indexOf("file:"))&&setTimeout(l)},c.onabort=function(){c&&(n(new F("Request aborted",F.ECONNABORTED,e,c)),c=null)},c.onerror=function(){n(new F("Network Error",F.ERR_NETWORK,e,c)),c=null},c.ontimeout=function(){let t=e.timeout?"timeout of "+e.timeout+"ms exceeded":"timeout exceeded";const r=e.transitional||X;e.timeoutErrorMessage&&(t=e.timeoutErrorMessage),n(new F(t,r.clarifyTimeoutError?F.ETIMEDOUT:F.ECONNABORTED,e,c)),c=null},ee.isStandardBrowserEnv){const t=(e.withCredentials||ge(u))&&e.xsrfCookieName&&me.read(e.xsrfCookieName);t&&o.set(e.xsrfHeaderName,t)}void 0===r&&o.setContentType(null),"setRequestHeader"in c&&B.forEach(o.toJSON(),(function(e,t){c.setRequestHeader(t,e)})),B.isUndefined(e.withCredentials)||(c.withCredentials=!!e.withCredentials),s&&"json"!==s&&(c.responseType=e.responseType),"function"==typeof e.onDownloadProgress&&c.addEventListener("progress",be(e.onDownloadProgress,!0)),"function"==typeof e.onUploadProgress&&c.upload&&c.upload.addEventListener("progress",be(e.onUploadProgress)),(e.cancelToken||e.signal)&&(i=t=>{c&&(n(!t||t.type?new pe(null,e,c):t),c.abort(),c=null)},e.cancelToken&&e.cancelToken.subscribe(i),e.signal&&(e.signal.aborted?i():e.signal.addEventListener("abort",i)));const f=function(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}(u);f&&-1===ee.protocols.indexOf(f)?n(new F("Unsupported protocol "+f+":",F.ERR_BAD_REQUEST,e)):c.send(r||null)}))}};B.forEach(we,((e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch(e){}Object.defineProperty(e,"adapterName",{value:t})}}));function Ee(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new pe(null,e)}function Oe(e){return Ee(e),e.headers=fe.from(e.headers),e.data=he.call(e,e.transformRequest),-1!==["post","put","patch"].indexOf(e.method)&&e.headers.setContentType("application/x-www-form-urlencoded",!1),(e=>{e=B.isArray(e)?e:[e];const{length:t}=e;let n,r;for(let o=0;o<t&&(n=e[o],!(r=B.isString(n)?we[n.toLowerCase()]:n));o++);if(!r){if(!1===r)throw new F(`Adapter ${n} is not supported by the environment`,"ERR_NOT_SUPPORT");throw new Error(B.hasOwnProp(we,n)?`Adapter '${n}' is not available in the build`:`Unknown adapter '${n}'`)}if(!B.isFunction(r))throw new TypeError("adapter is not a function");return r})(e.adapter||oe.adapter)(e).then((function(t){return Ee(e),t.data=he.call(e,e.transformResponse,t),t.headers=fe.from(t.headers),t}),(function(t){return de(t)||(Ee(e),t&&t.response&&(t.response.data=he.call(e,e.transformResponse,t.response),t.response.headers=fe.from(t.response.headers))),Promise.reject(t)}))}const ve=e=>e instanceof fe?e.toJSON():e;function Se(e,t){t=t||{};const n={};function r(e,t,n){return B.isPlainObject(e)&&B.isPlainObject(t)?B.merge.call({caseless:n},e,t):B.isPlainObject(t)?B.merge({},t):B.isArray(t)?t.slice():t}function o(e,t,n){return B.isUndefined(t)?B.isUndefined(e)?void 0:r(void 0,e,n):r(e,t,n)}function s(e,t){if(!B.isUndefined(t))return r(void 0,t)}function i(e,t){return B.isUndefined(t)?B.isUndefined(e)?void 0:r(void 0,e):r(void 0,t)}function a(n,o,s){return s in t?r(n,o):s in e?r(void 0,n):void 0}const c={url:s,method:s,data:s,baseURL:i,transformRequest:i,transformResponse:i,paramsSerializer:i,timeout:i,timeoutMessage:i,withCredentials:i,adapter:i,responseType:i,xsrfCookieName:i,xsrfHeaderName:i,onUploadProgress:i,onDownloadProgress:i,decompress:i,maxContentLength:i,maxBodyLength:i,beforeRedirect:i,transport:i,httpAgent:i,httpsAgent:i,cancelToken:i,socketPath:i,responseEncoding:i,validateStatus:a,headers:(e,t)=>o(ve(e),ve(t),!0)};return B.forEach(Object.keys(e).concat(Object.keys(t)),(function(r){const s=c[r]||o,i=s(e[r],t[r],r);B.isUndefined(i)&&s!==a||(n[r]=i)})),n}const Re={};["object","boolean","number","function","string","symbol"].forEach(((e,t)=>{Re[e]=function(n){return typeof n===e||"a"+(t<1?"n ":" ")+e}}));const Ae={};Re.transitional=function(e,t,n){function r(e,t){return"[Axios v1.2.1] Transitional option '"+e+"'"+t+(n?". "+n:"")}return(n,o,s)=>{if(!1===e)throw new F(r(o," has been removed"+(t?" in "+t:"")),F.ERR_DEPRECATED);return t&&!Ae[o]&&(Ae[o]=!0,console.warn(r(o," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(n,o,s)}};var je={assertOptions:function(e,t,n){if("object"!=typeof e)throw new F("options must be an object",F.ERR_BAD_OPTION_VALUE);const r=Object.keys(e);let o=r.length;for(;o-- >0;){const s=r[o],i=t[s];if(i){const t=e[s],n=void 0===t||i(t,s,e);if(!0!==n)throw new F("option "+s+" must be "+n,F.ERR_BAD_OPTION_VALUE)}else if(!0!==n)throw new F("Unknown option "+s,F.ERR_BAD_OPTION)}},validators:Re};const Te=je.validators;class xe{constructor(e){this.defaults=e,this.interceptors={request:new $,response:new $}}request(e,t){"string"==typeof e?(t=t||{}).url=e:t=e||{},t=Se(this.defaults,t);const{transitional:n,paramsSerializer:r,headers:o}=t;let s;void 0!==n&&je.assertOptions(n,{silentJSONParsing:Te.transitional(Te.boolean),forcedJSONParsing:Te.transitional(Te.boolean),clarifyTimeoutError:Te.transitional(Te.boolean)},!1),void 0!==r&&je.assertOptions(r,{encode:Te.function,serialize:Te.function},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase(),s=o&&B.merge(o.common,o[t.method]),s&&B.forEach(["delete","get","head","post","put","patch","common"],(e=>{delete o[e]})),t.headers=fe.concat(s,o);const i=[];let a=!0;this.interceptors.request.forEach((function(e){"function"==typeof e.runWhen&&!1===e.runWhen(t)||(a=a&&e.synchronous,i.unshift(e.fulfilled,e.rejected))}));const c=[];let u;this.interceptors.response.forEach((function(e){c.push(e.fulfilled,e.rejected)}));let l,f=0;if(!a){const e=[Oe.bind(this),void 0];for(e.unshift.apply(e,i),e.push.apply(e,c),l=e.length,u=Promise.resolve(t);f<l;)u=u.then(e[f++],e[f++]);return u}l=i.length;let h=t;for(f=0;f<l;){const e=i[f++],t=i[f++];try{h=e(h)}catch(e){t.call(this,e);break}}try{u=Oe.call(this,h)}catch(e){return Promise.reject(e)}for(f=0,l=c.length;f<l;)u=u.then(c[f++],c[f++]);return u}getUri(e){return V(ye((e=Se(this.defaults,e)).baseURL,e.url),e.params,e.paramsSerializer)}}B.forEach(["delete","get","head","options"],(function(e){xe.prototype[e]=function(t,n){return this.request(Se(n||{},{method:e,url:t,data:(n||{}).data}))}})),B.forEach(["post","put","patch"],(function(e){function t(t){return function(n,r,o){return this.request(Se(o||{},{method:e,headers:t?{"Content-Type":"multipart/form-data"}:{},url:n,data:r}))}}xe.prototype[e]=t(),xe.prototype[e+"Form"]=t(!0)}));var Ne=xe;class _e{constructor(e){if("function"!=typeof e)throw new TypeError("executor must be a function.");let t;this.promise=new Promise((function(e){t=e}));const n=this;this.promise.then((e=>{if(!n._listeners)return;let t=n._listeners.length;for(;t-- >0;)n._listeners[t](e);n._listeners=null})),this.promise.then=e=>{let t;const r=new Promise((e=>{n.subscribe(e),t=e})).then(e);return r.cancel=function(){n.unsubscribe(t)},r},e((function(e,r,o){n.reason||(n.reason=new pe(e,r,o),t(n.reason))}))}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){this.reason?e(this.reason):this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const t=this._listeners.indexOf(e);-1!==t&&this._listeners.splice(t,1)}static source(){let e;return{token:new _e((function(t){e=t})),cancel:e}}}var Ce=_e;const Pe=function e(t){const n=new Ne(t),o=r(Ne.prototype.request,n);return B.extend(o,Ne.prototype,n,{allOwnKeys:!0}),B.extend(o,n,null,{allOwnKeys:!0}),o.create=function(n){return e(Se(t,n))},o}(oe);Pe.Axios=Ne,Pe.CanceledError=pe,Pe.CancelToken=Ce,Pe.isCancel=de,Pe.VERSION="1.2.1",Pe.toFormData=q,Pe.AxiosError=F,Pe.Cancel=Pe.CanceledError,Pe.all=function(e){return Promise.all(e)},Pe.spread=function(e){return function(t){return e.apply(null,t)}},Pe.isAxiosError=function(e){return B.isObject(e)&&!0===e.isAxiosError},Pe.mergeConfig=Se,Pe.AxiosHeaders=fe,Pe.formToJSON=e=>te(B.isHTMLForm(e)?new FormData(e):e),Pe.default=Pe,e.exports=Pe}},t={};function n(r){var o=t[r];if(void 0!==o)return o.exports;var s=t[r]={exports:{}};return e[r](s,s.exports,n),s.exports}n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),n(138)})();
package/package.json ADDED
@@ -0,0 +1,42 @@
1
+ {
2
+ "name": "@fyno/node",
3
+ "version": "1.1.0",
4
+ "description": "This is the official Node.js module for sending notifications through Fyno.io.",
5
+ "main": "src/index.js",
6
+ "scripts": {
7
+ "prepare": "npm run build",
8
+ "build": "webpack --mode production",
9
+ "test": "jest index.spec.js --runInBand"
10
+ },
11
+ "keywords": [
12
+ "notifications",
13
+ "notification infrastructure",
14
+ "email",
15
+ "sms",
16
+ "whatsapp",
17
+ "slack",
18
+ "discord",
19
+ "teams",
20
+ "push"
21
+ ],
22
+ "author": "",
23
+ "license": "MIT",
24
+ "devDependencies": {
25
+ "@types/jest": "^29.2.4",
26
+ "jest": "^29.3.1",
27
+ "prettier": "^2.8.0",
28
+ "webpack-cli": "^5.0.1"
29
+ },
30
+ "dependencies": {
31
+ "@types/node": "^18.11.11",
32
+ "axios": "^1.2.0",
33
+ "moment": "^2.29.4"
34
+ },
35
+ "repository": {
36
+ "type": "git",
37
+ "url": "https://github.com/fynoio/node-sdk.git"
38
+ },
39
+ "publishConfig": {
40
+ "registry": "https://registry.npmjs.org"
41
+ }
42
+ }
package/src/index.js ADDED
@@ -0,0 +1,69 @@
1
+ const axios = require("axios");
2
+
3
+ const API_URL = "https://api.fyno.io/v1/";
4
+
5
+ class Fyno {
6
+ wsid = process.env.FYNO_WSID;
7
+ api_key = process.env.FYNO_API_KEY;
8
+ env = process.env.FYNO_ENV || "prod";
9
+
10
+ constructor(wsid = this.wsid, api_key = this.api_key, env = this.env) {
11
+ this.wsid = wsid;
12
+ this.api_key = api_key;
13
+ this.env = env;
14
+ this.api_url = `${API_URL}${this.wsid}${this.getENVUrl()}`;
15
+ this.headers = this.getHeaders();
16
+
17
+ this.validate();
18
+ }
19
+
20
+ getENVUrl() {
21
+ return `${this.env === "dev" ? "/dev" : ""}`;
22
+ }
23
+
24
+ getHeaders() {
25
+ return {
26
+ headers: {
27
+ Authorization: `Bearer ${this.api_key}`,
28
+ "Content-Type": "application/json",
29
+ },
30
+ };
31
+ }
32
+
33
+ validate() {
34
+ if (!this.wsid || this.wsid.length < 10 || this.wsid.length > 20) {
35
+ throw new Error(`Workspace ID value '${this.wsid}' is invalid`);
36
+ } else if (
37
+ !this.api_key ||
38
+ this.api_key.length < 25 ||
39
+ this.api_key.length > 60
40
+ ) {
41
+ throw new Error(`API Key value '${this.api_key}' is invalid`);
42
+ } else if (!["dev", "prod"].includes(`${this.env}`)) {
43
+ throw new Error(
44
+ `Environment value '${this.env}' is invalid. It should be either 'prod' or 'dev'.`
45
+ );
46
+ }
47
+ }
48
+
49
+ fire = async (event, payload) => {
50
+ return new Promise((resolve, reject) => {
51
+ axios
52
+ .post(
53
+ `${this.api_url}/event`,
54
+ { event, ...payload },
55
+ this.headers
56
+ )
57
+ .then((resp) => {
58
+ resolve(resp.data);
59
+ })
60
+ .catch((error) => {
61
+ reject(error.response.data);
62
+ });
63
+ });
64
+ };
65
+ }
66
+
67
+ module.exports = {
68
+ Fyno,
69
+ };
@@ -0,0 +1,152 @@
1
+ const { Fyno } = require("../src");
2
+ const moment = require("moment");
3
+
4
+ const to = {
5
+ sms: "",
6
+ whatsapp: "",
7
+ email: "",
8
+ slack: "ashwin@fyno.io",
9
+ discord: "",
10
+ teams: "",
11
+ push: "",
12
+ };
13
+
14
+ const data = {
15
+ name: "Ashwin",
16
+ sdk: "Node.js",
17
+ };
18
+
19
+ const event_name = "test-cases";
20
+
21
+ const success_response = {
22
+ request_id: expect.anything(),
23
+ event: event_name,
24
+ response: {
25
+ sms: {
26
+ status: "error",
27
+ message: expect.anything(),
28
+ },
29
+ whatsapp: {
30
+ status: "error",
31
+ message: expect.anything(),
32
+ },
33
+ email: {
34
+ status: "error",
35
+ message: expect.anything(),
36
+ },
37
+ slack: {
38
+ status: "ok",
39
+ destination: to.slack,
40
+ msg_id: expect.anything(),
41
+ },
42
+ discord: {
43
+ status: "error",
44
+ message: expect.anything(),
45
+ },
46
+ teams: {
47
+ status: "error",
48
+ message: expect.anything(),
49
+ },
50
+ push: {
51
+ status: "error",
52
+ message: expect.anything(),
53
+ },
54
+ },
55
+ };
56
+
57
+ const failure_response = {
58
+ status: "error",
59
+ _message: "Invalid API details",
60
+ };
61
+
62
+ describe("Firing an event should", () => {
63
+ test("Fail when WSID supplied is incorrect", async () => {
64
+ let response;
65
+
66
+ try {
67
+ const fyno = new Fyno("12345678910");
68
+ response = await fyno.fire(event_name, { to, data });
69
+ } catch (e) {
70
+ response = e;
71
+ }
72
+
73
+ expect(response).toMatchObject(failure_response);
74
+ });
75
+ test("Fail when WSID supplied is invalid", async () => {
76
+ let response;
77
+
78
+ try {
79
+ const fyno = new Fyno("12345");
80
+ } catch (e) {
81
+ response = e.message;
82
+ }
83
+
84
+ expect(response).toBe(`Workspace ID value '12345' is invalid`);
85
+ });
86
+ test("Fail when API Key supplied is incorrect", async () => {
87
+ let response;
88
+
89
+ try {
90
+ const fyno = new Fyno(
91
+ (wsid = undefined),
92
+ (api_key = "ABCDEFG.++HIJKLMNOPQRSTUVWXYZ012345678910")
93
+ );
94
+ response = await fyno.fire("event_name", { to, data });
95
+ } catch (e) {
96
+ response = e;
97
+ }
98
+
99
+ expect(response).toMatchObject(failure_response);
100
+ });
101
+ test("Fail when API Key supplied is invalid", async () => {
102
+ let response;
103
+
104
+ try {
105
+ const fyno = new Fyno((wsid = undefined), (api_key = "12345"));
106
+ } catch (e) {
107
+ response = e.message;
108
+ }
109
+
110
+ expect(response).toBe(`API Key value '12345' is invalid`);
111
+ });
112
+ test("Fail when ENV supplied is invalid", async () => {
113
+ let response;
114
+ try {
115
+ const fyno = new Fyno(undefined, undefined, "random");
116
+ } catch (e) {
117
+ response = e.message;
118
+ }
119
+
120
+ expect(response).toBe(
121
+ `Environment value 'random' is invalid. It should be either 'prod' or 'dev'.`
122
+ );
123
+ });
124
+ test("Work when all credentials are correct and supplied through ENV file", async () => {
125
+ const fyno = new Fyno();
126
+ const unix_time = moment().valueOf();
127
+ const response = await fyno.fire(event_name, { to, data });
128
+
129
+ expect(response.received_time).toBeGreaterThanOrEqual(unix_time);
130
+ expect(response).toMatchObject(success_response);
131
+ });
132
+ test("Work when all credentials are correct and supplied manually", async () => {
133
+ const fyno = new Fyno(
134
+ process.env.FYNO_WSID,
135
+ process.env.FYNO_API_KEY,
136
+ process.env.FYNO_ENV
137
+ );
138
+ const unix_time = moment().valueOf();
139
+ const response = await fyno.fire(event_name, { to, data });
140
+
141
+ expect(response.received_time).toBeGreaterThanOrEqual(unix_time);
142
+ expect(response).toMatchObject(success_response);
143
+ });
144
+ test("Work when all credentals are correct and supplied manually and through ENV files", async () => {
145
+ const fyno = new Fyno(process.env.FYNO_WSID);
146
+ const unix_time = moment().valueOf();
147
+ const response = await fyno.fire(event_name, { to, data });
148
+
149
+ expect(response.received_time).toBeGreaterThanOrEqual(unix_time);
150
+ expect(response).toMatchObject(success_response);
151
+ });
152
+ });
@@ -0,0 +1 @@
1
+ require("./event.test.js");