spacewave 0.57.7 → 0.57.8
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/API.md +112 -15
- package/CHANGELOG.md +1 -1
- package/README.md +4 -4
- package/dist/THIRD_PARTY_NOTICES.txt +95 -166
- package/dist/build.json +2 -2
- package/dist/chunks/json-BuGtLL3Z.mjs +2 -0
- package/dist/chunks/node.pb-L2jxLJ0J.mjs +2 -0
- package/dist/engine-worker.mjs +99 -99
- package/dist/index.mjs +1 -1
- package/dist/react.mjs +1 -1
- package/dist/server.mjs +4 -5
- package/dist/types/core/sync/config.d.ts +4 -1
- package/dist/types/packages/spacewave/index.d.ts +4 -0
- package/dist/types/packages/spacewave/react.d.ts +3 -1
- package/dist/types/sdk/sync/app.d.ts +37 -0
- package/dist/types/sdk/sync/query.d.ts +71 -0
- package/dist/types/web/sync/app-hooks.d.ts +31 -0
- package/examples/task-board/package.json +1 -1
- package/examples/task-board/react.tsx +27 -27
- package/package.json +1 -1
- package/dist/chunks/errors-BHnASqFk.mjs +0 -2
- package/dist/chunks/node.pb-ChF26ESv.mjs +0 -2
- package/dist/types/web/sync/index.d.ts +0 -4
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { Server as HTTPServer } from 'node:http';
|
|
2
2
|
import type { DatabaseAccess } from '../../sdk/sync/access.js';
|
|
3
|
+
import type { AppSource } from '../../sdk/sync/app.js';
|
|
3
4
|
import type { MutationHandlers, Principal, Schema, Transaction } from '../../sdk/sync/schema.js';
|
|
4
5
|
export interface Access<P extends Principal> {
|
|
5
6
|
readonly principal: P;
|
|
@@ -9,6 +10,8 @@ export interface Access<P extends Principal> {
|
|
|
9
10
|
}
|
|
10
11
|
export interface ApplicationConfig<S extends Schema, P extends Principal> {
|
|
11
12
|
schema: S;
|
|
13
|
+
/** instance selects one application dataset in the supplied World; defaults to schema.id. */
|
|
14
|
+
instance?: string;
|
|
12
15
|
authorize(access: Access<P>): boolean | Promise<boolean>;
|
|
13
16
|
mutations: MutationHandlers<S, P>;
|
|
14
17
|
limits?: {
|
|
@@ -47,7 +50,7 @@ export interface Listener extends Attachment {
|
|
|
47
50
|
readonly url: string;
|
|
48
51
|
}
|
|
49
52
|
export interface SyncServer<S extends Schema, P extends Principal> extends AsyncDisposable {
|
|
50
|
-
as(principal: P): DatabaseAccess<S>;
|
|
53
|
+
as(principal: P): DatabaseAccess<S> & AppSource<S>;
|
|
51
54
|
admin(scope: string): DatabaseAccess<S>;
|
|
52
55
|
attach(http: HTTPServer, options?: AttachmentOptions): Attachment;
|
|
53
56
|
listen(options?: ListenerOptions): Promise<Listener>;
|
|
@@ -5,3 +5,7 @@ export type { Schema, Principal, MutationContext, MutationHandlers, Transaction,
|
|
|
5
5
|
export { SyncError } from '../../sdk/sync/errors.js';
|
|
6
6
|
export type { SyncErrorCode } from '../../sdk/sync/errors.js';
|
|
7
7
|
export type { JsonValue } from '../../sdk/sync/json.js';
|
|
8
|
+
export { defineApp } from '../../sdk/sync/app.js';
|
|
9
|
+
export type { AppDefinition, AppMutation, AppSource, AppMigration, AppMigrationContext, } from '../../sdk/sync/app.js';
|
|
10
|
+
export { defineQuery } from '../../sdk/sync/query.js';
|
|
11
|
+
export type { QueryContext, QueryDefinition, LiveQuerySnapshot, } from '../../sdk/sync/query.js';
|
|
@@ -1 +1,3 @@
|
|
|
1
|
-
export { createSyncContext } from '../../web/sync/
|
|
1
|
+
export { createSyncContext } from '../../web/sync/react.js';
|
|
2
|
+
export { useAppQuery, useAppMutation } from '../../web/sync/app-hooks.js';
|
|
3
|
+
export type { AppQueryState, AppMutationState, } from '../../web/sync/app-hooks.js';
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { type CallOptions, type Input, type Output, type Validator, type MutationHandlers, type Principal, type MutationContext, type Schema } from './schema.js';
|
|
2
|
+
import type { LiveQuerySnapshot, QueryContext, QueryDefinition } from './query.js';
|
|
3
|
+
/** AppDefinition contains the shared schema and named operations without starting a runtime. */
|
|
4
|
+
export interface AppDefinition<S extends Schema> {
|
|
5
|
+
readonly schema: S;
|
|
6
|
+
readonly mutations: MutationHandlers<S, Principal>;
|
|
7
|
+
readonly migrations: Readonly<Record<number, AppMigration<S>>>;
|
|
8
|
+
}
|
|
9
|
+
/** AppMigrationContext reads original values and writes the new schema in one World transaction. */
|
|
10
|
+
export interface AppMigrationContext<S extends Schema> extends MutationContext<S, Principal> {
|
|
11
|
+
/** previous exposes bounded original records; parse unknown values with the old schema. */
|
|
12
|
+
readonly previous: QueryContext<Schema>;
|
|
13
|
+
}
|
|
14
|
+
/** AppMigration explicitly converts a stored schema version to the declared version. */
|
|
15
|
+
export type AppMigration<S extends Schema> = (context: AppMigrationContext<S>) => Promise<void>;
|
|
16
|
+
/** AppMutation pairs a named operation with its declared input type. */
|
|
17
|
+
export type AppMutation<S extends Schema> = {
|
|
18
|
+
[K in keyof S['mutations'] & string]: {
|
|
19
|
+
kind: 'mutate';
|
|
20
|
+
name: K;
|
|
21
|
+
input: Input<S['mutations'][K]['input']>;
|
|
22
|
+
};
|
|
23
|
+
}[keyof S['mutations'] & string];
|
|
24
|
+
/**
|
|
25
|
+
* defineApp binds typed handlers to a browser-safe schema. Importing a definition
|
|
26
|
+
* opens no storage or connection; hosts bind it to an authorized World instance.
|
|
27
|
+
* Validators may be any Standard Schema v1 implementation, including Zod.
|
|
28
|
+
* Handlers remain functions in the bundled module and are never serialized.
|
|
29
|
+
*/
|
|
30
|
+
export declare function defineApp<const S extends Schema>(schema: S, mutations: MutationHandlers<S, Principal>, migrations?: Readonly<Record<number, AppMigration<S>>>): AppDefinition<S>;
|
|
31
|
+
/** AppSource is the host-independent read, query, and named-operation contract. */
|
|
32
|
+
export interface AppSource<S extends Schema> extends QueryContext<S> {
|
|
33
|
+
/** mutate accepts a typed named operation with a stable retry identity. */
|
|
34
|
+
mutate<K extends keyof S['mutations'] & string>(name: K, input: Input<S['mutations'][K]['input']>, options?: CallOptions): Promise<Output<S['mutations'][K]['output']>>;
|
|
35
|
+
/** watch streams snapshot-bound results for this attachment's lifetime. */
|
|
36
|
+
watch<A extends Validator, R>(definition: QueryDefinition<S, A, R>, args: Input<A>, signal?: AbortSignal): AsyncIterable<LiveQuerySnapshot<R>>;
|
|
37
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { SyncError } from './errors.js';
|
|
2
|
+
import { type JsonValue } from './json.js';
|
|
3
|
+
import type { Output, Schema, TransactionCollection, Validator } from './schema.js';
|
|
4
|
+
/** LiveQuerySnapshot carries a successful value or a terminal query error. */
|
|
5
|
+
export type LiveQuerySnapshot<R> = {
|
|
6
|
+
readonly status: 'current';
|
|
7
|
+
readonly value: R;
|
|
8
|
+
readonly seqno: bigint;
|
|
9
|
+
} | {
|
|
10
|
+
readonly status: 'error';
|
|
11
|
+
readonly error: SyncError;
|
|
12
|
+
};
|
|
13
|
+
/** QueryCollection exposes only snapshot reads to a query callback. */
|
|
14
|
+
export type QueryCollection<V extends Validator> = Pick<TransactionCollection<V>, 'get' | 'scan'>;
|
|
15
|
+
/** QueryContext reads every collection from the same snapshot. */
|
|
16
|
+
export interface QueryContext<S extends Schema> {
|
|
17
|
+
collection<K extends keyof S['collections'] & string>(name: K): QueryCollection<S['collections'][K]>;
|
|
18
|
+
}
|
|
19
|
+
/** QueryDefinition binds validated arguments to a pure snapshot computation. */
|
|
20
|
+
export interface QueryDefinition<S extends Schema, A extends Validator, R> {
|
|
21
|
+
readonly name: string;
|
|
22
|
+
readonly input: A;
|
|
23
|
+
evaluate(context: QueryContext<S>, args: Output<A>): R | Promise<R>;
|
|
24
|
+
}
|
|
25
|
+
/** defineQuery preserves inferred arguments and results without evaluating a query. */
|
|
26
|
+
export declare function defineQuery<S extends Schema, A extends Validator, R>(_schema: S, definition: QueryDefinition<S, A, R>): QueryDefinition<S, A, R>;
|
|
27
|
+
/** RecordDependency tracks presence and the JSON paths actually inspected in one record. */
|
|
28
|
+
export interface RecordDependency {
|
|
29
|
+
readonly key: string;
|
|
30
|
+
readonly paths: readonly (readonly string[])[];
|
|
31
|
+
readonly shapes: readonly (readonly string[])[];
|
|
32
|
+
}
|
|
33
|
+
/** CollectionDependencies retains scan membership and inspected records, including absent keys. */
|
|
34
|
+
export interface CollectionDependencies {
|
|
35
|
+
readonly collection: string;
|
|
36
|
+
readonly prefixes: readonly string[];
|
|
37
|
+
readonly records: readonly RecordDependency[];
|
|
38
|
+
}
|
|
39
|
+
/** QueryEvaluation materializes the result before freezing its complete read set. */
|
|
40
|
+
export interface QueryEvaluation<R> {
|
|
41
|
+
readonly value: R;
|
|
42
|
+
readonly dependencies: readonly CollectionDependencies[];
|
|
43
|
+
}
|
|
44
|
+
/** RecordChange carries accepted before/after values; undefined represents absence. */
|
|
45
|
+
export interface RecordChange {
|
|
46
|
+
readonly collection: string;
|
|
47
|
+
readonly key: string;
|
|
48
|
+
readonly before?: JsonValue;
|
|
49
|
+
readonly after?: JsonValue;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* evaluateQuery traces ordinary property reads, predicates, sorting, and branches.
|
|
53
|
+
* Returning a complete record materializes every returned field. Queries may
|
|
54
|
+
* await snapshot reads; external effects and mutation of read values are forbidden.
|
|
55
|
+
*/
|
|
56
|
+
export declare function evaluateQuery<S extends Schema, R>(source: QueryContext<S>, evaluate: (context: QueryContext<S>) => R | Promise<R>): Promise<QueryEvaluation<R>>;
|
|
57
|
+
/**
|
|
58
|
+
* QueryFilter indexes dependencies once and rejects irrelevant accepted changes.
|
|
59
|
+
* Unknown collection changes invalidate conservatively. Rebuild the filter only
|
|
60
|
+
* after a successful reevaluation so dynamic branches replace their read sets.
|
|
61
|
+
*/
|
|
62
|
+
export declare class QueryFilter {
|
|
63
|
+
private readonly collections;
|
|
64
|
+
constructor(dependencies: readonly CollectionDependencies[]);
|
|
65
|
+
/** watchesKey filters unrelated record addresses before any value is read. */
|
|
66
|
+
watchesKey(collectionName: string, key: string): boolean;
|
|
67
|
+
/** affected reports whether one accepted change can alter the query result. */
|
|
68
|
+
affected(change: RecordChange): boolean;
|
|
69
|
+
/** unknown invalidates a watched collection when no complete change description exists. */
|
|
70
|
+
unknown(collection: string): boolean;
|
|
71
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { AppSource } from '../../sdk/sync/app.js';
|
|
2
|
+
import { SyncError } from '../../sdk/sync/errors.js';
|
|
3
|
+
import type { LiveQuerySnapshot, QueryDefinition } from '../../sdk/sync/query.js';
|
|
4
|
+
import type { Input, Output, Schema, Validator } from '../../sdk/sync/schema.js';
|
|
5
|
+
/** AppQueryState reports the initial read, a current snapshot, or a query failure. */
|
|
6
|
+
export type AppQueryState<R> = {
|
|
7
|
+
readonly status: 'pending';
|
|
8
|
+
} | LiveQuerySnapshot<R>;
|
|
9
|
+
/** useAppQuery shares a function query and releases this subscription on unmount. */
|
|
10
|
+
export declare function useAppQuery<S extends Schema, A extends Validator, R>(source: AppSource<S> | null, query: QueryDefinition<S, A, R>, args: Input<A>): AppQueryState<R>;
|
|
11
|
+
/** AppMutationState retains the request identity needed to retry uncertain acceptance. */
|
|
12
|
+
export type AppMutationState<R> = {
|
|
13
|
+
readonly status: 'idle';
|
|
14
|
+
} | {
|
|
15
|
+
readonly status: 'pending';
|
|
16
|
+
readonly requestId: string;
|
|
17
|
+
} | {
|
|
18
|
+
readonly status: 'accepted';
|
|
19
|
+
readonly requestId: string;
|
|
20
|
+
readonly value: R;
|
|
21
|
+
} | {
|
|
22
|
+
readonly status: 'error';
|
|
23
|
+
readonly requestId: string;
|
|
24
|
+
readonly error: SyncError;
|
|
25
|
+
};
|
|
26
|
+
/** useAppMutation owns one pending intent and retries it with the same identity. */
|
|
27
|
+
export declare function useAppMutation<S extends Schema, K extends keyof S['mutations'] & string>(source: AppSource<S> | null, name: K): {
|
|
28
|
+
submit: (input: Input<S["mutations"][K]["input"]>) => void;
|
|
29
|
+
state: AppMutationState<Output<S["mutations"][K]["output"]>>;
|
|
30
|
+
retry: () => void;
|
|
31
|
+
};
|
|
@@ -43,34 +43,34 @@ function TaskBoard() {
|
|
|
43
43
|
const [writeError, setWriteError] = useState<string | null>(null)
|
|
44
44
|
|
|
45
45
|
/** runWrite exposes an uncertain write's original operation for a later retry. */
|
|
46
|
-
const runWrite = useCallback(
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
setPending(false)
|
|
46
|
+
const runWrite = useCallback(async function runWrite(
|
|
47
|
+
run: () => Promise<unknown>,
|
|
48
|
+
requestId: string,
|
|
49
|
+
): Promise<void> {
|
|
50
|
+
// Suspend new edits and clear the previous write's feedback.
|
|
51
|
+
setPending(true)
|
|
52
|
+
setUncertain(null)
|
|
53
|
+
setWriteError(null)
|
|
54
|
+
|
|
55
|
+
// Keep failed writes recoverable without inserting unaccepted task rows.
|
|
56
|
+
try {
|
|
57
|
+
await run()
|
|
58
|
+
} catch (error) {
|
|
59
|
+
if (error instanceof SyncError && error.code === 'UNCERTAIN') {
|
|
60
|
+
setUncertain({
|
|
61
|
+
requestId,
|
|
62
|
+
message: error.message,
|
|
63
|
+
retry: () => {
|
|
64
|
+
void runWrite(run, requestId)
|
|
65
|
+
},
|
|
66
|
+
})
|
|
67
|
+
} else {
|
|
68
|
+
setWriteError(error instanceof Error ? error.message : String(error))
|
|
70
69
|
}
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
|
|
70
|
+
} finally {
|
|
71
|
+
setPending(false)
|
|
72
|
+
}
|
|
73
|
+
}, [])
|
|
74
74
|
|
|
75
75
|
/** addTask preserves the title and generated IDs until the write is accepted. */
|
|
76
76
|
const addTask = (event: FormEvent<HTMLFormElement>) => {
|
package/package.json
CHANGED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
var e=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports);const t=`ERR_RPC_ABORT`;function n(e){return typeof e==`object`&&e.message===t}var r=class extends Error{rpcService;rpcMethod;rpcError;constructor(e,t,n){super(n),this.name=`RemoteRPCError`,this.rpcService=e,this.rpcMethod=t,this.rpcError=n}};function i(){let e={};return e.promise=new Promise((t,n)=>{e.resolve=t,e.reject=n}),e}var a=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||e-1&e)throw Error(`Max size for a FixedFIFO should be a power of two`);this.buffer=Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]===void 0&&(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},o=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new a(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength==null?1:e.byteLength}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let t=this.head;this.head=t.next=new a(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}},s=class extends Error{type;code;constructor(e,t){super(e??`The operation was aborted`),this.type=`aborted`,this.code=t??`ABORT_ERR`}};function c(e={}){return l(e=>{let t=e.shift();if(t==null)return{done:!0};if(t.error!=null)throw t.error;return{done:t.done===!0,value:t.value}},e)}function l(e,t){t??={};let n=t.onEnd,r=new o,a,c,l,u=i(),d=async()=>{try{return r.isEmpty()?l?{done:!0}:await new Promise((t,n)=>{c=i=>{c=null,r.push(i);try{t(e(r))}catch(e){n(e)}return a}}):e(r)}finally{r.isEmpty()&&queueMicrotask(()=>{u.resolve(),u=i()})}},ee=e=>c==null?(r.push(e),a):c(e),te=e=>(r=new o,c==null?(r.push({error:e}),a):c({error:e})),ne=e=>{if(l)return a;if(t?.objectMode!==!0&&e?.byteLength==null)throw Error(`objectMode was not true but tried to push non-Uint8Array value`);return ee({done:!1,value:e})},f=e=>l?a:(l=!0,e==null?ee({done:!0}):te(e)),re=()=>(r=new o,f(),{done:!0}),ie=e=>(f(e),{done:!0});if(a={[Symbol.asyncIterator](){return this},next:d,return:re,throw:ie,push:ne,end:f,get readableLength(){return r.size},onEmpty:async e=>{let t=e?.signal;if(t?.throwIfAborted(),r.isEmpty())return;let n,i;t!=null&&(n=new Promise((e,n)=>{i=()=>{n(new s)},t.addEventListener(`abort`,i)}));try{await Promise.race([u.promise,n])}finally{i!=null&&t!=null&&t?.removeEventListener(`abort`,i)}}},n==null)return a;let p=a;return a={[Symbol.asyncIterator](){return this},next(){return p.next()},throw(e){return p.throw(e),n!=null&&(n(e),n=void 0),{done:!0}},return(){return p.return(),n!=null&&(n(),n=void 0),{done:!0}},push:ne,end(e){return p.end(e),n!=null&&(n(e),n=void 0),a},get readableLength(){return p.readableLength},onEmpty:e=>p.onEmpty(e)},a}var u=class extends Error{type;code;constructor(e,t,n){super(e??`The operation was aborted`),this.type=`aborted`,this.name=n??`AbortError`,this.code=t??`ABORT_ERR`}};async function d(e,t,n){if(t==null)return e;if(t.aborted)return e.catch(()=>{}),Promise.reject(new u(n?.errorMessage,n?.errorCode,n?.errorName));let r,i=new u(n?.errorMessage,n?.errorCode,n?.errorName);try{return await Promise.race([e,new Promise((e,n)=>{r=()=>{n(i)},t.addEventListener(`abort`,r)})])}finally{r!=null&&t.removeEventListener(`abort`,r)}}var ee=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=i(),this.haveNext=i()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult??await this.haveNext.promise,this.nextResult==null)throw Error(`HaveNext promise resolved but nextResult was undefined`);let e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=i(),e}async throw(e){return this.ended=!0,this.error=e,e!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(e)),{done:!0,value:void 0}}async return(){let e={done:!0,value:void 0};return this.ended=!0,this.nextResult=e,this.haveNext.resolve(),e}async push(e,t){await this._push(e,t)}async end(e,t){e==null?await this._push(void 0,t):await this.throw(e)}async _push(e,t){if(e!=null&&this.ended)throw this.error??Error(`Cannot push value onto an ended pushable`);for(;this.nextResult!=null;)await this.readNext.promise;e==null?(this.ended=!0,this.nextResult={done:!0,value:void 0}):this.nextResult={done:!1,value:e},this.haveNext.resolve(),this.haveNext=i(),await d(this.readNext.promise,t?.signal,t)}};function te(){return new ee}function ne(e){return e[Symbol.asyncIterator]!=null}async function f(e,t,n){try{await Promise.all(e.map(async e=>{for await(let r of e)await t.push(r,{signal:n}),n.throwIfAborted()})),await t.end(void 0,{signal:n})}catch(e){await t.end(e,{signal:n}).catch(()=>{})}}async function*re(e){let t=new AbortController,n=te();f(e,n,t.signal).catch(()=>{});try{yield*n}finally{t.abort()}}function*ie(e){for(let t of e)yield*t}function p(...e){let t=[];for(let n of e)ne(n)||t.push(n);return t.length===e.length?ie(t):re(e)}function m(e,...t){if(e==null)throw Error(`Empty pipeline`);if(ce(e)){let t=e;e=()=>t.source}else if(se(e)||oe(e)){let t=e;e=()=>t}let n=[e,...t];if(n.length>1&&ce(n[n.length-1])&&(n[n.length-1]=n[n.length-1].sink),n.length>2)for(let e=1;e<n.length-1;e++)ce(n[e])&&(n[e]=le(n[e]));return ae(...n)}const ae=(...e)=>{let t;for(;e.length>0;)t=e.shift()(t);return t},oe=e=>e?.[Symbol.asyncIterator]!=null,se=e=>e?.[Symbol.iterator]!=null,ce=e=>e!=null&&e.sink!=null&&e.source!=null,le=e=>t=>{let n=e.sink(t);if(n?.then!=null){let t=c({objectMode:!0});n.then(()=>{t.end()},e=>{t.end(e)});let r,i=e.source;if(oe(i))r=async function*(){yield*i,t.end()};else if(se(i))r=function*(){yield*i,t.end()};else throw Error(`Unknown duplex source type - must be Iterable or AsyncIterable`);return p(t,r())}return e.source};function h(e,t){if(!e)throw Error(t)}function g(e){if(typeof e!=`number`)throw Error(`invalid int 32: `+typeof e);if(!Number.isInteger(e)||e>2147483647||e<-2147483648)throw Error(`invalid int 32: `+e)}function ue(e){if(typeof e!=`number`)throw Error(`invalid uint 32: `+typeof e);if(!Number.isInteger(e)||e>4294967295||e<0)throw Error(`invalid uint 32: `+e)}function de(e){if(typeof e!=`number`)throw Error(`invalid float 32: `+typeof e);if(Number.isFinite(e)&&(e>34028234663852886e22||e<-34028234663852886e22))throw Error(`invalid float 32: `+e)}function fe(){let e=0,t=0;for(let n=0;n<28;n+=7){let r=this.buf[this.pos++];if(e|=(r&127)<<n,!(r&128))return this.assertBounds(),[e,t]}let n=this.buf[this.pos++];if(e|=(n&15)<<28,t=(n&112)>>4,!(n&128))return this.assertBounds(),[e,t];for(let n=3;n<=31;n+=7){let r=this.buf[this.pos++];if(t|=(r&127)<<n,!(r&128))return this.assertBounds(),[e,t]}throw Error(`invalid varint`)}function pe(e,t,n){for(let r=0;r<28;r+=7){let i=e>>>r,a=!(!(i>>>7)&&t==0),o=(a?i|128:i)&255;if(n.push(o),!a)return}let r=e>>>28&15|(t&7)<<4,i=!!(t>>3);if(n.push((i?r|128:r)&255),i){for(let e=3;e<31;e+=7){let r=t>>>e,i=!!(r>>>7),a=(i?r|128:r)&255;if(n.push(a),!i)return}n.push(t>>>31&1)}}const _=4294967296;function me(e){let t=e[0]===`-`;t&&(e=e.slice(1));let n=1e6,r=0,i=0;function a(t,a){let o=Number(e.slice(t,a));i*=n,r=r*n+o,r>=_&&(i+=r/_|0,r%=_)}return a(-24,-18),a(-18,-12),a(-12,-6),a(-6),t?ye(r,i):ve(r,i)}function he(e,t){let n=ve(e,t),r=n.hi&2147483648;r&&(n=ye(n.lo,n.hi));let i=ge(n.lo,n.hi);return r?`-`+i:i}function ge(e,t){if({lo:e,hi:t}=_e(e,t),t<=2097151)return String(_*t+e);let n=e&16777215,r=(e>>>24|t<<8)&16777215,i=t>>16&65535,a=n+r*6777216+i*6710656,o=r+i*8147497,s=i*2,c=1e7;return a>=c&&(o+=Math.floor(a/c),a%=c),o>=c&&(s+=Math.floor(o/c),o%=c),s.toString()+be(o)+be(a)}function _e(e,t){return{lo:e>>>0,hi:t>>>0}}function ve(e,t){return{lo:e|0,hi:t|0}}function ye(e,t){return t=~t,e?e=~e+1:t+=1,ve(e,t)}const be=e=>{let t=String(e);return`0000000`.slice(t.length)+t};function xe(e,t){if(e>=0){for(;e>127;)t.push(e&127|128),e>>>=7;t.push(e)}else{for(let n=0;n<9;n++)t.push(e&127|128),e>>=7;t.push(1)}}function Se(){let e=this.buf[this.pos++],t=e&127;if(!(e&128)||(e=this.buf[this.pos++],t|=(e&127)<<7,!(e&128))||(e=this.buf[this.pos++],t|=(e&127)<<14,!(e&128))||(e=this.buf[this.pos++],t|=(e&127)<<21,!(e&128)))return this.assertBounds(),t;e=this.buf[this.pos++],t|=(e&15)<<28;for(let t=5;e&128&&t<10;t++)e=this.buf[this.pos++];if(e&128)throw Error(`invalid varint`);return this.assertBounds(),t>>>0}function Ce(){let e=new DataView(new ArrayBuffer(8));if(typeof BigInt==`function`&&typeof e.getBigInt64==`function`&&typeof e.getBigUint64==`function`&&typeof e.setBigInt64==`function`&&typeof e.setBigUint64==`function`&&(typeof process!=`object`||typeof process.env!=`object`||process.env.BUF_BIGINT_DISABLE!==`1`)){let t=BigInt(`-9223372036854775808`),n=BigInt(`9223372036854775807`),r=BigInt(`0`),i=BigInt(`18446744073709551615`);return{zero:BigInt(0),supported:!0,parse(e){let r=typeof e==`bigint`?e:BigInt(e);if(r>n||r<t)throw Error(`int64 invalid: ${e}`);return r},uParse(e){let t=typeof e==`bigint`?e:BigInt(e);if(t>i||t<r)throw Error(`uint64 invalid: ${e}`);return t},enc(t){return e.setBigInt64(0,this.parse(t),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},uEnc(t){return e.setBigInt64(0,this.uParse(t),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},dec(t,n){return e.setInt32(0,t,!0),e.setInt32(4,n,!0),e.getBigInt64(0,!0)},uDec(t,n){return e.setInt32(0,t,!0),e.setInt32(4,n,!0),e.getBigUint64(0,!0)}}}let t=e=>h(/^-?[0-9]+$/.test(e),`int64 invalid: ${e}`),n=e=>h(/^[0-9]+$/.test(e),`uint64 invalid: ${e}`);return{zero:`0`,supported:!1,parse(e){return typeof e!=`string`&&(e=e.toString()),t(e),e},uParse(e){return typeof e!=`string`&&(e=e.toString()),n(e),e},enc(e){return typeof e!=`string`&&(e=e.toString()),t(e),me(e)},uEnc(e){return typeof e!=`string`&&(e=e.toString()),n(e),me(e)},dec(e,t){return he(e,t)},uDec(e,t){return ge(e,t)}}}const v=Ce();var y;(function(e){e[e.DOUBLE=1]=`DOUBLE`,e[e.FLOAT=2]=`FLOAT`,e[e.INT64=3]=`INT64`,e[e.UINT64=4]=`UINT64`,e[e.INT32=5]=`INT32`,e[e.FIXED64=6]=`FIXED64`,e[e.FIXED32=7]=`FIXED32`,e[e.BOOL=8]=`BOOL`,e[e.STRING=9]=`STRING`,e[e.BYTES=12]=`BYTES`,e[e.UINT32=13]=`UINT32`,e[e.SFIXED32=15]=`SFIXED32`,e[e.SFIXED64=16]=`SFIXED64`,e[e.SINT32=17]=`SINT32`,e[e.SINT64=18]=`SINT64`,e[e.DATE=100]=`DATE`})(y||={});var b;(function(e){e[e.BIGINT=0]=`BIGINT`,e[e.STRING=1]=`STRING`})(b||={});function x(e,t,n){if(t===n)return!0;if(t==null||n==null)return t===n;if(e==y.BYTES){if(!(t instanceof Uint8Array)||!(n instanceof Uint8Array)||t.length!==n.length)return!1;for(let e=0;e<t.length;e++)if(t[e]!==n[e])return!1;return!0}if(e==y.DATE){let e=De(t,!1),r=De(n,!1);return e==null||r==null?e===r:e!=null&&r!=null&&+e==+r}switch(e){case y.UINT64:case y.FIXED64:case y.INT64:case y.SFIXED64:case y.SINT64:return t==n}return!1}function S(e,t){switch(e){case y.BOOL:return!1;case y.UINT64:case y.FIXED64:case y.INT64:case y.SFIXED64:case y.SINT64:return t==0?v.zero:`0`;case y.DOUBLE:case y.FLOAT:return 0;case y.BYTES:return new Uint8Array;case y.STRING:return``;case y.DATE:return null;default:return 0}}const we=+new Date(0);function Te(e,t){if(t==null)return!0;switch(e){case y.DATE:return+t===we;case y.BOOL:return t===!1;case y.STRING:return t===``;case y.BYTES:return t instanceof Uint8Array&&!t.byteLength;default:return t==0}}function C(e,t,n,r=b.BIGINT){return t==null?S(e,r):e===y.BYTES?Ee(t,n):Te(e,t)?S(e,r):e===y.DATE?De(t,n):t}function Ee(e,t){return!t&&e instanceof Uint8Array?e:new Uint8Array(e)}function De(e,t){if(e instanceof Date)return t?new Date(e.getTime()):e;if(typeof e==`string`||typeof e==`number`){let t=new Date(e);return isNaN(t.getTime())?null:t}return null}function Oe(e,t){let n=Ae(e);return t?n:Fe(Pe(n))}function ke(e){return Oe(e,!1)}function Ae(e){let t=!1,n=[];for(let r=0;r<e.length;r++){let i=e.charAt(r);switch(i){case`_`:t=!0;break;case`0`:case`1`:case`2`:case`3`:case`4`:case`5`:case`6`:case`7`:case`8`:case`9`:n.push(i),t=!1;break;default:t&&(t=!1,i=i.toUpperCase()),n.push(i)}}return n.join(``)}const je=new Set([`constructor`,`toString`,`toJSON`,`valueOf`,`__proto__`,`prototype`]),Me=new Set([`__proto__`]),Ne=e=>`${e}$`,Pe=e=>Me.has(e)?Ne(e):e,Fe=e=>je.has(e)?Ne(e):e;function Ie(e){return typeof e==`string`&&!!e.length&&!je.has(e)}function w(e){if(typeof e!=`string`)throw Error(`illegal non-string object key: `+typeof e);if(!Ie(e))throw Error(`illegal object key: `+e)}var Le=class{_fields;_normalizer;all;numbersAsc;jsonNames;numbers;members;constructor(e,t){this._fields=e,this._normalizer=t}findJsonName(e){if(!this.jsonNames){let e={};for(let t of this.list())e[t.jsonName]=e[t.name]=t;this.jsonNames=e}return this.jsonNames[e]}find(e){if(!this.numbers){let e={};for(let t of this.list())e[t.no]=t;this.numbers=e}return this.numbers[e]}list(){return this.all||=this._normalizer(this._fields),this.all}byNumber(){return this.numbersAsc||=this.list().concat().sort((e,t)=>e.no-t.no),this.numbersAsc}byMember(){if(!this.members){this.members=[];let e=this.members,t;for(let n of this.list())n.oneof?n.oneof!==t&&(t=n.oneof,e.push(t)):e.push(n)}return this.members}};function Re(e,t){return new Le(e,e=>He(e,t))}function ze(e,t){let n=e.localName;if(!t)return!1;if(e.repeated)return!!t[n]?.length;if(e.oneof)return t[e.oneof.localName]?.case===n;switch(e.kind){case`enum`:case`scalar`:return e.opt||e.req?t[n]!=null:e.kind==`enum`?t[n]!==e.T.values[0].no:!Te(e.T,t[n]);case`message`:return t[n]!=null;case`map`:return t[n]!=null&&!!Object.keys(t[n]).length}}const Be=Ae;function T(e){return e instanceof Function?e():e}var Ve=class{kind=`oneof`;name;localName;repeated=!1;packed=!1;opt=!1;req=!1;default=void 0;fields=[];_lookup;constructor(e){this.name=e,this.localName=ke(e)}addField(e){h(e.oneof===this,`field ${e.name} not one of ${this.name}`),this.fields.push(e)}findField(e){if(!this._lookup){this._lookup=Object.create(null);for(let e=0;e<this.fields.length;e++)this._lookup[this.fields[e].localName]=this.fields[e]}return this._lookup[e]}};function He(e,t){let n=[],r;for(let i of typeof e==`function`?e():e){let e=i;if(e.localName=Oe(i.name,i.oneof!==void 0),e.jsonName=i.jsonName??Be(i.name),e.repeated=i.repeated??!1,i.kind==`scalar`&&(e.L=i.L??b.BIGINT,e.utf8=i.utf8??!1),i.kind==`map`&&(e.keyUtf8=i.keyUtf8??!1),e.delimited=i.delimited??!1,e.req=i.req??!1,e.opt=i.opt??!1,i.packed===void 0&&(e.packed=t?i.kind==`enum`||i.kind==`scalar`&&i.T!=y.BYTES&&i.T!=y.STRING:!1),i.oneof!==void 0){let t=typeof i.oneof==`string`?i.oneof:i.oneof.name;(!r||r.name!=t)&&(r=new Ve(t)),e.oneof=r,r.addField(e)}n.push(e)}return n}function Ue(e){return Array.isArray(e)}function We(e,t){let n=Object.create(null),r=Object.create(null),i=[];for(let e of t){let t=Ue(e)?{no:e[0],name:e[1],localName:e[1]}:`localName`in e?e:{...e,localName:e.name};i.push(t),n[t.name]=t,r[t.no]=t}return{typeName:e,values:i,findName(e){return n[e]},findNumber(e){return r[e]}}}function Ge(e){if(e.values.length<1)throw Error(`invalid enum: missing at least one value`);return e.values[0].no}function Ke(e,t){let n=Ge(e);if(t==null||t===``||t===n)return n;if(typeof t==`string`){let n=e.findName(t);if(!n)throw Error(`enum ${e.typeName}: invalid value: "${t}"`);return n.no}return t}function E(){return Object.create(null)}function D(e){return e}function O(e,t,n,r=!1){if(e==null||t==null)return;let i=D(t),a=D(e);for(let e of n.byMember()){let t=e.localName;if(w(t),!(t in a)||a[t]===void 0)continue;let n=a[t];if(n===null){delete i[t];continue}switch(e.kind){case`oneof`:{if(typeof n!=`object`)throw Error(`field ${t}: invalid oneof: must be an object with case and value`);let{case:a,value:o}=n,s=a==null?null:e.findField(a),c=t in i?i[t]:void 0;if(typeof c!=`object`&&(c=E()),a!=null&&s==null)throw Error(`field ${t}: invalid oneof case: ${a}`);if(c.case=a,(c.case!==a||a==null)&&delete c.value,i[t]=c,!s)break;if(s.kind===`message`){let e=c.value;if(typeof e!=`object`&&(e=c.value=E()),o!=null){let t=T(s.T);O(o,e,t.fields)}}else s.kind===`scalar`?c.value=C(s.T,o,r):c.value=o;break}case`scalar`:if(e.repeated){if(!Array.isArray(n))throw Error(`field ${t}: invalid value: must be array`);let a=t in i?i[t]:null;(a==null||!Array.isArray(a))&&(a=i[t]=[]),a.push(...n.map(t=>C(e.T,t,r)));break}i[t]=C(e.T,n,r);break;case`enum`:i[t]=Ke(e.T,n);break;case`map`:{if(typeof n!=`object`)throw Error(`field ${e.localName}: invalid value: must be object`);let a=i[t];typeof a!=`object`&&(a=i[t]=E()),qe(n,a,e.V,r);break}case`message`:{let r=T(e.T);if(e.repeated){if(!Array.isArray(n))throw Error(`field ${t}: invalid value: must be array`);let e=i[t];Array.isArray(e)||(e=i[t]=[]);for(let t of n)t!=null&&(r.fieldWrapper?e.push(r.fieldWrapper.unwrapField(r.fieldWrapper.wrapField(t))):e.push(r.create(t)));break}if(r.fieldWrapper)i[t]=r.fieldWrapper.unwrapField(r.fieldWrapper.wrapField(n));else{if(typeof n!=`object`)throw Error(`field ${e.localName}: invalid value: must be object`);let a=i[t];typeof a!=`object`&&(a=i[t]=E()),O(n,a,r.fields)}break}}}}function qe(e,t,n,r){if(e!=null){if(typeof e!=`object`)throw Error(`invalid map: must be object`);switch(n.kind){case`scalar`:for(let[i,a]of Object.entries(e))w(i),a===void 0?delete t[i]:t[i]=C(n.T,a,r);break;case`enum`:for(let[r,i]of Object.entries(e))w(r),i===void 0?delete t[r]:t[r]=Ke(n.T,i);break;case`message`:{let r=T(n.T);for(let[n,i]of Object.entries(e)){if(w(n),i===void 0){delete t[n];continue}if(typeof i!=`object`)throw Error(`invalid value: must be object`);let e=t[n];r.fieldWrapper?e=t[n]=Mt(r.fields):typeof e!=`object`&&(e=t[n]=E()),O(i,e,r.fields)}break}}}}const k=Symbol(`@aptre/protobuf-es-lite/unknown-fields`);function Je(e,t,n,r){if(typeof e!=`object`)return;let i=e;Array.isArray(i[k])||(i[k]=[]),i[k].push({no:t,wireType:n,data:r})}function Ye(e,t){return e?e.wrapField(t):t}function A(e,t){return e?e.unwrapField(t):t}y.DATE,y.DOUBLE,y.FLOAT,y.INT64,y.UINT64,y.INT32,y.UINT32,y.BOOL,y.STRING,y.BYTES;var j;(function(e){e[e.Varint=0]=`Varint`,e[e.Bit64=1]=`Bit64`,e[e.LengthDelimited=2]=`LengthDelimited`,e[e.StartGroup=3]=`StartGroup`,e[e.EndGroup=4]=`EndGroup`,e[e.Bit32=5]=`Bit32`})(j||={});var Xe=class{chunks;buf;stack=[];textEncoder;constructor(e){this.textEncoder=e??new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let e=0;for(let t=0;t<this.chunks.length;t++)e+=this.chunks[t].length;let t=new Uint8Array(e),n=0;for(let e=0;e<this.chunks.length;e++)t.set(this.chunks[e],n),n+=this.chunks[e].length;return this.chunks=[],t}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let e=this.finish(),t=this.stack.pop();if(!t)throw Error(`invalid state, fork stack empty`);return this.chunks=t.chunks,this.buf=t.buf,this.uint32(e.byteLength),this.raw(e)}tag(e,t){return this.uint32((e<<3|t)>>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(ue(e);e>127;)this.buf.push(e&127|128),e>>>=7;return this.buf.push(e),this}int32(e){return g(e),xe(e,this.buf),this}bool(e){return this.buf.push(+!!e),this}bytes(e){return this.uint32(e.byteLength),this.raw(e)}string(e){let t=this.textEncoder.encode(e);return this.uint32(t.byteLength),this.raw(t)}float(e){de(e);let t=new Uint8Array(4);return new DataView(t.buffer).setFloat32(0,e,!0),this.raw(t)}double(e){let t=new Uint8Array(8);return new DataView(t.buffer).setFloat64(0,e,!0),this.raw(t)}fixed32(e){ue(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){g(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return g(e),e=(e<<1^e>>31)>>>0,xe(e,this.buf),this}sfixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),r=v.enc(e);return n.setInt32(0,r.lo,!0),n.setInt32(4,r.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),r=v.uEnc(e);return n.setInt32(0,r.lo,!0),n.setInt32(4,r.hi,!0),this.raw(t)}int64(e){let t=v.enc(e);return pe(t.lo,t.hi,this.buf),this}sint64(e){let t=v.enc(e),n=t.hi>>31;return pe(t.lo<<1^n,(t.hi<<1|t.lo>>>31)^n,this.buf),this}uint64(e){let t=v.uEnc(e);return pe(t.lo,t.hi,this.buf),this}},Ze=class{pos;len;buf;view;textDecoder;fatalTextDecoder;constructor(e,t,n){this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.textDecoder=t??new TextDecoder,this.fatalTextDecoder=n}tag(){let e=this.uint32(),t=e>>>3,n=e&7;if(t<=0||n<0||n>5)throw Error(`illegal tag: field no `+t+` wire type `+n);return[t,n]}skip(e){let t=this.pos;switch(e){case j.Varint:for(;this.buf[this.pos++]&128;);break;case j.Bit64:this.pos+=4;case j.Bit32:this.pos+=4;break;case j.LengthDelimited:let t=this.uint32();this.pos+=t;break;case j.StartGroup:let n;for(;(n=this.tag()[1])!==j.EndGroup;)this.skip(n);break;default:throw Error(`cant skip wire type `+e)}return this.assertBounds(),this.buf.subarray(t,this.pos)}varint64=fe;assertBounds(){if(this.pos>this.len)throw RangeError(`premature EOF`)}uint32=Se;int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)}int64(){return v.dec(...this.varint64())}uint64(){return v.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),n=-(e&1);return e=(e>>>1|(t&1)<<31)^n,t=t>>>1^n,v.dec(e,t)}bool(){let[e,t]=this.varint64();return e!==0||t!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return v.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return v.dec(this.sfixed32(),this.sfixed32())}float(){return this.view.getFloat32((this.pos+=4)-4,!0)}double(){return this.view.getFloat64((this.pos+=8)-8,!0)}bytes(){let e=this.uint32(),t=this.pos;return this.pos+=e,this.assertBounds(),this.buf.subarray(t,t+e)}string(e=!1){return(e?this.fatalTextDecoder??=new TextDecoder(`utf-8`,{fatal:!0}):this.textDecoder).decode(this.bytes())}};const Qe={readUnknownFields:!0,readerFactory:e=>new Ze(e)},$e={writeUnknownFields:!0,writerFactory:()=>new Xe};function et(e){return e?{...Qe,...e}:Qe}function tt(e){return e?{...$e,...e}:$e}function nt(e,t,n,r,i){let{repeated:a}=n,{localName:o}=n;if(n.oneof){let t=e[n.oneof.localName];t||=e[n.oneof.localName]=E(),e=t,e.case!=o&&delete e.value,e.case=o,o=`value`}switch(n.kind){case`scalar`:case`enum`:{let i=n.kind==`enum`?y.INT32:n.T,s=M,c=n.kind==`scalar`&&n.utf8;if(n.kind==`scalar`&&n.L>0&&(s=it),a){let n=e[o];if(Array.isArray(n)||(n=e[o]=[]),r==j.LengthDelimited&&i!=y.STRING&&i!=y.BYTES){let e=t.uint32()+t.pos;for(;t.pos<e;)n.push(s(t,i,c))}else n.push(s(t,i,c))}else e[o]=s(t,i,c);break}case`message`:{let r=n.T,s=r instanceof Function?r():r;if(a){let r=e[o];Array.isArray(r)||(r=e[o]=[]),r.push(A(s.fieldWrapper,N(t,E(),s.fields,i,n)))}else e[o]=A(s.fieldWrapper,N(t,E(),s.fields,i,n));break}case`map`:{let[r,a]=rt(n,t,i);typeof e[o]!=`object`&&(e[o]=E()),e[o][r]=a;break}}}function rt(e,t,n){let r=t.uint32(),i=t.pos+r,a,o;for(;t.pos<i;){let[r]=t.tag();switch(r){case 1:a=M(t,e.K,e.keyUtf8);break;case 2:switch(e.V.kind){case`scalar`:o=M(t,e.V.T,e.V.utf8===!0);break;case`enum`:o=t.int32();break;case`message`:o=N(t,E(),T(e.V.T).fields,n,void 0)}}}if(a===void 0&&(a=S(e.K,b.BIGINT)),typeof a!=`string`&&typeof a!=`number`&&(a=a?.toString()??``),o===void 0)switch(e.V.kind){case`scalar`:o=S(e.V.T,b.BIGINT);break;case`enum`:o=e.V.T.values[0].no;break;case`message`:o=E()}return[a,o]}function M(e,t,n=!1){switch(t){case y.STRING:return e.string(n);case y.BOOL:return e.bool();case y.DOUBLE:return e.double();case y.FLOAT:return e.float();case y.INT32:return e.int32();case y.INT64:return e.int64();case y.UINT64:return e.uint64();case y.FIXED64:return e.fixed64();case y.BYTES:return e.bytes();case y.FIXED32:return e.fixed32();case y.SFIXED32:return e.sfixed32();case y.SFIXED64:return e.sfixed64();case y.SINT64:return e.sint64();case y.UINT32:return e.uint32();case y.SINT32:return e.sint32();case y.DATE:throw Error(`cannot read a date with readScalar`);default:throw Error(`unknown scalar type`)}}function it(e,t,n=!1){let r=M(e,t,n);return typeof r==`bigint`?r.toString():r}function N(e,t,n,r,i){return at(t,n,e,i?.delimited?i.no:e.uint32(),r,i?.delimited??!1),t}function at(e,t,n,r,i,a){let o=a?n.len:n.pos+r,s,c;for(;n.pos<o&&([s,c]=n.tag(),c!=j.EndGroup);){let r=t.find(s);if(!r){let t=n.skip(c);i.readUnknownFields&&Je(e,s,c,t);continue}nt(e,n,r,c,i)}if(a&&(c!=j.EndGroup||s!==r))throw Error(`invalid end group tag`)}function ot(e,t,n,r){for(let i of t.byNumber()){let t=e;if(!ze(i,t)){if(i.req)throw Error(`cannot encode field ${i.name} to binary: required field not set`);continue}let a=i.oneof?t[i.oneof.localName].value:t[i.localName];a!==void 0&&st(i,a,n,r)}r.writeUnknownFields&&ct(e,n)}function st(e,t,n,r){h(t!==void 0);let i=e.repeated;switch(e.kind){case`scalar`:case`enum`:{let r=e.kind==`enum`?y.INT32:e.T;if(i){if(h(Array.isArray(t)),e.packed)ut(n,r,e.no,t);else for(let i of t)P(n,r,e.no,i)}else P(n,r,e.no,t);break}case`message`:if(i){h(Array.isArray(t));for(let i of t)lt(n,r,e,i)}else lt(n,r,e,t);break;case`map`:h(typeof t==`object`&&!!t);for(let[i,a]of Object.entries(t))ft(n,r,e,i,a)}}function ct(e,t){let n=e[k];if(n)for(let e of n)t.tag(e.no,e.wireType).raw(e.data)}function lt(e,t,n,r){let i=T(n.T),a=Ye(i.fieldWrapper,r);n.delimited?e.tag(n.no,j.StartGroup).raw(i.toBinary(a,t)).tag(n.no,j.EndGroup):e.tag(n.no,j.LengthDelimited).bytes(i.toBinary(a,t))}function P(e,t,n,r){h(r!==void 0);let[i,a]=dt(t);e.tag(n,i)[a](r)}function ut(e,t,n,r){if(!r.length)return;e.tag(n,j.LengthDelimited).fork();let[,i]=dt(t);for(let t=0;t<r.length;t++)e[i](r[t]);e.join()}function dt(e){let t=j.Varint;switch(e){case y.BYTES:case y.STRING:t=j.LengthDelimited;break;case y.DOUBLE:case y.FIXED64:case y.SFIXED64:t=j.Bit64;break;case y.FIXED32:case y.SFIXED32:case y.FLOAT:t=j.Bit32}let n=y[e].toLowerCase();return[t,n]}function ft(e,t,n,r,i){e.tag(n.no,j.LengthDelimited),e.fork();let a=r;switch(n.K){case y.INT32:case y.FIXED32:case y.UINT32:case y.SFIXED32:case y.SINT32:a=Number.parseInt(r);break;case y.BOOL:h(r==`true`||r==`false`),a=r==`true`}switch(P(e,n.K,1,a),n.V.kind){case`scalar`:P(e,n.V.T,2,i);break;case`enum`:P(e,y.INT32,2,i);break;case`message`:{h(i!==void 0);let r=T(n.V.T);e.tag(2,j.LengthDelimited).bytes(r.toBinary(i,t));break}}e.join()}let F=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`.split(``),I=[];for(let e=0;e<F.length;e++)I[F[e].charCodeAt(0)]=e;I[45]=F.indexOf(`+`),I[95]=F.indexOf(`/`);const pt={dec(e){let t=e.length*3/4;e[e.length-2]==`=`?t-=2:e[e.length-1]==`=`&&--t;let n=new Uint8Array(t),r=0,i=0,a,o=0;for(let t=0;t<e.length;t++){if(a=I[e.charCodeAt(t)],a===void 0)switch(e[t]){case`=`:i=0;case`
|
|
2
|
-
`:case`\r`:case` `:case` `:continue;default:throw Error(`invalid base64 string.`)}switch(i){case 0:o=a,i=1;break;case 1:n[r++]=o<<2|(a&48)>>4,o=a,i=2;break;case 2:n[r++]=(o&15)<<4|(a&60)>>2,o=a,i=3;break;case 3:n[r++]=(o&3)<<6|a,i=0}}if(i==1)throw Error(`invalid base64 string.`);return n.subarray(0,r)},enc(e){let t=``,n=0,r,i=0;for(let a=0;a<e.length;a++)switch(r=e[a],n){case 0:t+=F[r>>2],i=(r&3)<<4,n=1;break;case 1:t+=F[i|r>>4],i=(r&15)<<2,n=2;break;case 2:t+=F[i|r>>6],t+=F[r&63],n=0}return n&&(t+=F[i],t+=`=`,n==1&&(t+=`=`)),t}},mt={ignoreUnknownFields:!1},ht={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function gt(e){return e?{...mt,...e}:mt}function _t(e){return e?{...ht,...e}:ht}function L(e){if(e===null)return`null`;switch(typeof e){case`object`:return Array.isArray(e)?`array`:`object`;case`string`:return e.length>100?`string`:`"${e.split(`"`).join(`\\"`)}"`;default:return String(e)}}function vt(e,t,n,r,i){if(n==null||Array.isArray(n)||typeof n!=`object`)throw Error(`cannot decode message ${t} from JSON: ${L(n)}`);let a=new Map;for(let[o,s]of Object.entries(n)){let n=e.findJsonName(o);if(n){if(n.oneof){if(s===null&&n.kind==`scalar`)continue;let e=a.get(n.oneof);if(e!==void 0)throw Error(`cannot decode message ${t} from JSON: multiple keys for oneof "${n.oneof.name}" present: "${e}", "${o}"`);a.set(n.oneof,o)}bt(i,s,n,r)}else if(!r.ignoreUnknownFields)throw Error(`cannot decode message ${t} from JSON: key "${o}" is unknown`)}return i}function yt(e,t,n){let r=Object.create(null),i;try{for(i of t.byNumber()){let t=e;if(!ze(i,t)){if(i.req)throw`required field not set`;if(!n.emitDefaultValues||!wt(i))continue}let a=i.oneof?t[i.oneof.localName].value:t[i.localName],o=Tt(i,a,n);o!==void 0&&(r[n.useProtoFieldName?i.name:i.jsonName]=o)}}catch(e){let t=i?`cannot encode field ${i.name} to JSON`:`cannot encode message to JSON`,n=e instanceof Error?e.message:String(e);throw Error(t+(n.length>0?`: ${n}`:``),{cause:e})}return r}function bt(e,t,n,r){let i=n.localName;if(n.repeated){if(h(n.kind!=`map`),t===null)return;if(!Array.isArray(t))throw Error(`cannot decode field ${n.name} from JSON: ${L(t)}`);let a=e[i];Array.isArray(a)||(a=e[i]=[]);for(let e of t){if(e===null)throw Error(`cannot decode field ${n.name} from JSON: ${L(e)}`);switch(n.kind){case`message`:{let t=T(n.T);a.push(A(t.fieldWrapper,t.fromJson(e,r)));break}case`enum`:{let t=xt(n.T,e,r.ignoreUnknownFields,!0);t!==z&&a.push(t);break}case`scalar`:try{a.push(B(n.T,e,n.L,!0))}catch(t){let r=`cannot decode field ${n.name} from JSON: ${L(e)}`;throw t instanceof Error&&t.message.length>0&&(r+=`: ${t.message}`),Error(r,{cause:t})}}}}else if(n.kind==`map`){if(t===null)return;if(typeof t!=`object`||Array.isArray(t))throw Error(`cannot decode field ${n.name} from JSON: ${L(t)}`);let a=e[i];typeof a!=`object`&&(a=e[i]=E());for(let[e,i]of Object.entries(t)){if(i===null)throw Error(`cannot decode field ${n.name} from JSON: map value null`);let o;try{o=St(n.K,e)}catch(e){let r=`cannot decode map key for field ${n.name} from JSON: ${L(t)}`;throw e instanceof Error&&e.message.length>0&&(r+=`: ${e.message}`),Error(r,{cause:e})}switch(w(o),n.V.kind){case`message`:{let e=T(n.V.T);a[o]=e.fromJson(i,r);break}case`enum`:{let e=xt(n.V.T,i,r.ignoreUnknownFields,!0);e!==z&&(a[o]=e);break}case`scalar`:try{a[o]=B(n.V.T,i,b.BIGINT,!0)}catch(e){let r=`cannot decode map value for field ${n.name} from JSON: ${L(t)}`;throw e instanceof Error&&e.message.length>0&&(r+=`: ${e.message}`),Error(r,{cause:e})}}}}else switch(n.oneof&&(e=e[n.oneof.localName]={case:i},i=`value`),n.kind){case`message`:{let a=T(n.T);if(t===null&&a.typeName!=`google.protobuf.Value`)return;e[i]=A(a.fieldWrapper,a.fromJson(t,r));break}case`enum`:{let a=xt(n.T,t,r.ignoreUnknownFields,!1);switch(a){case R:Ct(n,e);break;case z:break;default:e[i]=a}break}case`scalar`:try{let r=B(n.T,t,n.L,!1);switch(r){case R:Ct(n,e);break;default:e[i]=r}}catch(e){let r=`cannot decode field ${n.name} from JSON: ${L(t)}`;throw e instanceof Error&&e.message.length>0&&(r+=`: ${e.message}`),Error(r,{cause:e})}}}const R=Symbol(),z=Symbol();function xt(e,t,n,r){if(t===null)return e.typeName==`google.protobuf.NullValue`?0:r?e.values[0].no:R;switch(typeof t){case`number`:if(Number.isInteger(t))return t;break;case`string`:{let r=e.findName(t);if(r!==void 0)return r.no;if(n)return z;break}}throw Error(`cannot decode enum ${e.typeName} from JSON: ${L(t)}`)}function B(e,t,n=b.BIGINT,r=!0){if(t==null)return r?S(e,n):R;switch(e){case y.DOUBLE:case y.FLOAT:{if(t===`NaN`)return NaN;if(t===`Infinity`)return 1/0;if(t===`-Infinity`)return-1/0;if(t===``||typeof t==`string`&&t.trim().length!==t.length||typeof t!=`string`&&typeof t!=`number`)break;let n=Number(t);if(Number.isNaN(n)||!Number.isFinite(n))break;return e==y.FLOAT&&de(n),n}case y.INT32:case y.FIXED32:case y.SFIXED32:case y.SINT32:case y.UINT32:{let n;if(typeof t==`number`?n=t:typeof t==`string`&&t.length>0&&t.trim().length===t.length&&(n=Number(t)),n===void 0)break;return e==y.UINT32||e==y.FIXED32?ue(n):g(n),n}case y.INT64:case y.SFIXED64:case y.SINT64:{if(typeof t!=`number`&&typeof t!=`string`)break;let e=v.parse(t);return n?e.toString():e}case y.FIXED64:case y.UINT64:{if(typeof t!=`number`&&typeof t!=`string`)break;let e=v.uParse(t);return n?e.toString():e}case y.BOOL:if(typeof t!=`boolean`)break;return t;case y.STRING:if(typeof t!=`string`)break;return t;case y.BYTES:if(t===``)return new Uint8Array;if(typeof t!=`string`)break;return pt.dec(t)}throw Error()}function St(e,t){if(e===y.BOOL)switch(t){case`true`:t=!0;break;case`false`:t=!1}return B(e,t,b.BIGINT,!0)?.toString()??``}function Ct(e,t){let n=e.localName,r=!e.opt&&!e.req;if(e.repeated)t[n]=[];else if(e.oneof)t[e.oneof.localName]={case:void 0};else switch(e.kind){case`map`:t[n]=E();break;case`enum`:t[n]=r?e.T.values[0].no:void 0;break;case`scalar`:t[n]=r?S(e.T,e.L):void 0;break;case`message`:t[n]=void 0}}function wt(e){return e.repeated||e.kind==`map`?!0:!(e.oneof||e.kind==`message`||e.opt||e.req)}function Tt(e,t,n){if(e.kind==`map`){let r=Object.create(null);h(!t||typeof t==`object`);let i=t?Object.entries(t):[];switch(e.V.kind){case`scalar`:for(let[t,n]of i)r[t.toString()]=Et(e.V.T,n);break;case`message`:for(let[t,a]of i){let i=T(e.V.T);r[t.toString()]=i.toJson(a,n)}break;case`enum`:{let t=e.V.T;for(let[e,a]of i)r[e.toString()]=Dt(t,a,n.enumAsInteger);break}}return n.emitDefaultValues||i.length>0?r:void 0}if(e.repeated){h(!t||Array.isArray(t));let r=[],i=t;if(i&&i.length)switch(e.kind){case`scalar`:for(let t=0;t<i.length;t++)r.push(Et(e.T,i[t]));break;case`enum`:for(let t=0;t<i.length;t++)r.push(Dt(e.T,i[t],n.enumAsInteger));break;case`message`:{let t=T(e.T);for(let e=0;e<i.length;e++)r.push(t.toJson(Ye(t.fieldWrapper,i[e])));break}}return n.emitDefaultValues||r.length>0?r:void 0}switch(e.kind){case`scalar`:{let r=C(e.T,t,!1);return!n.emitDefaultValues&&Te(e.T,r)?void 0:Et(e.T,t)}case`enum`:{let r=Ke(e.T,t);return!n.emitDefaultValues&&Ge(e.T)===r?void 0:Dt(e.T,t,n.enumAsInteger)}case`message`:{if(!n.emitDefaultValues&&t==null)return;let r=T(e.T);return r.toJson(Ye(r.fieldWrapper,t))}}}function Et(e,t){switch(e){case y.INT32:case y.SFIXED32:case y.SINT32:case y.FIXED32:case y.UINT32:return h(typeof t==`number`),t;case y.FLOAT:case y.DOUBLE:return h(typeof t==`number`),Number.isNaN(t)?`NaN`:t===1/0?`Infinity`:t===-1/0?`-Infinity`:t;case y.STRING:return h(typeof t==`string`),t;case y.BOOL:return h(typeof t==`boolean`),t;case y.UINT64:case y.FIXED64:case y.INT64:case y.SFIXED64:case y.SINT64:return h(typeof t==`bigint`||typeof t==`string`||typeof t==`number`),t.toString();case y.BYTES:return h(t instanceof Uint8Array),pt.enc(t);case y.DATE:throw Error(`cannot write date with writeScalar`);default:throw Error(`unknown scalar type`)}}function Dt(e,t,n){return h(typeof t==`number`),e.typeName==`google.protobuf.NullValue`?null:n?t:e.findNumber(t)?.name??t}const Ot=[];function V(e,t){let{fields:n,typeName:r,packedByDefault:i,delimitedMessageEncoding:a,fieldWrapper:o}=e,s=Re(n,i),c={typeName:r,fields:s,fieldWrapper:o,create(e){let t=Object.create(null);return O(e,t,s),t},createComplete(e){let t=Mt(s);return O(e,t,s),t},equals(e,t){return At(s,e,t)},clone(e){return e==null?e:jt(e,s)},fromBinary(e,t){let n={};if(e&&e.length){let r=et(t);at(n,s,r.readerFactory(e),e.byteLength,r,a??!1)}return n},fromJson(e,t){let n={};if(e!=null){let i=gt(t);vt(s,r,e,i,n)}return n},fromJsonString(e,t){let n=null;if(e)try{n=JSON.parse(e)}catch(e){throw Error(`cannot decode ${r} from JSON: ${e instanceof Error?e.message:String(e)}`,{cause:e})}return c.fromJson(n,t)},toBinary(e,t){if(e==null)return new Uint8Array;let n=tt(t),r=n.writerFactory();return ot(e,s,r,n),r.finish()},toJson(e,t){let n=_t(t);return yt(e,s,n)},toJsonString(e,t){let n=c.toJson(e,t);return JSON.stringify(n,null,t?.prettySpaces??0)},...t??{}};return c}function kt(e,t){return V({typeName:e,fields:Ot,packedByDefault:t})}function At(e,t,n){return t==null&&n==null||t===n?!0:!t||!n?!1:e.byMember().every(e=>{let r=D(t)[e.localName],i=D(n)[e.localName];if(e.repeated){let t=r,n=i;if((t?.length??0)!==(n?.length??0))return!1;if(!t?.length)return!0;switch(e.kind){case`message`:{let r=T(e.T),i=t,a=n;return i.every((e,t)=>r.equals(e,a[t]))}case`scalar`:return t.every((t,r)=>x(e.T,t,n?.[r]));case`enum`:return t.every((e,t)=>x(y.INT32,e,n?.[t]))}throw Error(`repeated cannot contain ${e.kind}`)}switch(e.kind){case`message`:return T(e.T).equals(r,i);case`enum`:return x(y.INT32,r,i);case`scalar`:return x(e.T,r,i);case`oneof`:{let t=r,n=i;if(t?.case!==n?.case)return!1;if(t==null)return!0;let a=t.case;if(a===void 0)return!0;let o=e.findField(a);if(o===void 0)return!0;switch(o.kind){case`message`:return T(o.T).equals(t.value,n?.value);case`enum`:return x(y.INT32,t.value,n?.value);case`scalar`:return x(o.T,t.value,n?.value)}throw Error(`oneof cannot contain ${o.kind}`)}case`map`:{let t=r??{},n=i??{},a=Object.keys(t).concat(Object.keys(n));switch(e.V.kind){case`message`:{let r=T(e.V.T);return a.every(e=>r.equals(t[e],n[e]))}case`enum`:return a.every(e=>x(y.INT32,t[e],n[e]));case`scalar`:{let r=e.V.T;return a.every(e=>x(r,t[e],n[e]))}}}}})}function jt(e,t){if(e==null)return null;let n=E();return O(e,n,t,!0),n}function Mt(e){let t={};for(let n of e.byMember()){let{localName:e,kind:r}=n;switch(w(e),r){case`oneof`:t[e]=E(),t[e].case=void 0;break;case`scalar`:t[e]=n.repeated?[]:S(n.T,b.BIGINT);break;case`enum`:t[e]=n.repeated?[]:Ge(n.T);break;case`message`:{if(n.oneof)break;if(n.repeated){t[e]=[];break}let r=T(n.T);t[e]=r.fieldWrapper?r.fieldWrapper.unwrapField(null):Mt(r.fields);break}case`map`:t[e]=E()}}return t}const Nt=V({typeName:`srpc.CallStart`,fields:[{no:1,name:`rpc_service`,kind:`scalar`,T:y.STRING},{no:2,name:`rpc_method`,kind:`scalar`,T:y.STRING},{no:3,name:`data`,kind:`scalar`,T:y.BYTES},{no:4,name:`data_is_zero`,kind:`scalar`,T:y.BOOL}],packedByDefault:!0}),Pt=V({typeName:`srpc.CallData`,fields:[{no:1,name:`data`,kind:`scalar`,T:y.BYTES},{no:2,name:`data_is_zero`,kind:`scalar`,T:y.BOOL},{no:3,name:`complete`,kind:`scalar`,T:y.BOOL},{no:4,name:`error`,kind:`scalar`,T:y.STRING}],packedByDefault:!0}),Ft=V({typeName:`srpc.Packet`,fields:[{no:1,name:`call_start`,kind:`message`,T:()=>Nt,oneof:`body`},{no:2,name:`call_data`,kind:`message`,T:()=>Pt,oneof:`body`},{no:3,name:`call_cancel`,kind:`scalar`,T:y.BOOL,oneof:`body`}],packedByDefault:!0});var It=class{sink;source;rpcDataSource;_source=c({objectMode:!0});_rpcDataSource=c({objectMode:!0});service;method;closed;remoteError;invocationController=new AbortController;writeDrainAbort=new AbortController;constructor(){this.sink=this._createSink(),this.source=this._source,this.rpcDataSource=this._rpcDataSource}get isClosed(){return this.closed??!1}get invocationSignal(){return this.invocationController.signal}async writeCallData(e,t,n){await this.writeCallDataPacket(e,t,n)}async writeCallDataPacket(e,t,n,r){let i={data:e||new Uint8Array,dataIsZero:!!e&&e.length===0,complete:t||!1,error:n||``};await this.writePacket({body:{case:`callData`,value:i}},r)}async writeCallCancel(e=!1){await this.writePacket({body:{case:`callCancel`,value:!0}},{waitForDrain:!1}),e&&await this._source.onEmpty({signal:this.writeDrainAbort.signal})}async writeCallDataFromSource(e){try{for await(let t of e)await this.writeCallData(t);await this.writeCallData(void 0,!0)}catch(e){this.close(e)}}async writePacket(e,n){if(this.closed&&!n?.allowClosed)throw Error(t);if(this._source.push(e),!(n?.waitForDrain===!1||this._source.readableLength<=1))try{await this._source.onEmpty({signal:this.writeDrainAbort.signal})}catch(e){throw this.closed?Error(t,{cause:e}):e}}async handleMessage(e){return this.handlePacket(Ft.fromBinary(e))}async handlePacket(e){try{switch(e?.body?.case){case`callStart`:await this.handleCallStart(e.body.value);break;case`callData`:await this.handleCallData(e.body.value);break;case`callCancel`:e.body.value&&await this.handleCallCancel()}}catch(e){let t=e;t?.message||(t=Error(`error handling packet`)),this.close(t)}}async handleCallStart(e){throw Error(`unexpected call start: ${e.rpcService}/${e.rpcMethod}`)}pushRpcData(e,t){if(t)(!e||e.length!==0)&&(e=new Uint8Array);else if(!e||e.length===0)return;this._rpcDataSource.push(e)}async handleCallData(e){if(!this.service||!this.method)throw Error(`call start must be sent before call data`);this.pushRpcData(e.data,e.dataIsZero);let t=e.error?new r(this.service,this.method,e.error):void 0;t&&(this.remoteError??=t,this.invocationController.abort()),(e.complete&&!t||t)&&this._rpcDataSource.end(t)}async handleCallCancel(){await this.close(Error(t))}async close(e){this.closed||(this.closed=e??!0,!this.remoteError&&e&&(this.remoteError=e),this.invocationController.abort(),e&&e.message&&await this.writeCallDataPacket(void 0,!0,e.message,{allowClosed:!0,waitForDrain:!1}),this.writeDrainAbort.abort(),this._source.end(),this._rpcDataSource.end(e))}_createSink(){return async e=>{try{if(Symbol.asyncIterator in e)for await(let t of e)await this.handlePacket(t);else for(let t of e)await this.handlePacket(t)}catch(e){this.close(e)}}}},Lt=class extends It{constructor(e,t){super(),this.service=e,this.method=t}async writeCallStart(e){if(!this.service||!this.method)throw Error(`service and method must be set`);let t={rpcService:this.service,rpcMethod:this.method,data:e||new Uint8Array,dataIsZero:!!e&&e.length===0};await this.writePacket({body:{case:`callStart`,value:t}})}async handleCallStart(e){throw Error(`unexpected server to client rpc: ${e.rpcService||`<empty>`}/${e.rpcMethod||`<empty>`}`)}};async function Rt(e,t){try{for await(let n of e)t.push(n);t.end()}catch(e){t.end(e)}}function H(e=0){return new Uint8Array(e)}function zt(e=0){return new Uint8Array(e)}function Bt(e){return e?.buffer instanceof ArrayBuffer}function Vt(e){if(Bt(e))return e;let t=e.slice();return new Uint8Array(t.buffer,0,t.byteLength)}function Ht(e,t){t??=e.reduce((e,t)=>e+t.length,0);let n=zt(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return Vt(n)}function Ut(e,t){if(e===t)return!0;if(e.byteLength!==t.byteLength)return!1;for(let n=0;n<e.byteLength;n++)if(e[n]!==t[n])return!1;return!0}const Wt=Symbol.for(`@achingbrain/uint8arraylist`);function Gt(e,t){if(t==null||t<0)throw RangeError(`index is out of bounds`);let n=0;for(let r of e){let e=n+r.byteLength;if(t<e)return{buf:r,index:t-n};n=e}throw RangeError(`index is out of bounds`)}function U(e){return!!e?.[Wt]}var W=class e{bufs;length;[Wt]=!0;constructor(...e){this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let t=0;for(let n of e)if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.push(n);else if(U(n)){t+=n.byteLength;for(let e of n.bufs)this.bufs.push(e)}else throw Error(`Could not append value, must be an Uint8Array or a Uint8ArrayList`);this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(U(n))t+=n.byteLength,this.bufs.unshift(...n.bufs);else throw Error(`Could not prepend value, must be an Uint8Array or a Uint8ArrayList`);this.length+=t}get(e){let t=Gt(this.bufs,e);return t.buf[t.index]}set(e,t){let n=Gt(this.bufs,e);n.buf[n.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(t+n,e[n]);else if(U(e))for(let n=0;n<e.length;n++)this.set(t+n,e.get(n));else throw Error(`Could not write value, must be an Uint8Array or a Uint8ArrayList`)}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:n,length:r}=this._subList(e,t);return Ht(n,r)}subarray(e,t){let{bufs:n,length:r}=this._subList(e,t);return n.length===1?n[0]:Ht(n,r)}sublist(t,n){let{bufs:r,length:i}=this._subList(t,n),a=new e;return a.length=i,a.bufs=r,a}_subList(e,t){if(e??=0,t??=this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw RangeError(`index is out of bounds`);if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:[...this.bufs],length:this.length};let n=[],r=0;for(let i=0;i<this.bufs.length;i++){let a=this.bufs[i],o=r,s=o+a.byteLength;if(r=s,e>=s)continue;let c=e>=o&&e<s,l=t>o&&t<=s;if(c&&l){if(e===o&&t===s){n.push(a);break}let r=e-o;n.push(a.subarray(r,r+(t-e)));break}if(c){if(e===0){n.push(a);continue}n.push(a.subarray(e-o));continue}if(l){if(t===s){n.push(a);break}n.push(a.subarray(0,t-o));break}n.push(a)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!U(e)&&!(e instanceof Uint8Array))throw TypeError(`The "value" argument must be a Uint8ArrayList or Uint8Array`);let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let r=n.byteLength;if(r===0)throw TypeError(`search must be at least 1 byte long`);let i=new Int32Array(256);for(let e=0;e<256;e++)i[e]=-1;for(let e=0;e<r;e++)i[n[e]]=e;let a=i,o=this.byteLength-n.byteLength,s=n.byteLength-1,c;for(let e=t;e<=o;e+=c){c=0;for(let t=s;t>=0;t--){let r=this.get(e+t);if(n[t]!==r){c=Math.max(1,t-a[r]);break}}if(c===0)return e}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let n=zt(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let r=H(2);new DataView(r.buffer,r.byteOffset,r.byteLength).setInt16(0,t,n),this.write(r,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let r=H(4);new DataView(r.buffer,r.byteOffset,r.byteLength).setInt32(0,t,n),this.write(r,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let r=H(8);new DataView(r.buffer,r.byteOffset,r.byteLength).setBigInt64(0,t,n),this.write(r,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=zt(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let r=H(2);new DataView(r.buffer,r.byteOffset,r.byteLength).setUint16(0,t,n),this.write(r,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let r=H(4);new DataView(r.buffer,r.byteOffset,r.byteLength).setUint32(0,t,n),this.write(r,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let r=H(8);new DataView(r.buffer,r.byteOffset,r.byteLength).setBigUint64(0,t,n),this.write(r,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let r=H(4);new DataView(r.buffer,r.byteOffset,r.byteLength).setFloat32(0,t,n),this.write(r,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let r=H(8);new DataView(r.buffer,r.byteOffset,r.byteLength).setFloat64(0,t,n),this.write(r,e)}equals(t){if(t==null||!(t instanceof e)||t.bufs.length!==this.bufs.length)return!1;for(let e=0;e<this.bufs.length;e++)if(!Ut(this.bufs[e],t.bufs[e]))return!1;return!0}static fromUint8Arrays(t,n){let r=new e;return r.bufs=t,n??=t.reduce((e,t)=>e+t.byteLength,0),r.length=n,r}};function Kt(e){let t=e.fromBinary.bind(e);return async function*(e){for await(let n of e)if(Array.isArray(n))for(let e of n)yield*[t(e)];else yield*[t(n)]}}function qt(e){return async function*(t){for await(let n of t)if(Array.isArray(n))for(let t of n)yield e.toBinary(t);else yield e.toBinary(n)}}const Jt=1e7,Yt=Kt(Ft),Xt=qt(Ft),Zt=e=>{if(e.length<4)throw RangeError(`Could not decode int32BE`);return e.getUint32(0,!0)};Zt.bytes=4;const Qt=e=>{let t=new W(new Uint8Array(4));return t.setUint32(0,e,!0),t};Qt.bytes=4;async function*$t(e,t){for await(let n of e){let e=n instanceof Uint8Array?n.length:n.byteLength;if(e===0||e>Jt)throw RangeError(`invalid packet length: ${e}`);yield new W(t(e),n)}}async function*en(e,t){let n=new W;for await(let r of e)for(n.append(r);n.length>=t.bytes;){let e=t(n);if(e===0||e>Jt)throw RangeError(`invalid packet length: ${e}`);let r=t.bytes+e;if(n.length<r)break;yield new W(n.slice(t.bytes,r)),n.consume(r)}if(n.length!==0)throw RangeError(`truncated packet frame`)}function tn(e=Qt){return t=>$t(t,e)}function nn(e=Zt){return t=>en(t,e)}var rn=class{_value;_waiters;constructor(e){this._value=e||void 0,this._waiters=[]}get value(){return this._value}async wait(){let e=this._value;return e===void 0?new Promise(e=>{this.waitWithCb(t=>{e(t)})}):e}waitWithCb(e){e&&this._waiters.push(e)}set(e){if(this._value=e,e===void 0)return;let t=this._waiters;if(t.length!==0){this._waiters=[];for(let n of t)n(e)}}},an=class extends rn{constructor(e){super(e)}get openStreamFunc(){return async()=>{let e=this.value;return e||=await this.wait(),e()}}},on=class{openStreamCtr;constructor(e){this.openStreamCtr=new an(e||void 0)}setOpenStreamFn(e){this.openStreamCtr.set(e||void 0)}async request(e,t,n,r){let i=await this.startRpc(e,t,n,r);for await(let e of i.rpcDataSource)return i.close(),e;let a=Error(`empty response`);throw i.close(a),a}async clientStreamingRequest(e,t,n,r){let i=await this.startRpc(e,t,null,r);i.writeCallDataFromSource(n).catch(e=>i.close(e));for await(let e of i.rpcDataSource)return i.close(),e;let a=Error(`empty response`);throw i.close(a),a}serverStreamingRequest(e,t,n,r){let i=c({objectMode:!0});return this.startRpc(e,t,n,r).then(async e=>Rt(e.rpcDataSource,i)).catch(e=>i.end(e)),i}bidirectionalStreamingRequest(e,t,n,r){let i=c({objectMode:!0});return this.startRpc(e,t,null,r).then(async e=>{let t=t=>{i.end(t),e.close(t)};e.writeCallDataFromSource(n).catch(t);try{for await(let t of e.rpcDataSource)i.push(t);i.end(),e.close()}catch(e){t(e)}}).catch(e=>i.end(e)),i}async startRpc(e,n,r,i){if(i?.aborted)throw Error(t);let a=await(await this.openStreamCtr.wait())(),o=new Lt(e,n),s=()=>{if(o.isClosed)return;let e=Error(t);o.writeCallCancel().catch(()=>void 0),a.abort(e),o.close(e).catch(()=>void 0)};return i?.addEventListener(`abort`,s,{once:!0}),m(a,Yt,o,Xt,a).then(async()=>{if(o.isClosed instanceof Error){a.abort(o.isClosed);return}await a.close(),await o.close()},async e=>{let t=e instanceof Error?e:Error(String(e));a.abort(t),await o.close(t)}).finally(()=>{i?.removeEventListener(`abort`,s)}),await o.writeCallStart(r??void 0),o}},sn=class extends It{lookupMethod;constructor(e){super(),this.lookupMethod=e}async handleCallStart(e){if(this.service||this.method)throw Error(`call start must be sent only once`);if(this.service=e.rpcService,this.method=e.rpcMethod,!this.service||!this.method)throw Error(`rpcService and rpcMethod cannot be empty`);if(!this.lookupMethod)throw Error(`LookupMethod is not defined`);let t=await this.lookupMethod(this.service,this.method);if(!t)throw Error(`not found: ${this.service}/${this.method}`);this.pushRpcData(e.data,e.dataIsZero),this.invokeRPC(t)}async handleCallData(e){if(!this.service||!this.method)throw Error(`call start must be sent before call data`);return super.handleCallData(e)}async invokeRPC(e){let t=this._createDataSink();try{await e(this.rpcDataSource,t,{signal:this.invocationSignal})}catch(e){this.close(e)}}_createDataSink(){return async e=>{try{for await(let t of e)await this.writeCallData(t);await this.writeCallData(void 0,!0),this.close()}catch(e){this.close(e)}}}},cn=class{lookupMethod;constructor(e){this.lookupMethod=e}get rpcStreamHandler(){return async e=>ln(e,this.startRpc())}startRpc(){return new sn(this.lookupMethod)}handlePacketStream(e){let t=this.startRpc();return ln(e,t).catch(()=>void 0),t}};async function ln(e,t){try{if(await m(e,Yt,t,Xt,e),t.isClosed instanceof Error)throw e.abort(t.isClosed),t.isClosed;await e.close(),await t.close()}catch(n){let r=n instanceof Error?n:Error(String(n));throw e.abort(r),await t.close(r),r}}function un(e){if(e!=null){if(typeof e[Symbol.iterator]==`function`)return e[Symbol.iterator]();if(typeof e[Symbol.asyncIterator]==`function`)return e[Symbol.asyncIterator]();if(typeof e.next==`function`)return e}throw Error(`argument is not an iterator or iterable`)}var G=class extends Error{static name=`InvalidFrameError`;constructor(e=`The frame was invalid`){super(e),this.name=`InvalidFrameError`}},dn=class extends Error{static name=`UnrequestedPingError`;constructor(e=`Unrequested ping error`){super(e),this.name=`UnrequestedPingError`}},fn=class extends Error{static name=`NotMatchingPingError`;constructor(e=`Unrequested ping error`){super(e),this.name=`NotMatchingPingError`}},pn=class extends Error{static name=`InvalidStateError`;constructor(e=`Invalid state`){super(e),this.name=`InvalidStateError`}},mn=class extends Error{static name=`StreamAlreadyExistsError`;constructor(e=`Strean already exists`){super(e),this.name=`StreamAlreadyExistsError`}},hn=class extends Error{static name=`DecodeInvalidVersionError`;constructor(e=`Decode invalid version`){super(e),this.name=`DecodeInvalidVersionError`}},gn=class extends Error{static name=`BothClientsError`;constructor(e=`Both clients`){super(e),this.name=`BothClientsError`}},_n=class extends Error{static name=`ReceiveWindowExceededError`;constructor(e=`Receive window exceeded`){super(e),this.name=`ReceiveWindowExceededError`}};const vn=new Set([G.name,dn.name,fn.name,mn.name,hn.name,gn.name,_n.name]),yn=262144,bn=Symbol.for(`@libp2p/service-capabilities`);var xn=class extends Error{static name=`AbortError`;constructor(e=`The operation was aborted`){super(e),this.name=`AbortError`}},K=class extends Error{static name=`InvalidParametersError`;constructor(e=`Invalid parameters`){super(e),this.name=`InvalidParametersError`}},q=class extends Error{static name=`MuxerClosedError`;constructor(e=`The muxer is closed`){super(e),this.name=`MuxerClosedError`}},Sn=class extends Error{static name=`TooManyOutboundProtocolStreamsError`;constructor(e=`Too many outbound protocol streams`){super(e),this.name=`TooManyOutboundProtocolStreamsError`}};const Cn={enableKeepAlive:!0,keepAliveInterval:3e4,maxInboundStreams:1e3,maxOutboundStreams:1e3,initialStreamWindowSize:yn,maxStreamWindowSize:16777216,maxMessageSize:65536};function wn(e){if(e.keepAliveInterval<=0)throw new K(`keep-alive interval must be positive`);if(e.maxInboundStreams<0)throw new K(`max inbound streams must be larger or equal 0`);if(e.maxOutboundStreams<0)throw new K(`max outbound streams must be larger or equal 0`);if(e.initialStreamWindowSize<262144)throw new K(`InitialStreamWindowSize must be larger or equal 256 kB`);if(e.maxStreamWindowSize<e.initialStreamWindowSize)throw new K(`MaxStreamWindowSize must be larger than the InitialStreamWindowSize`);if(e.maxStreamWindowSize>2**32-1)throw new K(`MaxStreamWindowSize must be less than equal MAX_UINT32`);if(e.maxMessageSize<1024)throw new K(`MaxMessageSize must be greater than a kilobyte`)}var J;(function(e){e[e.Data=0]=`Data`,e[e.WindowUpdate=1]=`WindowUpdate`,e[e.Ping=2]=`Ping`,e[e.GoAway=3]=`GoAway`})(J||={});var Y;(function(e){e[e.SYN=1]=`SYN`,e[e.ACK=2]=`ACK`,e[e.FIN=4]=`FIN`,e[e.RST=8]=`RST`})(Y||={}),Object.values(Y).filter(e=>typeof e!=`string`);var X;(function(e){e[e.NormalTermination=0]=`NormalTermination`,e[e.ProtocolError=1]=`ProtocolError`,e[e.InternalError=2]=`InternalError`})(X||={});const Tn=2**24;function En(e){if(e[0]!==0)throw new G(`Invalid frame version`);return{type:e[1],flag:(e[2]<<8)+e[3],streamID:e[4]*Tn+(e[5]<<16)+(e[6]<<8)+e[7],length:e[8]*Tn+(e[9]<<16)+(e[10]<<8)+e[11]}}var Dn=class{source;buffer;frameInProgress;constructor(e){this.source=On(e),this.buffer=new W,this.frameInProgress=!1}async*emitFrames(){for await(let e of this.source)for(this.buffer.append(e);;){let e=this.readHeader();if(e===void 0)break;let{type:t,length:n}=e;t===J.Data?(this.frameInProgress=!0,yield{header:e,readData:this.readBytes.bind(this,n)}):yield{header:e}}}readHeader(){if(this.frameInProgress)throw new pn(`decoding frame already in progress`);if(this.buffer.length<12)return;let e=En(this.buffer.subarray(0,12));return this.buffer.consume(12),e}async readBytes(e){if(this.buffer.length<e){for await(let t of this.source)if(this.buffer.append(t),this.buffer.length>=e)break}let t=this.buffer.sublist(0,e);return this.buffer.consume(e),this.frameInProgress=!1,t}};function On(e){if(e[Symbol.iterator]!==void 0){let t=e[Symbol.iterator]();return t.return=void 0,{[Symbol.iterator](){return t}}}if(e[Symbol.asyncIterator]!==void 0){let t=e[Symbol.asyncIterator]();return t.return=void 0,{[Symbol.asyncIterator](){return t}}}throw Error(`a source must be either an iterable or an async iterable`)}function kn(e){let t=new Uint8Array(12);return t[1]=e.type,t[2]=e.flag>>>8,t[3]=e.flag,t[4]=e.streamID>>>24,t[5]=e.streamID>>>16,t[6]=e.streamID>>>8,t[7]=e.streamID,t[8]=e.length>>>24,t[9]=e.length>>>16,t[10]=e.length>>>8,t[11]=e.length,t}var An=class extends Error{static name=`StreamResetError`;constructor(e=`The stream has been reset`){super(e),this.name=`StreamResetError`}},jn=class extends Error{static name=`StreamStateError`;constructor(e=`The stream is in an invalid state`){super(e),this.name=`StreamStateError`}};function Mn(e){return e!=null&&typeof e.then==`function`&&typeof e.catch==`function`&&typeof e.finally==`function`}function Nn(e,t){let n=un(e).return?.();Mn(n)&&n.catch(e=>{t.error(`could not cause iterator to return`,e)})}function Pn(e){return e!=null&&typeof e.then==`function`&&typeof e.catch==`function`&&typeof e.finally==`function`}var Fn=class{id;direction;timeline;protocol;metadata;source;status;readStatus;writeStatus;log;sinkController;sinkEnd;closed;endErr;streamSource;onEnd;onCloseRead;onCloseWrite;onReset;onAbort;sendCloseWriteTimeout;sendingData;constructor(e){this.sinkController=new AbortController,this.sinkEnd=i(),this.closed=i(),this.log=e.log,this.status=`open`,this.readStatus=`ready`,this.writeStatus=`ready`,this.id=e.id,this.metadata=e.metadata??{},this.direction=e.direction,this.timeline={open:Date.now()},this.sendCloseWriteTimeout=e.sendCloseWriteTimeout??5e3,this.onEnd=e.onEnd,this.onCloseRead=e.onCloseRead,this.onCloseWrite=e.onCloseWrite,this.onReset=e.onReset,this.onAbort=e.onAbort,this.source=this.streamSource=c({onEnd:e=>{e==null?this.log.trace(`source ended`):this.log.trace(`source ended with error`,e),this.onSourceEnd(e)}}),this.sink=this.sink.bind(this)}async sink(e){if(this.writeStatus!==`ready`)throw new jn(`writable end state is "${this.writeStatus}" not "ready"`);try{this.writeStatus=`writing`;let t={signal:this.sinkController.signal};if(this.direction===`outbound`){let e=this.sendNewStream(t);Pn(e)&&await e}let n=()=>{Nn(e,this.log)};try{this.sinkController.signal.addEventListener(`abort`,n),this.log.trace(`sink reading from source`);for await(let n of e){n=n instanceof Uint8Array?new W(n):n;let e=this.sendData(n,t);Pn(e)&&(this.sendingData=i(),await e,this.sendingData.resolve(),this.sendingData=void 0)}}finally{this.sinkController.signal.removeEventListener(`abort`,n)}this.log.trace(`sink finished reading from source, write status is "%s"`,this.writeStatus),this.writeStatus===`writing`&&(this.writeStatus=`closing`,this.log.trace(`send close write to remote`),await this.sendCloseWrite({signal:AbortSignal.timeout(this.sendCloseWriteTimeout)}),this.writeStatus=`closed`),this.onSinkEnd()}catch(e){throw this.log.trace(`sink ended with error, calling abort with error`,e),this.abort(e),e}finally{this.log.trace(`resolve sink end`),this.sinkEnd.resolve()}}onSourceEnd(e){this.timeline.closeRead??(this.timeline.closeRead=Date.now(),this.readStatus=`closed`,e!=null&&this.endErr==null&&(this.endErr=e),this.onCloseRead?.(),this.timeline.closeWrite==null?this.log.trace(`source ended, waiting for sink to end`):(this.log.trace(`source and sink ended`),this.timeline.close=Date.now(),this.status!==`aborted`&&this.status!==`reset`&&(this.status=`closed`),this.onEnd!=null&&this.onEnd(this.endErr),this.closed.resolve()))}onSinkEnd(e){this.timeline.closeWrite??(this.timeline.closeWrite=Date.now(),this.writeStatus=`closed`,e!=null&&this.endErr==null&&(this.endErr=e),this.onCloseWrite?.(),this.timeline.closeRead==null?this.log.trace(`sink ended, waiting for source to end`):(this.log.trace(`sink and source ended`),this.timeline.close=Date.now(),this.status!==`aborted`&&this.status!==`reset`&&(this.status=`closed`),this.onEnd!=null&&this.onEnd(this.endErr),this.closed.resolve()))}async close(e){this.status===`open`&&(this.log.trace(`closing gracefully`),this.status=`closing`,await d(Promise.all([this.closeWrite(e),this.closeRead(e),this.closed.promise]),e?.signal),this.status=`closed`,this.log.trace(`closed gracefully`))}async closeRead(e={}){if(this.readStatus===`closing`||this.readStatus===`closed`)return;this.log.trace(`closing readable end of stream with starting read status "%s"`,this.readStatus);let t=this.readStatus;this.readStatus=`closing`,this.status!==`reset`&&this.status!==`aborted`&&this.timeline.closeRead==null&&(this.log.trace(`send close read to remote`),await this.sendCloseRead(e)),t===`ready`&&(this.log.trace(`ending internal source queue with %d queued bytes`,this.streamSource.readableLength),this.streamSource.end()),this.log.trace(`closed readable end of stream`)}async closeWrite(e={}){this.writeStatus!==`closing`&&this.writeStatus!==`closed`&&(this.log.trace(`closing writable end of stream with starting write status "%s"`,this.writeStatus),this.writeStatus===`ready`&&(this.log.trace(`sink was never sunk, sink an empty array`),await d(this.sink([]),e.signal)),this.writeStatus===`writing`&&(this.sendingData!=null&&await d(this.sendingData.promise,e.signal),this.log.trace(`aborting source passed to .sink`),this.sinkController.abort(),await d(this.sinkEnd.promise,e.signal)),this.writeStatus=`closed`,this.log.trace(`closed writable end of stream`))}abort(e){if(this.status===`closed`||this.status===`aborted`||this.status===`reset`)return;this.log(`abort with error`,e),this.log(`try to send reset to remote`);let t=this.sendReset();Pn(t)&&t.catch(e=>{this.log.error(`error sending reset message`,e)}),this.status=`aborted`,this.timeline.abort=Date.now(),this._closeSinkAndSource(e),this.onAbort?.(e)}reset(){if(this.status===`closed`||this.status===`aborted`||this.status===`reset`)return;let e=new An(`stream reset`);this.status=`reset`,this.timeline.reset=Date.now(),this._closeSinkAndSource(e),this.onReset?.()}_closeSinkAndSource(e){this._closeSink(e),this._closeSource(e)}_closeSink(e){this.writeStatus===`writing`&&(this.log.trace(`end sink source`),this.sinkController.abort()),this.onSinkEnd(e)}_closeSource(e){this.readStatus!==`closing`&&this.readStatus!==`closed`&&(this.log.trace(`ending source with %d bytes to be read by consumer`,this.streamSource.readableLength),this.readStatus=`closing`,this.streamSource.end(e))}remoteCloseWrite(){if(this.readStatus===`closing`||this.readStatus===`closed`){this.log(`received remote close write but local source is already closed`);return}this.log.trace(`remote close write`),this._closeSource()}remoteCloseRead(){if(this.writeStatus===`closing`||this.writeStatus===`closed`){this.log(`received remote close read but local sink is already closed`);return}this.log.trace(`remote close read`),this._closeSink()}destroy(){if(this.status===`closed`||this.status===`aborted`||this.status===`reset`){this.log(`received destroy but we are already closed`);return}this.log.trace(`stream destroyed`),this._closeSinkAndSource()}sourcePush(e){this.streamSource.push(e)}sourceReadableLength(){return this.streamSource.readableLength}};function In(e){let[t,n]=e[Symbol.asyncIterator]==null?[e[Symbol.iterator](),Symbol.iterator]:[e[Symbol.asyncIterator](),Symbol.asyncIterator],r=[];return{peek:()=>t.next(),push:e=>{r.push(e)},next:()=>r.length>0?{done:!1,value:r.shift()}:t.next(),[n](){return this}}}function Ln(e){return e[Symbol.asyncIterator]!=null}function Rn(e){return e?.then!=null}function zn(e,t){let n=0;if(Ln(e))return(async function*(){for await(let r of e){let e=t(r,n++);Rn(e)&&await e,yield r}})();let r=In(e),{value:i,done:a}=r.next();if(a===!0)return function*(){}();let o=t(i,n++);if(typeof o?.then==`function`)return(async function*(){await o,yield i;for(let e of r){let r=t(e,n++);Rn(r)&&await r,yield e}})();let s=t;return(function*(){yield i;for(let e of r)s(e,n++),yield e})()}var Z;(function(e){e[e.Init=0]=`Init`,e[e.SYNSent=1]=`SYNSent`,e[e.SYNReceived=2]=`SYNReceived`,e[e.Established=3]=`Established`,e[e.Finished=4]=`Finished`})(Z||={});var Bn=class extends Fn{name;state;config;_id;sendWindowCapacity;sendWindowCapacityUpdate;recvWindow;recvWindowCapacity;epochStart;getRTT;sendFrame;constructor(e){super({...e,onEnd:t=>{this.state=Z.Finished,e.onEnd?.(t)}}),this.config=e.config,this._id=parseInt(e.id,10),this.name=e.name,this.state=e.state,this.sendWindowCapacity=yn,this.recvWindow=this.config.initialStreamWindowSize,this.recvWindowCapacity=this.recvWindow,this.epochStart=Date.now(),this.getRTT=e.getRTT,this.sendFrame=e.sendFrame,this.source=zn(this.source,()=>{this.sendWindowUpdate()})}async sendNewStream(){}async sendData(e,t={}){for(e=e.sublist();e.byteLength!==0;){if(this.sendWindowCapacity===0&&(this.log?.trace(`wait for send window capacity, status %s`,this.status),await this.waitForSendWindowCapacity(t),this.status===`closed`||this.status===`aborted`||this.status===`reset`)){this.log?.trace(`%s while waiting for send window capacity`,this.status);return}let n=Math.min(this.sendWindowCapacity,this.config.maxMessageSize-12,e.length),r=this.getSendFlags();this.sendFrame({type:J.Data,flag:r,streamID:this._id,length:n},e.sublist(0,n)),this.sendWindowCapacity-=n,e.consume(n)}}sendReset(){this.sendFrame({type:J.WindowUpdate,flag:Y.RST,streamID:this._id,length:0})}async sendCloseWrite(){let e=this.getSendFlags()|Y.FIN;this.sendFrame({type:J.WindowUpdate,flag:e,streamID:this._id,length:0})}async sendCloseRead(){}async waitForSendWindowCapacity(e={}){if(this.sendWindowCapacity>0)return;let t,n,r=()=>{this.status===`open`||this.status===`closing`?n(new xn(`Stream aborted`)):t()};e.signal?.addEventListener(`abort`,r);try{await new Promise((e,r)=>{this.sendWindowCapacityUpdate=()=>{e()},n=r,t=e})}finally{e.signal?.removeEventListener(`abort`,r)}}handleWindowUpdate(e){this.log?.trace(`stream received window update id=%s`,this._id),this.processFlags(e.flag);let t=this.sendWindowCapacity;this.sendWindowCapacity+=e.length,t===0&&e.length>0&&this.sendWindowCapacityUpdate?.()}async handleData(e,t){if(this.log?.trace(`stream received data id=%s`,this._id),this.processFlags(e.flag),this.recvWindowCapacity<e.length)throw new _n(`Receive window exceeded`);let n=await t();this.recvWindowCapacity-=e.length,this.sourcePush(n)}processFlags(e){(e&Y.ACK)===Y.ACK&&this.state===Z.SYNSent&&(this.state=Z.Established),(e&Y.FIN)===Y.FIN&&this.remoteCloseWrite(),(e&Y.RST)===Y.RST&&this.reset()}getSendFlags(){switch(this.state){case Z.Init:return this.state=Z.SYNSent,Y.SYN;case Z.SYNReceived:return this.state=Z.Established,Y.ACK;default:return 0}}sendWindowUpdate(){if(this.readStatus!==`ready`)return;let e=this.getSendFlags(),t=Date.now(),n=this.getRTT();if(e===0&&n>-1&&t-this.epochStart<n*4&&(this.recvWindow=Math.min(this.recvWindow*2,this.config.maxStreamWindowSize)),this.recvWindowCapacity>=this.recvWindow&&e===0)return;let r=this.recvWindow-this.recvWindowCapacity;this.recvWindowCapacity=this.recvWindow,this.epochStart=t,this.sendFrame({type:J.WindowUpdate,flag:e,streamID:this._id,length:r})}};const Vn=`/yamux/1.0.0`;var Hn=class{protocol=Vn;_components;_init;constructor(e,t={}){this._components=e,this._init=t}[Symbol.toStringTag]=`@chainsafe/libp2p-yamux`;[bn]=[`@libp2p/stream-multiplexing`];createStreamMuxer(e){return new Un(this._components,{...this._init,...e})}},Un=class{protocol=Vn;source;sink;config;log;logger;closeController;nextStreamID;_streams;nextPingID;activePing;rtt;client;localGoAway;remoteGoAway;numInboundStreams;numOutboundStreams;onIncomingStream;onStreamEnd;constructor(e,t){this.client=t.direction===`outbound`,this.config={...Cn,...t},this.logger=e.logger,this.log=this.logger.forComponent(`libp2p:yamux`),wn(this.config),this.closeController=new AbortController,this.closeController.signal,this.onIncomingStream=t.onIncomingStream,this.onStreamEnd=t.onStreamEnd,this._streams=new Map,this.source=c({onEnd:()=>{this.log?.trace(`muxer source ended`),this._streams.forEach(e=>{e.destroy()})}}),this.sink=async e=>{let t=()=>{let t=un(e);if(t.return!=null){let e=t.return();Wn(e)&&e.catch(e=>{this.log?.(`could not cause sink source to return`,e)})}},n,r;try{let r=new Dn(e);try{this.closeController.signal.addEventListener(`abort`,t);for await(let e of r.emitFrames())await this.handleFrame(e.header,e.readData)}finally{this.closeController.signal.removeEventListener(`abort`,t)}n=X.NormalTermination}catch(e){vn.has(e.name)?(this.log?.error(`protocol error in sink`,e),n=X.ProtocolError):(this.log?.error(`internal error in sink`,e),n=X.InternalError),r=e}this.log?.trace(`muxer sink ended`),r==null?await this.close({reason:n}):this.abort(r,n)},this.numInboundStreams=0,this.numOutboundStreams=0,this.nextStreamID=this.client?1:2,this.nextPingID=0,this.rtt=-1,this.log?.trace(`muxer created`),this.config.enableKeepAlive&&this.keepAliveLoop().catch(e=>this.log?.error(`keepalive error: %s`,e)),this.ping().catch(e=>this.log?.error(`ping error: %s`,e))}get streams(){return Array.from(this._streams.values())}newStream(e){if(this.remoteGoAway!==void 0)throw new q(`Muxer closed remotely`);if(this.localGoAway!==void 0)throw new q(`Muxer closed locally`);let t=this.nextStreamID;if(this.nextStreamID+=2,this.numOutboundStreams>=this.config.maxOutboundStreams)throw new Sn(`max outbound streams exceeded`);this.log?.trace(`new outgoing stream id=%s`,t);let n=this._newStream(t,e,Z.Init,`outbound`);return this._streams.set(t,n),this.numOutboundStreams++,n.sendWindowUpdate(),n}async ping(){if(this.remoteGoAway!==void 0)throw new q(`Muxer closed remotely`);if(this.localGoAway!==void 0)throw new q(`Muxer closed locally`);if(this.activePing===void 0){let e=()=>{};this.activePing={id:this.nextPingID++,promise:new Promise((t,n)=>{let r=()=>{n(new q(`Muxer closed locally`))};this.closeController.signal.addEventListener(`abort`,r,{once:!0}),e=()=>{this.closeController.signal.removeEventListener(`abort`,r),t()}}),resolve:e};let t=Date.now();this.sendPing(this.activePing.id);try{await this.activePing.promise}finally{delete this.activePing}let n=Date.now();this.rtt=n-t}else await this.activePing.promise;return this.rtt}getRTT(){return this.rtt}async close(e={}){if(this.closeController.signal.aborted)return;let t=e?.reason??X.NormalTermination;if(this.log?.trace(`muxer close reason=%s`,t),e.signal==null){let t=AbortSignal.timeout(500);e={...e,signal:t}}try{await Promise.all([...this._streams.values()].map(async t=>t.close(e))),this.sendGoAway(t),this._closeMuxer()}catch(e){this.abort(e)}}abort(e,t){if(!this.closeController.signal.aborted){t??=X.InternalError,this.log?.error(`muxer abort reason=%s error=%s`,t,e);for(let t of this._streams.values())t.abort(e);this.sendGoAway(t),this._closeMuxer()}}isClosed(){return this.closeController.signal.aborted}_closeMuxer(){this.closeController.abort(),this.source.end()}_newStream(e,t,n,r){if(this._streams.get(e)!=null)throw new K(`Stream already exists with that id`);let i=new Bn({id:e.toString(),name:t,state:n,direction:r,sendFrame:this.sendFrame.bind(this),onEnd:()=>{this.closeStream(e),this.onStreamEnd?.(i)},log:this.logger.forComponent(`libp2p:yamux:${r}:${e}`),config:this.config,getRTT:this.getRTT.bind(this)});return i}closeStream(e){this.client===(e%2==0)?this.numInboundStreams--:this.numOutboundStreams--,this._streams.delete(e)}async keepAliveLoop(){for(this.log?.trace(`muxer keepalive enabled interval=%s`,this.config.keepAliveInterval);;){let e;try{await d(new Promise(t=>{e=setTimeout(t,this.config.keepAliveInterval)}),this.closeController.signal),this.ping().catch(e=>this.log?.error(`ping error: %s`,e))}catch{clearInterval(e);return}}}async handleFrame(e,t){let{streamID:n,type:r,length:i}=e;if(this.log?.trace(`received frame %o`,e),n===0)switch(r){case J.Ping:this.handlePing(e);return;case J.GoAway:this.handleGoAway(i);return;default:throw new G(`Invalid frame type`)}else switch(e.type){case J.Data:case J.WindowUpdate:await this.handleStreamMessage(e,t);return;default:throw new G(`Invalid frame type`)}}handlePing(e){if(e.flag===Y.SYN)this.log?.trace(`received ping request pingId=%s`,e.length),this.sendPing(e.length,Y.ACK);else if(e.flag===Y.ACK)this.log?.trace(`received ping response pingId=%s`,e.length),this.handlePingResponse(e.length);else throw new G(`Invalid frame flag`)}handlePingResponse(e){if(this.activePing===void 0)throw new dn(`ping not requested`);if(this.activePing.id!==e)throw new fn(`ping doesn't match our id`);this.activePing.resolve()}handleGoAway(e){this.log?.trace(`received GoAway reason=%s`,X[e]??`unknown`),this.remoteGoAway=e;for(let e of this._streams.values())e.reset();this._closeMuxer()}async handleStreamMessage(e,t){let{streamID:n,flag:r,type:i}=e;(r&Y.SYN)===Y.SYN&&this.incomingStream(n);let a=this._streams.get(n);if(a===void 0){if(i===J.Data){if(this.log?.(`discarding data for stream id=%s`,n),t===void 0)throw Error(`unreachable`);await t()}else this.log?.trace(`frame for missing stream id=%s`,n);return}switch(i){case J.WindowUpdate:a.handleWindowUpdate(e);return;case J.Data:if(t===void 0)throw Error(`unreachable`);await a.handleData(e,t);return;default:throw Error(`unreachable`)}}incomingStream(e){if(this.client!==(e%2==0))throw new K(`Both endpoints are clients`);if(this._streams.has(e))return;if(this.log?.trace(`new incoming stream id=%s`,e),this.localGoAway!==void 0){this.sendFrame({type:J.WindowUpdate,flag:Y.RST,streamID:e,length:0});return}if(this.numInboundStreams>=this.config.maxInboundStreams){this.log?.(`maxIncomingStreams exceeded, forcing stream reset`),this.sendFrame({type:J.WindowUpdate,flag:Y.RST,streamID:e,length:0});return}let t=this._newStream(e,void 0,Z.SYNReceived,`inbound`);this.numInboundStreams++,this._streams.set(e,t),this.onIncomingStream?.(t)}sendFrame(e,t){if(this.log?.trace(`sending frame %o`,e),e.type===J.Data){if(t===void 0)throw new G(`Invalid frame`);this.source.push(new W(kn(e),t))}else this.source.push(kn(e))}sendPing(e,t=Y.SYN){t===Y.SYN?this.log?.trace(`sending ping request pingId=%s`,e):this.log?.trace(`sending ping response pingId=%s`,e),this.sendFrame({type:J.Ping,flag:t,streamID:0,length:e})}sendGoAway(e=X.NormalTermination){this.log?.(`sending GoAway reason=%s`,X[e]),this.localGoAway=e,this.sendFrame({type:J.GoAway,flag:0,streamID:0,length:e})}};function Wn(e){return e!=null&&typeof e.then==`function`}function Gn(e={}){return t=>new Hn(t,e)}function Kn(){return async function*(e){for await(let t of e)U(t)?yield t.subarray():yield t}}var qn=class{_waiters=new Set;_error;_terminated=!1;get terminated(){return this._terminated}terminate(e){if(this._terminated)return!1;this._terminated=!0,this._error=e;for(let t of this._waiters)t(e);return this._waiters.clear(),!0}async wait(e){if(this._terminated)return{terminated:!0,error:this._error};let t,n=new Promise(e=>{t=t=>e({terminated:!0,error:t}),this._waiters.add(t)}),r=e.then(e=>({result:e}),e=>({error:e}));try{let e=await Promise.race([r,n]);return this._terminated?{terminated:!0,error:this._error}:e}finally{this._waiters.delete(t)}}next(e){return this.wait(e.next())}};function Jn(e){if(Symbol.asyncIterator in e)return e[Symbol.asyncIterator]();let t=e[Symbol.iterator]();return{next:async()=>t.next()}}function Yn(e){e.return&&Promise.resolve(e.return()).catch(()=>void 0)}function Xn(e){let t=new qn;return{close:async()=>{t.terminate()&&await e.close()},abort:n=>{t.terminate(n)&&e.abort(n)},source:(async function*(){let n=m(e,nn(),Kn())[Symbol.asyncIterator]();try{for(;;){let e=await t.next(n);if(`terminated`in e){if(e.error)throw e.error;return}if(`error`in e)throw e.error;if(e.result.done)return;yield e.result.value}}finally{Yn(n)}})(),sink:async n=>{let r=Jn(m(n,tn())),i=(async function*(){for(;;){let e=await t.next(r);if(`terminated`in e){if(e.error)throw e.error;return}if(`error`in e)throw e.error;if(e.result.done||t.terminated)return;yield e.result.value}})();try{let n=await t.wait(e.sink(i));if(`terminated`in n){if(n.error)throw n.error;return}if(`error`in n)throw n.error;await e.closeWrite()}catch(n){let r=n instanceof Error?n:Error(String(n));throw t.terminate(r)&&e.abort(r),r}finally{Yn(r)}}}}function Zn(e){let t=()=>{};return t.enabled=!1,t.color=``,t.diff=0,t.log=()=>{},t.namespace=e,t.destroy=()=>!0,t.extend=()=>t,t.debug=t,t.error=t,t.trace=t,t.newScope=()=>t,t}function Qn(){return{forComponent:Zn}}var $n=class{_muxer;_server;constructor(e,t){e&&(this._server=e);let n=t?.muxerFactory??Gn({enableKeepAlive:!1,...t?.yamuxParams})({logger:t?.logger??Qn()});this._muxer=n.createStreamMuxer({onIncomingStream:this.handleIncomingStream.bind(this),direction:t?.direction||`outbound`})}get sink(){return this._muxer.sink}get source(){return this._muxer.source}get streams(){return this._muxer.streams}get muxer(){return this._muxer}get server(){return this._server}buildClient(){return new on(this.openStream.bind(this))}async openStream(){return Xn(await this.muxer.newStream())}buildOpenStreamFunc(){return this.openStream.bind(this)}handleIncomingStream(e){let t=this.server;if(!t)return e.abort(Error(`server not implemented`));t.handlePacketStream(Xn(e))}close(e){e?this.muxer.abort(e):this.muxer.close()}},er=async e=>{if(e.readyState>=2)throw Error(`socket closed`);e.readyState!==1&&await new Promise((t,n)=>{function r(){e.removeEventListener(`open`,i),e.removeEventListener(`error`,a)}function i(){r(),t()}function a(t){r(),n(t.error??Error(`connect ECONNREFUSED ${e.url}`))}e.addEventListener(`open`,i),e.addEventListener(`error`,a)})},tr=(e,t)=>(t??={},t.closeOnEnd=t.closeOnEnd!==!1,async n=>{for await(let t of n){try{await er(e)}catch(e){if(e.message===`socket closed`)break;throw e}if(e.readyState===e.CLOSING||e.readyState===e.CLOSED)break;e.send(t)}t.closeOnEnd!=null&&e.readyState<=1&&await new Promise((t,n)=>{e.addEventListener(`close`,e=>{e.wasClean||e.code===1006?t():n(Object.assign(Error(`ws error`),{event:e}))}),setTimeout(()=>{e.close()})})}),nr=e((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=class{constructor(){this.pullQueue=[],this.pushQueue=[],this.eventHandlers={},this.isPaused=!1,this.isStopped=!1}push(e){if(this.isStopped)return;let t={value:e,done:!1};if(this.pullQueue.length){let e=this.pullQueue.shift();e&&e.resolve(t)}else this.pushQueue.push(Promise.resolve(t)),this.highWaterMark!==void 0&&this.pushQueue.length>=this.highWaterMark&&!this.isPaused&&(this.isPaused=!0,this.eventHandlers.highWater?this.eventHandlers.highWater():console&&console.warn(`EventIterator queue reached ${this.pushQueue.length} items`))}stop(){if(!this.isStopped){this.isStopped=!0,this.remove();for(let e of this.pullQueue)e.resolve({value:void 0,done:!0});this.pullQueue.length=0}}fail(e){if(!this.isStopped){if(this.isStopped=!0,this.remove(),this.pullQueue.length){for(let t of this.pullQueue)t.reject(e);this.pullQueue.length=0}else{let t=Promise.reject(e);t.catch(()=>{}),this.pushQueue.push(t)}}}remove(){Promise.resolve().then(()=>{this.removeCallback&&this.removeCallback()})}[Symbol.asyncIterator](){return{next:e=>{let t=this.pushQueue.shift();return t?(this.lowWaterMark!==void 0&&this.pushQueue.length<=this.lowWaterMark&&this.isPaused&&(this.isPaused=!1,this.eventHandlers.lowWater&&this.eventHandlers.lowWater()),t):this.isStopped?Promise.resolve({value:void 0,done:!0}):new Promise((e,t)=>{this.pullQueue.push({resolve:e,reject:t})})},return:()=>(this.isStopped=!0,this.pushQueue.length=0,this.remove(),Promise.resolve({value:void 0,done:!0}))}}},n=class{constructor(e,{highWaterMark:n=100,lowWaterMark:r=1}={}){let i=new t;i.highWaterMark=n,i.lowWaterMark=r,i.removeCallback=e({push:e=>i.push(e),stop:()=>i.stop(),fail:e=>i.fail(e),on:(e,t)=>{i.eventHandlers[e]=t}})||(()=>{}),this[Symbol.asyncIterator]=()=>i[Symbol.asyncIterator](),Object.freeze(this)}};e.EventIterator=n,e.default=n})),rr=e((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=nr();e.EventIterator=t.EventIterator,e.default=t.EventIterator}))();function ir(e){return e instanceof ArrayBuffer||e?.constructor?.name===`ArrayBuffer`&&typeof e?.byteLength==`number`}var ar=e=>{e.binaryType=`arraybuffer`;let t=async()=>{await new Promise((t,n)=>{if(r){t();return}if(i!=null){n(i);return}let a=t=>{e.removeEventListener(`open`,o),e.removeEventListener(`error`,s),t()},o=()=>{a(t)},s=t=>{a(()=>{n(t.error??Error(`connect ECONNREFUSED ${e.url}`))})};e.addEventListener(`open`,o),e.addEventListener(`error`,s)})},n=async function*(){let n=new rr.EventIterator(({push:t,stop:n,fail:r})=>{let i=e=>{let n=null;if(typeof e.data==`string`)throw Error(`Unsupported string encoding`);ir(e.data)&&(n=new Uint8Array(e.data)),e.data instanceof Uint8Array&&(n=e.data),n!=null&&t(n)},a=e=>{r(e.error??Error(`Socket error`))};return e.addEventListener(`message`,i),e.addEventListener(`error`,a),e.addEventListener(`close`,n),()=>{e.removeEventListener(`message`,i),e.removeEventListener(`error`,a),e.removeEventListener(`close`,n)}},{highWaterMark:1/0});await t();for await(let e of n)yield ir(e)?new Uint8Array(e):e}(),r=e.readyState===1,i;return e.addEventListener(`open`,()=>{r=!0,i=null}),e.addEventListener(`close`,()=>{r=!1,i=null}),e.addEventListener(`error`,t=>{r||(i=t.error??Error(`connect ECONNREFUSED ${e.url}`))}),Object.assign(n,{connected:t})},or=(e,t)=>{t??={};let n=ar(e),r=t.remoteAddress,i=t.remotePort;if(e.url!=null)try{let t=new URL(e.url);r=t.hostname,i=parseInt(t.port,10)}catch{}if(r==null||i==null)throw Error(`Remote connection did not have address and/or port`);return{sink:tr(e,t),source:n,connected:async()=>{await n.connected()},close:async()=>{(e.readyState===e.CONNECTING||e.readyState===e.OPEN)&&await new Promise(t=>{e.addEventListener(`close`,()=>{t()}),e.close()})},destroy:()=>{e.terminate==null?e.close():e.terminate()},remoteAddress:r,remotePort:i,socket:e}},sr=class extends $n{socket;constructor(e,t,n){super(n,{direction:t}),this.socket=e;let r=or(e);m(r,this,Kn(),r).catch(e=>this.close(e)).then(()=>this.close())}getSocket(){return this.socket}},Q;(function(e){e[e.Unary=0]=`Unary`,e[e.ServerStreaming=1]=`ServerStreaming`,e[e.ClientStreaming=2]=`ClientStreaming`,e[e.BiDiStreaming=3]=`BiDiStreaming`})(Q||={});var cr;(function(e){e[e.NoSideEffects=1]=`NoSideEffects`,e[e.Idempotent=2]=`Idempotent`})(cr||={});const lr=V({typeName:`rpcstream.RpcStreamInit`,fields:[{no:1,name:`component_id`,kind:`scalar`,T:y.STRING}],packedByDefault:!0}),ur=V({typeName:`rpcstream.RpcAck`,fields:[{no:1,name:`error`,kind:`scalar`,T:y.STRING}],packedByDefault:!0}),dr=V({typeName:`rpcstream.RpcStreamPacket`,fields:[{no:1,name:`init`,kind:`message`,T:()=>lr,oneof:`body`},{no:2,name:`ack`,kind:`message`,T:()=>ur,oneof:`body`},{no:3,name:`data`,kind:`scalar`,T:y.BYTES,oneof:`body`}],packedByDefault:!0}),$=V({typeName:`echo.EchoMsg`,fields:[{no:1,name:`body`,kind:`scalar`,T:y.STRING}],packedByDefault:!0}),fr=kt(`google.protobuf.Empty`,!0);({typeName:`echo.Echoer`,methods:{Echo:{name:`Echo`,I:$,O:$,kind:Q.Unary},EchoServerStream:{name:`EchoServerStream`,I:$,O:$,kind:Q.ServerStreaming},EchoClientStream:{name:`EchoClientStream`,I:$,O:$,kind:Q.ClientStreaming},EchoBidiStream:{name:`EchoBidiStream`,I:$,O:$,kind:Q.BiDiStreaming},RpcStream:{name:`RpcStream`,I:dr,O:dr,kind:Q.BiDiStreaming},DoNothing:{name:`DoNothing`,I:fr,O:fr,kind:Q.Unary}}}).typeName;const pr=Symbol.for(`spacewave.SyncError`);var mr=class extends Error{code;requestId;name=`SyncError`;[pr]=!0;static[Symbol.hasInstance](e){return e instanceof Error&&pr in e&&e[pr]===!0}constructor(e,t,n){super(t),this.code=e,this.requestId=n}};export{m as _,qn as a,n as b,Kn as c,Kt as d,qt as f,y as g,We as h,$n as i,cn as l,V as m,Q as n,Yn as o,kt as p,sr as r,Jn as s,mr as t,on as u,c as v,t as y};
|