@lionrapid/core 0.6.4 → 0.6.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/README.md +15 -2
  2. package/dist/browser/auto-init.d.ts.map +1 -1
  3. package/dist/browser/auto-init.js +4 -2
  4. package/dist/browser/auto-init.js.map +1 -1
  5. package/dist/browser/editor/editor-api.d.ts +12 -0
  6. package/dist/browser/editor/editor-api.d.ts.map +1 -1
  7. package/dist/browser/editor/editor-api.js.map +1 -1
  8. package/dist/browser/editor/editor-init.js +2 -1
  9. package/dist/browser/editor/editor-init.js.map +1 -1
  10. package/dist/browser/editor/sidebar.d.ts.map +1 -1
  11. package/dist/browser/editor/sidebar.js +11 -1
  12. package/dist/browser/editor/sidebar.js.map +1 -1
  13. package/dist/browser/lionrapid.auto.dev.js +314 -179
  14. package/dist/browser/lionrapid.auto.dev.js.map +3 -3
  15. package/dist/browser/lionrapid.auto.js +314 -179
  16. package/dist/browser/lionrapid.auto.js.map +3 -3
  17. package/dist/browser/lionrapid.auto.min.js +6 -4
  18. package/dist/browser/lionrapid.auto.min.js.map +4 -4
  19. package/dist/browser/lionrapid.editor.js +5 -2
  20. package/dist/browser/lionrapid.editor.js.map +3 -3
  21. package/dist/browser/lionrapid.editor.min.js +4 -4
  22. package/dist/browser/lionrapid.editor.min.js.map +4 -4
  23. package/dist/browser/lionrapid.esm.js +318 -178
  24. package/dist/browser/lionrapid.esm.js.map +3 -3
  25. package/dist/browser/lionrapid.esm.min.js +5 -3
  26. package/dist/browser/lionrapid.esm.min.js.map +4 -4
  27. package/dist/browser/lionrapid.iife.dev.js +318 -178
  28. package/dist/browser/lionrapid.iife.dev.js.map +3 -3
  29. package/dist/browser/lionrapid.iife.js +318 -178
  30. package/dist/browser/lionrapid.iife.js.map +3 -3
  31. package/dist/browser/lionrapid.iife.min.js +5 -3
  32. package/dist/browser/lionrapid.iife.min.js.map +4 -4
  33. package/dist/browser/lionrapid.umd.js +318 -178
  34. package/dist/browser/lionrapid.umd.js.map +3 -3
  35. package/dist/browser/lionrapid.umd.min.js +5 -3
  36. package/dist/browser/lionrapid.umd.min.js.map +4 -4
  37. package/dist/browser/storage/cache-names.d.ts +51 -0
  38. package/dist/browser/storage/cache-names.d.ts.map +1 -0
  39. package/dist/browser/storage/cache-names.js +51 -0
  40. package/dist/browser/storage/cache-names.js.map +1 -0
  41. package/dist/browser/storage/cache-storage-repository.d.ts.map +1 -1
  42. package/dist/browser/storage/cache-storage-repository.js +6 -2
  43. package/dist/browser/storage/cache-storage-repository.js.map +1 -1
  44. package/dist/builder.d.ts.map +1 -1
  45. package/dist/builder.js +9 -2
  46. package/dist/builder.js.map +1 -1
  47. package/dist/config/api.config.d.ts +35 -0
  48. package/dist/config/api.config.d.ts.map +1 -0
  49. package/dist/config/api.config.js +35 -0
  50. package/dist/config/api.config.js.map +1 -0
  51. package/dist/handlers/network-handler.d.ts +6 -0
  52. package/dist/handlers/network-handler.d.ts.map +1 -1
  53. package/dist/handlers/network-handler.js +9 -0
  54. package/dist/handlers/network-handler.js.map +1 -1
  55. package/dist/index.d.ts +4 -2
  56. package/dist/index.d.ts.map +1 -1
  57. package/dist/index.js +14 -5
  58. package/dist/index.js.map +1 -1
  59. package/dist/lionRapid.d.ts.map +1 -1
  60. package/dist/lionRapid.js +11 -2
  61. package/dist/lionRapid.js.map +1 -1
  62. package/dist/repositories/network-repository.d.ts.map +1 -1
  63. package/dist/repositories/network-repository.js +4 -3
  64. package/dist/repositories/network-repository.js.map +1 -1
  65. package/dist/utils/locale.d.ts +50 -7
  66. package/dist/utils/locale.d.ts.map +1 -1
  67. package/dist/utils/locale.js +83 -15
  68. package/dist/utils/locale.js.map +1 -1
  69. package/dist/utils/log-safe.d.ts +92 -0
  70. package/dist/utils/log-safe.d.ts.map +1 -0
  71. package/dist/utils/log-safe.js +168 -0
  72. package/dist/utils/log-safe.js.map +1 -0
  73. package/dist/utils/logger.d.ts.map +1 -1
  74. package/dist/utils/logger.js +3 -2
  75. package/dist/utils/logger.js.map +1 -1
  76. package/package.json +7 -3
