@docmentis/udoc-server 0.0.1 → 0.8.0

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 (53) hide show
  1. package/LICENSE-APACHE +202 -0
  2. package/LICENSE-MIT +21 -0
  3. package/README.md +42 -0
  4. package/config.example.toml +26 -0
  5. package/dist/collaboration.d.ts +25 -0
  6. package/dist/collaboration.d.ts.map +1 -0
  7. package/dist/collaboration.js +348 -0
  8. package/dist/collaboration.js.map +1 -0
  9. package/dist/config.d.ts +30 -0
  10. package/dist/config.d.ts.map +1 -0
  11. package/dist/config.js +87 -0
  12. package/dist/config.js.map +1 -0
  13. package/dist/document.d.ts +29 -0
  14. package/dist/document.d.ts.map +1 -0
  15. package/dist/document.js +308 -0
  16. package/dist/document.js.map +1 -0
  17. package/dist/http.d.ts +44 -0
  18. package/dist/http.d.ts.map +1 -0
  19. package/dist/http.js +96 -0
  20. package/dist/http.js.map +1 -0
  21. package/dist/index.d.ts +5 -0
  22. package/dist/index.d.ts.map +1 -0
  23. package/dist/index.js +3 -0
  24. package/dist/index.js.map +1 -0
  25. package/dist/main.d.ts +3 -0
  26. package/dist/main.d.ts.map +1 -0
  27. package/dist/main.js +105 -0
  28. package/dist/main.js.map +1 -0
  29. package/dist/package.d.ts +5 -0
  30. package/dist/package.d.ts.map +1 -0
  31. package/dist/package.js +116 -0
  32. package/dist/package.js.map +1 -0
  33. package/dist/route.d.ts +56 -0
  34. package/dist/route.d.ts.map +1 -0
  35. package/dist/route.js +126 -0
  36. package/dist/route.js.map +1 -0
  37. package/dist/server.d.ts +45 -0
  38. package/dist/server.d.ts.map +1 -0
  39. package/dist/server.js +103 -0
  40. package/dist/server.js.map +1 -0
  41. package/dist/session-pool.d.ts +19 -0
  42. package/dist/session-pool.d.ts.map +1 -0
  43. package/dist/session-pool.js +95 -0
  44. package/dist/session-pool.js.map +1 -0
  45. package/dist/store.d.ts +115 -0
  46. package/dist/store.d.ts.map +1 -0
  47. package/dist/store.js +441 -0
  48. package/dist/store.js.map +1 -0
  49. package/dist/version.d.ts +2 -0
  50. package/dist/version.d.ts.map +1 -0
  51. package/dist/version.js +10 -0
  52. package/dist/version.js.map +1 -0
  53. package/package.json +75 -5
