Socket
Socket
Sign inDemoInstall

graphql-ws

Package Overview
Dependencies
1
Maintainers
1
Versions
103
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

Comparing version 5.5.5 to 5.6.0

8

lib/client.d.ts

@@ -128,3 +128,3 @@ /**

*/
export interface ClientOptions {
export interface ClientOptions<P extends ConnectionInitMessage['payload'] = ConnectionInitMessage['payload']> {
/**

@@ -153,3 +153,3 @@ * URL of the GraphQL over WebSocket Protocol compliant server to connect.

*/
connectionParams?: ConnectionInitMessage['payload'] | (() => Promise<ConnectionInitMessage['payload']> | ConnectionInitMessage['payload']);
connectionParams?: P | (() => Promise<P> | P);
/**

@@ -259,3 +259,5 @@ * Controls when should the connection be established.

* - `4500: Internal server error`
* - `4005: Internal client error`
* - `4400: Bad request`
* - `4004: Bad response`
* - `4401: Unauthorized` _tried subscribing before connect ack_

@@ -353,2 +355,2 @@ * - `4406: Subprotocol not acceptable`

*/
export declare function createClient(options: ClientOptions): Client;
export declare function createClient<P extends ConnectionInitMessage['payload'] = ConnectionInitMessage['payload']>(options: ClientOptions<P>): Client;

@@ -76,3 +76,3 @@ "use strict";

if (!ws)
throw new Error('WebSocket implementation missing');
throw new Error("WebSocket implementation missing; on Node you can `import WebSocket from 'ws';` and pass `webSocketImpl: WebSocket` to `createClient`");
const WebSocketImpl = ws;

@@ -364,3 +364,2 @@ // websocket status emitter, subscriptions are handled differently

case common_1.MessageType.Next: {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
sink.next(message.payload);

@@ -367,0 +366,0 @@ return;

@@ -7,3 +7,3 @@ /**

import { OperationTypeNode, GraphQLSchema, ExecutionArgs, validate as graphqlValidate, GraphQLError, SubscriptionArgs } from 'graphql';
import { ID, SubscribeMessage, NextMessage, ErrorMessage, CompleteMessage, JSONMessageReplacer, JSONMessageReviver, PingMessage, PongMessage, ExecutionResult, ExecutionPatchResult } from './common';
import { ID, ConnectionInitMessage, SubscribeMessage, NextMessage, ErrorMessage, CompleteMessage, JSONMessageReplacer, JSONMessageReviver, PingMessage, PongMessage, ExecutionResult, ExecutionPatchResult } from './common';
/** @category Server */

@@ -23,3 +23,3 @@ export declare type OperationResult = Promise<AsyncGenerator<ExecutionResult | ExecutionPatchResult> | AsyncIterable<ExecutionResult | ExecutionPatchResult> | ExecutionResult> | AsyncGenerator<ExecutionResult | ExecutionPatchResult> | AsyncIterable<ExecutionResult | ExecutionPatchResult> | ExecutionResult;

/** @category Server */
export interface ServerOptions<E = unknown> {
export interface ServerOptions<P extends ConnectionInitMessage['payload'] = ConnectionInitMessage['payload'], E = unknown> {
/**

@@ -41,3 +41,3 @@ * The GraphQL schema on which the operations

*/
schema?: GraphQLSchema | ((ctx: Context<E>, message: SubscribeMessage, args: Omit<ExecutionArgs, 'schema'>) => Promise<GraphQLSchema> | GraphQLSchema);
schema?: GraphQLSchema | ((ctx: Context<P, E>, message: SubscribeMessage, args: Omit<ExecutionArgs, 'schema'>) => Promise<GraphQLSchema> | GraphQLSchema);
/**

@@ -62,3 +62,3 @@ * A value which is provided to every resolver and holds

*/
context?: GraphQLExecutionContextValue | ((ctx: Context<E>, message: SubscribeMessage, args: ExecutionArgs) => Promise<GraphQLExecutionContextValue> | GraphQLExecutionContextValue);
context?: GraphQLExecutionContextValue | ((ctx: Context<P, E>, message: SubscribeMessage, args: ExecutionArgs) => Promise<GraphQLExecutionContextValue> | GraphQLExecutionContextValue);
/**

@@ -146,3 +146,3 @@ * The GraphQL root fields or resolvers to go

*/
onConnect?: (ctx: Context<E>) => Promise<Record<string, unknown> | boolean | void> | Record<string, unknown> | boolean | void;
onConnect?: (ctx: Context<P, E>) => Promise<Record<string, unknown> | boolean | void> | Record<string, unknown> | boolean | void;
/**

@@ -164,3 +164,3 @@ * Called when the client disconnects for whatever reason after

*/
onDisconnect?: (ctx: Context<E>, code: number, reason: string) => Promise<void> | void;
onDisconnect?: (ctx: Context<P, E>, code: number, reason: string) => Promise<void> | void;
/**

@@ -180,3 +180,3 @@ * Called when the socket closes for whatever reason, at any

*/
onClose?: (ctx: Context<E>, code: number, reason: string) => Promise<void> | void;
onClose?: (ctx: Context<P, E>, code: number, reason: string) => Promise<void> | void;
/**

@@ -211,3 +211,3 @@ * The subscribe callback executed right after

*/
onSubscribe?: (ctx: Context<E>, message: SubscribeMessage) => Promise<ExecutionArgs | readonly GraphQLError[] | void> | ExecutionArgs | readonly GraphQLError[] | void;
onSubscribe?: (ctx: Context<P, E>, message: SubscribeMessage) => Promise<ExecutionArgs | readonly GraphQLError[] | void> | ExecutionArgs | readonly GraphQLError[] | void;
/**

@@ -233,3 +233,3 @@ * Executed after the operation call resolves. For streaming

*/
onOperation?: (ctx: Context<E>, message: SubscribeMessage, args: ExecutionArgs, result: OperationResult) => Promise<OperationResult | void> | OperationResult | void;
onOperation?: (ctx: Context<P, E>, message: SubscribeMessage, args: ExecutionArgs, result: OperationResult) => Promise<OperationResult | void> | OperationResult | void;
/**

@@ -248,3 +248,3 @@ * Executed after an error occured right before it

*/
onError?: (ctx: Context<E>, message: ErrorMessage, errors: readonly GraphQLError[]) => Promise<readonly GraphQLError[] | void> | readonly GraphQLError[] | void;
onError?: (ctx: Context<P, E>, message: ErrorMessage, errors: readonly GraphQLError[]) => Promise<readonly GraphQLError[] | void> | readonly GraphQLError[] | void;
/**

@@ -264,3 +264,3 @@ * Executed after an operation has emitted a result right before

*/
onNext?: (ctx: Context<E>, message: NextMessage, args: ExecutionArgs, result: ExecutionResult | ExecutionPatchResult) => Promise<ExecutionResult | ExecutionPatchResult | void> | ExecutionResult | ExecutionPatchResult | void;
onNext?: (ctx: Context<P, E>, message: NextMessage, args: ExecutionArgs, result: ExecutionResult | ExecutionPatchResult) => Promise<ExecutionResult | ExecutionPatchResult | void> | ExecutionResult | ExecutionPatchResult | void;
/**

@@ -279,3 +279,3 @@ * The complete callback is executed after the

*/
onComplete?: (ctx: Context<E>, message: CompleteMessage) => Promise<void> | void;
onComplete?: (ctx: Context<P, E>, message: CompleteMessage) => Promise<void> | void;
/**

@@ -372,3 +372,3 @@ * An optional override for the JSON.parse function used to hydrate

/** @category Server */
export interface Context<E = unknown> {
export interface Context<P extends ConnectionInitMessage['payload'] = ConnectionInitMessage['payload'], E = unknown> {
/**

@@ -388,3 +388,3 @@ * Indicates that the `ConnectionInit` message

/** The parameters passed during the connection initialisation. */
readonly connectionParams?: Readonly<Record<string, unknown>>;
readonly connectionParams?: Readonly<P>;
/**

@@ -416,2 +416,2 @@ * Holds the active subscriptions for this context. **All operations**

*/
export declare function makeServer<E = unknown>(options: ServerOptions<E>): Server<E>;
export declare function makeServer<P extends ConnectionInitMessage['payload'] = ConnectionInitMessage['payload'], E = unknown>(options: ServerOptions<P, E>): Server<E>;
import type { FastifyRequest } from 'fastify';
import type * as fastifyWebsocket from 'fastify-websocket';
import { ServerOptions } from '../server';
import { ConnectionInitMessage } from '../common';
/**

@@ -27,3 +28,3 @@ * The extra that will be put in the `Context`.

*/
export declare function makeHandler<E extends Record<PropertyKey, unknown> = Record<PropertyKey, never>>(options: ServerOptions<Extra & Partial<E>>,
export declare function makeHandler<P extends ConnectionInitMessage['payload'] = ConnectionInitMessage['payload'], E extends Record<PropertyKey, unknown> = Record<PropertyKey, never>>(options: ServerOptions<P, Extra & Partial<E>>,
/**

@@ -30,0 +31,0 @@ * The timout between dispatched keep-alive messages. Internally uses the [ws Ping and Pongs]((https://developer.mozilla.org/en-US/docs/Web/API/wss_API/Writing_ws_servers#Pings_and_Pongs_The_Heartbeat_of_wss))

@@ -5,2 +5,3 @@ /// <reference types="node" />

import { ServerOptions } from '../server';
import { ConnectionInitMessage } from '../common';
/**

@@ -59,3 +60,3 @@ * The extra that will be put in the `Context`.

*/
export declare function makeBehavior<E extends Record<PropertyKey, unknown> = Record<PropertyKey, never>>(options: ServerOptions<Extra & Partial<E>>, behavior?: uWS.WebSocketBehavior,
export declare function makeBehavior<P extends ConnectionInitMessage['payload'] = ConnectionInitMessage['payload'], E extends Record<PropertyKey, unknown> = Record<PropertyKey, never>>(options: ServerOptions<P, Extra & Partial<E>>, behavior?: uWS.WebSocketBehavior,
/**

@@ -62,0 +63,0 @@ * The timout between dispatched keep-alive messages. Internally uses the [ws Ping and Pongs]((https://developer.mozilla.org/en-US/docs/Web/API/wss_API/Writing_ws_servers#Pings_and_Pongs_The_Heartbeat_of_wss))

@@ -5,3 +5,3 @@ /// <reference types="node" />

import { ServerOptions } from '../server';
import { Disposable } from '../common';
import { ConnectionInitMessage, Disposable } from '../common';
declare type WebSocket = typeof ws.prototype;

@@ -31,3 +31,3 @@ declare type WebSocketServer = ws.Server;

*/
export declare function useServer<E extends Record<PropertyKey, unknown> = Record<PropertyKey, never>>(options: ServerOptions<Extra & Partial<E>>, ws: WebSocketServer,
export declare function useServer<P extends ConnectionInitMessage['payload'] = ConnectionInitMessage['payload'], E extends Record<PropertyKey, unknown> = Record<PropertyKey, never>>(options: ServerOptions<P, Extra & Partial<E>>, ws: WebSocketServer,
/**

@@ -34,0 +34,0 @@ * The timout between dispatched keep-alive messages. Internally uses the [ws Ping and Pongs]((https://developer.mozilla.org/en-US/docs/Web/API/wss_API/Writing_ws_servers#Pings_and_Pongs_The_Heartbeat_of_wss))

{
"name": "graphql-ws",
"version": "5.5.5",
"version": "5.6.0",
"description": "Coherent, zero-dependency, lazy, simple, GraphQL over WebSocket Protocol compliant server and client",

@@ -85,39 +85,42 @@ "keywords": [

"devDependencies": {
"@babel/core": "^7.15.8",
"@babel/plugin-proposal-class-properties": "^7.14.5",
"@babel/plugin-proposal-nullish-coalescing-operator": "^7.14.5",
"@babel/plugin-proposal-object-rest-spread": "^7.15.6",
"@babel/plugin-proposal-optional-chaining": "^7.14.5",
"@babel/preset-env": "^7.15.8",
"@babel/preset-typescript": "^7.15.0",
"@babel/core": "^7.17.5",
"@babel/plugin-proposal-class-properties": "^7.16.7",
"@babel/plugin-proposal-nullish-coalescing-operator": "^7.16.7",
"@babel/plugin-proposal-object-rest-spread": "^7.17.3",
"@babel/plugin-proposal-optional-chaining": "^7.16.7",
"@babel/preset-env": "^7.16.11",
"@babel/preset-typescript": "^7.16.7",
"@rollup/plugin-typescript": "^8.3.0",
"@semantic-release/changelog": "^6.0.0",
"@semantic-release/git": "^10.0.0",
"@types/jest": "^26.0.24",
"@types/ws": "^8.2.0",
"@typescript-eslint/eslint-plugin": "^5.2.0",
"@typescript-eslint/parser": "^5.2.0",
"babel-jest": "^27.3.1",
"eslint": "^8.1.0",
"eslint-config-prettier": "^8.3.0",
"@semantic-release/changelog": "^6.0.1",
"@semantic-release/git": "^10.0.1",
"@types/jest": "^27.4.0",
"@types/ws": "^8.2.3",
"@typescript-eslint/eslint-plugin": "^5.12.0",
"@typescript-eslint/parser": "^5.12.0",
"babel-jest": "^27.5.1",
"eslint": "^8.9.0",
"eslint-config-prettier": "^8.4.0",
"eslint-plugin-prettier": "^4.0.0",
"fastify": "^3.22.1",
"fastify": "^3.27.2",
"fastify-websocket": "^4.0.0",
"glob": "^7.2.0",
"graphql": "16.0.0",
"jest": "^27.3.1",
"prettier": "^2.4.1",
"graphql": "^16.3.0",
"jest": "^27.5.1",
"prettier": "^2.5.1",
"replacestream": "^4.0.3",
"rollup": "^2.58.3",
"rollup": "^2.67.3",
"rollup-plugin-terser": "^7.0.2",
"semantic-release": "^18.0.0",
"subscriptions-transport-ws": "^0.9.19",
"semantic-release": "^19.0.2",
"subscriptions-transport-ws": "^0.11.0",
"tslib": "^2.3.1",
"typedoc": "0.22.7",
"typedoc-plugin-markdown": "^3.11.3",
"typescript": "^4.4.4",
"uWebSockets.js": "uNetworking/uWebSockets.js#v20.2.0",
"ws": "^8.2.3",
"ws7": "npm:ws@^7.5.5"
"typedoc": "^0.22.11",
"typedoc-plugin-markdown": "^3.11.14",
"typescript": "^4.5.5",
"uWebSockets.js": "uNetworking/uWebSockets.js#v20.6.0",
"ws": "^8.5.0",
"ws7": "npm:ws@^7.5.7"
},
"resolutions": {
"npm/chalk": "^4.1.2"
}
}

@@ -26,27 +26,38 @@ <div align="center">

```ts
import { buildSchema } from 'graphql';
import { GraphQLSchema, GraphQLObjectType, GraphQLString } from 'graphql';
// Construct a schema, using GraphQL schema language
const schema = buildSchema(`
type Query {
hello: String
}
type Subscription {
greetings: String
}
`);
// The roots provide resolvers for each GraphQL operation
const roots = {
query: {
hello: () => 'Hello World!',
},
subscription: {
greetings: async function* sayHiIn5Languages() {
for (const hi of ['Hi', 'Bonjour', 'Hola', 'Ciao', 'Zdravo']) {
yield { greetings: hi };
}
/**
* Construct a GraphQL schema and define the necessary resolvers.
*
* type Query {
* hello: String
* }
* type Subscription {
* greetings: String
* }
*/
export const schema = new GraphQLSchema({
query: new GraphQLObjectType({
name: 'Query',
fields: {
hello: {
type: GraphQLString,
resolve: () => 'world',
},
},
},
};
}),
subscription: new GraphQLObjectType({
name: 'Subscription',
fields: {
greetings: {
type: GraphQLString,
subscribe: async function* () {
for (const hi of ['Hi', 'Bonjour', 'Hola', 'Ciao', 'Zdravo']) {
yield { greetings: hi };
}
},
},
},
}),
});
```

@@ -63,2 +74,3 @@

import { useServer } from 'graphql-ws/lib/use/ws';
import { schema } from './previous-step';

@@ -70,7 +82,3 @@ const server = new WebSocketServer({

useServer(
// from the previous step
{ schema, roots },
server,
);
useServer({ schema }, server);

@@ -85,12 +93,7 @@ console.log('Listening to port 4000');

import { makeBehavior } from 'graphql-ws/lib/use/uWebSockets';
import { schema } from './previous-step';
uWS
.App()
.ws(
'/graphql',
makeBehavior(
// from the previous step
{ schema, roots },
),
)
.ws('/graphql', makeBehavior({ schema }))
.listen(4000, (listenSocket) => {

@@ -109,2 +112,3 @@ if (listenSocket) {

import { makeHandler } from 'graphql-ws/lib/use/fastify-websocket';
import { schema } from './previous-step';

@@ -114,10 +118,3 @@ const fastify = Fastify();

fastify.get(
'/graphql',
{ websocket: true },
makeHandler(
// from the previous step
{ schema, roots },
),
);
fastify.get('/graphql', { websocket: true }, makeHandler({ schema }));

@@ -344,3 +341,2 @@ fastify.listen(4000, (err) => {

```ts
import { GraphQLError } from 'graphql';
import {

@@ -379,25 +375,3 @@ Network,

},
{
...sink,
error: (err) => {
if (err instanceof Error) {
return sink.error(err);
}
if (err instanceof CloseEvent) {
return sink.error(
// reason will be available on clean closes
new Error(
`Socket closed with event ${err.code} ${err.reason || ''}`,
),
);
}
return sink.error(
new Error(
(err as GraphQLError[]).map(({ message }) => message).join(', '),
),
);
},
},
sink,
);

@@ -449,2 +423,3 @@ });

```typescript
// for Apollo Client v3:
import {

@@ -456,3 +431,6 @@ ApolloLink,

} from '@apollo/client/core';
import { print, GraphQLError } from 'graphql';
// or for Apollo Client v2:
// import { ApolloLink, Operation, FetchResult, Observable } from 'apollo-link'; // yarn add apollo-link
import { print } from 'graphql';
import { createClient, ClientOptions, Client } from 'graphql-ws';

@@ -475,24 +453,3 @@

complete: sink.complete.bind(sink),
error: (err) => {
if (err instanceof Error) {
return sink.error(err);
}
if (err instanceof CloseEvent) {
return sink.error(
// reason will be available on clean closes
new Error(
`Socket closed with event ${err.code} ${err.reason || ''}`,
),
);
}
return sink.error(
new Error(
(err as GraphQLError[])
.map(({ message }) => message)
.join(', '),
),
);
},
error: sink.error.bind(sink),
},

@@ -794,2 +751,31 @@ );

<details id="node-client-headers">
<summary><a href="#node-client-headers">🔗</a> Client usage in Node with custom headers <a href="https://stackoverflow.com/a/4361358/3633671">(not possible in browsers)</a></summary>
```ts
const WebSocket = require('ws'); // yarn add ws
const { createClient } = require('graphql-ws');
class MyWebSocket extends WebSocket {
constructor(address, protocols) {
super(address, protocols, {
headers: {
// your custom headers go here
'User-Agent': 'graphql-ws client',
'X-Custom-Header': 'hello world',
},
});
}
}
const client = createClient({
url: 'ws://node.custom-headers:4000/graphql',
webSocketImpl: MyWebSocket,
});
// consider other recipes for usage inspiration
```
</details>
<details id="ws">

@@ -1272,3 +1258,3 @@ <summary><a href="#ws">🔗</a> Server usage with <a href="https://github.com/websockets/ws">ws</a></summary>

import { useServer } from 'graphql-ws/lib/use/ws';
import { schema, roots, getDynamicContext } from './my-graphql';
import { schema, getDynamicContext } from './my-graphql';

@@ -1286,3 +1272,2 @@ const wsServer = new WebSocketServer({

schema,
roots,
},

@@ -1289,0 +1274,0 @@ wsServer,

@@ -233,3 +233,3 @@ (function (global, factory) {

if (!ws)
throw new Error('WebSocket implementation missing');
throw new Error("WebSocket implementation missing; on Node you can `import WebSocket from 'ws';` and pass `webSocketImpl: WebSocket` to `createClient`");
const WebSocketImpl = ws;

@@ -521,3 +521,2 @@ // websocket status emitter, subscriptions are handled differently

case exports.MessageType.Next: {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
sink.next(message.payload);

@@ -524,0 +523,0 @@ return;

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

!function(e,o){"object"==typeof exports&&"undefined"!=typeof module?o(exports):"function"==typeof define&&define.amd?define(["exports"],o):o((e="undefined"!=typeof globalThis?globalThis:e||self).graphqlWs={})}(this,(function(e){"use strict";const o=Object.prototype.hasOwnProperty;function n(e){return"object"==typeof e&&null!==e}function t(e,n){return o.call(e,n)}function r(e,t){return o.call(e,t)&&n(e[t])}function i(e,n){return o.call(e,n)&&"string"==typeof e[n]}function a(e,o){return e.length<124?e:o}const s="graphql-transport-ws";var l,c;function d(o){if(n(o)){if(!i(o,"type"))return!1;switch(o.type){case e.MessageType.ConnectionInit:case e.MessageType.ConnectionAck:case e.MessageType.Ping:case e.MessageType.Pong:return!t(o,"payload")||void 0===o.payload||n(o.payload);case e.MessageType.Subscribe:return i(o,"id")&&r(o,"payload")&&(!t(o.payload,"operationName")||void 0===o.payload.operationName||null===o.payload.operationName||"string"==typeof o.payload.operationName)&&i(o.payload,"query")&&(!t(o.payload,"variables")||void 0===o.payload.variables||null===o.payload.variables||r(o.payload,"variables"))&&(!t(o.payload,"extensions")||void 0===o.payload.extensions||null===o.payload.extensions||r(o.payload,"extensions"));case e.MessageType.Next:return i(o,"id")&&r(o,"payload");case e.MessageType.Error:return i(o,"id")&&(a=o.payload,Array.isArray(a)&&a.length>0&&a.every((e=>"message"in e)));case e.MessageType.Complete:return i(o,"id");default:return!1}}var a;return!1}function p(e,o){if(d(e))return e;if("string"!=typeof e)throw new Error("Message not parsable");const n=JSON.parse(e,o);if(!d(n))throw new Error("Invalid message");return n}function u(e,o){if(!d(e))throw new Error("Cannot stringify invalid message");return JSON.stringify(e,o)}function y(e){return n(e)&&"code"in e&&"reason"in e}e.CloseCode=void 0,(l=e.CloseCode||(e.CloseCode={}))[l.InternalServerError=4500]="InternalServerError",l[l.InternalClientError=4005]="InternalClientError",l[l.BadRequest=4400]="BadRequest",l[l.BadResponse=4004]="BadResponse",l[l.Unauthorized=4401]="Unauthorized",l[l.Forbidden=4403]="Forbidden",l[l.SubprotocolNotAcceptable=4406]="SubprotocolNotAcceptable",l[l.ConnectionInitialisationTimeout=4408]="ConnectionInitialisationTimeout",l[l.ConnectionAcknowledgementTimeout=4504]="ConnectionAcknowledgementTimeout",l[l.SubscriberAlreadyExists=4409]="SubscriberAlreadyExists",l[l.TooManyInitialisationRequests=4429]="TooManyInitialisationRequests",e.MessageType=void 0,(c=e.MessageType||(e.MessageType={})).ConnectionInit="connection_init",c.ConnectionAck="connection_ack",c.Ping="ping",c.Pong="pong",c.Subscribe="subscribe",c.Next="next",c.Error="error",c.Complete="complete",e.GRAPHQL_TRANSPORT_WS_PROTOCOL=s,e.createClient=function(o){const{url:n,connectionParams:t,lazy:r=!0,onNonLazyError:i=console.error,lazyCloseTimeout:l=0,keepAlive:c=0,disablePong:d,connectionAckWaitTimeout:g=0,retryAttempts:f=5,retryWait:m=async function(e){let o=1e3;for(let n=0;n<e;n++)o*=2;await new Promise((e=>setTimeout(e,o+Math.floor(2700*Math.random()+300))))},isFatalConnectionProblem:C=(e=>!y(e)),on:b,webSocketImpl:w,generateID:x=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const o=16*Math.random()|0;return("x"==e?o:3&o|8).toString(16)}))},jsonMessageReplacer:T,jsonMessageReviver:v}=o;let M;if(w){if(!("function"==typeof(h=w)&&"constructor"in h&&"CLOSED"in h&&"CLOSING"in h&&"CONNECTING"in h&&"OPEN"in h))throw new Error("Invalid WebSocket implementation provided");M=w}else"undefined"!=typeof WebSocket?M=WebSocket:"undefined"!=typeof global?M=global.WebSocket||global.MozWebSocket:"undefined"!=typeof window&&(M=window.WebSocket||window.MozWebSocket);var h;if(!M)throw new Error("WebSocket implementation missing");const S=M,E=(()=>{const e=(()=>{const e={};return{on:(o,n)=>(e[o]=n,()=>{delete e[o]}),emit(o){var n;"id"in o&&(null===(n=e[o.id])||void 0===n||n.call(e,o))}}})(),o={connecting:(null==b?void 0:b.connecting)?[b.connecting]:[],opened:(null==b?void 0:b.opened)?[b.opened]:[],connected:(null==b?void 0:b.connected)?[b.connected]:[],ping:(null==b?void 0:b.ping)?[b.ping]:[],pong:(null==b?void 0:b.pong)?[b.pong]:[],message:(null==b?void 0:b.message)?[e.emit,b.message]:[e.emit],closed:(null==b?void 0:b.closed)?[b.closed]:[],error:(null==b?void 0:b.error)?[b.error]:[]};return{onMessage:e.on,on(e,n){const t=o[e];return t.push(n),()=>{t.splice(t.indexOf(n),1)}},emit(e,...n){for(const t of[...o[e]])t(...n)}}})();function N(e){const o=[E.on("error",(n=>{o.forEach((e=>e())),e(n)})),E.on("closed",(n=>{o.forEach((e=>e())),e(n)}))]}let I,P=0,A=!1,k=0,O=!1;async function R(){const[o,r]=await(null!=I?I:I=new Promise(((o,r)=>(async()=>{if(A){if(await m(k),!P)return I=void 0,r({code:1e3,reason:"All Subscriptions Gone"});k++}E.emit("connecting");const i=new S("function"==typeof n?await n():n,s);let l,y;function f(){isFinite(c)&&c>0&&(clearTimeout(y),y=setTimeout((()=>{i.readyState===S.OPEN&&(i.send(u({type:e.MessageType.Ping})),E.emit("ping",!1,void 0))}),c))}N((e=>{I=void 0,clearTimeout(l),clearTimeout(y),r(e)})),i.onerror=e=>E.emit("error",e),i.onclose=e=>E.emit("closed",e),i.onopen=async()=>{try{E.emit("opened",i);const o="function"==typeof t?await t():t;i.send(u(o?{type:e.MessageType.ConnectionInit,payload:o}:{type:e.MessageType.ConnectionInit},T)),isFinite(g)&&g>0&&(l=setTimeout((()=>{i.close(e.CloseCode.ConnectionAcknowledgementTimeout,"Connection acknowledgement timeout")}),g)),f()}catch(o){E.emit("error",o),i.close(e.CloseCode.InternalClientError,a(o instanceof Error?o.message:new Error(o).message,"Internal client error"))}};let C=!1;i.onmessage=({data:n})=>{try{const t=p(n,v);if(E.emit("message",t),"ping"===t.type||"pong"===t.type)return E.emit(t.type,!0,t.payload),void("pong"===t.type?f():d||(i.send(u(t.payload?{type:e.MessageType.Pong,payload:t.payload}:{type:e.MessageType.Pong})),E.emit("pong",!1,t.payload)));if(C)return;if(t.type!==e.MessageType.ConnectionAck)throw new Error(`First message cannot be of type ${t.type}`);clearTimeout(l),C=!0,E.emit("connected",i,t.payload),A=!1,k=0,o([i,new Promise(((e,o)=>N(o)))])}catch(o){i.onmessage=null,E.emit("error",o),i.close(e.CloseCode.BadResponse,a(o instanceof Error?o.message:new Error(o).message,"Bad response"))}}})())));o.readyState===S.CLOSING&&await r;let i=()=>{};const y=new Promise((e=>i=e));return[o,i,Promise.race([y.then((()=>{if(!P){const e=()=>o.close(1e3,"Normal Closure");isFinite(l)&&l>0?setTimeout((()=>{P||o.readyState!==S.OPEN||e()}),l):e()}})),r])]}function W(o){if(y(o)&&(n=o.code,![1e3,1001,1006,1005,1012,1013,1013].includes(n)&&n>=1e3&&n<=1999||[e.CloseCode.InternalServerError,e.CloseCode.InternalClientError,e.CloseCode.BadRequest,e.CloseCode.BadResponse,e.CloseCode.Unauthorized,e.CloseCode.SubprotocolNotAcceptable,e.CloseCode.SubscriberAlreadyExists,e.CloseCode.TooManyInitialisationRequests].includes(o.code)))throw o;var n;if(O)return!1;if(y(o)&&1e3===o.code)return P>0;if(!f||k>=f)throw o;if(C(o))throw o;return A=!0}return r||(async()=>{for(P++;;)try{const[,,e]=await R();await e}catch(e){try{if(!W(e))return}catch(e){return null==i?void 0:i(e)}}})(),{on:E.on,subscribe(o,n){const t=x();let r=!1,i=!1,a=()=>{P--,r=!0};return(async()=>{for(P++;;)try{const[s,l,c]=await R();if(r)return l();const d=E.onMessage(t,(o=>{switch(o.type){case e.MessageType.Next:return void n.next(o.payload);case e.MessageType.Error:return i=!0,r=!0,n.error(o.payload),void a();case e.MessageType.Complete:return r=!0,void a()}}));return s.send(u({id:t,type:e.MessageType.Subscribe,payload:o},T)),a=()=>{r||s.readyState!==S.OPEN||s.send(u({id:t,type:e.MessageType.Complete},T)),P--,r=!0,l()},void await c.finally(d)}catch(e){if(!W(e))return}})().then((()=>{i||n.complete()})).catch((e=>{n.error(e)})),()=>{r||a()}},async dispose(){if(O=!0,I){const[e]=await I;e.close(1e3,"Normal Closure")}}}},e.isMessage=d,e.parseMessage=p,e.stringifyMessage=u,Object.defineProperty(e,"__esModule",{value:!0})}));
!function(e,o){"object"==typeof exports&&"undefined"!=typeof module?o(exports):"function"==typeof define&&define.amd?define(["exports"],o):o((e="undefined"!=typeof globalThis?globalThis:e||self).graphqlWs={})}(this,(function(e){"use strict";const o=Object.prototype.hasOwnProperty;function n(e){return"object"==typeof e&&null!==e}function t(e,n){return o.call(e,n)}function r(e,t){return o.call(e,t)&&n(e[t])}function i(e,n){return o.call(e,n)&&"string"==typeof e[n]}function a(e,o){return e.length<124?e:o}const s="graphql-transport-ws";var c,l;function d(o){if(n(o)){if(!i(o,"type"))return!1;switch(o.type){case e.MessageType.ConnectionInit:case e.MessageType.ConnectionAck:case e.MessageType.Ping:case e.MessageType.Pong:return!t(o,"payload")||void 0===o.payload||n(o.payload);case e.MessageType.Subscribe:return i(o,"id")&&r(o,"payload")&&(!t(o.payload,"operationName")||void 0===o.payload.operationName||null===o.payload.operationName||"string"==typeof o.payload.operationName)&&i(o.payload,"query")&&(!t(o.payload,"variables")||void 0===o.payload.variables||null===o.payload.variables||r(o.payload,"variables"))&&(!t(o.payload,"extensions")||void 0===o.payload.extensions||null===o.payload.extensions||r(o.payload,"extensions"));case e.MessageType.Next:return i(o,"id")&&r(o,"payload");case e.MessageType.Error:return i(o,"id")&&(a=o.payload,Array.isArray(a)&&a.length>0&&a.every((e=>"message"in e)));case e.MessageType.Complete:return i(o,"id");default:return!1}}var a;return!1}function p(e,o){if(d(e))return e;if("string"!=typeof e)throw new Error("Message not parsable");const n=JSON.parse(e,o);if(!d(n))throw new Error("Invalid message");return n}function u(e,o){if(!d(e))throw new Error("Cannot stringify invalid message");return JSON.stringify(e,o)}function y(e){return n(e)&&"code"in e&&"reason"in e}e.CloseCode=void 0,(c=e.CloseCode||(e.CloseCode={}))[c.InternalServerError=4500]="InternalServerError",c[c.InternalClientError=4005]="InternalClientError",c[c.BadRequest=4400]="BadRequest",c[c.BadResponse=4004]="BadResponse",c[c.Unauthorized=4401]="Unauthorized",c[c.Forbidden=4403]="Forbidden",c[c.SubprotocolNotAcceptable=4406]="SubprotocolNotAcceptable",c[c.ConnectionInitialisationTimeout=4408]="ConnectionInitialisationTimeout",c[c.ConnectionAcknowledgementTimeout=4504]="ConnectionAcknowledgementTimeout",c[c.SubscriberAlreadyExists=4409]="SubscriberAlreadyExists",c[c.TooManyInitialisationRequests=4429]="TooManyInitialisationRequests",e.MessageType=void 0,(l=e.MessageType||(e.MessageType={})).ConnectionInit="connection_init",l.ConnectionAck="connection_ack",l.Ping="ping",l.Pong="pong",l.Subscribe="subscribe",l.Next="next",l.Error="error",l.Complete="complete",e.GRAPHQL_TRANSPORT_WS_PROTOCOL=s,e.createClient=function(o){const{url:n,connectionParams:t,lazy:r=!0,onNonLazyError:i=console.error,lazyCloseTimeout:c=0,keepAlive:l=0,disablePong:d,connectionAckWaitTimeout:g=0,retryAttempts:f=5,retryWait:m=async function(e){let o=1e3;for(let n=0;n<e;n++)o*=2;await new Promise((e=>setTimeout(e,o+Math.floor(2700*Math.random()+300))))},isFatalConnectionProblem:C=(e=>!y(e)),on:b,webSocketImpl:w,generateID:x=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const o=16*Math.random()|0;return("x"==e?o:3&o|8).toString(16)}))},jsonMessageReplacer:T,jsonMessageReviver:v}=o;let M;if(w){if(!("function"==typeof(S=w)&&"constructor"in S&&"CLOSED"in S&&"CLOSING"in S&&"CONNECTING"in S&&"OPEN"in S))throw new Error("Invalid WebSocket implementation provided");M=w}else"undefined"!=typeof WebSocket?M=WebSocket:"undefined"!=typeof global?M=global.WebSocket||global.MozWebSocket:"undefined"!=typeof window&&(M=window.WebSocket||window.MozWebSocket);var S;if(!M)throw new Error("WebSocket implementation missing; on Node you can `import WebSocket from 'ws';` and pass `webSocketImpl: WebSocket` to `createClient`");const h=M,E=(()=>{const e=(()=>{const e={};return{on:(o,n)=>(e[o]=n,()=>{delete e[o]}),emit(o){var n;"id"in o&&(null===(n=e[o.id])||void 0===n||n.call(e,o))}}})(),o={connecting:(null==b?void 0:b.connecting)?[b.connecting]:[],opened:(null==b?void 0:b.opened)?[b.opened]:[],connected:(null==b?void 0:b.connected)?[b.connected]:[],ping:(null==b?void 0:b.ping)?[b.ping]:[],pong:(null==b?void 0:b.pong)?[b.pong]:[],message:(null==b?void 0:b.message)?[e.emit,b.message]:[e.emit],closed:(null==b?void 0:b.closed)?[b.closed]:[],error:(null==b?void 0:b.error)?[b.error]:[]};return{onMessage:e.on,on(e,n){const t=o[e];return t.push(n),()=>{t.splice(t.indexOf(n),1)}},emit(e,...n){for(const t of[...o[e]])t(...n)}}})();function N(e){const o=[E.on("error",(n=>{o.forEach((e=>e())),e(n)})),E.on("closed",(n=>{o.forEach((e=>e())),e(n)}))]}let I,P=0,k=!1,A=0,O=!1;async function R(){const[o,r]=await(null!=I?I:I=new Promise(((o,r)=>(async()=>{if(k){if(await m(A),!P)return I=void 0,r({code:1e3,reason:"All Subscriptions Gone"});A++}E.emit("connecting");const i=new h("function"==typeof n?await n():n,s);let c,y;function f(){isFinite(l)&&l>0&&(clearTimeout(y),y=setTimeout((()=>{i.readyState===h.OPEN&&(i.send(u({type:e.MessageType.Ping})),E.emit("ping",!1,void 0))}),l))}N((e=>{I=void 0,clearTimeout(c),clearTimeout(y),r(e)})),i.onerror=e=>E.emit("error",e),i.onclose=e=>E.emit("closed",e),i.onopen=async()=>{try{E.emit("opened",i);const o="function"==typeof t?await t():t;i.send(u(o?{type:e.MessageType.ConnectionInit,payload:o}:{type:e.MessageType.ConnectionInit},T)),isFinite(g)&&g>0&&(c=setTimeout((()=>{i.close(e.CloseCode.ConnectionAcknowledgementTimeout,"Connection acknowledgement timeout")}),g)),f()}catch(o){E.emit("error",o),i.close(e.CloseCode.InternalClientError,a(o instanceof Error?o.message:new Error(o).message,"Internal client error"))}};let C=!1;i.onmessage=({data:n})=>{try{const t=p(n,v);if(E.emit("message",t),"ping"===t.type||"pong"===t.type)return E.emit(t.type,!0,t.payload),void("pong"===t.type?f():d||(i.send(u(t.payload?{type:e.MessageType.Pong,payload:t.payload}:{type:e.MessageType.Pong})),E.emit("pong",!1,t.payload)));if(C)return;if(t.type!==e.MessageType.ConnectionAck)throw new Error(`First message cannot be of type ${t.type}`);clearTimeout(c),C=!0,E.emit("connected",i,t.payload),k=!1,A=0,o([i,new Promise(((e,o)=>N(o)))])}catch(o){i.onmessage=null,E.emit("error",o),i.close(e.CloseCode.BadResponse,a(o instanceof Error?o.message:new Error(o).message,"Bad response"))}}})())));o.readyState===h.CLOSING&&await r;let i=()=>{};const y=new Promise((e=>i=e));return[o,i,Promise.race([y.then((()=>{if(!P){const e=()=>o.close(1e3,"Normal Closure");isFinite(c)&&c>0?setTimeout((()=>{P||o.readyState!==h.OPEN||e()}),c):e()}})),r])]}function W(o){if(y(o)&&(n=o.code,![1e3,1001,1006,1005,1012,1013,1013].includes(n)&&n>=1e3&&n<=1999||[e.CloseCode.InternalServerError,e.CloseCode.InternalClientError,e.CloseCode.BadRequest,e.CloseCode.BadResponse,e.CloseCode.Unauthorized,e.CloseCode.SubprotocolNotAcceptable,e.CloseCode.SubscriberAlreadyExists,e.CloseCode.TooManyInitialisationRequests].includes(o.code)))throw o;var n;if(O)return!1;if(y(o)&&1e3===o.code)return P>0;if(!f||A>=f)throw o;if(C(o))throw o;return k=!0}return r||(async()=>{for(P++;;)try{const[,,e]=await R();await e}catch(e){try{if(!W(e))return}catch(e){return null==i?void 0:i(e)}}})(),{on:E.on,subscribe(o,n){const t=x();let r=!1,i=!1,a=()=>{P--,r=!0};return(async()=>{for(P++;;)try{const[s,c,l]=await R();if(r)return c();const d=E.onMessage(t,(o=>{switch(o.type){case e.MessageType.Next:return void n.next(o.payload);case e.MessageType.Error:return i=!0,r=!0,n.error(o.payload),void a();case e.MessageType.Complete:return r=!0,void a()}}));return s.send(u({id:t,type:e.MessageType.Subscribe,payload:o},T)),a=()=>{r||s.readyState!==h.OPEN||s.send(u({id:t,type:e.MessageType.Complete},T)),P--,r=!0,c()},void await l.finally(d)}catch(e){if(!W(e))return}})().then((()=>{i||n.complete()})).catch((e=>{n.error(e)})),()=>{r||a()}},async dispose(){if(O=!0,I){const[e]=await I;e.close(1e3,"Normal Closure")}}}},e.isMessage=d,e.parseMessage=p,e.stringifyMessage=u,Object.defineProperty(e,"__esModule",{value:!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

SocketSocket SOC 2 Logo

Product

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

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc