@ic-reactor/core 2.0.0-alpha.0 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,21 +1,15 @@
1
1
  "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
2
  Object.defineProperty(exports, "__esModule", { value: true });
12
3
  exports.CandidAdapter = void 0;
13
4
  const agent_1 = require("@dfinity/agent");
14
5
  const constants_1 = require("../../utils/constants");
15
6
  const utils_1 = require("../../utils");
16
7
  class CandidAdapter {
8
+ agent;
9
+ didjsCanisterId;
10
+ parserModule;
11
+ unsubscribeAgent = utils_1.noop;
17
12
  constructor({ agentManager, agent, didjsCanisterId, }) {
18
- this.unsubscribeAgent = () => { };
19
13
  if (agent) {
20
14
  this.agent = agent;
21
15
  }
@@ -31,119 +25,104 @@ class CandidAdapter {
31
25
  }
32
26
  this.didjsCanisterId = didjsCanisterId || this.getDefaultDidJsId();
33
27
  }
34
- initializeParser(module) {
35
- return __awaiter(this, void 0, void 0, function* () {
36
- if (module !== undefined) {
37
- this.parserModule = module;
38
- return;
39
- }
40
- try {
41
- this.parserModule = require("@ic-reactor/parser");
42
- if (typeof this.parserModule !== "undefined" &&
43
- "default" in this.parserModule) {
44
- yield this.parserModule.default();
45
- }
46
- }
47
- catch (error) {
48
- throw new Error(`Error initializing parser: ${error}`);
28
+ async initializeParser(module) {
29
+ if (module !== undefined) {
30
+ this.parserModule = module;
31
+ return;
32
+ }
33
+ try {
34
+ this.parserModule = require("@ic-reactor/parser");
35
+ if (typeof this.parserModule !== "undefined" &&
36
+ "default" in this.parserModule) {
37
+ await this.parserModule.default();
49
38
  }
50
- });
39
+ }
40
+ catch (error) {
41
+ throw new Error(`Error initializing parser: ${error}`);
42
+ }
51
43
  }
52
44
  getDefaultDidJsId() {
53
- var _a, _b;
54
- return ((_b = (_a = this.agent).isLocal) === null || _b === void 0 ? void 0 : _b.call(_a)) === true
45
+ return this.agent.isLocal?.() === true
55
46
  ? constants_1.DEFAULT_LOCAL_DIDJS_ID
56
47
  : constants_1.DEFAULT_IC_DIDJS_ID;
57
48
  }
58
- fetchCandidDefinition(canisterId) {
59
- return __awaiter(this, void 0, void 0, function* () {
60
- let candidDef = "";
61
- // First attempt: Try getting Candid definition from metadata
62
- try {
63
- candidDef = yield this.getFromMetadata(canisterId);
64
- if (!candidDef) {
65
- throw new Error("Cannot retrieve Candid definition from metadata");
66
- }
67
- }
68
- catch (error) {
69
- // Second attempt: Try the temporary hack method
70
- candidDef = yield this.getFromTmpHack(canisterId).catch(() => {
71
- return undefined;
72
- });
73
- }
49
+ async fetchCandidDefinition(canisterId) {
50
+ let candidDef = "";
51
+ // First attempt: Try getting Candid definition from metadata
52
+ try {
53
+ candidDef = await this.getFromMetadata(canisterId);
74
54
  if (!candidDef) {
75
- throw new Error("Failed to retrieve Candid definition by any method.");
55
+ throw new Error("Cannot retrieve Candid definition from metadata");
76
56
  }
77
- return candidDef;
78
- });
57
+ }
58
+ catch (error) {
59
+ // Second attempt: Try the temporary hack method
60
+ candidDef = await this.getFromTmpHack(canisterId).catch(() => {
61
+ return undefined;
62
+ });
63
+ }
64
+ if (!candidDef) {
65
+ throw new Error("Failed to retrieve Candid definition by any method.");
66
+ }
67
+ return candidDef;
79
68
  }
80
- getCandidDefinition(canisterId) {
81
- return __awaiter(this, void 0, void 0, function* () {
82
- try {
83
- const candidDef = yield this.fetchCandidDefinition(canisterId);
84
- return this.dynamicEvalJs(candidDef);
85
- }
86
- catch (error) {
87
- throw new Error(`Error fetching canister ${canisterId}: ${error}`);
88
- }
89
- });
69
+ async getCandidDefinition(canisterId) {
70
+ try {
71
+ const candidDef = await this.fetchCandidDefinition(canisterId);
72
+ return this.evaluateCandidDefinition(candidDef);
73
+ }
74
+ catch (error) {
75
+ throw new Error(`Error fetching canister ${canisterId}: ${error}`);
76
+ }
90
77
  }
91
- getFromMetadata(canisterId) {
92
- return __awaiter(this, void 0, void 0, function* () {
93
- const status = yield agent_1.CanisterStatus.request({
94
- agent: this.agent,
95
- canisterId: canisterId,
96
- paths: ["candid"],
97
- });
98
- return status.get("candid");
78
+ async getFromMetadata(canisterId) {
79
+ const status = await agent_1.CanisterStatus.request({
80
+ agent: this.agent,
81
+ canisterId: canisterId,
82
+ paths: ["candid"],
99
83
  });
84
+ return status.get("candid");
100
85
  }
101
- getFromTmpHack(canisterId) {
102
- return __awaiter(this, void 0, void 0, function* () {
103
- const commonInterface = ({ IDL }) => IDL.Service({
104
- __get_candid_interface_tmp_hack: IDL.Func([], [IDL.Text], ["query"]),
105
- });
106
- const actor = agent_1.Actor.createActor(commonInterface, {
107
- agent: this.agent,
108
- canisterId,
109
- });
110
- return (yield actor.__get_candid_interface_tmp_hack());
86
+ async getFromTmpHack(canisterId) {
87
+ const commonInterface = ({ IDL }) => IDL.Service({
88
+ __get_candid_interface_tmp_hack: IDL.Func([], [IDL.Text], ["query"]),
89
+ });
90
+ const actor = agent_1.Actor.createActor(commonInterface, {
91
+ agent: this.agent,
92
+ canisterId,
111
93
  });
94
+ return (await actor.__get_candid_interface_tmp_hack());
112
95
  }
113
- dynamicEvalJs(data) {
114
- return __awaiter(this, void 0, void 0, function* () {
96
+ async evaluateCandidDefinition(data) {
97
+ try {
98
+ let candidDef = "";
115
99
  try {
116
- let candidDef = "";
117
- try {
118
- candidDef = this.parseDidToJs(data);
119
- if (candidDef === "") {
120
- throw new Error("Cannot compile Candid to JavaScript");
121
- }
122
- }
123
- catch (error) {
124
- candidDef = (yield this.fetchDidTojs(data))[0];
125
- }
126
- if (JSON.stringify(candidDef) === JSON.stringify([])) {
100
+ candidDef = this.parseDidToJs(data);
101
+ if (candidDef === "") {
127
102
  throw new Error("Cannot compile Candid to JavaScript");
128
103
  }
129
- return yield (0, utils_1.importCandidDefinition)(candidDef);
130
104
  }
131
105
  catch (error) {
132
- throw new Error(`Error evaluating Candid definition: ${error}`);
106
+ candidDef = (await this.fetchDidTojs(data))[0];
133
107
  }
134
- });
108
+ if (JSON.stringify(candidDef) === JSON.stringify([])) {
109
+ throw new Error("Cannot compile Candid to JavaScript");
110
+ }
111
+ return await (0, utils_1.importCandidDefinition)(candidDef);
112
+ }
113
+ catch (error) {
114
+ throw new Error(`Error evaluating Candid definition: ${error}`);
115
+ }
135
116
  }
136
- fetchDidTojs(candidSource, didjsCanisterId) {
137
- return __awaiter(this, void 0, void 0, function* () {
138
- const didjsInterface = ({ IDL }) => IDL.Service({
139
- did_to_js: IDL.Func([IDL.Text], [IDL.Opt(IDL.Text)], ["query"]),
140
- });
141
- const didjs = agent_1.Actor.createActor(didjsInterface, {
142
- agent: this.agent,
143
- canisterId: didjsCanisterId || this.didjsCanisterId,
144
- });
145
- return didjs.did_to_js(candidSource);
117
+ async fetchDidTojs(candidSource, didjsCanisterId) {
118
+ const didjsInterface = ({ IDL }) => IDL.Service({
119
+ did_to_js: IDL.Func([IDL.Text], [IDL.Opt(IDL.Text)], ["query"]),
120
+ });
121
+ const didjs = agent_1.Actor.createActor(didjsInterface, {
122
+ agent: this.agent,
123
+ canisterId: didjsCanisterId || this.didjsCanisterId,
146
124
  });
125
+ return didjs.did_to_js(candidSource);
147
126
  }
148
127
  parseDidToJs(candidSource) {
149
128
  if (!this.parserModule) {
@@ -1,20 +1,17 @@
1
1
  import { HttpAgent } from "@dfinity/agent";
2
2
  import { AuthClient } from "@dfinity/auth-client";
3
3
  import type { AuthClientLoginOptions } from "../../types";
4
- import type { AgentStore, AgentManagerParameters, UpdateAgentParameters, AuthState, AuthStore } from "./types";
4
+ import type { AgentStore, AgentManagerParameters, UpdateAgentParameters, AuthStore } from "./types";
5
5
  export declare class AgentManager {
6
- private _anonymousAgent;
7
6
  private _agent;
8
7
  private _auth;
9
8
  private _subscribers;
10
9
  agentStore: AgentStore;
11
10
  authStore: AuthStore;
12
- private initialAgentState;
13
- private initialAuthState;
14
11
  private updateAgentState;
15
- updateAuthState: (newState: Partial<AuthState>, action?: string) => void;
12
+ private updateAuthState;
16
13
  constructor(options?: AgentManagerParameters);
17
- private initializeAgent;
14
+ initializeAgent: () => Promise<void>;
18
15
  subscribeAgent: (callback: (agent: HttpAgent) => void, initialize?: boolean) => () => void;
19
16
  unsubscribeAgent: (callback: (agent: HttpAgent) => void) => void;
20
17
  private notifySubscribers;
@@ -28,6 +25,7 @@ export declare class AgentManager {
28
25
  getAgentHost: () => URL | undefined;
29
26
  getAgentHostName: () => string;
30
27
  getIsLocal: () => boolean;
28
+ isAuthClientInitialized: () => boolean;
31
29
  getNetwork: () => "local" | "remote" | "ic";
32
30
  getAgentState: AgentStore["getState"];
33
31
  subscribeAgentState: AgentStore["subscribe"];
@@ -35,5 +33,5 @@ export declare class AgentManager {
35
33
  subscribeAuthState: AuthStore["subscribe"];
36
34
  getAuth: () => AuthClient | null;
37
35
  getIdentity: () => import("@dfinity/agent").Identity | null;
38
- getPrincipal: () => import("@dfinity/principal").Principal | null;
36
+ getPrincipal: () => import("@dfinity/principal/lib/esm/principal").Principal | null;
39
37
  }
@@ -1,24 +1,4 @@
1
1
  "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- var __rest = (this && this.__rest) || function (s, e) {
12
- var t = {};
13
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
14
- t[p] = s[p];
15
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
16
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
17
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
18
- t[p[i]] = s[p[i]];
19
- }
20
- return t;
21
- };
22
2
  Object.defineProperty(exports, "__esModule", { value: true });
23
3
  exports.AgentManager = void 0;
24
4
  /* eslint-disable no-console */
@@ -26,166 +6,36 @@ const agent_1 = require("@dfinity/agent");
26
6
  const helper_1 = require("../../utils/helper");
27
7
  const auth_client_1 = require("@dfinity/auth-client");
28
8
  const constants_1 = require("../../utils/constants");
9
+ const AGENT_INITIAL_STATE = {
10
+ initialized: false,
11
+ isInitialized: false,
12
+ initializing: false,
13
+ isInitializing: false,
14
+ error: undefined,
15
+ network: undefined,
16
+ };
17
+ const AUTH_INITIAL_STATE = {
18
+ identity: null,
19
+ authenticating: false,
20
+ isAuthenticating: false,
21
+ authenticated: false,
22
+ isAuthenticated: false,
23
+ error: undefined,
24
+ };
29
25
  class AgentManager {
26
+ _agent;
27
+ _auth = null;
28
+ _subscribers = [];
29
+ agentStore;
30
+ authStore;
31
+ updateAgentState = (newState, action) => {
32
+ this.agentStore.setState((state) => ({ ...state, ...newState }), false, action);
33
+ };
34
+ updateAuthState = (newState, action) => {
35
+ this.authStore.setState((state) => ({ ...state, ...newState }), false, action);
36
+ };
30
37
  constructor(options) {
31
- var _a;
32
- this._auth = null;
33
- this._subscribers = [];
34
- this.initialAgentState = {
35
- initialized: false,
36
- initializing: false,
37
- error: undefined,
38
- network: "ic",
39
- };
40
- this.initialAuthState = {
41
- identity: null,
42
- authenticating: false,
43
- authenticated: false,
44
- error: undefined,
45
- };
46
- this.updateAgentState = (newState, action) => {
47
- this.agentStore.setState((state) => (Object.assign(Object.assign({}, state), newState)), false, action);
48
- };
49
- //TODO: make it private
50
- this.updateAuthState = (newState, action) => {
51
- this.authStore.setState((state) => (Object.assign(Object.assign({}, state), newState)), false, action);
52
- };
53
- this.initializeAgent = () => __awaiter(this, void 0, void 0, function* () {
54
- const network = this.getNetwork();
55
- this.updateAgentState({
56
- initializing: true,
57
- error: undefined,
58
- network,
59
- }, "initializing");
60
- if (network !== "ic") {
61
- try {
62
- yield this._agent.fetchRootKey();
63
- yield this._anonymousAgent.fetchRootKey();
64
- }
65
- catch (error) {
66
- this.updateAgentState({ error: error, initializing: false }, "error");
67
- }
68
- }
69
- this.updateAgentState({ initialized: true, initializing: false }, "initialized");
70
- });
71
- this.subscribeAgent = (callback, initialize = true) => {
72
- if (initialize) {
73
- callback(this._agent);
74
- }
75
- this._subscribers.push(callback);
76
- return () => this.unsubscribeAgent(callback);
77
- };
78
- this.unsubscribeAgent = (callback) => {
79
- this._subscribers = this._subscribers.filter((sub) => sub !== callback);
80
- };
81
- this.notifySubscribers = () => __awaiter(this, void 0, void 0, function* () {
82
- yield Promise.all(this._subscribers.map((callback) => __awaiter(this, void 0, void 0, function* () { return callback(this._agent); })));
83
- });
84
- this.updateAgent = (options) => __awaiter(this, void 0, void 0, function* () {
85
- const { agent } = options || {};
86
- if (agent) {
87
- this._agent = agent;
88
- }
89
- else if (options) {
90
- this._agent = agent_1.HttpAgent.createSync(options);
91
- yield this.initializeAgent();
92
- }
93
- yield this.notifySubscribers();
94
- });
95
- this.authenticate = () => __awaiter(this, void 0, void 0, function* () {
96
- console.log(`Authenticating on ${this.getNetwork()} network`);
97
- this.updateAuthState({ authenticating: true }, "authenticating");
98
- try {
99
- this._auth = yield auth_client_1.AuthClient.create();
100
- const authenticated = yield this._auth.isAuthenticated();
101
- const identity = this._auth.getIdentity();
102
- this._agent.replaceIdentity(identity);
103
- this.notifySubscribers();
104
- this.updateAuthState({
105
- authenticated,
106
- identity,
107
- authenticating: false,
108
- }, "authenticated");
109
- return identity;
110
- }
111
- catch (error) {
112
- this.updateAuthState({ error: error, authenticating: false }, "error");
113
- throw error;
114
- }
115
- });
116
- this.login = (options) => __awaiter(this, void 0, void 0, function* () {
117
- this.updateAuthState({ authenticating: true }, "login");
118
- if (!this._auth) {
119
- yield this.authenticate();
120
- }
121
- if (!this._auth) {
122
- throw new Error("Auth client not initialized");
123
- }
124
- yield this._auth.login(Object.assign(Object.assign({ identityProvider: this.getIsLocal()
125
- ? constants_1.LOCAL_INTERNET_IDENTITY_PROVIDER
126
- : constants_1.IC_INTERNET_IDENTITY_PROVIDER }, options), { onSuccess: (msg) => __awaiter(this, void 0, void 0, function* () {
127
- var _c;
128
- yield this.authenticate();
129
- (_c = options === null || options === void 0 ? void 0 : options.onSuccess) === null || _c === void 0 ? void 0 : _c.call(options, msg);
130
- }) }));
131
- });
132
- this.logout = (options) => __awaiter(this, void 0, void 0, function* () {
133
- if (!this._auth) {
134
- throw new Error("Auth client not initialized");
135
- }
136
- yield this._auth.logout(options);
137
- yield this.authenticate();
138
- });
139
- // agent store
140
- this.getAgent = () => {
141
- return this._agent;
142
- };
143
- this.getAgentHost = () => {
144
- return this._agent.host;
145
- };
146
- this.getAgentHostName = () => {
147
- var _a;
148
- return ((_a = this.getAgentHost()) === null || _a === void 0 ? void 0 : _a.hostname) || "";
149
- };
150
- this.getIsLocal = () => {
151
- return this.getNetwork() !== "ic";
152
- };
153
- this.getNetwork = () => {
154
- const hostname = this.getAgentHostName();
155
- if (constants_1.LOCAL_HOSTS.some((host) => hostname.endsWith(host))) {
156
- return "local";
157
- }
158
- else if (constants_1.REMOTE_HOSTS.some((host) => hostname.endsWith(host))) {
159
- return "remote";
160
- }
161
- else {
162
- return "ic";
163
- }
164
- };
165
- this.getAgentState = () => {
166
- return this.agentStore.getState();
167
- };
168
- this.subscribeAgentState = (listener) => {
169
- return this.agentStore.subscribe(listener);
170
- };
171
- // auth store
172
- this.getAuthState = () => {
173
- return this.authStore.getState();
174
- };
175
- this.subscribeAuthState = (listener) => {
176
- return this.authStore.subscribe(listener);
177
- };
178
- this.getAuth = () => {
179
- return this._auth;
180
- };
181
- this.getIdentity = () => {
182
- return this.authStore.getState().identity;
183
- };
184
- this.getPrincipal = () => {
185
- const identity = this.authStore.getState().identity;
186
- return identity ? identity.getPrincipal() : null;
187
- };
188
- const _b = options || {}, { withDevtools, port = 4943, withLocalEnv, withProcessEnv } = _b, agentOptions = __rest(_b, ["withDevtools", "port", "withLocalEnv", "withProcessEnv"]);
38
+ const { withDevtools, port = 4943, withLocalEnv, withProcessEnv, initializeOnCreate = true, ...agentOptions } = options || {};
189
39
  if (withProcessEnv) {
190
40
  const processNetwork = (0, helper_1.getProcessEnvNetwork)();
191
41
  agentOptions.host =
@@ -195,21 +45,177 @@ class AgentManager {
195
45
  agentOptions.host = `http://127.0.0.1:${port}`;
196
46
  }
197
47
  else {
198
- agentOptions.host = (_a = agentOptions.host) !== null && _a !== void 0 ? _a : constants_1.IC_HOST_NETWORK_URI;
48
+ agentOptions.host = agentOptions.host ?? constants_1.IC_HOST_NETWORK_URI;
199
49
  }
200
- this.agentStore = (0, helper_1.createStoreWithOptionalDevtools)(this.initialAgentState, {
50
+ this.agentStore = (0, helper_1.createStoreWithOptionalDevtools)(AGENT_INITIAL_STATE, {
201
51
  withDevtools,
202
52
  name: "reactor-agent",
203
53
  store: "agent",
204
54
  });
205
- this.authStore = (0, helper_1.createStoreWithOptionalDevtools)(this.initialAuthState, {
55
+ this.authStore = (0, helper_1.createStoreWithOptionalDevtools)(AUTH_INITIAL_STATE, {
206
56
  withDevtools,
207
57
  name: "reactor-agent",
208
58
  store: "auth",
209
59
  });
210
- this._anonymousAgent = agent_1.HttpAgent.createSync(agentOptions);
211
60
  this._agent = agent_1.HttpAgent.createSync(agentOptions);
212
- this.initializeAgent();
61
+ if (initializeOnCreate) {
62
+ this.initializeAgent();
63
+ }
213
64
  }
65
+ initializeAgent = async () => {
66
+ const network = this.getNetwork();
67
+ this.updateAgentState({
68
+ initializing: true,
69
+ isInitializing: true,
70
+ error: undefined,
71
+ network,
72
+ }, "initializing");
73
+ if (network !== "ic") {
74
+ try {
75
+ await this._agent.fetchRootKey();
76
+ }
77
+ catch (error) {
78
+ this.updateAgentState({
79
+ error: error,
80
+ initializing: false,
81
+ isInitializing: false,
82
+ }, "error");
83
+ }
84
+ }
85
+ this.updateAgentState({
86
+ initialized: true,
87
+ isInitialized: true,
88
+ initializing: false,
89
+ isInitializing: false,
90
+ }, "initialized");
91
+ };
92
+ subscribeAgent = (callback, initialize = true) => {
93
+ if (initialize) {
94
+ callback(this._agent);
95
+ }
96
+ this._subscribers.push(callback);
97
+ return () => this.unsubscribeAgent(callback);
98
+ };
99
+ unsubscribeAgent = (callback) => {
100
+ this._subscribers = this._subscribers.filter((sub) => sub !== callback);
101
+ };
102
+ notifySubscribers = async () => {
103
+ await Promise.all(this._subscribers.map(async (callback) => callback(this._agent)));
104
+ };
105
+ updateAgent = async (options) => {
106
+ const { agent } = options || {};
107
+ if (agent) {
108
+ this._agent = agent;
109
+ }
110
+ else if (options) {
111
+ this._agent = agent_1.HttpAgent.createSync(options);
112
+ await this.initializeAgent();
113
+ }
114
+ await this.notifySubscribers();
115
+ };
116
+ authenticate = async () => {
117
+ console.log(`Authenticating on ${this.getNetwork()} network`);
118
+ this.updateAuthState({ isAuthenticating: true, authenticating: true }, "authenticating");
119
+ try {
120
+ this._auth = await auth_client_1.AuthClient.create();
121
+ const isAuthenticated = await this._auth.isAuthenticated();
122
+ const identity = this._auth.getIdentity();
123
+ this._agent.replaceIdentity(identity);
124
+ this.notifySubscribers();
125
+ this.updateAuthState({
126
+ authenticated: isAuthenticated,
127
+ isAuthenticated,
128
+ identity,
129
+ authenticating: false,
130
+ isAuthenticating: false,
131
+ }, "authenticated");
132
+ return identity;
133
+ }
134
+ catch (error) {
135
+ this.updateAuthState({
136
+ error: error,
137
+ isAuthenticating: false,
138
+ authenticating: false,
139
+ }, "error");
140
+ throw error;
141
+ }
142
+ };
143
+ login = async (options) => {
144
+ this.updateAuthState({ isAuthenticating: true, authenticating: true }, "login");
145
+ if (!this._auth) {
146
+ await this.authenticate();
147
+ }
148
+ if (!this._auth) {
149
+ throw new Error("Auth client not initialized");
150
+ }
151
+ await this._auth.login({
152
+ identityProvider: this.getIsLocal()
153
+ ? constants_1.LOCAL_INTERNET_IDENTITY_PROVIDER
154
+ : constants_1.IC_INTERNET_IDENTITY_PROVIDER,
155
+ ...options,
156
+ onSuccess: async (msg) => {
157
+ await this.authenticate();
158
+ options?.onSuccess?.(msg);
159
+ },
160
+ });
161
+ };
162
+ logout = async (options) => {
163
+ if (!this._auth) {
164
+ throw new Error("Auth client not initialized");
165
+ }
166
+ await this._auth.logout(options);
167
+ await this.authenticate();
168
+ };
169
+ // agent store
170
+ getAgent = () => {
171
+ return this._agent;
172
+ };
173
+ getAgentHost = () => {
174
+ return this._agent.host;
175
+ };
176
+ getAgentHostName = () => {
177
+ return this.getAgentHost()?.hostname || "";
178
+ };
179
+ getIsLocal = () => {
180
+ return this.getNetwork() !== "ic";
181
+ };
182
+ isAuthClientInitialized = () => {
183
+ return this.getAgentState().isInitialized && this._auth !== null;
184
+ };
185
+ getNetwork = () => {
186
+ const hostname = this.getAgentHostName();
187
+ return (0, helper_1.getNetworkByHostname)(hostname);
188
+ };
189
+ getAgentState = () => {
190
+ return this.agentStore.getState();
191
+ };
192
+ // @ts-expect-error: Overrides subscribe method signature
193
+ subscribeAgentState = (selectorOrListener, listener, options) => {
194
+ if (listener) {
195
+ return this.agentStore.subscribe(selectorOrListener, listener, options);
196
+ }
197
+ return this.agentStore.subscribe(selectorOrListener);
198
+ };
199
+ // auth store
200
+ getAuthState = () => {
201
+ return this.authStore.getState();
202
+ };
203
+ // @ts-expect-error: Overrides subscribe method signature
204
+ subscribeAuthState = (selectorOrListener, listener, options) => {
205
+ if (listener) {
206
+ return this.authStore.subscribe(selectorOrListener, listener, options);
207
+ }
208
+ return this.authStore.subscribe(selectorOrListener);
209
+ };
210
+ getAuth = () => {
211
+ return this._auth;
212
+ };
213
+ getIdentity = () => {
214
+ return this.authStore.getState().identity;
215
+ };
216
+ getPrincipal = () => {
217
+ const identity = this.authStore.getState().identity;
218
+ return identity ? identity.getPrincipal() : null;
219
+ };
214
220
  }
215
221
  exports.AgentManager = AgentManager;