@classcad/client 0.0.0-stage → 3.0.0-beta.20261119090857
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/README.md +20 -2
- package/bin/buerli-classcad.cjs +23 -0
- package/build/cjs/BuerliCadFacade.js +718 -0
- package/build/cjs/cclass/utils/assembly.js +687 -0
- package/build/cjs/cclass/utils/base.js +136 -0
- package/build/cjs/cclass/utils/index.js +99 -0
- package/build/cjs/cclass/utils/part.js +153 -0
- package/build/cjs/classcadEngine.js +33 -0
- package/build/cjs/createApi.js +71 -0
- package/build/cjs/createUnwrappedApi.js +43 -0
- package/build/cjs/facade.js +103 -0
- package/build/cjs/globals.js +157 -0
- package/build/cjs/index.js +102 -0
- package/build/cjs/io/AwvNodeClient.js +290 -0
- package/build/cjs/io/SocketIOClient.js +339 -0
- package/build/cjs/io/Transaction.js +134 -0
- package/build/cjs/io/WASMClient.js +433 -0
- package/build/cjs/io/WSClient.js +646 -0
- package/build/cjs/io/engineKey.js +202 -0
- package/build/cjs/re-export.js +35 -0
- package/build/cjs/session/host.js +479 -0
- package/build/cjs/session/identity.js +38 -0
- package/build/cjs/session/selection.js +283 -0
- package/build/cjs/session/share.js +229 -0
- package/build/cjs/session/types.js +23 -0
- package/build/cjs/test/SocketIOClient.spec.js +178 -0
- package/build/cjs/types/ComClient.js +10 -0
- package/build/cjs/utils/createRecursiveBufferGeometry.js +55 -0
- package/build/cjs/utils/createRecursiveScene.js +140 -0
- package/build/cjs/utils/getDifferentColoredMeshesFromEntity.js +24 -0
- package/build/cjs/utils/index.js +20 -0
- package/build/cjs/utils/polyline.js +65 -0
- package/build/cjs/utils/waitForSelect.js +29 -0
- package/build/esm/BuerliCadFacade.js +714 -0
- package/build/esm/cclass/utils/assembly.js +665 -0
- package/build/esm/cclass/utils/base.js +127 -0
- package/build/esm/cclass/utils/index.js +62 -0
- package/build/esm/cclass/utils/part.js +144 -0
- package/build/esm/classcadEngine.js +30 -0
- package/build/esm/createApi.js +66 -0
- package/build/esm/createUnwrappedApi.js +39 -0
- package/build/esm/facade.js +98 -0
- package/build/esm/globals.js +150 -0
- package/build/esm/index.js +80 -0
- package/build/esm/io/AwvNodeClient.js +286 -0
- package/build/esm/io/SocketIOClient.js +332 -0
- package/build/esm/io/Transaction.js +130 -0
- package/build/esm/io/WASMClient.js +429 -0
- package/build/esm/io/WSClient.js +642 -0
- package/build/esm/io/engineKey.js +196 -0
- package/build/esm/re-export.js +3 -0
- package/build/esm/session/host.js +474 -0
- package/build/esm/session/identity.js +34 -0
- package/build/esm/session/selection.js +277 -0
- package/build/esm/session/share.js +221 -0
- package/build/esm/session/types.js +20 -0
- package/build/esm/test/SocketIOClient.spec.js +178 -0
- package/build/esm/types/ComClient.js +7 -0
- package/build/esm/utils/createRecursiveBufferGeometry.js +51 -0
- package/build/esm/utils/createRecursiveScene.js +136 -0
- package/build/esm/utils/getDifferentColoredMeshesFromEntity.js +20 -0
- package/build/esm/utils/index.js +4 -0
- package/build/esm/utils/polyline.js +60 -0
- package/build/esm/utils/waitForSelect.js +23 -0
- package/build/types/BuerliCadFacade.d.ts +410 -0
- package/build/types/cclass/utils/assembly.d.ts +180 -0
- package/build/types/cclass/utils/base.d.ts +55 -0
- package/build/types/cclass/utils/index.d.ts +46 -0
- package/build/types/cclass/utils/part.d.ts +46 -0
- package/build/types/classcadEngine.d.ts +40 -0
- package/build/types/createApi.d.ts +65 -0
- package/build/types/createUnwrappedApi.d.ts +36 -0
- package/build/types/facade.d.ts +9 -0
- package/build/types/globals.d.ts +79 -0
- package/build/types/index.d.ts +82 -0
- package/build/types/io/AwvNodeClient.d.ts +182 -0
- package/build/types/io/SocketIOClient.d.ts +84 -0
- package/build/types/io/Transaction.d.ts +56 -0
- package/build/types/io/WASMClient.d.ts +239 -0
- package/build/types/io/WSClient.d.ts +242 -0
- package/build/types/io/engineKey.d.ts +137 -0
- package/build/types/re-export.d.ts +6 -0
- package/build/types/session/host.d.ts +108 -0
- package/build/types/session/identity.d.ts +46 -0
- package/build/types/session/selection.d.ts +164 -0
- package/build/types/session/share.d.ts +131 -0
- package/build/types/session/types.d.ts +113 -0
- package/build/types/test/SocketIOClient.spec.d.ts +0 -0
- package/build/types/types/ComClient.d.ts +307 -0
- package/build/types/utils/createRecursiveBufferGeometry.d.ts +8 -0
- package/build/types/utils/createRecursiveScene.d.ts +24 -0
- package/build/types/utils/getDifferentColoredMeshesFromEntity.d.ts +14 -0
- package/build/types/utils/index.d.ts +4 -0
- package/build/types/utils/polyline.d.ts +43 -0
- package/build/types/utils/waitForSelect.d.ts +4 -0
- package/doc/api/advanced/connection.md +488 -0
- package/doc/api/clients.md +2045 -0
- package/doc/api/engine-keys.md +230 -0
- package/doc/api/index.md +58 -0
- package/doc/api/modeling.md +682 -0
- package/doc/api/other.md +33 -0
- package/doc/api/session-sharing.md +706 -0
- package/package.json +59 -4
- package/test/classcadEngine.test.cjs +44 -0
- package/test/connect.test.cjs +81 -0
- package/test/engineKey.test.cjs +80 -0
- package/test/onClient.test.cjs +82 -0
- package/typedoc.json +8 -0
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
// Engine keys from an access token or the app's own sign-in, so that an app carries no key.
|
|
2
|
+
//
|
|
3
|
+
// A ClassCAD account makes access tokens on its account page (classcad.ch/account):
|
|
4
|
+
// ccpk_… public: may sit in a web page; yields keys for the account's registered domains and localhost
|
|
5
|
+
// ccsk_… secret: for servers; never put it into a web page
|
|
6
|
+
// The token exchange turns a token into an engine key that the plan allows, with its expiry.
|
|
7
|
+
// Keys are cached until shortly before they expire and renewed in the background, and a cached
|
|
8
|
+
// key that has not expired keeps working when the service cannot be reached.
|
|
9
|
+
/**
|
|
10
|
+
* The token exchange of the ClassCAD backend.
|
|
11
|
+
*
|
|
12
|
+
* @advanced
|
|
13
|
+
* @category Engine Keys
|
|
14
|
+
*/
|
|
15
|
+
export const DEFAULT_KEY_URL = 'https://europe-west1-classcad-app.cloudfunctions.net/api/v1/key';
|
|
16
|
+
/**
|
|
17
|
+
* The error when there is no key for an engine: no token, the key service cannot be reached, or it refused.
|
|
18
|
+
*
|
|
19
|
+
* {@link WASMClient.connect} rejects with it.
|
|
20
|
+
*
|
|
21
|
+
* @example
|
|
22
|
+
* ```ts
|
|
23
|
+
* import { EngineKeyError, resolveEngineKey } from '@classcad/client'
|
|
24
|
+
*
|
|
25
|
+
* // Checks a page's token before the app starts, and says why it fails
|
|
26
|
+
* try {
|
|
27
|
+
* await resolveEngineKey({ token: 'ccpk_…' })
|
|
28
|
+
* } catch (error) {
|
|
29
|
+
* if (error instanceof EngineKeyError && error.status && error.status < 500) {
|
|
30
|
+
* showError(`ClassCAD refused the key: ${error.message}`) // e.g. a domain the account has not registered
|
|
31
|
+
* } else {
|
|
32
|
+
* showError('The ClassCAD key service cannot be reached')
|
|
33
|
+
* }
|
|
34
|
+
* }
|
|
35
|
+
* ```
|
|
36
|
+
* @category Engine Keys
|
|
37
|
+
*/
|
|
38
|
+
export class EngineKeyError extends Error {
|
|
39
|
+
/**
|
|
40
|
+
* @param message - What went wrong; the key service's own words when it refused.
|
|
41
|
+
* @param status - The HTTP status of the key service's answer, when it answered.
|
|
42
|
+
* @param code - The key service's error code, when it gave one.
|
|
43
|
+
*/
|
|
44
|
+
constructor(message, status, code) {
|
|
45
|
+
super(message);
|
|
46
|
+
this.status = status;
|
|
47
|
+
this.code = code;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
// A cached key is renewed once less than a quarter of its life, or less than a day, is left
|
|
51
|
+
const RENEW_SHARE = 0.25;
|
|
52
|
+
const MIN_LEFT = 24 * 3600 * 1000;
|
|
53
|
+
const storage = () => {
|
|
54
|
+
try {
|
|
55
|
+
return typeof localStorage !== 'undefined' ? localStorage : null;
|
|
56
|
+
}
|
|
57
|
+
catch (error) {
|
|
58
|
+
return null;
|
|
59
|
+
}
|
|
60
|
+
};
|
|
61
|
+
// One cache entry per token, page origin and service; the token itself is not stored as a name
|
|
62
|
+
const cacheName = async (token, keyUrl) => {
|
|
63
|
+
const origin = typeof location !== 'undefined' ? location.origin : '';
|
|
64
|
+
const subtle = typeof crypto !== 'undefined' ? crypto.subtle : undefined;
|
|
65
|
+
if (!subtle)
|
|
66
|
+
return null;
|
|
67
|
+
const hash = await subtle.digest('SHA-256', new TextEncoder().encode(`${keyUrl}|${origin}|${token}`));
|
|
68
|
+
return ('classcad.key.' +
|
|
69
|
+
Array.from(new Uint8Array(hash))
|
|
70
|
+
.slice(0, 16)
|
|
71
|
+
.map(b => b.toString(16).padStart(2, '0'))
|
|
72
|
+
.join(''));
|
|
73
|
+
};
|
|
74
|
+
/**
|
|
75
|
+
* Asks the token exchange for a key.
|
|
76
|
+
*
|
|
77
|
+
* Sends `source.token` to `source.keyUrl` (default {@link DEFAULT_KEY_URL}) every time; {@link resolveEngineKey}
|
|
78
|
+
* caches the key. Throws an {@link EngineKeyError} without a token, when the service cannot be reached, and with
|
|
79
|
+
* its reason when it refuses.
|
|
80
|
+
*
|
|
81
|
+
* @param source - The access token, and optionally `keyUrl`, `appType` and `client`.
|
|
82
|
+
* @example
|
|
83
|
+
* ```ts
|
|
84
|
+
* import { requestEngineKey } from '@classcad/client'
|
|
85
|
+
*
|
|
86
|
+
* // The app's server: hands its signed-in users engine keys, with the secret token only it knows
|
|
87
|
+
* export async function engineKeyRoute(request: Request): Promise<Response> {
|
|
88
|
+
* if (!(await isSignedIn(request))) return new Response('Sign in first', { status: 401 })
|
|
89
|
+
* const key = await requestEngineKey({ token: process.env.CLASSCAD_SECRET_TOKEN, client: 'my-app server' })
|
|
90
|
+
* return Response.json(key) // { key, exp }, what a WASMClient's getKey returns
|
|
91
|
+
* }
|
|
92
|
+
* ```
|
|
93
|
+
* @advanced
|
|
94
|
+
* @category Engine Keys
|
|
95
|
+
*/
|
|
96
|
+
export async function requestEngineKey(source) {
|
|
97
|
+
if (!source.token)
|
|
98
|
+
throw new EngineKeyError('No access token');
|
|
99
|
+
let res;
|
|
100
|
+
try {
|
|
101
|
+
res = await fetch(source.keyUrl || DEFAULT_KEY_URL, {
|
|
102
|
+
method: 'POST',
|
|
103
|
+
headers: { 'content-type': 'application/json', authorization: `Bearer ${source.token}` },
|
|
104
|
+
body: JSON.stringify({ appType: source.appType || 'wasm', client: source.client }),
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
catch (error) {
|
|
108
|
+
throw new EngineKeyError(`The ClassCAD key service cannot be reached: ${error.message}`);
|
|
109
|
+
}
|
|
110
|
+
const body = await res.json().catch(() => null);
|
|
111
|
+
if (!res.ok || !body || typeof body.key !== 'string') {
|
|
112
|
+
throw new EngineKeyError((body && body.message) || `The ClassCAD key service answered ${res.status}`, res.status, body === null || body === void 0 ? void 0 : body.code);
|
|
113
|
+
}
|
|
114
|
+
return { key: body.key, exp: body.exp };
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* The key for an engine start: the given key, the app's own, or one for the access token.
|
|
118
|
+
*
|
|
119
|
+
* Throws EngineKeyError when there is none, with the service's reason (an unregistered
|
|
120
|
+
* domain, a revoked token, a plan without the native engine).
|
|
121
|
+
*
|
|
122
|
+
* A key for a token is cached in `localStorage` (where there is one), per token, page origin and key service. It is
|
|
123
|
+
* used until a minute before it expires and renewed in the background once less than a quarter of its life, or less
|
|
124
|
+
* than a day, is left. When the service cannot be reached, a cached key that has not expired is used; a refusal
|
|
125
|
+
* (an HTTP 4xx) is final. {@link WASMClient} calls it on `connect`.
|
|
126
|
+
*
|
|
127
|
+
* @param source - The key, the app's `getKey`, or the access token to get one with.
|
|
128
|
+
* @returns The key.
|
|
129
|
+
* @example
|
|
130
|
+
* ```ts
|
|
131
|
+
* import { resolveEngineKey } from '@classcad/client'
|
|
132
|
+
*
|
|
133
|
+
* // A server that starts a native engine of its own, with a secret access token
|
|
134
|
+
* const key = await resolveEngineKey({
|
|
135
|
+
* token: process.env.CLASSCAD_SECRET_TOKEN,
|
|
136
|
+
* appType: 'native',
|
|
137
|
+
* client: 'render farm',
|
|
138
|
+
* })
|
|
139
|
+
* await startEngine(key)
|
|
140
|
+
* ```
|
|
141
|
+
* @category Engine Keys
|
|
142
|
+
*/
|
|
143
|
+
export async function resolveEngineKey(source) {
|
|
144
|
+
if (source.classcadKey)
|
|
145
|
+
return source.classcadKey;
|
|
146
|
+
if (source.getKey) {
|
|
147
|
+
const key = await source.getKey();
|
|
148
|
+
return typeof key === 'string' ? key : key.key;
|
|
149
|
+
}
|
|
150
|
+
if (!source.token)
|
|
151
|
+
throw new EngineKeyError('An engine needs a token, a getKey function or a classcadKey');
|
|
152
|
+
const keyUrl = source.keyUrl || DEFAULT_KEY_URL;
|
|
153
|
+
const store = storage();
|
|
154
|
+
const name = store ? await cacheName(source.token, keyUrl) : null;
|
|
155
|
+
let cached = null;
|
|
156
|
+
if (store && name) {
|
|
157
|
+
try {
|
|
158
|
+
cached = JSON.parse(store.getItem(name) || 'null');
|
|
159
|
+
}
|
|
160
|
+
catch (error) {
|
|
161
|
+
cached = null;
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
const fetchAndStore = async () => {
|
|
165
|
+
const fresh = await requestEngineKey(Object.assign(Object.assign({}, source), { keyUrl }));
|
|
166
|
+
if (store && name) {
|
|
167
|
+
try {
|
|
168
|
+
store.setItem(name, JSON.stringify({ key: fresh.key, exp: fresh.exp, iat: Date.now() }));
|
|
169
|
+
}
|
|
170
|
+
catch (error) {
|
|
171
|
+
// a full or blocked storage only costs a fetch next time
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
return fresh.key;
|
|
175
|
+
};
|
|
176
|
+
const now = Date.now();
|
|
177
|
+
if (cached && cached.exp > now + 60 * 1000) {
|
|
178
|
+
const left = cached.exp - now;
|
|
179
|
+
const life = cached.exp - (cached.iat || now);
|
|
180
|
+
// The engine checks its key at start only: renewing now readies the next start
|
|
181
|
+
if (left < MIN_LEFT || left < life * RENEW_SHARE)
|
|
182
|
+
fetchAndStore().catch(() => undefined);
|
|
183
|
+
return cached.key;
|
|
184
|
+
}
|
|
185
|
+
try {
|
|
186
|
+
return await fetchAndStore();
|
|
187
|
+
}
|
|
188
|
+
catch (error) {
|
|
189
|
+
// Our service down, or no network: a key that has not expired still starts the engine.
|
|
190
|
+
// A refusal (4xx) is final: the plan or the token does not allow it any more.
|
|
191
|
+
const refused = error instanceof EngineKeyError && !!error.status && error.status < 500;
|
|
192
|
+
if (cached && cached.exp > now && !refused)
|
|
193
|
+
return cached.key;
|
|
194
|
+
throw error;
|
|
195
|
+
}
|
|
196
|
+
}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
export { BooleanOperationType, ChamferType, CLASSCAD_VERSION, CLASSCAD_VERSION_QUALITY, DataType, ExtrusionType, FlipType, NOID, OrientationType, ReorientedType, SVGModusType, ViewType, WorkAxisType, WorkCoordSystemType, WorkPlaneType, WorkPointType, } from '@classcad/api-js';
|
|
2
|
+
export { MessageLevel, ScgClassType, ScgGraphicType } from '@classcad/api-js';
|
|
3
|
+
export { CCClasses, classMap, ContainerType, CurveTypes, EdgeTypes, EntityTypes, GraphicType, MemberType, MeshTypes, PointTypes, } from '@classcad/sdkjs';
|
|
@@ -0,0 +1,474 @@
|
|
|
1
|
+
// Session sharing — hosting a session from a page.
|
|
2
|
+
//
|
|
3
|
+
// An engine that runs in the page (WASMClient) has no server around it. To
|
|
4
|
+
// share its session all the same, the page speaks the server's part of the
|
|
5
|
+
// session protocol itself: this module. Guests connect with the client they
|
|
6
|
+
// would use against a ClassCAD server (WSClient, a ClassCAD MCP) and get a
|
|
7
|
+
// server's frames: SessionJoined, the presence snapshot, every command's
|
|
8
|
+
// StructurePatch / Graphic / Result, presence.
|
|
9
|
+
//
|
|
10
|
+
// A page cannot listen, so somebody has to introduce the guests: a ClassCAD
|
|
11
|
+
// MCP on the same machine, or the ClassCAD share relay (classcad-ai's
|
|
12
|
+
// packages/relay), where guests join from anywhere. For every invite the page
|
|
13
|
+
// keeps a connection to that session address open. When a guest joins there
|
|
14
|
+
// with that invite, the broker says so and the page opens one more connection,
|
|
15
|
+
// which the broker joins to the guest's. From then on host and guest talk to
|
|
16
|
+
// each other; the broker in the middle only passes the bytes.
|
|
17
|
+
//
|
|
18
|
+
// page ── ?host=<invite> ────────────────► MCP / relay ◄── ?invite=<invite> ── guest
|
|
19
|
+
// page ── ?host=<invite>&guest=<id> ─────► └─ joined to the guest's connection
|
|
20
|
+
//
|
|
21
|
+
// The relay takes an offer only from a signed-in account (`auth`). A browser's
|
|
22
|
+
// WebSocket sends no headers, so the sign-in rides as a protocol next to
|
|
23
|
+
// PAGE_PROTOCOL; a refusal comes back as a close code, 4000 + the HTTP status.
|
|
24
|
+
//
|
|
25
|
+
// The engine speaks an older dialect than a server (Patch/ops, binary
|
|
26
|
+
// packages, the value nested in `result`); pieces() translates it. The same
|
|
27
|
+
// translation serves the MCP's own engine: packages/mcp/src/share/hub.ts in
|
|
28
|
+
// the classcad-ai repository is this module's twin, keep them in step.
|
|
29
|
+
//
|
|
30
|
+
// Where a page differs from a server: its engine always generates everything a
|
|
31
|
+
// command changed, so a guest's emission config only decides the FORM of what
|
|
32
|
+
// that guest is sent (streamed frames, or bundled on the Result), never what
|
|
33
|
+
// the others get.
|
|
34
|
+
import { v4 as uuid } from 'uuid';
|
|
35
|
+
/** The emission config a fresh connection has on a server: full content, bundled on the Result. */
|
|
36
|
+
const DEFAULT_EMISSION = {
|
|
37
|
+
sendStructure: true,
|
|
38
|
+
sendStructure_Patch: false,
|
|
39
|
+
sendStructure_Compressed: false,
|
|
40
|
+
sendStructure_Immediately: false,
|
|
41
|
+
sendStructure_ImmediatelyBinary: false,
|
|
42
|
+
sendGraphic_Kernel: true,
|
|
43
|
+
sendGraphic_StructureObj: true,
|
|
44
|
+
sendGraphic_Sketch: true,
|
|
45
|
+
sendGraphic_Invisible: true,
|
|
46
|
+
sendGraphic_Compressed: false,
|
|
47
|
+
sendGraphic_Immediately: false,
|
|
48
|
+
sendGraphic_ImmediatelyBinary: false,
|
|
49
|
+
sendGraphic_Multipackage: false,
|
|
50
|
+
sendGraphic_UseDraco: false,
|
|
51
|
+
sendGraphic_UseDracoHybrid: false,
|
|
52
|
+
sendGraphic_AdvancedNotifications: false,
|
|
53
|
+
sendMessages: true,
|
|
54
|
+
sendMessages_Immediately: false,
|
|
55
|
+
sendMessages_MinLevel: 31,
|
|
56
|
+
storeState: false,
|
|
57
|
+
safeApi: false,
|
|
58
|
+
};
|
|
59
|
+
/** Pulls: they change nothing, so they concern only the one who asked. */
|
|
60
|
+
const READS = new Set(['GetTree', 'Sync']);
|
|
61
|
+
/** The engine's message level for an error; a Result at this level rejects in the client. */
|
|
62
|
+
const ERROR = 51;
|
|
63
|
+
/** A server relays presence frames of up to 8 KB and drops larger ones without a word. So does a page. */
|
|
64
|
+
const PRESENCE_MAX_BYTES = 8 * 1024;
|
|
65
|
+
/** Channels a guest may not publish on: the host's, and the server's own. */
|
|
66
|
+
const RESERVED_CHANNELS = new Set(['config', 'leave']);
|
|
67
|
+
/** The MCP may restart (an update, its idle exit), the network may drop: look for the broker again soon, and keep looking. */
|
|
68
|
+
const MAX_BACKOFF_MS = 5000;
|
|
69
|
+
/** The protocol a page names when it offers to a broker that wants a sign-in; the sign-in rides next to it as `bearer.<token>`. */
|
|
70
|
+
const PAGE_PROTOCOL = 'classcad-session';
|
|
71
|
+
/** How a broker refuses a page (4000 + the HTTP status): a sign-in it does not take, a plan that does not share, an invite offered by another account. */
|
|
72
|
+
const UNAUTHORIZED = 4401;
|
|
73
|
+
const FORBIDDEN = 4403;
|
|
74
|
+
const CONFLICT = 4409;
|
|
75
|
+
/** A Result frame that fails `req`, the way a server words an error. */
|
|
76
|
+
const errorResult = (req, message) => ({
|
|
77
|
+
command: 'Result',
|
|
78
|
+
_from_: String(req.command),
|
|
79
|
+
_transactionID_: req.transactionID,
|
|
80
|
+
maxLevel: ERROR,
|
|
81
|
+
messages: [{ message, level: ERROR, levelStr: 'ERROR', code: 0, timestamp: Date.now() }],
|
|
82
|
+
});
|
|
83
|
+
/** A streaming connection (WSClient) takes patches and graphics as frames of their own. */
|
|
84
|
+
const streams = (cfg) => cfg.sendStructure_Patch === true;
|
|
85
|
+
/** Translates one reply of the engine into what a server's frames are made of. */
|
|
86
|
+
export function pieces(req, res) {
|
|
87
|
+
var _a, _b, _c, _d, _e, _f, _g, _h;
|
|
88
|
+
const from = String(req.command);
|
|
89
|
+
const tx = req.transactionID;
|
|
90
|
+
const out = {
|
|
91
|
+
from,
|
|
92
|
+
tx,
|
|
93
|
+
patches: [],
|
|
94
|
+
packages: (_a = res.binaryMessages) !== null && _a !== void 0 ? _a : [],
|
|
95
|
+
result: { command: 'Result', _from_: from, _transactionID_: tx },
|
|
96
|
+
};
|
|
97
|
+
// Errors the engine reported on the side (errorState 2 and up).
|
|
98
|
+
const side = [];
|
|
99
|
+
let answer;
|
|
100
|
+
for (const m of (_b = res.messages) !== null && _b !== void 0 ? _b : []) {
|
|
101
|
+
if ((m === null || m === void 0 ? void 0 : m.command) === 'Patch' && Array.isArray(m.ops) && m.ops.length)
|
|
102
|
+
out.patches.push(m.ops);
|
|
103
|
+
else if ((m === null || m === void 0 ? void 0 : m.command) === 'ErrorMessage' && Number((_c = m.attributes) === null || _c === void 0 ? void 0 : _c.errorState) >= 2)
|
|
104
|
+
side.push({
|
|
105
|
+
level: ERROR,
|
|
106
|
+
levelStr: 'ERROR',
|
|
107
|
+
code: (_e = (_d = m.attributes) === null || _d === void 0 ? void 0 : _d.errorCode) !== null && _e !== void 0 ? _e : 0,
|
|
108
|
+
message: String((_g = (_f = m.attributes) === null || _f === void 0 ? void 0 : _f.errorMessage) !== null && _g !== void 0 ? _g : 'engine error'),
|
|
109
|
+
});
|
|
110
|
+
else if ((m === null || m === void 0 ? void 0 : m.command) === 'Result')
|
|
111
|
+
answer !== null && answer !== void 0 ? answer : (answer = m);
|
|
112
|
+
else if ((m === null || m === void 0 ? void 0 : m.command) === 'UndoStack')
|
|
113
|
+
out.undoStack = m;
|
|
114
|
+
}
|
|
115
|
+
if (!answer) {
|
|
116
|
+
out.result = errorResult(req, side.length ? side.map(e => e.message).join('; ') : `the engine returned no result for ${from}`);
|
|
117
|
+
return out;
|
|
118
|
+
}
|
|
119
|
+
if (READS.has(from)) {
|
|
120
|
+
out.structure = (_h = answer.structure) !== null && _h !== void 0 ? _h : answer.result;
|
|
121
|
+
return out;
|
|
122
|
+
}
|
|
123
|
+
let value = answer.result;
|
|
124
|
+
let maxLevel = typeof answer.maxLevel === 'number' ? answer.maxLevel : undefined;
|
|
125
|
+
let messages = Array.isArray(answer.messages) ? answer.messages : undefined;
|
|
126
|
+
let streamData = answer.streamData;
|
|
127
|
+
// The engine nests an Execute's value next to its level and messages: { result, maxLevel, messages }.
|
|
128
|
+
if (from === 'Execute' && value && typeof value === 'object' && !Array.isArray(value) && 'result' in value) {
|
|
129
|
+
if (typeof value.maxLevel === 'number')
|
|
130
|
+
maxLevel = Math.max(maxLevel !== null && maxLevel !== void 0 ? maxLevel : 0, value.maxLevel);
|
|
131
|
+
if (Array.isArray(value.messages))
|
|
132
|
+
messages = [...(messages !== null && messages !== void 0 ? messages : []), ...value.messages];
|
|
133
|
+
streamData !== null && streamData !== void 0 ? streamData : (streamData = value.streamData);
|
|
134
|
+
value = value.result;
|
|
135
|
+
}
|
|
136
|
+
// An error reported only on the side must not pass as an empty success.
|
|
137
|
+
if (from === 'Execute' && side.length && (maxLevel !== null && maxLevel !== void 0 ? maxLevel : 0) < ERROR && value == null) {
|
|
138
|
+
maxLevel = ERROR;
|
|
139
|
+
messages = [...(messages !== null && messages !== void 0 ? messages : []), ...side];
|
|
140
|
+
}
|
|
141
|
+
out.result.result = value;
|
|
142
|
+
if (maxLevel !== undefined)
|
|
143
|
+
out.result.maxLevel = maxLevel;
|
|
144
|
+
if (messages === null || messages === void 0 ? void 0 : messages.length)
|
|
145
|
+
out.result.messages = messages;
|
|
146
|
+
if (streamData)
|
|
147
|
+
out.result.streamData = streamData;
|
|
148
|
+
return out;
|
|
149
|
+
}
|
|
150
|
+
/**
|
|
151
|
+
* A page's side of a shared session: offers invites at a ClassCAD MCP on the
|
|
152
|
+
* same machine or on the share relay, and serves the guests that join with
|
|
153
|
+
* them as a ClassCAD server would. `WASMClient` makes one with its first
|
|
154
|
+
* invite; an app has no need to use it directly.
|
|
155
|
+
*
|
|
156
|
+
* @internal
|
|
157
|
+
*/
|
|
158
|
+
export class SessionHost {
|
|
159
|
+
constructor(opts) {
|
|
160
|
+
this.opts = opts;
|
|
161
|
+
/** The host's peer id, as guests see it on presence frames. */
|
|
162
|
+
this.hostId = uuid();
|
|
163
|
+
this.offers = new Map();
|
|
164
|
+
this.guests = new Set();
|
|
165
|
+
this.hostPresence = new Map();
|
|
166
|
+
this.closed = false;
|
|
167
|
+
}
|
|
168
|
+
/** The guests that are in the session right now. */
|
|
169
|
+
get peers() {
|
|
170
|
+
return Array.from(this.guests, g => g.peer);
|
|
171
|
+
}
|
|
172
|
+
/** Makes an invite joinable: keeps a connection to the broker open for it, whatever happens to the broker. */
|
|
173
|
+
offer(invite) {
|
|
174
|
+
if (this.closed || this.offers.has(invite.invite))
|
|
175
|
+
return;
|
|
176
|
+
const offer = { invite, control: null, backoff: 500 };
|
|
177
|
+
this.offers.set(invite.invite, offer);
|
|
178
|
+
void this.announce(offer);
|
|
179
|
+
}
|
|
180
|
+
/** Takes an invite back: nobody joins with it any more, and whoever did is cut off. Returns how many were. */
|
|
181
|
+
revoke(token) {
|
|
182
|
+
var _a;
|
|
183
|
+
const offer = this.offers.get(token);
|
|
184
|
+
if (!offer)
|
|
185
|
+
return 0;
|
|
186
|
+
this.offers.delete(token);
|
|
187
|
+
if (offer.timer)
|
|
188
|
+
clearTimeout(offer.timer);
|
|
189
|
+
try {
|
|
190
|
+
(_a = offer.control) === null || _a === void 0 ? void 0 : _a.close();
|
|
191
|
+
}
|
|
192
|
+
catch (_b) {
|
|
193
|
+
/* already closed */
|
|
194
|
+
}
|
|
195
|
+
let kicked = 0;
|
|
196
|
+
for (const guest of Array.from(this.guests)) {
|
|
197
|
+
if (guest.peer.invite !== token)
|
|
198
|
+
continue;
|
|
199
|
+
try {
|
|
200
|
+
guest.ws.close();
|
|
201
|
+
}
|
|
202
|
+
catch (_c) {
|
|
203
|
+
/* already closed */
|
|
204
|
+
}
|
|
205
|
+
this.leave(guest);
|
|
206
|
+
kicked++;
|
|
207
|
+
}
|
|
208
|
+
return kicked;
|
|
209
|
+
}
|
|
210
|
+
/** A command of the page itself, and what the engine emitted for it: the guests get it like any other. */
|
|
211
|
+
deliver(command, reply) {
|
|
212
|
+
if (this.closed || this.guests.size === 0)
|
|
213
|
+
return;
|
|
214
|
+
this.send(command.transactionID ? command : Object.assign(Object.assign({}, command), { transactionID: uuid() }), reply, null);
|
|
215
|
+
}
|
|
216
|
+
/** Presence from the host to every guest (kept for those who join later). */
|
|
217
|
+
sendPresence(channel, data) {
|
|
218
|
+
if (channel === 'leave')
|
|
219
|
+
return;
|
|
220
|
+
this.hostPresence.set(channel, data);
|
|
221
|
+
const text = JSON.stringify({ command: 'Presence', channel, peerId: this.hostId, data });
|
|
222
|
+
for (const guest of this.guests)
|
|
223
|
+
this.raw(guest, text);
|
|
224
|
+
}
|
|
225
|
+
/** The page stops hosting: every guest is closed, every invite taken back. */
|
|
226
|
+
close() {
|
|
227
|
+
this.closed = true;
|
|
228
|
+
for (const token of Array.from(this.offers.keys()))
|
|
229
|
+
this.revoke(token);
|
|
230
|
+
for (const guest of Array.from(this.guests)) {
|
|
231
|
+
try {
|
|
232
|
+
guest.ws.close();
|
|
233
|
+
}
|
|
234
|
+
catch (_a) {
|
|
235
|
+
/* already closed */
|
|
236
|
+
}
|
|
237
|
+
this.leave(guest);
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
// ── The broker (an MCP, or the relay) ──
|
|
241
|
+
/** The broker's session address, with what this connection is for. */
|
|
242
|
+
address(params) {
|
|
243
|
+
return `${this.opts.url.replace(/\/+$/, '')}/?${params}`;
|
|
244
|
+
}
|
|
245
|
+
/** Opens the standing connection for an invite, and opens it again whenever it is lost. */
|
|
246
|
+
async announce(offer) {
|
|
247
|
+
const offered = () => !this.closed && this.offers.has(offer.invite.invite);
|
|
248
|
+
if (!offered())
|
|
249
|
+
return;
|
|
250
|
+
let ws;
|
|
251
|
+
const retry = () => {
|
|
252
|
+
if (!offered())
|
|
253
|
+
return;
|
|
254
|
+
offer.timer = setTimeout(() => void this.announce(offer), Math.min(offer.backoff, MAX_BACKOFF_MS));
|
|
255
|
+
offer.backoff = Math.min(offer.backoff * 2, MAX_BACKOFF_MS);
|
|
256
|
+
};
|
|
257
|
+
// The sign-in, where the broker wants one: a fresh one after it did not take the last.
|
|
258
|
+
const fresh = offer.refresh === true;
|
|
259
|
+
let protocols;
|
|
260
|
+
if (this.opts.auth) {
|
|
261
|
+
let token;
|
|
262
|
+
try {
|
|
263
|
+
token = await this.opts.auth(fresh);
|
|
264
|
+
}
|
|
265
|
+
catch (_a) {
|
|
266
|
+
// (no token without a network, say: it is asked for again with the next look)
|
|
267
|
+
return retry();
|
|
268
|
+
}
|
|
269
|
+
if (!offered())
|
|
270
|
+
return;
|
|
271
|
+
if (!token)
|
|
272
|
+
return this.refused(offer, { code: UNAUTHORIZED, reason: 'Sign in to share this session.' });
|
|
273
|
+
protocols = [PAGE_PROTOCOL, `bearer.${token}`];
|
|
274
|
+
}
|
|
275
|
+
try {
|
|
276
|
+
ws = new WebSocket(this.address(`host=${encodeURIComponent(offer.invite.invite)}`), protocols);
|
|
277
|
+
}
|
|
278
|
+
catch (_b) {
|
|
279
|
+
return retry();
|
|
280
|
+
}
|
|
281
|
+
offer.control = ws;
|
|
282
|
+
ws.onopen = () => {
|
|
283
|
+
offer.backoff = 500;
|
|
284
|
+
};
|
|
285
|
+
ws.onmessage = ev => {
|
|
286
|
+
let note = null;
|
|
287
|
+
try {
|
|
288
|
+
note = JSON.parse(typeof ev.data === 'string' ? ev.data : '');
|
|
289
|
+
}
|
|
290
|
+
catch (_a) {
|
|
291
|
+
return;
|
|
292
|
+
}
|
|
293
|
+
// Somebody joined with this invite: meet them on a connection of their own.
|
|
294
|
+
if (note && note.relay === 'guest' && typeof note.guest === 'string')
|
|
295
|
+
this.meet(offer.invite, note.guest);
|
|
296
|
+
};
|
|
297
|
+
ws.onclose = ev => {
|
|
298
|
+
if (offer.control === ws)
|
|
299
|
+
offer.control = null;
|
|
300
|
+
// Refused for good: the plan does not share, another account offers the invite, or a fresh sign-in did
|
|
301
|
+
// not hold either. A sign-in that did not hold (it ran out, say) is tried once more, fresh.
|
|
302
|
+
if (ev.code === FORBIDDEN || ev.code === CONFLICT || (ev.code === UNAUTHORIZED && fresh))
|
|
303
|
+
return this.refused(offer, { code: ev.code, reason: ev.reason });
|
|
304
|
+
offer.refresh = ev.code === UNAUTHORIZED;
|
|
305
|
+
retry();
|
|
306
|
+
};
|
|
307
|
+
ws.onerror = () => {
|
|
308
|
+
/* onclose follows and looks for the broker again */
|
|
309
|
+
};
|
|
310
|
+
}
|
|
311
|
+
/** The broker will not take an invite: it is offered no more, and the page is told why. */
|
|
312
|
+
refused(offer, refusal) {
|
|
313
|
+
var _a, _b;
|
|
314
|
+
if (!this.offers.has(offer.invite.invite))
|
|
315
|
+
return;
|
|
316
|
+
this.revoke(offer.invite.invite);
|
|
317
|
+
(_b = (_a = this.opts).onRefused) === null || _b === void 0 ? void 0 : _b.call(_a, offer.invite, refusal);
|
|
318
|
+
}
|
|
319
|
+
/** Opens the connection the broker joins to one guest's. */
|
|
320
|
+
meet(invite, guestId) {
|
|
321
|
+
let ws;
|
|
322
|
+
try {
|
|
323
|
+
ws = new WebSocket(this.address(`host=${encodeURIComponent(invite.invite)}&guest=${encodeURIComponent(guestId)}`));
|
|
324
|
+
}
|
|
325
|
+
catch (_a) {
|
|
326
|
+
return;
|
|
327
|
+
}
|
|
328
|
+
ws.onopen = () => this.serve(ws, invite);
|
|
329
|
+
}
|
|
330
|
+
// ── The guests ──
|
|
331
|
+
/** Sends a guest one frame, if its connection still takes any. */
|
|
332
|
+
raw(guest, text) {
|
|
333
|
+
if (guest.ws.readyState !== WebSocket.OPEN)
|
|
334
|
+
return;
|
|
335
|
+
try {
|
|
336
|
+
guest.ws.send(text);
|
|
337
|
+
}
|
|
338
|
+
catch (_a) {
|
|
339
|
+
/* closing */
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
/** Takes a guest in: the handshake a server gives, then its commands and presence. */
|
|
343
|
+
serve(ws, invite) {
|
|
344
|
+
var _a, _b;
|
|
345
|
+
if (this.closed || !this.offers.has(invite.invite))
|
|
346
|
+
return ws.close();
|
|
347
|
+
const peer = { peerId: uuid(), invite: invite.invite, inviteName: invite.name, role: invite.role };
|
|
348
|
+
const guest = { peer, ws, config: Object.assign({}, DEFAULT_EMISSION), presence: new Map() };
|
|
349
|
+
this.raw(guest, JSON.stringify({ command: 'SessionJoined', role: invite.role, inviteName: invite.name }));
|
|
350
|
+
// The snapshot: what everyone already here last said, per channel.
|
|
351
|
+
for (const [channel, data] of this.hostPresence)
|
|
352
|
+
this.raw(guest, JSON.stringify({ command: 'Presence', channel, peerId: this.hostId, data }));
|
|
353
|
+
for (const other of this.guests)
|
|
354
|
+
for (const [channel, data] of other.presence)
|
|
355
|
+
this.raw(guest, JSON.stringify({ command: 'Presence', channel, peerId: other.peer.peerId, data }));
|
|
356
|
+
// The undo history as it is, as a server sends it to a guest that joins.
|
|
357
|
+
const undoStack = (_b = (_a = this.opts).undoStack) === null || _b === void 0 ? void 0 : _b.call(_a);
|
|
358
|
+
if (undoStack)
|
|
359
|
+
this.raw(guest, JSON.stringify(undoStack));
|
|
360
|
+
this.guests.add(guest);
|
|
361
|
+
this.opts.onPeerJoined(peer);
|
|
362
|
+
ws.onmessage = ev => {
|
|
363
|
+
if (this.closed || typeof ev.data !== 'string')
|
|
364
|
+
return;
|
|
365
|
+
let req;
|
|
366
|
+
try {
|
|
367
|
+
req = JSON.parse(ev.data);
|
|
368
|
+
}
|
|
369
|
+
catch (_a) {
|
|
370
|
+
return;
|
|
371
|
+
}
|
|
372
|
+
if (!req || typeof req !== 'object' || typeof req.command !== 'string')
|
|
373
|
+
return;
|
|
374
|
+
if (req.command === 'Presence')
|
|
375
|
+
return this.presence(guest, req, ev.data.length);
|
|
376
|
+
void this.command(guest, req);
|
|
377
|
+
};
|
|
378
|
+
ws.onclose = () => this.leave(guest);
|
|
379
|
+
ws.onerror = () => this.leave(guest);
|
|
380
|
+
}
|
|
381
|
+
/** A guest is gone: the others and the page are told. */
|
|
382
|
+
leave(guest) {
|
|
383
|
+
if (!this.guests.delete(guest))
|
|
384
|
+
return;
|
|
385
|
+
const left = JSON.stringify({ command: 'Presence', channel: 'leave', peerId: guest.peer.peerId, data: {} });
|
|
386
|
+
for (const other of this.guests)
|
|
387
|
+
this.raw(other, left);
|
|
388
|
+
this.opts.onPeerLeft(guest.peer);
|
|
389
|
+
this.opts.onPresence({ channel: 'leave', peerId: guest.peer.peerId, data: {} });
|
|
390
|
+
}
|
|
391
|
+
/** A guest's presence frame: kept for those who join later and relayed to everyone else, as a server does. */
|
|
392
|
+
presence(guest, frame, bytes) {
|
|
393
|
+
const channel = typeof frame.channel === 'string' ? frame.channel : '';
|
|
394
|
+
const data = frame.data;
|
|
395
|
+
if (!channel || bytes > PRESENCE_MAX_BYTES || !data || typeof data !== 'object' || Array.isArray(data))
|
|
396
|
+
return;
|
|
397
|
+
if (RESERVED_CHANNELS.has(channel))
|
|
398
|
+
return;
|
|
399
|
+
guest.presence.set(channel, data);
|
|
400
|
+
const text = JSON.stringify({ command: 'Presence', channel, peerId: guest.peer.peerId, data });
|
|
401
|
+
for (const other of this.guests)
|
|
402
|
+
if (other !== guest)
|
|
403
|
+
this.raw(other, text);
|
|
404
|
+
this.opts.onPresence({ channel, peerId: guest.peer.peerId, data });
|
|
405
|
+
}
|
|
406
|
+
/** A guest's command: answered here (emission config, what a guest may not do), or run on the page's engine. */
|
|
407
|
+
async command(guest, req) {
|
|
408
|
+
const name = req.command;
|
|
409
|
+
const answer = (result) => this.raw(guest, JSON.stringify({ command: 'Result', _from_: name, _transactionID_: req.transactionID, result }));
|
|
410
|
+
if (name === 'GetEmissionConfig')
|
|
411
|
+
return answer(Object.assign({}, guest.config));
|
|
412
|
+
if (name === 'SetEmissionConfig') {
|
|
413
|
+
const wanted = req.config && typeof req.config === 'object' ? req.config : {};
|
|
414
|
+
for (const [key, value] of Object.entries(wanted)) {
|
|
415
|
+
if (key in DEFAULT_EMISSION && typeof value === typeof DEFAULT_EMISSION[key])
|
|
416
|
+
guest.config[key] = value;
|
|
417
|
+
}
|
|
418
|
+
return answer(Object.assign({}, guest.config));
|
|
419
|
+
}
|
|
420
|
+
if (name === 'CreateInvite' || name === 'RevokeInvite')
|
|
421
|
+
return this.raw(guest, JSON.stringify(errorResult(req, `${name}: only the host of a session can do that, and this connection joined it by invite.`)));
|
|
422
|
+
try {
|
|
423
|
+
this.send(req, await this.opts.execute(req), guest);
|
|
424
|
+
}
|
|
425
|
+
catch (err) {
|
|
426
|
+
this.raw(guest, JSON.stringify(errorResult(req, err instanceof Error ? err.message : String(err))));
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
/** One engine reply, to everyone it concerns, each in the form its connection asked for. */
|
|
430
|
+
send(req, res, origin) {
|
|
431
|
+
const read = READS.has(String(req.command));
|
|
432
|
+
// A pull concerns only the one who asked; the page's own are its own.
|
|
433
|
+
const recipients = read ? (origin && this.guests.has(origin) ? [origin] : []) : Array.from(this.guests);
|
|
434
|
+
if (!recipients.length)
|
|
435
|
+
return;
|
|
436
|
+
const p = pieces(req, res);
|
|
437
|
+
const head = { _from_: p.from, _transactionID_: p.tx };
|
|
438
|
+
const version = { version: 11 };
|
|
439
|
+
let patchFrames = null;
|
|
440
|
+
let graphicFrames = null;
|
|
441
|
+
for (const guest of recipients) {
|
|
442
|
+
const cfg = guest.config;
|
|
443
|
+
const result = Object.assign({}, p.result);
|
|
444
|
+
if (read) {
|
|
445
|
+
result.structure = p.structure;
|
|
446
|
+
if (cfg.sendGraphic_Kernel !== false)
|
|
447
|
+
result.graphic = { containers: this.opts.containers(), properties: version };
|
|
448
|
+
}
|
|
449
|
+
else if (streams(cfg)) {
|
|
450
|
+
if (cfg.sendStructure !== false) {
|
|
451
|
+
patchFrames !== null && patchFrames !== void 0 ? patchFrames : (patchFrames = p.patches.map(ops => JSON.stringify(Object.assign(Object.assign({ command: 'StructurePatch' }, head), { structurePatch: ops }))));
|
|
452
|
+
for (const frame of patchFrames)
|
|
453
|
+
this.raw(guest, frame);
|
|
454
|
+
}
|
|
455
|
+
if (cfg.sendGraphic_Kernel !== false && p.packages.length) {
|
|
456
|
+
graphicFrames !== null && graphicFrames !== void 0 ? graphicFrames : (graphicFrames = p.packages.map(pkg => JSON.stringify(Object.assign(Object.assign({ command: 'Graphic' }, head), { graphic: pkg }))));
|
|
457
|
+
for (const frame of graphicFrames)
|
|
458
|
+
this.raw(guest, frame);
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
else if (cfg.sendGraphic_Kernel !== false && p.packages.length) {
|
|
462
|
+
// Bundled: what the command changed rides on its Result. The structure
|
|
463
|
+
// does not (it would cost a pull per command): GetTree returns it.
|
|
464
|
+
result.graphic = { containers: p.packages.flatMap(pkg => { var _a; return (_a = pkg === null || pkg === void 0 ? void 0 : pkg.containers) !== null && _a !== void 0 ? _a : []; }), properties: version };
|
|
465
|
+
}
|
|
466
|
+
if (cfg.sendMessages === false)
|
|
467
|
+
delete result.messages;
|
|
468
|
+
this.raw(guest, JSON.stringify(result));
|
|
469
|
+
// The undo history follows the Result, as on a server.
|
|
470
|
+
if (p.undoStack)
|
|
471
|
+
this.raw(guest, JSON.stringify(p.undoStack));
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
}
|