insite-subscriptions-server 1.0.216

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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Eugene Nesvetaev
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,13 @@
1
+ # inSite subscriptions server side
2
+
3
+ ## Installation
4
+
5
+ ```sh
6
+ $ npm install insite-subscriptions-server
7
+ ```
8
+
9
+ Or
10
+
11
+ ```sh
12
+ $ yarn add insite-subscriptions-server
13
+ ```
@@ -0,0 +1,163 @@
1
+ import sift from "sift";
2
+ import { Publication } from "./Publication";
3
+
4
+
5
+ function projectDocument(document, projection, isInclusive = true, isTop = true) {
6
+ if (projection)
7
+ if (isInclusive) {
8
+ const projected = {};
9
+ for (const key in projection) {
10
+ const subprojection = projection[key];
11
+ projected[key] =
12
+ typeof subprojection == "object" ?
13
+ Array.isArray(document[key]) ?
14
+ document[key].map(item => projectDocument(item, subprojection, true, false)) :
15
+ projectDocument(document[key], subprojection, true, false) :
16
+ document[key];
17
+ }
18
+ if (isTop && projection._id === 0)
19
+ delete projected._id;
20
+
21
+ return projected;
22
+ } else {
23
+ const projected = { ...document };
24
+ for (const key in projection) {
25
+ const subprojection = projection[key];
26
+ if (typeof subprojection == "object")
27
+ projected[key] =
28
+ Array.isArray(document[key]) ?
29
+ document[key].map(item => projectDocument(item, subprojection, false, false)) :
30
+ projectDocument(document[key], subprojection, false, false);
31
+ else
32
+ delete projected[key];
33
+ }
34
+
35
+ return projected;
36
+ }
37
+
38
+ return document;
39
+ }
40
+
41
+
42
+ export class CollectionMapPublication extends Publication {
43
+ constructor(name, collection, queryProps, transform) {
44
+ super(name, { collection, queryProps, transform });
45
+
46
+ }
47
+
48
+ type = "map";
49
+
50
+ skipSymbol = Symbol("skip");
51
+
52
+ skip(next) {
53
+ next[this.skipSymbol] = true;
54
+
55
+ }
56
+
57
+ makeQueryProps(args) {
58
+ const { query = null, projection = null, sort = null, triggers } = (typeof this.queryProps == "function" ? this.queryProps(...args) : this.queryProps) || {};
59
+
60
+ let isProjectionInclusive = null;
61
+ let fields = null;
62
+ if (projection) {
63
+ for (const key in projection) {
64
+ isProjectionInclusive = !!projection[key];
65
+ if (key !== "_id")
66
+ break;
67
+ }
68
+ if (isProjectionInclusive) {
69
+ fields = new Set([ ...Object.keys(query), ...Object.keys(projection), ...triggers ?? [] ]);
70
+ fields.delete("_id");
71
+ if (projection._id !== 0)
72
+ projection._id = 1;
73
+ }
74
+ }
75
+
76
+ return { query, projection, isProjectionInclusive, fields, sort, args };
77
+ }
78
+
79
+ async fetchSubscription(subscription, next) {
80
+ if (subscription.query) {
81
+ if (next) {
82
+ const { _id } = next.documentKey;
83
+
84
+ if (next.operationType === "insert" || (next.operationType != "delete" && subscription.match(next.fullDocument))) {
85
+ const doc = projectDocument(next.fullDocument, subscription.projection, subscription.isProjectionInclusive);
86
+ this.transform?.(doc, subscription.args);
87
+ if (subscription.ids.has(_id))
88
+ return [ "u"/* update */, doc, next.updateDescription && Object.keys(next.updateDescription.updatedFields) ];
89
+
90
+ subscription.ids.add(_id);
91
+
92
+ return [ "c"/* create */, doc ];
93
+
94
+ }
95
+ subscription.ids.delete(_id);
96
+
97
+ return [ "d"/* delete */, _id ];
98
+
99
+ }
100
+ const cursor = this.collection.find(subscription.query);
101
+
102
+ if (subscription.projection)
103
+ cursor.project(subscription.projection);
104
+
105
+ if (subscription.sort)
106
+ cursor.sort(subscription.sort);
107
+
108
+ const array = await cursor.toArray();
109
+
110
+ if (subscription.ids) {
111
+ subscription.ids.clear();
112
+ if (this.transform)
113
+ for (const item of array) {
114
+ subscription.ids.add(item._id);
115
+ this.transform(item, subscription.args);
116
+ }
117
+ else
118
+ for (const item of array)
119
+ subscription.ids.add(item._id);
120
+ } else if (this.transform)
121
+ for (const item of array)
122
+ this.transform(item, subscription.args);
123
+
124
+ return [ "i"/* initial */, array, subscription.sort ];
125
+
126
+ }
127
+
128
+ return null;
129
+ }
130
+
131
+ async fetch(...args) {
132
+ return [ await this.fetchSubscription(this.makeQueryProps(args), null) ];
133
+ }
134
+
135
+ changed(changed) {
136
+ return Promise.all(this.subscriptions.map(subscription => subscription.changed(changed)));
137
+ }
138
+
139
+ onSubscribe(subscription) {
140
+ Object.assign(subscription, this.makeQueryProps(subscription.args));
141
+
142
+ if (subscription.query) {
143
+ subscription.match = sift(subscription.query);
144
+ this.collection.changeListeners.add(subscription.collectionChangeListener);
145
+ }
146
+
147
+ }
148
+
149
+ flushInitial() {
150
+ return Promise.all(this.subscriptions.map(async subscription => {
151
+ subscription.handler([ await this.fetchSubscription(subscription) ]);
152
+ subscription.updates = [];
153
+
154
+ }));
155
+ }
156
+
157
+ onUnsubscribe(subscription) {
158
+ if (subscription.query)
159
+ this.collection.changeListeners.delete(subscription.collectionChangeListener);
160
+
161
+ }
162
+
163
+ }
@@ -0,0 +1,60 @@
1
+ import { SubscriptionHandle } from "./SubscriptionHandle";
2
+
3
+
4
+ export class CollectionMapSubscriptionHandle extends SubscriptionHandle {
5
+ constructor(publicationName, args, handler, immediately) {
6
+ super(publicationName, args, handler, immediately, true);
7
+
8
+ if (this.publication) {
9
+ this.publication.subscribe(this);
10
+
11
+ this.skipSymbol = this.publication.skipSymbol;
12
+
13
+ if (immediately)
14
+ this.changed(null);
15
+ }
16
+
17
+ }
18
+
19
+ ids = new Set();
20
+
21
+ async changed(next) {
22
+ this.handler([ await this.publication.fetchSubscription(this, next) ]);
23
+
24
+ }
25
+
26
+ updates = [];
27
+ flushTimeout = null;
28
+
29
+ handleUpdatedFieldsSome = field => this.fields.has(field);
30
+
31
+ flushUpdates = () => {
32
+
33
+ if (this.updates.length) {
34
+ this.handler(this.updates);
35
+ this.updates = [];
36
+ }
37
+
38
+ };
39
+
40
+ collectionChangeListener = async next => {
41
+
42
+ if (
43
+ !next[this.skipSymbol] &&
44
+ (this.ids.has(next.documentKey._id) ? (
45
+ next.operationType !== "update" ||
46
+ !this.fields ||
47
+ Object.keys(next.updateDescription.updatedFields).some(this.handleUpdatedFieldsSome)
48
+ ) : this.match(next.fullDocument))
49
+ ) {
50
+ clearTimeout(this.flushTimeout);
51
+
52
+ this.updates.push(await this.publication.fetchSubscription(this, next));
53
+
54
+ this.flushTimeout = setTimeout(this.flushUpdates, 1);
55
+ }
56
+
57
+ };
58
+
59
+
60
+ }
@@ -0,0 +1,42 @@
1
+ export const publications = new Map();
2
+
3
+
4
+ export class Publication {
5
+ constructor(name, props) {
6
+ this.name = name;
7
+ Object.assign(this, props);
8
+
9
+ publications.set(name, this);
10
+
11
+ }
12
+
13
+ type = "object";
14
+
15
+ subscriptions = new Set();
16
+
17
+ // eslint-disable-next-line @typescript-eslint/no-empty-function
18
+ fetch() {}
19
+
20
+ fetchSubscription(subscription) {
21
+ return this.fetch(...subscription.args);
22
+ }
23
+
24
+ subscribe(subscription) {
25
+ this.subscriptions.add(subscription);
26
+ this.onSubscribe?.(subscription);
27
+
28
+ }
29
+
30
+ changed(changed) {
31
+ for (const subscription of this.subscriptions)
32
+ subscription.changed(changed);
33
+
34
+ }
35
+
36
+ unsubscribe(subscription) {
37
+ this.onUnsubscribe?.(subscription);
38
+ this.subscriptions.delete(subscription);
39
+
40
+ }
41
+
42
+ }
@@ -0,0 +1,44 @@
1
+ import { publications } from "./Publication";
2
+
3
+
4
+ export class SubscriptionHandle {
5
+ constructor(publicationName, args, handler, immediately, prevent) {
6
+ this.publication = publications.get(publicationName);
7
+
8
+ if (this.publication) {
9
+ this.args = args;
10
+ this.handler = handler;
11
+
12
+ if (!prevent) {
13
+ this.publication.subscribe(this);
14
+
15
+ if (immediately)
16
+ this.changed(null);
17
+ }
18
+
19
+ } else if (process.env.NODE_ENV === "development")
20
+ console.error("Unknown publication", publicationName);
21
+
22
+ }
23
+
24
+ async changed(changed) {
25
+ this.handler(await this.publication.fetchSubscription(this, changed), changed);
26
+
27
+ }
28
+
29
+ cancel() {
30
+
31
+ this.publication?.unsubscribe(this);
32
+
33
+ }
34
+
35
+ renew() {
36
+
37
+ this.publication?.unsubscribe(this);
38
+
39
+ this.publication?.subscribe(this);
40
+
41
+ return this.changed(null);
42
+ }
43
+
44
+ }
package/lib/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export * from "./CollectionMapPublication";
2
+ export * from "./Publication";
3
+ export * from "./SubscriptionHandle";
@@ -0,0 +1,70 @@
1
+ import { CollectionMapSubscriptionHandle } from "../CollectionMapSubscriptionHandle";
2
+ import { publications } from "../Publication";
3
+ import { SubscriptionHandle } from "../SubscriptionHandle";
4
+ import { Subscriptions } from "./Subscriptions";
5
+
6
+
7
+ const handlesByType = {
8
+ object: SubscriptionHandle,
9
+ map: CollectionMapSubscriptionHandle
10
+ };
11
+
12
+
13
+ export class SubscriptionHandler {
14
+ constructor(wss, options = {}) {
15
+
16
+ const {
17
+ users
18
+ } = options;
19
+
20
+ if (users)
21
+ users.on("user-permissions-change", SubscriptionHandler.handleUserPermissionsChange);
22
+
23
+ wss.on("client-connect", SubscriptionHandler.handleClientConnect);
24
+ wss.on("client-session", SubscriptionHandler.handleClientSession);
25
+ wss.on("client-message:s-s"/* subscription subscribe */, SubscriptionHandler.handleClientSubscribe);
26
+ wss.on("client-message:s-u"/* subscription unsubscribe */, SubscriptionHandler.handleClientUnsubscribe);
27
+ wss.on("client-close", SubscriptionHandler.handleClientClose);
28
+
29
+ }
30
+
31
+
32
+ static handleUserPermissionsChange(user) {
33
+ if (user.webSockets)
34
+ for (const ws of user.webSockets)
35
+ ws.subscriptions.renew();
36
+
37
+ }
38
+
39
+ static handleClientConnect(ws) {
40
+ ws.subscriptions = new Subscriptions();
41
+
42
+ }
43
+
44
+ static handleClientSession(ws) {
45
+ ws.subscriptions.renew();
46
+
47
+ }
48
+
49
+ static handleClientSubscribe(ws, subscriptionType, publicationName, i, args, immediately) {
50
+ const Handle = handlesByType[subscriptionType];
51
+
52
+ if (Handle && publications.get(publicationName)?.type === subscriptionType) {
53
+ const handler = data => ws.sendMessage("s-c"/* subscription changed */, i, data);
54
+ ws.subscriptions.subscribe(i, new Handle(publicationName, [ ws, ...args ], handler, immediately));
55
+ }
56
+
57
+ }
58
+
59
+ static handleClientUnsubscribe(ws, i) {
60
+ ws.subscriptions.cancel(i);
61
+
62
+ }
63
+
64
+ static handleClientClose(ws) {
65
+ for (const subscription of ws.subscriptions.values())
66
+ subscription.cancel();
67
+
68
+ }
69
+
70
+ }
@@ -0,0 +1,15 @@
1
+ export class Subscriptions extends Map {
2
+
3
+ subscribe = this.set;
4
+
5
+ renew() {
6
+ return Promise.all(this.mapValues(subscription => subscription.renew()));
7
+ }
8
+
9
+ cancel(key) {
10
+ this.get(key)?.cancel();
11
+ this.delete(key);
12
+
13
+ }
14
+
15
+ }
@@ -0,0 +1 @@
1
+ export * from "./SubscriptionHandler";
package/package.json ADDED
@@ -0,0 +1,34 @@
1
+ {
2
+ "name": "insite-subscriptions-server",
3
+ "version": "1.0.216",
4
+ "description": "inSite subscriptions server side",
5
+ "type": "module",
6
+ "main": "./lib/index.js",
7
+ "module": "./lib/index.js",
8
+ "exports": {
9
+ ".": "./lib/index.js",
10
+ "./ws": "./lib/ws/index.js"
11
+ },
12
+ "packageManager": "yarn@1.22.22",
13
+ "scripts": {
14
+ "test": "echo \"Error: no test specified\" && exit 1"
15
+ },
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/nesvet/insite-subscriptions-server.git"
19
+ },
20
+ "keywords": [
21
+ "insite",
22
+ "subscriptions",
23
+ "server"
24
+ ],
25
+ "author": "Eugene Nesvetaev <dev@nesvet.dev> (https://nesvet.dev/)",
26
+ "license": "MIT",
27
+ "dependencies": {
28
+ "insite-ws": "^1",
29
+ "sift": "^16"
30
+ },
31
+ "devDependencies": {
32
+ "@nesvet/eslint-config": "^1"
33
+ }
34
+ }