UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

8 lines • 5.67 kB
import{A as concatBytes}from"./validate-Btv7lFe1.mjs";import{Dt as MAX_HEAD_FRAME_BYTES,Et as MAX_FRAME_BYTES,Ft as WS_OPCODE,Ot as MAX_HTTP_DATA_FRAME_BYTES}from"./src-BTTzpNjb.mjs";import{createRequire}from"node:module";import{existsSync}from"node:fs";import{fileURLToPath}from"node:url";import path from"node:path"; //!packages/openclaw-id-protocol/src/tunnel/framing.ts var TunnelProtocolError=class extends Error{};function isHeaderList(e){return Array.isArray(e)&&e.every(e=>Array.isArray(e)&&e.length===2&&typeof e[0]===`string`&&typeof e[1]===`string`)}function parseJsonFrame(e){if(e.length>65536)throw new TunnelProtocolError(`HEAD frame too large`);let t;try{t=JSON.parse(new TextDecoder(`utf-8`,{fatal:true}).decode(e))}catch{throw new TunnelProtocolError(`HEAD frame is not UTF-8 JSON`)}if(typeof t!==`object`||t===null||Array.isArray(t))throw new TunnelProtocolError(`HEAD frame is not an object`);return t}const METHOD_RE=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;function encodeHead(e){return new TextEncoder().encode(JSON.stringify(e))}function parseRequestHead(e){const t=parseJsonFrame(e);if(typeof t.path!==`string`||!t.path.startsWith(`/`)||!isHeaderList(t.headers))throw new TunnelProtocolError(`HEAD needs an absolute path and a header list`);if(t.kind===`http`){if(typeof t.method!==`string`||!METHOD_RE.test(t.method))throw new TunnelProtocolError(`invalid HTTP method`);return{kind:`http`,method:t.method,path:t.path,headers:t.headers}}if(t.kind===`ws`){const e=t.protocols??[];if(!Array.isArray(e)||!e.every(e=>typeof e===`string`))throw new TunnelProtocolError(`invalid WebSocket protocols`);return{kind:`ws`,path:t.path,headers:t.headers,protocols:e}}throw new TunnelProtocolError(`HEAD kind must be http or ws`)}function parseResponseHead(e){const t=parseJsonFrame(e);if(typeof t.status!==`number`||!Number.isInteger(t.status)||t.status<100||t.status>599)throw new TunnelProtocolError(`invalid status`);if(t.status===101){const e=t.protocol??null;if(e!==null&&typeof e!==`string`)throw new TunnelProtocolError(`invalid WebSocket protocol`);return{status:101,protocol:e}}const n=t.headers??[];if(!isHeaderList(n))throw new TunnelProtocolError(`invalid header list`);return{status:t.status,headers:n}}function encodeWsMessage(e){if(e.op===`close`){const t=new TextEncoder().encode(e.reason);if(e.code===null)return new Uint8Array([WS_OPCODE.close]);const n=new Uint8Array(3+t.length);n[0]=WS_OPCODE.close;new DataView(n.buffer).setUint16(1,e.code);n.set(t,3);return n}return concatBytes(new Uint8Array([WS_OPCODE[e.op]]),e.data)}function decodeWsMessage(e){const t=e[0];const n=e.slice(1);if(t===WS_OPCODE.text)return{op:`text`,data:n};if(t===WS_OPCODE.binary)return{op:`binary`,data:n};if(t===WS_OPCODE.close){if(n.length===0)return{op:`close`,code:null,reason:``};if(n.length<2)throw new TunnelProtocolError(`truncated close code`);return{op:`close`,code:new DataView(n.buffer,n.byteOffset).getUint16(0),reason:new TextDecoder().decode(n.slice(2))}}throw new TunnelProtocolError(`unknown WebSocket opcode ${String(t)}`)} //!src/gateway/openclaw-id/tunnel-child/addon.ts const PACKAGE_NAME=`@openclaw/iroh-node`;const SOURCE_CHECKOUT_PATH=path.join(`crates`,`openclaw-iroh-node`,`index.js`);function findSourceCheckoutBinding(){let e=path.dirname(fileURLToPath(import.meta.url));for(;;){const t=path.join(e,SOURCE_CHECKOUT_PATH);if(existsSync(t))return t;const n=path.dirname(e);if(n===e)return;e=n}}function loadIrohBinding(){const e=createRequire(import.meta.url);const t=[];for(const n of[PACKAGE_NAME,findSourceCheckoutBinding()]){if(!n)continue;try{const t=e(n);if(typeof t.Endpoint.prototype.watchHomeRelay!==`function`)throw new Error(`built without the home relay watcher`);return t}catch(e){t.push(`${n}: ${(e instanceof Error?e.message:String(e)).split(` `)[0]}`)}}const n=findSourceCheckoutBinding()?"OpenClaw ID is enabled, but the iroh binding is not built or could not be loaded. Run `pnpm build:iroh` from the source checkout.":`The OpenClaw ID transport is not available in this build.`;throw new Error(n,{cause:/* @__PURE__ */ new Error(`iroh binding unavailable (${t.join(`; `)||`not installed`})`)})} //!src/gateway/openclaw-id/tunnel-child/frames.ts const READ_CHUNK=1<<20;var FrameReader=class{constructor(e){this.recv=e;this.chunks=[];this.buffered=0;this.eof=false}async fill(){if(this.eof)return false;const e=await this.recv.read(READ_CHUNK);if(!e||e.length===0){this.eof=true;return false}this.chunks.push(e);this.buffered+=e.length;return true}take(e){const t=this.chunks.length===1?this.chunks[0]:Buffer.concat(this.chunks);this.chunks=e<t.length?[t.subarray(e)]:[];this.buffered-=e;return t.subarray(0,e)}async next(e=MAX_FRAME_BYTES){while(this.buffered<4)if(!await this.fill()){if(this.buffered===0)return null;throw new TunnelProtocolError(`truncated frame header`)}const t=this.take(4).readUInt32BE(0);if(t>e)throw new TunnelProtocolError(`frame of ${t} bytes exceeds ${e}`);while(this.buffered<t)if(!await this.fill())throw new TunnelProtocolError(`truncated frame`);return Buffer.from(this.take(t))}};async function writeFrame(e,t){if(t.length>33554432)throw new TunnelProtocolError(`frame too large`);const n=Buffer.allocUnsafe(4);n.writeUInt32BE(t.length,0);if(t.length<65536)await e.write(Buffer.concat([n,t]));else{await e.write(n);await e.write(t)}}async function writeDataFrames(e,t){for(let n=0;n<t.length;n+=MAX_HTTP_DATA_FRAME_BYTES)await writeFrame(e,t.subarray(n,n+MAX_HTTP_DATA_FRAME_BYTES))}export{TunnelProtocolError as a,encodeWsMessage as c,loadIrohBinding as i,parseRequestHead as l,writeDataFrames as n,decodeWsMessage as o,writeFrame as r,encodeHead as s,FrameReader as t,parseResponseHead as u};