@lionrapid/core 0.2.1 → 0.3.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/dist/browser/auto-translator.d.ts.map +1 -1
  2. package/dist/browser/auto-translator.js +15 -4
  3. package/dist/browser/auto-translator.js.map +1 -1
  4. package/dist/browser/block-extractor.d.ts.map +1 -1
  5. package/dist/browser/block-extractor.js +6 -0
  6. package/dist/browser/block-extractor.js.map +1 -1
  7. package/dist/browser/editor/editor-api.d.ts +31 -1
  8. package/dist/browser/editor/editor-api.d.ts.map +1 -1
  9. package/dist/browser/editor/editor-api.js +43 -1
  10. package/dist/browser/editor/editor-api.js.map +1 -1
  11. package/dist/browser/editor/editor-init.js +25 -0
  12. package/dist/browser/editor/editor-init.js.map +1 -1
  13. package/dist/browser/editor/editor-styles.d.ts +1 -1
  14. package/dist/browser/editor/editor-styles.d.ts.map +1 -1
  15. package/dist/browser/editor/editor-styles.js +55 -0
  16. package/dist/browser/editor/editor-styles.js.map +1 -1
  17. package/dist/browser/editor/live-preview.d.ts.map +1 -1
  18. package/dist/browser/editor/live-preview.js +20 -3
  19. package/dist/browser/editor/live-preview.js.map +1 -1
  20. package/dist/browser/editor/sidebar.d.ts +20 -1
  21. package/dist/browser/editor/sidebar.d.ts.map +1 -1
  22. package/dist/browser/editor/sidebar.js +147 -9
  23. package/dist/browser/editor/sidebar.js.map +1 -1
  24. package/dist/browser/lionrapid.auto.dev.js +125 -311
  25. package/dist/browser/lionrapid.auto.dev.js.map +3 -3
  26. package/dist/browser/lionrapid.auto.js +125 -311
  27. package/dist/browser/lionrapid.auto.js.map +3 -3
  28. package/dist/browser/lionrapid.auto.min.js +3 -3
  29. package/dist/browser/lionrapid.auto.min.js.map +4 -4
  30. package/dist/browser/lionrapid.editor.js +274 -181
  31. package/dist/browser/lionrapid.editor.js.map +3 -3
  32. package/dist/browser/lionrapid.editor.min.js +58 -3
  33. package/dist/browser/lionrapid.editor.min.js.map +4 -4
  34. package/dist/browser/lionrapid.esm.js +108 -294
  35. package/dist/browser/lionrapid.esm.js.map +3 -3
  36. package/dist/browser/lionrapid.esm.min.js +2 -2
  37. package/dist/browser/lionrapid.esm.min.js.map +4 -4
  38. package/dist/browser/lionrapid.iife.dev.js +108 -294
  39. package/dist/browser/lionrapid.iife.dev.js.map +3 -3
  40. package/dist/browser/lionrapid.iife.js +108 -294
  41. package/dist/browser/lionrapid.iife.js.map +3 -3
  42. package/dist/browser/lionrapid.iife.min.js +2 -2
  43. package/dist/browser/lionrapid.iife.min.js.map +4 -4
  44. package/dist/browser/lionrapid.umd.js +108 -294
  45. package/dist/browser/lionrapid.umd.js.map +3 -3
  46. package/dist/browser/lionrapid.umd.min.js +2 -2
  47. package/dist/browser/lionrapid.umd.min.js.map +4 -4
  48. package/dist/browser/markup-parser.d.ts +9 -5
  49. package/dist/browser/markup-parser.d.ts.map +1 -1
  50. package/dist/browser/markup-parser.js +19 -23
  51. package/dist/browser/markup-parser.js.map +1 -1
  52. package/dist/content/canonical-tag.d.ts +34 -0
  53. package/dist/content/canonical-tag.d.ts.map +1 -0
  54. package/dist/content/canonical-tag.js +57 -0
  55. package/dist/content/canonical-tag.js.map +1 -0
  56. package/dist/content/index.d.ts +1 -4
  57. package/dist/content/index.d.ts.map +1 -1
  58. package/dist/content/index.js +3 -1
  59. package/dist/content/index.js.map +1 -1
  60. package/dist/content/parser/MarkupParser.d.ts +9 -49
  61. package/dist/content/parser/MarkupParser.d.ts.map +1 -1
  62. package/dist/content/parser/MarkupParser.js +37 -157
  63. package/dist/content/parser/MarkupParser.js.map +1 -1
  64. package/dist/content/serializer/HTMLSerializer.d.ts +10 -43
  65. package/dist/content/serializer/HTMLSerializer.d.ts.map +1 -1
  66. package/dist/content/serializer/HTMLSerializer.js +29 -69
  67. package/dist/content/serializer/HTMLSerializer.js.map +1 -1
  68. package/dist/content/types.d.ts +21 -12
  69. package/dist/content/types.d.ts.map +1 -1
  70. package/dist/content/validator/ContentValidator.d.ts +2 -2
  71. package/dist/content/validator/ContentValidator.js +2 -2
  72. package/dist/index.d.ts +2 -3
  73. package/dist/index.d.ts.map +1 -1
  74. package/dist/index.js +4 -1
  75. package/dist/index.js.map +1 -1
  76. package/dist/lionRapid.d.ts +1 -1
  77. package/dist/lionRapid.js +4 -4
  78. package/dist/lionRapid.js.map +1 -1
  79. package/dist/repositories/network-repository.d.ts +14 -0
  80. package/dist/repositories/network-repository.d.ts.map +1 -1
  81. package/dist/repositories/network-repository.js +26 -4
  82. package/dist/repositories/network-repository.js.map +1 -1
  83. package/package.json +1 -1
  84. package/dist/content/safe-href.d.ts +0 -22
  85. package/dist/content/safe-href.d.ts.map +0 -1
  86. package/dist/content/safe-href.js +0 -48
  87. package/dist/content/safe-href.js.map +0 -1
  88. package/dist/content/style-mapper/DefaultStyleMapper.d.ts +0 -59
  89. package/dist/content/style-mapper/DefaultStyleMapper.d.ts.map +0 -1
  90. package/dist/content/style-mapper/DefaultStyleMapper.js +0 -132
  91. package/dist/content/style-mapper/DefaultStyleMapper.js.map +0 -1
  92. package/dist/content/style-mapper/IStyleMapper.d.ts +0 -50
  93. package/dist/content/style-mapper/IStyleMapper.d.ts.map +0 -1
  94. package/dist/content/style-mapper/IStyleMapper.js +0 -6
  95. package/dist/content/style-mapper/IStyleMapper.js.map +0 -1
