Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@opensea/vessel

Package Overview
Dependencies
Maintainers
7
Versions
609
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@opensea/vessel - npm Package Compare versions

Comparing version 0.1.0 to 0.2.0

dist/src/type-utils.d.ts

2

dist/index.js

@@ -1,2 +0,2 @@

var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};function e(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function i(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}var n=function(){return n=Object.assign||function(t){for(var e,n=1,i=arguments.length;n<i;n++)for(var o in e=arguments[n])Object.prototype.hasOwnProperty.call(e,o)&&(t[o]=e[o]);return t},n.apply(this,arguments)};function i(t,e,n,i){return new(n||(n=Promise))((function(o,s){function r(t){try{c(i.next(t))}catch(t){s(t)}}function a(t){try{c(i.throw(t))}catch(t){s(t)}}function c(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,a)}c((i=i.apply(t,e||[])).next())}))}function o(t,e){var n,i,o,s,r={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return s={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(a){return function(c){return function(a){if(n)throw new TypeError("Generator is already executing.");for(;s&&(s=0,a[0]&&(r=0)),r;)try{if(n=1,i&&(o=2&a[0]?i.return:a[0]?i.throw||((o=i.return)&&o.call(i),0):i.next)&&!(o=o.call(i,a[1])).done)return o;switch(i=0,o&&(a=[2&a[0],o.value]),a[0]){case 0:case 1:o=a;break;case 4:return r.label++,{value:a[1],done:!1};case 5:r.label++,i=a[1],a=[0];continue;case 7:a=r.ops.pop(),r.trys.pop();continue;default:if(!(o=r.trys,(o=o.length>0&&o[o.length-1])||6!==a[0]&&2!==a[0])){r=0;continue}if(3===a[0]&&(!o||a[1]>o[0]&&a[1]<o[3])){r.label=a[1];break}if(6===a[0]&&r.label<o[1]){r.label=o[1],o=a;break}if(o&&r.label<o[2]){r.label=o[2],r.ops.push(a);break}o[2]&&r.ops.pop(),r.trys.pop();continue}a=e.call(t,r)}catch(t){a=[6,t],i=0}finally{n=o=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,c])}}}function s(t,e,n){if(n||2===arguments.length)for(var i,o=0,s=e.length;o<s;o++)!i&&o in e||(i||(i=Array.prototype.slice.call(e,0,o)),i[o]=e[o]);return t.concat(i||Array.prototype.slice.call(e))}"function"==typeof SuppressedError&&SuppressedError;var r=function(t){function n(e,n,i){void 0===i&&(i=1);var o=t.call(this,"Failed to receive response for message ".concat(e.id," within ").concat(n,"ms. Payload: ").concat(JSON.stringify(e.payload)))||this;return o.name="TimeoutError",o.postedMessage=e,o.timeout=n,o.attempts=i,o}return e(n,t),n}(function(t){function n(){var e=null!==t&&t.apply(this,arguments)||this;return e.type="VesselError",e}return e(n,t),n}(Error)),a=function(t){function n(e,n,i){var o=t.call(this,e,n)||this;return o.name="HandshakeTimeoutError",o.message="Failed to receive handshake response within ".concat(n,"ms after ").concat(i," attempts. Payload: ").concat(JSON.stringify(e.payload)),o.attempts=i,o}return e(n,t),n}(r),c=function(){function t(t){var e=void 0===t?{}:t,n=e.iframe,i=e.targetOrigin,o=void 0===i?"*":i,s=e.application,r=void 0===s?"opensea-vessel":s,a=e.debug,c=void 0!==a&&a,u=e.handshakeTimeout,h=void 0===u?1e4:u,d=e.defaultTimeout,l=void 0===d?5e3:d,p=this;this.listeners=new Map,this.sentMessageCount=BigInt(0),this.connected=!1,this.createResponseId=function(){return"".concat(p.createId(),"r")},this.isResponseId=function(t){return t.endsWith("r")},this.createHandshakeId=function(){return"".concat(p.createId(),"h")},this.isHandshakeId=function(t){return t.endsWith("h")},this.type=n?"parent":"child",this.frame=n,this.targetOrigin=o,this.application=r,this.debug=c,this.handshakeTimeout=h,this.defaultTimeout=l,this.origin=window.location.origin,this.addListener("message",this.handshakeMessageListener.bind(this)),this.windowMessageEventListener=this.handleMessageEvent.bind(this),window.addEventListener("message",this.windowMessageEventListener)}return t.prototype.cleanup=function(){window.removeEventListener("message",this.windowMessageEventListener)},t.prototype.addListener=function(t,e){var n=this,i=this.listeners.get(t);return this.listeners.set(t,i?s(s([],i,!0),[e],!1):[e]),function(){var o;n.listeners.set(t,null!==(o=null==i?void 0:i.filter((function(t){return t!==e})))&&void 0!==o?o:[])}},t.prototype.removeListener=function(t,e){var n,i=this.listeners.get(t);this.listeners.set(t,null!==(n=null==i?void 0:i.filter((function(t){return t!==e})))&&void 0!==n?n:[])},t.prototype.handshake=function(){return i(this,void 0,void 0,(function(){return o(this,(function(t){return this.handshakePromise||(this.handshakePromise=this.sendHandshakeMessage()),[2,this.handshakePromise]}))}))},t.prototype.send=function(t,e){return void 0===e&&(e={}),i(this,void 0,void 0,(function(){return o(this,(function(i){switch(i.label){case 0:return this.connected?[3,2]:[4,this.handshake()];case 1:i.sent(),i.label=2;case 2:return[2,this.sendMessage({id:this.createId(),payload:t,application:this.application},n(n({},e),{timeout:"timeout"in e?e.timeout:this.defaultTimeout}))]}}))}))},t.prototype.debugLog=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];this.debug&&console.debug.apply(console,s(["[".concat(this.type,"]")],t,!1))},t.prototype.debugTime=function(t){this.debug&&console.time("[".concat(this.type,"] ").concat(t))},t.prototype.debugTimeEnd=function(t){this.debug&&console.timeEnd("[".concat(this.type,"] ").concat(t))},t.prototype.warn=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];console.warn.apply(console,s(["[".concat(this.type,"]")],t,!1))},t.prototype.createId=function(){return"".concat(this.type[0]).concat(this.sentMessageCount++)},t.prototype.postMessage=function(t){var e,n;this.debugLog("Posting message from ".concat(this.origin," to ").concat(this.targetOrigin),t),"parent"===this.type?null===(n=null===(e=this.frame)||void 0===e?void 0:e.contentWindow)||void 0===n||n.postMessage(t,this.targetOrigin):window.parent.postMessage(t,this.targetOrigin)},t.prototype.sendMessage=function(t,e){var n=(void 0===e?{}:e).timeout;return i(this,void 0,void 0,(function(){var e=this;return o(this,(function(i){return[2,new Promise((function(i,o){var s;void 0!==n&&(s=setTimeout((function(){o(new r(t,n)),e.removeListener("message",c)}),n));var a=t.id,c=function(t){var n=t;return n.originalId===a&&(e.debugTimeEnd(a),e.debugLog("Received response from ".concat(e.targetOrigin),n),clearTimeout(s),n.error?o(n.payload):(e.removeListener("message",c),i(n)),!0)};e.addListener("message",c),e.debugTime(t.id),e.postMessage(t)}))]}))}))},t.prototype.sendMessageWithRetries=function(t,e){var n=this,i=void 0===e?{}:e,o=i.interval,s=void 0===o?100:o,a=i.timeout;return new Promise((function(e,i){var o,c=1;n.sendMessage(t,{timeout:a}).then(e).catch((function(t){i(t instanceof r?new r(t.postedMessage,t.timeout,c):t)})).finally((function(){clearInterval(o)}));var u=function(){n.debugLog("Retrying message ".concat(t.id)),n.postMessage(t),c++,o=setTimeout(u,s)};o=setTimeout(u,s)}))},t.prototype.reply=function(t,e,n){void 0===e&&(e=void 0);var i=(void 0===n?{}:n).error;this.postMessage({id:this.createResponseId(),payload:e,application:this.application,originalId:t.id,error:i})},t.prototype.handleMessageEvent=function(t){var e;if(t.data.application===this.application&&("*"===this.targetOrigin||t.origin===this.targetOrigin)){this.debugLog("Received message from ".concat(t.origin),t.data);for(var n=!1,i=0,o=null!==(e=this.listeners.get("message"))&&void 0!==e?e:[];i<o.length;i++){var s=(0,o[i])(t.data,this.reply.bind(this,t.data));s&&n&&this.warn("Message was handled by multiple listeners",t.data),n||(n=s)}var r=this.isResponseId(t.data.id);n||r||this.warn("Message was not handled",t.data)}},t.prototype.connect=function(t){var e,n=this;this.connected=!0;for(var i=0,o=null!==(e=this.listeners.get("connect"))&&void 0!==e?e:[];i<o.length;i++){(0,o[i])(t,(function(){n.warn("Using reply function on connect event is not supported")}))}},t.prototype.sendHandshakeMessage=function(){return i(this,void 0,void 0,(function(){var t,e;return o(this,(function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,this.sendMessageWithRetries({id:this.createHandshakeId(),payload:"hand",application:this.application},{timeout:this.handshakeTimeout})];case 1:return t=n.sent(),this.connect(t),[2,t];case 2:throw e=n.sent(),this.handshakePromise=void 0,e instanceof r?new a(e.postedMessage,e.timeout,e.attempts):e;case 3:return[2]}}))}))},t.prototype.handshakeMessageListener=function(t,e){return!!this.isHandshakeId(t.id)&&(this.connect(t),e("shake!"),!0)},t}();export{c as Vessel};
var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};function e(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function i(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}var n=function(){return n=Object.assign||function(t){for(var e,n=1,i=arguments.length;n<i;n++)for(var o in e=arguments[n])Object.prototype.hasOwnProperty.call(e,o)&&(t[o]=e[o]);return t},n.apply(this,arguments)};function i(t,e,n,i){return new(n||(n=Promise))((function(o,s){function r(t){try{c(i.next(t))}catch(t){s(t)}}function a(t){try{c(i.throw(t))}catch(t){s(t)}}function c(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,a)}c((i=i.apply(t,e||[])).next())}))}function o(t,e){var n,i,o,s,r={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return s={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(a){return function(c){return function(a){if(n)throw new TypeError("Generator is already executing.");for(;s&&(s=0,a[0]&&(r=0)),r;)try{if(n=1,i&&(o=2&a[0]?i.return:a[0]?i.throw||((o=i.return)&&o.call(i),0):i.next)&&!(o=o.call(i,a[1])).done)return o;switch(i=0,o&&(a=[2&a[0],o.value]),a[0]){case 0:case 1:o=a;break;case 4:return r.label++,{value:a[1],done:!1};case 5:r.label++,i=a[1],a=[0];continue;case 7:a=r.ops.pop(),r.trys.pop();continue;default:if(!(o=r.trys,(o=o.length>0&&o[o.length-1])||6!==a[0]&&2!==a[0])){r=0;continue}if(3===a[0]&&(!o||a[1]>o[0]&&a[1]<o[3])){r.label=a[1];break}if(6===a[0]&&r.label<o[1]){r.label=o[1],o=a;break}if(o&&r.label<o[2]){r.label=o[2],r.ops.push(a);break}o[2]&&r.ops.pop(),r.trys.pop();continue}a=e.call(t,r)}catch(t){a=[6,t],i=0}finally{n=o=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,c])}}}function s(t,e,n){if(n||2===arguments.length)for(var i,o=0,s=e.length;o<s;o++)!i&&o in e||(i||(i=Array.prototype.slice.call(e,0,o)),i[o]=e[o]);return t.concat(i||Array.prototype.slice.call(e))}"function"==typeof SuppressedError&&SuppressedError;var r=function(t){function n(e,n,i){void 0===i&&(i=1);var o=t.call(this,"Failed to receive response for message ".concat(e.id," within ").concat(n,"ms. Payload: ").concat(JSON.stringify(e.payload)))||this;return o.name="TimeoutError",o.postedMessage=e,o.timeout=n,o.attempts=i,o}return e(n,t),n}(function(t){function n(){var e=null!==t&&t.apply(this,arguments)||this;return e.type="VesselError",e}return e(n,t),n}(Error)),a=function(t){function n(e,n,i){var o=t.call(this,e,n)||this;return o.name="HandshakeTimeoutError",o.message="Failed to receive handshake response within ".concat(n,"ms after ").concat(i," attempts. Payload: ").concat(JSON.stringify(e.payload)),o.attempts=i,o}return e(n,t),n}(r);var c=function(){function t(t){var e=void 0===t?{}:t,n=e.iframe,i=e.targetOrigin,o=void 0===i?"*":i,s=e.application,r=void 0===s?"opensea-vessel":s,a=e.debug,c=void 0!==a&&a,u=e.handshakeTimeout,h=void 0===u?1e4:u,d=e.defaultTimeout,p=void 0===d?5e3:d,l=this;this.listeners=new Map,this.sentMessageCount=BigInt(0),this.connected=!1,this.createResponseId=function(){return"".concat(l.createId(),"r")},this.isResponseId=function(t){return t.endsWith("r")},this.createHandshakeId=function(){return"".concat(l.createId(),"h")},this.isHandshakeId=function(t){return t.endsWith("h")},this.type=n?"parent":"child",this.frame=n,this.targetOrigin=o,this.application=r,this.debug=c,this.handshakeTimeout=h,this.defaultTimeout=p,this.origin=window.location.origin,this.addListener("message",this.handshakeMessageListener.bind(this)),this.windowMessageEventListener=this.handleMessageEvent.bind(this),window.addEventListener("message",this.windowMessageEventListener)}return t.prototype.cleanup=function(){window.removeEventListener("message",this.windowMessageEventListener)},t.prototype.addListener=function(t,e){var n=this.listeners.get(t),i=n?s(s([],n,!0),[e],!1):[e];return this.listeners.set(t,i),this.removeListener.bind(this,t,e)},t.prototype.removeListener=function(t,e){var n,i=this.listeners.get(t);this.listeners.set(t,null!==(n=null==i?void 0:i.filter((function(t){return t!==e})))&&void 0!==n?n:[])},t.prototype.handshake=function(){return i(this,void 0,void 0,(function(){return o(this,(function(t){return this.handshakePromise||(this.handshakePromise=this.sendHandshakeMessage()),[2,this.handshakePromise]}))}))},t.prototype.send=function(t,e){return void 0===e&&(e={}),i(this,void 0,void 0,(function(){return o(this,(function(i){switch(i.label){case 0:return this.connected?[3,2]:[4,this.handshake()];case 1:i.sent(),i.label=2;case 2:return[4,this.sendMessage({id:this.createId(),payload:t,application:this.application},n(n({},e),{timeout:"timeout"in e?e.timeout:this.defaultTimeout}))];case 3:return[2,i.sent().payload]}}))}))},t.prototype.debugLog=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];this.debug&&console.debug.apply(console,s(["[".concat(this.type,"]")],t,!1))},t.prototype.debugTime=function(t){this.debug&&console.time("[".concat(this.type,"] ").concat(t))},t.prototype.debugTimeEnd=function(t){this.debug&&console.timeEnd("[".concat(this.type,"] ").concat(t))},t.prototype.warn=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];console.warn.apply(console,s(["[".concat(this.type,"]")],t,!1))},t.prototype.createId=function(){return"".concat(this.type[0]).concat(this.sentMessageCount++)},t.prototype.postMessage=function(t){var e,n;this.debugLog("Posting message from ".concat(this.origin," to ").concat(this.targetOrigin),t),"parent"===this.type?null===(n=null===(e=this.frame)||void 0===e?void 0:e.contentWindow)||void 0===n||n.postMessage(t,this.targetOrigin):window.parent.postMessage(t,this.targetOrigin)},t.prototype.sendMessage=function(t,e){var n=(void 0===e?{}:e).timeout;return i(this,void 0,void 0,(function(){var e=this;return o(this,(function(i){return[2,new Promise((function(i,o){var s;void 0!==n&&(s=setTimeout((function(){o(new r(t,n)),e.removeListener("message",c)}),n));var a=t.id,c=function(t){return!(!function(t){return"originalId"in t}(t)||t.originalId!==a)&&(e.debugTimeEnd(a),e.debugLog("Received response from ".concat(e.targetOrigin),t),clearTimeout(s),t.error?o(t.payload):(e.removeListener("message",c),i(t)),!0)};e.addListener("message",c),e.debugTime(t.id),e.postMessage(t)}))]}))}))},t.prototype.sendMessageWithRetries=function(t,e){var n=this,i=void 0===e?{}:e,o=i.interval,s=void 0===o?100:o,a=i.timeout;return new Promise((function(e,i){var o,c=1;n.sendMessage(t,{timeout:a}).then(e).catch((function(t){i(t instanceof r?new r(t.postedMessage,t.timeout,c):t)})).finally((function(){clearInterval(o)}));var u=function(){n.debugLog("Retrying message ".concat(t.id)),n.postMessage(t),c++,o=setTimeout(u,s)};o=setTimeout(u,s)}))},t.prototype.reply=function(t,e,n){void 0===e&&(e=void 0);var i=(void 0===n?{}:n).error;this.postMessage({id:this.createResponseId(),payload:e,application:this.application,originalId:t.id,error:i})},t.prototype.handleMessageEvent=function(t){var e;if(t.data.application===this.application&&("*"===this.targetOrigin||t.origin===this.targetOrigin)){this.debugLog("Received message from ".concat(t.origin),t.data);for(var n=!1,i=0,o=null!==(e=this.listeners.get("message"))&&void 0!==e?e:[];i<o.length;i++){var s=(0,o[i])(t.data,this.reply.bind(this,t.data));s&&n&&this.warn("Message was handled by multiple listeners",t.data),n||(n=s)}var r=this.isResponseId(t.data.id);n||r||this.warn("Message was not handled",t.data)}},t.prototype.connect=function(t){var e,n=this;this.connected=!0;for(var i=0,o=null!==(e=this.listeners.get("connect"))&&void 0!==e?e:[];i<o.length;i++){(0,o[i])(t,(function(){n.warn("Using reply function on connect event is not supported")}))}},t.prototype.sendHandshakeMessage=function(){return i(this,void 0,void 0,(function(){var t,e;return o(this,(function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,this.sendMessageWithRetries({id:this.createHandshakeId(),payload:"hand",application:this.application},{timeout:this.handshakeTimeout})];case 1:return t=n.sent(),this.connect(t),[2,t];case 2:throw e=n.sent(),this.handshakePromise=void 0,e instanceof r?new a(e.postedMessage,e.timeout,e.attempts):e;case 3:return[2]}}))}))},t.prototype.handshakeMessageListener=function(t,e){return!!this.isHandshakeId(t.id)&&(this.connect(t),e("shake!"),!0)},t}();export{c as Vessel};
//# sourceMappingURL=index.js.map
export * from "./Vessel";
export * from "./types";
//# sourceMappingURL=index.d.ts.map

