i18n-works 0.1.18 → 0.1.19
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.
- package/dist/cli/bin.js +1 -1
- package/dist/cli/index.js +1 -1
- package/dist/index.js +2 -2
- package/dist/run-CUCYrBz-.js +25 -0
- package/dist/runtime/index.js +1 -1
- package/dist/sync-DrfpPJa0.js +7 -0
- package/package.json +1 -1
- package/dist/run-1mH_oPMI.js +0 -25
- package/dist/sync-CHmobLly.js +0 -7
package/dist/cli/bin.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{t as e}from"../run-
|
|
2
|
+
import{t as e}from"../run-CUCYrBz-.js";process.exitCode=await e(process.argv.slice(2));export{};
|
package/dist/cli/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export{s as DEFAULT_CATALOG_DIRECTORY,n as browse,r as listLanguages,o as prune,t as runCli,a as stats,i as translate}from"../run-
|
|
1
|
+
export{s as DEFAULT_CATALOG_DIRECTORY,n as browse,r as listLanguages,o as prune,t as runCli,a as stats,i as translate}from"../run-CUCYrBz-.js";
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{C as e,D as t,E as n,O as r,S as i,T as a,b as o,f as s,g as c,h as l,k as u,m as d,n as f,p,t as ee,v as m,w as h,x as g,y as _}from"./sync-
|
|
1
|
+
import{C as e,D as t,E as n,O as r,S as i,T as a,b as o,f as s,g as c,h as l,k as u,m as d,n as f,p,t as ee,v as m,w as h,x as g,y as _}from"./sync-DrfpPJa0.js";import{a as v,i as y,o as b}from"./icu-Cui2dM71.js";import x from"node:path";import{i as te,n as ne,r as S,t as re}from"./pick-Bpdsmz-0.js";function C(e){return JSON.stringify(e).replace(/[<>&\u2028\u2029]/g,e=>`\\u${e.charCodeAt(0).toString(16).padStart(4,`0`)}`)}function w(e,t,n=!1){let r=Object.entries(e).map(([e,t])=>` ${C(e)}: () => import(${C(t)}).then(m => unwrapDefault(m).messages)`).join(`,
|
|
2
2
|
`),i=[`import { formatAutoPluralMessage, formatMessage } from ${C(m)};`,`const unwrapDefault = ${te.toString()};`,`const loaders = {\n${r}\n};`,`const sourceLocale = ${C(t)};`,`const resolveLocale = ${S.toString()};`,`const createLocaleLoader = ${ne.toString()};`,`const loadLocale = createLocaleLoader(loaders, sourceLocale);`,`const listeners = new Set();`,`let currentLocale = sourceLocale;`,`let messages = {};`,`let version = 0;`,`let latestRequest = 0;`,`export const locales = Object.keys(loaders);`,`export function getLocale() { return currentLocale; }`,`export function getVersion() { return version; }`,`export function resolveSupported(preferred) { return resolveLocale(preferred, locales, sourceLocale); }`,`async function applyLocale(locale) {`,` const request = ++latestRequest;`,` let selected = loaders[locale] ? locale : sourceLocale;`,` let catalog;`,` try {`,` catalog = await loadLocale(selected);`,` } catch (error) {`,` console.warn('${y}: could not load "' + selected + '", falling back to "' + sourceLocale + '".', error);`,` selected = sourceLocale;`,` try {`,` catalog = await loadLocale(selected);`,` } catch (fallbackError) {`,` // Keep the current locale and messages so the UI stays consistent. Texts without a catalogue show their source.`,` console.error('${y}: could not load the source catalogue "' + sourceLocale + '".', fallbackError);`,` return;`,` }`,` }`,` // A slower earlier request must not overwrite the locale the user picked last.`,` if (request !== latestRequest) return;`,` messages = catalog;`,` currentLocale = selected;`,` notify();`,`}`,`function notify() {`,` version++;`,` listeners.forEach(fn => fn(currentLocale));`,`}`,`export function subscribe(fn) { listeners.add(fn); return () => { listeners.delete(fn); }; }`,`export function lookup(id, source, values) {`,` const text = messages[id] ?? source;`,` return values === undefined ? text : formatMessage(text, currentLocale, values);`,`}`,`export function lookupAutoPlural(id, source, values) {`,` const text = messages[id] ?? source;`,` return values === undefined ? text : formatAutoPluralMessage(text, currentLocale, values);`,`}`,`// Only literal t("...") and tauto("...") calls are translated at build time. Any other call returns its argument unchanged, formatted with values when given.`,`export function t(source, values) {`,` return values === undefined ? source : formatMessage(source, currentLocale, values);`,`}`,`export function tauto(source, valuesOrHint) {`,` const values = typeof valuesOrHint === "string" ? undefined : valuesOrHint;`,` return values === undefined ? source : formatMessage(source, currentLocale, values);`,`}`,`export function tt(source, values, hint) {`,` return values === undefined ? source : formatAutoPluralMessage(source, currentLocale, values);`,`}`],a=n?[`const localeStorageKey = ${C(`i18n-works:locale`)};`,`function storedLocale() {`,` try { return localStorage.getItem(localeStorageKey); } catch (error) { return null; }`,`}`,`function startupLocale() {`,` const stored = storedLocale();`,` return locales.includes(stored) ? stored : resolveSupported(navigator.languages);`,`}`,`// Module-scope lookups run while importers evaluate, so the chosen locale must be loaded before this module finishes.`,`await applyLocale(startupLocale());`,`// Module-scope messages were translated at import time, so a switch stores the choice and reloads the page.`,`export async function setLocale(locale) {`,` const selected = locales.includes(locale) ? locale : sourceLocale;`,` if (selected === currentLocale) return;`,` try {`,` localStorage.setItem(localeStorageKey, selected);`,` } catch (error) {`,` console.warn('${y}: could not save the locale, so module-scope texts keep their current language.', error);`,` return applyLocale(selected);`,` }`,` location.reload();`,`}`]:[`export { applyLocale as setLocale };`],o=[`// Dev server pushes the catalogues that changed after a source change; no page reload is needed.`,`if (import.meta.hot) {`,` import.meta.hot.on("i18n-works:update", data => {`,` for (const [locale, catalog] of Object.entries(data.catalogs)) loadLocale.prime(locale, catalog);`,` if (!data.catalogs[currentLocale]) return;`,` messages = data.catalogs[currentLocale];`,` notify();`,` });`,`}`];return[...i,...a,...o].join(`
|
|
3
3
|
`)+`
|
|
4
|
-
`}const T=`\0${_}`;function E(t){let n,r,a=``,s,l,u=!1;function d(){if(n.delivery!==`runtime`)return!1;for(let e of n.state.fileMessages.values())if(e.some(e=>e.component===`<module>`))return!0;return!1}function p(e){e.length&&s?.ws.send({type:`custom`,event:`i18n-works:update`,data:{catalogs:Object.fromEntries(e.map(e=>[e,n.state.catalogs.get(e)]))}})}function m(){if(!s||d()===u)return;let e=s.moduleGraph.getModuleById(T);e&&s.moduleGraph.invalidateModule(e),s.ws.send({type:`full-reload`})}async function g(e){try{p(await n.runSync(f(r.logger),e)),m()}catch(e){r.logger.error(b(`re-translation failed: ${e.message}`))}}function y(){clearTimeout(l),l=setTimeout(()=>void g(),150)}return{name:`i18n-works`,enforce:`pre`,config(r,i){let o=x.resolve(r.root??process.cwd()),s=t=>{h(t),n=new ee(t),a=e(o)},c=t(o,i);if(c instanceof Promise)return c.then(s);s(c)},configResolved(e){r=e,n.attach(e);let t=n.selectedLocale();if(t!==n.sourceLocale&&!n.locales.includes(t))throw v(`locale "${t}" is not one of the configured locales (${n.locales.join(`, `)}). Add it to locales in ${i}, or choose one of those locales for the locale option or the I18N_WORKS_LOCALE variable.`)},resolveId(e){if(e===`virtual:i18n-works`)return`\0${_}`},load(e){if(e===T)return u=d(),w(n.state.catalogFiles,n.sourceLocale,u)},configureServer(e){s=e,e.watcher.on(`add`,e=>{n.isSourceCandidate(e)&&y()}),e.watcher.on(`unlink`,e=>{n.state.fileMessages.has(e)&&y()}),e.watcher.on(`change`,t=>{x.resolve(t)===a&&e.restart().catch(e=>{let t=e instanceof Error?e.message:String(e);r.logger.error(b(`could not restart after ${i} changed: ${t}`))})})},closeBundle(){clearTimeout(l)},async buildStart(){await n.sync({info:e=>this.info(e),warn:e=>this.warn(e),error:e=>this.error(e)})},transform:{order:`pre`,async handler(e,t){let i=t.split(`?`)[0];if(!n.state.fileMessages.has(i))return null;let a=c(e);a!==n.state.hashOf(i)&&await n.runSync(f(r.logger),i);let s=n.state.fileMessages.get(i);if(!s||a!==n.state.hashOf(i))return n.state.warnedFiles.has(i)||(n.state.warnedFiles.add(i),this.warn(b(`${i} changed while it was being indexed; its messages are left untranslated.`))),null;if(s.length===0)return null;let l=n.isServing()?n.sourceLocale:n.selectedLocale(),u=n.isServing()||!!r.build.sourcemap,d=o(e,i,s,l,n.state.catalogs.get(l)??{},n.delivery===`runtime`,n.sourceLocale,u);return{code:d.code,map:d.map}}},async handleHotUpdate({file:e}){if(e.startsWith(n.localesDir()+x.sep))return[];n.state.fileMessages.has(e)&&await g(e)}}}const D=6e4;var O=class extends Error{retryable;retryAfterMs;constructor(e,t,n){super(e),this.retryable=t,this.retryAfterMs=n}};function ie(e,t=Date.now()){if(e===null||e===``)return;let n=Number(e);if(Number.isFinite(n))return Math.min(Math.max(n,0)*1e3,D);let r=Date.parse(e);if(!Number.isNaN(r))return Math.min(Math.max(r-t,0),D)}const ae=e=>new Promise(t=>setTimeout(t,e));function k(e){return`You are a professional software localization engine. Translate UI messages from ${e.sourceLocale} to ${e.targetLocale}. Preserve placeholders exactly. Some messages use ICU MessageFormat, such as {name}, {count, plural, one {# file} other {# files}} or {gender, select, ...}. Keep argument names, the keywords (one, other, select, plural, ...) and the # symbol unchanged, translate only the text inside the branches, and write the plural branches the target language needs. Messages marked "autoPlural" are natural-language count templates: convert their source to valid ICU plural syntax using the count argument, include language-appropriate categories (zero, one, two, few, many, other as needed), and include an explicit =0 branch when natural UI wording is different. A "hint" on an autoPlural message gives free-form source-author guidance for special count-dependent wording or thresholds; apply it naturally in the target language, using exact =N branches when a hint identifies specific counts and normal plural categories for ranges. Preserve {count} semantics and translate only the words inside branches. Respect context and UI conventions. When the source and target locales are the same, the source text is only a seed: rewrite it to apply the hint, keeping its placeholders. Keep the rewrite's length proportional to the seed: a one-word seed gets back one to three words, and a longer seed gets a proportionally longer rewrite, never a paragraph. A "hint" on a message without autoPlural is free-form author context, such as tone or audience; follow it in the wording while keeping every placeholder unchanged. Return ONLY a JSON object mapping message IDs to translated strings. Do not translate product names or code.`}function A(e){return JSON.stringify(e.map(e=>({id:e.id,text:e.source,context:e.context,...e.autoPlural===!0?{autoPlural:!0}:{},...e.hint!==void 0&&e.hint.length>0?{hint:e.hint}:{}})))}async function j(e){let t=e.status===408||e.status===409||e.status===429||e.status>=500;return await e.body?.cancel().catch(()=>void 0),new O(`Translation API failed (${e.status})`,t,ie(e.headers.get(`retry-after`)))}var M=class{options;slots;constructor(e){this.options=e,this.slots=new s(e.concurrency??4)}async translate(e){let t=Math.max(1,this.options.batchSize??40),n=[];for(let r=0;r<e.messages.length;r+=t)n.push(e.messages.slice(r,r+t));let r=await Promise.allSettled(n.map(t=>this.slots.run(()=>this.translateBatch({...e,messages:t})))),i={},a=[],o=0,s=0;if(r.forEach((e,t)=>{e.status===`fulfilled`?(s++,Object.assign(i,e.value)):(a.push(e.reason),o+=n[t].length)}),!a.length)return i;throw s?new l(`${o} messages failed to translate: ${a[0].message}`,i,o):a[0]}async translateBatch(e){let t=this.options.maxRetries??2,n=this.options.retryDelayMs??500;for(let r=0;;r++)try{return await this.request(e)}catch(e){if(e instanceof O&&!e.retryable||r>=t)throw e;let i=e instanceof O?e.retryAfterMs:void 0;await ae(i??n*2**r*(.5+Math.random()/2))}}async post(e,t,n){let r=await fetch(e,{method:`POST`,signal:AbortSignal.timeout(this.options.timeoutMs??6e4),headers:{...t,"content-type":`application/json`},body:JSON.stringify(n)});if(!r.ok)throw await j(r);return r.json()}async complete(e,t,n,r,i,a,o){let s=u(r,await this.post(e,t,n)),c=this.toCatalog(s.ok?i(s.value):void 0,a.messages);return a.onUsage?.({provider:o.provider,model:o.model,ids:a.messages.map(e=>e.id),...s.ok?o.tokens(s.value):{}}),c}toCatalog(e,t){let n=e?.trim().replace(/^```(?:json)?\s*|\s*```$/g,``);if(n===void 0||n===``)throw new O(`Translation provider returned no content`,!0);let i;try{i=JSON.parse(n)}catch{throw new O(`Translation provider returned invalid JSON`,!0)}let a=u(r,i);if(!a.ok)throw new O(`Translation provider returned a non-object`,!0);let o=new Set(t.map(e=>e.id)),s={};for(let[e,t]of Object.entries(a.value))o.has(e)&&typeof t==`string`&&t.trim()&&(s[e]=t);return s}};const N=`https://api.openai.com/v1`;var P=class extends M{async request(e){let{apiKey:t,model:r,baseURL:i=N}=this.options;return this.complete(`${i}/chat/completions`,t!==void 0&&t!==``?{Authorization:`Bearer ${t}`}:{},{model:r,temperature:0,response_format:{type:`json_object`},messages:[{role:`system`,content:k(e)},{role:`user`,content:A(e.messages)}]},n,e=>e.choices[0].message.content??void 0,e,{provider:i===N?`openai`:`openai-compatible`,model:r,tokens:e=>({inputTokens:e.usage?.prompt_tokens??void 0,outputTokens:e.usage?.completion_tokens??void 0})})}},F=class extends M{async request(e){return this.complete(`${this.options.baseURL??`https://api.anthropic.com/v1`}/messages`,{"x-api-key":this.options.apiKey,"anthropic-version":`2023-06-01`},{model:this.options.model,max_tokens:this.options.maxTokens??8192,system:k(e),messages:[{role:`user`,content:A(e.messages)}]},a,e=>e.content.filter(e=>e.type===`text`).map(e=>e.text??``).join(``),e,{provider:`anthropic`,model:this.options.model,tokens:e=>({inputTokens:e.usage?.input_tokens??void 0,outputTokens:e.usage?.output_tokens??void 0})})}},I=class extends M{async request(e){return this.complete(`${this.options.baseURL??`https://generativelanguage.googleapis.com/v1beta`}/models/${encodeURIComponent(this.options.model)}:generateContent`,{"x-goog-api-key":this.options.apiKey},{systemInstruction:{parts:[{text:k(e)}]},contents:[{role:`user`,parts:[{text:A(e.messages)}]}],generationConfig:{responseMimeType:`application/json`,maxOutputTokens:this.options.maxOutputTokens??8192}},t,e=>(e.candidates[0]?.content?.parts??[]).map(e=>e.text??``).join(``),e,{provider:`gemini`,model:this.options.model,tokens:e=>({inputTokens:e.usageMetadata?.promptTokenCount??void 0,outputTokens:e.usageMetadata?.candidatesTokenCount??void 0})})}};let oe=/* @__PURE__ */ function(e){return e.Anthropic=`anthropic`,e.Gemini=`gemini`,e.OpenAI=`openai`,e.Mistral=`mistral`,e.Groq=`groq`,e.DeepSeek=`deepseek`,e.OpenRouter=`openrouter`,e.XAI=`xai`,e.Cerebras=`cerebras`,e.Perplexity=`perplexity`,e.Together=`together`,e.Fireworks=`fireworks`,e.HuggingFace=`huggingface`,e.DeepInfra=`deepinfra`,e.SambaNova=`sambanova`,e.Moonshot=`moonshot`,e}({}),se=/* @__PURE__ */ function(e){return e.Ollama=`ollama`,e.LMStudio=`lmstudio`,e.LlamaCpp=`llamacpp`,e.VLLM=`vllm`,e.LocalAI=`localai`,e.DockerModelRunner=`dockermodelrunner`,e}({});const L={openai:{model:`gpt-4.1-mini`},mistral:{baseURL:`https://api.mistral.ai/v1`,model:`mistral-small-latest`},groq:{baseURL:`https://api.groq.com/openai/v1`,model:`llama-3.3-70b-versatile`},deepseek:{baseURL:`https://api.deepseek.com/v1`,model:`deepseek-chat`},openrouter:{baseURL:`https://openrouter.ai/api/v1`,model:`openai/gpt-4.1-mini`},xai:{baseURL:`https://api.x.ai/v1`,model:`grok-3-mini`},cerebras:{baseURL:`https://api.cerebras.ai/v1`,model:`llama-3.3-70b`},perplexity:{baseURL:`https://api.perplexity.ai`,model:`sonar`},together:{baseURL:`https://api.together.xyz/v1`,model:`meta-llama/Llama-3.3-70B-Instruct-Turbo`},fireworks:{baseURL:`https://api.fireworks.ai/inference/v1`,model:`accounts/fireworks/models/llama-v3p3-70b-instruct`},huggingface:{baseURL:`https://router.huggingface.co/v1`,model:`meta-llama/Llama-3.3-70B-Instruct`},deepinfra:{baseURL:`https://api.deepinfra.com/v1/openai`,model:`meta-llama/Meta-Llama-3.1-70B-Instruct`},sambanova:{baseURL:`https://api.sambanova.ai/v1`,model:`Meta-Llama-3.3-70B-Instruct`},moonshot:{baseURL:`https://api.moonshot.ai/v1`,model:`moonshot-v1-8k`}},ce={ollama:`http://localhost:11434/v1`,lmstudio:`http://localhost:1234/v1`,llamacpp:`http://localhost:8080/v1`,vllm:`http://localhost:8000/v1`,localai:`http://localhost:8080/v1`,dockermodelrunner:`http://localhost:12434/engines/v1`},R=e=>(t,n)=>new P({apiKey:t,baseURL:L[e].baseURL,model:n??L[e].model}),z={anthropic:(e,t)=>new F({apiKey:e,model:t??`claude-haiku-5-5`}),gemini:(e,t)=>new I({apiKey:e,model:t??`gemini-3.5-flash-lite`}),openai:R(`openai`),mistral:R(`mistral`),groq:R(`groq`),deepseek:R(`deepseek`),openrouter:R(`openrouter`),xai:R(`xai`),cerebras:R(`cerebras`),perplexity:R(`perplexity`),together:R(`together`),fireworks:R(`fireworks`),huggingface:R(`huggingface`),deepinfra:R(`deepinfra`),sambanova:R(`sambanova`),moonshot:R(`moonshot`)};function B(e,t,n){return t!==void 0&&t!==``?z[e](t,n):void 0}function V(e,t,n){if(t!==void 0&&t!==``)return new P({baseURL:n??ce[e],model:t})}function H(e,t){return B(e,t.apiKey,t.model)}function U(e,t){return V(e,t.model,t.baseURL)}const W=[`bg`,`cs`,`da`,`de`,`el`,`es`,`et`,`fi`,`fr`,`ga`,`hr`,`hu`,`it`,`lt`,`lv`,`mt`,`nl`,`pl`,`pt`,`ro`,`sk`,`sl`,`sv`],le=[`da`,`fi`,`is`,`no`,`sv`],ue=[`et`,`lv`,`lt`],de=[`bg`,`bs`,`el`,`hr`,`mk`,`ro`,`sq`,`sr`,`sl`],fe=[`nl`,`fr`,`lb`],pe=[.../* @__PURE__ */ new Set([...W,`no`,`is`,`sq`,`bs`,`mk`,`sr`,`uk`,`ru`,`be`,`ca`])],G=[`zh`,`ja`,`ko`,`mn`],K=[`hi`,`bn`,`ur`,`pa`,`ta`,`te`,`mr`,`gu`,`kn`,`ml`,`ne`,`si`],q=[`id`,`ms`,`my`,`km`,`lo`,`fil`,`th`,`vi`],J=[`kk`,`ky`,`tg`,`tk`,`uz`],Y=[`hy`,`az`,`ka`],me=[.../* @__PURE__ */ new Set([...G,...K,...q,...J,...Y])],he=[`ar`,`fa`,`he`,`tr`,`ku`],X=[`ar`,`fr`,`pt`,`sw`,`am`,`ha`,`yo`,`ig`,`zu`,`xh`,`af`,`so`,`rw`,`wo`],Z=[`en`,`fr`,`es`],Q=[`es`,`en`,`fr`,`ht`,`nl`],$=[`es`,`pt`,`qu`,`gn`,`ay`],ge={EU:W,EUROPE:pe,NORDIC:le,BALTIC:ue,BALKANS:de,BENELUX:fe,EAST_ASIA:G,SOUTH_ASIA:K,SOUTHEAST_ASIA:q,CENTRAL_ASIA:J,CAUCASUS:Y,ASIA:me,MIDDLE_EAST:he,AFRICA:X,NORTH_AMERICA:Z,CENTRAL_AMERICA_CARIBBEAN:Q,SOUTH_AMERICA:$,AMERICAS:[.../* @__PURE__ */ new Set([...Z,...Q,...$])],OCEANIA:[`en`,`mi`,`sm`,`to`],ASEAN:[`id`,`ms`,`my`,`km`,`lo`,`fil`,`th`,`vi`,`en`],MERCOSUR:[`es`,`pt`,`gn`],GCC:[`ar`,`en`],CIS:[`ru`,`be`,`hy`,`az`,`kk`,`ky`,`tg`,`uz`],G7:[`en`,`fr`,`de`,`it`,`ja`],FRANCOPHONE:[`fr`,`ht`,`wo`,`ln`,`rw`],WORLDWIDE_POPULAR:[`en`,`zh`,`hi`,`es`,`ar`,`bn`,`pt`,`ru`,`ja`,`de`,`fr`,`ko`,`it`,`tr`,`vi`,`id`,`ur`]};function _e(...e){if(e.length>0)throw v(`i18nWorks() no longer takes options. Move them to ${i} as the default export, then call i18nWorks() with no arguments in vite.config.`);return E(g)}export{F as AnthropicProvider,p as FallbackProvider,I as GeminiProvider,oe as HostedService,se as LocalService,P as OpenAICompatibleProvider,l as PartialTranslationError,_e as default,B as hosted,H as hostedFromEnv,V as local,U as localFromEnv,ge as locales,d as resolveProvider,re as tpick};
|
|
4
|
+
`}const T=`\0${_}`;function E(t){let n,r,a=``,s,l,u=!1;function d(){if(n.delivery!==`runtime`)return!1;for(let e of n.state.fileMessages.values())if(e.some(e=>e.component===`<module>`))return!0;return!1}function p(e){e.length&&s?.ws.send({type:`custom`,event:`i18n-works:update`,data:{catalogs:Object.fromEntries(e.map(e=>[e,n.state.catalogs.get(e)]))}})}function m(){if(!s||d()===u)return;let e=s.moduleGraph.getModuleById(T);e&&s.moduleGraph.invalidateModule(e),s.ws.send({type:`full-reload`})}async function g(e){try{p(await n.runSync(f(r.logger),e)),m()}catch(e){r.logger.error(b(`re-translation failed: ${e.message}`))}}function y(){clearTimeout(l),l=setTimeout(()=>void g(),150)}return{name:`i18n-works`,enforce:`pre`,config(r,i){let o=x.resolve(r.root??process.cwd()),s=t=>{h(t),n=new ee(t),a=e(o)},c=t(o,i);if(c instanceof Promise)return c.then(s);s(c)},configResolved(e){r=e,n.attach(e);let t=n.selectedLocale();if(t!==n.sourceLocale&&!n.locales.includes(t))throw v(`locale "${t}" is not one of the configured locales (${n.locales.join(`, `)}). Add it to locales in ${i}, or choose one of those locales for the locale option or the I18N_WORKS_LOCALE variable.`)},resolveId(e){if(e===`virtual:i18n-works`)return`\0${_}`},load(e){if(e===T)return u=d(),w(n.state.catalogFiles,n.sourceLocale,u)},configureServer(e){s=e,e.watcher.on(`add`,e=>{n.isSourceCandidate(e)&&y()}),e.watcher.on(`unlink`,e=>{n.state.fileMessages.has(e)&&y()}),e.watcher.on(`change`,t=>{x.resolve(t)===a&&e.restart().catch(e=>{let t=e instanceof Error?e.message:String(e);r.logger.error(b(`could not restart after ${i} changed: ${t}`))})})},closeBundle(){clearTimeout(l)},async buildStart(){await n.sync({info:e=>this.info(e),warn:e=>this.warn(e),error:e=>this.error(e)})},transform:{order:`pre`,async handler(e,t){let i=t.split(`?`)[0];if(!n.state.fileMessages.has(i))return null;let a=c(e);a!==n.state.hashOf(i)&&await n.runSync(f(r.logger),i);let s=n.state.fileMessages.get(i);if(!s||a!==n.state.hashOf(i))return n.state.warnedFiles.has(i)||(n.state.warnedFiles.add(i),this.warn(b(`${i} changed while it was being indexed; its messages are left untranslated.`))),null;if(s.length===0)return null;let l=n.isServing()?n.sourceLocale:n.selectedLocale(),u=n.isServing()||!!r.build.sourcemap,d=o(e,i,s,l,n.state.catalogs.get(l)??{},n.delivery===`runtime`,n.sourceLocale,u);return{code:d.code,map:d.map}}},async handleHotUpdate({file:e}){if(e.startsWith(n.localesDir()+x.sep))return[];n.state.fileMessages.has(e)&&await g(e)}}}const D=6e4;var O=class extends Error{retryable;retryAfterMs;constructor(e,t,n){super(e),this.retryable=t,this.retryAfterMs=n}};function ie(e,t=Date.now()){if(e===null||e===``)return;let n=Number(e);if(Number.isFinite(n))return Math.min(Math.max(n,0)*1e3,D);let r=Date.parse(e);if(!Number.isNaN(r))return Math.min(Math.max(r-t,0),D)}const ae=e=>new Promise(t=>setTimeout(t,e));function k(e){return`You are a professional software localization engine. Translate UI messages from ${e.sourceLocale} to ${e.targetLocale}. Preserve placeholders exactly. Some messages use ICU MessageFormat, such as {name}, {count, plural, one {# file} other {# files}} or {gender, select, ...}. Keep argument names, the keywords (one, other, select, plural, ...) and the # symbol unchanged, translate only the text inside the branches, and write the plural branches the target language needs. Messages marked "autoPlural" are natural-language count templates: convert their source to valid ICU plural syntax using the count argument, include language-appropriate categories (zero, one, two, few, many, other as needed), and include an explicit =0 branch when natural UI wording is different. A "hint" on an autoPlural message gives free-form source-author guidance for special count-dependent wording or thresholds; apply it naturally in the target language, using exact =N branches when a hint identifies specific counts and normal plural categories for ranges. Preserve {count} semantics and translate only the words inside branches. Respect context and UI conventions. When the source and target locales are the same, the source text is only a seed: rewrite it to apply the hint, keeping its placeholders. Keep the rewrite's length proportional to the seed: a one-word seed gets back one to three words, and a longer seed gets a proportionally longer rewrite, never a paragraph. A "hint" on a message without autoPlural is free-form author context, such as tone or audience; follow it in the wording while keeping every placeholder unchanged. Return ONLY a JSON object mapping message IDs to translated strings. Do not translate product names or code.`}function A(e){return JSON.stringify(e.map(e=>({id:e.id,text:e.source,context:e.context,...e.autoPlural===!0?{autoPlural:!0}:{},...e.hint!==void 0&&e.hint.length>0?{hint:e.hint}:{}})))}async function j(e){let t=e.status===408||e.status===409||e.status===429||e.status>=500;return await e.body?.cancel().catch(()=>void 0),new O(`Translation API failed (${e.status})`,t,ie(e.headers.get(`retry-after`)))}var M=class{options;slots;constructor(e){this.options=e,this.slots=new s(e.concurrency??4)}async translate(e){let t=Math.max(1,this.options.batchSize??40),n=[];for(let r=0;r<e.messages.length;r+=t)n.push(e.messages.slice(r,r+t));let r=await Promise.allSettled(n.map(t=>this.translateBatch({...e,messages:t}))),i={},a=[],o=0,s=0;if(r.forEach((e,t)=>{e.status===`fulfilled`?(s++,Object.assign(i,e.value)):(a.push(e.reason),o+=n[t].length)}),!a.length)return i;throw s?new l(`${o} messages failed to translate: ${a[0].message}`,i,o):a[0]}async translateBatch(e){let t=this.options.maxRetries??2,n=this.options.retryDelayMs??500;for(let r=0;;r++)try{return await this.slots.run(()=>this.request(e))}catch(e){if(e instanceof O&&!e.retryable||r>=t)throw e;let i=e instanceof O?e.retryAfterMs:void 0;await ae(i??n*2**r*(.5+Math.random()/2))}}async post(e,t,n){let r=await fetch(e,{method:`POST`,signal:AbortSignal.timeout(this.options.timeoutMs??6e4),headers:{...t,"content-type":`application/json`},body:JSON.stringify(n)});if(!r.ok)throw await j(r);return r.json()}async complete(e,t,n,r,i,a,o){let s=u(r,await this.post(e,t,n)),c=this.toCatalog(s.ok?i(s.value):void 0,a.messages);return a.onUsage?.({provider:o.provider,model:o.model,ids:a.messages.map(e=>e.id),...s.ok?o.tokens(s.value):{}}),c}toCatalog(e,t){let n=e?.trim().replace(/^```(?:json)?\s*|\s*```$/g,``);if(n===void 0||n===``)throw new O(`Translation provider returned no content`,!0);let i;try{i=JSON.parse(n)}catch{throw new O(`Translation provider returned invalid JSON`,!0)}let a=u(r,i);if(!a.ok)throw new O(`Translation provider returned a non-object`,!0);let o=new Set(t.map(e=>e.id)),s={};for(let[e,t]of Object.entries(a.value))o.has(e)&&typeof t==`string`&&t.trim()&&(s[e]=t);return s}};const N=`https://api.openai.com/v1`;var P=class extends M{async request(e){let{apiKey:t,model:r,baseURL:i=N}=this.options;return this.complete(`${i}/chat/completions`,t!==void 0&&t!==``?{Authorization:`Bearer ${t}`}:{},{model:r,temperature:0,response_format:{type:`json_object`},messages:[{role:`system`,content:k(e)},{role:`user`,content:A(e.messages)}]},n,e=>e.choices[0].message.content??void 0,e,{provider:i===N?`openai`:`openai-compatible`,model:r,tokens:e=>({inputTokens:e.usage?.prompt_tokens??void 0,outputTokens:e.usage?.completion_tokens??void 0})})}},F=class extends M{async request(e){return this.complete(`${this.options.baseURL??`https://api.anthropic.com/v1`}/messages`,{"x-api-key":this.options.apiKey,"anthropic-version":`2023-06-01`},{model:this.options.model,max_tokens:this.options.maxTokens??8192,system:k(e),messages:[{role:`user`,content:A(e.messages)}]},a,e=>e.content.filter(e=>e.type===`text`).map(e=>e.text??``).join(``),e,{provider:`anthropic`,model:this.options.model,tokens:e=>({inputTokens:e.usage?.input_tokens??void 0,outputTokens:e.usage?.output_tokens??void 0})})}},I=class extends M{async request(e){return this.complete(`${this.options.baseURL??`https://generativelanguage.googleapis.com/v1beta`}/models/${encodeURIComponent(this.options.model)}:generateContent`,{"x-goog-api-key":this.options.apiKey},{systemInstruction:{parts:[{text:k(e)}]},contents:[{role:`user`,parts:[{text:A(e.messages)}]}],generationConfig:{responseMimeType:`application/json`,maxOutputTokens:this.options.maxOutputTokens??8192}},t,e=>(e.candidates[0]?.content?.parts??[]).map(e=>e.text??``).join(``),e,{provider:`gemini`,model:this.options.model,tokens:e=>({inputTokens:e.usageMetadata?.promptTokenCount??void 0,outputTokens:e.usageMetadata?.candidatesTokenCount??void 0})})}};let oe=/* @__PURE__ */ function(e){return e.Anthropic=`anthropic`,e.Gemini=`gemini`,e.OpenAI=`openai`,e.Mistral=`mistral`,e.Groq=`groq`,e.DeepSeek=`deepseek`,e.OpenRouter=`openrouter`,e.XAI=`xai`,e.Cerebras=`cerebras`,e.Perplexity=`perplexity`,e.Together=`together`,e.Fireworks=`fireworks`,e.HuggingFace=`huggingface`,e.DeepInfra=`deepinfra`,e.SambaNova=`sambanova`,e.Moonshot=`moonshot`,e}({}),se=/* @__PURE__ */ function(e){return e.Ollama=`ollama`,e.LMStudio=`lmstudio`,e.LlamaCpp=`llamacpp`,e.VLLM=`vllm`,e.LocalAI=`localai`,e.DockerModelRunner=`dockermodelrunner`,e}({});const L={openai:{model:`gpt-4.1-mini`},mistral:{baseURL:`https://api.mistral.ai/v1`,model:`mistral-small-latest`},groq:{baseURL:`https://api.groq.com/openai/v1`,model:`llama-3.3-70b-versatile`},deepseek:{baseURL:`https://api.deepseek.com/v1`,model:`deepseek-chat`},openrouter:{baseURL:`https://openrouter.ai/api/v1`,model:`openai/gpt-4.1-mini`},xai:{baseURL:`https://api.x.ai/v1`,model:`grok-3-mini`},cerebras:{baseURL:`https://api.cerebras.ai/v1`,model:`llama-3.3-70b`},perplexity:{baseURL:`https://api.perplexity.ai`,model:`sonar`},together:{baseURL:`https://api.together.xyz/v1`,model:`meta-llama/Llama-3.3-70B-Instruct-Turbo`},fireworks:{baseURL:`https://api.fireworks.ai/inference/v1`,model:`accounts/fireworks/models/llama-v3p3-70b-instruct`},huggingface:{baseURL:`https://router.huggingface.co/v1`,model:`meta-llama/Llama-3.3-70B-Instruct`},deepinfra:{baseURL:`https://api.deepinfra.com/v1/openai`,model:`meta-llama/Meta-Llama-3.1-70B-Instruct`},sambanova:{baseURL:`https://api.sambanova.ai/v1`,model:`Meta-Llama-3.3-70B-Instruct`},moonshot:{baseURL:`https://api.moonshot.ai/v1`,model:`moonshot-v1-8k`}},ce={ollama:`http://localhost:11434/v1`,lmstudio:`http://localhost:1234/v1`,llamacpp:`http://localhost:8080/v1`,vllm:`http://localhost:8000/v1`,localai:`http://localhost:8080/v1`,dockermodelrunner:`http://localhost:12434/engines/v1`},R=e=>(t,n)=>new P({apiKey:t,baseURL:L[e].baseURL,model:n??L[e].model}),z={anthropic:(e,t)=>new F({apiKey:e,model:t??`claude-haiku-5-5`}),gemini:(e,t)=>new I({apiKey:e,model:t??`gemini-3.5-flash-lite`}),openai:R(`openai`),mistral:R(`mistral`),groq:R(`groq`),deepseek:R(`deepseek`),openrouter:R(`openrouter`),xai:R(`xai`),cerebras:R(`cerebras`),perplexity:R(`perplexity`),together:R(`together`),fireworks:R(`fireworks`),huggingface:R(`huggingface`),deepinfra:R(`deepinfra`),sambanova:R(`sambanova`),moonshot:R(`moonshot`)};function B(e,t,n){return t!==void 0&&t!==``?z[e](t,n):void 0}function V(e,t,n){if(t!==void 0&&t!==``)return new P({baseURL:n??ce[e],model:t})}function H(e,t){return B(e,t.apiKey,t.model)}function U(e,t){return V(e,t.model,t.baseURL)}const W=[`bg`,`cs`,`da`,`de`,`el`,`es`,`et`,`fi`,`fr`,`ga`,`hr`,`hu`,`it`,`lt`,`lv`,`mt`,`nl`,`pl`,`pt`,`ro`,`sk`,`sl`,`sv`],le=[`da`,`fi`,`is`,`no`,`sv`],ue=[`et`,`lv`,`lt`],de=[`bg`,`bs`,`el`,`hr`,`mk`,`ro`,`sq`,`sr`,`sl`],fe=[`nl`,`fr`,`lb`],pe=[.../* @__PURE__ */ new Set([...W,`no`,`is`,`sq`,`bs`,`mk`,`sr`,`uk`,`ru`,`be`,`ca`])],G=[`zh`,`ja`,`ko`,`mn`],K=[`hi`,`bn`,`ur`,`pa`,`ta`,`te`,`mr`,`gu`,`kn`,`ml`,`ne`,`si`],q=[`id`,`ms`,`my`,`km`,`lo`,`fil`,`th`,`vi`],J=[`kk`,`ky`,`tg`,`tk`,`uz`],Y=[`hy`,`az`,`ka`],me=[.../* @__PURE__ */ new Set([...G,...K,...q,...J,...Y])],he=[`ar`,`fa`,`he`,`tr`,`ku`],X=[`ar`,`fr`,`pt`,`sw`,`am`,`ha`,`yo`,`ig`,`zu`,`xh`,`af`,`so`,`rw`,`wo`],Z=[`en`,`fr`,`es`],Q=[`es`,`en`,`fr`,`ht`,`nl`],$=[`es`,`pt`,`qu`,`gn`,`ay`],ge={EU:W,EUROPE:pe,NORDIC:le,BALTIC:ue,BALKANS:de,BENELUX:fe,EAST_ASIA:G,SOUTH_ASIA:K,SOUTHEAST_ASIA:q,CENTRAL_ASIA:J,CAUCASUS:Y,ASIA:me,MIDDLE_EAST:he,AFRICA:X,NORTH_AMERICA:Z,CENTRAL_AMERICA_CARIBBEAN:Q,SOUTH_AMERICA:$,AMERICAS:[.../* @__PURE__ */ new Set([...Z,...Q,...$])],OCEANIA:[`en`,`mi`,`sm`,`to`],ASEAN:[`id`,`ms`,`my`,`km`,`lo`,`fil`,`th`,`vi`,`en`],MERCOSUR:[`es`,`pt`,`gn`],GCC:[`ar`,`en`],CIS:[`ru`,`be`,`hy`,`az`,`kk`,`ky`,`tg`,`uz`],G7:[`en`,`fr`,`de`,`it`,`ja`],FRANCOPHONE:[`fr`,`ht`,`wo`,`ln`,`rw`],WORLDWIDE_POPULAR:[`en`,`zh`,`hi`,`es`,`ar`,`bn`,`pt`,`ru`,`ja`,`de`,`fr`,`ko`,`it`,`tr`,`vi`,`id`,`ur`]};function _e(...e){if(e.length>0)throw v(`i18nWorks() no longer takes options. Move them to ${i} as the default export, then call i18nWorks() with no arguments in vite.config.`);return E(g)}export{F as AnthropicProvider,p as FallbackProvider,I as GeminiProvider,oe as HostedService,se as LocalService,P as OpenAICompatibleProvider,l as PartialTranslationError,_e as default,B as hosted,H as hostedFromEnv,V as local,U as localFromEnv,ge as locales,d as resolveProvider,re as tpick};
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import{o as e}from"./icu-Cui2dM71.js";import{S as t,a as n,c as r,d as i,i as a,l as o,o as s,r as c,s as l,t as u,u as d,w as f,x as p}from"./sync-DrfpPJa0.js";import{existsSync as m,readFileSync as h}from"node:fs";import g from"node:path";import{readFile as _,readdir as v,rm as y}from"node:fs/promises";import{emitKeypressEvents as b}from"node:readline";import{parseArgs as x}from"node:util";const S=`› `,C=(e,t,n)=>Math.min(Math.max(e,t),n),ee=e=>e.replace(/\s*\r?\n\s*/g,` `);function w(e,t,n){let r=Math.max(1,n),i=C(e-Math.floor(r/2),0,Math.max(0,t-r));return{start:i,end:Math.min(t,i+r)}}const T=(e,t)=>e.map(({role:e,text:n})=>e===void 0?n:t(e,n)).join(``),E=e=>e.reduce((e,{text:t})=>e+t.length,0);function te(e,t){let n=e.map(({role:e,text:t})=>({role:e,text:ee(t)}));if(E(n)<=t)return n;let r=[],i=Math.max(0,t-1);for(let e of n){let t=e.text.slice(0,i);t.length>0&&r.push({role:e.role,text:t}),i-=t.length}return[...r,{role:r.at(-1)?.role,text:`…`}]}function D(e,t){let n=te(e,t),r=E(n);return r<t?[...n,{text:` `.repeat(t-r)}]:n}const O=(e,t,n)=>T(te(e,t),n);function k(e,t,n){return e?n(`cursor`,S)+n(`selected`,T(t,n)):` `+T(t,n)}function A(e){let t=[];for(let[n,[r,i]]of e.entries())n>0&&t.push({role:`hint`,text:` · `}),t.push({role:`key`,text:r},{role:`hint`,text:i});return t}const j=(e,t)=>[{role:`hint`,text:e.padEnd(11)},...t],M=e=>[{text:e}],N=e=>[{role:`title`,text:e}],P=()=>({calls:0,inputTokens:0,outputTokens:0,cost:0,unpriced:0});function ne(e,t){e.calls+=1,e.inputTokens+=t.inputTokens??0,e.outputTokens+=t.outputTokens??0,t.cost===void 0?e.unpriced+=1:e.cost+=t.cost}function re(e,t){let n=/* @__PURE__ */ new Map;for(let r of e){let e=t(r),i=n.get(e)??P();ne(i,r),n.set(e,i)}return[...n].map(([e,t])=>({label:e,totals:t}))}function ie(e){let t=P();for(let n of e)ne(t,n);return{totals:t,models:re(e,e=>`${e.provider} ${e.model}`).sort((e,t)=>t.totals.cost-e.totals.cost||e.label.localeCompare(t.label)),months:re(e,e=>e.at.slice(0,7)).sort((e,t)=>e.label.localeCompare(t.label))}}const F=ie([]);function ae(e){if(e.calls===e.unpriced)return`unknown`;let t=`$${e.cost.toFixed(6)}`;return e.unpriced===0?t:`${t} (+${e.unpriced} unpriced)`}function oe(e){return[N(`Totals`),j(`calls`,M(String(e.calls))),j(`tokens in`,M(String(e.inputTokens))),j(`tokens out`,M(String(e.outputTokens))),j(`cost`,M(ae(e))),[]]}function se(e,t,n){let r=Math.max(t.length,...n.map(({label:e})=>e.length)),i=[{role:`hint`,text:t.padEnd(r)},{role:`hint`,text:`calls`.padStart(8)},{role:`hint`,text:`tokens in`.padStart(12)},{role:`hint`,text:`tokens out`.padStart(12)},{role:`hint`,text:` cost`}];return[N(e),i,...n.map(({label:e,totals:t})=>[{text:e.padEnd(r)},{text:String(t.calls).padStart(8)},{text:String(t.inputTokens).padStart(12)},{text:String(t.outputTokens).padStart(12)},{text:` ${ae(t)}`}]),[]]}function ce(e){return e.totals.calls===0?[[{role:`hint`,text:`No AI calls recorded yet. Enable the costs option to record them.`}]]:[...oe(e.totals),...se(`Models`,`model`,e.models),...se(`Months (UTC)`,`month`,e.months)]}function le(e,t,n,r){let i=ce(t),a=Math.max(1,n.height-4),{start:o,end:s}=w(e,i.length,a),c=r(`rule`,`─`.repeat(n.width));return[O([{role:`title`,text:`Costs`},{role:`hint`,text:` estimated USD`}],n.width,r),c,...i.slice(o,s).map(e=>O(e,n.width,r)),c,O(A([[`↑/↓`,` scroll`],[`PgUp/PgDn`,` page`],[`Esc`,` languages`],[`q`,` quit`]]),n.width,r)].join(`
|
|
2
|
+
`)}function ue(e){try{return h(e,`utf8`)}catch{return}}function de(e,t){let n=/* @__PURE__ */ new Map;return{entry:t=>Object.hasOwn(e,t)?e[t]:void 0,readSource:e=>(n.has(e)||n.set(e,ue(g.resolve(t,e))),n.get(e))}}function I(e,t){return Object.hasOwn(e,t)?e[t]:void 0}function L(e,t){return[.../* @__PURE__ */ new Set([...Object.keys(e.messages),...Object.keys(t.messages)])].map(n=>({id:n,source:I(e.sources,n)??I(t.sources,n),left:I(e.messages,n),right:I(t.messages,n)}))}function R(e){return new Set(e.flatMap(({file:e})=>Object.keys(e.messages))).size}const z=({file:e})=>Object.keys(e.messages).length;function fe(e,t){let n=/* @__PURE__ */ new Map;for(let{file:t}of e)for(let[e,r]of Object.entries(t.sources))n.has(e)||n.set(e,r);let r=Object.fromEntries(n);return e.map(e=>e.locale===t?{...e,file:{...e.file,messages:{...r,...e.file.messages}}}:e)}const B={entry:()=>void 0,readSource:()=>void 0},V=` │ `;function pe(e){return e===void 0?[]:[{role:`source`,text:`source: `},e.source===void 0?{role:`missing`,text:`(not recorded)`}:{role:`source`,text:e.source}]}function me(e,t){let n={column:Math.max(8,Math.floor((e-2-3)/2)),pane:0};if(!t)return n;let r=C(Math.floor(e*.4),24,48),i=Math.floor((e-2-6-r)/2);return i>=12?{column:i,pane:r}:n}function he(e,t){if(!(!Number.isInteger(t)||t<0||t>e.length))return e.slice(0,t).split(`
|
|
3
|
+
`).length}function ge(e,t,n){if(e===void 0)return[[{role:`missing`,text:`(source file cannot be read)`}]];if(t===void 0)return[[{role:`missing`,text:`(the file is shorter than the recorded location)`}]];let r=e.split(`
|
|
4
|
+
`),i=t-1,{start:a,end:o}=w(i,r.length,n),s=String(o).length;return r.slice(a,o).map((e,t)=>{let n=a+t===i;return[n?{role:`focus`,text:S}:{text:` `},{role:`hint`,text:String(a+t+1).padStart(s)},{text:` `},{role:n?`focus`:void 0,text:e.replace(/\r$/,``).replaceAll(` `,` `)}]})}function _e(e,t,n){if(e===void 0)return[[{role:`hint`,text:`No message selected.`}]];let r=N(e.id),i=t.entry(e.id);if(i===void 0)return[r,[{role:`missing`,text:`(not in the registry)`}]];let{file:a,start:o}=d(i.location),s=t.readSource(a),c=s===void 0?void 0:he(s,o),l=[r,j(`component`,M(i.component)),j(`status`,M(i.status)),j(`first seen`,M(i.firstSeen.slice(0,10))),j(`last seen`,M(i.lastSeen.slice(0,10))),...i.hint===void 0?[]:[j(`hint`,M(i.hint))],...i.autoPlural===!0?[j(`plural`,M(`automatic`))]:[],j(`file`,M(g.relative(process.cwd(),a))),j(`line`,c===void 0?[{role:`missing`,text:`unknown`}]:M(String(c)))],u=Math.max(0,n-l.length-2);return[...l,[],N(`preview`),...ge(s,c,u)].slice(0,n)}function ve(e,t,n,r,i){let a=t[e.left],o=t[e.right],s=L(a.file,o.file),c=R(t),{column:l,pane:u}=me(n.width,e.preview),d=(e,t)=>[...D(e,l),{role:`rule`,text:V},...D(t,l)],f=e=>e===void 0?[{role:`missing`,text:`(missing)`}]:[{text:e}],p=Math.max(1,n.height-5),{start:m,end:h}=w(e.row,s.length,p),g=u===0?[]:_e(s.at(e.row),i,p),_=e=>u===0?``:T([{role:`rule`,text:V},...D(e,u)],r),v=n.width-(u===0?0:u+3),y=s.length===0?[T(D([{role:`hint`,text:`no messages in either file.`}],v),r)]:s.slice(m,h).map((t,n)=>k(m+n===e.row,d(f(t.left),f(t.right)),r)),b=Array.from({length:p},(e,t)=>(y.at(t)??``)+_(g.at(t)??[])),x=r(`rule`,`─`.repeat(n.width));return[k(!1,d([{role:`left`,text:`${a.locale} (${z(a)}/${c})`}],[{role:`right`,text:`${o.locale} (${z(o)}/${c})`}]),r)+_(N(`Details`)),x,...b,x,O(pe(s.at(e.row)),n.width,r),O(A([[`←/→`,` left file`],[`Tab/Shift+Tab`,` right file`],[`↑/↓`,` row`],[`PgUp/PgDn`,` page`],[`Esc`,` languages`],[`q`,` quit`],[`p`,` toggle preview`]]),n.width,r)].join(`
|
|
5
|
+
`)}const H=(e,t)=>(e+t)%t;function ye(e,t,n,r,i=!1,a=F){return t.name===`q`||t.ctrl===!0&&t.name===`c`?null:e.view===`compare`?Se(e,t,n):e.view===`costs`?Ce(e,t,a):e.view===`prune`?{view:`languages`,selected:e.selected}:be(e.selected,t,n,r,i)}function be(e,t,n,r,i){let a=n.length-1;switch(t.name){case`up`:case`k`:return{view:`languages`,selected:C(e-1,0,a)};case`down`:case`j`:return{view:`languages`,selected:C(e+1,0,a)};case`return`:case`enter`:return a<0?{view:`languages`,selected:e}:xe(e,n,r);case`x`:return i?{view:`prune`,selected:e}:{view:`languages`,selected:e};case`c`:return{view:`costs`,selected:e,row:0};default:return{view:`languages`,selected:e}}}function xe(e,t,n){let r=t.findIndex(({locale:e})=>e===n);return{view:`compare`,left:e,right:r!==-1&&r!==e?r:H(e+1,t.length),row:0,preview:!0}}function U(e,t,n){return Math.max(0,L(e[t].file,e[n].file).length-1)}function Se(e,t,n){let r=n.length,i=U(n,e.left,e.right),a=t=>({...e,row:C(t,0,i)}),o=(t,r)=>({...e,left:t,right:r,row:C(e.row,0,U(n,t,r))});switch(t.name){case`up`:case`k`:return a(e.row-1);case`down`:case`j`:return a(e.row+1);case`pageup`:return a(e.row-10);case`pagedown`:return a(e.row+10);case`home`:return a(0);case`end`:return a(i);case`left`:return o(H(e.left-1,r),e.right);case`right`:return o(H(e.left+1,r),e.right);case`tab`:return o(e.left,H(e.right+(t.shift===!0?-1:1),r));case`p`:return{...e,preview:!e.preview};case`escape`:case`backspace`:return{view:`languages`,selected:e.left};default:return e}}function Ce(e,t,n){let r=Math.max(0,ce(n).length-1),i=t=>({...e,row:C(t,0,r)});switch(t.name){case`up`:case`k`:return i(e.row-1);case`down`:case`j`:return i(e.row+1);case`pageup`:return i(e.row-10);case`pagedown`:return i(e.row+10);case`home`:return i(0);case`end`:return i(r);case`escape`:case`backspace`:return{view:`languages`,selected:e.selected};default:return e}}const we={title:[`1;4`,`22;24`],language:[`1`,`22`],left:[`1;36`,`22;39`],right:[`1;35`,`22;39`],source:[`34`,`39`],complete:[`32`,`39`],partial:[`33`,`39`],empty:[`31`,`39`],missing:[`3;31`,`23;39`],cursor:[`1;36`,`22;39`],selected:[`7`,`27`],key:[`1`,`22`],hint:[`2`,`22`],rule:[`2`,`22`],focus:[`1;33`,`22;39`]},W=(e,t)=>t;function Te(e){return e?(e,t)=>{let[n,r]=we[e];return`\x1b[${n}m${t}\x1b[${r}m`}:W}function Ee(e,t){let n=t.NO_COLOR;return e===!0&&(n===void 0||n===``)&&t.TERM!==`dumb`}function De(e){return{status:`unavailable`,message:e instanceof Error?e.message:String(e)}}function Oe(e){if(e?.status!==`ready`)return!1;let{orphanedEntries:t,staleKeys:n,unconfiguredFiles:r}=e.summary;return t+n+r>0}function ke(e,t){return e===0?`empty`:e===t?`complete`:`partial`}const Ae=e=>`${(e*100).toFixed(1)}%`;function je(e){return[{text:` (${Ae(e.coverage)})`},{text:` · ${e.missing.length} missing · ${e.outdated.length} outdated · ${e.orphanedKeys.length} orphaned`}]}function Me(e,t,n){let r=R(e),i=Math.max(...e.map(({locale:e})=>e.length));return e.map(e=>{let a=e.locale===t?[{role:`source`,text:` (source)`}]:[],o=n?.locales.find(({locale:t})=>t===e.locale),s=o===void 0?[{role:ke(z(e),r),text:`${z(e)}/${r}`},{text:` translated`}]:[{role:ke(o.translated,o.total),text:`${o.translated}/${o.total}`},{text:` translated`},...je(o)];return[{role:`language`,text:e.locale.padEnd(i)},{text:` `},...s,...a]})}function Ne(e){if(e===void 0)return[];let{total:t,active:n,orphaned:r}=e.registry,i=e.averageCoverage===null?[]:[{text:` · average coverage ${Ae(e.averageCoverage)}`}];return[{role:`title`,text:`Registry:`},{text:` ${t} entries (${n} active, ${r} orphaned)`},...i]}function Pe(e){let t=Object.entries(e?.registry.byComponent??{}).sort(([e],[t])=>e.localeCompare(t));return t.length===0?[]:[{role:`hint`,text:`By component:`},{text:` ${t.map(([e,t])=>`${e} ${t}`).join(`, `)}`}]}function Fe(e,t,n,r=W){let i=Me(e,t,n).map(e=>T(e,r));return n===void 0?i:[...[Ne(n),Pe(n)].filter(e=>e.length>0).map(e=>T(e,r)),``,...i]}function Ie(e,t,n,r,i=W,a=B,o,s,c,l=F){return e.view===`compare`?ve(e,t,r,i,a):e.view===`costs`?le(e.row,l,r,i):Re(e,t,n,r,i,o,s,c)}function Le(e){let t={role:`title`,text:`Prune:`};if(e===void 0)return[];if(e.status===`unavailable`)return[t,{role:`missing`,text:` unavailable (${e.message})`}];if(!Oe(e))return[t,{text:` nothing to remove.`}];let{orphanedEntries:n,staleKeys:r,unconfiguredFiles:i}=e.summary;return[t,{text:` ${[n>0&&`${n} orphaned ${n===1?`entry`:`entries`}`,r>0&&`${r} stale ${r===1?`key`:`keys`}`,i>0&&`${i} unconfigured locale ${i===1?`file`:`files`}`].filter(e=>typeof e==`string`).join(`, `)}.`}]}function Re(e,t,n,r,i,a,o,s){let{selected:c}=e,l=Me(t,n,o),{start:u,end:d}=w(c,l.length,r.height-8),f=l.slice(u,d).map((e,t)=>k(u+t===c,D(e,r.width-2),i)),p=e.view===`prune`?A([[`y`,` prune now`],[`any other key`,` cancel`]]):A([[`↑/↓`,` move`],[`Enter`,` compare`],[`x`,` prune`],[`t`,` translate`],[`c`,` costs`],[`q`,` quit`]]);return[O([{role:`title`,text:`Translation files:`},{text:` ${t.length} languages, source `},{role:`language`,text:n}],r.width,i),O(Le(a),r.width,i),O(Ne(o),r.width,i),O(Pe(o),r.width,i),O(s===void 0?[]:[{text:s}],r.width,i),``,...f,``,O(p,r.width,i)].join(`
|
|
6
|
+
`)}const ze={width:80,height:24};function Be(e){let t=(e,t)=>e!==void 0&&e>0?e:t;return{width:t(e.columns,ze.width),height:t(e.rows,ze.height)}}function Ve(e,t,n){let{input:r,output:i}=n,a=Te(Ee(i.isTTY,n.env??process.env));return new Promise(o=>{let s={view:`languages`,selected:0},c={languages:e,inspector:n.inspector??B,notice:n.notice,report:n.report,costs:n.costs??F},l=!1,u=()=>{i.write(`\x1B[H\x1B[2J`+Ie(s,c.languages,t,Be(i),a,c.inspector,c.notice,c.report,c.status,c.costs))},d=async(e,t)=>{l=!0;try{c=await t()}catch(e){c={...c,notice:De(e)}}l=!1;let n=Math.max(0,c.languages.length-1);s={view:`languages`,selected:Math.min(e,n)},u()},f=async(e,t)=>{l=!0,c={...c,status:`Translating every locale...`},u();try{c=await t()}catch(e){c={...c,status:`Translation failed: ${e instanceof Error?e.message:String(e)}`}}l=!1;let n=Math.max(0,c.languages.length-1);s={view:`languages`,selected:Math.min(e,n)},u()},p=(e,r)=>{if(r===void 0||l)return;if(s.view===`prune`&&r.name===`y`&&n.prune!==void 0){d(s.selected,n.prune);return}if(s.view===`languages`&&r.name===`t`&&n.translate!==void 0){f(s.selected,n.translate);return}let i=n.prune!==void 0&&Oe(c.notice),a=ye(s,r,c.languages,t,i,c.costs);a===null?m():(s=a,u())},m=()=>{r.off(`keypress`,p),i.off(`resize`,u),r.isTTY===!0&&r.setRawMode?.(!1),r.pause(),i.write(`\x1B[?25h\x1B[?1049l`),o()};b(r),r.isTTY===!0&&r.setRawMode?.(!0),i.write(`\x1B[?1049h\x1B[?25l`),r.on(`keypress`,p),i.on(`resize`,u),r.resume(),u()})}const G=`.i18n-works`,K=e=>console.warn(e);function q(e){let t=g.resolve(e.root??process.cwd()),n=g.resolve(t,e.directory??`.i18n-works`,`registry.json`);return{root:t,registryFile:n,localesDir:g.join(g.dirname(n),`locales`)}}function He(e,t){let n=Object.keys(t),r={};for(let e of n)r[Ue(e)]={type:typeof t[e]==`boolean`?`boolean`:`string`};let{values:i}=x({args:e,options:r,strict:!0,allowPositionals:!1}),a={...t};for(let e of n){let n=i[Ue(e)];n!==void 0&&(a[e]=typeof t[e]==`boolean`?!0:typeof t[e]==`number`?Number(n):String(n))}return a}function Ue(e){return e.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`)}async function J(e){return m(e)?(await v(e)).filter(e=>e.endsWith(`.json`)):[]}async function We(e={}){let{registryFile:t,localesDir:r,root:o}=q(e),c=e.onWarning??K;if(!m(t))return{registryFile:t,registry:void 0,removedEntries:[],unconfiguredFiles:[],catalogs:[]};let l=e.retentionMinutes??43200;if(!(l>=0))throw Error(`retentionMinutes must be a number of minutes, 0 or more`);let u=await p(o,{command:`build`,mode:`production`});f(u);let d=/* @__PURE__ */ new Set([u.sourceLocale??`en`,...u.locales]),h=await a(t,c),_=i(h,l),v=new Set(Object.values(h.entries).filter(e=>e.status===`active`).map(e=>e.id)),y=[],b=[];for(let e of await J(r)){let t=g.join(r,e);if(!d.has(g.basename(e,`.json`))){y.push(t);continue}let i=n(await s(t,c),v);i.removed.length&&b.push({file:t,pruned:i.file,removed:i.removed})}return{registryFile:t,registry:h,removedEntries:_,unconfiguredFiles:y,catalogs:b}}async function Y(e={}){let t=await We(e),{registry:n,registryFile:i}=t;if(n===void 0)return{registryFile:i,registryFound:!1,removedEntries:[],removedLocaleFiles:[],catalogs:[]};t.removedEntries.length&&await l(i,n);for(let e of t.unconfiguredFiles)await y(e);for(let e of t.catalogs)await r(e.file,e.pruned);return{registryFile:i,registryFound:!0,removedEntries:t.removedEntries,removedLocaleFiles:t.unconfiguredFiles,catalogs:t.catalogs.map(({file:e,removed:t})=>({file:e,removed:t}))}}const Ge=e=>{let t={};for(let n of e)t[n]=(t[n]??0)+1;return t};function Ke(e,t){let n=Object.values(e.entries),r=n.filter(e=>e.status===`active`),i=new Set(r.map(e=>e.id)),a=n.filter(e=>e.status===`orphaned`).sort((e,t)=>e.lastSeen.localeCompare(t.lastSeen)||e.id.localeCompare(t.id)),o=Object.keys(t).sort((e,t)=>e.localeCompare(t)).map(e=>{let n=t[e],a=r.filter(e=>!Object.hasOwn(n.messages,e.id)).map(e=>e.id),o=r.filter(e=>Object.hasOwn(n.messages,e.id)&&n.sources[e.id]!==e.source).map(e=>e.id),s=[.../* @__PURE__ */ new Set([...Object.keys(n.messages),...Object.keys(n.sources)])].filter(e=>!i.has(e)),c=r.length,l=c-a.length;return{locale:e,translated:l,total:c,coverage:c===0?1:l/c,missing:a.sort(),outdated:o.sort(),orphanedKeys:s.sort()}}),s=o.length===0?null:o.reduce((e,t)=>e+t.coverage,0)/o.length;return{registry:{total:n.length,active:r.length,orphaned:a.length,byComponent:Ge(r.map(e=>e.component)),orphans:a},locales:o,averageCoverage:s}}async function qe(e,t,n){let r=(await J(e)).filter(e=>!e.endsWith(`.sources.json`)).map(e=>({name:e,locale:e.slice(0,-5)})).filter(({locale:e})=>e!==t),i=await Promise.all(r.map(({name:t})=>s(g.join(e,t),n)));return Object.fromEntries(r.map(({locale:e},t)=>[e,i[t]]))}async function X(e={}){let{registryFile:t,localesDir:n}=q(e),r=e.onWarning??K;if(!m(t))return{registryFile:t,registryFound:!1};let[i,o]=await Promise.all([a(t,r),qe(n,e.sourceLocale??`en`,r)]);return{registryFile:t,registryFound:!0,report:Ke(i,o)}}async function Je(e={}){let{root:t}=q(e),n=await p(t,{command:`build`,mode:`production`});f(n);let r=new u(e.directory===void 0?n:{...n,directory:e.directory});r.attach({root:t,command:`build`});let i=r.localesDir(),a=await Ye(i),o=[];return await r.runSync({info:()=>void 0,warn:e=>o.push(e),error:e=>o.push(e)}),{changedLocales:[...await Ye(i)].filter(([e,t])=>e!==r.sourceLocale&&a.get(e)!==t).map(([e])=>e),warnings:o}}async function Ye(e){let t=await v(e).catch(e=>{if(e.code===`ENOENT`)return[];throw e}),n=await Promise.all(t.filter(e=>e.endsWith(`.json`)).map(async t=>[g.basename(t,`.json`),await _(g.join(e,t),`utf8`)]));return new Map(n)}async function Z(e={}){let{localesDir:t}=q(e),n=e.onWarning??K,r=(await J(t)).filter(e=>!e.endsWith(`.sources.json`)).sort(),i=await Promise.all(r.map(e=>s(g.join(t,e),n)));return{localesDir:t,languages:fe(r.map((e,t)=>({locale:e.slice(0,-5),file:i[t]})),e.sourceLocale??`en`)}}async function Xe(e={}){let{localesDir:t,languages:n}=await Z(e);if(n.length===0)return{localesDir:t,opened:!1};let r=e.input??process.stdin,i=e.output??process.stdout;if(r.isTTY!==!0||i.isTTY!==!0)throw Error("browse needs an interactive terminal; use listLanguages(), or `vite-i18n browse --list`, to print the languages instead.");let[{inspector:a,costs:o},s,{report:c}]=await Promise.all([Qe(e),Q(e),X(e)]);return await Ve(n,e.sourceLocale??`en`,{input:r,output:i,inspector:a,notice:s,report:c,costs:o,prune:async()=>(await Y(e),$e(e)),translate:async()=>{let t=await Je(e).then(({changedLocales:e,warnings:t})=>Ze(e,t),e=>`Translation failed: ${e instanceof Error?e.message:String(e)}`);return{...await $e(e),status:t}}}),{localesDir:t,opened:!0}}function Ze(e,t){let n=e.length>0?`Translated ${e.join(`, `)}.`:`Translations are up to date.`;return t.length>0?`${n} ${t[0]}`:n}async function Qe(e){let{registryFile:t,root:n}=q(e),r=await a(t,e.onWarning??K);return{inspector:de(r.entries,n),costs:ie(Object.values(r.costs))}}async function Q(e){try{let{removedEntries:t,unconfiguredFiles:n,catalogs:r}=await We(e);return{status:`ready`,summary:{orphanedEntries:t.length,staleKeys:r.reduce((e,t)=>e+t.removed.length,0),unconfiguredFiles:n.length}}}catch(e){return De(e)}}async function $e(e){let[{languages:t},{inspector:n,costs:r},i,{report:a}]=await Promise.all([Z(e),Qe(e),Q(e),X(e)]);return{languages:t,inspector:n,notice:i,report:a,costs:r}}const et=/* @__PURE__ */ new Set([`help`,`--help`,`-h`]),$=`Usage: vite-i18n [command] [options]
|
|
7
|
+
|
|
8
|
+
Commands:
|
|
9
|
+
prune Remove orphaned registry entries and the locale files and keys they leave behind
|
|
10
|
+
browse Browse the translation files in an interactive terminal, with registry counts and coverage (default)
|
|
11
|
+
|
|
12
|
+
Options shared by every command:
|
|
13
|
+
--root <dir> Vite root that holds ${t} (default: the current directory)
|
|
14
|
+
--directory <dir> Catalogue directory, relative to --root (default: ${G})
|
|
15
|
+
|
|
16
|
+
prune:
|
|
17
|
+
--retention-minutes <n> Remove orphans last seen longer ago than n minutes (default: 30 days)
|
|
18
|
+
--debug Log every removal
|
|
19
|
+
|
|
20
|
+
browse:
|
|
21
|
+
--source-locale <locale> The source locale, compared against (default: en)
|
|
22
|
+
--list Print the languages, their coverage and the registry counts instead of opening the browser
|
|
23
|
+
--json With --list, print the registry statistics as JSON, including the missing, outdated and
|
|
24
|
+
orphaned IDs of each locale`;async function tt(n){let r=He(n,{root:process.cwd(),directory:G,retentionMinutes:o,debug:!1});if(!(r.retentionMinutes>=0))throw Error(`--retention-minutes must be a number of minutes, 0 or more`);let i=await Y(r);if(!i.registryFound)console.log(e(`no registry found at ${i.registryFile}; nothing to prune.`));else{if(r.debug){for(let e of i.removedEntries)c(`removed ${e.id} ${JSON.stringify(e.source)} (last seen ${e.lastSeen})`);for(let e of i.removedLocaleFiles)c(`removed ${e}; its locale is not in ${t}`);for(let{file:e,removed:t}of i.catalogs)for(let n of t)c(`removed ${n} from ${e}`)}console.log(e(`removed ${i.removedEntries.length} registry entries orphaned for more than ${r.retentionMinutes} minutes.`)),i.catalogs.length&&console.log(e(`removed stale keys from ${i.catalogs.length} locale files.`)),i.removedLocaleFiles.length&&console.log(e(`removed ${i.removedLocaleFiles.length} locale files for locales not in ${t}.`))}}async function nt(t){let n=He(t,{root:process.cwd(),directory:G,sourceLocale:`en`,list:!1,json:!1});if(n.list){let[{localesDir:t,languages:r},{report:i,registryFile:a}]=await Promise.all([Z(n),X(n)]);if(n.json){console.log(i?JSON.stringify(i,null,2):e(`no registry found at ${a}; nothing to report.`));return}if(r.length===0){console.log(e(`no locale files found in ${t}; nothing to browse.`));return}let o=Te(Ee(process.stdout.isTTY,process.env));console.log(Fe(r,n.sourceLocale,i,o).join(`
|
|
25
|
+
`));return}let r=await Xe(n);r.opened||console.log(e(`no locale files found in ${r.localesDir}; nothing to browse.`))}async function rt(t){let[n=``,...r]=t,i=n===``||n.startsWith(`-`),a=i?`browse`:n,o=i?t:r;if(et.has(a)||o.some(e=>e===`--help`||e===`-h`))return console.log($),0;try{switch(a){case`prune`:return await tt(o),0;case`browse`:return await nt(o),0;default:return console.error(e(`unknown command "${a}"`)),console.error($),1}}catch(t){return console.error(e(t.message)),1}}export{X as a,Je as i,Xe as n,Y as o,Z as r,G as s,rt as t};
|
package/dist/runtime/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{n as e,r as t,t as n}from"../pick-Bpdsmz-0.js";import r from"intl-messageformat";import{o as i,t as a}from"../icu-Cui2dM71.js";var o=class{limit;entries=/* @__PURE__ */ new Map;constructor(e){this.limit=e}get(e){let t=this.entries.get(e);return t!==void 0&&(this.entries.delete(e),this.entries.set(e,t)),t}set(e,t){this.entries.delete(e),this.entries.size>=this.limit&&this.entries.delete(this.entries.keys().next().value),this.entries.set(e,t)}};const s=new o(500),c=new o(500),l=/* @__PURE__ */ new Set([`AT`,`BE`,`CY`,`DE`,`EE`,`ES`,`FI`,`FR`,`GR`,`HR`,`IE`,`IT`,`LT`,`LU`,`LV`,`MT`,`NL`,`PT`,`SI`,`SK`]);function u(e){let t=new Intl.Locale(e).maximize().region;return t!==void 0&&l.has(t)?`EUR`:t===`GB`?`GBP`:t===`JP`?`JPY`:t===`CA`?`CAD`:t===`AU`?`AUD`:t===`CN`?`CNY`:t===`IN`?`INR`:`USD`}function d(e,t){let n={};for(let r of e.matchAll(/\{[^,{}]+,\s*number,\s*([^{}]+)\}/g)){let e=r[1].trim();e===`currency`?n.currency={style:`currency`,currency:u(t)}:/^[A-Z]{3}$/.test(e)&&(n[e]={style:`currency`,currency:e})}return n}function f(e){let t={people:`person`,children:`child`,men:`man`,women:`woman`,mice:`mouse`,teeth:`tooth`,feet:`foot`,geese:`goose`};return Object.hasOwn(t,e.toLowerCase())?m(e,t[e.toLowerCase()]):/[^aeiou]ies$/i.test(e)?e.slice(0,-3)+(e.endsWith(`IES`)?`Y`:`y`):/sses$/i.test(e)?e.slice(0,-2):/ses$/i.test(e)?/(uses|oses|ises|eses)$/i.test(e)?e.slice(0,-2):e.slice(0,-1):/(xes|zes|ches|shes)$/i.test(e)?e.slice(0,-2):/s$/i.test(e)&&!/ss$/i.test(e)?e.slice(0,-1):e}function p(e){let t={person:`people`,child:`children`,man:`men`,woman:`women`,mouse:`mice`,tooth:`teeth`,foot:`feet`,goose:`geese`};return Object.hasOwn(t,e.toLowerCase())?m(e,t[e.toLowerCase()]):/[^aeiou]y$/i.test(e)?e.slice(0,-1)+(e.endsWith(`Y`)?`IES`:`ies`):/(s|x|z|ch|sh)$/i.test(e)?e+`es`:e+`s`}function m(e,t){return e===e.toUpperCase()?t.toUpperCase():e[0]===e[0].toUpperCase()?t[0].toUpperCase()+t.slice(1):t}function h(e,t){if(!/^There\s+/i.test(e))return e;let n=t?{are:`is`,have:`has`,were:`was`,do:`does`}:{is:`are`,has:`have`,was:`were`,does:`do`};return e.replace(/\b(are|is|have|has|were|was|do|does)\b/gi,e=>{let t=e.toLowerCase(),r=n[t];return r===void 0?e:e===e.toUpperCase()?r.toUpperCase():e[0]===e[0].toUpperCase()?r[0].toUpperCase()+r.slice(1):r})}function g(e,t,n){return!e.includes(`{count}`)||typeof n.count!=`number`?y(e,t,n):y(_(e,t)??e,t,n)}function _(e,t){let n=`${t}\u0000${e}`,r=c.get(n);if(r!==void 0)return r;let i=v(e,t);return c.set(n,i),i}function v(e,t){if(t.split(/[-_]/)[0].toLowerCase()!==`en`)return null;let[n,r]=e.split(`{count}`,2),i=r.match(/[A-Za-z][A-Za-z-]*\w*/)?.[0];if(i===void 0)return null;let a=f(i),o=p(a),s=r.replace(i,a),c=r.replace(i,o),l=n.trim(),u=h(l,!0),d=h(l,!1),m=d?`${d} no`:`No`,g=`${u} # ${s.trim()}`.trim(),_=`${d} # ${c.trim()}`.trim();return`{count, plural, =0 {${`${m} ${c.trim()}`.trim()}} one {${g}} other {${_}}}`}function y(e,t,n){let o=`${t}\u0000${e}
|
|
1
|
+
import{n as e,r as t,t as n}from"../pick-Bpdsmz-0.js";import r from"intl-messageformat";import{o as i,t as a}from"../icu-Cui2dM71.js";var o=class{limit;entries=/* @__PURE__ */ new Map;constructor(e){this.limit=e}get(e){let t=this.entries.get(e);return t!==void 0&&(this.entries.delete(e),this.entries.set(e,t)),t}set(e,t){this.entries.delete(e),this.entries.size>=this.limit&&this.entries.delete(this.entries.keys().next().value),this.entries.set(e,t)}};const s=new o(500),c=new o(500),l=/* @__PURE__ */ new Set([`AT`,`BE`,`CY`,`DE`,`EE`,`ES`,`FI`,`FR`,`GR`,`HR`,`IE`,`IT`,`LT`,`LU`,`LV`,`MT`,`NL`,`PT`,`SI`,`SK`]);function u(e){let t=new Intl.Locale(e).maximize().region;return t!==void 0&&l.has(t)?`EUR`:t===`GB`?`GBP`:t===`JP`?`JPY`:t===`CA`?`CAD`:t===`AU`?`AUD`:t===`CN`?`CNY`:t===`IN`?`INR`:`USD`}function d(e,t){let n={};for(let r of e.matchAll(/\{[^,{}]+,\s*number,\s*([^{}]+)\}/g)){let e=r[1].trim();e===`currency`?n.currency={style:`currency`,currency:u(t)}:/^[A-Z]{3}$/.test(e)&&(n[e]={style:`currency`,currency:e})}return n}function f(e){let t={people:`person`,children:`child`,men:`man`,women:`woman`,mice:`mouse`,teeth:`tooth`,feet:`foot`,geese:`goose`};return Object.hasOwn(t,e.toLowerCase())?m(e,t[e.toLowerCase()]):/[^aeiou]ies$/i.test(e)?e.slice(0,-3)+(e.endsWith(`IES`)?`Y`:`y`):/sses$/i.test(e)?e.slice(0,-2):/ses$/i.test(e)?/(uses|oses|ises|eses)$/i.test(e)?e.slice(0,-2):e.slice(0,-1):/(xes|zes|ches|shes)$/i.test(e)?e.slice(0,-2):/s$/i.test(e)&&!/ss$/i.test(e)?e.slice(0,-1):e}function p(e){let t={person:`people`,child:`children`,man:`men`,woman:`women`,mouse:`mice`,tooth:`teeth`,foot:`feet`,goose:`geese`};return Object.hasOwn(t,e.toLowerCase())?m(e,t[e.toLowerCase()]):/[^aeiou]y$/i.test(e)?e.slice(0,-1)+(e.endsWith(`Y`)?`IES`:`ies`):/(s|x|z|ch|sh)$/i.test(e)?e+`es`:e+`s`}function m(e,t){return e===e.toUpperCase()?t.toUpperCase():e[0]===e[0].toUpperCase()?t[0].toUpperCase()+t.slice(1):t}function h(e,t){if(!/^There\s+/i.test(e))return e;let n=t?{are:`is`,have:`has`,were:`was`,do:`does`}:{is:`are`,has:`have`,was:`were`,does:`do`};return e.replace(/\b(are|is|have|has|were|was|do|does)\b/gi,e=>{let t=e.toLowerCase(),r=n[t];return r===void 0?e:e===e.toUpperCase()?r.toUpperCase():e[0]===e[0].toUpperCase()?r[0].toUpperCase()+r.slice(1):r})}function g(e,t,n){return!e.includes(`{count}`)||typeof n.count!=`number`?y(e,t,n):y(_(e,t)??e,t,n)}function _(e,t){let n=`${t}\u0000${e}`,r=c.get(n);if(r!==void 0)return r;let i=v(e,t);return c.set(n,i),i}function v(e,t){if(t.split(/[-_]/)[0].toLowerCase()!==`en`)return null;let[n,r]=e.split(`{count}`,2),i=r.match(/[A-Za-z][A-Za-z-]*\w*/)?.[0];if(i===void 0)return null;let a=f(i),o=p(a),s=r.replace(i,a),c=r.replace(i,o),l=n.trim(),u=h(l,!0),d=h(l,!1),m=d?`${d} no`:`No`,g=`${u} # ${s.trim()}`.trim(),_=`${d} # ${c.trim()}`.trim();return`{count, plural, =0 {${`${m} ${c.trim()}`.trim()}} one {${g}} other {${_}}}`}function y(e,t,n){let o=`${t}\u0000${e}`,c=s.get(o);if(c===void 0){try{let n=d(e,t),i=Object.keys(n).length?{number:n}:void 0;c=new r(e,t,i,a)}catch(n){return s.set(o,null),console.warn(i(`could not format "${e}" for "${t}".`),n),e}s.set(o,c)}if(c===null)return e;try{return[c.format(n)].flat().join(``)}catch(n){return console.warn(i(`could not format "${e}" for "${t}".`),n),e}}export{e as createLocaleLoader,g as formatAutoPluralMessage,y as formatMessage,t as resolveLocale,n as tpick};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import{a as e,i as t,n,o as r,r as i}from"./icu-Cui2dM71.js";import{createRequire as a}from"node:module";import{existsSync as o}from"node:fs";import{loadConfigFromFile as s}from"vite";import c,{basename as l,extname as u}from"node:path";import{createHash as d,randomUUID as f}from"node:crypto";import{parseSync as p}from"rolldown/utils";import m from"magic-string";import{glob as h,mkdir as g,readFile as _,rename as v,rm as y,stat as ee,writeFile as te}from"node:fs/promises";const b=Symbol(`failed`),x=(e,t)=>(e.push({path:[],message:t}),b),S=(e,t,n,r)=>{let i=r.length,a=e.check(t,r);if(a===b)for(let e=i;e<r.length;e++)r[e]={path:[n,...r[e].path],message:r[e].message};return a},C=e=>`must be ${e}`,w=(e,t)=>({expected:e,check:(n,r)=>t(n)?n:x(r,C(e))}),T=w(`a string`,e=>typeof e==`string`),E=w(`a finite number`,e=>typeof e==`number`&&Number.isFinite(e)),D=w(`a boolean`,e=>typeof e==`boolean`),O=w(`an object`,e=>typeof e==`object`&&!!e||typeof e==`function`);function k(e){let t=typeof e==`string`?JSON.stringify(e):String(e);return w(t,t=>t===e)}function A(e,t,n){return{expected:n,check:(r,i)=>{let a=e.check(r,i);return a===b?b:t(a)?a:x(i,C(n))}}}function j(e,{nonEmpty:t=!1}={}){let n=t?`a non-empty array`:`an array`;return{expected:n,check:(r,i)=>{if(!Array.isArray(r)||t&&r.length===0)return x(i,C(n));let a=!1,o=[];for(let[t,n]of r.entries()){let r=S(e,n,t,i);r===b?a=!0:o.push(r)}return a?b:o}}}function M(...e){let t=e.map(e=>e.expected).join(` or `);return{expected:t,check:(n,r)=>{for(let t of e){let e=t.check(n,[]);if(e!==b)return e}return x(r,C(t))}}}function N(e){return{...e,optional:!0}}function P(e,t=`ignore`){let n=Object.entries(e),r=new Set(Object.keys(e));return{expected:`an object`,check:(e,i)=>{let a=O.check(e,i);if(a===b)return b;let o=!1,s={};for(let[e,t]of n){if(!Object.hasOwn(a,e)){t.optional!==!0&&(i.push({path:[e],message:`is required`}),o=!0);continue}let n=S(t,a[e],e,i);n===b?o=!0:s[e]=n}if(t===`reject`)for(let e of Object.keys(a))r.has(e)||(i.push({path:[e],message:`is not a known key`}),o=!0);return o?b:s}}}function F(e,t){let n=[],r=e.check(t,n);return r===b?{ok:!1,issues:n}:{ok:!0,value:r}}const I=e=>N(M(e,k(void 0))),L=N(M(E,k(null))),ne=P({choices:j(P({message:P({content:N(M(T,k(null)))})}),{nonEmpty:!0}),usage:N(M(P({prompt_tokens:L,completion_tokens:L}),k(null)))}),re=P({content:j(P({type:T,text:N(T)})),usage:N(M(P({input_tokens:L,output_tokens:L}),k(null)))}),ie=P({candidates:j(P({content:N(P({parts:N(j(P({text:N(T)})))}))})),usageMetadata:N(M(P({promptTokenCount:L,candidatesTokenCount:L}),k(null)))}),ae=O,oe=P({messages:O,sources:O}),se=P({id:T,source:T,component:T,fingerprint:T,autoPlural:I(D),hint:I(T),location:T,status:M(k(`active`),k(`orphaned`)),firstSeen:T,lastSeen:T}),ce=P({id:T,at:T,sourceLocale:T,locale:T,provider:T,model:T,ids:j(T),inputTokens:I(E),outputTokens:I(E),cost:I(E)}),le=P({version:k(1),entries:O,costs:N(O)}),ue=A(T,e=>e.length>0,`a non-empty string`),de=/^[A-Za-z]{2,3}(?:-[A-Za-z0-9]{1,8})*$/,R=A(T,e=>de.test(e),`a locale tag`),fe=P({locales:j(R),sourceLocale:I(R),delivery:I(M(k(`build`),k(`runtime`))),locale:I(R),include:I(j(T)),exclude:I(j(T)),directory:I(ue),provider:I(O),failOnMissingProvider:I(D),onAmbiguous:I(M(k(`warn`),k(`error`))),orphanRetentionMinutes:I(M(A(E,e=>e>=0,`a number >= 0`),k(1/0))),localeConcurrency:I(A(E,e=>e>=1,`a number >= 1`)),debug:I(D),costs:I(D)},`reject`),z=`vite-i18n.config.js`;function pe(e){return c.resolve(e,z)}function me(t){let n=F(fe,t);if(n.ok)return;let r=n.issues.map(e=>`${e.path.join(`.`)||`options`}: ${e.message}`).join(`; `);throw e(`invalid options in ${z} (${r}). Fix or remove these keys; the README lists every option.`)}const he=async(t,n)=>{let r=pe(t);if(!o(r))throw e(`${z} was not found in ${t}. Create it next to vite.config with the plugin options as the default export, for example:\n\n export default {
|
|
2
|
+
locales: ["en", "de"],
|
|
3
|
+
sourceLocale: "en",
|
|
4
|
+
};\n\nThe README lists every option.`);try{return(await s(n,r,t))?.config}catch(t){let n=t instanceof Error?t.message:String(t);throw e(`could not load ${z}: ${n}. Check the file for syntax errors and make sure it has a default export that is an object.`)}};function B(e){return e.replace(/\s+/g,` `).trim()}function ge(e){let t=e.autoPlural===!0?`tt`:`t`;return d(`sha256`).update(`${t}\u0000${B(e.source)}\u0000${B(e.hint??``)}`).digest(`hex`).slice(0,24)}function V(e,t){let n=p(t,e,{lang:`tsx`,sourceType:`unambiguous`});if(n.errors.length)throw SyntaxError(`${t}: ${n.errors[0].message}`);return n.program}function _e(e,t){let n=[],r=e=>{if(t(e,n)!==!1){n.push(e);for(let t of Object.keys(e)){if(t===`parent`)continue;let n=e[t];Array.isArray(n)?n.forEach(e=>H(e)&&r(e)):H(n)&&r(n)}n.pop()}};r(e)}function H(e){return typeof e==`object`&&!!e&&typeof e.type==`string`}function U(e){return H(e)&&e.type===`Literal`&&typeof e.value==`string`}const ve=a(import.meta.url);function ye(t,n,r){try{return ve(t)}catch{throw e(`${r} files need the "${n}" package. Install it with your package manager.`)}}let be;function xe(e,t){be??=ye(`@astrojs/compiler/sync`,`@astrojs/compiler`,`Astro`);let{ast:n,diagnostics:r}=be.parse(e,{position:!0}),i=r.find(e=>e.severity===1);if(i)throw SyntaxError(`${t}: ${i.text}`);let a=Se(e),o=l(t,u(t)),s=[],c=(n,r)=>{let i=e.slice(n,r);i.trim()!==``&&s.push({root:V(`[${i}\n]`,t),offset:n-1,component:o})},d=e=>{if(e.type===`comment`)return;if(e.type===`expression`)return f(e.children??[]);let t=a(e.position.start.offset);return e.type===`text`?{start:t,end:t+e.value.length}:{start:t,end:a(e.position.end.offset)}},f=e=>{let t=e.map(d).filter(e=>e!==void 0);if(t.length!==0)return{start:t[0].start,end:t[t.length-1].end}},p=t=>{let n=a(t.position.start.offset),r=e.indexOf(t.value,n+t.name.length);c(r,r+t.value.length)},m=e=>{if(e.type===`frontmatter`){let n=a(e.position.start.offset)+3;s.push({root:V(e.value,t),offset:n,component:o})}else if(e.type===`expression`){let t=d(e);t&&c(t.start,t.end)}else{for(let t of e.attributes??[])t.kind===`expression`&&p(t);for(let t of e.children??[])m(t)}};return m(n),s}function Se(e){let t=Buffer.byteLength(e);if(t===e.length)return e=>e;let n=new Uint32Array(t+1),r=0;for(let t=0;t<e.length;){let i=e.codePointAt(t),a=Buffer.byteLength(String.fromCodePoint(i));n.fill(t,r,r+a),r+=a,t+=i>65535?2:1}return n[r]=e.length,e=>n[e]}let Ce;function W(e,t){Ce??=ye(`svelte/compiler`,`svelte`,`Svelte`);try{return Ce.parse(e,{modern:!0})}catch(e){throw SyntaxError(`${t}: ${e.message}`,{cause:e})}}function we(e,t){let n=W(e,t),r=l(t,u(t)),i=[];return n.module&&i.push({root:n.module.content,offset:0}),n.instance&&i.push({root:n.instance.content,offset:0,component:r}),i.push({root:n.fragment,offset:0,component:r}),i}function Te(e,t){let n=W(e,t),r=n.instance??n.module;return r?r.content.start:0}function Ee(e,t){switch(u(t)){case`.svelte`:return{regions:we(e,t)};case`.astro`:return{regions:xe(e,t)};default:return{regions:[{root:V(e,t),offset:0}]}}}const G=`virtual:i18n-works`,K=`i18n-works/runtime`,q=`__i18nWorksT`,De=`__i18nWorksFormat`,Oe=`__i18nWorksFormatAutoPlural`,ke=String.raw`\s*(["'])[^"'\n]*\1[ \t]*;?[ \t]*(?:\r?\n|$)`,J=new RegExp(ke,`y`);function Ae(e){let t=0;if(e.startsWith(`#!`)){let n=e.indexOf(`
|
|
5
|
+
`);t=n===-1?e.length:n+1}J.lastIndex=t;for(let n=J.exec(e);n;n=J.exec(e))t=J.lastIndex;return t}function je(e,t){switch(u(t)){case`.svelte`:return{offset:Te(e,t),format:e=>`\n${e}`};case`.astro`:return{offset:3,format:e=>`\n${e}`};default:return{offset:Ae(e),format:e=>`${e}\n`}}}function Me(e,t,n,r,i,a=!1,o=`en`,s=!0){let c=new m(e),l=e=>r===o&&e.hint===void 0?e.source:i[e.id]??e.source;for(let e of n){if(e.valuesStart===void 0){let t=a?`${q}(${JSON.stringify(e.id)}, ${JSON.stringify(e.source)})`:JSON.stringify(l(e));c.overwrite(e.start,e.end,t);continue}let t;t=a&&e.autoPlural===!0?`__i18nWorksLookupAutoPlural(${JSON.stringify(e.id)}, ${JSON.stringify(e.source)}, `:a?`${q}(${JSON.stringify(e.id)}, ${JSON.stringify(e.source)}, `:e.autoPlural===!0?`${Oe}(${JSON.stringify(l(e))}, ${JSON.stringify(r)}, `:`${De}(${JSON.stringify(l(e))}, ${JSON.stringify(r)}, `,c.overwrite(e.start,e.valuesStart,t)}let u=[];if(a&&n.length&&u.push(`import { lookup as ${q} } from "${G}";`),a&&n.some(e=>e.autoPlural===!0)&&u.push(`import { lookupAutoPlural as __i18nWorksLookupAutoPlural } from "${G}";`),!a&&n.some(e=>e.valuesStart!==void 0)&&u.push(`import { formatMessage as ${De} } from "${K}";`),!a&&n.some(e=>e.autoPlural===!0)&&u.push(`import { formatAutoPluralMessage as ${Oe} } from "${K}";`),u.length){let n=je(e,t);c.appendLeft(n.offset,n.format(u.join(`
|
|
6
|
+
`)))}return{code:c.toString(),map:s?c.generateMap({source:t,hires:!0,includeContent:!1}):null}}const Ne=`<module>`,Pe=e=>/[A-Za-z]/.test(e);function Fe(e,t){try{n(e)}catch(e){throw SyntaxError(`${t}: t() message is not valid ICU MessageFormat: ${e.message}`,{cause:e})}}function Ie(e){let t={t:/* @__PURE__ */ new Set,tt:/* @__PURE__ */ new Set,tauto:/* @__PURE__ */ new Set};for(let{root:n}of e)if(n.type===`Program`){for(let e of n.body)if(e.type===`ImportDeclaration`&&e.source.value===`virtual:i18n-works`)for(let n of e.specifiers){if(n.type!==`ImportSpecifier`)continue;let e=n.imported.type===`Identifier`?n.imported.name:n.imported.value;e===`t`&&t.t.add(n.local.name),e===`tt`&&t.tt.add(n.local.name),e===`tauto`&&t.tauto.add(n.local.name)}}return t}const Le=(e,t)=>e.type===`FunctionExpression`?!(t?.type===`MethodDefinition`||t?.type===`Property`&&(t.method||t.kind!==`init`)):e.type===`FunctionDeclaration`||e.type===`ArrowFunctionExpression`;function Re(e,t){let n=e.length-1;for(;n>=0&&!Le(e[n],e[n-1]);)n--;if(n<0)return t;let r=e[n],i=n>0?e[n-1]:void 0;return i?.type===`VariableDeclarator`&&i.id.type===`Identifier`?i.id.name:r.type===`FunctionDeclaration`&&r.id?r.id.name:`<anonymous>`}function ze(e,t,n){if(n===void 0&&!e.includes(`virtual:i18n-works`))return[];let{regions:r}=n??Ee(e,t),i=Ie(r),a=[];for(let e of r){let{root:n,offset:r}=e;_e(n,(n,o)=>{if(n.type!==`CallExpression`||n.callee.type!==`Identifier`)return;let s=i.tt.has(n.callee.name),c=s||i.tauto.has(n.callee.name);if(!c&&!i.t.has(n.callee.name))return;let l=i.tauto.has(n.callee.name)&&U(n.arguments.at(1));if(n.arguments.length>(c&&!l?3:2))return;let[u]=n.arguments,d=l?void 0:n.arguments.at(1),f=c?n.arguments.at(l?1:2):void 0;if(!U(u)||d?.type===`SpreadElement`||f!==void 0&&!U(f))return;let p=B(u.value);if(!p||!Pe(p))return;d&&Fe(p,t);let m=U(f)?B(f.value):void 0;a.push({source:p,file:t,start:r+n.start,end:r+n.end,valuesStart:d===void 0?void 0:r+d.start,autoPlural:s||void 0,hint:m!==void 0&&m.length>0?m:void 0,component:Re(o,e.component??`<module>`),fingerprint:ge({source:p,autoPlural:s,hint:m})})})}return a.sort((e,t)=>e.start-t.start)}const Be=e=>JSON.stringify(e,null,2)+`
|
|
7
|
+
`,Ve=e=>d(`sha256`).update(e).digest(`hex`);async function He(e,t,n){let i;try{i=await _(e,`utf8`)}catch(i){return i.code===`ENOENT`||n?.(r(`could not read ${e}: ${i.message}`)),t}try{return JSON.parse(i)}catch(i){let a=`${e}.corrupt-${Date.now()}`;return await v(e,a).catch(()=>void 0),n?.(r(`${e} is not valid JSON (${i.message}); moved to ${a} and starting fresh.`)),t}}async function Ue(e,t){await g(c.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${f()}.tmp`;await te(n,t,`utf8`),await v(n,e)}async function We(e,t){await _(e,`utf8`).catch(()=>void 0)!==t&&await Ue(e,t)}var Ge=class extends Error{partial;failed;constructor(e,t,n){super(e),this.partial=t,this.failed=n,this.name=`PartialTranslationError`}};function Ke(e){return e instanceof Error&&e.name===`PartialTranslationError`&&`partial`in e}var qe=class{providers;onFallback;constructor(e,t=()=>{}){this.providers=e,this.onFallback=t}async translate(e){let t={},n=e.messages,r,i;for(let[a,{name:o,provider:s}]of this.providers.entries()){try{Object.assign(t,await s.translate({...e,messages:n}))}catch(e){r??=e,i=e,Ke(e)&&Object.assign(t,e.partial);let s=this.providers.at(a+1);s&&n.some(e=>!Object.hasOwn(t,e.id))&&this.onFallback(`${o} failed (${Je(e)}); sending the rest to ${s.name}.`)}if(n=n.filter(e=>!Object.hasOwn(t,e.id)),!n.length)return t}throw Object.keys(t).length===0?r:new Ge(`${n.length} messages failed to translate: ${Je(i)}`,t,n.length)}};const Je=e=>e instanceof Error?e.message:String(e),Ye=e=>typeof e==`object`&&!!e&&typeof e.translate==`function`;function Xe(t,n){if(t===void 0)return;if(Ye(t))return t;let{primary:r,...i}=t,a=[];for(let[t,n]of Object.entries(i))if(n!==void 0){if(!Ye(n))throw e(`provider "${t}" must be an object with a translate(input) method. Use hosted(), local(), or a provider class exported by i18n-works.`);a.push({name:t,provider:n})}if(r!==void 0){let t=a.findIndex(e=>e.name===r);if(t<0)throw e(`primary provider "${r}" is not configured. Add it under provider in vite-i18n.config.js, or change primary to one of: ${a.map(e=>e.name).join(`, `)||`none`}.`);a.unshift(...a.splice(t,1))}if(a.length!==0)return a.length===1?a[0].provider:new qe(a,n)}async function Ze(e,t,n){let r=Array(e.length),i=0;return await Promise.all(Array.from({length:Math.min(Math.max(1,t),e.length)},async()=>{for(;i<e.length;){let t=i++;try{r[t]={status:`fulfilled`,value:await n(e[t])}}catch(e){r[t]={status:`rejected`,reason:e}}}})),r}var Qe=class{available;waiters=[];constructor(e){this.available=Math.max(1,Math.floor(e))}async run(e){await this.acquire();try{return await e()}finally{this.release()}}acquire(){return this.available>0?(this.available--,Promise.resolve()):new Promise(e=>this.waiters.push(e))}release(){let e=this.waiters.shift();e?e():this.available++}};const $e={anthropic:{"claude-haiku-5-5":{input:.1,output:.5},"claude-haiku-4-5":{input:1,output:5}},openai:{"gpt-4.1":{input:2,output:8},"gpt-4.1-mini":{input:.4,output:1.6},"gpt-4o":{input:2.5,output:10},"gpt-4o-mini":{input:.15,output:.6},"gpt-5-mini":{input:.25,output:2},"gpt-5-nano":{input:.05,output:.4}}};function et(e){let t=$e[e.provider]?.[e.model];if(t!==void 0&&e.inputTokens!==void 0&&e.outputTokens!==void 0)return(e.inputTokens*t.input+e.outputTokens*t.output)/1e6}const tt=e=>console.log(`[${t} costs] ${(/* @__PURE__ */ new Date()).toISOString()} ${e}`);function nt(e,t,n){let r=n.inputTokens===void 0||n.outputTokens===void 0?`tokens not reported`:`${n.inputTokens} input + ${n.outputTokens} output tokens`,i=et(n),a=i===void 0?`cost unknown`:`cost $${i.toFixed(6)}`;tt(`${e} -> ${t} ${n.ids.length} messages (${n.ids.join(`, `)}) via ${n.provider} ${n.model}: ${r}, ${a}`)}function rt(e,t,n){tt(`${e} -> ${t} ${n} messages translated, provider reported no usage: cost unknown`)}const it=43200,at=()=>({version:1,entries:{},costs:{}});function ot(e,t,n,r,i=(/* @__PURE__ */ new Date()).toISOString()){let a=`call_${f().replaceAll(`-`,``).slice(0,16)}`,o=et(r);return e.costs[a]={id:a,at:i,sourceLocale:t,locale:n,provider:r.provider,model:r.model,ids:r.ids,...r.inputTokens===void 0?{}:{inputTokens:r.inputTokens},...r.outputTokens===void 0?{}:{outputTokens:r.outputTokens},...o===void 0?{}:{cost:o}},a}function st(e,t){return`${e}:${String(t).padStart(12,`0`)}`}function ct(e){let t=e.lastIndexOf(`:`);return{file:e.slice(0,t),start:Number(e.slice(t+1))}}function lt(e){let{file:t,start:n}=ct(e);return st(t,n)}function Y(e,t){if(e.length<2)return;let n=new Map(e.map(e=>[e,t(e)]));e.sort((e,t)=>n.get(e).localeCompare(n.get(t)))}function ut(e,t){let n=Array(e.length),r=/* @__PURE__ */ new Set,i=/* @__PURE__ */ new Map;for(let e of t){let t=i.get(e.component)??{entries:[],next:0};t.entries.push(e),i.set(e.component,t)}e.forEach((e,t)=>{let a=i.get(e.component),o=a&&a.next<a.entries.length?a.entries[a.next++]:void 0;o&&(n[t]=o,r.add(o))});let a=t.filter(e=>!r.has(e)),o=0;return e.forEach((e,t)=>{n[t]===void 0&&o<a.length&&(n[t]=a[o++])}),n}function dt(t,n){let r=(/* @__PURE__ */ new Date()).toISOString(),i=Object.values(t.entries),a=/* @__PURE__ */ new Map;for(let e of i){let t=a.get(e.fingerprint)??[];t.push(e),a.set(e.fingerprint,t)}let o=/* @__PURE__ */ new Map;for(let e of n){let t=o.get(e.fingerprint)??[];t.push(e),o.set(e.fingerprint,t)}let s=/* @__PURE__ */ new Map,c=/* @__PURE__ */ new Set,l=[];for(let[e,n]of o){let i=a.get(e)??[],o=i.filter(e=>e.status===`active`),u=i.filter(e=>e.status===`orphaned`);Y(n,e=>st(e.file,e.start)),Y(o,e=>lt(e.location)),Y(u,e=>lt(e.location)),n.length!==o.length&&(n.length>1||o.length>1)&&l.push(n[0].source);let d=ut(n,o),p=n.flatMap((e,t)=>d[t]===void 0?[t]:[]),m=ut(p.map(e=>n[e]),u);p.forEach((e,t)=>{d[e]=m[t]});for(let[e,i]of n.entries()){let n=d[e];if(n)s.set(i,n.id),n.status=`active`,n.lastSeen=r,n.source=i.source,n.component=i.component,n.autoPlural=i.autoPlural,n.hint=i.hint,n.location=`${i.file}:${i.start}`,c.add(n.id);else{let e=`msg_${f().replaceAll(`-`,``).slice(0,16)}`;s.set(i,e),t.entries[e]={id:e,source:i.source,component:i.component,fingerprint:i.fingerprint,autoPlural:i.autoPlural,hint:i.hint,location:`${i.file}:${i.start}`,status:`active`,firstSeen:r,lastSeen:r},c.add(e)}}}for(let e of Object.values(t.entries))c.has(e.id)||(e.status=`orphaned`);return{registry:t,ambiguous:l,messages:n.map(t=>{let n=s.get(t);if(n===void 0)throw e(`no message ID was assigned to ${t.file}:${t.start}`);return{...t,id:n}})}}function ft(e,t,n=Date.now()){let r=n-t*6e4,i=[];for(let[t,n]of Object.entries(e.entries))n.status===`orphaned`&&Date.parse(n.lastSeen)<=r&&(delete e.entries[t],i.push(n));return i}const pt=()=>({messages:{},sources:{}});function X(t,n){if(!de.test(n))throw e(`"${n}" is not a valid locale tag.`);return c.join(t,`${n}.json`)}const mt=(e,t,n)=>{let i={};for(let[a,o]of Object.entries(e))typeof o==`string`?i[a]=o:t?.(r(`dropped non-text value for "${a}" in ${n}.`));return i};async function ht(e,t){let n=await He(e,null,t),r=F(oe,n);return r.ok?{messages:mt(r.value.messages,t,e),sources:mt(r.value.sources,t,e)}:pt()}const gt=(e,t)=>We(e,Be(t));function _t(e,t){let n={},r=[];for(let[i,a]of Object.entries(e))t.has(i)?n[i]=a:r.push(i);return{catalog:n,removed:r}}function vt(e,t){let n=_t(e.messages,t),r=_t(e.sources,t);return{file:{messages:n.catalog,sources:r.catalog},removed:[.../* @__PURE__ */ new Set([...n.removed,...r.removed])]}}async function yt(e,t){let n=await He(e,null,t);if(n===null)return at();let i=F(le,n);if(!i.ok)return t?.(r(`${e} has an unsupported format; message IDs will be regenerated.`)),at();let a={};for(let[n,o]of Object.entries(i.value.entries)){let i=F(se,o);i.ok?a[n]=i.value:t?.(r(`dropped invalid registry entry "${n}" in ${e}.`))}let o={};for(let[n,a]of Object.entries(i.value.costs??{})){let i=F(ce,a);i.ok?o[n]=i.value:t?.(r(`dropped invalid cost record "${n}" in ${e}.`))}return{version:1,entries:a,costs:o}}async function bt(e,t){await We(e,Be(t))}const Z=e=>console.log(`[${t} debug] ${(/* @__PURE__ */ new Date()).toISOString()} ${e}`);async function xt(e){let{provider:t,sourceLocale:n,locale:r,requests:a,previous:o,debug:s,costs:c}=e,{messages:l,sources:u}=vt(o,new Set(a.map(e=>e.id))).file,d=a.filter(e=>!Object.hasOwn(l,e.id)||u[e.id]!==e.source),f={},p=0,m,h=[];if(d.length&&t){if(s===!0)for(let e of d)Z(`sent ${n} -> ${r} ${e.id}: ${JSON.stringify(e.source)} (context: ${e.context})`);let e=c===!0?e=>{h.push(e),nt(n,r,e)}:void 0;try{f=await t.translate({sourceLocale:n,targetLocale:r,messages:d,...e===void 0?{}:{onUsage:e}})}catch(e){if(!Ke(e))throw e;f=e.partial,p=e.failed,m=e.message}if(c===!0&&h.length===0&&rt(n,r,Object.keys(f).length),s===!0)for(let e of d){let t=f[e.id];Z(`received ${n} -> ${r} ${e.id}: ${typeof t==`string`?JSON.stringify(t):`(no translation)`}`)}}let g={...l},_={...u};for(let e of d){delete g[e.id],delete _[e.id];let t=f[e.id];if(e.autoPlural===!0&&!(typeof t==`string`&&t.includes(`{count`)&&t.includes(`, plural,`)&&t.includes(`other`)))continue;let n=e.autoPlural===!0?[`count`]:[];typeof t==`string`&&t.trim()&&i(e.source,t,n)&&(g[e.id]=t,_[e.id]=e.source)}let v=a.filter(e=>!Object.hasOwn(g,e.id)).length;return{file:{messages:g,sources:_},untranslated:v,requested:d.length,failed:p,failure:m,calls:h}}function St(e){let t={};for(let[n,r]of Object.entries(e.entries))t[n]={...r};let n={};for(let[t,r]of Object.entries(e.costs))n[t]={...r,ids:[...r.ids]};return{version:e.version,entries:t,costs:n}}async function Ct(e){let t=St(e.registry),{ambiguous:n,messages:r}=dt(t,e.files.flatMap(e=>e.messages)),i=ft(t,e.orphanRetentionMinutes),a={};for(let e of r)a[e.id]=e.source;let o=r.map(e=>({id:e.id,source:e.source,context:e.component,autoPlural:e.autoPlural,hint:e.hint})),s=o.some(e=>e.hint!==void 0)&&!e.locales.includes(e.sourceLocale)?[...e.locales,e.sourceLocale]:e.locales,c=await Ze(s,e.localeConcurrency,t=>xt({provider:e.provider,sourceLocale:e.sourceLocale,locale:t,requests:t===e.sourceLocale?o.filter(e=>e.hint!==void 0):o,previous:e.previous.get(t)??pt(),debug:e.debug,costs:e.costs})),l=/* @__PURE__ */ new Map,u=/* @__PURE__ */ new Map;return c.forEach((n,r)=>{let i=s[r];if(n.status===`fulfilled`){l.set(i,n.value);for(let r of n.value.calls)ot(t,e.sourceLocale,i,r);if(i===e.sourceLocale)for(let[e,t]of Object.entries(n.value.file.messages))a[e]=t}else u.set(i,n.reason)}),{registry:t,ambiguous:n,pruned:i,messages:r,sourceFile:{messages:a,sources:{}},locales:l,failures:u}}async function Q(e){try{let t=await ee(e);return`${t.mtimeMs}:${t.size}`}catch{return}}var wt=class{entries=/* @__PURE__ */ new Map;async read(e,t){let n=await Q(e),r=this.entries.get(e);if(n!==void 0&&r?.stamp===n)return r.value;let i=await t();return n!==void 0&&this.entries.set(e,{stamp:n,value:i,written:!1}),i}async holds(e,t,n){let r=this.entries.get(e);return r?.written!==!0||!n(r.value,t)?!1:await Q(e)===r.stamp}async write(e,t,n){await n();let r=await Q(e);r!==void 0&&this.entries.set(e,{stamp:r,value:t,written:!0})}};function $(e,t){if(!e)return!1;let n=Object.keys(t);return n.length===Object.keys(e).length&&n.every(n=>e[n]===t[n])}function Tt(e,t){return $(e.messages,t.messages)&&$(e.sources,t.sources)}var Et=class{extractions=/* @__PURE__ */ new Map;fileMessages=/* @__PURE__ */ new Map;catalogs=/* @__PURE__ */ new Map;catalogFiles={};warnedFiles=/* @__PURE__ */ new Set;legacySidecarsRemoved=!1;locales=new wt;registries=new wt;hashOf(e){return this.extractions.get(e)?.hash}readLocale(e,t){return this.locales.read(e,()=>ht(e,t))}async writeLocale(e,t){if(!await this.locales.holds(e,t,Tt))return this.locales.write(e,t,()=>gt(e,t))}readRegistry(e,t){return this.registries.read(e,()=>yt(e,t))}writeRegistry(e,t){return this.registries.write(e,t,()=>bt(e,t))}};const Dt=[`src/**/*.{tsx,jsx,ts,js,svelte,astro}`],Ot=[`**/*.test.*`,`**/node_modules/**`],kt=e=>({info:t=>e.info(t),warn:t=>e.warn(t),error:t=>e.error(t)});async function At(e,t){await Promise.all(t.map(t=>y(c.join(e,`${t}.sources.json`),{force:!0})))}var jt=class{options;sourceLocale;locales;delivery;state=new Et;provider;directory;debug;costs;orphanRetentionMinutes;include;exclude;activeReport;config;queue=Promise.resolve();constructor(e){this.options=e,this.sourceLocale=e.sourceLocale??`en`,this.locales=e.locales,this.directory=e.directory??`.i18n-works`,this.delivery=e.delivery??`build`,this.debug=e.debug??!1,this.costs=e.costs??!1,this.orphanRetentionMinutes=e.orphanRetentionMinutes??43200,this.include=e.include??Dt,this.exclude=e.exclude??Ot,this.provider=Xe(e.provider,e=>this.activeReport?.warn(e))}attach(e){this.config=e}explicitLocale(){return this.options.locale??process.env.I18N_WORKS_LOCALE}selectedLocale(){return this.explicitLocale()??this.sourceLocale}isServing(){return this.config.command===`serve`}localesDir(){return c.resolve(this.config.root,this.directory,`locales`)}registryFile(){return c.resolve(this.config.root,this.directory,`registry.json`)}isSourceCandidate(e){if(!/\.(?:[jt]sx?|svelte|astro)$/.test(e))return!1;let t=c.relative(this.config.root,e).split(c.sep).join(`/`);return this.include.some(e=>c.matchesGlob(t,e))&&!this.exclude.some(e=>c.matchesGlob(t,e))}localesToTranslate(){let e=this.locales.filter(e=>e!==this.sourceLocale),t=this.explicitLocale();return this.delivery===`build`&&t!==void 0&&t!==``&&!this.isServing()?e.filter(e=>e===t):e}async collectFiles(){let e=[];for await(let t of h(this.include,{cwd:this.config.root})){let n=t.split(c.sep).join(`/`);this.exclude.some(e=>c.matchesGlob(n,e))||e.push(c.resolve(this.config.root,t))}return e}async extractFiles(e,t,n){let r=await Ze(e,16,e=>this.extractFile(e,t,n)),i=/* @__PURE__ */ new Map,a=[];return e.forEach((e,t)=>{let n=r[t];if(n.status===`rejected`)throw n.reason;i.set(e,n.value),a.push({file:e,messages:n.value.messages})}),{nextExtractions:i,indexed:a}}async extractFile(e,t,n){let r=this.state.extractions.get(e);if(r&&t&&e!==n)return r;let i=await _(e,`utf8`),a=Ve(i);return r?.hash===a?r:{hash:a,messages:ze(i,e)}}reportLocales(e,t){for(let[n,i]of t.locales){if(i.requested>0&&!this.provider&&this.options.failOnMissingProvider===!0&&e.error(`Missing ${i.requested} ${n} translations and no provider is configured. Add a provider to ${z}, for example provider: hosted(HostedService.OpenAI, apiKey), or set failOnMissingProvider to false.`),i.untranslated){let t=this.provider?e.warn:e.info,a=this.provider?``:` No provider is configured; add one to ${z} to translate them.`;t(r(`${i.untranslated} ${n} messages have no translation and fall back to the source text.${a}`))}i.failed&&e.warn(r(`${i.failed} ${n} translation batches failed (${i.failure}); they will be requested again on the next build.`))}}async sync(e,t){let n=this.state,i=this.sourceLocale;this.activeReport=e;let a=t!==void 0&&n.extractions.has(t),o=a?[...n.extractions.keys()]:await this.collectFiles(),{nextExtractions:s,indexed:c}=await this.extractFiles(o,a,t),l=this.localesDir(),u=this.localesToTranslate(),d=[i,...u],[f,...p]=await Promise.all([n.readRegistry(this.registryFile(),e.warn),...d.map(t=>n.readLocale(X(l,t),e.warn))]),m=new Map(d.map((e,t)=>[e,p[t]])),h=await Ct({files:c,registry:f,orphanRetentionMinutes:this.orphanRetentionMinutes,sourceLocale:i,locales:u,localeConcurrency:Math.max(1,Math.floor(this.options.localeConcurrency??2)),previous:m,provider:this.provider,debug:this.debug,costs:this.costs});if(this.debug)for(let e of h.pruned)Z(`removed ${e.id} ${JSON.stringify(e.source)} (last seen ${e.lastSeen})`);if(h.pruned.length&&e.info(r(`removed ${h.pruned.length} registry entries no longer in the source.`)),await n.writeRegistry(this.registryFile(),h.registry),h.ambiguous.length){let t=r(`${h.ambiguous.length} duplicated texts changed occurrence count, so their IDs may have moved (e.g. "${h.ambiguous[0]}").`);this.options.onAmbiguous===`error`?e.error(t):e.warn(t)}await Promise.all([n.writeLocale(X(l,i),h.sourceFile),...[...h.locales].map(([e,t])=>n.writeLocale(X(l,e),t.file))]),n.legacySidecarsRemoved||=(await At(l,[i,...this.locales]),!0);let g=/* @__PURE__ */ new Map([[i,h.sourceFile.messages]]);for(let[e,t]of h.locales)g.set(e,t.file.messages);for(let e of h.failures.keys())g.set(e,m.get(e)?.messages??{});let _=[...g].filter(([e,t])=>!$(n.catalogs.get(e),t)).map(([e])=>e),v=0;n.fileMessages=/* @__PURE__ */ new Map;for(let{file:e,messages:t}of c)n.fileMessages.set(e,h.messages.slice(v,v+t.length)),v+=t.length;n.extractions=s,n.catalogs=g,n.catalogFiles=Object.fromEntries(this.locales.map(e=>[e,X(l,e)])),this.reportLocales(e,h),h.messages.length&&e.info(r(`indexed ${h.messages.length} messages across ${o.length} files.`));let y=[...h.failures];for(let[t,n]of y.slice(1))e.warn(r(`${t} translation failed: ${n.message}`));if(y.length)throw y[0][1];return _}runSync(e,t){let n=this.queue.then(()=>this.sync(e,t));return this.queue=n.then(()=>void 0,()=>void 0),n}};export{pe as C,ie as D,ne as E,ae as O,z as S,re as T,Ne as _,vt as a,Me as b,gt as c,ft as d,Qe as f,Ve as g,Ge as h,yt as i,F as k,it as l,Xe as m,kt as n,ht as o,qe as p,Z as r,bt as s,jt as t,ct as u,K as v,me as w,he as x,G as y};
|
package/package.json
CHANGED
package/dist/run-1mH_oPMI.js
DELETED
|
@@ -1,25 +0,0 @@
|
|
|
1
|
-
import{S as e,a as t,c as n,d as r,i,l as a,o,r as s,s as c,t as l,u,w as d,x as f}from"./sync-CHmobLly.js";import{o as p}from"./icu-Cui2dM71.js";import m from"node:path";import{existsSync as h,readFileSync as g}from"node:fs";import{emitKeypressEvents as _}from"node:readline";import{readFile as v,readdir as y,rm as b}from"node:fs/promises";import{parseArgs as x}from"node:util";const ee=()=>({calls:0,inputTokens:0,outputTokens:0,cost:0,unpriced:0});function S(e,t){e.calls+=1,e.inputTokens+=t.inputTokens??0,e.outputTokens+=t.outputTokens??0,t.cost===void 0?e.unpriced+=1:e.cost+=t.cost}function te(e,t){let n=/* @__PURE__ */ new Map;for(let r of e){let e=t(r),i=n.get(e)??ee();S(i,r),n.set(e,i)}return[...n].map(([e,t])=>({label:e,totals:t}))}function ne(e){let t=ee();for(let n of e)S(t,n);return{totals:t,models:te(e,e=>`${e.provider} ${e.model}`).sort((e,t)=>t.totals.cost-e.totals.cost||e.label.localeCompare(t.label)),months:te(e,e=>e.at.slice(0,7)).sort((e,t)=>e.label.localeCompare(t.label))}}const C=ne([]);function re(e){try{return g(e,`utf8`)}catch{return}}function ie(e,t){let n=/* @__PURE__ */ new Map;return{entry:t=>Object.hasOwn(e,t)?e[t]:void 0,readSource:e=>(n.has(e)||n.set(e,re(m.resolve(t,e))),n.get(e))}}const ae={title:[`1;4`,`22;24`],language:[`1`,`22`],left:[`1;36`,`22;39`],right:[`1;35`,`22;39`],source:[`34`,`39`],complete:[`32`,`39`],partial:[`33`,`39`],empty:[`31`,`39`],missing:[`3;31`,`23;39`],cursor:[`1;36`,`22;39`],selected:[`7`,`27`],key:[`1`,`22`],hint:[`2`,`22`],rule:[`2`,`22`],focus:[`1;33`,`22;39`]},w=(e,t)=>t;function T(e){return e?(e,t)=>{let[n,r]=ae[e];return`\x1b[${n}m${t}\x1b[${r}m`}:w}function E(e,t){let n=t.NO_COLOR;return e===!0&&(n===void 0||n===``)&&t.TERM!==`dumb`}const D={entry:()=>void 0,readSource:()=>void 0};function oe(e){return{status:`unavailable`,message:e instanceof Error?e.message:String(e)}}function se(e){if(e?.status!==`ready`)return!1;let{orphanedEntries:t,staleKeys:n,unconfiguredFiles:r}=e.summary;return t+n+r>0}const ce=` │ `,le=`› `,O=(e,t,n)=>Math.min(Math.max(e,t),n),k=(e,t)=>(e+t)%t,ue=e=>e.replace(/\s*\r?\n\s*/g,` `);function A(e,t,n){let r=Math.max(1,n),i=O(e-Math.floor(r/2),0,Math.max(0,t-r));return{start:i,end:Math.min(t,i+r)}}function j(e,t){return Object.hasOwn(e,t)?e[t]:void 0}function de(e,t){return[.../* @__PURE__ */ new Set([...Object.keys(e.messages),...Object.keys(t.messages)])].map(n=>({id:n,source:j(e.sources,n)??j(t.sources,n),left:j(e.messages,n),right:j(t.messages,n)}))}function fe(e){return new Set(e.flatMap(({file:e})=>Object.keys(e.messages))).size}const M=({file:e})=>Object.keys(e.messages).length;function pe(e,t){let n=/* @__PURE__ */ new Map;for(let{file:t}of e)for(let[e,r]of Object.entries(t.sources))n.has(e)||n.set(e,r);let r=Object.fromEntries(n);return e.map(e=>e.locale===t?{...e,file:{...e.file,messages:{...r,...e.file.messages}}}:e)}const N=(e,t)=>e.map(({role:e,text:n})=>e===void 0?n:t(e,n)).join(``),P=e=>e.reduce((e,{text:t})=>e+t.length,0);function F(e,t){let n=e.map(({role:e,text:t})=>({role:e,text:ue(t)}));if(P(n)<=t)return n;let r=[],i=Math.max(0,t-1);for(let e of n){let t=e.text.slice(0,i);t.length>0&&r.push({role:e.role,text:t}),i-=t.length}return[...r,{role:r.at(-1)?.role,text:`…`}]}function I(e,t){let n=F(e,t),r=P(n);return r<t?[...n,{text:` `.repeat(t-r)}]:n}const L=(e,t,n)=>N(F(e,t),n);function R(e,t,n){return e?n(`cursor`,le)+n(`selected`,N(t,n)):` `+N(t,n)}function z(e){let t=[];for(let[n,[r,i]]of e.entries())n>0&&t.push({role:`hint`,text:` · `}),t.push({role:`key`,text:r},{role:`hint`,text:i});return t}function B(e,t){return e===0?`empty`:e===t?`complete`:`partial`}const V=e=>`${(e*100).toFixed(1)}%`;function me(e){return[{text:` (${V(e.coverage)})`},{text:` · ${e.missing.length} missing · ${e.outdated.length} outdated · ${e.orphanedKeys.length} orphaned`}]}function he(e,t,n){let r=fe(e),i=Math.max(...e.map(({locale:e})=>e.length));return e.map(e=>{let a=e.locale===t?[{role:`source`,text:` (source)`}]:[],o=n?.locales.find(({locale:t})=>t===e.locale),s=o===void 0?[{role:B(M(e),r),text:`${M(e)}/${r}`},{text:` translated`}]:[{role:B(o.translated,o.total),text:`${o.translated}/${o.total}`},{text:` translated`},...me(o)];return[{role:`language`,text:e.locale.padEnd(i)},{text:` `},...s,...a]})}function ge(e){if(e===void 0)return[];let{total:t,active:n,orphaned:r}=e.registry,i=e.averageCoverage===null?[]:[{text:` · average coverage ${V(e.averageCoverage)}`}];return[{role:`title`,text:`Registry:`},{text:` ${t} entries (${n} active, ${r} orphaned)`},...i]}function _e(e){let t=Object.entries(e?.registry.byComponent??{}).sort(([e],[t])=>e.localeCompare(t));return t.length===0?[]:[{role:`hint`,text:`By component:`},{text:` ${t.map(([e,t])=>`${e} ${t}`).join(`, `)}`}]}function ve(e,t,n,r=w){let i=he(e,t,n).map(e=>N(e,r));return n===void 0?i:[...[ge(n),_e(n)].filter(e=>e.length>0).map(e=>N(e,r)),``,...i]}function ye(e,t,n,r,i=!1,a=C){return t.name===`q`||t.ctrl===!0&&t.name===`c`?null:e.view===`compare`?Ce(e,t,n):e.view===`costs`?we(e,t,a):e.view===`prune`?{view:`languages`,selected:e.selected}:be(e.selected,t,n,r,i)}function be(e,t,n,r,i){let a=n.length-1;switch(t.name){case`up`:case`k`:return{view:`languages`,selected:O(e-1,0,a)};case`down`:case`j`:return{view:`languages`,selected:O(e+1,0,a)};case`return`:case`enter`:return a<0?{view:`languages`,selected:e}:xe(e,n,r);case`x`:return i?{view:`prune`,selected:e}:{view:`languages`,selected:e};case`c`:return{view:`costs`,selected:e,row:0};default:return{view:`languages`,selected:e}}}function xe(e,t,n){let r=t.findIndex(({locale:e})=>e===n);return{view:`compare`,left:e,right:r!==-1&&r!==e?r:k(e+1,t.length),row:0,preview:!0}}function Se(e,t,n){return Math.max(0,de(e[t].file,e[n].file).length-1)}function Ce(e,t,n){let r=n.length,i=Se(n,e.left,e.right),a=t=>({...e,row:O(t,0,i)}),o=(t,r)=>({...e,left:t,right:r,row:O(e.row,0,Se(n,t,r))});switch(t.name){case`up`:case`k`:return a(e.row-1);case`down`:case`j`:return a(e.row+1);case`pageup`:return a(e.row-10);case`pagedown`:return a(e.row+10);case`home`:return a(0);case`end`:return a(i);case`left`:return o(k(e.left-1,r),e.right);case`right`:return o(k(e.left+1,r),e.right);case`tab`:return o(e.left,k(e.right+(t.shift===!0?-1:1),r));case`p`:return{...e,preview:!e.preview};case`escape`:case`backspace`:return{view:`languages`,selected:e.left};default:return e}}function we(e,t,n){let r=Math.max(0,je(n).length-1),i=t=>({...e,row:O(t,0,r)});switch(t.name){case`up`:case`k`:return i(e.row-1);case`down`:case`j`:return i(e.row+1);case`pageup`:return i(e.row-10);case`pagedown`:return i(e.row+10);case`home`:return i(0);case`end`:return i(r);case`escape`:case`backspace`:return{view:`languages`,selected:e.selected};default:return e}}function Te(e,t,n,r,i=w,a=D,o,s,c,l=C){return e.view===`compare`?Re(e,t,r,i,a):e.view===`costs`?Me(e,l,r,i):De(e,t,n,r,i,o,s,c)}function Ee(e){let t={role:`title`,text:`Prune:`};if(e===void 0)return[];if(e.status===`unavailable`)return[t,{role:`missing`,text:` unavailable (${e.message})`}];if(!se(e))return[t,{text:` nothing to remove.`}];let{orphanedEntries:n,staleKeys:r,unconfiguredFiles:i}=e.summary;return[t,{text:` ${[n>0&&`${n} orphaned ${n===1?`entry`:`entries`}`,r>0&&`${r} stale ${r===1?`key`:`keys`}`,i>0&&`${i} unconfigured locale ${i===1?`file`:`files`}`].filter(e=>typeof e==`string`).join(`, `)}.`}]}function De(e,t,n,r,i,a,o,s){let{selected:c}=e,l=he(t,n,o),{start:u,end:d}=A(c,l.length,r.height-8),f=l.slice(u,d).map((e,t)=>R(u+t===c,I(e,r.width-2),i)),p=e.view===`prune`?z([[`y`,` prune now`],[`any other key`,` cancel`]]):z([[`↑/↓`,` move`],[`Enter`,` compare`],[`x`,` prune`],[`t`,` translate`],[`c`,` costs`],[`q`,` quit`]]);return[L([{role:`title`,text:`Translation files:`},{text:` ${t.length} languages, source `},{role:`language`,text:n}],r.width,i),L(Ee(a),r.width,i),L(ge(o),r.width,i),L(_e(o),r.width,i),L(s===void 0?[]:[{text:s}],r.width,i),``,...f,``,L(p,r.width,i)].join(`
|
|
2
|
-
`)}function Oe(e){if(e.calls===e.unpriced)return`unknown`;let t=`$${e.cost.toFixed(6)}`;return e.unpriced===0?t:`${t} (+${e.unpriced} unpriced)`}function ke(e){return[W(`Totals`),H(`calls`,U(String(e.calls))),H(`tokens in`,U(String(e.inputTokens))),H(`tokens out`,U(String(e.outputTokens))),H(`cost`,U(Oe(e))),[]]}function Ae(e,t,n){let r=Math.max(t.length,...n.map(({label:e})=>e.length)),i=[{role:`hint`,text:t.padEnd(r)},{role:`hint`,text:`calls`.padStart(8)},{role:`hint`,text:`tokens in`.padStart(12)},{role:`hint`,text:`tokens out`.padStart(12)},{role:`hint`,text:` cost`}];return[W(e),i,...n.map(({label:e,totals:t})=>[{text:e.padEnd(r)},{text:String(t.calls).padStart(8)},{text:String(t.inputTokens).padStart(12)},{text:String(t.outputTokens).padStart(12)},{text:` ${Oe(t)}`}]),[]]}function je(e){return e.totals.calls===0?[[{role:`hint`,text:`No AI calls recorded yet. Enable the costs option to record them.`}]]:[...ke(e.totals),...Ae(`Models`,`model`,e.models),...Ae(`Months (UTC)`,`month`,e.months)]}function Me(e,t,n,r){let i=je(t),a=Math.max(1,n.height-4),{start:o,end:s}=A(e.row,i.length,a),c=r(`rule`,`─`.repeat(n.width));return[L([{role:`title`,text:`Costs`},{role:`hint`,text:` estimated USD`}],n.width,r),c,...i.slice(o,s).map(e=>L(e,n.width,r)),c,L(z([[`↑/↓`,` scroll`],[`PgUp/PgDn`,` page`],[`Esc`,` languages`],[`q`,` quit`]]),n.width,r)].join(`
|
|
3
|
-
`)}function Ne(e){return e===void 0?[]:[{role:`source`,text:`source: `},e.source===void 0?{role:`missing`,text:`(not recorded)`}:{role:`source`,text:e.source}]}const H=(e,t)=>[{role:`hint`,text:e.padEnd(11)},...t],U=e=>[{text:e}],W=e=>[{role:`title`,text:e}];function Pe(e,t){let n={column:Math.max(8,Math.floor((e-2-3)/2)),pane:0};if(!t)return n;let r=O(Math.floor(e*.4),24,48),i=Math.floor((e-2-6-r)/2);return i>=12?{column:i,pane:r}:n}function Fe(e,t){if(!(!Number.isInteger(t)||t<0||t>e.length))return e.slice(0,t).split(`
|
|
4
|
-
`).length}function Ie(e,t,n){if(e===void 0)return[[{role:`missing`,text:`(source file cannot be read)`}]];if(t===void 0)return[[{role:`missing`,text:`(the file is shorter than the recorded location)`}]];let r=e.split(`
|
|
5
|
-
`),i=t-1,{start:a,end:o}=A(i,r.length,n),s=String(o).length;return r.slice(a,o).map((e,t)=>{let n=a+t===i;return[n?{role:`focus`,text:le}:{text:` `},{role:`hint`,text:String(a+t+1).padStart(s)},{text:` `},{role:n?`focus`:void 0,text:e.replace(/\r$/,``).replaceAll(` `,` `)}]})}function Le(e,t,n){if(e===void 0)return[[{role:`hint`,text:`No message selected.`}]];let r=W(e.id),i=t.entry(e.id);if(i===void 0)return[r,[{role:`missing`,text:`(not in the registry)`}]];let{file:a,start:o}=u(i.location),s=t.readSource(a),c=s===void 0?void 0:Fe(s,o),l=[r,H(`component`,U(i.component)),H(`status`,U(i.status)),H(`first seen`,U(i.firstSeen.slice(0,10))),H(`last seen`,U(i.lastSeen.slice(0,10))),...i.hint===void 0?[]:[H(`hint`,U(i.hint))],...i.autoPlural===!0?[H(`plural`,U(`automatic`))]:[],H(`file`,U(m.relative(process.cwd(),a))),H(`line`,c===void 0?[{role:`missing`,text:`unknown`}]:U(String(c)))],d=Math.max(0,n-l.length-2);return[...l,[],W(`preview`),...Ie(s,c,d)].slice(0,n)}function Re(e,t,n,r,i){let a=t[e.left],o=t[e.right],s=de(a.file,o.file),c=fe(t),{column:l,pane:u}=Pe(n.width,e.preview),d=(e,t)=>[...I(e,l),{role:`rule`,text:ce},...I(t,l)],f=e=>e===void 0?[{role:`missing`,text:`(missing)`}]:[{text:e}],p=Math.max(1,n.height-5),{start:m,end:h}=A(e.row,s.length,p),g=u===0?[]:Le(s.at(e.row),i,p),_=e=>u===0?``:N([{role:`rule`,text:ce},...I(e,u)],r),v=n.width-(u===0?0:u+3),y=s.length===0?[N(I([{role:`hint`,text:`no messages in either file.`}],v),r)]:s.slice(m,h).map((t,n)=>R(m+n===e.row,d(f(t.left),f(t.right)),r)),b=Array.from({length:p},(e,t)=>(y.at(t)??``)+_(g.at(t)??[])),x=r(`rule`,`─`.repeat(n.width));return[R(!1,d([{role:`left`,text:`${a.locale} (${M(a)}/${c})`}],[{role:`right`,text:`${o.locale} (${M(o)}/${c})`}]),r)+_(W(`Details`)),x,...b,x,L(Ne(s.at(e.row)),n.width,r),L(z([[`←/→`,` left file`],[`Tab/Shift+Tab`,` right file`],[`↑/↓`,` row`],[`PgUp/PgDn`,` page`],[`Esc`,` languages`],[`q`,` quit`],[`p`,` toggle preview`]]),n.width,r)].join(`
|
|
6
|
-
`)}const ze={width:80,height:24};function Be(e){let t=(e,t)=>e!==void 0&&e>0?e:t;return{width:t(e.columns,ze.width),height:t(e.rows,ze.height)}}function Ve(e,t,n){let{input:r,output:i}=n,a=T(E(i.isTTY,n.env??process.env));return new Promise(o=>{let s={view:`languages`,selected:0},c={languages:e,inspector:n.inspector??D,notice:n.notice,report:n.report,costs:n.costs??C},l=!1,u=()=>{i.write(`\x1B[H\x1B[2J`+Te(s,c.languages,t,Be(i),a,c.inspector,c.notice,c.report,c.status,c.costs))},d=async(e,t)=>{l=!0;try{c=await t()}catch(e){c={...c,notice:oe(e)}}l=!1;let n=Math.max(0,c.languages.length-1);s={view:`languages`,selected:Math.min(e,n)},u()},f=async(e,t)=>{l=!0,c={...c,status:`Translating every locale...`},u();try{c=await t()}catch(e){c={...c,status:`Translation failed: ${e instanceof Error?e.message:String(e)}`}}l=!1;let n=Math.max(0,c.languages.length-1);s={view:`languages`,selected:Math.min(e,n)},u()},p=(e,r)=>{if(r===void 0||l)return;if(s.view===`prune`&&r.name===`y`&&n.prune!==void 0){d(s.selected,n.prune);return}if(s.view===`languages`&&r.name===`t`&&n.translate!==void 0){f(s.selected,n.translate);return}let i=n.prune!==void 0&&se(c.notice),a=ye(s,r,c.languages,t,i,c.costs);a===null?m():(s=a,u())},m=()=>{r.off(`keypress`,p),i.off(`resize`,u),r.isTTY===!0&&r.setRawMode?.(!1),r.pause(),i.write(`\x1B[?25h\x1B[?1049l`),o()};_(r),r.isTTY===!0&&r.setRawMode?.(!0),i.write(`\x1B[?1049h\x1B[?25l`),r.on(`keypress`,p),i.on(`resize`,u),r.resume(),u()})}const G=`.i18n-works`,K=e=>console.warn(e);function q(e){let t=m.resolve(e.root??process.cwd()),n=m.resolve(t,e.directory??`.i18n-works`,`registry.json`);return{root:t,registryFile:n,localesDir:m.join(m.dirname(n),`locales`)}}function He(e,t){let n=Object.keys(t),r={};for(let e of n)r[Ue(e)]={type:typeof t[e]==`boolean`?`boolean`:`string`};let{values:i}=x({args:e,options:r,strict:!0,allowPositionals:!1}),a={...t};for(let e of n){let n=i[Ue(e)];n!==void 0&&(a[e]=typeof t[e]==`boolean`?!0:typeof t[e]==`number`?Number(n):String(n))}return a}function Ue(e){return e.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`)}async function J(e){return h(e)?(await y(e)).filter(e=>e.endsWith(`.json`)):[]}async function We(e={}){let{registryFile:n,localesDir:a,root:s}=q(e),c=e.onWarning??K;if(!h(n))return{registryFile:n,registry:void 0,removedEntries:[],unconfiguredFiles:[],catalogs:[]};let l=e.retentionMinutes??43200;if(!(l>=0))throw Error(`retentionMinutes must be a number of minutes, 0 or more`);let u=await f(s,{command:`build`,mode:`production`});d(u);let p=/* @__PURE__ */ new Set([u.sourceLocale??`en`,...u.locales]),g=await i(n,c),_=r(g,l),v=new Set(Object.values(g.entries).filter(e=>e.status===`active`).map(e=>e.id)),y=[],b=[];for(let e of await J(a)){let n=m.join(a,e);if(!p.has(m.basename(e,`.json`))){y.push(n);continue}let r=t(await o(n,c),v);r.removed.length&&b.push({file:n,pruned:r.file,removed:r.removed})}return{registryFile:n,registry:g,removedEntries:_,unconfiguredFiles:y,catalogs:b}}async function Y(e={}){let t=await We(e),{registry:r,registryFile:i}=t;if(r===void 0)return{registryFile:i,registryFound:!1,removedEntries:[],removedLocaleFiles:[],catalogs:[]};t.removedEntries.length&&await c(i,r);for(let e of t.unconfiguredFiles)await b(e);for(let e of t.catalogs)await n(e.file,e.pruned);return{registryFile:i,registryFound:!0,removedEntries:t.removedEntries,removedLocaleFiles:t.unconfiguredFiles,catalogs:t.catalogs.map(({file:e,removed:t})=>({file:e,removed:t}))}}const Ge=e=>{let t={};for(let n of e)t[n]=(t[n]??0)+1;return t};function Ke(e,t){let n=Object.values(e.entries),r=n.filter(e=>e.status===`active`),i=new Set(r.map(e=>e.id)),a=n.filter(e=>e.status===`orphaned`).sort((e,t)=>e.lastSeen.localeCompare(t.lastSeen)||e.id.localeCompare(t.id)),o=Object.keys(t).sort((e,t)=>e.localeCompare(t)).map(e=>{let n=t[e],a=r.filter(e=>!Object.hasOwn(n.messages,e.id)).map(e=>e.id),o=r.filter(e=>Object.hasOwn(n.messages,e.id)&&n.sources[e.id]!==e.source).map(e=>e.id),s=[.../* @__PURE__ */ new Set([...Object.keys(n.messages),...Object.keys(n.sources)])].filter(e=>!i.has(e)),c=r.length,l=c-a.length;return{locale:e,translated:l,total:c,coverage:c===0?1:l/c,missing:a.sort(),outdated:o.sort(),orphanedKeys:s.sort()}}),s=o.length===0?null:o.reduce((e,t)=>e+t.coverage,0)/o.length;return{registry:{total:n.length,active:r.length,orphaned:a.length,byComponent:Ge(r.map(e=>e.component)),orphans:a},locales:o,averageCoverage:s}}async function qe(e,t,n){let r=(await J(e)).filter(e=>!e.endsWith(`.sources.json`)).map(e=>({name:e,locale:e.slice(0,-5)})).filter(({locale:e})=>e!==t),i=await Promise.all(r.map(({name:t})=>o(m.join(e,t),n)));return Object.fromEntries(r.map(({locale:e},t)=>[e,i[t]]))}async function X(e={}){let{registryFile:t,localesDir:n}=q(e),r=e.onWarning??K;if(!h(t))return{registryFile:t,registryFound:!1};let[a,o]=await Promise.all([i(t,r),qe(n,e.sourceLocale??`en`,r)]);return{registryFile:t,registryFound:!0,report:Ke(a,o)}}async function Je(e={}){let{root:t}=q(e),n=await f(t,{command:`build`,mode:`production`});d(n);let r=new l(e.directory===void 0?n:{...n,directory:e.directory});r.attach({root:t,command:`build`});let i=r.localesDir(),a=await Ye(i),o=[];return await r.runSync({info:()=>void 0,warn:e=>o.push(e),error:e=>o.push(e)}),{changedLocales:[...await Ye(i)].filter(([e,t])=>e!==r.sourceLocale&&a.get(e)!==t).map(([e])=>e),warnings:o}}async function Ye(e){let t=await y(e).catch(e=>{if(e.code===`ENOENT`)return[];throw e}),n=await Promise.all(t.filter(e=>e.endsWith(`.json`)).map(async t=>[m.basename(t,`.json`),await v(m.join(e,t),`utf8`)]));return new Map(n)}async function Z(e={}){let{localesDir:t}=q(e),n=e.onWarning??K,r=(await J(t)).filter(e=>!e.endsWith(`.sources.json`)).sort(),i=await Promise.all(r.map(e=>o(m.join(t,e),n)));return{localesDir:t,languages:pe(r.map((e,t)=>({locale:e.slice(0,-5),file:i[t]})),e.sourceLocale??`en`)}}async function Xe(e={}){let{localesDir:t,languages:n}=await Z(e);if(n.length===0)return{localesDir:t,opened:!1};let r=e.input??process.stdin,i=e.output??process.stdout;if(r.isTTY!==!0||i.isTTY!==!0)throw Error("browse needs an interactive terminal; use listLanguages(), or `vite-i18n browse --list`, to print the languages instead.");let[{inspector:a,costs:o},s,{report:c}]=await Promise.all([Qe(e),Q(e),X(e)]);return await Ve(n,e.sourceLocale??`en`,{input:r,output:i,inspector:a,notice:s,report:c,costs:o,prune:async()=>(await Y(e),$e(e)),translate:async()=>{let t=await Je(e).then(({changedLocales:e,warnings:t})=>Ze(e,t),e=>`Translation failed: ${e instanceof Error?e.message:String(e)}`);return{...await $e(e),status:t}}}),{localesDir:t,opened:!0}}function Ze(e,t){let n=e.length>0?`Translated ${e.join(`, `)}.`:`Translations are up to date.`;return t.length>0?`${n} ${t[0]}`:n}async function Qe(e){let{registryFile:t,root:n}=q(e),r=await i(t,e.onWarning??K);return{inspector:ie(r.entries,n),costs:ne(Object.values(r.costs))}}async function Q(e){try{let{removedEntries:t,unconfiguredFiles:n,catalogs:r}=await We(e);return{status:`ready`,summary:{orphanedEntries:t.length,staleKeys:r.reduce((e,t)=>e+t.removed.length,0),unconfiguredFiles:n.length}}}catch(e){return oe(e)}}async function $e(e){let[{languages:t},{inspector:n,costs:r},i,{report:a}]=await Promise.all([Z(e),Qe(e),Q(e),X(e)]);return{languages:t,inspector:n,notice:i,report:a,costs:r}}const et=/* @__PURE__ */ new Set([`help`,`--help`,`-h`]),$=`Usage: vite-i18n [command] [options]
|
|
7
|
-
|
|
8
|
-
Commands:
|
|
9
|
-
prune Remove orphaned registry entries and the locale files and keys they leave behind
|
|
10
|
-
browse Browse the translation files in an interactive terminal, with registry counts and coverage (default)
|
|
11
|
-
|
|
12
|
-
Options shared by every command:
|
|
13
|
-
--root <dir> Vite root that holds ${e} (default: the current directory)
|
|
14
|
-
--directory <dir> Catalogue directory, relative to --root (default: ${G})
|
|
15
|
-
|
|
16
|
-
prune:
|
|
17
|
-
--retention-minutes <n> Remove orphans last seen longer ago than n minutes (default: 30 days)
|
|
18
|
-
--debug Log every removal
|
|
19
|
-
|
|
20
|
-
browse:
|
|
21
|
-
--source-locale <locale> The source locale, compared against (default: en)
|
|
22
|
-
--list Print the languages, their coverage and the registry counts instead of opening the browser
|
|
23
|
-
--json With --list, print the registry statistics as JSON, including the missing, outdated and
|
|
24
|
-
orphaned IDs of each locale`;async function tt(t){let n=He(t,{root:process.cwd(),directory:G,retentionMinutes:a,debug:!1});if(!(n.retentionMinutes>=0))throw Error(`--retention-minutes must be a number of minutes, 0 or more`);let r=await Y(n);if(!r.registryFound)console.log(p(`no registry found at ${r.registryFile}; nothing to prune.`));else{if(n.debug){for(let e of r.removedEntries)s(`removed ${e.id} ${JSON.stringify(e.source)} (last seen ${e.lastSeen})`);for(let t of r.removedLocaleFiles)s(`removed ${t}; its locale is not in ${e}`);for(let{file:e,removed:t}of r.catalogs)for(let n of t)s(`removed ${n} from ${e}`)}console.log(p(`removed ${r.removedEntries.length} registry entries orphaned for more than ${n.retentionMinutes} minutes.`)),r.catalogs.length&&console.log(p(`removed stale keys from ${r.catalogs.length} locale files.`)),r.removedLocaleFiles.length&&console.log(p(`removed ${r.removedLocaleFiles.length} locale files for locales not in ${e}.`))}}async function nt(e){let t=He(e,{root:process.cwd(),directory:G,sourceLocale:`en`,list:!1,json:!1});if(t.list){let[{localesDir:e,languages:n},{report:r,registryFile:i}]=await Promise.all([Z(t),X(t)]);if(t.json){console.log(r?JSON.stringify(r,null,2):p(`no registry found at ${i}; nothing to report.`));return}if(n.length===0){console.log(p(`no locale files found in ${e}; nothing to browse.`));return}let a=T(E(process.stdout.isTTY,process.env));console.log(ve(n,t.sourceLocale,r,a).join(`
|
|
25
|
-
`));return}let n=await Xe(t);n.opened||console.log(p(`no locale files found in ${n.localesDir}; nothing to browse.`))}async function rt(e){let[t=``,...n]=e,r=t===``||t.startsWith(`-`),i=r?`browse`:t,a=r?e:n;if(et.has(i)||a.some(e=>e===`--help`||e===`-h`))return console.log($),0;try{switch(i){case`prune`:return await tt(a),0;case`browse`:return await nt(a),0;default:return console.error(p(`unknown command "${i}"`)),console.error($),1}}catch(e){return console.error(p(e.message)),1}}export{X as a,Je as i,Xe as n,Y as o,Z as r,G as s,rt as t};
|
package/dist/sync-CHmobLly.js
DELETED
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
import{a as e,i as t,n,o as r,r as i}from"./icu-Cui2dM71.js";import{createRequire as a}from"node:module";import{existsSync as o}from"node:fs";import{loadConfigFromFile as s}from"vite";import c,{basename as l,extname as u}from"node:path";import{createHash as d,randomUUID as f}from"node:crypto";import{parseSync as p}from"rolldown/utils";import m from"magic-string";import{glob as h,mkdir as g,readFile as _,rename as v,rm as y,stat as ee,writeFile as te}from"node:fs/promises";const b=Symbol(`failed`),x=(e,t)=>(e.push({path:[],message:t}),b),ne=(e,t,n,r)=>{let i=r.length,a=e.check(t,r);if(a===b)for(let e=i;e<r.length;e++)r[e]={path:[n,...r[e].path],message:r[e].message};return a},S=e=>`must be ${e}`,C=(e,t)=>({expected:e,check:(n,r)=>t(n)?n:x(r,S(e))}),w=C(`a string`,e=>typeof e==`string`),T=C(`a finite number`,e=>typeof e==`number`&&Number.isFinite(e)),E=C(`a boolean`,e=>typeof e==`boolean`),D=C(`an object`,e=>typeof e==`object`&&!!e||typeof e==`function`);function O(e){let t=typeof e==`string`?JSON.stringify(e):String(e);return C(t,t=>t===e)}function k(e,t,n){return{expected:n,check:(r,i)=>{let a=e.check(r,i);return a===b?b:t(a)?a:x(i,S(n))}}}function A(e,{nonEmpty:t=!1}={}){let n=t?`a non-empty array`:`an array`;return{expected:n,check:(r,i)=>{if(!Array.isArray(r)||t&&r.length===0)return x(i,S(n));let a=!1,o=[];for(let[t,n]of r.entries()){let r=ne(e,n,t,i);r===b?a=!0:o.push(r)}return a?b:o}}}function j(...e){let t=e.map(e=>e.expected).join(` or `);return{expected:t,check:(n,r)=>{for(let t of e){let e=t.check(n,[]);if(e!==b)return e}return x(r,S(t))}}}function M(e){return{...e,optional:!0}}function N(e,t=`ignore`){let n=Object.entries(e),r=new Set(Object.keys(e));return{expected:`an object`,check:(e,i)=>{let a=D.check(e,i);if(a===b)return b;let o=!1,s={};for(let[e,t]of n){if(!Object.hasOwn(a,e)){t.optional!==!0&&(i.push({path:[e],message:`is required`}),o=!0);continue}let n=ne(t,a[e],e,i);n===b?o=!0:s[e]=n}if(t===`reject`)for(let e of Object.keys(a))r.has(e)||(i.push({path:[e],message:`is not a known key`}),o=!0);return o?b:s}}}function P(e,t){let n=[],r=e.check(t,n);return r===b?{ok:!1,issues:n}:{ok:!0,value:r}}const F=e=>M(j(e,O(void 0))),I=M(j(T,O(null))),re=N({choices:A(N({message:N({content:M(j(w,O(null)))})}),{nonEmpty:!0}),usage:M(j(N({prompt_tokens:I,completion_tokens:I}),O(null)))}),ie=N({content:A(N({type:w,text:M(w)})),usage:M(j(N({input_tokens:I,output_tokens:I}),O(null)))}),ae=N({candidates:A(N({content:M(N({parts:M(A(N({text:M(w)})))}))})),usageMetadata:M(j(N({promptTokenCount:I,candidatesTokenCount:I}),O(null)))}),oe=D,se=N({messages:D,sources:D}),ce=N({id:w,source:w,component:w,fingerprint:w,autoPlural:F(E),hint:F(w),location:w,status:j(O(`active`),O(`orphaned`)),firstSeen:w,lastSeen:w}),le=N({id:w,at:w,sourceLocale:w,locale:w,provider:w,model:w,ids:A(w),inputTokens:F(T),outputTokens:F(T),cost:F(T)}),ue=N({version:O(1),entries:D,costs:M(D)}),de=k(w,e=>e.length>0,`a non-empty string`),fe=/^[A-Za-z]{2,3}(?:-[A-Za-z0-9]{1,8})*$/,L=k(w,e=>fe.test(e),`a locale tag`),pe=N({locales:A(L),sourceLocale:F(L),delivery:F(j(O(`build`),O(`runtime`))),locale:F(L),include:F(A(w)),exclude:F(A(w)),directory:F(de),provider:F(D),failOnMissingProvider:F(E),onAmbiguous:F(j(O(`warn`),O(`error`))),orphanRetentionMinutes:F(j(k(T,e=>e>=0,`a number >= 0`),O(1/0))),localeConcurrency:F(k(T,e=>e>=1,`a number >= 1`)),debug:F(E),costs:F(E)},`reject`),R=`vite-i18n.config.js`;function me(e){return c.resolve(e,R)}function he(t){let n=P(pe,t);if(n.ok)return;let r=n.issues.map(e=>`${e.path.join(`.`)||`options`}: ${e.message}`).join(`; `);throw e(`invalid options in ${R} (${r}). Fix or remove these keys; the README lists every option.`)}const ge=async(t,n)=>{let r=me(t);if(!o(r))throw e(`${R} was not found in ${t}. Create it next to vite.config with the plugin options as the default export, for example:\n\n export default {
|
|
2
|
-
locales: ["en", "de"],
|
|
3
|
-
sourceLocale: "en",
|
|
4
|
-
};\n\nThe README lists every option.`);try{return(await s(n,r,t))?.config}catch(t){let n=t instanceof Error?t.message:String(t);throw e(`could not load ${R}: ${n}. Check the file for syntax errors and make sure it has a default export that is an object.`)}};function z(e){return e.replace(/\s+/g,` `).trim()}function _e(e){let t=e.autoPlural===!0?`tt`:`t`;return d(`sha256`).update(`${t}\u0000${z(e.source)}\u0000${z(e.hint??``)}`).digest(`hex`).slice(0,24)}function B(e,t){let n=p(t,e,{lang:`tsx`,sourceType:`unambiguous`});if(n.errors.length)throw SyntaxError(`${t}: ${n.errors[0].message}`);return n.program}function ve(e,t){let n=[],r=e=>{if(t(e,n)!==!1){n.push(e);for(let t of Object.keys(e)){if(t===`parent`)continue;let n=e[t];Array.isArray(n)?n.forEach(e=>V(e)&&r(e)):V(n)&&r(n)}n.pop()}};r(e)}function V(e){return typeof e==`object`&&!!e&&typeof e.type==`string`}function H(e){return V(e)&&e.type===`Literal`&&typeof e.value==`string`}const ye=a(import.meta.url);function be(t,n,r){try{return ye(t)}catch{throw e(`${r} files need the "${n}" package. Install it with your package manager.`)}}let xe;function Se(e,t){xe??=be(`@astrojs/compiler/sync`,`@astrojs/compiler`,`Astro`);let{ast:n,diagnostics:r}=xe.parse(e,{position:!0}),i=r.find(e=>e.severity===1);if(i)throw SyntaxError(`${t}: ${i.text}`);let a=Ce(e),o=l(t,u(t)),s=[],c=(n,r)=>{let i=e.slice(n,r);i.trim()!==``&&s.push({root:B(`[${i}\n]`,t),offset:n-1,component:o})},d=e=>{if(e.type===`comment`)return;if(e.type===`expression`)return f(e.children??[]);let t=a(e.position.start.offset);return e.type===`text`?{start:t,end:t+e.value.length}:{start:t,end:a(e.position.end.offset)}},f=e=>{let t=e.map(d).filter(e=>e!==void 0);if(t.length!==0)return{start:t[0].start,end:t[t.length-1].end}},p=t=>{let n=a(t.position.start.offset),r=e.indexOf(t.value,n+t.name.length);c(r,r+t.value.length)},m=e=>{if(e.type===`frontmatter`){let n=a(e.position.start.offset)+3;s.push({root:B(e.value,t),offset:n,component:o})}else if(e.type===`expression`){let t=d(e);t&&c(t.start,t.end)}else{for(let t of e.attributes??[])t.kind===`expression`&&p(t);for(let t of e.children??[])m(t)}};return m(n),s}function Ce(e){let t=Buffer.byteLength(e);if(t===e.length)return e=>e;let n=new Uint32Array(t+1),r=0;for(let t=0;t<e.length;){let i=e.codePointAt(t),a=Buffer.byteLength(String.fromCodePoint(i));n.fill(t,r,r+a),r+=a,t+=i>65535?2:1}return n[r]=e.length,e=>n[e]}let we;function U(e,t){we??=be(`svelte/compiler`,`svelte`,`Svelte`);try{return we.parse(e,{modern:!0})}catch(e){throw SyntaxError(`${t}: ${e.message}`,{cause:e})}}function Te(e,t){let n=U(e,t),r=l(t,u(t)),i=[];return n.module&&i.push({root:n.module.content,offset:0}),n.instance&&i.push({root:n.instance.content,offset:0,component:r}),i.push({root:n.fragment,offset:0,component:r}),i}function Ee(e,t){let n=U(e,t),r=n.instance??n.module;return r?r.content.start:0}function De(e,t){switch(u(t)){case`.svelte`:return{regions:Te(e,t)};case`.astro`:return{regions:Se(e,t)};default:return{regions:[{root:B(e,t),offset:0}]}}}const W=`virtual:i18n-works`,G=`i18n-works/runtime`,K=`__i18nWorksT`,Oe=`__i18nWorksFormat`,ke=`__i18nWorksFormatAutoPlural`,Ae=String.raw`\s*(["'])[^"'\n]*\1[ \t]*;?[ \t]*(?:\r?\n|$)`,q=new RegExp(Ae,`y`);function je(e){let t=0;if(e.startsWith(`#!`)){let n=e.indexOf(`
|
|
5
|
-
`);t=n===-1?e.length:n+1}q.lastIndex=t;for(let n=q.exec(e);n;n=q.exec(e))t=q.lastIndex;return t}function Me(e,t){switch(u(t)){case`.svelte`:return{offset:Ee(e,t),format:e=>`\n${e}`};case`.astro`:return{offset:3,format:e=>`\n${e}`};default:return{offset:je(e),format:e=>`${e}\n`}}}function Ne(e,t,n,r,i,a=!1,o=`en`,s=!0){let c=new m(e),l=e=>r===o&&e.hint===void 0?e.source:i[e.id]??e.source;for(let e of n){if(e.valuesStart===void 0){let t=a?`${K}(${JSON.stringify(e.id)}, ${JSON.stringify(e.source)})`:JSON.stringify(l(e));c.overwrite(e.start,e.end,t);continue}let t;t=a&&e.autoPlural===!0?`__i18nWorksLookupAutoPlural(${JSON.stringify(e.id)}, ${JSON.stringify(e.source)}, `:a?`${K}(${JSON.stringify(e.id)}, ${JSON.stringify(e.source)}, `:e.autoPlural===!0?`${ke}(${JSON.stringify(l(e))}, ${JSON.stringify(r)}, `:`${Oe}(${JSON.stringify(l(e))}, ${JSON.stringify(r)}, `,c.overwrite(e.start,e.valuesStart,t)}let u=[];if(a&&n.length&&u.push(`import { lookup as ${K} } from "${W}";`),a&&n.some(e=>e.autoPlural===!0)&&u.push(`import { lookupAutoPlural as __i18nWorksLookupAutoPlural } from "${W}";`),!a&&n.some(e=>e.valuesStart!==void 0)&&u.push(`import { formatMessage as ${Oe} } from "${G}";`),!a&&n.some(e=>e.autoPlural===!0)&&u.push(`import { formatAutoPluralMessage as ${ke} } from "${G}";`),u.length){let n=Me(e,t);c.appendLeft(n.offset,n.format(u.join(`
|
|
6
|
-
`)))}return{code:c.toString(),map:s?c.generateMap({source:t,hires:!0,includeContent:!1}):null}}const Pe=`<module>`,Fe=e=>/[A-Za-z]/.test(e);function Ie(e,t){try{n(e)}catch(e){throw SyntaxError(`${t}: t() message is not valid ICU MessageFormat: ${e.message}`,{cause:e})}}function Le(e){let t={t:/* @__PURE__ */ new Set,tt:/* @__PURE__ */ new Set,tauto:/* @__PURE__ */ new Set};for(let{root:n}of e)if(n.type===`Program`){for(let e of n.body)if(e.type===`ImportDeclaration`&&e.source.value===`virtual:i18n-works`)for(let n of e.specifiers){if(n.type!==`ImportSpecifier`)continue;let e=n.imported.type===`Identifier`?n.imported.name:n.imported.value;e===`t`&&t.t.add(n.local.name),e===`tt`&&t.tt.add(n.local.name),e===`tauto`&&t.tauto.add(n.local.name)}}return t}const Re=(e,t)=>e.type===`FunctionExpression`?!(t?.type===`MethodDefinition`||t?.type===`Property`&&(t.method||t.kind!==`init`)):e.type===`FunctionDeclaration`||e.type===`ArrowFunctionExpression`;function ze(e,t){let n=e.length-1;for(;n>=0&&!Re(e[n],e[n-1]);)n--;if(n<0)return t;let r=e[n],i=n>0?e[n-1]:void 0;return i?.type===`VariableDeclarator`&&i.id.type===`Identifier`?i.id.name:r.type===`FunctionDeclaration`&&r.id?r.id.name:`<anonymous>`}function Be(e,t,n){if(n===void 0&&!e.includes(`virtual:i18n-works`))return[];let{regions:r}=n??De(e,t),i=Le(r),a=[];for(let e of r){let{root:n,offset:r}=e;ve(n,(n,o)=>{if(n.type!==`CallExpression`||n.callee.type!==`Identifier`)return;let s=i.tt.has(n.callee.name),c=s||i.tauto.has(n.callee.name);if(!c&&!i.t.has(n.callee.name))return;let l=i.tauto.has(n.callee.name)&&H(n.arguments.at(1));if(n.arguments.length>(c&&!l?3:2))return;let[u]=n.arguments,d=l?void 0:n.arguments.at(1),f=c?n.arguments.at(l?1:2):void 0;if(!H(u)||d?.type===`SpreadElement`||f!==void 0&&!H(f))return;let p=z(u.value);if(!p||!Fe(p))return;d&&Ie(p,t);let m=H(f)?z(f.value):void 0;a.push({source:p,file:t,start:r+n.start,end:r+n.end,valuesStart:d===void 0?void 0:r+d.start,autoPlural:s||void 0,hint:m!==void 0&&m.length>0?m:void 0,component:ze(o,e.component??`<module>`),fingerprint:_e({source:p,autoPlural:s,hint:m})})})}return a.sort((e,t)=>e.start-t.start)}const Ve=e=>JSON.stringify(e,null,2)+`
|
|
7
|
-
`,He=e=>d(`sha256`).update(e).digest(`hex`);async function Ue(e,t,n){let i;try{i=await _(e,`utf8`)}catch(i){return i.code===`ENOENT`||n?.(r(`could not read ${e}: ${i.message}`)),t}try{return JSON.parse(i)}catch(i){let a=`${e}.corrupt-${Date.now()}`;return await v(e,a).catch(()=>void 0),n?.(r(`${e} is not valid JSON (${i.message}); moved to ${a} and starting fresh.`)),t}}async function We(e,t){await g(c.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${f()}.tmp`;await te(n,t,`utf8`),await v(n,e)}async function Ge(e,t){await _(e,`utf8`).catch(()=>void 0)!==t&&await We(e,t)}var Ke=class extends Error{partial;failed;constructor(e,t,n){super(e),this.partial=t,this.failed=n,this.name=`PartialTranslationError`}};function qe(e){return e instanceof Error&&e.name===`PartialTranslationError`&&`partial`in e}var Je=class{providers;onFallback;constructor(e,t=()=>{}){this.providers=e,this.onFallback=t}async translate(e){let t={},n=e.messages,r,i;for(let[a,{name:o,provider:s}]of this.providers.entries()){try{Object.assign(t,await s.translate({...e,messages:n}))}catch(e){r??=e,i=e,qe(e)&&Object.assign(t,e.partial);let s=this.providers.at(a+1);s&&n.some(e=>!Object.hasOwn(t,e.id))&&this.onFallback(`${o} failed (${Ye(e)}); sending the rest to ${s.name}.`)}if(n=n.filter(e=>!Object.hasOwn(t,e.id)),!n.length)return t}throw Object.keys(t).length===0?r:new Ke(`${n.length} messages failed to translate: ${Ye(i)}`,t,n.length)}};const Ye=e=>e instanceof Error?e.message:String(e),Xe=e=>typeof e==`object`&&!!e&&typeof e.translate==`function`;function Ze(t,n){if(t===void 0)return;if(Xe(t))return t;let{primary:r,...i}=t,a=[];for(let[t,n]of Object.entries(i))if(n!==void 0){if(!Xe(n))throw e(`provider "${t}" must be an object with a translate(input) method. Use hosted(), local(), or a provider class exported by i18n-works.`);a.push({name:t,provider:n})}if(r!==void 0){let t=a.findIndex(e=>e.name===r);if(t<0)throw e(`primary provider "${r}" is not configured. Add it under provider in vite-i18n.config.js, or change primary to one of: ${a.map(e=>e.name).join(`, `)||`none`}.`);a.unshift(...a.splice(t,1))}if(a.length!==0)return a.length===1?a[0].provider:new Je(a,n)}async function Qe(e,t,n){let r=Array(e.length),i=0;return await Promise.all(Array.from({length:Math.min(Math.max(1,t),e.length)},async()=>{for(;i<e.length;){let t=i++;try{r[t]={status:`fulfilled`,value:await n(e[t])}}catch(e){r[t]={status:`rejected`,reason:e}}}})),r}var $e=class{available;waiters=[];constructor(e){this.available=Math.max(1,Math.floor(e))}async run(e){await this.acquire();try{return await e()}finally{this.release()}}acquire(){return this.available>0?(this.available--,Promise.resolve()):new Promise(e=>this.waiters.push(e))}release(){let e=this.waiters.shift();e?e():this.available++}};const et={anthropic:{"claude-haiku-5-5":{input:.1,output:.5},"claude-haiku-4-5":{input:1,output:5}},openai:{"gpt-4.1":{input:2,output:8},"gpt-4.1-mini":{input:.4,output:1.6},"gpt-4o":{input:2.5,output:10},"gpt-4o-mini":{input:.15,output:.6},"gpt-5-mini":{input:.25,output:2},"gpt-5-nano":{input:.05,output:.4}}};function tt(e){let t=et[e.provider]?.[e.model];if(t!==void 0&&e.inputTokens!==void 0&&e.outputTokens!==void 0)return(e.inputTokens*t.input+e.outputTokens*t.output)/1e6}const nt=e=>console.log(`[${t} costs] ${(/* @__PURE__ */ new Date()).toISOString()} ${e}`);function rt(e,t,n){let r=n.inputTokens===void 0||n.outputTokens===void 0?`tokens not reported`:`${n.inputTokens} input + ${n.outputTokens} output tokens`,i=tt(n),a=i===void 0?`cost unknown`:`cost $${i.toFixed(6)}`;nt(`${e} -> ${t} ${n.ids.length} messages (${n.ids.join(`, `)}) via ${n.provider} ${n.model}: ${r}, ${a}`)}function it(e,t,n){nt(`${e} -> ${t} ${n} messages translated, provider reported no usage: cost unknown`)}const at=43200,ot=()=>({version:1,entries:{},costs:{}});function st(e,t,n,r,i=(/* @__PURE__ */ new Date()).toISOString()){let a=`call_${f().replaceAll(`-`,``).slice(0,16)}`,o=tt(r);return e.costs[a]={id:a,at:i,sourceLocale:t,locale:n,provider:r.provider,model:r.model,ids:r.ids,...r.inputTokens===void 0?{}:{inputTokens:r.inputTokens},...r.outputTokens===void 0?{}:{outputTokens:r.outputTokens},...o===void 0?{}:{cost:o}},a}function ct(e,t){return`${e}:${String(t).padStart(12,`0`)}`}function lt(e){let t=e.lastIndexOf(`:`);return{file:e.slice(0,t),start:Number(e.slice(t+1))}}function ut(e){let{file:t,start:n}=lt(e);return ct(t,n)}function J(e,t){if(e.length<2)return;let n=new Map(e.map(e=>[e,t(e)]));e.sort((e,t)=>n.get(e).localeCompare(n.get(t)))}function dt(e,t){let n=Array(e.length),r=/* @__PURE__ */ new Set,i=/* @__PURE__ */ new Map;for(let e of t){let t=i.get(e.component)??[];t.push(e),i.set(e.component,t)}e.forEach((e,t)=>{let a=i.get(e.component)?.shift();a&&(n[t]=a,r.add(a))});let a=t.filter(e=>!r.has(e)),o=0;return e.forEach((e,t)=>{n[t]===void 0&&o<a.length&&(n[t]=a[o++])}),n}function ft(t,n){let r=(/* @__PURE__ */ new Date()).toISOString(),i=Object.values(t.entries),a=/* @__PURE__ */ new Map;for(let e of i){let t=a.get(e.fingerprint)??[];t.push(e),a.set(e.fingerprint,t)}let o=/* @__PURE__ */ new Map;for(let e of n){let t=o.get(e.fingerprint)??[];t.push(e),o.set(e.fingerprint,t)}let s=/* @__PURE__ */ new Map,c=/* @__PURE__ */ new Set,l=[];for(let[e,n]of o){let i=a.get(e)??[],o=i.filter(e=>e.status===`active`),u=i.filter(e=>e.status===`orphaned`);J(n,e=>ct(e.file,e.start)),J(o,e=>ut(e.location)),J(u,e=>ut(e.location)),n.length!==o.length&&(n.length>1||o.length>1)&&l.push(n[0].source);let d=dt(n,o),p=n.flatMap((e,t)=>d[t]===void 0?[t]:[]),m=dt(p.map(e=>n[e]),u);p.forEach((e,t)=>{d[e]=m[t]});for(let[e,i]of n.entries()){let n=d[e];if(n)s.set(i,n.id),n.status=`active`,n.lastSeen=r,n.source=i.source,n.component=i.component,n.autoPlural=i.autoPlural,n.hint=i.hint,n.location=`${i.file}:${i.start}`,c.add(n.id);else{let e=`msg_${f().replaceAll(`-`,``).slice(0,16)}`;s.set(i,e),t.entries[e]={id:e,source:i.source,component:i.component,fingerprint:i.fingerprint,autoPlural:i.autoPlural,hint:i.hint,location:`${i.file}:${i.start}`,status:`active`,firstSeen:r,lastSeen:r},c.add(e)}}}for(let e of Object.values(t.entries))c.has(e.id)||(e.status=`orphaned`);return{registry:t,ambiguous:l,messages:n.map(t=>{let n=s.get(t);if(n===void 0)throw e(`no message ID was assigned to ${t.file}:${t.start}`);return{...t,id:n}})}}function pt(e,t,n=Date.now()){let r=n-t*6e4,i=[];for(let[t,n]of Object.entries(e.entries))n.status===`orphaned`&&Date.parse(n.lastSeen)<=r&&(delete e.entries[t],i.push(n));return i}const mt=()=>({messages:{},sources:{}});function Y(t,n){if(!fe.test(n))throw e(`"${n}" is not a valid locale tag.`);return c.join(t,`${n}.json`)}const ht=(e,t,n)=>{let i={};for(let[a,o]of Object.entries(e))typeof o==`string`?i[a]=o:t?.(r(`dropped non-text value for "${a}" in ${n}.`));return i};async function gt(e,t){let n=await Ue(e,null,t),r=P(se,n);return r.ok?{messages:ht(r.value.messages,t,e),sources:ht(r.value.sources,t,e)}:mt()}const _t=(e,t)=>Ge(e,Ve(t));function vt(e,t){let n={},r=[];for(let[i,a]of Object.entries(e))t.has(i)?n[i]=a:r.push(i);return{catalog:n,removed:r}}function yt(e,t){let n=vt(e.messages,t),r=vt(e.sources,t);return{file:{messages:n.catalog,sources:r.catalog},removed:[.../* @__PURE__ */ new Set([...n.removed,...r.removed])]}}async function bt(e,t){let n=await Ue(e,null,t);if(n===null)return ot();let i=P(ue,n);if(!i.ok)return t?.(r(`${e} has an unsupported format; message IDs will be regenerated.`)),ot();let a={};for(let[n,o]of Object.entries(i.value.entries)){let i=P(ce,o);i.ok?a[n]=i.value:t?.(r(`dropped invalid registry entry "${n}" in ${e}.`))}let o={};for(let[n,a]of Object.entries(i.value.costs??{})){let i=P(le,a);i.ok?o[n]=i.value:t?.(r(`dropped invalid cost record "${n}" in ${e}.`))}return{version:1,entries:a,costs:o}}async function xt(e,t){await Ge(e,Ve(t))}const X=e=>console.log(`[${t} debug] ${(/* @__PURE__ */ new Date()).toISOString()} ${e}`);async function St(e){let{provider:t,sourceLocale:n,locale:r,requests:a,previous:o,debug:s,costs:c}=e,{messages:l,sources:u}=yt(o,new Set(a.map(e=>e.id))).file,d=a.filter(e=>!Object.hasOwn(l,e.id)||u[e.id]!==e.source),f={},p=0,m,h=[];if(d.length&&t){if(s===!0)for(let e of d)X(`sent ${n} -> ${r} ${e.id}: ${JSON.stringify(e.source)} (context: ${e.context})`);let e=c===!0?e=>{h.push(e),rt(n,r,e)}:void 0;try{f=await t.translate({sourceLocale:n,targetLocale:r,messages:d,...e===void 0?{}:{onUsage:e}})}catch(e){if(!qe(e))throw e;f=e.partial,p=e.failed,m=e.message}if(c===!0&&h.length===0&&it(n,r,Object.keys(f).length),s===!0)for(let e of d){let t=f[e.id];X(`received ${n} -> ${r} ${e.id}: ${typeof t==`string`?JSON.stringify(t):`(no translation)`}`)}}let g={...l},_={...u};for(let e of d){delete g[e.id],delete _[e.id];let t=f[e.id];if(e.autoPlural===!0&&!(typeof t==`string`&&t.includes(`{count`)&&t.includes(`, plural,`)&&t.includes(`other`)))continue;let n=e.autoPlural===!0?[`count`]:[];typeof t==`string`&&t.trim()&&i(e.source,t,n)&&(g[e.id]=t,_[e.id]=e.source)}let v=a.filter(e=>!Object.hasOwn(g,e.id)).length;return{file:{messages:g,sources:_},untranslated:v,requested:d.length,failed:p,failure:m,calls:h}}async function Ct(e){let t=structuredClone(e.registry),{ambiguous:n,messages:r}=ft(t,e.files.flatMap(e=>e.messages)),i=pt(t,e.orphanRetentionMinutes),a={};for(let e of r)a[e.id]=e.source;let o=r.map(e=>({id:e.id,source:e.source,context:e.component,autoPlural:e.autoPlural,hint:e.hint})),s=o.some(e=>e.hint!==void 0)&&!e.locales.includes(e.sourceLocale)?[...e.locales,e.sourceLocale]:e.locales,c=await Qe(s,e.localeConcurrency,t=>St({provider:e.provider,sourceLocale:e.sourceLocale,locale:t,requests:t===e.sourceLocale?o.filter(e=>e.hint!==void 0):o,previous:e.previous.get(t)??mt(),debug:e.debug,costs:e.costs})),l=/* @__PURE__ */ new Map,u=/* @__PURE__ */ new Map;return c.forEach((n,r)=>{let i=s[r];if(n.status===`fulfilled`){l.set(i,n.value);for(let r of n.value.calls)st(t,e.sourceLocale,i,r);if(i===e.sourceLocale)for(let[e,t]of Object.entries(n.value.file.messages))a[e]=t}else u.set(i,n.reason)}),{registry:t,ambiguous:n,pruned:i,messages:r,sourceFile:{messages:a,sources:{}},locales:l,failures:u}}async function Z(e){try{let t=await ee(e);return`${t.mtimeMs}:${t.size}`}catch{return}}var Q=class{entries=/* @__PURE__ */ new Map;async read(e,t){let n=await Z(e),r=this.entries.get(e);if(n!==void 0&&r?.stamp===n)return r.value;let i=await t();return n!==void 0&&this.entries.set(e,{stamp:n,value:i,written:!1}),i}async holds(e,t,n){let r=this.entries.get(e);return r?.written!==!0||!n(r.value,t)?!1:await Z(e)===r.stamp}async write(e,t,n){await n();let r=await Z(e);r!==void 0&&this.entries.set(e,{stamp:r,value:t,written:!0})}};function $(e,t){if(!e)return!1;let n=Object.keys(t);return n.length===Object.keys(e).length&&n.every(n=>e[n]===t[n])}function wt(e,t){return $(e.messages,t.messages)&&$(e.sources,t.sources)}var Tt=class{extractions=/* @__PURE__ */ new Map;fileMessages=/* @__PURE__ */ new Map;catalogs=/* @__PURE__ */ new Map;catalogFiles={};warnedFiles=/* @__PURE__ */ new Set;legacySidecarsRemoved=!1;locales=new Q;registries=new Q;hashOf(e){return this.extractions.get(e)?.hash}readLocale(e,t){return this.locales.read(e,()=>gt(e,t))}async writeLocale(e,t){if(!await this.locales.holds(e,t,wt))return this.locales.write(e,t,()=>_t(e,t))}readRegistry(e,t){return this.registries.read(e,()=>bt(e,t))}writeRegistry(e,t){return this.registries.write(e,t,()=>xt(e,t))}};const Et=[`src/**/*.{tsx,jsx,ts,js,svelte,astro}`],Dt=[`**/*.test.*`,`**/node_modules/**`],Ot=e=>({info:t=>e.info(t),warn:t=>e.warn(t),error:t=>e.error(t)});async function kt(e,t){await Promise.all(t.map(t=>y(c.join(e,`${t}.sources.json`),{force:!0})))}var At=class{options;sourceLocale;locales;delivery;state=new Tt;provider;directory;debug;costs;orphanRetentionMinutes;include;exclude;activeReport;config;queue=Promise.resolve();constructor(e){this.options=e,this.sourceLocale=e.sourceLocale??`en`,this.locales=e.locales,this.directory=e.directory??`.i18n-works`,this.delivery=e.delivery??`build`,this.debug=e.debug??!1,this.costs=e.costs??!1,this.orphanRetentionMinutes=e.orphanRetentionMinutes??43200,this.include=e.include??Et,this.exclude=e.exclude??Dt,this.provider=Ze(e.provider,e=>this.activeReport?.warn(e))}attach(e){this.config=e}explicitLocale(){return this.options.locale??process.env.I18N_WORKS_LOCALE}selectedLocale(){return this.explicitLocale()??this.sourceLocale}isServing(){return this.config.command===`serve`}localesDir(){return c.resolve(this.config.root,this.directory,`locales`)}registryFile(){return c.resolve(this.config.root,this.directory,`registry.json`)}isSourceCandidate(e){if(!/\.(?:[jt]sx?|svelte|astro)$/.test(e))return!1;let t=c.relative(this.config.root,e).split(c.sep).join(`/`);return this.include.some(e=>c.matchesGlob(t,e))&&!this.exclude.some(e=>c.matchesGlob(t,e))}localesToTranslate(){let e=this.locales.filter(e=>e!==this.sourceLocale),t=this.explicitLocale();return this.delivery===`build`&&t!==void 0&&t!==``&&!this.isServing()?e.filter(e=>e===t):e}async collectFiles(){let e=[];for await(let t of h(this.include,{cwd:this.config.root})){let n=t.split(c.sep).join(`/`);this.exclude.some(e=>c.matchesGlob(n,e))||e.push(c.resolve(this.config.root,t))}return e}async extractFiles(e,t,n){let r=await Qe(e,16,e=>this.extractFile(e,t,n)),i=/* @__PURE__ */ new Map,a=[];return e.forEach((e,t)=>{let n=r[t];if(n.status===`rejected`)throw n.reason;i.set(e,n.value),a.push({file:e,messages:n.value.messages})}),{nextExtractions:i,indexed:a}}async extractFile(e,t,n){let r=this.state.extractions.get(e);if(r&&t&&e!==n)return r;let i=await _(e,`utf8`),a=He(i);return r?.hash===a?r:{hash:a,messages:Be(i,e)}}reportLocales(e,t){for(let[n,i]of t.locales){if(i.requested>0&&!this.provider&&this.options.failOnMissingProvider===!0&&e.error(`Missing ${i.requested} ${n} translations and no provider is configured. Add a provider to ${R}, for example provider: hosted(HostedService.OpenAI, apiKey), or set failOnMissingProvider to false.`),i.untranslated){let t=this.provider?e.warn:e.info,a=this.provider?``:` No provider is configured; add one to ${R} to translate them.`;t(r(`${i.untranslated} ${n} messages have no translation and fall back to the source text.${a}`))}i.failed&&e.warn(r(`${i.failed} ${n} translation batches failed (${i.failure}); they will be requested again on the next build.`))}}async sync(e,t){let n=this.state,i=this.sourceLocale;this.activeReport=e;let a=t!==void 0&&n.extractions.has(t),o=a?[...n.extractions.keys()]:await this.collectFiles(),{nextExtractions:s,indexed:c}=await this.extractFiles(o,a,t),l=this.localesDir(),u=this.localesToTranslate(),d=[i,...u],[f,...p]=await Promise.all([n.readRegistry(this.registryFile(),e.warn),...d.map(t=>n.readLocale(Y(l,t),e.warn))]),m=new Map(d.map((e,t)=>[e,p[t]])),h=await Ct({files:c,registry:f,orphanRetentionMinutes:this.orphanRetentionMinutes,sourceLocale:i,locales:u,localeConcurrency:Math.max(1,Math.floor(this.options.localeConcurrency??2)),previous:m,provider:this.provider,debug:this.debug,costs:this.costs});if(this.debug)for(let e of h.pruned)X(`removed ${e.id} ${JSON.stringify(e.source)} (last seen ${e.lastSeen})`);if(h.pruned.length&&e.info(r(`removed ${h.pruned.length} registry entries no longer in the source.`)),await n.writeRegistry(this.registryFile(),h.registry),h.ambiguous.length){let t=r(`${h.ambiguous.length} duplicated texts changed occurrence count, so their IDs may have moved (e.g. "${h.ambiguous[0]}").`);this.options.onAmbiguous===`error`?e.error(t):e.warn(t)}await n.writeLocale(Y(l,i),h.sourceFile),n.legacySidecarsRemoved||=(await kt(l,[i,...this.locales]),!0),await Promise.all([...h.locales].map(([e,t])=>n.writeLocale(Y(l,e),t.file)));let g=/* @__PURE__ */ new Map([[i,h.sourceFile.messages]]);for(let[e,t]of h.locales)g.set(e,t.file.messages);for(let e of h.failures.keys())g.set(e,m.get(e)?.messages??{});let _=[...g].filter(([e,t])=>!$(n.catalogs.get(e),t)).map(([e])=>e),v=0;n.fileMessages=/* @__PURE__ */ new Map;for(let{file:e,messages:t}of c)n.fileMessages.set(e,h.messages.slice(v,v+t.length)),v+=t.length;n.extractions=s,n.catalogs=g,n.catalogFiles=Object.fromEntries(this.locales.map(e=>[e,Y(l,e)])),this.reportLocales(e,h),h.messages.length&&e.info(r(`indexed ${h.messages.length} messages across ${o.length} files.`));let y=[...h.failures];for(let[t,n]of y.slice(1))e.warn(r(`${t} translation failed: ${n.message}`));if(y.length)throw y[0][1];return _}runSync(e,t){let n=this.queue.then(()=>this.sync(e,t));return this.queue=n.then(()=>void 0,()=>void 0),n}};export{me as C,ae as D,re as E,oe as O,R as S,ie as T,Pe as _,yt as a,Ne as b,_t as c,pt as d,$e as f,He as g,Ke as h,bt as i,P as k,at as l,Ze as m,Ot as n,gt as o,Je as p,X as r,xt as s,At as t,lt as u,G as v,he as w,ge as x,W as y};
|