derec-library 0.1.0

Rust SDK for the DeRec protocol, including native and WebAssembly bindings.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
// SPDX-License-Identifier: Apache-2.0
// Copyright (c) 2026 DeRec Alliance. All rights reserved.

//! Higher-level WASM binding: [`DeRecProtocolWasm`].
//!
//! This module exposes the same high-level orchestrator as the native
//! [`crate::protocol::DeRecProtocol`] but wired to JS-side store and transport
//! objects so that TypeScript applications can use it without managing raw
//! message routing.
//!
//! # Usage (TypeScript)
//!
//! ```ts
//! import { init, ContactMode, DeRecProtocolBuilder, FlowKind, SenderKind } from "@derec-alliance/web";
//!
//! await init(); // web only; the nodejs package needs no initialisation
//!
//! const protocol = new DeRecProtocolBuilder(secretId)
//!   .withChannelStore(channelStore)
//!   .withShareStore(shareStore)
//!   .withSecretStore(secretStore)
//!   .withUserSecretStore(userSecretStore)
//!   .withStateStore(stateStore)
//!   .withTransport(transport)
//!   .withOwnTransports([{ uri: "https://my-node.example.com/derec", protocol: "https" }])
//!   .build();
//!
//! // Responder: mint a contact message and hand it to the peer out of band.
//! const contact = await protocol.createContact(null, ContactMode.InlineKeys);
//!
//! // Initiator: begin pairing from the peer's contact message.
//! await protocol.start(FlowKind.Pairing, { kind: SenderKind.Owner, contact: peerContact });
//!
//! // Feed incoming wire bytes; react to returned events.
//! const events = await protocol.process(rawBytes);
//! for (const ev of events) {
//!   if (ev.type === "PairingCompleted") { ... }
//! }
//! ```
//!
//! The store and transport interfaces and every event shape are declared in
//! the package's `index.d.ts`.

mod events;

pub(super) use crate::interop::protocol_names::{
    protocol_discriminant_to_name, protocol_name_to_discriminant,
};

// `pending_action_wire` lives in `crate::protocol::utils` so both WASM
// and FFI bridges can share the same on-the-wire encoding for the opaque
// PendingAction blob.
pub(crate) use crate::protocol::utils::pending_action_wire;
mod stores;

use std::collections::HashMap;

use crate::interop::protocol_names::unpair_ack_from_name;
use crate::interop::recovered_secret;
use crate::interop::strict_json::object_into;
use crate::interop::wasm::primitives::pairing::ContactMessage as PairingContactMessage;
use crate::protocol_version::ProtocolVersion;
use crate::{
    interop::wasm::ts_bindings_utils::{js_error, js_error_from_lib},
    protocol::{
        AutoAcceptPolicy, DeRecFlow, DeRecProtocol, DeRecProtocolBuilder, DeRecProtocolConfig,
        TimeoutsConfig,
        types::{Secret, Target, UserSecret},
    },
    transport,
    types::{ChannelId, WeightedChannel},
};
use derec_proto::{
    ContactMessage, ContactMode, ParameterRange, SenderKind, StatusEnum, TransportProtocol,
};
use js_sys::{Array, BigInt, Map, Reflect};
use serde::de::DeserializeOwned;
use serde_wasm_bindgen::Serializer;
use stores::{
    JsChannelStore, JsSecretStore, JsShareStore, JsStateStore, JsTransport, JsUserSecretStore,
};
use tokio::sync::Mutex;
use wasm_bindgen::prelude::*;

type WasmProtocol = DeRecProtocol<
    JsChannelStore,
    JsShareStore,
    JsSecretStore,
    JsUserSecretStore,
    JsStateStore,
    JsTransport,
>;

/// Higher-level DeRec protocol orchestrator for TypeScript/JavaScript consumers.
///
/// Wraps [`crate::protocol::DeRecProtocol`] with JS-side store
/// and transport adapters so that a TypeScript application can drive every
/// protocol flow without routing raw bytes manually. Built with
/// [`DeRecProtocolBuilderWasm`] (`DeRecProtocolBuilder` in JS).
///
/// # Stores
///
/// The five stores and the transport are JS objects implementing the
/// `ChannelStore`, `ShareStore`, `SecretStore`, `UserSecretStore`,
/// `StateStore` and `Transport` interfaces in `index.d.ts`. All their methods
/// must return `Promise`s — synchronous implementations can wrap their result
/// with `Promise.resolve(...)`.
///
/// # Concurrency
///
/// Every method that touches protocol state is `async` and runs under one
/// lock per instance, so overlapping calls on the same instance — a
/// `tick` timer firing while `process` handles an inbound message — queue
/// and run one at a time, in the order they were made. Distinct instances
/// do not share the lock: two instances bound to the same `secret_id` and
/// the same stores must still be serialized by the caller.
///
/// A store or transport callback must not await a call on the instance
/// that invoked it: that call queues behind the one waiting on the
/// callback, and neither settles. Calling `free()` while a call is in
/// flight throws.
///
/// Methods take `&self` for this reason: wasm-bindgen holds the borrow of
/// the instance for an async call's whole lifetime, so under `&mut self` an
/// overlapping call fails that borrow outside its promise and never
/// settles.
///
/// # Events
///
/// [`process`](DeRecProtocolWasm::process), [`start`](DeRecProtocolWasm::start),
/// [`accept`](DeRecProtocolWasm::accept), [`tick`](DeRecProtocolWasm::tick)
/// and [`restore`](DeRecProtocolWasm::restore) return an `Array` of plain JS
/// objects, one per [`crate::protocol::DeRecEvent`], each tagged by a `type`
/// field naming the variant. Every `u64` identifier (`channel_id`,
/// `secret_id`, `replica_id`, `trace_id`) is a decimal string. The full set of
/// shapes is the `DeRecEvent` union in `index.d.ts`.
#[wasm_bindgen]
pub struct DeRecProtocolWasm {
    inner: Mutex<WasmProtocol>,
    secret_id: u64,
}

/// `value` read strictly as `T`: it must be a plain object, and a key `T`
/// does not define, at any level, is an error. The object goes through a
/// [`serde_json::Value`] first because that keeps every key it carries;
/// reading the `JsValue` as `T` directly sees only the keys `T` names.
fn js_object_into<T: DeserializeOwned>(value: JsValue) -> Result<T, String> {
    let json: serde_json::Value =
        serde_wasm_bindgen::from_value(value).map_err(|e| e.to_string())?;
    object_into(json)
}

/// Fluent builder for [`DeRecProtocolWasm`]. Mirrors the Rust
/// [`crate::protocol::DeRecProtocolBuilder`] and the dotnet
/// `DeRecProtocolBuilder` method-for-method so a developer who already
/// knows one SDK can move between them without reaching for reference
/// docs.
///
/// Required setters: `withChannelStore`, `withShareStore`,
/// `withSecretStore`, `withUserSecretStore`, `withStateStore`, and
/// `withTransport`. Calling `build()` without all six throws. Own transports
/// come from `withOwnTransports` or a config applied with `withConfig`;
/// `build()` fails with `InvalidInput` if none are set.
///
/// An optional setter that is never called leaves the Rust builder's default
/// in force: the value is forwarded only when the application supplied one.
#[wasm_bindgen(js_name = DeRecProtocolBuilder)]
pub struct DeRecProtocolBuilderWasm {
    secret_id: u64,
    channel_store: Option<JsValue>,
    share_store: Option<JsValue>,
    secret_store: Option<JsValue>,
    user_secret_store: Option<JsValue>,
    state_store: Option<JsValue>,
    transport: Option<JsValue>,
    /// Every data setting made so far, by the per-option setters and by
    /// `withConfig`, applied with [`DeRecProtocolBuilder::with_config`] at
    /// `build()`.
    config: DeRecProtocolConfig,
}

