@mocanetwork/airkit 0.5.0-beta.2

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 (80) hide show
  1. package/README.md +177 -0
  2. package/dist/airkit.cjs.js +2662 -0
  3. package/dist/airkit.esm.js +2468 -0
  4. package/dist/airkit.umd.min.js +2 -0
  5. package/dist/airkit.umd.min.js.LICENSE.txt +12 -0
  6. package/dist/lib.cjs/common/src/error.js +25 -0
  7. package/dist/lib.cjs/common/src/realm/messaging/auth.js +28 -0
  8. package/dist/lib.cjs/common/src/realm/messaging/types.js +15 -0
  9. package/dist/lib.cjs/ws-embed/src/PopupHandler.js +64 -0
  10. package/dist/lib.cjs/ws-embed/src/airService.js +364 -0
  11. package/dist/lib.cjs/ws-embed/src/baseProvider.js +178 -0
  12. package/dist/lib.cjs/ws-embed/src/communicationProvider.js +346 -0
  13. package/dist/lib.cjs/ws-embed/src/embed.js +735 -0
  14. package/dist/lib.cjs/ws-embed/src/error.js +21 -0
  15. package/dist/lib.cjs/ws-embed/src/iframeController.js +68 -0
  16. package/dist/lib.cjs/ws-embed/src/inPageProvider.js +307 -0
  17. package/dist/lib.cjs/ws-embed/src/index.js +20 -0
  18. package/dist/lib.cjs/ws-embed/src/interfaces.js +29 -0
  19. package/dist/lib.cjs/ws-embed/src/isStream.js +20 -0
  20. package/dist/lib.cjs/ws-embed/src/loglevel.js +7 -0
  21. package/dist/lib.cjs/ws-embed/src/messageService.js +212 -0
  22. package/dist/lib.cjs/ws-embed/src/messages.js +22 -0
  23. package/dist/lib.cjs/ws-embed/src/siteMetadata.js +77 -0
  24. package/dist/lib.cjs/ws-embed/src/utils.js +95 -0
  25. package/dist/lib.esm/common/src/error.js +23 -0
  26. package/dist/lib.esm/common/src/realm/messaging/auth.js +26 -0
  27. package/dist/lib.esm/common/src/realm/messaging/types.js +13 -0
  28. package/dist/lib.esm/ws-embed/src/PopupHandler.js +62 -0
  29. package/dist/lib.esm/ws-embed/src/airService.js +362 -0
  30. package/dist/lib.esm/ws-embed/src/baseProvider.js +176 -0
  31. package/dist/lib.esm/ws-embed/src/communicationProvider.js +344 -0
  32. package/dist/lib.esm/ws-embed/src/embed.js +730 -0
  33. package/dist/lib.esm/ws-embed/src/error.js +18 -0
  34. package/dist/lib.esm/ws-embed/src/iframeController.js +66 -0
  35. package/dist/lib.esm/ws-embed/src/inPageProvider.js +302 -0
  36. package/dist/lib.esm/ws-embed/src/index.js +5 -0
  37. package/dist/lib.esm/ws-embed/src/interfaces.js +21 -0
  38. package/dist/lib.esm/ws-embed/src/isStream.js +15 -0
  39. package/dist/lib.esm/ws-embed/src/loglevel.js +5 -0
  40. package/dist/lib.esm/ws-embed/src/messageService.js +210 -0
  41. package/dist/lib.esm/ws-embed/src/messages.js +20 -0
  42. package/dist/lib.esm/ws-embed/src/siteMetadata.js +75 -0
  43. package/dist/lib.esm/ws-embed/src/utils.js +88 -0
  44. package/dist/types/PopupHandler.d.ts +24 -0
  45. package/dist/types/airService.d.ts +34 -0
  46. package/dist/types/baseProvider.d.ts +66 -0
  47. package/dist/types/common/custom.d.ts +4 -0
  48. package/dist/types/common/error.d.ts +17 -0
  49. package/dist/types/common/realm/error/auth.d.ts +1 -0
  50. package/dist/types/common/realm/error/types.d.ts +1 -0
  51. package/dist/types/common/realm/messaging/auth.d.ts +138 -0
  52. package/dist/types/common/realm/messaging/types.d.ts +95 -0
  53. package/dist/types/common/realm/partner/config.d.ts +68 -0
  54. package/dist/types/common/realm/user/types.d.ts +78 -0
  55. package/dist/types/common/realm/wallet/bybit/bybit.d.ts +2 -0
  56. package/dist/types/common/realm/wallet/coinbase/coinbase.d.ts +2 -0
  57. package/dist/types/common/realm/wallet/cryptoCom/cryptoCom.d.ts +2 -0
  58. package/dist/types/common/realm/wallet/index.d.ts +22 -0
  59. package/dist/types/common/realm/wallet/metamask/metamask.d.ts +2 -0
  60. package/dist/types/common/realm/wallet/okx/okx.d.ts +2 -0
  61. package/dist/types/common/realm/wallet/phantom/phantom.d.ts +2 -0
  62. package/dist/types/common/realm/wallet/rabby/rabby.d.ts +2 -0
  63. package/dist/types/common/realm/wallet/rainbow/rainbow.d.ts +2 -0
  64. package/dist/types/common/realm/wallet/trust/trust.d.ts +2 -0
  65. package/dist/types/common/types.d.ts +8 -0
  66. package/dist/types/common/utils.d.ts +2 -0
  67. package/dist/types/communicationProvider.d.ts +82 -0
  68. package/dist/types/embed.d.ts +42 -0
  69. package/dist/types/error.d.ts +9 -0
  70. package/dist/types/iframeController.d.ts +18 -0
  71. package/dist/types/inPageProvider.d.ts +106 -0
  72. package/dist/types/index.d.ts +4 -0
  73. package/dist/types/interfaces.d.ts +261 -0
  74. package/dist/types/isStream.d.ts +4 -0
  75. package/dist/types/loglevel.d.ts +3 -0
  76. package/dist/types/messageService.d.ts +51 -0
  77. package/dist/types/messages.d.ts +19 -0
  78. package/dist/types/siteMetadata.d.ts +9 -0
  79. package/dist/types/utils.d.ts +24 -0
  80. package/package.json +76 -0