package/LICENSE-APACHE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/LICENSE-MIT ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 docMentis LLC
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,42 @@
1
+ # @docmentis/udoc-server
2
+
3
+ **Self-hosted document services and collaboration for your application.**
4
+
5
+ Host documents on your own infrastructure, access document content and rendered pages over HTTP, and support collaborative editing in applications built with docMentis.
6
+
7
+ [![npm version](https://img.shields.io/npm/v/@docmentis/udoc-server)](https://www.npmjs.com/package/@docmentis/udoc-server)
8
+ [![license](https://img.shields.io/npm/l/@docmentis/udoc-server)](https://github.com/docMentis/docmentis-udoc#open-source-packages-shared-runtime)
9
+
10
+ **[Docs](https://www.docmentis.com/docs)** · **[API Reference](https://www.docmentis.com/docs/api/udoc-server)** · **[Changelog](https://github.com/docMentis/docmentis-udoc/blob/main/CHANGELOG.md)** · **[Report Issue](https://github.com/docMentis/docmentis-udoc/issues)**
11
+
12
+ ---
13
+
14
+ ## What it provides
15
+
16
+ - **Document hosting.** Store and retrieve documents through a document service you operate.
17
+ - **Document APIs.** Access pages, previews, and saved documents from your application.
18
+ - **Remote document access.** Connect browser-based editors and Node.js integrations to documents held by the service.
19
+ - **Collaborative editing.** Synchronize changes between participants working on a shared document.
20
+
21
+ ## Quick start
22
+
23
+ ```sh
24
+ npm install -g @docmentis/udoc-server
25
+ udoc-server --port 8080 --data-dir ./udoc-data
26
+ ```
27
+
28
+ ```sh
29
+ curl --data-binary @report.pdf http://127.0.0.1:8080/documents
30
+ ```
31
+
32
+ The service listens on loopback by default and does not provide end-user authentication. **Add authentication, authorization, and appropriate deployment controls before exposing it to users or the public internet.** See the package documentation for configuration, embedding it into an existing Node.js server, and collaboration endpoints.
33
+
34
+ ## Part of the udoc ecosystem
35
+
36
+ The server works with [`@docmentis/udoc-editor`](https://www.npmjs.com/package/@docmentis/udoc-editor) for remote collaborative editing and builds on [`@docmentis/udoc-node`](https://www.npmjs.com/package/@docmentis/udoc-node).
37
+
38
+ ## Licensing
39
+
40
+ The server's source code is open source under **MIT OR Apache-2.0**. It uses the proprietary, separately licensed [`@docmentis/udoc-wasm`](https://www.npmjs.com/package/@docmentis/udoc-wasm) engine. Free runtime use requires online authorization; commercial licensing is available for offline use.
41
+
42
+ [Source and documentation](https://github.com/docMentis/docmentis-udoc)
@@ -0,0 +1,26 @@
1
+ # udoc-server settings — pass with `udoc-server --config <this file>`.
2
+ #
3
+ # Every key is a flag of the same name, in the same units, and a flag on the
4
+ # command line overrides it. Each is shown at its default. An unknown key is an
5
+ # error, so a typo never falls back to a default quietly.
6
+ #
7
+ # The license is not a setting: udoc-server reads it from the environment
8
+ # (UDOC_LICENSE, for the domain in UDOC_DOMAIN), so this file can be committed.
9
+
10
+ # The address to bind. Loopback by default: udoc-server does no authentication,
11
+ # so put it behind whatever authenticates your users before exposing it.
12
+ host = "127.0.0.1"
13
+
14
+ # The port to listen on.
15
+ port = 8080
16
+
17
+ # Where documents are kept: a directory per document, holding its original and
18
+ # its udoc package. A relative path is relative to this file.
19
+ data-dir = "udoc-data"
20
+
21
+ # How long, in seconds, a document's session stays open with no request for it.
22
+ session-timeout = 300
23
+
24
+ # How many sessions stay open once their requests finish. Past it, the least
25
+ # recently used idle sessions close; a closed one reopens on its next request.
26
+ session-pool = 32
@@ -0,0 +1,25 @@
1
+ import type { Upgrade } from "./http.ts";
2
+ import type { SessionPool } from "./session-pool.ts";
3
+ import type { DocumentStore } from "./store.ts";
4
+ /** The collaboration on each document being edited now, and the clients arriving at them. */
5
+ export declare class Collaborations {
6
+ #private;
7
+ /** Over the documents `store` keeps and the sessions `sessions` holds open; no message larger than `maxPayload` bytes. */
8
+ constructor(store: DocumentStore, sessions: SessionPool, maxPayload: number);
9
+ /**
10
+ * Take `upgrade` into document `id`'s collaboration, once its session is
11
+ * open. What refuses it — the server closing, a session that can't be
12
+ * opened — takes the upgrade and closes it with the code saying why.
13
+ */
14
+ join(id: string, upgrade: Upgrade): Promise<void>;
15
+ /**
16
+ * Take `upgrade` and close it with the code `error` calls for: no such
17
+ * document, a license refusal, or a document that can't be opened.
18
+ */
19
+ refuse(upgrade: Upgrade, error: unknown): void;
20
+ /** End document `id`'s collaboration, if one is under way: the document is no longer kept. */
21
+ end(id: string): void;
22
+ /** Refuse every client arriving from now on, and end every collaboration once its log is kept. */
23
+ close(): Promise<void>;
24
+ }
25
+ //# sourceMappingURL=collaboration.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"collaboration.d.ts","sourceRoot":"","sources":["../src/collaboration.ts"],"names":[],"mappings":"AAWA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACzC,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AACrD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AA0BhD,6FAA6F;AAC7F,qBAAa,cAAc;;IAOvB,0HAA0H;gBAC9G,KAAK,EAAE,aAAa,EAAE,QAAQ,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM;IAM3E;;;;OAIG;IACG,IAAI,CAAC,EAAE,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC;IAmBvD;;;OAGG;IACH,MAAM,CAAC,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO,GAAG,IAAI;IAI9C,8FAA8F;IAC9F,GAAG,CAAC,EAAE,EAAE,MAAM,GAAG,IAAI;IAIrB,kGAAkG;IAC5F,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;CAwB/B"}
@@ -0,0 +1,348 @@
1
+ // Clients editing a kept document together (docs/design/node-collaboration.md):
2
+ // a collaboration is the document's pooled session, held open while any client
3
+ // is connected; each client's edits are merged into it, sent on to every other
4
+ // client, and kept in the store as the document's edit log. The engine does
5
+ // the merging, and the server only carries its bytes, over a WebSocket.
6
+ import { WebSocketServer } from "ws";
7
+ import { LICENSE_CODES, failureOf, messageOf } from "./http.js";
8
+ /**
9
+ * A collaboration message is a binary frame: one byte saying what it is, then
10
+ * its payload — the engine's own bytes, crossed as they are.
11
+ */
12
+ const JOIN = 1;
13
+ const PATCH = 2;
14
+ const PRESENCE = 3;
15
+ /** The content of opaque parts a client's next patch names — kept before that patch is merged. */
16
+ const OPAQUE_PARTS = 4;
17
+ /**
18
+ * Why the server ends a client's connection: the WebSocket close codes it
19
+ * sends — WebSocket's own where it defines the meaning, and this server's from
20
+ * 4000.
21
+ */
22
+ const CLOSE_SERVER_CLOSING = 1001;
23
+ const CLOSE_PROTOCOL_ERROR = 1002;
24
+ const CLOSE_NOT_BINARY = 1003;
25
+ const CLOSE_DID_NOT_MERGE = 1008;
26
+ const CLOSE_SESSION_ENDED = 1011;
27
+ const CLOSE_NO_DOCUMENT = 4000;
28
+ const CLOSE_LICENSE_REFUSED = 4001;
29
+ const CLOSE_CANNOT_OPEN = 4002;
30
+ /** The collaboration on each document being edited now, and the clients arriving at them. */
31
+ export class Collaborations {
32
+ #store;
33
+ #sessions;
34
+ #collaborations = new Map();
35
+ #sockets;
36
+ #closing = false;
37
+ /** Over the documents `store` keeps and the sessions `sessions` holds open; no message larger than `maxPayload` bytes. */
38
+ constructor(store, sessions, maxPayload) {
39
+ this.#store = store;
40
+ this.#sessions = sessions;
41
+ this.#sockets = new WebSocketServer({ noServer: true, maxPayload });
42
+ }
43
+ /**
44
+ * Take `upgrade` into document `id`'s collaboration, once its session is
45
+ * open. What refuses it — the server closing, a session that can't be
46
+ * opened — takes the upgrade and closes it with the code saying why.
47
+ */
48
+ async join(id, upgrade) {
49
+ if (this.#closing) {
50
+ this.#refuse(upgrade, CLOSE_SERVER_CLOSING, "the server is closing");
51
+ return;
52
+ }
53
+ const collaboration = this.#collaborationOf(id);
54
+ const arrival = collaboration.arrive();
55
+ // A client that goes before it is admitted leaves nothing held.
56
+ upgrade.socket.once("close", () => arrival.leave());
57
+ try {
58
+ await collaboration.session;
59
+ }
60
+ catch (error) {
61
+ arrival.leave();
62
+ this.refuse(upgrade, error);
63
+ return;
64
+ }
65
+ this.#sockets.handleUpgrade(upgrade.request, upgrade.socket, upgrade.head, (client) => arrival.admit(client));
66
+ }
67
+ /**
68
+ * Take `upgrade` and close it with the code `error` calls for: no such
69
+ * document, a license refusal, or a document that can't be opened.
70
+ */
71
+ refuse(upgrade, error) {
72
+ this.#refuse(upgrade, ...closeOf(error, false));
73
+ }
74
+ /** End document `id`'s collaboration, if one is under way: the document is no longer kept. */
75
+ end(id) {
76
+ this.#collaborations.get(id)?.end(CLOSE_NO_DOCUMENT, "the document was deleted");
77
+ }
78
+ /** Refuse every client arriving from now on, and end every collaboration once its log is kept. */
79
+ async close() {
80
+ this.#closing = true;
81
+ const ending = [...this.#collaborations.values()];
82
+ for (const collaboration of ending)
83
+ collaboration.end(CLOSE_SERVER_CLOSING, "the server is closing");
84
+ await Promise.all(ending.map((collaboration) => collaboration.done));
85
+ this.#sockets.close();
86
+ }
87
+ /** Document `id`'s collaboration: the one under way, or a new one. */
88
+ #collaborationOf(id) {
89
+ let collaboration = this.#collaborations.get(id);
90
+ if (!collaboration || collaboration.ended) {
91
+ collaboration = new Collaboration(id, this.#store, this.#sessions, (ended) => {
92
+ if (this.#collaborations.get(id) === ended)
93
+ this.#collaborations.delete(id);
94
+ });
95
+ this.#collaborations.set(id, collaboration);
96
+ }
97
+ return collaboration;
98
+ }
99
+ /** Take `upgrade` and close it at once with `code` and `reason`. */
100
+ #refuse({ request, socket, head }, code, reason) {
101
+ this.#sockets.handleUpgrade(request, socket, head, (client) => client.close(code, truncateReason(reason)));
102
+ }
103
+ }
104
+ /**
105
+ * Document `id`'s collaboration: the clients editing it together over its
106
+ * pooled session, which it holds busy — so neither idled out nor evicted — for
107
+ * as long as any client is connected or arriving. A client's edits are merged
108
+ * into the session, sent on to every other client, and kept as the document's
109
+ * edit log; its presence is merged and sent on, and never kept.
110
+ *
111
+ * The log is the session's whole editing state, written after every merge —
112
+ * one write at a time, the next taking in everything merged meanwhile — and
113
+ * once more before the session is let go.
114
+ */
115
+ class Collaboration {
116
+ /** The session, once the pool has it open; rejects when it can't be opened. */
117
+ session;
118
+ /** Settles once the collaboration is over and its log is kept. */
119
+ done;
120
+ #id;
121
+ #store;
122
+ #onEnd;
123
+ /** Every connected client; the joined ones are those edits are sent on to. */
124
+ #clients = new Set();
125
+ #joined = new Set();
126
+ #arriving = 0;
127
+ #ended = false;
128
+ #finish;
129
+ /** Whether something merged since the log was last written. */
130
+ #logBehind = false;
131
+ #logWriting;
132
+ constructor(id, store, sessions, onEnd) {
133
+ this.#id = id;
134
+ this.#store = store;
135
+ this.#onEnd = onEnd;
136
+ this.done = new Promise((resolve) => (this.#finish = resolve));
137
+ this.session = new Promise((resolve, reject) => {
138
+ // The collaboration is one long use of the pooled session.
139
+ sessions
140
+ .use(id, (session) => {
141
+ resolve(session);
142
+ // However it goes — closed, or its engine gone — the
143
+ // clients can't go on with it.
144
+ void session.closed.then((reason) => this.end(CLOSE_SESSION_ENDED, `the document's session ended: ${reason.message}`));
145
+ return this.done;
146
+ })
147
+ .catch((error) => {
148
+ reject(error);
149
+ this.#ended = true;
150
+ this.#finish();
151
+ this.#onEnd(this);
152
+ });
153
+ });
154
+ // Its failure is each arrival's to answer, not an unhandled rejection.
155
+ this.session.catch(() => { });
156
+ }
157
+ /** Whether it is over, so an arriving client needs a new one. */
158
+ get ended() {
159
+ return this.#ended;
160
+ }
161
+ /** Count a client arriving, so the collaboration lasts until it is admitted or leaves. */
162
+ arrive() {
163
+ this.#arriving++;
164
+ let settled = false;
165
+ const settle = () => {
166
+ if (settled)
167
+ return false;
168
+ settled = true;
169
+ this.#arriving--;
170
+ return true;
171
+ };
172
+ return {
173
+ admit: (client) => {
174
+ if (!settle()) {
175
+ client.close(CLOSE_SESSION_ENDED, "the collaboration ended");
176
+ return;
177
+ }
178
+ if (this.#ended) {
179
+ client.close(CLOSE_SESSION_ENDED, "the collaboration ended");
180
+ this.#settleIfEmpty();
181
+ return;
182
+ }
183
+ this.#admit(client);
184
+ },
185
+ leave: () => {
186
+ if (settle())
187
+ this.#settleIfEmpty();
188
+ },
189
+ };
190
+ }
191
+ /** End it now: close every client with `code` and `reason`, keep the log, let the session go. */
192
+ end(code, reason) {
193
+ if (this.#ended)
194
+ return;
195
+ this.#ended = true;
196
+ this.#onEnd(this);
197
+ for (const client of this.#clients)
198
+ client.close(code, reason);
199
+ void this.#logKept().then(() => this.#finish());
200
+ }
201
+ #admit(client) {
202
+ this.#clients.add(client);
203
+ // One message at a time per client, in the order it sent them.
204
+ let received = Promise.resolve();
205
+ client.on("message", (data, isBinary) => {
206
+ received = received.then(() => this.#receive(client, data, isBinary));
207
+ });
208
+ client.on("close", () => {
209
+ this.#clients.delete(client);
210
+ this.#joined.delete(client);
211
+ this.#settleIfEmpty();
212
+ });
213
+ }
214
+ async #receive(client, data, isBinary) {
215
+ const message = isBinary && Buffer.isBuffer(data) ? data : undefined;
216
+ if (!message || message.byteLength === 0) {
217
+ client.close(CLOSE_NOT_BINARY, "a message is a binary frame: its kind's byte, then its payload");
218
+ return;
219
+ }
220
+ const kind = message[0];
221
+ const payload = new Uint8Array(message.subarray(1));
222
+ const joined = this.#joined.has(client);
223
+ if (kind !== JOIN && !joined) {
224
+ client.close(CLOSE_PROTOCOL_ERROR, "join first");
225
+ return;
226
+ }
227
+ const session = await this.session;
228
+ try {
229
+ switch (kind) {
230
+ case JOIN: {
231
+ if (joined) {
232
+ client.close(CLOSE_PROTOCOL_ERROR, "already joined");
233
+ return;
234
+ }
235
+ // Joined before it is answered, so an edit merged while the
236
+ // answer is made is sent on to it too: it may get one
237
+ // twice, which merging makes harmless, but never not at all.
238
+ this.#joined.add(client);
239
+ const missing = await session.patchSince(payload);
240
+ const held = await session.versionVector();
241
+ const presence = await session.presence();
242
+ send(client, JOIN, held);
243
+ send(client, PATCH, missing);
244
+ send(client, PRESENCE, presence);
245
+ return;
246
+ }
247
+ case OPAQUE_PARTS:
248
+ // Kept before the patch that names them is merged or sent on,
249
+ // so no client learns of a part it can't load.
250
+ await this.#store.putOpaqueParts(this.#id, payload);
251
+ return;
252
+ case PATCH:
253
+ await session.merge(payload);
254
+ this.#sendOn(client, PATCH, payload);
255
+ this.#keepLog();
256
+ return;
257
+ case PRESENCE:
258
+ await session.mergePresence(payload);
259
+ this.#sendOn(client, PRESENCE, payload);
260
+ return;
261
+ default:
262
+ client.close(CLOSE_PROTOCOL_ERROR, `no message is of kind ${kind}`);
263
+ }
264
+ }
265
+ catch (error) {
266
+ // What a client sent that the engine can't take ends that client
267
+ // alone; nothing of it was sent on or kept.
268
+ if (this.#ended)
269
+ return;
270
+ const [code, reason] = closeOf(error, true);
271
+ client.close(code, truncateReason(reason));
272
+ }
273
+ }
274
+ /** Send `payload` as `kind` to every joined client but `from`. */
275
+ #sendOn(from, kind, payload) {
276
+ for (const client of this.#joined)
277
+ if (client !== from)
278
+ send(client, kind, payload);
279
+ }
280
+ /** Once no client is connected or arriving, end it — unless one arrives while its log is written. */
281
+ #settleIfEmpty() {
282
+ if (this.#ended || this.#clients.size > 0 || this.#arriving > 0)
283
+ return;
284
+ void this.#logKept().then(() => {
285
+ if (this.#ended || this.#clients.size > 0 || this.#arriving > 0)
286
+ return;
287
+ this.#ended = true;
288
+ this.#onEnd(this);
289
+ this.#finish();
290
+ });
291
+ }
292
+ /** Write the log, now or after the write under way, which then takes this merge in too. */
293
+ #keepLog() {
294
+ this.#logBehind = true;
295
+ this.#logWriting ??= this.#writeLog().finally(() => (this.#logWriting = undefined));
296
+ }
297
+ async #writeLog() {
298
+ const session = await this.session;
299
+ while (this.#logBehind) {
300
+ this.#logBehind = false;
301
+ try {
302
+ await this.#store.putLog(this.#id, await session.snapshot());
303
+ }
304
+ catch (error) {
305
+ // A document deleted meanwhile has nothing to keep it for.
306
+ if (!this.#ended) {
307
+ console.error(`udoc-server: document ${this.#id}'s edits could not be kept: ${messageOf(error)}`);
308
+ }
309
+ }
310
+ }
311
+ }
312
+ /** Settles once every merge so far is in the kept log. */
313
+ async #logKept() {
314
+ while (this.#logWriting)
315
+ await this.#logWriting;
316
+ }
317
+ }
318
+ /** Send `payload` to `client` as a message of `kind`. */
319
+ function send(client, kind, payload) {
320
+ const message = new Uint8Array(payload.byteLength + 1);
321
+ message[0] = kind;
322
+ message.set(payload, 1);
323
+ client.send(message);
324
+ }
325
+ /** A close reason fits in a control frame: at most 123 bytes of UTF-8. */
326
+ function truncateReason(reason) {
327
+ const bytes = new TextEncoder().encode(reason);
328
+ return bytes.byteLength <= 123 ? reason : `${new TextDecoder().decode(bytes.subarray(0, 120))}...`;
329
+ }
330
+ /**
331
+ * The close code and reason `error` calls for, picked by its code: a license
332
+ * refusal, or no such document; then, for a document that couldn't be opened,
333
+ * that; and once it is open, its session failing — `internal` or `crashed` —
334
+ * or else a payload the engine couldn't merge.
335
+ */
336
+ function closeOf(error, opened) {
337
+ const { code, message } = failureOf(error);
338
+ if (LICENSE_CODES.has(code))
339
+ return [CLOSE_LICENSE_REFUSED, message];
340
+ if (code === "notFound")
341
+ return [CLOSE_NO_DOCUMENT, message];
342
+ if (!opened)
343
+ return [CLOSE_CANNOT_OPEN, message];
344
+ if (code === "internal" || code === "crashed")
345
+ return [CLOSE_SESSION_ENDED, message];
346
+ return [CLOSE_DID_NOT_MERGE, message];
347
+ }
348
+ //# sourceMappingURL=collaboration.js.map