#[wasm_bindgen(js_class = DeRecProtocolBuilder)]
impl DeRecProtocolBuilderWasm {
    /// `secretId` is a JS `bigint` or `number`. Identifies the single
    /// secret this protocol instance manages; apps that juggle multiple
    /// secrets instantiate one protocol per id.
    #[wasm_bindgen(constructor)]
    pub fn new(secret_id: JsValue) -> Result<DeRecProtocolBuilderWasm, JsValue> {
        let secret_id = js_value_to_u64(secret_id)
            .map_err(|e| js_error("invalid_secret_id", format!("{e:?}")))?;
        Ok(DeRecProtocolBuilderWasm {
            secret_id,
            channel_store: None,
            share_store: None,
            secret_store: None,
            user_secret_store: None,
            state_store: None,
            transport: None,
            config: DeRecProtocolConfig::default(),
        })
    }

    #[wasm_bindgen(js_name = withChannelStore)]
    pub fn with_channel_store(mut self, store: JsValue) -> DeRecProtocolBuilderWasm {
        self.channel_store = Some(store);
        self
    }

    #[wasm_bindgen(js_name = withShareStore)]
    pub fn with_share_store(mut self, store: JsValue) -> DeRecProtocolBuilderWasm {
        self.share_store = Some(store);
        self
    }

    #[wasm_bindgen(js_name = withSecretStore)]
    pub fn with_secret_store(mut self, store: JsValue) -> DeRecProtocolBuilderWasm {
        self.secret_store = Some(store);
        self
    }

    #[wasm_bindgen(js_name = withUserSecretStore)]
    pub fn with_user_secret_store(mut self, store: JsValue) -> DeRecProtocolBuilderWasm {
        self.user_secret_store = Some(store);
        self
    }

    #[wasm_bindgen(js_name = withStateStore)]
    pub fn with_state_store(mut self, store: JsValue) -> DeRecProtocolBuilderWasm {
        self.state_store = Some(store);
        self
    }

    /// Set every store in one call. `stores` is `{ channelStore, shareStore,
    /// secretStore, userSecretStore, stateStore }`. Forwards to the five
    /// per-store setters above, so calling one of them again afterwards
    /// replaces just that store.
    #[wasm_bindgen(js_name = withStores)]
    pub fn with_stores(mut self, stores: JsValue) -> Result<DeRecProtocolBuilderWasm, JsValue> {
        // `Reflect::get` returns `undefined` for an absent key rather than
        // erroring, so a missing or explicit `null`/`undefined` store must
        // be rejected here with the same message `build()` gives an unset
        // store — otherwise it is stored as `Some(undefined)` and survives
        // to construct a store wrapper over a value that isn't one.
        let get = |key: &str, setter_name: &str| -> Result<JsValue, JsValue> {
            let value = Reflect::get(&stores, &JsValue::from_str(key))
                .map_err(|e| js_error("decode_error", format!("missing {key}: {e:?}")))?;
            if value.is_undefined() || value.is_null() {
                return Err(js_error(
                    "builder_missing",
                    format!("{setter_name} is required"),
                ));
            }
            Ok(value)
        };
        self.channel_store = Some(get("channelStore", "withChannelStore")?);
        self.share_store = Some(get("shareStore", "withShareStore")?);
        self.secret_store = Some(get("secretStore", "withSecretStore")?);
        self.user_secret_store = Some(get("userSecretStore", "withUserSecretStore")?);
        self.state_store = Some(get("stateStore", "withStateStore")?);
        Ok(self)
    }

    #[wasm_bindgen(js_name = withTransport)]
    pub fn with_transport(mut self, transport: JsValue) -> DeRecProtocolBuilderWasm {
        self.transport = Some(transport);
        self
    }

    /// Every transport endpoint this application serves, in preference
    /// order. `transports` is an array of `{ uri: string, protocol: string
    /// }` objects, `protocol` being `"https"` or `"grpc"`
    /// (case-insensitive).
    ///
    /// The order is the application's own preference and decides which of
    /// a peer's offered endpoints is used. Every listed transport must
    /// actually be served, because delivery is push-only — listing an
    /// endpoint this application does not serve makes pairing succeed and
    /// replies vanish.
    #[wasm_bindgen(js_name = withOwnTransports)]
    pub fn with_own_transports(
        mut self,
        transports: Vec<JsValue>,
    ) -> Result<DeRecProtocolBuilderWasm, JsValue> {
        #[derive(serde::Deserialize)]
        struct EndpointShape {
            uri: String,
            protocol: String,
        }
        let mut parsed_transports = Vec::with_capacity(transports.len());
        for endpoint in transports {
            let parsed: EndpointShape = serde_wasm_bindgen::from_value(endpoint)
                .map_err(|e| js_error("invalid_own_transport", e.to_string()))?;
            let protocol_num =
                protocol_name_to_discriminant(&parsed.protocol).ok_or_else(|| {
                    js_error(
                        "invalid_protocol",
                        format!("unknown protocol: {}", parsed.protocol.to_lowercase()),
                    )
                })?;
            let proto_tp = TransportProtocol {
                uri: parsed.uri,
                protocol: protocol_num,
            };
            // Structural + scheme/protocol validation, run per entry, order
            // preserved verbatim — it is the application's preference.
            let tp = transport::TransportProtocol::try_from(&proto_tp)
                .map_err(|e| js_error("invalid_own_transport", e.to_string()))?;
            parsed_transports.push(tp);
        }
        self.config.own_transports = Some(parsed_transports);
        Ok(self)
    }

    /// Minimum number of shares required to reconstruct the secret.
    /// Default: [`crate::protocol::DEFAULT_THRESHOLD`]. `threshold` must be an
    /// integer in `0..=u32::MAX`.
    #[wasm_bindgen(js_name = withThreshold)]
    pub fn with_threshold(
        mut self,
        threshold: JsValue,
    ) -> Result<DeRecProtocolBuilderWasm, JsValue> {
        self.config.threshold = Some(js_number_to_u32(&threshold, "threshold")? as usize);
        Ok(self)
    }

    /// Accept plaintext transport endpoints — `http://` and `grpc://`.
    /// **Development only.** Default `false`.
    ///
    /// With it `false`, plaintext is accepted only for an endpoint this
    /// device configured for *itself* that names loopback (`localhost`,
    /// `127.0.0.1`, `::1`) — so a local dev server needs no configuration.
    /// With it `true`, plaintext is accepted for any host on any path,
    /// including endpoints a peer supplies. That is what makes the LAN case
    /// work (a phone against a laptop), and why the name is blunt.
    #[wasm_bindgen(js_name = withUnsafeConnection)]
    pub fn with_unsafe_connection(mut self, allow: bool) -> DeRecProtocolBuilderWasm {
        self.config.unsafe_connection = Some(allow);
        self
    }

