@pezkuwi/extension-base 0.62.8 → 0.62.12

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 (187) hide show
  1. package/LICENSE +201 -0
  2. package/background/RequestBytesSign.js +12 -0
  3. package/background/RequestExtrinsicSign.js +11 -0
  4. package/background/handlers/Extension.js +489 -0
  5. package/background/handlers/State.js +478 -0
  6. package/background/handlers/Tabs.js +195 -0
  7. package/{build/background → background}/handlers/helpers.js +1 -3
  8. package/background/handlers/index.js +40 -0
  9. package/background/handlers/subscriptions.js +18 -0
  10. package/background/index.js +1 -0
  11. package/bundle.js +1 -0
  12. package/cjs/background/RequestBytesSign.d.ts +12 -0
  13. package/cjs/background/RequestBytesSign.js +15 -0
  14. package/cjs/background/RequestExtrinsicSign.d.ts +12 -0
  15. package/cjs/background/RequestExtrinsicSign.js +14 -0
  16. package/cjs/background/handlers/Extension.d.ts +49 -0
  17. package/cjs/background/handlers/Extension.js +492 -0
  18. package/cjs/background/handlers/State.d.ts +96 -0
  19. package/cjs/background/handlers/State.js +482 -0
  20. package/cjs/background/handlers/Tabs.d.ts +25 -0
  21. package/cjs/background/handlers/Tabs.js +199 -0
  22. package/cjs/background/handlers/helpers.d.ts +1 -0
  23. package/cjs/background/handlers/helpers.js +14 -0
  24. package/cjs/background/handlers/index.d.ts +3 -0
  25. package/cjs/background/handlers/index.js +46 -0
  26. package/cjs/background/handlers/subscriptions.d.ts +3 -0
  27. package/cjs/background/handlers/subscriptions.js +22 -0
  28. package/cjs/background/index.d.ts +1 -0
  29. package/cjs/background/index.js +7 -0
  30. package/cjs/background/types.d.ts +343 -0
  31. package/cjs/background/types.js +2 -0
  32. package/cjs/bundle.d.ts +1 -0
  33. package/cjs/bundle.js +5 -0
  34. package/cjs/defaults.js +16 -0
  35. package/cjs/index.js +4 -0
  36. package/cjs/package.json +3 -0
  37. package/cjs/packageDetect.d.ts +1 -0
  38. package/cjs/packageDetect.js +8 -0
  39. package/cjs/packageInfo.js +4 -0
  40. package/cjs/page/Accounts.js +24 -0
  41. package/cjs/page/Injected.js +25 -0
  42. package/cjs/page/Metadata.js +15 -0
  43. package/cjs/page/PostMessageProvider.js +135 -0
  44. package/cjs/page/Signer.js +29 -0
  45. package/cjs/page/index.js +52 -0
  46. package/cjs/page/types.js +2 -0
  47. package/cjs/stores/Accounts.js +21 -0
  48. package/cjs/stores/Base.js +70 -0
  49. package/cjs/stores/Metadata.js +13 -0
  50. package/cjs/stores/index.js +8 -0
  51. package/cjs/types.js +2 -0
  52. package/cjs/utils/canDerive.js +6 -0
  53. package/cjs/utils/getId.js +8 -0
  54. package/cjs/utils/index.js +5 -0
  55. package/{build → cjs}/utils/portUtils.d.ts +0 -1
  56. package/cjs/utils/portUtils.js +49 -0
  57. package/defaults.d.ts +9 -0
  58. package/{src/defaults.ts → defaults.js} +2 -15
  59. package/index.d.ts +1 -0
  60. package/index.js +1 -0
  61. package/package.json +464 -10
  62. package/packageDetect.d.ts +1 -0
  63. package/{build/packageDetect.js → packageDetect.js} +0 -4
  64. package/packageInfo.d.ts +6 -0
  65. package/packageInfo.js +1 -0
  66. package/page/Accounts.d.ts +7 -0
  67. package/page/Accounts.js +21 -0
  68. package/page/Injected.d.ts +13 -0
  69. package/{build/page → page}/Injected.js +10 -10
  70. package/page/Metadata.d.ts +7 -0
  71. package/page/Metadata.js +12 -0
  72. package/page/PostMessageProvider.d.ts +63 -0
  73. package/page/PostMessageProvider.js +132 -0
  74. package/page/Signer.d.ts +8 -0
  75. package/page/Signer.js +26 -0
  76. package/page/index.d.ts +16 -0
  77. package/page/index.js +45 -0
  78. package/page/types.d.ts +6 -0
  79. package/page/types.js +1 -0
  80. package/stores/Accounts.d.ts +6 -0
  81. package/stores/Accounts.js +17 -0
  82. package/stores/Base.d.ts +9 -0
  83. package/stores/Base.js +67 -0
  84. package/stores/Metadata.d.ts +5 -0
  85. package/stores/Metadata.js +9 -0
  86. package/{src/stores/index.ts → stores/index.d.ts} +0 -3
  87. package/{build/stores → stores}/index.js +0 -2
  88. package/types.d.ts +9 -0
  89. package/types.js +1 -0
  90. package/utils/canDerive.d.ts +2 -0
  91. package/{build/utils → utils}/canDerive.js +0 -2
  92. package/utils/getId.d.ts +1 -0
  93. package/utils/getId.js +5 -0
  94. package/utils/index.d.ts +1 -0
  95. package/utils/index.js +1 -0
  96. package/utils/portUtils.d.ts +13 -0
  97. package/utils/portUtils.js +43 -0
  98. package/build/background/RequestBytesSign.js +0 -15
  99. package/build/background/RequestExtrinsicSign.js +0 -14
  100. package/build/background/handlers/Extension.js +0 -645
  101. package/build/background/handlers/State.js +0 -732
  102. package/build/background/handlers/Tabs.js +0 -313
  103. package/build/background/handlers/index.js +0 -45
  104. package/build/background/handlers/subscriptions.js +0 -22
  105. package/build/background/index.js +0 -3
  106. package/build/background/types.js +0 -3
  107. package/build/bundle.js +0 -3
  108. package/build/defaults.js +0 -17
  109. package/build/index.js +0 -5
  110. package/build/packageInfo.js +0 -4
  111. package/build/page/Accounts.js +0 -26
  112. package/build/page/Metadata.js +0 -17
  113. package/build/page/PostMessageProvider.js +0 -234
  114. package/build/page/Signer.js +0 -92
  115. package/build/page/index.js +0 -102
  116. package/build/page/types.js +0 -3
  117. package/build/stores/Accounts.js +0 -83
  118. package/build/stores/Base.js +0 -250
  119. package/build/stores/Metadata.js +0 -29
  120. package/build/types.js +0 -3
  121. package/build/utils/getId.js +0 -7
  122. package/build/utils/index.js +0 -3
  123. package/build/utils/portUtils.js +0 -106
  124. package/src/background/RequestBytesSign.ts +0 -28
  125. package/src/background/RequestExtrinsicSign.ts +0 -22
  126. package/src/background/handlers/Extension.spec.ts +0 -478
  127. package/src/background/handlers/Extension.ts +0 -690
  128. package/src/background/handlers/State.ts +0 -664
  129. package/src/background/handlers/Tabs.ts +0 -289
  130. package/src/background/handlers/helpers.ts +0 -14
  131. package/src/background/handlers/index.ts +0 -60
  132. package/src/background/handlers/subscriptions.ts +0 -32
  133. package/src/background/index.ts +0 -4
  134. package/src/background/types.ts +0 -432
  135. package/src/bundle.ts +0 -4
  136. package/src/index.ts +0 -7
  137. package/src/packageDetect.ts +0 -14
  138. package/src/packageInfo.ts +0 -6
  139. package/src/page/Accounts.ts +0 -33
  140. package/src/page/Injected.ts +0 -33
  141. package/src/page/Metadata.ts +0 -22
  142. package/src/page/PostMessageProvider.ts +0 -182
  143. package/src/page/Signer.ts +0 -45
  144. package/src/page/index.ts +0 -89
  145. package/src/page/types.ts +0 -10
  146. package/src/stores/Accounts.ts +0 -28
  147. package/src/stores/Base.ts +0 -93
  148. package/src/stores/Metadata.ts +0 -17
  149. package/src/types.ts +0 -12
  150. package/src/utils/canDerive.ts +0 -8
  151. package/src/utils/getId.ts +0 -10
  152. package/src/utils/index.ts +0 -4
  153. package/src/utils/portUtils.ts +0 -65
  154. package/tsconfig.build.json +0 -16
  155. package/tsconfig.build.tsbuildinfo +0 -1
  156. package/tsconfig.spec.json +0 -18
  157. package/tsconfig.spec.tsbuildinfo +0 -1
  158. /package/{build/background → background}/RequestBytesSign.d.ts +0 -0
  159. /package/{build/background → background}/RequestExtrinsicSign.d.ts +0 -0
  160. /package/{build/background → background}/handlers/Extension.d.ts +0 -0
  161. /package/{build/background → background}/handlers/State.d.ts +0 -0
  162. /package/{build/background → background}/handlers/Tabs.d.ts +0 -0
  163. /package/{build/background → background}/handlers/helpers.d.ts +0 -0
  164. /package/{build/background → background}/handlers/index.d.ts +0 -0
  165. /package/{build/background → background}/handlers/subscriptions.d.ts +0 -0
  166. /package/{build/background → background}/index.d.ts +0 -0
  167. /package/{build/background → background}/types.d.ts +0 -0
  168. /package/{build/packageDetect.d.ts → background/types.js} +0 -0
  169. /package/{build/bundle.d.ts → bundle.d.ts} +0 -0
  170. /package/{build → cjs}/defaults.d.ts +0 -0
  171. /package/{build → cjs}/index.d.ts +0 -0
  172. /package/{build → cjs}/packageInfo.d.ts +0 -0
  173. /package/{build → cjs}/page/Accounts.d.ts +0 -0
  174. /package/{build → cjs}/page/Injected.d.ts +0 -0
  175. /package/{build → cjs}/page/Metadata.d.ts +0 -0
  176. /package/{build → cjs}/page/PostMessageProvider.d.ts +0 -0
  177. /package/{build → cjs}/page/Signer.d.ts +0 -0
  178. /package/{build → cjs}/page/index.d.ts +0 -0
  179. /package/{build → cjs}/page/types.d.ts +0 -0
  180. /package/{build → cjs}/stores/Accounts.d.ts +0 -0
  181. /package/{build → cjs}/stores/Base.d.ts +0 -0
  182. /package/{build → cjs}/stores/Metadata.d.ts +0 -0
  183. /package/{build → cjs}/stores/index.d.ts +0 -0
  184. /package/{build → cjs}/types.d.ts +0 -0
  185. /package/{build → cjs}/utils/canDerive.d.ts +0 -0
  186. /package/{build → cjs}/utils/getId.d.ts +0 -0
  187. /package/{build → cjs}/utils/index.d.ts +0 -0
