@rimori/playwright-testing 0.3.31-next.0 → 0.3.32

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 (32) hide show
  1. package/dist/harness/__mfe_internal__rimori_mf_2_scenario_mf_2_host__loadShare___mf_0_rimori_mf_1_client__loadShare__.mjs.js +1 -5
  2. package/dist/harness/__mfe_internal__rimori_mf_2_scenario_mf_2_host__loadShare___mf_0_rimori_mf_1_react_mf_2_client__loadShare__.mjs.js +2 -130
  3. package/dist/harness/__mfe_internal__rimori_mf_2_scenario_mf_2_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js +1 -0
  4. package/dist/harness/__mfe_internal__rimori_mf_2_scenario_mf_2_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.mjs.js +1 -1
  5. package/dist/harness/__mfe_internal__rimori_mf_2_scenario_mf_2_host__loadShare__react__loadShare__.js +1 -0
  6. package/dist/harness/__mfe_internal__rimori_mf_2_scenario_mf_2_host__loadShare__react_mf_1_jsx_mf_2_dev_mf_2_runtime__loadShare__.js +1 -0
  7. package/dist/harness/__mfe_internal__rimori_mf_2_scenario_mf_2_host__loadShare__react_mf_1_jsx_mf_2_dev_mf_2_runtime__loadShare__.mjs.js +1 -1
  8. package/dist/harness/__mfe_internal__rimori_mf_2_scenario_mf_2_host__loadShare__react_mf_1_jsx_mf_2_runtime__loadShare__.js +1 -0
  9. package/dist/harness/__mfe_internal__rimori_mf_2_scenario_mf_2_host__loadShare__react_mf_2_dom__loadShare__.js +1 -0
  10. package/dist/harness/__mfe_internal__rimori_mf_2_scenario_mf_2_host__loadShare__react_mf_2_dom__loadShare__.mjs.js +1 -0
  11. package/dist/harness/__mfe_internal__rimori_mf_2_scenario_mf_2_host__loadShare__react_mf_2_dom_mf_1_client__loadShare__.mjs.js +3 -3
  12. package/dist/harness/__mfe_internal__rimori_mf_2_scenario_mf_2_host__loadShare__zod__loadShare__.js +1 -0
  13. package/dist/harness/__mfe_internal__rimori_mf_2_scenario_mf_2_host__loadShare__zod__loadShare__.mjs.js +1 -1
  14. package/dist/harness/client.js +1 -0
  15. package/dist/harness/dist.js +4 -0
  16. package/dist/harness/dist2.js +130 -0
  17. package/dist/harness/dist3.js +5 -0
  18. package/dist/harness/hostInit.js +1 -1
  19. package/dist/harness/index.html +1 -0
  20. package/dist/harness/index.js +1 -1
  21. package/dist/harness/jsx-dev-runtime.js +1 -0
  22. package/dist/harness/jsx-runtime.js +1 -0
  23. package/dist/harness/localSharedImportMap.js +1 -1
  24. package/dist/harness/modern.js +1 -0
  25. package/dist/harness/react-dom.js +1 -0
  26. package/dist/harness/react.js +1 -0
  27. package/dist/harness/virtualExposes.js +1 -1
  28. package/dist/harness/virtual_mf-REMOTE_ENTRY_ID___mfe_internal__rimori-scenario-host__remoteEntry-_hash_.js +2 -4
  29. package/dist/harness/virtual_mf-exposes___mfe_internal__rimori-scenario-host__remoteEntry-_hash_.js +1 -0
  30. package/dist/harness/zod.js +1 -0
  31. package/package.json +18 -17
  32. package/dist/harness/preload-helper.js +0 -1