    /// Configure the four waiting periods in one call.
    ///
    /// Object shape — every field optional, and **absent means "keep the
    /// library default"**:
    ///
    /// ```text
    /// {
    ///   inbound_message_secs?: number,   // staleness / replay window
    ///   sharing_round_secs?:   number,
    ///   unpair_ack_secs?:      number,
    ///   get_share_response_secs?: number, // recovery waits this long for each Helper
    ///   pairing_secs?:         number,   // how old a contact or pair request may be
    ///   expired_channels?:     { enabled: boolean, timeout_in_secs: number },
    /// }
    /// ```
    ///
    /// Values are forwarded verbatim; clamping and the meaning of a disabled
    /// `expired_channels` are library decisions, not this shim's. Not calling
    /// this leaves every default in force. A key outside this shape throws
    /// `invalid_timeouts` instead of being ignored.
    #[wasm_bindgen(js_name = withTimeouts)]
    pub fn with_timeouts(mut self, timeouts: JsValue) -> Result<DeRecProtocolBuilderWasm, JsValue> {
        let parsed: TimeoutsConfig =
            js_object_into(timeouts).map_err(|e| js_error("invalid_timeouts", e))?;
        self.config.timeouts = Some(parsed);
        Ok(self)
    }

    /// `info` shape: `Record<string, string>`. Default: empty.
    #[wasm_bindgen(js_name = withCommunicationInfo)]
    pub fn with_communication_info(
        mut self,
        info: JsValue,
    ) -> Result<DeRecProtocolBuilderWasm, JsValue> {
        let parsed: HashMap<String, String> = serde_wasm_bindgen::from_value(info)
            .map_err(|e| js_error("invalid_communication_info", e.to_string()))?;
        self.config.communication_info = Some(parsed);
        Ok(self)
    }

    /// Whether the protocol auto-replies on failed inbound processing.
    /// Default: false.
    #[wasm_bindgen(js_name = withAutoRespondOnFailure)]
    pub fn with_auto_respond_on_failure(mut self, enabled: bool) -> DeRecProtocolBuilderWasm {
        self.config.auto_respond_on_failure = Some(enabled);
        self
    }

    /// The oldest protocol version whose messages are still accepted; see
    /// [`crate::protocol::DeRecProtocolBuilder::with_min_protocol_version`].
    /// Default: 0.0.
    #[wasm_bindgen(js_name = withMinProtocolVersion)]
    pub fn with_min_protocol_version(mut self, major: u32, minor: u32) -> DeRecProtocolBuilderWasm {
        self.config.min_protocol_version = Some(ProtocolVersion { major, minor });
        self
    }

    /// `ack` is exactly `"required"` (default) or `"not_required"`, naming
    /// [`crate::protocol::UnpairAck::Required`] and
    /// [`crate::protocol::UnpairAck::NotRequired`].
    #[wasm_bindgen(js_name = withUnpairAck)]
    pub fn with_unpair_ack(mut self, ack: String) -> Result<DeRecProtocolBuilderWasm, JsValue> {
        self.config.unpair_ack = Some(unpair_ack_from_name(&ack).ok_or_else(|| {
            js_error(
                "invalid_unpair_ack",
                format!(
                    "unknown unpair_ack value: {ack:?}; expected \"required\" or \"not_required\""
                ),
            )
        })?);
        Ok(self)
    }

    /// Whether outbound requests carry this node's own transports as their reply-to list.
    /// Default: false.
    #[wasm_bindgen(js_name = withAutoReplyTo)]
    pub fn with_auto_reply_to(mut self, enabled: bool) -> DeRecProtocolBuilderWasm {
        self.config.auto_reply_to = Some(enabled);
        self
    }

    /// Per-flow auto-accept policy.
    ///
    /// `policy` shape (all fields optional, default `false`):
    /// `{ pairing, prePair, storeShare, verifyShare, discovery, getShare, unpair, updateChannelInfo }`.
    ///
    /// When a field is `true`, `process()` internally accepts the
    /// matching incoming request and emits an `AutoAccepted` event in
    /// place of `ActionRequired`. See the Rust-side
    /// `AutoAcceptPolicy` rustdoc for the per-flow trade-offs.
    /// Default: every field `false`.
    #[wasm_bindgen(js_name = withAutoAccept)]
    pub fn with_auto_accept(
        mut self,
        policy: JsValue,
    ) -> Result<DeRecProtocolBuilderWasm, JsValue> {
        #[derive(serde::Deserialize, Default)]
        #[serde(rename_all = "camelCase", default)]
        struct AutoAcceptPolicyShape {
            pairing: bool,
            pre_pair: bool,
            store_share: bool,
            verify_share: bool,
            discovery: bool,
            get_share: bool,
            unpair: bool,
            update_channel_info: bool,
        }
        let parsed: AutoAcceptPolicyShape = serde_wasm_bindgen::from_value(policy)
            .map_err(|e| js_error("invalid_auto_accept_policy", e.to_string()))?;
        self.config.auto_accept = Some(AutoAcceptPolicy {
            pairing: parsed.pairing,
            pre_pair: parsed.pre_pair,
            store_share: parsed.store_share,
            verify_share: parsed.verify_share,
            discovery: parsed.discovery,
            get_share: parsed.get_share,
            unpair: parsed.unpair,
            update_channel_info: parsed.update_channel_info,
        });
        Ok(self)
    }

    /// `id` is a JS `bigint` or `number`. Default: unset.
    #[wasm_bindgen(js_name = withReplicaId)]
    pub fn with_replica_id(mut self, id: JsValue) -> Result<DeRecProtocolBuilderWasm, JsValue> {
        let v =
            js_value_to_u64(id).map_err(|e| js_error("invalid_replica_id", format!("{e:?}")))?;
        self.config.replica_id = Some(v);
        Ok(self)
    }

    /// Declare the local node's acceptable parameter range for pair
    /// negotiation. `range` is a JS object whose keys match the
    /// `ParameterRange` interface every binding already declares —
    /// `min_share_size`, `max_share_size`, `min_time_between_verifications`,
    /// … — so one shape serves the wasm and FFI paths alike. Each field is
    /// `i64`: accept either a number or a `BigInt` on the JS side. Every
    /// field is optional and defaults to `0`, which the proto reads as no
    /// constraint on that dimension. Default: unset (no constraints
    /// advertised, every peer range accepted).
    #[wasm_bindgen(js_name = withParameterRange)]
    pub fn with_parameter_range(
        mut self,
        range: JsValue,
    ) -> Result<DeRecProtocolBuilderWasm, JsValue> {
        #[derive(serde::Deserialize)]
        struct In {
            #[serde(default)]
            min_share_size: i64,
            #[serde(default)]
            max_share_size: i64,
            #[serde(default)]
            min_time_between_verifications: i64,
            #[serde(default)]
            max_time_between_verifications: i64,
            #[serde(default)]
            min_time_between_share_updates: i64,
            #[serde(default)]
            max_time_between_share_updates: i64,
            #[serde(default)]
            min_unresponsive_deletion_timeout: i64,
            #[serde(default)]
            max_unresponsive_deletion_timeout: i64,
            #[serde(default)]
            min_unresponsive_deactivation_timeout: i64,
            #[serde(default)]
            max_unresponsive_deactivation_timeout: i64,
        }
        let parsed: In = serde_wasm_bindgen::from_value(range)
            .map_err(|e| js_error("invalid_parameter_range", e.to_string()))?;
        self.config.parameter_range = Some(ParameterRange {
            min_share_size: parsed.min_share_size,
            max_share_size: parsed.max_share_size,
            min_time_between_verifications: parsed.min_time_between_verifications,
            max_time_between_verifications: parsed.max_time_between_verifications,
            min_time_between_share_updates: parsed.min_time_between_share_updates,
            max_time_between_share_updates: parsed.max_time_between_share_updates,
            min_unresponsive_deletion_timeout: parsed.min_unresponsive_deletion_timeout,
            max_unresponsive_deletion_timeout: parsed.max_unresponsive_deletion_timeout,
            min_unresponsive_deactivation_timeout: parsed.min_unresponsive_deactivation_timeout,
            max_unresponsive_deactivation_timeout: parsed.max_unresponsive_deactivation_timeout,
        });
        Ok(self)
    }