@@ -1,182 +0,0 @@
1
- // Copyright 2019-2025 @pezkuwi/extension-base authors & contributors
2
- // SPDX-License-Identifier: Apache-2.0
3
-
4
- import type { InjectedProvider, ProviderList, ProviderMeta } from '@pezkuwi/extension-inject/types';
5
- import type { ProviderInterfaceEmitCb, ProviderInterfaceEmitted } from '@pezkuwi/rpc-provider/types';
6
- import type { AnyFunction } from '@pezkuwi/types/types';
7
- import type { SendRequest } from './types.js';
8
-
9
- import { EventEmitter } from 'eventemitter3';
10
-
11
- import { isUndefined, logger } from '@pezkuwi/util';
12
-
13
- const l = logger('PostMessageProvider');
14
-
15
- type CallbackHandler = (error?: null | Error, value?: unknown) => void;
16
-
17
- // Same as https://github.com/polkadot-js/api/blob/57ca9a9c3204339e1e1f693fcacc33039868dc27/packages/rpc-provider/src/ws/Provider.ts#L17
18
- interface SubscriptionHandler {
19
- callback: CallbackHandler;
20
- type: string;
21
- }
22
-
23
- // External to class, this.# is not private enough (yet)
24
- let sendRequest: SendRequest;
25
-
26
- /**
27
- * @name PostMessageProvider
28
- *
29
- * @description Extension provider to be used by dapps
30
- */
31
- export default class PostMessageProvider implements InjectedProvider {
32
- readonly #eventemitter: EventEmitter;
33
-
34
- // Whether or not the actual extension background provider is connected
35
- #isConnected = false;
36
-
37
- // Subscription IDs are (historically) not guaranteed to be globally unique;
38
- // only unique for a given subscription method; which is why we identify
39
- // the subscriptions based on subscription id + type
40
- readonly #subscriptions: Record<string, AnyFunction> = {}; // {[(type,subscriptionId)]: callback}
41
-
42
- /**
43
- * @param {function} sendRequest The function to be called to send requests to the node
44
- * @param {function} subscriptionNotificationHandler Channel for receiving subscription messages
45
- */
46
- public constructor (_sendRequest: SendRequest) {
47
- this.#eventemitter = new EventEmitter();
48
-
49
- sendRequest = _sendRequest;
50
- }
51
-
52
- public get isClonable (): boolean {
53
- return !!true;
54
- }
55
-
56
- /**
57
- * @description Returns a clone of the object
58
- */
59
- public clone (): PostMessageProvider {
60
- return new PostMessageProvider(sendRequest);
61
- }
62
-
63
- /**
64
- * @description Manually disconnect from the connection, clearing autoconnect logic
65
- */
66
- // eslint-disable-next-line @typescript-eslint/require-await
67
- public async connect (): Promise<void> {
68
- // FIXME This should see if the extension's state's provider can disconnect
69
- console.error('PostMessageProvider.disconnect() is not implemented.');
70
- }
71
-
72
- /**
73
- * @description Manually disconnect from the connection, clearing autoconnect logic
74
- */
75
- // eslint-disable-next-line @typescript-eslint/require-await
76
- public async disconnect (): Promise<void> {
77
- // FIXME This should see if the extension's state's provider can disconnect
78
- console.error('PostMessageProvider.disconnect() is not implemented.');
79
- }
80
-
81
- /**
82
- * @summary `true` when this provider supports subscriptions
83
- */
84
- public get hasSubscriptions (): boolean {
85
- // FIXME This should see if the extension's state's provider has subscriptions
86
- return !!true;
87
- }
88
-
89
- /**
90
- * @summary Whether the node is connected or not.
91
- * @return {boolean} true if connected
92
- */
93
- public get isConnected (): boolean {
94
- return this.#isConnected;
95
- }
96
-
97
- public listProviders (): Promise<ProviderList> {
98
- return sendRequest('pub(rpc.listProviders)', undefined);
99
- }
100
-
101
- /**
102
- * @summary Listens on events after having subscribed using the [[subscribe]] function.
103
- * @param {ProviderInterfaceEmitted} type Event
104
- * @param {ProviderInterfaceEmitCb} sub Callback
105
- * @return unsubscribe function
106
- */
107
- public on (type: ProviderInterfaceEmitted, sub: ProviderInterfaceEmitCb): () => void {
108
- this.#eventemitter.on(type, sub);
109
-
110
- return (): void => {
111
- this.#eventemitter.removeListener(type, sub);
112
- };
113
- }
114
-
115
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
116
- public async send (method: string, params: unknown[], _?: boolean, subscription?: SubscriptionHandler): Promise<any> {
117
- if (subscription) {
118
- const { callback, type } = subscription;
119
-
120
- const id = await sendRequest('pub(rpc.subscribe)', { method, params, type }, (res): void => {
121
- subscription.callback(null, res);
122
- });
123
-
124
- this.#subscriptions[`${type}::${id}`] = callback;
125
-
126
- return id;
127
- }
128
-
129
- return sendRequest('pub(rpc.send)', { method, params });
130
- }
131
-
132
- /**
133
- * @summary Spawn a provider on the extension background.
134
- */
135
- public async startProvider (key: string): Promise<ProviderMeta> {
136
- // Disconnect from the previous provider
137
- this.#isConnected = false;
138
- this.#eventemitter.emit('disconnected');
139
-
140
- const meta = await sendRequest('pub(rpc.startProvider)', key);
141
-
142
- // eslint-disable-next-line @typescript-eslint/no-floating-promises
143
- sendRequest('pub(rpc.subscribeConnected)', null, (connected) => {
144
- this.#isConnected = connected;
145
-
146
- if (connected) {
147
- this.#eventemitter.emit('connected');
148
- } else {
149
- this.#eventemitter.emit('disconnected');
150
- }
151
-
152
- return true;
153
- });
154
-
155
- return meta;
156
- }
157
-
158
- public subscribe (type: string, method: string, params: unknown[], callback: AnyFunction): Promise<number> {
159
- return this.send(method, params, false, { callback, type }) as Promise<number>;
160
- }
161
-
162
- /**
163
- * @summary Allows unsubscribing to subscriptions made with [[subscribe]].
164
- */
165
- public async unsubscribe (type: string, method: string, id: number): Promise<boolean> {
166
- const subscription = `${type}::${id}`;
167
-
168
- // FIXME This now could happen with re-subscriptions. The issue is that with a re-sub
169
- // the assigned id now does not match what the API user originally received. It has
170
- // a slight complication in solving - since we cannot rely on the send id, but rather
171
- // need to find the actual subscription id to map it
172
- if (isUndefined(this.#subscriptions[subscription])) {
173
- l.debug((): string => `Unable to find active subscription=${subscription}`);
174
-
175
- return false;
176
- }
177
-
178
- delete this.#subscriptions[subscription];
179
-
180
- return this.send(method, [id]) as Promise<boolean>;
181
- }
182
- }
@@ -1,45 +0,0 @@
1
- // Copyright 2019-2025 @pezkuwi/extension-base authors & contributors
2
- // SPDX-License-Identifier: Apache-2.0
3
-
4
- import type { Signer as SignerInterface, SignerResult } from '@pezkuwi/api/types';
5
- import type { SignerPayloadJSON, SignerPayloadRaw } from '@pezkuwi/types/types';
6
- import type { SendRequest } from './types.js';
7
-
8
- // External to class, this.# is not private enough (yet)
9
- let sendRequest: SendRequest;
10
- let nextId = 0;
11
-
12
- export default class Signer implements SignerInterface {
13
- constructor (_sendRequest: SendRequest) {
14
- sendRequest = _sendRequest;
15
- }
16
-
17
- public async signPayload (payload: SignerPayloadJSON): Promise<SignerResult> {
18
- const id = ++nextId;
19
- const result = await sendRequest('pub(extrinsic.sign)', payload);
20
-
21
- // we add an internal id (number) - should have a mapping from the
22
- // extension id (string) -> internal id (number) if we wish to provide
23
- // updated via the update functionality (noop at this point)
24
- return {
25
- ...result,
26
- id
27
- };
28
- }
29
-
30
- public async signRaw (payload: SignerPayloadRaw): Promise<SignerResult> {
31
- const id = ++nextId;
32
- const result = await sendRequest('pub(bytes.sign)', payload);
33
-
34
- return {
35
- ...result,
36
- id
37
- };
38
- }
39
-
40
- // NOTE We don't listen to updates at all, if we do we can interpret the
41
- // result as provided by the API here
42
- // public update (id: number, status: Hash | SubmittableResult): void {
43
- // // ignore
44
- // }
45
- }
package/src/page/index.ts DELETED
@@ -1,89 +0,0 @@
1
- // Copyright 2019-2025 @pezkuwi/extension-base authors & contributors
2
- // SPDX-License-Identifier: Apache-2.0
3
-
4
- /* eslint-disable no-redeclare */
5
-
6
- import type { MessageTypes, MessageTypesWithNoSubscriptions, MessageTypesWithNullRequest, MessageTypesWithSubscriptions, RequestTypes, ResponseTypes, SubscriptionMessageTypes, TransportRequestMessage, TransportResponseMessage } from '../background/types.js';
7
-
8
- import { MESSAGE_ORIGIN_PAGE } from '../defaults.js';
9
- import { getId } from '../utils/getId.js';
10
- import Injected from './Injected.js';
11
-
12
- // when sending a message from the injector to the extension, we
13
- // - create an event - this we send to the loader
14
- // - the loader takes this event and uses port.postMessage to background
15
- // - on response, the loader creates a response event
16
- // - this injector, listens on the events, maps it to the original
17
- // - resolves/rejects the promise with the result (or sub data)
18
-
19
- export interface Handler {
20
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
21
- resolve: (data?: any) => void;
22
- reject: (error: Error) => void;
23
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
24
- subscriber?: (data: any) => void;
25
- }
26
-
27
- export type Handlers = Record<string, Handler>;
28
-
29
- const handlers: Handlers = {};
30
-
31
- // a generic message sender that creates an event, returning a promise that will
32
- // resolve once the event is resolved (by the response listener just below this)
33
- export function sendMessage<TMessageType extends MessageTypesWithNullRequest>(message: TMessageType): Promise<ResponseTypes[TMessageType]>;
34
- export function sendMessage<TMessageType extends MessageTypesWithNoSubscriptions>(message: TMessageType, request: RequestTypes[TMessageType]): Promise<ResponseTypes[TMessageType]>;
35
- export function sendMessage<TMessageType extends MessageTypesWithSubscriptions>(message: TMessageType, request: RequestTypes[TMessageType], subscriber: (data: SubscriptionMessageTypes[TMessageType]) => void): Promise<ResponseTypes[TMessageType]>;
36
-
37
- export function sendMessage<TMessageType extends MessageTypes> (message: TMessageType, request?: RequestTypes[TMessageType], subscriber?: (data: unknown) => void): Promise<ResponseTypes[TMessageType]> {
38
- return new Promise((resolve, reject): void => {
39
- const id = getId();
40
-
41
- handlers[id] = { reject, resolve, subscriber };
42
-
43
- const transportRequestMessage: TransportRequestMessage<TMessageType> = {
44
- id,
45
- message,
46
- origin: MESSAGE_ORIGIN_PAGE,
47
- request: request || null as RequestTypes[TMessageType]
48
- };
49
-
50
- window.postMessage(transportRequestMessage, '*');
51
- });
52
- }
53
-
54
- // the enable function, called by the dapp to allow access
55
- export async function enable (origin: string): Promise<Injected> {
56
- await sendMessage('pub(authorize.tab)', { origin });
57
-
58
- return new Injected(sendMessage);
59
- }
60
-
61
- // redirect users if this page is considered as phishing, otherwise return false
62
- export async function redirectIfPhishing (): Promise<boolean> {
63
- const res = await sendMessage('pub(phishing.redirectIfDenied)');
64
-
65
- return res;
66
- }
67
-
68
- export function handleResponse<TMessageType extends MessageTypes> (data: TransportResponseMessage<TMessageType> & { subscription?: string }): void {
69
- const handler = handlers[data.id];
70
-
71
- if (!handler) {
72
- console.error(`Unknown response: ${JSON.stringify(data)}`);
73
-
74
- return;
75
- }
76
-
77
- if (!handler.subscriber) {
78
- delete handlers[data.id];
79
- }
80
-
81
- if (data.subscription) {
82
- // eslint-disable-next-line @typescript-eslint/ban-types
83
- (handler.subscriber as Function)(data.subscription);
84
- } else if (data.error) {
85
- handler.reject(new Error(data.error));
86
- } else {
87
- handler.resolve(data.response);
88
- }
89
- }
package/src/page/types.ts DELETED
@@ -1,10 +0,0 @@
1
- // Copyright 2019-2025 @pezkuwi/extension-base authors & contributors
2
- // SPDX-License-Identifier: Apache-2.0
3
-
4
- import type { MessageTypesWithNoSubscriptions, MessageTypesWithNullRequest, MessageTypesWithSubscriptions, RequestTypes, ResponseTypes, SubscriptionMessageTypes } from '../background/types.js';
5
-
6
- export interface SendRequest {
7
- <TMessageType extends MessageTypesWithNullRequest>(message: TMessageType): Promise<ResponseTypes[TMessageType]>;
8
- <TMessageType extends MessageTypesWithNoSubscriptions>(message: TMessageType, request: RequestTypes[TMessageType]): Promise<ResponseTypes[TMessageType]>;
9
- <TMessageType extends MessageTypesWithSubscriptions>(message: TMessageType, request: RequestTypes[TMessageType], subscriber: (data: SubscriptionMessageTypes[TMessageType]) => void): Promise<ResponseTypes[TMessageType]>;
10
- }
@@ -1,28 +0,0 @@
1
- // Copyright 2019-2025 @pezkuwi/extension-base authors & contributors
2
- // SPDX-License-Identifier: Apache-2.0
3
-
4
- import type { KeyringJson, KeyringStore } from '@pezkuwi/ui-keyring/types';
5
-
6
- import { EXTENSION_PREFIX } from '../defaults.js';
7
- import BaseStore from './Base.js';
8
-
9
- export default class AccountsStore extends BaseStore<KeyringJson> implements KeyringStore {
10
- constructor () {
11
- super(
12
- EXTENSION_PREFIX && EXTENSION_PREFIX !== 'polkadot{.js}'
13
- ? `${EXTENSION_PREFIX}accounts`
14
- : null
15
- );
16
- }
17
-
18
- public override async set (key: string, value: KeyringJson, update?: () => void): Promise<void> {
19
- // shortcut, don't save testing accounts in extension storage
20
- if (key.startsWith('account:') && value.meta && value.meta.isTesting) {
21
- update && update();
22
-
23
- return;
24
- }
25
-
26
- await super.set(key, value, update);
27
- }
28
- }
@@ -1,93 +0,0 @@
1
- // Copyright 2019-2025 @pezkuwi/extension-base authors & contributors
2
- // SPDX-License-Identifier: Apache-2.0
3
-
4
- /* global chrome */
5
-
6
- type StoreValue = Record<string, unknown>;
7
-
8
- const lastError = (type: string): void => {
9
- const error = chrome.runtime.lastError;
10
-
11
- if (error) {
12
- console.error(`BaseStore.${type}:: runtime.lastError:`, error);
13
- }
14
- };
15
-
16
- export default abstract class BaseStore <T> {
17
- #prefix: string;
18
-
19
- constructor (prefix: string | null) {
20
- this.#prefix = prefix ? `${prefix}:` : '';
21
- }
22
-
23
- public async all (update: (key: string, value: T) => void): Promise<void> {
24
- await this.allMap(async (map): Promise<void> => {
25
- const entries = Object.entries(map);
26
-
27
- for (const [key, value] of entries) {
28
- // eslint-disable-next-line @typescript-eslint/await-thenable
29
- await update(key, value);
30
- }
31
- });
32
- }
33
-
34
- public async allMap (update: (value: Record<string, T>) => Promise<void>): Promise<void> {
35
- await chrome.storage.local.get(null).then(async (result: StoreValue) => {
36
- lastError('all');
37
-
38
- const entries = Object.entries(result);
39
- const map: Record<string, T> = {};
40
-
41
- for (let i = 0, count = entries.length; i < count; i++) {
42
- const [key, value] = entries[i];
43
-
44
- if (key.startsWith(this.#prefix)) {
45
- map[key.replace(this.#prefix, '')] = value as T;
46
- }
47
- }
48
-
49
- await update(map);
50
- }).catch(({ message }: Error) => {
51
- console.error(`BaseStore error within allMap: ${message}`);
52
- });
53
- }
54
-
55
- public async get (key: string, update: (value: T) => void): Promise<void> {
56
- const prefixedKey = `${this.#prefix}${key}`;
57
-
58
- await chrome.storage.local.get([prefixedKey]).then(async (result: StoreValue) => {
59
- lastError('get');
60
-
61
- // eslint-disable-next-line @typescript-eslint/await-thenable
62
- await update(result[prefixedKey] as T);
63
- }).catch(({ message }: Error) => {
64
- console.error(`BaseStore error within get: ${message}`);
65
- });
66
- }
67
-
68
- public async remove (key: string, update?: () => void): Promise<void> {
69
- const prefixedKey = `${this.#prefix}${key}`;
70
-
71
- await chrome.storage.local.remove(prefixedKey).then(async () => {
72
- lastError('remove');
73
-
74
- // eslint-disable-next-line @typescript-eslint/await-thenable
75
- update && await update();
76
- }).catch(({ message }: Error) => {
77
- console.error(`BaseStore error within remove: ${message}`);
78
- });
79
- }
80
-
81
- public async set (key: string, value: T, update?: () => void): Promise<void> {
82
- const prefixedKey = `${this.#prefix}${key}`;
83
-
84
- await chrome.storage.local.set({ [prefixedKey]: value }).then(async () => {
85
- lastError('set');
86
-
87
- // eslint-disable-next-line @typescript-eslint/await-thenable
88
- update && await update();
89
- }).catch(({ message }: Error) => {
90
- console.error(`BaseStore error within set: ${message}`);
91
- });
92
- }
93
- }
@@ -1,17 +0,0 @@
1
- // Copyright 2019-2025 @pezkuwi/extension-base authors & contributors
2
- // SPDX-License-Identifier: Apache-2.0
3
-
4
- import type { MetadataDef } from '@pezkuwi/extension-inject/types';
5
-
6
- import { EXTENSION_PREFIX } from '../defaults.js';
7
- import BaseStore from './Base.js';
8
-
9
- export default class MetadataStore extends BaseStore<MetadataDef> {
10
- constructor () {
11
- super(
12
- EXTENSION_PREFIX && EXTENSION_PREFIX !== 'polkadot{.js}'
13
- ? `${EXTENSION_PREFIX}metadata`
14
- : 'metadata'
15
- );
16
- }
17
- }
package/src/types.ts DELETED
@@ -1,12 +0,0 @@
1
- // Copyright 2019-2025 @pezkuwi/extension-base authors & contributors
2
- // SPDX-License-Identifier: Apache-2.0
3
-
4
- export interface Message extends MessageEvent {
5
- data: {
6
- error?: string;
7
- id: string;
8
- origin: string;
9
- response?: string;
10
- subscription?: string;
11
- }
12
- }
@@ -1,8 +0,0 @@
1
- // Copyright 2019-2025 @pezkuwi/extension-base authors & contributors
2
- // SPDX-License-Identifier: Apache-2.0
3
-
4
- import type { KeypairType } from '@pezkuwi/util-crypto/types';
5
-
6
- export function canDerive (type?: KeypairType): boolean {
7
- return !!type && ['ed25519', 'sr25519', 'ecdsa', 'ethereum'].includes(type);
8
- }
@@ -1,10 +0,0 @@
1
- // Copyright 2019-2025 @pezkuwi/extension-base authors & contributors
2
- // SPDX-License-Identifier: Apache-2.0
3
-
4
- import { EXTENSION_PREFIX } from '../defaults.js';
5
-
6
- let counter = 0;
7
-
8
- export function getId (): string {
9
- return `${EXTENSION_PREFIX}.${Date.now()}.${++counter}`;
10
- }
@@ -1,4 +0,0 @@
1
- // Copyright 2019-2025 @pezkuwi/extension-base authors & contributors
2
- // SPDX-License-Identifier: Apache-2.0
3
-
4
- export { canDerive } from './canDerive.js';
@@ -1,65 +0,0 @@
1
- // Copyright 2019-2025 @pezkuwi/extension-base authors & contributors
2
- // SPDX-License-Identifier: Apache-2.0
3
-
4
- import type { Message } from '@pezkuwi/extension-base/types';
5
-
6
- import { chrome } from '@pezkuwi/extension-inject/chrome';
7
-
8
- export function setupPort (portName: string, onMessageHandler: (data: Message['data']) => void, onDisconnectHandler: () => void): chrome.runtime.Port {
9
- const port = chrome.runtime.connect({ name: portName });
10
-
11
- port.onMessage.addListener(onMessageHandler);
12
-
13
- port.onDisconnect.addListener(() => {
14
- console.log(`Disconnected from ${portName}`);
15
- onDisconnectHandler();
16
- });
17
-
18
- return port;
19
- }
20
-
21
- export async function wakeUpServiceWorker (): Promise<{ status: string }> {
22
- return new Promise((resolve, reject) => {
23
- chrome.runtime.sendMessage({ type: 'wakeup' }, (response: { status: string }) => {
24
- if (chrome.runtime.lastError) {
25
- reject(new Error(chrome.runtime.lastError.message));
26
- } else {
27
- resolve(response);
28
- }
29
- });
30
- });
31
- }
32
-
33
- // This object is required to allow jest.spyOn to be used to create a mock Implementation for testing
34
- export const wakeUpServiceWorkerWrapper = { wakeUpServiceWorker };
35
-
36
- export async function ensurePortConnection (
37
- portRef: chrome.runtime.Port | undefined,
38
- portConfig: {
39
- portName: string,
40
- onPortMessageHandler: (data: Message['data']) => void,
41
- onPortDisconnectHandler: () => void
42
- }
43
- ): Promise<chrome.runtime.Port> {
44
- const maxAttempts = 5;
45
- const delayMs = 1000;
46
-
47
- for (let attempt = 0; attempt < maxAttempts; attempt++) {
48
- try {
49
- const response = await wakeUpServiceWorkerWrapper.wakeUpServiceWorker();
50
-
51
- if (response?.status === 'awake') {
52
- if (!portRef) {
53
- return setupPort(portConfig.portName, portConfig.onPortMessageHandler, portConfig.onPortDisconnectHandler);
54
- }
55
-
56
- return portRef;
57
- }
58
- } catch (error) {
59
- console.error(`Attempt ${attempt + 1} failed: ${(error as Error).message}`);
60
- await new Promise((resolve) => setTimeout(resolve, delayMs));
61
- }
62
- }
63
-
64
- throw new Error('Failed to wake up the service worker and setup the port after multiple attempts');
65
- }
@@ -1,16 +0,0 @@
1
- {
2
- "extends": "../../tsconfig.base.json",
3
- "compilerOptions": {
4
- "baseUrl": "..",
5
- "outDir": "./build",
6
- "rootDir": "./src"
7
- },
8
- "exclude": [
9
- "**/*.spec.ts"
10
- ],
11
- "references": [
12
- { "path": "../extension-chains/tsconfig.build.json" },
13
- { "path": "../extension-dapp/tsconfig.build.json" },
14
- { "path": "../extension-inject/tsconfig.build.json" }
15
- ]
16
- }