@@ -1,5 +1,5 @@
1
- "use strict";var LionRapid=(()=>{var re=Object.defineProperty;var Oe=Object.getOwnPropertyDescriptor;var He=Object.getOwnPropertyNames;var De=Object.prototype.hasOwnProperty;var Ue=(o,e,t)=>e in o?re(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t;var je=(o,e)=>{for(var t in e)re(o,t,{get:e[t],enumerable:!0})},Be=(o,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of He(e))!De.call(o,r)&&r!==t&&re(o,r,{get:()=>e[r],enumerable:!(n=Oe(e,r))||n.enumerable});return o};var ze=o=>Be(re({},"__esModule",{value:!0}),o);var d=(o,e,t)=>Ue(o,typeof e!="symbol"?e+"":e,t);var ut={};je(ut,{AutoTranslator:()=>W,BlockExtractor:()=>V,CacheStorageRepository:()=>Y,DOMObserver:()=>_,ExcludeFilter:()=>z,LanguageSwitcher:()=>G,LionRapidBuilder:()=>U,LionRapidCore:()=>D,LocalStorageRepository:()=>Q,MemoryRepository:()=>B,NetworkRepository:()=>j,autoInit:()=>Te,generateAutoKey:()=>F,md5:()=>ve,parseBlockElement:()=>ne,parseConfig:()=>Ee});var fe=(s=>(s[s.DEBUG=0]="DEBUG",s[s.INFO=1]="INFO",s[s.WARN=2]="WARN",s[s.ERROR=3]="ERROR",s[s.NONE=4]="NONE",s))(fe||{});var K=typeof process<"u"&&process.env?process.env:{},Se=K.NODE_ENV==="production",ye=K.NODE_ENV==="development",Re=K.CI==="true",Fe=K.LIONRAPID_DEV==="true",Ve=K.LIONRAPID_PERFORMANCE_TRACKING==="true";function _e(){try{if(typeof localStorage<"u"){let o=localStorage.getItem("LIONRAPID_LOG_LEVEL");if(o&&typeof o=="string")return o}}catch{}return null}var ke=_e()||K.LOG_LEVEL||"WARN",v={RESET:"\x1B[0m",BLACK:"\x1B[30m",RED:"\x1B[31m",GREEN:"\x1B[32m",YELLOW:"\x1B[33m",BLUE:"\x1B[34m",MAGENTA:"\x1B[35m",CYAN:"\x1B[36m",WHITE:"\x1B[37m",ORANGE:"\x1B[38;5;208m",BRIGHT_BLACK:"\x1B[90m",BRIGHT_RED:"\x1B[91m",BRIGHT_GREEN:"\x1B[92m",BRIGHT_YELLOW:"\x1B[93m",BRIGHT_BLUE:"\x1B[94m",BRIGHT_MAGENTA:"\x1B[95m",BRIGHT_CYAN:"\x1B[96m",BRIGHT_WHITE:"\x1B[97m",BOLD:"\x1B[1m",DIM:"\x1B[2m",UNDERLINE:"\x1B[4m"},be=class o{constructor(e={}){d(this,"config");this.config={level:this.getLogLevelFromEnv(),enabled:this.shouldEnableLogging(),prefix:`${e.packageEmoji||"\u{1F4E6}"} ${e.packageName||"LionRapid"}`,showLineNumbers:Fe&&!Re,useColors:this.shouldUseColors(),...e}}configure(e){this.config={...this.config,...e}}debug(e,t){!this.config.enabled||this.config.level>0||this.log(0,e,t)}info(e,t){this.config.level>1||this.log(1,e,t)}warn(e,t){this.log(2,e,t)}error(e,t){this.log(3,e,t)}time(e){if(!Ve||Se)return()=>{};let t=ye?performance.now():0;return()=>{if(ye){let n=performance.now()-t;this.debug(`\u23F1\uFE0F ${e}: ${n.toFixed(2)}ms`,{duration:n})}}}log(e,t,n){if(!this.config.enabled||e<this.config.level)return;let r=fe[e],s=this.getLevelEmoji(e),a=this.config.showLineNumbers?this.getCallSite():null,i=this.buildColoredMessage(e,s,r,t,a,n);switch(e){case 3:console.error(i);break;case 2:console.warn(i);break;case 1:console.info(i);break;default:console.log(i)}}buildColoredMessage(e,t,n,r,s,a){if(!this.config.useColors){let k=s?` (${s.fileName}:${s.lineNumber})`:"",S=`${this.config.prefix} ${t} ${n} ${r}${k}`;return a!==void 0&&(S+=` ${JSON.stringify(a)}`),S}let i=this.getLevelColor(e),c=v.RESET,u=`${v.BOLD}${v.ORANGE}${this.config.prefix}${c}`,p=t,g=`${i}${v.BOLD}${n}${c}`,m=`${i}${r}${c}`,h=s?`${v.DIM}${v.BRIGHT_BLACK} (${s.fileName}:${s.lineNumber})${c}`:"",f=a!==void 0?`${v.DIM}${v.CYAN} ${JSON.stringify(a)}${c}`:"";return`${u} ${p} ${g} ${m}${h}${f}`}getLevelColor(e){switch(e){case 0:return v.BRIGHT_GREEN;case 1:return v.BRIGHT_CYAN;case 2:return v.BRIGHT_YELLOW;case 3:return v.BRIGHT_RED;default:return v.BRIGHT_BLACK}}getLevelEmoji(e){switch(e){case 0:return"\u{1F50D}";case 1:return"\u2139\uFE0F";case 2:return"\u26A0\uFE0F";case 3:return"\u274C";default:return"\u{1F4DD}"}}getCallSite(){try{let e=new Error().stack;if(!e)return null;let t=e.split(`
2
- `);for(let n=3;n<t.length;n++){let r=t[n];if(r&&!r.includes("logger.ts")&&!r.includes("Logger"))return this.parseStackLine(r)}}catch{}return null}parseStackLine(e){let t=e.match(/at\s+(.+?)\s+\((.+):(\d+):(\d+)\)/);return t?{functionName:t[1],fileName:this.extractFileName(t[2]),lineNumber:parseInt(t[3],10)}:(t=e.match(/at\s+(.+):(\d+):(\d+)/),t?{fileName:this.extractFileName(t[1]),lineNumber:parseInt(t[2],10)}:null)}extractFileName(e){let t=e.split("/");return t[t.length-1]||e}colorize(e,t){return this.config.useColors?`${v[t]}${e}${v.RESET}`:e}getColors(){return v}createPackageLogger(e,t){return new o({...this.config,packageName:e,packageEmoji:t||"\u{1F4E6}"})}getLogLevelFromEnv(){switch(ke.toUpperCase()){case"DEBUG":return 0;case"INFO":return 1;case"WARN":return 2;case"ERROR":return 3;case"NONE":return 4;default:return 2}}shouldEnableLogging(){return ke!=="NONE"}shouldUseColors(){return Re?!1:typeof window<"u"?!0:(typeof process<"u",ye)}},A=()=>{},xe=()=>()=>{},l=Se?{configure:A,debug:A,info:A,warn:(o,e)=>{console.warn(`\u{1F981} LionRapid Core \u26A0\uFE0F ${o}`,e||"")},error:(o,e)=>{console.error(`\u{1F981} LionRapid Core \u274C ${o}`,e||"")},time:xe,colorize:o=>o,getColors:()=>v,createPackageLogger:(o,e)=>({configure:A,debug:A,info:A,warn:(t,n)=>{let r=`${e||"\u{1F4E6}"} ${o}`;console.warn(`${r} \u26A0\uFE0F ${t}`,n||"")},error:(t,n)=>{let r=`${e||"\u{1F4E6}"} ${o}`;console.error(`${r} \u274C ${t}`,n||"")},time:xe,colorize:t=>t,getColors:()=>v,createPackageLogger:A})}:new be({packageName:"LionRapid Core",packageEmoji:"\u{1F981}"});var se=class{constructor(){d(this,"eventListeners",new Map);d(this,"debugMode",typeof process<"u"&&!1)}on(e,t){this.eventListeners.has(e)||this.eventListeners.set(e,new Set),this.eventListeners.get(e).add(t)}off(e,t){let n=this.eventListeners.get(e);n&&n.delete(t)}emit(e,t){let n=this.eventListeners.get(e);n&&n.forEach(r=>{try{r(t)}catch(s){console.error(`Error in event listener for ${String(e)}:`,s)}})}hasListeners(e){return this.eventListeners.has(e)&&this.eventListeners.get(e).size>0}clearEvents(){this.eventListeners.clear()}createContext(e,t,n){return{requestId:e,timestamp:performance.now(),trace:t,...n}}emitEvent(e,t,n,r){this.emit(e,{context:this.createContext(n,r),payload:t})}translation(e,t){let n=["translation"],r=t?[...n,t]:n;return{request:()=>{this.emit("translation:request",{context:this.createContext(e.id,[...n,"request"]),payload:{key:e.cleanKey}})},success:s=>{this.emit("translation:success",{context:this.createContext(e.id,[...r,"success"]),payload:{key:e.cleanKey,value:s}})},fallback:s=>{this.emit("translation:fallback",{context:this.createContext(e.id,[...n,"fallback"]),payload:{key:e.cleanKey,value:s}})},missing:(s,a,i)=>{this.emit("translation:missing",{context:this.createContext(e.id,[...n,"missing"]),payload:{key:e.cleanKey,fallbackValue:s,locale:a,namespace:i}})},notFound:(s,a,i)=>{this.emit("translation:not-found",{context:this.createContext(e.id,[...n,"not-found"]),payload:{key:e.cleanKey,fallbackValue:s,locale:a,namespace:i,status:404}})},locked:(s,a,i)=>{this.emit("translation:locked",{context:this.createContext(e.id,[...n,"locked"]),payload:{key:e.cleanKey,fallbackValue:s,locale:a,namespace:i,status:423}})}}}repo(e,t){let n=["repo",t];return{getStart:()=>{typeof e!="string"&&this.emit("repo:get:start",{context:this.createContext(e.id,[...n,"get","start"]),payload:{key:e.cleanKey,source:t}})},getSuccess:r=>{typeof e!="string"&&this.emit("repo:get:success",{context:this.createContext(e.id,[...n,"get","success"]),payload:{key:e.cleanKey,value:r,source:t}})},getMiss:()=>{typeof e!="string"&&this.emit("repo:get:miss",{context:this.createContext(e.id,[...n,"get","miss"]),payload:{key:e.cleanKey,source:t}})},setStart:r=>{typeof e!="string"&&this.emit("repo:set:start",{context:this.createContext(e.id,[...n,"set","start"]),payload:{key:e.cleanKey,value:r,source:t}})},setSuccess:r=>{let s=typeof e=="string"?"system":e.id,a=typeof e=="string"?e:e.cleanKey;this.emit("repo:set:success",{context:this.createContext(s,[...n,"set","success"]),payload:{key:a,value:r,source:t}})},error:r=>{typeof e!="string"&&this.emit("repo:error",{context:this.createContext(e.id,[...n,"error"]),payload:{key:e.cleanKey,source:t,error:r}})}}}network(e,t){let n=typeof e=="string"?e:e.cleanKey,r=typeof e=="string"?"network":e.id,s=["network",t||"request"];return{start:()=>{this.emit("network:request:start",{context:this.createContext(r,[...s,"start"]),payload:{key:n}})},success:a=>{this.emit("network:request:success",{context:this.createContext(r,[...s,"success"]),payload:{key:n,value:a,method:t||"GET"}})},error:(a,i)=>{this.emit("network:request:error",{context:this.createContext(r,[...s,"error"]),payload:{key:n,method:t||"GET",error:a,...i&&{status:i}}})},retry:(a,i,c)=>{this.emit("network:retry",{context:this.createContext(r,[...s,"retry"]),payload:{key:n,attempt:a,delayMs:i,...c&&{reason:c}}})}}}builder(){let e=["builder"],t=`build-${Date.now()}`;return{use:n=>{this.emit("builder:use",{context:this.createContext(t,[...e,"use"]),payload:{type:n}})},buildStart:(n,r)=>{this.emit("builder:build:start",{context:this.createContext(t,[...e,"build","start"]),payload:{locale:n,namespace:r}})},buildDone:(n,r)=>{this.emit("builder:build:done",{context:this.createContext(t,[...e,"build","done"]),payload:{repositories:n,plugins:r}})}}}language(e,t){let n=`lang-change-${Date.now()}`,r=["language","change"];return{start:()=>{this.emit("language:change:start",{context:this.createContext(n,[...r,"start"]),payload:{oldLocale:e,newLocale:t}})},complete:()=>{this.emit("language:change:success",{context:this.createContext(n,[...r,"complete"]),payload:{oldLocale:e,newLocale:t}})},error:s=>{this.emit("language:change:error",{context:this.createContext(n,[...r,"error"]),payload:{oldLocale:e,newLocale:t,error:s}})}}}cache(e,t,n){return this.debugMode?{start:()=>{l.debug(`\u{1F9F9} Cache ${e} starting: ${t}`)},complete:()=>{l.debug(`\u2705 Cache ${e} complete: ${n?.clearedCount||0} entries`)}}:{start:()=>{},complete:()=>{}}}};var ae=class{constructor(e){d(this,"asyncHandlers",[]);d(this,"syncHandlers",[]);d(this,"bus");this.bus=e}addSyncHandler(e){e.enabled&&(this.syncHandlers.push(e),this.sortHandlersIfNeeded(this.syncHandlers),l.debug(`Sync handler added: ${e.name}`))}handleSync(e){for(let t of this.syncHandlers)try{let n=t.lookup(e);if(n!==null&&n.value)return l.debug(`Sync hit: ${t.name} (${n.duration}ms)`),n}catch(n){l.warn(`Sync lookup failed in ${t.name}:`,n),this.bus.repo(e,t.name).error(n);continue}return null}saveToMemoryHandlers(e,t,n){let r=this.syncHandlers;r.length!==0&&(l.debug(`Saving to ${r.length} memory handlers`),r.forEach(s=>{try{s.save(e,t),l.debug(`Saved to memory: ${s.name}`)}catch(a){l.warn(`Failed to save to memory ${s.name}:`,a),this.bus.repo(e,s.name).error(a)}}))}saveNamespaceToMemoryHandlers(e,t){let n=this.syncHandlers.filter(r=>r.type==="memory"&&r.saveNamespace);n.length!==0&&(l.debug(`Saving namespace to ${n.length} memory handlers`),n.forEach(r=>{try{r.saveNamespace(e,t),l.debug(`Namespace saved to memory: ${r.name}`,{locale:t.locale,namespace:t.namespace})}catch(s){l.warn(`Failed to save namespace to memory ${r.name}:`,s),this.bus.repo(`${t.locale}:${t.namespace}`,r.name).error(s)}}))}addAsyncHandler(e){e.enabled&&(this.asyncHandlers.push(e),this.sortHandlersIfNeeded(this.asyncHandlers),l.debug(`Async handler added: ${e.name}`))}async handleAsync(e){for(let t of this.asyncHandlers)try{l.debug(`Trying handler: ${t.name}`);let n=await t.lookup(e);if(n.value&&n.status===200)return l.debug(`Async hit: ${t.name} (${n.duration}ms)`),n.namespaceLoaded?(l.debug(`Saving loaded namespace: ${n.namespaceLoaded.locale}:${n.namespaceLoaded.namespace}`),await this.saveNamespaceToHandlers(n.namespaceLoaded.data,{locale:n.namespaceLoaded.locale,namespace:n.namespaceLoaded.namespace}),n):(await this.saveToStorageHandlers(e,n,t),this.saveToMemoryHandlers(e,n,t),n);l.debug(`Handler ${t.name} returned fallback (status: ${n.status})`)}catch(n){l.warn(`Handler ${t.name} failed:`,n),this.bus.repo(e,t.name).error(n);continue}return l.debug(`No async handlers found translation for ${e.cleanKey}`),null}async saveToStorageHandlers(e,t,n){let r=this.asyncHandlers.indexOf(n),s=this.asyncHandlers.slice(0,r).filter(i=>i.type==="storage");if(s.length===0)return;l.debug(`Saving to ${s.length} storage handlers`);let a=s.map(async i=>{try{await i.save(e,t),l.debug(`Saved to storage: ${i.name}`)}catch(c){l.warn(`Failed to save to storage ${i.name}:`,c),this.bus.repo(e,i.name).error(c)}});await Promise.allSettled(a)}async saveNamespaceToStorageHandlers(e,t){let n=this.asyncHandlers.filter(s=>s.type==="storage"&&s.saveNamespace);if(n.length===0)return;l.debug(`Saving namespace to ${n.length} storage handlers`);let r=n.map(async s=>{try{await s.saveNamespace(e,t),l.debug(`Namespace saved to storage: ${s.name}`,{locale:t.locale,namespace:t.namespace})}catch(a){l.warn(`Failed to save namespace to storage ${s.name}:`,a),this.bus.repo(`${t.locale}:${t.namespace}`,s.name).error(a)}});await Promise.allSettled(r)}async saveNamespaceToHandlers(e,t){this.saveNamespaceToMemoryHandlers(e,t),await this.saveNamespaceToStorageHandlers(e,t)}getSyncHandlers(){return[...this.syncHandlers]}getAsyncHandlers(){return[...this.asyncHandlers]}getChainInfo(){return{length:this.syncHandlers.length+this.asyncHandlers.length,handlers:[...this.syncHandlers.map(e=>({name:e.name,priority:e.priority,type:e.type,enabled:e.enabled})),...this.asyncHandlers.map(e=>({name:e.name,priority:e.priority,type:e.type,enabled:e.enabled}))]}}isCached(e){return this.syncHandlers.some(t=>t.isCached?.(e)===!0)||this.asyncHandlers.some(t=>t.isCached?.(e)===!0)}getEntries(){let e={},t=[...this.syncHandlers,...this.asyncHandlers];for(let n of t)n.getEntries&&(e[n.name]=n.getEntries());return e}async destroy(){let t=[...this.syncHandlers,...this.asyncHandlers].map(async n=>{try{await n.destroy?.(),l.debug(`Handler destroyed: ${n.name}`)}catch(r){l.warn(`Failed to destroy handler: ${n.name}`,r)}});await Promise.allSettled(t),this.syncHandlers=[],this.asyncHandlers=[]}sortHandlersIfNeeded(e){e.some(n=>n.priority>0)&&e.sort((n,r)=>{let s=n.priority||Number.MAX_SAFE_INTEGER,a=r.priority||Number.MAX_SAFE_INTEGER;return s-a})}async loadNamespace(e,t){for(let n of this.asyncHandlers)if(n.type==="network")try{l.debug(`Trying to load namespace: ${e}:${t} from ${n.name}`);let r=await n.loadNamespace?.(e,t);if(r&&r.data&&r.status===200)return l.debug(`Loaded namespace: ${e}:${t} from ${n.name}`),await this.saveNamespaceToStorageHandlers(r.data,{namespace:t,locale:e}),this.saveNamespaceToMemoryHandlers(r.data,{namespace:t,locale:e}),r.data}catch(r){l.warn(`Failed to load namespace: ${e}:${t} from ${n.name}`,r),this.bus.repo(`${e}:${t}`,n.name).error(r);continue}return l.debug(`No handlers found namespace: ${e}:${t}`),null}clearCache(){let e=[...this.syncHandlers,...this.asyncHandlers];for(let t of e)try{t.destroy?.(),l.debug(`Cache cleared for handler: ${t.name}`)}catch(n){l.warn(`Failed to clear cache for handler: ${t.name}`,n)}l.debug("Cache cleared for all handlers")}clearNamespace(e,t){for(let n of this.syncHandlers)try{n.clearNamespace?.(e,t)}catch(r){l.warn(`Failed to clear namespace for handler: ${n.name}`,r)}l.debug(`Cleared namespace: ${e}:${t}`)}setCache(e,t,n){for(let r of this.syncHandlers)if(r.type==="memory"&&r.setCache)try{r.setCache(e,t,n)}catch(s){l.warn(`Failed to set cache in handler: ${r.name}`,s)}l.debug(`Cache set: ${e}`)}getNamespaceData(e){for(let t of this.syncHandlers)if(t.type==="memory")try{let n=t.getEntries?.();if(n&&n[e]){let r=n[e];return typeof r=="string"?JSON.parse(r):r}}catch(n){l.debug(`Error getting namespace data from ${t.name}:`,n)}return null}};function Le(o){let e=o.indexOf(":");if(e>0&&e<o.length-1){let t=o.substring(0,e),n=o.substring(e+1);return{originalKey:o,namespace:t,cleanKey:n,hasExplicitNamespace:!0}}return{originalKey:o,cleanKey:o,hasExplicitNamespace:!1}}function Ne(o,e,t,n){let r=o.hasExplicitNamespace?o.namespace:t;return{locale:e,namespace:r,fallbackLocale:n||e}}function $(o,e){if(!(!o||!e)){if(!e.includes(".")&&!e.includes("["))return o[e];try{let t=We(e),n=o;for(let r of t){if(n==null){l.debug(`\u{1F50D} Nested key resolution stopped at null/undefined for: ${e}`);return}if(typeof r=="number"){if(!Array.isArray(n)){l.debug(`\u{1F50D} Expected array for index ${r} in path: ${e}`);return}n=n[r]}else{if(typeof n!="object"){l.debug(`\u{1F50D} Expected object for key '${r}' in path: ${e}`);return}n=n[r]}}return l.debug(`\u{1F50D} Nested key resolved: ${e} \u2192 ${typeof n=="object"?"[Object]":n}`),n}catch(t){l.debug(`\u{1F50D} Nested key resolution error for '${e}':`,t);return}}}function We(o){let e=[],t="",n=!1;for(let r=0;r<o.length;r++){let s=o[r];if(s==="."&&!n)t&&(e.push(t),t="");else if(s==="[")t&&(e.push(t),t=""),n=!0;else if(s==="]"&&n){if(t){let a=parseInt(t,10);isNaN(a)?e.push(t):e.push(a),t=""}n=!1}else t+=s}return t&&e.push(t),e}function ie(o,e,t){let n=[o];return e&&n.push(e),n.push(t),n.join(":")}function w(o,e){return`@${o}:${e}`}function Z(o,e="",t,n){let r={};for(let[s,a]of Object.entries(o)){let i=e?`${e}.${s}`:s,c=ie(t,n,i);typeof a=="object"&&a!==null&&"text"in a&&"styles"in a?r[c]=JSON.stringify(a):typeof a=="object"&&a!==null?Object.assign(r,Z(a,i,t,n)):r[c]=JSON.stringify({text:String(a),styles:{}})}return r}function q(o,e,t,n,r,s){let a=performance.now(),{defaultValue:i,params:c}=Ge(t,n),u=Le(o),p=Ne(u,e,r,s),g=ie(p.locale,p.namespace,u.cleanKey),m=p.namespace?w(p.locale,p.namespace):void 0;return{id:`${g}-${a}`,originalKey:o,originalParams:t,originalDefaultValue:n,cleanKey:u.cleanKey,hasExplicitNamespace:u.hasExplicitNamespace,parsedParams:c,parsedDefaultValue:i,locale:e,namespace:p.namespace,fallbackLocale:s,individualCacheKey:g,namespaceCacheKey:m,startTime:a}}function Ge(o,e){let t,n;return typeof o=="object"&&typeof e=="object"&&(typeof process>"u"||!1)&&console.warn("[LionRapid] Warning: Both secondParam and thirdParam are objects. Expected pattern: t(key, params, defaultValue) or t(key, defaultValue, params). Second object will be ignored as it cannot be a defaultValue."),typeof o=="string"?(t=o,typeof e=="object"&&(n=e)):typeof o=="object"&&(n=o,typeof e=="string"&&(t=e)),{defaultValue:t,params:n}}var oe=class{constructor(e,t){d(this,"name");d(this,"version","1.0.0");d(this,"priority");d(this,"type","memory");d(this,"enabled");d(this,"ttlMap",new Map);d(this,"ttl");d(this,"repository");d(this,"bus");this.bus=e,this.repository=t,this.name=t.name;let n=t.getConfig();this.enabled=n.enabled??!0,this.priority=n.priority??0,this.ttl=n.options?.ttl??1800*1e3}getSourceType(){return"memory"}lookup(e){let t=Date.now();l.debug(`Sync lookup: ${e.cleanKey}`);let n=this.bus.repo(e,this.name);n.getStart();let r=this.tryDirectLookup(e);if(r!==null)return l.debug(`Cache hit: ${e.cleanKey}`),n.getSuccess(r.text),this.createResult(r,"memory",200,t,!0);if(e.cleanKey.includes(".")&&e.namespace){let s=this.tryNamespaceLookup(e);if(s!==null)return l.debug(`Namespace hit: ${e.cleanKey}`),n.getSuccess(s.text),this.createResult(s,"memory",200,t,!0)}return l.debug(`Cache miss: ${e.cleanKey}`),n.getMiss(),this.createResult({text:e.parsedDefaultValue||e.cleanKey,styles:{}},"fallback",404,t)}save(e,t){if(!t.value)return;let n=this.bus.repo(e,this.name),r={text:t.value,styles:t.styles||{}};this.setWithTTL(e.individualCacheKey,JSON.stringify(r)),l.debug(`Saved to cache: ${e.cleanKey}`),n.setSuccess(t.value)}saveNamespace(e,t){if(!t.namespace)return;let n=this.bus.repo(t.locale+":"+t.namespace,this.name),r=w(t.locale,t.namespace);this.setWithTTL(r,JSON.stringify(e));let s=Z(e,"",t.locale,t.namespace);for(let[a,i]of Object.entries(s))this.setWithTTL(a,i);n.setSuccess(JSON.stringify(e))}tryDirectLookup(e){if(this.checkAndExpireTTL(e.individualCacheKey))return null;let t=this.repository.get(e.individualCacheKey);if(!t)return null;this.refreshTTL(e.individualCacheKey);try{let n=JSON.parse(t);return typeof n=="object"&&"text"in n?{text:String(n.text),styles:n.styles||{}}:{text:t,styles:{}}}catch{return{text:t,styles:{}}}}tryNamespaceLookup(e){if(!e.namespace)return null;let t=w(e.locale,e.namespace);if(this.checkAndExpireTTL(t))return null;let n=this.repository.get(t);if(!n)return null;this.refreshTTL(t);try{let r=JSON.parse(n),s=$(r,e.cleanKey);if(s!=null){let a;return typeof s=="object"&&s!==null&&"text"in s?a={text:String(s.text),styles:s.styles||{}}:a={text:String(s),styles:{}},this.setWithTTL(e.individualCacheKey,JSON.stringify(a)),l.debug(`Cached from namespace: ${e.cleanKey}`),a}}catch(r){l.debug(`Invalid JSON in namespace cache: ${t}`,r),this.repository.remove(t),this.ttlMap.delete(t)}return null}createResult(e,t,n,r,s){return{value:e.text,styles:e.styles,source:t,status:n,duration:Date.now()-r,...s!==void 0&&{cached:s}}}checkAndExpireTTL(e){let t=this.ttlMap.get(e);return t&&Date.now()-t>this.ttl?(this.repository.remove(e),this.ttlMap.delete(e),l.debug(`TTL expired: ${e}`),!0):!1}setWithTTL(e,t){this.repository.set(e,t),this.ttlMap.set(e,Date.now())}refreshTTL(e){this.ttlMap.set(e,Date.now())}getTTLInfo(){let e={},t=Date.now();for(let[n,r]of this.ttlMap.entries()){let s=t-r,a=Math.max(0,this.ttl-s);e[n]={timestamp:r,age:s,remaining:a}}return e}getEntries(){if(this.repository.getEntries!==void 0)return this.repository.getEntries()}clearNamespace(e,t){let n=w(e,t),r=`${e}:${t}:`;this.repository.remove(n),this.ttlMap.delete(n);let s=this.repository.getEntries?.();if(s)for(let a of Object.keys(s))a.startsWith(r)&&(this.repository.remove(a),this.ttlMap.delete(a));l.debug(`Cleared namespace: ${e}:${t}`)}destroy(){this.repository.clear(),this.ttlMap.clear()}setCache(e,t,n){let r={text:t,styles:n||{}};this.setWithTTL(e,JSON.stringify(r)),l.debug(`Direct cache set: ${e}`)}};var le=class{constructor(e,t){d(this,"name");d(this,"version","1.0.0");d(this,"priority");d(this,"type","storage");d(this,"enabled");d(this,"ttlMap",new Map);d(this,"ttl");d(this,"repository");d(this,"bus");this.bus=e,this.repository=t,this.name=t.name;let n=t.getConfig();this.enabled=n.enabled??!0,this.priority=n.priority??0,this.ttl=n.options?.ttl??1800*1e3}getSourceType(){return"memory"}async lookup(e){let t=Date.now();l.debug(`Async lookup: ${e.cleanKey}`);let n=this.bus.repo(e,this.name),r=await this.tryDirectLookup(e);if(r!==null)return l.debug(`Cache hit: ${e.cleanKey}`),n.getSuccess(r.text),this.createResult(r,"storage",200,t,!0);if(e.cleanKey.includes(".")&&e.namespace){let s=await this.tryNamespaceLookup(e);if(s!==null)return l.debug(`Namespace hit: ${e.cleanKey}`),n.getSuccess(s.text),this.createResult(s,"storage",200,t,!0)}return l.debug(`Cache miss: ${e.cleanKey}`),n.getMiss(),this.createResult({text:e.parsedDefaultValue||e.cleanKey,styles:{}},"fallback",404,t)}async save(e,t){if(!t.value)return;let n=this.bus.repo(e,this.name),r={text:t.value,styles:t.styles||{}};await this.setWithTTL(e.individualCacheKey,JSON.stringify(r)),l.debug(`Saved to cache: ${e.cleanKey}`),n.setSuccess(t.value)}async saveNamespace(e,t){if(!t.namespace)return;let n=this.bus.repo(t.locale+":"+t.namespace,this.name),r=Object.keys(e).length;l.debug(`Saving namespace: ${t.locale}:${t.namespace} (${r} keys)`);let s=w(t.locale,t.namespace);await this.setWithTTL(s,JSON.stringify(e));let a=Z(e,"",t.locale,t.namespace),i=0;for(let[c,u]of Object.entries(a))await this.setWithTTL(c,u),i++;l.debug(`Saved: ${i} keys + namespace blob`),n.setSuccess(JSON.stringify(e))}async tryDirectLookup(e){if(await this.checkAndExpireTTL(e.individualCacheKey))return null;let t=await this.repository.get(e.individualCacheKey);if(!t)return null;this.refreshTTL(e.individualCacheKey);try{let n=JSON.parse(t);return typeof n=="object"&&"text"in n?{text:String(n.text),styles:n.styles||{}}:{text:t,styles:{}}}catch{return{text:t,styles:{}}}}async tryNamespaceLookup(e){if(!e.namespace)return null;let t=w(e.locale,e.namespace);if(await this.checkAndExpireTTL(t))return null;let n=await this.repository.get(t);if(!n)return null;this.refreshTTL(t);try{let r=JSON.parse(n),s=$(r,e.cleanKey);if(s!=null){let a;return typeof s=="object"&&s!==null&&"text"in s?a={text:String(s.text),styles:s.styles||{}}:a={text:String(s),styles:{}},await this.setWithTTL(e.individualCacheKey,JSON.stringify(a)),l.debug(`Cached from namespace: ${e.cleanKey}`),a}}catch(r){l.debug(`Invalid JSON in namespace cache: ${t}`,r),await this.repository.remove(t),this.ttlMap.delete(t)}return null}createResult(e,t,n,r,s){return{value:e.text,styles:e.styles,source:t,status:n,duration:Date.now()-r,...s!==void 0&&{cached:s}}}async checkAndExpireTTL(e){let t=this.ttlMap.get(e);return t&&Date.now()-t>this.ttl?(await this.repository.remove(e),this.ttlMap.delete(e),l.debug(`TTL expired: ${e}`),!0):!1}async setWithTTL(e,t){await this.repository.set(e,t),this.ttlMap.set(e,Date.now())}refreshTTL(e){this.ttlMap.set(e,Date.now())}getTTLInfo(){let e={},t=Date.now();for(let[n,r]of this.ttlMap.entries()){let s=t-r,a=Math.max(0,this.ttl-s);e[n]={timestamp:r,age:s,remaining:a}}return e}async destroy(){await this.repository.clear(),this.ttlMap.clear()}getEntries(){if(this.repository.getEntries!==void 0)return this.repository.getEntries()}};var ee=class extends Error{constructor(t,n,r){super(r);this.key=t;this.status=n;this.name=this.constructor.name,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}},b=class extends ee{constructor(e){super(e,404,`Translation not found: ${e}`)}},N=class extends ee{constructor(t,n){super(t,423,`Translation locked: ${t}`);this.retryAfter=n}},O=class extends ee{constructor(e,t){super(e,t,`Server error ${t}: ${e}`)}},L=class extends Error{constructor(t,n){super(t);this.cause=n;this.name="NetworkError",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}};function $e(o){return o instanceof O||o instanceof L}var ce=class{constructor(e,t){d(this,"repository");d(this,"name");d(this,"priority");d(this,"version","1.0.0");d(this,"type","network");d(this,"enabled");d(this,"bus");d(this,"retryCount");d(this,"retryDelay");this.bus=e,this.repository=t,this.name=t.name;let n=t.getConfig();this.enabled=n.enabled??!1,this.priority=n.priority??0,this.retryCount=n.options?.retries??3,this.retryDelay=n.options?.retryDelay??1e3}initialize(){return Promise.resolve()}getSourceType(){return"network"}async lookup(e){let t=Date.now(),n=e.parsedDefaultValue||e.cleanKey;if(!this.enabled)return this.createTranslationResult(n,"fallback",0,t);let r=this.bus.network(e,this.name);r.start(),l.debug(`Network lookup: ${e.cleanKey}`);try{let s=await this.lookupContentUnitWithRetry(e.individualCacheKey);return l.debug(`Network hit: ${e.cleanKey}`),r.success(s.text),this.createTranslationResult(s.text,"network",200,t,void 0,!1,void 0,s.styles)}catch(s){return s instanceof b&&e.namespace?(l.debug(`Individual key not found, trying namespace: ${e.cleanKey}`),this.lookupFromNamespace(e,n,t,r)):s instanceof N?(l.debug(`Translation locked (423): ${e.cleanKey}`),this.handleTranslationLocked(e,n,s,t,r)):(l.debug(`Network error: ${e.cleanKey}`,s),r.error(s),this.createTranslationResult(n,"fallback",0,t,s))}}async lookupFromNamespace(e,t,n,r){try{let s=await this.loadNamespace(e.locale,e.namespace);if(s&&s.data){let i=$(s.data,e.cleanKey);if(i!=null){let c,u={};if(typeof i=="object"&&i!==null&&"text"in i){let p=i;c=String(p.text),u=p.styles||{}}else c=String(i);return l.debug(`Network namespace hit: ${e.cleanKey}, hasStyles=${Object.keys(u).length>0}`),r.success(c),this.createTranslationResult(c,"network",200,n,void 0,!1,{locale:e.locale,namespace:e.namespace,data:s.data},u)}}let a=new b(e.cleanKey);return this.handleTranslationNotFound(e,t,a,n)}catch(s){return l.debug(`Namespace load failed: ${e.cleanKey}`,s),s instanceof b?this.handleTranslationNotFound(e,t,s,n):s instanceof N?this.handleTranslationLocked(e,t,s,n,r):(r.error(s),this.createTranslationResult(t,"fallback",0,n,s))}}async loadNamespace(e,t){let n=Date.now();if(!this.enabled)return this.createNamespaceResult(null,"fallback",0,n);try{let r=await this.loadNamespaceWithRetry(e,t);return r===null?(l.debug(`Network namespace not modified: ${e}:${t}`),this.createNamespaceResult(null,"network",304,n)):(l.debug(`Network namespace loaded: ${e}:${t}`),this.createNamespaceResult(r,"network",200,n))}catch(r){return r instanceof N?(l.debug(`Namespace locked (423): ${e}:${t}`),this.createNamespaceResult(null,"fallback",423,n,r)):r instanceof b?(l.debug(`Network namespace not found: ${e}:${t}`),this.createNamespaceResult(null,"fallback",404,n,r)):(l.debug(`Network namespace error: ${e}:${t}`,r),this.createNamespaceResult(null,"fallback",0,n,r))}}async loadNamespaceWithRetry(e,t){return this.withRetry(()=>this.repository.getNamespace(e,t),`${e}:${t}`,"namespace request")}async save(e,t){}async lookupWithRetry(e){return this.withRetry(()=>this.repository.get(e),e,"network request")}async lookupContentUnitWithRetry(e){let t=this.repository;return typeof t.getContentUnit!="function"?{text:await this.lookupWithRetry(e),styles:{}}:this.withRetry(()=>t.getContentUnit(e),e,"network content unit request")}delay(e){return new Promise(t=>setTimeout(t,e))}calculateBackoff(e){let n=this.retryDelay*Math.pow(2,e-1),r=1e4,s=Math.random()*.1*n;return Math.min(n+s,r)}async withRetry(e,t,n,r=1){let s=this.bus.network(t,"withRetry");try{return await e()}catch(a){if(r<=this.retryCount&&$e(a)){let i=this.calculateBackoff(r);return s.retry(r,i,a.message),await this.delay(i),l.debug(`Retrying ${n} (${r}/${this.retryCount}) after ${i}ms`),this.withRetry(e,t,n,r+1)}throw a}}handleTranslationNotFound(e,t,n,r){return l.debug(`Network namespace miss: ${e.cleanKey}`),this.bus.translation(e).notFound(t,e.locale,e.namespace||"default"),this.createTranslationResult(t,"fallback",404,r,n)}handleTranslationLocked(e,t,n,r,s){return this.bus.translation(e).locked(t,e.locale,e.namespace||"default"),s.error(n,423),this.createTranslationResult(t,"fallback",423,r,n)}createTranslationResult(e,t,n,r,s,a,i,c){return{value:e,source:t,status:n,duration:Date.now()-r,...s&&{error:s},...a!==void 0&&{cached:a},...i&&{namespaceLoaded:i},...c&&Object.keys(c).length>0&&{styles:c}}}createNamespaceResult(e,t,n,r,s){return{data:e,source:t,status:n,duration:Date.now()-r,...s&&{error:s}}}getPreload(){return this.repository.getConfig().options?.preloadNamespaces||[]}};var Je=/^[a-z][a-z0-9+.-]*:/i,Qe=new Set(["http:","https:","mailto:","tel:","sms:"]);function Ie(o){if(!o)return"#";let e=o.trim();if(!e||e.startsWith("//"))return"#";if(e.startsWith("/")||e.startsWith("?")||e.startsWith("#")||e.startsWith("./")||e.startsWith("../"))return e;let t=Je.exec(e);if(t){let n=t[0].toLowerCase();return Qe.has(n)?e:"#"}return e}var I=class{constructor(){d(this,"elementToStyles",{b:"bold",strong:"bold",i:"italic",em:"italic",u:"underline",s:"strikethrough",del:"strikethrough",strike:"strikethrough",code:"code",mark:"highlight",sub:"subscript",sup:"superscript"});d(this,"styleToElement",{bold:"b",italic:"i",underline:"u",strikethrough:"s",code:"code",highlight:"mark",subscript:"sub",superscript:"sup",strong:"b",b:"b",em:"i",i:"i",u:"u",s:"s",del:"s",strike:"s",mark:"mark",sub:"sub",sup:"sup"})}mapElementToStyles(e,t){let n=[],r=e.toLowerCase(),s=this.elementToStyles[r];return s&&n.push(s),r==="a"&&t.href&&n.push(`hyperlink:${t.href}`),n}mapStylesToElement(e){for(let t of e)if(t.startsWith("hyperlink:"))return{element:"a",attrs:{href:Ie(t.slice(10))}};for(let t of e){let n=this.styleToElement[t];if(n)return{element:n,attrs:{}}}return{element:"span",attrs:{}}}};var de=class{constructor(e={}){d(this,"styleMapper");this.styleMapper=e.styleMapper??new I}parse(e){if(/<\/?[0-9]+>/.test(e))return{text:e,styles:{}};let n={},r=0,s=[],a="",i=0;for(;i<e.length;){let c=this.matchTag(e,i);if(!c){a+=e.slice(i);break}if(a+=e.slice(i,c.startIndex),c.isClosing){let u=this.findMatchingOpenTag(s,c.tag.toLowerCase());if(u!==null){a+=`</${u}>`;let p=s.findIndex(g=>g.index===u);p!==-1&&s.splice(p,1)}else a+=e.slice(c.startIndex,c.endIndex)}else if(c.isSelfClosing){r++;let u=this.styleMapper.mapElementToStyles(c.tag,c.attrs);u.length>0&&(n[String(r)]=u,a+=`<${r}/>`)}else{let u=this.styleMapper.mapElementToStyles(c.tag,c.attrs);if(u.length>0)r++,n[String(r)]=u,a+=`<${r}>`,s.push({tag:c.tag.toLowerCase(),index:r});else{let p=this.findClosingTagIndex(e,c.endIndex,c.tag);if(p!==-1){let g=e.slice(c.endIndex,p),m=this.parse(g),h=r;for(let[S,M]of Object.entries(m.styles)){let y=String(h+parseInt(S,10));n[y]=M}a+=m.text.replace(/<(\/?)\d+>/g,(S,M)=>{let y=parseInt(S.replace(/[</>]/g,""),10);return`<${M}${h+y}>`});let f=this.matchTag(e,p);i=f?f.endIndex:p;let k=Object.keys(m.styles).length>0?Math.max(...Object.keys(m.styles).map(Number)):0;r=h+k;continue}}}i=c.endIndex}for(;s.length>0;){let c=s.pop();a+=`</${c.index}>`}return{text:a,styles:n}}matchTag(e,t){let n=e.indexOf("<",t);if(n===-1)return null;let r=/^<(\/?)([a-zA-Z][a-zA-Z0-9]*)((?:\s+[a-zA-Z][a-zA-Z0-9-]*(?:=(?:"[^"]*"|'[^']*'|[^\s>]*))?)*)\s*(\/?)>/,a=e.slice(n).match(r);if(!a)return n+1<e.length?this.matchTag(e,n+1):null;let[i,c,u,p,g]=a;return{tag:u,attrs:this.parseAttributes(p),isClosing:c==="/",isSelfClosing:g==="/",startIndex:n,endIndex:n+i.length}}parseAttributes(e){let t={};if(!e.trim())return t;let n=/([a-zA-Z][a-zA-Z0-9-]*)(?:=(?:"([^"]*)"|'([^']*)'|([^\s>]*)))?/g,r;for(;(r=n.exec(e))!==null;){let[,s,a,i,c]=r,u=a??i??c??"";t[s.toLowerCase()]=u}return t}findMatchingOpenTag(e,t){for(let n=e.length-1;n>=0;n--)if(e[n].tag===t)return e[n].index;return null}findClosingTagIndex(e,t,n){let r=n.toLowerCase(),s=1,a=t;for(;a<e.length&&s>0;){let i=this.matchTag(e,a);if(!i)break;if(i.tag.toLowerCase()===r)if(i.isClosing){if(s--,s===0)return i.startIndex}else i.isSelfClosing||s++;a=i.endIndex}return-1}};var H=class{constructor(e={}){d(this,"styleMapper");this.styleMapper=e.styleMapper??new I}serialize(e){let{text:t,styles:n}=e,r=/<(\/?)?(\d+)(\/)?>/g,s="",a=0,i;for(;(i=r.exec(t))!==null;){s+=t.slice(a,i.index);let[c,u,p,g]=i,h=n[p]||[];if(u){let f=this.styleMapper.mapStylesToElement(h);s+=`</${f.element}>`}else if(g){let f=this.styleMapper.mapStylesToElement(h),k=this.formatAttributes(f.attrs);s+=`<${f.element}${k} />`}else{let f=this.styleMapper.mapStylesToElement(h),k=this.formatAttributes(f.attrs);s+=`<${f.element}${k}>`}a=i.index+c.length}return s+=t.slice(a),s}formatAttributes(e){let t=Object.entries(e);return t.length===0?"":" "+t.map(([n,r])=>`${n}="${this.escapeAttributeValue(r)}"`).join(" ")}escapeAttributeValue(e){return e.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}};var ue=class{constructor(e,t,n,r){d(this,"handlerChain");d(this,"bus");d(this,"currentLocale");d(this,"loadNamespaces");this.handlerChain=e,this.bus=t,this.currentLocale=n,this.loadNamespaces=r}get(e){let t=this.handlerChain.getEntries();for(let n in t){let r=t[n];if(r&&typeof r=="object"&&e in r){let s=r[e];try{if(typeof s=="string"){let a=JSON.parse(s);return typeof a=="object"&&"text"in a?{value:String(a.text),styles:a.styles||void 0}:{value:s,styles:void 0}}return{value:JSON.stringify(s),styles:void 0}}catch{return{value:typeof s=="string"?s:JSON.stringify(s),styles:void 0}}}}return null}set(e,t,n){let[r,s,...a]=e.split(":"),i=a.join(":");if(!r||!s||!i)throw new Error(`Invalid cache key format: "${e}". Expected format: "locale:namespace:key"`);this.handlerChain.setCache(e,t,n),this.bus.emit("cache:set",{payload:{key:e,value:t,styles:n,optimistic:!0}})}has(e){return this.get(e)!==null}async invalidate(e={}){let{namespace:t,locale:n,key:r,predicate:s,refetch:a=!0}=e,i=this.currentLocale(),c=0;if(r){let[u,p]=r.split(":");u&&p&&(this.handlerChain.clearNamespace(u,p),c=1)}else if(t&&n)this.handlerChain.clearNamespace(n,t),c=this.countClearedKeys(n,t);else if(t)this.handlerChain.clearNamespace(i,t),c=this.countClearedKeys(i,t);else if(n){let u=this.handlerChain.getEntries(),p=new Set;for(let g in u){let m=u[g];if(m&&typeof m=="object"){for(let h of Object.keys(m))if(h.startsWith(`${n}:`)||h.startsWith(`@${n}:`)){let f=h.replace("@","").split(":");f[1]&&p.add(f[1])}}}for(let g of p)this.handlerChain.clearNamespace(n,g),c++}else if(s){let u=this.handlerChain.getEntries(),p=new Map;for(let g in u){let m=u[g];if(m&&typeof m=="object"){for(let h of Object.keys(m))if(s(h)){let f=h.replace("@","").split(":"),k=f[0],S=f[1];k&&S&&(p.has(k)||p.set(k,new Set),p.get(k).add(S),c++)}}}for(let[g,m]of p)for(let h of m)this.handlerChain.clearNamespace(g,h)}else this.handlerChain.clearCache(),c=-1;this.bus.emit("cache:invalidate",{payload:{filter:e,keysCleared:c,refetch:a}}),a&&await this.refetchAfterInvalidate(e)}countClearedKeys(e,t){let n=this.handlerChain.getEntries(),r=0,s=`${e}:${t}:`,a=`@${e}:${t}`;for(let i in n){let c=n[i];if(c&&typeof c=="object")for(let u of Object.keys(c))(u.startsWith(s)||u===a)&&r++}return r}async refetchAfterInvalidate(e){let{namespace:t,locale:n,key:r}=e,s=this.currentLocale();if(r){let[a,i]=r.split(":");a&&i&&await this.loadNamespaces(a,[i])}else t&&await this.loadNamespaces(n||s,[t])}};var Ye=/<\/?[0-9]+>/,Xe=/<[a-z][a-z0-9]*(?:\s+[^>]*)?\/?>/i,D=class{constructor(e,t,n="en",r="en",s){d(this,"handlerChain");d(this,"currentLocale");d(this,"fallbackLocale");d(this,"defaultNamespace");d(this,"pendingTranslations",new Map);d(this,"bus");d(this,"plugins",new Map);d(this,"formatters",new Map);d(this,"processors",new Map);d(this,"eventPlugins",new Set);d(this,"markupParser",new de);d(this,"htmlSerializer",new H);d(this,"cache");this.bus=e,this.handlerChain=t,this.currentLocale=n,this.fallbackLocale=r,this.defaultNamespace=s,this.cache=new ue(this.handlerChain,this.bus,()=>this.currentLocale,(a,i)=>this.loadNamespaces(a,i))}registerPlugin(e){this.plugins.set(e.name,e),this.isEmbeddedPlugin(e)&&this.integrateEmbeddedPlugin(e),this.isEventPlugin(e)&&this.eventPlugins.add(e)}integrateEmbeddedPlugin(e){if(e.getFormatters){let t=e.getFormatters();Object.entries(t).forEach(([n,r])=>{this.formatters.set(n,r),l.debug(`Embedded formatter: ${n} from ${e.name}`)})}if(e.getProcessors){let t=e.getProcessors();Object.entries(t).forEach(([n,r])=>{this.processors.set(n,r),l.debug(`Embedded processor: ${n} from ${e.name}`)})}}t(e,...t){let[n,r]=t,s=q(e,this.currentLocale,n,r,this.defaultNamespace,this.fallbackLocale);l.debug(`Translation requested: ${s.cleanKey}`);let a=this.bus.translation(s);a.request();let i=this.handlerChain.handleSync(s);if(i&&i.status===200){let p=this.processValue(i.value,s);return l.debug(`Translation found: ${s.cleanKey} from ${i.source} (${i.duration}ms)`),a.success(p),p}this.triggerBackgroundLoad(s);let c=s.parsedDefaultValue||s.cleanKey,u=this.processValue(c,s);return l.debug(`Translation fallback: ${s.cleanKey}`),a.fallback(u),u}tHtml(e,...t){let[n,r]=t,s=q(e,this.currentLocale,n,r,this.defaultNamespace,this.fallbackLocale);l.debug(`HTML translation requested: ${s.cleanKey}`);let a=this.bus.translation(s);a.request();let i=this.handlerChain.handleSync(s);if(i&&i.status===200){let p=this.processValueAsHtml(i.value,s,i.styles);return l.debug(`HTML translation found: ${s.cleanKey} from ${i.source}`),a.success(p),p}this.triggerBackgroundLoad(s);let c=s.parsedDefaultValue||s.cleanKey,u=this.processValueAsHtml(c,s);return l.debug(`HTML translation fallback: ${s.cleanKey}`),a.fallback(u),u}processValueAsHtml(e,t,n){let r=this.processTranslationValue(e,t);if(this.containsIndexedTags(r)){let s=n||this.getStylesFromNamespace(t),a={text:r,styles:s};return this.htmlSerializer.serialize(a)}if(this.containsHtml(r)){let s=this.markupParser.parse(r);return this.htmlSerializer.serialize(s)}return r}processValue(e,t){return this.containsIndexedTags(e)?this.processIndexedValue(e,t):this.containsHtml(e)?this.processHtmlValue(e,t):this.processTranslationValue(e,t)}containsIndexedTags(e){return Ye.test(e)}processIndexedValue(e,t){return this.processTranslationValue(e,t).replace(/<\/?[0-9]+>/g,"")}getStylesFromNamespace(e){if(!e.namespace)return{};try{let t=w(e.locale,e.namespace),n=this.handlerChain.getNamespaceData(t);if(!n)return{};let r=$(n,e.cleanKey);return r&&typeof r=="object"&&"styles"in r?r.styles:{}}catch(t){return l.debug(`Error getting styles for key ${e.cleanKey}:`,t),{}}}processHtmlValue(e,t){try{let n=this.markupParser.parse(e);return this.processTranslationValue(n.text,t).replace(/<\/?[0-9]+>/g,"")}catch(n){return l.warn(`ContentUnit processing failed for "${e}":`,n),this.processTranslationValue(e,t)}}processTranslationValue(e,t,n,r){let s,a,i;if(t&&"cleanKey"in t){let u=t;s=u.parsedParams,a=u.locale,i=u.cleanKey}else s=t,a=n||this.currentLocale,i=r;let c=e;try{if(c=this.applyStructuralFormatters(c,s,i),this.formatters.has("interpolate")&&(c=this.formatters.get("interpolate")(c,s,a,i)),this.processors.size>0)for(let[u,p]of this.processors.entries())try{c=p(c,s,i)}catch(g){l.warn(`Processor ${u} failed:`,g)}return c}catch(u){return l.warn(`Translation processing failed for "${e}":`,u),e}}getContentUnit(e,t,n){let r=q(e,this.currentLocale,t,n,this.defaultNamespace,this.fallbackLocale),s=this.handlerChain.handleSync(r),a=s&&s.status===200?s.value:r.parsedDefaultValue||r.cleanKey;return(!s||s.status!==200)&&this.triggerBackgroundLoad(r),this.markupParser.parse(a)}processContentText(e,t){return this.processTranslationValue(e,t,this.currentLocale)}containsHtml(e){return Xe.test(e)}applyStructuralFormatters(e,t,n){let r=e,s=i=>typeof i?.count=="number",a=i=>typeof i?.context=="string";if(this.formatters.has("plural")&&s(t)){let i=this.formatters.get("plural");try{let c=i(r,t,this.currentLocale,n);if(c!==String(r))return c}catch(c){l.warn("Plural formatting failed:",c)}}if(this.formatters.has("context")&&a(t)){let i=this.formatters.get("context");try{let c=i(r,t,this.currentLocale,n);if(c!==String(r))return c}catch(c){l.warn("Context formatting failed:",c)}}return String(r)}triggerBackgroundLoad(e){l.debug(`Background load: ${e.cleanKey}`);let t=e.individualCacheKey;if(!this.pendingTranslations.has(t)){let n=this.handlerChain.handleAsync(e).then(r=>{r&&r.value?l.debug(`Cached: ${e.cleanKey} = "${r.value}"`):l.debug(`Not found: ${e.cleanKey}`)}).catch(r=>{l.warn(`Background load failed: ${e.cleanKey}`,r)});this.pendingTranslations.set(t,n),n.finally(()=>this.pendingTranslations.delete(t))}}getCurrentLocale(){return this.currentLocale}setDefaultNamespace(e){this.defaultNamespace=e}getDefaultNamespace(){return this.defaultNamespace}getEntries(){return this.handlerChain.getEntries()}isCached(e){let t=q(e,this.currentLocale,void 0,void 0,this.defaultNamespace,this.fallbackLocale);return this.handlerChain.isCached(t)}getHandlerChainInfo(){return this.handlerChain.getChainInfo()}async changeLanguage(e,t){let n=this.currentLocale;if(n===e){l.debug(`Language already set to ${e}`);return}let r=t?.clear||!1,s=this.bus.language(n,e);try{l.info(`Language change: ${n} \u2192 ${e}`),l.debug("Language change options",{clear:r,preloadNamespaces:t?.preloadNamespaces}),s.start(),this.currentLocale=e,r&&(await this.clearCache(),this.clearOldLocalePendingTranslations(n)),t?.preloadNamespaces?.length&&await this.loadNamespaces(e,t.preloadNamespaces),s.complete(),l.info(`Language changed: ${e}`)}catch(a){throw l.error("Language change failed:",a),s.error(a),a}}async clearCache(){this.handlerChain.clearCache(),l.debug(`Cache cleared for locale: ${this.currentLocale}`)}clearOldLocalePendingTranslations(e){let t=0;for(let n of this.pendingTranslations.keys())n.includes(`${e}:`)&&(this.pendingTranslations.delete(n),t++);t>0&&l.debug(`Cleared ${t} pending translations for ${e}`)}async loadNamespaces(e,t){l.debug(`Preloading ${t.length} namespaces for ${e}`);let n=t.map(async r=>{try{await this.handlerChain.loadNamespace?.(e,r),l.debug(`Preloaded: ${e}:${r}`)}catch(s){l.warn(`Failed to preload ${e}:${r}:`,s)}});await Promise.allSettled(n)}async reloadNamespace(e,t){let n=t||this.currentLocale;l.debug(`Reloading namespace: ${n}:${e}`),await this.cache.invalidate({namespace:e,locale:n,refetch:!0}),l.info(`Namespace reloaded: ${n}:${e}`)}isEmbeddedPlugin(e){return e.capabilities.some(t=>["formatters","processors","pluralization","context"].includes(t))}isEventPlugin(e){return e.capabilities.some(t=>["analytics","logging","react","validation","dev-tools","monitoring"].includes(t))}};var Pe=6e4,pe=class{constructor(e,t,n){d(this,"queue",new Map);d(this,"debounceTimer",null);d(this,"repository");d(this,"config");d(this,"eventEmitter");d(this,"recentlySynced",new Map);this.repository=e,this.config=t,this.eventEmitter=n??null,t.enabled?l.debug(`MissingTranslationQueue: debounce=${t.debounceMs}ms, batchSize=${t.batchSize}`):l.debug("MissingTranslationQueue is disabled")}add(e){if(!this.config.enabled)return;let t=`${e.locale}:${e.namespace}:${e.key}`,n=this.recentlySynced.get(t);if(n&&Date.now()-n<Pe){l.debug(`Skipping recently synced key: ${t}`);return}if(this.queue.set(t,e),l.debug(`Missing translation queued: ${t} (queue size: ${this.queue.size})`),this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.queue.size>=this.config.batchSize){l.debug(`Batch size reached (${this.config.batchSize}), flushing`),this.flush();return}this.debounceTimer=setTimeout(()=>{this.flush()},this.config.debounceMs)}flush(){if(this.queue.size===0)return;let e=Date.now();for(let[r,s]of this.recentlySynced)e-s>=Pe&&this.recentlySynced.delete(r);let t=Array.from(this.queue.entries()).map(([r,s])=>({key:r,value:s.fallbackValue,styles:s.styles})),n=t.length;this.queue.clear(),this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),l.debug(`Flushing ${n} missing translations`),this.syncBatch(t).catch(r=>{l.warn(`Failed to sync ${n} missing translations:`,r)})}async syncBatch(e){try{if(e.some(s=>s.styles&&Object.keys(s.styles).length>0)&&"setBatchContentUnits"in this.repository){let s=e.map(a=>({key:a.key,value:{text:a.value,styles:a.styles??{}}}));await this.repository.setBatchContentUnits(s),l.debug(`Synced ${e.length} missing translations (ContentUnit)`)}else if("setBatch"in this.repository){let s=e.map(a=>({key:a.key,value:a.value}));await this.repository.setBatch(s),l.debug(`Synced ${e.length} missing translations`)}else l.warn("Repository does not support setBatch, syncing individually"),await this.syncIndividually(e);let n=Date.now(),r=[];for(let s of e)this.recentlySynced.set(s.key,n),r.push(s.key);this.eventEmitter&&this.eventEmitter.emit("sync:batch:complete",{payload:{count:e.length,keys:r}})}catch(t){throw l.error("Batch sync failed:",t),t}}async syncIndividually(e){let t=e.map(async n=>{try{await this.repository.set(n.key,n.value),l.debug(`Synced: ${n.key}`)}catch(r){l.warn(`Failed to sync ${n.key}:`,r)}});await Promise.allSettled(t)}getQueueSize(){return this.queue.size}getStats(){return{queueSize:this.queue.size,enabled:this.config.enabled,debounceMs:this.config.debounceMs,batchSize:this.config.batchSize}}destroy(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.queue.clear(),this.recentlySynced.clear(),l.debug("MissingTranslationQueue destroyed")}};var U=class o{constructor(e){d(this,"config");d(this,"plugins",[]);d(this,"syncStorageRepos",[]);d(this,"asyncStorageRepos",[]);d(this,"networkRepos",[]);d(this,"syncQueue",null);this.config={defaultLocale:e.defaultLocale||"en",fallbackLocale:e.fallbackLocale||"en",namespace:e.namespace||"app"}}static init(e={}){return new o(e)}useSyncStorage(e){return this.syncStorageRepos.push(e),this}useAsyncStorage(e){return this.asyncStorageRepos.push(e),this}useNetwork(e){return this.networkRepos.push(e),this}use(e){switch(e.type){case"plugin":this.plugins.push(e);break;case"memory":this.useSyncStorage(e);break;case"storage":this.useAsyncStorage(e);break;case"network":this.useNetwork(e);break}return this}async build(){let e=new se,t=e.builder();l.info("Builder started"),l.debug("Builder config",this.config),t.buildStart(this.config.defaultLocale,this.config.namespace);let n=new ae(e);for(let i of this.syncStorageRepos){if(!i.getConfig().enabled)continue;let c=new oe(e,i);t.use("sync"),n.addSyncHandler(c)}for(let i of this.asyncStorageRepos){if(!i.getConfig().enabled)continue;let c=new le(e,i);t.use("async"),n.addAsyncHandler(c)}let r=null;for(let i of this.networkRepos){if(!i.getConfig().enabled||!i.getConfig().options?.baseUrl)continue;let c=new ce(e,i);r||(r=c),t.use("network"),n.addAsyncHandler(c);let u=i.getConfig();u.options?.syncMissing?.enabled&&(this.syncQueue=new pe(i,{enabled:u.options.syncMissing.enabled,debounceMs:u.options.syncMissing.debounceMs||500,batchSize:u.options.syncMissing.batchSize||50},e),e.on("translation:not-found",p=>{this.syncQueue&&this.syncQueue.add({key:p.payload.key,fallbackValue:p.payload.fallbackValue,styles:p.payload.styles,locale:p.payload.locale,namespace:p.payload.namespace})}),l.info("Missing translation sync enabled"),l.debug("Sync queue config",u.options.syncMissing))}l.debug("Handler chain constructed");let s=new D(e,n,this.config.defaultLocale,this.config.fallbackLocale,this.config.namespace);for(let i of this.plugins)t.use("plugin"),await i.initialize({core:s,bus:e}),s.registerPlugin(i),l.info(`Plugin initialized: ${i.name}`),l.debug(`Plugin version: ${i.version}`,i.capabilities);let a=n.getChainInfo();return r&&await this.executePreloading(r,n),l.info("Builder completed"),t.buildDone(a.handlers.map(i=>i.name),this.plugins.map(i=>i.name)),s}async executePreloading(e,t){let n=e.getPreload().filter(s=>s.eager!==!1);if(!n||n.length===0)return;l.info(`Preloading ${n.length} namespaces`),l.debug("Preload targets",{namespaces:n.map(s=>`${s.locale}:${s.namespace}`)});let r=n.map(async s=>{try{let a=await e.loadNamespace(s.locale,s.namespace);if(a&&a.data&&a.status===200){let i={locale:s.locale,namespace:s.namespace,fallbackLocale:this.config.fallbackLocale};await t.saveNamespaceToHandlers(a.data,i),l.debug(`Preloaded: ${s.locale}:${s.namespace}`)}}catch(a){l.warn(`Preload failed: ${s.locale}:${s.namespace}`,a)}});await Promise.allSettled(r),l.info("Preloading completed")}};var te=class te{constructor(e={}){d(this,"name","NetworkRepository");d(this,"type","network");d(this,"config",{});d(this,"namespaceVersions",new Map);d(this,"DEFAULT_ENDPOINTS",{getTranslation:"/api/integrations/translations/:key",getNamespace:"/api/integrations/translations/:locale/:namespace",setTranslation:"/api/integrations/sync/:key",setNamespace:"/api/integrations/sync/:locale/:namespace",setBatch:"/api/integrations/sync/batch",removeTranslation:"/api/integrations/sync/:key",clearTranslations:"/translations"});this.config={options:{timeout:e.options?.timeout??5e3,baseUrl:e.options?.baseUrl??"",headers:e.options?.headers??{}},...e}}async get(e){if(!this.config?.options?.baseUrl)throw l.debug("API base URL is not set"),new L("API base URL is not set");let t=this.buildUrl("getTranslation",{key:e});l.debug(`API GET: ${t}`);try{let n=await this.makeRequest(t,"GET");n.ok||this.handleHttpError(n,e);let r=await n.json();l.debug("API response data:",r);let s=r.translations[r.meta?.key]||r.translations[e]||Object.values(r.translations)[0];if(l.debug(`Fetched translation for key "${e}":`,s),!s)throw new b(e);return typeof s=="object"&&"text"in s?(l.debug(`ContentUnit text: "${s.text}"`),s.text):String(s)}catch(n){this.handleCaughtError(n)}}async getContentUnit(e){if(!this.config?.options?.baseUrl)throw l.debug("API base URL is not set"),new L("API base URL is not set");let t=this.buildUrl("getTranslation",{key:e});l.debug(`API GET ContentUnit: ${t}`);try{let n=await this.makeRequest(t,"GET");n.ok||this.handleHttpError(n,e);let r=await n.json();l.debug("API response data:",r);let s=r.translations[r.meta?.key]||r.translations[e]||Object.values(r.translations)[0];if(!s)throw new b(e);return typeof s=="object"&&"text"in s?(l.debug(`ContentUnit for "${e}": text="${s.text}", styles=`,s.styles),{text:s.text,styles:s.styles||{}}):(l.debug(`Plain string for "${e}": "${s}" (no styles)`),{text:String(s),styles:{}})}catch(n){this.handleCaughtError(n)}}async getNamespace(e,t){if(!this.config?.options?.baseUrl)throw l.debug("API base URL is not set"),new L("API base URL is not set");let n=this.buildUrl("getNamespace",{locale:e,namespace:t});l.debug(`API GET Namespace: ${n}`);let r=`${e}:${t}`;try{let s={},a=this.getVersion(r);a&&(s["If-None-Match"]=`W/"${a}"`);let i=await this.makeRequest(n,"GET",void 0,s);if(i.status===304)return l.debug(`Namespace ${r}: 304 Not Modified`),null;i.ok||this.handleHttpError(i,r);let c=await i.json();if(l.debug("API response data:",c),!c.translations)throw new b(r);let u=c.meta?.version!=null?String(c.meta.version):null;return u&&this.setVersion(r,u),c.translations}catch(s){this.handleCaughtError(s)}}async set(e,t){if(!this.config?.options?.baseUrl)return l.debug("API base URL is not set"),Promise.reject(new Error("API base URL is not set"));try{let n=this.buildUrl("setTranslation",{key:e}),r=await this.makeRequest(n,"PUT",{translation:t});if(!r.ok)throw new Error(`Failed to save translation: ${r.status}`)}catch(n){throw l.debug(`API set failed for key "${e}":`,n),n}}async setNamespace(e,t,n){if(!this.config?.options?.baseUrl)return l.debug("API base URL is not set"),Promise.reject(new Error("API base URL is not set"));try{let r=this.buildUrl("setNamespace",{locale:e,namespace:t}),s=await this.makeRequest(r,"PUT",{translations:n});if(!s.ok)throw new Error(`Failed to save namespace: ${s.status}`)}catch(r){throw l.debug(`API setNamespace failed for ${e}:${t}:`,r),r}}async setBatch(e){if(!this.config?.options?.baseUrl)return l.debug("API base URL is not set"),Promise.reject(new Error("API base URL is not set"));try{let t=this.buildUrl("setBatch");l.debug(`API POST Batch: ${t} (${e.length} items)`);let n=await this.makeRequest(t,"POST",{translations:e});if(!n.ok)throw new Error(`Failed to sync batch: ${n.status}`);l.debug(`Batch sync successful: ${e.length} items`)}catch(t){throw l.debug(`API setBatch failed for ${e.length} items:`,t),t}}async getNamespaceContentUnits(e,t){if(!this.config?.options?.baseUrl)throw l.debug("API base URL is not set"),new L("API base URL is not set");let n=this.buildUrl("getNamespace",{locale:e,namespace:t});l.debug(`API GET Namespace ContentUnits: ${n}`);let r=`${e}:${t}`;try{let s={},a=this.getVersion(r);a&&(s["If-None-Match"]=`W/"${a}"`);let i=await this.makeRequest(n,"GET",void 0,s);if(i.status===304)return l.debug(`Namespace ContentUnits ${r}: 304 Not Modified`),null;i.ok||this.handleHttpError(i,r);let c=await i.json();if(l.debug("API response data:",c),!c.translations)throw new b(r);let u=c.meta?.version!=null?String(c.meta.version):null;return u&&this.setVersion(r,u),c.translations}catch(s){this.handleCaughtError(s)}}async setContentUnit(e,t){if(!this.config?.options?.baseUrl)return l.debug("API base URL is not set"),Promise.reject(new Error("API base URL is not set"));try{let n=this.buildUrl("setTranslation",{key:e}),r=await this.makeRequest(n,"PUT",{translation:t,format:"contentunit"});if(!r.ok)throw new Error(`Failed to save ContentUnit: ${r.status}`);l.debug(`Saved ContentUnit for key "${e}"`)}catch(n){throw l.debug(`API setContentUnit failed for key "${e}":`,n),n}}async setBatchContentUnits(e){if(!this.config?.options?.baseUrl)return l.debug("API base URL is not set"),Promise.reject(new Error("API base URL is not set"));try{let t=this.buildUrl("setBatch");l.debug(`API POST Batch ContentUnits: ${t} (${e.length} items)`);let n=await this.makeRequest(t,"POST",{translations:e,format:"contentunit"});if(!n.ok)throw new Error(`Failed to sync batch ContentUnits: ${n.status}`);l.debug(`Batch ContentUnit sync successful: ${e.length} items`)}catch(t){throw l.debug(`API setBatchContentUnits failed for ${e.length} items:`,t),t}}async remove(e){if(!this.config?.options?.baseUrl)return l.debug("API base URL is not set"),Promise.reject(new Error("API base URL is not set"));try{let t=this.buildUrl("removeTranslation",{key:e}),n=await this.makeRequest(t,"DELETE");if(!n.ok)throw new Error(`Failed to remove translation: ${n.status}`)}catch(t){throw l.debug(`API remove failed for key "${e}":`,t),t}}async clear(){if(!this.config?.options?.baseUrl)return l.debug("API base URL is not set"),Promise.reject(new Error("API base URL is not set"));try{let e=this.buildUrl("clearTranslations"),t=await this.makeRequest(e,"DELETE");if(!t.ok)throw new Error(`Failed to clear translations: ${t.status}`)}catch(e){throw l.debug("API clear failed:",e),e}}getConfig(){return this.config}getVersion(e){let t=this.namespaceVersions.get(e);if(t)return t;try{let n=localStorage.getItem(te.VERSION_PREFIX+e);if(n)return this.namespaceVersions.set(e,n),n}catch{}}setVersion(e,t){this.namespaceVersions.set(e,t);try{localStorage.setItem(te.VERSION_PREFIX+e,t)}catch{}}handleHttpError(e,t){if(l.debug(`API response: ${e.status} ${e.statusText}`),e.status===404)throw new b(t);if(e.status===423){let n=e.headers.get("Retry-After");throw new N(t,n?parseInt(n,10)*1e3:void 0)}throw e.status>=500&&e.status<600?new O(t,e.status):new L(`HTTP ${e.status}: ${e.statusText}`)}handleCaughtError(e){throw e instanceof b||e instanceof N||e instanceof O||e instanceof L?e:new L("Network request failed",e)}buildUrl(e,t={}){let n=this.config.options?.baseUrl||"",r=this.config.options?.endpoints?.[e]||this.DEFAULT_ENDPOINTS[e];r.startsWith("/")||(r=`/${r}`);let s=r;for(let[a,i]of Object.entries(t)){let c=new RegExp(`:${a}`,"g");s=s.replace(c,encodeURIComponent(i))}return`${n}${s}`}async makeRequest(e,t,n,r){let s=new AbortController,a=this.config.options?.timeout??1e4,i=setTimeout(()=>s.abort(),a);try{let c={"Content-Type":"application/json",...this.config.options?.headers,...r};return this.config.options?.apiKey&&(c.Authorization=`Bearer ${this.config.options.apiKey}`),await fetch(e,{method:t,headers:c,body:n?JSON.stringify(n):void 0,signal:s.signal})}finally{clearTimeout(i)}}};d(te,"VERSION_PREFIX","lionrapid:v:");var j=te;var B=class{constructor(e){d(this,"name","MemoryRepository");d(this,"type","memory");d(this,"config",{});d(this,"cache",new Map);d(this,"accessOrder",new Map);d(this,"maxSize",1e3);this.config=e,this.maxSize=this.config.options?.maxSize||1e3}get(e){let t=this.cache.get(e);return t!==void 0?(this.accessOrder.set(e,Date.now()),t):null}set(e,t){this.cache.size>=this.maxSize&&!this.cache.has(e)&&this.evictOldest(),this.cache.set(e,t),this.accessOrder.set(e,Date.now())}remove(e){this.cache.delete(e),this.accessOrder.delete(e)}clear(){this.cache.clear(),this.accessOrder.clear()}clearNamespace(e,t){let n=w(e,t),r=`${e}:${t}:`;this.cache.delete(n),this.accessOrder.delete(n);for(let s of this.cache.keys())s.startsWith(r)&&(this.cache.delete(s),this.accessOrder.delete(s))}getNamespace(e,t){let n=w(e,t),r=this.cache.get(n);if(!r)return null;try{return JSON.parse(r)}catch{return this.cache.delete(n),null}}setNamespace(e,t,n){let r=w(e,t);this.cache.set(r,JSON.stringify(n))}evictOldest(){let e="",t=Date.now();for(let[n,r]of this.accessOrder.entries())r<t&&(t=r,e=n);e&&(this.cache.delete(e),this.accessOrder.delete(e))}getEntries(){let e={};for(let[t,n]of this.cache.entries())e[t]=n;return e}getConfig(){return this.config}};var Ze={emails:!0,urls:!0,numbers:!0,phones:!0},ge={email:/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,url:/^(https?:\/\/|www\.)[^\s]+$/i,number:/^[\d\s.,+-]+$/,phone:/^[+\d][\d\s().-]{6,}$/},z=class{constructor(e={},t=2){d(this,"patterns");d(this,"minTextLength");this.patterns={...Ze,...e},this.minTextLength=t}shouldExclude(e){let t=e.trim();return!!(t.length<this.minTextLength||this.patterns.emails&&ge.email.test(t)||this.patterns.urls&&ge.url.test(t)||this.patterns.numbers&&ge.number.test(t)||this.patterns.phones&&ge.phone.test(t))}};var qe=new I;function ne(o){let e={},t=0;function n(s){if(s.nodeType===Node.TEXT_NODE)return s.nodeValue??"";if(s.nodeType!==Node.ELEMENT_NODE)return"";let a=s,i=a.tagName.toLowerCase(),c={};for(let g=0;g<a.attributes.length;g++){let m=a.attributes[g];c[m.name.toLowerCase()]=m.value}let u=qe.mapElementToStyles(i,c);if(u.length>0){t++;let g=t;e[String(g)]=u;let m="";for(let h=0;h<s.childNodes.length;h++)m+=n(s.childNodes[h]);return`<${g}>${m}</${g}>`}let p="";for(let g=0;g<s.childNodes.length;g++)p+=n(s.childNodes[g]);return p}let r="";for(let s=0;s<o.childNodes.length;s++)r+=n(o.childNodes[s]);return{text:r,styles:e}}function P(o,e){let t=(o&65535)+(e&65535);return(o>>16)+(e>>16)+(t>>16)<<16|t&65535}function et(o,e){return o<<e|o>>>32-e}function me(o,e,t,n,r,s){return P(et(P(P(e,o),P(n,s)),r),t)}function C(o,e,t,n,r,s,a){return me(e&t|~e&n,o,e,r,s,a)}function E(o,e,t,n,r,s,a){return me(e&n|t&~n,o,e,r,s,a)}function T(o,e,t,n,r,s,a){return me(e^t^n,o,e,r,s,a)}function R(o,e,t,n,r,s,a){return me(t^(e|~n),o,e,r,s,a)}function tt(o,e){o[e>>5]|=128<<e%32,o[(e+64>>>9<<4)+14]=e;let t=1732584193,n=-271733879,r=-1732584194,s=271733878;for(let a=0;a<o.length;a+=16){let i=t,c=n,u=r,p=s;t=C(t,n,r,s,o[a],7,-680876936),s=C(s,t,n,r,o[a+1],12,-389564586),r=C(r,s,t,n,o[a+2],17,606105819),n=C(n,r,s,t,o[a+3],22,-1044525330),t=C(t,n,r,s,o[a+4],7,-176418897),s=C(s,t,n,r,o[a+5],12,1200080426),r=C(r,s,t,n,o[a+6],17,-1473231341),n=C(n,r,s,t,o[a+7],22,-45705983),t=C(t,n,r,s,o[a+8],7,1770035416),s=C(s,t,n,r,o[a+9],12,-1958414417),r=C(r,s,t,n,o[a+10],17,-42063),n=C(n,r,s,t,o[a+11],22,-1990404162),t=C(t,n,r,s,o[a+12],7,1804603682),s=C(s,t,n,r,o[a+13],12,-40341101),r=C(r,s,t,n,o[a+14],17,-1502002290),n=C(n,r,s,t,o[a+15],22,1236535329),t=E(t,n,r,s,o[a+1],5,-165796510),s=E(s,t,n,r,o[a+6],9,-1069501632),r=E(r,s,t,n,o[a+11],14,643717713),n=E(n,r,s,t,o[a],20,-373897302),t=E(t,n,r,s,o[a+5],5,-701558691),s=E(s,t,n,r,o[a+10],9,38016083),r=E(r,s,t,n,o[a+15],14,-660478335),n=E(n,r,s,t,o[a+4],20,-405537848),t=E(t,n,r,s,o[a+9],5,568446438),s=E(s,t,n,r,o[a+14],9,-1019803690),r=E(r,s,t,n,o[a+3],14,-187363961),n=E(n,r,s,t,o[a+8],20,1163531501),t=E(t,n,r,s,o[a+13],5,-1444681467),s=E(s,t,n,r,o[a+2],9,-51403784),r=E(r,s,t,n,o[a+7],14,1735328473),n=E(n,r,s,t,o[a+12],20,-1926607734),t=T(t,n,r,s,o[a+5],4,-378558),s=T(s,t,n,r,o[a+8],11,-2022574463),r=T(r,s,t,n,o[a+11],16,1839030562),n=T(n,r,s,t,o[a+14],23,-35309556),t=T(t,n,r,s,o[a+1],4,-1530992060),s=T(s,t,n,r,o[a+4],11,1272893353),r=T(r,s,t,n,o[a+7],16,-155497632),n=T(n,r,s,t,o[a+10],23,-1094730640),t=T(t,n,r,s,o[a+13],4,681279174),s=T(s,t,n,r,o[a+0],11,-358537222),r=T(r,s,t,n,o[a+3],16,-722521979),n=T(n,r,s,t,o[a+6],23,76029189),t=T(t,n,r,s,o[a+9],4,-640364487),s=T(s,t,n,r,o[a+12],11,-421815835),r=T(r,s,t,n,o[a+15],16,530742520),n=T(n,r,s,t,o[a+2],23,-995338651),t=R(t,n,r,s,o[a],6,-198630844),s=R(s,t,n,r,o[a+7],10,1126891415),r=R(r,s,t,n,o[a+14],15,-1416354905),n=R(n,r,s,t,o[a+5],21,-57434055),t=R(t,n,r,s,o[a+12],6,1700485571),s=R(s,t,n,r,o[a+3],10,-1894986606),r=R(r,s,t,n,o[a+10],15,-1051523),n=R(n,r,s,t,o[a+1],21,-2054922799),t=R(t,n,r,s,o[a+8],6,1873313359),s=R(s,t,n,r,o[a+15],10,-30611744),r=R(r,s,t,n,o[a+6],15,-1560198380),n=R(n,r,s,t,o[a+13],21,1309151649),t=R(t,n,r,s,o[a+4],6,-145523070),s=R(s,t,n,r,o[a+11],10,-1120210379),r=R(r,s,t,n,o[a+2],15,718787259),n=R(n,r,s,t,o[a+9],21,-343485551),t=P(t,i),n=P(n,c),r=P(r,u),s=P(s,p)}return[t,n,r,s]}function nt(o){let e="0123456789abcdef",t="";for(let n=0;n<o.length*4;n++)t+=e.charAt(o[n>>2]>>n%4*8+4&15)+e.charAt(o[n>>2]>>n%4*8&15);return t}function rt(o){let e=[];for(let t=0;t<o.length*8;t+=8)e[t>>5]|=(o.charCodeAt(t/8)&255)<<t%32;return e}function ve(o){return nt(tt(rt(o),o.length*8))}function F(o){let e=o.trim();return"auto_"+ve(e).substring(0,12)}var we="p,h1,h2,h3,h4,h5,h6,li,td,th,label,button,figcaption,dt,dd,summary,caption",st=new Set(["SCRIPT","STYLE","CODE","PRE","TEXTAREA","NOSCRIPT","SVG"]),at=["data-lionrapid-translated","data-lionrapid-client","data-no-translate"],V=class{constructor(e={},t=[],n=2){d(this,"excludeFilter");d(this,"excludeSelectors");this.excludeFilter=new z(e,n),this.excludeSelectors=t}extract(e,t=!1){let n=[],r=e.querySelectorAll(we),s=[];e instanceof Element&&e.matches(we)&&s.push(e);for(let a=0;a<r.length;a++)s.push(r[a]);for(let a=0;a<s.length;a++){let i=s[a];if(this.isInsideSkipTag(i)||!t&&this.hasSkipAttribute(i)||this.matchesExcludeSelector(i)||i.getAttribute("translate")==="no"||i.querySelector(we))continue;let c=i.getAttribute("data-lr-block"),u=i.getAttribute("data-lr-original"),p;if(u){let h=document.createElement(i.tagName);h.innerHTML=u,p=ne(h)}else p=ne(i);let g=p.text.replace(/<\/?[0-9]+\/?>/g,"");if(this.excludeFilter.shouldExclude(g))continue;let m;if(c)m=c;else{let h=i.getAttribute("data-i18n");h?m=h.includes(":")?h:`common:${h}`:m=F(p.text)}n.push({element:i,unit:p,key:m})}return n}isInsideSkipTag(e){let t=e.parentElement;for(;t;){if(st.has(t.tagName))return!0;t=t.parentElement}return!1}hasSkipAttribute(e){let t=e;for(;t;){for(let n of at)if(t.hasAttribute(n))return!0;t=t.parentElement}return!1}matchesExcludeSelector(e){for(let t of this.excludeSelectors)try{if(e.matches(t)||e.closest(t))return!0}catch{}return!1}};var _=class{constructor(e,t=50){d(this,"observer",null);d(this,"callbacks");d(this,"debounceTimer",null);d(this,"pendingElements",new Set);d(this,"debounceMs");this.callbacks=e,this.debounceMs=t}start(){this.observer||(this.observer=new MutationObserver(e=>{this.handleMutations(e)}),this.observer.observe(document.body,{childList:!0,subtree:!0}))}stop(){this.observer&&(this.observer.disconnect(),this.observer=null),this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.pendingElements.clear()}handleMutations(e){let t=!1;for(let n of e)for(let r of Array.from(n.addedNodes)){if(r.nodeType!==Node.ELEMENT_NODE)continue;let s=r;this.hasLanguageSwitcher(s)&&(t=!0),this.callbacks.onNewContent&&this.pendingElements.add(s)}t&&this.callbacks.onNewSwitchers&&this.callbacks.onNewSwitchers(),this.pendingElements.size>0&&this.scheduleFlush()}scheduleFlush(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.flushPendingElements()},this.debounceMs)}flushPendingElements(){if(!(!this.callbacks.onNewContent||this.pendingElements.size===0)){for(let e of this.pendingElements)document.body.contains(e)&&this.callbacks.onNewContent(e);this.pendingElements.clear()}}hasLanguageSwitcher(e){return e.hasAttribute("data-lionrapid-switcher")||e.querySelector("[data-lionrapid-switcher]")!==null}};var it=new H,W=class{constructor(e={}){d(this,"core",null);d(this,"blockExtractor");d(this,"domObserver",null);d(this,"locale","");d(this,"sourceLocale","");d(this,"namespace","");d(this,"debounceMs");d(this,"pendingElements",new Set);d(this,"debounceTimer",null);d(this,"translatedCount",0);this.blockExtractor=new V(e.excludePatterns,e.excludeSelectors,e.minTextLength),this.debounceMs=e.debounceMs??100}setCore(e){this.core=e}init(e){this.locale=e.locale,this.sourceLocale=e.sourceLocale,this.namespace=e.namespace}updateLocale(e){this.locale=e}isReady(){return this.core!==null}generateAutoKey(e){return F(e)}queueElement(e){this.pendingElements.add(e),this.scheduleProcessing()}translateElement(e){if(!this.core)return 0;let t=this.blockExtractor.extract(e);return this.translateBlocks(t)}translatePage(){return this.translateElement(document.body)}observe(){this.domObserver||(this.domObserver=new _({onNewContent:e=>this.queueElement(e)}),this.domObserver.start())}stopObserving(){this.domObserver&&(this.domObserver.stop(),this.domObserver=null)}scheduleProcessing(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.processPendingElements()},this.debounceMs)}processPendingElements(){if(!this.core||this.pendingElements.size===0)return;let e=0;for(let t of this.pendingElements){if(!document.body.contains(t))continue;let n=this.translateElement(t);e+=n}this.pendingElements.clear(),this.translatedCount+=e}translateBlocks(e){if(!this.core)return 0;let t=0;for(let{element:n,unit:r,key:s}of e){let a=`${this.locale}:${this.namespace}:${s}`,i=this.core.cache.get(a);if(i&&i.value!==r.text&&i.value!==s){if(n.hasAttribute("data-lr-original")||n.setAttribute("data-lr-original",n.innerHTML),i.styles&&Object.keys(i.styles).length>0){let c={text:i.value,styles:i.styles};n.innerHTML=it.serialize(c)}else n.textContent=i.value;n.setAttribute("data-lr-block",s),n.setAttribute("data-lionrapid-client","1"),t++}else this.core.bus.emit("translation:not-found",{payload:{key:s,fallbackValue:r.text,locale:this.sourceLocale,namespace:this.namespace,status:404,styles:r.styles}})}return t}getTranslatedCount(){return this.translatedCount}retranslateElement(e){let t=e.getAttribute("data-lr-original");t!==null&&(e.innerHTML=t),e.removeAttribute("data-lionrapid-client"),e.removeAttribute("data-lr-block"),this.translateElement(e)}retranslate(){document.querySelectorAll("[data-lionrapid-client]").forEach(t=>{let n=t.getAttribute("data-lr-original");n!==null&&(t.innerHTML=n),t.removeAttribute("data-lionrapid-client"),t.removeAttribute("data-lr-block")}),this.translatedCount=0,this.locale!==this.sourceLocale&&this.translatePage()}};var Ae={en:{code:"en",name:"English",flag:"\u{1F1EC}\u{1F1E7}"},es:{code:"es",name:"Espa\xF1ol",flag:"\u{1F1EA}\u{1F1F8}"},fr:{code:"fr",name:"Fran\xE7ais",flag:"\u{1F1EB}\u{1F1F7}"},de:{code:"de",name:"Deutsch",flag:"\u{1F1E9}\u{1F1EA}"},it:{code:"it",name:"Italiano",flag:"\u{1F1EE}\u{1F1F9}"},pt:{code:"pt",name:"Portugu\xEAs",flag:"\u{1F1F5}\u{1F1F9}"},nl:{code:"nl",name:"Nederlands",flag:"\u{1F1F3}\u{1F1F1}"},pl:{code:"pl",name:"Polski",flag:"\u{1F1F5}\u{1F1F1}"},ru:{code:"ru",name:"\u0420\u0443\u0441\u0441\u043A\u0438\u0439",flag:"\u{1F1F7}\u{1F1FA}"},ja:{code:"ja",name:"\u65E5\u672C\u8A9E",flag:"\u{1F1EF}\u{1F1F5}"},ko:{code:"ko",name:"\uD55C\uAD6D\uC5B4",flag:"\u{1F1F0}\u{1F1F7}"},zh:{code:"zh",name:"\u4E2D\u6587",flag:"\u{1F1E8}\u{1F1F3}"},ar:{code:"ar",name:"\u0627\u0644\u0639\u0631\u0628\u064A\u0629",flag:"\u{1F1F8}\u{1F1E6}"},hi:{code:"hi",name:"\u0939\u093F\u0928\u094D\u0926\u0940",flag:"\u{1F1EE}\u{1F1F3}"},tr:{code:"tr",name:"T\xFCrk\xE7e",flag:"\u{1F1F9}\u{1F1F7}"},vi:{code:"vi",name:"Ti\u1EBFng Vi\u1EC7t",flag:"\u{1F1FB}\u{1F1F3}"},th:{code:"th",name:"\u0E44\u0E17\u0E22",flag:"\u{1F1F9}\u{1F1ED}"},sv:{code:"sv",name:"Svenska",flag:"\u{1F1F8}\u{1F1EA}"},da:{code:"da",name:"Dansk",flag:"\u{1F1E9}\u{1F1F0}"},fi:{code:"fi",name:"Suomi",flag:"\u{1F1EB}\u{1F1EE}"},no:{code:"no",name:"Norsk",flag:"\u{1F1F3}\u{1F1F4}"},cs:{code:"cs",name:"\u010Ce\u0161tina",flag:"\u{1F1E8}\u{1F1FF}"},el:{code:"el",name:"\u0395\u03BB\u03BB\u03B7\u03BD\u03B9\u03BA\u03AC",flag:"\u{1F1EC}\u{1F1F7}"},he:{code:"he",name:"\u05E2\u05D1\u05E8\u05D9\u05EA",flag:"\u{1F1EE}\u{1F1F1}"},id:{code:"id",name:"Bahasa Indonesia",flag:"\u{1F1EE}\u{1F1E9}"},ms:{code:"ms",name:"Bahasa Melayu",flag:"\u{1F1F2}\u{1F1FE}"},uk:{code:"uk",name:"\u0423\u043A\u0440\u0430\u0457\u043D\u0441\u044C\u043A\u0430",flag:"\u{1F1FA}\u{1F1E6}"},ro:{code:"ro",name:"Rom\xE2n\u0103",flag:"\u{1F1F7}\u{1F1F4}"},hu:{code:"hu",name:"Magyar",flag:"\u{1F1ED}\u{1F1FA}"},sk:{code:"sk",name:"Sloven\u010Dina",flag:"\u{1F1F8}\u{1F1F0}"},bg:{code:"bg",name:"\u0411\u044A\u043B\u0433\u0430\u0440\u0441\u043A\u0438",flag:"\u{1F1E7}\u{1F1EC}"},hr:{code:"hr",name:"Hrvatski",flag:"\u{1F1ED}\u{1F1F7}"},sr:{code:"sr",name:"\u0421\u0440\u043F\u0441\u043A\u0438",flag:"\u{1F1F7}\u{1F1F8}"},sl:{code:"sl",name:"Sloven\u0161\u010Dina",flag:"\u{1F1F8}\u{1F1EE}"},lt:{code:"lt",name:"Lietuvi\u0173",flag:"\u{1F1F1}\u{1F1F9}"},lv:{code:"lv",name:"Latvie\u0161u",flag:"\u{1F1F1}\u{1F1FB}"},et:{code:"et",name:"Eesti",flag:"\u{1F1EA}\u{1F1EA}"}},ot=`
1
+ "use strict";var LionRapid=(()=>{var ne=Object.defineProperty;var Ue=Object.getOwnPropertyDescriptor;var He=Object.getOwnPropertyNames;var je=Object.prototype.hasOwnProperty;var Be=(o,e,t)=>e in o?ne(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t;var ze=(o,e)=>{for(var t in e)ne(o,t,{get:e[t],enumerable:!0})},Fe=(o,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of He(e))!je.call(o,r)&&r!==t&&ne(o,r,{get:()=>e[r],enumerable:!(n=Ue(e,r))||n.enumerable});return o};var Ve=o=>Fe(ne({},"__esModule",{value:!0}),o);var d=(o,e,t)=>Be(o,typeof e!="symbol"?e+"":e,t);var ut={};ze(ut,{AutoTranslator:()=>_,BlockExtractor:()=>F,CacheStorageRepository:()=>Q,DOMObserver:()=>V,ExcludeFilter:()=>B,LanguageSwitcher:()=>G,LionRapidBuilder:()=>U,LionRapidCore:()=>M,LocalStorageRepository:()=>J,MemoryRepository:()=>j,NetworkRepository:()=>H,autoInit:()=>Re,generateAutoKey:()=>z,md5:()=>ve,parseBlockElement:()=>te,parseConfig:()=>Ee});var fe=(s=>(s[s.DEBUG=0]="DEBUG",s[s.INFO=1]="INFO",s[s.WARN=2]="WARN",s[s.ERROR=3]="ERROR",s[s.NONE=4]="NONE",s))(fe||{});var A=typeof process<"u"&&process.env?process.env:{},Le=A.NODE_ENV==="production",ye=A.NODE_ENV==="development",ke=A.CI==="true",_e=A.LIONRAPID_DEV==="true",Ge=A.LIONRAPID_PERFORMANCE_TRACKING==="true";function We(){try{if(typeof localStorage<"u"){let o=localStorage.getItem("LIONRAPID_LOG_LEVEL");if(o&&typeof o=="string")return o}}catch{}return null}var xe=We()||A.LOG_LEVEL||"WARN",v={RESET:"\x1B[0m",BLACK:"\x1B[30m",RED:"\x1B[31m",GREEN:"\x1B[32m",YELLOW:"\x1B[33m",BLUE:"\x1B[34m",MAGENTA:"\x1B[35m",CYAN:"\x1B[36m",WHITE:"\x1B[37m",ORANGE:"\x1B[38;5;208m",BRIGHT_BLACK:"\x1B[90m",BRIGHT_RED:"\x1B[91m",BRIGHT_GREEN:"\x1B[92m",BRIGHT_YELLOW:"\x1B[93m",BRIGHT_BLUE:"\x1B[94m",BRIGHT_MAGENTA:"\x1B[95m",BRIGHT_CYAN:"\x1B[96m",BRIGHT_WHITE:"\x1B[97m",BOLD:"\x1B[1m",DIM:"\x1B[2m",UNDERLINE:"\x1B[4m"},be=class o{constructor(e={}){d(this,"config");this.config={level:this.getLogLevelFromEnv(),enabled:this.shouldEnableLogging(),prefix:`${e.packageEmoji||"\u{1F4E6}"} ${e.packageName||"LionRapid"}`,showLineNumbers:_e&&!ke,useColors:this.shouldUseColors(),...e}}configure(e){this.config={...this.config,...e}}debug(e,t){!this.config.enabled||this.config.level>0||this.log(0,e,t)}info(e,t){this.config.level>1||this.log(1,e,t)}warn(e,t){this.log(2,e,t)}error(e,t){this.log(3,e,t)}time(e){if(!Ge||Le)return()=>{};let t=ye?performance.now():0;return()=>{if(ye){let n=performance.now()-t;this.debug(`\u23F1\uFE0F ${e}: ${n.toFixed(2)}ms`,{duration:n})}}}log(e,t,n){if(!this.config.enabled||e<this.config.level)return;let r=fe[e],s=this.getLevelEmoji(e),a=this.config.showLineNumbers?this.getCallSite():null,i=this.buildColoredMessage(e,s,r,t,a,n);switch(e){case 3:console.error(i);break;case 2:console.warn(i);break;case 1:console.info(i);break;default:console.log(i)}}buildColoredMessage(e,t,n,r,s,a){if(!this.config.useColors){let S=s?` (${s.fileName}:${s.lineNumber})`:"",I=`${this.config.prefix} ${t} ${n} ${r}${S}`;return a!==void 0&&(I+=` ${JSON.stringify(a)}`),I}let i=this.getLevelColor(e),c=v.RESET,u=`${v.BOLD}${v.ORANGE}${this.config.prefix}${c}`,p=t,m=`${i}${v.BOLD}${n}${c}`,g=`${i}${r}${c}`,h=s?`${v.DIM}${v.BRIGHT_BLACK} (${s.fileName}:${s.lineNumber})${c}`:"",f=a!==void 0?`${v.DIM}${v.CYAN} ${JSON.stringify(a)}${c}`:"";return`${u} ${p} ${m} ${g}${h}${f}`}getLevelColor(e){switch(e){case 0:return v.BRIGHT_GREEN;case 1:return v.BRIGHT_CYAN;case 2:return v.BRIGHT_YELLOW;case 3:return v.BRIGHT_RED;default:return v.BRIGHT_BLACK}}getLevelEmoji(e){switch(e){case 0:return"\u{1F50D}";case 1:return"\u2139\uFE0F";case 2:return"\u26A0\uFE0F";case 3:return"\u274C";default:return"\u{1F4DD}"}}getCallSite(){try{let e=new Error().stack;if(!e)return null;let t=e.split(`
2
+ `);for(let n=3;n<t.length;n++){let r=t[n];if(r&&!r.includes("logger.ts")&&!r.includes("Logger"))return this.parseStackLine(r)}}catch{}return null}parseStackLine(e){let t=e.match(/at\s+(.+?)\s+\((.+):(\d+):(\d+)\)/);return t?{functionName:t[1],fileName:this.extractFileName(t[2]),lineNumber:parseInt(t[3],10)}:(t=e.match(/at\s+(.+):(\d+):(\d+)/),t?{fileName:this.extractFileName(t[1]),lineNumber:parseInt(t[2],10)}:null)}extractFileName(e){let t=e.split("/");return t[t.length-1]||e}colorize(e,t){return this.config.useColors?`${v[t]}${e}${v.RESET}`:e}getColors(){return v}createPackageLogger(e,t){return new o({...this.config,packageName:e,packageEmoji:t||"\u{1F4E6}"})}getLogLevelFromEnv(){switch(xe.toUpperCase()){case"DEBUG":return 0;case"INFO":return 1;case"WARN":return 2;case"ERROR":return 3;case"NONE":return 4;default:return 2}}shouldEnableLogging(){return xe!=="NONE"}shouldUseColors(){return ke?!1:typeof window<"u"?!0:(typeof process<"u",ye)}},P=()=>{},Se=()=>()=>{},l=Le?{configure:P,debug:P,info:P,warn:(o,e)=>{console.warn(`\u{1F981} LionRapid Core \u26A0\uFE0F ${o}`,e||"")},error:(o,e)=>{console.error(`\u{1F981} LionRapid Core \u274C ${o}`,e||"")},time:Se,colorize:o=>o,getColors:()=>v,createPackageLogger:(o,e)=>({configure:P,debug:P,info:P,warn:(t,n)=>{let r=`${e||"\u{1F4E6}"} ${o}`;console.warn(`${r} \u26A0\uFE0F ${t}`,n||"")},error:(t,n)=>{let r=`${e||"\u{1F4E6}"} ${o}`;console.error(`${r} \u274C ${t}`,n||"")},time:Se,colorize:t=>t,getColors:()=>v,createPackageLogger:P})}:new be({packageName:"LionRapid Core",packageEmoji:"\u{1F981}"});var re=class{constructor(){d(this,"eventListeners",new Map);d(this,"debugMode",typeof process<"u"&&!1)}on(e,t){this.eventListeners.has(e)||this.eventListeners.set(e,new Set),this.eventListeners.get(e).add(t)}off(e,t){let n=this.eventListeners.get(e);n&&n.delete(t)}emit(e,t){let n=this.eventListeners.get(e);n&&n.forEach(r=>{try{r(t)}catch(s){console.error(`Error in event listener for ${String(e)}:`,s)}})}hasListeners(e){return this.eventListeners.has(e)&&this.eventListeners.get(e).size>0}clearEvents(){this.eventListeners.clear()}createContext(e,t,n){return{requestId:e,timestamp:performance.now(),trace:t,...n}}emitEvent(e,t,n,r){this.emit(e,{context:this.createContext(n,r),payload:t})}translation(e,t){let n=["translation"],r=t?[...n,t]:n;return{request:()=>{this.emit("translation:request",{context:this.createContext(e.id,[...n,"request"]),payload:{key:e.cleanKey}})},success:s=>{this.emit("translation:success",{context:this.createContext(e.id,[...r,"success"]),payload:{key:e.cleanKey,value:s}})},fallback:s=>{this.emit("translation:fallback",{context:this.createContext(e.id,[...n,"fallback"]),payload:{key:e.cleanKey,value:s}})},missing:(s,a,i)=>{this.emit("translation:missing",{context:this.createContext(e.id,[...n,"missing"]),payload:{key:e.cleanKey,fallbackValue:s,locale:a,namespace:i}})},notFound:(s,a,i)=>{this.emit("translation:not-found",{context:this.createContext(e.id,[...n,"not-found"]),payload:{key:e.cleanKey,fallbackValue:s,locale:a,namespace:i,status:404}})},locked:(s,a,i)=>{this.emit("translation:locked",{context:this.createContext(e.id,[...n,"locked"]),payload:{key:e.cleanKey,fallbackValue:s,locale:a,namespace:i,status:423}})}}}repo(e,t){let n=["repo",t];return{getStart:()=>{typeof e!="string"&&this.emit("repo:get:start",{context:this.createContext(e.id,[...n,"get","start"]),payload:{key:e.cleanKey,source:t}})},getSuccess:r=>{typeof e!="string"&&this.emit("repo:get:success",{context:this.createContext(e.id,[...n,"get","success"]),payload:{key:e.cleanKey,value:r,source:t}})},getMiss:()=>{typeof e!="string"&&this.emit("repo:get:miss",{context:this.createContext(e.id,[...n,"get","miss"]),payload:{key:e.cleanKey,source:t}})},setStart:r=>{typeof e!="string"&&this.emit("repo:set:start",{context:this.createContext(e.id,[...n,"set","start"]),payload:{key:e.cleanKey,value:r,source:t}})},setSuccess:r=>{let s=typeof e=="string"?"system":e.id,a=typeof e=="string"?e:e.cleanKey;this.emit("repo:set:success",{context:this.createContext(s,[...n,"set","success"]),payload:{key:a,value:r,source:t}})},error:r=>{typeof e!="string"&&this.emit("repo:error",{context:this.createContext(e.id,[...n,"error"]),payload:{key:e.cleanKey,source:t,error:r}})}}}network(e,t){let n=typeof e=="string"?e:e.cleanKey,r=typeof e=="string"?"network":e.id,s=["network",t||"request"];return{start:()=>{this.emit("network:request:start",{context:this.createContext(r,[...s,"start"]),payload:{key:n}})},success:a=>{this.emit("network:request:success",{context:this.createContext(r,[...s,"success"]),payload:{key:n,value:a,method:t||"GET"}})},error:(a,i)=>{this.emit("network:request:error",{context:this.createContext(r,[...s,"error"]),payload:{key:n,method:t||"GET",error:a,...i&&{status:i}}})},retry:(a,i,c)=>{this.emit("network:retry",{context:this.createContext(r,[...s,"retry"]),payload:{key:n,attempt:a,delayMs:i,...c&&{reason:c}}})}}}builder(){let e=["builder"],t=`build-${Date.now()}`;return{use:n=>{this.emit("builder:use",{context:this.createContext(t,[...e,"use"]),payload:{type:n}})},buildStart:(n,r)=>{this.emit("builder:build:start",{context:this.createContext(t,[...e,"build","start"]),payload:{locale:n,namespace:r}})},buildDone:(n,r)=>{this.emit("builder:build:done",{context:this.createContext(t,[...e,"build","done"]),payload:{repositories:n,plugins:r}})}}}language(e,t){let n=`lang-change-${Date.now()}`,r=["language","change"];return{start:()=>{this.emit("language:change:start",{context:this.createContext(n,[...r,"start"]),payload:{oldLocale:e,newLocale:t}})},complete:()=>{this.emit("language:change:success",{context:this.createContext(n,[...r,"complete"]),payload:{oldLocale:e,newLocale:t}})},error:s=>{this.emit("language:change:error",{context:this.createContext(n,[...r,"error"]),payload:{oldLocale:e,newLocale:t,error:s}})}}}cache(e,t,n){return this.debugMode?{start:()=>{l.debug(`\u{1F9F9} Cache ${e} starting: ${t}`)},complete:()=>{l.debug(`\u2705 Cache ${e} complete: ${n?.clearedCount||0} entries`)}}:{start:()=>{},complete:()=>{}}}};var se=class{constructor(e){d(this,"asyncHandlers",[]);d(this,"syncHandlers",[]);d(this,"bus");this.bus=e}addSyncHandler(e){e.enabled&&(this.syncHandlers.push(e),this.sortHandlersIfNeeded(this.syncHandlers),l.debug(`Sync handler added: ${e.name}`))}handleSync(e){for(let t of this.syncHandlers)try{let n=t.lookup(e);if(n!==null&&n.value)return l.debug(`Sync hit: ${t.name} (${n.duration}ms)`),n}catch(n){l.warn(`Sync lookup failed in ${t.name}:`,n),this.bus.repo(e,t.name).error(n);continue}return null}saveToMemoryHandlers(e,t,n){let r=this.syncHandlers;r.length!==0&&(l.debug(`Saving to ${r.length} memory handlers`),r.forEach(s=>{try{s.save(e,t),l.debug(`Saved to memory: ${s.name}`)}catch(a){l.warn(`Failed to save to memory ${s.name}:`,a),this.bus.repo(e,s.name).error(a)}}))}saveNamespaceToMemoryHandlers(e,t){let n=this.syncHandlers.filter(r=>r.type==="memory"&&r.saveNamespace);n.length!==0&&(l.debug(`Saving namespace to ${n.length} memory handlers`),n.forEach(r=>{try{r.saveNamespace(e,t),l.debug(`Namespace saved to memory: ${r.name}`,{locale:t.locale,namespace:t.namespace})}catch(s){l.warn(`Failed to save namespace to memory ${r.name}:`,s),this.bus.repo(`${t.locale}:${t.namespace}`,r.name).error(s)}}))}addAsyncHandler(e){e.enabled&&(this.asyncHandlers.push(e),this.sortHandlersIfNeeded(this.asyncHandlers),l.debug(`Async handler added: ${e.name}`))}async handleAsync(e){for(let t of this.asyncHandlers)try{l.debug(`Trying handler: ${t.name}`);let n=await t.lookup(e);if(n.value&&n.status===200)return l.debug(`Async hit: ${t.name} (${n.duration}ms)`),n.namespaceLoaded?(l.debug(`Saving loaded namespace: ${n.namespaceLoaded.locale}:${n.namespaceLoaded.namespace}`),await this.saveNamespaceToHandlers(n.namespaceLoaded.data,{locale:n.namespaceLoaded.locale,namespace:n.namespaceLoaded.namespace}),n):(await this.saveToStorageHandlers(e,n,t),this.saveToMemoryHandlers(e,n,t),n);l.debug(`Handler ${t.name} returned fallback (status: ${n.status})`)}catch(n){l.warn(`Handler ${t.name} failed:`,n),this.bus.repo(e,t.name).error(n);continue}return l.debug(`No async handlers found translation for ${e.cleanKey}`),null}async saveToStorageHandlers(e,t,n){let r=this.asyncHandlers.indexOf(n),s=this.asyncHandlers.slice(0,r).filter(i=>i.type==="storage");if(s.length===0)return;l.debug(`Saving to ${s.length} storage handlers`);let a=s.map(async i=>{try{await i.save(e,t),l.debug(`Saved to storage: ${i.name}`)}catch(c){l.warn(`Failed to save to storage ${i.name}:`,c),this.bus.repo(e,i.name).error(c)}});await Promise.allSettled(a)}async saveNamespaceToStorageHandlers(e,t){let n=this.asyncHandlers.filter(s=>s.type==="storage"&&s.saveNamespace);if(n.length===0)return;l.debug(`Saving namespace to ${n.length} storage handlers`);let r=n.map(async s=>{try{await s.saveNamespace(e,t),l.debug(`Namespace saved to storage: ${s.name}`,{locale:t.locale,namespace:t.namespace})}catch(a){l.warn(`Failed to save namespace to storage ${s.name}:`,a),this.bus.repo(`${t.locale}:${t.namespace}`,s.name).error(a)}});await Promise.allSettled(r)}async saveNamespaceToHandlers(e,t){this.saveNamespaceToMemoryHandlers(e,t),await this.saveNamespaceToStorageHandlers(e,t)}getSyncHandlers(){return[...this.syncHandlers]}getAsyncHandlers(){return[...this.asyncHandlers]}getChainInfo(){return{length:this.syncHandlers.length+this.asyncHandlers.length,handlers:[...this.syncHandlers.map(e=>({name:e.name,priority:e.priority,type:e.type,enabled:e.enabled})),...this.asyncHandlers.map(e=>({name:e.name,priority:e.priority,type:e.type,enabled:e.enabled}))]}}isCached(e){return this.syncHandlers.some(t=>t.isCached?.(e)===!0)||this.asyncHandlers.some(t=>t.isCached?.(e)===!0)}getEntries(){let e={},t=[...this.syncHandlers,...this.asyncHandlers];for(let n of t)n.getEntries&&(e[n.name]=n.getEntries());return e}async destroy(){let t=[...this.syncHandlers,...this.asyncHandlers].map(async n=>{try{await n.destroy?.(),l.debug(`Handler destroyed: ${n.name}`)}catch(r){l.warn(`Failed to destroy handler: ${n.name}`,r)}});await Promise.allSettled(t),this.syncHandlers=[],this.asyncHandlers=[]}sortHandlersIfNeeded(e){e.some(n=>n.priority>0)&&e.sort((n,r)=>{let s=n.priority||Number.MAX_SAFE_INTEGER,a=r.priority||Number.MAX_SAFE_INTEGER;return s-a})}async loadNamespace(e,t){for(let n of this.asyncHandlers)if(n.type==="network")try{l.debug(`Trying to load namespace: ${e}:${t} from ${n.name}`);let r=await n.loadNamespace?.(e,t);if(r&&r.data&&r.status===200)return l.debug(`Loaded namespace: ${e}:${t} from ${n.name}`),await this.saveNamespaceToStorageHandlers(r.data,{namespace:t,locale:e}),this.saveNamespaceToMemoryHandlers(r.data,{namespace:t,locale:e}),r.data}catch(r){l.warn(`Failed to load namespace: ${e}:${t} from ${n.name}`,r),this.bus.repo(`${e}:${t}`,n.name).error(r);continue}return l.debug(`No handlers found namespace: ${e}:${t}`),null}clearCache(){let e=[...this.syncHandlers,...this.asyncHandlers];for(let t of e)try{t.destroy?.(),l.debug(`Cache cleared for handler: ${t.name}`)}catch(n){l.warn(`Failed to clear cache for handler: ${t.name}`,n)}l.debug("Cache cleared for all handlers")}clearNamespace(e,t){for(let n of this.syncHandlers)try{n.clearNamespace?.(e,t)}catch(r){l.warn(`Failed to clear namespace for handler: ${n.name}`,r)}l.debug(`Cleared namespace: ${e}:${t}`)}setCache(e,t,n){for(let r of this.syncHandlers)if(r.type==="memory"&&r.setCache)try{r.setCache(e,t,n)}catch(s){l.warn(`Failed to set cache in handler: ${r.name}`,s)}l.debug(`Cache set: ${e}`)}getNamespaceData(e){for(let t of this.syncHandlers)if(t.type==="memory")try{let n=t.getEntries?.();if(n&&n[e]){let r=n[e];return typeof r=="string"?JSON.parse(r):r}}catch(n){l.debug(`Error getting namespace data from ${t.name}:`,n)}return null}};function Ne(o){let e=o.indexOf(":");if(e>0&&e<o.length-1){let t=o.substring(0,e),n=o.substring(e+1);return{originalKey:o,namespace:t,cleanKey:n,hasExplicitNamespace:!0}}return{originalKey:o,cleanKey:o,hasExplicitNamespace:!1}}function $e(o,e,t,n){let r=o.hasExplicitNamespace?o.namespace:t;return{locale:e,namespace:r,fallbackLocale:n||e}}function N(o,e){if(!(!o||!e)){if(!e.includes(".")&&!e.includes("["))return o[e];try{let t=Je(e),n=o;for(let r of t){if(n==null){l.debug(`\u{1F50D} Nested key resolution stopped at null/undefined for: ${e}`);return}if(typeof r=="number"){if(!Array.isArray(n)){l.debug(`\u{1F50D} Expected array for index ${r} in path: ${e}`);return}n=n[r]}else{if(typeof n!="object"){l.debug(`\u{1F50D} Expected object for key '${r}' in path: ${e}`);return}n=n[r]}}return l.debug(`\u{1F50D} Nested key resolved: ${e} \u2192 ${typeof n=="object"?"[Object]":n}`),n}catch(t){l.debug(`\u{1F50D} Nested key resolution error for '${e}':`,t);return}}}function Je(o){let e=[],t="",n=!1;for(let r=0;r<o.length;r++){let s=o[r];if(s==="."&&!n)t&&(e.push(t),t="");else if(s==="[")t&&(e.push(t),t=""),n=!0;else if(s==="]"&&n){if(t){let a=parseInt(t,10);isNaN(a)?e.push(t):e.push(a),t=""}n=!1}else t+=s}return t&&e.push(t),e}function ae(o,e,t){let n=[o];return e&&n.push(e),n.push(t),n.join(":")}function w(o,e){return`@${o}:${e}`}function X(o,e="",t,n){let r={};for(let[s,a]of Object.entries(o)){let i=e?`${e}.${s}`:s,c=ae(t,n,i);typeof a=="object"&&a!==null&&"text"in a&&"styles"in a?r[c]=JSON.stringify(a):typeof a=="object"&&a!==null?Object.assign(r,X(a,i,t,n)):r[c]=JSON.stringify({text:String(a),styles:{}})}return r}function Z(o,e,t,n,r,s){let a=performance.now(),{defaultValue:i,params:c}=Qe(t,n),u=Ne(o),p=$e(u,e,r,s),m=ae(p.locale,p.namespace,u.cleanKey),g=p.namespace?w(p.locale,p.namespace):void 0;return{id:`${m}-${a}`,originalKey:o,originalParams:t,originalDefaultValue:n,cleanKey:u.cleanKey,hasExplicitNamespace:u.hasExplicitNamespace,parsedParams:c,parsedDefaultValue:i,locale:e,namespace:p.namespace,fallbackLocale:s,individualCacheKey:m,namespaceCacheKey:g,startTime:a}}function Qe(o,e){let t,n;return typeof o=="object"&&typeof e=="object"&&(typeof process>"u"||!1)&&console.warn("[LionRapid] Warning: Both secondParam and thirdParam are objects. Expected pattern: t(key, params, defaultValue) or t(key, defaultValue, params). Second object will be ignored as it cannot be a defaultValue."),typeof o=="string"?(t=o,typeof e=="object"&&(n=e)):typeof o=="object"&&(n=o,typeof e=="string"&&(t=e)),{defaultValue:t,params:n}}var ie=class{constructor(e,t){d(this,"name");d(this,"version","1.0.0");d(this,"priority");d(this,"type","memory");d(this,"enabled");d(this,"ttlMap",new Map);d(this,"ttl");d(this,"repository");d(this,"bus");this.bus=e,this.repository=t,this.name=t.name;let n=t.getConfig();this.enabled=n.enabled??!0,this.priority=n.priority??0,this.ttl=n.options?.ttl??1800*1e3}getSourceType(){return"memory"}lookup(e){let t=Date.now();l.debug(`Sync lookup: ${e.cleanKey}`);let n=this.bus.repo(e,this.name);n.getStart();let r=this.tryDirectLookup(e);if(r!==null)return l.debug(`Cache hit: ${e.cleanKey}`),n.getSuccess(r.text),this.createResult(r,"memory",200,t,!0);if(e.cleanKey.includes(".")&&e.namespace){let s=this.tryNamespaceLookup(e);if(s!==null)return l.debug(`Namespace hit: ${e.cleanKey}`),n.getSuccess(s.text),this.createResult(s,"memory",200,t,!0)}return l.debug(`Cache miss: ${e.cleanKey}`),n.getMiss(),this.createResult({text:e.parsedDefaultValue||e.cleanKey,styles:{}},"fallback",404,t)}save(e,t){if(!t.value)return;let n=this.bus.repo(e,this.name),r={text:t.value,styles:t.styles||{}};this.setWithTTL(e.individualCacheKey,JSON.stringify(r)),l.debug(`Saved to cache: ${e.cleanKey}`),n.setSuccess(t.value)}saveNamespace(e,t){if(!t.namespace)return;let n=this.bus.repo(t.locale+":"+t.namespace,this.name),r=w(t.locale,t.namespace);this.setWithTTL(r,JSON.stringify(e));let s=X(e,"",t.locale,t.namespace);for(let[a,i]of Object.entries(s))this.setWithTTL(a,i);n.setSuccess(JSON.stringify(e))}tryDirectLookup(e){if(this.checkAndExpireTTL(e.individualCacheKey))return null;let t=this.repository.get(e.individualCacheKey);if(!t)return null;this.refreshTTL(e.individualCacheKey);try{let n=JSON.parse(t);return typeof n=="object"&&"text"in n?{text:String(n.text),styles:n.styles||{}}:{text:t,styles:{}}}catch{return{text:t,styles:{}}}}tryNamespaceLookup(e){if(!e.namespace)return null;let t=w(e.locale,e.namespace);if(this.checkAndExpireTTL(t))return null;let n=this.repository.get(t);if(!n)return null;this.refreshTTL(t);try{let r=JSON.parse(n),s=N(r,e.cleanKey);if(s!=null){let a;return typeof s=="object"&&s!==null&&"text"in s?a={text:String(s.text),styles:s.styles||{}}:a={text:String(s),styles:{}},this.setWithTTL(e.individualCacheKey,JSON.stringify(a)),l.debug(`Cached from namespace: ${e.cleanKey}`),a}}catch(r){l.debug(`Invalid JSON in namespace cache: ${t}`,r),this.repository.remove(t),this.ttlMap.delete(t)}return null}createResult(e,t,n,r,s){return{value:e.text,styles:e.styles,source:t,status:n,duration:Date.now()-r,...s!==void 0&&{cached:s}}}checkAndExpireTTL(e){let t=this.ttlMap.get(e);return t&&Date.now()-t>this.ttl?(this.repository.remove(e),this.ttlMap.delete(e),l.debug(`TTL expired: ${e}`),!0):!1}setWithTTL(e,t){this.repository.set(e,t),this.ttlMap.set(e,Date.now())}refreshTTL(e){this.ttlMap.set(e,Date.now())}getTTLInfo(){let e={},t=Date.now();for(let[n,r]of this.ttlMap.entries()){let s=t-r,a=Math.max(0,this.ttl-s);e[n]={timestamp:r,age:s,remaining:a}}return e}getEntries(){if(this.repository.getEntries!==void 0)return this.repository.getEntries()}clearNamespace(e,t){let n=w(e,t),r=`${e}:${t}:`;this.repository.remove(n),this.ttlMap.delete(n);let s=this.repository.getEntries?.();if(s)for(let a of Object.keys(s))a.startsWith(r)&&(this.repository.remove(a),this.ttlMap.delete(a));l.debug(`Cleared namespace: ${e}:${t}`)}destroy(){this.repository.clear(),this.ttlMap.clear()}setCache(e,t,n){let r={text:t,styles:n||{}};this.setWithTTL(e,JSON.stringify(r)),l.debug(`Direct cache set: ${e}`)}};var oe=class{constructor(e,t){d(this,"name");d(this,"version","1.0.0");d(this,"priority");d(this,"type","storage");d(this,"enabled");d(this,"ttlMap",new Map);d(this,"ttl");d(this,"repository");d(this,"bus");this.bus=e,this.repository=t,this.name=t.name;let n=t.getConfig();this.enabled=n.enabled??!0,this.priority=n.priority??0,this.ttl=n.options?.ttl??1800*1e3}getSourceType(){return"memory"}async lookup(e){let t=Date.now();l.debug(`Async lookup: ${e.cleanKey}`);let n=this.bus.repo(e,this.name),r=await this.tryDirectLookup(e);if(r!==null)return l.debug(`Cache hit: ${e.cleanKey}`),n.getSuccess(r.text),this.createResult(r,"storage",200,t,!0);if(e.cleanKey.includes(".")&&e.namespace){let s=await this.tryNamespaceLookup(e);if(s!==null)return l.debug(`Namespace hit: ${e.cleanKey}`),n.getSuccess(s.text),this.createResult(s,"storage",200,t,!0)}return l.debug(`Cache miss: ${e.cleanKey}`),n.getMiss(),this.createResult({text:e.parsedDefaultValue||e.cleanKey,styles:{}},"fallback",404,t)}async save(e,t){if(!t.value)return;let n=this.bus.repo(e,this.name),r={text:t.value,styles:t.styles||{}};await this.setWithTTL(e.individualCacheKey,JSON.stringify(r)),l.debug(`Saved to cache: ${e.cleanKey}`),n.setSuccess(t.value)}async saveNamespace(e,t){if(!t.namespace)return;let n=this.bus.repo(t.locale+":"+t.namespace,this.name),r=Object.keys(e).length;l.debug(`Saving namespace: ${t.locale}:${t.namespace} (${r} keys)`);let s=w(t.locale,t.namespace);await this.setWithTTL(s,JSON.stringify(e));let a=X(e,"",t.locale,t.namespace),i=0;for(let[c,u]of Object.entries(a))await this.setWithTTL(c,u),i++;l.debug(`Saved: ${i} keys + namespace blob`),n.setSuccess(JSON.stringify(e))}async tryDirectLookup(e){if(await this.checkAndExpireTTL(e.individualCacheKey))return null;let t=await this.repository.get(e.individualCacheKey);if(!t)return null;this.refreshTTL(e.individualCacheKey);try{let n=JSON.parse(t);return typeof n=="object"&&"text"in n?{text:String(n.text),styles:n.styles||{}}:{text:t,styles:{}}}catch{return{text:t,styles:{}}}}async tryNamespaceLookup(e){if(!e.namespace)return null;let t=w(e.locale,e.namespace);if(await this.checkAndExpireTTL(t))return null;let n=await this.repository.get(t);if(!n)return null;this.refreshTTL(t);try{let r=JSON.parse(n),s=N(r,e.cleanKey);if(s!=null){let a;return typeof s=="object"&&s!==null&&"text"in s?a={text:String(s.text),styles:s.styles||{}}:a={text:String(s),styles:{}},await this.setWithTTL(e.individualCacheKey,JSON.stringify(a)),l.debug(`Cached from namespace: ${e.cleanKey}`),a}}catch(r){l.debug(`Invalid JSON in namespace cache: ${t}`,r),await this.repository.remove(t),this.ttlMap.delete(t)}return null}createResult(e,t,n,r,s){return{value:e.text,styles:e.styles,source:t,status:n,duration:Date.now()-r,...s!==void 0&&{cached:s}}}async checkAndExpireTTL(e){let t=this.ttlMap.get(e);return t&&Date.now()-t>this.ttl?(await this.repository.remove(e),this.ttlMap.delete(e),l.debug(`TTL expired: ${e}`),!0):!1}async setWithTTL(e,t){await this.repository.set(e,t),this.ttlMap.set(e,Date.now())}refreshTTL(e){this.ttlMap.set(e,Date.now())}getTTLInfo(){let e={},t=Date.now();for(let[n,r]of this.ttlMap.entries()){let s=t-r,a=Math.max(0,this.ttl-s);e[n]={timestamp:r,age:s,remaining:a}}return e}async destroy(){await this.repository.clear(),this.ttlMap.clear()}getEntries(){if(this.repository.getEntries!==void 0)return this.repository.getEntries()}};var q=class extends Error{constructor(t,n,r){super(r);this.key=t;this.status=n;this.name=this.constructor.name,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}},b=class extends q{constructor(e){super(e,404,`Translation not found: ${e}`)}},L=class extends q{constructor(t,n){super(t,423,`Translation locked: ${t}`);this.retryAfter=n}},K=class extends q{constructor(e,t){super(e,t,`Server error ${t}: ${e}`)}},x=class extends Error{constructor(t,n){super(t);this.cause=n;this.name="NetworkError",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}};function Ie(o){return o instanceof K||o instanceof x}var le=class{constructor(e,t){d(this,"repository");d(this,"name");d(this,"priority");d(this,"version","1.0.0");d(this,"type","network");d(this,"enabled");d(this,"bus");d(this,"retryCount");d(this,"retryDelay");this.bus=e,this.repository=t,this.name=t.name;let n=t.getConfig();this.enabled=n.enabled??!1,this.priority=n.priority??0,this.retryCount=n.options?.retries??3,this.retryDelay=n.options?.retryDelay??1e3}initialize(){return Promise.resolve()}getSourceType(){return"network"}async lookup(e){let t=Date.now(),n=e.parsedDefaultValue||e.cleanKey;if(!this.enabled)return this.createTranslationResult(n,"fallback",0,t);let r=this.bus.network(e,this.name);r.start(),l.debug(`Network lookup: ${e.cleanKey}`);try{let s=await this.lookupContentUnitWithRetry(e.individualCacheKey);return l.debug(`Network hit: ${e.cleanKey}`),r.success(s.text),this.createTranslationResult(s.text,"network",200,t,void 0,!1,void 0,s.styles)}catch(s){return s instanceof b&&e.namespace?(l.debug(`Individual key not found, trying namespace: ${e.cleanKey}`),this.lookupFromNamespace(e,n,t,r)):s instanceof L?(l.debug(`Translation locked (423): ${e.cleanKey}`),this.handleTranslationLocked(e,n,s,t,r)):(l.debug(`Network error: ${e.cleanKey}`,s),r.error(s),this.createTranslationResult(n,"fallback",0,t,s))}}async lookupFromNamespace(e,t,n,r){try{let s=await this.loadNamespace(e.locale,e.namespace);if(s&&s.data){let i=N(s.data,e.cleanKey);if(i!=null){let c,u={};if(typeof i=="object"&&i!==null&&"text"in i){let p=i;c=String(p.text),u=p.styles||{}}else c=String(i);return l.debug(`Network namespace hit: ${e.cleanKey}, hasStyles=${Object.keys(u).length>0}`),r.success(c),this.createTranslationResult(c,"network",200,n,void 0,!1,{locale:e.locale,namespace:e.namespace,data:s.data},u)}}let a=new b(e.cleanKey);return this.handleTranslationNotFound(e,t,a,n)}catch(s){return l.debug(`Namespace load failed: ${e.cleanKey}`,s),s instanceof b?this.handleTranslationNotFound(e,t,s,n):s instanceof L?this.handleTranslationLocked(e,t,s,n,r):(r.error(s),this.createTranslationResult(t,"fallback",0,n,s))}}async loadNamespace(e,t){let n=Date.now();if(!this.enabled)return this.createNamespaceResult(null,"fallback",0,n);try{let r=await this.loadNamespaceWithRetry(e,t);return r===null?(l.debug(`Network namespace not modified: ${e}:${t}`),this.createNamespaceResult(null,"network",304,n)):(l.debug(`Network namespace loaded: ${e}:${t}`),this.createNamespaceResult(r,"network",200,n))}catch(r){return r instanceof L?(l.debug(`Namespace locked (423): ${e}:${t}`),this.createNamespaceResult(null,"fallback",423,n,r)):r instanceof b?(l.debug(`Network namespace not found: ${e}:${t}`),this.createNamespaceResult(null,"fallback",404,n,r)):(l.debug(`Network namespace error: ${e}:${t}`,r),this.createNamespaceResult(null,"fallback",0,n,r))}}async loadNamespaceWithRetry(e,t){return this.withRetry(()=>this.repository.getNamespace(e,t),`${e}:${t}`,"namespace request")}async save(e,t){}async lookupWithRetry(e){return this.withRetry(()=>this.repository.get(e),e,"network request")}async lookupContentUnitWithRetry(e){let t=this.repository;return typeof t.getContentUnit!="function"?{text:await this.lookupWithRetry(e),styles:{}}:this.withRetry(()=>t.getContentUnit(e),e,"network content unit request")}delay(e){return new Promise(t=>setTimeout(t,e))}calculateBackoff(e){let n=this.retryDelay*Math.pow(2,e-1),r=1e4,s=Math.random()*.1*n;return Math.min(n+s,r)}async withRetry(e,t,n,r=1){let s=this.bus.network(t,"withRetry");try{return await e()}catch(a){if(r<=this.retryCount&&Ie(a)){let i=this.calculateBackoff(r);return s.retry(r,i,a.message),await this.delay(i),l.debug(`Retrying ${n} (${r}/${this.retryCount}) after ${i}ms`),this.withRetry(e,t,n,r+1)}throw a}}handleTranslationNotFound(e,t,n,r){return l.debug(`Network namespace miss: ${e.cleanKey}`),this.bus.translation(e).notFound(t,e.locale,e.namespace||"default"),this.createTranslationResult(t,"fallback",404,r,n)}handleTranslationLocked(e,t,n,r,s){return this.bus.translation(e).locked(t,e.locale,e.namespace||"default"),s.error(n,423),this.createTranslationResult(t,"fallback",423,r,n)}createTranslationResult(e,t,n,r,s,a,i,c){return{value:e,source:t,status:n,duration:Date.now()-r,...s&&{error:s},...a!==void 0&&{cached:a},...i&&{namespaceLoaded:i},...c&&Object.keys(c).length>0&&{styles:c}}}createNamespaceResult(e,t,n,r,s){return{data:e,source:t,status:n,duration:Date.now()-r,...s&&{error:s}}}getPreload(){return this.repository.getConfig().options?.preloadNamespaces||[]}};var O=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]);function Ye(o){return o.replace(/"/g,"&quot;")}function ce(o,e){let n=`<${o.toLowerCase()}`;for(let[r,s]of Object.entries(e))n+=` ${r.toLowerCase()}="${Ye(s)}"`;return n+=">",n}function Pe(o){let e=o.search(/[\s>]/);return o.slice(1,e===-1?o.length:e).toLowerCase()}function Ae(o){for(let e of o)if(e.startsWith("raw:"))return e.slice(4);return null}var de=class{parse(e){if(/<\/?[0-9]+>/.test(e))return{text:e,styles:{}};let t={},n=0,r=[],s="",a=0;for(;a<e.length;){let i=this.matchTag(e,a);if(!i){s+=e.slice(a);break}if(s+=e.slice(a,i.startIndex),i.isClosing){let c=null;for(let u=r.length-1;u>=0;u--)if(r[u].tag===i.tag.toLowerCase()){c=r[u].index,r.splice(u,1);break}c!==null&&(s+=`</${c}>`)}else{let c=i.tag.toLowerCase(),u=O.has(c),p=i.isSelfClosing||u;n++,t[String(n)]=[`raw:${ce(c,i.attrs)}`],p?s+=`<${n}/>`:(s+=`<${n}>`,r.push({tag:c,index:n}))}a=i.endIndex}for(;r.length>0;){let i=r.pop();s+=`</${i.index}>`}return{text:s,styles:t}}matchTag(e,t){let n=e.indexOf("<",t);if(n===-1)return null;let r=/^<(\/?)([a-zA-Z][a-zA-Z0-9]*)((?:\s+[a-zA-Z][a-zA-Z0-9-]*(?:=(?:"[^"]*"|'[^']*'|[^\s>]*))?)*)\s*(\/?)>/,a=e.slice(n).match(r);if(!a)return n+1<e.length?this.matchTag(e,n+1):null;let[i,c,u,p,m]=a;return{tag:u,attrs:this.parseAttributes(p),isClosing:c==="/",isSelfClosing:m==="/",startIndex:n,endIndex:n+i.length}}parseAttributes(e){let t={};if(!e.trim())return t;let n=/([a-zA-Z][a-zA-Z0-9-]*)(?:=(?:"([^"]*)"|'([^']*)'|([^\s>]*)))?/g,r;for(;(r=n.exec(e))!==null;){let[,s,a,i,c]=r;t[s.toLowerCase()]=a??i??c??""}return t}};var D=class{serialize(e){let{text:t,styles:n}=e,r=/<(\/?)?(\d+)(\/)?>/g,s="",a=0,i;for(;(i=r.exec(t))!==null;){s+=t.slice(a,i.index);let[c,u,p]=i,m=n[p]??[],g=Ae(m);if(g){let h=Pe(g),f=O.has(h);u?f||(s+=`</${h}>`):s+=g}else s+=c;a=i.index+c.length}return s+=t.slice(a),s}};var ue=class{constructor(e,t,n,r){d(this,"handlerChain");d(this,"bus");d(this,"currentLocale");d(this,"loadNamespaces");this.handlerChain=e,this.bus=t,this.currentLocale=n,this.loadNamespaces=r}get(e){let t=this.handlerChain.getEntries();for(let n in t){let r=t[n];if(r&&typeof r=="object"&&e in r){let s=r[e];try{if(typeof s=="string"){let a=JSON.parse(s);return typeof a=="object"&&"text"in a?{value:String(a.text),styles:a.styles||void 0}:{value:s,styles:void 0}}return{value:JSON.stringify(s),styles:void 0}}catch{return{value:typeof s=="string"?s:JSON.stringify(s),styles:void 0}}}}return null}set(e,t,n){let[r,s,...a]=e.split(":"),i=a.join(":");if(!r||!s||!i)throw new Error(`Invalid cache key format: "${e}". Expected format: "locale:namespace:key"`);this.handlerChain.setCache(e,t,n),this.bus.emit("cache:set",{payload:{key:e,value:t,styles:n,optimistic:!0}})}has(e){return this.get(e)!==null}async invalidate(e={}){let{namespace:t,locale:n,key:r,predicate:s,refetch:a=!0}=e,i=this.currentLocale(),c=0;if(r){let[u,p]=r.split(":");u&&p&&(this.handlerChain.clearNamespace(u,p),c=1)}else if(t&&n)this.handlerChain.clearNamespace(n,t),c=this.countClearedKeys(n,t);else if(t)this.handlerChain.clearNamespace(i,t),c=this.countClearedKeys(i,t);else if(n){let u=this.handlerChain.getEntries(),p=new Set;for(let m in u){let g=u[m];if(g&&typeof g=="object"){for(let h of Object.keys(g))if(h.startsWith(`${n}:`)||h.startsWith(`@${n}:`)){let f=h.replace("@","").split(":");f[1]&&p.add(f[1])}}}for(let m of p)this.handlerChain.clearNamespace(n,m),c++}else if(s){let u=this.handlerChain.getEntries(),p=new Map;for(let m in u){let g=u[m];if(g&&typeof g=="object"){for(let h of Object.keys(g))if(s(h)){let f=h.replace("@","").split(":"),S=f[0],I=f[1];S&&I&&(p.has(S)||p.set(S,new Set),p.get(S).add(I),c++)}}}for(let[m,g]of p)for(let h of g)this.handlerChain.clearNamespace(m,h)}else this.handlerChain.clearCache(),c=-1;this.bus.emit("cache:invalidate",{payload:{filter:e,keysCleared:c,refetch:a}}),a&&await this.refetchAfterInvalidate(e)}countClearedKeys(e,t){let n=this.handlerChain.getEntries(),r=0,s=`${e}:${t}:`,a=`@${e}:${t}`;for(let i in n){let c=n[i];if(c&&typeof c=="object")for(let u of Object.keys(c))(u.startsWith(s)||u===a)&&r++}return r}async refetchAfterInvalidate(e){let{namespace:t,locale:n,key:r}=e,s=this.currentLocale();if(r){let[a,i]=r.split(":");a&&i&&await this.loadNamespaces(a,[i])}else t&&await this.loadNamespaces(n||s,[t])}};var Xe=/<\/?[0-9]+\/?>/,Ze=/<[a-z][a-z0-9]*(?:\s+[^>]*)?\/?>/i,M=class{constructor(e,t,n="en",r="en",s){d(this,"handlerChain");d(this,"currentLocale");d(this,"fallbackLocale");d(this,"defaultNamespace");d(this,"pendingTranslations",new Map);d(this,"bus");d(this,"plugins",new Map);d(this,"formatters",new Map);d(this,"processors",new Map);d(this,"eventPlugins",new Set);d(this,"markupParser",new de);d(this,"htmlSerializer",new D);d(this,"cache");this.bus=e,this.handlerChain=t,this.currentLocale=n,this.fallbackLocale=r,this.defaultNamespace=s,this.cache=new ue(this.handlerChain,this.bus,()=>this.currentLocale,(a,i)=>this.loadNamespaces(a,i))}registerPlugin(e){this.plugins.set(e.name,e),this.isEmbeddedPlugin(e)&&this.integrateEmbeddedPlugin(e),this.isEventPlugin(e)&&this.eventPlugins.add(e)}integrateEmbeddedPlugin(e){if(e.getFormatters){let t=e.getFormatters();Object.entries(t).forEach(([n,r])=>{this.formatters.set(n,r),l.debug(`Embedded formatter: ${n} from ${e.name}`)})}if(e.getProcessors){let t=e.getProcessors();Object.entries(t).forEach(([n,r])=>{this.processors.set(n,r),l.debug(`Embedded processor: ${n} from ${e.name}`)})}}t(e,...t){let[n,r]=t,s=Z(e,this.currentLocale,n,r,this.defaultNamespace,this.fallbackLocale);l.debug(`Translation requested: ${s.cleanKey}`);let a=this.bus.translation(s);a.request();let i=this.handlerChain.handleSync(s);if(i&&i.status===200){let p=this.processValue(i.value,s);return l.debug(`Translation found: ${s.cleanKey} from ${i.source} (${i.duration}ms)`),a.success(p),p}this.triggerBackgroundLoad(s);let c=s.parsedDefaultValue||s.cleanKey,u=this.processValue(c,s);return l.debug(`Translation fallback: ${s.cleanKey}`),a.fallback(u),u}tHtml(e,...t){let[n,r]=t,s=Z(e,this.currentLocale,n,r,this.defaultNamespace,this.fallbackLocale);l.debug(`HTML translation requested: ${s.cleanKey}`);let a=this.bus.translation(s);a.request();let i=this.handlerChain.handleSync(s);if(i&&i.status===200){let p=this.processValueAsHtml(i.value,s,i.styles);return l.debug(`HTML translation found: ${s.cleanKey} from ${i.source}`),a.success(p),p}this.triggerBackgroundLoad(s);let c=s.parsedDefaultValue||s.cleanKey,u=this.processValueAsHtml(c,s);return l.debug(`HTML translation fallback: ${s.cleanKey}`),a.fallback(u),u}processValueAsHtml(e,t,n){let r=this.processTranslationValue(e,t);if(this.containsIndexedTags(r)){let s=n||this.getStylesFromNamespace(t),a={text:r,styles:s};return this.htmlSerializer.serialize(a)}if(this.containsHtml(r)){let s=this.markupParser.parse(r);return this.htmlSerializer.serialize(s)}return r}processValue(e,t){return this.containsIndexedTags(e)?this.processIndexedValue(e,t):this.containsHtml(e)?this.processHtmlValue(e,t):this.processTranslationValue(e,t)}containsIndexedTags(e){return Xe.test(e)}processIndexedValue(e,t){return this.processTranslationValue(e,t).replace(/<\/?[0-9]+\/?>/g,"")}getStylesFromNamespace(e){if(!e.namespace)return{};try{let t=w(e.locale,e.namespace),n=this.handlerChain.getNamespaceData(t);if(!n)return{};let r=N(n,e.cleanKey);return r&&typeof r=="object"&&"styles"in r?r.styles:{}}catch(t){return l.debug(`Error getting styles for key ${e.cleanKey}:`,t),{}}}processHtmlValue(e,t){try{let n=this.markupParser.parse(e);return this.processTranslationValue(n.text,t).replace(/<\/?[0-9]+\/?>/g,"")}catch(n){return l.warn(`ContentUnit processing failed for "${e}":`,n),this.processTranslationValue(e,t)}}processTranslationValue(e,t,n,r){let s,a,i;if(t&&"cleanKey"in t){let u=t;s=u.parsedParams,a=u.locale,i=u.cleanKey}else s=t,a=n||this.currentLocale,i=r;let c=e;try{if(c=this.applyStructuralFormatters(c,s,i),this.formatters.has("interpolate")&&(c=this.formatters.get("interpolate")(c,s,a,i)),this.processors.size>0)for(let[u,p]of this.processors.entries())try{c=p(c,s,i)}catch(m){l.warn(`Processor ${u} failed:`,m)}return c}catch(u){return l.warn(`Translation processing failed for "${e}":`,u),e}}getContentUnit(e,t,n){let r=Z(e,this.currentLocale,t,n,this.defaultNamespace,this.fallbackLocale),s=this.handlerChain.handleSync(r),a=s&&s.status===200?s.value:r.parsedDefaultValue||r.cleanKey;return(!s||s.status!==200)&&this.triggerBackgroundLoad(r),this.markupParser.parse(a)}processContentText(e,t){return this.processTranslationValue(e,t,this.currentLocale)}containsHtml(e){return Ze.test(e)}applyStructuralFormatters(e,t,n){let r=e,s=i=>typeof i?.count=="number",a=i=>typeof i?.context=="string";if(this.formatters.has("plural")&&s(t)){let i=this.formatters.get("plural");try{let c=i(r,t,this.currentLocale,n);if(c!==String(r))return c}catch(c){l.warn("Plural formatting failed:",c)}}if(this.formatters.has("context")&&a(t)){let i=this.formatters.get("context");try{let c=i(r,t,this.currentLocale,n);if(c!==String(r))return c}catch(c){l.warn("Context formatting failed:",c)}}return String(r)}triggerBackgroundLoad(e){l.debug(`Background load: ${e.cleanKey}`);let t=e.individualCacheKey;if(!this.pendingTranslations.has(t)){let n=this.handlerChain.handleAsync(e).then(r=>{r&&r.value?l.debug(`Cached: ${e.cleanKey} = "${r.value}"`):l.debug(`Not found: ${e.cleanKey}`)}).catch(r=>{l.warn(`Background load failed: ${e.cleanKey}`,r)});this.pendingTranslations.set(t,n),n.finally(()=>this.pendingTranslations.delete(t))}}getCurrentLocale(){return this.currentLocale}setDefaultNamespace(e){this.defaultNamespace=e}getDefaultNamespace(){return this.defaultNamespace}getEntries(){return this.handlerChain.getEntries()}isCached(e){let t=Z(e,this.currentLocale,void 0,void 0,this.defaultNamespace,this.fallbackLocale);return this.handlerChain.isCached(t)}getHandlerChainInfo(){return this.handlerChain.getChainInfo()}async changeLanguage(e,t){let n=this.currentLocale;if(n===e){l.debug(`Language already set to ${e}`);return}let r=t?.clear||!1,s=this.bus.language(n,e);try{l.info(`Language change: ${n} \u2192 ${e}`),l.debug("Language change options",{clear:r,preloadNamespaces:t?.preloadNamespaces}),s.start(),this.currentLocale=e,r&&(await this.clearCache(),this.clearOldLocalePendingTranslations(n)),t?.preloadNamespaces?.length&&await this.loadNamespaces(e,t.preloadNamespaces),s.complete(),l.info(`Language changed: ${e}`)}catch(a){throw l.error("Language change failed:",a),s.error(a),a}}async clearCache(){this.handlerChain.clearCache(),l.debug(`Cache cleared for locale: ${this.currentLocale}`)}clearOldLocalePendingTranslations(e){let t=0;for(let n of this.pendingTranslations.keys())n.includes(`${e}:`)&&(this.pendingTranslations.delete(n),t++);t>0&&l.debug(`Cleared ${t} pending translations for ${e}`)}async loadNamespaces(e,t){l.debug(`Preloading ${t.length} namespaces for ${e}`);let n=t.map(async r=>{try{await this.handlerChain.loadNamespace?.(e,r),l.debug(`Preloaded: ${e}:${r}`)}catch(s){l.warn(`Failed to preload ${e}:${r}:`,s)}});await Promise.allSettled(n)}async reloadNamespace(e,t){let n=t||this.currentLocale;l.debug(`Reloading namespace: ${n}:${e}`),await this.cache.invalidate({namespace:e,locale:n,refetch:!0}),l.info(`Namespace reloaded: ${n}:${e}`)}isEmbeddedPlugin(e){return e.capabilities.some(t=>["formatters","processors","pluralization","context"].includes(t))}isEventPlugin(e){return e.capabilities.some(t=>["analytics","logging","react","validation","dev-tools","monitoring"].includes(t))}};var Ke=6e4,pe=class{constructor(e,t,n){d(this,"queue",new Map);d(this,"debounceTimer",null);d(this,"repository");d(this,"config");d(this,"eventEmitter");d(this,"recentlySynced",new Map);this.repository=e,this.config=t,this.eventEmitter=n??null,t.enabled?l.debug(`MissingTranslationQueue: debounce=${t.debounceMs}ms, batchSize=${t.batchSize}`):l.debug("MissingTranslationQueue is disabled")}add(e){if(!this.config.enabled)return;let t=`${e.locale}:${e.namespace}:${e.key}`,n=this.recentlySynced.get(t);if(n&&Date.now()-n<Ke){l.debug(`Skipping recently synced key: ${t}`);return}if(this.queue.set(t,e),l.debug(`Missing translation queued: ${t} (queue size: ${this.queue.size})`),this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.queue.size>=this.config.batchSize){l.debug(`Batch size reached (${this.config.batchSize}), flushing`),this.flush();return}this.debounceTimer=setTimeout(()=>{this.flush()},this.config.debounceMs)}flush(){if(this.queue.size===0)return;let e=Date.now();for(let[r,s]of this.recentlySynced)e-s>=Ke&&this.recentlySynced.delete(r);let t=Array.from(this.queue.entries()).map(([r,s])=>({key:r,value:s.fallbackValue,styles:s.styles})),n=t.length;this.queue.clear(),this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),l.debug(`Flushing ${n} missing translations`),this.syncBatch(t).catch(r=>{l.warn(`Failed to sync ${n} missing translations:`,r)})}async syncBatch(e){try{if(e.some(s=>s.styles&&Object.keys(s.styles).length>0)&&"setBatchContentUnits"in this.repository){let s=e.map(a=>({key:a.key,value:{text:a.value,styles:a.styles??{}}}));await this.repository.setBatchContentUnits(s),l.debug(`Synced ${e.length} missing translations (ContentUnit)`)}else if("setBatch"in this.repository){let s=e.map(a=>({key:a.key,value:a.value}));await this.repository.setBatch(s),l.debug(`Synced ${e.length} missing translations`)}else l.warn("Repository does not support setBatch, syncing individually"),await this.syncIndividually(e);let n=Date.now(),r=[];for(let s of e)this.recentlySynced.set(s.key,n),r.push(s.key);this.eventEmitter&&this.eventEmitter.emit("sync:batch:complete",{payload:{count:e.length,keys:r}})}catch(t){throw l.error("Batch sync failed:",t),t}}async syncIndividually(e){let t=e.map(async n=>{try{await this.repository.set(n.key,n.value),l.debug(`Synced: ${n.key}`)}catch(r){l.warn(`Failed to sync ${n.key}:`,r)}});await Promise.allSettled(t)}getQueueSize(){return this.queue.size}getStats(){return{queueSize:this.queue.size,enabled:this.config.enabled,debounceMs:this.config.debounceMs,batchSize:this.config.batchSize}}destroy(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.queue.clear(),this.recentlySynced.clear(),l.debug("MissingTranslationQueue destroyed")}};var U=class o{constructor(e){d(this,"config");d(this,"plugins",[]);d(this,"syncStorageRepos",[]);d(this,"asyncStorageRepos",[]);d(this,"networkRepos",[]);d(this,"syncQueue",null);this.config={defaultLocale:e.defaultLocale||"en",fallbackLocale:e.fallbackLocale||"en",namespace:e.namespace||"app"}}static init(e={}){return new o(e)}useSyncStorage(e){return this.syncStorageRepos.push(e),this}useAsyncStorage(e){return this.asyncStorageRepos.push(e),this}useNetwork(e){return this.networkRepos.push(e),this}use(e){switch(e.type){case"plugin":this.plugins.push(e);break;case"memory":this.useSyncStorage(e);break;case"storage":this.useAsyncStorage(e);break;case"network":this.useNetwork(e);break}return this}async build(){let e=new re,t=e.builder();l.info("Builder started"),l.debug("Builder config",this.config),t.buildStart(this.config.defaultLocale,this.config.namespace);let n=new se(e);for(let i of this.syncStorageRepos){if(!i.getConfig().enabled)continue;let c=new ie(e,i);t.use("sync"),n.addSyncHandler(c)}for(let i of this.asyncStorageRepos){if(!i.getConfig().enabled)continue;let c=new oe(e,i);t.use("async"),n.addAsyncHandler(c)}let r=null;for(let i of this.networkRepos){if(!i.getConfig().enabled||!i.getConfig().options?.baseUrl)continue;let c=new le(e,i);r||(r=c),t.use("network"),n.addAsyncHandler(c);let u=i.getConfig();u.options?.syncMissing?.enabled&&(this.syncQueue=new pe(i,{enabled:u.options.syncMissing.enabled,debounceMs:u.options.syncMissing.debounceMs||500,batchSize:u.options.syncMissing.batchSize||50},e),e.on("translation:not-found",p=>{this.syncQueue&&this.syncQueue.add({key:p.payload.key,fallbackValue:p.payload.fallbackValue,styles:p.payload.styles,locale:p.payload.locale,namespace:p.payload.namespace})}),l.info("Missing translation sync enabled"),l.debug("Sync queue config",u.options.syncMissing))}l.debug("Handler chain constructed");let s=new M(e,n,this.config.defaultLocale,this.config.fallbackLocale,this.config.namespace);for(let i of this.plugins)t.use("plugin"),await i.initialize({core:s,bus:e}),s.registerPlugin(i),l.info(`Plugin initialized: ${i.name}`),l.debug(`Plugin version: ${i.version}`,i.capabilities);let a=n.getChainInfo();return r&&await this.executePreloading(r,n),l.info("Builder completed"),t.buildDone(a.handlers.map(i=>i.name),this.plugins.map(i=>i.name)),s}async executePreloading(e,t){let n=e.getPreload().filter(s=>s.eager!==!1);if(!n||n.length===0)return;l.info(`Preloading ${n.length} namespaces`),l.debug("Preload targets",{namespaces:n.map(s=>`${s.locale}:${s.namespace}`)});let r=n.map(async s=>{try{let a=await e.loadNamespace(s.locale,s.namespace);if(a&&a.data&&a.status===200){let i={locale:s.locale,namespace:s.namespace,fallbackLocale:this.config.fallbackLocale};await t.saveNamespaceToHandlers(a.data,i),l.debug(`Preloaded: ${s.locale}:${s.namespace}`)}}catch(a){l.warn(`Preload failed: ${s.locale}:${s.namespace}`,a)}});await Promise.allSettled(r),l.info("Preloading completed")}};var ee=class ee{constructor(e={}){d(this,"name","NetworkRepository");d(this,"type","network");d(this,"config",{});d(this,"namespaceVersions",new Map);d(this,"DEFAULT_ENDPOINTS",{getTranslation:"/api/integrations/translations/:key",getNamespace:"/api/integrations/translations/:locale/:namespace",setTranslation:"/api/integrations/sync/:key",setNamespace:"/api/integrations/sync/:locale/:namespace",setBatch:"/api/integrations/sync/batch",removeTranslation:"/api/integrations/sync/:key",clearTranslations:"/translations"});this.config={options:{timeout:e.options?.timeout??5e3,baseUrl:e.options?.baseUrl??"",headers:e.options?.headers??{}},...e}}async get(e){if(!this.config?.options?.baseUrl)throw l.debug("API base URL is not set"),new x("API base URL is not set");let t=this.withDraftsParam(this.buildUrl("getTranslation",{key:e}));l.debug(`API GET: ${t}`);try{let n=await this.makeRequest(t,"GET");n.ok||this.handleHttpError(n,e);let r=await n.json();l.debug("API response data:",r);let s=r.translations[r.meta?.key]||r.translations[e]||Object.values(r.translations)[0];if(l.debug(`Fetched translation for key "${e}":`,s),!s)throw new b(e);return typeof s=="object"&&"text"in s?(l.debug(`ContentUnit text: "${s.text}"`),s.text):String(s)}catch(n){this.handleCaughtError(n)}}async getContentUnit(e){if(!this.config?.options?.baseUrl)throw l.debug("API base URL is not set"),new x("API base URL is not set");let t=this.withDraftsParam(this.buildUrl("getTranslation",{key:e}));l.debug(`API GET ContentUnit: ${t}`);try{let n=await this.makeRequest(t,"GET");n.ok||this.handleHttpError(n,e);let r=await n.json();l.debug("API response data:",r);let s=r.translations[r.meta?.key]||r.translations[e]||Object.values(r.translations)[0];if(!s)throw new b(e);return typeof s=="object"&&"text"in s?(l.debug(`ContentUnit for "${e}": text="${s.text}", styles=`,s.styles),{text:s.text,styles:s.styles||{}}):(l.debug(`Plain string for "${e}": "${s}" (no styles)`),{text:String(s),styles:{}})}catch(n){this.handleCaughtError(n)}}async getNamespace(e,t){if(!this.config?.options?.baseUrl)throw l.debug("API base URL is not set"),new x("API base URL is not set");let n=this.withDraftsParam(this.buildUrl("getNamespace",{locale:e,namespace:t}));l.debug(`API GET Namespace: ${n}`);let r=`${e}:${t}`;try{let s={},a=this.getVersion(r);a&&(s["If-None-Match"]=`W/"${a}"`);let i=await this.makeRequest(n,"GET",void 0,s);if(i.status===304)return l.debug(`Namespace ${r}: 304 Not Modified`),null;i.ok||this.handleHttpError(i,r);let c=await i.json();if(l.debug("API response data:",c),!c.translations)throw new b(r);let u=c.meta?.version!=null?String(c.meta.version):null;return u&&this.setVersion(r,u),c.translations}catch(s){this.handleCaughtError(s)}}async set(e,t){if(!this.config?.options?.baseUrl)return l.debug("API base URL is not set"),Promise.reject(new Error("API base URL is not set"));try{let n=this.buildUrl("setTranslation",{key:e}),r=await this.makeRequest(n,"PUT",{translation:t});if(!r.ok)throw new Error(`Failed to save translation: ${r.status}`)}catch(n){throw l.debug(`API set failed for key "${e}":`,n),n}}async setNamespace(e,t,n){if(!this.config?.options?.baseUrl)return l.debug("API base URL is not set"),Promise.reject(new Error("API base URL is not set"));try{let r=this.buildUrl("setNamespace",{locale:e,namespace:t}),s=await this.makeRequest(r,"PUT",{translations:n});if(!s.ok)throw new Error(`Failed to save namespace: ${s.status}`)}catch(r){throw l.debug(`API setNamespace failed for ${e}:${t}:`,r),r}}async setBatch(e){if(!this.config?.options?.baseUrl)return l.debug("API base URL is not set"),Promise.reject(new Error("API base URL is not set"));try{let t=this.buildUrl("setBatch");l.debug(`API POST Batch: ${t} (${e.length} items)`);let n=await this.makeRequest(t,"POST",{translations:e});if(!n.ok)throw new Error(`Failed to sync batch: ${n.status}`);l.debug(`Batch sync successful: ${e.length} items`)}catch(t){throw l.debug(`API setBatch failed for ${e.length} items:`,t),t}}async getNamespaceContentUnits(e,t){if(!this.config?.options?.baseUrl)throw l.debug("API base URL is not set"),new x("API base URL is not set");let n=this.withDraftsParam(this.buildUrl("getNamespace",{locale:e,namespace:t}));l.debug(`API GET Namespace ContentUnits: ${n}`);let r=`${e}:${t}`;try{let s={},a=this.getVersion(r);a&&(s["If-None-Match"]=`W/"${a}"`);let i=await this.makeRequest(n,"GET",void 0,s);if(i.status===304)return l.debug(`Namespace ContentUnits ${r}: 304 Not Modified`),null;i.ok||this.handleHttpError(i,r);let c=await i.json();if(l.debug("API response data:",c),!c.translations)throw new b(r);let u=c.meta?.version!=null?String(c.meta.version):null;return u&&this.setVersion(r,u),c.translations}catch(s){this.handleCaughtError(s)}}async setContentUnit(e,t){if(!this.config?.options?.baseUrl)return l.debug("API base URL is not set"),Promise.reject(new Error("API base URL is not set"));try{let n=this.buildUrl("setTranslation",{key:e}),r=await this.makeRequest(n,"PUT",{translation:t,format:"contentunit"});if(!r.ok)throw new Error(`Failed to save ContentUnit: ${r.status}`);l.debug(`Saved ContentUnit for key "${e}"`)}catch(n){throw l.debug(`API setContentUnit failed for key "${e}":`,n),n}}async setBatchContentUnits(e){if(!this.config?.options?.baseUrl)return l.debug("API base URL is not set"),Promise.reject(new Error("API base URL is not set"));try{let t=this.buildUrl("setBatch");l.debug(`API POST Batch ContentUnits: ${t} (${e.length} items)`);let n=await this.makeRequest(t,"POST",{translations:e,format:"contentunit"});if(!n.ok)throw new Error(`Failed to sync batch ContentUnits: ${n.status}`);l.debug(`Batch ContentUnit sync successful: ${e.length} items`)}catch(t){throw l.debug(`API setBatchContentUnits failed for ${e.length} items:`,t),t}}async remove(e){if(!this.config?.options?.baseUrl)return l.debug("API base URL is not set"),Promise.reject(new Error("API base URL is not set"));try{let t=this.buildUrl("removeTranslation",{key:e}),n=await this.makeRequest(t,"DELETE");if(!n.ok)throw new Error(`Failed to remove translation: ${n.status}`)}catch(t){throw l.debug(`API remove failed for key "${e}":`,t),t}}async clear(){if(!this.config?.options?.baseUrl)return l.debug("API base URL is not set"),Promise.reject(new Error("API base URL is not set"));try{let e=this.buildUrl("clearTranslations"),t=await this.makeRequest(e,"DELETE");if(!t.ok)throw new Error(`Failed to clear translations: ${t.status}`)}catch(e){throw l.debug("API clear failed:",e),e}}getConfig(){return this.config}getVersion(e){let t=this.namespaceVersions.get(e);if(t)return t;try{let n=localStorage.getItem(ee.VERSION_PREFIX+e);if(n)return this.namespaceVersions.set(e,n),n}catch{}}setVersion(e,t){this.namespaceVersions.set(e,t);try{localStorage.setItem(ee.VERSION_PREFIX+e,t)}catch{}}handleHttpError(e,t){if(l.debug(`API response: ${e.status} ${e.statusText}`),e.status===404)throw new b(t);if(e.status===423){let n=e.headers.get("Retry-After");throw new L(t,n?parseInt(n,10)*1e3:void 0)}throw e.status>=500&&e.status<600?new K(t,e.status):new x(`HTTP ${e.status}: ${e.statusText}`)}handleCaughtError(e){throw e instanceof b||e instanceof L||e instanceof K||e instanceof x?e:new x("Network request failed",e)}buildUrl(e,t={}){let n=this.config.options?.baseUrl||"",r=this.config.options?.endpoints?.[e]||this.DEFAULT_ENDPOINTS[e];r.startsWith("/")||(r=`/${r}`);let s=r;for(let[a,i]of Object.entries(t)){let c=new RegExp(`:${a}`,"g");s=s.replace(c,encodeURIComponent(i))}return`${n}${s}`}isEditorPreviewSession(){return typeof document>"u"?!1:document.cookie.split("; ").some(e=>e==="__lr_editor_active=1")}withDraftsParam(e){return this.isEditorPreviewSession()?e+(e.includes("?")?"&":"?")+"include_drafts=true":e}async makeRequest(e,t,n,r){let s=new AbortController,a=this.config.options?.timeout??1e4,i=setTimeout(()=>s.abort(),a);try{let c={"Content-Type":"application/json",...this.config.options?.headers,...r};return this.config.options?.apiKey&&(c.Authorization=`Bearer ${this.config.options.apiKey}`),await fetch(e,{method:t,headers:c,body:n?JSON.stringify(n):void 0,signal:s.signal})}finally{clearTimeout(i)}}};d(ee,"VERSION_PREFIX","lionrapid:v:");var H=ee;var j=class{constructor(e){d(this,"name","MemoryRepository");d(this,"type","memory");d(this,"config",{});d(this,"cache",new Map);d(this,"accessOrder",new Map);d(this,"maxSize",1e3);this.config=e,this.maxSize=this.config.options?.maxSize||1e3}get(e){let t=this.cache.get(e);return t!==void 0?(this.accessOrder.set(e,Date.now()),t):null}set(e,t){this.cache.size>=this.maxSize&&!this.cache.has(e)&&this.evictOldest(),this.cache.set(e,t),this.accessOrder.set(e,Date.now())}remove(e){this.cache.delete(e),this.accessOrder.delete(e)}clear(){this.cache.clear(),this.accessOrder.clear()}clearNamespace(e,t){let n=w(e,t),r=`${e}:${t}:`;this.cache.delete(n),this.accessOrder.delete(n);for(let s of this.cache.keys())s.startsWith(r)&&(this.cache.delete(s),this.accessOrder.delete(s))}getNamespace(e,t){let n=w(e,t),r=this.cache.get(n);if(!r)return null;try{return JSON.parse(r)}catch{return this.cache.delete(n),null}}setNamespace(e,t,n){let r=w(e,t);this.cache.set(r,JSON.stringify(n))}evictOldest(){let e="",t=Date.now();for(let[n,r]of this.accessOrder.entries())r<t&&(t=r,e=n);e&&(this.cache.delete(e),this.accessOrder.delete(e))}getEntries(){let e={};for(let[t,n]of this.cache.entries())e[t]=n;return e}getConfig(){return this.config}};var qe={emails:!0,urls:!0,numbers:!0,phones:!0},ge={email:/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,url:/^(https?:\/\/|www\.)[^\s]+$/i,number:/^[\d\s.,+-]+$/,phone:/^[+\d][\d\s().-]{6,}$/},B=class{constructor(e={},t=2){d(this,"patterns");d(this,"minTextLength");this.patterns={...qe,...e},this.minTextLength=t}shouldExclude(e){let t=e.trim();return!!(t.length<this.minTextLength||this.patterns.emails&&ge.email.test(t)||this.patterns.urls&&ge.url.test(t)||this.patterns.numbers&&ge.number.test(t)||this.patterns.phones&&ge.phone.test(t))}};function te(o){let e={},t=0;function n(s){if(s.nodeType===Node.TEXT_NODE)return s.nodeValue??"";if(s.nodeType!==Node.ELEMENT_NODE)return"";let a=s,i=a.tagName.toLowerCase(),c={};for(let m=0;m<a.attributes.length;m++){let g=a.attributes[m];c[g.name.toLowerCase()]=g.value}t++;let u=t;if(e[String(u)]=[`raw:${ce(i,c)}`],O.has(i))return`<${u}/>`;let p="";for(let m=0;m<s.childNodes.length;m++)p+=n(s.childNodes[m]);return`<${u}>${p}</${u}>`}let r="";for(let s=0;s<o.childNodes.length;s++)r+=n(o.childNodes[s]);return{text:r,styles:e}}function $(o,e){let t=(o&65535)+(e&65535);return(o>>16)+(e>>16)+(t>>16)<<16|t&65535}function et(o,e){return o<<e|o>>>32-e}function me(o,e,t,n,r,s){return $(et($($(e,o),$(n,s)),r),t)}function C(o,e,t,n,r,s,a){return me(e&t|~e&n,o,e,r,s,a)}function E(o,e,t,n,r,s,a){return me(e&n|t&~n,o,e,r,s,a)}function R(o,e,t,n,r,s,a){return me(e^t^n,o,e,r,s,a)}function T(o,e,t,n,r,s,a){return me(t^(e|~n),o,e,r,s,a)}function tt(o,e){o[e>>5]|=128<<e%32,o[(e+64>>>9<<4)+14]=e;let t=1732584193,n=-271733879,r=-1732584194,s=271733878;for(let a=0;a<o.length;a+=16){let i=t,c=n,u=r,p=s;t=C(t,n,r,s,o[a],7,-680876936),s=C(s,t,n,r,o[a+1],12,-389564586),r=C(r,s,t,n,o[a+2],17,606105819),n=C(n,r,s,t,o[a+3],22,-1044525330),t=C(t,n,r,s,o[a+4],7,-176418897),s=C(s,t,n,r,o[a+5],12,1200080426),r=C(r,s,t,n,o[a+6],17,-1473231341),n=C(n,r,s,t,o[a+7],22,-45705983),t=C(t,n,r,s,o[a+8],7,1770035416),s=C(s,t,n,r,o[a+9],12,-1958414417),r=C(r,s,t,n,o[a+10],17,-42063),n=C(n,r,s,t,o[a+11],22,-1990404162),t=C(t,n,r,s,o[a+12],7,1804603682),s=C(s,t,n,r,o[a+13],12,-40341101),r=C(r,s,t,n,o[a+14],17,-1502002290),n=C(n,r,s,t,o[a+15],22,1236535329),t=E(t,n,r,s,o[a+1],5,-165796510),s=E(s,t,n,r,o[a+6],9,-1069501632),r=E(r,s,t,n,o[a+11],14,643717713),n=E(n,r,s,t,o[a],20,-373897302),t=E(t,n,r,s,o[a+5],5,-701558691),s=E(s,t,n,r,o[a+10],9,38016083),r=E(r,s,t,n,o[a+15],14,-660478335),n=E(n,r,s,t,o[a+4],20,-405537848),t=E(t,n,r,s,o[a+9],5,568446438),s=E(s,t,n,r,o[a+14],9,-1019803690),r=E(r,s,t,n,o[a+3],14,-187363961),n=E(n,r,s,t,o[a+8],20,1163531501),t=E(t,n,r,s,o[a+13],5,-1444681467),s=E(s,t,n,r,o[a+2],9,-51403784),r=E(r,s,t,n,o[a+7],14,1735328473),n=E(n,r,s,t,o[a+12],20,-1926607734),t=R(t,n,r,s,o[a+5],4,-378558),s=R(s,t,n,r,o[a+8],11,-2022574463),r=R(r,s,t,n,o[a+11],16,1839030562),n=R(n,r,s,t,o[a+14],23,-35309556),t=R(t,n,r,s,o[a+1],4,-1530992060),s=R(s,t,n,r,o[a+4],11,1272893353),r=R(r,s,t,n,o[a+7],16,-155497632),n=R(n,r,s,t,o[a+10],23,-1094730640),t=R(t,n,r,s,o[a+13],4,681279174),s=R(s,t,n,r,o[a+0],11,-358537222),r=R(r,s,t,n,o[a+3],16,-722521979),n=R(n,r,s,t,o[a+6],23,76029189),t=R(t,n,r,s,o[a+9],4,-640364487),s=R(s,t,n,r,o[a+12],11,-421815835),r=R(r,s,t,n,o[a+15],16,530742520),n=R(n,r,s,t,o[a+2],23,-995338651),t=T(t,n,r,s,o[a],6,-198630844),s=T(s,t,n,r,o[a+7],10,1126891415),r=T(r,s,t,n,o[a+14],15,-1416354905),n=T(n,r,s,t,o[a+5],21,-57434055),t=T(t,n,r,s,o[a+12],6,1700485571),s=T(s,t,n,r,o[a+3],10,-1894986606),r=T(r,s,t,n,o[a+10],15,-1051523),n=T(n,r,s,t,o[a+1],21,-2054922799),t=T(t,n,r,s,o[a+8],6,1873313359),s=T(s,t,n,r,o[a+15],10,-30611744),r=T(r,s,t,n,o[a+6],15,-1560198380),n=T(n,r,s,t,o[a+13],21,1309151649),t=T(t,n,r,s,o[a+4],6,-145523070),s=T(s,t,n,r,o[a+11],10,-1120210379),r=T(r,s,t,n,o[a+2],15,718787259),n=T(n,r,s,t,o[a+9],21,-343485551),t=$(t,i),n=$(n,c),r=$(r,u),s=$(s,p)}return[t,n,r,s]}function nt(o){let e="0123456789abcdef",t="";for(let n=0;n<o.length*4;n++)t+=e.charAt(o[n>>2]>>n%4*8+4&15)+e.charAt(o[n>>2]>>n%4*8&15);return t}function rt(o){let e=[];for(let t=0;t<o.length*8;t+=8)e[t>>5]|=(o.charCodeAt(t/8)&255)<<t%32;return e}function ve(o){return nt(tt(rt(o),o.length*8))}function z(o){let e=o.trim();return"auto_"+ve(e).substring(0,12)}var we="p,h1,h2,h3,h4,h5,h6,li,td,th,label,button,figcaption,dt,dd,summary,caption",st=new Set(["SCRIPT","STYLE","CODE","PRE","TEXTAREA","NOSCRIPT","SVG"]),at=["data-lionrapid-translated","data-lionrapid-client","data-no-translate","data-lr-block"],F=class{constructor(e={},t=[],n=2){d(this,"excludeFilter");d(this,"excludeSelectors");this.excludeFilter=new B(e,n),this.excludeSelectors=t}extract(e,t=!1){let n=[],r=e.querySelectorAll(we),s=[];e instanceof Element&&e.matches(we)&&s.push(e);for(let a=0;a<r.length;a++)s.push(r[a]);for(let a=0;a<s.length;a++){let i=s[a];if(this.isInsideSkipTag(i)||!t&&this.hasSkipAttribute(i)||this.matchesExcludeSelector(i)||i.getAttribute("translate")==="no"||i.querySelector(we))continue;let c=i.getAttribute("data-lr-block"),u=i.getAttribute("data-lr-original"),p;if(u){let h=document.createElement(i.tagName);h.innerHTML=u,p=te(h)}else p=te(i);let m=p.text.replace(/<\/?[0-9]+\/?>/g,"");if(this.excludeFilter.shouldExclude(m))continue;let g;if(c)g=c;else{let h=i.getAttribute("data-i18n");h?g=h.includes(":")?h:`common:${h}`:g=z(p.text)}n.push({element:i,unit:p,key:g})}return n}isInsideSkipTag(e){let t=e.parentElement;for(;t;){if(st.has(t.tagName))return!0;t=t.parentElement}return!1}hasSkipAttribute(e){let t=e;for(;t;){for(let n of at)if(t.hasAttribute(n))return!0;t=t.parentElement}return!1}matchesExcludeSelector(e){for(let t of this.excludeSelectors)try{if(e.matches(t)||e.closest(t))return!0}catch{}return!1}};var V=class{constructor(e,t=50){d(this,"observer",null);d(this,"callbacks");d(this,"debounceTimer",null);d(this,"pendingElements",new Set);d(this,"debounceMs");this.callbacks=e,this.debounceMs=t}start(){this.observer||(this.observer=new MutationObserver(e=>{this.handleMutations(e)}),this.observer.observe(document.body,{childList:!0,subtree:!0}))}stop(){this.observer&&(this.observer.disconnect(),this.observer=null),this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.pendingElements.clear()}handleMutations(e){let t=!1;for(let n of e)for(let r of Array.from(n.addedNodes)){if(r.nodeType!==Node.ELEMENT_NODE)continue;let s=r;this.hasLanguageSwitcher(s)&&(t=!0),this.callbacks.onNewContent&&this.pendingElements.add(s)}t&&this.callbacks.onNewSwitchers&&this.callbacks.onNewSwitchers(),this.pendingElements.size>0&&this.scheduleFlush()}scheduleFlush(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.flushPendingElements()},this.debounceMs)}flushPendingElements(){if(!(!this.callbacks.onNewContent||this.pendingElements.size===0)){for(let e of this.pendingElements)document.body.contains(e)&&this.callbacks.onNewContent(e);this.pendingElements.clear()}}hasLanguageSwitcher(e){return e.hasAttribute("data-lionrapid-switcher")||e.querySelector("[data-lionrapid-switcher]")!==null}};var it=new D,_=class{constructor(e={}){d(this,"core",null);d(this,"blockExtractor");d(this,"domObserver",null);d(this,"locale","");d(this,"sourceLocale","");d(this,"namespace","");d(this,"debounceMs");d(this,"pendingElements",new Set);d(this,"debounceTimer",null);d(this,"translatedCount",0);this.blockExtractor=new F(e.excludePatterns,e.excludeSelectors,e.minTextLength),this.debounceMs=e.debounceMs??100}setCore(e){this.core=e}init(e){this.locale=e.locale,this.sourceLocale=e.sourceLocale,this.namespace=e.namespace}updateLocale(e){this.locale=e}isReady(){return this.core!==null}generateAutoKey(e){return z(e)}queueElement(e){this.pendingElements.add(e),this.scheduleProcessing()}translateElement(e){if(!this.core)return 0;let t=this.blockExtractor.extract(e);return this.translateBlocks(t)}translatePage(){return this.translateElement(document.body)}observe(){this.domObserver||(this.domObserver=new V({onNewContent:e=>this.queueElement(e)}),this.domObserver.start())}stopObserving(){this.domObserver&&(this.domObserver.stop(),this.domObserver=null)}scheduleProcessing(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.processPendingElements()},this.debounceMs)}processPendingElements(){if(!this.core||this.pendingElements.size===0)return;let e=0;for(let t of this.pendingElements){if(!document.body.contains(t))continue;let n=this.translateElement(t);e+=n}this.pendingElements.clear(),this.translatedCount+=e}translateBlocks(e){if(!this.core)return 0;let t=0;for(let{element:n,unit:r,key:s}of e){let a=`${this.locale}:${this.namespace}:${s}`,i=this.core.cache.get(a);if(i&&i.value!==r.text&&i.value!==s){n.hasAttribute("data-lr-original")||n.setAttribute("data-lr-original",n.innerHTML);let c=i.styles&&Object.keys(i.styles).length>0,u=Object.keys(r.styles).length>0,p=/<\/?[0-9]+\/?>/.test(i.value);if(!(u&&!p)){let m=c?i.styles:r.styles,g={text:i.value,styles:m};n.innerHTML=it.serialize(g)}n.setAttribute("data-lr-block",s),n.setAttribute("data-lionrapid-client","1"),t++}else this.core.bus.emit("translation:not-found",{payload:{key:s,fallbackValue:r.text,locale:this.sourceLocale,namespace:this.namespace,status:404,styles:r.styles}})}return t}getTranslatedCount(){return this.translatedCount}retranslateElement(e){let t=e.getAttribute("data-lr-original");t!==null&&(e.innerHTML=t),e.removeAttribute("data-lionrapid-client"),e.removeAttribute("data-lr-block"),this.translateElement(e)}retranslate(){document.querySelectorAll("[data-lionrapid-client]").forEach(t=>{let n=t.getAttribute("data-lr-original");n!==null&&(t.innerHTML=n),t.removeAttribute("data-lionrapid-client"),t.removeAttribute("data-lr-block")}),this.translatedCount=0,this.locale!==this.sourceLocale&&this.translatePage()}};var Oe={en:{code:"en",name:"English",flag:"\u{1F1EC}\u{1F1E7}"},es:{code:"es",name:"Espa\xF1ol",flag:"\u{1F1EA}\u{1F1F8}"},fr:{code:"fr",name:"Fran\xE7ais",flag:"\u{1F1EB}\u{1F1F7}"},de:{code:"de",name:"Deutsch",flag:"\u{1F1E9}\u{1F1EA}"},it:{code:"it",name:"Italiano",flag:"\u{1F1EE}\u{1F1F9}"},pt:{code:"pt",name:"Portugu\xEAs",flag:"\u{1F1F5}\u{1F1F9}"},nl:{code:"nl",name:"Nederlands",flag:"\u{1F1F3}\u{1F1F1}"},pl:{code:"pl",name:"Polski",flag:"\u{1F1F5}\u{1F1F1}"},ru:{code:"ru",name:"\u0420\u0443\u0441\u0441\u043A\u0438\u0439",flag:"\u{1F1F7}\u{1F1FA}"},ja:{code:"ja",name:"\u65E5\u672C\u8A9E",flag:"\u{1F1EF}\u{1F1F5}"},ko:{code:"ko",name:"\uD55C\uAD6D\uC5B4",flag:"\u{1F1F0}\u{1F1F7}"},zh:{code:"zh",name:"\u4E2D\u6587",flag:"\u{1F1E8}\u{1F1F3}"},ar:{code:"ar",name:"\u0627\u0644\u0639\u0631\u0628\u064A\u0629",flag:"\u{1F1F8}\u{1F1E6}"},hi:{code:"hi",name:"\u0939\u093F\u0928\u094D\u0926\u0940",flag:"\u{1F1EE}\u{1F1F3}"},tr:{code:"tr",name:"T\xFCrk\xE7e",flag:"\u{1F1F9}\u{1F1F7}"},vi:{code:"vi",name:"Ti\u1EBFng Vi\u1EC7t",flag:"\u{1F1FB}\u{1F1F3}"},th:{code:"th",name:"\u0E44\u0E17\u0E22",flag:"\u{1F1F9}\u{1F1ED}"},sv:{code:"sv",name:"Svenska",flag:"\u{1F1F8}\u{1F1EA}"},da:{code:"da",name:"Dansk",flag:"\u{1F1E9}\u{1F1F0}"},fi:{code:"fi",name:"Suomi",flag:"\u{1F1EB}\u{1F1EE}"},no:{code:"no",name:"Norsk",flag:"\u{1F1F3}\u{1F1F4}"},cs:{code:"cs",name:"\u010Ce\u0161tina",flag:"\u{1F1E8}\u{1F1FF}"},el:{code:"el",name:"\u0395\u03BB\u03BB\u03B7\u03BD\u03B9\u03BA\u03AC",flag:"\u{1F1EC}\u{1F1F7}"},he:{code:"he",name:"\u05E2\u05D1\u05E8\u05D9\u05EA",flag:"\u{1F1EE}\u{1F1F1}"},id:{code:"id",name:"Bahasa Indonesia",flag:"\u{1F1EE}\u{1F1E9}"},ms:{code:"ms",name:"Bahasa Melayu",flag:"\u{1F1F2}\u{1F1FE}"},uk:{code:"uk",name:"\u0423\u043A\u0440\u0430\u0457\u043D\u0441\u044C\u043A\u0430",flag:"\u{1F1FA}\u{1F1E6}"},ro:{code:"ro",name:"Rom\xE2n\u0103",flag:"\u{1F1F7}\u{1F1F4}"},hu:{code:"hu",name:"Magyar",flag:"\u{1F1ED}\u{1F1FA}"},sk:{code:"sk",name:"Sloven\u010Dina",flag:"\u{1F1F8}\u{1F1F0}"},bg:{code:"bg",name:"\u0411\u044A\u043B\u0433\u0430\u0440\u0441\u043A\u0438",flag:"\u{1F1E7}\u{1F1EC}"},hr:{code:"hr",name:"Hrvatski",flag:"\u{1F1ED}\u{1F1F7}"},sr:{code:"sr",name:"\u0421\u0440\u043F\u0441\u043A\u0438",flag:"\u{1F1F7}\u{1F1F8}"},sl:{code:"sl",name:"Sloven\u0161\u010Dina",flag:"\u{1F1F8}\u{1F1EE}"},lt:{code:"lt",name:"Lietuvi\u0173",flag:"\u{1F1F1}\u{1F1F9}"},lv:{code:"lv",name:"Latvie\u0161u",flag:"\u{1F1F1}\u{1F1FB}"},et:{code:"et",name:"Eesti",flag:"\u{1F1EA}\u{1F1EA}"}},ot=`
3
3
  .lionrapid-switcher {
4
4
  position: fixed;
5
5
  z-index: 999999;
@@ -76,5 +76,5 @@
76
76
  .lionrapid-btn-row button:last-child { border-right: none; }
77
77
  .lionrapid-btn-row button:hover { background: #f5f5f5; }
78
78
  .lionrapid-btn-row button.active { background: #3b82f6; color: #fff; }
79
- `,G=class{constructor(){d(this,"core",null);d(this,"languages",[]);d(this,"initialLocale","en");d(this,"onLanguageChange",null);d(this,"stylesInjected",!1)}setCore(e){this.core=e}setInitialLocale(e){this.initialLocale=e}setLanguages(e){this.languages=e.map(t=>typeof t=="string"?Ae[t]||{code:t,name:t}:t)}setOnLanguageChange(e){this.onLanguageChange=e}initAll(){this.injectStyles(),document.querySelectorAll("[data-lionrapid-switcher]").forEach(t=>this.initSwitcher(t))}initSwitcher(e){let t=e.dataset.lionrapidSwitcher||"floating",n=this.core?.getCurrentLocale()||this.initialLocale;e.innerHTML="",e.classList.add("lionrapid-switcher"),e.setAttribute("data-no-translate",""),e.setAttribute("translate","no");let r=e.dataset.lionrapidSwitcherPosition||"top-right",s=e.dataset.lionrapidSwitcherShowFlags!=="false",a=e.dataset.lionrapidSwitcherShowNames!=="false",i=e.dataset.lionrapidSwitcherCustomCss||null;if(e.dataset.position=r,i){let c=document.createElement("style");c.textContent=i,document.head.appendChild(c)}switch(t){case"flags":this.renderButtonRow(e,n,!0,!0);break;case"buttons":this.renderButtonRow(e,n,s,a);break;case"floating":default:this.renderFloating(e,n,r,s,a);break}}renderFloating(e,t,n,r,s){let a={};n.startsWith("bottom")?a.bottom="100%":a.top="100%",n.endsWith("left")?a.left="0":a.right="0";let i=m=>{let h=r&&m.flag||"",f=s?m.name:m.code.toUpperCase();return`${h}${h&&f?" ":""}${f}`},c=this.languages.find(m=>m.code===t)||this.languages[0],u=c?i(c):t,p=document.createElement("button");p.type="button",p.className="lionrapid-floating-btn",p.setAttribute("aria-expanded","false"),p.setAttribute("aria-haspopup","true"),p.textContent=`${u} \u25BE`;let g=document.createElement("div");g.className="lionrapid-floating-menu",Object.assign(g.style,a);for(let m of this.languages){let h=document.createElement("button");h.type="button",h.dataset.lang=m.code,h.textContent=i(m),m.code===t&&h.classList.add("active"),h.addEventListener("click",()=>{this.handleLanguageChange(m.code),p.textContent=i(m)+" \u25BE",g.querySelectorAll("button").forEach(f=>{f.classList.toggle("active",f.dataset.lang===m.code)}),g.classList.remove("open"),p.setAttribute("aria-expanded","false")}),g.appendChild(h)}p.addEventListener("click",m=>{m.stopPropagation();let h=g.classList.contains("open");g.classList.toggle("open",!h),p.setAttribute("aria-expanded",String(!h))}),document.addEventListener("click",()=>{g.classList.remove("open"),p.setAttribute("aria-expanded","false")}),e.appendChild(p),e.appendChild(g)}renderButtonRow(e,t,n,r){let s=document.createElement("div");s.className="lionrapid-btn-row";for(let a of this.languages){let i=document.createElement("button");i.type="button",i.dataset.lang=a.code;let c=n&&a.flag||"",u=r?a.name:a.code.toUpperCase();i.textContent=`${c}${c&&u?" ":""}${u}`,a.code===t&&i.classList.add("active"),i.addEventListener("click",()=>{this.handleLanguageChange(a.code),s.querySelectorAll("button").forEach(p=>{p.classList.toggle("active",p.dataset.lang===a.code)})}),s.appendChild(i)}e.appendChild(s)}handleLanguageChange(e){this.onLanguageChange&&this.onLanguageChange(e),document.querySelectorAll(".lionrapid-btn-row button").forEach(t=>{let n=t;n.classList.toggle("active",n.dataset.lang===e)})}injectStyles(){if(this.stylesInjected)return;let e=document.createElement("style");e.textContent=ot,document.head.appendChild(e),this.stylesInjected=!0}static getLanguage(e){return Ae[e]}};var Ce="lionrapid:",J=`${Ce}version`,Me="1",Q=class{constructor(e={}){d(this,"name","LocalStorageRepository");d(this,"type","memory");d(this,"config");d(this,"available");d(this,"prefix");d(this,"defaultTTL");d(this,"maxSize");this.config={enabled:e.enabled??!0,priority:e.priority??0,options:{prefix:e.options?.prefix??Ce,ttl:e.options?.ttl??1440*60*1e3,maxSize:e.options?.maxSize??500,...e.options}},this.prefix=this.config.options?.prefix??Ce,this.defaultTTL=this.config.options?.ttl??1440*60*1e3,this.maxSize=this.config.options?.maxSize??500,this.available=this.checkAvailability(),this.available&&this.migrateIfNeeded()}checkAvailability(){if(typeof window>"u")return!1;try{let e=`${this.prefix}__test__`;return window.localStorage.setItem(e,"test"),window.localStorage.removeItem(e),!0}catch{return!1}}migrateIfNeeded(){try{window.localStorage.getItem(J)!==Me&&(this.clear(),window.localStorage.setItem(J,Me))}catch{}}get(e){if(!this.available)return null;try{let t=this.prefix+e,n=window.localStorage.getItem(t);if(!n)return null;let r=JSON.parse(n);return r.expiry!==null&&Date.now()>r.expiry?(window.localStorage.removeItem(t),null):r.value}catch{return null}}set(e,t){if(!this.available)return;let n=this.prefix+e,r={value:t,expiry:this.defaultTTL?Date.now()+this.defaultTTL:null,timestamp:Date.now()};try{this.getEntryCount()>=this.maxSize&&this.evictOldest(),window.localStorage.setItem(n,JSON.stringify(r))}catch(s){if(this.isQuotaError(s)){this.evictOldest();try{window.localStorage.setItem(n,JSON.stringify(r))}catch{}}}}remove(e){if(this.available)try{window.localStorage.removeItem(this.prefix+e)}catch{}}clear(){if(this.available)try{let e=[];for(let t=0;t<window.localStorage.length;t++){let n=window.localStorage.key(t);n?.startsWith(this.prefix)&&n!==J&&e.push(n)}e.forEach(t=>window.localStorage.removeItem(t))}catch{}}clearNamespace(e,t){if(!this.available)return;let n=`@${e}:${t}`,r=`${e}:${t}:`;try{let s=[];for(let a=0;a<window.localStorage.length;a++){let i=window.localStorage.key(a);if(!i?.startsWith(this.prefix))continue;let c=i.slice(this.prefix.length);(c===n||c.startsWith(r))&&s.push(i)}s.forEach(a=>window.localStorage.removeItem(a))}catch{}}getNamespace(e,t){let n=`@${e}:${t}`,r=this.get(n);if(!r)return null;try{return JSON.parse(r)}catch{return this.remove(n),null}}setNamespace(e,t,n){let r=`@${e}:${t}`;this.set(r,JSON.stringify(n))}getEntries(){let e={};if(!this.available)return e;try{for(let t=0;t<window.localStorage.length;t++){let n=window.localStorage.key(t);if(!n?.startsWith(this.prefix)||n===J)continue;let r=n.slice(this.prefix.length),s=this.get(r);s!==null&&(e[r]=s)}}catch{}return e}getConfig(){return this.config}isAvailable(){return this.available}getEntryCount(){if(!this.available)return 0;let e=0;try{for(let t=0;t<window.localStorage.length;t++){let n=window.localStorage.key(t);n?.startsWith(this.prefix)&&n!==J&&e++}}catch{}return e}isQuotaError(e){return e instanceof DOMException?e.name==="QuotaExceededError"||e.name==="NS_ERROR_DOM_QUOTA_REACHED":!1}evictOldest(){if(this.available)try{let e=[];for(let n=0;n<window.localStorage.length;n++){let r=window.localStorage.key(n);if(!(!r?.startsWith(this.prefix)||r===J))try{let s=window.localStorage.getItem(r);if(s){let a=JSON.parse(s);e.push({key:r,timestamp:a.timestamp})}}catch{window.localStorage.removeItem(r)}}e.sort((n,r)=>n.timestamp-r.timestamp);let t=Math.max(1,Math.floor(e.length*.25));for(let n=0;n<t&&n<e.length;n++)window.localStorage.removeItem(e[n].key)}catch{}}getCacheStats(){let e=this.getEntryCount(),t=this.maxSize>0?`${Math.round(e/this.maxSize*100)}%`:"0%";return{size:e,maxSize:this.maxSize,usage:t}}};var Ke="lionrapid-v1",x="lionrapid:",Y=class{constructor(e={}){d(this,"name","CacheStorageRepository");d(this,"type","storage");d(this,"config");d(this,"cacheName");d(this,"defaultTTL");d(this,"available");this.config={enabled:e.enabled??!0,priority:e.priority??0,options:{cacheName:e.options?.cacheName??Ke,ttl:e.options?.ttl??10080*60*1e3,...e.options}},this.cacheName=this.config.options?.cacheName??Ke,this.defaultTTL=this.config.options?.ttl??10080*60*1e3,this.available=this.checkAvailability()}checkAvailability(){return typeof caches<"u"}async get(e){if(!this.available)throw new b(e);try{let t=await caches.open(this.cacheName),n=await t.match(x+e);if(!n)throw new b(e);let r=await n.json();if(r.expiry!==null&&Date.now()>r.expiry)throw await t.delete(x+e),new b(e);return r.value}catch(t){throw t instanceof b?t:new b(e)}}async set(e,t){if(this.available)try{let n=await caches.open(this.cacheName),r={value:t,expiry:this.defaultTTL?Date.now()+this.defaultTTL:null,timestamp:Date.now()};await n.put(x+e,new Response(JSON.stringify(r),{headers:{"Content-Type":"application/json"}}))}catch{}}async remove(e){if(this.available)try{await(await caches.open(this.cacheName)).delete(x+e)}catch{}}async clear(){if(this.available)try{let e=await caches.open(this.cacheName),t=await e.keys();await Promise.all(t.filter(n=>n.url.includes(x)).map(n=>e.delete(n)))}catch{}}async clearNamespace(e,t){if(!this.available)return;let n=`@${e}:${t}`,r=`${e}:${t}:`;try{let s=await caches.open(this.cacheName),a=await s.keys();await Promise.all(a.filter(i=>{let c=i.url,u=c.includes(x)?c.substring(c.indexOf(x)+x.length):"";return u===n||u.startsWith(r)}).map(i=>s.delete(i)))}catch{}}async getNamespace(e,t){let n=`@${e}:${t}`,r=await this.get(n);try{return JSON.parse(r)}catch{throw await this.remove(n),new b(n)}}async setNamespace(e,t,n){let r=`@${e}:${t}`;await this.set(r,JSON.stringify(n))}getConfig(){return this.config}isAvailable(){return this.available}async getEntries(){let e={};if(!this.available)return e;try{let n=await(await caches.open(this.cacheName)).keys();for(let r of n){let s=r.url;if(!s.includes(x))continue;let a=s.substring(s.indexOf(x)+x.length);try{let i=await this.get(a);e[a]=i}catch{}}}catch{}return e}async getCacheStats(){if(!this.available)return{size:0,cacheName:this.cacheName};try{return{size:(await(await caches.open(this.cacheName)).keys()).filter(r=>r.url.includes(x)).length,cacheName:this.cacheName}}catch{return{size:0,cacheName:this.cacheName}}}};function Ee(o){let e=o.dataset.apiKey||"",t=o.dataset.baseUrl||"https://api.lionrapid.com",n=o.dataset.defaultLocale||"en",r=o.dataset.namespace||"default",s=(o.dataset.languages||n).split(",").map(f=>f.trim()).filter(Boolean),a=(o.dataset.exclude||"").split(",").map(f=>f.trim()).filter(Boolean),i=o.dataset.autoDetect==="true",c=o.dataset.mode==="dynamic-only"?"dynamic-only":"full",u=o.dataset.switcher&&o.dataset.switcher!=="false"?o.dataset.switcher:void 0,p=o.dataset.switcherPosition||void 0,g=o.dataset.switcherShowFlags!=="false",m=o.dataset.switcherShowNames==="true",h=o.dataset.switcherCustomCss||void 0;return{apiKey:e,baseUrl:t,defaultLocale:n,namespace:r,languages:s,excludeSelectors:a,autoDetect:i,mode:c,switcherStyle:u,switcherPosition:p,switcherShowFlags:g,switcherShowNames:m,switcherCustomCss:h}}function lt(o){if(typeof document>"u")return null;let e=document.cookie.match(/lionrapid_locale=([a-z]{2})/);return e&&o.includes(e[1])?e[1]:null}function ct(o,e){if(typeof navigator>"u")return e;let n=(navigator.language||navigator.userLanguage||"").split("-")[0].toLowerCase();return o.includes(n)?n:e}function dt(o,e){let t=window.location.pathname.replace(/^\/([a-z]{2})(\/|$)/,"/"),n=o===e?"":"/"+o;window.location.href=n+(t||"/")+window.location.search}async function Te(){let o=document.querySelectorAll("script[data-api-key]"),e=o[o.length-1];if(!e){console.warn("[LionRapid] No script tag with data-api-key found");return}let t=Ee(e);if(window.__lionrapidConfig=t,!t.apiKey){console.warn("[LionRapid] Missing data-api-key attribute");return}let n=t.defaultLocale;if(t.mode==="dynamic-only")n=document.documentElement.lang?.split("-")[0]?.toLowerCase()||t.defaultLocale;else{let i=lt(t.languages);i?n=i:t.autoDetect&&(n=ct(t.languages,t.defaultLocale))}let r=t.apiKey.startsWith("pk_")?"report-only":"sync",s=new G;s.setLanguages(t.languages),s.setInitialLocale(n);let a=()=>{if(t.mode!=="dynamic-only"&&t.switcherStyle&&!document.querySelector("[data-lionrapid-switcher]")){let i=document.createElement("div");i.dataset.lionrapidSwitcher=t.switcherStyle,t.switcherPosition&&(i.dataset.lionrapidSwitcherPosition=t.switcherPosition),t.switcherShowFlags||(i.dataset.lionrapidSwitcherShowFlags="false"),t.switcherShowNames||(i.dataset.lionrapidSwitcherShowNames="false"),t.switcherCustomCss&&(i.dataset.lionrapidSwitcherCustomCss=t.switcherCustomCss),document.body.appendChild(i)}s.initAll()};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",a):a();try{let i=await U.init({defaultLocale:n,namespace:t.namespace}).use(new B({enabled:!0})).use(new Q({enabled:!0})).use(new Y({enabled:!0})).use(new j({enabled:!0,options:{baseUrl:t.baseUrl,apiKey:t.apiKey,syncMissing:{enabled:r==="sync",debounceMs:500,batchSize:50},preloadNamespaces:[{locale:n,namespace:t.namespace,eager:!0}]}})).build(),c=new W({excludeSelectors:t.excludeSelectors});c.setCore(i),c.init({namespace:t.namespace,locale:n,sourceLocale:t.defaultLocale}),s.setCore(i),s.setOnLanguageChange(async y=>{if(document.cookie=`lionrapid_locale=${y}; path=/; max-age=31536000; SameSite=Lax`,t.mode==="dynamic-only"){dt(y,t.defaultLocale);return}await i.changeLanguage(y,{preloadNamespaces:[t.namespace]}),c.updateLocale(y),c.retranslate()});let u=[2e3,8e3,3e4],p=6e4,g=!1,m=[],h=Date.now(),f=async()=>{await i.reloadNamespace(t.namespace),c.translatePage(),h=Date.now()},k=()=>{m.forEach(y=>clearTimeout(y)),m=[]};i.bus.on("sync:batch:complete",()=>{g=!0,k(),u.forEach(y=>{m.push(setTimeout(()=>f().catch(()=>{}),y))})}),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&(g?(g=!1,k(),f().catch(()=>{})):Date.now()-h>p&&f().catch(()=>{}))});let S={t:(y,X,he)=>i.t(y,X||{},he),tHtml:(y,X,he)=>i.tHtml(y,X||{},he),changeLanguage:async y=>{await i.changeLanguage(y,{preloadNamespaces:[t.namespace]}),c.updateLocale(y),c.retranslate(),s.initAll()},getCurrentLocale:()=>i.getCurrentLocale(),on:(y,X)=>i.bus.on(y,X),retranslate:()=>c.retranslate(),reloadTranslations:f,autoTranslator:c,languageSwitcher:s};window.LionRapid=S;let M=new URLSearchParams(window.location.search).get("__lr_editor");if(M&&!document.querySelector("script[data-grant]")){let y=document.createElement("script");y.src=t.editorCdnUrl||"https://cdn.lionrapid.com/lionrapid.editor.min.js",y.dataset.grant=M,y.dataset.locale=i.getCurrentLocale(),y.dataset.api=t.baseUrl,y.async=!0,document.body.appendChild(y)}t.mode!=="dynamic-only"&&c.translatePage(),c.observe()}catch(i){console.error("[LionRapid] Initialization failed:",i)}}Te();return ze(ut);})();
79
+ `,G=class{constructor(){d(this,"core",null);d(this,"languages",[]);d(this,"initialLocale","en");d(this,"onLanguageChange",null);d(this,"stylesInjected",!1)}setCore(e){this.core=e}setInitialLocale(e){this.initialLocale=e}setLanguages(e){this.languages=e.map(t=>typeof t=="string"?Oe[t]||{code:t,name:t}:t)}setOnLanguageChange(e){this.onLanguageChange=e}initAll(){this.injectStyles(),document.querySelectorAll("[data-lionrapid-switcher]").forEach(t=>this.initSwitcher(t))}initSwitcher(e){let t=e.dataset.lionrapidSwitcher||"floating",n=this.core?.getCurrentLocale()||this.initialLocale;e.innerHTML="",e.classList.add("lionrapid-switcher"),e.setAttribute("data-no-translate",""),e.setAttribute("translate","no");let r=e.dataset.lionrapidSwitcherPosition||"top-right",s=e.dataset.lionrapidSwitcherShowFlags!=="false",a=e.dataset.lionrapidSwitcherShowNames!=="false",i=e.dataset.lionrapidSwitcherCustomCss||null;if(e.dataset.position=r,i){let c=document.createElement("style");c.textContent=i,document.head.appendChild(c)}switch(t){case"flags":this.renderButtonRow(e,n,!0,!0);break;case"buttons":this.renderButtonRow(e,n,s,a);break;case"floating":default:this.renderFloating(e,n,r,s,a);break}}renderFloating(e,t,n,r,s){let a={};n.startsWith("bottom")?a.bottom="100%":a.top="100%",n.endsWith("left")?a.left="0":a.right="0";let i=g=>{let h=r&&g.flag||"",f=s?g.name:g.code.toUpperCase();return`${h}${h&&f?" ":""}${f}`},c=this.languages.find(g=>g.code===t)||this.languages[0],u=c?i(c):t,p=document.createElement("button");p.type="button",p.className="lionrapid-floating-btn",p.setAttribute("aria-expanded","false"),p.setAttribute("aria-haspopup","true"),p.textContent=`${u} \u25BE`;let m=document.createElement("div");m.className="lionrapid-floating-menu",Object.assign(m.style,a);for(let g of this.languages){let h=document.createElement("button");h.type="button",h.dataset.lang=g.code,h.textContent=i(g),g.code===t&&h.classList.add("active"),h.addEventListener("click",()=>{this.handleLanguageChange(g.code),p.textContent=i(g)+" \u25BE",m.querySelectorAll("button").forEach(f=>{f.classList.toggle("active",f.dataset.lang===g.code)}),m.classList.remove("open"),p.setAttribute("aria-expanded","false")}),m.appendChild(h)}p.addEventListener("click",g=>{g.stopPropagation();let h=m.classList.contains("open");m.classList.toggle("open",!h),p.setAttribute("aria-expanded",String(!h))}),document.addEventListener("click",()=>{m.classList.remove("open"),p.setAttribute("aria-expanded","false")}),e.appendChild(p),e.appendChild(m)}renderButtonRow(e,t,n,r){let s=document.createElement("div");s.className="lionrapid-btn-row";for(let a of this.languages){let i=document.createElement("button");i.type="button",i.dataset.lang=a.code;let c=n&&a.flag||"",u=r?a.name:a.code.toUpperCase();i.textContent=`${c}${c&&u?" ":""}${u}`,a.code===t&&i.classList.add("active"),i.addEventListener("click",()=>{this.handleLanguageChange(a.code),s.querySelectorAll("button").forEach(p=>{p.classList.toggle("active",p.dataset.lang===a.code)})}),s.appendChild(i)}e.appendChild(s)}handleLanguageChange(e){this.onLanguageChange&&this.onLanguageChange(e),document.querySelectorAll(".lionrapid-btn-row button").forEach(t=>{let n=t;n.classList.toggle("active",n.dataset.lang===e)})}injectStyles(){if(this.stylesInjected)return;let e=document.createElement("style");e.textContent=ot,document.head.appendChild(e),this.stylesInjected=!0}static getLanguage(e){return Oe[e]}};var Ce="lionrapid:",W=`${Ce}version`,De="1",J=class{constructor(e={}){d(this,"name","LocalStorageRepository");d(this,"type","memory");d(this,"config");d(this,"available");d(this,"prefix");d(this,"defaultTTL");d(this,"maxSize");this.config={enabled:e.enabled??!0,priority:e.priority??0,options:{prefix:e.options?.prefix??Ce,ttl:e.options?.ttl??1440*60*1e3,maxSize:e.options?.maxSize??500,...e.options}},this.prefix=this.config.options?.prefix??Ce,this.defaultTTL=this.config.options?.ttl??1440*60*1e3,this.maxSize=this.config.options?.maxSize??500,this.available=this.checkAvailability(),this.available&&this.migrateIfNeeded()}checkAvailability(){if(typeof window>"u")return!1;try{let e=`${this.prefix}__test__`;return window.localStorage.setItem(e,"test"),window.localStorage.removeItem(e),!0}catch{return!1}}migrateIfNeeded(){try{window.localStorage.getItem(W)!==De&&(this.clear(),window.localStorage.setItem(W,De))}catch{}}get(e){if(!this.available)return null;try{let t=this.prefix+e,n=window.localStorage.getItem(t);if(!n)return null;let r=JSON.parse(n);return r.expiry!==null&&Date.now()>r.expiry?(window.localStorage.removeItem(t),null):r.value}catch{return null}}set(e,t){if(!this.available)return;let n=this.prefix+e,r={value:t,expiry:this.defaultTTL?Date.now()+this.defaultTTL:null,timestamp:Date.now()};try{this.getEntryCount()>=this.maxSize&&this.evictOldest(),window.localStorage.setItem(n,JSON.stringify(r))}catch(s){if(this.isQuotaError(s)){this.evictOldest();try{window.localStorage.setItem(n,JSON.stringify(r))}catch{}}}}remove(e){if(this.available)try{window.localStorage.removeItem(this.prefix+e)}catch{}}clear(){if(this.available)try{let e=[];for(let t=0;t<window.localStorage.length;t++){let n=window.localStorage.key(t);n?.startsWith(this.prefix)&&n!==W&&e.push(n)}e.forEach(t=>window.localStorage.removeItem(t))}catch{}}clearNamespace(e,t){if(!this.available)return;let n=`@${e}:${t}`,r=`${e}:${t}:`;try{let s=[];for(let a=0;a<window.localStorage.length;a++){let i=window.localStorage.key(a);if(!i?.startsWith(this.prefix))continue;let c=i.slice(this.prefix.length);(c===n||c.startsWith(r))&&s.push(i)}s.forEach(a=>window.localStorage.removeItem(a))}catch{}}getNamespace(e,t){let n=`@${e}:${t}`,r=this.get(n);if(!r)return null;try{return JSON.parse(r)}catch{return this.remove(n),null}}setNamespace(e,t,n){let r=`@${e}:${t}`;this.set(r,JSON.stringify(n))}getEntries(){let e={};if(!this.available)return e;try{for(let t=0;t<window.localStorage.length;t++){let n=window.localStorage.key(t);if(!n?.startsWith(this.prefix)||n===W)continue;let r=n.slice(this.prefix.length),s=this.get(r);s!==null&&(e[r]=s)}}catch{}return e}getConfig(){return this.config}isAvailable(){return this.available}getEntryCount(){if(!this.available)return 0;let e=0;try{for(let t=0;t<window.localStorage.length;t++){let n=window.localStorage.key(t);n?.startsWith(this.prefix)&&n!==W&&e++}}catch{}return e}isQuotaError(e){return e instanceof DOMException?e.name==="QuotaExceededError"||e.name==="NS_ERROR_DOM_QUOTA_REACHED":!1}evictOldest(){if(this.available)try{let e=[];for(let n=0;n<window.localStorage.length;n++){let r=window.localStorage.key(n);if(!(!r?.startsWith(this.prefix)||r===W))try{let s=window.localStorage.getItem(r);if(s){let a=JSON.parse(s);e.push({key:r,timestamp:a.timestamp})}}catch{window.localStorage.removeItem(r)}}e.sort((n,r)=>n.timestamp-r.timestamp);let t=Math.max(1,Math.floor(e.length*.25));for(let n=0;n<t&&n<e.length;n++)window.localStorage.removeItem(e[n].key)}catch{}}getCacheStats(){let e=this.getEntryCount(),t=this.maxSize>0?`${Math.round(e/this.maxSize*100)}%`:"0%";return{size:e,maxSize:this.maxSize,usage:t}}};var Me="lionrapid-v1",k="lionrapid:",Q=class{constructor(e={}){d(this,"name","CacheStorageRepository");d(this,"type","storage");d(this,"config");d(this,"cacheName");d(this,"defaultTTL");d(this,"available");this.config={enabled:e.enabled??!0,priority:e.priority??0,options:{cacheName:e.options?.cacheName??Me,ttl:e.options?.ttl??10080*60*1e3,...e.options}},this.cacheName=this.config.options?.cacheName??Me,this.defaultTTL=this.config.options?.ttl??10080*60*1e3,this.available=this.checkAvailability()}checkAvailability(){return typeof caches<"u"}async get(e){if(!this.available)throw new b(e);try{let t=await caches.open(this.cacheName),n=await t.match(k+e);if(!n)throw new b(e);let r=await n.json();if(r.expiry!==null&&Date.now()>r.expiry)throw await t.delete(k+e),new b(e);return r.value}catch(t){throw t instanceof b?t:new b(e)}}async set(e,t){if(this.available)try{let n=await caches.open(this.cacheName),r={value:t,expiry:this.defaultTTL?Date.now()+this.defaultTTL:null,timestamp:Date.now()};await n.put(k+e,new Response(JSON.stringify(r),{headers:{"Content-Type":"application/json"}}))}catch{}}async remove(e){if(this.available)try{await(await caches.open(this.cacheName)).delete(k+e)}catch{}}async clear(){if(this.available)try{let e=await caches.open(this.cacheName),t=await e.keys();await Promise.all(t.filter(n=>n.url.includes(k)).map(n=>e.delete(n)))}catch{}}async clearNamespace(e,t){if(!this.available)return;let n=`@${e}:${t}`,r=`${e}:${t}:`;try{let s=await caches.open(this.cacheName),a=await s.keys();await Promise.all(a.filter(i=>{let c=i.url,u=c.includes(k)?c.substring(c.indexOf(k)+k.length):"";return u===n||u.startsWith(r)}).map(i=>s.delete(i)))}catch{}}async getNamespace(e,t){let n=`@${e}:${t}`,r=await this.get(n);try{return JSON.parse(r)}catch{throw await this.remove(n),new b(n)}}async setNamespace(e,t,n){let r=`@${e}:${t}`;await this.set(r,JSON.stringify(n))}getConfig(){return this.config}isAvailable(){return this.available}async getEntries(){let e={};if(!this.available)return e;try{let n=await(await caches.open(this.cacheName)).keys();for(let r of n){let s=r.url;if(!s.includes(k))continue;let a=s.substring(s.indexOf(k)+k.length);try{let i=await this.get(a);e[a]=i}catch{}}}catch{}return e}async getCacheStats(){if(!this.available)return{size:0,cacheName:this.cacheName};try{return{size:(await(await caches.open(this.cacheName)).keys()).filter(r=>r.url.includes(k)).length,cacheName:this.cacheName}}catch{return{size:0,cacheName:this.cacheName}}}};function Ee(o){let e=o.dataset.apiKey||"",t=o.dataset.baseUrl||"https://api.lionrapid.com",n=o.dataset.defaultLocale||"en",r=o.dataset.namespace||"default",s=(o.dataset.languages||n).split(",").map(f=>f.trim()).filter(Boolean),a=(o.dataset.exclude||"").split(",").map(f=>f.trim()).filter(Boolean),i=o.dataset.autoDetect==="true",c=o.dataset.mode==="dynamic-only"?"dynamic-only":"full",u=o.dataset.switcher&&o.dataset.switcher!=="false"?o.dataset.switcher:void 0,p=o.dataset.switcherPosition||void 0,m=o.dataset.switcherShowFlags!=="false",g=o.dataset.switcherShowNames==="true",h=o.dataset.switcherCustomCss||void 0;return{apiKey:e,baseUrl:t,defaultLocale:n,namespace:r,languages:s,excludeSelectors:a,autoDetect:i,mode:c,switcherStyle:u,switcherPosition:p,switcherShowFlags:m,switcherShowNames:g,switcherCustomCss:h}}function lt(o){if(typeof document>"u")return null;let e=document.cookie.match(/lionrapid_locale=([a-z]{2})/);return e&&o.includes(e[1])?e[1]:null}function ct(o,e){if(typeof navigator>"u")return e;let n=(navigator.language||navigator.userLanguage||"").split("-")[0].toLowerCase();return o.includes(n)?n:e}function dt(o,e){let t=window.location.pathname.replace(/^\/([a-z]{2})(\/|$)/,"/"),n=o===e?"":"/"+o;window.location.href=n+(t||"/")+window.location.search}async function Re(){let o=document.querySelectorAll("script[data-api-key]"),e=o[o.length-1];if(!e){console.warn("[LionRapid] No script tag with data-api-key found");return}let t=Ee(e);if(window.__lionrapidConfig=t,!t.apiKey){console.warn("[LionRapid] Missing data-api-key attribute");return}let n=t.defaultLocale;if(t.mode==="dynamic-only")n=document.documentElement.lang?.split("-")[0]?.toLowerCase()||t.defaultLocale;else{let i=lt(t.languages);i?n=i:t.autoDetect&&(n=ct(t.languages,t.defaultLocale))}let r=t.apiKey.startsWith("pk_")?"report-only":"sync",s=new G;s.setLanguages(t.languages),s.setInitialLocale(n);let a=()=>{if(t.mode!=="dynamic-only"&&t.switcherStyle&&!document.querySelector("[data-lionrapid-switcher]")){let i=document.createElement("div");i.dataset.lionrapidSwitcher=t.switcherStyle,t.switcherPosition&&(i.dataset.lionrapidSwitcherPosition=t.switcherPosition),t.switcherShowFlags||(i.dataset.lionrapidSwitcherShowFlags="false"),t.switcherShowNames||(i.dataset.lionrapidSwitcherShowNames="false"),t.switcherCustomCss&&(i.dataset.lionrapidSwitcherCustomCss=t.switcherCustomCss),document.body.appendChild(i)}s.initAll()};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",a):a();try{let i=await U.init({defaultLocale:n,namespace:t.namespace}).use(new j({enabled:!0})).use(new J({enabled:!0})).use(new Q({enabled:!0})).use(new H({enabled:!0,options:{baseUrl:t.baseUrl,apiKey:t.apiKey,syncMissing:{enabled:r==="sync",debounceMs:500,batchSize:50},preloadNamespaces:[{locale:n,namespace:t.namespace,eager:!0}]}})).build(),c=new _({excludeSelectors:t.excludeSelectors});c.setCore(i),c.init({namespace:t.namespace,locale:n,sourceLocale:t.defaultLocale}),s.setCore(i),s.setOnLanguageChange(async y=>{if(document.cookie=`lionrapid_locale=${y}; path=/; max-age=31536000; SameSite=Lax`,t.mode==="dynamic-only"){dt(y,t.defaultLocale);return}await i.changeLanguage(y,{preloadNamespaces:[t.namespace]}),c.updateLocale(y),c.retranslate()});let u=[2e3,8e3,3e4],p=6e4,m=!1,g=[],h=Date.now(),f=async()=>{await i.reloadNamespace(t.namespace),c.translatePage(),h=Date.now()},S=()=>{g.forEach(y=>clearTimeout(y)),g=[]};i.bus.on("sync:batch:complete",()=>{m=!0,S(),u.forEach(y=>{g.push(setTimeout(()=>f().catch(()=>{}),y))})}),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&(m?(m=!1,S(),f().catch(()=>{})):Date.now()-h>p&&f().catch(()=>{}))});let I={t:(y,Y,he)=>i.t(y,Y||{},he),tHtml:(y,Y,he)=>i.tHtml(y,Y||{},he),changeLanguage:async y=>{await i.changeLanguage(y,{preloadNamespaces:[t.namespace]}),c.updateLocale(y),c.retranslate(),s.initAll()},getCurrentLocale:()=>i.getCurrentLocale(),on:(y,Y)=>i.bus.on(y,Y),retranslate:()=>c.retranslate(),reloadTranslations:f,autoTranslator:c,languageSwitcher:s};window.LionRapid=I;let Te=new URLSearchParams(window.location.search).get("__lr_editor");if(Te&&!document.querySelector("script[data-grant]")){let y=document.createElement("script");y.src=t.editorCdnUrl||"https://cdn.lionrapid.com/lionrapid.editor.min.js",y.dataset.grant=Te,y.dataset.locale=i.getCurrentLocale(),y.dataset.api=t.baseUrl,y.async=!0,document.body.appendChild(y)}t.mode!=="dynamic-only"&&c.translatePage(),c.observe()}catch(i){console.error("[LionRapid] Initialization failed:",i)}}Re();return Ve(ut);})();
80
80
  //# sourceMappingURL=lionrapid.auto.min.js.map