    /// Cap the total number of subshares one sharing round may split the
    /// secret into (the sum of every helper's weight). `max` is a JS
    /// `bigint`, `number` or decimal string. Default: unset, no cap.
    ///
    /// Checked only when a round is started; a round over the cap fails
    /// with `too_many_subshares` before anything is sent. Recovery applies
    /// no cap. Recovering costs time that grows quadratically with the
    /// total number of subshares, so the cap bounds what a later recovery
    /// must do. A cap below the threshold makes `build()` throw.
    #[wasm_bindgen(js_name = withMaxSubshares)]
    pub fn with_max_subshares(mut self, max: JsValue) -> Result<DeRecProtocolBuilderWasm, JsValue> {
        let v = js_value_to_u64(max)
            .map_err(|e| js_error("invalid_max_subshares", format!("{e:?}")))?;
        self.config.max_subshares = Some(v);
        Ok(self)
    }

    /// Apply a `DeRecProtocolConfig`: a plain object in the canonical
    /// `snake_case` JSON shape every SDK shares, for example one loaded from a
    /// config file or a user record.
    ///
    /// Only the keys present are applied, each as its own setter would: a
    /// later `withConfig` or setter call overwrites a value per field, and
    /// `timeouts` merges per field. A key the config does not define throws
    /// `decode_error` instead of being ignored. `replica_id` and
    /// `max_subshares` are decimal strings. Values are validated by `build()`,
    /// exactly as when set through their own setter.
    #[wasm_bindgen(js_name = withConfig)]
    pub fn with_config(mut self, config: JsValue) -> Result<DeRecProtocolBuilderWasm, JsValue> {
        let parsed: DeRecProtocolConfig = js_object_into(config)
            .map_err(|e| js_error("decode_error", format!("invalid config: {e}")))?;
        self.config.layer(parsed);
        Ok(self)
    }

    /// Finalize the configuration. Throws if any of the required
    /// setters was not called.
    pub fn build(self) -> Result<DeRecProtocolWasm, JsValue> {
        let channel_store = self
            .channel_store
            .ok_or_else(|| js_error("builder_missing", "withChannelStore is required"))?;
        let share_store = self
            .share_store
            .ok_or_else(|| js_error("builder_missing", "withShareStore is required"))?;
        let secret_store = self
            .secret_store
            .ok_or_else(|| js_error("builder_missing", "withSecretStore is required"))?;
        let user_secret_store = self
            .user_secret_store
            .ok_or_else(|| js_error("builder_missing", "withUserSecretStore is required"))?;
        let state_store = self
            .state_store
            .ok_or_else(|| js_error("builder_missing", "withStateStore is required"))?;
        let transport = self
            .transport
            .ok_or_else(|| js_error("builder_missing", "withTransport is required"))?;
        let builder = DeRecProtocolBuilder::new(self.secret_id)
            .with_channel_store(JsChannelStore(channel_store))
            .with_share_store(JsShareStore(share_store))
            .with_secret_store(JsSecretStore(secret_store))
            .with_user_secret_store(JsUserSecretStore(user_secret_store))
            .with_state_store(JsStateStore(state_store))
            .with_transport(JsTransport(transport))
            .with_config(self.config);
        let inner = builder.build().map_err(js_error_from_lib)?;
        Ok(DeRecProtocolWasm {
            secret_id: inner.secret_id(),
            inner: Mutex::new(inner),
        })
    }
}

#[wasm_bindgen]
impl DeRecProtocolWasm {
    /// The secret identifier this protocol instance is bound to.
    #[wasm_bindgen(js_name = "secretId")]
    pub fn secret_id(&self) -> u64 {
        self.secret_id
    }

    /// Single entry point for all three contact modes (`InlineKeys`,
    /// `HashedKeys`, `NoKeys`).
    ///
    /// * `channel_id` — `null`/`undefined` lets the library mint a
    ///   random id; otherwise `bigint` / `number` is used verbatim.
    /// * `contact_mode` — `0` (InlineKeys), `1` (HashedKeys), `2` (NoKeys).
    /// * `nonce` — `null`/`undefined` lets the library generate a fresh
    ///   random `u64`; otherwise the supplied `bigint`/`number` is used.
    ///   Required for `NoKeys` where callers typically pick a small
    ///   human-typable value.
    #[wasm_bindgen(js_name = "createContact")]
    pub async fn create_contact(
        &self,
        channel_id: JsValue,
        contact_mode: JsValue,
        nonce: JsValue,
    ) -> Result<JsValue, JsValue> {
        let id = parse_optional_channel_id(channel_id)?;
        let mode = match js_number_to_u32(&contact_mode, "contact_mode")? {
            0 => ContactMode::InlineKeys,
            1 => ContactMode::HashedKeys,
            2 => ContactMode::NoKeys,
            other => {
                return Err(js_error(
                    "invalid_contact_mode",
                    format!(
                        "unknown contact_mode: {other}; expected 0 (InlineKeys), 1 (HashedKeys), or 2 (NoKeys)"
                    ),
                ));
            }
        };
        let nonce = if nonce.is_null() || nonce.is_undefined() {
            None
        } else {
            Some(js_value_to_u64(nonce)?)
        };
        let contact = self
            .inner
            .lock()
            .await
            .create_contact(id, mode, nonce)
            .await
            .map_err(js_error_from_lib)?;
        let contact: PairingContactMessage = contact.into();
        let serializer = Serializer::new().serialize_large_number_types_as_bigints(true);
        use serde::Serialize as _;
        contact
            .serialize(&serializer)
            .map_err(|e| js_error("wasm_serialize_error", e.to_string()))
    }

    /// Replace this node's local communication info. Does not contact peers —
    /// follow up with a `start(UpdateChannelInfo, ...)` to propagate.
    #[wasm_bindgen(js_name = "setCommunicationInfo")]
    pub async fn set_communication_info(&self, info: JsValue) -> Result<(), JsValue> {
        let map: HashMap<String, String> = if info.is_null() || info.is_undefined() {
            HashMap::new()
        } else {
            serde_wasm_bindgen::from_value(info)
                .map_err(|e| js_error("invalid_communication_info", e.to_string()))?
        };
        self.inner.lock().await.set_communication_info(map);
        Ok(())
    }