@@ -1,4 +1,6 @@
1
- "use strict";var LionRapid=(()=>{var oe=Object.defineProperty;var it=Object.getOwnPropertyDescriptor;var ot=Object.getOwnPropertyNames;var lt=Object.prototype.hasOwnProperty;var ct=(i,e,t)=>e in i?oe(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t;var ut=(i,e)=>{for(var t in e)oe(i,t,{get:e[t],enumerable:!0})},dt=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of ot(e))!lt.call(i,r)&&r!==t&&oe(i,r,{get:()=>e[r],enumerable:!(n=it(e,r))||n.enumerable});return i};var pt=i=>dt(oe({},"__esModule",{value:!0}),i);var u=(i,e,t)=>ct(i,typeof e!="symbol"?e+"":e,t);var zt={};ut(zt,{CacheManager:()=>_,CacheStorageRepository:()=>xe,Colors:()=>f,ContentValidator:()=>ie,EventEmitter:()=>W,ExcludeFilter:()=>Se,HTMLSerializer:()=>V,HandlerChain:()=>J,LOCALE_TAG_REGEX:()=>Be,LionRapidBuilder:()=>we,LionRapidCore:()=>Z,LocalStorageRepository:()=>Ee,LogLevel:()=>re,Logger:()=>je,MarkupParser:()=>z,MemoryRepository:()=>q,MissingTranslationQueue:()=>te,NetworkError:()=>N,NetworkRepository:()=>Re,SAFE_ATTRS:()=>ye,SAFE_STYLE_PROPS:()=>be,SAFE_TAGS:()=>me,ServerError:()=>A,StaticRepository:()=>ee,TranslationError:()=>P,TranslationLockedError:()=>x,TranslationNotFoundError:()=>g,VERSION:()=>Bt,VOID_TAGS:()=>j,createPackageLogger:()=>He,escapeHtml:()=>X,extractTagName:()=>M,generateAutoKey:()=>tt,isClientError:()=>We,isRetryableError:()=>he,isTranslationError:()=>Ge,localeDir:()=>ue,logger:()=>l,matchLocale:()=>ze,md5:()=>Ae,measure:()=>Me,normalizeLocale:()=>le,parseAcceptLanguage:()=>Ve,parseKeyPath:()=>$e,prepareTranslationRequest:()=>D,primarySubtag:()=>ce,readRawStyle:()=>B,replaceBlockInners:()=>Pe,resolveNestedKey:()=>L,sanitizeContentUnit:()=>Ie,sanitizeElement:()=>nt,sanitizeOpeningTag:()=>Y,sanitizeStyle:()=>ve,sanitizeStyleSheetText:()=>rt,sanitizeUrl:()=>Q,serializeOpeningTag:()=>H,splitBlocks:()=>Le});var re=(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))(re||{});var G=typeof process<"u"&&process.env?process.env:{},ae=G.NODE_ENV==="production",F=G.NODE_ENV==="development",Oe=G.CI==="true",gt=G.LIONRAPID_DEV==="true",ht=G.LIONRAPID_PERFORMANCE_TRACKING==="true";function ft(){try{if(typeof localStorage<"u"){let i=localStorage.getItem("LIONRAPID_LOG_LEVEL");if(i&&typeof i=="string")return i}}catch{}return null}var De=ft()||G.LOG_LEVEL||"WARN",f={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"},se=class i{constructor(e={}){u(this,"config");this.config={level:this.getLogLevelFromEnv(),enabled:this.shouldEnableLogging(),prefix:`${e.packageEmoji||"\u{1F4E6}"} ${e.packageName||"LionRapid"}`,showLineNumbers:gt&&!Oe,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(!ht||ae)return()=>{};let t=F?performance.now():0;return()=>{if(F){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=re[e],s=this.getLevelEmoji(e),a=this.config.showLineNumbers?this.getCallSite():null,o=this.buildColoredMessage(e,s,r,t,a,n);switch(e){case 3:console.error(o);break;case 2:console.warn(o);break;case 1:console.info(o);break;default:console.log(o)}}buildColoredMessage(e,t,n,r,s,a){if(!this.config.useColors){let y=s?` (${s.fileName}:${s.lineNumber})`:"",v=`${this.config.prefix} ${t} ${n} ${r}${y}`;return a!==void 0&&(v+=` ${JSON.stringify(a)}`),v}let o=this.getLevelColor(e),c=f.RESET,d=`${f.BOLD}${f.ORANGE}${this.config.prefix}${c}`,p=t,h=`${o}${f.BOLD}${n}${c}`,m=`${o}${r}${c}`,b=s?`${f.DIM}${f.BRIGHT_BLACK} (${s.fileName}:${s.lineNumber})${c}`:"",E=a!==void 0?`${f.DIM}${f.CYAN} ${JSON.stringify(a)}${c}`:"";return`${d} ${p} ${h} ${m}${b}${E}`}getLevelColor(e){switch(e){case 0:return f.BRIGHT_GREEN;case 1:return f.BRIGHT_CYAN;case 2:return f.BRIGHT_YELLOW;case 3:return f.BRIGHT_RED;default:return f.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?`${f[t]}${e}${f.RESET}`:e}getColors(){return f}createPackageLogger(e,t){return new i({...this.config,packageName:e,packageEmoji:t||"\u{1F4E6}"})}getLogLevelFromEnv(){switch(De.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 De!=="NONE"}shouldUseColors(){return Oe?!1:typeof window<"u"?!0:(typeof process<"u",F)}},k=()=>{},ke=()=>()=>{},l=ae?{configure:k,debug:k,info:k,warn:(i,e)=>{console.warn(`\u{1F981} LionRapid Core \u26A0\uFE0F ${i}`,e||"")},error:(i,e)=>{console.error(`\u{1F981} LionRapid Core \u274C ${i}`,e||"")},time:ke,colorize:i=>i,getColors:()=>f,createPackageLogger:(i,e)=>({configure:k,debug:k,info:k,warn:(t,n)=>{let r=`${e||"\u{1F4E6}"} ${i}`;console.warn(`${r} \u26A0\uFE0F ${t}`,n||"")},error:(t,n)=>{let r=`${e||"\u{1F4E6}"} ${i}`;console.error(`${r} \u274C ${t}`,n||"")},time:ke,colorize:t=>t,getColors:()=>f,createPackageLogger:k})}:new se({packageName:"LionRapid Core",packageEmoji:"\u{1F981}"}),je=ae?function(){return l}:se,He=i=>{if(ae){let e=`${i.packageEmoji||"\u{1F4E6}"} ${i.packageName||"LionRapid"}`;return{configure:k,debug:k,info:k,warn:(t,n)=>{console.warn(`${e} \u26A0\uFE0F ${t}`,n||"")},error:(t,n)=>{console.error(`${e} \u274C ${t}`,n||"")},time:ke,colorize:t=>t,getColors:()=>f,createPackageLogger:k}}return new se(i)},Me=i=>{if(ae)return{start:k,end:k,elapsed:()=>0};let e;return{start:()=>{F&&(e=performance.now(),l.debug(`\u23F1\uFE0F ${i} - started`))},end:()=>{if(F){let t=performance.now()-e;return l.debug(`\u23F1\uFE0F ${i} - completed in ${t.toFixed(2)}ms`),t}return 0},elapsed:()=>F?performance.now()-e:0}};var Be=/^[a-z]{2,3}(?:-[a-z0-9]{2,4})*$/i,mt=new Set(["ar","fa","he","ur","yi"]);function ce(i){return i.split("-")[0].toLowerCase()}function le(i){let e=i.trim();if(!e)return e;let[t,...n]=e.split("-"),r=[t.toLowerCase()];for(let s of n)s.length===4?r.push(s[0].toUpperCase()+s.slice(1).toLowerCase()):s.length===2?r.push(s.toUpperCase()):r.push(s.toLowerCase());return r.join("-")}function ze(i,e,t){if(e.length===0)return t;let n=e.map(r=>({raw:r,lower:le(r).toLowerCase()}));for(let r of i){if(!r)continue;let s=le(r).toLowerCase(),a=n.find(d=>d.lower===s);if(a)return a.raw;let o=ce(r),c=n.find(d=>d.lower===o);if(c)return c.raw}return t}function Ve(i){return i.split(",").map(e=>{let[t,...n]=e.trim().split(";"),r=n.find(a=>a.trim().startsWith("q=")),s=r?parseFloat(r.trim().slice(2)):1;return{tag:t.trim(),q:Number.isNaN(s)?0:s}}).filter(e=>e.tag.length>0&&e.tag!=="*").sort((e,t)=>t.q-e.q).map(e=>e.tag)}function ue(i){return mt.has(ce(i))?"rtl":"ltr"}var W=class{constructor(){u(this,"eventListeners",new Map);u(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,o)=>{this.emit("translation:missing",{context:this.createContext(e.id,[...n,"missing"]),payload:{key:e.cleanKey,fallbackValue:s,locale:a,namespace:o}})},notFound:(s,a,o)=>{this.emit("translation:not-found",{context:this.createContext(e.id,[...n,"not-found"]),payload:{key:e.cleanKey,fallbackValue:s,locale:a,namespace:o,status:404}})},locked:(s,a,o)=>{this.emit("translation:locked",{context:this.createContext(e.id,[...n,"locked"]),payload:{key:e.cleanKey,fallbackValue:s,locale:a,namespace:o,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,o)=>{this.emit("network:request:error",{context:this.createContext(r,[...s,"error"]),payload:{key:n,method:t||"GET",error:a,...o&&{status:o}}})},retry:(a,o,c)=>{this.emit("network:retry",{context:this.createContext(r,[...s,"retry"]),payload:{key:n,attempt:a,delayMs:o,...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,dir:ue(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 J=class{constructor(e){u(this,"asyncHandlers",[]);u(this,"syncHandlers",[]);u(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(o=>o.type==="storage");if(s.length===0)return;l.debug(`Saving to ${s.length} storage handlers`);let a=s.map(async o=>{try{await o.save(e,t),l.debug(`Saved to storage: ${o.name}`)}catch(c){l.warn(`Failed to save to storage ${o.name}:`,c),this.bus.repo(e,o.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 _e(i){let e=i.indexOf(":");if(e>0&&e<i.length-1){let t=i.substring(0,e),n=i.substring(e+1);return{originalKey:i,namespace:t,cleanKey:n,hasExplicitNamespace:!0}}return{originalKey:i,cleanKey:i,hasExplicitNamespace:!1}}function Fe(i,e,t){let n=i.hasExplicitNamespace?i.namespace:t;return{locale:e,namespace:n}}function L(i,e){if(!(!i||!e)){if(!e.includes(".")&&!e.includes("["))return i[e];try{let t=$e(e),n=i;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 $e(i){let e=[],t="",n=!1;for(let r=0;r<i.length;r++){let s=i[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 de(i,e,t){let n=[i];return e&&n.push(e),n.push(t),n.join(":")}function w(i,e){return`@${i}:${e}`}function O(i,e="",t,n){let r={};for(let[s,a]of Object.entries(i)){let o=e?`${e}.${s}`:s,c=de(t,n,o);typeof a=="object"&&a!==null&&"text"in a&&"styles"in a?r[c]=JSON.stringify(a):typeof a=="object"&&a!==null?Object.assign(r,O(a,o,t,n)):r[c]=JSON.stringify({text:String(a),styles:{}})}return r}function D(i,e,t,n,r){let s=performance.now(),{defaultValue:a,params:o}=yt(t,n),c=_e(i),d=Fe(c,e,r),p=de(d.locale,d.namespace,c.cleanKey),h=d.namespace?w(d.locale,d.namespace):void 0;return{id:`${p}-${s}`,originalKey:i,originalParams:t,originalDefaultValue:n,cleanKey:c.cleanKey,hasExplicitNamespace:c.hasExplicitNamespace,parsedParams:o,parsedDefaultValue:a,locale:e,namespace:d.namespace,individualCacheKey:p,namespaceCacheKey:h,startTime:s}}function yt(i,e){let t,n;return typeof i=="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 i=="string"?(t=i,typeof e=="object"&&(n=e)):typeof i=="object"&&(n=i,typeof e=="string"&&(t=e)),{defaultValue:t,params:n}}var pe=class{constructor(e,t){u(this,"name");u(this,"version","1.0.0");u(this,"priority");u(this,"type","memory");u(this,"enabled");u(this,"ttlMap",new Map);u(this,"ttl");u(this,"repository");u(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=O(e,"",t.locale,t.namespace);for(let[a,o]of Object.entries(s))this.setWithTTL(a,o);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=L(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 ge=class{constructor(e,t){u(this,"name");u(this,"version","1.0.0");u(this,"priority");u(this,"type","storage");u(this,"enabled");u(this,"ttlMap",new Map);u(this,"ttl");u(this,"repository");u(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=O(e,"",t.locale,t.namespace),o=0;for(let[c,d]of Object.entries(a))await this.setWithTTL(c,d),o++;l.debug(`Saved: ${o} 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=L(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 P=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)}},g=class extends P{constructor(e){super(e,404,`Translation not found: ${e}`)}},x=class extends P{constructor(t,n){super(t,423,`Translation locked: ${t}`);this.retryAfter=n}},A=class extends P{constructor(e,t){super(e,t,`Server error ${t}: ${e}`)}},N=class extends Error{constructor(t,n){super(t);this.cause=n;this.name="NetworkError",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}};function Ge(i){return i instanceof P}function he(i){return i instanceof A||i instanceof N}function We(i){return i instanceof g||i instanceof x}var fe=class{constructor(e,t){u(this,"repository");u(this,"name");u(this,"priority");u(this,"version","1.0.0");u(this,"type","network");u(this,"enabled");u(this,"bus");u(this,"retryCount");u(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 g&&e.namespace?(l.debug(`Individual key not found, trying namespace: ${e.cleanKey}`),this.lookupFromNamespace(e,n,t,r)):s instanceof x?(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 o=L(s.data,e.cleanKey);if(o!=null){let c,d={};if(typeof o=="object"&&o!==null&&"text"in o){let p=o;c=String(p.text),d=p.styles||{}}else c=String(o);return l.debug(`Network namespace hit: ${e.cleanKey}, hasStyles=${Object.keys(d).length>0}`),r.success(c),this.createTranslationResult(c,"network",200,n,void 0,!1,{locale:e.locale,namespace:e.namespace,data:s.data},d)}}let a=new g(e.cleanKey);return this.handleTranslationNotFound(e,t,a,n)}catch(s){return l.debug(`Namespace load failed: ${e.cleanKey}`,s),s instanceof g?this.handleTranslationNotFound(e,t,s,n):s instanceof x?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 x?(l.debug(`Namespace locked (423): ${e}:${t}`),this.createNamespaceResult(null,"fallback",423,n,r)):r instanceof g?(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&&he(a)){let o=this.calculateBackoff(r);return s.retry(r,o,a.message),await this.delay(o),l.debug(`Retrying ${n} (${r}/${this.retryCount}) after ${o}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,o,c){return{value:e,source:t,status:n,duration:Date.now()-r,...s&&{error:s},...a!==void 0&&{cached:a},...o&&{namespaceLoaded:o},...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 j=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]);function bt(i){return i.replace(/"/g,"&quot;")}function H(i,e){let n=`<${i.toLowerCase()}`;for(let[r,s]of Object.entries(e))n+=` ${r.toLowerCase()}="${bt(s)}"`;return n+=">",n}function M(i){let e=i.search(/[\s>]/);return i.slice(1,e===-1?i.length:e).toLowerCase()}function B(i){for(let e of i)if(e.startsWith("raw:"))return e.slice(4);return null}function Je(i){let e={amp:"&",lt:"<",gt:">",quot:'"',apos:"'",nbsp:" ",rsquo:"\u2019",lsquo:"\u2018",rdquo:"\u201D",ldquo:"\u201C",hellip:"\u2026",mdash:"\u2014",ndash:"\u2013",copy:"\xA9",reg:"\xAE",trade:"\u2122"};return i.replace(/&(#x[0-9a-f]+|#[0-9]+|[a-z][a-z0-9]*);/gi,(t,n)=>{if(n[0]==="#"){let r=n[1]==="x"||n[1]==="X"?parseInt(n.slice(2),16):parseInt(n.slice(1),10);if(Number.isFinite(r)&&r>0)try{return String.fromCodePoint(r)}catch{return t}return t}return e[n.toLowerCase()]??t})}var z=class{parse(e){if(/<\/?[0-9]+>/.test(e))return{text:Je(e),styles:{}};let t={},n=0,r=[],s="",a=0;for(;a<e.length;){let o=this.matchTag(e,a);if(!o){s+=e.slice(a);break}if(s+=e.slice(a,o.startIndex),o.isClosing){let c=null;for(let d=r.length-1;d>=0;d--)if(r[d].tag===o.tag.toLowerCase()){c=r[d].index,r.splice(d,1);break}c!==null&&(s+=`</${c}>`)}else{let c=o.tag.toLowerCase(),d=j.has(c),p=o.isSelfClosing||d;n++,t[String(n)]=[`raw:${H(c,o.attrs)}`],p?s+=`<${n}/>`:(s+=`<${n}>`,r.push({tag:c,index:n}))}a=o.endIndex}for(;r.length>0;){let o=r.pop();s+=`</${o.index}>`}return{text:Je(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[o,c,d,p,h]=a;return{tag:d,attrs:this.parseAttributes(p),isClosing:c==="/",isSelfClosing:h==="/",startIndex:n,endIndex:n+o.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,o,c]=r;t[s.toLowerCase()]=a??o??c??""}return t}};var me=new Set(["a","abbr","b","bdi","bdo","br","cite","code","del","dfn","em","i","img","ins","kbd","mark","q","s","samp","small","span","strong","sub","sup","time","u","var","wbr"]),ye=new Set(["alt","cite","class","datetime","dir","height","href","id","lang","loading","rel","role","src","target","title","width"]),vt=new Set(["href","src","cite"]),be=new Set(["color","background-color","font-family","font-size","font-style","font-weight","letter-spacing","line-height","text-decoration","text-decoration-color","text-decoration-line","text-decoration-style","text-transform","vertical-align","white-space","word-spacing"]),wt=/url\s*\(|expression\s*\(|image-set\s*\(|element\s*\(|paint\s*\(|javascript:|\\|[<>{}@]/i,Rt=new Set(["http","https","mailto","tel"]),Ct={amp:"&",lt:"<",gt:">",quot:'"',apos:"'",nbsp:"\xA0",colon:":",semi:";",sol:"/",bsol:"\\",Tab:" ",NewLine:`
3
- `};function Xe(i){return i.replace(/&(?:#[xX]([0-9a-fA-F]+);?|#(\d+);?|([a-zA-Z]+);)/g,(e,t,n,r)=>t?String.fromCodePoint(parseInt(t,16)):n?String.fromCodePoint(parseInt(n,10)):Ct[r]??e)}function X(i){return i.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function Q(i){let t=Xe(i).replace(/[\u0000-\u0020\u007f]/g,"").toLowerCase(),n=/^([a-z][a-z0-9+.-]*):/.exec(t);return n?Rt.has(n[1])?i:null:i}function ve(i){return Ye(i,!0)}function Qe(i){return Ye(i,!1)}function Ye(i,e){let t=Xe(i),n=[];for(let r of t.split(";")){let s=r.indexOf(":");if(s===-1)continue;let a=r.slice(0,s).trim().toLowerCase(),o=r.slice(s+1).trim();/^[a-z-]+$/.test(a)&&(e&&!be.has(a)||o===""||wt.test(o)||n.push(`${a}: ${o}`))}return n.length>0?n.join("; "):null}var Tt=/([^\s=/>"']+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]*)))?/g;function Y(i){if(!i.startsWith("<"))return null;let e=M(i);if(!/^[a-z][a-z0-9-]*$/.test(e)||!me.has(e))return null;let t=i.endsWith("/>")?i.length-2:i.endsWith(">")?i.length-1:i.length,n=i.slice(1+e.length,t),r={};for(let s of n.matchAll(Tt)){let a=s[1].toLowerCase(),o=s[2]??s[3]??s[4]??"";if(a in r)continue;if(a==="style"){let d=ve(o);d!==null&&(r[a]=d);continue}(ye.has(a)||/^data-[a-z0-9-]*$/.test(a)||/^aria-[a-z0-9-]*$/.test(a))&&(vt.has(a)&&Q(o)===null||(r[a]=o))}return H(e,r)}function Ie(i){let e=!1,t={};for(let[n,r]of Object.entries(i.styles)){let s=B(r);if(s===null){t[n]=r;continue}let a=Y(s);if(a===null){e=!0;let o=r.filter(c=>!c.startsWith("raw:"));o.length>0&&(t[n]=o)}else a===s?t[n]=r:(e=!0,t[n]=r.map(o=>o.startsWith("raw:")?`raw:${a}`:o))}return e?{text:i.text,styles:t}:i}var V=class{serialize(e){let{text:t,styles:n}=e,r=/<(\/?)?(\d+)(\/)?>/g,s="",a=0,o;for(;(o=r.exec(t))!==null;){s+=X(t.slice(a,o.index));let[c,d,p]=o,h=n[p]??[],m=B(h),b=m===null?null:Y(m);if(m&&b!==null){let E=M(m),y=j.has(E);d?y||(s+=`</${E}>`):s+=b}else s+=c;a=o.index+c.length}return s+=X(t.slice(a)),s}};var _=class{constructor(e,t,n,r){u(this,"handlerChain");u(this,"bus");u(this,"currentLocale");u(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(":"),o=a.join(":");if(!r||!s||!o)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,o=this.currentLocale(),c=0;if(r){let[d,p]=r.split(":");d&&p&&(this.handlerChain.clearNamespace(d,p),c=1)}else if(t&&n)this.handlerChain.clearNamespace(n,t),c=this.countClearedKeys(n,t);else if(t)this.handlerChain.clearNamespace(o,t),c=this.countClearedKeys(o,t);else if(n){let d=this.handlerChain.getEntries(),p=new Set;for(let h in d){let m=d[h];if(m&&typeof m=="object"){for(let b of Object.keys(m))if(b.startsWith(`${n}:`)||b.startsWith(`@${n}:`)){let E=b.replace("@","").split(":");E[1]&&p.add(E[1])}}}for(let h of p)this.handlerChain.clearNamespace(n,h),c++}else if(s){let d=this.handlerChain.getEntries(),p=new Map;for(let h in d){let m=d[h];if(m&&typeof m=="object"){for(let b of Object.keys(m))if(s(b)){let E=b.replace("@","").split(":"),y=E[0],v=E[1];y&&v&&(p.has(y)||p.set(y,new Set),p.get(y).add(v),c++)}}}for(let[h,m]of p)for(let b of m)this.handlerChain.clearNamespace(h,b)}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 o in n){let c=n[o];if(c&&typeof c=="object")for(let d of Object.keys(c))(d.startsWith(s)||d===a)&&r++}return r}async refetchAfterInvalidate(e){let{namespace:t,locale:n,key:r}=e,s=this.currentLocale();if(r){let[a,o]=r.split(":");a&&o&&await this.loadNamespaces(a,[o])}else t&&await this.loadNamespaces(n||s,[t])}};var St=/<\/?[0-9]+\/?>/,Et=/<[a-z][a-z0-9]*(?:\s+[^>]*)?\/?>/i,Z=class{constructor(e,t,n="en",r){u(this,"handlerChain");u(this,"currentLocale");u(this,"defaultNamespace");u(this,"pendingTranslations",new Map);u(this,"bus");u(this,"plugins",new Map);u(this,"formatters",new Map);u(this,"processors",new Map);u(this,"warnedNoInterpolate",!1);u(this,"eventPlugins",new Set);u(this,"markupParser",new z);u(this,"htmlSerializer",new V);u(this,"cache");this.bus=e,this.handlerChain=t,this.currentLocale=n,this.defaultNamespace=r,this.cache=new _(this.handlerChain,this.bus,()=>this.currentLocale,(s,a)=>this.loadNamespaces(s,a))}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=D(e,this.currentLocale,n,r,this.defaultNamespace);l.debug(`Translation requested: ${s.cleanKey}`);let a=this.bus.translation(s);a.request();let o=this.handlerChain.handleSync(s);if(o&&o.status===200){let p=this.processValue(o.value,s);return l.debug(`Translation found: ${s.cleanKey} from ${o.source} (${o.duration}ms)`),a.success(p),p}this.triggerBackgroundLoad(s);let c=s.parsedDefaultValue||s.cleanKey,d=this.processValue(c,s);return l.debug(`Translation fallback: ${s.cleanKey}`),a.fallback(d),d}tHtml(e,...t){let[n,r]=t,s=D(e,this.currentLocale,n,r,this.defaultNamespace);l.debug(`HTML translation requested: ${s.cleanKey}`);let a=this.bus.translation(s);a.request();let o=this.handlerChain.handleSync(s);if(o&&o.status===200){let p=this.processValueAsHtml(o.value,s,o.styles);return l.debug(`HTML translation found: ${s.cleanKey} from ${o.source}`),a.success(p),p}this.triggerBackgroundLoad(s);let c=s.parsedDefaultValue||s.cleanKey,d=this.processValueAsHtml(c,s);return l.debug(`HTML translation fallback: ${s.cleanKey}`),a.fallback(d),d}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 St.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=L(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,o;if(t&&"cleanKey"in t){let d=t;s=d.parsedParams,a=d.locale,o=d.cleanKey}else s=t,a=n||this.currentLocale,o=r;let c=e;try{if(c=this.applyStructuralFormatters(c,s,o),this.formatters.has("interpolate")?c=this.formatters.get("interpolate")(c,s,a,o):!this.warnedNoInterpolate&&s&&Object.keys(s).length>0&&c.includes("{")&&(this.warnedNoInterpolate=!0,console.warn("[LionRapid] Translation params were passed but no interpolate formatter is registered \u2014 {placeholders} render literally. Install @lionrapid/formatters and add .use(coreFormattersPlugin) to the builder.")),this.processors.size>0)for(let[d,p]of this.processors.entries())try{c=p(c,s,o)}catch(h){l.warn(`Processor ${d} failed:`,h)}return c}catch(d){return l.warn(`Translation processing failed for "${e}":`,d),e}}getContentUnit(e,t,n){let r=D(e,this.currentLocale,t,n,this.defaultNamespace),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 Et.test(e)}applyStructuralFormatters(e,t,n){let r=e,s=o=>typeof o?.count=="number",a=o=>typeof o?.context=="string";if(this.formatters.has("plural")&&s(t)){let o=this.formatters.get("plural");try{let c=o(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 o=this.formatters.get("context");try{let c=o(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=D(e,this.currentLocale,void 0,void 0,this.defaultNamespace);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 q=class{constructor(e){u(this,"name","MemoryRepository");u(this,"type","memory");u(this,"config",{});u(this,"cache",new Map);u(this,"accessOrder",new Map);u(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 ee=class{constructor(e,t={}){u(this,"name","StaticRepository");u(this,"type","memory");u(this,"config");u(this,"mem");this.config={enabled:t.enabled??!0,priority:t.priority??.5,options:{ttl:Number.MAX_SAFE_INTEGER,maxSize:Number.MAX_SAFE_INTEGER,...t.options}},this.mem=new q({options:{maxSize:Number.MAX_SAFE_INTEGER}});for(let[n,r]of Object.entries(e))for(let[s,a]of Object.entries(r)){this.mem.setNamespace(n,s,a);let o=O(a,"",n,s);for(let[c,d]of Object.entries(o))this.mem.set(c,d)}}get(e){return this.mem.get(e)}getNamespace(e,t){return this.mem.getNamespace(e,t)}getEntries(){return this.mem.getEntries()}getConfig(){return this.config}set(){}remove(){}clear(){}setNamespace(){}};var Ze=6e4,te=class{constructor(e,t,n){u(this,"queue",new Map);u(this,"debounceTimer",null);u(this,"repository");u(this,"config");u(this,"eventEmitter");u(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<Ze){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>=Ze&&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")}};function xt(i){return!(i instanceof g||i instanceof x)}var we=class i{constructor(e){u(this,"config");u(this,"plugins",[]);u(this,"syncStorageRepos",[]);u(this,"asyncStorageRepos",[]);u(this,"networkRepos",[]);u(this,"syncQueue",null);this.config={defaultLocale:e.defaultLocale||"en",namespace:e.namespace||"app"}}static init(e={}){return new i(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}useStaticBundle(e,t=.5){return this.use(new ee(e,{priority:t}))}async build(){let e=new W,t=e.builder();l.info("Builder started"),l.debug("Builder config",this.config),t.buildStart(this.config.defaultLocale,this.config.namespace);let n=new J(e);for(let o of this.syncStorageRepos){if(!o.getConfig().enabled)continue;let c=new pe(e,o);t.use("sync"),n.addSyncHandler(c)}for(let o of this.asyncStorageRepos){if(!o.getConfig().enabled)continue;let c=new ge(e,o);t.use("async"),n.addAsyncHandler(c)}let r=null;for(let o of this.networkRepos){if(!o.getConfig().enabled||!o.getConfig().options?.baseUrl)continue;let c=new fe(e,o);r||(r=c),t.use("network"),n.addAsyncHandler(c);let d=o.getConfig();d.options?.syncMissing?.enabled&&(this.syncQueue=new te(o,{enabled:d.options.syncMissing.enabled,debounceMs:d.options.syncMissing.debounceMs||500,batchSize:d.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",d.options.syncMissing))}l.debug("Handler chain constructed");let s=new Z(e,n,this.config.defaultLocale,this.config.namespace);for(let o of this.plugins)t.use("plugin"),await o.initialize({core:s,bus:e}),s.registerPlugin(o),l.info(`Plugin initialized: ${o.name}`),l.debug(`Plugin version: ${o.version}`,o.capabilities);let a=n.getChainInfo();return r&&await this.executePreloading(r,n),l.info("Builder completed"),t.buildDone(a.handlers.map(o=>o.name),this.plugins.map(o=>o.name)),s}async executePreloading(e,t){let n=e.getPreload().filter(o=>o.eager!==!1);if(!n||n.length===0)return;l.info(`Preloading ${n.length} namespaces`),l.debug("Preload targets",{namespaces:n.map(o=>`${o.locale}:${o.namespace}`)});let r=!1,s=(o,c)=>{!xt(c)||r||(r=!0,console.warn(`[LionRapid] Could not load translations for ${o} \u2014 the page stays untranslated until the server is reachable.`,c))},a=n.map(async o=>{let c=`${o.locale}:${o.namespace}`;try{let d=await e.loadNamespace(o.locale,o.namespace);if(d&&d.data&&d.status===200){let p={locale:o.locale,namespace:o.namespace};await t.saveNamespaceToHandlers(d.data,p),l.debug(`Preloaded: ${c}`);return}d?.error&&(s(c,d.error),l.warn(`Preload failed: ${c}`,d.error))}catch(d){s(c,d),l.warn(`Preload failed: ${c}`,d)}});await Promise.allSettled(a),l.info("Preloading completed")}};var Nt="X-LR-Surface",kt="snippet",I=class I{constructor(e={}){u(this,"name","NetworkRepository");u(this,"type","network");u(this,"config",{});u(this,"namespaceSnapshots",new Map);u(this,"inflightGets",new Map);u(this,"negativeCache",new Map);u(this,"authFailedStatus",null);u(this,"writesFailedStatus",null);u(this,"DEFAULT_ENDPOINTS",{getTranslation:"/api/integrations/translations/:key",getNamespace:"/api/integrations/translations/:locale/:namespace",getProjectConfig:"/api/integrations/project-config",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 N("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 g(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 N("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 g(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 N("API base URL is not set");try{return await this.fetchNamespaceRaw(e,t)}catch(n){this.handleCaughtError(n)}}async getProjectConfig(){if(!this.config?.options?.baseUrl)throw new N("API base URL is not set");let e=this.buildUrl("getProjectConfig",{});l.debug(`API GET ProjectConfig: ${e}`);try{let t=await this.makeRequest(e,"GET");if(t.status===404)return null;t.ok||this.handleHttpError(t,"project-config");let n=await t.json();return!n||typeof n.defaultLocale!="string"||!Array.isArray(n.languages)?(l.warn("project-config payload unusable \u2014 keeping local fallback"),null):{defaultLocale:n.defaultLocale,languages:n.languages.map(String)}}catch(t){this.handleCaughtError(t)}}async fetchNamespaceRaw(e,t,n=!0){let r=this.buildUrl("getNamespace",{locale:e,namespace:t});l.debug(`API GET Namespace: ${r}`);let s=`${e}:${t}`,a=n?this.getSnapshot(s):void 0,o={};a&&(o["If-None-Match"]=`W/"${a.version}"`);let c=await this.makeRequest(r,"GET",void 0,o);if(c.status===304)return a?(l.debug(`Namespace ${s}: 304 Not Modified (snapshot served)`),a.translations):(l.debug(`Namespace ${s}: unexpected 304 with no snapshot \u2014 refetching`),this.fetchNamespaceRaw(e,t,!1));c.ok||this.handleHttpError(c,s);let d=await c.json();if(l.debug("API response data:",d),!d.translations)throw new g(s);let p=d.meta?.version!=null?String(d.meta.version):null;return p&&this.setSnapshot(s,{version:p,translations:d.translations}),d.translations}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 N("API base URL is not set");try{return await this.fetchNamespaceRaw(e,t)}catch(n){this.handleCaughtError(n)}}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}getSnapshot(e){let t=this.namespaceSnapshots.get(e);if(t)return t;try{localStorage.removeItem(I.LEGACY_VERSION_PREFIX+e);let n=localStorage.getItem(I.SNAPSHOT_PREFIX+e);if(n){let r=JSON.parse(n);if(r&&typeof r.version=="string"&&r.version.length>0&&r.translations&&typeof r.translations=="object")return this.namespaceSnapshots.set(e,r),r;localStorage.removeItem(I.SNAPSHOT_PREFIX+e)}}catch{}}setSnapshot(e,t){this.namespaceSnapshots.set(e,t);try{localStorage.setItem(I.SNAPSHOT_PREFIX+e,JSON.stringify(t)),localStorage.removeItem(I.LEGACY_VERSION_PREFIX+e)}catch{}}handleHttpError(e,t){if(l.debug(`API response: ${e.status} ${e.statusText}`),e.status===404)throw new g(t);if(e.status===423){let n=e.headers.get("Retry-After");throw new x(t,n?parseInt(n,10)*1e3:void 0)}throw e.status>=500&&e.status<600?new A(t,e.status):new N(`HTTP ${e.status}: ${e.statusText}`)}handleCaughtError(e){throw e instanceof g||e instanceof x||e instanceof A||e instanceof N?e:new N("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,o]of Object.entries(t)){let c=new RegExp(`:${a}`,"g");s=s.replace(c,encodeURIComponent(o))}return`${n}${s}`}makeRequest(e,t,n,r){if(this.authFailedStatus!==null)return Promise.resolve(new Response(null,{status:this.authFailedStatus,statusText:`auth latched off after ${this.authFailedStatus}`}));if(t!=="GET")return this.writesFailedStatus!==null?Promise.resolve(new Response(null,{status:this.writesFailedStatus,statusText:`writes latched off after ${this.writesFailedStatus}`})):this.doFetch(e,t,n,r).then(d=>this.recordOutcome(e,t,d));let s=this.negativeCache.get(e);if(s){if(Date.now()<s.until){l.debug(`Negative-cache hit (${s.status}): ${e}`);let d=s.status===423?{"Retry-After":String(Math.ceil((s.until-Date.now())/1e3))}:void 0;return Promise.resolve(new Response(null,{status:s.status,statusText:"negative cache",headers:d}))}this.negativeCache.delete(e)}let a=`${e}|${r?.["If-None-Match"]??""}`,o=this.inflightGets.get(a);if(o)return o.then(d=>this.cloneResponse(d));let c=this.doFetch(e,t,n,r).then(d=>this.recordOutcome(e,t,d)).finally(()=>this.inflightGets.delete(a));return this.inflightGets.set(a,c),c.then(d=>this.cloneResponse(d))}recordOutcome(e,t,n){let r=n.status;if(r===401||r===403&&t==="GET")return this.authFailedStatus===null&&(this.authFailedStatus=r,console.warn(`[LionRapid] API key rejected (${r}) \u2014 network translations are disabled for this session. Fix the key and reload; retrying cannot heal an auth failure.`)),n;if((r===403||r===429)&&t!=="GET")return this.writesFailedStatus===null&&(this.writesFailedStatus=r,l.warn(`Write path disabled after ${r} (scope/quota) \u2014 running read-only`)),n;if(t==="GET"&&(r===404||r===423)){let s=r===423?Number(n.headers?.get?.("Retry-After")):NaN,a=Number.isFinite(s)&&s>0?s*1e3:this.config.options?.negativeCacheTtlMs??I.DEFAULT_NEGATIVE_TTL_MS;this.negativeCache.set(e,{status:r,until:Date.now()+a})}else t!=="GET"&&n.ok?this.negativeCache.clear():t==="GET"&&n.ok&&this.negativeCache.delete(e);return n}cloneResponse(e){return typeof e.clone=="function"?e.clone():e}async doFetch(e,t,n,r){let s=new AbortController,a=this.config.options?.timeout??1e4,o=setTimeout(()=>s.abort(),a);try{let c={"Content-Type":"application/json",[Nt]:kt,...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(o)}}};u(I,"SNAPSHOT_PREFIX","lionrapid:ns:"),u(I,"LEGACY_VERSION_PREFIX","lionrapid:v:"),u(I,"DEFAULT_NEGATIVE_TTL_MS",6e4);var Re=I;var ie=class{validate(e){let t=[],n=[];return this.validateTagBalance(e.text,t),this.validateStyleReferences(e.text,e.styles,t,n),this.validateICUBraces(e.text,t),{valid:t.length===0,errors:t,warnings:n}}validateTagBalance(e,t){let n=/<(\/?)?(\d+)(\/)?>/g,r=[],s;for(;(s=n.exec(e))!==null;){let[,a,o,c]=s;if(!c)if(a)if(r.length===0)t.push({code:"UNBALANCED_TAGS",message:`Closing tag </${o}> has no matching opening tag`,path:`text[${s.index}]`});else{let d=r[r.length-1];if(d.index===o)r.pop();else{let p=r.findIndex(h=>h.index===o);p>=0?(t.push({code:"UNBALANCED_TAGS",message:`Improperly nested: </${o}> should close before </${d.index}>`,path:`text[${s.index}]`}),r.splice(p,1)):t.push({code:"UNBALANCED_TAGS",message:`Closing tag </${o}> has no matching opening tag`,path:`text[${s.index}]`})}}else r.push({index:o,position:s.index})}for(let{index:a}of r)t.push({code:"UNBALANCED_TAGS",message:`Opening tag <${a}> has no matching closing tag`,path:"text"})}validateStyleReferences(e,t,n,r){let s=new Set,a=/<\/?(\d+)(?:\/)?>/g,o;for(;(o=a.exec(e))!==null;)s.add(o[1]);for(let c of s)(!t[c]||t[c].length===0)&&r.push({code:"EMPTY_STYLE",message:`Tag <${c}> has no style definition, will render as <span>`});for(let c of Object.keys(t))s.has(c)||r.push({code:"UNUSED_TAG",message:`Style for tag <${c}> is defined but tag is not used in text`})}validateICUBraces(e,t){let n=0,r=!1,s="";for(let o=0;o<e.length;o++){let c=e[o],d=o>0?e[o-1]:"";if((c==='"'||c==="'")&&d!=="\\"){r?c===s&&(r=!1,s=""):(r=!0,s=c);continue}r||(c==="{"?n++:c==="}"&&(n--,n<0&&(t.push({code:"INVALID_ICU",message:`Unbalanced ICU braces: unexpected '}' at position ${o}`,path:`text[${o}]`}),n=0)))}n>0&&t.push({code:"INVALID_ICU",message:`Unbalanced ICU braces: ${n} unclosed '{'`,path:"text"}),/\{\s*[,}]/.test(e)&&t.push({code:"INVALID_ICU",message:"ICU variable name is empty or missing",path:"text"})}};var et=new Set(["title","p","h1","h2","h3","h4","h5","h6","li","td","th","label","button","figcaption","dt","dd","summary","caption"]),$t=new Set(["a"]),It=new Set(["script","style","code","pre","textarea","noscript","svg"]),K=/<(\/?)([a-zA-Z][a-zA-Z0-9]*)((?:\s+[a-zA-Z][a-zA-Z0-9-]*(?:=(?:"[^"]*"|'[^']*'|[^\s>]*))?)*)\s*(\/?)>/g;function Lt(i){return i.includes("data-no-translate")?!0:/translate\s*=\s*["']no["']/.test(i)}function Pt(i){K.lastIndex=0;let e;for(;(e=K.exec(i))!==null;){let[,t,n,,r]=e;if(!t&&!r&&et.has(n.toLowerCase()))return!0}return!1}function qe(i,e,t){let n=t.toLowerCase(),r=1;K.lastIndex=e;let s;for(;(s=K.exec(i))!==null;){let[,a,o,,c]=s;if(o.toLowerCase()===n)if(a){if(r--,r===0)return s.index}else c||r++}return-1}function Le(i){let e=[],t=0,n=0,r=0,s=1e5,a=[];for(;t<i.length&&r<s;){r++;let o=i.indexOf("<",t);if(o===-1)break;if(i.startsWith("<!--",o)){let v=i.indexOf("-->",o+4);if(v===-1)break;t=v+3;continue}K.lastIndex=o;let c=K.exec(i);if(!c||c.index!==o){t=o+1;continue}let[d,p,h,m,b]=c,E=h.toLowerCase(),y=c.index+d.length;if(It.has(E)){p?n>0&&n--:b||n++,t=y;continue}if(n>0){t=y;continue}for(;a.length&&t>=a[a.length-1];)a.pop();if(!p&&!b&&Lt(m)){let v=qe(i,y,h);v!==-1&&a.push(v)}if(a.length>0){t=y;continue}if((et.has(E)||$t.has(E))&&!p&&!b){let v=qe(i,y,h);if(v===-1){t=y;continue}let Ue=i.slice(y,v);if(Pt(Ue)){t=y;continue}e.push({tag:E,openTag:d,attrs:m,inner:Ue,innerStart:y,innerEnd:v}),K.lastIndex=v;let Ne=K.exec(i);t=Ne?Ne.index+Ne[0].length:v+1;continue}t=y}return{blocks:e}}function Pe(i,e){let t=[...e].sort((r,s)=>s.block.innerStart-r.block.innerStart),n=i;for(let{block:r,inner:s}of t)n=n.slice(0,r.innerStart)+s+n.slice(r.innerEnd);return n}function U(i,e){let t=(i&65535)+(e&65535);return(i>>16)+(e>>16)+(t>>16)<<16|t&65535}function At(i,e){return i<<e|i>>>32-e}function Ce(i,e,t,n,r,s){return U(At(U(U(e,i),U(n,s)),r),t)}function R(i,e,t,n,r,s,a){return Ce(e&t|~e&n,i,e,r,s,a)}function C(i,e,t,n,r,s,a){return Ce(e&n|t&~n,i,e,r,s,a)}function T(i,e,t,n,r,s,a){return Ce(e^t^n,i,e,r,s,a)}function S(i,e,t,n,r,s,a){return Ce(t^(e|~n),i,e,r,s,a)}function Kt(i,e){i[e>>5]|=128<<e%32,i[(e+64>>>9<<4)+14]=e;let t=1732584193,n=-271733879,r=-1732584194,s=271733878;for(let a=0;a<i.length;a+=16){let o=t,c=n,d=r,p=s;t=R(t,n,r,s,i[a],7,-680876936),s=R(s,t,n,r,i[a+1],12,-389564586),r=R(r,s,t,n,i[a+2],17,606105819),n=R(n,r,s,t,i[a+3],22,-1044525330),t=R(t,n,r,s,i[a+4],7,-176418897),s=R(s,t,n,r,i[a+5],12,1200080426),r=R(r,s,t,n,i[a+6],17,-1473231341),n=R(n,r,s,t,i[a+7],22,-45705983),t=R(t,n,r,s,i[a+8],7,1770035416),s=R(s,t,n,r,i[a+9],12,-1958414417),r=R(r,s,t,n,i[a+10],17,-42063),n=R(n,r,s,t,i[a+11],22,-1990404162),t=R(t,n,r,s,i[a+12],7,1804603682),s=R(s,t,n,r,i[a+13],12,-40341101),r=R(r,s,t,n,i[a+14],17,-1502002290),n=R(n,r,s,t,i[a+15],22,1236535329),t=C(t,n,r,s,i[a+1],5,-165796510),s=C(s,t,n,r,i[a+6],9,-1069501632),r=C(r,s,t,n,i[a+11],14,643717713),n=C(n,r,s,t,i[a],20,-373897302),t=C(t,n,r,s,i[a+5],5,-701558691),s=C(s,t,n,r,i[a+10],9,38016083),r=C(r,s,t,n,i[a+15],14,-660478335),n=C(n,r,s,t,i[a+4],20,-405537848),t=C(t,n,r,s,i[a+9],5,568446438),s=C(s,t,n,r,i[a+14],9,-1019803690),r=C(r,s,t,n,i[a+3],14,-187363961),n=C(n,r,s,t,i[a+8],20,1163531501),t=C(t,n,r,s,i[a+13],5,-1444681467),s=C(s,t,n,r,i[a+2],9,-51403784),r=C(r,s,t,n,i[a+7],14,1735328473),n=C(n,r,s,t,i[a+12],20,-1926607734),t=T(t,n,r,s,i[a+5],4,-378558),s=T(s,t,n,r,i[a+8],11,-2022574463),r=T(r,s,t,n,i[a+11],16,1839030562),n=T(n,r,s,t,i[a+14],23,-35309556),t=T(t,n,r,s,i[a+1],4,-1530992060),s=T(s,t,n,r,i[a+4],11,1272893353),r=T(r,s,t,n,i[a+7],16,-155497632),n=T(n,r,s,t,i[a+10],23,-1094730640),t=T(t,n,r,s,i[a+13],4,681279174),s=T(s,t,n,r,i[a+0],11,-358537222),r=T(r,s,t,n,i[a+3],16,-722521979),n=T(n,r,s,t,i[a+6],23,76029189),t=T(t,n,r,s,i[a+9],4,-640364487),s=T(s,t,n,r,i[a+12],11,-421815835),r=T(r,s,t,n,i[a+15],16,530742520),n=T(n,r,s,t,i[a+2],23,-995338651),t=S(t,n,r,s,i[a],6,-198630844),s=S(s,t,n,r,i[a+7],10,1126891415),r=S(r,s,t,n,i[a+14],15,-1416354905),n=S(n,r,s,t,i[a+5],21,-57434055),t=S(t,n,r,s,i[a+12],6,1700485571),s=S(s,t,n,r,i[a+3],10,-1894986606),r=S(r,s,t,n,i[a+10],15,-1051523),n=S(n,r,s,t,i[a+1],21,-2054922799),t=S(t,n,r,s,i[a+8],6,1873313359),s=S(s,t,n,r,i[a+15],10,-30611744),r=S(r,s,t,n,i[a+6],15,-1560198380),n=S(n,r,s,t,i[a+13],21,1309151649),t=S(t,n,r,s,i[a+4],6,-145523070),s=S(s,t,n,r,i[a+11],10,-1120210379),r=S(r,s,t,n,i[a+2],15,718787259),n=S(n,r,s,t,i[a+9],21,-343485551),t=U(t,o),n=U(n,c),r=U(r,d),s=U(s,p)}return[t,n,r,s]}function Ut(i){let e="0123456789abcdef",t="";for(let n=0;n<i.length*4;n++)t+=e.charAt(i[n>>2]>>n%4*8+4&15)+e.charAt(i[n>>2]>>n%4*8&15);return t}function Ot(i){if(typeof TextEncoder<"u")return new TextEncoder().encode(i);let e=[];for(let t=0;t<i.length;t++){let n=i.charCodeAt(t);if(n<128)e.push(n);else if(n<2048)e.push(192|n>>6,128|n&63);else if(n>=55296&&n<56320&&t+1<i.length){let r=i.charCodeAt(++t),s=65536+(n-55296<<10)+(r-56320);e.push(240|s>>18,128|s>>12&63,128|s>>6&63,128|s&63)}else e.push(224|n>>12,128|n>>6&63,128|n&63)}return new Uint8Array(e)}function Dt(i){let e=[];for(let t=0;t<i.length;t++)e[t>>2]|=i[t]<<t%4*8;return e}function Ae(i){let e=Ot(i);return Ut(Kt(Dt(e),e.length*8))}function tt(i){let e=i.trim();return"auto_"+Ae(e).substring(0,12)}var jt={emails:!0,urls:!0,numbers:!0,phones:!0},Te={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,}$/},Se=class{constructor(e={},t=2){u(this,"patterns");u(this,"minTextLength");this.patterns={...jt,...e},this.minTextLength=t}shouldExclude(e){let t=e.trim();return!!(t.length<this.minTextLength||this.patterns.emails&&Te.email.test(t)||this.patterns.urls&&Te.url.test(t)||this.patterns.numbers&&Te.number.test(t)||this.patterns.phones&&Te.phone.test(t))}};var Ht=new Set(["script","iframe","frame","frameset","object","embed","applet","base","meta","link","template","portal"]),Mt=new Set(["href","src","action","formaction","poster","data","xlink:href"]);function nt(i){let e=[i,...Array.from(i.querySelectorAll("*"))];for(let t of e){let n=t.tagName.toLowerCase();if(Ht.has(n)){t.remove();continue}for(let r of t.getAttributeNames()){let s=r.toLowerCase();if(s.startsWith("on")||s==="srcdoc"){t.removeAttribute(r);continue}if(Mt.has(s)){Q(t.getAttribute(r)??"")===null&&t.removeAttribute(r);continue}if(s==="style"){let a=Qe(t.getAttribute(r)??"");a===null?t.removeAttribute(r):t.setAttribute(r,a)}}}}function rt(i,e){let t=i.replace(/@import[^;]*(;|$)/gi,"");return t=t.replace(/url\(\s*(['"]?)([^'")]*)\1\s*\)/gi,(n,r,s)=>{try{let a=new URL(s,e);if(a.protocol==="data:"||a.origin===new URL(e).origin)return n}catch{}return'url("")'}),t.replace(/expression\s*\(/gi,"blocked(")}var Ke="lionrapid:",ne=`${Ke}version`,st="1",Ee=class{constructor(e={}){u(this,"name","LocalStorageRepository");u(this,"type","memory");u(this,"config");u(this,"available");u(this,"prefix");u(this,"defaultTTL");u(this,"maxSize");this.config={enabled:e.enabled??!0,priority:e.priority??0,options:{prefix:e.options?.prefix??Ke,ttl:e.options?.ttl??1440*60*1e3,maxSize:e.options?.maxSize??500,...e.options}},this.prefix=this.config.options?.prefix??Ke,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(ne)!==st&&(this.clear(),window.localStorage.setItem(ne,st))}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!==ne&&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 o=window.localStorage.key(a);if(!o?.startsWith(this.prefix))continue;let c=o.slice(this.prefix.length);(c===n||c.startsWith(r))&&s.push(o)}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===ne)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!==ne&&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===ne))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 at="lionrapid-v1",$="https://cache.lionrapid.internal/",xe=class{constructor(e={}){u(this,"name","CacheStorageRepository");u(this,"type","storage");u(this,"config");u(this,"cacheName");u(this,"defaultTTL");u(this,"available");this.config={enabled:e.enabled??!0,priority:e.priority??0,options:{cacheName:e.options?.cacheName??at,ttl:e.options?.ttl??10080*60*1e3,...e.options}},this.cacheName=this.config.options?.cacheName??at,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 g(e);try{let t=await caches.open(this.cacheName),n=await t.match($+e);if(!n)throw new g(e);let r=await n.json();if(r.expiry!==null&&Date.now()>r.expiry)throw await t.delete($+e),new g(e);return r.value}catch(t){throw t instanceof g?t:new g(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($+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($+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($)).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(o=>{let c=o.url,d=c.includes($)?c.substring(c.indexOf($)+$.length):"";return d===n||d.startsWith(r)}).map(o=>s.delete(o)))}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 g(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($))continue;let a=s.substring(s.indexOf($)+$.length);try{let o=await this.get(a);e[a]=o}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($)).length,cacheName:this.cacheName}}catch{return{size:0,cacheName:this.cacheName}}}};var Bt="1.0.0";return pt(zt);})();
1
+ "use strict";var LionRapid=(()=>{var ce=Object.defineProperty;var bt=Object.getOwnPropertyDescriptor;var vt=Object.getOwnPropertyNames;var Rt=Object.prototype.hasOwnProperty;var wt=(a,e,t)=>e in a?ce(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t;var Ct=(a,e)=>{for(var t in e)ce(a,t,{get:e[t],enumerable:!0})},Et=(a,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of vt(e))!Rt.call(a,r)&&r!==t&&ce(a,r,{get:()=>e[r],enumerable:!(n=bt(e,r))||n.enumerable});return a};var Tt=a=>Et(ce({},"__esModule",{value:!0}),a);var u=(a,e,t)=>wt(a,typeof e!="symbol"?e+"":e,t);var on={};Ct(on,{CORE_CACHE_ENTRY_PREFIX:()=>$e,CORE_CACHE_NAMES:()=>ke,CacheManager:()=>V,CacheStorageRepository:()=>Ie,Colors:()=>h,ContentValidator:()=>le,DEFAULT_API_BASE_URL:()=>yt,EventEmitter:()=>J,ExcludeFilter:()=>xe,HTMLSerializer:()=>F,HandlerChain:()=>X,ISO639_2_TO_1:()=>De,LOCALE_TAG_REGEX:()=>qe,LionRapidBuilder:()=>Ee,LionRapidCore:()=>q,LocalStorageRepository:()=>Ne,LogLevel:()=>ae,Logger:()=>Qe,MarkupParser:()=>z,MemoryRepository:()=>ee,MissingTranslationQueue:()=>ne,NetworkError:()=>N,NetworkRepository:()=>Te,SAFE_ATTRS:()=>Re,SAFE_STYLE_PROPS:()=>we,SAFE_TAGS:()=>ve,ServerError:()=>O,StaticRepository:()=>te,TranslationError:()=>A,TranslationLockedError:()=>x,TranslationNotFoundError:()=>g,VERSION:()=>an,VOID_TAGS:()=>H,createPackageLogger:()=>Ye,escapeHtml:()=>Q,extractTagName:()=>M,generateAutoKey:()=>Ve,isClientError:()=>at,isRetryableError:()=>ye,isTranslationError:()=>st,localeCandidates:()=>je,localeDir:()=>ge,logger:()=>l,matchLocale:()=>et,md5:()=>se,measure:()=>Ze,normalizeLocale:()=>Ke,parseAcceptLanguage:()=>tt,parseKeyPath:()=>He,prepareTranslationRequest:()=>j,primarySubtag:()=>Ue,readRawStyle:()=>B,replaceBlockInners:()=>Be,resolveNestedKey:()=>L,sanitizeContentUnit:()=>_e,sanitizeElement:()=>gt,sanitizeOpeningTag:()=>Z,sanitizeStyle:()=>Ce,sanitizeStyleSheetText:()=>ft,sanitizeUrl:()=>Y,serializeOpeningTag:()=>_,splitBlocks:()=>Me});function P(a,e){let t=(a&65535)+(e&65535);return(a>>16)+(e>>16)+(t>>16)<<16|t&65535}function St(a,e){return a<<e|a>>>32-e}function ue(a,e,t,n,r,s){return P(St(P(P(e,a),P(n,s)),r),t)}function R(a,e,t,n,r,s,i){return ue(e&t|~e&n,a,e,r,s,i)}function w(a,e,t,n,r,s,i){return ue(e&n|t&~n,a,e,r,s,i)}function C(a,e,t,n,r,s,i){return ue(e^t^n,a,e,r,s,i)}function E(a,e,t,n,r,s,i){return ue(t^(e|~n),a,e,r,s,i)}function xt(a,e){a[e>>5]|=128<<e%32,a[(e+64>>>9<<4)+14]=e;let t=1732584193,n=-271733879,r=-1732584194,s=271733878;for(let i=0;i<a.length;i+=16){let o=t,c=n,d=r,p=s;t=R(t,n,r,s,a[i],7,-680876936),s=R(s,t,n,r,a[i+1],12,-389564586),r=R(r,s,t,n,a[i+2],17,606105819),n=R(n,r,s,t,a[i+3],22,-1044525330),t=R(t,n,r,s,a[i+4],7,-176418897),s=R(s,t,n,r,a[i+5],12,1200080426),r=R(r,s,t,n,a[i+6],17,-1473231341),n=R(n,r,s,t,a[i+7],22,-45705983),t=R(t,n,r,s,a[i+8],7,1770035416),s=R(s,t,n,r,a[i+9],12,-1958414417),r=R(r,s,t,n,a[i+10],17,-42063),n=R(n,r,s,t,a[i+11],22,-1990404162),t=R(t,n,r,s,a[i+12],7,1804603682),s=R(s,t,n,r,a[i+13],12,-40341101),r=R(r,s,t,n,a[i+14],17,-1502002290),n=R(n,r,s,t,a[i+15],22,1236535329),t=w(t,n,r,s,a[i+1],5,-165796510),s=w(s,t,n,r,a[i+6],9,-1069501632),r=w(r,s,t,n,a[i+11],14,643717713),n=w(n,r,s,t,a[i],20,-373897302),t=w(t,n,r,s,a[i+5],5,-701558691),s=w(s,t,n,r,a[i+10],9,38016083),r=w(r,s,t,n,a[i+15],14,-660478335),n=w(n,r,s,t,a[i+4],20,-405537848),t=w(t,n,r,s,a[i+9],5,568446438),s=w(s,t,n,r,a[i+14],9,-1019803690),r=w(r,s,t,n,a[i+3],14,-187363961),n=w(n,r,s,t,a[i+8],20,1163531501),t=w(t,n,r,s,a[i+13],5,-1444681467),s=w(s,t,n,r,a[i+2],9,-51403784),r=w(r,s,t,n,a[i+7],14,1735328473),n=w(n,r,s,t,a[i+12],20,-1926607734),t=C(t,n,r,s,a[i+5],4,-378558),s=C(s,t,n,r,a[i+8],11,-2022574463),r=C(r,s,t,n,a[i+11],16,1839030562),n=C(n,r,s,t,a[i+14],23,-35309556),t=C(t,n,r,s,a[i+1],4,-1530992060),s=C(s,t,n,r,a[i+4],11,1272893353),r=C(r,s,t,n,a[i+7],16,-155497632),n=C(n,r,s,t,a[i+10],23,-1094730640),t=C(t,n,r,s,a[i+13],4,681279174),s=C(s,t,n,r,a[i+0],11,-358537222),r=C(r,s,t,n,a[i+3],16,-722521979),n=C(n,r,s,t,a[i+6],23,76029189),t=C(t,n,r,s,a[i+9],4,-640364487),s=C(s,t,n,r,a[i+12],11,-421815835),r=C(r,s,t,n,a[i+15],16,530742520),n=C(n,r,s,t,a[i+2],23,-995338651),t=E(t,n,r,s,a[i],6,-198630844),s=E(s,t,n,r,a[i+7],10,1126891415),r=E(r,s,t,n,a[i+14],15,-1416354905),n=E(n,r,s,t,a[i+5],21,-57434055),t=E(t,n,r,s,a[i+12],6,1700485571),s=E(s,t,n,r,a[i+3],10,-1894986606),r=E(r,s,t,n,a[i+10],15,-1051523),n=E(n,r,s,t,a[i+1],21,-2054922799),t=E(t,n,r,s,a[i+8],6,1873313359),s=E(s,t,n,r,a[i+15],10,-30611744),r=E(r,s,t,n,a[i+6],15,-1560198380),n=E(n,r,s,t,a[i+13],21,1309151649),t=E(t,n,r,s,a[i+4],6,-145523070),s=E(s,t,n,r,a[i+11],10,-1120210379),r=E(r,s,t,n,a[i+2],15,718787259),n=E(n,r,s,t,a[i+9],21,-343485551),t=P(t,o),n=P(n,c),r=P(r,d),s=P(s,p)}return[t,n,r,s]}function Nt(a){let e="0123456789abcdef",t="";for(let n=0;n<a.length*4;n++)t+=e.charAt(a[n>>2]>>n%4*8+4&15)+e.charAt(a[n>>2]>>n%4*8&15);return t}function kt(a){if(typeof TextEncoder<"u")return new TextEncoder().encode(a);let e=[];for(let t=0;t<a.length;t++){let n=a.charCodeAt(t);if(n<128)e.push(n);else if(n<2048)e.push(192|n>>6,128|n&63);else if(n>=55296&&n<56320&&t+1<a.length){let r=a.charCodeAt(++t),s=65536+(n-55296<<10)+(r-56320);e.push(240|s>>18,128|s>>12&63,128|s>>6&63,128|s&63)}else e.push(224|n>>12,128|n>>6&63,128|n&63)}return new Uint8Array(e)}function $t(a){let e=[];for(let t=0;t<a.length;t++)e[t>>2]|=a[t]<<t%4*8;return e}function se(a){let e=kt(a);return Nt(xt($t(e),e.length*8))}function Ve(a){let e=a.trim();return"auto_"+se(e).substring(0,12)}var It=200,Ge=90;function Lt(a){return`${a.length} chars, md5:${se(a.trim()).slice(0,12)}`}function Pt(a){return a.length<=It?JSON.stringify(a):JSON.stringify(`${a.slice(0,Ge)}\u2026${a.slice(-Ge)}`)}var We=200,At=500,Ot=2,Ut=120;function de(a,e){return a.length<=e?a:`${a.slice(0,e)}\u2026 (${a.length} chars)`}function Pe(a){return JSON.stringify(a).slice(1,-1)}function pe(a){if(a instanceof Error){let e=a.name||"Error";return de(Pe(`${e}: ${a.message}`),We)}return de(Pe(String(a)),We)}function Ae(a){if(a instanceof Error){let t=String(a.message??"").split(`
2
+ `).length,n=(a.stack??"").split(`
3
+ `).slice(t).map(r=>r.trim()).filter(r=>r.startsWith("at ")).slice(0,Ot).map(r=>de(r,Ut));return[pe(a),...n].join(" | ")}let e;try{e=JSON.stringify(a)}catch{return"[unserializable]"}return de(e??Pe(String(a)),At)}function K(a){return`${Lt(a)}, ${Pt(a)}`}var ae=(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))(ae||{});var W=typeof process<"u"&&process.env?process.env:{},oe=W.NODE_ENV==="production",G=W.NODE_ENV==="development",Je=W.CI==="true",Kt=W.LIONRAPID_DEV==="true",Dt=W.LIONRAPID_PERFORMANCE_TRACKING==="true";function jt(){try{if(typeof localStorage<"u"){let a=localStorage.getItem("LIONRAPID_LOG_LEVEL");if(a&&typeof a=="string")return a}}catch{}return null}var Xe=jt()||W.LOG_LEVEL||"WARN",h={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"},ie=class a{constructor(e={}){u(this,"config");this.config={level:this.getLogLevelFromEnv(),enabled:this.shouldEnableLogging(),prefix:`${e.packageEmoji||"\u{1F4E6}"} ${e.packageName||"LionRapid"}`,showLineNumbers:Kt&&!Je,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(!Dt||oe)return()=>{};let t=G?performance.now():0;return()=>{if(G){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=ae[e],s=this.getLevelEmoji(e),i=this.config.showLineNumbers?this.getCallSite():null,o=this.buildColoredMessage(e,s,r,t,i,n);switch(e){case 3:console.error(o);break;case 2:console.warn(o);break;case 1:console.info(o);break;default:console.log(o)}}buildColoredMessage(e,t,n,r,s,i){if(!this.config.useColors){let y=s?` (${s.fileName}:${s.lineNumber})`:"",v=`${this.config.prefix} ${t} ${n} ${r}${y}`;return i!==void 0&&(v+=` ${Ae(i)}`),v}let o=this.getLevelColor(e),c=h.RESET,d=`${h.BOLD}${h.ORANGE}${this.config.prefix}${c}`,p=t,f=`${o}${h.BOLD}${n}${c}`,m=`${o}${r}${c}`,b=s?`${h.DIM}${h.BRIGHT_BLACK} (${s.fileName}:${s.lineNumber})${c}`:"",S=i!==void 0?`${h.DIM}${h.CYAN} ${Ae(i)}${c}`:"";return`${d} ${p} ${f} ${m}${b}${S}`}getLevelColor(e){switch(e){case 0:return h.BRIGHT_GREEN;case 1:return h.BRIGHT_CYAN;case 2:return h.BRIGHT_YELLOW;case 3:return h.BRIGHT_RED;default:return h.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(`
4
+ `);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?`${h[t]}${e}${h.RESET}`:e}getColors(){return h}createPackageLogger(e,t){return new a({...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 Je?!1:typeof window<"u"?!0:(typeof process<"u",G)}},k=()=>{},Oe=()=>()=>{},l=oe?{configure:k,debug:k,info:k,warn:(a,e)=>{console.warn(`\u{1F981} LionRapid Core \u26A0\uFE0F ${a}`,e||"")},error:(a,e)=>{console.error(`\u{1F981} LionRapid Core \u274C ${a}`,e||"")},time:Oe,colorize:a=>a,getColors:()=>h,createPackageLogger:(a,e)=>({configure:k,debug:k,info:k,warn:(t,n)=>{let r=`${e||"\u{1F4E6}"} ${a}`;console.warn(`${r} \u26A0\uFE0F ${t}`,n||"")},error:(t,n)=>{let r=`${e||"\u{1F4E6}"} ${a}`;console.error(`${r} \u274C ${t}`,n||"")},time:Oe,colorize:t=>t,getColors:()=>h,createPackageLogger:k})}:new ie({packageName:"LionRapid Core",packageEmoji:"\u{1F981}"}),Qe=oe?function(){return l}:ie,Ye=a=>{if(oe){let e=`${a.packageEmoji||"\u{1F4E6}"} ${a.packageName||"LionRapid"}`;return{configure:k,debug:k,info:k,warn:(t,n)=>{console.warn(`${e} \u26A0\uFE0F ${t}`,n||"")},error:(t,n)=>{console.error(`${e} \u274C ${t}`,n||"")},time:Oe,colorize:t=>t,getColors:()=>h,createPackageLogger:k}}return new ie(a)},Ze=a=>{if(oe)return{start:k,end:k,elapsed:()=>0};let e;return{start:()=>{G&&(e=performance.now(),l.debug(`\u23F1\uFE0F ${a} - started`))},end:()=>{if(G){let t=performance.now()-e;return l.debug(`\u23F1\uFE0F ${a} - completed in ${t.toFixed(2)}ms`),t}return 0},elapsed:()=>G?performance.now()-e:0}};var qe=/^[a-z]{2,3}(?:-[a-z0-9]{2,4})*$/i,Ht=new Set(["ar","fa","he","ur","yi"]);function Ue(a){return a.split("-")[0].toLowerCase()}function Ke(a){let e=a.trim();if(!e)return e;let[t,...n]=e.split("-"),r=[t.toLowerCase()];for(let s of n)s.length===4?r.push(s[0].toUpperCase()+s.slice(1).toLowerCase()):s.length===2?r.push(s.toUpperCase()):r.push(s.toLowerCase());return r.join("-")}var De=Object.freeze({ara:"ar",ben:"bn",bul:"bg",ces:"cs",cmn:"zh",dan:"da",deu:"de",ell:"el",eng:"en",est:"et",fas:"fa",fin:"fi",fra:"fr",heb:"he",hin:"hi",hrv:"hr",hun:"hu",ind:"id",isl:"is",ita:"it",jpn:"ja",kor:"ko",lav:"lv",lit:"lt",msa:"ms",nld:"nl",nor:"no",pol:"pl",por:"pt",ron:"ro",rus:"ru",slk:"sk",slv:"sl",spa:"es",srp:"sr",swe:"sv",tha:"th",tur:"tr",ukr:"uk",urd:"ur",vie:"vi",yid:"yi",zho:"zh"});function je(a){let e=a.trim().toLowerCase();if(!e)return[];let t=e.split("-"),n=[];for(;t.length>0;){let r=t.join("-");n.includes(r)||n.push(r);let s=De[r];s&&!n.includes(s)&&n.push(s),t.pop()}return n}function et(a,e,t){if(e.length===0)return t;let n=e.map(r=>({raw:r,lower:Ke(r).toLowerCase()}));for(let r of a)if(r)for(let s of je(r)){let i=n.find(o=>o.lower===s);if(i)return i.raw}return t}function tt(a){return a.split(",").map(e=>{let[t,...n]=e.trim().split(";"),r=n.find(i=>i.trim().startsWith("q=")),s=r?parseFloat(r.trim().slice(2)):1;return{tag:t.trim(),q:Number.isNaN(s)?0:s}}).filter(e=>e.tag.length>0&&e.tag!=="*").sort((e,t)=>t.q-e.q).map(e=>e.tag)}function ge(a){return Ht.has(Ue(a))?"rtl":"ltr"}var J=class{constructor(){u(this,"eventListeners",new Map);u(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,i,o)=>{this.emit("translation:missing",{context:this.createContext(e.id,[...n,"missing"]),payload:{key:e.cleanKey,fallbackValue:s,locale:i,namespace:o}})},notFound:(s,i,o)=>{this.emit("translation:not-found",{context:this.createContext(e.id,[...n,"not-found"]),payload:{key:e.cleanKey,fallbackValue:s,locale:i,namespace:o,status:404}})},locked:(s,i,o)=>{this.emit("translation:locked",{context:this.createContext(e.id,[...n,"locked"]),payload:{key:e.cleanKey,fallbackValue:s,locale:i,namespace:o,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,i=typeof e=="string"?e:e.cleanKey;this.emit("repo:set:success",{context:this.createContext(s,[...n,"set","success"]),payload:{key:i,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:i=>{this.emit("network:request:success",{context:this.createContext(r,[...s,"success"]),payload:{key:n,value:i,method:t||"GET"}})},error:(i,o)=>{this.emit("network:request:error",{context:this.createContext(r,[...s,"error"]),payload:{key:n,method:t||"GET",error:i,...o&&{status:o}}})},retry:(i,o,c)=>{this.emit("network:retry",{context:this.createContext(r,[...s,"retry"]),payload:{key:n,attempt:i,delayMs:o,...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,dir:ge(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 X=class{constructor(e){u(this,"asyncHandlers",[]);u(this,"syncHandlers",[]);u(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(i){l.warn(`Failed to save to memory ${s.name}:`,i),this.bus.repo(e,s.name).error(i)}}))}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(o=>o.type==="storage");if(s.length===0)return;l.debug(`Saving to ${s.length} storage handlers`);let i=s.map(async o=>{try{await o.save(e,t),l.debug(`Saved to storage: ${o.name}`)}catch(c){l.warn(`Failed to save to storage ${o.name}:`,c),this.bus.repo(e,o.name).error(c)}});await Promise.allSettled(i)}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(i){l.warn(`Failed to save namespace to storage ${s.name}:`,i),this.bus.repo(`${t.locale}:${t.namespace}`,s.name).error(i)}});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,i=r.priority||Number.MAX_SAFE_INTEGER;return s-i})}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 nt(a){let e=a.indexOf(":");if(e>0&&e<a.length-1){let t=a.substring(0,e),n=a.substring(e+1);return{originalKey:a,namespace:t,cleanKey:n,hasExplicitNamespace:!0}}return{originalKey:a,cleanKey:a,hasExplicitNamespace:!1}}function rt(a,e,t){let n=a.hasExplicitNamespace?a.namespace:t;return{locale:e,namespace:n}}function L(a,e){if(!(!a||!e)){if(!e.includes(".")&&!e.includes("["))return a[e];try{let t=He(e),n=a;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 He(a){let e=[],t="",n=!1;for(let r=0;r<a.length;r++){let s=a[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 i=parseInt(t,10);isNaN(i)?e.push(t):e.push(i),t=""}n=!1}else t+=s}return t&&e.push(t),e}function fe(a,e,t){let n=[a];return e&&n.push(e),n.push(t),n.join(":")}function T(a,e){return`@${a}:${e}`}function D(a,e="",t,n){let r={};for(let[s,i]of Object.entries(a)){let o=e?`${e}.${s}`:s,c=fe(t,n,o);typeof i=="object"&&i!==null&&"text"in i&&"styles"in i?r[c]=JSON.stringify(i):typeof i=="object"&&i!==null?Object.assign(r,D(i,o,t,n)):r[c]=JSON.stringify({text:String(i),styles:{}})}return r}function j(a,e,t,n,r){let s=performance.now(),{defaultValue:i,params:o}=_t(t,n),c=nt(a),d=rt(c,e,r),p=fe(d.locale,d.namespace,c.cleanKey),f=d.namespace?T(d.locale,d.namespace):void 0;return{id:`${p}-${s}`,originalKey:a,originalParams:t,originalDefaultValue:n,cleanKey:c.cleanKey,hasExplicitNamespace:c.hasExplicitNamespace,parsedParams:o,parsedDefaultValue:i,locale:e,namespace:d.namespace,individualCacheKey:p,namespaceCacheKey:f,startTime:s}}function _t(a,e){let t,n;return typeof a=="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 a=="string"?(t=a,typeof e=="object"&&(n=e)):typeof a=="object"&&(n=a,typeof e=="string"&&(t=e)),{defaultValue:t,params:n}}var he=class{constructor(e,t){u(this,"name");u(this,"version","1.0.0");u(this,"priority");u(this,"type","memory");u(this,"enabled");u(this,"ttlMap",new Map);u(this,"ttl");u(this,"repository");u(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=T(t.locale,t.namespace);this.setWithTTL(r,JSON.stringify(e));let s=D(e,"",t.locale,t.namespace);for(let[i,o]of Object.entries(s))this.setWithTTL(i,o);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=T(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=L(r,e.cleanKey);if(s!=null){let i;return typeof s=="object"&&s!==null&&"text"in s?i={text:String(s.text),styles:s.styles||{}}:i={text:String(s),styles:{}},this.setWithTTL(e.individualCacheKey,JSON.stringify(i)),l.debug(`Cached from namespace: ${e.cleanKey}`),i}}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,i=Math.max(0,this.ttl-s);e[n]={timestamp:r,age:s,remaining:i}}return e}getEntries(){if(this.repository.getEntries!==void 0)return this.repository.getEntries()}clearNamespace(e,t){let n=T(e,t),r=`${e}:${t}:`;this.repository.remove(n),this.ttlMap.delete(n);let s=this.repository.getEntries?.();if(s)for(let i of Object.keys(s))i.startsWith(r)&&(this.repository.remove(i),this.ttlMap.delete(i));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 me=class{constructor(e,t){u(this,"name");u(this,"version","1.0.0");u(this,"priority");u(this,"type","storage");u(this,"enabled");u(this,"ttlMap",new Map);u(this,"ttl");u(this,"repository");u(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=T(t.locale,t.namespace);await this.setWithTTL(s,JSON.stringify(e));let i=D(e,"",t.locale,t.namespace),o=0;for(let[c,d]of Object.entries(i))await this.setWithTTL(c,d),o++;l.debug(`Saved: ${o} 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=T(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=L(r,e.cleanKey);if(s!=null){let i;return typeof s=="object"&&s!==null&&"text"in s?i={text:String(s.text),styles:s.styles||{}}:i={text:String(s),styles:{}},await this.setWithTTL(e.individualCacheKey,JSON.stringify(i)),l.debug(`Cached from namespace: ${e.cleanKey}`),i}}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,i=Math.max(0,this.ttl-s);e[n]={timestamp:r,age:s,remaining:i}}return e}async destroy(){await this.repository.clear(),this.ttlMap.clear()}getEntries(){if(this.repository.getEntries!==void 0)return this.repository.getEntries()}};var A=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)}},g=class extends A{constructor(e){super(e,404,`Translation not found: ${e}`)}},x=class extends A{constructor(t,n){super(t,423,`Translation locked: ${t}`);this.retryAfter=n}},O=class extends A{constructor(e,t){super(e,t,`Server error ${t}: ${e}`)}},N=class extends Error{constructor(t,n){super(t);this.cause=n;this.name="NetworkError",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}};function st(a){return a instanceof A}function ye(a){return a instanceof O||a instanceof N}function at(a){return a instanceof g||a instanceof x}var be=class{constructor(e,t){u(this,"repository");u(this,"name");u(this,"priority");u(this,"version","1.0.0");u(this,"type","network");u(this,"enabled");u(this,"bus");u(this,"retryCount");u(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 g&&e.namespace?(l.debug(`Individual key not found, trying namespace: ${e.cleanKey}`),this.lookupFromNamespace(e,n,t,r)):s instanceof x?(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 o=L(s.data,e.cleanKey);if(o!=null){let c,d={};if(typeof o=="object"&&o!==null&&"text"in o){let p=o;c=String(p.text),d=p.styles||{}}else c=String(o);return l.debug(`Network namespace hit: ${e.cleanKey}, hasStyles=${Object.keys(d).length>0}`),r.success(c),this.createTranslationResult(c,"network",200,n,void 0,!1,{locale:e.locale,namespace:e.namespace,data:s.data},d)}}let i=new g(e.cleanKey);return this.handleTranslationNotFound(e,t,i,n)}catch(s){return l.debug(`Namespace load failed: ${e.cleanKey}`,s),s instanceof g?this.handleTranslationNotFound(e,t,s,n):s instanceof x?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 x?(l.debug(`Namespace locked (423): ${e}:${t}`),this.createNamespaceResult(null,"fallback",423,n,r)):r instanceof g?(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(i){if(r<=this.retryCount&&ye(i)){let o=this.calculateBackoff(r);return s.retry(r,o,i.message),await this.delay(o),l.debug(`Retrying ${n} (${r}/${this.retryCount}) after ${o}ms`),this.withRetry(e,t,n,r+1)}throw i}}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,i,o,c){return{value:e,source:t,status:n,duration:Date.now()-r,...s&&{error:s},...i!==void 0&&{cached:i},...o&&{namespaceLoaded:o},...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||[]}getBaseUrl(){return this.repository.getConfig().options?.baseUrl||""}};var H=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]);function Mt(a){return a.replace(/"/g,"&quot;")}function _(a,e){let n=`<${a.toLowerCase()}`;for(let[r,s]of Object.entries(e))n+=` ${r.toLowerCase()}="${Mt(s)}"`;return n+=">",n}function M(a){let e=a.search(/[\s>]/);return a.slice(1,e===-1?a.length:e).toLowerCase()}function B(a){for(let e of a)if(e.startsWith("raw:"))return e.slice(4);return null}function it(a){let e={amp:"&",lt:"<",gt:">",quot:'"',apos:"'",nbsp:" ",rsquo:"\u2019",lsquo:"\u2018",rdquo:"\u201D",ldquo:"\u201C",hellip:"\u2026",mdash:"\u2014",ndash:"\u2013",copy:"\xA9",reg:"\xAE",trade:"\u2122"};return a.replace(/&(#x[0-9a-f]+|#[0-9]+|[a-z][a-z0-9]*);/gi,(t,n)=>{if(n[0]==="#"){let r=n[1]==="x"||n[1]==="X"?parseInt(n.slice(2),16):parseInt(n.slice(1),10);if(Number.isFinite(r)&&r>0)try{return String.fromCodePoint(r)}catch{return t}return t}return e[n.toLowerCase()]??t})}var z=class{parse(e){if(/<\/?[0-9]+>/.test(e))return{text:it(e),styles:{}};let t={},n=0,r=[],s="",i=0;for(;i<e.length;){let o=this.matchTag(e,i);if(!o){s+=e.slice(i);break}if(s+=e.slice(i,o.startIndex),o.isClosing){let c=null;for(let d=r.length-1;d>=0;d--)if(r[d].tag===o.tag.toLowerCase()){c=r[d].index,r.splice(d,1);break}c!==null&&(s+=`</${c}>`)}else{let c=o.tag.toLowerCase(),d=H.has(c),p=o.isSelfClosing||d;n++,t[String(n)]=[`raw:${_(c,o.attrs)}`],p?s+=`<${n}/>`:(s+=`<${n}>`,r.push({tag:c,index:n}))}i=o.endIndex}for(;r.length>0;){let o=r.pop();s+=`</${o.index}>`}return{text:it(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*(\/?)>/,i=e.slice(n).match(r);if(!i)return n+1<e.length?this.matchTag(e,n+1):null;let[o,c,d,p,f]=i;return{tag:d,attrs:this.parseAttributes(p),isClosing:c==="/",isSelfClosing:f==="/",startIndex:n,endIndex:n+o.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,i,o,c]=r;t[s.toLowerCase()]=i??o??c??""}return t}};var ve=new Set(["a","abbr","b","bdi","bdo","br","cite","code","del","dfn","em","i","img","ins","kbd","mark","q","s","samp","small","span","strong","sub","sup","time","u","var","wbr"]),Re=new Set(["alt","cite","class","datetime","dir","height","href","id","lang","loading","rel","role","src","target","title","width"]),Bt=new Set(["href","src","cite"]),we=new Set(["color","background-color","font-family","font-size","font-style","font-weight","letter-spacing","line-height","text-decoration","text-decoration-color","text-decoration-line","text-decoration-style","text-transform","vertical-align","white-space","word-spacing"]),zt=/url\s*\(|expression\s*\(|image-set\s*\(|element\s*\(|paint\s*\(|javascript:|\\|[<>{}@]/i,Ft=new Set(["http","https","mailto","tel"]),Vt={amp:"&",lt:"<",gt:">",quot:'"',apos:"'",nbsp:"\xA0",colon:":",semi:";",sol:"/",bsol:"\\",Tab:" ",NewLine:`
5
+ `};function ot(a){return a.replace(/&(?:#[xX]([0-9a-fA-F]+);?|#(\d+);?|([a-zA-Z]+);)/g,(e,t,n,r)=>t?String.fromCodePoint(parseInt(t,16)):n?String.fromCodePoint(parseInt(n,10)):Vt[r]??e)}function Q(a){return a.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function Y(a){let t=ot(a).replace(/[\u0000-\u0020\u007f]/g,"").toLowerCase(),n=/^([a-z][a-z0-9+.-]*):/.exec(t);return n?Ft.has(n[1])?a:null:a}function Ce(a){return ct(a,!0)}function lt(a){return ct(a,!1)}function ct(a,e){let t=ot(a),n=[];for(let r of t.split(";")){let s=r.indexOf(":");if(s===-1)continue;let i=r.slice(0,s).trim().toLowerCase(),o=r.slice(s+1).trim();/^[a-z-]+$/.test(i)&&(e&&!we.has(i)||o===""||zt.test(o)||n.push(`${i}: ${o}`))}return n.length>0?n.join("; "):null}var Gt=/([^\s=/>"']+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]*)))?/g;function Z(a){if(!a.startsWith("<"))return null;let e=M(a);if(!/^[a-z][a-z0-9-]*$/.test(e)||!ve.has(e))return null;let t=a.endsWith("/>")?a.length-2:a.endsWith(">")?a.length-1:a.length,n=a.slice(1+e.length,t),r={};for(let s of n.matchAll(Gt)){let i=s[1].toLowerCase(),o=s[2]??s[3]??s[4]??"";if(i in r)continue;if(i==="style"){let d=Ce(o);d!==null&&(r[i]=d);continue}(Re.has(i)||/^data-[a-z0-9-]*$/.test(i)||/^aria-[a-z0-9-]*$/.test(i))&&(Bt.has(i)&&Y(o)===null||(r[i]=o))}return _(e,r)}function _e(a){let e=!1,t={};for(let[n,r]of Object.entries(a.styles)){let s=B(r);if(s===null){t[n]=r;continue}let i=Z(s);if(i===null){e=!0;let o=r.filter(c=>!c.startsWith("raw:"));o.length>0&&(t[n]=o)}else i===s?t[n]=r:(e=!0,t[n]=r.map(o=>o.startsWith("raw:")?`raw:${i}`:o))}return e?{text:a.text,styles:t}:a}var F=class{serialize(e){let{text:t,styles:n}=e,r=/<(\/?)?(\d+)(\/)?>/g,s="",i=0,o;for(;(o=r.exec(t))!==null;){s+=Q(t.slice(i,o.index));let[c,d,p]=o,f=n[p]??[],m=B(f),b=m===null?null:Z(m);if(m&&b!==null){let S=M(m),y=H.has(S);d?y||(s+=`</${S}>`):s+=b}else s+=c;i=o.index+c.length}return s+=Q(t.slice(i)),s}};var V=class{constructor(e,t,n,r){u(this,"handlerChain");u(this,"bus");u(this,"currentLocale");u(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 i=JSON.parse(s);return typeof i=="object"&&"text"in i?{value:String(i.text),styles:i.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,...i]=e.split(":"),o=i.join(":");if(!r||!s||!o)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:i=!0}=e,o=this.currentLocale(),c=0;if(r){let[d,p]=r.split(":");d&&p&&(this.handlerChain.clearNamespace(d,p),c=1)}else if(t&&n)this.handlerChain.clearNamespace(n,t),c=this.countClearedKeys(n,t);else if(t)this.handlerChain.clearNamespace(o,t),c=this.countClearedKeys(o,t);else if(n){let d=this.handlerChain.getEntries(),p=new Set;for(let f in d){let m=d[f];if(m&&typeof m=="object"){for(let b of Object.keys(m))if(b.startsWith(`${n}:`)||b.startsWith(`@${n}:`)){let S=b.replace("@","").split(":");S[1]&&p.add(S[1])}}}for(let f of p)this.handlerChain.clearNamespace(n,f),c++}else if(s){let d=this.handlerChain.getEntries(),p=new Map;for(let f in d){let m=d[f];if(m&&typeof m=="object"){for(let b of Object.keys(m))if(s(b)){let S=b.replace("@","").split(":"),y=S[0],v=S[1];y&&v&&(p.has(y)||p.set(y,new Set),p.get(y).add(v),c++)}}}for(let[f,m]of p)for(let b of m)this.handlerChain.clearNamespace(f,b)}else this.handlerChain.clearCache(),c=-1;this.bus.emit("cache:invalidate",{payload:{filter:e,keysCleared:c,refetch:i}}),i&&await this.refetchAfterInvalidate(e)}countClearedKeys(e,t){let n=this.handlerChain.getEntries(),r=0,s=`${e}:${t}:`,i=`@${e}:${t}`;for(let o in n){let c=n[o];if(c&&typeof c=="object")for(let d of Object.keys(c))(d.startsWith(s)||d===i)&&r++}return r}async refetchAfterInvalidate(e){let{namespace:t,locale:n,key:r}=e,s=this.currentLocale();if(r){let[i,o]=r.split(":");i&&o&&await this.loadNamespaces(i,[o])}else t&&await this.loadNamespaces(n||s,[t])}};var Wt=/<\/?[0-9]+\/?>/,Jt=/<[a-z][a-z0-9]*(?:\s+[^>]*)?\/?>/i,q=class{constructor(e,t,n="en",r){u(this,"handlerChain");u(this,"currentLocale");u(this,"defaultNamespace");u(this,"pendingTranslations",new Map);u(this,"bus");u(this,"plugins",new Map);u(this,"formatters",new Map);u(this,"processors",new Map);u(this,"warnedNoInterpolate",!1);u(this,"eventPlugins",new Set);u(this,"markupParser",new z);u(this,"htmlSerializer",new F);u(this,"cache");this.bus=e,this.handlerChain=t,this.currentLocale=n,this.defaultNamespace=r,this.cache=new V(this.handlerChain,this.bus,()=>this.currentLocale,(s,i)=>this.loadNamespaces(s,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=j(e,this.currentLocale,n,r,this.defaultNamespace);l.debug(`Translation requested: ${s.cleanKey}`);let i=this.bus.translation(s);i.request();let o=this.handlerChain.handleSync(s);if(o&&o.status===200){let p=this.processValue(o.value,s);return l.debug(`Translation found: ${s.cleanKey} from ${o.source} (${o.duration}ms)`),i.success(p),p}this.triggerBackgroundLoad(s);let c=s.parsedDefaultValue||s.cleanKey,d=this.processValue(c,s);return l.debug(`Translation fallback: ${s.cleanKey}`),i.fallback(d),d}tHtml(e,...t){let[n,r]=t,s=j(e,this.currentLocale,n,r,this.defaultNamespace);l.debug(`HTML translation requested: ${s.cleanKey}`);let i=this.bus.translation(s);i.request();let o=this.handlerChain.handleSync(s);if(o&&o.status===200){let p=this.processValueAsHtml(o.value,s,o.styles);return l.debug(`HTML translation found: ${s.cleanKey} from ${o.source}`),i.success(p),p}this.triggerBackgroundLoad(s);let c=s.parsedDefaultValue||s.cleanKey,d=this.processValueAsHtml(c,s);return l.debug(`HTML translation fallback: ${s.cleanKey}`),i.fallback(d),d}processValueAsHtml(e,t,n){let r=this.processTranslationValue(e,t);if(this.containsIndexedTags(r)){let s=n||this.getStylesFromNamespace(t),i={text:r,styles:s};return this.htmlSerializer.serialize(i)}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 Wt.test(e)}processIndexedValue(e,t){return this.processTranslationValue(e,t).replace(/<\/?[0-9]+\/?>/g,"")}getStylesFromNamespace(e){if(!e.namespace)return{};try{let t=T(e.locale,e.namespace),n=this.handlerChain.getNamespaceData(t);if(!n)return{};let r=L(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 key "${t.cleanKey}" \u2014 ${K(e)}: ${pe(n)}`),this.processTranslationValue(e,t)}}processTranslationValue(e,t,n,r){let s,i,o;if(t&&"cleanKey"in t){let d=t;s=d.parsedParams,i=d.locale,o=d.cleanKey}else s=t,i=n||this.currentLocale,o=r;let c=e;try{if(c=this.applyStructuralFormatters(c,s,o),this.formatters.has("interpolate")?c=this.formatters.get("interpolate")(c,s,i,o):!this.warnedNoInterpolate&&s&&Object.keys(s).length>0&&c.includes("{")&&(this.warnedNoInterpolate=!0,console.warn("[LionRapid] Translation params were passed but no interpolate formatter is registered \u2014 {placeholders} render literally. Install @lionrapid/formatters and add .use(coreFormattersPlugin) to the builder.")),this.processors.size>0)for(let[d,p]of this.processors.entries())try{c=p(c,s,o)}catch(f){l.warn(`Processor ${d} failed:`,f)}return c}catch(d){return l.warn(`Translation processing failed for key "${o??"(no key)"}" \u2014 ${K(e)}: ${pe(d)}`),e}}getContentUnit(e,t,n){let r=j(e,this.currentLocale,t,n,this.defaultNamespace),s=this.handlerChain.handleSync(r),i=s&&s.status===200?s.value:r.parsedDefaultValue||r.cleanKey;return(!s||s.status!==200)&&this.triggerBackgroundLoad(r),this.markupParser.parse(i)}processContentText(e,t){return this.processTranslationValue(e,t,this.currentLocale)}containsHtml(e){return Jt.test(e)}applyStructuralFormatters(e,t,n){let r=e,s=o=>typeof o?.count=="number",i=o=>typeof o?.context=="string";if(this.formatters.has("plural")&&s(t)){let o=this.formatters.get("plural");try{let c=o(r,t,this.currentLocale,n);if(c!==String(r))return c}catch(c){l.warn("Plural formatting failed:",c)}}if(this.formatters.has("context")&&i(t)){let o=this.formatters.get("context");try{let c=o(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=j(e,this.currentLocale,void 0,void 0,this.defaultNamespace);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(i){throw l.error("Language change failed:",i),s.error(i),i}}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 ee=class{constructor(e){u(this,"name","MemoryRepository");u(this,"type","memory");u(this,"config",{});u(this,"cache",new Map);u(this,"accessOrder",new Map);u(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=T(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=T(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=T(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 te=class{constructor(e,t={}){u(this,"name","StaticRepository");u(this,"type","memory");u(this,"config");u(this,"mem");this.config={enabled:t.enabled??!0,priority:t.priority??.5,options:{ttl:Number.MAX_SAFE_INTEGER,maxSize:Number.MAX_SAFE_INTEGER,...t.options}},this.mem=new ee({options:{maxSize:Number.MAX_SAFE_INTEGER}});for(let[n,r]of Object.entries(e))for(let[s,i]of Object.entries(r)){this.mem.setNamespace(n,s,i);let o=D(i,"",n,s);for(let[c,d]of Object.entries(o))this.mem.set(c,d)}}get(e){return this.mem.get(e)}getNamespace(e,t){return this.mem.getNamespace(e,t)}getEntries(){return this.mem.getEntries()}getConfig(){return this.config}set(){}remove(){}clear(){}setNamespace(){}};var ut=6e4,ne=class{constructor(e,t,n){u(this,"queue",new Map);u(this,"debounceTimer",null);u(this,"repository");u(this,"config");u(this,"eventEmitter");u(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<ut){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>=ut&&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(i=>({key:i.key,value:{text:i.value,styles:i.styles??{}}}));await this.repository.setBatchContentUnits(s),l.debug(`Synced ${e.length} missing translations (ContentUnit)`)}else if("setBatch"in this.repository){let s=e.map(i=>({key:i.key,value:i.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")}};function Xt(a){return!(a instanceof g||a instanceof x)}var Ee=class a{constructor(e){u(this,"config");u(this,"plugins",[]);u(this,"syncStorageRepos",[]);u(this,"asyncStorageRepos",[]);u(this,"networkRepos",[]);u(this,"syncQueue",null);this.config={defaultLocale:e.defaultLocale||"en",namespace:e.namespace||"app"}}static init(e={}){return new a(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}useStaticBundle(e,t=.5){return this.use(new te(e,{priority:t}))}async build(){let e=new J,t=e.builder();l.info("Builder started"),l.debug("Builder config",this.config),t.buildStart(this.config.defaultLocale,this.config.namespace);let n=new X(e);for(let o of this.syncStorageRepos){if(!o.getConfig().enabled)continue;let c=new he(e,o);t.use("sync"),n.addSyncHandler(c)}for(let o of this.asyncStorageRepos){if(!o.getConfig().enabled)continue;let c=new me(e,o);t.use("async"),n.addAsyncHandler(c)}let r=null;for(let o of this.networkRepos){if(!o.getConfig().enabled||!o.getConfig().options?.baseUrl)continue;let c=new be(e,o);r||(r=c),t.use("network"),n.addAsyncHandler(c);let d=o.getConfig();d.options?.syncMissing?.enabled&&(this.syncQueue=new ne(o,{enabled:d.options.syncMissing.enabled,debounceMs:d.options.syncMissing.debounceMs||500,batchSize:d.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",d.options.syncMissing))}l.debug("Handler chain constructed");let s=new q(e,n,this.config.defaultLocale,this.config.namespace);for(let o of this.plugins)t.use("plugin"),await o.initialize({core:s,bus:e}),s.registerPlugin(o),l.info(`Plugin initialized: ${o.name}`),l.debug(`Plugin version: ${o.version}`,o.capabilities);let i=n.getChainInfo();return r&&await this.executePreloading(r,n),l.info("Builder completed"),t.buildDone(i.handlers.map(o=>o.name),this.plugins.map(o=>o.name)),s}async executePreloading(e,t){let n=e.getPreload().filter(o=>o.eager!==!1);if(!n||n.length===0)return;l.info(`Preloading ${n.length} namespaces`),l.debug("Preload targets",{namespaces:n.map(o=>`${o.locale}:${o.namespace}`)});let r=!1,s=(o,c)=>{if(!Xt(c)||r)return;r=!0;let d=e.getBaseUrl()||"(no base URL configured)";console.warn(`[LionRapid] Could not load translations for ${o} from ${d} \u2014 the page stays untranslated until that host is reachable. If it is wrong, set data-base-url on the snippet tag (or \`baseUrl\` in the network repository options).`,c)},i=n.map(async o=>{let c=`${o.locale}:${o.namespace}`;try{let d=await e.loadNamespace(o.locale,o.namespace);if(d&&d.data&&d.status===200){let p={locale:o.locale,namespace:o.namespace};await t.saveNamespaceToHandlers(d.data,p),l.debug(`Preloaded: ${c}`);return}d?.error&&(s(c,d.error),l.warn(`Preload failed: ${c}`,d.error))}catch(d){s(c,d),l.warn(`Preload failed: ${c}`,d)}});await Promise.allSettled(i),l.info("Preloading completed")}};var Qt="X-LR-Surface",Yt="snippet",I=class I{constructor(e={}){u(this,"name","NetworkRepository");u(this,"type","network");u(this,"config",{});u(this,"namespaceSnapshots",new Map);u(this,"inflightGets",new Map);u(this,"negativeCache",new Map);u(this,"authFailedStatus",null);u(this,"writesFailedStatus",null);u(this,"DEFAULT_ENDPOINTS",{getTranslation:"/api/integrations/translations/:key",getNamespace:"/api/integrations/translations/:locale/:namespace",getProjectConfig:"/api/integrations/project-config",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 N("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 g(e);return typeof s=="object"&&"text"in s?(l.debug(`ContentUnit text: ${K(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 N("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 g(e);return typeof s=="object"&&"text"in s?(l.debug(`ContentUnit for "${e}": text=${K(s.text)}, styles=`,s.styles),{text:s.text,styles:s.styles||{}}):(l.debug(`Plain string for "${e}": ${K(String(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 N("API base URL is not set");try{return await this.fetchNamespaceRaw(e,t)}catch(n){this.handleCaughtError(n)}}async getProjectConfig(){if(!this.config?.options?.baseUrl)throw new N("API base URL is not set");let e=this.buildUrl("getProjectConfig",{});l.debug(`API GET ProjectConfig: ${e}`);try{let t=await this.makeRequest(e,"GET");if(t.status===404)return null;t.ok||this.handleHttpError(t,"project-config");let n=await t.json();return!n||typeof n.defaultLocale!="string"||!Array.isArray(n.languages)?(l.warn("project-config payload unusable \u2014 keeping local fallback"),null):{defaultLocale:n.defaultLocale,languages:n.languages.map(String)}}catch(t){this.handleCaughtError(t)}}async fetchNamespaceRaw(e,t,n=!0){let r=this.buildUrl("getNamespace",{locale:e,namespace:t});l.debug(`API GET Namespace: ${r}`);let s=`${e}:${t}`,i=n?this.getSnapshot(s):void 0,o={};i&&(o["If-None-Match"]=`W/"${i.version}"`);let c=await this.makeRequest(r,"GET",void 0,o);if(c.status===304)return i?(l.debug(`Namespace ${s}: 304 Not Modified (snapshot served)`),i.translations):(l.debug(`Namespace ${s}: unexpected 304 with no snapshot \u2014 refetching`),this.fetchNamespaceRaw(e,t,!1));c.ok||this.handleHttpError(c,s);let d=await c.json();if(l.debug("API response data:",d),!d.translations)throw new g(s);let p=d.meta?.version!=null?String(d.meta.version):null;return p&&this.setSnapshot(s,{version:p,translations:d.translations}),d.translations}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 N("API base URL is not set");try{return await this.fetchNamespaceRaw(e,t)}catch(n){this.handleCaughtError(n)}}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}getSnapshot(e){let t=this.namespaceSnapshots.get(e);if(t)return t;try{localStorage.removeItem(I.LEGACY_VERSION_PREFIX+e);let n=localStorage.getItem(I.SNAPSHOT_PREFIX+e);if(n){let r=JSON.parse(n);if(r&&typeof r.version=="string"&&r.version.length>0&&r.translations&&typeof r.translations=="object")return this.namespaceSnapshots.set(e,r),r;localStorage.removeItem(I.SNAPSHOT_PREFIX+e)}}catch{}}setSnapshot(e,t){this.namespaceSnapshots.set(e,t);try{localStorage.setItem(I.SNAPSHOT_PREFIX+e,JSON.stringify(t)),localStorage.removeItem(I.LEGACY_VERSION_PREFIX+e)}catch{}}handleHttpError(e,t){if(l.debug(`API response: ${e.status} ${e.statusText}`),e.status===404)throw new g(t);if(e.status===423){let n=e.headers.get("Retry-After");throw new x(t,n?parseInt(n,10)*1e3:void 0)}throw e.status>=500&&e.status<600?new O(t,e.status):new N(`HTTP ${e.status}: ${e.statusText}`)}handleCaughtError(e){throw e instanceof g||e instanceof x||e instanceof O||e instanceof N?e:new N("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[i,o]of Object.entries(t)){let c=new RegExp(`:${i}`,"g");s=s.replace(c,encodeURIComponent(o))}return`${n}${s}`}makeRequest(e,t,n,r){if(this.authFailedStatus!==null)return Promise.resolve(new Response(null,{status:this.authFailedStatus,statusText:`auth latched off after ${this.authFailedStatus}`}));if(t!=="GET")return this.writesFailedStatus!==null?Promise.resolve(new Response(null,{status:this.writesFailedStatus,statusText:`writes latched off after ${this.writesFailedStatus}`})):this.doFetch(e,t,n,r).then(d=>this.recordOutcome(e,t,d));let s=this.negativeCache.get(e);if(s){if(Date.now()<s.until){l.debug(`Negative-cache hit (${s.status}): ${e}`);let d=s.status===423?{"Retry-After":String(Math.ceil((s.until-Date.now())/1e3))}:void 0;return Promise.resolve(new Response(null,{status:s.status,statusText:"negative cache",headers:d}))}this.negativeCache.delete(e)}let i=`${e}|${r?.["If-None-Match"]??""}`,o=this.inflightGets.get(i);if(o)return o.then(d=>this.cloneResponse(d));let c=this.doFetch(e,t,n,r).then(d=>this.recordOutcome(e,t,d)).finally(()=>this.inflightGets.delete(i));return this.inflightGets.set(i,c),c.then(d=>this.cloneResponse(d))}recordOutcome(e,t,n){let r=n.status;if(r===401||r===403&&t==="GET")return this.authFailedStatus===null&&(this.authFailedStatus=r,console.warn(`[LionRapid] API key rejected (${r}) \u2014 network translations are disabled for this session. Fix the key and reload; retrying cannot heal an auth failure.`)),n;if((r===403||r===429)&&t!=="GET")return this.writesFailedStatus===null&&(this.writesFailedStatus=r,l.warn(`Write path disabled after ${r} (scope/quota) \u2014 running read-only`)),n;if(t==="GET"&&(r===404||r===423)){let s=r===423?Number(n.headers?.get?.("Retry-After")):NaN,i=Number.isFinite(s)&&s>0?s*1e3:this.config.options?.negativeCacheTtlMs??I.DEFAULT_NEGATIVE_TTL_MS;this.negativeCache.set(e,{status:r,until:Date.now()+i})}else t!=="GET"&&n.ok?this.negativeCache.clear():t==="GET"&&n.ok&&this.negativeCache.delete(e);return n}cloneResponse(e){return typeof e.clone=="function"?e.clone():e}async doFetch(e,t,n,r){let s=new AbortController,i=this.config.options?.timeout??1e4,o=setTimeout(()=>s.abort(),i);try{let c={"Content-Type":"application/json",[Qt]:Yt,...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(o)}}};u(I,"SNAPSHOT_PREFIX","lionrapid:ns:"),u(I,"LEGACY_VERSION_PREFIX","lionrapid:v:"),u(I,"DEFAULT_NEGATIVE_TTL_MS",6e4);var Te=I;var le=class{validate(e){let t=[],n=[];return this.validateTagBalance(e.text,t),this.validateStyleReferences(e.text,e.styles,t,n),this.validateICUBraces(e.text,t),{valid:t.length===0,errors:t,warnings:n}}validateTagBalance(e,t){let n=/<(\/?)?(\d+)(\/)?>/g,r=[],s;for(;(s=n.exec(e))!==null;){let[,i,o,c]=s;if(!c)if(i)if(r.length===0)t.push({code:"UNBALANCED_TAGS",message:`Closing tag </${o}> has no matching opening tag`,path:`text[${s.index}]`});else{let d=r[r.length-1];if(d.index===o)r.pop();else{let p=r.findIndex(f=>f.index===o);p>=0?(t.push({code:"UNBALANCED_TAGS",message:`Improperly nested: </${o}> should close before </${d.index}>`,path:`text[${s.index}]`}),r.splice(p,1)):t.push({code:"UNBALANCED_TAGS",message:`Closing tag </${o}> has no matching opening tag`,path:`text[${s.index}]`})}}else r.push({index:o,position:s.index})}for(let{index:i}of r)t.push({code:"UNBALANCED_TAGS",message:`Opening tag <${i}> has no matching closing tag`,path:"text"})}validateStyleReferences(e,t,n,r){let s=new Set,i=/<\/?(\d+)(?:\/)?>/g,o;for(;(o=i.exec(e))!==null;)s.add(o[1]);for(let c of s)(!t[c]||t[c].length===0)&&r.push({code:"EMPTY_STYLE",message:`Tag <${c}> has no style definition, will render as <span>`});for(let c of Object.keys(t))s.has(c)||r.push({code:"UNUSED_TAG",message:`Style for tag <${c}> is defined but tag is not used in text`})}validateICUBraces(e,t){let n=0,r=!1,s="";for(let o=0;o<e.length;o++){let c=e[o],d=o>0?e[o-1]:"";if((c==='"'||c==="'")&&d!=="\\"){r?c===s&&(r=!1,s=""):(r=!0,s=c);continue}r||(c==="{"?n++:c==="}"&&(n--,n<0&&(t.push({code:"INVALID_ICU",message:`Unbalanced ICU braces: unexpected '}' at position ${o}`,path:`text[${o}]`}),n=0)))}n>0&&t.push({code:"INVALID_ICU",message:`Unbalanced ICU braces: ${n} unclosed '{'`,path:"text"}),/\{\s*[,}]/.test(e)&&t.push({code:"INVALID_ICU",message:"ICU variable name is empty or missing",path:"text"})}};var pt=new Set(["title","p","h1","h2","h3","h4","h5","h6","li","td","th","label","button","figcaption","dt","dd","summary","caption"]),Zt=new Set(["a"]),qt=new Set(["script","style","code","pre","textarea","noscript","svg"]),U=/<(\/?)([a-zA-Z][a-zA-Z0-9]*)((?:\s+[a-zA-Z][a-zA-Z0-9-]*(?:=(?:"[^"]*"|'[^']*'|[^\s>]*))?)*)\s*(\/?)>/g;function en(a){return a.includes("data-no-translate")?!0:/translate\s*=\s*["']no["']/.test(a)}function tn(a){U.lastIndex=0;let e;for(;(e=U.exec(a))!==null;){let[,t,n,,r]=e;if(!t&&!r&&pt.has(n.toLowerCase()))return!0}return!1}function dt(a,e,t){let n=t.toLowerCase(),r=1;U.lastIndex=e;let s;for(;(s=U.exec(a))!==null;){let[,i,o,,c]=s;if(o.toLowerCase()===n)if(i){if(r--,r===0)return s.index}else c||r++}return-1}function Me(a){let e=[],t=0,n=0,r=0,s=1e5,i=[];for(;t<a.length&&r<s;){r++;let o=a.indexOf("<",t);if(o===-1)break;if(a.startsWith("<!--",o)){let v=a.indexOf("-->",o+4);if(v===-1)break;t=v+3;continue}U.lastIndex=o;let c=U.exec(a);if(!c||c.index!==o){t=o+1;continue}let[d,p,f,m,b]=c,S=f.toLowerCase(),y=c.index+d.length;if(qt.has(S)){p?n>0&&n--:b||n++,t=y;continue}if(n>0){t=y;continue}for(;i.length&&t>=i[i.length-1];)i.pop();if(!p&&!b&&en(m)){let v=dt(a,y,f);v!==-1&&i.push(v)}if(i.length>0){t=y;continue}if((pt.has(S)||Zt.has(S))&&!p&&!b){let v=dt(a,y,f);if(v===-1){t=y;continue}let Fe=a.slice(y,v);if(tn(Fe)){t=y;continue}e.push({tag:S,openTag:d,attrs:m,inner:Fe,innerStart:y,innerEnd:v}),U.lastIndex=v;let Le=U.exec(a);t=Le?Le.index+Le[0].length:v+1;continue}t=y}return{blocks:e}}function Be(a,e){let t=[...e].sort((r,s)=>s.block.innerStart-r.block.innerStart),n=a;for(let{block:r,inner:s}of t)n=n.slice(0,r.innerStart)+s+n.slice(r.innerEnd);return n}var nn={emails:!0,urls:!0,numbers:!0,phones:!0},Se={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,}$/},xe=class{constructor(e={},t=2){u(this,"patterns");u(this,"minTextLength");this.patterns={...nn,...e},this.minTextLength=t}shouldExclude(e){let t=e.trim();return!!(t.length<this.minTextLength||this.patterns.emails&&Se.email.test(t)||this.patterns.urls&&Se.url.test(t)||this.patterns.numbers&&Se.number.test(t)||this.patterns.phones&&Se.phone.test(t))}};var rn=new Set(["script","iframe","frame","frameset","object","embed","applet","base","meta","link","template","portal"]),sn=new Set(["href","src","action","formaction","poster","data","xlink:href"]);function gt(a){let e=[a,...Array.from(a.querySelectorAll("*"))];for(let t of e){let n=t.tagName.toLowerCase();if(rn.has(n)){t.remove();continue}for(let r of t.getAttributeNames()){let s=r.toLowerCase();if(s.startsWith("on")||s==="srcdoc"){t.removeAttribute(r);continue}if(sn.has(s)){Y(t.getAttribute(r)??"")===null&&t.removeAttribute(r);continue}if(s==="style"){let i=lt(t.getAttribute(r)??"");i===null?t.removeAttribute(r):t.setAttribute(r,i)}}}}function ft(a,e){let t=a.replace(/@import[^;]*(;|$)/gi,"");return t=t.replace(/url\(\s*(['"]?)([^'")]*)\1\s*\)/gi,(n,r,s)=>{try{let i=new URL(s,e);if(i.protocol==="data:"||i.origin===new URL(e).origin)return n}catch{}return'url("")'}),t.replace(/expression\s*\(/gi,"blocked(")}var ze="lionrapid:",re=`${ze}version`,ht="1",Ne=class{constructor(e={}){u(this,"name","LocalStorageRepository");u(this,"type","memory");u(this,"config");u(this,"available");u(this,"prefix");u(this,"defaultTTL");u(this,"maxSize");this.config={enabled:e.enabled??!0,priority:e.priority??0,options:{prefix:e.options?.prefix??ze,ttl:e.options?.ttl??1440*60*1e3,maxSize:e.options?.maxSize??500,...e.options}},this.prefix=this.config.options?.prefix??ze,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(re)!==ht&&(this.clear(),window.localStorage.setItem(re,ht))}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!==re&&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 i=0;i<window.localStorage.length;i++){let o=window.localStorage.key(i);if(!o?.startsWith(this.prefix))continue;let c=o.slice(this.prefix.length);(c===n||c.startsWith(r))&&s.push(o)}s.forEach(i=>window.localStorage.removeItem(i))}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===re)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!==re&&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===re))try{let s=window.localStorage.getItem(r);if(s){let i=JSON.parse(s);e.push({key:r,timestamp:i.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=Object.freeze({translations:"lionrapid-v1",offlineFloor:"lionrapid-offline-v1"}),$e="https://cache.lionrapid.internal/";var mt=ke.translations,$=$e,Ie=class{constructor(e={}){u(this,"name","CacheStorageRepository");u(this,"type","storage");u(this,"config");u(this,"cacheName");u(this,"defaultTTL");u(this,"available");this.config={enabled:e.enabled??!0,priority:e.priority??0,options:{cacheName:e.options?.cacheName??mt,ttl:e.options?.ttl??10080*60*1e3,...e.options}},this.cacheName=this.config.options?.cacheName??mt,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 g(e);try{let t=await caches.open(this.cacheName),n=await t.match($+e);if(!n)throw new g(e);let r=await n.json();if(r.expiry!==null&&Date.now()>r.expiry)throw await t.delete($+e),new g(e);return r.value}catch(t){throw t instanceof g?t:new g(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($+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($+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($)).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),i=await s.keys();await Promise.all(i.filter(o=>{let c=o.url,d=c.includes($)?c.substring(c.indexOf($)+$.length):"";return d===n||d.startsWith(r)}).map(o=>s.delete(o)))}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 g(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($))continue;let i=s.substring(s.indexOf($)+$.length);try{let o=await this.get(i);e[i]=o}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($)).length,cacheName:this.cacheName}}catch{return{size:0,cacheName:this.cacheName}}}};var yt="https://app.lionrapid.com";var an="0.6.6";return Tt(on);})();
4
6
  //# sourceMappingURL=lionrapid.iife.min.js.map