@@ -1,5 +1 @@
1
- import{r as e}from"./rolldown-runtime.js";var t=class e{listeners=new Map;responseResolvers=new Map;static instance=null;debugEnabled=!1;evName=``;generatedIds=new Map;cleanupInterval=null;constructor(){this.startIdCleanup()}static create(t){let n=new e;return t&&(n.evName=t),n}static getInstance(t){return e.instance||(e.instance=new e,e.instance.on(`global.system.requestDebug`,()=>{e.instance.debugEnabled=!0,console.log(`[${e.instance.evName}] Debug mode enabled. Make sure debugging messages are enabled in the browser console.`)})),t&&e.instance.evName===``&&(e.instance.evName=t),e.instance}startIdCleanup(){this.cleanupInterval=setInterval(()=>{let e=Date.now()-6e4;for(let[t,n]of this.generatedIds.entries())n<e&&this.generatedIds.delete(t)},1e4)}generateUniqueId(){let e=Date.now(),t=e-6e4,n=Math.floor(Math.random()*1e10),r=this.generatedIds.get(n);return r&&r>t?this.generateUniqueId():(this.generatedIds.set(n,e),n)}createEvent(e,t,n,r,i){return{eventId:r||this.generateUniqueId(),timestamp:new Date().toISOString(),sender:e,topic:t,data:n,debug:this.debugEnabled,ai_session_token:i}}emit(e,t,n,r,i){this.emitInternal(e,t,n||{},r,!1,i)}emitInternal(e,t,n,r,i=!1,a){if(!this.validateTopic(t)){this.logAndThrowError(!1,`Invalid topic: `+t);return}let o=this.createEvent(e,t,n,r,a),s=this.getMatchingHandlers(o.topic);s.forEach(t=>{t.ignoreSender&&t.ignoreSender.includes(e)||t.handler(o)}),this.logIfDebug(`Emitting event to `+t,o),s.size===0&&this.logAndThrowError(!1,`No handlers found for topic: `+t),r&&this.responseResolvers.has(r)&&!i&&(this.responseResolvers.get(r)(o),this.responseResolvers.delete(r))}on(e,t,n=[]){let r=this.toArray(e).map(e=>{this.logIfDebug(`Subscribing to `+e,{ignoreSender:n}),this.validateTopic(e)||this.logAndThrowError(!0,`Invalid topic: `+e),this.listeners.has(e)||this.listeners.set(e,new Set);let r=this.generateUniqueId(),i=[];return this.listeners.get(e).add({id:r,handler:e=>{if(!i.some(t=>t.eventId===e.eventId&&t.sender===e.sender))return i.push({eventId:e.eventId,sender:e.sender}),i.length>100&&i.shift(),t(e)},ignoreSender:n}),this.logIfDebug(`Subscribed to `+e,{listenerId:r,ignoreSender:n}),btoa(JSON.stringify({topic:e,id:r}))});return{off:()=>this.off(r)}}respond(e,t,n){let r=(Array.isArray(t)?t:[t]).map(t=>{let r=[],i=t.startsWith(`self.`)?[]:[e],a=this.on(t,async i=>{if(r.includes(i.eventId))return;r.push(i.eventId),r.length>100&&r.shift();let a=typeof n==`function`?await n(i):n;this.emit(e,t,a,i.eventId)},i);return this.logIfDebug(`Added respond listener `+e+` to topic `+t,{listener:a,sender:e}),{off:()=>a.off()}});return{off:()=>r.forEach(e=>e.off())}}once(e,t){if(!this.validateTopic(e)){this.logAndThrowError(!1,`Invalid topic: `+e);return}let n;n=this.on(e,e=>{t(e),n?.off()}),this.logIfDebug(`Added once listener `+e,{listener:n,topic:e})}off(e){this.toArray(e).forEach(e=>{let{topic:t,id:n}=JSON.parse(atob(e)),r=this.listeners.get(t)||new Set;r.forEach(i=>{i.id===Number(n)&&(r.delete(i),this.logIfDebug(`Removed listener `+e,{topic:t,listenerId:n}))})})}toArray(e){return Array.isArray(e)?e:[e]}async request(e,t,n,r){this.validateTopic(t)||this.logAndThrowError(!0,`Invalid topic: `+t);let i=this.createEvent(e,t,n||{},void 0,r);return this.logIfDebug(`Requesting data from `+t,{event:i}),new Promise(a=>{this.responseResolvers.set(i.eventId,e=>a(e)),this.emitInternal(e,t,n||{},i.eventId,!0,r)})}getMatchingHandlers(e){let t=this.listeners.get(e)||new Set,n=[...this.listeners.entries()].filter(([t])=>t.endsWith(`*`)&&e.startsWith(t.slice(0,-1))).flatMap(([e,t])=>[...t]);return new Set([...t,...n])}validateTopic(e){let t=e.split(`.`),[n,r,i]=t;if(t.length!==3)return t.length===1&&n===`*`||t.length===2&&n!==`*`&&r===`*`?!0:(this.logAndThrowError(!1,`Event type must have 3 parts separated by dots. Received: `+e),!1);if(i===`*`)return!0;let a=[`request`,`create`,`update`,`delete`,`trigger`];return a.some(e=>i.startsWith(e))?!0:(this.logAndThrowError(!1,`Invalid event topic name. The action: `+i+`. Must be or start with one of: `+a.join(`, `)),!1)}logIfDebug(...e){this.debugEnabled&&console.debug(`[${this.evName}] `+e[0],...e.slice(1))}destroy(){this.listeners.clear(),this.responseResolvers.clear(),this.cleanupInterval&&=(clearInterval(this.cleanupInterval),null),this.generatedIds.clear()}logAndThrowError(e,...t){let n=`[${this.evName}] `+t[0];if(console.error(n,...t.slice(1)),e)throw Error(n)}},n=t.getInstance(),r=class{supabase;rimoriClient;constructor(e,t){this.supabase=e,this.rimoriClient=t}async getNew(e){let t=await this.rimoriClient.runtime.fetchBackend(`/shared-content/generate`,{method:`POST`,body:JSON.stringify({tableName:e.table,skillType:e.skillType,placeholders:e.placeholders,filter:e.filter,customFields:e.customFields,tool:e.tool,options:{skipDbSave:e.skipDbSave,isPrivate:e.isPrivate,ignoreSkillLevel:e.ignoreSkillLevel}})});if(!t.ok)throw Error(`Failed to generate shared content: ${t.statusText}`);return await t.json()}async searchByTopic(e,t,n=10){let r=await this.rimoriClient.runtime.fetchBackend(`/shared-content/get-by-topic`,{method:`POST`,body:JSON.stringify({tableName:e,limit:n,filter:{title:{filterType:`rag`,value:t}}})});if(!r.ok)throw Error(`Failed to search shared content: ${r.statusText}`);return await r.json()}async getBookmarked(e,t=30){let n=this.getTableName(e),r=this.getCompletedTableName(e),{data:i,error:a}=await this.supabase.from(n).select(`*, completed:${r}!inner(*)`).eq(`completed.bookmarked`,!0).limit(t);if(a)throw console.error(`Error fetching bookmarked content:`,a),Error(`Error fetching bookmarked content`);return i||[]}async getOngoing(e,t=30){let n=this.getTableName(e),r=this.getCompletedTableName(e),{data:i,error:a}=await this.supabase.from(n).select(`*, completed:${r}!inner(*)`).eq(`completed.state`,`ongoing`).limit(t);if(a)throw console.error(`Error fetching ongoing content:`,a),Error(`Error fetching ongoing content`);return i||[]}async getCompleted(e,t=30){let n=this.getTableName(e),r=this.getCompletedTableName(e),{data:i,error:a}=await this.supabase.from(n).select(`*, completed:${r}!inner(*)`).eq(`completed.state`,`completed`).limit(t);if(a)throw console.error(`Error fetching completed content:`,a),Error(`Error fetching completed content`);return i||[]}async complete(e,t){let n=this.getCompletedTableName(e),{error:r}=await this.supabase.from(n).upsert({content_id:t,state:`completed`},{onConflict:`content_id,user_id`});if(r)throw console.error(`Error completing shared content:`,r),Error(`Error completing shared content`)}async updateState(e,t,n){let r=this.getCompletedTableName(e),{error:i}=await this.supabase.from(r).upsert({content_id:t,state:n},{onConflict:`content_id,user_id`});if(i)throw console.error(`Error updating content state:`,i),Error(`Error updating content state`)}async bookmark(e,t,n){let r=this.getCompletedTableName(e),{error:i}=await this.supabase.from(r).upsert({content_id:t,bookmarked:n},{onConflict:`content_id,user_id`});if(i)throw console.error(`Error bookmarking content:`,i),Error(`Error bookmarking content`)}async react(e,t,n){let r=this.getCompletedTableName(e),{error:i}=await this.supabase.from(r).upsert({content_id:t,reaction:n},{onConflict:`content_id,user_id`});if(i)throw console.error(`Error reacting to content:`,i),Error(`Error reacting to content`)}async get(e,t){let n=this.getTableName(e),{data:r,error:i}=await this.supabase.from(n).select(`*`).eq(`id`,t).single();if(i)throw console.error(`Error fetching shared content:`,i),Error(`Error fetching shared content`);return r}async getAll(e,t=100){let n=this.getTableName(e),{data:r,error:i}=await this.supabase.from(n).select(`*`).limit(t);if(i)throw console.error(`Error fetching all shared content:`,i),Error(`Error fetching all shared content`);return r||[]}async create(e,t,n){let r=this.getTableName(e),i=this.rimoriClient.plugin.getUserInfo()[`skill_level_${t}`],{data:a,error:o}=await this.supabase.from(r).insert({...n,skill_level:i}).select().single();if(o)throw console.error(`Error creating shared content:`,o),Error(`Error creating shared content`);return a}async update(e,t,n){let r=await this.rimoriClient.runtime.fetchBackend(`/shared-content/update`,{method:`POST`,body:JSON.stringify({tableName:e,contentId:t,updates:n})});if(!r.ok)throw console.error(`Error updating shared content:`,r.statusText),Error(`Failed to update shared content: ${r.statusText}`);return await r.json()}async validate(e,t){let n=await this.rimoriClient.runtime.fetchBackend(`/shared-content/validate`,{method:`POST`,body:JSON.stringify({tableName:e,contentId:t})});if(!n.ok)throw console.error(`Error validating shared content:`,n.statusText),Error(`Failed to validate shared content: ${n.statusText}`);return await n.json()}async remove(e,t){let n=this.getTableName(e),{error:r}=await this.supabase.from(n).delete().eq(`id`,t);if(r)throw console.error(`Error deleting shared content:`,r),Error(`Error deleting shared content`)}getCompletedTableName(e){return this.getTableName(e)+`_completed`}getTableName(e){return`${this.rimoriClient.plugin.pluginId}_sc_${e}`}},i=3,a=e=>Math.min(1e3*2**e,3e4),o=[520,503],s=[`GET`,`HEAD`,`OPTIONS`],c=class extends Error{constructor(e){super(e.message),this.name=`PostgrestError`,this.details=e.details,this.hint=e.hint,this.code=e.code}toJSON(){return{name:this.name,message:this.message,details:this.details,hint:this.hint,code:this.code}}};function l(e,t){return new Promise(n=>{if(t?.aborted){n();return}let r=setTimeout(()=>{t?.removeEventListener(`abort`,i),n()},e);function i(){clearTimeout(r),n()}t?.addEventListener(`abort`,i)})}function u(e,t,n,r){return!(!r||n>=i||!s.includes(e)||!o.includes(t))}var d=class{constructor(e){this.shouldThrowOnError=!1,this.retryEnabled=!0,this.method=e.method,this.url=e.url,this.headers=new Headers(e.headers),this.schema=e.schema,this.body=e.body,this.shouldThrowOnError=e.shouldThrowOnError??!1,this.signal=e.signal,this.isMaybeSingle=e.isMaybeSingle??!1,this.shouldStripNulls=e.shouldStripNulls??!1,this.urlLengthLimit=e.urlLengthLimit??8e3,this.retryEnabled=e.retry??!0,e.fetch?this.fetch=e.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}stripNulls(){if(this.headers.get(`Accept`)===`text/csv`)throw Error(`stripNulls() cannot be used with csv()`);return this.shouldStripNulls=!0,this}setHeader(e,t){return this.headers=new Headers(this.headers),this.headers.set(e,t),this}retry(e){return this.retryEnabled=e,this}then(e,t){var n=this;if(this.schema===void 0||([`GET`,`HEAD`].includes(this.method)?this.headers.set(`Accept-Profile`,this.schema):this.headers.set(`Content-Profile`,this.schema)),this.method!==`GET`&&this.method!==`HEAD`&&this.headers.set(`Content-Type`,`application/json`),this.shouldStripNulls){let e=this.headers.get(`Accept`);e===`application/vnd.pgrst.object+json`?this.headers.set(`Accept`,`application/vnd.pgrst.object+json;nulls=stripped`):(!e||e===`application/json`)&&this.headers.set(`Accept`,`application/vnd.pgrst.array+json;nulls=stripped`)}let r=this.fetch,o=(async()=>{let e=0;for(;;){let t=new Headers(n.headers);e>0&&t.set(`X-Retry-Count`,String(e));let o;try{o=await r(n.url.toString(),{method:n.method,headers:t,body:JSON.stringify(n.body,(e,t)=>typeof t==`bigint`?t.toString():t),signal:n.signal})}catch(t){if(t?.name===`AbortError`||t?.code===`ABORT_ERR`||!s.includes(n.method))throw t;if(n.retryEnabled&&e<i){let t=a(e);e++,await l(t,n.signal);continue}throw t}if(u(n.method,o.status,e,n.retryEnabled)){let t=o.headers?.get(`Retry-After`)??null,r=t===null?a(e):Math.max(0,parseInt(t,10)||0)*1e3;await o.text(),e++,await l(r,n.signal);continue}return await n.processResponse(o)}})();return this.shouldThrowOnError||(o=o.catch(e=>{let t=``,n=``,r=``,i=e?.cause;if(i){let n=i?.message??``,r=i?.code??``;t=`${e?.name??`FetchError`}: ${e?.message}`,t+=`\n\nCaused by: ${i?.name??`Error`}: ${n}`,r&&(t+=` (${r})`),i?.stack&&(t+=`\n${i.stack}`)}else t=e?.stack??``;let a=this.url.toString().length;return e?.name===`AbortError`||e?.code===`ABORT_ERR`?(r=``,n=`Request was aborted (timeout or manual cancellation)`,a>this.urlLengthLimit&&(n+=`. Note: Your request URL is ${a} characters, which may exceed server limits. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [many IDs])), consider using an RPC function to pass values server-side.`)):(i?.name===`HeadersOverflowError`||i?.code===`UND_ERR_HEADERS_OVERFLOW`)&&(r=``,n=`HTTP headers exceeded server limits (typically 16KB)`,a>this.urlLengthLimit&&(n+=`. Your request URL is ${a} characters. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [200+ IDs])), consider using an RPC function instead.`)),{success:!1,error:{message:`${e?.name??`FetchError`}: ${e?.message}`,details:t,hint:n,code:r},data:null,count:null,status:0,statusText:``}})),o.then(e,t)}async processResponse(e){var t=this;let n=null,r=null,i=null,a=e.status,o=e.statusText;if(e.ok){if(t.method!==`HEAD`){let n=await e.text();n===``||(r=t.headers.get(`Accept`)===`text/csv`||t.headers.get(`Accept`)&&t.headers.get(`Accept`)?.includes(`application/vnd.pgrst.plan+text`)?n:JSON.parse(n))}let s=t.headers.get(`Prefer`)?.match(/count=(exact|planned|estimated)/),c=e.headers.get(`content-range`)?.split(`/`);s&&c&&c.length>1&&(i=parseInt(c[1])),t.isMaybeSingle&&Array.isArray(r)&&(r.length>1?(n={code:`PGRST116`,details:`Results contain ${r.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:`JSON object requested, multiple (or no) rows returned`},r=null,i=null,a=406,o=`Not Acceptable`):r=r.length===1?r[0]:null)}else{let i=await e.text();try{n=JSON.parse(i),Array.isArray(n)&&e.status===404&&(r=[],n=null,a=200,o=`OK`)}catch{e.status===404&&i===``?(a=204,o=`No Content`):n={message:i}}if(n&&t.shouldThrowOnError)throw new c(n)}return{success:n===null,error:n,data:r,count:i,status:a,statusText:o}}returns(){return this}overrideTypes(){return this}},f=class extends d{select(e){let t=!1,n=(e??`*`).split(``).map(e=>/\s/.test(e)&&!t?``:(e===`"`&&(t=!t),e)).join(``);return this.url.searchParams.set(`select`,n),this.headers.append(`Prefer`,`return=representation`),this}order(e,{ascending:t=!0,nullsFirst:n,foreignTable:r,referencedTable:i=r}={}){let a=i?`${i}.order`:`order`,o=this.url.searchParams.get(a);return this.url.searchParams.set(a,`${o?`${o},`:``}${e}.${t?`asc`:`desc`}${n===void 0?``:n?`.nullsfirst`:`.nullslast`}`),this}limit(e,{foreignTable:t,referencedTable:n=t}={}){let r=n===void 0?`limit`:`${n}.limit`;return this.url.searchParams.set(r,`${e}`),this}range(e,t,{foreignTable:n,referencedTable:r=n}={}){let i=r===void 0?`offset`:`${r}.offset`,a=r===void 0?`limit`:`${r}.limit`;return this.url.searchParams.set(i,`${e}`),this.url.searchParams.set(a,`${t-e+1}`),this}abortSignal(e){return this.signal=e,this}single(){return this.headers.set(`Accept`,`application/vnd.pgrst.object+json`),this}maybeSingle(){return this.isMaybeSingle=!0,this}csv(){return this.headers.set(`Accept`,`text/csv`),this}geojson(){return this.headers.set(`Accept`,`application/geo+json`),this}explain({analyze:e=!1,verbose:t=!1,settings:n=!1,buffers:r=!1,wal:i=!1,format:a=`text`}={}){let o=[e?`analyze`:null,t?`verbose`:null,n?`settings`:null,r?`buffers`:null,i?`wal`:null].filter(Boolean).join(`|`),s=this.headers.get(`Accept`)??`application/json`;return this.headers.set(`Accept`,`application/vnd.pgrst.plan+${a}; for="${s}"; options=${o};`),this}rollback(){return this.headers.append(`Prefer`,`tx=rollback`),this}returns(){return this}maxAffected(e){return this.headers.append(`Prefer`,`handling=strict`),this.headers.append(`Prefer`,`max-affected=${e}`),this}},p=RegExp(`[,()]`),m=class extends f{eq(e,t){return this.url.searchParams.append(e,`eq.${t}`),this}neq(e,t){return this.url.searchParams.append(e,`neq.${t}`),this}gt(e,t){return this.url.searchParams.append(e,`gt.${t}`),this}gte(e,t){return this.url.searchParams.append(e,`gte.${t}`),this}lt(e,t){return this.url.searchParams.append(e,`lt.${t}`),this}lte(e,t){return this.url.searchParams.append(e,`lte.${t}`),this}like(e,t){return this.url.searchParams.append(e,`like.${t}`),this}likeAllOf(e,t){return this.url.searchParams.append(e,`like(all).{${t.join(`,`)}}`),this}likeAnyOf(e,t){return this.url.searchParams.append(e,`like(any).{${t.join(`,`)}}`),this}ilike(e,t){return this.url.searchParams.append(e,`ilike.${t}`),this}ilikeAllOf(e,t){return this.url.searchParams.append(e,`ilike(all).{${t.join(`,`)}}`),this}ilikeAnyOf(e,t){return this.url.searchParams.append(e,`ilike(any).{${t.join(`,`)}}`),this}regexMatch(e,t){return this.url.searchParams.append(e,`match.${t}`),this}regexIMatch(e,t){return this.url.searchParams.append(e,`imatch.${t}`),this}is(e,t){return this.url.searchParams.append(e,`is.${t}`),this}isDistinct(e,t){return this.url.searchParams.append(e,`isdistinct.${t}`),this}in(e,t){let n=Array.from(new Set(t)).map(e=>typeof e==`string`&&p.test(e)?`"${e}"`:`${e}`).join(`,`);return this.url.searchParams.append(e,`in.(${n})`),this}notIn(e,t){let n=Array.from(new Set(t)).map(e=>typeof e==`string`&&p.test(e)?`"${e}"`:`${e}`).join(`,`);return this.url.searchParams.append(e,`not.in.(${n})`),this}contains(e,t){return typeof t==`string`?this.url.searchParams.append(e,`cs.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cs.{${t.join(`,`)}}`):this.url.searchParams.append(e,`cs.${JSON.stringify(t)}`),this}containedBy(e,t){return typeof t==`string`?this.url.searchParams.append(e,`cd.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cd.{${t.join(`,`)}}`):this.url.searchParams.append(e,`cd.${JSON.stringify(t)}`),this}rangeGt(e,t){return this.url.searchParams.append(e,`sr.${t}`),this}rangeGte(e,t){return this.url.searchParams.append(e,`nxl.${t}`),this}rangeLt(e,t){return this.url.searchParams.append(e,`sl.${t}`),this}rangeLte(e,t){return this.url.searchParams.append(e,`nxr.${t}`),this}rangeAdjacent(e,t){return this.url.searchParams.append(e,`adj.${t}`),this}overlaps(e,t){return typeof t==`string`?this.url.searchParams.append(e,`ov.${t}`):this.url.searchParams.append(e,`ov.{${t.join(`,`)}}`),this}textSearch(e,t,{config:n,type:r}={}){let i=``;r===`plain`?i=`pl`:r===`phrase`?i=`ph`:r===`websearch`&&(i=`w`);let a=n===void 0?``:`(${n})`;return this.url.searchParams.append(e,`${i}fts${a}.${t}`),this}match(e){return Object.entries(e).filter(([e,t])=>t!==void 0).forEach(([e,t])=>{this.url.searchParams.append(e,`eq.${t}`)}),this}not(e,t,n){return this.url.searchParams.append(e,`not.${t}.${n}`),this}or(e,{foreignTable:t,referencedTable:n=t}={}){let r=n?`${n}.or`:`or`;return this.url.searchParams.append(r,`(${e})`),this}filter(e,t,n){return this.url.searchParams.append(e,`${t}.${n}`),this}},h=class{constructor(e,{headers:t={},schema:n,fetch:r,urlLengthLimit:i=8e3,retry:a}){this.url=e,this.headers=new Headers(t),this.schema=n,this.fetch=r,this.urlLengthLimit=i,this.retry=a}cloneRequestState(){return{url:new URL(this.url.toString()),headers:new Headers(this.headers)}}select(e,t){let{head:n=!1,count:r}=t??{},i=n?`HEAD`:`GET`,a=!1,o=(e??`*`).split(``).map(e=>/\s/.test(e)&&!a?``:(e===`"`&&(a=!a),e)).join(``),{url:s,headers:c}=this.cloneRequestState();return s.searchParams.set(`select`,o),r&&c.append(`Prefer`,`count=${r}`),new m({method:i,url:s,headers:c,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}insert(e,{count:t,defaultToNull:n=!0}={}){let{url:r,headers:i}=this.cloneRequestState();if(t&&i.append(`Prefer`,`count=${t}`),n||i.append(`Prefer`,`missing=default`),Array.isArray(e)){let t=e.reduce((e,t)=>e.concat(Object.keys(t)),[]);if(t.length>0){let e=[...new Set(t)].map(e=>`"${e}"`);r.searchParams.set(`columns`,e.join(`,`))}}return new m({method:`POST`,url:r,headers:i,schema:this.schema,body:e,fetch:this.fetch??fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}upsert(e,{onConflict:t,ignoreDuplicates:n=!1,count:r,defaultToNull:i=!0}={}){let{url:a,headers:o}=this.cloneRequestState();if(o.append(`Prefer`,`resolution=${n?`ignore`:`merge`}-duplicates`),t!==void 0&&a.searchParams.set(`on_conflict`,t),r&&o.append(`Prefer`,`count=${r}`),i||o.append(`Prefer`,`missing=default`),Array.isArray(e)){let t=e.reduce((e,t)=>e.concat(Object.keys(t)),[]);if(t.length>0){let e=[...new Set(t)].map(e=>`"${e}"`);a.searchParams.set(`columns`,e.join(`,`))}}return new m({method:`POST`,url:a,headers:o,schema:this.schema,body:e,fetch:this.fetch??fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}update(e,{count:t}={}){let{url:n,headers:r}=this.cloneRequestState();return t&&r.append(`Prefer`,`count=${t}`),new m({method:`PATCH`,url:n,headers:r,schema:this.schema,body:e,fetch:this.fetch??fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}delete({count:e}={}){let{url:t,headers:n}=this.cloneRequestState();return e&&n.append(`Prefer`,`count=${e}`),new m({method:`DELETE`,url:t,headers:n,schema:this.schema,fetch:this.fetch??fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}};function g(e){"@babel/helpers - typeof";return g=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},g(e)}function _(e,t){if(g(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(g(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function v(e){var t=_(e,`string`);return g(t)==`symbol`?t:t+``}function y(e,t,n){return(t=v(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function b(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function x(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?b(Object(n),!0).forEach(function(t){y(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):b(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}var S=class e{constructor(e,{headers:t={},schema:n,fetch:r,timeout:i,urlLengthLimit:a=8e3,retry:o}={}){this.url=e,this.headers=new Headers(t),this.schemaName=n,this.urlLengthLimit=a;let s=r??globalThis.fetch;i!==void 0&&i>0?this.fetch=(e,t)=>{let n=new AbortController,r=setTimeout(()=>n.abort(),i),a=t?.signal;if(a){if(a.aborted)return clearTimeout(r),s(e,t);let i=()=>{clearTimeout(r),n.abort()};return a.addEventListener(`abort`,i,{once:!0}),s(e,x(x({},t),{},{signal:n.signal})).finally(()=>{clearTimeout(r),a.removeEventListener(`abort`,i)})}return s(e,x(x({},t),{},{signal:n.signal})).finally(()=>clearTimeout(r))}:this.fetch=s,this.retry=o}from(e){if(!e||typeof e!=`string`||e.trim()===``)throw Error(`Invalid relation name: relation must be a non-empty string.`);return new h(new URL(`${this.url}/${e}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}schema(t){return new e(this.url,{headers:this.headers,schema:t,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}rpc(e,t={},{head:n=!1,get:r=!1,count:i}={}){let a,o=new URL(`${this.url}/rpc/${e}`),s,c=e=>typeof e==`object`&&!!e&&(!Array.isArray(e)||e.some(c)),l=n&&Object.values(t).some(c);l?(a=`POST`,s=t):n||r?(a=n?`HEAD`:`GET`,Object.entries(t).filter(([e,t])=>t!==void 0).map(([e,t])=>[e,Array.isArray(t)?`{${t.join(`,`)}}`:`${t}`]).forEach(([e,t])=>{o.searchParams.append(e,t)})):(a=`POST`,s=t);let u=new Headers(this.headers);return l?u.set(`Prefer`,i?`count=${i},return=minimal`:`return=minimal`):i&&u.set(`Prefer`,`count=${i}`),new m({method:a,url:o,headers:u,schema:this.schemaName,body:s,fetch:this.fetch??fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}},C=class{pluginId;port=null;queryParams={};supabase=null;rimoriInfo=null;isMessageChannelReady=!1;pendingRequests=[];updateCallbacks=new Set;constructor(e,t){this.pluginId=e,this.getClient=this.getClient.bind(this),!t&&this.initMessageChannel(typeof WorkerGlobalScope<`u`)}initMessageChannel(e=!1){let t=e=>{let{type:t,pluginId:r,queryParams:i,rimoriInfo:a}=e.data||{},[o]=e.ports||[];t!==`rimori:init`||!o||r!==this.pluginId||(this.queryParams=i||{},this.port=o,a&&(this.rimoriInfo=a,this.supabase=this.getSupabase(a.url,a.key,a.token)),this.port.onmessage=({data:e})=>{let{event:t,type:r,eventId:i,response:a,error:o}=e||{};if(r===`response`&&i)n.emit(this.pluginId,a.topic,a.data,i);else if(r===`error`&&i)n.emit(this.pluginId,`error`,{error:o},i);else if(t){let{topic:e,sender:r,data:i,eventId:a,ai_session_token:o}=t;r!==this.pluginId&&n.emit(r,e,i,a,o)}},n.on(`*`,e=>{e.sender===this.pluginId&&!e.topic.startsWith(`self.`)&&this.port?.postMessage({event:e})}),n.on(`${this.pluginId}.supabase.triggerUpdate`,e=>{this.handleRimoriInfoUpdate(e.data)}),this.isMessageChannelReady=!0,this.pendingRequests.forEach(e=>e()),this.pendingRequests=[])};e?self.onmessage=t:window.addEventListener(`message`,t),this.sendHello(e),n.on(`self.rimori.triggerInitFinished`,()=>{this.sendFinishedInit(e)})}sendHello(e=!1){try{let t={type:`rimori:hello`,pluginId:this.pluginId};e?self.postMessage(t):window.parent.postMessage(t,`*`)}catch(e){console.error(`[PluginController] Error sending hello:`,e)}}sendFinishedInit(e=!1){try{let t={type:`rimori:acknowledged`,pluginId:this.pluginId};e?self.postMessage(t):window.parent.postMessage(t,`*`)}catch(e){console.error(`[PluginController] Error sending finished init:`,e)}}getQueryParam(e){return this.queryParams[e]||null}getSupabase(e,t,n){return new S(`${e}/rest/v1`,{schema:this.rimoriInfo?.dbSchema,headers:{apikey:t,Authorization:`Bearer ${n}`,"plugin-id":this.pluginId}})}async getClient(){if(this.supabase&&this.rimoriInfo&&this.rimoriInfo.expiration>new Date)return{supabase:this.supabase,info:this.rimoriInfo};if(!this.isMessageChannelReady)return new Promise(e=>{this.pendingRequests.push(async()=>{e(await this.getClient())})});if(this.rimoriInfo&&this.supabase)return{supabase:this.supabase,info:this.rimoriInfo};if(!this.rimoriInfo)if(typeof WorkerGlobalScope<`u`){let e=Math.floor(Math.random()*1e9),t={event:{timestamp:new Date().toISOString(),eventId:e,sender:this.pluginId,topic:`global.supabase.requestAccess`,data:{},debug:!1}};return new Promise(n=>{let r=self.onmessage;self.onmessage=t=>{t.data?.topic===`global.supabase.requestAccess`&&t.data?.eventId===e?(this.rimoriInfo=t.data.data,this.supabase=this.getSupabase(this.rimoriInfo.url,this.rimoriInfo.key,this.rimoriInfo.token),self.onmessage=r,n({supabase:this.supabase,info:this.rimoriInfo})):r&&r.call(self,t)},self.postMessage(t)})}else{let{data:e}=await n.request(this.pluginId,`global.supabase.requestAccess`);this.rimoriInfo=e,this.supabase=this.getSupabase(this.rimoriInfo.url,this.rimoriInfo.key,this.rimoriInfo.token)}return{supabase:this.supabase,info:this.rimoriInfo}}handleRimoriInfoUpdate(e){JSON.stringify(this.rimoriInfo)!==JSON.stringify(e)&&(this.rimoriInfo=e,this.supabase=this.getSupabase(e.url,e.key,e.token),this.updateCallbacks.forEach(t=>{try{t(e)}catch(e){console.error(`[RimoriCommunicationHandler] Error in update callback:`,e)}}))}onUpdate(e){return this.updateCallbacks.add(e),()=>{this.updateCallbacks.delete(e)}}fetchBackend(e,t={}){if(!this.rimoriInfo)throw Error(`[CommunicationHandler:${this.pluginId}] fetchBackend called before rimoriInfo was initialized`);let{token:n,backendUrl:r}=this.rimoriInfo,i={};typeof t.body==`string`&&(i[`Content-Type`]=`application/json`);let a={...i,...t.headers,Authorization:`Bearer ${n}`,"plugin-id":this.pluginId};return fetch(r+e,{...t,headers:a})}},w=class e{static instance;isProduction;logs=[];logIdCounter=0;originalConsole;constructor(e,t){this.isProduction=this.validateIsProduction(t),this.originalConsole={log:console.log,info:console.info,warn:console.warn,error:console.error,debug:console.debug},this.overrideConsoleMethods(),this.exposeToDevTools(),this.setupNavigationClearing(),e.event.respond(`logging.requestPluginLogs`,async()=>{this.addLogEntry(await this.createLogEntry(`info`,`Log capture`));let t={logs:this.logs,pluginId:e.plugin.pluginId,timestamp:new Date().toISOString()};return this.logs=[],this.logIdCounter=0,t})}static getInstance(t,n){return e.instance||=new e(t,n),e.instance}validateIsProduction(e){return e===void 0?typeof window<`u`&&window.location.href?!window.location.href.includes(`localhost`):!0:e}exposeToDevTools(){typeof window<`u`&&(window.getRimoriLogs=()=>this.logs)}setupNavigationClearing(){if(typeof window>`u`||typeof history>`u`)return;window.addEventListener(`popstate`,()=>this.logs=[]);let e=history.pushState,t=history.replaceState;history.pushState=(...t)=>{e.apply(history,t),this.logs=[]},history.replaceState=(...e)=>{t.apply(history,e),this.logs=[]};let n=window.location.href;setInterval(()=>{window.location.href!==n&&(n=window.location.href,this.logs=[])},100),window.addEventListener(`hashchange`,()=>this.logs=[])}overrideConsoleMethods(){console.log=(...e)=>{let{location:t,style:n}=this.getCallerLocation();this.originalConsole.log(t,n,...e),this.handleConsoleCall(`info`,e)},console.info=(...e)=>{let{location:t,style:n}=this.getCallerLocation();this.originalConsole.info(t,n,...e),this.handleConsoleCall(`info`,e)},console.warn=(...e)=>{let{location:t,style:n}=this.getCallerLocation();this.originalConsole.warn(t,n,...e),this.handleConsoleCall(`warn`,e)},console.error=(...e)=>{let{location:t,style:n}=this.getCallerLocation();this.originalConsole.error(t,n,...e),this.handleConsoleCall(`error`,e)},console.debug=(...e)=>{let{location:t,style:n}=this.getCallerLocation();this.originalConsole.debug(t,n,...e),this.handleConsoleCall(`debug`,e)}}getCallerLocation(){let e={location:``,style:``},t=`color: #0063A2; font-weight: bold;`;if(this.isProduction)return e;try{let n=Error().stack;if(!n)return e;let r=n.split(`
2
- `)[3];if(!r)return e;let i=r.match(/(?:at\s+.*?\s+\()?([^/\\(]+\.(?:ts|tsx|js|jsx)):(\d+):(\d+)\)?/);if(i){let[,e,n]=i;return{style:t,location:`%c[${e}:${n}]`}}let a=r.match(/([^/\\]+\.(?:ts|tsx|js|jsx))/);return a?{style:t,location:`%c[${a[1]}]`}:e}catch{return e}}async handleConsoleCall(e,t){if(this.isProduction&&(e===`debug`||e===`info`))return;let n=t.map(e=>{if(typeof e!=`object`)return e;try{return JSON.stringify(e)}catch(t){return`Error adding object to log: `+t.message+` `+String(e)}}).join(` `),r=t.length>1?t.slice(1):void 0,i=await this.createLogEntry(e,n,r);this.addLogEntry(i)}getBrowserInfo(){return{userAgent:navigator.userAgent,language:navigator.language,cookieEnabled:navigator.cookieEnabled,onLine:navigator.onLine,screenResolution:`${screen.width}x${screen.height}`,windowSize:`${window.innerWidth}x${window.innerHeight}`,timestamp:new Date().toISOString()}}async createLogEntry(e,t,n){let r={};return typeof window>`u`||typeof document>`u`?{id:`log_${++this.logIdCounter}_${Date.now()}`,timestamp:new Date().toISOString(),level:e,message:t,data:n}:(r.url=window.location.href,r.browserInfo=this.getBrowserInfo(),r.userAgent=r.browserInfo.userAgent,{id:`log_${++this.logIdCounter}_${Date.now()}`,timestamp:new Date().toISOString(),level:e,message:t,data:n,context:r})}addLogEntry(e){this.logs.push(e),this.logs.length>1e3&&(this.logs=this.logs.slice(-1e3))}},T=e=>typeof e==`string`,E=()=>{let e,t,n=new Promise((n,r)=>{e=n,t=r});return n.resolve=e,n.reject=t,n},D=e=>e==null?``:``+e,O=(e,t,n)=>{e.forEach(e=>{t[e]&&(n[e]=t[e])})},k=/###/g,ee=e=>e&&e.indexOf(`###`)>-1?e.replace(k,`.`):e,te=e=>!e||T(e),A=(e,t,n)=>{let r=T(t)?t.split(`.`):t,i=0;for(;i<r.length-1;){if(te(e))return{};let t=ee(r[i]);!e[t]&&n&&(e[t]=new n),e=Object.prototype.hasOwnProperty.call(e,t)?e[t]:{},++i}return te(e)?{}:{obj:e,k:ee(r[i])}},j=(e,t,n)=>{let{obj:r,k:i}=A(e,t,Object);if(r!==void 0||t.length===1){r[i]=n;return}let a=t[t.length-1],o=t.slice(0,t.length-1),s=A(e,o,Object);for(;s.obj===void 0&&o.length;)a=`${o[o.length-1]}.${a}`,o=o.slice(0,o.length-1),s=A(e,o,Object),s?.obj&&s.obj[`${s.k}.${a}`]!==void 0&&(s.obj=void 0);s.obj[`${s.k}.${a}`]=n},ne=(e,t,n,r)=>{let{obj:i,k:a}=A(e,t,Object);i[a]=i[a]||[],i[a].push(n)},M=(e,t)=>{let{obj:n,k:r}=A(e,t);if(n&&Object.prototype.hasOwnProperty.call(n,r))return n[r]},re=(e,t,n)=>{let r=M(e,n);return r===void 0?M(t,n):r},ie=(e,t,n)=>{for(let r in t)r!==`__proto__`&&r!==`constructor`&&(r in e?T(e[r])||e[r]instanceof String||T(t[r])||t[r]instanceof String?n&&(e[r]=t[r]):ie(e[r],t[r],n):e[r]=t[r]);return e},N=e=>e.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,`\\$&`),ae={"&":`&amp;`,"<":`&lt;`,">":`&gt;`,'"':`&quot;`,"'":`&#39;`,"/":`&#x2F;`},oe=e=>T(e)?e.replace(/[&<>"'\/]/g,e=>ae[e]):e,se=class{constructor(e){this.capacity=e,this.regExpMap=new Map,this.regExpQueue=[]}getRegExp(e){let t=this.regExpMap.get(e);if(t!==void 0)return t;let n=new RegExp(e);return this.regExpQueue.length===this.capacity&&this.regExpMap.delete(this.regExpQueue.shift()),this.regExpMap.set(e,n),this.regExpQueue.push(e),n}},ce=[` `,`,`,`?`,`!`,`;`],le=new se(20),ue=(e,t,n)=>{t||=``,n||=``;let r=ce.filter(e=>t.indexOf(e)<0&&n.indexOf(e)<0);if(r.length===0)return!0;let i=le.getRegExp(`(${r.map(e=>e===`?`?`\\?`:e).join(`|`)})`),a=!i.test(e);if(!a){let t=e.indexOf(n);t>0&&!i.test(e.substring(0,t))&&(a=!0)}return a},P=(e,t,n=`.`)=>{if(!e)return;if(e[t])return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0;let r=t.split(n),i=e;for(let e=0;e<r.length;){if(!i||typeof i!=`object`)return;let t,a=``;for(let o=e;o<r.length;++o)if(o!==e&&(a+=n),a+=r[o],t=i[a],t!==void 0){if([`string`,`number`,`boolean`].indexOf(typeof t)>-1&&o<r.length-1)continue;e+=o-e+1;break}i=t}return i},F=e=>e?.replace(/_/g,`-`),de={type:`logger`,log(e){this.output(`log`,e)},warn(e){this.output(`warn`,e)},error(e){this.output(`error`,e)},output(e,t){console?.[e]?.apply?.(console,t)}},I=new class e{constructor(e,t={}){this.init(e,t)}init(e,t={}){this.prefix=t.prefix||`i18next:`,this.logger=e||de,this.options=t,this.debug=t.debug}log(...e){return this.forward(e,`log`,``,!0)}warn(...e){return this.forward(e,`warn`,``,!0)}error(...e){return this.forward(e,`error`,``)}deprecate(...e){return this.forward(e,`warn`,`WARNING DEPRECATED: `,!0)}forward(e,t,n,r){return r&&!this.debug?null:(T(e[0])&&(e[0]=`${n}${this.prefix} ${e[0]}`),this.logger[t](e))}create(t){return new e(this.logger,{prefix:`${this.prefix}:${t}:`,...this.options})}clone(t){return t||=this.options,t.prefix=t.prefix||this.prefix,new e(this.logger,t)}},L=class{constructor(){this.observers={}}on(e,t){return e.split(` `).forEach(e=>{this.observers[e]||(this.observers[e]=new Map);let n=this.observers[e].get(t)||0;this.observers[e].set(t,n+1)}),this}off(e,t){if(this.observers[e]){if(!t){delete this.observers[e];return}this.observers[e].delete(t)}}emit(e,...t){this.observers[e]&&Array.from(this.observers[e].entries()).forEach(([e,n])=>{for(let r=0;r<n;r++)e(...t)}),this.observers[`*`]&&Array.from(this.observers[`*`].entries()).forEach(([n,r])=>{for(let i=0;i<r;i++)n.apply(n,[e,...t])})}},R=class extends L{constructor(e,t={ns:[`translation`],defaultNS:`translation`}){super(),this.data=e||{},this.options=t,this.options.keySeparator===void 0&&(this.options.keySeparator=`.`),this.options.ignoreJSONStructure===void 0&&(this.options.ignoreJSONStructure=!0)}addNamespaces(e){this.options.ns.indexOf(e)<0&&this.options.ns.push(e)}removeNamespaces(e){let t=this.options.ns.indexOf(e);t>-1&&this.options.ns.splice(t,1)}getResource(e,t,n,r={}){let i=r.keySeparator===void 0?this.options.keySeparator:r.keySeparator,a=r.ignoreJSONStructure===void 0?this.options.ignoreJSONStructure:r.ignoreJSONStructure,o;e.indexOf(`.`)>-1?o=e.split(`.`):(o=[e,t],n&&(Array.isArray(n)?o.push(...n):T(n)&&i?o.push(...n.split(i)):o.push(n)));let s=M(this.data,o);return!s&&!t&&!n&&e.indexOf(`.`)>-1&&(e=o[0],t=o[1],n=o.slice(2).join(`.`)),s||!a||!T(n)?s:P(this.data?.[e]?.[t],n,i)}addResource(e,t,n,r,i={silent:!1}){let a=i.keySeparator===void 0?this.options.keySeparator:i.keySeparator,o=[e,t];n&&(o=o.concat(a?n.split(a):n)),e.indexOf(`.`)>-1&&(o=e.split(`.`),r=t,t=o[1]),this.addNamespaces(t),j(this.data,o,r),i.silent||this.emit(`added`,e,t,n,r)}addResources(e,t,n,r={silent:!1}){for(let r in n)(T(n[r])||Array.isArray(n[r]))&&this.addResource(e,t,r,n[r],{silent:!0});r.silent||this.emit(`added`,e,t,n)}addResourceBundle(e,t,n,r,i,a={silent:!1,skipCopy:!1}){let o=[e,t];e.indexOf(`.`)>-1&&(o=e.split(`.`),r=n,n=t,t=o[1]),this.addNamespaces(t);let s=M(this.data,o)||{};a.skipCopy||(n=JSON.parse(JSON.stringify(n))),r?ie(s,n,i):s={...s,...n},j(this.data,o,s),a.silent||this.emit(`added`,e,t,n)}removeResourceBundle(e,t){this.hasResourceBundle(e,t)&&delete this.data[e][t],this.removeNamespaces(t),this.emit(`removed`,e,t)}hasResourceBundle(e,t){return this.getResource(e,t)!==void 0}getResourceBundle(e,t){return t||=this.options.defaultNS,this.getResource(e,t)}getDataByLanguage(e){return this.data[e]}hasLanguageSomeTranslations(e){let t=this.getDataByLanguage(e);return!!(t&&Object.keys(t)||[]).find(e=>t[e]&&Object.keys(t[e]).length>0)}toJSON(){return this.data}},z={processors:{},addPostProcessor(e){this.processors[e.name]=e},handle(e,t,n,r,i){return e.forEach(e=>{t=this.processors[e]?.process(t,n,r,i)??t}),t}},B=Symbol(`i18next/PATH_KEY`);function fe(){let e=[],t=Object.create(null),n;return t.get=(r,i)=>(n?.revoke?.(),i===B?e:(e.push(i),n=Proxy.revocable(r,t),n.proxy)),Proxy.revocable(Object.create(null),t).proxy}function V(e,t){let{[B]:n}=e(fe()),r=t?.keySeparator??`.`,i=t?.nsSeparator??`:`;if(n.length>1&&i){let e=t?.ns,a=Array.isArray(e)?e:null;if(a&&a.length>1&&a.slice(1).includes(n[0]))return`${n[0]}${i}${n.slice(1).join(r)}`}return n.join(r)}var H={},U=e=>!T(e)&&typeof e!=`boolean`&&typeof e!=`number`,W=class e extends L{constructor(e,t={}){super(),O([`resourceStore`,`languageUtils`,`pluralResolver`,`interpolator`,`backendConnector`,`i18nFormat`,`utils`],e,this),this.options=t,this.options.keySeparator===void 0&&(this.options.keySeparator=`.`),this.logger=I.create(`translator`)}changeLanguage(e){e&&(this.language=e)}exists(e,t={interpolation:{}}){let n={...t};if(e==null)return!1;let r=this.resolve(e,n);if(r?.res===void 0)return!1;let i=U(r.res);return!(n.returnObjects===!1&&i)}extractFromKey(e,t){let n=t.nsSeparator===void 0?this.options.nsSeparator:t.nsSeparator;n===void 0&&(n=`:`);let r=t.keySeparator===void 0?this.options.keySeparator:t.keySeparator,i=t.ns||this.options.defaultNS||[],a=n&&e.indexOf(n)>-1,o=!this.options.userDefinedKeySeparator&&!t.keySeparator&&!this.options.userDefinedNsSeparator&&!t.nsSeparator&&!ue(e,n,r);if(a&&!o){let t=e.match(this.interpolator.nestingRegexp);if(t&&t.length>0)return{key:e,namespaces:T(i)?[i]:i};let a=e.split(n);(n!==r||n===r&&this.options.ns.indexOf(a[0])>-1)&&(i=a.shift()),e=a.join(r)}return{key:e,namespaces:T(i)?[i]:i}}translate(t,n,r){let i=typeof n==`object`?{...n}:n;if(typeof i!=`object`&&this.options.overloadTranslationOptionHandler&&(i=this.options.overloadTranslationOptionHandler(arguments)),typeof i==`object`&&(i={...i}),i||={},t==null)return``;typeof t==`function`&&(t=V(t,{...this.options,...i})),Array.isArray(t)||(t=[String(t)]),t=t.map(e=>typeof e==`function`?V(e,{...this.options,...i}):String(e));let a=i.returnDetails===void 0?this.options.returnDetails:i.returnDetails,o=i.keySeparator===void 0?this.options.keySeparator:i.keySeparator,{key:s,namespaces:c}=this.extractFromKey(t[t.length-1],i),l=c[c.length-1],u=i.nsSeparator===void 0?this.options.nsSeparator:i.nsSeparator;u===void 0&&(u=`:`);let d=i.lng||this.language,f=i.appendNamespaceToCIMode||this.options.appendNamespaceToCIMode;if(d?.toLowerCase()===`cimode`)return f?a?{res:`${l}${u}${s}`,usedKey:s,exactUsedKey:s,usedLng:d,usedNS:l,usedParams:this.getUsedParamsDetails(i)}:`${l}${u}${s}`:a?{res:s,usedKey:s,exactUsedKey:s,usedLng:d,usedNS:l,usedParams:this.getUsedParamsDetails(i)}:s;let p=this.resolve(t,i),m=p?.res,h=p?.usedKey||s,g=p?.exactUsedKey||s,_=[`[object Number]`,`[object Function]`,`[object RegExp]`],v=i.joinArrays===void 0?this.options.joinArrays:i.joinArrays,y=!this.i18nFormat||this.i18nFormat.handleAsObject,b=i.count!==void 0&&!T(i.count),x=e.hasDefaultValue(i),S=b?this.pluralResolver.getSuffix(d,i.count,i):``,C=i.ordinal&&b?this.pluralResolver.getSuffix(d,i.count,{ordinal:!1}):``,w=b&&!i.ordinal&&i.count===0,E=w&&i[`defaultValue${this.options.pluralSeparator}zero`]||i[`defaultValue${S}`]||i[`defaultValue${C}`]||i.defaultValue,D=m;y&&!m&&x&&(D=E);let O=U(D),k=Object.prototype.toString.apply(D);if(y&&D&&O&&_.indexOf(k)<0&&!(T(v)&&Array.isArray(D))){if(!i.returnObjects&&!this.options.returnObjects){this.options.returnedObjectHandler||this.logger.warn(`accessing an object - but returnObjects options is not enabled!`);let e=this.options.returnedObjectHandler?this.options.returnedObjectHandler(h,D,{...i,ns:c}):`key '${s} (${this.language})' returned an object instead of string.`;return a?(p.res=e,p.usedParams=this.getUsedParamsDetails(i),p):e}if(o){let e=Array.isArray(D),t=e?[]:{},n=e?g:h;for(let e in D)if(Object.prototype.hasOwnProperty.call(D,e)){let r=`${n}${o}${e}`;x&&!m?t[e]=this.translate(r,{...i,defaultValue:U(E)?E[e]:void 0,joinArrays:!1,ns:c}):t[e]=this.translate(r,{...i,joinArrays:!1,ns:c}),t[e]===r&&(t[e]=D[e])}m=t}}else if(y&&T(v)&&Array.isArray(m))m=m.join(v),m&&=this.extendTranslation(m,t,i,r);else{let e=!1,n=!1;!this.isValidLookup(m)&&x&&(e=!0,m=E),this.isValidLookup(m)||(n=!0,m=s);let a=(i.missingKeyNoValueFallbackToKey||this.options.missingKeyNoValueFallbackToKey)&&n?void 0:m,c=x&&E!==m&&this.options.updateMissing;if(n||e||c){if(this.logger.log(c?`updateKey`:`missingKey`,d,l,s,c?E:m),o){let e=this.resolve(s,{...i,keySeparator:!1});e&&e.res&&this.logger.warn(`Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format.`)}let e=[],t=this.languageUtils.getFallbackCodes(this.options.fallbackLng,i.lng||this.language);if(this.options.saveMissingTo===`fallback`&&t&&t[0])for(let n=0;n<t.length;n++)e.push(t[n]);else this.options.saveMissingTo===`all`?e=this.languageUtils.toResolveHierarchy(i.lng||this.language):e.push(i.lng||this.language);let n=(e,t,n)=>{let r=x&&n!==m?n:a;this.options.missingKeyHandler?this.options.missingKeyHandler(e,l,t,r,c,i):this.backendConnector?.saveMissing&&this.backendConnector.saveMissing(e,l,t,r,c,i),this.emit(`missingKey`,e,l,t,m)};this.options.saveMissing&&(this.options.saveMissingPlurals&&b?e.forEach(e=>{let t=this.pluralResolver.getSuffixes(e,i);w&&i[`defaultValue${this.options.pluralSeparator}zero`]&&t.indexOf(`${this.options.pluralSeparator}zero`)<0&&t.push(`${this.options.pluralSeparator}zero`),t.forEach(t=>{n([e],s+t,i[`defaultValue${t}`]||E)})}):n(e,s,E))}m=this.extendTranslation(m,t,i,p,r),n&&m===s&&this.options.appendNamespaceToMissingKey&&(m=`${l}${u}${s}`),(n||e)&&this.options.parseMissingKeyHandler&&(m=this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey?`${l}${u}${s}`:s,e?m:void 0,i))}return a?(p.res=m,p.usedParams=this.getUsedParamsDetails(i),p):m}extendTranslation(e,t,n,r,i){if(this.i18nFormat?.parse)e=this.i18nFormat.parse(e,{...this.options.interpolation.defaultVariables,...n},n.lng||this.language||r.usedLng,r.usedNS,r.usedKey,{resolved:r});else if(!n.skipInterpolation){n.interpolation&&this.interpolator.init({...n,interpolation:{...this.options.interpolation,...n.interpolation}});let a=T(e)&&(n?.interpolation?.skipOnVariables===void 0?this.options.interpolation.skipOnVariables:n.interpolation.skipOnVariables),o;if(a){let t=e.match(this.interpolator.nestingRegexp);o=t&&t.length}let s=n.replace&&!T(n.replace)?n.replace:n;if(this.options.interpolation.defaultVariables&&(s={...this.options.interpolation.defaultVariables,...s}),e=this.interpolator.interpolate(e,s,n.lng||this.language||r.usedLng,n),a){let t=e.match(this.interpolator.nestingRegexp),r=t&&t.length;o<r&&(n.nest=!1)}!n.lng&&r&&r.res&&(n.lng=this.language||r.usedLng),n.nest!==!1&&(e=this.interpolator.nest(e,(...e)=>i?.[0]===e[0]&&!n.context?(this.logger.warn(`It seems you are nesting recursively key: ${e[0]} in key: ${t[0]}`),null):this.translate(...e,t),n)),n.interpolation&&this.interpolator.reset()}let a=n.postProcess||this.options.postProcess,o=T(a)?[a]:a;return e!=null&&o?.length&&n.applyPostProcessor!==!1&&(e=z.handle(o,e,t,this.options&&this.options.postProcessPassResolved?{i18nResolved:{...r,usedParams:this.getUsedParamsDetails(n)},...n}:n,this)),e}resolve(e,t={}){let n,r,i,a,o;return T(e)&&(e=[e]),Array.isArray(e)&&(e=e.map(e=>typeof e==`function`?V(e,{...this.options,...t}):e)),e.forEach(e=>{if(this.isValidLookup(n))return;let s=this.extractFromKey(e,t),c=s.key;r=c;let l=s.namespaces;this.options.fallbackNS&&(l=l.concat(this.options.fallbackNS));let u=t.count!==void 0&&!T(t.count),d=u&&!t.ordinal&&t.count===0,f=t.context!==void 0&&(T(t.context)||typeof t.context==`number`)&&t.context!==``,p=t.lngs?t.lngs:this.languageUtils.toResolveHierarchy(t.lng||this.language,t.fallbackLng);l.forEach(e=>{this.isValidLookup(n)||(o=e,!H[`${p[0]}-${e}`]&&this.utils?.hasLoadedNamespace&&!this.utils?.hasLoadedNamespace(o)&&(H[`${p[0]}-${e}`]=!0,this.logger.warn(`key "${r}" for languages "${p.join(`, `)}" won't get resolved as namespace "${o}" was not yet loaded`,`This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!`)),p.forEach(r=>{if(this.isValidLookup(n))return;a=r;let o=[c];if(this.i18nFormat?.addLookupKeys)this.i18nFormat.addLookupKeys(o,c,r,e,t);else{let e;u&&(e=this.pluralResolver.getSuffix(r,t.count,t));let n=`${this.options.pluralSeparator}zero`,i=`${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;if(u&&(t.ordinal&&e.indexOf(i)===0&&o.push(c+e.replace(i,this.options.pluralSeparator)),o.push(c+e),d&&o.push(c+n)),f){let r=`${c}${this.options.contextSeparator||`_`}${t.context}`;o.push(r),u&&(t.ordinal&&e.indexOf(i)===0&&o.push(r+e.replace(i,this.options.pluralSeparator)),o.push(r+e),d&&o.push(r+n))}}let s;for(;s=o.pop();)this.isValidLookup(n)||(i=s,n=this.getResource(r,e,s,t))}))})}),{res:n,usedKey:r,exactUsedKey:i,usedLng:a,usedNS:o}}isValidLookup(e){return e!==void 0&&!(!this.options.returnNull&&e===null)&&!(!this.options.returnEmptyString&&e===``)}getResource(e,t,n,r={}){return this.i18nFormat?.getResource?this.i18nFormat.getResource(e,t,n,r):this.resourceStore.getResource(e,t,n,r)}getUsedParamsDetails(e={}){let t=[`defaultValue`,`ordinal`,`context`,`replace`,`lng`,`lngs`,`fallbackLng`,`ns`,`keySeparator`,`nsSeparator`,`returnObjects`,`returnDetails`,`joinArrays`,`postProcess`,`interpolation`],n=e.replace&&!T(e.replace),r=n?e.replace:e;if(n&&e.count!==void 0&&(r.count=e.count),this.options.interpolation.defaultVariables&&(r={...this.options.interpolation.defaultVariables,...r}),!n){r={...r};for(let e of t)delete r[e]}return r}static hasDefaultValue(e){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&t.substring(0,12)===`defaultValue`&&e[t]!==void 0)return!0;return!1}},G=class{constructor(e){this.options=e,this.supportedLngs=this.options.supportedLngs||!1,this.logger=I.create(`languageUtils`)}getScriptPartFromCode(e){if(e=F(e),!e||e.indexOf(`-`)<0)return null;let t=e.split(`-`);return t.length===2||(t.pop(),t[t.length-1].toLowerCase()===`x`)?null:this.formatLanguageCode(t.join(`-`))}getLanguagePartFromCode(e){if(e=F(e),!e||e.indexOf(`-`)<0)return e;let t=e.split(`-`);return this.formatLanguageCode(t[0])}formatLanguageCode(e){if(T(e)&&e.indexOf(`-`)>-1){let t;try{t=Intl.getCanonicalLocales(e)[0]}catch{}return t&&this.options.lowerCaseLng&&(t=t.toLowerCase()),t||(this.options.lowerCaseLng?e.toLowerCase():e)}return this.options.cleanCode||this.options.lowerCaseLng?e.toLowerCase():e}isSupportedCode(e){return(this.options.load===`languageOnly`||this.options.nonExplicitSupportedLngs)&&(e=this.getLanguagePartFromCode(e)),!this.supportedLngs||!this.supportedLngs.length||this.supportedLngs.indexOf(e)>-1}getBestMatchFromCodes(e){if(!e)return null;let t;return e.forEach(e=>{if(t)return;let n=this.formatLanguageCode(e);(!this.options.supportedLngs||this.isSupportedCode(n))&&(t=n)}),!t&&this.options.supportedLngs&&e.forEach(e=>{if(t)return;let n=this.getScriptPartFromCode(e);if(this.isSupportedCode(n))return t=n;let r=this.getLanguagePartFromCode(e);if(this.isSupportedCode(r))return t=r;t=this.options.supportedLngs.find(e=>{if(e===r||!(e.indexOf(`-`)<0&&r.indexOf(`-`)<0)&&(e.indexOf(`-`)>0&&r.indexOf(`-`)<0&&e.substring(0,e.indexOf(`-`))===r||e.indexOf(r)===0&&r.length>1))return e})}),t||=this.getFallbackCodes(this.options.fallbackLng)[0],t}getFallbackCodes(e,t){if(!e)return[];if(typeof e==`function`&&(e=e(t)),T(e)&&(e=[e]),Array.isArray(e))return e;if(!t)return e.default||[];let n=e[t];return n||=e[this.getScriptPartFromCode(t)],n||=e[this.formatLanguageCode(t)],n||=e[this.getLanguagePartFromCode(t)],n||=e.default,n||[]}toResolveHierarchy(e,t){let n=this.getFallbackCodes((t===!1?[]:t)||this.options.fallbackLng||[],e),r=[],i=e=>{e&&(this.isSupportedCode(e)?r.push(e):this.logger.warn(`rejecting language code not found in supportedLngs: ${e}`))};return T(e)&&(e.indexOf(`-`)>-1||e.indexOf(`_`)>-1)?(this.options.load!==`languageOnly`&&i(this.formatLanguageCode(e)),this.options.load!==`languageOnly`&&this.options.load!==`currentOnly`&&i(this.getScriptPartFromCode(e)),this.options.load!==`currentOnly`&&i(this.getLanguagePartFromCode(e))):T(e)&&i(this.formatLanguageCode(e)),n.forEach(e=>{r.indexOf(e)<0&&i(this.formatLanguageCode(e))}),r}},pe={zero:0,one:1,two:2,few:3,many:4,other:5},me={select:e=>e===1?`one`:`other`,resolvedOptions:()=>({pluralCategories:[`one`,`other`]})},he=class{constructor(e,t={}){this.languageUtils=e,this.options=t,this.logger=I.create(`pluralResolver`),this.pluralRulesCache={}}clearCache(){this.pluralRulesCache={}}getRule(e,t={}){let n=F(e===`dev`?`en`:e),r=t.ordinal?`ordinal`:`cardinal`,i=JSON.stringify({cleanedCode:n,type:r});if(i in this.pluralRulesCache)return this.pluralRulesCache[i];let a;try{a=new Intl.PluralRules(n,{type:r})}catch{if(typeof Intl>`u`)return this.logger.error(`No Intl support, please use an Intl polyfill!`),me;if(!e.match(/-|_/))return me;let n=this.languageUtils.getLanguagePartFromCode(e);a=this.getRule(n,t)}return this.pluralRulesCache[i]=a,a}needsPlural(e,t={}){let n=this.getRule(e,t);return n||=this.getRule(`dev`,t),n?.resolvedOptions().pluralCategories.length>1}getPluralFormsOfKey(e,t,n={}){return this.getSuffixes(e,n).map(e=>`${t}${e}`)}getSuffixes(e,t={}){let n=this.getRule(e,t);return n||=this.getRule(`dev`,t),n?n.resolvedOptions().pluralCategories.sort((e,t)=>pe[e]-pe[t]).map(e=>`${this.options.prepend}${t.ordinal?`ordinal${this.options.prepend}`:``}${e}`):[]}getSuffix(e,t,n={}){let r=this.getRule(e,n);return r?`${this.options.prepend}${n.ordinal?`ordinal${this.options.prepend}`:``}${r.select(t)}`:(this.logger.warn(`no plural rule found for: ${e}`),this.getSuffix(`dev`,t,n))}},ge=(e,t,n,r=`.`,i=!0)=>{let a=re(e,t,n);return!a&&i&&T(n)&&(a=P(e,n,r),a===void 0&&(a=P(t,n,r))),a},K=e=>e.replace(/\$/g,`$$$$`),_e=class{constructor(e={}){this.logger=I.create(`interpolator`),this.options=e,this.format=e?.interpolation?.format||(e=>e),this.init(e)}init(e={}){e.interpolation||={escapeValue:!0};let{escape:t,escapeValue:n,useRawValueToEscape:r,prefix:i,prefixEscaped:a,suffix:o,suffixEscaped:s,formatSeparator:c,unescapeSuffix:l,unescapePrefix:u,nestingPrefix:d,nestingPrefixEscaped:f,nestingSuffix:p,nestingSuffixEscaped:m,nestingOptionsSeparator:h,maxReplaces:g,alwaysFormat:_}=e.interpolation;this.escape=t===void 0?oe:t,this.escapeValue=n===void 0?!0:n,this.useRawValueToEscape=r===void 0?!1:r,this.prefix=i?N(i):a||`{{`,this.suffix=o?N(o):s||`}}`,this.formatSeparator=c||`,`,this.unescapePrefix=l?``:u||`-`,this.unescapeSuffix=this.unescapePrefix?``:l||``,this.nestingPrefix=d?N(d):f||N(`$t(`),this.nestingSuffix=p?N(p):m||N(`)`),this.nestingOptionsSeparator=h||`,`,this.maxReplaces=g||1e3,this.alwaysFormat=_===void 0?!1:_,this.resetRegExp()}reset(){this.options&&this.init(this.options)}resetRegExp(){let e=(e,t)=>e?.source===t?(e.lastIndex=0,e):new RegExp(t,`g`);this.regexp=e(this.regexp,`${this.prefix}(.+?)${this.suffix}`),this.regexpUnescape=e(this.regexpUnescape,`${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`),this.nestingRegexp=e(this.nestingRegexp,`${this.nestingPrefix}((?:[^()"']+|"[^"]*"|'[^']*'|\\((?:[^()]|"[^"]*"|'[^']*')*\\))*?)${this.nestingSuffix}`)}interpolate(e,t,n,r){let i,a,o,s=this.options&&this.options.interpolation&&this.options.interpolation.defaultVariables||{},c=e=>{if(e.indexOf(this.formatSeparator)<0){let i=ge(t,s,e,this.options.keySeparator,this.options.ignoreJSONStructure);return this.alwaysFormat?this.format(i,void 0,n,{...r,...t,interpolationkey:e}):i}let i=e.split(this.formatSeparator),a=i.shift().trim(),o=i.join(this.formatSeparator).trim();return this.format(ge(t,s,a,this.options.keySeparator,this.options.ignoreJSONStructure),o,n,{...r,...t,interpolationkey:a})};this.resetRegExp();let l=r?.missingInterpolationHandler||this.options.missingInterpolationHandler,u=r?.interpolation?.skipOnVariables===void 0?this.options.interpolation.skipOnVariables:r.interpolation.skipOnVariables;return[{regex:this.regexpUnescape,safeValue:e=>K(e)},{regex:this.regexp,safeValue:e=>this.escapeValue?K(this.escape(e)):K(e)}].forEach(t=>{for(o=0;i=t.regex.exec(e);){let n=i[1].trim();if(a=c(n),a===void 0)if(typeof l==`function`){let t=l(e,i,r);a=T(t)?t:``}else if(r&&Object.prototype.hasOwnProperty.call(r,n))a=``;else if(u){a=i[0];continue}else this.logger.warn(`missed to pass in variable ${n} for interpolating ${e}`),a=``;else !T(a)&&!this.useRawValueToEscape&&(a=D(a));let s=t.safeValue(a);if(e=e.replace(i[0],s),u?(t.regex.lastIndex+=a.length,t.regex.lastIndex-=i[0].length):t.regex.lastIndex=0,o++,o>=this.maxReplaces)break}}),e}nest(e,t,n={}){let r,i,a,o=(e,t)=>{let n=this.nestingOptionsSeparator;if(e.indexOf(n)<0)return e;let r=e.split(RegExp(`${N(n)}[ ]*{`)),i=`{${r[1]}`;e=r[0],i=this.interpolate(i,a);let o=i.match(/'/g),s=i.match(/"/g);((o?.length??0)%2==0&&!s||(s?.length??0)%2!=0)&&(i=i.replace(/'/g,`"`));try{a=JSON.parse(i),t&&(a={...t,...a})}catch(t){return this.logger.warn(`failed parsing options string in nesting for key ${e}`,t),`${e}${n}${i}`}return a.defaultValue&&a.defaultValue.indexOf(this.prefix)>-1&&delete a.defaultValue,e};for(;r=this.nestingRegexp.exec(e);){let s=[];a={...n},a=a.replace&&!T(a.replace)?a.replace:a,a.applyPostProcessor=!1,delete a.defaultValue;let c=/{.*}/.test(r[1])?r[1].lastIndexOf(`}`)+1:r[1].indexOf(this.formatSeparator);if(c!==-1&&(s=r[1].slice(c).split(this.formatSeparator).map(e=>e.trim()).filter(Boolean),r[1]=r[1].slice(0,c)),i=t(o.call(this,r[1].trim(),a),a),i&&r[0]===e&&!T(i))return i;T(i)||(i=D(i)),i||=(this.logger.warn(`missed to resolve ${r[1]} for nesting ${e}`),``),s.length&&(i=s.reduce((e,t)=>this.format(e,t,n.lng,{...n,interpolationkey:r[1].trim()}),i.trim())),e=e.replace(r[0],i),this.regexp.lastIndex=0}return e}},ve=e=>{let t=e.toLowerCase().trim(),n={};if(e.indexOf(`(`)>-1){let r=e.split(`(`);t=r[0].toLowerCase().trim();let i=r[1].substring(0,r[1].length-1);t===`currency`&&i.indexOf(`:`)<0?n.currency||=i.trim():t===`relativetime`&&i.indexOf(`:`)<0?n.range||=i.trim():i.split(`;`).forEach(e=>{if(e){let[t,...r]=e.split(`:`),i=r.join(`:`).trim().replace(/^'+|'+$/g,``),a=t.trim();n[a]||(n[a]=i),i===`false`&&(n[a]=!1),i===`true`&&(n[a]=!0),isNaN(i)||(n[a]=parseInt(i,10))}})}return{formatName:t,formatOptions:n}},ye=e=>{let t={};return(n,r,i)=>{let a=i;i&&i.interpolationkey&&i.formatParams&&i.formatParams[i.interpolationkey]&&i[i.interpolationkey]&&(a={...a,[i.interpolationkey]:void 0});let o=r+JSON.stringify(a),s=t[o];return s||(s=e(F(r),i),t[o]=s),s(n)}},be=e=>(t,n,r)=>e(F(n),r)(t),xe=class{constructor(e={}){this.logger=I.create(`formatter`),this.options=e,this.init(e)}init(e,t={interpolation:{}}){this.formatSeparator=t.interpolation.formatSeparator||`,`;let n=t.cacheInBuiltFormats?ye:be;this.formats={number:n((e,t)=>{let n=new Intl.NumberFormat(e,{...t});return e=>n.format(e)}),currency:n((e,t)=>{let n=new Intl.NumberFormat(e,{...t,style:`currency`});return e=>n.format(e)}),datetime:n((e,t)=>{let n=new Intl.DateTimeFormat(e,{...t});return e=>n.format(e)}),relativetime:n((e,t)=>{let n=new Intl.RelativeTimeFormat(e,{...t});return e=>n.format(e,t.range||`day`)}),list:n((e,t)=>{let n=new Intl.ListFormat(e,{...t});return e=>n.format(e)})}}add(e,t){this.formats[e.toLowerCase().trim()]=t}addCached(e,t){this.formats[e.toLowerCase().trim()]=ye(t)}format(e,t,n,r={}){let i=t.split(this.formatSeparator);if(i.length>1&&i[0].indexOf(`(`)>1&&i[0].indexOf(`)`)<0&&i.find(e=>e.indexOf(`)`)>-1)){let e=i.findIndex(e=>e.indexOf(`)`)>-1);i[0]=[i[0],...i.splice(1,e)].join(this.formatSeparator)}return i.reduce((e,t)=>{let{formatName:i,formatOptions:a}=ve(t);if(this.formats[i]){let t=e;try{let o=r?.formatParams?.[r.interpolationkey]||{},s=o.locale||o.lng||r.locale||r.lng||n;t=this.formats[i](e,s,{...a,...r,...o})}catch(e){this.logger.warn(e)}return t}else this.logger.warn(`there was no format function for ${i}`);return e},e)}},Se=(e,t)=>{e.pending[t]!==void 0&&(delete e.pending[t],e.pendingCount--)},Ce=class extends L{constructor(e,t,n,r={}){super(),this.backend=e,this.store=t,this.services=n,this.languageUtils=n.languageUtils,this.options=r,this.logger=I.create(`backendConnector`),this.waitingReads=[],this.maxParallelReads=r.maxParallelReads||10,this.readingCalls=0,this.maxRetries=r.maxRetries>=0?r.maxRetries:5,this.retryTimeout=r.retryTimeout>=1?r.retryTimeout:350,this.state={},this.queue=[],this.backend?.init?.(n,r.backend,r)}queueLoad(e,t,n,r){let i={},a={},o={},s={};return e.forEach(e=>{let r=!0;t.forEach(t=>{let o=`${e}|${t}`;!n.reload&&this.store.hasResourceBundle(e,t)?this.state[o]=2:this.state[o]<0||(this.state[o]===1?a[o]===void 0&&(a[o]=!0):(this.state[o]=1,r=!1,a[o]===void 0&&(a[o]=!0),i[o]===void 0&&(i[o]=!0),s[t]===void 0&&(s[t]=!0)))}),r||(o[e]=!0)}),(Object.keys(i).length||Object.keys(a).length)&&this.queue.push({pending:a,pendingCount:Object.keys(a).length,loaded:{},errors:[],callback:r}),{toLoad:Object.keys(i),pending:Object.keys(a),toLoadLanguages:Object.keys(o),toLoadNamespaces:Object.keys(s)}}loaded(e,t,n){let r=e.split(`|`),i=r[0],a=r[1];t&&this.emit(`failedLoading`,i,a,t),!t&&n&&this.store.addResourceBundle(i,a,n,void 0,void 0,{skipCopy:!0}),this.state[e]=t?-1:2,t&&n&&(this.state[e]=0);let o={};this.queue.forEach(n=>{ne(n.loaded,[i],a),Se(n,e),t&&n.errors.push(t),n.pendingCount===0&&!n.done&&(Object.keys(n.loaded).forEach(e=>{o[e]||(o[e]={});let t=n.loaded[e];t.length&&t.forEach(t=>{o[e][t]===void 0&&(o[e][t]=!0)})}),n.done=!0,n.errors.length?n.callback(n.errors):n.callback())}),this.emit(`loaded`,o),this.queue=this.queue.filter(e=>!e.done)}read(e,t,n,r=0,i=this.retryTimeout,a){if(!e.length)return a(null,{});if(this.readingCalls>=this.maxParallelReads){this.waitingReads.push({lng:e,ns:t,fcName:n,tried:r,wait:i,callback:a});return}this.readingCalls++;let o=(o,s)=>{if(this.readingCalls--,this.waitingReads.length>0){let e=this.waitingReads.shift();this.read(e.lng,e.ns,e.fcName,e.tried,e.wait,e.callback)}if(o&&s&&r<this.maxRetries){setTimeout(()=>{this.read.call(this,e,t,n,r+1,i*2,a)},i);return}a(o,s)},s=this.backend[n].bind(this.backend);if(s.length===2){try{let n=s(e,t);n&&typeof n.then==`function`?n.then(e=>o(null,e)).catch(o):o(null,n)}catch(e){o(e)}return}return s(e,t,o)}prepareLoading(e,t,n={},r){if(!this.backend)return this.logger.warn(`No backend was added via i18next.use. Will not load resources.`),r&&r();T(e)&&(e=this.languageUtils.toResolveHierarchy(e)),T(t)&&(t=[t]);let i=this.queueLoad(e,t,n,r);if(!i.toLoad.length)return i.pending.length||r(),null;i.toLoad.forEach(e=>{this.loadOne(e)})}load(e,t,n){this.prepareLoading(e,t,{},n)}reload(e,t,n){this.prepareLoading(e,t,{reload:!0},n)}loadOne(e,t=``){let n=e.split(`|`),r=n[0],i=n[1];this.read(r,i,`read`,void 0,void 0,(n,a)=>{n&&this.logger.warn(`${t}loading namespace ${i} for language ${r} failed`,n),!n&&a&&this.logger.log(`${t}loaded namespace ${i} for language ${r}`,a),this.loaded(e,n,a)})}saveMissing(e,t,n,r,i,a={},o=()=>{}){if(this.services?.utils?.hasLoadedNamespace&&!this.services?.utils?.hasLoadedNamespace(t)){this.logger.warn(`did not save key "${n}" as the namespace "${t}" was not yet loaded`,`This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!`);return}if(!(n==null||n===``)){if(this.backend?.create){let s={...a,isUpdate:i},c=this.backend.create.bind(this.backend);if(c.length<6)try{let i;i=c.length===5?c(e,t,n,r,s):c(e,t,n,r),i&&typeof i.then==`function`?i.then(e=>o(null,e)).catch(o):o(null,i)}catch(e){o(e)}else c(e,t,n,r,o,s)}!e||!e[0]||this.store.addResource(e[0],t,n,r)}}},q=()=>({debug:!1,initAsync:!0,ns:[`translation`],defaultNS:[`translation`],fallbackLng:[`dev`],fallbackNS:!1,supportedLngs:!1,nonExplicitSupportedLngs:!1,load:`all`,preload:!1,simplifyPluralSuffix:!0,keySeparator:`.`,nsSeparator:`:`,pluralSeparator:`_`,contextSeparator:`_`,partialBundledLanguages:!1,saveMissing:!1,updateMissing:!1,saveMissingTo:`fallback`,saveMissingPlurals:!0,missingKeyHandler:!1,missingInterpolationHandler:!1,postProcess:!1,postProcessPassResolved:!1,returnNull:!1,returnEmptyString:!0,returnObjects:!1,joinArrays:!1,returnedObjectHandler:!1,parseMissingKeyHandler:!1,appendNamespaceToMissingKey:!1,appendNamespaceToCIMode:!1,overloadTranslationOptionHandler:e=>{let t={};if(typeof e[1]==`object`&&(t=e[1]),T(e[1])&&(t.defaultValue=e[1]),T(e[2])&&(t.tDescription=e[2]),typeof e[2]==`object`||typeof e[3]==`object`){let n=e[3]||e[2];Object.keys(n).forEach(e=>{t[e]=n[e]})}return t},interpolation:{escapeValue:!0,format:e=>e,prefix:`{{`,suffix:`}}`,formatSeparator:`,`,unescapePrefix:`-`,nestingPrefix:`$t(`,nestingSuffix:`)`,nestingOptionsSeparator:`,`,maxReplaces:1e3,skipOnVariables:!0},cacheInBuiltFormats:!0}),we=e=>(T(e.ns)&&(e.ns=[e.ns]),T(e.fallbackLng)&&(e.fallbackLng=[e.fallbackLng]),T(e.fallbackNS)&&(e.fallbackNS=[e.fallbackNS]),e.supportedLngs?.indexOf?.(`cimode`)<0&&(e.supportedLngs=e.supportedLngs.concat([`cimode`])),typeof e.initImmediate==`boolean`&&(e.initAsync=e.initImmediate),e),J=()=>{},Te=e=>{Object.getOwnPropertyNames(Object.getPrototypeOf(e)).forEach(t=>{typeof e[t]==`function`&&(e[t]=e[t].bind(e))})},Ee=`__i18next_supportNoticeShown`,De=()=>!!(typeof globalThis<`u`&&globalThis[Ee]||typeof process<`u`&&{}.I18NEXT_NO_SUPPORT_NOTICE||typeof process<`u`),Oe=()=>{typeof globalThis<`u`&&(globalThis[Ee]=!0)},ke=e=>!!(e?.modules?.backend?.name?.indexOf(`Locize`)>0||e?.modules?.backend?.constructor?.name?.indexOf(`Locize`)>0||e?.options?.backend?.backends&&e.options.backend.backends.some(e=>e?.name?.indexOf(`Locize`)>0||e?.constructor?.name?.indexOf(`Locize`)>0)||e?.options?.backend?.projectId||e?.options?.backend?.backendOptions&&e.options.backend.backendOptions.some(e=>e?.projectId)),Y=class e extends L{constructor(e={},t){if(super(),this.options=we(e),this.services={},this.logger=I,this.modules={external:[]},Te(this),t&&!this.isInitialized&&!e.isClone){if(!this.options.initAsync)return this.init(e,t),this;setTimeout(()=>{this.init(e,t)},0)}}init(e={},t){this.isInitializing=!0,typeof e==`function`&&(t=e,e={}),e.defaultNS==null&&e.ns&&(T(e.ns)?e.defaultNS=e.ns:e.ns.indexOf(`translation`)<0&&(e.defaultNS=e.ns[0]));let n=q();this.options={...n,...this.options,...we(e)},this.options.interpolation={...n.interpolation,...this.options.interpolation},e.keySeparator!==void 0&&(this.options.userDefinedKeySeparator=e.keySeparator),e.nsSeparator!==void 0&&(this.options.userDefinedNsSeparator=e.nsSeparator),typeof this.options.overloadTranslationOptionHandler!=`function`&&(this.options.overloadTranslationOptionHandler=n.overloadTranslationOptionHandler),this.options.showSupportNotice!==!1&&!ke(this)&&!De()&&(typeof console<`u`&&console.info!==void 0&&console.info(`🌐 i18next is made possible by our own product, Locize — consider powering your project with managed localization (AI, CDN, integrations): https://locize.com 💙`),Oe());let r=e=>e?typeof e==`function`?new e:e:null;if(!this.options.isClone){this.modules.logger?I.init(r(this.modules.logger),this.options):I.init(null,this.options);let e;e=this.modules.formatter?this.modules.formatter:xe;let t=new G(this.options);this.store=new R(this.options.resources,this.options);let i=this.services;i.logger=I,i.resourceStore=this.store,i.languageUtils=t,i.pluralResolver=new he(t,{prepend:this.options.pluralSeparator,simplifyPluralSuffix:this.options.simplifyPluralSuffix}),this.options.interpolation.format&&this.options.interpolation.format!==n.interpolation.format&&this.logger.deprecate(`init: you are still using the legacy format function, please use the new approach: https://www.i18next.com/translation-function/formatting`),e&&(!this.options.interpolation.format||this.options.interpolation.format===n.interpolation.format)&&(i.formatter=r(e),i.formatter.init&&i.formatter.init(i,this.options),this.options.interpolation.format=i.formatter.format.bind(i.formatter)),i.interpolator=new _e(this.options),i.utils={hasLoadedNamespace:this.hasLoadedNamespace.bind(this)},i.backendConnector=new Ce(r(this.modules.backend),i.resourceStore,i,this.options),i.backendConnector.on(`*`,(e,...t)=>{this.emit(e,...t)}),this.modules.languageDetector&&(i.languageDetector=r(this.modules.languageDetector),i.languageDetector.init&&i.languageDetector.init(i,this.options.detection,this.options)),this.modules.i18nFormat&&(i.i18nFormat=r(this.modules.i18nFormat),i.i18nFormat.init&&i.i18nFormat.init(this)),this.translator=new W(this.services,this.options),this.translator.on(`*`,(e,...t)=>{this.emit(e,...t)}),this.modules.external.forEach(e=>{e.init&&e.init(this)})}if(this.format=this.options.interpolation.format,t||=J,this.options.fallbackLng&&!this.services.languageDetector&&!this.options.lng){let e=this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);e.length>0&&e[0]!==`dev`&&(this.options.lng=e[0])}!this.services.languageDetector&&!this.options.lng&&this.logger.warn(`init: no languageDetector is used and no lng is defined`),[`getResource`,`hasResourceBundle`,`getResourceBundle`,`getDataByLanguage`].forEach(e=>{this[e]=(...t)=>this.store[e](...t)}),[`addResource`,`addResources`,`addResourceBundle`,`removeResourceBundle`].forEach(e=>{this[e]=(...t)=>(this.store[e](...t),this)});let i=E(),a=()=>{let e=(e,n)=>{this.isInitializing=!1,this.isInitialized&&!this.initializedStoreOnce&&this.logger.warn(`init: i18next is already initialized. You should call init just once!`),this.isInitialized=!0,this.options.isClone||this.logger.log(`initialized`,this.options),this.emit(`initialized`,this.options),i.resolve(n),t(e,n)};if(this.languages&&!this.isInitialized)return e(null,this.t.bind(this));this.changeLanguage(this.options.lng,e)};return this.options.resources||!this.options.initAsync?a():setTimeout(a,0),i}loadResources(e,t=J){let n=t,r=T(e)?e:this.language;if(typeof e==`function`&&(n=e),!this.options.resources||this.options.partialBundledLanguages){if(r?.toLowerCase()===`cimode`&&(!this.options.preload||this.options.preload.length===0))return n();let e=[],t=t=>{t&&t!==`cimode`&&this.services.languageUtils.toResolveHierarchy(t).forEach(t=>{t!==`cimode`&&e.indexOf(t)<0&&e.push(t)})};r?t(r):this.services.languageUtils.getFallbackCodes(this.options.fallbackLng).forEach(e=>t(e)),this.options.preload?.forEach?.(e=>t(e)),this.services.backendConnector.load(e,this.options.ns,e=>{!e&&!this.resolvedLanguage&&this.language&&this.setResolvedLanguage(this.language),n(e)})}else n(null)}reloadResources(e,t,n){let r=E();return typeof e==`function`&&(n=e,e=void 0),typeof t==`function`&&(n=t,t=void 0),e||=this.languages,t||=this.options.ns,n||=J,this.services.backendConnector.reload(e,t,e=>{r.resolve(),n(e)}),r}use(e){if(!e)throw Error(`You are passing an undefined module! Please check the object you are passing to i18next.use()`);if(!e.type)throw Error(`You are passing a wrong module! Please check the object you are passing to i18next.use()`);return e.type===`backend`&&(this.modules.backend=e),(e.type===`logger`||e.log&&e.warn&&e.error)&&(this.modules.logger=e),e.type===`languageDetector`&&(this.modules.languageDetector=e),e.type===`i18nFormat`&&(this.modules.i18nFormat=e),e.type===`postProcessor`&&z.addPostProcessor(e),e.type===`formatter`&&(this.modules.formatter=e),e.type===`3rdParty`&&this.modules.external.push(e),this}setResolvedLanguage(e){if(!(!e||!this.languages)&&!([`cimode`,`dev`].indexOf(e)>-1)){for(let e=0;e<this.languages.length;e++){let t=this.languages[e];if(!([`cimode`,`dev`].indexOf(t)>-1)&&this.store.hasLanguageSomeTranslations(t)){this.resolvedLanguage=t;break}}!this.resolvedLanguage&&this.languages.indexOf(e)<0&&this.store.hasLanguageSomeTranslations(e)&&(this.resolvedLanguage=e,this.languages.unshift(e))}}changeLanguage(e,t){this.isLanguageChangingTo=e;let n=E();this.emit(`languageChanging`,e);let r=e=>{this.language=e,this.languages=this.services.languageUtils.toResolveHierarchy(e),this.resolvedLanguage=void 0,this.setResolvedLanguage(e)},i=(i,a)=>{a?this.isLanguageChangingTo===e&&(r(a),this.translator.changeLanguage(a),this.isLanguageChangingTo=void 0,this.emit(`languageChanged`,a),this.logger.log(`languageChanged`,a)):this.isLanguageChangingTo=void 0,n.resolve((...e)=>this.t(...e)),t&&t(i,(...e)=>this.t(...e))},a=t=>{!e&&!t&&this.services.languageDetector&&(t=[]);let n=T(t)?t:t&&t[0],a=this.store.hasLanguageSomeTranslations(n)?n:this.services.languageUtils.getBestMatchFromCodes(T(t)?[t]:t);a&&(this.language||r(a),this.translator.language||this.translator.changeLanguage(a),this.services.languageDetector?.cacheUserLanguage?.(a)),this.loadResources(a,e=>{i(e,a)})};return!e&&this.services.languageDetector&&!this.services.languageDetector.async?a(this.services.languageDetector.detect()):!e&&this.services.languageDetector&&this.services.languageDetector.async?this.services.languageDetector.detect.length===0?this.services.languageDetector.detect().then(a):this.services.languageDetector.detect(a):a(e),n}getFixedT(e,t,n){let r=(e,t,...i)=>{let a;a=typeof t==`object`?{...t}:this.options.overloadTranslationOptionHandler([e,t].concat(i)),a.lng=a.lng||r.lng,a.lngs=a.lngs||r.lngs,a.ns=a.ns||r.ns,a.keyPrefix!==``&&(a.keyPrefix=a.keyPrefix||n||r.keyPrefix);let o={...this.options,...a};typeof a.keyPrefix==`function`&&(a.keyPrefix=V(a.keyPrefix,o));let s=this.options.keySeparator||`.`,c;return a.keyPrefix&&Array.isArray(e)?c=e.map(e=>(typeof e==`function`&&(e=V(e,o)),`${a.keyPrefix}${s}${e}`)):(typeof e==`function`&&(e=V(e,o)),c=a.keyPrefix?`${a.keyPrefix}${s}${e}`:e),this.t(c,a)};return T(e)?r.lng=e:r.lngs=e,r.ns=t,r.keyPrefix=n,r}t(...e){return this.translator?.translate(...e)}exists(...e){return this.translator?.exists(...e)}setDefaultNamespace(e){this.options.defaultNS=e}hasLoadedNamespace(e,t={}){if(!this.isInitialized)return this.logger.warn(`hasLoadedNamespace: i18next was not initialized`,this.languages),!1;if(!this.languages||!this.languages.length)return this.logger.warn(`hasLoadedNamespace: i18n.languages were undefined or empty`,this.languages),!1;let n=t.lng||this.resolvedLanguage||this.languages[0],r=this.options?this.options.fallbackLng:!1,i=this.languages[this.languages.length-1];if(n.toLowerCase()===`cimode`)return!0;let a=(e,t)=>{let n=this.services.backendConnector.state[`${e}|${t}`];return n===-1||n===0||n===2};if(t.precheck){let e=t.precheck(this,a);if(e!==void 0)return e}return!!(this.hasResourceBundle(n,e)||!this.services.backendConnector.backend||this.options.resources&&!this.options.partialBundledLanguages||a(n,e)&&(!r||a(i,e)))}loadNamespaces(e,t){let n=E();return this.options.ns?(T(e)&&(e=[e]),e.forEach(e=>{this.options.ns.indexOf(e)<0&&this.options.ns.push(e)}),this.loadResources(e=>{n.resolve(),t&&t(e)}),n):(t&&t(),Promise.resolve())}loadLanguages(e,t){let n=E();T(e)&&(e=[e]);let r=this.options.preload||[],i=e.filter(e=>r.indexOf(e)<0&&this.services.languageUtils.isSupportedCode(e));return i.length?(this.options.preload=r.concat(i),this.loadResources(e=>{n.resolve(),t&&t(e)}),n):(t&&t(),Promise.resolve())}dir(e){if(e||=this.resolvedLanguage||(this.languages?.length>0?this.languages[0]:this.language),!e)return`rtl`;try{let t=new Intl.Locale(e);if(t&&t.getTextInfo){let e=t.getTextInfo();if(e&&e.direction)return e.direction}}catch{}let t=`ar.shu.sqr.ssh.xaa.yhd.yud.aao.abh.abv.acm.acq.acw.acx.acy.adf.ads.aeb.aec.afb.ajp.apc.apd.arb.arq.ars.ary.arz.auz.avl.ayh.ayl.ayn.ayp.bbz.pga.he.iw.ps.pbt.pbu.pst.prp.prd.ug.ur.ydd.yds.yih.ji.yi.hbo.men.xmn.fa.jpr.peo.pes.prs.dv.sam.ckb`.split(`.`),n=this.services?.languageUtils||new G(q());return e.toLowerCase().indexOf(`-latn`)>1?`ltr`:t.indexOf(n.getLanguagePartFromCode(e))>-1||e.toLowerCase().indexOf(`-arab`)>1?`rtl`:`ltr`}static createInstance(t={},n){let r=new e(t,n);return r.createInstance=e.createInstance,r}cloneInstance(t={},n=J){let r=t.forkResourceStore;r&&delete t.forkResourceStore;let i={...this.options,...t,isClone:!0},a=new e(i);if((t.debug!==void 0||t.prefix!==void 0)&&(a.logger=a.logger.clone(t)),[`store`,`services`,`language`].forEach(e=>{a[e]=this[e]}),a.services={...this.services},a.services.utils={hasLoadedNamespace:a.hasLoadedNamespace.bind(a)},r&&(a.store=new R(Object.keys(this.store.data).reduce((e,t)=>(e[t]={...this.store.data[t]},e[t]=Object.keys(e[t]).reduce((n,r)=>(n[r]={...e[t][r]},n),e[t]),e),{}),i),a.services.resourceStore=a.store),t.interpolation){let e={...q().interpolation,...this.options.interpolation,...t.interpolation},n={...i,interpolation:e};a.services.interpolator=new _e(n)}return a.translator=new W(a.services,i),a.translator.on(`*`,(e,...t)=>{a.emit(e,...t)}),a.init(i,n),a.translator.options=i,a.translator.backendConnector.services.utils={hasLoadedNamespace:a.hasLoadedNamespace.bind(a)},a}toJSON(){return{options:this.options,store:this.store,language:this.language,languages:this.languages,resolvedLanguage:this.resolvedLanguage}}}.createInstance(),Ae=Y.createInstance;Y.dir,Y.init,Y.loadResources,Y.reloadResources,Y.use,Y.changeLanguage,Y.getFixedT,Y.t,Y.exists,Y.setDefaultNamespace,Y.hasLoadedNamespace,Y.loadNamespaces,Y.loadLanguages;var je=class{currentLanguage;initializationState;initializationPromise;i18n;translationUrl;ai;aiTranslationCache=new Map;aiTranslationPending=new Map;constructor(e,t,n){this.currentLanguage=e,this.initializationState=`not-inited`,this.initializationPromise=null,this.translationUrl=t,this.ai=n}async initialize(){if(this.initializationState!==`finished`)return this.initializationState===`initing`&&this.initializationPromise?this.initializationPromise:(this.initializationState=`initing`,this.initializationPromise=(async()=>{try{let e=await this.fetchTranslations(this.currentLanguage),t=Ae({lng:this.currentLanguage,resources:{[this.currentLanguage]:{translation:e}},debug:!1,showSupportNotice:!1,parseMissingKeyHandler:(e,t)=>e.trim()?this.isTranslationKey(e)?(console.warn(`Translation key not found: ${e}`),t??``):(this.fetchTranslation(e).then(t=>{this.i18n?.addResource(this.currentLanguage,`translation`,e,t),this.i18n?.emit(`languageChanged`)}),e):``});await t.init(),this.i18n=t,this.initializationState=`finished`}catch(e){throw this.initializationState=`not-inited`,this.initializationPromise=null,e}})(),this.initializationPromise)}getTranslationUrl(e){return`${(this.translationUrl||window.location.origin).replace(/\/+$/,``)}/locales/${e}.json`}usePlugin(e){if(!this.i18n)throw Error(`Translator is not initialized`);this.i18n.use(e)}onLanguageChanged(e){if(!this.i18n)throw Error(`Translator is not initialized`);this.i18n.on(`languageChanged`,e)}async fetchTranslations(e,t=0){try{let n=await fetch(this.getTranslationUrl(e));if(!n.ok)throw Error(`Failed to fetch translations for ${e}: ${n.status}`);let r=await n.json();return Object.keys(r).length===0&&t===0?(await new Promise(e=>setTimeout(e,300)),this.fetchTranslations(e,1)):r}catch(n){return t===0?(await new Promise(e=>setTimeout(e,300)),this.fetchTranslations(e,1)):(console.warn(`Fetching of ${e} translation not possible. Falling back to english. Error details: `+n.message),e===`en`?{}:this.fetchTranslations(`en`).catch(e=>(console.error(`Failed to fetch fallback translations:`,e),{})))}}t(e,t){if(!this.i18n)throw Error(`Translator is not initialized`);return this.i18n.t(e,t)}getCurrentLanguage(){return this.currentLanguage}isReady(){return this.initializationState===`finished`}isTranslationKey(e){return/^[^\s.]+(\.[^\s.]+)+$/.test(e)}async fetchTranslation(e,t){let n=this.aiTranslationCache.get(e);if(n)return n;let r=this.aiTranslationPending.get(e);if(r)return r;if(!this.ai||this.currentLanguage===`en`)return e;let i=(async()=>{try{let n=(await this.ai.getObject({prompt:`global.translator.translate`,variables:{additionalInstructions:t??``,language:this.currentLanguage,text:e},cache:!0}))?.translation;if(n)return this.aiTranslationCache.set(e,n),n}catch(t){console.warn(`Failed to translate freeform text:`,{text:e,error:t})}finally{this.aiTranslationPending.delete(e)}return e})();return this.aiTranslationPending.set(e,i),i}},Me=class{pluginId;rimoriInfo;translator;supabase;communicationHandler;releaseChannel;applicationMode;theme;ttsEnabled=!0;constructor(e,t,n,r){this.rimoriInfo=n,this.supabase=e,this.pluginId=n.pluginId,this.releaseChannel=n.releaseChannel,this.communicationHandler=t;let i=n.installedPlugins.find(e=>e.id===n.pluginId);this.translator=new je(n.interfaceLanguage,i?.endpoint||``,r),this.ttsEnabled=n.ttsEnabled??!0,this.communicationHandler.onUpdate(e=>{this.rimoriInfo=e,this.ttsEnabled=e.ttsEnabled??!0}),this.applicationMode=this.communicationHandler.getQueryParam(`applicationMode`),this.theme=this.communicationHandler.getQueryParam(`rm_theme`)||`light`}async fetchSettings(){let e=!this.rimoriInfo.guild.allowUserPluginSettings,{data:t}=await this.supabase.schema(`public`).from(`plugin_settings`).select(`*`).eq(`plugin_id`,this.pluginId).eq(`guild_id`,this.rimoriInfo.guild.id).eq(`is_guild_setting`,e).maybeSingle();return t?.settings??null}async setSettings(e){let t=!this.rimoriInfo.guild.allowUserPluginSettings,n={plugin_id:this.pluginId,settings:e,guild_id:this.rimoriInfo.guild.id,is_guild_setting:t};t&&(n.user_id=null);let r=this.supabase.schema(`public`).from(`plugin_settings`).update({settings:e}).eq(`plugin_id`,this.pluginId).eq(`guild_id`,this.rimoriInfo.guild.id).eq(`is_guild_setting`,t),{data:i,error:a}=await(t?r.is(`user_id`,null).select():r.select());if(a&&(a.code===`42501`||a.message?.includes(`policy`)))throw Error(`Cannot set ${t?`guild`:`user`} settings: Permission denied.`);if(i&&i.length>0)return;let{error:o}=await this.supabase.schema(`public`).from(`plugin_settings`).insert(n);if(o){if(o.code===`23505`){let n=this.supabase.schema(`public`).from(`plugin_settings`).update({settings:e}).eq(`plugin_id`,this.pluginId).eq(`guild_id`,this.rimoriInfo.guild.id).eq(`is_guild_setting`,t),{error:r}=await(t?n.is(`user_id`,null):n);if(!r)return}throw o}}async getSettings(e){let t=await this.fetchSettings();if(!t)return await this.setSettings(e),e;let n=Object.keys(t),r=Object.keys(e);if(n.length!==r.length){let n=Object.fromEntries(Object.entries(t).filter(([e])=>r.includes(e))),i={...e,...n};return await this.setSettings(i),i}return t}getUserInfo(){return this.rimoriInfo.profile}getGuildInfo(){return{id:this.rimoriInfo.guild.id,name:this.rimoriInfo.guild.name,description:this.rimoriInfo.guild.description,isShadowGuild:this.rimoriInfo.guild.isShadowGuild}}onRimoriInfoUpdate(e){return this.communicationHandler.onUpdate(e)}getPluginInfo(){return{installedPlugins:this.rimoriInfo.installedPlugins,mainPanelPlugin:this.rimoriInfo.mainPanelPlugin,sidePanelPlugin:this.rimoriInfo.sidePanelPlugin}}async getTranslator(){return await this.translator.initialize(),this.translator}},Ne=[`anonymous`,`free`,`standard`,`premium`,`early_access`],Pe=[`user`,`plugin_moderator`,`lang_moderator`,`admin`],Fe=class{supabase;communicationHandler;tablePrefix;schema;constructor(e,t,n){this.supabase=e,this.communicationHandler=t,this.tablePrefix=n.tablePrefix,this.schema=n.dbSchema,t.onUpdate(e=>{this.tablePrefix=e.tablePrefix,this.schema=e.dbSchema})}from(e){let t=this.getTableName(e);return e.startsWith(`global_`)?this.supabase.schema(`public`).from(t):this.supabase.schema(this.schema).from(t)}getTableName(e){if(/[A-Z]/.test(e))throw Error(`Table name cannot include uppercase letters. Please use snake_case for table names.`);return e.startsWith(`global_`)?e.replace(`global_`,``):this.tablePrefix+`_`+e}async setPublicity(e,t,n){let r=this.getTableName(e);await this.communicationHandler.fetchBackend(`/db-entry/publicity`,{method:`POST`,body:JSON.stringify({table_name:r,schema:this.schema,entry_id:t,publicity:n})})}async vectorSearch(e){let t=await this.communicationHandler.fetchBackend(`/plugin-search/vector-search`,{method:`POST`,body:JSON.stringify(e)});if(!t.ok)throw Error(`Vector search failed: ${t.statusText}`);return await t.json()}},Ie=[`reading`,`listening`,`speaking`,`writing`,`learning`,`community`],Le=class{pluginId;eventBus;constructor(e,t){this.pluginId=e,this.eventBus=t??n}emitAccomplishment(e){let t={...e,type:`durationMinutes`in e?`macro`:`micro`};if(!this.validateAccomplishment(t))return;let n=this.sanitizeAccomplishment(t),r=`global.accomplishment.trigger`+(t.type===`macro`?`Macro`:`Micro`);this.eventBus.emit(this.pluginId,r,n)}validateAccomplishment(e){if(!Ie.includes(e.skillCategory))throw Error(`Invalid skill category: ${e.skillCategory}`);if(!/^[0-9a-z_.-]+$/.test(e.accomplishmentKeyword))throw Error(`The accomplishment keyword: ${e.accomplishmentKeyword} is invalid. Only lowercase letters, minuses, underscores and periods are allowed`);if(e.description.length<10)throw Error(`Description is too short`);if(![`micro`,`macro`].includes(e.type))throw Error(`Invalid accomplishment type `+e.type);if(e.type===`macro`&&(e.errorRatio<0||e.errorRatio>1))throw Error(`The error ratio must be between 0 and 1`);return!0}sanitizeAccomplishment(e){return e.description=e.description.replace(/[^\x20-\x7E]/g,``),e.meta?.forEach(e=>{e.description=e.description.replace(/[^\x20-\x7E]/g,``)}),e.meta?.forEach(e=>{e.key=e.key.replace(/([A-Z])/g,`_$1`).toLowerCase()}),e}getDecoupledTopic(e){let[t,n,r]=e.split(`.`);return{plugin:t||`*`,skillCategory:n||`*`,accomplishmentKeyword:r||`*`}}subscribe(e=`*`,t){typeof e==`string`&&(e=[e]),e.forEach(e=>{let n=e.split(`.`).length;if(n===1)e+=`.*.*`;else if(n===2)e+=`.*`;else if(n!==3)throw Error(`Invalid accomplishment topic pattern. The pattern must be plugin.skillCategory.accomplishmentKeyword or an * as wildcard for any plugin, skill category or accomplishment keyword`);this.eventBus.on([`global.accomplishment.triggerMicro`,`global.accomplishment.triggerMacro`],n=>{let{plugin:r,skillCategory:i,accomplishmentKeyword:a}=this.getDecoupledTopic(e);r!==`*`&&n.sender!==r||i!==`*`&&n.data.skillCategory!==i||a!==`*`&&n.data.accomplishmentKeyword!==a||t(n)},[this.pluginId])})}},Re=class{pluginId;accomplishmentController;aiModule;eventBus;constructor(e,t,r){this.pluginId=e,this.aiModule=t,this.eventBus=r??n,this.accomplishmentController=new Le(e,this.eventBus),this.eventBus.on([`global.session.triggerUpdate`],e=>{e.data.session_token?this.aiModule.session.set(e.data.session_token):this.aiModule.session.clear()})}getGlobalEventTopic(e){if(e.startsWith(`global.`)||e.startsWith(`self.`))return e;let t=e.split(`.`);if(t.length===3){if(!t[0].startsWith(`pl`)&&t[0]!==`global`)throw Error(`Invalid event topic '${e}'. The topic must start with the plugin id, 'self' or 'global'.`);return e}else if(t.length>3)throw Error(`The event topic must consist of 3 parts. <pluginId>.<topic area>.<action>. Received: ${e}`);return`${this.pluginId??`global`}.${e}`}emit(e,t,n){let r=this.getGlobalEventTopic(e);this.eventBus.emit(this.pluginId,r,t,n)}async request(e,t){let n=this.getGlobalEventTopic(e),r=this.aiModule.session.get()??void 0;return this.eventBus.request(this.pluginId,n,t,r)}on(e,t){let n=Array.isArray(e)?e:[e];return this.eventBus.on(n.map(e=>this.getGlobalEventTopic(e)),e=>{e.ai_session_token&&!this.aiModule.session.get()&&this.aiModule.session.set(e.ai_session_token),t(e)})}once(e,t){this.eventBus.once(this.getGlobalEventTopic(e),t)}respond(e,t){let n=Array.isArray(e)?e:[e],r=t;typeof t==`function`&&(r=async e=>{let n=this.aiModule.session.get();e.ai_session_token&&this.aiModule.session.set(e.ai_session_token);try{return await t(e)}finally{e.ai_session_token&&(n?this.aiModule.session.set(n):this.aiModule.session.clear())}}),this.eventBus.respond(this.pluginId,n.map(e=>this.getGlobalEventTopic(e)),r)}async emitAccomplishment(e){this.accomplishmentController.emitAccomplishment(e)}onAccomplishment(e,t){this.accomplishmentController.subscribe(e,t)}emitSidebarAction(e,t,n,r){this.emit(`global.sidebar.triggerAction`,{plugin_id:e,action_key:t,text:n,args:r})}emitMainPanelAction(e,t,n){this.emit(`global.mainPanel.triggerAction`,{plugin_id:e,action_key:t,...n})}onMainPanelAction(e,t=[]){let n=Array.isArray(t)?t:[t],r=this.on(`action.requestMain`,({data:t})=>{(n.length===0||n.includes(t.action_key))&&e(t)});return this.emit(`action.requestMain`),r}onSidePanelAction(e,t=[]){let n=Array.isArray(t)?t:[t],r=this.on(`action.requestSidebar`,({data:t})=>{(n.length===0||n.includes(t.action))&&e(t)});return this.emit(`action.requestSidebar`),this.eventBus.emit(this.pluginId,`global.session.requestCurrent`,{}),r}},ze=class{controller;sessionTokenId=null;onRateLimitedCb;constructor(e){this.controller=e}resolvePromptName(e){return e.startsWith(`global.`)?e:e.split(`.`).length===2&&this.controller.pluginId?`${this.controller.pluginId}.${e}`:e}session={get:()=>this.sessionTokenId,set:e=>{this.sessionTokenId=e},clear:()=>{this.sessionTokenId=null}};setOnRateLimited(e){this.onRateLimitedCb=e}async getText(e){let{messages:t,tools:n,cache:r=!1,prompt:i,variables:a}=e,{result:o}=await this.streamObject({cache:r,tools:n,messages:t,prompt:i,variables:a});return o}async getStreamedText(e){let{messages:t,onMessage:n,tools:r,cache:i=!1,prompt:a,variables:o}=e,s=Math.random().toString(36).substring(3),{result:c}=await this.streamObject({cache:i,tools:r,messages:t,prompt:a,variables:o,onResult:({result:e})=>n(s,e,!1)});return n(s,c,!0),c}async getVoice(e,t=`alloy`,n=1,r,i=!1,a){return e.trim().length?await this.controller.fetchBackend(`/voice/tts`,{method:`POST`,body:JSON.stringify({input:e,voice:t,speed:n,language:r,cache:i,instructions:a,session_token_id:this.sessionTokenId??void 0})}).then(e=>e.blob()):(console.warn(`[rimori-client] getVoice called with empty text — skipping TTS request and returning empty Blob.`),new Blob([],{type:`audio/mpeg`}))}async getImage(e){let{prompt:t,cache:n=!0}=e,r=await this.controller.fetchBackend(`/ai/image`,{method:`POST`,body:JSON.stringify({prompt:t,cache:n,session_token_id:this.sessionTokenId??void 0})});if(!r.ok)throw Error(`Failed to generate image: ${r.status} ${r.statusText}`);return r.json()}async getTextFromVoice(e,t){let n=new FormData;return n.append(`file`,e),t&&n.append(`language`,t.code),this.sessionTokenId&&n.append(`session_token_id`,this.sessionTokenId),await this.controller.fetchBackend(`/voice/stt`,{method:`POST`,body:n}).then(e=>e.json()).then(e=>e.text)}async getObject(e){let{cache:t=!1,tools:n=[],prompt:r,variables:i}=e;return await this.streamObject({messages:[],cache:t,tools:n,prompt:r,variables:i})}async getStreamedObject(e){let{onResult:t,cache:n=!1,tools:r=[],prompt:i,variables:a}=e;return await this.streamObject({messages:[],onResult:t,cache:n,tools:r,prompt:i,variables:a})}async streamObject(e){let{messages:t,onResult:n=()=>null,cache:r=!1,tools:i=[],prompt:a,variables:o}=e,s={cache:r,tools:i,stream:!0,messages:t.map((e,t)=>({...e,id:`${t+1}`})),session_token_id:this.sessionTokenId??void 0};a&&(s.prompt={name:this.resolvePromptName(a),variables:o??{}});let c=await this.controller.fetchBackend(`/ai/llm`,{method:`POST`,body:JSON.stringify(s)});if(!c.ok){if(c.status===429){let e=await c.json().catch(()=>({})),t=e.exercises_remaining??0;throw this.onRateLimitedCb?.(t),Error(`Rate limit exceeded: ${e.error??`Daily exercise limit reached`}. exercises_remaining: ${t}`)}throw Error(`Failed to stream object: ${c.status} ${c.statusText}`)}if(!c.body)throw Error(`No response body.`);let l=c.body.getReader(),u=new TextDecoder(`utf-8`),d={},f=``,p=!0;for(;p;){await new Promise(e=>setTimeout(e,30));let{value:e,done:t}=await l.read();if(t)return p=!1,n(d,!1),d;if(!e)continue;let r=u.decode(e,{stream:!0}),a=(f+r).split(`
3
- `);f=a.pop()??``;let o=a.filter(e=>e.trim());for(let e of o){if(e.startsWith(`token:`)){try{let t=JSON.parse(e.slice(6).trim());t.token_id&&(this.sessionTokenId=t.token_id)}catch{console.error(`Failed to parse token: line`,e)}continue}if(e.startsWith(`debug:`)){try{let t=JSON.parse(e.slice(6).trim());console.group(`[Rimori Prompt] ${t.promptName}`),console.log(`System prompt:
4
- `,t.system),console.log(`User prompt:
5
- `,t.user),console.log(`Variables:`,t.variables),console.groupEnd()}catch{}continue}let t=e.substring(0,5),r=e.substring(5).trim();if(r===`[DONE]`)return p=!1,n(d,!1),d;if(t===`data:`)d=JSON.parse(r),n(d,!0);else if(t===`tool:`){let{toolCallId:e,toolName:t,args:n}=JSON.parse(r),a=i.find(e=>e.name===t);if(a&&a.execute){let t=await a.execute(n);await this.sendToolResult(e,t)}else a&&!a.execute?console.error(`Tool found but has no execute function:`,t):console.error(`Tool not found:`,t)}else t===`error`?console.error(`Error:`,r.substring(1)):t===`info:`||console.error(`Unknown stream data:`,e)}}return d}async sendToolResult(e,t){await this.controller.fetchBackend(`/ai/llm/tool_result`,{method:`POST`,body:JSON.stringify({toolCallId:e,result:t??`[DONE]`})})}},Be=class{supabase;communicationHandler;eventModule;constructor(e,t,n,r){this.supabase=e,this.communicationHandler=t,this.eventModule=r}async view(){let{data:e,error:t}=await this.supabase.schema(`public`).from(`weekly_exercises`).select(`*`);if(t)throw Error(`Failed to fetch weekly exercises: ${t.message}`);return e||[]}async add(e){let t=Array.isArray(e)?e:[e],n=await this.communicationHandler.fetchBackend(`/exercises`,{method:`POST`,body:JSON.stringify({exercises:t})});if(!n.ok){let e=await n.text();throw Error(`Failed to create exercises: ${e}`)}let r=await n.json();return this.eventModule.emit(`global.exercises.triggerChange`),r}async start(e){return new Promise((t,n)=>{let r=setTimeout(()=>{i.off(),n(Error(`Exercise start timed out: rimori-main did not respond within 5s`))},5e3),i=this.eventModule.on(`global.session.triggerUpdate`,({data:e})=>{e.session_token&&(clearTimeout(r),i.off(),t())});this.eventModule.emit(`global.exercise.triggerStart`,e)})}async delete(e){let t=await this.communicationHandler.fetchBackend(`/exercises/${e}`,{method:`DELETE`});if(!t.ok){let e=await t.text();throw Error(`Failed to delete exercise: ${e}`)}return this.eventModule.emit(`global.exercises.triggerChange`),await t.json()}},Ve=class{controller;constructor(e){this.controller=e}async uploadImage(e){let t=new FormData;t.append(`file`,e,`image.png`);try{let e=await this.controller.fetchBackend(`/plugin-images/upload`,{method:`POST`,body:t});if(!e.ok){let t=await e.json().catch(()=>({}));return{error:Error(t.message??`Upload failed (${e.status})`)}}return{data:await e.json()}}catch(e){return{error:e instanceof Error?e:Error(String(e))}}}},He=class{controller;constructor(e){this.controller=e}async upload(e,t){let n=new FormData,r=t.filename??`asset.${t.kind}`;n.append(`file`,e,r),n.append(`kind`,t.kind);try{let e=await this.controller.fetchBackend(`/plugin-assets/upload`,{method:`POST`,body:n});if(!e.ok){let t=await e.json().catch(()=>({}));return{error:Error(t.message??`Upload failed (${e.status})`)}}return{data:await e.json()}}catch(e){return{error:e instanceof Error?e:Error(String(e))}}}},Ue=class e{static instance;controller;sharedContent;db;event;plugin;ai;exercise;storage;assets;eventBus;constructor(e,t,i,a){this.controller=e,this.eventBus=a??n,this.sharedContent=new r(t,this),this.ai=new ze(e),this.ai.setOnRateLimited(e=>{this.eventBus.emit(i.pluginId,`global.quota.triggerExceeded`,{exercises_remaining:e})}),this.event=new Re(i.pluginId,this.ai,this.eventBus),this.db=new Fe(t,e,i),this.plugin=new Me(t,e,i,this.ai),this.exercise=new Be(t,e,i,this.event),this.storage=new Ve(e),this.assets=new He(e),this.plugin.applicationMode!==`sidebar`&&w.getInstance(this)}static createWithInfo(n){let r=t.create(`Plugin EventBus `+n.pluginId),i=new C(n.pluginId,!0);i.handleRimoriInfoUpdate(n);let a=new e(i,new S(`${n.url}/rest/v1`,{schema:n.dbSchema,headers:{apikey:n.key,Authorization:`Bearer ${n.token}`,"plugin-id":n.pluginId}}),n,r);return r.on(`${n.pluginId}.supabase.triggerUpdate`,e=>{console.log(`[RimoriClient] Federated triggerUpdate received for`,n.pluginId,`| ttsEnabled:`,e.data?.ttsEnabled),i.handleRimoriInfoUpdate(e.data)}),a}static async getInstance(t){if(!e.instance){if(!t)throw Error(`Plugin ID is required`);let n=new C(t,!1),r=await n.getClient();e.instance=new e(n,r.supabase,r.info)}return e.instance}navigation={toDashboard:()=>{this.event.emit(`global.navigation.triggerToDashboard`)}};runtime={fetchBackend:(e,t={})=>this.controller.fetchBackend(e,t)}},We=class e{static instance;config;supabase;constructor(e){throw Error(`Authentication is disabled until new developer platform is released.`)}static async getInstance(){if(!e.instance){let t=await fetch(`https://app.rimori.se/config.json`).then(e=>e.json()).catch(e=>{console.warn(`Error fetching config.json, using default values`,e)});e.instance=new e({url:t?.SUPABASE_URL||`https://pheptqdoqsdnadgoihvr.supabase.co`,key:t?.SUPABASE_ANON_KEY||`eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InBoZXB0cWRvcXNkbmFkZ29paHZyIiwicm9sZSI6ImFub24iLCJpYXQiOjE3MzE2OTY2ODcsImV4cCI6MjA0NzI3MjY4N30.4GPFAXTF8685FaXISdAPNCIM-H3RGLo8GbyhQpu1mP0`,backendUrl:t?.BACKEND_URL||`https://api.rimori.se`})}return e.instance}async getClient(){return this.supabase}async needsLogin(){let{error:e}=await this.supabase.auth.getUser();return e!==null}async login(e,t){let{error:n}=await this.supabase.auth.signInWithPassword({email:e,password:t});return n?(console.error(`Login failed:`,n),!1):(console.log(`Successfully logged in`),!0)}static async initListeners(t){console.warn(`The plugin seams to not be running inside the Rimori platform. Switching to development standalone mode.`);let{supabase:r,config:i}=await e.getInstance();n.respond(`standalone`,`global.supabase.requestAccess`,async()=>{let e=await r.auth.getSession();console.log(`session`,e);let n=null;try{let{data:{user:e}}=await r.auth.getUser();if(e){let{data:t}=await r.from(`profiles`).select(`current_guild_id`).eq(`user_id`,e.id).maybeSingle();n=t?.current_guild_id||null}}catch{n=null}let a=await fetch(`${i.backendUrl}/plugin/token`,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${e.data.session?.access_token}`},body:JSON.stringify({pluginId:t,guildId:n})});if(!a.ok){let e=await a.text();throw Error(`Failed to get plugin token. ${a.status}: ${e}`)}return{token:(await a.json()).token,pluginId:t,url:i.url,key:i.key,backendUrl:i.backendUrl,tablePrefix:t,expiration:new Date(Date.now()+1e3*60*60*1.5)}}),n.on(`*`,async e=>{console.log(`[standalone] would send event to parent`,e)},[`standalone`])}},Ge=class{audioContext;chunkQueue=[];isPlaying=!1;analyser;dataArray;shouldMonitorLoudness=!0;isMonitoring=!1;handle=0;volume=1;loudnessCallback=()=>{};currentIndex=0;startedPlaying=!1;onEndOfSpeech=()=>{};backgroundNoiseLevel=30;currentSource=null;stopped=!1;constructor(){this.init()}init(){this.audioContext=new AudioContext,this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=256;let e=this.analyser.frequencyBinCount;this.dataArray=new Uint8Array(e)}setOnLoudnessChange(e){this.loudnessCallback=e}setVolume(e){this.volume=e}async addChunk(e,t){this.stopped||(console.log(`Adding chunk`,t,e),this.chunkQueue[t]=e,t===0&&!this.startedPlaying&&(this.startedPlaying=!0,this.playChunks()))}playChunks(){if(!(this.isPlaying||this.stopped)){if(!this.chunkQueue[this.currentIndex]){setTimeout(()=>this.playChunks(),10);return}this.isPlaying=!0,this.playChunk(this.chunkQueue[this.currentIndex]).then(()=>{this.isPlaying=!1,!this.stopped&&(this.currentIndex++,this.chunkQueue[this.currentIndex]?(this.shouldMonitorLoudness=!0,this.playChunks()):setTimeout(()=>{this.stopped||(this.chunkQueue.length>this.currentIndex?this.playChunks():(this.startedPlaying=!1,this.shouldMonitorLoudness=!1))},1e3))})}}stopPlayback(){if(this.stopped=!0,this.currentSource){try{this.currentSource.stop()}catch{}this.currentSource=null}this.isPlaying=!1,this.chunkQueue=[],this.startedPlaying=!1,this.shouldMonitorLoudness=!1,cancelAnimationFrame(this.handle),this.loudnessCallback(0)}cleanup(){this.stopPlayback(),this.audioContext&&this.audioContext.state!==`closed`&&this.audioContext.close().catch(e=>{console.warn(`Error closing AudioContext:`,e)})}playChunk(e){return!e||this.stopped?Promise.resolve():new Promise(t=>{let n=this.audioContext.createBufferSource();this.currentSource=n,this.audioContext.decodeAudioData(e.slice(0)).then(e=>{if(this.stopped){t();return}n.buffer=e;let r=this.audioContext.createGain();r.gain.value=this.volume,n.connect(r),r.connect(this.analyser),this.analyser.connect(this.audioContext.destination),n.start(0),r.gain.value=this.volume,n.onended=()=>{this.currentSource===n&&(this.currentSource=null),t()},this.isMonitoring||(this.isMonitoring=!0,this.shouldMonitorLoudness=!0,this.monitorLoudness())})})}async playAgain(){console.log(`Playing again`),this.chunkQueue.length>0&&!this.isPlaying&&this.playChunks()}monitorLoudness(){if(!this.shouldMonitorLoudness){cancelAnimationFrame(this.handle),this.loudnessCallback(0),this.onEndOfSpeech();return}this.analyser.getByteTimeDomainData(this.dataArray);let e=0;for(let t=0;t<this.dataArray.length;t++){let n=this.dataArray[t]/128-1;e+=n*n}let t=Math.sqrt(e/this.dataArray.length);if(t!==0){let e=20*Math.log10(t);e<-57&&(e=-57),e>-15&&(e=-15);let n=(e- -57)/42*100;n=n<this.backgroundNoiseLevel?0:(n-this.backgroundNoiseLevel)/(100-this.backgroundNoiseLevel)*100,this.loudnessCallback(Math.round(n))}this.handle=requestAnimationFrame(()=>this.monitorLoudness())}reset(){this.stopPlayback(),this.stopped=!1,this.currentIndex=0,this.shouldMonitorLoudness=!0,this.isMonitoring=!1,this.isPlaying=!1,this.init()}setOnEndOfSpeech(e){this.onEndOfSpeech=e}},Ke=class{player=new Ge;fetchedSentences=new Set;lastLoading=!1;voice;voiceBackend;cache;voiceSpeed=1;instructions;constructor(e,t,n=!1){if(t?.split(`_`).length!==2)throw Error(`Invalid voice id format '`+t+`'. Voice id needs to look like <provider>_<voice_id>`);this.voiceBackend=e,this.voice=t,this.cache=n}getCompletedSentences(e,t){let n=/(.+?[.?!]|.+?:\s+|.+?\n+)/g,r=[],i;for(;(i=n.exec(e))!==null;){let e=i[0].trim();e.length>0&&r.push(e)}if(!t){let t=r[r.length-1],n=e.lastIndexOf(t)+t.length;n<e.length&&r.push(e.slice(n).trim())}return r}async handleNewText(e,t){if(!this.lastLoading&&t&&this.reset(),this.lastLoading=t,!e)return;let n=this.getCompletedSentences(e,t);for(let e=0;e<n.length;e++){let t=n[e];if(!this.fetchedSentences.has(t)){this.fetchedSentences.add(t);let n=await this.generateSpeech(t);await this.player.addChunk(n,e)}}}setInstructions(e){this.instructions=e}async generateSpeech(e){return await(await this.voiceBackend(e,this.voice,this.voiceSpeed,void 0,this.cache,this.instructions)).arrayBuffer()}play(){this.player.playAgain()}stop(){this.player.stopPlayback()}cleanup(){this.player.cleanup()}reset(){this.stop(),this.fetchedSentences.clear(),this.player.reset()}setVolume(e){this.player.setVolume(e)}setOnLoudnessChange(e){this.player.setOnLoudnessChange(t=>{e(t)})}setOnEndOfSpeech(e){this.player.setOnEndOfSpeech(e)}setVoiceSpeed(e){this.voiceSpeed=e}},qe=[`Pre-A1`,`A1`,`A2`,`B1`,`B2`,`C1`,`C2`];function X(e){return qe.indexOf(e)+1}function Je(e){return qe[e]}function Ye(e,t){return Je(X(e)+t-1)}function Xe(e,t){return X(e)-X(t)}async function Ze(e,n){Object.assign(globalThis,{window:{isWorker:!0,location:{},parent:{postMessage:()=>{}},addEventListener:()=>{}}}),t.getInstance(`Worker `+e+` EventBus`);let r=await Ue.getInstance(e);console.debug(`[Worker] RimoriClient initialized.`);let i=Error(`[Worker `+e+`] Worker setup must complete within 5s. Use init event (e.g. onboarding.triggerInitPlugin) or run work async.`),a=Promise.resolve(n(r)),o=new Promise((e,t)=>setTimeout(()=>t(i),5e3));await Promise.race([a,o]),console.debug(`[Worker] Worker initialized.`),r.event.emit(`self.rimori.triggerInitFinished`)}var Qe=class{pluginId;constructor(e){this.pluginId=e}async startRecording(){n.emit(this.pluginId,`global.microphone.triggerStartRecording`)}async stopRecording(){return(await n.request(this.pluginId,`global.microphone.triggerStopRecording`)).data}async pauseRecording(){return(await n.request(this.pluginId,`global.microphone.triggerPauseRecording`)).data}async resumeRecording(){return(await n.request(this.pluginId,`global.microphone.triggerResumeRecording`)).data}async getCurrentStatus(){return(await n.request(this.pluginId,`global.microphone.triggerGetCurrentStatus`)).data}},$e=e({AssetsModule:()=>He,AudioController:()=>Qe,EventBus:()=>n,EventBusHandler:()=>t,MessageSender:()=>Ke,ROLE_ORDER:()=>Pe,RimoriClient:()=>Ue,RimoriCommunicationHandler:()=>C,StandaloneClient:()=>We,StorageModule:()=>Ve,TIER_ORDER:()=>Ne,Translator:()=>je,compareLanguageLevels:()=>Xe,getDifficultyLabel:()=>Je,getDifficultyLevel:()=>X,getNeighborDifficultyLevel:()=>Ye,setupWorker:()=>Ze}),et=e({AssetsModule:()=>lt,AudioController:()=>$,EventBus:()=>dt,EventBusHandler:()=>ut,MessageSender:()=>mt,ROLE_ORDER:()=>st,RimoriClient:()=>ft,RimoriCommunicationHandler:()=>yt,StandaloneClient:()=>pt,StorageModule:()=>ct,TIER_ORDER:()=>ot,Translator:()=>at,__moduleExports:()=>nt,compareLanguageLevels:()=>vt,default:()=>rt,getDifficultyLabel:()=>gt,getDifficultyLevel:()=>ht,getNeighborDifficultyLevel:()=>_t,setupWorker:()=>it}),Z=`__mf_module_cache__`;globalThis[Z]||={share:{},remote:{}},globalThis[Z].share||={},globalThis[Z].remote||={};var tt=globalThis[Z],Q=tt.share[`@rimori/client`];Q===void 0&&(Q=$e,tt.share[`@rimori/client`]=Q);var nt=Q,rt=Q.__esModule?Q.default:Q.default??Q,{setupWorker:it,AudioController:$,Translator:at,TIER_ORDER:ot,ROLE_ORDER:st,StorageModule:ct,AssetsModule:lt,EventBusHandler:ut,EventBus:dt,RimoriClient:ft,StandaloneClient:pt,MessageSender:mt,getDifficultyLevel:ht,getDifficultyLabel:gt,getNeighborDifficultyLevel:_t,compareLanguageLevels:vt,RimoriCommunicationHandler:yt}=Q;export{dt as a,$e as c,ut as i,pt as n,ft as o,mt as r,et as s,$ as t};
1
+ var e=`modulepreload`,t=function(e){return`/__rimori_harness__/`+e},n={},r=function(r,i,a){let o=Promise.resolve();if(i&&i.length>0){let r=document.getElementsByTagName(`link`),s=document.querySelector(`meta[property=csp-nonce]`),c=s?.nonce||s?.getAttribute(`nonce`);function l(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}o=l(i.map(i=>{if(i=t(i,a),i in n)return;n[i]=!0;let o=i.endsWith(`.css`),s=o?`[rel="stylesheet"]`:``;if(a)for(let e=r.length-1;e>=0;e--){let t=r[e];if(t.href===i&&(!o||t.rel===`stylesheet`))return}else if(document.querySelector(`link[href="${i}"]${s}`))return;let l=document.createElement(`link`);if(l.rel=o?`stylesheet`:e,o||(l.as=`script`),l.crossOrigin=``,l.href=i,c&&l.setAttribute(`nonce`,c),document.head.appendChild(l),o)return new Promise((e,t)=>{l.addEventListener(`load`,e),l.addEventListener(`error`,()=>t(Error(`Unable to preload CSS for ${i}`)))})}))}function s(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return o.then(e=>{for(let t of e||[])t.status===`rejected`&&s(t.reason);return r().catch(s)})},i=`__mf_module_cache__`;globalThis[i]||={share:{},remote:{}},globalThis[i].share||={},globalThis[i].remote||={};var a=globalThis[i],o=a.share[`@rimori/client`];o===void 0&&(o=await r(()=>import(`./dist3.js`),[]),a.share[`@rimori/client`]=o),o.__esModule,o.default;var{setupWorker:s,AudioController:c,Translator:l,TIER_ORDER:u,ROLE_ORDER:d,StorageModule:f,AssetsModule:p,EventBusHandler:m,EventBus:h,RimoriClient:g,StandaloneClient:_,MessageSender:v,getDifficultyLevel:y,getDifficultyLabel:b,getNeighborDifficultyLevel:x,compareLanguageLevels:S,RimoriCommunicationHandler:C}=o;export{m as a,r as c,u as i,_ as n,h as o,v as r,g as s,c as t};