    /// Replace every endpoint this node advertises, in preference order.
    ///
    /// `transports` is an array of `{ uri: string, protocol: string }`
    /// objects, same shape as `withOwnTransports`, and is its runtime
    /// counterpart. A node serves at most one endpoint per protocol, so this list
    /// is a preference order over distinct protocols and two entries of the
    /// same protocol are rejected.
    ///
    /// Every entry is validated before any is stored, so a malformed URI
    /// leaves the previous set intact. IMPORTANT: keep the old endpoints
    /// operational during the changeover — see the Rust docs on
    /// `set_own_transports` for the discipline.
    #[wasm_bindgen(js_name = "setOwnTransports")]
    pub async fn set_own_transports(&self, transports: Vec<JsValue>) -> Result<(), JsValue> {
        #[derive(serde::Deserialize)]
        struct EndpointShape {
            uri: String,
            protocol: String,
        }
        let mut validated = Vec::with_capacity(transports.len());
        for endpoint in transports {
            let parsed: EndpointShape = serde_wasm_bindgen::from_value(endpoint)
                .map_err(|e| js_error("invalid_own_transport", e.to_string()))?;
            let protocol_num =
                protocol_name_to_discriminant(&parsed.protocol).ok_or_else(|| {
                    js_error(
                        "invalid_protocol",
                        format!("unknown protocol: {}", parsed.protocol.to_lowercase()),
                    )
                })?;
            let proto_tp = TransportProtocol {
                uri: parsed.uri,
                protocol: protocol_num,
            };
            validated.push(
                transport::TransportProtocol::try_from(&proto_tp)
                    .map_err(|e| js_error("invalid_own_transport", e.to_string()))?,
            );
        }
        self.inner
            .lock()
            .await
            .set_own_transports(validated)
            .map_err(|e| js_error("invalid_own_transport", e.to_string()))?;
        Ok(())
    }

    /// Unified entry point for initiating any protocol flow.
    ///
    /// # Arguments
    ///
    /// * `flow_kind` — `FlowKind` discriminant: `0` Pairing, `1` Discovery,
    ///   `2` ProtectSecret, `3` VerifyShares, `4` RecoverSecret, `5` Unpair,
    ///   `6` UpdateChannelInfo, `7` ReplicaDiscovery, `8` UnpairReplica.
    /// * `params` — the flow's parameters, declared per kind in `index.d.ts`
    ///   as `PairingParams`, `DiscoveryParams`, … `UnpairReplicaParams`.
    ///   ProtectSecret's optional `weights` is a `Map<bigint, number>` of
    ///   channel ID to how many subshares that channel holds. It is the full
    ///   assignment: an unnamed Helper gets one, and absent or `null` is an
    ///   empty map, which resets every Helper to one. Its optional
    ///   `threshold` is the round's threshold; absent or `null` keeps the
    ///   stored one, or the builder's when none is stored.
    ///
    /// # Returns
    ///
    /// An `Array` of `*Started` / `*Failed` events describing the
    /// dispatched requests. Same shape as `process()`.
    #[wasm_bindgen(js_name = "start")]
    pub async fn start(&self, flow_kind: JsValue, params: JsValue) -> Result<JsValue, JsValue> {
        let flow = parse_flow(js_number_to_u32(&flow_kind, "flow_kind")?, params)?;
        let rust_events = self
            .inner
            .lock()
            .await
            .start(flow)
            .await
            .map_err(js_error_from_lib)?;
        let js_events = Array::new();
        for event in rust_events {
            js_events.push(&events::event_to_js(event)?);
        }
        Ok(js_events.into())
    }

    /// Derive the human-readable fingerprint for a paired channel. Both
    /// sides of a replica pair derive the same fingerprint from the
    /// shared key, enabling out-of-band confirmation before the channel
    /// transitions from `Pending` to `Paired`.
    #[wasm_bindgen(js_name = "getFingerprint")]
    pub async fn get_fingerprint(&self, channel_id: JsValue) -> Result<String, JsValue> {
        let id = js_value_to_u64(channel_id)?;
        self.inner
            .lock()
            .await
            .get_fingerprint(ChannelId(id))
            .await
            .map_err(js_error_from_lib)
    }

    /// Verify a fingerprint against the channel's locally-derived one. On
    /// match, the channel transitions from `Pending` to `Paired`. A mismatch
    /// rejects with code `fingerprint_mismatch` — a possible man-in-the-middle
    /// — after which a `Pending` pairing has been revoked.
    #[wasm_bindgen(js_name = "verifyFingerprint")]
    pub async fn verify_fingerprint(
        &self,
        channel_id: JsValue,
        fingerprint: String,
    ) -> Result<(), JsValue> {
        let id = js_value_to_u64(channel_id)?;
        self.inner
            .lock()
            .await
            .verify_fingerprint(ChannelId(id), &fingerprint)
            .await
            .map_err(js_error_from_lib)
    }

    /// Remove `Pending` channels older than `older_than_secs`, along with
    /// their pairing keys.
    ///
    /// Independent of the configured cleanup policy — it sweeps at the
    /// threshold given, even when the policy is disabled. The age
    /// comparison is strict, so a channel created within the current
    /// second survives even `0`.
    ///
    /// # Returns
    ///
    /// An `Array` of removed channel ids as decimal strings.
    ///
    /// `older_than_secs` is a `u64`: a `bigint`, a non-negative safe-integer
    /// `number`, or a decimal string.
    #[wasm_bindgen(js_name = removeExpiredChannels)]
    pub async fn remove_expired_channels(
        &self,
        older_than_secs: JsValue,
    ) -> Result<JsValue, JsValue> {
        let older_than_secs = js_value_to_u64(older_than_secs)?;
        let ids = self
            .inner
            .lock()
            .await
            .remove_expired_channels(older_than_secs)
            .await
            .map_err(js_error_from_lib)?;
        let decimal: Vec<String> = ids.iter().map(|c| c.0.to_string()).collect();
        serde_wasm_bindgen::to_value(&decimal)
            .map_err(|e| js_error("wasm_serialize_error", e.to_string()))
    }

    /// Accept a pending action from an `ActionRequired` event.
    ///
    /// # Arguments
    ///
    /// * `action_bytes` — Opaque `Uint8Array` from the `action` field of an `ActionRequired` event.
    ///
    /// # Returns
    ///
    /// An `Array` of event objects (same format as `process()`).
    pub async fn accept(&self, action_bytes: &[u8]) -> Result<JsValue, JsValue> {
        let action = pending_action_wire::deserialize(action_bytes)
            .map_err(|e| js_error("decode_error", e))?;
        let rust_events = self
            .inner
            .lock()
            .await
            .accept(action)
            .await
            .map_err(js_error_from_lib)?;
        let js_events = Array::new();
        for event in rust_events {
            js_events.push(&events::event_to_js(event)?);
        }
        Ok(js_events.into())
    }

    /// Reject a pending action from an `ActionRequired` event.
    ///
    /// # Arguments
    ///
    /// * `action_bytes` — Opaque `Uint8Array` from the `action` field of an `ActionRequired` event.
    /// * `status` — Numeric status code from `StatusEnum` (e.g. 2 for FAIL, 10 for REJECTED).
    /// * `memo` — Human-readable rejection reason.
    pub async fn reject(
        &self,
        action_bytes: &[u8],
        status: JsValue,
        memo: &str,
    ) -> Result<(), JsValue> {
        let action = pending_action_wire::deserialize(action_bytes)
            .map_err(|e| js_error("decode_error", e))?;
        let status_enum = status
            .as_f64()
            .filter(|f| f.fract() == 0.0 && (f64::from(i32::MIN)..=f64::from(i32::MAX)).contains(f))
            .and_then(|f| StatusEnum::try_from(f as i32).ok())
            .ok_or_else(|| {
                js_error(
                    "invalid_status",
                    format!("invalid StatusEnum value: {status:?}"),
                )
            })?;
        self.inner
            .lock()
            .await
            .reject(action, status_enum, memo)
            .await
            .map_err(js_error_from_lib)
    }

