bunite-core 0.9.0 → 0.10.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/package.json +1 -1
- package/src/host/core/App.ts +1 -1
- package/src/host/core/BrowserView.ts +18 -12
- package/src/host/core/BrowserWindow.ts +12 -11
- package/src/host/serveWeb.ts +33 -9
- package/src/preload/runtime.built.js +1 -1
- package/src/preload/runtime.ts +8 -10
- package/src/rpc/error.ts +25 -15
- package/src/rpc/framework.ts +12 -12
- package/src/rpc/index.ts +13 -4
- package/src/rpc/peer.ts +542 -159
- package/src/rpc/renderer.ts +16 -18
- package/src/rpc/schema.ts +30 -47
- package/src/rpc/wire.ts +18 -4
- package/src/rpc/hash.ts +0 -142
package/package.json
CHANGED
package/src/host/core/App.ts
CHANGED
|
@@ -162,7 +162,7 @@ export class AppRuntime {
|
|
|
162
162
|
|
|
163
163
|
createViewRuntime(viewId: number): ImplOf<typeof RuntimeCap> {
|
|
164
164
|
const notImpl = (name: string) => {
|
|
165
|
-
throw new IpcError({ code: "
|
|
165
|
+
throw new IpcError({ code: "not_found", message: `Runtime.${name}` });
|
|
166
166
|
};
|
|
167
167
|
const impl = {
|
|
168
168
|
window: () => notImpl("window"),
|
|
@@ -7,8 +7,6 @@ import {
|
|
|
7
7
|
createFrameTransport,
|
|
8
8
|
type Connection,
|
|
9
9
|
type BytesPipe,
|
|
10
|
-
type SchemaShape,
|
|
11
|
-
type ServerDescriptor,
|
|
12
10
|
} from "../../rpc/index";
|
|
13
11
|
import { createEncryptedPipe } from "../encryptedPipe";
|
|
14
12
|
import { ensureNativeRuntime, getNativeLibrary, toCString, waitForViewReady, cancelWaitForViewReady } from "../native";
|
|
@@ -18,10 +16,10 @@ import { randomBytes } from "node:crypto";
|
|
|
18
16
|
import { resolveDefaultAppResRoot } from "../paths";
|
|
19
17
|
import { removeSurfacesForHostView } from "./SurfaceRegistry";
|
|
20
18
|
|
|
21
|
-
const BrowserViewMap: Record<number, BrowserView
|
|
19
|
+
const BrowserViewMap: Record<number, BrowserView> = {};
|
|
22
20
|
let nextWebviewId = 1;
|
|
23
21
|
|
|
24
|
-
export type BrowserViewOptions
|
|
22
|
+
export type BrowserViewOptions = {
|
|
25
23
|
url: string | null;
|
|
26
24
|
html: string | null;
|
|
27
25
|
preload: string | null;
|
|
@@ -34,7 +32,8 @@ export type BrowserViewOptions<S extends SchemaShape = SchemaShape> = {
|
|
|
34
32
|
width: number;
|
|
35
33
|
height: number;
|
|
36
34
|
};
|
|
37
|
-
serve
|
|
35
|
+
/** Setup callback fired when a renderer connection attaches. Use `conn.serve(cap, impl)` or `conn.serveAll(schema, impls)`. */
|
|
36
|
+
serve?: (conn: Connection) => void;
|
|
38
37
|
windowId: number;
|
|
39
38
|
autoResize: boolean;
|
|
40
39
|
navigationRules: string[] | null;
|
|
@@ -55,7 +54,7 @@ const defaultOptions: BrowserViewOptions = {
|
|
|
55
54
|
sandbox: false
|
|
56
55
|
};
|
|
57
56
|
|
|
58
|
-
export class BrowserView
|
|
57
|
+
export class BrowserView {
|
|
59
58
|
id = nextWebviewId++;
|
|
60
59
|
private nativeAttached = false;
|
|
61
60
|
private _readyPromise: Promise<void>;
|
|
@@ -67,7 +66,7 @@ export class BrowserView<S extends SchemaShape = SchemaShape> {
|
|
|
67
66
|
preloadOrigins?: string[];
|
|
68
67
|
partition: string | null;
|
|
69
68
|
frame: BrowserViewOptions["frame"];
|
|
70
|
-
readonly
|
|
69
|
+
readonly serveSetup?: (conn: Connection) => void;
|
|
71
70
|
private connection: Connection | null = null;
|
|
72
71
|
private connectionGeneration = 0;
|
|
73
72
|
autoResize: boolean;
|
|
@@ -75,7 +74,7 @@ export class BrowserView<S extends SchemaShape = SchemaShape> {
|
|
|
75
74
|
sandbox: boolean;
|
|
76
75
|
secretKey: Uint8Array;
|
|
77
76
|
|
|
78
|
-
constructor(options: Partial<BrowserViewOptions
|
|
77
|
+
constructor(options: Partial<BrowserViewOptions>) {
|
|
79
78
|
ensureNativeRuntime();
|
|
80
79
|
|
|
81
80
|
this.windowId = options.windowId ?? defaultOptions.windowId;
|
|
@@ -86,7 +85,7 @@ export class BrowserView<S extends SchemaShape = SchemaShape> {
|
|
|
86
85
|
this.preloadOrigins = options.preloadOrigins ?? defaultOptions.preloadOrigins;
|
|
87
86
|
this.partition = options.partition ?? defaultOptions.partition;
|
|
88
87
|
this.frame = options.frame ?? defaultOptions.frame;
|
|
89
|
-
this.
|
|
88
|
+
this.serveSetup = options.serve;
|
|
90
89
|
this.autoResize = options.autoResize ?? defaultOptions.autoResize;
|
|
91
90
|
this.navigationRules = options.navigationRules ?? defaultOptions.navigationRules;
|
|
92
91
|
this.sandbox = options.sandbox ?? defaultOptions.sandbox;
|
|
@@ -174,10 +173,17 @@ export class BrowserView<S extends SchemaShape = SchemaShape> {
|
|
|
174
173
|
mode: "native",
|
|
175
174
|
origin: "appres://app.internal",
|
|
176
175
|
runtime,
|
|
176
|
+
attestation: {
|
|
177
|
+
origin: "appres://app.internal",
|
|
178
|
+
topOrigin: "appres://app.internal",
|
|
179
|
+
partition: this.partition ?? "default",
|
|
180
|
+
isAppRes: true,
|
|
181
|
+
isMainFrame: true,
|
|
182
|
+
userGesture: false,
|
|
183
|
+
level: "app-internal",
|
|
184
|
+
},
|
|
177
185
|
});
|
|
178
|
-
|
|
179
|
-
this.connection.serve(this.serveDescriptor);
|
|
180
|
-
}
|
|
186
|
+
this.serveSetup?.(this.connection);
|
|
181
187
|
}
|
|
182
188
|
|
|
183
189
|
detachNewConnection(): void {
|
|
@@ -3,11 +3,11 @@ import { BuniteEvent } from "../events/event";
|
|
|
3
3
|
import { buniteEventEmitter } from "../events/eventEmitter";
|
|
4
4
|
import { ensureNativeRuntime, getNativeLibrary, toCString } from "../native";
|
|
5
5
|
import { BrowserView } from "./BrowserView";
|
|
6
|
-
import type {
|
|
6
|
+
import type { Connection } from "../../rpc/index";
|
|
7
7
|
import { getNextWindowId } from "./windowIds";
|
|
8
8
|
import { getBaseDir, resolveDefaultAppResRoot } from "../paths";
|
|
9
9
|
|
|
10
|
-
export type WindowOptionsType
|
|
10
|
+
export type WindowOptionsType = {
|
|
11
11
|
title: string;
|
|
12
12
|
frame: {
|
|
13
13
|
x: number;
|
|
@@ -22,7 +22,8 @@ export type WindowOptionsType<S extends SchemaShape = SchemaShape> = {
|
|
|
22
22
|
preload: string | null;
|
|
23
23
|
appresRoot: string | null;
|
|
24
24
|
preloadOrigins?: string[];
|
|
25
|
-
|
|
25
|
+
/** Setup callback fired when the window's renderer connection attaches. */
|
|
26
|
+
serve?: (conn: Connection) => void;
|
|
26
27
|
titleBarStyle: "hidden" | "hiddenInset" | "default";
|
|
27
28
|
transparent: boolean;
|
|
28
29
|
hidden?: boolean;
|
|
@@ -50,7 +51,7 @@ const defaultOptions: WindowOptionsType = {
|
|
|
50
51
|
sandbox: false
|
|
51
52
|
};
|
|
52
53
|
|
|
53
|
-
const BrowserWindowMap: Record<number, BrowserWindow
|
|
54
|
+
const BrowserWindowMap: Record<number, BrowserWindow> = {};
|
|
54
55
|
|
|
55
56
|
let lastFocusedWindowId: number | null = null;
|
|
56
57
|
|
|
@@ -58,7 +59,7 @@ export function getLastFocusedWindowId(): number | null {
|
|
|
58
59
|
return lastFocusedWindowId;
|
|
59
60
|
}
|
|
60
61
|
|
|
61
|
-
export class BrowserWindow
|
|
62
|
+
export class BrowserWindow {
|
|
62
63
|
id = getNextWindowId();
|
|
63
64
|
private nativeAttached = false;
|
|
64
65
|
title: string;
|
|
@@ -127,7 +128,7 @@ export class BrowserWindow<S extends SchemaShape = SchemaShape> {
|
|
|
127
128
|
buniteEventEmitter.removeAllListeners(`close-requested-${this.id}`);
|
|
128
129
|
};
|
|
129
130
|
|
|
130
|
-
constructor(options: Partial<WindowOptionsType
|
|
131
|
+
constructor(options: Partial<WindowOptionsType> = {}) {
|
|
131
132
|
ensureNativeRuntime();
|
|
132
133
|
|
|
133
134
|
this.title = options.title ?? defaultOptions.title;
|
|
@@ -181,7 +182,7 @@ export class BrowserWindow<S extends SchemaShape = SchemaShape> {
|
|
|
181
182
|
buniteEventEmitter.on(`resize-${this.id}`, this.handleNativeResize);
|
|
182
183
|
buniteEventEmitter.on(`close-${this.id}`, this.handleNativeClose);
|
|
183
184
|
|
|
184
|
-
const webview = new BrowserView
|
|
185
|
+
const webview = new BrowserView({
|
|
185
186
|
url: this.url,
|
|
186
187
|
html: this.html,
|
|
187
188
|
preload: this.preload,
|
|
@@ -202,10 +203,10 @@ export class BrowserWindow<S extends SchemaShape = SchemaShape> {
|
|
|
202
203
|
this.webviewId = webview.id;
|
|
203
204
|
}
|
|
204
205
|
|
|
205
|
-
get view(): BrowserView
|
|
206
|
+
get view(): BrowserView {
|
|
206
207
|
const view = BrowserView.getById(this.webviewId);
|
|
207
208
|
if (!view) throw new Error(`BrowserWindow ${this.id} has no attached view`);
|
|
208
|
-
return view as BrowserView
|
|
209
|
+
return view as BrowserView;
|
|
209
210
|
}
|
|
210
211
|
|
|
211
212
|
static getById(id: number) {
|
|
@@ -216,8 +217,8 @@ export class BrowserWindow<S extends SchemaShape = SchemaShape> {
|
|
|
216
217
|
return Object.values(BrowserWindowMap);
|
|
217
218
|
}
|
|
218
219
|
|
|
219
|
-
get webview(): BrowserView
|
|
220
|
-
return BrowserView.getById(this.webviewId) as BrowserView
|
|
220
|
+
get webview(): BrowserView | undefined {
|
|
221
|
+
return BrowserView.getById(this.webviewId) as BrowserView | undefined;
|
|
221
222
|
}
|
|
222
223
|
|
|
223
224
|
show() {
|
package/src/host/serveWeb.ts
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import type { Server, ServerWebSocket, WebSocketHandler } from "bun";
|
|
2
2
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
3
3
|
import type { BytesPipe } from "../rpc/transport";
|
|
4
|
+
import type { Connection } from "../rpc/peer";
|
|
4
5
|
import { createConnection, _setCallContextStorage } from "../rpc/peer";
|
|
5
6
|
import { createFrameTransport } from "../rpc/transport";
|
|
6
|
-
import type { SchemaShape, ServerDescriptor } from "../rpc/schema";
|
|
7
7
|
import { DEFAULT_MAX_BYTES } from "../rpc/wire";
|
|
8
8
|
|
|
9
9
|
_setCallContextStorage(new AsyncLocalStorage<{ callId: number }>());
|
|
@@ -50,31 +50,55 @@ export function createBunWebSocketServerHandler<TData extends object>(
|
|
|
50
50
|
|
|
51
51
|
const DEFAULT_RPC_PATH = "/rpc";
|
|
52
52
|
|
|
53
|
+
export interface WsData {
|
|
54
|
+
origin: string;
|
|
55
|
+
}
|
|
56
|
+
|
|
53
57
|
export interface WebRpcMount {
|
|
54
58
|
fetch(req: Request, srv: Server<object>): Response | undefined;
|
|
55
59
|
websocket: WebSocketHandler<object> & { maxPayloadLength: number };
|
|
56
60
|
}
|
|
57
61
|
|
|
58
|
-
export
|
|
59
|
-
|
|
60
|
-
|
|
62
|
+
export interface ServeWebOptions<TData extends WsData = WsData> {
|
|
63
|
+
path?: string;
|
|
64
|
+
/** Enrichment hook fired at upgrade — return extra fields (e.g. auth-derived userId, perms) that the setup callback receives. */
|
|
65
|
+
onUpgrade?: (req: Request) => Omit<TData, keyof WsData> | undefined;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Mount a WebSocket RPC endpoint on `Bun.serve`. `setup(conn, wsData)` runs once per client connection. */
|
|
69
|
+
export function serveWeb<TData extends WsData = WsData>(
|
|
70
|
+
setup: (conn: Connection, wsData: TData) => void,
|
|
71
|
+
opts: ServeWebOptions<TData> = {}
|
|
61
72
|
): WebRpcMount {
|
|
62
73
|
const path = opts.path ?? DEFAULT_RPC_PATH;
|
|
63
74
|
return {
|
|
64
75
|
fetch(req, srv) {
|
|
65
76
|
if (new URL(req.url).pathname !== path) return undefined;
|
|
66
|
-
const
|
|
77
|
+
const enriched = opts.onUpgrade?.(req) ?? ({} as Omit<TData, keyof WsData>);
|
|
78
|
+
const data = { origin: req.headers.get("origin") ?? "", ...enriched } as TData;
|
|
79
|
+
const upgraded = srv.upgrade(req, { data });
|
|
67
80
|
return upgraded ? undefined : new Response("WebSocket upgrade failed", { status: 400 });
|
|
68
81
|
},
|
|
69
82
|
websocket: {
|
|
70
|
-
...createBunWebSocketServerHandler<
|
|
83
|
+
...createBunWebSocketServerHandler<TData>((ws, pipe) => {
|
|
84
|
+
const wsData = ws.data;
|
|
85
|
+
const origin = wsData?.origin ?? "";
|
|
71
86
|
const conn = createConnection({
|
|
72
87
|
transport: createFrameTransport(pipe),
|
|
73
88
|
mode: "web",
|
|
74
|
-
origin: "web-client",
|
|
89
|
+
origin: origin || "web-client",
|
|
90
|
+
attestation: {
|
|
91
|
+
origin,
|
|
92
|
+
topOrigin: origin,
|
|
93
|
+
partition: "default",
|
|
94
|
+
isAppRes: false,
|
|
95
|
+
isMainFrame: true,
|
|
96
|
+
userGesture: false,
|
|
97
|
+
level: "untrusted",
|
|
98
|
+
},
|
|
75
99
|
});
|
|
76
|
-
conn
|
|
77
|
-
}),
|
|
100
|
+
setup(conn, wsData);
|
|
101
|
+
}) as unknown as WebRpcMount["websocket"],
|
|
78
102
|
maxPayloadLength: DEFAULT_MAX_BYTES,
|
|
79
103
|
},
|
|
80
104
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var On=Symbol("CallDef"),Pn=Symbol("StreamDef"),Ep=Symbol("CapDef"),Hn=Symbol("CapRefToken"),Nn=Symbol("CapArrayToken"),vn=Symbol("CapRecordToken"),dm=Symbol("Schema");function Qe(e){return{[Hn]:!0,cap:e}}Qe.array=(e)=>({[Nn]:!0,cap:e});Qe.record=(e)=>({[vn]:!0,cap:e});var k=Qe;function re(e){return typeof e==="object"&&e!==null&&e[Hn]===!0}function le(e){return typeof e==="object"&&e!==null&&e[Nn]===!0}function de(e){return typeof e==="object"&&e!==null&&e[vn]===!0}function ye(e){return typeof e==="object"&&e!==null&&e[On]===!0}function Re(e){return typeof e==="object"&&e!==null&&e[Pn]===!0}function b(e){return{[On]:!0,idempotent:!!e?.idempotent,returns:e?.returns}}function Ie(e){return{[Pn]:!0,hint:e?.hint}}function W(e,n){return{[Ep]:!0,methods:e,disposal:n?.disposal??void 0}}var Ip=()=>{throw Error("schema.topologyHash bound after hash.ts import")};function Kn(e){Ip=e}function Gn(e){let n=new Map,p=[];for(let C of e.caps){if(n.has(C))continue;n.set(C,p.length),p.push(null)}let m=(C)=>{let r=n.get(C);if(r!==void 0)return r;let y=p.length;return n.set(C,y),p.push(null),y};for(let C=0;C<p.length;C++){if(p[C]!==null)continue;let r=e.caps[C];p[C]=Yn(r,m)}let o=Object.keys(e.roots).map((C)=>({name:C,capIndex:m(e.roots[C])}));for(let C=0;C<p.length;C++){if(p[C]!==null)continue;let r=[...n.keys()][C];p[C]=Yn(r,m)}return{v:1,roots:o,caps:p}}function Yn(e,n){let m={methods:Object.keys(e.methods).map((C)=>{let r=e.methods[C];if(ye(r))return{name:C,kind:"call",idempotent:r.idempotent,returns:Fp(r.returns,n)};if(Re(r))return{name:C,kind:"stream"};throw Error(`Unknown method def for "${C}"`)})},o=e.disposal;if(o)m.disposal={method:o.method,async:!!o.async};return m}function Fp(e,n){if(!e)return{kind:"type"};if(re(e))return{kind:"cap",capIndex:n(e.cap)};if(le(e))return{kind:"capArray",capIndex:n(e.cap)};if(de(e))return{kind:"capRecord",capIndex:n(e.cap)};return{kind:"type"}}function Ze(e){if(Array.isArray(e))return"["+e.map(Ze).join(",")+"]";if(e&&typeof e==="object")return"{"+Object.keys(e).sort().map((p)=>JSON.stringify(p)+":"+Ze(e[p])).join(",")+"}";return JSON.stringify(e)}async function Xn(e){let n=Gn(e),p=Ze(n),m=new TextEncoder().encode(p),o=await crypto.subtle.digest("SHA-256",m);return Mp(new Uint8Array(o))}function Mp(e){let n="";for(let p=0;p<e.length;p++)n+=e[p].toString(16).padStart(2,"0");return n}Kn(Xn);var We;try{We=new TextDecoder}catch(e){}var _,S,a=0;var jn=[],qe=jn,Se=0,H={},F,pe,q=0,z=0,U,g,L=[],E,$n={useRecords:!1,mapsAsObjects:!0};class Oe{}var Be=new Oe;Be.name="MessagePack 0xC1";var me=!1,Un=2,Ln,Qn,Zn;class V{constructor(e){if(e){if(e.useRecords===!1&&e.mapsAsObjects===void 0)e.mapsAsObjects=!0;if(e.sequential&&e.trusted!==!1){if(e.trusted=!0,!e.structures&&e.useRecords!=!1){if(e.structures=[],!e.maxSharedStructures)e.maxSharedStructures=0}}if(e.structures)e.structures.sharedLength=e.structures.length;else if(e.getStructures)(e.structures=[]).uninitialized=!0,e.structures.sharedLength=0;if(e.int64AsNumber)e.int64AsType="number"}Object.assign(this,e)}unpack(e,n){if(_)return pp(()=>{return Me(),this?this.unpack(e,n):V.prototype.unpack.call($n,e,n)});if(!e.buffer&&e.constructor===ArrayBuffer)e=typeof Buffer<"u"?Buffer.from(e):new Uint8Array(e);if(typeof n==="object")S=n.end||e.length,a=n.start||0;else a=0,S=n>-1?n:e.length;Se=0,z=0,pe=null,qe=jn,U=null,_=e;try{E=e.dataView||(e.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength))}catch(p){if(_=null,e instanceof Uint8Array)throw p;throw Error("Source must be a Uint8Array or Buffer but was a "+(e&&typeof e=="object"?e.constructor.name:typeof e))}if(this instanceof V){if(H=this,this.structures)return F=this.structures,Fe(n);else if(!F||F.length>0)F=[]}else if(H=$n,!F||F.length>0)F=[];return Fe(n)}unpackMultiple(e,n){let p,m=0;try{me=!0;let o=e.length,C=this?this.unpack(e,o):He.unpack(e,o);if(n){if(n(C,m,a)===!1)return;while(a<o)if(m=a,n(Fe(),m,a)===!1)return}else{p=[C];while(a<o)m=a,p.push(Fe());return p}}catch(o){throw o.lastPosition=m,o.values=p,o}finally{me=!1,Me()}}_mergeStructures(e,n){if(Qn)e=Qn.call(this,e);if(e=e||[],Object.isFrozen(e))e=e.map((p)=>p.slice(0));for(let p=0,m=e.length;p<m;p++){let o=e[p];if(o){if(o.isShared=!0,p>=32)o.highByte=p-32>>5}}e.sharedLength=e.length;for(let p in n||[])if(p>=0){let m=e[p],o=n[p];if(o){if(m)(e.restoreStructures||(e.restoreStructures=[]))[p]=m;e[p]=o}}return this.structures=e}decode(e,n){return this.unpack(e,n)}}function Fe(e){try{if(!H.trusted&&!me){let p=F.sharedLength||0;if(p<F.length)F.length=p}let n;if(H.randomAccessStructure&&_[a]<64&&_[a]>=32&&Ln){if(n=Ln(_,a,S,H),_=null,!(e&&e.lazy)&&n)n=n.toJSON();a=S}else n=X();if(U)a=U.postBundlePosition,U=null;if(me)F.restoreStructures=null;if(a==S){if(F&&F.restoreStructures)kn();if(F=null,_=null,g)g=null}else if(a>S)throw Error("Unexpected end of MessagePack data");else if(!me){let p;try{p=JSON.stringify(n,(m,o)=>typeof o==="bigint"?`${o}n`:o).slice(0,100)}catch(m){p="(JSON view not available "+m+")"}throw Error("Data read, but end of buffer not reached "+p)}return n}catch(n){if(F&&F.restoreStructures)kn();if(Me(),n instanceof RangeError||n.message.startsWith("Unexpected end of buffer")||a>S)n.incomplete=!0;throw n}}function kn(){for(let e in F.restoreStructures)F[e]=F.restoreStructures[e];F.restoreStructures=null}function X(){let e=_[a++];if(e<160)if(e<128)if(e<64)return e;else{let n=F[e&63]||H.getStructures&&un()[e&63];if(n){if(!n.read)n.read=ze(n,e&63);return n.read()}else return e}else if(e<144)if(e-=128,H.mapsAsObjects){let n={};for(let p=0;p<e;p++){let m=ep();if(m==="__proto__")m="__proto_";n[m]=X()}return n}else{let n=new Map;for(let p=0;p<e;p++)n.set(X(),X());return n}else{e-=144;let n=Array(e);for(let p=0;p<e;p++)n[p]=X();if(H.freezeData)return Object.freeze(n);return n}else if(e<192){let n=e-160;if(z>=a)return pe.slice(a-q,(a+=n)-q);if(z==0&&S<140){let p=n<16?Ve(n):gn(n);if(p!=null)return p}return Je(n)}else{let n;switch(e){case 192:return null;case 193:if(U)if(n=X(),n>0)return U[1].slice(U.position1,U.position1+=n);else return U[0].slice(U.position0,U.position0-=n);return Be;case 194:return!1;case 195:return!0;case 196:if(n=_[a++],n===void 0)throw Error("Unexpected end of buffer");return ke(n);case 197:return n=E.getUint16(a),a+=2,ke(n);case 198:return n=E.getUint32(a),a+=4,ke(n);case 199:return ae(_[a++]);case 200:return n=E.getUint16(a),a+=2,ae(n);case 201:return n=E.getUint32(a),a+=4,ae(n);case 202:if(n=E.getFloat32(a),H.useFloat32>2){let p=Pe[(_[a]&127)<<1|_[a+1]>>7];return a+=4,(p*n+(n>0?0.5:-0.5)>>0)/p}return a+=4,n;case 203:return n=E.getFloat64(a),a+=8,n;case 204:return _[a++];case 205:return n=E.getUint16(a),a+=2,n;case 206:return n=E.getUint32(a),a+=4,n;case 207:if(H.int64AsType==="number")n=E.getUint32(a)*4294967296,n+=E.getUint32(a+4);else if(H.int64AsType==="string")n=E.getBigUint64(a).toString();else if(H.int64AsType==="auto"){if(n=E.getBigUint64(a),n<=BigInt(2)<<BigInt(52))n=Number(n)}else n=E.getBigUint64(a);return a+=8,n;case 208:return E.getInt8(a++);case 209:return n=E.getInt16(a),a+=2,n;case 210:return n=E.getInt32(a),a+=4,n;case 211:if(H.int64AsType==="number")n=E.getInt32(a)*4294967296,n+=E.getUint32(a+4);else if(H.int64AsType==="string")n=E.getBigInt64(a).toString();else if(H.int64AsType==="auto"){if(n=E.getBigInt64(a),n>=BigInt(-2)<<BigInt(52)&&n<=BigInt(2)<<BigInt(52))n=Number(n)}else n=E.getBigInt64(a);return a+=8,n;case 212:if(n=_[a++],n==114)return zn(_[a++]&63);else{let p=L[n];if(p)if(p.read)return a++,p.read(X());else if(p.noBuffer)return a++,p();else return p(_.subarray(a,++a));else throw Error("Unknown extension "+n)}case 213:if(n=_[a],n==114)return a++,zn(_[a++]&63,_[a++]);else return ae(2);case 214:return ae(4);case 215:return ae(8);case 216:return ae(16);case 217:if(n=_[a++],z>=a)return pe.slice(a-q,(a+=n)-q);return Pp(n);case 218:if(n=E.getUint16(a),a+=2,z>=a)return pe.slice(a-q,(a+=n)-q);return Hp(n);case 219:if(n=E.getUint32(a),a+=4,z>=a)return pe.slice(a-q,(a+=n)-q);return ip(n);case 220:return n=E.getUint16(a),a+=2,qn(n);case 221:return n=E.getUint32(a),a+=4,qn(n);case 222:return n=E.getUint16(a),a+=2,Sn(n);case 223:return n=E.getUint32(a),a+=4,Sn(n);default:if(e>=224)return e-256;if(e===void 0){let p=Error("Unexpected end of MessagePack data");throw p.incomplete=!0,p}throw Error("Unknown MessagePack token "+e)}}}var Op=/^[a-zA-Z_$][a-zA-Z\d_$]*$/;function ze(e,n){function p(){if(p.count++>Un){let o;try{o=e.read=Function("r","return function(){return "+(H.freezeData?"Object.freeze":"")+"({"+e.map((C)=>C==="__proto__"?"__proto_:r()":Op.test(C)?C+":r()":"["+JSON.stringify(C)+"]:r()").join(",")+"})}")(X)}catch(C){return Un=1/0,p()}if(e.highByte===0)e.read=Wn(n,e.read);return o()}let m={};for(let o=0,C=e.length;o<C;o++){let r=e[o];if(r==="__proto__")r="__proto_";m[r]=X()}if(H.freezeData)return Object.freeze(m);return m}if(p.count=0,e.highByte===0)return Wn(n,p);return p}var Wn=(e,n)=>{return function(){let p=_[a++];if(p===0)return n();let m=e<32?-(e+(p<<5)):e+(p<<5),o=F[m]||un()[m];if(!o)throw Error("Record id is not defined for "+m);if(!o.read)o.read=ze(o,e);return o.read()}};function un(){let e=pp(()=>{return _=null,H.getStructures()});return F=H._mergeStructures(e,F)}var Je=Te,Pp=Te,Hp=Te,ip=Te;function Te(e){let n;if(e<16){if(n=Ve(e))return n}if(e>64&&We)return We.decode(_.subarray(a,a+=e));let p=a+e,m=[];n="";while(a<p){let o=_[a++];if((o&128)===0)m.push(o);else if((o&224)===192){let C=_[a++]&63,r=(o&31)<<6|C;if(r<128)m.push(65533);else m.push(r)}else if((o&240)===224){let C=_[a++]&63,r=_[a++]&63,y=(o&31)<<12|C<<6|r;if(y<2048||y>=55296&&y<=57343)m.push(65533);else m.push(y)}else if((o&248)===240){let C=_[a++]&63,r=_[a++]&63,y=_[a++]&63,D=(o&7)<<18|C<<12|r<<6|y;if(D<65536||D>1114111)m.push(65533);else if(D>65535)D-=65536,m.push(D>>>10&1023|55296),D=56320|D&1023,m.push(D);else m.push(D)}else m.push(65533);if(m.length>=4096)n+=$.apply(String,m),m.length=0}if(m.length>0)n+=$.apply(String,m);return n}function qn(e){let n=Array(e);for(let p=0;p<e;p++)n[p]=X();if(H.freezeData)return Object.freeze(n);return n}function Sn(e){if(H.mapsAsObjects){let n={};for(let p=0;p<e;p++){let m=ep();if(m==="__proto__")m="__proto_";n[m]=X()}return n}else{let n=new Map;for(let p=0;p<e;p++)n.set(X(),X());return n}}var $=String.fromCharCode;function gn(e){let n=a,p=Array(e);for(let m=0;m<e;m++){let o=_[a++];if((o&128)>0){a=n;return}p[m]=o}return $.apply(String,p)}function Ve(e){if(e<4)if(e<2)if(e===0)return"";else{let n=_[a++];if((n&128)>1){a-=1;return}return $(n)}else{let n=_[a++],p=_[a++];if((n&128)>0||(p&128)>0){a-=2;return}if(e<3)return $(n,p);let m=_[a++];if((m&128)>0){a-=3;return}return $(n,p,m)}else{let n=_[a++],p=_[a++],m=_[a++],o=_[a++];if((n&128)>0||(p&128)>0||(m&128)>0||(o&128)>0){a-=4;return}if(e<6)if(e===4)return $(n,p,m,o);else{let C=_[a++];if((C&128)>0){a-=5;return}return $(n,p,m,o,C)}else if(e<8){let C=_[a++],r=_[a++];if((C&128)>0||(r&128)>0){a-=6;return}if(e<7)return $(n,p,m,o,C,r);let y=_[a++];if((y&128)>0){a-=7;return}return $(n,p,m,o,C,r,y)}else{let C=_[a++],r=_[a++],y=_[a++],D=_[a++];if((C&128)>0||(r&128)>0||(y&128)>0||(D&128)>0){a-=8;return}if(e<10)if(e===8)return $(n,p,m,o,C,r,y,D);else{let t=_[a++];if((t&128)>0){a-=9;return}return $(n,p,m,o,C,r,y,D,t)}else if(e<12){let t=_[a++],w=_[a++];if((t&128)>0||(w&128)>0){a-=10;return}if(e<11)return $(n,p,m,o,C,r,y,D,t,w);let I=_[a++];if((I&128)>0){a-=11;return}return $(n,p,m,o,C,r,y,D,t,w,I)}else{let t=_[a++],w=_[a++],I=_[a++],v=_[a++];if((t&128)>0||(w&128)>0||(I&128)>0||(v&128)>0){a-=12;return}if(e<14)if(e===12)return $(n,p,m,o,C,r,y,D,t,w,I,v);else{let G=_[a++];if((G&128)>0){a-=13;return}return $(n,p,m,o,C,r,y,D,t,w,I,v,G)}else{let G=_[a++],Z=_[a++];if((G&128)>0||(Z&128)>0){a-=14;return}if(e<15)return $(n,p,m,o,C,r,y,D,t,w,I,v,G,Z);let M=_[a++];if((M&128)>0){a-=15;return}return $(n,p,m,o,C,r,y,D,t,w,I,v,G,Z,M)}}}}}function Jn(){let e=_[a++],n;if(e<192)n=e-160;else switch(e){case 217:n=_[a++];break;case 218:n=E.getUint16(a),a+=2;break;case 219:n=E.getUint32(a),a+=4;break;default:throw Error("Expected string")}return Te(n)}function ke(e){return H.copyBuffers?Uint8Array.prototype.slice.call(_,a,a+=e):_.subarray(a,a+=e)}function ae(e){let n=_[a++];if(L[n]){let p;return L[n](_.subarray(a,p=a+=e),(m)=>{a=m;try{return X()}finally{a=p}})}else throw Error("Unknown extension type "+n)}var Bn=Array(4096);function ep(){let e=_[a++];if(e>=160&&e<192){if(e=e-160,z>=a)return pe.slice(a-q,(a+=e)-q);else if(!(z==0&&S<180))return Je(e)}else return a--,np(X());let n=(e<<5^(e>1?E.getUint16(a):e>0?_[a]:0))&4095,p=Bn[n],m=a,o=a+e-3,C,r=0;if(p&&p.bytes==e){while(m<o){if(C=E.getUint32(m),C!=p[r++]){m=1879048192;break}m+=4}o+=3;while(m<o)if(C=_[m++],C!=p[r++]){m=1879048192;break}if(m===o)return a=m,p.string;o-=3,m=a}p=[],Bn[n]=p,p.bytes=e;while(m<o)C=E.getUint32(m),p.push(C),m+=4;o+=3;while(m<o)C=_[m++],p.push(C);let y=e<16?Ve(e):gn(e);if(y!=null)return p.string=y;return p.string=Je(e)}function np(e){if(typeof e==="string")return e;if(typeof e==="number"||typeof e==="boolean"||typeof e==="bigint")return e.toString();if(e==null)return e+"";if(H.allowArraysInMapKeys&&Array.isArray(e)&&e.flat().every((n)=>["string","number","boolean","bigint"].includes(typeof n)))return e.flat().toString();throw Error(`Invalid property type for record: ${typeof e}`)}var zn=(e,n)=>{let p=X().map(np),m=e;if(n!==void 0)e=e<32?-((n<<5)+e):(n<<5)+e,p.highByte=n;let o=F[e];if(o&&(o.isShared||me))(F.restoreStructures||(F.restoreStructures=[]))[e]=o;return F[e]=p,p.read=ze(p,m),p.read()};L[0]=()=>{};L[0].noBuffer=!0;L[66]=(e)=>{let n=e.byteLength%8||8,p=BigInt(e[0]&128?e[0]-256:e[0]);for(let m=1;m<n;m++)p<<=BigInt(8),p+=BigInt(e[m]);if(e.byteLength!==n){let m=new DataView(e.buffer,e.byteOffset,e.byteLength),o=(C,r)=>{let y=r-C;if(y<=40){let I=m.getBigUint64(C);for(let v=C+8;v<r;v+=8)I<<=BigInt(64),I|=m.getBigUint64(v);return I}let D=C+(y>>4<<3),t=o(C,D),w=o(D,r);return t<<BigInt((r-D)*8)|w};p=p<<BigInt((m.byteLength-n)*8)|o(n,m.byteLength)}return p};var Vn={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError,AggregateError:typeof AggregateError==="function"?AggregateError:null};L[101]=()=>{let e=X();if(!Vn[e[0]]){let n=Error(e[1],{cause:e[2]});return n.name=e[0],n}return Vn[e[0]](e[1],{cause:e[2]})};L[105]=(e)=>{if(H.structuredClone===!1)throw Error("Structured clone extension is disabled");let n=E.getUint32(a-4);if(!g)g=new Map;let p=_[a],m;if(p>=144&&p<160||p==220||p==221)m=[];else if(p>=128&&p<144||p==222||p==223)m=new Map;else if((p>=199&&p<=201||p>=212&&p<=216)&&_[a+1]===115)m=new Set;else m={};let o={target:m};g.set(n,o);let C=X();if(!o.used)return o.target=C;else Object.assign(m,C);if(m instanceof Map)for(let[r,y]of C.entries())m.set(r,y);if(m instanceof Set)for(let r of Array.from(C))m.add(r);return m};L[112]=(e)=>{if(H.structuredClone===!1)throw Error("Structured clone extension is disabled");let n=E.getUint32(a-4),p=g.get(n);return p.used=!0,p.target};L[115]=()=>new Set(X());var je=["Int8","Uint8","Uint8Clamped","Int16","Uint16","Int32","Uint32","Float32","Float64","BigInt64","BigUint64"].map((e)=>e+"Array"),Np=typeof globalThis==="object"?globalThis:window;L[116]=(e)=>{let n=e[0],p=Uint8Array.prototype.slice.call(e,1).buffer,m=je[n];if(!m){if(n===16)return p;if(n===17)return new DataView(p);throw Error("Could not find typed array for code "+n)}return new Np[m](p)};L[120]=()=>{let e=X();return new RegExp(e[0],e[1])};var vp=[];L[98]=(e)=>{let n=(e[0]<<24)+(e[1]<<16)+(e[2]<<8)+e[3],p=a;return a+=n-e.length,U=vp,U=[Jn(),Jn()],U.position0=0,U.position1=0,U.postBundlePosition=a,a=p,X()};L[255]=(e)=>{if(e.length==4)return new Date((e[0]*16777216+(e[1]<<16)+(e[2]<<8)+e[3])*1000);else if(e.length==8)return new Date(((e[0]<<22)+(e[1]<<14)+(e[2]<<6)+(e[3]>>2))/1e6+((e[3]&3)*4294967296+e[4]*16777216+(e[5]<<16)+(e[6]<<8)+e[7])*1000);else if(e.length==12)return new Date(((e[0]<<24)+(e[1]<<16)+(e[2]<<8)+e[3])/1e6+((e[4]&128?-281474976710656:0)+e[6]*1099511627776+e[7]*4294967296+e[8]*16777216+(e[9]<<16)+(e[10]<<8)+e[11])*1000);else return new Date("invalid")};function pp(e){if(Zn)Zn();let n=S,p=a,m=Se,o=q,C=z,r=pe,y=qe,D=g,t=U,w=new Uint8Array(_.slice(0,S)),I=F,v=F.slice(0,F.length),G=H,Z=me,M=e();return S=n,a=p,Se=m,q=o,z=C,pe=r,qe=y,g=D,U=t,_=w,me=Z,F=I,F.splice(0,F.length,...v),H=G,E=new DataView(_.buffer,_.byteOffset,_.byteLength),M}function Me(){_=null,g=null,F=null}function mp(e){if(e.unpack)L[e.type]=e.unpack;else L[e.type]=e}var Pe=Array(147);for(let e=0;e<256;e++)Pe[e]=+("1e"+Math.floor(45.15-e*0.30103));var He=new V({useRecords:!1}),Kp=He.unpack,Yp=He.unpackMultiple,Gp=He.unpack;var Xp=new Float32Array(1),xm=new Uint8Array(Xp.buffer,0,4);var Ne;try{Ne=new TextEncoder}catch(e){}var ve,Ke,xe=typeof Buffer<"u",ie=xe?function(e){return Buffer.allocUnsafeSlow(e)}:Uint8Array,rp=xe?Buffer:Uint8Array,op=xe?4294967296:2144337920,l,we,i,f=0,Q,Y=null,$p,Up=21760,Lp=/[\u0080-\uFFFF]/,se=Symbol("record-id");class _e extends V{constructor(e){super(e);this.offset=0;let n,p,m,o,C,r=rp.prototype.utf8Write?function(d,T){return l.utf8Write(d,T,l.byteLength-T)}:Ne&&Ne.encodeInto?function(d,T){return Ne.encodeInto(d,l.subarray(T)).written}:!1,y=this;if(!e)e={};let D=e&&e.sequential,t=e.structures||e.saveStructures,w=e.maxSharedStructures;if(w==null)w=t?32:0;if(w>8160)throw Error("Maximum maxSharedStructure is 8160");if(e.structuredClone&&e.moreTypes==null)this.moreTypes=!0;let I=e.maxOwnStructures;if(I==null)I=t?32:64;if(!this.structures&&e.useRecords!=!1)this.structures=[];let v=w>32||I+w>64,G=w+64,Z=w+I+64;if(Z>8256)throw Error("Maximum maxSharedStructure + maxOwnStructure is 8192");let M=[],ee=0,fe=0;this.pack=this.encode=function(d,T){if(!l)l=new ie(8192),i=l.dataView||(l.dataView=new DataView(l.buffer,0,8192)),f=0;if(Q=l.length-10,Q-f<2048)l=new ie(l.length),i=l.dataView||(l.dataView=new DataView(l.buffer,0,l.length)),Q=l.length-10,f=0;else f=f+7&2147483640;if(p=f,T&Rp)f+=T&255;if(C=y.structuredClone?new Map:null,y.bundleStrings&&typeof d!=="string")Y=[],Y.size=1/0;else Y=null;if(o=y.structures,o){if(o.uninitialized)o=y._mergeStructures(y.getStructures());let R=o.sharedLength||0;if(R>w)throw Error("Shared structures is larger than maximum shared structures, try increasing maxSharedStructures to "+o.sharedLength);if(!o.transitions){o.transitions=Object.create(null);for(let s=0;s<R;s++){let c=o[s];if(!c)continue;let h,A=o.transitions;for(let O=0,P=c.length;O<P;O++){let B=c[O];if(h=A[B],!h)h=A[B]=Object.create(null);A=h}A[se]=s+64}this.lastNamedStructuresLength=R}if(!D)o.nextId=R+64}if(m)m=!1;let x;try{if(y.randomAccessStructure&&d&&typeof d==="object")if(d.constructor===Object)Mn(d);else if(d.constructor!==Map&&!Array.isArray(d)&&!Ke.some((s)=>d instanceof s))Mn(d.toJSON?d.toJSON():d);else K(d);else K(d);let R=Y;if(Y)ap(p,K,0);if(C&&C.idsToInsert){let s=C.idsToInsert.sort((O,P)=>O.offset>P.offset?1:-1),c=s.length,h=-1;while(R&&c>0){let O=s[--c].offset+p;if(O<R.stringsPosition+p&&h===-1)h=0;if(O>R.position+p){if(h>=0)h+=6}else{if(h>=0)i.setUint32(R.position+p,i.getUint32(R.position+p)+h),h=-1;R=R.previous,c++}}if(h>=0&&R)i.setUint32(R.position+p,i.getUint32(R.position+p)+h);if(f+=s.length*6,f>Q)u(f);y.offset=f;let A=Qp(l.subarray(p,f),s);return C=null,A}if(y.offset=f,T&dp)return l.start=p,l.end=f,l;return l.subarray(p,f)}catch(R){throw x=R,R}finally{if(o){if(bn(),m&&y.saveStructures){let R=o.sharedLength||0,s=l.subarray(p,f),c=Zp(o,y);if(!x){if(y.saveStructures(c,c.isCompatible)===!1)return y.pack(d,T);if(y.lastNamedStructuresLength=R,l.length>1073741824)l=null;return s}}}if(l.length>1073741824)l=null;if(T&yp)f=p}};let bn=()=>{if(fe<10)fe++;let d=o.sharedLength||0;if(o.length>d&&!D)o.length=d;if(ee>1e4){if(o.transitions=null,fe=0,ee=0,M.length>0)M=[]}else if(M.length>0&&!D){for(let T=0,x=M.length;T<x;T++)M[T][se]=0;M=[]}},Ue=(d)=>{var T=d.length;if(T<16)l[f++]=144|T;else if(T<65536)l[f++]=220,l[f++]=T>>8,l[f++]=T&255;else l[f++]=221,i.setUint32(f,T),f+=4;for(let x=0;x<T;x++)K(d[x])},K=(d)=>{if(f>Q)l=u(f);var T=typeof d,x;if(T==="string"){let R=d.length;if(Y&&R>=4&&R<4096){if((Y.size+=R)>Up){let A,O=(Y[0]?Y[0].length*3+Y[1].length:0)+10;if(f+O>Q)l=u(f+O);let P;if(Y.position)P=Y,l[f]=200,f+=3,l[f++]=98,A=f-p,f+=4,ap(p,K,0),i.setUint16(A+p-3,f-p-A);else l[f++]=214,l[f++]=98,A=f-p,f+=4;Y=["",""],Y.previous=P,Y.size=0,Y.position=A}let h=Lp.test(d);Y[h?0:1]+=d,l[f++]=193,K(h?-R:R);return}let s;if(R<32)s=1;else if(R<256)s=2;else if(R<65536)s=3;else s=5;let c=R*3;if(f+c>Q)l=u(f+c);if(R<64||!r){let h,A,O,P=f+s;for(h=0;h<R;h++)if(A=d.charCodeAt(h),A<128)l[P++]=A;else if(A<2048)l[P++]=A>>6|192,l[P++]=A&63|128;else if((A&64512)===55296&&((O=d.charCodeAt(h+1))&64512)===56320)A=65536+((A&1023)<<10)+(O&1023),h++,l[P++]=A>>18|240,l[P++]=A>>12&63|128,l[P++]=A>>6&63|128,l[P++]=A&63|128;else l[P++]=A>>12|224,l[P++]=A>>6&63|128,l[P++]=A&63|128;x=P-f-s}else x=r(d,f+s);if(x<32)l[f++]=160|x;else if(x<256){if(s<2)l.copyWithin(f+2,f+1,f+1+x);l[f++]=217,l[f++]=x}else if(x<65536){if(s<3)l.copyWithin(f+3,f+2,f+2+x);l[f++]=218,l[f++]=x>>8,l[f++]=x&255}else{if(s<5)l.copyWithin(f+5,f+3,f+3+x);l[f++]=219,i.setUint32(f,x),f+=4}f+=x}else if(T==="number")if(d>>>0===d)if(d<32||d<128&&this.useRecords===!1||d<64&&!this.randomAccessStructure)l[f++]=d;else if(d<256)l[f++]=204,l[f++]=d;else if(d<65536)l[f++]=205,l[f++]=d>>8,l[f++]=d&255;else l[f++]=206,i.setUint32(f,d),f+=4;else if(d>>0===d)if(d>=-32)l[f++]=256+d;else if(d>=-128)l[f++]=208,l[f++]=d+256;else if(d>=-32768)l[f++]=209,i.setInt16(f,d),f+=2;else l[f++]=210,i.setInt32(f,d),f+=4;else{let R;if((R=this.useFloat32)>0&&d<4294967296&&d>=-2147483648){l[f++]=202,i.setFloat32(f,d);let s;if(R<4||(s=d*Pe[(l[f]&127)<<1|l[f+1]>>7])>>0===s){f+=4;return}else f--}l[f++]=203,i.setFloat64(f,d),f+=8}else if(T==="object"||T==="function")if(!d)l[f++]=192;else{if(C){let s=C.get(d);if(s){if(!s.id){let c=C.idsToInsert||(C.idsToInsert=[]);s.id=c.push(s)}l[f++]=214,l[f++]=112,i.setUint32(f,s.id),f+=4;return}else C.set(d,{offset:f-p})}let R=d.constructor;if(R===Object)Ee(d);else if(R===Array)Ue(d);else if(R===Map)if(this.mapAsEmptyObject)l[f++]=128;else{if(x=d.size,x<16)l[f++]=128|x;else if(x<65536)l[f++]=222,l[f++]=x>>8,l[f++]=x&255;else l[f++]=223,i.setUint32(f,x),f+=4;for(let[s,c]of d)K(s),K(c)}else{for(let s=0,c=ve.length;s<c;s++){let h=Ke[s];if(d instanceof h){let A=ve[s];if(A.write){if(A.type)l[f++]=212,l[f++]=A.type,l[f++]=0;let De=A.write.call(this,d);if(De===d)if(Array.isArray(d))Ue(d);else Ee(d);else K(De);return}let O=l,P=i,B=f;l=null;let ne;try{ne=A.pack.call(this,d,(De)=>{if(l=O,O=null,f+=De,f>Q)u(f);return{target:l,targetView:i,position:f-De}},K)}finally{if(O)l=O,i=P,f=B,Q=l.length-10}if(ne){if(ne.length+f>Q)u(ne.length+f);f=Cp(ne,l,f,A.type)}return}}if(Array.isArray(d))Ue(d);else{if(d.toJSON){let s=d.toJSON();if(s!==d)return K(s)}if(T==="function")return K(this.writeFunction&&this.writeFunction(d));Ee(d)}}}else if(T==="boolean")l[f++]=d?195:194;else if(T==="bigint"){if(d<9223372036854776000&&d>=-9223372036854776000)l[f++]=211,i.setBigInt64(f,d);else if(d<18446744073709552000&&d>0)l[f++]=207,i.setBigUint64(f,d);else if(this.largeBigIntToFloat)l[f++]=203,i.setFloat64(f,Number(d));else if(this.largeBigIntToString)return K(d.toString());else if(this.useBigIntExtension||this.moreTypes){let R=d<0?BigInt(-1):BigInt(0),s;if(d>>BigInt(65536)===R){let c=BigInt(18446744073709552000)-BigInt(1),h=[];while(!0){if(h.push(d&c),d>>BigInt(63)===R)break;d>>=BigInt(64)}s=new Uint8Array(new BigUint64Array(h).buffer),s.reverse()}else{let c=d<0,h=(c?~d:d).toString(16);if(h.length%2)h="0"+h;else if(parseInt(h.charAt(0),16)>=8)h="00"+h;if(xe)s=Buffer.from(h,"hex");else{s=new Uint8Array(h.length/2);for(let A=0;A<s.length;A++)s[A]=parseInt(h.slice(A*2,A*2+2),16)}if(c)for(let A=0;A<s.length;A++)s[A]=~s[A]}if(s.length+f>Q)u(s.length+f);f=Cp(s,l,f,66);return}else throw RangeError(d+" was too large to fit in MessagePack 64-bit integer format, use useBigIntExtension, or set largeBigIntToFloat to convert to float-64, or set largeBigIntToString to convert to string");f+=8}else if(T==="undefined")if(this.encodeUndefinedAsNil)l[f++]=192;else l[f++]=212,l[f++]=0,l[f++]=0;else throw Error("Unknown type: "+T)},tn=this.variableMapSize||this.coercibleKeyAsNumber||this.skipValues?(d)=>{let T;if(this.skipValues){T=[];for(let s in d)if((typeof d.hasOwnProperty!=="function"||d.hasOwnProperty(s))&&!this.skipValues.includes(d[s]))T.push(s)}else T=Object.keys(d);let x=T.length;if(x<16)l[f++]=128|x;else if(x<65536)l[f++]=222,l[f++]=x>>8,l[f++]=x&255;else l[f++]=223,i.setUint32(f,x),f+=4;let R;if(this.coercibleKeyAsNumber)for(let s=0;s<x;s++){R=T[s];let c=Number(R);K(isNaN(c)?R:c),K(d[R])}else for(let s=0;s<x;s++)K(R=T[s]),K(d[R])}:(d)=>{l[f++]=222;let T=f-p;f+=2;let x=0;for(let R in d)if(typeof d.hasOwnProperty!=="function"||d.hasOwnProperty(R))K(R),K(d[R]),x++;if(x>65535)throw Error('Object is too large to serialize with fast 16-bit map size, use the "variableMapSize" option to serialize this object');l[T+++p]=x>>8,l[T+p]=x&255},En=this.useRecords===!1?tn:e.progressiveRecords&&!v?(d)=>{let T,x=o.transitions||(o.transitions=Object.create(null)),R=f++-p,s;for(let c in d)if(typeof d.hasOwnProperty!=="function"||d.hasOwnProperty(c)){if(T=x[c],T)x=T;else{let h=Object.keys(d),A=x;x=o.transitions;let O=0;for(let P=0,B=h.length;P<B;P++){let ne=h[P];if(T=x[ne],!T)T=x[ne]=Object.create(null),O++;x=T}if(R+p+1==f)f--,Le(x,h,O);else Fn(x,h,R,O);s=!0,x=A[c]}K(d[c])}if(!s){let c=x[se];if(c)l[R+p]=c;else Fn(x,Object.keys(d),R,0)}}:(d)=>{let T,x=o.transitions||(o.transitions=Object.create(null)),R=0;for(let c in d)if(typeof d.hasOwnProperty!=="function"||d.hasOwnProperty(c)){if(T=x[c],!T)T=x[c]=Object.create(null),R++;x=T}let s=x[se];if(s)if(s>=96&&v)l[f++]=((s-=96)&31)+96,l[f++]=s>>5;else l[f++]=s;else Le(x,x.__keys__||Object.keys(d),R);for(let c in d)if(typeof d.hasOwnProperty!=="function"||d.hasOwnProperty(c))K(d[c])},In=typeof this.useRecords=="function"&&this.useRecords,Ee=In?(d)=>{In(d)?En(d):tn(d)}:En,u=(d)=>{let T;if(d>16777216){if(d-p>op)throw Error("Packed buffer would be larger than maximum buffer size");T=Math.min(op,Math.round(Math.max((d-p)*(d>67108864?1.25:2),4194304)/4096)*4096)}else T=(Math.max(d-p<<2,l.length-1)>>12)+1<<12;let x=new ie(T);if(i=x.dataView||(x.dataView=new DataView(x.buffer,0,T)),d=Math.min(d,l.length),l.copy)l.copy(x,0,p,d);else x.set(l.slice(p,d));return f-=p,p=0,Q=x.length-10,l=x},Le=(d,T,x)=>{let R=o.nextId;if(!R)R=64;if(R<G&&this.shouldShareStructure&&!this.shouldShareStructure(T)){if(R=o.nextOwnId,!(R<Z))R=G;o.nextOwnId=R+1}else{if(R>=Z)R=G;o.nextId=R+1}let s=T.highByte=R>=96&&v?R-96>>5:-1;if(d[se]=R,d.__keys__=T,o[R-64]=T,R<G)if(T.isShared=!0,o.sharedLength=R-63,m=!0,s>=0)l[f++]=(R&31)+96,l[f++]=s;else l[f++]=R;else{if(s>=0)l[f++]=213,l[f++]=114,l[f++]=(R&31)+96,l[f++]=s;else l[f++]=212,l[f++]=114,l[f++]=R;if(x)ee+=fe*x;if(M.length>=I)M.shift()[se]=0;M.push(d),K(T)}},Fn=(d,T,x,R)=>{let s=l,c=f,h=Q,A=p;if(l=we,f=0,p=0,!l)we=l=new ie(8192);Q=l.length-10,Le(d,T,R),we=l;let O=f;if(l=s,f=c,Q=h,p=A,O>1){let P=f+O-1;if(P>Q)u(P);let B=x+p;l.copyWithin(B+O,B+1,f),l.set(we.slice(0,O),B),f=P}else l[x+p]=we[0]},Mn=(d)=>{let T=$p(d,l,p,f,o,u,(x,R,s)=>{if(s)return m=!0;f=R;let c=l;if(K(x),bn(),c!==l)return{position:f,targetView:i,target:l};return f},this);if(T===0)return Ee(d);f=T}}useBuffer(e){l=e,l.dataView||(l.dataView=new DataView(l.buffer,l.byteOffset,l.byteLength)),i=l.dataView,f=0}set position(e){f=e}get position(){return f}clearSharedData(){if(this.structures)this.structures=[];if(this.typedStructs)this.typedStructs=[]}}Ke=[Date,Set,Error,RegExp,ArrayBuffer,Object.getPrototypeOf(Uint8Array.prototype).constructor,DataView,Oe];ve=[{pack(e,n,p){let m=e.getTime()/1000;if((this.useTimestamp32||e.getMilliseconds()===0)&&m>=0&&m<4294967296){let{target:o,targetView:C,position:r}=n(6);o[r++]=214,o[r++]=255,C.setUint32(r,m)}else if(m>0&&m<4294967296){let{target:o,targetView:C,position:r}=n(10);o[r++]=215,o[r++]=255,C.setUint32(r,e.getMilliseconds()*4000000+(m/1000/4294967296>>0)),C.setUint32(r+4,m)}else if(isNaN(m)){if(this.onInvalidDate)return n(0),p(this.onInvalidDate());let{target:o,targetView:C,position:r}=n(3);o[r++]=212,o[r++]=255,o[r++]=255}else{let{target:o,targetView:C,position:r}=n(15);o[r++]=199,o[r++]=12,o[r++]=255,C.setUint32(r,e.getMilliseconds()*1e6),C.setBigInt64(r+4,BigInt(Math.floor(m)))}}},{pack(e,n,p){if(this.setAsEmptyObject)return n(0),p({});let m=Array.from(e),{target:o,position:C}=n(this.moreTypes?3:0);if(this.moreTypes)o[C++]=212,o[C++]=115,o[C++]=0;p(m)}},{pack(e,n,p){let{target:m,position:o}=n(this.moreTypes?3:0);if(this.moreTypes)m[o++]=212,m[o++]=101,m[o++]=0;p([e.name,e.message,e.cause])}},{pack(e,n,p){let{target:m,position:o}=n(this.moreTypes?3:0);if(this.moreTypes)m[o++]=212,m[o++]=120,m[o++]=0;p([e.source,e.flags])}},{pack(e,n){if(this.moreTypes)ue(e,16,n);else ge(xe?Buffer.from(e):new Uint8Array(e),n)}},{pack(e,n){let p=e.constructor;if(p!==rp&&this.moreTypes)ue(e,je.indexOf(p.name),n);else ge(e,n)}},{pack(e,n){if(this.moreTypes)ue(e,17,n);else ge(xe?Buffer.from(e):new Uint8Array(e),n)}},{pack(e,n){let{target:p,position:m}=n(1);p[m]=193}}];function ue(e,n,p,m){let o=e.byteLength;if(o+1<256){var{target:C,position:r}=p(4+o);C[r++]=199,C[r++]=o+1}else if(o+1<65536){var{target:C,position:r}=p(5+o);C[r++]=200,C[r++]=o+1>>8,C[r++]=o+1&255}else{var{target:C,position:r,targetView:y}=p(7+o);C[r++]=201,y.setUint32(r,o+1),r+=4}if(C[r++]=116,C[r++]=n,!e.buffer)e=new Uint8Array(e);C.set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength),r)}function ge(e,n){let p=e.byteLength;var m,o;if(p<256){var{target:m,position:o}=n(p+2);m[o++]=196,m[o++]=p}else if(p<65536){var{target:m,position:o}=n(p+3);m[o++]=197,m[o++]=p>>8,m[o++]=p&255}else{var{target:m,position:o,targetView:C}=n(p+5);m[o++]=198,C.setUint32(o,p),o+=4}m.set(e,o)}function Cp(e,n,p,m){let o=e.length;switch(o){case 1:n[p++]=212;break;case 2:n[p++]=213;break;case 4:n[p++]=214;break;case 8:n[p++]=215;break;case 16:n[p++]=216;break;default:if(o<256)n[p++]=199,n[p++]=o;else if(o<65536)n[p++]=200,n[p++]=o>>8,n[p++]=o&255;else n[p++]=201,n[p++]=o>>24,n[p++]=o>>16&255,n[p++]=o>>8&255,n[p++]=o&255}return n[p++]=m,n.set(e,p),p+=o,p}function Qp(e,n){let p,m=n.length*6,o=e.length-m;while(p=n.pop()){let{offset:C,id:r}=p;e.copyWithin(C+m,C,o),m-=6;let y=C+m;e[y++]=214,e[y++]=105,e[y++]=r>>24,e[y++]=r>>16&255,e[y++]=r>>8&255,e[y++]=r&255,o=C}return e}function ap(e,n,p){if(Y.length>0){i.setUint32(Y.position+e,f+p-Y.position-e),Y.stringsPosition=f-e;let m=Y;Y=null,n(m[0]),n(m[1])}}function en(e){if(e.Class){if(!e.pack&&!e.write)throw Error("Extension has no pack or write function");if(e.pack&&!e.type)throw Error("Extension has no type (numeric code to identify the extension)");Ke.unshift(e.Class),ve.unshift(e)}mp(e)}function Zp(e,n){return e.isCompatible=(p)=>{let m=!p||(n.lastNamedStructuresLength||0)===p.length;if(!m)n._mergeStructures(p);return m},e}var lp=new _e({useRecords:!1}),kp=lp.pack,Wp=lp.pack;var dp=512,yp=1024,Rp=2048;var xp=80;class j{capId;constructor(e){this.capId=e}}var qp=new Set(["hello","goaway","call","result","cancel","stream","drop"]);function nn(e){if(typeof e!=="object"||e===null)return!1;let n=e,p=n.op;if(typeof p!=="string"||!qp.has(p))return!1;switch(p){case"hello":return n.v===1&&(n.mode==="native"||n.mode==="web")&&Array.isArray(n.features)&&typeof n.maxBytes==="number"&&typeof n.origin==="string";case"goaway":return n.reason===void 0||typeof n.reason==="string";case"call":return typeof n.id==="number"&&typeof n.method==="number"&&typeof n.target==="object"&&n.target!==null&&n.target.kind==="cap"&&typeof n.target.id==="number";case"result":return typeof n.id==="number"&&(n.ok===!0||n.ok===!1);case"cancel":return typeof n.id==="number";case"stream":return typeof n.id==="number"&&typeof n.ev==="string"&&(n.ev==="next"||n.ev==="credit"||n.ev==="end"||n.ev==="error");case"drop":return Array.isArray(n.caps)}}var sp=!1;function Sp(){if(sp)return;sp=!0,en({Class:j,type:xp,pack:(e)=>Jp(e.capId),unpack:(e)=>new j(zp(e))})}function pn(){return Sp(),{packr:new _e({useRecords:!0,sequential:!0,moreTypes:!0}),unpackr:new V({useRecords:!0,sequential:!0,moreTypes:!0})}}function Jp(e){let n=new Uint8Array(5),p=e>>>0,m=0;while(p>=128)n[m++]=p&127|128,p>>>=7;return n[m++]=p&127,n.subarray(0,m)}var Bp=5;function zp(e){let n=0,p=0,m=Math.min(e.length,Bp);for(let o=0;o<m;o++){let C=e[o];if(n|=(C&127)<<p,(C&128)===0)return n>>>0;p+=7}throw Error("Truncated or oversize varuint")}var mn=67108864,on=1;class N extends Error{code;details;retry;constructor(e){super(e.message??e.code);this.name="IpcError",this.code=e.code,this.details=e.details,this.retry=e.retry}toStatus(){return{code:this.code,message:this.message,details:this.details,retry:this.retry}}}var Ye=W({focus:b(),close:b(),setBounds:b(),setTitle:b(),id:b({idempotent:!0}),label:b({idempotent:!0})}),Cn=W({create:b({returns:k(Ye)}),list:b({returns:k.array(Ye),idempotent:!0}),focus:b(),close:b()}),Ge=W({text:b({idempotent:!0}),bytes:b({idempotent:!0}),path:b({idempotent:!0}),revoke:b()},{disposal:{method:"revoke",async:!0}}),an=W({openFile:b({returns:k.array(Ge)}),saveFile:b({returns:k(Ge)}),showMessage:b()}),fn=W({readText:b({idempotent:!0}),writeText:b(),readBytes:b({idempotent:!0}),writeBytes:b()}),rn=W({openExternal:b(),showItemInFolder:b()}),ln=W({init:b(),resize:b(),remove:b(),setHidden:b(),setMasks:b(),setAllPassthrough:b(),bringAllVisiblesToFront:b(),navigate:b(),goBack:b(),reload:b(),didNavigate:Ie()}),Ae=W({window:b({returns:k(Cn),idempotent:!0}),dialogs:b({returns:k(an),idempotent:!0}),clipboard:b({returns:k(fn),idempotent:!0}),shell:b({returns:k(rn),idempotent:!0}),appName:b({idempotent:!0}),appVersion:b({idempotent:!0}),theme:b({idempotent:!0}),themeWatch:Ie(),surface:b({returns:k(ln),idempotent:!0})}),oe={Runtime:1,Window:2,Dialogs:3,FileRef:4,Clipboard:5,Shell:6,BrowserWindow:7},Vp=new Map([[Ae,oe.Runtime],[Cn,oe.Window],[an,oe.Dialogs],[Ge,oe.FileRef],[fn,oe.Clipboard],[rn,oe.Shell],[Ye,oe.BrowserWindow],[ln,8]]);function _p(e){return Vp.get(e)}var ce=0,yn=1,wp=0,Ap=1,he=2,cp=128,sn=1024,jp=500,up=32,gp=8,em=1024;function nm(e){let n=e?.initialBudget;if(typeof n!=="number"||!Number.isFinite(n)||!Number.isInteger(n)||n<1)return up;return Math.min(n,em)}var Xe=null;class xn{entries=new Map;nextCapId=he;capLimit;constructor(e=sn){this.capLimit=e}install(e,n){if(this.entries.has(e))throw Error(`cap-id ${e} already installed`);let p={capId:e,...n};return this.entries.set(e,p),p}allocate(e){if(this.entries.size>=this.capLimit)throw new N({code:"resource_exhausted",message:`cap-table limit ${this.capLimit}`});let n=this.nextCapId++;while(this.entries.has(n))n=this.nextCapId++;return this.install(n,e)}get(e){return this.entries.get(e)}release(e,n=1){let p=this.entries.get(e);if(!p)return!1;if(p.refCount=Math.max(0,p.refCount-n),p.refCount===0&&e>=he)return this.entries.delete(e),!0;return!1}clear(){this.entries.clear(),this.nextCapId=he}size(){return this.entries.size}values(){return this.entries.values()}}var pm={origin:"bunite://internal",topOrigin:"bunite://internal",partition:"default",isAppRes:!0,isMainFrame:!0,userGesture:!1,level:"app-internal"},Rn=Symbol("bunite.rpc.ExportedCap"),Dp=Symbol("bunite.rpc.CapProxyMeta");function mm(e){return typeof e==="object"&&e!==null&&e[Rn]===!0}var om=typeof FinalizationRegistry<"u"?new FinalizationRegistry((e)=>{if(e.dropped())return;let n=e.connRef.deref();if(!n||n.closed)return;n._dropFromFinalizer(e.capId)}):{register:()=>{}};class hp{transport;capTable;pending=new Map;clientStreams=new Map;serverStreams=new Map;serverCallChildren=new Map;serverActiveCalls=new Map;rootInstances=new Map;userRootsSchema=null;closeHandlers=new Set;nextCallId=1;remoteHello=null;remoteReady;resolveRemoteReady;rejectRemoteReady;closed_=!1;maxBytes;mode;origin;features;attestation;peerId;constructor(e){this.transport=e.transport,this.mode=e.mode,this.origin=e.origin,this.features=e.features??[],this.maxBytes=e.maxBytes??mn,this.attestation=e.attestation??pm,this.peerId=e.peerId??"peer",this.capTable=new xn(e.capLimit??sn),this.capTable.install(ce,{typeId:wp,cap:null,impl:null,refCount:1}),this.capTable.install(yn,{typeId:Ap,cap:Ae,impl:e.runtime??null,refCount:1}),this.remoteReady=new Promise((n,p)=>{this.resolveRemoteReady=n,this.rejectRemoteReady=p}),this.remoteReady.catch(()=>{}),this.transport.setReceive((n)=>this.handleFrame(n)),this.transport.send({op:"hello",v:on,mode:this.mode,features:this.features,maxBytes:this.maxBytes,origin:this.origin})}get closed(){return this.closed_}onClose(e){return this.closeHandlers.add(e),()=>this.closeHandlers.delete(e)}serve(e){let n=this.capTable.get(ce);if(!n)throw Error("UserRoots slot missing");this.rootInstances.clear(),this.userRootsSchema=e.schema;let p=this.buildUserRootsCap(e.schema,e.impls);n.cap=p.def,n.impl=p.impl}buildUserRootsCap(e,n){let p={},m={};for(let o of Object.keys(e.roots)){let C=e.roots[o];p[o]=b({returns:k(C),idempotent:!0}),m[o]=(r,y)=>{let D=this.rootInstances.get(o);if(D!==void 0){let w=this.capTable.get(D);if(w)return w.refCount+=1,{[Rn]:!0,cap:C,capId:D,typeId:w.typeId};this.rootInstances.delete(o)}let t=y.exportCap(C,n[o]);return this.rootInstances.set(o,t.capId),t}}return{def:W(p),impl:m}}runtimeProxy=null;runtime(){if(!this.runtimeProxy)this.runtimeProxy=this.makeCapProxy(Ae,yn);return this.runtimeProxy}async bootstrap(e,n){await this.remoteReady;let m=Object.keys(e.roots).indexOf(n);if(m<0)throw new N({code:"invalid_argument",message:`root "${n}" not in schema`});let o=e.roots[n],C=await e.topologyHash(),r=await this.sendCallTyped(ce,m,void 0,void 0,{topologyHash:C});if(!(r instanceof j))throw new N({code:"protocol_error",message:"bootstrap did not return a CapRef"});return this.makeCapProxy(o,r.capId)}handleFrame(e){if(this.closed_)return;switch(e.op){case"hello":this.handleHello(e);return;case"call":this.handleCall(e);return;case"result":this.handleResult(e);return;case"cancel":this.handleCancel(e);return;case"stream":this.handleStreamFrame(e);return;case"drop":this.handleDrop(e);return;case"goaway":this.handleGoaway(e);return;default:this.handleUnknownFrame(e);return}}handleUnknownFrame(e){let n=e?.id;if(typeof n==="number"){this.transport.send({op:"result",id:n,ok:!1,error:{code:"protocol_error",message:"unknown opcode"}});return}this.transport.send({op:"goaway",reason:"protocol_error",error:{code:"protocol_error",message:"unknown opcode"}}),this.shutdown("protocol_error")}handleHello(e){this.remoteHello=e,this.resolveRemoteReady(e)}handleGoaway(e){this.rejectRemoteReady(new N(e.error??{code:"unavailable",message:e.reason??"peer goaway"})),this.shutdown(e.reason??"remote goaway")}async handleCall(e){let n=this.capTable.get(e.target.id);if(!n)return this.sendError(e.id,"not_found",`cap-id ${e.target.id} not found`);if(n.capId===ce){if(!this.userRootsSchema)return this.sendError(e.id,"not_supported","no server attached");let y=e.meta?.topologyHash;if(y){let D=await this.userRootsSchema.topologyHash();if(y!==D)return this.sendError(e.id,"failed_precondition",`topologyHash mismatch (client ${y.slice(0,8)} vs server ${D.slice(0,8)})`)}}let p=n.cap;if(!p||!n.impl)return this.sendError(e.id,"not_supported","cap has no impl");let m=Object.keys(p.methods);if(e.method>=m.length)return this.sendError(e.id,"not_supported",`method index ${e.method} out of range`);let o=m[e.method],C=p.methods[o],r=n.impl[o];if(typeof r!=="function")return this.sendError(e.id,"not_supported",`method "${o}" has no handler`);await this.invokeServerMethod(e,C,r)}async invokeServerMethod(e,n,p){let m=this.makeCallCtx(e);if(Re(n)){let o=nm(n.hint);try{let C=()=>p(e.args,m),r=Xe,D=(r?()=>r.run({callId:e.id},C):C)();this.runServerStream(e.id,D,m,o)}catch(C){this.transport.send({op:"stream",id:e.id,ev:"error",error:dn(C)})}return}if(ye(n)){let o=n.idempotent?void 0:this.armServerDeadline(e,m);this.serverActiveCalls.set(e.id,m._ctrl);let C=Cm(n.returns),r=()=>Promise.resolve(p(e.args,m)),y=Xe,D=y?()=>y.run({callId:e.id},r):r;try{let t=await D();if(o)clearTimeout(o);if(!this.serverActiveCalls.delete(e.id))return;let w=C(t);this.transport.send({op:"result",id:e.id,ok:!0,value:w})}catch(t){if(o)clearTimeout(o);if(!this.serverActiveCalls.delete(e.id))return;this.sendErrorFromException(e.id,t)}return}this.sendError(e.id,"not_supported","unknown method kind")}armServerDeadline(e,n){let p=e.meta?.deadlineMs;if(!p)return;return setTimeout(()=>{n._ctrl.abort()},p)}makeCallCtx(e){let n=new AbortController;return{callId:e.id,peerId:this.peerId,attestation:this.attestation,signal:n.signal,deadline:e.meta?.deadlineMs,context:e.meta?.context,_ctrl:n,exportCap:(m,o)=>this.exportCap(m,o)}}exportCap(e,n){let p=_p(e)??cp,m=this.capTable.allocate({typeId:p,cap:e,impl:n,refCount:1});return{[Rn]:!0,cap:e,capId:m.capId,typeId:m.typeId}}runServerStream(e,n,p,m){let o=n[Symbol.asyncIterator](),C=p._ctrl,r={iter:o,abort:C,cancelled:!1,credit:m,creditWaker:null};this.serverStreams.set(e,r);let y=()=>{if(r.credit>0||r.cancelled)return Promise.resolve();return new Promise((t)=>{r.creditWaker=t})};(async()=>{let t=!1;try{while(!r.cancelled){if(r.credit===0)await y();if(r.cancelled)break;let{done:w,value:I}=await o.next();if(w)break;if(r.cancelled)break;r.credit-=1,this.transport.send({op:"stream",id:e,ev:"next",value:I})}}catch(w){t=!0,this.transport.send({op:"stream",id:e,ev:"error",error:dn(w)})}finally{if(!t)this.transport.send({op:"stream",id:e,ev:"end"});this.serverStreams.delete(e)}})()}handleResult(e){let n=this.pending.get(e.id);if(n){if(this.pending.delete(e.id),this.serverCallChildren.delete(e.id),n.timer)clearTimeout(n.timer);if(e.ok){let m=n.decodeReturn?n.decodeReturn(e.value):e.value;n.resolve(m)}else n.reject(new N(e.error));return}let p=this.clientStreams.get(e.id);if(p){this.clientStreams.delete(e.id);let m=e.ok?new N({code:"protocol_error",message:"stream method returned result frame"}):new N(e.error);p.fail(m)}}handleCancel(e){let n=this.serverStreams.get(e.id);if(n)n.cancelled=!0,n.abort.abort(),n.iter?.return?.(),this.serverStreams.delete(e.id);let p=this.serverActiveCalls.get(e.id);if(p)this.serverActiveCalls.delete(e.id),p.abort(),this.transport.send({op:"result",id:e.id,ok:!1,error:{code:"cancelled",message:e.reason}});for(let[m,o]of this.serverCallChildren){if(o.parentId!==e.id)continue;if(this.serverCallChildren.delete(m),this.pending.has(m))this.transport.send({op:"cancel",id:m,reason:e.reason})}}releaseRef(e){if(typeof e!=="object"||e===null)return;let n=e[Dp];if(!n||n.dropped)return;n.dropped=!0,this.sendDrop(n.capId)}sendDrop(e){if(this.closed_)return;if(e<he)return;this.transport.send({op:"drop",caps:[{id:e,delta:1}]})}handleStreamFrame(e){if(e.ev==="credit"){let p=this.serverStreams.get(e.id);if(!p)return;p.credit+=e.credit?.messages??0;let m=p.creditWaker;p.creditWaker=null,m?.();return}let n=this.clientStreams.get(e.id);if(!n)return;switch(e.ev){case"next":n.push(e.value);return;case"end":n.end(),this.clientStreams.delete(e.id);return;case"error":n.fail(new N(e.error)),this.clientStreams.delete(e.id);return}}handleDrop(e){for(let{id:n,delta:p}of e.caps)if(this.capTable.release(n,p)){for(let[o,C]of this.rootInstances)if(C===n){this.rootInstances.delete(o);break}}}sendError(e,n,p){this.transport.send({op:"result",id:e,ok:!1,error:{code:n,message:p}})}sendErrorFromException(e,n){this.transport.send({op:"result",id:e,ok:!1,error:dn(n)})}nextId(){return this.nextCallId++}sendCallRaw(e,n,p,m){return this.sendCallTyped(e,n,p,void 0,m)}sendCallTyped(e,n,p,m,o){if(this.closed_)return Promise.reject(new N({code:"unavailable",message:"connection closed"}));let C=this.nextId();return new Promise((r,y)=>{let D=new AbortController,t={resolve:r,reject:y,abort:D,decodeReturn:m};if(o?.deadlineMs)t.timer=setTimeout(()=>{if(this.pending.delete(C))this.transport.send({op:"cancel",id:C,reason:"deadline_exceeded"}),y(new N({code:"deadline_exceeded"}))},o.deadlineMs+jp);this.pending.set(C,t);let w=o;if(w?.parentCallId===void 0&&Xe){let I=Xe.getStore();if(I)w={...w??{},parentCallId:I.callId}}if(w?.parentCallId!==void 0)this.serverCallChildren.set(C,{parentId:w.parentCallId});this.transport.send({op:"call",id:C,target:{kind:"cap",id:e},method:n,args:p,meta:w})})}openClientStream(e,n,p,m){if(this.closed_){let D=Tp(0,()=>{},()=>{});return D.fail(new N({code:"unavailable",message:"connection closed"})),D.stream}let o=this.nextId(),y=Tp(o,()=>{if(this.clientStreams.delete(o))this.transport.send({op:"cancel",id:o,reason:"client_cancel"})},(D)=>{if(this.closed_||!this.clientStreams.has(o))return;this.transport.send({op:"stream",id:o,ev:"credit",credit:{messages:D}})});return this.clientStreams.set(o,y),this.transport.send({op:"call",id:o,target:{kind:"cap",id:e},method:n,args:p,meta:m}),y.stream}makeCapProxy(e,n){let p=Object.keys(e.methods),m={},o={capId:n,dropped:!1};m[Dp]=o;let C=()=>{if(o.dropped)return;o.dropped=!0,this.sendDrop(n)};for(let y=0;y<p.length;y++){let D=p[y],t=e.methods[D];if(Re(t))m[D]=(w)=>this.openClientStream(n,y,w);else if(ye(t)){let w=am(t.returns,(I,v)=>this.makeCapProxy(I,v));m[D]=(I)=>this.sendCallTyped(n,y,I,w)}}let r=e.disposal;if(r){let y=()=>{let D=m[r.method];return D?.()};m[Symbol.asyncDispose]=async()=>{let D=y();await Promise.resolve(D),C()},m[Symbol.dispose]=()=>{let D=y();C()}}if(typeof FinalizationRegistry<"u")om.register(m,{connRef:new WeakRef(this),capId:n,dropped:()=>o.dropped});return m}_dropFromFinalizer(e){try{this.sendDrop(e)}catch{}}shutdown(e){if(this.closed_)return;this.closed_=!0;for(let n of this.pending.values()){if(n.timer)clearTimeout(n.timer);n.reject(new N({code:"unavailable",message:e}))}this.pending.clear();for(let n of this.clientStreams.values())n.fail(new N({code:"unavailable",message:e}));this.clientStreams.clear();for(let n of this.serverStreams.values())n.cancelled=!0,n.abort.abort(),n.iter?.return?.();this.serverStreams.clear();for(let n of this.serverActiveCalls.values())n.abort();this.serverActiveCalls.clear();for(let n of this.capTable.values())this.invokeServerDisposal(n);if(this.capTable.clear(),!this.remoteHello)this.rejectRemoteReady(new N({code:"unavailable",message:e}));for(let n of this.closeHandlers)try{n()}catch{}this.closeHandlers.clear();try{this.transport.close()}catch{}}invokeServerDisposal(e){let n=e.cap;if(!n)return;let p=n.disposal;if(!p)return;let m=e.impl,o=m?.[p.method];if(!o)return;try{o.call(m,void 0,void 0)}catch{}}}function Cm(e){if(!e)return(p)=>p;let n=(p,m)=>{if(!mm(p))throw new N({code:"protocol_error",message:"expected ctx.exportCap return for cap method"});if(p.cap!==m)throw new N({code:"protocol_error",message:"exported cap type mismatch with method returns"});return new j(p.capId)};if(re(e))return(p)=>n(p,e.cap);if(le(e))return(p)=>{if(!Array.isArray(p))throw new N({code:"protocol_error",message:"expected ExportedCap[] for cap.array method"});return p.map((m)=>n(m,e.cap))};if(de(e))return(p)=>{if(!p||typeof p!=="object")throw new N({code:"protocol_error",message:"expected Record<string, ExportedCap> for cap.record method"});let m={};for(let o of Object.keys(p))m[o]=n(p[o],e.cap);return m};return(p)=>p}function am(e,n){if(!e)return;if(re(e)){let p=e.cap;return(m)=>{if(!(m instanceof j))throw new N({code:"protocol_error",message:"expected CapRef"});return n(p,m.capId)}}if(le(e)){let p=e.cap,m=p.disposal;return(o)=>{if(!Array.isArray(o))throw new N({code:"protocol_error",message:"expected array"});let C=o.map((r)=>{if(!(r instanceof j))throw new N({code:"protocol_error",message:"expected CapRef in array"});return n(p,r.capId)});return fm(C,m),C}}if(de(e)){let p=e.cap;return(m)=>{if(!m||typeof m!=="object")throw new N({code:"protocol_error",message:"expected record"});let o={};for(let C of Object.keys(m)){let r=m[C];if(!(r instanceof j))throw new N({code:"protocol_error",message:"expected CapRef in record"});o[C]=n(p,r.capId)}return o}}return}function fm(e,n){if(!n)return;let p=n.async?Symbol.asyncDispose:Symbol.dispose;e[p]=n.async?()=>Promise.all(e.map((m)=>{let o=m[Symbol.asyncDispose];return o?o.call(m):void 0})).then(()=>{return}):()=>{for(let m of e)m[Symbol.dispose]?.call(m)}}function dn(e){if(e instanceof N)return e.toStatus();if(e instanceof Error)return{code:"unknown",message:e.message};return{code:"unknown",message:String(e)}}function Tp(e,n,p){let m=[],o=[],C=!1,r=null,y=!1,D=0;function t(){if(D+=1,D>=gp)p(D),D=0}function w(){if(m.length>0){let M=m.shift();return t(),{value:M,done:!1}}if(r)return null;if(C||y)return{value:void 0,done:!0};return null}function I(){let M=w();if(M)return Promise.resolve(M);if(r)return Promise.reject(r);return new Promise((ee,fe)=>o.push({resolve:ee,reject:fe}))}function v(){while(o.length>0){let M=o.shift(),ee=w();if(ee){M.resolve(ee);continue}if(r){M.reject(r);continue}o.unshift(M);break}}function G(){if(y||C||r)return;y=!0,n(),v()}return{stream:{[Symbol.asyncIterator]:()=>({next:I,return:()=>{return G(),Promise.resolve({value:void 0,done:!0})},throw:(M)=>{return G(),Promise.reject(M)}}),[Symbol.dispose]:G,cancel:G},push(M){if(y||C||r)return;m.push(M),v()},end(){C=!0,v()},fail(M){r=M,v()}}}function _n(e){return new hp(e)}function Dn(e,n={}){let p=pn(),m;return e.setReceive((o)=>{let C;try{C=p.unpackr.unpack(o)}catch(r){n.onProtocolError?.(`unpack failed: ${r instanceof Error?r.message:String(r)}`),e.close();return}if(!nn(C)){n.onProtocolError?.("malformed frame"),e.close();return}m?.(C)}),{send(o){let C=p.packr.pack(o);e.send(C instanceof Uint8Array?C:new Uint8Array(C))},setReceive(o){m=o},close(){e.close()}}}function Tn(e){if("binaryType"in e)try{e.binaryType="arraybuffer"}catch{}let n,p=(m)=>{if(!n)return;let o=m.data;if(o instanceof Uint8Array){n(o);return}if(o instanceof ArrayBuffer){n(new Uint8Array(o));return}if(typeof Blob<"u"&&o instanceof Blob){o.arrayBuffer().then((C)=>n?.(new Uint8Array(C)));return}};return e.addEventListener("message",p),{send(m){e.send(m)},setReceive(m){n=m},close(){e.removeEventListener?.("message",p),e.close?.()}}}function be(e){let n=new ArrayBuffer(e.byteLength);return new Uint8Array(n).set(e),n}async function rm(e){return crypto.subtle.importKey("raw",be(e),"AES-GCM",!1,["encrypt","decrypt"])}async function wn(e,n){let p=await rm(n),m,o=Promise.resolve(),C=Promise.resolve(),r=!1,y=()=>{if(!r)r=!0,e.close()};return e.setReceive((D)=>{if(r)return;if(D.length<13||D[0]!==1){y();return}let t=be(D.subarray(1,13)),w=be(D.subarray(13));C=C.then(async()=>{if(r)return;try{let I=await crypto.subtle.decrypt({name:"AES-GCM",iv:t},p,w);m?.(new Uint8Array(I))}catch{y()}})}),{send(D){if(r)return;let t=be(D);o=o.then(async()=>{if(r)return;try{let w=crypto.getRandomValues(new Uint8Array(12)),I=be(w),v=await crypto.subtle.encrypt({name:"AES-GCM",iv:I},p,t),G=new Uint8Array(v),Z=new Uint8Array(13+G.byteLength);Z[0]=1,Z.set(w,1),Z.set(G,13),e.send(Z)}catch{y()}})},setReceive(D){m=D},close(){y()}}}class lm{buffer=[];waiters=[];ctrl=new AbortController;cleanup;ended=!1;failure=null;constructor(e){let n=(p)=>{if(this.ended||this.failure)return;let m=this.waiters.shift();if(m){m.resolve({value:p,done:!1});return}this.buffer.push(p)};try{let p=e(n,this.ctrl.signal);if(typeof p==="function")this.cleanup=p}catch(p){this.failure=p}}[Symbol.asyncIterator](){return{next:async()=>{if(this.buffer.length>0)return{value:this.buffer.shift(),done:!1};if(this.failure)throw this.failure;if(this.ended)return{value:void 0,done:!0};return new Promise((e,n)=>this.waiters.push({resolve:e,reject:n}))},return:async()=>{return this.dispose(),{value:void 0,done:!0}}}}cancel(){this.dispose()}[Symbol.dispose](){this.dispose()}dispose(){if(this.ended)return;this.ended=!0,this.ctrl.abort();try{this.cleanup?.()}catch{}while(this.waiters.length>0)this.waiters.shift().resolve({value:void 0,done:!0})}}var An=null;function cn(){if(!An)An=host.runtime().then((e)=>e.surface());return An}function J(e){return cn().then(e).catch((n)=>{if(globalThis.__BUNITE_DEBUG__)console.warn("[bunite] surface call failed",n);return})}class bp{element;onBoundsChange;observer=null;rafId=0;lastRect={x:0,y:0,width:0,height:0};dirty=!1;stopped=!1;constructor(e,n){this.element=e,this.onBoundsChange=n}start(){this.observer=new ResizeObserver(()=>this.markDirty()),this.observer.observe(this.element),this.scheduleFrame()}stop(){if(this.stopped=!0,this.observer?.disconnect(),this.observer=null,this.rafId)cancelAnimationFrame(this.rafId),this.rafId=0}markDirty(){this.dirty=!0}scheduleFrame(){if(this.stopped)return;this.rafId=requestAnimationFrame(()=>{this.flush(),this.scheduleFrame()})}flush(){let e=window.devicePixelRatio||1,n=this.element.getBoundingClientRect(),p={x:Math.round(n.x*e),y:Math.round(n.y*e),width:Math.round(n.width*e),height:Math.round(n.height*e)};if(!this.dirty&&p.x===this.lastRect.x&&p.y===this.lastRect.y&&p.width===this.lastRect.width&&p.height===this.lastRect.height)return;this.dirty=!1,this.lastRect=p,this.onBoundsChange(p)}}class tp extends HTMLElement{static observedAttributes=["src"];_surfaceId=null;_syncCtrl=null;_initPromise=null;_aborted=!1;_pendingSrc=null;_syncHidden=!1;_userHidden=!1;_layoutObserver=null;_unsubNavigate=null;constructor(){super()}connectedCallback(){this._aborted=!1,this._syncHidden=!1,this._userHidden=!1;let e=new AbortController;this._unsubNavigate=()=>e.abort(),(async()=>{try{let p=(await cn()).didNavigate();for await(let m of p){if(e.signal.aborted)break;if(m.surfaceId===this._surfaceId)this.dispatchEvent(new CustomEvent("did-navigate",{detail:{url:m.url}}))}}catch(n){if(globalThis.__BUNITE_DEBUG__)console.warn("[bunite] didNavigate stream failed",n)}})(),this._waitForLayout()}_waitForLayout(){if(this._layoutObserver)return;let e=()=>{if(!this.isConnected||this._aborted)return!0;let n=this.getBoundingClientRect();if(n.width>0&&n.height>0){if(this.getAttribute("src")||this._pendingSrc||"")this.initSurface();return!0}return!1};requestAnimationFrame(()=>{if(e())return;this._layoutObserver=new ResizeObserver(()=>{if(e())this._layoutObserver?.disconnect(),this._layoutObserver=null}),this._layoutObserver.observe(this)})}disconnectedCallback(){if(this._aborted=!0,this._unsubNavigate?.(),this._unsubNavigate=null,this._layoutObserver?.disconnect(),this._layoutObserver=null,this._syncCtrl?.stop(),this._syncCtrl=null,this._surfaceId!=null){let e=this._surfaceId;this._surfaceId=null,J((n)=>n.remove({surfaceId:e}))}else if(this._initPromise)this._initPromise.then((e)=>{J((n)=>n.remove({surfaceId:e.surfaceId}))}).catch(()=>{});this._initPromise=null}attributeChangedCallback(e,n,p){if(e!=="src")return;if(this._surfaceId!=null){let m=this._surfaceId;J((o)=>o.navigate({surfaceId:m,url:p||""}))}else if(this._initPromise)this._pendingSrc=p||"";else if(this.isConnected&&!this._aborted&&p)this._waitForLayout()}setHidden(e){this._userHidden=e,this._applySurfaceHidden()}goBack(){let e=this._surfaceId;if(e!=null)J((n)=>n.goBack({surfaceId:e}))}reload(){let e=this._surfaceId;if(e!=null)J((n)=>n.reload({surfaceId:e}))}navigate(e){this.setAttribute("src",e)}_applySurfaceHidden(){let e=this._surfaceId;if(e==null)return;let n=this._userHidden||this._syncHidden;J((p)=>p.setHidden({surfaceId:e,hidden:n}))}initSurface(){if(this._surfaceId!=null||this._initPromise!=null)return;let e=window.devicePixelRatio||1,n=this.getBoundingClientRect(),p=this._pendingSrc||this.getAttribute("src")||"";this._pendingSrc=null;let m=cn().then((o)=>o.init({src:p,x:Math.round(n.x*e),y:Math.round(n.y*e),width:Math.round(n.width*e),height:Math.round(n.height*e),hidden:this._userHidden}));this._initPromise=m,m.then((o)=>{if(this._initPromise!==m)return;if(this._aborted){J((C)=>C.remove({surfaceId:o.surfaceId}));return}if(this._surfaceId=o.surfaceId,this._userHidden)this._applySurfaceHidden();if(this._pendingSrc!=null){let C=this._pendingSrc;this._pendingSrc=null;let r=this._surfaceId;if(r!=null)J((y)=>y.navigate({surfaceId:r,url:C}))}this._syncCtrl=new bp(this,(C)=>{let r=this._surfaceId;if(r==null)return;if(C.width===0&&C.height===0){if(!this._syncHidden)this._syncHidden=!0,this._applySurfaceHidden();return}if(this._syncHidden)this._syncHidden=!1,this._applySurfaceHidden();J((D)=>D.resize({surfaceId:r,x:C.x,y:C.y,w:C.width,h:C.height}))}),this._syncCtrl.start()}).catch(()=>{}).finally(()=>{if(this._initPromise===m)this._initPromise=null})}}if(typeof customElements<"u"){customElements.define("bunite-webview",tp);let e=()=>{J((n)=>n.bringAllVisiblesToFront())};document.addEventListener("pointerdown",e,!0),document.addEventListener("dragstart",()=>{J((n)=>n.setAllPassthrough({passthrough:!0}))},!0),document.addEventListener("dragend",()=>{J((n)=>n.setAllPassthrough({passthrough:!1})),e()},!0)}var hn=null,te=null;function $e(){if(hn)return Promise.resolve(hn);if(te)return te;let e=(async()=>{let n=new WebSocket(`ws://localhost:${__buniteRpcSocketPort}/rpc?webviewId=${__buniteWebviewId}`);n.binaryType="arraybuffer",await new Promise((C,r)=>{n.addEventListener("open",()=>C(),{once:!0}),n.addEventListener("error",()=>r(Error("bunite preload ws connect failed")),{once:!0})});let p=Uint8Array.from(atob(__buniteSecretKeyBase64),(C)=>C.charCodeAt(0)),m=await wn(Tn(n),p),o=_n({transport:Dn(m),mode:"native",origin:location.origin});return hn=o,o})();return te=e,e.catch(()=>{if(te===e)te=null}),e}var Ce=window;Ce.__bunite??={};Ce.__buniteWebviewId=__buniteWebviewId;Ce.__buniteRpcSocketPort=__buniteRpcSocketPort;Ce.host??={};Ce.host.bootstrap=async(e,n)=>(await $e()).bootstrap(e,n);Ce.host.serve=async(e)=>{(await $e()).serve(e)};Ce.host.runtime=async()=>(await $e()).runtime();Ce.host.releaseRef=async(e)=>{(await $e()).releaseRef(e)};
|
|
1
|
+
var y8=Symbol.for("bunite.rpc.CallDef"),k8=Symbol.for("bunite.rpc.StreamDef"),S8=Symbol.for("bunite.rpc.CapDef"),v8=Symbol.for("bunite.rpc.CapRefToken"),h8=Symbol.for("bunite.rpc.CapArrayToken"),m8=Symbol.for("bunite.rpc.CapRecordToken"),z$=Symbol.for("bunite.rpc.Schema");function c_(_){return{[v8]:!0,cap:_}}c_.array=(_)=>({[h8]:!0,cap:_});c_.record=(_)=>({[m8]:!0,cap:_});var o=c_;function A_(_){return typeof _==="object"&&_!==null&&_[v8]===!0}function U_(_){return typeof _==="object"&&_!==null&&_[h8]===!0}function T_(_){return typeof _==="object"&&_!==null&&_[m8]===!0}function B_(_){return typeof _==="object"&&_!==null&&_[y8]===!0}function z_(_){return typeof _==="object"&&_!==null&&_[k8]===!0}function T(_){return{[y8]:!0,idempotent:!!_?.idempotent,returns:_?.returns}}function P_(_){return{[k8]:!0,hint:_?.hint}}function a(_,$,H){return{[S8]:!0,name:_,version:H?.version!=null?String(H.version):void 0,methods:$,disposal:H?.disposal??void 0}}function V_(_){return typeof _==="object"&&_!==null&&_[S8]===!0}function n_(_){return typeof _==="object"&&_!==null&&_[z$]===!0}var s_;try{s_=new TextDecoder}catch(_){}var G,c,Z=0;var t8=[],i_=t8,a_=0,j={},E,K_,d=0,r=0,g,$_,l=[],V,f8={useRecords:!1,mapsAsObjects:!0};class b_{}var t_=new b_;t_.name="MessagePack 0xC1";var Q_=!1,g8=2,p8,l8,u8;class t{constructor(_){if(_){if(_.useRecords===!1&&_.mapsAsObjects===void 0)_.mapsAsObjects=!0;if(_.sequential&&_.trusted!==!1){if(_.trusted=!0,!_.structures&&_.useRecords!=!1){if(_.structures=[],!_.maxSharedStructures)_.maxSharedStructures=0}}if(_.structures)_.structures.sharedLength=_.structures.length;else if(_.getStructures)(_.structures=[]).uninitialized=!0,_.structures.sharedLength=0;if(_.int64AsNumber)_.int64AsType="number"}Object.assign(this,_)}unpack(_,$){if(G)return X$(()=>{return w_(),this?this.unpack(_,$):t.prototype.unpack.call(f8,_,$)});if(!_.buffer&&_.constructor===ArrayBuffer)_=typeof Buffer<"u"?Buffer.from(_):new Uint8Array(_);if(typeof $==="object")c=$.end||_.length,Z=$.start||0;else Z=0,c=$>-1?$:_.length;a_=0,r=0,K_=null,i_=t8,g=null,G=_;try{V=_.dataView||(_.dataView=new DataView(_.buffer,_.byteOffset,_.byteLength))}catch(H){if(G=null,_ instanceof Uint8Array)throw H;throw Error("Source must be a Uint8Array or Buffer but was a "+(_&&typeof _=="object"?_.constructor.name:typeof _))}if(this instanceof t){if(j=this,this.structures)return E=this.structures,E_($);else if(!E||E.length>0)E=[]}else if(j=f8,!E||E.length>0)E=[];return E_($)}unpackMultiple(_,$){let H,X=0;try{Q_=!0;let K=_.length,Q=this?this.unpack(_,K):j_.unpack(_,K);if($){if($(Q,X,Z)===!1)return;while(Z<K)if(X=Z,$(E_(),X,Z)===!1)return}else{H=[Q];while(Z<K)X=Z,H.push(E_());return H}}catch(K){throw K.lastPosition=X,K.values=H,K}finally{Q_=!1,w_()}}_mergeStructures(_,$){if(l8)_=l8.call(this,_);if(_=_||[],Object.isFrozen(_))_=_.map((H)=>H.slice(0));for(let H=0,X=_.length;H<X;H++){let K=_[H];if(K){if(K.isShared=!0,H>=32)K.highByte=H-32>>5}}_.sharedLength=_.length;for(let H in $||[])if(H>=0){let X=_[H],K=$[H];if(K){if(X)(_.restoreStructures||(_.restoreStructures=[]))[H]=X;_[H]=K}}return this.structures=_}decode(_,$){return this.unpack(_,$)}}function E_(_){try{if(!j.trusted&&!Q_){let H=E.sharedLength||0;if(H<E.length)E.length=H}let $;if(j.randomAccessStructure&&G[Z]<64&&G[Z]>=32&&p8){if($=p8(G,Z,c,j),G=null,!(_&&_.lazy)&&$)$=$.toJSON();Z=c}else $=h();if(g)Z=g.postBundlePosition,g=null;if(Q_)E.restoreStructures=null;if(Z==c){if(E&&E.restoreStructures)d8();if(E=null,G=null,$_)$_=null}else if(Z>c)throw Error("Unexpected end of MessagePack data");else if(!Q_){let H;try{H=JSON.stringify($,(X,K)=>typeof K==="bigint"?`${K}n`:K).slice(0,100)}catch(X){H="(JSON view not available "+X+")"}throw Error("Data read, but end of buffer not reached "+H)}return $}catch($){if(E&&E.restoreStructures)d8();if(w_(),$ instanceof RangeError||$.message.startsWith("Unexpected end of buffer")||Z>c)$.incomplete=!0;throw $}}function d8(){for(let _ in E.restoreStructures)E[_]=E.restoreStructures[_];E.restoreStructures=null}function h(){let _=G[Z++];if(_<160)if(_<128)if(_<64)return _;else{let $=E[_&63]||j.getStructures&&e8()[_&63];if($){if(!$.read)$.read=e_($,_&63);return $.read()}else return _}else if(_<144)if(_-=128,j.mapsAsObjects){let $={};for(let H=0;H<_;H++){let X=$$();if(X==="__proto__")X="__proto_";$[X]=h()}return $}else{let $=new Map;for(let H=0;H<_;H++)$.set(h(),h());return $}else{_-=144;let $=Array(_);for(let H=0;H<_;H++)$[H]=h();if(j.freezeData)return Object.freeze($);return $}else if(_<192){let $=_-160;if(r>=Z)return K_.slice(Z-d,(Z+=$)-d);if(r==0&&c<140){let H=$<16?_8($):_$($);if(H!=null)return H}return r_($)}else{let $;switch(_){case 192:return null;case 193:if(g)if($=h(),$>0)return g[1].slice(g.position1,g.position1+=$);else return g[0].slice(g.position0,g.position0-=$);return t_;case 194:return!1;case 195:return!0;case 196:if($=G[Z++],$===void 0)throw Error("Unexpected end of buffer");return o_($);case 197:return $=V.getUint16(Z),Z+=2,o_($);case 198:return $=V.getUint32(Z),Z+=4,o_($);case 199:return F_(G[Z++]);case 200:return $=V.getUint16(Z),Z+=2,F_($);case 201:return $=V.getUint32(Z),Z+=4,F_($);case 202:if($=V.getFloat32(Z),j.useFloat32>2){let H=x_[(G[Z]&127)<<1|G[Z+1]>>7];return Z+=4,(H*$+($>0?0.5:-0.5)>>0)/H}return Z+=4,$;case 203:return $=V.getFloat64(Z),Z+=8,$;case 204:return G[Z++];case 205:return $=V.getUint16(Z),Z+=2,$;case 206:return $=V.getUint32(Z),Z+=4,$;case 207:if(j.int64AsType==="number")$=V.getUint32(Z)*4294967296,$+=V.getUint32(Z+4);else if(j.int64AsType==="string")$=V.getBigUint64(Z).toString();else if(j.int64AsType==="auto"){if($=V.getBigUint64(Z),$<=BigInt(2)<<BigInt(52))$=Number($)}else $=V.getBigUint64(Z);return Z+=8,$;case 208:return V.getInt8(Z++);case 209:return $=V.getInt16(Z),Z+=2,$;case 210:return $=V.getInt32(Z),Z+=4,$;case 211:if(j.int64AsType==="number")$=V.getInt32(Z)*4294967296,$+=V.getUint32(Z+4);else if(j.int64AsType==="string")$=V.getBigInt64(Z).toString();else if(j.int64AsType==="auto"){if($=V.getBigInt64(Z),$>=BigInt(-2)<<BigInt(52)&&$<=BigInt(2)<<BigInt(52))$=Number($)}else $=V.getBigInt64(Z);return Z+=8,$;case 212:if($=G[Z++],$==114)return a8(G[Z++]&63);else{let H=l[$];if(H)if(H.read)return Z++,H.read(h());else if(H.noBuffer)return Z++,H();else return H(G.subarray(Z,++Z));else throw Error("Unknown extension "+$)}case 213:if($=G[Z],$==114)return Z++,a8(G[Z++]&63,G[Z++]);else return F_(2);case 214:return F_(4);case 215:return F_(8);case 216:return F_(16);case 217:if($=G[Z++],r>=Z)return K_.slice(Z-d,(Z+=$)-d);return V$($);case 218:if($=V.getUint16(Z),Z+=2,r>=Z)return K_.slice(Z-d,(Z+=$)-d);return E$($);case 219:if($=V.getUint32(Z),Z+=4,r>=Z)return K_.slice(Z-d,(Z+=$)-d);return w$($);case 220:return $=V.getUint16(Z),Z+=2,n8($);case 221:return $=V.getUint32(Z),Z+=4,n8($);case 222:return $=V.getUint16(Z),Z+=2,o8($);case 223:return $=V.getUint32(Z),Z+=4,o8($);default:if(_>=224)return _-256;if(_===void 0){let H=Error("Unexpected end of MessagePack data");throw H.incomplete=!0,H}throw Error("Unknown MessagePack token "+_)}}}var P$=/^[a-zA-Z_$][a-zA-Z\d_$]*$/;function e_(_,$){function H(){if(H.count++>g8){let K;try{K=_.read=Function("r","return function(){return "+(j.freezeData?"Object.freeze":"")+"({"+_.map((Q)=>Q==="__proto__"?"__proto_:r()":P$.test(Q)?Q+":r()":"["+JSON.stringify(Q)+"]:r()").join(",")+"})}")(h)}catch(Q){return g8=1/0,H()}if(_.highByte===0)_.read=c8($,_.read);return K()}let X={};for(let K=0,Q=_.length;K<Q;K++){let Y=_[K];if(Y==="__proto__")Y="__proto_";X[Y]=h()}if(j.freezeData)return Object.freeze(X);return X}if(H.count=0,_.highByte===0)return c8($,H);return H}var c8=(_,$)=>{return function(){let H=G[Z++];if(H===0)return $();let X=_<32?-(_+(H<<5)):_+(H<<5),K=E[X]||e8()[X];if(!K)throw Error("Record id is not defined for "+X);if(!K.read)K.read=e_(K,_);return K.read()}};function e8(){let _=X$(()=>{return G=null,j.getStructures()});return E=j._mergeStructures(_,E)}var r_=R_,V$=R_,E$=R_,w$=R_;function R_(_){let $;if(_<16){if($=_8(_))return $}if(_>64&&s_)return s_.decode(G.subarray(Z,Z+=_));let H=Z+_,X=[];$="";while(Z<H){let K=G[Z++];if((K&128)===0)X.push(K);else if((K&224)===192){let Q=G[Z++]&63,Y=(K&31)<<6|Q;if(Y<128)X.push(65533);else X.push(Y)}else if((K&240)===224){let Q=G[Z++]&63,Y=G[Z++]&63,N=(K&31)<<12|Q<<6|Y;if(N<2048||N>=55296&&N<=57343)X.push(65533);else X.push(N)}else if((K&248)===240){let Q=G[Z++]&63,Y=G[Z++]&63,N=G[Z++]&63,C=(K&7)<<18|Q<<12|Y<<6|N;if(C<65536||C>1114111)X.push(65533);else if(C>65535)C-=65536,X.push(C>>>10&1023|55296),C=56320|C&1023,X.push(C);else X.push(C)}else X.push(65533);if(X.length>=4096)$+=f.apply(String,X),X.length=0}if(X.length>0)$+=f.apply(String,X);return $}function n8(_){let $=Array(_);for(let H=0;H<_;H++)$[H]=h();if(j.freezeData)return Object.freeze($);return $}function o8(_){if(j.mapsAsObjects){let $={};for(let H=0;H<_;H++){let X=$$();if(X==="__proto__")X="__proto_";$[X]=h()}return $}else{let $=new Map;for(let H=0;H<_;H++)$.set(h(),h());return $}}var f=String.fromCharCode;function _$(_){let $=Z,H=Array(_);for(let X=0;X<_;X++){let K=G[Z++];if((K&128)>0){Z=$;return}H[X]=K}return f.apply(String,H)}function _8(_){if(_<4)if(_<2)if(_===0)return"";else{let $=G[Z++];if(($&128)>1){Z-=1;return}return f($)}else{let $=G[Z++],H=G[Z++];if(($&128)>0||(H&128)>0){Z-=2;return}if(_<3)return f($,H);let X=G[Z++];if((X&128)>0){Z-=3;return}return f($,H,X)}else{let $=G[Z++],H=G[Z++],X=G[Z++],K=G[Z++];if(($&128)>0||(H&128)>0||(X&128)>0||(K&128)>0){Z-=4;return}if(_<6)if(_===4)return f($,H,X,K);else{let Q=G[Z++];if((Q&128)>0){Z-=5;return}return f($,H,X,K,Q)}else if(_<8){let Q=G[Z++],Y=G[Z++];if((Q&128)>0||(Y&128)>0){Z-=6;return}if(_<7)return f($,H,X,K,Q,Y);let N=G[Z++];if((N&128)>0){Z-=7;return}return f($,H,X,K,Q,Y,N)}else{let Q=G[Z++],Y=G[Z++],N=G[Z++],C=G[Z++];if((Q&128)>0||(Y&128)>0||(N&128)>0||(C&128)>0){Z-=8;return}if(_<10)if(_===8)return f($,H,X,K,Q,Y,N,C);else{let L=G[Z++];if((L&128)>0){Z-=9;return}return f($,H,X,K,Q,Y,N,C,L)}else if(_<12){let L=G[Z++],z=G[Z++];if((L&128)>0||(z&128)>0){Z-=10;return}if(_<11)return f($,H,X,K,Q,Y,N,C,L,z);let B=G[Z++];if((B&128)>0){Z-=11;return}return f($,H,X,K,Q,Y,N,C,L,z,B)}else{let L=G[Z++],z=G[Z++],B=G[Z++],w=G[Z++];if((L&128)>0||(z&128)>0||(B&128)>0||(w&128)>0){Z-=12;return}if(_<14)if(_===12)return f($,H,X,K,Q,Y,N,C,L,z,B,w);else{let y=G[Z++];if((y&128)>0){Z-=13;return}return f($,H,X,K,Q,Y,N,C,L,z,B,w,y)}else{let y=G[Z++],v=G[Z++];if((y&128)>0||(v&128)>0){Z-=14;return}if(_<15)return f($,H,X,K,Q,Y,N,C,L,z,B,w,y,v);let p=G[Z++];if((p&128)>0){Z-=15;return}return f($,H,X,K,Q,Y,N,C,L,z,B,w,y,v,p)}}}}}function s8(){let _=G[Z++],$;if(_<192)$=_-160;else switch(_){case 217:$=G[Z++];break;case 218:$=V.getUint16(Z),Z+=2;break;case 219:$=V.getUint32(Z),Z+=4;break;default:throw Error("Expected string")}return R_($)}function o_(_){return j.copyBuffers?Uint8Array.prototype.slice.call(G,Z,Z+=_):G.subarray(Z,Z+=_)}function F_(_){let $=G[Z++];if(l[$]){let H;return l[$](G.subarray(Z,H=Z+=_),(X)=>{Z=X;try{return h()}finally{Z=H}})}else throw Error("Unknown extension type "+$)}var i8=Array(4096);function $$(){let _=G[Z++];if(_>=160&&_<192){if(_=_-160,r>=Z)return K_.slice(Z-d,(Z+=_)-d);else if(!(r==0&&c<180))return r_(_)}else return Z--,H$(h());let $=(_<<5^(_>1?V.getUint16(Z):_>0?G[Z]:0))&4095,H=i8[$],X=Z,K=Z+_-3,Q,Y=0;if(H&&H.bytes==_){while(X<K){if(Q=V.getUint32(X),Q!=H[Y++]){X=1879048192;break}X+=4}K+=3;while(X<K)if(Q=G[X++],Q!=H[Y++]){X=1879048192;break}if(X===K)return Z=X,H.string;K-=3,X=Z}H=[],i8[$]=H,H.bytes=_;while(X<K)Q=V.getUint32(X),H.push(Q),X+=4;K+=3;while(X<K)Q=G[X++],H.push(Q);let N=_<16?_8(_):_$(_);if(N!=null)return H.string=N;return H.string=r_(_)}function H$(_){if(typeof _==="string")return _;if(typeof _==="number"||typeof _==="boolean"||typeof _==="bigint")return _.toString();if(_==null)return _+"";if(j.allowArraysInMapKeys&&Array.isArray(_)&&_.flat().every(($)=>["string","number","boolean","bigint"].includes(typeof $)))return _.flat().toString();throw Error(`Invalid property type for record: ${typeof _}`)}var a8=(_,$)=>{let H=h().map(H$),X=_;if($!==void 0)_=_<32?-(($<<5)+_):($<<5)+_,H.highByte=$;let K=E[_];if(K&&(K.isShared||Q_))(E.restoreStructures||(E.restoreStructures=[]))[_]=K;return E[_]=H,H.read=e_(H,X),H.read()};l[0]=()=>{};l[0].noBuffer=!0;l[66]=(_)=>{let $=_.byteLength%8||8,H=BigInt(_[0]&128?_[0]-256:_[0]);for(let X=1;X<$;X++)H<<=BigInt(8),H+=BigInt(_[X]);if(_.byteLength!==$){let X=new DataView(_.buffer,_.byteOffset,_.byteLength),K=(Q,Y)=>{let N=Y-Q;if(N<=40){let B=X.getBigUint64(Q);for(let w=Q+8;w<Y;w+=8)B<<=BigInt(64),B|=X.getBigUint64(w);return B}let C=Q+(N>>4<<3),L=K(Q,C),z=K(C,Y);return L<<BigInt((Y-C)*8)|z};H=H<<BigInt((X.byteLength-$)*8)|K($,X.byteLength)}return H};var r8={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError,AggregateError:typeof AggregateError==="function"?AggregateError:null};l[101]=()=>{let _=h();if(!r8[_[0]]){let $=Error(_[1],{cause:_[2]});return $.name=_[0],$}return r8[_[0]](_[1],{cause:_[2]})};l[105]=(_)=>{if(j.structuredClone===!1)throw Error("Structured clone extension is disabled");let $=V.getUint32(Z-4);if(!$_)$_=new Map;let H=G[Z],X;if(H>=144&&H<160||H==220||H==221)X=[];else if(H>=128&&H<144||H==222||H==223)X=new Map;else if((H>=199&&H<=201||H>=212&&H<=216)&&G[Z+1]===115)X=new Set;else X={};let K={target:X};$_.set($,K);let Q=h();if(!K.used)return K.target=Q;else Object.assign(X,Q);if(X instanceof Map)for(let[Y,N]of Q.entries())X.set(Y,N);if(X instanceof Set)for(let Y of Array.from(Q))X.add(Y);return X};l[112]=(_)=>{if(j.structuredClone===!1)throw Error("Structured clone extension is disabled");let $=V.getUint32(Z-4),H=$_.get($);return H.used=!0,H.target};l[115]=()=>new Set(h());var $8=["Int8","Uint8","Uint8Clamped","Int16","Uint16","Int32","Uint32","Float32","Float64","BigInt64","BigUint64"].map((_)=>_+"Array"),b$=typeof globalThis==="object"?globalThis:window;l[116]=(_)=>{let $=_[0],H=Uint8Array.prototype.slice.call(_,1).buffer,X=$8[$];if(!X){if($===16)return H;if($===17)return new DataView(H);throw Error("Could not find typed array for code "+$)}return new b$[X](H)};l[120]=()=>{let _=h();return new RegExp(_[0],_[1])};var x$=[];l[98]=(_)=>{let $=(_[0]<<24)+(_[1]<<16)+(_[2]<<8)+_[3],H=Z;return Z+=$-_.length,g=x$,g=[s8(),s8()],g.position0=0,g.position1=0,g.postBundlePosition=Z,Z=H,h()};l[255]=(_)=>{if(_.length==4)return new Date((_[0]*16777216+(_[1]<<16)+(_[2]<<8)+_[3])*1000);else if(_.length==8)return new Date(((_[0]<<22)+(_[1]<<14)+(_[2]<<6)+(_[3]>>2))/1e6+((_[3]&3)*4294967296+_[4]*16777216+(_[5]<<16)+(_[6]<<8)+_[7])*1000);else if(_.length==12)return new Date(((_[0]<<24)+(_[1]<<16)+(_[2]<<8)+_[3])/1e6+((_[4]&128?-281474976710656:0)+_[6]*1099511627776+_[7]*4294967296+_[8]*16777216+(_[9]<<16)+(_[10]<<8)+_[11])*1000);else return new Date("invalid")};function X$(_){if(u8)u8();let $=c,H=Z,X=a_,K=d,Q=r,Y=K_,N=i_,C=$_,L=g,z=new Uint8Array(G.slice(0,c)),B=E,w=E.slice(0,E.length),y=j,v=Q_,p=_();return c=$,Z=H,a_=X,d=K,r=Q,K_=Y,i_=N,$_=C,g=L,G=z,Q_=v,E=B,E.splice(0,E.length,...w),j=y,V=new DataView(G.buffer,G.byteOffset,G.byteLength),p}function w_(){G=null,$_=null,E=null}function K$(_){if(_.unpack)l[_.type]=_.unpack;else l[_.type]=_}var x_=Array(147);for(let _=0;_<256;_++)x_[_]=+("1e"+Math.floor(45.15-_*0.30103));var j_=new t({useRecords:!1}),j$=j_.unpack,I$=j_.unpackMultiple,y$=j_.unpack;var k$=new Float32Array(1),YH=new Uint8Array(k$.buffer,0,4);var y_;try{y_=new TextEncoder}catch(_){}var k_,S_,D_=typeof Buffer<"u",I_=D_?function(_){return Buffer.allocUnsafeSlow(_)}:Uint8Array,D$=D_?Buffer:Uint8Array,Q$=D_?4294967296:2144337920,D,J_,I,F=0,u,S=null,S$,v$=21760,h$=/[\u0080-\uFFFF]/,Y_=Symbol("record-id");class O_ extends t{constructor(_){super(_);this.offset=0;let $,H,X,K,Q,Y=D$.prototype.utf8Write?function(O,W){return D.utf8Write(O,W,D.byteLength-W)}:y_&&y_.encodeInto?function(O,W){return y_.encodeInto(O,D.subarray(W)).written}:!1,N=this;if(!_)_={};let C=_&&_.sequential,L=_.structures||_.saveStructures,z=_.maxSharedStructures;if(z==null)z=L?32:0;if(z>8160)throw Error("Maximum maxSharedStructure is 8160");if(_.structuredClone&&_.moreTypes==null)this.moreTypes=!0;let B=_.maxOwnStructures;if(B==null)B=L?32:64;if(!this.structures&&_.useRecords!=!1)this.structures=[];let w=z>32||B+z>64,y=z+64,v=z+B+64;if(v>8256)throw Error("Maximum maxSharedStructure + maxOwnStructure is 8192");let p=[],m=0,e=0;this.pack=this.encode=function(O,W){if(!D)D=new I_(8192),I=D.dataView||(D.dataView=new DataView(D.buffer,0,8192)),F=0;if(u=D.length-10,u-F<2048)D=new I_(D.length),I=D.dataView||(D.dataView=new DataView(D.buffer,0,D.length)),u=D.length-10,F=0;else F=F+7&2147483640;if(H=F,W&R$)F+=W&255;if(Q=N.structuredClone?new Map:null,N.bundleStrings&&typeof O!=="string")S=[],S.size=1/0;else S=null;if(K=N.structures,K){if(K.uninitialized)K=N._mergeStructures(N.getStructures());let q=K.sharedLength||0;if(q>z)throw Error("Shared structures is larger than maximum shared structures, try increasing maxSharedStructures to "+K.sharedLength);if(!K.transitions){K.transitions=Object.create(null);for(let R=0;R<q;R++){let A=K[R];if(!A)continue;let U,M=K.transitions;for(let b=0,x=A.length;b<x;b++){let i=A[b];if(U=M[i],!U)U=M[i]=Object.create(null);M=U}M[Y_]=R+64}this.lastNamedStructuresLength=q}if(!C)K.nextId=q+64}if(X)X=!1;let J;try{if(N.randomAccessStructure&&O&&typeof O==="object")if(O.constructor===Object)I8(O);else if(O.constructor!==Map&&!Array.isArray(O)&&!S_.some((R)=>O instanceof R))I8(O.toJSON?O.toJSON():O);else k(O);else k(O);let q=S;if(S)F$(H,k,0);if(Q&&Q.idsToInsert){let R=Q.idsToInsert.sort((b,x)=>b.offset>x.offset?1:-1),A=R.length,U=-1;while(q&&A>0){let b=R[--A].offset+H;if(b<q.stringsPosition+H&&U===-1)U=0;if(b>q.position+H){if(U>=0)U+=6}else{if(U>=0)I.setUint32(q.position+H,I.getUint32(q.position+H)+U),U=-1;q=q.previous,A++}}if(U>=0&&q)I.setUint32(q.position+H,I.getUint32(q.position+H)+U);if(F+=R.length*6,F>u)__(F);N.offset=F;let M=m$(D.subarray(H,F),R);return Q=null,M}if(N.offset=F,W&N$)return D.start=H,D.end=F,D;return D.subarray(H,F)}catch(q){throw J=q,q}finally{if(K){if(L_(),X&&N.saveStructures){let q=K.sharedLength||0,R=D.subarray(H,F),A=f$(K,N);if(!J){if(N.saveStructures(A,A.isCompatible)===!1)return N.pack(O,W);if(N.lastNamedStructuresLength=q,D.length>1073741824)D=null;return R}}}if(D.length>1073741824)D=null;if(W&q$)F=H}};let L_=()=>{if(e<10)e++;let O=K.sharedLength||0;if(K.length>O&&!C)K.length=O;if(m>1e4){if(K.transitions=null,e=0,m=0,p.length>0)p=[]}else if(p.length>0&&!C){for(let W=0,J=p.length;W<J;W++)p[W][Y_]=0;p=[]}},u_=(O)=>{var W=O.length;if(W<16)D[F++]=144|W;else if(W<65536)D[F++]=220,D[F++]=W>>8,D[F++]=W&255;else D[F++]=221,I.setUint32(F,W),F+=4;for(let J=0;J<W;J++)k(O[J])},k=(O)=>{if(F>u)D=__(F);var W=typeof O,J;if(W==="string"){let q=O.length;if(S&&q>=4&&q<4096){if((S.size+=q)>v$){let M,b=(S[0]?S[0].length*3+S[1].length:0)+10;if(F+b>u)D=__(F+b);let x;if(S.position)x=S,D[F]=200,F+=3,D[F++]=98,M=F-H,F+=4,F$(H,k,0),I.setUint16(M+H-3,F-H-M);else D[F++]=214,D[F++]=98,M=F-H,F+=4;S=["",""],S.previous=x,S.size=0,S.position=M}let U=h$.test(O);S[U?0:1]+=O,D[F++]=193,k(U?-q:q);return}let R;if(q<32)R=1;else if(q<256)R=2;else if(q<65536)R=3;else R=5;let A=q*3;if(F+A>u)D=__(F+A);if(q<64||!Y){let U,M,b,x=F+R;for(U=0;U<q;U++)if(M=O.charCodeAt(U),M<128)D[x++]=M;else if(M<2048)D[x++]=M>>6|192,D[x++]=M&63|128;else if((M&64512)===55296&&((b=O.charCodeAt(U+1))&64512)===56320)M=65536+((M&1023)<<10)+(b&1023),U++,D[x++]=M>>18|240,D[x++]=M>>12&63|128,D[x++]=M>>6&63|128,D[x++]=M&63|128;else D[x++]=M>>12|224,D[x++]=M>>6&63|128,D[x++]=M&63|128;J=x-F-R}else J=Y(O,F+R);if(J<32)D[F++]=160|J;else if(J<256){if(R<2)D.copyWithin(F+2,F+1,F+1+J);D[F++]=217,D[F++]=J}else if(J<65536){if(R<3)D.copyWithin(F+3,F+2,F+2+J);D[F++]=218,D[F++]=J>>8,D[F++]=J&255}else{if(R<5)D.copyWithin(F+5,F+3,F+3+J);D[F++]=219,I.setUint32(F,J),F+=4}F+=J}else if(W==="number")if(O>>>0===O)if(O<32||O<128&&this.useRecords===!1||O<64&&!this.randomAccessStructure)D[F++]=O;else if(O<256)D[F++]=204,D[F++]=O;else if(O<65536)D[F++]=205,D[F++]=O>>8,D[F++]=O&255;else D[F++]=206,I.setUint32(F,O),F+=4;else if(O>>0===O)if(O>=-32)D[F++]=256+O;else if(O>=-128)D[F++]=208,D[F++]=O+256;else if(O>=-32768)D[F++]=209,I.setInt16(F,O),F+=2;else D[F++]=210,I.setInt32(F,O),F+=4;else{let q;if((q=this.useFloat32)>0&&O<4294967296&&O>=-2147483648){D[F++]=202,I.setFloat32(F,O);let R;if(q<4||(R=O*x_[(D[F]&127)<<1|D[F+1]>>7])>>0===R){F+=4;return}else F--}D[F++]=203,I.setFloat64(F,O),F+=8}else if(W==="object"||W==="function")if(!O)D[F++]=192;else{if(Q){let R=Q.get(O);if(R){if(!R.id){let A=Q.idsToInsert||(Q.idsToInsert=[]);R.id=A.push(R)}D[F++]=214,D[F++]=112,I.setUint32(F,R.id),F+=4;return}else Q.set(O,{offset:F-H})}let q=O.constructor;if(q===Object)M_(O);else if(q===Array)u_(O);else if(q===Map)if(this.mapAsEmptyObject)D[F++]=128;else{if(J=O.size,J<16)D[F++]=128|J;else if(J<65536)D[F++]=222,D[F++]=J>>8,D[F++]=J&255;else D[F++]=223,I.setUint32(F,J),F+=4;for(let[R,A]of O)k(R),k(A)}else{for(let R=0,A=k_.length;R<A;R++){let U=S_[R];if(O instanceof U){let M=k_[R];if(M.write){if(M.type)D[F++]=212,D[F++]=M.type,D[F++]=0;let q_=M.write.call(this,O);if(q_===O)if(Array.isArray(O))u_(O);else M_(O);else k(q_);return}let b=D,x=I,i=F;D=null;let X_;try{X_=M.pack.call(this,O,(q_)=>{if(D=b,b=null,F+=q_,F>u)__(F);return{target:D,targetView:I,position:F-q_}},k)}finally{if(b)D=b,I=x,F=i,u=D.length-10}if(X_){if(X_.length+F>u)__(X_.length+F);F=Z$(X_,D,F,M.type)}return}}if(Array.isArray(O))u_(O);else{if(O.toJSON){let R=O.toJSON();if(R!==O)return k(R)}if(W==="function")return k(this.writeFunction&&this.writeFunction(O));M_(O)}}}else if(W==="boolean")D[F++]=O?195:194;else if(W==="bigint"){if(O<9223372036854776000&&O>=-9223372036854776000)D[F++]=211,I.setBigInt64(F,O);else if(O<18446744073709552000&&O>0)D[F++]=207,I.setBigUint64(F,O);else if(this.largeBigIntToFloat)D[F++]=203,I.setFloat64(F,Number(O));else if(this.largeBigIntToString)return k(O.toString());else if(this.useBigIntExtension||this.moreTypes){let q=O<0?BigInt(-1):BigInt(0),R;if(O>>BigInt(65536)===q){let A=BigInt(18446744073709552000)-BigInt(1),U=[];while(!0){if(U.push(O&A),O>>BigInt(63)===q)break;O>>=BigInt(64)}R=new Uint8Array(new BigUint64Array(U).buffer),R.reverse()}else{let A=O<0,U=(A?~O:O).toString(16);if(U.length%2)U="0"+U;else if(parseInt(U.charAt(0),16)>=8)U="00"+U;if(D_)R=Buffer.from(U,"hex");else{R=new Uint8Array(U.length/2);for(let M=0;M<R.length;M++)R[M]=parseInt(U.slice(M*2,M*2+2),16)}if(A)for(let M=0;M<R.length;M++)R[M]=~R[M]}if(R.length+F>u)__(R.length+F);F=Z$(R,D,F,66);return}else throw RangeError(O+" was too large to fit in MessagePack 64-bit integer format, use useBigIntExtension, or set largeBigIntToFloat to convert to float-64, or set largeBigIntToString to convert to string");F+=8}else if(W==="undefined")if(this.encodeUndefinedAsNil)D[F++]=192;else D[F++]=212,D[F++]=0,D[F++]=0;else throw Error("Unknown type: "+W)},w8=this.variableMapSize||this.coercibleKeyAsNumber||this.skipValues?(O)=>{let W;if(this.skipValues){W=[];for(let R in O)if((typeof O.hasOwnProperty!=="function"||O.hasOwnProperty(R))&&!this.skipValues.includes(O[R]))W.push(R)}else W=Object.keys(O);let J=W.length;if(J<16)D[F++]=128|J;else if(J<65536)D[F++]=222,D[F++]=J>>8,D[F++]=J&255;else D[F++]=223,I.setUint32(F,J),F+=4;let q;if(this.coercibleKeyAsNumber)for(let R=0;R<J;R++){q=W[R];let A=Number(q);k(isNaN(A)?q:A),k(O[q])}else for(let R=0;R<J;R++)k(q=W[R]),k(O[q])}:(O)=>{D[F++]=222;let W=F-H;F+=2;let J=0;for(let q in O)if(typeof O.hasOwnProperty!=="function"||O.hasOwnProperty(q))k(q),k(O[q]),J++;if(J>65535)throw Error('Object is too large to serialize with fast 16-bit map size, use the "variableMapSize" option to serialize this object');D[W+++H]=J>>8,D[W+H]=J&255},b8=this.useRecords===!1?w8:_.progressiveRecords&&!w?(O)=>{let W,J=K.transitions||(K.transitions=Object.create(null)),q=F++-H,R;for(let A in O)if(typeof O.hasOwnProperty!=="function"||O.hasOwnProperty(A)){if(W=J[A],W)J=W;else{let U=Object.keys(O),M=J;J=K.transitions;let b=0;for(let x=0,i=U.length;x<i;x++){let X_=U[x];if(W=J[X_],!W)W=J[X_]=Object.create(null),b++;J=W}if(q+H+1==F)F--,d_(J,U,b);else j8(J,U,q,b);R=!0,J=M[A]}k(O[A])}if(!R){let A=J[Y_];if(A)D[q+H]=A;else j8(J,Object.keys(O),q,0)}}:(O)=>{let W,J=K.transitions||(K.transitions=Object.create(null)),q=0;for(let A in O)if(typeof O.hasOwnProperty!=="function"||O.hasOwnProperty(A)){if(W=J[A],!W)W=J[A]=Object.create(null),q++;J=W}let R=J[Y_];if(R)if(R>=96&&w)D[F++]=((R-=96)&31)+96,D[F++]=R>>5;else D[F++]=R;else d_(J,J.__keys__||Object.keys(O),q);for(let A in O)if(typeof O.hasOwnProperty!=="function"||O.hasOwnProperty(A))k(O[A])},x8=typeof this.useRecords=="function"&&this.useRecords,M_=x8?(O)=>{x8(O)?b8(O):w8(O)}:b8,__=(O)=>{let W;if(O>16777216){if(O-H>Q$)throw Error("Packed buffer would be larger than maximum buffer size");W=Math.min(Q$,Math.round(Math.max((O-H)*(O>67108864?1.25:2),4194304)/4096)*4096)}else W=(Math.max(O-H<<2,D.length-1)>>12)+1<<12;let J=new I_(W);if(I=J.dataView||(J.dataView=new DataView(J.buffer,0,W)),O=Math.min(O,D.length),D.copy)D.copy(J,0,H,O);else J.set(D.slice(H,O));return F-=H,H=0,u=J.length-10,D=J},d_=(O,W,J)=>{let q=K.nextId;if(!q)q=64;if(q<y&&this.shouldShareStructure&&!this.shouldShareStructure(W)){if(q=K.nextOwnId,!(q<v))q=y;K.nextOwnId=q+1}else{if(q>=v)q=y;K.nextId=q+1}let R=W.highByte=q>=96&&w?q-96>>5:-1;if(O[Y_]=q,O.__keys__=W,K[q-64]=W,q<y)if(W.isShared=!0,K.sharedLength=q-63,X=!0,R>=0)D[F++]=(q&31)+96,D[F++]=R;else D[F++]=q;else{if(R>=0)D[F++]=213,D[F++]=114,D[F++]=(q&31)+96,D[F++]=R;else D[F++]=212,D[F++]=114,D[F++]=q;if(J)m+=e*J;if(p.length>=B)p.shift()[Y_]=0;p.push(O),k(W)}},j8=(O,W,J,q)=>{let R=D,A=F,U=u,M=H;if(D=J_,F=0,H=0,!D)J_=D=new I_(8192);u=D.length-10,d_(O,W,q),J_=D;let b=F;if(D=R,F=A,u=U,H=M,b>1){let x=F+b-1;if(x>u)__(x);let i=J+H;D.copyWithin(i+b,i+1,F),D.set(J_.slice(0,b),i),F=x}else D[J+H]=J_[0]},I8=(O)=>{let W=S$(O,D,H,F,K,__,(J,q,R)=>{if(R)return X=!0;F=q;let A=D;if(k(J),L_(),A!==D)return{position:F,targetView:I,target:D};return F},this);if(W===0)return M_(O);F=W}}useBuffer(_){D=_,D.dataView||(D.dataView=new DataView(D.buffer,D.byteOffset,D.byteLength)),I=D.dataView,F=0}set position(_){F=_}get position(){return F}clearSharedData(){if(this.structures)this.structures=[];if(this.typedStructs)this.typedStructs=[]}}S_=[Date,Set,Error,RegExp,ArrayBuffer,Object.getPrototypeOf(Uint8Array.prototype).constructor,DataView,b_];k_=[{pack(_,$,H){let X=_.getTime()/1000;if((this.useTimestamp32||_.getMilliseconds()===0)&&X>=0&&X<4294967296){let{target:K,targetView:Q,position:Y}=$(6);K[Y++]=214,K[Y++]=255,Q.setUint32(Y,X)}else if(X>0&&X<4294967296){let{target:K,targetView:Q,position:Y}=$(10);K[Y++]=215,K[Y++]=255,Q.setUint32(Y,_.getMilliseconds()*4000000+(X/1000/4294967296>>0)),Q.setUint32(Y+4,X)}else if(isNaN(X)){if(this.onInvalidDate)return $(0),H(this.onInvalidDate());let{target:K,targetView:Q,position:Y}=$(3);K[Y++]=212,K[Y++]=255,K[Y++]=255}else{let{target:K,targetView:Q,position:Y}=$(15);K[Y++]=199,K[Y++]=12,K[Y++]=255,Q.setUint32(Y,_.getMilliseconds()*1e6),Q.setBigInt64(Y+4,BigInt(Math.floor(X)))}}},{pack(_,$,H){if(this.setAsEmptyObject)return $(0),H({});let X=Array.from(_),{target:K,position:Q}=$(this.moreTypes?3:0);if(this.moreTypes)K[Q++]=212,K[Q++]=115,K[Q++]=0;H(X)}},{pack(_,$,H){let{target:X,position:K}=$(this.moreTypes?3:0);if(this.moreTypes)X[K++]=212,X[K++]=101,X[K++]=0;H([_.name,_.message,_.cause])}},{pack(_,$,H){let{target:X,position:K}=$(this.moreTypes?3:0);if(this.moreTypes)X[K++]=212,X[K++]=120,X[K++]=0;H([_.source,_.flags])}},{pack(_,$){if(this.moreTypes)H8(_,16,$);else X8(D_?Buffer.from(_):new Uint8Array(_),$)}},{pack(_,$){let H=_.constructor;if(H!==D$&&this.moreTypes)H8(_,$8.indexOf(H.name),$);else X8(_,$)}},{pack(_,$){if(this.moreTypes)H8(_,17,$);else X8(D_?Buffer.from(_):new Uint8Array(_),$)}},{pack(_,$){let{target:H,position:X}=$(1);H[X]=193}}];function H8(_,$,H,X){let K=_.byteLength;if(K+1<256){var{target:Q,position:Y}=H(4+K);Q[Y++]=199,Q[Y++]=K+1}else if(K+1<65536){var{target:Q,position:Y}=H(5+K);Q[Y++]=200,Q[Y++]=K+1>>8,Q[Y++]=K+1&255}else{var{target:Q,position:Y,targetView:N}=H(7+K);Q[Y++]=201,N.setUint32(Y,K+1),Y+=4}if(Q[Y++]=116,Q[Y++]=$,!_.buffer)_=new Uint8Array(_);Q.set(new Uint8Array(_.buffer,_.byteOffset,_.byteLength),Y)}function X8(_,$){let H=_.byteLength;var X,K;if(H<256){var{target:X,position:K}=$(H+2);X[K++]=196,X[K++]=H}else if(H<65536){var{target:X,position:K}=$(H+3);X[K++]=197,X[K++]=H>>8,X[K++]=H&255}else{var{target:X,position:K,targetView:Q}=$(H+5);X[K++]=198,Q.setUint32(K,H),K+=4}X.set(_,K)}function Z$(_,$,H,X){let K=_.length;switch(K){case 1:$[H++]=212;break;case 2:$[H++]=213;break;case 4:$[H++]=214;break;case 8:$[H++]=215;break;case 16:$[H++]=216;break;default:if(K<256)$[H++]=199,$[H++]=K;else if(K<65536)$[H++]=200,$[H++]=K>>8,$[H++]=K&255;else $[H++]=201,$[H++]=K>>24,$[H++]=K>>16&255,$[H++]=K>>8&255,$[H++]=K&255}return $[H++]=X,$.set(_,H),H+=K,H}function m$(_,$){let H,X=$.length*6,K=_.length-X;while(H=$.pop()){let{offset:Q,id:Y}=H;_.copyWithin(Q+X,Q,K),X-=6;let N=Q+X;_[N++]=214,_[N++]=105,_[N++]=Y>>24,_[N++]=Y>>16&255,_[N++]=Y>>8&255,_[N++]=Y&255,K=Q}return _}function F$(_,$,H){if(S.length>0){I.setUint32(S.position+_,F+H-S.position-_),S.stringsPosition=F-_;let X=S;S=null,$(X[0]),$(X[1])}}function K8(_){if(_.Class){if(!_.pack&&!_.write)throw Error("Extension has no pack or write function");if(_.pack&&!_.type)throw Error("Extension has no type (numeric code to identify the extension)");S_.unshift(_.Class),k_.unshift(_)}K$(_)}function f$(_,$){return _.isCompatible=(H)=>{let X=!H||($.lastNamedStructuresLength||0)===H.length;if(!X)$._mergeStructures(H);return X},_}var O$=new O_({useRecords:!1}),g$=O$.pack,p$=O$.pack;var N$=512,q$=1024,R$=2048;var G$=80;class s{capId;constructor(_){this.capId=_}}var l$=new Set(["hello","goaway","call","result","cancel","stream","drop","cap_revoked"]);function Q8(_){if(typeof _!=="object"||_===null)return!1;let $=_,H=$.op;if(typeof H!=="string"||!l$.has(H))return!1;switch(H){case"hello":return $.v===1&&($.mode==="native"||$.mode==="web")&&Array.isArray($.features)&&typeof $.maxBytes==="number"&&typeof $.origin==="string";case"goaway":return $.reason===void 0||typeof $.reason==="string";case"call":return typeof $.id==="number"&&typeof $.method==="string"&&typeof $.target==="object"&&$.target!==null&&$.target.kind==="cap"&&typeof $.target.id==="number";case"result":return typeof $.id==="number"&&($.ok===!0||$.ok===!1);case"cancel":return typeof $.id==="number";case"stream":return typeof $.id==="number"&&typeof $.ev==="string"&&($.ev==="next"||$.ev==="credit"||$.ev==="end"||$.ev==="error");case"drop":return Array.isArray($.caps);case"cap_revoked":if(!Array.isArray($.capIds))return!1;for(let X of $.capIds)if(typeof X!=="number"||!Number.isInteger(X)||X<0||X>4294967295)return!1;return!0}}var J$=!1;function u$(){if(J$)return;J$=!0,K8({Class:s,type:G$,pack:(_)=>d$(_.capId),unpack:(_)=>new s(n$(_))})}function Z8(){return u$(),{packr:new O_({useRecords:!0,sequential:!0,moreTypes:!0}),unpackr:new t({useRecords:!0,sequential:!0,moreTypes:!0})}}function d$(_){let $=new Uint8Array(5),H=_>>>0,X=0;while(H>=128)$[X++]=H&127|128,H>>>=7;return $[X++]=H&127,$.subarray(0,X)}var c$=5;function n$(_){let $=0,H=0,X=Math.min(_.length,c$);for(let K=0;K<X;K++){let Q=_[K];if($|=(Q&127)<<H,(Q&128)===0)return $>>>0;H+=7}throw Error("Truncated or oversize varuint")}var F8=67108864,Y8=1,v_="bunite.",h_="bootstrap";class P extends Error{code;details;retry;constructor(_){super(_.message??_.code);this.name="IpcError",this.code=_.code,this.details=_.details,this.retry=_.retry}toStatus(){return{code:this.code,message:this.message,details:this.details,retry:this.retry}}}var m_=a("bunite.BrowserWindow",{focus:T(),close:T(),setBounds:T(),setTitle:T(),id:T({idempotent:!0}),label:T({idempotent:!0})}),D8=a("bunite.Window",{create:T({returns:o(m_)}),list:T({returns:o.array(m_),idempotent:!0}),focus:T(),close:T()}),f_=a("bunite.FileRef",{text:T({idempotent:!0}),bytes:T({idempotent:!0}),path:T({idempotent:!0}),revoke:T()},{disposal:{method:"revoke"}}),O8=a("bunite.Dialogs",{openFile:T({returns:o.array(f_)}),saveFile:T({returns:o(f_)}),showMessage:T()}),N8=a("bunite.Clipboard",{readText:T({idempotent:!0}),writeText:T(),readBytes:T({idempotent:!0}),writeBytes:T()}),q8=a("bunite.Shell",{openExternal:T(),showItemInFolder:T()}),R8=a("bunite.Surface",{init:T(),resize:T(),remove:T(),setHidden:T(),setMasks:T(),setAllPassthrough:T(),bringAllVisiblesToFront:T(),navigate:T(),goBack:T(),reload:T(),didNavigate:P_()}),G_=a("bunite.Runtime",{window:T({returns:o(D8),idempotent:!0}),dialogs:T({returns:o(O8),idempotent:!0}),clipboard:T({returns:o(N8),idempotent:!0}),shell:T({returns:o(q8),idempotent:!0}),appName:T({idempotent:!0}),appVersion:T({idempotent:!0}),theme:T({idempotent:!0}),themeWatch:P_(),surface:T({returns:o(R8),idempotent:!0})}),H_={Runtime:1,Window:2,Dialogs:3,FileRef:4,Clipboard:5,Shell:6,BrowserWindow:7,Surface:8},o$=new Map([[G_,H_.Runtime],[D8,H_.Window],[O8,H_.Dialogs],[f_,H_.FileRef],[N8,H_.Clipboard],[q8,H_.Shell],[m_,H_.BrowserWindow],[R8,H_.Surface]]);function J8(_){return o$.get(_)}var p_=0,C8=1,C$=0,L$=1,N_=2,L8=128,M8=1024,M$=1024,s$=500,i$=32,a$=8,r$=1024;function t$(_){let $=_?.initialBudget;if(typeof $!=="number"||!Number.isFinite($)||!Number.isInteger($)||$<1)return i$;return Math.min($,r$)}var g_=null;class A8{entries=new Map;nextCapId=N_;capLimit;constructor(_=M8){this.capLimit=_}install(_,$){if(this.entries.has(_))throw Error(`cap-id ${_} already installed`);let H={capId:_,...$};return this.entries.set(_,H),H}allocate(_){if(this.entries.size>=this.capLimit)throw new P({code:"resource_exhausted",message:`cap-table limit ${this.capLimit}`,details:{reason:"max_caps_per_connection"}});let $=this.nextCapId++;while(this.entries.has($))$=this.nextCapId++;return this.install($,_)}get(_){return this.entries.get(_)}release(_,$=1){let H=this.entries.get(_);if(!H)return!1;if(H.refCount=Math.max(0,H.refCount-$),H.refCount===0&&_>=N_)return this.entries.delete(_),!0;return!1}delete(_){if(_<N_)return!1;return this.entries.delete(_)}clear(){this.entries.clear(),this.nextCapId=N_}size(){return this.entries.size}values(){return this.entries.values()}}var e$={origin:"",topOrigin:"",partition:"default",isAppRes:!1,isMainFrame:!1,userGesture:!1,level:"untrusted"},A$=Symbol("bunite.rpc.ExportedCap"),W$=Symbol("bunite.rpc.CapProxyMeta");function _H(_){return typeof _==="object"&&_!==null&&_[A$]===!0}var $H=typeof FinalizationRegistry<"u"?new FinalizationRegistry((_)=>{if(_.dropped())return;let $=_.connRef.deref();if(!$||$.closed)return;$._dropFromFinalizer(_.capId)}):{register:()=>{}};class U${transport;capTable;pending=new Map;clientStreams=new Map;serverStreams=new Map;serverCallChildren=new Map;serverActiveCalls=new Map;registry=new Map;rootInstances=new Map;revokedCapIds=new Set;closeHandlers=new Set;observers={};nextCallId=1;remoteHello=null;remoteReady;resolveRemoteReady;rejectRemoteReady;closed_=!1;maxBytes;maxInFlightCalls;mode;origin;features;attestation;peerId;policy;constructor(_){this.transport=_.transport,this.mode=_.mode,this.origin=_.origin,this.features=_.features??[],this.maxBytes=_.maxBytes??F8,this.maxInFlightCalls=_.maxInFlightCalls??M$,this.attestation=_.attestation??e$,this.peerId=_.peerId??"peer",this.policy=_.policy,this.capTable=new A8(_.capLimit??M8),this.capTable.install(p_,{typeId:C$,cap:null,impl:null,refCount:1}),this.capTable.install(C8,{typeId:L$,cap:G_,impl:_.runtime??null,refCount:1}),this.remoteReady=new Promise(($,H)=>{this.resolveRemoteReady=$,this.rejectRemoteReady=H}),this.remoteReady.catch(()=>{}),this.transport.setReceive(($)=>this.handleFrame($)),this.transport.send({op:"hello",v:Y8,mode:this.mode,features:this.features,maxBytes:this.maxBytes,origin:this.origin})}get closed(){return this.closed_}onClose(_){return this.closeHandlers.add(_),()=>this.closeHandlers.delete(_)}on(_,$){let H=this.observers[_];if(!H)H=new Set,this.observers[_]=H;return H.add($),()=>{H.delete($)}}emitObs(_,$){let H=this.observers[_];if(!H||H.size===0)return;for(let X of H)try{X($)}catch{}}serve(_,$,H){this.assertNotFrameworkName(_.name);let X=H?.ifExists??"throw";if(this.registry.get(_.name))switch(X){case"throw":throw new P({code:"already_exists",message:`cap "${_.name}" already served`,details:{reason:"name_collision"}});case"skip":return this.makeHandle([]);case"replace":return this.replace(_,$),this.makeHandle([_.name])}return this.registry.set(_.name,{cap:_,impl:$,version:_.version}),this.makeHandle([_.name])}makeHandle(_){let $={names:_,[Symbol.dispose]:()=>this.unserve($)};return $}serveAll(_,$,H){let X=H?.ifExists??"throw";for(let Q of Object.keys(_.roots)){let Y=_.roots[Q];this.assertNotFrameworkName(Y.name);let N=this.registry.get(Y.name);if(N){if(X==="throw")throw new P({code:"already_exists",message:`cap "${Y.name}" already served`,details:{reason:"name_collision"}});if(X==="replace"&&N.version!==Y.version)throw new P({code:"failed_precondition",message:`version mismatch on replace for "${Y.name}" (current "${N.version}", new "${Y.version}")`,details:{reason:"version_mismatch"}})}}let K=[];for(let Q of Object.keys(_.roots)){let Y=_.roots[Q],N=$[Q];if(this.serve(Y,N,{ifExists:X}).names.length>0)K.push(Y.name)}return this.makeHandle(K)}unserve(_){let $=V_(_)?[_.name]:Array.from(_.names),H=[];for(let X of $){if(!this.registry.delete(X))continue;let K=this.rootInstances.get(X);if(K!==void 0){let Q=this.capTable.get(K);if(Q)this.invokeServerDisposal(Q);this.rootInstances.delete(X),this.capTable.delete(K),H.push(K)}}if(H.length>0)this.transport.send({op:"cap_revoked",capIds:H}),this.emitObs("revoke",{capIds:H,reason:"unserve"})}replace(_,$){let H=this.registry.get(_.name);if(!H)throw new P({code:"not_found",message:`cap "${_.name}" not served`});if(H.version!==_.version)throw new P({code:"failed_precondition",message:`version mismatch (current "${H.version}", new "${_.version}")`,details:{reason:"version_mismatch"}});H.impl=$,H.cap=_;let X=this.rootInstances.get(_.name);if(X!==void 0){let K=this.capTable.get(X);if(K)K.impl=$,K.cap=_}this.emitObs("revoke",{capIds:X!==void 0?[X]:[],reason:"replace"})}assertNotFrameworkName(_){if(_.startsWith(v_))throw new P({code:"already_exists",message:`cap name "${_}" uses reserved prefix "${v_}"`,details:{reason:"reserved_namespace"}})}runtimeProxy=null;runtime(){if(!this.runtimeProxy)this.runtimeProxy=this.makeCapProxy(G_,C8);return this.runtimeProxy}async bootstrap(_){if(V_(_))return this._bootstrapCap(_);if(n_(_))return this._bootstrapSchema(_);throw new P({code:"invalid_argument",message:"bootstrap target must be CapDef or Schema"})}async _bootstrapCap(_){await this.remoteReady;let $={name:_.name};if(_.version!=null)$.version=_.version;let H=await this.sendCallTyped(p_,h_,$,void 0);if(!(H instanceof s))throw new P({code:"invalid_argument",message:"bootstrap did not return a CapRef"});return this.makeCapProxy(_,H.capId)}async _bootstrapSchema(_){let $=Object.keys(_.roots),H=await Promise.allSettled($.map((Q)=>this._bootstrapCap(_.roots[Q]))),X=H.find((Q)=>Q.status==="rejected");if(X){for(let Q of H)if(Q.status==="fulfilled")try{this.releaseRef(Q.value)}catch{}throw X.reason}let K={};for(let Q=0;Q<$.length;Q++)K[$[Q]]=H[Q].value;return K}handleFrame(_){if(this.closed_)return;switch(_.op){case"hello":this.handleHello(_);return;case"call":this.handleCall(_);return;case"result":this.handleResult(_);return;case"cancel":this.handleCancel(_);return;case"stream":this.handleStreamFrame(_);return;case"drop":this.handleDrop(_);return;case"cap_revoked":this.handleCapRevoked(_);return;case"goaway":this.handleGoaway(_);return;default:this.handleUnknownFrame(_);return}}handleUnknownFrame(_){let $=_?.id;if(typeof $==="number"){this.transport.send({op:"result",id:$,ok:!1,error:{code:"invalid_argument",message:"unknown opcode"}});return}this.transport.send({op:"goaway",reason:"invalid_argument",error:{code:"invalid_argument",message:"unknown opcode"}}),this.shutdown("invalid_argument")}handleHello(_){this.remoteHello=_,this.resolveRemoteReady(_)}handleGoaway(_){this.rejectRemoteReady(new P(_.error??{code:"unavailable",message:_.reason??"peer goaway"})),this.shutdown(_.reason??"remote goaway")}handleCapRevoked(_){for(let $ of _.capIds){this.revokedCapIds.add($);let H=new P({code:"failed_precondition",message:"cap revoked",details:{reason:"revoked"}});for(let[X,K]of this.pending)if(K.capId===$){if(this.pending.delete(X),K.timer)clearTimeout(K.timer);K.reject(H)}for(let[X,K]of this.clientStreams)if(K.capId===$)this.clientStreams.delete(X),K.fail(H)}}async handleCall(_){if(_.target.id===p_&&_.method===h_){await this.handleBootstrap(_);return}let $=this.capTable.get(_.target.id);if(!$)return this.emitObs("call",{capId:_.target.id,method:_.method,callId:_.id,result:"not_found"}),this.sendError(_.id,"not_found",`cap-id ${_.target.id} not found`);let H=$.cap;if(!H||!$.impl)return this.emitObs("call",{capId:_.target.id,method:_.method,callId:_.id,result:"not_found"}),this.sendError(_.id,"not_found","cap has no impl");let X=H.methods[_.method];if(!X)return this.emitObs("call",{capId:_.target.id,capName:H.name,method:_.method,callId:_.id,result:"not_found"}),this.sendError(_.id,"not_found",`method "${_.method}" on cap "${H.name}"`);let K=$.impl[_.method];if(typeof K!=="function")return this.emitObs("call",{capId:_.target.id,capName:H.name,method:_.method,callId:_.id,result:"not_found"}),this.sendError(_.id,"not_found",`method "${_.method}" has no handler`);if(this.serverActiveCalls.size+this.serverStreams.size>=this.maxInFlightCalls)return this.emitObs("call",{capId:_.target.id,capName:H.name,method:_.method,callId:_.id,result:"resource_exhausted"}),this.sendError(_.id,"resource_exhausted",`in-flight calls limit ${this.maxInFlightCalls}`,{reason:"max_concurrent_calls"});await this.invokeServerMethod(_,H,X,K)}async handleBootstrap(_){let $=_.args??{},H=$.name;if(typeof H!=="string")return this.emitObs("bootstrap",{name:String(H),attestation:this.attestation,result:"invalid_argument"}),this.sendError(_.id,"invalid_argument","bootstrap requires {name: string}");let X=$.version!=null?String($.version):void 0,K=this.registry.get(H);if(!K)return this.emitObs("bootstrap",{name:H,version:X,attestation:this.attestation,result:"not_found"}),this.sendError(_.id,"not_found",`cap "${H}" not served`);let Q=K.version;if(Q!=null&&X!=null&&Q!==X)return this.emitObs("bootstrap",{name:H,version:X,attestation:this.attestation,result:"version_mismatch"}),this.sendError(_.id,"failed_precondition",`version mismatch (server "${Q}", client "${X}")`,{reason:"version_mismatch"});if(this.policy)try{if(!await this.policy(H,this.attestation))return this.emitObs("bootstrap",{name:H,version:X,attestation:this.attestation,result:"denied"}),this.sendError(_.id,"failed_precondition","policy denied",{reason:"unauthorized"})}catch(N){return this.emitObs("error",{phase:"policy",error:N instanceof Error?N:Error(String(N))}),this.emitObs("bootstrap",{name:H,version:X,attestation:this.attestation,result:"internal"}),this.sendError(_.id,"internal","policy threw")}let Y=this.rootInstances.get(H);if(Y!==void 0){let N=this.capTable.get(Y);if(N)N.refCount+=1;else this.rootInstances.delete(H),Y=void 0}if(Y===void 0)try{Y=this.capTable.allocate({typeId:J8(K.cap)??L8,cap:K.cap,impl:K.impl,refCount:1}).capId,this.rootInstances.set(H,Y)}catch(N){if(N instanceof P){let C=N.code==="resource_exhausted"?"resource_exhausted":"internal";return this.emitObs("bootstrap",{name:H,version:X,attestation:this.attestation,result:C}),this.sendError(_.id,N.code,N.message,N.details)}throw N}this.emitObs("bootstrap",{name:H,version:X,attestation:this.attestation,result:"ok",capId:Y}),this.transport.send({op:"result",id:_.id,ok:!0,value:new s(Y)})}async invokeServerMethod(_,$,H,X){let K=this.makeCallCtx(_);if(z_(H)){let Q=t$(H.hint);try{let Y=()=>X(_.args,K),N=g_,L=(N?()=>N.run({callId:_.id},Y):Y)();this.runServerStream(_.id,L,K,Q,$,_.method,_.target.id)}catch(Y){this.emitObs("stream",{capId:_.target.id,capName:$.name,method:_.method,callId:_.id,event:"error"}),this.transport.send({op:"stream",id:_.id,ev:"error",error:G8(Y)})}return}if(B_(H)){let Q=performance.now(),Y=H.idempotent?void 0:this.armServerDeadline(_,K);this.serverActiveCalls.set(_.id,{ctrl:K._ctrl,capId:_.target.id,capName:$.name,method:_.method,startedAt:Q});let N=HH(H.returns),C=()=>Promise.resolve(X(_.args,K)),L=g_,z=L?()=>L.run({callId:_.id},C):C;try{let B=await z();if(Y)clearTimeout(Y);if(!this.serverActiveCalls.delete(_.id))return;let w=N(B);this.transport.send({op:"result",id:_.id,ok:!0,value:w}),this.emitObs("call",{capId:_.target.id,capName:$.name,method:_.method,callId:_.id,durationMs:performance.now()-Q,result:"ok"})}catch(B){if(Y)clearTimeout(Y);if(!this.serverActiveCalls.delete(_.id))return;let w=G8(B);this.sendErrorFromStatus(_.id,w),this.emitObs("call",{capId:_.target.id,capName:$.name,method:_.method,callId:_.id,durationMs:performance.now()-Q,result:w.code})}return}this.sendError(_.id,"not_found","unknown method kind")}armServerDeadline(_,$){let H=_.meta?.deadlineMs;if(!H)return;return setTimeout(()=>{$._ctrl.abort()},H)}makeCallCtx(_){let $=new AbortController;return{callId:_.id,peerId:this.peerId,attestation:this.attestation,signal:$.signal,deadline:_.meta?.deadlineMs,context:_.meta?.context,_ctrl:$,exportCap:(X,K)=>this.exportCap(X,K)}}exportCap(_,$){let H=J8(_)??L8,X=this.capTable.allocate({typeId:H,cap:_,impl:$,refCount:1});return{[A$]:!0,cap:_,capId:X.capId,typeId:X.typeId}}runServerStream(_,$,H,X,K,Q,Y){let N=$[Symbol.asyncIterator](),C=H._ctrl,L={iter:N,abort:C,cancelled:!1,credit:X,creditWaker:null,capId:Y,capName:K.name,method:Q,callId:_,count:0};this.serverStreams.set(_,L),this.emitObs("stream",{capId:Y,capName:K.name,method:Q,callId:_,event:"start"});let z=()=>{if(L.credit>0||L.cancelled)return Promise.resolve();return new Promise((w)=>{L.creditWaker=w})};(async()=>{let w=!1;try{while(!L.cancelled){if(L.credit===0)await z();if(L.cancelled)break;let{done:y,value:v}=await N.next();if(y)break;if(L.cancelled)break;L.credit-=1,L.count+=1,this.transport.send({op:"stream",id:_,ev:"next",value:v})}}catch(y){w=!0,this.transport.send({op:"stream",id:_,ev:"error",error:G8(y)}),this.emitObs("stream",{capId:Y,capName:K.name,method:Q,callId:_,event:"error",count:L.count})}finally{if(!w)this.transport.send({op:"stream",id:_,ev:"end"}),this.emitObs("stream",{capId:Y,capName:K.name,method:Q,callId:_,event:L.cancelled?"cancel":"end",count:L.count});this.serverStreams.delete(_)}})()}handleResult(_){let $=this.pending.get(_.id);if($){if(this.pending.delete(_.id),this.serverCallChildren.delete(_.id),$.timer)clearTimeout($.timer);if(_.ok){let X=$.decodeReturn?$.decodeReturn(_.value):_.value;$.resolve(X)}else $.reject(new P(_.error));return}let H=this.clientStreams.get(_.id);if(H){this.clientStreams.delete(_.id);let X=_.ok?new P({code:"invalid_argument",message:"stream method returned result frame"}):new P(_.error);H.fail(X)}}handleCancel(_){let $=this.serverStreams.get(_.id);if($)$.cancelled=!0,$.abort.abort(),$.iter?.return?.(),this.serverStreams.delete(_.id);let H=this.serverActiveCalls.get(_.id);if(H)this.serverActiveCalls.delete(_.id),H.ctrl.abort(),this.transport.send({op:"result",id:_.id,ok:!1,error:{code:"cancelled",message:_.reason}}),this.emitObs("call",{capId:H.capId,capName:H.capName,method:H.method,callId:_.id,durationMs:performance.now()-H.startedAt,result:"cancelled"});for(let[X,K]of this.serverCallChildren){if(K.parentId!==_.id)continue;if(this.serverCallChildren.delete(X),this.pending.has(X))this.transport.send({op:"cancel",id:X,reason:_.reason})}}releaseRef(_){if(typeof _!=="object"||_===null)return;let $=_[W$];if(!$||$.dropped)return;$.dropped=!0,this.sendDrop($.capId)}sendDrop(_){if(this.closed_)return;if(_<N_)return;this.transport.send({op:"drop",caps:[{id:_,delta:1}]})}handleStreamFrame(_){if(_.ev==="credit"){let H=this.serverStreams.get(_.id);if(!H)return;H.credit+=_.credit?.messages??0;let X=H.creditWaker;H.creditWaker=null,X?.();return}let $=this.clientStreams.get(_.id);if(!$)return;switch(_.ev){case"next":$.push(_.value);return;case"end":$.end(),this.clientStreams.delete(_.id);return;case"error":$.fail(new P(_.error)),this.clientStreams.delete(_.id);return}}handleDrop(_){for(let{id:$,delta:H}of _.caps)if(this.capTable.release($,H)){for(let[K,Q]of this.rootInstances)if(Q===$){this.rootInstances.delete(K);break}}}sendError(_,$,H,X){let K={code:$,message:H};if(X!==void 0)K.details=X;this.transport.send({op:"result",id:_,ok:!1,error:K})}sendErrorFromStatus(_,$){this.transport.send({op:"result",id:_,ok:!1,error:$})}nextId(){return this.nextCallId++}sendCallTyped(_,$,H,X,K,Q){if(this.closed_)return Promise.reject(new P({code:"unavailable",message:"connection closed"}));if(this.revokedCapIds.has(_))return Promise.reject(new P({code:"failed_precondition",message:"cap revoked",details:{reason:"revoked"}}));if(this.pending.size>=this.maxInFlightCalls)return Promise.reject(new P({code:"resource_exhausted",message:`in-flight calls limit ${this.maxInFlightCalls}`,details:{reason:"max_concurrent_calls"}}));let Y=this.nextId();return new Promise((N,C)=>{let L=new AbortController,z={resolve:N,reject:C,abort:L,decodeReturn:X,startedAt:performance.now(),capId:_,method:$,capName:Q,kind:"call"};if(K?.deadlineMs)z.timer=setTimeout(()=>{if(this.pending.delete(Y))this.transport.send({op:"cancel",id:Y,reason:"deadline_exceeded"}),C(new P({code:"deadline_exceeded"}))},K.deadlineMs+s$);this.pending.set(Y,z);let B=K;if(B?.parentCallId===void 0&&g_){let w=g_.getStore();if(w)B={...B??{},parentCallId:w.callId}}if(B?.parentCallId!==void 0)this.serverCallChildren.set(Y,{parentId:B.parentCallId});this.transport.send({op:"call",id:Y,target:{kind:"cap",id:_},method:$,args:H,meta:B})})}openClientStream(_,$,H,X,K){if(this.closed_){let L=W8(_,0,()=>{},()=>{});return L.fail(new P({code:"unavailable",message:"connection closed"})),L.stream}if(this.revokedCapIds.has(_)){let L=W8(_,0,()=>{},()=>{});return L.fail(new P({code:"failed_precondition",message:"cap revoked",details:{reason:"revoked"}})),L.stream}let Q=this.nextId(),C=W8(_,Q,()=>{if(this.clientStreams.delete(Q))this.transport.send({op:"cancel",id:Q,reason:"client_cancel"})},(L)=>{if(this.closed_||!this.clientStreams.has(Q))return;this.transport.send({op:"stream",id:Q,ev:"credit",credit:{messages:L}})});return this.clientStreams.set(Q,C),this.transport.send({op:"call",id:Q,target:{kind:"cap",id:_},method:$,args:H,meta:X}),C.stream}makeCapProxy(_,$){let H={},X={capId:$,dropped:!1};H[W$]=X;let K=()=>{if(X.dropped)return;X.dropped=!0,this.sendDrop($)};for(let Y of Object.keys(_.methods)){let N=_.methods[Y];if(z_(N))H[Y]=(C)=>this.openClientStream($,Y,C,void 0,_.name);else if(B_(N)){let C=XH(N.returns,(L,z)=>this.makeCapProxy(L,z));H[Y]=(L)=>this.sendCallTyped($,Y,L,C,void 0,_.name)}}let Q=_.disposal;if(Q){let Y=this;H[Symbol.dispose]=()=>{try{let N=H[Q.method]?.();if(N&&typeof N.then==="function")N.catch((C)=>Y.emitObs("error",{phase:"dispose",error:C instanceof Error?C:Error(String(C))}))}catch(N){Y.emitObs("error",{phase:"dispose",error:N instanceof Error?N:Error(String(N))})}K()}}if(typeof FinalizationRegistry<"u")$H.register(H,{connRef:new WeakRef(this),capId:$,dropped:()=>X.dropped});return H}_dropFromFinalizer(_){try{this.sendDrop(_)}catch{}}shutdown(_){if(this.closed_)return;this.closed_=!0;for(let $ of this.pending.values()){if($.timer)clearTimeout($.timer);$.reject(new P({code:"unavailable",message:_}))}this.pending.clear();for(let $ of this.clientStreams.values())$.fail(new P({code:"unavailable",message:_}));this.clientStreams.clear();for(let $ of this.serverStreams.values())$.cancelled=!0,$.abort.abort(),$.iter?.return?.();this.serverStreams.clear();for(let $ of this.serverActiveCalls.values())$.ctrl.abort();this.serverActiveCalls.clear();for(let $ of this.capTable.values())this.invokeServerDisposal($);if(this.capTable.clear(),!this.remoteHello)this.rejectRemoteReady(new P({code:"unavailable",message:_}));for(let $ of this.closeHandlers)try{$()}catch{}this.closeHandlers.clear();try{this.transport.close()}catch{}}invokeServerDisposal(_){let $=_.cap;if(!$)return;let H=$.disposal;if(!H)return;let X=_.impl,K=X?.[H.method];if(!K)return;try{K.call(X,void 0,void 0)}catch{}}}function HH(_){if(!_)return(H)=>H;let $=(H,X)=>{if(!_H(H))throw new P({code:"failed_precondition",message:"expected ctx.exportCap return for cap method",details:{reason:"unregistered_cap_return"}});if(H.cap!==X)throw new P({code:"failed_precondition",message:"exported cap type mismatch with method returns",details:{reason:"unregistered_cap_return"}});return new s(H.capId)};if(A_(_))return(H)=>$(H,_.cap);if(U_(_))return(H)=>{if(!Array.isArray(H))throw new P({code:"invalid_argument",message:"expected ExportedCap[] for cap.array method"});return H.map((X)=>$(X,_.cap))};if(T_(_))return(H)=>{if(!H||typeof H!=="object")throw new P({code:"invalid_argument",message:"expected Record<string, ExportedCap> for cap.record method"});let X={};for(let K of Object.keys(H))X[K]=$(H[K],_.cap);return X};return(H)=>H}function XH(_,$){if(!_)return;if(A_(_)){let H=_.cap;return(X)=>{if(!(X instanceof s))throw new P({code:"invalid_argument",message:"expected CapRef"});return $(H,X.capId)}}if(U_(_)){let H=_.cap,X=H.disposal;return(K)=>{if(!Array.isArray(K))throw new P({code:"invalid_argument",message:"expected array"});let Q=K.map((Y)=>{if(!(Y instanceof s))throw new P({code:"invalid_argument",message:"expected CapRef in array"});return $(H,Y.capId)});return KH(Q,X),Q}}if(T_(_)){let H=_.cap;return(X)=>{if(!X||typeof X!=="object")throw new P({code:"invalid_argument",message:"expected record"});let K={};for(let Q of Object.keys(X)){let Y=X[Q];if(!(Y instanceof s))throw new P({code:"invalid_argument",message:"expected CapRef in record"});K[Q]=$(H,Y.capId)}return K}}return}function KH(_,$){if(!$)return;_[Symbol.dispose]=()=>{for(let H of _)H[Symbol.dispose]?.call(H)}}function G8(_){if(_ instanceof P)return _.toStatus();if(_ instanceof Error)return{code:"internal",message:_.message};return{code:"internal",message:String(_)}}function W8(_,$,H,X){let K=[],Q=[],Y=!1,N=null,C=!1,L=0;function z(){if(L+=1,L>=a$)X(L),L=0}function B(){if(K.length>0){let m=K.shift();return z(),{value:m,done:!1}}if(N)return null;if(Y||C)return{value:void 0,done:!0};return null}function w(){let m=B();if(m)return Promise.resolve(m);if(N)return Promise.reject(N);return new Promise((e,L_)=>Q.push({resolve:e,reject:L_}))}function y(){while(Q.length>0){let m=Q.shift(),e=B();if(e){m.resolve(e);continue}if(N){m.reject(N);continue}Q.unshift(m);break}}function v(){if(C||Y||N)return;C=!0,H(),y()}let p={[Symbol.asyncIterator]:()=>({next:w,return:()=>{return v(),Promise.resolve({value:void 0,done:!0})},throw:(m)=>{return v(),Promise.reject(m)}}),[Symbol.dispose]:v,cancel:v};return{capId:_,stream:p,push(m){if(C||Y||N)return;K.push(m),y()},end(){Y=!0,y()},fail(m){N=m,y()}}}function U8(_){return new U$(_)}function T8(_,$={}){let H=Z8(),X;return _.setReceive((K)=>{let Q;try{Q=H.unpackr.unpack(K)}catch(Y){$.onProtocolError?.(`unpack failed: ${Y instanceof Error?Y.message:String(Y)}`),_.close();return}if(!Q8(Q)){$.onProtocolError?.("malformed frame"),_.close();return}X?.(Q)}),{send(K){let Q=H.packr.pack(K);_.send(Q instanceof Uint8Array?Q:new Uint8Array(Q))},setReceive(K){X=K},close(){_.close()}}}function B8(_){if("binaryType"in _)try{_.binaryType="arraybuffer"}catch{}let $,H=(X)=>{if(!$)return;let K=X.data;if(K instanceof Uint8Array){$(K);return}if(K instanceof ArrayBuffer){$(new Uint8Array(K));return}if(typeof Blob<"u"&&K instanceof Blob){K.arrayBuffer().then((Q)=>$?.(new Uint8Array(Q)));return}};return _.addEventListener("message",H),{send(X){_.send(X)},setReceive(X){$=X},close(){_.removeEventListener?.("message",H),_.close?.()}}}function W_(_){let $=new ArrayBuffer(_.byteLength);return new Uint8Array($).set(_),$}async function QH(_){return crypto.subtle.importKey("raw",W_(_),"AES-GCM",!1,["encrypt","decrypt"])}async function z8(_,$){let H=await QH($),X,K=Promise.resolve(),Q=Promise.resolve(),Y=!1,N=()=>{if(!Y)Y=!0,_.close()};return _.setReceive((C)=>{if(Y)return;if(C.length<13||C[0]!==1){N();return}let L=W_(C.subarray(1,13)),z=W_(C.subarray(13));Q=Q.then(async()=>{if(Y)return;try{let B=await crypto.subtle.decrypt({name:"AES-GCM",iv:L},H,z);X?.(new Uint8Array(B))}catch{N()}})}),{send(C){if(Y)return;let L=W_(C);K=K.then(async()=>{if(Y)return;try{let z=crypto.getRandomValues(new Uint8Array(12)),B=W_(z),w=await crypto.subtle.encrypt({name:"AES-GCM",iv:B},H,L),y=new Uint8Array(w),v=new Uint8Array(13+y.byteLength);v[0]=1,v.set(z,1),v.set(y,13),_.send(v)}catch{N()}})},setReceive(C){X=C},close(){N()}}}class ZH{buffer=[];waiters=[];ctrl=new AbortController;cleanup;ended=!1;failure=null;constructor(_){let $=(H)=>{if(this.ended||this.failure)return;let X=this.waiters.shift();if(X){X.resolve({value:H,done:!1});return}this.buffer.push(H)};try{let H=_($,this.ctrl.signal);if(typeof H==="function")this.cleanup=H}catch(H){this.failure=H}}[Symbol.asyncIterator](){return{next:async()=>{if(this.buffer.length>0)return{value:this.buffer.shift(),done:!1};if(this.failure)throw this.failure;if(this.ended)return{value:void 0,done:!0};return new Promise((_,$)=>this.waiters.push({resolve:_,reject:$}))},return:async()=>{return this.dispose(),{value:void 0,done:!0}}}}cancel(){this.dispose()}[Symbol.dispose](){this.dispose()}dispose(){if(this.ended)return;this.ended=!0,this.ctrl.abort();try{this.cleanup?.()}catch{}while(this.waiters.length>0)this.waiters.shift().resolve({value:void 0,done:!0})}}var P8=null;function V8(){if(!P8)P8=host.runtime().then((_)=>_.surface());return P8}function n(_){return V8().then(_).catch(($)=>{if(globalThis.__BUNITE_DEBUG__)console.warn("[bunite] surface call failed",$);return})}class T${element;onBoundsChange;observer=null;rafId=0;lastRect={x:0,y:0,width:0,height:0};dirty=!1;stopped=!1;constructor(_,$){this.element=_,this.onBoundsChange=$}start(){this.observer=new ResizeObserver(()=>this.markDirty()),this.observer.observe(this.element),this.scheduleFrame()}stop(){if(this.stopped=!0,this.observer?.disconnect(),this.observer=null,this.rafId)cancelAnimationFrame(this.rafId),this.rafId=0}markDirty(){this.dirty=!0}scheduleFrame(){if(this.stopped)return;this.rafId=requestAnimationFrame(()=>{this.flush(),this.scheduleFrame()})}flush(){let _=window.devicePixelRatio||1,$=this.element.getBoundingClientRect(),H={x:Math.round($.x*_),y:Math.round($.y*_),width:Math.round($.width*_),height:Math.round($.height*_)};if(!this.dirty&&H.x===this.lastRect.x&&H.y===this.lastRect.y&&H.width===this.lastRect.width&&H.height===this.lastRect.height)return;this.dirty=!1,this.lastRect=H,this.onBoundsChange(H)}}class B$ extends HTMLElement{static observedAttributes=["src"];_surfaceId=null;_syncCtrl=null;_initPromise=null;_aborted=!1;_pendingSrc=null;_syncHidden=!1;_userHidden=!1;_layoutObserver=null;_unsubNavigate=null;constructor(){super()}connectedCallback(){this._aborted=!1,this._syncHidden=!1,this._userHidden=!1;let _=new AbortController;this._unsubNavigate=()=>_.abort(),(async()=>{try{let H=(await V8()).didNavigate();for await(let X of H){if(_.signal.aborted)break;if(X.surfaceId===this._surfaceId)this.dispatchEvent(new CustomEvent("did-navigate",{detail:{url:X.url}}))}}catch($){if(globalThis.__BUNITE_DEBUG__)console.warn("[bunite] didNavigate stream failed",$)}})(),this._waitForLayout()}_waitForLayout(){if(this._layoutObserver)return;let _=()=>{if(!this.isConnected||this._aborted)return!0;let $=this.getBoundingClientRect();if($.width>0&&$.height>0){if(this.getAttribute("src")||this._pendingSrc||"")this.initSurface();return!0}return!1};requestAnimationFrame(()=>{if(_())return;this._layoutObserver=new ResizeObserver(()=>{if(_())this._layoutObserver?.disconnect(),this._layoutObserver=null}),this._layoutObserver.observe(this)})}disconnectedCallback(){if(this._aborted=!0,this._unsubNavigate?.(),this._unsubNavigate=null,this._layoutObserver?.disconnect(),this._layoutObserver=null,this._syncCtrl?.stop(),this._syncCtrl=null,this._surfaceId!=null){let _=this._surfaceId;this._surfaceId=null,n(($)=>$.remove({surfaceId:_}))}else if(this._initPromise)this._initPromise.then((_)=>{n(($)=>$.remove({surfaceId:_.surfaceId}))}).catch(()=>{});this._initPromise=null}attributeChangedCallback(_,$,H){if(_!=="src")return;if(this._surfaceId!=null){let X=this._surfaceId;n((K)=>K.navigate({surfaceId:X,url:H||""}))}else if(this._initPromise)this._pendingSrc=H||"";else if(this.isConnected&&!this._aborted&&H)this._waitForLayout()}setHidden(_){this._userHidden=_,this._applySurfaceHidden()}goBack(){let _=this._surfaceId;if(_!=null)n(($)=>$.goBack({surfaceId:_}))}reload(){let _=this._surfaceId;if(_!=null)n(($)=>$.reload({surfaceId:_}))}navigate(_){this.setAttribute("src",_)}_applySurfaceHidden(){let _=this._surfaceId;if(_==null)return;let $=this._userHidden||this._syncHidden;n((H)=>H.setHidden({surfaceId:_,hidden:$}))}initSurface(){if(this._surfaceId!=null||this._initPromise!=null)return;let _=window.devicePixelRatio||1,$=this.getBoundingClientRect(),H=this._pendingSrc||this.getAttribute("src")||"";this._pendingSrc=null;let X=V8().then((K)=>K.init({src:H,x:Math.round($.x*_),y:Math.round($.y*_),width:Math.round($.width*_),height:Math.round($.height*_),hidden:this._userHidden}));this._initPromise=X,X.then((K)=>{if(this._initPromise!==X)return;if(this._aborted){n((Q)=>Q.remove({surfaceId:K.surfaceId}));return}if(this._surfaceId=K.surfaceId,this._userHidden)this._applySurfaceHidden();if(this._pendingSrc!=null){let Q=this._pendingSrc;this._pendingSrc=null;let Y=this._surfaceId;if(Y!=null)n((N)=>N.navigate({surfaceId:Y,url:Q}))}this._syncCtrl=new T$(this,(Q)=>{let Y=this._surfaceId;if(Y==null)return;if(Q.width===0&&Q.height===0){if(!this._syncHidden)this._syncHidden=!0,this._applySurfaceHidden();return}if(this._syncHidden)this._syncHidden=!1,this._applySurfaceHidden();n((C)=>C.resize({surfaceId:Y,x:Q.x,y:Q.y,w:Q.width,h:Q.height}))}),this._syncCtrl.start()}).catch(()=>{}).finally(()=>{if(this._initPromise===X)this._initPromise=null})}}if(typeof customElements<"u"){customElements.define("bunite-webview",B$);let _=()=>{n(($)=>$.bringAllVisiblesToFront())};document.addEventListener("pointerdown",_,!0),document.addEventListener("dragstart",()=>{n(($)=>$.setAllPassthrough({passthrough:!0}))},!0),document.addEventListener("dragend",()=>{n(($)=>$.setAllPassthrough({passthrough:!1})),_()},!0)}var E8=null,C_=null;function l_(){if(E8)return Promise.resolve(E8);if(C_)return C_;let _=(async()=>{let $=new WebSocket(`ws://localhost:${__buniteRpcSocketPort}/rpc?webviewId=${__buniteWebviewId}`);$.binaryType="arraybuffer",await new Promise((Q,Y)=>{$.addEventListener("open",()=>Q(),{once:!0}),$.addEventListener("error",()=>Y(Error("bunite preload ws connect failed")),{once:!0})});let H=Uint8Array.from(atob(__buniteSecretKeyBase64),(Q)=>Q.charCodeAt(0)),X=await z8(B8($),H),K=U8({transport:T8(X),mode:"native",origin:location.origin});return E8=K,K})();return C_=_,_.catch(()=>{if(C_===_)C_=null}),_}var Z_=window;Z_.__bunite??={};Z_.__buniteWebviewId=__buniteWebviewId;Z_.__buniteRpcSocketPort=__buniteRpcSocketPort;Z_.host??={};Z_.host.bootstrap=async(_)=>{return(await l_()).bootstrap(_)};Z_.host.runtime=async()=>(await l_()).runtime();Z_.host.releaseRef=async(_)=>{(await l_()).releaseRef(_)};Z_.host.getConnection=()=>l_();
|
package/src/preload/runtime.ts
CHANGED
|
@@ -4,10 +4,10 @@ import {
|
|
|
4
4
|
createWebSocketPipe,
|
|
5
5
|
createEncryptedPipe,
|
|
6
6
|
type Connection,
|
|
7
|
+
type CapDef,
|
|
7
8
|
type Schema,
|
|
8
|
-
type
|
|
9
|
+
type SchemaRoots,
|
|
9
10
|
type ClientOf,
|
|
10
|
-
type ServerDescriptor,
|
|
11
11
|
type WebSocketLike,
|
|
12
12
|
} from "../rpc/index";
|
|
13
13
|
|
|
@@ -53,19 +53,17 @@ w.__buniteWebviewId = __buniteWebviewId;
|
|
|
53
53
|
w.__buniteRpcSocketPort = __buniteRpcSocketPort;
|
|
54
54
|
w.host ??= {};
|
|
55
55
|
|
|
56
|
-
w.host.bootstrap = async <
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
): Promise<ClientOf<S["roots"][K]>> => (await ensureConnection()).bootstrap(schema, name);
|
|
60
|
-
|
|
61
|
-
w.host.serve = async <S extends SchemaShape>(descriptor: ServerDescriptor<S>): Promise<void> => {
|
|
62
|
-
(await ensureConnection()).serve(descriptor);
|
|
56
|
+
w.host.bootstrap = async (target: CapDef<any, any> | Schema<SchemaRoots>): Promise<unknown> => {
|
|
57
|
+
const conn = await ensureConnection();
|
|
58
|
+
return (conn.bootstrap as (t: unknown) => Promise<unknown>)(target);
|
|
63
59
|
};
|
|
64
60
|
|
|
65
|
-
w.host.runtime = async () => (await ensureConnection()).runtime()
|
|
61
|
+
w.host.runtime = async () => (await ensureConnection()).runtime() as ClientOf<typeof import("../rpc/framework").RuntimeCap>;
|
|
66
62
|
|
|
67
63
|
w.host.releaseRef = async (proxy: unknown): Promise<void> => {
|
|
68
64
|
(await ensureConnection()).releaseRef(proxy);
|
|
69
65
|
};
|
|
70
66
|
|
|
67
|
+
w.host.getConnection = (): Promise<Connection> => ensureConnection();
|
|
68
|
+
|
|
71
69
|
import "../webview/native";
|