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