    /// Advance time-driven state without an inbound message.
    ///
    /// Timeouts are otherwise only evaluated by `process`, so a publish whose
    /// helpers all go quiet has nothing left to close it. Call this from a
    /// timer — `setInterval`, a service-worker alarm, a job runner — at an
    /// interval shorter than the configured timeout.
    ///
    /// Returns an `Array` of plain JS event objects, empty when nothing was
    /// in flight. Safe to call at any time.
    pub async fn tick(&self) -> Result<JsValue, JsValue> {
        let rust_events = self.inner.lock().await.tick().await;
        let js_events = Array::new();
        for event in rust_events {
            js_events.push(&events::event_to_js(event)?);
        }
        Ok(js_events.into())
    }

    /// Feed any incoming wire bytes to the protocol.
    ///
    /// Returns an `Array` of plain JS event objects (see struct-level docs for shapes).
    /// Every inbound flow — pairing, sharing, verification, discovery,
    /// recovery, unpairing, channel-info updates and the replica flows — is
    /// handled through this single entry point.
    ///
    /// # Arguments
    ///
    /// * `message` — Raw wire bytes of an incoming `DeRecMessage`.
    pub async fn process(&self, message: &[u8]) -> Result<JsValue, JsValue> {
        let rust_events = self
            .inner
            .lock()
            .await
            .process(message)
            .await
            .map_err(|e| {
                let error = js_error_from_lib(e.source);
                if let Some(channel_id) = e.channel_id {
                    let _ = Reflect::set(
                        &error,
                        &JsValue::from_str("channel_id"),
                        &JsValue::from_str(&channel_id.0.to_string()),
                    );
                }
                let settled = Array::new();
                for event in e.events {
                    match events::event_to_js(event) {
                        Ok(js_event) => {
                            settled.push(&js_event);
                        }
                        Err(encode_error) => return encode_error,
                    }
                }
                let _ = Reflect::set(&error, &JsValue::from_str("events"), &settled);
                error
            })?;
        let js_events = Array::new();
        for event in rust_events {
            js_events.push(&events::event_to_js(event)?);
        }
        Ok(js_events.into())
    }

    /// Rebuild this protocol's `secret_id` namespace from a recovered
    /// `Secret`. Mirrors [`crate::protocol::DeRecProtocol::restore`] —
    /// see that method for the full contract.
    ///
    /// `recoveredSecret` is the typed `Secret` object carried by the
    /// `SecretRecovered` event; pass it verbatim. A helper or member whose
    /// `transports` is empty, `null` or absent gets no channel; it is
    /// reported as a `PeerNotRestored` event in the returned array and the
    /// rest of the roster is restored. An absent or `null`
    /// `communication_info` reads as an empty map, and an absent or `null`
    /// helper `weight` as `1`.
    ///
    /// Errors surface as a `DeRecError` (`category`, `code`, `message`):
    ///
    /// | code               | meaning                                                          |
    /// |--------------------|------------------------------------------------------------------|
    /// | `already_restored` | A user-secret snapshot already exists for this `secret_id`.      |
    /// | `restore_conflict` | Channels live at ids restore is about to write. The error        |
    /// |                    | carries `channel_ids: string[]` listing the collisions.          |
    /// | `invariant`        | The recovered `Secret` is internally inconsistent.               |
    /// | `invalid_recovered_secret` | `recoveredSecret` is malformed — e.g. a missing or       |
    /// |                    | non-decimal `channel_id` / `replica_id`.                         |
    /// | `store_error`      | A store call failed mid-restore; `category` names the store.     |
    #[wasm_bindgen(js_name = "restore")]
    pub async fn restore(
        &self,
        recovered_secret: JsValue,
        version: JsValue,
    ) -> Result<JsValue, JsValue> {
        let version = js_number_to_u32(&version, "version")?;
        let secret = parse_recovered_secret(recovered_secret)?;
        let rust_events = self
            .inner
            .lock()
            .await
            .restore(&secret, version)
            .await
            .map_err(js_error_from_lib)?;
        let js_events = Array::new();
        for event in rust_events {
            js_events.push(&events::event_to_js(event)?);
        }
        Ok(js_events.into())
    }
}

fn parse_recovered_secret(value: JsValue) -> Result<Secret, JsValue> {
    serde_wasm_bindgen::from_value::<recovered_secret::RecoveredSecretIn>(value)
        .map_err(|e| js_error("invalid_recovered_secret", e.to_string()))?
        .into_secret()
        .map_err(|e| js_error("invalid_recovered_secret", e))
}

fn parse_optional_channel_id(val: JsValue) -> Result<Option<ChannelId>, JsValue> {
    if val.is_null() || val.is_undefined() {
        return Ok(None);
    }
    Ok(Some(ChannelId(js_value_to_u64(val)?)))
}

/// Convert a JS value to a Rust `u64` without loss.
///
/// Accepts a `bigint`, a `number`, or a decimal string. Strings are the
/// documented wire convention for u64 identifiers on the JS/TS surface (see
/// `packages/{nodejs,web}/index.d.ts`) — they dodge `Number.MAX_SAFE_INTEGER`
/// without forcing every caller to reach for BigInt.
///
/// A `number` must be a non-negative safe integer: a fraction, a negative, a
/// non-finite value, or one above `Number.MAX_SAFE_INTEGER` (which may already
/// have been rounded) is rejected rather than truncated. A `bigint` or string
/// must be in `u64` range, and a string must be plain decimal digits.
fn js_value_to_u64(val: JsValue) -> Result<u64, JsValue> {
    if val.is_bigint() {
        let s = BigInt::from(val)
            .to_string(10)
            .map_err(|e| js_error("decode_error", format!("{e:?}")))?
            .as_string()
            .ok_or_else(|| js_error("decode_error", "BigInt.toString returned non-string"))?;
        recovered_secret::parse_decimal_u64(&s, "bigint").map_err(|e| js_error("decode_error", e))
    } else if let Some(s) = val.as_string() {
        recovered_secret::parse_decimal_u64(&s, "string").map_err(|e| js_error("decode_error", e))
    } else if let Some(f) = val.as_f64() {
        exact_u64_from_f64(f).ok_or_else(|| {
            js_error(
                "decode_error",
                format!(
                    "number {f} is not a non-negative safe integer; pass a bigint or decimal string"
                ),
            )
        })
    } else {
        Err(js_error(
            "decode_error",
            "value must be BigInt, number, or decimal string",
        ))
    }
}

/// `Number.MAX_SAFE_INTEGER`: the largest integer every `number` up to which
/// is exactly representable.
const MAX_SAFE_INTEGER: f64 = 9_007_199_254_740_991.0;

fn exact_u64_from_f64(f: f64) -> Option<u64> {
    (f.is_finite() && f.fract() == 0.0 && (0.0..=MAX_SAFE_INTEGER).contains(&f)).then_some(f as u64)
}

/// Convert a JS `number` to a Rust `u32` without loss: it must be an integer
/// in `0..=u32::MAX`.
fn js_number_to_u32(val: &JsValue, field: &str) -> Result<u32, JsValue> {
    val.as_f64()
        .filter(|f| f.fract() == 0.0 && (0.0..=f64::from(u32::MAX)).contains(f))
        .map(|f| f as u32)
        .ok_or_else(|| {
            js_error(
                "decode_error",
                format!("{field} must be an integer in 0..=4294967295"),
            )
        })
}

