keymaster-connect 0.0.0-stage → 0.1.1

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/index.js ADDED
@@ -0,0 +1,655 @@
1
+ import { PROTOCOL_METHODS, PROTOCOL_VERSION, sameNetworkIdentity, validateNetworkIdentity } from './chunk-JDAJD3SX.js';
2
+ export { MSFILE_BLOCK_SIZE_BYTES, MSFILE_DIGEST_SIZE_BYTES, MSFILE_LOCAL_SOURCE_ID, MSFILE_MAX_BLOCK_BYTES, MSFILE_MAX_CONTENT_BYTES, MSFILE_MAX_ERROR_MESSAGE_BYTES, MSFILE_MAX_HEADER_BYTES, MSFILE_MAX_SEED_BYTES, MSFILE_PROTOCOL_ID, PROTOCOL_METHODS, PROTOCOL_VERSION, STORAGE_DEFAULT_LIST_LIMIT, STORAGE_MAX_LIST_LIMIT, STORAGE_MAX_PAYLOAD_BYTES, isValidMsFileSourceId, sameNetworkIdentity, validateBsvNetwork, validateNetworkIdentity } from './chunk-JDAJD3SX.js';
3
+
4
+ // src/binary.ts
5
+ function binary(bytes, mime) {
6
+ const view = bytes instanceof ArrayBuffer ? new Uint8Array(bytes) : new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength);
7
+ const copy = new Uint8Array(view.byteLength);
8
+ copy.set(view);
9
+ return {
10
+ $type: "binary",
11
+ bytes: copy.buffer,
12
+ ...mime ? { mime } : {}
13
+ };
14
+ }
15
+ function binaryBytes(field) {
16
+ if (field.$type !== "binary" || !(field.bytes instanceof ArrayBuffer)) {
17
+ throw new TypeError("Expected a Keymaster BinaryField");
18
+ }
19
+ return new Uint8Array(field.bytes.slice(0));
20
+ }
21
+ function binaryText(value, mime = "text/plain;charset=utf-8") {
22
+ return binary(new TextEncoder().encode(value), mime);
23
+ }
24
+ function binaryToText(field) {
25
+ return new TextDecoder().decode(binaryBytes(field));
26
+ }
27
+
28
+ // src/client.ts
29
+ var KeymasterTransportError = class extends Error {
30
+ constructor(code, message) {
31
+ super(message);
32
+ this.code = code;
33
+ this.name = "KeymasterTransportError";
34
+ }
35
+ code;
36
+ };
37
+ var KeymasterProtocolError = class extends Error {
38
+ constructor(code, message) {
39
+ super(message);
40
+ this.code = code;
41
+ this.name = "KeymasterProtocolError";
42
+ }
43
+ code;
44
+ };
45
+ var DEFAULT_POPUP_PATH = "/protocol/v1/popup";
46
+ var DEFAULT_POPUP_NAME = "keymaster-connect-v1";
47
+ var DEFAULT_READY_TIMEOUT_MS = 3e4;
48
+ var DEFAULT_REQUEST_TIMEOUT_MS = 12e4;
49
+ var DEFAULT_CLOSE_POLL_MS = 500;
50
+ var KeymasterConnectClient = class {
51
+ identityValue = null;
52
+ bindingId = null;
53
+ /** Identity returned by the authenticated wallet, or null before establishment. */
54
+ get networkIdentity() {
55
+ return this.identityValue;
56
+ }
57
+ targetOrigin;
58
+ mode;
59
+ environment;
60
+ options;
61
+ pending = /* @__PURE__ */ new Map();
62
+ stateValue = "idle";
63
+ sessionWindow = null;
64
+ ownsSessionWindow = false;
65
+ listenerInstalled = false;
66
+ readyPromise = null;
67
+ readyResolve = null;
68
+ readyReject = null;
69
+ readyTimer = null;
70
+ closePoller = null;
71
+ constructor(options) {
72
+ if ("networkIdentity" in options) throw new TypeError("networkIdentity option has been removed; read identity from the connection result");
73
+ this.targetOrigin = normalizeHttpOrigin(options.targetOrigin);
74
+ this.mode = options.mode ?? "popup";
75
+ this.options = {
76
+ ...options,
77
+ popupPath: options.popupPath ?? DEFAULT_POPUP_PATH,
78
+ popupName: options.popupName ?? DEFAULT_POPUP_NAME,
79
+ popupWidth: positiveNumber(options.popupWidth ?? 520, "popupWidth"),
80
+ popupHeight: positiveNumber(options.popupHeight ?? 760, "popupHeight"),
81
+ readyTimeoutMs: positiveNumber(options.readyTimeoutMs ?? DEFAULT_READY_TIMEOUT_MS, "readyTimeoutMs"),
82
+ requestTimeoutMs: positiveNumber(options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS, "requestTimeoutMs"),
83
+ closePollMs: positiveNumber(options.closePollMs ?? DEFAULT_CLOSE_POLL_MS, "closePollMs")
84
+ };
85
+ this.environment = options.environment ?? createBrowserEnvironment();
86
+ }
87
+ /**
88
+ * Current browser transport state.
89
+ *
90
+ * @group Transport
91
+ */
92
+ get state() {
93
+ return this.stateValue;
94
+ }
95
+ /**
96
+ * Establishes the browser transport.
97
+ *
98
+ * Popup mode opens the Session Window and waits for `ready`. appView mode
99
+ * adopts `window.opener`, installs the listener, and sends the child `ready`
100
+ * message without ever opening a fallback popup.
101
+ *
102
+ * @group Transport
103
+ */
104
+ connect() {
105
+ return this.mode === "appView" ? this.connectAppView() : this.connectPopup();
106
+ }
107
+ /**
108
+ * Sends any public Connect method with compile-time parameter and result
109
+ * inference.
110
+ *
111
+ * @group Transport
112
+ */
113
+ async request(method, params, options = {}) {
114
+ if (options.signal?.aborted) throw abortReason(options.signal);
115
+ if (!PROTOCOL_METHODS.includes(method)) throw new TypeError("Unknown Connect method");
116
+ if (!params || typeof params !== "object" || Array.isArray(params)) throw new TypeError("params must be an object");
117
+ for (const field of ["walletPublicKeyHex", "networkIdentity", "bsvNetwork", "assetId"]) {
118
+ if (field in params) throw new TypeError(`Removed wallet selector: ${field}`);
119
+ }
120
+ const establishing = ["connect.login", "connect.resume", "connect.launch"].includes(method);
121
+ if (establishing && this.pending.size) throw new TypeError("Cannot establish a connection while requests are pending");
122
+ if (!establishing && !this.bindingId) throw new KeymasterProtocolError("invalid_request", "Login, resume or launch before making business requests");
123
+ if ([...this.pending.values()].some((request) => ["connect.login", "connect.resume", "connect.launch"].includes(request.method))) throw new TypeError("Connection establishment is already pending");
124
+ await this.connect();
125
+ if (establishing && this.pending.size) throw new TypeError("Cannot establish a connection while requests are pending");
126
+ if ([...this.pending.values()].some((request) => ["connect.login", "connect.resume", "connect.launch"].includes(request.method))) throw new TypeError("Connection establishment is already pending");
127
+ if (options.signal?.aborted) throw abortReason(options.signal);
128
+ const target = this.sessionWindow;
129
+ if (!target || isWindowClosed(target)) {
130
+ throw new KeymasterTransportError("popup_closed", "Keymaster Session Window is closed");
131
+ }
132
+ const requestId = options.requestId ?? this.environment.randomUUID();
133
+ if (!requestId || this.pending.has(requestId)) {
134
+ throw new TypeError("requestId must be non-empty and unique among pending requests");
135
+ }
136
+ const timeoutMs = positiveNumber(options.timeoutMs ?? this.options.requestTimeoutMs, "timeoutMs");
137
+ return new Promise((resolve, reject) => {
138
+ const timer = this.environment.setTimeout(() => {
139
+ this.postCancel(requestId);
140
+ this.deletePending(requestId);
141
+ reject(new KeymasterTransportError("request_timeout", `Keymaster request timed out: ${method}`));
142
+ }, timeoutMs);
143
+ const abortListener = options.signal ? () => {
144
+ this.postCancel(requestId);
145
+ this.deletePending(requestId);
146
+ reject(abortReason(options.signal));
147
+ } : void 0;
148
+ if (abortListener) options.signal.addEventListener("abort", abortListener, { once: true });
149
+ this.pending.set(requestId, {
150
+ method,
151
+ resolve: (value) => resolve(value),
152
+ reject,
153
+ timer,
154
+ signal: options.signal,
155
+ abortListener
156
+ });
157
+ try {
158
+ target.postMessage({
159
+ v: PROTOCOL_VERSION,
160
+ type: "request",
161
+ ...!establishing ? { bindingId: this.bindingId } : {},
162
+ id: requestId,
163
+ method,
164
+ params
165
+ }, this.targetOrigin);
166
+ } catch (cause) {
167
+ this.deletePending(requestId);
168
+ reject(new KeymasterTransportError("send_failed", errorMessage(cause, "Unable to send Keymaster request")));
169
+ }
170
+ });
171
+ }
172
+ /**
173
+ * Calls `connect.login` to create a persistent Connect session.
174
+ *
175
+ * @group Connect
176
+ */
177
+ login(params, options) {
178
+ return this.request("connect.login", params, options);
179
+ }
180
+ /**
181
+ * Calls `connect.resume` to restore the unlock runtime for a persistent
182
+ * session.
183
+ *
184
+ * @group Connect
185
+ */
186
+ resume(params = {}, options) {
187
+ return this.request("connect.resume", params, options);
188
+ }
189
+ /**
190
+ * Calls `connect.logout` to revoke a persistent Connect session.
191
+ *
192
+ * @group Connect
193
+ */
194
+ logout(options) {
195
+ if (options !== void 0 && (typeof options !== "object" || options === null)) return Promise.reject(new TypeError("logout no longer accepts a wallet public key"));
196
+ return this.request("connect.logout", {}, options);
197
+ }
198
+ /**
199
+ * Calls `connect.launch` to consume the one-time launch token of an appView
200
+ * session.
201
+ *
202
+ * @group Connect
203
+ */
204
+ launch(params, options) {
205
+ if (this.mode !== "appView") {
206
+ return Promise.reject(new TypeError('connect.launch requires mode: "appView"'));
207
+ }
208
+ return this.request("connect.launch", params, options);
209
+ }
210
+ /**
211
+ * Calls `identity.get` to return signed identity claims for the session
212
+ * owner.
213
+ *
214
+ * @group Identity
215
+ */
216
+ identityGet(params, options) {
217
+ return this.request("identity.get", params, options);
218
+ }
219
+ /**
220
+ * Calls `intent.sign` to sign caller-provided bytes with a human-readable
221
+ * intent.
222
+ *
223
+ * @group Identity
224
+ */
225
+ intentSign(params, options) {
226
+ return this.request("intent.sign", params, options);
227
+ }
228
+ /**
229
+ * Calls `cipher.encrypt` to encrypt origin-bound application data.
230
+ *
231
+ * @group Cipher
232
+ */
233
+ cipherEncrypt(params, options) {
234
+ return this.request("cipher.encrypt", params, options);
235
+ }
236
+ /**
237
+ * Calls `cipher.decrypt` to decrypt data previously returned by
238
+ * `cipher.encrypt`.
239
+ *
240
+ * @group Cipher
241
+ */
242
+ cipherDecrypt(params, options) {
243
+ return this.request("cipher.decrypt", params, options);
244
+ }
245
+ /**
246
+ * 请求 `payment.pay`;资金审批、选币与持久幂等由钱包负责。
247
+ * Promise resolve 不等于已广播,应检查返回状态。
248
+ *
249
+ * @group Payment
250
+ */
251
+ paymentPay(params, options) {
252
+ return this.request("payment.pay", params, options);
253
+ }
254
+ /** 按原业务 ID 只读查询付款状态,不自动重付或更换 ID。 */
255
+ paymentStatus(params, options) {
256
+ return this.request("payment.status", params, options);
257
+ }
258
+ /**
259
+ * @deprecated Connect v1 接收端拒绝旧转账方法,使用 paymentPay。
260
+ * @group Transfer
261
+ */
262
+ p2pkhTransfer(params, options) {
263
+ return this.request("p2pkh.transfer", params, options);
264
+ }
265
+ /** 注册零额度渠道;用户在钱包设置额度后,付款携带返回的 channelId。 */
266
+ registerPaymentChannel(params, options) {
267
+ return this.request("payment.channel.register", params, options);
268
+ }
269
+ /**
270
+ * 发布到任意精确频道;owner、公钥签名和消息编号由 Keymaster 生成。
271
+ *
272
+ * @group Channel
273
+ */
274
+ channelPublish(params, options) {
275
+ return this.request("channel.publish", params, options);
276
+ }
277
+ /**
278
+ * 替换当前 Connect caller 的精确频道订阅集合;传空数组表示释放。
279
+ *
280
+ * @group Channel
281
+ */
282
+ channelSubscriptionSet(params, options) {
283
+ return this.request("channel.subscription_set", params, options);
284
+ }
285
+ /**
286
+ * Calls `storage.list` to list paths in the verified application's namespace.
287
+ *
288
+ * @group Storage
289
+ */
290
+ storageList(params, options) {
291
+ return this.request("storage.list", params, options);
292
+ }
293
+ /**
294
+ * Calls `storage.directory.create` to create an app-scoped directory.
295
+ *
296
+ * @group Storage
297
+ */
298
+ storageDirectoryCreate(params, options) {
299
+ return this.request("storage.directory.create", params, options);
300
+ }
301
+ /**
302
+ * Calls `storage.directory.delete` to delete an app-scoped directory.
303
+ *
304
+ * @group Storage
305
+ */
306
+ storageDirectoryDelete(params, options) {
307
+ return this.request("storage.directory.delete", params, options);
308
+ }
309
+ /**
310
+ * Calls `storage.put` to write an app-scoped object.
311
+ *
312
+ * @group Storage
313
+ */
314
+ storagePut(params, options) {
315
+ return this.request("storage.put", params, options);
316
+ }
317
+ /**
318
+ * Calls `storage.get` to read an app-scoped object.
319
+ *
320
+ * @group Storage
321
+ */
322
+ storageGet(params, options) {
323
+ return this.request("storage.get", params, options);
324
+ }
325
+ /**
326
+ * Calls `storage.delete` to delete an app-scoped object.
327
+ *
328
+ * @group Storage
329
+ */
330
+ storageDelete(params, options) {
331
+ return this.request("storage.delete", params, options);
332
+ }
333
+ /**
334
+ * Calls `msfile.stat` to query every enabled MSFile supplier for a seed
335
+ * hash. The caller selects supplier/hash only; price policy stays inside
336
+ * Keymaster.
337
+ *
338
+ * @group MSFile
339
+ */
340
+ msfileStat(params, options) {
341
+ return this.request("msfile.stat", params, options);
342
+ }
343
+ /**
344
+ * Calls `msfile.seed.read` to buy and read a MasterSeed by hash. There is no
345
+ * price parameter: Keymaster resolves the amount from its settings or asks
346
+ * the user for approval when needed.
347
+ *
348
+ * @group MSFile
349
+ */
350
+ msfileReadSeed(params, options) {
351
+ return this.request("msfile.seed.read", params, options);
352
+ }
353
+ /**
354
+ * Calls `msfile.block.read` to buy and read a single file block by hash.
355
+ * Like {@link msfileReadSeed}, no caller-supplied price is accepted.
356
+ *
357
+ * @group MSFile
358
+ */
359
+ msfileReadBlock(params, options) {
360
+ return this.request("msfile.block.read", params, options);
361
+ }
362
+ /**
363
+ * Cancels a locally pending request. Keymaster only cancels work that has not
364
+ * entered execution; cancellation is therefore best-effort remotely.
365
+ *
366
+ * @group Transport
367
+ */
368
+ cancel(requestId, reason = new DOMException("The operation was aborted", "AbortError")) {
369
+ const pending = this.pending.get(requestId);
370
+ if (!pending) return false;
371
+ this.postCancel(requestId);
372
+ this.deletePending(requestId);
373
+ pending.reject(reason);
374
+ return true;
375
+ }
376
+ /**
377
+ * Tears down the local transport. This does not revoke persistent Connect
378
+ * sessions; call {@link logout} before closing when revocation is required.
379
+ *
380
+ * @group Transport
381
+ */
382
+ close() {
383
+ this.identityValue = null;
384
+ this.bindingId = null;
385
+ const error = new KeymasterTransportError("client_closed", "Keymaster client was closed");
386
+ this.rejectAll(error);
387
+ this.failReady(error);
388
+ this.stopClosePolling();
389
+ if (this.listenerInstalled) {
390
+ this.environment.removeMessageListener(this.handleMessage);
391
+ this.listenerInstalled = false;
392
+ }
393
+ try {
394
+ if (this.ownsSessionWindow && this.sessionWindow && !isWindowClosed(this.sessionWindow)) {
395
+ this.sessionWindow.close();
396
+ }
397
+ } catch {
398
+ }
399
+ this.sessionWindow = null;
400
+ this.ownsSessionWindow = false;
401
+ this.setState("disconnected");
402
+ }
403
+ connectPopup() {
404
+ if (this.isConnected()) return Promise.resolve();
405
+ if (this.readyPromise) return this.readyPromise;
406
+ const url = new URL(this.options.popupPath, `${this.targetOrigin}/`);
407
+ if (url.origin !== this.targetOrigin) {
408
+ return Promise.reject(new TypeError("popupPath must resolve inside targetOrigin"));
409
+ }
410
+ this.installListener();
411
+ this.setState("opening");
412
+ this.sessionWindow = this.environment.open(
413
+ url.toString(),
414
+ this.options.popupName,
415
+ popupFeatures(this.options.popupWidth, this.options.popupHeight)
416
+ );
417
+ if (!this.sessionWindow) {
418
+ this.setState("disconnected");
419
+ return Promise.reject(new KeymasterTransportError("popup_blocked", "Keymaster Session Window was blocked"));
420
+ }
421
+ this.ownsSessionWindow = true;
422
+ this.startClosePolling();
423
+ this.readyPromise = new Promise((resolve, reject) => {
424
+ this.readyResolve = resolve;
425
+ this.readyReject = reject;
426
+ this.readyTimer = this.environment.setTimeout(() => {
427
+ this.disconnect(new KeymasterTransportError("ready_timeout", "Timed out waiting for Keymaster ready"));
428
+ }, this.options.readyTimeoutMs);
429
+ });
430
+ return this.readyPromise;
431
+ }
432
+ connectAppView() {
433
+ if (this.isConnected()) return Promise.resolve();
434
+ const opener = this.environment.opener();
435
+ if (!opener || isWindowClosed(opener)) {
436
+ const code = this.stateValue === "idle" ? "no_opener" : "appview_session_lost";
437
+ this.setState("disconnected");
438
+ return Promise.reject(new KeymasterTransportError(
439
+ code,
440
+ "No live Keymaster appView Session Window is available"
441
+ ));
442
+ }
443
+ this.installListener();
444
+ this.sessionWindow = opener;
445
+ this.ownsSessionWindow = false;
446
+ try {
447
+ opener.postMessage({ v: PROTOCOL_VERSION, type: "ready" }, this.targetOrigin);
448
+ } catch (cause) {
449
+ this.sessionWindow = null;
450
+ this.setState("disconnected");
451
+ return Promise.reject(new KeymasterTransportError("send_failed", errorMessage(cause, "Unable to send appView ready")));
452
+ }
453
+ this.startClosePolling();
454
+ this.setState("connected");
455
+ return Promise.resolve();
456
+ }
457
+ handleMessage = (event) => {
458
+ if (!this.sessionWindow || event.origin !== this.targetOrigin || event.source !== this.sessionWindow) return;
459
+ const value = event.data;
460
+ if (!value || typeof value.type !== "string") return;
461
+ if (value.v !== PROTOCOL_VERSION) {
462
+ if (value.type === "ready" || value.type === "result") this.disconnect(new KeymasterTransportError("unsupported_protocol", "Incompatible Keymaster protocol version"));
463
+ return;
464
+ }
465
+ if (value.type === "ready" && this.mode === "popup") {
466
+ this.finishReady();
467
+ return;
468
+ }
469
+ if (value.type === "closing") {
470
+ this.disconnect(new KeymasterTransportError("popup_closed", "Keymaster Session Window is closing"));
471
+ return;
472
+ }
473
+ if (value.type === "event") {
474
+ if (value.event !== "channel.message_received") return;
475
+ try {
476
+ if (!this.identityValue || value.bindingId !== this.bindingId || !sameNetworkIdentity(this.identityValue, validateNetworkIdentity(value.networkIdentity))) return;
477
+ } catch {
478
+ return;
479
+ }
480
+ try {
481
+ this.options.onEvent?.(event.data);
482
+ } catch {
483
+ }
484
+ return;
485
+ }
486
+ if (value.type !== "result" || typeof value.id !== "string" || typeof value.ok !== "boolean") return;
487
+ const result = event.data;
488
+ const pending = this.pending.get(result.id);
489
+ if (!pending) return;
490
+ this.deletePending(result.id);
491
+ if (!result.ok) {
492
+ if (!result.error || typeof result.error.code !== "string" || !result.error.code || typeof result.error.message !== "string") {
493
+ pending.reject(new KeymasterProtocolError("invalid_request", "Malformed Keymaster error result"));
494
+ return;
495
+ }
496
+ if (result.error.code === "connection_expired") {
497
+ this.identityValue = null;
498
+ this.bindingId = null;
499
+ }
500
+ pending.reject(new KeymasterProtocolError(result.error.code, result.error.message));
501
+ return;
502
+ }
503
+ try {
504
+ const identity = validateNetworkIdentity(value.networkIdentity);
505
+ if (["connect.login", "connect.resume", "connect.launch"].includes(pending.method)) {
506
+ const connected = result.result;
507
+ if (!sameNetworkIdentity(identity, validateNetworkIdentity(connected.networkIdentity)) || typeof value.bindingId !== "string" || !value.bindingId) throw new Error("Invalid connection identity or binding");
508
+ this.identityValue = Object.freeze({ ...identity });
509
+ this.bindingId = value.bindingId;
510
+ } else if (!this.identityValue || value.bindingId !== this.bindingId || !sameNetworkIdentity(this.identityValue, identity)) {
511
+ throw new Error("Keymaster connection identity mismatch");
512
+ }
513
+ if (pending.method === "connect.logout") {
514
+ this.identityValue = null;
515
+ this.bindingId = null;
516
+ }
517
+ pending.resolve(result.result);
518
+ } catch (error) {
519
+ pending.reject(new KeymasterProtocolError("invalid_request", errorMessage(error, "Invalid connection result")));
520
+ }
521
+ };
522
+ isConnected() {
523
+ return this.stateValue === "connected" && !!this.sessionWindow && !isWindowClosed(this.sessionWindow);
524
+ }
525
+ installListener() {
526
+ if (this.listenerInstalled) return;
527
+ this.environment.addMessageListener(this.handleMessage);
528
+ this.listenerInstalled = true;
529
+ }
530
+ finishReady() {
531
+ if (!this.readyPromise) return;
532
+ if (this.readyTimer !== null) this.environment.clearTimeout(this.readyTimer);
533
+ this.readyTimer = null;
534
+ this.readyResolve?.();
535
+ this.readyPromise = null;
536
+ this.readyResolve = null;
537
+ this.readyReject = null;
538
+ this.setState("connected");
539
+ }
540
+ failReady(reason) {
541
+ if (this.readyTimer !== null) this.environment.clearTimeout(this.readyTimer);
542
+ this.readyTimer = null;
543
+ this.readyReject?.(reason);
544
+ this.readyPromise = null;
545
+ this.readyResolve = null;
546
+ this.readyReject = null;
547
+ }
548
+ disconnect(reason) {
549
+ this.identityValue = null;
550
+ this.bindingId = null;
551
+ this.rejectAll(reason);
552
+ this.failReady(reason);
553
+ this.stopClosePolling();
554
+ try {
555
+ if (this.ownsSessionWindow && this.sessionWindow && !isWindowClosed(this.sessionWindow)) {
556
+ this.sessionWindow.close();
557
+ }
558
+ } catch {
559
+ }
560
+ this.sessionWindow = null;
561
+ this.ownsSessionWindow = false;
562
+ this.setState("disconnected");
563
+ }
564
+ startClosePolling() {
565
+ this.stopClosePolling();
566
+ this.closePoller = this.environment.setInterval(() => {
567
+ if (this.sessionWindow && isWindowClosed(this.sessionWindow)) {
568
+ this.disconnect(new KeymasterTransportError("popup_closed", "Keymaster Session Window was closed"));
569
+ }
570
+ }, this.options.closePollMs);
571
+ }
572
+ stopClosePolling() {
573
+ if (this.closePoller !== null) this.environment.clearInterval(this.closePoller);
574
+ this.closePoller = null;
575
+ }
576
+ rejectAll(reason) {
577
+ for (const [id, pending] of this.pending) {
578
+ this.deletePending(id);
579
+ pending.reject(reason);
580
+ }
581
+ }
582
+ deletePending(id) {
583
+ const pending = this.pending.get(id);
584
+ if (!pending) return;
585
+ this.environment.clearTimeout(pending.timer);
586
+ if (pending.signal && pending.abortListener) {
587
+ pending.signal.removeEventListener("abort", pending.abortListener);
588
+ }
589
+ this.pending.delete(id);
590
+ }
591
+ postCancel(id) {
592
+ try {
593
+ this.sessionWindow?.postMessage({ v: PROTOCOL_VERSION, type: "cancel", id, ...this.bindingId ? { bindingId: this.bindingId } : {} }, this.targetOrigin);
594
+ } catch {
595
+ }
596
+ }
597
+ setState(state) {
598
+ if (state === this.stateValue) return;
599
+ this.stateValue = state;
600
+ try {
601
+ this.options.onStateChange?.(state);
602
+ } catch {
603
+ }
604
+ }
605
+ };
606
+ function createKeymasterConnect(options) {
607
+ return new KeymasterConnectClient(options);
608
+ }
609
+ function createBrowserEnvironment() {
610
+ if (typeof window === "undefined") {
611
+ throw new TypeError("keymaster-connect requires a browser Window or an explicit environment");
612
+ }
613
+ return {
614
+ open: (url, target, features) => window.open(url, target, features),
615
+ opener: () => window.opener,
616
+ addMessageListener: (listener) => window.addEventListener("message", listener),
617
+ removeMessageListener: (listener) => window.removeEventListener("message", listener),
618
+ setTimeout: (handler, timeoutMs) => window.setTimeout(handler, timeoutMs),
619
+ clearTimeout: (timer) => window.clearTimeout(timer),
620
+ setInterval: (handler, intervalMs) => window.setInterval(handler, intervalMs),
621
+ clearInterval: (timer) => window.clearInterval(timer),
622
+ randomUUID: () => window.crypto.randomUUID()
623
+ };
624
+ }
625
+ function normalizeHttpOrigin(input) {
626
+ const url = new URL(input);
627
+ if (url.protocol !== "https:" && url.protocol !== "http:") {
628
+ throw new TypeError("targetOrigin must use http or https");
629
+ }
630
+ return url.origin;
631
+ }
632
+ function popupFeatures(width, height) {
633
+ return `popup=yes,width=${Math.max(320, Math.trunc(width))},height=${Math.max(320, Math.trunc(height))}`;
634
+ }
635
+ function positiveNumber(value, name) {
636
+ if (!Number.isFinite(value) || value <= 0) throw new TypeError(`${name} must be a positive number`);
637
+ return value;
638
+ }
639
+ function isWindowClosed(value) {
640
+ try {
641
+ return value.closed === true;
642
+ } catch {
643
+ return true;
644
+ }
645
+ }
646
+ function abortReason(signal) {
647
+ return signal.reason ?? new DOMException("The operation was aborted", "AbortError");
648
+ }
649
+ function errorMessage(value, fallback) {
650
+ return value instanceof Error && value.message ? value.message : fallback;
651
+ }
652
+
653
+ export { KeymasterConnectClient, KeymasterProtocolError, KeymasterTransportError, binary, binaryBytes, binaryText, binaryToText, createBrowserEnvironment, createKeymasterConnect };
654
+ //# sourceMappingURL=index.js.map
655
+ //# sourceMappingURL=index.js.map