@abraca/dabra 2.101.0 → 2.103.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.
- package/dist/abracadabra-provider.cjs +6673 -6543
- package/dist/abracadabra-provider.cjs.map +1 -1
- package/dist/esm/AbracadabraBaseProvider.js +558 -0
- package/dist/esm/AbracadabraBaseProvider.js.map +1 -0
- package/dist/esm/AbracadabraClient.js +1424 -0
- package/dist/esm/AbracadabraClient.js.map +1 -0
- package/dist/esm/AbracadabraProvider.js +547 -0
- package/dist/esm/AbracadabraProvider.js.map +1 -0
- package/dist/esm/AbracadabraWS.js +398 -0
- package/dist/esm/AbracadabraWS.js.map +1 -0
- package/dist/esm/BackgroundSyncManager.js +571 -0
- package/dist/esm/BackgroundSyncManager.js.map +1 -0
- package/dist/esm/BackgroundSyncPersistence.js +62 -0
- package/dist/esm/BackgroundSyncPersistence.js.map +1 -0
- package/dist/esm/ChatClient.js +176 -0
- package/dist/esm/ChatClient.js.map +1 -0
- package/dist/esm/CloseEvents.js +45 -0
- package/dist/esm/CloseEvents.js.map +1 -0
- package/dist/esm/ContentManager.js +153 -0
- package/dist/esm/ContentManager.js.map +1 -0
- package/dist/esm/CoverReconcile.js +124 -0
- package/dist/esm/CoverReconcile.js.map +1 -0
- package/dist/esm/CryptoIdentityKeystore.js +580 -0
- package/dist/esm/CryptoIdentityKeystore.js.map +1 -0
- package/dist/esm/DeviceRegistrationService.js +158 -0
- package/dist/esm/DeviceRegistrationService.js.map +1 -0
- package/dist/esm/DocConverters.js +1300 -0
- package/dist/esm/DocConverters.js.map +1 -0
- package/dist/esm/DocKeyManager.js +145 -0
- package/dist/esm/DocKeyManager.js.map +1 -0
- package/dist/esm/DocTypes.js +792 -0
- package/dist/esm/DocTypes.js.map +1 -0
- package/dist/esm/DocUtils.js +180 -0
- package/dist/esm/DocUtils.js.map +1 -0
- package/dist/esm/DocumentCache.js +131 -0
- package/dist/esm/DocumentCache.js.map +1 -0
- package/dist/esm/DocumentManager.js +240 -0
- package/dist/esm/DocumentManager.js.map +1 -0
- package/dist/esm/E2EAbracadabraProvider.js +273 -0
- package/dist/esm/E2EAbracadabraProvider.js.map +1 -0
- package/dist/esm/E2EOfflineStore.js +53 -0
- package/dist/esm/E2EOfflineStore.js.map +1 -0
- package/dist/esm/EncryptedChatClient.js +156 -0
- package/dist/esm/EncryptedChatClient.js.map +1 -0
- package/dist/esm/EncryptedY.js +115 -0
- package/dist/esm/EncryptedY.js.map +1 -0
- package/dist/esm/EventEmitter.js +40 -0
- package/dist/esm/EventEmitter.js.map +1 -0
- package/dist/esm/FileBlobStore.js +410 -0
- package/dist/esm/FileBlobStore.js.map +1 -0
- package/dist/esm/IdentityDoc.js +413 -0
- package/dist/esm/IdentityDoc.js.map +1 -0
- package/dist/esm/IncomingMessage.js +39 -0
- package/dist/esm/IncomingMessage.js.map +1 -0
- package/dist/esm/LifecycleGate.js +124 -0
- package/dist/esm/LifecycleGate.js.map +1 -0
- package/dist/esm/MessageReceiver.js +86 -0
- package/dist/esm/MessageReceiver.js.map +1 -0
- package/dist/esm/MessageSender.js +19 -0
- package/dist/esm/MessageSender.js.map +1 -0
- package/dist/esm/MetaManager.js +112 -0
- package/dist/esm/MetaManager.js.map +1 -0
- package/dist/esm/MnemonicKeyDerivation.js +137 -0
- package/dist/esm/MnemonicKeyDerivation.js.map +1 -0
- package/dist/esm/NodeConnect.js +63 -0
- package/dist/esm/NodeConnect.js.map +1 -0
- package/dist/esm/NodeIdentity.js +212 -0
- package/dist/esm/NodeIdentity.js.map +1 -0
- package/dist/esm/NotificationsClient.js +136 -0
- package/dist/esm/NotificationsClient.js.map +1 -0
- package/dist/esm/OfflineStore.js +291 -0
- package/dist/esm/OfflineStore.js.map +1 -0
- package/dist/esm/OutgoingMessage.js +18 -0
- package/dist/esm/OutgoingMessage.js.map +1 -0
- package/dist/esm/OutgoingMessages/AuthenticationMessage.js +24 -0
- package/dist/esm/OutgoingMessages/AuthenticationMessage.js.map +1 -0
- package/dist/esm/OutgoingMessages/AwarenessMessage.js +28 -0
- package/dist/esm/OutgoingMessages/AwarenessMessage.js.map +1 -0
- package/dist/esm/OutgoingMessages/CloseMessage.js +21 -0
- package/dist/esm/OutgoingMessages/CloseMessage.js.map +1 -0
- package/dist/esm/OutgoingMessages/QueryAwarenessMessage.js +21 -0
- package/dist/esm/OutgoingMessages/QueryAwarenessMessage.js.map +1 -0
- package/dist/esm/OutgoingMessages/StatelessMessage.js +22 -0
- package/dist/esm/OutgoingMessages/StatelessMessage.js.map +1 -0
- package/dist/esm/OutgoingMessages/SubdocMessage.js +34 -0
- package/dist/esm/OutgoingMessages/SubdocMessage.js.map +1 -0
- package/dist/esm/OutgoingMessages/SyncStepOneMessage.js +24 -0
- package/dist/esm/OutgoingMessages/SyncStepOneMessage.js.map +1 -0
- package/dist/esm/OutgoingMessages/UpdateMessage.js +23 -0
- package/dist/esm/OutgoingMessages/UpdateMessage.js.map +1 -0
- package/dist/esm/PerfCounters.js +336 -0
- package/dist/esm/PerfCounters.js.map +1 -0
- package/dist/esm/QueryClient.js +117 -0
- package/dist/esm/QueryClient.js.map +1 -0
- package/dist/esm/RpcClient.js +456 -0
- package/dist/esm/RpcClient.js.map +1 -0
- package/dist/esm/SchemaTypes.js +38 -0
- package/dist/esm/SchemaTypes.js.map +1 -0
- package/dist/esm/SearchIndex.js +167 -0
- package/dist/esm/SearchIndex.js.map +1 -0
- package/dist/esm/ServerRegistry.js +139 -0
- package/dist/esm/ServerRegistry.js.map +1 -0
- package/dist/esm/ServerReset.js +170 -0
- package/dist/esm/ServerReset.js.map +1 -0
- package/dist/esm/TokenManager.js +236 -0
- package/dist/esm/TokenManager.js.map +1 -0
- package/dist/esm/TreeManager.js +655 -0
- package/dist/esm/TreeManager.js.map +1 -0
- package/dist/esm/TreeTimestamps.js +61 -0
- package/dist/esm/TreeTimestamps.js.map +1 -0
- package/dist/esm/auth.js +43 -0
- package/dist/esm/auth.js.map +1 -0
- package/dist/esm/awarenessStatesToArray.js +13 -0
- package/dist/esm/awarenessStatesToArray.js.map +1 -0
- package/dist/esm/docIds.js +53 -0
- package/dist/esm/docIds.js.map +1 -0
- package/dist/esm/encryptedContent.js +21 -0
- package/dist/esm/encryptedContent.js.map +1 -0
- package/dist/esm/index.js +61 -0
- package/dist/esm/messageRecord.js +64 -0
- package/dist/esm/messageRecord.js.map +1 -0
- package/dist/esm/sync/BroadcastChannelSync.js +160 -0
- package/dist/esm/sync/BroadcastChannelSync.js.map +1 -0
- package/dist/esm/types.js +54 -0
- package/dist/esm/types.js.map +1 -0
- package/dist/esm/webrtc/AbracadabraWebRTC.js +483 -0
- package/dist/esm/webrtc/AbracadabraWebRTC.js.map +1 -0
- package/dist/esm/webrtc/DataChannelRouter.js +124 -0
- package/dist/esm/webrtc/DataChannelRouter.js.map +1 -0
- package/dist/esm/webrtc/DevicePairingChannel.js +335 -0
- package/dist/esm/webrtc/DevicePairingChannel.js.map +1 -0
- package/dist/esm/webrtc/E2EEChannel.js +137 -0
- package/dist/esm/webrtc/E2EEChannel.js.map +1 -0
- package/dist/esm/webrtc/FileTransferChannel.js +250 -0
- package/dist/esm/webrtc/FileTransferChannel.js.map +1 -0
- package/dist/esm/webrtc/ManualSignaling.js +161 -0
- package/dist/esm/webrtc/ManualSignaling.js.map +1 -0
- package/dist/esm/webrtc/PeerConnection.js +96 -0
- package/dist/esm/webrtc/PeerConnection.js.map +1 -0
- package/dist/esm/webrtc/SignalingSocket.js +274 -0
- package/dist/esm/webrtc/SignalingSocket.js.map +1 -0
- package/dist/esm/webrtc/YjsDataChannel.js +135 -0
- package/dist/esm/webrtc/YjsDataChannel.js.map +1 -0
- package/dist/esm/webrtc/types.js +29 -0
- package/dist/esm/webrtc/types.js.map +1 -0
- package/dist/esm/x25519Convert.js +69 -0
- package/dist/esm/x25519Convert.js.map +1 -0
- package/dist/index.d.ts +26 -11
- package/package.json +6 -4
- package/dist/abracadabra-provider.esm.js +0 -14860
- package/dist/abracadabra-provider.esm.js.map +0 -1
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
import EventEmitter from "../EventEmitter.js";
|
|
2
|
+
import { retry } from "@lifeomic/attempt";
|
|
3
|
+
|
|
4
|
+
//#region packages/provider/src/webrtc/SignalingSocket.ts
|
|
5
|
+
var SignalingSocket = class extends EventEmitter {
|
|
6
|
+
constructor(configuration) {
|
|
7
|
+
super();
|
|
8
|
+
this.ws = null;
|
|
9
|
+
this.wsHandlers = {};
|
|
10
|
+
this.shouldConnect = true;
|
|
11
|
+
this.connectionAttempt = null;
|
|
12
|
+
this.localPeerId = null;
|
|
13
|
+
this.isConnected = false;
|
|
14
|
+
this._connectPromise = null;
|
|
15
|
+
this.config = {
|
|
16
|
+
url: configuration.url,
|
|
17
|
+
token: configuration.token,
|
|
18
|
+
delay: configuration.delay ?? 1e3,
|
|
19
|
+
factor: configuration.factor ?? 2,
|
|
20
|
+
minDelay: configuration.minDelay ?? 1e3,
|
|
21
|
+
maxDelay: configuration.maxDelay ?? 3e4,
|
|
22
|
+
jitter: configuration.jitter ?? true,
|
|
23
|
+
maxAttempts: configuration.maxAttempts ?? 0,
|
|
24
|
+
WebSocketPolyfill: configuration.WebSocketPolyfill ?? WebSocket
|
|
25
|
+
};
|
|
26
|
+
if (configuration.autoConnect !== false) this.connect();
|
|
27
|
+
}
|
|
28
|
+
async getToken() {
|
|
29
|
+
if (typeof this.config.token === "function") return await this.config.token();
|
|
30
|
+
return this.config.token;
|
|
31
|
+
}
|
|
32
|
+
async connect() {
|
|
33
|
+
if (this.isConnected) return;
|
|
34
|
+
if (this._connectPromise) return this._connectPromise;
|
|
35
|
+
this._connectPromise = this._doConnect();
|
|
36
|
+
try {
|
|
37
|
+
await this._connectPromise;
|
|
38
|
+
} finally {
|
|
39
|
+
this._connectPromise = null;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
async _doConnect() {
|
|
43
|
+
if (this.cancelRetry) {
|
|
44
|
+
this.cancelRetry();
|
|
45
|
+
this.cancelRetry = void 0;
|
|
46
|
+
}
|
|
47
|
+
this.shouldConnect = true;
|
|
48
|
+
let cancelAttempt = false;
|
|
49
|
+
const retryPromise = retry(() => this.createConnection(), {
|
|
50
|
+
delay: this.config.delay,
|
|
51
|
+
initialDelay: 0,
|
|
52
|
+
factor: this.config.factor,
|
|
53
|
+
maxAttempts: this.config.maxAttempts,
|
|
54
|
+
minDelay: this.config.minDelay,
|
|
55
|
+
maxDelay: this.config.maxDelay,
|
|
56
|
+
jitter: this.config.jitter,
|
|
57
|
+
timeout: 0,
|
|
58
|
+
beforeAttempt: (context) => {
|
|
59
|
+
if (!this.shouldConnect || cancelAttempt) context.abort();
|
|
60
|
+
}
|
|
61
|
+
}).catch((error) => {
|
|
62
|
+
if (error && error.code !== "ATTEMPT_ABORTED") throw error;
|
|
63
|
+
});
|
|
64
|
+
this.cancelRetry = () => {
|
|
65
|
+
cancelAttempt = true;
|
|
66
|
+
};
|
|
67
|
+
return retryPromise;
|
|
68
|
+
}
|
|
69
|
+
async createConnection() {
|
|
70
|
+
this.cleanup();
|
|
71
|
+
const token = await this.getToken();
|
|
72
|
+
const separator = this.config.url.includes("?") ? "&" : "?";
|
|
73
|
+
const url = `${this.config.url}${separator}token=${encodeURIComponent(token)}`;
|
|
74
|
+
const ws = new this.config.WebSocketPolyfill(url);
|
|
75
|
+
return new Promise((resolve, reject) => {
|
|
76
|
+
const onOpen = () => {
|
|
77
|
+
this.isConnected = true;
|
|
78
|
+
this.sendRaw({ type: "join" });
|
|
79
|
+
};
|
|
80
|
+
const onMessage = (event) => {
|
|
81
|
+
const data = typeof event === "string" ? event : typeof event.data === "string" ? event.data : null;
|
|
82
|
+
if (!data) return;
|
|
83
|
+
let msg;
|
|
84
|
+
try {
|
|
85
|
+
msg = JSON.parse(data);
|
|
86
|
+
} catch {
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
this.handleMessage(msg, resolve);
|
|
90
|
+
};
|
|
91
|
+
const onClose = (event) => {
|
|
92
|
+
const wasConnected = this.isConnected;
|
|
93
|
+
this.isConnected = false;
|
|
94
|
+
this.localPeerId = null;
|
|
95
|
+
if (this.connectionAttempt) {
|
|
96
|
+
this.connectionAttempt = null;
|
|
97
|
+
reject(/* @__PURE__ */ new Error(`Signaling WebSocket closed: ${event?.code}`));
|
|
98
|
+
}
|
|
99
|
+
this.emit("disconnected");
|
|
100
|
+
if (!wasConnected) return;
|
|
101
|
+
if (this.shouldConnect && !this.cancelRetry) setTimeout(() => this.connect(), this.config.delay);
|
|
102
|
+
};
|
|
103
|
+
const onError = (err) => {
|
|
104
|
+
if (this.connectionAttempt) {
|
|
105
|
+
this.connectionAttempt = null;
|
|
106
|
+
reject(err);
|
|
107
|
+
}
|
|
108
|
+
};
|
|
109
|
+
this.wsHandlers = {
|
|
110
|
+
open: onOpen,
|
|
111
|
+
message: onMessage,
|
|
112
|
+
close: onClose,
|
|
113
|
+
error: onError
|
|
114
|
+
};
|
|
115
|
+
for (const [name, handler] of Object.entries(this.wsHandlers)) ws.addEventListener(name, handler);
|
|
116
|
+
this.ws = ws;
|
|
117
|
+
this.connectionAttempt = {
|
|
118
|
+
resolve,
|
|
119
|
+
reject
|
|
120
|
+
};
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
handleMessage(msg, resolveConnection) {
|
|
124
|
+
switch (msg.type) {
|
|
125
|
+
case "welcome":
|
|
126
|
+
this.localPeerId = msg.peer_id;
|
|
127
|
+
if (this.connectionAttempt) {
|
|
128
|
+
this.connectionAttempt = null;
|
|
129
|
+
resolveConnection?.();
|
|
130
|
+
}
|
|
131
|
+
this.emit("welcome", {
|
|
132
|
+
peerId: msg.peer_id,
|
|
133
|
+
peers: msg.peers
|
|
134
|
+
});
|
|
135
|
+
break;
|
|
136
|
+
case "joined":
|
|
137
|
+
this.emit("joined", {
|
|
138
|
+
peer_id: msg.peer_id,
|
|
139
|
+
user_id: msg.user_id,
|
|
140
|
+
muted: msg.muted,
|
|
141
|
+
video: msg.video,
|
|
142
|
+
screen: msg.screen,
|
|
143
|
+
name: msg.name,
|
|
144
|
+
color: msg.color
|
|
145
|
+
});
|
|
146
|
+
break;
|
|
147
|
+
case "left":
|
|
148
|
+
this.emit("left", { peerId: msg.peer_id });
|
|
149
|
+
break;
|
|
150
|
+
case "offer":
|
|
151
|
+
this.emit("offer", {
|
|
152
|
+
from: msg.from,
|
|
153
|
+
sdp: msg.sdp
|
|
154
|
+
});
|
|
155
|
+
break;
|
|
156
|
+
case "answer":
|
|
157
|
+
this.emit("answer", {
|
|
158
|
+
from: msg.from,
|
|
159
|
+
sdp: msg.sdp
|
|
160
|
+
});
|
|
161
|
+
break;
|
|
162
|
+
case "ice":
|
|
163
|
+
this.emit("ice", {
|
|
164
|
+
from: msg.from,
|
|
165
|
+
candidate: msg.candidate
|
|
166
|
+
});
|
|
167
|
+
break;
|
|
168
|
+
case "mute":
|
|
169
|
+
this.emit("mute", {
|
|
170
|
+
peerId: msg.peer_id,
|
|
171
|
+
muted: msg.muted
|
|
172
|
+
});
|
|
173
|
+
break;
|
|
174
|
+
case "media-state":
|
|
175
|
+
this.emit("media-state", {
|
|
176
|
+
peerId: msg.peer_id,
|
|
177
|
+
video: msg.video,
|
|
178
|
+
screen: msg.screen
|
|
179
|
+
});
|
|
180
|
+
break;
|
|
181
|
+
case "profile":
|
|
182
|
+
this.emit("profile", {
|
|
183
|
+
peerId: msg.peer_id,
|
|
184
|
+
name: msg.name,
|
|
185
|
+
color: msg.color
|
|
186
|
+
});
|
|
187
|
+
break;
|
|
188
|
+
case "ping":
|
|
189
|
+
this.sendRaw({ type: "pong" });
|
|
190
|
+
break;
|
|
191
|
+
case "error":
|
|
192
|
+
this.emit("error", {
|
|
193
|
+
code: msg.code,
|
|
194
|
+
message: msg.message
|
|
195
|
+
});
|
|
196
|
+
break;
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
sendRaw(msg) {
|
|
200
|
+
if (this.ws?.readyState === 1) this.ws.send(JSON.stringify(msg));
|
|
201
|
+
}
|
|
202
|
+
sendOffer(to, sdp) {
|
|
203
|
+
this.sendRaw({
|
|
204
|
+
type: "offer",
|
|
205
|
+
to,
|
|
206
|
+
sdp
|
|
207
|
+
});
|
|
208
|
+
}
|
|
209
|
+
sendAnswer(to, sdp) {
|
|
210
|
+
this.sendRaw({
|
|
211
|
+
type: "answer",
|
|
212
|
+
to,
|
|
213
|
+
sdp
|
|
214
|
+
});
|
|
215
|
+
}
|
|
216
|
+
sendIce(to, candidate) {
|
|
217
|
+
this.sendRaw({
|
|
218
|
+
type: "ice",
|
|
219
|
+
to,
|
|
220
|
+
candidate
|
|
221
|
+
});
|
|
222
|
+
}
|
|
223
|
+
sendMute(muted) {
|
|
224
|
+
this.sendRaw({
|
|
225
|
+
type: "mute",
|
|
226
|
+
muted
|
|
227
|
+
});
|
|
228
|
+
}
|
|
229
|
+
sendMediaState(video, screen) {
|
|
230
|
+
this.sendRaw({
|
|
231
|
+
type: "media-state",
|
|
232
|
+
video,
|
|
233
|
+
screen
|
|
234
|
+
});
|
|
235
|
+
}
|
|
236
|
+
sendProfile(name, color) {
|
|
237
|
+
this.sendRaw({
|
|
238
|
+
type: "profile",
|
|
239
|
+
name,
|
|
240
|
+
color
|
|
241
|
+
});
|
|
242
|
+
}
|
|
243
|
+
sendLeave() {
|
|
244
|
+
this.sendRaw({ type: "leave" });
|
|
245
|
+
}
|
|
246
|
+
disconnect() {
|
|
247
|
+
this.shouldConnect = false;
|
|
248
|
+
this.sendLeave();
|
|
249
|
+
if (this.cancelRetry) {
|
|
250
|
+
this.cancelRetry();
|
|
251
|
+
this.cancelRetry = void 0;
|
|
252
|
+
}
|
|
253
|
+
this.cleanup();
|
|
254
|
+
}
|
|
255
|
+
destroy() {
|
|
256
|
+
this.disconnect();
|
|
257
|
+
this.removeAllListeners();
|
|
258
|
+
}
|
|
259
|
+
cleanup() {
|
|
260
|
+
if (!this.ws) return;
|
|
261
|
+
for (const [name, handler] of Object.entries(this.wsHandlers)) this.ws.removeEventListener(name, handler);
|
|
262
|
+
this.wsHandlers = {};
|
|
263
|
+
try {
|
|
264
|
+
if (this.ws.readyState !== 3) this.ws.close();
|
|
265
|
+
} catch {}
|
|
266
|
+
this.ws = null;
|
|
267
|
+
this.isConnected = false;
|
|
268
|
+
this.localPeerId = null;
|
|
269
|
+
}
|
|
270
|
+
};
|
|
271
|
+
|
|
272
|
+
//#endregion
|
|
273
|
+
export { SignalingSocket };
|
|
274
|
+
//# sourceMappingURL=SignalingSocket.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"SignalingSocket.js","names":[],"sources":["../../../src/webrtc/SignalingSocket.ts"],"sourcesContent":["import { retry } from \"@lifeomic/attempt\";\nimport EventEmitter from \"../EventEmitter.ts\";\nimport type {\n\tPeerInfo,\n\tSignalingIncoming,\n\tSignalingOutgoing,\n} from \"./types.ts\";\n\nexport interface SignalingSocketConfiguration {\n\t/** WebSocket URL for the signaling endpoint. */\n\turl: string;\n\n\t/** JWT token or async token factory for auth. */\n\ttoken: string | (() => string) | (() => Promise<string>);\n\n\t/** Auto-connect on construction. Default: true. */\n\tautoConnect?: boolean;\n\n\t/** WebSocket polyfill (e.g. for Node.js). */\n\tWebSocketPolyfill?: any;\n\n\t/** Retry delay in ms. Default: 1000. */\n\tdelay?: number;\n\t/** Retry factor. Default: 2. */\n\tfactor?: number;\n\t/** Min retry delay. Default: 1000. */\n\tminDelay?: number;\n\t/** Max retry delay. Default: 30000. */\n\tmaxDelay?: number;\n\t/** Randomize delay. Default: true. */\n\tjitter?: boolean;\n\t/** Max retry attempts (0 = unlimited). Default: 0. */\n\tmaxAttempts?: number;\n}\n\nexport class SignalingSocket extends EventEmitter {\n\tprivate ws: WebSocket | null = null;\n\tprivate wsHandlers: Record<string, (e: any) => void> = {};\n\tprivate shouldConnect = true;\n\tprivate cancelRetry?: () => void;\n\tprivate connectionAttempt: {\n\t\tresolve: (v?: any) => void;\n\t\treject: (r?: any) => void;\n\t} | null = null;\n\n\tprivate readonly config: Required<\n\t\tPick<\n\t\t\tSignalingSocketConfiguration,\n\t\t\t| \"url\"\n\t\t\t| \"token\"\n\t\t\t| \"delay\"\n\t\t\t| \"factor\"\n\t\t\t| \"minDelay\"\n\t\t\t| \"maxDelay\"\n\t\t\t| \"jitter\"\n\t\t\t| \"maxAttempts\"\n\t\t>\n\t> & { WebSocketPolyfill: any };\n\n\tpublic localPeerId: string | null = null;\n\tpublic isConnected = false;\n\n\tconstructor(configuration: SignalingSocketConfiguration) {\n\t\tsuper();\n\n\t\tthis.config = {\n\t\t\turl: configuration.url,\n\t\t\ttoken: configuration.token,\n\t\t\tdelay: configuration.delay ?? 1000,\n\t\t\tfactor: configuration.factor ?? 2,\n\t\t\tminDelay: configuration.minDelay ?? 1000,\n\t\t\tmaxDelay: configuration.maxDelay ?? 30000,\n\t\t\tjitter: configuration.jitter ?? true,\n\t\t\tmaxAttempts: configuration.maxAttempts ?? 0,\n\t\t\tWebSocketPolyfill: configuration.WebSocketPolyfill ?? WebSocket,\n\t\t};\n\n\t\tif (configuration.autoConnect !== false) {\n\t\t\tthis.connect();\n\t\t}\n\t}\n\n\tprivate async getToken(): Promise<string> {\n\t\tif (typeof this.config.token === \"function\") {\n\t\t\treturn await this.config.token();\n\t\t}\n\t\treturn this.config.token;\n\t}\n\n\tprivate _connectPromise: Promise<void> | null = null;\n\n\tasync connect(): Promise<void> {\n\t\tif (this.isConnected) return;\n\t\tif (this._connectPromise) return this._connectPromise;\n\n\t\tthis._connectPromise = this._doConnect();\n\t\ttry {\n\t\t\tawait this._connectPromise;\n\t\t} finally {\n\t\t\tthis._connectPromise = null;\n\t\t}\n\t}\n\n\tprivate async _doConnect(): Promise<void> {\n\t\tif (this.cancelRetry) {\n\t\t\tthis.cancelRetry();\n\t\t\tthis.cancelRetry = undefined;\n\t\t}\n\n\t\tthis.shouldConnect = true;\n\n\t\tlet cancelAttempt = false;\n\n\t\tconst retryPromise = retry(\n\t\t\t() => this.createConnection(),\n\t\t\t{\n\t\t\t\tdelay: this.config.delay,\n\t\t\t\tinitialDelay: 0,\n\t\t\t\tfactor: this.config.factor,\n\t\t\t\tmaxAttempts: this.config.maxAttempts,\n\t\t\t\tminDelay: this.config.minDelay,\n\t\t\t\tmaxDelay: this.config.maxDelay,\n\t\t\t\tjitter: this.config.jitter,\n\t\t\t\ttimeout: 0,\n\t\t\t\tbeforeAttempt: (context) => {\n\t\t\t\t\tif (!this.shouldConnect || cancelAttempt) {\n\t\t\t\t\t\tcontext.abort();\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t},\n\t\t).catch((error: any) => {\n\t\t\tif (error && error.code !== \"ATTEMPT_ABORTED\") {\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t});\n\n\t\tthis.cancelRetry = () => {\n\t\t\tcancelAttempt = true;\n\t\t};\n\n\t\treturn retryPromise;\n\t}\n\n\tprivate async createConnection(): Promise<void> {\n\t\tthis.cleanup();\n\n\t\tconst token = await this.getToken();\n\t\tconst separator = this.config.url.includes(\"?\") ? \"&\" : \"?\";\n\t\tconst url = `${this.config.url}${separator}token=${encodeURIComponent(token)}`;\n\n\t\tconst ws = new this.config.WebSocketPolyfill(url);\n\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst onOpen = () => {\n\t\t\t\tthis.isConnected = true;\n\t\t\t\t// Server auto-sends Welcome on join; we send Join to register\n\t\t\t\tthis.sendRaw({ type: \"join\" });\n\t\t\t};\n\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n\t\t\tconst onMessage = (event: MessageEvent | { data: string }) => {\n\t\t\t\tconst data =\n\t\t\t\t\ttypeof event === \"string\"\n\t\t\t\t\t\t? event\n\t\t\t\t\t\t: typeof (event as MessageEvent).data === \"string\"\n\t\t\t\t\t\t\t? (event as MessageEvent).data\n\t\t\t\t\t\t\t: null;\n\t\t\t\tif (!data) return;\n\n\t\t\t\tlet msg: SignalingOutgoing;\n\t\t\t\ttry {\n\t\t\t\t\tmsg = JSON.parse(data);\n\t\t\t\t} catch {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tthis.handleMessage(msg, resolve);\n\t\t\t};\n\n\t\t\tconst onClose = (event: CloseEvent | { code?: number }) => {\n\t\t\t\tconst wasConnected = this.isConnected;\n\t\t\t\tthis.isConnected = false;\n\t\t\t\tthis.localPeerId = null;\n\n\t\t\t\tif (this.connectionAttempt) {\n\t\t\t\t\tthis.connectionAttempt = null;\n\t\t\t\t\treject(\n\t\t\t\t\t\tnew Error(`Signaling WebSocket closed: ${(event as CloseEvent)?.code}`),\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tthis.emit(\"disconnected\");\n\n\t\t\t\tif (!wasConnected) return;\n\n\t\t\t\t// Auto-reconnect if desired\n\t\t\t\tif (this.shouldConnect && !this.cancelRetry) {\n\t\t\t\t\tsetTimeout(() => this.connect(), this.config.delay);\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tconst onError = (err: Event) => {\n\t\t\t\tif (this.connectionAttempt) {\n\t\t\t\t\tthis.connectionAttempt = null;\n\t\t\t\t\treject(err);\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tthis.wsHandlers = {\n\t\t\t\topen: onOpen,\n\t\t\t\tmessage: onMessage,\n\t\t\t\tclose: onClose,\n\t\t\t\terror: onError,\n\t\t\t};\n\n\t\t\tfor (const [name, handler] of Object.entries(this.wsHandlers)) {\n\t\t\t\tws.addEventListener(name, handler);\n\t\t\t}\n\n\t\t\tthis.ws = ws;\n\t\t\tthis.connectionAttempt = { resolve, reject };\n\t\t});\n\t}\n\n\tprivate handleMessage(msg: SignalingOutgoing, resolveConnection?: (v?: any) => void): void {\n\t\tswitch (msg.type) {\n\t\t\tcase \"welcome\":\n\t\t\t\tthis.localPeerId = msg.peer_id;\n\t\t\t\tif (this.connectionAttempt) {\n\t\t\t\t\tthis.connectionAttempt = null;\n\t\t\t\t\tresolveConnection?.();\n\t\t\t\t}\n\t\t\t\tthis.emit(\"welcome\", {\n\t\t\t\t\tpeerId: msg.peer_id,\n\t\t\t\t\tpeers: msg.peers,\n\t\t\t\t});\n\t\t\t\tbreak;\n\n\t\t\tcase \"joined\":\n\t\t\t\tthis.emit(\"joined\", {\n\t\t\t\t\tpeer_id: msg.peer_id,\n\t\t\t\t\tuser_id: msg.user_id,\n\t\t\t\t\tmuted: msg.muted,\n\t\t\t\t\tvideo: msg.video,\n\t\t\t\t\tscreen: msg.screen,\n\t\t\t\t\tname: msg.name,\n\t\t\t\t\tcolor: msg.color,\n\t\t\t\t} satisfies PeerInfo);\n\t\t\t\tbreak;\n\n\t\t\tcase \"left\":\n\t\t\t\tthis.emit(\"left\", { peerId: msg.peer_id });\n\t\t\t\tbreak;\n\n\t\t\tcase \"offer\":\n\t\t\t\tthis.emit(\"offer\", { from: msg.from, sdp: msg.sdp });\n\t\t\t\tbreak;\n\n\t\t\tcase \"answer\":\n\t\t\t\tthis.emit(\"answer\", { from: msg.from, sdp: msg.sdp });\n\t\t\t\tbreak;\n\n\t\t\tcase \"ice\":\n\t\t\t\tthis.emit(\"ice\", { from: msg.from, candidate: msg.candidate });\n\t\t\t\tbreak;\n\n\t\t\tcase \"mute\":\n\t\t\t\tthis.emit(\"mute\", {\n\t\t\t\t\tpeerId: msg.peer_id,\n\t\t\t\t\tmuted: msg.muted,\n\t\t\t\t});\n\t\t\t\tbreak;\n\n\t\t\tcase \"media-state\":\n\t\t\t\tthis.emit(\"media-state\", {\n\t\t\t\t\tpeerId: msg.peer_id,\n\t\t\t\t\tvideo: msg.video,\n\t\t\t\t\tscreen: msg.screen,\n\t\t\t\t});\n\t\t\t\tbreak;\n\n\t\t\tcase \"profile\":\n\t\t\t\tthis.emit(\"profile\", {\n\t\t\t\t\tpeerId: msg.peer_id,\n\t\t\t\t\tname: msg.name,\n\t\t\t\t\tcolor: msg.color,\n\t\t\t\t});\n\t\t\t\tbreak;\n\n\t\t\tcase \"ping\":\n\t\t\t\tthis.sendRaw({ type: \"pong\" });\n\t\t\t\tbreak;\n\n\t\t\tcase \"error\":\n\t\t\t\tthis.emit(\"error\", {\n\t\t\t\t\tcode: msg.code,\n\t\t\t\t\tmessage: msg.message,\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\tprivate sendRaw(msg: SignalingIncoming): void {\n\t\tif (this.ws?.readyState === 1 /* OPEN */) {\n\t\t\tthis.ws.send(JSON.stringify(msg));\n\t\t}\n\t}\n\n\t// ── Public send methods ─────────────────────────────────────────────────\n\n\tsendOffer(to: string, sdp: string): void {\n\t\tthis.sendRaw({ type: \"offer\", to, sdp });\n\t}\n\n\tsendAnswer(to: string, sdp: string): void {\n\t\tthis.sendRaw({ type: \"answer\", to, sdp });\n\t}\n\n\tsendIce(to: string, candidate: string): void {\n\t\tthis.sendRaw({ type: \"ice\", to, candidate });\n\t}\n\n\tsendMute(muted: boolean): void {\n\t\tthis.sendRaw({ type: \"mute\", muted });\n\t}\n\n\tsendMediaState(video: boolean, screen: boolean): void {\n\t\tthis.sendRaw({ type: \"media-state\", video, screen });\n\t}\n\n\tsendProfile(name: string, color: string): void {\n\t\tthis.sendRaw({ type: \"profile\", name, color });\n\t}\n\n\tsendLeave(): void {\n\t\tthis.sendRaw({ type: \"leave\" });\n\t}\n\n\t// ── Lifecycle ───────────────────────────────────────────────────────────\n\n\tdisconnect(): void {\n\t\tthis.shouldConnect = false;\n\t\tthis.sendLeave();\n\n\t\tif (this.cancelRetry) {\n\t\t\tthis.cancelRetry();\n\t\t\tthis.cancelRetry = undefined;\n\t\t}\n\n\t\tthis.cleanup();\n\t}\n\n\tdestroy(): void {\n\t\tthis.disconnect();\n\t\tthis.removeAllListeners();\n\t}\n\n\tprivate cleanup(): void {\n\t\tif (!this.ws) return;\n\n\t\tfor (const [name, handler] of Object.entries(this.wsHandlers)) {\n\t\t\tthis.ws.removeEventListener(name, handler);\n\t\t}\n\t\tthis.wsHandlers = {};\n\n\t\ttry {\n\t\t\tif (this.ws.readyState !== 3 /* CLOSED */) {\n\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,GAAG,eAAe,EAC1B,MAAK,GAAG,OAAO;UAET;AAIR,OAAK,KAAK;AACV,OAAK,cAAc;AACnB,OAAK,cAAc"}
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import { CHANNEL_NAMES, YJS_MSG } from "./types.js";
|
|
2
|
+
import { applyAwarenessUpdate, encodeAwarenessUpdate } from "y-protocols/awareness";
|
|
3
|
+
import * as Y from "yjs";
|
|
4
|
+
import * as decoding from "lib0/decoding";
|
|
5
|
+
import * as encoding from "lib0/encoding";
|
|
6
|
+
import * as syncProtocol from "y-protocols/sync";
|
|
7
|
+
|
|
8
|
+
//#region packages/provider/src/webrtc/YjsDataChannel.ts
|
|
9
|
+
/**
|
|
10
|
+
* Handles Y.js document sync and awareness over WebRTC data channels.
|
|
11
|
+
*
|
|
12
|
+
* Uses the same y-protocols/sync encoding as the WebSocket provider but
|
|
13
|
+
* transported over RTCDataChannel instead. A unique origin is used to
|
|
14
|
+
* prevent echo loops with the server-based provider.
|
|
15
|
+
*/
|
|
16
|
+
var YjsDataChannel = class {
|
|
17
|
+
/**
|
|
18
|
+
* @param document - The Y.Doc to sync
|
|
19
|
+
* @param awareness - Optional Awareness instance
|
|
20
|
+
* @param router - DataChannelRouter for the peer connection
|
|
21
|
+
* @param channelPrefix - Optional prefix for subdocument channels (e.g. `"{childId}:"`)
|
|
22
|
+
*/
|
|
23
|
+
constructor(document, awareness, router, channelPrefix) {
|
|
24
|
+
this.document = document;
|
|
25
|
+
this.awareness = awareness;
|
|
26
|
+
this.router = router;
|
|
27
|
+
this.isSynced = false;
|
|
28
|
+
this.docUpdateHandler = null;
|
|
29
|
+
this.awarenessUpdateHandler = null;
|
|
30
|
+
this.channelOpenHandler = null;
|
|
31
|
+
this.channelMessageHandler = null;
|
|
32
|
+
const prefix = channelPrefix ?? "";
|
|
33
|
+
this.syncChannelName = `${prefix}${CHANNEL_NAMES.YJS_SYNC}`;
|
|
34
|
+
this.awarenessChannelName = `${prefix}${CHANNEL_NAMES.AWARENESS}`;
|
|
35
|
+
}
|
|
36
|
+
/** Start listening for Y.js updates and data channel messages. */
|
|
37
|
+
attach() {
|
|
38
|
+
this.docUpdateHandler = (update, origin) => {
|
|
39
|
+
if (origin === this) return;
|
|
40
|
+
if (!this.router.isOpen(this.syncChannelName)) return;
|
|
41
|
+
const encoder = encoding.createEncoder();
|
|
42
|
+
encoding.writeVarUint(encoder, YJS_MSG.UPDATE);
|
|
43
|
+
encoding.writeVarUint8Array(encoder, update);
|
|
44
|
+
this.router.send(this.syncChannelName, encoding.toUint8Array(encoder));
|
|
45
|
+
};
|
|
46
|
+
this.document.on("update", this.docUpdateHandler);
|
|
47
|
+
if (this.awareness) {
|
|
48
|
+
this.awarenessUpdateHandler = ({ added, updated, removed }, _origin) => {
|
|
49
|
+
if (!this.router.isOpen(this.awarenessChannelName)) return;
|
|
50
|
+
const changedClients = added.concat(updated).concat(removed);
|
|
51
|
+
const update = encodeAwarenessUpdate(this.awareness, changedClients);
|
|
52
|
+
this.router.send(this.awarenessChannelName, update);
|
|
53
|
+
};
|
|
54
|
+
this.awareness.on("update", this.awarenessUpdateHandler);
|
|
55
|
+
}
|
|
56
|
+
this.channelMessageHandler = ({ name, data }) => {
|
|
57
|
+
if (name === this.syncChannelName) this.handleSyncMessage(data);
|
|
58
|
+
else if (name === this.awarenessChannelName) this.handleAwarenessMessage(data);
|
|
59
|
+
};
|
|
60
|
+
this.router.on("channelMessage", this.channelMessageHandler);
|
|
61
|
+
this.channelOpenHandler = ({ name }) => {
|
|
62
|
+
if (name === this.syncChannelName) this.sendSyncStep1();
|
|
63
|
+
else if (name === this.awarenessChannelName && this.awareness) {
|
|
64
|
+
if (this.router.isOpen(this.awarenessChannelName)) {
|
|
65
|
+
const update = encodeAwarenessUpdate(this.awareness, Array.from(this.awareness.getStates().keys()));
|
|
66
|
+
this.router.send(this.awarenessChannelName, update);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
};
|
|
70
|
+
this.router.on("channelOpen", this.channelOpenHandler);
|
|
71
|
+
if (this.router.isOpen(this.syncChannelName)) this.sendSyncStep1();
|
|
72
|
+
if (this.awareness && this.router.isOpen(this.awarenessChannelName)) {
|
|
73
|
+
const update = encodeAwarenessUpdate(this.awareness, Array.from(this.awareness.getStates().keys()));
|
|
74
|
+
this.router.send(this.awarenessChannelName, update);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
/** Stop listening and clean up handlers. */
|
|
78
|
+
detach() {
|
|
79
|
+
if (this.docUpdateHandler) {
|
|
80
|
+
this.document.off("update", this.docUpdateHandler);
|
|
81
|
+
this.docUpdateHandler = null;
|
|
82
|
+
}
|
|
83
|
+
if (this.awarenessUpdateHandler && this.awareness) {
|
|
84
|
+
this.awareness.off("update", this.awarenessUpdateHandler);
|
|
85
|
+
this.awarenessUpdateHandler = null;
|
|
86
|
+
}
|
|
87
|
+
if (this.channelMessageHandler) {
|
|
88
|
+
this.router.off("channelMessage", this.channelMessageHandler);
|
|
89
|
+
this.channelMessageHandler = null;
|
|
90
|
+
}
|
|
91
|
+
if (this.channelOpenHandler) {
|
|
92
|
+
this.router.off("channelOpen", this.channelOpenHandler);
|
|
93
|
+
this.channelOpenHandler = null;
|
|
94
|
+
}
|
|
95
|
+
this.isSynced = false;
|
|
96
|
+
}
|
|
97
|
+
destroy() {
|
|
98
|
+
this.detach();
|
|
99
|
+
}
|
|
100
|
+
sendSyncStep1() {
|
|
101
|
+
if (!this.router.isOpen(this.syncChannelName)) return;
|
|
102
|
+
const encoder = encoding.createEncoder();
|
|
103
|
+
encoding.writeVarUint(encoder, YJS_MSG.SYNC);
|
|
104
|
+
syncProtocol.writeSyncStep1(encoder, this.document);
|
|
105
|
+
this.router.send(this.syncChannelName, encoding.toUint8Array(encoder));
|
|
106
|
+
}
|
|
107
|
+
handleSyncMessage(data) {
|
|
108
|
+
const buf = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
|
|
109
|
+
const decoder = decoding.createDecoder(buf);
|
|
110
|
+
const msgType = decoding.readVarUint(decoder);
|
|
111
|
+
if (msgType === YJS_MSG.SYNC) {
|
|
112
|
+
const encoder = encoding.createEncoder();
|
|
113
|
+
const syncMessageType = syncProtocol.readSyncMessage(decoder, encoder, this.document, this);
|
|
114
|
+
if (encoding.length(encoder) > 0) {
|
|
115
|
+
const responseEncoder = encoding.createEncoder();
|
|
116
|
+
encoding.writeVarUint(responseEncoder, YJS_MSG.SYNC);
|
|
117
|
+
encoding.writeUint8Array(responseEncoder, encoding.toUint8Array(encoder));
|
|
118
|
+
if (this.router.isOpen(this.syncChannelName)) this.router.send(this.syncChannelName, encoding.toUint8Array(responseEncoder));
|
|
119
|
+
}
|
|
120
|
+
if (syncMessageType === syncProtocol.messageYjsSyncStep2) this.isSynced = true;
|
|
121
|
+
} else if (msgType === YJS_MSG.UPDATE) {
|
|
122
|
+
const update = decoding.readVarUint8Array(decoder);
|
|
123
|
+
Y.applyUpdate(this.document, update, this);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
handleAwarenessMessage(data) {
|
|
127
|
+
if (!this.awareness) return;
|
|
128
|
+
const buf = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
|
|
129
|
+
applyAwarenessUpdate(this.awareness, buf, this);
|
|
130
|
+
}
|
|
131
|
+
};
|
|
132
|
+
|
|
133
|
+
//#endregion
|
|
134
|
+
export { YjsDataChannel };
|
|
135
|
+
//# sourceMappingURL=YjsDataChannel.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"YjsDataChannel.js","names":[],"sources":["../../../src/webrtc/YjsDataChannel.ts"],"sourcesContent":["import * as Y from \"yjs\";\nimport * as syncProtocol from \"y-protocols/sync\";\nimport {\n\tencodeAwarenessUpdate,\n\tapplyAwarenessUpdate,\n\ttype Awareness,\n} from \"y-protocols/awareness\";\nimport * as encoding from \"lib0/encoding\";\nimport * as decoding from \"lib0/decoding\";\nimport type { DataChannelRouter } from \"./DataChannelRouter.ts\";\nimport { CHANNEL_NAMES, YJS_MSG } from \"./types.ts\";\n\n/**\n * Handles Y.js document sync and awareness over WebRTC data channels.\n *\n * Uses the same y-protocols/sync encoding as the WebSocket provider but\n * transported over RTCDataChannel instead. A unique origin is used to\n * prevent echo loops with the server-based provider.\n */\nexport class YjsDataChannel {\n\tpublic isSynced = false;\n\tprivate docUpdateHandler: ((update: Uint8Array, origin: any) => void) | null = null;\n\tprivate awarenessUpdateHandler: ((changes: { added: number[]; updated: number[]; removed: number[] }, origin: any) => void) | null = null;\n\tprivate channelOpenHandler: ((data: { name: string; channel: RTCDataChannel }) => void) | null = null;\n\tprivate channelMessageHandler: ((data: { name: string; data: any }) => void) | null = null;\n\n\t/** Channel names used for sync and awareness (supports namespaced subdoc channels). */\n\tprivate readonly syncChannelName: string;\n\tprivate readonly awarenessChannelName: string;\n\n\t/**\n\t * @param document - The Y.Doc to sync\n\t * @param awareness - Optional Awareness instance\n\t * @param router - DataChannelRouter for the peer connection\n\t * @param channelPrefix - Optional prefix for subdocument channels (e.g. `\"{childId}:\"`)\n\t */\n\tconstructor(\n\t\tprivate readonly document: Y.Doc,\n\t\tprivate readonly awareness: Awareness | null,\n\t\tprivate readonly router: DataChannelRouter,\n\t\tchannelPrefix?: string,\n\t) {\n\t\tconst prefix = channelPrefix ?? \"\";\n\t\tthis.syncChannelName = `${prefix}${CHANNEL_NAMES.YJS_SYNC}`;\n\t\tthis.awarenessChannelName = `${prefix}${CHANNEL_NAMES.AWARENESS}`;\n\t}\n\n\t/** Start listening for Y.js updates and data channel messages. */\n\tattach(): void {\n\t\t// Listen for local doc updates and send to peer.\n\t\tthis.docUpdateHandler = (update: Uint8Array, origin: any) => {\n\t\t\t// Don't echo updates we received from this data channel.\n\t\t\tif (origin === this) return;\n\n\t\t\tif (!this.router.isOpen(this.syncChannelName)) return;\n\n\t\t\tconst encoder = encoding.createEncoder();\n\t\t\tencoding.writeVarUint(encoder, YJS_MSG.UPDATE);\n\t\t\tencoding.writeVarUint8Array(encoder, update);\n\t\t\tthis.router.send(this.syncChannelName, encoding.toUint8Array(encoder));\n\t\t};\n\t\tthis.document.on(\"update\", this.docUpdateHandler);\n\n\t\t// Listen for local awareness updates and send to peer.\n\t\tif (this.awareness) {\n\t\t\tthis.awarenessUpdateHandler = (\n\t\t\t\t{ added, updated, removed }: { added: number[]; updated: number[]; removed: number[] },\n\t\t\t\t_origin: any,\n\t\t\t) => {\n\t\t\t\tif (!this.router.isOpen(this.awarenessChannelName)) return;\n\n\t\t\t\tconst changedClients = added.concat(updated).concat(removed);\n\t\t\t\tconst update = encodeAwarenessUpdate(this.awareness!, changedClients);\n\t\t\t\tthis.router.send(this.awarenessChannelName, update);\n\t\t\t};\n\t\t\tthis.awareness.on(\"update\", this.awarenessUpdateHandler);\n\t\t}\n\n\t\t// Handle incoming data channel messages.\n\t\tthis.channelMessageHandler = ({ name, data }: { name: string; data: any }) => {\n\t\t\tif (name === this.syncChannelName) {\n\t\t\t\tthis.handleSyncMessage(data);\n\t\t\t} else if (name === this.awarenessChannelName) {\n\t\t\t\tthis.handleAwarenessMessage(data);\n\t\t\t}\n\t\t};\n\t\tthis.router.on(\"channelMessage\", this.channelMessageHandler);\n\n\t\t// When sync channel opens, initiate sync handshake.\n\t\tthis.channelOpenHandler = ({ name }: { name: string; channel: RTCDataChannel }) => {\n\t\t\tif (name === this.syncChannelName) {\n\t\t\t\tthis.sendSyncStep1();\n\t\t\t} else if (name === this.awarenessChannelName && this.awareness) {\n\t\t\t\t// Send full awareness state on channel open.\n\t\t\t\tif (this.router.isOpen(this.awarenessChannelName)) {\n\t\t\t\t\tconst update = encodeAwarenessUpdate(\n\t\t\t\t\t\tthis.awareness,\n\t\t\t\t\t\tArray.from(this.awareness.getStates().keys()),\n\t\t\t\t\t);\n\t\t\t\t\tthis.router.send(this.awarenessChannelName, update);\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\t\tthis.router.on(\"channelOpen\", this.channelOpenHandler);\n\n\t\t// If sync channel is already open, start sync immediately.\n\t\tif (this.router.isOpen(this.syncChannelName)) {\n\t\t\tthis.sendSyncStep1();\n\t\t}\n\n\t\t// If awareness channel is already open, send state immediately.\n\t\tif (this.awareness && this.router.isOpen(this.awarenessChannelName)) {\n\t\t\tconst update = encodeAwarenessUpdate(\n\t\t\t\tthis.awareness,\n\t\t\t\tArray.from(this.awareness.getStates().keys()),\n\t\t\t);\n\t\t\tthis.router.send(this.awarenessChannelName, update);\n\t\t}\n\t}\n\n\t/** Stop listening and clean up handlers. */\n\tdetach(): void {\n\t\tif (this.docUpdateHandler) {\n\t\t\tthis.document.off(\"update\", this.docUpdateHandler);\n\t\t\tthis.docUpdateHandler = null;\n\t\t}\n\n\t\tif (this.awarenessUpdateHandler && this.awareness) {\n\t\t\tthis.awareness.off(\"update\", this.awarenessUpdateHandler);\n\t\t\tthis.awarenessUpdateHandler = null;\n\t\t}\n\n\t\tif (this.channelMessageHandler) {\n\t\t\tthis.router.off(\"channelMessage\", this.channelMessageHandler);\n\t\t\tthis.channelMessageHandler = null;\n\t\t}\n\n\t\tif (this.channelOpenHandler) {\n\t\t\tthis.router.off(\"channelOpen\", this.channelOpenHandler);\n\t\t\tthis.channelOpenHandler = null;\n\t\t}\n\n\t\tthis.isSynced = false;\n\t}\n\n\tdestroy(): void {\n\t\tthis.detach();\n\t}\n\n\tprivate sendSyncStep1(): void {\n\t\tif (!this.router.isOpen(this.syncChannelName)) return;\n\n\t\tconst encoder = encoding.createEncoder();\n\t\tencoding.writeVarUint(encoder, YJS_MSG.SYNC);\n\t\tsyncProtocol.writeSyncStep1(encoder, this.document);\n\t\tthis.router.send(this.syncChannelName, encoding.toUint8Array(encoder));\n\t}\n\n\tprivate handleSyncMessage(data: ArrayBuffer | Uint8Array): void {\n\t\tconst buf = data instanceof ArrayBuffer ? new Uint8Array(data) : data;\n\t\tconst decoder = decoding.createDecoder(buf);\n\t\tconst msgType = decoding.readVarUint(decoder);\n\n\t\tif (msgType === YJS_MSG.SYNC) {\n\t\t\t// Standard y-protocols/sync message (SyncStep1, SyncStep2, or Update).\n\t\t\tconst encoder = encoding.createEncoder();\n\t\t\tconst syncMessageType = syncProtocol.readSyncMessage(\n\t\t\t\tdecoder,\n\t\t\t\tencoder,\n\t\t\t\tthis.document,\n\t\t\t\tthis,\n\t\t\t);\n\n\t\t\t// If the sync protocol generated a response (SyncStep2), send it.\n\t\t\tif (encoding.length(encoder) > 0) {\n\t\t\t\tconst responseEncoder = encoding.createEncoder();\n\t\t\t\tencoding.writeVarUint(responseEncoder, YJS_MSG.SYNC);\n\t\t\t\tencoding.writeUint8Array(\n\t\t\t\t\tresponseEncoder,\n\t\t\t\t\tencoding.toUint8Array(encoder),\n\t\t\t\t);\n\t\t\t\tif (this.router.isOpen(this.syncChannelName)) {\n\t\t\t\t\tthis.router.send(this.syncChannelName, encoding.toUint8Array(responseEncoder));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// SyncStep2 means initial sync is complete.\n\t\t\tif (syncMessageType === syncProtocol.messageYjsSyncStep2) {\n\t\t\t\tthis.isSynced = true;\n\t\t\t}\n\t\t} else if (msgType === YJS_MSG.UPDATE) {\n\t\t\t// Raw incremental update.\n\t\t\tconst update = decoding.readVarUint8Array(decoder);\n\t\t\tY.applyUpdate(this.document, update, this);\n\t\t}\n\t}\n\n\tprivate handleAwarenessMessage(data: ArrayBuffer | Uint8Array): void {\n\t\tif (!this.awareness) return;\n\t\tconst buf = data instanceof ArrayBuffer ? new Uint8Array(data) : data;\n\t\tapplyAwarenessUpdate(this.awareness, buf, this);\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;AAmBA,IAAa,iBAAb,MAA4B;;;;;;;CAiB3B,YACC,AAAiB,UACjB,AAAiB,WACjB,AAAiB,QACjB,eACC;EAJgB;EACA;EACA;kBAnBA;0BAC6D;gCACsD;4BACpC;+BACX;EAkBrF,MAAM,SAAS,iBAAiB;AAChC,OAAK,kBAAkB,GAAG,SAAS,cAAc;AACjD,OAAK,uBAAuB,GAAG,SAAS,cAAc;;;C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AGD,OAAI,SAAS,OAAO,QAAQ,GAAG,GAAG;IACjC,MAAM,kBAAkB,SAAS,eAAe;AAChD,aAAS,aAAa,iBAAiB,QAAQ,KAAK;AACpD,aAAS,gBACR,iBACA,SAAS,aAAa,QAAQ,CAC9B;AACD,QAAI,KAAK,OAAO,OAAO,KAAK,gBAAgB,CAC3C,MAAK,OAAO,KAAK,KAAK,iBAAiB,SAAS,aAAa,gBAAgB,CAAC;;AAKhF,OAAI,oBAAoB,aAAa,oBACpC,MAAK,WAAW;aAEP,YAAY,QAAQ,QAAQ;GAEtC,MAAM,SAAS,SAAS,kBAAkB,QAAQ;AAClD,KAAE,YAAY,KAAK,UAAU,QAAQ,KAAK;;;CAI5C,AAAQ,uBAAuB,MAAsC;AACpE,MAAI,CAAC,KAAK,UAAW;EACrB,MAAM,MAAM,gBAAgB,cAAc,IAAI,WAAW,KAAK,GAAG;AACjE,uBAAqB,KAAK,WAAW,KAAK,KAAK"}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
//#region packages/provider/src/webrtc/types.ts
|
|
2
|
+
/** Data channel file transfer message type discriminators (first byte). */
|
|
3
|
+
const FILE_MSG = {
|
|
4
|
+
START: 1,
|
|
5
|
+
CHUNK: 2,
|
|
6
|
+
COMPLETE: 3,
|
|
7
|
+
CANCEL: 4
|
|
8
|
+
};
|
|
9
|
+
/** Data channel Y.js message type discriminators (first byte). */
|
|
10
|
+
const YJS_MSG = {
|
|
11
|
+
SYNC: 0,
|
|
12
|
+
UPDATE: 1
|
|
13
|
+
};
|
|
14
|
+
const CHANNEL_NAMES = {
|
|
15
|
+
YJS_SYNC: "yjs-sync",
|
|
16
|
+
AWARENESS: "awareness",
|
|
17
|
+
FILE_TRANSFER: "file-transfer",
|
|
18
|
+
CUSTOM: "custom"
|
|
19
|
+
};
|
|
20
|
+
const DEFAULT_ICE_SERVERS = [{ urls: "stun:stun.l.google.com:19302" }];
|
|
21
|
+
const DEFAULT_FILE_CHUNK_SIZE = 16384;
|
|
22
|
+
/** UUID v4 transfer ID length when encoded as raw bytes. */
|
|
23
|
+
const TRANSFER_ID_BYTES = 16;
|
|
24
|
+
/** SHA-256 hash length in bytes. */
|
|
25
|
+
const SHA256_BYTES = 32;
|
|
26
|
+
|
|
27
|
+
//#endregion
|
|
28
|
+
export { CHANNEL_NAMES, DEFAULT_FILE_CHUNK_SIZE, DEFAULT_ICE_SERVERS, FILE_MSG, SHA256_BYTES, TRANSFER_ID_BYTES, YJS_MSG };
|
|
29
|
+
//# sourceMappingURL=types.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.js","names":[],"sources":["../../../src/webrtc/types.ts"],"sourcesContent":["// ── Signaling Wire Protocol ─────────────────────────────────────────────────\n// Mirrors the Rust server's Incoming/Outgoing enums in signaling.rs exactly.\n// All messages are JSON text frames with a \"type\" discriminator.\n\nexport type SignalingIncoming =\n\t| { type: \"join\" }\n\t| { type: \"leave\" }\n\t| { type: \"offer\"; to: string; sdp: string }\n\t| { type: \"answer\"; to: string; sdp: string }\n\t| { type: \"ice\"; to: string; candidate: string }\n\t| { type: \"mute\"; muted: boolean }\n\t| { type: \"media-state\"; video: boolean; screen: boolean }\n\t| { type: \"profile\"; name: string; color: string }\n\t| { type: \"pong\" };\n\nexport type SignalingOutgoing =\n\t| { type: \"welcome\"; peer_id: string; peers: PeerInfo[] }\n\t| {\n\t\t\ttype: \"joined\";\n\t\t\tpeer_id: string;\n\t\t\tuser_id: string;\n\t\t\tmuted: boolean;\n\t\t\tvideo: boolean;\n\t\t\tscreen: boolean;\n\t\t\tname: string | null;\n\t\t\tcolor: string | null;\n\t }\n\t| { type: \"left\"; peer_id: string }\n\t| { type: \"offer\"; from: string; sdp: string }\n\t| { type: \"answer\"; from: string; sdp: string }\n\t| { type: \"ice\"; from: string; candidate: string }\n\t| { type: \"mute\"; peer_id: string; muted: boolean }\n\t| {\n\t\t\ttype: \"media-state\";\n\t\t\tpeer_id: string;\n\t\t\tvideo: boolean;\n\t\t\tscreen: boolean;\n\t }\n\t| { type: \"profile\"; peer_id: string; name: string; color: string }\n\t| { type: \"ping\" }\n\t| { type: \"error\"; code: string; message: string };\n\n// ── Peer State ──────────────────────────────────────────────────────────────\n\nexport interface PeerInfo {\n\tpeer_id: string;\n\tuser_id: string;\n\tmuted: boolean;\n\tvideo: boolean;\n\tscreen: boolean;\n\tname: string | null;\n\tcolor: string | null;\n}\n\nexport interface PeerState extends PeerInfo {\n\tconnectionState: RTCPeerConnectionState | \"new\";\n}\n\n// ── File Transfer ───────────────────────────────────────────────────────────\n\nexport interface FileTransferMeta {\n\ttransferId: string;\n\tfilename: string;\n\tmimeType: string;\n\ttotalSize: number;\n\tchunkSize: number;\n\ttotalChunks: number;\n}\n\nexport type FileTransferStatus =\n\t| \"pending\"\n\t| \"sending\"\n\t| \"receiving\"\n\t| \"complete\"\n\t| \"cancelled\"\n\t| \"error\";\n\n/** Data channel file transfer message type discriminators (first byte). */\nexport const FILE_MSG = {\n\tSTART: 0x01,\n\tCHUNK: 0x02,\n\tCOMPLETE: 0x03,\n\tCANCEL: 0x04,\n} as const;\n\n/** Data channel Y.js message type discriminators (first byte). */\nexport const YJS_MSG = {\n\tSYNC: 0x00,\n\tUPDATE: 0x01,\n} as const;\n\n// ── Data Channel Names ──────────────────────────────────────────────────────\n\nexport const CHANNEL_NAMES = {\n\tYJS_SYNC: \"yjs-sync\",\n\tAWARENESS: \"awareness\",\n\tFILE_TRANSFER: \"file-transfer\",\n\tCUSTOM: \"custom\",\n} as const;\n\n// ── E2EE ────────────────────────────────────────────────────────────────────\n\nexport type { E2EEIdentity } from \"./E2EEChannel.ts\";\n\n// ── Configuration ───────────────────────────────────────────────────────────\n\nexport interface AbracadabraWebRTCConfiguration {\n\t/** Document ID for the signaling room. */\n\tdocId: string;\n\n\t/** Server base URL (http/https). Signaling URL derived automatically. */\n\turl: string;\n\n\t/**\n\t * Override the signaling WebSocket URL. When set, signaling connects to\n\t * this server instead of deriving from `url`. Useful for local spaces that\n\t * piggyback a remote server's signaling endpoint.\n\t */\n\tsignalingUrl?: string;\n\n\t/** JWT token or async token factory. */\n\ttoken: string | (() => string) | (() => Promise<string>);\n\n\t/** Optional Y.Doc to sync over data channels (hybrid mode). */\n\tdocument?: InstanceType<typeof import(\"yjs\").Doc> | null;\n\n\t/** Optional Awareness instance for presence sync over data channels. */\n\tawareness?: InstanceType<\n\t\ttypeof import(\"y-protocols/awareness\").Awareness\n\t> | null;\n\n\t/** ICE server configuration. Defaults to Google STUN. */\n\ticeServers?: RTCIceServer[];\n\n\t/** Display name for this peer. */\n\tdisplayName?: string;\n\n\t/** Color identifier for this peer. */\n\tcolor?: string;\n\n\t/** Enable Y.js document sync over data channels. Default: true when document is provided. */\n\tenableDocSync?: boolean;\n\n\t/** Enable awareness sync over data channels. Default: true when awareness is provided. */\n\tenableAwarenessSync?: boolean;\n\n\t/** Enable file transfer channel. Default: false. */\n\tenableFileTransfer?: boolean;\n\n\t/** Max file chunk size in bytes. Default: 16384 (16KB). */\n\tfileChunkSize?: number;\n\n\t/** Auto-connect on construction. Default: true. */\n\tautoConnect?: boolean;\n\n\t/**\n\t * E2EE identity for application-level encryption on data channels.\n\t * When provided, all data channel messages (except key-exchange) are\n\t * encrypted with AES-256-GCM using X25519 ECDH-derived session keys.\n\t */\n\te2ee?: import(\"./E2EEChannel.ts\").E2EEIdentity | (() => Promise<import(\"./E2EEChannel.ts\").E2EEIdentity>);\n\n\t/** WebSocket polyfill for signaling (e.g. for Node.js). */\n\tWebSocketPolyfill?: any;\n}\n\nexport const DEFAULT_ICE_SERVERS: RTCIceServer[] = [\n\t{ urls: \"stun:stun.l.google.com:19302\" },\n];\n\nexport const DEFAULT_FILE_CHUNK_SIZE = 16384; // 16KB\n\n/** UUID v4 transfer ID length when encoded as raw bytes. */\nexport const TRANSFER_ID_BYTES = 16;\n\n/** SHA-256 hash length in bytes. */\nexport const SHA256_BYTES = 32;\n"],"mappings":";;AA8EA,MAAa,WAAW;CACvB,OAAO;CACP,OAAO;CACP,UAAU;CACV,QAAQ;CACR;;AAGD,MAAa,UAAU;CACtB,MAAM;CACN,QAAQ;CACR;AAID,MAAa,gBAAgB;CAC5B,UAAU;CACV,WAAW;CACX,eAAe;CACf,QAAQ;CACR;AAoED,MAAa,sBAAsC,CAClD,EAAE,MAAM,gCAAgC,CACxC;AAED,MAAa,0BAA0B;;AAGvC,MAAa,oBAAoB;;AAGjC,MAAa,eAAe"}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { sha512 } from "@noble/hashes/sha2.js";
|
|
2
|
+
|
|
3
|
+
//#region packages/provider/src/x25519Convert.ts
|
|
4
|
+
/**
|
|
5
|
+
* Ed25519 → X25519 key conversion, without `@noble/curves`.
|
|
6
|
+
*
|
|
7
|
+
* `CryptoIdentityKeystore` is constructed on every boot, and its only uses of
|
|
8
|
+
* `@noble/curves` were `toMontgomery` / `toMontgomerySecret` — which put the
|
|
9
|
+
* whole Edwards/Montgomery/modular stack (~24 KB minified) on the critical
|
|
10
|
+
* path of every page that loads the SDK. Both conversions are one formula
|
|
11
|
+
* each, so they live here; anything that needs real X25519 ECDH
|
|
12
|
+
* (`DocKeyManager`, E2EE channels) still imports noble, off the boot path.
|
|
13
|
+
*
|
|
14
|
+
* - public: u = (1 + y) / (1 − y) mod p, p = 2^255 − 19 (RFC 7748 §4.1)
|
|
15
|
+
* - secret: the first 32 bytes of SHA-512(seed), clamped (RFC 8032 §5.1.5)
|
|
16
|
+
*
|
|
17
|
+
* Byte-for-byte equal to `ed25519.utils.toMontgomery` /
|
|
18
|
+
* `toMontgomerySecret`; `tests/x25519-convert.test.ts` asserts it against
|
|
19
|
+
* noble for random keys. BigInt via the constructor, not `1n` literals: the
|
|
20
|
+
* package's TypeScript target is ES2019.
|
|
21
|
+
*/
|
|
22
|
+
const ZERO = BigInt(0);
|
|
23
|
+
const ONE = BigInt(1);
|
|
24
|
+
const EIGHT = BigInt(8);
|
|
25
|
+
const P = (ONE << BigInt(255)) - BigInt(19);
|
|
26
|
+
function mod(a) {
|
|
27
|
+
const r = a % P;
|
|
28
|
+
return r >= ZERO ? r : r + P;
|
|
29
|
+
}
|
|
30
|
+
function powMod(base, exp) {
|
|
31
|
+
let result = ONE;
|
|
32
|
+
let b = mod(base);
|
|
33
|
+
let e = exp;
|
|
34
|
+
while (e > ZERO) {
|
|
35
|
+
if (e & ONE) result = result * b % P;
|
|
36
|
+
b = b * b % P;
|
|
37
|
+
e >>= ONE;
|
|
38
|
+
}
|
|
39
|
+
return result;
|
|
40
|
+
}
|
|
41
|
+
/** Ed25519 public key (32 bytes) → X25519 public key (32 bytes). */
|
|
42
|
+
function ed25519PublicToX25519(edPublicKey) {
|
|
43
|
+
if (edPublicKey.length !== 32) throw new Error("ed25519 public key must be 32 bytes");
|
|
44
|
+
let y = ZERO;
|
|
45
|
+
for (let i = 31; i >= 0; i--) {
|
|
46
|
+
const raw = edPublicKey[i] ?? 0;
|
|
47
|
+
const byte = i === 31 ? raw & 127 : raw;
|
|
48
|
+
y = y << EIGHT | BigInt(byte);
|
|
49
|
+
}
|
|
50
|
+
const u = mod((ONE + y) * powMod(ONE - y, P - BigInt(2)));
|
|
51
|
+
const out = new Uint8Array(32);
|
|
52
|
+
let v = u;
|
|
53
|
+
for (let i = 0; i < 32; i++) {
|
|
54
|
+
out[i] = Number(v & BigInt(255));
|
|
55
|
+
v >>= EIGHT;
|
|
56
|
+
}
|
|
57
|
+
return out;
|
|
58
|
+
}
|
|
59
|
+
/** Ed25519 seed (32 bytes) → X25519 private scalar (32 bytes, clamped). */
|
|
60
|
+
function ed25519SecretToX25519(seed) {
|
|
61
|
+
const scalar = sha512(seed.subarray(0, 32)).slice(0, 32);
|
|
62
|
+
scalar[0] = (scalar[0] ?? 0) & 248;
|
|
63
|
+
scalar[31] = (scalar[31] ?? 0) & 127 | 64;
|
|
64
|
+
return scalar;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
//#endregion
|
|
68
|
+
export { ed25519PublicToX25519, ed25519SecretToX25519 };
|
|
69
|
+
//# sourceMappingURL=x25519Convert.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"x25519Convert.js","names":[],"sources":["../../src/x25519Convert.ts"],"sourcesContent":["/**\n * Ed25519 → X25519 key conversion, without `@noble/curves`.\n *\n * `CryptoIdentityKeystore` is constructed on every boot, and its only uses of\n * `@noble/curves` were `toMontgomery` / `toMontgomerySecret` — which put the\n * whole Edwards/Montgomery/modular stack (~24 KB minified) on the critical\n * path of every page that loads the SDK. Both conversions are one formula\n * each, so they live here; anything that needs real X25519 ECDH\n * (`DocKeyManager`, E2EE channels) still imports noble, off the boot path.\n *\n * - public: u = (1 + y) / (1 − y) mod p, p = 2^255 − 19 (RFC 7748 §4.1)\n * - secret: the first 32 bytes of SHA-512(seed), clamped (RFC 8032 §5.1.5)\n *\n * Byte-for-byte equal to `ed25519.utils.toMontgomery` /\n * `toMontgomerySecret`; `tests/x25519-convert.test.ts` asserts it against\n * noble for random keys. BigInt via the constructor, not `1n` literals: the\n * package's TypeScript target is ES2019.\n */\nimport { sha512 } from \"@noble/hashes/sha2.js\";\n\nconst ZERO = BigInt(0);\nconst ONE = BigInt(1);\nconst EIGHT = BigInt(8);\nconst P = (ONE << BigInt(255)) - BigInt(19);\n\nfunction mod(a: bigint): bigint {\n\tconst r = a % P;\n\treturn r >= ZERO ? r : r + P;\n}\n\nfunction powMod(base: bigint, exp: bigint): bigint {\n\tlet result = ONE;\n\tlet b = mod(base);\n\tlet e = exp;\n\twhile (e > ZERO) {\n\t\tif (e & ONE) result = (result * b) % P;\n\t\tb = (b * b) % P;\n\t\te >>= ONE;\n\t}\n\treturn result;\n}\n\n/** Ed25519 public key (32 bytes) → X25519 public key (32 bytes). */\nexport function ed25519PublicToX25519(edPublicKey: Uint8Array): Uint8Array {\n\tif (edPublicKey.length !== 32) throw new Error(\"ed25519 public key must be 32 bytes\");\n\tlet y = ZERO;\n\tfor (let i = 31; i >= 0; i--) {\n\t\tconst raw = edPublicKey[i] ?? 0;\n\t\tconst byte = i === 31 ? raw & 0x7f : raw;\n\t\ty = (y << EIGHT) | BigInt(byte);\n\t}\n\tconst u = mod((ONE + y) * powMod(ONE - y, P - BigInt(2)));\n\tconst out = new Uint8Array(32);\n\tlet v = u;\n\tfor (let i = 0; i < 32; i++) {\n\t\tout[i] = Number(v & BigInt(0xff));\n\t\tv >>= EIGHT;\n\t}\n\treturn out;\n}\n\n/** Ed25519 seed (32 bytes) → X25519 private scalar (32 bytes, clamped). */\nexport function ed25519SecretToX25519(seed: Uint8Array): Uint8Array {\n\tconst scalar = sha512(seed.subarray(0, 32)).slice(0, 32);\n\tscalar[0] = (scalar[0] ?? 0) & 248;\n\tscalar[31] = ((scalar[31] ?? 0) & 127) | 64;\n\treturn scalar;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAoBA,MAAM,OAAO,OAAO,EAAE;AACtB,MAAM,MAAM,OAAO,EAAE;AACrB,MAAM,QAAQ,OAAO,EAAE;AACvB,MAAM,KAAK,OAAO,OAAO,IAAI,IAAI,OAAO,GAAG;AAE3C,SAAS,IAAI,GAAmB;CAC/B,MAAM,IAAI,IAAI;AACd,QAAO,KAAK,OAAO,IAAI,IAAI;;AAG5B,SAAS,OAAO,MAAc,KAAqB;CAClD,IAAI,SAAS;CACb,IAAI,IAAI,IAAI,KAAK;CACjB,IAAI,IAAI;AACR,QAAO,IAAI,MAAM;AAChB,MAAI,IAAI,IAAK,UAAU,SAAS,IAAK;AACrC,MAAK,IAAI,IAAK;AACd,QAAM;;AAEP,QAAO;;;AAIR,SAAgB,sBAAsB,aAAqC;AAC1E,KAAI,YAAY,WAAW,GAAI,OAAM,IAAI,MAAM,sCAAsC;CACrF,IAAI,IAAI;AACR,MAAK,IAAI,IAAI,IAAI,KAAK,GAAG,KAAK;EAC7B,MAAM,MAAM,YAAY,MAAM;EAC9B,MAAM,OAAO,MAAM,KAAK,MAAM,MAAO;AACrC,MAAK,KAAK,QAAS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