fn parse_sender_kind(kind: u32) -> Result<SenderKind, JsValue> {
    match kind {
        0 => Ok(SenderKind::Owner),
        1 => Ok(SenderKind::Helper),
        3 => Ok(SenderKind::ReplicaSource),
        4 => Ok(SenderKind::ReplicaDestination),
        _ => Err(js_error(
            "invalid_sender_kind",
            format!(
                "invalid sender kind: {kind}, valid values are 0 (Owner), 1 (Helper), 3 (ReplicaSource), 4 (ReplicaDestination)"
            ),
        )),
    }
}

/// Parse a JS discovery target into [`Target`].
///
/// - `null` / `undefined` → `All`
/// - `BigInt` or `number` → `Single`
/// - `Array<BigInt | number>` → `Many`
fn parse_target(val: JsValue) -> Result<Target, JsValue> {
    if val.is_null() || val.is_undefined() {
        return Ok(Target::All);
    }
    if val.is_bigint() || val.as_f64().is_some() {
        let id = js_value_to_u64(val)?;
        return Ok(Target::Single(ChannelId(id)));
    }
    if Array::is_array(&val) {
        let arr = Array::from(&val);
        let mut ids = Vec::with_capacity(arr.length() as usize);
        for i in 0..arr.length() {
            ids.push(ChannelId(js_value_to_u64(arr.get(i))?));
        }
        return Ok(Target::Many(ids));
    }
    Err(js_error(
        "invalid_discovery_target",
        "target must be null (all), a BigInt (single), or an array of BigInts (many)",
    ))
}

/// Parse a JS `Map<u64, number>` of channel ID to subshare weight.
///
/// `null` / `undefined` is an empty map: every channel holds one subshare. A key
/// is any `u64` form [`js_value_to_u64`] accepts; a value must be an integer
/// in `0..=u32::MAX`. Whether a weight is valid for the split is decided by
/// the sharing primitive, not here.
fn parse_weights(val: JsValue) -> Result<HashMap<ChannelId, u32>, JsValue> {
    if val.is_null() || val.is_undefined() {
        return Ok(HashMap::new());
    }
    if !val.is_instance_of::<Map>() {
        return Err(js_error(
            "decode_error",
            "weights must be a Map of channel ID to weight",
        ));
    }
    let map = Map::from(val);
    let mut weights = HashMap::with_capacity(map.size() as usize);
    for entry in map.entries() {
        let entry = Array::from(&entry.map_err(|e| js_error("decode_error", format!("{e:?}")))?);
        let channel_id = ChannelId(js_value_to_u64(entry.get(0))?);
        let weight = js_number_to_u32(&entry.get(1), "weight")?;
        weights.insert(channel_id, weight);
    }
    Ok(weights)
}

/// Parse a JS array of `[channelId, weight]` tuples into [`WeightedChannel`]s.
///
/// `channelId` is any `u64` form [`js_value_to_u64`] accepts; `weight` must be
/// an integer in `0..=u32::MAX`. A non-array value, or an entry that is not a
/// two-element array, is a decode error. Whether a weight is valid for the
/// split is decided by the sharing primitive, not here.
pub(crate) fn parse_weighted_channels(val: JsValue) -> Result<Vec<WeightedChannel>, JsValue> {
    if !Array::is_array(&val) {
        return Err(js_error(
            "decode_error",
            "channels must be an array of [channelId, weight] tuples",
        ));
    }
    let arr = Array::from(&val);
    let mut channels = Vec::with_capacity(arr.length() as usize);
    for i in 0..arr.length() {
        let entry = arr.get(i);
        if !Array::is_array(&entry) || Array::from(&entry).length() != 2 {
            return Err(js_error(
                "decode_error",
                format!("channels[{i}] must be a [channelId, weight] tuple"),
            ));
        }
        let entry = Array::from(&entry);
        let channel_id = ChannelId(js_value_to_u64(entry.get(0))?);
        let weight = js_number_to_u32(&entry.get(1), "weight")?;
        channels.push((channel_id, weight));
    }
    Ok(channels)
}

/// Parse a JS `Array<{ id: Uint8Array, name: string, data: Uint8Array }>` into
/// a `Vec<UserSecret>`. A value that is not an array, or an entry missing a
/// field or carrying one of the wrong type, is a decode error.
fn parse_user_secrets(val: JsValue) -> Result<Vec<UserSecret>, JsValue> {
    #[derive(serde::Deserialize)]
    struct UserSecretShape {
        #[serde(with = "serde_bytes")]
        id: Vec<u8>,
        name: String,
        #[serde(with = "serde_bytes")]
        data: Vec<u8>,
    }
    if !Array::is_array(&val) {
        return Err(js_error("decode_error", "secrets must be an array"));
    }
    let parsed: Vec<UserSecretShape> = serde_wasm_bindgen::from_value(val)
        .map_err(|e| js_error("decode_error", format!("invalid secrets: {e}")))?;
    Ok(parsed
        .into_iter()
        .map(|s| UserSecret {
            id: s.id,
            name: s.name,
            data: s.data,
        })
        .collect())
}

/// `params[key]` as an optional string: `undefined` or `null` is `None`, any
/// other non-string is a decode error.
fn optional_string(params: &JsValue, key: &str) -> Result<Option<String>, JsValue> {
    let value = Reflect::get(params, &JsValue::from_str(key)).unwrap_or(JsValue::UNDEFINED);
    if value.is_undefined() || value.is_null() {
        return Ok(None);
    }
    value
        .as_string()
        .map(Some)
        .ok_or_else(|| js_error("decode_error", format!("{key} must be a string")))
}

