@lukso/transaction-view-headless 0.2.2-dev.a8c9315

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/.turbo/turbo-build.log +51 -0
  2. package/CHANGELOG.md +88 -0
  3. package/COMPONENT_ARCHITECTURE.md +190 -0
  4. package/COMPONENT_CONVERSION_ANALYSIS.md +371 -0
  5. package/CONTEXT_VARIANT_GUIDE.md +425 -0
  6. package/LAZY_LOADING_GUIDE.md +534 -0
  7. package/LICENSE +201 -0
  8. package/PLAYBACK_EXAMPLES.md +658 -0
  9. package/PLAYBACK_GUIDE.md +402 -0
  10. package/README.md +43 -0
  11. package/REGISTRY_SUMMARY.md +638 -0
  12. package/SUFFERING_ECONOMICS.md +346 -0
  13. package/SUFFERING_ECONOMICS.zip +0 -0
  14. package/VIEW_REGISTRATION_GUIDE.md +795 -0
  15. package/dist/composables/index.cjs +1321 -0
  16. package/dist/composables/index.cjs.map +1 -0
  17. package/dist/composables/index.d.cts +6 -0
  18. package/dist/composables/index.d.ts +6 -0
  19. package/dist/composables/index.js +1276 -0
  20. package/dist/composables/index.js.map +1 -0
  21. package/dist/index-CMLU1hKL.d.ts +374 -0
  22. package/dist/index-CSDjhiKV.d.cts +374 -0
  23. package/dist/index.cjs +1534 -0
  24. package/dist/index.cjs.map +1 -0
  25. package/dist/index.d.cts +93 -0
  26. package/dist/index.d.ts +93 -0
  27. package/dist/index.js +1463 -0
  28. package/dist/index.js.map +1 -0
  29. package/dist/registry/index.cjs +522 -0
  30. package/dist/registry/index.cjs.map +1 -0
  31. package/dist/registry/index.d.cts +46 -0
  32. package/dist/registry/index.d.ts +46 -0
  33. package/dist/registry/index.js +487 -0
  34. package/dist/registry/index.js.map +1 -0
  35. package/dist/types/index.cjs +19 -0
  36. package/dist/types/index.cjs.map +1 -0
  37. package/dist/types/index.d.cts +203 -0
  38. package/dist/types/index.d.ts +203 -0
  39. package/dist/types/index.js +1 -0
  40. package/dist/types/index.js.map +1 -0
  41. package/dist/utils/index.cjs +217 -0
  42. package/dist/utils/index.cjs.map +1 -0
  43. package/dist/utils/index.d.cts +47 -0
  44. package/dist/utils/index.d.ts +47 -0
  45. package/dist/utils/index.js +188 -0
  46. package/dist/utils/index.js.map +1 -0
  47. package/dist/view-loader-dD86QAlQ.d.cts +121 -0
  48. package/dist/view-loader-ii8AxiQR.d.ts +121 -0
  49. package/package.json +64 -0
  50. package/publish.log +0 -0
  51. package/src/composables/index.ts +59 -0
  52. package/src/composables/use-image-loader.ts +315 -0
  53. package/src/composables/use-transaction-playback.ts +396 -0
  54. package/src/composables/use-transaction-view.ts +309 -0
  55. package/src/config/lukso-config.ts +171 -0
  56. package/src/examples/context-aware-views.ts +300 -0
  57. package/src/examples/example-views.ts +197 -0
  58. package/src/examples/lit-plus-rn-strategy.ts +448 -0
  59. package/src/examples/lsp7-custom-matcher-examples.ts +174 -0
  60. package/src/examples/opt-in-context-examples.ts +372 -0
  61. package/src/examples/optimized-view-definitions.ts +408 -0
  62. package/src/examples/vue-to-lit-compilation.ts +358 -0
  63. package/src/hooks/useAddressQuery.ts +135 -0
  64. package/src/hooks/useAddressResolution.ts +437 -0
  65. package/src/index.ts +36 -0
  66. package/src/registry/index.ts +13 -0
  67. package/src/registry/view-loader.ts +305 -0
  68. package/src/registry/view-registry.ts +135 -0
  69. package/src/types/index.ts +16 -0
  70. package/src/types/view-contexts.ts +72 -0
  71. package/src/types/view-matching.ts +173 -0
  72. package/src/utils/context-matcher.ts +165 -0
  73. package/src/utils/index.ts +5 -0
  74. package/src/utils/view-matcher.ts +338 -0
  75. package/tsconfig.json +20 -0
  76. package/tsup.config.ts +34 -0
@@ -0,0 +1,1321 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __esm = (fn, res) => function __init() {
9
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
10
+ };
11
+ var __export = (target, all) => {
12
+ for (var name in all)
13
+ __defProp(target, name, { get: all[name], enumerable: true });
14
+ };
15
+ var __copyProps = (to, from, except, desc) => {
16
+ if (from && typeof from === "object" || typeof from === "function") {
17
+ for (let key of __getOwnPropNames(from))
18
+ if (!__hasOwnProp.call(to, key) && key !== except)
19
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
20
+ }
21
+ return to;
22
+ };
23
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
24
+ // If the importer is in node compatibility mode or this is not an ESM
25
+ // file that has been converted to a CommonJS file using a Babel-
26
+ // compatible transform (i.e. "__esModule" has not been set), then set
27
+ // "default" to the CommonJS "module.exports" for node compatibility.
28
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
29
+ mod
30
+ ));
31
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
32
+
33
+ // src/config/lukso-config.ts
34
+ function setLuksoConfig(config) {
35
+ globalConfig = { ...globalConfig, ...config };
36
+ clearAddressCache();
37
+ if (typeof window !== "undefined" && window.console) {
38
+ console.log("\u{1F310} LUKSO Config Updated:", {
39
+ chainId: globalConfig.chainId,
40
+ network: globalConfig.chainId === 42 ? "mainnet" : globalConfig.chainId === 4201 ? "testnet" : "custom",
41
+ addressResolution: globalConfig.enableAddressResolution
42
+ });
43
+ }
44
+ }
45
+ function getLuksoConfig() {
46
+ return { ...globalConfig };
47
+ }
48
+ function useLuksoMainnet() {
49
+ setLuksoConfig({
50
+ chainId: 42,
51
+ rpcUrl: "https://rpc.lukso.network"
52
+ });
53
+ }
54
+ function useLuksoTestnet() {
55
+ setLuksoConfig({
56
+ chainId: 4201,
57
+ rpcUrl: "https://rpc.testnet.lukso.network"
58
+ });
59
+ }
60
+ function cacheAddress(address, data) {
61
+ if (!globalConfig.enableAddressResolution) return;
62
+ const key = address.toLowerCase();
63
+ addressCache.set(key, data);
64
+ cacheTimestamps.set(key, Date.now());
65
+ }
66
+ function getCachedAddress(address) {
67
+ if (!globalConfig.enableAddressResolution) return null;
68
+ const key = address.toLowerCase();
69
+ const data = addressCache.get(key);
70
+ const timestamp = cacheTimestamps.get(key);
71
+ if (!data || !timestamp) return null;
72
+ if (Date.now() - timestamp > globalConfig.cacheDuration) {
73
+ addressCache.delete(key);
74
+ cacheTimestamps.delete(key);
75
+ return null;
76
+ }
77
+ return data;
78
+ }
79
+ function clearAddressCache() {
80
+ addressCache.clear();
81
+ cacheTimestamps.clear();
82
+ }
83
+ function isAddressResolutionEnabled() {
84
+ return globalConfig.enableAddressResolution ?? true;
85
+ }
86
+ async function initializeChainSignal() {
87
+ if (currentChainSignal.value) return;
88
+ try {
89
+ const { lukso, luksoTestnet } = await import("viem/chains");
90
+ const config = getLuksoConfig();
91
+ const chain = config.chainId === 42 ? lukso : luksoTestnet;
92
+ currentChainSignal.value = chain;
93
+ } catch (error) {
94
+ console.warn("Failed to initialize chain signal:", error);
95
+ }
96
+ }
97
+ var import_signals_core, DEFAULT_CONFIG, globalConfig, addressCache, cacheTimestamps, currentChainSignal;
98
+ var init_lukso_config = __esm({
99
+ "src/config/lukso-config.ts"() {
100
+ "use strict";
101
+ import_signals_core = require("@preact/signals-core");
102
+ DEFAULT_CONFIG = {
103
+ chainId: 42,
104
+ // LUKSO mainnet
105
+ rpcUrl: "https://rpc.lukso.network",
106
+ graphqlEndpoint: "/api/graphql",
107
+ // Use local API proxy
108
+ ipfsGateway: "https://api.universalprofile.cloud/ipfs",
109
+ enableAddressResolution: true,
110
+ cacheDuration: 5 * 60 * 1e3
111
+ // 5 minutes
112
+ };
113
+ globalConfig = { ...DEFAULT_CONFIG };
114
+ addressCache = /* @__PURE__ */ new Map();
115
+ cacheTimestamps = /* @__PURE__ */ new Map();
116
+ currentChainSignal = (0, import_signals_core.signal)(null);
117
+ }
118
+ });
119
+
120
+ // src/hooks/useAddressResolution.ts
121
+ var useAddressResolution_exports = {};
122
+ __export(useAddressResolution_exports, {
123
+ createAddressResolutionState: () => createAddressResolutionState,
124
+ resolveAddress: () => resolveAddress,
125
+ resolveAddressWithState: () => resolveAddressWithState,
126
+ resolveAddresses: () => resolveAddresses
127
+ });
128
+ function truncateAddress(address, prefixLength = 5, suffixLength = 4) {
129
+ if (!address || address.length <= prefixLength + suffixLength + 2) {
130
+ return address;
131
+ }
132
+ const prefix = address.slice(0, 2 + prefixLength);
133
+ const suffix = address.slice(-suffixLength);
134
+ return `${prefix}...${suffix}`;
135
+ }
136
+ function getBatchState(chainId) {
137
+ let state = chainBatchStates.get(chainId);
138
+ if (!state) {
139
+ state = {
140
+ batchTimeout: null,
141
+ batchQueue: /* @__PURE__ */ new Set(),
142
+ batchResolvers: /* @__PURE__ */ new Map(),
143
+ pendingResolutions: /* @__PURE__ */ new Map(),
144
+ isProcessing: false
145
+ };
146
+ chainBatchStates.set(chainId, state);
147
+ }
148
+ return state;
149
+ }
150
+ async function processBatch(chainId) {
151
+ const state = getBatchState(chainId);
152
+ if (state.batchQueue.size === 0 || state.isProcessing) return;
153
+ state.isProcessing = true;
154
+ const addresses = Array.from(state.batchQueue);
155
+ state.batchQueue.clear();
156
+ try {
157
+ const { fetchMultipleAddresses: fetchMultipleAddresses2, getGraphQLEndpoint: getGraphQLEndpoint2 } = await import("@lukso/transaction-decoder");
158
+ const { lukso, luksoTestnet } = await import("viem/chains");
159
+ const chain = chainId === 42 ? lukso : luksoTestnet;
160
+ const graphqlEndpoint = getGraphQLEndpoint2(chain);
161
+ const dataKeys = addresses;
162
+ const results = await fetchMultipleAddresses2(dataKeys, graphqlEndpoint);
163
+ for (const address of addresses) {
164
+ const normalizedAddress = address.toLowerCase();
165
+ const enhanced = results.get(normalizedAddress);
166
+ let result;
167
+ if (enhanced) {
168
+ const profileImages = enhanced.profileImages;
169
+ const resolvedData = {
170
+ ...enhanced,
171
+ hasProfile: !!(enhanced.name || profileImages?.length)
172
+ };
173
+ cacheAddressForChain(address, resolvedData, chainId);
174
+ result = {
175
+ ...resolvedData,
176
+ address,
177
+ truncatedAddress: truncateAddress(address)
178
+ };
179
+ } else {
180
+ result = {
181
+ address,
182
+ truncatedAddress: truncateAddress(address),
183
+ hasProfile: false
184
+ };
185
+ cacheAddressForChain(address, { hasProfile: false }, chainId);
186
+ }
187
+ const resolver = state.batchResolvers.get(normalizedAddress);
188
+ if (resolver) {
189
+ resolver(result);
190
+ state.batchResolvers.delete(normalizedAddress);
191
+ }
192
+ }
193
+ } catch (error) {
194
+ console.warn(
195
+ "Batch address resolution failed (falling back to API):",
196
+ error
197
+ );
198
+ try {
199
+ const response = await fetch("/api/resolveAddresses", {
200
+ method: "POST",
201
+ headers: { "Content-Type": "application/json" },
202
+ body: JSON.stringify({
203
+ addresses,
204
+ chainId
205
+ })
206
+ });
207
+ if (!response.ok) {
208
+ throw new Error(`API fallback failed: ${response.status}`);
209
+ }
210
+ const data = await response.json();
211
+ for (const address of addresses) {
212
+ const normalizedAddress = address.toLowerCase();
213
+ const resolved = data.resolved?.[normalizedAddress];
214
+ let result;
215
+ if (resolved) {
216
+ const resolvedData = {
217
+ name: resolved.name,
218
+ profileImage: resolved.profileImage,
219
+ hasProfile: !!(resolved.name || resolved.profileImage)
220
+ };
221
+ cacheAddressForChain(address, resolvedData, chainId);
222
+ result = {
223
+ address,
224
+ truncatedAddress: truncateAddress(address),
225
+ ...resolvedData
226
+ };
227
+ } else {
228
+ result = {
229
+ address,
230
+ truncatedAddress: truncateAddress(address),
231
+ hasProfile: false
232
+ };
233
+ cacheAddressForChain(address, { hasProfile: false }, chainId);
234
+ }
235
+ const resolver = state.batchResolvers.get(normalizedAddress);
236
+ if (resolver) {
237
+ resolver(result);
238
+ state.batchResolvers.delete(normalizedAddress);
239
+ }
240
+ }
241
+ } catch (fallbackError) {
242
+ console.warn("Both GraphQL and API resolution failed:", fallbackError);
243
+ for (const address of addresses) {
244
+ const fallback = {
245
+ address,
246
+ truncatedAddress: truncateAddress(address),
247
+ hasProfile: false
248
+ };
249
+ cacheAddressForChain(address, { hasProfile: false }, chainId);
250
+ const resolver = state.batchResolvers.get(address.toLowerCase());
251
+ if (resolver) {
252
+ resolver(fallback);
253
+ state.batchResolvers.delete(address.toLowerCase());
254
+ }
255
+ }
256
+ }
257
+ } finally {
258
+ state.isProcessing = false;
259
+ }
260
+ }
261
+ function cacheAddressForChain(address, data, chainId) {
262
+ const key = `${address.toLowerCase()}:${chainId}`;
263
+ cacheAddress(key, data);
264
+ }
265
+ function getCachedAddressForChain(address, chainId) {
266
+ const key = `${address.toLowerCase()}:${chainId}`;
267
+ return getCachedAddress(key);
268
+ }
269
+ async function getEffectiveChainId(chainId) {
270
+ if (chainId !== void 0) return chainId;
271
+ await initializeChainSignal();
272
+ const currentChain = currentChainSignal.value;
273
+ if (currentChain) {
274
+ return currentChain.id;
275
+ }
276
+ const config = getLuksoConfig();
277
+ return config.chainId;
278
+ }
279
+ async function resolveAddress(address, chainId) {
280
+ const effectiveChainId = await getEffectiveChainId(chainId);
281
+ const normalizedAddress = address.toLowerCase();
282
+ const fallback = {
283
+ address,
284
+ truncatedAddress: truncateAddress(address),
285
+ hasProfile: false
286
+ };
287
+ if (!isAddressResolutionEnabled()) {
288
+ return fallback;
289
+ }
290
+ const cached = getCachedAddressForChain(address, effectiveChainId);
291
+ if (cached) {
292
+ return {
293
+ ...fallback,
294
+ ...cached,
295
+ hasProfile: !!(cached.name || cached.profileImage)
296
+ };
297
+ }
298
+ const state = getBatchState(effectiveChainId);
299
+ const existingPromise = state.pendingResolutions.get(normalizedAddress);
300
+ if (existingPromise) {
301
+ return existingPromise;
302
+ }
303
+ if (state.batchQueue.has(normalizedAddress)) {
304
+ return Promise.resolve(fallback);
305
+ }
306
+ const resolutionPromise = new Promise((resolve) => {
307
+ state.batchQueue.add(normalizedAddress);
308
+ state.batchResolvers.set(normalizedAddress, resolve);
309
+ if (state.batchTimeout) {
310
+ clearTimeout(state.batchTimeout);
311
+ }
312
+ if (!state.isProcessing) {
313
+ state.batchTimeout = setTimeout(() => {
314
+ state.batchTimeout = null;
315
+ processBatch(effectiveChainId);
316
+ }, BATCH_DELAY);
317
+ if (state.batchQueue.size >= BATCH_SIZE) {
318
+ if (state.batchTimeout) {
319
+ clearTimeout(state.batchTimeout);
320
+ state.batchTimeout = null;
321
+ }
322
+ processBatch(effectiveChainId);
323
+ }
324
+ }
325
+ });
326
+ state.pendingResolutions.set(normalizedAddress, resolutionPromise);
327
+ resolutionPromise.finally(() => {
328
+ state.pendingResolutions.delete(normalizedAddress);
329
+ });
330
+ return resolutionPromise;
331
+ }
332
+ async function resolveAddresses(addresses, chainId) {
333
+ const results = /* @__PURE__ */ new Map();
334
+ const resolutionPromises = addresses.map(async (address) => {
335
+ const resolved = await resolveAddress(address, chainId);
336
+ results.set(address.toLowerCase(), resolved);
337
+ });
338
+ await Promise.all(resolutionPromises);
339
+ return results;
340
+ }
341
+ function createAddressResolutionState() {
342
+ return {
343
+ resolved: null,
344
+ loading: false,
345
+ error: null
346
+ };
347
+ }
348
+ async function resolveAddressWithState(address, _state, updateCallback, chainId) {
349
+ updateCallback({ loading: true, error: null });
350
+ try {
351
+ const resolved = await resolveAddress(address, chainId);
352
+ updateCallback({
353
+ resolved,
354
+ loading: false,
355
+ error: null
356
+ });
357
+ } catch (error) {
358
+ updateCallback({
359
+ loading: false,
360
+ error: error instanceof Error ? error.message : "Resolution failed"
361
+ });
362
+ }
363
+ }
364
+ var chainBatchStates, BATCH_DELAY, BATCH_SIZE;
365
+ var init_useAddressResolution = __esm({
366
+ "src/hooks/useAddressResolution.ts"() {
367
+ "use strict";
368
+ init_lukso_config();
369
+ chainBatchStates = /* @__PURE__ */ new Map();
370
+ BATCH_DELAY = 0;
371
+ BATCH_SIZE = 50;
372
+ }
373
+ });
374
+
375
+ // src/composables/index.ts
376
+ var composables_exports = {};
377
+ __export(composables_exports, {
378
+ cacheAddress: () => cacheAddress,
379
+ clearAddressCache: () => clearAddressCache,
380
+ createAddressResolutionState: () => createAddressResolutionState,
381
+ createTransactionPlayback: () => createTransactionPlayback,
382
+ findAllTransactionViews: () => findAllTransactionViews,
383
+ findBestTransactionView: () => findBestTransactionView,
384
+ getCachedAddress: () => getCachedAddress,
385
+ getLuksoConfig: () => getLuksoConfig,
386
+ getValidPlaybackIndices: () => getValidPlaybackIndices,
387
+ isAddressResolutionEnabled: () => isAddressResolutionEnabled,
388
+ isValidPlaybackIndex: () => isValidPlaybackIndex,
389
+ resolveAddress: () => resolveAddress,
390
+ resolveAddressWithState: () => resolveAddressWithState,
391
+ resolveAddresses: () => resolveAddresses,
392
+ setLuksoConfig: () => setLuksoConfig,
393
+ useAddressResolver: () => useAddressResolver,
394
+ useImageLoader: () => useImageLoader,
395
+ useLuksoMainnet: () => useLuksoMainnet,
396
+ useLuksoTestnet: () => useLuksoTestnet,
397
+ useTransactionPlayback: () => useTransactionPlayback,
398
+ useTransactionView: () => useTransactionView
399
+ });
400
+ module.exports = __toCommonJS(composables_exports);
401
+ init_lukso_config();
402
+ init_useAddressResolution();
403
+
404
+ // src/composables/use-image-loader.ts
405
+ console.log(
406
+ "\u{1F525} LOADING NEW useAddressResolver CODE - should see GraphQL integration"
407
+ );
408
+ var imageLoadCache = /* @__PURE__ */ new Map();
409
+ function getImageCacheKey(imageData, options) {
410
+ const imageUrls = imageData.filter((img) => img?.url || img?.src).map((img) => img.url || img.src).sort().join(",");
411
+ const sizeKey = `${options.width || 32}x${options.height || options.width || 32}@${options.dpr || 1}`;
412
+ return `${imageUrls}-${sizeKey}`;
413
+ }
414
+ function useImageLoader() {
415
+ async function loadImage(imageData, options = {}) {
416
+ try {
417
+ if (!imageData || imageData.length === 0) {
418
+ return null;
419
+ }
420
+ const loadOptions = {
421
+ width: options.width || 32,
422
+ height: options.height || options.width || 32,
423
+ dpr: options.dpr || (typeof window !== "undefined" ? window.devicePixelRatio : 1),
424
+ ignoreHead: true
425
+ // Skip HEAD requests in component context
426
+ };
427
+ const cacheKey = getImageCacheKey(imageData, loadOptions);
428
+ const cachedPromise = imageLoadCache.get(cacheKey);
429
+ if (cachedPromise) {
430
+ console.log("\u{1F4F8} loadImage: Using cached promise for", cacheKey);
431
+ return cachedPromise;
432
+ }
433
+ console.log(
434
+ "\u{1F4F8} loadImage: Creating new request for",
435
+ imageData.length,
436
+ "options:",
437
+ loadOptions
438
+ );
439
+ const loadingPromise = (async () => {
440
+ const { getImage } = await import("@lukso/transaction-decoder");
441
+ const result = await getImage(imageData, loadOptions);
442
+ if (result?.src) {
443
+ console.log("\u{1F4F8} loadImage: Selected image:", result.src);
444
+ return {
445
+ src: result.src,
446
+ width: result.width,
447
+ height: result.height
448
+ };
449
+ }
450
+ return null;
451
+ })();
452
+ imageLoadCache.set(cacheKey, loadingPromise);
453
+ loadingPromise.finally(() => {
454
+ loadingPromise.then((result) => {
455
+ if (!result) {
456
+ imageLoadCache.delete(cacheKey);
457
+ }
458
+ }).catch(() => {
459
+ imageLoadCache.delete(cacheKey);
460
+ });
461
+ });
462
+ return loadingPromise;
463
+ } catch (error) {
464
+ console.warn("Failed to load image:", error);
465
+ return null;
466
+ }
467
+ }
468
+ async function loadProfileImage(addressData, options = {}) {
469
+ if (addressData.__gqltype === "Profile") {
470
+ if (addressData.profileImages?.length) {
471
+ const result = await loadImage(addressData.profileImages, options);
472
+ if (result) return result;
473
+ }
474
+ if (addressData.icons?.length) {
475
+ const result = await loadImage(addressData.icons, options);
476
+ if (result) return result;
477
+ }
478
+ if (addressData.images?.length) {
479
+ return loadImage(addressData.images, options);
480
+ }
481
+ return null;
482
+ }
483
+ if (addressData.icons?.length) {
484
+ const result = await loadImage(addressData.icons, options);
485
+ if (result) return result;
486
+ }
487
+ if (addressData.images?.length) {
488
+ return loadImage(addressData.images, options);
489
+ }
490
+ return null;
491
+ }
492
+ async function loadBackgroundImage(addressData, options = {}) {
493
+ const imageGroup = addressData.backgroundImages || [];
494
+ return loadImage(imageGroup, options);
495
+ }
496
+ function getFallbackImage(addressData) {
497
+ const isProfile = addressData.__gqltype === "Profile";
498
+ return {
499
+ src: isProfile ? "/assets/images/profile-default.svg" : "/assets/images/token-default.svg"
500
+ };
501
+ }
502
+ function isContractAddress(addressData) {
503
+ return addressData.__gqltype !== "Profile";
504
+ }
505
+ return {
506
+ loadImage,
507
+ loadProfileImage,
508
+ loadBackgroundImage,
509
+ getFallbackImage,
510
+ isContractAddress
511
+ };
512
+ }
513
+ function useAddressResolver() {
514
+ async function resolveAddress2(address) {
515
+ console.log("\u{1F525} useAddressResolver.resolveAddress called with:", address);
516
+ try {
517
+ const { resolveAddress: batchedResolve } = await Promise.resolve().then(() => (init_useAddressResolution(), useAddressResolution_exports));
518
+ console.log("\u{1F525} useAddressResolver: calling batchedResolve...");
519
+ const resolved = await batchedResolve(address);
520
+ console.log("\u{1F525} useAddressResolver: batchedResolve returned:", resolved);
521
+ const result = {
522
+ // Preserve all image arrays from GraphQL
523
+ ...resolved,
524
+ // Override with computed values only if not already set by GraphQL
525
+ address: resolved.address,
526
+ name: resolved.name || "",
527
+ __gqltype: resolved.__gqltype || (resolved.hasProfile ? "Profile" : "Contract")
528
+ };
529
+ console.log("\u{1F525} useAddressResolver: returning result:", result);
530
+ return result;
531
+ } catch (error) {
532
+ console.error("\u{1F525} useAddressResolver: Failed to resolve address:", error);
533
+ return {
534
+ address,
535
+ name: "",
536
+ __gqltype: "Contract",
537
+ profileImages: [],
538
+ avatar: [],
539
+ icon: []
540
+ };
541
+ }
542
+ }
543
+ function formatDisplayName(addressData) {
544
+ const baseName = addressData.name?.toLowerCase?.() || addressData.lsp4TokenName || addressData.baseAsset?.lsp4TokenName || "";
545
+ const symbol = addressData.lsp4TokenSymbol || addressData.baseAsset?.lsp4TokenSymbol || "";
546
+ return symbol ? `${baseName} (${symbol})` : baseName;
547
+ }
548
+ function getAddressPrefix(addressData) {
549
+ return addressData.__gqltype !== "Profile" ? "\u{1FA99} " : "@";
550
+ }
551
+ function shouldShowNameColor(addressData) {
552
+ return addressData.__gqltype === "Profile";
553
+ }
554
+ return {
555
+ resolveAddress: resolveAddress2,
556
+ formatDisplayName,
557
+ getAddressPrefix,
558
+ shouldShowNameColor
559
+ };
560
+ }
561
+
562
+ // src/utils/view-matcher.ts
563
+ var CRITERIA_WEIGHTS = {
564
+ recordType: 0.25,
565
+ // Most specific to transaction type
566
+ functionName: 0.2,
567
+ // Function-level specificity
568
+ context: 0.2,
569
+ // Context specificity (when opt-in)
570
+ standard: 0.15,
571
+ // LSP standard specificity
572
+ contractAddress: 0.1,
573
+ // Contract-specific logic
574
+ contextRequirements: 0.05,
575
+ // Context requirement matching
576
+ chainId: 0.03,
577
+ // Network-specific behavior
578
+ customMatcher: 0.02
579
+ // Custom logic (lowest weight due to unpredictability)
580
+ };
581
+ function calculateMatchScore(transaction, view, options) {
582
+ const { criteria } = view;
583
+ const matchedCriteria = [];
584
+ let totalWeight = 0;
585
+ let matchedWeight = 0;
586
+ for (const [criterion, weight] of Object.entries(CRITERIA_WEIGHTS)) {
587
+ const criterionKey = criterion;
588
+ const criterionValue = criteria[criterionKey];
589
+ if (criterionValue === void 0) continue;
590
+ totalWeight += weight;
591
+ if (criterionKey === "customMatcher" && typeof criterionValue === "function") {
592
+ try {
593
+ const matchCount = criterionValue(transaction);
594
+ if (matchCount > 0) {
595
+ matchedCriteria.push(criterionKey);
596
+ const normalizedScore = Math.min(matchCount / 10, 1);
597
+ matchedWeight += weight * normalizedScore;
598
+ }
599
+ } catch (error) {
600
+ console.warn("Custom matcher threw error:", error);
601
+ }
602
+ continue;
603
+ }
604
+ if (doesCriterionMatch(transaction, criterionKey, criterionValue, options)) {
605
+ matchedCriteria.push(criterionKey);
606
+ matchedWeight += weight;
607
+ }
608
+ }
609
+ const viewHasContext = criteria.context !== void 0;
610
+ const requestHasContext = options?.context !== void 0;
611
+ if (viewHasContext && !requestHasContext) {
612
+ matchedWeight *= 0.1;
613
+ } else if (!viewHasContext && requestHasContext) {
614
+ matchedWeight *= 0.9;
615
+ }
616
+ if (totalWeight === 0) return { score: 0, matchedCriteria: [] };
617
+ const score = matchedWeight / totalWeight;
618
+ return { score, matchedCriteria };
619
+ }
620
+ function doesCriterionMatch(transaction, criterion, criterionValue, options) {
621
+ switch (criterion) {
622
+ case "recordType":
623
+ return matchesStringOrArray(
624
+ transaction.recordType,
625
+ criterionValue
626
+ );
627
+ case "functionName":
628
+ return matchesStringOrArray(
629
+ transaction.functionName,
630
+ criterionValue
631
+ );
632
+ case "standard":
633
+ return matchesStringOrArray(
634
+ transaction.standard,
635
+ criterionValue
636
+ );
637
+ case "contractAddress":
638
+ return matchesStringOrArray(
639
+ transaction.contractAddress,
640
+ criterionValue
641
+ );
642
+ case "chainId":
643
+ return matchesNumberOrArray(transaction.chainId, criterionValue);
644
+ case "context":
645
+ if (!options?.context) return false;
646
+ return matchesStringOrArray(options.context, criterionValue);
647
+ case "contextRequirements":
648
+ if (!options?.contextRequirements || !criterionValue) return false;
649
+ return areContextRequirementsCompatible(
650
+ options.contextRequirements,
651
+ criterionValue
652
+ );
653
+ case "customMatcher":
654
+ if (typeof criterionValue === "function") {
655
+ try {
656
+ const matchCount = criterionValue(transaction);
657
+ return matchCount > 0;
658
+ } catch (error) {
659
+ console.warn("Custom matcher threw error:", error);
660
+ return false;
661
+ }
662
+ }
663
+ return false;
664
+ default:
665
+ return false;
666
+ }
667
+ }
668
+ function matchesStringOrArray(value, criteria) {
669
+ if (!value || !criteria) return false;
670
+ if (Array.isArray(criteria)) {
671
+ return criteria.includes(value);
672
+ }
673
+ return value === criteria;
674
+ }
675
+ function matchesNumberOrArray(value, criteria) {
676
+ if (value === void 0 || criteria === void 0) return false;
677
+ if (Array.isArray(criteria)) {
678
+ return criteria.includes(value);
679
+ }
680
+ return value === criteria;
681
+ }
682
+ function areContextRequirementsCompatible(requested, viewRequirements) {
683
+ if (requested.detailLevel && viewRequirements.detailLevel) {
684
+ const detailOrder = ["minimal", "summary", "full", "debug"];
685
+ const requestedLevel = detailOrder.indexOf(requested.detailLevel);
686
+ const viewLevel = detailOrder.indexOf(viewRequirements.detailLevel);
687
+ if (viewLevel < requestedLevel) return false;
688
+ }
689
+ if (requested.maxHeight && viewRequirements.maxHeight) {
690
+ if (viewRequirements.maxHeight > requested.maxHeight) return false;
691
+ }
692
+ return true;
693
+ }
694
+ function calculateNativeFrameworkBonus(view, requestedFramework) {
695
+ if (requestedFramework === "lit") {
696
+ return 0;
697
+ }
698
+ if (requestedFramework === "vue" && view.frameworks.vue) {
699
+ return 0.15;
700
+ }
701
+ if (requestedFramework === "rn" && view.frameworks.rn) {
702
+ return 0.15;
703
+ }
704
+ return 0;
705
+ }
706
+ function findMatchingViews(transaction, views, options) {
707
+ const matches = [];
708
+ const minScore = options.minScore ?? 0;
709
+ for (const view of views) {
710
+ if (!view.frameworks[options.framework]) {
711
+ continue;
712
+ }
713
+ const { score, matchedCriteria } = calculateMatchScore(transaction, view, {
714
+ context: options.context,
715
+ contextRequirements: options.contextRequirements
716
+ });
717
+ if (score < minScore) {
718
+ continue;
719
+ }
720
+ const frameworkBonus = calculateNativeFrameworkBonus(
721
+ view,
722
+ options.framework
723
+ );
724
+ const finalScore = Math.min(1, score + frameworkBonus);
725
+ const match = {
726
+ view,
727
+ score: finalScore,
728
+ matchedCriteria,
729
+ frameworkConfig: options.includeFrameworkConfig ? view.frameworks[options.framework] : void 0
730
+ };
731
+ matches.push(match);
732
+ }
733
+ matches.sort((a, b) => {
734
+ if (a.score !== b.score) {
735
+ return b.score - a.score;
736
+ }
737
+ return b.view.priority - a.view.priority;
738
+ });
739
+ if (options.maxMatches) {
740
+ return matches.slice(0, options.maxMatches);
741
+ }
742
+ return matches;
743
+ }
744
+
745
+ // src/registry/view-registry.ts
746
+ var DefaultViewRegistry = class {
747
+ views = /* @__PURE__ */ new Map();
748
+ register(view) {
749
+ if (this.views.has(view.id)) {
750
+ console.warn(
751
+ `View with id "${view.id}" is already registered. Overwriting.`
752
+ );
753
+ }
754
+ this.views.set(view.id, view);
755
+ }
756
+ unregister(viewId) {
757
+ this.views.delete(viewId);
758
+ }
759
+ getAllViews() {
760
+ return Array.from(this.views.values());
761
+ }
762
+ findMatches(transaction, options) {
763
+ const allViews = this.getAllViews();
764
+ return findMatchingViews(transaction, allViews, options);
765
+ }
766
+ getView(viewId) {
767
+ return this.views.get(viewId);
768
+ }
769
+ clear() {
770
+ this.views.clear();
771
+ }
772
+ /**
773
+ * Get the best matching view (highest score) for a transaction
774
+ */
775
+ getBestMatch(transaction, options) {
776
+ const matches = this.findMatches(transaction, { ...options, maxMatches: 1 });
777
+ return matches[0] || null;
778
+ }
779
+ /**
780
+ * Bulk register multiple views
781
+ */
782
+ registerMany(views) {
783
+ for (const view of views) {
784
+ this.register(view);
785
+ }
786
+ }
787
+ /**
788
+ * Get stats about registered views
789
+ */
790
+ getStats() {
791
+ const allViews = this.getAllViews();
792
+ const totalViews = allViews.length;
793
+ const viewsByFramework = {};
794
+ const viewsByRecordType = {};
795
+ for (const view of allViews) {
796
+ for (const framework of Object.keys(view.frameworks)) {
797
+ viewsByFramework[framework] = (viewsByFramework[framework] || 0) + 1;
798
+ }
799
+ const recordType = view.criteria.recordType;
800
+ if (recordType) {
801
+ const types = Array.isArray(recordType) ? recordType : [recordType];
802
+ for (const type of types) {
803
+ viewsByRecordType[type] = (viewsByRecordType[type] || 0) + 1;
804
+ }
805
+ }
806
+ }
807
+ return {
808
+ totalViews,
809
+ viewsByFramework,
810
+ viewsByRecordType
811
+ };
812
+ }
813
+ };
814
+ var globalRegistry = null;
815
+ function getGlobalRegistry() {
816
+ if (!globalRegistry) {
817
+ globalRegistry = new DefaultViewRegistry();
818
+ }
819
+ return globalRegistry;
820
+ }
821
+
822
+ // src/composables/use-transaction-playback.ts
823
+ function isBatchTransaction(transaction) {
824
+ return transaction.resultType === "executeBatch" || transaction.resultType === "setDataBatch" || !!transaction.children?.length;
825
+ }
826
+ function getBatchChildren(transaction) {
827
+ if (!isBatchTransaction(transaction)) {
828
+ return [];
829
+ }
830
+ return transaction.children || [];
831
+ }
832
+ function selectViewAtIndex(rootTransaction, index, options) {
833
+ const {
834
+ registry = getGlobalRegistry(),
835
+ framework = "lit",
836
+ fallbackViewId,
837
+ minScore = 0,
838
+ includeFrameworkConfig = true
839
+ } = options;
840
+ const isBatch = isBatchTransaction(rootTransaction);
841
+ const children = getBatchChildren(rootTransaction);
842
+ const childCount = children.length;
843
+ const result = {
844
+ match: null,
845
+ transaction: null,
846
+ indexInfo: {
847
+ requested: index,
848
+ childIndex: null,
849
+ isBatchSummary: false,
850
+ isValid: false
851
+ },
852
+ batchInfo: {
853
+ isBatch,
854
+ childCount,
855
+ availableIndices: []
856
+ }
857
+ };
858
+ if (isBatch) {
859
+ result.batchInfo.availableIndices = Array.from(
860
+ { length: childCount + 1 },
861
+ (_, i) => i
862
+ );
863
+ } else {
864
+ result.batchInfo.availableIndices = [0, 1];
865
+ }
866
+ if (index < 0) {
867
+ return result;
868
+ }
869
+ if (!isBatch) {
870
+ if (index === 0 || index === 1) {
871
+ result.indexInfo.isValid = true;
872
+ result.transaction = rootTransaction;
873
+ const matchOptions = {
874
+ framework,
875
+ minScore,
876
+ maxMatches: 1,
877
+ includeFrameworkConfig
878
+ };
879
+ const matches = registry.findMatches(rootTransaction, matchOptions);
880
+ result.match = matches[0] || null;
881
+ if (!result.match && fallbackViewId) {
882
+ const fallbackView = registry.getView(fallbackViewId);
883
+ if (fallbackView && fallbackView.frameworks[framework]) {
884
+ result.match = {
885
+ view: fallbackView,
886
+ score: 0,
887
+ matchedCriteria: [],
888
+ frameworkConfig: includeFrameworkConfig ? fallbackView.frameworks[framework] : void 0
889
+ };
890
+ }
891
+ }
892
+ return result;
893
+ }
894
+ return result;
895
+ }
896
+ if (index === 0) {
897
+ result.indexInfo.isValid = true;
898
+ result.indexInfo.isBatchSummary = true;
899
+ result.transaction = rootTransaction;
900
+ const matchOptions = {
901
+ framework,
902
+ minScore,
903
+ maxMatches: 1,
904
+ includeFrameworkConfig
905
+ };
906
+ const matches = registry.findMatches(rootTransaction, matchOptions);
907
+ result.match = matches[0] || null;
908
+ if (!result.match && fallbackViewId) {
909
+ const fallbackView = registry.getView(fallbackViewId);
910
+ if (fallbackView && fallbackView.frameworks[framework]) {
911
+ result.match = {
912
+ view: fallbackView,
913
+ score: 0,
914
+ matchedCriteria: [],
915
+ frameworkConfig: includeFrameworkConfig ? fallbackView.frameworks[framework] : void 0
916
+ };
917
+ }
918
+ }
919
+ return result;
920
+ }
921
+ const childIndex = index - 1;
922
+ if (childIndex >= 0 && childIndex < childCount) {
923
+ result.indexInfo.isValid = true;
924
+ result.indexInfo.childIndex = childIndex;
925
+ result.transaction = children[childIndex];
926
+ const matchOptions = {
927
+ framework,
928
+ minScore,
929
+ maxMatches: 1,
930
+ includeFrameworkConfig
931
+ };
932
+ const matches = registry.findMatches(result.transaction, matchOptions);
933
+ result.match = matches[0] || null;
934
+ if (!result.match && fallbackViewId) {
935
+ const fallbackView = registry.getView(fallbackViewId);
936
+ if (fallbackView && fallbackView.frameworks[framework]) {
937
+ result.match = {
938
+ view: fallbackView,
939
+ score: 0,
940
+ matchedCriteria: [],
941
+ frameworkConfig: includeFrameworkConfig ? fallbackView.frameworks[framework] : void 0
942
+ };
943
+ }
944
+ }
945
+ return result;
946
+ }
947
+ return result;
948
+ }
949
+ function createTransactionPlayback(rootTransaction, options = {}) {
950
+ const isBatch = isBatchTransaction(rootTransaction);
951
+ const children = getBatchChildren(rootTransaction);
952
+ const childCount = children.length;
953
+ const indexCount = isBatch ? childCount + 1 : 2;
954
+ const availableIndices = isBatch ? Array.from({ length: childCount + 1 }, (_, i) => i) : [0, 1];
955
+ return {
956
+ rootTransaction,
957
+ isBatch,
958
+ children,
959
+ indexCount,
960
+ batchInfo: {
961
+ isBatch,
962
+ childCount,
963
+ availableIndices
964
+ },
965
+ getViewAtIndex: (index) => selectViewAtIndex(rootTransaction, index, options),
966
+ getAllViews: () => {
967
+ const views = [];
968
+ for (let i = 0; i < indexCount; i++) {
969
+ views.push(selectViewAtIndex(rootTransaction, i, options));
970
+ }
971
+ return views;
972
+ }
973
+ };
974
+ }
975
+ function useTransactionPlayback(rootTransaction, index, options = {}) {
976
+ return selectViewAtIndex(rootTransaction, index, options);
977
+ }
978
+ function isValidPlaybackIndex(transaction, index) {
979
+ const isBatch = isBatchTransaction(transaction);
980
+ if (!isBatch) {
981
+ return index === 0 || index === 1;
982
+ }
983
+ const childCount = getBatchChildren(transaction).length;
984
+ return index >= 0 && index <= childCount;
985
+ }
986
+ function getValidPlaybackIndices(transaction) {
987
+ const isBatch = isBatchTransaction(transaction);
988
+ if (!isBatch) {
989
+ return [0, 1];
990
+ }
991
+ const childCount = getBatchChildren(transaction).length;
992
+ return Array.from({ length: childCount + 1 }, (_, i) => i);
993
+ }
994
+
995
+ // src/composables/use-transaction-view.ts
996
+ var import_transaction_decoder = require("@lukso/transaction-decoder");
997
+
998
+ // src/registry/view-loader.ts
999
+ var ViewLoadingError = class extends Error {
1000
+ loader;
1001
+ config;
1002
+ cause;
1003
+ constructor(message, loader, config, cause) {
1004
+ super(message);
1005
+ this.name = "ViewLoadingError";
1006
+ this.loader = loader;
1007
+ this.config = config;
1008
+ this.cause = cause;
1009
+ }
1010
+ };
1011
+ var UniversalViewLoader = class {
1012
+ cache = /* @__PURE__ */ new Map();
1013
+ /**
1014
+ * Load a component based on the framework configuration
1015
+ */
1016
+ async loadComponent(config) {
1017
+ const cacheKey = this.getCacheKey(config);
1018
+ if (this.cache.has(cacheKey)) {
1019
+ return this.cache.get(cacheKey);
1020
+ }
1021
+ try {
1022
+ const component = await this.loadByStrategy(config.loader);
1023
+ this.cache.set(cacheKey, component);
1024
+ return component;
1025
+ } catch (error) {
1026
+ throw new ViewLoadingError(
1027
+ `Failed to load component "${config.component}"`,
1028
+ config.loader,
1029
+ config,
1030
+ error instanceof Error ? error : new Error(String(error))
1031
+ );
1032
+ }
1033
+ }
1034
+ /**
1035
+ * Load a component from a view match
1036
+ */
1037
+ async loadFromMatch(match) {
1038
+ if (!match.frameworkConfig) {
1039
+ throw new ViewLoadingError(
1040
+ `No framework config available for view "${match.view.id}"`,
1041
+ { type: "dynamic-import", path: "" },
1042
+ {}
1043
+ );
1044
+ }
1045
+ return this.loadComponent(match.frameworkConfig);
1046
+ }
1047
+ /**
1048
+ * Load component using the specific strategy
1049
+ */
1050
+ async loadByStrategy(loader) {
1051
+ switch (loader.type) {
1052
+ case "dynamic-import":
1053
+ return this.loadDynamicImport(loader.path);
1054
+ case "static-import":
1055
+ return this.loadStaticImport(loader.path);
1056
+ case "custom-element":
1057
+ return this.loadCustomElement(loader.tagName);
1058
+ case "registry-lookup":
1059
+ return this.loadFromRegistry(loader.registryKey);
1060
+ case "custom":
1061
+ return loader.loader({});
1062
+ // Will be passed proper config in real usage
1063
+ default:
1064
+ throw new Error(`Unknown loader type: ${loader.type}`);
1065
+ }
1066
+ }
1067
+ /**
1068
+ * Dynamic import strategy (most common)
1069
+ * Supports both static strings and lazy-loaded callbacks
1070
+ */
1071
+ async loadDynamicImport(path) {
1072
+ if (typeof path === "function") {
1073
+ const module3 = await path();
1074
+ if (module3.default) {
1075
+ return module3.default;
1076
+ }
1077
+ return module3;
1078
+ }
1079
+ const module2 = await import(path);
1080
+ if (module2.default) {
1081
+ return module2.default;
1082
+ }
1083
+ return module2;
1084
+ }
1085
+ /**
1086
+ * Static import strategy (requires bundler support)
1087
+ * Supports both static strings and lazy-loaded callbacks
1088
+ */
1089
+ async loadStaticImport(path) {
1090
+ if (typeof path === "function") {
1091
+ const module2 = await path();
1092
+ if (module2.default) {
1093
+ return module2.default;
1094
+ }
1095
+ return module2;
1096
+ }
1097
+ console.warn(
1098
+ "Static import not implemented, falling back to dynamic import"
1099
+ );
1100
+ return this.loadDynamicImport(path);
1101
+ }
1102
+ /**
1103
+ * Custom element strategy (for Lit components)
1104
+ */
1105
+ async loadCustomElement(tagName) {
1106
+ if (typeof window !== "undefined" && window.customElements) {
1107
+ await window.customElements.whenDefined(tagName);
1108
+ return { tagName, type: "custom-element" };
1109
+ }
1110
+ throw new Error("Custom elements not available in this environment");
1111
+ }
1112
+ /**
1113
+ * Registry lookup strategy (for pre-registered components)
1114
+ */
1115
+ async loadFromRegistry(registryKey) {
1116
+ throw new Error(`Registry lookup not implemented for key: ${registryKey}`);
1117
+ }
1118
+ /**
1119
+ * Generate cache key for component config
1120
+ */
1121
+ getCacheKey(config) {
1122
+ const { loader, component, package: pkg } = config;
1123
+ return JSON.stringify({ loader, component, package: pkg });
1124
+ }
1125
+ /**
1126
+ * Clear the component cache
1127
+ */
1128
+ clearCache() {
1129
+ this.cache.clear();
1130
+ }
1131
+ /**
1132
+ * Get cache statistics
1133
+ */
1134
+ getCacheStats() {
1135
+ return {
1136
+ size: this.cache.size,
1137
+ keys: Array.from(this.cache.keys())
1138
+ };
1139
+ }
1140
+ };
1141
+ var globalLoader = null;
1142
+ function getGlobalLoader() {
1143
+ if (!globalLoader) {
1144
+ globalLoader = new UniversalViewLoader();
1145
+ }
1146
+ return globalLoader;
1147
+ }
1148
+
1149
+ // src/composables/use-transaction-view.ts
1150
+ function useTransactionView(transaction, options) {
1151
+ const {
1152
+ registry = getGlobalRegistry(),
1153
+ autoLoad = false,
1154
+ fallbackViewId,
1155
+ framework = "lit",
1156
+ minScore = 0,
1157
+ maxMatches,
1158
+ includeFrameworkConfig = true,
1159
+ resolve = false,
1160
+ chain,
1161
+ addressCache: addressCache2
1162
+ } = options;
1163
+ const loader = getGlobalLoader();
1164
+ let matches = [];
1165
+ let bestMatch = null;
1166
+ let component = null;
1167
+ let isLoading = false;
1168
+ let error = null;
1169
+ let isResolvingAddresses = false;
1170
+ let resolvedAddresses = {};
1171
+ const refreshMatches = () => {
1172
+ const matchOptions = {
1173
+ framework,
1174
+ minScore,
1175
+ maxMatches,
1176
+ includeFrameworkConfig
1177
+ };
1178
+ matches = registry.findMatches(transaction, matchOptions);
1179
+ bestMatch = matches[0] || null;
1180
+ if (!bestMatch && fallbackViewId) {
1181
+ const fallbackView = registry.getView(fallbackViewId);
1182
+ if (fallbackView && fallbackView.frameworks[framework]) {
1183
+ bestMatch = {
1184
+ view: fallbackView,
1185
+ score: 0,
1186
+ matchedCriteria: [],
1187
+ frameworkConfig: includeFrameworkConfig ? fallbackView.frameworks[framework] : void 0
1188
+ };
1189
+ }
1190
+ }
1191
+ };
1192
+ const loadMatch = async (match) => {
1193
+ if (!match.frameworkConfig) {
1194
+ throw new ViewLoadingError(
1195
+ `No framework config for view "${match.view.id}" and framework "${framework}"`,
1196
+ { type: "dynamic-import", path: "" },
1197
+ {}
1198
+ );
1199
+ }
1200
+ isLoading = true;
1201
+ error = null;
1202
+ try {
1203
+ const loadedComponent = await loader.loadFromMatch(match);
1204
+ component = loadedComponent;
1205
+ return loadedComponent;
1206
+ } catch (err) {
1207
+ error = err instanceof ViewLoadingError ? err : new ViewLoadingError(
1208
+ "Unknown loading error",
1209
+ match.frameworkConfig.loader,
1210
+ match.frameworkConfig,
1211
+ err instanceof Error ? err : new Error(String(err))
1212
+ );
1213
+ throw error;
1214
+ } finally {
1215
+ isLoading = false;
1216
+ }
1217
+ };
1218
+ const loadBestMatch = async () => {
1219
+ if (!bestMatch) {
1220
+ throw new Error("No matching view found for transaction");
1221
+ }
1222
+ return loadMatch(bestMatch);
1223
+ };
1224
+ const resolveAddressesFunc = async () => {
1225
+ if (!resolve || !transaction.addresses || transaction.addresses.length === 0) {
1226
+ return;
1227
+ }
1228
+ if (!chain) {
1229
+ console.warn(
1230
+ "Address resolution requested but no chain provided. Pass chain option to resolve addresses."
1231
+ );
1232
+ return;
1233
+ }
1234
+ isResolvingAddresses = true;
1235
+ try {
1236
+ const dataKeys = transaction.addresses.filter((addr) => addr && typeof addr === "string").map((addr) => addr.toLowerCase());
1237
+ if (dataKeys.length === 0) {
1238
+ return;
1239
+ }
1240
+ const endpoint = (0, import_transaction_decoder.getGraphQLEndpoint)(chain);
1241
+ const resolvedMap = await (0, import_transaction_decoder.fetchMultipleAddresses)(
1242
+ dataKeys,
1243
+ endpoint,
1244
+ addressCache2
1245
+ );
1246
+ const resolved = {};
1247
+ resolvedMap.forEach((enhancedInfo, dataKey) => {
1248
+ resolved[dataKey] = enhancedInfo;
1249
+ });
1250
+ resolvedAddresses = resolved;
1251
+ } catch (err) {
1252
+ console.error("Address resolution failed:", err);
1253
+ } finally {
1254
+ isResolvingAddresses = false;
1255
+ }
1256
+ };
1257
+ refreshMatches();
1258
+ if (resolve) {
1259
+ resolveAddressesFunc().catch((err) => {
1260
+ console.error("Auto address resolution failed:", err);
1261
+ });
1262
+ }
1263
+ if (autoLoad && bestMatch) {
1264
+ loadBestMatch().catch((err) => {
1265
+ console.error("Auto-load failed:", err);
1266
+ });
1267
+ }
1268
+ return {
1269
+ matches,
1270
+ bestMatch,
1271
+ component,
1272
+ isLoading,
1273
+ error,
1274
+ isResolvingAddresses,
1275
+ resolvedAddresses,
1276
+ loadMatch,
1277
+ loadBestMatch,
1278
+ refreshMatches,
1279
+ resolveAddresses: resolveAddressesFunc
1280
+ };
1281
+ }
1282
+ function findBestTransactionView(transaction, framework, registry) {
1283
+ const reg = registry || getGlobalRegistry();
1284
+ const matches = reg.findMatches(transaction, {
1285
+ framework,
1286
+ includeFrameworkConfig: true
1287
+ });
1288
+ return matches.length > 0 ? matches[0] : null;
1289
+ }
1290
+ function findAllTransactionViews(transaction, framework, registry) {
1291
+ const reg = registry || getGlobalRegistry();
1292
+ return reg.findMatches(transaction, {
1293
+ framework,
1294
+ includeFrameworkConfig: true
1295
+ });
1296
+ }
1297
+ // Annotate the CommonJS export names for ESM import in node:
1298
+ 0 && (module.exports = {
1299
+ cacheAddress,
1300
+ clearAddressCache,
1301
+ createAddressResolutionState,
1302
+ createTransactionPlayback,
1303
+ findAllTransactionViews,
1304
+ findBestTransactionView,
1305
+ getCachedAddress,
1306
+ getLuksoConfig,
1307
+ getValidPlaybackIndices,
1308
+ isAddressResolutionEnabled,
1309
+ isValidPlaybackIndex,
1310
+ resolveAddress,
1311
+ resolveAddressWithState,
1312
+ resolveAddresses,
1313
+ setLuksoConfig,
1314
+ useAddressResolver,
1315
+ useImageLoader,
1316
+ useLuksoMainnet,
1317
+ useLuksoTestnet,
1318
+ useTransactionPlayback,
1319
+ useTransactionView
1320
+ });
1321
+ //# sourceMappingURL=index.cjs.map