@pezkuwi/extension-base 0.62.10 → 0.62.13

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.
Files changed (97) hide show
  1. package/LICENSE +201 -0
  2. package/background/RequestBytesSign.js +6 -9
  3. package/background/RequestExtrinsicSign.js +6 -9
  4. package/background/handlers/Extension.js +304 -460
  5. package/background/handlers/State.js +365 -619
  6. package/background/handlers/Tabs.js +155 -273
  7. package/background/handlers/helpers.js +1 -3
  8. package/background/handlers/index.js +17 -22
  9. package/background/handlers/subscriptions.js +5 -9
  10. package/background/index.js +0 -2
  11. package/background/types.js +0 -2
  12. package/bundle.js +0 -2
  13. package/cjs/background/RequestBytesSign.d.ts +12 -0
  14. package/cjs/background/RequestBytesSign.js +15 -0
  15. package/cjs/background/RequestExtrinsicSign.d.ts +12 -0
  16. package/cjs/background/RequestExtrinsicSign.js +14 -0
  17. package/cjs/background/handlers/Extension.d.ts +49 -0
  18. package/cjs/background/handlers/Extension.js +492 -0
  19. package/cjs/background/handlers/State.d.ts +96 -0
  20. package/cjs/background/handlers/State.js +482 -0
  21. package/cjs/background/handlers/Tabs.d.ts +25 -0
  22. package/cjs/background/handlers/Tabs.js +199 -0
  23. package/cjs/background/handlers/helpers.d.ts +1 -0
  24. package/cjs/background/handlers/helpers.js +14 -0
  25. package/cjs/background/handlers/index.d.ts +3 -0
  26. package/cjs/background/handlers/index.js +46 -0
  27. package/cjs/background/handlers/subscriptions.d.ts +3 -0
  28. package/cjs/background/handlers/subscriptions.js +22 -0
  29. package/cjs/background/index.d.ts +1 -0
  30. package/cjs/background/index.js +7 -0
  31. package/cjs/background/types.d.ts +343 -0
  32. package/cjs/background/types.js +2 -0
  33. package/cjs/bundle.d.ts +1 -0
  34. package/cjs/bundle.js +5 -0
  35. package/cjs/defaults.d.ts +9 -0
  36. package/cjs/defaults.js +16 -0
  37. package/cjs/index.d.ts +1 -0
  38. package/cjs/index.js +4 -0
  39. package/cjs/package.json +3 -0
  40. package/cjs/packageDetect.d.ts +1 -0
  41. package/cjs/packageDetect.js +8 -0
  42. package/cjs/packageInfo.d.ts +6 -0
  43. package/cjs/packageInfo.js +4 -0
  44. package/cjs/page/Accounts.d.ts +7 -0
  45. package/cjs/page/Accounts.js +24 -0
  46. package/cjs/page/Injected.d.ts +13 -0
  47. package/cjs/page/Injected.js +25 -0
  48. package/cjs/page/Metadata.d.ts +7 -0
  49. package/cjs/page/Metadata.js +15 -0
  50. package/cjs/page/PostMessageProvider.d.ts +63 -0
  51. package/cjs/page/PostMessageProvider.js +135 -0
  52. package/cjs/page/Signer.d.ts +8 -0
  53. package/cjs/page/Signer.js +29 -0
  54. package/cjs/page/index.d.ts +16 -0
  55. package/cjs/page/index.js +52 -0
  56. package/cjs/page/types.d.ts +6 -0
  57. package/cjs/page/types.js +2 -0
  58. package/cjs/stores/Accounts.d.ts +6 -0
  59. package/cjs/stores/Accounts.js +21 -0
  60. package/cjs/stores/Base.d.ts +9 -0
  61. package/cjs/stores/Base.js +70 -0
  62. package/cjs/stores/Metadata.d.ts +5 -0
  63. package/cjs/stores/Metadata.js +13 -0
  64. package/cjs/stores/index.d.ts +2 -0
  65. package/cjs/stores/index.js +8 -0
  66. package/cjs/types.d.ts +9 -0
  67. package/cjs/types.js +2 -0
  68. package/cjs/utils/canDerive.d.ts +2 -0
  69. package/cjs/utils/canDerive.js +6 -0
  70. package/cjs/utils/getId.d.ts +1 -0
  71. package/cjs/utils/getId.js +8 -0
  72. package/cjs/utils/index.d.ts +1 -0
  73. package/cjs/utils/index.js +5 -0
  74. package/cjs/utils/portUtils.d.ts +13 -0
  75. package/cjs/utils/portUtils.js +49 -0
  76. package/defaults.js +10 -14
  77. package/index.js +0 -4
  78. package/package.json +464 -10
  79. package/packageDetect.js +0 -4
  80. package/packageInfo.js +1 -4
  81. package/page/Accounts.js +13 -18
  82. package/page/Injected.js +10 -10
  83. package/page/Metadata.js +8 -13
  84. package/page/PostMessageProvider.js +90 -192
  85. package/page/Signer.js +24 -90
  86. package/page/index.js +15 -72
  87. package/page/types.js +0 -2
  88. package/stores/Accounts.js +14 -80
  89. package/stores/Base.js +57 -240
  90. package/stores/Metadata.js +6 -26
  91. package/stores/index.js +0 -2
  92. package/types.js +0 -2
  93. package/utils/canDerive.js +0 -2
  94. package/utils/getId.js +2 -4
  95. package/utils/index.js +0 -2
  96. package/utils/portUtils.d.ts +0 -1
  97. package/utils/portUtils.js +31 -94
@@ -1,73 +1,3 @@
1
- // Copyright 2019-2025 @pezkuwi/extension-bg authors & contributors
2
- // SPDX-License-Identifier: Apache-2.0
3
- var __assign = (this && this.__assign) || function () {
4
- __assign = Object.assign || function(t) {
5
- for (var s, i = 1, n = arguments.length; i < n; i++) {
6
- s = arguments[i];
7
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
8
- t[p] = s[p];
9
- }
10
- return t;
11
- };
12
- return __assign.apply(this, arguments);
13
- };
14
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
15
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
16
- return new (P || (P = Promise))(function (resolve, reject) {
17
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
18
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
19
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
20
- step((generator = generator.apply(thisArg, _arguments || [])).next());
21
- });
22
- };
23
- var __generator = (this && this.__generator) || function (thisArg, body) {
24
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
25
- return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
26
- function verb(n) { return function (v) { return step([n, v]); }; }
27
- function step(op) {
28
- if (f) throw new TypeError("Generator is already executing.");
29
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
30
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
31
- if (y = 0, t) op = [op[0] & 2, t.value];
32
- switch (op[0]) {
33
- case 0: case 1: t = op; break;
34
- case 4: _.label++; return { value: op[1], done: false };
35
- case 5: _.label++; y = op[1]; op = [0]; continue;
36
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
37
- default:
38
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
39
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
40
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
41
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
42
- if (t[2]) _.ops.pop();
43
- _.trys.pop(); continue;
44
- }
45
- op = body.call(thisArg, _);
46
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
47
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
48
- }
49
- };
50
- var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
51
- if (kind === "m") throw new TypeError("Private method is not writable");
52
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
53
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
54
- return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
55
- };
56
- var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
57
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
58
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
59
- return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
60
- };
61
- var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
62
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
63
- if (ar || !(i in from)) {
64
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
65
- ar[i] = from[i];
66
- }
67
- }
68
- return to.concat(ar || Array.prototype.slice.call(from));
69
- };
70
- var _State_authUrls, _State_lastRequestTimestamps, _State_maxEntries, _State_rateLimitInterval, _State_authRequests, _State_metaStore, _State_injectedProviders, _State_metaRequests, _State_notification, _State_providers, _State_signRequests, _State_windows, _State_connectedTabsUrl;
71
1
  import { BehaviorSubject } from 'rxjs';
