@ecency/sdk 1.2.1 → 1.3.0

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.
@@ -0,0 +1,1646 @@
1
+ import { QueryClient, useQuery, useInfiniteQuery, useMutation, queryOptions, useQueryClient, infiniteQueryOptions } from '@tanstack/react-query';
2
+ import { Client, PrivateKey, cryptoUtils, RCAPI } from '@hiveio/dhive';
3
+ import hs from 'hivesigner';
4
+ import * as R from 'remeda';
5
+
6
+ var __defProp = Object.defineProperty;
7
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __publicField = (obj, key, value) => __defNormalProp(obj, key + "" , value);
13
+
14
+ // src/modules/core/mock-storage.ts
15
+ var MockStorage = class {
16
+ constructor() {
17
+ __publicField(this, "length", 0);
18
+ }
19
+ clear() {
20
+ throw new Error("Method not implemented.");
21
+ }
22
+ getItem(key) {
23
+ return this[key];
24
+ }
25
+ key(index) {
26
+ return Object.keys(this)[index];
27
+ }
28
+ removeItem(key) {
29
+ delete this[key];
30
+ }
31
+ setItem(key, value) {
32
+ this[key] = value;
33
+ }
34
+ };
35
+ var CONFIG = {
36
+ privateApiHost: "https://ecency.com",
37
+ storage: typeof window === "undefined" ? new MockStorage() : window.localStorage,
38
+ storagePrefix: "ecency",
39
+ hiveClient: new Client(
40
+ [
41
+ "https://api.hive.blog",
42
+ "https://api.deathwing.me",
43
+ "https://rpc.mahdiyari.info",
44
+ "https://api.openhive.network",
45
+ "https://techcoderx.com",
46
+ "https://hive-api.arcange.eu",
47
+ "https://api.syncad.com",
48
+ "https://anyx.io",
49
+ "https://api.c0ff33a.uk",
50
+ "https://hiveapi.actifit.io",
51
+ "https://hive-api.3speak.tv"
52
+ ],
53
+ {
54
+ timeout: 2e3,
55
+ failoverThreshold: 2,
56
+ consoleOnFailover: true
57
+ }
58
+ ),
59
+ heliusApiKey: process.env.VITE_HELIUS_API_KEY,
60
+ queryClient: new QueryClient(),
61
+ plausibleHost: "https://pl.ecency.com",
62
+ spkNode: "https://spk.good-karma.xyz"
63
+ };
64
+ var ConfigManager;
65
+ ((ConfigManager2) => {
66
+ function setQueryClient(client) {
67
+ CONFIG.queryClient = client;
68
+ }
69
+ ConfigManager2.setQueryClient = setQueryClient;
70
+ })(ConfigManager || (ConfigManager = {}));
71
+
72
+ // src/modules/core/utils/decoder-encoder.ts
73
+ function encodeObj(o) {
74
+ return btoa(JSON.stringify(o));
75
+ }
76
+ function decodeObj(o) {
77
+ let dataToParse = atob(o);
78
+ if (dataToParse[0] !== "{") {
79
+ return void 0;
80
+ }
81
+ return JSON.parse(dataToParse);
82
+ }
83
+
84
+ // src/modules/core/utils/parse-asset.ts
85
+ var Symbol2 = /* @__PURE__ */ ((Symbol3) => {
86
+ Symbol3["HIVE"] = "HIVE";
87
+ Symbol3["HBD"] = "HBD";
88
+ Symbol3["VESTS"] = "VESTS";
89
+ Symbol3["SPK"] = "SPK";
90
+ return Symbol3;
91
+ })(Symbol2 || {});
92
+ var NaiMap = /* @__PURE__ */ ((NaiMap2) => {
93
+ NaiMap2["@@000000021"] = "HIVE";
94
+ NaiMap2["@@000000013"] = "HBD";
95
+ NaiMap2["@@000000037"] = "VESTS";
96
+ return NaiMap2;
97
+ })(NaiMap || {});
98
+ function parseAsset(sval) {
99
+ if (typeof sval === "string") {
100
+ const sp = sval.split(" ");
101
+ return {
102
+ amount: parseFloat(sp[0]),
103
+ // @ts-ignore
104
+ symbol: Symbol2[sp[1]]
105
+ };
106
+ } else {
107
+ return {
108
+ amount: parseFloat(sval.amount.toString()) / Math.pow(10, sval.precision),
109
+ // @ts-ignore
110
+ symbol: NaiMap[sval.nai]
111
+ };
112
+ }
113
+ }
114
+
115
+ // src/modules/core/utils/get-bound-fetch.ts
116
+ var cachedFetch;
117
+ function getBoundFetch() {
118
+ if (!cachedFetch) {
119
+ if (typeof globalThis.fetch !== "function") {
120
+ throw new Error("[Ecency][SDK] - global fetch is not available");
121
+ }
122
+ cachedFetch = globalThis.fetch.bind(globalThis);
123
+ }
124
+ return cachedFetch;
125
+ }
126
+
127
+ // src/modules/core/storage.ts
128
+ var getUser = (username) => {
129
+ try {
130
+ const raw = CONFIG.storage.getItem(
131
+ CONFIG.storagePrefix + "_user_" + username
132
+ );
133
+ return decodeObj(JSON.parse(raw));
134
+ } catch (e) {
135
+ console.error(e);
136
+ return void 0;
137
+ }
138
+ };
139
+ var getAccessToken = (username) => getUser(username) && getUser(username).accessToken;
140
+ var getPostingKey = (username) => getUser(username) && getUser(username).postingKey;
141
+ var getLoginType = (username) => getUser(username) && getUser(username).loginType;
142
+ var getRefreshToken = (username) => getUser(username) && getUser(username).refreshToken;
143
+
144
+ // src/modules/keychain/keychain.ts
145
+ var keychain_exports = {};
146
+ __export(keychain_exports, {
147
+ broadcast: () => broadcast,
148
+ customJson: () => customJson,
149
+ handshake: () => handshake
150
+ });
151
+ function handshake() {
152
+ return new Promise((resolve) => {
153
+ window.hive_keychain?.requestHandshake(() => {
154
+ resolve();
155
+ });
156
+ });
157
+ }
158
+ var broadcast = (account, operations, key, rpc = null) => new Promise((resolve, reject) => {
159
+ window.hive_keychain?.requestBroadcast(
160
+ account,
161
+ operations,
162
+ key,
163
+ (resp) => {
164
+ if (!resp.success) {
165
+ reject({ message: "Operation cancelled" });
166
+ }
167
+ resolve(resp);
168
+ },
169
+ rpc
170
+ );
171
+ });
172
+ var customJson = (account, id, key, json, display_msg, rpc = null) => new Promise((resolve, reject) => {
173
+ window.hive_keychain?.requestCustomJson(
174
+ account,
175
+ id,
176
+ key,
177
+ json,
178
+ display_msg,
179
+ (resp) => {
180
+ if (!resp.success) {
181
+ reject({ message: "Operation cancelled" });
182
+ }
183
+ resolve(resp);
184
+ },
185
+ rpc
186
+ );
187
+ });
188
+
189
+ // src/modules/core/mutations/use-broadcast-mutation.ts
190
+ function useBroadcastMutation(mutationKey = [], username, operations, onSuccess = () => {
191
+ }) {
192
+ return useMutation({
193
+ onSuccess,
194
+ mutationKey: [...mutationKey, username],
195
+ mutationFn: async (payload) => {
196
+ if (!username) {
197
+ throw new Error(
198
+ "[Core][Broadcast] Attempted to call broadcast API with anon user"
199
+ );
200
+ }
201
+ const postingKey = getPostingKey(username);
202
+ if (postingKey) {
203
+ const privateKey = PrivateKey.fromString(postingKey);
204
+ return CONFIG.hiveClient.broadcast.sendOperations(
205
+ operations(payload),
206
+ privateKey
207
+ );
208
+ }
209
+ const loginType = getLoginType(username);
210
+ if (loginType && loginType == "keychain") {
211
+ return keychain_exports.broadcast(
212
+ username,
213
+ operations(payload),
214
+ "Posting"
215
+ ).then((r) => r.result);
216
+ }
217
+ let token = getAccessToken(username);
218
+ if (token) {
219
+ const f = getBoundFetch();
220
+ const res = await f("https://hivesigner.com/api/broadcast", {
221
+ method: "POST",
222
+ headers: {
223
+ Authorization: token,
224
+ "Content-Type": "application/json",
225
+ Accept: "application/json"
226
+ },
227
+ body: JSON.stringify({ operations: operations(payload) })
228
+ });
229
+ if (!res.ok) {
230
+ const txt = await res.text().catch(() => "");
231
+ throw new Error(`[Hivesigner] ${res.status} ${res.statusText} ${txt}`);
232
+ }
233
+ const json = await res.json();
234
+ if (json?.errors) {
235
+ throw new Error(`[Hivesigner] ${JSON.stringify(json.errors)}`);
236
+ }
237
+ return json.result;
238
+ }
239
+ throw new Error(
240
+ "[SDK][Broadcast] \u2013 cannot broadcast w/o posting key or token"
241
+ );
242
+ }
243
+ });
244
+ }
245
+ async function broadcastJson(username, id, payload) {
246
+ if (!username) {
247
+ throw new Error(
248
+ "[Core][Broadcast] Attempted to call broadcast API with anon user"
249
+ );
250
+ }
251
+ const jjson = {
252
+ id,
253
+ required_auths: [],
254
+ required_posting_auths: [username],
255
+ json: JSON.stringify(payload)
256
+ };
257
+ const postingKey = getPostingKey(username);
258
+ if (postingKey) {
259
+ const privateKey = PrivateKey.fromString(postingKey);
260
+ return CONFIG.hiveClient.broadcast.json(
261
+ jjson,
262
+ privateKey
263
+ );
264
+ }
265
+ const loginType = getLoginType(username);
266
+ if (loginType && loginType == "keychain") {
267
+ return keychain_exports.broadcast(username, [["custom_json", jjson]], "Posting").then((r) => r.result);
268
+ }
269
+ let token = getAccessToken(username);
270
+ if (token) {
271
+ const response = await new hs.Client({
272
+ accessToken: token
273
+ }).customJson([], [username], id, JSON.stringify(payload));
274
+ return response.result;
275
+ }
276
+ throw new Error(
277
+ "[SDK][Broadcast] \u2013 cannot broadcast w/o posting key or token"
278
+ );
279
+ }
280
+ function makeQueryClient() {
281
+ return new QueryClient({
282
+ defaultOptions: {
283
+ queries: {
284
+ // With SSR, we usually want to set some default staleTime
285
+ // above 0 to avoid refetching immediately on the client
286
+ // staleTime: 60 * 1000,
287
+ refetchOnWindowFocus: false,
288
+ refetchOnMount: false
289
+ }
290
+ }
291
+ });
292
+ }
293
+ var getQueryClient = () => CONFIG.queryClient;
294
+ var EcencyQueriesManager;
295
+ ((EcencyQueriesManager2) => {
296
+ function getQueryData(queryKey) {
297
+ const queryClient = getQueryClient();
298
+ return queryClient.getQueryData(queryKey);
299
+ }
300
+ EcencyQueriesManager2.getQueryData = getQueryData;
301
+ function getInfiniteQueryData(queryKey) {
302
+ const queryClient = getQueryClient();
303
+ return queryClient.getQueryData(queryKey);
304
+ }
305
+ EcencyQueriesManager2.getInfiniteQueryData = getInfiniteQueryData;
306
+ async function prefetchQuery(options) {
307
+ const queryClient = getQueryClient();
308
+ await queryClient.prefetchQuery(options);
309
+ return getQueryData(options.queryKey);
310
+ }
311
+ EcencyQueriesManager2.prefetchQuery = prefetchQuery;
312
+ async function prefetchInfiniteQuery(options) {
313
+ const queryClient = getQueryClient();
314
+ await queryClient.prefetchInfiniteQuery(options);
315
+ return getInfiniteQueryData(options.queryKey);
316
+ }
317
+ EcencyQueriesManager2.prefetchInfiniteQuery = prefetchInfiniteQuery;
318
+ function generateClientServerQuery(options) {
319
+ return {
320
+ prefetch: () => prefetchQuery(options),
321
+ getData: () => getQueryData(options.queryKey),
322
+ useClientQuery: () => useQuery(options),
323
+ fetchAndGet: () => getQueryClient().fetchQuery(options)
324
+ };
325
+ }
326
+ EcencyQueriesManager2.generateClientServerQuery = generateClientServerQuery;
327
+ function generateClientServerInfiniteQuery(options) {
328
+ return {
329
+ prefetch: () => prefetchInfiniteQuery(options),
330
+ getData: () => getInfiniteQueryData(options.queryKey),
331
+ useClientQuery: () => useInfiniteQuery(options),
332
+ fetchAndGet: () => getQueryClient().fetchInfiniteQuery(options)
333
+ };
334
+ }
335
+ EcencyQueriesManager2.generateClientServerInfiniteQuery = generateClientServerInfiniteQuery;
336
+ })(EcencyQueriesManager || (EcencyQueriesManager = {}));
337
+ function getDynamicPropsQueryOptions() {
338
+ return queryOptions({
339
+ queryKey: ["core", "dynamic-props"],
340
+ refetchInterval: 6e4,
341
+ staleTime: 6e4,
342
+ refetchOnMount: true,
343
+ queryFn: async () => {
344
+ const globalDynamic = await CONFIG.hiveClient.database.getDynamicGlobalProperties().then((r) => ({
345
+ total_vesting_fund_hive: r.total_vesting_fund_hive || r.total_vesting_fund_steem,
346
+ total_vesting_shares: r.total_vesting_shares,
347
+ hbd_print_rate: r.hbd_print_rate || r.sbd_print_rate,
348
+ hbd_interest_rate: r.hbd_interest_rate,
349
+ head_block_number: r.head_block_number,
350
+ vesting_reward_percent: r.vesting_reward_percent,
351
+ virtual_supply: r.virtual_supply
352
+ }));
353
+ const feedHistory = await CONFIG.hiveClient.database.call("get_feed_history");
354
+ const chainProps = await CONFIG.hiveClient.database.call(
355
+ "get_chain_properties"
356
+ );
357
+ const rewardFund = await CONFIG.hiveClient.database.call(
358
+ "get_reward_fund",
359
+ ["post"]
360
+ );
361
+ const hivePerMVests = parseAsset(globalDynamic.total_vesting_fund_hive).amount / parseAsset(globalDynamic.total_vesting_shares).amount * 1e6;
362
+ const base = parseAsset(feedHistory.current_median_history.base).amount;
363
+ const quote = parseAsset(feedHistory.current_median_history.quote).amount;
364
+ const fundRecentClaims = parseFloat(rewardFund.recent_claims);
365
+ const fundRewardBalance = parseAsset(rewardFund.reward_balance).amount;
366
+ const hbdPrintRate = globalDynamic.hbd_print_rate;
367
+ const hbdInterestRate = globalDynamic.hbd_interest_rate;
368
+ const headBlock = globalDynamic.head_block_number;
369
+ const totalVestingFund = parseAsset(
370
+ globalDynamic.total_vesting_fund_hive
371
+ ).amount;
372
+ const totalVestingShares = parseAsset(
373
+ globalDynamic.total_vesting_shares
374
+ ).amount;
375
+ const virtualSupply = parseAsset(globalDynamic.virtual_supply).amount;
376
+ const vestingRewardPercent = globalDynamic.vesting_reward_percent;
377
+ const accountCreationFee = chainProps.account_creation_fee;
378
+ return {
379
+ hivePerMVests,
380
+ base,
381
+ quote,
382
+ fundRecentClaims,
383
+ fundRewardBalance,
384
+ hbdPrintRate,
385
+ hbdInterestRate,
386
+ headBlock,
387
+ totalVestingFund,
388
+ totalVestingShares,
389
+ virtualSupply,
390
+ vestingRewardPercent,
391
+ accountCreationFee
392
+ };
393
+ }
394
+ });
395
+ }
396
+ function getAccountFullQueryOptions(username) {
397
+ return queryOptions({
398
+ queryKey: ["get-account-full", username],
399
+ queryFn: async () => {
400
+ if (!username) {
401
+ throw new Error("[SDK] Username is empty");
402
+ }
403
+ const response = await CONFIG.hiveClient.database.getAccounts([
404
+ username
405
+ ]);
406
+ if (!response[0]) {
407
+ throw new Error("[SDK] No account with given username");
408
+ }
409
+ const profile = JSON.parse(response[0].posting_json_metadata).profile;
410
+ let follow_stats;
411
+ try {
412
+ follow_stats = await CONFIG.hiveClient.database.call(
413
+ "get_follow_count",
414
+ [username]
415
+ );
416
+ } catch (e) {
417
+ }
418
+ const reputation = await CONFIG.hiveClient.call(
419
+ "condenser_api",
420
+ "get_account_reputations",
421
+ [username, 1]
422
+ );
423
+ return {
424
+ name: response[0].name,
425
+ owner: response[0].owner,
426
+ active: response[0].active,
427
+ posting: response[0].posting,
428
+ memo_key: response[0].memo_key,
429
+ post_count: response[0].post_count,
430
+ created: response[0].created,
431
+ posting_json_metadata: response[0].posting_json_metadata,
432
+ last_vote_time: response[0].last_vote_time,
433
+ last_post: response[0].last_post,
434
+ json_metadata: response[0].json_metadata,
435
+ reward_hive_balance: response[0].reward_hive_balance,
436
+ reward_hbd_balance: response[0].reward_hbd_balance,
437
+ reward_vesting_hive: response[0].reward_vesting_hive,
438
+ reward_vesting_balance: response[0].reward_vesting_balance,
439
+ balance: response[0].balance,
440
+ hbd_balance: response[0].hbd_balance,
441
+ savings_balance: response[0].savings_balance,
442
+ savings_hbd_balance: response[0].savings_hbd_balance,
443
+ savings_hbd_last_interest_payment: response[0].savings_hbd_last_interest_payment,
444
+ savings_hbd_seconds_last_update: response[0].savings_hbd_seconds_last_update,
445
+ savings_hbd_seconds: response[0].savings_hbd_seconds,
446
+ next_vesting_withdrawal: response[0].next_vesting_withdrawal,
447
+ pending_claimed_accounts: response[0].pending_claimed_accounts,
448
+ vesting_shares: response[0].vesting_shares,
449
+ delegated_vesting_shares: response[0].delegated_vesting_shares,
450
+ received_vesting_shares: response[0].received_vesting_shares,
451
+ vesting_withdraw_rate: response[0].vesting_withdraw_rate,
452
+ to_withdraw: response[0].to_withdraw,
453
+ withdrawn: response[0].withdrawn,
454
+ witness_votes: response[0].witness_votes,
455
+ proxy: response[0].proxy,
456
+ recovery_account: response[0].recovery_account,
457
+ proxied_vsf_votes: response[0].proxied_vsf_votes,
458
+ voting_manabar: response[0].voting_manabar,
459
+ voting_power: response[0].voting_power,
460
+ downvote_manabar: response[0].downvote_manabar,
461
+ follow_stats,
462
+ reputation: reputation[0].reputation,
463
+ profile: {
464
+ ...profile,
465
+ reputation: reputation[0].reputation
466
+ }
467
+ };
468
+ },
469
+ enabled: !!username,
470
+ staleTime: 6e4
471
+ });
472
+ }
473
+ function getSearchAccountsByUsernameQueryOptions(query, limit = 5, excludeList = []) {
474
+ return queryOptions({
475
+ queryKey: ["accounts", "search", query, excludeList],
476
+ enabled: !!query,
477
+ queryFn: async () => {
478
+ const response = await CONFIG.hiveClient.database.call(
479
+ "lookup_accounts",
480
+ [query, limit]
481
+ );
482
+ return response.filter(
483
+ (item) => excludeList.length > 0 ? !excludeList.includes(item) : true
484
+ );
485
+ }
486
+ });
487
+ }
488
+ function checkUsernameWalletsPendingQueryOptions(username) {
489
+ return queryOptions({
490
+ queryKey: ["accounts", "check-wallet-pending", username],
491
+ queryFn: async () => {
492
+ const fetchApi = getBoundFetch();
493
+ const response = await fetchApi(
494
+ CONFIG.privateApiHost + "/private-api/wallets-chkuser",
495
+ {
496
+ method: "POST",
497
+ headers: {
498
+ "Content-Type": "application/json"
499
+ },
500
+ body: JSON.stringify({
501
+ username
502
+ })
503
+ }
504
+ );
505
+ return await response.json();
506
+ },
507
+ enabled: !!username,
508
+ refetchOnMount: true
509
+ });
510
+ }
511
+ function getRelationshipBetweenAccountsQueryOptions(reference, target) {
512
+ return queryOptions({
513
+ queryKey: ["accounts", "relations", reference, target],
514
+ enabled: !!reference && !!target,
515
+ refetchOnMount: false,
516
+ refetchInterval: 36e5,
517
+ queryFn: async () => {
518
+ return await CONFIG.hiveClient.call(
519
+ "bridge",
520
+ "get_relationship_between_accounts",
521
+ [reference, target]
522
+ );
523
+ }
524
+ });
525
+ }
526
+ function getAccountSubscriptionsQueryOptions(username) {
527
+ return queryOptions({
528
+ queryKey: ["accounts", "subscriptions", username],
529
+ enabled: !!username,
530
+ queryFn: async () => {
531
+ const response = await CONFIG.hiveClient.call(
532
+ "bridge",
533
+ "list_all_subscriptions",
534
+ {
535
+ account: username
536
+ }
537
+ );
538
+ return response ?? [];
539
+ }
540
+ });
541
+ }
542
+ function getActiveAccountBookmarksQueryOptions(activeUsername) {
543
+ return queryOptions({
544
+ queryKey: ["accounts", "bookmarks", activeUsername],
545
+ enabled: !!activeUsername,
546
+ queryFn: async () => {
547
+ if (!activeUsername) {
548
+ throw new Error("[SDK][Accounts][Bookmarks] \u2013 no active user");
549
+ }
550
+ const fetchApi = getBoundFetch();
551
+ const response = await fetchApi(
552
+ CONFIG.privateApiHost + "/private-api/bookmarks",
553
+ {
554
+ method: "POST",
555
+ headers: {
556
+ "Content-Type": "application/json"
557
+ },
558
+ body: JSON.stringify({ code: getAccessToken(activeUsername) })
559
+ }
560
+ );
561
+ return await response.json();
562
+ }
563
+ });
564
+ }
565
+ function getActiveAccountFavouritesQueryOptions(activeUsername) {
566
+ return queryOptions({
567
+ queryKey: ["accounts", "favourites", activeUsername],
568
+ enabled: !!activeUsername,
569
+ queryFn: async () => {
570
+ if (!activeUsername) {
571
+ throw new Error("[SDK][Accounts][Favourites] \u2013 no active user");
572
+ }
573
+ const fetchApi = getBoundFetch();
574
+ const response = await fetchApi(
575
+ CONFIG.privateApiHost + "/private-api/favorites",
576
+ {
577
+ method: "POST",
578
+ headers: {
579
+ "Content-Type": "application/json"
580
+ },
581
+ body: JSON.stringify({ code: getAccessToken(activeUsername) })
582
+ }
583
+ );
584
+ return await response.json();
585
+ }
586
+ });
587
+ }
588
+ function getAccountRecoveriesQueryOptions(username) {
589
+ return queryOptions({
590
+ enabled: !!username,
591
+ queryKey: ["accounts", "recoveries", username],
592
+ queryFn: async () => {
593
+ const fetchApi = getBoundFetch();
594
+ const response = await fetchApi(
595
+ CONFIG.privateApiHost + "/private-api/recoveries",
596
+ {
597
+ method: "POST",
598
+ headers: {
599
+ "Content-Type": "application/json"
600
+ },
601
+ body: JSON.stringify({ code: getAccessToken(username) })
602
+ }
603
+ );
604
+ return response.json();
605
+ }
606
+ });
607
+ }
608
+ function getAccountPendingRecoveryQueryOptions(username) {
609
+ return queryOptions({
610
+ enabled: !!username,
611
+ queryKey: ["accounts", "recoveries", username, "pending-request"],
612
+ queryFn: () => CONFIG.hiveClient.call(
613
+ "database_api",
614
+ "find_change_recovery_account_requests",
615
+ { accounts: [username] }
616
+ )
617
+ });
618
+ }
619
+ function sanitizeTokens(tokens) {
620
+ return tokens?.map(({ meta, ...rest }) => {
621
+ if (!meta || typeof meta !== "object") {
622
+ return { ...rest, meta };
623
+ }
624
+ const { privateKey, username, ...safeMeta } = meta;
625
+ return { ...rest, meta: safeMeta };
626
+ });
627
+ }
628
+ function getBuiltProfile({
629
+ profile,
630
+ tokens,
631
+ data
632
+ }) {
633
+ const metadata = R.pipe(
634
+ JSON.parse(data?.posting_json_metadata || "{}").profile,
635
+ R.mergeDeep(profile ?? {})
636
+ );
637
+ if (tokens && tokens.length > 0) {
638
+ metadata.tokens = tokens;
639
+ }
640
+ metadata.tokens = sanitizeTokens(metadata.tokens);
641
+ return metadata;
642
+ }
643
+ function useAccountUpdate(username) {
644
+ const queryClient = useQueryClient();
645
+ const { data } = useQuery(getAccountFullQueryOptions(username));
646
+ return useBroadcastMutation(
647
+ ["accounts", "update"],
648
+ username,
649
+ (payload) => {
650
+ if (!data) {
651
+ throw new Error("[SDK][Accounts] \u2013 cannot update not existing account");
652
+ }
653
+ return [
654
+ [
655
+ "account_update2",
656
+ {
657
+ account: username,
658
+ json_metadata: "",
659
+ extensions: [],
660
+ posting_json_metadata: JSON.stringify({
661
+ profile: getBuiltProfile({ ...payload, data })
662
+ })
663
+ }
664
+ ]
665
+ ];
666
+ },
667
+ (_, variables) => queryClient.setQueryData(
668
+ getAccountFullQueryOptions(username).queryKey,
669
+ (data2) => {
670
+ if (!data2) {
671
+ return data2;
672
+ }
673
+ const obj = R.clone(data2);
674
+ obj.profile = getBuiltProfile({ ...variables, data: data2 });
675
+ return obj;
676
+ }
677
+ )
678
+ );
679
+ }
680
+ function useAccountRelationsUpdate(reference, target, onSuccess, onError) {
681
+ return useMutation({
682
+ mutationKey: ["accounts", "relation", "update", reference, target],
683
+ mutationFn: async (kind) => {
684
+ const relationsQuery = getRelationshipBetweenAccountsQueryOptions(
685
+ reference,
686
+ target
687
+ );
688
+ await getQueryClient().prefetchQuery(relationsQuery);
689
+ const actualRelation = getQueryClient().getQueryData(
690
+ relationsQuery.queryKey
691
+ );
692
+ await broadcastJson(reference, "follow", [
693
+ "follow",
694
+ {
695
+ follower: reference,
696
+ following: target,
697
+ what: [
698
+ ...kind === "toggle-ignore" && !actualRelation?.ignores ? ["ignore"] : [],
699
+ ...kind === "toggle-follow" && !actualRelation?.follows ? ["blog"] : []
700
+ ]
701
+ }
702
+ ]);
703
+ return {
704
+ ...actualRelation,
705
+ ignores: kind === "toggle-ignore" ? !actualRelation?.ignores : actualRelation?.ignores,
706
+ follows: kind === "toggle-follow" ? !actualRelation?.follows : actualRelation?.follows
707
+ };
708
+ },
709
+ onError,
710
+ onSuccess(data) {
711
+ onSuccess(data);
712
+ getQueryClient().setQueryData(
713
+ ["accounts", "relations", reference, target],
714
+ data
715
+ );
716
+ }
717
+ });
718
+ }
719
+ function useBookmarkAdd(username, onSuccess, onError) {
720
+ return useMutation({
721
+ mutationKey: ["accounts", "bookmarks", "add", username],
722
+ mutationFn: async ({ author, permlink }) => {
723
+ if (!username) {
724
+ throw new Error("[SDK][Account][Bookmarks] \u2013 no active user");
725
+ }
726
+ const fetchApi = getBoundFetch();
727
+ const response = await fetchApi(
728
+ CONFIG.privateApiHost + "/private-api/bookmarks-add",
729
+ {
730
+ method: "POST",
731
+ headers: {
732
+ "Content-Type": "application/json"
733
+ },
734
+ body: JSON.stringify({
735
+ author,
736
+ permlink,
737
+ code: getAccessToken(username)
738
+ })
739
+ }
740
+ );
741
+ return response.json();
742
+ },
743
+ onSuccess: () => {
744
+ onSuccess();
745
+ getQueryClient().invalidateQueries({
746
+ queryKey: ["accounts", "bookmarks", username]
747
+ });
748
+ },
749
+ onError
750
+ });
751
+ }
752
+ function useBookmarkDelete(username, onSuccess, onError) {
753
+ return useMutation({
754
+ mutationKey: ["accounts", "bookmarks", "delete", username],
755
+ mutationFn: async (bookmarkId) => {
756
+ if (!username) {
757
+ throw new Error("[SDK][Account][Bookmarks] \u2013 no active user");
758
+ }
759
+ const fetchApi = getBoundFetch();
760
+ const response = await fetchApi(
761
+ CONFIG.privateApiHost + "/private-api/bookmarks-delete",
762
+ {
763
+ method: "POST",
764
+ headers: {
765
+ "Content-Type": "application/json"
766
+ },
767
+ body: JSON.stringify({
768
+ id: bookmarkId,
769
+ code: getAccessToken(username)
770
+ })
771
+ }
772
+ );
773
+ return response.json();
774
+ },
775
+ onSuccess: () => {
776
+ onSuccess();
777
+ getQueryClient().invalidateQueries({
778
+ queryKey: ["accounts", "bookmarks", username]
779
+ });
780
+ },
781
+ onError
782
+ });
783
+ }
784
+ function useAccountFavouriteAdd(username, onSuccess, onError) {
785
+ return useMutation({
786
+ mutationKey: ["accounts", "favourites", "add", username],
787
+ mutationFn: async (account) => {
788
+ if (!username) {
789
+ throw new Error("[SDK][Account][Bookmarks] \u2013 no active user");
790
+ }
791
+ const fetchApi = getBoundFetch();
792
+ const response = await fetchApi(
793
+ CONFIG.privateApiHost + "/private-api/favorites-add",
794
+ {
795
+ method: "POST",
796
+ headers: {
797
+ "Content-Type": "application/json"
798
+ },
799
+ body: JSON.stringify({
800
+ account,
801
+ code: getAccessToken(username)
802
+ })
803
+ }
804
+ );
805
+ return response.json();
806
+ },
807
+ onSuccess: () => {
808
+ onSuccess();
809
+ getQueryClient().invalidateQueries({
810
+ queryKey: ["accounts", "favourites", username]
811
+ });
812
+ },
813
+ onError
814
+ });
815
+ }
816
+ function useAccountFavouriteDelete(username, onSuccess, onError) {
817
+ return useMutation({
818
+ mutationKey: ["accounts", "favourites", "add", username],
819
+ mutationFn: async (account) => {
820
+ if (!username) {
821
+ throw new Error("[SDK][Account][Bookmarks] \u2013 no active user");
822
+ }
823
+ const fetchApi = getBoundFetch();
824
+ const response = await fetchApi(
825
+ CONFIG.privateApiHost + "/private-api/favorites-delete",
826
+ {
827
+ method: "POST",
828
+ headers: {
829
+ "Content-Type": "application/json"
830
+ },
831
+ body: JSON.stringify({
832
+ account,
833
+ code: getAccessToken(username)
834
+ })
835
+ }
836
+ );
837
+ return response.json();
838
+ },
839
+ onSuccess: () => {
840
+ onSuccess();
841
+ getQueryClient().invalidateQueries({
842
+ queryKey: ["accounts", "favourites", username]
843
+ });
844
+ },
845
+ onError
846
+ });
847
+ }
848
+ function dedupeAndSortKeyAuths(existing, additions) {
849
+ const merged = /* @__PURE__ */ new Map();
850
+ existing.forEach(([key, weight]) => {
851
+ merged.set(key.toString(), weight);
852
+ });
853
+ additions.forEach(([key, weight]) => {
854
+ merged.set(key.toString(), weight);
855
+ });
856
+ return Array.from(merged.entries()).sort(([keyA], [keyB]) => keyA.localeCompare(keyB)).map(([key, weight]) => [key, weight]);
857
+ }
858
+ function useAccountUpdateKeyAuths(username, options) {
859
+ const { data: accountData } = useQuery(getAccountFullQueryOptions(username));
860
+ return useMutation({
861
+ mutationKey: ["accounts", "keys-update", username],
862
+ mutationFn: async ({ keys, keepCurrent = false, currentKey }) => {
863
+ if (!accountData) {
864
+ throw new Error(
865
+ "[SDK][Update password] \u2013 cannot update keys for anon user"
866
+ );
867
+ }
868
+ const prepareAuth = (keyName) => {
869
+ const auth = R.clone(accountData[keyName]);
870
+ auth.key_auths = dedupeAndSortKeyAuths(
871
+ keepCurrent ? auth.key_auths : [],
872
+ keys.map(
873
+ (values, i) => [values[keyName].createPublic().toString(), i + 1]
874
+ )
875
+ );
876
+ return auth;
877
+ };
878
+ return CONFIG.hiveClient.broadcast.updateAccount(
879
+ {
880
+ account: username,
881
+ json_metadata: accountData.json_metadata,
882
+ owner: prepareAuth("owner"),
883
+ active: prepareAuth("active"),
884
+ posting: prepareAuth("posting"),
885
+ memo_key: keepCurrent ? accountData.memo_key : keys[0].memo_key.createPublic().toString()
886
+ },
887
+ currentKey
888
+ );
889
+ },
890
+ ...options
891
+ });
892
+ }
893
+ function useAccountUpdatePassword(username, options) {
894
+ const { data: accountData } = useQuery(getAccountFullQueryOptions(username));
895
+ const { mutateAsync: updateKeys } = useAccountUpdateKeyAuths(username);
896
+ return useMutation({
897
+ mutationKey: ["accounts", "password-update", username],
898
+ mutationFn: async ({
899
+ newPassword,
900
+ currentPassword,
901
+ keepCurrent
902
+ }) => {
903
+ if (!accountData) {
904
+ throw new Error(
905
+ "[SDK][Update password] \u2013 cannot update password for anon user"
906
+ );
907
+ }
908
+ const currentKey = PrivateKey.fromLogin(
909
+ username,
910
+ currentPassword,
911
+ "owner"
912
+ );
913
+ return updateKeys({
914
+ currentKey,
915
+ keepCurrent,
916
+ keys: [
917
+ {
918
+ owner: PrivateKey.fromLogin(username, newPassword, "owner"),
919
+ active: PrivateKey.fromLogin(username, newPassword, "active"),
920
+ posting: PrivateKey.fromLogin(username, newPassword, "posting"),
921
+ memo_key: PrivateKey.fromLogin(username, newPassword, "memo")
922
+ }
923
+ ]
924
+ });
925
+ },
926
+ ...options
927
+ });
928
+ }
929
+ function useAccountRevokePosting(username, options) {
930
+ const queryClient = useQueryClient();
931
+ const { data } = useQuery(getAccountFullQueryOptions(username));
932
+ return useMutation({
933
+ mutationKey: ["accounts", "revoke-posting", data?.name],
934
+ mutationFn: async ({ accountName, type, key }) => {
935
+ if (!data) {
936
+ throw new Error(
937
+ "[SDK][Accounts] \u2013\xA0cannot revoke posting for anonymous user"
938
+ );
939
+ }
940
+ const posting = R.pipe(
941
+ {},
942
+ R.mergeDeep(data.posting)
943
+ );
944
+ posting.account_auths = posting.account_auths.filter(
945
+ ([account]) => account !== accountName
946
+ );
947
+ const operationBody = {
948
+ account: data.name,
949
+ posting,
950
+ memo_key: data.memo_key,
951
+ json_metadata: data.json_metadata
952
+ };
953
+ if (type === "key" && key) {
954
+ return CONFIG.hiveClient.broadcast.updateAccount(operationBody, key);
955
+ } else if (type === "keychain") {
956
+ return keychain_exports.broadcast(
957
+ data.name,
958
+ [["account_update", operationBody]],
959
+ "Active"
960
+ );
961
+ } else {
962
+ const params = {
963
+ callback: `https://ecency.com/@${data.name}/permissions`
964
+ };
965
+ return hs.sendOperation(
966
+ ["account_update", operationBody],
967
+ params,
968
+ () => {
969
+ }
970
+ );
971
+ }
972
+ },
973
+ onError: options.onError,
974
+ onSuccess: (resp, payload, ctx) => {
975
+ options.onSuccess?.(resp, payload, ctx);
976
+ queryClient.setQueryData(
977
+ getAccountFullQueryOptions(username).queryKey,
978
+ (data2) => ({
979
+ ...data2,
980
+ posting: {
981
+ ...data2?.posting,
982
+ account_auths: data2?.posting?.account_auths?.filter(
983
+ ([account]) => account !== payload.accountName
984
+ ) ?? []
985
+ }
986
+ })
987
+ );
988
+ }
989
+ });
990
+ }
991
+ function useAccountUpdateRecovery(username, options) {
992
+ const { data } = useQuery(getAccountFullQueryOptions(username));
993
+ return useMutation({
994
+ mutationKey: ["accounts", "recovery", data?.name],
995
+ mutationFn: async ({ accountName, type, key, email }) => {
996
+ if (!data) {
997
+ throw new Error(
998
+ "[SDK][Accounts] \u2013\xA0cannot change recovery for anonymous user"
999
+ );
1000
+ }
1001
+ const operationBody = {
1002
+ account_to_recover: data.name,
1003
+ new_recovery_account: accountName,
1004
+ extensions: []
1005
+ };
1006
+ if (type === "ecency") {
1007
+ const fetchApi = getBoundFetch();
1008
+ return fetchApi(CONFIG.privateApiHost + "/private-api/recoveries-add", {
1009
+ method: "POST",
1010
+ body: JSON.stringify({
1011
+ code: getAccessToken(data.name),
1012
+ email,
1013
+ publicKeys: [
1014
+ ...data.owner.key_auths,
1015
+ ...data.active.key_auths,
1016
+ ...data.posting.key_auths,
1017
+ data.memo_key
1018
+ ]
1019
+ })
1020
+ });
1021
+ } else if (type === "key" && key) {
1022
+ return CONFIG.hiveClient.broadcast.sendOperations(
1023
+ [["change_recovery_account", operationBody]],
1024
+ key
1025
+ );
1026
+ } else if (type === "keychain") {
1027
+ return keychain_exports.broadcast(
1028
+ data.name,
1029
+ [["change_recovery_account", operationBody]],
1030
+ "Active"
1031
+ );
1032
+ } else {
1033
+ const params = {
1034
+ callback: `https://ecency.com/@${data.name}/permissions`
1035
+ };
1036
+ return hs.sendOperation(
1037
+ ["change_recovery_account", operationBody],
1038
+ params,
1039
+ () => {
1040
+ }
1041
+ );
1042
+ }
1043
+ },
1044
+ onError: options.onError,
1045
+ onSuccess: options.onSuccess
1046
+ });
1047
+ }
1048
+ function useAccountRevokeKey(username, options) {
1049
+ const { data: accountData } = useQuery(getAccountFullQueryOptions(username));
1050
+ return useMutation({
1051
+ mutationKey: ["accounts", "revoke-key", accountData?.name],
1052
+ mutationFn: async ({ currentKey, revokingKey }) => {
1053
+ if (!accountData) {
1054
+ throw new Error(
1055
+ "[SDK][Update password] \u2013 cannot update keys for anon user"
1056
+ );
1057
+ }
1058
+ const prepareAuth = (keyName) => {
1059
+ const auth = R.clone(accountData[keyName]);
1060
+ auth.key_auths = auth.key_auths.filter(
1061
+ ([key]) => key !== revokingKey.toString()
1062
+ );
1063
+ return auth;
1064
+ };
1065
+ return CONFIG.hiveClient.broadcast.updateAccount(
1066
+ {
1067
+ account: accountData.name,
1068
+ json_metadata: accountData.json_metadata,
1069
+ owner: prepareAuth("owner"),
1070
+ active: prepareAuth("active"),
1071
+ posting: prepareAuth("posting"),
1072
+ memo_key: accountData.memo_key
1073
+ },
1074
+ currentKey
1075
+ );
1076
+ },
1077
+ ...options
1078
+ });
1079
+ }
1080
+ function useSignOperationByKey(username) {
1081
+ return useMutation({
1082
+ mutationKey: ["operations", "sign", username],
1083
+ mutationFn: ({
1084
+ operation,
1085
+ keyOrSeed
1086
+ }) => {
1087
+ if (!username) {
1088
+ throw new Error("[Operations][Sign] \u2013 cannot sign op with anon user");
1089
+ }
1090
+ let privateKey;
1091
+ if (keyOrSeed.split(" ").length === 12) {
1092
+ privateKey = PrivateKey.fromLogin(username, keyOrSeed, "active");
1093
+ } else if (cryptoUtils.isWif(keyOrSeed)) {
1094
+ privateKey = PrivateKey.fromString(keyOrSeed);
1095
+ } else {
1096
+ privateKey = PrivateKey.from(keyOrSeed);
1097
+ }
1098
+ return CONFIG.hiveClient.broadcast.sendOperations(
1099
+ [operation],
1100
+ privateKey
1101
+ );
1102
+ }
1103
+ });
1104
+ }
1105
+ function useSignOperationByKeychain(username, keyType = "Active") {
1106
+ return useMutation({
1107
+ mutationKey: ["operations", "sign-keychain", username],
1108
+ mutationFn: ({ operation }) => {
1109
+ if (!username) {
1110
+ throw new Error(
1111
+ "[SDK][Keychain] \u2013\xA0cannot sign operation with anon user"
1112
+ );
1113
+ }
1114
+ return keychain_exports.broadcast(username, [operation], keyType);
1115
+ }
1116
+ });
1117
+ }
1118
+ function useSignOperationByHivesigner(callbackUri = "/") {
1119
+ return useMutation({
1120
+ mutationKey: ["operations", "sign-hivesigner", callbackUri],
1121
+ mutationFn: async ({ operation }) => {
1122
+ return hs.sendOperation(operation, { callback: callbackUri }, () => {
1123
+ });
1124
+ }
1125
+ });
1126
+ }
1127
+ function getChainPropertiesQueryOptions() {
1128
+ return queryOptions({
1129
+ queryKey: ["operations", "chain-properties"],
1130
+ queryFn: async () => {
1131
+ return await CONFIG.hiveClient.database.getChainProperties();
1132
+ }
1133
+ });
1134
+ }
1135
+ function getTrendingTagsQueryOptions(limit = 20) {
1136
+ return infiniteQueryOptions({
1137
+ queryKey: ["posts", "trending-tags"],
1138
+ queryFn: async ({ pageParam: { afterTag } }) => CONFIG.hiveClient.database.call("get_trending_tags", [afterTag, limit]).then(
1139
+ (tags) => tags.filter((x) => x.name !== "").filter((x) => !x.name.startsWith("hive-")).map((x) => x.name)
1140
+ ),
1141
+ initialPageParam: { afterTag: "" },
1142
+ getNextPageParam: (lastPage) => ({
1143
+ afterTag: lastPage?.[lastPage?.length - 1]
1144
+ }),
1145
+ staleTime: Infinity,
1146
+ refetchOnMount: true
1147
+ });
1148
+ }
1149
+ function getFragmentsQueryOptions(username) {
1150
+ return queryOptions({
1151
+ queryKey: ["posts", "fragments", username],
1152
+ queryFn: async () => {
1153
+ const fetchApi = getBoundFetch();
1154
+ const response = await fetchApi(
1155
+ CONFIG.privateApiHost + "/private-api/fragments",
1156
+ {
1157
+ method: "POST",
1158
+ body: JSON.stringify({
1159
+ code: getAccessToken(username)
1160
+ }),
1161
+ headers: {
1162
+ "Content-Type": "application/json"
1163
+ }
1164
+ }
1165
+ );
1166
+ return response.json();
1167
+ },
1168
+ enabled: !!username
1169
+ });
1170
+ }
1171
+ function getPromotedPostsQuery(type = "feed") {
1172
+ return queryOptions({
1173
+ queryKey: ["posts", "promoted", type],
1174
+ queryFn: async () => {
1175
+ const url = new URL(
1176
+ CONFIG.privateApiHost + "/private-api/promoted-entries"
1177
+ );
1178
+ if (type === "waves") {
1179
+ url.searchParams.append("short_content", "1");
1180
+ }
1181
+ const fetchApi = getBoundFetch();
1182
+ const response = await fetchApi(url.toString(), {
1183
+ method: "GET",
1184
+ headers: {
1185
+ "Content-Type": "application/json"
1186
+ }
1187
+ });
1188
+ const data = await response.json();
1189
+ return data;
1190
+ }
1191
+ });
1192
+ }
1193
+ function useAddFragment(username) {
1194
+ return useMutation({
1195
+ mutationKey: ["posts", "add-fragment", username],
1196
+ mutationFn: async ({ title, body }) => {
1197
+ const fetchApi = getBoundFetch();
1198
+ const response = await fetchApi(
1199
+ CONFIG.privateApiHost + "/private-api/fragments-add",
1200
+ {
1201
+ method: "POST",
1202
+ body: JSON.stringify({
1203
+ code: getAccessToken(username),
1204
+ title,
1205
+ body
1206
+ }),
1207
+ headers: {
1208
+ "Content-Type": "application/json"
1209
+ }
1210
+ }
1211
+ );
1212
+ return response.json();
1213
+ },
1214
+ onSuccess(response) {
1215
+ getQueryClient().setQueryData(
1216
+ getFragmentsQueryOptions(username).queryKey,
1217
+ (data) => [response, ...data ?? []]
1218
+ );
1219
+ }
1220
+ });
1221
+ }
1222
+ function useEditFragment(username, fragmentId) {
1223
+ return useMutation({
1224
+ mutationKey: ["posts", "edit-fragment", username, fragmentId],
1225
+ mutationFn: async ({ title, body }) => {
1226
+ const fetchApi = getBoundFetch();
1227
+ const response = await fetchApi(
1228
+ CONFIG.privateApiHost + "/private-api/fragments-update",
1229
+ {
1230
+ method: "POST",
1231
+ body: JSON.stringify({
1232
+ code: getAccessToken(username),
1233
+ id: fragmentId,
1234
+ title,
1235
+ body
1236
+ }),
1237
+ headers: {
1238
+ "Content-Type": "application/json"
1239
+ }
1240
+ }
1241
+ );
1242
+ return response.json();
1243
+ },
1244
+ onSuccess(response) {
1245
+ getQueryClient().setQueryData(
1246
+ getFragmentsQueryOptions(username).queryKey,
1247
+ (data) => {
1248
+ if (!data) {
1249
+ return [];
1250
+ }
1251
+ const index = data.findIndex(({ id }) => id === fragmentId);
1252
+ if (index >= 0) {
1253
+ data[index] = response;
1254
+ }
1255
+ return [...data];
1256
+ }
1257
+ );
1258
+ }
1259
+ });
1260
+ }
1261
+ function useRemoveFragment(username, fragmentId) {
1262
+ return useMutation({
1263
+ mutationKey: ["posts", "remove-fragment", username],
1264
+ mutationFn: async () => {
1265
+ const fetchApi = getBoundFetch();
1266
+ return fetchApi(CONFIG.privateApiHost + "/private-api/fragments-delete", {
1267
+ method: "POST",
1268
+ body: JSON.stringify({
1269
+ code: getAccessToken(username),
1270
+ id: fragmentId
1271
+ }),
1272
+ headers: {
1273
+ "Content-Type": "application/json"
1274
+ }
1275
+ });
1276
+ },
1277
+ onSuccess() {
1278
+ getQueryClient().setQueryData(
1279
+ getFragmentsQueryOptions(username).queryKey,
1280
+ (data) => [...data ?? []].filter(({ id }) => id !== fragmentId)
1281
+ );
1282
+ }
1283
+ });
1284
+ }
1285
+
1286
+ // src/modules/analytics/mutations/index.ts
1287
+ var mutations_exports = {};
1288
+ __export(mutations_exports, {
1289
+ useRecordActivity: () => useRecordActivity
1290
+ });
1291
+ function useRecordActivity(username, activityType) {
1292
+ return useMutation({
1293
+ mutationKey: ["analytics", activityType],
1294
+ mutationFn: async () => {
1295
+ if (!activityType) {
1296
+ throw new Error("[SDK][Analytics] \u2013 no activity type provided");
1297
+ }
1298
+ const fetchApi = getBoundFetch();
1299
+ await fetchApi(CONFIG.plausibleHost + "/api/event", {
1300
+ method: "POST",
1301
+ headers: {
1302
+ "Content-Type": "application/json"
1303
+ },
1304
+ body: JSON.stringify({
1305
+ name: activityType,
1306
+ url: window.location.href,
1307
+ domain: window.location.host,
1308
+ props: {
1309
+ username
1310
+ }
1311
+ })
1312
+ });
1313
+ }
1314
+ });
1315
+ }
1316
+
1317
+ // src/modules/integrations/3speak/queries/index.ts
1318
+ var queries_exports2 = {};
1319
+ __export(queries_exports2, {
1320
+ getAccountTokenQueryOptions: () => getAccountTokenQueryOptions,
1321
+ getAccountVideosQueryOptions: () => getAccountVideosQueryOptions
1322
+ });
1323
+
1324
+ // src/modules/integrations/hivesigner/queries/index.ts
1325
+ var queries_exports = {};
1326
+ __export(queries_exports, {
1327
+ getDecodeMemoQueryOptions: () => getDecodeMemoQueryOptions
1328
+ });
1329
+ function getDecodeMemoQueryOptions(username, memo) {
1330
+ return queryOptions({
1331
+ queryKey: ["integrations", "hivesigner", "decode-memo", username],
1332
+ queryFn: async () => {
1333
+ const accessToken = getAccessToken(username);
1334
+ if (accessToken) {
1335
+ const hsClient = new hs.Client({
1336
+ accessToken
1337
+ });
1338
+ return hsClient.decode(memo);
1339
+ }
1340
+ }
1341
+ });
1342
+ }
1343
+
1344
+ // src/modules/integrations/hivesigner/index.ts
1345
+ var HiveSignerIntegration = {
1346
+ queries: queries_exports
1347
+ };
1348
+
1349
+ // src/modules/integrations/3speak/queries/get-account-token-query-options.ts
1350
+ function getAccountTokenQueryOptions(username) {
1351
+ return queryOptions({
1352
+ queryKey: ["integrations", "3speak", "authenticate", username],
1353
+ enabled: !!username,
1354
+ queryFn: async () => {
1355
+ if (!username) {
1356
+ throw new Error("[SDK][Integrations][3Speak] \u2013\xA0anon user");
1357
+ }
1358
+ const fetchApi = getBoundFetch();
1359
+ const response = await fetchApi(
1360
+ `https://studio.3speak.tv/mobile/login?username=${username}&hivesigner=true`,
1361
+ {
1362
+ headers: {
1363
+ "Content-Type": "application/json"
1364
+ }
1365
+ }
1366
+ );
1367
+ const memoQueryOptions = HiveSignerIntegration.queries.getDecodeMemoQueryOptions(
1368
+ username,
1369
+ (await response.json()).memo
1370
+ );
1371
+ await getQueryClient().prefetchQuery(memoQueryOptions);
1372
+ const { memoDecoded } = getQueryClient().getQueryData(
1373
+ memoQueryOptions.queryKey
1374
+ );
1375
+ return memoDecoded.replace("#", "");
1376
+ }
1377
+ });
1378
+ }
1379
+ function getAccountVideosQueryOptions(username) {
1380
+ return queryOptions({
1381
+ queryKey: ["integrations", "3speak", "videos", username],
1382
+ enabled: !!username,
1383
+ queryFn: async () => {
1384
+ await getQueryClient().prefetchQuery(
1385
+ getAccountTokenQueryOptions(username)
1386
+ );
1387
+ const token = getQueryClient().getQueryData(
1388
+ getAccountTokenQueryOptions(username).queryKey
1389
+ );
1390
+ const fetchApi = getBoundFetch();
1391
+ const response = await fetchApi(
1392
+ `https://studio.3speak.tv/mobile/api/my-videos`,
1393
+ {
1394
+ headers: {
1395
+ "Content-Type": "application/json",
1396
+ Authorization: `Bearer ${token}`
1397
+ }
1398
+ }
1399
+ );
1400
+ return await response.json();
1401
+ }
1402
+ });
1403
+ }
1404
+
1405
+ // src/modules/integrations/3speak/index.ts
1406
+ var ThreeSpeakIntegration = {
1407
+ queries: queries_exports2
1408
+ };
1409
+ function getHivePoshLinksQueryOptions(username) {
1410
+ return queryOptions({
1411
+ queryKey: ["integrations", "hiveposh", "links", username],
1412
+ queryFn: async () => {
1413
+ const fetchApi = getBoundFetch();
1414
+ const response = await fetchApi(
1415
+ `https://hiveposh.com/api/v0/linked-accounts/${username}`,
1416
+ {
1417
+ headers: {
1418
+ "Content-Type": "application/json"
1419
+ }
1420
+ }
1421
+ );
1422
+ const data = await response.json();
1423
+ return {
1424
+ twitter: {
1425
+ username: data.twitter_username,
1426
+ profile: data.twitter_profile
1427
+ },
1428
+ reddit: {
1429
+ username: data.reddit_username,
1430
+ profile: data.reddit_profile
1431
+ }
1432
+ };
1433
+ }
1434
+ });
1435
+ }
1436
+ function getStatsQueryOptions({
1437
+ url,
1438
+ dimensions = [],
1439
+ metrics = ["visitors", "pageviews", "visit_duration"],
1440
+ enabled = true
1441
+ }) {
1442
+ return queryOptions({
1443
+ queryKey: ["integrations", "plausible", url, dimensions, metrics],
1444
+ queryFn: async () => {
1445
+ const fetchApi = getBoundFetch();
1446
+ const response = await fetchApi(`https://ecency.com/api/stats`, {
1447
+ method: "POST",
1448
+ body: JSON.stringify({
1449
+ metrics,
1450
+ url: encodeURIComponent(url),
1451
+ dimensions
1452
+ }),
1453
+ headers: {
1454
+ "Content-Type": "application/json"
1455
+ }
1456
+ });
1457
+ return await response.json();
1458
+ },
1459
+ enabled: !!url && enabled
1460
+ });
1461
+ }
1462
+ function getRcStatsQueryOptions() {
1463
+ return queryOptions({
1464
+ queryKey: ["resource-credits", "stats"],
1465
+ queryFn: async () => {
1466
+ const response = await CONFIG.hiveClient.call(
1467
+ "rc_api",
1468
+ "get_rc_stats",
1469
+ {}
1470
+ );
1471
+ return response.rc_stats;
1472
+ }
1473
+ });
1474
+ }
1475
+ function getAccountRcQueryOptions(username) {
1476
+ return queryOptions({
1477
+ queryKey: ["resource-credits", "account", username],
1478
+ queryFn: async () => {
1479
+ const rcClient = new RCAPI(CONFIG.hiveClient);
1480
+ return rcClient.findRCAccounts([username]);
1481
+ },
1482
+ enabled: !!username
1483
+ });
1484
+ }
1485
+ function getGameStatusCheckQueryOptions(username, gameType) {
1486
+ return queryOptions({
1487
+ queryKey: ["games", "status-check", gameType, username],
1488
+ enabled: !!username,
1489
+ queryFn: async () => {
1490
+ if (!username) {
1491
+ throw new Error("[SDK][Games] \u2013 anon user in status check");
1492
+ }
1493
+ const fetchApi = getBoundFetch();
1494
+ const response = await fetchApi(
1495
+ CONFIG.privateApiHost + "/private-api/get-game",
1496
+ {
1497
+ method: "POST",
1498
+ body: JSON.stringify({
1499
+ game_type: gameType,
1500
+ code: getAccessToken(username)
1501
+ }),
1502
+ headers: {
1503
+ "Content-Type": "application/json"
1504
+ }
1505
+ }
1506
+ );
1507
+ return await response.json();
1508
+ }
1509
+ });
1510
+ }
1511
+ function useGameClaim(username, gameType, key) {
1512
+ const { mutateAsync: recordActivity } = useRecordActivity(
1513
+ username,
1514
+ "spin-rolled"
1515
+ );
1516
+ return useMutation({
1517
+ mutationKey: ["games", "post", gameType, username],
1518
+ mutationFn: async () => {
1519
+ if (!username) {
1520
+ throw new Error("[SDK][Games] \u2013 anon user in game post");
1521
+ }
1522
+ const fetchApi = getBoundFetch();
1523
+ const response = await fetchApi(
1524
+ CONFIG.privateApiHost + "/private-api/post-game",
1525
+ {
1526
+ method: "POST",
1527
+ body: JSON.stringify({
1528
+ game_type: gameType,
1529
+ code: getAccessToken(username),
1530
+ key
1531
+ }),
1532
+ headers: {
1533
+ "Content-Type": "application/json"
1534
+ }
1535
+ }
1536
+ );
1537
+ return await response.json();
1538
+ },
1539
+ onSuccess() {
1540
+ recordActivity();
1541
+ }
1542
+ });
1543
+ }
1544
+ function getCommunitiesQueryOptions(sort, query, limit = 100, observer = void 0, enabled = true) {
1545
+ return queryOptions({
1546
+ queryKey: ["communities", "list", sort, query, limit],
1547
+ enabled,
1548
+ queryFn: async () => {
1549
+ const response = await CONFIG.hiveClient.call(
1550
+ "bridge",
1551
+ "list_communities",
1552
+ {
1553
+ last: "",
1554
+ limit,
1555
+ sort: sort === "hot" ? "rank" : sort,
1556
+ query: query ? query : null,
1557
+ observer
1558
+ }
1559
+ );
1560
+ return response ? sort === "hot" ? response.sort(() => Math.random() - 0.5) : response : [];
1561
+ }
1562
+ });
1563
+ }
1564
+ function getCommunityContextQueryOptions(username, communityName) {
1565
+ return queryOptions({
1566
+ queryKey: ["community", "context", username, communityName],
1567
+ enabled: !!username && !!communityName,
1568
+ queryFn: async () => {
1569
+ const response = await CONFIG.hiveClient.call(
1570
+ "bridge",
1571
+ "get_community_context",
1572
+ {
1573
+ account: username,
1574
+ name: communityName
1575
+ }
1576
+ );
1577
+ return {
1578
+ role: response?.role ?? "guest",
1579
+ subscribed: response?.subscribed ?? false
1580
+ };
1581
+ }
1582
+ });
1583
+ }
1584
+
1585
+ // src/modules/communities/types/community.ts
1586
+ var ROLES = /* @__PURE__ */ ((ROLES2) => {
1587
+ ROLES2["OWNER"] = "owner";
1588
+ ROLES2["ADMIN"] = "admin";
1589
+ ROLES2["MOD"] = "mod";
1590
+ ROLES2["MEMBER"] = "member";
1591
+ ROLES2["GUEST"] = "guest";
1592
+ ROLES2["MUTED"] = "muted";
1593
+ return ROLES2;
1594
+ })(ROLES || {});
1595
+ var roleMap = {
1596
+ ["owner" /* OWNER */]: [
1597
+ "admin" /* ADMIN */,
1598
+ "mod" /* MOD */,
1599
+ "member" /* MEMBER */,
1600
+ "guest" /* GUEST */,
1601
+ "muted" /* MUTED */
1602
+ ],
1603
+ ["admin" /* ADMIN */]: ["mod" /* MOD */, "member" /* MEMBER */, "guest" /* GUEST */, "muted" /* MUTED */],
1604
+ ["mod" /* MOD */]: ["member" /* MEMBER */, "guest" /* GUEST */, "muted" /* MUTED */]
1605
+ };
1606
+
1607
+ // src/modules/communities/utils/index.ts
1608
+ function getCommunityType(name, type_id) {
1609
+ if (name.startsWith("hive-3") || type_id === 3) return "Council";
1610
+ if (name.startsWith("hive-2") || type_id === 2) return "Journal";
1611
+ return "Topic";
1612
+ }
1613
+ function getCommunityPermissions({
1614
+ communityType,
1615
+ userRole,
1616
+ subscribed
1617
+ }) {
1618
+ const canPost = (() => {
1619
+ if (userRole === "muted" /* MUTED */) return false;
1620
+ if (communityType === "Topic") return true;
1621
+ return ["owner" /* OWNER */, "admin" /* ADMIN */, "mod" /* MOD */, "member" /* MEMBER */].includes(
1622
+ userRole
1623
+ );
1624
+ })();
1625
+ const canComment = (() => {
1626
+ if (userRole === "muted" /* MUTED */) return false;
1627
+ switch (communityType) {
1628
+ case "Topic":
1629
+ return true;
1630
+ case "Journal":
1631
+ return userRole !== "guest" /* GUEST */ || subscribed;
1632
+ case "Council":
1633
+ return canPost;
1634
+ }
1635
+ })();
1636
+ const isModerator = ["owner" /* OWNER */, "admin" /* ADMIN */, "mod" /* MOD */].includes(userRole);
1637
+ return {
1638
+ canPost,
1639
+ canComment,
1640
+ isModerator
1641
+ };
1642
+ }
1643
+
1644
+ export { CONFIG, ConfigManager, mutations_exports as EcencyAnalytics, EcencyQueriesManager, HiveSignerIntegration, keychain_exports as Keychain, NaiMap, ROLES, Symbol2 as Symbol, ThreeSpeakIntegration, broadcastJson, checkUsernameWalletsPendingQueryOptions, decodeObj, dedupeAndSortKeyAuths, encodeObj, getAccessToken, getAccountFullQueryOptions, getAccountPendingRecoveryQueryOptions, getAccountRcQueryOptions, getAccountRecoveriesQueryOptions, getAccountSubscriptionsQueryOptions, getActiveAccountBookmarksQueryOptions, getActiveAccountFavouritesQueryOptions, getBoundFetch, getChainPropertiesQueryOptions, getCommunitiesQueryOptions, getCommunityContextQueryOptions, getCommunityPermissions, getCommunityType, getDynamicPropsQueryOptions, getFragmentsQueryOptions, getGameStatusCheckQueryOptions, getHivePoshLinksQueryOptions, getLoginType, getPostingKey, getPromotedPostsQuery, getQueryClient, getRcStatsQueryOptions, getRefreshToken, getRelationshipBetweenAccountsQueryOptions, getSearchAccountsByUsernameQueryOptions, getStatsQueryOptions, getTrendingTagsQueryOptions, getUser, makeQueryClient, parseAsset, roleMap, useAccountFavouriteAdd, useAccountFavouriteDelete, useAccountRelationsUpdate, useAccountRevokeKey, useAccountRevokePosting, useAccountUpdate, useAccountUpdateKeyAuths, useAccountUpdatePassword, useAccountUpdateRecovery, useAddFragment, useBookmarkAdd, useBookmarkDelete, useBroadcastMutation, useEditFragment, useGameClaim, useRemoveFragment, useSignOperationByHivesigner, useSignOperationByKey, useSignOperationByKeychain };
1645
+ //# sourceMappingURL=index.js.map
1646
+ //# sourceMappingURL=index.js.map