i18n-works 0.1.15 → 0.1.17
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/README.md
CHANGED
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
<img src="https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg" alt="semantic-release">
|
|
11
11
|
</div>
|
|
12
12
|
|
|
13
|
-
# i18n-works (
|
|
13
|
+
# i18n-works (Vite-plugin) & CLI tools & 🤖
|
|
14
14
|
|
|
15
15
|

|
|
16
16
|
|
|
@@ -23,8 +23,6 @@ A Vite plugin and CLI tools for AI-powered internationalization (i18n) and local
|
|
|
23
23
|
|
|
24
24
|
[**Read the docs >>**](https://rand0mc0d3r.github.io/i18n-works/)
|
|
25
25
|
|
|
26
|
-
|
|
27
|
-
|
|
28
26
|
## Your favorite frameworks, supported
|
|
29
27
|
|
|
30
28
|

|
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-1mH_oPMI.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-1mH_oPMI.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-CHmobLly.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
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};
|
|
@@ -1,4 +1,4 @@
|
|
|
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-
|
|
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
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
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
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(`
|
|
@@ -4,4 +4,4 @@ import{a as e,i as t,n,o as r,r as i}from"./icu-Cui2dM71.js";import{createRequir
|
|
|
4
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
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
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,exclude:this.exclude}))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};
|
|
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};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "i18n-works",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.17",
|
|
4
4
|
"description": "Build-time AI localization for strings marked with t() in React, Solid, Svelte and Astro applications",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"ai",
|
|
@@ -105,7 +105,7 @@
|
|
|
105
105
|
}
|
|
106
106
|
},
|
|
107
107
|
"engines": {
|
|
108
|
-
"node": ">=
|
|
108
|
+
"node": ">=22.18.0"
|
|
109
109
|
},
|
|
110
110
|
"packageManager": "bun@1.4.4-canary.20261114.1"
|
|
111
111
|
}
|