{"version":3,"file":"connection.d.ts","sourceRoot":"","sources":["../src/connection.ts"],"names":[],"mappings":"AAAA,OAAO,EAKN,KAAK,WAAW,EAChB,KAAK,aAAa,EAElB,MAAM,6BAA6B,CAAC;AAGrC,OAAO,KAAK,EAAiB,oBAAoB,EAAyB,MAAM,gBAAgB,CAAC;AACjG,OAAO,KAAK,EAAE,eAAe,EAAE,qBAAqB,EAAE,MAAM,YAAY,CAAC;AAmBzE,UAAU,iBAAiB;IAC1B,gBAAgB,EAAE,oBAAoB,CAAC;IACvC,QAAQ,EAAE,MAAM,CAAC;IACjB,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,WAAW,CAAC,KAAK,EAAE,WAAW,GAAG,IAAI,CAAC;IACtC,SAAS,CAAC,OAAO,EAAE,OAAO,CAAC,aAAa,EAAE;QAAE,IAAI,EAAE,OAAO,GAAG,aAAa,CAAA;KAAE,CAAC,GAAG,IAAI,CAAC;IACpF,aAAa,CAAC,MAAM,EAAE,qBAAqB,GAAG,IAAI,CAAC;CACnD;AAED,qBAAa,UAAU;;IAMtB,YAAY,OAAO,EAAE,iBAAiB,EAUrC;IAED,IAAI,KAAK,IAAI,eAAe,CAE3B;IAED,IAAI,cAAc,IAAI,MAAM,CAE3B;IAED,OAAO,IAAI,OAAO,CAAC,WAAW,CAAC,CAwB9B;IAED,UAAU,CAAC,MAAM,GAAE,MAAM,GAAG,KAA6B,GAAG,IAAI,CAG/D;IAED,IAAI,CAAC,KAAK,EAAE,KAAK,GAAG,IAAI,CAEvB;IAED,IAAI,CAAC,KAAK,EAAE,UAAU,GAAG,IAAI,CAgB5B;CA+HD","sourcesContent":["import {\n\tDEFAULT_MAX_FRAME_LENGTH,\n\tencodeClientMessage,\n\tPROTOCOL_VERSION,\n\tProtocolValidationError,\n\ttype ServerHello,\n\ttype ServerMessage,\n\tServerMessageDecoder,\n} from \"@earendil-works/pi-protocol\";\nimport { DisconnectedError, ServerError, toDisconnectedError, toError } from \"./errors.ts\";\nimport { createPromiseResolvers, type PromiseResolvers } from \"./promise.ts\";\nimport type { ByteTransport, ByteTransportFactory, ByteTransportHandlers } from \"./transport.ts\";\nimport type { ConnectionState, ConnectionStateChange } from \"./types.ts\";\n\nconst MAX_UINT32 = 0xffff_ffff;\n\ntype ActiveConnection = {\n\tid: number;\n\tdecoder: ServerMessageDecoder;\n\ttransport?: ByteTransport;\n};\n\ntype ConnectionLifecycle =\n\t| { state: \"disconnected\" }\n\t| ({ state: \"connecting\"; handshake: PromiseResolvers<ServerHello> } & ActiveConnection)\n\t| ({\n\t\t\tstate: \"connected\";\n\t\t\ttransport: ByteTransport;\n\t\t\thandshake: PromiseResolvers<ServerHello> | undefined;\n\t  } & ActiveConnection);\n\ninterface ConnectionOptions {\n\ttransportFactory: ByteTransportFactory;\n\tserverId: string;\n\tmaxFrameLength?: number;\n\tonHandshake(hello: ServerHello): void;\n\tonMessage(message: Exclude<ServerMessage, { type: \"hello\" | \"hello_error\" }>): void;\n\tonStateChange(change: ConnectionStateChange): void;\n}\n\nexport class Connection {\n\treadonly #options: ConnectionOptions;\n\treadonly #maxFrameLength: number;\n\t#lifecycle: ConnectionLifecycle = { state: \"disconnected\" };\n\t#sequence = 0;\n\n\tconstructor(options: ConnectionOptions) {\n\t\tthis.#options = options;\n\t\tthis.#maxFrameLength = options.maxFrameLength ?? DEFAULT_MAX_FRAME_LENGTH;\n\t\tif (\n\t\t\t!Number.isSafeInteger(this.#maxFrameLength) ||\n\t\t\tthis.#maxFrameLength <= 0 ||\n\t\t\tthis.#maxFrameLength > MAX_UINT32\n\t\t) {\n\t\t\tthrow new TypeError(`Client maxFrameLength must be an integer between 1 and ${MAX_UINT32}`);\n\t\t}\n\t}\n\n\tget state(): ConnectionState {\n\t\treturn this.#lifecycle.state;\n\t}\n\n\tget maxFrameLength(): number {\n\t\treturn this.#maxFrameLength;\n\t}\n\n\tconnect(): Promise<ServerHello> {\n\t\tif (this.#lifecycle.state !== \"disconnected\") {\n\t\t\treturn Promise.reject(new DisconnectedError(`Client is already ${this.#lifecycle.state}`));\n\t\t}\n\t\tconst id = ++this.#sequence;\n\t\tconst handshake = createPromiseResolvers<ServerHello>();\n\t\tthis.#lifecycle = {\n\t\t\tstate: \"connecting\",\n\t\t\tid,\n\t\t\tdecoder: new ServerMessageDecoder({ maxFrameLength: this.#maxFrameLength }),\n\t\t\thandshake,\n\t\t};\n\t\tthis.#options.onStateChange({ state: \"connecting\" });\n\t\tconst handlers = {\n\t\t\tonData: (chunk) => this.#handleData(id, chunk),\n\t\t\tonClose: () => {\n\t\t\t\tif (this.#isCurrent(id)) this.#handleClose();\n\t\t\t},\n\t\t\tonError: (error) => {\n\t\t\t\tif (this.#isCurrent(id)) this.#failAndClose(toDisconnectedError(error));\n\t\t\t},\n\t\t} satisfies ByteTransportHandlers;\n\t\tvoid this.#openTransport(id, handlers);\n\t\treturn handshake.promise;\n\t}\n\n\tdisconnect(reason: string | Error = \"Client disconnected\"): void {\n\t\tif (this.#lifecycle.state === \"disconnected\") return;\n\t\tthis.#failAndClose(typeof reason === \"string\" ? new DisconnectedError(reason) : reason);\n\t}\n\n\tfail(error: Error): void {\n\t\tthis.#failAndClose(error);\n\t}\n\n\tsend(frame: Uint8Array): void {\n\t\tconst lifecycle = this.#lifecycle;\n\t\tif (lifecycle.state !== \"connected\") throw new DisconnectedError();\n\t\tlet sending: Promise<void>;\n\t\ttry {\n\t\t\tsending = lifecycle.transport.send(frame);\n\t\t} catch (error) {\n\t\t\tthis.#failAndClose(toDisconnectedError(error));\n\t\t\treturn;\n\t\t}\n\t\tvoid sending.catch((error: unknown) => {\n\t\t\tconst current = this.#lifecycle;\n\t\t\tif (current.state !== \"disconnected\" && current.transport === lifecycle.transport) {\n\t\t\t\tthis.#failAndClose(toDisconnectedError(error));\n\t\t\t}\n\t\t});\n\t}\n\n\tasync #openTransport(id: number, handlers: ByteTransportHandlers): Promise<void> {\n\t\tlet transport: ByteTransport;\n\t\ttry {\n\t\t\ttransport = await this.#options.transportFactory(handlers);\n\t\t} catch (error) {\n\t\t\tif (this.#isCurrent(id)) this.#fail(toDisconnectedError(error));\n\t\t\treturn;\n\t\t}\n\t\tconst lifecycle = this.#lifecycle;\n\t\tif (lifecycle.state !== \"connecting\" || lifecycle.id !== id) {\n\t\t\ttransport.close();\n\t\t\treturn;\n\t\t}\n\t\tthis.#lifecycle = { ...lifecycle, transport };\n\t\ttry {\n\t\t\tawait transport.send(\n\t\t\t\tencodeClientMessage({ type: \"hello\", version: PROTOCOL_VERSION }, { maxFrameLength: this.#maxFrameLength }),\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tif (this.#isCurrent(id)) this.#failAndClose(toDisconnectedError(error));\n\t\t}\n\t}\n\n\t#handleData(id: number, chunk: Uint8Array): void {\n\t\tconst lifecycle = this.#lifecycle;\n\t\tif (lifecycle.state === \"disconnected\" || lifecycle.id !== id) return;\n\t\tif (lifecycle.state === \"connecting\" && !lifecycle.transport) {\n\t\t\tthis.#failAndClose(new ProtocolValidationError(\"Received server data before the client hello was sent\"));\n\t\t\treturn;\n\t\t}\n\t\tlet messages: ServerMessage[];\n\t\ttry {\n\t\t\tmessages = lifecycle.decoder.push(chunk);\n\t\t} catch (error) {\n\t\t\tthis.#failAndClose(toError(error));\n\t\t\treturn;\n\t\t}\n\t\tfor (const message of messages) {\n\t\t\tif (this.#lifecycle.state === \"disconnected\") return;\n\t\t\tthis.#handleMessage(message);\n\t\t}\n\t}\n\n\t#handleMessage(message: ServerMessage): void {\n\t\tconst lifecycle = this.#lifecycle;\n\t\tif (lifecycle.state === \"connecting\") {\n\t\t\tif (message.type === \"hello_error\") {\n\t\t\t\tthis.#failAndClose(new ServerError(message.error));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (message.type !== \"hello\") {\n\t\t\t\tthis.#failAndClose(new ProtocolValidationError(\"Expected server hello as first message\"));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (message.serverId !== this.#options.serverId) {\n\t\t\t\tthis.#failAndClose(\n\t\t\t\t\tnew ProtocolValidationError(\n\t\t\t\t\t\t`Connected server ${JSON.stringify(message.serverId)} does not match ${JSON.stringify(this.#options.serverId)}`,\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!lifecycle.transport) {\n\t\t\t\tthis.#failAndClose(new ProtocolValidationError(\"Received server hello before the client hello was sent\"));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst connected = {\n\t\t\t\tstate: \"connected\",\n\t\t\t\tid: lifecycle.id,\n\t\t\t\tdecoder: lifecycle.decoder,\n\t\t\t\ttransport: lifecycle.transport,\n\t\t\t\thandshake: lifecycle.handshake,\n\t\t\t} satisfies Extract<ConnectionLifecycle, { state: \"connected\" }>;\n\t\t\tthis.#lifecycle = connected;\n\t\t\ttry {\n\t\t\t\tthis.#options.onHandshake(message);\n\t\t\t} catch (error) {\n\t\t\t\tif (this.#lifecycle === connected) this.#failAndClose(toError(error));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (this.#lifecycle !== connected) return;\n\t\t\tthis.#options.onStateChange({ state: \"connected\" });\n\t\t\tif (this.#lifecycle !== connected) return;\n\t\t\tthis.#lifecycle = { ...connected, handshake: undefined };\n\t\t\tlifecycle.handshake.resolve(message);\n\t\t\treturn;\n\t\t}\n\t\tif (lifecycle.state !== \"connected\") return;\n\t\tif (message.type === \"hello\" || message.type === \"hello_error\") {\n\t\t\tthis.#failAndClose(new ProtocolValidationError(\"Unexpected handshake message\"));\n\t\t\treturn;\n\t\t}\n\t\tthis.#options.onMessage(message);\n\t}\n\n\t#handleClose(): void {\n\t\tconst lifecycle = this.#lifecycle;\n\t\tif (lifecycle.state === \"disconnected\") return;\n\t\tlet error: Error = new DisconnectedError(\"Byte transport closed\");\n\t\ttry {\n\t\t\tlifecycle.decoder.end();\n\t\t} catch (decoderError) {\n\t\t\terror = toError(decoderError);\n\t\t}\n\t\tthis.#fail(error);\n\t}\n\n\t#failAndClose(error: Error): void {\n\t\tconst lifecycle = this.#lifecycle;\n\t\tconst transport = lifecycle.state === \"disconnected\" ? undefined : lifecycle.transport;\n\t\tthis.#fail(error);\n\t\ttransport?.close();\n\t}\n\n\t#fail(error: Error): void {\n\t\tconst lifecycle = this.#lifecycle;\n\t\tif (lifecycle.state === \"disconnected\") return;\n\t\tthis.#lifecycle = { state: \"disconnected\" };\n\t\tlifecycle.handshake?.reject(error);\n\t\tthis.#options.onStateChange({ state: \"disconnected\", error });\n\t}\n\n\t#isCurrent(id: number): boolean {\n\t\treturn this.#lifecycle.state !== \"disconnected\" && this.#lifecycle.id === id;\n\t}\n}\n"]}