openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
1 lines • 1.59 kB
JavaScript
const e={},t=/[\p{ASCII}]+|[^\p{ASCII}]/gu,n=[[[183,183],[12288,12703],[19968,40869],[44032,55215],[65281,65376]],[[4352,4607],[11904,12287],[12704,19967],[40870,40959],[40960,42239],[42752,42759],[43360,43391],[55216,55295],[63744,64255]],[[711,711],[713,715],[729,729],[746,747],[773,773],[803,803],[65040,65103],[65377,65500],[65504,65510]],[[119648,119665]],[[94176,94207],[110576,110591],[110592,110959],[127488,127743],[131072,195103],[196608,210047]]],r=RegExp(`[${n.flatMap(e=>e.map(([e,t])=>`\\u{${e.toString(16)}}-\\u{${t.toString(16)}}`)).join(``)}]`,`u`),i=(()=>{let e=Math.max(...n.flatMap(e=>e.map(([,e])=>e))),t=new Uint8Array(e+1);for(let[e,r]of n.entries())for(let[n,i]of r)t.fill(e+1,n,i+1);return t})();function estimateStringChars(e){return estimateStringCharsWithMinimumRawWeight(e)}function estimateStringCharsWithMinimumRawWeight(n,a=e){let o=Math.max(1,a.minimumRawWeight??1);if(o!==1&&o!==2){let e=0;for(let r of n.matchAll(t)){let t=r[0],n=Math.ceil(t.length*o);e+=t.charCodeAt(0)<=127?n:Math.max(estimateStringChars(t),n)}return e}let s=n.search(r);if(s<0)return n.length*o;let c=0,l=0,u=0,d=0,f=0;for(let e=s;e<n.length;e+=1){let t=n.charCodeAt(e);if(!(t<128)){if(t>=55296&&t<=56319){let r=n.charCodeAt(e+1);r>=56320&&r<=57343&&(t=65536+(t-55296)*1024+r-56320,e+=1)}switch(i[t]){case 1:c+=1;break;case 2:l+=1;break;case 3:u+=1;break;case 4:d+=1;break;case 5:f+=1}}}return n.length*o+c*(4-o)+l*(12-o)+u*(8-o)+d*(12-2*o)+f*(16-2*o)}function estimateTokensFromChars(e){return Math.ceil(Math.max(0,e)/4)}export{estimateTokensFromChars as n,estimateStringChars as t};