/// Parse a JS flow kind + params into a [`DeRecFlow`].
///
/// Flow kinds:
/// - `0` = Pairing: `{ kind: number, contact: ContactMessage, peerCommunicationInfo?: Record<string, string> }`
/// - `1` = Discovery: `{ target?: Target }`
/// - `2` = ProtectSecret: `{ secrets: UserSecret[], description?: string, weights?: Map<u64, number>, threshold?: number }`
/// - `3` = VerifyShares: `{ secretId: u64, version: number, target?: Target }`
/// - `4` = RecoverSecret: `{ secretId: u64, version: number }`
/// - `5` = Unpair: `{ channel_id: u64, memo?: string }`
/// - `6` = UpdateChannelInfo: `{ target?: Target, communication_info?: Record<string, string>, own_transports?: { uri: string, protocol: "https" | "grpc" }[] }`
/// - `7` = ReplicaDiscovery: no params
/// - `8` = UnpairReplica: `{ replica_id: string, memo?: string }`
///
/// `u64` is a `bigint`, a non-negative safe-integer `number`, or a decimal
/// string; `Target` is `null`/absent (every channel), a `bigint`/`number`, or an array
/// of them. `weights` maps a channel ID to how many subshares that channel
/// holds. It is the full assignment, so `null`/absent is an empty map: every
/// channel holds one subshare and that is what is stored (see [`parse_weights`]).
/// `threshold` is the round's threshold; `null`/absent keeps the stored one,
/// or the builder's when none is stored.
fn parse_flow(flow_kind: u32, params: JsValue) -> Result<DeRecFlow, JsValue> {
    match flow_kind {
        0 => {
            // Pairing
            let kind_val = Reflect::get(&params, &JsValue::from_str("kind"))
                .map_err(|e| js_error("decode_error", format!("missing kind: {e:?}")))?;
            let kind = js_number_to_u32(&kind_val, "kind")?;
            let sender_kind = parse_sender_kind(kind)?;
            let contact_val = Reflect::get(&params, &JsValue::from_str("contact"))
                .map_err(|e| js_error("decode_error", format!("missing contact: {e:?}")))?;
            let contact: PairingContactMessage = serde_wasm_bindgen::from_value(contact_val)
                .map_err(|e| js_error("decode_error", e.to_string()))?;
            let contact: ContactMessage = contact.into();
            let raw = Reflect::get(&params, &JsValue::from_str("peerCommunicationInfo"))
                .unwrap_or(JsValue::UNDEFINED);
            let peer_communication_info: HashMap<String, String> =
                if raw.is_null() || raw.is_undefined() {
                    HashMap::new()
                } else {
                    serde_wasm_bindgen::from_value(raw)
                        .map_err(|e| js_error("invalid_peer_communication_info", e.to_string()))?
                };
            Ok(DeRecFlow::Pairing {
                kind: sender_kind,
                contact,
                peer_communication_info,
            })
        }
        1 => {
            // Discovery
            let target_val =
                Reflect::get(&params, &JsValue::from_str("target")).unwrap_or(JsValue::UNDEFINED);
            let target = parse_target(target_val)?;
            Ok(DeRecFlow::Discovery { target })
        }
        2 => {
            // ProtectSecret
            let secrets_val = Reflect::get(&params, &JsValue::from_str("secrets"))
                .map_err(|e| js_error("decode_error", format!("missing secrets: {e:?}")))?;
            let secrets = parse_user_secrets(secrets_val)?;
            let description = optional_string(&params, "description")?;
            let weights_val =
                Reflect::get(&params, &JsValue::from_str("weights")).unwrap_or(JsValue::UNDEFINED);
            let weights = parse_weights(weights_val)?;
            let threshold_val = Reflect::get(&params, &JsValue::from_str("threshold"))
                .unwrap_or(JsValue::UNDEFINED);
            let threshold = if threshold_val.is_undefined() || threshold_val.is_null() {
                None
            } else {
                Some(js_number_to_u32(&threshold_val, "threshold")?)
            };
            Ok(DeRecFlow::ProtectSecret {
                secrets,
                description,
                weights,
                threshold,
            })
        }
        3 => {
            // VerifyShares
            let secret_id_val = Reflect::get(&params, &JsValue::from_str("secretId"))
                .map_err(|e| js_error("decode_error", format!("missing secretId: {e:?}")))?;
            let secret_id = js_value_to_u64(secret_id_val)?;
            let version_val = Reflect::get(&params, &JsValue::from_str("version"))
                .map_err(|e| js_error("decode_error", format!("missing version: {e:?}")))?;
            let version = js_number_to_u32(&version_val, "version")?;
            let target_val =
                Reflect::get(&params, &JsValue::from_str("target")).unwrap_or(JsValue::UNDEFINED);
            let target = parse_target(target_val)?;
            Ok(DeRecFlow::VerifyShares {
                secret_id,
                version,
                target,
            })
        }
        4 => {
            // RecoverSecret
            let secret_id_val = Reflect::get(&params, &JsValue::from_str("secretId"))
                .map_err(|e| js_error("decode_error", format!("missing secretId: {e:?}")))?;
            let secret_id = js_value_to_u64(secret_id_val)?;
            let version_val = Reflect::get(&params, &JsValue::from_str("version"))
                .map_err(|e| js_error("decode_error", format!("missing version: {e:?}")))?;
            let version = js_number_to_u32(&version_val, "version")?;
            Ok(DeRecFlow::RecoverSecret { secret_id, version })
        }
        5 => {
            // Unpair
            let channel_id_val = Reflect::get(&params, &JsValue::from_str("channel_id"))
                .map_err(|e| js_error("decode_error", format!("missing channel_id: {e:?}")))?;
            let channel_id = ChannelId(js_value_to_u64(channel_id_val)?);
            let memo = optional_string(&params, "memo")?;
            Ok(DeRecFlow::Unpair { channel_id, memo })
        }
        6 => {
            // UpdateChannelInfo
            //
            // Wire-shape mirrors the dotnet `UpdateChannelInfoParams`:
            // `{ target, communication_info?, own_transports?: { uri, protocol: "https" | "grpc" }[] }`.
            // Field names are snake_case for SDK parity.
            let target_val =
                Reflect::get(&params, &JsValue::from_str("target")).unwrap_or(JsValue::UNDEFINED);
            let target = parse_target(target_val)?;
            let communication_info_val =
                Reflect::get(&params, &JsValue::from_str("communication_info"))
                    .unwrap_or(JsValue::UNDEFINED);
            let communication_info: Option<HashMap<String, String>> =
                if communication_info_val.is_null() || communication_info_val.is_undefined() {
                    None
                } else {
                    Some(
                        serde_wasm_bindgen::from_value(communication_info_val)
                            .map_err(|e| js_error("invalid_communication_info", e.to_string()))?,
                    )
                };
            #[derive(serde::Deserialize)]
            struct TransportShape {
                uri: String,
                #[serde(deserialize_with = "crate::interop::protocol_names::protocol_from_name")]
                protocol: i32,
            }
            let read_one = |v: JsValue| -> Result<TransportProtocol, JsValue> {
                let parsed: TransportShape = serde_wasm_bindgen::from_value(v)
                    .map_err(|e| js_error("invalid_transport_protocol", e.to_string()))?;
                Ok(TransportProtocol {
                    uri: parsed.uri,
                    protocol: parsed.protocol,
                })
            };

            let own_transports_val = Reflect::get(&params, &JsValue::from_str("own_transports"))
                .unwrap_or(JsValue::UNDEFINED);
            let own_transports =
                if own_transports_val.is_null() || own_transports_val.is_undefined() {
                    Vec::new()
                } else {
                    let array = Array::from(&own_transports_val);
                    let mut out = Vec::with_capacity(array.length() as usize);
                    for entry in array.iter() {
                        out.push(read_one(entry)?);
                    }
                    out
                };
            Ok(DeRecFlow::UpdateChannelInfo {
                target,
                communication_info,
                own_transports,
            })
        }
        8 => {
            // UnpairReplica: `{ replica_id, memo? }`. `replica_id` is a
            // decimal string so large values survive JS number handling.
            let replica_id_val = Reflect::get(&params, &JsValue::from_str("replica_id"))
                .unwrap_or(JsValue::UNDEFINED);
            // A decimal string, so ids above 2^53 survive JS number handling.
            let replica_id: u64 = replica_id_val
                .as_string()
                .ok_or_else(|| {
                    js_error(
                        "invalid_flow_params",
                        "replica_id must be a decimal string".to_owned(),
                    )
                })?
                .parse::<u64>()
                .map_err(|e| {
                    js_error(
                        "invalid_flow_params",
                        format!("replica_id must be a decimal u64: {e}"),
                    )
                })?;
            let memo = optional_string(&params, "memo")?;
            Ok(DeRecFlow::UnpairReplica { replica_id, memo })
        }
        7 => {
            // ReplicaDiscovery takes no parameters: the group and this device's own
            // version are both read from the stores.
            Ok(DeRecFlow::ReplicaDiscovery)
        }
        _ => Err(js_error(
            "invalid_flow_kind",
            format!("invalid flow kind: {flow_kind}, must be 0..8"),
        )),
    }
}