UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

3 lines • 2.22 kB
//!src/infra/json-utf8-bytes.ts function jsonUtf8Bytes(e){try{return Buffer.byteLength(JSON.stringify(e),`utf8`)}catch{return Buffer.byteLength(String(e),`utf8`)}}function jsonUtf8BytesOrInfinity(e){try{const t=JSON.stringify(e);return typeof t===`string`?Buffer.byteLength(t,`utf8`):Number.POSITIVE_INFINITY}catch{return Number.POSITIVE_INFINITY}}const JSON_STRING_ESCAPES=/["\\\u0000-\u001f\ud800-\udfff]/gu;function jsonStringByteLengthUpToLimit(e,t){if(e.length+2>t)return t+1;let n=Buffer.byteLength(e,`utf8`)+2;if(n>t)return t+1;for(const t of e.match(JSON_STRING_ESCAPES)??[]){const e=t.charCodeAt(0);n+=e>=55296?3:e<32&&!`\b \f\r`.includes(t)?5:1}return n}function firstEnumerableOwnKeys(e,t){const n=[];for(const r in e){if(!Object.prototype.propertyIsEnumerable.call(e,r))continue;n.push(r);if(n.length>=t)break}return n}function boundedJsonUtf8Bytes(e,t){let n=0;let r;const add=e=>{n+=e;if(n>t)throw new Error(`json_byte_limit_exceeded`)};const visit=(e,i)=>{if(e===null){add(4);return}switch(typeof e){case`string`:add(jsonStringByteLengthUpToLimit(e,t-n));return;case`number`:add(jsonUtf8BytesOrInfinity(Number.isFinite(e)?e:null));return;case`boolean`:add(e?4:5);return;case`undefined`:case`function`:case`symbol`:if(i)add(4);return;case`bigint`:throw new Error(`json_byte_length_unsupported`)}const a=e;if((r??=/* @__PURE__ */ new WeakSet).has(a))throw new Error(`json_byte_length_circular`);if(typeof a.toJSON===`function`&&!(a instanceof Date))throw new Error(`json_byte_length_custom_to_json`);r.add(a);try{if(a instanceof Date){visit(a.toJSON(),i);return}const e=Array.isArray(a);add(1);if(e)for(let e=0;e<a.length;e+=1){if(e>0)add(1);visit(a[e],true)}else{let e=false;const r=a;for(const i in r){if(!Object.prototype.propertyIsEnumerable.call(r,i))continue;const a=r[i];if(a===void 0||typeof a===`function`||typeof a===`symbol`)continue;if(e)add(1);e=true;add(jsonStringByteLengthUpToLimit(i,t-n));add(1);visit(a,false)}}add(1)}finally{r.delete(a)}};try{visit(e,false);return{bytes:n,complete:true}}catch{return{bytes:Math.max(n,t+1),complete:false}}}export{jsonUtf8BytesOrInfinity as a,jsonUtf8Bytes as i,firstEnumerableOwnKeys as n,jsonStringByteLengthUpToLimit as r,boundedJsonUtf8Bytes as t};