@based/client 3.2.2 → 4.0.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 (205) hide show
  1. package/README.md +28 -330
  2. package/dist/Emitter.d.ts +7 -6
  3. package/dist/Emitter.js +31 -6
  4. package/dist/Emitter.js.map +1 -1
  5. package/dist/authState/parseAuthState.d.ts +3 -0
  6. package/dist/authState/parseAuthState.js +51 -0
  7. package/dist/authState/parseAuthState.js.map +1 -0
  8. package/dist/authState/updateAuthState.d.ts +3 -0
  9. package/dist/authState/updateAuthState.js +15 -0
  10. package/dist/authState/updateAuthState.js.map +1 -0
  11. package/dist/channel/cleanUp.d.ts +2 -0
  12. package/dist/channel/cleanUp.js +32 -0
  13. package/dist/channel/cleanUp.js.map +1 -0
  14. package/dist/channel/index.d.ts +12 -0
  15. package/dist/channel/index.js +67 -0
  16. package/dist/channel/index.js.map +1 -0
  17. package/dist/genObserveId.d.ts +1 -0
  18. package/dist/genObserveId.js +12 -0
  19. package/dist/genObserveId.js.map +1 -0
  20. package/dist/getTargetInfo.d.ts +6 -0
  21. package/dist/getTargetInfo.js +14 -0
  22. package/dist/getTargetInfo.js.map +1 -0
  23. package/dist/getUrlFromOpts.d.ts +3 -0
  24. package/dist/getUrlFromOpts.js +24 -0
  25. package/dist/getUrlFromOpts.js.map +1 -0
  26. package/dist/incoming/debug.d.ts +9 -0
  27. package/dist/incoming/debug.js +132 -0
  28. package/dist/incoming/debug.js.map +1 -0
  29. package/dist/incoming/index.d.ts +2 -0
  30. package/dist/incoming/index.js +341 -0
  31. package/dist/incoming/index.js.map +1 -0
  32. package/dist/incoming/protocol.d.ts +9 -0
  33. package/dist/incoming/protocol.js +62 -0
  34. package/dist/incoming/protocol.js.map +1 -0
  35. package/dist/index.d.ts +69 -127
  36. package/dist/index.js +224 -15
  37. package/dist/index.js.map +1 -1
  38. package/dist/outgoing/debug.d.ts +8 -0
  39. package/dist/outgoing/debug.js +70 -0
  40. package/dist/outgoing/debug.js.map +1 -0
  41. package/dist/outgoing/index.d.ts +14 -0
  42. package/dist/outgoing/index.js +227 -0
  43. package/dist/outgoing/index.js.map +1 -0
  44. package/dist/outgoing/protocol.d.ts +24 -0
  45. package/dist/outgoing/protocol.js +200 -0
  46. package/dist/outgoing/protocol.js.map +1 -0
  47. package/dist/persistentStorage/browser.d.ts +5 -0
  48. package/dist/persistentStorage/browser.js +150 -0
  49. package/dist/persistentStorage/browser.js.map +1 -0
  50. package/dist/persistentStorage/index.d.ts +6 -0
  51. package/dist/persistentStorage/index.js +56 -0
  52. package/dist/persistentStorage/index.js.map +1 -0
  53. package/dist/persistentStorage/node.d.ts +6 -0
  54. package/dist/persistentStorage/node.js +104 -0
  55. package/dist/persistentStorage/node.js.map +1 -0
  56. package/dist/query/index.d.ts +17 -0
  57. package/dist/query/index.js +112 -0
  58. package/dist/query/index.js.map +1 -0
  59. package/dist/stream/fetch.d.ts +4 -0
  60. package/dist/stream/fetch.js +42 -0
  61. package/dist/stream/fetch.js.map +1 -0
  62. package/dist/stream/index.d.ts +4 -0
  63. package/dist/stream/index.js +65 -0
  64. package/dist/stream/index.js.map +1 -0
  65. package/dist/stream/nodeStream.d.ts +7 -0
  66. package/dist/stream/nodeStream.js +117 -0
  67. package/dist/stream/nodeStream.js.map +1 -0
  68. package/dist/stream/types.d.ts +37 -0
  69. package/dist/stream/types.js +8 -0
  70. package/dist/stream/types.js.map +1 -0
  71. package/dist/stream/uploadFileBrowser.d.ts +4 -0
  72. package/dist/stream/uploadFileBrowser.js +113 -0
  73. package/dist/stream/uploadFileBrowser.js.map +1 -0
  74. package/dist/types/auth.d.ts +11 -0
  75. package/dist/{selvaTypes/get.js → types/auth.js} +1 -1
  76. package/dist/types/auth.js.map +1 -0
  77. package/dist/types/cache.d.ts +6 -0
  78. package/dist/{selvaTypes/set.js → types/cache.js} +1 -1
  79. package/dist/types/cache.js.map +1 -0
  80. package/dist/types/channel.d.ts +25 -0
  81. package/dist/types/channel.js +3 -0
  82. package/dist/types/channel.js.map +1 -0
  83. package/dist/types/error.d.ts +36 -0
  84. package/dist/types/error.js +40 -0
  85. package/dist/types/error.js.map +1 -0
  86. package/dist/types/events.d.ts +34 -0
  87. package/dist/{selvaTypes/schema.js → types/events.js} +1 -1
  88. package/dist/types/events.js.map +1 -0
  89. package/dist/types/functions.d.ts +8 -0
  90. package/dist/types/functions.js +3 -0
  91. package/dist/types/functions.js.map +1 -0
  92. package/dist/types/generic.d.ts +20 -0
  93. package/dist/types/generic.js +3 -0
  94. package/dist/types/generic.js.map +1 -0
  95. package/dist/types/index.d.ts +6 -0
  96. package/dist/{subscriptions → types}/index.js +6 -10
  97. package/dist/types/index.js.map +1 -0
  98. package/dist/types/observe.d.ts +46 -0
  99. package/dist/types/observe.js +3 -0
  100. package/dist/types/observe.js.map +1 -0
  101. package/dist/websocket/index.d.ts +1 -1
  102. package/dist/websocket/index.js +14 -5
  103. package/dist/websocket/index.js.map +1 -1
  104. package/package.json +17 -27
  105. package/dist/Client.d.ts +0 -80
  106. package/dist/Client.js +0 -271
  107. package/dist/Client.js.map +0 -1
  108. package/dist/auth.d.ts +0 -13
  109. package/dist/auth.js +0 -87
  110. package/dist/auth.js.map +0 -1
  111. package/dist/createError.d.ts +0 -3
  112. package/dist/createError.js +0 -67
  113. package/dist/createError.js.map +0 -1
  114. package/dist/debug.d.ts +0 -2
  115. package/dist/debug.js +0 -21
  116. package/dist/debug.js.map +0 -1
  117. package/dist/file/fetch.d.ts +0 -6
  118. package/dist/file/fetch.js +0 -27
  119. package/dist/file/fetch.js.map +0 -1
  120. package/dist/file/getUrl.d.ts +0 -4
  121. package/dist/file/getUrl.js +0 -42
  122. package/dist/file/getUrl.js.map +0 -1
  123. package/dist/file/index.d.ts +0 -6
  124. package/dist/file/index.js +0 -95
  125. package/dist/file/index.js.map +0 -1
  126. package/dist/file/stream/browser.d.ts +0 -7
  127. package/dist/file/stream/browser.js +0 -17
  128. package/dist/file/stream/browser.js.map +0 -1
  129. package/dist/file/stream/index.d.ts +0 -7
  130. package/dist/file/stream/index.js +0 -86
  131. package/dist/file/stream/index.js.map +0 -1
  132. package/dist/file/uploadFileBrowser.d.ts +0 -3
  133. package/dist/file/uploadFileBrowser.js +0 -72
  134. package/dist/file/uploadFileBrowser.js.map +0 -1
  135. package/dist/findPrefix.d.ts +0 -3
  136. package/dist/findPrefix.js +0 -20
  137. package/dist/findPrefix.js.map +0 -1
  138. package/dist/idleTimeout.d.ts +0 -3
  139. package/dist/idleTimeout.js +0 -17
  140. package/dist/idleTimeout.js.map +0 -1
  141. package/dist/observable/index.d.ts +0 -28
  142. package/dist/observable/index.js +0 -84
  143. package/dist/observable/index.js.map +0 -1
  144. package/dist/printBasedObject.d.ts +0 -4
  145. package/dist/printBasedObject.js +0 -76
  146. package/dist/printBasedObject.js.map +0 -1
  147. package/dist/queue.d.ts +0 -5
  148. package/dist/queue.js +0 -53
  149. package/dist/queue.js.map +0 -1
  150. package/dist/request.d.ts +0 -6
  151. package/dist/request.js +0 -67
  152. package/dist/request.js.map +0 -1
  153. package/dist/selvaTypes/get.d.ts +0 -97
  154. package/dist/selvaTypes/get.js.map +0 -1
  155. package/dist/selvaTypes/schema.d.ts +0 -89
  156. package/dist/selvaTypes/schema.js.map +0 -1
  157. package/dist/selvaTypes/set.d.ts +0 -73
  158. package/dist/selvaTypes/set.js.map +0 -1
  159. package/dist/subscriptions/addGetSubscriber.d.ts +0 -3
  160. package/dist/subscriptions/addGetSubscriber.js +0 -87
  161. package/dist/subscriptions/addGetSubscriber.js.map +0 -1
  162. package/dist/subscriptions/addSubscriber.d.ts +0 -2
  163. package/dist/subscriptions/addSubscriber.js +0 -136
  164. package/dist/subscriptions/addSubscriber.js.map +0 -1
  165. package/dist/subscriptions/generateId.d.ts +0 -1
  166. package/dist/subscriptions/generateId.js +0 -11
  167. package/dist/subscriptions/generateId.js.map +0 -1
  168. package/dist/subscriptions/incomingSubscription.d.ts +0 -3
  169. package/dist/subscriptions/incomingSubscription.js +0 -87
  170. package/dist/subscriptions/incomingSubscription.js.map +0 -1
  171. package/dist/subscriptions/incomingSubscriptionDiff.d.ts +0 -3
  172. package/dist/subscriptions/incomingSubscriptionDiff.js +0 -85
  173. package/dist/subscriptions/incomingSubscriptionDiff.js.map +0 -1
  174. package/dist/subscriptions/index.d.ts +0 -10
  175. package/dist/subscriptions/index.js.map +0 -1
  176. package/dist/subscriptions/logoutSubscriptions.d.ts +0 -3
  177. package/dist/subscriptions/logoutSubscriptions.js +0 -36
  178. package/dist/subscriptions/logoutSubscriptions.js.map +0 -1
  179. package/dist/subscriptions/removeSendSubscriptionDataFromQueue.d.ts +0 -2
  180. package/dist/subscriptions/removeSendSubscriptionDataFromQueue.js +0 -14
  181. package/dist/subscriptions/removeSendSubscriptionDataFromQueue.js.map +0 -1
  182. package/dist/subscriptions/removeSubscriber.d.ts +0 -2
  183. package/dist/subscriptions/removeSubscriber.js +0 -44
  184. package/dist/subscriptions/removeSubscriber.js.map +0 -1
  185. package/dist/subscriptions/removeUnsubscribesFromQueue.d.ts +0 -2
  186. package/dist/subscriptions/removeUnsubscribesFromQueue.js +0 -14
  187. package/dist/subscriptions/removeUnsubscribesFromQueue.js.map +0 -1
  188. package/dist/subscriptions/sendAllSubscriptions.d.ts +0 -2
  189. package/dist/subscriptions/sendAllSubscriptions.js +0 -114
  190. package/dist/subscriptions/sendAllSubscriptions.js.map +0 -1
  191. package/dist/token.d.ts +0 -4
  192. package/dist/token.js +0 -35
  193. package/dist/token.js.map +0 -1
  194. package/dist/track.d.ts +0 -8
  195. package/dist/track.js +0 -71
  196. package/dist/track.js.map +0 -1
  197. package/docs/auth-based-ui-howto.md +0 -74
  198. package/docs/auth-howto.md +0 -166
  199. package/docs/auth.md +0 -93
  200. package/docs/authorize.md +0 -56
  201. package/docs/files.md +0 -66
  202. package/docs/get-started.md +0 -60
  203. package/docs/get.md +0 -759
  204. package/docs/schema.md +0 -244
  205. package/docs/set.md +0 -652