@@ -0,0 +1,2662 @@
1
+ /******/ (() => { // webpackBootstrap
2
+ /******/ "use strict";
3
+ /******/ // The require scope
4
+ /******/ var __webpack_require__ = {};
5
+ /******/
6
+ /************************************************************************/
7
+ /******/ /* webpack/runtime/compat get default export */
8
+ /******/ (() => {
9
+ /******/ // getDefaultExport function for compatibility with non-harmony modules
10
+ /******/ __webpack_require__.n = (module) => {
11
+ /******/ var getter = module && module.__esModule ?
12
+ /******/ () => (module['default']) :
13
+ /******/ () => (module);
14
+ /******/ __webpack_require__.d(getter, { a: getter });
15
+ /******/ return getter;
16
+ /******/ };
17
+ /******/ })();
18
+ /******/
19
+ /******/ /* webpack/runtime/define property getters */
20
+ /******/ (() => {
21
+ /******/ // define getter functions for harmony exports
22
+ /******/ __webpack_require__.d = (exports, definition) => {
23
+ /******/ for(var key in definition) {
24
+ /******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
25
+ /******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
26
+ /******/ }
27
+ /******/ }
28
+ /******/ };
29
+ /******/ })();
30
+ /******/
31
+ /******/ /* webpack/runtime/hasOwnProperty shorthand */
32
+ /******/ (() => {
33
+ /******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
34
+ /******/ })();
35
+ /******/
36
+ /******/ /* webpack/runtime/make namespace object */
37
+ /******/ (() => {
38
+ /******/ // define __esModule on exports
39
+ /******/ __webpack_require__.r = (exports) => {
40
+ /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
41
+ /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
42
+ /******/ }
43
+ /******/ Object.defineProperty(exports, '__esModule', { value: true });
44
+ /******/ };
45
+ /******/ })();
46
+ /******/
47
+ /************************************************************************/
48
+ var __webpack_exports__ = {};
49
+ // ESM COMPAT FLAG
50
+ __webpack_require__.r(__webpack_exports__);
51
+
52
+ // EXPORTS
53
+ __webpack_require__.d(__webpack_exports__, {
54
+ AirInPageProvider: () => (/* reexport */ inPageProvider),
55
+ AirService: () => (/* reexport */ airService),
56
+ BUTTON_POSITION: () => (/* reexport */ BUTTON_POSITION),
57
+ CONFIRMATION_STRATEGY: () => (/* reexport */ base_controllers_namespaceObject.CONFIRMATION_STRATEGY),
58
+ EMBED_BUILD_ENV: () => (/* reexport */ EMBED_BUILD_ENV),
59
+ EXTERNAL_LOGIN_PROVIDER: () => (/* reexport */ EXTERNAL_LOGIN_PROVIDER),
60
+ RealmEmbed: () => (/* reexport */ src_embed)
61
+ });
62
+
63
+ ;// external "@babel/runtime/helpers/objectSpread2"
64
+ const objectSpread2_namespaceObject = require("@babel/runtime/helpers/objectSpread2");
65
+ var objectSpread2_default = /*#__PURE__*/__webpack_require__.n(objectSpread2_namespaceObject);
66
+ ;// external "@babel/runtime/helpers/classPrivateMethodInitSpec"
67
+ const classPrivateMethodInitSpec_namespaceObject = require("@babel/runtime/helpers/classPrivateMethodInitSpec");
68
+ var classPrivateMethodInitSpec_default = /*#__PURE__*/__webpack_require__.n(classPrivateMethodInitSpec_namespaceObject);
69
+ ;// external "@babel/runtime/helpers/classPrivateFieldInitSpec"
70
+ const classPrivateFieldInitSpec_namespaceObject = require("@babel/runtime/helpers/classPrivateFieldInitSpec");
71
+ var classPrivateFieldInitSpec_default = /*#__PURE__*/__webpack_require__.n(classPrivateFieldInitSpec_namespaceObject);
72
+ ;// external "@toruslabs/base-controllers"
73
+ const base_controllers_namespaceObject = require("@toruslabs/base-controllers");
74
+ ;// ../common/src/realm/messaging/auth.js
75
+ const AirAuthMessageTypes = {
76
+ SETUP_COMPLETED: "air_auth_setup_completed",
77
+ LOGIN_REQUEST: "air_auth_login_request",
78
+ LOGIN_RESPONSE: "air_auth_login_response",
79
+ LOGIN_WALLET_RESPONSE: "air_auth_login_wallet_response",
80
+ USER_INFO_REQUEST: "air_auth_user_info_request",
81
+ USER_INFO_RESPONSE: "air_auth_user_info_response",
82
+ PARTNER_USER_INFO_REQUEST: "air_auth_partner_user_info_request",
83
+ PARTNER_USER_INFO_RESPONSE: "air_auth_partner_user_info_response",
84
+ REFRESH_TOKEN_REQUEST: "air_auth_refresh_token_request",
85
+ REFRESH_TOKEN_RESPONSE: "air_auth_refresh_token_response",
86
+ WALLET_TOKEN_REQUEST: "air_auth_wallet_token_request",
87
+ WALLET_TOKEN_RESPONSE: "air_auth_wallet_token_response",
88
+ INITIALIZATION_REQUEST: "air_auth_initialization_request",
89
+ INITIALIZATION_RESPONSE: "air_auth_initialization_response",
90
+ INIT_WALLET_COMMUNICATION: "air_auth_init_wallet_communication",
91
+ IFRAME_VISIBILITY_REQUEST: "air_auth_iframe_visibility_request",
92
+ SETUP_WALLET_REQUEST: "air_auth_setup_wallet_request",
93
+ SETUP_WALLET_RESPONSE: "air_auth_setup_wallet_response",
94
+ SIGN_SIWE_MESSAGE_REQUEST: "air_auth_sign_siwe_message_request",
95
+ SIGN_SIWE_MESSAGE_RESPONSE: "air_auth_sign_siwe_message_response",
96
+ LOGOUT_REQUEST: "air_auth_logout_request",
97
+ LOGOUT_RESPONSE: "air_auth_logout_response"
98
+ };
99
+ ;// external "@toruslabs/ethereum-controllers"
100
+ const ethereum_controllers_namespaceObject = require("@toruslabs/ethereum-controllers");
101
+ ;// external "@web3auth/auth"
102
+ const external_web3auth_auth_namespaceObject = require("@web3auth/auth");
103
+ ;// ../common/src/realm/messaging/types.js
104
+ const AirMessageTypes = {
105
+ SERVICE_INITIALIZED: "air_service_initialized",
106
+ SERVICE_INITIALIZED_ERROR: "air_service_initialized_error",
107
+ LOGIN_REQUEST: "air_login_request",
108
+ CLAIM_REQUEST: "air_claim_request",
109
+ LOGIN_CLAIM_STATE: "air_login_claim_state",
110
+ CLOSE_MODAL: "air_close_modal",
111
+ INIT_AUTH_COMMUNICATION: "air_init_auth_communication",
112
+ DEPLOY_SMART_ACCOUNT_REQUEST: "air_deploy_smart_account_request",
113
+ DEPLOY_SMART_ACCOUNT_RESPONSE: "air_deploy_smart_account_response"
114
+ };
115
+ const AirLoginClaimStates = {
116
+ CONNECTED: "connected",
117
+ LOGGED_IN: "logged_in",
118
+ CLAIM_FLOW_STARTED: "claim_flow_started",
119
+ CLAIM_FLOW_CANCELLED: "claim_flow_cancelled",
120
+ MINTING_STARTED: "minting_started",
121
+ MINTING_FAILED: "minting_failed"
122
+ };
123
+ ;// external "@babel/runtime/helpers/defineProperty"
124
+ const defineProperty_namespaceObject = require("@babel/runtime/helpers/defineProperty");
125
+ var defineProperty_default = /*#__PURE__*/__webpack_require__.n(defineProperty_namespaceObject);
126
+ ;// external "pump"
127
+ const external_pump_namespaceObject = require("pump");
128
+ var external_pump_default = /*#__PURE__*/__webpack_require__.n(external_pump_namespaceObject);
129
+ ;// ./src/isStream.ts
130
+ /* eslint-disable @typescript-eslint/no-explicit-any */
131
+ function isStream(stream) {
132
+ return stream !== null && typeof stream === "object" && typeof stream.pipe === "function";
133
+ }
134
+ function isWritableStream(stream) {
135
+ return isStream(stream) && stream.writable !== false && typeof stream._write === "function" && typeof stream._writableState === "object";
136
+ }
137
+ function isReadableStream(stream) {
138
+ return isStream(stream) && stream.readable !== false && typeof stream._read === "function" && typeof stream._readableState === "object";
139
+ }
140
+ function isDuplexStream(stream) {
141
+ return isWritableStream(stream) && isReadableStream(stream);
142
+ }
143
+ ;// ./src/messages.ts
144
+ /* harmony default export */ const messages = ({
145
+ errors: {
146
+ disconnected: () => "Web3Auth: Lost connection to Web3Auth.",
147
+ permanentlyDisconnected: () => "Web3Auth: Disconnected from iframe. Page reload required.",
148
+ unsupportedSync: method => `Web3Auth: The Web3Auth Ethereum provider does not support synchronous methods like ${method} without a callback parameter.`,
149
+ invalidDuplexStream: () => "Must provide a Node.js-style duplex stream.",
150
+ invalidOptions: maxEventListeners => `Invalid options. Received: { maxEventListeners: ${maxEventListeners}}`,
151
+ invalidRequestArgs: () => `Expected a single, non-array, object argument.`,
152
+ invalidRequestMethod: () => `'args.method' must be a non-empty string.`,
153
+ invalidRequestParams: () => `'args.params' must be an object or array if provided.`,
154
+ invalidLoggerObject: () => `'args.logger' must be an object if provided.`,
155
+ invalidLoggerMethod: method => `'args.logger' must include required method '${method}'.`
156
+ },
157
+ info: {
158
+ connected: chainId => `Web3Auth: Connected to chain with ID "${chainId}".`
159
+ },
160
+ warnings: {}
161
+ });
162
+ ;// ./src/interfaces.ts
163
+
164
+ const EMBED_BUILD_ENV = {
165
+ PRODUCTION: "production",
166
+ STAGING: "staging",
167
+ DEVELOPMENT: "development",
168
+ TESTING: "testing"
169
+ };
170
+ const BUTTON_POSITION = {
171
+ BOTTOM_LEFT: "bottom-left",
172
+ TOP_LEFT: "top-left",
173
+ BOTTOM_RIGHT: "bottom-right",
174
+ TOP_RIGHT: "top-right"
175
+ };
176
+ const EXTERNAL_LOGIN_PROVIDER = {
177
+ METAMASK: "metamask",
178
+ WALLET_CONNECT: "walletconnect",
179
+ WAGMI: "wagmi"
180
+ };
181
+ ;// external "loglevel"
182
+ const external_loglevel_namespaceObject = require("loglevel");
183
+ var external_loglevel_default = /*#__PURE__*/__webpack_require__.n(external_loglevel_namespaceObject);
184
+ ;// ./src/loglevel.ts
185
+
186
+ /* harmony default export */ const loglevel = (external_loglevel_default().getLogger("ws-embed"));
187
+ ;// ./src/utils.ts
188
+
189
+
190
+
191
+
192
+ const AIR_URLS = {
193
+ [EMBED_BUILD_ENV.TESTING]: {
194
+ authUrl: "http://localhost:8100",
195
+ walletUrl: "https://lrc-mocaverse.web3auth.io",
196
+ logLevel: "debug"
197
+ },
198
+ [EMBED_BUILD_ENV.DEVELOPMENT]: {
199
+ authUrl: "http://localhost:8100",
200
+ walletUrl: "https://localhost:4050",
201
+ logLevel: "debug"
202
+ },
203
+ [EMBED_BUILD_ENV.STAGING]: {
204
+ authUrl: "https://login.staging.realmnetwork.io",
205
+ walletUrl: "https://account.staging.realmnetwork.io",
206
+ logLevel: "info"
207
+ },
208
+ [EMBED_BUILD_ENV.PRODUCTION]: {
209
+ authUrl: "https://login.realmnetwork.io",
210
+ walletUrl: "https://account.realmnetwork.io",
211
+ logLevel: "error"
212
+ }
213
+ };
214
+ const handleEvent = (handle, eventName, handler, ...handlerArgs) => {
215
+ const handlerWrapper = () => {
216
+ handler(...handlerArgs);
217
+ handle.removeEventListener(eventName, handlerWrapper);
218
+ };
219
+ handle.addEventListener(eventName, handlerWrapper);
220
+ };
221
+ const htmlToElement = html => {
222
+ const template = window.document.createElement("template");
223
+ const trimmedHtml = html.trim(); // Never return a text node of whitespace as the result
224
+ template.innerHTML = trimmedHtml;
225
+ return template.content.firstChild;
226
+ };
227
+ const isElement = element => element instanceof Element || element instanceof Document;
228
+
229
+ /**
230
+ * json-rpc-engine middleware that logs RPC errors and and validates req.method.
231
+ *
232
+ * @param log - The logging API to use.
233
+ * @returns json-rpc-engine middleware function
234
+ */
235
+ function createErrorMiddleware() {
236
+ return (req, res, next) => {
237
+ // json-rpc-engine will terminate the request when it notices this error
238
+ if (typeof req.method !== "string" || !req.method) {
239
+ res.error = external_web3auth_auth_namespaceObject.rpcErrors.invalidRequest({
240
+ message: `The request 'method' must be a non-empty string.`,
241
+ data: objectSpread2_default()(objectSpread2_default()({}, req || {}), {}, {
242
+ cause: `The request 'method' must be a non-empty string.`
243
+ })
244
+ });
245
+ }
246
+ next(done => {
247
+ const {
248
+ error
249
+ } = res;
250
+ if (!error) {
251
+ return done();
252
+ }
253
+ loglevel.error(`Ws-Embed - RPC Error: ${error.message}`, error);
254
+ return done();
255
+ });
256
+ };
257
+ }
258
+
259
+ /**
260
+ * Logs a stream disconnection error. Emits an 'error' if given an
261
+ * EventEmitter that has listeners for the 'error' event.
262
+ *
263
+ * @param log - The logging API to use.
264
+ * @param remoteLabel - The label of the disconnected stream.
265
+ * @param error - The associated error to log.
266
+ * @param emitter - The logging API to use.
267
+ */
268
+ function logStreamDisconnectWarning(remoteLabel, error, emitter) {
269
+ let warningMsg = `Web3Auth: Lost connection to "${remoteLabel}".`;
270
+ if (error !== null && error !== void 0 && error.stack) {
271
+ warningMsg += `\n${error.stack}`;
272
+ }
273
+ loglevel.warn(warningMsg);
274
+ if (emitter && emitter.listenerCount("error") > 0) {
275
+ emitter.emit("error", warningMsg);
276
+ }
277
+ }
278
+ const EMITTED_NOTIFICATIONS = ["eth_subscription" // per eth-json-rpc-filters/subscriptionManager
279
+ ];
280
+ ;// ./src/baseProvider.ts
281
+
282
+
283
+
284
+
285
+
286
+
287
+
288
+
289
+
290
+ /**
291
+ * @param connectionStream - A Node.js duplex stream
292
+ * @param opts - An options bag
293
+ */
294
+ class BaseProvider extends external_web3auth_auth_namespaceObject.SafeEventEmitter {
295
+ constructor(connectionStream, {
296
+ maxEventListeners = 100,
297
+ jsonRpcStreamName = "provider"
298
+ }) {
299
+ super();
300
+ defineProperty_default()(this, "rpcEngine", void 0);
301
+ defineProperty_default()(this, "jsonRpcConnectionEvents", void 0);
302
+ /**
303
+ * Indicating that this provider is a Web3Auth provider.
304
+ */
305
+ defineProperty_default()(this, "isWeb3Auth", void 0);
306
+ defineProperty_default()(this, "state", void 0);
307
+ if (!isDuplexStream(connectionStream)) {
308
+ throw new Error(messages.errors.invalidDuplexStream());
309
+ }
310
+ this.isWeb3Auth = true;
311
+ this.setMaxListeners(maxEventListeners);
312
+ this.handleConnect = this.handleConnect.bind(this);
313
+ this.handleDisconnect = this.handleDisconnect.bind(this);
314
+ this.handleStreamDisconnect = this.handleStreamDisconnect.bind(this);
315
+ this.rpcRequest = this.rpcRequest.bind(this);
316
+ this.initializeState = this.initializeState.bind(this);
317
+ this.request = this.request.bind(this);
318
+ this.sendAsync = this.sendAsync.bind(this);
319
+ this.send = this.send.bind(this);
320
+ // this.enable = this.enable.bind(this);
321
+
322
+ // setup connectionStream multiplexing
323
+ const mux = new external_web3auth_auth_namespaceObject.ObjectMultiplex();
324
+ external_pump_default()(connectionStream, mux, connectionStream, this.handleStreamDisconnect.bind(this, "Web3Auth"));
325
+
326
+ // ignore phishing warning message (handled elsewhere)
327
+ mux.ignoreStream("phishing");
328
+
329
+ // setup own event listeners
330
+ // connect to async provider
331
+
332
+ const jsonRpcConnection = (0,external_web3auth_auth_namespaceObject.createStreamMiddleware)();
333
+ external_pump_default()(jsonRpcConnection.stream, mux.createStream(jsonRpcStreamName), jsonRpcConnection.stream, this.handleStreamDisconnect.bind(this, "Web3Auth RpcProvider"));
334
+
335
+ // handle RPC requests via dapp-side rpc engine
336
+ const rpcEngine = new external_web3auth_auth_namespaceObject.JRPCEngine();
337
+ rpcEngine.push((0,external_web3auth_auth_namespaceObject.createIdRemapMiddleware)());
338
+ rpcEngine.push(createErrorMiddleware());
339
+ rpcEngine.push((0,base_controllers_namespaceObject.createLoggerMiddleware)({
340
+ origin: location.origin
341
+ }));
342
+ rpcEngine.push(jsonRpcConnection.middleware);
343
+ this.rpcEngine = rpcEngine;
344
+ this.jsonRpcConnectionEvents = jsonRpcConnection.events;
345
+ }
346
+
347
+ /**
348
+ * Submits an RPC request for the given method, with the given params.
349
+ * Resolves with the result of the method call, or rejects on error.
350
+ *
351
+ * @param args - The RPC request arguments.
352
+ * @returns A Promise that resolves with the result of the RPC method,
353
+ * or rejects if an error is encountered.
354
+ */
355
+ async request(args) {
356
+ if (!args || typeof args !== "object" || Array.isArray(args)) {
357
+ throw external_web3auth_auth_namespaceObject.rpcErrors.invalidRequest({
358
+ message: messages.errors.invalidRequestArgs(),
359
+ data: objectSpread2_default()(objectSpread2_default()({}, args || {}), {}, {
360
+ cause: messages.errors.invalidRequestArgs()
361
+ })
362
+ });
363
+ }
364
+ const {
365
+ method,
366
+ params
367
+ } = args;
368
+ if (typeof method !== "string" || method.length === 0) {
369
+ throw external_web3auth_auth_namespaceObject.rpcErrors.invalidRequest({
370
+ message: messages.errors.invalidRequestMethod(),
371
+ data: objectSpread2_default()(objectSpread2_default()({}, args || {}), {}, {
372
+ cause: messages.errors.invalidRequestArgs()
373
+ })
374
+ });
375
+ }
376
+ if (params !== undefined && !Array.isArray(params) && (typeof params !== "object" || params === null)) {
377
+ throw external_web3auth_auth_namespaceObject.rpcErrors.invalidRequest({
378
+ message: messages.errors.invalidRequestParams(),
379
+ data: objectSpread2_default()(objectSpread2_default()({}, args || {}), {}, {
380
+ cause: messages.errors.invalidRequestArgs()
381
+ })
382
+ });
383
+ }
384
+ return new Promise((resolve, reject) => {
385
+ this.rpcRequest({
386
+ method,
387
+ params
388
+ }, (0,external_web3auth_auth_namespaceObject.getRpcPromiseCallback)(resolve, reject));
389
+ });
390
+ }
391
+ /**
392
+ * Submits an RPC request per the given JSON-RPC request object.
393
+ *
394
+ * @param payload - The RPC request object.
395
+ * @param cb - The callback function.
396
+ */
397
+ send(payload, callback) {
398
+ this.rpcRequest(payload, callback);
399
+ }
400
+ /**
401
+ * Submits an RPC request per the given JSON-RPC request object.
402
+ *
403
+ * @param payload - The RPC request object.
404
+ * @param cb - The callback function.
405
+ */
406
+ sendAsync(payload) {
407
+ return new Promise((resolve, reject) => {
408
+ this.rpcRequest(payload, (0,external_web3auth_auth_namespaceObject.getRpcPromiseCallback)(resolve, reject));
409
+ });
410
+ }
411
+
412
+ /**
413
+ * Called when connection is lost to critical streams.
414
+ *
415
+ * emits InpageProvider#disconnect
416
+ */
417
+ handleStreamDisconnect(streamName, error) {
418
+ logStreamDisconnectWarning(streamName, error, this);
419
+ this.handleDisconnect(false, error ? error.message : undefined);
420
+ }
421
+
422
+ // Private Methods
423
+ //= ===================
424
+ /**
425
+ * Constructor helper.
426
+ * Populates initial state by calling 'wallet_getProviderState' and emits
427
+ * necessary events.
428
+ */
429
+
430
+ /**
431
+ * Internal RPC method. Forwards requests to background via the RPC engine.
432
+ * Also remap ids inbound and outbound
433
+ */
434
+
435
+ /**
436
+ * When the provider becomes connected, updates internal state and emits
437
+ * required events. Idempotent.
438
+ *
439
+ * @param chainId - The ID of the newly connected chain.
440
+ * emits InPageProvider#connect
441
+ */
442
+
443
+ /**
444
+ * When the provider becomes disconnected, updates internal state and emits
445
+ * required events. Idempotent with respect to the isRecoverable parameter.
446
+ *
447
+ * Error codes per the CloseEvent status codes as required by EIP-1193:
448
+ * https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent#Status_codes
449
+ *
450
+ * @param isRecoverable - Whether the disconnection is recoverable.
451
+ * @param errorMessage - A custom error message.
452
+ * emits InpageProvider#disconnect
453
+ */
454
+ }
455
+ /* harmony default export */ const baseProvider = (BaseProvider);
456
+ ;// ./src/PopupHandler.ts
457
+
458
+
459
+
460
+ class PopupHandler extends external_web3auth_auth_namespaceObject.SafeEventEmitter {
461
+ constructor({
462
+ url,
463
+ target,
464
+ features,
465
+ timeout = 30000
466
+ }) {
467
+ super();
468
+ defineProperty_default()(this, "url", void 0);
469
+ defineProperty_default()(this, "target", void 0);
470
+ defineProperty_default()(this, "features", void 0);
471
+ defineProperty_default()(this, "window", void 0);
472
+ defineProperty_default()(this, "windowTimer", void 0);
473
+ defineProperty_default()(this, "iClosedWindow", void 0);
474
+ defineProperty_default()(this, "timeout", void 0);
475
+ this.url = url;
476
+ this.target = target || "_blank";
477
+ this.features = features || (0,base_controllers_namespaceObject.getPopupFeatures)(base_controllers_namespaceObject.FEATURES_DEFAULT_POPUP_WINDOW);
478
+ this.window = undefined;
479
+ this.windowTimer = undefined;
480
+ this.iClosedWindow = false;
481
+ this.timeout = timeout;
482
+ this._setupTimer();
483
+ }
484
+ _setupTimer() {
485
+ this.windowTimer = Number(setInterval(() => {
486
+ if (this.window && this.window.closed) {
487
+ clearInterval(this.windowTimer);
488
+ setTimeout(() => {
489
+ if (!this.iClosedWindow) {
490
+ this.emit("close");
491
+ }
492
+ this.iClosedWindow = false;
493
+ this.window = undefined;
494
+ }, this.timeout);
495
+ }
496
+ if (this.window === undefined) clearInterval(this.windowTimer);
497
+ }, 500));
498
+ }
499
+ open() {
500
+ var _this$window;
501
+ this.window = window.open(this.url.href, this.target, this.features);
502
+ if ((_this$window = this.window) !== null && _this$window !== void 0 && _this$window.focus) this.window.focus();
503
+ }
504
+ close() {
505
+ this.iClosedWindow = true;
506
+ if (this.window) this.window.close();
507
+ }
508
+ redirect(locationReplaceOnRedirect) {
509
+ if (locationReplaceOnRedirect) {
510
+ window.location.replace(this.url.href);
511
+ } else {
512
+ window.location.href = this.url.href;
513
+ }
514
+ }
515
+ }
516
+ /* harmony default export */ const src_PopupHandler = (PopupHandler);
517
+ ;// ./src/communicationProvider.ts
518
+
519
+
520
+
521
+
522
+
523
+
524
+
525
+
526
+
527
+ /**
528
+ * @param connectionStream - A Node.js duplex stream
529
+ * @param opts - An options bag
530
+ */
531
+ class CommunicationProvider extends baseProvider {
532
+ constructor(connectionStream, {
533
+ maxEventListeners = 100,
534
+ jsonRpcStreamName = "provider"
535
+ }, state) {
536
+ super(connectionStream, {
537
+ maxEventListeners,
538
+ jsonRpcStreamName
539
+ });
540
+
541
+ // private state
542
+ defineProperty_default()(this, "tryWindowHandle", void 0);
543
+ defineProperty_default()(this, "onLoginStateHandle", void 0);
544
+ defineProperty_default()(this, "windowRefs", void 0);
545
+ defineProperty_default()(this, "iframeUrl", void 0);
546
+ defineProperty_default()(this, "iframeId", void 0);
547
+ this.state = objectSpread2_default()(objectSpread2_default()({}, CommunicationProvider.defaultState), state);
548
+
549
+ // public state
550
+ this.iframeUrl = "";
551
+ this.iframeId = "";
552
+ this.windowRefs = new Map();
553
+
554
+ // setup own event listeners
555
+
556
+ // EIP-1193 connect
557
+ this.on("connect", () => {
558
+ this.state.isConnected = true;
559
+ });
560
+ const notificationHandler = payload => {
561
+ const {
562
+ method,
563
+ params
564
+ } = payload;
565
+ // create_window should never come here..
566
+ // we either pre-open from embed.
567
+ // if it's blocked, we communicate down that it's blocked and we show full screen iframe and open from iframe
568
+ if (method === base_controllers_namespaceObject.COMMUNICATION_NOTIFICATIONS.IFRAME_STATUS) {
569
+ const {
570
+ isFullScreen,
571
+ rid
572
+ } = params;
573
+ this.displayIframe({
574
+ isFull: isFullScreen,
575
+ rid: rid
576
+ }, true);
577
+ } else if (method === base_controllers_namespaceObject.COMMUNICATION_NOTIFICATIONS.CLOSE_WINDOW) {
578
+ this.handleCloseWindow(params);
579
+ } else if (method === base_controllers_namespaceObject.COMMUNICATION_NOTIFICATIONS.USER_LOGGED_IN) {
580
+ loglevel.info("[TEST METAMASK] User received notification ", base_controllers_namespaceObject.COMMUNICATION_NOTIFICATIONS.USER_LOGGED_IN);
581
+ const {
582
+ currentLoginProvider
583
+ } = params;
584
+ this.state.isLoggedIn = true;
585
+ this.state.currentLoginProvider = currentLoginProvider;
586
+ if (this.onLoginStateHandle) this.onLoginStateHandle(true);
587
+ } else if (method === base_controllers_namespaceObject.COMMUNICATION_NOTIFICATIONS.USER_LOGGED_OUT) {
588
+ this.state.isLoggedIn = false;
589
+ this.state.currentLoginProvider = null;
590
+ this.displayIframe();
591
+ if (this.onLoginStateHandle) this.onLoginStateHandle(false);
592
+ }
593
+ };
594
+ this.jsonRpcConnectionEvents.on("notification", notificationHandler);
595
+ }
596
+ get isLoggedIn() {
597
+ return this.state.isLoggedIn;
598
+ }
599
+
600
+ // e.g. Metamask, WalletConnect, etc.
601
+ get isExternalWallet() {
602
+ return !this.state.currentLoginProvider || this.state.currentLoginProvider === EXTERNAL_LOGIN_PROVIDER.METAMASK || this.state.currentLoginProvider === EXTERNAL_LOGIN_PROVIDER.WALLET_CONNECT || this.state.currentLoginProvider === EXTERNAL_LOGIN_PROVIDER.WAGMI;
603
+ }
604
+ get isIFrameFullScreen() {
605
+ return this.state.isIFrameFullScreen;
606
+ }
607
+
608
+ /**
609
+ * Returns whether the inPage provider is connected to Torus.
610
+ */
611
+ isConnected() {
612
+ return this.state.isConnected;
613
+ }
614
+ async initializeState(params) {
615
+ try {
616
+ const {
617
+ torusUrl,
618
+ torusIframeId
619
+ } = params;
620
+ this.iframeUrl = torusUrl;
621
+ this.iframeId = torusIframeId;
622
+ const {
623
+ currentLoginProvider,
624
+ isLoggedIn
625
+ } = await this.request({
626
+ method: base_controllers_namespaceObject.COMMUNICATION_JRPC_METHODS.GET_PROVIDER_STATE,
627
+ params: []
628
+ });
629
+
630
+ // indicate that we've connected, for EIP-1193 compliance
631
+ if (isLoggedIn) this.handleConnect(currentLoginProvider, isLoggedIn);
632
+ } catch (error) {
633
+ loglevel.error("Web3Auth: Failed to get initial state. Please report this bug.", error);
634
+ } finally {
635
+ loglevel.info("initialized communication state");
636
+ this.state.initialized = true;
637
+ }
638
+ }
639
+ hideTorusButton() {
640
+ this.state.widgetVisibility = false;
641
+ this.displayIframe();
642
+ }
643
+ showTorusButton() {
644
+ this.state.widgetVisibility = true;
645
+ this.displayIframe();
646
+ }
647
+ moveToBackground() {
648
+ this.state.isBackground = true;
649
+ this.displayIframe({
650
+ isFull: this.state.isIFrameFullScreen
651
+ });
652
+ }
653
+ moveToForeground() {
654
+ this.state.isBackground = false;
655
+ this.displayIframe({
656
+ isFull: this.state.isIFrameFullScreen
657
+ });
658
+ }
659
+ setIframeVisibility({
660
+ isVisible
661
+ }) {
662
+ this.state.isBackground = !isVisible;
663
+ }
664
+ displayIframe({
665
+ isFull = false,
666
+ rid = ""
667
+ } = {}, walletRequest = false) {
668
+ const style = {};
669
+ // set phase
670
+ if (!isFull) {
671
+ style.display = this.state.widgetVisibility && !this.state.isBackground ? "block" : "none";
672
+ style.height = "70px";
673
+ style.width = "70px";
674
+ switch (this.state.buttonPosition) {
675
+ case BUTTON_POSITION.TOP_LEFT:
676
+ style.top = "0px";
677
+ style.left = "0px";
678
+ style.right = "auto";
679
+ style.bottom = "auto";
680
+ break;
681
+ case BUTTON_POSITION.TOP_RIGHT:
682
+ style.top = "0px";
683
+ style.right = "0px";
684
+ style.left = "auto";
685
+ style.bottom = "auto";
686
+ break;
687
+ case BUTTON_POSITION.BOTTOM_RIGHT:
688
+ style.bottom = "0px";
689
+ style.right = "0px";
690
+ style.top = "auto";
691
+ style.left = "auto";
692
+ break;
693
+ case BUTTON_POSITION.BOTTOM_LEFT:
694
+ default:
695
+ style.bottom = "0px";
696
+ style.left = "0px";
697
+ style.top = "auto";
698
+ style.right = "auto";
699
+ break;
700
+ }
701
+ } else {
702
+ style.display = this.state.isBackground ? "none" : "block";
703
+ style.width = "100%";
704
+ style.height = "100%";
705
+ style.top = "0px";
706
+ style.right = "0px";
707
+ style.left = "0px";
708
+ style.bottom = "0px";
709
+ }
710
+ const iframe = document.getElementById(this.iframeId);
711
+ Object.assign(iframe.style, style);
712
+ this.state.isIFrameFullScreen = isFull;
713
+ if (!walletRequest) {
714
+ this.request({
715
+ method: base_controllers_namespaceObject.COMMUNICATION_JRPC_METHODS.IFRAME_STATUS,
716
+ params: {
717
+ isIFrameFullScreen: isFull,
718
+ rid
719
+ }
720
+ });
721
+ }
722
+ }
723
+
724
+ /**
725
+ * Scenarios:
726
+ * - Login request or pre-open confirmation windows
727
+ * We try to open here or send a rpc request to iframe that window is blocked.
728
+ */
729
+ async handleWindow(windowId, {
730
+ url,
731
+ target,
732
+ features,
733
+ timeout
734
+ } = {}) {
735
+ const finalUrl = new URL(url || `${this.iframeUrl}/redirect?windowId=${windowId}&sessionNamespace=${window.location.hostname}`);
736
+ const handledWindow = new src_PopupHandler({
737
+ url: finalUrl,
738
+ target,
739
+ features,
740
+ timeout
741
+ });
742
+ handledWindow.open();
743
+ if (!handledWindow.window) {
744
+ this.displayIframe({
745
+ isFull: true
746
+ });
747
+ this.request({
748
+ method: base_controllers_namespaceObject.COMMUNICATION_JRPC_METHODS.WINDOW_BLOCKED,
749
+ params: {
750
+ windowId,
751
+ finalUrl: finalUrl.href
752
+ }
753
+ });
754
+ return;
755
+ }
756
+ // Add to collection only if window is opened
757
+ this.windowRefs.set(windowId, handledWindow);
758
+ handledWindow.once("close", () => {
759
+ // user closed the window
760
+ this.windowRefs.delete(windowId);
761
+ this.request({
762
+ method: base_controllers_namespaceObject.COMMUNICATION_JRPC_METHODS.CLOSED_WINDOW,
763
+ params: {
764
+ windowId
765
+ }
766
+ });
767
+ });
768
+ }
769
+
770
+ /**
771
+ * Internal RPC method. Forwards requests to background via the RPC engine.
772
+ * Also remap ids inbound and outbound
773
+ */
774
+ rpcRequest(payload, callback) {
775
+ const cb = callback;
776
+ const _payload = payload;
777
+ if (!Array.isArray(_payload)) {
778
+ if (!_payload.jsonrpc) {
779
+ _payload.jsonrpc = "2.0";
780
+ }
781
+ }
782
+ this.rpcEngine.handle(_payload, cb);
783
+ }
784
+
785
+ /**
786
+ * When the provider becomes connected, updates internal state and emits
787
+ * required events. Idempotent.
788
+ *
789
+ * @param currentLoginProvider - The login Provider
790
+ * emits TorusInpageProvider#connect
791
+ */
792
+ handleConnect(currentLoginProvider, isLoggedIn) {
793
+ if (!this.state.isConnected) {
794
+ this.state.isConnected = true;
795
+ this.emit("connect", {
796
+ currentLoginProvider,
797
+ isLoggedIn
798
+ });
799
+ loglevel.debug(messages.info.connected(currentLoginProvider));
800
+ }
801
+ }
802
+
803
+ /**
804
+ * When the provider becomes disconnected, updates internal state and emits
805
+ * required events. Idempotent with respect to the isRecoverable parameter.
806
+ *
807
+ * Error codes per the CloseEvent status codes as required by EIP-1193:
808
+ * https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent#Status_codes
809
+ *
810
+ * @param isRecoverable - Whether the disconnection is recoverable.
811
+ * @param errorMessage - A custom error message.
812
+ * emits TorusInpageProvider#disconnect
813
+ */
814
+ handleDisconnect(isRecoverable, errorMessage) {
815
+ if (this.state.isConnected || !this.state.isPermanentlyDisconnected && !isRecoverable) {
816
+ this.state.isConnected = false;
817
+ let error;
818
+ if (isRecoverable) {
819
+ error = new external_web3auth_auth_namespaceObject.EthereumProviderError(1013,
820
+ // Try again later
821
+ errorMessage || messages.errors.disconnected());
822
+ loglevel.debug(error);
823
+ } else {
824
+ error = new external_web3auth_auth_namespaceObject.EthereumProviderError(1011,
825
+ // Internal error
826
+ errorMessage || messages.errors.permanentlyDisconnected());
827
+ loglevel.error(error);
828
+ this.state.currentLoginProvider = null;
829
+ this.state.isLoggedIn = false;
830
+ this.state.widgetVisibility = false;
831
+ this.state.isIFrameFullScreen = false;
832
+ this.state.isPermanentlyDisconnected = true;
833
+ }
834
+ this.emit("disconnect", error);
835
+ }
836
+ }
837
+ handleCloseWindow(params) {
838
+ const {
839
+ windowId
840
+ } = params;
841
+ if (this.windowRefs.has(windowId)) {
842
+ this.windowRefs.get(windowId).close();
843
+ this.windowRefs.delete(windowId);
844
+ }
845
+ }
846
+ }
847
+ defineProperty_default()(CommunicationProvider, "defaultState", {
848
+ buttonPosition: "bottom-left",
849
+ currentLoginProvider: null,
850
+ isIFrameFullScreen: false,
851
+ isBackground: false,
852
+ widgetVisibility: false,
853
+ initialized: false,
854
+ isLoggedIn: false,
855
+ isPermanentlyDisconnected: false,
856
+ isConnected: false,
857
+ hasEmittedConnection: false
858
+ });
859
+ /* harmony default export */ const src_communicationProvider = (CommunicationProvider);
860
+ ;// ../common/src/error.js
861
+ class BaseError extends Error {
862
+ constructor(name, message, options = {}) {
863
+ const {
864
+ cause,
865
+ context
866
+ } = options;
867
+ super(message || name);
868
+ this.name = name;
869
+ this.stack = cause === null || cause === void 0 ? void 0 : cause.stack;
870
+ this.cause = cause;
871
+ this.context = context;
872
+ }
873
+ toJSON() {
874
+ return {
875
+ name: this.name,
876
+ message: this.message,
877
+ context: this.context,
878
+ cause: this.cause
879
+ };
880
+ }
881
+ }
882
+ function ensureError(value) {
883
+ if (value instanceof Error) return value;
884
+ let stringified = "[Unable to stringify the thrown value]";
885
+ try {
886
+ stringified = JSON.stringify(value);
887
+ } catch {
888
+ // ignoring failed stringify
889
+ }
890
+ return new Error(`This value was not thrown as type Error: ${stringified}`);
891
+ }
892
+ ;// ./src/error.ts
893
+
894
+ class AirServiceError extends BaseError {
895
+ static from(error) {
896
+ if (error instanceof AirServiceError) {
897
+ return error;
898
+ } else if (error instanceof Object && "message" in error) {
899
+ if (error.message === "User cancelled login") {
900
+ return new AirServiceError("USER_CANCELLED", error.message);
901
+ }
902
+ return new AirServiceError("UNKNOWN_ERROR", error.message.toString());
903
+ }
904
+ return new AirServiceError("UNKNOWN_ERROR");
905
+ }
906
+ }
907
+ class RealmEmbedError extends AirServiceError {}
908
+ ;// external "fast-deep-equal"
909
+ const external_fast_deep_equal_namespaceObject = require("fast-deep-equal");
910
+ var external_fast_deep_equal_default = /*#__PURE__*/__webpack_require__.n(external_fast_deep_equal_namespaceObject);
911
+ ;// ./src/inPageProvider.ts
912
+
913
+
914
+
915
+
916
+
917
+
918
+
919
+
920
+
921
+ /**
922
+ * @param connectionStream - A Node.js duplex stream
923
+ * @param opts - An options bag
924
+ */
925
+ class AirInPageProvider extends baseProvider {
926
+ constructor(connectionStream, {
927
+ maxEventListeners = 100,
928
+ jsonRpcStreamName = "provider"
929
+ }) {
930
+ super(connectionStream, {
931
+ maxEventListeners,
932
+ jsonRpcStreamName
933
+ });
934
+
935
+ // private state
936
+ /**
937
+ * The chain ID of the currently connected EVM chain.
938
+ * See [chainId.network]{@link https://chainid.network} for more information.
939
+ */
940
+ defineProperty_default()(this, "chainId", void 0);
941
+ /**
942
+ * The user's currently selected EVM address.
943
+ * If null, Torus is either locked or the user has not permitted any
944
+ * addresses to be viewed.
945
+ */
946
+ defineProperty_default()(this, "selectedAddress", void 0);
947
+ defineProperty_default()(this, "tryWindowHandle", void 0);
948
+ this.state = objectSpread2_default()({}, AirInPageProvider.defaultState);
949
+
950
+ // public state
951
+ this.selectedAddress = null;
952
+ this.chainId = null;
953
+ this.handleAccountsChanged = this.handleAccountsChanged.bind(this);
954
+ this.handleChainChanged = this.handleChainChanged.bind(this);
955
+ this.handleUnlockStateChanged = this.handleUnlockStateChanged.bind(this);
956
+
957
+ // setup own event listeners
958
+
959
+ // EIP-1193 connect
960
+ this.on("connect", () => {
961
+ this.state.isConnected = true;
962
+ });
963
+ const jsonRpcNotificationHandler = payload => {
964
+ const {
965
+ method,
966
+ params
967
+ } = payload;
968
+ if (method === base_controllers_namespaceObject.PROVIDER_NOTIFICATIONS.ACCOUNTS_CHANGED) {
969
+ this.handleAccountsChanged(params);
970
+ } else if (method === base_controllers_namespaceObject.PROVIDER_NOTIFICATIONS.UNLOCK_STATE_CHANGED) {
971
+ this.handleUnlockStateChanged(params);
972
+ } else if (method === base_controllers_namespaceObject.PROVIDER_NOTIFICATIONS.CHAIN_CHANGED) {
973
+ this.handleChainChanged(params);
974
+ } else if (EMITTED_NOTIFICATIONS.includes(method)) {
975
+ this.emit("data", payload);
976
+ this.emit("notification", params.result);
977
+ this.emit("message", {
978
+ type: method,
979
+ data: params
980
+ });
981
+ }
982
+ };
983
+
984
+ // json rpc notification listener
985
+ this.jsonRpcConnectionEvents.on("notification", jsonRpcNotificationHandler);
986
+ }
987
+
988
+ /**
989
+ * Returns whether the inpage provider is connected to Torus.
990
+ */
991
+ isConnected() {
992
+ return this.state.isConnected;
993
+ }
994
+
995
+ // Private Methods
996
+ //= ===================
997
+ /**
998
+ * Constructor helper.
999
+ * Populates initial state by calling 'wallet_getProviderState' and emits
1000
+ * necessary events.
1001
+ */
1002
+ async initializeState() {
1003
+ try {
1004
+ const {
1005
+ accounts,
1006
+ chainId,
1007
+ isUnlocked
1008
+ } = await this.request({
1009
+ method: base_controllers_namespaceObject.PROVIDER_JRPC_METHODS.GET_PROVIDER_STATE,
1010
+ params: []
1011
+ });
1012
+
1013
+ // indicate that we've connected, for EIP-1193 compliance
1014
+ this.emit("connect", {
1015
+ chainId
1016
+ });
1017
+ this.handleChainChanged({
1018
+ chainId
1019
+ });
1020
+ this.handleUnlockStateChanged({
1021
+ accounts,
1022
+ isUnlocked
1023
+ });
1024
+ this.handleAccountsChanged(accounts);
1025
+ } catch (error) {
1026
+ loglevel.error("WsEmbed: Failed to get initial state. Please report this bug.", error);
1027
+ } finally {
1028
+ loglevel.info("initialized provider state");
1029
+ this.state.initialized = true;
1030
+ }
1031
+ }
1032
+
1033
+ /**
1034
+ * Internal RPC method. Forwards requests to background via the RPC engine.
1035
+ * Also remap ids inbound and outbound
1036
+ */
1037
+ rpcRequest(payload, callback, isInternal = false) {
1038
+ let cb = callback;
1039
+ const _payload = payload;
1040
+ if (!Array.isArray(_payload)) {
1041
+ if (!_payload.jsonrpc) {
1042
+ _payload.jsonrpc = "2.0";
1043
+ }
1044
+ if (_payload.method === "eth_accounts" || _payload.method === "eth_requestAccounts") {
1045
+ // handle accounts changing
1046
+ cb = (err, res) => {
1047
+ this.handleAccountsChanged(res.result || [], _payload.method === "eth_accounts", isInternal);
1048
+ callback(err, res);
1049
+ };
1050
+ } else if (_payload.method === "wallet_getProviderState") {
1051
+ this.rpcEngine.handle(payload, cb);
1052
+ return;
1053
+ }
1054
+ }
1055
+ this.tryWindowHandle(_payload, cb);
1056
+ }
1057
+
1058
+ /**
1059
+ * When the provider becomes connected, updates internal state and emits
1060
+ * required events. Idempotent.
1061
+ *
1062
+ * @param chainId - The ID of the newly connected chain.
1063
+ * emits TorusInpageProvider#connect
1064
+ */
1065
+ handleConnect(chainId) {
1066
+ if (!this.state.isConnected) {
1067
+ this.state.isConnected = true;
1068
+ this.emit("connect", {
1069
+ chainId
1070
+ });
1071
+ loglevel.debug(messages.info.connected(chainId));
1072
+ }
1073
+ }
1074
+
1075
+ /**
1076
+ * When the provider becomes disconnected, updates internal state and emits
1077
+ * required events. Idempotent with respect to the isRecoverable parameter.
1078
+ *
1079
+ * Error codes per the CloseEvent status codes as required by EIP-1193:
1080
+ * https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent#Status_codes
1081
+ *
1082
+ * @param isRecoverable - Whether the disconnection is recoverable.
1083
+ * @param errorMessage - A custom error message.
1084
+ * emits TorusInpageProvider#disconnect
1085
+ */
1086
+ handleDisconnect(isRecoverable, errorMessage) {
1087
+ if (this.state.isConnected || !this.state.isPermanentlyDisconnected && !isRecoverable) {
1088
+ this.state.isConnected = false;
1089
+ let error;
1090
+ if (isRecoverable) {
1091
+ error = new external_web3auth_auth_namespaceObject.EthereumProviderError(1013,
1092
+ // Try again later
1093
+ errorMessage || messages.errors.disconnected());
1094
+ loglevel.debug(error);
1095
+ } else {
1096
+ error = new external_web3auth_auth_namespaceObject.EthereumProviderError(1011,
1097
+ // Internal error
1098
+ errorMessage || messages.errors.permanentlyDisconnected());
1099
+ loglevel.error(error);
1100
+ this.chainId = null;
1101
+ this.state.accounts = null;
1102
+ this.selectedAddress = null;
1103
+ this.state.isUnlocked = false;
1104
+ this.state.isPermanentlyDisconnected = true;
1105
+ }
1106
+ this.emit("disconnect", error);
1107
+ }
1108
+ }
1109
+
1110
+ /**
1111
+ * Called when accounts may have changed.
1112
+ */
1113
+ handleAccountsChanged(accounts, isEthAccounts = false, isInternal = false) {
1114
+ // defensive programming
1115
+ let finalAccounts = accounts;
1116
+ if (!Array.isArray(finalAccounts)) {
1117
+ loglevel.error("WsEmbed: Received non-array accounts parameter. Please report this bug.", finalAccounts);
1118
+ finalAccounts = [];
1119
+ }
1120
+ for (const account of accounts) {
1121
+ if (typeof account !== "string") {
1122
+ loglevel.error("WsEmbed: Received non-string account. Please report this bug.", accounts);
1123
+ finalAccounts = [];
1124
+ break;
1125
+ }
1126
+ }
1127
+
1128
+ // emit accountsChanged if anything about the accounts array has changed
1129
+ if (!external_fast_deep_equal_default()(this.state.accounts, finalAccounts)) {
1130
+ // we should always have the correct accounts even before eth_accounts
1131
+ // returns, except in cases where isInternal is true
1132
+ if (isEthAccounts && Array.isArray(this.state.accounts) && this.state.accounts.length > 0 && !isInternal) {
1133
+ loglevel.error('WsEmbed: "eth_accounts" unexpectedly updated accounts. Please report this bug.', finalAccounts);
1134
+ }
1135
+ this.state.accounts = finalAccounts;
1136
+ this.emit("accountsChanged", finalAccounts);
1137
+ }
1138
+
1139
+ // handle selectedAddress
1140
+ if (this.selectedAddress !== finalAccounts[0]) {
1141
+ this.selectedAddress = finalAccounts[0] || null;
1142
+ }
1143
+ }
1144
+
1145
+ /**
1146
+ * Upon receipt of a new chainId and networkVersion, emits corresponding
1147
+ * events and sets relevant public state.
1148
+ * Does nothing if neither the chainId nor the networkVersion are different
1149
+ * from existing values.
1150
+ *
1151
+ * emits TorusInpageProvider#chainChanged
1152
+ * @param networkInfo - An object with network info.
1153
+ */
1154
+ handleChainChanged({
1155
+ chainId
1156
+ } = {}) {
1157
+ if (!chainId) {
1158
+ loglevel.error("WsEmbed: Received invalid network parameters. Please report this bug.", {
1159
+ chainId
1160
+ });
1161
+ return;
1162
+ }
1163
+ if (chainId === "loading") {
1164
+ this.handleDisconnect(true);
1165
+ } else {
1166
+ this.handleConnect(chainId);
1167
+ if (chainId !== this.chainId) {
1168
+ this.chainId = chainId;
1169
+ if (this.state.initialized) {
1170
+ this.emit("chainChanged", this.chainId);
1171
+ }
1172
+ }
1173
+ }
1174
+ }
1175
+
1176
+ /**
1177
+ * Upon receipt of a new isUnlocked state, sets relevant public state.
1178
+ * Calls the accounts changed handler with the received accounts, or an empty
1179
+ * array.
1180
+ *
1181
+ * Does nothing if the received value is equal to the existing value.
1182
+ * There are no lock/unlock events.
1183
+ *
1184
+ * @param opts - Options bag.
1185
+ */
1186
+ handleUnlockStateChanged({
1187
+ accounts,
1188
+ isUnlocked
1189
+ } = {}) {
1190
+ if (typeof isUnlocked !== "boolean") {
1191
+ loglevel.error("WsEmbed: Received invalid isUnlocked parameter. Please report this bug.", {
1192
+ isUnlocked
1193
+ });
1194
+ return;
1195
+ }
1196
+ if (isUnlocked !== this.state.isUnlocked) {
1197
+ this.state.isUnlocked = isUnlocked;
1198
+ this.handleAccountsChanged(accounts || []);
1199
+ }
1200
+ }
1201
+ }
1202
+ defineProperty_default()(AirInPageProvider, "defaultState", {
1203
+ accounts: null,
1204
+ isConnected: false,
1205
+ isUnlocked: false,
1206
+ initialized: false,
1207
+ isPermanentlyDisconnected: false,
1208
+ hasEmittedConnection: false
1209
+ });
1210
+ /* harmony default export */ const inPageProvider = (AirInPageProvider);
1211
+ class TorusInPageProvider extends AirInPageProvider {}
1212
+ ;// external "rxjs"
1213
+ const external_rxjs_namespaceObject = require("rxjs");
1214
+ ;// ./src/messageService.ts
1215
+
1216
+ var _AirMessageService;
1217
+
1218
+
1219
+
1220
+
1221
+
1222
+
1223
+ const REALM_EMBED_MESSAGES = [AirMessageTypes.LOGIN_CLAIM_STATE, AirMessageTypes.CLOSE_MODAL, AirMessageTypes.SERVICE_INITIALIZED, AirMessageTypes.SERVICE_INITIALIZED_ERROR, AirMessageTypes.DEPLOY_SMART_ACCOUNT_RESPONSE];
1224
+ const AUTH_EMBED_MESSAGES = [AirAuthMessageTypes.LOGIN_RESPONSE, AirAuthMessageTypes.USER_INFO_RESPONSE, AirAuthMessageTypes.PARTNER_USER_INFO_RESPONSE, AirAuthMessageTypes.REFRESH_TOKEN_RESPONSE, AirAuthMessageTypes.INITIALIZATION_RESPONSE, AirAuthMessageTypes.LOGOUT_RESPONSE, AirAuthMessageTypes.IFRAME_VISIBILITY_REQUEST, AirAuthMessageTypes.SETUP_WALLET_REQUEST];
1225
+ class AirMessageService {
1226
+ constructor() {
1227
+ defineProperty_default()(this, "airMessages$", void 0);
1228
+ defineProperty_default()(this, "_loginState$", void 0);
1229
+ defineProperty_default()(this, "_authMessage$", void 0);
1230
+ defineProperty_default()(this, "_authIframe", null);
1231
+ defineProperty_default()(this, "closeAuthMessageListeners", null);
1232
+ defineProperty_default()(this, "closeRealmMessageListeners", null);
1233
+ }
1234
+ static get instance() {
1235
+ if (!AirMessageService._instance) {
1236
+ AirMessageService._instance = new AirMessageService();
1237
+ }
1238
+ return AirMessageService._instance;
1239
+ }
1240
+ get messages$() {
1241
+ return this.airMessages$.asObservable();
1242
+ }
1243
+ get loginState$() {
1244
+ return this._loginState$;
1245
+ }
1246
+ get authMessage$() {
1247
+ return this._authMessage$.asObservable();
1248
+ }
1249
+ async openAuthObservables({
1250
+ authIframeOrigin
1251
+ }) {
1252
+ this.closeAuthObservables();
1253
+ this.setupAuthObservables();
1254
+ const handleAuthMessage = async ev => {
1255
+ if (ev.origin !== authIframeOrigin || !ev.data || !(ev.data instanceof Object)) return;
1256
+ loglevel.debug("Embed auth message received from auth", ev.data);
1257
+ if (AUTH_EMBED_MESSAGES.includes(ev.data.type)) {
1258
+ this._authMessage$.next(ev.data);
1259
+ }
1260
+ };
1261
+ window.addEventListener("message", handleAuthMessage);
1262
+ this.closeAuthMessageListeners = () => {
1263
+ window.removeEventListener("message", handleAuthMessage);
1264
+ };
1265
+ }
1266
+ async openRealmObservables({
1267
+ walletIframeOrigin
1268
+ }) {
1269
+ this.closeRealmObservables();
1270
+ this.setupRealmObservables();
1271
+ const handleMessage = async ev => {
1272
+ if (ev.origin !== walletIframeOrigin || !ev.data || !(ev.data instanceof Object)) return;
1273
+ // filter out torus and communication provider messages
1274
+ if ("target" in ev.data && (ev.data.target === "embed_torus" || ev.data.target === "embed_communication")) return;
1275
+ loglevel.debug("Embed realm message received from wallet", ev.data);
1276
+ if (REALM_EMBED_MESSAGES.includes(ev.data.type)) {
1277
+ this.airMessages$.next(ev.data);
1278
+ }
1279
+ };
1280
+ window.addEventListener("message", handleMessage);
1281
+ this.closeRealmMessageListeners = () => {
1282
+ window.removeEventListener("message", handleMessage);
1283
+ };
1284
+ }
1285
+
1286
+ // Note: Only use when embed is needed in airAuth
1287
+ setupAuthIframe(authIframe) {
1288
+ this._authIframe = authIframe;
1289
+ }
1290
+ setupIframeCommunication(walletIframe) {
1291
+ if (!this._authIframe) return;
1292
+ const channel = new MessageChannel();
1293
+ const authOrigin = new URL(this._authIframe.src).origin;
1294
+ this._authIframe.contentWindow.postMessage({
1295
+ type: AirAuthMessageTypes.INIT_WALLET_COMMUNICATION
1296
+ }, authOrigin, [channel.port1]);
1297
+ const walletOrigin = new URL(walletIframe.src).origin;
1298
+ walletIframe.contentWindow.postMessage({
1299
+ type: AirMessageTypes.INIT_AUTH_COMMUNICATION
1300
+ }, walletOrigin, [channel.port2]);
1301
+ this._authIframe = undefined;
1302
+ }
1303
+ onInitialized() {
1304
+ return (0,external_rxjs_namespaceObject.firstValueFrom)(this.messages$.pipe((0,external_rxjs_namespaceObject.filter)(msg => msg.type === AirMessageTypes.SERVICE_INITIALIZED)));
1305
+ }
1306
+ sendLoginRequest(walletIframe, payload) {
1307
+ const response = (0,external_rxjs_namespaceObject.lastValueFrom)(this.loginState$.pipe((0,external_rxjs_namespaceObject.takeWhile)(msg => (!payload.skipClaimFlow || msg.payload.state !== "connected") && msg.payload.state !== "logged_in" && msg.payload.state !== "claim_flow_cancelled", true), (0,external_rxjs_namespaceObject.tap)(msg => {
1308
+ switch (msg.payload.state) {
1309
+ case "claim_flow_cancelled":
1310
+ throw new RealmEmbedError(msg.payload.errorName, msg.payload.errorMessage);
1311
+ default:
1312
+ break;
1313
+ }
1314
+ })));
1315
+ const {
1316
+ origin
1317
+ } = new URL(walletIframe.src);
1318
+ walletIframe.contentWindow.postMessage({
1319
+ type: AirMessageTypes.LOGIN_REQUEST,
1320
+ payload
1321
+ }, origin);
1322
+ return response;
1323
+ }
1324
+ sendClaimRequest(walletIframe, options) {
1325
+ const response = (0,external_rxjs_namespaceObject.lastValueFrom)((0,external_rxjs_namespaceObject.forkJoin)([this.loginState$.pipe((0,external_rxjs_namespaceObject.takeWhile)(msg => !["logged_in", "claim_flow_cancelled"].includes(msg.payload.state), true), (0,external_rxjs_namespaceObject.tap)(msg => {
1326
+ if (msg.payload.state === "claim_flow_cancelled") {
1327
+ throw new RealmEmbedError(msg.payload.errorName, msg.payload.errorMessage);
1328
+ }
1329
+ }), (0,external_rxjs_namespaceObject.last)()), this.messages$.pipe((0,external_rxjs_namespaceObject.filter)(msg => msg.type === AirMessageTypes.CLOSE_MODAL), (0,external_rxjs_namespaceObject.first)())]));
1330
+ const {
1331
+ origin
1332
+ } = new URL(walletIframe.src);
1333
+ walletIframe.contentWindow.postMessage({
1334
+ type: AirMessageTypes.CLAIM_REQUEST,
1335
+ payload: {
1336
+ token: options === null || options === void 0 ? void 0 : options.token,
1337
+ claimInBackground: options === null || options === void 0 ? void 0 : options.background
1338
+ }
1339
+ }, origin);
1340
+ return response;
1341
+ }
1342
+ sendDeploySmartAccountRequest(walletIframe) {
1343
+ const response = (0,external_rxjs_namespaceObject.firstValueFrom)(this.messages$.pipe((0,external_rxjs_namespaceObject.filter)(msg => msg.type === AirMessageTypes.DEPLOY_SMART_ACCOUNT_RESPONSE)));
1344
+ const {
1345
+ origin
1346
+ } = new URL(walletIframe.src);
1347
+ walletIframe.contentWindow.postMessage({
1348
+ type: AirMessageTypes.DEPLOY_SMART_ACCOUNT_REQUEST
1349
+ }, origin);
1350
+ return response;
1351
+ }
1352
+ async sendUserInfoRequest(authIframe) {
1353
+ const response = (0,external_rxjs_namespaceObject.firstValueFrom)(this.authMessage$.pipe((0,external_rxjs_namespaceObject.filter)(msg => msg.type === AirAuthMessageTypes.USER_INFO_RESPONSE)));
1354
+ const {
1355
+ origin
1356
+ } = new URL(authIframe.src);
1357
+ authIframe.contentWindow.postMessage({
1358
+ type: AirAuthMessageTypes.USER_INFO_REQUEST
1359
+ }, origin);
1360
+ return response;
1361
+ }
1362
+ async sendPartnerUserInfoRequest(authIframe) {
1363
+ const response = (0,external_rxjs_namespaceObject.firstValueFrom)(this.authMessage$.pipe((0,external_rxjs_namespaceObject.filter)(msg => msg.type === AirAuthMessageTypes.PARTNER_USER_INFO_RESPONSE)));
1364
+ const {
1365
+ origin
1366
+ } = new URL(authIframe.src);
1367
+ authIframe.contentWindow.postMessage({
1368
+ type: AirAuthMessageTypes.PARTNER_USER_INFO_REQUEST
1369
+ }, origin);
1370
+ return response;
1371
+ }
1372
+ async sendAuthLoginRequest(authIframe, payload) {
1373
+ const response = (0,external_rxjs_namespaceObject.firstValueFrom)(this.authMessage$.pipe((0,external_rxjs_namespaceObject.filter)(msg => msg.type === AirAuthMessageTypes.LOGIN_RESPONSE)));
1374
+ const {
1375
+ origin
1376
+ } = new URL(authIframe.src);
1377
+ authIframe.contentWindow.postMessage({
1378
+ type: AirAuthMessageTypes.LOGIN_REQUEST,
1379
+ payload
1380
+ }, origin);
1381
+ return response;
1382
+ }
1383
+ async logoutAuth(authIframe) {
1384
+ const response = (0,external_rxjs_namespaceObject.firstValueFrom)(this.authMessage$.pipe((0,external_rxjs_namespaceObject.filter)(msg => msg.type === AirAuthMessageTypes.LOGOUT_RESPONSE)));
1385
+ const {
1386
+ origin
1387
+ } = new URL(authIframe.src);
1388
+ authIframe.contentWindow.postMessage({
1389
+ type: AirAuthMessageTypes.LOGOUT_REQUEST
1390
+ }, origin);
1391
+ return response;
1392
+ }
1393
+ async waitForAuthInitialization() {
1394
+ const response = await (0,external_rxjs_namespaceObject.firstValueFrom)(this._authMessage$.pipe((0,external_rxjs_namespaceObject.filter)(msg => msg.type === AirAuthMessageTypes.INITIALIZATION_RESPONSE)));
1395
+ if (response.payload.success === false) {
1396
+ throw new RealmEmbedError(response.payload.errorName, response.payload.errorMessage);
1397
+ }
1398
+ return response.payload;
1399
+ }
1400
+ async waitForWalletInitialization() {
1401
+ const response = await (0,external_rxjs_namespaceObject.firstValueFrom)(this.messages$.pipe((0,external_rxjs_namespaceObject.filter)(msg => msg.type === AirMessageTypes.SERVICE_INITIALIZED || msg.type === AirMessageTypes.SERVICE_INITIALIZED_ERROR)));
1402
+ if (response.type === AirMessageTypes.SERVICE_INITIALIZED_ERROR) {
1403
+ throw new RealmEmbedError(response.payload.errorName, response.payload.errorMessage);
1404
+ }
1405
+ }
1406
+ closeAuthObservables() {
1407
+ if (this._authMessage$ && !this._authMessage$.closed) this._authMessage$.complete();
1408
+ if (this.closeAuthMessageListeners) this.closeAuthMessageListeners();
1409
+ }
1410
+ closeRealmObservables() {
1411
+ if (this.airMessages$ && !this.airMessages$.closed) this.airMessages$.complete();
1412
+ if (this.closeRealmMessageListeners) this.closeRealmMessageListeners();
1413
+ }
1414
+ setupAuthObservables() {
1415
+ this._authMessage$ = new external_rxjs_namespaceObject.Subject();
1416
+ }
1417
+ setupRealmObservables() {
1418
+ this.airMessages$ = new external_rxjs_namespaceObject.Subject();
1419
+ this._loginState$ = this.airMessages$.pipe((0,external_rxjs_namespaceObject.filter)(msg => msg.type === AirMessageTypes.LOGIN_CLAIM_STATE), (0,external_rxjs_namespaceObject.distinctUntilChanged)((external_fast_deep_equal_default())));
1420
+ }
1421
+ }
1422
+ _AirMessageService = AirMessageService;
1423
+ // eslint-disable-next-line no-use-before-define
1424
+ defineProperty_default()(AirMessageService, "_instance", void 0);
1425
+ /* harmony default export */ const messageService = (AirMessageService.instance);
1426
+ ;// ./src/siteMetadata.ts
1427
+ /**
1428
+ * Returns whether the given image URL exists
1429
+ * @param url - the url of the image
1430
+ * @returns whether the image exists
1431
+ */
1432
+ function imgExists(url) {
1433
+ return new Promise((resolve, reject) => {
1434
+ try {
1435
+ const img = document.createElement("img");
1436
+ img.onload = () => resolve(true);
1437
+ img.onerror = () => resolve(false);
1438
+ img.src = url;
1439
+ } catch (e) {
1440
+ reject(e);
1441
+ }
1442
+ });
1443
+ }
1444
+
1445
+ /**
1446
+ * Extracts a name for the site from the DOM
1447
+ */
1448
+ const getSiteName = window => {
1449
+ const {
1450
+ document
1451
+ } = window;
1452
+ const siteName = document.querySelector('head > meta[property="og:site_name"]');
1453
+ if (siteName) {
1454
+ return siteName.content;
1455
+ }
1456
+ const metaTitle = document.querySelector('head > meta[name="title"]');
1457
+ if (metaTitle) {
1458
+ return metaTitle.content;
1459
+ }
1460
+ if (document.title && document.title.length > 0) {
1461
+ return document.title;
1462
+ }
1463
+ return window.location.hostname;
1464
+ };
1465
+
1466
+ /**
1467
+ * Extracts an icon for the site from the DOM
1468
+ */
1469
+ async function getSiteIcon(window) {
1470
+ try {
1471
+ const {
1472
+ document
1473
+ } = window;
1474
+
1475
+ // Use the site's favicon if it exists
1476
+ let icon = document.querySelector('head > link[rel="shortcut icon"]');
1477
+ if (icon && (await imgExists(icon.href))) {
1478
+ return icon.href;
1479
+ }
1480
+
1481
+ // Search through available icons in no particular order
1482
+ icon = Array.from(document.querySelectorAll('head > link[rel="icon"]')).find(_icon => Boolean(_icon.href));
1483
+ if (icon && (await imgExists(icon.href))) {
1484
+ return icon.href;
1485
+ }
1486
+ return "";
1487
+ } catch (error) {
1488
+ return "";
1489
+ }
1490
+ }
1491
+
1492
+ /**
1493
+ * Gets site metadata and returns it
1494
+ *
1495
+ */
1496
+ const getSiteMetadata = async () => ({
1497
+ name: getSiteName(window),
1498
+ icon: await getSiteIcon(window)
1499
+ });
1500
+ /* harmony default export */ const siteMetadata = (getSiteMetadata);
1501
+ ;// ./src/embed.ts
1502
+
1503
+
1504
+
1505
+ function _classPrivateFieldGet(s, a) { return s.get(_assertClassBrand(s, a)); }
1506
+ function _classPrivateFieldSet(s, a, r) { return s.set(_assertClassBrand(s, a), r), r; }
1507
+ function _assertClassBrand(e, t, n) { if ("function" == typeof e ? e === t : e.has(t)) return arguments.length < 3 ? t : n; throw new TypeError("Private element is not present on this object"); }
1508
+
1509
+
1510
+
1511
+
1512
+
1513
+
1514
+
1515
+
1516
+
1517
+
1518
+
1519
+
1520
+
1521
+ // preload for iframe doesn't work https://bugs.chromium.org/p/chromium/issues/detail?id=593267
1522
+ (async function preLoadIframe() {
1523
+ try {
1524
+ if (typeof document === "undefined") return;
1525
+ const airWalletIframeHtml = document.createElement("link");
1526
+ const {
1527
+ walletUrl: airWalletUrl
1528
+ } = AIR_URLS.production;
1529
+ airWalletIframeHtml.href = `${airWalletUrl}/frame`;
1530
+ airWalletIframeHtml.crossOrigin = "anonymous";
1531
+ airWalletIframeHtml.type = "text/html";
1532
+ airWalletIframeHtml.rel = "prefetch";
1533
+ if (airWalletIframeHtml.relList && airWalletIframeHtml.relList.supports) {
1534
+ if (airWalletIframeHtml.relList.supports("prefetch")) {
1535
+ document.head.appendChild(airWalletIframeHtml);
1536
+ }
1537
+ }
1538
+ } catch (error) {
1539
+ loglevel.warn(error);
1540
+ }
1541
+ })();
1542
+ const COMMUNICATION_UNSAFE_METHODS = new Set([base_controllers_namespaceObject.COMMUNICATION_JRPC_METHODS.SET_PROVIDER]);
1543
+ const PROVIDER_UNSAFE_METHODS = new Set([ethereum_controllers_namespaceObject.METHOD_TYPES.ETH_SIGN, ethereum_controllers_namespaceObject.METHOD_TYPES.ETH_SIGN_TYPED_DATA_V4, ethereum_controllers_namespaceObject.METHOD_TYPES.PERSONAL_SIGN, ethereum_controllers_namespaceObject.METHOD_TYPES.ETH_TRANSACTION, ethereum_controllers_namespaceObject.METHOD_TYPES.ADD_CHAIN, ethereum_controllers_namespaceObject.METHOD_TYPES.SWITCH_CHAIN]);
1544
+ const embedChainConfig = {
1545
+ polygon: {
1546
+ chainNamespace: base_controllers_namespaceObject.CHAIN_NAMESPACES.EIP155,
1547
+ chainId: "0x89",
1548
+ decimals: 18,
1549
+ displayName: "Polygon",
1550
+ blockExplorerUrl: "https://polygonscan.com",
1551
+ logo: "https://cryptologos.cc/logos/polygon-matic-logo.png",
1552
+ ticker: "MATIC",
1553
+ tickerName: "Matic Network Token"
1554
+ },
1555
+ polygonAmoy: {
1556
+ chainNamespace: base_controllers_namespaceObject.CHAIN_NAMESPACES.EIP155,
1557
+ chainId: "0x13882",
1558
+ decimals: 18,
1559
+ displayName: "Polygon Amoy",
1560
+ blockExplorerUrl: "https://amoy.polygonscan.com",
1561
+ logo: "https://cryptologos.cc/logos/polygon-matic-logo.png",
1562
+ ticker: "MATIC",
1563
+ tickerName: "Matic Network Token",
1564
+ isTestnet: true
1565
+ }
1566
+ };
1567
+ const web3AuthClientId = "BANbxuTYFGeYi8HxUzaPQkvQlSAXiKRtUqb1vqsXbsZsZKrNr05PEPCM2J2PhUJZpIYl0XzQa6jxUjnYzSU9LXY";
1568
+ const web3AuthNetwork = external_web3auth_auth_namespaceObject.WEB3AUTH_NETWORK.SAPPHIRE_MAINNET;
1569
+ var _embedNonce = /*#__PURE__*/new WeakMap();
1570
+ var _provider = /*#__PURE__*/new WeakMap();
1571
+ var _isInitialized = /*#__PURE__*/new WeakMap();
1572
+ var _rehydrationState = /*#__PURE__*/new WeakMap();
1573
+ var _modalZIndex = /*#__PURE__*/new WeakMap();
1574
+ var _communicationProvider = /*#__PURE__*/new WeakMap();
1575
+ var _buttonPosition = /*#__PURE__*/new WeakMap();
1576
+ var _realmPartnerId = /*#__PURE__*/new WeakMap();
1577
+ var _web3AuthClientId = /*#__PURE__*/new WeakMap();
1578
+ var _web3AuthNetwork = /*#__PURE__*/new WeakMap();
1579
+ var _isPluginMode = /*#__PURE__*/new WeakMap();
1580
+ var _confirmationStrategy = /*#__PURE__*/new WeakMap();
1581
+ var _walletIframe = /*#__PURE__*/new WeakMap();
1582
+ var _buildEnv = /*#__PURE__*/new WeakMap();
1583
+ var _walletAddresses = /*#__PURE__*/new WeakMap();
1584
+ var _realmId = /*#__PURE__*/new WeakMap();
1585
+ var _loginToken = /*#__PURE__*/new WeakMap();
1586
+ var _sessionId = /*#__PURE__*/new WeakMap();
1587
+ var _embedListeners = /*#__PURE__*/new WeakMap();
1588
+ var _RealmEmbed_brand = /*#__PURE__*/new WeakSet();
1589
+ class RealmEmbed {
1590
+ constructor({
1591
+ modalZIndex = 99999,
1592
+ partnerId
1593
+ }) {
1594
+ classPrivateMethodInitSpec_default()(this, _RealmEmbed_brand);
1595
+ classPrivateFieldInitSpec_default()(this, _embedNonce, (0,base_controllers_namespaceObject.randomId)());
1596
+ classPrivateFieldInitSpec_default()(this, _provider, void 0);
1597
+ classPrivateFieldInitSpec_default()(this, _isInitialized, void 0);
1598
+ classPrivateFieldInitSpec_default()(this, _rehydrationState, void 0);
1599
+ classPrivateFieldInitSpec_default()(this, _modalZIndex, void 0);
1600
+ classPrivateFieldInitSpec_default()(this, _communicationProvider, void 0);
1601
+ classPrivateFieldInitSpec_default()(this, _buttonPosition, void 0);
1602
+ classPrivateFieldInitSpec_default()(this, _realmPartnerId, void 0);
1603
+ classPrivateFieldInitSpec_default()(this, _web3AuthClientId, void 0);
1604
+ classPrivateFieldInitSpec_default()(this, _web3AuthNetwork, void 0);
1605
+ classPrivateFieldInitSpec_default()(this, _isPluginMode, void 0);
1606
+ classPrivateFieldInitSpec_default()(this, _confirmationStrategy, void 0);
1607
+ classPrivateFieldInitSpec_default()(this, _walletIframe, void 0);
1608
+ classPrivateFieldInitSpec_default()(this, _buildEnv, void 0);
1609
+ classPrivateFieldInitSpec_default()(this, _walletAddresses, void 0);
1610
+ classPrivateFieldInitSpec_default()(this, _realmId, void 0);
1611
+ classPrivateFieldInitSpec_default()(this, _loginToken, void 0);
1612
+ classPrivateFieldInitSpec_default()(this, _sessionId, void 0);
1613
+ classPrivateFieldInitSpec_default()(this, _embedListeners, []);
1614
+ _classPrivateFieldSet(_isInitialized, this, false); // init done
1615
+ _classPrivateFieldSet(_modalZIndex, this, modalZIndex);
1616
+ _classPrivateFieldSet(_realmPartnerId, this, partnerId);
1617
+ _classPrivateFieldSet(_web3AuthClientId, this, web3AuthClientId);
1618
+ _classPrivateFieldSet(_web3AuthNetwork, this, web3AuthNetwork);
1619
+ }
1620
+ get isConnected() {
1621
+ return !!_classPrivateFieldGet(_walletAddresses, this) && _classPrivateFieldGet(_communicationProvider, this).isLoggedIn;
1622
+ }
1623
+ get isInitialized() {
1624
+ return _classPrivateFieldGet(_isInitialized, this) && !!_classPrivateFieldGet(_rehydrationState, this);
1625
+ }
1626
+ get isLoggedIn() {
1627
+ return !!_classPrivateFieldGet(_realmId, this) && this.isConnected;
1628
+ }
1629
+ get getBuildEnv() {
1630
+ return _classPrivateFieldGet(_buildEnv, this);
1631
+ }
1632
+ get walletAddresses() {
1633
+ var _classPrivateFieldGet2;
1634
+ return (_classPrivateFieldGet2 = _classPrivateFieldGet(_walletAddresses, this)) !== null && _classPrivateFieldGet2 !== void 0 ? _classPrivateFieldGet2 : null;
1635
+ }
1636
+ get sessionId() {
1637
+ var _classPrivateFieldGet3;
1638
+ return (_classPrivateFieldGet3 = _classPrivateFieldGet(_sessionId, this)) !== null && _classPrivateFieldGet3 !== void 0 ? _classPrivateFieldGet3 : null;
1639
+ }
1640
+ get realmId() {
1641
+ var _classPrivateFieldGet4;
1642
+ return (_classPrivateFieldGet4 = _classPrivateFieldGet(_realmId, this)) !== null && _classPrivateFieldGet4 !== void 0 ? _classPrivateFieldGet4 : null;
1643
+ }
1644
+ get provider() {
1645
+ return _classPrivateFieldGet(_walletAddresses, this) ? _classPrivateFieldGet(_provider, this) : null;
1646
+ }
1647
+ async init({
1648
+ buildEnv = EMBED_BUILD_ENV.PRODUCTION,
1649
+ enableLogging = false,
1650
+ skipRehydration = false
1651
+ // confirmationStrategy = CONFIRMATION_STRATEGY.DEFAULT,
1652
+ } = {}) {
1653
+ if (_classPrivateFieldGet(_isInitialized, this)) throw new RealmEmbedError("ALREADY_INITIALISED", "Already initialized");
1654
+ _classPrivateFieldSet(_buildEnv, this, buildEnv);
1655
+ _classPrivateFieldSet(_confirmationStrategy, this, base_controllers_namespaceObject.CONFIRMATION_STRATEGY.DEFAULT);
1656
+ _classPrivateFieldSet(_buttonPosition, this, base_controllers_namespaceObject.BUTTON_POSITION.BOTTOM_LEFT);
1657
+ const {
1658
+ walletUrl,
1659
+ logLevel
1660
+ } = AIR_URLS[buildEnv];
1661
+ loglevel.info(walletUrl, "url loaded");
1662
+ loglevel.setDefaultLevel(logLevel);
1663
+ if (enableLogging) loglevel.enableAll();else loglevel.disableAll();
1664
+ const walletIframeUrl = _assertClassBrand(_RealmEmbed_brand, this, _getWsIframeUrl).call(this);
1665
+ const walletIframeOrigin = walletIframeUrl.origin;
1666
+ messageService.openRealmObservables({
1667
+ walletIframeOrigin
1668
+ });
1669
+ _classPrivateFieldSet(_walletIframe, this, htmlToElement(`<iframe
1670
+ id="walletIframe-${_classPrivateFieldGet(_embedNonce, this)}"
1671
+ class="walletIframe-${_classPrivateFieldGet(_embedNonce, this)}"
1672
+ sandbox="allow-popups allow-scripts allow-same-origin allow-forms allow-modals allow-downloads"
1673
+ src="${walletIframeUrl.href}"
1674
+ style="display: none; position: fixed; top: 0; right: 0; width: 100%; color-scheme: none; border-width: 0px; height: 100%; border: none; border-radius: 0; z-index: ${_classPrivateFieldGet(_modalZIndex, this).toString()}"
1675
+ allow="clipboard-write"
1676
+ ></iframe>`));
1677
+ messageService.messages$.subscribe(msg => {
1678
+ switch (msg.type) {
1679
+ case AirMessageTypes.SERVICE_INITIALIZED:
1680
+ {
1681
+ _classPrivateFieldSet(_rehydrationState, this, msg.payload.rehydration);
1682
+ _assertClassBrand(_RealmEmbed_brand, this, _triggerInitializedEvent).call(this);
1683
+ break;
1684
+ }
1685
+ }
1686
+ });
1687
+ messageService.loginState$.subscribe(async msg => {
1688
+ switch (msg.payload.state) {
1689
+ case "connected":
1690
+ {
1691
+ await _assertClassBrand(_RealmEmbed_brand, this, _onInitialized).call(this);
1692
+ if (msg.payload.addresses && !this.isLoggedIn) {
1693
+ _classPrivateFieldSet(_walletAddresses, this, msg.payload.addresses);
1694
+ _classPrivateFieldSet(_loginToken, this, msg.payload.token);
1695
+ _classPrivateFieldSet(_sessionId, this, msg.payload.sessionId);
1696
+ _assertClassBrand(_RealmEmbed_brand, this, _triggerEvent).call(this, {
1697
+ event: "connected",
1698
+ result: {
1699
+ isLoggedIn: false,
1700
+ addresses: msg.payload.addresses,
1701
+ token: msg.payload.token,
1702
+ sessionId: msg.payload.sessionId
1703
+ }
1704
+ });
1705
+ }
1706
+ break;
1707
+ }
1708
+ case "logged_in":
1709
+ {
1710
+ await _assertClassBrand(_RealmEmbed_brand, this, _onInitialized).call(this);
1711
+ const isNotConnectedYet = !_classPrivateFieldGet(_walletAddresses, this);
1712
+ _classPrivateFieldSet(_realmId, this, msg.payload.airId);
1713
+ _classPrivateFieldSet(_walletAddresses, this, msg.payload.addresses);
1714
+ _classPrivateFieldSet(_loginToken, this, msg.payload.token);
1715
+ _classPrivateFieldSet(_sessionId, this, msg.payload.sessionId);
1716
+ if (isNotConnectedYet) {
1717
+ _assertClassBrand(_RealmEmbed_brand, this, _triggerEvent).call(this, {
1718
+ event: "connected",
1719
+ result: {
1720
+ isLoggedIn: false,
1721
+ addresses: msg.payload.addresses,
1722
+ token: msg.payload.token,
1723
+ sessionId: msg.payload.sessionId
1724
+ }
1725
+ });
1726
+ }
1727
+ _assertClassBrand(_RealmEmbed_brand, this, _triggerEvent).call(this, {
1728
+ event: "logged_in",
1729
+ result: {
1730
+ isLoggedIn: true,
1731
+ realmId: msg.payload.airId,
1732
+ addresses: msg.payload.addresses,
1733
+ token: msg.payload.token,
1734
+ sessionId: msg.payload.sessionId
1735
+ }
1736
+ });
1737
+ break;
1738
+ }
1739
+ case "minting_started":
1740
+ {
1741
+ _assertClassBrand(_RealmEmbed_brand, this, _triggerEvent).call(this, {
1742
+ event: "minting_started"
1743
+ });
1744
+ break;
1745
+ }
1746
+ case "minting_failed":
1747
+ {
1748
+ _assertClassBrand(_RealmEmbed_brand, this, _triggerEvent).call(this, {
1749
+ event: "minting_failed",
1750
+ errorMessage: msg.payload.errorMessage
1751
+ });
1752
+ break;
1753
+ }
1754
+ }
1755
+ });
1756
+ try {
1757
+ // Handle wallet iframe message
1758
+ window.document.body.appendChild(_classPrivateFieldGet(_walletIframe, this));
1759
+ const initializeWalletService = new Promise((resolve, reject) => {
1760
+ const handleMessage = async ev => {
1761
+ try {
1762
+ if (ev.origin !== walletIframeOrigin) return;
1763
+ if (ev.data === base_controllers_namespaceObject.SETUP_COMPLETE) {
1764
+ window.removeEventListener("message", handleMessage);
1765
+ // send init params here
1766
+ const dappMetadata = await siteMetadata();
1767
+ _classPrivateFieldGet(_walletIframe, this).contentWindow.postMessage({
1768
+ chainConfig: _classPrivateFieldGet(_buildEnv, this) === EMBED_BUILD_ENV.PRODUCTION ? embedChainConfig.polygon : embedChainConfig.polygonAmoy,
1769
+ dappMetadata,
1770
+ enableLogging,
1771
+ skipRehydration,
1772
+ realmPartnerId: _classPrivateFieldGet(_realmPartnerId, this),
1773
+ web3AuthClientId: _classPrivateFieldGet(_web3AuthClientId, this),
1774
+ web3AuthNetwork: _classPrivateFieldGet(_web3AuthNetwork, this),
1775
+ confirmationStrategy: _classPrivateFieldGet(_confirmationStrategy, this)
1776
+ }, walletIframeOrigin);
1777
+ await _assertClassBrand(_RealmEmbed_brand, this, _setupWeb).call(this, {
1778
+ torusUrl: walletUrl
1779
+ });
1780
+ _classPrivateFieldGet(_communicationProvider, this).onLoginStateHandle = async isLoggedIn => {
1781
+ if (!isLoggedIn) {
1782
+ await _assertClassBrand(_RealmEmbed_brand, this, _logout).call(this);
1783
+ }
1784
+ };
1785
+ resolve();
1786
+ }
1787
+ } catch (err) {
1788
+ reject(err);
1789
+ }
1790
+ };
1791
+ window.addEventListener("message", handleMessage);
1792
+ });
1793
+ const walletServiceInitialization = messageService.waitForWalletInitialization();
1794
+ await Promise.all([initializeWalletService, walletServiceInitialization]);
1795
+ messageService.setupIframeCommunication(_classPrivateFieldGet(_walletIframe, this));
1796
+ _classPrivateFieldSet(_isInitialized, this, true);
1797
+ _assertClassBrand(_RealmEmbed_brand, this, _triggerInitializedEvent).call(this);
1798
+ loglevel.debug("Wallet service initialization resolved");
1799
+ } catch (error) {
1800
+ loglevel.debug("Wallet service initialization error", error);
1801
+ _assertClassBrand(_RealmEmbed_brand, this, _clearInit).call(this, true);
1802
+ throw error;
1803
+ }
1804
+ }
1805
+ moveToBackground() {
1806
+ _classPrivateFieldGet(_communicationProvider, this).moveToBackground();
1807
+ }
1808
+ moveToForeground() {
1809
+ _classPrivateFieldGet(_communicationProvider, this).moveToForeground();
1810
+ }
1811
+ async getUserInfo() {
1812
+ if (!_classPrivateFieldGet(_realmId, this)) return null;
1813
+ const userInfoResponse = await _classPrivateFieldGet(_communicationProvider, this).request({
1814
+ method: base_controllers_namespaceObject.COMMUNICATION_JRPC_METHODS.USER_INFO,
1815
+ params: []
1816
+ });
1817
+ return objectSpread2_default()(objectSpread2_default()({}, userInfoResponse), {}, {
1818
+ realmId: _classPrivateFieldGet(_realmId, this)
1819
+ });
1820
+ }
1821
+ async login(options) {
1822
+ var _options$legacy;
1823
+ return _assertClassBrand(_RealmEmbed_brand, this, _login).call(this, options, (_options$legacy = options === null || options === void 0 ? void 0 : options.legacy) !== null && _options$legacy !== void 0 ? _options$legacy : true);
1824
+ }
1825
+ async _deploySmartAccount() {
1826
+ if (!this.isConnected) throw new RealmEmbedError("NOT_LOGGED_IN", "User needs to be connected first");
1827
+ try {
1828
+ await messageService.sendDeploySmartAccountRequest(_classPrivateFieldGet(_walletIframe, this));
1829
+ } catch (error) {
1830
+ throw RealmEmbedError.from(error);
1831
+ }
1832
+ }
1833
+ // async loginV2<T extends boolean>(options?: {
1834
+ // skipClaiming: T;
1835
+ // token?: string;
1836
+ // }): Promise<T extends true ? RealmLoginResult | RealmConnectResult : RealmLoginResult> {
1837
+ // if (!this.#isInitialized) throw new Error("Call init() first");
1838
+
1839
+ // const iframeController = this.#authIframeController;
1840
+ // iframeController.setIframeVisibility(true);
1841
+ // iframeController.updateIframeState();
1842
+
1843
+ // const { payload } = await RealmMessageService.sendAuthLoginRequest(iframeController.iframeElement);
1844
+
1845
+ // iframeController.setIframeVisibility(false);
1846
+ // iframeController.updateIframeState();
1847
+
1848
+ // if (payload.success === true) {
1849
+ // return this.#login({
1850
+ // skipClaiming: options?.skipClaiming,
1851
+ // token: options?.token,
1852
+ // });
1853
+ // }
1854
+ // throw new RealmEmbedError(payload.errorName, payload.errorMessage);
1855
+ // }
1856
+
1857
+ // This is for internal use only
1858
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
1859
+ // @ts-ignore
1860
+ async _loginWithSessionId(params) {
1861
+ if (!_classPrivateFieldGet(_isInitialized, this)) throw new Error("Call init() first");
1862
+ if (!params.sessionId) throw new Error("sessionId is required");
1863
+ try {
1864
+ const res = await _classPrivateFieldGet(_communicationProvider, this).request({
1865
+ method: base_controllers_namespaceObject.COMMUNICATION_JRPC_METHODS.LOGIN_WITH_SESSION_ID,
1866
+ params: [params.sessionId, ""]
1867
+ });
1868
+ loglevel.info("Login with session id", res);
1869
+ return res.success;
1870
+ } catch (error) {
1871
+ loglevel.error("login with session id failed", error);
1872
+ throw error;
1873
+ }
1874
+ }
1875
+
1876
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
1877
+ // @ts-ignore
1878
+ async _showWalletWidget() {
1879
+ _classPrivateFieldGet(_communicationProvider, this).showTorusButton();
1880
+ }
1881
+ async claimRealmId(options) {
1882
+ if (!this.isConnected) throw new RealmEmbedError("NOT_CONNECTED", "User needs to be connected first");
1883
+ try {
1884
+ if (options !== null && options !== void 0 && options.background) {
1885
+ _classPrivateFieldGet(_communicationProvider, this).setIframeVisibility({
1886
+ isVisible: false
1887
+ });
1888
+ }
1889
+ _classPrivateFieldGet(_communicationProvider, this).displayIframe({
1890
+ isFull: true
1891
+ });
1892
+ const claimPromise = messageService.sendClaimRequest(_classPrivateFieldGet(_walletIframe, this), options);
1893
+ loglevel.debug("before claimPromise");
1894
+ await claimPromise;
1895
+ loglevel.debug("after claimPromise");
1896
+ return {
1897
+ isLoggedIn: true,
1898
+ realmId: _classPrivateFieldGet(_realmId, this),
1899
+ addresses: _classPrivateFieldGet(_walletAddresses, this),
1900
+ token: _classPrivateFieldGet(_loginToken, this),
1901
+ sessionId: _classPrivateFieldGet(_sessionId, this)
1902
+ };
1903
+ } catch (e) {
1904
+ throw RealmEmbedError.from(e);
1905
+ } finally {
1906
+ if (options !== null && options !== void 0 && options.background) {
1907
+ _classPrivateFieldGet(_communicationProvider, this).setIframeVisibility({
1908
+ isVisible: true
1909
+ });
1910
+ }
1911
+ _classPrivateFieldGet(_communicationProvider, this).displayIframe({
1912
+ isFull: false
1913
+ });
1914
+ }
1915
+ }
1916
+ async logout() {
1917
+ if (!_classPrivateFieldGet(_communicationProvider, this).isLoggedIn) throw new RealmEmbedError("NOT_LOGGED_IN", "Not logged in");
1918
+ await _assertClassBrand(_RealmEmbed_brand, this, _logout).call(this);
1919
+ }
1920
+ async cleanUp() {
1921
+ var _classPrivateFieldGet5;
1922
+ if ((_classPrivateFieldGet5 = _classPrivateFieldGet(_communicationProvider, this)) !== null && _classPrivateFieldGet5 !== void 0 && _classPrivateFieldGet5.isLoggedIn) {
1923
+ await this.logout();
1924
+ }
1925
+ await this.clearInit();
1926
+ }
1927
+ async clearInit() {
1928
+ _assertClassBrand(_RealmEmbed_brand, this, _clearInit).call(this);
1929
+ }
1930
+ on(listener) {
1931
+ if (_classPrivateFieldGet(_embedListeners, this).indexOf(listener) < 0) _classPrivateFieldGet(_embedListeners, this).push(listener);
1932
+ }
1933
+ off(listener) {
1934
+ const index = _classPrivateFieldGet(_embedListeners, this).indexOf(listener);
1935
+ if (index >= 0) _classPrivateFieldGet(_embedListeners, this).splice(index, 1);
1936
+ }
1937
+ clearEventListeners() {
1938
+ _classPrivateFieldSet(_embedListeners, this, []);
1939
+ }
1940
+ }
1941
+ function _getWsIframeUrl() {
1942
+ const {
1943
+ walletUrl
1944
+ } = AIR_URLS[_classPrivateFieldGet(_buildEnv, this)];
1945
+ const torusIframeUrl = new URL(walletUrl);
1946
+ if (torusIframeUrl.pathname.endsWith("/")) torusIframeUrl.pathname += "frame";else torusIframeUrl.pathname += "/frame";
1947
+ const hashParams = new URLSearchParams();
1948
+ hashParams.append("origin", window.location.origin);
1949
+ torusIframeUrl.hash = hashParams.toString();
1950
+ return torusIframeUrl;
1951
+ }
1952
+ async function _login(options, isLegacyLogin) {
1953
+ let loginResult;
1954
+ if (this.isLoggedIn) {
1955
+ loginResult = _assertClassBrand(_RealmEmbed_brand, this, _createLoginResult).call(this);
1956
+ } else if (this.isConnected) {
1957
+ if ((options === null || options === void 0 ? void 0 : options.skipClaiming) === true) {
1958
+ loginResult = _assertClassBrand(_RealmEmbed_brand, this, _createLoginResult).call(this);
1959
+ } else {
1960
+ loginResult = await this.claimRealmId(options);
1961
+ }
1962
+ } else {
1963
+ loginResult = await _assertClassBrand(_RealmEmbed_brand, this, _realmLogin).call(this, options, isLegacyLogin);
1964
+ }
1965
+ return loginResult;
1966
+ }
1967
+ function _createLoginResult() {
1968
+ if (this.isLoggedIn) {
1969
+ return {
1970
+ isLoggedIn: true,
1971
+ realmId: _classPrivateFieldGet(_realmId, this),
1972
+ addresses: _classPrivateFieldGet(_walletAddresses, this),
1973
+ token: _classPrivateFieldGet(_loginToken, this),
1974
+ sessionId: _classPrivateFieldGet(_sessionId, this)
1975
+ };
1976
+ }
1977
+ return {
1978
+ isLoggedIn: false,
1979
+ addresses: _classPrivateFieldGet(_walletAddresses, this),
1980
+ token: _classPrivateFieldGet(_loginToken, this),
1981
+ sessionId: _classPrivateFieldGet(_sessionId, this)
1982
+ };
1983
+ }
1984
+ async function _authLogin(params = {}) {
1985
+ try {
1986
+ if (!params.loginProvider || params.loginProvider === EXTERNAL_LOGIN_PROVIDER.WALLET_CONNECT) {
1987
+ _classPrivateFieldGet(_communicationProvider, this).displayIframe({
1988
+ isFull: true
1989
+ });
1990
+ }
1991
+
1992
+ // If user is already logged in, we assume they have given access to the website
1993
+ const res = await new Promise((resolve, reject) => {
1994
+ // We use this method because we want to update inPage provider state with account info
1995
+ _classPrivateFieldGet(_provider, this).rpcRequest({
1996
+ method: "eth_requestAccounts",
1997
+ params: [params.loginProvider, params.login_hint]
1998
+ }, (0,external_web3auth_auth_namespaceObject.getRpcPromiseCallback)(resolve, reject));
1999
+ });
2000
+ loglevel.debug("check: res", res);
2001
+ if (Array.isArray(res) && res.length > 0) {
2002
+ if (_classPrivateFieldGet(_confirmationStrategy, this) === base_controllers_namespaceObject.CONFIRMATION_STRATEGY.AUTO_APPROVE) loglevel.warn("Confirmation strategy auto approve is not allowed on Embed Mode, using Default instead.");
2003
+ return res;
2004
+ }
2005
+ // This would never happen, but just in case
2006
+ throw new Error("Login failed");
2007
+ } catch (error) {
2008
+ loglevel.error("login failed", error);
2009
+ throw error;
2010
+ }
2011
+ }
2012
+ async function _realmLogin(options, isLegacyLogin) {
2013
+ const skipClaimFlow = (options === null || options === void 0 ? void 0 : options.skipClaiming) === true;
2014
+ try {
2015
+ if (options !== null && options !== void 0 && options.authToken) {
2016
+ _classPrivateFieldGet(_communicationProvider, this).setIframeVisibility({
2017
+ isVisible: false
2018
+ });
2019
+ }
2020
+ const loginPromise = Promise.all([_assertClassBrand(_RealmEmbed_brand, this, _authLogin).call(this), messageService.sendLoginRequest(_classPrivateFieldGet(_walletIframe, this), {
2021
+ skipClaimFlow,
2022
+ token: options === null || options === void 0 ? void 0 : options.token,
2023
+ customAuthToken: options === null || options === void 0 ? void 0 : options.authToken,
2024
+ isLegacyLogin: !!isLegacyLogin
2025
+ })]);
2026
+ loglevel.debug("start logging in...");
2027
+ await loginPromise;
2028
+ loglevel.debug("login ended");
2029
+ return _assertClassBrand(_RealmEmbed_brand, this, _createLoginResult).call(this);
2030
+ } catch (e) {
2031
+ await _assertClassBrand(_RealmEmbed_brand, this, _logout).call(this);
2032
+ throw RealmEmbedError.from(e);
2033
+ } finally {
2034
+ if (options !== null && options !== void 0 && options.authToken) {
2035
+ _classPrivateFieldGet(_communicationProvider, this).setIframeVisibility({
2036
+ isVisible: true
2037
+ });
2038
+ }
2039
+ _classPrivateFieldGet(_communicationProvider, this).displayIframe({
2040
+ isFull: false
2041
+ });
2042
+ }
2043
+ }
2044
+ async function _logout() {
2045
+ var _classPrivateFieldGet6;
2046
+ const silent = !_classPrivateFieldGet(_walletAddresses, this);
2047
+ if ((_classPrivateFieldGet6 = _classPrivateFieldGet(_communicationProvider, this)) !== null && _classPrivateFieldGet6 !== void 0 && _classPrivateFieldGet6.isLoggedIn) {
2048
+ await _classPrivateFieldGet(_communicationProvider, this).request({
2049
+ method: base_controllers_namespaceObject.COMMUNICATION_JRPC_METHODS.LOGOUT,
2050
+ params: []
2051
+ });
2052
+ }
2053
+ if (_classPrivateFieldGet(_communicationProvider, this)) _classPrivateFieldGet(_communicationProvider, this).onLoginStateHandle = undefined;
2054
+ _classPrivateFieldSet(_walletAddresses, this, undefined);
2055
+ _classPrivateFieldSet(_realmId, this, undefined);
2056
+ if (!silent) {
2057
+ _assertClassBrand(_RealmEmbed_brand, this, _triggerEvent).call(this, {
2058
+ event: "logged_out"
2059
+ });
2060
+ }
2061
+ }
2062
+ async function _clearInit(isSilent) {
2063
+ function isElement(element) {
2064
+ return element instanceof Element || element instanceof Document;
2065
+ }
2066
+ if (isElement(_classPrivateFieldGet(_walletIframe, this)) && window.document.body.contains(_classPrivateFieldGet(_walletIframe, this))) {
2067
+ _classPrivateFieldGet(_walletIframe, this).remove();
2068
+ _classPrivateFieldSet(_walletIframe, this, undefined);
2069
+ }
2070
+ messageService.closeRealmObservables();
2071
+ _classPrivateFieldSet(_isInitialized, this, false);
2072
+ _classPrivateFieldSet(_walletAddresses, this, undefined);
2073
+ _classPrivateFieldSet(_realmId, this, undefined);
2074
+ if (isSilent === true) _assertClassBrand(_RealmEmbed_brand, this, _triggerEvent).call(this, {
2075
+ event: "reset"
2076
+ });
2077
+ }
2078
+ function _getConfirmationStrategyFinal(payload, communicationProvider) {
2079
+ // for external wallets, we'll show the modal and don't need to open a new window
2080
+ let confirmationStrategyFinal = _classPrivateFieldGet(_confirmationStrategy, this);
2081
+ if (!Array.isArray(payload) && PROVIDER_UNSAFE_METHODS.has(payload.method) && _classPrivateFieldGet(_confirmationStrategy, this) !== base_controllers_namespaceObject.CONFIRMATION_STRATEGY.MODAL && !_classPrivateFieldGet(_isPluginMode, this) && !communicationProvider.isExternalWallet) {
2082
+ confirmationStrategyFinal = base_controllers_namespaceObject.CONFIRMATION_STRATEGY.POPUP;
2083
+ }
2084
+ return confirmationStrategyFinal;
2085
+ }
2086
+ async function _setupWeb(providerParams) {
2087
+ loglevel.debug("setup embed communication...");
2088
+ // setup background connection
2089
+ const providerStream = new external_web3auth_auth_namespaceObject.BasePostMessageStream({
2090
+ name: "embed_torus",
2091
+ target: "iframe_torus",
2092
+ targetWindow: _classPrivateFieldGet(_walletIframe, this).contentWindow,
2093
+ targetOrigin: new URL(providerParams.torusUrl).origin
2094
+ });
2095
+
2096
+ // We create another LocalMessageDuplexStream for communication between dapp <> iframe
2097
+ const communicationStream = new external_web3auth_auth_namespaceObject.BasePostMessageStream({
2098
+ name: "embed_communication",
2099
+ target: "iframe_communication",
2100
+ targetWindow: _classPrivateFieldGet(_walletIframe, this).contentWindow,
2101
+ targetOrigin: new URL(providerParams.torusUrl).origin
2102
+ });
2103
+
2104
+ // compose the inPage provider
2105
+ const inPageProvider = new TorusInPageProvider(providerStream, {});
2106
+ const communicationProvider = new src_communicationProvider(communicationStream, {}, {
2107
+ buttonPosition: _classPrivateFieldGet(_buttonPosition, this)
2108
+ });
2109
+ inPageProvider.tryWindowHandle = (payload, cb) => {
2110
+ const _payload = payload;
2111
+ const confirmationStrategyFinal = _assertClassBrand(_RealmEmbed_brand, this, _getConfirmationStrategyFinal).call(this, payload, communicationProvider);
2112
+ if (confirmationStrategyFinal === base_controllers_namespaceObject.CONFIRMATION_STRATEGY.POPUP) {
2113
+ const windowId = (0,base_controllers_namespaceObject.randomId)();
2114
+ communicationProvider.handleWindow(windowId, {
2115
+ target: "_blank",
2116
+ features: (0,base_controllers_namespaceObject.getPopupFeatures)(base_controllers_namespaceObject.FEATURES_CONFIRM_WINDOW),
2117
+ timeout: 500
2118
+ });
2119
+ // for inPageProvider methods sending windowId in request instead of params
2120
+ // as params might be positional.
2121
+ _payload.windowId = windowId;
2122
+ }
2123
+ inPageProvider.rpcEngine.handle(_payload, cb);
2124
+ };
2125
+ communicationProvider.tryWindowHandle = (payload, cb) => {
2126
+ const _payload = payload;
2127
+ const confirmationStrategyFinal = _assertClassBrand(_RealmEmbed_brand, this, _getConfirmationStrategyFinal).call(this, payload, communicationProvider);
2128
+ if (confirmationStrategyFinal === base_controllers_namespaceObject.CONFIRMATION_STRATEGY.POPUP) {
2129
+ const windowId = (0,base_controllers_namespaceObject.randomId)();
2130
+ communicationProvider.handleWindow(windowId, {
2131
+ target: "_blank",
2132
+ features: (0,base_controllers_namespaceObject.getPopupFeatures)(base_controllers_namespaceObject.FEATURES_PROVIDER_CHANGE_WINDOW),
2133
+ // todo: are these features generic for all
2134
+ timeout: 500
2135
+ });
2136
+ // for communication methods sending window id in jrpc req params
2137
+ _payload.params.windowId = windowId;
2138
+ }
2139
+ communicationProvider.rpcEngine.handle(_payload, cb);
2140
+ };
2141
+
2142
+ // detect eth_requestAccounts and pipe to enable for now
2143
+ const detectAccountRequestPrototypeModifier = m => {
2144
+ const originalMethod = inPageProvider[m];
2145
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
2146
+ const self = this;
2147
+
2148
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
2149
+ // @ts-ignore
2150
+ inPageProvider[m] = function providerFunc(request, cb) {
2151
+ const {
2152
+ method,
2153
+ params = []
2154
+ } = request;
2155
+ if (method === "eth_requestAccounts") {
2156
+ let login = _assertClassBrand(_RealmEmbed_brand, self, _authLogin).call(self, {
2157
+ loginProvider: params[0]
2158
+ });
2159
+ if (cb) {
2160
+ login = login.then(res => cb(null, res)).catch(err => cb(err));
2161
+ }
2162
+ return login.finally(() => {
2163
+ _classPrivateFieldGet(_communicationProvider, self).displayIframe({
2164
+ isFull: false
2165
+ });
2166
+ });
2167
+ }
2168
+ return originalMethod.apply(this, [request, cb]);
2169
+ };
2170
+ };
2171
+
2172
+ // Detects call to eth_requestAccounts in request & sendAsync and passes to login
2173
+ detectAccountRequestPrototypeModifier("request");
2174
+ detectAccountRequestPrototypeModifier("sendAsync");
2175
+ detectAccountRequestPrototypeModifier("send");
2176
+ const proxiedInPageProvider = new Proxy(inPageProvider, {
2177
+ // straight up lie that we deleted the property so that it doesn't
2178
+ // throw an error in strict mode
2179
+ deleteProperty: () => true
2180
+ });
2181
+ const proxiedCommunicationProvider = new Proxy(communicationProvider, {
2182
+ // straight up lie that we deleted the property so that it doesn't
2183
+ // throw an error in strict mode
2184
+ deleteProperty: () => true
2185
+ });
2186
+ _classPrivateFieldSet(_provider, this, proxiedInPageProvider);
2187
+ _classPrivateFieldSet(_communicationProvider, this, proxiedCommunicationProvider);
2188
+ await Promise.all([inPageProvider.initializeState(), communicationProvider.initializeState(objectSpread2_default()(objectSpread2_default()({}, providerParams), {}, {
2189
+ torusIframeId: _classPrivateFieldGet(_walletIframe, this).id
2190
+ }))]);
2191
+ loglevel.debug("embed communication setup ended");
2192
+ }
2193
+ function _triggerEvent(data) {
2194
+ const listenersCopy = [..._classPrivateFieldGet(_embedListeners, this)];
2195
+ listenersCopy.forEach(listener => {
2196
+ try {
2197
+ listener(data);
2198
+ } catch (error) {
2199
+ loglevel.error(error);
2200
+ }
2201
+ });
2202
+ }
2203
+ function _triggerInitializedEvent() {
2204
+ if (_classPrivateFieldGet(_isInitialized, this) && _classPrivateFieldGet(_rehydrationState, this)) {
2205
+ _assertClassBrand(_RealmEmbed_brand, this, _triggerEvent).call(this, {
2206
+ event: "initialized",
2207
+ result: {
2208
+ rehydration: _classPrivateFieldGet(_rehydrationState, this)
2209
+ }
2210
+ });
2211
+ }
2212
+ }
2213
+ function _onInitialized() {
2214
+ return new Promise(resolve => {
2215
+ if (!_classPrivateFieldGet(_isInitialized, this) || !_classPrivateFieldGet(_rehydrationState, this)) {
2216
+ const sub = event => {
2217
+ loglevel.debug("onInitialized:", event);
2218
+ if (event.event === "initialized") {
2219
+ this.off(sub);
2220
+ resolve();
2221
+ }
2222
+ };
2223
+ this.on(sub);
2224
+ } else {
2225
+ resolve();
2226
+ }
2227
+ });
2228
+ }
2229
+ /* harmony default export */ const src_embed = (RealmEmbed);
2230
+ ;// ./src/iframeController.ts
2231
+
2232
+
2233
+ class IframeController {
2234
+ constructor(iframeUrl, iframeId, state) {
2235
+ defineProperty_default()(this, "state", void 0);
2236
+ defineProperty_default()(this, "_iframeElement", null);
2237
+ defineProperty_default()(this, "iframeUrl", void 0);
2238
+ defineProperty_default()(this, "iframeId", void 0);
2239
+ this.state = objectSpread2_default()(objectSpread2_default()({}, IframeController.defaultState), state);
2240
+ this.iframeUrl = iframeUrl;
2241
+ this.iframeId = iframeId;
2242
+ }
2243
+ get iframeElement() {
2244
+ return this._iframeElement;
2245
+ }
2246
+ createIframe() {
2247
+ if (this._iframeElement) return this._iframeElement;
2248
+ const iframe = document.createElement("iframe");
2249
+ iframe.id = this.iframeId;
2250
+ iframe.allow = "publickey-credentials-get *; publickey-credentials-create *";
2251
+ iframe.src = this.iframeUrl;
2252
+ iframe.style.position = "fixed";
2253
+ iframe.style.zIndex = "999999";
2254
+ iframe.style.border = "none";
2255
+ iframe.style.margin = "0";
2256
+ iframe.style.padding = "0";
2257
+ iframe.style.display = "none";
2258
+ document.body.appendChild(iframe);
2259
+ this._iframeElement = iframe;
2260
+ return iframe;
2261
+ }
2262
+ setIframeVisibility(isVisible) {
2263
+ this.state.isVisible = isVisible;
2264
+ }
2265
+ updateIframeState() {
2266
+ if (!this.iframeElement) return;
2267
+ const style = {};
2268
+ style.display = this.state.isVisible ? "block" : "none";
2269
+ style.width = "100%";
2270
+ style.height = "100%";
2271
+ style.top = "0px";
2272
+ style.right = "0px";
2273
+ style.left = "0px";
2274
+ style.bottom = "0px";
2275
+ Object.assign(this.iframeElement.style, style);
2276
+ }
2277
+ destroy() {
2278
+ if (this.iframeElement) {
2279
+ this.iframeElement.remove();
2280
+ this._iframeElement = null;
2281
+ }
2282
+ }
2283
+ postMessage(message) {
2284
+ if (!this.iframeElement) return;
2285
+ const {
2286
+ origin
2287
+ } = new URL(this.iframeElement.src);
2288
+ this.iframeElement.contentWindow.postMessage(message, origin);
2289
+ }
2290
+ }
2291
+ defineProperty_default()(IframeController, "defaultState", {
2292
+ isVisible: false
2293
+ });
2294
+ ;// ./src/airService.ts
2295
+
2296
+
2297
+
2298
+ function airService_classPrivateFieldGet(s, a) { return s.get(airService_assertClassBrand(s, a)); }
2299
+ function airService_classPrivateFieldSet(s, a, r) { return s.set(airService_assertClassBrand(s, a), r), r; }
2300
+ function airService_assertClassBrand(e, t, n) { if ("function" == typeof e ? e === t : e.has(t)) return arguments.length < 3 ? t : n; throw new TypeError("Private element is not present on this object"); }
2301
+
2302
+
2303
+
2304
+
2305
+
2306
+
2307
+
2308
+
2309
+
2310
+ var _authIframeController = /*#__PURE__*/new WeakMap();
2311
+ var _loginResult = /*#__PURE__*/new WeakMap();
2312
+ var airService_buildEnv = /*#__PURE__*/new WeakMap();
2313
+ var airService_embedNonce = /*#__PURE__*/new WeakMap();
2314
+ var _enableLogging = /*#__PURE__*/new WeakMap();
2315
+ var airService_isInitialized = /*#__PURE__*/new WeakMap();
2316
+ var _partnerId = /*#__PURE__*/new WeakMap();
2317
+ var _realmEmbed = /*#__PURE__*/new WeakMap();
2318
+ var _walletInitialization = /*#__PURE__*/new WeakMap();
2319
+ var _airAuthListener = /*#__PURE__*/new WeakMap();
2320
+ var _AirService_brand = /*#__PURE__*/new WeakSet();
2321
+ class AirService {
2322
+ constructor({
2323
+ partnerId
2324
+ }) {
2325
+ classPrivateMethodInitSpec_default()(this, _AirService_brand);
2326
+ classPrivateFieldInitSpec_default()(this, _authIframeController, void 0);
2327
+ classPrivateFieldInitSpec_default()(this, _loginResult, void 0);
2328
+ classPrivateFieldInitSpec_default()(this, airService_buildEnv, void 0);
2329
+ classPrivateFieldInitSpec_default()(this, airService_embedNonce, (0,base_controllers_namespaceObject.randomId)());
2330
+ classPrivateFieldInitSpec_default()(this, _enableLogging, false);
2331
+ classPrivateFieldInitSpec_default()(this, airService_isInitialized, false);
2332
+ classPrivateFieldInitSpec_default()(this, _partnerId, void 0);
2333
+ // Realm Embed related
2334
+ classPrivateFieldInitSpec_default()(this, _realmEmbed, void 0);
2335
+ classPrivateFieldInitSpec_default()(this, _walletInitialization, void 0);
2336
+ classPrivateFieldInitSpec_default()(this, _airAuthListener, []);
2337
+ airService_classPrivateFieldSet(_partnerId, this, partnerId);
2338
+ airService_classPrivateFieldSet(_realmEmbed, this, new src_embed({
2339
+ partnerId: airService_classPrivateFieldGet(_partnerId, this)
2340
+ }));
2341
+ }
2342
+ get buildEnv() {
2343
+ return airService_classPrivateFieldGet(airService_buildEnv, this);
2344
+ }
2345
+ get isAirAuth() {
2346
+ return true;
2347
+ }
2348
+ get isInitialized() {
2349
+ return airService_classPrivateFieldGet(airService_isInitialized, this);
2350
+ }
2351
+ get isLoggedIn() {
2352
+ return !!airService_classPrivateFieldGet(_loginResult, this);
2353
+ }
2354
+ get isWalletLoaded() {
2355
+ var _classPrivateFieldGet2;
2356
+ return (_classPrivateFieldGet2 = airService_classPrivateFieldGet(_realmEmbed, this)) === null || _classPrivateFieldGet2 === void 0 ? void 0 : _classPrivateFieldGet2.isInitialized;
2357
+ }
2358
+ async init({
2359
+ buildEnv = EMBED_BUILD_ENV.PRODUCTION,
2360
+ enableLogging = false,
2361
+ skipRehydration = false
2362
+ }) {
2363
+ if (!airService_classPrivateFieldGet(_partnerId, this)) throw new Error("Partner ID is required to initialize auth service");
2364
+ if (airService_classPrivateFieldGet(airService_isInitialized, this)) return;
2365
+ airService_classPrivateFieldSet(airService_buildEnv, this, buildEnv);
2366
+ airService_classPrivateFieldSet(_enableLogging, this, enableLogging);
2367
+ const {
2368
+ authUrl,
2369
+ logLevel
2370
+ } = AIR_URLS[buildEnv];
2371
+ loglevel.setDefaultLevel(logLevel);
2372
+ if (airService_classPrivateFieldGet(_enableLogging, this)) loglevel.enableAll();else loglevel.disableAll();
2373
+ const authIframeOrigin = new URL(authUrl).origin;
2374
+ await messageService.openAuthObservables({
2375
+ authIframeOrigin
2376
+ });
2377
+ airService_classPrivateFieldSet(_authIframeController, this, new IframeController(authUrl, `air-login-${airService_classPrivateFieldGet(airService_embedNonce, this)}`));
2378
+ messageService.authMessage$.subscribe(async msg => {
2379
+ switch (msg.type) {
2380
+ case AirAuthMessageTypes.IFRAME_VISIBILITY_REQUEST:
2381
+ {
2382
+ const authIframeController = airService_classPrivateFieldGet(_authIframeController, this);
2383
+ authIframeController.setIframeVisibility(msg.payload.visible);
2384
+ authIframeController.updateIframeState();
2385
+ break;
2386
+ }
2387
+ case AirAuthMessageTypes.SETUP_WALLET_REQUEST:
2388
+ {
2389
+ await airService_assertClassBrand(_AirService_brand, this, _initializeWallet).call(this);
2390
+ break;
2391
+ }
2392
+ }
2393
+ });
2394
+ try {
2395
+ airService_classPrivateFieldGet(_authIframeController, this).createIframe();
2396
+ const initializationPromise = new Promise((resolve, reject) => {
2397
+ const handleAuthMessage = ev => {
2398
+ try {
2399
+ if (ev.origin !== authIframeOrigin) return;
2400
+ if (ev.data === AirAuthMessageTypes.SETUP_COMPLETED) {
2401
+ window.removeEventListener("message", handleAuthMessage);
2402
+ airService_classPrivateFieldGet(_authIframeController, this).postMessage({
2403
+ type: AirAuthMessageTypes.INITIALIZATION_REQUEST,
2404
+ payload: {
2405
+ partnerId: airService_classPrivateFieldGet(_partnerId, this),
2406
+ skipRehydration
2407
+ }
2408
+ });
2409
+ resolve();
2410
+ }
2411
+ } catch (err) {
2412
+ reject(err);
2413
+ }
2414
+ };
2415
+ window.addEventListener("message", handleAuthMessage);
2416
+ });
2417
+ const authServiceInitialization = messageService.waitForAuthInitialization();
2418
+ const result = await Promise.all([initializationPromise, authServiceInitialization]);
2419
+ airService_classPrivateFieldSet(airService_isInitialized, this, true);
2420
+ airService_assertClassBrand(_AirService_brand, this, _triggerAirAuthInitialized).call(this);
2421
+ airService_assertClassBrand(_AirService_brand, this, _prepareRealmEmbedListeners).call(this);
2422
+
2423
+ // rehydrated auth session
2424
+ if (result[1].rehydrated) {
2425
+ airService_classPrivateFieldSet(_loginResult, this, airService_assertClassBrand(_AirService_brand, this, airService_createLoginResult).call(this, result[1]));
2426
+ airService_assertClassBrand(_AirService_brand, this, _triggerAirAuthLoggedIn).call(this);
2427
+ return airService_classPrivateFieldGet(_loginResult, this);
2428
+ }
2429
+ } catch (error) {
2430
+ loglevel.debug("Error initializing auth service", error);
2431
+ await this.cleanUp();
2432
+ throw error;
2433
+ }
2434
+ return null;
2435
+ }
2436
+ async cleanUp() {
2437
+ var _classPrivateFieldGet3;
2438
+ // Clear up wallet service iframe if exists
2439
+ await airService_assertClassBrand(_AirService_brand, this, _cleanUpWallet).call(this);
2440
+
2441
+ // Logout auth session
2442
+ await messageService.logoutAuth(airService_classPrivateFieldGet(_authIframeController, this).iframeElement);
2443
+
2444
+ // Destroy the auth iframe
2445
+ const authIframeElement = (_classPrivateFieldGet3 = airService_classPrivateFieldGet(_authIframeController, this)) === null || _classPrivateFieldGet3 === void 0 ? void 0 : _classPrivateFieldGet3.iframeElement;
2446
+ if (isElement(authIframeElement) && window.document.body.contains(authIframeElement)) {
2447
+ airService_classPrivateFieldGet(_authIframeController, this).destroy();
2448
+ airService_classPrivateFieldSet(_authIframeController, this, undefined);
2449
+ }
2450
+
2451
+ // Close the message service
2452
+ messageService.closeAuthObservables();
2453
+ this.clearEventListeners();
2454
+ airService_classPrivateFieldSet(airService_isInitialized, this, false);
2455
+ }
2456
+ async login(options) {
2457
+ if (!airService_classPrivateFieldGet(airService_isInitialized, this)) throw new Error("Service is not initialized");
2458
+ if (airService_classPrivateFieldGet(_loginResult, this)) return airService_classPrivateFieldGet(_loginResult, this);
2459
+ const iframeController = airService_classPrivateFieldGet(_authIframeController, this);
2460
+ const {
2461
+ payload
2462
+ } = await messageService.sendAuthLoginRequest(iframeController.iframeElement, {
2463
+ partnerLoginToken: options === null || options === void 0 ? void 0 : options.authToken
2464
+ });
2465
+ if (payload.success === true) {
2466
+ airService_classPrivateFieldSet(_loginResult, this, airService_assertClassBrand(_AirService_brand, this, airService_createLoginResult).call(this, payload));
2467
+ airService_assertClassBrand(_AirService_brand, this, _triggerAirAuthLoggedIn).call(this);
2468
+ return airService_classPrivateFieldGet(_loginResult, this);
2469
+ }
2470
+ throw new AirServiceError("UNKNOWN_ERROR", "Unknown error occurred");
2471
+ }
2472
+ async deploySmartAccount() {
2473
+ if (!airService_classPrivateFieldGet(airService_isInitialized, this)) throw new Error("Service is not initialized");
2474
+ await airService_assertClassBrand(_AirService_brand, this, _ensureWallet).call(this);
2475
+ return airService_classPrivateFieldGet(_realmEmbed, this)._deploySmartAccount();
2476
+ }
2477
+ async logout() {
2478
+ if (!airService_classPrivateFieldGet(airService_isInitialized, this)) throw new Error("Service is not initialized");
2479
+ if (!this.isLoggedIn) throw new Error("No active session to logout");
2480
+
2481
+ // Clear up wallet
2482
+ await airService_assertClassBrand(_AirService_brand, this, _cleanUpWallet).call(this);
2483
+ await messageService.logoutAuth(airService_classPrivateFieldGet(_authIframeController, this).iframeElement);
2484
+ airService_classPrivateFieldSet(_loginResult, this, undefined);
2485
+ airService_assertClassBrand(_AirService_brand, this, _triggerAirAuthLoggedOut).call(this);
2486
+ }
2487
+ async getProvider() {
2488
+ if (!this.isLoggedIn) return null;
2489
+ await airService_assertClassBrand(_AirService_brand, this, _ensureWallet).call(this);
2490
+ return airService_classPrivateFieldGet(_realmEmbed, this).provider;
2491
+ }
2492
+ async preloadWallet() {
2493
+ return airService_assertClassBrand(_AirService_brand, this, _ensureWallet).call(this);
2494
+ }
2495
+ async claimAirId(options) {
2496
+ await airService_assertClassBrand(_AirService_brand, this, _ensureWallet).call(this);
2497
+ return airService_classPrivateFieldGet(_realmEmbed, this).claimRealmId(options);
2498
+ }
2499
+ async getUserInfo() {
2500
+ if (!this.isLoggedIn) throw new Error("User not logged in");
2501
+ const info = await messageService.sendUserInfoRequest(airService_classPrivateFieldGet(_authIframeController, this).iframeElement);
2502
+ if (info.payload.success === false) {
2503
+ throw new AirServiceError(info.payload.errorName, info.payload.errorMessage);
2504
+ }
2505
+ return {
2506
+ id: info.payload.id,
2507
+ abstractAccountAddress: info.payload.abstractAccountAddress,
2508
+ email: info.payload.email,
2509
+ airIds: info.payload.airIds
2510
+ };
2511
+ }
2512
+ async getPartnerUserInfo() {
2513
+ if (!this.isLoggedIn) throw new Error("User not logged in");
2514
+ const info = await messageService.sendPartnerUserInfoRequest(airService_classPrivateFieldGet(_authIframeController, this).iframeElement);
2515
+ if (info.payload.success === false) {
2516
+ throw new AirServiceError(info.payload.errorName, info.payload.errorMessage);
2517
+ }
2518
+ return {
2519
+ partnerId: info.payload.partnerId,
2520
+ partnerUserId: info.payload.partnerUserId,
2521
+ airId: info.payload.airId
2522
+ };
2523
+ }
2524
+ on(listener) {
2525
+ if (airService_classPrivateFieldGet(_airAuthListener, this).indexOf(listener) < 0) airService_classPrivateFieldGet(_airAuthListener, this).push(listener);
2526
+ }
2527
+ off(listener) {
2528
+ if (airService_classPrivateFieldGet(_airAuthListener, this).indexOf(listener) >= 0) airService_classPrivateFieldGet(_airAuthListener, this).splice(airService_classPrivateFieldGet(_airAuthListener, this).indexOf(listener), 1);
2529
+ }
2530
+ clearEventListeners() {
2531
+ airService_classPrivateFieldSet(_airAuthListener, this, []);
2532
+ }
2533
+
2534
+ // This is for internal use only
2535
+ // @ts-expect-error for unused function
2536
+ async _showWalletWidget() {
2537
+ await airService_assertClassBrand(_AirService_brand, this, _ensureWallet).call(this);
2538
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
2539
+ return airService_classPrivateFieldGet(_realmEmbed, this)._showWalletWidget();
2540
+ }
2541
+ }
2542
+ async function _createWallet() {
2543
+ return airService_classPrivateFieldGet(_realmEmbed, this).login({
2544
+ skipClaiming: true,
2545
+ legacy: false
2546
+ });
2547
+ }
2548
+ async function _ensureWallet() {
2549
+ if (!this.isLoggedIn) throw new Error("No active session to create wallet");
2550
+ if (!airService_classPrivateFieldGet(_walletInitialization, this)) {
2551
+ messageService.setupAuthIframe(airService_classPrivateFieldGet(_authIframeController, this).iframeElement);
2552
+ airService_classPrivateFieldSet(_walletInitialization, this, (async () => {
2553
+ try {
2554
+ await airService_assertClassBrand(_AirService_brand, this, _initializeWallet).call(this);
2555
+ return await airService_assertClassBrand(_AirService_brand, this, _createWallet).call(this);
2556
+ } catch (error) {
2557
+ loglevel.error("Error initializing wallet", error);
2558
+ throw error;
2559
+ }
2560
+ })());
2561
+ }
2562
+ return airService_classPrivateFieldGet(_walletInitialization, this);
2563
+ }
2564
+ async function _cleanUpWallet() {
2565
+ if (airService_classPrivateFieldGet(_walletInitialization, this) || airService_classPrivateFieldGet(_realmEmbed, this)) {
2566
+ await airService_classPrivateFieldGet(_walletInitialization, this);
2567
+ await airService_classPrivateFieldGet(_realmEmbed, this).cleanUp();
2568
+ airService_classPrivateFieldSet(_walletInitialization, this, undefined);
2569
+ }
2570
+ }
2571
+ async function _initializeWallet() {
2572
+ if (!airService_classPrivateFieldGet(_realmEmbed, this).isInitialized) {
2573
+ try {
2574
+ await airService_classPrivateFieldGet(_realmEmbed, this).init({
2575
+ buildEnv: airService_classPrivateFieldGet(airService_buildEnv, this),
2576
+ skipRehydration: true,
2577
+ enableLogging: airService_classPrivateFieldGet(_enableLogging, this) || false
2578
+ });
2579
+ airService_classPrivateFieldGet(_authIframeController, this).postMessage({
2580
+ type: AirAuthMessageTypes.SETUP_WALLET_RESPONSE,
2581
+ payload: {
2582
+ success: true
2583
+ }
2584
+ });
2585
+ } catch (error) {
2586
+ loglevel.error("Error initializing wallet", error);
2587
+ airService_classPrivateFieldGet(_authIframeController, this).postMessage({
2588
+ type: AirAuthMessageTypes.SETUP_WALLET_RESPONSE,
2589
+ payload: {
2590
+ success: false,
2591
+ errorName: "UNKNOWN_ERROR",
2592
+ errorMessage: "Unknown error occurred"
2593
+ }
2594
+ });
2595
+ throw error;
2596
+ }
2597
+ }
2598
+ }
2599
+ async function _triggerEventListeners(data) {
2600
+ airService_classPrivateFieldGet(_airAuthListener, this).forEach(listener => {
2601
+ listener(data);
2602
+ });
2603
+ }
2604
+ async function _triggerAirAuthInitialized() {
2605
+ await airService_assertClassBrand(_AirService_brand, this, _triggerEventListeners).call(this, {
2606
+ event: "initialized"
2607
+ });
2608
+ }
2609
+ async function _triggerAirAuthLoggedIn() {
2610
+ await airService_assertClassBrand(_AirService_brand, this, _triggerEventListeners).call(this, {
2611
+ event: "logged_in",
2612
+ result: airService_classPrivateFieldGet(_loginResult, this)
2613
+ });
2614
+ }
2615
+ async function _triggerAirAuthLoggedOut() {
2616
+ await airService_assertClassBrand(_AirService_brand, this, _triggerEventListeners).call(this, {
2617
+ event: "logged_out"
2618
+ });
2619
+ }
2620
+ function airService_createLoginResult(payload) {
2621
+ return {
2622
+ isLoggedIn: true,
2623
+ id: payload.id,
2624
+ abstractAccountAddress: payload.abstractAccountAddress,
2625
+ token: payload.partnerAccessToken
2626
+ };
2627
+ }
2628
+ async function _prepareRealmEmbedListeners() {
2629
+ airService_classPrivateFieldGet(_realmEmbed, this).on(data => {
2630
+ if (data.event === "connected" || data.event === "logged_in") {
2631
+ var _data$result$addresse;
2632
+ const result = objectSpread2_default()(objectSpread2_default()({}, data.result), {}, {
2633
+ addresses: {
2634
+ eoa: data.result.addresses.eoa,
2635
+ aa: (_data$result$addresse = data.result.addresses.aa) !== null && _data$result$addresse !== void 0 ? _data$result$addresse : ""
2636
+ }
2637
+ });
2638
+ airService_assertClassBrand(_AirService_brand, this, _triggerEventListeners).call(this, {
2639
+ event: "wallet_loaded",
2640
+ result
2641
+ });
2642
+ } else if (data.event === "minting_started") {
2643
+ airService_assertClassBrand(_AirService_brand, this, _triggerEventListeners).call(this, {
2644
+ event: "minting_started"
2645
+ });
2646
+ } else if (data.event === "minting_failed") {
2647
+ airService_assertClassBrand(_AirService_brand, this, _triggerEventListeners).call(this, {
2648
+ event: "minting_failed",
2649
+ errorMessage: data.errorMessage
2650
+ });
2651
+ }
2652
+ });
2653
+ }
2654
+ /* harmony default export */ const airService = (AirService);
2655
+ ;// ./src/index.ts
2656
+
2657
+
2658
+
2659
+
2660
+ module.exports = __webpack_exports__;
2661
+ /******/ })()
2662
+ ;