72
2
  import { addMetadata, knownMetadata } from '@pezkuwi/extension-chains';
73
3
  import { knownGenesis } from '@pezkuwi/networks/defaults';
@@ -76,8 +6,8 @@ import { assert } from '@pezkuwi/util';
76
6
  import { MetadataStore } from '../../stores/index.js';
77
7
  import { getId } from '../../utils/getId.js';
78
8
  import { withErrorLog } from './helpers.js';
79
- var NOTIFICATION_URL = chrome.runtime.getURL('notification.html');
80
- var POPUP_WINDOW_OPTS = {
9
+ const NOTIFICATION_URL = chrome.runtime.getURL('notification.html');
10
+ const POPUP_WINDOW_OPTS = {
81
11
  focused: true,
82
12
  height: 621,
83
13
  left: 150,
@@ -86,7 +16,7 @@ var POPUP_WINDOW_OPTS = {
86
16
  url: NOTIFICATION_URL,
87
17
  width: 560
88
18
  };
89
- var NORMAL_WINDOW_OPTS = {
19
+ const NORMAL_WINDOW_OPTS = {
90
20
  focused: true,
91
21
  type: 'normal',
92
22
  url: NOTIFICATION_URL
@@ -97,412 +27,254 @@ export var NotificationOptions;
97
27
  NotificationOptions[NotificationOptions["Normal"] = 1] = "Normal";
98
28
  NotificationOptions[NotificationOptions["PopUp"] = 2] = "PopUp";
99
29
  })(NotificationOptions || (NotificationOptions = {}));
100
- var AUTH_URLS_KEY = 'authUrls';
101
- var DEFAULT_AUTH_ACCOUNTS = 'defaultAuthAccounts';
102
- function extractMetadata(store) {
103
- return __awaiter(this, void 0, void 0, function () {
104
- var _this = this;
105
- return __generator(this, function (_a) {
106
- switch (_a.label) {
107
- case 0: return [4 /*yield*/, store.allMap(function (map) { return __awaiter(_this, void 0, void 0, function () {
108
- var knownEntries, defs, removals, _i, removals_1, key;
109
- return __generator(this, function (_a) {
110
- switch (_a.label) {
111
- case 0:
112
- knownEntries = Object.entries(knownGenesis);
113
- defs = {};
114
- removals = [];
115
- Object
116
- .entries(map)
117
- .forEach(function (_a) {
118
- var key = _a[0], def = _a[1];
119
- var entry = knownEntries.find(function (_a) {
120
- var hashes = _a[1];
121
- return hashes.includes(def.genesisHash);
122
- });
123
- if (entry) {
124
- var name_1 = entry[0], hashes = entry[1];
125
- var index = hashes.indexOf(def.genesisHash);
126
- // flatten the known metadata based on the genesis index
127
- // (lower is better/newer)
128
- if (!defs[name_1] || (defs[name_1].index > index)) {
129
- if (defs[name_1]) {
130
- // remove the old version of the metadata
131
- removals.push(defs[name_1].key);
132
- }
133
- defs[name_1] = { def: def, index: index, key: key };
134
- }
135
- }
136
- else {
137
- // this is not a known entry, so we will just apply it
138
- defs[key] = { def: def, index: 0, key: key };
139
- }
140
- });
141
- _i = 0, removals_1 = removals;
142
- _a.label = 1;
143
- case 1:
144
- if (!(_i < removals_1.length)) return [3 /*break*/, 4];
145
- key = removals_1[_i];
146
- return [4 /*yield*/, store.remove(key)];
147
- case 2:
148
- _a.sent();
149
- _a.label = 3;
150
- case 3:
151
- _i++;
152
- return [3 /*break*/, 1];
153
- case 4:
154
- Object.values(defs).forEach(function (_a) {
155
- var def = _a.def;
156
- return addMetadata(def);
157
- });
158
- return [2 /*return*/];
159
- }
160
- });
161
- }); })];
162
- case 1:
163
- _a.sent();
164
- return [2 /*return*/];
30
+ const AUTH_URLS_KEY = 'authUrls';
31
+ const DEFAULT_AUTH_ACCOUNTS = 'defaultAuthAccounts';
32
+ async function extractMetadata(store) {
33
+ await store.allMap(async (map) => {
34
+ const knownEntries = Object.entries(knownGenesis);
35
+ const defs = {};
36
+ const removals = [];
37
+ Object
38
+ .entries(map)
39
+ .forEach(([key, def]) => {
40
+ const entry = knownEntries.find(([, hashes]) => hashes.includes(def.genesisHash));
41
+ if (entry) {
42
+ const [name, hashes] = entry;
43
+ const index = hashes.indexOf(def.genesisHash);
44
+ // flatten the known metadata based on the genesis index
45
+ // (lower is better/newer)
46
+ if (!defs[name] || (defs[name].index > index)) {
47
+ if (defs[name]) {
48
+ // remove the old version of the metadata
49
+ removals.push(defs[name].key);
50
+ }
51
+ defs[name] = { def, index, key };
52
+ }
53
+ }
54
+ else {
55
+ // this is not a known entry, so we will just apply it
56
+ defs[key] = { def, index: 0, key };
165
57
  }
166
58
  });
59
+ for (const key of removals) {
60
+ await store.remove(key);
61
+ }
62
+ Object.values(defs).forEach(({ def }) => addMetadata(def));
167
63
  });
168
64
  }
169
- var State = /** @class */ (function () {
170
- function State(providers, rateLimitInterval) {
171
- if (providers === void 0) { providers = {}; }
172
- if (rateLimitInterval === void 0) { rateLimitInterval = 3000; }
173
- var _this = this;
174
- _State_authUrls.set(this, new Map());
175
- _State_lastRequestTimestamps.set(this, new Map());
176
- _State_maxEntries.set(this, 10);
177
- _State_rateLimitInterval.set(this, 3000); // 3 seconds
178
- _State_authRequests.set(this, {});
179
- _State_metaStore.set(this, new MetadataStore());
180
- // Map of providers currently injected in tabs
181
- _State_injectedProviders.set(this, new Map());
182
- _State_metaRequests.set(this, {});
183
- _State_notification.set(this, settings.notification);
184
- // Map of all providers exposed by the extension, they are retrievable by key
185
- _State_providers.set(this, void 0);
186
- _State_signRequests.set(this, {});
187
- _State_windows.set(this, []);
188
- _State_connectedTabsUrl.set(this, []);
189
- this.authSubject = new BehaviorSubject([]);
190
- this.metaSubject = new BehaviorSubject([]);
191
- this.signSubject = new BehaviorSubject([]);
192
- this.authUrlSubjects = {};
193
- this.defaultAuthAccountSelection = [];
194
- this.authComplete = function (id, resolve, reject) {
195
- var complete = function () {
196
- var args_1 = [];
197
- for (var _i = 0; _i < arguments.length; _i++) {
198
- args_1[_i] = arguments[_i];
199
- }
200
- return __awaiter(_this, __spreadArray([], args_1, true), void 0, function (authorizedAccounts) {
201
- var _a, idStr, origin, url, strippedUrl, authInfo;
202
- if (authorizedAccounts === void 0) { authorizedAccounts = []; }
203
- return __generator(this, function (_b) {
204
- switch (_b.label) {
205
- case 0:
206
- _a = __classPrivateFieldGet(this, _State_authRequests, "f")[id], idStr = _a.idStr, origin = _a.request.origin, url = _a.url;
207
- strippedUrl = this.stripUrl(url);
208
- authInfo = {
209
- authorizedAccounts: authorizedAccounts,
210
- count: 0,
211
- id: idStr,
212
- origin: origin,
213
- url: url
214
- };
215
- __classPrivateFieldGet(this, _State_authUrls, "f").set(strippedUrl, authInfo);
216
- if (!this.authUrlSubjects[strippedUrl]) {
217
- this.authUrlSubjects[strippedUrl] = new BehaviorSubject(authInfo);
218
- }
219
- else {
220
- this.authUrlSubjects[strippedUrl].next(authInfo);
221
- }
222
- return [4 /*yield*/, this.saveCurrentAuthList()];
223
- case 1:
224
- _b.sent();
225
- return [4 /*yield*/, this.updateDefaultAuthAccounts(authorizedAccounts)];
226
- case 2:
227
- _b.sent();
228
- delete __classPrivateFieldGet(this, _State_authRequests, "f")[id];
229
- this.updateIconAuth(true);
230
- return [2 /*return*/];
231
- }
232
- });
233
- });
234
- };
235
- return {
236
- // eslint-disable-next-line @typescript-eslint/no-misused-promises
237
- reject: function (error) { return __awaiter(_this, void 0, void 0, function () {
238
- return __generator(this, function (_a) {
239
- switch (_a.label) {
240
- case 0:
241
- if (!(error.message === 'Cancelled')) return [3 /*break*/, 1];
242
- delete __classPrivateFieldGet(this, _State_authRequests, "f")[id];
243
- this.updateIconAuth(true);
244
- reject(new Error('Connection request was cancelled by the user.'));
245
- return [3 /*break*/, 3];
246
- case 1: return [4 /*yield*/, complete()];
247
- case 2:
248
- _a.sent();
249
- reject(new Error('Connection request was rejected by the user.'));
250
- _a.label = 3;
251
- case 3: return [2 /*return*/];
252
- }
253
- });
254
- }); },
255
- // eslint-disable-next-line @typescript-eslint/no-misused-promises
256
- resolve: function (_a) { return __awaiter(_this, [_a], void 0, function (_b) {
257
- var authorizedAccounts = _b.authorizedAccounts, result = _b.result;
258
- return __generator(this, function (_c) {
259
- switch (_c.label) {
260
- case 0: return [4 /*yield*/, complete(authorizedAccounts)];
261
- case 1:
262
- _c.sent();
263
- resolve({ authorizedAccounts: authorizedAccounts, result: result });
264
- return [2 /*return*/];
265
- }
266
- });
267
- }); }
268
- };
269
- };
270
- this.metaComplete = function (id, resolve, reject) {
271
- var complete = function () {
272
- delete __classPrivateFieldGet(_this, _State_metaRequests, "f")[id];
273
- _this.updateIconMeta(true);
274
- };
275
- return {
276
- reject: function (error) {
277
- complete();
278
- reject(error);
279
- },
280
- resolve: function (result) {
281
- complete();
282
- resolve(result);
283
- }
284
- };
285
- };
286
- this.signComplete = function (id, resolve, reject) {
287
- var complete = function () {
288
- delete __classPrivateFieldGet(_this, _State_signRequests, "f")[id];
289
- _this.updateIconSign(true);
290
- };
291
- return {
292
- reject: function (error) {
293
- complete();
294
- reject(error);
295
- },
296
- resolve: function (result) {
297
- complete();
298
- resolve(result);
299
- }
300
- };
301
- };
65
+ export default class State {
66
+ #authUrls = new Map();
67
+ #lastRequestTimestamps = new Map();
68
+ #maxEntries = 10;
69
+ #rateLimitInterval = 3000; // 3 seconds
70
+ #authRequests = {};
71
+ #metaStore = new MetadataStore();
72
+ // Map of providers currently injected in tabs
73
+ #injectedProviders = new Map();
74
+ #metaRequests = {};
75
+ #notification = settings.notification;
76
+ // Map of all providers exposed by the extension, they are retrievable by key
77
+ #providers;
78
+ #signRequests = {};
79
+ #windows = [];
80
+ #connectedTabsUrl = [];
81
+ authSubject = new BehaviorSubject([]);
82
+ metaSubject = new BehaviorSubject([]);
83
+ signSubject = new BehaviorSubject([]);
84
+ authUrlSubjects = {};
85
+ defaultAuthAccountSelection = [];
86
+ constructor(providers = {}, rateLimitInterval = 3000) {
302
87
  assert(rateLimitInterval >= 0, 'Expects non-negative number for rateLimitInterval');
303
- __classPrivateFieldSet(this, _State_providers, providers, "f");
304
- __classPrivateFieldSet(this, _State_rateLimitInterval, rateLimitInterval, "f");
305
- }
306
- State.prototype.init = function () {
307
- return __awaiter(this, void 0, void 0, function () {
308
- var storageAuthUrls, authString, previousAuth, storageDefaultAuthAccounts, defaultAuthString, previousDefaultAuth;
309
- var _this = this;
310
- return __generator(this, function (_a) {
311
- switch (_a.label) {
312
- case 0: return [4 /*yield*/, extractMetadata(__classPrivateFieldGet(this, _State_metaStore, "f"))];
313
- case 1:
314
- _a.sent();
315
- return [4 /*yield*/, chrome.storage.local.get(AUTH_URLS_KEY)];
316
- case 2:
317
- storageAuthUrls = _a.sent();
318
- authString = (storageAuthUrls === null || storageAuthUrls === void 0 ? void 0 : storageAuthUrls[AUTH_URLS_KEY]) || '{}';
319
- previousAuth = JSON.parse(authString);
320
- __classPrivateFieldSet(this, _State_authUrls, new Map(Object.entries(previousAuth)), "f");
321
- // Initialize authUrlSubjects for each URL
322
- __classPrivateFieldGet(this, _State_authUrls, "f").forEach(function (authInfo, url) {
323
- _this.authUrlSubjects[url] = new BehaviorSubject(authInfo);
324
- });
325
- return [4 /*yield*/, chrome.storage.local.get(DEFAULT_AUTH_ACCOUNTS)];
326
- case 3:
327
- storageDefaultAuthAccounts = _a.sent();
328
- defaultAuthString = (storageDefaultAuthAccounts === null || storageDefaultAuthAccounts === void 0 ? void 0 : storageDefaultAuthAccounts[DEFAULT_AUTH_ACCOUNTS]) || '[]';
329
- previousDefaultAuth = JSON.parse(defaultAuthString);
330
- this.defaultAuthAccountSelection = previousDefaultAuth;
331
- return [2 /*return*/];
332
- }
333
- });
334
- });
335
- };
336
- Object.defineProperty(State.prototype, "knownMetadata", {
337
- get: function () {
338
- return knownMetadata();
339
- },
340
- enumerable: false,
341
- configurable: true
342
- });
343
- Object.defineProperty(State.prototype, "numAuthRequests", {
344
- get: function () {
345
- return Object.keys(__classPrivateFieldGet(this, _State_authRequests, "f")).length;
346
- },
347
- enumerable: false,
348
- configurable: true
349
- });
350
- Object.defineProperty(State.prototype, "numMetaRequests", {
351
- get: function () {
352
- return Object.keys(__classPrivateFieldGet(this, _State_metaRequests, "f")).length;
353
- },
354
- enumerable: false,
355
- configurable: true
356
- });
357
- Object.defineProperty(State.prototype, "numSignRequests", {
358
- get: function () {
359
- return Object.keys(__classPrivateFieldGet(this, _State_signRequests, "f")).length;
360
- },
361
- enumerable: false,
362
- configurable: true
363
- });
364
- Object.defineProperty(State.prototype, "allAuthRequests", {
365
- get: function () {
366
- return Object
367
- .values(__classPrivateFieldGet(this, _State_authRequests, "f"))
368
- .map(function (_a) {
369
- var id = _a.id, request = _a.request, url = _a.url;
370
- return ({ id: id, request: request, url: url });
371
- });
372
- },
373
- enumerable: false,
374
- configurable: true
375
- });
376
- Object.defineProperty(State.prototype, "allMetaRequests", {
377
- get: function () {
378
- return Object
379
- .values(__classPrivateFieldGet(this, _State_metaRequests, "f"))
380
- .map(function (_a) {
381
- var id = _a.id, request = _a.request, url = _a.url;
382
- return ({ id: id, request: request, url: url });
383
- });
384
- },
385
- enumerable: false,
386
- configurable: true
387
- });
388
- Object.defineProperty(State.prototype, "allSignRequests", {
389
- get: function () {
390
- return Object
391
- .values(__classPrivateFieldGet(this, _State_signRequests, "f"))
392
- .map(function (_a) {
393
- var account = _a.account, id = _a.id, request = _a.request, url = _a.url;
394
- return ({ account: account, id: id, request: request, url: url });
395
- });
396
- },
397
- enumerable: false,
398
- configurable: true
399
- });
400
- Object.defineProperty(State.prototype, "authUrls", {
401
- get: function () {
402
- return Object.fromEntries(__classPrivateFieldGet(this, _State_authUrls, "f"));
403
- },
404
- enumerable: false,
405
- configurable: true
406
- });
407
- State.prototype.popupClose = function () {
408
- __classPrivateFieldGet(this, _State_windows, "f").forEach(function (id) {
409
- return withErrorLog(function () { return chrome.windows.remove(id); });
88
+ this.#providers = providers;
89
+ this.#rateLimitInterval = rateLimitInterval;
90
+ }
91
+ async init() {
92
+ await extractMetadata(this.#metaStore);
93
+ // retrieve previously set authorizations
94
+ const storageAuthUrls = await chrome.storage.local.get(AUTH_URLS_KEY);
95
+ const authString = storageAuthUrls?.[AUTH_URLS_KEY] || '{}';
96
+ const previousAuth = JSON.parse(authString);
97
+ this.#authUrls = new Map(Object.entries(previousAuth));
98
+ // Initialize authUrlSubjects for each URL
99
+ this.#authUrls.forEach((authInfo, url) => {
100
+ this.authUrlSubjects[url] = new BehaviorSubject(authInfo);
410
101
  });
411
- __classPrivateFieldSet(this, _State_windows, [], "f");
412
- };
413
- State.prototype.popupOpen = function () {
414
- var _this = this;
415
- __classPrivateFieldGet(this, _State_notification, "f") !== 'extension' &&
416
- chrome.windows.create(__classPrivateFieldGet(this, _State_notification, "f") === 'window'
102
+ // retrieve previously set default auth accounts
103
+ const storageDefaultAuthAccounts = await chrome.storage.local.get(DEFAULT_AUTH_ACCOUNTS);
104
+ const defaultAuthString = storageDefaultAuthAccounts?.[DEFAULT_AUTH_ACCOUNTS] || '[]';
105
+ const previousDefaultAuth = JSON.parse(defaultAuthString);
106
+ this.defaultAuthAccountSelection = previousDefaultAuth;
107
+ }
108
+ get knownMetadata() {
109
+ return knownMetadata();
110
+ }
111
+ get numAuthRequests() {
112
+ return Object.keys(this.#authRequests).length;
113
+ }
114
+ get numMetaRequests() {
115
+ return Object.keys(this.#metaRequests).length;
116
+ }
117
+ get numSignRequests() {
118
+ return Object.keys(this.#signRequests).length;
119
+ }
120
+ get allAuthRequests() {
121
+ return Object
122
+ .values(this.#authRequests)
123
+ .map(({ id, request, url }) => ({ id, request, url }));
124
+ }
125
+ get allMetaRequests() {
126
+ return Object
127
+ .values(this.#metaRequests)
128
+ .map(({ id, request, url }) => ({ id, request, url }));
129
+ }
130
+ get allSignRequests() {
131
+ return Object
132
+ .values(this.#signRequests)
133
+ .map(({ account, id, request, url }) => ({ account, id, request, url }));
134
+ }
135
+ get authUrls() {
136
+ return Object.fromEntries(this.#authUrls);
137
+ }
138
+ popupClose() {
139
+ this.#windows.forEach((id) => withErrorLog(() => chrome.windows.remove(id)));
140
+ this.#windows = [];
141
+ }
142
+ popupOpen() {
143
+ this.#notification !== 'extension' &&
144
+ chrome.windows.create(this.#notification === 'window'
417
145
  ? NORMAL_WINDOW_OPTS
418
- : POPUP_WINDOW_OPTS, function (window) {
146
+ : POPUP_WINDOW_OPTS, (window) => {
419
147
  if (window) {
420
- __classPrivateFieldGet(_this, _State_windows, "f").push(window.id || 0);
148
+ this.#windows.push(window.id || 0);
421
149
  }
422
150
  });
151
+ }
152
+ authComplete = (id, resolve, reject) => {
153
+ const complete = async (authorizedAccounts = []) => {
154
+ const { idStr, request: { origin }, url } = this.#authRequests[id];
155
+ const strippedUrl = this.stripUrl(url);
156
+ const authInfo = {
157
+ authorizedAccounts,
158
+ count: 0,
159
+ id: idStr,
160
+ origin,
161
+ url
162
+ };
163
+ this.#authUrls.set(strippedUrl, authInfo);
164
+ if (!this.authUrlSubjects[strippedUrl]) {
165
+ this.authUrlSubjects[strippedUrl] = new BehaviorSubject(authInfo);
166
+ }
167
+ else {
168
+ this.authUrlSubjects[strippedUrl].next(authInfo);
169
+ }
170
+ await this.saveCurrentAuthList();
171
+ await this.updateDefaultAuthAccounts(authorizedAccounts);
172
+ delete this.#authRequests[id];
173
+ this.updateIconAuth(true);
174
+ };
175
+ return {
176
+ // eslint-disable-next-line @typescript-eslint/no-misused-promises
177
+ reject: async (error) => {
178
+ if (error.message === 'Cancelled') {
179
+ delete this.#authRequests[id];
180
+ this.updateIconAuth(true);
181
+ reject(new Error('Connection request was cancelled by the user.'));
182
+ }
183
+ else {
184
+ await complete();
185
+ reject(new Error('Connection request was rejected by the user.'));
186
+ }
187
+ },
188
+ // eslint-disable-next-line @typescript-eslint/no-misused-promises
189
+ resolve: async ({ authorizedAccounts, result }) => {
190
+ await complete(authorizedAccounts);
191
+ resolve({ authorizedAccounts, result });
192
+ }
193
+ };
423
194
  };
424
195
  /**
425
196
  * @deprecated This method is deprecated in favor of {@link updateCurrentTabs} and will be removed in a future release.
426
197
  */
427
- State.prototype.udateCurrentTabsUrl = function (urls) {
198
+ udateCurrentTabsUrl(urls) {
428
199
  this.updateCurrentTabsUrl(urls);
429
- };
430
- State.prototype.updateCurrentTabsUrl = function (urls) {
431
- var _this = this;
432
- var connectedTabs = urls.map(function (url) {
433
- var strippedUrl = '';
200
+ }
201
+ updateCurrentTabsUrl(urls) {
202
+ const connectedTabs = urls.map((url) => {
203
+ let strippedUrl = '';
434
204
  // the assert in stripUrl may throw for new tabs with "chrome://newtab/"
435
205
  try {
436
- strippedUrl = _this.stripUrl(url);
206
+ strippedUrl = this.stripUrl(url);
437
207
  }
438
208
  catch (e) {
439
209
  console.error(e);
440
210
  }
441
211
  // return the stripped url only if this website is known
442
- return !!strippedUrl && _this.authUrls[strippedUrl]
212
+ return !!strippedUrl && this.authUrls[strippedUrl]
443
213
  ? strippedUrl
444
214
  : undefined;
445
215
  })
446
- .filter(function (value) { return !!value; });
447
- __classPrivateFieldSet(this, _State_connectedTabsUrl, connectedTabs, "f");
448
- };
449
- State.prototype.getConnectedTabsUrl = function () {
450
- return __classPrivateFieldGet(this, _State_connectedTabsUrl, "f");
451
- };
452
- State.prototype.deleteAuthRequest = function (requestId) {
453
- delete __classPrivateFieldGet(this, _State_authRequests, "f")[requestId];
216
+ .filter((value) => !!value);
217
+ this.#connectedTabsUrl = connectedTabs;
218
+ }
219
+ getConnectedTabsUrl() {
220
+ return this.#connectedTabsUrl;
221
+ }
222
+ deleteAuthRequest(requestId) {
223
+ delete this.#authRequests[requestId];
454
224
  this.updateIconAuth(true);
225
+ }
226
+ async saveCurrentAuthList() {
227
+ await chrome.storage.local.set({ [AUTH_URLS_KEY]: JSON.stringify(Object.fromEntries(this.#authUrls)) });
228
+ }
229
+ async saveDefaultAuthAccounts() {
230
+ await chrome.storage.local.set({ [DEFAULT_AUTH_ACCOUNTS]: JSON.stringify(this.defaultAuthAccountSelection) });
231
+ }
232
+ async updateDefaultAuthAccounts(newList) {
233
+ this.defaultAuthAccountSelection = newList;
234
+ await this.saveDefaultAuthAccounts();
235
+ }
236
+ metaComplete = (id, resolve, reject) => {
237
+ const complete = () => {
238
+ delete this.#metaRequests[id];
239
+ this.updateIconMeta(true);
240
+ };
241
+ return {
242
+ reject: (error) => {
243
+ complete();
244
+ reject(error);
245
+ },
246
+ resolve: (result) => {
247
+ complete();
248
+ resolve(result);
249
+ }
250
+ };
455
251
  };
456
- State.prototype.saveCurrentAuthList = function () {
457
- return __awaiter(this, void 0, void 0, function () {
458
- var _a;
459
- return __generator(this, function (_b) {
460
- switch (_b.label) {
461
- case 0: return [4 /*yield*/, chrome.storage.local.set((_a = {}, _a[AUTH_URLS_KEY] = JSON.stringify(Object.fromEntries(__classPrivateFieldGet(this, _State_authUrls, "f"))), _a))];
462
- case 1:
463
- _b.sent();
464
- return [2 /*return*/];
465
- }
466
- });
467
- });
468
- };
469
- State.prototype.saveDefaultAuthAccounts = function () {
470
- return __awaiter(this, void 0, void 0, function () {
471
- var _a;
472
- return __generator(this, function (_b) {
473
- switch (_b.label) {
474
- case 0: return [4 /*yield*/, chrome.storage.local.set((_a = {}, _a[DEFAULT_AUTH_ACCOUNTS] = JSON.stringify(this.defaultAuthAccountSelection), _a))];
475
- case 1:
476
- _b.sent();
477
- return [2 /*return*/];
478
- }
479
- });
480
- });
481
- };
482
- State.prototype.updateDefaultAuthAccounts = function (newList) {
483
- return __awaiter(this, void 0, void 0, function () {
484
- return __generator(this, function (_a) {
485
- switch (_a.label) {
486
- case 0:
487
- this.defaultAuthAccountSelection = newList;
488
- return [4 /*yield*/, this.saveDefaultAuthAccounts()];
489
- case 1:
490
- _a.sent();
491
- return [2 /*return*/];
492
- }
493
- });
494
- });
252
+ signComplete = (id, resolve, reject) => {
253
+ const complete = () => {
254
+ delete this.#signRequests[id];
255
+ this.updateIconSign(true);
256
+ };
257
+ return {
258
+ reject: (error) => {
259
+ complete();
260
+ reject(error);
261
+ },
262
+ resolve: (result) => {
263
+ complete();
264
+ resolve(result);
265
+ }
266
+ };
495
267
  };
496
- State.prototype.stripUrl = function (url) {
268
+ stripUrl(url) {
497
269
  try {
498
- var parsedUrl = new URL(url);
270
+ const parsedUrl = new URL(url);
499
271
  if (!['http:', 'https:', 'ipfs:', 'ipns:'].includes(parsedUrl.protocol)) {
500
- throw new Error("Invalid protocol ".concat(parsedUrl.protocol));
272
+ throw new Error(`Invalid protocol ${parsedUrl.protocol}`);
501
273
  }
502
274
  // For ipfs/ipns which don't have a standard origin, we handle it differently.
503
275
  if (parsedUrl.protocol === 'ipfs:' || parsedUrl.protocol === 'ipns:') {
504
276
  // ipfs://<hash> | ipns://<hash>
505
- return "".concat(parsedUrl.protocol, "//").concat(parsedUrl.hostname);
277
+ return `${parsedUrl.protocol}//${parsedUrl.hostname}`;
506
278
  }
507
279
  return parsedUrl.origin;
508
280
  }
@@ -510,223 +282,197 @@ var State = /** @class */ (function () {
510
282
  console.error(e);
511
283
  throw new Error('Invalid URL');
512
284
  }
513
- };
514
- State.prototype.updateIcon = function (shouldClose) {
515
- var authCount = this.numAuthRequests;
516
- var metaCount = this.numMetaRequests;
517
- var signCount = this.numSignRequests;
518
- var text = (authCount
285
+ }
286
+ updateIcon(shouldClose) {
287
+ const authCount = this.numAuthRequests;
288
+ const metaCount = this.numMetaRequests;
289
+ const signCount = this.numSignRequests;
290
+ const text = (authCount
519
291
  ? 'Auth'
520
292
  : metaCount
521
293
  ? 'Meta'
522
- : (signCount ? "".concat(signCount) : ''));
523
- withErrorLog(function () { return chrome.action.setBadgeText({ text: text }); });
294
+ : (signCount ? `${signCount}` : ''));
295
+ withErrorLog(() => chrome.action.setBadgeText({ text }));
524
296
  if (shouldClose && text === '') {
525
297
  this.popupClose();
526
298
  }
527
- };
528
- State.prototype.removeAuthorization = function (url) {
529
- return __awaiter(this, void 0, void 0, function () {
530
- var entry;
531
- return __generator(this, function (_a) {
532
- switch (_a.label) {
533
- case 0:
534
- entry = __classPrivateFieldGet(this, _State_authUrls, "f").get(url);
535
- assert(entry, "The source ".concat(url, " is not known"));
536
- __classPrivateFieldGet(this, _State_authUrls, "f").delete(url);
537
- return [4 /*yield*/, this.saveCurrentAuthList()];
538
- case 1:
539
- _a.sent();
540
- if (this.authUrlSubjects[url]) {
541
- entry.authorizedAccounts = [];
542
- this.authUrlSubjects[url].next(entry);
543
- }
544
- return [2 /*return*/, this.authUrls];
545
- }
546
- });
547
- });
548
- };
549
- State.prototype.updateIconAuth = function (shouldClose) {
299
+ }
300
+ async removeAuthorization(url) {
301
+ const entry = this.#authUrls.get(url);
302
+ assert(entry, `The source ${url} is not known`);
303
+ this.#authUrls.delete(url);
304
+ await this.saveCurrentAuthList();
305
+ if (this.authUrlSubjects[url]) {
306
+ entry.authorizedAccounts = [];
307
+ this.authUrlSubjects[url].next(entry);
308
+ }
309
+ return this.authUrls;
310
+ }
311
+ updateIconAuth(shouldClose) {
550
312
  this.authSubject.next(this.allAuthRequests);
551
313
  this.updateIcon(shouldClose);
552
- };
553
- State.prototype.updateIconMeta = function (shouldClose) {
314
+ }
315
+ updateIconMeta(shouldClose) {
554
316
  this.metaSubject.next(this.allMetaRequests);
555
317
  this.updateIcon(shouldClose);
556
- };
557
- State.prototype.updateIconSign = function (shouldClose) {
318
+ }
319
+ updateIconSign(shouldClose) {
558
320
  this.signSubject.next(this.allSignRequests);
559
321
  this.updateIcon(shouldClose);
560
- };
561
- State.prototype.updateAuthorizedAccounts = function (authorizedAccountsDiff) {
562
- return __awaiter(this, void 0, void 0, function () {
563
- var _this = this;
564
- return __generator(this, function (_a) {
565
- switch (_a.label) {
566
- case 0:
567
- authorizedAccountsDiff.forEach(function (_a) {
568
- var url = _a[0], authorizedAccountDiff = _a[1];
569
- var authInfo = __classPrivateFieldGet(_this, _State_authUrls, "f").get(url);
570
- if (authInfo) {
571
- authInfo.authorizedAccounts = authorizedAccountDiff;
572
- __classPrivateFieldGet(_this, _State_authUrls, "f").set(url, authInfo);
573
- _this.authUrlSubjects[url].next(authInfo);
574
- }
575
- });
576
- return [4 /*yield*/, this.saveCurrentAuthList()];
577
- case 1:
578
- _a.sent();
579
- return [2 /*return*/];
580
- }
581
- });
322
+ }
323
+ async updateAuthorizedAccounts(authorizedAccountsDiff) {
324
+ authorizedAccountsDiff.forEach(([url, authorizedAccountDiff]) => {
325
+ const authInfo = this.#authUrls.get(url);
326
+ if (authInfo) {
327
+ authInfo.authorizedAccounts = authorizedAccountDiff;
328
+ this.#authUrls.set(url, authInfo);
329
+ this.authUrlSubjects[url].next(authInfo);
330
+ }
582
331
  });
583
- };
584
- State.prototype.authorizeUrl = function (url, request) {
585
- return __awaiter(this, void 0, void 0, function () {
586
- var idStr, isDuplicate, authInfo;
587
- var _this = this;
588
- return __generator(this, function (_a) {
589
- idStr = this.stripUrl(url);
590
- isDuplicate = Object
591
- .values(__classPrivateFieldGet(this, _State_authRequests, "f"))
592
- .some(function (request) { return request.idStr === idStr; });
593
- assert(!isDuplicate, "The source ".concat(url, " has a pending authorization request"));
594
- if (__classPrivateFieldGet(this, _State_authUrls, "f").has(idStr)) {
595
- authInfo = __classPrivateFieldGet(this, _State_authUrls, "f").get(idStr);
596
- assert((authInfo === null || authInfo === void 0 ? void 0 : authInfo.authorizedAccounts) || (authInfo === null || authInfo === void 0 ? void 0 : authInfo.isAllowed), "The source ".concat(url, " is not allowed to interact with this extension"));
597
- return [2 /*return*/, {
598
- authorizedAccounts: [],
599
- result: false
600
- }];
601
- }
602
- return [2 /*return*/, new Promise(function (resolve, reject) {
603
- var id = getId();
604
- __classPrivateFieldGet(_this, _State_authRequests, "f")[id] = __assign(__assign({}, _this.authComplete(id, resolve, reject)), { id: id, idStr: idStr, request: request, url: url });
605
- _this.updateIconAuth();
606
- _this.popupOpen();
607
- })];
608
- });
332
+ await this.saveCurrentAuthList();
333
+ }
334
+ async authorizeUrl(url, request) {
335
+ const idStr = this.stripUrl(url);
336
+ // Do not enqueue duplicate authorization requests.
337
+ const isDuplicate = Object
338
+ .values(this.#authRequests)
339
+ .some((request) => request.idStr === idStr);
340
+ assert(!isDuplicate, `The source ${url} has a pending authorization request`);
341
+ if (this.#authUrls.has(idStr)) {
342
+ // this url was seen in the past
343
+ const authInfo = this.#authUrls.get(idStr);
344
+ assert(authInfo?.authorizedAccounts || authInfo?.isAllowed, `The source ${url} is not allowed to interact with this extension`);
345
+ return {
346
+ authorizedAccounts: [],
347
+ result: false
348
+ };
349
+ }
350
+ return new Promise((resolve, reject) => {
351
+ const id = getId();
352
+ this.#authRequests[id] = {
353
+ ...this.authComplete(id, resolve, reject),
354
+ id,
355
+ idStr,
356
+ request,
357
+ url
358
+ };
359
+ this.updateIconAuth();
360
+ this.popupOpen();
609
361
  });
610
- };
611
- State.prototype.ensureUrlAuthorized = function (url) {
612
- var entry = __classPrivateFieldGet(this, _State_authUrls, "f").get(this.stripUrl(url));
613
- assert(entry, "The source ".concat(url, " has not been enabled yet"));
362
+ }
363
+ ensureUrlAuthorized(url) {
364
+ const entry = this.#authUrls.get(this.stripUrl(url));
365
+ assert(entry, `The source ${url} has not been enabled yet`);
614
366
  return true;
615
- };
616
- State.prototype.injectMetadata = function (url, request) {
617
- var _this = this;
618
- return new Promise(function (resolve, reject) {
619
- var id = getId();
620
- __classPrivateFieldGet(_this, _State_metaRequests, "f")[id] = __assign(__assign({}, _this.metaComplete(id, resolve, reject)), { id: id, request: request, url: url });
621
- _this.updateIconMeta();
622
- _this.popupOpen();
367
+ }
368
+ injectMetadata(url, request) {
369
+ return new Promise((resolve, reject) => {
370
+ const id = getId();
371
+ this.#metaRequests[id] = {
372
+ ...this.metaComplete(id, resolve, reject),
373
+ id,
374
+ request,
375
+ url
376
+ };
377
+ this.updateIconMeta();
378
+ this.popupOpen();
623
379
  });
624
- };
625
- State.prototype.getAuthRequest = function (id) {
626
- return __classPrivateFieldGet(this, _State_authRequests, "f")[id];
627
- };
628
- State.prototype.getMetaRequest = function (id) {
629
- return __classPrivateFieldGet(this, _State_metaRequests, "f")[id];
630
- };
631
- State.prototype.getSignRequest = function (id) {
632
- return __classPrivateFieldGet(this, _State_signRequests, "f")[id];
633
- };
380
+ }
381
+ getAuthRequest(id) {
382
+ return this.#authRequests[id];
383
+ }
384
+ getMetaRequest(id) {
385
+ return this.#metaRequests[id];
386
+ }
387
+ getSignRequest(id) {
388
+ return this.#signRequests[id];
389
+ }
634
390
  // List all providers the extension is exposing
635
- State.prototype.rpcListProviders = function () {
636
- var _this = this;
637
- return Promise.resolve(Object.keys(__classPrivateFieldGet(this, _State_providers, "f")).reduce(function (acc, key) {
638
- acc[key] = __classPrivateFieldGet(_this, _State_providers, "f")[key].meta;
391
+ rpcListProviders() {
392
+ return Promise.resolve(Object.keys(this.#providers).reduce((acc, key) => {
393
+ acc[key] = this.#providers[key].meta;
639
394
  return acc;
640
395
  }, {}));
641
- };
642
- State.prototype.rpcSend = function (request, port) {
643
- var provider = __classPrivateFieldGet(this, _State_injectedProviders, "f").get(port);
396
+ }
397
+ rpcSend(request, port) {
398
+ const provider = this.#injectedProviders.get(port);
644
399
  assert(provider, 'Cannot call pub(rpc.subscribe) before provider is set');
645
400
  return provider.send(request.method, request.params);
646
- };
401
+ }
647
402
  // Start a provider, return its meta
648
- State.prototype.rpcStartProvider = function (key, port) {
649
- var _this = this;
650
- assert(Object.keys(__classPrivateFieldGet(this, _State_providers, "f")).includes(key), "Provider ".concat(key, " is not exposed by extension"));
651
- if (__classPrivateFieldGet(this, _State_injectedProviders, "f").get(port)) {
652
- return Promise.resolve(__classPrivateFieldGet(this, _State_providers, "f")[key].meta);
403
+ rpcStartProvider(key, port) {
404
+ assert(Object.keys(this.#providers).includes(key), `Provider ${key} is not exposed by extension`);
405
+ if (this.#injectedProviders.get(port)) {
406
+ return Promise.resolve(this.#providers[key].meta);
653
407
  }
654
408
  // Instantiate the provider
655
- __classPrivateFieldGet(this, _State_injectedProviders, "f").set(port, __classPrivateFieldGet(this, _State_providers, "f")[key].start());
409
+ this.#injectedProviders.set(port, this.#providers[key].start());
656
410
  // Close provider connection when page is closed
657
- port.onDisconnect.addListener(function () {
658
- var provider = __classPrivateFieldGet(_this, _State_injectedProviders, "f").get(port);
411
+ port.onDisconnect.addListener(() => {
412
+ const provider = this.#injectedProviders.get(port);
659
413
  if (provider) {
660
- withErrorLog(function () { return provider.disconnect(); });
414
+ withErrorLog(() => provider.disconnect());
661
415
  }
662
- __classPrivateFieldGet(_this, _State_injectedProviders, "f").delete(port);
416
+ this.#injectedProviders.delete(port);
663
417
  });
664
- return Promise.resolve(__classPrivateFieldGet(this, _State_providers, "f")[key].meta);
665
- };
666
- State.prototype.rpcSubscribe = function (_a, cb, port) {
667
- var method = _a.method, params = _a.params, type = _a.type;
668
- var provider = __classPrivateFieldGet(this, _State_injectedProviders, "f").get(port);
418
+ return Promise.resolve(this.#providers[key].meta);
419
+ }
420
+ rpcSubscribe({ method, params, type }, cb, port) {
421
+ const provider = this.#injectedProviders.get(port);
669
422
  assert(provider, 'Cannot call pub(rpc.subscribe) before provider is set');
670
423
  return provider.subscribe(type, method, params, cb);
671
- };
672
- State.prototype.rpcSubscribeConnected = function (_request, cb, port) {
673
- var provider = __classPrivateFieldGet(this, _State_injectedProviders, "f").get(port);
424
+ }
425
+ rpcSubscribeConnected(_request, cb, port) {
426
+ const provider = this.#injectedProviders.get(port);
674
427
  assert(provider, 'Cannot call pub(rpc.subscribeConnected) before provider is set');
675
428
  cb(null, provider.isConnected); // Immediately send back current isConnected
676
- provider.on('connected', function () { return cb(null, true); });
677
- provider.on('disconnected', function () { return cb(null, false); });
678
- };
679
- State.prototype.rpcUnsubscribe = function (request, port) {
680
- var provider = __classPrivateFieldGet(this, _State_injectedProviders, "f").get(port);
429
+ provider.on('connected', () => cb(null, true));
430
+ provider.on('disconnected', () => cb(null, false));
431
+ }
432
+ rpcUnsubscribe(request, port) {
433
+ const provider = this.#injectedProviders.get(port);
681
434
  assert(provider, 'Cannot call pub(rpc.unsubscribe) before provider is set');
682
435
  return provider.unsubscribe(request.type, request.method, request.subscriptionId);
683
- };
684
- State.prototype.saveMetadata = function (meta) {
685
- return __awaiter(this, void 0, void 0, function () {
686
- return __generator(this, function (_a) {
687
- switch (_a.label) {
688
- case 0: return [4 /*yield*/, __classPrivateFieldGet(this, _State_metaStore, "f").set(meta.genesisHash, meta)];
689
- case 1:
690
- _a.sent();
691
- addMetadata(meta);
692
- return [2 /*return*/];
693
- }
694
- });
695
- });
696
- };
697
- State.prototype.setNotification = function (notification) {
698
- __classPrivateFieldSet(this, _State_notification, notification, "f");
436
+ }
437
+ async saveMetadata(meta) {
438
+ await this.#metaStore.set(meta.genesisHash, meta);
439
+ addMetadata(meta);
440
+ }
441
+ setNotification(notification) {
442
+ this.#notification = notification;
699
443
  return true;
700
- };
701
- State.prototype.handleSignRequest = function (origin) {
702
- var now = Date.now();
703
- var lastTime = __classPrivateFieldGet(this, _State_lastRequestTimestamps, "f").get(origin) || 0;
704
- if (now - lastTime < __classPrivateFieldGet(this, _State_rateLimitInterval, "f")) {
444
+ }
445
+ handleSignRequest(origin) {
446
+ const now = Date.now();
447
+ const lastTime = this.#lastRequestTimestamps.get(origin) || 0;
448
+ if (now - lastTime < this.#rateLimitInterval) {
705
449
  throw new Error('Rate limit exceeded. Try again later.');
706
450
  }
707
451
  // If we're about to exceed max entries, evict the oldest
708
- if (!__classPrivateFieldGet(this, _State_lastRequestTimestamps, "f").has(origin) && __classPrivateFieldGet(this, _State_lastRequestTimestamps, "f").size >= __classPrivateFieldGet(this, _State_maxEntries, "f")) {
709
- var oldestKey = __classPrivateFieldGet(this, _State_lastRequestTimestamps, "f").keys().next().value;
710
- oldestKey && __classPrivateFieldGet(this, _State_lastRequestTimestamps, "f").delete(oldestKey);
452
+ if (!this.#lastRequestTimestamps.has(origin) && this.#lastRequestTimestamps.size >= this.#maxEntries) {
453
+ const oldestKey = this.#lastRequestTimestamps.keys().next().value;
454
+ oldestKey && this.#lastRequestTimestamps.delete(oldestKey);
711
455
  }
712
- __classPrivateFieldGet(this, _State_lastRequestTimestamps, "f").set(origin, now);
713
- };
714
- State.prototype.sign = function (url, request, account) {
715
- var _this = this;
716
- var id = getId();
456
+ this.#lastRequestTimestamps.set(origin, now);
457
+ }
458
+ sign(url, request, account) {
459
+ const id = getId();
717
460
  try {
718
461
  this.handleSignRequest(url);
719
462
  }
720
463
  catch (error) {
721
464
  return Promise.reject(error);
722
465
  }
723
- return new Promise(function (resolve, reject) {
724
- __classPrivateFieldGet(_this, _State_signRequests, "f")[id] = __assign(__assign({}, _this.signComplete(id, resolve, reject)), { account: account, id: id, request: request, url: url });
725
- _this.updateIconSign();
726
- _this.popupOpen();
466
+ return new Promise((resolve, reject) => {
467
+ this.#signRequests[id] = {
468
+ ...this.signComplete(id, resolve, reject),
469
+ account,
470
+ id,
471
+ request,
472
+ url
473
+ };
474
+ this.updateIconSign();
475
+ this.popupOpen();
727
476
  });
728
- };
729
- return State;
730
- }());
731
- _State_authUrls = new WeakMap(), _State_lastRequestTimestamps = new WeakMap(), _State_maxEntries = new WeakMap(), _State_rateLimitInterval = new WeakMap(), _State_authRequests = new WeakMap(), _State_metaStore = new WeakMap(), _State_injectedProviders = new WeakMap(), _State_metaRequests = new WeakMap(), _State_notification = new WeakMap(), _State_providers = new WeakMap(), _State_signRequests = new WeakMap(), _State_windows = new WeakMap(), _State_connectedTabsUrl = new WeakMap();
732
- export default State;
477
+ }
478
+ }