@quiltt/core 2.1.0 → 2.1.1

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.
Files changed (67) hide show
  1. package/CHANGELOG.md +346 -0
  2. package/README.md +32 -9
  3. package/dist/{VersionLink-2203a632.d.ts → VersionLink-b7dfbaba.d.ts} +1 -1
  4. package/dist/api/graphql/index.cjs +4 -4
  5. package/dist/api/graphql/index.cjs.map +1 -1
  6. package/dist/api/graphql/index.d.ts +1 -1
  7. package/dist/api/graphql/index.js +3 -3
  8. package/dist/api/graphql/index.js.map +1 -1
  9. package/dist/api/graphql/links/actioncable/index.cjs +4 -4
  10. package/dist/api/graphql/links/actioncable/index.cjs.map +1 -1
  11. package/dist/api/graphql/links/actioncable/index.js +2 -2
  12. package/dist/api/graphql/links/actioncable/index.js.map +1 -1
  13. package/dist/api/graphql/links/index.cjs +2 -2
  14. package/dist/api/graphql/links/index.cjs.map +1 -1
  15. package/dist/api/graphql/links/index.d.ts +1 -1
  16. package/dist/api/graphql/links/index.js +2 -2
  17. package/dist/api/graphql/links/index.js.map +1 -1
  18. package/dist/api/index.cjs +1 -1
  19. package/dist/api/index.cjs.map +1 -1
  20. package/dist/api/index.d.ts +1 -1
  21. package/dist/api/index.js +1 -1
  22. package/dist/api/index.js.map +1 -1
  23. package/dist/api/rest/index.cjs +1 -1
  24. package/dist/api/rest/index.cjs.map +1 -1
  25. package/dist/api/rest/index.js +1 -1
  26. package/dist/api/rest/index.js.map +1 -1
  27. package/dist/index.cjs +5 -5
  28. package/dist/index.cjs.map +1 -1
  29. package/dist/index.d.ts +1 -1
  30. package/dist/index.js +2 -2
  31. package/dist/index.js.map +1 -1
  32. package/package.json +10 -2
  33. package/src/JsonWebToken.ts +48 -0
  34. package/src/Observable.ts +39 -0
  35. package/src/Storage/Local.ts +92 -0
  36. package/src/Storage/Memory.ts +43 -0
  37. package/src/Storage/index.ts +93 -0
  38. package/src/Timeoutable.ts +32 -0
  39. package/src/api/graphql/client.ts +48 -0
  40. package/src/api/graphql/index.ts +2 -0
  41. package/src/api/graphql/links/ActionCableLink.ts +93 -0
  42. package/src/api/graphql/links/AuthLink.ts +32 -0
  43. package/src/api/graphql/links/BatchHttpLink.ts +12 -0
  44. package/src/api/graphql/links/ErrorLink.ts +23 -0
  45. package/src/api/graphql/links/ForwardableLink.ts +5 -0
  46. package/src/api/graphql/links/HttpLink.ts +12 -0
  47. package/src/api/graphql/links/RetryLink.ts +10 -0
  48. package/src/api/graphql/links/SubscriptionLink.ts +11 -0
  49. package/src/api/graphql/links/TerminatingLink.ts +5 -0
  50. package/src/api/graphql/links/VersionLink.ts +15 -0
  51. package/src/api/graphql/links/actioncable/adapters.ts +4 -0
  52. package/src/api/graphql/links/actioncable/connection.ts +191 -0
  53. package/src/api/graphql/links/actioncable/connection_monitor.ts +139 -0
  54. package/src/api/graphql/links/actioncable/consumer.ts +87 -0
  55. package/src/api/graphql/links/actioncable/index.ts +35 -0
  56. package/src/api/graphql/links/actioncable/internal.ts +19 -0
  57. package/src/api/graphql/links/actioncable/logger.ts +16 -0
  58. package/src/api/graphql/links/actioncable/subscription.ts +44 -0
  59. package/src/api/graphql/links/actioncable/subscription_guarantor.ts +54 -0
  60. package/src/api/graphql/links/actioncable/subscriptions.ts +113 -0
  61. package/src/api/graphql/links/index.ts +9 -0
  62. package/src/api/index.ts +2 -0
  63. package/src/api/rest/AuthAPI.ts +115 -0
  64. package/src/api/rest/index.ts +1 -0
  65. package/src/configuration.ts +45 -0
  66. package/src/index.ts +6 -0
  67. package/src/types.ts +10 -0
