@belocal/js-sdk 0.6.1 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/browser.cjs CHANGED
@@ -1,3 +1,3 @@
1
- 'use strict';var jsMd5=require('js-md5');function q(a,t,s,e){let r=[...a].sort(),i=null;if(e&&Object.keys(e).length>0){i={};let n=Object.keys(e).sort();for(let o of n)i[o]=e[o];}let u=JSON.stringify([r,t,s||null,i]);return jsMd5.md5(u)}async function S(a,t,s){a.debug&&console.log(`[BeLocal Multi Transport] Sending multi request with ${t.length} texts`);try{let e=new Map;t.forEach(n=>{let o=JSON.stringify({lang:n.lang,sourceLang:n.sourceLang||null,context:n.context||null});e.has(o)||e.set(o,[]),e.get(o).push(n);});let r=new Map,i=Array.from(e.entries()).map(([n,o])=>{let c=o[0],g=o.map(d=>d.text),p=q(g,c.lang,c.sourceLang,c.context);return r.set(p,o),{requestId:p,texts:g,lang:c.lang,sourceLang:c.sourceLang,context:c.context}}),l=await a.baseTransport.post({requests:i},"/v1/translate/multi");a.debug&&console.log(`[BeLocal Multi Transport] Multi response received with ${l.results.length} groups`);let u=new Map;l.results.forEach(n=>{u.set(n.requestId,{texts:n.data.texts,status:n.data.status});}),r.forEach((n,o)=>{let c=u.get(o);if(!c){a.debug&&console.error(`[BeLocal Multi Transport] No result found for requestId: ${o}`),n.forEach(g=>{g.reject(new Error(`No result found for request ${o}`));});return}if(c.texts.length!==n.length){let g=new Error(`Mismatch: expected ${n.length} texts, got ${c.texts.length} for requestId ${o}`);a.debug&&console.error("[BeLocal Multi Transport]",g.message),n.forEach(p=>p.reject(g));return}n.forEach((g,p)=>{let d=c.texts[p],x=c.status||"success";a.debug&&console.log(`[BeLocal Multi Transport] Success for requestId ${o}[${p}]: "${d}"`),g.resolve({text:d,status:x});});});}catch(e){a.debug&&console.error("[BeLocal Multi Transport] Multi request error:",e);let r=e instanceof Error?e:new Error(String(e));t.forEach(i=>i.reject(r));}finally{}}function b(a,t){if(t.currentMulti.length===0||t.isRequestInFlight)return;let s=[...t.currentMulti];t.currentMulti=[],t.multiTimer=null,t.isRequestInFlight=true,S(a,s).finally(()=>{if(t.isRequestInFlight=false,t.currentMulti.length>0){let e=a.batchWindowMs??50;t.multiTimer=setTimeout(()=>b(a,t),e);}});}function T(a){let t=a.batchWindowMs??50,s={currentMulti:[],multiTimer:null,isRequestInFlight:false};return ({text:e,lang:r,source_lang:i,ctx:l})=>new Promise((u,n)=>{if(a.debug){let c=jsMd5.md5(JSON.stringify([e,r,i||null,l||null]));console.log(`[BeLocal Multi Transport] Queuing request ${c}: "${e}" to ${r}`);}let o={text:e,lang:r,sourceLang:i,context:l,resolve:u,reject:n};s.currentMulti.push(o),s.multiTimer===null&&!s.isRequestInFlight&&(s.multiTimer=setTimeout(()=>b(a,s),t));})}var B=(()=>{try{return "0.6.1"}catch{return "undefined"}})(),w="js";function E(a,t){let s=r=>{if(r==null)return r;if(Array.isArray(r))return r.map(s);if(typeof r=="object"){let i={};for(let l of Object.keys(r).sort())i[l]=s(r[l]);return i}return r},e=JSON.stringify(s(t));return `${a}:${e}`}var h=class{constructor(t,s){this.wrappedTransport=t;this.debug=s;this.inFlightRequests=new Map;}async post(t,s){let e=E(s,t),r=this.inFlightRequests.get(e);if(r)return this.debug&&console.log(`[DedupeTransport] Deduplicating request to ${s}`),r;let i=this.wrappedTransport.post(t,s).finally(()=>{this.inFlightRequests.delete(e);});return this.inFlightRequests.set(e,i),this.debug&&console.log(`[DedupeTransport] New request to ${s} (${this.inFlightRequests.size} in-flight)`),i}};var L="https://dynamic.belocal.dev",f=class{constructor(t){this.config=t;}async post(t,s){let e=`${L}${s}`,r=new AbortController,i=this.config.timeoutMs??1e4,l=setTimeout(()=>r.abort(),i);this.config.debug&&console.log(`[Base Browser Transport] POST request to ${e}`,t);try{let u=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json","x-sdk":w,"x-sdk-version":B,...this.config.headers},body:JSON.stringify(t),signal:r.signal});if(!u.ok){let o=`HTTP ${u.status}: ${u.statusText}`;throw this.config.debug&&console.error("[Base Browser Transport] Request failed:",o),new Error(o)}let n=await u.json();return this.config.debug&&console.log("[Base Browser Transport] Request successful:",n),n}finally{l&&clearTimeout(l);}}};function m(a){let t=new f(a);return new h(t,a.debug)}var y=class{constructor(){this.storage=new Map;}get(t){return this.storage.get(t)||null}set(t,s){this.storage.set(t,s);}isAvailable(){return true}};var R=class{constructor(t){let{apiKey:s,batchWindowMs:e=50,timeoutMs:r=1e4,debug:i=false}=t;this.debug=i,this.cache=new y;let l={Authorization:`Bearer ${s}`},u=m({headers:l,timeoutMs:r,debug:this.debug});this.transport=T({baseTransport:u,debug:this.debug,batchWindowMs:e}),this.debug&&console.log("[BeLocal Engine] Multi transport created with config:",{baseUrl:"https://dynamic.belocal.dev",timeoutMs:r,batchWindowMs:e});}async translate(t,s,e,r){return (await this.translateMany([t],s,e,r))[0]}async translateMany(t,s,e,r){let i=new Array(t.length),l=[];for(let u=0;u<t.length;u++){let n=t[u],o=this.generateCacheKey(n,s,e,r),c=this.cache.get(o);if(c){i[u]=c,this.debug&&console.log("[BeLocal Engine] Translation from cache:",n);continue}i[u]=null,l.push({index:u,text:n});}return l.length>0&&(await Promise.all(l.map(async({index:n,text:o})=>{let c=await this.transport({text:o,lang:s,source_lang:e,ctx:r});if(c.status!=="error"){let g=this.generateCacheKey(o,s,e,r);this.cache.set(g,c.text),this.debug&&console.log("[BeLocal Engine] Translation from API, cached:",o);}else this.debug&&console.log("[BeLocal Engine] Translation from API (not cached due to error status):",o);return {index:n,translation:c.text}}))).forEach(({index:n,translation:o})=>{i[n]=o;}),i}async t(t,s,e,r){return r?this.translate(t,s,e,{user_ctx:r}):this.translate(t,s,e)}generateCacheKey(t,s,e,r){let i=r?Object.keys(r).sort().reduce((u,n)=>(u[n]=r[n],u),{}):null;return jsMd5.md5(JSON.stringify({text:t,lang:s,source_lang:e||null,ctx:i}))}};
2
- exports.BaseBrowserTransport=f;exports.BelocalEngine=R;exports.createBaseBrowserTransport=m;exports.createMultiTransport=T;//# sourceMappingURL=browser.cjs.map
1
+ 'use strict';var jsMd5=require('js-md5');var B=(()=>{try{return "1.0.0"}catch{return "undefined"}})(),b="js";function E(a,t){let s=r=>{if(r==null)return r;if(Array.isArray(r))return r.map(s);if(typeof r=="object"){let i={};for(let c of Object.keys(r).sort())i[c]=s(r[c]);return i}return r},e=JSON.stringify(s(t));return `${a}:${e}`}var h=class{constructor(t,s){this.wrappedTransport=t;this.debug=s;this.inFlightRequests=new Map;}async post(t,s){let e=E(s,t),r=this.inFlightRequests.get(e);if(r)return this.debug&&console.log(`[DedupeTransport] Deduplicating request to ${s}`),r;let i=this.wrappedTransport.post(t,s).finally(()=>{this.inFlightRequests.delete(e);});return this.inFlightRequests.set(e,i),this.debug&&console.log(`[DedupeTransport] New request to ${s} (${this.inFlightRequests.size} in-flight)`),i}};var S="https://dynamic.belocal.dev",f=class{constructor(t){this.config=t;}async post(t,s){let e=`${S}${s}`,r=new AbortController,i=this.config.timeoutMs??1e4,c=setTimeout(()=>r.abort(),i);this.config.debug&&console.log(`[Base Browser Transport] POST request to ${e}`,t);try{let u=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json","x-sdk":b,"x-sdk-version":B,...this.config.headers},body:JSON.stringify(t),signal:r.signal});if(!u.ok){let o=`HTTP ${u.status}: ${u.statusText}`;throw this.config.debug&&console.error("[Base Browser Transport] Request failed:",o),new Error(o)}let n=await u.json();return this.config.debug&&console.log("[Base Browser Transport] Request successful:",n),n}finally{c&&clearTimeout(c);}}};function m(a){let t=new f(a);return new h(t,a.debug)}function _(a,t,s,e){let r=[...a].sort(),i=null;if(e&&Object.keys(e).length>0){i={};let n=Object.keys(e).sort();for(let o of n)i[o]=e[o];}let u=JSON.stringify([r,t,s||null,i]);return jsMd5.md5(u)}async function K(a,t,s){a.debug&&console.log(`[BeLocal Multi Transport] Sending multi request with ${t.length} texts`);try{let e=new Map;t.forEach(n=>{let o=JSON.stringify({lang:n.lang,sourceLang:n.sourceLang||null,context:n.context||null});e.has(o)||e.set(o,[]),e.get(o).push(n);});let r=new Map,i=Array.from(e.entries()).map(([n,o])=>{let l=o[0],g=o.map(d=>d.text),p=_(g,l.lang,l.sourceLang,l.context);return r.set(p,o),{request_id:p,texts:g,lang:l.lang,source_lang:l.sourceLang,ctx:l.context}}),c=await a.baseTransport.post({requests:i},"/v1/translate/multi");a.debug&&console.log(`[BeLocal Multi Transport] Multi response received with ${c.results.length} groups`);let u=new Map;c.results.forEach(n=>{u.set(n.request_id,{texts:n.data.texts,status:n.data.status});}),r.forEach((n,o)=>{let l=u.get(o);if(!l){a.debug&&console.error(`[BeLocal Multi Transport] No result found for request_id: ${o}`),n.forEach(g=>{g.reject(new Error(`No result found for request ${o}`));});return}if(l.texts.length!==n.length){let g=new Error(`Mismatch: expected ${n.length} texts, got ${l.texts.length} for request_id ${o}`);a.debug&&console.error("[BeLocal Multi Transport]",g.message),n.forEach(p=>p.reject(g));return}n.forEach((g,p)=>{let d=l.texts[p],q=l.status||"success";a.debug&&console.log(`[BeLocal Multi Transport] Success for request_id ${o}[${p}]: "${d}"`),g.resolve({text:d,status:q});});});}catch(e){a.debug&&console.error("[BeLocal Multi Transport] Multi request error:",e);let r=e instanceof Error?e:new Error(String(e));t.forEach(i=>i.reject(r));}finally{}}function x(a,t){if(t.currentMulti.length===0||t.isRequestInFlight)return;let s=[...t.currentMulti];t.currentMulti=[],t.multiTimer=null,t.isRequestInFlight=true,K(a,s).finally(()=>{if(t.isRequestInFlight=false,t.currentMulti.length>0){let e=a.batchWindowMs??50;t.multiTimer=setTimeout(()=>x(a,t),e);}});}function M(a){let t=a.batchWindowMs??50,s={currentMulti:[],multiTimer:null,isRequestInFlight:false};return ({text:e,lang:r,source_lang:i,ctx:c})=>new Promise((u,n)=>{if(a.debug){let l=jsMd5.md5(JSON.stringify([e,r,i||null,c||null]));console.log(`[BeLocal Multi Transport] Queuing request ${l}: "${e}" to ${r}`);}let o={text:e,lang:r,sourceLang:i,context:c,resolve:u,reject:n};s.currentMulti.push(o),s.multiTimer===null&&!s.isRequestInFlight&&(s.multiTimer=setTimeout(()=>x(a,s),t));})}var y=class{constructor(){this.storage=new Map;}get(t){return this.storage.get(t)||null}set(t,s){this.storage.set(t,s);}isAvailable(){return true}};var T=class{constructor(t,s){let{apiKey:e,batchWindowMs:r=50,timeoutMs:i=1e4,debug:c=false}=t;this.debug=c,this.cache=new y;let u={Authorization:`Bearer ${e}`},n=s({headers:u,timeoutMs:i,debug:this.debug});this.transport=M({baseTransport:n,debug:this.debug,batchWindowMs:r}),this.debug&&console.log("[BeLocal Engine] Multi transport created with config:",{baseUrl:"https://dynamic.belocal.dev",timeoutMs:i,batchWindowMs:r});}async translate(t,s,e,r){return (await this.translateMany([t],s,e,r))[0]}async translateMany(t,s,e,r){let i=new Array(t.length),c=[];for(let u=0;u<t.length;u++){let n=t[u],o=this.generateCacheKey(n,s,e,r),l=this.cache.get(o);if(l){i[u]=l,this.debug&&console.log("[BeLocal Engine] Translation from cache:",n);continue}i[u]=null,c.push({index:u,text:n});}return c.length>0&&(await Promise.all(c.map(async({index:n,text:o})=>{let l=await this.transport({text:o,lang:s,source_lang:e,ctx:r});if(l.status!=="error"){let g=this.generateCacheKey(o,s,e,r);this.cache.set(g,l.text),this.debug&&console.log("[BeLocal Engine] Translation from API, cached:",o);}else this.debug&&console.log("[BeLocal Engine] Translation from API (not cached due to error status):",o);return {index:n,translation:l.text}}))).forEach(({index:n,translation:o})=>{i[n]=o;}),i}async t(t,s,e,r){return r?this.translate(t,s,e,{user_ctx:r}):this.translate(t,s,e)}generateCacheKey(t,s,e,r){let i=r?Object.keys(r).sort().reduce((u,n)=>(u[n]=r[n],u),{}):null;return jsMd5.md5(JSON.stringify({text:t,lang:s,source_lang:e||null,ctx:i}))}};var R=class extends T{constructor(t){super(t,m);}};
2
+ exports.BaseBrowserTransport=f;exports.BelocalEngine=R;exports.createBaseBrowserTransport=m;exports.createMultiTransport=M;//# sourceMappingURL=browser.cjs.map
3
3
  //# sourceMappingURL=browser.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/transports/multi.ts","../src/version.ts","../src/transports/base/dedupe.ts","../src/transports/base/browser.ts","../src/cache/local.ts","../src/core/engine/browser.ts"],"names":["generateRequestId","texts","lang","sourceLang","context","sortedTexts","sortedContext","sortedKeys","key","json","md5","sendMulti","config","items","state","groups","item","groupKey","requestIdToGroupItems","requests","groupItems","firstItem","requestId","multiResponse","resultMap","result","error","index","translatedText","status","errorToReject","processMulti","itemsToSend","windowMs","createMultiTransport","text","source_lang","ctx","resolve","reject","tempRequestId","requestItem","SDK_VERSION","SDK_NAME","generateRequestKey","endpointPath","data","normalize","value","sorted","normalizedData","DedupeTransport","wrappedTransport","debug","requestKey","existingRequest","requestPromise","BASE_URL","BaseBrowserTransport","url","controller","timeoutMs","timeoutId","response","errorMsg","createBaseBrowserTransport","transport","LocalCache","BelocalEngine","options","apiKey","batchWindowMs","authHeaders","baseTransport","results","cacheMisses","i","cacheKey","cachedResult","translation","sortedCtx","acc"],"mappings":"yCAuCA,SAASA,EAAkBC,CAAAA,CAAiBC,CAAAA,CAAcC,CAAAA,CAAqBC,CAAAA,CAA0C,CAEvH,IAAMC,CAAAA,CAAc,CAAC,GAAGJ,CAAK,CAAA,CAAE,IAAA,EAAK,CAGhCK,CAAAA,CAA+C,KACnD,GAAIF,CAAAA,EAAW,MAAA,CAAO,IAAA,CAAKA,CAAO,CAAA,CAAE,MAAA,CAAS,CAAA,CAAG,CAC9CE,EAAgB,EAAC,CACjB,IAAMC,CAAAA,CAAa,OAAO,IAAA,CAAKH,CAAO,CAAA,CAAE,IAAA,GACxC,IAAA,IAAWI,CAAAA,IAAOD,CAAAA,CAChBD,CAAAA,CAAcE,CAAG,CAAA,CAAIJ,CAAAA,CAAQI,CAAG,EAEpC,CAMA,IAAMC,CAAAA,CAAO,IAAA,CAAK,SAAA,CADL,CAACJ,CAAAA,CAAaH,CAA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5B,GAAA,CAAK4C,CACP,CAC8B,CAAC,CACjC,CACF","file":"browser.cjs","sourcesContent":["import type { Transport, BaseTransport } from '../core/types';\nimport { md5 } from 'js-md5';\n\nexport interface MultiTransportConfig {\n baseTransport: BaseTransport;\n debug?: boolean;\n batchWindowMs?: number;\n}\n\ninterface MultiRequest {\n requestId: string;\n texts: string[];\n lang: string;\n sourceLang?: string;\n context?: Record<string, string>;\n}\n\ninterface MultiRequestItem {\n text: string;\n lang: string;\n sourceLang?: string;\n context?: Record<string, string>;\n resolve: (value: { text: string; status: string }) => void;\n reject: (error: Error) => void;\n}\n\ninterface MultiResponse {\n results: Array<{\n requestId: string;\n data: { texts: string[]; status: string };\n }>;\n}\n\ninterface MultiState {\n currentMulti: MultiRequestItem[];\n multiTimer: ReturnType<typeof setTimeout> | null;\n isRequestInFlight: boolean;\n}\n\nfunction generateRequestId(texts: string[], lang: string, sourceLang?: string, context?: Record<string, string>): string {\n // Сортируем тексты (создаем копию, чтобы не изменять оригинал)\n const sortedTexts = [...texts].sort();\n \n // Сортируем ключи контекста (создаем копию, чтобы не изменять оригинал)\n let sortedContext: Record<string, string> | null = null;\n if (context && Object.keys(context).length > 0) {\n sortedContext = {};\n const sortedKeys = Object.keys(context).sort();\n for (const key of sortedKeys) {\n sortedContext[key] = context[key];\n }\n }\n \n // Создаем JSON массив: [sortedTexts, lang, sourceLang, context]\n // В PHP примере: [$sortedTexts, $this->lang, $context] (sourceLang не включен)\n // Но мы включаем sourceLang для правильной группировки запросов с разными sourceLang\n const data = [sortedTexts, lang, sourceLang || null, sortedContext];\n const json = JSON.stringify(data);\n \n return md5(json);\n}\n\nasync function sendMulti(\n config: MultiTransportConfig,\n items: MultiRequestItem[],\n state: MultiState\n): Promise<void> {\n if (config.debug) {\n console.log(`[BeLocal Multi Transport] Sending multi request with ${items.length} texts`);\n }\n\n try {\n // Группируем тексты по параметрам перевода (lang, sourceLang, context)\n const groups = new Map<string, MultiRequestItem[]>();\n \n items.forEach(item => {\n // Используем ключ для группировки без текстов (только параметры перевода)\n const groupKey = JSON.stringify({\n lang: item.lang,\n sourceLang: item.sourceLang || null,\n context: item.context || null\n });\n \n if (!groups.has(groupKey)) {\n groups.set(groupKey, []);\n }\n groups.get(groupKey)!.push(item);\n });\n\n // Создаем запросы для каждой группы и сохраняем соответствие requestId -> groupItems\n const requestIdToGroupItems = new Map<string, MultiRequestItem[]>();\n const requests: MultiRequest[] = Array.from(groups.entries()).map(([groupKey, groupItems]) => {\n const firstItem = groupItems[0];\n const texts = groupItems.map(item => item.text);\n \n // Генерируем requestId включая отсортированные тексты группы\n // Включаем sourceLang для правильной группировки запросов с разными sourceLang\n const requestId = generateRequestId(\n texts,\n firstItem.lang,\n firstItem.sourceLang,\n firstItem.context\n );\n \n // Сохраняем соответствие requestId -> groupItems\n requestIdToGroupItems.set(requestId, groupItems);\n \n return {\n requestId,\n texts,\n lang: firstItem.lang,\n sourceLang: firstItem.sourceLang,\n context: firstItem.context\n };\n });\n\n const multiResponse: MultiResponse = await config.baseTransport.post({ requests }, '/v1/translate/multi');\n \n if (config.debug) {\n console.log(`[BeLocal Multi Transport] Multi response received with ${multiResponse.results.length} groups`);\n }\n\n // Создаем map для быстрого поиска результатов по requestId\n const resultMap = new Map<string, { texts: string[]; status: string }>();\n multiResponse.results.forEach(result => {\n resultMap.set(result.requestId, { texts: result.data.texts, status: result.data.status });\n });\n\n // Раздаем результаты каждому промису\n requestIdToGroupItems.forEach((groupItems, requestId) => {\n const result = resultMap.get(requestId);\n \n if (!result) {\n if (config.debug) {\n console.error(`[BeLocal Multi Transport] No result found for requestId: ${requestId}`);\n }\n groupItems.forEach(item => {\n item.reject(new Error(`No result found for request ${requestId}`));\n });\n return;\n }\n\n // Маппим тексты обратно на промисы по индексу\n if (result.texts.length !== groupItems.length) {\n const error = new Error(`Mismatch: expected ${groupItems.length} texts, got ${result.texts.length} for requestId ${requestId}`);\n if (config.debug) {\n console.error(`[BeLocal Multi Transport]`, error.message);\n }\n groupItems.forEach(item => item.reject(error));\n return;\n }\n\n groupItems.forEach((item, index) => {\n const translatedText = result.texts[index];\n const status = result.status || 'success';\n \n if (config.debug) {\n console.log(`[BeLocal Multi Transport] Success for requestId ${requestId}[${index}]: \"${translatedText}\"`);\n }\n \n item.resolve({ text: translatedText, status });\n });\n });\n\n } catch (error) {\n if (config.debug) {\n console.error(`[BeLocal Multi Transport] Multi request error:`, error);\n }\n \n // При ошибке сети отклоняем все промисы\n const errorToReject = error instanceof Error ? error : new Error(String(error));\n items.forEach(item => item.reject(errorToReject));\n } finally {\n // Cleanup handled by base transport\n }\n}\n\nfunction processMulti(config: MultiTransportConfig, state: MultiState): void {\n if (state.currentMulti.length === 0 || state.isRequestInFlight) {\n return;\n }\n\n const itemsToSend = [...state.currentMulti];\n state.currentMulti = [];\n state.multiTimer = null;\n state.isRequestInFlight = true;\n\n sendMulti(config, itemsToSend, state).finally(() => {\n state.isRequestInFlight = false;\n \n if (state.currentMulti.length > 0) {\n const windowMs = config.batchWindowMs ?? 50;\n state.multiTimer = setTimeout(() => processMulti(config, state), windowMs);\n }\n });\n}\n\nexport function createMultiTransport(config: MultiTransportConfig): Transport {\n const windowMs = config.batchWindowMs ?? 50;\n\n const state: MultiState = {\n currentMulti: [],\n multiTimer: null,\n isRequestInFlight: false,\n };\n \n return ({ text, lang, source_lang, ctx }) => {\n return new Promise<{ text: string; status: string }>((resolve, reject) => {\n if (config.debug) {\n // Для отладки показываем временный requestId (будет пересчитан при группировке)\n const tempRequestId = md5(JSON.stringify([text, lang, source_lang || null, ctx || null]));\n console.log(`[BeLocal Multi Transport] Queuing request ${tempRequestId}: \"${text}\" to ${lang}`);\n }\n\n const requestItem: MultiRequestItem = {\n text,\n lang,\n sourceLang: source_lang,\n context: ctx,\n resolve,\n reject,\n };\n\n state.currentMulti.push(requestItem);\n\n if (state.multiTimer === null && !state.isRequestInFlight) {\n state.multiTimer = setTimeout(() => processMulti(config, state), windowMs);\n }\n });\n };\n}\n\n","// SDK version - will be replaced during build with tsup define\ndeclare const __SDK_VERSION__: string | undefined;\n\n// Safely check if __SDK_VERSION__ is defined (replaced during build)\nexport const SDK_VERSION: string = \n (() => { try { return typeof __SDK_VERSION__ !== 'undefined' ? __SDK_VERSION__ : 'undefined'; } catch { return 'undefined'; } })();\n\nexport const SDK_NAME = 'js';\n\n","import type { BaseTransport } from '../../core/types';\n\n/**\n * Generates a deterministic key for request deduplication.\n * Uses sorted keys to ensure consistent key generation regardless of object property order.\n */\nfunction generateRequestKey(endpointPath: string, data: any): string {\n // Normalize data by sorting object keys for consistent serialization\n const normalize = (value: any): any => {\n if (value === null || value === undefined) {\n return value;\n }\n if (Array.isArray(value)) {\n return value.map(normalize);\n }\n if (typeof value === 'object') {\n const sorted: Record<string, any> = {};\n for (const key of Object.keys(value).sort()) {\n sorted[key] = normalize(value[key]);\n }\n return sorted;\n }\n return value;\n };\n \n const normalizedData = JSON.stringify(normalize(data));\n return `${endpointPath}:${normalizedData}`;\n}\n\n/**\n * DedupeTransport wraps a BaseTransport instance and deduplicates in-flight requests.\n * If multiple identical requests (same endpointPath + same request body) are made\n * concurrently, they will share the same underlying HTTP request and promise.\n */\nexport class DedupeTransport implements BaseTransport {\n private inFlightRequests = new Map<string, Promise<any>>();\n\n constructor(\n private wrappedTransport: BaseTransport,\n private debug?: boolean\n ) {}\n\n async post(data: any, endpointPath: string): Promise<any> {\n const requestKey = generateRequestKey(endpointPath, data);\n\n // Check if an identical request is already in-flight\n const existingRequest = this.inFlightRequests.get(requestKey);\n if (existingRequest) {\n if (this.debug) {\n console.log(`[DedupeTransport] Deduplicating request to ${endpointPath}`);\n }\n return existingRequest;\n }\n\n // Create new request and store it\n const requestPromise = this.wrappedTransport.post(data, endpointPath)\n .finally(() => {\n // Clean up when request completes (success or failure)\n this.inFlightRequests.delete(requestKey);\n });\n\n this.inFlightRequests.set(requestKey, requestPromise);\n\n if (this.debug) {\n console.log(`[DedupeTransport] New request to ${endpointPath} (${this.inFlightRequests.size} in-flight)`);\n }\n\n return requestPromise;\n }\n}\n","import type { BaseTransport } from '../../core/types';\nimport { SDK_NAME, SDK_VERSION } from '../../version';\nimport { DedupeTransport } from './dedupe';\n\nconst BASE_URL = 'https://dynamic.belocal.dev';\n\nexport interface BaseBrowserTransportConfig {\n headers?: Record<string, string>;\n timeoutMs?: number;\n debug?: boolean;\n}\n\nexport class BaseBrowserTransport implements BaseTransport {\n constructor(private config: BaseBrowserTransportConfig) {}\n\n async post(data: any, endpointPath: string): Promise<any> {\n const url = `${BASE_URL}${endpointPath}`;\n const controller = new AbortController();\n const timeoutMs = this.config.timeoutMs ?? 10000;\n const timeoutId = setTimeout(() => controller.abort(), timeoutMs);\n\n if (this.config.debug) {\n console.log(`[Base Browser Transport] POST request to ${url}`, data);\n }\n\n try {\n const response = await fetch(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'x-sdk': SDK_NAME,\n 'x-sdk-version': SDK_VERSION,\n ...this.config.headers,\n },\n body: JSON.stringify(data),\n signal: controller.signal,\n });\n\n if (!response.ok) {\n const errorMsg = `HTTP ${response.status}: ${response.statusText}`;\n if (this.config.debug) {\n console.error(`[Base Browser Transport] Request failed:`, errorMsg);\n }\n throw new Error(errorMsg);\n }\n\n const result = await response.json();\n if (this.config.debug) {\n console.log(`[Base Browser Transport] Request successful:`, result);\n }\n \n return result;\n } finally {\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n }\n }\n}\n\nexport function createBaseBrowserTransport(config: BaseBrowserTransportConfig): BaseTransport {\n const transport = new BaseBrowserTransport(config);\n return new DedupeTransport(transport, config.debug);\n}\n","import type { Cache } from './types';\n\nexport class LocalCache implements Cache {\n private storage = new Map<string, string>();\n\n get(key: string): string | null {\n return this.storage.get(key) || null;\n }\n\n set(key: string, value: string): void {\n this.storage.set(key, value);\n }\n\n isAvailable(): boolean {\n return true;\n }\n}\n","import type { BelocalEngineOptions, KV, Lang, Transport } from '../types';\nimport { createMultiTransport } from '../../transports/multi';\nimport { createBaseBrowserTransport } from '../../transports/base/browser';\nimport { LocalCache } from '../../cache/local';\nimport type { Cache } from '../../cache/types';\nimport { md5 } from 'js-md5';\n\n/**\n * BeLocal translation engine for browser environments.\n * \n * Provides on-demand translation with automatic request batching, caching, and deduplication.\n * Optimized for browser environments using the Fetch API.\n * \n * @example\n * ```typescript\n * const engine = new BelocalEngine({\n * apiKey: 'your-api-key',\n * debug: true\n * });\n * \n * const translated = await engine.translate('Hello world', 'es');\n * ```\n */\nexport class BelocalEngine {\n private transport: Transport;\n private debug: boolean;\n private cache: Cache;\n\n /**\n * Creates a new BelocalEngine instance.\n * \n * @param options - Configuration options for the engine\n * @throws {Error} If apiKey is not provided or invalid\n * \n * @example\n * ```typescript\n * const engine = new BelocalEngine({\n * apiKey: 'your-api-key',\n * batchWindowMs: 100,\n * timeoutMs: 10000,\n * debug: false\n * });\n * ```\n */\n constructor(options: BelocalEngineOptions) {\n const {\n apiKey,\n batchWindowMs = 50,\n timeoutMs = 10000,\n debug = false\n } = options;\n\n this.debug = debug;\n \n this.cache = new LocalCache();\n\n const authHeaders = {\n 'Authorization': `Bearer ${apiKey}`\n };\n\n const baseTransport = createBaseBrowserTransport({\n headers: authHeaders,\n timeoutMs,\n debug: this.debug\n });\n\n // Always use multi transport\n this.transport = createMultiTransport({\n baseTransport,\n debug: this.debug,\n batchWindowMs\n });\n \n if (this.debug) {\n console.log('[BeLocal Engine] Multi transport created with config:', {\n baseUrl: 'https://dynamic.belocal.dev',\n timeoutMs,\n batchWindowMs\n });\n }\n }\n\n /**\n * Translates a single text string to the target language.\n * \n * Uses in-memory cache to avoid redundant API calls. Results are automatically cached\n * for subsequent requests with the same parameters.\n * \n * @param text - The text to translate\n * @param lang - Target language code (e.g., 'es', 'fr', 'ru')\n * @param source_lang - Optional source language code. If not provided, auto-detection is used\n * @param ctx - Optional key-value pairs for translation context. Supported keys: `user_ctx` (string - descriptive context), `cache_type` ('editable')\n * @returns Promise resolving to the translated text\n * @throws {Error} If the translation request fails (network error, API error, timeout)\n * \n * @example\n * ```typescript\n * // Simple translation\n * const result = await engine.translate('Hello world', 'es');\n * \n * // With source language\n * const result = await engine.translate('Hello world', 'es', 'en');\n * \n * // With context (user_ctx) - descriptive context helps improve translation quality\n * const result = await engine.translate('Hello world', 'es', undefined, { \n * user_ctx: 'greeting message on the homepage' \n * });\n * \n * // With cache_type\n * const result = await engine.translate('Hello world', 'es', undefined, { cache_type: 'editable' });\n * \n * // With source language and context\n * const result = await engine.translate('Hello world', 'es', 'en', { \n * user_ctx: 'greeting message on the homepage' \n * });\n * ```\n */\n async translate(text: string, lang: Lang, source_lang?: string, ctx?: KV): Promise<string> {\n const results = await this.translateMany([text], lang, source_lang, ctx);\n return results[0];\n }\n\n /**\n * Translates multiple text strings to the target language in a single batch.\n * \n * This method is more efficient than calling `translate()` multiple times as it:\n * - Batches requests together to reduce API calls\n * - Checks cache for each text individually\n * - Only requests translations for cache misses\n * - Maintains the order of input texts in the result array\n * \n * @param texts - Array of texts to translate\n * @param lang - Target language code (e.g., 'es', 'fr', 'ru')\n * @param source_lang - Optional source language code. If not provided, auto-detection is used\n * @param ctx - Optional key-value pairs for translation context. Supported keys: `user_ctx` (string - descriptive context in English), `cache_type` ('editable' | string)\n * @returns Promise resolving to an array of translated texts in the same order as input\n * @throws {Error} If the translation request fails (network error, API error, timeout)\n * \n * @example\n * ```typescript\n * // Translate multiple texts\n * const results = await engine.translateMany(['Hello', 'World', 'Test'], 'es');\n * // Returns: ['Hola', 'Mundo', 'Prueba']\n * \n * // With source language\n * const results = await engine.translateMany(['Hello', 'World'], 'fr', 'en');\n * \n * // With context (user_ctx) - descriptive context helps improve translation quality\n * const results = await engine.translateMany(\n * ['Hello', 'World'], \n * 'es', \n * undefined, \n * { user_ctx: 'greeting message on the homepage' }\n * );\n * \n * // With cache_type\n * const results = await engine.translateMany(\n * ['Hello', 'World'], \n * 'es', \n * undefined, \n * { cache_type: 'editable' }\n * );\n * \n * // Empty array returns empty array\n * const results = await engine.translateMany([], 'es');\n * // Returns: []\n * ```\n */\n async translateMany(texts: string[], lang: Lang, source_lang?: string, ctx?: KV): Promise<string[]> {\n const results: (string | null)[] = new Array(texts.length);\n const cacheMisses: Array<{ index: number; text: string }> = [];\n\n for (let i = 0; i < texts.length; i++) {\n const text = texts[i];\n const cacheKey = this.generateCacheKey(text, lang, source_lang, ctx);\n \n const cachedResult = this.cache.get(cacheKey);\n if (cachedResult) {\n results[i] = cachedResult;\n if (this.debug) {\n console.log(`[BeLocal Engine] Translation from cache:`, text);\n }\n continue;\n }\n \n results[i] = null;\n cacheMisses.push({ index: i, text });\n }\n\n if (cacheMisses.length > 0) {\n const translations = await Promise.all(\n cacheMisses.map(async ({ index, text }) => {\n const result = await this.transport({ text, lang, source_lang, ctx });\n \n if (result.status !== 'error') {\n const cacheKey = this.generateCacheKey(text, lang, source_lang, ctx);\n this.cache.set(cacheKey, result.text);\n if (this.debug) {\n console.log(`[BeLocal Engine] Translation from API, cached:`, text);\n }\n } else {\n if (this.debug) {\n console.log('[BeLocal Engine] Translation from API (not cached due to error status):', text);\n }\n }\n \n return { index, translation: result.text };\n })\n );\n\n translations.forEach(({ index, translation }) => {\n results[index] = translation;\n });\n }\n\n return results as string[];\n }\n\n /**\n * Shortcut method for translation with simplified API.\n * \n * This is a convenience method that wraps `translate()`. When `context` is provided as a string,\n * it is automatically wrapped in `{user_ctx: context}` object.\n * \n * @param text - The text to translate\n * @param lang - Target language code (e.g., 'es', 'fr', 'ru')\n * @param source_lang - Optional source language code\n * @param context - Optional descriptive context string in English (will be wrapped as {user_ctx: context})\n * @returns Promise resolving to the translated text\n * @throws {Error} If the translation request fails (network error, API error, timeout)\n * \n * @example\n * ```typescript\n * // Simple translation\n * const result = await engine.t('Hello world', 'es');\n * \n * // With source language\n * const result = await engine.t('Hello world', 'fr', 'en');\n * \n * // With context string (automatically wrapped as {user_ctx: 'greeting message on the homepage'})\n * const result = await engine.t('Hello world', 'es', undefined, 'greeting message on the homepage');\n * \n * // With source language and context\n * const result = await engine.t('Hello world', 'es', 'en', 'greeting message on the homepage');\n * ```\n */\n async t(text: string, lang: Lang, source_lang?: string, context?: string): Promise<string> {\n if (context) {\n return this.translate(text, lang, source_lang, {user_ctx: context});\n }\n return this.translate(text, lang, source_lang);\n }\n\n private generateCacheKey(text: string, lang: Lang, source_lang?: string, ctx?: KV): string {\n const sortedCtx = ctx ? Object.keys(ctx)\n .sort()\n .reduce((acc, key) => {\n acc[key] = ctx[key];\n return acc;\n }, {} as KV) : null;\n\n const data = {\n text,\n lang,\n source_lang: source_lang || null,\n ctx: sortedCtx\n };\n return md5(JSON.stringify(data));\n }\n}\n\n// Re-export types and transports\nexport type { BelocalEngineOptions, Lang, KV, BaseTransport } from '../types';\nexport { createMultiTransport } from '../../transports/multi';\nexport { BaseBrowserTransport, createBaseBrowserTransport } from '../../transports/base';\n"]}
1
+ {"version":3,"sources":["../src/version.ts","../src/transports/base/dedupe.ts","../src/transports/base/browser.ts","../src/transports/multi.ts","../src/cache/local.ts","../src/core/engine/engine.ts","../src/core/engine/browser.ts"],"names":["SDK_VERSION","SDK_NAME","generateRequestKey","endpointPath","data","normalize","value","sorted","key","normalizedData","DedupeTransport","wrappedTransport","debug","requestKey","existingRequest","requestPromise","BASE_URL","BaseBrowserTransport","config","url","controller","timeoutMs","timeoutId","response","errorMsg","result","createBaseBrowserTransport","transport","generateRequestId","texts","lang","sourceLang","context","sortedTexts","sortedContext","sortedKeys","json","md5","sendMulti","items","state","groups","item","groupKey","requestIdToGroupItems","requests","groupItems","firstItem","requestId","multiResponse","resultMap","error","index","translatedText","status","errorToReject","processMulti","itemsToSend","windowMs","createMultiTransport","text","source_lang","ctx","resolve","reject","tempRequestId","requestItem","LocalCache","BelocalEngine","options","baseTransportFactory","apiKey","batchWindowMs","authHeaders","baseTransport","results","cacheMisses","i","cacheKey","cachedResult","translation","sortedCtx","acc"],"mappings":"yCAIO,IAAMA,GACV,IAAM,CAAE,GAAI,CAAE,OAAgD,OAA+B,CAA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B,CAAAA,CAAM,OAAO,IAAA,CAAKA,CAAG,CAAA,CACpC,IAAA,GACA,MAAA,CAAO,CAACoB,CAAAA,CAAK1E,CAAAA,IACZ0E,EAAI1E,CAAG,CAAA,CAAIsD,CAAAA,CAAItD,CAAG,EACX0E,CAAAA,CAAAA,CACN,EAAQ,CAAA,CAAI,KAQjB,OAAO7C,SAAAA,CAAI,IAAA,CAAK,SAAA,CANH,CACX,IAAA,CAAAuB,CAAAA,CACA,IAAA,CAAA9B,CAAAA,CACA,YAAa+B,CAAAA,EAAe,IAAA,CAC5B,GAAA,CAAKoB,CACP,CAC8B,CAAC,CACjC,CACF,CAAA,KCzNab,CAAAA,CAAN,cAA4BA,CAAW,CAiB5C,YAAYC,CAAAA,CAA+B,CACzC,MAAMA,CAAAA,CAAS3C,CAA0B,EAC3C,CACF","file":"browser.cjs","sourcesContent":["// SDK version - will be replaced during build with tsup define\ndeclare const __SDK_VERSION__: string | undefined;\n\n// Safely check if __SDK_VERSION__ is defined (replaced during build)\nexport const SDK_VERSION: string = \n (() => { try { return typeof __SDK_VERSION__ !== 'undefined' ? __SDK_VERSION__ : 'undefined'; } catch { return 'undefined'; } })();\n\nexport const SDK_NAME = 'js';\n\n","import type { BaseTransport } from '../../core/types';\n\n/**\n * Generates a deterministic key for request deduplication.\n * Uses sorted keys to ensure consistent key generation regardless of object property order.\n */\nfunction generateRequestKey(endpointPath: string, data: any): string {\n // Normalize data by sorting object keys for consistent serialization\n const normalize = (value: any): any => {\n if (value === null || value === undefined) {\n return value;\n }\n if (Array.isArray(value)) {\n return value.map(normalize);\n }\n if (typeof value === 'object') {\n const sorted: Record<string, any> = {};\n for (const key of Object.keys(value).sort()) {\n sorted[key] = normalize(value[key]);\n }\n return sorted;\n }\n return value;\n };\n \n const normalizedData = JSON.stringify(normalize(data));\n return `${endpointPath}:${normalizedData}`;\n}\n\n/**\n * DedupeTransport wraps a BaseTransport instance and deduplicates in-flight requests.\n * If multiple identical requests (same endpointPath + same request body) are made\n * concurrently, they will share the same underlying HTTP request and promise.\n */\nexport class DedupeTransport implements BaseTransport {\n private inFlightRequests = new Map<string, Promise<any>>();\n\n constructor(\n private wrappedTransport: BaseTransport,\n private debug?: boolean\n ) {}\n\n async post(data: any, endpointPath: string): Promise<any> {\n const requestKey = generateRequestKey(endpointPath, data);\n\n // Check if an identical request is already in-flight\n const existingRequest = this.inFlightRequests.get(requestKey);\n if (existingRequest) {\n if (this.debug) {\n console.log(`[DedupeTransport] Deduplicating request to ${endpointPath}`);\n }\n return existingRequest;\n }\n\n // Create new request and store it\n const requestPromise = this.wrappedTransport.post(data, endpointPath)\n .finally(() => {\n // Clean up when request completes (success or failure)\n this.inFlightRequests.delete(requestKey);\n });\n\n this.inFlightRequests.set(requestKey, requestPromise);\n\n if (this.debug) {\n console.log(`[DedupeTransport] New request to ${endpointPath} (${this.inFlightRequests.size} in-flight)`);\n }\n\n return requestPromise;\n }\n}\n","import type { BaseTransport } from '../../core/types';\nimport { SDK_NAME, SDK_VERSION } from '../../version';\nimport { DedupeTransport } from './dedupe';\n\nconst BASE_URL = 'https://dynamic.belocal.dev';\n\nexport interface BaseBrowserTransportConfig {\n headers?: Record<string, string>;\n timeoutMs?: number;\n debug?: boolean;\n}\n\nexport class BaseBrowserTransport implements BaseTransport {\n constructor(private config: BaseBrowserTransportConfig) {}\n\n async post(data: any, endpointPath: string): Promise<any> {\n const url = `${BASE_URL}${endpointPath}`;\n const controller = new AbortController();\n const timeoutMs = this.config.timeoutMs ?? 10000;\n const timeoutId = setTimeout(() => controller.abort(), timeoutMs);\n\n if (this.config.debug) {\n console.log(`[Base Browser Transport] POST request to ${url}`, data);\n }\n\n try {\n const response = await fetch(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'x-sdk': SDK_NAME,\n 'x-sdk-version': SDK_VERSION,\n ...this.config.headers,\n },\n body: JSON.stringify(data),\n signal: controller.signal,\n });\n\n if (!response.ok) {\n const errorMsg = `HTTP ${response.status}: ${response.statusText}`;\n if (this.config.debug) {\n console.error(`[Base Browser Transport] Request failed:`, errorMsg);\n }\n throw new Error(errorMsg);\n }\n\n const result = await response.json();\n if (this.config.debug) {\n console.log(`[Base Browser Transport] Request successful:`, result);\n }\n \n return result;\n } finally {\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n }\n }\n}\n\nexport function createBaseBrowserTransport(config: BaseBrowserTransportConfig): BaseTransport {\n const transport = new BaseBrowserTransport(config);\n return new DedupeTransport(transport, config.debug);\n}\n","import type { Transport, BaseTransport } from '../core/types';\nimport { md5 } from 'js-md5';\n\nexport interface MultiTransportConfig {\n baseTransport: BaseTransport;\n debug?: boolean;\n batchWindowMs?: number;\n}\n\ninterface MultiRequest {\n request_id: string;\n texts: string[];\n lang: string;\n source_lang?: string;\n ctx?: Record<string, string>;\n}\n\ninterface MultiRequestItem {\n text: string;\n lang: string;\n sourceLang?: string;\n context?: Record<string, string>;\n resolve: (value: { text: string; status: string }) => void;\n reject: (error: Error) => void;\n}\n\ninterface MultiResponse {\n results: Array<{\n request_id: string;\n data: { texts: string[]; status: string };\n }>;\n}\n\ninterface MultiState {\n currentMulti: MultiRequestItem[];\n multiTimer: ReturnType<typeof setTimeout> | null;\n isRequestInFlight: boolean;\n}\n\nfunction generateRequestId(texts: string[], lang: string, sourceLang?: string, context?: Record<string, string>): string {\n const sortedTexts = [...texts].sort();\n \n let sortedContext: Record<string, string> | null = null;\n if (context && Object.keys(context).length > 0) {\n sortedContext = {};\n const sortedKeys = Object.keys(context).sort();\n for (const key of sortedKeys) {\n sortedContext[key] = context[key];\n }\n }\n \n // Include sourceLang for proper grouping of requests with different source languages\n const data = [sortedTexts, lang, sourceLang || null, sortedContext];\n const json = JSON.stringify(data);\n \n return md5(json);\n}\n\nasync function sendMulti(\n config: MultiTransportConfig,\n items: MultiRequestItem[],\n state: MultiState\n): Promise<void> {\n if (config.debug) {\n console.log(`[BeLocal Multi Transport] Sending multi request with ${items.length} texts`);\n }\n\n try {\n // Group texts by translation parameters\n const groups = new Map<string, MultiRequestItem[]>();\n \n items.forEach(item => {\n const groupKey = JSON.stringify({\n lang: item.lang,\n sourceLang: item.sourceLang || null,\n context: item.context || null\n });\n \n if (!groups.has(groupKey)) {\n groups.set(groupKey, []);\n }\n groups.get(groupKey)!.push(item);\n });\n\n const requestIdToGroupItems = new Map<string, MultiRequestItem[]>();\n const requests: MultiRequest[] = Array.from(groups.entries()).map(([groupKey, groupItems]) => {\n const firstItem = groupItems[0];\n const texts = groupItems.map(item => item.text);\n \n const requestId = generateRequestId(\n texts,\n firstItem.lang,\n firstItem.sourceLang,\n firstItem.context\n );\n \n requestIdToGroupItems.set(requestId, groupItems);\n \n return {\n request_id: requestId,\n texts,\n lang: firstItem.lang,\n source_lang: firstItem.sourceLang,\n ctx: firstItem.context\n };\n });\n\n const multiResponse: MultiResponse = await config.baseTransport.post({ requests }, '/v1/translate/multi');\n \n if (config.debug) {\n console.log(`[BeLocal Multi Transport] Multi response received with ${multiResponse.results.length} groups`);\n }\n\n const resultMap = new Map<string, { texts: string[]; status: string }>();\n multiResponse.results.forEach(result => {\n resultMap.set(result.request_id, { texts: result.data.texts, status: result.data.status });\n });\n\n requestIdToGroupItems.forEach((groupItems, requestId) => {\n const result = resultMap.get(requestId);\n \n if (!result) {\n if (config.debug) {\n console.error(`[BeLocal Multi Transport] No result found for request_id: ${requestId}`);\n }\n groupItems.forEach(item => {\n item.reject(new Error(`No result found for request ${requestId}`));\n });\n return;\n }\n\n if (result.texts.length !== groupItems.length) {\n const error = new Error(`Mismatch: expected ${groupItems.length} texts, got ${result.texts.length} for request_id ${requestId}`);\n if (config.debug) {\n console.error(`[BeLocal Multi Transport]`, error.message);\n }\n groupItems.forEach(item => item.reject(error));\n return;\n }\n\n groupItems.forEach((item, index) => {\n const translatedText = result.texts[index];\n const status = result.status || 'success';\n \n if (config.debug) {\n console.log(`[BeLocal Multi Transport] Success for request_id ${requestId}[${index}]: \"${translatedText}\"`);\n }\n \n item.resolve({ text: translatedText, status });\n });\n });\n\n } catch (error) {\n if (config.debug) {\n console.error(`[BeLocal Multi Transport] Multi request error:`, error);\n }\n \n const errorToReject = error instanceof Error ? error : new Error(String(error));\n items.forEach(item => item.reject(errorToReject));\n } finally {\n // Cleanup handled by base transport\n }\n}\n\nfunction processMulti(config: MultiTransportConfig, state: MultiState): void {\n if (state.currentMulti.length === 0 || state.isRequestInFlight) {\n return;\n }\n\n const itemsToSend = [...state.currentMulti];\n state.currentMulti = [];\n state.multiTimer = null;\n state.isRequestInFlight = true;\n\n sendMulti(config, itemsToSend, state).finally(() => {\n state.isRequestInFlight = false;\n \n if (state.currentMulti.length > 0) {\n const windowMs = config.batchWindowMs ?? 50;\n state.multiTimer = setTimeout(() => processMulti(config, state), windowMs);\n }\n });\n}\n\nexport function createMultiTransport(config: MultiTransportConfig): Transport {\n const windowMs = config.batchWindowMs ?? 50;\n\n const state: MultiState = {\n currentMulti: [],\n multiTimer: null,\n isRequestInFlight: false,\n };\n \n return ({ text, lang, source_lang, ctx }) => {\n return new Promise<{ text: string; status: string }>((resolve, reject) => {\n if (config.debug) {\n const tempRequestId = md5(JSON.stringify([text, lang, source_lang || null, ctx || null]));\n console.log(`[BeLocal Multi Transport] Queuing request ${tempRequestId}: \"${text}\" to ${lang}`);\n }\n\n const requestItem: MultiRequestItem = {\n text,\n lang,\n sourceLang: source_lang,\n context: ctx,\n resolve,\n reject,\n };\n\n state.currentMulti.push(requestItem);\n\n if (state.multiTimer === null && !state.isRequestInFlight) {\n state.multiTimer = setTimeout(() => processMulti(config, state), windowMs);\n }\n });\n };\n}\n\n","import type { Cache } from './types';\n\nexport class LocalCache implements Cache {\n private storage = new Map<string, string>();\n\n get(key: string): string | null {\n return this.storage.get(key) || null;\n }\n\n set(key: string, value: string): void {\n this.storage.set(key, value);\n }\n\n isAvailable(): boolean {\n return true;\n }\n}\n","import type { BelocalEngineOptions, KV, Lang, Transport, BaseTransport } from '../types';\nimport { createMultiTransport } from '../../transports/multi';\nimport { LocalCache } from '../../cache/local';\nimport type { Cache } from '../../cache/types';\nimport { md5 } from 'js-md5';\n\n/**\n * Base engine implementation shared between browser and Node.js environments.\n */\nexport class BelocalEngine {\n private transport: Transport;\n private debug: boolean;\n private cache: Cache;\n\n constructor(options: BelocalEngineOptions, baseTransportFactory: (opts: any) => BaseTransport) {\n const {\n apiKey,\n batchWindowMs = 50,\n timeoutMs = 10000,\n debug = false\n } = options;\n\n this.debug = debug;\n this.cache = new LocalCache();\n\n const authHeaders = {\n 'Authorization': `Bearer ${apiKey}`\n };\n\n const baseTransport = baseTransportFactory({\n headers: authHeaders,\n timeoutMs,\n debug: this.debug\n });\n\n this.transport = createMultiTransport({\n baseTransport,\n debug: this.debug,\n batchWindowMs\n });\n \n if (this.debug) {\n console.log('[BeLocal Engine] Multi transport created with config:', {\n baseUrl: 'https://dynamic.belocal.dev',\n timeoutMs,\n batchWindowMs\n });\n }\n }\n\n /**\n * Translates a single text string to the target language.\n * \n * Uses in-memory cache to avoid redundant API calls. Results are automatically cached\n * for subsequent requests with the same parameters.\n * \n * @param text - The text to translate\n * @param lang - Target language code (e.g., 'es', 'fr', 'ru')\n * @param source_lang - Optional source language code. If not provided, auto-detection is used\n * @param ctx - Optional key-value pairs for translation context. Supported keys: `user_ctx` (string - descriptive context), `cache_type` ('managed')\n * @returns Promise resolving to the translated text\n * @throws {Error} If the translation request fails (network error, API error, timeout)\n * \n * @example\n * ```typescript\n * // Simple translation\n * const result = await engine.translate('Hello world', 'es');\n * \n * // With source language\n * const result = await engine.translate('Hello world', 'es', 'en');\n * \n * // With context (user_ctx) - descriptive context helps improve translation quality\n * const result = await engine.translate('Hello world', 'es', undefined, { \n * user_ctx: 'greeting message on the homepage' \n * });\n * \n * // With cache_type\n * const result = await engine.translate('Hello world', 'es', undefined, { cache_type: 'managed' });\n * \n * // With source language and context\n * const result = await engine.translate('Hello world', 'es', 'en', { \n * user_ctx: 'greeting message on the homepage' \n * });\n * ```\n */\n async translate(text: string, lang: Lang, source_lang?: string, ctx?: KV): Promise<string> {\n const results = await this.translateMany([text], lang, source_lang, ctx);\n return results[0];\n }\n\n /**\n * Translates multiple text strings to the target language in a single batch.\n * \n * This method is more efficient than calling `translate()` multiple times as it:\n * - Batches requests together to reduce API calls\n * - Checks cache for each text individually\n * - Only requests translations for cache misses\n * - Maintains the order of input texts in the result array\n * \n * @param texts - Array of texts to translate\n * @param lang - Target language code (e.g., 'es', 'fr', 'ru')\n * @param source_lang - Optional source language code. If not provided, auto-detection is used\n * @param ctx - Optional key-value pairs for translation context. Supported keys: `user_ctx` (string - descriptive context in English), `cache_type` ('managed' | string)\n * @returns Promise resolving to an array of translated texts in the same order as input\n * @throws {Error} If the translation request fails (network error, API error, timeout)\n * \n * @example\n * ```typescript\n * // Translate multiple texts\n * const results = await engine.translateMany(['Hello', 'World', 'Test'], 'es');\n * // Returns: ['Hola', 'Mundo', 'Prueba']\n * \n * // With source language\n * const results = await engine.translateMany(['Hello', 'World'], 'fr', 'en');\n * \n * // With context (user_ctx) - descriptive context helps improve translation quality\n * const results = await engine.translateMany(\n * ['Hello', 'World'], \n * 'es', \n * undefined, \n * { user_ctx: 'greeting message on the homepage' }\n * );\n * \n * // With cache_type\n * const results = await engine.translateMany(\n * ['Hello', 'World'], \n * 'es', \n * undefined, \n * { cache_type: 'managed' }\n * );\n * \n * // Empty array returns empty array\n * const results = await engine.translateMany([], 'es');\n * // Returns: []\n * ```\n */\n async translateMany(texts: string[], lang: Lang, source_lang?: string, ctx?: KV): Promise<string[]> {\n const results: (string | null)[] = new Array(texts.length);\n const cacheMisses: Array<{ index: number; text: string }> = [];\n\n for (let i = 0; i < texts.length; i++) {\n const text = texts[i];\n const cacheKey = this.generateCacheKey(text, lang, source_lang, ctx);\n \n const cachedResult = this.cache.get(cacheKey);\n if (cachedResult) {\n results[i] = cachedResult;\n if (this.debug) {\n console.log('[BeLocal Engine] Translation from cache:', text);\n }\n continue;\n }\n \n results[i] = null;\n cacheMisses.push({ index: i, text });\n }\n\n if (cacheMisses.length > 0) {\n const translations = await Promise.all(\n cacheMisses.map(async ({ index, text }) => {\n const result = await this.transport({ text, lang, source_lang, ctx });\n \n if (result.status !== 'error') {\n const cacheKey = this.generateCacheKey(text, lang, source_lang, ctx);\n this.cache.set(cacheKey, result.text);\n if (this.debug) {\n console.log('[BeLocal Engine] Translation from API, cached:', text);\n }\n } else {\n if (this.debug) {\n console.log('[BeLocal Engine] Translation from API (not cached due to error status):', text);\n }\n }\n \n return { index, translation: result.text };\n })\n );\n\n translations.forEach(({ index, translation }) => {\n results[index] = translation;\n });\n }\n\n return results as string[];\n }\n\n /**\n * Shortcut method for translation with simplified API.\n * \n * This is a convenience method that wraps `translate()`. When `context` is provided as a string,\n * it is automatically wrapped in `{user_ctx: context}` object.\n * \n * @param text - The text to translate\n * @param lang - Target language code (e.g., 'es', 'fr', 'ru')\n * @param source_lang - Optional source language code\n * @param context - Optional descriptive context string in English (will be wrapped as {user_ctx: context})\n * @returns Promise resolving to the translated text\n * @throws {Error} If the translation request fails (network error, API error, timeout)\n * \n * @example\n * ```typescript\n * // Simple translation\n * const result = await engine.t('Hello world', 'es');\n * \n * // With source language\n * const result = await engine.t('Hello world', 'fr', 'en');\n * \n * // With context string (automatically wrapped as {user_ctx: 'greeting message on the homepage'})\n * const result = await engine.t('Hello world', 'es', undefined, 'greeting message on the homepage');\n * \n * // With source language and context\n * const result = await engine.t('Hello world', 'es', 'en', 'greeting message on the homepage');\n * ```\n */\n async t(text: string, lang: Lang, source_lang?: string, context?: string): Promise<string> {\n if (context) {\n return this.translate(text, lang, source_lang, {user_ctx: context});\n }\n return this.translate(text, lang, source_lang);\n }\n\n private generateCacheKey(text: string, lang: Lang, source_lang?: string, ctx?: KV): string {\n const sortedCtx = ctx ? Object.keys(ctx)\n .sort()\n .reduce((acc, key) => {\n acc[key] = ctx[key];\n return acc;\n }, {} as KV) : null;\n\n const data = {\n text,\n lang,\n source_lang: source_lang || null,\n ctx: sortedCtx\n };\n return md5(JSON.stringify(data));\n }\n}\n","import type { BelocalEngineOptions } from '../types';\nimport { createBaseBrowserTransport } from '../../transports/base/browser';\nimport { BelocalEngine as BaseEngine } from './engine';\n\n/**\n * BeLocal translation engine for browser environments.\n * \n * Provides on-demand translation with automatic request batching, caching, and deduplication.\n * Optimized for browser environments using the Fetch API.\n * \n * @example\n * ```typescript\n * const engine = new BelocalEngine({\n * apiKey: 'your-api-key',\n * debug: true\n * });\n * \n * const translated = await engine.translate('Hello world', 'es');\n * ```\n */\nexport class BelocalEngine extends BaseEngine {\n /**\n * Creates a new BelocalEngine instance for browser environments.\n * \n * @param options - Configuration options for the engine\n * @throws {Error} If apiKey is not provided or invalid\n * \n * @example\n * ```typescript\n * const engine = new BelocalEngine({\n * apiKey: 'your-api-key',\n * batchWindowMs: 100,\n * timeoutMs: 10000,\n * debug: false\n * });\n * ```\n */\n constructor(options: BelocalEngineOptions) {\n super(options, createBaseBrowserTransport);\n }\n}\n\n// Re-export types and transports\nexport type { BelocalEngineOptions, Lang, KV, BaseTransport } from '../types';\nexport { createMultiTransport } from '../../transports/multi';\nexport { BaseBrowserTransport, createBaseBrowserTransport } from '../../transports/base';\n"]}
package/dist/browser.d.ts CHANGED
@@ -7,7 +7,7 @@ type Lang = string;
7
7
  * Key-value pairs for translation context.
8
8
  * Supported keys:
9
9
  * - `user_ctx` (string): Descriptive context to help improve translation quality (e.g., 'greeting message on the homepage')
10
- * - `cache_type` (string): Cache type, e.g., 'editable'
10
+ * - `cache_type` (string): Cache type, e.g., 'managed' (managed translations cache)
11
11
  *
12
12
  * Other keys will be ignored by the API.
13
13
  */
@@ -46,62 +46,14 @@ interface BelocalEngineOptions {
46
46
  debug?: boolean;
47
47
  }
48
48
 
49
- interface MultiTransportConfig {
50
- baseTransport: BaseTransport;
51
- debug?: boolean;
52
- batchWindowMs?: number;
53
- }
54
- declare function createMultiTransport(config: MultiTransportConfig): Transport;
55
-
56
- interface BaseBrowserTransportConfig {
57
- headers?: Record<string, string>;
58
- timeoutMs?: number;
59
- debug?: boolean;
60
- }
61
- declare class BaseBrowserTransport implements BaseTransport {
62
- private config;
63
- constructor(config: BaseBrowserTransportConfig);
64
- post(data: any, endpointPath: string): Promise<any>;
65
- }
66
- declare function createBaseBrowserTransport(config: BaseBrowserTransportConfig): BaseTransport;
67
-
68
49
  /**
69
- * BeLocal translation engine for browser environments.
70
- *
71
- * Provides on-demand translation with automatic request batching, caching, and deduplication.
72
- * Optimized for browser environments using the Fetch API.
73
- *
74
- * @example
75
- * ```typescript
76
- * const engine = new BelocalEngine({
77
- * apiKey: 'your-api-key',
78
- * debug: true
79
- * });
80
- *
81
- * const translated = await engine.translate('Hello world', 'es');
82
- * ```
50
+ * Base engine implementation shared between browser and Node.js environments.
83
51
  */
84
- declare class BelocalEngine {
52
+ declare class BelocalEngine$1 {
85
53
  private transport;
86
54
  private debug;
87
55
  private cache;
88
- /**
89
- * Creates a new BelocalEngine instance.
90
- *
91
- * @param options - Configuration options for the engine
92
- * @throws {Error} If apiKey is not provided or invalid
93
- *
94
- * @example
95
- * ```typescript
96
- * const engine = new BelocalEngine({
97
- * apiKey: 'your-api-key',
98
- * batchWindowMs: 100,
99
- * timeoutMs: 10000,
100
- * debug: false
101
- * });
102
- * ```
103
- */
104
- constructor(options: BelocalEngineOptions);
56
+ constructor(options: BelocalEngineOptions, baseTransportFactory: (opts: any) => BaseTransport);
105
57
  /**
106
58
  * Translates a single text string to the target language.
107
59
  *
@@ -111,7 +63,7 @@ declare class BelocalEngine {
111
63
  * @param text - The text to translate
112
64
  * @param lang - Target language code (e.g., 'es', 'fr', 'ru')
113
65
  * @param source_lang - Optional source language code. If not provided, auto-detection is used
114
- * @param ctx - Optional key-value pairs for translation context. Supported keys: `user_ctx` (string - descriptive context), `cache_type` ('editable')
66
+ * @param ctx - Optional key-value pairs for translation context. Supported keys: `user_ctx` (string - descriptive context), `cache_type` ('managed')
115
67
  * @returns Promise resolving to the translated text
116
68
  * @throws {Error} If the translation request fails (network error, API error, timeout)
117
69
  *
@@ -129,7 +81,7 @@ declare class BelocalEngine {
129
81
  * });
130
82
  *
131
83
  * // With cache_type
132
- * const result = await engine.translate('Hello world', 'es', undefined, { cache_type: 'editable' });
84
+ * const result = await engine.translate('Hello world', 'es', undefined, { cache_type: 'managed' });
133
85
  *
134
86
  * // With source language and context
135
87
  * const result = await engine.translate('Hello world', 'es', 'en', {
@@ -150,7 +102,7 @@ declare class BelocalEngine {
150
102
  * @param texts - Array of texts to translate
151
103
  * @param lang - Target language code (e.g., 'es', 'fr', 'ru')
152
104
  * @param source_lang - Optional source language code. If not provided, auto-detection is used
153
- * @param ctx - Optional key-value pairs for translation context. Supported keys: `user_ctx` (string - descriptive context in English), `cache_type` ('editable' | string)
105
+ * @param ctx - Optional key-value pairs for translation context. Supported keys: `user_ctx` (string - descriptive context in English), `cache_type` ('managed' | string)
154
106
  * @returns Promise resolving to an array of translated texts in the same order as input
155
107
  * @throws {Error} If the translation request fails (network error, API error, timeout)
156
108
  *
@@ -176,7 +128,7 @@ declare class BelocalEngine {
176
128
  * ['Hello', 'World'],
177
129
  * 'es',
178
130
  * undefined,
179
- * { cache_type: 'editable' }
131
+ * { cache_type: 'managed' }
180
132
  * );
181
133
  *
182
134
  * // Empty array returns empty array
@@ -217,4 +169,59 @@ declare class BelocalEngine {
217
169
  private generateCacheKey;
218
170
  }
219
171
 
172
+ interface MultiTransportConfig {
173
+ baseTransport: BaseTransport;
174
+ debug?: boolean;
175
+ batchWindowMs?: number;
176
+ }
177
+ declare function createMultiTransport(config: MultiTransportConfig): Transport;
178
+
179
+ interface BaseBrowserTransportConfig {
180
+ headers?: Record<string, string>;
181
+ timeoutMs?: number;
182
+ debug?: boolean;
183
+ }
184
+ declare class BaseBrowserTransport implements BaseTransport {
185
+ private config;
186
+ constructor(config: BaseBrowserTransportConfig);
187
+ post(data: any, endpointPath: string): Promise<any>;
188
+ }
189
+ declare function createBaseBrowserTransport(config: BaseBrowserTransportConfig): BaseTransport;
190
+
191
+ /**
192
+ * BeLocal translation engine for browser environments.
193
+ *
194
+ * Provides on-demand translation with automatic request batching, caching, and deduplication.
195
+ * Optimized for browser environments using the Fetch API.
196
+ *
197
+ * @example
198
+ * ```typescript
199
+ * const engine = new BelocalEngine({
200
+ * apiKey: 'your-api-key',
201
+ * debug: true
202
+ * });
203
+ *
204
+ * const translated = await engine.translate('Hello world', 'es');
205
+ * ```
206
+ */
207
+ declare class BelocalEngine extends BelocalEngine$1 {
208
+ /**
209
+ * Creates a new BelocalEngine instance for browser environments.
210
+ *
211
+ * @param options - Configuration options for the engine
212
+ * @throws {Error} If apiKey is not provided or invalid
213
+ *
214
+ * @example
215
+ * ```typescript
216
+ * const engine = new BelocalEngine({
217
+ * apiKey: 'your-api-key',
218
+ * batchWindowMs: 100,
219
+ * timeoutMs: 10000,
220
+ * debug: false
221
+ * });
222
+ * ```
223
+ */
224
+ constructor(options: BelocalEngineOptions);
225
+ }
226
+
220
227
  export { BaseBrowserTransport, type BaseTransport, BelocalEngine, type BelocalEngineOptions, type KV, type Lang, createBaseBrowserTransport, createMultiTransport };
package/dist/browser.mjs CHANGED
@@ -1,3 +1,3 @@
1
- import {md5}from'js-md5';function q(a,t,s,e){let r=[...a].sort(),i=null;if(e&&Object.keys(e).length>0){i={};let n=Object.keys(e).sort();for(let o of n)i[o]=e[o];}let u=JSON.stringify([r,t,s||null,i]);return md5(u)}async function S(a,t,s){a.debug&&console.log(`[BeLocal Multi Transport] Sending multi request with ${t.length} texts`);try{let e=new Map;t.forEach(n=>{let o=JSON.stringify({lang:n.lang,sourceLang:n.sourceLang||null,context:n.context||null});e.has(o)||e.set(o,[]),e.get(o).push(n);});let r=new Map,i=Array.from(e.entries()).map(([n,o])=>{let c=o[0],g=o.map(d=>d.text),p=q(g,c.lang,c.sourceLang,c.context);return r.set(p,o),{requestId:p,texts:g,lang:c.lang,sourceLang:c.sourceLang,context:c.context}}),l=await a.baseTransport.post({requests:i},"/v1/translate/multi");a.debug&&console.log(`[BeLocal Multi Transport] Multi response received with ${l.results.length} groups`);let u=new Map;l.results.forEach(n=>{u.set(n.requestId,{texts:n.data.texts,status:n.data.status});}),r.forEach((n,o)=>{let c=u.get(o);if(!c){a.debug&&console.error(`[BeLocal Multi Transport] No result found for requestId: ${o}`),n.forEach(g=>{g.reject(new Error(`No result found for request ${o}`));});return}if(c.texts.length!==n.length){let g=new Error(`Mismatch: expected ${n.length} texts, got ${c.texts.length} for requestId ${o}`);a.debug&&console.error("[BeLocal Multi Transport]",g.message),n.forEach(p=>p.reject(g));return}n.forEach((g,p)=>{let d=c.texts[p],x=c.status||"success";a.debug&&console.log(`[BeLocal Multi Transport] Success for requestId ${o}[${p}]: "${d}"`),g.resolve({text:d,status:x});});});}catch(e){a.debug&&console.error("[BeLocal Multi Transport] Multi request error:",e);let r=e instanceof Error?e:new Error(String(e));t.forEach(i=>i.reject(r));}finally{}}function b(a,t){if(t.currentMulti.length===0||t.isRequestInFlight)return;let s=[...t.currentMulti];t.currentMulti=[],t.multiTimer=null,t.isRequestInFlight=true,S(a,s).finally(()=>{if(t.isRequestInFlight=false,t.currentMulti.length>0){let e=a.batchWindowMs??50;t.multiTimer=setTimeout(()=>b(a,t),e);}});}function T(a){let t=a.batchWindowMs??50,s={currentMulti:[],multiTimer:null,isRequestInFlight:false};return ({text:e,lang:r,source_lang:i,ctx:l})=>new Promise((u,n)=>{if(a.debug){let c=md5(JSON.stringify([e,r,i||null,l||null]));console.log(`[BeLocal Multi Transport] Queuing request ${c}: "${e}" to ${r}`);}let o={text:e,lang:r,sourceLang:i,context:l,resolve:u,reject:n};s.currentMulti.push(o),s.multiTimer===null&&!s.isRequestInFlight&&(s.multiTimer=setTimeout(()=>b(a,s),t));})}var B=(()=>{try{return "0.6.1"}catch{return "undefined"}})(),w="js";function E(a,t){let s=r=>{if(r==null)return r;if(Array.isArray(r))return r.map(s);if(typeof r=="object"){let i={};for(let l of Object.keys(r).sort())i[l]=s(r[l]);return i}return r},e=JSON.stringify(s(t));return `${a}:${e}`}var h=class{constructor(t,s){this.wrappedTransport=t;this.debug=s;this.inFlightRequests=new Map;}async post(t,s){let e=E(s,t),r=this.inFlightRequests.get(e);if(r)return this.debug&&console.log(`[DedupeTransport] Deduplicating request to ${s}`),r;let i=this.wrappedTransport.post(t,s).finally(()=>{this.inFlightRequests.delete(e);});return this.inFlightRequests.set(e,i),this.debug&&console.log(`[DedupeTransport] New request to ${s} (${this.inFlightRequests.size} in-flight)`),i}};var L="https://dynamic.belocal.dev",f=class{constructor(t){this.config=t;}async post(t,s){let e=`${L}${s}`,r=new AbortController,i=this.config.timeoutMs??1e4,l=setTimeout(()=>r.abort(),i);this.config.debug&&console.log(`[Base Browser Transport] POST request to ${e}`,t);try{let u=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json","x-sdk":w,"x-sdk-version":B,...this.config.headers},body:JSON.stringify(t),signal:r.signal});if(!u.ok){let o=`HTTP ${u.status}: ${u.statusText}`;throw this.config.debug&&console.error("[Base Browser Transport] Request failed:",o),new Error(o)}let n=await u.json();return this.config.debug&&console.log("[Base Browser Transport] Request successful:",n),n}finally{l&&clearTimeout(l);}}};function m(a){let t=new f(a);return new h(t,a.debug)}var y=class{constructor(){this.storage=new Map;}get(t){return this.storage.get(t)||null}set(t,s){this.storage.set(t,s);}isAvailable(){return true}};var R=class{constructor(t){let{apiKey:s,batchWindowMs:e=50,timeoutMs:r=1e4,debug:i=false}=t;this.debug=i,this.cache=new y;let l={Authorization:`Bearer ${s}`},u=m({headers:l,timeoutMs:r,debug:this.debug});this.transport=T({baseTransport:u,debug:this.debug,batchWindowMs:e}),this.debug&&console.log("[BeLocal Engine] Multi transport created with config:",{baseUrl:"https://dynamic.belocal.dev",timeoutMs:r,batchWindowMs:e});}async translate(t,s,e,r){return (await this.translateMany([t],s,e,r))[0]}async translateMany(t,s,e,r){let i=new Array(t.length),l=[];for(let u=0;u<t.length;u++){let n=t[u],o=this.generateCacheKey(n,s,e,r),c=this.cache.get(o);if(c){i[u]=c,this.debug&&console.log("[BeLocal Engine] Translation from cache:",n);continue}i[u]=null,l.push({index:u,text:n});}return l.length>0&&(await Promise.all(l.map(async({index:n,text:o})=>{let c=await this.transport({text:o,lang:s,source_lang:e,ctx:r});if(c.status!=="error"){let g=this.generateCacheKey(o,s,e,r);this.cache.set(g,c.text),this.debug&&console.log("[BeLocal Engine] Translation from API, cached:",o);}else this.debug&&console.log("[BeLocal Engine] Translation from API (not cached due to error status):",o);return {index:n,translation:c.text}}))).forEach(({index:n,translation:o})=>{i[n]=o;}),i}async t(t,s,e,r){return r?this.translate(t,s,e,{user_ctx:r}):this.translate(t,s,e)}generateCacheKey(t,s,e,r){let i=r?Object.keys(r).sort().reduce((u,n)=>(u[n]=r[n],u),{}):null;return md5(JSON.stringify({text:t,lang:s,source_lang:e||null,ctx:i}))}};
2
- export{f as BaseBrowserTransport,R as BelocalEngine,m as createBaseBrowserTransport,T as createMultiTransport};//# sourceMappingURL=browser.mjs.map
1
+ import {md5}from'js-md5';var B=(()=>{try{return "1.0.0"}catch{return "undefined"}})(),b="js";function E(a,t){let s=r=>{if(r==null)return r;if(Array.isArray(r))return r.map(s);if(typeof r=="object"){let i={};for(let c of Object.keys(r).sort())i[c]=s(r[c]);return i}return r},e=JSON.stringify(s(t));return `${a}:${e}`}var h=class{constructor(t,s){this.wrappedTransport=t;this.debug=s;this.inFlightRequests=new Map;}async post(t,s){let e=E(s,t),r=this.inFlightRequests.get(e);if(r)return this.debug&&console.log(`[DedupeTransport] Deduplicating request to ${s}`),r;let i=this.wrappedTransport.post(t,s).finally(()=>{this.inFlightRequests.delete(e);});return this.inFlightRequests.set(e,i),this.debug&&console.log(`[DedupeTransport] New request to ${s} (${this.inFlightRequests.size} in-flight)`),i}};var S="https://dynamic.belocal.dev",f=class{constructor(t){this.config=t;}async post(t,s){let e=`${S}${s}`,r=new AbortController,i=this.config.timeoutMs??1e4,c=setTimeout(()=>r.abort(),i);this.config.debug&&console.log(`[Base Browser Transport] POST request to ${e}`,t);try{let u=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json","x-sdk":b,"x-sdk-version":B,...this.config.headers},body:JSON.stringify(t),signal:r.signal});if(!u.ok){let o=`HTTP ${u.status}: ${u.statusText}`;throw this.config.debug&&console.error("[Base Browser Transport] Request failed:",o),new Error(o)}let n=await u.json();return this.config.debug&&console.log("[Base Browser Transport] Request successful:",n),n}finally{c&&clearTimeout(c);}}};function m(a){let t=new f(a);return new h(t,a.debug)}function _(a,t,s,e){let r=[...a].sort(),i=null;if(e&&Object.keys(e).length>0){i={};let n=Object.keys(e).sort();for(let o of n)i[o]=e[o];}let u=JSON.stringify([r,t,s||null,i]);return md5(u)}async function K(a,t,s){a.debug&&console.log(`[BeLocal Multi Transport] Sending multi request with ${t.length} texts`);try{let e=new Map;t.forEach(n=>{let o=JSON.stringify({lang:n.lang,sourceLang:n.sourceLang||null,context:n.context||null});e.has(o)||e.set(o,[]),e.get(o).push(n);});let r=new Map,i=Array.from(e.entries()).map(([n,o])=>{let l=o[0],g=o.map(d=>d.text),p=_(g,l.lang,l.sourceLang,l.context);return r.set(p,o),{request_id:p,texts:g,lang:l.lang,source_lang:l.sourceLang,ctx:l.context}}),c=await a.baseTransport.post({requests:i},"/v1/translate/multi");a.debug&&console.log(`[BeLocal Multi Transport] Multi response received with ${c.results.length} groups`);let u=new Map;c.results.forEach(n=>{u.set(n.request_id,{texts:n.data.texts,status:n.data.status});}),r.forEach((n,o)=>{let l=u.get(o);if(!l){a.debug&&console.error(`[BeLocal Multi Transport] No result found for request_id: ${o}`),n.forEach(g=>{g.reject(new Error(`No result found for request ${o}`));});return}if(l.texts.length!==n.length){let g=new Error(`Mismatch: expected ${n.length} texts, got ${l.texts.length} for request_id ${o}`);a.debug&&console.error("[BeLocal Multi Transport]",g.message),n.forEach(p=>p.reject(g));return}n.forEach((g,p)=>{let d=l.texts[p],q=l.status||"success";a.debug&&console.log(`[BeLocal Multi Transport] Success for request_id ${o}[${p}]: "${d}"`),g.resolve({text:d,status:q});});});}catch(e){a.debug&&console.error("[BeLocal Multi Transport] Multi request error:",e);let r=e instanceof Error?e:new Error(String(e));t.forEach(i=>i.reject(r));}finally{}}function x(a,t){if(t.currentMulti.length===0||t.isRequestInFlight)return;let s=[...t.currentMulti];t.currentMulti=[],t.multiTimer=null,t.isRequestInFlight=true,K(a,s).finally(()=>{if(t.isRequestInFlight=false,t.currentMulti.length>0){let e=a.batchWindowMs??50;t.multiTimer=setTimeout(()=>x(a,t),e);}});}function M(a){let t=a.batchWindowMs??50,s={currentMulti:[],multiTimer:null,isRequestInFlight:false};return ({text:e,lang:r,source_lang:i,ctx:c})=>new Promise((u,n)=>{if(a.debug){let l=md5(JSON.stringify([e,r,i||null,c||null]));console.log(`[BeLocal Multi Transport] Queuing request ${l}: "${e}" to ${r}`);}let o={text:e,lang:r,sourceLang:i,context:c,resolve:u,reject:n};s.currentMulti.push(o),s.multiTimer===null&&!s.isRequestInFlight&&(s.multiTimer=setTimeout(()=>x(a,s),t));})}var y=class{constructor(){this.storage=new Map;}get(t){return this.storage.get(t)||null}set(t,s){this.storage.set(t,s);}isAvailable(){return true}};var T=class{constructor(t,s){let{apiKey:e,batchWindowMs:r=50,timeoutMs:i=1e4,debug:c=false}=t;this.debug=c,this.cache=new y;let u={Authorization:`Bearer ${e}`},n=s({headers:u,timeoutMs:i,debug:this.debug});this.transport=M({baseTransport:n,debug:this.debug,batchWindowMs:r}),this.debug&&console.log("[BeLocal Engine] Multi transport created with config:",{baseUrl:"https://dynamic.belocal.dev",timeoutMs:i,batchWindowMs:r});}async translate(t,s,e,r){return (await this.translateMany([t],s,e,r))[0]}async translateMany(t,s,e,r){let i=new Array(t.length),c=[];for(let u=0;u<t.length;u++){let n=t[u],o=this.generateCacheKey(n,s,e,r),l=this.cache.get(o);if(l){i[u]=l,this.debug&&console.log("[BeLocal Engine] Translation from cache:",n);continue}i[u]=null,c.push({index:u,text:n});}return c.length>0&&(await Promise.all(c.map(async({index:n,text:o})=>{let l=await this.transport({text:o,lang:s,source_lang:e,ctx:r});if(l.status!=="error"){let g=this.generateCacheKey(o,s,e,r);this.cache.set(g,l.text),this.debug&&console.log("[BeLocal Engine] Translation from API, cached:",o);}else this.debug&&console.log("[BeLocal Engine] Translation from API (not cached due to error status):",o);return {index:n,translation:l.text}}))).forEach(({index:n,translation:o})=>{i[n]=o;}),i}async t(t,s,e,r){return r?this.translate(t,s,e,{user_ctx:r}):this.translate(t,s,e)}generateCacheKey(t,s,e,r){let i=r?Object.keys(r).sort().reduce((u,n)=>(u[n]=r[n],u),{}):null;return md5(JSON.stringify({text:t,lang:s,source_lang:e||null,ctx:i}))}};var R=class extends T{constructor(t){super(t,m);}};
2
+ export{f as BaseBrowserTransport,R as BelocalEngine,m as createBaseBrowserTransport,M as createMultiTransport};//# sourceMappingURL=browser.mjs.map
3
3
  //# sourceMappingURL=browser.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/transports/multi.ts","../src/version.ts","../src/transports/base/dedupe.ts","../src/transports/base/browser.ts","../src/cache/local.ts","../src/core/engine/browser.ts"],"names":["generateRequestId","texts","lang","sourceLang","context","sortedTexts","sortedContext","sortedKeys","key","json","md5","sendMulti","config","items","state","groups","item","groupKey","requestIdToGroupItems","requests","groupItems","firstItem","requestId","multiResponse","resultMap","result","error","index","translatedText","status","errorToReject","processMulti","itemsToSend","windowMs","createMultiTransport","text","source_lang","ctx","resolve","reject","tempRequestId","requestItem","SDK_VERSION","SDK_NAME","generateRequestKey","endpointPath","data","normalize","value","sorted","normalizedData","DedupeTransport","wrappedTransport","debug","requestKey","existingRequest","requestPromise","BASE_URL","BaseBrowserTransport","url","controller","timeoutMs","timeoutId","response","errorMsg","createBaseBrowserTransport","transport","LocalCache","BelocalEngine","options","apiKey","batchWindowMs","authHeaders","baseTransport","results","cacheMisses","i","cacheKey","cachedResult","translation","sortedCtx","acc"],"mappings":"yBAuCA,SAASA,EAAkBC,CAAAA,CAAiBC,CAAAA,CAAcC,CAAAA,CAAqBC,CAAAA,CAA0C,CAEvH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,gBAAA,CAAiBD,EAAcjC,CAAAA,CAAYkC,CAAAA,CAAsBC,CAAAA,CAAkB,CACzF,IAAM2C,CAAAA,CAAY3C,CAAAA,CAAM,MAAA,CAAO,IAAA,CAAKA,CAAG,CAAA,CACpC,IAAA,EAAK,CACL,MAAA,CAAO,CAAC4C,CAAAA,CAAKzE,CAAAA,IACZyE,CAAAA,CAAIzE,CAAG,EAAI6B,CAAAA,CAAI7B,CAAG,CAAA,CACXyE,CAAAA,CAAAA,CACN,EAAQ,CAAA,CAAI,IAAA,CAQjB,OAAOvE,IAAI,IAAA,CAAK,SAAA,CANH,CACX,IAAA,CAAAyB,EACA,IAAA,CAAAjC,CAAAA,CACA,WAAA,CAAakC,CAAAA,EAAe,KAC5B,GAAA,CAAK4C,CACP,CAC8B,CAAC,CACjC,CACF","file":"browser.mjs","sourcesContent":["import type { Transport, BaseTransport } from '../core/types';\nimport { md5 } from 'js-md5';\n\nexport interface MultiTransportConfig {\n baseTransport: BaseTransport;\n debug?: boolean;\n batchWindowMs?: number;\n}\n\ninterface MultiRequest {\n requestId: string;\n texts: string[];\n lang: string;\n sourceLang?: string;\n context?: Record<string, string>;\n}\n\ninterface MultiRequestItem {\n text: string;\n lang: string;\n sourceLang?: string;\n context?: Record<string, string>;\n resolve: (value: { text: string; status: string }) => void;\n reject: (error: Error) => void;\n}\n\ninterface MultiResponse {\n results: Array<{\n requestId: string;\n data: { texts: string[]; status: string };\n }>;\n}\n\ninterface MultiState {\n currentMulti: MultiRequestItem[];\n multiTimer: ReturnType<typeof setTimeout> | null;\n isRequestInFlight: boolean;\n}\n\nfunction generateRequestId(texts: string[], lang: string, sourceLang?: string, context?: Record<string, string>): string {\n // Сортируем тексты (создаем копию, чтобы не изменять оригинал)\n const sortedTexts = [...texts].sort();\n \n // Сортируем ключи контекста (создаем копию, чтобы не изменять оригинал)\n let sortedContext: Record<string, string> | null = null;\n if (context && Object.keys(context).length > 0) {\n sortedContext = {};\n const sortedKeys = Object.keys(context).sort();\n for (const key of sortedKeys) {\n sortedContext[key] = context[key];\n }\n }\n \n // Создаем JSON массив: [sortedTexts, lang, sourceLang, context]\n // В PHP примере: [$sortedTexts, $this->lang, $context] (sourceLang не включен)\n // Но мы включаем sourceLang для правильной группировки запросов с разными sourceLang\n const data = [sortedTexts, lang, sourceLang || null, sortedContext];\n const json = JSON.stringify(data);\n \n return md5(json);\n}\n\nasync function sendMulti(\n config: MultiTransportConfig,\n items: MultiRequestItem[],\n state: MultiState\n): Promise<void> {\n if (config.debug) {\n console.log(`[BeLocal Multi Transport] Sending multi request with ${items.length} texts`);\n }\n\n try {\n // Группируем тексты по параметрам перевода (lang, sourceLang, context)\n const groups = new Map<string, MultiRequestItem[]>();\n \n items.forEach(item => {\n // Используем ключ для группировки без текстов (только параметры перевода)\n const groupKey = JSON.stringify({\n lang: item.lang,\n sourceLang: item.sourceLang || null,\n context: item.context || null\n });\n \n if (!groups.has(groupKey)) {\n groups.set(groupKey, []);\n }\n groups.get(groupKey)!.push(item);\n });\n\n // Создаем запросы для каждой группы и сохраняем соответствие requestId -> groupItems\n const requestIdToGroupItems = new Map<string, MultiRequestItem[]>();\n const requests: MultiRequest[] = Array.from(groups.entries()).map(([groupKey, groupItems]) => {\n const firstItem = groupItems[0];\n const texts = groupItems.map(item => item.text);\n \n // Генерируем requestId включая отсортированные тексты группы\n // Включаем sourceLang для правильной группировки запросов с разными sourceLang\n const requestId = generateRequestId(\n texts,\n firstItem.lang,\n firstItem.sourceLang,\n firstItem.context\n );\n \n // Сохраняем соответствие requestId -> groupItems\n requestIdToGroupItems.set(requestId, groupItems);\n \n return {\n requestId,\n texts,\n lang: firstItem.lang,\n sourceLang: firstItem.sourceLang,\n context: firstItem.context\n };\n });\n\n const multiResponse: MultiResponse = await config.baseTransport.post({ requests }, '/v1/translate/multi');\n \n if (config.debug) {\n console.log(`[BeLocal Multi Transport] Multi response received with ${multiResponse.results.length} groups`);\n }\n\n // Создаем map для быстрого поиска результатов по requestId\n const resultMap = new Map<string, { texts: string[]; status: string }>();\n multiResponse.results.forEach(result => {\n resultMap.set(result.requestId, { texts: result.data.texts, status: result.data.status });\n });\n\n // Раздаем результаты каждому промису\n requestIdToGroupItems.forEach((groupItems, requestId) => {\n const result = resultMap.get(requestId);\n \n if (!result) {\n if (config.debug) {\n console.error(`[BeLocal Multi Transport] No result found for requestId: ${requestId}`);\n }\n groupItems.forEach(item => {\n item.reject(new Error(`No result found for request ${requestId}`));\n });\n return;\n }\n\n // Маппим тексты обратно на промисы по индексу\n if (result.texts.length !== groupItems.length) {\n const error = new Error(`Mismatch: expected ${groupItems.length} texts, got ${result.texts.length} for requestId ${requestId}`);\n if (config.debug) {\n console.error(`[BeLocal Multi Transport]`, error.message);\n }\n groupItems.forEach(item => item.reject(error));\n return;\n }\n\n groupItems.forEach((item, index) => {\n const translatedText = result.texts[index];\n const status = result.status || 'success';\n \n if (config.debug) {\n console.log(`[BeLocal Multi Transport] Success for requestId ${requestId}[${index}]: \"${translatedText}\"`);\n }\n \n item.resolve({ text: translatedText, status });\n });\n });\n\n } catch (error) {\n if (config.debug) {\n console.error(`[BeLocal Multi Transport] Multi request error:`, error);\n }\n \n // При ошибке сети отклоняем все промисы\n const errorToReject = error instanceof Error ? error : new Error(String(error));\n items.forEach(item => item.reject(errorToReject));\n } finally {\n // Cleanup handled by base transport\n }\n}\n\nfunction processMulti(config: MultiTransportConfig, state: MultiState): void {\n if (state.currentMulti.length === 0 || state.isRequestInFlight) {\n return;\n }\n\n const itemsToSend = [...state.currentMulti];\n state.currentMulti = [];\n state.multiTimer = null;\n state.isRequestInFlight = true;\n\n sendMulti(config, itemsToSend, state).finally(() => {\n state.isRequestInFlight = false;\n \n if (state.currentMulti.length > 0) {\n const windowMs = config.batchWindowMs ?? 50;\n state.multiTimer = setTimeout(() => processMulti(config, state), windowMs);\n }\n });\n}\n\nexport function createMultiTransport(config: MultiTransportConfig): Transport {\n const windowMs = config.batchWindowMs ?? 50;\n\n const state: MultiState = {\n currentMulti: [],\n multiTimer: null,\n isRequestInFlight: false,\n };\n \n return ({ text, lang, source_lang, ctx }) => {\n return new Promise<{ text: string; status: string }>((resolve, reject) => {\n if (config.debug) {\n // Для отладки показываем временный requestId (будет пересчитан при группировке)\n const tempRequestId = md5(JSON.stringify([text, lang, source_lang || null, ctx || null]));\n console.log(`[BeLocal Multi Transport] Queuing request ${tempRequestId}: \"${text}\" to ${lang}`);\n }\n\n const requestItem: MultiRequestItem = {\n text,\n lang,\n sourceLang: source_lang,\n context: ctx,\n resolve,\n reject,\n };\n\n state.currentMulti.push(requestItem);\n\n if (state.multiTimer === null && !state.isRequestInFlight) {\n state.multiTimer = setTimeout(() => processMulti(config, state), windowMs);\n }\n });\n };\n}\n\n","// SDK version - will be replaced during build with tsup define\ndeclare const __SDK_VERSION__: string | undefined;\n\n// Safely check if __SDK_VERSION__ is defined (replaced during build)\nexport const SDK_VERSION: string = \n (() => { try { return typeof __SDK_VERSION__ !== 'undefined' ? __SDK_VERSION__ : 'undefined'; } catch { return 'undefined'; } })();\n\nexport const SDK_NAME = 'js';\n\n","import type { BaseTransport } from '../../core/types';\n\n/**\n * Generates a deterministic key for request deduplication.\n * Uses sorted keys to ensure consistent key generation regardless of object property order.\n */\nfunction generateRequestKey(endpointPath: string, data: any): string {\n // Normalize data by sorting object keys for consistent serialization\n const normalize = (value: any): any => {\n if (value === null || value === undefined) {\n return value;\n }\n if (Array.isArray(value)) {\n return value.map(normalize);\n }\n if (typeof value === 'object') {\n const sorted: Record<string, any> = {};\n for (const key of Object.keys(value).sort()) {\n sorted[key] = normalize(value[key]);\n }\n return sorted;\n }\n return value;\n };\n \n const normalizedData = JSON.stringify(normalize(data));\n return `${endpointPath}:${normalizedData}`;\n}\n\n/**\n * DedupeTransport wraps a BaseTransport instance and deduplicates in-flight requests.\n * If multiple identical requests (same endpointPath + same request body) are made\n * concurrently, they will share the same underlying HTTP request and promise.\n */\nexport class DedupeTransport implements BaseTransport {\n private inFlightRequests = new Map<string, Promise<any>>();\n\n constructor(\n private wrappedTransport: BaseTransport,\n private debug?: boolean\n ) {}\n\n async post(data: any, endpointPath: string): Promise<any> {\n const requestKey = generateRequestKey(endpointPath, data);\n\n // Check if an identical request is already in-flight\n const existingRequest = this.inFlightRequests.get(requestKey);\n if (existingRequest) {\n if (this.debug) {\n console.log(`[DedupeTransport] Deduplicating request to ${endpointPath}`);\n }\n return existingRequest;\n }\n\n // Create new request and store it\n const requestPromise = this.wrappedTransport.post(data, endpointPath)\n .finally(() => {\n // Clean up when request completes (success or failure)\n this.inFlightRequests.delete(requestKey);\n });\n\n this.inFlightRequests.set(requestKey, requestPromise);\n\n if (this.debug) {\n console.log(`[DedupeTransport] New request to ${endpointPath} (${this.inFlightRequests.size} in-flight)`);\n }\n\n return requestPromise;\n }\n}\n","import type { BaseTransport } from '../../core/types';\nimport { SDK_NAME, SDK_VERSION } from '../../version';\nimport { DedupeTransport } from './dedupe';\n\nconst BASE_URL = 'https://dynamic.belocal.dev';\n\nexport interface BaseBrowserTransportConfig {\n headers?: Record<string, string>;\n timeoutMs?: number;\n debug?: boolean;\n}\n\nexport class BaseBrowserTransport implements BaseTransport {\n constructor(private config: BaseBrowserTransportConfig) {}\n\n async post(data: any, endpointPath: string): Promise<any> {\n const url = `${BASE_URL}${endpointPath}`;\n const controller = new AbortController();\n const timeoutMs = this.config.timeoutMs ?? 10000;\n const timeoutId = setTimeout(() => controller.abort(), timeoutMs);\n\n if (this.config.debug) {\n console.log(`[Base Browser Transport] POST request to ${url}`, data);\n }\n\n try {\n const response = await fetch(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'x-sdk': SDK_NAME,\n 'x-sdk-version': SDK_VERSION,\n ...this.config.headers,\n },\n body: JSON.stringify(data),\n signal: controller.signal,\n });\n\n if (!response.ok) {\n const errorMsg = `HTTP ${response.status}: ${response.statusText}`;\n if (this.config.debug) {\n console.error(`[Base Browser Transport] Request failed:`, errorMsg);\n }\n throw new Error(errorMsg);\n }\n\n const result = await response.json();\n if (this.config.debug) {\n console.log(`[Base Browser Transport] Request successful:`, result);\n }\n \n return result;\n } finally {\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n }\n }\n}\n\nexport function createBaseBrowserTransport(config: BaseBrowserTransportConfig): BaseTransport {\n const transport = new BaseBrowserTransport(config);\n return new DedupeTransport(transport, config.debug);\n}\n","import type { Cache } from './types';\n\nexport class LocalCache implements Cache {\n private storage = new Map<string, string>();\n\n get(key: string): string | null {\n return this.storage.get(key) || null;\n }\n\n set(key: string, value: string): void {\n this.storage.set(key, value);\n }\n\n isAvailable(): boolean {\n return true;\n }\n}\n","import type { BelocalEngineOptions, KV, Lang, Transport } from '../types';\nimport { createMultiTransport } from '../../transports/multi';\nimport { createBaseBrowserTransport } from '../../transports/base/browser';\nimport { LocalCache } from '../../cache/local';\nimport type { Cache } from '../../cache/types';\nimport { md5 } from 'js-md5';\n\n/**\n * BeLocal translation engine for browser environments.\n * \n * Provides on-demand translation with automatic request batching, caching, and deduplication.\n * Optimized for browser environments using the Fetch API.\n * \n * @example\n * ```typescript\n * const engine = new BelocalEngine({\n * apiKey: 'your-api-key',\n * debug: true\n * });\n * \n * const translated = await engine.translate('Hello world', 'es');\n * ```\n */\nexport class BelocalEngine {\n private transport: Transport;\n private debug: boolean;\n private cache: Cache;\n\n /**\n * Creates a new BelocalEngine instance.\n * \n * @param options - Configuration options for the engine\n * @throws {Error} If apiKey is not provided or invalid\n * \n * @example\n * ```typescript\n * const engine = new BelocalEngine({\n * apiKey: 'your-api-key',\n * batchWindowMs: 100,\n * timeoutMs: 10000,\n * debug: false\n * });\n * ```\n */\n constructor(options: BelocalEngineOptions) {\n const {\n apiKey,\n batchWindowMs = 50,\n timeoutMs = 10000,\n debug = false\n } = options;\n\n this.debug = debug;\n \n this.cache = new LocalCache();\n\n const authHeaders = {\n 'Authorization': `Bearer ${apiKey}`\n };\n\n const baseTransport = createBaseBrowserTransport({\n headers: authHeaders,\n timeoutMs,\n debug: this.debug\n });\n\n // Always use multi transport\n this.transport = createMultiTransport({\n baseTransport,\n debug: this.debug,\n batchWindowMs\n });\n \n if (this.debug) {\n console.log('[BeLocal Engine] Multi transport created with config:', {\n baseUrl: 'https://dynamic.belocal.dev',\n timeoutMs,\n batchWindowMs\n });\n }\n }\n\n /**\n * Translates a single text string to the target language.\n * \n * Uses in-memory cache to avoid redundant API calls. Results are automatically cached\n * for subsequent requests with the same parameters.\n * \n * @param text - The text to translate\n * @param lang - Target language code (e.g., 'es', 'fr', 'ru')\n * @param source_lang - Optional source language code. If not provided, auto-detection is used\n * @param ctx - Optional key-value pairs for translation context. Supported keys: `user_ctx` (string - descriptive context), `cache_type` ('editable')\n * @returns Promise resolving to the translated text\n * @throws {Error} If the translation request fails (network error, API error, timeout)\n * \n * @example\n * ```typescript\n * // Simple translation\n * const result = await engine.translate('Hello world', 'es');\n * \n * // With source language\n * const result = await engine.translate('Hello world', 'es', 'en');\n * \n * // With context (user_ctx) - descriptive context helps improve translation quality\n * const result = await engine.translate('Hello world', 'es', undefined, { \n * user_ctx: 'greeting message on the homepage' \n * });\n * \n * // With cache_type\n * const result = await engine.translate('Hello world', 'es', undefined, { cache_type: 'editable' });\n * \n * // With source language and context\n * const result = await engine.translate('Hello world', 'es', 'en', { \n * user_ctx: 'greeting message on the homepage' \n * });\n * ```\n */\n async translate(text: string, lang: Lang, source_lang?: string, ctx?: KV): Promise<string> {\n const results = await this.translateMany([text], lang, source_lang, ctx);\n return results[0];\n }\n\n /**\n * Translates multiple text strings to the target language in a single batch.\n * \n * This method is more efficient than calling `translate()` multiple times as it:\n * - Batches requests together to reduce API calls\n * - Checks cache for each text individually\n * - Only requests translations for cache misses\n * - Maintains the order of input texts in the result array\n * \n * @param texts - Array of texts to translate\n * @param lang - Target language code (e.g., 'es', 'fr', 'ru')\n * @param source_lang - Optional source language code. If not provided, auto-detection is used\n * @param ctx - Optional key-value pairs for translation context. Supported keys: `user_ctx` (string - descriptive context in English), `cache_type` ('editable' | string)\n * @returns Promise resolving to an array of translated texts in the same order as input\n * @throws {Error} If the translation request fails (network error, API error, timeout)\n * \n * @example\n * ```typescript\n * // Translate multiple texts\n * const results = await engine.translateMany(['Hello', 'World', 'Test'], 'es');\n * // Returns: ['Hola', 'Mundo', 'Prueba']\n * \n * // With source language\n * const results = await engine.translateMany(['Hello', 'World'], 'fr', 'en');\n * \n * // With context (user_ctx) - descriptive context helps improve translation quality\n * const results = await engine.translateMany(\n * ['Hello', 'World'], \n * 'es', \n * undefined, \n * { user_ctx: 'greeting message on the homepage' }\n * );\n * \n * // With cache_type\n * const results = await engine.translateMany(\n * ['Hello', 'World'], \n * 'es', \n * undefined, \n * { cache_type: 'editable' }\n * );\n * \n * // Empty array returns empty array\n * const results = await engine.translateMany([], 'es');\n * // Returns: []\n * ```\n */\n async translateMany(texts: string[], lang: Lang, source_lang?: string, ctx?: KV): Promise<string[]> {\n const results: (string | null)[] = new Array(texts.length);\n const cacheMisses: Array<{ index: number; text: string }> = [];\n\n for (let i = 0; i < texts.length; i++) {\n const text = texts[i];\n const cacheKey = this.generateCacheKey(text, lang, source_lang, ctx);\n \n const cachedResult = this.cache.get(cacheKey);\n if (cachedResult) {\n results[i] = cachedResult;\n if (this.debug) {\n console.log(`[BeLocal Engine] Translation from cache:`, text);\n }\n continue;\n }\n \n results[i] = null;\n cacheMisses.push({ index: i, text });\n }\n\n if (cacheMisses.length > 0) {\n const translations = await Promise.all(\n cacheMisses.map(async ({ index, text }) => {\n const result = await this.transport({ text, lang, source_lang, ctx });\n \n if (result.status !== 'error') {\n const cacheKey = this.generateCacheKey(text, lang, source_lang, ctx);\n this.cache.set(cacheKey, result.text);\n if (this.debug) {\n console.log(`[BeLocal Engine] Translation from API, cached:`, text);\n }\n } else {\n if (this.debug) {\n console.log('[BeLocal Engine] Translation from API (not cached due to error status):', text);\n }\n }\n \n return { index, translation: result.text };\n })\n );\n\n translations.forEach(({ index, translation }) => {\n results[index] = translation;\n });\n }\n\n return results as string[];\n }\n\n /**\n * Shortcut method for translation with simplified API.\n * \n * This is a convenience method that wraps `translate()`. When `context` is provided as a string,\n * it is automatically wrapped in `{user_ctx: context}` object.\n * \n * @param text - The text to translate\n * @param lang - Target language code (e.g., 'es', 'fr', 'ru')\n * @param source_lang - Optional source language code\n * @param context - Optional descriptive context string in English (will be wrapped as {user_ctx: context})\n * @returns Promise resolving to the translated text\n * @throws {Error} If the translation request fails (network error, API error, timeout)\n * \n * @example\n * ```typescript\n * // Simple translation\n * const result = await engine.t('Hello world', 'es');\n * \n * // With source language\n * const result = await engine.t('Hello world', 'fr', 'en');\n * \n * // With context string (automatically wrapped as {user_ctx: 'greeting message on the homepage'})\n * const result = await engine.t('Hello world', 'es', undefined, 'greeting message on the homepage');\n * \n * // With source language and context\n * const result = await engine.t('Hello world', 'es', 'en', 'greeting message on the homepage');\n * ```\n */\n async t(text: string, lang: Lang, source_lang?: string, context?: string): Promise<string> {\n if (context) {\n return this.translate(text, lang, source_lang, {user_ctx: context});\n }\n return this.translate(text, lang, source_lang);\n }\n\n private generateCacheKey(text: string, lang: Lang, source_lang?: string, ctx?: KV): string {\n const sortedCtx = ctx ? Object.keys(ctx)\n .sort()\n .reduce((acc, key) => {\n acc[key] = ctx[key];\n return acc;\n }, {} as KV) : null;\n\n const data = {\n text,\n lang,\n source_lang: source_lang || null,\n ctx: sortedCtx\n };\n return md5(JSON.stringify(data));\n }\n}\n\n// Re-export types and transports\nexport type { BelocalEngineOptions, Lang, KV, BaseTransport } from '../types';\nexport { createMultiTransport } from '../../transports/multi';\nexport { BaseBrowserTransport, createBaseBrowserTransport } from '../../transports/base';\n"]}
1
+ {"version":3,"sources":["../src/version.ts","../src/transports/base/dedupe.ts","../src/transports/base/browser.ts","../src/transports/multi.ts","../src/cache/local.ts","../src/core/engine/engine.ts","../src/core/engine/browser.ts"],"names":["SDK_VERSION","SDK_NAME","generateRequestKey","endpointPath","data","normalize","value","sorted","key","normalizedData","DedupeTransport","wrappedTransport","debug","requestKey","existingRequest","requestPromise","BASE_URL","BaseBrowserTransport","config","url","controller","timeoutMs","timeoutId","response","errorMsg","result","createBaseBrowserTransport","transport","generateRequestId","texts","lang","sourceLang","context","sortedTexts","sortedContext","sortedKeys","json","md5","sendMulti","items","state","groups","item","groupKey","requestIdToGroupItems","requests","groupItems","firstItem","requestId","multiResponse","resultMap","error","index","translatedText","status","errorToReject","processMulti","itemsToSend","windowMs","createMultiTransport","text","source_lang","ctx","resolve","reject","tempRequestId","requestItem","LocalCache","BelocalEngine","options","baseTransportFactory","apiKey","batchWindowMs","authHeaders","baseTransport","results","cacheMisses","i","cacheKey","cachedResult","translation","sortedCtx","acc"],"mappings":"yBAIO,IAAMA,GACV,IAAM,CAAE,GAAI,CAAE,OAAgD,OAA+B,CAAA,KAAQ,CAAE,OAAO,WAAa,CAAE,CAAA,GAAG,CAEtHC,CAAAA,CAAW,KCDxB,SAASC,CAAAA,CAAmBC,CAAAA,CAAsBC,CAAAA,CAAmB,CAEnE,IAAMC,CAAAA,CAAaC,CAAAA,EAAoB,CACrC,GAAIA,CAAAA,EAAU,IAAA,CACZ,OAAOA,CAAAA,CAET,GAAI,KAAA,CAAM,OAAA,CAAQA,CAAK,CAAA,CACrB,OAAOA,CAAAA,CAAM,GAAA,CAAID,CAAS,CAAA,CAE5B,GAAI,OAAOC,CAAAA,EAAU,QAAA,CAAU,CAC7B,IAAMC,CAAAA,CAA8B,EAAC,CACrC,IAAA,IAAWC,KAAO,MAAA,CAAO,IAAA,CAAKF,CAAK,CAAA,CAAE,MAAK,CACxCC,CAAAA,CAAOC,CAAG,CAAA,CAAIH,EAAUC,CAAAA,CAAME,CAAG,CAAC,CAAA,CAEpC,OAAOD,CACT,CACA,OAAOD,CACT,EAEMG,CAAAA,CAAiB,IAAA,CAAK,SAAA,CAAUJ,CAAAA,CAAUD,CAAI,CAAC,CAAA,CACrD,OAAO,CAAA,EAAGD,CAAY,CAAA,CAAA,EAAIM,CAAc,CAAA,CAC1C,CAOO,IAAMC,CAAAA,CAAN,KAA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AAY,CAAA,GAAM,CAC/CL,CAAAA,CAAQvB,CAAK,EAAI4B,EACnB,CAAC,CAAA,CAGIL,CACT,CA8BA,MAAM,CAAA,CAAEf,EAAc9B,CAAAA,CAAY+B,CAAAA,CAAsB7B,EAAmC,CACzF,OAAIA,CAAAA,CACK,IAAA,CAAK,UAAU4B,CAAAA,CAAM9B,CAAAA,CAAM+B,CAAAA,CAAa,CAAC,SAAU7B,CAAO,CAAC,CAAA,CAE7D,IAAA,CAAK,UAAU4B,CAAAA,CAAM9B,CAAAA,CAAM+B,CAAW,CAC/C,CAEQ,gBAAA,CAAiBD,CAAAA,CAAc9B,CAAAA,CAAY+B,CAAAA,CAAsBC,EAAkB,CACzF,IAAMmB,CAAAA,CAAYnB,CAAAA,CAAM,OAAO,IAAA,CAAKA,CAAG,CAAA,CACpC,IAAA,GACA,MAAA,CAAO,CAACoB,CAAAA,CAAK1E,CAAAA,IACZ0E,EAAI1E,CAAG,CAAA,CAAIsD,CAAAA,CAAItD,CAAG,EACX0E,CAAAA,CAAAA,CACN,EAAQ,CAAA,CAAI,KAQjB,OAAO7C,GAAAA,CAAI,IAAA,CAAK,SAAA,CANH,CACX,IAAA,CAAAuB,CAAAA,CACA,IAAA,CAAA9B,CAAAA,CACA,YAAa+B,CAAAA,EAAe,IAAA,CAC5B,GAAA,CAAKoB,CACP,CAC8B,CAAC,CACjC,CACF,CAAA,KCzNab,CAAAA,CAAN,cAA4BA,CAAW,CAiB5C,YAAYC,CAAAA,CAA+B,CACzC,MAAMA,CAAAA,CAAS3C,CAA0B,EAC3C,CACF","file":"browser.mjs","sourcesContent":["// SDK version - will be replaced during build with tsup define\ndeclare const __SDK_VERSION__: string | undefined;\n\n// Safely check if __SDK_VERSION__ is defined (replaced during build)\nexport const SDK_VERSION: string = \n (() => { try { return typeof __SDK_VERSION__ !== 'undefined' ? __SDK_VERSION__ : 'undefined'; } catch { return 'undefined'; } })();\n\nexport const SDK_NAME = 'js';\n\n","import type { BaseTransport } from '../../core/types';\n\n/**\n * Generates a deterministic key for request deduplication.\n * Uses sorted keys to ensure consistent key generation regardless of object property order.\n */\nfunction generateRequestKey(endpointPath: string, data: any): string {\n // Normalize data by sorting object keys for consistent serialization\n const normalize = (value: any): any => {\n if (value === null || value === undefined) {\n return value;\n }\n if (Array.isArray(value)) {\n return value.map(normalize);\n }\n if (typeof value === 'object') {\n const sorted: Record<string, any> = {};\n for (const key of Object.keys(value).sort()) {\n sorted[key] = normalize(value[key]);\n }\n return sorted;\n }\n return value;\n };\n \n const normalizedData = JSON.stringify(normalize(data));\n return `${endpointPath}:${normalizedData}`;\n}\n\n/**\n * DedupeTransport wraps a BaseTransport instance and deduplicates in-flight requests.\n * If multiple identical requests (same endpointPath + same request body) are made\n * concurrently, they will share the same underlying HTTP request and promise.\n */\nexport class DedupeTransport implements BaseTransport {\n private inFlightRequests = new Map<string, Promise<any>>();\n\n constructor(\n private wrappedTransport: BaseTransport,\n private debug?: boolean\n ) {}\n\n async post(data: any, endpointPath: string): Promise<any> {\n const requestKey = generateRequestKey(endpointPath, data);\n\n // Check if an identical request is already in-flight\n const existingRequest = this.inFlightRequests.get(requestKey);\n if (existingRequest) {\n if (this.debug) {\n console.log(`[DedupeTransport] Deduplicating request to ${endpointPath}`);\n }\n return existingRequest;\n }\n\n // Create new request and store it\n const requestPromise = this.wrappedTransport.post(data, endpointPath)\n .finally(() => {\n // Clean up when request completes (success or failure)\n this.inFlightRequests.delete(requestKey);\n });\n\n this.inFlightRequests.set(requestKey, requestPromise);\n\n if (this.debug) {\n console.log(`[DedupeTransport] New request to ${endpointPath} (${this.inFlightRequests.size} in-flight)`);\n }\n\n return requestPromise;\n }\n}\n","import type { BaseTransport } from '../../core/types';\nimport { SDK_NAME, SDK_VERSION } from '../../version';\nimport { DedupeTransport } from './dedupe';\n\nconst BASE_URL = 'https://dynamic.belocal.dev';\n\nexport interface BaseBrowserTransportConfig {\n headers?: Record<string, string>;\n timeoutMs?: number;\n debug?: boolean;\n}\n\nexport class BaseBrowserTransport implements BaseTransport {\n constructor(private config: BaseBrowserTransportConfig) {}\n\n async post(data: any, endpointPath: string): Promise<any> {\n const url = `${BASE_URL}${endpointPath}`;\n const controller = new AbortController();\n const timeoutMs = this.config.timeoutMs ?? 10000;\n const timeoutId = setTimeout(() => controller.abort(), timeoutMs);\n\n if (this.config.debug) {\n console.log(`[Base Browser Transport] POST request to ${url}`, data);\n }\n\n try {\n const response = await fetch(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'x-sdk': SDK_NAME,\n 'x-sdk-version': SDK_VERSION,\n ...this.config.headers,\n },\n body: JSON.stringify(data),\n signal: controller.signal,\n });\n\n if (!response.ok) {\n const errorMsg = `HTTP ${response.status}: ${response.statusText}`;\n if (this.config.debug) {\n console.error(`[Base Browser Transport] Request failed:`, errorMsg);\n }\n throw new Error(errorMsg);\n }\n\n const result = await response.json();\n if (this.config.debug) {\n console.log(`[Base Browser Transport] Request successful:`, result);\n }\n \n return result;\n } finally {\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n }\n }\n}\n\nexport function createBaseBrowserTransport(config: BaseBrowserTransportConfig): BaseTransport {\n const transport = new BaseBrowserTransport(config);\n return new DedupeTransport(transport, config.debug);\n}\n","import type { Transport, BaseTransport } from '../core/types';\nimport { md5 } from 'js-md5';\n\nexport interface MultiTransportConfig {\n baseTransport: BaseTransport;\n debug?: boolean;\n batchWindowMs?: number;\n}\n\ninterface MultiRequest {\n request_id: string;\n texts: string[];\n lang: string;\n source_lang?: string;\n ctx?: Record<string, string>;\n}\n\ninterface MultiRequestItem {\n text: string;\n lang: string;\n sourceLang?: string;\n context?: Record<string, string>;\n resolve: (value: { text: string; status: string }) => void;\n reject: (error: Error) => void;\n}\n\ninterface MultiResponse {\n results: Array<{\n request_id: string;\n data: { texts: string[]; status: string };\n }>;\n}\n\ninterface MultiState {\n currentMulti: MultiRequestItem[];\n multiTimer: ReturnType<typeof setTimeout> | null;\n isRequestInFlight: boolean;\n}\n\nfunction generateRequestId(texts: string[], lang: string, sourceLang?: string, context?: Record<string, string>): string {\n const sortedTexts = [...texts].sort();\n \n let sortedContext: Record<string, string> | null = null;\n if (context && Object.keys(context).length > 0) {\n sortedContext = {};\n const sortedKeys = Object.keys(context).sort();\n for (const key of sortedKeys) {\n sortedContext[key] = context[key];\n }\n }\n \n // Include sourceLang for proper grouping of requests with different source languages\n const data = [sortedTexts, lang, sourceLang || null, sortedContext];\n const json = JSON.stringify(data);\n \n return md5(json);\n}\n\nasync function sendMulti(\n config: MultiTransportConfig,\n items: MultiRequestItem[],\n state: MultiState\n): Promise<void> {\n if (config.debug) {\n console.log(`[BeLocal Multi Transport] Sending multi request with ${items.length} texts`);\n }\n\n try {\n // Group texts by translation parameters\n const groups = new Map<string, MultiRequestItem[]>();\n \n items.forEach(item => {\n const groupKey = JSON.stringify({\n lang: item.lang,\n sourceLang: item.sourceLang || null,\n context: item.context || null\n });\n \n if (!groups.has(groupKey)) {\n groups.set(groupKey, []);\n }\n groups.get(groupKey)!.push(item);\n });\n\n const requestIdToGroupItems = new Map<string, MultiRequestItem[]>();\n const requests: MultiRequest[] = Array.from(groups.entries()).map(([groupKey, groupItems]) => {\n const firstItem = groupItems[0];\n const texts = groupItems.map(item => item.text);\n \n const requestId = generateRequestId(\n texts,\n firstItem.lang,\n firstItem.sourceLang,\n firstItem.context\n );\n \n requestIdToGroupItems.set(requestId, groupItems);\n \n return {\n request_id: requestId,\n texts,\n lang: firstItem.lang,\n source_lang: firstItem.sourceLang,\n ctx: firstItem.context\n };\n });\n\n const multiResponse: MultiResponse = await config.baseTransport.post({ requests }, '/v1/translate/multi');\n \n if (config.debug) {\n console.log(`[BeLocal Multi Transport] Multi response received with ${multiResponse.results.length} groups`);\n }\n\n const resultMap = new Map<string, { texts: string[]; status: string }>();\n multiResponse.results.forEach(result => {\n resultMap.set(result.request_id, { texts: result.data.texts, status: result.data.status });\n });\n\n requestIdToGroupItems.forEach((groupItems, requestId) => {\n const result = resultMap.get(requestId);\n \n if (!result) {\n if (config.debug) {\n console.error(`[BeLocal Multi Transport] No result found for request_id: ${requestId}`);\n }\n groupItems.forEach(item => {\n item.reject(new Error(`No result found for request ${requestId}`));\n });\n return;\n }\n\n if (result.texts.length !== groupItems.length) {\n const error = new Error(`Mismatch: expected ${groupItems.length} texts, got ${result.texts.length} for request_id ${requestId}`);\n if (config.debug) {\n console.error(`[BeLocal Multi Transport]`, error.message);\n }\n groupItems.forEach(item => item.reject(error));\n return;\n }\n\n groupItems.forEach((item, index) => {\n const translatedText = result.texts[index];\n const status = result.status || 'success';\n \n if (config.debug) {\n console.log(`[BeLocal Multi Transport] Success for request_id ${requestId}[${index}]: \"${translatedText}\"`);\n }\n \n item.resolve({ text: translatedText, status });\n });\n });\n\n } catch (error) {\n if (config.debug) {\n console.error(`[BeLocal Multi Transport] Multi request error:`, error);\n }\n \n const errorToReject = error instanceof Error ? error : new Error(String(error));\n items.forEach(item => item.reject(errorToReject));\n } finally {\n // Cleanup handled by base transport\n }\n}\n\nfunction processMulti(config: MultiTransportConfig, state: MultiState): void {\n if (state.currentMulti.length === 0 || state.isRequestInFlight) {\n return;\n }\n\n const itemsToSend = [...state.currentMulti];\n state.currentMulti = [];\n state.multiTimer = null;\n state.isRequestInFlight = true;\n\n sendMulti(config, itemsToSend, state).finally(() => {\n state.isRequestInFlight = false;\n \n if (state.currentMulti.length > 0) {\n const windowMs = config.batchWindowMs ?? 50;\n state.multiTimer = setTimeout(() => processMulti(config, state), windowMs);\n }\n });\n}\n\nexport function createMultiTransport(config: MultiTransportConfig): Transport {\n const windowMs = config.batchWindowMs ?? 50;\n\n const state: MultiState = {\n currentMulti: [],\n multiTimer: null,\n isRequestInFlight: false,\n };\n \n return ({ text, lang, source_lang, ctx }) => {\n return new Promise<{ text: string; status: string }>((resolve, reject) => {\n if (config.debug) {\n const tempRequestId = md5(JSON.stringify([text, lang, source_lang || null, ctx || null]));\n console.log(`[BeLocal Multi Transport] Queuing request ${tempRequestId}: \"${text}\" to ${lang}`);\n }\n\n const requestItem: MultiRequestItem = {\n text,\n lang,\n sourceLang: source_lang,\n context: ctx,\n resolve,\n reject,\n };\n\n state.currentMulti.push(requestItem);\n\n if (state.multiTimer === null && !state.isRequestInFlight) {\n state.multiTimer = setTimeout(() => processMulti(config, state), windowMs);\n }\n });\n };\n}\n\n","import type { Cache } from './types';\n\nexport class LocalCache implements Cache {\n private storage = new Map<string, string>();\n\n get(key: string): string | null {\n return this.storage.get(key) || null;\n }\n\n set(key: string, value: string): void {\n this.storage.set(key, value);\n }\n\n isAvailable(): boolean {\n return true;\n }\n}\n","import type { BelocalEngineOptions, KV, Lang, Transport, BaseTransport } from '../types';\nimport { createMultiTransport } from '../../transports/multi';\nimport { LocalCache } from '../../cache/local';\nimport type { Cache } from '../../cache/types';\nimport { md5 } from 'js-md5';\n\n/**\n * Base engine implementation shared between browser and Node.js environments.\n */\nexport class BelocalEngine {\n private transport: Transport;\n private debug: boolean;\n private cache: Cache;\n\n constructor(options: BelocalEngineOptions, baseTransportFactory: (opts: any) => BaseTransport) {\n const {\n apiKey,\n batchWindowMs = 50,\n timeoutMs = 10000,\n debug = false\n } = options;\n\n this.debug = debug;\n this.cache = new LocalCache();\n\n const authHeaders = {\n 'Authorization': `Bearer ${apiKey}`\n };\n\n const baseTransport = baseTransportFactory({\n headers: authHeaders,\n timeoutMs,\n debug: this.debug\n });\n\n this.transport = createMultiTransport({\n baseTransport,\n debug: this.debug,\n batchWindowMs\n });\n \n if (this.debug) {\n console.log('[BeLocal Engine] Multi transport created with config:', {\n baseUrl: 'https://dynamic.belocal.dev',\n timeoutMs,\n batchWindowMs\n });\n }\n }\n\n /**\n * Translates a single text string to the target language.\n * \n * Uses in-memory cache to avoid redundant API calls. Results are automatically cached\n * for subsequent requests with the same parameters.\n * \n * @param text - The text to translate\n * @param lang - Target language code (e.g., 'es', 'fr', 'ru')\n * @param source_lang - Optional source language code. If not provided, auto-detection is used\n * @param ctx - Optional key-value pairs for translation context. Supported keys: `user_ctx` (string - descriptive context), `cache_type` ('managed')\n * @returns Promise resolving to the translated text\n * @throws {Error} If the translation request fails (network error, API error, timeout)\n * \n * @example\n * ```typescript\n * // Simple translation\n * const result = await engine.translate('Hello world', 'es');\n * \n * // With source language\n * const result = await engine.translate('Hello world', 'es', 'en');\n * \n * // With context (user_ctx) - descriptive context helps improve translation quality\n * const result = await engine.translate('Hello world', 'es', undefined, { \n * user_ctx: 'greeting message on the homepage' \n * });\n * \n * // With cache_type\n * const result = await engine.translate('Hello world', 'es', undefined, { cache_type: 'managed' });\n * \n * // With source language and context\n * const result = await engine.translate('Hello world', 'es', 'en', { \n * user_ctx: 'greeting message on the homepage' \n * });\n * ```\n */\n async translate(text: string, lang: Lang, source_lang?: string, ctx?: KV): Promise<string> {\n const results = await this.translateMany([text], lang, source_lang, ctx);\n return results[0];\n }\n\n /**\n * Translates multiple text strings to the target language in a single batch.\n * \n * This method is more efficient than calling `translate()` multiple times as it:\n * - Batches requests together to reduce API calls\n * - Checks cache for each text individually\n * - Only requests translations for cache misses\n * - Maintains the order of input texts in the result array\n * \n * @param texts - Array of texts to translate\n * @param lang - Target language code (e.g., 'es', 'fr', 'ru')\n * @param source_lang - Optional source language code. If not provided, auto-detection is used\n * @param ctx - Optional key-value pairs for translation context. Supported keys: `user_ctx` (string - descriptive context in English), `cache_type` ('managed' | string)\n * @returns Promise resolving to an array of translated texts in the same order as input\n * @throws {Error} If the translation request fails (network error, API error, timeout)\n * \n * @example\n * ```typescript\n * // Translate multiple texts\n * const results = await engine.translateMany(['Hello', 'World', 'Test'], 'es');\n * // Returns: ['Hola', 'Mundo', 'Prueba']\n * \n * // With source language\n * const results = await engine.translateMany(['Hello', 'World'], 'fr', 'en');\n * \n * // With context (user_ctx) - descriptive context helps improve translation quality\n * const results = await engine.translateMany(\n * ['Hello', 'World'], \n * 'es', \n * undefined, \n * { user_ctx: 'greeting message on the homepage' }\n * );\n * \n * // With cache_type\n * const results = await engine.translateMany(\n * ['Hello', 'World'], \n * 'es', \n * undefined, \n * { cache_type: 'managed' }\n * );\n * \n * // Empty array returns empty array\n * const results = await engine.translateMany([], 'es');\n * // Returns: []\n * ```\n */\n async translateMany(texts: string[], lang: Lang, source_lang?: string, ctx?: KV): Promise<string[]> {\n const results: (string | null)[] = new Array(texts.length);\n const cacheMisses: Array<{ index: number; text: string }> = [];\n\n for (let i = 0; i < texts.length; i++) {\n const text = texts[i];\n const cacheKey = this.generateCacheKey(text, lang, source_lang, ctx);\n \n const cachedResult = this.cache.get(cacheKey);\n if (cachedResult) {\n results[i] = cachedResult;\n if (this.debug) {\n console.log('[BeLocal Engine] Translation from cache:', text);\n }\n continue;\n }\n \n results[i] = null;\n cacheMisses.push({ index: i, text });\n }\n\n if (cacheMisses.length > 0) {\n const translations = await Promise.all(\n cacheMisses.map(async ({ index, text }) => {\n const result = await this.transport({ text, lang, source_lang, ctx });\n \n if (result.status !== 'error') {\n const cacheKey = this.generateCacheKey(text, lang, source_lang, ctx);\n this.cache.set(cacheKey, result.text);\n if (this.debug) {\n console.log('[BeLocal Engine] Translation from API, cached:', text);\n }\n } else {\n if (this.debug) {\n console.log('[BeLocal Engine] Translation from API (not cached due to error status):', text);\n }\n }\n \n return { index, translation: result.text };\n })\n );\n\n translations.forEach(({ index, translation }) => {\n results[index] = translation;\n });\n }\n\n return results as string[];\n }\n\n /**\n * Shortcut method for translation with simplified API.\n * \n * This is a convenience method that wraps `translate()`. When `context` is provided as a string,\n * it is automatically wrapped in `{user_ctx: context}` object.\n * \n * @param text - The text to translate\n * @param lang - Target language code (e.g., 'es', 'fr', 'ru')\n * @param source_lang - Optional source language code\n * @param context - Optional descriptive context string in English (will be wrapped as {user_ctx: context})\n * @returns Promise resolving to the translated text\n * @throws {Error} If the translation request fails (network error, API error, timeout)\n * \n * @example\n * ```typescript\n * // Simple translation\n * const result = await engine.t('Hello world', 'es');\n * \n * // With source language\n * const result = await engine.t('Hello world', 'fr', 'en');\n * \n * // With context string (automatically wrapped as {user_ctx: 'greeting message on the homepage'})\n * const result = await engine.t('Hello world', 'es', undefined, 'greeting message on the homepage');\n * \n * // With source language and context\n * const result = await engine.t('Hello world', 'es', 'en', 'greeting message on the homepage');\n * ```\n */\n async t(text: string, lang: Lang, source_lang?: string, context?: string): Promise<string> {\n if (context) {\n return this.translate(text, lang, source_lang, {user_ctx: context});\n }\n return this.translate(text, lang, source_lang);\n }\n\n private generateCacheKey(text: string, lang: Lang, source_lang?: string, ctx?: KV): string {\n const sortedCtx = ctx ? Object.keys(ctx)\n .sort()\n .reduce((acc, key) => {\n acc[key] = ctx[key];\n return acc;\n }, {} as KV) : null;\n\n const data = {\n text,\n lang,\n source_lang: source_lang || null,\n ctx: sortedCtx\n };\n return md5(JSON.stringify(data));\n }\n}\n","import type { BelocalEngineOptions } from '../types';\nimport { createBaseBrowserTransport } from '../../transports/base/browser';\nimport { BelocalEngine as BaseEngine } from './engine';\n\n/**\n * BeLocal translation engine for browser environments.\n * \n * Provides on-demand translation with automatic request batching, caching, and deduplication.\n * Optimized for browser environments using the Fetch API.\n * \n * @example\n * ```typescript\n * const engine = new BelocalEngine({\n * apiKey: 'your-api-key',\n * debug: true\n * });\n * \n * const translated = await engine.translate('Hello world', 'es');\n * ```\n */\nexport class BelocalEngine extends BaseEngine {\n /**\n * Creates a new BelocalEngine instance for browser environments.\n * \n * @param options - Configuration options for the engine\n * @throws {Error} If apiKey is not provided or invalid\n * \n * @example\n * ```typescript\n * const engine = new BelocalEngine({\n * apiKey: 'your-api-key',\n * batchWindowMs: 100,\n * timeoutMs: 10000,\n * debug: false\n * });\n * ```\n */\n constructor(options: BelocalEngineOptions) {\n super(options, createBaseBrowserTransport);\n }\n}\n\n// Re-export types and transports\nexport type { BelocalEngineOptions, Lang, KV, BaseTransport } from '../types';\nexport { createMultiTransport } from '../../transports/multi';\nexport { BaseBrowserTransport, createBaseBrowserTransport } from '../../transports/base';\n"]}