microsoft-webui-desktop 0.0.30

Configurable native desktop SDK for WebUI applications
Documentation
1
2
3
4
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.

var ae=["invalid-frame","invalid-payload","payload-too-large","unsupported-version","schema-mismatch","permission-denied","unknown-method","receiver-unavailable","not-ready","overloaded","cancelled","deadline-exceeded","navigated","closed","transport","handler"],n=class extends Error{constructor(t,i=t,o="Check the connection and the generated contract.",c){super(i);this.code=t;this.help=o;this.applicationCode=c;this.name="IpcError"}code;help;applicationCode};function ce(r){return ae.includes(r)?r:"transport"}function w(r,e="transport"){if(r instanceof n)return r;if(r&&typeof r=="object"){let t=Object.getOwnPropertyDescriptor(r,"name")?.value,i=Object.getOwnPropertyDescriptor(r,"code")?.value;if(t==="IpcError"&&ae.includes(i))return new n(i)}return new n(e)}var Pe=30,de=0,le=1,fe=2,_=class{constructor(e,t){this.view=e;this.bytes=t}view;bytes;pos=0;take(e){if(this.pos+e>this.bytes.length)throw new n("invalid-frame");let t=this.pos;return this.pos+=e,t}u8(){return this.view.getUint8(this.take(1))}u32(){return this.view.getUint32(this.take(4),!0)}u64(){return this.view.getBigUint64(this.take(8),!0)}bytes_(e){let t=this.take(e);return this.bytes.subarray(t,t+e)}delimited(){let e=this.u32();if(e>this.bytes.length-this.pos)throw new n("invalid-frame");return this.bytes_(e)}string(){return new TextDecoder("utf-8",{fatal:!0}).decode(this.delimited())}atEnd(){return this.pos===this.bytes.length}},$=class{chunks=[];u8(e){this.chunks.push(Uint8Array.of(e&255))}u32(e){let t=new Uint8Array(4);new DataView(t.buffer).setUint32(0,e,!0),this.chunks.push(t)}u64(e){let t=new Uint8Array(8);new DataView(t.buffer).setBigUint64(0,e,!0),this.chunks.push(t)}raw(e){this.chunks.push(e)}delimited(e){this.u32(e.length),this.raw(e)}string(e){this.delimited(new TextEncoder().encode(e))}finish(){let e=0;for(let o of this.chunks)e+=o.length;let t=new Uint8Array(e),i=0;for(let o of this.chunks)t.set(o,i),i+=o.length;return t}};function he(r,e){r.string(e.code),r.string(e.message),r.string(e.help),r.string(e.applicationCode)}function ue(r){return{code:r.string(),message:r.string(),help:r.string(),applicationCode:r.string()}}var pe={encode(r){let e=new $;return he(e,r),e},decode(r){let e=new _(new DataView(r.buffer,r.byteOffset,r.byteLength),r),t=ue(e);if(!e.atEnd())throw new n("invalid-frame");return t}},L={encode(r){let e=new $;switch(e.u32(r.version),e.u64(r.generation),e.u64(r.id),e.u8(r.kind>=0&&r.kind<=6?r.kind:0),e.u32(r.methodId),e.u32(r.timeoutMs),r.body?.$case){case void 0:e.u8(de);break;case"payload":e.u8(le),e.delimited(r.body.value);break;case"error":e.u8(fe),he(e,r.body.value);break}return e},decode(r){if(r.length<Pe)throw new n("invalid-frame");let e=new _(new DataView(r.buffer,r.byteOffset,r.byteLength),r),t=e.u32(),i=e.u64(),o=e.u64(),c=e.u8(),l=e.u32(),d=e.u32(),a=e.u8(),f;switch(a){case de:f=void 0;break;case le:f={$case:"payload",value:e.delimited()};break;case fe:f={$case:"error",value:ue(e)};break;default:throw new n("invalid-frame")}if(!e.atEnd())throw new n("invalid-frame");return{version:t,generation:i,id:o,kind:c,methodId:l,timeoutMs:d,body:f}}};var ye=3;function A(r,e,t){return{version:ye,generation:r,id:e,kind:t,methodId:0,timeoutMs:0}}function q(r,e){if(r.byteLength>e.maxFrameBytes)throw new n("payload-too-large");try{let t=L.decode(r);if(t.version!==ye)throw new n("unsupported-version");if(!t.id||!t.generation||t.kind<1||t.kind>6)throw new n("invalid-frame");if(t.kind===1||t.kind===4?!t.methodId:t.methodId!==0||t.timeoutMs!==0)throw new n("invalid-frame");if(t.kind===1?!t.timeoutMs||t.timeoutMs>e.maxTimeoutMs:t.timeoutMs!==0)throw new n("invalid-frame");let o=t.kind===3?"error":t.kind===1||t.kind===4||t.kind===2?"payload":void 0;if(t.body?.$case!==o)throw new n("invalid-frame");if(t.body?.$case==="error"){let c=t.body.value;if(new TextEncoder().encode(c.code+c.message+c.help+c.applicationCode).length>e.maxErrorTextBytesTotal)throw new n("invalid-frame")}return t}catch(t){throw t instanceof n?t:new n("invalid-frame")}}function z(r){return new n(ce(r.code),r.message,r.help,r.applicationCode||void 0)}function be(r){return{code:r.code,message:r.code,help:"Check the connection and contract.",applicationCode:""}}var M=Object.freeze({maxFrameBytes:1048576,maxNativeControlBytes:4096,maxPendingCallsPerDirection:64,maxOutstandingNotificationsPerDirection:64,maxQueuedFramesPerDirection:128,maxQueuedBytesPerDirection:8388608,maxAdmittedInputBytesPerFrame:8388608,maxRetainedBytesPerFrame:16777216,maxWorkerTasksPerFrameIncludingRetiredDocuments:128,maxCallbacksPerEvent:16,maxCallbacksPerDocument:128,maxCallbackTasksPerDocument:128,maxCollectionEntriesPerMessage:16384,maxSchemaDepth:16,maxReadinessWaiters:16,defaultTimeoutMs:3e4,maxTimeoutMs:3e5,notificationAcceptTimeoutMs:3e4,handshakeTimeoutMs:5e3,maxErrorTextBytesTotal:2048,reservedControlFramesPerDirection:128});function Y(r){for(let e of Object.keys(M))if(!Number.isSafeInteger(r[e])||r[e]<=0)throw new n("invalid-frame",`Invalid IPC limit: ${e}`);if(r.maxFrameBytes>16*1048576||r.maxNativeControlBytes>65536||r.maxPendingCallsPerDirection>4096||r.maxCallbacksPerDocument>1024||r.maxQueuedBytesPerDirection>64*1048576||r.maxFrameBytes>r.maxQueuedBytesPerDirection||r.defaultTimeoutMs>r.maxTimeoutMs||r.maxTimeoutMs>3e5||r.maxOutstandingNotificationsPerDirection>4096||r.maxCallbacksPerEvent>r.maxCallbacksPerDocument||r.maxSchemaDepth>16||r.maxReadinessWaiters>16||r.notificationAcceptTimeoutMs>r.maxTimeoutMs||r.maxWorkerTasksPerFrameIncludingRetiredDocuments>4096||r.maxCallbackTasksPerDocument>4096||r.maxQueuedFramesPerDirection>8192||r.reservedControlFramesPerDirection>8192||r.maxCollectionEntriesPerMessage>1048576||r.maxErrorTextBytesTotal>2048||r.handshakeTimeoutMs>5e3||r.maxFrameBytes<r.maxErrorTextBytesTotal+128)throw new n("invalid-frame","Inconsistent IPC limits.");if(r.maxAdmittedInputBytesPerFrame>64*1048576||r.maxRetainedBytesPerFrame>128*1048576||r.maxAdmittedInputBytesPerFrame<r.maxFrameBytes||r.maxRetainedBytesPerFrame<r.maxAdmittedInputBytesPerFrame)throw new n("invalid-frame","Inconsistent IPC byte budgets.")}var G=class{constructor(e,t,i){this.transport=e;this.limits=t;this.ledger=i}transport;limits;ledger;entries=[];bytes=0;data=0;controls=0;reserved=0;running=!1;failure;reserveControl(){if(this.failure)throw this.failure;if(this.controls+this.reserved>=this.limits.reservedControlFramesPerDirection)throw new n("overloaded");this.reserved++;let e=!0,t=()=>e?(e=!1,this.failure||this.reserved--,!0):!1;return{owner:this,claim:t,release:t}}send(e,t,i,o,c){if(this.failure)return Promise.reject(this.failure);if(e.byteLength>this.limits.maxFrameBytes)return Promise.reject(new n("payload-too-large"));let l=c?.owner===this&&c.claim();if(t?!l&&this.controls+this.reserved>=this.limits.reservedControlFramesPerDirection:this.data>=this.limits.maxQueuedFramesPerDirection||this.bytes+e.byteLength>this.limits.maxQueuedBytesPerDirection)return Promise.reject(new n("overloaded"));if(t&&e.byteLength>this.limits.maxErrorTextBytesTotal+128)return Promise.reject(new n("payload-too-large"));let d;try{d=t?()=>{}:this.ledger.reserve(e.buffer.byteLength)}catch(a){return Promise.reject(w(a))}return t?this.controls++:(this.data++,this.bytes+=e.byteLength),new Promise((a,f)=>{let u={bytes:e,control:t,resolve:a,reject:f,release:d};i&&(u.prepare=i),o!==void 0&&(u.id=o),this.entries.push(u),this.pump()})}remove(e){let t=this.entries.findIndex((o,c)=>o.id===e&&(!this.running||c!==0));if(t<0)return;let[i]=this.entries.splice(t,1);i&&(this.release(i),i.resolve())}close(e){this.failure??=e;for(let t=0;t<this.entries.length;t++){let i=this.entries[t];i.reject(e),(!this.running||t!==0)&&i.release()}this.entries=[],this.bytes=this.data=this.controls=this.reserved=0}async pump(){if(!this.running){this.running=!0;try{for(;this.entries.length&&!this.failure;){let e=this.entries[0],t;try{let i;if(e.prepare){let o=this.ledger.reserve(e.bytes.byteLength*3+256);try{i=e.prepare(e.bytes)}finally{o()}}else i=e.bytes;i&&i!==e.bytes&&!e.control&&(t=this.ledger.reserve(i.buffer.byteLength)),i&&await this.transport.send(i),e.resolve()}catch(i){e.reject(w(i))}finally{t?.()}if(this.failure){e.release();break}this.entries.shift(),this.release(e)}}finally{this.running=!1}}}release(e){e.release(),e.control?this.controls--:(this.data--,this.bytes-=e.bytes.byteLength)}};var S=class{state;constructor(e){this.state={input:0,retained:0,limits:e}}get input(){return this.state.input}set input(e){this.state.input=e}get retained(){return this.state.retained}set retained(e){this.state.retained=e}get limits(){return this.state.limits}set limits(e){this.state.limits=e}shareWith(e){if(this.state!==e.state){if(this.input||this.retained)throw new n("invalid-frame","Cannot replace an active byte ledger.");this.state=e.state}}reserve(e){if(!Number.isSafeInteger(e)||e<0||this.retained+e>this.limits.maxRetainedBytesPerFrame)throw new n("overloaded");this.retained+=e;let t=!0;return()=>{t&&(t=!1,this.retained-=e)}}reserveInput(e){return new K(this,e)}},K=class{constructor(e,t){this.owner=e;this.grow(t)}owner;releases=[];active=!0;capacity=0;grow(e){if(!this.active||this.owner.input+e>this.owner.limits.maxAdmittedInputBytesPerFrame)throw new n("overloaded");let t=this.owner.reserve(e);this.owner.input+=e,this.capacity+=e,this.releases.push(t)}release(){if(this.active){this.active=!1,this.owner.input-=this.capacity;for(let e of this.releases)e();this.releases=[]}}owns(e,t){return this.active&&this.owner===t&&this.capacity>=e.buffer.byteLength}};function ee(r){return"byteLedger"in r&&"receiveReserved"in r}function te(r,e,t,i){let o;try{r.validate(e,i.limits);let c=i.limits.maxFrameBytes+i.limits.maxCollectionEntriesPerMessage*16+256;o=i.reserve(c*4);let l=r.encode(e);if(l.byteLength>i.limits.maxFrameBytes)throw new n("payload-too-large");t.body={$case:"payload",value:l};let d=L.encode(t).finish();if(d.byteLength>i.limits.maxFrameBytes)throw new n("payload-too-large");return d}catch(c){throw w(c,"invalid-payload")}finally{o?.()}}function re(r,e,t){try{r.validateBytes(e,t);let i=r.decode(e);return r.validate(i,t),i}catch(i){throw w(i,"invalid-payload")}}function X(r){return{wireVersion:r.wireVersion,contractName:r.contractName,contractMajor:r.contractMajor,schemaHash:r.schemaHash}}var J=class{constructor(e,t,i){this.schema=e;this.transport=t;this.options=i;this.options={...i},this.closed=new Promise(o=>{this.resolveClosed=o});for(let o of e.methods){if(!Number.isInteger(o.id)||o.id<1024||o.id>4294967295||this.methods.has(o.id))throw new n("invalid-payload","Invalid or duplicate method ID.");this.methods.set(o.id,o)}}schema;transport;options;closed;stats={staleReplies:0,callbackErrors:0,timeouts:0,cancellations:0};resolveClosed;failure;limits=M;generation=0n;nextId=1n;lastIncoming=0n;pending=new Map;handlers=new Map;callbacks=new Map;incoming=new Map;methods=new Map;output;callbackCount=0;callbackTasks=0;handlerTasks=0;ledger=new S(M);async start(){let e=[],t=0;try{let i=this.options.setup;delete this.options.setup,i?.(this);let o=async(d,a)=>{if(this.failure){a.release();return}if(!a.owns(d,this.ledger)){a.release(),this.fail(new n("invalid-frame"));return}if(this.generation)this.receive(d,a);else{if(t+=d.byteLength,e.length>=M.maxQueuedFramesPerDirection||t>M.maxQueuedBytesPerDirection){this.fail(new n("overloaded")),a.release();return}e.push({bytes:d,credit:a})}},c={byteLedger:this.ledger,receiveReserved:o,receive:async d=>{if(this.generation){this.receive(d);return}await o(d,this.ledger.reserveInput(d.buffer.byteLength))},closed:d=>this.fail(d)},l=await this.transport.start(X(this.schema),c);if(this.failure)throw this.failure;if(Y(l.limits),this.limits=Object.freeze({...l.limits}),this.ledger.limits=this.limits,this.ledger.input>this.limits.maxAdmittedInputBytesPerFrame||this.ledger.retained>this.limits.maxRetainedBytesPerFrame)throw new n("overloaded");if(this.callbackCount>this.limits.maxCallbacksPerDocument)throw new n("overloaded");for(let d of this.callbacks.values())if(d.size>this.limits.maxCallbacksPerEvent)throw new n("overloaded");if(this.generation=BigInt(l.generation),this.generation<=0n||this.generation>0xffffffffffffffffn||String(this.generation)!==l.generation)throw new n("invalid-frame");for(this.output=new G(this.transport,this.limits,this.ledger);e.length;){let d=e.shift();this.receive(d.bytes,d.credit)}if(this.failure)throw this.failure}catch(i){for(let o of e)o.credit.release();throw this.fail(w(i)),this.failure}}call(e,t,i={}){return this.invoke(e,t,i)}notify(e,t){return this.invoke(e,t,{})}handle(e,t){if(this.checkMethod(e,"renderer"),this.handlers.has(e.id))throw new n("invalid-payload","Handler already registered.");let i={invoke:t};return this.handlers.set(e.id,i),{close:()=>{this.handlers.get(e.id)===i&&this.handlers.delete(e.id),delete i.invoke}}}subscribe(e,t){this.checkMethod(e,"renderer");let i=this.callbacks.get(e.id)??new Set;if(i.size>=this.limits.maxCallbacksPerEvent||this.callbackCount>=this.limits.maxCallbacksPerDocument)throw new n("overloaded");let o={active:!0,tail:Promise.resolve(),invoke:t};return i.add(o),this.callbacks.set(e.id,i),this.callbackCount++,{close:()=>{o.active&&(o.active=!1,delete o.invoke,i.delete(o),this.callbackCount--,i.size||this.callbacks.delete(e.id))}}}close(){this.fail(new n("closed"))}checkMethod(e,t){if(this.failure)throw this.failure;if(this.methods.get(e.id)!==e||e.receiver!==t)throw new n("unknown-method")}async invoke(e,t,i){let o=performance.now();if(this.checkMethod(e,"host"),!this.output)throw new n("not-ready");let c=e.kind==="notification"?this.limits.notificationAcceptTimeoutMs:i.timeoutMs??this.limits.defaultTimeoutMs;if(!Number.isInteger(c)||c<=0||c>this.limits.maxTimeoutMs)throw new n("invalid-payload");if(i.signal?.aborted)throw new n("cancelled");let l=0;for(let p of this.pending.values())p.kind===e.kind&&l++;let d=e.kind==="rpc"?this.limits.maxPendingCallsPerDirection:this.limits.maxOutstandingNotificationsPerDirection;if(l>=d)throw new n("overloaded");if(this.nextId>0xffffffffffffffffn)throw this.close(),this.failure;let a=this.nextId++,f=A(this.generation,a,e.kind==="rpc"?1:4);f.methodId=e.id,f.timeoutMs=e.kind==="rpc"?c:0;let u=te(e.request,t,f,this.ledger),s=e.kind==="rpc"?this.output.reserveControl():void 0,m=o+c;return new Promise((p,g)=>{let R=!1,k=D=>{this.pending.has(a)&&(D==="cancelled"?this.stats.cancellations++:this.stats.timeouts++,this.settle(a,new n(D)),R&&e.kind==="rpc"&&this.sendControl(A(this.generation,a,6)))},B=()=>k("cancelled"),Z=setTimeout(()=>k("deadline-exceeded"),Math.max(0,m-performance.now()));if(i.signal?.addEventListener("abort",B,{once:!0}),this.pending.set(a,{kind:e.kind,...e.kind==="rpc"?{codec:e.response}:{},resolve:p,reject:g,cleanup:()=>{clearTimeout(Z),i.signal?.removeEventListener("abort",B),s?.release()}}),i.signal?.aborted){k("cancelled");return}this.output.send(u,!1,D=>{if(!this.pending.has(a))return;let E=Math.ceil(m-performance.now());if(E<=0){k("deadline-exceeded");return}let W=L.decode(D);return R=!0,e.kind!=="rpc"||W.timeoutMs===E?D:(W.timeoutMs=E,L.encode(W).finish())},a).catch(D=>{let E=w(D);this.settle(a,E),(E.code==="transport"||E.code==="closed"||E.code==="navigated")&&this.fail(E)})})}settle(e,t,i){let o=this.pending.get(e);o&&(this.pending.delete(e),this.output?.remove(e),o.cleanup(),t?o.reject(t):o.resolve(i))}receive(e,t){if(this.failure){t?.release();return}let i=!1;try{let o=q(e,this.limits);if(o.generation!==this.generation){this.stats.staleReplies++;return}if(o.kind===1||o.kind===4){if(o.id<=this.lastIncoming)throw new n("invalid-frame");this.lastIncoming=o.id;try{t??=this.ledger.reserveInput(e.buffer.byteLength)}catch(c){this.sendError(o.id,w(c));return}i=this.dispatch(o,t)}else o.kind===6?this.cancelIncoming(o.id):this.complete(o)}catch(o){this.fail(w(o,"invalid-frame"))}finally{i||t?.release()}}complete(e){let t=this.pending.get(e.id);if(!t){this.stats.staleReplies++;return}if(e.kind===3&&e.body?.$case==="error"){this.settle(e.id,z(e.body.value));return}if(t.kind==="notification"&&e.kind===5){this.settle(e.id);return}if(t.kind!=="rpc"||e.kind!==2||e.body?.$case!=="payload")throw new n("invalid-frame");try{this.settle(e.id,void 0,re(t.codec,e.body.value,this.limits))}catch(i){this.settle(e.id,w(i,"invalid-payload"))}}dispatch(e,t){try{let i=this.methods.get(e.methodId);if(!i)throw new n("unknown-method");if(i.receiver!=="renderer"||i.kind==="rpc"!=(e.kind===1))throw new n("invalid-frame");let o=re(i.request,e.body.value,this.limits);return i.kind==="notification"?this.deliver(e,o,t):(this.runHandler(e,i,o,t),!0)}catch(i){return this.sendError(e.id,w(i,"handler")),!1}}deliver(e,t,i){let o=this.callbacks.get(e.methodId);if(this.callbackTasks+(o?.size??0)>this.limits.maxCallbackTasksPerDocument)throw new n("overloaded");if(this.sendControl(A(this.generation,e.id,5),this.output.reserveControl()),this.failure||!o?.size)return!1;let c=o.size;for(let l of o)this.callbackTasks++,l.tail=l.tail.then(async()=>{l.active&&!this.failure&&await l.invoke?.(t)}).catch(d=>{this.stats.callbackErrors++,this.report(w(d,"handler"))}).finally(()=>{this.callbackTasks--,--c===0&&i.release()});return!0}runHandler(e,t,i,o){let c=this.handlers.get(t.id);if(!c?.invoke)throw new n("receiver-unavailable");if(this.handlerTasks>=this.limits.maxPendingCallsPerDirection)throw new n("overloaded");let l=this.output.reserveControl();this.handlerTasks++;let d=new AbortController,a={signal:d.signal,deadlineMs:performance.now()+e.timeoutMs},f=setTimeout(()=>{this.incoming.has(e.id)&&(this.cancelIncoming(e.id),this.sendError(e.id,new n("deadline-exceeded")))},e.timeoutMs);this.incoming.set(e.id,{abort:d,timer:f,control:l}),Promise.resolve().then(()=>{if(d.signal.aborted||this.failure)throw new n("cancelled");if(this.handlers.get(t.id)!==c||!c.invoke)throw new n("receiver-unavailable");return c.invoke(i,a)}).then(u=>{if(!this.incoming.has(e.id)||this.failure)return;let s=A(this.generation,e.id,2),m=te(t.response,u,s,this.ledger);return this.output.send(m,!1,()=>{if(!(!this.incoming.has(e.id)||this.failure)){if(performance.now()>=a.deadlineMs){this.cancelIncoming(e.id),this.sendError(e.id,new n("deadline-exceeded"));return}return clearTimeout(f),this.incoming.delete(e.id),m}})}).catch(u=>{let s=w(u,"handler");s.code==="transport"?this.fail(s):this.incoming.has(e.id)&&!this.failure&&this.sendError(e.id,s,l)}).finally(()=>{clearTimeout(f),this.incoming.delete(e.id),this.handlerTasks--,o.release(),l.release()})}cancelIncoming(e){let t=this.incoming.get(e);t&&(this.incoming.delete(e),clearTimeout(t.timer),t.abort.abort(),t.control.release())}sendError(e,t,i){let o=A(this.generation,e,3);o.body={$case:"error",value:be(t)},this.sendControl(o,i)}sendControl(e,t){this.failure||this.output.send(L.encode(e).finish(),!0,void 0,void 0,t).catch(i=>this.fail(w(i)))}report(e){let t=i=>{typeof globalThis.reportError=="function"?globalThis.reportError(i):queueMicrotask(()=>{throw i})};if(this.options.onError)try{this.options.onError(e)}catch{t(new n("handler","onError callback failed."))}else t(e)}fail(e){if(!this.failure){this.failure=e;for(let t of this.pending.keys())this.settle(t,e);for(let t of this.incoming.keys())this.cancelIncoming(t);for(let t of this.callbacks.values())for(let i of t)i.active=!1,delete i.invoke;this.callbacks.clear();for(let t of this.handlers.values())delete t.invoke;this.handlers.clear(),this.callbackCount=0,this.output?.close(e),this.transport.close(),this.resolveClosed(e)}}};async function ie(r,e,t={}){let i=new J(r,e,t);return await i.start(),i}var ve=new WeakMap;function Be(r={}){let e=r.bootstrap??globalThis.window?.__webuiDesktopIpcV2,t=e?.documentNonce,i=r.fetch??globalThis.fetch,o=r.applicationUrl??globalThis.location?.href,c,l,d,a=!1,f=!1,u=!1,s,m=!1,p,g,R=new AbortController;function k(y){return o?new URL(y,o).href:y}function B(y=new n("closed")){if(!s){s=y,p?.(y),p=void 0,R.abort(),d?.close(),d=void 0;try{e?.documentNonce===t&&e?.disconnect(c?.generation??"0",c?.token??"")}catch{}c=void 0,l?.closed(y),l=void 0}}async function Z(y,I,x){let P=y.headers.get("Content-Length");if(P&&(!Number.isSafeInteger(Number(P))||Number(P)>I||Number(P)<0))throw await y.body?.cancel(),new n("payload-too-large");if(!y.body)return{bytes:new Uint8Array};let C=y.body.getReader(),b,v,T=0;try{let H=g.limits.maxErrorTextBytesTotal+128,Ee=Math.min(I,H,P?Math.max(1,Number(P)):H);for(b=new Uint8Array(Ee);;){let F=await C.read();if(F.done)break;if(T+F.value.byteLength>I)throw new n("payload-too-large");if(T+F.value.byteLength>b.byteLength){let V=Math.min(I,Math.max(b.byteLength*2,T+F.value.byteLength)),Te=v?g.reserve(b.byteLength):()=>{};try{x&&(v||V>H)&&(v?v.grow(V-b.byteLength):v=g.reserveInput(V));let se=new Uint8Array(V);se.set(b.subarray(0,T)),b=se}finally{Te()}}b.set(F.value,T),T+=F.value.byteLength}if(x){let F=q(b.subarray(0,T),g.limits);!v&&(F.kind===1||F.kind===4||F.kind===2)&&(v=g.reserveInput(b.byteLength))}}catch(H){throw v?.release(),await C.cancel().catch(()=>{}),H}finally{C.releaseLock()}return{bytes:b.subarray(0,T),...v?{credit:v}:{}}}async function D(y,I){if(s)throw s;let x=c;if(!x)throw new n("not-ready");let P={"X-WebUI-Ipc-Session":x.token};I&&(P["Content-Type"]="application/x-protobuf");let C={method:I?"POST":"GET",headers:P,cache:"no-store",credentials:"omit",mode:"same-origin",redirect:"error",signal:R.signal};I?C.body=I:C.keepalive=!0;let b=await i(k(y),C);if(s)throw s;if(b.status===204)return;if(!b.ok&&![400,401,409,413,429,503].includes(b.status))throw await b.body?.cancel(),new n("transport");if(b.ok&&(I||b.status!==200))throw await b.body?.cancel(),new n("transport");if(b.headers.get("Content-Type")?.split(";")[0]!=="application/x-protobuf")throw new n("transport");let v=await Z(b,b.ok?x.limits.maxFrameBytes:x.limits.maxErrorTextBytesTotal+128,b.ok);if(s)throw v.credit?.release(),s;if(!b.ok)try{throw z(pe.decode(v.bytes))}catch(T){throw w(T)}return v}async function E(){if(!(f||!c||s)){f=!0;try{do for(a=!1;!s;){let y=await D("/_webui/ipc/outbound");if(!y)break;if(l&&ee(l)&&y.credit)await l.receiveReserved(y.bytes,y.credit);else try{await l?.receive(y.bytes)}finally{y.credit?.release()}}while(a&&!s)}catch(y){B(s??w(y))}finally{f=!1,a&&!s&&E()}}}return{async start(y,I){if(u||s)throw s??new n("not-ready");u=!0,l=I;try{if(!e)throw new n("not-ready","Native IPC bootstrap is absent.");if(e.documentNonce!==t)throw new n("navigated");let x=X(y);d=e.subscribeControl(v=>{if(!s&&!(c&&v.generation!==c.generation)){if(v.kind==="closed"){B(new n(v.code));return}a=!0,c&&E()}});let P=new Promise((v,T)=>{p=T}),C=await Promise.race([e.hello(x).then(v=>(s&&e.documentNonce===t&&e.disconnect(v.generation,v.token),v)),P]);if(p=void 0,s)throw e.documentNonce===t&&e.disconnect(C.generation,C.token),s;c=C,Y(C.limits),g=ee(I)?I.byteLedger:new S(C.limits);let b=ve.get(e);return b&&g.shareWith(b),ve.set(e,g),g.limits=Object.freeze({...C.limits}),a&&E(),C}catch(x){throw B(w(x)),s}},async send(y){if(s)throw s;if(!c)throw new n("not-ready");if(y.byteLength>c.limits.maxFrameBytes)throw new n("payload-too-large");if(m)throw new n("overloaded");m=!0;try{await D("/_webui/ipc",y)}catch(I){let x=s??w(I);throw x.code!=="overloaded"&&x.code!=="payload-too-large"&&x.code!=="invalid-payload"&&B(x),x}finally{m=!1}},close:()=>B()}}async function De(r,e,t={}){let i=new Map;for(let a of e.methods){if(i.has(a.id)||a.kind==="rpc"&&!a.response)throw new n("invalid-payload");i.set(a.id,a)}let o=(a,f,u)=>{let s=i.get(a);if(!s||s.kind!==f||s.receiver!==u)throw new n("unknown-method");return s},c=new Set,l,d=await ie({...e.hello,methods:[...i.values()]},r,{...t.onError?{onError:t.onError}:{},setup(a){l=f=>{for(let p of f.keys())if(o(p,"rpc","renderer"),c.has(p))throw new n("invalid-payload","Duplicate renderer registration.");let u=[],s=[];for(let[p,g]of f)u.push(a.handle(o(p,"rpc","renderer"),g)),c.add(p),s.push(p);let m=!0;return{close(){if(m){m=!1;for(let p of u)p.close();for(let p of s)c.delete(p)}}}},t.handlers&&l(t.handlers)}});return{closed:d.closed,close:()=>d.close(),call:(a,f,u)=>d.call(o(a,"rpc","host"),f,u),notify:(a,f)=>d.notify(o(a,"notification","host"),f),subscribe:(a,f)=>d.subscribe(o(a,"notification","renderer"),f),register:l}}var Fe=new TextEncoder,gt=new TextDecoder("utf-8",{fatal:!0}),ne=class{bytes=[];finish(){return new Uint8Array(this.bytes)}bool(e,t){return this.varintField(e,t?1n:0n),this}uint32(e,t){return this.varintField(e,BigInt(t>>>0)),this}int32(e,t){return this.varintField(e,BigInt.asUintN(64,BigInt(t))),this}enum(e,t){return this.int32(e,t),this}uint64(e,t){return this.varintField(e,t),this}int64(e,t){return this.varintField(e,BigInt.asUintN(64,t)),this}sint32(e,t){return this.varintField(e,BigInt(t<<1^t>>31)&0xffffffffn),this}sint64(e,t){return this.varintField(e,BigInt.asUintN(64,t<<1n^t>>63n)),this}fixed32(e,t){return this.key(e,5),this.u32(t>>>0),this}sfixed32(e,t){return this.fixed32(e,t),this}fixed64(e,t){return this.key(e,1),this.u64(t),this}sfixed64(e,t){return this.fixed64(e,BigInt.asUintN(64,t)),this}float(e,t){this.key(e,5);let i=new Uint8Array(4);return new DataView(i.buffer).setFloat32(0,t,!0),this.raw(i),this}double(e,t){this.key(e,1);let i=new Uint8Array(8);return new DataView(i.buffer).setFloat64(0,t,!0),this.raw(i),this}string(e,t){return this.bytesField(e,Fe.encode(t)),this}bytesField(e,t){return this.key(e,2),this.varint(BigInt(t.byteLength)),this.raw(t),this}varintField(e,t){this.key(e,0),this.varint(t)}key(e,t){this.varint(BigInt(e)<<3n|BigInt(t))}varint(e){let t=BigInt.asUintN(64,e);for(;t>=0x80n;)this.bytes.push(Number(t&0x7fn)|128),t>>=7n;this.bytes.push(Number(t))}u32(e){this.bytes.push(e&255,e>>>8&255,e>>>16&255,e>>>24&255)}u64(e){let t=BigInt.asUintN(64,e);for(let i=0;i<8;i++)this.bytes.push(Number(t&0xffn)),t>>=8n}raw(e){for(let t=0;t<e.byteLength;t++)this.bytes.push(e[t])}},N=class{constructor(e){this.bytesView=e;this.len=e.byteLength}bytesView;len;pos=0;tag(){let e=this.uint64(),t=Number(e>>3n);if(t<=0||t>536870911)throw new n("invalid-payload");return[t,Number(e&7n)]}uint64(){Re(this);let e=0n,t=0n;for(;;){let i=this.readByte();if(e|=BigInt(i&127)<<t,i<128)return e;t+=7n}}fixed32(){return this.readFixed32()}sfixed32(){return this.readFixed32()|0}fixed64(){return this.readFixed64()}sfixed64(){return BigInt.asIntN(64,this.readFixed64())}float(){let t=this.view(4).getFloat32(0,!0);return this.pos+=4,t}double(){let t=this.view(8).getFloat64(0,!0);return this.pos+=8,t}bytes(){let e=j(this);if(e>this.len-this.pos)throw new n("invalid-payload");let t=this.pos;return this.pos+=e,this.bytesView.subarray(t,this.pos)}skip(e){if(e===0){this.uint64();return}if(e===1){if(this.pos+=8,this.pos>this.len)throw new n("invalid-payload");return}if(e===2){this.bytes();return}if(e===5){if(this.pos+=4,this.pos>this.len)throw new n("invalid-payload");return}throw new n("invalid-payload")}readByte(){let e=this.bytesView[this.pos];if(e===void 0)throw new n("invalid-payload");return this.pos++,e}view(e){if(e>this.len-this.pos)throw new n("invalid-payload");return new DataView(this.bytesView.buffer,this.bytesView.byteOffset+this.pos,e)}readFixed32(){let t=this.view(4).getUint32(0,!0);return this.pos+=4,t}readFixed64(){let t=this.view(8).getBigUint64(0,!0);return this.pos+=8,t}};function Re(r){for(let e=0;e<10;e++){let t=r.bytesView[r.pos+e];if(t===void 0||e===9&&t>1)throw new n("invalid-payload");if(t<128)return}throw new n("invalid-payload")}function O(r){return BigInt(r.uint64())}function j(r){let e=O(r);if(e>0xffffffffn)throw new n("invalid-payload");return Number(e)}function U(r){let e=r.pos;if(j(r)>r.len-r.pos)throw new n("invalid-payload");return r.pos=e,r.bytes()}function oe(r,e){if(e===0){O(r);return}if(e===2){U(r);return}if(e!==1&&e!==5)throw new n("invalid-payload");r.skip(e)}var we=new Set(["int64","sint64","sfixed64"]),Le=new Set(["uint64","fixed64"]),ge=new Set(["int32","sint32","sfixed32","enum"]),Me=new Set(["uint32","fixed32"]),Ue=new Set(["fixed32","sfixed32","float"]),Ae=new Set(["fixed64","sfixed64","double"]),xe=new TextEncoder,Se=new TextDecoder("utf-8",{fatal:!0});function h(){throw new n("invalid-payload")}function Q(r,e){let t=e===void 0?void 0:r[e];return t||h()}function ke(r,e){if(we.has(e)||Le.has(e)){typeof r!="bigint"&&h();let t=we.has(e);(r<(t?-0x8000000000000000n:0n)||r>(t?0x7fffffffffffffffn:0xffffffffffffffffn))&&h()}else if(ge.has(e)||Me.has(e)){(typeof r!="number"||!Number.isInteger(r))&&h();let t=ge.has(e);(r<(t?-2147483648:0)||r>(t?2147483647:4294967295))&&h()}else e==="double"||e==="float"?typeof r!="number"&&h():e==="bytes"?r instanceof Uint8Array||h():e==="bool"?typeof r!="boolean"&&h():e==="string"?typeof r!="string"&&h():h()}function Ne(r,e,t,i){let o=[{value:r,shape:Q(t,e),depth:1}],c=0,l=0,d=(a,f,u)=>{if(f.kind==="message")u>=i.maxSchemaDepth&&h(),o.push({value:a,shape:Q(t,f.message),depth:u+1});else{if(ke(a,f.kind),typeof a=="string"){if(a.length>i.maxFrameBytes)throw new n("payload-too-large");l+=xe.encode(a).byteLength}else a instanceof Uint8Array&&(l+=a.byteLength);if(l>i.maxFrameBytes)throw new n("payload-too-large")}};for(;o.length;){let a=o.pop();(!a.value||typeof a.value!="object"||Array.isArray(a.value))&&h();let f=a.value,u=new Set;for(let s of a.shape.fields){let m=f[s.name];if(s.oneof){f[s.name]!==void 0&&h();let p=f[s.oneof];if(p===void 0||((typeof p!="object"||p===null)&&h(),a.shape.fields.some(g=>g.oneof===s.oneof&&g.name===p.$case)||h(),p.$case!==s.name))continue;(u.has(s.oneof)||f[s.name]!==void 0)&&h(),u.add(s.oneof),m=p.value}else if(m===void 0&&s.optional)continue;if(s.map){m instanceof Map||h(),a.depth>=i.maxSchemaDepth&&h(),c+m.size>i.maxCollectionEntriesPerMessage&&h(),c+=m.size;let p=Q(t,s.message),g=p.fields.find(k=>k.mapKey||k.number===1),R=p.fields.find(k=>k.number===2);(!g||!R)&&h();for(let[k,B]of m){if(ke(k,g.kind),typeof k=="string"){if(k.length>i.maxFrameBytes)throw new n("payload-too-large");if(l+=xe.encode(k).byteLength,l>i.maxFrameBytes)throw new n("payload-too-large")}d(B,R,a.depth+1)}}else if(s.repeated){Array.isArray(m)||h(),c+m.length>i.maxCollectionEntriesPerMessage&&h(),c+=m.length;for(let p of m)d(p,s,a.depth)}else d(m,s,a.depth)}}}function Ie(r){return Ae.has(r)?1:Ue.has(r)?5:r==="string"||r==="bytes"||r==="message"?2:0}function Ce(r,e){switch(e.kind){case"string":Se.decode(U(r));return;case"bytes":U(r);return;case"bool":{let t=j(r);t!==0&&t!==1&&h();return}case"int64":case"uint64":case"sint64":O(r);return;case"fixed64":r.fixed64();return;case"sfixed64":r.sfixed64();return;case"int32":case"enum":{let t=O(r);t>0x7fffffffn&&t<0xffffffff80000000n&&h();return}case"uint32":case"sint32":j(r);return;case"fixed32":r.fixed32();return;case"sfixed32":r.sfixed32();return;case"float":r.float();return;case"double":r.double();return;default:h()}}function Oe(r,e,t,i){if(r.byteLength>i.maxFrameBytes)throw new n("payload-too-large");let o=[{bytes:r,shape:Q(t,e),depth:1}],c=0;try{for(;o.length;){let l=o.pop(),d=new N(l.bytes),a=new Set;for(;d.pos<d.len;){let[f,u]=d.tag();(u===3||u===4)&&h();let s=l.shape.fields.find(m=>m.number===f);if(!s){oe(d,u);continue}if(s.oneof&&(a.has(s.oneof)&&h(),a.add(s.oneof)),s.kind==="message")s.repeated&&++c>i.maxCollectionEntriesPerMessage&&h(),(u!==2||l.depth>=i.maxSchemaDepth)&&h(),o.push({bytes:U(d),shape:Q(t,s.message),depth:l.depth+1});else if(u===2&&s.repeated&&s.packed===!0&&Ie(s.kind)!==2){let m=new N(U(d));for(;m.pos<m.len;)++c>i.maxCollectionEntriesPerMessage&&h(),Ce(m,s)}else s.repeated&&++c>i.maxCollectionEntriesPerMessage&&h(),u!==Ie(s.kind)&&h(),Ce(d,s)}}}catch(l){if(l instanceof n)throw l;h()}}export{N as BoundaryReader,J as Connection,n as IpcError,ne as PayloadWriter,De as connect,ie as createConnection,Be as createDesktopTransport,M as defaultLimits,U as readDelimited,j as readUint32,O as readUint64,oe as skipField,Oe as validateMessage,Ne as validateValue};