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