package/README.md CHANGED
@@ -1,356 +1,54 @@
1
1
  # @based/client
2
2
 
3
- ### Index
4
-
5
- - [Modify data](#modify-data)
6
- - [Observe data](#observe-data)
7
- - [Upload files](#upload-files)
8
- - [Schema](#schema)
9
- - [Analytics](#analytics)
10
- - [Auth System](https://github.com/atelier-saulx/based/blob/main/packages/client/docs/auth.md)
11
-
12
- ---
13
-
14
- This package allows to interact with a Based environment, set and observe data, upload files, track and see analytics, and authenticate users.
15
-
16
- This page provides a quick first look at the main methods this package offers. Detailed information about each method is linked in the appropriate paragraph.
17
-
18
- ###### Example:
3
+ Based client
19
4
 
20
5
  ```js
21
6
  import based from '@based/client'
22
7
 
8
+ // Create client
23
9
  const client = based({
24
- org: 'my-org',
25
- project: 'someproject',
26
- env: 'production',
27
- })
28
-
29
- // create a schema
30
- await client.updateSchema({
31
- schema: {
32
- types: {
33
- thing: {
34
- fields: {
35
- name: { type: 'string' },
36
- quantity: { type: 'number' },
37
- reason: { type: 'string' },
38
- otherThings: { type: 'references' },
39
- favouriteThing: { type: 'reference' },
40
- },
41
- },
42
- },
43
- },
10
+ env: 'myEnv',
11
+ org: 'myOrg',
12
+ project: 'myProject'
44
13
  })
45
14
 
46
- // observe some data
47
- await client.observe(
48
- { $id: 'root', children: { $all: true, $list: true } },
49
- (data) => {
50
- console.log(data)
51
- }
52
- )
53
-
54
- // set data
55
- await client.set({
56
- type: 'thing',
57
- name: 'book',
58
- quantity: 3,
59
- })
60
- ```
61
-
62
- ## Modify data
63
-
64
- > Read more about `set` and its operators [here](docs/set.md)
65
-
66
- ### `set`
67
-
68
- The `based.set()` method allows to create new nodes or modify data on existing nodes. To change an existing one, one can do the following:
69
-
70
- ###### Example:
71
-
72
- <!-- prettier-ignore-start -->
73
- ```js
74
- /*
75
- Let's assume the following node in database:
76
- {
77
- id: 'maASxsd3',
78
- type: 'match',
79
- value: 10,
80
- title: {
81
- en: 'yes'
82
- }
83
- }
84
- */
85
-
86
- const result = await client.set({ // Value of result: maASxsd3
87
- $id: 'maASxsd3', // Resulting node in database:
88
- type: 'match', // { id: 'maASxsd3',
89
- title: { // type: 'match',
90
- en: 'hello', // value: 10, // existing value remains
91
- de: 'hallo', // title: {
92
- }, // en: 'hello', // .en is overwritten
93
- name: 'match', // de: 'hallo' // .de is added
94
- // },
95
- // name: 'match' // name is added
96
- })
97
- ```
98
- <!-- prettier-ignore-end -->
99
-
100
- Omitting the `$id` field would **create a new node instead**.
101
-
102
- > :exclamation: **All set operations must still respect the schema, otherwise the set won't take effect.**
103
-
104
- ### `delete`
105
-
106
- A node can be removed using `client.delete()`, by passing an object with a property named `$id` containing the node's ID.
107
-
108
- ###### Example:
109
-
110
- ```js
111
- await client.delete({
112
- $id: 'maASxsd3',
15
+ client.once('connect', (isConnected) => {
16
+ console.info('connect', isConnected)
113
17
  })
114
- ```
115
-
116
- ## Observe data
117
-
118
- > Read more about `observe` and the query language [here](docs/get.md)
119
-
120
- Based is built from the ground up with realtime updates in mind. This is why the best way to retrieve data for the database is to _observe_ it. This allows to pass an `onData` function that will get called any time the data that the query points to changes.
121
18
 
122
- > Warning: The `data` object that gets passed to the onData function should **NOT** be modified in place since, due to performance reasons, the object gets reused between calls.
123
-
124
- Using this same method, it is also possible to observe a data function.
125
-
126
- This method returns a `close` function that must be called in order to allow the subscription to close gracefully.
127
-
128
- ###### Example:
129
-
130
- ```js
131
- // This query observes all nodes of type `thing` and counts how many times any of them
132
- // changes, is removed, or is added, while also logging all the entries every time.
133
- let receivedCnt = 0
134
-
135
- const close = await client.observe(
136
- {
137
- things: {
138
- name: true,
139
- id: true,
140
- nested: true,
141
- $list: {
142
- $find: {
143
- $traverse: 'children',
144
- $filter: {
145
- $operator: '=',
146
- $value: 'thing',
147
- $field: 'type',
148
- },
149
- },
150
- },
151
- },
152
- },
153
- (data) => {
154
- console.log(data)
155
- receivedCnt++
156
- }
157
- )
158
-
159
- // when done ...
160
- close()
161
- ```
162
-
163
- **To observe a data function instead**, one can simply replace the query with the name of the function:
164
-
165
- ###### Example:
166
-
167
- ```js
168
- let receivedCnt = 0
169
-
170
- const close = await client.observe('observeAllThings', (data) => {
171
- console.log(data)
172
- receivedCnt++
19
+ // Authenticate and use localStorage or a file in node
20
+ const authState = await client.setAuthState({
21
+ token,
22
+ persistent: true
173
23
  })
174
24
 
175
- // when done ...
176
- close()
177
- ```
178
-
179
- #### `get`
180
-
181
- It's also possible to simply get the data once, instead of observing it, using the `based.get()` method, which accepts a query or data function name as argument.
182
-
183
- ###### Example:
184
-
185
- ```js
186
- // Gets every child of `root`
187
- const data = await client.get({
188
- $id: 'root',
189
- children: { $all: true, $list: true },
190
- })
191
- ```
192
-
193
- ## Upload files
194
-
195
- > Details [here](docs/files.md)
196
-
197
- Based provides a way to upload and serve user content without hassle using the `client.file()` API.
198
-
199
- This sets a new node of type `file` in the database, which contains all its relevant information
200
-
201
- ###### Example:
202
-
203
- ```js
204
- const fileId = await client.file({
205
- contents: 'This is a string I want to store as plain text!',
206
- mimeType: 'text/plain',
207
- name: 'my-file-name',
208
- })
209
- ```
210
-
211
- Also supports browser file objects
212
-
213
- ```jsx
214
- <input
215
- type="file"
216
- onChange={async (e) => {
217
- const id = await client.file(e.target.files[0])
218
- // const id = await client.file({ contents: e.target.files[0], name: 'custom name' });
219
- }}
220
- />
221
- ```
222
-
223
- Or streams in node
224
-
225
- ```js
226
- import fs from 'fs'
227
-
228
- const id = await client.file(fs.createReadStream(aFile))
229
- ```
230
-
231
- ###### Retrieve the file node:
232
-
233
- ```js
234
- const data = await client.get({
235
- $id: fileId,
236
- $all: true,
237
- })
238
- /*
239
- data = {
240
- id: "fi6a535226",
241
- name: "eb3f67a3bc65325bf739ebddd94403e5",
242
- mimeType: "text/plain",
243
- version: "eb3f67a3bc65325bf739ebddd94403e5",
244
- origin: "https://based-env-files-do-usproduction-enb-xz-apz--orn-t-v-...98446afcb87d",
245
- src: "https://based-2129034536588.imgix.net/fi6a535226/84e62df3-75...98446afcb87d",
246
- progress: 1,
247
- size: 31,
248
- type: "file",
249
- createdAt: 1650360875043,
250
- updatedAt: 1650360882865,
251
- }
252
- */
253
- ```
254
-
255
- ## Schema
256
-
257
- > Read more about schemas [here](docs/schema.md)
258
-
259
- The schema describes what types of nodes can exist on the database. Each `type` can have several named `fields`, each with its own data type (i.e. `string`, `number`, `object`, and so on). Based on the data type, Based will validate the value passed.
260
-
261
- One of the first things a Based user will have to do is set a schema for its database. This is done using the `client.updateSchema()` method.
262
-
263
- ###### Example:
264
-
265
- ```js
266
- await client.updateSchema({
25
+ // Call a function
26
+ await client.call('db:update-schema', {
27
+ languages: ['en'],
267
28
  types: {
268
29
  thing: {
269
30
  fields: {
270
31
  name: { type: 'string' },
271
- nested: {
272
- type: 'object',
273
- properties: {
274
- something: { type: 'string' },
275
- },
276
- },
277
32
  },
278
33
  },
279
34
  },
280
35
  })
281
- ```
282
-
283
- ## Analytics
284
-
285
- Based is capable of tracking a client in realtime using the included `client.track()` method (and `client.untrack()`).
286
- This method allows to track any user defined event, attaching a payload to it. The client stops being tracked when `client.untrack()` is called, or when the connection is closed.
287
-
288
- ###### Example:
289
-
290
- <!-- prettier-ignore-start -->
291
- ```js
292
- client.track('view', {
293
- edition: '2022',
294
- language: 'en',
295
- })
296
36
 
297
- // when the event is no longer happening (e.g. the user moves to a different view)...
298
- client.untrack('view', {
299
- edition: '2022', // The payload needs to be specified again, since it defines a unique event type
300
- language: 'en',
301
- })
302
- ```
303
- <!-- prettier-ignore-end -->
37
+ // Get data once
38
+ const data = await client
39
+ .query('db', { $id: 'fwe2233', title: true })
40
+ .get()
304
41
 
305
- To then retrieve the analytics data, Based provides the `client.analytics()` method, which takes as argument an object containg the event type and its payload.
306
- This method can also take a `onData` function as a second argument, which turns it into an observer.
42
+ // Get updates, persitent stores results in localStorage
43
+ const unsubscribe = client
44
+ .query('db', { $id: 'fwe2233', title: true }, { persistent: true})
45
+ .subscribe((data) => console.log(data))
307
46
 
308
- ###### Example:
47
+ // Channels are stateless streams
48
+ const unsubscribeChannel = client.channel('events', { type: 'page-view })
49
+ .subscribe(event => console.log(event))
309
50
 
310
- <!-- prettier-ignore-start -->
311
- ```js
312
- const data = await client.analytics({ type: 'view' })
313
- console.log(data) // prints an object { all, unique, active }
314
- // `all` represents the total count of how many times the event was fired overall
315
- // `unique` represents the total count of unique users that fired the event
316
- // `active` are the users that are active right now (real time visitors)
317
-
318
-
319
- // it's also possible to observe the analytics by passing an onData function to it
320
- const close = await client.analytics(
321
- { type: 'view' },
322
- (analyticsInfo) => console.log(analyticsInfo)
323
- )
51
+ client
52
+ .channel('events', { type: 'page-view })
53
+ .publish({ id: 'mypage' })
324
54
  ```
325
- <!-- prettier-ignore-end -->
326
-
327
- ### `$geo` and `$history`
328
-
329
- Based analytics can provide more specific data by using the `$geo` and `$history` operators, which give information about the location of the user and the historical values of the event tracked, respectively.
330
-
331
- ###### Example:
332
-
333
- <!-- prettier-ignore-start -->
334
- ```js
335
- const data = await client.analytics({ type: 'view', $geo: true, $history: 30 })
336
- console.log(data) // prints an object containing all the information as the normal
337
- // client.analytics call, but with a geo property containig ISO value counts,
338
- // and with the total counts turned into an array of max 30 tuples,
339
- // with the first item in the tuple being a timestamp and the second one being the value at the time
340
-
341
-
342
- // it's also possible to observe the analytics by passing an onData function to it
343
- const close = await client.analytics(
344
- { type: 'view' },
345
- (analyticsInfo) => console.log(analyticsInfo)
346
- )
347
- ```
348
- <!-- prettier-ignore-end -->
349
-
350
- ---
351
-
352
- ## License
353
-
354
- Licensed under the MIT License.
355
-
356
- See [LICENSE](./LICENSE) for more information.
package/dist/Emitter.d.ts CHANGED
@@ -1,13 +1,14 @@
1
- export declare type Listener = (val?: any) => void;
1
+ import { EventMap, Event, Listener } from './types';
2
2
  declare class Emitter {
3
3
  constructor();
4
4
  listeners: {
5
- [event: string]: Listener[];
5
+ [E in Event]?: Listener<EventMap[E]>[];
6
6
  };
7
- emit(type: string, val: any): void;
8
- on(type: string, fn: Listener): void;
7
+ emit<E extends Event>(type: E, val: EventMap[E]): void;
8
+ on<E extends Event>(type: E, fn: Listener<EventMap[E]>): void;
9
9
  removeAllListeners(): void;
10
- once(type: string, fn: Listener): void;
11
- removeListener(type: string, fn: Listener): void;
10
+ once<E extends Event>(type: E): Promise<EventMap[E]>;
11
+ once<E extends Event>(type: E, fn: Listener<EventMap[E]>): void;
12
+ off<E extends Event>(type: E, fn?: Listener<EventMap[E]>): void;
12
13
  }
13
14
  export default Emitter;
package/dist/Emitter.js CHANGED
@@ -10,7 +10,18 @@ class Emitter {
10
10
  }
11
11
  emit(type, val) {
12
12
  if (this.listeners[type]) {
13
- this.listeners[type].forEach((fn) => fn(val));
13
+ const lis = this.listeners[type];
14
+ for (let i = 0, len = lis.length; i < lis.length; i++) {
15
+ const fn = lis[i];
16
+ // @ts-ignore
17
+ fn(val);
18
+ if (len > lis.length) {
19
+ if (lis[i] !== fn) {
20
+ i--;
21
+ len = lis.length;
22
+ }
23
+ }
24
+ }
14
25
  }
15
26
  }
16
27
  on(type, fn) {
@@ -23,24 +34,38 @@ class Emitter {
23
34
  this.listeners = {};
24
35
  }
25
36
  once(type, fn) {
26
- this.on(type, (v) => {
37
+ if (!fn) {
38
+ return new Promise((resolve) => {
39
+ const listener = (v) => {
40
+ resolve(v);
41
+ this.off(type, listener);
42
+ };
43
+ this.on(type, listener);
44
+ });
45
+ }
46
+ const listener = (v) => {
27
47
  fn(v);
28
- this.removeListener(type, fn);
29
- });
48
+ this.off(type, listener);
49
+ };
50
+ this.on(type, listener);
30
51
  }
31
- removeListener(type, fn) {
52
+ off(type, fn) {
32
53
  const listeners = this.listeners[type];
33
54
  if (listeners) {
34
55
  if (!fn) {
35
56
  delete this.listeners[type];
36
57
  }
37
58
  else {
38
- for (let i = 0, len = listeners.length; i < len; i++) {
59
+ for (let i = 0; i < listeners.length; i++) {
39
60
  if (listeners[i] === fn) {
40
61
  listeners.splice(i, 1);
62
+ i--;
41
63
  break;
42
64
  }
43
65
  }
66
+ if (listeners.length === 0) {
67
+ delete this.listeners[type];
68
+ }
44
69
  }
45
70
  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AAM,EAAE,CAAC,EAAE,EAAE;oBACzC,IAAI,SAAS,CAAC,CAAC,CAAC,KAAK,EAAE,EAAE;wBACvB,SAAS,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,CAAA;wBACtB,CAAC,EAAE,CAAA;wBACH,MAAK;qBACN;iBACF;gBACD,IAAI,SAAS,CAAC,MAAM,KAAK,CAAC,EAAE;oBAC1B,OAAO,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAA;iBAC5B;aACF;SACF;IACH,CAAC;CACF;AAED,kBAAe,OAAO,CAAA"}
@@ -0,0 +1,3 @@
1
+ import { AuthState } from '../types';
2
+ export declare const decodeAuthState: (authState: string) => AuthState;
3
+ export declare const encodeAuthState: (authState: AuthState) => string;
@@ -0,0 +1,51 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.encodeAuthState = exports.decodeAuthState = void 0;
4
+ const utils_1 = require("@saulx/utils");
5
+ const decodeAuthState = (authState) => {
6
+ try {
7
+ const str = (0, utils_1.uft8ToString)((0, utils_1.decodeBase64)(decodeURI(authState)));
8
+ return JSON.parse(str);
9
+ }
10
+ catch (err) {
11
+ return { error: 'Invalid authState' };
12
+ }
13
+ };
14
+ exports.decodeAuthState = decodeAuthState;
15
+ /*
16
+ Websocket Protocol
17
+ token = 1*<any CHAR except CTLs or separators>
18
+ separators = "(" | ")" | "<" | ">" | "@"
19
+ | "," | ";" | ":" | "\" | <">
20
+ | "/" | "[" | "]" | "?" | "="
21
+ | "{" | "}" | SP | HT
22
+ exclude " | '
23
+ */
24
+ // | HT (what is this?)
25
+ // can also encode the json - no base64
26
+ const { encode } = (0, utils_1.createEncoder)([
27
+ '(',
28
+ ')',
29
+ '<',
30
+ '>',
31
+ '@',
32
+ ',',
33
+ ';',
34
+ ':',
35
+ '\\',
36
+ '"',
37
+ '/',
38
+ '[',
39
+ ']',
40
+ '?',
41
+ '=',
42
+ '{',
43
+ '}',
44
+ ' ',
45
+ ], ['0']);
46
+ const encodeAuthState = (authState) => {
47
+ const b64 = encode((0, utils_1.encodeBase64)((0, utils_1.stringToUtf8)(JSON.stringify(authState))));
48
+ return encodeURI(b64);
49
+ };
50
+ exports.encodeAuthState = encodeAuthState;
51
+ //# sourceMappingURL=parseAuthState.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"parseAuthState.js","sourceRoot":"","sources":["../../src/authState/parseAuthState.ts"],"names":[],"mappings":";;;AACA,wCAMqB;AAEd,MAAM,eAAe,GAAG,CAAC,SAAiB,EAAa,EAAE;IAC9D,IAAI;QACF,MAAM,GAAG,GAAG,IAAA,oBAAY,EAAC,IAAA,oBAAY,EAAC,SAAS,CAAC,SAAS,CAAC,CAAC,CAAC,CAAA;QAC5D,OAAO,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAA;KACvB;IAAC,OAAO,GAAG,EAAE;QACZ,OAAO,EAAE,KAAK,EAAE,mBAAmB,EAAE,CAAA;KACtC;AACH,CAAC,CAAA;AAPY,QAAA,eAAe,mBAO3B;AAED;;;;;;;;EAQE;AACF,uBAAuB;AAEvB,uCAAuC;AAEvC,MAAM,EAAE,MAAM,EAAE,GAAG,IAAA,qBAAa,EAC9B;IACE,GAAG;IACH,GAAG;IACH,GAAG;IACH,GAAG;IACH,GAAG;IACH,GAAG;IACH,GAAG;IACH,GAAG;IACH,IAAI;IACJ,GAAG;IACH,GAAG;IACH,GAAG;IACH,GAAG;IACH,GAAG;IACH,GAAG;IACH,GAAG;IACH,GAAG;IACH,GAAG;CACJ,EACD,CAAC,GAAG,CAAC,CACN,CAAA;AAEM,MAAM,eAAe,GAAG,CAAC,SAAoB,EAAU,EAAE;IAC9D,MAAM,GAAG,GAAG,MAAM,CAAC,IAAA,oBAAY,EAAC,IAAA,oBAAY,EAAC,IAAI,CAAC,SAAS,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAA;IACzE,OAAO,SAAS,CAAC,GAAG,CAAC,CAAA;AACvB,CAAC,CAAA;AAHY,QAAA,eAAe,mBAG3B"}
@@ -0,0 +1,3 @@
1
+ import { AuthState } from '../types';
2
+ import { BasedClient } from '..';
3
+ export declare const updateAuthState: (client: BasedClient, authState: AuthState) => void;
@@ -0,0 +1,15 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.updateAuthState = void 0;
4
+ const persistentStorage_1 = require("../persistentStorage");
5
+ const updateAuthState = (client, authState) => {
6
+ if (authState.persistent) {
7
+ (0, persistentStorage_1.setStorage)(client, '@based-authState', authState);
8
+ }
9
+ else {
10
+ (0, persistentStorage_1.removeStorage)(client, '@based-authState');
11
+ }
12
+ client.authState = authState;
13
+ };
14
+ exports.updateAuthState = updateAuthState;
15
+ //# sourceMappingURL=updateAuthState.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"updateAuthState.js","sourceRoot":"","sources":["../../src/authState/updateAuthState.ts"],"names":[],"mappings":";;;AAEA,4DAAgE;AAEzD,MAAM,eAAe,GAAG,CAAC,MAAmB,EAAE,SAAoB,EAAE,EAAE;IAC3E,IAAI,SAAS,CAAC,UAAU,EAAE;QACxB,IAAA,8BAAU,EAAC,MAAM,EAAE,kBAAkB,EAAE,SAAS,CAAC,CAAA;KAClD;SAAM;QACL,IAAA,iCAAa,EAAC,MAAM,EAAE,kBAAkB,CAAC,CAAA;KAC1C;IACD,MAAM,CAAC,SAAS,GAAG,SAAS,CAAA;AAC9B,CAAC,CAAA;AAPY,QAAA,eAAe,mBAO3B"}
@@ -0,0 +1,2 @@
1
+ import { BasedClient } from '..';
2
+ export declare const cleanUpChannels: (client: BasedClient) => void;
@@ -0,0 +1,32 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.cleanUpChannels = void 0;
4
+ const cleanUpChannels = (client) => {
5
+ if (!client.channelCleanTimeout) {
6
+ client.channelCleanTimeout = setTimeout(() => {
7
+ client.channelCleanTimeout = null;
8
+ if (client.connected) {
9
+ let keepRunning = false;
10
+ client.channelState.forEach((value, key) => {
11
+ if (value.removeTimer !== -1) {
12
+ value.removeTimer--;
13
+ if (value.removeTimer === 0) {
14
+ client.channelState.delete(key);
15
+ }
16
+ else {
17
+ keepRunning = true;
18
+ }
19
+ }
20
+ });
21
+ if (keepRunning) {
22
+ (0, exports.cleanUpChannels)(client);
23
+ }
24
+ }
25
+ else {
26
+ (0, exports.cleanUpChannels)(client);
27
+ }
28
+ }, client.channelCleanupCycle);
29
+ }
30
+ };
31
+ exports.cleanUpChannels = cleanUpChannels;
32
+ //# sourceMappingURL=cleanUp.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cleanUp.js","sourceRoot":"","sources":["../../src/channel/cleanUp.ts"],"names":[],"mappings":";;;AAEO,MAAM,eAAe,GAAG,CAAC,MAAmB,EAAE,EAAE;IACrD,IAAI,CAAC,MAAM,CAAC,mBAAmB,EAAE;QAC/B,MAAM,CAAC,mBAAmB,GAAG,UAAU,CAAC,GAAG,EAAE;YAC3C,MAAM,CAAC,mBAAmB,GAAG,IAAI,CAAA;YACjC,IAAI,MAAM,CAAC,SAAS,EAAE;gBACpB,IAAI,WAAW,GAAG,KAAK,CAAA;gBACvB,MAAM,CAAC,YAAY,CAAC,OAAO,CAAC,CAAC,KAAK,EAAE,GAAG,EAAE,EAAE;oBACzC,IAAI,KAAK,CAAC,WAAW,KAAK,CAAC,CAAC,EAAE;wBAC5B,KAAK,CAAC,WAAW,EAAE,CAAA;wBACnB,IAAI,KAAK,CAAC,WAAW,KAAK,CAAC,EAAE;4BAC3B,MAAM,CAAC,YAAY,CAAC,MAAM,CAAC,GAAG,CAAC,CAAA;yBAChC;6BAAM;4BACL,WAAW,GAAG,IAAI,CAAA;yBACnB;qBACF;gBACH,CAAC,CAAC,CAAA;gBACF,IAAI,WAAW,EAAE;oBACf,IAAA,uBAAe,EAAC,MAAM,CAAC,CAAA;iBACxB;aACF;iBAAM;gBACL,IAAA,uBAAe,EAAC,MAAM,CAAC,CAAA;aACxB;QACH,CAAC,EAAE,MAAM,CAAC,mBAAmB,CAAC,CAAA;KAC/B;AACH,CAAC,CAAA;AAxBY,QAAA,eAAe,mBAwB3B"}
@@ -0,0 +1,12 @@
1
+ import { BasedClient } from '../';
2
+ import { ChannelMessageFunction } from '../types/channel';
3
+ import { BasedError } from '../types/error';
4
+ export declare class BasedChannel<P = any, K = any> {
5
+ id: number;
6
+ payload: P;
7
+ name: string;
8
+ client: BasedClient;
9
+ constructor(client: BasedClient, name: string, payload: P);
10
+ subscribe(onMessage: ChannelMessageFunction, onError?: (err: BasedError) => void): () => void;
11
+ publish(message: K): void;
12
+ }