@learncard/chapi-plugin 1.0.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,1595 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
+
21
+ // src/index.ts
22
+ var src_exports = {};
23
+ __export(src_exports, {
24
+ getCHAPIPlugin: () => getCHAPIPlugin
25
+ });
26
+ module.exports = __toCommonJS(src_exports);
27
+
28
+ // ../../../node_modules/.pnpm/web-request-rpc@2.0.3/node_modules/web-request-rpc/utils.js
29
+ var RPC_ERRORS = {
30
+ ParseError: {
31
+ message: "Parse error",
32
+ code: -32700
33
+ },
34
+ InvalidRequest: {
35
+ message: "Invalid Request",
36
+ code: -32600
37
+ },
38
+ MethodNotFound: {
39
+ message: "Method not found",
40
+ code: -32601
41
+ },
42
+ InvalidParams: {
43
+ message: "Invalid params",
44
+ code: -32602
45
+ },
46
+ InternalError: {
47
+ message: "Internal Error",
48
+ code: -32603
49
+ },
50
+ ServerError: {
51
+ message: "Server error",
52
+ code: -32e3
53
+ }
54
+ };
55
+ function parseUrl(url, base) {
56
+ if (base === void 0) {
57
+ base = window.location.href;
58
+ }
59
+ if (typeof URL === "function") {
60
+ return new URL(url, base);
61
+ }
62
+ if (typeof url !== "string") {
63
+ throw new TypeError('"url" must be a string.');
64
+ }
65
+ if (!url.includes(":")) {
66
+ if (base.startsWith("http") && !url.startsWith("/")) {
67
+ url = base + "/" + url;
68
+ } else {
69
+ url = base + url;
70
+ }
71
+ }
72
+ const parser = document.createElement("a");
73
+ parser.href = url;
74
+ let origin = (parser.protocol || window.location.protocol) + "//";
75
+ if (parser.host) {
76
+ if (parser.protocol === "http:" && parser.port === "80" || parser.protocol === "https:" && parser.port === "443") {
77
+ origin += parser.hostname;
78
+ } else {
79
+ origin += parser.host;
80
+ }
81
+ } else {
82
+ origin += window.location.host;
83
+ }
84
+ let pathname = parser.pathname;
85
+ if (!pathname.startsWith("/")) {
86
+ pathname = "/" + pathname;
87
+ }
88
+ return {
89
+ host: parser.host || window.location.host,
90
+ hostname: parser.hostname,
91
+ origin,
92
+ protocol: parser.protocol,
93
+ pathname
94
+ };
95
+ }
96
+ __name(parseUrl, "parseUrl");
97
+ function uuidv4(a, b) {
98
+ for (b = a = ""; a++ < 36; b += a * 51 & 52 ? (a ^ 15 ? 8 ^ Math.random() * (a ^ 20 ? 16 : 4) : 4).toString(16) : "-")
99
+ ;
100
+ return b;
101
+ }
102
+ __name(uuidv4, "uuidv4");
103
+ function isValidMessage(message) {
104
+ return message && typeof message === "object" && message.jsonrpc === "2.0" && message.id && typeof message.id === "string";
105
+ }
106
+ __name(isValidMessage, "isValidMessage");
107
+ function isValidRequest(message) {
108
+ return isValidMessage(message) && Array.isArray(message.params);
109
+ }
110
+ __name(isValidRequest, "isValidRequest");
111
+ function isValidResponse(message) {
112
+ return isValidMessage(message) && !!("result" in message ^ "error" in message) && (!("error" in message) || isValidError(message.error));
113
+ }
114
+ __name(isValidResponse, "isValidResponse");
115
+ function isValidError(error) {
116
+ return error && typeof error === "object" && typeof error.code === "number" && typeof error.message === "string";
117
+ }
118
+ __name(isValidError, "isValidError");
119
+ function serializeError(error) {
120
+ const err = {
121
+ message: error.message
122
+ };
123
+ if (error.constructor.name !== "Error") {
124
+ err.constructor = error.constructor.name;
125
+ }
126
+ if ("name" in error) {
127
+ err.name = error.name;
128
+ }
129
+ if ("code" in error) {
130
+ err.code = error.code;
131
+ } else {
132
+ err.code = RPC_ERRORS.ServerError.code;
133
+ }
134
+ if ("details" in error) {
135
+ err.details = error.details;
136
+ }
137
+ return err;
138
+ }
139
+ __name(serializeError, "serializeError");
140
+ function deserializeError(error) {
141
+ let err;
142
+ if (error.constructor === "DOMException") {
143
+ err = new DOMException(error.message, error.name);
144
+ } else {
145
+ err = new Error(error.message);
146
+ if ("code" in error) {
147
+ err.code = error.code;
148
+ }
149
+ }
150
+ if (error.details) {
151
+ err.details = error.details;
152
+ }
153
+ return err;
154
+ }
155
+ __name(deserializeError, "deserializeError");
156
+ function createMessageListener({ listener: listener2, origin, handle, expectRequest }) {
157
+ if (isHandlePromise(handle)) {
158
+ const promise = handle;
159
+ handle = false;
160
+ promise.then((h) => handle = h);
161
+ }
162
+ return (e) => {
163
+ if (!(e.source === handle && e.origin === origin && (expectRequest && isValidRequest(e.data) || !expectRequest && isValidResponse(e.data)))) {
164
+ return;
165
+ }
166
+ listener2(e.data, e);
167
+ };
168
+ }
169
+ __name(createMessageListener, "createMessageListener");
170
+ function destructureMethodName(fqMethodName) {
171
+ let [name, ...rest] = fqMethodName.split(".");
172
+ const method = rest.pop();
173
+ name = [name, ...rest].join(".");
174
+ return { name, method };
175
+ }
176
+ __name(destructureMethodName, "destructureMethodName");
177
+ function isHandlePromise(handle) {
178
+ try {
179
+ return typeof handle.then === "function";
180
+ } catch (e) {
181
+ }
182
+ return false;
183
+ }
184
+ __name(isHandlePromise, "isHandlePromise");
185
+
186
+ // ../../../node_modules/.pnpm/web-request-rpc@2.0.3/node_modules/web-request-rpc/Client.js
187
+ var RPC_CLIENT_CALL_TIMEOUT = 3e4;
188
+ var Client = class {
189
+ constructor() {
190
+ this.origin = null;
191
+ this._handle = null;
192
+ this._listener = null;
193
+ this._pending = /* @__PURE__ */ new Map();
194
+ }
195
+ async connect(origin, options) {
196
+ if (this._listener) {
197
+ throw new Error("Already connected.");
198
+ }
199
+ options = options || {};
200
+ const self = this;
201
+ self.origin = parseUrl(origin).origin;
202
+ self._handle = options.handle || window.opener || window.parent;
203
+ const pending = self._pending;
204
+ self._listener = createMessageListener({
205
+ origin: self.origin,
206
+ handle: self._handle,
207
+ expectRequest: false,
208
+ listener: (message) => {
209
+ if (!pending.has(message.id)) {
210
+ return;
211
+ }
212
+ const { resolve, reject, cancelTimeout } = pending.get(message.id);
213
+ cancelTimeout();
214
+ if ("result" in message) {
215
+ return resolve(message.result);
216
+ }
217
+ reject(deserializeError(message.error));
218
+ }
219
+ });
220
+ window.addEventListener("message", self._listener);
221
+ return new Injector(self);
222
+ }
223
+ async send(qualifiedMethodName, parameters, {
224
+ timeout = RPC_CLIENT_CALL_TIMEOUT
225
+ }) {
226
+ if (!this._listener) {
227
+ throw new Error("RPC client not connected.");
228
+ }
229
+ const self = this;
230
+ const message = {
231
+ jsonrpc: "2.0",
232
+ id: uuidv4(),
233
+ method: qualifiedMethodName,
234
+ params: parameters
235
+ };
236
+ if (isHandlePromise(self._handle)) {
237
+ const handle = await self._handle;
238
+ handle.postMessage(message, self.origin);
239
+ } else {
240
+ self._handle.postMessage(message, self.origin);
241
+ }
242
+ return new Promise((resolve, reject) => {
243
+ const pending = self._pending;
244
+ let cancelTimeout;
245
+ if (timeout > 0) {
246
+ const timeoutId = setTimeout(() => {
247
+ pending.delete(message.id);
248
+ reject(new Error("RPC call timed out."));
249
+ }, timeout);
250
+ cancelTimeout = /* @__PURE__ */ __name(() => {
251
+ pending.delete(message.id);
252
+ clearTimeout(timeoutId);
253
+ }, "cancelTimeout");
254
+ } else {
255
+ cancelTimeout = /* @__PURE__ */ __name(() => {
256
+ pending.delete(message.id);
257
+ }, "cancelTimeout");
258
+ }
259
+ pending.set(message.id, { resolve, reject, cancelTimeout });
260
+ });
261
+ }
262
+ close() {
263
+ if (this._listener) {
264
+ window.removeEventListener("message", this._listener);
265
+ this._handle = this.origin = this._listener = null;
266
+ for (const value of this._pending.values()) {
267
+ value.reject(new Error("RPC client closed."));
268
+ }
269
+ this._pending = /* @__PURE__ */ new Map();
270
+ }
271
+ }
272
+ };
273
+ __name(Client, "Client");
274
+ var Injector = class {
275
+ constructor(client) {
276
+ this.client = client;
277
+ this._apis = /* @__PURE__ */ new Map();
278
+ }
279
+ define(name, definition) {
280
+ if (!(name && typeof name === "string")) {
281
+ throw new TypeError("`name` must be a non-empty string.");
282
+ }
283
+ if (!(definition && typeof definition === "object" && Array.isArray(definition.functions))) {
284
+ throw new TypeError(
285
+ "`definition.function` must be an array of function names or function definition objects to be defined."
286
+ );
287
+ }
288
+ const self = this;
289
+ const api = {};
290
+ definition.functions.forEach((fn) => {
291
+ if (typeof fn === "string") {
292
+ fn = { name: fn, options: {} };
293
+ }
294
+ api[fn.name] = async function() {
295
+ return self.client.send(
296
+ name + "." + fn.name,
297
+ [...arguments],
298
+ fn.options
299
+ );
300
+ };
301
+ });
302
+ self._apis[name] = api;
303
+ return api;
304
+ }
305
+ get(name, definition) {
306
+ const api = this._apis[name];
307
+ if (!api) {
308
+ if (definition) {
309
+ return this.define(name, definition);
310
+ }
311
+ throw new Error(`API "${name}" has not been defined.`);
312
+ }
313
+ return this._apis[name];
314
+ }
315
+ };
316
+ __name(Injector, "Injector");
317
+
318
+ // ../../../node_modules/.pnpm/web-request-rpc@2.0.3/node_modules/web-request-rpc/EventEmitter.js
319
+ var EventEmitter = class {
320
+ constructor({ deserialize = /* @__PURE__ */ __name((e) => e, "deserialize"), waitUntil = /* @__PURE__ */ __name(async () => {
321
+ }, "waitUntil") } = {}) {
322
+ this._listeners = [];
323
+ this._deserialize = deserialize;
324
+ this._waitUntil = waitUntil;
325
+ }
326
+ async emit(event) {
327
+ event = this._deserialize(event);
328
+ (this._listeners[event.type] || []).forEach((l) => l(event));
329
+ return this._waitUntil(event);
330
+ }
331
+ addEventListener(eventType, fn) {
332
+ if (!this._listeners[eventType]) {
333
+ this._listeners[eventType] = [fn];
334
+ } else {
335
+ this._listeners[eventType].push(fn);
336
+ }
337
+ }
338
+ removeEventListener(eventType, fn) {
339
+ const listeners = this._listeners[eventType];
340
+ if (!listeners) {
341
+ return;
342
+ }
343
+ const idx = listeners.indexOf(fn);
344
+ if (idx !== -1) {
345
+ listeners.splice(idx, 1);
346
+ }
347
+ }
348
+ };
349
+ __name(EventEmitter, "EventEmitter");
350
+
351
+ // ../../../node_modules/.pnpm/web-request-rpc@2.0.3/node_modules/web-request-rpc/Server.js
352
+ var Server = class {
353
+ constructor() {
354
+ this.origin = null;
355
+ this._handle = null;
356
+ this._apis = /* @__PURE__ */ new Map();
357
+ }
358
+ define(name, api) {
359
+ if (!(name && typeof name === "string")) {
360
+ throw new TypeError("`name` must be a non-empty string.");
361
+ }
362
+ if (!(api && api !== "object")) {
363
+ throw new TypeError("`api` must be an object.");
364
+ }
365
+ if (name in this._apis) {
366
+ throw new Error(`The "${name}" API is already defined.`);
367
+ }
368
+ this._apis[name] = api;
369
+ }
370
+ async listen(origin, options) {
371
+ if (this._listener) {
372
+ throw new Error("Already listening.");
373
+ }
374
+ options = options || {};
375
+ const self = this;
376
+ self.origin = parseUrl(origin).origin;
377
+ self._handle = options.handle || window.opener || window.parent;
378
+ const ignoreUnknownApi = options.ignoreUnknownApi === "true" || false;
379
+ self._listener = createMessageListener({
380
+ origin: self.origin,
381
+ handle: self._handle,
382
+ expectRequest: true,
383
+ listener: (message) => {
384
+ const { name, method } = destructureMethodName(message.method);
385
+ const api = self._apis[name];
386
+ if (method && method.startsWith("_")) {
387
+ return sendMethodNotFound(self._handle, self.origin, message);
388
+ }
389
+ if (!api && ignoreUnknownApi) {
390
+ return;
391
+ }
392
+ if (!api || typeof api[method] !== "function") {
393
+ return sendMethodNotFound(self._handle, self.origin, message);
394
+ }
395
+ const fn = api[method];
396
+ (async () => {
397
+ const response = {
398
+ jsonrpc: "2.0",
399
+ id: message.id
400
+ };
401
+ try {
402
+ response.result = await fn.apply(api, message.params);
403
+ } catch (e) {
404
+ response.error = serializeError(e);
405
+ }
406
+ if (self._handle) {
407
+ if (isHandlePromise(self._handle)) {
408
+ self._handle.then((h) => h.postMessage(response, self.origin));
409
+ } else {
410
+ self._handle.postMessage(response, self.origin);
411
+ }
412
+ }
413
+ })();
414
+ }
415
+ });
416
+ window.addEventListener("message", self._listener);
417
+ }
418
+ close() {
419
+ if (this._listener) {
420
+ window.removeEventListener("message", this._listener);
421
+ this._handle = this.origin = this._listener = null;
422
+ }
423
+ }
424
+ };
425
+ __name(Server, "Server");
426
+ function sendMethodNotFound(handle, origin, message) {
427
+ const response = {
428
+ jsonrpc: "2.0",
429
+ id: message.id,
430
+ error: Object.assign({}, RPC_ERRORS.MethodNotFound)
431
+ };
432
+ if (isHandlePromise(handle)) {
433
+ return handle.then((h) => h.postMessage(response, origin));
434
+ } else {
435
+ return handle.postMessage(response, origin);
436
+ }
437
+ }
438
+ __name(sendMethodNotFound, "sendMethodNotFound");
439
+
440
+ // ../../../node_modules/.pnpm/web-request-rpc@2.0.3/node_modules/web-request-rpc/WebApp.js
441
+ var WebApp = class {
442
+ constructor(relyingOrigin) {
443
+ this.relyingOrigin = parseUrl(relyingOrigin).origin;
444
+ this.client = null;
445
+ this.injector = null;
446
+ this.client = new Client();
447
+ this.server = new Server();
448
+ this._control = null;
449
+ this._connected = false;
450
+ }
451
+ async connect() {
452
+ this.injector = await this.client.connect(this.relyingOrigin);
453
+ this._connected = true;
454
+ this._control = this.injector.define("core.control", {
455
+ functions: ["ready", "show", "hide"]
456
+ });
457
+ this.server.listen(this.relyingOrigin);
458
+ return this.injector;
459
+ }
460
+ async ready() {
461
+ if (!this._connected) {
462
+ throw new Error('WebApp not connected. Did you call ".connect()"?');
463
+ }
464
+ await this._control.ready();
465
+ return this;
466
+ }
467
+ close() {
468
+ if (this._connected) {
469
+ this.server.close();
470
+ this.client.close();
471
+ this._connected = false;
472
+ }
473
+ }
474
+ async show() {
475
+ if (!this._connected) {
476
+ throw new Error(
477
+ 'Cannot "show" yet; not connected. Did you call ".connect()"?'
478
+ );
479
+ }
480
+ return this._control.show();
481
+ }
482
+ async hide() {
483
+ if (!this._connected) {
484
+ throw new Error(
485
+ 'Cannot "hide" yet; not connected. Did you call ".connect()?"'
486
+ );
487
+ }
488
+ return this._control.hide();
489
+ }
490
+ };
491
+ __name(WebApp, "WebApp");
492
+
493
+ // ../../../node_modules/.pnpm/web-request-rpc@2.0.3/node_modules/web-request-rpc/WebAppWindowDialog.js
494
+ var WebAppWindowDialog = class {
495
+ constructor() {
496
+ this._closeEventListeners = /* @__PURE__ */ new Set();
497
+ }
498
+ addEventListener(name, listener2) {
499
+ if (name !== "close") {
500
+ throw new Error(`Unknown event "${name}".`);
501
+ }
502
+ if (typeof listener2 !== "function") {
503
+ throw new TypeError('"listener" must be a function.');
504
+ }
505
+ this._closeEventListeners.add(listener2);
506
+ }
507
+ removeEventListener(name, listener2) {
508
+ if (name !== "close") {
509
+ throw new Error(`Unknown event "${name}".`);
510
+ }
511
+ if (typeof listener2 !== "function") {
512
+ throw new TypeError('"listener" must be a function.');
513
+ }
514
+ this._closeEventListeners.delete(listener2);
515
+ }
516
+ show() {
517
+ }
518
+ close() {
519
+ for (const listener2 of this._closeEventListeners) {
520
+ listener2({});
521
+ }
522
+ }
523
+ destroy() {
524
+ this._closeEventListeners.clear();
525
+ }
526
+ };
527
+ __name(WebAppWindowDialog, "WebAppWindowDialog");
528
+
529
+ // ../../../node_modules/.pnpm/web-request-rpc@2.0.3/node_modules/web-request-rpc/WebAppWindowInlineDialog.js
530
+ var WebAppWindowInlineDialog = class extends WebAppWindowDialog {
531
+ constructor({ url, handle, className }) {
532
+ super();
533
+ this.url = url;
534
+ this.handle = handle;
535
+ this.dialog = document.createElement("dialog");
536
+ applyStyle(this.dialog, {
537
+ position: "fixed",
538
+ top: 0,
539
+ left: 0,
540
+ width: "100%",
541
+ height: "100%",
542
+ "max-width": "100%",
543
+ "max-height": "100%",
544
+ display: "none",
545
+ margin: 0,
546
+ padding: 0,
547
+ border: "none",
548
+ background: "transparent",
549
+ color: "black",
550
+ "box-sizing": "border-box",
551
+ overflow: "hidden",
552
+ "user-select": "none",
553
+ "z-index": 1e6
554
+ });
555
+ this.dialog.className = "web-app-window";
556
+ if (typeof className === "string") {
557
+ this.dialog.className = this.dialog.className + " " + className;
558
+ }
559
+ const style = document.createElement("style");
560
+ style.appendChild(
561
+ document.createTextNode(`dialog.web-app-window::backdrop {
562
+ background-color: transparent;
563
+ }`)
564
+ );
565
+ this.container = document.createElement("div");
566
+ applyStyle(this.container, {
567
+ position: "relative",
568
+ width: "100%",
569
+ height: "100%",
570
+ margin: 0,
571
+ padding: 0,
572
+ display: "flex",
573
+ "flex-direction": "column"
574
+ });
575
+ this.container.className = "web-app-window-backdrop";
576
+ this.iframe = document.createElement("iframe");
577
+ this.iframe.src = url;
578
+ this.iframe.scrolling = "auto";
579
+ applyStyle(this.iframe, {
580
+ position: "fixed",
581
+ top: 0,
582
+ left: 0,
583
+ width: "100%",
584
+ height: "100%",
585
+ border: "none",
586
+ background: "transparent",
587
+ overflow: "hidden",
588
+ margin: 0,
589
+ padding: 0,
590
+ "flex-grow": 1,
591
+ "user-select": "none"
592
+ });
593
+ this.dialog.appendChild(style);
594
+ this.container.appendChild(this.iframe);
595
+ this.dialog.appendChild(this.container);
596
+ this.dialog.addEventListener("cancel", (e) => {
597
+ e.preventDefault();
598
+ this.hide();
599
+ });
600
+ document.body.appendChild(this.dialog);
601
+ this.handle = this.iframe.contentWindow;
602
+ }
603
+ show() {
604
+ this.dialog.style.display = "block";
605
+ if (this.dialog.showModal) {
606
+ this.dialog.showModal();
607
+ }
608
+ try {
609
+ this.dialog.style.pointerEvents = "none";
610
+ } catch (e) {
611
+ }
612
+ setTimeout(() => {
613
+ try {
614
+ this.dialog.style.pointerEvents = "";
615
+ } catch (e) {
616
+ }
617
+ }, 32);
618
+ }
619
+ close() {
620
+ this.dialog.style.display = "none";
621
+ if (this.dialog.close) {
622
+ try {
623
+ this.dialog.close();
624
+ } catch (e) {
625
+ console.error(e);
626
+ }
627
+ }
628
+ super.close();
629
+ }
630
+ destroy() {
631
+ this.dialog.parentNode.removeChild(this.dialog);
632
+ super.destroy();
633
+ }
634
+ };
635
+ __name(WebAppWindowInlineDialog, "WebAppWindowInlineDialog");
636
+ function applyStyle(element, style) {
637
+ for (const name in style) {
638
+ element.style[name] = style[name];
639
+ }
640
+ }
641
+ __name(applyStyle, "applyStyle");
642
+
643
+ // ../../../node_modules/.pnpm/web-request-rpc@2.0.3/node_modules/web-request-rpc/WebAppWindowPopupDialog.js
644
+ var WebAppWindowPopupDialog = class extends WebAppWindowDialog {
645
+ constructor({ url, handle, bounds = { width: 500, height: 400 } }) {
646
+ super();
647
+ this.url = url;
648
+ this.handle = handle;
649
+ this._locationChanging = false;
650
+ if (!handle) {
651
+ this._openWindow({ url, name: "web-app-window", bounds });
652
+ }
653
+ this.destroyed = false;
654
+ this._removeListeners = () => {
655
+ };
656
+ }
657
+ show() {
658
+ }
659
+ close() {
660
+ this.destroy();
661
+ }
662
+ destroy() {
663
+ if (this.handle && !this.destroyed) {
664
+ this.handle.close();
665
+ super.close();
666
+ this.handle = null;
667
+ this.destroyed = true;
668
+ this._removeListeners();
669
+ super.destroy();
670
+ }
671
+ }
672
+ isClosed() {
673
+ return !this.handle || this.handle.closed;
674
+ }
675
+ _openWindow({ url, name, bounds }) {
676
+ const { x, y } = bounds;
677
+ let { width = 500, height = 400 } = bounds;
678
+ width = Math.min(width, window.innerWidth);
679
+ height = Math.min(height, window.innerHeight);
680
+ const left = Math.floor(x !== void 0 ? x : window.screenX + (window.innerWidth - width) / 2);
681
+ const top = Math.floor(y !== void 0 ? y : window.screenY + (window.innerHeight - height) / 2);
682
+ const features = `popup=yes,menubar=no,location=no,resizable=no,scrollbars=no,status=no,width=${width},height=${height},left=${left},top=${top}`;
683
+ this._locationChanging = true;
684
+ this.handle = window.open(url, name, features);
685
+ this._addListeners();
686
+ }
687
+ setLocation(url) {
688
+ this.url = url;
689
+ this._locationChanging = true;
690
+ this.handle.location.replace(url);
691
+ }
692
+ _addListeners() {
693
+ const destroyDialog = /* @__PURE__ */ __name(() => this.destroy(), "destroyDialog");
694
+ const loadDialog = /* @__PURE__ */ __name(() => {
695
+ this._locationChanging = false;
696
+ }, "loadDialog");
697
+ const unloadDialog = /* @__PURE__ */ __name(() => {
698
+ if (this._locationChanging) {
699
+ return;
700
+ }
701
+ this.destroy();
702
+ }, "unloadDialog");
703
+ this.handle.addEventListener("unload", unloadDialog);
704
+ this.handle.addEventListener("load", loadDialog);
705
+ window.addEventListener("beforeUnload", destroyDialog, { once: true });
706
+ const intervalId = setInterval(() => {
707
+ if (this.isClosed()) {
708
+ this.destroy();
709
+ clearInterval(intervalId);
710
+ }
711
+ }, 250);
712
+ this._removeListeners = () => {
713
+ clearInterval(intervalId);
714
+ this.handle.removeListener("unload", unloadDialog);
715
+ this.handle.removeListener("load", loadDialog);
716
+ window.removeEventListener("beforeUnload", destroyDialog);
717
+ };
718
+ }
719
+ };
720
+ __name(WebAppWindowPopupDialog, "WebAppWindowPopupDialog");
721
+
722
+ // ../../../node_modules/.pnpm/web-request-rpc@2.0.3/node_modules/web-request-rpc/WebAppWindow.js
723
+ var LOAD_WINDOW_TIMEOUT = 6e4;
724
+ var WebAppWindow = class {
725
+ constructor(url, {
726
+ timeout = LOAD_WINDOW_TIMEOUT,
727
+ dialog = null,
728
+ handle,
729
+ popup = false,
730
+ className = null,
731
+ customize = null,
732
+ bounds
733
+ } = {}) {
734
+ this.visible = false;
735
+ this.dialog = dialog;
736
+ this.handle = null;
737
+ this.popup = popup;
738
+ this.windowControl = null;
739
+ this._destroyed = false;
740
+ this._ready = false;
741
+ this._private = {};
742
+ this._timeoutId = null;
743
+ if (handle && handle._dialog) {
744
+ this.dialog = dialog = handle._dialog;
745
+ }
746
+ this._private._readyPromise = new Promise((resolve, reject) => {
747
+ this._timeoutId = setTimeout(
748
+ () => reject(new DOMException(
749
+ "Loading Web application window timed out.",
750
+ "TimeoutError"
751
+ )),
752
+ timeout
753
+ );
754
+ this._private._resolveReady = (value) => {
755
+ clearTimeout(this.timeoutId);
756
+ this._timeoutId = null;
757
+ resolve(value);
758
+ };
759
+ this._private._rejectReady = (err) => {
760
+ clearTimeout(this.timeoutId);
761
+ this._timeoutId = null;
762
+ reject(err);
763
+ };
764
+ });
765
+ this._private.isReady = async () => {
766
+ return this._private._readyPromise;
767
+ };
768
+ this._private.destroy = () => {
769
+ if (this._timeoutId) {
770
+ this._private._rejectReady(new DOMException(
771
+ "Web application window closed before ready.",
772
+ "AbortError"
773
+ ));
774
+ }
775
+ if (!this._destroyed) {
776
+ this.dialog.destroy();
777
+ this.dialog = null;
778
+ this._destroyed = true;
779
+ }
780
+ };
781
+ if (customize) {
782
+ if (!typeof customize === "function") {
783
+ throw new TypeError("`options.customize` must be a function.");
784
+ }
785
+ }
786
+ if (!this.dialog) {
787
+ if (this.popup) {
788
+ this.dialog = new WebAppWindowPopupDialog({ url, handle, bounds });
789
+ } else {
790
+ this.dialog = new WebAppWindowInlineDialog({ url, handle, className });
791
+ }
792
+ }
793
+ if (this.popup && bounds) {
794
+ let { x, y, width = 500, height = 400 } = bounds;
795
+ width = Math.min(width, window.innerWidth);
796
+ height = Math.min(height + 30, window.innerHeight);
797
+ x = Math.floor(x !== void 0 ? x : window.screenX + (window.innerWidth - width) / 2);
798
+ y = Math.floor(y !== void 0 ? y : window.screenY + (window.innerHeight - height) / 2 + 15);
799
+ this.dialog.handle.resizeTo(width, height);
800
+ this.dialog.handle.moveTo(x, y);
801
+ }
802
+ this.handle = this.dialog.handle;
803
+ if (customize) {
804
+ try {
805
+ customize({
806
+ dialog: this.dialog.dialog,
807
+ container: this.dialog.container,
808
+ iframe: this.dialog.iframe,
809
+ webAppWindow: this
810
+ });
811
+ } catch (e) {
812
+ console.error(e);
813
+ }
814
+ }
815
+ }
816
+ ready() {
817
+ this._ready = true;
818
+ this._private._resolveReady(true);
819
+ }
820
+ show() {
821
+ if (!this.visible) {
822
+ this.visible = true;
823
+ const body = document.querySelector("body");
824
+ this._bodyOverflowStyle = body.style.overflow;
825
+ body.style.overflow = "hidden";
826
+ if (!this._destroyed) {
827
+ this.dialog.show();
828
+ } else if (this.windowControl.show) {
829
+ this.windowControl.show();
830
+ }
831
+ }
832
+ }
833
+ hide() {
834
+ if (this.visible) {
835
+ this.visible = false;
836
+ const body = document.querySelector("body");
837
+ if (this._bodyOverflowStyle) {
838
+ body.style.overflow = this._bodyOverflowStyle;
839
+ } else {
840
+ body.style.overflow = "";
841
+ }
842
+ if (!this._destroyed) {
843
+ this.dialog.close();
844
+ } else if (this.windowControl.hide) {
845
+ this.windowControl.hide();
846
+ }
847
+ }
848
+ }
849
+ };
850
+ __name(WebAppWindow, "WebAppWindow");
851
+
852
+ // ../../../node_modules/.pnpm/web-request-rpc@2.0.3/node_modules/web-request-rpc/WebAppContext.js
853
+ var WEB_APP_CONTEXT_LOAD_TIMEOUT = 1e4;
854
+ var WebAppContext = class {
855
+ constructor() {
856
+ this.client = new Client();
857
+ this.server = new Server();
858
+ this.injector = null;
859
+ this.control = null;
860
+ this.loaded = false;
861
+ this.closed = false;
862
+ }
863
+ async createWindow(url, {
864
+ timeout = WEB_APP_CONTEXT_LOAD_TIMEOUT,
865
+ iframe,
866
+ dialog = null,
867
+ popup = false,
868
+ handle,
869
+ windowControl,
870
+ className,
871
+ customize,
872
+ bounds
873
+ } = {}) {
874
+ if (this.loaded) {
875
+ throw new Error("AppContext already loaded.");
876
+ }
877
+ this.loaded = true;
878
+ this.control = new WebAppWindow(url, {
879
+ timeout,
880
+ dialog,
881
+ iframe,
882
+ popup,
883
+ handle,
884
+ windowControl,
885
+ className,
886
+ customize,
887
+ bounds
888
+ });
889
+ window.addEventListener("pagehide", () => this.close(), { once: true });
890
+ this.server.define("core.control", this.control);
891
+ const origin = parseUrl(url).origin;
892
+ this.server.listen(origin, {
893
+ handle: this.control.handle,
894
+ ignoreUnknownApi: true
895
+ });
896
+ await this.control._private.isReady();
897
+ this.injector = await this.client.connect(origin, {
898
+ handle: this.control.handle
899
+ });
900
+ return this.injector;
901
+ }
902
+ close() {
903
+ if (!this.closed) {
904
+ this.closed = true;
905
+ this.control._private.destroy();
906
+ this.server.close();
907
+ this.client.close();
908
+ }
909
+ }
910
+ };
911
+ __name(WebAppContext, "WebAppContext");
912
+
913
+ // ../../../node_modules/.pnpm/credential-handler-polyfill@3.1.0/node_modules/credential-handler-polyfill/CredentialRequestEvent.js
914
+ var CredentialRequestEvent = class {
915
+ constructor({
916
+ credentialHandler,
917
+ credentialRequestOrigin,
918
+ credentialRequestOptions,
919
+ hintKey
920
+ }) {
921
+ this.type = "credentialrequest";
922
+ this._credentialHandler = credentialHandler;
923
+ this.credentialRequestOrigin = credentialRequestOrigin;
924
+ this.credentialRequestOptions = credentialRequestOptions;
925
+ this.hintKey = hintKey;
926
+ }
927
+ async openWindow(url) {
928
+ await this._credentialHandler.show();
929
+ const appWindow = new WebAppWindow(url, {
930
+ className: "credential-handler"
931
+ });
932
+ appWindow.ready();
933
+ appWindow.show();
934
+ appWindow.handle._dialog = appWindow.dialog;
935
+ return appWindow.handle;
936
+ }
937
+ respondWith(handlerResponse) {
938
+ this._promise = handlerResponse;
939
+ }
940
+ };
941
+ __name(CredentialRequestEvent, "CredentialRequestEvent");
942
+
943
+ // ../../../node_modules/.pnpm/credential-handler-polyfill@3.1.0/node_modules/credential-handler-polyfill/CredentialStoreEvent.js
944
+ var CredentialStoreEvent = class {
945
+ constructor({
946
+ credentialHandler,
947
+ credentialRequestOrigin,
948
+ credential,
949
+ hintKey
950
+ }) {
951
+ this.type = "credentialstore";
952
+ this._credentialHandler = credentialHandler;
953
+ this.credentialRequestOrigin = credentialRequestOrigin;
954
+ this.credential = credential;
955
+ this.hintKey = hintKey;
956
+ }
957
+ async openWindow(url) {
958
+ await this._credentialHandler.show();
959
+ const appWindow = new WebAppWindow(url);
960
+ appWindow.ready();
961
+ appWindow.show();
962
+ appWindow.handle._dialog = appWindow.dialog;
963
+ return appWindow.handle;
964
+ }
965
+ respondWith(handlerResponse) {
966
+ this._promise = handlerResponse;
967
+ }
968
+ };
969
+ __name(CredentialStoreEvent, "CredentialStoreEvent");
970
+
971
+ // ../../../node_modules/.pnpm/credential-handler-polyfill@3.1.0/node_modules/credential-handler-polyfill/CredentialHandlerService.js
972
+ var CredentialHandlerService = class {
973
+ constructor(credentialHandler) {
974
+ this._credentialHandler = credentialHandler;
975
+ }
976
+ async request(credentialRequestEvent) {
977
+ return await this._credentialHandler._emitter.emit(
978
+ new CredentialRequestEvent(Object.assign(
979
+ { credentialHandler: this._credentialHandler },
980
+ credentialRequestEvent
981
+ ))
982
+ );
983
+ }
984
+ async store(credentialStoreEvent) {
985
+ return await this._credentialHandler._emitter.emit(
986
+ new CredentialStoreEvent(Object.assign(
987
+ { credentialHandler: this._credentialHandler },
988
+ credentialStoreEvent
989
+ ))
990
+ );
991
+ }
992
+ };
993
+ __name(CredentialHandlerService, "CredentialHandlerService");
994
+
995
+ // ../../../node_modules/.pnpm/credential-handler-polyfill@3.1.0/node_modules/credential-handler-polyfill/CredentialHandler.js
996
+ var EVENT_TYPES = ["credentialrequest", "credentialstore"];
997
+ var CredentialHandler = class extends WebApp {
998
+ constructor(mediatorOrigin, inline = false) {
999
+ if (typeof mediatorOrigin !== "string") {
1000
+ throw new TypeError('"mediatorOrigin" must be a string.');
1001
+ }
1002
+ super(mediatorOrigin, inline);
1003
+ this._emitter = new EventEmitter({
1004
+ async waitUntil(event) {
1005
+ return event._promise || Promise.reject(
1006
+ new DOMException(
1007
+ 'No "credentialrequest" event handler found.',
1008
+ "NotFoundError"
1009
+ )
1010
+ );
1011
+ }
1012
+ });
1013
+ }
1014
+ async connect() {
1015
+ const injector = await super.connect();
1016
+ this.server.define("credentialHandler", new CredentialHandlerService(this));
1017
+ await this.ready();
1018
+ return injector;
1019
+ }
1020
+ addEventListener(eventType, fn) {
1021
+ if (!EVENT_TYPES.includes(eventType)) {
1022
+ throw new DOMException(
1023
+ `Unsupported event type "${eventType}"`,
1024
+ "NotSupportedError"
1025
+ );
1026
+ }
1027
+ return this._emitter.addEventListener(eventType, fn);
1028
+ }
1029
+ removeEventListener(eventType, fn) {
1030
+ if (!EVENT_TYPES.includes(eventType)) {
1031
+ throw new DOMException(
1032
+ `Unsupported event type "${eventType}"`,
1033
+ "NotSupportedError"
1034
+ );
1035
+ }
1036
+ return this._emitter.removeEventListener(eventType, fn);
1037
+ }
1038
+ };
1039
+ __name(CredentialHandler, "CredentialHandler");
1040
+
1041
+ // ../../../node_modules/.pnpm/credential-handler-polyfill@3.1.0/node_modules/credential-handler-polyfill/CredentialHints.js
1042
+ var CredentialHints = class {
1043
+ constructor(url, injector) {
1044
+ const remote = injector.get("credentialHints", {
1045
+ functions: ["delete", "get", "keys", "has", "set", "clear"]
1046
+ });
1047
+ for (let methodName in remote) {
1048
+ if (methodName !== "set") {
1049
+ const method = remote[methodName].bind(this, url);
1050
+ this[methodName] = function(...args) {
1051
+ this._deprecateNotice();
1052
+ return method(...args);
1053
+ };
1054
+ }
1055
+ }
1056
+ this._remoteSet = remote.set.bind(this, url);
1057
+ }
1058
+ async set(hintKey, credentialHint) {
1059
+ this._deprecateNotice();
1060
+ credentialHint.icons = credentialHint.icons || [];
1061
+ const promises = credentialHint.icons.map((icon) => imageToDataUrl(icon.src).then((fetchedImage) => {
1062
+ icon.fetchedImage = fetchedImage;
1063
+ }));
1064
+ await Promise.all(promises);
1065
+ return this._remoteSet(hintKey, credentialHint);
1066
+ }
1067
+ _deprecateNotice() {
1068
+ console.warn("Credential hints are deprecated and no longer used.");
1069
+ }
1070
+ };
1071
+ __name(CredentialHints, "CredentialHints");
1072
+ function imageToDataUrl(url) {
1073
+ return new Promise((resolve) => {
1074
+ const img = new Image();
1075
+ img.crossOrigin = "Anonymous";
1076
+ img.onload = () => {
1077
+ let canvas = document.createElement("canvas");
1078
+ const ctx = canvas.getContext("2d");
1079
+ canvas.height = img.height;
1080
+ canvas.width = img.width;
1081
+ ctx.drawImage(img, 0, 0);
1082
+ const dataUrl = canvas.toDataURL();
1083
+ resolve(dataUrl);
1084
+ canvas = null;
1085
+ };
1086
+ img.onerror = () => resolve(null);
1087
+ img.src = url;
1088
+ });
1089
+ }
1090
+ __name(imageToDataUrl, "imageToDataUrl");
1091
+
1092
+ // ../../../node_modules/.pnpm/credential-handler-polyfill@3.1.0/node_modules/credential-handler-polyfill/CredentialManager.js
1093
+ var CredentialManager = class {
1094
+ constructor(url, injector) {
1095
+ if (!(url && typeof url === "string")) {
1096
+ throw new TypeError('"url" must be a non-empty string.');
1097
+ }
1098
+ this.hints = new CredentialHints(url, injector);
1099
+ }
1100
+ static async requestPermission() {
1101
+ const status = await navigator.credentialsPolyfill.permissions.request(
1102
+ { name: "credentialhandler" }
1103
+ );
1104
+ return status.state;
1105
+ }
1106
+ };
1107
+ __name(CredentialManager, "CredentialManager");
1108
+
1109
+ // ../../../node_modules/.pnpm/credential-handler-polyfill@3.1.0/node_modules/credential-handler-polyfill/CredentialHandlerRegistration.js
1110
+ var CredentialHandlerRegistration = class {
1111
+ constructor(url, injector) {
1112
+ if (!(url && typeof url === "string")) {
1113
+ throw new TypeError('"url" must be a non-empty string.');
1114
+ }
1115
+ this.credentialManager = new CredentialManager(url, injector);
1116
+ }
1117
+ };
1118
+ __name(CredentialHandlerRegistration, "CredentialHandlerRegistration");
1119
+
1120
+ // ../../../node_modules/.pnpm/credential-handler-polyfill@3.1.0/node_modules/credential-handler-polyfill/CredentialHandlers.js
1121
+ var CredentialHandlers = class {
1122
+ constructor(injector) {
1123
+ this._init = (async () => {
1124
+ this._injector = await injector;
1125
+ this._remote = this._injector.get("credentialHandlers", {
1126
+ functions: [
1127
+ "register",
1128
+ "unregister",
1129
+ "getRegistration",
1130
+ "hasRegistration"
1131
+ ]
1132
+ });
1133
+ })();
1134
+ }
1135
+ async register(url) {
1136
+ this._deprecateNotice();
1137
+ await this._init;
1138
+ url = await this._remote.register("credential", url);
1139
+ return new CredentialHandlerRegistration(url, this._injector);
1140
+ }
1141
+ async unregister(url) {
1142
+ this._deprecateNotice();
1143
+ await this._init;
1144
+ return this._remote.unregister("credential", url);
1145
+ }
1146
+ async getRegistration(url) {
1147
+ this._deprecateNotice();
1148
+ await this._init;
1149
+ url = await this._remote.getRegistration("credential", url);
1150
+ if (!url) {
1151
+ return null;
1152
+ }
1153
+ return new CredentialHandlerRegistration(url, this._injector);
1154
+ }
1155
+ async hasRegistration(url) {
1156
+ this._deprecateNotice();
1157
+ await this._init;
1158
+ return await this._remote.hasRegistration("credential", url);
1159
+ }
1160
+ _deprecateNotice() {
1161
+ console.warn(
1162
+ 'Credential handler registration APIs are deprecated. The credential handler specified in "manifest.json" is now automatically registered when a user grants permission to install a credential handler via "CredentialManager.requestPermission()".'
1163
+ );
1164
+ }
1165
+ };
1166
+ __name(CredentialHandlers, "CredentialHandlers");
1167
+
1168
+ // ../../../node_modules/.pnpm/credential-handler-polyfill@3.1.0/node_modules/credential-handler-polyfill/WebCredential.js
1169
+ var WebCredential2 = class {
1170
+ constructor(dataType, data, { recommendedHandlerOrigins = [] } = {}) {
1171
+ if (typeof dataType !== "string") {
1172
+ throw new TypeError('"dataType" must be a string.');
1173
+ }
1174
+ this.type = "web";
1175
+ this.dataType = dataType;
1176
+ this.data = data;
1177
+ this.options = { recommendedHandlerOrigins };
1178
+ }
1179
+ };
1180
+ __name(WebCredential2, "WebCredential");
1181
+
1182
+ // ../../../node_modules/.pnpm/credential-handler-polyfill@3.1.0/node_modules/credential-handler-polyfill/CredentialsContainer.js
1183
+ var CREDENTIAL_GET_TIMEOUT = 0;
1184
+ var CREDENTIAL_STORE_TIMEOUT = 0;
1185
+ var CredentialsContainer = class {
1186
+ constructor(injector) {
1187
+ this._nativeCredentialsContainer = {
1188
+ get: navigator.credentials && navigator.credentials.get && navigator.credentials.get.bind(navigator.credentials),
1189
+ store: navigator.credentials && navigator.credentials.store && navigator.credentials.store.bind(navigator.credentials)
1190
+ };
1191
+ this._init = (async () => {
1192
+ this._remote = (await injector).get("credentialsContainer", {
1193
+ functions: [
1194
+ { name: "get", options: { timeout: CREDENTIAL_GET_TIMEOUT } },
1195
+ { name: "store", options: { timeout: CREDENTIAL_STORE_TIMEOUT } }
1196
+ ]
1197
+ });
1198
+ })();
1199
+ }
1200
+ async get(options = {}) {
1201
+ if (options.web) {
1202
+ await this._init;
1203
+ const credential = await this._remote.get(options);
1204
+ if (!credential) {
1205
+ return null;
1206
+ }
1207
+ return new WebCredential2(credential.dataType, credential.data);
1208
+ }
1209
+ if (this._nativeCredentialsContainer.get) {
1210
+ return this._nativeCredentialsContainer.get(options);
1211
+ }
1212
+ throw new DOMException("Not implemented.", "NotSupportedError");
1213
+ }
1214
+ async store(credential) {
1215
+ if (credential instanceof WebCredential2) {
1216
+ await this._init;
1217
+ const result = await this._remote.store(credential);
1218
+ if (!result) {
1219
+ return null;
1220
+ }
1221
+ return new WebCredential2(result.dataType, result.data);
1222
+ }
1223
+ if (this._nativeCredentialsContainer.store) {
1224
+ return this._nativeCredentialsContainer.store(credential);
1225
+ }
1226
+ throw new DOMException("Not implemented.", "NotSupportedError");
1227
+ }
1228
+ };
1229
+ __name(CredentialsContainer, "CredentialsContainer");
1230
+
1231
+ // ../../../node_modules/.pnpm/credential-handler-polyfill@3.1.0/node_modules/credential-handler-polyfill/PermissionManager.js
1232
+ var PERMISSION_REQUEST_TIMEOUT = 0;
1233
+ var PermissionManager = class {
1234
+ constructor(injector) {
1235
+ this._init = (async () => {
1236
+ this._remote = (await injector).get("permissionManager", {
1237
+ functions: [
1238
+ "query",
1239
+ { name: "request", options: { timeout: PERMISSION_REQUEST_TIMEOUT } },
1240
+ "revoke"
1241
+ ]
1242
+ });
1243
+ })();
1244
+ }
1245
+ async query(permissionDesc) {
1246
+ await this._init;
1247
+ return await this._remote.query(permissionDesc);
1248
+ }
1249
+ async request(permissionDesc) {
1250
+ await this._init;
1251
+ return await this._remote.request(permissionDesc);
1252
+ }
1253
+ async revoke(permissionDesc) {
1254
+ await this._init;
1255
+ return await this._remote.revoke(permissionDesc);
1256
+ }
1257
+ };
1258
+ __name(PermissionManager, "PermissionManager");
1259
+
1260
+ // ../../../node_modules/.pnpm/credential-handler-polyfill@3.1.0/node_modules/credential-handler-polyfill/index.js
1261
+ var DEFAULT_MEDIATOR_ORIGIN = "https://authn.io";
1262
+ var loaded;
1263
+ async function loadOnce(options) {
1264
+ if (loaded) {
1265
+ return loaded;
1266
+ }
1267
+ loaded = true;
1268
+ return load(options);
1269
+ }
1270
+ __name(loadOnce, "loadOnce");
1271
+ async function load(options = {
1272
+ mediatorOrigin: DEFAULT_MEDIATOR_ORIGIN
1273
+ }) {
1274
+ _assertSecureContext();
1275
+ let mediatorUrl;
1276
+ if (typeof options === "string") {
1277
+ mediatorUrl = options;
1278
+ } else if (options && typeof options === "object" && typeof options.mediatorOrigin === "string") {
1279
+ mediatorUrl = `${options.mediatorOrigin}/mediator`;
1280
+ } else {
1281
+ throw new Error(
1282
+ '"options.mediatorOrigin" must be a string expressing the origin of the mediator.'
1283
+ );
1284
+ }
1285
+ const appContext = new WebAppContext();
1286
+ const injector = appContext.createWindow(mediatorUrl, {
1287
+ className: "credential-mediator",
1288
+ timeout: 3e4
1289
+ });
1290
+ const style = document.createElement("style");
1291
+ style.appendChild(document.createTextNode(
1292
+ `dialog.web-app-window.credential-mediator > .web-app-window-backdrop {
1293
+ background-color: rgba(0, 0, 0, 0.25);
1294
+ }`
1295
+ ));
1296
+ document.body.appendChild(style);
1297
+ const polyfill = {};
1298
+ polyfill.permissions = new PermissionManager(injector);
1299
+ polyfill.CredentialHandlers = new CredentialHandlers(injector);
1300
+ polyfill.CredentialHandler = CredentialHandler;
1301
+ polyfill.CredentialManager = CredentialManager;
1302
+ polyfill.credentials = new CredentialsContainer(injector);
1303
+ polyfill.WebCredential = WebCredential2;
1304
+ navigator.credentialsPolyfill = polyfill;
1305
+ if ("credentials" in navigator) {
1306
+ navigator.credentials.get = polyfill.credentials.get.bind(
1307
+ polyfill.credentials
1308
+ );
1309
+ navigator.credentials.store = polyfill.credentials.store.bind(
1310
+ polyfill.credentials
1311
+ );
1312
+ } else {
1313
+ navigator.credentials = polyfill.credentials;
1314
+ }
1315
+ window.CredentialManager = CredentialManager;
1316
+ window.WebCredential = WebCredential2;
1317
+ return polyfill;
1318
+ }
1319
+ __name(load, "load");
1320
+ function _assertSecureContext() {
1321
+ if (!window.isSecureContext) {
1322
+ throw new DOMException("SecurityError", "The operation is insecure.");
1323
+ }
1324
+ }
1325
+ __name(_assertSecureContext, "_assertSecureContext");
1326
+
1327
+ // ../../../node_modules/.pnpm/web-credential-handler@2.0.2/node_modules/web-credential-handler/CredentialEventProxy.js
1328
+ var PROXY_EVENT_TIMEOUT = 6e4;
1329
+ var CredentialEventProxy = class extends WebApp {
1330
+ constructor() {
1331
+ super(window.location.origin);
1332
+ }
1333
+ async receive() {
1334
+ const self = this;
1335
+ await self.connect();
1336
+ return new Promise((resolveReceive, rejectReceive) => {
1337
+ const timeoutId = setTimeout(() => {
1338
+ rejectReceive(new Error("Timed out waiting to receive event."));
1339
+ }, PROXY_EVENT_TIMEOUT);
1340
+ self.server.define("credentialEventProxy", {
1341
+ async send(event) {
1342
+ resolveReceive(event);
1343
+ clearTimeout(timeoutId);
1344
+ return new Promise((resolveSend, rejectSend) => {
1345
+ event.respondWith = (promise) => {
1346
+ try {
1347
+ resolveSend(promise);
1348
+ } catch (e) {
1349
+ rejectSend(e);
1350
+ }
1351
+ };
1352
+ });
1353
+ }
1354
+ });
1355
+ self.ready();
1356
+ });
1357
+ }
1358
+ };
1359
+ __name(CredentialEventProxy, "CredentialEventProxy");
1360
+
1361
+ // ../../../node_modules/.pnpm/web-credential-handler@2.0.2/node_modules/web-credential-handler/index.js
1362
+ var DEFAULT_MEDIATOR = "https://authn.io";
1363
+ async function installHandler() {
1364
+ const CredentialManager2 = navigator.credentialsPolyfill.CredentialManager;
1365
+ const result = await CredentialManager2.requestPermission();
1366
+ if (result !== "granted") {
1367
+ throw new Error("Permission denied.");
1368
+ }
1369
+ }
1370
+ __name(installHandler, "installHandler");
1371
+ async function activateHandler({
1372
+ mediatorOrigin = DEFAULT_MEDIATOR,
1373
+ get,
1374
+ store
1375
+ }) {
1376
+ if (!(get || store)) {
1377
+ throw new Error('"get" or "store" function(s) must be specified.');
1378
+ }
1379
+ const CredentialHandler2 = navigator.credentialsPolyfill.CredentialHandler;
1380
+ const self = new CredentialHandler2(mediatorOrigin);
1381
+ if (get) {
1382
+ if (typeof get !== "function") {
1383
+ throw new TypeError('"get" must be a function.');
1384
+ }
1385
+ self.addEventListener("credentialrequest", (event) => listener({ event, get }));
1386
+ }
1387
+ if (store) {
1388
+ if (typeof store !== "function") {
1389
+ throw new TypeError('"store" must be a function.');
1390
+ }
1391
+ self.addEventListener("credentialstore", (event) => listener({ event, store }));
1392
+ }
1393
+ await self.connect();
1394
+ }
1395
+ __name(activateHandler, "activateHandler");
1396
+ async function receiveCredentialEvent() {
1397
+ const proxy = new CredentialEventProxy();
1398
+ return proxy.receive();
1399
+ }
1400
+ __name(receiveCredentialEvent, "receiveCredentialEvent");
1401
+ function listener({ event, get, store }) {
1402
+ event.respondWith(createResponse({ event, get, store }));
1403
+ }
1404
+ __name(listener, "listener");
1405
+ async function createResponse({ event, get, store }) {
1406
+ const result = await (get || store)({ event });
1407
+ if (!(result && typeof result === "object")) {
1408
+ throw new TypeError(
1409
+ 'Return value of "get" or "store" hook must be an object.'
1410
+ );
1411
+ }
1412
+ if (result.type === "response") {
1413
+ return { dataType: result.dataType, data: result.data };
1414
+ }
1415
+ if (result.type === "redirect") {
1416
+ const appContext = new WebAppContext();
1417
+ const handle = await event.openWindow(result.url);
1418
+ const windowReady = appContext.createWindow(result.url, {
1419
+ handle,
1420
+ popup: false,
1421
+ timeout: 6e5
1422
+ });
1423
+ const injector = await windowReady;
1424
+ const proxy = injector.get("credentialEventProxy", {
1425
+ functions: [{ name: "send", options: { timeout: 0 } }]
1426
+ });
1427
+ return proxy.send({
1428
+ type: event.type,
1429
+ credentialRequestOptions: event.credentialRequestOptions,
1430
+ credentialRequestOrigin: event.credentialRequestOrigin,
1431
+ credential: event.credential,
1432
+ hintKey: event.hintKey
1433
+ });
1434
+ }
1435
+ throw new Error(
1436
+ 'Return value of "get" or "store" must have a type of "response" or "redirect".'
1437
+ );
1438
+ }
1439
+ __name(createResponse, "createResponse");
1440
+
1441
+ // src/chapi.ts
1442
+ var getCHAPIPlugin = /* @__PURE__ */ __name(async () => {
1443
+ if (typeof window === "undefined") {
1444
+ return {
1445
+ name: "CHAPI",
1446
+ methods: {
1447
+ installChapiHandler: async () => {
1448
+ throw new Error("CHAPI is only available inside of a browser!");
1449
+ },
1450
+ activateChapiHandler: async () => {
1451
+ throw new Error("CHAPI is only available inside of a browser!");
1452
+ },
1453
+ receiveChapiEvent: async () => {
1454
+ throw new Error("CHAPI is only available inside of a browser!");
1455
+ },
1456
+ storeCredentialViaChapiDidAuth: async () => {
1457
+ throw new Error("CHAPI is only available inside of a browser!");
1458
+ },
1459
+ storePresentationViaChapi: async () => {
1460
+ throw new Error("CHAPI is only available inside of a browser!");
1461
+ }
1462
+ }
1463
+ };
1464
+ }
1465
+ await loadOnce();
1466
+ return {
1467
+ name: "CHAPI",
1468
+ displayName: "CHAPI",
1469
+ description: "Credential Handler API. Allows sending/retrieving credentials across wallets and issuers",
1470
+ methods: {
1471
+ installChapiHandler: async () => installHandler(),
1472
+ activateChapiHandler: async (_learnCard, {
1473
+ mediatorOrigin = `https://authn.io/mediator?${encodeURIComponent(
1474
+ window.location.origin
1475
+ )}`,
1476
+ get,
1477
+ store
1478
+ }) => {
1479
+ return activateHandler({ mediatorOrigin, get, store });
1480
+ },
1481
+ receiveChapiEvent: async () => receiveCredentialEvent(),
1482
+ storeCredentialViaChapiDidAuth: async (_learnCard, credential) => {
1483
+ const challenge = crypto.randomUUID();
1484
+ const domain = window.location.origin;
1485
+ const vpr = {
1486
+ web: {
1487
+ VerifiablePresentation: {
1488
+ query: { type: "DIDAuthentication" },
1489
+ challenge,
1490
+ domain
1491
+ }
1492
+ }
1493
+ };
1494
+ const res = await navigator.credentials.get(vpr);
1495
+ if (!res)
1496
+ return { success: false, reason: "did not auth" };
1497
+ const verification = await _learnCard.invoke.verifyPresentation(res.data, {
1498
+ challenge,
1499
+ domain,
1500
+ proofPurpose: "authentication"
1501
+ });
1502
+ if (verification.warnings.length > 0 || verification.errors.length > 0) {
1503
+ return { success: false, reason: "auth failed verification" };
1504
+ }
1505
+ const subject = res.data?.proof?.verificationMethod?.split("#")[0];
1506
+ if (!Array.isArray(credential.credentialSubject)) {
1507
+ credential.credentialSubject.id = subject;
1508
+ }
1509
+ const vp = await _learnCard.invoke.getTestVp(
1510
+ await _learnCard.invoke.issueCredential(credential)
1511
+ );
1512
+ const success = await _learnCard.invoke.storePresentationViaChapi(vp);
1513
+ if (success)
1514
+ return { success: true };
1515
+ return { success: false, reason: "did not store" };
1516
+ },
1517
+ storePresentationViaChapi: async (_learnCard, presentation) => {
1518
+ const wc = new WebCredential("VerifiablePresentation", presentation);
1519
+ return window.navigator.credentials.store(wc);
1520
+ }
1521
+ }
1522
+ };
1523
+ }, "getCHAPIPlugin");
1524
+ /*!
1525
+ * A CredentialHandlerRegistration provides a CredentialManager to enable Web
1526
+ * apps to register Profiles that can be presented to websites.
1527
+ *
1528
+ * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved.
1529
+ */
1530
+ /*!
1531
+ * A CredentialRequestEvent is emitted when a request has been made for
1532
+ * credentials.
1533
+ *
1534
+ * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved.
1535
+ */
1536
+ /*!
1537
+ * A CredentialStoreEvent is emitted when a request has been made to
1538
+ * store a credential.
1539
+ *
1540
+ * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved.
1541
+ */
1542
+ /*!
1543
+ * A WebApp is a remote application that runs in a WebAppContext.
1544
+ *
1545
+ * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved.
1546
+ */
1547
+ /*!
1548
+ * A WebCredential is a Credential that can be retrieved from or stored by a
1549
+ * "credential handler" that runs in a third party Web application.
1550
+ *
1551
+ * Copyright (c) 2017-2021 Digital Bazaar, Inc. All rights reserved.
1552
+ */
1553
+ /*!
1554
+ * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved.
1555
+ */
1556
+ /*!
1557
+ * Copyright (c) 2017-2018 Digital Bazaar, Inc. All rights reserved.
1558
+ */
1559
+ /*!
1560
+ * Copyright (c) 2017-2022 Digital Bazaar, Inc. All rights reserved.
1561
+ */
1562
+ /*!
1563
+ * Copyright (c) 2017-2023 Digital Bazaar, Inc. All rights reserved.
1564
+ */
1565
+ /*!
1566
+ * Copyright (c) 2018-2022 Digital Bazaar, Inc. All rights reserved.
1567
+ */
1568
+ /*!
1569
+ * Copyright (c) 2022 Digital Bazaar, Inc. All rights reserved.
1570
+ */
1571
+ /*!
1572
+ * Copyright (c) 2022-2023 Digital Bazaar, Inc. All rights reserved.
1573
+ */
1574
+ /*!
1575
+ * JSON-RPC for Web Request Polyfills.
1576
+ *
1577
+ * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved.
1578
+ */
1579
+ /*!
1580
+ * The core CredentialHandler class.
1581
+ *
1582
+ * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved.
1583
+ */
1584
+ /*!
1585
+ * Utilities for Web Request RPC.
1586
+ *
1587
+ * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved.
1588
+ */
1589
+ /*!
1590
+ * Wrapper for native CredentialsContainer that uses remote Credential Mediator
1591
+ * for WebCredential-related operations.
1592
+ *
1593
+ * Copyright (c) 2017-2018 Digital Bazaar, Inc. All rights reserved.
1594
+ */
1595
+ //# sourceMappingURL=chapi-plugin.cjs.development.js.map