package/CHANGELOG.md ADDED
@@ -0,0 +1,346 @@
1
+ # @quiltt/core
2
+
3
+ ## 2.1.1
4
+
5
+ ### Patch Changes
6
+
7
+ - 43131d5: - Add code examples to README
8
+ - Auto-create Github Releases
9
+ - Misc cleanups
10
+
11
+ ## 2.1.0
12
+
13
+ ### Minor Changes
14
+
15
+ - 7debd45: Add support for custom components 'as' props
16
+
17
+ ## 2.0.0
18
+
19
+ ### Major Changes
20
+
21
+ - bc6fd8c: Create new React Connector SDK helper components supported by refactored hook
22
+
23
+ ## 1.3.0
24
+
25
+ ### Minor Changes
26
+
27
+ - 6936687: - Fix transpilation issues caused by importing React components
28
+ - Add CI via Github Action
29
+ - Add test Next.js app
30
+ - Misc cleanups
31
+
32
+ ## 1.2.8
33
+
34
+ ### Patch Changes
35
+
36
+ - fa07b6a: Add READMEs
37
+
38
+ ## 1.2.7
39
+
40
+ ### Patch Changes
41
+
42
+ - 0321f3e: Filter packages to publish
43
+
44
+ ## 1.2.6
45
+
46
+ ### Patch Changes
47
+
48
+ - 1594b4a: Pass NPM_TOKEN for publishing
49
+
50
+ ## 1.2.5
51
+
52
+ ### Patch Changes
53
+
54
+ - ba18907: Publish to npm registry
55
+
56
+ ## 1.2.4
57
+
58
+ ### Patch Changes
59
+
60
+ - a05ccfc: Revert types/react and tsup
61
+
62
+ ## 1.2.3
63
+
64
+ ### Patch Changes
65
+
66
+ - 71ba4d9: Add react and react-dom as devDependency
67
+
68
+ ## 1.2.2
69
+
70
+ ### Patch Changes
71
+
72
+ - 89fca3b: Add useQuilttConnector hook
73
+
74
+ ## 1.2.1
75
+
76
+ ### Patch Changes
77
+
78
+ - 01e1247: Update packages
79
+
80
+ ## 1.2.0
81
+
82
+ ### Minor Changes
83
+
84
+ - 215662a: Update deps
85
+
86
+ ## 1.1.5
87
+
88
+ ### Patch Changes
89
+
90
+ - 4e237ce: Expose useEventListener
91
+
92
+ ## 1.1.4
93
+
94
+ ### Patch Changes
95
+
96
+ - c67e98d: Revert attempt to force reset through renders
97
+
98
+ ## 1.1.3
99
+
100
+ ### Patch Changes
101
+
102
+ - d8fdcaa: Add option to set QuilttProvider to reset on session change
103
+
104
+ ## 1.1.2
105
+
106
+ ### Patch Changes
107
+
108
+ - dcf2c5c: Improve session yanking after getting a 401
109
+
110
+ ## 1.1.1
111
+
112
+ ### Patch Changes
113
+
114
+ - 0a78cd2: Move session revoking to be directly to storage
115
+
116
+ ## 1.1.0
117
+
118
+ ### Minor Changes
119
+
120
+ - 7a1e387: Attempt to reduce race conditions with session changes by pulling token changing logic directly into the respective apollo links
121
+
122
+ ## 1.0.37
123
+
124
+ ### Patch Changes
125
+
126
+ - 9169fde: Reduce complexity of useSession by replacing useState with useMemo
127
+
128
+ ## 1.0.36
129
+
130
+ ### Patch Changes
131
+
132
+ - 9f34730: Remove redundant initializeState logic from useSession
133
+
134
+ ## 1.0.35
135
+
136
+ ### Patch Changes
137
+
138
+ - 14309ed: Update deps
139
+ - 6b8d7a4: Reduce the risk of race conditions double subscribing to localstorage changes
140
+
141
+ ## 1.0.34
142
+
143
+ ### Patch Changes
144
+
145
+ - 54a6574: Save localstorage before memorystorage to give localstorage more time to flush
146
+
147
+ ## 1.0.33
148
+
149
+ ### Patch Changes
150
+
151
+ - f0c60dd: Update useSession hook to memoize initialSession
152
+
153
+ ## 1.0.32
154
+
155
+ ### Patch Changes
156
+
157
+ - 97aa921: Revert adding loading state to graphql as it causes unexpected resets to subcomponents
158
+
159
+ ## 1.0.31
160
+
161
+ ### Patch Changes
162
+
163
+ - 18cb0a2: Add loading state to graphql provider to reduce unauthd requests
164
+
165
+ ## 1.0.30
166
+
167
+ ### Patch Changes
168
+
169
+ - 5d6027b: Fix issue with useSession setSession not being wrapped in useCallback, causing invalidations every render
170
+
171
+ ## 1.0.29
172
+
173
+ ### Patch Changes
174
+
175
+ - 098710f: Fix useEffect and useState looping hell
176
+
177
+ ## 1.0.28
178
+
179
+ ### Patch Changes
180
+
181
+ - 3877274: Fix issues with graphql client not being updated with new sessions
182
+
183
+ ## 1.0.27
184
+
185
+ ### Patch Changes
186
+
187
+ - 1b073ea: - Fix potential bugs and memory leaks in `Storage`
188
+ - Add helper hooks to compose other hooks
189
+ - Update useStorage hook
190
+
191
+ ## 1.0.26
192
+
193
+ ### Patch Changes
194
+
195
+ - 4a03bc8: Update types & fix linting
196
+
197
+ ## 1.0.25
198
+
199
+ ### Patch Changes
200
+
201
+ - 2ffea2f: Fix issue with this being undefined for ActionCableLink
202
+
203
+ ## 1.0.24
204
+
205
+ ### Patch Changes
206
+
207
+ - d9d234b: Switch to using globalThis for actioncable self
208
+
209
+ ## 1.0.23
210
+
211
+ ### Patch Changes
212
+
213
+ - 9fb69ae: Fix issues with SSR on nextjs and subscriptions
214
+
215
+ ## 1.0.22
216
+
217
+ ### Patch Changes
218
+
219
+ - 4a06719: Revert back to upstream packages
220
+
221
+ ## 1.0.21
222
+
223
+ ### Patch Changes
224
+
225
+ - 49f108a: Fix graphql subscriptions from not working due to channel name mismatch
226
+
227
+ ## 1.0.20
228
+
229
+ ### Patch Changes
230
+
231
+ - 7e0d314: Set cable to be a singleton to reduce the chance of having multiple trying to run
232
+
233
+ ## 1.0.19
234
+
235
+ ### Patch Changes
236
+
237
+ - 866407c: Improve websocket subscriptions lifecycle handling
238
+
239
+ ## 1.0.18
240
+
241
+ ### Patch Changes
242
+
243
+ - bf25cc4: Prevent websockets from attempting to connect without a token
244
+
245
+ ## 1.0.17
246
+
247
+ ### Patch Changes
248
+
249
+ - 190df4d: Fix issue with ActionCableLink calling the wrong #perform
250
+
251
+ ## 1.0.16
252
+
253
+ ### Patch Changes
254
+
255
+ - c284002: Add some types to actioncable and connect logging to config
256
+
257
+ ## 1.0.15
258
+
259
+ ### Patch Changes
260
+
261
+ - 2f6f903: Fix issue with importing sessions and cache resetting causing request cancelations during race conditions
262
+
263
+ ## 1.0.14
264
+
265
+ ### Patch Changes
266
+
267
+ - a97e9c8: Pin Dependencies & Update Linting
268
+ - 6d35bae: Remove unused global declares
269
+
270
+ ## 1.0.13
271
+
272
+ ### Patch Changes
273
+
274
+ - 24d28f3: Add missing apollo esms
275
+
276
+ ## 1.0.12
277
+
278
+ ### Patch Changes
279
+
280
+ - 3eb86ce: Force load all of apollo esms
281
+
282
+ ## 1.0.11
283
+
284
+ ### Patch Changes
285
+
286
+ - 2932555: Load ActionLinkCable Apollo esms
287
+
288
+ ## 1.0.10
289
+
290
+ ### Patch Changes
291
+
292
+ - f014a84: Set apollo links to load esm from .js
293
+
294
+ ## 1.0.9
295
+
296
+ ### Patch Changes
297
+
298
+ - be8e696: Attempt to improve esm loading of apollo links
299
+
300
+ ## 1.0.8
301
+
302
+ ### Patch Changes
303
+
304
+ - 250f817: Refactor AuthLink to improve compiling
305
+
306
+ ## 1.0.7
307
+
308
+ ### Patch Changes
309
+
310
+ - 9e78757: Fix issues with QuilttClient/Link not working
311
+
312
+ ## 1.0.6
313
+
314
+ ### Patch Changes
315
+
316
+ - 882b229: Set default forwardlink within quiltt link
317
+
318
+ ## 1.0.5
319
+
320
+ ### Patch Changes
321
+
322
+ - 795bf20: Improve how graphql client is loaded
323
+
324
+ ## 1.0.4
325
+
326
+ ### Patch Changes
327
+
328
+ - 9bc26d1: Import action cable code to help with building
329
+
330
+ ## 1.0.3
331
+
332
+ ### Patch Changes
333
+
334
+ - 19a5f41: Allow client id to be optional for token based apps
335
+
336
+ ## 1.0.2
337
+
338
+ ### Patch Changes
339
+
340
+ - 3f06262: Update build config
341
+
342
+ ## 1.0.1
343
+
344
+ ### Patch Changes
345
+
346
+ - 86d6689: Fix issue with react not reexporting core
package/README.md CHANGED
@@ -1,18 +1,37 @@
1
1
  # @quiltt/core
2
2
 
3
- ## Overview
3
+ [![npm version](https://badge.fury.io/js/@quiltt%2Fcore.svg)](https://badge.fury.io/js/@quiltt%2Fcore)
4
+ [![CI](https://github.com/quiltt/quiltt-public/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/quiltt/quiltt-public/actions/workflows/ci.yml)
4
5
 
5
- `@quiltt/core` is a comprehensive JavaScript library that provides essential functionality for building applications. It offers various modules, utilities, and types that can be utilized to enhance your development workflow.
6
+ `@quiltt/core` provides essential functionality for building Javascript-based applications with Quiltt. It provides an Auth API client and modules for handling JSON Web Tokens (JWT), observables, storage management, timeouts, API handling, and Typescript types.
6
7
 
7
- ## Installation
8
-
9
- To install `@quiltt/core` in your project, you need to have Node.js and npm (Node Package Manager) installed. Then, you can run the following command:
8
+ ## Install
10
9
 
11
10
  ```shell
12
- npm install @quiltt/core
11
+ $ npm install @quiltt/core
12
+ # or
13
+ $ yarn add @quiltt/core
14
+ # or
15
+ $ pnpm add @quiltt/core
13
16
  ```
14
17
 
15
- ## Features
18
+ ## Auth API Client
19
+
20
+ ```ts
21
+ // Import Auth API client
22
+ import { AuthAPI } from '@quiltt/core'
23
+
24
+ // Set up client instance
25
+ const auth = new AuthAPI()
26
+
27
+ // Check if a Session token is valid
28
+ auth.ping('{SESSION_TOKEN}')
29
+
30
+ // Revoke a Session token
31
+ auth.revoke('{SESSION_TOKEN}')
32
+ ```
33
+
34
+ ## Modules
16
35
 
17
36
  ### JsonWebToken
18
37
 
@@ -47,10 +66,14 @@ import { JsonWebToken, Observable, Storage, Timeoutable, api, types } from '@qui
47
66
  // ...
48
67
  ```
49
68
 
69
+ ## Typescript support
70
+
71
+ `@quiltt/core` is written in Typescript and ships with its own type definitions.
72
+
50
73
  ## License
51
74
 
52
75
  This project is licensed under the terms of the MIT license. See the [LICENSE](LICENSE.md) file for more information.
53
76
 
54
- For information on how to contribute to this project, please refer to the [CONTRIBUTING.md](CONTRIBUTING.md) file.
77
+ ## Contributing
55
78
 
56
- By moving the development guidelines to a CONTRIBUTING.md file, it allows you to provide more detailed instructions on how to contribute, including information on setting up a development environment, running tests, coding guidelines, and submitting pull requests.
79
+ For information on how to contribute to this project, please refer to the [CONTRIBUTING.md](CONTRIBUTING.md) file.
@@ -7,7 +7,7 @@ import { ApolloLink as ApolloLink$1, Operation as Operation$1, NextLink as NextL
7
7
  import { C as Consumer } from './consumer-c13efb94.js';
8
8
 
9
9
  /**
10
- * unauthorizedCallback only triggers in the event the the token is present, and
10
+ * unauthorizedCallback only triggers in the event the token is present, and
11
11
  * returns the token; This allows sessions to be forgotten without race conditions
12
12
  * causing null sessions to kill valid sessions, or invalid sessions for killing
13
13
  * valid sessions during rotation and networking weirdness.
@@ -2,7 +2,7 @@
2
2
 
3
3
  var index_js = require('@apollo/client/index.js');
4
4
  var index_js$1 = require('@apollo/client/link/batch-http/index.js');
5
- var wt = require('cross-fetch');
5
+ var Tt = require('cross-fetch');
6
6
  var index_js$2 = require('@apollo/client/link/error/index.js');
7
7
  var index_js$3 = require('@apollo/client/link/http/index.js');
8
8
  var index_js$4 = require('@apollo/client/link/retry/index.js');
@@ -11,9 +11,9 @@ var graphql = require('graphql');
11
11
 
12
12
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
13
13
 
14
- var wt__default = /*#__PURE__*/_interopDefault(wt);
14
+ var Tt__default = /*#__PURE__*/_interopDefault(Tt);
15
15
 
16
- var dt=Object.defineProperty,mt=Object.defineProperties;var ft=Object.getOwnPropertyDescriptors;var Q=Object.getOwnPropertySymbols;var bt=Object.prototype.hasOwnProperty,gt=Object.prototype.propertyIsEnumerable;var N=(o,t,e)=>t in o?dt(o,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):o[t]=e,u=(o,t)=>{for(var e in t||(t={}))bt.call(t,e)&&N(o,e,t[e]);if(Q)for(var e of Q(t))gt.call(t,e)&&N(o,e,t[e]);return o},x=(o,t)=>mt(o,ft(t));var r=(o,t,e)=>(N(o,typeof t!="symbol"?t+"":t,e),e);var T=class{constructor(){r(this,"observers",{});r(this,"isEnabled",()=>{try{return localStorage.setItem("quiltt.ping","pong"),localStorage.removeItem("quiltt.ping"),!0}catch(t){return !1}});r(this,"isDisabled",()=>!this.isEnabled());r(this,"get",t=>{if(typeof window!="undefined")try{let e=window.localStorage.getItem(`quiltt.${t}`);return e&&JSON.parse(e)}catch(e){console.warn(`localStorage Error: "quiltt.${t}"`,e);return}});r(this,"set",(t,e)=>{if(typeof window!="undefined")try{e?window.localStorage.setItem(`quiltt.${t}`,JSON.stringify(e)):window.localStorage.removeItem(`quiltt.${t}`);}catch(n){console.warn(`localStorage Error: "quiltt.${t}"`,n);}});r(this,"remove",t=>{try{window.localStorage.removeItem(`quiltt.${t}`);}catch(e){console.warn(`localStorage Error: "quiltt.${t}">`,e);}});r(this,"subscribe",(t,e)=>{this.observers[t]||(this.observers[t]=[]),this.observers[t].push(e);});r(this,"unsubscribe",(t,e)=>{var n;this.observers[t]=(n=this.observers[t])==null?void 0:n.filter(i=>i!==e);});r(this,"handleStorageEvent",t=>{if(t.key&&t.key.includes("quiltt.")){let e=t.newValue?JSON.parse(t.newValue):null;this.observers[t.key]&&this.observers[t.key].forEach(n=>n(e));}else Object.entries(this.observers).forEach(([e,n])=>{n.forEach(i=>i(this.get(e)));});});typeof window!="undefined"&&window.addEventListener("storage",this.handleStorageEvent.bind(this));}};var f=class{constructor(t){r(this,"state");r(this,"observers",[]);r(this,"get",()=>this.state);r(this,"set",t=>{this.state!==t&&(this.state=t,this.observers.forEach(e=>e(t)));});r(this,"subscribe",t=>{this.observers.push(t);});r(this,"unsubscribe",t=>{this.observers=this.observers.filter(e=>e!==t);});this.state=t;}};var w=class{constructor(){r(this,"observables",{});r(this,"get",t=>{if(this.observables[t])return this.observables[t].get()});r(this,"set",(t,e)=>{this.observables[t]?this.observables[t].set(e):this.observables[t]=new f(e);});r(this,"subscribe",(t,e)=>{this.observables[t]||(this.observables[t]=new f),this.observables[t].subscribe(e);});r(this,"unsubscribe",(t,e)=>{this.observables[t]&&this.observables[t].unsubscribe(e);});}};var R=class{constructor(){r(this,"memoryStore",new w);r(this,"localStore",new T);r(this,"observers",{});r(this,"monitors",new Set);r(this,"get",t=>{this.monitorLocalStorageChanges(t);let e=this.memoryStore.get(t);return e===void 0&&(e=this.localStore.get(t)),e});r(this,"set",(t,e)=>{var n;this.monitorLocalStorageChanges(t),this.localStore.set(t,e),this.memoryStore.set(t,e),(n=this.observers[t])==null||n.forEach(i=>i(e));});r(this,"subscribe",(t,e)=>{this.observers[t]||(this.observers[t]=[]),this.observers[t].push(e);});r(this,"unsubscribe",(t,e)=>{var n;this.observers[t]=(n=this.observers[t])==null?void 0:n.filter(i=>i!==e);});r(this,"monitorLocalStorageChanges",t=>{this.monitors.has(t)||(this.monitors.add(t),this.localStore.subscribe(t,e=>{var c;let n=this.memoryStore.get(t),i=e instanceof Function?e(n):e;this.memoryStore.set(t,i),(c=this.observers[t])==null||c.forEach(d=>d(i));}));});}},h=new R;var A=class extends index_js.ApolloLink{request(t,e){let n=h.get("session");return n?(t.setContext(({headers:i={}})=>({headers:x(u({},i),{authorization:`Bearer ${n}`})})),e(t)):(console.warn("QuilttLink attempted to send an unauthenticated Query"),null)}};var U="@quiltt/core",B="2.1.0";var St=(()=>{try{return process.env.QUILTT_API_INSECURE}catch(o){return}})(),V=(()=>{try{return process.env.QUILTT_API_DOMAIN}catch(o){return}})(),yt=(()=>{try{return !!process.env.QUILTT_DEBUG||process.env.NODE_ENV!=="production"}catch(o){return !1}})(),E=V||"quiltt.io",F=`http${St?"":"s"}`,xt=`ws${V?"":"s"}`,k=yt,C=`${F}://api.${E}/v1/graphql`,J=`${xt}://api.${E}/websockets`,z=`${U}: v${B}`;var K=new index_js$1.BatchHttpLink({uri:C,fetch:wt__default.default});var X=index_js$2.onError(({graphQLErrors:o,networkError:t})=>{o&&o.forEach(({message:e,locations:n,path:i})=>{console.log(`[GraphQL error]: Message: ${e}, Location: ${n}, Path: ${i}`);}),t&&(t.statusCode===401?(console.warn("[Authentication error]:",t),h.set("session",null)):console.warn("[Network error]:",t));});var Y=new index_js.ApolloLink((o,t)=>t(o));var Z=new index_js$3.HttpLink({uri:C,fetch:wt__default.default});var tt=new index_js$4.RetryLink({attempts:{retryIf:(o,t)=>o.statusCode>=500}});var l={logger:typeof globalThis!="undefined"?globalThis.console:void 0,WebSocket:typeof globalThis!="undefined"?globalThis.WebSocket:void 0};var I=class{constructor(){r(this,"enabled",k);}log(...t){l.logger&&this.enabled&&(t.push(Date.now().toString()),l.logger.log("[ActionCable]",...t));}},$t=new I,s=$t;var b=()=>new Date().getTime(),O=o=>(b()-o)/1e3,g=class{constructor(t){this.visibilityDidChange=this.visibilityDidChange.bind(this),this.connection=t,this.reconnectAttempts=0;}start(){this.isRunning()||(this.startedAt=b(),delete this.stoppedAt,this.startPolling(),addEventListener("visibilitychange",this.visibilityDidChange),s.log(`ConnectionMonitor started. stale threshold = ${this.constructor.staleThreshold} s`));}stop(){this.isRunning()&&(this.stoppedAt=b(),this.stopPolling(),removeEventListener("visibilitychange",this.visibilityDidChange),s.log("ConnectionMonitor stopped"));}isRunning(){return this.startedAt&&!this.stoppedAt}recordPing(){this.pingedAt=b();}recordConnect(){this.reconnectAttempts=0,this.recordPing(),delete this.disconnectedAt,s.log("ConnectionMonitor recorded connect");}recordDisconnect(){this.disconnectedAt=b(),s.log("ConnectionMonitor recorded disconnect");}startPolling(){this.stopPolling(),this.poll();}stopPolling(){clearTimeout(this.pollTimeout);}poll(){this.pollTimeout=setTimeout(()=>{this.reconnectIfStale(),this.poll();},this.getPollInterval());}getPollInterval(){let{staleThreshold:t,reconnectionBackoffRate:e}=this.constructor,n=Math.pow(1+e,Math.min(this.reconnectAttempts,10)),c=(this.reconnectAttempts===0?1:e)*Math.random();return t*1e3*n*(1+c)}reconnectIfStale(){this.connectionIsStale()&&(s.log(`ConnectionMonitor detected stale connection. reconnectAttempts = ${this.reconnectAttempts}, time stale = ${O(this.refreshedAt)} s, stale threshold = ${this.constructor.staleThreshold} s`),this.reconnectAttempts++,this.disconnectedRecently()?s.log(`ConnectionMonitor skipping reopening recent disconnect. time disconnected = ${O(this.disconnectedAt)} s`):(s.log("ConnectionMonitor reopening"),this.connection.reopen()));}get refreshedAt(){return this.pingedAt?this.pingedAt:this.startedAt}connectionIsStale(){return O(this.refreshedAt)>this.constructor.staleThreshold}disconnectedRecently(){return this.disconnectedAt&&O(this.disconnectedAt)<this.constructor.staleThreshold}visibilityDidChange(){document.visibilityState==="visible"&&setTimeout(()=>{(this.connectionIsStale()||!this.connection.isOpen())&&(s.log(`ConnectionMonitor reopening stale connection on visibilitychange. visibilityState = ${document.visibilityState}`),this.connection.reopen());},200);}};g.staleThreshold=6;g.reconnectionBackoffRate=.15;var et=g;var Nt={message_types:{welcome:"welcome",disconnect:"disconnect",ping:"ping",confirmation:"confirm_subscription",rejection:"reject_subscription"},disconnect_reasons:{unauthorized:"unauthorized",invalid_request:"invalid_request",server_restart:"server_restart",remote:"remote"},default_mount_path:"/cable",protocols:["actioncable-v1-json","actioncable-unsupported"]},L=Nt;var{message_types:v,protocols:M}=L,Rt=M.slice(0,M.length-1),ot=[].indexOf,S=class{constructor(t){this.open=this.open.bind(this),this.consumer=t,this.subscriptions=this.consumer.subscriptions,this.monitor=new et(this),this.disconnected=!0;}send(t){return this.isOpen()?(this.webSocket.send(JSON.stringify(t)),!0):!1}open(){if(this.isActive())return s.log(`Attempted to open WebSocket, but existing socket is ${this.getState()}`),!1;{let t=[...M,...this.consumer.subprotocols||[]];return s.log(`Opening WebSocket, current state is ${this.getState()}, subprotocols: ${t}`),this.webSocket&&this.uninstallEventHandlers(),this.webSocket=new l.WebSocket(this.consumer.url,t),this.installEventHandlers(),this.monitor.start(),!0}}close({allowReconnect:t}={allowReconnect:!0}){if(t||this.monitor.stop(),this.isOpen())return this.webSocket.close()}reopen(){if(s.log(`Reopening WebSocket, current state is ${this.getState()}`),this.isActive())try{return this.close()}catch(t){s.log("Failed to reopen WebSocket",t);}finally{s.log(`Reopening WebSocket in ${this.constructor.reopenDelay}ms`),setTimeout(this.open,this.constructor.reopenDelay);}else return this.open()}getProtocol(){if(this.webSocket)return this.webSocket.protocol}isOpen(){return this.isState("open")}isActive(){return this.isState("open","connecting")}triedToReconnect(){return this.monitor.reconnectAttempts>0}isProtocolSupported(){return ot.call(Rt,this.getProtocol())>=0}isState(...t){return ot.call(t,this.getState())>=0}getState(){if(this.webSocket){for(let t in l.WebSocket)if(l.WebSocket[t]===this.webSocket.readyState)return t.toLowerCase()}return null}installEventHandlers(){for(let t in this.events){let e=this.events[t].bind(this);this.webSocket[`on${t}`]=e;}}uninstallEventHandlers(){for(let t in this.events)this.webSocket[`on${t}`]=function(){};}};S.reopenDelay=500;S.prototype.events={message(o){if(!this.isProtocolSupported())return;let{identifier:t,message:e,reason:n,reconnect:i,type:c}=JSON.parse(o.data);switch(c){case v.welcome:return this.triedToReconnect()&&(this.reconnectAttempted=!0),this.monitor.recordConnect(),this.subscriptions.reload();case v.disconnect:return s.log(`Disconnecting. Reason: ${n}`),this.close({allowReconnect:i});case v.ping:return this.monitor.recordPing();case v.confirmation:return this.subscriptions.confirmSubscription(t),this.reconnectAttempted?(this.reconnectAttempted=!1,this.subscriptions.notify(t,"connected",{reconnected:!0})):this.subscriptions.notify(t,"connected",{reconnected:!1});case v.rejection:return this.subscriptions.reject(t);default:return this.subscriptions.notify(t,"received",e)}},open(){if(s.log(`WebSocket onopen event, using '${this.getProtocol()}' subprotocol`),this.disconnected=!1,!this.isProtocolSupported())return s.log("Protocol is unsupported. Stopping monitor and disconnecting."),this.close({allowReconnect:!1})},close(o){if(s.log("WebSocket onclose event"),!this.disconnected)return this.disconnected=!0,this.monitor.recordDisconnect(),this.subscriptions.notifyAll("disconnected",{willAttemptReconnect:this.monitor.isRunning()})},error(){s.log("WebSocket onerror event");}};var rt=S;var Et=function(o,t){if(t!==null)for(let e in t){let n=t[e];o[e]=n;}return o},P=class{constructor(t,e={},n){r(this,"consumer");r(this,"identifier");this.consumer=t,this.identifier=JSON.stringify(e),Et(this,n);}perform(t,e={}){return e.action=t,this.send(e)}send(t){return this.consumer.send({command:"message",identifier:this.identifier,data:JSON.stringify(t)})}unsubscribe(){return this.consumer.subscriptions.remove(this)}},nt=P;var D=class{constructor(t){r(this,"subscriptions");r(this,"pendingSubscriptions");r(this,"retryTimeout");this.subscriptions=t,this.pendingSubscriptions=[];}guarantee(t){this.pendingSubscriptions.indexOf(t)==-1?(s.log(`SubscriptionGuarantor guaranteeing ${t.identifier}`),this.pendingSubscriptions.push(t)):s.log(`SubscriptionGuarantor already guaranteeing ${t.identifier}`),this.startGuaranteeing();}forget(t){s.log(`SubscriptionGuarantor forgetting ${t.identifier}`),this.pendingSubscriptions=this.pendingSubscriptions.filter(e=>e!==t);}startGuaranteeing(){this.stopGuaranteeing(),this.retrySubscribing();}stopGuaranteeing(){clearTimeout(this.retryTimeout);}retrySubscribing(){this.retryTimeout=setTimeout(()=>{this.subscriptions&&typeof this.subscriptions.subscribe=="function"&&this.pendingSubscriptions.map(t=>{s.log(`SubscriptionGuarantor resubscribing ${t.identifier}`),this.subscriptions.subscribe(t);});},500);}},it=D;var q=class{constructor(t){r(this,"consumer");r(this,"guarantor");r(this,"subscriptions");this.consumer=t,this.guarantor=new it(this),this.subscriptions=[];}create(t,e){let n=t,i=typeof n=="object"?n:{channel:n},c=new nt(this.consumer,i,e);return this.add(c)}add(t){return this.subscriptions.push(t),this.consumer.ensureActiveConnection(),this.notify(t,"initialized"),this.subscribe(t),t}remove(t){return this.forget(t),this.findAll(t.identifier).length||this.sendCommand(t,"unsubscribe"),t}reject(t){return this.findAll(t).map(e=>(this.forget(e),this.notify(e,"rejected"),e))}forget(t){return this.guarantor.forget(t),this.subscriptions=this.subscriptions.filter(e=>e!==t),t}findAll(t){return this.subscriptions.filter(e=>e.identifier===t)}reload(){return this.subscriptions.map(t=>this.subscribe(t))}notifyAll(t,...e){return this.subscriptions.map(n=>this.notify(n,t,...e))}notify(t,e,...n){let i;return typeof t=="string"?i=this.findAll(t):i=[t],i.map(c=>typeof c[e]=="function"?c[e](...n):void 0)}subscribe(t){this.sendCommand(t,"subscribe")&&this.guarantor.guarantee(t);}confirmSubscription(t){s.log(`Subscription confirmed ${t}`),this.findAll(t).map(e=>this.guarantor.forget(e));}sendCommand(t,e){let{identifier:n}=t;return this.consumer.send({command:e,identifier:n})}},st=q;var j=class{constructor(t){r(this,"_url");r(this,"subscriptions");r(this,"connection");r(this,"subprotocols");this._url=t,this.subscriptions=new st(this),this.connection=new rt(this),this.subprotocols=[];}get url(){return ct(this._url)}send(t){return this.connection.send(t)}connect(){return this.connection.open()}disconnect(){return this.connection.close({allowReconnect:!1})}ensureActiveConnection(){if(!this.connection.isActive())return this.connection.open()}addSubProtocol(t){this.subprotocols=[...this.subprotocols,t];}};function ct(o){if(typeof o=="function"&&(o=o()),o&&!/^wss?:/i.test(o)){let t=document.createElement("a");return t.href=o,t.href=t.href,t.protocol=t.protocol.replace("http","ws"),t.href}else return o}var at=j;function lt(o=It("url")||L.default_mount_path){return new at(o)}function It(o){let t=document.head.querySelector(`meta[name='action-cable-${o}']`);if(t)return t.getAttribute("content")}var _=class extends index_js$5.ApolloLink{constructor(e){super();r(this,"cables");r(this,"channelName");r(this,"actionName");r(this,"connectionParams");this.cables={},this.channelName=e.channelName||"GraphqlChannel",this.actionName=e.actionName||"execute",this.connectionParams=e.connectionParams||{};}request(e,n){let i=h.get("session");return i?(this.cables[i]||(this.cables[i]=lt(J+(i?`?token=${i}`:""))),new index_js$5.Observable(c=>{let d=Math.round(Date.now()+Math.random()*1e5).toString(16),m=this.actionName,p=typeof this.connectionParams=="function"?this.connectionParams(e):this.connectionParams,y=this.cables[i].subscriptions.create(Object.assign({},{channel:this.channelName,channelId:d},p),{connected:()=>{y.perform(m,{query:e.query?graphql.print(e.query):null,variables:e.variables,operationId:e.operationId,operationName:e.operationName});},received:a=>{var G,W;((G=a==null?void 0:a.result)!=null&&G.data||(W=a==null?void 0:a.result)!=null&&W.errors)&&c.next(a.result),a.more||c.complete();}});return Object.assign(y,{closed:!1})})):(console.warn("QuilttLink attempted to send an unauthenticated Subscription"),null)}},pt=_;var $=class extends pt{constructor(){super({channelName:"GraphQLChannel"});}};var po=new index_js.ApolloLink(()=>null);var ut=new index_js.ApolloLink((o,t)=>(o.setContext(({headers:e={}})=>({headers:x(u({},e),{"Quiltt-Client-Version":z})})),t(o)));var ht=class extends index_js.ApolloClient{constructor(t){t.connectToDevTools||(t.connectToDevTools=k);let e=m=>m.query.definitions.some(({kind:p,operation:y})=>p==="OperationDefinition"&&y==="subscription"),n=m=>{var p;return (p=m.getContext().batchable)!=null?p:!0},i=new A,c=new $,d=index_js.ApolloLink.from([ut,i,X,tt]).split(e,c,Y).split(n,K,Z);super(u({link:d},t));}};
16
+ var dt=Object.defineProperty,mt=Object.defineProperties;var ft=Object.getOwnPropertyDescriptors;var Q=Object.getOwnPropertySymbols;var bt=Object.prototype.hasOwnProperty,gt=Object.prototype.propertyIsEnumerable;var $=(o,t,e)=>t in o?dt(o,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):o[t]=e,u=(o,t)=>{for(var e in t||(t={}))bt.call(t,e)&&$(o,e,t[e]);if(Q)for(var e of Q(t))gt.call(t,e)&&$(o,e,t[e]);return o},x=(o,t)=>mt(o,ft(t));var r=(o,t,e)=>($(o,typeof t!="symbol"?t+"":t,e),e);var w=class{constructor(){r(this,"observers",{});r(this,"isEnabled",()=>{try{return localStorage.setItem("quiltt.ping","pong"),localStorage.removeItem("quiltt.ping"),!0}catch(t){return !1}});r(this,"isDisabled",()=>!this.isEnabled());r(this,"get",t=>{if(typeof window!="undefined")try{let e=window.localStorage.getItem(`quiltt.${t}`);return e&&JSON.parse(e)}catch(e){console.warn(`localStorage Error: "quiltt.${t}"`,e);return}});r(this,"set",(t,e)=>{if(typeof window!="undefined")try{e?window.localStorage.setItem(`quiltt.${t}`,JSON.stringify(e)):window.localStorage.removeItem(`quiltt.${t}`);}catch(i){console.warn(`localStorage Error: "quiltt.${t}"`,i);}});r(this,"remove",t=>{try{window.localStorage.removeItem(`quiltt.${t}`);}catch(e){console.warn(`localStorage Error: "quiltt.${t}">`,e);}});r(this,"subscribe",(t,e)=>{this.observers[t]||(this.observers[t]=[]),this.observers[t].push(e);});r(this,"unsubscribe",(t,e)=>{var i;this.observers[t]=(i=this.observers[t])==null?void 0:i.filter(n=>n!==e);});r(this,"handleStorageEvent",t=>{if(t.key&&t.key.includes("quiltt.")){let e=t.newValue?JSON.parse(t.newValue):null;this.observers[t.key]&&this.observers[t.key].forEach(i=>i(e));}else Object.entries(this.observers).forEach(([e,i])=>{i.forEach(n=>n(this.get(e)));});});typeof window!="undefined"&&window.addEventListener("storage",this.handleStorageEvent.bind(this));}};var f=class{constructor(t){r(this,"state");r(this,"observers",[]);r(this,"get",()=>this.state);r(this,"set",t=>{this.state!==t&&(this.state=t,this.observers.forEach(e=>e(t)));});r(this,"subscribe",t=>{this.observers.push(t);});r(this,"unsubscribe",t=>{this.observers=this.observers.filter(e=>e!==t);});this.state=t;}};var T=class{constructor(){r(this,"observables",{});r(this,"get",t=>{if(this.observables[t])return this.observables[t].get()});r(this,"set",(t,e)=>{this.observables[t]?this.observables[t].set(e):this.observables[t]=new f(e);});r(this,"subscribe",(t,e)=>{this.observables[t]||(this.observables[t]=new f),this.observables[t].subscribe(e);});r(this,"unsubscribe",(t,e)=>{this.observables[t]&&this.observables[t].unsubscribe(e);});}};var E=class{constructor(){r(this,"memoryStore",new T);r(this,"localStore",new w);r(this,"observers",{});r(this,"monitors",new Set);r(this,"get",t=>{this.monitorLocalStorageChanges(t);let e=this.memoryStore.get(t);return e===void 0&&(e=this.localStore.get(t)),e});r(this,"set",(t,e)=>{var i;this.monitorLocalStorageChanges(t),this.localStore.set(t,e),this.memoryStore.set(t,e),(i=this.observers[t])==null||i.forEach(n=>n(e));});r(this,"subscribe",(t,e)=>{this.observers[t]||(this.observers[t]=[]),this.observers[t].push(e);});r(this,"unsubscribe",(t,e)=>{var i;this.observers[t]=(i=this.observers[t])==null?void 0:i.filter(n=>n!==e);});r(this,"monitorLocalStorageChanges",t=>{this.monitors.has(t)||(this.monitors.add(t),this.localStore.subscribe(t,e=>{var c;let i=this.memoryStore.get(t),n=e instanceof Function?e(i):e;this.memoryStore.set(t,n),(c=this.observers[t])==null||c.forEach(d=>d(n));}));});}},h=new E;var A=class extends index_js.ApolloLink{request(t,e){let i=h.get("session");return i?(t.setContext(({headers:n={}})=>({headers:x(u({},n),{authorization:`Bearer ${i}`})})),e(t)):(console.warn("QuilttLink attempted to send an unauthenticated Query"),null)}};var U="@quiltt/core",B="2.1.1";var St=(()=>{try{return process.env.QUILTT_API_INSECURE}catch(o){return}})(),V=(()=>{try{return process.env.QUILTT_API_DOMAIN}catch(o){return}})(),yt=(()=>{try{return !!process.env.QUILTT_DEBUG||process.env.NODE_ENV!=="production"}catch(o){return !1}})(),R=V||"quiltt.io",F=`http${St?"":"s"}`,xt=`ws${V?"":"s"}`,k=yt,C=`${F}://api.${R}/v1/graphql`,J=`${xt}://api.${R}/websockets`,z=`${U}: v${B}`;var K=new index_js$1.BatchHttpLink({uri:C,fetch:Tt__default.default});var X=index_js$2.onError(({graphQLErrors:o,networkError:t})=>{o&&o.forEach(({message:e,locations:i,path:n})=>{console.log(`[GraphQL error]: Message: ${e}, Location: ${i}, Path: ${n}`);}),t&&(t.statusCode===401?(console.warn("[Authentication error]:",t),h.set("session",null)):console.warn("[Network error]:",t));});var Y=new index_js.ApolloLink((o,t)=>t(o));var Z=new index_js$3.HttpLink({uri:C,fetch:Tt__default.default});var tt=new index_js$4.RetryLink({attempts:{retryIf:(o,t)=>o.statusCode>=500}});var l={logger:typeof globalThis!="undefined"?globalThis.console:void 0,WebSocket:typeof globalThis!="undefined"?globalThis.WebSocket:void 0};var I=class{constructor(){r(this,"enabled",k);}log(...t){l.logger&&this.enabled&&(t.push(Date.now().toString()),l.logger.log("[ActionCable]",...t));}},Nt=new I,s=Nt;var b=()=>new Date().getTime(),O=o=>(b()-o)/1e3,g=class{constructor(t){this.visibilityDidChange=this.visibilityDidChange.bind(this),this.connection=t,this.reconnectAttempts=0;}start(){this.isRunning()||(this.startedAt=b(),delete this.stoppedAt,this.startPolling(),addEventListener("visibilitychange",this.visibilityDidChange),s.log(`ConnectionMonitor started. stale threshold = ${this.constructor.staleThreshold} s`));}stop(){this.isRunning()&&(this.stoppedAt=b(),this.stopPolling(),removeEventListener("visibilitychange",this.visibilityDidChange),s.log("ConnectionMonitor stopped"));}isRunning(){return this.startedAt&&!this.stoppedAt}recordPing(){this.pingedAt=b();}recordConnect(){this.reconnectAttempts=0,this.recordPing(),delete this.disconnectedAt,s.log("ConnectionMonitor recorded connect");}recordDisconnect(){this.disconnectedAt=b(),s.log("ConnectionMonitor recorded disconnect");}startPolling(){this.stopPolling(),this.poll();}stopPolling(){clearTimeout(this.pollTimeout);}poll(){this.pollTimeout=setTimeout(()=>{this.reconnectIfStale(),this.poll();},this.getPollInterval());}getPollInterval(){let{staleThreshold:t,reconnectionBackoffRate:e}=this.constructor,i=Math.pow(1+e,Math.min(this.reconnectAttempts,10)),c=(this.reconnectAttempts===0?1:e)*Math.random();return t*1e3*i*(1+c)}reconnectIfStale(){this.connectionIsStale()&&(s.log(`ConnectionMonitor detected stale connection. reconnectAttempts = ${this.reconnectAttempts}, time stale = ${O(this.refreshedAt)} s, stale threshold = ${this.constructor.staleThreshold} s`),this.reconnectAttempts++,this.disconnectedRecently()?s.log(`ConnectionMonitor skipping reopening recent disconnect. time disconnected = ${O(this.disconnectedAt)} s`):(s.log("ConnectionMonitor reopening"),this.connection.reopen()));}get refreshedAt(){return this.pingedAt?this.pingedAt:this.startedAt}connectionIsStale(){return O(this.refreshedAt)>this.constructor.staleThreshold}disconnectedRecently(){return this.disconnectedAt&&O(this.disconnectedAt)<this.constructor.staleThreshold}visibilityDidChange(){document.visibilityState==="visible"&&setTimeout(()=>{(this.connectionIsStale()||!this.connection.isOpen())&&(s.log(`ConnectionMonitor reopening stale connection on visibilitychange. visibilityState = ${document.visibilityState}`),this.connection.reopen());},200);}};g.staleThreshold=6;g.reconnectionBackoffRate=.15;var et=g;var $t={message_types:{welcome:"welcome",disconnect:"disconnect",ping:"ping",confirmation:"confirm_subscription",rejection:"reject_subscription"},disconnect_reasons:{unauthorized:"unauthorized",invalid_request:"invalid_request",server_restart:"server_restart",remote:"remote"},default_mount_path:"/cable",protocols:["actioncable-v1-json","actioncable-unsupported"]},L=$t;var{message_types:v,protocols:M}=L,Et=M.slice(0,M.length-1),ot=[].indexOf,S=class{constructor(t){this.open=this.open.bind(this),this.consumer=t,this.subscriptions=this.consumer.subscriptions,this.monitor=new et(this),this.disconnected=!0;}send(t){return this.isOpen()?(this.webSocket.send(JSON.stringify(t)),!0):!1}open(){if(this.isActive())return s.log(`Attempted to open WebSocket, but existing socket is ${this.getState()}`),!1;{let t=[...M,...this.consumer.subprotocols||[]];return s.log(`Opening WebSocket, current state is ${this.getState()}, subprotocols: ${t}`),this.webSocket&&this.uninstallEventHandlers(),this.webSocket=new l.WebSocket(this.consumer.url,t),this.installEventHandlers(),this.monitor.start(),!0}}close({allowReconnect:t}={allowReconnect:!0}){if(t||this.monitor.stop(),this.isOpen())return this.webSocket.close()}reopen(){if(s.log(`Reopening WebSocket, current state is ${this.getState()}`),this.isActive())try{return this.close()}catch(t){s.log("Failed to reopen WebSocket",t);}finally{s.log(`Reopening WebSocket in ${this.constructor.reopenDelay}ms`),setTimeout(this.open,this.constructor.reopenDelay);}else return this.open()}getProtocol(){if(this.webSocket)return this.webSocket.protocol}isOpen(){return this.isState("open")}isActive(){return this.isState("open","connecting")}triedToReconnect(){return this.monitor.reconnectAttempts>0}isProtocolSupported(){return ot.call(Et,this.getProtocol())>=0}isState(...t){return ot.call(t,this.getState())>=0}getState(){if(this.webSocket){for(let t in l.WebSocket)if(l.WebSocket[t]===this.webSocket.readyState)return t.toLowerCase()}return null}installEventHandlers(){for(let t in this.events){let e=this.events[t].bind(this);this.webSocket[`on${t}`]=e;}}uninstallEventHandlers(){for(let t in this.events)this.webSocket[`on${t}`]=function(){};}};S.reopenDelay=500;S.prototype.events={message(o){if(!this.isProtocolSupported())return;let{identifier:t,message:e,reason:i,reconnect:n,type:c}=JSON.parse(o.data);switch(c){case v.welcome:return this.triedToReconnect()&&(this.reconnectAttempted=!0),this.monitor.recordConnect(),this.subscriptions.reload();case v.disconnect:return s.log(`Disconnecting. Reason: ${i}`),this.close({allowReconnect:n});case v.ping:return this.monitor.recordPing();case v.confirmation:return this.subscriptions.confirmSubscription(t),this.reconnectAttempted?(this.reconnectAttempted=!1,this.subscriptions.notify(t,"connected",{reconnected:!0})):this.subscriptions.notify(t,"connected",{reconnected:!1});case v.rejection:return this.subscriptions.reject(t);default:return this.subscriptions.notify(t,"received",e)}},open(){if(s.log(`WebSocket onopen event, using '${this.getProtocol()}' subprotocol`),this.disconnected=!1,!this.isProtocolSupported())return s.log("Protocol is unsupported. Stopping monitor and disconnecting."),this.close({allowReconnect:!1})},close(o){if(s.log("WebSocket onclose event"),!this.disconnected)return this.disconnected=!0,this.monitor.recordDisconnect(),this.subscriptions.notifyAll("disconnected",{willAttemptReconnect:this.monitor.isRunning()})},error(){s.log("WebSocket onerror event");}};var rt=S;var Rt=function(o,t){if(t!==null)for(let e in t){let i=t[e];o[e]=i;}return o},q=class{constructor(t,e={},i){r(this,"consumer");r(this,"identifier");this.consumer=t,this.identifier=JSON.stringify(e),Rt(this,i);}perform(t,e={}){return e.action=t,this.send(e)}send(t){return this.consumer.send({command:"message",identifier:this.identifier,data:JSON.stringify(t)})}unsubscribe(){return this.consumer.subscriptions.remove(this)}},it=q;var P=class{constructor(t){r(this,"subscriptions");r(this,"pendingSubscriptions");r(this,"retryTimeout");this.subscriptions=t,this.pendingSubscriptions=[];}guarantee(t){this.pendingSubscriptions.indexOf(t)==-1?(s.log(`SubscriptionGuarantor guaranteeing ${t.identifier}`),this.pendingSubscriptions.push(t)):s.log(`SubscriptionGuarantor already guaranteeing ${t.identifier}`),this.startGuaranteeing();}forget(t){s.log(`SubscriptionGuarantor forgetting ${t.identifier}`),this.pendingSubscriptions=this.pendingSubscriptions.filter(e=>e!==t);}startGuaranteeing(){this.stopGuaranteeing(),this.retrySubscribing();}stopGuaranteeing(){clearTimeout(this.retryTimeout);}retrySubscribing(){this.retryTimeout=setTimeout(()=>{this.subscriptions&&typeof this.subscriptions.subscribe=="function"&&this.pendingSubscriptions.map(t=>{s.log(`SubscriptionGuarantor resubscribing ${t.identifier}`),this.subscriptions.subscribe(t);});},500);}},nt=P;var D=class{constructor(t){r(this,"consumer");r(this,"guarantor");r(this,"subscriptions");this.consumer=t,this.guarantor=new nt(this),this.subscriptions=[];}create(t,e){let i=t,n=typeof i=="object"?i:{channel:i},c=new it(this.consumer,n,e);return this.add(c)}add(t){return this.subscriptions.push(t),this.consumer.ensureActiveConnection(),this.notify(t,"initialized"),this.subscribe(t),t}remove(t){return this.forget(t),this.findAll(t.identifier).length||this.sendCommand(t,"unsubscribe"),t}reject(t){return this.findAll(t).map(e=>(this.forget(e),this.notify(e,"rejected"),e))}forget(t){return this.guarantor.forget(t),this.subscriptions=this.subscriptions.filter(e=>e!==t),t}findAll(t){return this.subscriptions.filter(e=>e.identifier===t)}reload(){return this.subscriptions.map(t=>this.subscribe(t))}notifyAll(t,...e){return this.subscriptions.map(i=>this.notify(i,t,...e))}notify(t,e,...i){let n;return typeof t=="string"?n=this.findAll(t):n=[t],n.map(c=>typeof c[e]=="function"?c[e](...i):void 0)}subscribe(t){this.sendCommand(t,"subscribe")&&this.guarantor.guarantee(t);}confirmSubscription(t){s.log(`Subscription confirmed ${t}`),this.findAll(t).map(e=>this.guarantor.forget(e));}sendCommand(t,e){let{identifier:i}=t;return this.consumer.send({command:e,identifier:i})}},st=D;var j=class{constructor(t){r(this,"_url");r(this,"subscriptions");r(this,"connection");r(this,"subprotocols");this._url=t,this.subscriptions=new st(this),this.connection=new rt(this),this.subprotocols=[];}get url(){return ct(this._url)}send(t){return this.connection.send(t)}connect(){return this.connection.open()}disconnect(){return this.connection.close({allowReconnect:!1})}ensureActiveConnection(){if(!this.connection.isActive())return this.connection.open()}addSubProtocol(t){this.subprotocols=[...this.subprotocols,t];}};function ct(o){if(typeof o=="function"&&(o=o()),o&&!/^wss?:/i.test(o)){let t=document.createElement("a");return t.href=o,t.href=t.href,t.protocol=t.protocol.replace("http","ws"),t.href}else return o}var at=j;function lt(o=It("url")||L.default_mount_path){return new at(o)}function It(o){let t=document.head.querySelector(`meta[name='action-cable-${o}']`);if(t)return t.getAttribute("content")}var _=class extends index_js$5.ApolloLink{constructor(e){super();r(this,"cables");r(this,"channelName");r(this,"actionName");r(this,"connectionParams");this.cables={},this.channelName=e.channelName||"GraphqlChannel",this.actionName=e.actionName||"execute",this.connectionParams=e.connectionParams||{};}request(e,i){let n=h.get("session");return n?(this.cables[n]||(this.cables[n]=lt(J+(n?`?token=${n}`:""))),new index_js$5.Observable(c=>{let d=Math.round(Date.now()+Math.random()*1e5).toString(16),m=this.actionName,p=typeof this.connectionParams=="function"?this.connectionParams(e):this.connectionParams,y=this.cables[n].subscriptions.create(Object.assign({},{channel:this.channelName,channelId:d},p),{connected:()=>{y.perform(m,{query:e.query?graphql.print(e.query):null,variables:e.variables,operationId:e.operationId,operationName:e.operationName});},received:a=>{var G,W;((G=a==null?void 0:a.result)!=null&&G.data||(W=a==null?void 0:a.result)!=null&&W.errors)&&c.next(a.result),a.more||c.complete();}});return Object.assign(y,{closed:!1})})):(console.warn("QuilttLink attempted to send an unauthenticated Subscription"),null)}},pt=_;var N=class extends pt{constructor(){super({channelName:"GraphQLChannel"});}};var po=new index_js.ApolloLink(()=>null);var ut=new index_js.ApolloLink((o,t)=>(o.setContext(({headers:e={}})=>({headers:x(u({},e),{"Quiltt-Client-Version":z})})),t(o)));var ht=class extends index_js.ApolloClient{constructor(t){t.connectToDevTools||(t.connectToDevTools=k);let e=m=>m.query.definitions.some(({kind:p,operation:y})=>p==="OperationDefinition"&&y==="subscription"),i=m=>{var p;return (p=m.getContext().batchable)!=null?p:!0},n=new A,c=new N,d=index_js.ApolloLink.from([ut,n,X,tt]).split(e,c,Y).split(i,K,Z);super(u({link:d},t));}};
17
17
 
18
18
  Object.defineProperty(exports, 'InMemoryCache', {
19
19
  enumerable: true,
@@ -42,7 +42,7 @@ exports.ForwardableLink = Y;
42
42
  exports.HttpLink = Z;
43
43
  exports.QuilttClient = ht;
44
44
  exports.RetryLink = tt;
45
- exports.SubscriptionLink = $;
45
+ exports.SubscriptionLink = N;
46
46
  exports.TerminatingLink = po;
47
47
  exports.VersionLink = ut;
48
48
  //# sourceMappingURL=out.js.map