@@ -31,3 +31,3 @@ export interface VesselMessage<T = unknown> {

*/
export type VesselMessageListener = (message: VesselMessage, reply: (response: unknown, options?: ReplyOptions) => void) => boolean;
export type VesselMessageListener<ResponseType = undefined> = (message: VesselMessage, reply: (response?: ResponseType, options?: ReplyOptions) => void) => boolean;
//# sourceMappingURL=types.d.ts.map

@@ -58,3 +58,3 @@ import type { SendOptions, VesselMessageListener, VesselResponse } from "./types";

*/
addListener(eventName: EventType, listener: VesselMessageListener): () => void;
addListener<ResponseType = unknown>(eventName: EventType, listener: VesselMessageListener<ResponseType>): () => void;
/**

@@ -64,3 +64,3 @@ * Remove a listener from handling incoming messages or lifecycle events (connection).

*/
removeListener(eventName: EventType, listener: VesselMessageListener): void;
removeListener<ResponseType = unknown>(eventName: EventType, listener: VesselMessageListener<ResponseType>): void;
/**

@@ -78,3 +78,3 @@ * Send a handshake message to connect to iframe or parent window.

*/
send<T>(payload: T, options?: SendOptions): Promise<VesselResponse<unknown>>;
send<ResponseType = undefined, PayloadType = unknown>(payload: PayloadType, options?: SendOptions): Promise<ResponseType>;
private debugLog;

@@ -81,0 +81,0 @@ private debugTime;

import React from "react";
interface Props {
export interface ChildProps {
initVesselImmediately?: boolean;
}
export declare const Child: ({ initVesselImmediately }: Props) => React.JSX.Element;
export {};
export declare const Child: ({ initVesselImmediately }: ChildProps) => React.JSX.Element;
//# sourceMappingURL=Child.d.ts.map
{
"name": "@opensea/vessel",
"version": "0.1.0",
"version": "0.2.0",
"description": "Promise based wrapper for postMessage API 🚢",

@@ -14,3 +14,3 @@ "license": "ISC",

},
"main": "./src/index.ts",
"main": "./dist/index.js",
"files": [

@@ -29,3 +29,3 @@ "dist",

"@types/node": "20.3.2",
"@types/react": "^18.3.1",
"@types/react": "^18.2.0",
"eslint-plugin-storybook": "^0.6.13",

@@ -36,4 +36,4 @@ "husky": "^8.0.3",

"prettier-package-json": "^2.8.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"rollup": "^4.4.1",

@@ -40,0 +40,0 @@ "rollup-plugin-analyzer": "^4.0.0",

export * from "./Vessel"
export * from "./types"

@@ -36,5 +36,5 @@ export interface VesselMessage<T = unknown> {

*/
export type VesselMessageListener = (
export type VesselMessageListener<ResponseType = undefined> = (
message: VesselMessage,
reply: (response: unknown, options?: ReplyOptions) => void,
reply: (response?: ResponseType, options?: ReplyOptions) => void,
) => boolean
import { HandshakeTimeoutError, TimeoutError } from "./errors"
import { isVesselResponse } from "./type-utils"
import type {

@@ -54,3 +55,3 @@ ReplyOptions,

private origin: string
private listeners = new Map<EventType, VesselMessageListener[]>()
private listeners = new Map<EventType, VesselMessageListener<unknown>[]>()
private sentMessageCount = BigInt(0)

@@ -95,17 +96,14 @@ private windowMessageEventListener: (event: MessageEvent) => void

*/
public addListener(
public addListener<ResponseType = unknown>(
eventName: EventType,
listener: VesselMessageListener,
listener: VesselMessageListener<ResponseType>,
): () => void {
const listeners = this.listeners.get(eventName)
const prevListeners = this.listeners.get(eventName)
const listeners = prevListeners ? [...prevListeners, listener] : [listener]
this.listeners.set(
eventName,
listeners ? [...listeners, listener] : [listener],
// Casting to allow adding generic listeners
listeners as VesselMessageListener<unknown>[],
)
return () => {
this.listeners.set(
eventName,
listeners?.filter(l => l !== listener) ?? [],
)
}
return this.removeListener.bind(this, eventName, listener)
}

@@ -117,5 +115,5 @@

*/
public removeListener(
public removeListener<ResponseType = unknown>(
eventName: EventType,
listener: VesselMessageListener,
listener: VesselMessageListener<ResponseType>,
): void {

@@ -144,3 +142,6 @@ const listeners = this.listeners.get(eventName)

*/
public async send<T>(payload: T, options: SendOptions = {}) {
public async send<ResponseType = undefined, PayloadType = unknown>(
payload: PayloadType,
options: SendOptions = {},
): Promise<ResponseType> {
if (!this.connected) {

@@ -150,3 +151,3 @@ // Shake hands to ensure connection is established

}
return this.sendMessage(
const response = await this.sendMessage<ResponseType>(
{

@@ -162,2 +163,3 @@ id: this.createId(),

)
return response.payload
}

@@ -232,7 +234,7 @@

*/
private async sendMessage(
private async sendMessage<ResponseType = unknown>(
message: VesselMessage,
{ timeout }: SendOptions = {},
): Promise<VesselResponse> {
return new Promise<VesselResponse>((resolve, reject) => {
): Promise<VesselResponse<ResponseType>> {
return new Promise<VesselResponse<ResponseType>>((resolve, reject) => {
// Reject if no response is received within timeout milliseconds

@@ -249,5 +251,4 @@ let timeoutId: NodeJS.Timeout

const id = message.id
const listener = (message: VesselMessage) => {
const response = message as VesselResponse
if (response.originalId !== id) {
const listener = (response: VesselMessage<unknown>) => {
if (!isVesselResponse(response) || response.originalId !== id) {
return false // Ignore messages not related to this send operation

@@ -262,3 +263,4 @@ }

this.removeListener("message", listener)
resolve(response)
// NOTE: Trusting expected type provided as generic by caller
resolve(response as VesselResponse<ResponseType>)
}

@@ -265,0 +267,0 @@ return true

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc