bitcoin-inscription-viewer
Version:
🔍 A robust, production-ready React/TypeScript library for viewing Bitcoin Ordinals inscriptions with advanced optimization features including LRU caching, LaserEyes wallet integration, virtual scrolling, and performance monitoring
1 lines • 253 kB
JavaScript
"use strict";var e=require("react/jsx-runtime"),t=require("react"),s=require("lucide-react"),r=require("three");function n(e){var t=Object.create(null);return e&&Object.keys(e).forEach(function(s){if("default"!==s){var r=Object.getOwnPropertyDescriptor(e,s);Object.defineProperty(t,s,r.get?r:{enumerable:!0,get:function(){return e[s]}})}}),t.default=e,Object.freeze(t)}var a=n(r);const i=t.forwardRef(({className:t="",variant:s="default",size:r="default",children:n,...a},i)=>{const o=`inline-flex items-center justify-center rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 ${{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"}[s]} ${{default:"h-10 px-4 py-2",sm:"h-9 rounded-md px-3",lg:"h-11 rounded-md px-8",icon:"h-10 w-10"}[r]} ${t}`;return e.jsx("button",{className:o,ref:i,...a,children:n})});i.displayName="Button";class o{constructor(e=3,t=.5){Object.defineProperty(this,"tokens",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"lastRefill",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxTokens",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"refillRate",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"refillInterval",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxTokens=e,this.refillRate=t,this.refillInterval=1e3/t,this.tokens=e,this.lastRefill=Date.now()}canMakeRequest(){return this.refillTokens(),this.tokens>0&&(this.tokens--,!0)}async waitForToken(){for(;!this.canMakeRequest();){const e=Math.max(100,this.refillInterval);await new Promise(t=>setTimeout(t,e))}}getWaitTime(){return this.refillTokens(),this.tokens>0?0:this.refillInterval}refillTokens(){const e=Date.now(),t=e-this.lastRefill,s=Math.floor(t/this.refillInterval);s>0&&(this.tokens=Math.min(this.maxTokens,this.tokens+s),this.lastRefill=e)}getTokenCount(){return this.refillTokens(),this.tokens}reset(){this.tokens=this.maxTokens,this.lastRefill=Date.now()}}const l=new o(2,.3);async function c(e,t){return e.includes("ordinals.com")&&(await l.waitForToken(),console.log(`🚦 Making throttled request to: ${e} (${l.getTokenCount()} tokens remaining)`)),fetch(e,t)}async function d(e,t,s){console.log(`🔍 Starting content analysis for: ${e}`,{originalInscriptionId:t,knownContentType:s});try{const t=e.includes("/inscription/")||e.includes("/inscriptions")||e.includes("/block/")||e.includes("/sat/")||e.includes("/address/")||e.includes("/output/")||e.includes("/r/");let s,r=!1;try{console.log(`📡 Attempting ${t?"JSON API":"range"} request for: ${e}`);const n={};if(t?(n.Accept="application/json",n["User-Agent"]="InscriptionViewer/1.0.0"):n.Range="bytes=0-8191",s=await c(e,{headers:n}),206!==s.status||t)if(416!==s.status||t){if(!s.ok){if(404===s.status||400===s.status)throw new Error(`PERMANENT_ERROR_${s.status}: ${s.statusText}`);throw new Error(`HTTP ${s.status}: ${s.statusText}`)}}else console.log(`⚠️ Range not supported, falling back to full request for: ${e}`),s=await c(e);else r=!0,console.log(`✅ Range request successful for: ${e}`)}catch(t){if(t.message?.includes("PERMANENT_ERROR"))throw t;console.log(`⚠️ Range request failed, trying full request for: ${e}`,t),s=await c(e)}if(!s.ok){if(404===s.status||400===s.status)throw new Error(`PERMANENT_ERROR_${s.status}: ${s.statusText}`);throw new Error(`HTTP ${s.status}: ${s.statusText}`)}const n=s.headers.get("content-type")||"application/octet-stream",a=s.headers.get("content-length");console.log(`📊 Content analysis - Type: ${n}, Length: ${a}, Range: ${r}`);const i=await s.arrayBuffer(),o=new Uint8Array(r?i:i.slice(0,8192)),l=new TextDecoder("utf-8",{fatal:!1});console.log(`📦 Received ${o.length} bytes for analysis`);let d="";try{d=l.decode(o)}catch{}const u=function(e,t,s){const r=e.toLowerCase();let n;if(console.log(`🔬 Analyzing content type - MIME: ${r}, Bytes: ${t.length}, Has text: ${!!s}`),t.length>=4){const e=Array.from(t.slice(0,4)).map(e=>e.toString(16).padStart(2,"0")).join(""),s=t.length>=8?Array.from(t.slice(0,8)).map(e=>e.toString(16).padStart(2,"0")).join(""):"";if(console.log(`🔍 Magic bytes: ${e} (first 4), ${s} (first 8)`),"89504e47"===e)return console.log("✅ Detected PNG by magic bytes"),{detectedType:"image",renderStrategy:"native",fileExtension:"png",isInlineable:!0,category:"media",displayName:"PNG Image",description:"Portable Network Graphics (detected by content)"};if(e.startsWith("ffd8"))return console.log("✅ Detected JPEG by magic bytes"),{detectedType:"image",renderStrategy:"native",fileExtension:"jpg",isInlineable:!0,category:"media",displayName:"JPEG Image",description:"JPEG compressed image (detected by content)"};if("47494638"===e)return console.log("✅ Detected GIF by magic bytes"),{detectedType:"image",renderStrategy:"native",fileExtension:"gif",isInlineable:!0,category:"media",displayName:"GIF Animation",description:"Graphics Interchange Format (detected by content)"};if("52494646"===e&&t.length>=12){if("57454250"===Array.from(t.slice(8,12)).map(e=>e.toString(16).padStart(2,"0")).join(""))return console.log("✅ Detected WebP by magic bytes"),{detectedType:"image",renderStrategy:"native",fileExtension:"webp",isInlineable:!0,category:"media",displayName:"WebP Image",description:"WebP compressed image (detected by content)"}}if(t.length>=4&&"%PDF"===String.fromCharCode(...t.slice(0,4)))return console.log("✅ Detected PDF by magic bytes"),{detectedType:"pdf",renderStrategy:"iframe",fileExtension:"pdf",isInlineable:!1,category:"document",displayName:"PDF Document",description:"Portable Document Format (detected by content)"};if(e.startsWith("504b"))return console.log("✅ Detected ZIP by magic bytes"),{detectedType:"archive",renderStrategy:"download",fileExtension:"zip",isInlineable:!1,category:"archive",displayName:"ZIP Archive",description:"ZIP compressed archive (detected by content)"}}if(s){const e=s.trim();if(console.log(`📝 Analyzing text content: ${e.substring(0,100)}...`),e.includes("<!DOCTYPE")||e.includes("<html")||e.includes("<head>")||e.includes("<body>")||e.includes("<")&&e.includes(">")&&e.includes("</"))return console.log("✅ Detected HTML by content structure"),{detectedType:"html",renderStrategy:"native",fileExtension:"html",isInlineable:!0,category:"document",displayName:"HTML Document",description:"HyperText Markup Language (detected by content)"};if(e.startsWith("{")&&e.includes("}")||e.startsWith("[")&&e.includes("]"))try{return JSON.parse(e),console.log("✅ Detected JSON by content structure"),{detectedType:"json",renderStrategy:"native",fileExtension:"json",isInlineable:!0,category:"data",displayName:"JSON Data",description:"JavaScript Object Notation (detected by content)"}}catch{console.log("❌ Content looks like JSON but failed to parse")}if(e.includes("<svg")||e.includes('xmlns="http://www.w3.org/2000/svg"'))return console.log("✅ Detected SVG by content structure"),{detectedType:"svg",renderStrategy:"native",fileExtension:"svg",isInlineable:!0,category:"media",displayName:"SVG Vector",description:"Scalable Vector Graphics (detected by content)"};if(e.includes("<?xml")||e.includes("<")&&e.includes(">")&&e.includes("</"))return console.log("✅ Detected XML by content structure"),{detectedType:"text",renderStrategy:"native",fileExtension:"xml",encoding:"utf-8",isInlineable:!0,category:"document",displayName:"XML Document",description:"Extensible Markup Language (detected by content)"}}console.log(`🏷️ Analyzing by MIME type: ${r}`),r.includes("audio/mpeg")||r.includes("audio/mp3")?n="mp3":r.includes("model/gltf-binary")?n="glb":r.includes("model/gltf")?n="gltf":r.includes("image/jpeg")?n="jpg":r.includes("image/png")?n="png":r.includes("video/mp4")?n="mp4":r.includes("image/svg")?n="svg":r.includes("text/html")&&(n="html");if(r.includes("application/json")||r.includes("text/json")||"json"===n||"jsonl"===n||"ndjson"===n)return{detectedType:"json",renderStrategy:"native",fileExtension:n||"json",encoding:"utf-8",isInlineable:!0,category:"data",displayName:"JSON Data",description:"JavaScript Object Notation data file"};if("text/html"===r||"html"===n||"htm"===n)return{detectedType:"html",renderStrategy:"native",fileExtension:n||"html",isInlineable:!0,category:"document",displayName:"HTML Document",description:"HyperText Markup Language document"};const a={js:"JavaScript",jsx:"JSX",ts:"TypeScript",tsx:"TSX",css:"CSS",scss:"SCSS",sass:"Sass",less:"Less",php:"PHP",asp:"ASP",aspx:"ASP.NET",py:"Python",java:"Java",c:"C",cpp:"C++",cc:"C++",h:"C Header",hpp:"C++ Header",cs:"C#",vb:"Visual Basic",fs:"F#",rb:"Ruby",go:"Go",rs:"Rust",kt:"Kotlin",swift:"Swift",dart:"Dart",scala:"Scala",pl:"Perl",pm:"Perl Module",hs:"Haskell",ml:"ML",elm:"Elm",clj:"Clojure",lisp:"Lisp",scm:"Scheme",rkt:"Racket",sh:"Shell Script",bash:"Bash",zsh:"Zsh",fish:"Fish",ps1:"PowerShell",bat:"Batch",cmd:"Command",xml:"XML",xsl:"XSLT",xsd:"XML Schema",sql:"SQL",psql:"PostgreSQL",mysql:"MySQL",asm:"Assembly",s:"Assembly",nasm:"NASM",lua:"Lua",vim:"Vim Script",r:"R",matlab:"MATLAB",julia:"Julia",nim:"Nim",zig:"Zig"};if(a[n||""]||r.includes("javascript")||r.includes("python")||r.includes("x-python")||r.includes("x-perl")||r.includes("x-ruby")||r.includes("x-php")||r.includes("x-c")||r.includes("x-java")||r.includes("x-go")||r.includes("x-rust")||r.includes("x-csharp")||r.includes("x-kotlin")||r.includes("x-swift")||r.includes("x-dart")||r.includes("x-scala")||r.includes("x-shell")||r.includes("x-sql")||r.includes("x-lua")){const e=a[n||""]||"Source Code";return{detectedType:"code",renderStrategy:"native",fileExtension:n,encoding:"utf-8",isInlineable:!0,category:"code",displayName:e,description:`${e} source code`}}if(r.startsWith("text/")||["txt","md","markdown","rst","asciidoc","org","tex","rtf","csv","tsv","ini","cfg","conf","log","yaml","yml","toml","properties","env","gitignore","gitconfig","dockerfile","makefile","readme","license","changelog","authors","contributors","copying","install","news"].includes(n||"")){let e="Text File",t="Plain text document";return r.includes("markdown")||"md"===n||"markdown"===n?(e="Markdown",t="Markdown formatted text"):r.includes("csv")||"csv"===n?(e="CSV Data",t="Comma-separated values data"):"yaml"===n||"yml"===n?(e="YAML Config",t="YAML configuration file"):"toml"===n?(e="TOML Config",t="TOML configuration file"):"log"===n&&(e="Log File",t="Application log file"),{detectedType:"text",renderStrategy:"native",fileExtension:n,encoding:"utf-8",isInlineable:!0,category:"document",displayName:e,description:t}}if(r.startsWith("image/")){let e="Image",t="Image file";return"image/svg+xml"===r||"svg"===n?{detectedType:"svg",renderStrategy:"native",fileExtension:"svg",isInlineable:!0,category:"media",displayName:"SVG Vector",description:"Scalable Vector Graphics"}:("image/webp"===r||"webp"===n?(e="WebP Image",t="WebP compressed image"):"image/avif"===r||"avif"===n?(e="AVIF Image",t="AV1 Image File Format"):r.includes("heic")||r.includes("heif")||"heic"===n||"heif"===n?(e="HEIC Image",t="High Efficiency Image Container"):"image/jpeg"===r||"jpg"===n||"jpeg"===n?(e="JPEG Image",t="JPEG compressed image"):"image/png"===r||"png"===n?(e="PNG Image",t="Portable Network Graphics"):"image/gif"===r||"gif"===n?(e="GIF Animation",t="Graphics Interchange Format"):"image/bmp"===r||"bmp"===n?(e="BMP Bitmap",t="Windows Bitmap"):"image/tiff"===r||"tiff"===n||"tif"===n?(e="TIFF Image",t="Tagged Image File Format"):"image/x-icon"!==r&&"ico"!==n||(e="Icon File",t="Windows Icon"),{detectedType:"image",renderStrategy:"native",fileExtension:n,isInlineable:!0,category:"media",displayName:e,description:t})}if(r.startsWith("audio/")){let e="Audio",t="Audio file";return r.includes("mp3")||"mp3"===n?(e="MP3 Audio",t="MPEG Layer-3 audio"):r.includes("wav")||"wav"===n?(e="WAV Audio",t="Waveform audio file"):r.includes("ogg")||"ogg"===n?(e="OGG Audio",t="Ogg Vorbis audio"):r.includes("flac")||"flac"===n?(e="FLAC Audio",t="Free Lossless Audio Codec"):r.includes("aac")||"aac"===n?(e="AAC Audio",t="Advanced Audio Coding"):r.includes("m4a")||"m4a"===n?(e="M4A Audio",t="MPEG-4 Audio"):"opus"===n&&(e="Opus Audio",t="Opus compressed audio"),{detectedType:"audio",renderStrategy:"native",fileExtension:n,isInlineable:!0,category:"media",displayName:e,description:t}}if(r.startsWith("video/")){let e="Video",t="Video file";return r.includes("mp4")||"mp4"===n?(e="MP4 Video",t="MPEG-4 video"):r.includes("webm")||"webm"===n?(e="WebM Video",t="WebM video format"):r.includes("ogg")||"ogv"===n?(e="OGV Video",t="Ogg video format"):r.includes("avi")||"avi"===n?(e="AVI Video",t="Audio Video Interleave"):r.includes("mov")||"mov"===n?(e="QuickTime Video",t="QuickTime movie"):"mkv"===n?(e="MKV Video",t="Matroska video"):"wmv"===n&&(e="WMV Video",t="Windows Media Video"),{detectedType:"video",renderStrategy:"native",fileExtension:n,isInlineable:!0,category:"media",displayName:e,description:t}}const i=["obj","gltf","glb","stl","3ds","dae","fbx","blend","max","ma","mb","c4d","x3d","wrl","ply"];if(r.startsWith("model/")||i.includes(n||"")){let e="3D Model",t="3D model file";return r.includes("gltf")||"gltf"===n?(e="GLTF Model",t="GL Transmission Format 3D model"):"glb"===n?(e="GLB Model",t="Binary GLTF 3D model"):"obj"===n?(e="OBJ Model",t="Wavefront OBJ 3D model"):"stl"===n?(e="STL Model",t="Stereolithography 3D model"):"fbx"===n?(e="FBX Model",t="Autodesk FBX 3D model"):"blend"===n&&(e="Blender File",t="Blender 3D project file"),{detectedType:"3d",renderStrategy:"native",fileExtension:n,isInlineable:!0,category:"media",displayName:e,description:t}}const o=["ttf","otf","woff","woff2","eot","fon","pfb","pfm"];if(r.includes("font")||o.includes(n||"")){let e="Font File",t="Font file";return"ttf"===n?(e="TrueType Font",t="TrueType font file"):"otf"===n?(e="OpenType Font",t="OpenType font file"):"woff"!==n&&"woff2"!==n||(e="Web Font",t="Web Open Font Format"),{detectedType:"font",renderStrategy:"iframe",fileExtension:n,isInlineable:!1,category:"font",displayName:e,description:t}}const l=["zip","rar","7z","tar","gz","bz2","xz","lzma","lz4","zst","cab","dmg","iso"];if(r.includes("zip")||r.includes("compressed")||r.includes("archive")||l.includes(n||"")){let e="Archive",t="Compressed archive file";return"zip"===n?(e="ZIP Archive",t="ZIP compressed archive"):"rar"===n?(e="RAR Archive",t="WinRAR compressed archive"):"7z"===n?(e="7-Zip Archive",t="7-Zip compressed archive"):"tar"===n?(e="TAR Archive",t="Tape archive file"):"gz"===n&&(e="GZIP Archive",t="GZIP compressed file"),{detectedType:"archive",renderStrategy:"download",fileExtension:n,isInlineable:!1,category:"archive",displayName:e,description:t}}if("application/pdf"===r||"pdf"===n)return{detectedType:"pdf",renderStrategy:"iframe",fileExtension:"pdf",isInlineable:!1,category:"document",displayName:"PDF Document",description:"Portable Document Format"};const c={doc:"Word Document",docx:"Word Document",xls:"Excel Spreadsheet",xlsx:"Excel Spreadsheet",ppt:"PowerPoint Presentation",pptx:"PowerPoint Presentation",odt:"OpenDocument Text",ods:"OpenDocument Spreadsheet",odp:"OpenDocument Presentation"};if(r.includes("officedocument")||r.includes("opendocument")||c[n||""]){return{detectedType:"document",renderStrategy:"download",fileExtension:n,isInlineable:!1,category:"document",displayName:c[n||""]||"Office Document",description:"Microsoft Office or OpenDocument file"}}if(["epub","mobi","azw","azw3","fb2","lit","pdb"].includes(n||""))return{detectedType:"ebook",renderStrategy:"download",fileExtension:n,isInlineable:!1,category:"document",displayName:"E-book",description:"Electronic book file"};if(["exe","msi","app","deb","rpm","dmg","pkg","appimage","flatpak","snap"].includes(n||"")||r.includes("executable"))return{detectedType:"executable",renderStrategy:"download",fileExtension:n,isInlineable:!1,category:"executable",displayName:"Executable File",description:"Application or installer"};const d={db:"Database",sqlite:"SQLite Database",mdb:"Access Database",xsd:"XML Schema",dtd:"Document Type Definition",plist:"Property List",reg:"Registry File",bin:"Binary Data",dat:"Data File",dump:"Memory Dump"};if(d[n||""])return{detectedType:"data",renderStrategy:"download",fileExtension:n,isInlineable:!1,category:"data",displayName:d[n||""]||"Data File",description:"Data or database file"};if(s){if(s.includes("<!DOCTYPE")||s.includes("<html")||s.includes("<head>")||s.includes("<body>"))return{detectedType:"html",renderStrategy:"native",fileExtension:n,isInlineable:!0,category:"document",displayName:"HTML Document",description:"HyperText Markup Language document"};const e=s.trim();if(e.startsWith("{")&&e.includes("}")||e.startsWith("[")&&e.includes("]"))try{return JSON.parse(e),{detectedType:"json",renderStrategy:"native",fileExtension:n,isInlineable:!0,category:"data",displayName:"JSON Data",description:"JavaScript Object Notation data"}}catch{}return s.includes("<?xml")||s.includes("<root")||s.includes("<")&&s.includes(">")?{detectedType:"text",renderStrategy:"native",fileExtension:n,encoding:"utf-8",isInlineable:!0,category:"document",displayName:"XML Document",description:"Extensible Markup Language document"}:s.includes("<svg")||s.includes('xmlns="http://www.w3.org/2000/svg"')?{detectedType:"svg",renderStrategy:"native",fileExtension:n,isInlineable:!0,category:"media",displayName:"SVG Vector",description:"Scalable Vector Graphics"}:{detectedType:"text",renderStrategy:"native",fileExtension:n,encoding:"utf-8",isInlineable:!0,category:"document",displayName:"Text File",description:"Plain text document"}}if(t.length>=4){const e=Array.from(t.slice(0,4)).map(e=>e.toString(16).padStart(2,"0")).join("");if(t.length>=8&&Array.from(t.slice(0,8)).map(e=>e.toString(16).padStart(2,"0")).join(""),"89504e47"===e)return{detectedType:"image",renderStrategy:"native",fileExtension:"png",isInlineable:!0,category:"media",displayName:"PNG Image",description:"Portable Network Graphics"};if(e.startsWith("ffd8"))return{detectedType:"image",renderStrategy:"native",fileExtension:"jpg",isInlineable:!0,category:"media",displayName:"JPEG Image",description:"JPEG compressed image"};if("47494638"===e)return{detectedType:"image",renderStrategy:"native",fileExtension:"gif",isInlineable:!0,category:"media",displayName:"GIF Animation",description:"Graphics Interchange Format"};if("52494646"===e&&t.length>=12){if("WEBP"===Array.from(t.slice(8,12)).map(e=>String.fromCharCode(e)).join(""))return{detectedType:"image",renderStrategy:"native",fileExtension:"webp",isInlineable:!0,category:"media",displayName:"WebP Image",description:"WebP compressed image"}}if(t.length>=4&&"%PDF"===String.fromCharCode(...t.slice(0,4)))return{detectedType:"pdf",renderStrategy:"iframe",fileExtension:"pdf",isInlineable:!1,category:"document",displayName:"PDF Document",description:"Portable Document Format"};if("504b0304"===e||"504b0506"===e||"504b0708"===e)return{detectedType:"archive",renderStrategy:"download",fileExtension:"zip",isInlineable:!1,category:"archive",displayName:"ZIP Archive",description:"ZIP compressed archive"}}return{detectedType:"binary",renderStrategy:"iframe",fileExtension:n,isInlineable:!1,category:"unknown",displayName:"Unknown File",description:`Unknown file type (${r})`}}(n,o,d);return{contentInfo:{...u,mimeType:n},preview:"text"===u.detectedType?d.slice(0,200):void 0}}catch(e){return{contentInfo:{mimeType:"application/octet-stream",detectedType:"unknown",renderStrategy:"iframe",isInlineable:!1},error:e.message}}}class u{constructor(e=100,t=30){Object.defineProperty(this,"cache",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxAge",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e,this.maxAge=60*t*1e3}get(e){const t=this.cache.get(e);return t?Date.now()-t.timestamp>this.maxAge?(this.cache.delete(e),null):t.data:null}set(e,t,s){if(this.cache.size>=this.maxSize){const e=this.cache.keys().next().value;e&&this.cache.delete(e)}this.cache.set(e,{data:t,timestamp:Date.now(),contentType:s})}has(e){const t=this.cache.get(e);return!!t&&(!(Date.now()-t.timestamp>this.maxAge)||(this.cache.delete(e),!1))}delete(e){return this.cache.delete(e)}clear(){this.cache.clear()}getStats(){return{size:this.cache.size,maxSize:this.maxSize,maxAge:this.maxAge}}async fetchContent(e){const t=this.get(e);if(t)return{data:t,contentType:this.cache.get(e)?.contentType||"text/plain"};try{const t=await fetch(e,{headers:{Accept:"application/json","User-Agent":"InscriptionViewer/1.0.0"}});if(!t.ok)throw new Error(`HTTP ${t.status}: ${t.statusText}`);const s=t.headers.get("content-type")||"text/plain";let r;if(s.includes("application/json"))r=await t.json();else if(s.includes("text/"))r=await t.text();else if(s.startsWith("image/")||s.startsWith("audio/")||s.startsWith("video/"))r=e;else{const e=await t.blob();r=URL.createObjectURL(e)}return this.set(e,r,s),{data:r,contentType:s}}catch(e){throw console.error("Failed to fetch content:",e),e}}cleanup(){const e=Date.now(),t=[];this.cache.forEach((s,r)=>{e-s.timestamp>this.maxAge&&t.push(r)}),t.forEach(e=>this.cache.delete(e))}}const h=new u;class m{constructor(e){Object.defineProperty(this,"wallet",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"cache",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"cacheMaxAge",{enumerable:!0,configurable:!0,writable:!0,value:6e5}),this.wallet=e||null}setWallet(e){this.wallet=e}isAvailable(){return null!==this.wallet&&this.wallet.isConnected()}getAddress(){return this.wallet?.getAddress()||null}async getInscriptionContent(e){if(!this.isAvailable())return console.warn("LaserEyes wallet not available for inscription content fetch"),null;const t=this.cache.get(e);if(t&&Date.now()-t.timestamp<this.cacheMaxAge)return console.log(`🎯 Using cached LaserEyes content for inscription ${e}`),t.data;try{console.log(`🔥 Fetching inscription content via LaserEyes for: ${e}`);const t=await this.wallet.getInscriptionContent(e);if(!t)return console.warn(`No content returned from LaserEyes for inscription: ${e}`),null;let s,r;"string"==typeof t?(s=t,r="text/plain"):t.content&&t.contentType?(s=t.content,r=t.contentType):t instanceof ArrayBuffer||t.buffer?(s=t instanceof ArrayBuffer?t:t.buffer,r="application/octet-stream"):(s=JSON.stringify(t),r="application/json");const n={content:s,contentType:r,inscriptionId:e};return this.cache.set(e,{data:n,timestamp:Date.now()}),console.log(`✅ Successfully fetched inscription content via LaserEyes for: ${e}`),n}catch(t){return console.error(`❌ Failed to fetch inscription content via LaserEyes for ${e}:`,t),null}}clearCache(e){e?this.cache.delete(e):this.cache.clear()}getCacheStats(){return{size:this.cache.size,entries:Array.from(this.cache.keys())}}}const p=new m;function x({content:r,mimeType:n,fileExtension:a,maxHeight:o=400,showControls:l=!1}){const[c,d]=t.useState(!1),u=t.useMemo(()=>n.includes("javascript")||n.includes("json")||n.includes("xml")||n.includes("html")||["javascript","typescript","json","html","css","xml","yaml","python","java","c","cpp","rust","go"].some(e=>n.includes(e))||["js","ts","jsx","tsx","json","html","css","xml","yaml","yml","py","java","c","cpp","rs","go","php","rb","sql"].includes(a||""),[n,a]),h=t.useMemo(()=>{if(n.includes("javascript"))return"javascript";if(n.includes("typescript"))return"typescript";if(n.includes("json"))return"json";if(n.includes("html"))return"html";if(n.includes("css"))return"css";if(n.includes("xml"))return"xml";if(n.includes("yaml"))return"yaml";if(n.includes("python"))return"python";return{js:"javascript",ts:"typescript",jsx:"javascript",tsx:"typescript",json:"json",html:"html",css:"css",xml:"xml",yaml:"yaml",yml:"yaml",py:"python",java:"java",c:"c",cpp:"cpp",rs:"rust",go:"go",php:"php",rb:"ruby",sql:"sql"}[a||""]||"text"},[n,a]);return e.jsxs("div",{className:"w-full h-full flex flex-col",children:[l&&e.jsxs("div",{className:"flex justify-between items-center p-2 border-b bg-gray-50 dark:bg-gray-800",children:[e.jsxs("div",{className:"text-xs text-gray-600 dark:text-gray-400",children:[e.jsx("span",{className:"font-mono",children:h}),e.jsxs("span",{className:"ml-2",children:["(",r.length.toLocaleString()," chars)"]})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsxs(i,{variant:"ghost",size:"sm",onClick:async()=>{try{await navigator.clipboard.writeText(r),d(!0),setTimeout(()=>d(!1),2e3)}catch(e){console.error("Failed to copy:",e)}},className:"h-6 px-2 text-xs",children:[e.jsx(s.Copy,{className:"h-3 w-3 mr-1"}),c?"Copied!":"Copy"]}),e.jsxs(i,{variant:"ghost",size:"sm",onClick:()=>{const e=new Blob([r],{type:n}),t=URL.createObjectURL(e),s=document.createElement("a");s.href=t,s.download=`content.${a||"txt"}`,document.body.appendChild(s),s.click(),document.body.removeChild(s),URL.revokeObjectURL(t)},className:"h-6 px-2 text-xs",children:[e.jsx(s.Download,{className:"h-3 w-3 mr-1"}),"Download"]})]})]}),e.jsx("div",{className:"flex-1 overflow-hidden w-full",style:{maxHeight:o-(l?70:0),minHeight:"100px"},children:e.jsx("pre",{className:"text-xs p-4 w-full h-full overflow-auto font-mono whitespace-pre-wrap break-words scrollbar-hide "+(u?"text-gray-800 dark:text-gray-200":"text-gray-900 dark:text-gray-100"),style:{scrollbarWidth:"none",msOverflowStyle:"none"},children:r})})]})}function g(e,t="Unknown"){if(!e||"string"!=typeof e)return t;const s=e.split("/");return s.length<2||!s[1]?t:s[1].toUpperCase()}function f(e,t="Unknown"){if(!e||"string"!=typeof e)return t;return(e.startsWith(".")?e.slice(1):e).toUpperCase()}function b(e,t,s="Unknown"){if(t){const e=f(t,"");if(e&&"Unknown"!==e)return e}if(e){const t=g(e,"");if(t&&"Unknown"!==t)return t}return s}function y(e){if(!e||!Number.isFinite(e)||e<0)return"0 B";const t=["B","KB","MB","GB","TB"];let s=e,r=0;for(;s>=1024&&r<t.length-1;)s/=1024,r++;return`${s.toFixed(0===r?0:1)} ${t[r]}`}function v({src:r,alt:n="Inscription image",mimeType:a,fileExtension:o,maxHeight:l=400,showControls:c=!1}){const[d,u]=t.useState(1),[h,m]=t.useState(0),[p,x]=t.useState({x:0,y:0}),[f,b]=t.useState(!1),[y,v]=t.useState(!1),[w,j]=t.useState(!1),[N,k]=t.useState(null),[T,C]=t.useState(!1),[S,A]=t.useState({x:0,y:0}),R=t.useRef(null),E=t.useRef(null),I=t.useCallback(e=>{v(!0);const t=e.target;k({width:t.naturalWidth,height:t.naturalHeight})},[]),L=t.useCallback(()=>{j(!0),v(!1)},[]),M=t.useCallback(()=>{u(1),m(0),x({x:0,y:0})},[]),P=t.useCallback(()=>{u(e=>Math.min(5,e+.2))},[]),D=t.useCallback(()=>{u(e=>{const t=Math.max(.1,e-.2);return t<=1&&x({x:0,y:0}),t})},[]),z=t.useCallback(()=>{m(e=>(e+90)%360),x({x:0,y:0})},[]),O=t.useCallback(e=>{d>1&&(C(!0),A({x:e.clientX-p.x,y:e.clientY-p.y}),e.preventDefault())},[d,p]),_=t.useCallback(e=>{T&&d>1&&x({x:e.clientX-S.x,y:e.clientY-S.y})},[T,S,d]),F=t.useCallback(()=>{C(!1)},[]);t.useEffect(()=>{const e=e=>{if(y)switch(e.key){case"+":case"=":e.preventDefault(),P();break;case"-":e.preventDefault(),D();break;case"r":case"R":e.preventDefault(),z();break;case"Escape":f&&b(!1);break;case"0":e.preventDefault(),M()}};if(f)return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[y,f,P,D,z,M]);const U=t.useCallback(e=>{if(e.ctrlKey||e.metaKey){e.preventDefault();const t=e.deltaY>0?-.1:.1;u(e=>Math.max(.1,Math.min(5,e+t)))}},[]),B=f?"100vh":l-(c&&y?70:0)+"px";return w?e.jsx("div",{className:"w-full h-full flex items-center justify-center bg-gray-100 dark:bg-gray-800 rounded-lg",children:e.jsxs("div",{className:"text-center text-gray-500",children:[e.jsx("div",{className:"text-4xl mb-4 opacity-50",children:"🖼️"}),e.jsx("div",{className:"text-sm font-medium mb-1",children:"Failed to load image"}),e.jsxs("div",{className:"text-xs text-gray-400",children:[a," • ",o]}),e.jsx(i,{variant:"outline",size:"sm",className:"mt-3",onClick:()=>{j(!1),v(!1)},children:"Retry"})]})}):e.jsxs("div",{className:"w-full h-full flex flex-col "+(f?"fixed inset-0 z-50 bg-black":"rounded-lg overflow-hidden border"),children:[c&&y&&e.jsxs("div",{className:"flex justify-between items-center p-3 border-b bg-gray-50 dark:bg-gray-800",children:[e.jsxs("div",{className:"text-xs text-gray-600 dark:text-gray-400 space-x-3",children:[e.jsx("span",{className:"font-mono bg-gray-200 dark:bg-gray-700 px-2 py-1 rounded",children:g(a)}),N&&e.jsxs("span",{children:[N.width," × ",N.height]}),e.jsxs("span",{children:[Math.round(100*d),"%"]})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(i,{variant:"ghost",size:"sm",onClick:D,className:"h-8 px-2 text-xs",disabled:d<=.2,title:"Zoom out (-)",children:e.jsx(s.ZoomOut,{className:"h-3 w-3"})}),e.jsx(i,{variant:"ghost",size:"sm",onClick:P,className:"h-8 px-2 text-xs",disabled:d>=5,title:"Zoom in (+)",children:e.jsx(s.ZoomIn,{className:"h-3 w-3"})}),e.jsx(i,{variant:"ghost",size:"sm",onClick:z,className:"h-8 px-2 text-xs",title:"Rotate (R)",children:e.jsx(s.RotateCw,{className:"h-3 w-3"})}),e.jsx(i,{variant:"ghost",size:"sm",onClick:M,className:"h-8 px-2 text-xs",title:"Reset (0)",children:"Reset"}),d>1&&e.jsx(i,{variant:"ghost",size:"sm",className:"h-8 px-2 text-xs pointer-events-none",title:"Pan mode active",children:e.jsx(s.Move,{className:"h-3 w-3"})}),e.jsx(i,{variant:"ghost",size:"sm",onClick:()=>b(!f),className:"h-8 px-2 text-xs",title:"Fullscreen",children:e.jsx(s.Maximize2,{className:"h-3 w-3"})}),e.jsx(i,{variant:"ghost",size:"sm",onClick:async()=>{try{const e=await fetch(r),t=await e.blob(),s=URL.createObjectURL(t),n=document.createElement("a");n.href=s,n.download=`image.${o||"png"}`,document.body.appendChild(n),n.click(),document.body.removeChild(n),URL.revokeObjectURL(s)}catch(e){console.error("Failed to download:",e)}},className:"h-8 px-2 text-xs",title:"Download",children:e.jsx(s.Download,{className:"h-3 w-3"})})]})]}),e.jsxs("div",{ref:E,className:"flex-1 relative overflow-hidden bg-gray-50 dark:bg-gray-900",style:{height:B,minHeight:f?"100vh":"200px",cursor:d>1?T?"grabbing":"grab":"default"},onMouseDown:O,onMouseMove:_,onMouseUp:F,onMouseLeave:F,onWheel:U,children:[e.jsx("div",{className:"absolute inset-0 flex items-center justify-center transition-transform duration-200",style:{transform:`translate(${p.x}px, ${p.y}px)`},children:e.jsx("img",{ref:R,src:r,alt:n,className:"max-w-full max-h-full object-contain transition-transform duration-200 select-none",style:{transform:`scale(${d}) rotate(${h}deg)`,imageRendering:d>2?"pixelated":"auto"},onLoad:I,onError:L,draggable:!1})}),!y&&!w&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsxs("div",{className:"text-center text-gray-500",children:[e.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500 mx-auto mb-4"}),e.jsx("div",{className:"text-sm font-medium",children:"Loading image..."}),e.jsx("div",{className:"text-xs text-gray-400 mt-1",children:"Please wait"})]})}),f&&e.jsxs("div",{className:"absolute top-4 right-4 flex gap-2",children:[e.jsx("div",{className:"bg-black/70 text-white text-xs px-3 py-1 rounded",children:"Press ESC to exit • Use +/- to zoom • R to rotate"}),e.jsx(i,{variant:"ghost",size:"sm",onClick:()=>b(!1),className:"bg-black/70 text-white hover:bg-black/90 border-white/20",children:"✕ Exit"})]}),1!==d&&!f&&e.jsxs("div",{className:"absolute bottom-4 left-4 bg-black/70 text-white text-xs px-2 py-1 rounded",children:[Math.round(100*d),"%"]})]})]})}function w({src:r,mimeType:n,fileExtension:a,maxHeight:o=400,showControls:l=!0}){const c=t.useRef(null),[d,u]=t.useState(null),[h,m]=t.useState(!0),[p,x]=t.useState(!1),[g,f]=t.useState(!1),[b,y]=t.useState(!1),[v,w]=t.useState(null),j=()=>{const e=c.current;e&&(p?e.pause():e.play())},N=async()=>{try{const e=await fetch(r),t=await e.blob(),s=URL.createObjectURL(t),n=document.createElement("a");n.href=s,n.download=`video.${a||"mp4"}`,document.body.appendChild(n),n.click(),document.body.removeChild(n),URL.revokeObjectURL(s)}catch(e){console.error("Failed to download:",e)}};return d?e.jsx("div",{className:"w-full h-full flex items-center justify-center bg-gray-100 dark:bg-gray-800",children:e.jsxs("div",{className:"text-center text-gray-500",children:[e.jsx("div",{className:"text-2xl mb-2",children:"🎬"}),e.jsx("div",{className:"text-sm",children:"Failed to load video"}),e.jsxs("div",{className:"text-xs mt-1 text-gray-400",children:[n," • ",a]}),e.jsx("div",{className:"mt-3",children:e.jsxs(i,{variant:"outline",size:"sm",onClick:N,className:"text-xs",children:[e.jsx(s.Download,{className:"h-3 w-3 mr-1"}),"Download Video"]})})]})}):e.jsx("div",{className:"w-full h-full flex flex-col rounded-lg overflow-hidden border border-gray-200 dark:border-gray-700",children:e.jsxs("div",{className:"flex-1 relative bg-black rounded-lg overflow-hidden",onMouseEnter:()=>y(!0),onMouseLeave:()=>y(!1),children:[h&&e.jsx("div",{className:"absolute inset-0 z-20 flex items-center justify-center",children:e.jsxs("div",{className:"text-center text-white",children:[e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-white mx-auto mb-2"}),e.jsx("div",{className:"text-sm",children:"Loading video..."})]})}),e.jsx("video",{ref:c,src:r,className:"w-full h-full object-contain rounded-lg",style:{maxHeight:o},onLoadedMetadata:e=>{const t=e.currentTarget;w({width:t.videoWidth,height:t.videoHeight}),m(!1)},onCanPlay:()=>{m(!1)},onError:()=>{u("Failed to load video"),m(!1)},onPlay:()=>{x(!0)},onPause:()=>{x(!1)},preload:"metadata",onClick:j}),!h&&e.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center pointer-events-none",children:e.jsx(i,{variant:"default",size:"lg",onClick:j,className:"pointer-events-auto bg-white hover:bg-gray-100 text-black border-2 border-gray-300 hover:border-gray-400 rounded-full p-6 transition-all duration-300 shadow-2xl backdrop-blur-sm",children:p?e.jsx(s.Pause,{className:"h-12 w-12"}):e.jsx(s.Play,{className:"h-12 w-12 ml-1"})})}),b&&!h&&e.jsx("div",{className:"absolute bottom-0 left-0 right-0 z-10 bg-gradient-to-t from-black/80 via-black/40 to-transparent p-4 transition-all duration-200",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(i,{variant:"ghost",size:"sm",onClick:j,className:"text-white hover:bg-white/20 h-8 w-8 p-0",children:p?e.jsx(s.Pause,{className:"h-4 w-4"}):e.jsx(s.Play,{className:"h-4 w-4"})})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(i,{variant:"ghost",size:"sm",onClick:()=>{const e=c.current;e&&(e.muted=!e.muted,f(e.muted))},className:"text-white hover:bg-white/20 h-8 w-8 p-0",children:g?e.jsx(s.VolumeX,{className:"h-4 w-4"}):e.jsx(s.Volume2,{className:"h-4 w-4"})}),e.jsx(i,{variant:"ghost",size:"sm",onClick:()=>{const e=c.current;e&&(document.fullscreenElement?document.exitFullscreen():e.requestFullscreen())},className:"text-white hover:bg-white/20 h-8 w-8 p-0",children:e.jsx(s.Maximize2,{className:"h-4 w-4"})})]})]})})]})})}function j({src:r,mimeType:n,fileExtension:a,maxHeight:o=300,showControls:l=!0}){console.log("🎵 AudioRenderer render:",{src:r.substring(0,50),showControls:l,mimeType:n,fileExtension:a});const c=t.useRef(null),[d,u]=t.useState(null),[h,m]=t.useState(!0),[p,x]=t.useState(!1),[b,y]=t.useState(!1),[v,w]=t.useState(!1),[j,N]=t.useState(0);t.useEffect(()=>{console.log("🎵 AudioRenderer props:",{showControls:l,shouldShowControls:true,mimeType:n,fileExtension:a,src:r})},[l,n,a,r]);const k=()=>{const e=c.current;e&&(p?e.pause():e.play())},T=async()=>{try{const e=await fetch(r),t=await e.blob(),s=URL.createObjectURL(t),n=document.createElement("a");n.href=s,n.download=`audio.${a||"mp3"}`,document.body.appendChild(n),n.click(),document.body.removeChild(n),URL.revokeObjectURL(s)}catch(e){console.error("Failed to download:",e)}};return t.useMemo(()=>{const e=a?.toLowerCase()||"";return["mp3","wav","ogg","m4a","aac","flac","webm","opus"].includes(e)||n.startsWith("audio/")},[n,a])?d?e.jsx("div",{className:"w-full h-full flex items-center justify-center bg-gray-100 dark:bg-gray-800",children:e.jsxs("div",{className:"text-center text-gray-500",children:[e.jsx("div",{className:"text-2xl mb-2",children:"⚠️"}),e.jsx("div",{className:"text-sm text-red-600 dark:text-red-400",children:"Audio Load Error"}),e.jsx("div",{className:"text-xs mt-1 text-gray-400",children:d}),e.jsxs("div",{className:"text-xs mt-1 text-gray-400",children:[g(n)," • ",f(a)]}),e.jsx("div",{className:"mt-3",children:e.jsxs(i,{variant:"outline",size:"sm",onClick:T,className:"text-xs",children:[e.jsx(s.Download,{className:"h-3 w-3 mr-1"}),"Download Audio"]})})]})}):e.jsx("div",{className:"w-full h-full flex flex-col rounded-lg overflow-hidden border border-gray-200 dark:border-gray-700",children:e.jsxs("div",{className:"flex-1 relative bg-gradient-to-br from-blue-50 to-purple-50 dark:from-gray-800 dark:to-gray-900 rounded-lg",style:{minHeight:"120px"},onMouseEnter:()=>w(!0),onMouseLeave:()=>w(!1),children:[e.jsx("audio",{ref:c,src:r,onLoadedMetadata:e=>{const t=e.currentTarget;t.duration>0&&(N(t.duration),m(!1),console.log("✅ Audio metadata loaded - duration:",t.duration))},onCanPlay:()=>{m(!1),console.log("✅ Audio can play")},onError:e=>{console.error("❌ Audio error:",e),u("Failed to load audio"),m(!1)},onPlay:()=>{x(!0)},onPause:()=>{x(!1)},preload:"metadata",className:"hidden"}),e.jsx("div",{className:"absolute inset-0 flex items-center justify-center cursor-pointer rounded-lg",onClick:k,children:e.jsxs("div",{className:"text-center",children:[h?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-4xl mb-4 animate-pulse",children:"🔄"}),e.jsx("div",{className:"text-lg font-medium text-gray-700 dark:text-gray-300",children:"Loading Audio..."})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-6xl mb-4 opacity-30",children:"🎵"}),e.jsx("div",{className:"text-lg font-medium text-gray-700 dark:text-gray-300",children:p?"Now Playing":"Audio Player"})]}),e.jsxs("div",{className:"text-sm text-gray-500 dark:text-gray-400 mt-1 opacity-75",children:[g(n)," • ",f(a)]})]})}),!h&&e.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center pointer-events-none",children:e.jsx(i,{variant:"default",size:"lg",onClick:k,className:"pointer-events-auto bg-white hover:bg-gray-100 text-black border-2 border-gray-300 hover:border-gray-400 rounded-full p-6 transition-all duration-300 shadow-2xl backdrop-blur-sm",children:p?e.jsx(s.Pause,{className:"h-12 w-12"}):e.jsx(s.Play,{className:"h-12 w-12 ml-1"})})}),v&&!h&&e.jsx("div",{className:"absolute bottom-0 left-0 right-0 z-10 bg-gradient-to-t from-black/80 via-black/40 to-transparent p-4 transition-all duration-200",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(i,{variant:"ghost",size:"sm",onClick:k,className:"text-white hover:bg-white/20 h-8 w-8 p-0",children:p?e.jsx(s.Pause,{className:"h-4 w-4"}):e.jsx(s.Play,{className:"h-4 w-4"})}),j>0&&e.jsxs("span",{className:"text-white text-xs",children:[Math.floor(j/60),":",(j%60).toFixed(0).padStart(2,"0")]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(i,{variant:"ghost",size:"sm",onClick:()=>{const e=c.current;e&&(e.muted=!e.muted,y(e.muted))},className:"text-white hover:bg-white/20 h-8 w-8 p-0",children:b?e.jsx(s.VolumeX,{className:"h-4 w-4"}):e.jsx(s.Volume2,{className:"h-4 w-4"})}),e.jsx(i,{variant:"ghost",size:"sm",onClick:T,className:"text-white hover:bg-white/20 h-8 w-8 p-0",children:e.jsx(s.Download,{className:"h-4 w-4"})})]})]})})]})}):e.jsx("div",{className:"w-full h-full flex items-center justify-center bg-gray-100 dark:bg-gray-800",children:e.jsxs("div",{className:"text-center text-gray-500",children:[e.jsx("div",{className:"text-2xl mb-2",children:"🎵"}),e.jsx("div",{className:"text-sm",children:"Audio format not supported"}),e.jsxs("div",{className:"text-xs mt-1 text-gray-400",children:[g(n)," • ",f(a)]}),e.jsx("div",{className:"mt-3",children:e.jsxs(i,{variant:"outline",size:"sm",onClick:T,className:"text-xs",children:[e.jsx(s.Download,{className:"h-3 w-3 mr-1"}),"Download Audio"]})})]})})}function N({content:r,mimeType:n,maxHeight:a=400,showControls:o=!1}){const[l,c]=t.useState(null),[d,u]=t.useState(null),[h,m]=t.useState(new Set),[p,x]=t.useState(!1),[g,f]=t.useState(!1);t.useEffect(()=>{try{const e=JSON.parse(r);c(e),u(null)}catch(e){u(e.message),c(null)}},[r]);const b=async()=>{try{await navigator.clipboard.writeText(r),f(!0),setTimeout(()=>f(!1),2e3)}catch(e){console.error("Failed to copy:",e)}},y=e=>{const t=new Set(h);t.has(e)?t.delete(e):t.add(e),m(t)},v=(t,s="",r=0)=>{if(null===t)return e.jsx("span",{className:"text-gray-500",children:"null"});if("boolean"==typeof t)return e.jsx("span",{className:"text-blue-600 dark:text-blue-400",children:t.toString()});if("number"==typeof t)return e.jsx("span",{className:"text-purple-600 dark:text-purple-400",children:t});if("string"==typeof t)return e.jsxs("span",{className:"text-green-600 dark:text-green-400",children:['"',t,'"']});if(Array.isArray(t)){const n=h.has(s);return e.jsxs("div",{children:[e.jsx("span",{className:"cursor-pointer hover:bg-gray-100 dark:hover:bg-gray-700 px-1 rounded",onClick:()=>y(s),children:e.jsxs("span",{className:"text-gray-500",children:[n?"►":"▼"," [",t.length,"]"]})}),!n&&e.jsx("div",{className:"ml-4",children:t.map((n,a)=>e.jsxs("div",{className:"font-mono text-sm",children:[e.jsxs("span",{className:"text-gray-400",children:[a,": "]}),v(n,`${s}[${a}]`,r+1),a<t.length-1&&e.jsx("span",{className:"text-gray-500",children:","})]},a))})]})}if("object"==typeof t){const n=Object.keys(t),a=h.has(s);return e.jsxs("div",{children:[e.jsx("span",{className:"cursor-pointer hover:bg-gray-100 dark:hover:bg-gray-700 px-1 rounded",onClick:()=>y(s),children:e.jsxs("span",{className:"text-gray-500",children:[a?"►":"▼"," ",`{${n.length}}`]})}),!a&&e.jsx("div",{className:"ml-4",children:n.map((a,i)=>e.jsxs("div",{className:"font-mono text-sm",children:[e.jsxs("span",{className:"text-blue-600 dark:text-blue-400",children:['"',a,'"']}),e.jsx("span",{className:"text-gray-500",children:": "}),v(t[a],s?`${s}.${a}`:a,r+1),i<n.length-1&&e.jsx("span",{className:"text-gray-500",children:","})]},a))})]})}return e.jsx("span",{children:String(t)})};return d?e.jsxs("div",{className:"w-full h-full flex flex-col bg-white dark:bg-gray-900",children:[o&&e.jsxs("div",{className:"flex justify-between items-center p-2 border-b bg-red-50 dark:bg-red-900/20",children:[e.jsx("div",{className:"text-xs text-red-600 dark:text-red-400",children:e.jsx("span",{className:"font-mono",children:"Invalid JSON"})}),e.jsxs(i,{variant:"ghost",size:"sm",onClick:b,className:"h-6 px-2 text-xs",children:[e.jsx(s.Copy,{className:"h-3 w-3 mr-1"}),"Copy Raw"]})]}),e.jsxs("div",{className:"flex-1 p-4",children:[e.jsx("div",{className:"text-red-600 dark:text-red-400 mb-2",children:"JSON Parse Error:"}),e.jsx("div",{className:"text-sm text-red-500 mb-4",children:d}),e.jsx("pre",{className:"text-xs font-mono bg-gray-100 dark:bg-gray-800 p-3 rounded overflow-auto whitespace-pre-wrap scrollbar-hide",style:{scrollbarWidth:"none",msOverflowStyle:"none"},children:r})]})]}):e.jsxs("div",{className:"w-full h-full flex flex-col",children:[o&&e.jsxs("div",{className:"flex justify-between items-center p-2 border-b bg-gray-50 dark:bg-gray-800",children:[e.jsxs("div",{className:"text-xs text-gray-600 dark:text-gray-400",children:[e.jsx("span",{className:"font-mono",children:"JSON"}),e.jsxs("span",{className:"ml-2",children:["(",r.length.toLocaleString()," chars)"]})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsxs(i,{variant:"ghost",size:"sm",onClick:()=>{if(p)m(new Set);else{const e=new Set,t=(s,r="")=>{"object"==typeof s&&null!==s&&(r&&e.add(r),Object.keys(s).forEach(e=>{const n=r?`${r}.${e}`:e;t(s[e],n)}))};l&&t(l),m(e)}x(!p)},className:"h-6 px-2 text-xs",children:[p?e.jsx(s.Expand,{className:"h-3 w-3 mr-1"}):e.jsx(s.Minimize,{className:"h-3 w-3 mr-1"}),p?"Expand":"Collapse"]}),e.jsxs(i,{variant:"ghost",size:"sm",onClick:b,className:"h-6 px-2 text-xs",children:[e.jsx(s.Copy,{className:"h-3 w-3 mr-1"}),g?"Copied!":"Copy"]}),e.jsxs(i,{variant:"ghost",size:"sm",onClick:()=>{const e=new Blob([r],{type:"application/json"}),t=URL.createObjectURL(e),s=document.createElement("a");s.href=t,s.download="data.json",document.body.appendChild(s),s.click(),document.body.removeChild(s),URL.revokeObjectURL(t)},className:"h-6 px-2 text-xs",children:[e.jsx(s.Download,{className:"h-3 w-3 mr-1"}),"Download"]})]})]}),e.jsx("div",{className:"flex-1 overflow-hidden p-4 font-mono text-sm w-full",style:{maxHeight:a-(o?60:0),minHeight:"100px"},children:e.jsx("div",{className:"w-full h-full overflow-auto scrollbar-hide",style:{scrollbarWidth:"none",msOverflowStyle:"none"},children:l&&v(l)})})]})}function k({content:r,src:n,mimeType:a,maxHeight:o=400,showControls:l=!1}){const[c,d]=t.useState(!1),[u,h]=t.useState(null),m=t.useRef(null),p=t.useMemo(()=>{if(!r)return n;try{const e=new Blob([r],{type:"text/html"});return URL.createObjectURL(e)}catch(e){return h(e.message),null}},[r,n]);t.useEffect(()=>()=>{p&&p.startsWith("blob:")&&URL.revokeObjectURL(p)},[p]);return u?e.jsx("div",{className:"w-full h-full flex items-center justify-center bg-gray-100 dark:bg-gray-800",children:e.jsxs("div",{className:"text-center text-gray-500",children:[e.jsx("div",{className:"text-2xl mb-2",children:"🌐"}),e.jsx("div",{className:"text-sm",children:"Failed to render HTML"}),e.jsx("div",{className:"text-xs mt-1 text-gray-400",children:u})]})}):e.jsxs("div",{className:"w-full h-full flex flex-col",children:[l&&e.jsxs("div",{className:"flex justify-between items-center p-2 border-b bg-gray-50 dark:bg-gray-800",children:[e.jsxs("div",{className:"text-xs text-gray-600 dark:text-gray-400",children:[e.jsx("span",{className:"font-mono",children:"HTML"}),r&&e.jsxs("span",{className:"ml-2",children:["(",r.length.toLocaleString()," chars)"]})]}),e.jsxs("div",{className:"flex gap-1",children:[r&&e.jsxs(i,{variant:"ghost",size:"sm",onClick:()=>d(!c),className:"h-6 px-2 text-xs",children:[c?e.jsx(s.Eye,{className:"h-3 w-3 mr-1"}):e.jsx(s.EyeOff,{className:"h-3 w-3 mr-1"}),c?"Rendered":"Source"]}),e.jsxs(i,{variant:"ghost",size:"sm",onClick:()=>{p&&window.open(p,"_blank")},className:"h-6 px-2 text-xs",children:[e.jsx(s.ExternalLink,{className:"h-3 w-3 mr-1"}),"Open"]}),r&&e.jsxs(i,{variant:"ghost",size:"sm",onClick:()=>{const e=new Blob([r||""],{type:"text/html"}),t=URL.createObjectURL(e),s=document.createElement("a");s.href=t,s.download="content.html",document.body.appendChild(s),s.click(),document.body.removeChild(s),URL.revokeObjectURL(t)},className:"h-6 px-2 text-xs",children:[e.jsx(s.Download,{className:"h-3 w-3 mr-1"}),"Download"]})]})]}),e.jsx("div",{className:"flex-1 overflow-hidden",style:{maxHeight:o-(l?60:0),minHeight:"200px"},children:c&&r?e.jsx("pre",{className:"text-xs p-4 h-full overflow-auto font-mono whitespace-pre-wrap break-words bg-gray-50 dark:bg-gray-900 text-gray-800 dark:text-gray-200 scrollbar-hide",style:{scrollbarWidth:"none",msOverflowStyle:"none"},children:r}):e.jsx("iframe",{ref:m,src:p||void 0,className:"w-full h-full border-0",sandbox:"allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox",title:"HTML Content",onError:()=>h("Failed to load HTML content")})})]})}function T(e,t){if(t===r.TrianglesDrawMode)return console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."),e;if(t===r.TriangleFanDrawMode||t===r.TriangleStripDrawMode){let s=e.getIndex();if(null===s){const t=[],r=e.getAttribute("position");if(void 0===r)return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible."),e;for(let e=0;e<r.count;e++)t.push(e);e.setIndex(t),s=e.getIndex()}const n=s.count-2,a=[];if(t===r.TriangleFanDrawMode)for(let e=1;e<=n;e++)a.push(s.getX(0)),a.push(s.getX(e)),a.push(s.getX(e+1));else for(let e=0;e<n;e++)e%2==0?(a.push(s.getX(e)),a.push(s.getX(e+1)),a.push(s.getX(e+2))):(a.push(s.getX(e+2)),a.push(s.getX(e+1)),a.push(s.getX(e)));a.length/3!==n&&console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.");const i=e.clone();return i.setIndex(a),i.clearGroups(),i}return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:",t),e}class C extends r.Loader{constructor(e){super(e),this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register(function(e){return new L(e)}),this.register(function(e){return new B(e)}),this.register(function(e){return new H(e)}),this.register(function(e){return new $(e)}),this.register(function(e){return new P(e)}),this.register(function(e){return new D(e)}),this.register(function(e){return new z(e)}),this.register(function(e){return new O(e)}),this.register(function(e){return new I(e)}),this.register(function(e){return new _(e)}),this.register(function(e){return new M(e)}),this.register(function(e){return new U(e)}),this.register(function(e){return new F(e)}),this.register(function(e){return new R(e)}),this.register(function(e){return new G(e)}),this.register(function(e){return new q(e)})}load(e,t,s,n){const a=this;let i;if(""!==this.resourcePath)i=this.resourcePath;else if(""!==this.path){const t=r.LoaderUtils.extractUrlBase(e);i=r.LoaderUtils.resolveURL(t,this.path)}else i=r.LoaderUtils.extractUrlBa